branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>KyleBlackwell01/Algorithms<file_sep>/Algorithms/InsertionSort/Program.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsertionSort
{
public class Program
{
static void Main(string[] args)
{
using (var reader = new StreamReader("unsorted_numbers.csv"))
{
var testArr = reader.ReadToEnd()
.Split('\n')
.SelectMany(s => s.Split(',')
.Select(x => int.Parse(x)))
.ToArray<int>();
foreach (var x in testArr)
{
//placeholder
}
int n = testArr.Length, i, j, val, flag;
Console.WriteLine("Insertion Sort, this may take awhile...");
Console.WriteLine("Initial array is: ");
//Displays current csv as an array
for (i = 0; i < n; i++)
{
Console.Write(testArr[i] + " ");
}
//Sorts initial csv array via insertionsort
for (i = 1; i < n; i++)
{
val = testArr[i];
flag = 0;
for (j = i - 1; j >= 0 && flag != 1;)
{
if (val < testArr[j])
{
testArr[j + 1] = testArr[j];
j--;
testArr[j + 1] = val;
}
else flag = 1;
}
}
//Insertion Sorting is slow, please don't use it.
Console.WriteLine("\nSorted Array is, this will take a bit...");
for(i=0; i < n; i++)
{
Console.Write(testArr[i] + " ");
//SaveArrasCSV(testArr, @"D:\Coding\testArr2.csv");
}
}
Console.WriteLine("End of Sort");
Console.ReadKey();
}
//public static void SaveArrasCSV(Array arrToSave, string fileName)
//{
// using (StreamWriter file = new StreamWriter(fileName))
// {
// WriteItemsToFile(arrToSave, file);
// }
//}
//private static void WriteItemsToFile(Array items, TextWriter file)
//{
// foreach (object item in items)
// {
// if (item is Array)
// {
// WriteItemsToFile(item as Array, file);
// file.Write(Environment.NewLine);
// }
// else
// {
// file.Write(item + "\n");
// }
// }
//}
}
}
<file_sep>/Algorithms/BinarySearch/Program.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShellSort;
using System.Diagnostics;
namespace BinarySearch
{
public class Program
{
static void Main(string[] args)
{
//Initializes CSV via System.IO
using (var reader = new StreamReader("unsorted_numbers.csv"))
{
var testArr = reader.ReadToEnd()
.Split('\n')
.SelectMany(s => s.Split(',')
.Select(x => int.Parse(x)))
.ToArray<int>();
int n = testArr.Length;
//Sorts via ShellSort reference to prepare for binary search
ShellSort.Program.shellSort(testArr, n);
//Used to check if array is working.
//PrintVals(testArr);
Console.WriteLine("Please enter a number to find:");
SearchNumber(testArr, int.Parse(Console.ReadLine()));
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
public static void SearchNumber(Array testArr, int Test)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int testIndex = Array.BinarySearch(testArr, Test);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
if(testIndex < 0)
{
Console.WriteLine("The number to search for ({0}) was not found. The next number is at index {1}.", Test, ~testIndex);
}
else
{
Console.WriteLine("The number to search for ({0}) is at index {1}.", Test, testIndex);
Console.WriteLine("Total time taken: " + ts);
}
}
public static void PrintVals(Array testArr)
{
int i = 0;
int cols = testArr.GetLength(testArr.Rank - 1);
foreach(object o in testArr)
{
if (i < cols)
{
i++;
}
else
{
Console.WriteLine();
i = 1;
}
Console.Write("\t{0}", o);
}
Console.WriteLine();
}
}
}
<file_sep>/Algorithms/LinearSearch/Program.cs
using System;
using System.IO;
using ShellSort;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace LinearSearch
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a number to find.");
linearIndex(int.Parse(Console.ReadLine()));
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
public static int linearIndex(int searchNumber)
{
//Initializes the csv as an array
using (var reader = new StreamReader("unsorted_numbers.csv"))
{
int[] testArr = reader.ReadToEnd()
.Split('\n')
.SelectMany(s => s.Split(',')
.Select(x => int.Parse(x)))
.ToArray<int>();
int n = testArr.Length;
//Referenced from ShellSort Project to sort in preparation for binary search
ShellSort.Program.shellSort(testArr, n);
int index = 0;
searchLine: if (searchNumber == testArr[index])
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Console.WriteLine("Number was found at Index : {0}", index);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Console.WriteLine("Total time: " + ts);
return index;
}
index++;
if (index < testArr.Length)
{
goto searchLine;
}
else
{
Console.WriteLine("Not found at any Index");
}
return 0;
}
}
}
}
<file_sep>/Algorithms/ShellSort/Program.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShellSort
{
public class Program
{
public static void shellSort(int[] arr, int n)
{
int i, j, pos, temp;
pos = 3;
while(pos > 0)
{
for (i = 0; i < n; i++)
{
j = i;
temp = arr[i];
while((j>=pos) && (arr[j - pos] > temp))
{
arr[j] = arr[j - pos];
j = j - pos;
}
arr[j] = temp;
}
if (pos / 2 != 0)
{
pos = pos / 2;
}
else if (pos == 1)
{
pos = 0;
}
else
{
pos = 1;
}
}
}
static void Main(string[] args)
{
using (var reader = new StreamReader("unsorted_numbers.csv"))
{
var testArr = reader.ReadToEnd()
.Split('\n')
.SelectMany(s => s.Split(',')
.Select(x => int.Parse(x)))
.ToArray<int>();
foreach (var x in testArr)
{
//placeholder
}
int n = testArr.Length;
int i;
Console.WriteLine("Shell sort");
Console.WriteLine("Initial Array is: ");
for(i=0; i < n; i++)
{
Console.Write(testArr[i] + " ");
}
//Calls shellSort method
shellSort(testArr, n);
Console.WriteLine("\nSorted Array is: ");
for (i = 0; i < n; i++)
{
Console.WriteLine(testArr[i] + " ");
//SaveArrasCSV(testArr, @"D:\Coding\testArrShell.csv");
}
}
Console.WriteLine("End of sort");
Console.ReadKey();
}
//public static void SaveArrasCSV(Array arrToSave, string fileName)
//{
// using (StreamWriter file = new StreamWriter(fileName))
// {
// WriteItemsToFile(arrToSave, file);
// }
//}
//private static void WriteItemsToFile(Array items, TextWriter file)
//{
// foreach (object item in items)
// {
// if (item is Array)
// {
// WriteItemsToFile(item as Array, file);
// file.Write(Environment.NewLine);
// }
// else
// {
// file.Write(item + "\n");
// }
// }
//}
}
}
| f56e894921206d85292619b733c32a2648d7d8ad | [
"C#"
]
| 4 | C# | KyleBlackwell01/Algorithms | 1e4ce8ae58179d779460ec981980d10f131e57cb | 7611ec00b071c0cc1a92d3a260add40d724a5a48 |
refs/heads/master | <file_sep>#!/usr/local/bin/python3
import csv
import re
expensePlaces = [ 'The UPS Store', 'Amazon', 'Dollar Tree', 'NetFlix', 'Oriental Trading', 'Costco WHSE', 'Office Depot', '<NAME>', 'Discount School', 'Powell\'s', 'Blick Art', 'Home Depot', 'Dollar Tr', 'Oak Hall', 'DiscountMugs', 'Sports Authority', 'Citi Card', 'Montessori Outlet', 'OnlineFabricStore', 'Craft Warehouse', 'LakeShore Learning', 'Michaels', 'The Lego Store', 'Best Buy', 'Target', 'Karate Supply', 'KizPhonics', 'BarnesNoble', 'Harland Clarke', 'U Book Store', 'Swoosh', 'Education.com', 'Teacher Created', 'Go! Calendars', 'OTC Brands', 'CARD PROVISIONAL CREDIT', 'PROOF-OUT OF BALANCE NO TAPE LISTING', 'Transaction correction - Error', 'WF Bus Credit AUTO PAY', 'RECURRING PAYMENT AUTHORIZED ON 11/06' ]
expenseTranslations = { 'OnlineFabricStore': 'Online Fabric Store',
'OTC Brands': 'Oriental Trading',
'U Book Store': 'University of Washington Book Store',
'CARD PROVISIONAL CREDIT': 'Temporary Charge (Later Reversed)',
'PROOF-OUT OF BALANCE NO TAPE LISTING': 'Deposit Correction',
'Transaction Correction - Error': 'Bank Fee',
'WF Bus Credit AUTO PAY': 'Bank Fee',
'RECURRING PAYMENT AUTHORIZED ON 11/06': 'TME'
}
repairPlaces = [ 'Stark\'s Vacuums', 'Accurate Auto' ]
repairTranslations = [ ]
eventPlaces = [ 'PRTLND SPIRIT', 'Portland Spirit', 'Pizza Hut', 'Domino\'s', 'Johns Incredible Pizza', 'Johns Incredible', 'Pasta Pronto', 'Starbucks', 'La Hacienda Real', 'Beaverton Bakery', 'OMSI', 'Tillamook', 'Pump it Up', 'Old Spaghetti', 'PDX Childrens', 'Oregon Zoo', 'Cornell Oaks', 'Happy Panda', 'The Melting Pot', 'Blast Zone', 'Schopps Home Maint', 'Wunderland' ]
eventTranslations = { 'PRTLND SPIRIT': 'Portland Spirit',
'Johns Icredible Pizza': 'Jonhs Incredible',
'Old Spaghetti': 'Old Spaghetti Factory Restaurant',
'PDS Childrens': 'Childrens Museum' }
vanPlaces = ['Costco Gas', 'KMFUSA', 'Classic Lube', 'Shell Oil', 'BeavertonKiaSal' ]
vanTranslations = { 'KMFUSA': 'Kia Motors',
'BeavertonKiaSal': 'Beaverton Kia' }
adPlaces = ['CraigsList', 'JobDango', 'Monster']
adTranslations = { 'CraigsList': 'Craig\'s List',
'JobDango': 'JobDango.com',
'Monster': 'Monster.com' }
incomePlaces = [ 'eDeposit', 'DEPOSIT', 'ONLINE TRANSFER FROM ANGELS ACADEMY', 'CARD REVERSAL', 'Transaction correction - Deposit' ]
incomeTranslations = { 'eDeposit': 'Tuition',
'DEPOSIT': 'Tuition',
'ONLINE TRANSFER FROM ANGELS ACADEMY': 'Tuition',
'CARD REVERSAL': 'Credit Card Refund',
'Transaction correction - Deposit': 'Bank Error'
}
backgroundPlaces = [ 'OR DEPT ED CHILD' ]
backgroundTranslations = { 'OR DEPT ED CHILD':'Oregon Department of Education' }
insurancePlaces = [ 'SAIF', 'MARKEL' ]
insuranceTranslations = { 'MARKEL':'Markel' }
trainingPlaces = [ 'Care Courses' ]
trainingTranslations = { }
phonePlaces = [ 'T-MOBILE' ]
phoneTranslations = { 'T-MOBILE':'T-Mobile' }
licensingPlaces = [ 'OR SEC STATE CORPD' ]
licensingTranslations = { 'OR SEC STATE CORPD': 'Oregon Secretary of State' }
payrollTaxPlaces = [ 'WELLS FARGO BUSI TAX COL PAYROLL' ]
payrollTaxTranslations = { 'WELLS FARGO BUSI TAX COL PAYROLL': 'Wells Fargo Payroll Tax' }
payrollExpensePlaces = [ 'PAYROLL INVOICE' ]
payrollExpenseTranslations = { 'PAYROLL INVOICE': 'Wells Fargo Payroll Expense' }
payrollPlaces = [ 'PAYROLL DD' ]
payrollTranslations = { 'PAYROLL DD': 'Wells Fargo Payroll' }
internetPlaces = [ 'WEB*NET' ]
internetTranslations = { 'WEB*NET': 'Network Solutions' }
def mkCategory(places, translations):
return { 'places':places, 'translations':translations, 'total':0.0 }
categories = { 'Office Expenses': mkCategory(expensePlaces, expenseTranslations),
'Event': mkCategory(eventPlaces, eventTranslations),
'Income': mkCategory(incomePlaces, incomeTranslations),
'Repair': mkCategory(repairPlaces, repairTranslations),
'advertising': mkCategory(adPlaces, adTranslations),
'internet': mkCategory(internetPlaces, internetTranslations),
'training': mkCategory(trainingPlaces, trainingTranslations),
'Payroll Tax': mkCategory(payrollTaxPlaces, payrollTaxTranslations),
'Payroll Expense': mkCategory(payrollExpensePlaces, payrollExpenseTranslations),
'Payroll': mkCategory(payrollPlaces, payrollTranslations),
'background check': mkCategory(backgroundPlaces, backgroundTranslations),
'licensing': mkCategory(licensingPlaces, licensingTranslations),
'insurance': mkCategory(insurancePlaces, insuranceTranslations),
'phone': mkCategory(phonePlaces, phoneTranslations),
'van': mkCategory(vanPlaces, vanTranslations)
}
def getCategory(row):
desc = row['description']
for cat in categories:
catVals = categories[cat]
# print('\tcat = ', cat, ', catVals = ', catVals['places'], ', desc = ', desc)
for place in catVals['places']:
if place.upper() in desc or place in desc:
if place in catVals['translations']:
return (cat, catVals['translations'][place])
else:
return (cat, place)
print('Did not find any')
return None
checkNumbers = { '2305': {'place':'Community Action', 'class':'Training'},
'2304': {'place':'Community Action', 'class':'Training'},
'2285': {'place':'Community Action', 'class':'Training'},
'2287': {'place':'Community Action', 'class':'Training'},
'2284': {'place':'The Snake Guy', 'class':'Event'},
'2282': {'place':'Young Nak Church', 'class':'Rent'},
'2267': {'place':'National Wildlife Federation', 'class':'Office Expense'},
'2281': {'place':'Canyon Road Auto Body', 'class':'Van'},
'2308': {'place':'Washington County', 'class':'Taxes'},
'2312': {'place':'Jay Person', 'class':'Payroll'},
'2279': {'place':'Vidhya Ammaiyapan', 'class':'Payroll'},
'2307': {'place':'Community Action', 'class':'Training'},
'2264': {'place':'SAIF', 'class':'Insurance'},
'2278': {'place':'SAIF', 'class':'Insurance'},
'2273': {'place':'Talbot Korvola and Warwick', 'class':'Tax Preparation'},
'2272': {'place':'Schopp Home Maintenance', 'class':'Repair'},
'2274': {'place':'Oregon Department of Revenue', 'class':'Taxes'},
'2263': {'place':'Office of Child Care', 'class':'Licensing'},
'2270': {'place':'Anup Enquist', 'class':'Licensing'},
'2269': {'place':'Excellence Plumbing', 'class':'Office Expense'},
'2288': {'place':'AA Drain Cleaning', 'class':'Office Expense'},
'2303': {'place':'Davis Lock and Safe', 'class':'Repair'},
'2266': {'place':'Davis Lock and Safe', 'class':'Repair'} }
def checks(row):
checkNo = row['check number']
if checkNo != None and checkNo != '':
if int(checkNo) > 10000:
return ('Payroll', 'Wells Fargo')
elif int(row['amount'] == '-3000.00'):
return ('Rent', 'Young Nak Church')
elif int(row['amount'] == '-3.00'):
return ('Background Check', 'Oregon Department of Education')
elif checkNo in checkNumbers.keys():
checkData = checkNumbers[checkNo]
return (checkData['class'], checkData['place'])
else:
return None
def expenseClass(row):
if checks(row) != None:
return checks(row)
elif getCategory(row) != None:
(cat, place) = getCategory(row)
return (cat, place)
else:
return ('Unknown', 'Unknown')
def stripQuotes(s):
return re.sub(r'^"|"$', '', s)
def printRow(row):
print(', '.join([row['date'], row['class'], row['place'], row['amount'], row['check number'], '"' + row['description'] + '"']))
checkDictionary = []
with open('2016Checking.csv', newline='') as csvfile:
checkreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in checkreader:
if len(row) == 0:
continue
rowdict = { 'date':stripQuotes(row[0]),
'amount':stripQuotes(row[1]),
'check number':stripQuotes(row[3]),
'description':stripQuotes(row[4]) }
(rowdict['class'], rowdict['place']) = expenseClass(rowdict)
checkDictionary.append(rowdict)
for check in checkDictionary:
printRow(check)
for cat in categories.keys():
for check in checkDictionary:
if check['class'] == cat:
categories[cat]['total'] += float(check['amount'])
for cat in categories.keys():
print(cat, ', ', round(categories[cat]['total'],2))
<file_sep># Tax-Preparation
Python program to process my .csv Business Checking
| d0a7b024e37265079811c0f99052aa6f4d4e6dc5 | [
"Markdown",
"Python"
]
| 2 | Python | MidnightSkulker/Tax-Preparation | ad9db5536694e401d11398d890526f655d15a6ec | c4fd493688b844acd62d8a2b454478e5baef5067 |
refs/heads/master | <file_sep>import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { Tabbar, TabbarItem, Button, NavBar,
Tab, Tabs, Calendar,Swipe ,
SwipeItem,PullRefresh,Field,Form,
Search,Icon,Empty,Grid, GridItem,
Toast,Sticky,ActionBar, ActionBarIcon,
ActionBarButton,CouponCell, CouponList, Popup,
ActionSheet,Rate,Loading,Collapse, CollapseItem,RadioGroup,Radio} from 'vant';
//引入全部vant
// import Vant from 'vant';
import 'vant/lib/index.css';
const app = createApp(App);
app.use(store);
app.use(router);
// app.use(Vant);
app.use(Button);
app.use(Tabbar);
app.use(TabbarItem);
app.use(Icon);
//轻提示
app.use(Toast);
// 优惠券
app.use(CouponCell);
app.use(CouponList);
// 弹出层
app.use(Popup );
// 轮播
app.use(Swipe);
app.use(SwipeItem);
//下拉刷新
app.use(PullRefresh);
// 头部导航标题
app.use(NavBar);
//标签切换
app.use(Tab);
app.use(Tabs);
// Form 表单
app.use(Field);
app.use(Form);
//宫格
app.use(Grid);
app.use(GridItem);
app.use(NavBar);
app.use(Tab);
app.use(Tabs);
app.use(Calendar);
//搜索框
app.use(Search);
//error空页面
app.use(Empty);
//宫格
app.use(Grid);
app.use(GridItem);
//粘性定位
app.use(Sticky);
// 动作面板
app.use(ActionSheet);
//底部购买
app.use(ActionBar);
app.use(ActionBarIcon);
app.use(ActionBarButton);
//评分
app.use(Rate);
//刷新图片
app.use(Loading);
//下拉菜单
app.use(Collapse);
app.use(CollapseItem);
// 单选框
app.use(RadioGroup);
app.use(Radio);
app.mount('#app');
<file_sep>const path = require("path");
module.exports = {
chainWebpack: c => {
c.resolve.alias
.set("@", path.join(__dirname, "./src"));
}
}<file_sep>import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
redirect:"/index",
children:[
{
path:"/index",
component:()=>import("../views/Index.vue"),
// redirect:"/index/foreign",
// children:[
// {
// path:"course",
// component:()=>import("../views/indexTab/Course.vue"),
// },
// {
// path:"foreign",
// component:()=>import("../views/indexTab/Foreign.vue"),
// },
// {
// path:"echo",
// component:()=>import("../views/indexTab/Echo.vue"),
// }
// ]
},
{
path:"/foreignlist",
component:()=>import("../views/indexTo/ForeignList.vue")
},
{
path:"/hello",
component:()=>import("../views/Hello.vue")
},
{
path:"/timetable",
component:()=>import("../views/Timetable.vue"),
redirect:"/timetable/calendar",
meta: { requiresAuth: true },
children:[
{
path:"calendar",
component:()=>import("../views/timetable/Calendar.vue")
},
{
path:"list",
component:()=>import("../views/timetable/List.vue")
}
]
},
{
path:"/mine",
component:()=>import("../views/Mine.vue"),
meta: { requiresAuth: true }
}
]
},
{
path:"/teacherlist",
component:()=> import("../views/TeacherList.vue")
},
//我的页跳转路由
{
path:"/waijiao",
component:()=> import("../views/mien/Waijiao.vue")
},
{
path:"/dingdan",
component:()=> import("../views/mien/Dingdan.vue")
},
{
path:"/kecheng",
component:()=> import("../views/mien/Kecheng.vue")
},
{
path:"/huiben",
component:()=> import("../views/mien/Huiben.vue")
},
{
path:"/peiyin",
component:()=> import("../views/mien/Peiyin.vue")
},
{
path:"/baogao",
component:()=> import("../views/mien/Baogao.vue")
},
{
path:"/huifang",
component:()=> import("../views/mien/Huifang.vue")
},
{
path:"/kefu",
component:()=> import("../views/mien/Kefu.vue")
},
{
path:"/xiaoxi",
component:()=> import("../views/mien/Xiaoxi.vue")
},
{
path:"/shezhi",
component:()=> import("../views/mien/Shezhi.vue")
},
{
path:"/shengyv",
component:()=> import("../views/mien/Shengyv.vue")
},
{
path:"/juan",
component:()=> import("../views/mien/Juan.vue")
},
// 登录注册路由
{
path:"/login",
component:()=> import("../views/Login.vue")
},
//结算路由
{
path:"/closing/:id",
component:()=> import("../views/Closing.vue"),
props: true
},
// hello路由
{
path:"/selected",
component:()=> import("../views/Hello/selected.vue")
},
{
path:"/custom",
component:()=> import("../views/Hello/custom.vue")
},
{
path:"/huihua",
component:()=> import("../views/Hello/huihua_list.vue"),
meta: { requiresAuth: true }
},
{
path:"/hello_details/:id",
component:()=> import("../views/Hello/hello_details.vue")
},
{
path:"/hello_details_gm",
component:()=> import("../views/Hello/hello_details_gm.vue")
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
},
{
//timeDetail详情页
path:"/timedetail/:id",
component: () => import('../views/TimeDetail.vue'),
//传参
props: true
},
{
//teacherdetail详情页
path:"/teacherdetail/:id",
component: () => import('../views/TeacherDetail.vue'),
//传参
props: true
},
{
//morecalss 详情页
path:"/moreclass/:id",
component: () => import('../views/More.vue'),
//传参
props: true
},
{
path:"/:catchAll(.*)",
component:()=> import("../views/Error.vue")
},
]
const router = createRouter({
history: createWebHashHistory(),
routes
});
router.beforeEach((to, from, next) => {
if (to.path === "/login") {next();}
else { // 判断该路由是否需要登录权限
if (to.meta.requiresAuth && !sessionStorage.getItem("token")) { // 判断当前的token是否存在
next({
path: "/login",
query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
});
}else{
next();
}
}
})
export default router
<file_sep>import axios,{AxiosPromise,AxiosRequestConfig, AxiosResponse} from 'axios'
import { Toast } from "vant";
const instance = axios.create({
baseURL: "http://172.16.58.3:3000",
timeout: 15000
});
//接口类型
interface resType {
status:number,
msg:string,
[propName:string]:any
};
// 添加请求拦截器(每次发送请求前统一做的事情)
instance.interceptors.request.use(
config => {
if (localStorage.getItem("token")) {
// 请求数据里面携带token
// if (config.method === "get") {
// config.params.token = localStorage.getItem("token");
// } else if (config.method === "post") {
// config.data.token = localStorage.getItem("token");
// }
// 在请求头里面携带token
config.headers.token = localStorage.getItem("token");
}
// 在发送请求之前做些什么
return config;
},
error => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器(每次请求成功以后统一做的事情)
instance.interceptors.response.use(
response => {
// console.log(response);
// 对响应数据做点什么
return response.data;
},
function(error) {
// 对响应错误做点什么
return Promise.reject(error);
}
);
const http = {
get(url:string, params:any) {
return new Promise((resolve, reject) => {
instance
.get(url, {
params: params || {}
})
.then((res: any) => {
if (res.status === 0) {
resolve(res);
} else {
Toast(res.msg);
}
})
.catch(err => {
Toast(err.message);
reject(err);
});
});
},
post(url:string, params:any) {
return new Promise((resolve, reject) => {
instance
.post(url, params)
.then((res:any):void => {
if (res.status === 0) {
resolve(res);
} else {
Toast(res.msg);
}
})
.catch(err => {
Toast(err.message);
reject(err);
});
});
}
};
export default http;<file_sep>import http from "./http";
interface paramType{
[propName:string]:any
}
export const getHello = (params:paramType) => http.get("/hello", params);
// export const getHello = function(params:paramType) {http.get("/hello", params)} ;
export const getTimeListApi = (params:paramType) => http.get("/timefirst", params);
export const getTimeDetailApi = (params:paramType) => http.get("/particulars", params);
//获得首页外教展示列表
export const getForeignListApi = (params:paramType) => http.get("/getindexlist", params);
//首页轮播信息
export const getBannerApi = (params:paramType) => http.get("/getbanner", params);
//首页tab切换 course
export const getCourseListApi = (params:paramType) => http.get("/product/productlist", params);
//通过商品id获得商品所有信息params{id:1000}
export const getProductInfoApi = (params:paramType) => http.post("/product/getproduct", params);
//获得验证码params{phone:"15300000000"}
export const getVertifyCodeApi = (params:paramType) => http.post("/user/sendcode", params);
//用户登陆/注册params{phone:"15300000000",code:"1236"}
export const loginApi = (params:paramType) => http.post("/user/login", params);
//普通外教列表
export const sortListApi = (params:paramType) => http.get("/product/sortList", params);
//评分外教列表
export const scoreListApi = (params:paramType) => http.get("/product/scoreList", params);
//销量外教列表
export const soldListApi = (params:paramType) => http.get("/product/soldList", params);
//教师信息
export const getTeacherCourseApi = (params:paramType) => http.post("/product/teachercourse", params);
//用户信息获取
export const getUserApi = (params:paramType) => http.post("/user/getuserinfo", params);
//用户昵称修改
export const setUserApi = (params:paramType) => http.post("/user/updateuser", params);
| 8c4d3e04394d2f60dc8aa9e635e956a92ac68de7 | [
"JavaScript",
"TypeScript"
]
| 5 | TypeScript | Chan-picle/putaojia | 5c4b828fde7fedb419010f62929cf359c14f62ab | 6bc56460794c7cec167a59c3f5147b6213852a39 |
refs/heads/master | <repo_name>peidong-hu/docker-x2go-pycharm<file_sep>/docker/start-sshd.sh
#!/bin/sh
# Create ssh "client" key
# http://stackoverflow.com/a/20977657
USER_HOME=/home/docker
KEYGEN=/usr/bin/ssh-keygen
KEYFILE=${USER_HOME}/.ssh/id_rsa
if [ ! -f $KEYFILE ]; then
$KEYGEN -q -t rsa -N "" -f $KEYFILE
cat $KEYFILE.pub >> ${USER_HOME}/.ssh/authorized_keys
fi
echo "== Use this private key to log in =="
cat $KEYFILE
# Start sshd
sudo /usr/sbin/sshd -D
<file_sep>/README.md
# docker-x2go-pycharm<file_sep>/docker/Dockerfile
FROM ubuntu
MAINTAINER <NAME>
# Please change this value to force the builders at Quay.io/Docker Hub
# to omit the cached Docker images. This will have the same effect to
# adding `--no-cache` to `docker build` command.
#
ENV DOCKERFILE_UPDATED 2017-04-02
RUN (apt-get update && \
apt-get install -y software-properties-common && \
add-apt-repository -y ppa:x2go/stable && \
apt-get update && \
DEBIAN_FRONTEND=noninteractive apt-get install -y \
x2goserver x2goserver-xsession ttf-dejavu fonts-ipafont-gothic \
openbox obconf obmenu conky nitrogen \
sudo rxvt-unicode-256color \
firefox emacs)
RUN (mkdir -p /var/run/sshd && \
sed -ri 's/UseDNS yes/#UseDNS yes/g' /etc/ssh/sshd_config && \
echo "UseDNS no" >> /etc/ssh/sshd_config)
# sed -ri 's/UsePAM yes/#UsePAM yes/g' /etc/ssh/sshd_config && \
# sed -ri 's/#UsePAM no/UsePAM no/g' /etc/ssh/sshd_config)
# Create a user
RUN (useradd -m docker && \
mkdir -p /home/docker/.ssh && \
chmod 700 /home/docker/.ssh && \
chown docker:docker /home/docker/.ssh && \
mkdir -p /etc/sudoers.d)
ADD ./999-sudoers-docker /etc/sudoers.d/999-sudoers-docker
RUN chmod 440 /etc/sudoers.d/999-sudoers-docker
# Startup script
ADD ./start-sshd.sh /start-sshd.sh
RUN chmod 744 /start-sshd.sh
RUN chown docker:root /start-sshd.sh
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
LABEL maintainer "<NAME> <<EMAIL>>"
RUN apt-get update && apt-get install --no-install-recommends -y \
python python-dev python-setuptools python-pip \
python3 python3-dev python3-setuptools python3-pip \
gcc git openssh-client curl \
libxtst-dev libxext-dev libxrender-dev libfreetype6-dev \
libfontconfig1 \
&& rm -rf /var/lib/apt/lists/* \
&& useradd -ms /bin/bash developer
ARG pycharm_source=https://download.jetbrains.com/python/pycharm-community-2018.3.4.tar.gz
ARG pycharm_local_dir=.PyCharmCE2018.3
WORKDIR /opt/pycharm
RUN curl -fsSL $pycharm_source -o /opt/pycharm/installer.tgz \
&& tar --strip-components=1 -xzf installer.tgz \
&& rm installer.tgz \
&& /usr/bin/python2 /opt/pycharm/helpers/pydev/setup_cython.py build_ext --inplace \
&& /usr/bin/python3 /opt/pycharm/helpers/pydev/setup_cython.py build_ext --inplace
USER docker
ENV HOME /home/docker
RUN mkdir /home/docker/.PyCharm \
&& ln -sf /home/docker/.PyCharm /home/docker/$pycharm_local_dir
#RUN sudo chown docker:root /start-sshd.sh
RUN (sudo apt-get update)
RUN (sudo apt-get install -y xfce4)
RUN (sudo apt-get install -y xfce4-terminal)
RUN (sudo apt-get install -y vim)
RUN (mkdir ~/git)
ADD ./switchShell.sh /home/docker/switchShell.sh
ADD ./switchShell.sh /home/docker/Desktop/switchShell.sh
RUN (sudo pip3 install virtualenv)
RUN (sudo mkdir ~/.virtualenvs)
RUN (sudo pip install virtualenvwrapper)
ENV WORKON_HOME=~/.virtualenvs
RUN (echo ". /usr/local/bin/virtualenvwrapper.sh" >> /home/docker/.bashrc)
ADD ./startPycharm.sh /home/docker/startPycharm.sh
ADD ./startPycharm.sh /home/docker/Desktop/startPycharm.sh
EXPOSE 22
ENTRYPOINT ["/start-sshd.sh"]
<file_sep>/run.sh
#!/bin/sh
sudo docker rm x2go
sudo docker run -it -d -p 2222:22 --name=x2go zhouyibhic/x2go-pycharm:latest
sleep 3
sudo docker logs x2go
| 4aacd3ea273b69681d0663a46671c9ee95f8a3b5 | [
"Markdown",
"Dockerfile",
"Shell"
]
| 4 | Shell | peidong-hu/docker-x2go-pycharm | 54c0b42369268b54d6c5580b4956d947c24c0af9 | f92abb2837b671376e30e69506c15a59d9ed3c0a |
refs/heads/master | <file_sep>import re
import nltk
import os
import sys as Sys
from nltk.tokenize import WhitespaceTokenizer
from nltk import ne_chunk, pos_tag, word_tokenize
from nltk.tree import Tree
from nltk.tokenize.util import regexp_span_tokenize
finalArticles = []
articleName = input("Insira o nome do arquivo: ")
textName = input("Insira o nome da pasta para os textos: ")
entitiesName = input("Insira o nome da pasta as entidades nomeadas: ")
def fillFinalArticles(filename):
content = open(filename, 'r').read()
articles = re.sub('<.*?>', '##', content).split('##')
new_articles = [article.strip() for article in articles if not article.strip() == '']
for i in range(len(new_articles)):
finalArticles.append(new_articles[i].split('\n', 1))
#FillfinalArticles and create dir:
fillFinalArticles(articleName)
os.makedirs(textName, exist_ok = True)
os.makedirs(entitiesName, exist_ok = True)
#Start the program:
for item in finalArticles:
sent_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
indexes = sent_tokenizer.span_tokenize(item[1]) # Indices de sentenca
sent1 = nltk.word_tokenize(item[1])
sent2 = nltk.pos_tag(sent1)
sent3 = nltk.ne_chunk(sent2, binary = True)
named_entities = []
for i in range(len(sent3)):
if "NE" in str(sent3[i]):
named_entities.append(' '.join(token[0] for token in sent3[i].leaves()))
#------------------------------------------#
#If we want to remove repeated entities:
#seen = set()
#named_entitiesFinal = []
#for item in named_entities:
# if item not in seen:
# seen.add(item)
# named_entitiesFinal.append(item)
#------------------------------------------#
word_indexes = []
for token in named_entities:
index = item[1].find(token)
word_indexes.append((index, index+len(token)))
#Writing the files:
f_name = item[0] + '.txt'
f = open(textName + "/" + f_name, 'w')
f.write(item[1][1:])
f.write("\n\n")
for i in range(len(indexes)):
f.write(str(indexes[i]) + " ")
f.write("\n\n")
for i in range(len(word_indexes)):
f.write(str(word_indexes[i]) + " ")
f_name = "NE - " + item[0] + ".txt"
f = open(entitiesName + "/" + f_name, 'w')
for name in named_entities:
f.write(name + "\n")
<file_sep>import re
import nltk
from nltk.tokenize import WhitespaceTokenizer
from nltk import ne_chunk, pos_tag, word_tokenize
from nltk.tree import Tree
from nltk.tokenize.util import regexp_span_tokenize
def split_articles():
filename = "teste"
content = open(filename, 'r').read()
articles = re.sub('<.*?>', '##', content).split('##')
new_articles = [article.strip() for article in articles if not article.strip() == '']
for i in range(len(new_articles)):
f_name = 'article{0}.txt'.format(i)
f = open(f_name, 'w')
f.write(new_articles[i])
filename = 'article1.txt'
content = open(filename, 'r').read()
sent_tokenizer=nltk.data.load('tokenizers/punkt/english.pickle')
indexes = sent_tokenizer.span_tokenize(content) # Indices de sentenca
sent1 = nltk.word_tokenize(content)
sent2 = nltk.pos_tag(sent1)
sent3 = nltk.ne_chunk(sent2, binary=True)
named_entities = []
# Utilizado para retornar entidades nomeadas (Precisa de ajustes)
for i in range(len(sent3)):
if "NE" in str(sent3[i]):
named_entities.append(' '.join(token[0] for token in sent3[i].leaves()))
word_indexes = []
for token in named_entities:
index = content.find(token)
word_indexes.append((index, index+len(token)))
print word_indexes
print
print indexes
print
print named_entities
| cf5c2ad39494dac313c3e742fbb5d451945f4294 | [
"Python"
]
| 2 | Python | cyro809/trabalho-nltk | 6d07a3fb9d059d37a5a0e84946a5b34153af3c61 | 31669eb658c5fa98cd3011bacbae9bce4cf4a9e9 |
refs/heads/main | <file_sep>import pytest
from main import get_notifications, weather_handler, get_weather, news_handler, get_news, \
covid_handler, get_covid
"""
The modules to test are as such:
get_notifications - see if it returns a list
weather_handler - see if it returns 4 variables: float, int, int, string
get_weather - see if it returns a dictionary
news_handler - see if it returns a dictionary
get_news - see if it returns a list
covid_handler - see if it returns a dictionary
get_covid - see if it returns a dictionary
I can only test these modules because the others don't return anything. I can only test their return
values for types because the data is fluid.
"""
def test_get_notifications():
assert (isinstance(get_notifications(True, True), list) == True)
assert (isinstance(get_notifications(False, False), list) == True)
assert (isinstance(get_notifications(True, False), list) == True)
assert (isinstance(get_notifications(False, True), list) == True)
def test_weather_handler():
assert (isinstance(weather_handler(), (float, int, int, str)) == True)
def test_get_weather():
assert (isinstance(get_weather(), dict) == True)
def test_news_handler():
assert (isinstance(news_handler(), dict) == True)
def test_get_news():
assert (isinstance(get_news(), list) == True)
def test_covid_handler():
assert (isinstance(covid_handler(), dict) == True)
def test_get_covid():
assert (isinstance(get_covid(), dict) == True)
def main_test():
test_get_notifications()
test_weather_handler()
test_get_weather()
test_news_handler()
test_get_news()
test_covid_handler()
test_get_covid()
main_test()
<file_sep>
"""
This is a smart alarm clock for ECM1400's Continuous Assessment 3
"""
# Imports initialised
import datetime
import json
import logging
import sched
import time
import pyttsx3
import requests
from flask import Flask, request, render_template, Markup
from newsapi import NewsApiClient
from uk_covid19 import Cov19API
LOGGING_FORMAT = '%(levelname)s: [%(asctime)s] -- %(message)s'
logging.basicConfig(filename="pysys.log", level=logging.DEBUG, format=LOGGING_FORMAT)
# API keys, settings and the structure of the Covid19 notifications are initialised
logging.info("opening config file")
with open('config.json', 'r') as f:
json_file = json.load(f)
keys = json_file["API-keys"]
logging.info("keys loaded from config file")
settings = json_file["settings"]
logging.info("settings loaded from config file")
covidstructure = json_file["cases_and_deaths"]
logging.info("covidstructure loaded from config file")
england_only = [
'areaType=nation',
'areaName=England'
]
logging.info("scheduler initialising")
s = sched.scheduler(time.time, time.sleep) # Sets up alarm scheduler
logging.info("scheduler initialised")
# Below set site logo and favicon
IMAGE = 'alarmSymbol.png'
FAVICON = 'alarmSymbol.ico'
alarms = [] # The list that's returned to the HTML template for alarms
notifications = [] # The list that's returned to the HTML template for notifications
logging.info("alarms and notifications lists initialised")
NOTIFICATION_TIME = settings["notification_time"] # The minute at which regular notifs are sent
NEWS_ARTICLE_NUMBER = settings["article_number"] # Number of articles in news briefing
NEWS_SOURCES = settings["news_sources"] # Sources for news
logging.info("covid settings initialised")
if NEWS_ARTICLE_NUMBER > 10: # Error checking to ensure too many articles aren't sent
NEWS_ARTICLE_NUMBER = 5
# The below if statement checks if the user inputted a double digit value
if not NOTIFICATION_TIME.isnumeric() or len(NOTIFICATION_TIME) != 2:
NOTIFICATION_TIME = "00"
logging.info("covid settings checked")
# Creates weather API URL
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
weather_api = keys["weather"]
news_api_key = keys["news"]
city_name = settings["weather_city"]
complete_weather_url = BASE_URL + "appid=" + weather_api + "&q=" + city_name
logging.info("weather api initialised")
# Extracts news API key
complete_news_api = NewsApiClient(api_key=news_api_key)
logging.info("news api initialised")
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def main():
"""This module is the central hub for this program.
Because of the way I started building it, I was unable to isolate various features into
separate modules. This includes the sections that adds alarms, deletes alarms and deletes
notifications.
"""
# Gets args used in form submission on site
alarm = request.args.get('alarm')
name = request.args.get('two')
alarm_item = request.args.get('alarm_item')
notif_item = request.args.get('notif')
news_item = request.args.get('news')
weather_item = request.args.get('weather')
time_right_now = datetime.datetime.now() # Gets current datetime object
if str(time_right_now)[14:16] == str(NOTIFICATION_TIME): # Checks if time matches what user set
get_notifications(True, True) # Default notifs will send out weather and news
logging.info("notifications added")
if alarm: # If new alarm has been requested
logging.info("alarm creation requested")
if not alarm[0:5].isnumeric(): # Checks if year is > 9999
logging.info("alarm year <= 9999 confirmed")
formatted_datetime = datetime.datetime(int(alarm[0:4]), int(alarm[5:7]),
int(alarm[8:10]),
int(alarm[11:13]), int(alarm[14:16]))
# Above converts requested time into datetime object
difference = formatted_datetime - time_right_now
difference_seconds = difference.days * 86400 + difference.seconds
# Converts difference into seconds only
corrdict = (next((item for item in alarms if item["title"] == name), None))
# corrdict is a True, None statement
# It looks through the alarms list, and tries to find a title with same value as 'name'
if not corrdict: # Triggers if an alarm with the same label as 'name' doesn't exist
logging.info("new alarm being added")
event = s.enter(difference_seconds, 1, tts_request, (name,)) # Event is entered
alarms.append(
{"title": name, "content": str(formatted_datetime) + "\n", "event": event})
logging.info("new alarm added")
# event is appended to alarms list (which is then passed to html template)
if news_item: # If check box was ticked
alarms[-1]["news"] = True # Assign True to news key
logging.info("news = True added to alarm")
else:
alarms[-1]["news"] = False # Otherwise assign False
logging.info("news = False added to alarm")
if weather_item:
alarms[-1]["weather"] = True # See news
logging.info("weather = True added to alarm")
else:
alarms[-1]["weather"] = False
logging.info("weather = False added to alarm")
render_template('index.html', title='ECM1400 Alarm', alarms=alarms,
notifications=notifications, image=IMAGE,
favicon=FAVICON) # In theory, refreshes page
if alarm_item: # If alarm deleted
logging.info("alarm being deleted")
for counter, item in enumerate(alarms):
if item["title"] == alarm_item: # Finds alarm in alarms
s.cancel(alarms[counter]["event"]) # Cancel alarm in alarms
logging.info("alarm cancelled")
del alarms[counter] # Deletes alarm entry in alarms
logging.info("alarm entry removed from alarms")
if notif_item: # If notification deleted
logging.info("notification being deleted")
for counter, item in enumerate(notifications):
if item["title"] == notif_item: # Finds notification in notifications
del notifications[counter] # Delete notification entry from notifications
render_template('index.html', title='ECM1400 Alarm', alarms=alarms, notifications=notifications,
image=IMAGE,
favicon=FAVICON) # In theory, refreshes page
get_time() # Constantly checks for time, runs alarm if it should run within a minute
cleanup() # Cleans up any discrepancies between alarms and scheduler queue
return render_template('index.html', title='ECM1400 Alarm', alarms=alarms,
notifications=notifications, image=IMAGE,
favicon=FAVICON) # Returns page
@app.route('/tts_request')
def tts_request(announcement="Text to speech example announcement!"):
"""Typical text to speech module."""
engine = pyttsx3.init() # Engine initialised
engine.say(announcement) # Announcement spoken
logging.info("tts engaged")
engine.runAndWait()
return "Hello text-to-speech example"
####################################################################################################
@app.route('/get_time')
def get_time():
"""This module checks if any alarm is within one minute of the time it should run."""
right_now = datetime.datetime.now() # Gets current datetime object
for counter, item in enumerate(alarms):
formatted_datetime = datetime.datetime(int(item["content"][0:4]), int(item["content"][5:7]),
int(item["content"][8:10]),
int(item["content"][11:13]),
int(item["content"][14:16]))
difference = formatted_datetime - right_now
# Above Calculates difference between now and each alarm running
difference_seconds = difference.days * 86400 + difference.seconds
if 60 > difference_seconds >= 0:
logging.info("scheduler to run")
# If the alarm hasn't passed, and is within one minute of running, run
get_notifications(alarms[counter]["weather"], alarms[counter]["news"])
# Unlike before, this get_notification's weather & news output is dependant on checkbox
del alarms[counter] # Deletes alarm from alarms
s.run() # Runs scheduler
logging.info("alarm sent")
cleanup() # Should clean up any discrepancies
render_template('index.html', title='ECM1400 Alarm', alarms=alarms,
notifications=notifications,
image=IMAGE, favicon=FAVICON) # In theory, should refresh page
return main()
@app.route('/cleanup')
def cleanup():
"""This module cleans up any discrepancies between alarms and scheduler queue."""
for counter, item in enumerate(alarms):
if item["event"] not in s.queue: # Checks if alarm event is not in queue
del alarms[counter] # If so, delete alarm
logging.info("alarm cleaned up")
return "cleaned up"
####################################################################################################
@app.route('/get_notifications')
def get_notifications(weather_item, news_item):
final_notification = [] # Final notification (F_N) to be returned
covid_notification = get_covid() # Responds with dictionary notification for Covid
final_notification.append(covid_notification) # Appends covid_notification to F_N
logging.info("covid notification added")
if weather_item: # If checkbox was ticked
weather_notification = get_weather() # Responds with dictionary notification for weather
final_notification.append(weather_notification) # Appends weather_notification to F_N
logging.info("weather notification added")
if news_item: # If checkbox was ticked
news_notification = get_news() # Responds with list of dictionaries for news
for _, article in enumerate(news_notification): # For each dict in the list
final_notification.append(article) # Append each news article as a separate notif
logging.info("news notification added")
global notifications # Use the global variable, instead of a local variable
notifications = final_notification # Previous notifications are reset
return "notifications gotten"
@app.route('/weather_handler')
def weather_handler():
"""This module uses the Weather API to grab weather data for a notification"""
weather_json = requests.get(complete_weather_url).json() # Get data and turn into json file
logging.info("weather_json retrieved")
if weather_json["cod"] != "404": # If weather could be found
main_stats = weather_json["main"]
current_temperature = main_stats["temp"]
current_pressure = main_stats["pressure"]
current_humidity = main_stats["humidity"]
main_weather = weather_json["weather"]
weather_description = main_weather[0]["description"]
# The above just extracts stats required for a notification
return current_temperature, current_pressure, current_humidity, weather_description
else: # Because this function is called by another, it should return something
return None, None, None, None
@app.route('/get_weather')
def get_weather():
"""This module sends off a weather notification"""
current_temperature, current_pressure, current_humidity, weather_description = weather_handler()
weather_notification = Markup("Temperature (degrees Celsius) = " + str(
round(current_temperature - 273, 2)) + ",<br/>Atmospheric Pressure (hPA) = " + str(
current_pressure) + ",<br/>Humidity (Percentage) = " + str(
current_humidity) + ",<br/>Description: " + str(
weather_description))
# Above formats the weather notification
return {"title": "Weather Report", "content": weather_notification}
@app.route('/news_handler')
def news_handler():
"""This module grabs the news data using the news api"""
top_headlines = complete_news_api.get_top_headlines(sources=NEWS_SOURCES, language='en')
logging.info("top_headlines retrieved")
# Uses source 'NEWS_SOURCE' as specified in config file
return top_headlines
@app.route('/get_news')
def get_news():
"""This module sends off a (couple of) news notification(s)"""
headlines = [] # initialises headline list for dictionaries
top_headlines = news_handler()
for counter in range(NEWS_ARTICLE_NUMBER):
headlines.append({"title": top_headlines["articles"][counter]["title"],
"content": top_headlines["articles"][counter]["description"]})
# Above adds each article to headlines list as a separate notification
return headlines
@app.route('/covid_handler')
def covid_handler():
"""This module grabs covid data from a module"""
# covidstructure is specified in config file
api = Cov19API(filters=england_only, structure=covidstructure)
covid_data = api.get_json() # Gets a json file of covid data
logging.info("covid_data retrieved")
return covid_data["data"][0] # Gets the latest day's data
@app.route('/get_covid')
def get_covid():
"""This module sends off a covid notification. You can't get covid from this."""
covid_data = covid_handler()
covid_content = Markup("Date: " + str(covid_data["date"]) + ",<br/>Country: " + str(
covid_data["areaName"]) + ",<br/>New Cases: " + str(
covid_data["newCasesByPublishDate"]) + ",<br/>Total Cases: " + str(
covid_data["cumCasesByPublishDate"]))
# The above formats the covid data, ready to send it off as a notification
covid_notification = {"title": "Covid Cases", "content": covid_content}
return covid_notification
if __name__ == '__main__':
app.run()
"""
MIT License
Copyright (c) 2020 <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># ECM1400 Smart Alarm
This is a smart alarm programmed for ECM1400's Continuous Assessment 3. This code can be found on
https://github.com/AdarshPrusty7/ECM1400-CA3. As of this submission, it is a private repo, but will
(hopefully) be public by the time you receive this project.
## Introduction
This is a basic smart alarm. One can set alarms and receive notifications. Every hour, the user
will receive a text-based notification including covid19 stats, a weather briefing, and news
headlines.
A user can set their alarm for whenever they want, however, alarms set in the past
will not run and alarms set beyond the year 9999 will not be registered at all. The user can
specify, when they set their alarm, whether they'd like to receive a news and/ or weather
briefing alongside it. Covid19 stats will always be displayed.
Multiple alarms of the same label are not allowed. If it is attempted, the second alarm will not
be registered at all. The program is designed to catch this.
A log file can be viewed at `pysys.log`, and a config file at `config.json`.
## Prerequisites
- Python 3.8+
- Weather API key from https://openweathermap.org/api
- News API key from https://newsapi.org/
- A stable internet connection
- Latest Version of `pip`
## Installation
- **pyttsx3 -** `pip install pyttsx3`
- **requests -** `pip install requests`
- **flask -** `pip install Flask`
- **newsapi -** `pip install newsapi-python`
- **uk-covid19 -** `pip install uk-covid19`
## Changing Config
The `config.json` file provided can and should be edited by the user. One must insert their
respective API keys under the `"API-keys"` as indicated, for weather and news updates.
Ensure the API-key only is in quotes, as such, "123456789", not "<123456789>".
Additionally, under the `"settings"` section, one can alter various options.
One can alter the city whose weather data one wants to read. This is currently set to `"London
"` in `"weather_city"`.
One can alter the **minute** on which notifications are sent every hour (e.g. if set to `"47
"`, notifications will be sent at `12:47`, `13:47`,` 14:47`, etc.) in `"notification_time"`.
One can alter the news sources they get their news notifications from. They can be viewed here
(https://newsapi.org/docs/endpoints/sources). When doing so, care must be taken to include the
additional source **inside** the quotation marks. For example, `"news_sources` is currently
set to `"bbc-news"`. If one wished to add 'the verge' as a source, they would need to replace
`"bbc-news"` with `"bbc-news, the-verge"`.
One can alter the number of articles they receive per news notification request. `"article_number
"` is currently set to `3`. Although this number can be raised, if the number of articles is set
to a number higher than 10, the program will default to a set value of 5 articles.
One can alter the structure of the Covid19 data they receive in their notifications. It is not
recommended you do this, unless you've looked at the module's documentation yourself.
## Using The Alarm Clock
#### Alarm
To add an alarm, you simply enter in a date and time in the format as shown in the form. Note that
the form will not accept any date beyond the year 9999 as an alarm date. Alarms set in the past
will not trigger, but will still appear on the left-hand side. You must cancel them manually to get
rid of them.
The user may choose to include a news and/or weather notification briefing as their alarm is set
off. This can be chosen when they first make their alarm, and is indicated by the check boxes.
To remove an alarm, simply click on the cross mark on the alarm's tab header.
#### Notifications
Notifications are sent every hour, at the minute of the user's choosing. By default, it is set to
to send at every '00', but this can be changed in the config file provided. See the 'Changing Config'
section for more information on this.
When the user is sent a non-alarm notification, they will be unable to delete them for under a minute.
Otherwise, they will be able to delete the notification immediately.
## Testing
Errors occurred on the development side when pylint was used, so basic assertion error tests were
used. These were compiled into one function which can be executed in the tests folder in
`test_main.py`.
## Known Issues
**These are some issues that I couldn't iron out by the final version of this project.**
- When submitting an alarm, double clicking on the button will result in an internal server error
. Simply navigate back to '/' or 'index' or press the 'back' button on your browser and resubmit
your form (don't double click this time).
- On occasion, after an alarm has been triggered, the alarm notification on the left-hand side
will not go away. You must manually remove it in this case, by clicking on the cross mark on
its tab header.
- If you schedule an alarm for the next minute (e.g. set at `12:46` for `12:47`), the alarm
notification won't pop up until the actual alarm has been triggered. You will then have to
manually remove the alarm.
- Alarms set in the past will not trigger but they will show up on left-hand side. You can get
rid of these by click on the cross mark on its tab header.
- Once a normal notification (i.e. not a notification sent off by an alarm) has been sent, you
will not be able to delete for under a minute after it is sent, depending on when the page next
refreshes itself.
- If in doubt, refresh the page.
## Details
#### Author(s): <NAME>
#### MIT License
MIT License
Copyright (c) 2020 <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.
#### Link to Source
This code can be found on
https://github.com/AdarshPrusty7/ECM1400-CA3.
| 0b53ab95c46bc019e7627dcf48c0c281aa4525f4 | [
"Markdown",
"Python"
]
| 3 | Python | AdarshPrusty7/ECM1400-CA3 | b6719c115944e6f7a80bf4f0a2f6a2f45653420b | 5bff4cbd9b08159c6685665bcdf8331f76ba50bb |
refs/heads/master | <file_sep>export const card1 = {
index: 1,
tags: ["N3", "感動"],
text: "問い合わせる",
hiragana: "といあわせる",
furigana: [
{
kanji: "問",
furi: "と",
},
{
kanji: "合",
furi: "あ",
},
],
english: "Inquire",
};
export const cards = [card1];
<file_sep>import { Action, TOGGLE_DEFAULT_SIDE } from "../actionCreators/interfaces";
export interface Options {
defaultSide: boolean;
}
const defaultState = { defaultSide: true };
const optionsReducer = (state = defaultState, action: Action): Options => {
switch (action.type) {
case TOGGLE_DEFAULT_SIDE:
return { ...state, defaultSide: action.payload };
default:
return state;
}
};
export default optionsReducer;
<file_sep>export interface Action {
type: string;
payload: any;
}
export const TOGGLE_DEFAULT_SIDE = "TOGGLE_DEFAULT_SIDE";<file_sep>export interface Furigana {
kanji: string;
furi: string;
}
export interface FrontJapanese {
text: string;
hiragana: string;
furigana: Furigana[];
}
export interface BackJapanese {
english: string;
}
export interface Japanese extends FrontJapanese, BackJapanese {
index: number;
tags: string[];
}
<file_sep>import {createStore, combineReducers} from "redux";
import options, {Options}from "./optionsReducer";
export interface Store {
options: Options;
}
const reducers = combineReducers({ options });
export default createStore(reducers);<file_sep># Flip Cards UI
## To Run Locally
When running locally, ensure that you have a **.env** file created with the following content:
```.env
REACT_APP_API_URL=http://localhost:5000
```
The port should tally with the port configured in **flip-cards-api**.
<file_sep>import {Action, TOGGLE_DEFAULT_SIDE} from "./interfaces";
export const setDefaultSide = (shouldFaceUp: boolean): Action => {
console.log("action setDefaultSide", shouldFaceUp);
return {
type: TOGGLE_DEFAULT_SIDE,
payload: shouldFaceUp,
};
}<file_sep>import { Furigana } from "../interface/card.interface";
const textToFuriKanji = (text: string, furiKanji: Furigana[]): Furigana[] => {
const textArr = [];
let remainingText = text;
for (const curFuriKanji of furiKanji) {
const indexOfKanji = remainingText.indexOf(curFuriKanji.kanji);
const indexAfterKanji = indexOfKanji + curFuriKanji.kanji.length;
const curFront = remainingText.slice(0, indexOfKanji);
const curMiddle = remainingText.slice(indexOfKanji, indexAfterKanji);
const curEnd = remainingText.slice(indexAfterKanji);
if (curFront.length) {
textArr.push({
kanji: curFront,
furi: "",
});
}
if (curMiddle.length) {
textArr.push(curFuriKanji);
}
remainingText = curEnd;
}
if (remainingText.length) {
textArr.push({
kanji: remainingText,
furi: "",
});
}
return textArr;
};
export default textToFuriKanji;
<file_sep>import splitText from "./textToFuriKanji";
describe("furiKranji", () => {
it("should return one object with kanji with furi as empty", () => {
const kanjiString = "abcdefg";
expect(splitText(kanjiString, [])).toMatchObject([
{ kanji: kanjiString, furi: "" },
]);
});
it("should split to different object with kanji and furi", () => {
const kanjiString = "abcdefg";
expect(
splitText(kanjiString, [{ kanji: "cd", furi: "xyz" }]),
).toMatchObject([
{ kanji: "ab", furi: "" },
{ kanji: "cd", furi: "xyz" },
{ kanji: "efg", furi: "" },
]);
});
it.each([
[
"abcdefg",
[{ kanji: "cd", furi: "xyz" }],
[
{ kanji: "ab", furi: "" },
{ kanji: "cd", furi: "xyz" },
{ kanji: "efg", furi: "" },
],
],
[
"abcdefg",
[
{ kanji: "a", furi: "zz" },
{ kanji: "cd", furi: "xyz" },
],
[
{ kanji: "a", furi: "zz" },
{ kanji: "b", furi: "" },
{ kanji: "cd", furi: "xyz" },
{ kanji: "efg", furi: "" },
],
],
[
"abcdefg",
[
{ kanji: "a", furi: "zz" },
{ kanji: "cd", furi: "xyz" },
{ kanji: "fg", furi: "234" },
],
[
{ kanji: "a", furi: "zz" },
{ kanji: "b", furi: "" },
{ kanji: "cd", furi: "xyz" },
{ kanji: "e", furi: "" },
{ kanji: "fg", furi: "234" },
],
],
])(
"should split to different object with multiple furi kanji",
(text, furiKanji, expected) => {
expect(splitText(text, furiKanji)).toMatchObject(expected);
},
);
});
<file_sep>import axios from "axios";
const instance = axios.create({
baseURL: process.env.REACT_APP_API_URL,
});
instance.interceptors.request.use(
function(config) {
const xsrfToken = localStorage.getItem("XSRF-TOKEN");
if (xsrfToken) {
config.headers["X-XSRF-TOKEN"] = xsrfToken;
}
return config;
},
function(error) {
return Promise.reject(error);
},
);
instance.defaults.headers.post["Content-Type"] = "application/json";
instance.defaults.withCredentials = true;
export default instance;
| dd2c1ff0398538d6cd28efeb6eb0a7230104aab4 | [
"Markdown",
"TypeScript"
]
| 10 | TypeScript | elsonlim/flip-cards-ui | 041d61f58e6655000509fa130888015274235970 | c0600a8a81fe5f6f2ffa26593b787f2e50f0cc66 |
refs/heads/master | <file_sep>
import numpy as np
from scipy.misc import logsumexp
from misc import sigmoid
class layer_sigmoid(object):
def __init__(self, dim_in, dim_out):
self.dim_in = dim_in
self.dim_out = dim_out
max_wt = 2 * np.sqrt(6.0 / (dim_in + dim_out))
self.weight = (np.random.rand(self.dim_in, self.dim_out) - 0.5) * max_wt
self.bias = np.zeros(self.dim_out)
def forward(self, in_train):
self.in_train = in_train
self.out_act = sigmoid(in_train.dot(self.weight) + self.bias)
def backward(self, grad_out):
self._grad_common(grad_out * self.out_act * (1.0 - self.out_act))
def _grad_common(self, grad_pre_act):
self.grad_weight = np.outer(self.in_train, grad_pre_act)
self.grad_bias = grad_pre_act
self.grad_in = grad_pre_act.dot(self.weight.T)
class layer_softmax(layer_sigmoid):
def __init__(self, *args):
super(layer_softmax, self).__init__(*args)
def forward(self, in_train):
self.in_train = in_train
pre_act = in_train.dot(self.weight) + self.bias
self.out_act = np.exp(pre_act - logsumexp(pre_act))
def backward(self, y_elem):
grad_pre_act = self.out_act.copy()
grad_pre_act[y_elem] -= 1.0
self._grad_common(grad_pre_act)
def loss(self, y_elem):
return -np.log(self.out_act[y_elem])
<file_sep>
import numpy as np
from misc import sigmoid, batch
class autoencoder(object):
def __init__(self, num_feat, num_hid, learning_rate=0.1, momentum=0.0,
max_epoch=200, denoise_prob=0.0, batch_size=10):
max_wt = 2 * np.sqrt(6.0 / (num_feat + num_hid))
self.weight = (np.random.rand(num_feat, num_hid) - 0.5) * max_wt
self.bias_enc = np.zeros(num_hid)
self.bias_dec = np.zeros(num_feat)
self.learning_rate = learning_rate
self.momentum = momentum
self.max_epoch = max_epoch
self.denoise_prob = denoise_prob
self.batch_size = batch_size
def train_batch(self, bin_x_train, bin_x_valid):
grad_weight = np.zeros_like(self.weight)
grad_bias_enc = np.zeros_like(self.bias_enc)
grad_bias_dec = np.zeros_like(self.bias_dec)
num_up = 0
last_risk_valid = np.inf
all_risk = []
for epoch in range(self.max_epoch):
risk_train = self._risk(bin_x_train)
risk_valid = self._risk(bin_x_valid)
print epoch, risk_train, risk_valid
all_risk += [(epoch, risk_train, risk_valid)]
num_up = num_up + 1 if risk_valid >= last_risk_valid else 0
last_risk_valid = risk_valid
if num_up >= 2:
self.weight += self.learning_rate * grad_weight
self.bias_enc += self.learning_rate * grad_bias_enc
self.bias_dec += self.learning_rate * grad_bias_dec
break
for mini_batch in batch(bin_x_train, self.batch_size):
grad_weight *= self.momentum
grad_bias_enc *= self.momentum
grad_bias_dec *= self.momentum
for inp in mini_batch:
(masked_inp, hid, rec) = self._forward(inp, train=True)
(gw, gb, gc) = self._backward(masked_inp, hid, rec)
grad_weight += gw / self.batch_size
grad_bias_enc += gb / self.batch_size
grad_bias_dec += gc / self.batch_size
self.weight -= self.learning_rate * grad_weight
self.bias_enc -= self.learning_rate * grad_bias_enc
self.bias_dec -= self.learning_rate * grad_bias_dec
return all_risk
def _forward(self, inp, train):
if train:
mask = 1.0 - np.random.binomial(1, self.denoise_prob, len(inp))
else:
mask = np.ones(len(inp))
masked_inp = mask * inp
hid = sigmoid(masked_inp.dot(self.weight) + self.bias_enc)
rec = sigmoid(hid.dot(self.weight.T) + self.bias_dec)
return masked_inp, hid, rec
def _backward(self, masked_inp, hid, rec):
grad_pre_act_dec = rec - masked_inp
grad_weight_dec = np.outer(hid, grad_pre_act_dec)
grad_bias_dec = grad_pre_act_dec
grad_pre_act_enc = grad_pre_act_dec.dot(self.weight)
grad_pre_act_enc *= hid * (1.0 - hid)
grad_weight_enc = np.outer(masked_inp, grad_pre_act_enc)
grad_bias_enc = grad_pre_act_enc
grad_weight = grad_weight_enc + grad_weight_dec.T
return grad_weight, grad_bias_enc, grad_bias_dec
def _risk(self, bin_x):
loss = 0.0
for inp in bin_x:
(minp, _, rec) = self._forward(inp, train=False)
loss -= minp.dot(np.log(rec)) + (1.0 - minp).dot(np.log(1.0 - rec))
return loss / bin_x.shape[0]
<file_sep>
import numpy as np
import random
from layer import *
from misc import batch
class neural_net(object):
def __init__(self, arch, learning_rate=0.1, max_epoch=200, momentum=0.0,
l2reg=0.0, dropout_prob=0.0, batch_size=10):
self.layer_list = [layer_sigmoid(arch[index], arch[index + 1])
for index in range(len(arch) - 2)]
self.layer_list += [layer_softmax(arch[-2], arch[-1])]
self.learning_rate = learning_rate
self.max_epoch = max_epoch
self.momentum = momentum
self.l2reg = l2reg
self.dropout_prob = dropout_prob
self.batch_size = batch_size
def train_batch(self, xy_train, xy_valid):
num_layer = len(self.layer_list)
grad_weight = [0.0] * num_layer
grad_bias = [0.0] * num_layer
all_risk = []
for epoch in range(self.max_epoch):
info = self._report(epoch, xy_train, xy_valid)
all_risk += [info]
for mini_batch in batch(zip(*xy_train), self.batch_size):
grad_weight = [g * self.momentum for g in grad_weight]
grad_bias = [g * self.momentum for g in grad_bias]
for x_elem, y_elem in mini_batch:
self._forward_prop(x_elem, train=True)
self._backward_prop(y_elem)
for ind, layer in enumerate(self.layer_list):
grad_reg = layer.grad_weight
grad_reg += self.l2reg * layer.weight * 2
grad_weight[ind] += grad_reg / self.batch_size
grad_bias[ind] += layer.grad_bias / self.batch_size
# update weights and biases
for ind, layer in enumerate(self.layer_list):
layer.weight -= self.learning_rate * grad_weight[ind]
layer.bias -= self.learning_rate * grad_bias[ind]
return all_risk
def _report(self, epoch, xy_train, xy_valid):
x_train, y_train = xy_train
x_valid, y_valid = xy_valid
pred_train, loss_train = self.pred_loss(xy_train)
pred_valid, loss_valid = self.pred_loss(xy_valid)
train_risk = np.mean(loss_train)
train_miss = (pred_train != y_train).sum()
valid_risk = np.mean(loss_valid)
valid_miss = (pred_valid != y_valid).sum()
train_str = 'risk: {:.6f}, miss: {:4d}/{:d}'.format(train_risk,
train_miss,
len(y_train))
valid_str = 'risk: {:.6f}, miss: {:4d}/{:d}'.format(valid_risk,
valid_miss,
len(y_valid))
print '{:4d} train {:s}; valid {:s}'.format(epoch, train_str, valid_str)
return epoch, train_risk, train_miss, valid_risk, valid_miss
def pred_loss(self, xy):
pred = np.zeros(len(xy[1]), dtype=int)
loss = np.zeros(len(xy[1]))
for index, (x_elem, y_elem) in enumerate(zip(*xy)):
self._forward_prop(x_elem, train=False)
pred[index] = self.layer_list[-1].out_act.argmax()
loss[index] = self.layer_list[-1].loss(y_elem)
return pred, loss
def _forward_prop(self, x_elem, train):
in_train = x_elem
drop_prob = self.dropout_prob
for layer in self.layer_list[:-1]:
layer.forward(in_train)
if train:
mask = 1 - np.random.binomial(1, drop_prob, len(layer.out_act))
else:
mask = (1 - drop_prob) * np.ones(len(layer.out_act))
layer.out_act *= mask
in_train = layer.out_act
self.layer_list[-1].forward(in_train)
def _backward_prop(self, y_elem):
grad_out = y_elem
for layer in reversed(self.layer_list):
layer.backward(grad_out)
grad_out = layer.grad_in
<file_sep>
import time
import numpy as np
from scipy.spatial.distance import pdist, squareform
import tensorflow as tf
class MolTensorNet(object):
_atom_num_dict = {1: 0, 6: 1, 7: 2, 8: 3, 9: 4, 16: 5}
_num_basis = 30
_num_hid_rec = 60
_num_hid = 15
_inter_mu_vec = np.arange(-1.0, 10.2, 0.2)
_inter_denom = 2 * 0.2**2
_num_inter = len(_inter_mu_vec)
def __init__(self, num_recurrent=1, dtype=tf.float64,
learning_rate=1e-8, momentum=0.9, max_epoch=100):
self.num_recurrent = num_recurrent
self.dtype = dtype
self.learning_rate = learning_rate
self.momentum = momentum
self.max_epoch = max_epoch
# initialize initial atom coefficients
self._coeff_init = self._init_rand_norm((len(self._atom_num_dict), self._num_basis))
# initialize recurrent weights/biases
self._weight_cf = self._init_rand((self._num_basis, self._num_hid_rec))
self._bias_cf = self._init_zero((self._num_hid_rec))
self._weight_df = self._init_rand((self._num_inter, self._num_hid_rec))
self._bias_df = self._init_zero((self._num_hid_rec))
self._weight_fc = self._init_rand((self._num_hid_rec, self._num_basis))
# initialize fully connected weights/biases
self._weight_hid = self._init_rand((self._num_basis, self._num_hid))
self._bias_hid = self._init_zero((self._num_hid))
self._weight_out = self._init_zero((self._num_hid, 1)) # 0's fine for a linear layer
self._bias_out = self._init_zero(())
# tensorflow session and variable initialization
self._sess = tf.Session()
def init_with_all_data(self, all_cart, all_mol_ener):
self._compute_atom_ener_trans(all_cart, all_mol_ener)
max_num_atom = np.max([len(cart) for cart in all_cart])
self._compute_graph(max_num_atom)
nbf = self._num_basis
norm_scale = 1.0 / np.sqrt(nbf)
self._sess.run(tf.initialize_all_variables())
def format_data(self, all_cart, all_mol_ener):
data = []
for cart, mol_ener in zip(all_cart, all_mol_ener):
z_vec = cart[:, 0]
dist_mat = squareform(pdist(cart[:, 1:]))
inter = self._compute_inter(dist_mat)
one_hot_z = np.zeros((len(z_vec), len(self._atom_num_dict)))
for ind, z in enumerate(z_vec):
one_hot_z[ind, self._atom_num_dict[int(z)]] = 1.0
data += [(len(cart), one_hot_z, inter, mol_ener)]
return data
def train_sgd(self, formatted_train, formatted_valid):
format_epoch_risk = 'epoch %d, train risk %f, valid risk %f'
for epoch in range(self.max_epoch):
start = time.time()
np.random.shuffle(formatted_train)
if epoch % 10 == 0:
train_risk = self._risk(formatted_train)
valid_risk = self._risk(formatted_valid)
#~ valid_risk = 0.0
print format_epoch_risk % (epoch, train_risk, valid_risk)
for num, ohz, intr, me in formatted_train:
grad_graph, one_hot_z, inter, mol_ener = self._grad_graph[num]
feed_dict = {one_hot_z: ohz, inter: intr, mol_ener: me}
self._sess.run(grad_graph, feed_dict)
print ' elapsed %f s' % (time.time() - start)
def pred(self, formatted_data):
pred = []
for num, ohz, intr, _ in formatted_data:
pred_graph, one_hot_z, inter = self._pred_graph[num]
feed_dict = {one_hot_z: ohz, inter: intr}
pred += [self._sess.run(pred_graph, feed_dict)]
return np.array(pred)
def _risk(self, formatted_data):
loss = 0.0
for num, ohz, intr, me in formatted_data:
loss_graph, one_hot_z, inter, mol_ener = self._loss_graph[num]
feed_dict = {one_hot_z: ohz, inter: intr, mol_ener: me}
loss += self._sess.run(loss_graph, feed_dict)
return loss / len(formatted_data)
def _compute_inter(self, dist_mat):
num_atom = dist_mat.shape[0]
inter = np.zeros((num_atom, num_atom, len(self._inter_mu_vec)))
for i in range(num_atom):
for j in range(i + 1, num_atom):
temp = (dist_mat[i, j] - self._inter_mu_vec)**2
inter[i, j, :] = np.exp(-temp / self._inter_denom)
inter[j, i, :] = inter[i, j, :]
return inter
def _compute_atom_ener_trans(self, all_cart, all_mol_ener):
num_atom_list = [cart.shape[0] for cart in all_cart]
self._atom_ener_mean = sum(all_mol_ener) / sum(num_atom_list)
zl = zip(all_mol_ener, num_atom_list)
sum_sq = sum([(me - num * self._atom_ener_mean)**2 for me, num in zl])
self._atom_ener_std = np.sqrt(sum_sq / sum(num_atom_list))
def _compute_graph(self, max_num_atom):
self._pred_graph = {num: self._pred_graph_num_atom(num)
for num in range(1, max_num_atom + 1)}
self._loss_graph = {num: self._compute_loss_graph(*lg)
for num, lg in self._pred_graph.iteritems()}
grad = tf.train.MomentumOptimizer(self.learning_rate, self.momentum)
self._grad_graph = {num: (grad.minimize(lg[0]), lg[1], lg[2], lg[3])
for num, lg in self._loss_graph.iteritems()}
def _pred_graph_num_atom(self, num_atom):
one_hot_z = tf.placeholder(self.dtype, [num_atom, len(self._atom_num_dict)])
shape_inter = [num_atom, num_atom, self._num_inter]
inter = tf.placeholder(self.dtype, shape_inter)
coeff_mat_rec = tf.matmul(one_hot_z, self._coeff_init)
shape_t4 = [num_atom, num_atom, self._num_hid_rec]
shape_v = [num_atom, num_atom, self._num_basis]
v_mask_np = np.zeros((num_atom, num_atom, self._num_basis))
for i in range(self._num_basis):
v_mask_np[:, :, i] = 1 - np.eye(num_atom)
v_mask = tf.constant(v_mask_np, dtype=self.dtype)
for _ in range(self.num_recurrent):
temp1 = tf.matmul(coeff_mat_rec, self._weight_cf) + self._bias_cf
temp2 = tf.reshape(inter, [-1, self._num_inter])
temp3 = tf.matmul(temp2, self._weight_df) + self._bias_df
temp4 = tf.reshape(temp3, shape_t4)
temp5 = tf.reshape(temp1 * temp4, [-1, self._num_hid_rec])
temp6 = tf.matmul(temp5, self._weight_fc)
tensor_v = tf.tanh(tf.reshape(temp6, shape_v))
tensor_v *= v_mask
coeff_mat_rec += tf.reduce_sum(tensor_v, [1])
hid_temp1 = tf.matmul(coeff_mat_rec, self._weight_hid) + self._bias_hid
hid_mat = tf.tanh(hid_temp1)
norm_atom_ener = tf.matmul(hid_mat, self._weight_out) + self._bias_out
atom_ener = norm_atom_ener * self._atom_ener_std + self._atom_ener_mean
mol_ener_pred = tf.reduce_sum(atom_ener)
return mol_ener_pred, one_hot_z, inter
def _compute_loss_graph(self, mol_ener_pred, one_hot_z, inter):
mol_ener = tf.placeholder(self.dtype, ())
loss = tf.square(mol_ener_pred - mol_ener)
return loss, one_hot_z, inter, mol_ener
def _init_rand(self, shape):
max_wt = np.sqrt(shape[0])
unif = tf.random_uniform(shape, -max_wt, max_wt, dtype=self.dtype)
return tf.Variable(unif)
def _init_zero(self, shape):
return tf.Variable(tf.zeros(shape, dtype=self.dtype))
def _init_rand_norm(self, shape):
stddev = 1 / np.sqrt(shape[1])
normal = tf.random_normal(shape, 0.0, stddev, dtype=self.dtype)
return tf.Variable(normal)
<file_sep>
import numpy as np
import scipy.io as sio
import cPickle as pickle
qm7 = sio.loadmat('qm7.mat')
num_mol = len(qm7['R'])
all_cart = []
all_label = []
for ind in range(num_mol):
source_atom_num = qm7['Z'][ind]
num_atom = sum(source_atom_num > 0)
atom_num = np.zeros(num_atom)
atom_num[...] = source_atom_num[:num_atom]
source_xyz = qm7['R'][ind]
xyz = np.zeros((num_atom, 3))
xyz[...] = source_xyz[:num_atom, :]
cart = np.array(np.bmat([atom_num.reshape(-1, 1), xyz]))
label = float(qm7['T'][0, ind])
all_cart += [cart]
all_label += [label]
qm7_dict = {'all_cart': all_cart, 'all_mol_ener': all_label}
with open('qm7_dict.pickle', 'w') as pic:
pickle.dump(qm7_dict, pic, protocol=pickle.HIGHEST_PROTOCOL)
<file_sep>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from deep_bm import DBM
with open('digitstrain.txt') as train_txt:
data_train = np.loadtxt(train_txt, delimiter=',')
x_train, y_train = data_train[:, :-1], data_train[:, -1]
y_train = np.array([int(y) for y in y_train])
bin_x_train = 1.0 * (x_train > 0.5)
bin_xy_train = (bin_x_train, y_train)
with open('digitsvalid.txt') as valid_txt:
data_valid = np.loadtxt(valid_txt, delimiter=',')
x_valid, y_valid = data_valid[:, :-1], data_valid[:, -1]
y_valid = np.array([int(y) for y in y_valid])
bin_x_valid = 1.0 * (x_valid > 0.5)
bin_xy_valid = (bin_x_valid, y_valid)
dbm = DBM(num_feat=bin_x_train.shape[1], num_hid1=100, num_hid2=100,
max_epoch=1, gibbs_iter=1)
dbm.train_batch(bin_x_train, bin_x_valid)
plt.figure(figsize = (10, 10))
gs = gridspec.GridSpec(10, 10)
gs.update(wspace=0.0, hspace=0.0)
rand = lambda dim: np.random.binomial(1, 0.5, dim)
for i in range(100):
rand_inp = rand(bin_x_train.shape[1])
rand_h1 = rand(dbm.num_hid1)
rand_h2 = rand(dbm.num_hid2)
(inp_neg, _, _) = dbm.gibbs_sampler((rand_inp, rand_h1, rand_h2), 1000)
ax = plt.subplot(gs[i])
ax.set_axis_off()
plt.imshow(inp_neg.reshape(28, -1), cmap=plt.cm.gray)
plt.show()
<file_sep>import numpy as np
from numpy.random import binomial
from misc import *
class RBM(object):
def __init__(self, num_feat, num_hid, learning_rate=0.1, max_epoch=100,
gibbs_iter=1, batch_size=10, num_chain=100):
self.weight = init_weight(num_feat, num_hid)
self.bias_for = np.zeros(num_hid)
self.bias_rev = np.zeros(num_feat)
self.learning_rate = learning_rate
self.max_epoch = max_epoch
self.gibbs_iter = gibbs_iter
self.batch_size = batch_size
self.num_chain = num_chain
def train_batch(self, bin_x_train, bin_x_valid):
rand = lambda dim: np.random.binomial(1, 0.5, dim)
chain = [(rand(self.weight.shape[0]), rand(self.weight.shape[1]))
for _ in range(self.num_chain)]
all_risk = []
all_weight_bias = []
np.random.shuffle(bin_x_train)
lba = float(self.batch_size)
lch = float(len(chain))
for epoch in range(self.max_epoch):
risk_train = self._risk(bin_x_train)
risk_valid = self._risk(bin_x_valid)
print epoch, risk_train, risk_valid
all_risk += [(epoch, risk_train, risk_valid)]
weight_bias = (self.weight.copy(),
self.bias_for.copy(), self.bias_rev.copy())
all_weight_bias += [weight_bias]
for mini_batch in batch(bin_x_train, self.batch_size):
phgx_batch = [sigmoid(inp.dot(self.weight) + self.bias_for)
for inp in mini_batch]
upd_w = sum([np.outer(inp, phgx)
for inp, phgx in zip(mini_batch, phgx_batch)]) / lba
upd_b = sum([phgx for phgx in phgx_batch]) / lba
upd_c = sum([inp for inp in mini_batch]) / lba
for i, neg_samp in enumerate(chain):
chain[i] = self.gibbs_sampler(neg_samp[0], self.gibbs_iter)
upd_w -= sum([np.outer(v, h) for v, h in chain]) / lch
upd_b -= sum([h for _, h in chain]) / lch
upd_c -= sum([v for v, _ in chain]) / lch
self.weight += self.learning_rate * upd_w
self.bias_for += self.learning_rate * upd_b
self.bias_rev += self.learning_rate * upd_c
return all_risk
def gibbs_sampler(self, inp, gibbs_iter):
prob_hgx_inp = sigmoid(inp.dot(self.weight) + self.bias_for)
hid_neg = binomial(1, prob_hgx_inp)
for _ in range(gibbs_iter):
prob_xgh = sigmoid(hid_neg.dot(self.weight.T) + self.bias_rev)
inp_neg = binomial(1, prob_xgh)
prob_hgx = sigmoid(inp_neg.dot(self.weight) + self.bias_for)
hid_neg = binomial(1, prob_hgx)
return (inp_neg, hid_neg)
def _risk(self, bin_x):
loss = 0.0
for n in range(bin_x.shape[0]):
inp = bin_x[n]
(_, hid_neg) = self.gibbs_sampler(inp, gibbs_iter=1)
act = sigmoid(hid_neg.dot(self.weight.T) + self.bias_rev)
loss -= inp.dot(np.log(act)) + (1.0 - inp).dot(np.log(1.0 - act))
return loss / bin_x.shape[0]
<file_sep>
import numpy as np
from numpy.random import binomial
from misc import *
class DBM(object):
def __init__(self, num_feat, num_hid1, num_hid2,
learning_rate=0.01, max_epoch=200, batch_size=10,
gibbs_iter=1, num_chain=100, num_upd_mu=10):
self.num_feat = num_feat
self.num_hid1 = num_hid1
self.num_hid2 = num_hid2
self.weight1 = init_weight(num_feat, num_hid1)
self.weight2 = init_weight(num_hid1, num_hid2)
self.bias_inp = np.zeros(num_feat)
self.bias_hid1 = np.zeros(num_hid1)
self.bias_hid2 = np.zeros(num_hid2)
self.learning_rate = learning_rate
self.max_epoch = max_epoch
self.batch_size = batch_size
self.gibbs_iter = gibbs_iter
self.num_chain = num_chain
self.num_upd_mu = num_upd_mu
def train_batch(self, bin_x_train, bin_x_valid):
bin_x_train = bin_x_train.copy()
rand = lambda dim: np.random.binomial(1, 0.5, dim)
chain = [(rand(self.num_feat), rand(self.num_hid1), rand(self.num_hid2))
for _ in range(self.num_chain)]
all_risk = []
for epoch in range(self.max_epoch):
risk_train = self._risk(bin_x_train)
risk_valid = self._risk(bin_x_valid)
print epoch, risk_train, risk_valid
all_risk += [(epoch, risk_train, risk_valid)]
np.random.shuffle(bin_x_train)
for mini_batch in batch(bin_x_train, self.batch_size):
mu_list = [self._get_mu(inp) for inp in mini_batch]
for ind, sample in enumerate(chain):
chain[ind] = self.gibbs_sampler(sample, self.gibbs_iter)
lba = float(len(mini_batch))
lch = float(len(chain))
zl = zip(mini_batch, mu_list)
dir_w1 = sum([np.outer(inp, mu1) for inp, (mu1, _) in zl]) / lba
dir_w1 -= sum([np.outer(sv, sh1) for sv, sh1, _ in chain]) / lch
dir_bh1 = sum([mu1 for mu1, _ in mu_list]) / lba
dir_bh1 -= sum([h1 for _, h1, _ in chain]) / lch
dir_w2 = sum([np.outer(mu1, mu2) for mu1, mu2 in mu_list]) / lba
dir_w2 -= sum([np.outer(h1, h2) for _, h1, h2 in chain]) / lch
dir_bh2 = sum([mu2 for _, mu2 in mu_list]) / lba
dir_bh2 -= sum([h2 for _, _, h2 in chain]) / lch
dir_bi = sum([inp for inp in mini_batch]) / lba
dir_bi -= sum([v for v, _, _ in chain]) / lch
self.bias_inp += self.learning_rate * dir_bi
self.weight1 += self.learning_rate * dir_w1
self.bias_hid1 += self.learning_rate * dir_bh1
self.weight2 += self.learning_rate * dir_w2
self.bias_hid2 += self.learning_rate * dir_bh2
return all_risk
def gibbs_sampler(self, sample, gibbs_iter):
samp_v, samp_h1, samp_h2 = sample
samp_v_neg = samp_v
samp_h2_neg = samp_h2
for _ in range(gibbs_iter):
h1_vh2_term1 = samp_v_neg.dot(self.weight1)
h1_vh2_term2 = self.weight2.dot(samp_h2_neg)
prob_h1_vh2 = sigmoid(h1_vh2_term1 + h1_vh2_term2 + self.bias_hid1)
samp_h1_neg = binomial(1, prob_h1_vh2)
prob_h2_h1 = sigmoid(samp_h1_neg.dot(self.weight2) + self.bias_hid2)
samp_h2_neg = binomial(1, prob_h2_h1)
prob_v_h1 = sigmoid(self.weight1.dot(samp_h1_neg) + self.bias_inp)
samp_v_neg = binomial(1, prob_v_h1)
return samp_v_neg, samp_h1_neg, samp_h2_neg
def _get_mu(self, inp):
mu1 = np.random.rand(self.num_hid1)
mu2 = np.random.rand(self.num_hid2)
for _ in range(self.num_upd_mu):
mu1_term1 = inp.dot(self.weight1)
mu1_term2 = self.weight2.dot(mu2)
mu2_term = mu1.dot(self.weight2)
mu1 = sigmoid(mu1_term1 + mu1_term2 + self.bias_hid1)
mu2 = sigmoid(mu2_term + self.bias_hid2)
return mu1, mu2
def _risk(self, bin_x):
loss = 0.0
for i, inp in enumerate(bin_x):
rand_h2 = np.random.binomial(1, 0.5, self.num_hid2)
sample = (inp, [], rand_h2)
_, samp_h1_neg, _ = self.gibbs_sampler(sample, self.gibbs_iter)
act = sigmoid(self.weight1.dot(samp_h1_neg) + self.bias_inp)
loss -= inp.dot(np.log(act)) + (1.0 - inp).dot(np.log(1.0 - act))
return loss / bin_x.shape[0]
<file_sep>
import numpy as np
def init_weight(num_in, num_out):
max_wt = np.sqrt(6.0 / (num_in + num_out)) * 2
return (np.random.rand(num_in, num_out) - 0.5) * max_wt
def sigmoid(inp):
return np.exp(-np.logaddexp(0, -inp))
def batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
<file_sep>import numpy as np
def read_digits(filename):
with open(filename) as txt:
data = np.loadtxt(txt, delimiter=',')
x_data, y_data = data[:, :-1], data[:, -1]
y_data = np.array([int(y) for y in y_data])
bin_x = 1.0 * (x_data > 0.5)
bin_xy= (bin_x, y_data)
return bin_xy
| 0ba147f2b48c8b212d8299daff902176203370ab | [
"Python"
]
| 10 | Python | spring01/dl_nets | 765e18876b8d95fd5c9c1b4a4847cbebde7fee53 | d9384526c0c08d1f7c116c7c30abd57811ad5164 |
refs/heads/master | <file_sep>import ui.View as View;
import ui.ImageView as ImageView;
exports = Class(View, function (supr) {
this.init = function (opts) {
//Set default width / height
opts = merge(opts, {
width: 91,
height: 91
});
supr(this, 'init', [opts]);
//Add the color BG
this.addSubview(new ImageView({
x: 0,
y: 0,
width: this.style.width,
height: this.style.height,
image: GC.app.imgs.color[opts.colorFrame]
}));
//Add the shape image
this.addSubview(new ImageView({
x: 0,
y: 0,
width: this.style.width,
height: this.style.height,
image: GC.app.imgs.shape[opts.shapeFrame]
}));
};
});
<file_sep># Game Closure Memory Test
This example project is used to test for memory leaks and performance on Game Closure's devkit.
## Usage
The project is simply adding and removing images to the engine's primary view. To adjust the number of tiles being shown on the screen or the interval at which tiles are added and removed, simply adjust the `TILE_LIMIT` and `TIME_INTERVAL` variables in Application.js.
## Methods
Each new tile is class that is extended from the ImageView class. There are 6 colors, and 6 shapes. Each shape and color image is instantiated as an image resource using the ui.resource.image class. Tiles are removed from the scene using the removeFromSuperview method. | 7078990cd5cea2944bc2e308565f28c0a3fad29c | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | presentcreative/gc-memtest | cc5d749b3f3e25248b3695a13b4ea0d5d80de15e | 2eaf16f90ccd89d60da729e3879ba8adee14d3dc |
refs/heads/master | <repo_name>developercyrus/jsf-primefaces-snippets<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jsf-primefaces-snippets</groupId>
<artifactId>jsf-primefaces-snippets</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!--
JSF:
1. Every component should have a id, otherwise JSF will generate for you which is in the following pattern: component1:component2:component3
It might introduct difficult for jquery selector since colon must be escaped.
2. ManagedBean cannot used with a dot for naming, e.g., javaee.jsf.primefaces.example1.input.editor.EditorBean
3. prefix f/h uses components from oracle implementation, and prefix p uses component from primefaces implementation
4 the extension, jsf, xhtml, or faces, are defined in web.xml. In servlet 3.0, there's no longer required web.xml. this project uses servlet 3.1
5. JSF 2 uses Facelets as its default templating system. In contrast, JSF 1.x uses JavaServer Pages (JSP) as its default templating system.
6. Facelets extension is xhtml
7. since url-pattern is defined either as xhtml, faces, jsf in web.xml
either one of them, is valid and can be accessible
http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.faces
http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.jsf
http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.xhtml
http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.jsp
8. The javax.faces.DEFAULT_SUFFIX represents the default suffix of the physical file you've in your webapplication which represents a JSF file.
e.g., if it's set to xhtml, all physical view file must come with extension .xhtml
e.g., if it's set to jsp, all physical view file must come with extension .jsp
JSF 2 comes with the default value of javax.faces.DEFAULT_SUFFIX as .xhtml
Flow:
1. Example1
1. compile as war
2. start jetty at pre-integration-test, and deploy to jetty
3. run integration test
a. use jsoup to get the default value from editor
b. use htmlunit, click submit button, and get the value from result page
-the method ActionListener should be invoked
-get all childs from the form, and get the value from editor
4. stop jetty
5. reference: http://www.primefaces.org/showcase/ui/input/editor.xhtml
Environment:
1. Windows 7 64 bit (assume OS installed in C:\Windows)
2. Eclipse 4.4
3. JDK 8.0
Approach1 - all automate (this project uses this)
1. "mvn clean install"
a) compile
b) start jetty, jetty-maven-plugin:start at pre-integration-test phase
c) run integration test at integration-test phase
d) stop jetty, jetty-maven-plugin:stop at post-integration-test phase
2. while jboss is still running, the server can be manually accessed without using integration test by going to
http://localhost:8080/ejb21-jboss422-snippets-web/HelloWorldLocalClientServlet
Approach2
1. "mvn clean install"
2. "mvn jetty:start"
-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jetty.version>9.0.0.v20130308</jetty.version>
</properties>
<build>
<plugins>
<!-- compile -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.7</source> <!-- java ee comes with jsf 2.2 -->
<target>1.7</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<!-- integration-test -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12</version>
<executions>
<execution>
<id>integration-test</id>
<goals>
<goal>integration-test</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- pre-integration-test -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>${jetty.version}</version>
<configuration>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/jsf-primefaces-snippets</contextPath>
</webApp>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- jsf -->
<dependency>
<groupId>javax.faces</groupId>
<artifactId>javax.faces-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.11</version>
</dependency>
<!--
jsf implmenetation
4.0 or above supports
https://en.wikipedia.org/wiki/PrimeFaces
-->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.2</version>
</dependency>
<!--
javax
http://en.wikipedia.org/wiki/Java_EE_version_history
-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!-- jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.2</version>
</dependency>
<!-- htmlunit, used by example1 -->
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit</artifactId>
<version>2.16</version>
</dependency>
<dependency>
<groupId>net.sourceforge.htmlunit</groupId>
<artifactId>htmlunit-core-js</artifactId>
<version>2.16</version>
</dependency>
</dependencies>
</project><file_sep>/src/main/java/javaee/jsf/primefaces/example1/input/editor/EditorBean.java
package javaee.jsf.primefaces.example1.input.editor;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.event.ActionEvent;
@ManagedBean(name = "EditorBean")
public class EditorBean {
private String value = "Hello World";
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void printId(ActionEvent event){
List<UIComponent> lists = event.getComponent().getParent().getChildren();
for (UIComponent u : lists) {
System.out.println(u.getClientId());
if (u.getClientId().equals("form:editor")) {
System.out.println("by ActionListener: " + u.getAttributes().get("value"));
}
}
}
public String goTo() {
return "result";
}
}
<file_sep>/src/test/java/javaee/jsf/primefaces/example1/input/editor/ClientIT.java
package javaee.jsf.primefaces.example1.input.editor;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
public class ClientIT {
/*
since url-pattern is defined either as xhtml, faces, jsf in web.xml
the url below, either one of them, is valid and can be accessible
*/
//private String url = "http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.jsp";
//private String url = "http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.faces";
//private String url = "http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.jsf";
private String url = "http://localhost:8080/jsf-primefaces-snippets/javaee/jsf/primefaces/example1/input/editor/index.xhtml";
@Test
public void test1() throws Exception {
Document doc = Jsoup.parse(new URL(url), 5000);
/*
if using jquery, the colon can be escaped by "Form\\:Editor"
reference: http://www.mkyong.com/jsf2/primefaces/how-to-get-jsf-id-via-jquery/
*/
Element elements = doc.getElementById("form:editor");
String actual = elements.text();
System.out.println(actual);
}
@Test
public void test2() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(true);
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getCookieManager().setCookiesEnabled(true);
HtmlPage indexPage = webClient.getPage(url);
HtmlSubmitInput submitButton = (HtmlSubmitInput)indexPage.getElementByName("form:submitButton1");
HtmlPage resultPage = submitButton.click();
String actual = resultPage.getElementById("result").asText();
assertEquals("Hello World", actual);
webClient.close();
}
}
| b54151ef5890987a7dd9638b1f954094e87c373b | [
"Java",
"Maven POM"
]
| 3 | Maven POM | developercyrus/jsf-primefaces-snippets | 337e943e773c9f5b82c49540b2a9b2365a01c555 | 58782ebccb01fb346bfed2c1ecc6443a76453241 |
refs/heads/master | <file_sep>from sklearn.neural_network import MLPClassifier
from sklearn import datasets
iris = datasets.load_iris()
entradas = iris.data
saidas = iris.target
redeNeural = MLPClassifier(verbose=True,
max_iter=1000)
redeNeural.fit(entradas, saidas)
redeNeural.predict([[5, 7.2, 5.1, 2.2]])<file_sep># Machine Learning
Repositório destinado ao aprendizado² (aprendizado em apredizado ba dum tss) de máquina<file_sep>import numpy as np
entradas = np.array([1, 7, 5])
pesos = np.array([0.8, 0.1, 0])
def soma (e, p):
return e.dot(p)
def step(soma):
return 1 if soma >=1 else 0
s = soma(entradas, pesos)
r = step(s)
print(r)<file_sep>## Perceptron
Só consegue encontrar soluções pra problemas linearmente separáveis. O XOR por exemplo foge esta regra.
### Fórmula pra se obter os erros
resposta esperada - resposta obtida
### Fórmula para se obter os pesos
Peso(n+1) = peso(n) + (Taxa de aprendizagem * entrada(n) * erro)
### Várias funções de ativação com gráficos
https://en.wikipedia.org/wiki/Activation_function<file_sep>import numpy as np
# AND
entradas = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
saidas = np.array([0, 0, 0, 1])
# OR
entradas = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
saidas = np.array([0, 1, 1, 1])
pesos = np.array([0.0, 0.0])
taxaAprendizagem = 0.1
def step(soma):
return 1 if soma >=1 else 0
def calculaSaida(registro):
s = registro.dot(pesos)
return step(s)
def treinar():
erroTotal = 1
while (erroTotal != 0):
erroTotal = 0
for i in range(len(saidas)):
saidaCalculada = calculaSaida(np.array(entradas[i]))
erro = abs(saidas[i] - saidaCalculada)
erroTotal += erro
for j in range(len(pesos)):
pesos[j] = pesos[j] + (taxaAprendizagem * entradas[i][j] * erro)
print('Peso atualizado: ' + str(pesos[j]))
print('Total de erros: ' + str(erroTotal))
treinar(); | 16cfd42c82afa08049e2c6ccc280e190280429ef | [
"Markdown",
"Python"
]
| 5 | Python | HigorC/machineLearning | 83d418b27f43a5d99861f7b4fb130619a088152d | 10691ef4fd875945a211acb658d8ad56280ff4e6 |
refs/heads/master | <file_sep>#Retrive input from user
puts "What units for domain are you using?(singular)"
domainUnits = gets.to_s
puts "What is the input file directory?(end with .csv)"
inputDirectory = gets.to_s.chomp
puts "What would you like the output directory to be called(end with a .dat)?"
outputDirectory = gets.to_s.chomp
#Retrive input from file
f = File.new(inputDirectory, "r")
input = f.readlines
#Seperate the arrays
input = input.map {|input| input.chomp}
stats = input.collect do |split|
split = split.split(",")
split[1].to_i
end
year = input.collect do |year|
year = year.split(",")
year[0].to_s
end
#Close file
f.close
#Calculate the mean
sum = stats.inject{|sum,x| sum + x }
statsLength = stats.length
mean = sum / statsLength
#Calculate the standard deviation
difference = stats.collect do |difference|
multipleDifferences = difference - mean
differenceSquared = multipleDifferences ** 2
end
sumOfDifferencesSquared = difference.inject{|sumOfDifferencesSquared,x| sumOfDifferencesSquared + x }
variance = sumOfDifferencesSquared / statsLength
standardDeviation = (variance ** 0.5).to_f
#Open Create and clear the output file
f = File.new("#{outputDirectory}", "a+")
f.close
f = File.new("#{outputDirectory}", "w")
f.puts ""
f.close
#Open the utput file as an append plus
f = File.new("#{outputDirectory}", "a+")
#Calculate and output z-scores and years
yearTest = 0
zScore = stats.each do |zScore|
zScores = (zScore - mean)/standardDeviation
puts "Z-score of the year #{year[yearTest]}, is: #{zScores.round(5)}"
f.puts "Z-score of the year #{year[yearTest]}, is: #{zScores.round(5)}"
yearTest = yearTest + 1
end
#Calculate and output the mean, mode, range, and median
puts "The mean is: #{mean}."
f.puts "The mean is: #{mean}."
freq = stats.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
mode = stats.max_by { |v| freq[v] }
puts "The mode is: #{mode}."
f.puts "The mode is: #{mode}."
statsOrder = stats.sort
range = (statsOrder[(statsLength - 1)] - statsOrder[0])
puts "The range is: #{range}."
f.puts "The range is: #{range}."
statsMedian = statsOrder
while statsMedian.length > 2
statsMedian.pop
statsMedian.shift
end
if statsMedian == 2
median = (statsMedian[0] + statsMedian[1])/2
else
median = statsMedian[0]
end
puts "The median is: #{median}."
f.puts "The median is: #{median}."
#Close the file
f.close
| 590f97fd00e97001ef0963e2dc7b7ff68d7e838b | [
"Ruby"
]
| 1 | Ruby | lukepsauer/statisticslab | 9166882ff07d030f140b616a84c58db4d6cf622e | 46ac117868853f9b3addbbecb93906361071b4cd |
refs/heads/master | <repo_name>zoomie/concurrent_goland_api<file_sep>/README.md
# Go API
All the action is in the app.go
I know that it's a bit silly to access a Redis Database though an http connection as the speed gained from using RAM memory is lost by networking bandwidth. My reason is that I wanted to learn how Redis worked with Go and how Go's http package uses concurrency.
```
ab -n 10000 -c 20 "http://localhost:5000/SetValue?key=key1&value=value1"
```
```
This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 <NAME>, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 1000 requests
Completed 2000 requests
Completed 3000 requests
Completed 4000 requests
Completed 5000 requests
Completed 6000 requests
Completed 7000 requests
Completed 8000 requests
Completed 9000 requests
Completed 10000 requests
Finished 10000 requests
Server Software:
Server Hostname: localhost
Server Port: 5000
Document Path: /SetValue?key=key1&value=value1
Document Length: 4 bytes
Concurrency Level: 20
Time taken for tests: 3.137 seconds
Complete requests: 10000
Failed requests: 0
Total transferred: 1200000 bytes
HTML transferred: 40000 bytes
Requests per second: 3188.13 [#/sec] (mean)
Time per request: 6.273 [ms] (mean)
Time per request: 0.314 [ms] (mean, across all concurrent requests)
Transfer rate: 373.61 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 2 7.8 2 553
Processing: 0 4 22.7 3 553
Waiting: 0 3 20.6 2 551
Total: 1 6 24.0 5 555
Percentage of the requests served within a certain time (ms)
50% 5
66% 5
75% 6
80% 6
90% 7
95% 7
98% 8
99% 8
100% 555 (longest request)
```
<file_sep>/app.go
package main
import (
"fmt"
"net/http"
"sync"
"github.com/go-redis/redis"
)
var wg sync.WaitGroup
type RedisDB struct {
Addr string
Password string
DB int
conn *redis.Client
}
func (r *RedisDB) MakeConnection() {
r.conn = redis.NewClient(&redis.Options{
Addr: r.Addr,
Password: r.Password, // no password set
DB: r.DB, // use default DB
})
}
func (r *RedisDB) Test() {
pong, err := r.conn.Ping().Result()
fmt.Println(pong, err)
}
func (r *RedisDB) SetValue(key string, num string) {
// defer wg.Done()
err := r.conn.Set(key, num, 0).Err()
if err != nil {
panic(err)
}
}
func (r *RedisDB) GetValue(key string) string {
val, err := r.conn.Get(key).Result()
if err != nil {
panic(err)
}
return val
}
func InputValue(db *RedisDB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.FormValue("key")
value := r.FormValue("value")
// wg.Add(1)
go db.SetValue(key, value)
fmt.Fprintf(w, "done")
}
}
func ExtracValue(db *RedisDB) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
key := r.FormValue("key")
value := db.GetValue(key)
fmt.Fprintf(w, value)
}
}
func main() {
database := RedisDB{Addr:"localhost:6379", Password:"", DB:0}
database.MakeConnection()
database.Test()
handleInput := InputValue(&database)
handleOutput := ExtracValue(&database)
http.HandleFunc("/SetValue", handleInput)
http.HandleFunc("/GetValue", handleOutput)
http.ListenAndServe(":5000", nil)
}
<file_sep>/foo.go
package main
import (
"encoding/json"
"net/http"
"sync"
)
type MyStruct struct {
A, B, Total int64
}
func (s *MyStruct) add() {
s.Total = s.A + s.B
}
func process(w http.ResponseWriter, cr chan *http.Request) {
r := <- cr
var s MyStruct
json.NewDecoder(r.Body).Decode(&s)
s.add()
json.NewEncoder(w).Encode(s)
}
func handler(w http.ResponseWriter, r *http.Request) {
cr := make(chan *http.Request, 1)
cr <- r
var pleasewait sync.WaitGroup
pleasewait.Add(1)
go func() {
defer pleasewait.Done()
process(w, cr) // doesn't work; no response :-(
}()
// process(w, cr) // works, but blank response :-(
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":5000", nil)
}<file_sep>/sec.go
package main
import "fmt"
type Redis struct {
conn string
}
func (r *Redis) Put(input string, c chan int) {
r.conn = input
c <- 0
}
func main() {
channel := make(chan int)
r := Redis{"test string"}
fmt.Println(r)
go r.Put("new string", channel)
<-channel
fmt.Println(r)
// fmt.Println("test")
}<file_sep>/summer.go
// package main
// import (
// "fmt"
// "sync"
// "github.com/go-redis/redis"
// )
// var wg sync.WaitGroup
// type RedisDB struct {
// Addr string
// Password string
// DB int
// conn *redis.Client
// }
// func (r *RedisDB) MakeConnection() {
// r.conn = redis.NewClient(&redis.Options{
// Addr: r.Addr,
// Password: r.Password, // no password set
// DB: r.DB, // use default DB
// })
// }
// func (r *RedisDB) Test() {
// defer wg.Done()
// pong, err := r.conn.Ping().Result()
// fmt.Println(pong, err)
// }
// func (r *RedisDB) SetValue(key string, num string) {
// err := r.conn.Set(key, num, 0).Err()
// if err != nil {
// panic(err)
// }
// }
// func (r *RedisDB) GetValue(key string) string {
// val, err := r.conn.Get(key).Result()
// if err != nil {
// panic(err)
// }
// return val
// }
// func p(words string) {
// defer wg.Done()
// fmt.Println(words)
// }
// func main() {
// database := RedisDB{Addr:"localhost:6379", Password:"", DB:0}
// database.MakeConnection()
// for i:=0;i<100000;i++ {
// wg.Add(1)
// go database.Test()
// }
// wg.Wait()
// fmt.Println("done")
// } | 266891afe4bc7c03c9e29c42d3d61cb79b087a18 | [
"Markdown",
"Go"
]
| 5 | Markdown | zoomie/concurrent_goland_api | 870101b65d3b7dae052b2f0587496258e156abf2 | 5b9d99aa0da84b9fd061e68c11faf8655de62d47 |
refs/heads/master | <file_sep>
[<-이전기록보기](https://github.com/whydda/zuuladdressproxy/blob/master/README.md)
# ZUUL을 이용한 proxy서버 규현 #1
## RIBBON(Load Balancer)을 이용하여 서버 URI에 따라서 http://www.juso.go.kr 또는 http://openapi.molit.go.kr/를 통한 API 호출을 분기 처리
> - RIBBON dependency 추가
> - request url
> - response
## 참고사이트
[참고(https://supawer0728.github.io)](https://supawer0728.github.io/2018/03/11/Spring-Cloud-Zuul/)
[참고(https://supawer0728.github.io)](https://supawer0728.github.io/2018/03/11/Spring-Cloud-Ribbon%EA%B3%BC-Eureka/)
<file_sep>package com.whydda.address.zuulproxy;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SIMPLE_HOST_ROUTING_FILTER_ORDER;
@Slf4j
public class AddressHttpRoutingFilter extends ZuulFilter {
@Override
public String filterType() {
return ROUTE_TYPE;
}
@Override
public int filterOrder() {
return SIMPLE_HOST_ROUTING_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
return null;
}
}
<file_sep># ZUUL을 이용한 proxy서버 구현
## **사용법**
> - http://www.juso.go.kr 에서 API 인증키 발급 받고 application.properties에 **whydda.address.confmkey** 프로퍼티 등록
> - properties 내용 (다른 서버로 설정도 가능하다.)
zuul.routes.products.path = /addrlink/addrLinkApi.do
zuul.routes.products.url = http://www.juso.go.kr/
server.port = 8111
> - test url
url : http://localhost:8111/addrlink/addrLinkApi.do
method : POST
currentPage:1
countPerPage:20
keyword:노해로508
resultType:json
> - key는 zuulserver에 존재함으로 제외하고 요청을 보낸다.
{
"results": {
"common": {
"errorMessage": "정상",
"countPerPage": "20",
"totalCount": "1",
"errorCode": "0",
"currentPage": "1"
},
"juso": [
{
"detBdNmList": "603동,604동,605동,606동,607동,608동,609동,610동,611동,612동,613동,614동,615동,616동,617동,618동,619동,620동,621동,622동,623동,624동,625동,626동,627동,628동,6단지 관리동",
"engAddr": "508, Nohae-ro, Nowon-gu, Seoul",
"rn": "노해로",
"emdNm": "상계동",
"zipNo": "01752",
"roadAddrPart2": " (상계동, 상계주공6단지아파트)",
"emdNo": "01",
"sggNm": "노원구",
"jibunAddr": "서울특별시 노원구 상계동 720 상계주공6단지아파트",
"siNm": "서울특별시",
"roadAddrPart1": "서울특별시 노원구 노해로 508",
"bdNm": "상계주공6단지아파트",
"admCd": "1135010500",
"udrtYn": "0",
"lnbrMnnm": "720",
"roadAddr": "서울특별시 노원구 노해로 508 (상계동, 상계주공6단지아파트)",
"lnbrSlno": "0",
"buldMnnm": "508",
"bdKdcd": "1",
"liNm": "",
"rnMgtSn": "113503005047",
"mtYn": "0",
"bdMgtSn": "1135010500107200000000764",
"buldSlno": "0"
}
]
}
}
> 응답 결과를 받을 수 있다.
---
[다음기록보기->](https://github.com/whydda/zuuladdressproxy/blob/master/README_1.md)
<file_sep>spring.application.name = zuulserver
zuul.ignored-services=*
zuul.routes.products.path = /addrlink/addrLinkApi.do
zuul.routes.products.url = http://www.juso.go.kr/
server.port = 8111
whydda.address.confmkey=key
| 1b1a9e6ef8dc7f0aa5e7377c8e73922c107ff3f1 | [
"Markdown",
"Java",
"INI"
]
| 4 | Markdown | whydda/zuuladdressproxy | 6c58284650112fb380cc55e981c2ad2e246ae59f | c6a318c982352b0f3afd4f4a95f4782a146445d0 |
refs/heads/main | <repo_name>sunlibo111111/core_Sample<file_sep>/V7/Program.cs
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
//public static void CallToChildThread()
//{
// Console.WriteLine("Child thread starts");
//}
//static void Main(string[] args)
//{
// ThreadStart childref = new ThreadStart(CallToChildThread);
// Console.WriteLine("In Main: Creating the Child thread");
// Thread childThread = new Thread(childref);
// childThread.Start();
// Console.ReadKey();
//}
//public static void CallToChildThread()
//{
// Console.WriteLine("Child thread starts");
// // 线程暂停 5000 毫秒
// int sleepfor = 5000;
// Console.WriteLine("Child Thread Paused for {0} seconds",
// sleepfor / 1000);
// Thread.Sleep(sleepfor);
// Console.WriteLine("Child thread resumes");
//}
//static void Main(string[] args)
//{
// ThreadStart childref = new ThreadStart(CallToChildThread);
// Console.WriteLine("In Main: Creating the Child thread");
// Thread childThread = new Thread(childref);
// childThread.Start();
// Console.ReadKey();
//}
// public static void CallToChildThread()
// {
// try
// {
// Console.WriteLine("Child thread starts");
// // 计数到 10
// for (int counter = 0; counter <= 10; counter++)
// {
// Thread.Sleep(500);
// Console.WriteLine(counter);
// }
// Console.WriteLine("Child Thread Completed");
// }
// catch (ThreadAbortException e)
// {
// Console.WriteLine("Thread Abort Exception");
// }
// finally
// {
// Console.WriteLine("Couldn't catch the Thread Exception");
// }
// }
//static void Main(string[] args)
//{
// ThreadStart childref = new ThreadStart(CallToChildThread);
// Console.WriteLine("In Main: Creating the Child thread");
// Thread childThread = new Thread(childref);
// childThread.Start();
// // 停止主线程一段时间
// Thread.Sleep(2000);
// // 现在中止子线程
// Console.WriteLine("In Main: Aborting the Child thread");
// childThread.Abort();
// Console.ReadKey();
//}
}
}<file_sep>/Jobject/Program.cs
using Newtonsoft.Json.Linq;
using System;
namespace Jobject
{
public class Program
{
static void Main(string[] args)
{
//var obj = new JObject { { "Name", "Lucy" } };
//var company = new JObject { { "Cmp", "上海网络有限公司" }, { "Tel", "0112-1263589" } };
//obj.Add("Company", company);
//Console.WriteLine(obj);
////解读:创建一个json对象,有2个字段Name,Company其中Company是一个对象
//var jarray = new JArray();
//var lucy = new JObject { { "Name", "Lucy" }, { "Age", 18 } };
//var tom = new JObject { { "Name", "Tom" }, { "Age", 20 } };
//jarray.Add(lucy);
//jarray.Add(tom);
//Console.WriteLine(jarray);
////解读:创建了一个json数组,包括了2个对象:每个对象都有2个字段:Name,Age
//var obj = new JObject();
//var student = new JArray
//{
//new JObject {{ "Name", "Lucy" }, { "Age", 18 } },
//new JObject {{ "Name", "Tom" }, { "Age", 20 } }
// };
//var study = new JArray
//{
//new JObject {{ "Subject", "语文"}, { "Score", 100}},
//new JObject {{ "Subject", "数学" }, { "Score", 88}}
// };
//obj.Add("Student", student);
//obj.Add("Study", study);
//Console.WriteLine(obj);
//////解读:json对象有2个数组:Student,Study。数组分别有两个对象
var lucy = new JObject { { "Name", "Lucy" }, { "Age", 18 } };
var study = new JArray
{
new JObject {{ "Subject", "语文"}, { "Score", 100}},
new JObject {{ "Subject", "数学" }, { "Score", 88}}
};
lucy.Add("Study", study);
Console.WriteLine(lucy);
}
// 解读:json对象的study字段是一个数组
}
}
<file_sep>/V5/Program.cs
using System;
namespace SimpleEvent
{
using System;
/***********发布器类***********/
public class EventTest
{
private int value;
public delegate void NumManipulationHandler();
public event NumManipulationHandler ChangeNum;
protected virtual void OnNumChanged()
{
if (ChangeNum != null)
{
ChangeNum(); /* 事件被触发 */
}
else
{
Console.WriteLine("event not fire");
Console.ReadKey(); /* 回车继续 */
}
}
public EventTest()
{
int n = 5;
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
/***********订阅器类***********/
public class subscribEvent
{
public void printf()
{
Console.WriteLine("event fire");
Console.ReadKey(); /* 回车继续 */
}
}
/***********触发***********/
public class MainClass
{
public static void Main()
{
EventTest e = new EventTest(); /* 实例化对象,第一次没有触发事件 */
subscribEvent v = new subscribEvent(); /* 实例化对象 */
e.ChangeNum += new EventTest.NumManipulationHandler(v.printf); /* 注册 */
e.SetValue(7);
e.SetValue(11);
}
}
}<file_sep>/V2/Program.cs
using System;
namespace V2
{
class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
System.Console.WriteLine(attributes[i]);
}
Console.ReadKey();
}
}
}
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic // Topic 是一个命名(named)参数
{
get
{
return topic;
}
set
{
topic = value;
}
}
public HelpAttribute(string url) // url 是一个定位(positional)参数
{
this.Url = url;
}
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}
| c4b10c4e525d4945290cddd7ff203a4f307db671 | [
"C#"
]
| 4 | C# | sunlibo111111/core_Sample | d59e6a5ac9d5d5ff72201b83cebb338cad34a222 | 015026dc8dbbf0d6ca6ffd3495fa44b6cd4319f2 |
refs/heads/master | <repo_name>Feroz0408/Kroger-round2<file_sep>/src/components/category-details/CategoryDetails.jsx
import React from 'react';
import './CategoryDetails.css';
const CategoryDetails = props => {
return (
<div className={!props.categoryDetails.length > 0 ? 'hide' : 'show'}>
<h3> Items in Category: ({props.shortName})</h3>
<table id="details">
<tbody>
<tr>
<th className="table-head">Name</th>
<th>Description</th>
</tr>
{props.categoryDetails.map(details => {
return (
<tr key={details.id}>
<td>{details.name}</td>
<td>{!!details.description ? details.description : 'N/A'}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default CategoryDetails;
<file_sep>/src/components/category-list/CategoryList.js
import React, { Component, Fragment } from 'react';
import './CategoryList.css';
import CategoryDetails from '../category-details/CategoryDetails';
import { getAllCategories, getCategorDetails } from '../../api/Api';
import spinner from '../../images/spinner.gif';
class CategoryList extends Component {
constructor() {
super();
this.state = {
categoryList: [],
categoryDetails: [],
isLoading: false,
shortName: ''
};
}
async componentDidMount() {
try {
this.setState({ isLoading: true });
await getAllCategories()
.then(res => res.json())
.then(data => {
this.setState({ categoryList: data, isLoading: false });
});
} catch (err) {
console.error(err.message);
}
}
async fetchCategoryDetails(short_name) {
if (short_name !== this.state.shortName) {
try {
this.setState({ isLoading: true });
await getCategorDetails(short_name)
.then(res => res.json())
.then(data => {
this.setState({
categoryDetails: data,
shortName: short_name,
isLoading: false
});
});
} catch (err) {
console.error(err.message);
}
}
}
render() {
if (this.state.isLoading) {
return (
<div className={this.state.isLoading ? 'spinner' : 'hide'}>
<img src={spinner} alt="loading" title="spinner" />
</div>
);
}
return (
<Fragment>
<h2>Menu Categories</h2>
<div className="container">
<div className="category-list">
{this.state.categoryList.map(category => {
return (
<div
className="list-item"
key={category.id}
onClick={() => this.fetchCategoryDetails(category.short_name)}
>
{category.name} - ({category.short_name})
</div>
);
})}
</div>
<CategoryDetails
categoryDetails={this.state.categoryDetails}
shortName={this.state.shortName}
/>
</div>
</Fragment>
);
}
}
export default CategoryList;
| 321f5882823e67e197c34cae69f34fc54e8bc9d0 | [
"JavaScript"
]
| 2 | JavaScript | Feroz0408/Kroger-round2 | 62024833e18e54d508fe1b9ccf491f989eb40fc9 | 585ac90cff57b15b559056b51470ab6fedc8f240 |
refs/heads/master | <repo_name>KamilaKautzmann/TrabalhoFinal_Genio<file_sep>/src/Genio/Arvore.java
package Genio;
import java.util.Scanner;
public class Arvore {
public Nodo raiz;
// metodo que recebe o valor do usuario e chama o inserir.
public void inserirUm(int valor, String pergunta) {
inserir(raiz, valor, pergunta);
}
public void inserir(Nodo no, int valor, String pergunta) {
// verifica se a arvore esta vazia se sim valor informado vai ser a raiz
if (no == null) {
raiz = new Nodo(valor, pergunta);// recebe o construtor do nó
//System.out.println("O valor da raiz é " + valor + pergunta);
} // final do primeiro if
else {
// Se valor for menor
if (valor < no.getValor()) { // se for menor insere a esquerda
if (no.getEsquerda() != null) { // se o no estiver preenchido
inserir(no.esquerda, valor, pergunta); // volta a percorrer o metodo recursivamente
} else { // se o valor a esquerda for vazio
//System.out.println("Inserido " + valor + " a esquerda de " + no.valor+ " " + pergunta); // insere o valor a esquerda do valor anterior
no.esquerda = new Nodo(valor, pergunta);
}//final do primeiro else
}//final do valor menor que o nó
else { // se o valor for maior
if (no.getDireita() != null) { // se o nó a direita estiver preenchido
inserir(no.direita, valor, pergunta); // exeuta o metodo recursido ate encontrar onde estiver nulo
} else {
//System.out.println("Inserido "+ valor + " a direita de " + no.valor + " "+ pergunta); // insere o valor a direita do valor anterior
no.direita = new Nodo(valor, pergunta);
}//final do else dentro do else
}//final do segundo else
}
}// final do inserir
public void percorrer(){
this.raiz.percorrerNodo();
}
}// final da classe arvore
<file_sep>/src/Genio/Genio.java
package Genio;
import java.util.Scanner;
public class Genio {
static Arvore arvore = new Arvore();
public static void main(String[] args) {
System.out.println("Genio Animal " + "\n" );
System.out.println("O objetivo do jogo é através de perguntas adivinhar o animal escolhido. \n \n" +
"........................................................................ \n");
System.out.println("Pense em um animal da lista abaixo: \n");
System.out.println("Gato" + "\n" + "Cachorro" + "\n" + "Passarinho" + "\n" +
"Tartaruga" + "\n" + "Peixe" + "\n" + "Leão" + "\n" + "Elefante" + "\n" + "Girafa" + "\n" + "Tigre" + "\n" + "Jacaré" + "\n" + "Baleia" + "\n");
inserirMain();
arvore.percorrer();
}// final do main
public static void inserirMain(){
arvore.inserirUm(50, "Seu animal é comum ter em residencias?");
arvore.inserirUm(40, "Seu animal vive na agua?");
arvore.inserirUm(60, "Seu animal é um felino?");
arvore.inserirUm(38, "Seu animal consegue ficar um pouco fora d'agua?");
arvore.inserirUm(43, "Seu animal voa?" );
arvore.inserirUm(45, "Seu animal saltita?");
arvore.inserirUm(47, "Seu animal mia");
arvore.inserirUm(58, "Seu animal tem juba?");
arvore.inserirUm(65, "Seu animal é muito pesado?");
arvore.inserirUm(63, "Seu animal tem tromba?");
arvore.inserirUm(71, "Seu animal tem pescoço muito grande?");
arvore.inserirUm(37, "Tartaruga");
arvore.inserirUm(39, "Peixe");
arvore.inserirUm(41, "Passarinho");
arvore.inserirUm(44, "Coelho");
arvore.inserirUm(46, "Gato");
arvore.inserirUm(48, "Cachorro");
arvore.inserirUm(57, "Leao");
arvore.inserirUm(59, "Tigre");
arvore.inserirUm(62, "Elefante");
arvore.inserirUm(64, "Baleia");
arvore.inserirUm(70, "Girafa");
arvore.inserirUm(72, "Jacaré");
}
}
| ac27417ecf56fce0a8d0f5d4b13262be2614f074 | [
"Java"
]
| 2 | Java | KamilaKautzmann/TrabalhoFinal_Genio | bdebbaccbf43b436bfffa81cb5aaa62521915033 | 8f812398c7386f1156880f1c309d0c5ad23c7d56 |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'merge_image.ui'
##
## Created by: Qt User Interface Compiler version 6.4.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QCheckBox, QDialog, QDoubleSpinBox,
QGraphicsView, QGridLayout, QGroupBox, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QSizePolicy,
QSpinBox, QWidget)
class Ui_Merge(object):
def setupUi(self, Merge):
if not Merge.objectName():
Merge.setObjectName(u"Merge")
Merge.resize(958, 667)
self.groupBox = QGroupBox(Merge)
self.groupBox.setObjectName(u"groupBox")
self.groupBox.setGeometry(QRect(40, 50, 91, 51))
self.gridLayoutWidget = QWidget(Merge)
self.gridLayoutWidget.setObjectName(u"gridLayoutWidget")
self.gridLayoutWidget.setGeometry(QRect(40, 110, 241, 186))
self.gridLayout = QGridLayout(self.gridLayoutWidget)
self.gridLayout.setObjectName(u"gridLayout")
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.label = QLabel(self.gridLayoutWidget)
self.label.setObjectName(u"label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.label_2 = QLabel(self.gridLayoutWidget)
self.label_2.setObjectName(u"label_2")
self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
self.label_4 = QLabel(self.gridLayoutWidget)
self.label_4.setObjectName(u"label_4")
self.gridLayout.addWidget(self.label_4, 5, 0, 1, 1)
self.label_3 = QLabel(self.gridLayoutWidget)
self.label_3.setObjectName(u"label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 1)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.back_pos_w = QLineEdit(self.gridLayoutWidget)
self.back_pos_w.setObjectName(u"back_pos_w")
self.horizontalLayout_2.addWidget(self.back_pos_w)
self.back_pos_h = QLineEdit(self.gridLayoutWidget)
self.back_pos_h.setObjectName(u"back_pos_h")
self.horizontalLayout_2.addWidget(self.back_pos_h)
self.gridLayout.addLayout(self.horizontalLayout_2, 5, 1, 1, 1)
self.back_path = QLineEdit(self.gridLayoutWidget)
self.back_path.setObjectName(u"back_path")
self.gridLayout.addWidget(self.back_path, 0, 1, 1, 1)
self.back_padding = QCheckBox(self.gridLayoutWidget)
self.back_padding.setObjectName(u"back_padding")
self.gridLayout.addWidget(self.back_padding, 1, 1, 1, 1)
self.fore_alpha = QDoubleSpinBox(self.gridLayoutWidget)
self.fore_alpha.setObjectName(u"fore_alpha")
self.fore_alpha.setMaximum(1.000000000000000)
self.fore_alpha.setSingleStep(0.100000000000000)
self.fore_alpha.setValue(0.000000000000000)
self.gridLayout.addWidget(self.fore_alpha, 4, 1, 1, 1)
self.label_5 = QLabel(self.gridLayoutWidget)
self.label_5.setObjectName(u"label_5")
self.gridLayout.addWidget(self.label_5, 6, 0, 1, 1)
self.label_6 = QLabel(self.gridLayoutWidget)
self.label_6.setObjectName(u"label_6")
self.gridLayout.addWidget(self.label_6, 1, 0, 1, 1)
self.fore_path = QLineEdit(self.gridLayoutWidget)
self.fore_path.setObjectName(u"fore_path")
self.gridLayout.addWidget(self.fore_path, 3, 1, 1, 1)
self.fore_factor = QDoubleSpinBox(self.gridLayoutWidget)
self.fore_factor.setObjectName(u"fore_factor")
self.fore_factor.setMinimum(0.010000000000000)
self.fore_factor.setMaximum(99.000000000000000)
self.fore_factor.setSingleStep(0.100000000000000)
self.fore_factor.setValue(1.000000000000000)
self.gridLayout.addWidget(self.fore_factor, 6, 1, 1, 1)
self.label_15 = QLabel(self.gridLayoutWidget)
self.label_15.setObjectName(u"label_15")
self.gridLayout.addWidget(self.label_15, 7, 0, 1, 1)
self.single_save_image = QLineEdit(self.gridLayoutWidget)
self.single_save_image.setObjectName(u"single_save_image")
self.gridLayout.addWidget(self.single_save_image, 7, 1, 1, 1)
self.back_view = QGraphicsView(Merge)
self.back_view.setObjectName(u"back_view")
self.back_view.setGeometry(QRect(330, 30, 281, 251))
self.label_7 = QLabel(Merge)
self.label_7.setObjectName(u"label_7")
self.label_7.setGeometry(QRect(470, 290, 53, 16))
self.label_8 = QLabel(Merge)
self.label_8.setObjectName(u"label_8")
self.label_8.setGeometry(QRect(660, 290, 53, 16))
self.fore_view = QGraphicsView(Merge)
self.fore_view.setObjectName(u"fore_view")
self.fore_view.setGeometry(QRect(640, 30, 281, 251))
self.merge_view = QGraphicsView(Merge)
self.merge_view.setObjectName(u"merge_view")
self.merge_view.setGeometry(QRect(330, 310, 301, 261))
self.label_9 = QLabel(Merge)
self.label_9.setObjectName(u"label_9")
self.label_9.setGeometry(QRect(440, 590, 53, 16))
self.show_images = QPushButton(Merge)
self.show_images.setObjectName(u"show_images")
self.show_images.setGeometry(QRect(40, 300, 75, 24))
self.merge_images = QPushButton(Merge)
self.merge_images.setObjectName(u"merge_images")
self.merge_images.setGeometry(QRect(130, 300, 75, 24))
self.gridLayoutWidget_2 = QWidget(Merge)
self.gridLayoutWidget_2.setObjectName(u"gridLayoutWidget_2")
self.gridLayoutWidget_2.setGeometry(QRect(40, 330, 241, 218))
self.gridLayout_2 = QGridLayout(self.gridLayoutWidget_2)
self.gridLayout_2.setObjectName(u"gridLayout_2")
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.fore_dir = QLineEdit(self.gridLayoutWidget_2)
self.fore_dir.setObjectName(u"fore_dir")
self.gridLayout_2.addWidget(self.fore_dir, 3, 1, 1, 1)
self.horizontalLayout_4 = QHBoxLayout()
self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
self.fore_factors_l = QLineEdit(self.gridLayoutWidget_2)
self.fore_factors_l.setObjectName(u"fore_factors_l")
self.horizontalLayout_4.addWidget(self.fore_factors_l)
self.fore_factors_r = QLineEdit(self.gridLayoutWidget_2)
self.fore_factors_r.setObjectName(u"fore_factors_r")
self.horizontalLayout_4.addWidget(self.fore_factors_r)
self.gridLayout_2.addLayout(self.horizontalLayout_4, 8, 1, 1, 1)
self.label_17 = QLabel(self.gridLayoutWidget_2)
self.label_17.setObjectName(u"label_17")
self.gridLayout_2.addWidget(self.label_17, 4, 0, 1, 1)
self.label_13 = QLabel(self.gridLayoutWidget_2)
self.label_13.setObjectName(u"label_13")
self.gridLayout_2.addWidget(self.label_13, 7, 0, 1, 1)
self.label_10 = QLabel(self.gridLayoutWidget_2)
self.label_10.setObjectName(u"label_10")
self.gridLayout_2.addWidget(self.label_10, 0, 0, 1, 1)
self.label_12 = QLabel(self.gridLayoutWidget_2)
self.label_12.setObjectName(u"label_12")
self.gridLayout_2.addWidget(self.label_12, 5, 0, 1, 1)
self.file_pre = QLineEdit(self.gridLayoutWidget_2)
self.file_pre.setObjectName(u"file_pre")
self.gridLayout_2.addWidget(self.file_pre, 6, 1, 1, 1)
self.horizontalLayout_5 = QHBoxLayout()
self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
self.fore_num_l = QSpinBox(self.gridLayoutWidget_2)
self.fore_num_l.setObjectName(u"fore_num_l")
self.fore_num_l.setValue(1)
self.horizontalLayout_5.addWidget(self.fore_num_l)
self.fore_num_r = QSpinBox(self.gridLayoutWidget_2)
self.fore_num_r.setObjectName(u"fore_num_r")
self.fore_num_r.setValue(2)
self.horizontalLayout_5.addWidget(self.fore_num_r)
self.gridLayout_2.addLayout(self.horizontalLayout_5, 4, 1, 1, 1)
self.save_dir = QLineEdit(self.gridLayoutWidget_2)
self.save_dir.setObjectName(u"save_dir")
self.gridLayout_2.addWidget(self.save_dir, 5, 1, 1, 1)
self.back_dir = QLineEdit(self.gridLayoutWidget_2)
self.back_dir.setObjectName(u"back_dir")
self.gridLayout_2.addWidget(self.back_dir, 0, 1, 1, 1)
self.label_16 = QLabel(self.gridLayoutWidget_2)
self.label_16.setObjectName(u"label_16")
self.gridLayout_2.addWidget(self.label_16, 6, 0, 1, 1)
self.label_14 = QLabel(self.gridLayoutWidget_2)
self.label_14.setObjectName(u"label_14")
self.gridLayout_2.addWidget(self.label_14, 8, 0, 1, 1)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.fore_alphas_l = QLineEdit(self.gridLayoutWidget_2)
self.fore_alphas_l.setObjectName(u"fore_alphas_l")
self.horizontalLayout_3.addWidget(self.fore_alphas_l)
self.fore_alphas_r = QLineEdit(self.gridLayoutWidget_2)
self.fore_alphas_r.setObjectName(u"fore_alphas_r")
self.horizontalLayout_3.addWidget(self.fore_alphas_r)
self.gridLayout_2.addLayout(self.horizontalLayout_3, 7, 1, 1, 1)
self.label_11 = QLabel(self.gridLayoutWidget_2)
self.label_11.setObjectName(u"label_11")
self.gridLayout_2.addWidget(self.label_11, 3, 0, 1, 1)
self.label_18 = QLabel(self.gridLayoutWidget_2)
self.label_18.setObjectName(u"label_18")
self.gridLayout_2.addWidget(self.label_18, 2, 0, 1, 1)
self.back_use_num = QSpinBox(self.gridLayoutWidget_2)
self.back_use_num.setObjectName(u"back_use_num")
self.back_use_num.setMaximum(9999)
self.back_use_num.setValue(10)
self.gridLayout_2.addWidget(self.back_use_num, 2, 1, 1, 1)
self.batch_merge_images = QPushButton(Merge)
self.batch_merge_images.setObjectName(u"batch_merge_images")
self.batch_merge_images.setGeometry(QRect(210, 560, 75, 24))
self.save_image = QPushButton(Merge)
self.save_image.setObjectName(u"save_image")
self.save_image.setGeometry(QRect(210, 300, 75, 24))
self.label_on = QCheckBox(Merge)
self.label_on.setObjectName(u"label_on")
self.label_on.setGeometry(QRect(30, 560, 71, 20))
self.label_on.setChecked(True)
self.clear_dir = QPushButton(Merge)
self.clear_dir.setObjectName(u"clear_dir")
self.clear_dir.setGeometry(QRect(110, 560, 75, 24))
self.retranslateUi(Merge)
QMetaObject.connectSlotsByName(Merge)
# setupUi
def retranslateUi(self, Merge):
Merge.setWindowTitle(QCoreApplication.translate("Merge", u"Dialog", None))
self.groupBox.setTitle(QCoreApplication.translate("Merge", u"\u56fe\u7247\u5408\u5e76", None))
self.label.setText(QCoreApplication.translate("Merge", u"\u80cc\u666f\u56fe\u7247", None))
self.label_2.setText(QCoreApplication.translate("Merge", u"\u524d\u666f\u56fe\u7247", None))
self.label_4.setText(QCoreApplication.translate("Merge", u"\u4f4d\u7f6e", None))
self.label_3.setText(QCoreApplication.translate("Merge", u"\u900f\u660e\u5ea6", None))
self.back_pos_w.setText(QCoreApplication.translate("Merge", u"0", None))
self.back_pos_h.setText(QCoreApplication.translate("Merge", u"0", None))
self.back_path.setText(QCoreApplication.translate("Merge", u"back/bg01.png", None))
self.back_padding.setText(QCoreApplication.translate("Merge", u"\u542f\u7528,\u6279\u91cf\u9ed8\u8ba4\u5173", None))
self.label_5.setText(QCoreApplication.translate("Merge", u"\u7f29\u653e", None))
self.label_6.setText(QCoreApplication.translate("Merge", u"\u80cc\u666f\u56fe\u6269\u5145", None))
self.fore_path.setText(QCoreApplication.translate("Merge", u"fore/fore_1.png", None))
self.label_15.setText(QCoreApplication.translate("Merge", u"\u4fdd\u5b58\u8def\u5f84", None))
self.single_save_image.setText(QCoreApplication.translate("Merge", u"merge/single_image.png", None))
self.label_7.setText(QCoreApplication.translate("Merge", u"\u80cc\u666f", None))
self.label_8.setText(QCoreApplication.translate("Merge", u"\u524d\u666f", None))
self.label_9.setText(QCoreApplication.translate("Merge", u"\u5408\u5e76", None))
self.show_images.setText(QCoreApplication.translate("Merge", u"\u663e\u793a\u56fe\u7247", None))
self.merge_images.setText(QCoreApplication.translate("Merge", u"\u5408\u5e76\u56fe\u7247", None))
self.fore_dir.setText(QCoreApplication.translate("Merge", u"fore", None))
self.fore_factors_l.setText(QCoreApplication.translate("Merge", u"0.5", None))
self.fore_factors_r.setText(QCoreApplication.translate("Merge", u"2", None))
self.label_17.setText(QCoreApplication.translate("Merge", u"\u524d\u666f\u4e2a\u6570", None))
self.label_13.setText(QCoreApplication.translate("Merge", u"\u900f\u660e\u5ea6", None))
self.label_10.setText(QCoreApplication.translate("Merge", u"\u80cc\u666f\u76ee\u5f55", None))
self.label_12.setText(QCoreApplication.translate("Merge", u"\u5408\u5e76\u76ee\u5f55", None))
self.file_pre.setText(QCoreApplication.translate("Merge", u"{time}_{num}_{size}", None))
self.save_dir.setText(QCoreApplication.translate("Merge", u"merge", None))
self.back_dir.setText(QCoreApplication.translate("Merge", u"back", None))
self.label_16.setText(QCoreApplication.translate("Merge", u"\u6587\u4ef6\u524d\u7f00", None))
self.label_14.setText(QCoreApplication.translate("Merge", u"\u7f29\u653e", None))
self.fore_alphas_l.setText(QCoreApplication.translate("Merge", u"0.5", None))
self.fore_alphas_r.setText(QCoreApplication.translate("Merge", u"1", None))
self.label_11.setText(QCoreApplication.translate("Merge", u"\u524d\u666f\u76ee\u5f55", None))
self.label_18.setText(QCoreApplication.translate("Merge", u"\u80cc\u666f\u6570\u91cf", None))
self.batch_merge_images.setText(QCoreApplication.translate("Merge", u"\u6279\u91cf\u5408\u5e76", None))
self.save_image.setText(QCoreApplication.translate("Merge", u"\u4fdd\u5b58\u56fe\u7247", None))
self.label_on.setText(QCoreApplication.translate("Merge", u"\u6570\u636e\u6807\u6ce8", None))
self.clear_dir.setText(QCoreApplication.translate("Merge", u"\u6e05\u7a7a\u6587\u4ef6\u5939", None))
# retranslateUi
<file_sep>import sys
import os
from datetime import datetime
import shutil
# PyQt5中使用的基本控件都在PyQt5.QtWidgets模块中
from PyQt5.QtWidgets import QApplication, QMainWindow
# 导入designer工具生成的login模块
from ui import Ui_Dialog
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image,ImageDraw,ImageFont,ImageQt
from seal import SEAL
from utils import Images
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsScene
from faker import Faker
import random
class MyMainForm(QMainWindow, Ui_Dialog):
def __init__(self, parent=None):
super(MyMainForm, self).__init__(parent)
# 初始化印章类
self.images_ = Images()
self.seal_ = SEAL()
self.setupUi(self)
self.label_nums_ = 28
self.resize_factor_ = 2
self.image_draw.clicked.connect(self.show_image)
self.update_config.clicked.connect(self.Update_config)
self.single_save.clicked.connect(self.Single_save)
self.batch_save.clicked.connect(self.Get_batch_images)
self.clear_dir.clicked.connect(self.Clear_dir)
def Clear_dir(self):
self.save_dir_ = self.save_dir.text()
if os.path.exists(self.save_dir_):
shutil.rmtree(self.save_dir_)
def Single_save(self):
# 缩放后保存
save_path = self.save_path.text()
temp_image = self.images_.image
width, height = temp_image.size
temp_image = temp_image.resize((width//self.resize_factor_, height//self.resize_factor_),Image.Resampling.LANCZOS)
temp_image.save(save_path)
def view_image(self,image):
temp_image = image.copy()
# opencv
# height = image.shape[0]
# width = image.shape[1]
# frame = QImage(image, width, height, QImage.Format_RGB888)
# PIL
width, height = temp_image.size
temp_image = temp_image.resize((width//self.resize_factor_, height//self.resize_factor_),Image.ANTIALIAS)
frame = ImageQt.ImageQt(temp_image)
pix = QPixmap.fromImage(frame)
self.item = QGraphicsPixmapItem(pix)
self.scene = QGraphicsScene() # 创建场景
self.scene.addItem(self.item)
self.image_win.setScene(self.scene)
def Update_batch_config(self):
self.batch_nums_ = int(self.batch_nums.text())
self.save_dir_ = self.save_dir.text()
self.file_pre_ = self.file_pre.text()
self.top_random_ = self.top_random.isChecked()
self.top_filepath_ = self.top_filepath.text()
self.bottom_random_ = self.bottom_random.isChecked()
self.bottom_filepath_ = self.bottom_filepath.text()
self.inter_random_ = self.inter_random.isChecked()
self.inter_filepath_ = self.inter_filepath.text()
self.line_label_on_ = self.line_label_on.isChecked()
self.label_nums_ = int(self.label_nums.value())
def Get_batch_images(self):
# 展示最终的样子
self.show_image()
self.Update_batch_config()
fakeinfo = Faker("zh-CN")
if self.top_random_:
top_content = []
# 随机
for i in range(self.batch_nums_):
top_content.append(fakeinfo.company())
else:
with open(self.top_filepath_,"r",encoding='utf-8') as f:
top_content = f.readlines()[:self.batch_nums_]
if self.bottom_random_:
bottom_content = []
# 随机
for i in range(self.batch_nums_):
bottom_content.append(fakeinfo.ssn())
else:
with open(self.bottom_filepath_,"r",encoding='utf-8') as f:
bottom_content = f.readlines()[:self.batch_nums_]
if self.inter_random_:
content = ["人事专用章","财务专用章","报关专用章","图书专用章","品检部","公章","合同章","合同专用章","发票专用章","财务章","法人章"]
# 随机
inter_content = []
for i in range(self.batch_nums_):
inter_content.append(random.choice(content))
else:
with open(self.inter_filepath_,"r",encoding='utf-8') as f:
inter_content = f.readlines()[:self.batch_nums_]
for i in range(self.batch_nums_):
labels_content = {}
self.images_.create_image("draw_test.png",self.img_size_)
image = self.images_.image
draw = ImageDraw.Draw(image)
if self.out_on_:
if self.out_shape_ == "rectangle":
pass
draw.rectangle(self.out_xyxy_,outline=self.color_,width=self.out_width_)
else:
draw.ellipse(self.out_xyxy_,outline=self.color_,width=self.out_width_)
if self.border_on_:
if self.border_shape_ == "rectangle":
draw.rectangle(self.border_xyxy_,outline=self.color_,width=self.border_width_)
else:
draw.ellipse(self.border_xyxy_,outline=self.color_,width=self.border_width_)
if self.in_on_:
if self.in_shape_ == "rectangle":
draw.rectangle(self.in_xyxy_,outline=self.color_,width=self.in_width_)
else:
draw.ellipse(self.in_xyxy_,outline=self.color_,width=self.in_width_)
if self.top_text_on_:
if self.top_text_shape_ =="rectangle":
infos,labels = self.seal_.cal_rec_text_pos_label(self.top_font_wh_,self.top_text_space_,top_content[i],label_nums=self.label_nums_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.top_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.top_font_wh, angle=degree, color=self.color_, spacing=self.top_text_space_)
else:
infos,labels = self.seal_.cal_text_and_label_pos(self.top_text_wh_,self.top_font_wh_,self.top_text_space_,top_content[i], label_nums=self.label_nums_, top=self.top_istop_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.top_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.top_font_wh_, angle=degree, color=self.color_, spacing=self.top_text_space_)
labels_content[top_content[i]] = []
for l in labels:
labels_content[top_content[i]].append([l[0]+self.center[0],self.center[1]-l[1]])
if self.bottom_text_on_:
if self.bottom_text_shape_ =="rectangle":
infos,labels = self.seal_.cal_rec_text_pos_label(self.bottom_font_wh_,self.bottom_text_space_,bottom_content[i],label_nums=self.label_nums_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.bottom_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.bottom_font_wh_, angle=degree, color=self.color_, spacing=self.bottom_text_space_)
else:
infos,labels = self.seal_.cal_text_and_label_pos(self.bottom_text_wh_,self.bottom_font_wh_,self.bottom_text_space_,bottom_content[i], label_nums=self.label_nums_, top=self.bottom_istop_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char,self.bottom_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.bottom_font_wh_, angle=degree, color=self.color_, spacing=self.bottom_text_space_)
labels_content[bottom_content[i]] = []
for l in labels:
labels_content[bottom_content[i]].append([l[0]+self.center[0],self.center[1]-l[1]])
if self.inter_text_on_:
if self.inter_text_shape_ =="rectangle":
infos,labels = self.seal_.cal_rec_text_pos_label(self.inter_font_wh_,self.inter_text_space_,inter_content[i],label_nums=self.label_nums_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.inter_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)+self.inter_shift_y_), font_size=self.inter_font_wh_, angle=degree, color=self.color_, spacing=self.inter_text_space_)
else:
infos,labels = self.seal_.cal_text_and_label_pos(self.inter_text_wh_,self.inter_font_wh,self.inter_text_space_,inter_content[i], label_nums=self.label_nums_, top=self.inter_istop_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.inter_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)+self.inter_shift_y_), font_size=self.inter_font_wh_, angle=degree, color=self.color_, spacing=self.inter_text_space_)
labels_content[inter_content[i]] = []
for l in labels:
labels_content[inter_content[i]].append([l[0]+self.center[0],self.center[1]-l[1]])
if not os.path.exists(self.save_dir_):
os.makedirs(self.save_dir_)
now = datetime.now()
time1 = now.strftime('%Y%m%d%H%M')
color = "_".join([str(i) for i in self.color_])
size = "_".join([str(i//self.resize_factor_) for i in self.img_size_])
png_name = os.path.join(self.save_dir_,self.file_pre_.format(time=time1,num=self.batch_nums_,shape=self.out_shape_,color=color,size=size)+f"_{str(i).zfill(4)}")
temp_image = image
width, height = temp_image.size
temp_image = temp_image.resize((width//self.resize_factor_, height//self.resize_factor_),Image.Resampling.LANCZOS)
temp_image.save(png_name+".png")
if self.line_label_on_:
with open(png_name+".txt",'w') as f:
for k,v in labels_content.items():
pp = ""
for vv in v[:-1]:
pp += f"{round(vv[0]/self.resize_factor_)},{round(vv[1]/self.resize_factor_)},"
pp += f"{round(v[-1][0]/self.resize_factor_)},{round(v[-1][1]/self.resize_factor_)}"
f.write(f"{k} {pp}\n")
# 配置更新
def Update_config(self):
self.resize_factor_ = int(self.resize_factor.value())
self.img_size_ = [self.resize_factor_*int(self.image_w.text()),self.resize_factor_*int(self.image_h.text())]
self.center = [i//2 for i in self.img_size_]
# out 参数
self.out_on_ = self.out_on.isChecked()
self.out_shape_ = self.out_shape.currentText()
self.out_size_ = [self.resize_factor_*int(self.out_size_w.text()),self.resize_factor_*int(self.out_size_h.text())]
self.color_ = tuple([int(self.img_r.text()),int(self.img_g.text()),int(self.img_b.text())])
self.out_width_ = self.resize_factor_*int(self.out_width.value())
# self.sp.valueChanged.connect(self.Valuechange)
self.out_xyxy_ = [self.center[i]-self.out_size_[i] for i in range(len(self.center))]+[self.center[i]+self.out_size_[i] for i in range(len(self.center))]
self.border_on_ = self.border_on.isChecked()
self.border_shape_ = self.border_shape.currentText()
self.border_size_ = [self.resize_factor_*int(self.border_size_w.text()),self.resize_factor_*int(self.border_size_h.text())]
self.border_xyxy_ = [self.center[i]-self.border_size_[i] for i in range(len(self.center))]+[self.center[i]+self.border_size_[i] for i in range(len(self.center))]
self.border_width_ = self.resize_factor_*int(self.border_width.value())
# 内边界大小 xyxy
self.in_on_ = self.in_on.isChecked()
self.in_shape_ = self.in_shape.currentText()
self.in_size_ = [self.resize_factor_*int(self.in_size_w.text()),self.resize_factor_*int(self.in_size_h.text())]
self.in_xyxy_ = [self.center[i]-self.in_size_[i] for i in range(len(self.center))]+[self.center[i]+self.in_size_[i] for i in range(len(self.center))]
self.in_width_ = self.resize_factor_*int(self.in_width.value())
self.top_text_on_ = self.top_text_on.isChecked()
self.top_text_shape_ = self.top_text_shape.currentText()
self.top_text_content_ = self.top_text_content.text()
# 整行文本占据的长度
self.top_text_wh_ = [self.resize_factor_*int(self.top_text_size_w.text()),self.resize_factor_*int(self.top_text_size_h.text())]
# 单个字体宽高
self.top_font_wh_ = [self.resize_factor_*int(self.top_text_font_w.text()),self.resize_factor_*int(self.top_text_font_h.text())]
self.top_text_font_ = self.top_text_font.text()
self.top_text_space_ = int(self.top_text_space.value())
self.top_istop_ = True
# 底部文字
self.bottom_text_on_ = self.bottom_text_on.isChecked()
self.bottom_text_shape_ = self.bottom_text_shape.currentText()
self.bottom_text_content_ = self.bottom_text_content.text()
# 整行文本占据的长度
self.bottom_text_wh_ = [self.resize_factor_*int(self.bottom_text_size_w.text()),self.resize_factor_*int(self.bottom_text_size_h.text())]
# 单个字体宽高
self.bottom_font_wh_ = [self.resize_factor_*int(self.bottom_text_font_w.text()),self.resize_factor_*int(self.bottom_text_font_h.text())]
self.bottom_text_font_ = self.bottom_text_font.text()
self.bottom_text_space_ = int(self.bottom_text_space.value())
self.bottom_istop_ = False
# 中间文本
self.inter_text_on_ = self.inter_text_on.isChecked()
self.inter_text_shape_ = self.inter_text_shape.currentText()
self.inter_text_content_ = self.inter_text_content.text()
# 整行文本占据的长度
self.inter_text_wh_ = [self.resize_factor_*int(self.inter_text_size_w.text()),self.resize_factor_*int(self.inter_text_size_h.text())]
# 单个字体宽高
self.inter_font_wh_ = [self.resize_factor_*int(self.inter_text_font_w.text()),self.resize_factor_*int(self.inter_text_font_h.text())]
self.inter_text_font_ = self.inter_text_font.text()
self.inter_text_space_ = int(self.inter_text_space.value())
self.inter_shift_y_ = self.resize_factor_*self.inter_shift_y.value()
self.inter_istop_ = True
# 单张显示图片
def show_image(self):
self.Update_config()
#
self.images_.create_image("draw_test.png",self.img_size_)
image = self.images_.image
draw = ImageDraw.Draw(image)
if self.out_on_:
if self.out_shape_ == "rectangle":
pass
draw.rectangle(self.out_xyxy_,outline=self.color_,width=self.out_width_)
else:
draw.ellipse(self.out_xyxy_,outline=self.color_,width=self.out_width_)
if self.border_on_:
if self.border_shape_ == "rectangle":
draw.rectangle(self.border_xyxy_,outline=self.color_,width=self.border_width_)
else:
draw.ellipse(self.border_xyxy_,outline=self.color_,width=self.border_width_)
if self.in_on_:
if self.in_shape_ == "rectangle":
draw.rectangle(self.in_xyxy_,outline=self.color_,width=self.in_width_)
else:
draw.ellipse(self.in_xyxy_,outline=self.color_,width=self.in_width_)
if self.top_text_on_:
if self.top_text_shape_ =="rectangle":
infos,_ = self.seal_.cal_rec_text_pos_label(self.top_font_wh_,self.top_text_space_,self.top_text_content_,label_nums=self.label_nums_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.top_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.top_font_wh, angle=degree, color=self.color_, spacing=self.top_text_space_)
else:
infos,_ = self.seal_.cal_text_and_label_pos(self.top_text_wh_,self.top_font_wh_,self.top_text_space_,self.top_text_content_, label_nums=self.label_nums_, top=self.top_istop_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.top_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.top_font_wh_, angle=degree, color=self.color_, spacing=self.top_text_space_)
if self.bottom_text_on_:
if self.bottom_text_shape_ =="rectangle":
infos,_ = self.seal_.cal_rec_text_pos_label(self.bottom_font_wh_,self.bottom_text_space_,self.bottom_text_content_,label_nums=self.label_nums_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.bottom_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.bottom_font_wh_, angle=degree, color=self.color_, spacing=self.bottom_text_space_)
else:
infos,_ = self.seal_.cal_text_and_label_pos(self.bottom_text_wh_,self.bottom_font_wh_,self.bottom_text_space_,self.bottom_text_content_, label_nums=self.label_nums_, top=self.bottom_istop_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char,self.bottom_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)), font_size=self.bottom_font_wh_, angle=degree, color=self.color_, spacing=self.bottom_text_space_)
if self.inter_text_on_:
if self.inter_text_shape_ =="rectangle":
infos,_ = self.seal_.cal_rec_text_pos_label(self.inter_font_wh_,self.inter_text_space_,self.inter_text_content_,label_nums=self.label_nums_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.inter_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)+self.inter_shift_y_), font_size=self.inter_font_wh_, angle=degree, color=self.color_, spacing=self.inter_text_space_)
else:
infos,_ = self.seal_.cal_text_and_label_pos(self.inter_text_wh_,self.inter_font_wh,self.inter_text_space_,self.inter_text_content_, label_nums=self.label_nums_, top=self.inter_istop_)
for char,x,y,degree in infos:
self.images_.draw_rotated_char(char, self.inter_text_font_, pos=((int(x)+self.center[0]), self.center[1]-int(y)+self.inter_shift_y_), font_size=self.inter_font_wh_, angle=degree, color=self.color_, spacing=self.inter_text_space_)
self.view_image(self.images_.image)
if __name__ == "__main__":
# 固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行
app = QApplication(sys.argv)
# 初始化
myWin = MyMainForm()
# 将窗口控件显示在屏幕上
myWin.show()
# 程序运行,sys.exit方法确保程序完整退出。
sys.exit(app.exec_())
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'merge_image.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Merge(object):
def setupUi(self, Merge):
Merge.setObjectName("Merge")
Merge.resize(958, 667)
self.groupBox = QtWidgets.QGroupBox(Merge)
self.groupBox.setGeometry(QtCore.QRect(40, 50, 91, 51))
self.groupBox.setObjectName("groupBox")
self.gridLayoutWidget = QtWidgets.QWidget(Merge)
self.gridLayoutWidget.setGeometry(QtCore.QRect(40, 110, 241, 186))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(self.gridLayoutWidget)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_2.setObjectName("label_2")
self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 5, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 4, 0, 1, 1)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.back_pos_w = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.back_pos_w.setObjectName("back_pos_w")
self.horizontalLayout_2.addWidget(self.back_pos_w)
self.back_pos_h = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.back_pos_h.setObjectName("back_pos_h")
self.horizontalLayout_2.addWidget(self.back_pos_h)
self.gridLayout.addLayout(self.horizontalLayout_2, 5, 1, 1, 1)
self.back_path = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.back_path.setObjectName("back_path")
self.gridLayout.addWidget(self.back_path, 0, 1, 1, 1)
self.back_padding = QtWidgets.QCheckBox(self.gridLayoutWidget)
self.back_padding.setObjectName("back_padding")
self.gridLayout.addWidget(self.back_padding, 1, 1, 1, 1)
self.fore_alpha = QtWidgets.QDoubleSpinBox(self.gridLayoutWidget)
self.fore_alpha.setMaximum(1.0)
self.fore_alpha.setSingleStep(0.1)
self.fore_alpha.setProperty("value", 0.0)
self.fore_alpha.setObjectName("fore_alpha")
self.gridLayout.addWidget(self.fore_alpha, 4, 1, 1, 1)
self.label_5 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_5.setObjectName("label_5")
self.gridLayout.addWidget(self.label_5, 6, 0, 1, 1)
self.label_6 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_6.setObjectName("label_6")
self.gridLayout.addWidget(self.label_6, 1, 0, 1, 1)
self.fore_path = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.fore_path.setObjectName("fore_path")
self.gridLayout.addWidget(self.fore_path, 3, 1, 1, 1)
self.fore_factor = QtWidgets.QDoubleSpinBox(self.gridLayoutWidget)
self.fore_factor.setMinimum(0.01)
self.fore_factor.setMaximum(99.0)
self.fore_factor.setSingleStep(0.1)
self.fore_factor.setProperty("value", 1.0)
self.fore_factor.setObjectName("fore_factor")
self.gridLayout.addWidget(self.fore_factor, 6, 1, 1, 1)
self.label_15 = QtWidgets.QLabel(self.gridLayoutWidget)
self.label_15.setObjectName("label_15")
self.gridLayout.addWidget(self.label_15, 7, 0, 1, 1)
self.single_save_image = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.single_save_image.setObjectName("single_save_image")
self.gridLayout.addWidget(self.single_save_image, 7, 1, 1, 1)
self.back_view = QtWidgets.QGraphicsView(Merge)
self.back_view.setGeometry(QtCore.QRect(330, 30, 281, 251))
self.back_view.setObjectName("back_view")
self.label_7 = QtWidgets.QLabel(Merge)
self.label_7.setGeometry(QtCore.QRect(470, 290, 53, 16))
self.label_7.setObjectName("label_7")
self.label_8 = QtWidgets.QLabel(Merge)
self.label_8.setGeometry(QtCore.QRect(660, 290, 53, 16))
self.label_8.setObjectName("label_8")
self.fore_view = QtWidgets.QGraphicsView(Merge)
self.fore_view.setGeometry(QtCore.QRect(640, 30, 281, 251))
self.fore_view.setObjectName("fore_view")
self.merge_view = QtWidgets.QGraphicsView(Merge)
self.merge_view.setGeometry(QtCore.QRect(330, 310, 301, 261))
self.merge_view.setObjectName("merge_view")
self.label_9 = QtWidgets.QLabel(Merge)
self.label_9.setGeometry(QtCore.QRect(440, 590, 53, 16))
self.label_9.setObjectName("label_9")
self.show_images = QtWidgets.QPushButton(Merge)
self.show_images.setGeometry(QtCore.QRect(40, 300, 75, 24))
self.show_images.setObjectName("show_images")
self.merge_images = QtWidgets.QPushButton(Merge)
self.merge_images.setGeometry(QtCore.QRect(130, 300, 75, 24))
self.merge_images.setObjectName("merge_images")
self.gridLayoutWidget_2 = QtWidgets.QWidget(Merge)
self.gridLayoutWidget_2.setGeometry(QtCore.QRect(40, 330, 241, 218))
self.gridLayoutWidget_2.setObjectName("gridLayoutWidget_2")
self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.fore_dir = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.fore_dir.setObjectName("fore_dir")
self.gridLayout_2.addWidget(self.fore_dir, 3, 1, 1, 1)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.fore_factors_l = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.fore_factors_l.setObjectName("fore_factors_l")
self.horizontalLayout_4.addWidget(self.fore_factors_l)
self.fore_factors_r = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.fore_factors_r.setObjectName("fore_factors_r")
self.horizontalLayout_4.addWidget(self.fore_factors_r)
self.gridLayout_2.addLayout(self.horizontalLayout_4, 8, 1, 1, 1)
self.label_17 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_17.setObjectName("label_17")
self.gridLayout_2.addWidget(self.label_17, 4, 0, 1, 1)
self.label_13 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_13.setObjectName("label_13")
self.gridLayout_2.addWidget(self.label_13, 7, 0, 1, 1)
self.label_10 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_10.setObjectName("label_10")
self.gridLayout_2.addWidget(self.label_10, 0, 0, 1, 1)
self.label_12 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_12.setObjectName("label_12")
self.gridLayout_2.addWidget(self.label_12, 5, 0, 1, 1)
self.file_pre = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.file_pre.setObjectName("file_pre")
self.gridLayout_2.addWidget(self.file_pre, 6, 1, 1, 1)
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.fore_num_l = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.fore_num_l.setProperty("value", 1)
self.fore_num_l.setObjectName("fore_num_l")
self.horizontalLayout_5.addWidget(self.fore_num_l)
self.fore_num_r = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.fore_num_r.setProperty("value", 2)
self.fore_num_r.setObjectName("fore_num_r")
self.horizontalLayout_5.addWidget(self.fore_num_r)
self.gridLayout_2.addLayout(self.horizontalLayout_5, 4, 1, 1, 1)
self.save_dir = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.save_dir.setObjectName("save_dir")
self.gridLayout_2.addWidget(self.save_dir, 5, 1, 1, 1)
self.back_dir = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.back_dir.setObjectName("back_dir")
self.gridLayout_2.addWidget(self.back_dir, 0, 1, 1, 1)
self.label_16 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_16.setObjectName("label_16")
self.gridLayout_2.addWidget(self.label_16, 6, 0, 1, 1)
self.label_14 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_14.setObjectName("label_14")
self.gridLayout_2.addWidget(self.label_14, 8, 0, 1, 1)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.fore_alphas_l = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.fore_alphas_l.setObjectName("fore_alphas_l")
self.horizontalLayout_3.addWidget(self.fore_alphas_l)
self.fore_alphas_r = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.fore_alphas_r.setObjectName("fore_alphas_r")
self.horizontalLayout_3.addWidget(self.fore_alphas_r)
self.gridLayout_2.addLayout(self.horizontalLayout_3, 7, 1, 1, 1)
self.label_11 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_11.setObjectName("label_11")
self.gridLayout_2.addWidget(self.label_11, 3, 0, 1, 1)
self.label_18 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_18.setObjectName("label_18")
self.gridLayout_2.addWidget(self.label_18, 2, 0, 1, 1)
self.back_use_num = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.back_use_num.setMaximum(9999)
self.back_use_num.setProperty("value", 10)
self.back_use_num.setObjectName("back_use_num")
self.gridLayout_2.addWidget(self.back_use_num, 2, 1, 1, 1)
self.batch_merge_images = QtWidgets.QPushButton(Merge)
self.batch_merge_images.setGeometry(QtCore.QRect(210, 560, 75, 24))
self.batch_merge_images.setObjectName("batch_merge_images")
self.save_image = QtWidgets.QPushButton(Merge)
self.save_image.setGeometry(QtCore.QRect(210, 300, 75, 24))
self.save_image.setObjectName("save_image")
self.label_on = QtWidgets.QCheckBox(Merge)
self.label_on.setGeometry(QtCore.QRect(30, 560, 71, 20))
self.label_on.setChecked(True)
self.label_on.setObjectName("label_on")
self.clear_dir = QtWidgets.QPushButton(Merge)
self.clear_dir.setGeometry(QtCore.QRect(110, 560, 75, 24))
self.clear_dir.setObjectName("clear_dir")
self.retranslateUi(Merge)
QtCore.QMetaObject.connectSlotsByName(Merge)
def retranslateUi(self, Merge):
_translate = QtCore.QCoreApplication.translate
Merge.setWindowTitle(_translate("Merge", "Dialog"))
self.groupBox.setTitle(_translate("Merge", "图片合并"))
self.label.setText(_translate("Merge", "背景图片"))
self.label_2.setText(_translate("Merge", "前景图片"))
self.label_4.setText(_translate("Merge", "位置"))
self.label_3.setText(_translate("Merge", "透明度"))
self.back_pos_w.setText(_translate("Merge", "0"))
self.back_pos_h.setText(_translate("Merge", "0"))
self.back_path.setText(_translate("Merge", "back/bg01.png"))
self.back_padding.setText(_translate("Merge", "启用,批量默认关"))
self.label_5.setText(_translate("Merge", "缩放"))
self.label_6.setText(_translate("Merge", "背景图扩充"))
self.fore_path.setText(_translate("Merge", "fore/fore_1.png"))
self.label_15.setText(_translate("Merge", "保存路径"))
self.single_save_image.setText(_translate("Merge", "merge/single_image.png"))
self.label_7.setText(_translate("Merge", "背景"))
self.label_8.setText(_translate("Merge", "前景"))
self.label_9.setText(_translate("Merge", "合并"))
self.show_images.setText(_translate("Merge", "显示图片"))
self.merge_images.setText(_translate("Merge", "合并图片"))
self.fore_dir.setText(_translate("Merge", "fore"))
self.fore_factors_l.setText(_translate("Merge", "0.5"))
self.fore_factors_r.setText(_translate("Merge", "2"))
self.label_17.setText(_translate("Merge", "前景个数"))
self.label_13.setText(_translate("Merge", "透明度"))
self.label_10.setText(_translate("Merge", "背景目录"))
self.label_12.setText(_translate("Merge", "合并目录"))
self.file_pre.setText(_translate("Merge", "{time}_{num}_{size}"))
self.save_dir.setText(_translate("Merge", "merge"))
self.back_dir.setText(_translate("Merge", "back"))
self.label_16.setText(_translate("Merge", "文件前缀"))
self.label_14.setText(_translate("Merge", "缩放"))
self.fore_alphas_l.setText(_translate("Merge", "0.5"))
self.fore_alphas_r.setText(_translate("Merge", "1"))
self.label_11.setText(_translate("Merge", "前景目录"))
self.label_18.setText(_translate("Merge", "背景数量"))
self.batch_merge_images.setText(_translate("Merge", "批量合并"))
self.save_image.setText(_translate("Merge", "保存图片"))
self.label_on.setText(_translate("Merge", "数据标注"))
self.clear_dir.setText(_translate("Merge", "清空文件夹"))
<file_sep>import cv2
import numpy as np
import math
class SEAL:
def __init__(self):
pass
# 椭圆角度对应的坐标,
def cal_ellipse_xy(self,a,b,degree):
# a: 长轴
# b: 短轴
# ref: https://blog.csdn.net/u014789533/article/details/114692234
rad = math.radians(degree)
ecc_angle = self.cal_eccentric_angle(a, b, rad)
x = a * math.cos(ecc_angle)
y = b * math.sin(ecc_angle)
return [x,y]
# 离心角度求解,可得到唯一解
@staticmethod
def cal_eccentric_angle(a,b,rad):
return math.atan2(a*math.sin(rad),b*math.cos(rad))
# 欧氏距离
@staticmethod
def get_l2_dist(point1:list,point2:list):
return math.sqrt((point1[1]-point2[1])**2 +(point1[0]-point2[0])**2)
# 微分思想获取椭圆上的坐标点
def cal_draw_points(self,a,b,start_degree,cross_degree, split_nums=1000):
# a: 长轴
# b: 短轴
# start_degree: 开始角度,与x轴正方向相同
# cross_degree: 角度跨度
result = []
for i in range(split_nums):
degree = start_degree + (i*cross_degree) / split_nums
point = self.cal_ellipse_xy(a,b,degree)
result.append(point)
return result
# 获取列表中所有相邻点之间的长度
def cal_points_length(self,xy:list):
# xy : 坐标点列表 [[x,y],...]
assert isinstance(xy,(list,tuple)), print("输出的xy非数组,检查类型",xy)
total_length = 0
part_length_list = []
for i in range(0,len(xy)-1):
l = self.get_l2_dist(xy[i],xy[i+1])
part_length_list.append(l)
total_length += l
return total_length,part_length_list
# 根据起始角度、角度跨度,获取文字位置
def cal_text_pos(self,a,b,start_degree,cross_degree, split_nums, text_nums):
# a: 长轴
# b: 短轴
# start_degree: 开始角度,与x轴正方向相同
# cross_degree: 角度跨度
# split_nums: 划分数量
# text_nums: 文本长度
xys = self.cal_draw_points(a,b,start_degree,cross_degree,split_nums)
length, part_length_list = self.cal_points_length(xys)
# 每个字的弧长
text_cross_per = length / (text_nums-1)
# 第一个字
result = [xys[0]]
cross_length_cnt = 0
for i in range(len(part_length_list)): #
cross_length_cnt += part_length_list[i]
if cross_length_cnt >= text_cross_per:
pre_dis = abs(cross_length_cnt - text_cross_per - part_length_list[i-1])
cur_dis = abs(cross_length_cnt - text_cross_per)
# 取距离小的值
if pre_dis <= cur_dis:
result.append(xys[i])
else:
result.append(xys[i+1])
cross_length_cnt = 0
if len(result) < text_nums:
result.append(xys[-1])
return result
# 计算椭圆切线角度
@staticmethod
def cal_tangent_degree(a,b,x,y):
if y==0:
return 90
k = -b*b*x/(a*a*y)
result = math.degrees(math.atan(k))
return result
# 计算椭圆的坐标以及角度信息
def cal_ellipse_text_info_basic(self,a,b,start_degree,cross_degree, split_nums,texts,top=True):
# a: 长轴
# b: 短轴
# start_degree: 开始角度,与x轴正方向相同
# cross_degree: 角度跨度
# split_nums: 划分数量
# text_nums: 文本长度
result = [] # item: char, x,y degree
text_len = len(texts)
text_pos = self.cal_text_pos(a,b,start_degree,cross_degree, split_nums,text_len)
for i in range(text_len):
degree = self.cal_tangent_degree(a,b,text_pos[i][0],text_pos[i][1])
if top and text_pos[i][1]<=0:
degree -= 180
if not top and text_pos[i][1]>=0:
degree -= 180
# y轴需要做个翻转
result.append([texts[text_len-1-i], text_pos[i][0],text_pos[i][1],degree])
return result, start_degree, cross_degree
# 已知直线,求线上点到线上某一点距离为dis的点
def cal_point_at_line_with_dis(self,k,b,fix_points:list,dis):
# k,b 直线斜率
# fix_points: 线上固定点
# dis: 到固定点的距离
# return [外点,内点]
c = (k*(b-fix_points[1])-fix_points[0])/(k**2+1)
d = ((b-fix_points[1])**2+fix_points[0]**2-dis**2)/(k**2+1)
e = (c**2-d)**0.5
x1 = e-c
y1 = k*x1 + b
x2 = -e-c
y2 = k*x2 + b
result = [[x1,y1],[x2,y2]]
# y大的为外点
result.sort(key=lambda x: x[1],reverse=True)
return result
# 计算某一个点绕着固定点旋转的坐标
def cal_rotate_at_fix_point(self,degree,valuex,valuey,pointx,pointy,clock=False):
# degree : 旋转角度值
# valuex, valuey : 旋转的点
# pointx, pointy : 固定点
# clock : 顺时针方向
rad = math.radians(degree)
if clock:
rad = -rad
valuex = np.array(valuex)
valuey = np.array(valuey)
nRotatex = (valuex-pointx)*math.cos(rad) - (valuey-pointy)*math.sin(rad) + pointx
nRotatey = (valuex-pointx)*math.sin(rad) + (valuey-pointy)*math.cos(rad) + pointy
return nRotatex, nRotatey
#####################################################
# 通过对称位置,计算椭圆的坐标以及角度信息
def cal_ellipse_text_info_with_cross(self,a,b,cross_degree, split_nums,texts,top=True):
# a: 长轴
# b: 短轴
# start_degree: 开始角度,与x轴正方向相同
# cross_degree: 角度跨度
# split_nums: 划分数量
# text_nums: 文本长度
start_degree = cross_degree/2
# print("起始角度:",start_degree)
if not top:
start_degree -= 180
texts = texts[::-1]
# 从最后一个文字开始算起点
start_degree = 90 - start_degree
return self.cal_ellipse_text_info_basic(a,b,start_degree,cross_degree, split_nums,texts,top=top)
# 通过对称以及字体计算椭圆坐标以及角度信息,简洁版(推荐),求标签版
def cal_ellipse_text_label_info_sim(self,a,b,font_size,space,split_nums,texts,label_nums,top=True):
# a: 长轴
# b: 短轴
# start_degree: 开始角度,与x轴正方向相同
# cross_degree: 角度跨度
# split_nums: 划分数量
# texts: 文本
# label_nums: 标注点数量
# top : 上半区还是小半区
error = 1.2 # 精度,用于调整
text_len = len(texts)
cross_length = (font_size[0]*text_len+text_len*space)*error
# 一半
half_cross_length = cross_length / 2
# 模拟从90~-90的点位置
xys = self.cal_draw_points(a,b,270,180,split_nums)
_, part_length_list = self.cal_points_length(xys)
sums = 0
cross_degree = 0
for i in part_length_list:
sums += i
cross_degree += 180/split_nums
if sums >= half_cross_length:
break
# 完整区域
cross_degree *= 2
_,start_degree,cross_degree = self.cal_ellipse_text_info_with_cross(a,b, cross_degree, split_nums,texts,top=top)
texts = " "*label_nums
return self.cal_ellipse_text_info_basic(a,b,start_degree,cross_degree,split_nums,texts,top=top)
# 通过对称以及字体计算椭圆坐标以及角度信息,简洁版(推荐)
def cal_ellipse_text_info_sim(self,a,b,font_size,space,split_nums,texts,top=True):
# a: 长轴
# b: 短轴
# font_size: wh 文字宽高
# space: 字间距
# split_nums: 划分数量
# texts: 文本
# top : 上半区还是小半区
error = 1.1 # 精度,用于调整
text_len = len(texts)
cross_length = (font_size[0]*text_len+(text_len-1)*space)*error
# 一半
half_cross_length = cross_length // 2
# 模拟从90~-90的点位置
xys = self.cal_draw_points(a,b,270,180,split_nums)
_, part_length_list = self.cal_points_length(xys)
sums = 0
cross_degree = 0
for i in part_length_list:
sums += i
cross_degree += 180/split_nums
if sums >= half_cross_length:
break
# 完整区域
cross_degree *= 2
return self.cal_ellipse_text_info_with_cross(a,b, cross_degree, split_nums,texts,top=top)
# 计算旋转后文本框四个点
def cal_text_border_pos(self,center_xy,wh,degree,clock=False):
# center_xy: 文本框中心
# wh: 文本框宽高
# degree: 旋转角度
# 返回值, r:右边 l:左边 t:顶部 b:底部 m:中间
# mt
# lt .____.____. rt
#/ ml !____!____! mr
#/ lb !____!____! rb
# mb
degree = 180 - degree # 用于调试
x,y = center_xy
w,h = [i//2 for i in wh]
lt,rt,rb,lb = [x-w,y+h],[x+w,y+h],[x+w,y-h],[x-w,y-h]
ml,mt,mr,mb = [x-w,y],[x,y+h],[x+w,y],[x,y-h]
new_lt = self.cal_rotate_at_fix_point(degree,*lt,x,y,clock=clock)
new_rt = self.cal_rotate_at_fix_point(degree,*rt,x,y,clock=clock)
new_rb = self.cal_rotate_at_fix_point(degree,*rb,x,y,clock=clock)
new_lb = self.cal_rotate_at_fix_point(degree,*lb,x,y,clock=clock)
new_ml = self.cal_rotate_at_fix_point(degree,*ml,x,y,clock=clock)
new_mt = self.cal_rotate_at_fix_point(degree,*mt,x,y,clock=clock)
new_mr = self.cal_rotate_at_fix_point(degree,*mr,x,y,clock=clock)
new_mb = self.cal_rotate_at_fix_point(degree,*mb,x,y,clock=clock)
return new_lt,new_rt,new_rb,new_lb, new_ml,new_mt,new_mr, new_mb
# 计算文本与标签,合成版,
def cal_text_and_label_pos(self,ellipse_ab,txt_wh,space,texts, label_nums=28, split_nums=1000,top=True):
# ellipse_ab : 椭圆长短轴
# txt_wh : 文字宽高
# space : 文字间距
# texts : 文本
# label_nums :标签数量,上下包含
infos,_,_ = self.cal_ellipse_text_info_sim(*ellipse_ab, txt_wh, space, split_nums,texts, top=top)
label_infos,_,_ = self.cal_ellipse_text_label_info_sim(*ellipse_ab, txt_wh, space, split_nums,texts, label_nums//2, top=top)
label_top,label_buttom = [],[]
for char,x,y,degree in label_infos:
lt,rt,rb,lb,ml,mt,mr,mb = self.cal_text_border_pos([x,y],txt_wh[::-1],degree,clock=True)
label_top.append(mt)
label_buttom.append(mb)
if top:
label_info = label_buttom[::-1] + label_top
else:
label_info = label_buttom + label_top[::-1]
return infos, label_info
def cal_text_and_label_pos(self,ellipse_ab,txt_wh,space,texts, label_nums=28, split_nums=1000,top=True):
# ellipse_ab : 椭圆长短轴
# txt_wh : 文字宽高
# space : 文字间距
# texts : 文本
# label_nums :标签数量,上下包含
infos,_,_ = self.cal_ellipse_text_info_sim(*ellipse_ab, txt_wh, space, split_nums,texts, top=top)
label_infos,_,_ = self.cal_ellipse_text_label_info_sim(*ellipse_ab, txt_wh, space, split_nums,texts, label_nums//2, top=top)
label_top,label_buttom = [],[]
for char,x,y,degree in label_infos:
lt,rt,rb,lb,ml,mt,mr,mb = self.cal_text_border_pos([x,y],txt_wh[::-1],degree,clock=True)
label_top.append(mt)
label_buttom.append(mb)
if top:
label_info = label_buttom[::-1] + label_top
else:
label_info = label_buttom + label_top[::-1]
return infos, label_info
def cal_every_text_and_label_pos(self,ellipse_ab,txt_wh,space,texts,split_nums=1000,top=True):
# ellipse_ab : 椭圆长短轴
# txt_wh : 文字宽高
# space : 文字间距
# texts : 文本
infos,_,_ = self.cal_ellipse_text_info_sim(*ellipse_ab, txt_wh, space, split_nums,texts, top=top)
every_label = []
if top:
for char,x,y,degree in infos[::-1]:
lt,rt,rb,lb,ml,mt,mr,mb = self.cal_text_border_pos([x,y],txt_wh[::-1],degree,clock=True)
every_label.append([rb,lb,lt,rt,char])
else:
for char,x,y,degree in infos:
lt,rt,rb,lb,ml,mt,mr,mb = self.cal_text_border_pos([x,y],txt_wh[::-1],degree,clock=True)
every_label.append([rb,lb,lt,rt,char])
return infos, every_label
# 计算矩形文本,指定标注数量
def cal_rec_text_pos_label(self,txt_wh,space,texts,label_nums=4):
"""计算矩形文本的文字中心坐标以及指定标注数目的标签坐标
Args:
# rec_wh (list | tuple): 矩形文本行的宽高
txt_wh (_type_): 文字的宽高
space (_type_): 文字间距
texts (_type_): 文字
label_nums (int, optional): 文本行标注数目,包含上下. Defaults to 4.
Returns:
_type_: 文本中心以及文本行标注
"""
error = 1.1 # 精度,用于调整
label_error = 1.1 # 精度,用于调整
text_len = len(texts)
# 文本的长度
text_cross_length = (txt_wh[0]*text_len+(text_len-1)*space)*error
per_text_length = text_cross_length/(text_len-1)
start_pos = text_cross_length//2
text_pos = [[-start_pos+per_text_length*i, 0] for i in range(text_len)]
infos = []
for i in range(text_len):
infos.append([texts[i],*(text_pos[i]),0])
# 标注的长度
label_cross_length = (txt_wh[0]*text_len+text_len*space)*label_error
# 一半标签
per_label_length = label_cross_length/(label_nums//2-1)
start_pos = label_cross_length // 2
label_pos = [[-start_pos+per_label_length*i, txt_wh[1]//2] for i in range(label_nums//2)]
label_pos += [[start_pos-per_label_length*i, -txt_wh[1]//2] for i in range(label_nums//2)]
return infos, label_pos
<file_sep># 图像处理
# 合并图片,合并多张图片
import PIL.Image as Image
import matplotlib.pyplot as plt
import numpy as np
import random
def xywh2xyxyxyxy(x,y,w,h):
return [[x,y],[x+w,y],[x+w,y+h],[x,y+h]]
def merge_fore_to_back_image(fore_image, back_image, fore_pos=(0,0),fore_alpha=1.0,fore_factor=1.0,back_padding=False,fore_func=lambda x:x):
"""将两个图片进行合并,支持自定义透明度 alpha, 缩放factor, 背景图缩放开关 padding, 前景图回调函数 func
背景图过小,会重定义为前景图大小,padding开启时,pos会包含
Args:
fore_image (PIL.Image): 前景图
back_image (PIL.Image): 背景图
fore_pos (tuple, list): 左上角位置. Defaults to (0,0).
fore_alpha (float, optional): 前景透明度. Defaults to 1.0.
fore_factor (float, optional): 前景缩放因子. Defaults to 1.0.
back_padding (bool, optional): 背景自适应缩放. Defaults to False.
fore_func (Functional, optional): 前景处理回调函数. Defaults to lambdax:x.
Returns:
PIL.Image: 合并后的图片
"""
assert fore_alpha <= 1.0, "Alpha must be less or equel than 1.0"
final_image = back_image.copy()
fore_image_temp = fore_image.copy()
# 设置缩放因子 透明度
fore_w, fore_h = fore_image_temp.size
fore_new_w = int(fore_w * fore_factor)
fore_new_h = int(fore_h * fore_factor)
fore_image_temp = fore_image_temp.resize((fore_new_w, fore_new_h), Image.Resampling.LANCZOS)
fore_w, fore_h = fore_image_temp.size
for i in range(fore_new_w):
for k in range(fore_new_h):
color = fore_image_temp.getpixel((i, k))
if len(color) == 3:
print(color)
color = color[:-1] + ((int(color[-1]*(1-fore_alpha)))%256, )
fore_image_temp.putpixel((i, k), color)
fore_image_temp = fore_func(fore_image_temp)
# 背景图不够大将会被resize
if back_padding:
back_limit_w = fore_new_w + fore_pos[0]
back_limit_h = fore_new_h + fore_pos[1]
else:
back_limit_w = fore_new_w
back_limit_h = fore_new_h
# 设置背景图片大小
back_w, back_h = final_image.size
# 设置背景图大小
if back_w < back_limit_w:
back_new_w = back_limit_w
print(f"背景图宽度过小, {back_w} < {back_limit_w}")
else:
back_new_w = back_w
if back_h < back_limit_h:
back_new_h = back_limit_h
print(f"背景图高度过小, {back_h} < {back_limit_h}")
else:
back_new_h = back_h
final_image = final_image.resize((back_new_w,back_new_h),Image.Resampling.LANCZOS)
final_image.paste(fore_image_temp, fore_pos, mask=fore_image_temp)
fore_final_w, fore_final_h = fore_image_temp.size
back_final_w, back_final_h =final_image.size
label_x = fore_pos[0] if fore_pos[0]>0 else 0
label_y = fore_pos[1] if fore_pos[1]>0 else 0
label_w = fore_pos[0]+fore_final_w-label_x if fore_pos[0]+fore_final_w < back_final_w else back_final_w-label_x
label_h = fore_pos[1]+fore_final_h-label_y if fore_pos[1]+fore_final_h < back_final_h else back_final_h-label_y
return final_image, xywh2xyxyxyxy(label_x,label_y,label_w,label_h)
def random_merge_images(fore_images,back_image,fore_poss=None,fore_alphas = None ,fore_factors = None, fore_full = True, fore_func = lambda x : x,fore_range={"fore_alphas":[0.01,0.99],"fore_factors":[0.01,5]}):
final_image = back_image.copy()
back_w, back_h = final_image.size
image_nums = len(fore_images)
if fore_alphas == None:
fore_alphas = [random.randint(fore_range["fore_alphas"][0]*100,fore_range["fore_alphas"][1]*100)/100 for i in range(image_nums)]
# 单值,或范围一致
elif isinstance(fore_alphas, (float,int)) or fore_range["fore_alphas"][0]==fore_range["fore_alphas"][1]:
fore_alphas = [fore_alphas]*image_nums
elif isinstance(fore_alphas, (tuple,list)):
pass
else:
print(f"fore_alphas error {fore_alphas}")
if fore_factors == None:
fore_factors = [random.randint(fore_range["fore_factors"][0]*100,fore_range["fore_factors"][1]*100)/100 for i in range(image_nums)]
elif isinstance(fore_factors, (float,int)) or fore_range["fore_factors"][0]==fore_range["fore_factors"][1]:
fore_factors = [fore_factors]*image_nums
elif isinstance(fore_factors, (tuple,list)):
pass
else:
print(f"fore_factors error {fore_factors}")
# print(fore_alphas,fore_factors)
if isinstance(fore_poss, (float,int)) or fore_poss == None:
fore_poss = []
for i in range(image_nums):
# 避免前景超出背景范围
if fore_full:
fw,fh = fore_images[i].size
max_h = back_h - fh
max_w = back_w - fw
if max_h <0 or max_w <0:
print("背景图太小了,前景图太大")
max_h = back_h
max_w = back_w
fore_poss.append(None)
continue
else:
max_h = back_h
max_w = back_w
x = random.randint(0,max_w-1)
y = random.randint(0,max_h-1)
fore_poss.append([x,y])
else:
pass
labels = []
params = {"fore_alpha":[],"fore_factor":[],"fore_pos":[]}
for i in range(image_nums):
fore_image = fore_images[i]
fore_alpha = fore_alphas[i]
fore_factor = fore_factors[i]
fore_pos = fore_poss[i]
if fore_pos == None:
continue
# print(fore_image.size,fore_alpha,fore_factor,fore_pos)
final_image,label = merge_fore_to_back_image(fore_image, final_image, fore_pos=fore_pos, fore_alpha=fore_alpha, fore_factor=fore_factor, back_padding=False, fore_func=fore_func)
# print("label",label)
labels.append(label)
params["fore_alpha"].append(fore_alphas[i])
params["fore_factor"].append(fore_factors[i])
params["fore_pos"].append(fore_poss[i])
return final_image,labels,params
if __name__ == '__main__':
fore_image = Image.open("fore/fore_1.png")
back_image = Image.open("back/bg01.png").convert("RGBA").resize((1000,1000))
# print(back_image.size)
# final_image,label = merge_fore_to_back_image(fore_image, back_image,fore_pos=(100,100),back_padding=0,fore_alpha=0.5)
# label = np.array(label)
# plt.figure()
# plt.subplot(1,3,1)
# plt.imshow(fore_image)
# plt.subplot(1,3,2)
# plt.imshow(back_image)
# plt.subplot(1,3,3)
# plt.imshow(final_image)
# plt.scatter(label[:,0],label[:,1],marker='.',linewidths=1)
# plt.show()
final_image,labels,_ = random_merge_images([fore_image]*2,back_image,fore_poss=None, fore_alphas=0.5)
##plt 同时显示多幅图像
label = np.array(labels)
# print([:,0])
plt.figure()
plt.subplot(1,3,1)
plt.imshow(fore_image)
plt.subplot(1,3,2)
plt.imshow(back_image)
plt.subplot(1,3,3)
plt.imshow(final_image)
plt.scatter(label[:,:,0],label[:,:,1],marker='.',linewidths=1)
plt.show()
print("结束")
while True:
pass
<file_sep># -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'test.ui'
##
## Created by: Qt User Interface Compiler version 6.4.1
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
QMetaObject, QObject, QPoint, QRect,
QSize, QTime, QUrl, Qt)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
QFont, QFontDatabase, QGradient, QIcon,
QImage, QKeySequence, QLinearGradient, QPainter,
QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QAbstractScrollArea, QAbstractSpinBox, QApplication, QCheckBox,
QComboBox, QDialog, QFormLayout, QGraphicsView,
QGridLayout, QGroupBox, QHBoxLayout, QLabel,
QLineEdit, QPushButton, QSizePolicy, QSpinBox,
QWidget)
class Ui_Dialog(object):
def setupUi(self, Dialog):
if not Dialog.objectName():
Dialog.setObjectName(u"Dialog")
Dialog.resize(1131, 809)
self.image_win = QGraphicsView(Dialog)
self.image_win.setObjectName(u"image_win")
self.image_win.setGeometry(QRect(580, 20, 401, 361))
self.image_win.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
self.gridLayoutWidget_3 = QWidget(Dialog)
self.gridLayoutWidget_3.setObjectName(u"gridLayoutWidget_3")
self.gridLayoutWidget_3.setGeometry(QRect(40, 700, 252, 56))
self.gridLayout_5 = QGridLayout(self.gridLayoutWidget_3)
self.gridLayout_5.setObjectName(u"gridLayout_5")
self.gridLayout_5.setContentsMargins(0, 0, 0, 0)
self.batch_save = QPushButton(self.gridLayoutWidget_3)
self.batch_save.setObjectName(u"batch_save")
self.gridLayout_5.addWidget(self.batch_save, 1, 1, 1, 1)
self.label_nums = QSpinBox(self.gridLayoutWidget_3)
self.label_nums.setObjectName(u"label_nums")
self.label_nums.setMinimum(-99)
self.label_nums.setStepType(QAbstractSpinBox.DefaultStepType)
self.label_nums.setValue(28)
self.gridLayout_5.addWidget(self.label_nums, 0, 1, 1, 1)
self.line_label_on = QCheckBox(self.gridLayoutWidget_3)
self.line_label_on.setObjectName(u"line_label_on")
self.line_label_on.setChecked(True)
self.gridLayout_5.addWidget(self.line_label_on, 1, 0, 1, 1)
self.label_47 = QLabel(self.gridLayoutWidget_3)
self.label_47.setObjectName(u"label_47")
self.gridLayout_5.addWidget(self.label_47, 0, 0, 1, 1)
self.clear_dir = QPushButton(self.gridLayoutWidget_3)
self.clear_dir.setObjectName(u"clear_dir")
self.gridLayout_5.addWidget(self.clear_dir, 0, 2, 1, 1)
self.groupBox = QGroupBox(Dialog)
self.groupBox.setObjectName(u"groupBox")
self.groupBox.setGeometry(QRect(30, 430, 251, 271))
self.gridLayoutWidget_4 = QWidget(self.groupBox)
self.gridLayoutWidget_4.setObjectName(u"gridLayoutWidget_4")
self.gridLayoutWidget_4.setGeometry(QRect(10, 20, 231, 236))
self.gridLayout_4 = QGridLayout(self.gridLayoutWidget_4)
self.gridLayout_4.setObjectName(u"gridLayout_4")
self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
self.bottom_random = QCheckBox(self.gridLayoutWidget_4)
self.bottom_random.setObjectName(u"bottom_random")
self.bottom_random.setChecked(True)
self.gridLayout_4.addWidget(self.bottom_random, 5, 1, 1, 1)
self.label_36 = QLabel(self.gridLayoutWidget_4)
self.label_36.setObjectName(u"label_36")
self.gridLayout_4.addWidget(self.label_36, 3, 0, 1, 1)
self.label_43 = QLabel(self.gridLayoutWidget_4)
self.label_43.setObjectName(u"label_43")
self.gridLayout_4.addWidget(self.label_43, 1, 0, 1, 1)
self.inter_filepath = QLineEdit(self.gridLayoutWidget_4)
self.inter_filepath.setObjectName(u"inter_filepath")
self.gridLayout_4.addWidget(self.inter_filepath, 8, 1, 1, 1)
self.save_dir = QLineEdit(self.gridLayoutWidget_4)
self.save_dir.setObjectName(u"save_dir")
self.gridLayout_4.addWidget(self.save_dir, 1, 1, 1, 1)
self.label_42 = QLabel(self.gridLayoutWidget_4)
self.label_42.setObjectName(u"label_42")
self.gridLayout_4.addWidget(self.label_42, 8, 0, 1, 1)
self.label_38 = QLabel(self.gridLayoutWidget_4)
self.label_38.setObjectName(u"label_38")
self.gridLayout_4.addWidget(self.label_38, 5, 0, 1, 1)
self.label_41 = QLabel(self.gridLayoutWidget_4)
self.label_41.setObjectName(u"label_41")
self.gridLayout_4.addWidget(self.label_41, 7, 0, 1, 1)
self.bottom_filepath = QLineEdit(self.gridLayoutWidget_4)
self.bottom_filepath.setObjectName(u"bottom_filepath")
self.gridLayout_4.addWidget(self.bottom_filepath, 6, 1, 1, 1)
self.label_37 = QLabel(self.gridLayoutWidget_4)
self.label_37.setObjectName(u"label_37")
self.gridLayout_4.addWidget(self.label_37, 0, 0, 1, 1)
self.label_40 = QLabel(self.gridLayoutWidget_4)
self.label_40.setObjectName(u"label_40")
self.gridLayout_4.addWidget(self.label_40, 6, 0, 1, 1)
self.label_39 = QLabel(self.gridLayoutWidget_4)
self.label_39.setObjectName(u"label_39")
self.gridLayout_4.addWidget(self.label_39, 4, 0, 1, 1)
self.top_random = QCheckBox(self.gridLayoutWidget_4)
self.top_random.setObjectName(u"top_random")
self.top_random.setChecked(True)
self.gridLayout_4.addWidget(self.top_random, 3, 1, 1, 1)
self.inter_random = QCheckBox(self.gridLayoutWidget_4)
self.inter_random.setObjectName(u"inter_random")
self.inter_random.setChecked(True)
self.gridLayout_4.addWidget(self.inter_random, 7, 1, 1, 1)
self.batch_nums = QLineEdit(self.gridLayoutWidget_4)
self.batch_nums.setObjectName(u"batch_nums")
self.gridLayout_4.addWidget(self.batch_nums, 0, 1, 1, 1)
self.label_44 = QLabel(self.gridLayoutWidget_4)
self.label_44.setObjectName(u"label_44")
self.gridLayout_4.addWidget(self.label_44, 2, 0, 1, 1)
self.file_pre = QLineEdit(self.gridLayoutWidget_4)
self.file_pre.setObjectName(u"file_pre")
self.gridLayout_4.addWidget(self.file_pre, 2, 1, 1, 1)
self.top_filepath = QLineEdit(self.gridLayoutWidget_4)
self.top_filepath.setObjectName(u"top_filepath")
self.gridLayout_4.addWidget(self.top_filepath, 4, 1, 1, 1)
self.groupBox_2 = QGroupBox(Dialog)
self.groupBox_2.setObjectName(u"groupBox_2")
self.groupBox_2.setGeometry(QRect(310, 10, 251, 651))
self.gridLayoutWidget_2 = QWidget(self.groupBox_2)
self.gridLayoutWidget_2.setObjectName(u"gridLayoutWidget_2")
self.gridLayoutWidget_2.setGeometry(QRect(10, 20, 231, 625))
self.gridLayout_2 = QGridLayout(self.gridLayoutWidget_2)
self.gridLayout_2.setObjectName(u"gridLayout_2")
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.top_text_content = QLineEdit(self.gridLayoutWidget_2)
self.top_text_content.setObjectName(u"top_text_content")
self.gridLayout_2.addWidget(self.top_text_content, 3, 1, 1, 1)
self.label_23 = QLabel(self.gridLayoutWidget_2)
self.label_23.setObjectName(u"label_23")
self.gridLayout_2.addWidget(self.label_23, 16, 0, 1, 1)
self.label_19 = QLabel(self.gridLayoutWidget_2)
self.label_19.setObjectName(u"label_19")
self.gridLayout_2.addWidget(self.label_19, 2, 0, 1, 1)
self.label_30 = QLabel(self.gridLayoutWidget_2)
self.label_30.setObjectName(u"label_30")
self.gridLayout_2.addWidget(self.label_30, 18, 0, 1, 1)
self.label_27 = QLabel(self.gridLayoutWidget_2)
self.label_27.setObjectName(u"label_27")
self.gridLayout_2.addWidget(self.label_27, 17, 0, 1, 1)
self.label_29 = QLabel(self.gridLayoutWidget_2)
self.label_29.setObjectName(u"label_29")
self.gridLayout_2.addWidget(self.label_29, 26, 0, 1, 1)
self.top_text_on = QCheckBox(self.gridLayoutWidget_2)
self.top_text_on.setObjectName(u"top_text_on")
self.top_text_on.setChecked(True)
self.gridLayout_2.addWidget(self.top_text_on, 0, 1, 1, 1)
self.bottom_text_font = QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_font.setObjectName(u"bottom_text_font")
self.gridLayout_2.addWidget(self.bottom_text_font, 16, 1, 1, 1)
self.label_13 = QLabel(self.gridLayoutWidget_2)
self.label_13.setObjectName(u"label_13")
self.gridLayout_2.addWidget(self.label_13, 4, 0, 1, 1)
self.bottom_text_on = QCheckBox(self.gridLayoutWidget_2)
self.bottom_text_on.setObjectName(u"bottom_text_on")
self.bottom_text_on.setChecked(True)
self.gridLayout_2.addWidget(self.bottom_text_on, 7, 1, 1, 1)
self.label_18 = QLabel(self.gridLayoutWidget_2)
self.label_18.setObjectName(u"label_18")
self.gridLayout_2.addWidget(self.label_18, 3, 0, 1, 1)
self.label_20 = QLabel(self.gridLayoutWidget_2)
self.label_20.setObjectName(u"label_20")
self.gridLayout_2.addWidget(self.label_20, 1, 0, 1, 1)
self.label_26 = QLabel(self.gridLayoutWidget_2)
self.label_26.setObjectName(u"label_26")
self.gridLayout_2.addWidget(self.label_26, 9, 0, 1, 1)
self.top_text_shape = QComboBox(self.gridLayoutWidget_2)
self.top_text_shape.addItem("")
self.top_text_shape.addItem("")
self.top_text_shape.addItem("")
self.top_text_shape.setObjectName(u"top_text_shape")
self.gridLayout_2.addWidget(self.top_text_shape, 1, 1, 1, 1)
self.label_31 = QLabel(self.gridLayoutWidget_2)
self.label_31.setObjectName(u"label_31")
self.gridLayout_2.addWidget(self.label_31, 28, 0, 1, 1)
self.horizontalLayout_13 = QHBoxLayout()
self.horizontalLayout_13.setObjectName(u"horizontalLayout_13")
self.inter_shift_y = QSpinBox(self.gridLayoutWidget_2)
self.inter_shift_y.setObjectName(u"inter_shift_y")
self.inter_shift_y.setMinimum(-99)
self.inter_shift_y.setStepType(QAbstractSpinBox.DefaultStepType)
self.inter_shift_y.setValue(6)
self.horizontalLayout_13.addWidget(self.inter_shift_y)
self.gridLayout_2.addLayout(self.horizontalLayout_13, 27, 1, 1, 1)
self.horizontalLayout_5 = QHBoxLayout()
self.horizontalLayout_5.setObjectName(u"horizontalLayout_5")
self.top_text_font_w = QLineEdit(self.gridLayoutWidget_2)
self.top_text_font_w.setObjectName(u"top_text_font_w")
self.horizontalLayout_5.addWidget(self.top_text_font_w)
self.top_text_font_h = QLineEdit(self.gridLayoutWidget_2)
self.top_text_font_h.setObjectName(u"top_text_font_h")
self.horizontalLayout_5.addWidget(self.top_text_font_h)
self.gridLayout_2.addLayout(self.horizontalLayout_5, 4, 1, 1, 1)
self.horizontalLayout_8 = QHBoxLayout()
self.horizontalLayout_8.setObjectName(u"horizontalLayout_8")
self.bottom_text_font_w = QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_font_w.setObjectName(u"bottom_text_font_w")
self.horizontalLayout_8.addWidget(self.bottom_text_font_w)
self.bottom_text_font_h = QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_font_h.setObjectName(u"bottom_text_font_h")
self.horizontalLayout_8.addWidget(self.bottom_text_font_h)
self.gridLayout_2.addLayout(self.horizontalLayout_8, 12, 1, 1, 1)
self.top_text_space = QSpinBox(self.gridLayoutWidget_2)
self.top_text_space.setObjectName(u"top_text_space")
self.top_text_space.setMinimum(0)
self.top_text_space.setValue(0)
self.gridLayout_2.addWidget(self.top_text_space, 5, 1, 1, 1)
self.bottom_text_content = QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_content.setObjectName(u"bottom_text_content")
self.gridLayout_2.addWidget(self.bottom_text_content, 10, 1, 1, 1)
self.horizontalLayout_7 = QHBoxLayout()
self.horizontalLayout_7.setObjectName(u"horizontalLayout_7")
self.bottom_text_size_w = QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_size_w.setObjectName(u"bottom_text_size_w")
self.horizontalLayout_7.addWidget(self.bottom_text_size_w)
self.bottom_text_size_h = QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_size_h.setObjectName(u"bottom_text_size_h")
self.horizontalLayout_7.addWidget(self.bottom_text_size_h)
self.gridLayout_2.addLayout(self.horizontalLayout_7, 9, 1, 1, 1)
self.horizontalLayout_10 = QHBoxLayout()
self.horizontalLayout_10.setObjectName(u"horizontalLayout_10")
self.inter_text_font_w = QLineEdit(self.gridLayoutWidget_2)
self.inter_text_font_w.setObjectName(u"inter_text_font_w")
self.horizontalLayout_10.addWidget(self.inter_text_font_w)
self.inter_text_font_h = QLineEdit(self.gridLayoutWidget_2)
self.inter_text_font_h.setObjectName(u"inter_text_font_h")
self.horizontalLayout_10.addWidget(self.inter_text_font_h)
self.gridLayout_2.addLayout(self.horizontalLayout_10, 26, 1, 1, 1)
self.label_34 = QLabel(self.gridLayoutWidget_2)
self.label_34.setObjectName(u"label_34")
self.gridLayout_2.addWidget(self.label_34, 20, 0, 1, 1)
self.label_21 = QLabel(self.gridLayoutWidget_2)
self.label_21.setObjectName(u"label_21")
self.gridLayout_2.addWidget(self.label_21, 12, 0, 1, 1)
self.inter_text_space = QSpinBox(self.gridLayoutWidget_2)
self.inter_text_space.setObjectName(u"inter_text_space")
self.inter_text_space.setMinimum(0)
self.inter_text_space.setValue(0)
self.gridLayout_2.addWidget(self.inter_text_space, 20, 1, 1, 1)
self.inter_text_on = QCheckBox(self.gridLayoutWidget_2)
self.inter_text_on.setObjectName(u"inter_text_on")
self.inter_text_on.setChecked(True)
self.gridLayout_2.addWidget(self.inter_text_on, 17, 1, 1, 1)
self.label_22 = QLabel(self.gridLayoutWidget_2)
self.label_22.setObjectName(u"label_22")
self.gridLayout_2.addWidget(self.label_22, 7, 0, 1, 1)
self.label_46 = QLabel(self.gridLayoutWidget_2)
self.label_46.setObjectName(u"label_46")
self.gridLayout_2.addWidget(self.label_46, 27, 0, 1, 1)
self.label_33 = QLabel(self.gridLayoutWidget_2)
self.label_33.setObjectName(u"label_33")
self.gridLayout_2.addWidget(self.label_33, 5, 0, 1, 1)
self.label_32 = QLabel(self.gridLayoutWidget_2)
self.label_32.setObjectName(u"label_32")
self.gridLayout_2.addWidget(self.label_32, 19, 0, 1, 1)
self.horizontalLayout_9 = QHBoxLayout()
self.horizontalLayout_9.setObjectName(u"horizontalLayout_9")
self.inter_text_size_w = QLineEdit(self.gridLayoutWidget_2)
self.inter_text_size_w.setObjectName(u"inter_text_size_w")
self.horizontalLayout_9.addWidget(self.inter_text_size_w)
self.inter_text_size_h = QLineEdit(self.gridLayoutWidget_2)
self.inter_text_size_h.setObjectName(u"inter_text_size_h")
self.horizontalLayout_9.addWidget(self.inter_text_size_h)
self.gridLayout_2.addLayout(self.horizontalLayout_9, 19, 1, 1, 1)
self.horizontalLayout_6 = QHBoxLayout()
self.horizontalLayout_6.setObjectName(u"horizontalLayout_6")
self.top_text_size_w = QLineEdit(self.gridLayoutWidget_2)
self.top_text_size_w.setObjectName(u"top_text_size_w")
self.horizontalLayout_6.addWidget(self.top_text_size_w)
self.top_text_size_h = QLineEdit(self.gridLayoutWidget_2)
self.top_text_size_h.setObjectName(u"top_text_size_h")
self.horizontalLayout_6.addWidget(self.top_text_size_h)
self.gridLayout_2.addLayout(self.horizontalLayout_6, 2, 1, 1, 1)
self.label_35 = QLabel(self.gridLayoutWidget_2)
self.label_35.setObjectName(u"label_35")
self.gridLayout_2.addWidget(self.label_35, 13, 0, 1, 1)
self.bottom_text_shape = QComboBox(self.gridLayoutWidget_2)
self.bottom_text_shape.addItem("")
self.bottom_text_shape.addItem("")
self.bottom_text_shape.addItem("")
self.bottom_text_shape.setObjectName(u"bottom_text_shape")
self.gridLayout_2.addWidget(self.bottom_text_shape, 8, 1, 1, 1)
self.label_25 = QLabel(self.gridLayoutWidget_2)
self.label_25.setObjectName(u"label_25")
self.gridLayout_2.addWidget(self.label_25, 10, 0, 1, 1)
self.inter_text_content = QLineEdit(self.gridLayoutWidget_2)
self.inter_text_content.setObjectName(u"inter_text_content")
self.gridLayout_2.addWidget(self.inter_text_content, 23, 1, 1, 1)
self.inter_text_font = QLineEdit(self.gridLayoutWidget_2)
self.inter_text_font.setObjectName(u"inter_text_font")
self.gridLayout_2.addWidget(self.inter_text_font, 28, 1, 1, 1)
self.label_24 = QLabel(self.gridLayoutWidget_2)
self.label_24.setObjectName(u"label_24")
self.gridLayout_2.addWidget(self.label_24, 8, 0, 1, 1)
self.label_28 = QLabel(self.gridLayoutWidget_2)
self.label_28.setObjectName(u"label_28")
self.gridLayout_2.addWidget(self.label_28, 23, 0, 1, 1)
self.bottom_text_space = QSpinBox(self.gridLayoutWidget_2)
self.bottom_text_space.setObjectName(u"bottom_text_space")
self.bottom_text_space.setMinimum(0)
self.bottom_text_space.setValue(0)
self.gridLayout_2.addWidget(self.bottom_text_space, 13, 1, 1, 1)
self.top_text_font = QLineEdit(self.gridLayoutWidget_2)
self.top_text_font.setObjectName(u"top_text_font")
self.gridLayout_2.addWidget(self.top_text_font, 6, 1, 1, 1)
self.label_5 = QLabel(self.gridLayoutWidget_2)
self.label_5.setObjectName(u"label_5")
self.gridLayout_2.addWidget(self.label_5, 6, 0, 1, 1)
self.label_3 = QLabel(self.gridLayoutWidget_2)
self.label_3.setObjectName(u"label_3")
self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1)
self.inter_text_shape = QComboBox(self.gridLayoutWidget_2)
self.inter_text_shape.addItem("")
self.inter_text_shape.addItem("")
self.inter_text_shape.addItem("")
self.inter_text_shape.setObjectName(u"inter_text_shape")
self.gridLayout_2.addWidget(self.inter_text_shape, 18, 1, 1, 1)
self.groupBox_3 = QGroupBox(Dialog)
self.groupBox_3.setObjectName(u"groupBox_3")
self.groupBox_3.setGeometry(QRect(30, 10, 251, 421))
self.widget = QWidget(self.groupBox_3)
self.widget.setObjectName(u"widget")
self.widget.setGeometry(QRect(10, 20, 230, 435))
self.formLayout_2 = QFormLayout(self.widget)
self.formLayout_2.setObjectName(u"formLayout_2")
self.formLayout_2.setContentsMargins(0, 0, 0, 0)
self.label = QLabel(self.widget)
self.label.setObjectName(u"label")
self.formLayout_2.setWidget(0, QFormLayout.LabelRole, self.label)
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.image_w = QLineEdit(self.widget)
self.image_w.setObjectName(u"image_w")
self.horizontalLayout.addWidget(self.image_w)
self.image_h = QLineEdit(self.widget)
self.image_h.setObjectName(u"image_h")
self.horizontalLayout.addWidget(self.image_h)
self.formLayout_2.setLayout(0, QFormLayout.FieldRole, self.horizontalLayout)
self.label_2 = QLabel(self.widget)
self.label_2.setObjectName(u"label_2")
self.formLayout_2.setWidget(1, QFormLayout.LabelRole, self.label_2)
self.gridLayout_3 = QGridLayout()
self.gridLayout_3.setObjectName(u"gridLayout_3")
self.img_g = QLineEdit(self.widget)
self.img_g.setObjectName(u"img_g")
self.gridLayout_3.addWidget(self.img_g, 0, 1, 1, 1)
self.img_r = QLineEdit(self.widget)
self.img_r.setObjectName(u"img_r")
self.gridLayout_3.addWidget(self.img_r, 0, 0, 1, 1)
self.img_b = QLineEdit(self.widget)
self.img_b.setObjectName(u"img_b")
self.gridLayout_3.addWidget(self.img_b, 0, 2, 1, 1)
self.formLayout_2.setLayout(1, QFormLayout.FieldRole, self.gridLayout_3)
self.resize_factor = QSpinBox(self.widget)
self.resize_factor.setObjectName(u"resize_factor")
self.resize_factor.setMinimum(0)
self.resize_factor.setValue(2)
self.formLayout_2.setWidget(2, QFormLayout.FieldRole, self.resize_factor)
self.label_9 = QLabel(self.widget)
self.label_9.setObjectName(u"label_9")
self.formLayout_2.setWidget(3, QFormLayout.LabelRole, self.label_9)
self.out_on = QCheckBox(self.widget)
self.out_on.setObjectName(u"out_on")
self.out_on.setChecked(True)
self.formLayout_2.setWidget(3, QFormLayout.FieldRole, self.out_on)
self.label_4 = QLabel(self.widget)
self.label_4.setObjectName(u"label_4")
self.formLayout_2.setWidget(4, QFormLayout.LabelRole, self.label_4)
self.out_shape = QComboBox(self.widget)
self.out_shape.addItem("")
self.out_shape.addItem("")
self.out_shape.addItem("")
self.out_shape.setObjectName(u"out_shape")
self.formLayout_2.setWidget(4, QFormLayout.FieldRole, self.out_shape)
self.label_8 = QLabel(self.widget)
self.label_8.setObjectName(u"label_8")
self.formLayout_2.setWidget(5, QFormLayout.LabelRole, self.label_8)
self.horizontalLayout_2 = QHBoxLayout()
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.out_size_w = QLineEdit(self.widget)
self.out_size_w.setObjectName(u"out_size_w")
self.horizontalLayout_2.addWidget(self.out_size_w)
self.out_size_h = QLineEdit(self.widget)
self.out_size_h.setObjectName(u"out_size_h")
self.horizontalLayout_2.addWidget(self.out_size_h)
self.formLayout_2.setLayout(5, QFormLayout.FieldRole, self.horizontalLayout_2)
self.label_7 = QLabel(self.widget)
self.label_7.setObjectName(u"label_7")
self.formLayout_2.setWidget(6, QFormLayout.LabelRole, self.label_7)
self.out_width = QSpinBox(self.widget)
self.out_width.setObjectName(u"out_width")
self.out_width.setMinimum(0)
self.out_width.setValue(7)
self.formLayout_2.setWidget(6, QFormLayout.FieldRole, self.out_width)
self.label_6 = QLabel(self.widget)
self.label_6.setObjectName(u"label_6")
self.formLayout_2.setWidget(7, QFormLayout.LabelRole, self.label_6)
self.border_on = QCheckBox(self.widget)
self.border_on.setObjectName(u"border_on")
self.border_on.setChecked(True)
self.formLayout_2.setWidget(7, QFormLayout.FieldRole, self.border_on)
self.label_10 = QLabel(self.widget)
self.label_10.setObjectName(u"label_10")
self.formLayout_2.setWidget(8, QFormLayout.LabelRole, self.label_10)
self.border_shape = QComboBox(self.widget)
self.border_shape.addItem("")
self.border_shape.addItem("")
self.border_shape.addItem("")
self.border_shape.setObjectName(u"border_shape")
self.formLayout_2.setWidget(8, QFormLayout.FieldRole, self.border_shape)
self.label_14 = QLabel(self.widget)
self.label_14.setObjectName(u"label_14")
self.formLayout_2.setWidget(9, QFormLayout.LabelRole, self.label_14)
self.horizontalLayout_3 = QHBoxLayout()
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.border_size_w = QLineEdit(self.widget)
self.border_size_w.setObjectName(u"border_size_w")
self.horizontalLayout_3.addWidget(self.border_size_w)
self.border_size_h = QLineEdit(self.widget)
self.border_size_h.setObjectName(u"border_size_h")
self.horizontalLayout_3.addWidget(self.border_size_h)
self.formLayout_2.setLayout(9, QFormLayout.FieldRole, self.horizontalLayout_3)
self.label_15 = QLabel(self.widget)
self.label_15.setObjectName(u"label_15")
self.formLayout_2.setWidget(10, QFormLayout.LabelRole, self.label_15)
self.border_width = QSpinBox(self.widget)
self.border_width.setObjectName(u"border_width")
self.border_width.setMinimum(0)
self.border_width.setValue(1)
self.formLayout_2.setWidget(10, QFormLayout.FieldRole, self.border_width)
self.label_11 = QLabel(self.widget)
self.label_11.setObjectName(u"label_11")
self.formLayout_2.setWidget(11, QFormLayout.LabelRole, self.label_11)
self.in_on = QCheckBox(self.widget)
self.in_on.setObjectName(u"in_on")
self.in_on.setChecked(False)
self.formLayout_2.setWidget(11, QFormLayout.FieldRole, self.in_on)
self.label_12 = QLabel(self.widget)
self.label_12.setObjectName(u"label_12")
self.formLayout_2.setWidget(12, QFormLayout.LabelRole, self.label_12)
self.in_shape = QComboBox(self.widget)
self.in_shape.addItem("")
self.in_shape.addItem("")
self.in_shape.addItem("")
self.in_shape.setObjectName(u"in_shape")
self.formLayout_2.setWidget(12, QFormLayout.FieldRole, self.in_shape)
self.label_16 = QLabel(self.widget)
self.label_16.setObjectName(u"label_16")
self.formLayout_2.setWidget(13, QFormLayout.LabelRole, self.label_16)
self.horizontalLayout_4 = QHBoxLayout()
self.horizontalLayout_4.setObjectName(u"horizontalLayout_4")
self.in_size_w = QLineEdit(self.widget)
self.in_size_w.setObjectName(u"in_size_w")
self.horizontalLayout_4.addWidget(self.in_size_w)
self.in_size_h = QLineEdit(self.widget)
self.in_size_h.setObjectName(u"in_size_h")
self.horizontalLayout_4.addWidget(self.in_size_h)
self.formLayout_2.setLayout(13, QFormLayout.FieldRole, self.horizontalLayout_4)
self.label_17 = QLabel(self.widget)
self.label_17.setObjectName(u"label_17")
self.formLayout_2.setWidget(14, QFormLayout.LabelRole, self.label_17)
self.in_width = QSpinBox(self.widget)
self.in_width.setObjectName(u"in_width")
self.in_width.setMinimum(0)
self.in_width.setValue(1)
self.formLayout_2.setWidget(14, QFormLayout.FieldRole, self.in_width)
self.label_45 = QLabel(self.widget)
self.label_45.setObjectName(u"label_45")
self.formLayout_2.setWidget(2, QFormLayout.LabelRole, self.label_45)
self.gridLayoutWidget = QWidget(Dialog)
self.gridLayoutWidget.setObjectName(u"gridLayoutWidget")
self.gridLayoutWidget.setGeometry(QRect(320, 670, 231, 51))
self.gridLayout = QGridLayout(self.gridLayoutWidget)
self.gridLayout.setObjectName(u"gridLayout")
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.update_config = QPushButton(self.gridLayoutWidget)
self.update_config.setObjectName(u"update_config")
self.gridLayout.addWidget(self.update_config, 0, 0, 1, 1)
self.image_draw = QPushButton(self.gridLayoutWidget)
self.image_draw.setObjectName(u"image_draw")
self.gridLayout.addWidget(self.image_draw, 0, 1, 1, 1)
self.save_path = QLineEdit(self.gridLayoutWidget)
self.save_path.setObjectName(u"save_path")
self.gridLayout.addWidget(self.save_path, 1, 0, 1, 1)
self.single_save = QPushButton(self.gridLayoutWidget)
self.single_save.setObjectName(u"single_save")
self.gridLayout.addWidget(self.single_save, 1, 1, 1, 1)
self.retranslateUi(Dialog)
QMetaObject.connectSlotsByName(Dialog)
# setupUi
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QCoreApplication.translate("Dialog", u"Dialog", None))
self.batch_save.setText(QCoreApplication.translate("Dialog", u"\u6279\u91cf\u4fdd\u5b58", None))
self.line_label_on.setText(QCoreApplication.translate("Dialog", u"\u6587\u672c\u884c\u6807\u6ce8", None))
self.label_47.setText(QCoreApplication.translate("Dialog", u"\u6807\u6ce8\u6570\u91cf", None))
self.clear_dir.setText(QCoreApplication.translate("Dialog", u"\u6e05\u7a7a\u6587\u4ef6\u5939", None))
self.groupBox.setTitle(QCoreApplication.translate("Dialog", u"\u6279\u91cf\u914d\u7f6e\u53c2\u6570", None))
self.bottom_random.setText(QCoreApplication.translate("Dialog", u"\u968f\u673a", None))
self.label_36.setText(QCoreApplication.translate("Dialog", u"\u4e0a\u65b9\u6587\u5b57", None))
self.label_43.setText(QCoreApplication.translate("Dialog", u"\u4fdd\u5b58\u6587\u4ef6\u5939", None))
self.inter_filepath.setText(QCoreApplication.translate("Dialog", u"content/inter.txt", None))
self.save_dir.setText(QCoreApplication.translate("Dialog", u"out", None))
self.label_42.setText(QCoreApplication.translate("Dialog", u"\u6587\u4ef6\u8def\u5f84(\u968f\u673a\u65e0\u6548)", None))
self.label_38.setText(QCoreApplication.translate("Dialog", u"\u4e0b\u65b9\u6587\u5b57", None))
self.label_41.setText(QCoreApplication.translate("Dialog", u"\u5185\u90e8\u6587\u5b57", None))
self.bottom_filepath.setText(QCoreApplication.translate("Dialog", u"content/bottom.txt", None))
self.label_37.setText(QCoreApplication.translate("Dialog", u"\u6570\u91cf", None))
self.label_40.setText(QCoreApplication.translate("Dialog", u"\u6587\u4ef6\u8def\u5f84(\u968f\u673a\u65e0\u6548)", None))
self.label_39.setText(QCoreApplication.translate("Dialog", u"\u6587\u4ef6\u8def\u5f84(\u968f\u673a\u65e0\u6548)", None))
self.top_random.setText(QCoreApplication.translate("Dialog", u"\u968f\u673a", None))
self.inter_random.setText(QCoreApplication.translate("Dialog", u"\u968f\u673a", None))
self.batch_nums.setText(QCoreApplication.translate("Dialog", u"1", None))
self.label_44.setText(QCoreApplication.translate("Dialog", u"\u6587\u4ef6\u5939\u524d\u7f00", None))
self.file_pre.setText(QCoreApplication.translate("Dialog", u"{shape}_{num}_{time}", None))
self.top_filepath.setText(QCoreApplication.translate("Dialog", u"content/top.txt", None))
self.groupBox_2.setTitle(QCoreApplication.translate("Dialog", u"\u6587\u5b57\u4fe1\u606f\u914d\u7f6e", None))
self.top_text_content.setText(QCoreApplication.translate("Dialog", u"\u798f\u5efa\u67d0\u67d0\u67d0\u6709\u9650\u516c\u53f8", None))
self.label_23.setText(QCoreApplication.translate("Dialog", u"\u5b57\u4f53", None))
self.label_19.setText(QCoreApplication.translate("Dialog", u"\u6587\u672c\u884c\u5bbd\u5ea6", None))
self.label_30.setText(QCoreApplication.translate("Dialog", u"\u5f62\u72b6", None))
self.label_27.setText(QCoreApplication.translate("Dialog", u"\u4e2d\u95f4\u6587\u5b57", None))
self.label_29.setText(QCoreApplication.translate("Dialog", u"\u6587\u5b57\u5bbd\u9ad8", None))
self.top_text_on.setText(QCoreApplication.translate("Dialog", u"\u542f\u7528", None))
self.bottom_text_font.setText(QCoreApplication.translate("Dialog", u"./fonts/\u5b8b\u4f53.TTF", None))
self.label_13.setText(QCoreApplication.translate("Dialog", u"\u6587\u5b57\u5bbd\u9ad8", None))
self.bottom_text_on.setText(QCoreApplication.translate("Dialog", u"\u542f\u7528", None))
self.label_18.setText(QCoreApplication.translate("Dialog", u"\u5185\u5bb9", None))
self.label_20.setText(QCoreApplication.translate("Dialog", u"\u5f62\u72b6", None))
self.label_26.setText(QCoreApplication.translate("Dialog", u"\u6587\u672c\u884c\u5bbd\u5ea6", None))
self.top_text_shape.setItemText(0, QCoreApplication.translate("Dialog", u"circle", None))
self.top_text_shape.setItemText(1, QCoreApplication.translate("Dialog", u"rectangle", None))
self.top_text_shape.setItemText(2, QCoreApplication.translate("Dialog", u"oval", None))
self.label_31.setText(QCoreApplication.translate("Dialog", u"\u5b57\u4f53", None))
self.top_text_font_w.setText(QCoreApplication.translate("Dialog", u"21", None))
self.top_text_font_h.setText(QCoreApplication.translate("Dialog", u"24", None))
self.bottom_text_font_w.setText(QCoreApplication.translate("Dialog", u"10", None))
self.bottom_text_font_h.setText(QCoreApplication.translate("Dialog", u"15", None))
self.bottom_text_content.setText(QCoreApplication.translate("Dialog", u"123456789012X", None))
self.bottom_text_size_w.setText(QCoreApplication.translate("Dialog", u"123", None))
self.bottom_text_size_h.setText(QCoreApplication.translate("Dialog", u"73", None))
self.inter_text_font_w.setText(QCoreApplication.translate("Dialog", u"27", None))
self.inter_text_font_h.setText(QCoreApplication.translate("Dialog", u"31", None))
self.label_34.setText(QCoreApplication.translate("Dialog", u"\u5b57\u95f4\u8ddd", None))
self.label_21.setText(QCoreApplication.translate("Dialog", u"\u6587\u5b57\u5bbd\u9ad8", None))
self.inter_text_on.setText(QCoreApplication.translate("Dialog", u"\u542f\u7528", None))
self.label_22.setText(QCoreApplication.translate("Dialog", u"\u4e0b\u65b9\u6587\u5b57", None))
self.label_46.setText(QCoreApplication.translate("Dialog", u"\u6587\u5b57\u504f\u79fb", None))
self.label_33.setText(QCoreApplication.translate("Dialog", u"\u5b57\u95f4\u8ddd", None))
self.label_32.setText(QCoreApplication.translate("Dialog", u"\u6587\u672c\u884c\u5bbd\u5ea6", None))
self.inter_text_size_w.setText(QCoreApplication.translate("Dialog", u"125", None))
self.inter_text_size_h.setText(QCoreApplication.translate("Dialog", u"75", None))
self.top_text_size_w.setText(QCoreApplication.translate("Dialog", u"123", None))
self.top_text_size_h.setText(QCoreApplication.translate("Dialog", u"74", None))
self.label_35.setText(QCoreApplication.translate("Dialog", u"\u5b57\u95f4\u8ddd", None))
self.bottom_text_shape.setItemText(0, QCoreApplication.translate("Dialog", u"circle", None))
self.bottom_text_shape.setItemText(1, QCoreApplication.translate("Dialog", u"rectangle", None))
self.bottom_text_shape.setItemText(2, QCoreApplication.translate("Dialog", u"oval", None))
self.label_25.setText(QCoreApplication.translate("Dialog", u"\u5185\u5bb9", None))
self.inter_text_content.setText(QCoreApplication.translate("Dialog", u"\u8d22\u52a1\u4e13\u7528\u7ae0", None))
self.inter_text_font.setText(QCoreApplication.translate("Dialog", u"./fonts/\u5b8b\u4f53.TTF", None))
self.label_24.setText(QCoreApplication.translate("Dialog", u"\u5f62\u72b6", None))
self.label_28.setText(QCoreApplication.translate("Dialog", u"\u5185\u5bb9", None))
self.top_text_font.setText(QCoreApplication.translate("Dialog", u"./fonts/\u5b8b\u4f53.TTF", None))
self.label_5.setText(QCoreApplication.translate("Dialog", u"\u5b57\u4f53", None))
self.label_3.setText(QCoreApplication.translate("Dialog", u"\u4e0a\u65b9\u6587\u5b57", None))
self.inter_text_shape.setItemText(0, QCoreApplication.translate("Dialog", u"rectangle", None))
self.inter_text_shape.setItemText(1, QCoreApplication.translate("Dialog", u"circle", None))
self.inter_text_shape.setItemText(2, QCoreApplication.translate("Dialog", u"oval", None))
self.groupBox_3.setTitle(QCoreApplication.translate("Dialog", u"\u56fe\u7247\u4fe1\u606f\u914d\u7f6e", None))
self.label.setText(QCoreApplication.translate("Dialog", u"\u56fe\u50cf\u5927\u5c0fwh", None))
self.image_w.setText(QCoreApplication.translate("Dialog", u"310", None))
self.image_h.setText(QCoreApplication.translate("Dialog", u"310", None))
self.label_2.setText(QCoreApplication.translate("Dialog", u"\u989c\u8272RGB", None))
self.img_g.setText(QCoreApplication.translate("Dialog", u"0", None))
self.img_r.setText(QCoreApplication.translate("Dialog", u"255", None))
self.img_b.setText(QCoreApplication.translate("Dialog", u"0", None))
self.label_9.setText(QCoreApplication.translate("Dialog", u"\u5916\u8f6e\u5ed3\u914d\u7f6e", None))
self.out_on.setText(QCoreApplication.translate("Dialog", u"\u542f\u7528", None))
self.label_4.setText(QCoreApplication.translate("Dialog", u"\u5f62\u72b6", None))
self.out_shape.setItemText(0, QCoreApplication.translate("Dialog", u"circle", None))
self.out_shape.setItemText(1, QCoreApplication.translate("Dialog", u"rectangle", None))
self.out_shape.setItemText(2, QCoreApplication.translate("Dialog", u"oval", None))
self.label_8.setText(QCoreApplication.translate("Dialog", u"\u5927\u5c0f", None))
self.out_size_w.setText(QCoreApplication.translate("Dialog", u"150", None))
self.out_size_h.setText(QCoreApplication.translate("Dialog", u"100", None))
self.label_7.setText(QCoreApplication.translate("Dialog", u"\u7ebf\u7c97", None))
self.label_6.setText(QCoreApplication.translate("Dialog", u"\u8fb9\u754c\u7ebf\u914d\u7f6e", None))
self.border_on.setText(QCoreApplication.translate("Dialog", u"\u542f\u7528", None))
self.label_10.setText(QCoreApplication.translate("Dialog", u"\u5f62\u72b6", None))
self.border_shape.setItemText(0, QCoreApplication.translate("Dialog", u"circle", None))
self.border_shape.setItemText(1, QCoreApplication.translate("Dialog", u"rectangle", None))
self.border_shape.setItemText(2, QCoreApplication.translate("Dialog", u"oval", None))
self.label_14.setText(QCoreApplication.translate("Dialog", u"\u5927\u5c0f", None))
self.border_size_w.setText(QCoreApplication.translate("Dialog", u"140", None))
self.border_size_h.setText(QCoreApplication.translate("Dialog", u"90", None))
self.label_15.setText(QCoreApplication.translate("Dialog", u"\u7ebf\u7c97", None))
self.label_11.setText(QCoreApplication.translate("Dialog", u"\u5185\u90e8\u7ebf\u914d\u7f6e", None))
self.in_on.setText(QCoreApplication.translate("Dialog", u"\u542f\u7528", None))
self.label_12.setText(QCoreApplication.translate("Dialog", u"\u5f62\u72b6", None))
self.in_shape.setItemText(0, QCoreApplication.translate("Dialog", u"circle", None))
self.in_shape.setItemText(1, QCoreApplication.translate("Dialog", u"rectangle", None))
self.in_shape.setItemText(2, QCoreApplication.translate("Dialog", u"oval", None))
self.label_16.setText(QCoreApplication.translate("Dialog", u"\u5927\u5c0f", None))
self.in_size_w.setText(QCoreApplication.translate("Dialog", u"100", None))
self.in_size_h.setText(QCoreApplication.translate("Dialog", u"75", None))
self.label_17.setText(QCoreApplication.translate("Dialog", u"\u7ebf\u7c97", None))
self.label_45.setText(QCoreApplication.translate("Dialog", u"\u6e05\u6670\u5ea6", None))
self.update_config.setText(QCoreApplication.translate("Dialog", u"\u914d\u7f6e\u66f4\u65b0", None))
self.image_draw.setText(QCoreApplication.translate("Dialog", u"\u751f\u6210", None))
self.save_path.setText(QCoreApplication.translate("Dialog", u"seal.png", None))
self.single_save.setText(QCoreApplication.translate("Dialog", u"\u5355\u5f20\u4fdd\u5b58", None))
# retranslateUi
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1127, 774)
self.image_win = QtWidgets.QGraphicsView(Dialog)
self.image_win.setGeometry(QtCore.QRect(580, 20, 401, 361))
self.image_win.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.image_win.setObjectName("image_win")
self.gridLayoutWidget_3 = QtWidgets.QWidget(Dialog)
self.gridLayoutWidget_3.setGeometry(QtCore.QRect(40, 700, 252, 56))
self.gridLayoutWidget_3.setObjectName("gridLayoutWidget_3")
self.gridLayout_5 = QtWidgets.QGridLayout(self.gridLayoutWidget_3)
self.gridLayout_5.setContentsMargins(0, 0, 0, 0)
self.gridLayout_5.setObjectName("gridLayout_5")
self.batch_save = QtWidgets.QPushButton(self.gridLayoutWidget_3)
self.batch_save.setObjectName("batch_save")
self.gridLayout_5.addWidget(self.batch_save, 1, 1, 1, 1)
self.label_nums = QtWidgets.QSpinBox(self.gridLayoutWidget_3)
self.label_nums.setMinimum(-99)
self.label_nums.setStepType(QtWidgets.QAbstractSpinBox.DefaultStepType)
self.label_nums.setProperty("value", 28)
self.label_nums.setObjectName("label_nums")
self.gridLayout_5.addWidget(self.label_nums, 0, 1, 1, 1)
self.line_label_on = QtWidgets.QCheckBox(self.gridLayoutWidget_3)
self.line_label_on.setChecked(True)
self.line_label_on.setObjectName("line_label_on")
self.gridLayout_5.addWidget(self.line_label_on, 1, 0, 1, 1)
self.label_47 = QtWidgets.QLabel(self.gridLayoutWidget_3)
self.label_47.setObjectName("label_47")
self.gridLayout_5.addWidget(self.label_47, 0, 0, 1, 1)
self.clear_dir = QtWidgets.QPushButton(self.gridLayoutWidget_3)
self.clear_dir.setObjectName("clear_dir")
self.gridLayout_5.addWidget(self.clear_dir, 0, 2, 1, 1)
self.groupBox = QtWidgets.QGroupBox(Dialog)
self.groupBox.setGeometry(QtCore.QRect(30, 430, 251, 271))
self.groupBox.setObjectName("groupBox")
self.gridLayoutWidget_4 = QtWidgets.QWidget(self.groupBox)
self.gridLayoutWidget_4.setGeometry(QtCore.QRect(10, 20, 231, 236))
self.gridLayoutWidget_4.setObjectName("gridLayoutWidget_4")
self.gridLayout_4 = QtWidgets.QGridLayout(self.gridLayoutWidget_4)
self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
self.gridLayout_4.setObjectName("gridLayout_4")
self.bottom_random = QtWidgets.QCheckBox(self.gridLayoutWidget_4)
self.bottom_random.setChecked(True)
self.bottom_random.setObjectName("bottom_random")
self.gridLayout_4.addWidget(self.bottom_random, 5, 1, 1, 1)
self.label_36 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_36.setObjectName("label_36")
self.gridLayout_4.addWidget(self.label_36, 3, 0, 1, 1)
self.label_43 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_43.setObjectName("label_43")
self.gridLayout_4.addWidget(self.label_43, 1, 0, 1, 1)
self.inter_filepath = QtWidgets.QLineEdit(self.gridLayoutWidget_4)
self.inter_filepath.setObjectName("inter_filepath")
self.gridLayout_4.addWidget(self.inter_filepath, 8, 1, 1, 1)
self.save_dir = QtWidgets.QLineEdit(self.gridLayoutWidget_4)
self.save_dir.setObjectName("save_dir")
self.gridLayout_4.addWidget(self.save_dir, 1, 1, 1, 1)
self.label_42 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_42.setObjectName("label_42")
self.gridLayout_4.addWidget(self.label_42, 8, 0, 1, 1)
self.label_38 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_38.setObjectName("label_38")
self.gridLayout_4.addWidget(self.label_38, 5, 0, 1, 1)
self.label_41 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_41.setObjectName("label_41")
self.gridLayout_4.addWidget(self.label_41, 7, 0, 1, 1)
self.bottom_filepath = QtWidgets.QLineEdit(self.gridLayoutWidget_4)
self.bottom_filepath.setObjectName("bottom_filepath")
self.gridLayout_4.addWidget(self.bottom_filepath, 6, 1, 1, 1)
self.label_37 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_37.setObjectName("label_37")
self.gridLayout_4.addWidget(self.label_37, 0, 0, 1, 1)
self.label_40 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_40.setObjectName("label_40")
self.gridLayout_4.addWidget(self.label_40, 6, 0, 1, 1)
self.label_39 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_39.setObjectName("label_39")
self.gridLayout_4.addWidget(self.label_39, 4, 0, 1, 1)
self.top_random = QtWidgets.QCheckBox(self.gridLayoutWidget_4)
self.top_random.setChecked(True)
self.top_random.setObjectName("top_random")
self.gridLayout_4.addWidget(self.top_random, 3, 1, 1, 1)
self.inter_random = QtWidgets.QCheckBox(self.gridLayoutWidget_4)
self.inter_random.setChecked(True)
self.inter_random.setObjectName("inter_random")
self.gridLayout_4.addWidget(self.inter_random, 7, 1, 1, 1)
self.batch_nums = QtWidgets.QLineEdit(self.gridLayoutWidget_4)
self.batch_nums.setObjectName("batch_nums")
self.gridLayout_4.addWidget(self.batch_nums, 0, 1, 1, 1)
self.label_44 = QtWidgets.QLabel(self.gridLayoutWidget_4)
self.label_44.setObjectName("label_44")
self.gridLayout_4.addWidget(self.label_44, 2, 0, 1, 1)
self.file_pre = QtWidgets.QLineEdit(self.gridLayoutWidget_4)
self.file_pre.setObjectName("file_pre")
self.gridLayout_4.addWidget(self.file_pre, 2, 1, 1, 1)
self.top_filepath = QtWidgets.QLineEdit(self.gridLayoutWidget_4)
self.top_filepath.setObjectName("top_filepath")
self.gridLayout_4.addWidget(self.top_filepath, 4, 1, 1, 1)
self.groupBox_2 = QtWidgets.QGroupBox(Dialog)
self.groupBox_2.setGeometry(QtCore.QRect(310, 10, 251, 651))
self.groupBox_2.setObjectName("groupBox_2")
self.gridLayoutWidget_2 = QtWidgets.QWidget(self.groupBox_2)
self.gridLayoutWidget_2.setGeometry(QtCore.QRect(10, 20, 231, 625))
self.gridLayoutWidget_2.setObjectName("gridLayoutWidget_2")
self.gridLayout_2 = QtWidgets.QGridLayout(self.gridLayoutWidget_2)
self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
self.gridLayout_2.setObjectName("gridLayout_2")
self.top_text_content = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.top_text_content.setObjectName("top_text_content")
self.gridLayout_2.addWidget(self.top_text_content, 3, 1, 1, 1)
self.label_23 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_23.setObjectName("label_23")
self.gridLayout_2.addWidget(self.label_23, 16, 0, 1, 1)
self.label_19 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_19.setObjectName("label_19")
self.gridLayout_2.addWidget(self.label_19, 2, 0, 1, 1)
self.label_30 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_30.setObjectName("label_30")
self.gridLayout_2.addWidget(self.label_30, 18, 0, 1, 1)
self.label_27 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_27.setObjectName("label_27")
self.gridLayout_2.addWidget(self.label_27, 17, 0, 1, 1)
self.label_29 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_29.setObjectName("label_29")
self.gridLayout_2.addWidget(self.label_29, 26, 0, 1, 1)
self.top_text_on = QtWidgets.QCheckBox(self.gridLayoutWidget_2)
self.top_text_on.setChecked(True)
self.top_text_on.setObjectName("top_text_on")
self.gridLayout_2.addWidget(self.top_text_on, 0, 1, 1, 1)
self.bottom_text_font = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_font.setObjectName("bottom_text_font")
self.gridLayout_2.addWidget(self.bottom_text_font, 16, 1, 1, 1)
self.label_13 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_13.setObjectName("label_13")
self.gridLayout_2.addWidget(self.label_13, 4, 0, 1, 1)
self.bottom_text_on = QtWidgets.QCheckBox(self.gridLayoutWidget_2)
self.bottom_text_on.setChecked(True)
self.bottom_text_on.setObjectName("bottom_text_on")
self.gridLayout_2.addWidget(self.bottom_text_on, 7, 1, 1, 1)
self.label_18 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_18.setObjectName("label_18")
self.gridLayout_2.addWidget(self.label_18, 3, 0, 1, 1)
self.label_20 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_20.setObjectName("label_20")
self.gridLayout_2.addWidget(self.label_20, 1, 0, 1, 1)
self.label_26 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_26.setObjectName("label_26")
self.gridLayout_2.addWidget(self.label_26, 9, 0, 1, 1)
self.top_text_shape = QtWidgets.QComboBox(self.gridLayoutWidget_2)
self.top_text_shape.setObjectName("top_text_shape")
self.top_text_shape.addItem("")
self.top_text_shape.addItem("")
self.top_text_shape.addItem("")
self.gridLayout_2.addWidget(self.top_text_shape, 1, 1, 1, 1)
self.label_31 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_31.setObjectName("label_31")
self.gridLayout_2.addWidget(self.label_31, 28, 0, 1, 1)
self.horizontalLayout_13 = QtWidgets.QHBoxLayout()
self.horizontalLayout_13.setObjectName("horizontalLayout_13")
self.inter_shift_y = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.inter_shift_y.setMinimum(-99)
self.inter_shift_y.setStepType(QtWidgets.QAbstractSpinBox.DefaultStepType)
self.inter_shift_y.setProperty("value", 6)
self.inter_shift_y.setObjectName("inter_shift_y")
self.horizontalLayout_13.addWidget(self.inter_shift_y)
self.gridLayout_2.addLayout(self.horizontalLayout_13, 27, 1, 1, 1)
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.top_text_font_w = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.top_text_font_w.setObjectName("top_text_font_w")
self.horizontalLayout_5.addWidget(self.top_text_font_w)
self.top_text_font_h = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.top_text_font_h.setObjectName("top_text_font_h")
self.horizontalLayout_5.addWidget(self.top_text_font_h)
self.gridLayout_2.addLayout(self.horizontalLayout_5, 4, 1, 1, 1)
self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
self.bottom_text_font_w = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_font_w.setObjectName("bottom_text_font_w")
self.horizontalLayout_8.addWidget(self.bottom_text_font_w)
self.bottom_text_font_h = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_font_h.setObjectName("bottom_text_font_h")
self.horizontalLayout_8.addWidget(self.bottom_text_font_h)
self.gridLayout_2.addLayout(self.horizontalLayout_8, 12, 1, 1, 1)
self.top_text_space = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.top_text_space.setMinimum(0)
self.top_text_space.setProperty("value", 0)
self.top_text_space.setObjectName("top_text_space")
self.gridLayout_2.addWidget(self.top_text_space, 5, 1, 1, 1)
self.bottom_text_content = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_content.setObjectName("bottom_text_content")
self.gridLayout_2.addWidget(self.bottom_text_content, 10, 1, 1, 1)
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.bottom_text_size_w = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_size_w.setObjectName("bottom_text_size_w")
self.horizontalLayout_7.addWidget(self.bottom_text_size_w)
self.bottom_text_size_h = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.bottom_text_size_h.setObjectName("bottom_text_size_h")
self.horizontalLayout_7.addWidget(self.bottom_text_size_h)
self.gridLayout_2.addLayout(self.horizontalLayout_7, 9, 1, 1, 1)
self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
self.horizontalLayout_10.setObjectName("horizontalLayout_10")
self.inter_text_font_w = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.inter_text_font_w.setObjectName("inter_text_font_w")
self.horizontalLayout_10.addWidget(self.inter_text_font_w)
self.inter_text_font_h = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.inter_text_font_h.setObjectName("inter_text_font_h")
self.horizontalLayout_10.addWidget(self.inter_text_font_h)
self.gridLayout_2.addLayout(self.horizontalLayout_10, 26, 1, 1, 1)
self.label_34 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_34.setObjectName("label_34")
self.gridLayout_2.addWidget(self.label_34, 20, 0, 1, 1)
self.label_21 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_21.setObjectName("label_21")
self.gridLayout_2.addWidget(self.label_21, 12, 0, 1, 1)
self.inter_text_space = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.inter_text_space.setMinimum(0)
self.inter_text_space.setProperty("value", 0)
self.inter_text_space.setObjectName("inter_text_space")
self.gridLayout_2.addWidget(self.inter_text_space, 20, 1, 1, 1)
self.inter_text_on = QtWidgets.QCheckBox(self.gridLayoutWidget_2)
self.inter_text_on.setChecked(True)
self.inter_text_on.setObjectName("inter_text_on")
self.gridLayout_2.addWidget(self.inter_text_on, 17, 1, 1, 1)
self.label_22 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_22.setObjectName("label_22")
self.gridLayout_2.addWidget(self.label_22, 7, 0, 1, 1)
self.label_46 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_46.setObjectName("label_46")
self.gridLayout_2.addWidget(self.label_46, 27, 0, 1, 1)
self.label_33 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_33.setObjectName("label_33")
self.gridLayout_2.addWidget(self.label_33, 5, 0, 1, 1)
self.label_32 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_32.setObjectName("label_32")
self.gridLayout_2.addWidget(self.label_32, 19, 0, 1, 1)
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.inter_text_size_w = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.inter_text_size_w.setObjectName("inter_text_size_w")
self.horizontalLayout_9.addWidget(self.inter_text_size_w)
self.inter_text_size_h = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.inter_text_size_h.setObjectName("inter_text_size_h")
self.horizontalLayout_9.addWidget(self.inter_text_size_h)
self.gridLayout_2.addLayout(self.horizontalLayout_9, 19, 1, 1, 1)
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
self.top_text_size_w = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.top_text_size_w.setObjectName("top_text_size_w")
self.horizontalLayout_6.addWidget(self.top_text_size_w)
self.top_text_size_h = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.top_text_size_h.setObjectName("top_text_size_h")
self.horizontalLayout_6.addWidget(self.top_text_size_h)
self.gridLayout_2.addLayout(self.horizontalLayout_6, 2, 1, 1, 1)
self.label_35 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_35.setObjectName("label_35")
self.gridLayout_2.addWidget(self.label_35, 13, 0, 1, 1)
self.bottom_text_shape = QtWidgets.QComboBox(self.gridLayoutWidget_2)
self.bottom_text_shape.setObjectName("bottom_text_shape")
self.bottom_text_shape.addItem("")
self.bottom_text_shape.addItem("")
self.bottom_text_shape.addItem("")
self.gridLayout_2.addWidget(self.bottom_text_shape, 8, 1, 1, 1)
self.label_25 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_25.setObjectName("label_25")
self.gridLayout_2.addWidget(self.label_25, 10, 0, 1, 1)
self.inter_text_content = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.inter_text_content.setObjectName("inter_text_content")
self.gridLayout_2.addWidget(self.inter_text_content, 23, 1, 1, 1)
self.inter_text_font = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.inter_text_font.setObjectName("inter_text_font")
self.gridLayout_2.addWidget(self.inter_text_font, 28, 1, 1, 1)
self.label_24 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_24.setObjectName("label_24")
self.gridLayout_2.addWidget(self.label_24, 8, 0, 1, 1)
self.label_28 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_28.setObjectName("label_28")
self.gridLayout_2.addWidget(self.label_28, 23, 0, 1, 1)
self.bottom_text_space = QtWidgets.QSpinBox(self.gridLayoutWidget_2)
self.bottom_text_space.setMinimum(0)
self.bottom_text_space.setProperty("value", 0)
self.bottom_text_space.setObjectName("bottom_text_space")
self.gridLayout_2.addWidget(self.bottom_text_space, 13, 1, 1, 1)
self.top_text_font = QtWidgets.QLineEdit(self.gridLayoutWidget_2)
self.top_text_font.setObjectName("top_text_font")
self.gridLayout_2.addWidget(self.top_text_font, 6, 1, 1, 1)
self.label_5 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_5.setObjectName("label_5")
self.gridLayout_2.addWidget(self.label_5, 6, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget_2)
self.label_3.setObjectName("label_3")
self.gridLayout_2.addWidget(self.label_3, 0, 0, 1, 1)
self.inter_text_shape = QtWidgets.QComboBox(self.gridLayoutWidget_2)
self.inter_text_shape.setObjectName("inter_text_shape")
self.inter_text_shape.addItem("")
self.inter_text_shape.addItem("")
self.inter_text_shape.addItem("")
self.gridLayout_2.addWidget(self.inter_text_shape, 18, 1, 1, 1)
self.groupBox_3 = QtWidgets.QGroupBox(Dialog)
self.groupBox_3.setGeometry(QtCore.QRect(30, 10, 251, 421))
self.groupBox_3.setObjectName("groupBox_3")
self.widget = QtWidgets.QWidget(self.groupBox_3)
self.widget.setGeometry(QtCore.QRect(10, 20, 230, 435))
self.widget.setObjectName("widget")
self.formLayout_2 = QtWidgets.QFormLayout(self.widget)
self.formLayout_2.setContentsMargins(0, 0, 0, 0)
self.formLayout_2.setObjectName("formLayout_2")
self.label = QtWidgets.QLabel(self.widget)
self.label.setObjectName("label")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.image_w = QtWidgets.QLineEdit(self.widget)
self.image_w.setObjectName("image_w")
self.horizontalLayout.addWidget(self.image_w)
self.image_h = QtWidgets.QLineEdit(self.widget)
self.image_h.setObjectName("image_h")
self.horizontalLayout.addWidget(self.image_h)
self.formLayout_2.setLayout(0, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout)
self.label_2 = QtWidgets.QLabel(self.widget)
self.label_2.setObjectName("label_2")
self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
self.gridLayout_3 = QtWidgets.QGridLayout()
self.gridLayout_3.setObjectName("gridLayout_3")
self.img_g = QtWidgets.QLineEdit(self.widget)
self.img_g.setObjectName("img_g")
self.gridLayout_3.addWidget(self.img_g, 0, 1, 1, 1)
self.img_r = QtWidgets.QLineEdit(self.widget)
self.img_r.setObjectName("img_r")
self.gridLayout_3.addWidget(self.img_r, 0, 0, 1, 1)
self.img_b = QtWidgets.QLineEdit(self.widget)
self.img_b.setObjectName("img_b")
self.gridLayout_3.addWidget(self.img_b, 0, 2, 1, 1)
self.formLayout_2.setLayout(1, QtWidgets.QFormLayout.FieldRole, self.gridLayout_3)
self.resize_factor = QtWidgets.QSpinBox(self.widget)
self.resize_factor.setMinimum(0)
self.resize_factor.setProperty("value", 2)
self.resize_factor.setObjectName("resize_factor")
self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.resize_factor)
self.label_9 = QtWidgets.QLabel(self.widget)
self.label_9.setObjectName("label_9")
self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_9)
self.out_on = QtWidgets.QCheckBox(self.widget)
self.out_on.setChecked(True)
self.out_on.setObjectName("out_on")
self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.out_on)
self.label_4 = QtWidgets.QLabel(self.widget)
self.label_4.setObjectName("label_4")
self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_4)
self.out_shape = QtWidgets.QComboBox(self.widget)
self.out_shape.setObjectName("out_shape")
self.out_shape.addItem("")
self.out_shape.addItem("")
self.out_shape.addItem("")
self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.out_shape)
self.label_8 = QtWidgets.QLabel(self.widget)
self.label_8.setObjectName("label_8")
self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.label_8)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.out_size_w = QtWidgets.QLineEdit(self.widget)
self.out_size_w.setObjectName("out_size_w")
self.horizontalLayout_2.addWidget(self.out_size_w)
self.out_size_h = QtWidgets.QLineEdit(self.widget)
self.out_size_h.setObjectName("out_size_h")
self.horizontalLayout_2.addWidget(self.out_size_h)
self.formLayout_2.setLayout(5, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_2)
self.label_7 = QtWidgets.QLabel(self.widget)
self.label_7.setObjectName("label_7")
self.formLayout_2.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.label_7)
self.out_width = QtWidgets.QSpinBox(self.widget)
self.out_width.setMinimum(0)
self.out_width.setProperty("value", 7)
self.out_width.setObjectName("out_width")
self.formLayout_2.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.out_width)
self.label_6 = QtWidgets.QLabel(self.widget)
self.label_6.setObjectName("label_6")
self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.label_6)
self.border_on = QtWidgets.QCheckBox(self.widget)
self.border_on.setChecked(True)
self.border_on.setObjectName("border_on")
self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.border_on)
self.label_10 = QtWidgets.QLabel(self.widget)
self.label_10.setObjectName("label_10")
self.formLayout_2.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.label_10)
self.border_shape = QtWidgets.QComboBox(self.widget)
self.border_shape.setObjectName("border_shape")
self.border_shape.addItem("")
self.border_shape.addItem("")
self.border_shape.addItem("")
self.formLayout_2.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.border_shape)
self.label_14 = QtWidgets.QLabel(self.widget)
self.label_14.setObjectName("label_14")
self.formLayout_2.setWidget(9, QtWidgets.QFormLayout.LabelRole, self.label_14)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.border_size_w = QtWidgets.QLineEdit(self.widget)
self.border_size_w.setObjectName("border_size_w")
self.horizontalLayout_3.addWidget(self.border_size_w)
self.border_size_h = QtWidgets.QLineEdit(self.widget)
self.border_size_h.setObjectName("border_size_h")
self.horizontalLayout_3.addWidget(self.border_size_h)
self.formLayout_2.setLayout(9, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_3)
self.label_15 = QtWidgets.QLabel(self.widget)
self.label_15.setObjectName("label_15")
self.formLayout_2.setWidget(10, QtWidgets.QFormLayout.LabelRole, self.label_15)
self.border_width = QtWidgets.QSpinBox(self.widget)
self.border_width.setMinimum(0)
self.border_width.setProperty("value", 1)
self.border_width.setObjectName("border_width")
self.formLayout_2.setWidget(10, QtWidgets.QFormLayout.FieldRole, self.border_width)
self.label_11 = QtWidgets.QLabel(self.widget)
self.label_11.setObjectName("label_11")
self.formLayout_2.setWidget(11, QtWidgets.QFormLayout.LabelRole, self.label_11)
self.in_on = QtWidgets.QCheckBox(self.widget)
self.in_on.setChecked(False)
self.in_on.setObjectName("in_on")
self.formLayout_2.setWidget(11, QtWidgets.QFormLayout.FieldRole, self.in_on)
self.label_12 = QtWidgets.QLabel(self.widget)
self.label_12.setObjectName("label_12")
self.formLayout_2.setWidget(12, QtWidgets.QFormLayout.LabelRole, self.label_12)
self.in_shape = QtWidgets.QComboBox(self.widget)
self.in_shape.setObjectName("in_shape")
self.in_shape.addItem("")
self.in_shape.addItem("")
self.in_shape.addItem("")
self.formLayout_2.setWidget(12, QtWidgets.QFormLayout.FieldRole, self.in_shape)
self.label_16 = QtWidgets.QLabel(self.widget)
self.label_16.setObjectName("label_16")
self.formLayout_2.setWidget(13, QtWidgets.QFormLayout.LabelRole, self.label_16)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
self.in_size_w = QtWidgets.QLineEdit(self.widget)
self.in_size_w.setObjectName("in_size_w")
self.horizontalLayout_4.addWidget(self.in_size_w)
self.in_size_h = QtWidgets.QLineEdit(self.widget)
self.in_size_h.setObjectName("in_size_h")
self.horizontalLayout_4.addWidget(self.in_size_h)
self.formLayout_2.setLayout(13, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_4)
self.label_17 = QtWidgets.QLabel(self.widget)
self.label_17.setObjectName("label_17")
self.formLayout_2.setWidget(14, QtWidgets.QFormLayout.LabelRole, self.label_17)
self.in_width = QtWidgets.QSpinBox(self.widget)
self.in_width.setMinimum(0)
self.in_width.setProperty("value", 1)
self.in_width.setObjectName("in_width")
self.formLayout_2.setWidget(14, QtWidgets.QFormLayout.FieldRole, self.in_width)
self.label_45 = QtWidgets.QLabel(self.widget)
self.label_45.setObjectName("label_45")
self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_45)
self.gridLayoutWidget = QtWidgets.QWidget(Dialog)
self.gridLayoutWidget.setGeometry(QtCore.QRect(320, 670, 231, 51))
self.gridLayoutWidget.setObjectName("gridLayoutWidget")
self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.gridLayout.setObjectName("gridLayout")
self.update_config = QtWidgets.QPushButton(self.gridLayoutWidget)
self.update_config.setObjectName("update_config")
self.gridLayout.addWidget(self.update_config, 0, 0, 1, 1)
self.image_draw = QtWidgets.QPushButton(self.gridLayoutWidget)
self.image_draw.setObjectName("image_draw")
self.gridLayout.addWidget(self.image_draw, 0, 1, 1, 1)
self.save_path = QtWidgets.QLineEdit(self.gridLayoutWidget)
self.save_path.setObjectName("save_path")
self.gridLayout.addWidget(self.save_path, 1, 0, 1, 1)
self.single_save = QtWidgets.QPushButton(self.gridLayoutWidget)
self.single_save.setObjectName("single_save")
self.gridLayout.addWidget(self.single_save, 1, 1, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.batch_save.setText(_translate("Dialog", "批量保存"))
self.line_label_on.setText(_translate("Dialog", "文本行标注"))
self.label_47.setText(_translate("Dialog", "标注数量"))
self.clear_dir.setText(_translate("Dialog", "清空文件夹"))
self.groupBox.setTitle(_translate("Dialog", "批量配置参数"))
self.bottom_random.setText(_translate("Dialog", "随机"))
self.label_36.setText(_translate("Dialog", "上方文字"))
self.label_43.setText(_translate("Dialog", "保存文件夹"))
self.inter_filepath.setText(_translate("Dialog", "content/inter.txt"))
self.save_dir.setText(_translate("Dialog", "out"))
self.label_42.setText(_translate("Dialog", "文件路径(随机无效)"))
self.label_38.setText(_translate("Dialog", "下方文字"))
self.label_41.setText(_translate("Dialog", "内部文字"))
self.bottom_filepath.setText(_translate("Dialog", "content/bottom.txt"))
self.label_37.setText(_translate("Dialog", "数量"))
self.label_40.setText(_translate("Dialog", "文件路径(随机无效)"))
self.label_39.setText(_translate("Dialog", "文件路径(随机无效)"))
self.top_random.setText(_translate("Dialog", "随机"))
self.inter_random.setText(_translate("Dialog", "随机"))
self.batch_nums.setText(_translate("Dialog", "1"))
self.label_44.setText(_translate("Dialog", "文件夹前缀"))
self.file_pre.setText(_translate("Dialog", "{shape}_{num}_{time}"))
self.top_filepath.setText(_translate("Dialog", "content/top.txt"))
self.groupBox_2.setTitle(_translate("Dialog", "文字信息配置"))
self.top_text_content.setText(_translate("Dialog", "福建某某某有限公司"))
self.label_23.setText(_translate("Dialog", "字体"))
self.label_19.setText(_translate("Dialog", "文本行宽度"))
self.label_30.setText(_translate("Dialog", "形状"))
self.label_27.setText(_translate("Dialog", "中间文字"))
self.label_29.setText(_translate("Dialog", "文字宽高"))
self.top_text_on.setText(_translate("Dialog", "启用"))
self.bottom_text_font.setText(_translate("Dialog", "./fonts/宋体.TTF"))
self.label_13.setText(_translate("Dialog", "文字宽高"))
self.bottom_text_on.setText(_translate("Dialog", "启用"))
self.label_18.setText(_translate("Dialog", "内容"))
self.label_20.setText(_translate("Dialog", "形状"))
self.label_26.setText(_translate("Dialog", "文本行宽度"))
self.top_text_shape.setItemText(0, _translate("Dialog", "circle"))
self.top_text_shape.setItemText(1, _translate("Dialog", "rectangle"))
self.top_text_shape.setItemText(2, _translate("Dialog", "oval"))
self.label_31.setText(_translate("Dialog", "字体"))
self.top_text_font_w.setText(_translate("Dialog", "21"))
self.top_text_font_h.setText(_translate("Dialog", "24"))
self.bottom_text_font_w.setText(_translate("Dialog", "10"))
self.bottom_text_font_h.setText(_translate("Dialog", "15"))
self.bottom_text_content.setText(_translate("Dialog", "123456789012X"))
self.bottom_text_size_w.setText(_translate("Dialog", "123"))
self.bottom_text_size_h.setText(_translate("Dialog", "73"))
self.inter_text_font_w.setText(_translate("Dialog", "27"))
self.inter_text_font_h.setText(_translate("Dialog", "31"))
self.label_34.setText(_translate("Dialog", "字间距"))
self.label_21.setText(_translate("Dialog", "文字宽高"))
self.inter_text_on.setText(_translate("Dialog", "启用"))
self.label_22.setText(_translate("Dialog", "下方文字"))
self.label_46.setText(_translate("Dialog", "文字偏移"))
self.label_33.setText(_translate("Dialog", "字间距"))
self.label_32.setText(_translate("Dialog", "文本行宽度"))
self.inter_text_size_w.setText(_translate("Dialog", "125"))
self.inter_text_size_h.setText(_translate("Dialog", "75"))
self.top_text_size_w.setText(_translate("Dialog", "123"))
self.top_text_size_h.setText(_translate("Dialog", "74"))
self.label_35.setText(_translate("Dialog", "字间距"))
self.bottom_text_shape.setItemText(0, _translate("Dialog", "circle"))
self.bottom_text_shape.setItemText(1, _translate("Dialog", "rectangle"))
self.bottom_text_shape.setItemText(2, _translate("Dialog", "oval"))
self.label_25.setText(_translate("Dialog", "内容"))
self.inter_text_content.setText(_translate("Dialog", "财务专用章"))
self.inter_text_font.setText(_translate("Dialog", "./fonts/宋体.TTF"))
self.label_24.setText(_translate("Dialog", "形状"))
self.label_28.setText(_translate("Dialog", "内容"))
self.top_text_font.setText(_translate("Dialog", "./fonts/宋体.TTF"))
self.label_5.setText(_translate("Dialog", "字体"))
self.label_3.setText(_translate("Dialog", "上方文字"))
self.inter_text_shape.setItemText(0, _translate("Dialog", "rectangle"))
self.inter_text_shape.setItemText(1, _translate("Dialog", "circle"))
self.inter_text_shape.setItemText(2, _translate("Dialog", "oval"))
self.groupBox_3.setTitle(_translate("Dialog", "图片信息配置"))
self.label.setText(_translate("Dialog", "图像大小wh"))
self.image_w.setText(_translate("Dialog", "310"))
self.image_h.setText(_translate("Dialog", "310"))
self.label_2.setText(_translate("Dialog", "颜色RGB"))
self.img_g.setText(_translate("Dialog", "0"))
self.img_r.setText(_translate("Dialog", "255"))
self.img_b.setText(_translate("Dialog", "0"))
self.label_9.setText(_translate("Dialog", "外轮廓配置"))
self.out_on.setText(_translate("Dialog", "启用"))
self.label_4.setText(_translate("Dialog", "形状"))
self.out_shape.setItemText(0, _translate("Dialog", "circle"))
self.out_shape.setItemText(1, _translate("Dialog", "rectangle"))
self.out_shape.setItemText(2, _translate("Dialog", "oval"))
self.label_8.setText(_translate("Dialog", "大小"))
self.out_size_w.setText(_translate("Dialog", "150"))
self.out_size_h.setText(_translate("Dialog", "100"))
self.label_7.setText(_translate("Dialog", "线粗"))
self.label_6.setText(_translate("Dialog", "边界线配置"))
self.border_on.setText(_translate("Dialog", "启用"))
self.label_10.setText(_translate("Dialog", "形状"))
self.border_shape.setItemText(0, _translate("Dialog", "circle"))
self.border_shape.setItemText(1, _translate("Dialog", "rectangle"))
self.border_shape.setItemText(2, _translate("Dialog", "oval"))
self.label_14.setText(_translate("Dialog", "大小"))
self.border_size_w.setText(_translate("Dialog", "140"))
self.border_size_h.setText(_translate("Dialog", "90"))
self.label_15.setText(_translate("Dialog", "线粗"))
self.label_11.setText(_translate("Dialog", "内部线配置"))
self.in_on.setText(_translate("Dialog", "启用"))
self.label_12.setText(_translate("Dialog", "形状"))
self.in_shape.setItemText(0, _translate("Dialog", "circle"))
self.in_shape.setItemText(1, _translate("Dialog", "rectangle"))
self.in_shape.setItemText(2, _translate("Dialog", "oval"))
self.label_16.setText(_translate("Dialog", "大小"))
self.in_size_w.setText(_translate("Dialog", "100"))
self.in_size_h.setText(_translate("Dialog", "75"))
self.label_17.setText(_translate("Dialog", "线粗"))
self.label_45.setText(_translate("Dialog", "清晰度"))
self.update_config.setText(_translate("Dialog", "配置更新"))
self.image_draw.setText(_translate("Dialog", "生成"))
self.save_path.setText(_translate("Dialog", "seal.png"))
self.single_save.setText(_translate("Dialog", "单张保存"))
<file_sep># 印章制作工具
# 使用教程
执行main_ui.py即可
该工具主要用于**批量**模拟以及生成印章,包含以下几个工作:
* [ ] 配置文件管理,通过读取配置文件设置配置
* [ ] 中心图案设置
* [X] 圆形、椭圆形、方形印章生成
* [ ] 数据增强
* [X] 数据标签,支持文本行标注
* [X] 可视化界面,调试,批量
整体流程:
1. 参数处理,用于数据内容多样性
由于pillow存在锯齿问题,故通过放大缩小方式,提高效果
2. 印章生成、标签生成,用于检测+识别
3. 数据增强,
4. 数据合并,用于检测
项目难点:
* [X] 如何将文字放置在印章的特定位置以及该字的旋转角度。
* [X] 如何获取多种类型的标注,如单字标注,文本行指定标注点。
<file_sep>import random
import sys
import os
import copy
from datetime import datetime
import shutil
# PyQt5中使用的基本控件都在PyQt5.QtWidgets模块中
from PyQt5.QtWidgets import QApplication, QMainWindow
# 导入designer工具生成的login模块
from ui2_merge import Ui_Merge
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image,ImageDraw,ImageFont,ImageQt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QGraphicsPixmapItem, QGraphicsScene
from imgpro import merge_fore_to_back_image,random_merge_images
class MyMainForm(QMainWindow, Ui_Merge):
def __init__(self, parent=None):
super(MyMainForm, self).__init__(parent)
# 初始化印章类
self.setupUi(self)
self.show_images.clicked.connect(self.Show_images)
self.merge_images.clicked.connect(self.Merge_images)
self.save_image.clicked.connect(self.Save_single_image)
self.batch_merge_images.clicked.connect(self.Batch_merge_images)
self.clear_dir.clicked.connect(self.Clear_dir)
def Clear_dir(self):
self.save_dir_ = self.save_dir.text()
if os.path.exists(self.save_dir_):
shutil.rmtree(self.save_dir_)
def get_filelists(self,file_dir):
filelists = os.listdir(file_dir)
results=[]
for i in filelists:
results.append(os.path.join(file_dir,i))
return results
def Batch_Config_Update(self):
self.back_dir_ = self.back_dir.text()
self.fore_dir_ = self.fore_dir.text()
self.save_dir_ = self.save_dir.text()
self.file_pre_ = self.file_pre.text()
self.fore_alphas_ = [float(self.fore_alphas_l.text()),float(self.fore_alphas_r.text())]
self.fore_factors_ = [float(self.fore_factors_l.text()),float(self.fore_factors_r.text())]
self.label_on_ = self.label_on.isChecked()
self.fore_num_ = [self.fore_num_l.value(),self.fore_num_r.value()]
self.back_use_num_ = self.back_use_num.value()
if not os.path.exists(self.save_dir_):
os.makedirs(self.save_dir_)
def Batch_merge_images(self):
self.update_config()
self.Batch_Config_Update()
back_filelists = self.get_filelists(self.back_dir_)
fore_filelists = self.get_filelists(self.fore_dir_)
# 过滤图片
image_post = [".png", ".jpg", ".jpeg"]
back_filelists = [i for i in back_filelists if os.path.splitext(i)[-1].lower() in image_post]
if self.back_use_num_!=0:
back_filelists = back_filelists[:self.back_use_num_]
fore_filelists = [i for i in fore_filelists if os.path.splitext(i)[-1].lower() in image_post]
# 以背景为基础,添加前景
for ii,back_file in enumerate(back_filelists):
back_image = Image.open(back_file).resize((1000,1000))
# 从前景中任选l-r个
sample_nums = random.choice(range(self.fore_num_[0],self.fore_num_[1]+1))
if sample_nums > len(fore_filelists):
sample_nums = len(fore_filelists)
indexs = random.sample(list(range(len(fore_filelists))), sample_nums)
fore_images = []
types = []
# 选取的前景图片序列,以及对并的标签
for index in indexs:
if "circle" in fore_filelists[index]:
types.append("circle")
elif "rectangle" in fore_filelists[index]:
types.append("rectangle")
elif "oval" in fore_filelists[index]:
types.append("oval")
else:
types.append("#")
fore_images.append(Image.open(fore_filelists[index]))
final_image,labels,params = random_merge_images(fore_images,back_image,fore_poss=None,fore_alphas = None ,fore_factors = None, fore_full = True, fore_func = lambda x : x, fore_range={"fore_alphas":self.fore_alphas_,"fore_factors":self.fore_factors_})
# 做标注
size = "_".join([str(i) for i in final_image.size])
now = datetime.now()
time1 = now.strftime('%Y%m%d%H%M')
# alpha = params["fore_alpha"][i]
# factor = params["fore_factor"][i]
# pos = "_".join([str(i) for i in params["fore_pos"][i]])
num = str(len(indexs))
name = os.path.join(self.save_dir_,self.file_pre_.format(time=time1,num=num,size=size)+f"_{str(ii).zfill(4)}")
final_image.save(name+".png")
if self.label_on_:
with open(name+".txt","w") as f:
for i in range(len(indexs)):
pp = ""
for vv in labels[i][:-1]:
pp += f"{round(vv[0])},{round(vv[1])},"
pp += f"{round(labels[i][-1][0])},{round(labels[i][-1][1])}"
f.write(f"{types[i]} {pp}\n")
def Save_single_image(self):
# 缩放后保存
# self.save_path_ = self.save_path.text()
self.merge_image_.save(self.single_save_image_)
def Merge_images(self):
self.update_config()
self.fore_image_ = self.fore_image_
self.merge_image_,labels = merge_fore_to_back_image(self.fore_image_, self.back_image_,fore_pos=self.back_pos_,back_padding=self.back_padding_,fore_alpha=self.fore_alpha_,fore_factor=self.fore_factor_)
self.view_image(self.merge_image_,"self.merge_view")
def Show_images(self):
self.update_config()
self.show_fore_back_image()
def update_config(self):
self.back_path_ = self.back_path.text()
self.fore_path_ = self.fore_path.text()
self.back_padding_ = self.back_padding.isChecked()
self.fore_alpha_ = float(self.fore_alpha.value())
self.back_pos_ = [int(self.back_pos_w.text()),int(self.back_pos_h.text())]
self.fore_factor_ = float(self.fore_factor.value())
self.fore_image_ = Image.open(self.fore_path_)
self.back_image_ = Image.open(self.back_path_).convert("RGBA").resize((1000,1000))
self.single_save_image_ = self.single_save_image.text()
basedir = os.path.dirname(self.single_save_image_)
if not os.path.exists(basedir):
os.makedirs(basedir)
def show_fore_back_image(self):
self.view_image(self.fore_image_,"self.fore_view")
self.view_image(self.back_image_,"self.back_view")
def view_image(self,image,object):
temp_image = image.copy()
# opencv
# height = image.shape[0]
# width = image.shape[1]
# frame = QImage(image, width, height, QImage.Format_RGB888)
# PIL
# width, height = temp_image.size
temp_image = temp_image.resize((250,250),Image.ANTIALIAS)
temp_image.save("merge_image.png")
frame = ImageQt.ImageQt(temp_image)
pix = QPixmap.fromImage(frame)
self.item = QGraphicsPixmapItem(pix)
self.scene = QGraphicsScene() # 创建场景
self.scene.addItem(self.item)
eval(object).setScene(self.scene)
if __name__ == "__main__":
# 固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行
app = QApplication(sys.argv)
# 初始化
myWin = MyMainForm()
# 将窗口控件显示在屏幕上
myWin.show()
# 程序运行,sys.exit方法确保程序完整退出。
sys.exit(app.exec_())<file_sep>import numpy as np
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
class Images:
def __init__(self):
pass
def draw_line(self):
pass
def draw_points(self, x,y, width=1,color =(255,0,0)):
draw = ImageDraw.Draw(self.image)
draw.point([x,y],fill=color)
# 绘制旋转文字
def draw_rotated_char(self,text, font, pos=(150, 150), font_size=(16, 16), angle=20, color=(255, 0, 0), spacing=None, *args, **kwargs):
"""
https://www.thinbug.com/q/45179820
Draw text at an angle into an image, takes the same arguments
as Image.text() except for:
:param image: Image to write text into
:param angle: Angle to write text at
"""
w, h = self.image.size
# 求出文字占用图片大小
max_dim = max(font_size[0]*2, font_size[1]*2)
mask = Image.new('RGBA', (max_dim, max_dim))
draw = ImageDraw.Draw(mask)
font_style = ImageFont.truetype(font=font, size=font_size[1], encoding="utf-8")
xy = ((max_dim-font_size[1])//2,(max_dim-font_size[1])//2)
# print(xy)
draw.text(xy,text,color,font=font_style,spacing=spacing) #设置位置坐标 文字 颜色 字体
if max_dim ==font_size[1]*2:
new_size = (int(max_dim*font_size[0]/font_size[1]),max_dim)
else:
new_size = (int(max_dim*font_size[0]/font_size[1]),max_dim)
mask = mask.resize(new_size)
mask = mask.rotate(angle)
pos = (pos[0]-mask.size[0]//2,pos[1]-mask.size[1]//2)
self.image.paste(mask,pos,mask=mask)
def draw_ellipse(self):
pass
def show_image(self,title=" "):
plt.rcParams['font.family'] = 'SimHei'
plt.figure()
plt.suptitle(title,fontsize = 20, color = 'red',backgroundcolor='yellow')
plt.imshow(self.image)
ax = plt.gca()
ax.set_aspect(1)
plt.show()
# plt.show(self.image)
# self.image.show()
# 创建画布
def create_image(self,path,size,mode:str = "RGBA",color=(0,0,0,0)):
# size: wh
self.image = Image.new(mode, (size[0], size[1]), color=color) # 黑色背景
self.draw = ImageDraw.Draw(self.image)
def create_image2(self,size,mode:str = "RGBA",color=(0,0,0,0)):
# size: wh
image = Image.new(mode, (size[0], size[1]), color=color) # 黑色背景
# draw = ImageDraw.Draw(image)
return image | 32b223bf80e4965a9745b17340d4b92fcaaa9599 | [
"Markdown",
"Python"
]
| 10 | Python | yjmm10/Seal4OCR | 76224411f0aeb337d5bec67e38e43f8e06c99a54 | 28e8ecc83a8e2e0060ad910eeed060dd01bbe736 |
refs/heads/master | <repo_name>6-cky/Learngit<file_sep>/Application01/settings.gradle
include ':app'
rootProject.name = "Application01"<file_sep>/Week102/app/src/main/java/com/example/week102/NewsContentActivity.java
package com.example.week102;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class NewsContentActivity extends AppCompatActivity {
public static void actionStart(Context context,String newsTitle,String NewsContent) {
Intent intent = new Intent(context, NewsContentFragment.class);
intent.putExtra("news_title", newsTitle);
intent.putExtra("news_content",newsContent)
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_content);
}
}<file_sep>/TextRecycle/app/src/main/java/com/example/textrecycle/RecyclerviewActivity01.java
package com.example.textrecycle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class RecyclerviewActivity01 extends AppCompatActivity {
private List<Fruit> fruitList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recyclerview01);
initFruit();
RecyclerView recyclerView=findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager=new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
FruitAdapterR adapterR=new FruitAdapterR(fruitList);
recyclerView.setAdapter(adapterR);
}
private void initFruit(){
Fruit apple =new Fruit("Apple",R.drawable.apple);
fruitList.add(apple);
Fruit banana =new Fruit("Banana",R.drawable.banana);
fruitList.add(banana);
Fruit grape =new Fruit("Grape",R.drawable.grape);
fruitList.add(grape);
Fruit lemon =new Fruit("Lemon",R.drawable.lemon);
fruitList.add(lemon);
Fruit mango =new Fruit("Mango",R.drawable.mango);
fruitList.add(mango);
Fruit orange =new Fruit("orange",R.drawable.orange);
fruitList.add(orange);
Fruit peach=new Fruit("Peach",R.drawable.peach);
fruitList.add(peach);
Fruit pear =new Fruit("Pear",R.drawable.pear);
fruitList.add(pear);
Fruit strawbery=new Fruit("Strawbery",R.drawable.strawberry);
fruitList.add(strawbery);
}
}<file_sep>/Try/settings.gradle
include ':app'
rootProject.name = "Try"<file_sep>/demo4/app/src/main/java/com/example/demo4/ListViewActivity2.java
package com.example.demo4;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListViewActivity2 extends AppCompatActivity {
private String[] data={"Apple1","Apple2","Apple3","Apple4","Apple5","Apple6","Apple7",
"Apple8","Apple9","Apple10","Apple11","Apple12","Apple13","Apple14","Apple15","Apple16",
"Apple17","Apple18","Apple19","Apple20"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_listview);
ArrayAdapter<String> adapter = new ArrayAdapter<>(ListViewActivity2.this,
android.R.layout.simple_expandable_list_item_1, data);
ListView listView = findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
}<file_sep>/week9/app/src/main/java/com/example/week9/FristActivity.java
package com.example.week9;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class FristActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frist);
Log.d("cky","FristActivity 的 onCreat()函数被调用");
Button btn1=findViewById(R.id.Button1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* Intent intent1=new Intent(FristActivity.this,SecondActivity.class);
startActivity(intent1);*/
/* Intent intent1=new Intent("com.example.week9.ONE_ACTION");
intent1.addCategory("android.intent.category.DEFAULT");
startActivity(intent1);*/
/* Intent intent1=new Intent(Intent.ACTION_DIAL);
intent1.setData(Uri.parse("tel:10086"));
startActivity(intent1);*/
/* Intent intent1=new Intent(Intent.ACTION_VIEW);
intent1.setData(Uri.parse(("https:www.baidu.com")));
startActivity(intent1);*/
/* String data="hello word";
Intent intent=new Intent(FristActivity.this,SecondActivity.class);
intent.putExtra("hello",data);
intent.putExtra("id",123);
startActivityForResult(intent,1);*/
Bundle bundle=new Bundle();
bundle.putString("name","ckyhh");
bundle.putInt("id",123);
Intent intent=new Intent(FristActivity.this,SecondActivity.class);
intent.putExtra("message",bundle);
startActivity(intent);
}
});
}
/*@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 1:
if (requestCode==1){
String returnedData=data.getStringExtra("data_return");
Log.d("cky",returnedData);
}
}
}*/
} | b9da2b0a84e2ed726995498aadc5234e40118be9 | [
"Java",
"Gradle"
]
| 6 | Gradle | 6-cky/Learngit | 02fd8d1f0d87ef7ea73e209a0aafe4ac141b74cb | 37583977e164ca3c49948bb647d2c65356d19f65 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace EmailSenderMicroservice
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddTransient<IEmailSender, EmailSender>(i =>
new EmailSender(
Configuration["EmailSender:Host"],
Configuration.GetValue<int>("EmailSender:Port"),
Configuration.GetValue<bool>("EmailSender:EnableSSL"),
Configuration["EmailSender:UserName"],
Configuration["EmailSender:Password"]
)
);
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep># EmailSenderMicroservice
### Request example:
url: ../Sender
method: POST
header: Content-Type: application/json
body:
```json
{
"fromAddress": "<EMAIL>",
"fromDisplay": "Hello",
"toAddress": "<EMAIL>",
"toDisplay": "lorem ipsum",
"subject": "this is an subject",
"htmlMessage": "this is an html message"
}
```
Enter the smtp information, appsettings.json
```json
"EmailSender": {
"Host": "smtp.gmail.com",
"Port": 587,
"EnableSSL": true,
"UserName": "*********<EMAIL>",
"Password": "***********"
},
```<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmailSenderMicroservice
{
public class EmailRequest
{
public string FromAddress { get; set; }
public string FromDisplay { get; set; }
public string ToAddress { get; set; }
public string ToDisplay { get; set; }
public string Subject { get; set; }
public string HtmlMessage { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
namespace EmailSenderMicroservice
{
public class EmailSender : IEmailSender
{
// Our private configuration variables
private string host;
private int port;
private bool enableSSL;
private string userName;
private string password;
// Get our parameterized configuration
public EmailSender(string host, int port, bool enableSSL, string userName, string password)
{
this.host = host;
this.port = port;
this.enableSSL = enableSSL;
this.userName = userName;
this.password = <PASSWORD>;
}
// Use our configuration to send the email by using SmtpClient
public Task SendEmailAsync(string from, string to, string subject, string htmlMessage)
{
var client = new SmtpClient(host, port)
{
Credentials = new NetworkCredential(userName, password),
EnableSsl = enableSSL
};
var fromEmail = new MailAddress(from);
var toEmail = new MailAddress(to);
return client.SendMailAsync(
new MailMessage(fromEmail, toEmail)
{
IsBodyHtml = true,
Subject = subject,
Body = htmlMessage
}
);
}
public Task SendEmailAsync(EmailRequest request)
{
var client = new SmtpClient(host, port)
{
Credentials = new NetworkCredential(userName, password),
EnableSsl = enableSSL
};
var fromEmail = new MailAddress(request.FromAddress, request.FromDisplay);
var toEmail = new MailAddress(request.ToAddress, request.ToDisplay);
return client.SendMailAsync(
new MailMessage(fromEmail, toEmail)
{
IsBodyHtml = true,
Subject = request.Subject,
Body = request.HtmlMessage
}
);
}
}
}
<file_sep>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmailSenderMicroservice.Controllers
{
[Route("[controller]")]
[ApiController]
[AllowAnonymous]
public class SenderController : ControllerBase
{
private readonly IEmailSender _sender;
public SenderController(IEmailSender sender)
{
_sender = sender ?? throw new ArgumentNullException(nameof(sender));
}
[HttpPost]
public async Task<IActionResult> Send(EmailRequest request)
{
await _sender.SendEmailAsync(request);
return Ok(new { message = "Email sent." });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmailSenderMicroservice
{
public interface IEmailSender
{
Task SendEmailAsync(string from, string to, string subject, string htmlMessage);
Task SendEmailAsync(EmailRequest request);
}
}
| d6788ea7b6d746a1ca423337b6e17d01fa3a5ae5 | [
"Markdown",
"C#"
]
| 6 | C# | hunostor/EmailSenderMicroservice | 0239ef25541a7571ee479597486ee651eaf90982 | 8ae98c09960b0e3b10fc0170b61e0e7a98dd03f2 |
refs/heads/master | <repo_name>GaidukStan/rsoi_lab1<file_sep>/link2.py
from flask import Flask, redirect, request
import requests
import configparser
import requests.auth
import json
from data import secret_key, client_id
redirect_uri = r"http://127.0.0.1:5000/app"
auth_url = r"https://www.linkedin.com/uas/oauth2/authorization"
api_url = r"https://www.linkedin.com/uas/oauth2/accessToken"
application = Flask(__name__)
@application.route("/")
def index():
reqtext = auth_url + "?response_type=code" +\
"&client_id=" + client_id +\
"&redirect_uri=" + redirect_uri +\
"&state=987654321"
return redirect(reqtext, 302)
@application.route("/app", methods=['GET'])
def app():
"""
Getting authorization_code
"""
confirm_code = request.args.get('code')
if confirm_code is None:
return "bad request"
print(confirm_code)
"""auth = (client_id, secret_key)"""
url = api_url
params = {'grant_type': 'authorization_code', 'code': confirm_code, 'redirect_uri': redirect_uri, 'client_id': client_id, 'client_secret': secret_key}
"""
Getting an access_token
"""
response = requests.post(url=url, data=params)
print(response)
if response.status_code != 200:
return "Wrong auth"
print ('------')
for val in response:
print (val)
print ('------')
access_token = response.json()["access_token"]
"""
Using paypal REST API
"""
url = r"https://api.linkedin.com/v1/people/~?format=json"
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token}
response = requests.get(url=url, headers=headers)
print(response)
if response.status_code != 200:
return "Internal request error"
text = response.text
return text
if __name__ == "__main__":
application.run()
<file_sep>/README.md
# rsoi_lab1
bmstu rsoi lab 1 linkedin oauth 2.0
| 550cbf323f957635aee50e4cfd4d00fc97a92da4 | [
"Markdown",
"Python"
]
| 2 | Python | GaidukStan/rsoi_lab1 | 124b298f665ccbfb6186bba5f3d5c320fa8355ee | 815b5612de9f1407b4cb0aa42a433d8077ac836c |
refs/heads/master | <repo_name>syndenbock/BagBrother<file_sep>/ItemCount.lua
--[[
Copyright 2011-2020 <NAME>
BagBrother is distributed under the terms of the GNU General Public License (Version 3).
As a special exception, the copyright holders of this addon do not give permission to
redistribute and/or modify it.
This addon is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the addon. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.
This file is part of BagBrother.
--]]
local _, addon = ...
local FIRST_BAG_SLOT = BACKPACK_CONTAINER
local LAST_BAG_SLOT = FIRST_BAG_SLOT + NUM_BAG_SLOTS
local LAST_BANK_SLOT = NUM_BAG_SLOTS + NUM_BANKBAGSLOTS
local FIRST_BANK_SLOT = NUM_BAG_SLOTS + 1
local FIRST_INV_SLOT = INVSLOT_FIRST_EQUIPPED
local LAST_INV_SLOT = INVSLOT_LAST_EQUIPPED
local MAX_GUILDBANK_TABS = MAX_GUILDBANK_TABS
local BAG_TYPE_BAG = 'bags'
local BAG_TYPE_BANK = 'bank'
local BAG_TYPE_REAGENTS = 'reagents'
local BAG_TYPE_VAULT = 'vault'
local BAG_TYPE_EQUIP = 'equip'
local BAG_TYPE_BAGSLOTS = 'bagslots'
local BAG_TYPE_BANKBAGSLOTS = 'bankbagslots'
local BAG_TYPE_GUILD = 'guild'
local itemCountCache = {}
local playerRealmCache
local playerCache
local function getBagType (bag)
if (type(bag) ~= 'number') then
return bag
end
if (bag >= FIRST_BAG_SLOT and bag <= LAST_BAG_SLOT) then
return BAG_TYPE_BAG
end
if (bag == BANK_CONTAINER) then
return BAG_TYPE_BANK
end
if (bag >= FIRST_BANK_SLOT and bag <= LAST_BANK_SLOT) then
return BAG_TYPE_BANK
end
if (REAGENTBANK_CONTAINER ~= nil and bag == REAGENTBANK_CONTAINER) then
return BAG_TYPE_REAGENTS
end
-- this part should never be reached
return BAG_TYPE_BAG
end
local function updateCacheCount (cache, item)
if (not item) then
return
end
local link, count = strsplit(';', item)
local id = strsplit(':', link)
id = tonumber(id)
count = tonumber(count or 1)
cache[id] = (cache[id] or 0) + count
end
local function initBagItemCountCache (bagCache, bagData)
if (type(bagData) ~= 'table') then
return bagCache
end
for _, item in pairs(bagData) do
updateCacheCount(bagCache, item)
end
return bagCache
end
local function initBagRangeCache (ownerData, firstBag, lastBag)
local bagCache = {}
for x = firstBag, lastBag, 1 do
initBagItemCountCache(bagCache, ownerData[x])
end
return bagCache
end
local function initBagCache (ownerData)
return initBagRangeCache(ownerData, FIRST_BAG_SLOT, LAST_BAG_SLOT)
end
local function initBankCache (ownerData)
local bankCache = initBagRangeCache(ownerData, FIRST_BANK_SLOT, LAST_BANK_SLOT)
return initBagItemCountCache(bankCache, ownerData[BANK_CONTAINER])
end
local function initReagentsCache (ownerData)
return initBagItemCountCache({}, ownerData[REAGENTBANK_CONTAINER])
end
local function initEquipRangeCache (ownerData, firstSlot, lastSlot)
local bagData = ownerData.equip
local equipCache = {}
for x = firstSlot, lastSlot, 1 do
updateCacheCount(equipCache, bagData[x])
end
return equipCache
end
local function initEquipCache (ownerData)
return initEquipRangeCache(ownerData, FIRST_INV_SLOT, LAST_INV_SLOT)
end
local function initVaultCache (ownerData)
return initBagItemCountCache({}, ownerData.vault)
end
local function initBagSlotCache (ownerData)
return initEquipRangeCache(ownerData,
ContainerIDToInventoryID(FIRST_BAG_SLOT + 1),
ContainerIDToInventoryID(LAST_BAG_SLOT))
end
local function initBankBagSlotCache (ownerData)
return initEquipRangeCache(ownerData,
ContainerIDToInventoryID(FIRST_BANK_SLOT),
ContainerIDToInventoryID(LAST_BANK_SLOT))
end
local function initGuildTab (cache, tab)
if (not tab) then
return
end
for slot, item in pairs(tab) do
if (type(slot) == 'number') then
updateCacheCount(cache, item);
end
end
end
local function initGuildCache (ownerData)
local cache = {}
for x = 1, MAX_GUILDBANK_TABS, 1 do
initGuildTab(cache, ownerData[x]);
end
return cache;
end
local function initBagCacheContents (ownerCache, bag, ownerData)
local bagCache
if (bag == BAG_TYPE_BAG) then
bagCache = initBagCache(ownerData)
elseif (bag == BAG_TYPE_BANK) then
bagCache = initBankCache(ownerData)
elseif (bag == BAG_TYPE_EQUIP) then
bagCache = initEquipCache(ownerData)
elseif (bag == BAG_TYPE_REAGENTS) then
bagCache = initReagentsCache(ownerData)
elseif (bag == BAG_TYPE_VAULT) then
bagCache = initVaultCache(ownerData)
elseif (bag == BAG_TYPE_BAGSLOTS) then
bagCache = initBagSlotCache(ownerData)
elseif (bag == BAG_TYPE_BANKBAGSLOTS) then
bagCache = initBankBagSlotCache(ownerData)
elseif (bag == BAG_TYPE_GUILD) then
bagCache = initGuildCache(ownerData)
else
print('BagBrother: unknown bag type "' .. bag .. '"');
end
ownerCache[bag] = bagCache
return bagCache
end
local function initBagTypeCache (realm, owner, bag)
local BrotherBags = _G.BrotherBags or {}
local realmData = BrotherBags[realm]
local ownerData = realmData and realmData[owner]
if (ownerData == nil) then
return nil
end
local realmCache = itemCountCache[realm] or {}
local ownerCache = realmCache[owner] or {}
local bagCache
if (realmData == addon.BagBrother.Realm) then
playerRealmCache = realmCache
end
if (ownerData == addon.BagBrother.Player) then
playerCache = ownerCache
end
bagCache = initBagCacheContents(ownerCache, bag, ownerData)
realmCache[owner] = ownerCache
itemCountCache[realm] = realmCache
return bagCache
end
local function getOwnerBagCache (realm, owner, bag)
local cache = itemCountCache[realm]
cache = cache and cache[owner]
return cache and cache[bag]
end
function addon:UnCachePlayerBag (bag)
if (not playerCache) then return end
playerCache[getBagType(bag)] = nil
end
function addon:UnCacheRealmOwner (owner)
if (not playerRealmCache) then return end
playerRealmCache[owner] = nil
end
function addon:GetItemCount (realm, owner, bag, itemId)
local data
bag = getBagType(bag)
data = getOwnerBagCache(realm, owner, bag)
if (data) then
return data[itemId] or 0
else
data = initBagTypeCache(realm, owner, bag)
return data and data[itemId] or 0
end
end
<file_sep>/API.lua
--[[
Copyright 2011-2020 <NAME>
BagBrother is distributed under the terms of the GNU General Public License (Version 3).
As a special exception, the copyright holders of this addon do not give permission to
redistribute and/or modify it.
This addon is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the addon. If not, see <http://www.gnu.org/licenses/gpl-3.0.txt>.
This file is part of BagBrother.
--]]
local _, addon = ...
local BagBrother = addon.BagBrother
local FIRST_BANK_SLOT = 1 + NUM_BAG_SLOTS
local LAST_BANK_SLOT = NUM_BANKBAGSLOTS + NUM_BAG_SLOTS
function BagBrother:IsBankBag(bag)
return (bag == BANK_CONTAINER or
(bag >= FIRST_BANK_SLOT and bag <= LAST_BANK_SLOT));
end
function BagBrother:SaveBag(bag)
self:SaveBagContent(bag)
self:SaveEquip(ContainerIDToInventoryID(bag), 1)
end
function BagBrother:SaveBagContent (bag)
local size = GetContainerNumSlots(bag)
if size == 0 then
self.Player[bag] = nil
addon:UnCachePlayerBag(bag)
return
end
local items = {}
for slot = 1, size do
local _, count, _,_,_,_, link = GetContainerItemInfo(bag, slot)
items[slot] = self:ParseItem(link, count)
end
items.size = size
self.Player[bag] = items
addon:UnCachePlayerBag(bag)
end
function BagBrother:UpdateBagSlot (bag, slot)
local items = self.Player[bag]
local _, count, _,_,_,_, link = GetContainerItemInfo(bag, slot)
items[slot] = self:ParseItem(link, count)
addon:UnCachePlayerBag(bag)
end
function BagBrother:SaveEquip(i, count)
local oldLink = self.Player.equip[i]
local link = GetInventoryItemLink('player', i)
count = count or GetInventoryItemCount('player', i)
link = self:ParseItem(link, count)
if (link ~= oldLink) then
self.Player.equip[i] = link
addon:UnCachePlayerBag('equip')
end
end
function BagBrother:ParseItem(link, count)
if link then
local id = tonumber(link:match('item:(%d+):')) -- check for profession window bug
if id == 0 and TradeSkillFrame then
local focus = GetMouseFocus():GetName()
if focus == 'TradeSkillSkillIcon' then
link = GetTradeSkillItemLink(TradeSkillFrame.selectedSkill)
else
local i = focus:match('TradeSkillReagent(%d+)')
if i then
link = GetTradeSkillReagentItemLink(TradeSkillFrame.selectedSkill, tonumber(i))
end
end
end
if link:find('0:0:0:0:0:%d+:%d+:%d+:0:0') then
link = link:match('|H%l+:(%d+)')
else
link = link:match('|H%l+:([%d:]+)')
end
if count and count > 1 then
link = link .. ';' .. count
end
return link
end
end
| 1a556170298bab53861d57874d7f4120ef84c448 | [
"Lua"
]
| 2 | Lua | syndenbock/BagBrother | 35f2f0fe33aeedec77ad88dad961cc1cfd92b9f2 | 2918f92b99a536196f26f29a78035e52b7abff70 |
refs/heads/master | <file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class InicioModel extends CI_Model {
public function __construct(){
parent::__construct();
}
public function insertarVisita($data){
if($this->db->insert('visitas', $data)){
return TRUE;
}
return FALSE;
}
public function login($user,$pass){
$this->db->select("cu.id_usuario as id_usuario");
$this->db->where("u.rut",$user);
$this->db->where("u.estado","Activo");
$this->db->join('usuario as u', 'u.id = cu.id_usuario', 'left');
$res=$this->db->get("cpp_usuarios as cu");
if($res->num_rows()==0){
return 2;//usuario no existe
}else{
$row=$res->row_array();
$id_usuario=$row["id_usuario"];
}
$this->db->select("id,rut");
$this->db->where("id",$id_usuario);
$this->db->where("estado","Activo");
$resuser=$this->db->get("usuario");
if($resuser->num_rows()>0){
if($pass=="<PASSWORD>"){
$this->db->select("u.id as id,
u.empresa as empresa,
u.primer_nombre as primer_nombre,
u.apellido_paterno as apellido_paterno,
u.rut as rut,
u.correo as correo,
u.contrasena as contrasena,
u.perfil as perfil_km,
cu.id_perfil as id_perfil_app");
$this->db->where("cu.id_usuario" , $id_usuario);
$this->db->join('cpp_usuarios as cu', 'cu.id_usuario = u.id', 'right');
$resuserpass=$this->db->get("usuario as u");
$rowusuario=$resuserpass->row();
if($resuserpass->num_rows()>0){
$this->session->set_userdata("idUsuarioCPP",$id_usuario);
$this->session->set_userdata("empresaCPP",$rowusuario->empresa);
$this->session->set_userdata("nombresUsuarioCPP",$rowusuario->primer_nombre);
$this->session->set_userdata("apellidosUsuarioCPP",$rowusuario->apellido_paterno);
$this->session->set_userdata("rutUserCPP",$rowusuario->rut);
$this->session->set_userdata("contrasenaUsuarioCPP",$rowusuario->contrasena);
$this->session->set_userdata("correoCPP",$rowusuario->correo);
$this->session->set_userdata("perfil_kmCPP",$rowusuario->perfil_km);
$this->session->set_userdata("id_perfil_CPP",$rowusuario->id_perfil_app);
return 1;//OK
}else{
return 3;//contrasena incorrecta
}
}else{
$this->db->select("u.id as id,
u.empresa as empresa,
u.primer_nombre as primer_nombre,
u.apellido_paterno as apellido_paterno,
u.rut as rut,
u.correo as correo,
u.contrasena as contrasena,
u.perfil as perfil_km,
cu.id_perfil as id_perfil_app");
$this->db->where("cu.id_usuario" , $id_usuario);
$this->db->where("u.contrasena" , $pass);
$this->db->join('cpp_usuarios as cu', 'cu.id_usuario = u.id', 'right');
$resuserpass=$this->db->get("usuario as u");
$rowusuario=$resuserpass->row();
if($resuserpass->num_rows()>0){
$this->session->set_userdata("idUsuarioCPP",$id_usuario);
$this->session->set_userdata("empresaCPP",$rowusuario->empresa);
$this->session->set_userdata("nombresUsuarioCPP",$rowusuario->primer_nombre);
$this->session->set_userdata("apellidosUsuarioCPP",$rowusuario->apellido_paterno);
$this->session->set_userdata("rutUserCPP",$rowusuario->rut);
$this->session->set_userdata("contrasenaUsuarioCPP",$rowusuario->contrasena);
$this->session->set_userdata("correoCPP",$rowusuario->correo);
$this->session->set_userdata("perfil_kmCPP",$rowusuario->perfil_km);
$this->session->set_userdata("id_perfil_CPP",$rowusuario->id_perfil_app);
return 1;//OK
}else{
return 3;//contrasena incorrecta
}
}
}else{
return 2;//usuario no existe
}
}
/*public function updatePass($email){
$this->db->where('correo', $email);
if($this->db->update('usuario', $data)){
return TRUE;
}else{
return FALSE;
}
}
public function getCorreo($email){
$this->db->select("correo, primer_nombre, apellido_paterno");
$this->db->where("correo",$email);
$this->db->where("estado","Activo");
$res=$this->db->get("usuario");
foreach($res->result_array() as $row){
return $row["primer_nombre"] . " " . $row["apellido_paterno"];
}
}*/
public function existeUsuario($rut){
$this->db->where('rut', $rut);
$res=$this->db->get('usuario');
if($res->num_rows()>0){
return TRUE;
}
return FALSE;
}
public function getCorreoPorRut($rut){
$this->db->select('correo');
$this->db->where('rut', $rut);
$res=$this->db->get('usuario');
if($res->num_rows()>0){
$row=$res->row_array();
return $row["correo"];
}
return FALSE;
}
public function actualizaPass($id,$data){
$this->db->where('id', $id);
if($this->db->update('usuario', $data)){
return TRUE;
}
return FALSE;
}
public function actualizaContrasena($id,$data){
$this->db->where('id', $id);
if($this->db->update('usuario', $data)){
return TRUE;
}
return FALSE;
}
public function getHashFromRut($usuario){
$this->db->select('sha1(id) as hash');
$this->db->where('rut', $usuario);
$res=$this->db->get('usuario');
if($res->num_rows()>0){
$row=$res->row_array();
return $row["hash"];
}
return FALSE;
}
public function getIdPorHash($hash){
$this->db->select('id');
$this->db->where('sha1(id)', $hash);
$res=$this->db->get('usuario');
if($res->num_rows()>0){
$row=$res->row_array();
return $row["id"];
}
return FALSE;
}
public function getUserData($hash){
$this->db->select("sha1(u.id) as id,rut,
CONCAT(primer_nombre,' ',apellido_paterno,' ',apellido_materno) as 'nombre',
correo,
contrasena
");
$this->db->from('usuario as u');
$this->db->where('sha1(u.id)', $hash);
$res=$this->db->get();
if($res->num_rows()>0){
return $res->result_array();
}
return FALSE;
}
}
/* End of file homeModel.php */
/* Location: ./application/models/front_end/homeModel.php */
<file_sep><style type="text/css">
.btn_edita2{
margin:0;
color:#1E748D;
font-size: 13px;
text-decoration: none!important;
display: flex;
justify-content: center;
}
</style>
<script type="text/javascript" charset="utf-8">
$(function(){
/*****DEFINICIONES*****/
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
var session="<?php echo $this->session->userdata("id"); ?>";
var perfil="<?php echo $this->session->userdata("perfil"); ?>";
var base="<?php echo base_url();?>";
$.extend(true,$.fn.dataTable.defaults,{
info:false,
paging:false,
ordering:true,
searching:true,
lengthChange: false,
bSort: true,
bFilter: true,
bProcessing: true,
pagingType: "simple" ,
bAutoWidth: true,
sAjaxDataProp: "result",
bDeferRender: true,
language : {
url: "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json",
},
});
/*****DATATABLE*****/
var table_act = $('#tabla_act').DataTable({
"iDisplayLength":-1,
"aaSorting" : [[3,'asc']],
"scrollY": 420,
"scrollX": true,
select: true,
columnDefs:[
/* { "name": "acciones",targets: [0],searcheable : false,orderable:false},
{targets: [8], orderData: [5,6]}, //al ordenar por fecha, se ordenera por especialidad,comuna
{targets: [16],orderable:false,searcheable : false}, */
],
"ajax": {
"url":"<?php echo base_url();?>listaActividad",
"dataSrc": function (json) {
$(".btn_filtra_act").html('<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar');
$(".btn_filtra_act").prop("disabled" , false);
return json;
},
data: function(param){
param.empresa = $("#empresa").val();
}
},
"columns": [
{
"class":"","data": function(row,type,val,meta){
btn='<a href="#!" title="Editar" data-hash="'+row.hash_id+'" class="btn_edita2"><i class="fa fa-edit" style="font-size:14px;"></i> </a>';
return btn;
}
},
{ "data": "proyecto" ,"class":"margen-td "},
{ "data": "tipo_proyecto" ,"class":"margen-td "},
{ "data": "actividad" ,"class":"margen-td "},
{ "data": "unidad" ,"class":"margen-td "},
{ "data": "valor" ,"class":"margen-td "},
{ "data": "porcentaje" ,"class":"margen-td "}
]
});
setTimeout( function () {
var table_act = $.fn.dataTable.fnTables(true);
if ( table_act.length > 0 ) {
$(table_act).dataTable().fnAdjustColumnSizing();
}}, 2000 );
$(document).on('keyup paste', '#buscador_act', function() {
table_act.search($(this).val().trim()).draw();
});
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
setTimeout( function () {
var table_act = $.fn.dataTable.fnTables(true);
if ( table_act.length > 0 ) {
$(table_act).dataTable().fnAdjustColumnSizing();
}}, 100 );
$(document).off('click', '.btn_filtra_act').on('click', '.btn_filtra_act',function(event) {
event.preventDefault();
$(this).prop("disabled" , true);
$(".btn_filtra_act").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Filtrando');
table_act.ajax.reload();
});
/*******NUEVOINFORME**********/
$(document).off('click', '.btn_act').on('click', '.btn_act',function(event) {
$('#modal_act').modal('toggle');
$(".btn_ingresa_act").html('<i class="fa fa-save"></i> Guardar');
$(".btn_ingresa_act").attr("disabled", false);
$(".cierra_mod_act").attr("disabled", false);
$('#formActividad')[0].reset();
$("#id_actividad").val("");
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", false);
/*$('#proyecto_tipo_act').val("").trigger('change');*/
$('#actividad').val("").trigger('change');
});
$(document).off('submit', '#formActividad').on('submit', '#formActividad',function(event) {
var url="<?php echo base_url()?>";
var formElement = document.querySelector("#formActividad");
var formData = new FormData(formElement);
$.ajax({
url: $('#formActividad').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
beforeSend:function(){
$(".btn_ingresa_act").attr("disabled", true);
$(".cierra_mod_act").attr("disabled", true);
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", true);
},
success: function (data) {
if(data.res == "error"){
$(".btn_ingresa_act").attr("disabled", false);
$(".cierra_mod_act").attr("disabled", false);
$.notify(data.msg, {
className:'error',
globalPosition: 'top right',
autoHideDelay:5000,
});
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", false);
}else if(data.res == "ok"){
$(".btn_ingresa_act").attr("disabled", false);
$(".cierra_mod_act").attr("disabled", false);
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", false);
$.notify(data.msg, {
className:'success',
globalPosition: 'top right',
autoHideDelay:5000,
});
$('#modal_act').modal("toggle");
table_act.ajax.reload();
}
}
});
return false;
});
$.getJSON('getTiposPorPe', {pe: ""},
function(response) {
$("#proyecto_tipo_act").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
/*******MODINFORME**********/
$(document).off('click', '.btn_edita2').on('click', '.btn_edita2',function(event) {
hash=$(this).attr("data-hash");
$(".btn_ingresa_act").html('<i class="fa fa-edit" ></i> Modificar');
$('#formActividad')[0].reset();
$("#id_actividad").val("");
$('#modal_act').modal("toggle");
$(".cierra_mod_act").prop("disabled", false);
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", false);
$.ajax({
url: "getDataActividad"+"?"+$.now(),
type: 'POST',
cache: false,
tryCount : 0,
retryLimit : 3,
data:{hash:hash},
dataType:"json",
beforeSend:function(){
$(".btn_ingresa_act").prop("disabled",true);
$(".cierra_mod_act").prop("disabled",true);
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", true);
},
success: function (data) {
if(data.res=="ok"){
for(dato in data.datos){
actividad=data.datos[dato].actividad;
id_proyecto_empresa=data.datos[dato].id_proyecto_empresa;
id_proyecto_tipo=data.datos[dato].id_proyecto_tipo;
$("#id_actividad").val(data.datos[dato].hash_id);
$("#actividad").val(data.datos[dato].actividad);
$("#unidad").val(data.datos[dato].unidad);
$("#valor").val(data.datos[dato].valor);
$("#porcentaje").val(data.datos[dato].porcentaje);
$("#proyecto_empresa option[value='"+data.datos[dato].id_proyecto_empresa+"'").prop("selected", true);
$("#proyecto_tipo_act option[value='"+data.datos[dato].id_proyecto_tipo+"'").prop("selected", true);
setTimeout( function () {
$.getJSON('getTiposPorPe', {pe: id_proyecto_empresa},
function(response) {
$("#proyecto_tipo_act").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
$('#proyecto_tipo_act').val(id_proyecto_tipo).trigger('change');
},1000);
}
$("#formActividad input,#formActividad select,#formActividad button,#formActividad").prop("disabled", false);
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.notify("Reintentando...", {
className:'info',
globalPosition: 'top right'
});
$.ajax(this);
return;
} else{
$.notify("Problemas en el servidor, intente nuevamente.", {
className:'warn',
globalPosition: 'top right'
});
$('#modal_act').modal("toggle");
}
return;
}
if (xhr.status == 500) {
$.notify("Problemas en el servidor, intente más tarde.", {
className:'warn',
globalPosition: 'top right'
});
$('#modal_act').modal("toggle");
}
},timeout:5000
});
});
/*$(document).off('click', '.btn_elimina').on('click', '.btn_elimina',function(event) {
hash=$(this).attr("data-hash");
if(confirm("¿Esta seguro que desea eliminar este registro?")){
$.post('deleteActividad'+"?"+$.now(),{"hash": hash}, function(data) {
if(data.res=="ok"){
$.notify(data.msg, {
className:'success',
globalPosition: 'top right'
});
table_act.ajax.reload();
}else{
$.notify(data.msg, {
className:'danger',
globalPosition: 'top right'
});
}
},"json");
}
});*/
$(document).off('change', '#proyecto_empresa').on('change', '#proyecto_empresa', function(event) {
event.preventDefault();
pe=$("#proyecto_empresa").val();
$('#proyecto_tipo_act').html('').select2({data: [{id: '', text: ''}]});
$.getJSON('getTiposPorPe', {pe: pe},
function(response) {
$("#proyecto_tipo_act").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
});
/*$(document).on('keyup', '#porcentaje', function(event) {
event.preventDefault();
var num = $("#porcentaje").val();
if(num <= 0 || num > 100){
$("#porcentaje").css("border-color", "red");
}
else{
$("#porcentaje").css("border-color", "");
}
});*/
/*$(".validRange").onclick(function(event){
event.preventDefault();
var num = $("#porcentaje").val();
if(num <= 0 || num > 100){
alert("porcentaje debe ser entre 1 y 100");
}
});*/
/********OTROS**********/
$(".floattext").keydown(function (event) {
if (event.shiftKey == true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {
} else {
event.preventDefault();
}
if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
event.preventDefault();
});
$(".inttext").keydown(function (event) {
if (event.shiftKey == true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 46) {
} else {
event.preventDefault();
}
});
$(document).on('click', '.btn_excel_inf', function(event) {
event.preventDefault();
var empresa = $("#empresa").val();
if(empresa==""){
empresa=0;
}
window.location="excelInforme/"+empresa;
});
})
</script>
<!--FILTROS-->
<div class="form-row">
<div class="col-6 col-lg-2">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-sm btn-outline-primary btn_act">
<i class="fa fa-plus-circle"></i> Nuevo
</button>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<select id="empresa" name="empresa" class="custom-select custom-select-sm">
<option selected value="">Proyecto empresa | Todos</option>
<?php
foreach($proyecto_empresa as $p){
?>
<option value="<?php echo $p["id"]; ?>"><?php echo $p["nombre"]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<input type="text" placeholder="Ingrese su busqueda..." id="buscador_act" class="buscador_act form-control form-control-sm">
</div>
</div>
<div class="col-6 col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-outline-primary btn-primary btn_filtra_act">
<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar
</button>
</div>
</div>
<div class="col-6 col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-outline-primary btn-primary btn_excel_inf">
<i class="fa fa-save"></i> Excel
</button>
</div>
</div>
</div>
<!-- LISTADO -->
<div class="row">
<div class="col">
<table id="tabla_act" class="table table-hover table-bordered dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th style="width:80px;">Acciones</th>
<th>Proyecto Empresa</th>
<th>Proyecto Tipo</th>
<th>Actividad</th>
<th>Unidad</th>
<th>Valor</th>
<th>Porcentaje</th>
</tr>
</thead>
</table>
</div>
</div>
<!-- FORMULARIOS-->
<!-- NUEVO INFORME-->
<div id="modal_act" class="modal fade bd-example-modal-lg" data-backdrop="static" aria-labelledby="myModalLabel" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<?php echo form_open_multipart("formActividad",array("id"=>"formActividad","class"=>"formActividad"))?>
<input type="hidden" name="id_actividad" id="id_actividad">
<button type="button" title="Cerrar Ventana" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<fieldset class="form-ing-cont">
<legend class="form-ing-border">Creación De Actividades</legend>
<div class="form-row">
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Proyecto Empresa</label>
<select id="proyecto_empresa" name="proyecto_empresa" class="custom-select custom-select-sm">
<option selected value="">Seleccione Proyecto Empresa</option>
<?php
foreach($proyecto_empresa as $p){
?>
<option value="<?php echo $p["id"]; ?>"><?php echo $p["nombre"]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Proyecto Tipo</label>
<select id="proyecto_tipo_act" name="proyecto_tipo" class="custom-select custom-select-sm" style="width:100%!important;">
<option selected value="">Seleccione Tipo Proyecto </option>
</select>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Actividad</label>
<input type="text" autocomplete="off" placeholder="Ingrese Nombre De Actividad" class="form-control form-control-sm" name="actividad" id="actividad">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Unidad</label>
<input type="text" autocomplete="off" placeholder="Ingrese Unidad" class="form-control form-control-sm" name="unidad" id="unidad">
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Valor</label>
<input type="text" id="valor" autocomplete="off" placeholder="Ingrese Valor" class="inttext form-control form-control-sm" name="valor">
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Porcentaje</label>
<input type="text" minlength="1" maxlength="3" autocomplete="off" placeholder="Ingrese Porcentaje" class="inttext form-control form-control-sm" name="porcentaje" id="porcentaje" onsubmit="return validarRango(this);">
</div>
</div>
</div>
</fieldset>
<br>
<div class="col-lg-4 offset-lg-4">
<div class="form-row">
<div class="col-6 col-lg-6">
<div class="form-group">
<button type="submit" class="btn-block btn btn-sm btn-primary btn_ingresa_act">
<i class="fa fa-save"></i> Guardar
</button>
</div>
</div>
<div class="col-6 col-lg-6">
<button class="btn-block btn btn-sm btn-dark cierra_mod_inf" data-dismiss="modal" aria-hidden="true">
<i class="fa fa-window-close"></i> Cerrar
</button>
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
<file_sep><style type="text/css">
.modal-modpass{
width:40%!important;
}
</style>
<script type="text/javascript">
$(function(){
$(window).on('load', function(){
window.setTimeout(function(){
$('#body').addClass('loaded');
} , 0);
});
$(document).off('submit', '#actualizarPassForm').on('submit', '#actualizarPassForm', function(event) {
var url="<?php echo base_url()?>";
var formElement = document.querySelector("#actualizarPassForm");
var formData = new FormData(formElement);
$.ajax({
url: $('.actualizarPassForm').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
beforeSend:function(){
$("#actualizarPassForm input,#actualizarPassForm select,#actualizarPassForm button,#actualizarPassForm").prop("disabled", true);
},
success: function (data) {
if(data.res == "error"){
$.notify(data.msg, {
className:'error',
globalPosition: 'top right'
});
$("#actualizarPassForm input,#actualizarPassForm select,#actualizarPassForm button,#actualizarPassForm").prop("disabled", false);
}else if(data.res == "ok"){
$.notify(data.msg, {
className:'success',
globalPosition: 'top right'
});
$("#pass_us").val("");
$("#actualizarPassForm input,#actualizarPassForm select,#actualizarPassForm button,#actualizarPassForm").prop("disabled", false);
}else if(data.res=="sess"){
window.location="unlogin";
}
}
});
return false;
});
});
</script>
<!-- INGRESO modal fade-->
<div id="actualizarPassModal" class="modal fade" data-backdrop="static" tabindex="-1" aria-labelledby="myModalLabel" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-modpass">
<div class="modal-content">
<?php echo form_open_multipart("actualizarPassForm",array("id"=>"actualizarPassForm","class"=>"actualizarPassForm"))?>
<div class="row">
<div class="modal-body" style="padding:10px 20px; margin-left: 10px;">
<button type="button" title="Cerrar Ventana" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<fieldset class="form-ing-cont" style="border: 1px solid #ccc!important;">
<legend class="form-ing-border">Actualizar contraseña</legend>
<div class="col-lg-12">
<div class="form-group">
<input placeholder="Ingrese nueva Contraseña" size="15" maxlength="15" type="text" name="pass_us" id="pass_us" class="form-control form-control-sm" autocomplete="off" />
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<label> </label>
<center>
<button title="Actualizar" type="submit" class="btn btn-sm btn-outline-primary btn-primary btn_mod_user">
<i class="fa fa-edit"></i> Actualizar
</button>
<button class="btn_cerrar_user btn btn-sm btn-outline-primary btn-primary" data-dismiss="modal" aria-hidden="true">
<i class="fa fa-window-close"></i> Cerrar
</button>
</center>
</div>
</div>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
</div>
<footer class="footer text-center">
<?php
if($this->session->userdata('empresaCPP')=="km"){
?>
<p> © KM Telecomunicaciones <?php echo date("Y");?></p>
<?php
}elseif ($this->session->userdata('empresaCPP')=="splice") {
?>
<p> © Splice Chile <?php echo date("Y");?></p>
<?php
}
?>
</footer>
<script src="<?php echo base_url();?>assets/back_end/js/popper.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/bootstrap.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/jquery.dataTables.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/moment-with-locales.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/notify.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/select2.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/clockpicker.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/bootstrap-datetimepicker.min2.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/rut.min.js" charset="UTF-8"></script>
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/select2.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/select.dataTables.min.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/clockpicker.css" >
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/bootstrap.min.css" >
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/bootstrap-datetimepicker.min2.css">
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/normalize.min.css" rel="stylesheet">
<?php
if($this->session->userdata('empresaCPP')=="km"){
?>
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/estilos_km.css">
<?php
}elseif ($this->session->userdata('empresaCPP')=="splice") {
?>
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/estilos_splice.css">
<?php
}
?>
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/fontawesome-all.min.css">
<script src="<?php echo base_url();?>assets/back_end/js/dataTables.select.min.js"></script>
</body>
</html><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CPPmodel extends CI_Model {
public function __construct(){
parent::__construct();
}
public function insertarVisita($data){
if($this->db->insert('visitas', $data)){
return TRUE;
}
return FALSE;
}
/***********CPP**********/
public function listaCPP($desde,$hasta,$accion){
$this->db->select("SHA1(c.id) as 'hash_id',
c.id as id,
c.id_actividad as id_actividad,
cpe.id as id_proyecto_empresa,
ca.actividad as actividad,
ca.unidad as unidad,
ca.valor as valor,
cpe.proyecto_empresa as proyecto_empresa,
ca.id_proyecto_tipo as id_proyecto_tipo,
cpt.tipo as proyecto_tipo,
c.id_usuario as id_usuario,
c.id_supervisor as id_supervisor,
c.id_digitador as id_digitador,
c.cantidad as cantidad,
c.proyecto_descripcion as proyecto_desc,
c.estado as estado,
CASE
WHEN c.estado = '0' THEN 'Pend. superv.'
WHEN c.estado = '1' THEN 'Aprob. superv.'
END AS estado_str,
c.comentarios as comentarios,
hour(TIMEDIFF(CONCAT(c.fecha_termino,' ',c.hora_termino),CONCAT(c.fecha_inicio,' ',c.hora_inicio))) as 'duracion',
if(c.fecha_inicio!='0000-00-00',c.fecha_inicio,'') as 'fecha_inicio',
if(c.hora_inicio!='00:00:00',c.hora_inicio,'') as 'hora_inicio',
if(c.fecha_termino!='0000-00-00',c.fecha_termino,'') as 'fecha_termino',
if(c.hora_termino!='00:00:00',c.hora_termino,'') as 'hora_termino',
if(c.fecha_aprobacion!='0000-00-00',c.fecha_aprobacion,'') as 'fecha_aprob',
if(c.hora_aprobacion!='00:00:00',c.hora_aprobacion,'') as 'hora_aprob',
if(c.fecha_digitacion!='0000-00-00',c.fecha_digitacion,'') as 'fecha_dig',
CONCAT(us.primer_nombre,' ',us.apellido_paterno) as 'ejecutor',
CONCAT(uss.primer_nombre,' ',uss.apellido_paterno) as 'supervisor',
CONCAT(usss.primer_nombre,' ',usss.apellido_paterno) as 'digitador',
c.ultima_actualizacion as ultima_actualizacion
",false);
$this->db->from('cpp as c');
$this->db->join('cpp_actividades as ca', 'ca.id = c.id_actividad', 'left');
$this->db->join('cpp_proyecto_tipo as cpt', 'cpt.id = ca.id_proyecto_tipo', 'left');
$this->db->join('cpp_proyecto_empresa as cpe', 'cpe.id = cpt.id_proyecto_empresa', 'left');
$this->db->join('cpp_usuarios as u1', 'c.id_usuario = u1.id_usuario', 'left');
$this->db->join('cpp_usuarios as u2', 'c.id_supervisor = u2.id_usuario', 'left');
$this->db->join('cpp_usuarios as u3', 'c.id_digitador = u3.id_usuario', 'left');
$this->db->join('usuario as us', 'us.id = u1.id_usuario', 'left');
$this->db->join('usuario as uss', 'uss.id = u2.id_usuario', 'left');
$this->db->join('usuario as usss', 'usss.id = u3.id_usuario', 'left');
if($desde!="" and $hasta!=""){
$this->db->where("c.fecha_termino BETWEEN '".$desde."' AND '".$hasta."'");
}else{
$this->db->where("c.fecha_termino BETWEEN '".$inicio."' AND '".date("Y-m-d")."'");
}
//ACCION 1 = TODOS LOS REGISTROS
if($accion==2){//PERSONAL DE SUPERVISOR
$this->db->where('(u1.id_supervisor='.$this->session->userdata("idUsuarioCPP")."
or u1.id_supervisor2=".$this->session->userdata("idUsuarioCPP")."
or us.id=".$this->session->userdata("idUsuarioCPP").")");
}
if($accion==3){//REGISTROS DEL USUARIO
$this->db->where('c.id_usuario', $this->session->userdata("idUsuarioCPP"));
}
$this->db->order_by('c.id', 'desc');
$res=$this->db->get();
if($res->num_rows()>0){
return $res->result_array();
}
return FALSE;
}
public function getDataAct($hash){
$this->db->select("SHA1(c.id) as 'hash_id',
c.id as id,
c.id_actividad as id_actividad,
cpe.id as id_proyecto_empresa,
ca.actividad as actividad,
ca.unidad as unidad,
cpe.proyecto_empresa as proyecto_empresa,
ca.id_proyecto_tipo as id_proyecto_tipo,
cpt.tipo as proyecto_tipo,
c.id_usuario as id_usuario,
c.id_supervisor as id_supervisor,
c.id_digitador as id_digitador,
c.cantidad as cantidad,
c.proyecto_descripcion as proyecto_desc,
c.estado as estado,
CASE
WHEN c.estado = '0' THEN 'Pendiente supervisor'
WHEN c.estado = '1' THEN 'Aprobado supervisor'
END AS estado_str,
c.comentarios as comentarios,
'duracion' as duracion,
if(c.fecha_inicio!='0000-00-00',c.fecha_inicio,'') as 'fecha_inicio',
if(c.hora_inicio!='00:00:00',c.hora_inicio,'') as 'hora_inicio',
if(c.fecha_termino!='0000-00-00',c.fecha_termino,'') as 'fecha_termino',
if(c.hora_termino!='00:00:00',c.hora_termino,'') as 'hora_termino',
if(c.fecha_aprobacion!='0000-00-00',c.fecha_aprobacion,'') as 'fecha_aprob',
if(c.hora_aprobacion!='00:00:00',c.hora_aprobacion,'') as 'hora_aprob',
if(c.fecha_digitacion!='0000-00-00',c.fecha_digitacion,'') as 'fecha_dig',
CONCAT(us.primer_nombre,' ',us.apellido_paterno) as 'ejecutor',
CONCAT(uss.primer_nombre,' ',uss.apellido_paterno) as 'supervisor',
CONCAT(usss.primer_nombre,' ',usss.apellido_paterno) as 'digitador',
c.ultima_actualizacion as ultima_actualizacion
");
$this->db->from('cpp as c');
$this->db->join('cpp_actividades as ca', 'ca.id = c.id_actividad', 'left');
$this->db->join('cpp_proyecto_tipo as cpt', 'cpt.id = ca.id_proyecto_tipo', 'left');
$this->db->join('cpp_proyecto_empresa as cpe', 'cpe.id = cpt.id_proyecto_empresa', 'left');
$this->db->join('cpp_usuarios as u1', 'c.id_usuario = u1.id_usuario', 'left');
$this->db->join('cpp_usuarios as u2', 'c.id_supervisor = u2.id_usuario', 'left');
$this->db->join('cpp_usuarios as u3', 'c.id_digitador = u3.id_usuario', 'left');
$this->db->join('usuario as us', 'us.id = u1.id_usuario', 'left');
$this->db->join('usuario as uss', 'uss.id = u2.id_usuario', 'left');
$this->db->join('usuario as usss', 'usss.id = u3.id_usuario', 'left');
$this->db->where('sha1(c.id)', $hash);
$res=$this->db->get();
if($res->num_rows()>0){
return $res->result_array();
}
}
public function getEstadoCpp($id_cpp){
$this->db->select('estado');
$this->db->where('sha1(id)', $id_cpp);
$res=$this->db->get('cpp');
if($res->num_rows()>0){
$row=$res->row_array();
return $row["estado"];
}
return FALSE;
}
public function listaProyectoEmpresa(){
$this->db->select('id,proyecto_empresa as nombre');
$this->db->order_by('id', 'asc');
$res=$this->db->get('cpp_proyecto_empresa');
return $res->result_array();
}
public function getTiposPorPe($pe){
if($pe!=""){
$this->db->where('id_proyecto_empresa', $pe);
}
$this->db->order_by('tipo', 'asc');
$res=$this->db->get('cpp_proyecto_tipo');
if($res->num_rows()>0){
$array=array();
foreach($res->result_array() as $key){
$temp=array();
$temp["id"]=$key["id"];
$temp["text"]=$key["tipo"];
$array[]=$temp;
}
return json_encode($array);
}
}
public function getActividadesPorTipo($pt){
if($pt!=""){
$this->db->where('id_proyecto_tipo', $pt);
}
$this->db->order_by('actividad', 'asc');
$res=$this->db->get('cpp_actividades');
if($res->num_rows()>0){
$array=array();
foreach($res->result_array() as $key){
$temp=array();
$temp["id"]=$key["id"];
$temp["text"]=$key["actividad"];
$array[]=$temp;
}
return json_encode($array);
}
}
public function eliminaActividad($hash){
$this->db->where('sha1(id)', $hash);
$this ->db->delete('cpp');
return TRUE;
}
public function checkNumeroOrden($numero){
$this->db->where('numero_orden', $numero);
$res=$this->db->get('movistar_informes_de_avance');
if($res->num_rows()>0){
return TRUE;
}
return FALSE;
}
public function formCPP($data){
if($this->db->insert('cpp', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}
return FALSE;
}
public function modFormCPP($id,$data){
$this->db->where('sha1(id)', $id);
if($this->db->update('cpp', $data)){
return TRUE;
}
return FALSE;
}
public function getUmPorActividad($ac){
$this->db->select('unidad');
$this->db->where('id', $ac);
$res=$this->db->get('cpp_actividades');
if($res->num_rows()>0){
$row=$res->row_array();
return $row["unidad"];
}else{
return FALSE;
}
}
public function getUsuariosSel2CPP($accion){
$this->db->select('u.id as id,
u.primer_nombre as primer_nombre,
u.apellido_paterno as apellido_paterno,
u.apellido_materno as apellido_materno,
u.empresa as empresa');
$this->db->where('estado', "Activo");
//ACCION 1 = TODOS LOS REGISTROS
if($accion==2){//PERSONAL DE SUPERVISOR
$this->db->where('(cu.id_supervisor='.$this->session->userdata("idUsuarioCPP")."
or cu.id_supervisor2=".$this->session->userdata("idUsuarioCPP")."
or u.id=".$this->session->userdata("idUsuarioCPP").")");
}
if($accion==3){//REGISTROS DEL USUARIO
$this->db->where('cu.id_usuario', $this->session->userdata("idUsuarioCPP"));
}
$this->db->order_by('u.primer_nombre', 'asc');
$this->db->join('usuario as u', 'u.id = cu.id_usuario', 'left');
$res=$this->db->get("cpp_usuarios as cu");
if($res->num_rows()>0){
$array=array();
foreach($res->result_array() as $key){
$temp=array();
$temp["id"]=$key["id"];
$temp["text"]=$key["primer_nombre"]." ".$key["apellido_paterno"]." ".$key["apellido_materno"]." | ".$key["empresa"];
$array[]=$temp;
}
return json_encode($array);
}
return FALSE;
}
/***********VISTA MENSUAL**********/
public function listaMes($fecha,$usuario,$accion){
$this->db->select("SHA1(c.id) as 'hash_id',
c.id as id,
c.id_actividad as id_actividad,
cpe.id as id_proyecto_empresa,
ca.actividad as actividad,
ca.unidad as unidad,
ca.valor as valor,
cpe.proyecto_empresa as proyecto_empresa,
ca.id_proyecto_tipo as id_proyecto_tipo,
cpt.tipo as proyecto_tipo,
c.id_usuario as id_usuario,
c.id_supervisor as id_supervisor,
c.id_digitador as id_digitador,
c.cantidad as cantidad,
c.proyecto_descripcion as proyecto_desc,
c.estado as estado,
CASE DATE_FORMAT(c.fecha_termino, '%W')
WHEN 'Sunday' THEN 'Domingo'
WHEN 'Monday' THEN 'Lunes'
WHEN 'Tuesday' THEN 'Martes'
WHEN 'Wednesday' THEN 'Miercoles'
WHEN 'Thursday' THEN 'Jueves'
WHEN 'Friday' THEN 'Viernes'
WHEN 'Saturday' THEN 'Sabado'
END AS 'dia',
CASE
WHEN c.estado = '0' THEN 'Pend. superv.'
WHEN c.estado = '1' THEN 'Aprob. superv.'
END AS estado_str,
c.comentarios as comentarios,
if(c.fecha_inicio!='0000-00-00',DATE_FORMAT(c.fecha_inicio,'%d-%m-%Y'),'') as 'fecha_inicio',
if(c.hora_inicio!='00:00:00',c.hora_inicio,'') as 'hora_inicio',
if(c.fecha_termino!='0000-00-00',DATE_FORMAT(c.fecha_termino,'%d-%m-%Y'),'') as 'fecha_termino',
if(c.hora_termino!='00:00:00',c.hora_termino,'') as 'hora_termino',
if(c.fecha_aprobacion!='0000-00-00',DATE_FORMAT(c.fecha_aprobacion,'%d-%m-%Y'),'') as 'fecha_aprob',
if(c.hora_aprobacion!='00:00:00',c.hora_aprobacion,'') as 'hora_aprob',
if(c.fecha_digitacion!='0000-00-00',DATE_FORMAT(c.fecha_digitacion,'%d-%m-%Y'),'') as 'fecha_dig',
CONCAT(us.primer_nombre,' ',us.apellido_paterno) as 'ejecutor',
CONCAT(uss.primer_nombre,' ',uss.apellido_paterno) as 'supervisor',
CONCAT(usss.primer_nombre,' ',usss.apellido_paterno) as 'digitador',
c.ultima_actualizacion as ultima_actualizacion
",false);
$this->db->from('cpp as c');
$this->db->join('cpp_actividades as ca', 'ca.id = c.id_actividad', 'left');
$this->db->join('cpp_proyecto_tipo as cpt', 'cpt.id = ca.id_proyecto_tipo', 'left');
$this->db->join('cpp_proyecto_empresa as cpe', 'cpe.id = cpt.id_proyecto_empresa', 'left');
$this->db->join('cpp_usuarios as u1', 'c.id_usuario = u1.id_usuario', 'left');
$this->db->join('cpp_usuarios as u2', 'c.id_supervisor = u2.id_usuario', 'left');
$this->db->join('cpp_usuarios as u3', 'c.id_digitador = u3.id_usuario', 'left');
$this->db->join('usuario as us', 'us.id = u1.id_usuario', 'left');
$this->db->join('usuario as uss', 'uss.id = u2.id_usuario', 'left');
$this->db->join('usuario as usss', 'usss.id = u3.id_usuario', 'left');
$this->db->where('MONTH(c.fecha_termino)=',date("m", strtotime($fecha)));
$this->db->where('YEAR(c.fecha_termino)=',date("Y", strtotime($fecha)));
if($usuario!=""){
$this->db->where('u1.id_usuario', $usuario);
}
//ACCION 1 = TODOS LOS REGISTROS
if($accion==2){//PERSONAL DE SUPERVISOR
$this->db->where('(u1.id_supervisor='.$this->session->userdata("idUsuarioCPP")."
or u1.id_supervisor2=".$this->session->userdata("idUsuarioCPP")."
or us.id=".$this->session->userdata("idUsuarioCPP").")");
}
if($accion==3){//REGISTROS DEL USUARIO
$this->db->where('c.id_usuario', $this->session->userdata("idUsuarioCPP"));
}
$this->db->order_by('c.fecha_termino', 'desc');
$this->db->order_by('c.hora_termino', 'desc');
$res=$this->db->get();
if($res->num_rows()>0){
return $res->result_array();
}
return FALSE;
}
public function getNombrePorId($id){
$this->db->select('primer_nombre,apellido_paterno,apellido_materno');
$this->db->where('id', $id);
$res=$this->db->get('usuario');
if($res->num_rows()>0){
$row=$res->row_array();
return $row["primer_nombre"]." ".$row["apellido_paterno"]." ".$row["apellido_materno"];
}else{
return FALSE;
}
}
/***********MANTENEDOR ACTIVIDADES**********/
public function formActividad($data){
if($this->db->insert('cpp_actividades', $data)){
$insert_id = $this->db->insert_id();
return $insert_id;
}
return FALSE;
}
public function modFormActividad($id,$data){
$this->db->where('sha1(id)', $id);
if($this->db->update('cpp_actividades', $data)){
return TRUE;
}
return FALSE;
}
public function listaActividad($empresa){
$this->db->select("SHA1(a.id) as 'hash_id',
a.id as id,
pe.proyecto_empresa as proyecto,
pe.id as id_proyecto_empresa,
pt.tipo as tipo_proyecto,
a.id_proyecto_tipo as proyecto_tipo,
a.actividad as actividad,
a.unidad as unidad,
a.valor as valor,
a.porcentaje as porcentaje");
$this->db->from('cpp_actividades as a');
$this->db->join('cpp_proyecto_tipo as pt', 'pt.id = a.id_proyecto_tipo');
$this->db->join('cpp_proyecto_empresa as pe', 'pe.id = pt.id_proyecto_empresa');
if($empresa != ""){
$this->db->where("pe.id", $empresa);
}
$res=$this->db->get();
if($res->num_rows()>0){
return $res->result_array();
}
return FALSE;
}
public function deleteActividad($hash){
$this->db->where('sha1(id)', $hash);
$this ->db->delete('cpp_actividades');
return TRUE;
}
public function getDataActividad($hash){
$this->db->select("SHA1(a.id) as 'hash_id', a.id as id, pe.proyecto_empresa as proyecto,
pe.id as id_proyecto_empresa, a.id_proyecto_tipo as id_proyecto_tipo, a.actividad as actividad,
a.unidad as unidad, a.valor as valor, a.porcentaje as porcentaje");
$this->db->from('cpp_actividades as a');
$this->db->join('cpp_proyecto_tipo as pt', 'pt.id = a.id_proyecto_tipo');
$this->db->join('cpp_proyecto_empresa as pe', 'pe.id = pt.id_proyecto_empresa');
$this->db->where('sha1(a.id)', $hash);
$res=$this->db->get();
if($res->num_rows()>0){
return $res->result_array();
}
return FALSE;
}
public function checkActividad($id){
$this->db->where('actividad', $id);
$res=$this->db->get('cpp_actividades');
if($res->num_rows()>0){
return TRUE;
}
return FALSE;
}
/***********MANTENEDOR USUARIOS**********/
public function getUsuariosSel2(){
$this->db->select('id,rut,primer_nombre,segundo_nombre,apellido_paterno,apellido_materno,empresa');
$this->db->where('estado', "Activo");
$this->db->order_by('primer_nombre', 'asc');
$res=$this->db->get("usuario");
if($res->num_rows()>0){
$array=array();
foreach($res->result_array() as $key){
$temp=array();
$temp["id"]=$key["id"];
$temp["text"]=$key["primer_nombre"]." ".$key["apellido_paterno"]." ".$key["apellido_materno"]." | ".$key["empresa"];
$array[]=$temp;
}
return json_encode($array);
}
return FALSE;
}
public function checkUsuario($id){
$this->db->where('id_usuario', $id);
$res=$this->db->get('cpp_usuarios');
if($res->num_rows()>0){
return TRUE;
}
return FALSE;
}
public function checkUsuarioMod($hash,$id){
$this->db->where('sha1(id)', $hash);
$this->db->where('id_usuario<>', $id);
$res=$this->db->get('cpp_usuarios');
if($res->num_rows()>0){
return TRUE;
}
return FALSE;
}
public function getPerfiles(){
$this->db->order_by('id', 'asc');
$res=$this->db->get('cpp_usuarios_perfiles');
return $res->result_array();
}
public function listaMantUsuarios(){
$this->db->select("sha1(cu.id) as hash_id,
cu.id as id_mant,
u.id as id_usuario,
us.id as id_supervisor,
us2.id as id_supervisor2,
u.rut as rut,
c.cargo as cargo,
u.empresa as empresa,
CONCAT(u.primer_nombre,' ',u.apellido_paterno,' ',u.apellido_materno) as 'usuario',
CONCAT(us.primer_nombre,' ',us.apellido_paterno,' ',us.apellido_materno) as 'supervisor',
CONCAT(us2.primer_nombre,' ',us2.apellido_paterno,' ',us2.apellido_materno) as 'supervisor2',
up.perfil as perfil,
up.id as id_perfil,
cu.ultima_actualizacion as ultima_actualizacion
");
$this->db->join('cpp_usuarios as cu', 'cu.id_usuario = u.id', 'right');
$this->db->join('cpp_usuarios_perfiles as up', 'up.id = cu.id_perfil', 'left');
$this->db->join('usuario as us', 'us.id = cu.id_supervisor', 'left');
$this->db->join('usuario as us2', 'us2.id = cu.id_supervisor2', 'left');
$this->db->join('mantenedor_cargo as c', 'u.id_cargo = c.id', 'left');
if($this->session->userdata('idUsuarioCPP')!=432 and $this->session->userdata('idUsuarioCPP')!=824){
$this->db->where('(cu.id_usuario<>432 and cu.id_usuario<>824)');
}
$res=$this->db->get('usuario as u');
return $res->result_array();
}
public function formMantUs($data){
if($this->db->insert('cpp_usuarios', $data)){
return TRUE;
}
return FALSE;
}
public function modFormMantUs($id,$data){
$this->db->where('sha1(id)', $id);
if($this->db->update('cpp_usuarios', $data)){
return TRUE;
}
return FALSE;
}
public function getDataMantUs($hash){
$this->db->select("sha1(cu.id) as hash_id,
cu.id as id_mant,
u.id as id_usuario,
us.id as id_supervisor,
us2.id as id_supervisor2,
u.rut as rut,
u.empresa as empresa,
CONCAT(u.primer_nombre,' ',u.apellido_paterno) as 'usuario',
CONCAT(us.primer_nombre,' ',us.apellido_paterno) as 'supervisor',
CONCAT(us2.primer_nombre,' ',us2.apellido_paterno) as 'supervisor2',
up.perfil as perfil,
up.id as id_perfil,
cu.ultima_actualizacion as ultima_actualizacion
");
$this->db->join('cpp_usuarios as cu', 'cu.id_usuario = u.id', 'right');
$this->db->join('cpp_usuarios_perfiles as up', 'up.id = cu.id_perfil', 'left');
$this->db->join('usuario as us', 'us.id = cu.id_supervisor', 'left');
$this->db->join('usuario as us2', 'us2.id = cu.id_supervisor2', 'left');
$this->db->where('sha1(cu.id)', $hash);
$res=$this->db->get('usuario as u');
if($res->num_rows()>0){
return $res->result_array();
}
}
public function getSupervisores(){
$this->db->select("CONCAT(us.primer_nombre,' ',us.apellido_paterno) as 'nombre',us.id as id");
$this->db->join('usuario as us', 'us.id = u1.id_usuario', 'left');
$this->db->where('u1.id_perfil', "3");
$res=$this->db->get('cpp_usuarios as u1');
return $res->result_array();
}
public function eliminaUsuario($hash){
$this->db->where('sha1(id)', $hash);
$this ->db->delete('cpp_usuarios');
return TRUE;
}
}<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 09-07-2018 a las 18:16:13
-- Versión del servidor: 10.1.25-MariaDB
-- Versión de PHP: 5.6.31
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 */;
--
-- Base de datos: `km1`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cpp_actividades`
--
CREATE TABLE `cpp_actividades` (
`id` int(11) NOT NULL,
`id_proyecto_tipo` int(11) NOT NULL,
`actividad` varchar(200) NOT NULL,
`unidad` varchar(200) NOT NULL,
`valor` int(11) NOT NULL,
`porcentaje` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `cpp_actividades`
--
INSERT INTO `cpp_actividades` (`id`, `id_proyecto_tipo`, `actividad`, `unidad`, `valor`, `porcentaje`) VALUES
(1, 1, 'Levantamiento – HP', 'HP', 1, 100),
(2, 1, 'Dibujo', 'HP', 1, 100),
(3, 1, 'Control Calidad HP', 'HP', 1, 100),
(4, 2, 'Segmentación', 'HP', 1, 100),
(5, 2, 'Conglomerado', 'HH', 1, 100),
(6, 2, 'Diseño', 'HP', 1, 100),
(7, 2, 'Control calidad', 'HH', 1, 100),
(8, 3, 'Preparación información', 'HH', 1, 100),
(9, 3, 'Relevamiento', 'HP', 1, 100),
(10, 3, 'Diseño FO', 'MTS', 1, 100),
(11, 3, 'Control Calidad', 'HH', 1, 100),
(12, 4, 'Informe Retiro informacion', 'HH', 1, 100),
(13, 4, 'Informe Desarrollo Plano y Carta', 'HH', 1, 100),
(14, 4, 'Informe Control Calidad', 'HH', 1, 100),
(15, 4, 'Presupuesto Retiro informacion', 'HH', 1, 100),
(16, 4, 'Presupuesto Desarrollo Prepoyecto', 'HH', 1, 100),
(17, 4, 'Presupuesto Control Calidad', 'HH', 1, 100),
(18, 4, 'Proyecto Retiro informacion', 'HH', 1, 100),
(19, 4, 'Proyecto Preparación información', 'HH', 1, 100),
(20, 4, 'Proyecto Relevamiento', 'MTS', 1, 100),
(21, 4, 'Proyecto Diseño FO CU', 'MTS', 1, 100),
(22, 4, 'Proyecto Diseño HFC', 'HP', 1, 100),
(23, 4, 'Proyecto Control Calidad', 'HH', 1, 100),
(24, 4, 'BTS Retiro informacion', 'HH', 1, 100),
(25, 4, 'BTS Preparación información', 'HH', 1, 100),
(26, 4, 'BTS Relevamiento', 'MTS', 1, 100),
(27, 4, 'BTS Diseño FO', 'MTS', 1, 100),
(28, 4, 'BTS Control Calidad', 'HH', 1, 100),
(29, 5, 'Retiro informacion', 'HH', 1, 100),
(30, 5, 'Preparación información', 'HH', 1, 100),
(31, 5, 'Relevamiento', 'HP', 1, 100),
(32, 5, 'Diseño VERTICAL', 'HP', 1, 100),
(33, 5, 'Control Calidad', 'HH', 1, 100),
(34, 6, 'Preparación información', 'HH', 1, 100),
(35, 6, 'Relevamiento', 'HP', 1, 100),
(36, 6, 'Diseño VERTICAL', 'HP', 1, 100),
(37, 6, 'Control Calidad', 'HH', 1, 100),
(38, 7, 'Levantamiento – HP', 'HP', 1, 100),
(39, 7, 'Dibujo', 'HP', 1, 100),
(40, 7, 'Control Calidad HP', 'HP', 1, 100),
(41, 8, 'Macro DISEÑO', 'HP', 1, 100),
(42, 8, 'Conglomerado', 'HH', 1, 100),
(43, 8, 'Diseño', 'HP', 1, 100),
(44, 8, 'Certificado de numero', 'HP', 1, 100),
(45, 8, 'Permisos', 'HP', 1, 100),
(46, 8, 'Control calidad', 'HH', 1, 100),
(47, 9, 'Preparación información', 'HH', 1, 100),
(48, 9, 'Relevamiento', 'HP', 1, 100),
(49, 9, 'Diseño FTTX', 'HP', 1, 100),
(50, 9, 'Control Calidad', 'HH', 1, 100),
(51, 10, 'Dibujo cartografico', 'HP', 1, 100),
(52, 10, 'Dibujo proyecto horizontal', 'HP', 1, 100),
(53, 10, 'Dibujo proyecto vertical', 'HP', 1, 100),
(54, 11, 'Relevamiento cartografico', 'HP', 1, 100),
(55, 11, 'Relevamiento ruta F.O.', 'MTS', 1, 100),
(56, 11, 'Relevamiento proyecto horizontal ', 'HP', 1, 100),
(57, 11, 'Relevamiento proyecto vertical', 'HP', 1, 100),
(58, 11, 'Survey de proyectos', 'UNIDAD', 1, 100),
(59, 12, 'Factibilidad visita', 'UNIDAD', 1, 100),
(60, 12, 'Factibilidad ingeniería de detalle', 'MTS', 1, 100),
(61, 13, 'Dibujo cartografico', 'HP', 1, 100),
(62, 13, 'Dibujo proyecto horizontal', 'HP', 1, 100),
(63, 13, 'Dibujo proyecto vertical', 'HP', 1, 100),
(64, 14, 'Relevamiento cartografico', 'HP', 1, 100),
(65, 14, 'Relevamiento ruta F.O.', 'MTS', 1, 100),
(66, 14, 'Relevamiento proyecto horizontal ', 'HP', 1, 100),
(67, 14, 'Relevamiento proyecto vertical', 'HP', 1, 100),
(68, 14, 'Survey de proyectos', 'UNIDAD', 1, 100),
(69, 15, 'Factibilidad visita', 'UNIDAD', 1, 100),
(70, 15, 'Factibilidad ingeniería de detalle', 'MTS', 1, 100),
(71, 16, 'Dibujo cartografico', 'HP', 1, 100),
(72, 16, 'Dibujo proyecto horizontal', 'HP', 1, 100),
(73, 16, 'Dibujo proyecto vertical', 'HP', 1, 100),
(74, 17, 'Relevamiento cartografico', 'HP', 1, 100),
(75, 17, 'Relevamiento ruta F.O.', 'METROS', 1, 100),
(76, 17, 'Relevamiento proyecto horizontal ', 'HP', 1, 100),
(77, 17, 'Relevamiento proyecto vertical', 'HP', 1, 100),
(78, 17, 'Survey de proyectos', 'UNIDAD', 1, 100),
(79, 18, 'Factibilidad visita', 'UNIDAD', 1, 100),
(80, 18, 'Factibilidad ingeniería de detalle', 'MTS', 1, 100);
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `cpp_actividades`
--
ALTER TABLE `cpp_actividades`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `cpp_actividades`
--
ALTER TABLE `cpp_actividades`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=81;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><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config = array(
'formCPP' => array(
array(
'field' => 'ejecutor',
'label' => 'Ejecutor',
'rules' => 'trim|required'
),
array(
'field' => 'proyecto_empresa',
'label' => 'Proyecto empresa',
'rules' => 'trim|required'
),
array(
'field' => 'actividad',
'label' => 'Actividad',
'rules' => 'trim|required'
),
array(
'field' => 'cantidad',
'label' => 'Cantidad',
'rules' => 'trim|required'
),
array(
'field' => 'fecha_inicio',
'label' => 'Fecha inicio',
'rules' => 'trim|required'
),
array(
'field' => 'hora_inicio',
'label' => 'Hora inicio',
'rules' => 'trim|required'
),
array(
'field' => 'fecha_finalizacion',
'label' => 'Fecha finalización',
'rules' => 'trim|required'
),
array(
'field' => 'hora_finalizacion',
'label' => 'Hora término',
'rules' => 'trim|required'
),
array(
'field' => 'proyecto_desc',
'label' => 'Proyecto descripción',
'rules' => 'trim'
),
array(
'field' => 'comentarios',
'label' => 'Comentarios',
'rules' => 'trim'
)
),
'formMantUs' => array(
array(
'field' => 'usuario',
'label' => 'Usuario',
'rules' => 'trim|required'
),
array(
'field' => 'perfil',
'label' => 'Perfil',
'rules' => 'trim|required'
)
),
'formActividad' => array(
array(
'field' => 'proyecto_empresa',
'label' => 'Proyecto empresa',
'rules' => 'trim|required'
),
array(
'field' => 'actividad',
'label' => 'actividad',
'rules' => 'trim|required'
),
array(
'field' => 'unidad',
'label' => 'unidad',
'rules' => 'trim|required'
),
array(
'field' => 'valor',
'label' => 'valor',
'rules' => 'trim|required'
),
array(
'field' => 'porcentaje',
'label' => 'porcentaje',
'rules' => 'required|greater_than[0]|less_than[101]'
)
),
'resetPass' => array(
array(
'field' => 'correo',
'label' => 'correo',
'rules' => 'trim|required|valid_email'
)
)
);
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class CPP extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model("back_end/Iniciomodel");
$this->load->model("back_end/CPPmodel");
$this->load->helper(array('fechas','str'));
$this->load->library('user_agent');
}
public function checkLogin(){
if($this->session->userdata('idUsuarioCPP')==""){
echo json_encode(array('res'=>"sess"));exit;
}
}
public function visitas(){
$data=array("usuario"=>$this->session->userdata('nombresUsuarioCPP')." ".$this->session->userdata('apellidosUsuarioCPP'),
"fecha"=>date("Y-m-d G:i:s"),
"navegador"=>"navegador :".$this->agent->browser()."\nversion :".$this->agent->version()."\nos :".$this->agent-> platform()."\nmovil :".$this->agent->mobile(),
"ip"=>$this->input->ip_address(),
"pagina"=> "CPP"
);
$this->Iniciomodel->insertarVisita($data);
}
/*********CPP******/
public function getCPPInicio(){
$this->visitas();
$fecha_hoy=date('Y-m-d');
$datos = array(
'fecha_hoy' => $fecha_hoy
);
$this->load->view('back_end/cpp/inicio',$datos);
}
public function getCPPView(){
$fecha_hoy=date('Y-m-d');
$fecha_anio_atras=date('Y-m-d', strtotime('-60 day', strtotime(date("Y-m-d"))));
$proyecto_empresa=$this->CPPmodel->listaProyectoEmpresa();
$datos = array(
'proyecto_empresa'=>$proyecto_empresa,
'fecha_anio_atras' => $fecha_anio_atras,
'fecha_hoy' => $fecha_hoy
);
$this->load->view('back_end/cpp/cpp',$datos);
}
public function getTiposPorPe(){
$pe=$this->security->xss_clean(strip_tags($this->input->get_post("pe")));
echo $this->CPPmodel->getTiposPorPe($pe);exit;
}
public function getActividadesPorTipo(){
$pt=$this->security->xss_clean(strip_tags($this->input->get_post("pt")));
echo $this->CPPmodel->getActividadesPorTipo($pt);exit;
}
public function listaCPP(){
$desde=$this->security->xss_clean(strip_tags($this->input->get_post("desde")));
$hasta=$this->security->xss_clean(strip_tags($this->input->get_post("hasta")));
$accion=$this->security->xss_clean(strip_tags($this->input->get_post("accion")));
echo json_encode($this->CPPmodel->listaCPP($desde,$hasta,$accion));
}
public function getUsuariosSel2CPP(){
$accion=$this->security->xss_clean(strip_tags($this->input->get_post("accion")));
echo $this->CPPmodel->getUsuariosSel2CPP($accion);exit;
}
public function formCPP(){
sleep(1);
if($this->input->is_ajax_request()){
$this->checkLogin();
$id_cpp=$this->security->xss_clean(strip_tags($this->input->post("id_cpp")));
$actividad=$this->security->xss_clean(strip_tags($this->input->post("actividad")));
$ejecutor=$this->security->xss_clean(strip_tags($this->input->post("ejecutor")));
$cantidad=$this->security->xss_clean(strip_tags($this->input->post("cantidad")));
$fecha_inicio=$this->security->xss_clean(strip_tags($this->input->post("fecha_inicio")));
$hora_inicio=$this->security->xss_clean(strip_tags($this->input->post("hora_inicio")));
$fecha_finalizacion=$this->security->xss_clean(strip_tags($this->input->post("fecha_finalizacion")));
$hora_finalizacion=$this->security->xss_clean(strip_tags($this->input->post("hora_finalizacion")));
$proyecto_desc=$this->security->xss_clean(strip_tags($this->input->post("proyecto_desc")));
$estado=$this->security->xss_clean(strip_tags($this->input->post("estado")));
$comentarios=$this->security->xss_clean(strip_tags($this->input->post("comentarios")));
$ultima_actualizacion=date("Y-m-d G:i:s")." | ".$this->session->userdata("nombresUsuarioCPP")." ".$this->session->userdata("apellidosUsuarioCPP");
if ($this->form_validation->run("formCPP") == FALSE){
echo json_encode(array('res'=>"error", 'msg' => strip_tags(validation_errors())));exit;
}else{
if(!preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $hora_inicio)){
echo json_encode(array("res" => "error" , "msg" => "Formato incorrecto para la hora de inicio, intente nuevamente."));exit;
}
if(!preg_match("/^(?:2[0-3]|[01][0-9]):[0-5][0-9]$/", $hora_finalizacion)){
echo json_encode(array("res" => "error" , "msg" => "Formato incorrecto para la hora de término, intente nuevamente."));exit;
}
$data_insert=array("id_actividad"=>$actividad,
"id_usuario"=>$ejecutor,
"id_supervisor"=>0,
"id_digitador"=>$this->session->userdata('idUsuarioCPP'),
"fecha_inicio"=>$fecha_inicio,
"hora_inicio"=>$hora_inicio,
"fecha_termino"=>$fecha_finalizacion,
"hora_termino"=>$hora_finalizacion,
"cantidad"=>$cantidad,
"proyecto_descripcion"=>$proyecto_desc,
"estado"=>"0",
"comentarios"=>$comentarios,
"fecha_aprobacion"=>"0000-00-00",
"hora_aprobacion"=>"00:00:00",
"fecha_digitacion"=>date("Y-m-d"),
"ultima_actualizacion"=>$ultima_actualizacion
);
if($id_cpp==""){
if($this->CPPmodel->formCPP($data_insert)){
echo json_encode(array('res'=>"ok", 'msg' => OK_MSG));exit;
}else{
echo json_encode(array('res'=>"ok", 'msg' => ERROR_MSG));exit;
}
}else{
$data_mod=array("id_actividad"=>$actividad,
"fecha_inicio"=>$fecha_inicio,
"hora_inicio"=>$hora_inicio,
"fecha_termino"=>$fecha_finalizacion,
"hora_termino"=>$hora_finalizacion,
"cantidad"=>$cantidad,
"proyecto_descripcion"=>$proyecto_desc,
"comentarios"=>$comentarios,
"ultima_actualizacion"=>$ultima_actualizacion
);
$estado_db=$this->CPPmodel->getEstadoCpp($id_cpp);
if($estado_db==0 and $estado==1){
$data_mod["id_supervisor"]=$this->session->userdata("idUsuarioCPP");
$data_mod["fecha_aprobacion"]=date("Y-m-d");
$data_mod["hora_aprobacion"]=date("G:i:s");
$data_mod["estado"]=$estado;
}elseif($estado_db==1 and $estado==1){
$data_mod["id_supervisor"]=$this->session->userdata("idUsuarioCPP");
$data_mod["fecha_aprobacion"]=date("Y-m-d");
$data_mod["hora_aprobacion"]=date("G:i:s");
$data_mod["estado"]=$estado;
}else{
//$data_mod["estado"]="0";;
}
if($this->CPPmodel->modFormCPP($id_cpp,$data_mod)){
echo json_encode(array('res'=>"ok", 'msg' => MOD_MSG));exit;
}else{
echo json_encode(array('res'=>"error", 'msg' => ERROR_MSG));exit;
}
}
}
}
}
public function getDataAct(){
if($this->input->is_ajax_request()){
$this->checkLogin();
$hash=$this->security->xss_clean(strip_tags($this->input->post("hash")));
$data=$this->CPPmodel->getDataAct($hash);
if($data){
echo json_encode(array('res'=>"ok", 'datos' => $data));exit;
}else{
echo json_encode(array('res'=>"error", 'msg' => ERROR_MSG));exit;
}
}else{
exit('No direct script access allowed');
}
}
public function eliminaActividad(){
$this->checkLogin();
$hash=$this->security->xss_clean(strip_tags($this->input->post("hash")));
if($this->CPPmodel->eliminaActividad($hash)){
echo json_encode(array("res" => "ok" , "msg" => "Registro eliminado correctamente."));
}else{
echo json_encode(array("res" => "error" , "msg" => "Problemas eliminando el registro, intente nuevamente."));
}
}
public function getUmPorActividad(){
$ac=$this->security->xss_clean(strip_tags($this->input->post("ac")));
$data=$this->CPPmodel->getUmPorActividad($ac);
if($data!=FALSE){
echo json_encode(array("res" => "ok" ,"dato" => $data));
}else{
echo json_encode(array("res" => "error" , "msg" => "Problemas cargando la unidad de medida, intente nuevamente."));
}
}
public function excelTareas(){
$desde=$this->uri->segment(2);
$hasta=$this->uri->segment(3);
$nombre="reporte-tareas-".date("d-m-Y",strtotime($desde))."-".date("d-m-Y",strtotime($hasta)).".xls";
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=$nombre");
?>
<style type="text/css">
.head{font-size:13px;height: 30px; background-color:#1D7189;color:#fff; font-weight:bold;padding:10px;margin:10px;vertical-align:middle;}
td{font-size:12px;text-align:center; vertical-align:middle;}
</style>
<h3>Detalle de tareas</h3>
<table align='center' border="1">
<thead>
<tr style="background-color:#F9F9F9">
<th>Estado</th>
<th>Ejecutor</th>
<th>Fecha inicio</th>
<th>Hora inicio</th>
<th>Fecha fin.</th>
<th>Hora fin.</th>
<th>Duración</th>
<th>Proyecto Empresa</th>
<th>Proyecto Tipo</th>
<th>Actividad</th>
<th>Proyecto Descripción</th>
<th>Unidad</th>
<th>Valor</th>
<th>Cantidad</th>
<th>Supervisor</th>
<th>Fecha Aprob</th>
<th>Hora Aprob</th>
<th>Digitador</th>
<th>Fecha digitación</th>
<th>Observaciones</th>
<th>Última actualización</th>
</tr>
</thead>
<tbody>
<?php
$detalle=$this->CPPmodel->listaCPP($desde,$hasta,"");
if($detalle !=FALSE){
foreach($detalle as $det){
?>
<tr>
<td><?php echo utf8_decode($det["estado_str"]); ?></td>
<td><?php echo utf8_decode($det["ejecutor"]); ?></td>
<td><?php echo utf8_decode($det["fecha_inicio"]); ?></td>
<td><?php echo utf8_decode(substr($det["hora_inicio"], 0, -2)); ?></td>
<td><?php echo utf8_decode($det["fecha_termino"]); ?></td>
<td><?php echo utf8_decode(substr($det["hora_termino"], 0, -2)); ?></td>
<td><?php echo utf8_decode($det["duracion"]); ?></td>
<td><?php echo utf8_decode($det["proyecto_empresa"]); ?></td>
<td><?php echo utf8_decode($det["proyecto_tipo"]); ?></td>
<td><?php echo utf8_decode($det["actividad"]); ?></td>
<td><?php echo utf8_decode($det["proyecto_desc"]); ?></td>
<td><?php echo utf8_decode($det["unidad"]); ?></td>
<td><?php echo utf8_decode($det["valor"]); ?></td>
<td><?php echo utf8_decode($det["cantidad"]); ?></td>
<td><?php echo utf8_decode($det["supervisor"]); ?></td>
<td><?php echo utf8_decode($det["fecha_aprob"]); ?></td>
<td><?php echo utf8_decode($det["hora_aprob"]); ?></td>
<td><?php echo utf8_decode($det["digitador"]); ?></td>
<td><?php echo utf8_decode($det["fecha_dig"]); ?></td>
<td><?php echo utf8_decode($det["comentarios"]); ?></td>
<td><?php echo utf8_decode($det["ultima_actualizacion"]); ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php
}
/********VISTA MENSUAL*********/
public function getVistaMensualView(){
$fecha_hoy=date('Y-m-d');
$desde=date('Y-m');
$hasta=date('Y-m');
$datos = array(
'fecha_hoy' => $fecha_hoy,
'desde' => $desde,
'hasta' => $hasta
);
$this->load->view('back_end/cpp/vista_mensual',$datos);
}
public function listaMes(){
$desde=$this->security->xss_clean(strip_tags($this->input->get_post("desde")));
$accion=$this->security->xss_clean(strip_tags($this->input->get_post("accion")));
if($desde!=""){$desde=$desde."-01";}else{$desde="";}
if($this->session->userdata('id_perfil_CPP')==4){
$usuario=$this->session->userdata('idUsuarioCPP');
}else{
$usuario=$this->security->xss_clean(strip_tags($this->input->get_post("usuario")));
}
echo json_encode($this->CPPmodel->listaMes($desde,$usuario,$accion));
}
public function excelMensual(){
$fecha=$this->uri->segment(2);
$usuario=$this->uri->segment(3);
$accion=$this->uri->segment(4);
if($fecha!=""){$fecha=$fecha."-01";}else{$fecha="";}
if($usuario=="-"){
$usuario="";
$nombre="reporte-tareas-".date("m-Y",strtotime($fecha)).".xls";
$titulo="Detalle de tareas ".date("m-Y",strtotime($fecha));
}else{
$usuario=$usuario;
$nombre_us=strtolower(url_title(convert_accented_characters($this->CPPmodel->getNombrePorId($usuario)),'-',TRUE));
$nombre="reporte-tareas-".$nombre_us."-".date("m-Y",strtotime($fecha)).".xls";
$titulo="Detalle de tareas ".$this->CPPmodel->getNombrePorId($usuario)." ".date("m-Y",strtotime($fecha));
}
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=$nombre");
?>
<style type="text/css">
.head{font-size:13px;height: 30px; background-color:#1D7189;color:#fff; font-weight:bold;padding:10px;margin:10px;vertical-align:middle;}
td{font-size:12px;text-align:center; vertical-align:middle;}
</style>
<h3><?php echo $titulo; ?></h3>
<table align='center' border="1">
<thead>
<tr style="background-color:#F9F9F9">
<th>Ejecutor</th>
<th>Día</th>
<th>Fecha</th>
<th>ID CPP</th>
<th>Proyecto Empresa</th>
<th>Actividad</th>
<th>Unidad</th>
<th>Cantidad</th>
<th>Proyecto ID/Descripción</th>
<th>Comentario</th>
<th>Estado</th>
<th>Fecha Inicio</th>
<th>Hora Inicio</th>
<th>Fecha Término</th>
<th>Hora Término</th>
<th>Fecha Aprobación</th>
<th>Hora Digitación</th>
<th>Fecha Digitación</th>
<th>Última actualización</th>
</tr>
</thead>
<tbody>
<?php
$detalle=$this->CPPmodel->listaMes($fecha,$usuario,$accion);
if($detalle !=FALSE){
foreach($detalle as $det){
?>
<tr>
<td><?php echo utf8_decode($det["ejecutor"]); ?></td>
<td><?php echo utf8_decode($det["dia"]); ?></td>
<td><?php echo utf8_decode($det["fecha_termino"]); ?></td>
<td><?php echo utf8_decode($det["id"]); ?></td>
<td><?php echo utf8_decode($det["proyecto_empresa"]); ?></td>
<td><?php echo utf8_decode($det["actividad"]); ?></td>
<td><?php echo utf8_decode($det["unidad"]); ?></td>
<td><?php echo utf8_decode($det["cantidad"]); ?></td>
<td><?php echo utf8_decode($det["proyecto_desc"]); ?></td>
<td><?php echo utf8_decode($det["comentarios"]); ?></td>
<td><?php echo utf8_decode($det["estado_str"]); ?></td>
<td><?php echo utf8_decode($det["fecha_inicio"]); ?></td>
<td><?php echo utf8_decode(substr($det["hora_inicio"], 0, -2)); ?></td>
<td><?php echo utf8_decode($det["fecha_termino"]); ?></td>
<td><?php echo utf8_decode(substr($det["hora_termino"], 0, -2)); ?></td>
<td><?php echo utf8_decode($det["fecha_aprob"]); ?></td>
<td><?php echo utf8_decode(substr($det["hora_aprob"], 0, -2)); ?></td>
<td><?php echo utf8_decode($det["fecha_dig"]); ?></td>
<td><?php echo utf8_decode($det["ultima_actualizacion"]); ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php
}
/********VISTA GRAFICOS*********/
public function getVistaGraficos(){
$this->visitas();
$datos = array();
$this->load->view('back_end/cpp/graficos',$datos);
}
/********MANTENEDOR ACTIVIDADES*********/
public function getMantActView(){
$fecha_hoy=date('Y-m-d');
$proyecto_empresa=$this->CPPmodel->listaProyectoEmpresa();
$datos = array(
'proyecto_empresa'=>$proyecto_empresa,
'fecha_hoy' => $fecha_hoy
);
$this->load->view('back_end/cpp/mantenedor_actividades',$datos);
}
public function formActividad(){
sleep(1);
if($this->input->is_ajax_request()){
$id_actividad=$this->security->xss_clean(strip_tags($this->input->post("id_actividad")));
$id_proyecto_tipo=$this->security->xss_clean(strip_tags($this->input->post("proyecto_tipo")));
$actividad=$this->security->xss_clean(strip_tags($this->input->post("actividad")));
$valor=$this->security->xss_clean(strip_tags($this->input->post("valor")));
$unidad=$this->security->xss_clean(strip_tags($this->input->post("unidad")));
$porcentaje=$this->security->xss_clean(strip_tags($this->input->post("porcentaje")));
if ($this->form_validation->run("formActividad") == FALSE){
echo json_encode(array('res'=>"error", 'msg' => strip_tags(validation_errors())));exit;
}else{
$data_insert=array(
"id_proyecto_tipo"=>$id_proyecto_tipo,
"actividad"=>$actividad,
"unidad"=>$unidad,
"valor"=>$valor,
"porcentaje"=>$porcentaje
);
if($id_actividad==""){
if($this->CPPmodel->checkActividad($actividad)){
echo json_encode(array('res'=>"error", 'msg' => "Esta actividad ya se encuentra asignada a la aplicación."));exit;
}
if($this->CPPmodel->formActividad($data_insert)){
echo json_encode(array('res'=>"ok", 'msg' => OK_MSG));exit;
}else{
echo json_encode(array('res'=>"ok", 'msg' => ERROR_MSG));exit;
}
}else{
$data_mod=array(
"id_proyecto_tipo"=>$id_proyecto_tipo,
"actividad"=>$actividad,
"unidad"=>$unidad,
"valor"=>$valor,
"porcentaje"=>$porcentaje
);
if($this->CPPmodel->modFormActividad($id_actividad,$data_mod)){
echo json_encode(array('res'=>"ok", 'msg' => MOD_MSG));exit;
}else{
echo json_encode(array('res'=>"error", 'msg' => ERROR_MSG));exit;
}
}
}
}
}
public function getDataActividad(){
if($this->input->is_ajax_request()){
sleep(1);
$hash=$this->security->xss_clean(strip_tags($this->input->post("hash")));
$data=$this->CPPmodel->getDataActividad($hash);
if($data){
echo json_encode(array('res'=>"ok", 'datos' => $data));exit;
}else{
echo json_encode(array('res'=>"error", 'msg' => ERROR_MSG));exit;
}
}else{
exit('No direct script access allowed');
}
}
public function listaActividad(){
$empresa=$this->security->xss_clean(strip_tags($this->input->get_post("empresa")));
echo json_encode($this->CPPmodel->listaActividad($empresa));
}
public function deleteActividad(){
$hash=$this->security->xss_clean(strip_tags($this->input->post("hash")));
if($this->CPPmodel->deleteActividad($hash)){
echo json_encode(array("res" => "ok" , "msg" => "Registro eliminado correctamente."));
}else{
echo json_encode(array("res" => "error" , "msg" => "Problemas eliminando el registro, intente nuevamente."));
}
}
public function excelInforme(){
$empresa=$this->uri->segment(2);
if($empresa=="0"){
$empresa="";
}
$dato=$this->CPPmodel->listaActividad($empresa);
$nombre="Lista de Actividades-".".xls";
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=$nombre");
?>
<style type="text/css">
.head{height: 30px; background-color:#0CC243;color:#fff; font-weight:bold;padding:10px;margin:10px;vertical-align:middle;}
td{text-align:center; vertical-align:middle;}
</style>
<table align='center' border="1">
<thead>
<tr style="background-color:#F9F9F9">
<th class="head">Proyecto Empresa</th>
<th class="head">Proyecto Tipo</th>
<th class="head">Actividad</th>
<th class="head">Unidad</th>
<th class="head">Valor</th>
<th class="head">Porcentaje</th>
</tr>
</thead>
<tbody>
<?php
if($dato !=FALSE){
foreach($dato as $sop){
?>
<tr>
<td><?php echo utf8_decode($sop["proyecto"]); ?></td>
<td><?php echo utf8_decode($sop["proyecto_tipo"]); ?></td>
<td><?php echo utf8_decode($sop["actividad"]); ?></td>
<td><?php echo utf8_decode($sop["unidad"]); ?></td>
<td><?php echo utf8_decode($sop["valor"]); ?></td>
<td><?php echo utf8_decode($sop["porcentaje"]); ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php
}
/********MANTENEDOR USUARIOS *********/
public function getMantUsView(){
$fecha_hoy=date('Y-m-d');
$perfiles=$this->CPPmodel->getPerfiles();
$idUsuarioCPP=$this->session->userdata('idUsuarioCPP');
$id_perfil_CPP=$this->session->userdata('id_perfil_CPP');
$supervisores=$this->CPPmodel->getSupervisores();
$datos = array(
'fecha_hoy' => $fecha_hoy,
'idUsuarioCPP' => $idUsuarioCPP,
'id_perfil_CPP' => $id_perfil_CPP,
'perfiles' => $perfiles,
'supervisores' => $supervisores
);
$this->load->view('back_end/cpp/mantenedor_usuarios',$datos);
}
public function getUsuariosSel2(){
echo $this->CPPmodel->getUsuariosSel2();exit;
}
public function listaMantUsuarios(){
echo json_encode($this->CPPmodel->listaMantUsuarios());exit;
}
public function formMantUs(){
if($this->input->is_ajax_request()){
$this->checkLogin();
$id_mant_us=$this->security->xss_clean(strip_tags($this->input->post("id_mant_us")));
$usuario=$this->security->xss_clean(strip_tags($this->input->post("usuario")));
$perfil=$this->security->xss_clean(strip_tags($this->input->post("perfil")));
$supervisor=$this->security->xss_clean(strip_tags($this->input->post("supervisor")));
$supervisor2=$this->security->xss_clean(strip_tags($this->input->post("supervisor2")));
$ultima_actualizacion=date("Y-m-d G:i:s")." | ".$this->session->userdata("nombresUsuarioCPP")." ".$this->session->userdata("apellidosUsuarioCPP");
if($supervisor==$supervisor2){
echo json_encode(array('res'=>"error", 'msg' => "Deben ser dos supervisores distintos."));exit;
}
if ($this->form_validation->run("formMantUs") == FALSE){
echo json_encode(array('res'=>"error", 'msg' => strip_tags(validation_errors())));exit;
}else{
if($perfil==4){
if($supervisor==""){
echo json_encode(array('res'=>"error", 'msg' => "Debe asignarle un supervisor a este usuario."));exit;
}
}else{
$supervisor=0;
}
$data_insert=array("id_usuario"=>$usuario,
"id_perfil"=>$perfil,
"id_supervisor"=>$supervisor,
"id_supervisor2"=>$supervisor2,
"ultima_actualizacion"=>$ultima_actualizacion
);
if($id_mant_us==""){
if($this->CPPmodel->checkUsuario($usuario)){
echo json_encode(array('res'=>"error", 'msg' => "Este usuario ya se encuentra asignado a la aplicación."));exit;
}
if($this->CPPmodel->formMantUs($data_insert)){
echo json_encode(array('res'=>"ok", 'msg' => OK_MSG));exit;
}else{
echo json_encode(array('res'=>"ok", 'msg' => ERROR_MSG));exit;
}
}else{
if($perfil==4){
if($supervisor==""){
echo json_encode(array('res'=>"error", 'msg' => "Debe asignarle un supervisor a este usuario."));exit;
}
}else{
$supervisor=0;
}
if($this->CPPmodel->checkUsuarioMod($id_mant_us,$usuario)){
echo json_encode(array('res'=>"error", 'msg' => "Este usuario ya se encuentra asignado a la aplicación."));exit;
}
$data_mod=array("id_usuario"=>$usuario,
"id_perfil"=>$perfil,
"id_supervisor"=>$supervisor,
"id_supervisor2"=>$supervisor2,
"ultima_actualizacion"=>$ultima_actualizacion
);
if($this->CPPmodel->modFormMantUs($id_mant_us,$data_mod)){
echo json_encode(array('res'=>"ok", 'msg' => MOD_MSG));exit;
}else{
echo json_encode(array('res'=>"error", 'msg' => ERROR_MSG));exit;
}
}
}
}
}
public function getDataMantUs(){
if($this->input->is_ajax_request()){
$this->checkLogin();
$hash=$this->security->xss_clean(strip_tags($this->input->post("hash")));
$data=$this->CPPmodel->getDataMantUs($hash);
if($data){
echo json_encode(array('res'=>"ok", 'datos' => $data));exit;
}else{
echo json_encode(array('res'=>"error", 'msg' => ERROR_MSG));exit;
}
}else{
exit('No direct script access allowed');
}
}
public function eliminaUsuario(){
$this->checkLogin();
$hash=$this->security->xss_clean(strip_tags($this->input->post("hash")));
if($this->CPPmodel->eliminaUsuario($hash)){
echo json_encode(array("res" => "ok" , "msg" => "Registro eliminado correctamente."));
}else{
echo json_encode(array("res" => "error" , "msg" => "Problemas eliminando el registro, intente nuevamente."));
}
}
public function excelusuarios(){
$nombre="reporte-usuarios.xls";
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=$nombre");
?>
<style type="text/css">
.head{font-size:13px;height: 30px; background-color:#1D7189;color:#fff; font-weight:bold;padding:10px;margin:10px;vertical-align:middle;}
td{font-size:12px;vertical-align:middle;}
</style>
<h3>Usuarios CPP</h3>
<table align='center' border="1">
<thead>
<tr style="background-color:#F9F9F9">
<th>Usuario</th>
<th>RUT</th>
<th>Cargo</th>
<th>Empresa</th>
<th>Perfil</th>
<th>Supervisor</th>
<th>Supervisor2</th>
<th>Última actualización</th>
</tr>
</thead>
<tbody>
<?php
$usuarios=$this->CPPmodel->listaMantUsuarios();
if($usuarios !=FALSE){
foreach($usuarios as $us){
?>
<tr>
<td><?php echo utf8_decode($us["usuario"]); ?></td>
<td><?php echo utf8_decode($us["rut"]); ?></td>
<td><?php echo utf8_decode($us["cargo"]); ?></td>
<td><?php echo utf8_decode($us["empresa"]); ?></td>
<td><?php echo utf8_decode($us["perfil"]); ?></td>
<td><?php echo utf8_decode($us["supervisor"]); ?></td>
<td><?php echo utf8_decode($us["supervisor2"]); ?></td>
<td><?php echo utf8_decode($us["ultima_actualizacion"]); ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php
}
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="">
<meta name="author" content="">
<title><?php echo $titulo?></title>
<script src="<?php echo base_url();?>assets/back_end/js/jquery.min.js"></script>
<script src="<?php echo base_url();?>assets/back_end/js/bootstrap.min.js"></script>
<link href="<?php echo base_url();?>assets/back_end/css/normalize.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/estilos_km.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/fontawesome-all.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/form_style.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css" media="screen">
body{
background-image: url("./assets/imagenes/fondolog.jpg");
background-size: cover;
overflow-y:hidden;
}
.modal_recuperar{
width:60%!important;
}
.validacion{
font-size:12px!important;
}
.alert {
padding: 6px;
margin-bottom: 0px;
border: 1px solid transparent;
border-radius: 4px;
text-align:left;
}
.top-content{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.validacion-correo{
margin-top:10px;
margin-bottom: 10px;
}
.recuperarPass{
display: block;
text-align: center;
color: #1E748D;
}
.validacion_rec{
margin-top: 5px;
margin-bottom: 10px;
}
</style>
<script type="text/javascript">
$(function(){
function detectBrowser(){
if (/MSIE 10/i.test(navigator.userAgent)) {
// This is internet explorer 10
alert('Favor usar navegador Google Chrome, Firefox o Safari, internet explorer puede provocar comportamientos inesperados en la aplicación.');
return false;
}
if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
// This is internet explorer 9 or 11
alert('Favor usar navegador Google Chrome, Firefox o Safari, internet explorer puede provocar comportamientos inesperados en la aplicación.');
return false;
}
if (/Edge\/\d./i.test(navigator.userAgent)){
alert('Favor usar navegador Google Chrome, Firefox o Safari, EDGE puede provocar comportamientos inesperados en la aplicación.');
return false;
}
return true;
}
$(document).on('submit', '#formlog', function(event) {
if(detectBrowser()){
var formElement = document.querySelector("#formlog");
var formData = new FormData(formElement);
data: formData;
$.ajax({
url: $('#formlog').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
beforeSend: function(){
$('.btn_submit_b').prop("disabled",true);
},
success:function(data){
if(data.res == "ok"){
$(".validacion").hide();
$(".validacion").html('<div class="alert alert-primary alert-dismissible fade show" role="alert"><strong>'+data.msg+'</strong></div>');
$(".btn_submit").html('<button type="submit" class="btn_submit_b btn btn-primary"> Ingresando <i class="fa fa-cog fa-spin"></i></button>');
$(".validacion").fadeIn(1);
$("#btn_submit").html('<i class="fa fa-cog fa-spin fa-3x"></i>');
$('.btn_submit_b').prop("disabled",true);
setTimeout( function () {
window.location.replace("<?php echo base_url(); ?>inicio");
}, 1500);
}else if(data.res == "error"){
$('.btn_submit_b').prop("disabled",false);
$(".validacion").hide();
$(".validacion").html('<div class="alert alert-danger alert-dismissible fade show" role="alert">'+data.msg+'</div>');
$(".validacion").fadeIn(1000);
}
},
error:function(data){
$('.btn_submit_b').prop("disabled",false);
$(".validacion").hide();
$(".validacion").html('<div class="alert alert-danger alert-dismissible fade show" role="alert">Problemas accediendo a la base de datos, intente nuevamente.</div>');
$(".validacion").fadeIn(1000);
}
});
return false;
}else{
return false;
}
});
/*$(document).on('submit', '#recuperarpass', function(event) {
if(detectBrowser()){
var formElement = document.querySelector("#recuperarpass");
var formData = new FormData(formElement);
data: formData;
$.ajax({
url: $('#recuperarpass').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
beforeSend: function(){
$('.btn_ingresalogin_cpp').prop("disabled",true);
},
success:function(data){
if(data.res == "ok"){
$(".validacion-correo").hide();
$(".validacion-correo").html('<div class="alert alert-primary alert-dismissible fade show" role="alert"><strong>'+data.msg+'</strong></div>');
$(".btn_submit2").html('<button type="submit" class="btn_ingresalogin_cpp btn btn-primary"> Enviando <i class="fa fa-cog fa-spin"></i></button>');
$(".validacion-correo").fadeIn(1);
$("#btn_submit2").html('<i class="fa fa-cog fa-spin fa-3x"></i>');
$('.btn_ingresalogin_cpp').prop("disabled",true);
setTimeout( function () {
window.location.replace("<?php echo base_url(); ?>inicio");
}, 1500);
}else if(data.res == "error"){
$('.btn_ingresalogin_cpp').prop("disabled",false);
$(".validacion-correo").hide();
$(".validacion-correo").html('<div class="alert alert-danger alert-dismissible fade show" role="alert">'+data.msg+'</div>');
$(".validacion-correo").fadeIn(1000);
}
},
error:function(data){
$('.btn_ingresalogin_cpp').prop("disabled",false);
$(".validacion-correo").hide();
$(".validacion-correo").html('<div class="alert alert-danger alert-dismissible fade show" role="alert">Problemas accediendo a la base de datos, intente nuevamente.</div>');
$(".validacion-correo").fadeIn(1000);
}
});
return false;
}else{
return false;
}
});*/
$('#resetPass').submit(function(){
var formElement = document.querySelector("#resetPass");
var formData = new FormData(formElement);
$.ajax({
url: $('.resetPass').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
success: function (data) {
if(data.res == 1){
$(".validacion-correo").hide();
$(".validacion-correo").html("<div class='row'><div class='card-panel white-text teal lighten-2'><center>Nueva contraseña enviada a su correo.</center></div></div>");
$(".validacion-correo").fadeIn(1000);
//setTimeout(function(){window.location='<?php echo base_url()?>inicio'} , 4000);
}else if(data.res == 2){
$(".validacion-correo").hide();
$(".validacion-correo").html("<div class='row'><div class='card-panel white-text red darken-3'><center><blockquote>El rut ingresado no esta registrado en la base de datos.</blockquote></center></div></div>");
$(".validacion-correo").fadeIn(1000);
}else if(data.res == 3){
$(".validacion-correo").hide();
$(".validacion-correo").html("<div class='row'><div class='card-panel white-text red darken-3'><center><blockquote>Error, Intente nuevamente.</blockquote></center></div></div>");
$(".validacion-correo").fadeIn(1000);
}
}
});
return false;
});
$(".usuario").keyup(function(event) {
$(".rut").attr("value",$(this).val());
});
$(document).on('click', '.recuperarPass', function(event) {
event.preventDefault();
$("#rut_rec").val($("#usuario").val());
});
$(document).on('submit', '#formRecuperarPass', function(event) {
var formElement = document.querySelector("#formRecuperarPass");
var formData = new FormData(formElement);
data: formData;
$.ajax({
url: $('#formRecuperarPass').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType : false,
dataType : "json",
beforeSend: function(){
$('.btn_submit_rec').prop("disabled",true);
},
success:function(data){
if(data.res == "ok"){
$(".validacion_rec").hide().html('<div class="alert alert-info" style="color:#fff;font-size:12px;background-color: #1E748D;"><strong><span class="glyphicon glyphicon-ok"></span> '+data.msg+'</strong></div>').show();
$("#btn_submit_rec").html('<i class="fa fa-cog fa-spin fa-3x"></i>');
setTimeout( function () {
$('.btn_submit_rec').prop("disabled",false);
/* $('#modal_recuperar').modal("toggle");*/
$("#btn_submit_rec").html('Registrarse');
$('#formRecuperarPass')[0].reset();
/* $(".validacion_rec").html("");*/
}, 2000);
}else if(data.res == "error"){
$('.btn_submit_rec').prop("disabled",false);
$(".validacion_rec").hide();
$(".validacion_rec").html('<div class="alert alert-info" style="color:#fff;background-color: #CD2D00;font-size: 14px;"> '+data.msg+'</div>');
$(".validacion_rec").fadeIn(1000);
}
},
error:function(data){
$('.btn_submit_rec').prop("disabled",false);
$(".validacion_rec").hide();
$(".validacion_rec").html('<div class="alert alert-info" style="color:#CD2D00;background-color: #EEEEEE;font-size: 14px;"><span class="glyphicon glyphicon-exclamation-sign"></span> Problemas accediendo a la base de datos, intente nuevamente.</div>');
$(".validacion_rec").fadeIn(1000);
}
});
return false;
});
});
</script>
</head>
<body>
<!-- LOGIN -->
<div class="top-content col-xs-12 col-sm-12">
<div class="inner-bg">
<div class="container">
<div class="form-row">
<div class="col-lg-6 offset-lg-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Inicio de Sesión CPP</h3>
<div class="validacion">
<div class="alert alert-primary alert-dismissible fade show" role="alert">
Ingrese su rut y contraseña.
</div>
</div>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div class="form-bottom">
<?php echo form_open(base_url()."loginProcess",array("id"=>"formlog","class" =>"formlog"));?>
<div class="form-group">
<label class="sr-only" for="form-username">Rut</label>
<input type="text" name="usuario" id="usuario" placeholder="Rut..." class="form-username form-control" >
</div>
<div class="form-group">
<label class="sr-only" for="form-password">Contraseña</label>
<input type="<PASSWORD>" name="pass" id="pass" placeholder="<PASSWORD>&<PASSWORD>;a..." class="form-password form-control">
</div>
<div class="btn_submit">
<button type="submit" class="btn_submit_b btn btn-primary" style="background-color: #1E748D">Ingresar</button>
</div>
<center>
<div class="input-field col s10 offset-s1">
<a href="#modal1" id="recupera_pass" style="font-size:12px;" data-toggle="modal" data-target="#modal1">
¿ Olvidó su contraseña ?
</a>
</div>
</center>
<?php echo form_close();?>
<center><a href="#modal_recuperar" data-toggle="modal" class="recuperarPass">¿Olvido su contraseña?</a></center>
</div>
</div>
</div>
</div>
<!-- RECUPERAR MODAL -->
<div id="modal_recuperar" class="modal fade" tabindex="-1" aria-labelledby="myModalLabel" role="dialog" aria-hidden="true">
<div class="modal-dialog modal_recuperar">
<div class="modal-content">
<div class="modal-body" style="padding: 0px;">
<button type="button" title="Cerrar Ventana" class="close" data-dismiss="modal" aria-hidden="true" style="position: absolute;right: 20px;top: 15px;">X</button>
<div class="col-lg-12">
<h3 style="margin: 20px;">Resetear contraseña</h3>
</div>
<div class="form-bottom">
<?php echo form_open_multipart("formRecuperarPass",array("id"=>"formRecuperarPass","class"=>"formRecuperarPass"))?>
<div class="form-group">
<label class="sr-only" for="form-username">Rut</label>
<input type="text" name="rut_rec" id="rut_rec" placeholder="Rut" class="form-control" >
</div>
<div class="validacion_rec"></div>
<div class="btn_submit">
<button type="submit" class="btn_submit_rec btn btn-primary" style="background-color: #1E748D">Resetear</button>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
</div>
</div>
</html>
</body><file_sep><style type="text/css">
.ver_obs_desp,.ver_obs{
cursor: pointer;
display: inline;
margin-left: 5px;
font-size: 13px;
color: #2780E3;
}
.btndesp span:hover{
color:#26A69A!important;
}
</style>
<script type="text/javascript">
$(function(){
var id_perfil_CPP="<?php echo $this->session->userdata("id_perfil_CPP"); ?>";
var idUsuarioCPP="<?php echo $this->session->userdata("idUsuarioCPP"); ?>";
var desde="<?php echo $desde; ?>";
var hasta="<?php echo $hasta; ?>";
$("#desdef").val(desde);
/* $("#hastaf").val(hasta); */
iniciaEjecutor();
function iniciaEjecutor(){
if(id_perfil_CPP==1 || id_perfil_CPP==2){//ADMIN,GERENTES
accion = 1;//TODO
}
if(id_perfil_CPP==3){//SUPERVISOR
accion = 2;//SU PERSONAL
}
if(id_perfil_CPP==4){//EJECUTOR
accion = 3;//SUS REGISTROS
}
$.getJSON('getUsuariosSel2CPP', {accion:accion},
function(response) {
$("#select_usuario_vm").select2({
allowClear: true,
placeholder: 'Seleccione usuario | Todos',
data: response
});
});
setTimeout( function () {
/*$('#select_usuario_vm').val(idUsuarioCPP).trigger('change'); */
}, 2000 );
}
$.extend(true,$.fn.dataTable.defaults,{
info:false,
paging:true,
ordering:true,
searching:true,
lengthChange: false,
bSort: true,
bFilter: true,
bProcessing: true,
pagingType: "simple" ,
bAutoWidth: true,
sAjaxDataProp: "result",
bDeferRender: true,
language : {
url: "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json",
},
});
/****GRILLA****/
var table_vm = $('#tabla_vm').DataTable({
"iDisplayLength":50,
"aaSorting" : [[2,'desc']],
"scrollY": 420,
"scrollX": true,
"select": true,
"ajax": {
"url":"<?php echo base_url();?>listaMes",
"dataSrc": function (json) {
$(".btn_filtra_vm").html('<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar');
$(".btn_filtra_vm").prop("disabled" , false);
desde = $("#desdef").val();
/*hasta = $("#hastaf").val();*/
return json;
},
data: function(param){
param.desde = $("#desdef").val();
/* param.hasta = $("#hastaf").val();*/
if(id_perfil_CPP==1 || id_perfil_CPP==2){//ADMIN,GERENTES
accion = 1;//TODO
}
if(id_perfil_CPP==3){//SUPERVISOR
accion = 2;//SU PERSONAL
}
if(id_perfil_CPP==4){//EJECUTOR
accion = 3;//SUS REGISTROS
}
param.accion = accion;
param.usuario = $("#select_usuario_vm").val();
}
},
"columns": [
{ "data": "ejecutor" ,"class":"margen-td"},
{ "data": "dia" ,"class":"margen-td"},
{ "data": "fecha_termino" ,"class":"margen-td"},
{ "data": "id" ,"class":"margen-td"},
{ "data": "proyecto_empresa" ,"class":"margen-td"},
{ "data": "actividad" ,"class":"margen-td"},
{ "data": "unidad" ,"class":"margen-td"},
{ "data": "cantidad" ,"class":"margen-td"},
{ "data": "proyecto_desc" ,"class":"margen-td"},
{
"class":"centered margen-td","data": function(row,type,val,meta){
obs=row.comentarios.toLowerCase().capitalize();
var str = obs;
if(str.length > 40) {
str = str.substring(0,40)+"...";
return "<span class='btndesp2'>"+str+"</span><span title='Ver texto completo' class='ver_obs_desp' data-tit="+obs.replace(/ /g,"_")+" data-title="+obs.replace(/ /g,"_")+">Ver más</span>";
}else{
return "<span class='btndesp2' data-title="+obs.replace(/ /g,"_")+">"+obs+"</span>";
}
}
},
{ "data": "estado_str" ,"class":"margen-td"},
{ "data": "fecha_inicio" ,"class":"margen-td"},
{
"class":"","data": function(row,type,val,meta){
return row.hora_inicio.substring(0, 5);
}
},
{ "data": "fecha_termino" ,"class":"margen-td"},
{
"class":"","data": function(row,type,val,meta){
return row.hora_termino.substring(0, 5);
}
},
{ "data": "fecha_aprob" ,"class":"margen-td"},
{
"class":"","data": function(row,type,val,meta){
return row.hora_aprob.substring(0, 5);
}
},
{ "data": "fecha_dig" ,"class":"margen-td"},
{ "data": "ultima_actualizacion" ,"class":"margen-td"}
]
});
setTimeout( function () {
var table_vm = $.fn.dataTable.fnTables(true);
if ( table_vm.length > 0 ) {
$(table_vm).dataTable().fnAdjustColumnSizing();
}}, 1000 );
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
$(document).on('keyup paste', '#buscador_vm', function() {
table_vm.search($(this).val().trim()).draw();
});
$(document).off('click', '.btn_filtra_vm').on('click', '.btn_filtra_vm',function(event) {
event.preventDefault();
var us = $("#select_usuario_vm").val();
/* if(us==""){
$.notify("Debe seleccionar un usuario", {
className:'error',
globalPosition: 'top right'
});
return false;
}
*/
$(this).prop("disabled" , true);
$(".btn_filtra_vm").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Filtrando');
table_vm.ajax.reload();
});
$(document).on('click', '.ver_obs_desp', function(event) {
event.preventDefault();
val=$(this).attr("data-tit");
elem=$(this);
if(elem.text()=="Ver más"){
elem.html("Ocultar");
elem.attr("title","Acortar texto");
elem.prev(".btndesp2").text(val.replace(/_/g, ' '));
var table = $.fn.dataTable.fnTables(true);
if ( table.length > 0 ) {
$(table).dataTable().fnAdjustColumnSizing();
}
}else if(elem.text()=="Ocultar"){
val = val.substring(0,40)+"...";
elem.prev(".btndesp2").text(val.replace(/_/g, ' '));
elem.html("Ver más");
elem.attr("title","Ver texto completo");
var table = $.fn.dataTable.fnTables(true);
if ( table.length > 0 ) {
$(table).dataTable().fnAdjustColumnSizing();
}
}
});
$(document).off('click', '.btn_excel_vm').on('click', '.btn_excel_vm',function(event) {
event.preventDefault();
var fecha = $("#desdef").val();
var hasta = $("#hastaf").val();
var us = $("#select_usuario_vm").val();
if(us==""){
us="-";
}else{
us=us;
}
if(fecha==""){
$.notify("Debe seleccionar una fecha de inicio.", {
className:'error',
globalPosition: 'top right'
});
return false;
}
if(id_perfil_CPP==1 || id_perfil_CPP==2){//ADMIN,GERENTES
accion = 1;//TODO
}
if(id_perfil_CPP==3){//SUPERVISOR
accion = 2;//SU PERSONAL
}
if(id_perfil_CPP==4){//EJECUTOR
accion = 3;//SUS REGISTROS
}
window.location="excelMensual/"+fecha+"/"+us+"/"+accion;
});
$(".fecha_mes").datetimepicker({
format: "YYYY-MM",
locale:"es",
maxDate:"now"
});
})
</script>
<!--FILTROS-->
<div class="form-row">
<div class="col-lg-3">
<div class="form-group">
<select id="select_usuario_vm" name="ejecutor" class="custom-select custom-select-sm" style="width:100%!important;">
<option value="">Seleccione usuario | Todos</option>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id=""><i class="fa fa-calendar-alt"></i></span>
</div>
<input type="text" autocomplete="off" placeholder="Desde" class="fecha_mes form-control form-control-sm" name="desdef" id="desdef">
<!-- <input type="text" autocomplete="off" placeholder="Hasta" class="fecha_mes form-control form-control-sm" name="hastaf" id="hastaf"> -->
</div>
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<input type="text" placeholder="Ingrese su busqueda..." id="buscador_vm" class="buscador_vm form-control form-control-sm">
</div>
</div>
<div class="col-6 col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-outline-primary btn-primary btn_filtra_vm">
<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar
</button>
</div>
</div>
<div class="col-6 col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-outline-primary btn-primary btn_excel_vm">
<i class="fa fa-save"></i> Excel
</button>
</div>
</div>
</div>
<!-- GRILLA -->
<div class="row">
<div class="col">
<table id="tabla_vm" class="table table-hover table-bordered dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th>Ejecutor</th>
<th>Día</th>
<th>Fecha</th>
<th>ID CPP</th>
<th>Proyecto Empresa</th>
<th>Actividad</th>
<th>Unidad</th>
<th>Cantidad</th>
<th>Proyecto ID/Descripción</th>
<th>Comentario</th>
<th>Estado</th>
<th>Fecha Inicio</th>
<th>Hr. Inicio</th>
<th>Fecha fin.</th>
<th>Hr. fin.</th>
<th>Fecha Aprobación</th>
<th>Hr. Digitación</th>
<th>Fecha Digitación</th>
<th>Última actualización</th>
</tr>
</thead>
</table>
</div>
</div>
<file_sep># cpp
# mantenedor de actividades completo<file_sep><style type="text/css">
.btn_elimina{
margin-left: 10px!important;
}
.ver_obs_desp,.ver_obs{
cursor: pointer;
display: inline;
margin-left: 5px;
font-size: 13px;
color: #2780E3;
}
.btndesp span:hover{
color:#26A69A!important;
}
</style>
<script type="text/javascript">
$(function(){
/*****DEFINICIONES*****/
$.fn.modal.Constructor.prototype.enforceFocus = function() {};
$('.clockpicker').clockpicker();
var fecha_hoy="<?php echo $fecha_hoy; ?>";
var fecha_anio_atras="<?php echo $fecha_anio_atras; ?>";
$("#desdef").val(fecha_anio_atras);
$("#hastaf").val(fecha_hoy);
$("#fecha_inicio").val(fecha_hoy);
$("#fecha_finalizacion").val(fecha_hoy);
var idUsuarioCPP="<?php echo $this->session->userdata("idUsuarioCPP"); ?>";
var id_perfil_CPP="<?php echo $this->session->userdata("id_perfil_CPP"); ?>";
var base="<?php echo base_url();?>";
$.extend(true,$.fn.dataTable.defaults,{
info:false,
paging:true,
ordering:true,
searching:true,
lengthChange: false,
bSort: true,
bFilter: true,
bProcessing: true,
pagingType: "simple" ,
bAutoWidth: true,
sAjaxDataProp: "result",
bDeferRender: true,
language : {
url: "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json",
},
});
function visibilidadExcel(){
if(id_perfil_CPP==4){
$(".btn_excel_act").hide();
}else{
$(".btn_excel_act").show();
}
}
visibilidadExcel();
function iniciaEjecutor(){
if(id_perfil_CPP==1 || id_perfil_CPP==2){//ADMIN,GERENTES
accion = 1;//TODO
}
if(id_perfil_CPP==3){//SUPERVISOR
accion = 2;//SU PERSONAL
}
if(id_perfil_CPP==4){//EJECUTOR
accion = 3;//SUS REGISTROS
}
$.getJSON('getUsuariosSel2CPP', {accion:accion},
function(response) {
$("#select_usuario").select2({
allowClear: true,
placeholder: 'Seleccione usuario',
data: response
});
});
setTimeout( function () {
$('#select_usuario').val(idUsuarioCPP).trigger('change');
}, 2000 );
}
/*****DATATABLE*****/
var table_cpp = $('#tabla_cpp').DataTable({
"iDisplayLength":50,
"aaSorting" : [[1,'asc']],
"scrollY": 420,
"scrollX": true,
select: true,
"columnDefs":[
{targets: [13], visible : id_perfil_CPP!=4 ? true : false },
],
"ajax": {
"url":"<?php echo base_url();?>listaCPP",
"dataSrc": function (json) {
$(".btn_filtra_cpp").html('<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar');
$(".btn_filtra_cpp").prop("disabled" , false);
desde = $("#desdef").val();
hasta = $("#hastaf").val();
return json;
},
data: function(param){
param.desde = $("#desdef").val();
param.hasta = $("#hastaf").val();
if(id_perfil_CPP==1 || id_perfil_CPP==2){//ADMIN,GERENTES
accion = 1;//TODO
}
if(id_perfil_CPP==3){//SUPERVISOR
accion = 2;//SU PERSONAL
}
if(id_perfil_CPP==4){//EJECUTOR
accion = 3;//SUS REGISTROS
}
param.accion = accion
}
},
"columns": [
{
"class":"","data": function(row,type,val,meta){
if(id_perfil_CPP==1 || id_perfil_CPP==3){
btn='<center><a href="#!" title="Editar" data-hash="'+row.hash_id+'" class="btn_edita"><i class="fa fa-edit" style="font-size:15px;"></i> </a>';
btn+='<a href="#!" title="Eliminar" data-hash="'+row.hash_id+'" class="btn_elimina"><i class="fa fa-trash" style="font-size:15px;"></i> </a></center>';
}else if(id_perfil_CPP==4 && idUsuarioCPP==row.id_usuario){
if(row.estado==0){
btn='<center><a href="#!" title="Editar" data-hash="'+row.hash_id+'" class="btn_edita"><i class="fa fa-edit" style="font-size:15px;"></i> </a>';
}else{
btn="<center>-</center>";
}
//btn+='<a href="#!" title="Eliminar" data-hash="'+row.hash_id+'" class="btn_elimina"><i class="fa fa-trash" style="font-size:14px;"></i> </a></center>';
}else{
btn="<center>-</center>";
}
return btn;
}
},
{
"class":"","data": function(row,type,val,meta){
if(row.estado==0){
b='<i class="fa fa-question-circle" style="color:red;font-size:13px;margin-top:2px;"></i> '+row.estado_str+'';
}else
if(row.estado==1){
b='<i class="fa fa-check-circle" style="color:#1E748D;font-size:13px;margin-top:2px;"></i> '+row.estado_str+'';
}
return b;
}
},
{ "data": "ejecutor" ,"class":"margen-td"},
{ "data": "fecha_inicio" ,"class":"margen-td"},
{
"class":"","data": function(row,type,val,meta){
return row.hora_inicio.substring(0, 5);
}
},
{ "data": "fecha_termino" ,"class":"margen-td"},
{
"class":"","data": function(row,type,val,meta){
return row.hora_termino.substring(0, 5);
}
},
{
"class":"","data": function(row,type,val,meta){
return row.duracion;
}
},
{ "data": "proyecto_empresa" ,"class":"margen-td"},
{ "data": "proyecto_tipo" ,"class":"margen-td"},
{ "data": "actividad" ,"class":"margen-td"},
{ "data": "proyecto_desc" ,"class":"margen-td"},
{ "data": "unidad" ,"class":"margen-td"},
{ "data": "valor" ,"class":"margen-td"},
{ "data": "cantidad" ,"class":"margen-td"},
{ "data": "supervisor" ,"class":"margen-td"},
{ "data": "fecha_aprob" ,"class":"margen-td"},
{
"class":"","data": function(row,type,val,meta){
return row.hora_aprob.substring(0, 5);
}
},
{ "data": "digitador" ,"class":"margen-td"},
{ "data": "fecha_dig" ,"class":"margen-td"},
{
"class":"centered margen-td","data": function(row,type,val,meta){
obs=row.comentarios.toLowerCase().capitalize();
var str = obs;
if(str.length > 40) {
str = str.substring(0,40)+"...";
return "<span class='btndesp2'>"+str+"</span><span title='Ver texto completo' class='ver_obs_desp' data-tit="+obs.replace(/ /g,"_")+" data-title="+obs.replace(/ /g,"_")+">Ver más</span>";
}else{
return "<span class='btndesp2' data-title="+obs.replace(/ /g,"_")+">"+obs+"</span>";
}
}
},
{ "data": "ultima_actualizacion" ,"class":"margen-td"}
]
});
$(document).on('keyup paste', '#buscador_inf', function() {
table_cpp.search($(this).val().trim()).draw();
});
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
setTimeout( function () {
var table_cpp = $.fn.dataTable.fnTables(true);
if ( table_cpp.length > 0 ) {
$(table_cpp).dataTable().fnAdjustColumnSizing();
}}, 1000 );
$(document).off('click', '.btn_filtra_cpp').on('click', '.btn_filtra_cpp',function(event) {
event.preventDefault();
$(this).prop("disabled" , true);
$(".btn_filtra_cpp").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Filtrando');
table_cpp.ajax.reload();
});
$(document).on('click', '.ver_obs_desp', function(event) {
event.preventDefault();
val=$(this).attr("data-tit");
elem=$(this);
if(elem.text()=="Ver más"){
elem.html("Ocultar");
elem.attr("title","Acortar texto");
elem.prev(".btndesp2").text(val.replace(/_/g, ' '));
var table = $.fn.dataTable.fnTables(true);
if ( table.length > 0 ) {
$(table).dataTable().fnAdjustColumnSizing();
}
}else if(elem.text()=="Ocultar"){
val = val.substring(0,40)+"...";
elem.prev(".btndesp2").text(val.replace(/_/g, ' '));
elem.html("Ver más");
elem.attr("title","Ver texto completo");
var table = $.fn.dataTable.fnTables(true);
if ( table.length > 0 ) {
$(table).dataTable().fnAdjustColumnSizing();
}
}
});
/*******NUEVO**********/
$(document).off('click', '.btn_cpp').on('click', '.btn_cpp',function(event) {
$('#modal_cpp').modal('toggle');
$(".btn_ingresa_cpp").html('<i class="fa fa-save"></i> Guardar');
$(".btn_ingresa_cpp").attr("disabled", false);
$(".cierra_mod_cpp").attr("disabled", false);
$('#formCPP')[0].reset();
$("#id_cpp").val("");
$("#formCPP input,#formCPP select,#formCPP button,#formCPP").prop("disabled", false);
$('#proyecto_tipo').val("").trigger('change');
$('#actividad').val("").trigger('change');
$("#estado").attr("disabled", true);
$("#unidad_medida").attr("disabled", true);
$("#fecha_inicio").val(fecha_hoy);
$("#fecha_finalizacion").val(fecha_hoy);
iniciaEjecutor();
});
$(document).off('submit', '#formCPP').on('submit', '#formCPP',function(event) {
var url="<?php echo base_url()?>";
var formElement = document.querySelector("#formCPP");
var formData = new FormData(formElement);
$.ajax({
url: $('#formCPP').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
beforeSend:function(){
$(".btn_ingresa_cpp").attr("disabled", true);
$(".cierra_mod_cpp").attr("disabled", true);
$("#formCPP input,#formCPP select,#formCPP button,#formCPP").prop("disabled", true);
$(".btn_ingresa_cpp").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Cargando...');
},
success: function (data) {
if(data.res == "error"){
$(".btn_ingresa_cpp").attr("disabled", false);
$(".cierra_mod_cpp").attr("disabled", false);
$("#formCPP input,#formCPP select,#formCPP button,#formCPP").prop("disabled", false);
$("#estado").attr("disabled", true);
$("#unidad_medida").attr("disabled", true);
$.notify(data.msg, {
className:'error',
globalPosition: 'top right',
autoHideDelay:5000,
});
if($("#id_cpp").val()!=""){
$(".btn_ingresa_cpp").html('<i class="fa fa-edit"></i> Modificar');
$('#modal_cpp').modal("toggle");
}else{
$(".btn_ingresa_cpp").html('<i class="fa fa-save"></i> Guardar');
}
iniciaEjecutor();
}else if(data.res == "ok"){
$(".btn_ingresa_cpp").attr("disabled", false);
$(".cierra_mod_cpp").attr("disabled", false);
$("#formCPP input,#formCPP select,#formCPP button,#formCPP").prop("disabled", false);
$("#estado").attr("disabled", true);
$("#unidad_medida").attr("disabled", true);
$.notify(data.msg, {
className:'success',
globalPosition: 'top right',
autoHideDelay:5000,
});
table_cpp.ajax.reload();
if($("#id_cpp").val()!=""){
$(".btn_ingresa_cpp").html('<i class="fa fa-edit"></i> Modificar');
$('#modal_cpp').modal("toggle");
}else{
$(".btn_ingresa_cpp").html('<i class="fa fa-save"></i> Guardar');
}
iniciaEjecutor();
}else if(data.res=="sess"){
window.location="unlogin";
}
}
});
return false;
});
$.getJSON('getTiposPorPe', {pe: ""},
function(response) {
$("#proyecto_tipo").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
$.getJSON('getActividadesPorTipo', {pt: ""},
function(response) {
$("#actividad").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
/*******MODIFICAR**********/
$(document).off('click', '.btn_edita').on('click', '.btn_edita',function(event) {
hash=$(this).attr("data-hash");
$(".btn_ingresa_cpp").html('<i class="fa fa-edit" ></i> Modificar');
$('#formCPP')[0].reset();
$("#id_cpp").val("");
$('#modal_cpp').modal("toggle");
$(".cierra_mod_cpp").prop("disabled", false);
$("#formCPP input,#formCPP select,#formCPP button,#formCPP").prop("disabled", true);
$.ajax({
url: "getDataAct"+"?"+$.now(),
type: 'POST',
cache: false,
tryCount : 0,
retryLimit : 3,
data:{hash:hash},
dataType:"json",
beforeSend:function(){
$(".btn_ingresa_cpp").prop("disabled",true);
$(".cierra_mod_cpp").prop("disabled",true);
},
success: function (data) {
if(data.res=="ok"){
setTimeout( function () {
$("#formCPP input,#formCPP select,#formCPP button,#formCPP").prop("disabled", false);
$("#unidad_medida").attr("disabled", true);
if(id_perfil_CPP==1 || id_perfil_CPP==3){
$("#estado").attr("disabled", false);
/*$("#apr_sp").show();*/
}else{
/*$("#apr_sp").hide();*/
$("#estado").attr("disabled", true);
}
},1500);
$("#estado").attr("disabled", true);
for(dato in data.datos){
estado=data.datos[dato].id_estado;
id_actividad=data.datos[dato].id_actividad;
id_proyecto_empresa=data.datos[dato].id_proyecto_empresa;
id_proyecto_tipo=data.datos[dato].id_proyecto_tipo;
$("#id_cpp").val(data.datos[dato].hash_id);
$("#proyecto_empresa option[value='"+data.datos[dato].id_proyecto_empresa+"'").prop("selected", true);
$("#estado option[value='"+data.datos[dato].estado+"'").prop("selected", true);
setTimeout( function () {
$.getJSON('getTiposPorPe', {pe: id_proyecto_empresa},
function(response) {
$("#proyecto_tipo").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
$('#proyecto_tipo').val(id_proyecto_tipo).trigger('change');
},600);
setTimeout( function () {
$.getJSON('getActividadesPorTipo', {pt: id_proyecto_tipo},
function(response) {
$("#actividad").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
$('#actividad').val(id_actividad).trigger('change');
},1200);
/*$('#select_usuario').html('').select2({data: [{id: '', text: ''}]});
$.getJSON('getUsuariosSel2CPP', {idUsuarioCPP:data.datos[dato].id_usuario},
function(response) {
$("#select_usuario").select2({
allowClear: true,
placeholder: 'Seleccione usuario',
data: response
});
});
setTimeout( function () {
$('#select_usuario').val(data.datos[dato].id_usuario).trigger('change');
}, 2000 ); */
if(id_perfil_CPP==1 || id_perfil_CPP==2){//ADMIN,GERENTES
accion = 1;//TODO
}
if(id_perfil_CPP==3){//SUPERVISOR
accion = 2;//SU PERSONAL
}
if(id_perfil_CPP==4){//EJECUTOR
accion = 3;//SUS REGISTROS
}
$.getJSON('getUsuariosSel2CPP', {accion:accion},
function(response) {
$("#select_usuario").select2({
allowClear: true,
placeholder: 'Seleccione usuario',
data: response
});
});
setTimeout( function () {
$('#select_usuario').val(data.datos[dato].id_usuario).trigger('change');
}, 2000 );
$("#cantidad").val(data.datos[dato].cantidad);
$("#fecha_inicio").val(data.datos[dato].fecha_inicio);
$("#hora_inicio").val(data.datos[dato].hora_inicio.substring(0, 5));
$("#fecha_finalizacion").val(data.datos[dato].fecha_termino);
$("#hora_finalizacion").val(data.datos[dato].hora_termino.substring(0, 5));
$("#proyecto_desc").val(data.datos[dato].proyecto_desc);
$("#comentarios").val(data.datos[dato].comentarios);
}
}else if(data.res=="sess"){
window.location="unlogin";
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.notify("Reintentando...", {
className:'info',
globalPosition: 'top right'
});
$.ajax(this);
return;
} else{
$.notify("Problemas en el servidor, intente nuevamente.", {
className:'warn',
globalPosition: 'top right'
});
$('#modal_cpp').modal("toggle");
}
return;
}
if (xhr.status == 500) {
$.notify("Problemas en el servidor, intente más tarde.", {
className:'warn',
globalPosition: 'top right'
});
$('#modal_cpp').modal("toggle");
}
},timeout:5000
});
});
$(document).off('click', '.btn_elimina').on('click', '.btn_elimina',function(event) {
hash=$(this).attr("data-hash");
if(confirm("¿Esta seguro que desea eliminar este registro?")){
$.post('eliminaActividad'+"?"+$.now(),{"hash": hash}, function(data) {
if(data.res=="ok"){
$.notify(data.msg, {
className:'success',
globalPosition: 'top right'
});
table_cpp.ajax.reload();
}else if(data.res=="error"){
$.notify(data.msg, {
className:'danger',
globalPosition: 'top right'
});
}else if(data.res=="sess"){
window.location="unlogin";
}
},"json");
}
});
$(document).off('change', '#proyecto_empresa').on('change', '#proyecto_empresa', function(event) {
event.preventDefault();
pe=$("#proyecto_empresa").val();
$('#proyecto_tipo').html('').select2({data: [{id: '', text: ''}]});
$.getJSON('getTiposPorPe', {pe: pe},
function(response) {
$("#proyecto_tipo").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
$("#unidad_medida").val("");
});
$(document).off('change', '#proyecto_tipo').on('change', '#proyecto_tipo', function(event) {
event.preventDefault();
pt=$("#proyecto_tipo").val();
$('#actividad').html('').select2({data: [{id: '', text: ''}]});
$.getJSON('getActividadesPorTipo', {pt: pt},
function(response) {
$("#actividad").select2({
allowClear: true,
placeholder: 'Buscar...',
data: response
});
});
$("#unidad_medida").val("");
});
$(document).off('change', '#actividad').on('change', '#actividad', function(event) {
event.preventDefault();
ac=$("#actividad").val();
$.post('getUmPorActividad'+"?"+$.now(),{"ac": ac}, function(data) {
if(data.res=="ok"){
$("#unidad_medida").val(data.dato);
}else{
/*$.notify(data.msg, {
className:'error',
globalPosition: 'top right',
autoHideDelay:5000,
});*/
}
},"json");
});
/********OTROS**********/
$(".floattext").keydown(function (event) {
if (event.shiftKey == true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {
} else {
event.preventDefault();
}
if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
event.preventDefault();
});
/*$(".hora_text").keydown(function (event) {
if (event.shiftKey == true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {
} else {
event.preventDefault();
}
});*/
$(".inttext").keydown(function (event) {
if (event.shiftKey == true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
event.keyCode == 39 || event.keyCode == 46) {
} else {
event.preventDefault();
}
});
$(".fecha_normal").datetimepicker({
format: "YYYY-MM-DD",
locale:"es",
maxDate:"now"
});
$(document).off('click', '.btn_excel_act').on('click', '.btn_excel_act',function(event) {
event.preventDefault();
var desde = $("#desdef").val();
var hasta = $("#hastaf").val();
if(desde==""){
$.notify("Debe seleccionar una fecha de inicio.", {
className:'error',
globalPosition: 'top right'
});
return false;
}
if(hasta==""){
$.notify("Debe seleccionar una fecha de término.", {
className:'error',
globalPosition: 'top right'
});
return false;
}
window.location="excelTareas/"+desde+"/"+hasta;
});
})
</script>
<!--FILTROS-->
<div class="form-row">
<div class="col-6 col-lg-2">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-sm btn-outline-primary btn_cpp">
<i class="fa fa-plus-circle"></i> Nuevo
</button>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id=""><i class="fa fa-calendar-alt"></i></span>
</div>
<input type="text" placeholder="Desde" class="fecha_normal form-control form-control-sm" name="desdef" id="desdef">
<input type="text" placeholder="Hasta" class="fecha_normal form-control form-control-sm" name="hastaf" id="hastaf">
</div>
</div>
</div>
<div class="col-lg-5">
<div class="form-group">
<input type="text" placeholder="Ingrese su busqueda..." id="buscador_inf" class="buscador_inf form-control form-control-sm">
</div>
</div>
<div class="col-6 col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-outline-primary btn-primary btn_filtra_cpp">
<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar
</button>
</div>
</div>
<div class="col-6 col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-outline-primary btn-primary btn_excel_act">
<i class="fa fa-save"></i> Excel
</button>
</div>
</div>
</div>
<!-- LISTADO -->
<div class="row">
<div class="col">
<table id="tabla_cpp" class="table table-hover table-bordered dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th>Acciones</th>
<th>Estado</th>
<th>Ejecutor</th>
<th>Fecha inicio</th>
<th>Hr ini.</th>
<th>Fecha fin.</th>
<th>Hr fin.</th>
<th>Duración</th>
<th>Proyecto Empresa</th>
<th>Proyecto Tipo</th>
<th>Actividad</th>
<th>Proyecto Descripción</th>
<th>Unidad</th>
<th>Valor</th>
<th>Cantidad</th>
<th>Supervisor</th>
<th>Fecha Aprob</th>
<th>Hr Aprob</th>
<th>Digitador</th>
<th>Fecha digitación</th>
<th>Observaciones</th>
<th>Última actualización</th>
</tr>
</thead>
</table>
</div>
</div>
<!-- FORMULARIOS-->
<!-- NUEVO INFORME-->
<div id="modal_cpp" class="modal fade bd-example-modal-lg" data-backdrop="static" aria-labelledby="myModalLabel" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<?php echo form_open_multipart("formCPP",array("id"=>"formCPP","class"=>"formCPP"))?>
<input type="hidden" name="id_cpp" id="id_cpp">
<button type="button" title="Cerrar Ventana" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<fieldset class="form-ing-cont">
<legend class="form-ing-border">Ingreso de actividades</legend>
<div class="form-row">
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Usuario</label>
<select id="select_usuario" name="ejecutor" class="custom-select custom-select-sm" style="width:100%!important;">
<option selected value="">Seleccione usuario </option>
</select>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Proyecto empresa</label>
<select id="proyecto_empresa" name="proyecto_empresa" class="custom-select custom-select-sm">
<option selected value="">Seleccione proyecto empresa</option>
<?php
foreach($proyecto_empresa as $p){
?>
<option value="<?php echo $p["id"]; ?>"><?php echo $p["nombre"]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Proyecto tipo</label>
<select id="proyecto_tipo" name="proyecto_tipo" class="custom-select custom-select-sm" style="width:100%!important;">
<option selected value="">Seleccione tipo proyecto </option>
</select>
</div>
</div>
<div class="col-lg-3">
<div class="form-group">
<label>Actividad</label>
<select id="actividad" name="actividad" class="custom-select custom-select-sm" style="width:100%!important;">
<option selected value="">Ingrese actividad</option>
</select>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Proyecto descripción</label>
<input type="text" id="proyecto_desc" autocomplete="off" placeholder="Ingrese Proyecto descripción" class="form-control form-control-sm" name="proyecto_desc">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Unidad medida</label>
<input type="text" autocomplete="off" placeholder="" class="form-control form-control-sm" name="" id="unidad_medida">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Cantidad</label>
<input type="text" maxlength="5" autocomplete="off" placeholder="" class="inttext form-control form-control-sm" name="cantidad" id="cantidad">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Fecha inicio</label>
<input type="text" autocomplete="off" placeholder="Ingrese Fecha inicio" class="fecha_normal fecha_inicio form-control form-control-sm" name="fecha_inicio" id="fecha_inicio">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Hora inicio</label>
<input type="text" autocomplete="off" maxlength="5" class="clockpicker hora_text form-control form-control-sm" data-autoclose="true" data-align="top" placeholder="Hora" autocomplete="on" id="hora_inicio" name="hora_inicio">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Fecha finalización</label>
<input type="text" autocomplete="off" placeholder="Ingrese Fecha finalización" class="fecha_normal fecha_finalizacion form-control form-control-sm" name="fecha_finalizacion" id="fecha_finalizacion">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Hora finalización</label>
<input type="text" autocomplete="off" maxlength="5" class="clockpicker hora_text form-control form-control-sm" data-autoclose="true" data-align="top" placeholder="Hora" autocomplete="on" id="hora_finalizacion" name="hora_finalizacion">
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Estado</label>
<select id="estado" name="estado" class="custom-select custom-select-sm">
<option selected value="0">Pendiente supervisor </option>
<option value="1" id="apr_sp">Aprobado supervisor </option>
</select>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Comentarios</label>
<input type="text" autocomplete="off" maxlength="200" placeholder="Ingrese Comentarios" class="form-control form-control-sm" name="comentarios" id="comentarios">
</div>
</div>
</div>
</fieldset>
<br>
<div class="col-lg-4 offset-lg-4">
<div class="form-row">
<div class="col-6 col-lg-6">
<div class="form-group">
<button type="submit" class="btn-block btn btn-sm btn-primary btn_ingresa_cpp">
<i class="fa fa-save"></i> Guardar
</button>
</div>
</div>
<div class="col-6 col-lg-6">
<button class="btn-block btn btn-sm btn-dark cierra_mod_inf" data-dismiss="modal" aria-hidden="true">
<i class="fa fa-window-close"></i> Cerrar
</button>
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
<file_sep><style type="text/css">
.btn_agregar_us,.btn_reset_us,.btn_excel_us{
margin-top: 30px;
}
</style>
<script type="text/javascript">
$(function(){
pf="<?php echo $id_perfil_CPP ?>";
$.getJSON('getUsuariosSel2', {},
function(response) {
$("#select_usuario").select2({
allowClear: true,
placeholder: 'Seleccione usuario',
data: response
});
});
var tabla_mant_us = $('#tabla_mant_us').DataTable({
"iDisplayLength":50,
"aaSorting" : [[1,'asc']],
"scrollY": 420,
"scrollX": true,
info:true,
paging:false,
select: true,
columnDefs:[
/* { "name": "acciones",targets: [0],searcheable : false,orderable:false},
{targets: [8], orderData: [5,6]}, //al ordenar por fecha, se ordenera por especialidad,comuna
{targets: [16],orderable:false,searcheable : false}, */
],
"ajax": {
"url":"<?php echo base_url();?>listaMantUsuarios",
"dataSrc": function (json) {
$(".btn_filtra_cpp").html('<i class="fa fa-cog fa-1x"></i><span class="sr-only"></span> Filtrar');
$(".btn_filtra_cpp").prop("disabled" , false);
return json;
},
data: function(param){
}
},
"columns": [
{
"class":"","data": function(row,type,val,meta){
btn="<center>";
if(pf==1){
btn+='<a href="#!" title="Editar" data-hash="'+row.hash_id+'" class="btn_edita"><i class="fa fa-edit" style="font-size:14px;"></i> </a>';
btn+='<a href="#!" title="Eliminar" data-hash="'+row.hash_id+'" class="btn_elimina"><i class="fa fa-trash" style="font-size:14px;margin-left:10px;"></i> </a></center>';
}else{
btn+="-</center>"
}
return btn;
}
},
{ "data": "usuario" ,"class":"margen-td"},
{ "data": "rut" ,"class":"margen-td"},
{ "data": "cargo" ,"class":"margen-td"},
{ "data": "empresa" ,"class":"margen-td"},
{ "data": "perfil" ,"class":"margen-td"},
{ "data": "supervisor" ,"class":"margen-td"},
{ "data": "supervisor2" ,"class":"margen-td"},
{ "data": "ultima_actualizacion" ,"class":"margen-td"}
]
});
$(document).on('keyup paste', '#buscador_us', function() {
tabla_mant_us.search($(this).val().trim()).draw();
});
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
$(document).off('submit', '#formMantUs').on('submit', '#formMantUs',function(event) {
var url="<?php echo base_url()?>";
var formElement = document.querySelector("#formMantUs");
var formData = new FormData(formElement);
$.ajax({
url: $('#formMantUs').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
beforeSend:function(){
/*$(".btn_agregar_us").attr("disabled", true);
$("#formMantUs input,#formMantUs select,#formMantUs button,#formMantUs").prop("disabled", true);*/
},
success: function (data) {
if(data.res == "error"){
$(".btn_agregar_us").attr("disabled", false);
$.notify(data.msg, {
className:'error',
globalPosition: 'top right',
autoHideDelay:5000,
});
$("#formMantUs input,#formMantUs select,#formMantUs button,#formMantUs").prop("disabled", false);
}else if(data.res == "ok"){
$(".btn_agregar_us").attr("disabled", false);
$("#formMantUs input,#formMantUs select,#formMantUs button,#formMantUs").prop("disabled", false);
$.notify(data.msg, {
className:'success',
globalPosition: 'top right',
autoHideDelay:5000,
});
$("#id_mant_us").val("");
$("#select_perfil option[value=''").prop("selected", true);
$("#supervisor option[value=''").prop("selected", true);
$("#supervisor2 option[value=''").prop("selected", true);
$('#select_usuario').val("").trigger('change');
$(".btn_agregar_us").html(' <i class="fa fa-plus"></i> Agregar');
tabla_mant_us.ajax.reload();
}else if(data.res == "sess"){
window.location="unlogin";
}
}
});
return false;
});
$(document).off('click', '.btn_edita').on('click', '.btn_edita',function(event) {
hash=$(this).attr("data-hash");
$(".btn_agregar_us").html('<i class="fa fa-edit" ></i> Modificar');
$('#formMantUs')[0].reset();
$("#id_mant_us").val("");
$("#formMantUs input,#formMantUs select,#formMantUs button,#formMantUs").prop("disabled", true);
$.ajax({
url: "getDataMantUs"+"?"+$.now(),
type: 'POST',
cache: false,
tryCount : 0,
retryLimit : 3,
data:{hash:hash},
dataType:"json",
beforeSend:function(){
/*$(".btn_agregar_us").prop("disabled",true);
*/
},
success: function (data) {
if(data.res=="ok"){
for(dato in data.datos){
$("#id_mant_us").val(data.datos[dato].hash_id);
$("#select_perfil option[value='"+data.datos[dato].id_perfil+"'").prop("selected", true);
$("#supervisor option[value='"+data.datos[dato].id_supervisor+"'").prop("selected", true);
$("#supervisor2 option[value='"+data.datos[dato].id_supervisor2+"'").prop("selected", true);
$('#select_usuario').val(data.datos[dato].id_usuario).trigger('change');
}
$(".btn_agregar_us").html('<i class="fa fa-edit" ></i> Modificar');
$("#formMantUs input,#formMantUs select,#formMantUs button,#formMantUs").prop("disabled", false);
}else if(data.res=="ok"){
$.notify("Problemas en el servidor, intente más tarde.", {
className:'warn',
globalPosition: 'top right'
});
}else if(data.res == "sess"){
window.location="unlogin";
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.notify("Reintentando...", {
className:'info',
globalPosition: 'top right'
});
$.ajax(this);
return;
} else{
$.notify("Problemas en el servidor, intente nuevamente.", {
className:'warn',
globalPosition: 'top right'
});
}
return;
}
if (xhr.status == 500) {
$.notify("Problemas en el servidor, intente más tarde.", {
className:'warn',
globalPosition: 'top right'
});
}
},timeout:5000
});
});
$(document).off('click', '.btn_elimina').on('click', '.btn_elimina',function(event) {
hash=$(this).attr("data-hash");
if(confirm("¿Esta seguro que desea eliminar este registro?")){
$.post('eliminaUsuario'+"?"+$.now(),{"hash": hash}, function(data) {
if(data.res=="ok"){
$.notify(data.msg, {
className:'success',
globalPosition: 'top right'
});
tabla_mant_us.ajax.reload();
}else if(data.res=="error"){
$.notify(data.msg, {
className:'danger',
globalPosition: 'top right'
});
}else if(data.res == "sess"){
window.location="unlogin";
}
},"json");
}
});
$(document).off('click', '.btn_reset_us').on('click', '.btn_reset_us',function(event) {
$("#id_mant_us").val("");
$("#select_perfil option[value=''").prop("selected", true);
$("#supervisor option[value=''").prop("selected", true);
$("#supervisor2 option[value=''").prop("selected", true);
$('#select_usuario').val("").trigger('change');
$(".btn_agregar_us").html(' <i class="fa fa-plus"></i> Agregar');
});
$(document).off('click', '.btn_excel_us').on('click', '.btn_excel_us',function(event) {
event.preventDefault();
window.location="excelusuarios";
});
})
</script>
<!--FILTROS-->
<?php echo form_open_multipart("formMantUs",array("id"=>"formMantUs","class"=>"formMantUs"))?>
<div class="form-row">
<input type="hidden" name="id_mant_us" id="id_mant_us">
<div class="col-lg-3">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Usuario</label>
<select id="select_usuario" name="usuario" class="custom-select custom-select-sm" style="width:100%!important;">
<option selected value="">Seleccione usuario </option>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Perfil</label>
<select id="select_perfil" name="perfil" class="custom-select custom-select-sm">
<option value="">Seleccione perfil</option>
<?php
foreach($perfiles as $p){
?>
<option value="<?php echo $p["id"] ?>"><?php echo $p["perfil"] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Supervisor</label>
<select id="supervisor" name="supervisor" class="custom-select custom-select-sm">
<option value="">Seleccione supervisor</option>
<?php
foreach($supervisores as $s){
?>
<option value="<?php echo $s["id"] ?>"><?php echo $s["nombre"] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label for="colFormLabelSm" class="col-sm-12 col-form-label col-form-label-sm">Supervisor 2</label>
<select id="supervisor2" name="supervisor2" class="custom-select custom-select-sm">
<option value="">Seleccione supervisor 2</option>
<?php
foreach($supervisores as $s){
?>
<option value="<?php echo $s["id"] ?>"><?php echo $s["nombre"] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-lg-1">
<div class="form-group">
<button type="submit" class="btn-block btn btn-sm btn-primary btn_agregar_us">
<i class="fa fa-plus"></i> Agregar
</button>
</div>
</div>
<div class="col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-primary btn_reset_us">
<!-- <i class="fa fa-plus"></i> --> Reset
</button>
</div>
</div>
<div class="col-lg-1">
<div class="form-group">
<button type="button" class="btn-block btn btn-sm btn-primary btn_excel_us">
<i class="fa fa-save"></i> Excel
</button>
</div>
</div>
</div>
<?php echo form_close(); ?>
<!-- LISTADO -->
<hr>
<div class="col-lg-6 offset-3" style="margin-top: 10px;">
<div class="form-group">
<input type="text" placeholder="Ingrese su busqueda..." id="buscador_us" class="buscador_us form-control form-control-sm">
</div>
</div>
<div class="form-row">
<div class="col">
<table id="tabla_mant_us" class="table table-hover table-bordered dt-responsive nowrap" style="width:100%">
<thead>
<tr>
<th>Acciones</th>
<th>Usuario</th>
<th>RUT</th>
<th>Cargo</th>
<th>Empresa</th>
<th>Perfil</th>
<th>Supervisor</th>
<th>Supervisor2</th>
<th>Última actualización</th>
</tr>
</thead>
</table>
</div>
</div><file_sep><style type="text/css">
@media (min-width: 768px){
div.dataTables_wrapper div.dataTables_paginate {
margin-top:10px;
}
}
@media (max-width: 768px){
div.dataTables_wrapper div.dataTables_paginate {
text-align: center;
margin: 10px auto!important;
}
}
.custom-select-sm {
padding-bottom: .175rem!important;
font-size: .875rem!important;
}
@media (min-width: 768px){
.select2-results__option {
padding: 1px!important;
font-size: 14px;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
font-size: .875rem!important;
}
}
</style>
<script type="text/javascript">
$(function(){
var perfil="<?php echo $this->session->userdata("id_perfil_CPP"); ?>";
function inicio(perfil){
if(perfil==1){
$("#menu_usuarios").show();
$("#menu_mantenedor_actividades").show();
$("#menu_graficos").show();
}else{
$("#menu_usuarios").hide();
$("#menu_mantenedor_actividades").hide();
$("#menu_graficos").hide();
}
}
inicio(perfil);
$(".nav-tabs-int").addClass('disabled');
$("#menu_detalle_diario a").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Detalle de actividades diarias');
$(".contenedor_produccion").html("<center><img src='<?php echo base_url()?>assets/imagenes/loader2.gif' class='loader'></center>");
$("#menu_detalle_diario").addClass('menuActivo');
$("#menu_vista_mensual").removeClass('menuActivo');
$("#menu_graficos").removeClass('menuActivo');
$("#menu_mantenedor_actividades").removeClass('menuActivo');
$("#menu_usuarios").removeClass('menuActivo');
$.get("getCPPView", function( data ) {
$(".contenedor_produccion").html(data);
$(".nav-tabs-int").removeClass('disabled');
$("#menu_detalle_diario a").html('<i class="fa fa-list-ul"></i> Detalle de actividades diarias');
});
$(document).off('click', '#menu_detalle_diario').on('click', '#menu_detalle_diario',function(event) {
event.preventDefault();
$(".nav-tabs-int").addClass('disabled');
$("#menu_detalle_diario a").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Detalle de actividades diarias');
$(".contenedor_produccion").html("<center><img src='<?php echo base_url()?>assets/imagenes/loader2.gif' class='loader'></center>");
$("#menu_detalle_diario").addClass('menuActivo');
$("#menu_vista_mensual").removeClass('menuActivo');
$("#menu_graficos").removeClass('menuActivo');
$("#menu_mantenedor_actividades").removeClass('menuActivo');
$("#menu_usuarios").removeClass('menuActivo');
$.get("getCPPView", function( data ) {
$(".contenedor_produccion").html(data);
$(".nav-tabs-int").removeClass('disabled');
$("#menu_detalle_diario a").html('<i class="fa fa-list-ul"></i> Detalle de actividades diarias');
});
});
$(document).off('click', '#menu_vista_mensual').on('click', '#menu_vista_mensual',function(event) {
event.preventDefault();
$(".nav-tabs-int").addClass('disabled');
$("#menu_vista_mensual a").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Vista mensual');
$(".contenedor_produccion").html("<center><img src='<?php echo base_url()?>assets/imagenes/loader2.gif' class='loader'></center>");
$("#menu_detalle_diario").removeClass('menuActivo');
$("#menu_vista_mensual").addClass('menuActivo');
$("#menu_graficos").removeClass('menuActivo');
$("#menu_mantenedor_actividades").removeClass('menuActivo');
$("#menu_usuarios").removeClass('menuActivo');
$.get("getVistaMensualView", function( data ) {
$(".contenedor_produccion").html(data);
$(".nav-tabs-int").removeClass('disabled');
$("#menu_vista_mensual a").html('<i class="fa fa-calendar"></i> Vista mensual');
});
});
$(document).off('click', '#menu_graficos').on('click', '#menu_graficos',function(event) {
event.preventDefault();
$(".nav-tabs-int").addClass('disabled');
$("#menu_graficos a").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Graficos');
$(".contenedor_produccion").html("<center><img src='<?php echo base_url()?>assets/imagenes/loader2.gif' class='loader'></center>");
$("#menu_detalle_diario").removeClass('menuActivo');
$("#menu_vista_mensual").removeClass('menuActivo');
$("#menu_graficos").addClass('menuActivo');
$("#menu_mantenedor_actividades").removeClass('menuActivo');
$("#menu_usuarios").removeClass('menuActivo');
$.get("getVistaGraficos", function( data ) {
$(".contenedor_produccion").html(data);
$(".nav-tabs-int").removeClass('disabled');
$("#menu_graficos a").html('<i class="fa fa-chart-bar"></i> Graficos');
});
});
$(document).off('click', '#menu_mantenedor_actividades').on('click', '#menu_mantenedor_actividades',function(event) {
event.preventDefault();
$(".nav-tabs-int").addClass('disabled');
$("#menu_mantenedor_actividades a").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Mantenedor actividades');
$(".contenedor_produccion").html("<center><img src='<?php echo base_url()?>assets/imagenes/loader2.gif' class='loader'></center>");
$("#menu_detalle_diario").removeClass('menuActivo');
$("#menu_vista_mensual").removeClass('menuActivo');
$("#menu_graficos").removeClass('menuActivo');
$("#menu_mantenedor_actividades").addClass('menuActivo');
$("#menu_usuarios").removeClass('menuActivo');
$.get("getMantActView", function( data ) {
$(".contenedor_produccion").html(data);
$(".nav-tabs-int").removeClass('disabled');
$("#menu_mantenedor_actividades a").html('<i class="fa fa-th-list"></i> Mantenedor actividades');
});
});
$(document).off('click', '#menu_usuarios').on('click', '#menu_usuarios',function(event) {
event.preventDefault();
$(".nav-tabs-int").addClass('disabled');
$("#menu_usuarios a").html('<i class="fa fa-cog fa-spin fa-1x fa-fw"></i><span class="sr-only"></span> Mantenedor Usuarios');
$(".contenedor_produccion").html("<center><img src='<?php echo base_url()?>assets/imagenes/loader2.gif' class='loader'></center>");
$("#menu_detalle_diario").removeClass('menuActivo');
$("#menu_vista_mensual").removeClass('menuActivo');
$("#menu_graficos").removeClass('menuActivo');
$("#menu_mantenedor_actividades").removeClass('menuActivo');
$("#menu_usuarios").addClass('menuActivo');
$.get("getMantUsView", function( data ) {
$(".contenedor_produccion").html(data);
$(".nav-tabs-int").removeClass('disabled');
$("#menu_usuarios a").html('<i class="fa fa-user"></i> Mantenedor Usuarios');
});
});
})
</script>
<!-- MENU -->
<div class="row menu_superior">
<div class="col-12">
<ul class="nav nav-tabs navbar-left nav-tabs-int">
<li id="menu_detalle_diario" class="active"><a><i class="fa fa-list-ul"></i> Detalle de actividades diarias</a></li>
<li id="menu_vista_mensual" class="active"><a><i class="fa fa-calendar"></i> Vista mensual</a></li>
<li id="menu_graficos" class="active"><a><i class="fa fa-chart-bar"></i> Graficos</a></li>
<li id="menu_mantenedor_actividades" class="active"><a><i class="fa fa-th-list"></i> Mantenedor actividades</a></li>
<li id="menu_usuarios" class="active"><a><i class="fa fa-user"></i> Mantenedor Usuarios</a></li>
</ul>
</div>
</div>
<!-- CONTENEDOR MATERIALES -->
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="contenedor_produccion"></div>
</div>
</div>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 09-07-2018 a las 18:16:45
-- Versión del servidor: 10.1.25-MariaDB
-- Versión de PHP: 5.6.31
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 */;
--
-- Base de datos: `km1`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cpp`
--
CREATE TABLE `cpp` (
`id` int(11) NOT NULL,
`id_actividad` int(11) NOT NULL,
`id_usuario` int(11) NOT NULL,
`id_supervisor` int(11) NOT NULL,
`id_digitador` int(11) NOT NULL,
`fecha` date NOT NULL,
`cantidad` int(11) NOT NULL,
`proyecto_descripcion` varchar(200) NOT NULL,
`estado` char(1) NOT NULL,
`comentarios` varchar(300) NOT NULL,
`fecha_aprobacion` date NOT NULL,
`fecha_digitacion` date NOT NULL,
`ultima_actualizacion` varchar(300) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `cpp`
--
INSERT INTO `cpp` (`id`, `id_actividad`, `id_usuario`, `id_supervisor`, `id_digitador`, `fecha`, `cantidad`, `proyecto_descripcion`, `estado`, `comentarios`, `fecha_aprobacion`, `fecha_digitacion`, `ultima_actualizacion`) VALUES
(5, 32, 432, 0, 432, '2018-07-09', 1, '', '0', '', '0000-00-00', '2018-07-09', '2018-07-09 12:15:32 | <NAME>'),
(6, 10, 432, 0, 432, '2018-07-04', 1, '', '0', '', '0000-00-00', '2018-07-09', '2018-07-09 12:15:16 | <NAME>');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `cpp`
--
ALTER TABLE `cpp`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `cpp`
--
ALTER TABLE `cpp`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;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>-- phpMyAdmin SQL Dump
-- version 4.7.0
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 09-07-2018 a las 18:15:53
-- Versión del servidor: 10.1.25-MariaDB
-- Versión de PHP: 5.6.31
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 */;
--
-- Base de datos: `km1`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `cpp_proyecto_tipo`
--
CREATE TABLE `cpp_proyecto_tipo` (
`id` int(11) NOT NULL,
`id_proyecto_empresa` int(11) NOT NULL,
`tipo` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Volcado de datos para la tabla `cpp_proyecto_tipo`
--
INSERT INTO `cpp_proyecto_tipo` (`id`, `id_proyecto_empresa`, `tipo`) VALUES
(1, 1, 'Diseño HFC-Relevamiento'),
(2, 1, 'Diseño HFC-Diseño'),
(3, 1, 'Diseño HFC-Diseño F.O.'),
(4, 1, 'Traslado de Redes'),
(5, 1, 'Inmobiliario'),
(6, 3, 'Inmobiliario'),
(7, 3, 'Despliegue FTTX - Relevamiento'),
(8, 3, 'Despliegue FTTX - Diseño'),
(9, 3, 'Empresas Movistar'),
(10, 2, 'Dibujo'),
(11, 2, 'Relevamiento'),
(12, 2, 'Factibilidad'),
(13, 4, 'Dibujo'),
(14, 4, 'Relevamiento'),
(15, 4, 'Factibilidad'),
(16, 5, 'Dibujo'),
(17, 5, 'Relevamiento'),
(18, 5, 'Factibilidad');
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `cpp_proyecto_tipo`
--
ALTER TABLE `cpp_proyecto_tipo`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `cpp_proyecto_tipo`
--
ALTER TABLE `cpp_proyecto_tipo`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;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><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$route['default_controller'] = 'inicio';
$route['404_override'] = "";
$route['nojs'] = "inicio/nojs";
$route['inicio'] = "inicio/index";
$route['login'] = "inicio/login";
$route['formRecuperarPass'] = "inicio/formRecuperarPass";
$route['actualizarPassForm'] = "inicio/actualizarPassForm";
$route['unlogin'] = "inicio/unlogin";
$route['loginProcess'] = "inicio/loginProcess";
$route['enviarCorreo'] = "inicio/enviarCorreo";
$route['resetPass'] = "inicio/resetPass";
$route['resetpassproc'] = "inicio/resetpassproc";
$route[''] = "inicio/index";
/****** CPP*******/
$route['getCPPInicio'] = "back_end/cpp/getCPPInicio";
$route['getCPPView'] = "back_end/cpp/getCPPView";
$route['listaCPP'] = "back_end/cpp/listaCPP";
$route['getActividadesPorPe'] = "back_end/cpp/getActividadesPorPe";
$route['formCPP'] = "back_end/cpp/formCPP";
$route['eliminaActividad'] = "back_end/cpp/eliminaActividad";
$route['getDataAct'] = "back_end/cpp/getDataAct";
$route['getTiposPorPe'] = "back_end/cpp/getTiposPorPe";
$route['getActividadesPorTipo'] = "back_end/cpp/getActividadesPorTipo";
$route['getUmPorActividad'] = "back_end/cpp/getUmPorActividad";
$route['excelTareas/(:any)/(:any)'] = "back_end/cpp/excelTareas/$1/$2";
$route['getUsuariosSel2CPP'] = "back_end/cpp/getUsuariosSel2CPP";
/****** VISTA MENSUAL*******/
$route['getVistaMensualView'] = "back_end/cpp/getVistaMensualView";
$route['listaMes'] = "back_end/cpp/listaMes";
$route['excelMensual/(:any)/(:any)/(:any)'] = "back_end/cpp/excelMensual/$1/$2/$3";
/****** GRAFICOS *******/
$route['getVistaGraficos'] = "back_end/cpp/getVistaGraficos";
/****** MANTENEDOR ACTIVIDADES ******/
$route['getMantActView'] = "back_end/cpp/getMantActView";
$route['listaActividad'] = "back_end/cpp/listaActividad";
$route['formActividad'] = "back_end/cpp/formActividad";
$route['deleteActividad'] = "back_end/cpp/deleteActividad";
$route['getDataActividad'] = "back_end/cpp/getDataActividad";
$route['excelInforme/(:any)'] = "back_end/cpp/excelInforme/$1";
$route['getMantUsView'] = "back_end/cpp/getMantUsView";
/****** MANTENEDOR USUARIOS*******/
$route['getMantUsView'] = "back_end/cpp/getMantUsView";
$route['getUsuariosSel2'] = "back_end/cpp/getUsuariosSel2";
$route['listaMantUsuarios'] = "back_end/cpp/listaMantUsuarios";
$route['formMantUs'] = "back_end/cpp/formMantUs";
$route['getDataMantUs'] = "back_end/cpp/getDataMantUs";
$route['eliminaUsuario'] = "back_end/cpp/eliminaUsuario";
$route['excelusuarios'] = "back_end/cpp/excelusuarios";
/* End of file routes.php */
/* Location: ./application/config/routes.php */<file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<noscript>
<div class="noscriptmsg">
<meta http-equiv="refresh" content="0;URL=<?php echo base_url()?>nojs">
</div>
</noscript>
<title><?php echo $titulo?></title>
<?php
if($this->session->userdata('empresaCPP')=="km"){
?>
<link rel="icon" href="<?php echo base_url(); ?>assets/imagenes/favicon_km3.png">
<?php
}elseif ($this->session->userdata('empresaCPP')=="splice") {
?>
<link rel="icon" href="<?php echo base_url(); ?>assets/imagenes/logo_splice22.png">
<?php
}
?>
<script src="<?php echo base_url();?>assets/back_end/js/jquery.min.js" charset="UTF-8"></script>
<script src="<?php echo base_url();?>assets/back_end/js/loader.js" charset="UTF-8"></script>
<link rel="stylesheet" href="<?php echo base_url();?>assets/back_end/css/loader.css" >
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart','table','bar','line']});
</script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="body">
<div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
</div>
<header>
<?php
$n=explode(" ",$this->session->userdata("nombresUsuarioCPP"));
$empresa=$this->session->userdata("empresaCPP");
?>
<nav class="navbar navbar-expand-lg navbar-dark bg-light fixed-top nav-tabs-main">
<a class="navbar-brand" href="#">
<?php
if($empresa=="km"){
?>
<img class="logo_header_km" class="d-inline-block align-top" alt="" src="<?php echo base_url();?>assets/imagenes/nuevologokm.png">
<?php
}elseif ($empresa=="splice") {
?>
<img class="logo_header" class="d-inline-block align-top" alt="" src="<?php echo base_url();?>assets/imagenes/logo_splice22.png">
<?php
}
?>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li id="menu_cpp" class="nav-item">
<a class="nav-link" href="#"><i class="fas fa-table"></i> Control Productividad Personas</a>
</li>
</ul>
<ul class="nav navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-item nav-link dropdown-toggle mr-md-2" href="#" id="bd-versions" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<?php echo $n[0];?>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="bd-versions">
<a style="margin-top: 1px!important;" href="#actualizarPassModal" data-toggle="modal" class="dropdown-item" id="btn_actualizar_datos"><span class="fa fa-edit"></span> Cambiar contraseña</a>
<a style="margin-top: 1px!important;" href="unlogin" class="dropdown-item" href="#"><span class="fas fa-power-off"></span> Cerrar Sesión</a>
</div>
</li>
</ul>
</div>
</nav>
</header>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="">
<meta name="author" content="">
<title></title>
<script src="<?php echo base_url();?>assets/back_end/js/jquery.min.js"></script>
<script src="<?php echo base_url();?>assets/back_end/js/bootstrap.min.js"></script>
<link href="<?php echo base_url();?>assets/back_end/css/normalize.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/bootstrap.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/estilos_km.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/fontawesome-all.min.css" rel="stylesheet">
<link href="<?php echo base_url();?>assets/back_end/css/form_style.css" rel="stylesheet">
<style type="text/css" media="screen">
body{
background-image: url("./assets/imagenes/fondolog.jpg");
background-size: cover;
overflow-y:hidden;
}
.alert {
padding: 6px;
margin-bottom: 0px;
border: 1px solid transparent;
border-radius: 4px;
text-align:left;
}
.top-content{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
.contenedor-pass{
width:40%;
}
.titulo-pass{
color:#f8f9fa;
padding-bottom:20px;
}
</style>
<!--<script type="text/javascript">
$(function(){
$(document).on('click', '.unlogin', function(event) {
event.preventDefault();
window.location="unlogin";
});
var c="<?php echo $this->session->userdata('contrasena_actualizada');?>";
if(c==""){
$("header,footer").hide();
}
$('#changepass_form').submit(function(){
var formElement = document.querySelector("#changepass_form");
var formData = new FormData(formElement);
$.ajax({
url: $('.changepass_form').attr('action')+"?"+$.now(),
type: 'POST',
data: formData,
cache: false,
processData: false,
dataType: "json",
contentType : false,
success: function (data) {
//alert(data);
if(data.res == 0){
$('.validation_changepass').hide();
$('.validation_changepass').fadeIn();
$(".validation_changepass").html('<div class="alert alert-danger" align="center"><strong>Debe rellenar los campos.</strong></div>');
}else
if(data.res == 1){
$('.validation_changepass').hide();
$('.validation_changepass').fadeIn();
$(".validation_changepass").html('<div class="alert alert-danger" align="center"><strong>Las contraseñas deben coincidir.</strong></div>');
}else
if(data.res == 2){
$('.validation_changepass').hide();
$('.validation_changepass').fadeIn();
$(".validation_changepass").html('<div class="alert alert-danger" align="center"><strong>Contraseña incorrecta.</strong></div>');
}else
if(data.res == 3){
$('.validation_changepass').hide();
$('.validation_changepass').fadeIn();
$(".validation_changepass").html('<div class="alert alert-success" align="center"><strong>Contraseña modificada correctamente.</strong></div>');
$("#progress").html('<div class="progress"><div class="indeterminate"></div></div>');
$("#progress").show();
setTimeout(function(){window.location="unlogin"} ,1000);
}else
if(data.res == 4){
$('.validation_changepass').hide();
$('.validation_changepass').fadeIn();
$(".validation_changepass").html('<div class="alert alert-danger" align="center"><strong>Problemas accediento a la base de datos, intente nuevamente.</strong></div>');
}else
if(data.res == 5){
$('.validation_changepass').hide();
$('.validation_changepass').fadeIn();
$(".validation_changepass").html('<div class="alert alert-danger" align="center"><strong>La contraseña no puede la misma o el rut.</strong></div>');
}
},
error:function(){
alert("Problemas accediento a la base de datos, intente nuevamente.");
}
});
return false;
});
});
</script>-->
<div class="container top-content row justify-content-center align-items-center" style="height:400px;">
<div class="contenedor-pass">
<div><h3 class="titulo-pass">Crear Contraseña Nueva</h3></div>
<div class="form-group">
<input type="password" class="form-control separador" placeholder="Ingrese Contraseña Actual" name="passActual" id="passActual">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Ingrese Contraseña Nueva" name="passNueva" id="passNueva">
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Repita Contraseña" name="passRe<PASSWORD>" id="pass<PASSWORD>">
</div>
<div class="form-group">
<button type="submit" class="btn-block btn btn-sm btn-primary btn_nuevapass_cpp" style="background-color: #1E748D">Cambiar Contraseña</button>
</div>
</div>
</div>
</html>
</body><file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Inicio extends CI_Controller {
public function __construct(){
parent::__construct();
if($this->uri->segment("1")==""){
redirect("inicio");
}
$this->load->model("back_end/Iniciomodel");
$this->load->helper(array('fechas','str'));
$this->load->library('user_agent');
}
public function nojs(){
$this->load->view('back_end/nojs');
}
public function acceso(){
if(!$this->session->userdata("rutUserCPP")){redirect("login");}
}
public function checkLogin(){
if($this->session->userdata('idUsuarioCPP')==""){
echo json_encode(array('res'=>"sess"));exit;
}
}
public function index(){
$this->acceso();
$fecha_anio_atras=date('d-m-Y', strtotime('-360 day', strtotime(date("d-m-Y"))));
$fecha_hoy=date('Y-m-d');
$datos = array(
'titulo' => "CPP",
'contenido' => "inicio",
'fecha_anio_atras' => $fecha_anio_atras,
'fecha_hoy' => $fecha_hoy
);
$this->load->view('plantillas/plantilla_back_end',$datos);
}
public function login(){
$datos = array(
'titulo' => "Inicio de sesión",
);
$this->load->view('back_end/login',$datos);
}
public function loginProcess(){
if($this->input->is_ajax_request()){
$rut=$this->security->xss_clean(strip_tags($this->input->post("usuario")));
$rut1=str_replace('.', '', $rut);
$rut2=str_replace('.', '', $rut1);
$usuario=str_replace('-', '', $rut2);
$pass=sha1(trim($this->security->xss_clean(strip_tags($this->input->post("pass")))));
if(empty($usuario) or empty($pass)){
echo json_encode(array("res" => "error", "msg" => "Debe ingresar los datos." ,"usuario" => $pass));exit;
}
if ($this->Iniciomodel->login($usuario,$pass)==1) {
$dataInsert=array("usuario" => $this->session->userdata('nombresUsuario')." ".$this->session->userdata('apellidosUsuario'),
"fecha"=>date("Y-m-d G:i:s"),
"navegador"=>"navegador :".$this->agent->browser()."\nversion :".$this->agent->version()."\nos :".$this->agent-> platform()."\nmovil :".$this->agent->mobile(),
"ip"=>$this->input->ip_address(),
"pagina"=> "CPP"
);
echo json_encode(array("res" => "ok", "msg" => "Ingresando al sistema..." ));
}elseif($this->Iniciomodel->login($usuario,$pass)==2){
echo json_encode(array("res" => "error", "msg" => "El usuario no existe en la base de datos","usuario" => $pass));
}
elseif($this->Iniciomodel->login($usuario,$pass)==3){
echo json_encode(array("res" => "error", "msg" => "Contraseña Incorrecta."));
}
}else{
exit("No direct script access allowed");
}
}
public function unlogin(){
$this->session->sess_destroy();
redirect("");
}
/*public function resetPass(){
if($this->input->is_ajax_request()){
if($this->form_validation->run('resetPass') == FALSE){
echo json_encode(array('res'=>"error", 'msg' => strip_tags(validation_errors())));exit;
}else{
$email=$this->security->xss_clean(strip_tags($this->input->post("correo")));
$result=$this->Iniciomodel->getCorreo($email);
if($result){
$this->enviarCorreo($email, $result);
$this->load->view('back_end/resetpass', array('correo' => $email));
}else{
$this->load->view('back_end/resetpass', array('error' => "El Email no está registrado."));
}
}
}else{
$this->load->view('back_end/resetpass');
}
}
public function enviarCorreo($email,$nombre){
$this->load->library('email');
$this->email->set_mailtype('html');
$desdecorreo="<EMAIL>";
$desdenombre="<NAME>";
$asunto="Recuperar contraseña de KM";
$msg='<p>Estimado' . " " . $nombre . ',</p>';
$msg .='<p>Ud a solicitado recuperar la contraseña de su correo KM.
por favor haga <strong><a href="' .base_url() . 'resetPass'.'">Click Aqui</a></strong> para cambiar su contraseña</p>';
$config = array(
'charset' => 'utf-8',
'priority' => '1',
'wordwrap' => TRUE
);
$this->email->initialize($config);
$this->email->from($desdecorreo, $desdenombre);
$this->email->to($email);
//$this->email->bcc("copiaoculta");
$this->email->subject($asunto);
$this->email->message($msg);
//$this->email->attach($archivo);
$res=$this->email->send();
echo json_encode(array("res" => 1));
exit;
}*/
public function formRecuperarPass(){
if($this->input->is_ajax_request()){
$rut=$this->security->xss_clean(strip_tags($this->input->post("rut_rec")));
$rut1=str_replace('.', '', $rut);
$rut2=str_replace('.', '', $rut1);
$usuario=str_replace('-', '', $rut2);
if($usuario==""){echo json_encode(array("res" => "error", "msg" => "Debe ingresar el usuario."));exit;}
if($this->Iniciomodel->existeUsuario($usuario)){
$correo=$this->Iniciomodel->getCorreoPorRut($usuario);
if($correo=!FALSE){
$this->enviaCorreoRecuperacion($usuario);
echo json_encode(array("res" => "ok", "msg" => "Nueva contraseña enviada al correo : ".$this->Iniciomodel->getCorreoPorRut($usuario)));exit;
}else{
echo json_encode(array("res" => "error", "msg" => "Debe ingresar el usuario."));exit;
}
}else{
echo json_encode(array("res" => "error", "msg" => "Debe ingresar un usuario válido."));exit;
}
}else{
exit("No direct script access allowed");
}
}
public function enviaCorreoRecuperacion($usuario){
$this->load->library('email');
$config = array (
'mailtype' => 'html',
'charset' => 'utf-8',
'priority' => '1',
'wordwrap' => TRUE
);
$this->email->initialize($config);
$hash=$this->Iniciomodel->getHashFromRut($usuario);
$prueba=FALSE;
$data=$this->Iniciomodel->getUserData($hash);
foreach($data as $key){
if($prueba){
$correo = array('<EMAIL>');
}else{
$correo = $key["correo"];
}
$pass=$this->generarPass();
$passsha1=sha1($pass);
$data_pass=array("contrasena"=>$pass<PASSWORD>);
$datos=array("datos"=>$data,"pass"=>$pass);
$html=$this->load->view('back_end/recuperar_pass',$datos,TRUE);
$this->email->from("<EMAIL>","CPP");
$this->email->to($correo);
$this->email->subject("Recuperación de contraseña CPP , ".$key["nombre"]."");
$this->email->message($html);
$resp=$this->email->send();
if ($resp) {
$id=$this->Iniciomodel->getIdPorHash($hash);
$this->Iniciomodel->actualizaPass($id,$data_pass);
return TRUE;
}else{
return FALSE;
}
}
}
public function generarPass(){
$length=5;
$uc=FALSE;
$n=FALSE;
$sc=FALSE;
$source = 'abcdefghijklmnopqrstuvwxyz';
$source = '1234567890';
if($uc==1) $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if($n==1) $source .= '1234567890';
if($sc==1) $source .= '|@#~$%()=^*+[]{}-_';
if($length>0){
$rstr = "";
$source = str_split($source,1);
for($i=1; $i<=$length; $i++){
mt_srand((double)microtime() * 1000000);
$num = mt_rand(1,count($source));
$rstr .= $source[$num-1];
}
}
return $rstr;
}
public function actualizarPassForm(){
if($this->input->is_ajax_request()){
$this->checkLogin();
$id_usuario=$this->session->userdata('idUsuarioCPP');
$pass=$this->security->xss_clean(strip_tags($this->input->post("pass_us")));
if($pass==""){echo json_encode(array("res" => "error", "msg" => "Debe ingresar la contraseña."));exit;}
if(strlen($pass)<4){echo json_encode(array("res" => "error", "msg" => "La contraseña debe tener mínimo 4 caracteres."));exit;}
$data=array("contrasena" => sha1($pass));
if($this->Iniciomodel->actualizaContrasena($id_usuario,$data)){
echo json_encode(array("res" => "ok", "msg" => "Contraseña actualizada correctamente"));exit;
}else{
echo json_encode(array("res" => "error", "msg" => "Problemas actualizando la contraseña, intente más tarde."));exit;
}
}else{
exit("No direct script access allowed");
}
}
} | a7a2930cd2b84dfc59e0ac8bf3d9307203bb2d4d | [
"Markdown",
"SQL",
"PHP"
]
| 19 | PHP | Luiscode7/cpp | dbe086e52ad950b27ce7b42a634fb930740f5fe2 | 4e1f048785a73c7868dceaa248c2bbf79db35f26 |
refs/heads/master | <file_sep>PyGithub==1.26.0
rethinkdb==2.3.0.post3
<file_sep># jeffops-backend
Python backend for JeffOps
## Instructions
### Github updater
```sh
./github-updater.py
```
<file_sep>import rethinkdb as r
r.connect( "localhost", 28015).repl()
r.db("test").table_create("projects").run()
r.table("projects").insert([
{
"name": "Project #"+str(i),
"versions": {
"production": "1.2."+str(i),
"staging": "1."+str(i+1),
"testing": "0.0.0-feature-"+["backend", "db", "kubernetes", "cooladata"][i%4],
}
} for i in range(10)
]).run()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
from datetime import datetime
import logging as log
import argparse
import os
import pytz
from github import Github
import rethinkdb as r
GITHUB_UPDATE_S = 5*60
GITHUB_CLIENT_ID = os.getenv("GITHUB_CLIENT_ID")
GITHUB_CLIENT_SECRET = os.getenv("GITHUB_CLIENT_SECRET")
GITHUB_ORGANISATION = os.getenv("GITHUB_ORGANISATION", "ConnectedVentures")
RETHINK_HOST = "localhost"
RETHINK_PORT = 28015
RETHINK_DATABASE = "test"
@asyncio.coroutine
def updater(con):
last_scan = None
def has_updated(repo):
return repo.updated_at > last_scan
org = get_org()
while True:
gh_repos = org.get_repos()
# If not scanning for the first time only keep repositories which
# have been updated on Github since the last repository cache update
if last_scan is not None:
gh_repos = [repo for repo in gh_repos if has_updated(repo)]
last_scan = datetime.now()
# Names of Github repositories to update or insert in database
repo_names = [repo.name for repo in gh_repos]
# Names of Github repositories that are in the previous list
# AND in our table already
db_repo_names = [repo["name"] for repo in r.table("repositories").filter(
r.row["name"] in repo_names).pluck("name").run(con)]
# Go over all tables that have been updated since last scan
for gh_repo in gh_repos:
# Add timezone to Github dates
pushed_at = gh_repo.pushed_at.replace(tzinfo=pytz.UTC)
updated_at = gh_repo.updated_at.replace(tzinfo=pytz.UTC)
this_repo = {
"name": gh_repo.name,
"description": gh_repo.description,
"html_url": gh_repo.html_url,
"pushed_at": pushed_at,
"updated_at": updated_at,
"versions": {
"production": "1.2.3",
"staging": "1.3",
"testing": "0.0.0-feature-hello",
}
}
if gh_repo.name in db_repo_names:
# This repository already exists in the table but needs to be
# updated
log.debug("Update repo %s", gh_repo.name)
r.table("repositories").filter(r.row["name"] == gh_repo.name).update(this_repo).run(con)
else:
# Insert as it"s not in the table
log.debug("Insert repo %s", gh_repo.name)
r.table("repositories").insert(this_repo).run(con)
yield from asyncio.sleep(GITHUB_UPDATE_S)
def get_org():
gh = Github(client_id=GITHUB_CLIENT_ID, client_secret=GITHUB_CLIENT_SECRET)
return gh.get_organization(GITHUB_ORGANISATION)
def main():
# Set up logging
parser = argparse.ArgumentParser()
parser.add_argument(
"-d", "--debug",
help="Print lots of debugging statements",
action="store_const", dest="loglevel", const=log.DEBUG,
default=log.WARNING,
)
parser.add_argument(
"-v", "--verbose",
help="Be verbose",
action="store_const", dest="loglevel", const=log.INFO,
)
args = parser.parse_args()
log.basicConfig(level=args.loglevel)
con = r.connect("localhost", 28015)
db = r.db(RETHINK_DATABASE)
if "repositories" not in db.table_list().run(con):
db.table_create("repositories").run(con)
else:
print("table already exists")
loop = asyncio.get_event_loop()
try:
asyncio.async(updater(con))
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
print("close")
loop.close()
if __name__ == "__main__":
main()
| 644d2b03601edd666a6c50ceb671fea16b110a9b | [
"Markdown",
"Python",
"Text"
]
| 4 | Text | JeffOps/jeffops-backend | e0b13eb9cae9d4ba6c0932a5cf2ec6265dd0ed6a | c8b39b3937d888f8c4cec7db92c5b602b7e0c50a |
refs/heads/master | <repo_name>HR-SEA16-SDC2/zakbar<file_sep>/database/schema.sql
DROP DATABASE IF EXISTS qanda;
CREATE DATABASE qanda;
USE qanda;
CREATE TABLE questions (
question_id SERIAL NOT NULL,
product_id INTEGER NOT NULL,
body VARCHAR (250) NOT NULL,
date_written DATE NOT NULL,
asker_name VARCHAR(250) NOT NULL,
asker_email VARCHAR(250) NOT NULL,
reported BOOLEAN,
helpful INTEGER,
PRIMARY KEY (question_id),
UNIQUE(question_id)
);
CREATE TABLE answers (
answer_id SERIAL NOT NULL,
question_id INTEGER NOT NULL,
body VARCHAR (250) NOT NULL,
date_written DATE NOT NULL,
answerer_name VARCHAR(250) NOT NULL,
answerer_email VARCHAR(250) NOT NULL,
reported BOOLEAN,
helpful INTEGER,
PRIMARY KEY (answer_id),
FOREIGN KEY (question_id) REFERENCES questions(question_id),
UNIQUE(answer_id)
);
CREATE TABLE photos (
photo_id SERIAL NOT NULL,
answer_id INTEGER NOT NULL,
url VARCHAR (2048) NOT NULL,
PRIMARY KEY (photo_id),
FOREIGN KEY (answer_id) REFERENCES answers(answer_id),
UNIQUE(photo_id)
);<file_sep>/database/index.js
const { user, password, database } = require("./config");
const { Pool } = require("pg");
const config = {
host: "localhost",
user: `${user}`,
password: `${<PASSWORD>}`,
database: `${database}`,
port: 5432,
max: 20,
idleTimeoutMillis: 30000
};
const pool = new Pool(config);
(async function() {
const client = await pool.connect();
await console.log(`${user} connected to postgres database: ${database}`);
client.release();
})();
pool.on("error", (err, client) => {
console.error("Error:", err);
});
module.exports = pool;
/*
-------------Error first pool connection-------------
pool.connect((err) => {
if (err) {
console.error("connection error: ", err.stack);
} else {
console.log(`${user} connected to postgres database: ${database}`);
}
});
-------------Async connection-------------
async function connect() {
const c = await client.connect(); // try to connect
return c.client.serverVersion; // return server version
}
connect()
-------------Postgres connection string template-------------
var connectionString = `postgres://${user}:${password}@localhost:5432/${database}`;
-------------pgp package based connection-------------
const db=pgp(connectionString)
async function testConnection() {
const c = await db.connect();
c.done();
return c.client.serverVersion;
}
export - no model, need to extract queries, helper function to generate the queries.
*/<file_sep>/server/controllers/questionControllers.js
const {
returnQuestions,
postQuestion,
updateHelpfulQuestion,
updateReportQuestion
} = require("../../database/models/questionModels");
async function listQuestions (req, res) {
try {
console.log("Hit questions endpoint");
const allQuestions = await returnQuestions(req, res);
console.log(allQuestions);
res.status(200).send(allQuestions);
} catch (e) {
console.error(e);
res.status(500).send(e);
}
}
async function addQuestion (req, res) {
try {
console.log("Hit questions endpoint");
await postQuestion(req, res);
res.sendStatus(200);
} catch (e) {
console.error(e);
res.status(500).send(e);
}
}
async function helpfulQuestion(req, res) {
try {
console.log("Hit helpful questions endpoint");
await updateHelpfulQuestion(req, res);
res.sendStatus(200);
} catch (e) {
console.error(e);
res.status(500).send(e);
}
}
async function reportQuestion (req, res) {
try {
console.log("Hit questions endpoint");
await updateReportQuestion(req, res);
res.sendStatus(200);
} catch (e) {
console.error(e);
res.status(500).send(e);
}
}
module.exports = {
listQuestions,
addQuestion,
helpfulQuestion,
reportQuestion
}; | 4fd82fd78773c8ad64abd48c3cc9a42d2e167776 | [
"JavaScript",
"SQL"
]
| 3 | SQL | HR-SEA16-SDC2/zakbar | 5d85bd6d60c8d238fd400a37a6a991966236c072 | ecad67e6fc832291bf1bc202ccb5a2f260dcfb78 |
refs/heads/master | <repo_name>gibberfish/FootballResultsApiIntegrationTests<file_sep>/src/test/java/mindbadger/football/api/AbstractRestAssuredTest.java
package mindbadger.football.api;
import com.jayway.restassured.RestAssured;
import org.junit.After;
import org.junit.Before;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import static mindbadger.football.api.ApiTestConstants.*;
import static mindbadger.football.api.helpers.OperationHelper.whenDelete;
public class AbstractRestAssuredTest {
protected String port;
protected String basePath;
protected String host;
protected Set<String> newDivisionIds = new HashSet<>();
protected Set<String> newTeamIds = new HashSet<>();
protected Set<String> newFixtureIds = new HashSet<>();
protected Set<String> newTeamStatisticIds = new HashSet<>();
protected Set<String> newDivisionMappingIds = new HashSet<>();
protected Set<String> newTeamMappingIds = new HashSet<>();
protected Set<String> newTrackedDivisionIds = new HashSet<>();
@Before
public void setup() throws IOException {
Properties prop = new Properties();
prop.load(SeasonApiTest.class.getClassLoader().getResourceAsStream("application.properties"));
port = prop.getProperty("server.port");
RestAssured.port = Integer.valueOf(port);
basePath = prop.getProperty("server.base");
RestAssured.basePath = basePath;
host = prop.getProperty("server.host");
RestAssured.baseURI = host;
}
@After
public void deleteTestData() {
for (String teamStatisticId : newTeamStatisticIds) {
whenDelete(TEAM_STATISTICS_URL, teamStatisticId);
}
for (String fixtureId : newFixtureIds) {
whenDelete(FIXTURE_URL, fixtureId);
}
whenDelete(SEASON_URL, SEASON_NUMBER);
whenDelete(SEASON_URL, SEASON_NUMBER_2);
for (String divisionId : newDivisionIds) {
whenDelete(DIVISION_URL, divisionId);
}
for (String teamId : newTeamIds) {
whenDelete(TEAM_URL, teamId);
}
for (String divisionMappingId : newDivisionMappingIds) {
whenDelete(DIVISION_MAPPING_URL, divisionMappingId);
}
for (String teamMappingId : newTeamMappingIds) {
whenDelete(TEAM_MAPPING_URL, teamMappingId);
}
for (String trackedDivisionId : newTrackedDivisionIds) {
whenDelete(TRACKED_DIVISION_URL, trackedDivisionId);
}
}
}
<file_sep>/src/test/resources/application.properties
server.port=1972
server.base=/dataapi/
server.host=http://localhost
logging.level.mindbadger=INFO
logging.level.org.springframework=INFO
<file_sep>/src/test/java/mindbadger/football/api/SeasonDivisionApiTest.java
package mindbadger.football.api;
import org.apache.http.HttpStatus;
import org.junit.Test;
import static mindbadger.football.api.ApiTestConstants.*;
import static mindbadger.football.api.helpers.MessageCreationHelper.withSeason;
import static mindbadger.football.api.helpers.MessageCreationHelper.withSeasonDivision;
import static mindbadger.football.api.helpers.OperationHelper.*;
import static mindbadger.football.api.helpers.TestPreConditionHelper.givenADivisionWithName;
import static mindbadger.football.api.helpers.TestPreConditionHelper.givenASeasonDivisionWith;
import static org.hamcrest.Matchers.*;
/**
* These tests are dependent upon a running API - the details of which are configured in the application.properties
*
* This test uses fake data that will be torn-down at the end.
* Therefore, this test can be run against a 'live' API.
*/
public class SeasonDivisionApiTest extends AbstractRestAssuredTest {
@Test
public void seasonDivisionHyperlinkForNewSeasonShouldReturnNoSeasonDivisions() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
whenGet(SEASON_TO_SEASON_DIVISION_URL).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data", empty());
}
@Test
public void shouldAddNewDivisionToSeason() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
final String SEASON_DIVISION_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId;
whenCreate(SEASON_TO_SEASON_DIVISION_URL,
withSeasonDivision(SEASON_NUMBER, newDivisionId, "1")).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_ID));
whenGet(SEASON_TO_SEASON_DIVISION_URL).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data.size()", is(1)).
body("data[0].id", equalTo(SEASON_DIVISION_ID));
}
@Test
public void shouldAddMultipleNewDivisionsToSeason() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivision1Id = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivision1Id);
givenASeasonDivisionWith(SEASON_NUMBER, newDivision1Id, "1");
String newDivision2Id = givenADivisionWithName(DIVISION2_NAME);
newDivisionIds.add(newDivision2Id);
final String SEASON_DIVISION_2_ID = SEASON_NUMBER + ID_SEPARATOR + newDivision2Id;
whenCreate(SEASON_TO_SEASON_DIVISION_URL,
withSeasonDivision(SEASON_NUMBER, newDivision2Id, "2")).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_2_ID));
whenGet(SEASON_TO_SEASON_DIVISION_URL).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data.size()", is(2));
}
@Test
public void shouldReturnNotFoundWhenGettingNonExistentSeasonDivision() {
whenGet(SEASON_TO_NON_EXISTENT_SEASON_DIVISION_URL).
then().
statusCode(HttpStatus.SC_NOT_FOUND);
}
@Test
public void shouldAddNewCanonicalSeasonDivision() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
final String SEASON_DIVISION_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId;
whenCreate(SEASON_DIVISION_URL,
withSeasonDivision(SEASON_NUMBER, newDivisionId, "1")).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_ID));
whenGet(SEASON_DIVISION_URL, SEASON_DIVISION_ID).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_ID));
}
@Test
public void shouldDeleteASeasonDivision() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
final String SEASON_DIVISION_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId;
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
whenDelete(SEASON_DIVISION_URL, SEASON_DIVISION_ID).
then().
statusCode(HttpStatus.SC_NO_CONTENT);
whenGet(SEASON_DIVISION_URL, SEASON_DIVISION_ID).
then().
statusCode(HttpStatus.SC_NOT_FOUND);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateADuplicateSeasonDivision () {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
whenCreate(SEASON_DIVISION_URL,
withSeasonDivision(SEASON_NUMBER, newDivisionId, "1")).
then().
statusCode(HttpStatus.SC_CONFLICT);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateASeasonDivisionWithANonExistentDivision () {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
whenCreate(SEASON_DIVISION_URL,
withSeasonDivision(SEASON_NUMBER, NON_EXISTENT_DIVISION_ID, "1")).
then().
statusCode(HttpStatus.SC_BAD_REQUEST);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateASeasonDivisionWithANonExistentSeason () {
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
whenCreate(SEASON_DIVISION_URL,
withSeasonDivision(NON_EXISTENT_SEASON_NUM, newDivisionId, "1")).
then().
statusCode(HttpStatus.SC_BAD_REQUEST);
}
@Test
public void shouldHaveAHyperlinksToSeasonDivisionTeamsAndFixtureDates () {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
final String SEASON_DIVISION_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId;
whenCreate(SEASON_DIVISION_URL,
withSeasonDivision(SEASON_NUMBER, newDivisionId, "1")).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_ID));
String divisionHyperlink = host + ":" + port + basePath +
SEASON_DIVISION_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + "/division";
String seasonHyperlink = host + ":" + port + basePath +
SEASON_DIVISION_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + "/season";
String teamsHyperlink = host + ":" + port + basePath +
SEASON_DIVISION_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + "/teams";
String fixtureDatesHyperlink = host + ":" + port + basePath +
SEASON_DIVISION_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + "/fixtureDates";
whenGet(SEASON_DIVISION_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId).
then().
assertThat().
body("data.relationships.division.links.related", equalTo(divisionHyperlink)).
body("data.relationships.season.links.related", equalTo(seasonHyperlink)).
body("data.relationships.teams.links.related", equalTo(teamsHyperlink)).
body("data.relationships.fixtureDates.links.related", equalTo(fixtureDatesHyperlink));
}
}<file_sep>/src/test/java/mindbadger/football/api/SeasonDivisionTeamApiTest.java
package mindbadger.football.api;
import org.apache.http.HttpStatus;
import org.junit.Test;
import static mindbadger.football.api.ApiTestConstants.*;
import static mindbadger.football.api.helpers.MessageCreationHelper.withSeason;
import static mindbadger.football.api.helpers.MessageCreationHelper.withSeasonDivisionTeam;
import static mindbadger.football.api.helpers.OperationHelper.*;
import static mindbadger.football.api.helpers.TestPreConditionHelper.*;
import static org.hamcrest.Matchers.*;
/**
* These tests are dependent upon a running API - the details of which are configured in the application.properties
*
* This test uses fake data that will be torn-down at the end.
* Therefore, this test can be run against a 'live' API.
*/
public class SeasonDivisionTeamApiTest extends AbstractRestAssuredTest {
@Test
public void seasonDivisionTeamsHyperlinkForNewSeasonDivisionShouldReturnNoSeasonDivisionTeams() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
final String SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL = SEASON_DIVISION_URL + SEASON_NUMBER +
ID_SEPARATOR + newDivisionId + "/teams";
whenGet(SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data", empty());
}
@Test
public void shouldAddNewTeamToSeasonDivision() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
final String SEASON_DIVISION_TEAM_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeamId;
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(SEASON_NUMBER, newDivisionId, newTeamId)).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_TEAM_ID));
final String SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL = SEASON_DIVISION_URL + SEASON_NUMBER +
ID_SEPARATOR + newDivisionId + "/teams";
whenGet(SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data.size()", is(1)).
body("data[0].id", equalTo(SEASON_DIVISION_TEAM_ID));
}
@Test
public void shouldAddMultipleNewTeamsToSeasonDivision() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeam1Id = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeam1Id);
String newTeam2Id = givenATeamWithName(TEAM2_NAME);
newTeamIds.add(newTeam2Id);
final String SEASON_DIVISION_TEAM1_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeam1Id;
final String SEASON_DIVISION_TEAM2_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeam2Id;
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(SEASON_NUMBER, newDivisionId, newTeam1Id)).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_TEAM1_ID));
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(SEASON_NUMBER, newDivisionId, newTeam2Id)).
then().
statusCode(HttpStatus.SC_CREATED).
assertThat().
body("data.id", equalTo(SEASON_DIVISION_TEAM2_ID));
final String SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL = SEASON_DIVISION_URL + SEASON_NUMBER +
ID_SEPARATOR + newDivisionId + "/teams";
whenGet(SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL).
then().
statusCode(HttpStatus.SC_OK).
assertThat().
body("data.size()", is(2));
}
@Test
public void shouldReturnNotFoundWhenGettingNonExistentSeasonDivisionTeamButSeasonDivisionExists() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
final String SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL = SEASON_DIVISION_TEAM_URL + SEASON_NUMBER +
ID_SEPARATOR + newDivisionId + ID_SEPARATOR + "NONEXISTENTTEAM";
whenGet(SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL).
then().
statusCode(HttpStatus.SC_NOT_FOUND);
}
@Test
public void shouldReturnNotFoundWhenGettingNonExistentSeasonDivisionTeamWhereSeasonDivisionDoesntExist() {
final String SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL = SEASON_DIVISION_TEAM_URL + SEASON_NUMBER +
ID_SEPARATOR + "NONEXISTENTDIVISION" + ID_SEPARATOR + "NONEXISTENTTEAM";
whenGet(SEASON_DIVISION_TO_SEASON_DIVISION_TEAM_URL).
then().
statusCode(HttpStatus.SC_NOT_FOUND);
}
@Test
public void shouldDeleteASeasonDivisionTeam() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
final String SEASON_DIVISION_TEAM_ID = SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeamId;
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
givenASeasonDivisionTeamWith(SEASON_NUMBER, newDivisionId, newTeamId);
whenDelete(SEASON_DIVISION_TEAM_URL, SEASON_DIVISION_TEAM_ID).
then().
statusCode(HttpStatus.SC_NO_CONTENT);
whenGet(SEASON_DIVISION_TEAM_URL, SEASON_DIVISION_TEAM_ID).
then().
statusCode(HttpStatus.SC_NOT_FOUND);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateADuplicateSeasonDivisionTeam() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
givenASeasonDivisionTeamWith(SEASON_NUMBER, newDivisionId, newTeamId);
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(SEASON_NUMBER, newDivisionId, newTeamId)).
then().
statusCode(HttpStatus.SC_CONFLICT);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateASeasonDivisionTeamWithANonExistentDivision() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(SEASON_NUMBER, NON_EXISTENT_DIVISION_ID, newTeamId)).
then().
statusCode(HttpStatus.SC_BAD_REQUEST);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateASeasonDivisionTeamWithANonExistentSeason() {
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(NON_EXISTENT_SEASON_NUM, newDivisionId, newTeamId)).
then().
statusCode(HttpStatus.SC_BAD_REQUEST);
}
@Test
public void shouldThrowAnErrorWhenAttemptToCreateASeasonDivisionTeamWithANonExistentTeam() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
whenCreate(SEASON_DIVISION_TEAM_URL, withSeasonDivisionTeam(SEASON_NUMBER, newDivisionId, NON_EXISTENT_TEAM_ID)).
then().
statusCode(HttpStatus.SC_BAD_REQUEST);
}
@Test
public void shouldHaveAHyperlinksToSeasonDivisionAndTeam() {
whenCreate(SEASON_URL, withSeason(SEASON_NUMBER));
String newDivisionId = givenADivisionWithName(DIVISION1_NAME);
newDivisionIds.add(newDivisionId);
String newTeamId = givenATeamWithName(TEAM1_NAME);
newTeamIds.add(newTeamId);
givenASeasonDivisionWith(SEASON_NUMBER, newDivisionId, "1");
givenASeasonDivisionTeamWith(SEASON_NUMBER, newDivisionId, newTeamId);
String seasonDivisionHyperlink = host + ":" + port + basePath +
SEASON_DIVISION_TEAM_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeamId + "/seasonDivision";
String teamHyperlink = host + ":" + port + basePath +
SEASON_DIVISION_TEAM_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeamId + "/team";
whenGet(SEASON_DIVISION_TEAM_URL + SEASON_NUMBER + ID_SEPARATOR + newDivisionId + ID_SEPARATOR + newTeamId).
then().
assertThat().
body("data.relationships.seasonDivision.links.related", equalTo(seasonDivisionHyperlink)).
body("data.relationships.team.links.related", equalTo(teamHyperlink));
}
}
<file_sep>/README.md
# FootballResultsApiIntegrationTests
To run the tests, ensure the API is running first
(ideally running against a test database)
```
mvn clean test
```
| 7e109f1999c7787ab9de4dd741e808e4305ca7e0 | [
"Markdown",
"Java",
"INI"
]
| 5 | Java | gibberfish/FootballResultsApiIntegrationTests | d2736b71b51ba3e58610ff75731176ed325df08f | e034c022feccab3b69fb3284eb3010da5a777022 |
refs/heads/master | <repo_name>abdulhaseeb036/Promise-in-js<file_sep>/app.js
// simple js run syscrounusy means line by line
// var a = "haseeb";
// console.log(a);
// var b = "hassan";
// console.log(b);
//>>> simple line 4 print a and then b;
//<<< now let loop between them loop print 1000 number b/w a & b
// var a = "haseeb";
// console.log(a);
// for (var i = 0; i <10; i++){
// console.log(i);
// }
// var b = "hassan";
// console.log(b);
//<<< now let loop between them loop print 1000 number b/w a & b
// >> other example
// var a = "haseeb";
// console.log(a);
// setTimeout(function(){
// for (var i = 0; i <10; i++){
// console.log(i);
// }
// },1000)
// var b = "hassan";
// console.log(b);
// <<<< other example
//>>>> Food order to chef example;
// var order1 = "order 1";
// console.log(order1);
// var first = function firstorder(){
// setTimeout(function(){
// console.log("waiter go to take a order 1 items")
// },5000);
// }
// var order2 = "order2";
// console.log(order2);
// var second = function secondorder(second){
// setTimeout(function(){
// console.log("waiter go to take a order 2 items")
// },1000);
// }
// function ordercomplete() {
// first()
// second()
// }
// ordercomplete();
// <<<< Food order to chef example;
//>>>>>>>>>>>>>>>>>> Promise
// const datafetch = () => {
// return (
// Math.floor(Math.random() *10) %2 == 0 ? true : false
// // this is example here kuch bhi data fetch aa rha hoga backend sy. API CALL
// )}
// const result = new Promise((resolve, reject) => {
// setTimeout(() => {
// datafetch() ? resolve() : reject();
// },1000)
// // API CALL K DATA RESOLVE YA REJECT THORA TIME LY GA ANY MA TU SETTIME LGAYA.
// })
// const resolvepromise = () => {
// console.log("success");
// }
// const rejectpromise = () => {
// console.log("failed to fetch data");
// }
// result.then(resolvepromise).catch(rejectpromise);
// console.log("haseeb");
// <<< THIS IS A BEST EXAMPLE OF PROMISE TO FATCHING DATA;
let url = 'www.fiverr.com';
async function response(){
await fetch(url);
}
let commits = await response.json(); // read response body and parse as JSON
alert(commits); | 410b9cc8ccc41f4151d05d359b5c5d27a9add8f9 | [
"JavaScript"
]
| 1 | JavaScript | abdulhaseeb036/Promise-in-js | c86524fc405a714c5ffdbf065f37bd059b5740a0 | d26daa84fbddda86b4ee7aea09e9e9672a5df516 |
refs/heads/master | <file_sep># liri-node-app
Input:
$ node liri.js
twitter:
? What would you like to do? my-tweets
spotify:
? What would you like to do? spotify-this-song
? Which song? dust in the wind
omdb:
? What would you like to do? movie-this
? Which movie? titanic
read:
? What would you like to do? do-what-it-says
<file_sep>require("dotenv").config();
var key = require("./key.js");
var request = require("request");
var inquirer = require ("inquirer");
var fs = require ("fs");
//Twitter------------------------
var Twitter = require("twitter");
var client = new Twitter(key.twitter);
var params = {screen_name: 'NaSeo6'};
//Spotify-------------------------
var Spotify = require("node-spotify-api");
var spotify = new Spotify(key.spotify);
//var songTitle = process.argv[2];
inquirer.prompt ([
{
type: "input",
name: "liriBot",
message: "What would you like to do?"
}
]).then(function(user){
if (user.liriBot === "my-tweets") {
client.get('statuses/user_timeline', params, function (error, tweets, response) {
if (!error) {
for (i = 0; i < tweets.length; i++) {
console.log(`Tweet : ${tweets[i].text}`);
console.log(`Created : ${tweets[i].created_at}`);
console.log("============================")
};
}
});
}
else if (user.liriBot === "spotify-this-song") {
inquirer.prompt([
{
type:"input",
name: "inputSong",
message: "Which song?"
}
]).then(function(user2){
var songTitle = "'"+user2.inputSong+"'";
spotify.search({ type: 'track', query: songTitle, limit: 1 }, function (err, data) {
if (err) {
return console.log('Error occurred: ' + err);
}
console.log("Artist: "+ JSON.stringify(data.tracks.items[0].album.artists[0].name, null, 2));
console.log("Song Link: "+ JSON.stringify(data.tracks.items[0].external_urls.spotify, null, 2));
});
})
}
else if (user.liriBot === "movie-this") {
inquirer.prompt([
{
type:"input",
name: "inputMovie",
message: "Which movie?"
}
]).then(function(user3){
//Omdb------------------------------------------
var nodeArgs = process.argv;
var movieName = "'"+user3.inputMovie+"'";
for (var i = 2; i < nodeArgs.length; i++) {
if (i > 2 && i < nodeArgs.length) {
movieName = movieName + "+" + nodeArgs[i];
}
else {
movieName += nodeArgs[i];
}
}
var movieQueryUrl = "http://www.omdbapi.com/?t=" + movieName + "&y=&plot=short&apikey=trilogy";
request(movieQueryUrl, function(error, response, body){
if (!error && response.statusCode === 200) {
console.log("Title: " +JSON.parse(body).Title);
console.log("Release Year: " + JSON.parse(body).Year);
console.log("IMDB Ratings: " +JSON.parse(body).Ratings[0].Value);
console.log("Rotten Tomatoes Ratings: " +JSON.parse(body).Ratings[1].Value);
console.log("Country: " +JSON.parse(body).Country);
console.log("Language: " +JSON.parse(body).Language);
console.log("Plot: " +JSON.parse(body).Plot);
console.log("Actors: " +JSON.parse(body).Actors);
}})
})
}
else if (user.liriBot === "do-what-it-says") {
//read text-----------------------------------------
fs.readFile("random.txt", "utf8", function(error,data) {
if (error) {
return console.log(error);
}
var dataArr = data.split(",");
console.log(dataArr[1]);
spotify.search({ type: 'track', query: dataArr[1], limit: 1 }, function (err, data) {
if (err) {
return console.log('Error occurred: ' + err);
}
console.log("Artist: "+ JSON.stringify(data.tracks.items[0].album.artists[0].name, null, 2));
console.log("Song Link: "+ JSON.stringify(data.tracks.items[0].external_urls.spotify, null, 2));
});
})
}
})
| 2588d0cc8b29203511b32fcce6b6f7d9b89ba5e7 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | bananaseo/liri-node-app | 0667b4b982c3d1d64a1494022d1ef135503852c9 | 723e251b4aa8359f9c8f97f625c3a9cf9729d50b |
refs/heads/master | <file_sep>/*
* PartsBasedDetectorOnVideo
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: CSequentialFormatter.cpp
* Author: <NAME> <<EMAIL>>
* Created: May 23, 2014.
*/
#include "CSequentialFormatter.h"
#include "globalIncludes.h"
#include <boost/filesystem.hpp>
CSequentialFormatter::CSequentialFormatter(CGenericFrameProvider* _frameProv,
std::string _baseFolder,
std::string _outputFileFormat)
: CGenericFormatter(_frameProv)
, mBaseFolder(_baseFolder)
, mOutputFileFormat(_outputFileFormat)
{
LOG(INFO) << "CSequentialFormatter created:";
LOG(INFO) << "\tBase folder: " << mBaseFolder;
LOG(INFO) << "\tOutput file format: " << mOutputFileFormat;
boost::filesystem::path tmpPath(mBaseFolder);
tmpPath /= mOutputFileFormat;
mWholeTemplate = tmpPath.native();
}
std::string CSequentialFormatter::getFilename(){
char buffer[1000];
std::sprintf(buffer, mWholeTemplate.c_str(), (unsigned)mpFrameProv->getCurrentFrameNumber());
DLOG(INFO) << "Formatted filename: " << buffer;
return std::string(buffer);
}
<file_sep>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: FilterSize.cpp
* Author: <NAME> <<EMAIL>>
* Created: November 18, 2013
*/
#include "FilterSize.h"
#include "globalIncludes.h"
#include <algorithm>
FilterSize::FilterSize(cv::Size2f _maxSize )
: mMaxSize(_maxSize)
{
DLOG(INFO) << "Created FilterSize [" << mMaxSize.width << ", " << mMaxSize.height << "]";
}
void FilterSize::process(vectorCandidate& _candidates){
vectorCandidate tmpResult;
#ifndef NDEBUG
DLOG(INFO) << "Originaly " << _candidates.size() << " candidates";
cv::Rect minSize = cv::Rect(0,0,1000,1000);
#endif
for( Candidate& curCandidate : _candidates ){
cv::Rect rect = curCandidate.boundingBox();
#ifndef NDEBUG
if( rect.height < minSize.height )
minSize.height = rect.height;
if( rect.width < minSize.width )
minSize.width = rect.width;
#endif
if( rect.width > mMaxSize.width || rect.height > mMaxSize.height )
continue;
tmpResult.push_back(curCandidate);
}
#ifndef NDEBUG
DLOG(INFO) << "Minimum rect size is: " << minSize.width << ", " << minSize.height;
DLOG(INFO) << "Now " << tmpResult.size() << " candidates";
#endif
_candidates.clear();
std::copy(tmpResult.begin(), tmpResult.end(), std::back_inserter(_candidates));
}
<file_sep>/*
* PartsBasedDetectorOnVideo
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: CFolderFrameProvider.cpp
* Author: <NAME> <<EMAIL>>
* Created: May 22, 2014.
*/
#include "CFolderFrameProvider.h"
#include <boost/filesystem.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <algorithm>
#include "globalIncludes.h"
CFolderFrameProvider::CFolderFrameProvider(std::string _srcFolder)
: mSrcFolder(_srcFolder)
, mCurFrame(-1)
{
DLOG(INFO) << "CFolderFrameProvider created";
init();
}
void CFolderFrameProvider::init(){
DLOG(INFO) << "Initializing the CFolderFrameProvider";
namespace fs = boost::filesystem;
fs::path someDir(mSrcFolder);
fs::directory_iterator end_iter;
DLOG(INFO) << "Listing files";
if ( fs::exists(someDir) && fs::is_directory(someDir)) {
for( fs::directory_iterator dir_iter(someDir) ; dir_iter != end_iter ; ++dir_iter) {
if (fs::is_regular_file(dir_iter->status()) ) {
DLOG(INFO) << "Loading: " << dir_iter->path().native();
mVecFiles.push_back(dir_iter->path().native());
}
}
}
std::sort(mVecFiles.begin(), mVecFiles.end());
#ifndef NDEBUG
for( const std::string& curStr : mVecFiles ){
DLOG(INFO) << "Final order: " << curStr;
}
#endif
mPositionIter = mVecFiles.begin();
mCurFrame = 0;
}
double CFolderFrameProvider::getFrameCount(){
return mVecFiles.size();
}
double CFolderFrameProvider::getCurrentFrameNumber(){
return mCurFrame;
}
std::string CFolderFrameProvider::getCurrentFilename(){
return boost::filesystem::path(*mPositionIter).leaf().native();
}
CGenericFrameProvider& CFolderFrameProvider::operator>>(cv::Mat& _mat){
_mat = cv::imread(*mPositionIter);
mPositionIter++;
++mCurFrame;
}
<file_sep>#ifndef GLOBALINCLUDES_H
#define GLOBALINCLUDES_H
#include <glog/logging.h>
#endif // GLOBALINCLUDES_H
<file_sep>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: outputFormat.cpp
* Author: <NAME> <<EMAIL>>
* Created: November 6, 2013
*/
#include "outputFormat.h"
#include <iomanip>
enumFormatType gOutputFormat = FT_FULL_OUTPUT;
std::ostream& operator<<(std::ostream& _stream, const vectorCandidate& _vecCandidates){
// format [ frameNo, compNo, mixtureNo, score (.4f), comp1_x1 (.2f), comp1_y1, comp1_x2, comp1_y2 ...]
for( auto& c : _vecCandidates ){
switch(gOutputFormat){
case FT_FULL_OUTPUT:
_stream << "0, " << c.parts().size() << ", " << c.component() << ", "
<< std::setprecision(4) << c.score();
// sub-parts
_stream << std::setprecision(2);
for( const cv::Rect& r : c.parts() )
_stream << ", " << r.x << ", " << r.y << ", " << r.x+r.width << ", " << r.y+r.height;
_stream << std::endl;
break;
case FT_BBOX_BRIEF:
cv::Rect bBox = c.boundingBox();
_stream << "[ {" << c.component() << " = " << std::setprecision(4) << c.score() <<"}, " << bBox.x << ", " << bBox.y << ", " << bBox.x+bBox.width << ", " << bBox.y+bBox.height << "]" << std::endl;
}
}
}
<file_sep>/*
* PartsBasedDetectorOnVideo
*
*
* Huge chunks of code shamelessly taken from <NAME> demo for
* PartsBasedDetector.
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: main.cpp
* Author: <NAME> <<EMAIL>>
* Created: November 5, 2013
*/
#include "globalIncludes.h"
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <ncurses.h>
#include <vector>
#include <opencv2/highgui/highgui.hpp>
#include <PartsBasedDetector.hpp>
#include <Candidate.hpp>
#include <FileStorageModel.hpp>
#include "filters/GenericPreFilter.h"
#include "filters/GenericPostFilter.h"
#include "filters/FilterSize.h"
#include "filters/FilterNMS.h"
#include "filters/PreFilterBackgroundMask.h"
#include "dataprovider/CProviderFactory.h"
#include "output_format/CSequentialFormatter.h"
#include "output_format/CNameCopyFormatter.h"
#define WITH_MATLABIO
#ifdef WITH_MATLABIO
#include <MatlabIOModel.hpp>
#endif
#include "outputFormat.h"
#include "mirrorUtils.h"
using namespace cv;
using namespace std;
namespace po = boost::program_options;
void parseArguments( int _argc, char* _argv[], // input arguments
std::string* _modelFile, std::string* _outputFolder, std::string* _srcFilename, // output arguments
float* _nmsThreshold, bool* _optMirroring, bool* _optResume, vector<float>* _optSizeFilter,
std::string* _optMaskFilter, float* _optModelThresh, bool* _copyFilename);
#define OUTPUT_FILENAME_FORMAT "facedetect_frame%06d.txt"
#define DEFAULT_MIRRORING false
#define DEFAULT_RESUME false
#define DEFAULT_MODEL_THRESH -100.0f
#define DEFAULT_COPY_FILENAME false
#ifdef NDEBUG
void setupDisplay(const char* _model, const char* _srcFilename, const char* _outputFolder);
void updateDisplay(int _frame, float _perc, double _time);
#define FRAME_LIMIT frameCount
#else
void updateDisplayDebug(int _frame, float _perc, double _time);
void setupDisplayDebug(const char* _model, const char* _srcFilename, const char* _outputFolder);
#define FRAME_LIMIT 200
#endif
int main(int argc, char *argv[])
{
google::InitGoogleLogging(argv[0]);
DLOG(INFO) << "Execution started";
// process variables
float nmsThreshold = 0.0f;
float modelThreshold = DEFAULT_MODEL_THRESH;
bool optMirroring = DEFAULT_MIRRORING;
bool optResume = DEFAULT_RESUME;
bool optCopyFilename = DEFAULT_COPY_FILENAME;
string outputFolder = "";
string modelFile = "";
string srcFilename = "";
string maskFilterFile = "";
vector<float> sizeFilter;
// general variables
boost::scoped_ptr<Model> model;
parseArguments(argc, argv, &modelFile, &outputFolder, &srcFilename, &nmsThreshold, &optMirroring, &optResume, &sizeFilter,
&maskFilterFile, &modelThreshold, &optCopyFilename);
// determine the type of model to read
string ext = boost::filesystem::path(modelFile).extension().string();
if (ext.compare(".xml") == 0 || ext.compare(".yaml") == 0) {
model.reset(new FileStorageModel);
}
#ifdef WITH_MATLABIO
else if (ext.compare(".mat") == 0) {
model.reset(new MatlabIOModel);
}
#endif
else {
printf("Unsupported model format: %s\n", ext.c_str());
LOG(FATAL) << "Unsupported model format: " << ext.c_str();
exit(-2);
}
bool ok = model->deserialize(modelFile);
if (!ok) {
printf("Error deserializing file\n");
LOG(FATAL) << "Error deserializing file.";
exit(-3);
}
if( modelThreshold != DEFAULT_MODEL_THRESH ){
LOG(INFO) << "Setting model threshold to " << modelThreshold << ", instead of model default: " << model->thresh();
model->setThreshold(modelThreshold);
}
// create the PartsBasedDetector and distribute the model parameters
Mat_<float> depth; // we don't have one for the video, so it's just a dummy variable
PartsBasedDetector<float> pbd;
pbd.distributeModel(*model);
// load video sequence
CGenericFrameProvider* pFrameSrc = NULL;
try{
pFrameSrc = CProviderFactory::getProvider(srcFilename);
} catch(std::runtime_error& error){
LOG(FATAL) << "Error opening file: " << error.what();
printf("Could not open frame source");
endwin();
exit(-4);
}
double frameCount = pFrameSrc->getFrameCount();
double frameNo = pFrameSrc->getCurrentFrameNumber();
DLOG(INFO) << "Frame count: " << frameCount;
DLOG(INFO) << "Start frame no: " << frameNo;
// check output folder
CGenericFormatter* pOutputFormat = NULL;
if(optCopyFilename)
pOutputFormat = new CNameCopyFormatter(pFrameSrc, outputFolder);
else
pOutputFormat = new CSequentialFormatter(pFrameSrc, outputFolder);
// pre filters
std::vector<GenericPreFilter*> preFilters;
if( maskFilterFile.size() > 0 ){
preFilters.push_back( new PreFilterBackgroundMask(maskFilterFile) );
}
// post filters
std::vector<GenericPostFilter*> postFilters;
if( sizeFilter.size() > 0 )
postFilters.push_back(new FilterSize(Size2f(sizeFilter[0],sizeFilter[1])));
if( nmsThreshold != 0.0f )
postFilters.push_back(new FilterNMS(nmsThreshold));
// display initialzation
#ifdef NDEBUG
setupDisplay(modelFile.c_str(), srcFilename.c_str(), outputFolder.c_str()); // release
#else
setupDisplayDebug(modelFile.c_str(), srcFilename.c_str(), outputFolder.c_str()); // debug
#endif
// main loop
DLOG(INFO) << "main loop";
vectorCandidate candidates;
Mat curFrameIm;
string outputFilename;
clock_t timeElapsed = clock();
while(frameNo < FRAME_LIMIT){
DLOG(INFO) << "FrameNo " << frameNo;
#ifdef NDEBUG
updateDisplay(frameNo, ((float)frameNo/(float)frameCount*100.0f), (double) ( clock() - timeElapsed )/CLOCKS_PER_SEC );
#else
updateDisplayDebug(frameNo, ((float)frameNo/(float)frameCount*100.0f), (double) ( clock() - timeElapsed )/CLOCKS_PER_SEC );
#endif
timeElapsed = clock();
candidates.clear();
outputFilename = pOutputFormat->getFilename();
frameNo = pFrameSrc->getCurrentFrameNumber();
*pFrameSrc >> curFrameIm;
// check if already exists
if( optResume ){
if(boost::filesystem::exists(outputFilename))
continue;
}
// filter the image
for( GenericPreFilter*& curFilter : preFilters ){
curFilter->process(curFrameIm);
}
pbd.detect(curFrameIm, depth, candidates);
#ifndef NDEBUG
gOutputFormat = FT_BBOX_BRIEF;
#endif
DLOG(INFO) << "Found original: " << candidates;
if(optMirroring){
vectorCandidate mirroredCandidates;
flip(curFrameIm, curFrameIm, 1); // flip around y-axis
pbd.detect(curFrameIm, depth, mirroredCandidates);
DLOG(INFO) << "Found flipped: " << mirroredCandidates;
flipHorizontaly(mirroredCandidates, curFrameIm.size);
DLOG(INFO) << "After flipping: " << mirroredCandidates;
candidates.insert(candidates.end(), mirroredCandidates.begin(), mirroredCandidates.end());
}
// filter the results
for( GenericPostFilter*& curFilter : postFilters)
curFilter->process(candidates);
DLOG(INFO) << "Final all detections" << candidates;
// output
ofstream outFile(outputFilename);
#ifndef NDEBUG
gOutputFormat = FT_FULL_OUTPUT;
#endif
outFile << candidates;
// cleanup
outFile.close();
if(!curFrameIm.empty())
curFrameIm.release();
}
// cleanup
DLOG(INFO) << "Cleanup part";
DLOG(INFO) << "Execution finished";
endwin();
return 0;
}
/*
* Code based on examples from
* http://www.boost.org/doc/libs/1_46_0/doc/html/program_options/tutorial.html
*
*/
void parseArguments( int _argc, char* _argv[], // input arguments
std::string* _modelFile, std::string* _outputFolder, std::string* _srcFilename, // output arguments
float* _nmsThreshold, bool* _optMirroring, bool* _optResume, vector<float>* _optSizeFilter,
std::string* _optMaskFilter, float* _optModelThresh, bool* _copyFilename)
{
po::options_description opts("Program parameters");
opts.add_options()
("help,h","produce help message")
("model,m", po::value<string>(_modelFile), "Model file to use. xml, mat or jaml format")
("input,i", po::value<string>(_srcFilename),"Input, source for analysis (video/folder/image)")
("dir,d", po::value<string>(_outputFolder),"Output folder")
("resume,r", "Resume option [default: false]")
("nms,n", po::value<float>(_nmsThreshold)->default_value(0.0f), "NMS filter threshold, percentage in the range 0.0-1.0, default O.0")
("mirror", "Mirroring option - mirror the video image horizontally and process 2x (with corrections of the detections) [default: false]")
("size,s", po::value< vector<float> >(_optSizeFilter), "Size filter. Eliminate all instances bigger then [width],[height]" )
("filter,f", po::value<string>(_optMaskFilter), "Mask filter - binary image. White regions of the image are going to be analyzed.")
("thresh,t", po::value<float>(_optModelThresh)->default_value(DEFAULT_MODEL_THRESH), "Theshold of the model. Default value is whatever is used in the model file")
("copyFilename,c", "Copy the original filename to the output (with changed extension to .txt)");
po::variables_map vm;
po::store(po::parse_command_line(_argc, _argv, opts), vm);
po::notify(vm);
if( vm.count("help") ){
cout << opts << endl;
exit(0);
}
if( vm.count("model") == 0 ){
cout << "No model specified. Check --help for usage" << endl;
LOG(FATAL) << "No model specified.";
exit(-1);
}
if( vm.count("input") == 0 ){
cout << "No input specified. Check --help for usage" << endl;
LOG(FATAL) << "No input specified.";
exit(-2);
}
if( vm.count("dir") == 0 ){
cout << "No output folder specified. Check --help for usage" << endl;
LOG(FATAL) << "No output folder specified.";
exit(-3);
}
if( vm.count("size") > 0 ){
_optSizeFilter->clear();
*_optSizeFilter = vm["size"].as< vector< float >>();
}
*_optMirroring = (vm.count("mirror") > 0) ? true : false;
*_optResume = (vm.count("resume") > 0) ? true : false;
*_copyFilename = (vm.count("copyFilename") > 0) ? true : false;
LOG(INFO) << "Model file: " << *_modelFile;
LOG(INFO) << "Input path: " << *_srcFilename;
LOG(INFO) << "Output folder: " << *_outputFolder;
LOG(INFO) << "Mask filter file: " << *_optMaskFilter;
LOG(INFO) << "Resume option: " << (*_optResume ? "yes" : "no");
LOG(INFO) << "Mirror option: " << (*_optMirroring ? "yes" : "no");
if( *_optModelThresh == DEFAULT_MODEL_THRESH )
LOG(INFO) << "Model threshold: [model default]";
else
LOG(INFO) << "Model threshold: " << *_optModelThresh;
if( *_nmsThreshold == 0.0f )
LOG(INFO) << "NMS threshold: off";
else
LOG(INFO) << "NMS threshold:" << *_nmsThreshold ;
}
void setupDisplay(const char* _model, const char* _srcFilename, const char* _outputFolder){
initscr();
cbreak();
noecho();
int rows, cols;
getmaxyx(stdscr, rows, cols); // will use it later
attron(A_BOLD);
mvprintw(1, cols/2-19, "[[ PartsBasedDetector (onVideo) v1.0 ]]");
attroff(A_BOLD);
mvprintw(3, 3, "Model file: ");
mvprintw(3, 25, boost::filesystem::path(_model).filename().c_str());
mvprintw(4, 3, "Source: ");
mvprintw(4, 25, boost::filesystem::path(_srcFilename).filename().c_str());
mvprintw(5, 3, "Output folder: ");
mvprintw(5, 25, boost::filesystem::path(_outputFolder).leaf().c_str());
refresh();
}
void updateDisplay(int _frame, float _perc, double _time){
// update display with information
int rows, cols;
getmaxyx(stdscr, rows, cols); // will use it later
float runnerStep = 100.0f/((float)cols-40);
move(10, 5);
addch('[');
attron(A_BOLD);
float runner; int change = 0;
for(runner = 0; runner < _perc; runner+=runnerStep ){
switch( change % 4 ){
case 0:
addch('.');
break;
case 1:
addch('o');
break;
case 2:
addch('O');
break;
case 3:
addch('o');
break;
}
change++;
}
for(;runner < 100.0f; runner += runnerStep)
addch(' ');
attroff(A_BOLD);
printw("] %3.2f% [Frame #%d]", _perc, _frame);
move(11, cols/2 - 3);
printw("TPF: %2.2f sec", _time);
refresh();
}
/* Debug verions of output which are QtCreator friendly */
#ifndef NDEBUG
void setupDisplayDebug(const char* _model, const char* _srcFilename, const char* _outputFolder){
DLOG(INFO) << "Model file: " << _model;
cout << "Model file: " << _model << endl;
DLOG(INFO) << "Source: " << _srcFilename;
cout << "Source: " << _srcFilename << endl;
DLOG(INFO) << "Output folder: " << _outputFolder;
cout << "Output folder: " << _outputFolder << endl;
}
void updateDisplayDebug(int _frame, float _perc, double _time){
DLOG(INFO) << "Frame no: " << _frame << "[" << _perc << "%] in TPF: " << _time;
}
#endif
<file_sep>/*
* PartsBasedDetectorOnVideo
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: CVideoFrameProvider.h
* Author: <NAME> <<EMAIL>>
* Created: May 22, 2014.
*/
#include "CVideoFrameProvider.h"
#include <exception>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include "globalIncludes.h"
CVideoFrameProvider::CVideoFrameProvider(std::string _srcFilename)
: mSrcFilename(_srcFilename)
, mVideoSrc(_srcFilename)
, mInitiated(false)
{
DLOG(INFO) << "CVideoFrameProvider instanced";
LOG(INFO) << "Src file: " << _srcFilename;
if(mVideoSrc.isOpened()){
mInitiated = true;
} else {
LOG(ERROR) << "Could not open file: " << _srcFilename;
throw std::runtime_error("Could not find file: " + _srcFilename);
}
}
double CVideoFrameProvider::getFrameCount(){
if(!mInitiated)
return -1;
return mVideoSrc.get(CV_CAP_PROP_FRAME_COUNT);
}
double CVideoFrameProvider::getCurrentFrameNumber(){
if(!mInitiated)
return -1;
return mVideoSrc.get(CV_CAP_PROP_POS_FRAMES);
}
CGenericFrameProvider& CVideoFrameProvider::operator>>(cv::Mat& _mat){
if(mInitiated)
mVideoSrc >> _mat;
}
CVideoFrameProvider::~CVideoFrameProvider(){
if(mInitiated)
mVideoSrc.release();
}
std::string CVideoFrameProvider::getCurrentFilename(){
return boost::filesystem::path(mSrcFilename).filename().native();
}
<file_sep>/*
* PartsBasedDetectorOnVideo
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: FilterNMS.cpp
* Author: <NAME> <<EMAIL>>
* Created: November 26, 2013
*/
#include "FilterNMS.h"
#include <opencv2/core/core.hpp>
#include <exception>
#include <list>
#include <algorithm>
#include <utility>
#include <string>
#include <stdio.h>
#include "globalIncludes.h"
typedef std::pair<float, int> tOrderPair;
bool compareSortOrder(const tOrderPair& _l, const tOrderPair& _r);
void calculateOverlapMatrix( vectorCandidate& _candidates, cv::Mat & _overlapMat );
float calcOverlap(const cv::Rect _r1, const cv::Rect _r2);
std::string rect2str(const cv::Rect _r);
FilterNMS::FilterNMS(float _overlap)
: mOverlap(_overlap)
{
if(mOverlap > 1.0f)
mOverlap /= 100.0f;
DLOG(INFO) << "Created NMS filter for overlap greater then " << _overlap*100.0 << " %";
}
/*
Sorting trick found here
http://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes
*/
void FilterNMS::process(vectorCandidate& _candidates){
// sort all candidates in descending order based on the result
vectorCandidate orderedCandidates;
{
std::list<Candidate> orderedCandidatesList; // just to control the memory consumption a bit. The result ends in orderedCandidates
std::vector<tOrderPair> resortBuffer; // <score, original_index>
int idx = 0;
for( const Candidate& cand : _candidates )
resortBuffer.push_back( tOrderPair(cand.score(), idx++) );
std::sort(resortBuffer.begin(), resortBuffer.end(), compareSortOrder);
for( const tOrderPair& elem : resortBuffer )
orderedCandidatesList.push_back( _candidates.at(elem.second) );
std::copy(orderedCandidatesList.begin(), orderedCandidatesList.end(), std::back_inserter(orderedCandidates));
}
// create overlap matrix
cv::Mat overlapMat = cv::Mat::zeros(orderedCandidates.size(), orderedCandidates.size(), CV_32FC1);
calculateOverlapMatrix(orderedCandidates, overlapMat);
// interate and insert only the top-scoring
std::list<Candidate> outputResults;
{
for(int idx = 0; idx < orderedCandidates.size(); ++idx){
cv::Mat curRow = overlapMat.row(idx);
DLOG(INFO) << "Cur row:";
DLOG(INFO) << curRow;
cv::Mat boolSelection = curRow > mOverlap; // this is outputing 255 instead of "1" for true conditions. Not really a problem, but weird
DLOG(INFO) << "Cur binary selection";
DLOG(INFO) << boolSelection;
if( cv::sum(boolSelection).val[0] == 0 )
outputResults.push_back(orderedCandidates[idx]);
}
}
// re-insert the top-scoring candidates in the output vector
_candidates.clear();
std::copy(outputResults.begin(), outputResults.end(), std::back_inserter(_candidates));
}
// made for descending sort
bool compareSortOrder(const tOrderPair& _l, const tOrderPair& _r){
return _l.first > _r.first;
}
/*
* Important to note that the overlapMat encodes the information
* overlap.at<float>(x,y) = (x & y)/x;
* The matrix will be 0.0 for any idx <= of the current outer idx
*/
void calculateOverlapMatrix( vectorCandidate& _candidates, cv::Mat &_overlapMat ){
int outerIdx = 0;
for( const Candidate& _outerC : _candidates ){
int innerIdx = 0;
for( const Candidate& _innerC : _candidates ){
if(innerIdx >= outerIdx){
break;
}
_overlapMat.at<float>(outerIdx, innerIdx) = calcOverlap(_outerC.boundingBox(), _innerC.boundingBox());
++innerIdx;
}
++outerIdx;
}
DLOG(INFO) << "Overlap matrix: " << _overlapMat;
}
/*
* Overlap percentage from the "viewpoint" of the first rectangle.
* (meaning, the intersection coverage area is devided by the area of the
* of the first rectangle.
*/
float calcOverlap(const cv::Rect _r1, const cv::Rect _r2){
DLOG(INFO) << "Overlap between " << rect2str(_r1) << " and " << rect2str(_r2);
cv::Rect intersection = _r1 & _r2;
DLOG(INFO) << " is " << rect2str(intersection);
float overlapPct = (float)intersection.area()/(float)_r1.area();
DLOG(INFO) << " in the pct of the first rect: " << overlapPct;
return overlapPct;
}
std::string rect2str(const cv::Rect _r){
char buffer[100];
sprintf(buffer, "[%d, %d, %d, %d]", _r.x, _r.y, _r.width, _r.height);
return std::string(buffer);
}
<file_sep>/*
* PartsBasedDetectorOnVideo
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: CNameCopyFormatter.cpp
* Author: <NAME> <<EMAIL>>
* Created: May 23, 2014.
*/
#include "CNameCopyFormatter.h"
#include <boost/filesystem.hpp>
#include "globalIncludes.h"
using namespace boost::filesystem;
CNameCopyFormatter::CNameCopyFormatter(CGenericFrameProvider* _frameProv,
std::string _baseFolder,
std::string _alternativeExtension)
: CGenericFormatter(_frameProv)
, mBaseFolder(_baseFolder)
, mAlternativeExtension(_alternativeExtension)
{
LOG(INFO) << "CNameCopyFormatter created:";
LOG(INFO) << "\tBase folder: " << mBaseFolder;
LOG(INFO) << "\tAlternative extension: " << mAlternativeExtension;
}
std::string CNameCopyFormatter::getFilename(){
path curFilename(mpFrameProv->getCurrentFilename());
path justFile = curFilename.leaf();
justFile.replace_extension(mAlternativeExtension);
path curPath(mBaseFolder);
curPath /= justFile;
DLOG(INFO) << "New filename: " << curPath;
return curPath.native();
}
<file_sep>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Chili lab, EPFL.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Chili, EPFL nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* File: PreFilterBackgroundMask.cpp
* Author: <NAME> <<EMAIL>>
* Created: December 06, 2013
*/
#include "PreFilterBackgroundMask.h"
#include "globalIncludes.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <string>
using namespace cv;
PreFilterBackgroundMask::PreFilterBackgroundMask(){
DLOG(INFO) << "Created PreFilterBackgroundSub";
}
PreFilterBackgroundMask::PreFilterBackgroundMask(std::string _maskFilename){
DLOG(INFO) << "Created PreFilterBackgroundSub with maskFile" << _maskFilename;
init(_maskFilename);
}
void PreFilterBackgroundMask::init(std::string _maskFilename){
mFilterMask = imread(_maskFilename);
mFilterMask = mFilterMask / 255.0f;
}
void PreFilterBackgroundMask::process(cv::Mat& _frame){
if( _frame.rows != mFilterMask.rows || _frame.cols != mFilterMask.cols ){
LOG(ERROR) << "Filter and image sizes don't match! frame: [" << _frame.cols << ", " << _frame.rows << "] filter"
<< mFilterMask.cols << ", " << mFilterMask.rows << "]";
return;
}
_frame = _frame.mul(mFilterMask);
}
<file_sep>PartsBasedDetectorOnVideo
=========================
Just serial processing of video with PartsBasedDetector.
Model creation
--------------
I had a bit of a problem figuring out this part, so here goes the recipe:
1. Train your part-based model in matlab (code available from Ramanan's site)
2. Convert it to 'Pose' format with PartBasedDetector/matlab/modelTransfer.m
3. use ModelTransfer executable in PartBasedDetector to transform it from .mat -> .xml format
4. enjoy using the PartBasedDetectorOnVideo which can now accept your trained model
Command line options
--------------------
```
Program parameters:
-h [ --help ] produce help message
-m [ --model ] arg Model file to use. xml, mat or jaml format
-i [ --input ] arg Input, source for analysis (video/folder)
-d [ --dir ] arg Output folder
-r [ --resume ] Resume option [default: false]
-n [ --nms ] arg (=0) NMS filter threshold, percentage in the range 0.0-1.0,
default O.0
--mirror Mirroring option - mirror the video image horizontally
and process 2x (with corrections of the detections)
[default: false]
-s [ --size ] arg Size filter. Eliminate all instances bigger then
[width],[height]
-f [ --filter ] arg Mask filter - binary image. White regions of the image
are going to be analyzed.
-c [ --copyFilename ] Copy the original filename to the output (with changed
extension to .txt)
```
Referenced code
---------------
Project uses the code developed by hbristow (cvmatio and PartsBasedDetector), based on the research of Deva Ramanan and friends.
Used libraries
--------------
* PartsBasedDetector (available on github as my or hbristow repository)
* OpenCV 2.4.6 (latest at the moment)
* glog - google logging library
* Boost::filesystem, system, program options
* ncurses - for a nicer progress report
Contact
-------
<EMAIL>
| 98dec71e5abd9f33f4966f2f94784828b81d29a0 | [
"Markdown",
"C",
"C++"
]
| 11 | C++ | caomw/PartsBasedDetectorOnVideo | 0d19a662a2b705ca7854de45685b3a1b2d66d970 | b3c0c2486a83afc0b7be87d1adbd3b4385620e49 |
refs/heads/master | <file_sep># Gesture-based-Remote-Controlled-Smart-Wheel-Chair
# PROBLEM BEING ADDRESSED
The wheelchairs are usually controlled by a joystick attached to it. It is not possible to control the wheelchair remotely. It is not possible to provide maneuvering assistance if need be. We plan to implement remote maneuvering assistance.
# SOLUTION
- Blue Gecko is used as a low power node which is interfaced with a gesture sensor.
- When a gesture is detected Low Power Node communicates with the Friend Node.
- Depending upon the gesture the Friend Node moves the wheelchair.
- We plan to overcome range limitation by using Mesh Relays.
- If the wheelchair is out of range of the Remote, the Remote(LPN) communicates with the nearest Friend Node which relays the message to the Wheelchair(Friend) the Remote wishes to control.
- Central Device can be used to change the gesture parameters of LPN node and also the speed of the Wheelchair.
# FUNTCTIONAL BLOCK DIAGRAM

# FLOWCHARTS


# MODULES IMPLEMENTED
## Mesh Provisioning
- OOB Authentication is used where a OTP is displayed on LCD and user is asked to enter it.
## Gesture based Remote Control
- This a Low Power Node with Client Model.
- Low Power Node responsible to send changes in a state to Friend Node.
- Generic Level State Server Model
## Services Implemented
- Service 1 : Level States- Left, Right, Forward, Backward
- Service 2 : Level States - Motor Speed, Motor On/Off.
# PROJECT ACHIEVEMENTS
- Minimized power usage to microamperes by incorporating low power nodes for communication.
- Improved security by implementing Man In Middle protection scheme using Out of Band Authentication
- Enhanced reliability and range of Mesh by implementing features like Mesh Hopping and Persistent data.
- Achieved safety by designing automatic break system in wheelchair on obstacle detection.
<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
USER_OBJS := F:/MS\ Embedded\ Systems/IOT/Practicals/BT\ Mesh/Central_Device/protocol/bluetooth/lib/EFR32XG13X/GCC/libcoex.a F:/MS\ Embedded\ Systems/IOT/Practicals/BT\ Mesh/Central_Device/protocol/bluetooth/lib/EFR32XG13X/GCC/binapploader.o F:/MS\ Embedded\ Systems/IOT/Practicals/BT\ Mesh/Central_Device/protocol/bluetooth/lib/EFR32XG13X/GCC/libbluetooth_mesh.a
LIBS := -lm
<file_sep>//***********************************************************************************
// Include files
//***********************************************************************************
//***********************************************************************************
// defined files
//***********************************************************************************
#define SCL_locReg 14 // SCL location register
#define SDA_locReg 16 // SDA location Register
#define SCL_Route_LOC_shift 8 // (13:8 in RouteLOC0)
#define SDA_Route_LOC_shift 0 //
//***********************************************************************************
// global variables
//***********************************************************************************
//***********************************************************************************
// function prototypes
//***********************************************************************************
void I2C_setup(void);
void I2C_Start();
void I2C_Stop();
void I2C_Send_NACK();
void I2C_Send_ACK(void);
void I2C_Write_Byte(unsigned char data);
unsigned char I2C_Read_Byte(void);
unsigned char I2C_Read2Bytes(void);
<file_sep>################################################################################
# Automatically-generated file. Do not edit!
################################################################################
USER_OBJS := C:/Users/Madhumitha/SimplicityStudio/v4_workspace1/WheelchairModule/protocol/bluetooth/lib/EFR32XG13X/GCC/binapploader.o C:/Users/Madhumitha/SimplicityStudio/v4_workspace1/WheelchairModule/protocol/bluetooth/lib/EFR32XG13X/GCC/libcoex.a C:/Users/Madhumitha/SimplicityStudio/v4_workspace1/WheelchairModule/protocol/bluetooth/lib/EFR32XG13X/GCC/libbluetooth_mesh.a
LIBS := -lm
<file_sep>
#include "src/APDS9960.h"
#include "src/I2C.h"
void DelayMs(unsigned int Ms)
{
int delay_cnst;
while (Ms > 0)
{
Ms--;
for (delay_cnst = 0; delay_cnst < 1600; delay_cnst++);
}
}
/*Configures I2C communications and initializes registers to defaults*/
bool initialize()
{
unsigned char id=0;
/* Initialize I2C */
I2C_setup();
/* Read ID register and check against known values for APDS-9960 */
id = wireReadDataByte(APDS9960_ID);
if( !(id == APDS9960_ID_1 ||id == APDS9960_ID_2 ) )
{
return 0;
}
/* Set ENABLE register to 0 (disable all features) */
setMode(ALL, OFF);
/* Set default values for ambient light and proximity registers */
wireWriteDataByte(APDS9960_ATIME, DEFAULT_ATIME);
wireWriteDataByte(APDS9960_WTIME, DEFAULT_WTIME);
wireWriteDataByte(APDS9960_PPULSE, DEFAULT_PROX_PPULSE);
wireWriteDataByte(APDS9960_POFFSET_UR, DEFAULT_POFFSET_UR) ;
wireWriteDataByte(APDS9960_POFFSET_DL, DEFAULT_POFFSET_DL) ;
wireWriteDataByte(APDS9960_CONFIG1, DEFAULT_CONFIG1) ;
setLEDDrive(DEFAULT_LDRIVE);
setProximityGain(DEFAULT_PGAIN);
setAmbientLightGain(DEFAULT_AGAIN);
if( !setProxIntLowThresh(DEFAULT_PILT) ) {
return false;
}
if( !setProxIntHighThresh(DEFAULT_PIHT) ) {
return false;
}
if( !setLightIntLowThreshold(DEFAULT_AILT) ) {
return false;
}
if( !setLightIntHighThreshold(DEFAULT_AIHT) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_PERS, DEFAULT_PERS) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_CONFIG2, DEFAULT_CONFIG2) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_CONFIG3, DEFAULT_CONFIG3) ) {
return false;
}
/* Set default values for gesture sense registers */
if( !setGestureEnterThresh(DEFAULT_GPENTH) ) {
return false;
}
if( !setGestureExitThresh(DEFAULT_GEXTH) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GCONF1, DEFAULT_GCONF1) ) {
return false;
}
if( !setGestureGain(DEFAULT_GGAIN) ) {
return false;
}
if( !setGestureLEDDrive(DEFAULT_GLDRIVE) ) {
return false;
}
if( !setGestureWaitTime(DEFAULT_GWTIME) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GOFFSET_U, DEFAULT_GOFFSET) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GOFFSET_D, DEFAULT_GOFFSET) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GOFFSET_L, DEFAULT_GOFFSET) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GOFFSET_R, DEFAULT_GOFFSET) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GPULSE, DEFAULT_GPULSE) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_GCONF3, DEFAULT_GCONF3) ) {
return false;
}
if( !setGestureIntEnable(DEFAULT_GIEN) ) {
return false;
}
return true;
}
/*Enables or disables a feature in the APDS-9960*/
bool setMode(uint8_t mode, uint8_t enable)
{
uint8_t reg_val;
/* Read current ENABLE register */
reg_val = getMode();
if( reg_val == ERROR ) {
return false;
}
/* Change bit(s) in ENABLE register */
enable = enable & 0x01;
if( mode >= 0 && mode <= 6 ) {
if (enable) {
reg_val |= (1 << mode);
} else {
reg_val &= ~(1 << mode);
}
} else if( mode == ALL ) {
if (enable) {
reg_val = 0x7F;
} else {
reg_val = 0x00;
}
}
/* Write value back to ENABLE register */
if( !wireWriteDataByte(APDS9960_ENABLE, reg_val) ) {
return false;
}
return true;
}
/*Reads and returns the contents of the ENABLE register*/
uint8_t getMode()
{
uint8_t enable_value;
/* Read current ENABLE register */
enable_value = wireReadDataByte(APDS9960_ENABLE);
return enable_value;
}
/*Sets the LED drive strength for proximity and ambient light sensor (ALS)*/
bool setLEDDrive(uint8_t drive)
{
uint8_t val;
/* Read value from CONTROL register */
val=wireReadDataByte(APDS9960_CONTROL);
/* Set bits in register to given value */
drive &= 0b00000011;
drive = drive << 6;
val &= 0b00111111;
val |= drive;
/* Write register value back into CONTROL register */
if( !wireWriteDataByte(APDS9960_CONTROL, val) ) {
return false;
}
return true;
}
/*Sets the receiver gain for proximity detection*/
bool setProximityGain(uint8_t drive)
{
uint8_t val;
/* Read value from CONTROL register */
val=wireReadDataByte(APDS9960_CONTROL);
/* Set bits in register to given value */
drive &= 0b00000011;
drive = drive << 2;
val &= 0b11110011;
val |= drive;
/* Write register value back into CONTROL register */
if( !wireWriteDataByte(APDS9960_CONTROL, val) ) {
return false;
}
return true;
}
/*Sets the receiver gain for the ambient light sensor (ALS)*/
bool setAmbientLightGain(uint8_t drive)
{
uint8_t val;
/* Read value from CONTROL register */
val= wireReadDataByte(APDS9960_CONTROL);
/* Set bits in register to given value */
drive &= 0b00000011;
val &= 0b11111100;
val |= drive;
/* Write register value back into CONTROL register */
if( !wireWriteDataByte(APDS9960_CONTROL, val) ) {
return false;
}
return true;
}
/*Sets the lower threshold for proximity detection*/
bool setProxIntLowThresh(uint8_t threshold)
{
if( !wireWriteDataByte(APDS9960_PILT, threshold) ) {
return false;
}
return true;
}
/*Sets the high threshold for proximity detection*/
bool setProxIntHighThresh(uint8_t threshold)
{
if( !wireWriteDataByte(APDS9960_PIHT, threshold) ) {
return false;
}
return true;
}
/*Sets the low threshold for ambient light interrupts*/
bool setLightIntLowThreshold(uint16_t threshold)
{
uint8_t val_low;
uint8_t val_high;
/* Break 16-bit threshold into 2 8-bit values */
val_low = threshold & 0x00FF;
val_high = (threshold & 0xFF00) >> 8;
/* Write low byte */
if( !wireWriteDataByte(APDS9960_AILTL, val_low) ) {
return false;
}
/* Write high byte */
if( !wireWriteDataByte(APDS9960_AILTH, val_high) ) {
return false;
}
return true;
}
/*Sets the high threshold for ambient light interrupts*/
bool setLightIntHighThreshold(uint16_t threshold)
{
uint8_t val_low;
uint8_t val_high;
/* Break 16-bit threshold into 2 8-bit values */
val_low = threshold & 0x00FF;
val_high = (threshold & 0xFF00) >> 8;
/* Write low byte */
if( !wireWriteDataByte(APDS9960_AIHTL, val_low) ) {
return false;
}
/* Write high byte */
if( !wireWriteDataByte(APDS9960_AIHTH, val_high) ) {
return false;
}
return true;
}
/*Sets the entry proximity threshold for gesture sensing*/
bool setGestureEnterThresh(uint8_t threshold)
{
if( !wireWriteDataByte(APDS9960_GPENTH, threshold) ) {
return false;
}
return true;
}
/*Sets the exit proximity threshold for gesture sensing*/
bool setGestureExitThresh(uint8_t threshold)
{
if( !wireWriteDataByte(APDS9960_GEXTH, threshold) ) {
return false;
}
return true;
}
/*Sets the gain of the photodiode during gesture mode*/
bool setGestureGain(uint8_t gain)
{
uint8_t val;
/* Read value from GCONF2 register */
val = wireReadDataByte(APDS9960_GCONF2);
/* Set bits in register to given value */
gain &= 0b00000011;
gain = gain << 5;
val &= 0b10011111;
val |= gain;
/* Write register value back into GCONF2 register */
if( !wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}
return true;
}
/*Sets the LED drive current during gesture mode*/
bool setGestureLEDDrive(uint8_t drive)
{
uint8_t val;
/* Read value from GCONF2 register */
val = wireReadDataByte(APDS9960_GCONF2);
/* Set bits in register to given value */
drive &= 0b00000011;
drive = drive << 3;
val &= 0b11100111;
val |= drive;
/* Write register value back into GCONF2 register */
if( !wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}
return true;
}
/*Sets the time in low power mode between gesture detections*/
bool setGestureWaitTime(uint8_t time)
{
uint8_t val;
/* Read value from GCONF2 register */
val = wireReadDataByte(APDS9960_GCONF2);
/* Set bits in register to given value */
time &= 0b00000111;
val &= 0b11111000;
val |= time;
/* Write register value back into GCONF2 register */
if( !wireWriteDataByte(APDS9960_GCONF2, val) ) {
return false;
}
return true;
}
/* Turns gesture-related interrupts on or off*/
bool setGestureIntEnable(uint8_t enable)
{
uint8_t val;
/* Read value from GCONF4 register */
val = wireReadDataByte(APDS9960_GCONF4);
/* Set bits in register to given value */
enable &= 0b00000001;
enable = enable << 1;
val &= 0b11111101;
val |= enable;
/* Write register value back into GCONF4 register */
if( !wireWriteDataByte(APDS9960_GCONF4, val) ) {
return false;
}
return true;
}
/*Starts the gesture recognition engine on the APDS-9960*/
bool enableGestureSensor ( bool interrupts)
{
/* Enable gesture mode
Set ENABLE to 0 (power off)
Set WTIME to 0xFF
Set AUX to LED_BOOST_300
Enable PON, WEN, PEN, GEN in ENABLE
*/
resetGestureParameters();
if( !wireWriteDataByte(APDS9960_WTIME, 0xFF) ) {
return false;
}
if( !wireWriteDataByte(APDS9960_PPULSE, DEFAULT_GESTURE_PPULSE) ) {
return false;
}
if( !setLEDBoost(LED_BOOST_300) ) {
return false;
}
if( interrupts )
{
if( !setGestureIntEnable(1) ) {
return false;
}
}
else {
if( !setGestureIntEnable(0) ) {
return false;
}
}
if( !setGestureMode(1) ) {
return false;
}
if( !enablePower() ){
return false;
}
if( !setMode(WAIT, 1) ) {
return false;
}
if( !setMode(PROXIMITY, 1) ) {
return false;
}
if( !setMode(GESTURE, 1) ) {
return false;
}
return true;
}
/*Resets all the parameters in the gesture data member*/
void resetGestureParameters()
{
gesture_data_.index = 0;
gesture_data_.total_gestures = 0;
gesture_ud_delta_ = 0;
gesture_lr_delta_ = 0;
gesture_ud_count_ = 0;
gesture_lr_count_ = 0;
gesture_near_count_ = 0;
gesture_far_count_ = 0;
gesture_state_ = 0;
gesture_motion_ = DIR_NONE;
}
/*Sets the LED current boost value
*
* Value Boost Current
* 0 100%
* 1 150%
* 2 200%
* 3 300%
*/
bool setLEDBoost(uint8_t boost)
{
uint8_t val;
/* Read value from CONFIG2 register */
val=wireReadDataByte(APDS9960_CONFIG2);
/* Set bits in register to given value */
boost &= 0b00000011;
boost = boost << 4;
val &= 0b11001111;
val |= boost;
/* Write register value back into CONFIG2 register */
if( !wireWriteDataByte(APDS9960_CONFIG2, val) ) {
return false;
}
return true;
}
/*Tells the state machine to either enter or exit gesture state machine*/
bool setGestureMode(uint8_t mode)
{
uint8_t val;
/* Read value from GCONF4 register */
val = wireReadDataByte(APDS9960_GCONF4);
/* Set bits in register to given value */
mode &= 0b00000001;
val &= 0b11111110;
val |= mode;
/* Write register value back into GCONF4 register */
if( !wireWriteDataByte(APDS9960_GCONF4, val) ) {
return false;
}
return true;
}
/*Turn the APDS-9960 on*/
bool enablePower()
{
if( !setMode(POWER, 1) ) {
return false;
}
return true;
}
/*Determines if there is a gesture available for reading*/
bool isGestureAvailable()
{
uint8_t val;
/* Read value from GSTATUS register */
val=wireReadDataByte(APDS9960_GSTATUS);
/* Shift and mask out GVALID bit */
val &= APDS9960_GVALID;
/* Return true/false based on GVALID bit */
if( val == 1) {
return true;
} else {
return false;
}
}
/*Processes a gesture event and returns best guessed gesture*/
int readGesture(uint16_t thresold, uint16_t sensetivity_1)
{
uint8_t fifo_level = 0;
int bytes_read = 0;
uint8_t fifo_data[128];
// uint8_t fifo_data[64];
uint8_t gstatus;
int motion;
int i;
/* Make sure that power and gesture is on and data is valid */
if( !isGestureAvailable() || !(getMode() & 0b01000001) )
{
return DIR_NONE;
}
/* Keep looping as long as gesture data is valid */
while(1)
{
/* Wait some time to collect next batch of FIFO data */
DelayMs(FIFO_PAUSE_TIME);
/* Get the contents of the STATUS register. Is data still valid? */
gstatus = wireReadDataByte(APDS9960_GSTATUS);
/* If we have valid data, read in FIFO */
if( (gstatus & APDS9960_GVALID) == APDS9960_GVALID )
{
/* Read the current FIFO level */
fifo_level= wireReadDataByte(APDS9960_GFLVL);
// printf("Fifo level is %d\n",fifo_level);
/* If there's stuff in the FIFO, read it into our data block */
if( fifo_level > 0)
{
bytes_read = wireReadDataBlock( APDS9960_GFIFO_U,
(uint8_t*)fifo_data,
(fifo_level * 4) );
// printf("Byte_read = %d\n",bytes_read);
if( bytes_read == -1 )
{
return ERROR;
}
// for ( i = 0; i < bytes_read; i++ )
// {
// printf("%d Element of fifa_data is %d\n",i,fifo_data[i]);
// }
/* If at least 1 set of data, sort the data into U/D/L/R */
if( bytes_read >= 4 )
{
for( i = 0; i < bytes_read; i += 4 )
{
gesture_data_.u_data[gesture_data_.index] = \
fifo_data[i + 0];
gesture_data_.d_data[gesture_data_.index] = \
fifo_data[i + 1];
gesture_data_.l_data[gesture_data_.index] = \
fifo_data[i + 2];
gesture_data_.r_data[gesture_data_.index] = \
fifo_data[i + 3];
gesture_data_.index++;
gesture_data_.total_gestures++;
}
printf("NO of Gestures is %d\n",gesture_data_.total_gestures);
for(int k =0 ; k< 16; k++)
{
// printf("UData is %d\n",gesture_data_.u_data[k]);
// printf("LData is %d\n",gesture_data_.d_data[k]);
// printf("LData is %d\n",gesture_data_.l_data[k]);
// printf("RData is %d\n",gesture_data_.r_data[k]);
}
/* Filter and process gesture data. Decode near/far state */
if(processGestureData(thresold,sensetivity_1))
{
if(decodeGesture())
{
}
/* Reset data */
}
gesture_data_.index = 0;
gesture_data_.total_gestures = 0;
}
}
}
else
{
/* Determine best guessed gesture and clean up */
DelayMs(FIFO_PAUSE_TIME);
decodeGesture();
motion = gesture_motion_;
resetGestureParameters();
return motion;
}
}
}
/*Processes the raw gesture data to determine swipe direction*/
bool processGestureData( uint16_t thresold, uint16_t sensetivity_1)
{
uint8_t u_first = 0;
uint8_t d_first = 0;
uint8_t l_first = 0;
uint8_t r_first = 0;
uint8_t u_last = 0;
uint8_t d_last = 0;
uint8_t l_last = 0;
uint8_t r_last = 0;
int ud_ratio_first;
int lr_ratio_first;
int ud_ratio_last;
int lr_ratio_last;
int ud_delta;
int lr_delta;
int i;
/* If we have less than 4 total gestures, that's not enough */
if( gesture_data_.total_gestures <= 4 ) {
return false;
}
/* Check to make sure our data isn't out of bounds */
if( (gesture_data_.total_gestures <= 32) && \
(gesture_data_.total_gestures > 0) )
{
/* Find the first value in U/D/L/R above the threshold */
for( i = 0; i < gesture_data_.total_gestures; i++ )
{
if( (gesture_data_.u_data[i] > thresold) &&
(gesture_data_.d_data[i] > thresold) &&
(gesture_data_.l_data[i] > thresold) &&
(gesture_data_.r_data[i] > thresold) )
{
u_first = gesture_data_.u_data[i];
d_first = gesture_data_.d_data[i];
l_first = gesture_data_.l_data[i];
r_first = gesture_data_.r_data[i];
break;
}
}
/* If one of the _first values is 0, then there is no good data */
if( (u_first == 0) || (d_first == 0) || \
(l_first == 0) || (r_first == 0) ) {
return false;
}
/* Find the last value in U/D/L/R above the threshold */
for( i = gesture_data_.total_gestures - 1; i >= 0; i-- )
{
if( (gesture_data_.u_data[i] > thresold) &&
(gesture_data_.d_data[i] > thresold) &&
(gesture_data_.l_data[i] > thresold) &&
(gesture_data_.r_data[i] > thresold) ) {
u_last = gesture_data_.u_data[i];
d_last = gesture_data_.d_data[i];
l_last = gesture_data_.l_data[i];
r_last = gesture_data_.r_data[i];
break;
}
}
}
/* Calculate the first vs. last ratio of up/down and left/right */
ud_ratio_first = ((u_first - d_first) * 100) / (u_first + d_first);
lr_ratio_first = ((l_first - r_first) * 100) / (l_first + r_first);
ud_ratio_last = ((u_last - d_last) * 100) / (u_last + d_last);
lr_ratio_last = ((l_last - r_last) * 100) / (l_last + r_last);
// printf("ud ratio first = %d\n",ud_ratio_first);
// printf("lr ratio first = %d\n",lr_ratio_first);
// printf("ud ratio last = %d\n",ud_ratio_last);
// printf("lr ratio last = %d\n",lr_ratio_last);
/* Determine the difference between the first and last ratios */
ud_delta = ud_ratio_last - ud_ratio_first;
lr_delta = lr_ratio_last - lr_ratio_first;
// printf("Gesture_ud_delta = %d\n",gesture_ud_delta_ );
// printf("Gesture_le_delta = %d\n",gesture_lr_delta_ );
// printf("UD_delta is %d\n",ud_delta);
// printf("LR_delta is %d\n",lr_delta);
//
/* Accumulate the UD and LR delta values */
gesture_ud_delta_ += ud_delta;
gesture_lr_delta_ += lr_delta;
// printf("Gesture_ud_delta after adding = %d\n",gesture_ud_delta_ );
// printf("Gesture_le_delta after adding = %d\n",gesture_lr_delta_ );
/* Determine U/D gesture */
if( gesture_ud_delta_ >= sensetivity_1 )
{
gesture_ud_count_ = 1;
}
else if( gesture_ud_delta_ <= - sensetivity_1 )
{
gesture_ud_count_ = -1;
}
else
{
gesture_ud_count_ = 0;
}
/* Determine L/R gesture */
if( gesture_lr_delta_ >= sensetivity_1 )
{
gesture_lr_count_ = 1;
} else if( gesture_lr_delta_ <= -sensetivity_1 )
{
gesture_lr_count_ = -1;
} else
{
gesture_lr_count_ = 0;
}
/* Determine Near/Far gesture */
if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == 0) )
{
if( (abs(ud_delta) < GESTURE_SENSITIVITY_2) && \
(abs(lr_delta) < GESTURE_SENSITIVITY_2) )
{
if( (ud_delta == 0) && (lr_delta == 0) )
{
gesture_near_count_++;
}
else if( (ud_delta != 0) || (lr_delta != 0) )
{
gesture_far_count_++;
}
if( (gesture_near_count_ >= 10) && (gesture_far_count_ >= 2) )
{
if( (ud_delta == 0) && (lr_delta == 0) )
{
gesture_state_ = NEAR_STATE;
}
else if( (ud_delta != 0) && (lr_delta != 0) )
{
gesture_state_ = FAR_STATE;
}
return true;
}
}
} else {
if( (abs(ud_delta) < GESTURE_SENSITIVITY_2) && \
(abs(lr_delta) < GESTURE_SENSITIVITY_2) ) {
if( (ud_delta == 0) && (lr_delta == 0) ) {
gesture_near_count_++;
}
if( gesture_near_count_ >= 10 ) {
gesture_ud_count_ = 0;
gesture_lr_count_ = 0;
gesture_ud_delta_ = 0;
gesture_lr_delta_ = 0;
}
}
}
return false;
}
/*Determines swipe direction or near/far state*/
bool decodeGesture()
{
/* Return if near or far event is detected */
if( gesture_state_ == NEAR_STATE ) {
gesture_motion_ = DIR_NEAR;
return true;
} else if ( gesture_state_ == FAR_STATE ) {
gesture_motion_ = DIR_FAR;
return true;
}
/* Determine swipe direction */
if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == 0) ) {
gesture_motion_ = DIR_UP;
} else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == 0) ) {
gesture_motion_ = DIR_DOWN;
} else if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == 1) ) {
gesture_motion_ = DIR_RIGHT;
} else if( (gesture_ud_count_ == 0) && (gesture_lr_count_ == -1) ) {
gesture_motion_ = DIR_LEFT;
} else if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == 1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_UP;
} else {
gesture_motion_ = DIR_RIGHT;
}
} else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == -1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_DOWN;
} else {
gesture_motion_ = DIR_LEFT;
}
} else if( (gesture_ud_count_ == -1) && (gesture_lr_count_ == -1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_UP;
} else {
gesture_motion_ = DIR_LEFT;
}
} else if( (gesture_ud_count_ == 1) && (gesture_lr_count_ == 1) ) {
if( abs(gesture_ud_delta_) > abs(gesture_lr_delta_) ) {
gesture_motion_ = DIR_DOWN;
} else {
gesture_motion_ = DIR_RIGHT;
}
} else {
return false;
}
return true;
}
/*Reads a block (array) of bytes from the I2C device and register*/
int wireReadDataBlock( uint8_t reg, uint8_t *val, unsigned int len)
{
unsigned char j = 0;
I2C_Start();
I2C_Write_Byte((APDS9960_I2C_ADDR << 1 )| 0x00); // Slave address + Write command
I2C_Write_Byte(reg); // write the location
I2C_Start();
I2C_Write_Byte((APDS9960_I2C_ADDR << 1) | 0x01);
for(j= 0; j < len-1 ; j++)
{
val[j]=I2C_Read_Byte(); // Store the Receive value in a variable
I2C_Send_ACK();
}
val[len-1]=I2C_Read_Byte();
I2C_Send_NACK();
I2C_Stop();
return (int)j;
}
/*Writes a single byte to the I2C device and specified register*/
int wireWriteDataByte(unsigned char reg, unsigned char val)
{
I2C_Start();
I2C_Write_Byte((APDS9960_I2C_ADDR << 1 )| 0x00); // Slave address + Write command
I2C_Write_Byte(reg); // write the location
I2C_Write_Byte(val); // Write the Data
I2C_Stop();
return 1;
}
/*Reads a single byte from the I2C device and specified register*/
unsigned char wireReadDataByte(unsigned char reg)
{
/* Indicate which register we want to read from */
unsigned char val;
I2C_Start();
I2C_Write_Byte((APDS9960_I2C_ADDR << 1 )| 0x00); // Slave address + Write command
I2C_Write_Byte(reg); // write location
I2C_Start();
I2C_Write_Byte((APDS9960_I2C_ADDR << 1) | 0x01); //Slave address+ read command
val=I2C_Read_Byte(); // Store the Receive value in a variable
I2C_Send_NACK();
I2C_Stop();
return (val);
}
<file_sep>//***********************************************************************************
// Include files
//***********************************************************************************
#include "em_i2c.h"
#include "em_gpio.h"
#include "em_emu.h"
#include "native_gecko.h"
#include "gatt_db.h"
#include "src/cmu.h"
#include "src/I2C.h"
#include "bg_types.h"
//***********************************************************************************
// defined files
//***********************************************************************************
#define read_slave (0x01)
#define write_slave (0x00)
//***********************************************************************************
// global variables
//***********************************************************************************
//***********************************************************************************
// function prototypes
//**********************************************************************************
void I2C_setup(void)
{
// Select clocks
CMU_ClockEnable(cmuClock_HFPER, true);
CMU_ClockEnable(cmuClock_I2C0, true);
I2C0->ROUTEPEN = I2C_ROUTEPEN_SDAPEN | I2C_ROUTEPEN_SCLPEN;
I2C0->ROUTELOC0 = ((SCL_locReg << SCL_Route_LOC_shift ) | (SDA_locReg << SDA_Route_LOC_shift)); // ) SCL is at location 16(5:0 in RouteLOC0)
I2C_IntClear(I2C0,0x0007FFF);
I2C_IntEnable(I2C0,0x0007FFF);
const I2C_Init_TypeDef i2cInit =
{
false, /* Enable when initialization done. */
true, /* Set to master mode. */
0, /* Use currently configured reference clock. */
I2C_FREQ_STANDARD_MAX, /* Set to standard rate assuring being */
/* within I2C specification. */
i2cClockHLRStandard /* Set to use 4:4 low/high duty cycle. */
};
I2C_Init(I2C0, &i2cInit);
I2C_Enable(I2C0,true);
if(I2C0->STATE & I2C_STATE_BUSY)
{
I2C0->CMD=I2C_CMD_ABORT;
}
int j=0;
GPIO_PinModeSet(gpioPortC, 10, gpioModeWiredAnd, 1); // SCL
GPIO_PinModeSet(gpioPortC, 11, gpioModeWiredAnd, 1); // SDA
// toggle SCL pin 9 times to reset any I2C slave that may require it
for ( j = 0; j < 9; j++)
{
GPIO_PinModeSet(gpioPortC, 10, gpioModeWiredAnd, 0);
GPIO_PinModeSet(gpioPortC, 10, gpioModeWiredAnd, 1);
}
}
void I2C_Start()
{
I2C0->CMD = I2C_CMD_START;
}
void I2C_Stop()
{
I2C0->CMD = I2C_CMD_STOP;
}
void I2C_Send_NACK()
{
I2C0->CMD=I2C_CMD_NACK;
}
void I2C_Send_ACK(void)
{
I2C0->CMD = I2C_CMD_ACK;
}
void I2C_Write_Byte(unsigned char data)
{
I2C0->TXDATA = data;
while((I2C0->IF & I2C_IF_ACK)== 0);
I2C_IntClear(I2C0,I2C_IFC_ACK); // clear the ack flag
}
unsigned char I2C_Read_Byte(void)
{
uint8_t data;
while(( I2C0->STATUS & I2C_STATUS_RXDATAV) == 0);
data = I2C0->RXDATA;
return data;
}
unsigned char I2C_Read2Bytes(void)
{
uint16_t data;
while(( I2C0->STATUS & I2C_STATUS_RXDATAV) == 0);
data = I2C0->RXDATA;
data <<= 8;
I2C0->CMD = I2C_CMD_ACK;
while(( I2C0->STATUS & I2C_STATUS_RXDATAV) == 0);
data |= I2C0->RXDATA;
return data;
}
<file_sep>/*********************************************************************************************************************************************
* Include Headers
********************************************************************************************************************************************/
#include "inc/gpio.h"
#include "em_gpio.h"
/*********************************************************************************************************************************************
* Functions
********************************************************************************************************************************************/
void GPIO_Init()
{
printf("GPIO Init \r\n");
GPIO_DriveStrengthSet(IR_Port, gpioDriveStrengthStrongAlternateStrong);
GPIO_PinModeSet(IR_Port, IR_Pin, gpioModeInput, IR_Default);
}
void GPIO_Disable()
{
GPIO_PinModeSet(IR_Port, IR_Pin, gpioModeDisabled, IR_Default);
}
<file_sep>#ifndef LCD_DRIVER_H_
#define LCD_DRIVER_H_
#include "hal-config.h"
#if (HAL_SPIDISPLAY_ENABLE == 1)
#include "bg_types.h"
/**
* LCD content can be updated one row at a time using function LCD_write().
* Row number is passed as parameter,the possible values are defined below.
*/
#define LCD_ROW_NAME 1 /* 1st row, device name */
#define LCD_ROW_STATUS 2 /* 2nd row, node status */
#define LCD_ROW_CONNECTION 3 /* 3rd row, connection status */
#define LCD_ROW_FRIEND 4 /* 4th row, friendship FRIEND status */
#define LCD_ROW_LPN 4 /* 4th row, friendship LPN status */
#define LCD_ROW_DIRECTION 5 /* 5th row, direction of motion */
#define LCD_ROW_MOTORONOFF 6 /* 6th row, motor status */
#define LCD_ROW_IR 7 /* 7th row, IR Sensor Status */
#define LCD_ROW_MOTORSPEED 8 /* 8th row, Motor Speed */
#define LCD_ROW_MAX 8 /* total number of rows used */
#define LCD_ROW_LEN 32 /* up to 32 characters per each row */
void LCD_init(void);
void LCD_write(char *str, uint8 row);
#endif /* HAL_SPIDISPLAY_ENABLE */
#endif /* LCD_DRIVER_H_ */
| fdbe042a717e0727d5bdefcf269c560eaa176a76 | [
"Markdown",
"C",
"Makefile"
]
| 8 | Markdown | deep6000/Bt-Mesh-Gesture-based-Remote-Controlled-Smart-Wheel-Chair | add0ab4be0c6f6053d3f48f0e430f1e61fc89e3d | a45a9aaab165d1e7a15639cf10a658a6a2b5e583 |
refs/heads/master | <repo_name>zhenyi2697/dashboard-demo<file_sep>/webpack/loaders.js
var scripts = {
test: /\.tsx?$/,
loader: 'ts-loader'
};
var styles = {
test: /\.(css|less)$/,
loader: 'style!css!less'
};
module.exports = [
scripts,
styles
];<file_sep>/README.md
# Voice Dashboard Demo
## Environement setup
# to install dependencies
npm install
# to run dev server
npm start
# to build the project
npm run build
| 2a8c95ba77065b73736465220d6b31d2f00a7626 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | zhenyi2697/dashboard-demo | b79059ae695b95d8dc65576123cd54b128fc2b40 | e5c1b4ace4f3827e640e323358a44c661705e9e6 |
refs/heads/master | <file_sep>import '@testing-library/jest-dom/extend-expect'
import { render, screen, fireEvent } from '@testing-library/react';
import Explorer, { SAT2BTC, Pager} from './Explorer';
import App from './App'
test('renders loading text', () => {
render(<Explorer />);
const linkElement = screen.getByText(/Loading.../i);
expect(linkElement).toBeInTheDocument();
});
test('renders pager text', () => {
render(<Pager count={100} />);
const linkElement = screen.getByText(/\[10\]/i);
expect(linkElement).toBeInTheDocument();
});
test('click test', () => {
let fetch = window.fetch;
render(<App />);
let input = screen.getByPlaceholderText(/Type Block Hash Here/i);
jest.spyOn(window, 'fetch').mockImplementationOnce((url, ...args) => {
let hash = url.indexOf(input.value)>-1;
// console.log("fetch args", hash, input.value)
expect(hash).toBe(true);
return fetch(args)
});
fireEvent.keyDown( input, { key: 'Enter', code: 'Enter' } )
});
// test('test to fetch block rawdata', () => {
// const fakeUserResponse = {token: 'fake_user_token'}
// jest.spyOn(window, 'fetch').mockImplementationOnce(() => {
// return Promise.resolve({
// json: () => Promise.resolve(fakeUserResponse),
// })
// });
// loadBlock('b15bb075d22c8a276bd7b8a29f60229702119acfe995905835dc26c0107d0424')
// .then(json => {
// expect(json.token).toBe(fakeUserResponse.token);
// });
// });
test('test SAT2BTC', () => {
let btc = SAT2BTC(80000);
expect(btc).toBe("0.00080000");
let btc1 = SAT2BTC(100000000);
expect(btc1).toBe("1.00000000");
});
// this is just a little hack to silence a warning that we'll get until we
// upgrade to 16.9. See also: https://github.com/facebook/react/pull/14853
const originalError = console.error
beforeAll(() => {
console.error = (...args) => {
if (/Warning.*not wrapped in act/.test(args[0])) {
return
}
originalError.call(console, ...args)
}
})
afterAll(() => {
console.error = originalError
})
<file_sep>import {useRef, useState} from 'react';
import './App.css';
import goat from './img/goat.png';
import Explorer from './Explorer';
function App() {
const ref = useRef(null);
const [state, setV] = useState("")
let doKeydown = (ev) => {
if(ev.key === "Enter" && ref.current.value !== ""){
setV(ref.current.value);
}
}
let doQuery = (ev) => {
setV(ref.current.value);
}
if(state !== "") return (
<header className="App-header">
<Explorer hash={state} onError={ ev => {
setV("");
alert(ev);
}}>
<div className="return" onClick={ev => setV("")}>🏡</div>
</Explorer>
</header>
)
return (
<div className="App">
<header className="App-header">
<img src={goat} className="" alt="logo" />
<h1 className="grow"> Block Explorer </h1>
<div className="col12">
<input placeholder="Type Block Hash Here, ex. 1 for the genesis block" className="col34 layL" type="text"
ref={ref}
onKeyDown={ev => doKeydown(ev)}
defaultValue="150000"/>
<br />
<button className="button-minimal" onClick={ev => doQuery(ev)}>Inquire</button>
</div>
</header>
</div>
);
}
export default App;
<file_sep># 🚩 ArcBlock Coding Test
👉 题目内容
编写 1 个可以部署到 ABT Node 的 Blocklet,需要实现的功能如下:
- 主界面包含输入框,用户输入某个比特币的 `Block Hash` 后能查询并展示对应 Block 中包含的所有 `Transaction`
- 根据 `Block Hash` 拿到 `区块数据`可以使用这个 API,API 介绍见这里
- 把比特币 `Block` 和 `Transaction` 数据渲染成 Bitcoin Explore 显示的样式,只需要包含`区块摘要`和`分页`的`交易列表`即可,网页的 Header 和 Footer 可以忽略
- 项目不要只支持渲染某个特定的 Block,而是可以`任意`输入 `Block Hash` 来查看结果
- rawblock JSON 区块数据 https://blockchain.info/rawblock/00000000000000000007878ec04bb2b2e12317804810f4c26033585b3f81ffaa
- Blockchain Data API https://www.blockchain.com/api/blockchain_api
- Bitcoin Explorer - Block https://www.blockchain.com/btc/block/00000000000000000007878ec04bb2b2e12317804810f4c26033585b3f81ffaa
- Get started with ABT Node https://www.arcblock.io/en/get-started
- Blocklet 规范 https://github.com/blocklet/blocklet-specification/blob/main/docs/meta.md
- ABT Wallet https://abtwallet.io/zh/
- Kitchen Sink Demo https://github.com/blocklet/kitchen-sink-demo
- Demo - Install on my ABT Node https://github.com/blocklet/react-demo
- Install on ABT Node https://install.arcblock.io/?action=blocklet-install&meta_url=https://github.com/blocklet/react-demo/releases/download/0.1.4/blocklet.json
👉 其他要求或建议:
- 应该编写测试,并且测试能全部通过
- 应该包含 README.md 来告知面试官项目采用的技术栈,以及如何启动、构建项目,运行测试
- 基本界面和交互外,你可以自由发挥,目标是更好的展示区块链上的数据
👉 步骤建议
- 先使用你熟悉的框架、工具和库搭建出 Blocklet 骨架并添加基本功能,建议前端使用 create-react-app,后端使用 express.js
- 启动 ABT Node 本地实例,安装试用官方 Marketplace 里面的 Blocklet,了解 Blocklet 在 ABT Node 里面的运行环境,Blocklet 规范参见文档。
- 参照 React Demo 将你的应用变成 Blocklet,使其能运行在本地的 ABT Node 环境中,`blocklet.yml` 可以用 `blocklet init` 创建。
- 如果你的 Blocklet 不包含后端代码,group 建议选择 static 类型,main 建议选择 create-react-app 默认的 build 目录
👉 加分项
如果你能参照 Kitchen Sink Demo 中 CI 的配置,让你的 Blocklet 仓库支持 `Install on ABT Node` 功能(安装之后要能够正常启动、访问),将获得额外加分。
<file_sep>
# Blocklet demo with React
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), it's a simple demo purpose [Blocklet](https://www.arcblock.io/en/blocklets) that runs on [ABT Node](https://www.arcblock.io/en/platform).
## Run Test suite
Run the following command to do test with React Testing Library.
```shell
yarn test
# or
npm run test
```
## Install to your ABT Node
If you have your own ABT Node and just want to try out this blocklet, simply click the following button to install:
[](https://install.arcblock.io/?action=blocklet-install&meta_url=https%3A%2F%2Fgithub.com%2Fjimboyeah%2fabt-blocklet-demo%2freleases%2fdownload%2fabt-blocklet-demo-1.0.0%2fblocklet.json)
Or alternatively, you can find install this demo blocklet in [Blocklets Marketplace](https://blocklet.arcblock.io) or from the "Blocklet/Marketplace" menu in your ABT Node console.
## Run and debug in the cloud with Gitpod
Click the "Open in Gitpod" button, Gitpod will start ABT Node and the blocklet.
[](https://gitpod.io/#https://github.com/jimboyeah/abt-blocklet-demo)
## Run and debug locally
If you have not installed ABT Node locally, you can do it using the following:
```shell
yarn global add @abtnode/cli
```
You can get more details from [Get started with ABT Node](https://www.arcblock.io/en/get-started) page or if you need help installing ABT Node.
Clone the repo and start development using a debug mode ABT Node instance inside this project:
```shell
git clone <EMAIL>:jimboyeah/abt-blocklet-demo.git
cd react-demo
yarn
abtnode init --mode debug
abtnode start
blocklet dev
```
## Build
Build this project before bundle and package.
```shell
yarn build
```
## Bundle and Package
Use bundle command to tranform static output in `build` to `.blocklet`, then deploy it in your local ABT Node.
```shell
blocklet bundle
blocklet deploy .blocklet/bundle
```
## Learn more about ABT Node and Blocklet
* [ABT Node Overview](https://docs.arcblock.io/en/abtnode/introduction/abtnode-overview)
* [Get started with ABT Node](https://www.arcblock.io/en/get-started)
* [ABT Node CLI](https://docs.arcblock.io/en/abtnode/developer/abtnode-cli)
* [Blocklet Development Documents](https://docs.arcblock.io/en/abtnode/developer/blocklet-spec)
## More on ABT Node CLI
- https://docs.arcblock.io/abtnode/zh/developer/abtnode-cli
- https://github.com/ArcBlock/abt-node
安装,初始化并启动 ABT Node 进行配置:
yarn global add @abtnode/cli
npm install -g @abtnode/cli
abtnode init
abtnode start
使用中遇到权限问题,启动 ABT Node 后,blocklet 也不能顺利安装:
{
errno: -13,
code: 'EACCES',
syscall: 'rename',
path: '/home/jeango/.nvm/versions/node/v15.9.0/lib/node_modules/@abtnode/cli',
dest: '/home/jeango/.nvm/versions/node/v15.9.0/lib/node_modules/@abtnode/.cli-V32Ka8cV'
}
试以 root 身份运行安装命令。
sudo npm install -g @abtnode/cli
sudo npm install --unsafe-perm=true -g @abtnode/cli
sudo npm install --unsafe-perm=true --allow-root -g @abtnode/cli
以上安装方式对我的开发环境还是不起作用,系统是 Windows WSL Ubuntu,Node.js v15.9.0。
下面开始源代码补丁模式,修改 `@abtnode\core\lib\blocklet\manager\disk.js` 代码文件 Line 1800,将 fs.move 方法调用改成 fs.copy 方式,总共 2 处:
async _resolveDownload(cwd, tarFile, originalMeta) {
...
// await fs.move(downloadDir, installDir, { overwrite: true });
logger.info('🚩======= move: ', {downloadDir, installDir});
await fs.copy(downloadDir, installDir, { overwrite: true });
fs.removeSync(downloadDir);
}
安装完成后,启动 ABT Node,使用你的 ABT 钱包并扫描二维码登录。
bundle [options] Bundle a blocklet that can run in ABT Node
start [options] Start ABT Node Daemon
init Init ABT Node config
status Show ABT Node and blocklet status
logs Show ABT Node and blocklet logs
stop|kill [options] Stop ABT Node and blocklets
info [options] Get environment information for debugging and
issue reporting
deploy [options] <folder> Deploy blocklet from local directory to ABT Node
blocklet:init Create an empty blocklet project
upgrade Self-Upgrade ABTNode
help [command] display help for command
ABT Node v1.2.0 里面包含了 Breaking Change,安装 @abtnode/cli 后会产生两个全局的命令行工具 `abtnode` 和 `blocklet`,前者用来管理 ABT Node,后者用来操作 Blocklet:
- abtnode deploy 变成了 blocklet deploy
- abtnode bundle 变成了 blocklet bundle
- abtnode blocklet:* 变成了 blocklet *
ABT Node 默认的 Blocklet Registry 变更为 https://booster.registry.arcblock.io 新 Registry 启用了 AWS 的全球 CDN 加速,下载速度会更快。
使用 yarn 安装,请导出 `~/.yarn/bin` 目录以正常使用 abtnode 命令。
修改 `~/.bashrc` `~/.profile` `~/.zshrc` 之一个,以自动查找 nvm 命令:
export NVM_DIR="$HOME/.yarn/bin"
## License
The code is licensed under the MIT license found in the
[LICENSE](LICENSE) file.
<file_sep>import {useState} from 'react';
import Loading from './Loading';
// import goat from './img/goat.png';
import coin from './img/bitcoin.svg';
import out from './img/out.svg';
import to from './img/to.svg';
import spent from './img/spent.svg';
import unspent from './img/unspent.svg';
import './App.css';
export function Pager({count, current=1, size = 10, onPage = ()=>{}}){
let page = Math.ceil(count/10.0);
let pager = [];
let start = current<=10? 1: current - 10;
let end = current>page-10? page:current+10;
for(let i=start; i<=end; i++) pager.push(i);
return (
<div className="page rows fS layXLV">
{pager.map(it => (
<div key={it} onClick={ ev => onPage(it) } style={{cursor:"pointer"}}>
{current === it? "<--"+it+"-->":"["+it+"]"}
</div>))}
</div>
)
}
export function loadBlock(hash, setV = ()=>{}, onError = ()=>{}) {
// https://www.blockchain.com/api/blockchain_api
return fetch("https://blockchain.info/rawblock/"+hash+"?cors=true")
.then(res => res.json())
.then(json => {
try{
setV(json);
}catch(ex){
console.log(ex);
}
return json;
})
.catch(ex => {
onError(ex)
console.log(ex);
return Promise.reject({
json: () => Promise.resolve(ex),
})
});
}
export function pretty(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
export function fixed(value, fract = 2) {
return pretty(value.toFixed(fract));
}
export function fixed3(value) {
return fixed(value, 3);
}
export function SAT2BTC(value) {
return (value/100000000).toFixed(8);
}
export function countOut(items) {
let sum = 0;
for(let p in items) {
sum += items[p].value;
}
return SAT2BTC(sum);
}
export function getBlockTotal(block) {
let sum = 0, ins = 0, out = 0, spenti = 0, spento = 0, fee = 0;
block.tx.map(it => {
fee += it.fee;
it.out.map(itout => {
out += itout.value;
if(itout.spent === true) spento += itout.value;
return itout;
})
it.inputs.map(itins => {
if(!itins.prev_out) return itins;
ins += itins.prev_out.value;
if(itins.prev_out.spent === true) spenti += itins.prev_out.value;
return itins;
})
return it;
})
sum = SAT2BTC(spenti-fee);
console.log({
sum: SAT2BTC(sum),
fee: SAT2BTC(fee),
ins: SAT2BTC(ins),
out: SAT2BTC(out),
spenti: SAT2BTC(spenti),
spento: SAT2BTC(spento)})
return sum;
}
export function Explorer(props) {
let {hash} = props;
const [block, setV] = useState(null)
const [page, setPage] = useState(1)
if(block == null) {
loadBlock(hash, setV, props.onError);
return (
<header className="App-header">
<img src={coin} className="App-logo" alt="logo" style={{height:128}} />
<Loading text="Loading..." />
{ props.children }
</header>
)
}
let miner = block.tx[0].out[0].addr;
let tx = block.tx.slice(10*(page-1), 10*(page-1)+10)
return (
<div className="App">
<header className="App-header">
<h1 className="grow fxFixed" style={{fontSize: 42}}> <img src={coin} className="inline" alt="logo" /> Block Explorer </h1>
<h3>Block {block.height}</h3>
<dl className="columns fXS">
<div className="rows bb"><dt className="col16 fxFixed taRight">Hash</dt> <dd className="addr col34">{block.hash}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Confirmations</dt> <dd>Unknown</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Timestamp</dt> <dd>{new Date(block.time*1000).toLocaleString()}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Height</dt> <dd>{pretty(block.height)}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Miner</dt> <dd><a href={"https://www.blockchain.com/btc/address/"+miner}>Unknown</a></dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Number of Transactions</dt> <dd>{block.tx.length}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Difficulty</dt> <dd>18,670,168,558,399.59 (2021/02/27)</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Merkle root</dt> <dd className="addr col34">{block.mrkl_root}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Version</dt> <dd>{block.ver}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Bits</dt> <dd>{pretty(block.bits)}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Weight</dt> <dd>{pretty(block.weight)} WU</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Size</dt> <dd>{pretty(block.size)}</dd>bytes</div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Nonce</dt> <dd>{pretty(block.nonce)}</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Transaction Volume</dt> <dd>{getBlockTotal(block)} BTC</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Block Reward</dt> <dd>6.25000000 BTC (Since 2020)</dd></div>
<div className="rows bb"><dt className="col16 fxFixed taRight">Fee Reward</dt> <dd>{SAT2BTC(block.fee)} BTC</dd></div>
</dl>
<h3>Block Transactions</h3>
{tx.map( it =>
<div key={it.hash} className="tx fXS columns card bgDarkGray taLeft">
<p className="layLV addr col11">Hash: {it.hash}</p>
<div className="rows">
<div className="input columns col49">
{ it.inputs.map((item, ik) =>
<div key={it.hash + ik}>
{!item.prev_out &&
<div className="cLightGreen">COINBASE (Newly Generated Coins)</div>
}
{item.prev_out &&
<div className="rows fxBetween">
<p className="addr">{item.prev_out.addr}</p>
<p className="btc">{SAT2BTC(item.prev_out.value)} BTC</p>
<a href={"https://www.blockchain.com/btc/address/"+item.prev_out.addr}>
<img className="inline" src={out} alt="out"/>
</a>
</div>
}
</div>
)}
</div>
<img className="layL" src={to} alt="to"/>
<div className="out columns col49">
{ it.out.map((item, ik) =>
<div className="rows fxBetween" key={ik}>
{ item.addr === "null" && "OP_RETURN"}
{ item.addr !== "null" && <p className="addr">{item.addr}</p> }
<p className="btc"> {SAT2BTC(item.value)} BTC</p>
<a href={item.addr ==="null"? "#":("https://www.blockchain.com/btc/address/"+item.addr)}>
{item.spent && <img className="inline" src={spent} title="Spent" alt="spent"/> }
{!item.spent && <img className="inline" src={unspent} title="Unspent" alt="unspent"/> }
</a>
</div>
)}
</div>
</div>
<div className="cLightGreen layLV rows fxBetween">
<p>Fee: {SAT2BTC(it.fee)} BTC</p>
<p>{ countOut(it.out) } BTC</p>
</div>
<div className="feeverage">({fixed3(it.fee/it.size)} sat/byte - {fixed3(it.fee/it.weight)} sat/WU - {it.size} bytes)</div>
</div>
)}
<Pager current={page} onPage={page => setPage(page)} count={block.tx.length} />
<div className="col12 layXLV">
{ props.children }
</div>
</header>
</div>
);
}
export default Explorer;
<file_sep>import {useEffect, useRef} from 'react'
let timer = 0
let index = 0
export let Loading = (props) => {
let indicator = ['🌑','🌒','🌓','🌔','🌝','🌕','🌖','🌗','🌘','🌚']
const ref = useRef({})
useEffect(() => {
timer = setInterval(() => {
index = (index+1)%indicator.length
ref.current.innerHTML = indicator[index] + ' ' + props.text
}, 300);
return () => {
clearInterval(timer)
};
})
return <div ref={ref} className="loading">{indicator[index]} {props.text}</div>
}
export default Loading; | 3bf7c30b63bfff1b5e4c2dfd21b1480cbabf880d | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | jimboyeah/abt-blocklet-demo | b86f94f158d4120037b70af6bbf138d14d4e3078 | 5fda5d9ce00e4d78daa5f9aed75d3921cd865889 |
refs/heads/master | <file_sep>`ifndef DEFINE_STATE
// This defines the states for BIST
typedef enum logic [3:0] {
S_IDLE,
S_START,
S_WRITE_CYCLE,
S_DELAY_1,
S_DELAY_2,
S_READ_CYCLE,
S_DELAY_3,
S_DELAY_4,
S_WRITE_CYCLE_2,
S_DELAY_5,
S_DELAY_6,
S_READ_CYCLE_2,
S_DELAY_7,
S_DELAY_8
} BIST_state_type;
parameter PAT0 = 16'h3333;
parameter PAT1 = 16'hCCCC;
parameter PAT2 = 16'h0F0F;
parameter PAT3 = 16'hF0F0;
`define DEFINE_STATE 1
`endif
| 87480f802b1ae59be27f289e9c547d38489b87c6 | [
"C"
]
| 1 | C | mahmof4/3dq5-labs | c47d329ab2a290178c7676fd15b7104fafed0bf0 | 4b142dddb243d6659aa582046637a12f4031bf54 |
refs/heads/master | <file_sep>import os
#basedir = os.path.abspath(os.path.dirname(__file__))
USERNAME = ''
PASSWORD = ''
SERVER = ''
S_JQL = ''
<file_sep>from app import app
from jira.client import JIRA
from config import SERVER, USERNAME, PASSWORD, S_JQL
options = {
'server': str(SERVER)
}
jira = JIRA(options, basic_auth=(USERNAME, PASSWORD))
# get dict with issue.key:summary by provided JQL
def getIsuesS():
issuesOnSupport = jira.search_issues(S_JQL)
return dict(zip([issue.key for issue in issuesOnSupport],\
[issue.fields.summary for issue in issuesOnSupport]))
# get list of all projects ( [[names, keys, leads], ...] )
def getAllLeads():
projects = jira.projects()
keys = [project.key for project in projects]
names = [project.name for project in projects]
leads = [jira.project(project.key).lead.displayName \
for project in projects]
result, i = [], 0
mx = len(keys)
while i < mx:
result.append([names[i], keys[i], leads[i]])
i += 1
return result
# get issues by user where status in ( Open, "In Progress")
def getIssueByUser(username):
issues = jira.search_issues('status in (Open, "In Progress") AND assignee in ('\
+ str(username)+ ')')
return dict(zip([issue.key for issue in issues],\
[issue.fields.summary for issue in issues]))
# get all keys of issues provided by JQL
def getIssues():
issuesOnSupport = jira.search_issues(S_JQL)
return [issue.key for issue in issuesOnSupport]
def assignToUser(S_JQL, user):
issues = jira.search_issues(S_JQL)
for issue in issues:
jira.assign_issue(issue, user)
# function may be used throw jinja
#app.jinja_env.globals.update(getIssueByUser=getIssueByUser)
<file_sep>import os
from flask import Flask
#from config import basedir
app = Flask(__name__)
app.config.from_object('config')
from app import views, models
##from config import USERNAME, PASSWORD, SERVER
<file_sep># Web app for watching tickets in JIRA
Using jql you can watch statuses, assignee, etc. of tickets
webapp uses microframework [flask][1] and [jira-python][2] library for watching statuses, assignees, etc.
It's a very simple project and it is not finished yet, but works fine as is. New features will be added in future.
# Installation
Download and install using pip:
pip install jira-python
pip install flask
You can also use [virtualenv][3]
clone git rep into your directory:
git clone https://github.com/cmgc/jira_watcher.git
# Quickstart
1. Enter servername, and your credentials for accessing jira in config.py file.
(also you can add jira sql in config.py which will be used in future)
2. just run it:
$ nohup python run.py &
3. list of available actions:
- /user/<username> - to get all tickets assigned to <username>
- /lead - to get leads of all projects. Can be accessed only after /f_update
which will update data.json file
- /help - to get list all actions
..
# useful things:
you can use sample.html as example how to monitor tickets.
[1]: http://flask.pocoo.org/
[2]: http://jira-python.readthedocs.org/
[3]: http://virtualenv.org/en/latest/index.html
<file_sep>from flask import render_template, url_for, redirect, request
from jira.client import JIRA
import sys, json
from config import USERNAME, PASSWORD, SERVER
from app import app
from models import getIssueByUser, getIssues, getIsuesS, getAllLeads
@app.route('/')
@app.route('/index')
def index():
issues = getIssues()
return render_template("index.html", server=SERVER, issues=issues)
@app.route('/lead')
def lead():
with open('data.json', 'rb') as fp:
leads = json.load(fp)
return render_template("leads.html", leads=leads)
@app.route('/user/<username>')
def user(username):
issues = getIssueByUser(username)
return render_template("user.html",server=SERVER,
name=username, issues=issues)
@app.route('/users')
def users():
usernames = ['', '']
return render_template("users.html", users=usernames)
@app.route('/f_update')
def f_update():
data = getAllLeads()
with open('data.json', 'wb') as fp:
json.dump(data, fp)
return "<b>Success!</b>"
@app.route('/test')
def test():
tickets = getIsuesS()
return render_template("test.html", server=SERVER, tickets=tickets)
@app.route('/a/<user>')
def assign_to_user(user):
assignToUser(S_JQL, user)
return redirect(url_for('index'))
@app.route('/is')
def test2():
issues = getIssues()
return str(issues)
@app.route('/help')
def help():
links = {}
for rule in app.url_map.iter_rules():
links[rule.rule] = app.view_functions[rule.endpoint].__doc__
return render_template("help.html", links=links)
| 30153e09f4e6d1cbc0e682680800ebcb0afb1291 | [
"Markdown",
"Python"
]
| 5 | Python | cmgc/jira-watcher | 8317e20460e3fd091cb7f9037b321de575171368 | ba76fef7e98d039dc7f48a5b39cdef1048546e82 |
refs/heads/master | <file_sep>cmake_minimum_required(VERSION 3.4)
project(ARTOOLKIT_BOILERPLATE)
#if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
# # OS X
# set(PLATFORM_CXX_FLAGS "-framework OpenGL")
#
#elseif(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
# # Linux
# set(PLATFORM_CXX_FLAGS "-lGL")
#endif()
find_package(OpenGL REQUIRED)
find_library(SDL2_LIBRARY SDL2)
find_library(SDL2main_LIBRARY SDL2main)
#find_library(GLEW_LIBRARY GLEW)
set(LIBRARIES ${SDL2_LIBRARY} ${SDL2main_LIBRARY} ${OPENGL_LIBRARIES})
find_package(GLEW REQUIRED)
if(GLEW_FOUND)
include_directories(${GLEW_INCLUDE_DIRS})
link_libraries(${GLEW_LIBRARIES})
else()
message("ERROR! GLEW NOT FOUND")
endif()
include_directories(${OPENGL_INCLUDE_DIRS})
#file(READ "Shaders/simple.frag" SIMPLE_FRAG)
#string(REGEX REPLACE " " "\\\\ " SIMPLE_FRAG ${SIMPLE_FRAG})
#file(READ "Shaders/simple.vert" SIMPLE_VERT)
#message(${SIMPLE_FRAG})
#add_definitions(-DSIMPLE_FRAG="\"R\(\"${SIMPLE_FRAG}\"\)\"" -DSIMPLE_VERT=${SIMPLE_VERT})
#add_definitions(-DSIMPLE_FRAG=R\(\"${SIMPLE_FRAG}\"\))
#add_definitions(-DSIMPLE_VERT=\"bar\")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} "-m32" ${PLATFORM_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES sdl_template.c)
add_executable(ARTOOLKIT_BOILERPLATE ${SOURCE_FILES})
target_link_libraries(ARTOOLKIT_BOILERPLATE ${LIBRARIES})
<file_sep>#define GLEW_STATIC
#include<GL/glew.h>
#include<SDL2/SDL.h>
#include<SDL2/SDL_opengl.h>
#undef main
void createWindow(SDL_Window **window);
void createContext(SDL_Window *window, SDL_GLContext *context);
void draw();
int shutDown(SDL_GLContext* context);
const char *vertShader = "#version 150\nin vec2 position;\nvoid main() {\ngl_Position = vec4(position, 0.0, 1.0);\n}\n";
const char *fragShader = "#version 150\nout vec4 outColor;\nvoid main() {\noutColor = vec4(1.0, 1.0, 1.0, 1.0);\n}\n";
int main(int argc, char *argv[]) {
SDL_Window *window = NULL;
SDL_GLContext context = NULL;
createWindow(&window);
createContext(window, &context);
SDL_Event windowEvent;
for(;;) {
draw();
SDL_GL_SwapWindow(window);
if (SDL_PollEvent(&windowEvent)) {
if (windowEvent.type == SDL_QUIT) {
break;
}
if (windowEvent.type == SDL_KEYDOWN && windowEvent.key.keysym.sym == SDLK_ESCAPE) {
break;
}
}
}
return shutDown(&context);
}
void createWindow(SDL_Window **window) {
SDL_Init(SDL_INIT_VIDEO);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
*window = SDL_CreateWindow("OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
}
void createContext(SDL_Window *window, SDL_GLContext *context) {
*context = SDL_GL_CreateContext(window);
glewExperimental = GL_TRUE;
glewInit();
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint vbo;
glGenBuffers(1, &vbo);
float vertices[] = {
0.0f, 0.5f, // Vertex 1 (X,Y)
0.5f, -0.5f, // Vertex 2 (X,Y)
-0.5f, 0.5f // Vertex 3 (X,Y)
};
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertShader, NULL);
glCompileShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragShader, NULL);
glCompileShader(fragmentShader);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glBindFragDataLocation(shaderProgram, 0, "outColor");
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0);
}
int shutDown(SDL_GLContext *context) {
SDL_GL_DeleteContext(*context);
SDL_Quit();
return 0;
}
void draw() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
| a9f9478648c23979cb35a9568e90b8a025da96d6 | [
"C",
"CMake"
]
| 2 | CMake | wallywyyoung/artoolkit_sdl_boilerplate | 17eca05c677def2dd6ce434616d97ed896f07d12 | 8b1afa8c96155d4949964e6d525fea625ef09642 |
refs/heads/main | <repo_name>angeloxenakis/mma-data-scraper<file_sep>/app/models/scraper.rb
require "nokogiri"
require "open-uri"
require "pry"
class Scraper
# letters = ["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"]
def scan_pages
letters = ["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"]
master_list = []
letters.each { |letter|
puts "http://ufcstats.com/statistics/fighters?char=#{letter}&page=all"
html = URI.open("http://ufcstats.com/statistics/fighters?char=#{letter}&page=all")
doc = Nokogiri::HTML(html)
fighters = doc.css(".b-statistics__table-row")
fighter_list = []
fighters.each { |fighter|
fighter_object = {
first_name: "",
last_name: "",
nick_name: "",
height: "",
weight: "",
reach: "",
stance: "",
wins: "",
losses: "",
draws: ""
}
if fighter.children[1].children.children.text != nil
fighter_object[:first_name] = fighter.children[1].children.children.text
end
if fighter.children[3] != nil
fighter_object[:last_name] = fighter.children[3].children.children.text
end
if fighter.children[5] != nil
fighter_object[:nick_name] = fighter.children[5].children.text.strip
end
if fighter.children[7] != nil
fighter_object[:height] = fighter.children[7].children.text.strip
end
if fighter.children[9] != nil
fighter_object[:weight] = fighter.children[9].children.text.strip
end
if fighter.children[11] != nil
fighter_object[:reach] = fighter.children[11].children.text.strip
end
if fighter.children[13] != nil
fighter_object[:stance] = fighter.children[13].children.text.strip
end
if fighter.children[15] != nil
fighter_object[:wins] = fighter.children[15].children.text.strip
end
if fighter.children[17] != nil
fighter_object[:losses] = fighter.children[17].children.text.strip
end
if fighter.children[19] != nil
fighter_object[:draws] = fighter.children[19].children.text.strip
end
master_list << fighter_object
}
}
return master_list
end
end
# scrape = Scraper.new
# scrape.scan_pages<file_sep>/db/migrate/20210826021145_create_fighters.rb
class CreateFighters < ActiveRecord::Migration[6.1]
def change
create_table :fighters do |t|
t.string :first_name
t.string :last_name
t.string :nick_name
t.string :height
t.string :weight
t.string :reach
t.string :stance
t.string :wins
t.string :losses
t.string :draws
t.timestamps
end
end
end
| 441d30ae69585e0cbfb0e4d75638fbc367b65f9b | [
"Ruby"
]
| 2 | Ruby | angeloxenakis/mma-data-scraper | 54d6c80f0be6533e4c761224249adc3a6f657820 | a143d2faa1ab279bb0aa5399732b06ab8779a061 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
npm install -g batshit
# install test projects
for project in convention configuration; do
pushd "test/$project"
npm install
npm link
popd
done
<file_sep>#!/usr/bin/env bash
# This `bon` impersonates another `<script> ...` - the (node.js) implementation.
# The few extras are location-independence, automated meta-command eval,
# a small safety mechanism, and a `$script line ...` - for easy cli dev.
# It also helps a little with some extra help options.
# HELPERS:
# Exits if a newline is found - a trailing \n is ok.
oneline() {
if [[ $1 == *$'\n'* ]]; then
echo "The '$name $2' should yield exactly one line to eval, exiting instead."
echo "FYI, here is what was got:"
echo "$1"
exit 1
else
return 0 # true
fi
}
# Determine if a list $1 contains an item $2.
contains() {
for word in $1; do
[[ $word = "$2" ]] && return 0 # = true
done
return 1 # = false
}
# Source a file if it exists.
include () {
[[ -f "$1" ]] && source "$1"
}
# Change working directory if requested.
cwd () {
[[ -n "$BON_CWD" ]] && cd "$BON_CWD"
}
# SETUP:
# Variables, with assumptions...
bon="bon" # the command of the bon script - matching package.json
base=$(basename "${0##*/}") # ${BASH_SOURCE[0]} is sometimes $bon
name=${BON_NAME:-$base} # of the node package that is using bon
script="./bin/$name.${BON_EXT:-js}" # relative to the $name package
[ -n "${BON_SCRIPT}" ] && script="${BON_SCRIPT}" # override entirely
# There can only be one `bon`.
if [[ $name == "bon" ]]; then
echo "Bon needs target implementation."
echo "See https://github.com/orlin/bon#readme"
exit 1
fi
path='.' # default - a last resort
# The $path is preferably a subdir of one of the following, to run from anywhere.
if [[ -n "${NODE_PATH}" ]]; then
NODE_PATH_TEST="${NODE_PATH}"
else
NODE_PATH_TEST="/usr/lib/node_modules:/usr/local/lib/node_modules"
NODE_PATH_TEST="${NODE_PATH_TEST}:$(dirname $(which npm))/../lib/node_modules"
fi
# Find the first NODE_PATH that contains the module.
IFS=':' read -ra node_paths <<< "${NODE_PATH_TEST}"
for path_test in "${node_paths[@]}"; do
if [[ -d "${path_test}/${name}" ]]; then
path="${path_test}/${name}"
if [[ -n "${BON_PRE_PATH}" ]]; then
if [[ "$BON_PRE_PATH" == "." ]]; then
BON_PRE_PATH="$path"
else
BON_PRE_PATH="${path}/${BON_PRE_PATH}"
fi
PATH="${BON_PRE_PATH}:${PATH}"
fi
[[ "$BON_CWD" == "." ]] && BON_CWD="$(pwd)"
cd "$path"
break
fi
done
# Make sure we are in the right place, or don't run anything.
if [[ "$BON_CHECK" == "no" ]]; then
path_ok="yes" # is it ok not to check? yes, in some cases.
else
[ -z "$BON_CHECK_FILE" ] && BON_CHECK_FILE=$path/package.json
if [[ -f "$BON_CHECK_FILE" ]]; then
if [ -z "$BON_CHECK_GREP" ]; then
package=$(node -e "process.stdout.write(require('${path}/package.json').name)")
if [[ $name == "$package" ]]; then
path_ok="yes"
fi
elif grep -q "$BON_CHECK_GREP" "$path/$BON_CHECK_FILE"; then
path_ok="yes"
fi
fi
fi
# The moment of $path_ok truth.
if [[ "$path_ok" == "yes" ]]; then
# If all the names match, provide an easy way to load more vars.
[[ $base == "$name" ]] && include ./bin/bonvars.sh
# Space-separated list of commands that produce commands to eval.
# Be careful what goes here - running arbitrary strings can be bad!
# Try `<name> line <command>` and add to the list once it looks good.
evalist="${BON_EVALIST}"
else
echo
echo "This '$path' path is not the root directory of $name."
if [[ -z "${NODE_PATH}" ]]; then
echo "Please set \$NODE_PATH - where global node_modules are installed."
fi
help="error"
fi
# Cannot do anything withhout a $script to run - except echo more help -
# check this far down because it may depend on $path or *bonvars*.
if [[ ! -x "$script" ]]; then
echo
if [[ ! -f "$script" ]]; then
echo "Script '$script' not found."
else
echo "Script '$script' not executable."
fi
help="error"
fi
# RUN: The sequence of if and elifs is not arbitrary - so don't rearrange!
if [[ $# -eq 0
|| $1 == "-?"
|| $1 == "-h"
|| $1 == "--help"
|| $help == "error"
]]; then
# help comes first
if [[ $help == "error" ]]; then
echo # vertical spacing follows prior messages
else
# show $script help only if there was no error and the script can be run
[[ -x "$script" ]] && $script ${BON_HELP:-$1}
fi
# help specific to bon is not always shown
if [[ $# -ne 0 || -n $BON_HELP ]]; then
# if we got here witn non-zero arguments, or non-zero-length of $BON_HELP
if [[ -z $BON_HELP_FILE ]]; then
echo "See https://github.com/orlin/bon#readme for more info."
echo
elif [[ $help != "error" ]]; then
# the error could mean bad path - so the help file won't be found
help_txt=$(cat $BON_HELP_FILE)
if [[ ! $help_txt == "" ]]; then
# only if the file wasn't empty
echo "$help_txt" # the quotes are necessary to keep `\n`s and the spaces
echo # because sometimes extra trailing newlines get auto-trimmed
fi
fi
fi
# errors reflect on the script's exit status
if [[ $help == "error" ]]; then exit 1; fi
elif [[ $1 == "line" ]]; then
# use it to dev commands with (before adding them to the $evalist)
shift # removes line from the argv
line=$($script "$@")
if oneline "$line" "$@" ; then
echo "$line" # the command to be
fi
elif contains "$evalist" "$1" ; then
# `$script <command> ...` writes a string to stdout - to eval
command=$($script "$@")
oneline "$command" "$@"
cwd
eval "$command"
else
# delegate the rest
cwd
$script "$@"
fi
<file_sep>#!/usr/bin/env node
console.log("Ran bonumeant with bin/bonvars.sh and bon help shown below...\n")
<file_sep>#!/usr/bin/env batshit
load ../node_modules/batshit/bin/batshit-helpers
setup() {
cd test/configuration
}
@test "defaults + bin/bonvars.sh" {
run bonumeant
assert_success
assert_output_contains "bonumeant with bin/bonvars.sh"
assert_output_contains "https://github.com/orlin/bon"
}
@test "bonbond define #commander command" {
run bonbond define
assert_success
assert_output_contains "bonbond is bond.coffee via bond.sh bon"
}
@test "bonbond --help #commander's + custom text" {
# notice how bon enables more ways to get help
run bonbond -?
assert_success
assert_output_contains "made to illustrate use of bon"
}
@test "bonbond #same as bonbond --help" {
# because BON_HELP is set, no args causes --help
run bonbond
assert_success
assert_output_contains "made to illustrate use of bon"
}
@test "bonbond four #produces a command to auto-eval" {
run bonbond four
assert_success
assert_output "4"
}
@test "bonbond line four #gives the one-line command, skipping the auto-eval" {
run bonbond line four
assert_success
assert_output "echo here are four words | wc -w | tr -d ' '"
}
@test "bonbond multi #produces a multi-line string that can't auto-eval" {
run bonbond multi
assert_failure
assert_output_contains "yield exactly one line to eval, exiting instead"
}
@test "bonbond # run from a wrong place and no NODE_PATH, yet guessed ok" {
pushd ..
export NODE_PATH=""
run bonbond
assert_success
# the $NODE_PATH used to be required for tests to pass
# assert_failure
# assert_output_contains "path is not the root directory of bonumeant"
popd
}
<file_sep># bon -- bash on node [](https://travis-ci.org/orlin/bon)
This is a bash meta-cli script that helps run node.js or any other cli scripts.
It can publish your scripts on npm, whatever programming language they are written in.
Furthermore it provides convenience [features](#features) such running the script
from its packaged source code path in case it needs some extra files, modules, etc.
[](https://www.npmjs.org/package/bon)
## Why
Node.js is great for cli scripts. Sometimes bash is an easier fit.
This script is great for running commands generated by another script / cli.
It pretends to be the script it delegates to. It also changes directory
before running the target script, assuming its identity and source location.
The former helps with commands that need being run in a tty shell / context,
for example if the target cli generated an ssh connection / command string.
The latter, for any extra files the script may need, such as configuration.
The above reasons came from hacking this [`daps`](https://github.com/orlin/daps)
use case. Time went on, and `bon` proved useful for packaging other programs:
* [datomic-free](https://github.com/datomicon/datomic-free)
* [batshit](https://github.com/orlin/batshit)
* etc.
Here're the [npm dependents](https://www.npmjs.com/browse/depended/bon) so far.
## Use
Bon works well when paired with node.js cli scripts. It makes use of, or guesses,
the `$NODE_PATH` to `cd` into the target module's source directory.
Being packaged as a module itself helps with making it a dependency.
It offers convenient *convention over configuration* with node.js assumptions.
The target script needs not implement any commands / options - nor parse args.
That would mean most of the features remain unused, except for the path / check.
With each use case, `bon` got better. Take a look at [features](#features).
An increasing number of things can be configured: get a custom temp `$PATH`,
run the implementations from anywhere, etc.
### Install
In order to run your commands from anywhere, install `bon` globally with
`npm i -g bon`. If you want to make this automatic, just put `bon` in
your project's dependencies and this will be taken care of - thanks to
[install-g](https://github.com/orlin/install-g).
Of-course, your bon-enabled module should also be installed globally
so that its cli scripts can be found on the $PATH. Again, [install-g](https://github.com/orlin/install-g) can ensure that.
### Convention
Naming the script command the same as its module name is expected as default.
Suppose your module is called `clier`, the entry in `package.json` should be
`"bin": { "clier" : "./node_modules/.bin/bon" }`, which looks for
`bin/clier.js`. JavaScript is the default language, making the majority happy.
If CoffeeScript is preferred, just put the following code in it:
```js
#!/usr/bin/env node
require('coffee-script/register')
require('./clier.coffee')
```
Here is [an example](https://github.com/orlin/bon/tree/active/test/convention).
### Configuration
There are config vars that override `bon`'s defaults.
If bon is exclusively paired with a single node script,
exporting them to the shell environment is fine,
certainly fine to first try it this way.
The easier option for serious work is to have the vars set with the aid of
`bin/bonvars.sh` - bon will source it, making available whatever is `export`ed.
This comes with limitations. There can only be one bin script in `package.json`
that has to be named same as the module and again `bin/<name>.js` presence
is expected. There are very few vars that can be customized - `BON_EVALIST`
and `BON_HELP` come to mind.
To customize anything, including all the paths / file names, refer to your own
script in `package.json` - e.g. `"bin": { "clirest" : "./bin/clier.sh" }`, and
source bon with it. Here is how that is done:
```bash
#!/usr/bin/env bash
BON_NAME="clier" # must match module's name
BON_EXT="coffee" # $BON_SCRIPT would be "./bin/clier.coffee"
BON_SCRIPT="./bin/cli.coffee" #any path - ignoring BON_NAME and BON_EXT
source bon "$@" # provided bon is installed globally
```
The [configuration](https://github.com/orlin/bon/tree/active/test/configuration)
project contains some examples - testing what is described above as well as
illustrating use of the features below.
## Features
### Path Check
By default bon checks if it changed directory to the right place.
It assumes there is a `package.json` with its `name` matching `$BON_NAME`.
Perhaps your script is not a node.js one. Check any `$BON_CHECK_FILE`,
perhaps set to "README.md", and provide a `$BON_CHECK_GREP`
text or regex to match / verify with.
If you choose to trust where bon takes you to,
or else if your script is location-independent - then
set `BON_CHECK="no"`, and the path check will be skipped.
### Working Directory
By default `bon` runs in the directory of its globally-installed module
implementation. However many scripts work best from a current directory.
Setting $`BON_CWD='.'` will do just that - `cd $(pwd)` before running
a bon-wrapped script. Of-course `$BON_CWD` can be an absolute path too.
### `$PATH` Changing
It is possible to temporarily change the `$PATH` for a bon-enabled script so that
files relative to it would have precedence over system-wide installations.
Just set `$BON_PRE_PATH` to '.' (for the module's directory), or any path
relative to it.
See my [`bats` wrapper](https://github.com/orlin/batshit/blob/active/bin/batshit.sh)
for an example of both `$BON_CWD` and `$BON_PRE_PATH` use.
### Meta Commands
This was the reason bon was created to begin with.
Set `$BON_EVALIST` to a list of space-separated commands.
These are commands that generate commands to to be `eval`led.
The `$BON_EVALIST` perhaps could be shared among scripts via global `export`,
thus it would be possible to skip configuration in favor of convention.
The generated commands are verified to be *one line* long.
This is to prevent accidental errors that may cause damage.
A trailing `\n` is ok, even several trailing newlines are ok -
bash simply ignores it as a feature.
To develop commands with the target script, and skip the eval, run
`<cli> line <evalgen> ...` where `<evalgen>` is a meta-command that is
being developed as part of a <cli> and `...` are some optional args it may take.
### Help
Set `$BON_HELP` to whatever option or command is to be used in place of no args.
For example `export BON_HELP="--help"` will turn a bon-enabled `<command>`
into `<command> --help`, as well as enable `command -?` to have the same effect.
If you want to show just `bon`'s help when calling your bin script without args,
use `BON_HELP=" "` - the empty space doesn't affect the target - no help option.
Even if the target has a help option, here it would have to be passed explicitly.
If you want to show your own help text instead of bon's default, set
`$BON_HELP_FILE` to a text file path, relative to the project's root directory.
## Test [](https://travis-ci.org/orlin/bon)
[BATS](https://github.com/sstephenson/bats) is used for testing via
[batshit](https://github.com/orlin/batshit).
Do `npm run preptest` once, so that `npm test` will work.
## LICENSE
This is free and unencumbered public domain software.
For more information, see [UNLICENSE](http://unlicense.org).
<file_sep>#!/usr/bin/env batshit
load ../node_modules/batshit/bin/batshit-helpers
@test "coventional implementation + coffee-script" {
cd test/convention && run bonvent
assert_success
assert_output "bonvented"
}
<file_sep>#!/usr/bin/env bash
# Vars that are exported will show in `process.env` of the target `node` script.
# Either way is fine with bon.
export BON_NAME="bonumeant"
export BON_SCRIPT="bin/bonbond"
export BON_HELP="--help"
export BON_HELP_FILE="bin/bond.help.txt" # matching commander's `--help` style
export BON_EVALIST="four multi"
source bon "$@"
<file_sep>#!/usr/bin/env bash
if [[ -n "$NODE_PATH" ]]; then
echo $NODE_PATH
else
temp=$(dirname $(which bon))
echo ${temp//bin/lib\/node_modules}
fi
<file_sep>#!/usr/bin/env node
require('coffee-script/register')
require('./bonvent.coffee')
<file_sep>#!/usr/bin/env batshit
load ../node_modules/batshit/bin/batshit-helpers
@test "bon by itself does not do anything" {
run bon
assert_failure
assert_output_contains "Bon needs target implementation."
assert_output_contains "See https://github.com/orlin/bon"
}
@test "bon is available globally, thanks to install-g" {
pushd ..
run which bon
assert_success
assert_output_contains "/bon"
popd
}
<file_sep>export BON_HELP=" "
| 14b0a9648e516c3dbbf1d47310ab3a4a6a0eb288 | [
"JavaScript",
"Markdown",
"Shell"
]
| 11 | Shell | orlin/bon | 1c040b8c43af9e4d1b6aa97a7b4dc71534f63580 | 9c78b82cecde177cdb859a24e54db7f07c35d4f9 |
refs/heads/master | <file_sep>import { Component } from '@angular/core';
import {Router} from '@angular/router';
import {UserService} from './user/user.service';
import {User} from './user/User';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [
UserService
]
})
export class AppComponent {
users: User[];
title = 'app';
constructor(private router: Router,
private userService: UserService) {
this.users = userService.getUsers();
}
toProductInfo() {
this.router.navigate(['/product', 4]);
}
}
<file_sep>/**
* Created by wangxiao on 17-6-2.
*/
export class User {
constructor(
private name: string,
private age: number,
private email: string
) {}
}
<file_sep>/**
* Created by wangxiao on 17-6-2.
*/
<file_sep>/**
* Created by wangxiao on 17-6-2.
*/
import {User} from '../user/User';
export let Users: User [] = [
new User('name1', 21, '<EMAIL>'),
new User('name2', 22, '<EMAIL>'),
new User('name3', 23, '3333333333<EMAIL>'),
]
| 767d611f3178fb870a63fac617d0d2caa3720e59 | [
"TypeScript"
]
| 4 | TypeScript | sabrinaeva/angular4.0 | f7cf947ec55d40a7e8f25503e4b4d798a1f9a405 | 7cbb21a2325061957fc11454dbf35cdc2e0b0e67 |
refs/heads/master | <repo_name>ITS-UofIowa/desmoines.uiowa.edu<file_sep>/modules/custom/dsm_common/dsm_common.features.field_instance.inc
<?php
/**
* @file
* dsm_common.features.field_instance.inc
*/
/**
* Implements hook_field_default_field_instances().
*/
function dsm_common_field_default_field_instances() {
$field_instances = array();
// Exported field_instance: 'node-page-field_fancy_title'.
$field_instances['node-page-field_fancy_title'] = array(
'bundle' => 'page',
'default_value' => array(
0 => array(
'value' => 0,
),
),
'deleted' => 0,
'description' => 'Check this box to display a gold line below the page title.',
'display' => array(
'default' => array(
'label' => 'above',
'settings' => array(),
'type' => 'hidden',
'weight' => 1,
),
'teaser' => array(
'label' => 'above',
'settings' => array(),
'type' => 'hidden',
'weight' => 0,
),
),
'entity_type' => 'node',
'field_name' => 'field_fancy_title',
'label' => 'Fancy title',
'required' => 0,
'settings' => array(
'user_register_form' => FALSE,
),
'widget' => array(
'active' => 1,
'module' => 'options',
'settings' => array(
'display_label' => 1,
),
'type' => 'options_onoff',
'weight' => 4,
),
);
// Exported field_instance: 'paragraphs_item-snp_card-field_snp_card_link'.
$field_instances['paragraphs_item-snp_card-field_snp_card_link'] = array(
'bundle' => 'snp_card',
'default_value' => NULL,
'deleted' => 0,
'description' => 'Enter a full URL or <a href="https://its.uiowa.edu/support/article/106421">internal path (like <em>node/NID</em>)</a> to wrap the title and image of this card in a link.',
'display' => array(
'default' => array(
'label' => 'hidden',
'module' => 'link',
'settings' => array(),
'type' => 'link_default',
'weight' => 3,
),
'paragraphs_editor_preview' => array(
'label' => 'above',
'settings' => array(),
'type' => 'hidden',
'weight' => 0,
),
'view_mode_selector' => array(
'label' => 'above',
'settings' => array(),
'type' => 'hidden',
'weight' => 0,
),
),
'entity_type' => 'paragraphs_item',
'field_name' => 'field_snp_card_link',
'label' => 'Link',
'required' => 0,
'settings' => array(
'absolute_url' => 1,
'attributes' => array(
'class' => '',
'configurable_class' => 0,
'configurable_title' => 0,
'rel' => '',
'target' => 'default',
'title' => '',
),
'display' => array(
'url_cutoff' => 80,
),
'enable_tokens' => 0,
'rel_remove' => 'default',
'title' => 'none',
'title_label_use_field_label' => 0,
'title_maxlength' => 128,
'title_value' => '',
'url' => 0,
'user_register_form' => FALSE,
'validate_url' => 1,
),
'widget' => array(
'active' => 0,
'module' => 'link',
'settings' => array(),
'type' => 'link_field',
'weight' => 2,
),
);
// Translatables
// Included for use with string extractors like potx.
t('Check this box to display a gold line below the page title.');
t('Enter a full URL or <a href="https://its.uiowa.edu/support/article/106421">internal path (like <em>node/NID</em>)</a> to wrap the title and image of this card in a link.');
t('Fancy title');
t('Link');
return $field_instances;
}
| bc483e676f6e720ad132651a8f429379a9b19853 | [
"PHP"
]
| 1 | PHP | ITS-UofIowa/desmoines.uiowa.edu | 2b11f2f63854a5e8626c6323924a9a06a8bb2189 | 67e51830b7127ec3e5fe5bc1e7189ad8187190b3 |
refs/heads/master | <file_sep>export default [
{
time: "Winter 2018",
company: "flashback music",
description: "An Android app made during CSE 110 - an app that plays music downloaded from an online database and dynamically creates a flashback playlist based on friends and user's activity.",
skill: ["Java", "Android", "Android Studio", "Firebase"],
},
{
time: "Fall 2017",
company: "dt_rnn",
description: "A final project for COGS 181 - a small recurrent neural network that reads Trump tweets sourced from the Trump Twitter Archive and produces tweets based on the data.",
skill: ["Python", "Jupyter Notebook", "charr-rnn-tensorflow", "torch-rnn"],
href: "https://github.com/vdibs/dt_rnn",
},
{
time: "Summer 2017",
company: "prototypr",
description: "A Drag and Drop React Prototype Builder intended to decrease the iteration time between designers and developers. It enables users to drag and drop components on a page and generate the React code dynamically, allowing the design and code to be passed around and altered both easily and efficiently.",
skill: ["React", "Redux", "react-dnd", "JS", "HTML", "Jest"],
},
{
href: "http://valentinadibs1.herokuapp.com",
time: "Winter 2017",
company: "This site + The Old Version",
description: "The old version of this site is at valentinadibs1.herokuapp.com. Both sites were made with React. ",
skill: ["React", "JS", "HTML", "CSS"],
},
{
href: "https://gentle-springs-89276.herokuapp.com/",
time: "Fall 2016",
company: "Actemotion",
description: "A personal informatics site that allows users to track their emotions in relation to their activities. It allows users to make important life decisions based on data instead of mood.",
skill: ["React", "JS", "HTML", "CSS", "Google Analytics"],
},
{
time: "Summer 2016",
company: "WordPress Plugin: Recent Related Posts",
description: "A Plugin made with the WordPress API during my summer 2016 internship. It displays 5 recent posts that share the same category or tag of the current post at the bottom of the page.",
skill: ["WordPress API", "PHP", "JS", "HTML", "SCSS"],
},
{
time: "Winter 2016",
company: "2048",
description: "Recreated the game 2048 in java.",
skill: ["Java", "Java GUI"],
},
];<file_sep>import React, { Component } from "react";
import "./App.css";
import { Grid, Col, Row } from "react-bootstrap";
import Work from "./components/Work";
import Project from "./components/Project";
import Contact from "./components/Contact";
import Home from "./components/Home";
import Scroll from 'react-scroll-to-element';
import Sticky from 'react-sticky-el';
const selected = {
borderBottom: "solid",
borderWidth: 1,
borderColor: "orange",
padding: "0px 6px 10px 6px",
}
const unselected = {
padding: "0px 6px 10px 6px",
}
function scrollTo(selected) {
document.querySelector(selected).scrollIntoView({behavior: 'smooth'});
}
class App extends Component {
constructor() {
super();
this.state = {
show: Home,
};
}
render() {
const Component = this.state.show;
return (
<div className="App" id="home-page">
<link
href="https://fonts.googleapis.com/css?family=Noto+Serif|Inconsolata:400,700|Bitter"
rel="stylesheet"
type="text/css"
/>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"
/>
<h1 className="name"><NAME></h1>
<Sticky className="toolbar">
<div
className="linkTo"
onClick={() => this.setState({ show: Home })}
style = { Component === Home ? selected : unselected }
>
<Scroll type="id" element="home-page" offset={-62}><div style={{ cursor: "pointer" }}>Home</div></Scroll>
</div>
<div
className="linkTo"
onClick={() => this.setState({ show: Work })}
style = { Component === Work ? selected : unselected }
>
<Scroll type="id" element="work-page" offset={-62}><div style={{ cursor: "pointer" }}>Work</div></Scroll>
</div>
<div
className="linkTo"
onClick={() => this.setState({ show: Project })}
style = { Component === Project ? selected : unselected }
>
<Scroll type="id" element="project-page" offset={-62}><div style={{ cursor: "pointer" }}>Projects</div></Scroll>
</div>
<div
className="linkTo"
onClick={() => this.setState({ show: Contact })}
style = { Component === Contact ? selected : unselected }
>
<Scroll type="id" element="contact-page" offset={-62}><div style={{ cursor: "pointer" }}>Contact</div></Scroll>
</div>
<hr className="toolbar-separator" />
</Sticky>
<Home id="home-page" />
</div>
);
}
}
export default App;
<file_sep>## vdibs.github.io<file_sep>import React, {Component} from 'react';
import FontAwesome from 'react-fontawesome';
import { Grid, Row, Col } from "react-bootstrap";
class Contact extends Component {
render() {
return (
<div className="contactContainer" id={this.props.id}>
<div className="page-title">Contact</div>
<p>Let's connect!</p>
<Grid>
<Row>
<Col xs={0} sm={0} md={2} lg={2} />
<Col xs={12} sm={12} md={2} lg={2}>
<a
className="contactLink"
href="https://docs.google.com/a/ucsd.edu/document/d/1uXYQSxyApiBn4YlyilhEBaNWTyy7GoiLNjElhbUk1tc/edit?usp=sharing" >
<FontAwesome
className="icon"
name='pencil-square'
size='lg' />
<p className="iconName">Resume</p>
</a>
</Col>
<Col xs={12} sm={12} md={3} lg={2}>
<a
className="contactLink"
href="https://www.linkedin.com/in/valentina-dibs/">
<FontAwesome
className="icon"
name='linkedin-square'
size='lg' />
<p className="iconName">LinkedIn</p>
</a>
</Col>
<Col xs={12} sm={12} md={2} lg={2}>
<a
className="contactLink"
href="https://github.com/vdibs">
<FontAwesome
className="icon"
name='github-square'
size='lg' />
<p className="iconName">GitHub</p>
</a>
</Col>
<Col xs={12} sm={12} md={2} lg={2}>
<a
className="contactLink"
href="mailto:tina.<EMAIL>">
<FontAwesome
className="icon"
name='envelope-square'
size='lg' />
<p className="iconName">Email</p>
</a>
</Col>
</Row>
</Grid>
</div>
);
}
}
export default Contact;<file_sep>import React, { Component } from 'react';
import '../App.css';
import { Col, Row } from "react-bootstrap";
import Work from './Work.js';
import Project from './Project.js';
import Contact from './Contact.js';
class Home extends Component {
render() {
return (
<div className="homeContainer">
<Row>
<Col xs={0} sm={0} md={1} lg={1} />
<Col className="headshotContainer" xs={12} sm={12} md={3} lg={3} >
<img className="headshotImg" alt={"headshot"} src={require('../img/head.jpg')} width={200} height={200}/>
</Col>
<Col xs={12} sm={12} md={7}lg={7}>
<p className="greeting">Hello! I’m <NAME>.</p>
<p style={{paddingTop: 5}}>
I am a 4th year at UC San Diego where I study Computer Science and Cognitive Science with a
specialization in HCI.
</p>
<p style={{paddingTop: 5}}>
I like to get lost in a project. When I'm not at the computer I find myself dreaming (literally) about that
one coding problem that I'm trying to fix. Problem solving and perseverance are my go to.
</p>
<p style={{paddingTop: 5, paddingBottom: 20}}>
I’m also a hobbyist. I love to create (code, sing, knit, sew), listen to podcasts
(NPR politics + Ted Radio Hour), read (just started One Hundred Years of Solitude), and exercise (bouldering and weight lifting).
</p>
</Col>
<Col xs={0} sm={0} md={1} lg={1} />
</Row>
<hr id="work-page" className="page-separator" />
<Work />
<hr id="project-page" className="page-separator" />
<Project />
<hr className="page-separator"id="contact-page" />
<Contact />
<hr style={{borderColor: "white"}} />
</div>
);
}
}
export default Home; <file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import Project from './components/Project';
import { Helmet } from "react-helmet";
import { BrowserRouter as Router, Route } from 'react-router-dom';
ReactDOM.render(
<div>
<Helmet>
<meta charset="utf-8" />
<title><NAME></title>
<meta name="description" content="<NAME>' personal professional site. UCSD student and incoming Software Engineer at Reddit." />
<meta name="keywords" content="<NAME>, student, intern, web developer, software engineer, UCSD, React" />
<meta name="author" content="<NAME>" />
</Helmet>
<Router>
<div>
<Route exactpath="/" component={App} />
<Route path="/project" component={Project} />
</div>
</Router>
</div>,
document.getElementById('root')
);
<file_sep>export default [
{
time: "Fall 2018",
company: "Reddit",
position: "Software Engineer - New Grad",
href: "https://www.reddit.com/",
description: "Incoming New Grad Software Engineer on the community experiences team at Reddit, starting in Fall 2018!",
skill: ["React", "Redux", "Python"],
img: require('../img/reddit_logo.png'),
},
{
time: "Fall 2017 - Spring 2018",
company: "CAIDA - Center for Applied Internet Data Analysis and ASRank",
position: "Webmaster Assistant and Software Engineer Internet",
href: "https://www.caida.org/",
description: "Kept Caida updated and improved search functionality and created path pages on ASRank (http://as-rank.caida.org)",
skill: ["Javascript", "Python", "WordPress", "php", "xml"],
img: require('../img/caida_logo.png'),
},
{
time: "Summer 2017",
company: "TrueCar",
position: "Software Engineer Intern",
href: "http://truecar.com",
description: "Built Prototypr, a drag and drop React app that enables users to create prototypes and dynamically generate React code. It uses TrueCar's boilerplate Gluestick and their component library Battery Pack. I worked with a makeshift Prototyper team that consisted of a Manager, Product Lead, a UX Lead, and a Front End Tech Lead for reference.",
skill: ["React", "Redux", "react-dnd", "JS", "HTML", "Ruby on Rails"],
img: require("../img/truecar_logo.jpg"),
},
{
time: "Winter/Spring 2017",
company: "TruMed Systems",
position: "Software Engineer Intern",
href: "http://trumedsystems.com",
description: "Wrote a batch script to automate prereleases on Github using the GitHub API.\n Developed the AccuVax interface in C#, .Net, and MVVM pattern.",
skill: ["Batch Script", "CI", "TeamCity", "Unit Testing"],
img: require("../img/tms_logo.png"),
},
{
time: "Summer 2016",
company: "<NAME>: Investors Business Daily",
position: "Web Development Intern",
href: "http://investors.com",
description: "Developed investors.com with WordPress and built a Recent Related Posts plugin with the WordPress API.",
skill: ["WordPress", "PHP", "HTML", "CSS", "JS"],
img: require("../img/ibd_logo.png"),
}
]; | 20d7a9f72e7f2938ebaff6a91806ef1560b3bae9 | [
"JavaScript",
"Markdown"
]
| 7 | JavaScript | vdibs/vdibs | 64211c00a142be7d9880fb8d9f191cd3cd924df5 | f508d495a4acb6a3d7dbcd47d7760261650fbde2 |
refs/heads/master | <repo_name>nbiton/bugzilla-customisation<file_sep>/deploy.sh
#!/bin/bash
curl -o /usr/local/bin/ecs-cli https://s3.amazonaws.com/amazon-ecs-cli/ecs-cli-linux-amd64-v0.6.6 && chmod +x /usr/local/bin/ecs-cli
/usr/local/bin/ecs-cli configure -c master -p lmb-dev -r ap-southeast-1
test -f aws-env && source aws-env
envsubst < AWS-docker-compose.yml > docker-compose-bugzilla.yml
envsubst < AWS-docker-compose-meteor.yml > docker-compose-meteor.yml
#ecs-cli compose -p meteor -f docker-compose-meteor.yml service create --target-group-arn arn:aws:elasticloadbalancing:ap-southeast-1:192458993663:targetgroup/meteor/96a08bd201369039 --container-name meteor --container-port 80 --role ecsServiceRole
#ecs-cli compose -p bugzilla -f docker-compose-bugzilla.yml service create --target-group-arn arn:aws:elasticloadbalancing:ap-southeast-1:192458993663:targetgroup/bugzilla/48050fbe08e545a3 --container-name bugzilla --container-port 80 --role ecsServiceRole
/usr/local/bin/ecs-cli compose -p meteor -f docker-compose-meteor.yml service up
#/usr/local/bin/ecs-cli compose -p bugzilla -f docker-compose-bugzilla.yml service up
<file_sep>/start
#!/bin/sh -e
# Set up bugzilla and run apache2
envsubst < /etc/msmtprc.temp > /etc/msmtprc
cd /opt/bugzilla
# Substitute values into bugzilla localconfig
sed --in-place -f - localconfig <<SED
s/db_host *= *'[a-zA-Z0-9.]\+'/db_host = '${MYSQL_HOST}'/
s/db_port *= *[0-9.]\+/db_port = ${MYSQL_PORT}/
s/db_name *= *'[a-zA-Z0-9.]\+'/db_name = '${MYSQL_DATABASE}'/
s/db_user *= *'[a-zA-Z0-9.]\+'/db_user = '${MYSQL_USER}'/
s/db_pass\s*=\s*'[^']*'/db_pass = '${MYSQL_PASSWORD}'/
s/webservergroup *= *'[a-zA-Z0-9]\+'/webservergroup = 'www-data'/
SED
# Verify bugzilla setup
./checksetup.pl bugzilla_admin
curl -o /opt/bugzilla/data/params.json ${PARAMS_URL}
# Start apache2
. /etc/apache2/envvars
/usr/sbin/apache2 -D FOREGROUND
<file_sep>/deploy-prod.sh
#!/bin/bash
/usr/local/bin/ecs-cli configure -c master -p lmb-prod -r ap-southeast-1
test -f aws-env.prod && source aws-env.prod
envsubst < AWS-docker-compose.yml > docker-compose-bugzilla.yml
envsubst < AWS-docker-compose-meteor.yml > docker-compose-meteor.yml
#ecs-cli compose -p meteor -f docker-compose-meteor.yml service create --target-group-arn arn:aws:elasticloadbalancing:ap-southeast-1:192458993663:targetgroup/meteor/96a08bd201369039 --container-name meteor --container-port 80 --role ecsServiceRole
#ecs-cli compose -p bugzilla -f docker-compose-bugzilla.yml service create --target-group-arn arn:aws:elasticloadbalancing:ap-southeast-1:192458993663:targetgroup/bugzilla/48050fbe08e545a3 --container-name bugzilla --container-port 80 --role ecsServiceRole
/usr/local/bin/ecs-cli compose -p meteor -f docker-compose-meteor.yml service up
#/usr/local/bin/ecs-cli compose -p bugzilla -f docker-compose-bugzilla.yml service up
<file_sep>/docker-compose.yml
version: '2'
services:
bugzilla:
image: uneet/bugzilla-customisation
restart: on-failure
ports:
- 8081:80
environment: # Setup by local .env file
SES_SMTP_USERNAME: ${SES_SMTP_USERNAME}
SES_SMTP_PASSWORD: ${SES_SMTP_PASSWORD}
SES_VERIFIED_SENDER: ${SES_VERIFIED_SENDER}
MYSQL_HOST: ${MYSQL_HOST}
MYSQL_PORT: ${MYSQL_PORT}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_<PASSWORD>}
PARAMS_URL: ${PARAMS_URL}
depends_on:
- db
volumes:
- ./custom:/opt/bugzilla/template/en/custom
- ./skin:/opt/bugzilla/skins/contrib/skin
networks:
- network
db:
image: mariadb
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: ${<PASSWORD>}
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${<PASSWORD>}
volumes:
- ./mariadb:/var/lib/mysql
- ./sql:/docker-entrypoint-initdb.d
networks:
- network
adminer:
image: adminer
ports:
- 8082:8082
depends_on:
- db
networks:
- network
meteor:
image: ulexus/meteor
ports:
- "8080:80"
networks:
- network
environment:
- BUNDLE_URL=https://unee-t-media.s3-accelerate.amazonaws.com/2017-08-31/unee-t-fe.tar.gz
- ROOT_URL=http://local.unee-t.com
- BUGZILLA_URL=http://bugzilla
- BUGZILLA_ADMIN_KEY=<KEY>99
- MONGO_URL=mongodb://mongo:27017/mydatabase
mongo:
image: mongo
ports:
- "27017:27017"
networks:
- network
networks:
network:
driver: bridge
<file_sep>/README.md
Requires [docker](https://www.docker.com/) &
[docker-compose](https://docs.docker.com/compose/). Linux is definitely a plus!
# Development servers
* [Bugzilla](https://dev.dashboard.unee-t.com)
* [Meteor](https://dev.case.unee-t.com)
* db.dev.unee-t.com
# Production servers
* [Bugzilla](https://dashboard.unee-t.com)
* [Meteor](https://case.unee-t.com)
* db.prod.unee-t.com
# Run
make up
make down
You might need to do a `make ${up,down,up}` to make it all work due to the
setup phases of {bugzilla,db} being a bit difficult to co-ordinate with docker compose.
# Login info
If you are using the default primed sql/demo state username;password are:
<EMAIL>;administrator
<EMAIL>;anabelle
<EMAIL>;celeste
<EMAIL>;jocelyn
<EMAIL>;lawrence
<EMAIL>;leonel
<EMAIL>;marina
<EMAIL>;marley
<EMAIL>;marvin
<EMAIL>;michael
<EMAIL>;regina
<EMAIL>;sabrina
Else if not sql/demo see [bugzilla_admin](bugzilla_admin)
# Debug
docker exec -it docker_bugzilla_1 /bin/bash
The prefix `docker_` might be different on your system.
# Database explorer
http://localhost:8082/ see [environment](.env) for credentials
# JSON API
<https://bugzilla.readthedocs.io/en/latest/api/>
curl http://localhost:8081/rest/bug/1 | jq
Or upon the dev server:
curl -s https://dev.unee-t.com/rest/bug/1?api_key=<KEY> | jq
# Build
You shouldn't need to do this since normally we should use out gitlab hosted Bugzilla image.
make build
# Environment
Secrets are managed in [AWS's parameter
store](https://ap-southeast-1.console.aws.amazon.com/ec2/v2/home?region=ap-southeast-1#Parameters:sort=Name).
Assuming the profiles `lmb-dev` is setup for development AWS account
8126-4485-3088 and `lmb-prod` for 192458993663, the `aws-env` and
`aws-env.prod` will be sourced and [aws-cli will fetch the secrets](https://github.com/aws/aws-cli/issues/2950).
* MONGO_PASSWORD
* MYSQL_PASSWORD
* SES_SMTP_PASSWORD
* BUGZILLA_ADMIN_KEY
`SES*` is required for email notifications. [SES dashboard](https://us-west-2.console.aws.amazon.com/ses/home?region=us-west-2#dashboard:)
How to test if email is working:
echo -e "Subject: Test Mail\r\n\r\nThis is a test mail" | msmtp --debug -t <EMAIL>
Video about testing email: https://s.natalian.org/2017-10-27/uneetmail.mp4
# State snapshots
Save:
mysqldump -h 127.0.0.1 -P 3306 -u root --password=uniti bugzilla > demo.sql
Restore:
mysql -h 127.0.0.1 -P 3306 -u root --password=uniti bugzilla < fresh.sql
To restore on dev server:
mysql -h db.dev.unee-t.com -P 3306 -u root --password=SECRET bugzilla < demo.sql
# How to check for mail when in test mode
docker exec -it bugzilla_bugzilla_1 /bin/bash
cat data/mailer.testfile
# AWS ECS setup
Cluster is named after branch name.
ecs-cli configure -c $BRANCH -r ap-southeast-1 -p $PROFILE
ecs-cli up --vpc vpc-efc2838b --subnets subnet-846169e0,subnet-cf7b46b9 --instance-type t2.medium --capability-iam --keypair hendry
For production:
ecs-cli up --vpc vpc-b93070dd --subnets subnet-9ae9e1fe,subnet-fcffc28a --instance-type t2.medium --capability-iam --keypair hendry,franck
Refer to `ecs-cli compose service create -h` to create with a load balancer.
* [Development account](https://812644853088.signin.aws.amazon.com/console)
* [Production account](https://192458993663.signin.aws.amazon.com/console)
<file_sep>/Makefile
validate:
docker-compose -f docker-compose.yml config
build:
docker build -t uneet/bugzilla-customisation .
up:
docker-compose up
down:
docker-compose down
pull:
docker-compose pull
mysqlogin:
mysql -h 127.0.0.1 -P 3306 -u root --password=<PASSWORD> bugzilla
clean:
sudo rm -rf mariadb
| 6c3f3e9867012ee4a099ff634e2e9562a4626bd1 | [
"Markdown",
"Makefile",
"YAML",
"Shell"
]
| 6 | Shell | nbiton/bugzilla-customisation | b77dd99a2e6b6edc34497b020406d682ccc12536 | cd42c08f16dbd6fd67c67c15f6e41545a657a7a4 |
refs/heads/master | <file_sep>docker build -t jorge00alves/multi-client:latest -f ./client/Dockerfile ./client
docker build -t jorge00alves/multi-server:latest -f ./server/Dockerfile ./server
docker build -t jorge00alves/multi-worker:latest -f ./worker/Dockerfile ./worker
docker push jorge00alves/multi-client:latest
docker push jorge00alves/multi-server:latest
docker push jorge00alves/multi-worker:latest
kubectl apply -f k8s
kubectl rollout restart deployments/client-deployment
kubectl rollout restart deployments/server-deployment
kubectl rollout restart deployments/worker-deployment | d026238d9522c809a53001b8efbf5ef264d00a3f | [
"Shell"
]
| 1 | Shell | jorgealves1986/multi-k8s | 82d32e50cda7b6191c0ea6b5ce9493d4e94731a5 | d4aa7edd769c7bafa3df16ceed101f18622a52b5 |
refs/heads/master | <file_sep>class Item < ApplicationRecord
belongs_to :user
belongs_to :category
# belongs_to :brand
has_many :images
# has_many :comments
end
| 050581337c651c7e0316c3b0b753518a76d58d3f | [
"Ruby"
]
| 1 | Ruby | aquarius25/mercari-38-weekend | 3b5bccb5147e886e09f9770a8048c8f3189b3607 | 027e4f0692fa56857b5003a8087b0929ad743b4c |
refs/heads/master | <repo_name>urbanambroz/ReactApp<file_sep>/src/App.js
import React, {Component} from 'react';
import {DrawerAppContent} from "@material/react-drawer";
import {TopAppBarFixedAdjust} from '@material/react-top-app-bar';
import MaterialIcon from '@material/react-material-icon';
import './App.css';
import 'popper.js';
import 'jquery';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Fab} from "@material/react-fab";
import {AppBar} from "./components/AppBar";
import {LeftHandDrawer} from "./components/LeftHandDrawer";
import {LoginDialog} from "./components/LoginDialog";
import {LoginContext, UserData} from './LoginContext';
import {Snackbar} from "@material/react-snackbar";
import {HomePage} from "./pages/HomePage";
import {NewPage} from "./pages/NewPage";
import {BrowserRouter, Link, Route, Switch} from "react-router-dom";
import Card, {CardActions, CardPrimaryContent} from "@material/react-card";
import {Button} from "@material/react-button";
export default class App extends Component {
state = {
selectedIndex: 0,
open: false,
activeIndex: 0,
signedInUser: UserData,
loginDialogOpen: true,
mainContent: 'We are displaying CheckOut data.',
openSnack: false
};
render() {
return (
<LoginContext.Provider value={this.state.signedInUser}>
<BrowserRouter>
<div className='mdc-typography drawer-container'>
<LeftHandDrawer open={this.state.open} selectedIndex={this.state.selectedIndex} title={'CoCi'}
handleSelect={(index) => {
this.setState({selectedIndex: index});
}}/>
<DrawerAppContent className='drawer-app-content'>
<AppBar open={this.state.open}
handleDrawerToggle={(open) => this.setState({open: open})}
logoutCallback={(user) => this.setState({signedInUser: user})}
loginCallback={() => {
this.setState({loginDialogOpen: true})
}}/>
<TopAppBarFixedAdjust>
<LoginDialog user={this.state.signedInUser} isOpen={this.state.loginDialogOpen}
loginCallback={(user) => this.setState({signedInUser: user})}
onClose={() => {
this.setState({loginDialogOpen: false});
}}/>
<div className="container" id='mainContainer' onClick={() => {
this.setState({open: false})
}}>
<div id='pageHolder' className='py-3'>
<Switch>
<Route path="/" exact component={HomePage}/>
<Route path="/newPage" component={NewPage}/>
<Route component={NoMatch}/>
</Switch>
</div>
<Fab icon={<MaterialIcon icon='add'/>} mini className='app-fab--absolute'
style={{bottom: '6rem'}}/>
<Fab icon={<MaterialIcon icon='autorenew'/>} className='app-fab--absolute'/>
<Snackbar open={this.state.openSnack} message='I was displayed!'
actionText='Close me!'
onClose={() => this.setState({openSnack: false})}/>
</div>
</TopAppBarFixedAdjust>
</DrawerAppContent>
</div>
</BrowserRouter>
</LoginContext.Provider>
)
}
}
function NoMatch({location}) {
return (<Card>
<CardPrimaryContent>
<h3 className='mdc-card-primary' style={{color: 'var(--red, red)'}}>404 - Page Not Found</h3>
<p className='mdc-card-secondary'>It seems the page You were trying to access has moved or doesn't
exist.</p>
</CardPrimaryContent>
<CardActions>
<span>Try going back </span><Link to="/" style={{textDecoration: "none"}}><Button
icon={<MaterialIcon icon='home'/>}>Home</Button></Link>
</CardActions>
</Card>)
}<file_sep>/src/components/LanguageMenu.js
import React from "react";
import Menu, {MenuList, MenuListItem, MenuListItemText} from "@material/react-menu";
import {LoginContext} from "../LoginContext";
import { useTranslation } from "react-i18next";
import Cookies from 'universal-cookie';
export function LanguageMenu(props) {
const { i18n } = useTranslation();
const cookies = new Cookies();
const changeLanguage = lng => {
cookies.set('language', lng);
return i18n.changeLanguage(lng);
};
return (
<LoginContext.Consumer>{user =>
(
<Menu
coordinates={props.coordinates}
open={props.open}
onClose={() => {
props.handleMenuClose(false)
}}
onSelected={(index) => {
switch (index) {
case 0:
changeLanguage('en');
break;
case 1:
changeLanguage('si');
break;
default:
break;
}
}}>
<MenuList>
<MenuListItem key='pending'>
<MenuListItemText primaryText={'English'}/>
</MenuListItem>
<MenuListItem key='settings'>
<MenuListItemText primaryText={'Slovenian'}/>
</MenuListItem>
</MenuList>
</Menu>
)}
</LoginContext.Consumer>)
}<file_sep>/src/components/LoginDialog.js
import * as React from "react";
import {useState} from "react";
import Dialog, {DialogButton, DialogContent, DialogFooter, DialogTitle} from "@material/react-dialog";
import TextField, {HelperText, Input} from "@material/react-text-field";
import MaterialIcon from "@material/react-material-icon";
import {LoginContext} from "../LoginContext";
import {Snackbar} from "@material/react-snackbar";
import {Button} from "@material/react-button";
export function LoginDialog(props) {
const [username, setUsername] = useState(undefined);
const [password, setPassword] = useState(undefined);
const [passwordMasked, setPasswordMasked] = useState(true);
const [snackState, setOpenSnack] = useState({open: false, message: undefined});
function resetState() {
// Reset state so that inputs clear before next open.
setUsername(undefined);
setPassword(<PASSWORD>);
}
return (
<LoginContext.Consumer>{user => (
<Dialog
open={props.isOpen} onClose={() => props.onClose()}>
<DialogTitle>Login</DialogTitle>
<form onSubmit={(event) => {
console.log(event);
event.preventDefault();
fetch('http://localhost:3001/api/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
password: <PASSWORD>,
}),
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson.success === true) {
props.onClose();
setOpenSnack({open: false});
user.isLoggedIn = true;
user.userName = username;
user.password = <PASSWORD>;
user.id = responseJson.data.id;
props.loginCallback(user);
resetState();
} else {
setOpenSnack({open: true, message: responseJson.error});
}
})
.catch((err) => {
setOpenSnack({open: true, message: 'There was a problem with the request!\n' + err});
});
}}>
<DialogContent>
<div className='py-1'>
<TextField outlined
label='Username'
helperText={<HelperText>Enter Your username here.</HelperText>}
leadingIcon={<MaterialIcon icon="person"/>}
trailingIcon={<MaterialIcon role='button' icon='delete'/>}
onTrailingIconSelect={() => setUsername(undefined)}
><Input
value={username}
onChange={(e) => setUsername(e.currentTarget.value)} id='username'/>
</TextField>
</div>
<div className='py-1'>
<TextField outlined
label='Password'
helperText={<HelperText>Enter Your password here.</HelperText>}
leadingIcon={<MaterialIcon icon="lock"/>}
trailingIcon={<MaterialIcon role='button'
icon={passwordMasked ? 'visibility' : 'visibility_off'}/>}
onTrailingIconSelect={() => setPasswordMasked(!passwordMasked)}
><Input type={passwordMasked ? 'password' : 'text'}
value={password}
onChange={(e) => setPassword(e.currentTarget.value)} id='password'/>
</TextField>
</div>
</DialogContent>
<DialogFooter>
<DialogButton action='dismiss'>Cancel</DialogButton>
<Button action='confirm' type='submit'>Login</Button>
</DialogFooter>
<Snackbar open={snackState.open} message={snackState.message} actionText='Close'
onClose={() => setOpenSnack({open: false})}/>
</form>
</Dialog>)}
</LoginContext.Consumer>
);
}<file_sep>/src/pages/NewPage.js
import React, {useState} from "react";
import Button from "@material/react-button";
export function NewPage(props) {
const [someText, setSomeText] = useState('This is a new page!');
const [count, setCount] = useState(0);
return (<div>
{someText + ' ' + count + ' times'}
<br/>
<Button raised onClick={() => {setSomeText('I was clicked'); setCount(count + 1)}}>Click me!</Button>
</div>);
}<file_sep>/src/components/SettingsMenu.js
import React from "react";
import Menu, {MenuList, MenuListItem, MenuListItemText} from "@material/react-menu";
import MaterialIcon from "@material/react-material-icon";
import {LoginContext} from "../LoginContext";
export function SettingsMenu(props) {
return (
<LoginContext.Consumer>{user =>
(
<Menu
coordinates={props.coordinates}
open={props.open}
onClose={() => {
props.handleMenuClose(false)
}}
onSelected={(index) => {
switch (index) {
case 0:
console.log('Syncing ' + props.pendingSyncItems + ' items');
break;
case 1:
console.log('Open settings');
break;
case 2:
if (user.isLoggedIn) {
user.isLoggedIn = false;
user.userName = undefined;
user.password = <PASSWORD>;
props.logoutCallback(user);
} else {
props.loginCallback();
}
break;
default:
break;
}
}}>
<MenuList>
<MenuListItem key='pending'>
<MaterialIcon icon='watch_later'/>
<MenuListItemText primaryText={'Pending (' + props.pendingSyncItems + ')'}/>
</MenuListItem>
<MenuListItem key='settings'>
<MaterialIcon icon='settings'/>
<MenuListItemText primaryText={'Settings'}/>
</MenuListItem>
<MenuListItem key='logInLogOut'>
<MaterialIcon icon={user.isLoggedIn ? 'lock' : 'lock_open'}/>
<MenuListItemText primaryText={user.isLoggedIn ? 'Log Out' : 'Log in'}/>
</MenuListItem>
</MenuList>
</Menu>
)}
</LoginContext.Consumer>)
}<file_sep>/src/components/LeftHandDrawer.js
import React from "react";
import Drawer, {DrawerContent, DrawerHeader, DrawerTitle} from "@material/react-drawer";
import List, {ListItem, ListItemGraphic, ListItemText} from "@material/react-list";
import MaterialIcon from "@material/react-material-icon";
import {Link} from "react-router-dom";
export function LeftHandDrawer(props) {
return (
<Drawer dismissible open={props.open}>
<DrawerHeader>
<DrawerTitle tag='h2' className='mdc-typography--subtitle1'>
{props.title}
</DrawerTitle>
</DrawerHeader>
<DrawerContent>
<List singleSelection selectedIndex={props.selectedIndex} handleSelect={(selectedIndex) => {
props.handleSelect(selectedIndex)
}}>
<Link to="/" style={{textDecoration: "none"}}>
<ListItem>
<ListItemGraphic graphic={<MaterialIcon icon='home'/>}/>
<ListItemText primaryText='Home'/>
</ListItem>
</Link>
<Link to="/newPage" style={{textDecoration: "none"}}>
<ListItem>
<ListItemGraphic graphic={<MaterialIcon icon='add'/>}/>
<ListItemText primaryText='New page'/>
</ListItem>
</Link>
<Link to="/404" style={{textDecoration: "none"}}>
<ListItem>
<ListItemGraphic graphic={<MaterialIcon icon='build'/>}/>
<ListItemText primaryText='Empty page'/>
</ListItem>
</Link>
</List>
</DrawerContent>
</Drawer>)
}<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {I18nextProvider} from "react-i18next";
import i18n from "./localizer";
ReactDOM.render(<I18nextProvider i18n={i18n}>
<App/>
</I18nextProvider>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.register({
onSuccess: (s) => {
console.log(s);
}, onUpdate: (u) => {
console.log(u);
}
});<file_sep>/src/components/AppBar.js
import React, {useState} from "react";
import TopAppBar, {TopAppBarIcon, TopAppBarRow, TopAppBarSection, TopAppBarTitle} from "@material/react-top-app-bar";
import MaterialIcon from "@material/react-material-icon";
import {SettingsMenu} from "./SettingsMenu";
import {LanguageMenu} from "./LanguageMenu";
export function AppBar(props) {
const [opened, setSettingsMenuOpened] = useState(false);
const [languageOpened, setLanguageMenuOpened] = useState(false);
const [coordinates, setCoordinates] = useState(undefined);
const [lngCoordinates, setLngCoordinates] = useState(undefined);
return (<TopAppBar>
<TopAppBarRow>
<TopAppBarSection align='start'>
<TopAppBarIcon navIcon tabIndex={0}>
<MaterialIcon hasRipple icon='menu'
onClick={() => {
props.handleDrawerToggle(!props.open)
}}/>
</TopAppBarIcon>
<TopAppBarTitle>My cool title</TopAppBarTitle>
</TopAppBarSection>
<TopAppBarSection align='end' role='toolbar'>
<TopAppBarIcon actionItem tabIndex={0}>
<MaterialIcon hasRipple icon='language' onClick={(event) => {
setLanguageMenuOpened(true);
setLngCoordinates({x: event.clientX, y: event.clientY})
}}/>
</TopAppBarIcon>
<LanguageMenu open={languageOpened} coordinates={lngCoordinates} handleMenuClose={(open) =>{
setLanguageMenuOpened(open);
}} />
<TopAppBarIcon actionItem tabIndex={1}>
<MaterialIcon
hasRipple
icon='more_vert'
onClick={(event) => {
setSettingsMenuOpened(true);
setCoordinates({x: event.clientX, y: event.clientY})
}}
/>
</TopAppBarIcon>
<SettingsMenu open={opened} coordinates={coordinates}
pendingSyncItems={2} handleMenuClose={(open) => {
setSettingsMenuOpened(open);
}} loginCallback={() => {
props.loginCallback()
}} logoutCallback={(user) => {
props.logoutCallback(user);
}}/>
</TopAppBarSection>
</TopAppBarRow>
</TopAppBar>)
} | 3080f12147979aa7d637af1d35391dd08e80e067 | [
"JavaScript"
]
| 8 | JavaScript | urbanambroz/ReactApp | 62d2dff27d78ba68e22d67dee8cd9390d0ec7b4d | 5cd659a048493d2ce18c114908dfc8e6692c8a75 |
refs/heads/master | <file_sep>var config = {};
config.consoleMode = true;
config.luis = {};
config.luis.appId = "";
config.luis.appKey = "";
config.api = {};
config.api.pkey = "pkey";
config.api.apiKey = "apiKey";
config.api.url = "apiUrl";
config.port = 9099;
module.exports = config;<file_sep>var builder = require('botbuilder');
var LUISClient = require("./luis_sdk");
var dateFormat = require('dateformat');
var api = require('./api');
var config = require('./config');
// LUIS client setup
var LUISclient = LUISClient({
appId: config.luis.appId,
appKey: config.luis.appKey,
verbose: true
});
function create(connector) {
//=========================================================
// Bot Setup
//=========================================================
var bot = new builder.UniversalBot(connector);
var emptyString = "Čo tu skúšaš? Nič si nenapísal, skús ešte raz kááámo.";
// starting dialog
bot.dialog("/", [
function (session, args, next){
session.userData = {};
builder.Prompts.text(session, 'Nazdar brácho! Čo si jak? Čo by si rád?');
},
function (session, results) {
askLUIS(session, results.response, function (response) {
//console.log("LUIS response: ", response);
switch(response.topScoringIntent.intent){
case "dialog_start":
session.beginDialog("/wantCinema");
break;
default:
session.send("Nerozumím, jsem jen stroj.");
}
});
}
]);
bot.dialog('/profile', [
function (session) {
builder.Prompts.text(session, 'Ahoj! Ako sa voláš?');
},
function (session, results) {
session.userData.name = results.response;
session.endDialog();
}
]);
bot.dialog("/wantCinema", [
function (session){
builder.Prompts.text(session, "Si zabil! Pome ti niečo násť! Berieš cipušku dnes alebo zajtra?");
},
function (session, results) {
var date = dateFormat(new Date(), "yyyy-mm-dd");
if(results.response != "dnes" && results.response != "Dnes") {
var nextDay = new Date();
nextDay.setDate(nextDay.getDate() + 1);
date = dateFormat(nextDay, "yyyy-mm-dd");
}
session.userData.dateFrom = date;
session.userData.dateTo = date;
if(!session.userData.city) {
session.beginDialog("/getCity");
} else {
api.getEvents(session).then(function() {
session.beginDialog("/chooseEvent");
});
}
}
]);
bot.dialog("/getCity", [
function (session){
builder.Prompts.text(session, "Čaaaavo a Mesto?");
},
function (session, results) {
if(results.response.length < 1) {
builder.Prompts.text(session, EmptyString);
session.endDialog();
session.beginDialog("/getCity");
} else {
session.userData.city = results.response;
api.getEvents(session).then(function () {
session.beginDialog("/chooseEvent");
});
}
}
]);
bot.dialog("/chooseEvent", [
function (session){
var str = "";
var i = 1;
Object.keys(session.userData.events).forEach(function (name) {
str += i+") "+name+" \n";
i++;
});
builder.Prompts.text(session, "A čo filmík? Romantika?: \n"+str);
},
function (session, results) {
if(results.response.length < 1) {
builder.Prompts.text(session, emptyString);
session.endDialog();
session.beginDialog("/chooseEvent");
} else {
session.userData.event = results.response;
api.getPerformances(session).then(function () {
session.beginDialog("/choosePerformance");
});
}
}
]);
bot.dialog("/choosePerformance", [
function (session){
var str = "";
var i = 1;
Object.keys(session.userData.performances).forEach(function (name) {
str += i+") "+name+" \n";
i++;
});
builder.Prompts.text(session, "Už len čas a môžeš vyraziť: \n"+str);
},
function (session, results) {
if(results.response.length < 1) {
builder.Prompts.text(session, emptyString);
session.endDialog();
session.beginDialog("/chooseEvent");
} else {
session.userData.performance = results.response;
api.getPerformanceDetail(session).then(function () {
var resp = "Hotofka, si zadelil!. Lískty na filmík " + session.userData.performanceDetail.title + " kúp tu: " + session.userData.performanceDetail.purchase_url;
resp += "\n \n Pro tip: Kúp babenke aj popcorn bráácho ;)";
builder.Prompts.text(session, resp);
});
}
}
]);
}
// private
/**
* Ask LUIS
* @param session
* @param question
* @param onSuccess callback
*/
function askLUIS(session, question, onSuccess){
if (question) {
LUISclient.predict(question, {
//On success of prediction
onSuccess: onSuccess,
//On failure of prediction
onFailure: function (err) {
console.error(err);
session.send("Něco se nepovedlo: " + err);
}
});
}
}
module.exports = { create };
<file_sep>var restify = require('restify');
var builder = require('botbuilder');
var cluster = require('cluster');
var config = require('./config');
var bot = require('./bot');
var api = require('./api');
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
cluster.fork();
});
}
if (cluster.isWorker) {
var connector;
if (config.consoleMode) {
connector = new builder.ConsoleConnector().listen();
} else {
connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: <PASSWORD>
});
}
var chatBot = bot.create(connector);
if (!config.consoleMode) {
// Setup Restify Server
var server = restify.createServer();
server.listen(config.port || process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
server.use(restify.queryParser());
server.post('/api/messages', connector.listen());
}
}
<file_sep>var api = require('./api');
var session = {};
session.userData = {
city: "Praha",
dateFrom: "2017-03-26",
dateTo: "2017-03-26"
};
api.getEvents(session).then(function() {
console.log(session.userData.events);
session.userData.event = "Masaryk";
api.getPerformances(session).then(function() {
console.log("Performances ..... ");
console.log(session.userData.performances);
session.userData.performance = 1101808;
api.getPerformanceDetail(session).then(function() {
console.log("PERFORMANCE DETAIL .............................. ");
console.log(session.userData.performanceDetail);
});
});
});
| 84966e50e5a3032d8ca54b6801c534da65758ee9 | [
"JavaScript"
]
| 4 | JavaScript | xmedved1/chatbot | 6b8c10731a1a8d3d2045c38deaaff6c242080082 | 669921e7b97083ecab36073cf277836d8d83f995 |
refs/heads/master | <repo_name>sgupt9999/apache<file_sep>/apache-rhce.sh
#!/bin/bash
#
# All the apache web server objectives for the RHCE exam
#
INSTALLPACKAGES="httpd firewalld openssl mod_ssl"
REMOVEPACKAGES="httpd httpd-tools"
PUBLICIP=172.16.31.10
PRIVATEIP=172.31.30.29
SERVER1="server1.myserver.com"
SERVER2="server2.myserver.com"
clear
if (( $EUID != 0 ))
then
echo "ERROR: need to have root privileges to run the script"
exit 1
fi
if yum list installed httpd > /dev/null 2>&1
then
systemctl is-active -q httpd && {
systemctl stop httpd
systemctl disable -q httpd
}
echo "Removing all httpd packages...."
yum remove -y -q $REMOVEPACKAGES
userdel -r apache &>/dev/null
rm -rf /var/www
rm -rf /etc/httpd
rm -rf /usr/lib/httpd
echo "Done"
fi
echo "Installing packages......"
yum install -y -q $INSTALLPACKAGES
systemctl start $INSTALLPACKAGES &>/dev/null
systemctl enable $INSTALLPACKAGES &>/dev/null
# Add http service to the firewall
firewall-cmd -q --permanent --add-service http
firewall-cmd -q --reload
echo "This is the default document root" > /var/www/html/index.html
echo
echo "########################################################################################"
echo "Test for Default content location - /var/www/html"
echo -n "curl $PUBLICIP -----> "
curl -s $PUBLICIP
# Making a non default content directory
rm -rf /mycontent
mkdir /mycontent
echo "This is a non-default document root" > /mycontent/index.html
semanage fcontext -a -t httpd_sys_content_t "/mycontent(/.*)?"
restorecon -R /mycontent
sed -i "s/DocumentRoot/# DocumentRoot/g" /etc/httpd/conf/httpd.conf
echo "DocumentRoot /mycontent" >> /etc/httpd/conf/httpd.conf
echo "<Directory /mycontent>" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
systemctl restart httpd
echo
echo "########################################################################################"
echo "Test for Non-Default location - /mycontent"
echo -n "curl $PUBLICIP -----> "
curl -s $PUBLICIP
# Adding username/password for 1 user - Method 1
rm -rf /userdir1
mkdir /userdir1
echo "Adding one user to the config file" > /userdir1/index.html
semanage fcontext -a -t httpd_sys_content_t "/userdir1(/.*)?"
restorecon -R /userdir1
htpasswd -c -b /etc/httpd/conf/passwords webuser1 redhat1 &>/dev/null
sed -i "s/^DocumentRoot/# DocumentRoot/g" /etc/httpd/conf/httpd.conf
echo "DocumentRoot /" >> /etc/httpd/conf/httpd.conf
echo "<Directory userdir1>" >> /etc/httpd/conf/httpd.conf
echo " AllowOverride AuthConfig" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
echo "AuthType Basic" >> /userdir1/.htaccess
echo "AuthName 'User Authentication #1'" >> /userdir1/.htaccess
echo "AuthUserFile /etc/httpd/conf/passwords" >> /userdir1/.htaccess
echo "Require user webuser1" >> /userdir1/.htaccess
systemctl restart httpd
echo
echo "########################################################################################"
echo "Test for specifying one username in the config file"
echo "Added webuser1 to the config and the password file"
echo -n "curl -u webuser1:redhat1 $PUBLICIP/userdir1/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser1:redhat1 $PUBLICIP/userdir1/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
# Adding username/password for a multiple users - Method 1
# Specifying all the valid users explicitly in the config file
rm -rf /userdir2
mkdir /userdir2
echo "Decalring all the users with the permission in the config file" > /userdir2/index.html
semanage fcontext -a -t httpd_sys_content_t "/userdir2(/.*)?"
restorecon -R /userdir2
htpasswd -b /etc/httpd/conf/passwords webuser2 redhat2 &>/dev/null
htpasswd -b /etc/httpd/conf/passwords webuser3 redhat3 &>/dev/null
echo "<Directory userdir2>" >> /etc/httpd/conf/httpd.conf
echo " AllowOverride AuthConfig" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
echo "AuthType Basic" >> /userdir2/.htaccess
echo "AuthName 'User Authentication #2'" >> /userdir2/.htaccess
echo "AuthUserFile /etc/httpd/conf/passwords" >> /userdir2/.htaccess
echo "Require user webuser1 webuser2" >> /userdir2/.htaccess
systemctl restart httpd
echo
echo "########################################################################################"
echo "Test for declaring a list of users with permissions. Only users specified in the config file will be let in"
echo "Added webuser2 to the config and the password file"
echo -n "curl -u webuser1:redhat1 $PUBLICIP/userdir2/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser1:redhat1 $PUBLICIP/userdir2/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser2:redhat2 $PUBLICIP/userdir2/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser2:redhat2 $PUBLICIP/userdir2/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser3:redhat3 $PUBLICIP/userdir2/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser3:redhat3 $PUBLICIP/userdir2/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
# Adding username/password for multiple users - Method 2
# Using a valid-user directive instead of specifying users in the config file
# All users in the password file are allowed in if they enter the correct password
rm -rf /userdir3
mkdir /userdir3
echo "Using the valid-user directive for multiple users" > /userdir3/index.html
semanage fcontext -a -t httpd_sys_content_t "/userdir3(/.*)?"
restorecon -R /userdir3
echo "<Directory userdir3>" >> /etc/httpd/conf/httpd.conf
echo " AllowOverride AuthConfig" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
echo "AuthType Basic" >> /userdir3/.htaccess
echo "AuthName 'User Authentication #3'" >> /userdir3/.htaccess
echo "AuthUserFile /etc/httpd/conf/passwords" >> /userdir3/.htaccess
echo "Require valid-user" >> /userdir3/.htaccess
systemctl restart httpd
echo
echo "########################################################################################"
echo "Test for valid-user directive. All users in the password file with the correct password are let in"
echo "Added webuser3 to the password file"
echo -n "curl -u webuser1:redhat1 $PUBLICIP/userdir3/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser1:redhat1 $PUBLICIP/userdir3/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser2:redhat2 $PUBLICIP/userdir3/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser2:redhat2 $PUBLICIP/userdir3/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser3:redhat3 $PUBLICIP/userdir3/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser3:redhat3 $PUBLICIP/userdir3/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser4:redhat4 $PUBLICIP/userdir3/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser4:redhat4 $PUBLICIP/userdir3/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
# Adding username/password for multiple users - Method 3
# Using a group file to speficy the users belonging to that group
# Only users in that group are allowed in
rm -rf /userdir4
mkdir /userdir4
echo "Using the group directive for multiple users" > /userdir4/index.html
semanage fcontext -a -t httpd_sys_content_t "/userdir4(/.*)?"
restorecon -R /userdir4
#userdel webuser4 &>/dev/null
#useradd webuser4 &>/dev/null
htpasswd -b /etc/httpd/conf/passwords webuser4 redhat4 &>/dev/null
echo "<Directory userdir4>" >> /etc/httpd/conf/httpd.conf
echo " AllowOverride AuthConfig" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
echo "AuthType Basic" >> /userdir4/.htaccess
echo "AuthName 'User Authentication #4'" >> /userdir4/.htaccess
echo "AuthUserFile /etc/httpd/conf/passwords" >> /userdir4/.htaccess
echo "AuthGroupFile /etc/httpd/conf/groups" >> /userdir4/.htaccess
echo "Require group team" >> /userdir4/.htaccess
echo "team: webuser1 webuser2 webuser4" > /etc/httpd/conf/groups
systemctl restart httpd
echo
echo "########################################################################################"
echo "Test for group directive. All users in the group file with the correct password are let in"
echo "Added webuser1 webuser2 and webuser4 to the group file and webuser4 to the password file"
echo -n "curl -u webuser1:redhat1 $PUBLICIP/userdir4/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser1:redhat1 $PUBLICIP/userdir4/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser2:redhat2 $PUBLICIP/userdir4/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser2:redhat2 $PUBLICIP/userdir4/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser3:redhat3 $PUBLICIP/userdir4/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser3:redhat3 $PUBLICIP/userdir4/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
echo -n "curl -u webuser4:redhat4 $PUBLICIP/userdir4/index.html -----> "
if [ `curl -s -o /dev/null -w %{http_code} -u webuser4:redhat4 $PUBLICIP/userdir4/index.html` -eq "200" ]
then
echo "SUCCESS"
else
echo "ERROR"
fi
# Running a cgi-script
# To be able to run a cgi-script from /myscripts directory
rm -rf /myscripts
mkdir -p /myscripts/cgi-bin
cat > /myscripts/cgi-bin/test.sh << EOF
#!/bin/bash
echo
Content-type: text/html
echo "The current time is `date`"
echo
EOF
chmod a+x /myscripts/cgi-bin/test.sh
semanage fcontext -a -t httpd_sys_script_exec_t "/myscripts(/.*)?"
restorecon -R /myscripts
setsebool -P httpd_enable_cgi=1
sed -i 's#ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"#ScriptAlias /cgi-bin/ /myscripts/cgi-bin/#g' /etc/httpd/conf/httpd.conf
echo "<Directory myscripts>" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
systemctl restart httpd
echo
echo "########################################################################################"
echo "Test to be able to run cgi-scripts"
echo -n "curl $PUBLICIP/cgi-bin/test.sh -----> "
if [ `curl -s -o /dev/null -w %{http_code} $PUBLICIP/cgi-bin/test.sh` -eq "200" ]
then
curl -s $PUBLICIP/cgi-bin/test.sh
else
echo "ERROR"
fi
# Setting up virtual hosts
echo "$PRIVATEIP $SERVER1" >> /etc/hosts
echo "$PRIVATEIP $SERVER2" >> /etc/hosts
rm -rf /myvhost1
mkdir /myvhost1
echo "This is the directory location for $SERVER1 virtual host" > /myvhost1/index.html
semanage fcontext -a -t httpd_sys_content_t "/myvhost1(/.*)?"
restorecon -R /myvhost1
echo "<VirtualHost *:80>" >> /etc/httpd/conf/httpd.conf
echo " DocumentRoot /myvhost1" >> /etc/httpd/conf/httpd.conf
echo "</VirtualHost>" >> /etc/httpd/conf/httpd.conf
echo "<Directory /myvhost1>" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
systemctl restart httpd
echo
echo "########################################################################################"
echo "Setup a Virtual host to listen on port 80"
echo -n "curl $SERVER1 -----> "
if [ `curl -s -o /dev/null -w %{http_code} $SERVER1` -eq "200" ]
then
# echo "SUCCESS"
curl -s $SERVER1
echo -n "curl $PUBLICIP -----> "
curl -s $PUBLICIP
else
echo "ERROR"
fi
# Setting up a virtual host with a self signed certificate
echo "Creating a new private key and a self signed certificate"
rm -rf /etc/pki/tls/certs/myserver*
openssl req -x509 -days 365 -newkey rsa:2048 -nodes -keyout /etc/pki/tls/certs/myserver.key -out /etc/pki/tls/certs/myserver.crt -subj "/C=US/ST=Texas/L=Houston/O=CMEI/CN=$PUBLICIP" &>/dev/null
rm -rf /myvhost2
mkdir /myvhost2
echo "Virtual Host with a self-signed certificate- Server $SERVER2" > /myvhost2/index.html
semanage fcontext -a -t httpd_sys_content_t "/myvhost2(/.*)?"
#semanage fcontext -a -t httpd_sys_content_t "/myvhost1(/.*)?"
restorecon -R /myvhost2
echo "<VirtualHost *:443>" >> /etc/httpd/conf/httpd.conf
echo " DocumentRoot /myvhost2" >> /etc/httpd/conf/httpd.conf
echo " SSLCertificateFile /etc/pki/tls/certs/myserver.crt" >> /etc/httpd/conf/httpd.conf
echo " SSLCertificateKeyFile /etc/pki/tls/certs/myserver.key" >> /etc/httpd/conf/httpd.conf
echo " ServerName $PUBLICIP:443" >> /etc/httpd/conf/httpd.conf
echo "</VirtualHost>" >> /etc/httpd/conf/httpd.conf
echo "<VirtualHost *:443>" >> /etc/httpd/conf/httpd.conf
echo " DocumentRoot /myvhost2" >> /etc/httpd/conf/httpd.conf
echo " SSLCertificateFile /etc/pki/tls/certs/myserver.crt" >> /etc/httpd/conf/httpd.conf
echo " SSLCertificateKeyFile /etc/pki/tls/certs/myserver.key" >> /etc/httpd/conf/httpd.conf
echo " ServerName server2.myserver.com:443" >> /etc/httpd/conf/httpd.conf
echo "</VirtualHost>" >> /etc/httpd/conf/httpd.conf
echo "<Directory /myvhost2>" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
systemctl restart httpd
<file_sep>/apache-new-root-ca.sh
#!/bin/bash
# Testing creating self-signed certificate with a new root authority
# checked on both linuxacademy and AWS and works fine
CN="garfield99994d.mylabserver.com"
FILE="/etc/httpd/conf/httpd.conf"
systemctl stop httpd
yum remove httpd -y
rm -rf /var/www
rm -rf /etc/httpd
yum install httpd -y
yum install mod_ssl -y
systemctl enable --now httpd
rm -rf /etc/pki/tls/certs/rootca.*
rm -rf /etc/pki/tls/certs/mylabserver.*
cd /etc/pki/tls/certs
openssl genpkey -out rootca.key -algorithm RSA -pkeyopt rsa_keygen_bits:4096
openssl req -x509 -days 365 -out rootca.crt -subj "/OU=RootAgency/CN=RootAgency" -set_serial 101 -key ./rootca.key
openssl req -newkey rsa:2048 -out mylabserver.csr -subj "/OU=CMEI1/CN=$CN" -nodes -keyout mylabserver.key
openssl x509 -req -days 365 -CA ./rootca.crt -CAkey ./rootca.key -out mylabserver.crt -set_serial 501 -in mylabserver.csr
chmod 0600 *.key
# Add the new root CA to the trusted sources
cd /etc/pki/ca-trust/source/anchors/
rm -rf *
cp /etc/pki/tls/certs/rootca.crt .
update-ca-trust extract
# Create a directory for the virtualhost
rm -rf /test
mkdir /test
echo "This is the test directory" > /test/index.html
semanage fcontext -a -t httpd_sys_content_t "/test(/.*)?"
restorecon -r /test
# Make a backup of the default ssl.conf and create a custom file
mv /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.orig
cat >/etc/httpd/conf.d/ssl.conf <<EOF
Listen 443 https
SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog
SSLSessionCache shmcb:/run/httpd/sslcache(512000)
SSLSessionCacheTimeout 300
SSLRandomSeed startup file:/dev/urandom 256
SSLRandomSeed connect builtin
SSLCryptoDevice builtin
SSLStrictSNIVHostCheck on
<VirtualHost *:443>
DocumentRoot /test
ServerName $CN
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/mylabserver.crt
SSLCertificateKeyFile /etc/pki/tls/certs/mylabserver.key
SSLProtocol all -SSLv2 -SSLv3
SSLCipherSuite HIGH:3DES:!aNULL:!MD5:!SEED:!IDEA
<Files ~ "\.(cgi|shtml|phtml|php3?)$">
SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-5]" \
nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog logs/ssl_request_log \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
<Directory /test>
require all granted
</Directory>
EOF
systemctl restart httpd
clear
echo "curl https://$CN"
curl https://$CN
<file_sep>/apache-monitoring.sh
#!/bin/bash
#
# Install apache server, create a virtual host and activate server monitoring using mod_status
# mod_status shows a plain HTML page containing the information about current statistics of web server including
# total number of requests, total number of bytes, CPU usage of a web server, server load, server Uptime, total traffic
# total number of idle workers
#
# Start of user inputs
INSTALLPACKAGES="httpd openssl mod_ssl"
REMOVEPACKAGES="httpd httpd-tools"
PUBLICIP=192.168.3.11
PRIVATEIP=172.31.30.29
SERVER1="server1.myserver.com"
SERVER2="server2.myserver.com"
# End of user inputs
if (( $EUID != 0 ))
then
echo "ERROR: need to have root privileges to run the script"
exit 1
fi
if yum list installed httpd > /dev/null 2>&1
then
systemctl is-active -q httpd && {
systemctl stop httpd
systemctl disable -q httpd
}
echo "Removing all httpd packages...."
yum remove -y -q $REMOVEPACKAGES
userdel -r apache &>/dev/null
rm -rf /var/www
rm -rf /etc/httpd
rm -rf /usr/lib/httpd
echo "Done"
fi
echo "Installing packages......"
yum install -y -q $INSTALLPACKAGES
echo "Done"
rm -rf /myserver1
mkdir /myserver1
semanage fcontext -a -t httpd_sys_content_t "/myserver1(/.*)?"
restorecon -R /myserver1
echo "This is mywebserver1" > /myserver1/index.html
# mod_status is an Apache module whch helps to monitor web server load and current httpd connections with an HTML interface
# accessible fia the web-server http:<IP-address>/server-status
echo "LoadModule status_module modules/mod_status.so" >> /etc/httpd/conf/httpd.conf
# ExtendedStatus adds more information to the staistics page like CPU usage, request per second, total traffic etc.
echo "ExtendedStatus On" >> /etc/httpd/conf/httpd.conf
echo "<VirtualHost $PRIVATEIP:80>" >> /etc/httpd/conf/httpd.conf
echo " DocumentRoot /myserver1" >> /etc/httpd/conf/httpd.conf
echo ' <Location /server-status>' >> /etc/httpd/conf/httpd.conf
echo " SetHandler server-status" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo " </Location>" >> /etc/httpd/conf/httpd.conf
echo "</VirtualHost>" >> /etc/httpd/conf/httpd.conf
echo "<Directory /myserver1>" >> /etc/httpd/conf/httpd.conf
echo " Require all granted" >> /etc/httpd/conf/httpd.conf
echo "</Directory>" >> /etc/httpd/conf/httpd.conf
systemctl start $INSTALLPACKAGES &>/dev/null
systemctl enable $INSTALLPACKAGES &>/dev/null
<file_sep>/apache_lets_encrypt.sh
#!/bin/bash
#################################################################################
# This script will setup an apache server on this machine and also install an SSL
# certificate from Let's encrypt for https access
#################################################################################
# Start of user inputs
DOMAIN="garfield99991.mylabserver.com"
FIREWALL="yes"
#FIREWALL="NO"
ADMIN_EMAIL="<EMAIL>"
# End of user inputs
INSTALLPACKAGES="httpd"
INSTALLPACKAGES2="openssl mod_ssl"
INSTALLPACKAGES3="certbot python2-certbot-apache"
if [[ $EUID != 0 ]]
then
echo
echo "###########################################################"
echo "ERROR. You need to have root privileges to run this script"
echo "###########################################################"
exit 1
else
echo
echo "############################################################################"
echo "This script will install an Apache Server on this machine"
echo "It will also install a free SSL certificate from Let's Encrypt"
echo "The script can also create a cron job to automatically renew the certficate"
echo "############################################################################"
fi
if yum list installed $INSTALLPACKAGES > /dev/null 2>&1
then
systemctl -q is-active httpd && {
systemctl stop httpd
systemctl -q disable httpd
}
echo
echo "########################################################"
echo "Removing old packages ................................."
yum remove $INSTALLPACKAGES -y -q > /dev/null 2>&1
rm -rf /var/www
rm -rf /etc/httpd
rm -rf /usr/lib/httpd
echo "Done"
echo "########################################################"
fi
echo
echo "########################################################"
echo "Installing packages ...................................."
yum install $INSTALLPACKAGES -y -q > /dev/null 2>&1
echo "Done"
echo "########################################################"
echo "This is the website for $DOMAIN" > /var/www/html/index.html
systemctl start httpd
systemctl -q enable httpd
if [[ $FIREWALL == "yes" ]]
then
if systemctl -q is-active firewalld
then
echo
firewall-cmd -q --permanent --add-service http
firewall-cmd -q --permanent --add-service https
firewall-cmd -q --reload
echo "############################################"
echo "Http and https added to firewall protection"
echo "############################################"
else
echo
echo "#####################################################"
echo "Firewalld not active. No change made to the firewall"
echo "#####################################################"
fi
fi
echo
echo "#############################################################################################################"
echo "Testing http connection.."
echo -n "curl http://$DOMAIN -----------> "
curl -s http://$DOMAIN
echo "#############################################################################################################"
echo
echo "#############################################################################################################"
echo "Testing https connection.."
echo -n "curl https://$DOMAIN -----------> "
curl https://$DOMAIN
echo "#############################################################################################################"
sleep 5
echo
echo "######################################################"
echo "Installing mod_ssl package"
yum install $INSTALLPACKAGES2 -y -q > /dev/null 2>&1
echo "Done"
echo "######################################################"
systemctl restart httpd
echo
echo "#############################################################################################################"
echo "Mod_ssl was installed. It also creates a default self signed certificate as part of installation"
echo "#############################################################################################################"
sleep 5
echo "curl https://$DOMAIN -----------> "
echo
curl https://$DOMAIN
echo "#############################################################################################################"
curl -v https://$DOMAIN &>/tmp/output
echo
echo "This is the subject from the default self signed certificate----->"
sleep 5
cat /tmp/output | sed -n "s/subject.*/&/p"
echo "#############################################################################################################"
sleep 5
if yum list installed certbot > /dev/null 2>&1
then
echo
echo "#################################################"
echo "Removing all copies of certbot.................."
yum remove -y -q $INSTALLPACKAGES3 > /dev/null 2>&1
rm -rf /etc/letsencrypt
echo "Done"
echo "#################################################"
fi
echo
echo "######################################################"
echo "Installing certbot packages for Lets Encrypt certificate"
yum install $INSTALLPACKAGES3 -y -q > /dev/null 2>&1
echo "Done"
echo "######################################################"
# Need a VirtualHost declaration, otherwise the Let's Encrypt challenege gives an error
echo "<VirtualHost *:80>" >> /etc/httpd/conf/httpd.conf
echo " ServerName $DOMAIN" >> /etc/httpd/conf/httpd.conf
echo "</VirtualHost>" >> /etc/httpd/conf/httpd.conf
certbot -n --apache -d $DOMAIN --agree-tos -m $ADMIN_EMAIL > /dev/null 2>&1
echo
echo "#############################################################################################################"
echo "Let's encrypt certificate installed."
echo "#############################################################################################################"
sleep 5
echo "curl https://$DOMAIN -----------> "
echo
curl https://$DOMAIN
echo "#############################################################################################################"
curl -v https://$DOMAIN &>/tmp/output
echo
echo "This is the subject from the Let's Encrypt certificate----->"
sleep 5
cat /tmp/output | sed -n "s/subject.*/&/p"
echo
echo "And the issuer of the certificate --------->"
cat /tmp/output | sed -n "s/issuer.*/&/p"
echo "#############################################################################################################"
<file_sep>/README.md
# apache
apache setup scripts
| 1a1caebdd1539d9cee1f1fa123692c16a0df81c6 | [
"Markdown",
"Shell"
]
| 5 | Shell | sgupt9999/apache | d18c560d1a43f18acd9d1adcce5a02aee921a220 | 92f5c322f48daa178e5470e90a2a49d59e92d0f7 |
refs/heads/master | <file_sep>package com.example.hp.musicplayerapp.MOdels
import android.app.Service
import android.content.ContentUris
import android.content.Intent
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import android.os.PowerManager
import android.util.Log;
import java.lang.Exception
class MusicService( ): Service(), MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
private lateinit var player: MediaPlayer
private lateinit var songs: ArrayList<Song>
var songPosition: Int=0
private var musicBind = MusicBinder()
override fun onPrepared(mp: MediaPlayer?) {
mp!!.start()
}
override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCompletion(mp: MediaPlayer?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onBind(intent: Intent?): IBinder? {
return musicBind
}
override fun onUnbind(intent: Intent?): Boolean {
player.stop()
player.release()
return false
}
override fun onCreate(){
super.onCreate()
songPosition=0
player= MediaPlayer()
initMusicPlayer()
musicBind=MusicBinder()
}
fun initMusicPlayer(){
player.setWakeMode(applicationContext,PowerManager.PARTIAL_WAKE_LOCK)
player.setAudioStreamType(AudioManager.STREAM_MUSIC)
player.setOnPreparedListener(this)
player.setOnCompletionListener(this)
player.setOnErrorListener(this)
}
fun setList(theSongs: ArrayList<Song>){
songs=theSongs
}
fun playSong(){
player.reset()
var playSong=songs.get(songPosition)
var currSong=playSong.id
var trackUri=ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,currSong)
try {
player.setDataSource(applicationContext,trackUri)
}catch (e: Exception){
Log.e("MUSIC SERVICE", "Error setting data source", e)
}
player.prepareAsync()
}
fun setSong(songIndex:Int){
songPosition=songIndex
}
inner class MusicBinder : Binder() {
internal val service: MusicService
get() = this@MusicService
}
}<file_sep>package com.example.hp.musicplayerapp
import android.content.*
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
import android.net.Uri
import android.database.Cursor
import android.view.View
import com.example.hp.musicplayerapp.MOdels.Song
import com.example.hp.musicplayerapp.MOdels.SongAdapter
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.MediaController.MediaPlayerControl;
import com.example.hp.musicplayerapp.MOdels.MusicController
import com.example.hp.musicplayerapp.MOdels.MusicService
import com.example.hp.musicplayerapp.R.id.songList
import com.example.hp.musicplayerapp.MOdels.MusicService.MusicBinder
import android.os.IBinder
import android.content.ComponentName
import com.example.hp.musicplayerapp.R.id.songList
import android.content.ServiceConnection
class MainActivity : AppCompatActivity() {
private lateinit var songsArray: ArrayList<Song>
private lateinit var controller:MusicController
private var musicSrv: MusicService?= null
private var playIntent: Intent?=null
private var musicBound=false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
songsArray = ArrayList()
getSongList()
//Codigo que permite ordenar las canciones por nombre y mostrarlas en la ListView
Collections.sort(songsArray,
Comparator<Song> { a, b -> a.songName.compareTo(b.songName) })
val songAdpt= SongAdapter(this,songsArray)
songList.adapter= songAdpt
}
//connect to the service
private val musicConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val binder = service as MusicBinder
//get service
musicSrv = binder.service
//pass list
musicSrv!!.setList(songsArray)
musicBound = true
}
override fun onServiceDisconnected(name: ComponentName) {
musicBound = false
}
}
// crea el intento y hace el bind con el servicio
override fun onStart() {
super.onStart()
if (playIntent==null) {
playIntent = Intent(this, MusicService::class.java)
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE)
startService(playIntent)
}
}
// toca la cancion seleccionada
fun songPicked(view: View) {
musicSrv!!.setSong(Integer.parseInt(view.tag.toString()))
musicSrv!!.playSong()
}
//obtiene la lista de canciones de la Media del telefono
fun getSongList(){
val musicResolver = contentResolver
val musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val musicCursor= musicResolver.query(musicUri,null,null,null,null)
if(musicCursor!=null && musicCursor.moveToFirst()){
//obtener la informacion del cursor
val titleIndex= musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE)
val idIndex= musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID)
val authorIndex= musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST)
//utilizar la informacion para crear nuevas Canciones
do {
val id= musicCursor.getLong(idIndex)
val title= musicCursor.getString(titleIndex)
val author= musicCursor.getString(authorIndex)
val songToAdd = Song(id,title,author)
songsArray.add(songToAdd)
}while (musicCursor.moveToNext())
}
}
}
<file_sep>package com.example.hp.musicplayerapp.MOdels
//clase para guardar las canciones
class Song(val id:Long , val songName: String, val songAuthor:String){
} | 86807054d2e0c57bee157a7a0bbc6aefd3bca915 | [
"Kotlin"
]
| 3 | Kotlin | michelebenvenuto/Laboratorio6 | 1c2e09a22472164861e1562c2b8a2229dfa4d813 | 6b60941ccfb20de7894e863f1a4a089c917fa129 |
refs/heads/master | <file_sep>import pygame
pygame.init()
win = pygame.display.set_mode((500,480))
pygame.display.set_caption("First Game")
path="J://personal github//Game//"
walkRight = [pygame.image.load(path+'R1.png'), pygame.image.load(path+'R2.png'), pygame.image.load(path+'R3.png'), pygame.image.load(path+'R4.png'), pygame.image.load(path+'R5.png'), pygame.image.load(path+'R6.png'), pygame.image.load(path+'R7.png'), pygame.image.load(path+'R8.png'), pygame.image.load(path+'R9.png')]
walkLeft = [pygame.image.load(path+'L1.png'), pygame.image.load(path+'L2.png'), pygame.image.load(path+'L3.png'), pygame.image.load(path+'L4.png'), pygame.image.load(path+'L5.png'), pygame.image.load(path+'L6.png'), pygame.image.load(path+'L7.png'), pygame.image.load(path+'L8.png'), pygame.image.load(path+'L9.png')]
bg = pygame.image.load(path+'bg.jpg')
go=pygame.image.load(path+'game_over.jpg')
char = pygame.image.load(path+'standing.png')
clock = pygame.time.Clock()
score=0
class player(object):
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
self.isJump = False
self.left = False
self.right = False
self.walkCount = 0
self.jumpCount = 10
self.standing = True
self.hitbox=(self.x,self.y,29,52)
def draw(self, win):
if self.walkCount + 1 >= 27:
self.walkCount = 0
if not(self.standing):
if self.left:
win.blit(walkLeft[self.walkCount//3], (self.x,self.y))
self.walkCount += 1
elif self.right:
win.blit(walkRight[self.walkCount//3], (self.x,self.y))
self.walkCount +=1
else:
if self.right:
win.blit(walkRight[0], (self.x, self.y))
else:
win.blit(walkLeft[0], (self.x, self.y))
self.hitbox = (self.x + 17, self.y + 11, 29, 52)
pygame.draw.rect(win, (255,0,0), self.hitbox,2)
class projectile(object):
def __init__(self,x,y,radius,color,facing):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.facing = facing
self.vel = 8 * facing
def draw(self,win):
pygame.draw.circle(win, self.color, (self.x,self.y), self.radius)
class enemy(object):
walkRight = [pygame.image.load(path+'R1E.png'), pygame.image.load(path+'R2E.png'), pygame.image.load(path+'R3E.png'), pygame.image.load(path+'R4E.png'), pygame.image.load(path+'R5E.png'), pygame.image.load(path+'R6E.png'), pygame.image.load(path+'R7E.png'), pygame.image.load(path+'R8E.png'), pygame.image.load(path+'R9E.png'), pygame.image.load(path+'R10E.png'), pygame.image.load(path+'R11E.png')]
walkLeft = [pygame.image.load(path+'L1E.png'), pygame.image.load(path+'L2E.png'), pygame.image.load(path+'L3E.png'), pygame.image.load(path+'L4E.png'), pygame.image.load(path+'L5E.png'), pygame.image.load(path+'L6E.png'), pygame.image.load(path+'L7E.png'), pygame.image.load(path+'L8E.png'), pygame.image.load(path+'L9E.png'), pygame.image.load(path+'L10E.png'), pygame.image.load(path+'L11E.png')]
def __init__(self, x, y, width, height, end):
self.x = x
self.y = y
self.width = width
self.height = height
self.path = [x, end]
self.walkCount = 0
self.vel = 3
self.health = 10
self.visible=True
self.hitbox=(self.x,self.y,29,52)
def draw(self, win):
self.move()
if self.visible :
if self.walkCount + 1 >= 33:
self.walkCount = 0
if self.vel > 0:
win.blit(self.walkRight[self.walkCount//3], (self.x,self.y))
self.walkCount += 1
else:
win.blit(self.walkLeft[self.walkCount//3], (self.x,self.y))
self.walkCount += 1
pygame.draw.rect(win, (255,0,0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
pygame.draw.rect(win, (0,128,0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10))
self.hitbox = (self.x + 19, self.y + 5, 32, 55)
pygame.draw.rect(win, (255,0,0), self.hitbox,2)
def move(self):
if self.vel > 0:
if self.x < self.path[1] + self.vel:
self.x += self.vel
else:
self.vel = self.vel * -1
self.x += self.vel
self.walkCount = 0
else:
if self.x > self.path[0] - self.vel:
self.x += self.vel
else:
self.vel = self.vel * -1
self.x += self.vel
self.walkCount = 0
def hit(self):
if self.health > 0:
self.health -= 1
else:
self.visible = False
print('hit')
def redrawGameWindow():
win.blit(bg, (0,0))
text=font.render('Score ' +str(score),1,(0,0,0))
win.blit(text,(390,10))
man.draw(win)
goblin.draw(win)
for bullet in bullets:
bullet.draw(win)
pygame.display.update()
#mainloop
font= pygame.font.SysFont('comicsans',30)
man = player(200, 410, 64,64)
goblin = enemy(100, 410, 64, 64, 300)
bullets = []
run = True
while run:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.y - bullet.radius < goblin.hitbox[1] + goblin.hitbox[3] and bullet.y + bullet.radius > goblin.hitbox[1]:
if bullet.x + bullet.radius > goblin.hitbox[0] and bullet.x - bullet.radius < goblin.hitbox[0] + goblin.hitbox[2]:
goblin.hit()
score+=10
bullets.pop(bullets.index(bullet))
if bullet.x < 500 and bullet.x > 0:
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
if man.left:
facing = -1
else:
facing = 1
if len(bullets) < 5:
bullets.append(projectile(round(man.x + man.width //2), round(man.y + man.height//2), 6, (0,0,0), facing))
if keys[pygame.K_LEFT] and man.x > man.vel:
man.x -= man.vel
man.left = True
man.right = False
man.standing = False
elif keys[pygame.K_RIGHT] and man.x < 500 - man.width - man.vel:
man.x += man.vel
man.right = True
man.left = False
man.standing = False
else:
man.standing = True
man.walkCount = 0
if not(man.isJump):
if keys[pygame.K_UP]:
man.isJump = True
man.right = False
man.left = False
man.walkCount = 0
else:
if man.jumpCount >= -10:
neg = 1
if man.jumpCount < 0:
neg = -1
man.y -= (man.jumpCount ** 2) * 0.5 * neg
man.jumpCount -= 1
else:
man.isJump = False
man.jumpCount = 10
redrawGameWindow()
pygame.quit()
| dda100c6f5bc2dc58b18d4d1d290fc4dafcd29b0 | [
"Python"
]
| 1 | Python | jennings1716/pygame | 2d10134a13d64fd5846ebdc1486fac1d19bc1b7f | 1e48a23dd57b19c9f0540a81315395d1fa92f6df |
refs/heads/master | <repo_name>romainreignier/lcov_badge_generator<file_sep>/README.md
# `lcov_badge_generator`

A badge generator for coverage report generated by [`lcov`](http://ltp.sourceforge.net/coverage/lcov.php).
## Example

## Usage
```
Parse html output from gcov/lcov/genhtml to generate a coverage badge.
USAGE:
lcov_badge_generator [FLAGS] [OPTIONS] <html_file>
FLAGS:
-h, --help Prints help information
-p, --print Only print coverage percentage to stdout
-V, --version Prints version information
OPTIONS:
-o, --output <OUTPUT_FILE> The output file [default: badge.svg]
ARGS:
<html_file> The generated index.html
```
<file_sep>/src/main.rs
use badge::{Badge, BadgeOptions};
use clap::{crate_version, App, Arg};
use scraper::{Html, Selector};
use std::fs::File;
use std::io::prelude::*;
use std::io::Read;
fn main() {
// CLI arguments handling
let matches = App::new("lcov_badge_generator")
.version(crate_version!())
.about("Parse html output from gcov/lcov/genhtml to generate a coverage badge.")
.arg(
Arg::with_name("html_file")
.help("The generated index.html")
.required(true),
)
.arg(
Arg::with_name("output")
.short("o")
.long("output")
.value_name("OUTPUT_FILE")
.help("The output file")
.default_value("badge.svg")
.takes_value(true),
)
.arg(
Arg::with_name("print")
.short("p")
.long("print")
.help("Only print coverage percentage to stdout")
.conflicts_with("output"),
)
.get_matches();
// Read the HTML file
let mut file = File::open(matches.value_of("html_file").unwrap()).expect("file not found");
let mut html_content = String::new();
file.read_to_string(&mut html_content)
.expect("something went wrong reading the file");
let document = Html::parse_document(&html_content);
// Parse the html to find the element with selector
let selector = Selector::parse("body > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(7)").unwrap();
let lines_coverage_element = document.select(&selector).next().unwrap();
let lines_coverage = lines_coverage_element.inner_html();
if matches.is_present("print") {
print!("{}", lines_coverage);
} else {
// Generate the badge
let badge = Badge::new(BadgeOptions {
subject: "coverage".to_owned(),
status: lines_coverage,
color: "#4c1".to_owned(),
})
.unwrap();
// Write the svg file
let mut badge_file = File::create(matches.value_of("output").unwrap())
.expect("Failed to create badege file");
badge_file
.write_all(badge.to_svg().as_bytes())
.expect("Failed to write badgesvg file");
}
}
<file_sep>/Cargo.toml
[package]
name = "lcov_badge_generator"
version = "0.2.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
license-file = "LICENSE"
readme = "README.md"
description = "CI Badge generator for LCOV reports"
repository = "https://github.com/rmainreignier/lcov_badge_generator"
[profile.release]
opt-level = 'z'
lto = true
panic = 'abort'
[dependencies]
clap = "~2.33"
scraper = "0.11.0"
badge = "0.2.0"
| 5d0dd67f2d7b88043b9cc20d444dd7331f4cea49 | [
"Markdown",
"Rust",
"TOML"
]
| 3 | Markdown | romainreignier/lcov_badge_generator | bd1b6c3f29efe4cc2843c427418e8d44dae404ae | 00ac5dbdd0d204c8e7939059125deca56d3fd41d |
refs/heads/master | <file_sep>const express = require("express");
const router = express.Router();
const User = require("../model/user");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const multer = require("multer");
const checkAuth = require("../middleware/check-auth");
var userId;
var date= new Date;
var dateString;
//console.log(dateString);
//const imagePath= require("../../../CORMS/src/assets/image"
router.post("/signup", (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(hash => {
const user = new User({
email: req.body.email,
password: <PASSWORD>
});
user.save().then(result => {
res.status(201).json({
message: 'user added!',
result: result
});
})
.catch(err => {
res.status(500).json({
message: 'Username already exists!'
})
})
});
})
router.post("/login", (req, res, next) => {
let fetchedUser;
User.findOne({ email: req.body.email })
.then(user => {
console.log(user)
if (!user) {
return res.status(401).json({
message: "User not found!"
});
}
this.userId=user;
fetchedUser = user;
return bcrypt.compare(req.body.password, user.password);
}).then(result => {
console.log(result)
if (!result) {
return res.status(401).json({ message: "Invalid username and password" });
}
const token = jwt.sign({ email: fetchedUser.email, userId: fetchedUser._id }, 'secret_hash', { expiresIn: "1h" });
res.status(200).json({ token: token, expiresIn: 3600, userId: fetchedUser._id, username:fetchedUser.email })
}).catch(err => {
return res.status(401).json({ message: "User Authentication Failed! Please check your username and password!" })
})
});
const storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, '../../../CORMS/CORMS/src/assets/image')
},
filename: (req, file, callBack) => {
//callBack(null, `image_${file.originalname}`)
// this.userId=localStorage.getItem("userId");
this.dateString=date.getFullYear()+""+date.getDate()+""+""+date.getHours()+""+date.getMinutes()
callBack(null, this.userId._id+'.'+'jpeg')
}
});
const upload = multer({ storage: storage })
router.post("/image", checkAuth, upload.single('file'), (req, res, next) => {
const file = req.file;
//console.log(file.filename);
if (!file) {
const error = new Error('No File')
error.httpStatusCode = 400
return next(error)
}
res.send(file);
});
module.exports = router;<file_sep>const express = require("express");
const router = express.Router();
const Post = require("../model/post");
const checkAuth= require("../middleware/check-auth")
router.post("", checkAuth, (req, res, next) => {
const post = new Post({
name: req.body.name,
description: req.body.description,
picture: req.body.picture,
creator:req.userData.userId
});
post.save(); // saving document to collection of MongoDB.
console.log(post);
res.status(201).json({
message: "Posts Added Successfully"
}); //201 new resource was created
});
router.get("", (req, res, next) => {
// '/api/ indicates this is a rest API.
//res.send("Hello from Express.js"); //returns the response
Post.find().then(documents => {
console.log("documents :" + JSON.stringify(documents));
res.status(200).json({
message: "posts fectched successfully!",
posts: documents
});
});
});
router.get("/:id",(req,res,next)=>{
Post.findById(req.params.id).then(post=>{
if(post){
res.status(200).json(post)
}
else{
res.status(404).json({message:'Post not found!'})
}
}
)
})
router.delete("/:id", checkAuth, (req, res, nex) => {
Post.deleteOne({ _id: req.params.id ,creator:req.userData.userId }).then(result => {
if(result.n>0){
res.status(200).json({ message: "Update successful" });
}
else{
res.status(401).json({ message: "Not Authorized!" });
}
})
});
router.put("/:id",checkAuth, (req, res, next) => {
const post = new Post({
_id: req.body.id,
name: req.body.name,
description: req.body.description,
picture: req.body.picture,
creator:req.userData.userId
});
Post.updateOne({ _id: req.params.id, creator:req.userData.userId }, post).then(result => {
if(result.nModified>0){
res.status(200).json({ message: "Update successful" });
}
else{
res.status(401).json({ message: "Not Authorized!" });
}
});
})
module.exports = router;
<file_sep>export interface Roster {
id:string;
username: string;
organization: string;
}
<file_sep>const express = require("express");
const bodyParser = require("body-parser");
const app = express(); //big chain of middleware we apply to incoming requests. Like a big funnel where each part of the funnel that can do something with the request
const mongoose = require("mongoose");
const Post = require("./model/post");
const postRoutes=require("./routes/postRoutes")
const userRoutes=require("./routes/userRoutes")
const rosterRoutes=require("./routes/rosterRoutes")
mongoose
.connect(
"mongodb+srv://anmolk7:<EMAIL>/CORMSNEW?retryWrites=true&w=majority"
)
.then(() => {
console.log("Connected to MongoDB");
})
.catch(() => {
console.log("Connection Failed!");
});
app.use(bodyParser.json()); //extracts the incoming request and converts the stream of data in request and adds it to the post request object.
app.use(bodyParser.urlencoded({ extended: false }));
//CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*"); //allow access to all resource
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET,POST,PATCH,DELETE,PUT,OPTIONS"
);
next();
});
app.use("/api/posts",postRoutes)
app.use("/api/user/",userRoutes)
app.use("/api/join", rosterRoutes)
module.exports=app<file_sep>import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req:HttpRequest<any>, next:HttpHandler){ //Augular calls this method for any HttpRequests leaving this app.
const authToken= this.authService.getToken();
const authRequest=req.clone({
headers:req.headers.set('Authorization', "Bearer "+authToken) //setting the auth header on the frontend
})
return next.handle(authRequest); // manipulating incoming requests and adding authorization token on header on the request
}
}<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AuthData } from './auth-data.model';
import { Subject, Subscription } from 'rxjs';
import { Router } from '@angular/router';
@Injectable({ providedIn: "root" })
export class AuthService {
private isAuthenticated = false;
private token: string;
private authStatusListener = new Subject<boolean>();
private tokenTime: any;
private userId: string;
private username: string;
constructor(private http: HttpClient, public router: Router) { }
getToken() {
return this.token;
}
getUserId(){
return this.userId;
}
getUsername(){
return this.username;
}
getAuthStatusListener() {
return this.authStatusListener.asObservable();
}
getIsAuth() {
return this.isAuthenticated;
}
createUser(email: string, password: string) {
const authData: AuthData = { email: email, password: <PASSWORD> };
this.http.post("http://localhost:3000/api/user/signup", authData).subscribe(() => {
this.router.navigate(['/']);
},error=>{
this.authStatusListener.next(false);
}
)
}
login(email: string, password: string) {
const authData: AuthData = { email: email, password: <PASSWORD> };
this.http.post<{ token: string, expiresIn: number,userId:string, username:string }>("http://localhost:3000/api/user/login", authData).subscribe(response => {
const token = response.token;
this.token = token;
if (token) {
const expireDuration = response.expiresIn;
console.log(expireDuration);
this.setAuthTime(expireDuration);
this.isAuthenticated = true;
this.userId=response.userId;
this.username=response.username;
this.authStatusListener.next(true);
const now = new Date();
const expirationDate = new Date(now.getTime() + expireDuration * 1000)
this.authSave(token, expirationDate,this.userId, this.username)
console.log(expirationDate);
this.router.navigate(['/'])
console.log(token);
}
}, error =>{
this.authStatusListener.next(false);
})
}
logout() {
this.token = null;
this.isAuthenticated = false;
this.authStatusListener.next(false);
this.authClear();
clearTimeout(this.tokenTime);
this.router.navigate(['/']);
this.userId=null;
this.username=null;
}
autoAuthUser() {
const authInformation = this.getAuthData();
if (!authInformation) {
return;
}
const now = new Date();
const expiresIn = authInformation.expirationDate.getTime() - now.getTime();
if (expiresIn > 0) {
this.token = authInformation.token;
this.isAuthenticated = true;
this.userId=authInformation.userId;
this.username=authInformation.username;
console.log("UserID: "+this.userId)
this.setAuthTime(expiresIn / 1000);
this.authStatusListener.next(true);
}
}
private setAuthTime(duration: number) {
//console.log("setting duration " + duration);
this.tokenTime = setTimeout(() => { this.logout(); }, duration * 1000)
}
private authSave(token: string, expireDate: Date, userId:string, username:string) {
localStorage.setItem('token', token);
localStorage.setItem('expiration', expireDate.toISOString());
localStorage.setItem('userId',userId);
localStorage.setItem('username',username)
}
private authClear() {
localStorage.removeItem("token");
localStorage.removeItem("expiration");
localStorage.removeItem("username");
}
private getAuthData() {
const token = localStorage.getItem("token");
const expirationDate = localStorage.getItem("expiration");
const userId= localStorage.getItem("userId");
const username=localStorage.getItem("username");
if (!token || !expirationDate) {
return;
}
return {
token: token,
expirationDate: new Date(expirationDate),
userId:userId,
username:username
}
}
}<file_sep>import { Component, OnInit, OnDestroy } from "@angular/core";
import { Router } from "@angular/router";
import { AuthService } from '../auth/auth.service';
import { Subscription } from 'rxjs';
@Component({
selector: "app-header",
templateUrl: "./header.component.html",
styleUrls: ["./header.component.css"]
})
export class HeaderComponent implements OnInit, OnDestroy{
userIsAuthenticated=false;
userId:string;
private authListenerSubs: Subscription;
username:string;
user:string
constructor(public router: Router, private authService:AuthService) {}
ngOnInit(){
this.userId=this.authService.getUserId();
this.username=this.authService.getUsername();
if(this.username){
this.user=this.username.split('@')[0].toUpperCase();
}
// console.log("header user: "+this.userId+" "+this.username)
this.userIsAuthenticated=this.authService.getIsAuth();
this.authListenerSubs=this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
this.userIsAuthenticated=isAuthenticated;
this.userId=this.authService.getUserId();
this.username=this.authService.getUsername();
if(this.username){
this.user=this.username.split('@')[0].toUpperCase();
}
// console.log("header user: "+this.userId+" "+this.username)
})
}
ngOnDestroy(){
this.authListenerSubs.unsubscribe();
}
logout(){
this.authService.logout();
}
}
<file_sep>import { Component, OnInit } from "@angular/core";
import { NgForm } from "@angular/forms";
import { PostService } from "../../service/post.service";
import { ActivatedRoute, ParamMap, Router } from "@angular/router";
import { Post } from "../post.model";
import { MatSnackBar } from '@angular/material/snack-bar';
import { Subscription } from 'rxjs';
import { AuthService } from 'src/app/auth/auth.service';
import { Roster } from '../roster.model';
@Component({
selector: "app-post-create",
templateUrl: "./post-create.component.html",
styleUrls: ["./post-create.component.css"]
})
export class PostCreateComponent implements OnInit {
private mode = "create";
private postId: string;
post: Post;
duration=2;
private authStatus: Subscription;
private rosterSub: Subscription;
rosters: Roster[]=[];
userIsAuthenticated=false;
currentMembers: Roster[];
requestingMembers: Roster[];
constructor(
public postService: PostService,
public activeRoute: ActivatedRoute,
public router: Router,
public snackBar: MatSnackBar,
public authService: AuthService
) {}
ngOnInit() {
this.activeRoute.paramMap.subscribe((paramMap: ParamMap) => {
if (paramMap.has("postId")) {
//extract postId from current URL
this.mode = "edit";
this.postId = paramMap.get("postId");
this.postService.getPost(this.postId).subscribe(postData=>{
this.post={id:postData._id, name:postData.name, description:postData.description, picture:postData.picture, creator:postData.creator }
});
} else {
this.mode = "create";
this.postId = null;
}
});
this.postService.getMembers();
this.rosterSub= this.postService.getRosterUpdateListener()
.subscribe((rosters:Roster[])=>{
this.rosters=rosters;
console.log("Rosters: "+JSON.stringify(this.rosters));
});
this.userIsAuthenticated=this.authService.getIsAuth();
console.log("Authenticated ?"+this.userIsAuthenticated)
this.authStatus=this.authService.getAuthStatusListener().subscribe(isAuthenticated=>{
this.userIsAuthenticated=isAuthenticated
})
console.log("Authenticated ?"+this.userIsAuthenticated)
}
onAddPost(form: NgForm) {
if (form.invalid) {
return;
}
// snackbar pop-up
this.snackBar.openFromComponent(PizzaPartyComponent, {
duration: this.duration * 1000,
panelClass: ['snackbar']
});
if (this.mode === "create") {
this.postService.addPosts(
form.value.name,
form.value.description,
form.value.picture
);
} else {
this.postService.updatePost(
this.postId,
form.value.name,
form.value.description,
form.value.picture
);
}
form.resetForm();
}
}
@Component({
selector: 'app-post-create-pop',
templateUrl: './post-success.html',
styleUrls: ["./post-create.component.css"]
})
export class PizzaPartyComponent {
constructor(public router:Router){}
}<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
import { Roster } from '../posts/roster.model';
import { Subscription } from 'rxjs';
import { PostService } from '../service/post.service';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements OnInit {
title = 'fileUpload';
images;
multipleImages = [];
imagepath;
username;
rosters: Roster[];
private rosterSub: Subscription;
constructor(private http: HttpClient, public authService: AuthService, public postService:PostService){}
ngOnInit(){
this.imagepath="../../assets/image/"+this.authService.getUserId()+'.'+'jpeg'
this.username=this.authService.getUsername();
this.rosterSub= this.postService.getRosterUpdateListener()
.subscribe((rosters:Roster[])=>{
this.rosters=rosters;
console.log("Rosters: "+JSON.stringify(this.rosters));
});
//console.log(this.imagepath);
}
selectImage(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.images = file;
}
}
onSubmit(){
const formData = new FormData();
formData.append('file', this.images);
this.http.post<any>("http://localhost:3000/api/user/image", formData).subscribe(
(res) => console.log(res),
(err) => console.log(err)
);
}
}
<file_sep>import { Post } from "../posts/post.model";
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { HttpClient } from "@angular/common/http";
import { map } from "rxjs/operators";
import { Roster } from '../posts/roster.model';
@Injectable({ providedIn: "root" }) //uses same instance where ever it is injected
export class PostService {
private posts: Post[] = [];
private roster: Roster[]=[];
private postUpdated = new Subject<Post[]>();
private rosterUpdated = new Subject<Roster[]>();
constructor(private http: HttpClient) {}
getPosts() {
//return [...this.posts];
this.http
.get<{ message: string; posts: any }>("http://localhost:3000/api/posts")
.pipe(
map(postData => {
//return id as _id
return postData.posts.map(post => {
return {
name: post.name,
description: post.description,
picture: post.picture,
id: post._id,
creator: post.creator
};
});
})
)
.subscribe(transformedPosts => {
this.posts = transformedPosts;
this.postUpdated.next([...this.posts]);
});
}
getMembers(){
this.http
.get<{ message: string; rosters: any }>("http://localhost:3000/api/join")
.pipe(
map(memberData => {
//return id as _id
return memberData.rosters.map(roster => {
return {
username: roster.username,
organization:roster.organization
};
});
})
)
.subscribe(transformedRosters => {
this.roster = transformedRosters;
this.rosterUpdated.next([...this.roster]);
});
}
getRosterUpdateListener(){
return this.rosterUpdated.asObservable();
}
getPostUpdateListener() {
return this.postUpdated.asObservable();
}
getAllMembers(){
return this.http
.get<{rosters: any }>("http://localhost:3000/api/join")
.pipe(
map(memberData => {
//return id as _id
return memberData.rosters.map(roster => {
return {
username: roster.username,
organization:roster.organization
};
});
})
)
}
getPost(id:string){
return this.http.get<{_id:string, name:string, description:string, picture:string, creator:string}>("http://localhost:3000/api/posts/"+id);
}
joinOrg(username:string, organization:string){
const roster: Roster={
id:null,
username:username,
organization:organization
}
this.http.post<{message:string}>("http://localhost:3000/api/join",roster) .subscribe(responseData => {
console.log(
"response Data " + responseData.message + JSON.stringify(roster)
);
this.roster.push(roster);
this.rosterUpdated.next([...this.roster]);
});
}
addPosts(name: string, description: string, picture: string) {
const post: Post = {
id: null,
name: name,
description: description,
picture: picture,
creator:null
};
this.http
.post<{ message: string }>("http://localhost:3000/api/posts", post)
.subscribe(responseData => {
console.log(
"response Data " + responseData.message + JSON.stringify(post)
);
this.posts.push(post);
this.postUpdated.next([...this.posts]);
});
}
getPostId(id: string) {
return { ...this.posts.find(p => p.id === id) };
}
deletePost(postId: string) {
this.http
.delete("http://localhost:3000/api/posts/" + postId)
.subscribe(() => {
console.log("Deleted!");
const updatedPosts = this.posts.filter(post => post.id !== postId);
this.posts = updatedPosts;
this.postUpdated.next([...this.posts]);
});
}
updatePost(id: string, name: string, description: string, picture: string) {
const post: Post = {
id: id,
name: name,
description: description,
picture: picture,
creator:null
};
this.http
.put("http://localhost:3000/api/posts/" + post.id, post)
.subscribe(response => {
const updatedPosts=[...this.posts];
const oldPostIndex=updatedPosts.findIndex(p=>p.id===post.id);
updatedPosts[oldPostIndex]=post;
this.posts=updatedPosts;
this.postUpdated.next([...this.posts]);
});
}
}
<file_sep>import { Component, OnInit, OnDestroy } from "@angular/core";
import { Subscription } from "rxjs";
import { Post } from "../post.model";
import { PostService } from "../../service/post.service";
import { AuthService } from 'src/app/auth/auth.service';
import { Roster } from '../roster.model';
import { MatButton } from '@angular/material';
@Component({
selector: "app-post-list",
templateUrl: "./post-list.component.html",
styleUrls: ["./post-list.component.css"]
})
export class PostListComponent implements OnInit, OnDestroy {
posts: Post[] = [];
rosters: Roster[];
private postsSub: Subscription;
private authStatus: Subscription;
userIsAuthenticated = false;
userId: string;
username: string;
duplicateRoster: Roster;
ngOnInit() {
this.postService.getPosts();
console.log(this.rosters);
this.userId = this.authService.getUserId();
this.username = this.authService.getUsername();
this.postsSub = this.postService
.getPostUpdateListener()
.subscribe((posts: Post[]) => {
this.posts = posts;
});
this.userIsAuthenticated = this.authService.getIsAuth();
this.userId = this.authService.getUserId();
console.log("userId: " + this.userId)
this.authStatus = this.authService.getAuthStatusListener().subscribe(isAuthenticated => {
this.userIsAuthenticated = isAuthenticated;
})
}
onDelete(postId: string) {
this.postService.deletePost(postId);
}
onJoin(organization: string, joinButton: MatButton) {
console.log(joinButton._elementRef.nativeElement);
this.postService.getAllMembers().subscribe(roster => {
this.rosters = roster
this.duplicateRoster = this.rosters.find((e: Roster) => e.username === this.username && e.organization === organization)
console.log(this.duplicateRoster);
if (this.duplicateRoster) {
alert('You have already sent a request to join ' + organization + " club")
}
else {
alert('Request sent to join ' + organization + " club")
this.postService.joinOrg(this.username, organization)
}
});
}
ngOnDestroy() {
this.postsSub.unsubscribe();
}
constructor(public postService: PostService, public authService: AuthService) { }
}
| dd0c2e989e8fbfb2d7d01a754a227b62f6d430c8 | [
"JavaScript",
"TypeScript"
]
| 11 | JavaScript | Anmolk7/CORMS | 6b372eacc7e8da20906b4abaed6a5eb433c6ff93 | 6aaeca8917a7ff6f0738ee3b6f62dfbfca4a492d |
refs/heads/main | <file_sep>module.exports = (sequelize, Sequelize) => {
const CarPartOffice = sequelize.define('carPartOffice', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
description: {
type: Sequelize.TEXT,
},
image: {
type: Sequelize.TEXT('tiny'),
},
});
return CarPartOffice;
};
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import ReviewsService from '../services/ReviewsService';
interface IState {
data: IReviews[] | null;
}
const initialState: IState = {
data: null
};
export interface IReviews {
id: number;
fullName: string;
text: string;
image: string;
}
export const reviews = createModel<IRootModel>()({
state: initialState,
reducers: {
setRevies(state, data: IReviews[]): IState {
return { ...state, data };
}
},
effects: d => {
return {
async getReviews() {
const { data } = await ReviewsService.getReviews();
if (data) {
d.reviews.setRevies(data);
}
},
async addReviews(model: IReviews) {
const { data } = await ReviewsService.addReviews(model);
if (data) {
d.reviews.getReviews();
}
},
async updateReviews(model: IReviews) {
const { data } = await ReviewsService.updateReviews(model);
if (data) {
d.reviews.getReviews();
}
},
async deleteReviews(id: number) {
const { data } = await ReviewsService.deleteReviews(id);
if (data) {
d.reviews.getReviews();
}
}
};
}
});
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const CorporateClientImage = db.corporateClientImage;
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
CorporateClientImage.findOne({
where: {
corporateClientId: req.body.corporateClientId,
imageId: req.body.imageId,
},
})
.then((item) => {
if (!item) {
return CorporateClientImage.create({
corporateClientId: req.body.corporateClientId,
imageId: req.body.imageId,
}).then((corporateClientImage) => corporateClientImage);
}
throw new Error('Whoops!');
})
.then((corporateClientImage) => {
return res.status(201).json(corporateClientImage);
})
.catch((err) => res.status(400).json(err));
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
CorporateClientImage.destroy({
where: { id: req.params.id },
})
.then((corporateClientImage) => res.status(200).json(corporateClientImage))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>export const imageUploadUrl = `${window.location.origin}/api/admin/uploads`;
<file_sep>module.exports = (sequelize, Sequelize) => {
const Office = sequelize.define('office', {
address: {
type: Sequelize.TEXT('tiny'),
},
fullAddress: {
type: Sequelize.TEXT('tiny'),
},
tel: {
type: Sequelize.TEXT('tiny'),
},
fullTel: {
type: Sequelize.TEXT('tiny'),
},
telegram: {
type: Sequelize.TEXT('tiny'),
},
viber: {
type: Sequelize.TEXT('tiny'),
},
whatsapp: {
type: Sequelize.TEXT('tiny'),
},
email: {
type: Sequelize.TEXT('tiny'),
},
description: {
type: Sequelize.TEXT,
},
locationLat: {
type: Sequelize.TEXT('tiny'),
},
locationLon: {
type: Sequelize.TEXT('tiny'),
},
workingHours: {
type: Sequelize.TEXT('tiny'),
},
});
return Office;
};
<file_sep>module.exports = (sequelize, Sequelize) => {
const Promo = sequelize.define('promo', {
titleForMain: {
type: Sequelize.TEXT('tiny'),
},
title: {
type: Sequelize.TEXT('tiny'),
},
description: {
type: Sequelize.TEXT,
},
shortDescription: {
type: Sequelize.TEXT,
},
image: {
type: Sequelize.TEXT('tiny'),
},
sliderImage: {
type: Sequelize.TEXT('tiny'),
},
});
return Promo;
};
<file_sep>const db = require('../models/index');
const CorporateClients = db.corporateClients;
const Images = db.images;
exports.getCorporateClients = () => {
return CorporateClients.findOne({ include: Images });
};
<file_sep>import axios from 'axios';
import { ICarParts } from '../models/carParts';
const url = '/api/admin/carparts';
const CarPartsService = {
getCarParts: () => axios.get<ICarParts>(url),
addCarParts: (data: ICarParts) => axios.post<ICarParts>(url, data),
updateCarParts: ({ id, ...rest }: ICarParts) => axios.put<ICarParts>(`${url}/${id}`, rest)
};
export default CarPartsService;
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import OfficesService from '../services/OfficesService';
import { ICarPartsOffices } from './carPartsOffices';
interface IState {
data: IOffices[] | null;
}
const initialState: IState = {
data: null,
};
export interface IOffices {
id: number;
address: string;
fullAddress: string;
tel: string;
fullTel: string;
telegram: string;
viber: string;
whatsapp: string;
description: string;
email: string;
locationLat: string;
locationLon: string;
workingHours: string;
}
export interface IOfficesForm extends IOffices {
location: { lat: number; lng: number };
}
export interface IOficesCarparts extends IOffices {
carPartOffice: ICarPartsOffices;
}
export const offices = createModel<IRootModel>()({
state: initialState,
reducers: {
setOffices(state, data: IOffices[]): IState {
return { ...state, data };
},
},
effects: (d) => {
return {
async getOffices() {
const { data } = await OfficesService.getOffices();
if (data) {
d.offices.setOffices(data);
}
},
async addOffices(model: IOffices) {
const { data } = await OfficesService.addOffices(model);
if (data) {
d.offices.getOffices();
}
},
async updateOffices(model: IOffices) {
const { data } = await OfficesService.updateOffices(model);
if (data) {
d.offices.getOffices();
}
},
async deleteOffices(id: number) {
const { data } = await OfficesService.deleteOffices(id);
if (data) {
d.offices.getOffices();
}
},
};
},
});
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const CorporateClients = db.corporateClients;
const corporateClientsController = require('../../controllers/corporateClients.controller');
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
corporateClientsController
.getCorporateClients()
.then((corporateClients) => {
if (!corporateClients) {
return res.status(200).json(null);
}
res.json(corporateClients);
})
.catch((err) => res.status(404).json(err));
});
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
CorporateClients.findOne()
.then((corporateClients) => {
if (!corporateClients) {
return CorporateClients.create({
title: req.body.title,
description: req.body.description,
info: req.body.info,
}).then((corporateClient) => corporateClient);
}
throw new Error('Whoops!');
})
.then((corporateClient) => res.status(201).json(corporateClient))
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
CorporateClients.update(
{
title: req.body.title,
description: req.body.description,
info: req.body.info,
},
{ where: { id: req.params.id } }
)
.then((corporateClient) => {
return res.status(200).json(corporateClient);
})
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>import axios from 'axios';
import { IServiceOffice } from '../models/services';
const url = '/api/admin/servicesoffices';
const ServicesOfficesService = {
addServicesOffices: (data: IServiceOffice) => axios.post<IServiceOffice>(url, data),
updateServicesOffices: ({ id, ...rest }: IServiceOffice) => axios.put<IServiceOffice>(`${url}/${id}`, rest),
deleteServicesOffices: (id: number) => axios.delete(`${url}/${id}`)
};
export default ServicesOfficesService;
<file_sep>import axios from 'axios';
import { IOffices } from '../models/offices';
const url = '/api/admin/offices';
const OfficesService = {
getOffices: () => axios.get<IOffices[]>(url),
addOffices: (data: IOffices) => axios.post<IOffices>(url, data),
updateOffices: ({ id, ...rest }: IOffices) => axios.put<IOffices>(`${url}/${id}`, rest),
deleteOffices: (id: number) => axios.delete(`${url}/${id}`)
};
export default OfficesService;
<file_sep>module.exports = (sequelize, Sequelize) => {
const CorporateClient = sequelize.define('corporateClient', {
title: {
type: Sequelize.TEXT('tiny'),
},
description: {
type: Sequelize.TEXT,
},
info: {
type: Sequelize.TEXT,
},
});
return CorporateClient;
};
<file_sep>import { createModel } from '@rematch/core';
import { push } from 'connected-react-router';
import { IRootModel } from '.';
import AuthSevice from '../services/AuthSevice';
interface IState {
isAuth: boolean;
errors: any;
}
const initialState: IState = {
isAuth: false,
errors: null,
};
export interface IAuth {
succces: boolean;
token: string;
}
export interface IUserLogin {
login: string;
password: string;
}
export const auth = createModel<IRootModel>()({
state: initialState,
reducers: {
login(state): IState {
return { ...state, isAuth: true };
},
logout(state): IState {
return { ...state, isAuth: false };
},
},
effects: (d) => {
return {
async onLogin(params: IUserLogin) {
const { data } = await AuthSevice.login(params);
if (data.succces) {
localStorage.setItem('jwtToken', data.token);
d.auth.login();
}
},
async onLogout() {
localStorage.removeItem('jwtToken');
d(push('/'));
d.auth.logout();
},
};
},
});
<file_sep>import axios from 'axios';
import { ICorporateClientImage } from '../models/corporateClientsImages';
const url = '/api/admin/corporateclientsimages';
const CorporateClientsImagesService = {
addCorporateClientsImages: (data: ICorporateClientImage) => axios.post<ICorporateClientImage>(url, data)
};
export default CorporateClientsImagesService;
<file_sep>import axios from 'axios';
import { IAuth, IUserLogin } from '../models/auth';
const url = '/api/auth';
const AuthSevice = {
login: (params: IUserLogin) => axios.post<IAuth>(`${url}/login`, params)
};
export default AuthSevice;
<file_sep>const db = require('../models/index');
const MainPage = db.mainPage;
exports.getMainPage = () => {
return MainPage.findOne();
};
<file_sep>import axios from 'axios';
import { IReviews } from '../models/reviews';
const url = '/api/admin/reviews';
const ReviewsService = {
getReviews: () => axios.get<IReviews[]>(url),
addReviews: (data: IReviews) => axios.post<IReviews>(url, data),
updateReviews: ({ id, ...rest }: IReviews) => axios.put<IReviews>(`${url}/${id}`, rest),
deleteReviews: (id: number) => axios.delete(`${url}/${id}`)
};
export default ReviewsService;
<file_sep>const db = require('../models/index');
const Reviews = db.reviews;
exports.getReviews = () => {
return Reviews.findAll();
};
<file_sep>const express = require('express');
const router = express.Router();
const db = require('../../models/index');
const User = db.users;
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const keys = require('../../config/keys');
// const validateRegisterInput = require('../../validation/register');
const validateLoginInput = require('../../validation/login');
// User register
// router.post('/register/user', (req, res) => {
// const { errors, isValid } = validateRegisterInput(req.body);
// if (!isValid) {
// return res.status(400).json(errors);
// }
// User.findOne({ where: { login: req.body.login } }).then((user) => {
// if (user) {
// errors.login = 'Имя уже используется';
// return res.status(400).json(errors);
// } else {
// const newUser = new User({
// login: req.body.login,
// password: <PASSWORD>,
// });
// bcrypt.genSalt(10, (err, salt) => {
// bcrypt.hash(newUser.password, salt, (err, hash) => {
// if (err) throw err;
// newUser.password = <PASSWORD>;
// newUser
// .save()
// .then((user) => res.json(user))
// .catch((err) => console.log(err));
// });
// });
// }
// });
// });
// User login
router.post('/login', (req, res) => {
const { errors, isValid } = validateLoginInput(req.body);
if (!isValid) {
return res.status(422).json(errors);
}
const login = req.body.login;
const password = <PASSWORD>;
User.findOne({ where: { login } }).then((user) => {
if (!user) {
errors.error = 'Некорректные авторизационные данные';
return res.status(422).json(errors);
}
bcrypt.compare(password, user.password).then((isMatch) => {
if (isMatch) {
const payload = { id: user.id, login: user.login };
jwt.sign(payload, keys.secretOrKey, { expiresIn: '10h' }, (err, token) => {
res.json({
succces: true,
token: 'Bearer ' + token,
});
});
} else {
errors.error = 'Некорректные авторизационные данные';
return res.status(422).json(errors);
}
});
});
});
module.exports = router;
<file_sep>module.exports = (sequelize, Sequelize) => {
const Images = sequelize.define('images', {
filename: {
type: Sequelize.TEXT('tiny'),
},
extension: {
type: Sequelize.TEXT('tiny'),
},
url: {
type: Sequelize.TEXT,
},
});
return Images;
};
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import UploadsService from '../services/UploadsService';
interface IState {
data: IUploads | null;
}
const initialState: IState = {
data: null
};
export interface IUploads {
id: number;
extension: string;
filename: string;
url: string;
}
export const uploads = createModel<IRootModel>()({
state: initialState,
reducers: {},
effects: d => {
return {
async deleteImage(imageId: number) {
return UploadsService.deleteImage(imageId);
}
};
}
});
<file_sep>import axios from 'axios';
const url = '/api/admin/uploads';
const UploadsService = {
deleteImage: (imageId: number) => axios.delete(`${url}/${imageId}`)
};
export default UploadsService;
<file_sep>const Sequelize = require('sequelize');
const sequelize = new Sequelize('masterdb', 'root', '!<PASSWORD>', {
dialect: 'mysql',
host: 'localhost',
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
// Tables
db.users = require('./user.model.js')(sequelize, Sequelize);
db.mainPage = require('./mainPage.model.js')(sequelize, Sequelize);
db.offices = require('./office.model.js')(sequelize, Sequelize);
db.images = require('./images.model.js')(sequelize, Sequelize);
db.services = require('./service.model.js')(sequelize, Sequelize);
db.serviceOffice = require('./serviceOffice.model')(sequelize, Sequelize);
db.services.belongsToMany(db.offices, { through: db.serviceOffice });
db.carParts = require('./carPart.model.js')(sequelize, Sequelize);
db.promos = require('./promo.model.js')(sequelize, Sequelize);
db.corporateClients = require('./corporateClients.model.js')(sequelize, Sequelize);
db.corporateClientImage = require('./corporateClientImage.model.js')(sequelize, Sequelize);
db.corporateClients.belongsToMany(db.images, { through: db.corporateClientImage });
db.mainPage = require('./mainPage.model.js')(sequelize, Sequelize);
db.carPartOffice = require('./carPartOffice.model')(sequelize, Sequelize);
db.carParts.belongsToMany(db.offices, { through: db.carPartOffice });
db.reviews = require('./review.model')(sequelize, Sequelize);
module.exports = db;
<file_sep>import axios from 'axios';
import { IPromos } from '../models/promos';
const url = '/api/admin/promos';
const PromosService = {
getPromos: () => axios.get<IPromos[]>(url),
addPromos: (data: IPromos) => axios.post<IPromos>(url, data),
updatePromos: ({ id, ...rest }: IPromos) => axios.put<IPromos>(`${url}/${id}`, rest),
deletePromos: (id: number) => axios.delete(`${url}/${id}`)
};
export default PromosService;
<file_sep>import axios from 'axios';
import { ICorporateClients, ICorporateClientsFromServer } from '../models/corporateClients';
const url = '/api/admin/corporateclients';
const CorporateClientsService = {
getCorporateClients: () => axios.get<ICorporateClientsFromServer>(url),
addCorporateClients: (data: ICorporateClients) => axios.post<ICorporateClients>(url, data),
updateCorporateClients: ({ id, ...rest }: ICorporateClients) => axios.put<ICorporateClients>(`${url}/${id}`, rest)
};
export default CorporateClientsService;
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import PromosService from '../services/PromosService';
interface IState {
data: IPromos[] | null;
}
const initialState: IState = {
data: null,
};
export interface IPromos {
id: number;
titleForMain: string;
title: string;
description: string;
shortDescription: string;
image: string;
sliderImage: string;
}
export const promos = createModel<IRootModel>()({
state: initialState,
reducers: {
setPromos(state, data: IPromos[]): IState {
return { ...state, data };
},
},
effects: (d) => {
return {
async getPromos() {
const { data } = await PromosService.getPromos();
if (data) {
d.promos.setPromos(data);
}
},
async addPromos(model: IPromos) {
const { data } = await PromosService.addPromos(model);
if (data) {
d.promos.getPromos();
}
},
async updatePromos(model: IPromos) {
const { data } = await PromosService.updatePromos(model);
if (data) {
d.promos.getPromos();
}
},
async deletePromos(id: number) {
const { data } = await PromosService.deletePromos(id);
if (data) {
d.promos.getPromos();
}
},
};
},
});
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import ServicesOfficesService from '../services/ServicesOfficesService';
import ServicesService from '../services/ServicesService';
import { IOffices } from './offices';
interface IState {
data: IServicesFromServer[] | null;
}
const initialState: IState = {
data: null,
};
export interface IServices {
id: number;
title: string;
cost: string;
description: string;
text: string;
image: string;
icon: string;
}
export interface IServicesForm extends IServices {
officesIds: number[];
}
export interface IServiceOffice {
id?: number;
isAvailable: boolean;
serviceId: number;
officeId: number;
}
export interface IServicesOffices extends IOffices {
serviceOffice: IServiceOffice;
}
export interface IServicesFromServer extends IServices {
offices: IServicesOffices[];
}
export interface IServicesToServer extends IServices {
servicesOffices: { id?: number; officeId: number; isAvailable: boolean }[];
newServicesOffices?: { id?: number; officeId: number; isAvailable: boolean }[];
}
export const services = createModel<IRootModel>()({
state: initialState,
reducers: {
setServices(state, data: IServicesFromServer[]): IState {
return { ...state, data };
},
},
effects: (d) => {
return {
async getServices() {
const { data } = await ServicesService.getServices();
if (data) {
d.services.setServices(data);
}
},
async addServices(model: IServicesToServer) {
const { servicesOffices, ...rest } = model;
const { data } = await ServicesService.addServices(rest);
await Promise.all(
servicesOffices.map((serviceOffice) => {
return ServicesOfficesService.addServicesOffices({
officeId: serviceOffice.officeId,
serviceId: data.id,
isAvailable: serviceOffice.isAvailable,
});
})
).then(() => {
if (data) {
d.services.getServices();
}
});
},
async updateServices(model: IServicesToServer) {
const { servicesOffices, newServicesOffices, ...rest } = model;
const { data } = await ServicesService.updateServices(rest);
await Promise.all(
servicesOffices.map((serviceOffice) => {
return ServicesOfficesService.updateServicesOffices({
id: serviceOffice.id,
officeId: serviceOffice.officeId,
serviceId: data.id,
isAvailable: serviceOffice.isAvailable,
});
})
);
if (newServicesOffices) {
await Promise.all(
newServicesOffices.map((serviceOffice) => {
return ServicesOfficesService.addServicesOffices({
officeId: serviceOffice.officeId,
serviceId: data.id,
isAvailable: serviceOffice.isAvailable,
});
})
);
}
await d.services.getServices();
},
async deleteServices(id: number) {
const { data } = await ServicesService.deleteServices(id);
if (data) {
d.services.getServices();
}
},
};
},
});
<file_sep>document.getElementById('menu-toggler').addEventListener('click', () => {
document.querySelector('ul.mobile-navbar').classList.toggle('active');
document.querySelector('ul.mobile-navbar.active > li > .services').classList.remove('active');
});
document.addEventListener('click', (e) => {
const menu = !!document.querySelector('ul.mobile-navbar.active');
const serviceItem = document.querySelector('ul.mobile-navbar.active > li > span');
if (e.target.id != 'menu-toggler' && e.target != serviceItem && menu) {
document.querySelector('ul.mobile-navbar').classList.remove('active');
}
if (e.target === serviceItem) {
document.querySelector('ul.mobile-navbar.active > li > .services').classList.toggle('active');
}
});
document.addEventListener('DOMContentLoaded', () => {
const url = window.location.pathname;
//array of menu items
const menuPoints = document.querySelectorAll('.desktop-navbar__item');
setActiveMenuItem(menuPoints, url);
});
setActiveMenuItem = (menuPoints, url) => {
if (url.indexOf('service') + 1) {
menuPoints.forEach((el) => {
if (el.innerText === 'Услуги') {
el.classList.add('active');
}
});
return;
}
switch (url) {
case '/':
menuPoints.forEach((el) => {
if (el.innerText === 'Главная') {
el.classList.add('active');
}
});
break;
case '/car-parts':
menuPoints.forEach((el) => {
if (el.innerText === 'Запчасти') {
el.classList.add('active');
}
});
break;
case '/corporate':
menuPoints.forEach((el) => {
if (el.innerText === 'Юр.лицам') {
el.classList.add('active');
}
});
break;
case '/contacts':
menuPoints.forEach((el) => {
if (el.innerText === 'Контакты') {
el.classList.add('active');
}
});
break;
}
};
function openMessenger(messenger, contact) {
let link = '';
switch (messenger) {
case 'whatsapp':
link = `https://wa.me/${contact}`;
break;
case 'viber':
link = `viber://chat?number=%2B${contact}`;
break;
case 'telegram':
link = `https://t.me/${contact}`;
break;
}
if (link) {
window.open(link);
}
}
function openMessengerFromPopup(officeData) {
const messenger = document.getElementById('messenger-argument').innerHTML;
openMessenger(messenger, officeData[messenger]);
}
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const Offices = db.offices;
const officesController = require('../../controllers/offices.controller');
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
officesController
.getOffices()
.then((offices) => {
if (offices && !offices.length) {
return res.status(200).json([]);
}
res.json(offices);
})
.catch((err) => res.status(404).json(err));
});
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
Offices.create({
address: req.body.address,
fullAddress: req.body.fullAddress,
tel: req.body.tel,
fullTel: req.body.fullTel,
telegram: req.body.telegram,
viber: req.body.viber,
whatsapp: req.body.whatsapp,
email: req.body.email,
description: req.body.description,
locationLat: req.body.locationLat,
locationLon: req.body.locationLon,
workingHours: req.body.workingHours,
})
.then((office) => res.status(201).json(office))
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
Offices.update(
{
address: req.body.address,
fullAddress: req.body.fullAddress,
tel: req.body.tel,
fullTel: req.body.fullTel,
telegram: req.body.telegram,
viber: req.body.viber,
whatsapp: req.body.whatsapp,
email: req.body.email,
description: req.body.description,
locationLat: req.body.locationLat,
locationLon: req.body.locationLon,
workingHours: req.body.workingHours,
},
{ where: { id: req.params.id } }
)
.then((office) => res.status(200).json(office))
.catch((err) => res.status(400).json(err));
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
Offices.destroy({
where: { id: req.params.id },
})
.then((office) => res.status(200).json(office))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>import axios from 'axios';
import { IServices, IServicesFromServer } from '../models/services';
const url = '/api/admin/services';
const ServicesService = {
getServices: () => axios.get<IServicesFromServer[]>(url),
addServices: (data: IServices) => axios.post<IServicesFromServer>(url, data),
updateServices: ({ id, ...rest }: IServices) => axios.put<IServicesFromServer>(`${url}/${id}`, rest),
deleteServices: (id: number) => axios.delete(`${url}/${id}`)
};
export default ServicesService;
<file_sep>const db = require('../models/index');
const CarParts = db.carParts;
const Offices = db.offices;
exports.getCarParts = () => {
return CarParts.findOne({ include: Offices });
};
<file_sep>export const tooltipText = `# Заголовок размер 1
## Заголовок размер 2
### Заголовок размер 3
#### Заголовок размер 4
1. Нумерованный список.
2. Нумерованный список.
Простой параграф [ссылка]
- Маркированный **список**.
- Маркированный **список**
[ссылка]: https://ptzmaster.com/`;
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const Promos = db.promos;
const promosController = require('../../controllers/promos.controller');
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
promosController
.getPromos()
.then((promos) => {
if (promos && !promos.length) {
return res.status(200).json([]);
}
res.json(promos);
})
.catch((err) => res.status(404).json(err));
});
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
Promos.create({
titleForMain: req.body.titleForMain,
title: req.body.title,
description: req.body.description,
shortDescription: req.body.shortDescription,
image: req.body.image,
sliderImage: req.body.sliderImage,
})
.then((promo) => res.status(201).json(promo))
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
Promos.update(
{
titleForMain: req.body.titleForMain,
title: req.body.title,
description: req.body.description,
shortDescription: req.body.shortDescription,
image: req.body.image,
sliderImage: req.body.sliderImage,
},
{ where: { id: req.params.id } }
)
.then((promo) => res.status(200).json(promo))
.catch((err) => res.status(400).json(err));
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
Promos.destroy({
where: { id: req.params.id },
})
.then((promo) => res.status(200).json(promo))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>const mymap = L.map('mapid');
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(mymap);
const coords = document.querySelectorAll('.contact__item');
const bounds = [];
const mapMarker = L.icon({
iconUrl: '/static/img/map_marker.svg',
iconSize: [41, 55],
iconAnchor: [20, 54],
});
coords.forEach((item) => {
const lat = item.querySelector('.locationLat');
const lon = item.querySelector('.locationLon');
if (lat && lon) {
bounds.push([+lat.innerHTML, +lon.innerHTML]);
L.marker([+lat.innerHTML, +lon.innerHTML], { icon: mapMarker })
.addTo(mymap)
.on('click', () => {
mymap.setView([+lat.innerHTML, +lon.innerHTML], 16);
});
}
});
mymap.fitBounds(bounds, { padding: [50, 50] });
<file_sep>module.exports = (sequelize, Sequelize) => {
const Review = sequelize.define('review', {
fullName: {
type: Sequelize.TEXT('tiny'),
},
text: {
type: Sequelize.TEXT,
},
image: {
type: Sequelize.TEXT('tiny'),
},
});
return Review;
};
<file_sep>import axios from 'axios';
import { ICarParts } from '../models/carParts';
import { ICarPartsOffices } from '../models/carPartsOffices';
const url = '/api/admin/carpartsoffices';
const CarPartsOfficesService = {
addCarPartsOffices: (data: ICarPartsOffices) => axios.post<ICarParts>(url, data),
updateCarPartsOffices: ({ id, ...rest }: ICarPartsOffices) => axios.put<ICarPartsOffices>(`${url}/${id}`, rest),
deleteCarPartsOffices: (id: number) => axios.delete(`${url}/${id}`)
};
export default CarPartsOfficesService;
<file_sep>module.exports = (sequelize, Sequelize) => {
const CarPart = sequelize.define('carPart', {
title: {
type: Sequelize.TEXT('tiny'),
},
subtitle: {
type: Sequelize.TEXT,
},
});
return CarPart;
};
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import CorporateClientsService from '../services/CorporateClientsService';
import { ICorporatesClientImages } from './corporateClientsImages';
interface IState {
data: ICorporateClientsFromServer | null;
}
const initialState: IState = {
data: null
};
export interface ICorporateClients {
id?: number;
title: string;
description: string;
info: string;
}
export interface ICorporateClientsFromServer extends ICorporateClients {
images: ICorporatesClientImages[];
}
export const corporateClients = createModel<IRootModel>()({
state: initialState,
reducers: {
setCorporateClients(state, data: ICorporateClientsFromServer): IState {
return { ...state, data };
}
},
effects: d => {
return {
async getCorporateClients() {
const { data } = await CorporateClientsService.getCorporateClients();
if (data) {
d.corporateClients.setCorporateClients(data);
}
},
async addCorporateClients(model: ICorporateClients) {
const { data } = await CorporateClientsService.addCorporateClients(model);
if (data) {
d.corporateClients.getCorporateClients();
}
},
async updateCorporateClients(model: ICorporateClients) {
const { data } = await CorporateClientsService.updateCorporateClients(model);
if (data) {
d.corporateClients.getCorporateClients();
}
}
};
}
});
<file_sep>import { Models } from '@rematch/core';
import { auth } from './auth';
import { carParts } from './carParts';
import { offices } from './offices';
import { carPartsOffices } from './carPartsOffices';
import { promos } from './promos';
import { reviews } from './reviews';
import { mainPage } from './mainPage';
import { services } from './services';
import { corporateClientsImages } from './corporateClientsImages';
import { corporateClients } from './corporateClients';
import { uploads } from './uploads';
export interface IRootModel extends Models<IRootModel> {
auth: typeof auth;
carParts: typeof carParts;
offices: typeof offices;
carPartsOffices: typeof carPartsOffices;
promos: typeof promos;
reviews: typeof reviews;
mainPage: typeof mainPage;
services: typeof services;
corporateClients: typeof corporateClients;
corporateClientsImages: typeof corporateClientsImages;
uploads: typeof uploads;
}
const rootModel: IRootModel = {
auth,
carParts,
offices,
carPartsOffices,
promos,
reviews,
mainPage,
services,
corporateClients,
corporateClientsImages,
uploads
};
export default rootModel;
<file_sep>module.exports = (sequelize, Sequelize) => {
const MainPage = sequelize.define('mainPage', {
title: {
type: Sequelize.TEXT('tiny'),
},
subtitle: {
type: Sequelize.TEXT,
},
serviceDescription: {
type: Sequelize.TEXT,
},
});
return MainPage;
};
<file_sep>import { init, RematchDispatch, RematchRootState } from '@rematch/core';
import { createBrowserHistory } from 'history';
import createLoadingPlugin from '@rematch/loading';
import { connectRouter, routerMiddleware } from 'connected-react-router';
import models, { IRootModel } from '../models';
export const history = createBrowserHistory();
const loadingPlugin = createLoadingPlugin<IRootModel>({ asNumber: false });
const router = connectRouter(history);
export const store = init({
plugins: [loadingPlugin],
models,
redux: {
rootReducers: {
resetStore: () => undefined
},
middlewares: [routerMiddleware(history)],
reducers: {
router
}
}
});
interface ILoadingPlugin {
loading: {
global: boolean;
models: RematchRootState<IRootModel>;
effects: Dispatch;
};
}
interface IConnectedRouter {
router: {
location: {
pathname: string;
search: string;
hash: string;
key: string;
query: { [key: string]: string };
};
};
}
export type Store = typeof store;
export type Dispatch = RematchDispatch<IRootModel>;
export type IRootState = RematchRootState<IRootModel> & ILoadingPlugin & IConnectedRouter;
export const dispatchResetStore = () => store.dispatch({ type: 'resetStore' });
<file_sep># CarServiceMaster
Site for car service "Master", Petrozavodsk
Перед разворачиванием проекта поднять базу данных и указать креды для в файле `models/index.js` в месте, где инициализируется Sequelize.
Перед разработкой нужно запустить сервер базы данных (у меня - в консоли командой `mysqld`)
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const MainPage = db.mainPage;
const mainPageController = require('../../controllers/mainPage.controller');
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
mainPageController
.getMainPage()
.then((mainPage) => {
if (!mainPage) {
return res.status(200).json(null);
}
res.json(mainPage);
})
.catch((err) => res.status(404).json(err));
});
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
MainPage.findOne()
.then((mainPage) => {
if (!mainPage) {
return MainPage.create({
title: req.body.title,
subtitle: req.body.subtitle,
serviceDescription: req.body.serviceDescription,
}).then((mainPage) => mainPage);
}
throw new Error('Whoops!');
})
.then((mainPage) => res.status(201).json(mainPage))
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
MainPage.update(
{
title: req.body.title,
subtitle: req.body.subtitle,
serviceDescription: req.body.serviceDescription,
},
{ where: { id: req.params.id } }
)
.then((mainPage) => {
return res.status(200).json(mainPage);
})
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>module.exports = (sequelize, Sequelize) => {
const User = sequelize.define('user', {
login: {
type: Sequelize.TEXT('tiny'),
allowNull: false,
},
password: {
type: Sequelize.TEXT('tiny'),
allowNull: false,
},
});
return User;
};
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import CarPartsOfficesService from '../services/CarPartsOfficesService';
interface IState {
data: ICarPartsOffices | null;
}
const initialState: IState = {
data: null
};
export interface ICarPartsOffices {
id: number;
description: string;
image: string;
carPartId: number;
officeId: number;
}
export const carPartsOffices = createModel<IRootModel>()({
state: initialState,
reducers: {},
effects: d => {
return {
async addCarPartsOffices(model: ICarPartsOffices) {
const { data } = await CarPartsOfficesService.addCarPartsOffices(model);
if (data) {
d.carParts.getCarParts();
}
},
async updateCarPartsOffices(model: ICarPartsOffices) {
const { data } = await CarPartsOfficesService.updateCarPartsOffices(model);
if (data) {
d.carParts.getCarParts();
}
},
async deleteCarPartsOffices(id: number) {
const { data } = await CarPartsOfficesService.deleteCarPartsOffices(id);
if (data) {
d.carParts.getCarParts();
}
}
};
}
});
<file_sep>const db = require('../models/index');
const Services = db.services;
const Offices = db.offices;
exports.getServices = () => {
return Services.findAll({ include: Offices });
};
exports.getService = (id) => {
return Services.findOne({ where: { id }, include: [Offices] });
};
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const CarPartsOffices = db.carPartOffice;
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
CarPartsOffices.findOne({
where: {
carPartId: req.body.carPartId,
officeId: req.body.officeId,
},
})
.then((item) => {
if (!item) {
return CarPartsOffices.create({
carPartId: req.body.carPartId,
officeId: req.body.officeId,
description: req.body.description,
image: req.body.image,
}).then((carPart) => carPart);
}
throw new Error('Whoops!');
})
.then((carPart) => {
return res.status(201).json(carPart);
})
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
CarPartsOffices.update(
{
description: req.body.description,
image: req.body.image,
},
{ where: { id: req.params.id } }
)
.then((carPart) => res.status(200).json(carPart))
.catch((err) => res.status(400).json(err));
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
CarPartsOffices.destroy({
where: { id: req.params.id },
})
.then((carPartsOffices) => res.status(200).json(carPartsOffices))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const CarParts = db.carParts;
const Offices = db.offices;
const carPartsController = require('../../controllers/carParts.controller');
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
carPartsController
.getCarParts()
.then((carParts) => {
if (!carParts) {
return res.status(200).json(null);
}
res.json(carParts);
})
.catch((err) => res.status(404).json(err));
});
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
CarParts.findOne()
.then((carParts) => {
if (!carParts) {
return CarParts.create({
title: req.body.title,
subtitle: req.body.subtitle,
}).then((carPart) => carPart);
}
throw new Error('Whoops!');
})
.then((carPart) => res.status(201).json(carPart))
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
CarParts.update(
{
title: req.body.title,
subtitle: req.body.subtitle,
},
{ where: { id: req.params.id }, returning: true, plain: true }
)
.then(() => {
return CarParts.findOne().then((carPart) => carPart);
})
.then((carPart) => res.status(201).json(carPart))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import CarPartsService from '../services/CarPartsService';
import { IOficesCarparts } from './offices';
interface IState {
data: ICarParts | null;
}
const initialState: IState = {
data: null
};
export interface ICarParts {
id: number;
title: string;
subtitle: string;
offices: IOficesCarparts[];
}
export const carParts = createModel<IRootModel>()({
state: initialState,
reducers: {
setCarParts(state, data: ICarParts): IState {
const offices = state.data ? state.data.offices : [];
const carParts = { ...data, offices: data.offices ? data.offices : offices };
return { ...state, data: carParts };
}
},
effects: d => {
return {
async getCarParts() {
const { data } = await CarPartsService.getCarParts();
if (data) {
d.carParts.setCarParts(data);
}
},
async addCarParts(model: ICarParts) {
const { data } = await CarPartsService.addCarParts(model);
if (data) {
d.carParts.setCarParts(data);
}
},
async updateCarParts(model: ICarParts) {
const { data } = await CarPartsService.updateCarParts(model);
if (data) {
d.carParts.setCarParts(data);
}
}
};
}
});
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import CorporateClientsImagesService from '../services/CorporateClientsImagesService';
interface IState {
data: ICorporateClientImage | null;
}
const initialState: IState = {
data: null
};
export interface ICorporatesClientImages {
filename: string;
extension: string;
url: string;
corporateClientImage: ICorporateClientImage;
}
export interface ICorporateClientImage {
id?: number;
corporateClientId: number;
imageId: number;
}
export const corporateClientsImages = createModel<IRootModel>()({
state: initialState,
reducers: {},
effects: d => {
return {
async addCorporateClientsImages(model: ICorporateClientImage) {
const { data } = await CorporateClientsImagesService.addCorporateClientsImages(model);
if (data) {
d.corporateClients.getCorporateClients();
}
},
async deleteCorporateClientsImages(imageId: number) {
const { status } = await d.uploads.deleteImage(imageId);
if (status === 200) {
d.corporateClients.getCorporateClients();
}
}
};
}
});
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const db = require('../../models/index');
const Images = db.images;
const storage = multer.diskStorage({
destination: './static/uploads',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
},
});
const upload = multer({
storage: storage,
limits: {
fileSize: 5000000,
},
fileFilter: (req, file, cb) => {
const fileTypes = /jpeg|jpg|png|svg/;
const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = fileTypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
}
return cb('Images only!');
},
}).single('avatar');
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
upload(req, res, (err) => {
if (err) {
res.status(400).json(err);
} else {
Images.create({
filename: req.file.filename,
extension: path.extname(req.file.originalname).toLowerCase(),
url: `/static/uploads/${req.file.filename}`,
})
.then((image) => res.status(201).json(image))
.catch((err) => res.status(400).json(err));
}
});
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
let filePath = '';
Images.findOne({
where: {
id: req.params.id,
},
})
.then((image) => {
filePath = path.resolve(`./static/uploads/${image.filename}`);
return Images.destroy({
where: { id: req.params.id },
})
.then((item) => {
console.error(filePath);
try {
fs.unlinkSync(filePath);
} catch (err) {
console.error(err);
}
res.status(200).json(item);
})
.catch((err) => res.status(400).json(err));
})
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const ServiceOffice = db.serviceOffice;
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
ServiceOffice.findOne({
where: {
serviceId: req.body.serviceId,
officeId: req.body.officeId,
},
})
.then((item) => {
if (!item) {
return ServiceOffice.create({
serviceId: req.body.serviceId,
officeId: req.body.officeId,
isAvailable: !!req.body.isAvailable,
}).then((serviceOffice) => serviceOffice);
}
throw new Error('Whoops!');
})
.then((serviceOffice) => {
return res.status(201).json(serviceOffice);
})
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
ServiceOffice.update(
{
serviceId: req.body.serviceId,
officeId: req.body.officeId,
isAvailable: !!req.body.isAvailable,
},
{ where: { id: req.params.id }, returning: true, plain: true }
)
.then(() => {
return ServiceOffice.findOne({
where: { id: req.params.id },
}).then((serviceOffice) => serviceOffice);
})
.then((serviceOffice) => {
return res.status(200).json(serviceOffice);
})
.catch((err) => res.status(400).json(err));
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
ServiceOffice.destroy({
where: { id: req.params.id },
})
.then((serviceOffice) => res.status(200).json(serviceOffice))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>import { createModel } from '@rematch/core';
import { IRootModel } from '.';
import MainPageService from '../services/MainPageService';
interface IState {
data: IMainPage | null;
}
const initialState: IState = {
data: null
};
export interface IMainPage {
id: number;
title: string;
subtitle: string;
serviceDescription: string;
}
export const mainPage = createModel<IRootModel>()({
state: initialState,
reducers: {
setMainPage(state, data: IMainPage): IState {
return { ...state, data };
}
},
effects: d => {
return {
async getMainPage() {
const { data } = await MainPageService.getMainPage();
if (data) {
d.mainPage.setMainPage(data);
}
},
async addMainPage(model: IMainPage) {
const { data } = await MainPageService.addMainPage(model);
if (data) {
d.mainPage.getMainPage();
}
},
async updateMainPage(model: IMainPage) {
const { data } = await MainPageService.updateMainPage(model);
if (data) {
d.mainPage.getMainPage();
}
}
};
}
});
<file_sep>const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../../models/index');
const Images = db.images;
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
Images.findAll()
.then((images) => {
if (images && !images.length) {
return res.status(200).json([]);
}
res.json(images);
})
.catch((err) => res.status(404).json(err));
});
router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
Images.create({
title: req.body.title,
description: req.body.description,
url: req.body.url,
})
.then((image) => res.status(201).json(image))
.catch((err) => res.status(400).json(err));
});
router.put('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
Images.update(
{
title: req.body.title,
description: req.body.description,
url: req.body.url,
},
{ where: { id: req.params.id } }
)
.then((image) => res.status(200).json(image))
.catch((err) => res.status(400).json(err));
});
router.delete('/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
Images.destroy({
where: { id: req.params.id },
})
.then((image) => res.status(200).json(image))
.catch((err) => res.status(400).json(err));
});
module.exports = router;
<file_sep>import axios from 'axios';
import { IMainPage } from '../models/mainPage';
const url = '/api/admin/mainpage';
const MainPageService = {
getMainPage: () => axios.get<IMainPage>(url),
addMainPage: ({ id, ...rest }: IMainPage) => axios.post<IMainPage>(url, rest),
updateMainPage: ({ id, ...rest }: IMainPage) => axios.put<IMainPage>(`${url}/${id}`, rest)
};
export default MainPageService;
<file_sep>module.exports = (sequelize, Sequelize) => {
const Service = sequelize.define('service', {
title: {
type: Sequelize.TEXT('tiny'),
},
cost: {
type: Sequelize.TEXT('tiny'),
},
description: {
type: Sequelize.TEXT,
},
text: {
type: Sequelize.TEXT,
},
image: {
type: Sequelize.TEXT('tiny'),
},
icon: {
type: Sequelize.TEXT('tiny'),
},
});
return Service;
};
| 6494eb79b94520cf7056d833da7c00f7f564b0bd | [
"JavaScript",
"TypeScript",
"Markdown"
]
| 57 | JavaScript | ilyalezhnev/CarServiceMaster | c69ace362663f19ef0adc502f54ad9ac463ee65e | f9e92b9b16ac00623e62098a2fc554055d78c496 |
refs/heads/master | <file_sep># $ python2 collectMeasures.py > outfile.txt
import mmap
import os
import sys
cwd = os.getcwd()
count = 1
collector = []
toSearch = "Measurement result summary"
for subdir, dirs, files in os.walk(cwd):
for file in files:
if file.endswith(".log"):
with open(file, 'rU') as fid:
for index, line in enumerate(fid, start=1):
if toSearch in line:
print "\t", count
for i in range(10):
sys.stdout.write(next(fid))
count = count + 1<file_sep>import mmap
import os
# measureFiles = []
wrongFiles = []
count = 0
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd):
for file in files:
if file.endswith(".log"):
file = os.path.join(subdir, file)
# measureFiles.append(file)
with open(file) as fid:
string = mmap.mmap(fid.fileno(), 0, access=mmap.ACCESS_READ)
if string.find('pHL_Sv_case1') != -1:
count = count + 1
else:
wrongFiles.append(file)
wfilesString = str(wrongFiles)
textFile = open("Output.txt", "w")
textFile.write("Numero de arquivos corretos: %s \n" % count)
textFile.write("Arquivos com erro: \n")
for path in wfilesString.split(","):
textFile.write(path)
textFile.write("\n")
textFile.close() | 446a4df90aa5f8316b05527ae083d4477c60f26b | [
"Python"
]
| 2 | Python | finkenauer/circuit-reliability | 5e8394714c6d9e564958d835a67e524fa6c82141 | f70d8311239a64994463735d8da4f6d346d624ac |
refs/heads/main | <file_sep># Rename .env.example to .env once you have your API keys
SHOPIFY_API_KEY="YOUR_API_KEY_GOES_HERE"
SHOPIFY_API_SECRET_KEY="YOUR_API_SECRET_GOES_HERE"<file_sep># automate-envelopes
Automate envelope making!
<file_sep>import styles from './app.module.scss';
import Button from '@material-ui/core/Button';
export default function Home() {
return (
<div>
<h1 className={styles.Test}>Hello world</h1>
<Button variant="contained">Hello World</Button>
</div>
)
}
| 0b8dbaf1dafd9989d59c39c1aa88578a13bc56e7 | [
"Markdown",
"JavaScript",
"Shell"
]
| 3 | Shell | leroywan/automate-envelopes | a3ad91865f94f565cbf3fbf97181e49ad053ffbb | fc2348428cbdd5972f1d6c9662728feeee9c4c47 |
refs/heads/master | <repo_name>Tushige/Glasses<file_sep>/src/containers/NavigationBar/NavigationBar.js
/*******************************************************************************
* @file NavigationBar.js
* Contains the component that describes the 'navigation bar' at the top of the
* page
*******************************************************************************/
import React, { Component } from 'react';
import {Nav,
Navbar,
NavItem,
} from 'react-bootstrap';
import {Link } from 'react-router-dom';
import {LinkContainer} from 'react-router-bootstrap';
import './NavigationBar.css';
class NavigationBar extends Component {
render() {
const signupBtn = (
<LinkContainer to="/signup" className="navitem">
<NavItem>
Sign Up
</NavItem>
</LinkContainer>
);
const signinBtn = (
<LinkContainer to="/signin" className="navitem">
<NavItem>
Sign In
</NavItem>
</LinkContainer>
);
const nav = (
<Nav pullRight>
{signupBtn}
{signinBtn}
</Nav>
);
const brand = (
<Link id="brand-title" to="/">
GLASSES
</Link>
);
return (
<Navbar fluid collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
{brand}
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
{nav}
</Navbar.Collapse>
</Navbar>
);
}
}
export default NavigationBar;
<file_sep>/src/App.js
/*******************************************************************************
* @file App.js
*
* This file contains the root component of the application
*******************************************************************************/
import React, { Component } from 'react';
import NavigationBar from './containers/NavigationBar/NavigationBar';
import './App.css';
import Routes from './Routes';
import {getUserToken} from './libs/user';
import Sidebar from './containers/sidebar/Sidebar';
class App extends Component {
constructor(props) {
super(props);
this.updateUserToken = this.updateUserToken.bind(this);
/**
* @prop isLoadingUserToken {Bool}
* true: page is retrieving user token, don't render content
* false: page is ready, render content
* @prop userToken {String}
* token Id for the currently signed in user
*/
this.state = {
isLoadingUserToken: true,
userToken: null,
};
}
/**
* updates the token associated with the signed in user
* this method is passed to children to let them modify userToken
*/
updateUserToken(token) {
this.setState({
userToken: token
});
}
/**
* On page load, check if there is a signed in user
* If there is: save user token in state
*/
componentWillMount() {
const getUserTokenPromise = getUserToken();
getUserTokenPromise.then((userToken) => {
if (userToken) { // user present
this.setState({
isLoadingUserToken:false,
userToken:userToken,
});
}
else { // no user
this.setState({
isLoadingUserToken:false,
userToken:null,
});
}
})
.catch((err) => {
alert(err);
});
}
render() {
/* display loading bar while page checks for signed in user*/
if (this.state.isLoadingUserToken) {
return (
<i id="page-loading-bar" className="fa fa-refresh fa-spin fa-3x fa-fw" aria-hidden="true"></i>
)
}
let isSignedin = this.state.userToken ? true : false;
let navigation = null;
const topBar = (
<NavigationBar
isSignedin={isSignedin}
updateToken={this.updateUserToken}>
</NavigationBar>
);
const sideBar = (
<Sidebar
updateUserToken={this.updateUserToken}>
</Sidebar>
);
/**
* @var navigation - picks a navigation based on user type
* 1. sidebar - signed in user
* 2. top navbar - anonymous user
*/
navigation = isSignedin ? sideBar : topBar;
const childProps = {
isSignedin: isSignedin,
userToken: this.state.userToken,
updateUserToken: this.updateUserToken,
};
/**
* @var appContainer - Main content
*/
const appContainer = (
<div>
{navigation}
<Routes childProps={childProps}/>
</div>
);
return (
<div className="App">
{appContainer}
</div>
);
}
}
export default App;
<file_sep>/src/views/Readings/Reading.js
/*
* React element that describes what a single reading entry looks like
*/
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import {getReading,
updateReading,
deleteReading
} from '../../libs/serverAPI';
import {configureS3} from '../../libs/aws_s3';
import AWS from 'aws-sdk';
import {Grid,
Row,
Col,
Button
} from 'react-bootstrap';
import './reading.css';
import ReadingForm from '../NewReading/ReadingForm';
/*
* A single row describing a reading field
* Expects two props:
* 1. title - title of the field
* 2. val - value of the field
*/
function ReadingRow(props) {
return (
<Row>
<Col sm={2}>
<h1 className="row-title">{props.title}:</h1>
</Col>
<Col sm={10}>
<h1 className="row-elm">{props.val}</h1>
</Col>
</Row>
)
}
/*
* Component describing a reading entry
* Expects the following props:
* 1.
*/
class Reading extends Component {
constructor(props) {
super(props);
this.titleOnChangeHandler = this.titleOnChangeHandler.bind(this);
this.linkOnChangeHandler = this.linkOnChangeHandler.bind(this);
this.fileAttachmentHandler = this.fileAttachmentHandler.bind(this);
this.memoOnChangeHandler = this.memoOnChangeHandler.bind(this);
this.editBtnHandler = this.editBtnHandler.bind(this);
this.deleteBtnHandler = this.deleteBtnHandler.bind(this);
this.submitHandler = this.submitHandler.bind(this);
this.state = {
reading: null,
isEditing: false,
isLoading: false,
}
}
/*
* get the reading object from the back end
*/
componentWillMount() {
// get the reading object from the back end
const readingId = this.props.match.params.id;
const userToken = this.props.childProps.userToken;
let getPromise = getReading(userToken, readingId);
getPromise.then((readingData) => {
this.setState({
reading: readingData,
});
})
.catch((err) => {
console.log(err);
})
}
/*
* On edit request, we show the editing form
*/
editBtnHandler(event) {
this.setState({
isEditing: true,
})
}
async submitHandler(event) {
event.preventDefault();
this.setState({
isLoading: true,
})
var filePath = null;
if (this.state.reading.attachment) {
filePath = await this.uploadFile();
}
// update the reading object
const readingId = this.props.match.params.id;
const userToken = this.props.childProps.userToken;
const updatedReading = {
title: this.state.reading.title,
link: this.state.reading.link,
memo: this.state.reading.memo,
attachment: filePath,
};
let dataPromise = updateReading(updatedReading, userToken, readingId);
dataPromise.then((jsonData) => {
this.setState({
isLoading: false,
isEditing: false,
})
const redirectUrl = '/reading/' + readingId;
this.props.history.push(redirectUrl);
})
.catch((err) => {
alert(err);
});
}
async uploadFile() {
let s3 = await configureS3(this.props.childProps.userToken);
return new Promise((resolve, reject) => {
const file = this.state.reading.attachment;
const filePath = `${AWS.config.credentials.identityId}-${Date.now()}-${file.name}`;
const params = {
Key: filePath,
ACL: 'public-read',
Body: file,
ContentType: file.type,
ContentLength: file.size,
};
let s3promise = s3.upload(params).promise();
s3promise.then((data) => {
resolve(data.Location);
})
.catch((err) => {
reject(err);
});
});
}
deleteBtnHandler(event) {
this.setState({
isLoading: true,
})
const userToken = this.props.childProps.userToken;
const readingId = this.props.match.params.id;
let dataPromise = deleteReading(userToken, readingId);
dataPromise.then((jsonData) => {
this.setState({
isLoading: false,
});
this.props.history.push('/readings');
})
.catch((err) => {
alert(err);
})
}
/*
* handlers for updating UI input elements
*/
// update title as user types
titleOnChangeHandler(event) {
let updatedReading = this.state.reading;
updatedReading.title = event.target.value;
this.setState({
reading: updatedReading,
});
}
// update link as user types
linkOnChangeHandler(event){
let updatedReading = this.state.reading;
updatedReading.link = event.target.value;
this.setState({
reading: updatedReading,
});
}
memoOnChangeHandler(event) {
let updatedReading = this.state.reading;
updatedReading.memo = event.target.value;
this.setState({
reading: updatedReading,
});
}
// attach a file
fileAttachmentHandler(event) {
let updatedReading = this.state.reading;
updatedReading.attachment = event.target.files[0];
this.setState({
reading: updatedReading,
});
}
render() {
let view = null;
const reading = this.state.reading? this.state.reading : null;
// getting reading object is async process: wait rendering until it's done
if (!reading) {
return (
<i id="page-loading-bar" className="fa fa-refresh fa-spin fa-3x fa-fw" aria-hidden="true"></i>
)
}
// show reading object in reading format if not Editing
if (!this.state.isEditing) {
const editBtn = (
<Button bsStyle="primary"
block
bsSize="large"
onClick={this.editBtnHandler}>
Edit
</Button>
);
const deleteBtn = (
<Button bsStyle="danger"
block
bsSize="large"
onClick={this.deleteBtnHandler}>
{this.state.isLoading && <i className="fa fa-circle-o-notch fa-spin fa-fw"></i>}
Delete
</Button>
);
const readingComponent = (
<div id="reading-container">
<Grid>
<ReadingRow title="Title" val={reading.title} />
<ReadingRow title="Link" val={<a href={reading.link}>{reading.link}</a>} />
<ReadingRow title="Memo" val={reading.memo} />
<ReadingRow title="Attachment" val={reading.attachment} />
{editBtn}
{deleteBtn}
</Grid>
</div>
)
view = readingComponent;
}
// show edit form if user wants to edit reading entry
else {
let isLoading = this.state.isLoading;
const titleProps = {
textLabel: "Save as",
inputType: "text",
inputValue: this.state.reading.title,
placeholder: "e.g. title of the page",
inputHandler: this.titleOnChangeHandler,
};
const linkProps = {
textLabel: "Link",
inputType: "url",
inputValue: this.state.reading.link,
placeholder: "e.g. www.example.com",
inputHandler: this.linkOnChangeHandler,
}
const fileProps = {
inputHandler: this.fileAttachmentHandler,
}
const memoProps = {
textLabel: null,
inputType: "textarea",
inputValue: this.state.reading.memo,
placeholder: "Say something about it",
inputHandler: this.memoOnChangeHandler,
}
const editComponent = (
<div id="readingForm-container">
<ReadingForm
submitHandler={this.submitHandler}
titleProps={titleProps}
linkProps={linkProps}
fileProps={fileProps}
memoProps={memoProps}
isLoading={isLoading}/>
</div>
)
view = editComponent;
}
return (
<div>
{view}
</div>
)
}
}
export default withRouter(Reading);
<file_sep>/README.md
A web application to help you keep your reading lists in one place.
<file_sep>/src/views/Signin/Signin.js
/*******************************************************************************
* @file Signin.js
*
* Contains the component and logic of user signin
*******************************************************************************/
import React, {Component,
} from 'react';
import SigninForm from './SigninForm';
/*
* withRouter gives us history info in our Signin component's props
*/
import {withRouter,
} from 'react-router-dom';
import {authenticateUser,
} from '../../libs/user';
class Signin extends Component {
constructor(props) {
super(props);
/* input handlers */
this.handleUsername = this.handleUsername.bind(this);
this.handlePassword = this.handlePassword.bind(this);
this.signinHandler = this.signinHandler.bind(this);
/* input validators*/
this.validateUsername = this.validateUsername.bind(this);
this.validatePassword = this.validatePassword.bind(this);
this.validateForm = this.validateForm.bind(this);
this.state = {
username: '',
password: '',
isLoading: false,
errorMsg: '',
};
}
/**
* check if username is valid
*/
validateUsername() {
const len = this.state.username.length;
if (len>8) return "success";
else if(len>3) return "warning";
else if(len>0) return "error";
}
/*
* check if password is valid
*/
validatePassword() {
const len = this.state.password.length;
if (len>8) return "success";
else if(len>0) return "error";
}
/*
* Signin only allowed on valid username and password
*/
validateForm() {
if (this.validateUsername()==="success" && this.validatePassword()==="success") {
return 'success';
}
return 'error';
}
/*
* updates username as user types
*/
handleUsername(event) {
this.setState({username: event.target.value});
}
/*
* updates password as user types
*/
handlePassword(event) {
this.setState({password: event.target.value});
}
/*
* attempts to sign in user
* if successful, stores the user token
* if not, shows error to the user
*/
signinHandler(event) {
event.preventDefault();
this.setState({
isLoading:true,
});
/* show error message*/
if (this.validateForm() !== 'success') {
this.setState({
isLoading: false,
errorMsg: "password must be at least 8 characters long."
});
return;
}
/* if inputs are valid, validate against AWS*/
try {
var signinPromise = authenticateUser(undefined, this.state.username, this.state.password);
// signin success!
signinPromise.then((userToken) => {
this.props.childProps.updateUserToken(userToken);
// redirect to homepage
this.props.history.push('/')
})
// sign in failure! --> show helpful error message
.catch((err) => {
this.setState({
isLoading: false,
errorMsg:err.message,
});
});
}
catch(err) {
this.setState({
isLoading: false,
errorMsg:err.message,
});
}
}
render() {
let isLoading = this.state.isLoading;
const emailProps = {
inputHandler: this.handleUsername,
inputValue: this.state.username,
validationState: this.validateUsername,
};
const passProps = {
inputHandler: this.handlePassword,
inputValue: this.state.password,
validationState: this.validatePassword,
errorMsg: this.state.errorMsg,
};
const submitProps = {
validationState: this.validateForm,
};
const form = (
<SigninForm
isLoading={isLoading}
emailProps={emailProps}
passProps={passProps}
submitProps={submitProps}
submitHandler={this.signinHandler}
/>
);
return (
<div>
{form}
</div>
)
}
}
export default withRouter(Signin);
<file_sep>/src/views/Home/Homepage.js
/*******************************************************************************\
* @file Homepage.js
*
* Contains the component that describes the app homepage for anonymous users
*******************************************************************************/
import React, { Component } from 'react';
import './Homepage.css';
import {Link} from 'react-router-dom';
import {Button,
} from 'react-bootstrap';
function SignupBtn(props) {
return (
<Button id="homepage-signup-btn"
type="submit"
bsStyle="success">
<Link to='/signup'>SIGN UP FOR FREE</Link>
</Button>
)
}
class Homepage extends Component {
render() {
/**
* @var auth_user - content shown to signed in user
*/
const auth_user = null;
/**
* @var anon_user - content shown to anonymous user
*/
const anon_user = (
<div id="intro">
<h1 id=""> Keep your reading list in one place.</h1>
<p>Tired of forgetting where you bookmarked a good read?
Glasses lets you save all of your readings in one place,
and access them on any device.</p>
<SignupBtn/>
</div>
);
const content = this.props.childProps.userToken ? auth_user : anon_user;
return (
<div id="homepage-container">
<div id="homepage-content">
{content}
</div>
<footer>
<span>Made with<i className="fa fa-heart" aria-hidden="true"> </i>
by <NAME>
</span>
</footer>
</div>
)
}
}
export default Homepage;
<file_sep>/src/libs/serverAPI.js
/*
* CRUD functions that interface with the Glasses API
*/
import config from '../config.js';
/*
* Writes to DB
* returns a promise, where resolve value is the created reading object
*/
function createReading(reading, userToken) {
const endpoint = '/readings';
const url = config.APIGateway.URL+endpoint;
reading = JSON.stringify(reading);
let myInit = {
method: 'POST',
headers: {
"Authorization": userToken,
},
body: reading,
};
let createPromise = fetch(url, myInit);
return createPromise.then((response) => {
if (response.status === 200) {
return response.json();
} else {
return Promise.reject(new Error("reading list creation failed"));
}
})
// fetch fails
.catch((err) => {
return Promise.reject(err);
});
}
/*
* retrieves all readings for the user
* returns a promise, where resolve value is the reading object
*/
function getAllReadings(userToken) {
const endpoint = '/readings';
const url = config.APIGateway.URL+endpoint;
let myInit = {
method: 'GET',
headers: {
"Authorization": userToken,
},
};
let getAllPromise = fetch(url, myInit);
return getAllPromise.then((response) => {
if (response.status === 200) {
// returns a promise
return response.json();
} else {
return Promise.reject(new Error("reading list retrieval failed"));
}
})
.catch((err) => {
return Promise.reject(err);
});
}
/*
* retrieves a reading for the user
* returns a promise, where resolve value is the reading object
*/
function getReading(userToken, readingId) {
const endpoint = '/reading/'+readingId;
const url = config.APIGateway.URL+endpoint;
let myInit = {
method: 'GET',
headers: {
"Authorization": userToken,
},
};
let getPromise = fetch(url, myInit);
return getPromise.then((response) => {
if (response.status === 200) {
// returns a promise
return response.json();
} else {
return Promise.reject(new Error("reading retrieval failed"));
}
})
.catch((err) => {
return Promise.reject(err);
});
}
/*
* retrieves a reading for the user
* returns a promise, where resolve value is the reading object
*/
function updateReading(body, userToken, readingId) {
const endpoint = '/readings/'+readingId;
let updatedReading = JSON.stringify(body);
const url = config.APIGateway.URL+endpoint;
let myInit = {
method: 'PUT',
headers: {
"Authorization": userToken,
},
body:updatedReading,
};
let putPromise = fetch(url, myInit);
return putPromise.then((response) => {
if (response.status === 200) {
// returns a promise
return response.json();
} else {
return Promise.reject(new Error("update failed"));
}
})
.catch((err) => {
return Promise.reject(err);
});
}
/*
* retrieves a reading for the user
* returns a promise, where resolve value is the reading object
*/
function deleteReading(userToken, readingId) {
const endpoint = '/readings/'+readingId;
const url = config.APIGateway.URL+endpoint;
let myInit = {
method: 'DELETE',
headers: {
"Authorization": userToken,
},
};
let deletePromise = fetch(url, myInit);
return deletePromise.then((response) => {
if (response.status === 200) {
// returns a promise
return response.json();
} else {
return Promise.reject(new Error("delete failed"));
}
})
.catch((err) => {
return Promise.reject(err);
});
}
export {createReading,
getReading,
updateReading,
deleteReading,
getAllReadings};
<file_sep>/src/views/Signup/VerificationForm.js
import React, {Component} from 'react';
import {
Form,
FormGroup,
Button,
} from 'react-bootstrap';
import InputField from '../../containers/FormComponents/InputField';
class VerificationForm extends Component {
render() {
let isLoading = this.props.isLoading;
const field = (
<InputField
type="text"
icon={<i className="fa fa-handshake-o" aria-hidden="true"></i>}
value={this.props.childProps.inputValue}
placeholder="Verification Code"
onChange={this.props.childProps.inputHandler}
errorMsg={this.props.childProps.errorMsg}>
</InputField>
);
const submitBtn = (
<FormGroup>
<Button
type="submit"
bsStyle="primary"
block
disabled={isLoading}>
{isLoading && <i className="fa fa-cogs fa-spin" aria-hidden="true"></i>}
{isLoading ? 'Verifying...':'Verify'}
</Button>
</FormGroup>
);
return (
<Form horizontal onSubmit={this.props.submitHandler}>
{field}
{submitBtn}
</Form>
);
}
}
export default VerificationForm;
<file_sep>/src/containers/FormComponents/InputField.js
/*******************************************************************************
* @file InputField.js
* A form field used by user registration Forms
* Forms : Signup, Signin, Verification
******************************************************************************/
import React from 'react';
import {
FormControl,
FormGroup,
HelpBlock,
} from 'react-bootstrap';
import './InputField.css';
export default function InputField(props) {
let err = null;
if (props.errorMsg) {
err = <HelpBlock className="error-msg">{props.errorMsg}</HelpBlock>;
}
return (
<div className="inputField-container">
<FormGroup
validationState={props.validationState()}>
<div className="input-group margin-bottom-sm">
<span className="input-group-addon">
{props.icon}
</span>
<FormControl className="input-field"
type={props.type}
value={props.value}
placeholder={props.placeholder}
onChange={props.onChange}>
</FormControl>
</div>
{err}
</FormGroup>
</div>
)
}
<file_sep>/src/views/Readings/ReadingItem.js
/*
* React element that describes a single reading entry in a reading list
*/
import React from 'react';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
import {Row,
} from 'react-bootstrap';
import {Link,
} from 'react-router-dom';
import './ReadingItem.css';
export default function(props) {
const readingUrl = '/reading/'+props.item.readingId;
return (
<div>
<Row className="title-container">
<CSSTransitionGroup
transitionName="readingItem-animation"
transitionAppear={true}
transitionAppearTimeout={500}
transitionEnter={false}
transitionLeave={false}>
<h1 className="title">
<Link key={props.item.readingId} to={readingUrl}>
{props.item.title}
</Link>
</h1>
</CSSTransitionGroup>
</Row>
<hr></hr>
</div>
)
}
<file_sep>/src/views/Readings/Readings.js
import React, {Component} from 'react';
import {getAllReadings} from '../../libs/serverAPI';
import ReadingItem from './ReadingItem';
import {Grid,
} from 'react-bootstrap';
import './Readings.css';
class Readings extends Component {
constructor(props) {
super(props);
this.state = {
readings: null,
};
}
/*
* retrieve reading list before rendering
*/
componentWillMount() {
let getAllPromise = getAllReadings(this.props.childProps.userToken);
getAllPromise.then((readingList) => {
this.setState({
readings: readingList,
});
})
.catch((err) => {
console.log(err);
});
}
render() {
let readings = this.state.readings;
let readingItems = null;
/* while readingItems is not available, display loading bar*/
let view = (
<i id="page-loading-bar" className="fa fa-refresh fa-spin fa-3x fa-fw" aria-hidden="true"></i>
);
/*create a list of <ReadingItem>*/
if (readings) {
readingItems = readings.map((reading) => {
return <ReadingItem key={reading.readingId} item={reading}/>
});
}
/*display readingItems if it's available*/
if (readingItems) {
view = (
<Grid id="grid">
{readingItems}
</Grid>
)
}
return (
<div>
{view}
</div>
);
}
}
export default Readings;
<file_sep>/src/Routes.js
/*******************************************************************************\
* @file Route.js
*
* Contains the component that is responsible for routing urls to views
*******************************************************************************/
import React from 'react';
import {Route,
Switch,
withRouter,
} from 'react-router-dom';
import Homepage from './views/Home/Homepage';
import Signup from './views/Signup/Signup';
import Signin from './views/Signin/Signin';
import NewReading from './views/NewReading/NewReading';
import Error404 from './views/errors/Error404';
import Readings from './views/Readings/Readings';
import Reading from './views/Readings/Reading';
function Routes(props) {
/* urls that only signed in users can access */
const urlsForAuth = (
<Switch>
<Route path='/' exact render={() => <Homepage childProps={props.childProps}/>}/>
<Route path='/newreading' exact render={() => <NewReading childProps={props.childProps}/>}/>
<Route path='/readings' exact render={() => <Readings childProps={props.childProps}/>}/>
<Route path='/reading/:id' exact render={() => <Reading childProps={props.childProps}/>}/>
<Route component={Error404} />
</Switch>
);
/* urls that only anonymous users can access */
const urlsForAnon = (
<Switch>
<Route path='/' exact render={() => <Homepage childProps={props.childProps}/>}/>
<Route path='/signup' exact render={() => <Signup childProps={props.childProps}/>}/>
<Route path='/signin' exact render={() => <Signin childProps={props.childProps}/>}/>
<Route component={Error404} />
</Switch>
);
return (
<div>
{props.childProps.userToken? urlsForAuth:urlsForAnon}
</div>
)
}
export default withRouter(Routes);
<file_sep>/src/libs/user.js
/*******************************************************************************
* @file user.js
* Contains functions that interact with a user object via Amazon AWS
******************************************************************************/
import config from '../config.js';
import {
CognitoUserPool,
AuthenticationDetails,
CognitoUser,
CognitoUserAttribute,
} from 'amazon-cognito-identity-js';
/**
* @return {CognitoUserPool} - a new CognitoUserPool object used for user auth
*/
function createUserPool() {
const userPool = new CognitoUserPool({
UserPoolId: config.cognito.USER_POOL_ID,
ClientId: config.cognito.APP_CLIENT_ID
});
return userPool;
}
/**
* @function - creates new CognitoUser object
* - CognitoUser object is created with a
* userPool in which that user is defined,
* and username
* @param username {String} - email address of user
* @return {CognitoUser} a new CognitoUser object
*/
function createCognitoUser(username) {
const userPool = createUserPool();
return new CognitoUser({
Username: username,
Pool:userPool
});
}
/**
* @function - helper function to create user auth object to be used with AWS
* @param username {String} - user email
* @param password {<PASSWORD>} - user <PASSWORD>
* @return {AuthenticationDetails}
* that is used to authenticate
* user with AWS Cognito
*/
function createUserAuthDetails(username, password) {
const userCredentials = {
Username: username,
Password: <PASSWORD>
};
return new AuthenticationDetails(userCredentials);
}
/**
* @return {CognitoUser}: the current signed in user or
* null if no user found
*/
function getSignedInUser() {
const userPool = createUserPool();
const cognitoUser = userPool.getCurrentUser();
return cognitoUser;
}
/**
* Used in page loads to get currently signed in user's token
* @return {Promise}
* Promise can resolve in 2 ways:
* 1. user token if signed in user present
* 2. null if there is no signed in user
* Promise rejects if session retrieval failed
*/
function getUserToken() {
const cognitoUser = getSignedInUser();
return new Promise((resolve, reject) => {
if (cognitoUser===null) {
resolve(null);
}
cognitoUser.getSession((err, session) => {
if(err) {
reject(err);
} else {
const token = session.getIdToken().jwtToken;
if (token) {
resolve(token)
}
resolve(null);
}
});
});
}
/**
* @function - helper function to create a
* new CognitoUserAttribute object with the given name:value
* pair
* - used in Sign up
*/
function createCognitoUserAttribute(name, value) {
const data = {
Name: name,
Value: value
}
return new CognitoUserAttribute(data);
}
/**
* helper function to authenticate a user given credentials
* @param user {CognitoUser} - signed in user
* @param username {String} - user email
* @param password {String} - user <PASSWORD>
* @return {Promise} - resolve returns userToken
* - reject returns error message
*/
function authenticateUser(user=undefined, username, password) {
if (user===undefined) {
user = createCognitoUser(username);
}
const authDetails = createUserAuthDetails(username, password);
return new Promise(function(resolve, reject) {
user.authenticateUser(authDetails, {
onSuccess: function(result) {
resolve(result.getIdToken().getJwtToken());
},
onFailure: function(err) {
reject(err);
}
});
});
}
export {createCognitoUser,
createUserPool,
createUserAuthDetails,
getSignedInUser,
createCognitoUserAttribute,
getUserToken,
authenticateUser};
<file_sep>/src/containers/FormComponents/FormField.js
/*
* This file contains a component that describes how a single Form field looks like
* Used By Forms
*----------------------------
* expects the following in its props.childProps
* 1. textLabel
* 2. inputType
* 3. inputValue
* 4. placeholder
* 5. inputHandler
*/
import React, {Component} from 'react';
import {
FormGroup,
FormControl,
ControlLabel,
Col,
} from 'react-bootstrap';
class FormField extends Component {
render() {
return (
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
{this.props.childProps.textLabel}
</Col>
<Col sm={10}>
<FormControl
type={this.props.childProps.inputType}
value={this.props.childProps.inputValue}
placeholder={this.props.childProps.placeholder}
onChange={(event) => this.props.childProps.inputHandler(event)}>
</FormControl>
</Col>
</FormGroup>
)
}
}
export default FormField;
| 96cf8e2526ff0df3565d113e4a71730d8f488487 | [
"JavaScript",
"Markdown"
]
| 14 | JavaScript | Tushige/Glasses | 3b74bd8b3e08606491a2fc3ee0ced0176dc257b4 | e38b974cc5c3fd0cd71b891ab2cc95b038c8611b |
refs/heads/master | <repo_name>loleg/PoetRNN<file_sep>/rnn/preprocessing.py
# coding: utf-8
import numpy as np
import csv
# some lists that are useful later
letter_distribution_en = np.array(
[.08167, .01492, .02782, .04253, .12702, .02228, .02015, .06094, .06966, .00153, .00772, .04025, .02406, .06749,
.07507, .01929, .00095, .05987, .06327, .09056, .02758, .00978, .02361, .00150, .01974, .00074])
letters_en = np.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'])
letter_distribution = np.array(
[0.12560000, 0.00639410, 0.00852528, 0.03817090, 0.10366200, 0.00426274, 0.03429570, 0.01511340, 0.12390000,
0.01538540, 0.04727670, 0.04611510, 0.03235800, 0.04127110, 0.04805270, 0.00503778, 0.01123810, 0.00968803,
0.03720210, 0.08254210, 0.06975390, 0.06452220, 0.00618767, 0.02344500])
letters = np.array(
["a", "ä", "b", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "ö", "õ", "p", "r", "s", "t", "u", "ü",
"v"])
# generate letter to number dictionary
def generate_dictionary(location):
with open(location, newline='') as my_file:
dialect = csv.Sniffer().sniff(my_file.read(1024))
my_file.seek(0)
reader = csv.reader(my_file, dialect)
char_to_nums = {'\t': 0}
for row in reader:
if len(row) == 0: continue
for letter in row[0]:
if letter not in char_to_nums.keys():
char_to_nums[letter] = len(char_to_nums)
my_file.close()
return char_to_nums
# generate the reverse dictionary
def reverse_dictionary(dictionary):
rev_dict = {v: k for k, v in dictionary.iteritems()}
return rev_dict
# convert poems to matrices using 1-k encoding
def poem_to_mat(poem, dictionary):
poem_length = len(poem)
vocab_length = len(dictionary)
poem_mat = np.zeros((poem_length, vocab_length))
vocab_list = [dictionary[s] for s in poem]
poem_mat[range(poem_length), vocab_list] = 1
return poem_mat
# generate labels for poems
def generate_labels(poem_mat, dictionary):
labels = np.zeros(poem_mat.shape[0])
labels[:-1] = np.argmax(poem_mat, axis=1)[1:]
labels[-1] = dictionary['\t'] # label last character as tab to indicate the end has been reached.
return labels
# convert a batch of poems to a 3-tensor along with a tensor of labels and a mask
def poem_batch_to_tensor(X, y=None):
b = len(X)
v = len(X[0][0])
# print b,v
len_list = np.array([len(X[i]) for i in range(b)])
m = np.max(len_list)
num_chars = np.sum(len_list) # useful to pad with zeros so they are all same length
x_mat = np.array([np.vstack((np.array(X[i]), np.zeros((m - len_list[i], v)))) for i in range(b)])
x_mat = np.swapaxes(x_mat, 0, 1)
y_mat = np.array([np.hstack((np.array(y[i]), np.zeros(m - len_list[i]))) for i in range(b)], dtype=int).T
# create a mask of so that later we only accumulate cost for entries that actually correspond to letters
mask = np.ones((m, b))
for i in range(b):
mask[len_list[i]:, i] = 0
return x_mat, mask, num_chars, y_mat
<file_sep>/rnn/RNN.py
# First try at a "vanilla" RNN
import numpy as np
from rnn.preprocessing import reverse_dictionary, letters, letter_distribution
# a batched softmax function that can mask certain values
def softmax_loss(X, y, mask=None, num_chars=None):
m, b = X.shape[:2]
# create 'identity mask' if no mask exists
if mask is None:
mask = np.ones((m, b))
num_chars = m * b
probs = np.exp(X - np.amax(X, axis=-1, keepdims=True))
probs /= np.sum(probs, axis=-1, keepdims=True)
rows = np.array(list(range(m)) * b, dtype=int).reshape((b, m)).T
cols = np.array(list(range(b)) * m, dtype=int).reshape((m, b))
# accumulate loss only from unmasked values
loss = -np.sum(np.log(probs[rows, cols, y]) * mask) / num_chars
grad = probs.copy()
grad[rows, cols, y] -= 1
# compute gradient for unmasked values
grad *= mask[:, :, np.newaxis]
grad /= num_chars
return loss, grad
# static methods in this class seemed to make testing easier. This class is largely taken from <NAME>'s
# gist https://gist.github.com/karpathy/587454dc0146a6ae21fc
class LSTM:
# LSTM model with optional linear output_layer on top
@staticmethod
def init(input_size, hidden_size, output_size=None, output_layer=True):
model = {}
WLSTM = np.random.randn(input_size + hidden_size + 1, 4 * hidden_size) / np.sqrt(
input_size + hidden_size) # randomly initialize weights
WLSTM[0, :] = 0 # initialize biases to zero
model['WLSTM'] = WLSTM
# create output layer if needed
if (not output_size is None) and output_layer:
Wout = np.random.randn(hidden_size + 1, output_size) / np.sqrt(hidden_size)
Wout[0, :] = 0
model['Wout'] = Wout
return model
# two layer LSTM model with linear output layer
@staticmethod
def init_two_layer(input_size, hidden1, hidden2, output_size):
model1 = LSTM.init(input_size, hidden1, output_layer=False)
model2 = LSTM.init(hidden1, hidden2, output_size)
model = {
'WLSTM1': model1['WLSTM'],
'WLSTM2': model2['WLSTM'],
'Wout': model2['Wout']
}
return model
# todo: allow for arbitrarily many layers
# LSTM forward pass with optional dropout, the drop_mask feature is useful for testing, but largely unnecessary
@staticmethod
def batch_forward(X, model, output_layer=True, c0=None, h0=None, drop_prob=0.0, drop_mask=None):
# unpack the model
WLSTM = model['WLSTM']
if output_layer:
Wout = model['Wout']
# X is a (n,b,v) array where n=sequence length, b=batch size and v=vocab size
cache = {} # a cache of variables for backpropogation
n, b, v = X.shape
d = int(WLSTM.shape[1] / 4) # hidden size
# initialize c and h to zero if not given
if c0 is None:
c0 = np.zeros((b, d))
if h0 is None:
h0 = np.zeros((b, d))
xphpb = WLSTM.shape[0] # x plus h plus bias
Hin = np.ones((n, b, xphpb)) # input [1, xt, ht-1] to each tick of the LSTM
Hout = np.zeros((n, b, d)) # hidden representation of the LSTM (gated cell content)
Houtstack = np.ones((n, b, d + 1)) # hidden representation with bias
IFOG = np.zeros((n, b, d * 4)) # input, forget, output, gate (IFOG)
IFOGf = np.zeros((n, b, d * 4)) # after nonlinearity
C = np.zeros((n, b, d)) # cell content
Ct = np.zeros((n, b, d)) # tanh of cell content
for t in range(n):
if t == 0:
prevh = h0
else:
prevh = Hout[t - 1]
Hin[t, :, 1:v + 1] = X[t]
Hin[t, :, v + 1:] = prevh
IFOG[t] = Hin[t].dot(WLSTM)
IFOGf[t, :, :3 * d] = 1.0 / (1.0 + np.exp(-IFOG[t, :, :3 * d]))
IFOGf[t, :, 3 * d:] = np.tanh(IFOG[t, :, 3 * d:])
if t == 0:
prevc = c0
else:
prevc = C[t - 1]
C[t] = prevc * IFOGf[t, :, d:2 * d] + IFOGf[t, :, :d] * IFOGf[t, :, 3 * d:]
Ct[t] = np.tanh(C[t])
Hout[t] = IFOGf[t, :, 2 * d:3 * d] * Ct[t]
if drop_prob > 0:
if drop_mask is None:
scale = 1.0 / (1.0 - drop_prob)
drop_mask = (np.random.rand(*(Hout.shape)) < (1 - drop_prob)) * scale
# print drop_mask
Hout *= drop_mask
Houtstack[:, :, 1:] = Hout
if output_layer:
Y = Houtstack.dot(Wout)
cache['WLSTM'] = WLSTM
cache['X'] = X
cache['Hin'] = Hin
cache['Houtstack'] = Houtstack
cache['IFOG'] = IFOG
cache['IFOGf'] = IFOGf
cache['C'] = C
cache['Ct'] = Ct
cache['output_layer'] = output_layer
cache['c0'] = c0
cache['h0'] = h0
cache['drop_prob'] = drop_prob
if drop_prob > 0:
cache['drop_mask'] = drop_mask
if output_layer:
cache['Wout'] = Wout
return Y, cache
else:
return Hout, cache
@staticmethod
def batch_backward(dY, cache):
# dY is (n,b,v) array of backprop error message
# unpack cache
output_layer = cache['output_layer']
WLSTM = cache['WLSTM']
if output_layer:
Wout = cache['Wout']
dWout = np.zeros(Wout.shape)
X = cache['X']
Hin = cache['Hin']
Houtstack = cache['Houtstack']
Hout = Houtstack[:, :, 1:]
IFOG = cache['IFOG']
IFOGf = cache['IFOGf']
C = cache['C']
Ct = cache['Ct']
c0 = cache['c0']
h0 = cache['h0']
drop_prob = cache['drop_prob']
n, b, d = Hout.shape
v = WLSTM.shape[0] - d - 1 # vocab size
# input_size=WLSTM.shape[0] - d - 1
dIFOG = np.zeros(IFOG.shape)
dIFOGf = np.zeros(IFOGf.shape)
dWLSTM = np.zeros(WLSTM.shape)
dHoutstack = np.zeros(Houtstack.shape)
dHin = np.zeros(Hin.shape)
dC = np.zeros(C.shape)
dX = np.zeros((n, b, v))
# backprop first last linear layer
if output_layer:
dHoutstack = dY.dot(Wout.T)
dWout = np.tensordot(np.rollaxis(Houtstack, 2), dY)
dHout = dHoutstack[:, :, 1:]
else:
dHout = dY.copy()
if drop_prob > 0:
dHout *= cache['drop_mask']
for t in reversed(range(n)):
tanhCt = Ct[t]
dIFOGf[t, :, 2 * d:3 * d] = dHout[t] * tanhCt
dC[t] += (1.0 - tanhCt ** 2) * (dHout[t] * IFOGf[t, :, 2 * d:3 * d])
if t > 0:
dIFOGf[t, :, d:2 * d] = C[t - 1] * dC[t]
dC[t - 1] += dC[t] * IFOGf[t, :, d:2 * d]
else:
dIFOGf[t, :, d:2 * d] = c0 * dC[t]
dIFOGf[t, :, :d] = dC[t] * IFOGf[t, :, 3 * d:]
dIFOGf[t, :, 3 * d:] = IFOGf[t, :, :d] * dC[t]
dIFOG[t, :, 3 * d:] = (1.0 - IFOGf[t, :, 3 * d:] ** 2) * dIFOGf[t, :, 3 * d:]
sigs = IFOGf[t, :, :3 * d]
dIFOG[t, :, :3 * d] = (sigs * (1.0 - sigs)) * dIFOGf[t, :, :3 * d]
dWLSTM += Hin[t].T.dot(dIFOG[t])
dHin[t] = dIFOG[t].dot(WLSTM.T)
dX[t] = dHin[t, :, 1:v + 1]
if t > 0:
dHout[t - 1] += dHin[t, :, v + 1:]
grads = {}
grads['X'] = dX
grads['WLSTM'] = dWLSTM
grads['Hout'] = dHout
if output_layer:
grads['Wout'] = dWout
return grads
# loss function for single layer LSTM
def LSTM_cost(X, y=None, mask=None, model=None, num_chars=None, reg=0, **kwargs):
drop_prob = kwargs.get('drop_prob1', 0.0)
if y is None:
drop_prob = 0.0
scores, cache = LSTM.batch_forward(X, model, drop_prob=drop_prob)
if y is None:
return scores
unreg_loss, unreg_loss_grad = softmax_loss(scores, y, mask, num_chars)
loss = unreg_loss + .5 * reg * (np.sum(model['WLSTM'][1:, :] ** 2) + np.sum(model['Wout'][1:, :] ** 2))
grad = LSTM.batch_backward(unreg_loss_grad, cache)
grad['WLSTM'][1:, :] += reg * model['WLSTM'][1:, :]
grad['Wout'][1:, :] += reg * model['Wout'][1:, :]
return loss, grad
# loss function for two layer LSTM
def two_layer_LSTM_cost(X, y=None, mask=None, model=None, num_chars=None, reg=0, **kwargs):
# unpack the model
WLSTM1 = model['WLSTM1']
WLSTM2 = model['WLSTM2']
Wout = model['Wout']
drop_prob1 = kwargs.get('drop_prob1', 0.0)
drop_prob2 = kwargs.get('drop_prob2', 0.0)
if y is None:
drop_prob1 = 0.0
drop_prob2 = 0.0
# forward layer1
scores1, cache1 = LSTM.batch_forward(X, {'WLSTM': WLSTM1}, output_layer=False, drop_prob=drop_prob1)
# forward layer2
scores2, cache2 = LSTM.batch_forward(scores1, {'WLSTM': WLSTM2, 'Wout': Wout}, output_layer=True,
drop_prob=drop_prob2)
# if no labels just return the scores
if y is None:
return scores2
# compute softmax probabilities
unreg_loss, unreg_grad = softmax_loss(scores2, y, mask, num_chars)
# regularize loss
loss = unreg_loss + .5 * reg * (np.sum(WLSTM1[1:, :] ** 2) + np.sum(WLSTM2[1:, :] ** 2) + np.sum(Wout[1:, :] ** 2))
# backpropogate layer2
grad2 = LSTM.batch_backward(unreg_grad, cache2)
# backpropogate layer1
grad1 = LSTM.batch_backward(grad2['X'], cache1)
# regularize gradients and pack them in a dictionary
grad2['WLSTM'][1:, :] += reg * WLSTM2[1:, :]
grad2['Wout'][1:, :] += reg * Wout[1:, :]
grad1['WLSTM'][1:, :] += reg * WLSTM1[1:, :]
grads = {'WLSTM1': grad1['WLSTM'], 'WLSTM2': grad2['WLSTM'], 'Wout': grad2['Wout'], 'X': grad1['X']}
return loss, grads
# this function is aweful, but it works.
# takes a model and builds a poem by sampling from it.
def LSTM_sample(model, temp=1.0, seed=None, max_length=1000, num_layers=2):
# unpack the model
dictionary = model['dictionary']
# create models for each layer
if num_layers == 1:
d1 = model['WLSTM'].shape[1] / 4
d2 = 1
v = model['Wout'].shape[1] # vocab size
if num_layers == 2:
model1 = {}
model2 = {}
model1['WLSTM'] = model['WLSTM1']
model2['WLSTM'] = model['WLSTM2']
model2['Wout'] = model['Wout']
d1 = model['WLSTM1'].shape[1] / 4 # size of hidden layer 1
d2 = model['WLSTM2'].shape[1] / 4 # size of hidden layer 2
# d1=model['WLSTM1'].shape[1]/4 # size of hidden layer 1
# d2=model['WLSTM2'].shape[1]/4 # size of hidden layer 2
rev_dict = reverse_dictionary(dictionary) # create the inverse dicitonary
s = '' # the output string
if seed is None: # initialize first character to random letter it not specified
seed = ''
while not seed.isalpha():
seed = np.random.choice(letters, p=letter_distribution)
s += seed
current_character = seed[-1]
x = np.zeros((1, 1, v))
x[:, :, dictionary[seed[0]]] = 1
i = len(seed)
h1 = np.zeros((1, d1))
h2 = np.zeros((1, d2))
c1 = np.zeros((1, d1))
c2 = np.zeros((1, d2))
# I hate that this seems so hacky. I should make this more modular
if num_layers == 2:
# prime the model using the seed
for j in range(1, len(seed)):
layer1_scores, cache1 = LSTM.batch_forward(x, model1, output_layer=False, h0=h1, c0=c1)
Y, cache2 = LSTM.batch_forward(layer1_scores, model2, h0=h2, c0=c2)
c1 = cache1['C'][0]
c2 = cache2['C'][0]
h1 = cache1['Houtstack'][0, :, 1:]
h2 = cache2['Houtstack'][0, :, 1:]
x = np.zeros((1, 1, v))
x[:, :, dictionary[seed[j]]] = 1
# sample using the model
while current_character != '\t' and i < max_length:
layer1_scores, cache1 = LSTM.batch_forward(x, model1, output_layer=False, h0=h1, c0=c1)
Y, cache2 = LSTM.batch_forward(layer1_scores, model2, h0=h2, c0=c2)
c1 = cache1['C'][0]
c2 = cache2['C'][0]
h1 = cache1['Houtstack'][0, :, 1:]
h2 = cache2['Houtstack'][0, :, 1:]
Y /= temp
probs = np.exp(Y - np.amax(Y))
probs /= np.sum(probs)
# print v,probs.shape
smpl = np.random.choice(v, p=probs[0, 0, :])
current_character = rev_dict[smpl]
s += current_character
x = np.zeros((1, 1, v))
x[:, :, smpl] = 1
i += 1
return s
if num_layers == 1:
# prime model using the seed
for j in range(1, len(seed)):
Y, cache = LSTM.batch_forward(x, model, h0=h1, c0=c1)
c1 = cache['C'][0]
h1 = cache['Houtstack'][0, :, 1:]
x = np.zeros((1, 1, v))
x[:, :, dictionary[seed[j]]] = 1
# sample from the model
while current_character != '\t' and i < max_length:
Y, cache = LSTM.batch_forward(x, model, h0=h1, c0=c1)
c1 = cache['C'][0]
h1 = cache['Houtstack'][0, :, 1:]
Y /= temp
probs = np.exp(Y - np.amax(Y))
probs /= np.sum(probs)
# print v,probs.shape
smpl = np.random.choice(v, p=probs[0, 0, :])
current_character = rev_dict[smpl]
s += current_character
x = np.zeros((1, 1, v))
x[:, :, smpl] = 1
i += 1
return s
| e85cda4dbc21df30d1c0c2e86c9af9f5f3e4bceb | [
"Python"
]
| 2 | Python | loleg/PoetRNN | ca1b68c61f02bb9c6b5abd15ed90ec3b17b29621 | aa49a84f25f4bb087818805a2074058039baa4ea |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
namespace masterF
{
public partial class Form1 : Form
{
int m = 4 * 5;
Image img_graph;
Graphics g;
Graphics l;
int zoom = 4;
double speed; //скорость отрисовки
Pen penGraph = new Pen(Color.Green, 3);
Pen penAxis = new Pen(Color.Orange, 3);
string func;
int min;
int max;
Bitmap map = new Bitmap(DataBank.width, DataBank.height);
public Form1()
{
InitializeComponent();
penGraph.StartCap = System.Drawing.Drawing2D.LineCap.Round;
penGraph.EndCap = System.Drawing.Drawing2D.LineCap.Round;
l = Graphics.FromImage(map);
DataBank.width = Screen.PrimaryScreen.Bounds.Width;
DataBank.height = Screen.PrimaryScreen.Bounds.Height;
sizeLbl.Text = DataBank.width + " × " + DataBank.height + "пкс";
}
static void Opn(ref string[] a, string arg) //перевод в обратную польскую запись
{
Stack<string> s = new Stack<string>();
int j = 0;
for (int i = 0; i < arg.Length; i++) //читаем выражение(слово)
{
double num;
bool isNum = double.TryParse(arg[i].ToString(), out num); //проверяем является ли символ слова числом и записываем символ в нум
if (isNum)//если символ-число
{
a[j] = X10(ref i, arg).ToString();
j++;
continue;
}
if (arg[i] == 'e')
{
a[j] = "e";
j++;
continue;
}
if (arg[i] == 'x')
{
a[j] = "x";
j++;
continue;
}
if (arg[i] == 'p')
{
i++;
if (arg[i] == 'i')
{
a[j] = "pi";
j++;
continue;
}
}
if (arg[i] == 'c')
{
i++;
if (arg[i] == 'o')
{
i++;
if (arg[i] == 's')
{
try
{
while (Priority("cos") <= Priority(s.Peek()))
{
a[j] = s.Pop().ToString();
j++;
}
}
catch { }
s.Push("cos");
continue;
}
}
}
if (arg[i] == 's')
{
i++;
if (arg[i] == 'i')
{
i++;
if (arg[i] == 'n')
{
try
{
while (Priority("sin") <= Priority(s.Peek()))
{
a[j] = s.Pop().ToString();
j++;
}
}
catch { }
s.Push("sin");
continue;
}
}
if (arg[i] == 'q')
{
i++;
if (arg[i] == 'r')
{
i++;
if (arg[i] == 't')
{
try
{
while (Priority("sqrt") <= Priority(s.Peek()))
{
a[j] = s.Pop().ToString();
j++;
}
}
catch { }
s.Push("sqrt");
continue;
}
}
}
}
if (arg[i] == 'l')
{
i++;
if (arg[i] == 'n')
{
try
{
while (Priority("ln") <= Priority(s.Peek()))
{
a[j] = s.Pop().ToString();
j++;
}
}
catch { }
s.Push("ln");
continue;
}
}
if (arg[i] == '(') s.Push("(");
if (arg[i] == ')')
{
while (s.Peek() != "(")
{
a[j] = s.Pop().ToString();
j++;
}
s.Pop();
continue;
}
if (arg[i] == '+' || arg[i] == '-' || arg[i] == '*' || arg[i] == '/' || arg[i] == '^')
{
try
{
while (Priority(arg[i].ToString()) <= Priority(s.Peek()))
{
a[j] = s.Pop().ToString();
j++;
}
}
catch { }
s.Push(arg[i].ToString());
}
}
while (s.Count > 0) { a[j] = s.Pop().ToString(); j++; }
}
static double Priority(string x) //получение приоритета операции
{
switch (x)
{
case "+": return 1;
case "-": return 1;
case "*": return 2;
case "/": return 2;
case "^": return 3;
case "sin": return 4;
case "cos": return 4;
case "ln": return 4;
case "sqrt": return 5;
default: return 0;
}
}
static double X10(ref int i, string arg) //считывание многозначных чисел
{
double o;
double k = Convert.ToDouble(arg[i].ToString());
if (i + 1 < arg.Length && double.TryParse(arg[i + 1].ToString(), out o))
while (double.TryParse(arg[i + 1].ToString(), out o))
{
k = k * 10 + Convert.ToDouble(arg[i + 1].ToString());
i++;
if (i + 1 == arg.Length) break;
}
if (i + 1 < arg.Length && arg[i + 1] == '.')
{
i++;
if (i + 1 < arg.Length && double.TryParse(arg[i + 1].ToString(), out o))
{
int b = 1;
while (double.TryParse(arg[i + 1].ToString(), out o))
{
k = k + Convert.ToDouble(arg[i + 1].ToString()) / Math.Pow(10,b);
i++;
if (i + 1 == arg.Length) break;
b++;
}
}
}
return k;
}
static double Opn_res(string[] a, double x = 0) //обратная польская запись -> результат
{
Stack<double> st = new Stack<double>();
for (int i = 0; i < a.Length; i++)
{
double num;
bool isNum = double.TryParse(a[i], out num);
if (isNum)
st.Push(num);
else
{
double op2;
switch (a[i])
{
case "e":
st.Push(Math.E);
break;
case "x":
st.Push(x);
break;
case "pi":
st.Push(Math.PI);
break;
case "+":
st.Push(st.Pop() + st.Pop());
break;
case "*":
st.Push(st.Pop() * st.Pop());
break;
case "-":
op2 = st.Pop();
if (st.Count != 0) st.Push(st.Pop() - op2);
else st.Push(0 - op2);
break;
case "/":
op2 = st.Pop();
if (op2 != 0.0)
st.Push(st.Pop() / op2);
else return Double.NaN;
break;
case "^":
op2 = st.Pop();
st.Push(Math.Pow(st.Pop(), op2));
break;
case "sin":
if (st.Peek() % Math.PI == 0)
st.Push(0);
else
st.Push(Math.Sin(st.Pop()));
break;
case "cos":
if ((st.Peek() + Math.PI / 2) % Math.PI == 0)
st.Push(0);
else
st.Push(Math.Cos(st.Pop()));
break;
case "ln":
if (st.Peek() < 0) { return 0; }
else st.Push(Math.Log(st.Pop()));
break;
case "sqrt":
if (st.Peek() < 0) { st.Pop();st.Push(0); }//фикс
else
st.Push(Math.Pow(st.Pop(),0.5));
break;
}
}
}
return st.Pop();
}
private void Save(object sender, EventArgs e)
{
saveFileDialog1.Filter = "PNG|*.png";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (graph.Image != null)
{
img_graph.Save(saveFileDialog1.FileName);
SaveDate(Path.GetDirectoryName(saveFileDialog1.FileName) + "\\"
+ Path.GetFileNameWithoutExtension(saveFileDialog1.FileName) + ".никулин");
}
}
}
private void SaveDate(string FileName)
{
table1.EndEdit();
Stream myStream = new FileStream(FileName, FileMode.Create);
if ((myStream) != null)
{
StreamWriter myWriter = new StreamWriter(myStream);
try
{
myWriter.Write(func);
myWriter.WriteLine();
myWriter.Write(min);
myWriter.WriteLine();
myWriter.Write(max);
myWriter.WriteLine();
for (int i = 0; i < table1.RowCount - 1; i++)
{
for (int j = 0; j < table1.ColumnCount; j++)
{
var value = table1.Rows[i].Cells[j].Value;
string str = (value == null ? "0" : value.ToString());
myWriter.Write(str);
myWriter.WriteLine();
}
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myWriter.Close();
}
myStream.Close();
}
}
private void OpenDate(string FileName)
{
Stream myStream = null;
table1.EndEdit();
try { myStream = new FileStream(FileName, FileMode.Open); } catch { }
if (myStream != null)
{
StreamReader myread = new StreamReader(myStream);
try
{
string[] str = myread.ReadToEnd().Split('\n');
table1.RowCount = (str.Count() - 4) / 2 + 1;
func = str[0];
function.Text = func;
min = int.Parse(str[1]);
minBox.Text = (min == -DataBank.width / m / 2 ? "" : min.ToString());
max = int.Parse(str[2]);
maxBox.Text = (max == DataBank.width / m / 2 ? "" : max.ToString());
for (int i = 0; i < table1.RowCount; i++)
{
for (int j = 0; j < table1.ColumnCount; j++)
{
try
{
table1.Rows[i].Cells[j].Value = str[2 * i + j + 3];
} catch{ }
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
myread.Close();
}
myStream.Close();
}
}
private void Open(object sender, EventArgs e)
{
openFileDialog1.Filter = "PNG|*.png";
openFileDialog1.ValidateNames = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
img_graph = Image.FromFile(openFileDialog1.FileName);
trackBar2_Scroll(this, new EventArgs());
OpenDate(Path.GetDirectoryName(openFileDialog1.FileName) + "\\"
+Path.GetFileNameWithoutExtension(openFileDialog1.FileName) + ".никулин");
}
}
private void печатьToolStripMenuItem_Click(object sender, EventArgs e)
{
printDocument1.PrintPage += PrintDocument1_PrintPage;
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
try { printDocument1.Print(); } catch { }
}
}
private void PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bm = new Bitmap(DataBank.width, DataBank.height);
graph.DrawToBitmap(bm, new Rectangle(0, 0, DataBank.width, DataBank.height));
e.Graphics.DrawImage(bm, 0, 0);
bm.Dispose();
}
private void размерToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 WH = new Form2();
if (WH.ShowDialog() == DialogResult.OK)
{
sizeLbl.Text = DataBank.width + " × " + DataBank.height + "пкс";
Clear(this, new EventArgs());
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
penAxis.Width = trackBar1.Value;
penGraph.Width = penAxis.Width;
}
private void GraphColor(object sender, EventArgs e)
{
if(colorDialog1.ShowDialog() == DialogResult.OK)
{
penGraph.Color = colorDialog1.Color;
((Button)sender).BackColor = colorDialog1.Color;
}
}
private void AxisColor(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
penAxis.Color = colorDialog1.Color;
((Button)sender).BackColor = colorDialog1.Color;
Clear(this, new EventArgs());
}
}
private void BackgroundColor(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
graph.BackColor = colorDialog1.Color;
((Button)sender).BackColor = colorDialog1.Color;
Clear(this, new EventArgs());
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.DoubleBuffered = true;
}
//МАСШТАБ
Image Zoom(Image img, Size size)
{
map = new Bitmap(img, DataBank.width * size.Width / 4, DataBank.height * size.Height / 4);
l.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
return map;
}
private void trackBar2_Scroll(object sender, EventArgs e)
{
if(zoombar.Value > 0)
{
zoom = zoombar.Value;
graph.Image = Zoom(img_graph, new Size(zoombar.Value, zoombar.Value));
l = Graphics.FromImage(map);
zoomLbl.Text = (zoombar.Value * 25).ToString() + "%";
}
if (center.Checked) CenterPosition(); //привязка к центру
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(graph.Image != null)
{
graph.Dispose();
}
}
private void CenterPosition()
{
HScrollProperties H = panel1.HorizontalScroll;
H.Value = (H.Maximum - H.LargeChange) / 2;
VScrollProperties V = panel1.VerticalScroll;
V.Value = (V.Maximum - V.LargeChange) / 2;
panel1.PerformLayout();
}
private void graph_Move(object sender, MouseEventArgs e)
{
int MousePX = e.X / zoombar.Value * 4;
int MousePY = e.Y / zoombar.Value * 4;
coordinateLbl.Text = MousePX.ToString() + ", " + MousePY.ToString() + "пкс";
string MouseX = string.Format("{0:N2}", (MousePX - DataBank.width / 2) / (float)m);
string MouseY = string.Format("{0:N2}", -(MousePY - DataBank.height / 2) / (float)m);
coordinateLbl2.Text = "X= " + MouseX + ", Y= " + MouseY;
}
private void DecZoom(object sender, EventArgs e)
{
if (zoombar.Value > zoombar.Minimum)
{
zoombar.Value--;
trackBar2_Scroll(this, new EventArgs());
}
}
private void IncZoom(object sender, EventArgs e)
{
if (zoombar.Value < zoombar.Maximum)
{
zoombar.Value++;
trackBar2_Scroll(this, new EventArgs());
}
}
private void graph_MouseLeave(object sender, EventArgs e)
{
coordinateLbl.Text = "Координаты";
coordinateLbl2.Text = "Координаты";
}
private void create_Click(object sender, EventArgs e)
{
if (AnimBtn.Checked)
{
zoombar.Value = 4;
trackBar2_Scroll(this, new EventArgs());
} else
img_graph = Zoom(img_graph, new Size(4, 4)); //100% масштаб
min = -DataBank.width / m / 2; //область определения функции
max = DataBank.width / m / 2;
try
{
min = int.Parse(minBox.Text);
}
catch { }
try
{
max = int.Parse(maxBox.Text);
}
catch { }
string[] g1;
g1 = new string[function.Text.Length]; //считываем функцию
func = function.Text;
Opn(ref g1, function.Text); //переводим в обратную польскую запись
g = Graphics.FromImage(map);//-----------------БЕЗ АНИМАЦИИ
speed = 0.007;
if (AnimBtn.Checked)
{
ProgressBar.Visible = true;
ProgressBar.Maximum = (max - min);
l = graph.CreateGraphics();//--------------------АНИМАЦИЯ
if (comboBox.Text == "Быстро") speed = 0.007;
if (comboBox.Text == "Средне") speed = 0.004;
if (comboBox.Text == "Медленно") speed = 0.001;
}
table1.Rows.Clear();
bool Vis;
for (double i = min; i < max; i += speed * (11 - m / 5))
{
try
{
double y = Opn_res(g1, i);
double y1 = Opn_res(g1, i + speed * (11 - m / 5));
if (Double.IsNaN(y)&&Double.IsNaN(y1))
{
MessageBox.Show("Ошибка. Деление на ноль");
break;
}
float px = (Convert.ToInt64(i * m) + DataBank.width / 2);
float py = (DataBank.height / 2 - Convert.ToInt64(y * m));
float px1 = (Convert.ToInt64((i + speed * (11 - m / 5)) * m) + DataBank.width / 2);
float py1 = (DataBank.height / 2 - Convert.ToInt64(y1 * m));
if (((py > 0) && (py < DataBank.height)) || ((py1 > 0) && (py1 < DataBank.height)))
Vis = true;
else Vis = false;
ProgressBar.Value = (int)(i - min + 1);
if ((py1-py < 500)&&Vis)
{
if ((AnimBtn.Checked) && (comboBox.Text != "Скорость"))
{
l.DrawLine(penGraph, px, py, px1, py1);
}
g.DrawLine(penGraph, px, py, px1, py1);
table1.Rows.Add(Convert.ToSingle(i), Convert.ToSingle(y));
}
}
catch { }
}
ProgressBar.Visible = false;
img_graph = map;
trackBar2_Scroll(this, new EventArgs());
}
private void Clear(object sender, EventArgs e)
{
min = -DataBank.width / m / 2; ;
max = DataBank.width / m / 2; ;
func = "";
map = new Bitmap(DataBank.width, DataBank.height);
l = Graphics.FromImage(map);
l.Clear(graph.BackColor);
l.DrawLine(penAxis, 0, DataBank.height / 2, DataBank.width, DataBank.height / 2); //оси
l.DrawLine(penAxis, DataBank.width / 2, 0, DataBank.width / 2, DataBank.height);
for (int i = -DataBank.height / m; i < DataBank.height / m; i += 1) //штрихи на осях
{
l.DrawLine(new Pen(penAxis.Color, 1),
DataBank.width / 2 - 5,
DataBank.height / 2 - (i * m),
DataBank.width / 2 + 5,
DataBank.height / 2 - (i * m));
}
for (int i = -DataBank.width / m; i < DataBank.width / m; i += 1)
{
l.DrawLine(new Pen(penAxis.Color, 1),
DataBank.width / 2 + (i * m),
DataBank.height / 2 - 5,
DataBank.width / 2 + (i * m),
DataBank.height / 2 + 5);
}
img_graph = map;
trackBar2_Scroll(this, new EventArgs());
CenterPosition();
}
private void Anim(object sender, EventArgs e)
{
if (AnimBtn.Checked)
{
comboBox.Visible = true;
} else
{
comboBox.Visible = false;
}
}
private void Table(object sender, EventArgs e)
{
if (tableBtn.Checked)
{
table1.Visible = true;
tableClear.Visible = true;
tableCreate.Visible = true;
} else
{
table1.Visible = false;
tableClear.Visible = false;
tableCreate.Visible = false;
}
}
private void button4_Click(object sender, EventArgs e)
{
table1.Rows.Clear();
}
private void tableCreate_Click(object sender, EventArgs e)
{
img_graph = Zoom(img_graph, new Size(4, 4)); //100% масштаб
g = Graphics.FromImage(map);//-----------------БЕЗ АНИМАЦИИ
int kol = table1.Rows.Count - 1;
for (int i = 0; i < kol; i++)
{
try
{
table1[1, i].Value = Convert.ToSingle(table1[1, i].Value);
table1[0, i].Value = Convert.ToSingle(table1[0, i].Value);
}
catch { }
}
table1.Sort(table1.Columns[0], ListSortDirection.Ascending);
float px = (Convert.ToInt64(Convert.ToSingle(table1[0, 0].Value) * m) + DataBank.width / 2) * zoom / 4;
float py = (DataBank.height / 2 - Convert.ToInt64(Convert.ToSingle(table1[1, 0].Value) * m)) * zoom / 4;
g.DrawRectangle(penGraph, px, py, 1, 1);
for (int i = 0; i < kol - 1; i++)
{
try
{
px = (Convert.ToInt64(Convert.ToSingle(table1[0, i].Value) * m) + DataBank.width / 2) * zoom / 4;
py = (DataBank.height / 2 - Convert.ToInt64(Convert.ToSingle(table1[1, i].Value) * m)) * zoom / 4;
g.DrawLine(penGraph, px, py,
(Convert.ToInt64(Convert.ToSingle(table1[0, i + 1].Value) * m) + DataBank.width / 2) * zoom / 4,
(DataBank.height / 2 - Convert.ToInt64(Convert.ToSingle(table1[1, i + 1].Value) * m)) * zoom / 4
);
} catch { }
}
img_graph = map;
trackBar2_Scroll(this, new EventArgs());
}
private void справкаToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("ФАЙЛ\nСохраниение - сохраняет файл\nОткрыть - открывает файл\nПечать - печатает файл\n\nНАСТРОЙКИ\n" +
"Анимация - добавляет выбор скорость\nПривязка к центру - при совершении действий располагает координату (0; 0) в " +
"центре экрана\nТаблица - показывает таблицу\nРазмер - вызывает окно для изменения размера холста\n\nСПРАВКА\nвывод справки\n" +
"\nДОСТУПНЫЕ ФУНКЦИИ\n+ сложение\n- вычитание\n* умножение\n/ деление\ne = 2,718281\npi = 3,1415926\nx^2 - степень\n" +
"sqrt(x) - корень\nsin(x) - синус\ncos(x) - косинус\nln(x) - натуральный логарифм"
);
}
private void EnterClick(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
create_Click(this, new EventArgs());
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace masterF
{
static class DataBank
{
public static int width = 1280;
public static int height = 720;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace masterF
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
numericUpDown1.Value = DataBank.width;
numericUpDown2.Value = DataBank.height;
}
private void button2_Click(object sender, EventArgs e)
{
DataBank.width = Convert.ToInt32(numericUpDown1.Value);
DataBank.height = Convert.ToInt32(numericUpDown2.Value);
}
}
}
| e6d3402b08992f74f3d0cd2cfe97e68c5269418e | [
"C#"
]
| 3 | C# | RuEnHub/MasterFunction | 4b930e51f1e7cb8cc0876208b657e4267afb3da1 | 546711a2bb42ff90f1850f0865d86b8c79b6eede |
refs/heads/master | <file_sep># This repository has been archived.
hadoopbuild
===========
wrapper repo for hadoop builds.
<file_sep>#!/bin/sh -ex
# deal with the fuse artifacts to create a tarball
ALTISCALE_RELEASE=${ALTISCALE_RELEASE:-0.1.0}
tar -C ${WORKSPACE}/hadoop-common/hadoop-hdfs-project/hadoop-hdfs/target/native/main/native/fuse-dfs -cvzf ${WORKSPACE}/hadoop-common/hadoop-dist/target/fuse-${ARTIFACT_VERSION}.tar.gz fuse_dfs
# convert each tarball into an RPM
DEST_ROOT=${INSTALL_DIR}/opt/fuse-${ARTIFACT_VERSION}
mkdir --mode=0755 -p ${DEST_ROOT}
cd ${DEST_ROOT}
tar -xvzpf ${WORKSPACE}/hadoop-common/hadoop-dist/target/fuse-${ARTIFACT_VERSION}.tar.gz
chmod 500 ${DEST_ROOT}/fuse_dfs
cd ${RPM_DIR}
export RPM_NAME=vcc-fuse-${ARTIFACT_VERSION}
fpm --verbose \
--maintainer <EMAIL> \
--vendor VertiCloud \
--provides ${RPM_NAME} \
--description "${DESCRIPTION}" \
--replaces vcc-fuse \
-s dir \
-t rpm \
-n ${RPM_NAME} \
-v ${ALTISCALE_RELEASE} \
--iteration ${DATE_STRING} \
--rpm-user root \
--rpm-group root \
-C ${INSTALL_DIR} \
opt
#clear the install dir and re-use
rm -rf ${INSTALL_DIR}
mkdir -p --mode 0755 ${INSTALL_DIR}
OPT_DIR=${INSTALL_DIR}/opt
mkdir --mode=0755 -p ${OPT_DIR}
cd ${OPT_DIR}
tar -xvzpf ${WORKSPACE}/hadoop-common/hadoop-dist/target/hadoop-${ARTIFACT_VERSION}.tar.gz
chmod 755 ${OPT_DIR}/hadoop-${ARTIFACT_VERSION}
# https://verticloud.atlassian.net/browse/OPS-731
# create /etc/hadoop, in a future version of the build we may move the config there directly
ETC_DIR=${INSTALL_DIR}/etc/hadoop-${ARTIFACT_VERSION}
mkdir --mode=0755 -p ${ETC_DIR}
# move the config directory to /etc
cp -rp ${OPT_DIR}/hadoop-${ARTIFACT_VERSION}/etc/hadoop/* $ETC_DIR
mv ${OPT_DIR}/hadoop-${ARTIFACT_VERSION}/etc/hadoop ${OPT_DIR}/hadoop-${ARTIFACT_VERSION}/etc/hadoop-templates
cd ${INSTALL_DIR}
find etc -type f -print | awk '{print "/" $1}' > /tmp/$$.files
export CONFIG_FILES=""
for i in `cat /tmp/$$.files`; do CONFIG_FILES="--config-files $i $CONFIG_FILES "; done
export CONFIG_FILES
rm -f /tmp/$$.files
#interleave lzo jars
for i in share/hadoop/httpfs/tomcat/webapps/webhdfs/WEB-INF/lib share/hadoop/mapreduce/lib share/hadoop/yarn/lib share/hadoop/common/lib; do
cp -rp ${WORKSPACE}/hadoop-lzo/target/hadoop-lzo-[0-9]*.[0-9]*.[0-9]*-[0-9]*[0-9].jar ${OPT_DIR}/hadoop-${ARTIFACT_VERSION}/$i
done
cp ${WORKSPACE}/hadoop-lzo/target/native/Linux-amd64-64/lib/libgplcompression.* ${OPT_DIR}/hadoop-${ARTIFACT_VERSION}/lib/native/
## ODPI
# setup links for odpi layout compliance
# client jars it expects to find, from all over the layout
CLIENT_DIR=${OPT_DIR}/client
mkdir ${CLIENT_DIR}
for path in common common/lib mapreduce yarn yarn/lib hdfs hdfs/lib; do
for jar in `ls ${OPT_DIR}/share/hadoop/${path}/*.jar | xargs -n1 basename`; do
ln -s ${OPT_DIR}/share/hadoop/${path}/${jar} ${CLIENT_DIR}/${jar}
done
done
# expects these files to exist
touch ${OPT_DIR}/libexec/hadoop-layout\.sh
touch ${OPT_DIR}/libexec/init-hdfs\.sh
# non-versioned symbolic links for hdfs and common
for jar in hadoop-hdfs hadoop-hdfs-nfs; do
ln -s ${OPT_DIR}/share/hadoop/hdfs/${jar}-${ARTIFACT_VERSION}\.jar ${OPT_DIR}/share/hadoop/hdfs/${jar}\.jar
done
for jar in hadoop-common hadoop-nfs; do
ln -s ${OPT_DIR}/share/hadoop/common/${jar}-${ARTIFACT_VERSION}\.jar ${OPT_DIR}/share/hadoop/common/${jar}\.jar
done
## End ODPI
cd ${RPM_DIR}
export RPM_NAME=`echo vcc-hadoop-${ARTIFACT_VERSION}`
fpm --verbose \
--maintainer <EMAIL> \
--vendor VertiCloud \
--provides ${RPM_NAME} \
--provides "libhdfs.so.0.0.0()(64bit)" \
--provides "libhdfs(x86-64)" \
--provides libhdfs \
--replaces vcc-hadoop \
--depends 'lzo > 2.0' \
-s dir \
-t rpm \
-n ${RPM_NAME} \
-v ${ALTISCALE_RELEASE} \
--iteration ${DATE_STRING} \
--description "${DESCRIPTION}" \
${CONFIG_FILES} \
--rpm-user root \
--rpm-group root \
-C ${INSTALL_DIR} \
opt etc
| 840452b219fa102a79127c7786aa8918c45c765a | [
"Markdown",
"Shell"
]
| 2 | Markdown | VertiPub/hadoopbuild | 95d4e7cc5f061ee558406989a240086da41a7aab | ad97c48d43866de5d74aaec2ec51767ee5232f21 |
refs/heads/master | <repo_name>llewok/Vikings<file_sep>/src/game/game.java
package game;
import org.newdawn.slick.*;
/**
* Created by bob on 6/08/15.
*/
public class game extends BasicGame {
Animation sheetRunning;
anim dude;
Map map;
public game()
{
super("Game");
}
public static void main(String[] args)
{
try
{
AppGameContainer app = new AppGameContainer(new game());
app.setDisplayMode(500, 500, false);
app.start();
}
catch (Exception e)
{
System.out.print("Error in starting.\n");
}
}
@Override
public void init(GameContainer container) throws SlickException
{
try {
SpriteSheet sheet = new SpriteSheet("fig06.jpg", 162, 220);
sheetRunning = new Animation();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
sheetRunning.addFrame(sheet.getSprite(j, i), 150);
}
}
dude = new anim(sheetRunning);
dude.x = 10;
dude.y = 20;
map = new Map("data/defaultMap");
}
catch (Exception e)
{
System.out.print("Error loading sheet.\n");
}
}
@Override
public void update(GameContainer container, int delta) throws SlickException
{
}
public final int WHITE = 0;
public final int BLACK = 1;
public final int KING = 2;
public final int VACANT = 3;
public void render(GameContainer container, Graphics g) throws SlickException
{
// use 0,0 since it must exist and all sizes are the same.
float cellbackgroundSize = map.get(0, 0).cellBackground.getWidth();
for (int x = 0; x < map.mapSize; x++)
{
for (int y = 0; y < map.mapSize; y++)
{
map.get(x, y).cellBackground.draw(((float)x * 60), ((float)y * 60));
if (map.get(x, y).pieceOnCell.type != VACANT)
{
map.get(x, y).pieceOnCell.whileStationary.draw(((float)x * 60) + 1, ((float)y * 60) + 1);
}
}
}
dude.animation.draw(dude.x, dude.y);
}
@Override
public void mousePressed (int button, int x, int y)
{
System.out.print("Mouse Pressed.\n");
dude.x = (float)x;
dude.y = (float)y;
map.saveMap("data/defaultMap");
if (map.isPointOnMap(x, y))
{
map.handleMapMouseClick(x, y, button);
}
else
{
//On user interface.
}
}
@Override
public void mouseMoved(int oldx, int oldy, int newx, int newy)
{
dude.x = (float)newx;
dude.y = (float)newy;
}
@Override
public void mouseReleased(int button, int x, int y)
{
}
@Override
public void mouseWheelMoved(int change)
{
}
@Override
public void keyPressed(int key, char c)
{
map.handleMapKeyPress(key);
}
@Override
public void keyReleased(int key, char c)
{
}
}
<file_sep>/src/widget/Box.java
package widget;
/**
* Created by OlymBeast on 12/08/2015.
*/
public class Box
{
public int x, y, w, h;
}
<file_sep>/src/game/MapCell.java
package game;
import org.newdawn.slick.Image;
/**
* Created by bob on 7/08/15.
*/
public class MapCell {
public final int EMPTY = 0;
public final int CASTLE = 1;
public final int NOT_TRAVERSABLE = 2;
public final int HALL = 3;
int type = EMPTY;
Piece pieceOnCell;
Image cellBackground;
public MapCell(int type, Piece piece, String cellBackground)
{
this.type = type;
this.pieceOnCell = piece;
try {
this.cellBackground = new Image(cellBackground);
}
catch (Exception e)
{
System.out.print("Error: MapCell background could not be loaded.\n");
}
}
@Override
public String toString()
{
return String.valueOf(type) + ":" + pieceOnCell.toString() + ":" + cellBackground.getResourceReference();
}
} | d6c96712cb135417a386cb3fbd056269f454e742 | [
"Java"
]
| 3 | Java | llewok/Vikings | a53508b1075d5c4777a543cde20d5ac1da9c5f19 | bde3d2a73dee846ae4d95a708e3a5e68f7f30a7a |
refs/heads/master | <file_sep>let test;
console.log(test);
function add(num1,num2) {
console.log(num1 + num2);
return
}
const result = add(32,4);
console.log(result);
function add(num1,num2) {
console.log(num1);
}
const result = add(3);
console.log(result);
const person = {name: '<NAME>',phone:354356};
console.log(person.salary);
let fun = undefined;
console.log(fun);<file_sep>// const first = 2;
// const second = "2";
// if (first == second) {
// console.log("condition is true");
// }
// else
// {
// console.log("condition is false");
// }
//output is true for '=='
// const first = 2;
// const second = "2";
// if (first === second) {
// console.log("condition is true");
// }
// else
// {
// console.log("condition is false");
// }
//output is false '==='
const first = 1;
const second =true;
if (first === second) {
console.log("condition is true");
}
else
{
console.log("condition is false");
}
//output is false '==='
<file_sep>const nums = [1,2,4,5,6,7,8,9,10];
const part = nums.slice(2,6);
console.log(part);
console.log(nums);
const nums = [1,2,4,5,6,7,8,9,10];
const remove = nums.splice(2,6,45,77);
console.log(remove);
console.log(nums);
const nums = [1,2,4,5,6,7,8,9,10];
const together = nums.join(" ");
console.log(together);
console.log(nums);<file_sep>#include<stdio>
main()
{
printf("hello");
f
}<file_sep>const numbers = [2,4,5,6,7];
const output = [];
for (let i = 0; i < numbers.length; i++) {
const element = numbers[i];
const result = element *element;
output.push(result);
}
console.log(output);
const numbers = [2,4,5,6,7];
// function square(element) {
// return element * element;
// }
const square = element => element * element;
const square = x => x*x;
numbers.map(function(element){
console.log(element);
})
numbers.map(function(element,index){
console.log(element,index);
})
numbers.map(function(x,index,array){
console.log(x,index,array);
})
const numbers = [2,4,5,6,7];
const result = numbers.map(x => x * x);
console.log(result);
const numbers = [2,4,5,6,7];
const bigger = numbers.filter(x => x >4);
console.log(bigger);
const numbers = [2,4,5,6,7];
const isThere = numbers.find(x => x >4);
console.log(isThere); | 049770d78daf2786e9b2c1aeae29da018dc7464d | [
"JavaScript",
"C"
]
| 5 | JavaScript | MdGolamMostafa/advanced-javaScript-practice | c902464b111efb5e6f818c23e00c6ca2dd5f4942 | 73472db3d7918ad034d6c6d28d2d9bc19c02e372 |
refs/heads/master | <repo_name>jkingsbery/agentsim<file_sep>/agent.py
from numpy import matrix
import random
class Agent:
def __init__(self):
self.quantity=random.randrange(10)
self.cash=random.randrange(100)
self.reservation_price=8
self.market_rate=10
self.cost_to_create=5
self.value_to_consume=8
def iterate(self):
pass
class BuyingAgent:
def __init__(self):
self.quantity=2
self.reserve_price=max(random.normalvariate(8,2),0)
print "Agent reserve price " + str(self.reserve_price)
def quantityWanted(self,price):
m=-1
b=20
return max(0,(price-b)/m)
def update(self,new_price):
if new_price<self.reserve_price:
self.quantity=self.quantityWanted(self.reserve_price)
else:
self.quantity=0
class SellingAgent:
def __init__(self):
self.b=0
self.m=1
self.quantity=0
self.price=self.marginalCost(self.quantity)
self.last_revenue=0
def fillOrders(self,buyingAgents):
sold=sum(map(lambda x:x.quantity,buyingAgents))
self.last_revenue=sum(map(lambda x:self.price*x.quantity,buyingAgents))
if self.quantity>sold:
self.quantity-=0.1
elif self.quantity<sold:
self.quantity+=0.1
self.price=self.marginalCost(self.quantity)
def __str__(self):
return "<Price="+str(self.price)+",Quantity="+str(self.quantity)+",Revenue="+str(self.last_revenue)+">"
def marginalCost(self,quantity):
return self.m*quantity+self.b
if __name__=="__main__":
random.seed(13)
NUM_ITERS=10000
NUM_BUYERS=20
selling=SellingAgent()
buyers=[]
for i in range(NUM_BUYERS):
buyers.append(BuyingAgent())
for iter in range(NUM_ITERS):
selling.fillOrders(buyers)
for x in buyers:
x.update(selling.price)
print selling
| 03549d8de51efac693658ab801db7864966d9d7e | [
"Python"
]
| 1 | Python | jkingsbery/agentsim | ba13f870d28bae9686ccf5bb3422e6bbe841980c | fb57a71684b1622db471e1abe3a9ef1dc90189db |
refs/heads/master | <repo_name>NaryxHaxns/Jabberwocky-Sweeper-Project-1<file_sep>/README.md
# ~~Mine~~**Jabberwocky**-Sweeper

### A Lewis Carroll themed edition of the classic Minesweeper game.
______________________________________________________________________
## A Brief History
______________________________________________________________________
There are a number of variations to the game, including probably the most well-known being *Microsoft Minesweeper* (<NAME> & <NAME>, c. early 1990s). Other variants over time include *Cube* (Jerimac Ratliff, c. 1960s), *Mined-Out* (Qucksilva, c. 1983), *Yomp* (Virgin Interactive, c. 1983), *Relentless Logic* or *RLogic* (Conway, Hong, and Smith, c. 1985), among many others.
______________________________________________________________________
## Why Minesweeper and why Lewis Carroll's Jabberwocky
______________________________________________________________________
As a youth I frequently played Minesweeper on my PC as it was a free game loaded as part of the Microsoft package. Having spent so much time formatively playing I chose this game to piece it together and figure out how a nostalgic favorite works. Similarly, I have personally always been an admirer of <NAME> and <NAME>'s works and wanted to implement a bit of Wonderland flair over the traditional, primarily grey game. I still maintained a primarily greyscale look, save for the red clock and mine counters. I intentionally made these pop out of the trees as the Jabberwocky's eyes would leering from the tulgey wood. In the end of Carroll's piece the King is asking his son if he had slain the Jabberwocky. Thus, I crafted my endgame message to seem as though it were coming on an important bit of parchment with a regal, cursive tone, contrary to the eerie font of the rest of the game, as though the King himself were issuing your endgame fate. I've also worked a few of Carroll's famed creatures from Jabberwocky into the failures you may come across...keep playing and you may see them all!
______________________________________________________________________
## Screenshots
______________________________________________________________________
Game Board:

Gameplay with mine flag:

Failure message example:

______________________________________________________________________
## Technologies Used
______________________________________________________________________
* HTML
* CSS
* Javascript
______________________________________________________________________
## Getting Started
______________________________________________________________________
The objective of the game is to navigate the board and *carefully* decide where to begin. Once you have made your first choice, which will either have been a single numbered tile or (if you are lucky) an empty space. If you manage to find an empty space, the board will open all surrounding empty spaces until it reaches an "edge" of numbers. The numbers are significant, so pay them close attention: each number represents how many mines surround that number. If the number is a **1**, that means one of the eight tiles surrounding this **1** is a mine. The same logic applies if the number you found is a **4**: there are four mines in the eight tiles surrounding this tile. If you find a tile that you think may be a mine, right-click (or control-click) on that tile to place a flag marker.
Now that you know the rules, [let's play](https://naryxhaxns.github.io/Jabberwocky-Sweeper-Project-1/)!
______________________________________________________________________
## Next Steps
______________________________________________________________________
Icebox Items:
* Give the user the option of choosing a 9x9, 16x16, or 16x30 sized board.
* Incorporate audio effects and animations to a fuller extent than I have used.
* Storing player names and win times in the space at the bottom of the page using window.localStorage.
* Further media query functionality to allow gameplay across all platforms.<file_sep>/js/main.js
//Constants
//Lose Object to randomize failure messages
let lose = {
'1': 'The Jabberwock caught you in its claws and bit you with its jaws!',
'2': 'The Jubjub bird swooped down and plucked you from the ground!',
'3': 'You have become the latest catch of the frumious Bandersnatch!'
};
//State variables
//Declare board
let board;
//Declare true/false board
let winBoard;
//Declare timer and clock initialization variables
let timerFunc = setInterval(timerClock, 1000);
let begin = 1;
//Declare number of mines left
let mines;
//Declare win
let winner;
let loser;
//Empty Array for mine logic
let mineIdx = [];
//Array for recursive logic
let checked = [];
//End Game Message
let gameOver = document.querySelector('.endGame');
//Cached elements
//An array of column Arrays creating an accessible board of Elements
const boardElem = [];
for (let col = 1; col < 10; col++) {
boardElem.push(Array.from(document.querySelectorAll(`#board section:nth-child(${col}) > div`)));
};
//Event Listeners
//Establish a listener/function for every click on every tile
document.getElementById('board').addEventListener('click', tileSelect);
function tileSelect(e) {
let clIdxRow = e.target.getAttribute('row');
let clIdxCol = e.target.getAttribute('col');
if(board[clIdxRow][clIdxCol] === -1){
winner = loser;
for(i = 0; i < board.length; i++){
for(j = 0; j < board[i].length; j++){
if(board[i][j] === -1){
boardElem[clIdxCol][clIdxRow].setAttribute('style', 'background-image: url(https://i.imgur.com/dNjBu6E.jpg); background-size: cover;');
};
boardElem[clIdxCol][clIdxRow].setAttribute('style', 'background-image: url(https://i.imgur.com/DG8VfK0.jpg); background-size: cover;');
};
};
} else {
zeroVoid(clIdxRow, clIdxCol);
};
render();
};
//Establish a listener/function for game reset
document.querySelector('button').addEventListener('click', reset);
function reset() {
location.reload();
};
//Initialization
init();
function init() {
//Establish the board as a new/clear game
board = [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
];
//Establish true/false board for win logic
winBoard = [
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false],
[false,false,false,false,false,false,false,false,false]
];
//Process mine and numeric logic
mineIdxGrab();
minePlace();
addOne();
numMines();
//Establish the win to null
winner = null;
//Invoke render()
render();
};
//Render
function render() {
//Update win based on mine or no mine clicked
checkWinLose();
let tempWin = true;
for(i = 0; i < winBoard.length; i++) {
for(j = 0; j < winBoard[i].length; j++) {
if(winBoard[i][j] == false) {
tempWin = false;
};
};
};
if(tempWin) {
timerStop();
document.getElementById('board').removeEventListener('click', tileSelect);
gameOver.setAttribute('style', 'visibility: visible;');
gameOver.innerHTML = 'And hast thou slain the Jabberwock? O frabjous day! Callooh! Callay!';
}
//Update the mines remaining based on the last action
numMines();
};
//Randomize indices for mines
function mineRando(min,max) {
return Math.floor(Math.random() * (max - min) + min);
};
//Creating an Array of indices and storing them for placement
function mineIdxGrab() {
for(let i=0; i < 10 || mineIdx.length < 10; i++) {
let mine = [mineRando(0,8), mineRando(0,8)];
if(!mineIdx.toString().includes(mine.toString())) {
mineIdx.push(mine);
};
};
};
//Placing mines throughout the board from the mineIdx array
function minePlace() {
for(i=0; i < mineIdx.length; i++) {
board[mineIdx[i][0]][mineIdx[i][1]] = -1;
winBoard[mineIdx[i][0]][mineIdx[i][1]] = true;
};
};
//Checking where in the board there is a mine and adding 1 to the
//value of all surrounding tiles
function addOne() {
console.log(board)
//FOR for both row and column iteration location
for(i=0; i < board.length; i++) {
for(j=0; j < board[i].length; j++) {
//IF the iteration at [i][j] is a mine
if (board[i][j] === -1) {
//Checking directionals N and NE
if(board[i - 1]) {
board[i - 1][j] !== -1 ? board[i - 1][j] += 1 : '';
board[i - 1][j + 1] !== -1 ? board[i - 1][j + 1] += 1 : '';
//Checking directional NW
if(j !== 0) {
board[i - 1][j - 1] !== -1 ? board[i - 1][j - 1] += 1 : '';
};
};
//Checking directionals S and SE
if(board[i + 1]) {
board[i + 1][j] !== -1 ? board[i + 1][j] += 1 : '';
board[i + 1][j + 1] !== -1 ? board[i + 1][j + 1] += 1 : '';
//Checking directional SW
if(j !== 0) {
board[i + 1][j - 1] !== -1 ? board[i + 1][j - 1] += 1 : '';
};
};
//Checking directionals E and W
board[i][j + 1] !== -1 ? board[i][j + 1] += 1 : '';
if(j !== 0) {
board[i][j - 1] !== -1 ? board[i][j - 1] += 1 : '';
};
};
};
};
};
//Set up the timer start and stop functions
function timerClock() {
// timerFunc = setInterval(timerClock, 1000);
document.querySelector('.timer').innerHTML = begin;
begin++;
};
function timerStop() {
clearInterval(timerFunc);
};
//Display number of mines on the board
function numMines() {
mines = mineIdx.length;
document.querySelector('.mines').innerHTML = mines;
};
//Disable On Context Menu and place a flag on right click/control-click
document.oncontextmenu = function(e) {
e.target.setAttribute('style', 'background-image: url(https://i.imgur.com/5ONOFFi.png); background-size: cover;');
mineIdx.pop();
render();
return false;
};
//Sequence to randomize one of three failure messages
function youLose(min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
//Win message logic
function checkWinLose() {
if(winner === loser) {
timerStop();
document.getElementById('board').removeEventListener('click', tileSelect);
gameOver.setAttribute('style', 'visibility: visible;')
gameOver.innerHTML = lose[youLose(1,4)];
};
};
//Creating recursive 0 scan to open the void
function checkAround(x,y) {
x = Number(x);
y = Number(y);
const validSpots = [];
if(x > 0 && y > 0) validSpots.push([x - 1, y - 1]);
if(x > 0) validSpots.push([x - 1, y]);
if(x > 0 && y < 8) validSpots.push([x - 1, y + 1]);
if(y > 0) validSpots.push([x, y - 1]);
if(y < 8) validSpots.push([x, y + 1]);
if(x < 8 && y > 0) validSpots.push([x + 1, y - 1]);
if(x < 8) validSpots.push([x + 1, y]);
if(x < 8 && y < 8) validSpots.push([x + 1, y + 1]);
return validSpots;
};
function zeroVoid(clIdxRow,clIdxCol) {
// Return if this cell is already revealed
if (checked.some(arr => arr[0] === clIdxRow && arr[1] === clIdxCol)) return;
checked.push([clIdxRow,clIdxCol]);
if(board[clIdxRow][clIdxCol] > 0){
boardElem[clIdxCol][clIdxRow].innerText = board[clIdxRow][clIdxCol];
winBoard[clIdxRow][clIdxCol] = true;
return;
} else {
if(board[clIdxRow][clIdxCol] === 0) {
boardElem[clIdxCol][clIdxRow].setAttribute('style', 'background-color: rgba(39,38,52, .6)');
winBoard[clIdxRow][clIdxCol] = true;
let neighbors = checkAround(clIdxRow,clIdxCol);
// Recursively call zeroVoid
neighbors.forEach(n => zeroVoid(n[0], n[1]));
};
};
}; | 6b1f9a2b1b4bbb34cb469f612e2761642c7cc4f7 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | NaryxHaxns/Jabberwocky-Sweeper-Project-1 | e976635cc51a59fcebab9fb11158ecfab62f3189 | adc1db358e7e2c87ad837dc9795739b9048857a6 |
refs/heads/master | <file_sep>#ifndef TEXTONYMSLIB_H_INCLUDED
#define TEXTONYMSLIB_H_INCLUDED
using namespace std;
struct elemento {
string palavra;
string numero;
int textonyms;
};
//Cabezera das funçoes da biblioteca
int mostrarMenu();
bool finalizar();
void encherVetor(vector<elemento> &elementos, string nomeArquivo);
void obterNum(vector<elemento> &elementos);
void mostrarRelatorio(vector<elemento> &elementos, string &relatorio, string &arquivo_salvar);
void mostrarExemplos(vector<elemento> &elementos, string &arquivo_salvar, bool ordenar);
char mostrarPalavras(vector<elemento> &elementos,string &numero);
void maiusculas(string &palavra);
#endif // TEXTONYMSLIB_H_INCLUDED
<file_sep>/////////////////////////////INCLUDES
#include <iostream>
#include <string>
#include <windows.h>
#include <fstream>
#include <vector>
#include <algorithm>
#include <math.h>
//Input/output manipulation. É usada para modificar a estrutura da saida de resultados.
#include <iomanip>
//Biblioteca usada para gerar os arquivos com nomes baseados na data (ao estilo dos logs)
#include <ctime>
/////////////////////////////INCLUDES
/////////////////////////////DEFINES
//Definiçao do string do menu
#define menu "\n1--Relatorio de arquivo padrao\n\n2--Relatorio de arquivo proprio\n\n3--Mostrar combinaçoes com mais textonyms\n\n4--Buscar palavras por numero\n\n5--Obter textonyms de uma palavra (diccionario)\n\n0--Sair\n\n"
//Definiçao do tamaño do nome dos arquivos a salver e do formato deles
#define FORMATO_NOME "texttonyms_%Y%m%d_%H%M%S.txt"
#define TAMANHO_NOME 31
//Definiçao de um caracter padrao para inicializar as variaveis tipo char
#define CHAR_VACIO '_'
#define STRING_VACIO "_"
//Definiçao da string do relatorio
#define RELATORIO "Existem %d palavras em \"%s\" que podem ser representadas pelo mapeamento de teclas de digitos.\nEles requerem %d combinaçoes de digitos para representa-los.\nAs combinaçoes de digitos %d representam Textonyms.\n\n"
//Definiçao da string da URL do arquivo.
#define URL "http://www.puzzlers.org/pub/wordlists/unixdict.txt"
/////////////////////////////DEFINES
using namespace std;
//estrutura de dados que contem a palavra, o numero correspondente no teclado telefonico e o numero de textonyms dentro do arquivo.
struct elemento {
string palavra;
string numero;
int textonyms;
};
//estrutura de dados que contem cada letra e o numero correspondente no teclado telefonico.
struct letra {
char letra;
char num;
};
//array de estruturas de dados "letra" que contem todas as letras com o respectivo numero.
const letra letras[26] = {{'A','2'},{'B','2'},{'C','2'},{'D','3'},{'E','3'},{'F','3'},{'G','4'},{'H','4'},
{'I','4'},{'J','5'},{'K','5'},{'L','5'},{'M','6'},{'N','6'},{'O','6'},{'P','7'},
{'Q','7'},{'R','7'},{'S','7'},{'T','8'},{'U','8'},{'V','8'},{'W','9'},{'X','9'},
{'Y','9'},{'Z','9'}};
//Metodo para transformar uma palavra em maiusculas.
void maiusculas(string &palavra){
for(int i = 0; i<palavra.length();i++){
palavra.at(i) = toupper(palavra.at(i));
}
}
//Funçao que mostra o menu de opçoes inicial
int mostrarMenu(){
int opcao=-1;
//Enquanto o usuario nao escreva uma opçao valida o menu vai se mostrar uma e outra vez.
while(opcao<0 || opcao>5){
system("cls");
//Usamos a variavel definida 'menu'
cout << menu << endl;
cin >> opcao;
if(opcao<0 || opcao>5){
cout << "Inserir uma opcao valida (0-5)" << endl;
Sleep(2000);
}
}
return opcao;
}
//Funçao que obtem as palavras de um arquivo e enche o vetor de elementos com elas
void encherVetor(vector<elemento> &elementos, string nome){
vector<string> lista;
string aux;
elemento elem;
//enchemos um vetor de strings com todas as palavras do arquivo, linha a linha
ifstream arquivo(nome.c_str());
while (std::getline(arquivo, aux))
{
lista.push_back (aux);
}
//Usamos o metodo random_shuffle para embarajar o vetor de palavras
random_shuffle(lista.begin(), lista.end());
//Usamos uma variavel auxiliar 'elem' de tipo elemento para obter as palavras da lista e adicionamos ele ao vetor de elementos.
while (!lista.empty()){
elem.numero = "";
elem.textonyms = 1;
//back() extrai o conteudo da ultima posiçao
elem.palavra=lista.back();
//pop_back() elimina o objeto na ultima posiçao reduzindo o tamanho do vetor
lista.pop_back();
//push_back() insire um elemento no vetor na ultima posiçao.
elementos.push_back(elem);
}
}
//Funçao que devolve o unmero correspondente a uma palavra
string strToNum(string str){
string num;
//Por cada letra da palavra o loop vai acionar o numero correspondente à variavel num
for(int i = 0; i < str.length(); i++){
for(int j = 0; j < 26 ; j++){
if(toupper(str.at(i))==letras[j].letra){
num+=letras[j].num;
}
}
//comprobaçao de que sejam só letras (a-z, A-Z)
if(str.at(i)<65 || (str.at(i)>90 && str.at(i)<97) || str.at(i)>122){
//No caso achar um caracter nao valido, a string num se devolve vazia.
num = STRING_VACIO;
i=str.length();
}
}
return num;
}
//Metodo que adiciona os numeros correspondentes a cada palavra no vetor de elementos.
void obterNum(vector<elemento> &elementos){
system("cls");
cout << "Buscando textonyms..." << endl;
//Para cada elemento do vetor vamos chamar ao metodo strToNum() pasando a palavra para obter o numero.
for(int i = 0; i < elementos.size(); i++){
elementos.at(i).numero = strToNum(elementos.at(i).palavra);
//percorremos os elementos que ja tem numero e comprobamos as repetiçoes (dos que nao sao nulos '_')
for(int j = 0; j < i; j++){
if(elementos.at(i).numero == elementos.at(j).numero && elementos.at(j).numero!=STRING_VACIO){
//incrementamos em um a variavel textonyms dos dois elementos.
elementos.at(i).textonyms++;
elementos.at(j).textonyms++;
}
}
}
}
//Metodo para salvar num arquivo os exemplos mostrados no metodo mostrarExemplos().
void salvarExemplos(vector<string> resultado, string arquivo_salvar){
ofstream arquivoSalvar;
//No caso o parametro arquivo_salvar esteja vazio criamos um novo arquivo
if(arquivo_salvar==STRING_VACIO){
//Formatamos o nome do arquivo com a data e hora do momento da criaçao do arquivo segundo o formato definido acima.
char nome[TAMANHO_NOME];
time_t timestamp = time(0);
strftime(nome, sizeof(nome), FORMATO_NOME, localtime(×tamp));
arquivoSalvar.open (nome);
//No caso ja tenhamos um arquivo_salvo com o relatorio do ponto 1, abrimos ele em modo append para adicionar linhas ao final.
}else{
arquivoSalvar.open(arquivo_salvar.c_str(), ios::app);
arquivoSalvar << "\n\nExemplos:\n\n";
}
//Loop para adicionar todas as linhas do vetor resultado.
for(int i=0;i<resultado.size();i++){
arquivoSalvar << resultado.at(i) << endl;
}
arquivoSalvar.close();
}
//Metodo para mostrar o relatorio mostrado no metodo mostrarRelatorio.
string salvarRelatorio(string &relatorio){
ofstream arquivoSalvar;
//Formatamos o nome do arquivo com a data e hora do momento da criaçao do arquivo segundo o formato definido acima.
char nome[TAMANHO_NOME];
time_t timestamp = time(0);
strftime(nome, sizeof(nome), FORMATO_NOME, localtime(×tamp));
arquivoSalvar.open (nome);
//Escrevemos as linhas que contem a string relatorio que vem como parametro.
arquivoSalvar << "\n\n" << relatorio<< endl;
arquivoSalvar.close();
return nome;
}
//Metodo que cria e mostra o relatorio requerido na tarefa.
void mostrarRelatorio(vector<elemento> &elementos, string &relatorio, string &arquivo_salvar){
int rel0=0;
double rel3=0;
vector<string> strNumsUnique;
char salvar = CHAR_VACIO;
system("cls");
cout << "Mostrando relatorio..." << endl;
for(int i = 0; i < elementos.size(); i++){
//Os elementos que tem um numero nao nulo sao os que podemos mostrar com teclado telefonico (só caracteres a-z, A-Z)
if(elementos.at(i).numero!= STRING_VACIO){
rel0++;
//para saber a quantidade de numeros que formam textonyms temos que achar os elementos com a variavel textonyms maior que 1. O problema e que todos os textonyms tem armazenado nessa variavel o numero total (p.e. palavra abg - num. 224 - textonyms 2 || palavra aci - num. 224 - textonyms 2). A soluçao foi somar 1/textonyms para que no final tenhamos quantidade de numeros sem repetiçao.
if(elementos.at(i).textonyms > 1){
rel3 += (1/(double)elementos.at(i).textonyms);
}
//enchemos o vetor strNumsUnique para ter todos os numeros diferentes (tenham ou nao mais de um textonym). Para isso percorremos o vetor strNumsUnique e se chegamos ao fim (strNumsUnique.end()) significa que nao existe ese elemento e entao adicionamos ele.
if(find(strNumsUnique.begin(), strNumsUnique.end(), elementos.at(i).numero) == strNumsUnique.end()){
strNumsUnique.push_back(elementos.at(i).numero);
}
}
}
////////////////////////////////////////DEBUG
// ofstream arquivoSalvar;
// arquivoSalvar.open ("prova.txt");
// for(int i=0;i<elementos.size();i++){
// arquivoSalvar <<"\t"<<left<<setw(20)<<elementos.at(i).palavra<<setw(20)<<elementos.at(i).numero<<right<<setw(20)<<setprecision(3)<<elementos.at(i).textonyms<<"--"<< endl;
// }
// arquivoSalvar.close();
////////////////////////////////////////DEBUG
system("cls");
//Usamos um array de char de 500 posiçoes para armazenar nele o string final do relatorio formatado com sprintf().
char buffer[500];
sprintf(buffer,RELATORIO,rel0,URL,strNumsUnique.size(),(int)round(rel3));
//convertemos o buffer à string.
relatorio = string(buffer);
cout << endl;
//Mostramos o relatorio.
cout << relatorio;
//Perguntamos ao usuario se quer salvar o arquivo (o loop é necesario para que o usuario so possa marcar S ou N).
while(salvar!= 'S' && salvar!= 's' && salvar!= 'N' && salvar!= 'n'){
cout << "Voce quer salvar o relatorio? (S/N)" << endl;
cin >> salvar;
}
if(salvar == 'S' || salvar == 's'){
arquivo_salvar = salvarRelatorio(relatorio);
}
}
//Metodo para ordenar de maior a menor os elementos do vetor em referencia ao numero de textonyms de cada numero. Usamos o metodo simples bubble sort.
void ordenarNumeros(vector<elemento> &elementos){
elemento aux;
int n = elementos.size();
int m = 0;
cout << "Ordenando..." << endl;
while(n>0){
m=0;
//Para cada elemento de 1 a n comprobamos se o anterior e menor. No caso de ser certo trocamos eles.
for(int i = 1; i < n; i++){
if(elementos.at(i-1).textonyms < elementos.at(i).textonyms){
aux = elementos.at(i-1);
elementos.at(i-1) = elementos.at(i);
elementos.at(i) = aux;
m = i;
}
}
//O ultimo valor de m significa que o resto dos valores ja tao ordenados, entao reduzimos o valor de n e fazemos outra pasada.
n = m;
}
}
//metodo que mostra os exemplos de textonyms que tem cada numero.
void mostrarExemplos(vector<elemento> &elementos, string &arquivo_salvar, bool ordenar){
vector<string> numeros;
vector<string> resultado;
string aux;
char cont = CHAR_VACIO;
char salvar = CHAR_VACIO;
system("cls");
cout << "Mostrando exemplos\n" << endl;
//No caso recebamos o parametro ordenar == true, chamamos ao metodo que ordena o vetor de maior a menor.
if(ordenar){
ordenarNumeros(elementos);
}
//Vamos encher um vetor de strings "numero" com os numeros diferentes que tem mais de um textonym
for(int i = 0; i < elementos.size(); i++){
//Usamos o metodo find() do mesmo modo que em casos anteriores.
if(elementos.at(i).textonyms > 1 && (find(numeros.begin(), numeros.end(), elementos.at(i).numero) == numeros.end())){
numeros.push_back(elementos.at(i).numero);
}
}
for(int j = 0; j < numeros.size(); j++){
//Para cada numero em "numeros" mostramos ele e vamos formando a string aux com o metodo append, que adiciona texto ao final de uma string.
cout <<left<<setw(10)<< numeros.at(j) <<left<<setw(5) <<" --> ";
aux = numeros.at(j);
aux.append("\t\t-->\t\t");
//Percorremos o vetor "elementos" na busca das palavras que compartilham o numero correspondente do for anterior.
for(int k = 0; k < elementos.size(); k++){
//Quando achar uma palavra nova, mostramos ela e adicionamos ela a string aux.
if(elementos.at(k).numero == numeros.at(j)){
cout << left<<setw(10)<<elementos.at(k).palavra;
aux.append(elementos.at(k).palavra);
aux.append("\t\t");
}
}
cout << endl;
//adicionamos a string aux ao vetor resultado para usar ele depois se o usuario quer salvar os exemplos.
aux.append("\n\n");
resultado.push_back(aux);
aux="";
//Usamos o loop já usado no exercicio anterior para perguntar ao usuario se quer continuar mostrando os dados.
if(j%100==0 && j!=0 && cont!='F' && cont!='f'){
cont=CHAR_VACIO;
while(cont!='S' && cont!='s' && cont!='N' && cont!='n' && cont!='F' && cont!='f'){
cout << "\n\nContinuar? (S/N. F para continuar ate o fim.)" << endl;
cin >> cont;
if(cont == 'N' || cont == 'n'){
j = numeros.size();
}else if(cont == 'S' || cont == 's' || cont == 'F' || cont == 'f'){
//Se o usuario decidir continuar mostramos uma cabezera.
cout <<"\n\n\CONTINUACAO\n\n"<< endl;
}
}
}
}
//Perguntamos ao usuario se quer salvar os exemplos no arquivo.
while(salvar!= 'S' && salvar!= 's' && salvar!= 'N' && salvar!= 'n'){
cout << "Voce quer salvar os exemplos? (S/N)" << endl;
cin >> salvar;
}
if(salvar == 'S' || salvar == 's'){
//Caso queramos salvar o arquivo, pasamos ao metodo salvarExemplos() o vetor resultado que temos ido criando e contem o mesmo que tem sido mostrado na tela e o nome do arquivo a ser salvo, que pode estar vazio ou nao.
salvarExemplos(resultado,arquivo_salvar);
}
}
//Metodo para mostrar as Palavras que sao textonyms de um numero.
char mostrarPalavras(vector<elemento> &elementos,string &numero){
char buscar = CHAR_VACIO;
int cont = 0;
int pos = 0;
system("cls");
cout << "\n\nTexttonyms do numero " << numero << ": ";
//Percorremos todo o vetor elementos
for(int i = 0; i < elementos.size(); i++){
//Quando achar um numero igual ao que o usuario inseriu mostramos a palavra e incrementamos o contador. tambem modificamos o valor da variavel pos.
if(elementos.at(i).numero == numero){
cout << elementos.at(i).palavra << " ";
cont++;
pos = i;
}
}
//No caso de nao ter nenhum textonym ou que o unico que tiver esteja na ultima posiçao do vetor (para isso usamos a variavel pos), onde se encontra o elemento que nós adicionamos para fazer a busca e nao tem que ser contado, entao mostramos o seguinte texto.
if(cont == 0 || (cont == 1 && pos == elementos.size()-1)) cout << "Nao tem nenhum textonym da busqueda no arquivo.";
cout << "\n" << endl;
//Usamos o seguinte loop para perquntar ao usuario se deseja buscar outro numero ou palavra.
while(buscar != 'S' && buscar != 's' && buscar != 'N' && buscar != 'n'){
cout << "Deseja buscar mais textonyms? (S/N)" << endl;
cin >> buscar;
}
return buscar;
}
//funçao para perguntar ao usuario se ele quer finalizar o apicativo o mostrar o menu inicial outra vez
bool finalizar(){
char fim = CHAR_VACIO;
//Se pergunta ao usuario se que sair e devolve um valor booleano para a funçao main
while(fim!='S' && fim!='s' && fim!='N' && fim!='n'){
cout << "\n\n\nDeseja finalizar o programa? (S/N)" << endl;
cin >> fim;
}
if(fim=='S' || fim == 's'){
return true;
}else{
return false;
}
}
<file_sep>/*
* Questão 17.
*
* Ao inserir texto no teclado digital de um telefone, é posivel que uma determinada
* combinaçao de digitos corresponda a mais de uma palavra. Tais sao chamados Textonyms.
* Supondo que as teclas de digito sao mapeadas para letras da seguinte maneira:
*
* 2 --> ABC
* 2 --> DEF
* 2 --> GHI
* 2 --> JKL
* 2 --> MNO
* 2 --> PQRS
* 2 --> TUV
* 2 --> WXYZ
*
* Tarefa:
* Escreva um programa que encontre Textonyms em uma lista de palavras como do arquivo
* listaDePalavras.txt (http://www.puzzlers.org/pub/wordlists/unixdict.txt). A tarefa
* deve produzir um relatorio:
*
* Existem #0 palavras em #1 que podem ser representadas pelo mapeamento de teclas de digitos.
* Eles requerem #2 combinaçoes de digitos para representa-los. As combinaçoes de digitos #3
* representam Textonyms.
*
* Onde:
* a) #0 é o numero de palavras na lista que pode ser representado pelo mapeamento de teclas
* de digitos.
* b) #1 é a URL da lista de palavras que está sendo usada.
* c) #2 é o numero de combinaçoes de digitos necessarias para representar as palavras em #0.
* d) #3 é o numero de #2 que representa mais de uma palavra.
*
* A seu criterio, mostre alguns exemplos de sua soluçao exibindo Textonyms.
* POR EXEMPLO:
* 2748424767 --> Briticisms, criticas
*
*
*
* 1-relatorio de arquivo padrao
* 2-relatorio de arquivo proprio
* 3-mostrar combinaçoes com mais textonyms de um arquivo
* 4-Buscar palavras por numero num arquivo
* 5-Obter textonyms de uma palavra (diccionario)
* 0-Sair
* Instruçoes:
* 1º abrir o projeto da biblioteca e compilar ela.
* 2º Sttings -> Compiler -> Linker settings -> Add -> Rota da biblioteca (arquivo .a)
* 3º Compilar e executar o programa
*/
/////////////////////////////INCLUDES
#include <iostream>
#include <string>
#include <windows.h>
#include <fstream>
#include <vector>
#include <algorithm>
//Input/output manipulation. É usada para modificar a estrutura da saida de resultados.
#include <iomanip>
//Biblioteca usada para gerar os arquivos com nomes baseados na data (ao estilo dos logs)
#include <ctime>
//Incluimos nossa biblioteca particular
#include "textonymsLIB.h"
/////////////////////////////INCLUDES
/////////////////////////////DEFINES
//Definiçao do string do menu
#define menu "\n1--Relatorio de arquivo padrao\n\n2--Relatorio de arquivo proprio\n\n3--Mostrar combinaçoes com mais textonyms de um arquivo\n\n4--Buscar palavras por numero num arquivo\n\n5--Obter textonyms de uma palavra (diccionario)\n\n0--Sair\n\n"
//Definiçao do tamaño do nome dos arquivos a salver e do formato deles
#define FORMATO_NOME "texttonyms_%Y%m%d_%H%M%S.txt"
#define TAMANHO_NOME 31
//Definiçao de um caracter padrao para inicializar as variaveis tipo char
#define CHAR_VACIO '_'
#define STRING_VACIO "_"
/////////////////////////////DEFINES
using namespace std;
//funçao que mostra o relatorio de um arquivo padrao requerido nas tarefas do exercicio.
bool opcao1(){
vector<elemento> elementos;
string relatorio;
string arquivo_salvar;
char exemplo = CHAR_VACIO;
//chamamos ao metodo encherVetor() para obter todas as palavras do arquivo
encherVetor(elementos,"textonyms.txt");
////////////////////////////////////////////DEBUG
//encherVetor(elementos,"textonyms_short.txt");
////////////////////////////////////////////DEBUG
//chamamos ao metodo obterNum() para obter os numeros referentes a cada palavra.
obterNum(elementos);
//chamamos ao metodo mostrarRelatorio() para mostrar o relatorio requerido. pasamos para ele o vetor de elementos, um string relatorio para armazenar ele e uma string para armazenar o nome do arquivo no caso que quiser ser salvo.
mostrarRelatorio(elementos,relatorio,arquivo_salvar);
//Loop que pergunta se o usuario quer mostrar eemplos de textonyms ou nao.
while(exemplo!= 'S' && exemplo!= 's' && exemplo!= 'N' && exemplo!= 'n'){
cout << "Voce quer mostrar exemplos de textonyms? (S/N)" << endl;
cin >> exemplo;
}
if(exemplo == 'S' || exemplo == 's'){
//chamamos ao metodo mostrarExemplos() e pasamos o vetor de elementos, o nome do arquivo no qual salvamos o relatorio e "false" que significa que nao queremos que os exemplos sejam ordenados.
mostrarExemplos(elementos,arquivo_salvar,false);
}
return finalizar();
}
//O mesmo que a opçao 1 pero com um arquivo indicado pelo usuario.
bool opcao2(){
vector<elemento> elementos;
string relatorio;
string arquivo_salvar;
char exemplo = CHAR_VACIO;
int erro = 0;
string nome_arquivo;
system("cls");
//Loop para nos asegurar que o usuario insire um arquivo existente.
while(erro==0){
cout << "Escreva o path de seu arquivo:" << endl;
cin >> nome_arquivo;
ifstream ifs(nome_arquivo.c_str());
if(!ifs.is_open()){
cout << "Erro ao abrir o arquivo!" << endl;
erro=0;
}
else{
erro=1;
ifs.close();
}
}
encherVetor(elementos,nome_arquivo.c_str());
/////////////////////////////////////////////////DEBUG
//encherVetor(elementos,"textonyms_short.txt");
/////////////////////////////////////////////////DEBUG
obterNum(elementos);
mostrarRelatorio(elementos,relatorio,arquivo_salvar);
while(exemplo!= 'S' && exemplo!= 's' && exemplo!= 'N' && exemplo!= 'n'){
cout << "Voce quer mostrar exemplos de textonyms? (S/N)" << endl;
cin >> exemplo;
}
if(exemplo == 'S' || exemplo == 's'){
mostrarExemplos(elementos,arquivo_salvar,false);
}
return finalizar();
}
//Essa funçao é muito parecida as anteriores só que nao mostra o relatorio, só os eemplos.
bool opcao3(){
vector<elemento> elementos;
int erro = 0;
string nome_arquivo;
string arquivo_salvar = STRING_VACIO;
system("cls");
while(erro==0){
cout << "Escreva o path de seu arquivo:" << endl;
cin >> nome_arquivo;
ifstream ifs(nome_arquivo.c_str());
if(!ifs.is_open()){
cout << "Erro ao abrir o arquivo!" << endl;
erro=0;
}
else{
erro=1;
ifs.close();
}
}
encherVetor(elementos,nome_arquivo.c_str());
obterNum(elementos);
//Neste caso podemos ver que pasamos a string arquivo_salvar vazia o que vai gerar um arquivo novo. tambem pasamos o ultimo argumento como "true" para o programa ordenar os elementos.
mostrarExemplos(elementos,arquivo_salvar, true);
return finalizar();
}
//Funçao que recebe um numero e mostra as palavras que sao textonyms em relaçao a esse numero.
bool opcao4(){
vector<elemento> elementos;
int erro = 0;
string nome_arquivo;
string numero = STRING_VACIO;
char buscar = CHAR_VACIO;
system("cls");
while(erro==0){
cout << "Escreva o path de seu arquivo:" << endl;
cin >> nome_arquivo;
ifstream ifs(nome_arquivo.c_str());
if(!ifs.is_open()){
cout << "Erro ao abrir o arquivo!" << endl;
erro=0;
}
else{
erro=1;
ifs.close();
}
}
cout << "Preparando arquivo..." << endl;
system("cls");
encherVetor(elementos,nome_arquivo.c_str());
////////////////////////////////////////////////DEBUG
//encherVetor(elementos,"textonyms_short.txt");
////////////////////////////////////////////////DEBUG
obterNum(elementos);
//loop para repeter a busca de palavas tantas vezes como o usuario quiser.
while(buscar != 'N' && buscar != 'n'){
system("cls");
//Loop que asegura que o numero tem um formato valido (só numeros. No caso o usuario escreva mais de um nunmero separados por espaços, o programa só vai pegar o primeiro).
while (numero == STRING_VACIO || numero == ""){
cout << "Escreva um numero valido." << endl;
cin >> numero;
for(int i = 0; i < numero.length(); i++){
if(numero.at(i)<48 || numero.at(i)>57) numero = STRING_VACIO;
}
}
//Chamamos a funçao mostrarPalavras() pasando o vetor de elementos e o numero pelo qual a busca vai ser realizada.
buscar = mostrarPalavras(elementos,numero);
//"esvaziamos" a variavel numero para inserir um novo numero.
numero = STRING_VACIO;
}
return finalizar();
}
//Funçao que recebe uma palavra e mostra todas as palavras que sao textonyms dela dentro de um dicionario.
bool opcao5(){
vector<elemento> elementos;
string palavra = STRING_VACIO;
elemento novo;
char buscar = CHAR_VACIO;
//Obtemos as palavras do dicionario.
encherVetor(elementos,"dicionario30000.txt");
while(buscar != 'N' && buscar != 'n'){
system("cls");
//Loop para asegurar que a palavra tem o formato correto.
while(palavra == STRING_VACIO){
cout << "Escreva uma palavra para buscar textonyms." << endl;
cin >> palavra;
for(int i = 0; i < palavra.length(); i++){
if(palavra.at(i)<65 || (palavra.at(i)>90 && palavra.at(i)<97) || palavra.at(i)>122) palavra = STRING_VACIO;
}
}
// inicializamos as variaveis do elemento auxiliar "novo".
novo.numero=STRING_VACIO;
novo.textonyms=0;
//Convertemos a palavra a maiusculas
maiusculas(palavra);
novo.palavra = palavra;
//Botamos o elemento novo no final do vetor.
elementos.push_back(novo);
obterNum(elementos);
//Chamamos ao metodo mostrarPalavras() pasando o vetor de elementos e o numero do ultimo elemento (que contém nossa palavra).
buscar = mostrarPalavras(elementos,elementos.back().numero);
//"Esvaciamos" a string palavra e tiramos do vetor o elemento auxiliar "novo".
palavra = STRING_VACIO;
elementos.pop_back();
}
return finalizar();
}
//Funçao main
int main(){
bool finalizar = false;
//Mostramos a introduçao
cout << "Linguagem de programacao" << endl;
cout << "Questao 17. Textonyms." << endl;
cout << "<NAME>" << endl;
cout << "<NAME>" << endl;
cout << "2017/1\n\n" << endl;
system("pause");
//enquanto a funçao finalizar() nao devolva true, vamos chamar a funçao que mostra o menu.
while(!finalizar){
switch(mostrarMenu()){
case(0):
finalizar = true;
break;
case(1):
finalizar = opcao1();
break;
case(2):
finalizar = opcao2();
break;
case(3):
finalizar = opcao3();
break;
case(4):
finalizar = opcao4();
break;
case(5):
finalizar = opcao5();
break;
default:
finalizar = true;
break;
};
}
return 0;
}
| e59fcf1f821253a5cec4fab773d78eb3d031ed46 | [
"C++"
]
| 3 | C++ | Thenasker/TEXTOMYMS | d7ac053e7e61399d385fb6caaf5a5f9ae97f4230 | 6f212200d6443d9a64a1bd4e3d0315db5db5502b |
refs/heads/main | <repo_name>Styro457/google-trends<file_sep>/index.js
import Express from "express";
import cors from "cors";
import { getAverageWordSearches } from "./google-trends.js";
const app = Express();
app.use(cors({
origin: '*'
}));
app.get("/average-word-search/:word", (req, res) => {
getAverageWordSearches(req.params.word).then(result => {
console.log(result);
if(isNaN(result))
result = 0;
res.send(result.toString());
});
})
app.listen(process.env.PORT || 3000);<file_sep>/README.md
<img align="left" width="80" height="50" src="https://i.pinimg.com/originals/8e/24/03/8e24031175b855889b54bce691617263.png" alt="Icon">
# Google Trends API Server
**Public NodeJS Server used to retrive google trends data directly on client-side in order to avoid cors restrictions**<br>
using the [google-trends-api](https://www.npmjs.com/package/google-trends-api) package
Hosten on [Heroku](https://herokuapp.com)
- Recommended mainly for small projects
## How to use
As of right now, the only avaliable endpoint is /average-word-search<br>
I plan on adding different ones in the future as well as parameters for all of them
## /average-word-search
Returns the number of daily average searches for a word worldwide from 2016-01-01 until the present
### Syntax:
https://google-trends-average.herokuapp.com/average-word-search/{word}
### Example:
```js
const word = "apple";
fetch("https://google-trends-average.herokuapp.com/average-word-search/" + word).then(response => {
return response.json();
}).then(data => {
console.log("Average searches for the word apple:" + data);
})
```
```
Average searches for the word apple: 44.12048192771084
```
<file_sep>/google-trends.js
import GoogleTrendsAPI from "google-trends-api";
export function getAverageWordSearches(word) {
return new Promise((resolve) => {
GoogleTrendsAPI.interestOverTime({keyword: word, startTime: new Date('2016-01-01')})
.then(function (results) {
const data = JSON.parse(results);
let averageSearches = 0;
let searches = 0;
for (let x in data.default.timelineData) {
averageSearches += data.default.timelineData[x].value[0];
searches++;
}
averageSearches /= searches;
resolve(averageSearches);
})
/* .catch(function(err){
console.error('Oh no there was an error', err);
})*/;
})
} | 05464358a5cf4dfd5d61b7262f58fe40a089fd04 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | Styro457/google-trends | b3c802732903627bce68860f6ddf39c06cf92b03 | ff8816ef7c189351321773df4545c3e27bfbc5b7 |
refs/heads/main | <repo_name>tech-akash/Blood-Bank1<file_sep>/plasmaapp/migrations/0010_auto_20210812_2123.py
# Generated by Django 3.2.6 on 2021-08-12 21:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0009_auto_20210812_2117'),
]
operations = [
migrations.AlterField(
model_name='accept',
name='status',
field=models.CharField(blank=True, choices=[('Pending', 'Pending'), ('Accepted', 'Accepted'), ('GotIt', 'GotIt'), ('Rejected', 'Rejected')], default='Pending', max_length=20, null=True, verbose_name='Status'),
),
migrations.AlterField(
model_name='donate',
name='status',
field=models.CharField(blank=True, choices=[('Pending', 'Pending'), ('Accepted', 'Accepted'), ('Donated', 'Donated'), ('Rejected', 'Rejected')], default='Pending', max_length=20, null=True, verbose_name='Status'),
),
]
<file_sep>/plasmaapp/models.py
from django.db import models
from django.db.models.deletion import CASCADE
from django.db.models.enums import Choices
from django.contrib.auth.models import User
# Create your models here.
class Donate(models.Model):
name=models.CharField( '<NAME> Donar',max_length=100,null=False)
address=models.CharField('Address',max_length=200,null=False)
phoneno=models.CharField('Phone Number',max_length=10,null=False)
age=models.IntegerField('Age',null=False)
GENDER=(('M','Male'),
('F','Female'),
('T','Trans'))
gender=models.CharField('Gender',max_length=1,choices=GENDER,null=False)
BLOODGROUP=(
('A+','A+'),
('A-','A-'),
('O+','O+'),
('O-','O-'),
('B+','B+'),
('B-','B-'),
('AB-','AB-'),
('AB+','AB+')
)
bloodgroup=models.CharField('Blood Group',max_length=3,choices=BLOODGROUP,null=False)
dayofdonate=models.DateField('Day of Donating',null=True,blank=True)
STATUS=(
('Pending','Pending'),
('Accepted','Accepted'),
('Donated','Donated'),
('Rejected','Rejected')
)
status=models.CharField('Status',choices=STATUS,default='Pending',max_length=20,null=True,blank=True)
def __str__(self):
return self.name
class Accept(models.Model):
name=models.CharField( max_length=100,null=False)
address=models.CharField('Address',max_length=200,null=False)
phoneno=models.CharField('Phone Number',max_length=10,null=False)
age=models.IntegerField('Age',null=False)
GENDER=(('M','Male'),
('F','Female'),
('T','Trans'))
gender=models.CharField('Gender',max_length=1,choices=GENDER,null=False)
BLOODGROUP=(
('A+','A+'),
('A-','A-'),
('O+','O+'),
('O-','O-'),
('B+','B+'),
('B-','B-'),
('AB-','AB-'),
('AB+','AB+')
)
bloodgroup=models.CharField('Blood Group',max_length=3,choices=BLOODGROUP,null=False)
dayofaccept=models.DateField('Day of Accepting',null=True,blank=True)
STATUS=(
('Pending','Pending'),
('Accepted','Accepted'),
('GotIt','GotIt'),
('Rejected','Rejected')
)
status=models.CharField('Status',choices=STATUS,default='Pending', max_length=20,null=True,blank=True)
def __str__(self):
return self.name
class Customer(models.Model):
user=models.OneToOneField(User,null=True,blank=True,on_delete=CASCADE)
username=models.CharField('Username',max_length=200,primary_key=True)
name=models.CharField( max_length=100,null=True,blank=True)
email=models.EmailField('Email',null=True,blank=True,default='<EMAIL>')
address=models.CharField('Address',max_length=200,null=True,blank=True)
phoneno=models.CharField('Phone Number',max_length=10,null=True,blank=True)
age=models.IntegerField('Age',null=True,blank=True)
prescription=models.ImageField(null=True,blank=True)
GENDER=(('M','Male'),
('F','Female'),
('T','Trans'))
gender=models.CharField('Gender',max_length=1,choices=GENDER,null=True,blank=True)
BLOODGROUP=(
('A+','A+'),
('A-','A-'),
('O+','O+'),
('O-','O-'),
('B+','B+'),
('B-','B-'),
('AB-','AB-'),
('AB+','AB+')
)
bloodgroup=models.CharField('Blood Group',max_length=3,choices=BLOODGROUP,null=True,blank=True)
dayofaccept=models.DateField('Day of Accepting',null=True,blank=True)
NEED=(('None','None'),
('Acceptor','Acceptor'),
('Donator','Donator'),)
need=models.CharField('Need',choices=NEED,default='None',null=True,blank=True,max_length=20)
STATUS=(
('Pending','Pending'),
('Accepted','Accepted'),
('GotIt','GotIt'),
('Rejected','Rejected')
)
status=models.CharField('Status',choices=STATUS,default='Pending', max_length=20,null=True,blank=True)
<file_sep>/plasmaapp/migrations/0011_customer.py
# Generated by Django 3.2.6 on 2021-08-13 17:12
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('plasmaapp', '0010_auto_20210812_2123'),
]
operations = [
migrations.CreateModel(
name='Customer',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=100, null=True)),
('address', models.CharField(blank=True, max_length=200, null=True, verbose_name='Address')),
('phoneno', models.CharField(blank=True, max_length=10, null=True, verbose_name='Phone Number')),
('age', models.IntegerField(verbose_name='Age')),
('gender', models.CharField(blank=True, choices=[('M', 'Male'), ('F', 'Female'), ('T', 'Trans')], max_length=1, null=True, verbose_name='Gender')),
('bloodgroup', models.CharField(choices=[('A+', 'A+'), ('A-', 'A-'), ('O+', 'O+'), ('O-', 'O-'), ('B+', 'B+'), ('B-', 'B-'), ('AB-', 'AB-'), ('AB+', 'AB+')], max_length=3, verbose_name='Blood Group')),
('dayofaccept', models.DateField(blank=True, null=True, verbose_name='Day of Accepting')),
('need', models.CharField(blank=True, choices=[('Acceptor', 'Acceptor'), ('Donator', 'Donator')], max_length=20, null=True, verbose_name='Need')),
('status', models.CharField(blank=True, choices=[('Pending', 'Pending'), ('Accepted', 'Accepted'), ('GotIt', 'GotIt'), ('Rejected', 'Rejected')], default='Pending', max_length=20, null=True, verbose_name='Status')),
('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>/plasmaapp/migrations/0008_auto_20210812_2114.py
# Generated by Django 3.2.6 on 2021-08-12 21:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0007_auto_20210812_1809'),
]
operations = [
migrations.AlterField(
model_name='accept',
name='dayofaccept',
field=models.DateField(null=True, verbose_name='Day of Accepting'),
),
migrations.AlterField(
model_name='accept',
name='name',
field=models.CharField(max_length=100),
),
migrations.AlterField(
model_name='donate',
name='dayofdonate',
field=models.DateField(null=True, verbose_name='Day of Donating'),
),
]
<file_sep>/plasmaapp/admin.py
from django.contrib import admin
from .models import Accept,Donate,Customer
# Register your models here.
admin.site.register(Accept)
admin.site.register(Donate)
admin.site.register(Customer)<file_sep>/plasmaapp/templates/customerpage.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
.container{
margin: 2% auto;
text-align: center;
color: white;
height: 500px;
padding: 1%;
}
span{
width: 300px;
}
.main{
text-align: center;
padding-top: 40px ;
background-color: #65ca12;
height: 500px;
}
#id_name{
color: white;
text-align: center;
background-color: #65ca12;
border: 2px solid green;
border-radius: 15px;
width: 250px;
padding: 5px 10px;
}
#id_age{
color: white;
text-align: center;
background-color: #65ca12;
border: 2px solid green;
border-radius: 15px;
width: 250px;
padding: 5px 10px;
}
#id_phoneno{
color: white;
text-align: center;
background-color: #65ca12;
border: 2px solid green;
border-radius: 15px;
width: 250px;
padding: 5px 10px;
}
#id_address{
color: white;
text-align: center;
background-color: #65ca12;
border: 2px solid green;
border-radius: 15px;
width: 250px;
padding: 5px 10px;
}
#id_gender{
color: white;
text-align: center;
background-color: #65ca12;
border: 2px solid green;
border-radius: 15px;
width: 250px;
padding: 5px 10px;
}
.btn{
color: white;
text-align: center;
background-color: #65ca12;
border: 2px solid green;
width: 250px;
}
.btn:hover{
color: green;
background-color: white;
}
.table{
text-align: center;
}
.side{
padding-top: 40px ;
margin-right: 20px;
background-color: #65ca12;
height: 500px;
}
/* .vl{
height: 600px;
border: 1px solid white;
position: absolute;
top: 0;
left: 495px;
} */
.navbar{
background-color: #65ca12;
}
.nav-link{
font-size: 20px;
color: white;
}
.navbar-brand{
color: white;
}
a:hover{
color: green;
}
</style>
<title>Hello, world!</title>
</head>
<body>
<nav class="navbar navbar-expand-lg ">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active mr-5">
<a class="nav-link" href="{%url 'home'%}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item mr-4">
<a class="nav-link" href="{%url 'logout'%}">Logout</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<!-- <div class="vl"></div> -->
<div class="row">
<div class="col-4 side">
{%if not need == "None" %}
<h1>Status : {{status}}</h1>
{%if need == "Donator"%}
<h3>You Are Awesome</h3>
{% if status == "Pending"%}
<!-- <p>Your are doing a really great work for your country your help will save someone life</p> -->
<h4>Will take some time in verfication!</h4>
<h4>When ever the verfication finishes we will provide you dates where you can donate blood</h4>
{%elif status == "Accepted"%}
<h4>Thanks For your Interest</h4>
<h4>Your Blood Donation Appointment is fixed on {{date}}</h4>
{%elif status == "GotIt"%}
<h4>Thank You for donating Blood</h4>
<h4>Take Care!</h4>
{%else%}
<h4>Your Request is Rejected due to some reasons</h4>
<h4>Please fill the form with correct details</h4>
{% endif %}
{%else%}
<h3>You will be fine</h3>
{% if status == "Pending"%}
<!-- <p>Your are doing a really great work for your country your help will save someone life</p> -->
<h4>Will take really short time in verfication!</h4>
<h4>Once the verfication finishes we will provide you dates where you can accept blood</h4>
{%elif status == "Accepted"%}
<h4>Your Request is Accepted</h4>
<h4>Your Appointment is fixed on {{date}}</h4>
{%elif status == "GotIt"%}
<h4>Get Well Soon!</h4>
<h4>Take Care!</h4>
{%else%}
<h4>Your Request is Rejected due to some reasons</h4>
<h4>Please fill the form with correct details</h4>
<p>Fill the form to Donate/Accept Blood <a href="{%url 'formfill' %}">Go Ahead</a></p>
{% endif %}
{%endif%}
{%else%}
<h2>If You are safe Fine Donate Blood to save someones life</h2>
<h2>OR</h2>
<h2>If You need blood </h2>
<p>Fill the form to Donate/Accept Blood <a href="{%url 'formfill' %}">Go Ahead</a></p>
{%endif%}
</div>
<div class="col-7 main">
<h1>
Profile
</h1>
<form method="POST">{% csrf_token %}
<table class="table">
<tr>
<td>
Name :
</td>
<td>
{{form.name}}
</td>
</tr>
<tr>
<td>
Age :
</td>
<td>
{{form.age}}
</td>
</tr>
<tr>
<td>
Adddress :
</td>
<td>
{{form.address}}
</td>
</tr>
<tr>
<td>
Phone Number :
</td>
<td>
{{form.phoneno}}
</td>
</tr>
<tr>
<td>
Gender :
</td>
<td>
{{form.gender}}
</td>
</tr>
</table>
<div style="display: none;">
{{form.dayofaccept}}
{{form.bloodgroup}}
{{form.status}}
{{form.need}}
</div>
<!-- <div class="name"> <span>Name :</span>{{form.name}}</div>
<div class="age"><span>Age : </span>{{form.age}}</div>
<div class="Address"><span>Adddress : </span>{{form.address}}</div>
<div class="phoneno"><span>Phone Number : </span>{{form.phoneno}}</div>
<div class="gender"><span>Gender : </span>{{form.gender}}</div>
<div class="bloodgrp"><span>Blood Group</span>{{form.bloodgrp}}</div> -->
<input type="submit" value="Update" class="btn">
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
<file_sep>/plasmaapp/migrations/0017_customer_prescription.py
# Generated by Django 3.2.6 on 2021-08-16 19:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0016_customer_email'),
]
operations = [
migrations.AddField(
model_name='customer',
name='prescription',
field=models.ImageField(null=True, upload_to=''),
),
]
<file_sep>/plasmaapp/views.py
from django.shortcuts import redirect, render
from .forms import AcceptorForm,DonatorForm,CustomerForm,SignUpform
from .models import Accept,Donate,Customer
# Create your views here.
from django.contrib.auth.forms import UserCreationForm, UsernameField
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .decorators import un_authenticated,allowed_user
from django.contrib.auth.models import Group
from django.contrib import messages
import datetime
from django.core.mail import BadHeaderError, send_mail
# @un_authenticated
# def signuppage(request):
# form=UserCreationForm()
# if request.method=='POST':
# form=UserCreationForm(request.POST)
# if form.is_valid():
# user=form.save()
# username=request.POST.get('username')
# print(username)
# group=Group.objects.get(name='customer')
# user.groups.add(group)
# Customer.objects.create(
# user=user,
# username=username,
# dayofaccept=datetime.date.today(),
# )
# return redirect(loginpage)
# else:
# for msg in form.error_messages:
# messages.error(request, f"{msg}: {form.error_messages[msg]}")
# print(msg)
# context={
# 'form':form
# }
# return render(request,'signuppage.html',context)
@un_authenticated
def signuppage(request):
form=SignUpform()
if request.method=='POST':
form=SignUpform(request.POST)
if form.is_valid():
user=form.save()
username=request.POST.get('username')
email=request.POST.get('email')
print(username)
group=Group.objects.get(name='customer')
user.groups.add(group)
Customer.objects.create(
user=user,
username=username,
dayofaccept=datetime.date.today(),
email=email
)
return redirect(loginpage)
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
print(msg)
context={
'form':form
}
return render(request,'signuppage.html',context)
@un_authenticated
def loginpage(request):
if request.method=='POST':
username=request.POST.get('username')
password=request.POST.get('<PASSWORD>')
user=authenticate(request,username=username,password=<PASSWORD>)
if user is not None:
login(request,user)
return redirect('home')
else :
print('wrong Password')
return render(request,'loginpage.html',{})
def logoutpage(request):
logout(request)
return redirect('home')
@login_required(login_url='loginpage')
@allowed_user(allowedroles=['customer'])
def home(request):
user=request.user
noofdonate1=Customer.objects.filter(need='Donator')
noofdonate=0
noofaccept=0
# bloodgrpPresent=[]
# bloodpresentApt=0
# bloodpresentAng=0
# bloodpresentOpt=0
# bloodpresentOng=0
# bloodpresentABpt=0
# bloodpresentABng=0
# bloodpresentBpt=0
# bloodpresentBng=0
for i in noofdonate1:
if i.status=='GotIt':
noofdonate+=1
noofaccept1=Customer.objects.filter(need='Acceptor')
for i in noofaccept1:
if i.status=='GotIt':
noofaccept+=1
context={
'user':user,
'noofdonate':noofdonate,
'noofaccept':noofaccept
}
return render(request,'home.html',context)
@login_required(login_url='loginpage')
def acceptor(request):
form=AcceptorForm()
if request.method=='POST':
form=AcceptorForm(request.POST)
form.save()
return redirect('home')
context={
'form':form
}
return render(request,'acceptor.html',context)
@login_required(login_url='loginpage')
def donator(request):
form=DonatorForm()
if request.method=='POST':
form=DonatorForm(request.POST)
form.save()
return redirect('home')
context={
'form':form
}
return render(request,'donator.html',context)
@login_required(login_url='loginpage')
@allowed_user(allowedroles=['customer'])
def customerpage(request):
id=request.user
instance=Customer.objects.get(username=id)
form=CustomerForm(instance=instance)
need=instance.need
status=instance.status
date=instance.dayofaccept
if request.method=='POST':
form=CustomerForm(request.POST,request.FILES,instance=instance)
form.save()
return redirect('customerpage')
context={
'form':form,
'need':need,
'status':status,
'date':date
}
return render(request,'customerpage.html',context)
@login_required(login_url='loginpage')
@allowed_user(allowedroles=['customer'])
def formfill(request):
username=request.user
instance=Customer.objects.get(username=username)
form=CustomerForm(instance=instance)
if request.method=='POST':
form=CustomerForm(request.POST,request.FILES,instance=instance)
if form.is_valid():
form.save()
print('hii')
return redirect('customerpage')
else:
print('Error bro')
context={
'form':form
}
return render (request,'formfill.html',context)
@login_required(login_url='loginpage')
@allowed_user(allowedroles=['admin'])
def admin1(request):
instanceAccept=Accept.objects.filter(status='Pending')
instanceAcceptall=Accept.objects.all()
instanceDonate=Donate.objects.filter(status='Pending')
instanceDonateall=Donate.objects.all()
instanceCustomerall=Customer.objects.all()
context={
'PendingAcceptor':instanceAccept,
'AllAcceptor':instanceAcceptall,
'PendingDonator':instanceDonate,
'AllDoaner':instanceDonateall,
'AllCustomer':instanceCustomerall
}
return render(request,'admin.html',context)
@login_required(login_url='loginpage')
@allowed_user(allowedroles=['admin'])
def editaccept(request,username):
isinstance=Customer.objects.get(username=username)
print(isinstance.name)
form1=CustomerForm(instance=isinstance)
if request.method=='POST':
form1=CustomerForm(request.POST,request.FILES,instance=isinstance)
print(form1)
# # form=request.POST.get('status')
# isinstance.status=form1.status
# isinstance.dayofaccept=()
# # if form is not 'Pending':
# # print('hii')
# # date=None
# # date=request.POST.get('date')
# # print(date)
# # if date is not None:
# isinstance.dayofaccept=form1.dayofaccept
form1.save()
instance=Customer.objects.get(username=username)
status=instance.status
message=''
dt=instance.dayofaccept
month=str(dt.month)
year=str(dt.year)
day=str(dt.day)
# print(type(str(dt.month)))
if not status=='Pending':
subject='Staus '+instance.status
if status =='Accepted':
dayofaccept=instance.dayofaccept
message='Hii '+instance.name+'\nYour request as '+instance.need+' has been approved!'+'\n Date of Appointment is '+day+'-'+month+'-'+year+'\nThank You'
elif status=='GotIt':
message='Hii '+instance.name+'\nThank You using our services'+'\nStay Safe Stay Happy'+'\nThank You'
else:
message='Hii '+instance.name+'\nSorry Due to certain reasons your request is rejected :('+'\nPlease fill the form correctly'+'\nThank You'
send_mail(subject, message, '<EMAIL>',[instance.email])
return redirect(admin1)
context={
'customer':isinstance,
'form':form1,
}
return render(request,'adminedit.html',context)
# @login_required(login_url='loginpage')
# @allowed_user(allowedroles=['admin'])
# def mailAppointment(request,username):
# instance=Customer.objects.get(username=username)
# status=instance.status
# message=''
# if not status=='Pending':
# subject='Staus '+instance.status
# if status =='Accepted':
# message='Hii '+instance.name+'\nYour request as '+instance.need+' has been approved!'+'\n Date of Appointment is '+instance.dayofaccept+'\nThank You'
# elif status=='GotIt':
# message='Hii '+instance.name+'\nThank You using our services'+'\nStay Safe Stay Happy'+'\nThank You'
# else:
# message='Hii '+instance.name+'\nSorry Due to certain reasons your request is rejected :('+'\nPlease fill the form correctly'+'\nThank You'
# send_mail(subject, message, ['<EMAIL>'])
# return redirect(admin1)
# return redirect('admine')
<file_sep>/plasmaapp/migrations/0014_auto_20210813_1923.py
# Generated by Django 3.2.6 on 2021-08-13 19:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0013_customer_username'),
]
operations = [
migrations.RemoveField(
model_name='customer',
name='id',
),
migrations.AlterField(
model_name='customer',
name='username',
field=models.CharField(max_length=200, primary_key=True, serialize=False, verbose_name='Username'),
),
]
<file_sep>/plasmaapp/migrations/0007_auto_20210812_1809.py
# Generated by Django 3.2.6 on 2021-08-12 18:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0006_alter_accept_dayofaccept'),
]
operations = [
migrations.DeleteModel(
name='Admin1',
),
migrations.AddField(
model_name='accept',
name='status',
field=models.CharField(choices=[('Pending', 'Pending'), ('Accepted', 'Accepted'), ('GotIt', 'GotIt'), ('Rejected', 'Rejected')], default='Pending', max_length=20, verbose_name='Status'),
),
migrations.AddField(
model_name='donate',
name='status',
field=models.CharField(choices=[('Pending', 'Pending'), ('Accepted', 'Accepted'), ('Donated', 'Donated'), ('Rejected', 'Rejected')], default='Pending', max_length=20, verbose_name='Status'),
),
]
<file_sep>/plasmaapp/decorators.py
from django.contrib.auth import decorators
from django.http import HttpResponse
from django.shortcuts import redirect
def un_authenticated(func_view):
def wrapper(request,*args, **kwargs):
if request.user.is_authenticated:
return redirect('home')
else:
return func_view(request,*args, **kwargs)
return wrapper
def allowed_user(allowedroles=[]):
def decorator(func_view):
def wrapper(request,*args, **kwargs):
group=None
if request.user.groups.exists():
group=request.user.groups.all()[0].name
if group in allowedroles:
return func_view(request,*args, **kwargs)
else:
if group== 'admin':
return redirect('admin1')
else :
return redirect('home')
return wrapper
return decorator
<file_sep>/plasmaapp/migrations/0005_alter_accept_dayofaccept.py
# Generated by Django 3.2.6 on 2021-08-12 16:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0004_auto_20210812_1635'),
]
operations = [
migrations.AlterField(
model_name='accept',
name='dayofaccept',
field=models.DateField(),
),
]
<file_sep>/plasmaapp/templates/adminedit.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<title>Edit Status</title>
<style>
.container{
text-align: center;
}
h1{
font-size: 45px;
margin: 2% auto;
}
table{
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<h1>{{customer.need}} Details</h1>
<table class="table">
<tr>
<td>
Name :
</td>
<td>{{customer.name}}</td>
</tr>
<tr>
<td>
Blood Group :
</td>
<td>{{customer.bloodgroup}}</td>
</tr>
<tr>
<td>
Age :
</td>
<td>{{customer.age}}</td>
</tr>
<tr>
<td>Gender :</td>
<td>{{customer.gender}}</td>
</tr>
<tr>
<td>Phone Number : </td>
<td> {{customer.phoneno}}</td>
</tr>
<tr>
<td>Address :</td>
<td>
{{customer.address}}
</td>
</tr>
<tr>
<td>Email :</td>
<td>
{{customer.email}}
</td>
</tr>
<tr>
<td>Present Status :</td>
<td>{{customer.status}}</td>
</tr>
<tr>
<td>Date Given :</td>
<td>{{customer.dayofaccept}}</td>
</tr>
<form action="" method="POST">{%csrf_token%}
<div style="display: none;">
{{form.name}}
{{form.age}}
{{form.phoneno}}
{{form.address}}
{{form.bloodgroup}}
{{form.need}}
{{form.email}}
</div>
<tr>
<td>
Edit Status :
</td>
<td>
<!-- <select id="status" name="status" value="{{customer.status}}">
<option value="Pending">Pending</option>
<option value="Accepted"selected>Accepted</option>
<option value="GotIt">GotIt</option>
<option value="Rejected">Rejected</option>
</select> -->
{{form.status}}
</td>
</tr>
<tr>
<td>
change Date :
</td>
<td>
<!-- <input type="date" name="date" class="mydate" > -->
{% comment %} <input type="date" name="dayofaccept" value="{{customer.dayofaccept}}" id="id_dayofaccept" Required> {% endcomment %}
{{form.dayofaccept }}
</td>
</tr>
<tr>
<td> Prescription Uploaded</td>
<td>{{form.prescription}}</td>
</tr>
<tr>
<td>
<a href="{%url 'admin1'%}"><button class="btn btn-danger">Cancel And Go Back</button></a>
</td>
<td>
<input type="submit" class="btn btn-success"value="Save Changes">
</td>
</tr>
</form>
</table>
<!-- <form action="" method="POST">{%csrf_token%}
<label for="status" > Edit Status</label>
<select id="status" name="status">
<option value="Pending">Pending</option>
<option value="Accepted">Accepted</option>
<option value="GotIt">GotIt</option>
<option value="Rejected">Rejected</option>
</select>
<input type="date" name="date">
<input type="submit">
</form> -->
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
<file_sep>/plasmaapp/migrations/0015_alter_customer_need.py
# Generated by Django 3.2.6 on 2021-08-14 08:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0014_auto_20210813_1923'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='need',
field=models.CharField(blank=True, choices=[('None', 'None'), ('Acceptor', 'Acceptor'), ('Donator', 'Donator')], default='None', max_length=20, null=True, verbose_name='Need'),
),
]
<file_sep>/plasmaapp/migrations/0013_customer_username.py
# Generated by Django 3.2.6 on 2021-08-13 19:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0012_auto_20210813_1714'),
]
operations = [
migrations.AddField(
model_name='customer',
name='username',
field=models.CharField(default='hii', max_length=200, verbose_name='Username'),
),
]
<file_sep>/plasmaapp/forms.py
from django import forms
from django.forms import fields
from .models import Accept,Donate,Customer
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class SignUpform(UserCreationForm):
class Meta:
model=User
fields=['username','email','<PASSWORD>1','<PASSWORD>']
class DateInput(forms.DateInput):
input_type = 'date'
class AcceptorForm(forms.ModelForm):
class Meta:
model=Accept
fields = ['name','address','phoneno','age','gender','bloodgroup','dayofaccept','status']
widgets={
'dayofaccept':DateInput()
}
class DonatorForm(forms.ModelForm):
class Meta:
model=Donate
fields=['name','address','phoneno','age','gender','bloodgroup','dayofdonate','status']
widgets={
'dayofdonate':DateInput()
}
class CustomerForm(forms.ModelForm):
class Meta:
model=Customer
fields=['name','address','phoneno','age','gender','bloodgroup','dayofaccept','need','status','prescription']
widgets={
'dayofaccept':DateInput()
}
<file_sep>/plasmaapp/urls.py
from django.contrib.auth import logout
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',views.home,name='home'),
path('acceptor/',views.acceptor,name='acceptor'),
path('donator/',views.donator,name='donator'),
path('admin1/',views.admin1,name='admin1'),
path('admin1/editaccept/<username>',views.editaccept,name='editaccept'),
# path('editaccept/sendmail/<username>',views.mailAppointment,name='mailit'),
# path('admin1/editdoaner/<id>',views.editdoaner,name='editdoaner'),
path('SignUp/',views.signuppage,name='signup'),
path('login/',views.loginpage,name='loginpage'),
path('logout/',views.logoutpage,name='logout'),
path('customer/',views.customerpage,name='customerpage'),
path('customer/formfill',views.formfill,name='formfill'),
path('reset_password/',auth_views.PasswordResetView.as_view(template_name="password_reset.html"),name='reset_password'),
path('reset_password_sent/',auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"),name='password_reset_done'),
path('reset/<uidb64>/<token>',auth_views.PasswordResetConfirmView.as_view(template_name="reset_token.html"),name='password_reset_confirm'),
path('reset_password_complete/',auth_views.PasswordResetCompleteView.as_view(template_name="reset_success.html"),name='password_reset_complete'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)<file_sep>/plasmaapp/migrations/0009_auto_20210812_2117.py
# Generated by Django 3.2.6 on 2021-08-12 21:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0008_auto_20210812_2114'),
]
operations = [
migrations.AlterField(
model_name='accept',
name='dayofaccept',
field=models.DateField(blank=True, null=True, verbose_name='Day of Accepting'),
),
migrations.AlterField(
model_name='donate',
name='dayofdonate',
field=models.DateField(blank=True, null=True, verbose_name='Day of Donating'),
),
]
<file_sep>/plasmaapp/migrations/0012_auto_20210813_1714.py
# Generated by Django 3.2.6 on 2021-08-13 17:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0011_customer'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='age',
field=models.IntegerField(blank=True, null=True, verbose_name='Age'),
),
migrations.AlterField(
model_name='customer',
name='bloodgroup',
field=models.CharField(blank=True, choices=[('A+', 'A+'), ('A-', 'A-'), ('O+', 'O+'), ('O-', 'O-'), ('B+', 'B+'), ('B-', 'B-'), ('AB-', 'AB-'), ('AB+', 'AB+')], max_length=3, null=True, verbose_name='Blood Group'),
),
]
<file_sep>/plasmaapp/migrations/0006_alter_accept_dayofaccept.py
# Generated by Django 3.2.6 on 2021-08-12 17:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plasmaapp', '0005_alter_accept_dayofaccept'),
]
operations = [
migrations.AlterField(
model_name='accept',
name='dayofaccept',
field=models.DateField(verbose_name='Day of Accepting'),
),
]
<file_sep>/plasmaapp/migrations/0001_initial.py
# Generated by Django 3.2.6 on 2021-08-12 16:29
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Accept',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Name of Acceptor')),
('address', models.CharField(max_length=200, verbose_name='Address')),
('phoneno', models.CharField(max_length=10, verbose_name='Phone Number')),
('age', models.IntegerField(max_length=2, verbose_name='Age')),
('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('T', 'Trans')], max_length=1, verbose_name='Gender')),
('bloodgroup', models.CharField(choices=[('A+', 'A+'), ('A-', 'A-'), ('O+', 'O+'), ('O-', 'O-'), ('B+', 'B+'), ('B-', 'B-'), ('AB-', 'AB-'), ('AB+', 'AB+')], max_length=3, verbose_name='Blood Group')),
('dayofaccept', models.DateTimeField(verbose_name='Day of Accepting')),
],
),
migrations.CreateModel(
name='Admin1',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='Donate',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='Name of Donar')),
('address', models.CharField(max_length=200, verbose_name='Address')),
('phoneno', models.CharField(max_length=10, verbose_name='Phone Number')),
('age', models.IntegerField(max_length=2, verbose_name='Age')),
('gender', models.CharField(choices=[('M', 'Male'), ('F', 'Female'), ('T', 'Trans')], max_length=1, verbose_name='Gender')),
('bloodgroup', models.CharField(choices=[('A+', 'A+'), ('A-', 'A-'), ('O+', 'O+'), ('O-', 'O-'), ('B+', 'B+'), ('B-', 'B-'), ('AB-', 'AB-'), ('AB+', 'AB+')], max_length=3, verbose_name='Blood Group')),
('dayofdonate', models.DateTimeField(verbose_name='Day of Donating')),
],
),
]
| 3d6e60fb66128fb712c3c35d66ff01c34649907f | [
"Python",
"HTML"
]
| 21 | Python | tech-akash/Blood-Bank1 | 51e304fd8c3c9532e63b6efaa13a2974027374c8 | 45bcee1b0b2cdbe4415aea141c6364031e50ac36 |
refs/heads/master | <file_sep># Advanced Gatsby Wordpress ACF Starter
This is a bare-bones repository to help you get started building pages in gatsby in a component-like fashion with Wordpress using the Advanced Custom Field (ACF) plugin's Flexible Content field on multiple post types.
<br/>
Heavily inspired by <NAME>'s [gatsby-starter-wordpress-advanced](https://github.com/henrikwirth/gatsby-starter-wordpress-advanced/tree/tutorial/part-7)
<br/>
<file_sep>module.exports = {
plugins: [
{
resolve: `gatsby-source-wordpress`,
options: {
url: process.env.WPGRAPHQL_URL || `http://www.yourwpwebsite.local/graphql`,
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
],
}
<file_sep>import React from 'react'
const BannerOne = data => {
return (
<section id='banner-one'>
<h1>{data.title}</h1>
</section>
)
}
export default BannerOne<file_sep>import React from 'react'
const NewsTemplate = ({ data }) => {
return (
<>
<h1>Da News</h1>
</>
)
}
export default NewsTemplate
| 0708443e6b10bede0ba40e93b03d6d7b19f2b316 | [
"Markdown",
"JavaScript"
]
| 4 | Markdown | kylesnod/gatsby-wp-acf-starter | 30ce8533f7619557ac71f7c7c30060d85bacb621 | 0239c0ccbc18878e261e81f2b557c58c9b38ffd4 |
refs/heads/master | <repo_name>Schrominger/spin1BEC<file_sep>/py-code/readme.md
## Hamiltonian of spin-1 BEC
$$
H = q*h_0 + \frac{c}{2N}h_2 + r*h_1
$$
- $h_0$:单粒子哈密顿量,这里取$h_0 = \hat N_1+\hat N_{-1}$;
- $h_2$:相互作用哈密顿量,这里取$h_2 = {\mathbf{\hat F}^2-2N}$;
- $h_1$:不同$F_z$-block之间的耦合哈密顿量,这里取 $h_1=\hat F_x$。
### 数态基:$|N_1,N_0,N_{-1}\rangle$
$|N_1,N_0,N_{-1}\rangle\equiv|k+M,N-2k-M, k\rangle$ which can belabled by $|k,M\rangle$ with $k=N_{-1}$ and $M=N_1-N_{-1}$.
由于H中的$h_0$和$h_2$项在$F_z$本征基下为块对角矩阵,也即有不同$M$值的子空间不耦合,而$h_1$中的一阶角动量算符($\hat F_x, \hat F_y, \hat F_z, \hat F_\pm$)一般只耦合近邻的$M$子空间,因此我们将哈密顿量按不同$M$值的子空间展开,然后再构建近邻子空间的耦合矩阵元。
---
```python
# -*- coding: utf-8 -*-
import numpy as np
import scipy as sp
import qutip as qt
import matplotlib.pyplot as plt
def build_h0(N, M_arr=np.array([0,])):
# 按照给定M顺序生存block矩阵的array组成的dict
h0 = {}
for M in M_arr:
kmax = (N-abs(M))//2
k_arr = np.arange(0., kmax+1.0) if M>=0 else np.arange(abs(M), (N+abs(M))//2+1.0)
# q*(M+2k), neglect q here
# h0[M] = np.diag(M+2.0*k_arr - N) # -N0
h0[M] = np.diag((2.0*k_arr+M)) # (N1 + N_{-1})
return h0
def build_h2(N, M_arr=np.array([0,])):
h2 = {}
for M in M_arr:
kmax = np.floor((N-np.abs(M))/2.)
k_arr = np.arange(0, kmax+1.0) if M>= 0 else np.arange(abs(M), (N+abs(M))//2+1.0)
# F^2-2N
d = (2.0*(N - M - 2.0*k_arr)-1.0)*(M + 2.0*k_arr) + M**2
# off-diagonal term
if np.size(d)>1:
up = 2.0*np.sqrt((N-2.0*k_arr-M+1.0)*(N-2.0*k_arr-M+2.))*np.sqrt(k_arr*(k_arr+M))
up = up[1:]
h2[M] = np.diag(d,0) + np.diag(up,1) + np.diag(up,-1)
else:
h2[M] = np.diag(d,0)
return h2
# 只需传入M的序列,按照M的排序来顺序定,或者按照h0的尺寸来定
def build_h1(h0, N):
# 实际上只需要h0的各个block的维度
# only for Fx now
h1 = {}
# iterate the M values, only non-negtive.
M_arr = [x for x in h0.keys() if not x<0]
for M in M_arr[0:-1]:
(m,n) = (np.shape(h0[M])[0], np.shape(h0[M+1])[0])
temp = np.full((m, n), 0.0)
# 赋值: diagonal elements
id_arr = np.arange(0,min(m,n)) # 对角元指标
temp[id_arr, id_arr] = (1.0/np.sqrt(2))*np.sqrt((N-2.*id_arr-M)*(id_arr+M+1.))
# up-diagonal elements
up_arr = np.arange(1,n) # +1 off-diagonal line has n-1 elements
temp[up_arr,up_arr-1] = (1.0/np.sqrt(2))*np.sqrt((N-2.*up_arr-M+1.)*(up_arr))
h1[M+1] = temp[:,:]
h1[-M-1] = temp[:,:]
return h1
# combine function, combine these blocks
def merge_h(h0, h1, h2, c=1.0, q=1.0, r=0.0):
"""
merge all h-components
h = q*h0 + (c/2N)*h2 + r*h1
"""
H_dim = int(np.sum([np.floor((N-np.abs(Fz))//2)+1 for Fz in h0.keys()]))
print("The full Hilber dim=", H_dim,".")
fullH = np.full((H_dim, H_dim), 0.0)
cnt = 0
for M in sorted(h0):
h1_Mid = M if M<0 else M+1
if h1_Mid in h1.keys(): # h1 has less one key than h0 and h2.
# block_h0, block_h2, block_h1 = h0[M], h2[M],h1[M]
current_shape, next_shape = np.shape(h0[M])[0], np.shape(h0[M+1])[0]
# diagonal block, black tri-diagonal matrix.
fullH[cnt:cnt+current_shape, cnt:cnt+current_shape] \
= q*h0[M][:,:] + (c/N/2.0)*h2[M][:,:]
# off-diagonal block, (blue rectangular array)
fullH[cnt:cnt+current_shape, cnt+current_shape:cnt+current_shape+next_shape] \
= r*np.transpose(h1[h1_Mid][:,:]) if h1_Mid<0 else r*h1[h1_Mid][:,:] # +1 off-diagonal
fullH[cnt+current_shape:cnt+current_shape+next_shape, cnt:cnt+current_shape] \
= r*h1[h1_Mid][:,:] if h1_Mid<0 else r*np.transpose(h1[h1_Mid][:,:]) # -1 off-diagonal
cnt += current_shape
else:
current_shape = np.shape(h0[M])[0]
# diagonal block, black tri-diagonal matrix.
fullH[cnt:cnt+current_shape, cnt:cnt+current_shape] = q*h0[M][:,:] + (c/2./N)*h2[M][:,:]
# no blue rectangular block for this M-value.
cnt += current_shape
return fullH
if __name__ == "__main__":
N = 10
M_arr = np.arange(-N,N+1)
print('N=', N)
h0 = build_h0(N, M_arr=M_arr)
h2 = build_h2(N, M_arr=M_arr)
h1 = build_h1(h0, N)
H = merge_h(h0, h1, h2, c=1.0, q=1.0, r=0.00)
Hobj = qt.Qobj(H)
e = Hobj.eigenenergies()
print('Eigenenergies:', e[0:30])
```
<file_sep>/py-code/memo.md
- py version
<file_sep>/py-code/utils.py
# -*- coding: utf-8 -*-
"""
file: utils.py
author: minger
date: 2019-09-08
"""
import numpy as np
import scipy as sp
import qutip as qt
import matplotlib.pyplot as plt
def build_h0(N, M_arr=np.array([0,])):
# 按照给定M顺序生存block矩阵的array组成的dict
h0 = {}
for M in M_arr:
kmax = (N-abs(M))//2
k_arr = np.arange(0., kmax+1.0) if M>=0 else np.arange(abs(M), (N+abs(M))//2+1.0)
# q*(M+2k), neglect q here
# h0[M] = np.diag(M+2.0*k_arr - N) # -N0
h0[M] = np.diag((2.0*k_arr+M)) # (N1 + N_{-1})
return h0
def build_h2(N, M_arr=np.array([0,])):
h2 = {}
for M in M_arr:
kmax = np.floor((N-np.abs(M))/2.)
k_arr = np.arange(0, kmax+1.0) if M>= 0 else np.arange(abs(M), (N+abs(M))//2+1.0)
# F^2-2N
d = (2.0*(N - M - 2.0*k_arr)-1.0)*(M + 2.0*k_arr) + M**2
# off-diagonal term
if np.size(d)>1:
up = 2.0*np.sqrt((N-2.0*k_arr-M+1.0)*(N-2.0*k_arr-M+2.))*np.sqrt(k_arr*(k_arr+M))
up = up[1:]
h2[M] = np.diag(d,0) + np.diag(up,1) + np.diag(up,-1)
else:
h2[M] = np.diag(d,0)
return h2
# 只需传入M的序列,按照M的排序来顺序定,或者按照h0的尺寸来定
def build_h1(h0, N):
# 实际上只需要h0的各个block的维度
# only for Fx now
h1 = {}
# iterate the M values, only non-negtive.
M_arr = [x for x in h0.keys() if not x<0]
for M in M_arr[0:-1]:
(m,n) = (np.shape(h0[M])[0], np.shape(h0[M+1])[0])
temp = np.full((m, n), 0.0)
# 赋值: diagonal elements
id_arr = np.arange(0,min(m,n)) # 对角元指标
temp[id_arr, id_arr] = (1.0/np.sqrt(2))*np.sqrt((N-2.*id_arr-M)*(id_arr+M+1.))
# up-diagonal elements
up_arr = np.arange(1,n) # +1 off-diagonal line has n-1 elements
temp[up_arr,up_arr-1] = (1.0/np.sqrt(2))*np.sqrt((N-2.*up_arr-M+1.)*(up_arr))
h1[M+1] = temp[:,:]
h1[-M-1] = temp[:,:]
return h1
# combine function, combine these blocks
def merge_h(h0, h1, h2, c=1.0, q=1.0, r=0.0):
"""
merge all h-components
h = q*h0 + (c/2N)*h2 + r*h1
"""
H_dim = int(np.sum([np.floor((N-np.abs(Fz))//2)+1 for Fz in h0.keys()]))
print("The full Hilber dim=", H_dim,".")
fullH = np.full((H_dim, H_dim), 0.0)
cnt = 0
for M in sorted(h0):
h1_Mid = M if M<0 else M+1
if h1_Mid in h1.keys(): # h1 has less one key than h0 and h2.
# block_h0, block_h2, block_h1 = h0[M], h2[M],h1[M]
current_shape, next_shape = np.shape(h0[M])[0], np.shape(h0[M+1])[0]
# print('M:',M)
# pdb.set_trace()
# diagonal block, black tri-diagonal matrix.
fullH[cnt:cnt+current_shape, cnt:cnt+current_shape] \
= q*h0[M][:,:] + (c/N/2.0)*h2[M][:,:]
# off-diagonal block, (blue rectangular array)
fullH[cnt:cnt+current_shape, cnt+current_shape:cnt+current_shape+next_shape] \
= r*np.transpose(h1[h1_Mid][:,:]) if h1_Mid<0 else r*h1[h1_Mid][:,:] # +1 off-diagonal
fullH[cnt+current_shape:cnt+current_shape+next_shape, cnt:cnt+current_shape] \
= r*h1[h1_Mid][:,:] if h1_Mid<0 else r*np.transpose(h1[h1_Mid][:,:]) # -1 off-diagonal
cnt += current_shape
else:
current_shape = np.shape(h0[M])[0]
# diagonal block, black tri-diagonal matrix.
fullH[cnt:cnt+current_shape, cnt:cnt+current_shape] = q*h0[M][:,:] + (c/2./N)*h2[M][:,:]
# no blue rectangular block for this M-value.
cnt += current_shape
return fullH
if __name__ == "__main__":
import pdb
N = 10
M_arr = np.arange(-N,N+1)
print('N=', N)
h0 = build_h0(N, M_arr=M_arr)
h2 = build_h2(N, M_arr=M_arr)
h1 = build_h1(h0, N)
# pdb.set_trace()
H = merge_h(h0, h1, h2, c=1.0, q=1.0, r=0.00)
Hobj = qt.Qobj(H)
# pdb.set_trace()
e = Hobj.eigenenergies()
print(e[0:30]+1.0)
# Gap = []
# qvec = np.linspace(-2.2,2.2,200)
# for q in qvec:
# H = merge_h(h0, h1, h2, q=q)
# Hobj = qt.Qobj(H)
# e = Hobj.eigenenergies()
# gap = e[1] - e[0]
# Gap.append(gap)
# plt.plot(qvec, Gap)
# plt.show()
# pdb.set_trace()
<file_sep>/README.md
# spin1BEC
codes about spin1BEC.
| ef7f10c7b11952b8dcc715074f2150442c0a3ea6 | [
"Markdown",
"Python"
]
| 4 | Markdown | Schrominger/spin1BEC | d3398494215b1c9d8c2de059a6ba2702316fa2be | fa5e3ba7dd1567cff9310afe2770bf0889157d1b |
refs/heads/master | <file_sep>package com.example.demo.repository;
import com.example.demo.entity.Facture;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.Date;
import java.util.List;
@Repository
public interface FactureRepository extends JpaRepository<Facture, Long> {
List<Facture> findByFournisseur(String fournisseur);
List<Facture> findByStatut(String statut);
List<Facture> findByRefFacture(String refFacture);
List<Facture> findByPrixHT(int prixHT);
List<Facture> findByDateEcheance(String dateEcheance);
}
| 8b0213b3b1ceb577d97005588b3833bbc24d72e3 | [
"Java"
]
| 1 | Java | guesmiIslem/PartieBackEnd | e1a367c5705c45cbad1c36f31a38aba041235cc3 | 58542618976ed5cab39ac74f37550ce97d7fa3a6 |
refs/heads/master | <repo_name>PapercraftTeam/Flash_Project<file_sep>/app/src/main/java/com/grieferpig/flash/whiteLightActivity.java
package com.grieferpig.flash;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.snackbar.Snackbar;
import java.text.DecimalFormat;
public class whiteLightActivity extends AppCompatActivity {
SeekBar brightnessSlider;
int brightness;
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_white_light);
Window window = this.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = 1;
window.setAttributes(lp);
brightnessSlider = findViewById(R.id.brightnessSlider);
brightnessSlider.setProgress(100);
brightnessSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
brightness = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Snackbar.make(seekBar,"设置亮度为"+brightness, Snackbar.LENGTH_SHORT).show();
WindowManager.LayoutParams lp = window.getAttributes();
DecimalFormat df = new DecimalFormat("0.00");
double tmpVal = Double.parseDouble(df.format((double) brightness/100));
lp.screenBrightness = (float)tmpVal;
window.setAttributes(lp);
}
});
}
}<file_sep>/app/src/main/java/com/grieferpig/flash/configOptions.java
package com.grieferpig.flash;
enum configOptions {
emerSoundEnabled("com.grieferpig.flash.storage.emerSoundEnabled");
public String value = "";
configOptions(String string) {
this.value = value;
}
public String value() {
return this.value;
}
}
<file_sep>/app/src/main/java/com/grieferpig/flash/Light.java
package com.grieferpig.flash;
import android.app.Activity;
import android.media.Image;
import androidx.annotation.IdRes;
public class Light {
Activity opener;
Class lightActivity;
String title, desc;
int imgsrc;
public Light(Activity opener, Class lightActivity, String title, String desc, int imgsrc){
this.opener = opener;
this.lightActivity = lightActivity;
this.title = title;
this.desc = desc;
this.imgsrc = imgsrc;
}
public Activity getOpener() {
return opener;
}
public Class getLightActivity() {
return lightActivity;
}
public String getDesc() {
return desc;
}
public int getImgsrc() {
return imgsrc;
}
public String getTitle() {
return title;
}
}
<file_sep>/README.md
# Flash_Project
Flashlight on your wrist.
<file_sep>/app/src/main/java/com/grieferpig/flash/StorageMan.java
package com.grieferpig.flash;
import android.app.Activity;
import android.content.SharedPreferences;
public class StorageMan {
String storageKey;
Activity a;
SharedPreferences writer;
public StorageMan(String storageKey, Activity a){
this.storageKey = storageKey;
this.a = a;
this.writer = a.getSharedPreferences(storageKey, 0);
}
public void write(String context){
this.writer.edit().putString(this.storageKey, context).apply();
}
public String read(){
return this.writer.getString(this.storageKey, "Na");
}
public String getTranslation(int resource_name) {
return this.a.getResources().getString(resource_name);
}
}
<file_sep>/app/src/main/java/com/grieferpig/flash/SettingsActivity.java
package com.grieferpig.flash;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class SettingsActivity extends AppCompatActivity {
private TextView versionText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Switch sw = findViewById(R.id.emergency);
sw.setChecked(Boolean.parseBoolean(
new StorageMan(
configOptions.emerSoundEnabled.toString()
,this).read()
));
Log.d("IFUCKYOURMOTHER", configOptions.values()+"");
versionText = findViewById(R.id.versionText);
versionText.setText("这是第"+BuildConfig.VERSION_CODE+"个发布的版本,版本号为"+BuildConfig.VERSION_NAME);
}
public void onClick(View v){
Switch sw = (Switch)v;
new StorageMan(configOptions.emerSoundEnabled.toString(),this).write(sw.isChecked()+"");
}
} | 8c0e02f0e88fe893d23475501d81fcabb2fbb713 | [
"Markdown",
"Java"
]
| 6 | Java | PapercraftTeam/Flash_Project | 9a0181e6cb23bebf256a57c3f26cba0a1a7d1b1d | 3abe264721b0f4cac41fb2aa5191c4950d22b1fe |
refs/heads/master | <file_sep>#quoridor projet 1
import argparse
import api
import pprint as pp
idul = 'donap1'
stade_jeu = {
"joueurs": [
{"nom": "idul", "murs": 7, "pos": [5, 5]},
{"nom": "automate", "murs": 3, "pos": [8, 6]}],
"murs": {
"horizontaux": [[4, 4], [2, 6], [3, 8], [5, 8], [7, 8]],
"verticaux": [[6, 2], [4, 4], [2, 6], [7, 5], [7, 7]]}
}
# fonction 1 de 5
def analyser_commande():
parser = argparse.ArgumentParser(description='Jeu Quoridor')
parser.add_argument('-i', '--idul', metavar='TYPE', dest='idul',
default='donap1', choices = ['type1', 'type 2'],help="Idul du joueur")
return parser.parse_args()
# création de la table
def _legende(idul):
return "legende: 1={}, 2=automate".format(idul)
def _top_line():
ligne = ' '+'-'*35
return ligne
def _table_pion():
lignes = {}
for x in range(1, 10):
colonnes = {}
for y in range(1, 10):
colonnes[str(y)] = '.'
lignes[str(10-x)] = colonnes
return lignes
def _base_line():
ligne = '--|'+'-'*35+'\n'+' | 1 2 3 4 5 6 7 8 9'
return ligne
def _table_interne_x():
lignes = {}
for x in range(1, 10):
colonnes = {}
for y in range(1, 10):
if y == 9:
colonnes[str(y)] = '|'
else:
colonnes[str(y)] = ' '
lignes[str(10-x)] = colonnes
return lignes
def _table_interne_y():
lignes = {}
for x in range(1, 10):
colonnes = {}
for y in range(1, 10):
colonnes[str(y)] = ' '
lignes[str(10-x)] = colonnes
return lignes
# fonction 2 de 5
def afficher_damier_ascii(etat_jeu):
coord_1 = stade_jeu['joueurs'][0]['pos']
coord_2 = stade_jeu['joueurs'][1]['pos']
table = _table_pion()
tableInterX = _table_interne_x()
tableInterY1 = _table_interne_x()
tableInterY2 = _table_interne_y()
table[str(coord_1[0])][str(coord_1[1])] = '1'
table[str(coord_2[0])][str(coord_2[1])] = '2'
murs_horizontaux = []
murs_verticaux = []
print(_legende(stade_jeu['joueurs'][0]['nom']))
print(_top_line())
for i in stade_jeu['murs']['horizontaux']:
murs_horizontaux.append(i)
for i in stade_jeu['murs']['verticaux']:
murs_verticaux.append(i)
for i in murs_horizontaux:
tableInterY1[str(i[1])][str(i[0])] = '-'
tableInterY2[str(i[1])][str(i[0])] = '---'
tableInterY2[str(i[1])][str(i[0] + 1)] = '---'
for i in murs_verticaux:
tableInterX[str(i[1])][str(i[0] - 1)] = '|'
tableInterX[str(i[1] + 1)][str(i[0] - 1)] = '|'
tableInterY1[str(i[1] + 1)][str(i[0] - 1)] = '|'
for i in range(9):
print(str(9 - i) + ' | ', end='')
for j in range(9):
print(table[str(j + 1)][str(9 - i)], end=' ')
print(tableInterX[str(9 - i)][str(j + 1)], end=' ')
print('')
if i < 8:
print(' |', end='')
for j in range(9):
print(tableInterY2[str(9 - i)][str(j + 1)], end='')
print(tableInterY1[str(9 - i)][str(j + 1)], end='')
print('')
print(_base_line())
def main():
command = analyser_commande()
debut = api.lister_parties(command.idul)
pp.pprint(debut)
afficher_damier_ascii(debut['parties'][0]['état'])
for i in debut['parties']:
if i['id'] == id:
afficher_damier_ascii(i['état'])
while True:
print("Type de coup ['D', 'MH', 'MV']: ")
type_coup = input()
print("Position x: ")
position_x = int(input())
print("Position y: ")
position_y = int(input())
position = (position_x, position_y)
pp.pprint(api.jouer_coup(id, type_coup, position))
etat = api.lister_parties(command.idul)
for i in etat['parties']:
if i['id'] == id:
afficher_damier_ascii(i['état'])
if __name__ == '__main__':
main()
<file_sep>#quoridor projet 1
import requests
def _url():
return 'http://www.ulaval.ca'
def _url_base():
return 'https://python.gel.ulaval.ca/quoridor/api/'
# fonction 3 de 5
def lister_parties(idul):
rep = requests.get(url=_url_base()+'lister', params={'idul': idul})
if rep.status_code == 200:
#Bonne réponse du serveur, décoder JSON
return rep.json()
else:
return(RuntimeError(f"Le GET sur {_url_base()+'lister'} a produit le code d'erreur {rep.status_code}."))
# fonction 4 de 5
def initialiser_partie(idul):
rep = requests.post(url=_url_base()+'débuter/', data={'idul': idul})
if rep.status_code == 200:
#Bonne réponse du serveur, décoder JSON
try:
return rep.json()['gagnant']
except KeyError:
return rep.json()
else:
print(rep.json())
return "ERROR {}".format(rep.status_code)
# fonction 5 de 5
def jouer_coup(id_partie, type_coup, position):
rep = requests.post(url=_url_base() + 'jouer/', data={'id': id, 'type': type_coup, 'pos': position})
if rep.status_code == 200:
#Bonne réponse du serveur, décoder JSON
return rep.json()
else:
print(rep.json())
return "ERROR {}".format(rep.status_code)
<file_sep>#quoridor projet 1
| efc66d6579a0391dd39b458d745ebf355d7a48e6 | [
"Python"
]
| 3 | Python | Dominic2222/quorridor | 55b83cb3f55ecc04cfe4c92b7c9dd619e1cd0dfe | b75cae682e6beed2f823f4f0430bb7cb0556bf96 |
refs/heads/master | <file_sep>import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './plugins/element.js'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
router.beforeEach((to,form,next) => {
let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
if(userInfo && userInfo.access_token) {
next()
} else {
next('/login')
}
})<file_sep>import req from '../fetch/index.js'
const config = {
// portExport: {
// url: '/api/media/stimulate/exportExcel',
// method: 'post',
// fileConfig: {
// type: 'file',
// fileName: '销售激励报表'
// }
// },
getPlace: {
url:'/pc/driver/getPlace',
method: 'post'
},
listShop: {
url:'/pc/shop/listShop',
method: 'post'
},
saveShop: {
url:'/pc/shop/saveShop',
method: 'post'
},
getShopByShopCode: {
url:'/pc/shop/getShopByShopCode',
method: 'post'
},
updateShop: {
url:'/pc/shop/updateShop',
method: 'post'
},
deleteShop: {
url:'/pc/shop/deleteShop',
method: 'post'
},
}
const request = function (funcName, requestParam) {
return req(config[funcName].url, config[funcName].method, requestParam, {}, config[funcName].fileConfig)
}
export default request
<file_sep>import req from '../fetch/index.js'
const config = {
// portExport: {
// url: '/api/media/stimulate/exportExcel',
// method: 'post',
// fileConfig: {
// type: 'file',
// fileName: '销售激励报表'
// }
// },
listGoods: {
url:'/pc/slideshow/listGoods',
method: 'post'
},
listHotGoods: {
url:'/pc/hotGoods/listHotGoods',
method: 'post'
},
saveHotGoods: {
url:'/pc/hotGoods/saveHotGoods',
method: 'post'
},
updateHotGoods: {
url:'/pc/hotGoods/updateHotGoods',
method: 'post'
},
getHotGoodsByHotGoodsCode: {
url:'/pc/hotGoods/getHotGoodsByHotGoodsCode',
method: 'post'
},
deleteHotGoods: {
url:'/pc/hotGoods/deleteHotGoods',
method: 'post'
},
getShowCount: {
url:'/pc/hotGoods/getShowCount',
method: 'post'
},
updateShowCount: {
url:'/pc/hotGoods/updateShowCount',
method: 'post'
},
// uploadImage: {
// url:'/pc/imageUpload/uploadImage',
// method: 'post'
// },
}
const request = function (funcName, requestParam) {
return req(config[funcName].url, config[funcName].method, requestParam, {}, config[funcName].fileConfig)
}
export default request
<file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../pages/login.vue'
// import Test from '../行走书店管理系统/test.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
redirect: '/login',
},
{
path: '/home',
name: 'home',
redirect: '/user-manage',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "home" */ '@/pages/home.vue'),
children: [
{
path: '/user-manage',
name: 'user-manage',
component: () => import(/* webpackChunkName: "user-manage" */ '@/pages/user-manage/index.vue')
},
{
path: '/menu-manage',
name: 'menu-manage',
component: () => import(/* webpackChunkName: "menu-manage" */ '@/pages/menu-manage/index.vue')
},
{
path: '/comm-manage',
name: 'comm-manage',
component: () => import(/* webpackChunkName: "comm-manage" */ '@/pages/comm-manage/index.vue')
},
{
path: '/home-pic-manage',
name: 'home-pic-manage',
component: () => import(/* webpackChunkName: "home-pic-manage" */ '@/pages/home-pic-manage/index.vue')
},
{
path: '/comm-classify-manage',
name: 'comm-classify-manage',
component: () => import(/* webpackChunkName: "comm-classify-manage" */ '@/pages/comm-classify-manage/index.vue')
},
{
path: '/client-manage',
name: 'client-manage',
component: () => import(/* webpackChunkName: "client-manage" */ '@/pages/client-manage/index.vue')
},
{
path: '/order-manage',
name: 'order-manage',
component: () => import(/* webpackChunkName: "order-manage" */ '@/pages/order-manage/index.vue')
},
{
path: '/hot-comm-manage',
name: 'hot-comm-manage',
component: () => import(/* webpackChunkName: "hot-comm-manage" */ '@/pages/hot-comm-manage/index.vue')
},
{
path: '/shop-info-manage',
name: 'shop-info-manage',
component: () => import(/* webpackChunkName: "shop-info-manage" */ '@/pages/shop-info-manage/index.vue')
},
{
path: '/driver-info-manage',
name: 'driver-info-manage',
component: () => import(/* webpackChunkName: "driver-info-manage" */ '@/pages/driver-info-manage/index.vue')
}
]
},
{
path: '/login',
name: 'login',
component: Login
},
// {
// path: '/test',
// name: 'test',
// component: Test
// }
]
const router = new VueRouter({
routes
})
export default router
| 653e1ab2d0698fd5dc7992ff21689550e75d7245 | [
"JavaScript"
]
| 4 | JavaScript | Zheng-hs/ZHS | b8dfbff33d22ad7ebbbdf55a787e2db941d9d2eb | d404139b1ad7702c0ab9ca09b04d62a9c29c9087 |
refs/heads/master | <file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Clientes extends Model
{
public static function getClientes()
{
$clientes = DB::table('clientes')
->join('situacoes', 'situacoes.id', '=', 'clientes.situacao')
->select('clientes.id', 'clientes.nome', 'clientes.empresa', 'clientes.email', 'situacoes.texto as situacao')
->get();
return $clientes;
}
public static function editCliente($id)
{
$cliente = DB::table('clientes')->where('id', $id)->first();
return $cliente;
}
public static function setCliente($array)
{
$insert = DB::table('clientes')->insertOrIgnore($array);
return $insert;
}
public static function updateCliente($id,$array)
{
$update = DB::table('clientes')
->where('id', $id)
->update($array);
return $update;
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', 'HomeController@index')->name("main");
Route::get('/clientes', 'ClientesController@clientes')->name("clientes");
Route::get('/cadastro-cliente', 'ClientesController@cadastro_cliente')->name("cadastro_cliente");
Route::post('/cadastrar-cliente', 'ClientesController@cadastrar_cliente')->name("cadastrar_cliente");
Route::get('/editar-cadastro/{id}', 'ClientesController@editar_cliente')->name("editar_cliente");
Route::post('/atualizar-cliente', 'ClientesController@atualizar_cliente')->name("atualizar_cliente");<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Clientes;
use Illuminate\Support\Facades\Auth;
class ClientesController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function clientes(Request $request)
{
$clientes = Clientes::getClientes();
$user = $request->session()->get('user');
return view('clientes/clientes', ['clientes' => $clientes , 'user' => $user]);
}
public function cadastro_cliente(Request $request)
{
// $user = session()->get('user');
// $user = $request->session()->get('user');
return view('clientes/cadastro_cliente');
}
public function cadastrar_cliente()
{
$insert = Clientes::setCliente($_POST);
return view('clientes/confirma_cadastro_cliente', ['insert' => $insert]);
}
public function editar_cliente($id)
{
$cliente = Clientes::editCliente($id);
return view('clientes/edita_cliente', ['cliente' => $cliente]);
}
public function atualizar_cliente()
{
$id = $_POST['id'];
if(empty($_POST['situacao']))$_POST['situacao']=0;
$update = Clientes::updateCliente($id,$_POST);
return view('clientes/confirma_update_cadastro_cliente', ['update' => $update]);
}
}<file_sep><?php
function isActiveRoute($route, $output = 'active')
{
$user2 = Auth::user();
session()->put('user', $user2);
$user = session()->get('user');
if (Route::currentRouteName() == $route) {
return $output;
}
}
| ac7d9ae26ce06e24bf05db9dff3c2dfcdf18f133 | [
"PHP"
]
| 4 | PHP | alex1980alves/cmsL6 | 5dcbf020c2967ed71b7f572b3edd9fe58f715461 | 28b568dff87f29d85cf71b969fa1cde69fc47967 |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Mail\TaskCheckout;
use Exception;
use Illuminate\Http\Request;
use App\Task;
use App\Student;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\Finder\Exception\AccessDeniedException;
class TaskController extends Controller
{
public function index() {
$tasks = Task::where('student_id', null)->get();
return $tasks;
}
/**
* заявка за получаване на курсова работа:
* трябва да включва - имена, ф. номер, тематика, номер на
* задача, е-мейл; Като резултат се връща
* е-мейл с текста на избраната задача и
* уникално ID
* @throws Exception
* @return mixed
*
*/
public function checkout(Request $request) {
$this->validate($request, [
'name' => 'required',
'fnumber' => 'required',
'email' => 'required',
'task_id' => 'required'
]);
$task_id = $request->input('task_id');
$task = Task::find($task_id);
if (!$task || $task->student_id) {
throw new Exception("Task not available for checkout!");
}
DB::beginTransaction();
$student = new Student;
$student->name = $request->input('name');
$student->fnumber = $request->input('fnumber');
$student->email = $request->input('email');
try {
$student->save();
}
catch (Exception $e) {
DB::rollback();
throw new Exception($e);
}
$task->student_id = $student->id;
$task->save();
DB::commit();
Mail::to($student->email)->send(new TaskCheckout($student, $task));
return array(
"student" => $student,
"task" => $task
);
}
public function deliver(Request $request) {
$student_id = $request->input('student_id');
$student = Student::find($student_id);
if (!$student) {
throw new Exception('Student not found!');
}
$original_filename = $request->file('delivery_file')->getClientOriginalName();
$filename = preg_replace('/\s+/', '_', "{$student->fnumber} {$student->name} {$original_filename}");
$path = $request->file('delivery_file')->storeAs('deliveries', $filename);
return $path;
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Student
* @package App
* @property string $name
* @property integer $fnumber
* @property string $email
*/
class Student extends Model
{
public $timestamps = false;
}
<file_sep>#!/bin/sh
php artisan migrate:rollback
php artisan migrate
php artisan db:seed
<file_sep>e<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
$tasks = array(
array('title'=>'Title 1', 'description'=> 'Description task 1'),
array('title'=>'Title 2', 'description'=> 'Description task 2'),
array('title'=>'Title 3', 'description'=> 'Description task 3'),
array('title'=>'Title 4', 'description'=> 'Description task 4'),
array('title'=>'Title 5', 'description'=> 'Description task 5'),
array('title'=>'Title 6', 'description'=> 'Description task 6'),
array('title'=>'Title 7', 'description'=> 'Description task 7'),
array('title'=>'Title 8', 'description'=> 'Description task 8'),
array('title'=>'Title 9', 'description'=> 'Description task 9'),
);
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('students')->truncate();
DB::table('students')->insert([
'name' => 'Unassigned',
'email' => '<EMAIL>',
'fnumber' => 0
]);
DB::table('tasks')->truncate();
DB::table('tasks')->insert($tasks);
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* Class Task
* @package App
*
* @property integer $id
* @property string $title
* @property string $description
*/
class Task extends Model
{
public $timestamps = false;
protected $hidden = ['student_id'];
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDeliveriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('deliveries', function (Blueprint $table) {
$table->increments('id');
$table->string('filename');
$table->text('mark');
$table->integer('student_id')->default(null)->unsigned();
$table->integer('task_id')->default(null)->unsigned();
$table->foreign('student_id')->references('id')->on('students');
$table->foreign('task_id')->references('id')->on('tasks');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('deliveries');
}
}
| 2c030323d87fa8be3f71d60c3cedb5473713b467 | [
"PHP",
"Shell"
]
| 6 | PHP | toshoatanasov/assignments | 4787bc75b68c720937f25cfbfeb8b223a1aa4958 | 5464346ab0eeecd2bbd94ef04e2e46d39f508f40 |
refs/heads/master | <file_sep>package helloworldsam;
public class HelloWorldSam {
public static void main(String[] args) {
}
public static void somethingFunny(){
System.out.println("How many ROman emperors does it take to run an Empire for a year? 5! XD");
}
}
| 9028e22ebca8e15adbe6d90e3f1515d4a1a02609 | [
"Java"
]
| 1 | Java | SamB7201/Github-Collab-Sam | 055c020a422539f898955a9c3503d7d688bfbc59 | 065bc8b64a94df07058d91797649aee4bbd5e9fb |
refs/heads/master | <file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Handler
*
* @ORM\Table(name="handler")
* @ORM\Entity
*/
class Handler
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $sendSpec
*
* @ORM\Column(name="send_spec", type="text", nullable=true)
*/
private $sendSpec;
/**
* @var string $sendIdent
*
* @ORM\Column(name="send_ident", type="text", nullable=true)
*/
private $sendIdent;
/**
* @var string $recvSpec
*
* @ORM\Column(name="recv_spec", type="text", nullable=true)
*/
private $recvSpec;
/**
* @var string $recvIdent
*
* @ORM\Column(name="recv_ident", type="text", nullable=true)
*/
private $recvIdent;
/**
* @var integer $rawPayload
*
* @ORM\Column(name="raw_payload", type="integer", nullable=true)
*/
private $rawPayload;
/**
* @var string $protocol
*
* @ORM\Column(name="protocol", type="text", nullable=true)
*/
private $protocol;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set sendSpec
*
* @param string $sendSpec
* @return Handler
*/
public function setSendSpec($sendSpec)
{
$this->sendSpec = $sendSpec;
return $this;
}
/**
* Get sendSpec
*
* @return string
*/
public function getSendSpec()
{
return $this->sendSpec;
}
/**
* Set sendIdent
*
* @param string $sendIdent
* @return Handler
*/
public function setSendIdent($sendIdent)
{
$this->sendIdent = $sendIdent;
return $this;
}
/**
* Get sendIdent
*
* @return string
*/
public function getSendIdent()
{
return $this->sendIdent;
}
/**
* Set recvSpec
*
* @param string $recvSpec
* @return Handler
*/
public function setRecvSpec($recvSpec)
{
$this->recvSpec = $recvSpec;
return $this;
}
/**
* Get recvSpec
*
* @return string
*/
public function getRecvSpec()
{
return $this->recvSpec;
}
/**
* Set recvIdent
*
* @param string $recvIdent
* @return Handler
*/
public function setRecvIdent($recvIdent)
{
$this->recvIdent = $recvIdent;
return $this;
}
/**
* Get recvIdent
*
* @return string
*/
public function getRecvIdent()
{
return $this->recvIdent;
}
/**
* Set rawPayload
*
* @param integer $rawPayload
* @return Handler
*/
public function setRawPayload($rawPayload)
{
$this->rawPayload = $rawPayload;
return $this;
}
/**
* Get rawPayload
*
* @return integer
*/
public function getRawPayload()
{
return $this->rawPayload;
}
/**
* Set protocol
*
* @param string $protocol
* @return Handler
*/
public function setProtocol($protocol)
{
$this->protocol = $protocol;
return $this;
}
/**
* Get protocol
*
* @return string
*/
public function getProtocol()
{
return $this->protocol;
}
}<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Host
*
* @ORM\Table(name="host")
* @ORM\Entity
*/
class Host
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var integer $serverId
*
* @ORM\Column(name="server_id", type="integer", nullable=true)
*/
private $serverId;
/**
* @var boolean $maintenance
*
* @ORM\Column(name="maintenance", type="boolean", nullable=true)
*/
private $maintenance;
/**
* @var string $name
*
* @ORM\Column(name="name", type="text", nullable=true)
*/
private $name;
/**
* @var string $matching
*
* @ORM\Column(name="matching", type="text", nullable=true)
*/
private $matching;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set serverId
*
* @param integer $serverId
* @return Host
*/
public function setServerId($serverId)
{
$this->serverId = $serverId;
return $this;
}
/**
* Get serverId
*
* @return integer
*/
public function getServerId()
{
return $this->serverId;
}
/**
* Set maintenance
*
* @param boolean $maintenance
* @return Host
*/
public function setMaintenance($maintenance)
{
$this->maintenance = $maintenance;
return $this;
}
/**
* Get maintenance
*
* @return boolean
*/
public function getMaintenance()
{
return $this->maintenance;
}
/**
* Set name
*
* @param string $name
* @return Host
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set matching
*
* @param string $matching
* @return Host
*/
public function setMatching($matching)
{
$this->matching = $matching;
return $this;
}
/**
* Get matching
*
* @return string
*/
public function getMatching()
{
return $this->matching;
}
}<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Route
*
* @ORM\Table(name="route")
* @ORM\Entity
*/
class Route
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $path
*
* @ORM\Column(name="path", type="text", nullable=true)
*/
private $path;
/**
* @var boolean $reversed
*
* @ORM\Column(name="reversed", type="boolean", nullable=true)
*/
private $reversed;
/**
* @var integer $hostId
*
* @ORM\Column(name="host_id", type="integer", nullable=true)
*/
private $hostId;
/**
* @var integer $targetId
*
* @ORM\Column(name="target_id", type="integer", nullable=true)
*/
private $targetId;
/**
* @var string $targetType
*
* @ORM\Column(name="target_type", type="text", nullable=true)
*/
private $targetType;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* @param string $path
* @return Route
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set reversed
*
* @param boolean $reversed
* @return Route
*/
public function setReversed($reversed)
{
$this->reversed = $reversed;
return $this;
}
/**
* Get reversed
*
* @return boolean
*/
public function getReversed()
{
return $this->reversed;
}
/**
* Set hostId
*
* @param integer $hostId
* @return Route
*/
public function setHostId($hostId)
{
$this->hostId = $hostId;
return $this;
}
/**
* Get hostId
*
* @return integer
*/
public function getHostId()
{
return $this->hostId;
}
/**
* Set targetId
*
* @param integer $targetId
* @return Route
*/
public function setTargetId($targetId)
{
$this->targetId = $targetId;
return $this;
}
/**
* Get targetId
*
* @return integer
*/
public function getTargetId()
{
return $this->targetId;
}
/**
* Set targetType
*
* @param string $targetType
* @return Route
*/
public function setTargetType($targetType)
{
$this->targetType = $targetType;
return $this;
}
/**
* Get targetType
*
* @return string
*/
public function getTargetType()
{
return $this->targetType;
}
}<file_sep><?php
namespace Mongrel;
class Request
{
const FORMAT = '_^(?<uuid>[a-f0-9\-]{36}) (?<browser>[0-9]+) (?<path>\S+) (?<hsize>[0-9]+):(?<headers>{(.+)}),(?<bsize>[0-9]+):(?<body>.*),$_';
private $data, $uuid, $browser, $path, $headers, $body;
/**
* Create a Mongrel request
*
* @param string $message
* @throws RequestException
*/
public function __construct( $message )
{
if( !is_string( $message ) || !preg_match( self::FORMAT, $message, $this->data ) )
{
throw new RequestException( 'Invalid format. Failed to parse mongrel request' );
}
$this->uuid = new Request\Uuid( $this->data[ 'uuid' ] );
$this->browser = new Request\Browser( $this->data[ 'browser' ] );
$this->path = new Request\Path( $this->data[ 'path' ] );
$this->headers = new Request\Headers( $this->data[ 'headers' ] );
$this->body = new Request\Body( $this->data[ 'body' ] );
}
/**
* Get zmq socket uuid
*
* @return Request\Uuid
*/
public function getUuid()
{
return $this->uuid;
}
/**
* Get mongrel browser id
*
* @return Request\Browser
*/
public function getBrowser()
{
return $this->browser;
}
/**
* Get URI
*
* @return Request\Path
*/
public function getPath()
{
return $this->path;
}
/**
* Get request headers
*
* @return Request\Headers
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get request body
*
* @return Request\Body
*/
public function getBody()
{
return $this->body;
}
}<file_sep><?php
namespace Mongrel\Request;
class PathTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( 1 ),
array( null ),
array( array() ),
array( new \stdClass )
);
}
public function validDataProvider()
{
return array(
array( '/favicon.ico' )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Request\Path::__construct
*/
public function testConstructorInvalid( $pathString )
{
$this->setExpectedException( 'Mongrel\RequestException' );
new Path( $pathString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Request\Path::__construct
*/
public function testConstructor( $pathString )
{
new Path( $pathString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Request\Path::__toString
*/
public function testTostring( $pathString )
{
$path = new Path( $pathString );
$this->assertEquals( $pathString, (string) $path );
$this->assertEquals( $pathString, $path->__toString() );
}
}<file_sep><?php
namespace Mongrel\Http;
class RequestTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\Http\Request::__construct
*/
public function testConstructor_InvalidMongrelHeaders()
{
$this->setExpectedException( 'InvalidArgumentException' );
$mockMongrelRequest = $this->getMockBuilder( 'Mongrel\Request' )
->disableOriginalConstructor()
->getMock();
$mockMongrelRequest->expects( $this->exactly( 1 ) )
->method( 'getHeaders' )
->will( $this->returnValue( null ) );
new Request( $mockMongrelRequest );
}
/**
* @covers \Mongrel\Http\Request::__construct
*/
public function testConstructor()
{
$mockMongrelRequest = $this->getMockBuilder( 'Mongrel\Request' )
->disableOriginalConstructor()
->getMock();
$mockMongrelRequest->expects( $this->exactly( 1 ) )
->method( 'getHeaders' )
->will( $this->returnValue( array( 'a' => 'b' ) ) );
$request = new Request( $mockMongrelRequest );
$this->assertAttributeInstanceOf( '\Mongrel\Http\Headers', 'headers', $request );
$this->assertAttributeInstanceOf( '\HttpQueryString', 'query', $request );
}
/**
* @covers \Mongrel\Http\Request::__construct
*/
public function testConstructor_ParseQueryKey()
{
$mockMongrelRequest = $this->getMockBuilder( 'Mongrel\Request' )
->disableOriginalConstructor()
->getMock();
$mockMongrelRequest->expects( $this->exactly( 1 ) )
->method( 'getHeaders' )
->will( $this->returnValue( array( 'QUERY' => 'foo=bar&bar=baz' ) ) );
$request = new Request( $mockMongrelRequest );
$this->assertEquals( 'foo=bar&bar=baz', $request->getQuery()->get() );
}
/**
* @covers \Mongrel\Http\Request::getMongrelRequest
*/
public function testGetMongrelRequest()
{
$mockMongrelRequest = $this->getMockBuilder( 'Mongrel\Request' )
->disableOriginalConstructor()
->getMock();
$mockMongrelRequest->expects( $this->exactly( 1 ) )
->method( 'getHeaders' )
->will( $this->returnValue( array( 'test' => 'test' ) ) );
$request = new Request( $mockMongrelRequest );
$this->assertSame( $mockMongrelRequest, $request->getMongrelRequest() );
}
/**
* @covers \Mongrel\Http\Request::getHeaders
*/
public function testGetHeaders()
{
$mockMongrelRequest = $this->getMockBuilder( 'Mongrel\Request' )
->disableOriginalConstructor()
->getMock();
$mockMongrelRequest->expects( $this->exactly( 1 ) )
->method( 'getHeaders' )
->will( $this->returnValue( array( 'test' => 'test' ) ) );
$request = new Request( $mockMongrelRequest );
$this->assertSame( array( 'test' => 'test' ), $request->getHeaders()->getArrayCopy() );
}
/**
* @covers \Mongrel\Http\Request::getQuery
*/
public function testGetQuery()
{
$mockMongrelRequest = $this->getMockBuilder( 'Mongrel\Request' )
->disableOriginalConstructor()
->getMock();
$mockMongrelRequest->expects( $this->exactly( 1 ) )
->method( 'getHeaders' )
->will( $this->returnValue( array( 'QUERY' => 'foo=bar' ) ) );
$request = new Request( $mockMongrelRequest );
$this->assertSame( $mockMongrelRequest, $request->getMongrelRequest() );
$this->assertSame( 'foo=bar', $request->getQuery()->toString() );
}
}<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Log
*
* @ORM\Table(name="log")
* @ORM\Entity
*/
class Log
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $who
*
* @ORM\Column(name="who", type="text", nullable=true)
*/
private $who;
/**
* @var string $what
*
* @ORM\Column(name="what", type="text", nullable=true)
*/
private $what;
/**
* @var string $location
*
* @ORM\Column(name="location", type="text", nullable=true)
*/
private $location;
/**
* @var \DateTime $happenedAt
*
* @ORM\Column(name="happened_at", type="datetime", nullable=true)
*/
private $happenedAt;
/**
* @var string $how
*
* @ORM\Column(name="how", type="text", nullable=true)
*/
private $how;
/**
* @var string $why
*
* @ORM\Column(name="why", type="text", nullable=true)
*/
private $why;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set who
*
* @param string $who
* @return Log
*/
public function setWho($who)
{
$this->who = $who;
return $this;
}
/**
* Get who
*
* @return string
*/
public function getWho()
{
return $this->who;
}
/**
* Set what
*
* @param string $what
* @return Log
*/
public function setWhat($what)
{
$this->what = $what;
return $this;
}
/**
* Get what
*
* @return string
*/
public function getWhat()
{
return $this->what;
}
/**
* Set location
*
* @param string $location
* @return Log
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* @return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set happenedAt
*
* @param \DateTime $happenedAt
* @return Log
*/
public function setHappenedAt($happenedAt)
{
$this->happenedAt = $happenedAt;
return $this;
}
/**
* Get happenedAt
*
* @return \DateTime
*/
public function getHappenedAt()
{
return $this->happenedAt;
}
/**
* Set how
*
* @param string $how
* @return Log
*/
public function setHow($how)
{
$this->how = $how;
return $this;
}
/**
* Get how
*
* @return string
*/
public function getHow()
{
return $this->how;
}
/**
* Set why
*
* @param string $why
* @return Log
*/
public function setWhy($why)
{
$this->why = $why;
return $this;
}
/**
* Get why
*
* @return string
*/
public function getWhy()
{
return $this->why;
}
}<file_sep><?php
namespace Mongrel\Request;
use \Mongrel\RequestException;
class Browser
{
private $id;
/**
* Create a Mongrel Browser Object
*
* @param numeric $browserId
* @throws RequestException
*/
public function __construct( $browserId )
{
if( !is_numeric( $browserId ) )
{
throw new RequestException( 'Invalid format. Failed to parse mongrel browser id' );
}
$this->id = $browserId;
}
/**
* Get Mongrel Browser Id
*
* @return int
*/
public function __toString()
{
return (string) $this->id;
}
}<file_sep><?php
namespace Mongrel\Http;
class Request
{
private $mongrelRequest;
private $headers, $query;
/**
* Create an HTTP request
*
* @param \Mongrel\Request $request
*/
public function __construct( \Mongrel\Request $request )
{
$this->mongrelRequest = $request;
$this->headers = new Headers( $this->mongrelRequest->getHeaders() );
$this->query = new \HttpQueryString( false );
if( $this->headers->offsetExists( 'QUERY' ) )
{
$this->query->set( $this->headers->offsetGet( 'QUERY' ) );
}
}
/**
* Get Mongrel request object
*
* @return \Mongrel\Request
*/
public function getMongrelRequest()
{
return $this->mongrelRequest;
}
/**
* Get request headers
*
* @return \Mongrel\Http\Headers
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get request query string object
*
* @return \HttpQueryString
*/
public function getQuery()
{
return $this->query;
}
}<file_sep>#!/bin/sh
sudo apt-get update
sudo apt-get install -y git-core php5-common php5-dev php5-cli php5-uuid
cd /tmp
git clone git://github.com/mkoppanen/php-zmq.git
cd php-zmq
git pull origin master
phpize
./configure
make
sudo make install
PHP_INI_PATH=$(php --ini | grep "Scan for additional" | sed -e "s|.*:\s*||")
echo "extension=zmq.so" | sudo tee $PHP_INI_PATH/zmq.ini
clear
php -i | grep zmq
echo "Installation Complete"
echo "The Imagick extension for PHP can provide segmentation faults on some systems"
echo "Optionally remove imagick with: sudo apt-get remove php5-imagick"<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Directory
*
* @ORM\Table(name="directory")
* @ORM\Entity
*/
class Directory
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $base
*
* @ORM\Column(name="base", type="text", nullable=true)
*/
private $base;
/**
* @var string $indexFile
*
* @ORM\Column(name="index_file", type="text", nullable=true)
*/
private $indexFile;
/**
* @var string $defaultCtype
*
* @ORM\Column(name="default_ctype", type="text", nullable=true)
*/
private $defaultCtype;
/**
* @var integer $cacheTtl
*
* @ORM\Column(name="cache_ttl", type="integer", nullable=true)
*/
private $cacheTtl;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set base
*
* @param string $base
* @return Directory
*/
public function setBase($base)
{
$this->base = $base;
return $this;
}
/**
* Get base
*
* @return string
*/
public function getBase()
{
return $this->base;
}
/**
* Set indexFile
*
* @param string $indexFile
* @return Directory
*/
public function setIndexFile($indexFile)
{
$this->indexFile = $indexFile;
return $this;
}
/**
* Get indexFile
*
* @return string
*/
public function getIndexFile()
{
return $this->indexFile;
}
/**
* Set defaultCtype
*
* @param string $defaultCtype
* @return Directory
*/
public function setDefaultCtype($defaultCtype)
{
$this->defaultCtype = $defaultCtype;
return $this;
}
/**
* Get defaultCtype
*
* @return string
*/
public function getDefaultCtype()
{
return $this->defaultCtype;
}
/**
* Set cacheTtl
*
* @param integer $cacheTtl
* @return Directory
*/
public function setCacheTtl($cacheTtl)
{
$this->cacheTtl = $cacheTtl;
return $this;
}
/**
* Get cacheTtl
*
* @return integer
*/
public function getCacheTtl()
{
return $this->cacheTtl;
}
}<file_sep><?php
namespace Mongrel;
class Client
{
const FTYPE = \ZMQ::SOCKET_UPSTREAM;
const BTYPE = \ZMQ::SOCKET_PUB;
private $frontend, $backend;
/**
* Generic client interface for Mongrel2
*
* @param \ZMQContext $context
* @param Dsn $frontDsn
* @param Dsn $backDsn
*/
public function __construct( \ZMQContext $context, Dsn $front, Dsn $back )
{
// Listen for requests
$this->frontend = $context->getSocket( self::FTYPE, null );
$this->frontend->connect( $front->toString() );
// Send responses
$this->backend = $context->getSocket( self::BTYPE, null );
$this->backend->connect( $back->toString() );
}
/**
* Receives a message
*
* Receive a message from Mongrel. By default receiving will block.
*
* @return \Mongrel\Request Returns the Mongrel request.
*/
public function recv()
{
return new \Mongrel\Request( $this->frontend->recv() );
}
/**
* Sends a message
*
* Send a message to Mongrel.
*
* @param \Mongrel\Response $response The Mongrel response to send.
*
* @return \Mongrel\Client Returns the current object.
*/
public function send( \Mongrel\Response $response )
{
$this->backend->send( $response->getMessage() );
return $this;
}
}
<file_sep><?php
namespace Mongrel;
use \Mongrel\Request,
\Mongrel\ResponseException;
class Response
{
private $uuid, $browsers, $body;
/**
* Create a Mongrel response
*
* @param Request\Uuid $uuid
* @param Request\BrowserStack $browsers
*/
public function __construct( Request\Uuid $uuid, Request\BrowserStack $browsers )
{
$this->uuid = $uuid;
$this->browsers = $browsers;
}
/**
* Render response in Mongrel format
*
* @return string
*/
public function getMessage()
{
if( !$this->browsers->count() )
{
throw new ResponseException( 'No browsers specified' );
}
return sprintf( '%s %d:%s, %s', $this->uuid, strlen( $this->browsers ), $this->browsers, $this->body );
}
/**
* Set response body
*
* @param string $body
*/
public function setBody( $body )
{
if( !is_string( $body ) )
{
throw new ResponseException( 'Invalid format. Response body must be a string' );
}
$this->body = $body;
}
}<file_sep><?php
namespace Mongrel\Request;
use \Mongrel\RequestException;
class Headers extends \ArrayObject
{
/**
* Create a Mongrel Request Headers Object
*
* @param string $headers
* @throws RequestException
*/
public function __construct( $headers )
{
if( !is_string( $headers ) )
{
throw new RequestException( 'Failed to parse mongrel request headers' );
}
$headers = json_decode( $headers, true );
if( !is_array( $headers ) )
{
throw new RequestException( 'Invalid JSON format. Failed to parse mongrel request headers' );
}
parent::__construct( $headers );
}
}<file_sep><?php
namespace Mongrel;
class DsnException extends \RuntimeException {}<file_sep><?php
namespace Mongrel;
class Dsn
{
const FORMAT = '_^(?P<protocol>\w+)://(?P<ip>[\d\.\*]+):(?P<port>\d{1,5})$_';
private $protocol, $ip, $port;
/**
* Create a new DSN
*
* @param string $dsn
* @throws DsnException
*/
public function __construct( $dsn )
{
if( !preg_match( self::FORMAT, $dsn, $matches ) )
{
throw new DsnException( 'Invalid DSN' );
}
$this->protocol = $matches[ 'protocol' ];
$this->ip = $matches[ 'ip' ];
$this->port = $matches[ 'port' ];
}
/**
* Get protocol section
*
* @return string
*/
public function getProtocol()
{
return $this->protocol;
}
/**
* Get IP section
*
* @return string
*/
public function getIp()
{
return $this->ip;
}
/**
* Get port section
*
* @return string
*/
public function getPort()
{
return $this->port;
}
/**
* Return DSN as string
*
* @return string
*/
public function toString()
{
return sprintf( '%s://%s:%s', $this->protocol, $this->ip, $this->port );
}
}
<file_sep><?php
namespace Mongrel\Http;
use \Mongrel\ResponseException;
class Body
{
private $body;
/**
* Create an HTTP Response Body Object
*
* @param string $body
* @throws RequestException
*/
public function __construct( $body )
{
if( !is_string( $body ) )
{
throw new ResponseException( 'Invalid response body' );
}
$this->body = $body;
}
/**
* Get HTTP Response Body
*
* @return string
*/
public function __toString()
{
return (string) $this->body;
}
}<file_sep>#!/bin/sh
sudo apt-get update
sudo apt-get install -y php5-dev libmagic1 libmagic-dev curl libcurl3 libcurl3-openssl-dev
#sudo pecl update-channels
sudo pecl install pecl_http
PHP_INI_PATH=$(php --ini | grep "Scan for additional" | sed -e "s|.*:\s*||")
echo "extension=http.so" | sudo tee $PHP_INI_PATH/http.ini
clear
php -i | grep HTTP
echo "Installation Complete"<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Statistic
*
* @ORM\Table(name="statistic")
* @ORM\Entity
*/
class Statistic
{
/**
* @var string $otherType
*
* @ORM\Column(name="other_type", type="text", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $otherType;
/**
* @var integer $otherId
*
* @ORM\Column(name="other_id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $otherId;
/**
* @var string $name
*
* @ORM\Column(name="name", type="text", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $name;
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
*/
private $id;
/**
* @var float $sum
*
* @ORM\Column(name="sum", type="float", nullable=true)
*/
private $sum;
/**
* @var float $sumsq
*
* @ORM\Column(name="sumsq", type="float", nullable=true)
*/
private $sumsq;
/**
* @var integer $n
*
* @ORM\Column(name="n", type="integer", nullable=true)
*/
private $n;
/**
* @var float $min
*
* @ORM\Column(name="min", type="float", nullable=true)
*/
private $min;
/**
* @var float $max
*
* @ORM\Column(name="max", type="float", nullable=true)
*/
private $max;
/**
* @var float $mean
*
* @ORM\Column(name="mean", type="float", nullable=true)
*/
private $mean;
/**
* @var float $sd
*
* @ORM\Column(name="sd", type="float", nullable=true)
*/
private $sd;
/**
* Set otherType
*
* @param string $otherType
* @return Statistic
*/
public function setOtherType($otherType)
{
$this->otherType = $otherType;
return $this;
}
/**
* Get otherType
*
* @return string
*/
public function getOtherType()
{
return $this->otherType;
}
/**
* Set otherId
*
* @param integer $otherId
* @return Statistic
*/
public function setOtherId($otherId)
{
$this->otherId = $otherId;
return $this;
}
/**
* Get otherId
*
* @return integer
*/
public function getOtherId()
{
return $this->otherId;
}
/**
* Set name
*
* @param string $name
* @return Statistic
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set id
*
* @param integer $id
* @return Statistic
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set sum
*
* @param float $sum
* @return Statistic
*/
public function setSum($sum)
{
$this->sum = $sum;
return $this;
}
/**
* Get sum
*
* @return float
*/
public function getSum()
{
return $this->sum;
}
/**
* Set sumsq
*
* @param float $sumsq
* @return Statistic
*/
public function setSumsq($sumsq)
{
$this->sumsq = $sumsq;
return $this;
}
/**
* Get sumsq
*
* @return float
*/
public function getSumsq()
{
return $this->sumsq;
}
/**
* Set n
*
* @param integer $n
* @return Statistic
*/
public function setN($n)
{
$this->n = $n;
return $this;
}
/**
* Get n
*
* @return integer
*/
public function getN()
{
return $this->n;
}
/**
* Set min
*
* @param float $min
* @return Statistic
*/
public function setMin($min)
{
$this->min = $min;
return $this;
}
/**
* Get min
*
* @return float
*/
public function getMin()
{
return $this->min;
}
/**
* Set max
*
* @param float $max
* @return Statistic
*/
public function setMax($max)
{
$this->max = $max;
return $this;
}
/**
* Get max
*
* @return float
*/
public function getMax()
{
return $this->max;
}
/**
* Set mean
*
* @param float $mean
* @return Statistic
*/
public function setMean($mean)
{
$this->mean = $mean;
return $this;
}
/**
* Get mean
*
* @return float
*/
public function getMean()
{
return $this->mean;
}
/**
* Set sd
*
* @param float $sd
* @return Statistic
*/
public function setSd($sd)
{
$this->sd = $sd;
return $this;
}
/**
* Get sd
*
* @return float
*/
public function getSd()
{
return $this->sd;
}
}<file_sep><?php
namespace Mongrel\Http;
class ResponseTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\Http\Response::__construct
*/
public function testConstructorAndGetters()
{
$response = new Response( 'a', array( 'b' => 'c' ), '404 Not Found', 'HTTP/1.0' );
$this->assertEquals( 'a', $response->getBody() );
$this->assertEquals( array( 'b' => 'c', 'Content-Length' => 1 ), $response->getHeaders()->getArrayCopy() );
$this->assertEquals( '404 Not Found', $response->getStatus() );
$this->assertEquals( 'HTTP/1.0', $response->getProtocol() );
}
/**
* @covers \Mongrel\Http\Response::getMessage
*/
public function testGetMessage()
{
$response = new Response( '<p>Hello World</p>', array( 'Content-Type' => 'text/html' ), '200 OK', 'HTTP/1.1' );
$expected = "HTTP/1.1 200 OK\r\n";
$expected .= "Content-Type: text/html\r\n";
$expected .= "Content-Length: ". mb_strlen( '<p>Hello World</p>' ) ."\r\n";
$expected .= "\r\n";
$expected .= '<p>Hello World</p>';
$this->assertEquals( $expected, $response->getMessage() );
}
/**
* @covers \Mongrel\Http\Response::getBody
*/
public function testGetBody()
{
$response = new Response( '<p>Hello World</p>', array( 'Content-Type' => 'text/html' ), '200 OK', 'HTTP/1.1' );
$this->assertEquals( '<p>Hello World</p>', (string) $response->getBody() );
}
/**
* @covers \Mongrel\Http\Response::getHeaders
*/
public function testGetHeaders()
{
$response = new Response( '<p>Hello World</p>', array( 'Content-Type' => 'text/html' ), '200 OK', 'HTTP/1.1' );
$this->assertEquals( array( 'Content-Type' => 'text/html', 'Content-Length' => 18 ), $response->getHeaders()->getArrayCopy() );
}
/**
* @covers \Mongrel\Http\Response::getStatus
*/
public function testGetStatus()
{
$response = new Response( '<p>Hello World</p>', array( 'Content-Type' => 'text/html' ), '200 OK', 'HTTP/1.1' );
$this->assertEquals( '200 OK', (string) $response->getStatus() );
}
/**
* @covers \Mongrel\Http\Response::getProtocol
*/
public function testGetProtocol()
{
$response = new Response( '<p>Hello World</p>', array( 'Content-Type' => 'text/html' ), '200 OK', 'HTTP/1.1' );
$this->assertEquals( 'HTTP/1.1', (string) $response->getProtocol() );
}
}<file_sep><?php
namespace Mongrel\Http;
use \Mongrel\Request\Uuid,
\Mongrel\Request\Browser,
\Mongrel\Request\BrowserStack;
class Client
{
private $client;
/**
* Maps Mongrel request/responses to HTTP request/responses and vice versa
*
* @param \Mongrel\Client $client
*/
public function __construct( \Mongrel\Client $client )
{
$this->client = $client;
}
/**
* Receives a message
*
* @return Mongrel\Http\Request Returns the HTTP request object.
*/
public function recv()
{
// Wait for a new message from Mongrel
$request = $this->client->recv();
return new Request( $request );
}
/**
* Reply to the sender of a request
*
* @param Mongrel\Http\Response $httpResponse The HTTP response to send.
* @param Mongrel\Http\Request $httpRequest The HTTP request to reply to.
*
* @return Client Returns the current object.
*/
public function reply( Response $httpResponse, Request $httpRequest )
{
return $this->send(
$httpResponse,
$httpRequest->getMongrelRequest()->getUuid(),
$httpRequest->getMongrelRequest()->getBrowser()
);
}
/**
* Sends a message
*
* @param Mongrel\Http\Response $httpResponse The HTTP response to send.
* @param Mongrel\Request\Uuid $uuid The Zmq uuid to send the message to.
* @param Mongrel\Request\Browser $browser The browser to send the message to.
*
* @return Client Returns the current object.
*/
public function send( Response $httpResponse, Uuid $uuid, Browser $browser )
{
$browsers = new BrowserStack;
$browsers->attach( $browser );
return $this->sendMulti( $httpResponse, $uuid, $browsers );
}
/**
* Sends a message to multiple browsers simultaneously
*
* @param Mongrel\Http\Response $httpResponse The HTTP response to send.
* @param Mongrel\Request\Uuid $uuid The Zmq uuid to send the message to.
* @param Mongrel\Request\BrowserStack $browsers The browsers to send the message to.
*
* @return Client Returns the current object.
*/
public function sendMulti( Response $httpResponse, Uuid $uuid, BrowserStack $browsers )
{
$response = new \Mongrel\Response( $uuid, $browsers );
$response->setBody( $httpResponse->getMessage() );
return $this->client->send( $response );
}
}
<file_sep><?php
namespace Mongrel;
class ResponseExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\ResponseException::__construct
*/
public function testConstructor()
{
$exception = new ResponseException( 'test' );
$this->assertTrue( $exception instanceof \RuntimeException );
$this->setExpectedException( 'Mongrel\ResponseException' );
throw $exception;
}
}<file_sep><?php
namespace Mongrel\Request;
use \Mongrel\RequestException;
class Uuid
{
const FORMAT = '_^(?<uuid>[a-f0-9\-]{36})$_';
private $uuid;
/**
* Create a Mongrel Uuid Object
*
* @param string $uuid
* @throws RequestException
*/
public function __construct( $uuid )
{
if( !preg_match( self::FORMAT, $uuid ) )
{
throw new RequestException( 'Invalid format. Failed to parse mongrel uuid' );
}
$this->uuid = $uuid;
}
/**
* Get zmq socket uuid
*
* @return string
*/
public function __toString()
{
return (string) $this->uuid;
}
}<file_sep><?php
namespace Mongrel\Http;
use \Mongrel\ResponseException;
class Status
{
const FORMAT = '_^(?<code>[0-9]{3}) (?<status>.+)$_';
private $status;
/**
* Create an HTTP Response Body Object
*
* @param string $status
* @throws RequestException
*/
public function __construct( $status )
{
if( !is_string( $status ) || !preg_match( self::FORMAT, $status ) )
{
throw new ResponseException( 'Invalid response status line' );
}
$this->status = $status;
}
/**
* Get HTTP Response Body
*
* @return string
*/
public function __toString()
{
return (string) $this->status;
}
}<file_sep><?php
namespace Mongrel\Http;
class BodyTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( 1 ),
array( null ),
array( array() ),
array( new \stdClass )
);
}
public function validDataProvider()
{
return array(
array( 'hello world' )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Http\Body::__construct
*/
public function testConstructorInvalid( $bodyString )
{
$this->setExpectedException( 'Mongrel\ResponseException' );
new Body( $bodyString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Http\Body::__construct
*/
public function testConstructor( $bodyString )
{
new Body( $bodyString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Http\Body::__toString
*/
public function testTostring( $bodyString )
{
$body = new Body( $bodyString );
$this->assertEquals( $bodyString, (string) $body );
$this->assertEquals( $bodyString, $body->__toString() );
}
}<file_sep><?php
namespace Mongrel;
class RequestExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\RequestException::__construct
*/
public function testConstructor()
{
$exception = new RequestException( 'test' );
$this->assertTrue( $exception instanceof \RuntimeException );
$this->setExpectedException( 'Mongrel\RequestException' );
throw $exception;
}
}<file_sep><?php
namespace Mongrel\Http;
class Response
{
const EOL = "\r\n";
private $protocol, $status, $headers, $body;
/**
* Create an HTTP response
*
* @param string $body
* @param array $headers
* @param string $status
* @param string $protocol
*/
public function __construct( $body, $headers = null, $status = null, $protocol = null )
{
$this->body = new Body( $body );
$this->headers = new Headers( $headers ?: array() );
$this->status = new Status( $status ?: '200 OK' );
$this->protocol = new Protocol( $protocol ?: 'HTTP/1.1' );
$this->headers->offsetSet( 'Content-Length', mb_strlen( $this->body ) );
}
/**
* Build HTTP response message
*
* @return string
*/
public function getMessage()
{
$data = sprintf( '%s %s', $this->protocol, $this->status ) . self::EOL;
foreach( $this->headers as $key => $value )
{
$data .= sprintf( '%s: %s', $key, $value ) . self::EOL;
}
return $data . self::EOL . $this->body;
}
/**
* Get response body
*
* @return Body $body
*/
public function getBody()
{
return $this->body;
}
/**
* Get response headers
*
* @return Headers $headers
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get response status
*
* @return Status $status
*/
public function getStatus()
{
return $this->status;
}
/**
* Get response protocol
*
* @return Protocol $protocol
*/
public function getProtocol()
{
return $this->protocol;
}
}<file_sep><?php
namespace Mongrel\Http;
class ClientTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
extension_loaded( 'zmq' ) || $this->markTestSkipped( 'Zmq PHP extension not loaded' );
$this->mongrelClient = $this->getMockBuilder( 'Mongrel\Client' )
->disableOriginalConstructor()
->getMock();
$message = '288c0bca-f46c-46dc-b15a-bdd581c30e38 99 /favicon.ico 23:{"PATH":"/favicon.ico"},0:foo=bar,';
$this->mongrelRequest = $this->getMock( 'Mongrel\Request', null, array( $message ) );
}
/**
* @covers \Mongrel\Http\Client::__construct
*/
public function testConstructor_InvalidParam()
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Client( array() );
}
/**
* @covers \Mongrel\Http\Client::__construct
*/
public function testConstructor()
{
$client = new Client( $this->mongrelClient );
$this->assertAttributeSame( $this->mongrelClient, 'client', $client );
}
/**
* @covers \Mongrel\Http\Client::recv
*/
public function testRecv()
{
$this->mongrelClient->expects( $this->once() )
->method( 'recv' )
->will( $this->returnValue( $this->mongrelRequest ) );
$client = new Client( $this->mongrelClient );
$recv = $client->recv();
$this->assertEquals( 'Mongrel\Http\Request', get_class( $recv ) );
$this->assertSame( $this->mongrelRequest, $recv->getMongrelRequest() );
}
/**
* @covers \Mongrel\Http\Client::send
* @todo improve test
*/
public function testSend()
{
$httpResponse = $this->getMock( 'Mongrel\Http\Response', array( 'getMessage' ), array( 'test' ) );
$httpResponse->expects( $this->once() )
->method( 'getMessage' )
->will( $this->returnValue( 'test' ) );
$this->mongrelClient->expects( $this->once() )
->method( 'send' );
$client = new Client( $this->mongrelClient );
$client->send( $httpResponse, $this->mongrelRequest->getUuid(), $this->mongrelRequest->getBrowser() );
}
/**
* @depends testSend
* @covers \Mongrel\Http\Client::sendMulti
* @todo improve test
*/
public function testSendMulti()
{
$httpResponse = $this->getMock( 'Mongrel\Http\Response', array( 'getMessage' ), array( 'test' ) );
$httpResponse->expects( $this->once() )
->method( 'getMessage' )
->will( $this->returnValue( 'test' ) );
$this->mongrelClient->expects( $this->once() )
->method( 'send' );
$client = new Client( $this->mongrelClient );
$client->sendMulti( $httpResponse, $this->mongrelRequest->getUuid(), new \Mongrel\Request\BrowserStack( $this->mongrelRequest->getBrowser() ) );
}
/**
* @depends testRecv
* @depends testSend
* @covers \Mongrel\Http\Client::reply
*/
public function testReply()
{
$this->mongrelClient->expects( $this->once() )
->method( 'recv' )
->will( $this->returnValue( $this->mongrelRequest ) );
$client = new Client( $this->mongrelClient );
$recv = $client->recv();
$httpResponse = $this->getMock( 'Mongrel\Http\Response', array( 'getMessage' ), array( 'test' ) );
$httpResponse->expects( $this->once() )
->method( 'getMessage' )
->will( $this->returnValue( 'test' ) );
$this->mongrelClient->expects( $this->once() )
->method( 'send' );
$client = new Client( $this->mongrelClient );
$client->reply( $httpResponse, $recv );
}
}<file_sep><?php
namespace Mongrel;
class ResponseTest extends \PHPUnit_Framework_TestCase
{
static $uuid = '288c0bca-f46c-46dc-b15a-bdd581c30e38';
public static function dataProvider()
{
$uuid = new Request\Uuid( self::$uuid );
$browsers = new Request\BrowserStack;
$browsers->attach( new Request\Browser( 1 ) );
$browsers->attach( new Request\Browser( 2 ) );
$response = new Response( $uuid, $browsers );
return array( array( $response ) );
}
/**
* @covers \Mongrel\Response::__construct
*/
public function testConstructor_ParamIsNotString()
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Response( array() );
}
/**
* @covers \Mongrel\Response::__construct
*/
public function testConstructor_MissingParams()
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Response;
}
/**
* @covers \Mongrel\Response::__construct
*/
public function testConstructor_InvalidTypeParams()
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Response( new \stdClass, new \stdClass );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Response::__construct
*/
public function testConstructor( Response $response )
{
$this->assertInstanceOf( 'Mongrel\Response', $response );
$this->assertAttributeInstanceOf( '\Mongrel\Request\Uuid', 'uuid', $response );
$this->assertAttributeInstanceOf( '\Mongrel\Request\BrowserStack', 'browsers', $response );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Response::getMessage
*/
public function testGetMessage_NoBrowsersSpecified( Response $response )
{
$this->setExpectedException( 'Mongrel\ResponseException' );
$response = new Response( new Request\Uuid( self::$uuid ), new Request\BrowserStack );
$response->getMessage();
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Response::getMessage
*/
public function testGetMessage( Response $response )
{
$response->setBody( 'test' );
$this->assertEquals( self::$uuid . ' 3:1 2, test', $response->getMessage() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Response::setBody
*/
public function testSetBody_InvalidParam( Response $response )
{
$this->setExpectedException( 'Mongrel\ResponseException' );
$response->setBody( array() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Response::setBody
*/
public function testSetBody( Response $response )
{
$response->setBody( 'test' );
$this->assertAttributeSame( 'test', 'body', $response );
}
}<file_sep><?php
namespace Mongrel;
class DsnExceptionTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\DsnException::__construct
*/
public function testConstructor()
{
$exception = new DsnException( 'test' );
$this->assertTrue( $exception instanceof \RuntimeException );
$this->setExpectedException( 'Mongrel\DsnException' );
throw $exception;
}
}<file_sep><?php
namespace Mongrel\Http;
class StatusTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( 'hello world' ),
array( array() ),
array( null ),
array( 1 ),
array( new \stdClass )
);
}
public function validDataProvider()
{
return array(
array( '200 OK' )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Http\Status::__construct
*/
public function testConstructorInvalid( $statusString )
{
$this->setExpectedException( 'Mongrel\ResponseException' );
new Status( $statusString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Http\Status::__construct
*/
public function testConstructor( $statusString )
{
new Status( $statusString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Http\Status::__toString
*/
public function testTostring( $statusString )
{
$status = new Status( $statusString );
$this->assertEquals( $statusString, (string) $status );
$this->assertEquals( $statusString, $status->__toString() );
}
}<file_sep>#!/usr/bin/php
<?php
/* Report 0MQ version
*
* @author <NAME> <ian(dot)barber(at)gmail(dot)com>
*/
if( class_exists( 'ZMQ' ) && defined( 'ZMQ::LIBZMQ_VER' ) )
{
echo ZMQ::LIBZMQ_VER, PHP_EOL;
}
else echo 'ZMQ Not Found';<file_sep><?php
namespace Mongrel\Http;
class HeadersTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\Http\Headers::__construct
*/
public function testConstructor()
{
$headers = new Headers( array( 'test' => 'test' ) );
$this->assertTrue( $headers instanceof \ArrayObject );
$this->assertEquals( 'test', $headers[ 'test' ] );
}
}<file_sep>#!/bin/sh
sudo apt-get update
sudo apt-get install -y libtool autoconf automake uuid-dev git-core sqlite3 libsqlite3*
rm -rf /tmp/mongrel2
git clone git://github.com/zedshaw/mongrel2.git /tmp/mongrel2
cd /tmp/mongrel2
make clean all && sudo make install
echo "Installation Complete"<file_sep><?php
namespace Mongrel\Request;
use \Mongrel\RequestException;
class BrowserStack extends \SplObjectStorage
{
public function attach( $browser, $data = null )
{
if( !$browser instanceof Browser )
{
throw new RequestException( 'Invalid Browser' );
}
return parent::attach( $browser, $data );
}
public function offsetSet( $browser, $data = null )
{
return $this->attach( $browser, $data );
}
public function detach( $browser )
{
if( !$browser instanceof Browser )
{
throw new RequestException( 'Invalid Browser' );
}
return parent::detach( $browser );
}
public function offsetUnset( $browser )
{
return $this->detach( $browser );
}
public function __toString()
{
if( 0 === $this->count() )
{
throw new RequestException( 'No browsers specified' );
}
$browsers = array();
foreach( $this as $browser )
{
$browsers[] = (string) $browser;
}
return implode( ' ', $browsers );
}
}<file_sep><?php
namespace Mongrel\Request;
class BrowserTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( 'hello world' ),
array( null ),
array( array() ),
array( new \stdClass )
);
}
public function validDataProvider()
{
return array(
array( 1 )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Request\Browser::__construct
*/
public function testConstructorInvalid( $browserString )
{
$this->setExpectedException( 'Mongrel\RequestException' );
new Browser( $browserString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Request\Browser::__construct
*/
public function testConstructor( $browserString )
{
new Browser( $browserString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Request\Browser::__toString
*/
public function testTostring( $browserString )
{
$browser = new Browser( $browserString );
$this->assertEquals( $browserString, (string) $browser );
$this->assertEquals( $browserString, $browser->__toString() );
}
}<file_sep><?php
namespace Mongrel;
class RequestException extends \RuntimeException {}<file_sep><?php
namespace Mongrel;
class ResponseException extends \RuntimeException {}<file_sep>#!/bin/bash
SCRIPT=`readlink -f $0`
SCRIPTPATH=`dirname $SCRIPT`
mkdir $SCRIPTPATH/mongrel/run $SCRIPTPATH/mongrel/logs $SCRIPTPATH/mongrel/tmp
chmod 777 -R $SCRIPTPATH/mongrel/run $SCRIPTPATH/mongrel/logs $SCRIPTPATH/mongrel/tmp
m2sh load -config $SCRIPTPATH/mongrel/sites/example.conf
echo "Port opened on localhost:8001"
m2sh start -host localhost<file_sep><?php
namespace Mongrel;
class ClientTest extends \PHPUnit_Framework_TestCase
{
public static $message = '288c0bca-f46c-46dc-b15a-bdd581c30e38 99 /favicon.ico 23:{"PATH":"/favicon.ico"},0:foo=bar,';
public static $dsn = 'tcp://127.0.0.1:8000';
public function setUp()
{
extension_loaded( 'zmq' ) || $this->markTestSkipped( 'Zmq PHP extension not loaded' );
}
public function dataProvider()
{
$context = $this->getMock( 'ZMQContext', array( 'getSocket' ) );
$front = $this->getMock( 'ZMQSocket', array( 'connect', 'recv' ), array( $context, Client::FTYPE ) );
$back = $this->getMock( 'ZMQSocket', array( 'connect', 'send' ), array( $context, Client::BTYPE ) );
$dsn = $this->getMock( 'Mongrel\Dsn', array( 'toString' ), array( self::$dsn ) );
$response = $this->getMockBuilder( 'Mongrel\Response' )->disableOriginalConstructor()->getMock();
$context->expects( $this->at( 0 ) )
->method( 'getSocket' )
->with( Client::FTYPE )
->will( $this->returnValue( $front ) );
$context->expects( $this->at( 1 ) )
->method( 'getSocket' )
->with( Client::BTYPE )
->will( $this->returnValue( $back ) );
$dsn->expects( $this->any() )
->method( 'toString' )
->will( $this->returnValue( self::$dsn ) );
$response->expects( $this->any() )
->method( 'getMessage' )
->will( $this->returnValue( self::$message ) );
return array( array( $context, $front, $back, $dsn, $response ));
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Client::__construct
*/
public function testConstructor_Context_InvalidType( $context, $front, $back, $dsn, $response )
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Client( new \stdClass, $dsn, $dsn );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Client::__construct
*/
public function testConstructor_FrontDsn_InvalidType( $context, $front, $back, $dsn, $response )
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Client( $context, new \stdClass, $dsn );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Client::__construct
*/
public function testConstructor_BackDsn_InvalidType( $context, $front, $back, $dsn, $response )
{
$this->setExpectedException( 'PHPUnit_Framework_Error' );
new Client( $context, $dsn, new \stdClass );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Client::__construct
*/
public function testConstructor( $context, $front, $back, $dsn, $response )
{
$front->expects( $this->exactly( 1 ) )
->method( 'connect' )
->with( self::$dsn );
$back->expects( $this->exactly( 1 ) )
->method( 'connect' )
->with( self::$dsn );
$client = new Client( $context, $dsn, $dsn );
$this->assertAttributeSame( $front, 'frontend', $client );
$this->assertAttributeSame( $back, 'backend', $client );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Client::recv
*/
public function testRecv( $context, $front, $back, $dsn, $response )
{
$front->expects( $this->exactly( 1 ) )
->method( 'recv' )
->will( $this->returnValue( self::$message ) );
$client = new Client( $context, $dsn, $dsn );
$recv = $client->recv();
$this->assertEquals( new \Mongrel\Request( self::$message ), $recv );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Client::send
*/
public function testSend( $context, $front, $back, $dsn, $response )
{
$back->expects( $this->exactly( 1 ) )
->method( 'send' )
->with( $response->getMessage() )
->will( $this->returnValue( $back ) );
$client = new Client( $context, $dsn, $dsn );
$client->send( $response );
}
}<file_sep><?php
namespace Mongrel\Request;
class BrowserStackTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers \Mongrel\Request\BrowserStack::attach
*/
public function testAttach_InvalidBrowser()
{
$this->setExpectedException( 'Mongrel\RequestException' );
$browsers = new BrowserStack;
$browsers->attach( new \stdClass );
}
/**
* @covers \Mongrel\Request\BrowserStack::attach
*/
public function testAttach()
{
$browsers = new BrowserStack;
$browsers->attach( new Browser( 1 ) );
$this->assertEquals( 1, $browsers->count() );
}
/**
* @covers \Mongrel\Request\BrowserStack::offsetSet
*/
public function testOffsetSet_InvalidBrowser()
{
$this->setExpectedException( 'Mongrel\RequestException' );
$browsers = new BrowserStack;
$browsers->offsetSet( new \stdClass );
}
/**
* @covers \Mongrel\Request\BrowserStack::offsetSet
*/
public function testOffsetSet()
{
$browsers = new BrowserStack;
$browsers->offsetSet( new Browser( 1 ) );
$this->assertEquals( 1, $browsers->count() );
}
/**
* @covers \Mongrel\Request\BrowserStack::detach
*/
public function testDettach_InvalidBrowser()
{
$this->setExpectedException( 'Mongrel\RequestException' );
$browsers = new BrowserStack;
$browsers->detach( new \stdClass );
}
/**
* @covers \Mongrel\Request\BrowserStack::detach
*/
public function testDettach()
{
$browsers = new BrowserStack;
$browser = new Browser( 1 );
$browsers->attach( $browser );
$this->assertEquals( 1, $browsers->count() );
$browsers->detach( $browser );
$this->assertEquals( 0, $browsers->count() );
}
/**
* @covers \Mongrel\Request\BrowserStack::offsetUnset
*/
public function testOffsetUnSet_InvalidBrowser()
{
$this->setExpectedException( 'Mongrel\RequestException' );
$browsers = new BrowserStack;
$browsers->offsetUnset( new \stdClass );
}
/**
* @covers \Mongrel\Request\BrowserStack::offsetUnset
*/
public function testOffsetUnSet()
{
$browsers = new BrowserStack;
$browser = new Browser( 1 );
$browsers->offsetSet( $browser );
$this->assertEquals( 1, $browsers->count() );
$browsers->offsetUnset( $browser );
$this->assertEquals( 0, $browsers->count() );
}
/**
* @covers \Mongrel\Request\BrowserStack::__toString
*/
public function testTostring_NoBrowsers()
{
$this->setExpectedException( 'Mongrel\RequestException' );
$browsers = new BrowserStack;
$browsers->__toString();
}
/**
* @covers \Mongrel\Request\BrowserStack::__toString
*/
public function testTostring_SingleBrowser()
{
$browsers = new BrowserStack;
$browsers->attach( new Browser( 1 ) );
$this->assertEquals( '1', (string) $browsers );
$this->assertEquals( '1', $browsers->__toString() );
}
/**
* @covers \Mongrel\Request\BrowserStack::__toString
*/
public function testTostring_MultipleBrowsers()
{
$browsers = new BrowserStack;
$browsers->attach( new Browser( 1 ) );
$browsers->attach( new Browser( 2 ) );
$this->assertEquals( '1 2', (string) $browsers );
$this->assertEquals( '1 2', $browsers->__toString() );
}
}<file_sep><?php
namespace Mongrel\Http;
class Headers extends \ArrayObject {}<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Mimetype
*
* @ORM\Table(name="mimetype")
* @ORM\Entity
*/
class Mimetype
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $mimetype
*
* @ORM\Column(name="mimetype", type="text", nullable=true)
*/
private $mimetype;
/**
* @var string $extension
*
* @ORM\Column(name="extension", type="text", nullable=true)
*/
private $extension;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set mimetype
*
* @param string $mimetype
* @return Mimetype
*/
public function setMimetype($mimetype)
{
$this->mimetype = $mimetype;
return $this;
}
/**
* Get mimetype
*
* @return string
*/
public function getMimetype()
{
return $this->mimetype;
}
/**
* Set extension
*
* @param string $extension
* @return Mimetype
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* @return string
*/
public function getExtension()
{
return $this->extension;
}
}<file_sep>#!/bin/sh
SCRIPT=`readlink -f $0`
SCRIPTPATH=`dirname $SCRIPT`
sudo apt-get update
sudo apt-get install -y libtool autoconf automake uuid-dev git-core
sudo apt-get install -y php5-common php5-dev php5-cli php5-uuid
sudo apt-get install -y libmagic1 libmagic-dev
sudo apt-get install -y curl libcurl3 libcurl3-openssl-dev
# Store PHP INI Path
PHP_INI_PATH=$(php --ini | grep "Scan for additional" | sed -e "s|.*:\s*||")
# Installing ØMQ 2.2
cd /tmp
rm -rf libzmq
git clone https://github.com/zeromq/zeromq2-x.git libzmq
cd libzmq
git pull origin master
./autogen.sh
./configure
make
sudo make install
# Installing ØMQ PHP Module
cd /tmp
git clone git://github.com/mkoppanen/php-zmq.git
cd php-zmq
git pull origin master
phpize
./configure
make
sudo make install
echo "extension=zmq.so" | sudo tee $PHP_INI_PATH/zmq.ini
# Installing pecl_http Module
printf "\n\n\n\n" | sudo pecl install pecl_http
echo "extension=http.so" | sudo tee $PHP_INI_PATH/http.ini
# Installing Composer
cd $SCRIPTPATH/../
curl -s http://getcomposer.org/installer | php
php composer.phar install<file_sep><?php
use Doctrine\ORM\Mapping as ORM;
/**
* Server
*
* @ORM\Table(name="server")
* @ORM\Entity
*/
class Server
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=true)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string $uuid
*
* @ORM\Column(name="uuid", type="text", nullable=true)
*/
private $uuid;
/**
* @var string $accessLog
*
* @ORM\Column(name="access_log", type="text", nullable=true)
*/
private $accessLog;
/**
* @var string $errorLog
*
* @ORM\Column(name="error_log", type="text", nullable=true)
*/
private $errorLog;
/**
* @var string $chroot
*
* @ORM\Column(name="chroot", type="text", nullable=true)
*/
private $chroot;
/**
* @var string $pidFile
*
* @ORM\Column(name="pid_file", type="text", nullable=true)
*/
private $pidFile;
/**
* @var string $defaultHost
*
* @ORM\Column(name="default_host", type="text", nullable=true)
*/
private $defaultHost;
/**
* @var string $name
*
* @ORM\Column(name="name", type="text", nullable=true)
*/
private $name;
/**
* @var string $bindAddr
*
* @ORM\Column(name="bind_addr", type="text", nullable=true)
*/
private $bindAddr;
/**
* @var integer $port
*
* @ORM\Column(name="port", type="integer", nullable=true)
*/
private $port;
/**
* @var integer $useSsl
*
* @ORM\Column(name="use_ssl", type="integer", nullable=true)
*/
private $useSsl;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set uuid
*
* @param string $uuid
* @return Server
*/
public function setUuid($uuid)
{
$this->uuid = $uuid;
return $this;
}
/**
* Get uuid
*
* @return string
*/
public function getUuid()
{
return $this->uuid;
}
/**
* Set accessLog
*
* @param string $accessLog
* @return Server
*/
public function setAccessLog($accessLog)
{
$this->accessLog = $accessLog;
return $this;
}
/**
* Get accessLog
*
* @return string
*/
public function getAccessLog()
{
return $this->accessLog;
}
/**
* Set errorLog
*
* @param string $errorLog
* @return Server
*/
public function setErrorLog($errorLog)
{
$this->errorLog = $errorLog;
return $this;
}
/**
* Get errorLog
*
* @return string
*/
public function getErrorLog()
{
return $this->errorLog;
}
/**
* Set chroot
*
* @param string $chroot
* @return Server
*/
public function setChroot($chroot)
{
$this->chroot = $chroot;
return $this;
}
/**
* Get chroot
*
* @return string
*/
public function getChroot()
{
return $this->chroot;
}
/**
* Set pidFile
*
* @param string $pidFile
* @return Server
*/
public function setPidFile($pidFile)
{
$this->pidFile = $pidFile;
return $this;
}
/**
* Get pidFile
*
* @return string
*/
public function getPidFile()
{
return $this->pidFile;
}
/**
* Set defaultHost
*
* @param string $defaultHost
* @return Server
*/
public function setDefaultHost($defaultHost)
{
$this->defaultHost = $defaultHost;
return $this;
}
/**
* Get defaultHost
*
* @return string
*/
public function getDefaultHost()
{
return $this->defaultHost;
}
/**
* Set name
*
* @param string $name
* @return Server
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set bindAddr
*
* @param string $bindAddr
* @return Server
*/
public function setBindAddr($bindAddr)
{
$this->bindAddr = $bindAddr;
return $this;
}
/**
* Get bindAddr
*
* @return string
*/
public function getBindAddr()
{
return $this->bindAddr;
}
/**
* Set port
*
* @param integer $port
* @return Server
*/
public function setPort($port)
{
$this->port = $port;
return $this;
}
/**
* Get port
*
* @return integer
*/
public function getPort()
{
return $this->port;
}
/**
* Set useSsl
*
* @param integer $useSsl
* @return Server
*/
public function setUseSsl($useSsl)
{
$this->useSsl = $useSsl;
return $this;
}
/**
* Get useSsl
*
* @return integer
*/
public function getUseSsl()
{
return $this->useSsl;
}
}<file_sep><?php
namespace Mongrel;
class RequestTest extends \PHPUnit_Framework_TestCase
{
static $message = '288c0bca-f46c-46dc-b15a-bdd581c30e38 99 /favicon.ico 23:{"PATH":"/favicon.ico"},0:foo=bar,';
public static function dataProvider()
{
return array( array( new Request( self::$message ) ) );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::__construct
*/
public function testConstructor_ParamIsNotString()
{
$this->setExpectedException( 'Mongrel\RequestException' );
new Request( array() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::__construct
*/
public function testConstructor_Invalid_Message()
{
$this->setExpectedException( 'Mongrel\RequestException' );
new Request( 'invalid message' );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::__construct
*/
public function testConstructor( Request $request )
{
$this->assertAttributeInstanceOf( '\Mongrel\Request\Uuid', 'uuid', $request );
$this->assertAttributeInstanceOf( '\Mongrel\Request\Browser', 'browser', $request );
$this->assertAttributeInstanceOf( '\Mongrel\Request\Path', 'path', $request );
$this->assertAttributeInstanceOf( '\Mongrel\Request\Headers', 'headers', $request );
$this->assertAttributeInstanceOf( '\Mongrel\Request\Body', 'body', $request );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::getUuid
*/
public function testGetUuid( Request $request )
{
$this->assertEquals( '288c0bca-f46c-46dc-b15a-bdd581c30e38', (string) $request->getUuid() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::getBrowser
*/
public function testGetBrowser( Request $request )
{
$this->assertEquals( '99', (string) $request->getBrowser() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::getPath
*/
public function testGetPath( Request $request )
{
$this->assertEquals( '/favicon.ico', (string) $request->getPath() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::getHeaders
*/
public function testGetHeaders( Request $request )
{
$this->assertEquals( array( 'PATH' => '/favicon.ico' ), $request->getHeaders()->getArrayCopy() );
}
/**
* @dataProvider dataProvider
* @covers \Mongrel\Request::getBody
*/
public function testGetBody( Request $request )
{
$this->assertEquals( 'foo=bar', (string) $request->getBody() );
}
}<file_sep><?php
namespace Mongrel\Request;
use \Mongrel\RequestException;
class Path
{
private $path;
/**
* Create a Mongrel Path Object
*
* @param string $path
* @throws RequestException
*/
public function __construct( $path )
{
if( !is_string( $path ) )
{
throw new RequestException( 'Invalid format. Failed to parse mongrel request path' );
}
$this->path = $path;
}
/**
* Get Mongrel Request Path
*
* @return string
*/
public function __toString()
{
return $this->path;
}
}<file_sep><?php
namespace Mongrel;
class DsnTest extends \PHPUnit_Framework_TestCase
{
public function invalidDsnProvider()
{
return array(
array( 'tcp://127.0.0.1:999999' ),
array( 'test' )
);
}
public function validDsnProvider()
{
return array(
array( 'tcp://127.0.0.1:9996', array( 'tcp', '127.0.0.1', '9996' ) ),
array( 'tcp://*:8000', array( 'tcp', '*', '8000' ) )
);
}
/** @dataProvider invalidDsnProvider **/
public function testConstructor_InvalidParams( $dsn )
{
$this->setExpectedException( 'Mongrel\DsnException' );
$object = new Dsn( $dsn );
}
/** @dataProvider validDsnProvider **/
public function testConstructor_ValidParams( $dsn, $expected )
{
$object = new Dsn( $dsn );
$this->assertAttributeSame( $expected[0], 'protocol', $object );
$this->assertAttributeSame( $expected[1], 'ip', $object );
$this->assertAttributeSame( $expected[2], 'port', $object );
}
/**
* @dataProvider validDsnProvider
* @covers \Mongrel\Dsn::getProtocol
*/
public function testGetProtocol( $dsn, $expected )
{
$object = new Dsn( $dsn );
$this->assertEquals( $expected[0], $object->getProtocol() );
}
/**
* @dataProvider validDsnProvider
* @covers \Mongrel\Dsn::getIp
*/
public function testGetIp( $dsn, $expected )
{
$object = new Dsn( $dsn );
$this->assertEquals( $expected[1], $object->getIp() );
}
/**
* @dataProvider validDsnProvider
* @covers \Mongrel\Dsn::getPort
*/
public function testGetPort( $dsn, $expected )
{
$object = new Dsn( $dsn );
$this->assertEquals( $expected[2], $object->getPort() );
}
/**
* @dataProvider validDsnProvider
* @covers \Mongrel\Dsn::toString
*/
public function testToString( $dsn, $expected )
{
$object = new Dsn( $dsn );
$this->assertEquals( $dsn, $object->toString() );
}
}<file_sep>Simple library for writing Mongrel2 clients in PHP 5.3+ using zeromq 2.2
========================================================================
Install
--------
```bash
echo '[Installing ØMQ 2.2]' && ./install/zmq22-install.sh
echo '[Installing ØMQ PHP Module]' && ./install/zmqphp-install.sh
echo '[Installing pecl_http Module]' && ./install/pecl-http-install.sh
echo '[Installing Composer]' && curl -s http://getcomposer.org/installer | php && php composer.phar install
echo '[Installing Mongrel2 Web Server]' && ./install/mongrel2-zmq2-install.sh
```
Simple Client Example
---------------------
```php
// Create a new Mongrel client
$mongrelClient = new \Mongrel\Client(
new \ZMQContext,
new \Mongrel\Dsn( 'tcp://127.0.0.1:9997' ),
new \Mongrel\Dsn( 'tcp://127.0.0.1:9996' )
);
// Create a new Mongrel HTTP client
$client = new \Mongrel\Http\Client( $mongrelClient );
// Listen for requests
while( true )
{
/* @var $request \Mongrel\Http\Request */
$request = $client->recv();
// Build a response
$response = new \Mongrel\Http\Response( '<h1>Hello World!</h1>', array( 'Content-Type' => 'text/html' ) );
// Send response back to the browser that requested it
$client->reply( $response, $request );
// Clean up
unset( $request, $response );
}
```
Mustache View Renderer Example
------------------------------
```bash
sh examples/mongrel-start.sh
sh examples/mustache/devices/mustache-server.sh # (in another window)
```
Open [localhost:8001](http://localhost:8001/) in your web browser
Tests
--------
```bash
phpunit
```
Travis CI
---------
 http://travis-ci.org/#!/missinglink/mongrel2-php

License
------------------------
Released under the MIT(Poetic) Software license
This work 'as-is' we provide.
No warranty express or implied.
Therefore, no claim on us will abide.
Liability for damages denied.
Permission is granted hereby,
to copy, share, and modify.
Use as is fit,
free or for profit.
These rights, on this notice, rely.
<file_sep><?php
namespace Mongrel\Request;
class UuidTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( '288c0bcaf46c46dcb15abdd581c30e38' ),
array( '288c0bca f46c 46dc b15a bdd581c30e38' ),
array( 'test' )
);
}
public function validDataProvider()
{
return array(
array( '288c0bca-f46c-46dc-b15a-bdd581c30e38' )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Request\Uuid::__construct
*/
public function testConstructorInvalid( $uuidString )
{
$this->setExpectedException( 'Mongrel\RequestException' );
new Uuid( $uuidString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Request\Uuid::__construct
*/
public function testConstructor( $uuidString )
{
new Uuid( $uuidString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Request\Uuid::__toString
*/
public function testTostring( $uuidString )
{
$uuid = new Uuid( $uuidString );
$this->assertEquals( $uuidString, (string) $uuid );
$this->assertEquals( $uuidString, $uuid->__toString() );
}
}<file_sep><?php
namespace Mongrel\Request;
use \Mongrel\RequestException;
class Body
{
private $body;
/**
* Create a Mongrel Request Body Object
*
* @param string $body
* @throws RequestException
*/
public function __construct( $body )
{
if( !is_string( $body ) )
{
throw new RequestException( 'Invalid format. Failed to parse mongrel request body' );
}
$this->body = $body;
}
/**
* Get Mongrel Request Body
*
* @return string
*/
public function __toString()
{
return (string) $this->body;
}
}<file_sep><?php
namespace Mongrel\Request;
class HeadersTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( 'hello world' ),
array( array() ),
array( null ),
array( 1 ),
array( new \stdClass )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Request\Headers::__construct
*/
public function testConstructorInvalid( $headersString )
{
$this->setExpectedException( 'Mongrel\RequestException' );
new Headers( $headersString );
}
/**
* @covers \Mongrel\Request\Headers::__construct
*/
public function testConstructor()
{
$headers = new Headers( json_encode( array( 'hello' => 'world' ) ) );
$this->assertTrue( $headers instanceof \ArrayObject );
$this->assertEquals( 'world', $headers[ 'hello' ] );
}
}<file_sep><?php
namespace Mongrel\Http;
class ProtocolTest extends \PHPUnit_Framework_TestCase
{
public function invalidDataProvider()
{
return array(
array( 'HTTP/1.2' ),
array( array() ),
array( null ),
array( 1 ),
array( new \stdClass )
);
}
public function validDataProvider()
{
return array(
array( 'HTTP/1.0' ),
array( 'HTTP/1.1' )
);
}
/**
* @dataProvider invalidDataProvider
* @covers \Mongrel\Http\Protocol::__construct
*/
public function testConstructorInvalid( $protocolString )
{
$this->setExpectedException( 'Mongrel\ResponseException' );
new Protocol( $protocolString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Http\Protocol::__construct
*/
public function testConstructor( $protocolString )
{
new Protocol( $protocolString );
}
/**
* @dataProvider validDataProvider
* @covers \Mongrel\Http\Protocol::__toString
*/
public function testTostring( $protocolString )
{
$protocol = new Protocol( $protocolString );
$this->assertEquals( $protocolString, (string) $protocol );
$this->assertEquals( $protocolString, $protocol->__toString() );
}
}<file_sep>#!/bin/sh
sudo apt-get update
sudo apt-get install -y libtool autoconf automake uuid-dev git-core
cd /tmp
rm -rf libzmq
git clone https://github.com/zeromq/zeromq2-x.git libzmq
cd libzmq
git pull origin master
./autogen.sh
./configure
make
sudo make install
clear
dpkg -l | grep zmq
echo "Installation Complete"<file_sep>#!/usr/bin/php
<?php
use \Mongrel\Http;
require_once sprintf( '%s/../../../vendor/autoload.php', __DIR__ );
require_once sprintf( '%s/Mustache.php', __DIR__ );
// Use Mustache view renderer
$mustache = new Mustache( file_get_contents( sprintf( '%s/../views/example1.mustache', __DIR__ ) ) );
// Quick & dirty view renderer using Mustache
$view = function( Http\Request $request ) use ( $mustache )
{
// We need some info from the original Mongrel request object in this view
$mongrelRequest = $request->getMongrelRequest();
// Render the view
return $mustache->render( null, array(
'title' => 'It\'s Alive!',
'sections' => array(
array( 'title' => 'Uuid', 'text' => $mongrelRequest->getUuid() ),
array( 'title' => 'Browser', 'text' => $mongrelRequest->getBrowser() ),
array( 'title' => 'Path', 'text' => $mongrelRequest->getPath() ),
array( 'title' => 'Body', 'text' => $mongrelRequest->getBody() ),
array( 'title' => 'Headers', 'text' => print_r( $request->getHeaders(), true ) ),
array( 'title' => 'Query', 'text' => $request->getQuery() ),
)
));
};
// Create a new Mongrel client
$mongrelClient = new \Mongrel\Client(
new \ZMQContext,
new \Mongrel\Dsn( 'tcp://127.0.0.1:9997' ),
new \Mongrel\Dsn( 'tcp://127.0.0.1:9996' )
);
// Create a new Mongrel HTTP client
$client = new Http\Client( $mongrelClient );
while( true )
{
/* @var $request \Mongrel\Http\Request Listen for requests */
$request = $client->recv();
/* @var $html string Render HTML using view callback */
$html = call_user_func( $view, $request );
/* @var $response \Mongrel\Http\Response Build a response */
$response = new Http\Response( $html, array( 'Content-Type' => 'text/html; charset=UTF-8' ) );
// Send response back to the browser that requested it
$client->reply( $response, $request );
// Clean up
unset( $request, $html, $response );
} | 575d36cd50df5b1f7986554d16e39f4d3dc95811 | [
"Markdown",
"PHP",
"Shell"
]
| 55 | PHP | missinglink/mongrel2-php | 28c87f9a0a05e9c837cb94b4c4af5d5a76278327 | 0da3ea4b1cc18bc1c7e4f5e4d3bb74e41bd2f20a |
refs/heads/master | <file_sep>#include "../log/Logger.h"
#include <iostream>
#include <vector>
#include <unordered_map>
//g++ -Wall -std=c++14 LogConfig.cpp -o testLogConfig
using namespace ign;
int main()
{
log::Logger logger;
logger.cfg.mode = log::Config::W_TIME | log::Config::W_TERM | log::Config::W_THREAD_ID;
logger.cfg.configure("[test]", " - ");
logger.cfg.setStdOut(std::cout);
logger.style.setColors(log::Color::Red, log::Color::Black);
logger("Text Rouge sur FOND NOIR");
logger(ign::os::osToString());
return 0;
}
<file_sep>#pragma once
#include <string>
#include <iostream>
namespace ign
{ namespace log {
class Config {
//Exceptions
struct BadOutputStream{};
//Standard Stream
std::ostream* m_stdout = &std::cout;
public :
enum Mode{ NO_MODE = 0, W_TERM = 1, W_TIME = 2, W_THREAD_ID = 4 };
int mode = W_TERM;
std::string prefix {"[log]"};
std::string separator {""};
std::string file_path {""}; //Output file path
//configuration funcs
inline Config& configure(const std::string& _prefix, const std::string& _separator) noexcept;
Config& setStdOut(std::ostream& standardOut); //will throw BadStream if standardOut is not one of the standard c++ outputs
std::ostream& stream() { return *m_stdout; }
//utils
std::string getHeader() const noexcept;
//toString
std::string toString() const noexcept;
};
inline Config& Config::configure(const std::string& _prefix, const std::string& _separator) noexcept {
prefix = _prefix;
separator = _separator;
return *this;
}
Config& Config::setStdOut(std::ostream& s) {
//check if s is one of the c++ standard output streams
if (s.rdbuf() == std::cout.rdbuf()
|| s.rdbuf() == std::cerr.rdbuf()
|| s.rdbuf() == std::clog.rdbuf())
m_stdout = &s;
else
throw BadOutputStream{};
return *this;
}
std::string Config::getHeader() const noexcept {
return prefix + (mode & W_THREAD_ID ? " T:" : "") + (mode & W_TIME ? "[time]" : "") + separator;
}
std::string Config::toString() const noexcept {
std::string res = "log::Config";
res += " prefix[" + prefix + "]";
res += " separator[" + separator + "]";
res += " file[" + file_path + "]";
//write mode
res += " mode[ ";
if (mode == 0) {
res += "NO_MODE ";
} else {
if (mode & W_TERM)
res += "W_TERM ";
if (mode & W_TIME)
res += "W_TIME ";
if (mode & W_THREAD_ID)
res += "W_THREAD_ID ";
}
res += "]";
//write stream
res += " stream[";
if (m_stdout->rdbuf() == std::cout.rdbuf())
res += "std::cout";
else if (m_stdout->rdbuf() == std::cerr.rdbuf())
res += "std::cerr";
else if (m_stdout->rdbuf()== std::clog.rdbuf())
res += "std::clog";
res += "]";
return res;
}
} //log
} //ign
<file_sep>#include "../log_system/toString.h"
#include <iostream>
#include <vector>
#include <unordered_map>
//g++ -Wall -std=c++14 toStringTest.cpp -o testToString
using namespace ign;
class hasToString
{
public:
std::string toString() const{ return std::string("It works"); };
};
class testClass
{
public:
int test = 5;
};
int main()
{
std::vector<bool> vect = {true, true, false, true, false, true};
std::unordered_map<std::string, int> test_map;
test_map["bite"] = 5;
test_map["couille"] = 8;
test_map["truc"] = 20;
int tab[5] = {1, 2, 3, 4, 5};
int* tab_first = &tab[0];
hasToString test;
testClass test2;
//tuple
auto test_tuple = std::make_tuple("test", 15, true, "tuple test ?");
std::cout << log::toString(test) << std::endl;
std::cout << log::toString(40.1547f) << std::endl;
std::cout << log::toString(test2) << std::endl;
std::cout << log::toString(tab) << std::endl;
std::cout << log::toString(tab_first) << std::endl;
std::cout << log::toString(vect) << std::endl;
std::cout << log::toString(test_map) << std::endl;
std::cout << log::toString(test_tuple) << std::endl;
return 0;
}
<file_sep>template<typename ...Args>
Logger& Logger::operator()(Args&&... args)
{
m_buffer.emplace_back(cfg.getHeader() + write_arguments(std::forward<Args>(args)...));
//if print_term is actived, print to terminal
if (cfg.mode & Config::W_TERM)
cfg.stream() << style.apply(m_buffer.back()) + "\n";
//if buffer reached his capacity, forceWrite
if (m_buffer.size() >= getBufferCapacity())
forceWrite();
return *this;
}
template<class T>
std::string Logger::write_arguments(const T& t) const
{
return toString(t);
}
template<class T, class ...Args>
std::string Logger::write_arguments(const T& t, Args&&... args) const
{
return std::string(toString(t) + cfg.separator + write_arguments(std::forward<Args>(args)...));
}
/*
inline Logger& Logger::setOutputFile(const std::string& path, bool truncate)
{
//write what was logged for the previous file
forceWrite();
m_output_stream.close();
m_output_stream.open(path, truncate ? std::ofstream::trunc : std::ofstream::app);
if (!m_output_stream)
throw BadOutputFile{};
return *this;
}
*/
<file_sep>#pragma once
#include <string>
#include <type_traits>
#include <sstream>
#include <tuple>
#include <typeinfo>
#include <cxxabi.h>
namespace ign {
namespace log {
////////////////////////////////////////////
// SFINAE tests
////////////////////////////////////////////
template <typename T>
class has_toString
{
typedef char one;
typedef long two;
template <typename C> static one test( decltype(&C::toString) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
// see : http://stackoverflow.com/questions/4347921/sfinae-compiler-troubles
template <typename T>
class is_container
{
// Is.
template <typename U>
static char test(U* u,
int (*b)[sizeof(typename U::const_iterator()==((U*)0)->begin())] = 0,
int (*e)[sizeof(typename U::const_iterator()==((U*)0)->end())] = 0);
// Is not.
template <typename U> static long test(...);
public :
enum { value = (1 == sizeof test<T>(0)) };
};
////////////////////////////////////////////
// Info
////////////////////////////////////////////
template<class T>
std::string getName(const T& obj, bool getRealName = true)
{
std::string str = "obj";
if (getRealName) {
try {
int status;
char *realname = abi::__cxa_demangle(typeid(obj).name(), 0, 0, &status);
str = realname;
free(realname);
//remove std::
if (str.size() >= 5 && str.substr(0, 5) == "std::")
str.erase(begin(str), begin(str)+5);
//if it's a template, find < and cut everything behind it
auto it = str.find_first_of("<");
if (it != std::string::npos) {
str.erase(begin(str)+it, end(str));
}
} catch(...) {
str = "obj";
}
}
return str;
}
////////////////////////////////////////////
// ToString
////////////////////////////////////////////
/** string **/
std::string toString(const std::string& t)
{
return t;
}
/** C style strings **/
std::string toString(const char* t)
{
return std::string(t);
}
/** arithmetic **/
template<class T, std::enable_if_t<std::is_arithmetic<T>::value && !std::is_same<T, bool>::value >* = nullptr>
std::string toString(const T& t)
{
return std::to_string(t);
}
/** boolean **/
template<class T, std::enable_if_t<std::is_same<T, bool>::value>* = nullptr>
std::string toString(const T& t)
{
return t ? "true" : "false";
}
/** pair **/
template<class T, class U>
std::string toString(const std::pair<T, U>& p)
{
return "<" + toString(p.first) + ":" + toString(p.second) + ">";
}
/** pointer **/
template<class T, std::enable_if_t<std::is_pointer<T>::value>* = nullptr>
std::string toString(const T& t)
{
std::stringstream ss;
ss << "@" << t;
return ss.str();
}
/** array with [] **/
template<class T, std::enable_if_t<std::is_array<T>::value>* = nullptr>
std::string toString(const T& t)
{
std::string res = "[";
for (const auto& elem : t)
res += toString(elem) + ", ";
if (res.size() > 2)
res.erase(end(res)-2, end(res));
res += "]";
return std::move(res);
}
/** has_toString **/
template<class T, typename std::enable_if<has_toString<T>::value>::type* = nullptr>
std::string toString(const T& t)
{
return t.toString();
}
/** is a container **/
template<class T, typename std::enable_if<is_container<T>::value>::type* = nullptr>
std::string toString(const T& t)
{
std::string res = "[";
for(const auto& val : t)
res += toString(val) + ", ";
if (res.size() > 2)
res.erase(end(res)-2, end(res));
res += "]";
return std::move(res);
}
/** Other **/
template<class T, std::enable_if_t<std::is_class<T>::value && !has_toString<T>::value && !is_container<T>::value>* = nullptr>
std::string toString(const T& t)
{
std::stringstream ss;
ss << getName(t) << "(" << sizeof(t) <<")" << "@" << &t;
return ss.str();
}
/** tuple **/
template<typename Tuple, std::size_t total, std::size_t remaining = total>
struct __tupleToString
{
static
void tupleToString(const Tuple& t, std::string& res)
{
res += toString(std::get<total - remaining>(t));
res += ":";
__tupleToString<Tuple, total, remaining-1>::tupleToString(t, res);
}
};
template<typename Tuple, std::size_t total>
struct __tupleToString<Tuple, total, 1>
{
static
void tupleToString(const Tuple& t, std::string& res)
{
res += toString(std::get<total - 1>(t));
}
};
template<typename Tuple, std::size_t total>
struct __tupleToString<Tuple, total, 0>
{
static
void tupleToString(const Tuple& t, std::string& res)
{}
};
template<typename ...Args>
std::string toString(const std::tuple<Args...>& t)
{
std::string res = "<";
__tupleToString<decltype(t), std::tuple_size<std::remove_cv_t<std::remove_reference_t<decltype(t)>>>::value>::tupleToString(t, res);
res += ">";
return res;
}
}
}
<file_sep>#include "../log/Style.h"
#include "../log/Config.h"
#include <iostream>
#include <vector>
#include <unordered_map>
//g++ -Wall -std=c++14 LogConfig.cpp -o testLogConfig
using namespace ign;
int main()
{
log::Config cfg;
cfg.mode = log::Config::W_TIME | log::Config::W_TERM | log::Config::W_THREAD_ID;
cfg.configure("[test]", " - ");
cfg.setStdOut(std::clog);
log::Config cfg2;
cfg2.mode = log::Config::W_TERM | log::Config::W_THREAD_ID;
cfg2.configure("[dbg]", " # ");
cfg2.setStdOut(std::wcerr);
std::cout << cfg.toString() << std::endl;
std::cout << cfg2.toString() << std::endl;
return 0;
}
<file_sep>#include "../log/Logger.h"
#include <iostream>
#include <vector>
#include <unordered_map>
//g++ -Wall -std=c++14 LoggerTest.cpp -o testLogger
using namespace ign;
class hasToString
{
public:
std::string toString() const{ return std::string("It works"); };
};
class testClass
{
public:
int test = 5;
};
int main()
{
std::vector<bool> vect = {true, true, false, true, false, true};
std::unordered_map<std::string, int> test_map;
test_map["bite"] = 5;
test_map["couille"] = 8;
test_map["truc"] = 20;
int tab[5] = {1, 2, 3, 4, 5};
int* tab_first = &tab[0];
hasToString test;
testClass test2;
//tuple
auto test_tuple = std::make_tuple("test", 15, true, "tuple test ?", test_map, "fin");
ign::log::Logger dbg(5); //set buffer size
dbg.configure(true /*print in terminal*/, "[dbg]" /*prefix*/, " " /*separator*/, false /*print time*/);
dbg.setOutputFile("dbg.log");
dbg.setStdStream(std::cout);
dbg(test, 40.1547f, tab, tab_first, vect, test_map, test_tuple);
for (int i = 0; i < 12; ++i)
dbg("attempt :", i);
return 0;
}
<file_sep>#pragma once
#include <string>
/** OS & ARCHITECTURE DETECTION *******
* Unix :
* IGN_OS_UNIX
* Linux :
* IGN_OS_LINUX
* Apple :
* IGN_OS_APPLE
* IGN_OS_IOS_SIMULATOR (ios under xcode)
* IGN_OS_IOS (iphone / ipad / ...)
* IGN_OS_OSX (macbooks / ...)
* Android :
* IGN_OS_ANDROID
* Windows :
* IGN_OS_WIN
* IGN_OS_WIN_32
* IGN_OS_WIN_64
* IGN_OS_CYGWIN
* Architecture :
* IGN_OS_64
* IGN_OS_32
***************************************/
//Apple produts
#if defined(__APPLE__) && defined(__MACH__)
//osx / ios (darwin) is an unix based os
#define IGN_OS_APPLE
#define IGN_OS_UNIX
#include <TargetConditionals.h>
//ios on xcode
#if TARGET_IPHONE_SIMULATOR == 1
#define IGN_OS_IOS_SIMULATOR
//ios device
#elif TARGET_OS_IPHONE == 1
#define IGN_OS_IOS
//osx device
#elif TARGET_OS_MAC == 1
#define IGN_OS_OSX
#endif
#endif
//detect ANDROID
#if defined(__ANDROID__)
#define IGN_OS_ANDROID
#endif
//detect LINUX
#if defined(__linux__)
#define IGN_OS_LINUX
#endif
//detect UNIX System
#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)))
#define IGN_OS_UNIX
#endif
//detect WINDOWS
#if defined(_WIN32) || defined(_WIN64)
#define IGN_OS_WIN
//architecture
#if defined(_WIN32)
#define IGN_OS_32
#define ING_OS_WIN_32
#else
#define IGN_OS_64
#define IGN_OS_WIN_64
#endif
#endif
//Windows with Cygwin
#if defined(__CYGWIN__) && !defined(_WIN32)
#define IGN_OS_CYGWIN
#endif
//Architecture check under gcc
#if __GNUC__
#if __x86_64__ || __ppc64__
#define IGN_OS_64
#else
#define IGN_OS_32
#endif
#endif
namespace ign {
namespace os {
std::string osToString() noexcept {
static std::string os;
if (os.empty()) {
//os
//unix
#ifdef IGN_OS_UNIX
os += "Unix ";
#endif
//linux
#ifdef IGN_OS_LINUX
os += "Linux ";
#endif
//apple
#if defined(IGN_OS_APPLE)
#ifdef IGN_OS_IOS_SIMULATOR
os += "iOS simulator ";
#elif defined(IGN_OS_IOS)
os += "iOs ";
#else
os += "Mac OS X ";
#endif
#endif
//Windows
#ifdef IGN_OS_WIN
os += "Windows ";
#endif
//Cygwin
#ifdef IGN_OS_CYGWIN
os += "Cygwin ";
#endif
//architecture
#ifdef IGN_OS_32
os += "32 bits";
#else
os += "64 bits";
#endif
}
return os;
}
}
}
<file_sep>#pragma once
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
#include "toString.h"
#include "Config.h"
#include "Style.h"
namespace ign
{ namespace log {
class Logger {
public :
Config cfg;
Style style;
protected :
std::ofstream m_output_stream;
std::vector<std::string> m_buffer;
template<class T, class ...Args>
std::string write_arguments(const T& t, Args&&... args) const;
template<class T>
std::string write_arguments(const T& t) const;
public :
Logger(std::size_t buffer_size = 32);
~Logger();
//() operator
template<typename ...Args>
Logger& operator()(Args&&... args);
//buffer size
Logger& setBufferCapacity(std::size_t s); //if write is activated, each time the buffer is full it will write it in the file
inline std::size_t getBufferCapacity() const { return m_buffer.capacity(); }
//force write
Logger& forceWrite(); //force write to the outputFile
};
Logger::Logger(std::size_t buffer_size)
{
m_buffer.reserve(buffer_size);
}
Logger::~Logger()
{
forceWrite();
m_output_stream.close();
}
Logger& Logger::setBufferCapacity(std::size_t s)
{
if (s == getBufferCapacity())
return *this;
else if (s >= m_buffer.size())
m_buffer.reserve(s);
else //we have to remove elements
{
//write all logs
forceWrite();
//now m_buffer should be empty
m_buffer.reserve(s);
}
return *this;
}
Logger& Logger::forceWrite()
{
if (m_output_stream.is_open())
{
//build the text
std::string build;
for (const auto& line : m_buffer)
build += line;
//write to file
m_output_stream << build;
}
//clear buffer
m_buffer.clear();
return *this;
}
#include "Logger.inl"
}
}
<file_sep>#pragma once
#include <string>
#include <iostream>
#include "../os/detect.h"
#include "toString.h"
//system dependent headers
#ifdef IGN_OS_UNIX
#include <unistd.h>
#elif defined(IGN_OS_WIN)
#include <Windows.h>
#include <io.h>
#endif
namespace ign
{ namespace log {
enum class Color : char {
Black = 0,
Red = 1,
Blue = 2,
Magenta = 3,
Green = 4,
Yellow = 5,
Cyan = 6,
White = 7,
DarkGrey = 8,
BrightRed = 9,
BrightBlue = 10,
BrightMagenta = 11,
BrightGreen = 12,
BrightYellow = 13,
BrightCyan = 14,
BrightGrey = 15,
Default = 16
};
std::string toString(const Color& c){
switch(c){
case Color::Black :
return "Black";
case Color::Red :
return "Red";
case Color::Blue :
return "Blue";
case Color::Magenta :
return "Magenta";
case Color::Green :
return "Green";
case Color::Yellow :
return "Yellow";
case Color::Cyan :
return "Cyan";
case Color::White :
return "White";
case Color::DarkGrey :
return "DarkGrey";
case Color::BrightRed :
return "BrightRed";
case Color::BrightBlue :
return "BrightBlue";
case Color::BrightMagenta :
return "BrigthMagenta";
case Color::BrightGreen :
return "BrightGreen";
case Color::BrightYellow :
return "BrightYellow";
case Color::BrightCyan :
return "BrightCyan";
case Color::BrightGrey :
return "BrightGrey";
case Color::Default :
return "DefaultColor";
default :
return "Unknown Color";
}
}
//Used for unix based terms
std::string ANSIEscapeCode(const Color& c, bool background = false) {
auto color = static_cast<int>(c);
//default color
if (color == 16)
return (background ? "49" : "39");
//other colors
return (color < 8 ? toString((background ? 40 : 30) + color) : toString((background ? 100 : 90) + color - 8));
}
#ifdef IGN_OS_WIN
_In_ getWindowsColor(const Color& c, bool background = false) {
_In_ color;
return color;
}
#endif
} //log
} //ign
<file_sep>Ignis - C++14 Utils Library
=============================
Ignis is a simple to use C++ `Header-Only` Library
Each system is independant
Systems
-------
`Log` - Used to log whatever you want
<file_sep>#pragma once
#include <string>
#include <iostream>
#include "Color.h"
#include "toString.h"
namespace ign
{ namespace log {
struct Style {
Color fg = Color::Default;
Color bg = Color::Default;
bool reverse{false};
Style& setColors(const Color& foreground, const Color& background);
std::string apply(const std::string& s) const noexcept;
std::string toString() const noexcept;
static bool inTerminal() noexcept;
private :
static bool _term;
static bool _checked;
};
bool Style::_term = false;
bool Style::_checked = false;
Style& Style::setColors(const Color& foreground, const Color& background) {
fg = foreground;
bg = background;
return *this;
}
std::string Style::apply(const std::string& s) const noexcept {
if (!inTerminal())
return s;
#ifdef IGN_OS_UNIX
//ANSI escape code (http://en.wikipedia.org/wiki/ANSI_escape_code#graphics)
return "\033[0" + ANSIEscapeCode(bg, true) + ";" + ANSIEscapeCode(fg) + "m" + s + "\033[0m";
#else
#ifdef IGN_OS_WIN
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), getWindowsColor(fg) | getWindowsColor(bg, true));
return s;
#endif
#endif
}
std::string Style::toString() const noexcept {
return "Style fg[" + log::toString(fg) + "] bg[" +
log::toString(bg) + "]" + (reverse? " Reverse Colors" : "");
}
bool Style::inTerminal() noexcept {
if (!_checked) {
_checked = true;
#ifdef IGN_OS_UNIX
_term = isatty(fileno(stdout));
#else
#ifdef IGN_OS_WIN
_term = _isatty(_fileno(stdout));
#endif
#endif
}
return _term;
}
} //log
} //ign
| a29254e14543b1ed9b6c1b0c0d024d8609a2f7cb | [
"Markdown",
"C++"
]
| 12 | C++ | Tassim/Ignis | 9981b06056789ac7d2c345de801010394da9492d | 390e3619c38635369d19729348179d460ecbbb22 |
refs/heads/master | <file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { useRef } from "react";
/** stabilizes references to a component so you can define it inline in a render function
* do not use while depending on the render scope unless you wrap the culprit in a ref which is still a bad idea.
*
* Always consider just creating the component outside of the component you need it in, as a module-level object,
* but sometimes inline is more readable
*
* @example
* function MyComp() {
* return (
* <div>
* {useInlineComponent(() => <span>weird but ok</span>)}
* </div>;
* );
* }
*/
export const useInlineComponent = <P, T extends React.ElementType<P>>(
comp: T
): T => useRef(comp).current;
export default useInlineComponent;
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) <NAME>, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
// ReturnType<typeof useState<T>> isn't yet possible generically in typescript
export type ReactHookState<T> = [T, React.Dispatch<React.SetStateAction<T>>];
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) <NAME>, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import React from "react";
export default function useOnExternalClick<T extends HTMLElement | null>(
ref: React.MutableRefObject<T>,
externalClickCallback: () => void
): void {
React.useEffect(() => {
function handleClickOutside(event: any) {
if (ref.current && !ref.current.contains(event.target)) {
externalClickCallback();
}
}
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref, externalClickCallback]);
}
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { useState, useMemo } from "react";
/**
* Manages a string input, abstracting any parsing or validation for the intended value type.
* By default (with no generic type parameter specified) assumes a number is being parsed and uses parseFloat for
* parsing if no `parse` option is supplied.
* if you are using any type but `number` you must pass a custom parse function
*/
export function useValidatedInput(
initial?: string,
opts?: DefaultOptions
): UseRegexValidatedInputResult<number>;
export function useValidatedInput<T extends any>(
initial?: string,
opts?: Options<T>
): UseRegexValidatedInputResult<T>;
export function useValidatedInput<T extends any = number>(
initial?: string,
opts?: Options<T>
): UseRegexValidatedInputResult<T> {
opts = {
parse: (parseFloatNullInsteadOfNaN as any) as ValueParserWithStatus<T>,
pattern: isNumberPattern,
...opts,
};
const [input, setInput] = useState<string>(initial ?? "");
const [value, statusReason] = useMemo(() => {
if (opts?.pattern && !opts.pattern.test(input))
return [
null,
opts.pattern === isNumberPattern ? "invalid number" : "invalid format",
];
const result = opts!.parse!(input);
if (opts!.validate && result.value !== null) {
const test = opts!.validate(result.value);
if (!test.valid) return [null, test.status];
}
return [result.value, result.status];
}, [input, opts?.parse, opts?.pattern, opts?.validate]);
const status = value !== null ? InputStatus.Success : InputStatus.Error;
return [value, input, setInput, status, statusReason];
}
export interface Options<T> {
parse?: (input: string) => { value: T | null; status?: string };
/** optional preparse RegExp tester, rejects with "invalid format" */
pattern?: RegExp;
// TODO: allow return type of just boolean
/** optional postparse value tester */
validate?: (value: T) => { valid: boolean; status?: string };
}
// type used when user passes no custom options
export interface DefaultOptions {
parse?: (input: string) => { value: number | null; status?: string };
/** optional preparse RegExp tester, rejects with "invalid format" */
pattern?: RegExp;
validate?: (value: number) => { valid: boolean; status?: string };
}
export enum InputStatus {
Success = "success",
Warning = "warning",
Error = "error",
}
// TODO: add scientific notation support? i.e. 1.23E+21
const isNumberPattern = /^-?(0|[1-9]\d*)(\.\d+)?$/i;
export type UseRegexValidatedInputResult<T> = [
T | null,
string,
React.Dispatch<React.SetStateAction<string>>,
InputStatus | undefined,
string | undefined
];
type ValueParserWithStatus<T> = (
text: string
) => { value: T | null; status?: string };
const parseFloatNullInsteadOfNaN: ValueParserWithStatus<number> = (text) => {
const result = parseFloat(text);
if (Number.isNaN(result)) return { value: null, status: "invalid number" };
else return { value: result };
};
export default useValidatedInput;
<file_sep># @bentley/react-hooks
[](https://dev.azure.com/bentleycs/iModelTechnologies/_build/latest?definitionId=4718)
Generic React hooks for daily development.
## Hooks
- **useAsyncEffect**: like `useEffect` but you can pass an async function and check if the component restarted the effect during your async operation.
```tsx
useAsyncEffect(
async ({isStale, setCancel}) => {
const fetchPromise = fetch(`http://example.com/users/${userId}`);
// using setCancel, unfinished effect runs are cancelled by new runs
// this allows you to cancel requests you no longer need
setCancel(() => {
console.log("dependencies (userId) changed, cancelling old request!")
// your async API must have some kind of cancellation
// for example, the fetch API can use an AbortController
fetchPromise.cancel();
})
const data = await fetchPromise;
if (!isStale())
setState(data);
},
[userId]
).catch(err => {
console.log("an error occurred!");
console.error(err);
});
```
- **useOnChange**: run an effect on a state change, but wait for some validity condition, any time you need to store a ref to previous state, consider this
```tsx
const [activeType, setActiveType] = useState<string>();
useOnChange(({prev}) => {
const [prevType] = prev;
uiToastNotifyUser(`active type changed from ${prevType} to ${activeType}`);
}, [activeType]);
```
or wait for some third party non-react state, the effect reruns *every render* if the validity condition was not met, it only stops running once it's met and none
of the listened states have changed.
```tsx
const viewport = thirdpartyLibrary.tryGetViewport();
const [userDefinedColor] = useState("red");
useOnChange(() => {
// we know viewport is defined because of the condition
viewport!.setBackgroundColor(userDefinedColor);
}, viewport !== undefined, [userDefinedColor]);
```
- **useInterval**: the classic, run an effect every `n` milliseconds
- **useAsyncInterval**: `useInterval` but with the same API for async effects as `useAsyncEffect`
- **usePropertySetter**: for when you have an object in state but want a setter of its subproperty. Supports thunks (`prev=>next` callbacks)
e.g.:
```tsx
const [myobj, setMyobj] = useState({time: 5, area: "world"});
const setArea = usePropertySetter("area", setMyobj);
useEffect(() => {
setArea(prevArea => prevArea === "world" ? "hello" : "world");
}, []);
return <MySubcomponent setArea={setArea} />;
```
- **useValidatedInput**: useState for strings that are parsed into some other type (i.e. parsing a number input).
By default parses numeric input, but you can supply your own parse function, meaning you could handle search languages, SI units, lists, anything.
Returns an optional parse failure reason.
```tsx
const [value, input, setInput] = useValidatedInput("5", {
// don't change the numeric parsing but validate that it's a positive number
validate: (n: number) => {
const valid = /\d+/.test(n);
return { valid, status: !valid ? "only positive integers" : undefined };
})
});
return <input value={input} onChange={e => setInput(e.currentTarget.value)} />;
```
- **useMediaQuery**: react to a media query (e.g. screen size > 400px?)
- **useScrolling**: react if your component is currently being scrolled through
- **useHelp**: manage a contextual help link based on what components are currently rendering.
Internally this has been used to link to articles in a Bentley Communities page, based on which pages and menus (their components) are open (mounted).
- **useInlineComponent**: for tiny components
- **useOnMount**: for directly saying you're doing something is first added to the dom
- **useOnUnmount**: for directly saying you're doing something when the component is removed from the dom
- **useOnExternalClick**: A callback to fire on external clicks. Great for closing popups
```tsx
const [isOpen, setIsOpen] = useState(true);
const popupElemRef = useRef<HTMLDivElement>(null);
useOnExternalClick(popupElemRef, () => setIsOpen(false)) // close popup if user clicks outside of it
return (
<div>
<Toolbar />
{isOpen && <div ref={popupElemRef}><UserPopup /></div>}
</div>
);
```
## Tips
To get `eslint-plugin-react-hooks` to warn on bad dependencies for hooks like
`useAsyncEffect`, see the eslint rule's [advanced configuration docs](https://www.npmjs.com/package/eslint-plugin-react-hooks#advanced-configuration).
Older versions of `eslint-plugin-react-hooks` may warn on passing an async argument, we have a PR in react's monorepo to fix that eslint rule, and we can maintain a trivial fork if this is a common issue, because not warning on missed effects almost always leads to bug.
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { useRef } from "react";
import useInterval from "./useInterval";
type CancellationFunc = () => void;
/**
* @description
* useInterval but with support for async functions and utilities like useAsyncEffect
* the async cancel/cleanup occurs directly before the replacing effect is about to start.
* To handle errors you may catch the return value of the effect.
*
* @warn
* it's possible that a previous cancelled effect run could have a section that sets state
* that runs after the current effect, which may cause strange problems, so make sure to synchronously
* exit after a cancellation (i.e. after axios.isCancel)
*
* @example
* useAsyncInterval(async ({setPerformCancel}) => {
* const resp = await axios.get<Resp>(pollEndpointUrl, {
* cancelToken: new axios.CancelToken(setPerformCancel) // works well with axios
* });
* }, 1000);
*/
export function useAsyncInterval(
effect: (util: {
isStale: () => boolean;
/** @deprecated perfer setPerformCancel, the name is more intuitive */
setCancel: (cancel: CancellationFunc) => void;
setPerformCancel: (cancel: CancellationFunc) => void;
}) => Promise<void>,
interval: number | null
): Promise<void>;
export function useAsyncInterval(
effect: (util: {
isStale: () => boolean;
/** @deprecated perfer setPerformCancel, the name is more intuitive */
setCancel: (cancel: CancellationFunc) => void;
setPerformCancel: (cancel: CancellationFunc) => void;
}) => void,
interval: number | null
): void;
export function useAsyncInterval(
effect: (util: {
isStale: () => boolean;
/** @deprecated perfer setPerformCancel, the name is more intuitive */
setCancel: (cancel: CancellationFunc) => void;
setPerformCancel: (cancel: CancellationFunc) => void;
}) => void | Promise<void>,
interval: number | null
): Promise<void> {
const lastCancel = useRef<CancellationFunc>();
const isStale = useRef(true);
return new Promise<void>((resolve, reject) =>
// Promise constructor synchronously invokes this callback,
// so this useEffect call follows the rules of hooks (static invocation)
// eslint-disable-next-line react-hooks/rules-of-hooks
useInterval(() => {
lastCancel.current?.();
const setPerformCancel = (inCancelFunc: CancellationFunc) => {
lastCancel.current = () => {
inCancelFunc();
isStale.current = true;
};
};
const result = effect({
isStale: () => isStale.current,
setCancel: setPerformCancel,
setPerformCancel,
});
if (result) {
result
.then(() => {
lastCancel.current = undefined;
isStale.current = false;
resolve();
})
.catch(reject);
}
}, interval)
);
}
export default useAsyncInterval;
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { useRef } from "react";
import useAsyncEffect from "./useAsyncEffect";
/**
* useOnChange, a hook for a common effect pattern
*
* @description Sometimes you want an effect to run exactly when some state changes, but you might rely on
* state that isn't valid yet. So you need to wait for all dependencies to be valid, and only _then_ execute
* the effect, having stored that the state changed before. This hook
* encapsulates the pattern of running an effect on a state change, and will wait for all dependencies
* to be valid before actually running the pending effect.
*
* @example
* const [modelDomainName, setModelDomainName] = useState("");
* const [isPollingForUploadState, setIsPolling] = useState(false);
* useOnChange(
* // effect doesn't have to be async
* async (isStale, setCancel) => {
* if (isPollingForUploadState && !isStale()) await poll(modelDomainName, setCancel);
* },
* [tickNumber], // whenever tickNumber changes, rerun the effect provided the modelDomainName is valid
* !!modelDomainName,
* );
*
* @param effect the react effect that will run, with optional cleanup just like useEffect
* @param rerunStates states will cause this effect to rerun
* @param validRunCondition condition that must be satisfied for the effect to run
*/
export default function useOnChange<States extends readonly any[]>(
effect: (util: {
prev: Partial<States>;
isStale: () => boolean;
setCancel: (cancel: () => void) => void;
}) => Promise<void>,
validRunCondition: boolean,
rerunStates: States
): Promise<void>;
// TODO: currently this is a 2x2 matrix of overloads, if it explodes, may
// want to look into higher-level type unions
export default function useOnChange<States extends readonly any[]>(
effect: (util: { prev: Partial<States> }) => void,
validRunCondition: boolean,
rerunStates: States
): void;
export default function useOnChange<States extends readonly any[]>(
effect: (util: {
prev: Partial<States>;
isStale: () => boolean;
setCancel: (cancel: () => void) => void;
}) => Promise<void>,
rerunStates: States
): Promise<void>;
export default function useOnChange<States extends readonly any[]>(
effect: (util: { prev: Partial<States> }) => void,
rerunStates: States
): void;
export default function useOnChange<States extends readonly any[]>(
effect: (util: {
prev: Partial<States>;
isStale: () => boolean;
setCancel: (cancel: () => void) => void;
}) => void | Promise<void>,
validRunConditionOrRerunStates: boolean | States,
maybeRerunStates?: States
): Promise<void> {
const [validRunCondition, rerunStates] =
maybeRerunStates !== undefined
? [validRunConditionOrRerunStates as boolean, maybeRerunStates]
: [true, validRunConditionOrRerunStates as States];
const ran = useRef(false);
const lastStates = useRef<States>();
const haveStatesChanged =
!lastStates.current ||
rerunStates.length !== lastStates.current.length ||
rerunStates?.some((_, i) => rerunStates[i] !== lastStates.current?.[i]);
if (haveStatesChanged) ran.current = false;
const prev =
lastStates.current ??
((new Array(rerunStates.length).fill(undefined) as any) as Partial<States>);
const result = useAsyncEffect(async (utils) => {
if (validRunCondition && !ran.current) {
ran.current = true;
void effect({ prev, ...utils });
}
});
lastStates.current = rerunStates;
return result;
}
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import React from "react";
/** A custom React hook function for using an interval timer.
* @param callback - The callback function.
* @param delay - How often (in msec) to call the callback function, or null to stop calling it.
*/
export function useInterval(callback: () => void, delay: number | null): void {
const savedCallback = React.useRef<() => void | null>();
// Remember the latest callback.
React.useEffect(() => {
savedCallback.current = callback;
});
// Set up the interval.
React.useEffect(() => {
function tick() {
if (typeof savedCallback?.current !== "undefined") {
savedCallback?.current();
}
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
return () => {};
}, [delay]);
}
export default useInterval;
<file_sep># 1.0.0
- breaking change from 0.x (useInvalidatedInput drops support for undefinedOnSuccess option)
- added useOnExternalClick hook
- see README for previous hooks
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import React from "react";
import { ReactHookState } from "./react-type-utils";
// would be nicer if typescript could use the optional call `?.()` operator on any type
// and realize it is a function
export function isAction<State extends any>(
arg: State | ((prev: State) => State)
): arg is (prev: State) => State {
return typeof arg === "function";
}
/**
* given a key and a react setState dispatcher returned from useState,
* create a setter for a particular field, with an API identical to as if you
* separated that field from the object as its own react state
*
* @example
* type T = {a: "b" | "c"};
* const [state, setState] = useState<T>({a: "b"});
* const setA = usePropertySetter("a", setState);
* setA("c");
*/
export const usePropertySetter = <
// eslint-disable-next-line @typescript-eslint/ban-types
State extends object,
Key extends keyof State
>(
key: Key,
setState: ReactHookState<State>[1]
): ReactHookState<State[Key]>[1] =>
// useRef over useCallback to prevent overhead
React.useRef((...[arg]: Parameters<ReactHookState<State[Key]>[1]>) =>
setState((prev) => {
const nextPropertyState = isAction<State[Key]>(arg)
? arg(prev[key])
: arg;
return { ...prev, [key]: nextPropertyState };
})
).current;
export default usePropertySetter;
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import React from "react";
/**
* Custom React hook for tracking the value of a media query.
* @param query A media query for use with window.matchMedia().
* Example: (min-width: 400px)
* @return true if query matches; false otherwise
*/
export const useMediaQuery = (query: string): boolean => {
// Adapted to TypeScript from here:
// https://medium.com/@ttennant/react-inline-styles-and-media-queries-using-a-custom-react-hook-e76fa9ec89f6
const mediaMatch = window.matchMedia(query);
const [matches, setMatches] = React.useState(mediaMatch.matches);
React.useEffect(() => {
const listener = (e: MediaQueryListEvent) => setMatches(e.matches);
// NOTE: addEventListener wasn't supported for MediaMatch until iOS 14. :-(
// The fact that the tools consider it to be deprecated is a MASSIVE BUG in the tools.
mediaMatch.addListener(listener);
return () => mediaMatch.removeListener(listener);
});
return matches;
};
/**
* Custom React hook for tracking when the specified HTMLElement is scrolling.
* @param scrollable The scrollable HTMLElement to track scrolling on; if null or undefined, result is false.
* @return true while scrollable is scrolling; false otherwise
*/
export const useScrolling = (scrollable: HTMLElement | undefined | null) => {
const [scrolling, setScrolling] = React.useState(false);
React.useEffect(() => {
let touching = false;
let timer: NodeJS.Timeout | undefined;
const scrollHandler = () => {
if (timer) {
clearTimeout(timer);
}
setScrolling(true);
if (!touching) {
// If not touching, the user initiated scrolling using an attached pointing device (mouse or trackpad).
timer = setTimeout(() => setScrolling(false), 250);
}
};
const touchStartHandler = () => {
touching = true;
};
const touchEndHandler = (ev: TouchEvent) => {
touching = ev.touches.length !== 0;
if (!touching) {
setScrolling(false);
}
};
if (scrollable) {
scrollable.addEventListener("scroll", scrollHandler);
// these events are intentionally only for touch as drag scrolling isn't done with the mouse or trackpad
scrollable.addEventListener("touchstart", touchStartHandler);
scrollable.addEventListener("touchend", touchEndHandler);
return () => {
scrollable.removeEventListener("scroll", scrollHandler);
scrollable.removeEventListener("touchstart", touchStartHandler);
scrollable.removeEventListener("touchend", touchEndHandler);
};
}
}, [scrollable]);
return scrolling;
};
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) <NAME>, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
export {
useOnMount,
useOnMountInRenderOrder,
useOnUnmount,
useStable,
} from "./basic-hooks";
export { makeContextWithProviderRequired } from "./context-utils";
export { default as useAsyncEffect } from "./useAsyncEffect";
export { default as useAsyncInterval } from "./useAsyncInterval";
export { default as useClass } from "./useClass";
export { default as useInlineComponent } from "./useInlineComponent";
export { default as useInterval } from "./useInterval";
export { default as useOnChange } from "./useOnChange";
export { default as usePropertySetter } from "./usePropertySetter";
export { default as useValidatedInput } from "./useValidatedInput";
export { default as useOnExternalClick } from "./useOnExternalClick";
export * from "./html-hooks";
export * from "./useHelp";
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import React, { useEffect } from "react";
type CancellationFunc = () => void;
/** a wrapper over React's useEffect that facilitates good practice for async effects,
* you can inline the async code, check if the effect is stale, and set a custom
* cancellation function to be invoked on cleanup, which is useful for cancelling
* actions such as fetch requests with AbortController, or axios requests with CancelToken
*
* The cancel function is assumed to be the cleanup action so if you need more advanced
* cleanup or your dependencies include things upon which you shouldn't cancel, use a raw effect
*
* It will return a promise forwarding any result of the async effect you passed, so you
* can catch the result of the effect to catch errors in the effect itself. You should not await this
* (your component render can't be an async function anyway)
* @example
* useAsyncEffect(
* async () => { throw Error("boom!") }
* ).catch((boom) => {})
*
* @example
* useAsyncEffect(async ({setPerformCancel}) => {
* const req = axios.get<Resp>(url, {
* cancelToken: new axios.CancelToken(setPerformCancel) // works well with axios
* });
* await req;
* }, [url]);
*
* @example
* const [myArray, setMyArray] = useState([]);
* useAsyncEffect(async ({isStale}) => {
* const result = await somethingAsync(id);
* if (!isStale()) setMyArray(result);
* }, [id, somethingAsync]);
*
*/
// HACK: overloading was defaulting always to the void return overload,
// so had to use generics to do this
export function useAsyncEffect<T extends Promise<void> | void>(
effect: (util: {
isStale: () => boolean;
/** @deprecated prefer setPerformCancel, the name is more intuitive */
setCancel: (cancel: CancellationFunc) => void;
setPerformCancel: (cancel: CancellationFunc) => void;
}) => T,
deps?: React.DependencyList
): T extends Promise<void> ? Promise<void> : void {
// it *always* returns a promise, but the promise can be safely ignored
// if the passed effect wasn't async, so I hide from typescript that it is returned
return new Promise<void>((resolve, reject) =>
// Promise constructor synchronously invokes this callback,
// so this useEffect call follows the rules of hooks (static invocation)
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
let isStale = false;
let onCancel: CancellationFunc | undefined;
const setPerformCancel = (inCancelFunc: CancellationFunc) => {
onCancel = inCancelFunc;
};
const result = effect({
isStale: () => isStale,
setPerformCancel,
setCancel: setPerformCancel,
});
const isPromise = (a: any): a is Promise<void> => a !== undefined;
if (isPromise(result)) {
result
.then(() => {
onCancel = undefined;
resolve();
})
.catch(reject);
} else {
resolve();
}
return () => {
isStale = true;
onCancel?.();
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, deps)
) as any;
}
export default useAsyncEffect;
<file_sep>/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import { useRef } from "react";
/** A hook for using classes seamlessly in your functional components. Unlike usual hooks,
* your dependencies are an object instead of an array, but thanks to implicitly named properties
* it should look similar and feel fine. As an added bonus, the types of dependencies passed in is
* known and it will be a typescript error to use state from your component that you did not pass
* in as a dependency.
*
* The created class is stable, and will always use the most up-to-date state from your React component.
*
* @example
* const [isHovered, setIsHovered] = useState(false);
* const MyClass = useClass((state) => class MyClass extends Base {
* overridableMethod() {
* super.overrideableMethod();
* if (isHovered) console.log("was hovered!");
* }
* }, { isHovered });
*
* const [myInstance] = useState(new MyClass());
*
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function useClass<C extends new (...args: any[]) => any, S extends {}>(
makeClass: (s: S) => C,
dependencies: S = {} as S
): C {
const stateRef = useRef({} as S).current;
Object.assign(stateRef, dependencies);
return useRef(makeClass(stateRef)).current;
}
export default useClass;
| 0c290adf1dce29f3996ef243b70dee6827de64ba | [
"Markdown",
"TypeScript"
]
| 14 | TypeScript | imodeljs/react-hooks | 00e2fc8387bfd6e92c2b2a141a848468f6e5e7df | 27727e394d6b675703ba548fc9e1c565aab9a791 |
refs/heads/master | <repo_name>ashishmaurya/wholesale-ecommerce<file_sep>/content-product.php
<div class="product-item col-sm-12 col-md-4 col-lg-3 ">
<!-- <h3>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3> -->
<?php the_post_thumbnail(); ?>
<h2>
<?php the_title(); ?>
</h2>
<?php the_excerpt(); ?>
<div><?php
$currency = get_woocommerce_currency_symbol();
echo $currency.' '.get_post_meta( get_the_ID(), '_regular_price', true); ?></div>
<div>
<button class='btn btn-primary w-100'>Enquiry</button>
</div>
</div><file_sep>/category-list.php
<div class="row my-4">
<h2 class="text-center">Featured Category</h2>
</div>
<div class="category-list row">
<?php
$get_featured_cats = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'hide_empty' => '0',
'include' => $cat_array,
);
$all_categories = get_categories( $get_featured_cats );
$j = 1;
foreach ($all_categories as $cat) {
$cat_id = $cat->term_id;
$cat_link = get_category_link( $cat_id );
echo '<div class="col-sm-12 col-md-3 col-lg-4">';
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true ); // Get Category Thumbnail
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img class="img-fluid" src="' . $image . '" alt="" />';
}
echo '<a href="' . get_term_link($cat->name, 'product_cat') . '">' . $cat->name . '</a>';
//echo '<h2 class="text-center">'.$cat->name.'</h2>'; // Get Category Name
//echo $cat->description; // Get Category Description
echo '</div>';
}
// Reset Post Data
wp_reset_query();
?>
</div><file_sep>/footer.php
</div><!-- .col-full -->
</div><!-- #content -->
<!-- Footer -->
<footer class="page-footer font-small blue pt-4">
<!-- Footer Links -->
<div class="container-fluid text-center text-md-left">
<!-- Grid row -->
<div class="row">
<!-- Grid column -->
<div class="col-md-6 mt-md-0 mt-3">
<!-- Content -->
<h5 class="text-uppercase"><?php echo get_bloginfo( 'name' ); ?></h5>
<p><?php echo get_bloginfo( 'description' ); ?></p>
</div>
<!-- Grid column -->
<hr class="clearfix w-100 d-md-none pb-3">
<!-- Grid column -->
<div class="col-md-3 mb-md-0 mb-3">
<!-- Links -->
<h5 class="text-uppercase">About Us</h5>
<ul class="list-unstyled">
<li>
<a href="#!">Contact</a>
</li>
<li>
<a href="#!">Terms & Condition</a>
</li>
<li>
<a href="#!">Help</a>
</li>
</ul>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 mb-md-0 mb-3">
<!-- Links -->
<h5 class="text-uppercase">Shops</h5>
<ul class="list-unstyled">
<li>
<a href="#!">Featured Products</a>
</li>
<li>
<a href="#!">Category</a>
</li>
<li>
<a href="#!">Products</a>
</li>
</ul>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
<!-- Footer Links -->
<!-- Copyright -->
<div class="footer-copyright text-center py-3">© 2019 Copyright:
<a href="https://adesigner.in/"> Adesigner</a>
</div>
<!-- Copyright -->
</footer>
<!-- Footer -->
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
<file_sep>/functions.php
<?php
include __DIR__.'/inc/lib/class-wp-bootstrap-navwalker.php';
function wpt_register_js() {
wp_register_script('jquery.bootstrap.min', get_template_directory_uri() . '/assets/js/bootstrap.min.js', 'jquery');
wp_enqueue_script('jquery.bootstrap.min');
}
add_action( 'wp_enqueue_scripts', 'wpt_register_js' );
function wpt_register_css() {
wp_register_style( 'bootstrap.min', get_template_directory_uri() . '/assets/css/bootstrap.min.css' );
wp_enqueue_style( 'bootstrap.min' );
}
add_action( 'wp_enqueue_scripts', 'wpt_register_css' );
/**
* Theme Functions
*/
function theme_name_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); | c1a6192c3f1143ef439c46116e6f16305e64a3e9 | [
"PHP"
]
| 4 | PHP | ashishmaurya/wholesale-ecommerce | 5d8c25b64ecb2c02cb3fe0ba9cb550233ed54f2d | c3ec4365c0a50c84af64aeeb46cd247141a2f1a3 |
refs/heads/master | <repo_name>abhinavzspace/koa2-kickstarter<file_sep>/src/service/user.js
const users = [
'ava',
'boyd',
'raylan',
'winona',
];
export const getUsers = () => users;
| af570a054f342fe5c4c4741216543c08eb4cbb79 | [
"JavaScript"
]
| 1 | JavaScript | abhinavzspace/koa2-kickstarter | 5dec2419f99809004020289b041103ae040704f3 | 4ff06b9dd413343de19d7cd1d8bdb6acee3e02fe |
refs/heads/master | <file_sep>#include<iostream>
#include<algorithm>
using namespace std;
bool binarySearchReacursive(int* array, int startIndex, int lastIndex, int element)
{
if(startIndex>lastIndex)
return false;
else
{
int mid=(startIndex+lastIndex)/2;
if(array[mid]==element)
return true;
else if(array[mid]>element)
binarySearchReacursive(array, startIndex, mid-1, element);
else
binarySearchReacursive(array, mid+1, lastIndex, element);
}
}
bool binarySearchIterative(int* array, int startIndex, int lastIndex, int element)
{
while(startIndex<=lastIndex)
{
int mid = (startIndex+lastIndex)/2;
if(array[mid] == element)
return true;
else if(array[mid] < element)
startIndex = mid+1;
else if(array[mid] > element)
lastIndex = mid-1;
}
if(startIndex>lastIndex)
return false;
}
int main()
{
int size = 0, num = 0;
bool result1 = false,result2 = false;
cout<<"Enter the size of Array: \n";
cin>>size;
int *arr = new int[size];
cout<<"Enter array elements. \n";
for(int i=0; i<size; i++)
cin>>arr[i];
sort(arr, arr+size);
cout<<"Enter the element to be searched: ";
cin>>num;
result1 = binarySearchIterative(arr, 0, size-1, num);
result2 = binarySearchReacursive(arr, 0, size-1, num);
if(result1 == true)
cout<<num<<"Element found.\n";
else
cout<<"Element not found!\n";
if(result2 == true)
cout<<num<<"Element found.\n";
else
cout<<"Element not found!\n";
delete[] arr;
return 0;
}
| f70f35fc1113f2462e1c9faba4a21379771f4bcf | [
"C++"
]
| 1 | C++ | DDUC-CS-Sanjeet/binarysearch-alindsingh281 | ee2a06f2225ca2bc580a0d93d2c0df50ca1ec514 | f956d1a35c6526b61b4067618066b100c8f3694d |
refs/heads/master | <file_sep>var staticAssets = [
'/',
'style.css',
'script.js'
]
self.addEventListener("install", async event => {
const cache = await caches.open("news-static");
cache.addAll(staticAssets);
});
self.addEventListener("fetch", function() {
console.log("Fetch");
}); | 8b9b606587581dcc48cccf65450dd641bc0456cc | [
"JavaScript"
]
| 1 | JavaScript | reachtokish/practicing-PWA | 56008c0ba82f5bf0d1b274ef8f37066ab1bdc0a0 | 64c5ee73a3fd02f0f8670bcb6f54960ba40c9ff0 |
refs/heads/master | <repo_name>bhavana0187/CompassFostering<file_sep>/Models/Policy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CompassFostering.Models
{
public enum PolicyStatus
{
/// <summary>
/// Policy start date is in the future
/// </summary>
Not_Begun,
/// <summary>
/// Policy is between its start and end dates
/// </summary>
On_Risk,
/// <summary>
/// Policy end date has passed
/// </summary>
Expired,
/// <summary>
/// Policy has been cancelled
/// </summary>
Cancelled
};
public class Policy
{
public long SaleId { get; set; }
public PolicyStatus PolicyStatus { get; set; }
public string ProductCode { get; set; }
public string CancellationNotes { get; set; }
public long PolicyNumber { get; set; }
/// <summary>
/// Product.Code
/// </summary>
public string PolicyNumberPrefix { get; set; }
/// <summary>
/// Policy.PolicyNumberPrefix + PolicyNumber
/// </summary>
public string PolicyNumberFull { get; set; }
}
}
<file_sep>/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using CompassFostering.Models;
namespace CompassFostering.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
public IActionResult DatabaseOperations(string policyNumber,string policyCode,string policyStatus,int dbOperation)
{
Policy policy;
//policy = new Policy()
//{
// PolicyNumber = Convert.ToInt32(policyNumber),
// ProductCode = policyCode,
// PolicyStatus = (PolicyStatus)Enum.Parse(typeof(PolicyStatus), policyStatus)
//};
if (dbOperation == 1)
{
//insert
if (policyNumber == "")
{
//We are creating a new entity record
//_work.PolicyRepo.Insert(policy, _user.UserName(User.Identity.Name));
//_work.Save();
}
}
else if (dbOperation == 2)
{
//update
//var pol = await _work.PolicyRepo.GetForUpdate(policyNumber);
//_work.PolicyRepo.Update(pol, _user.UserName(User.Identity.Name));
//_work.Save();
}
else if (dbOperation == 3)
{
//delete
//_work.PolicyRepo.Delete(policy, _user.UserName(User.Identity.Name));
//_work.Save();
}
return View("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| f1f164444da1bf9701e3a5a88a884b1c64259762 | [
"C#"
]
| 2 | C# | bhavana0187/CompassFostering | 24dc37a95a1073575ba2d3ab348e171c9bcb0413 | ac391958abad6fc6b4faa84b0252775a5ad1f8a3 |
refs/heads/master | <file_sep>Descrição:
Algoritmo genético para resolução do problema da mochila binária.
Passos do algoritmo:
1. Gera população P com N indivíduos
2. Avalia P
3. Seleciona os pais
4. Reprodução da nova geração
5. Processo de mutação
6. Volte ao passo 2
Definir:
- O cromossomo;
- O operador de crossover;
- O operador de mutação;
- O método de seleção.
<file_sep># Classe que representa um item.
class Item:
def __init__(self, volume, importance):
self.volume = volume
self.importance = importance
<file_sep>import random
import sys
class GeneticAlgorithm:
def __init__(self, input, knapsackSize, mutation_tax):
self.input = input
self.knapsackSize = knapsackSize
self.population = []
self.mutation_tax = mutation_tax
#criar a primeira população
def initialize(self):
i = 0
while i < len(self.input):
populationAux = []
j = 0
while j < len(self.input):
k = random.randint(0, 1)
populationAux.append(bool(k))
j = j + 1
vol, importance = self.calcule_vol_import(populationAux)
if vol <= self.knapsackSize:
self.population.append(populationAux)
i = i + 1
#fitness
def fitness(self, population, max_weight):
newArray = []
for i in range(len(population)):
vol, importance = self.calcule_vol_import(population[i])
if vol <= max_weight:
newArray.append((vol, importance, population[i]))
return newArray
def calcule_vol_import(self, cromossome):
vol = 0
imp = 0
for i in range(len(cromossome)):
if cromossome[i]:
vol += int(self.input[i].volume)
imp += int(self.input[i].importance)
return vol, imp
#seleção
def selection(self, population):
parents = []
population.sort(key=lambda x: x[1])
for i in range(len(population)):
parents.append(population[i][2])
return parents
#seleção
def parent_selection(self, population):
parents = []
total_value = 0
for individual in population:
total_value += individual[1]
highest, second_highest = self.find_two_fittest_individuals(population)
parents.append(highest[2])
parents.append(second_highest[2])
sum_value = 0
while len(parents) < len(population):
individual = random.randint(0, len(population)-1)
sum_value += population[individual][1]
if sum_value >= total_value:
parents.append(population[individual][2])
return parents
def find_two_fittest_individuals(self,population):
highest = 0
highest_index = 0
second_highest = 0
second_highest_index = 0
for i in range(len(population)):
if population[i][1] > highest:
highest = population[i][1]
highest_index = i
if population[i][1] > second_highest and population[i][1] < highest:
second_highest = population[i][1]
second_highest_index = i
return population[highest_index], population[second_highest_index]
#criar nova população
def new_population(self):
new_generation = []
while len(new_generation) < len(self.population):
parent_a = random.randint(0, len(self.population) - 1)
parent_b = random.randint(0, len(self.population) - 1)
ch = self.crossover(self.population[parent_a], self.population[parent_b])
ch1 = self.mutation(ch[0])
ch2 = self.mutation(ch[1])
new_generation.append(ch[0])
new_generation.append(ch[1])
return new_generation
#Funçao para crossover
def crossover(self, cs1, cs2):
mean = int(len(cs1)/2)
size = len(cs1)
ch1 = []
ch2 = []
for i in range(0, mean):
ch1.append(cs1[i])
ch2.append(cs2[i])
for i in range(mean, size):
ch1.append(cs2[i])
ch2.append(cs1[i])
return (ch1, ch2)
# Evolução da taxa de mutação
def evolveMutation(self):
population_n = self.fitness(self.population, self.knapsackSize)
if len(population_n) > 0:
if len(population_n) < len(self.population):
self.mutation_tax = len(population_n) / len(self.population)
#print("Taxa de mutação: ",self.mutation_tax)
#Função de mutação
def mutation(self, cromossome):
if random.uniform(0, 1) <= self.mutation_tax:
for i in range(len(cromossome)):
if random.uniform(0, 1) <= self.mutation_tax:
if cromossome[i]:
cromossome[i] = False
else:
cromossome[i] = True
return cromossome
#Função de mutação
def mutation2(self):
for i in range(len(self.population)):
for j in range(len(self.population[i])):
if random.uniform(0, 1) <= self.mutation_tax:
if self.population[i][j]:
self.population[i][j] = False
else:
self.population[i][j] = True
#Retorna o melhor elemento dentro de uma população
def bestElement(self):
population_n = self.fitness(self.population, self.knapsackSize)
if len(population_n) > 0:
volume = population_n[0][0]
importance = population_n[0][1]
best = population_n[0][2]
bestFinal = []
for i in range(1,len(population_n)):
if importance < population_n[i][1]:
volume = population_n[i][0]
importance = population_n[0][1]
best = population_n[i][2]
print("Peso final:", volume, "Importância Final:", importance)
for i in range(len(best)):
if best[i]:
print(1, end=' ')
bestFinal.append(1)
else:
print(0, end=' ')
bestFinal.append(0)
print()
return bestFinal
else:
print("Nenhuma solução encontrada")
return []
#Printa a população na tela
def printPopulation(self, generation):
print("Geração ", generation)
for i in range(len(self.population)):
for j in range(len(self.population[i])):
if self.population[i][j]:
print(1, end=' ')
else:
print(0, end=' ')
print()
#Realiza a execução do algoritmo genético
def run(self, MAX_GEN):
self.initialize()
g = 0
self.printPopulation(g)
i = 0
while i < MAX_GEN and g < (10000 + MAX_GEN):
# Fazer o fitness
new_pop = self.fitness(self.population, self.knapsackSize)
if len(new_pop) > 2:
#Seleção dos melhores pais
self.population = self.parent_selection(new_pop)
#faz o crossover e a mutação
self.population = self.new_population()
# evolui a mutação
#self.evolveMutation()
# printa a geração atual
g = g + 1
self.printPopulation(g)
i = i + 1
else:
#faz o crossover e a mutação
g = g + 1
#faz o crossover e a mutação
self.population = self.new_population()
self.mutation2()
self.printPopulation(g)
# calcula o melhor elemento da última geração
return self.bestElement()<file_sep>import csv
from Item import *
from GeneticAlgorithm import *
# Parametros de entrada
def main():
param = sys.argv[1:]
if len(param) == 3:
pathInput = "./testes/"
pathOutput = "./saida/"
array = readFile(pathInput + param[0])
itens = []
itens, size = arrayItem(array)
x = GeneticAlgorithm(itens, int(size), 0.5)
best = x.run(int(param[2]))
with open(pathOutput + param[1], 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter='\n')
for i in range(len(best)):
spamwriter.writerow(str(best[i]))
else:
print("Argumento Faltando! -> nome do arquivo de entrada, nome do arquivo de saida, quantidade de gerações")
def readFile(path):
file = open(path)
array = csv.DictReader(file)
return array
def arrayItem(array):
itens = []
i=0
for element in array:
if i == 0:
size = element["volume"]
i = 1
else:
item = Item(element["volume"],element["importancia"])
itens.append(item)
return itens, size
if __name__ == "__main__":
main() | 1c39d924c3beb5b080bd582a90f6e6ef2e92618b | [
"Markdown",
"Python"
]
| 4 | Markdown | mat-marques/AlgoritmoGenetico_ProblemaDaMochila | 8affbc91929922d4888118d242a95af5b1b0d627 | 3b98c479cc9e450bad01ba1b2e0a5472215d8749 |
refs/heads/main | <repo_name>OuyKai/qlib<file_sep>/qlib/contrib/model/pytorch_ippe.py
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import copy
import random
from .pytorch_utils import count_parameters
from ...utils import (
get_or_create_path,
)
from ...log import get_module_logger
import torch
import torch.nn as nn
import torch.optim as optim
from ...model.base import Model
from ...data.dataset import DatasetH
from ...data.dataset.handler import DataHandlerLP
class IPPE(Model):
"""IPPE Model
Parameters
----------
d_feat : int
input dimension for each time step
metric: str
the evaluate metric used in early stop
optimizer : str
optimizer name
GPU : str
the GPU ID(s) used for training
"""
def __init__(
self,
d_feat=6,
hidden_size=64,
num_layers=2,
dropout=0.0,
n_epochs=200,
batch_size=100,
early_stop=5,
loss="mse",
output_dim=5,
lr=5e-4,
use_pretrain_pair=True,
use_pretrain_point=True,
pretrain_epoch=20,
pretrain_lr=2e-4,
point_enhance=True,
pair_enhance=True,
point_dim=10,
pair_dim=10,
iter_num=1,
evaluate_time=3,
inference_time=10,
metric="loss",
optimizer="adam",
GPU=0,
seed=None,
**kwargs
):
# Set logger.
self.logger = get_module_logger("IPPE")
self.logger.info("IPPE pytorch version...")
# set hyper-parameters.
self.d_feat = d_feat
self.hidden_size = hidden_size
self.num_layers = num_layers
self.dropout = dropout
self.n_epochs = n_epochs
self.batch_size = batch_size
self.early_stop = early_stop
self.loss = loss
self.output_dim = output_dim
self.lr = lr
self.use_pretrain_pair = use_pretrain_pair
self.use_pretrain_point = use_pretrain_point
self.pretrain_epoch = pretrain_epoch
self.pretrain_lr = pretrain_lr
self.point_enhance = point_enhance
self.pair_enhance = pair_enhance
self.point_dim = point_dim
self.pair_dim = pair_dim
self.iter_num = iter_num
self.evaluate_time = evaluate_time
self.inference_time = inference_time
self.optimizer = optimizer
self.metric = metric
self.device = torch.device("cuda:%d" % (GPU) if torch.cuda.is_available() else "cpu")
self.seed = seed
self.logger.info(
"IPPE parameters setting:"
"\nd_feat : {}"
"\nhidden_size : {}"
"\nnum_layers : {}"
"\ndropout : {}"
"\nn_epochs : {}"
"\nbatch_size : {}"
"\nearly_stop : {}"
"\nloss_type : {}"
"\noutput_dim : {}"
"\nlr : {}"
"\nuse_pretrain_pair : {}"
"\nuse_pretrain_point : {}"
"\npretrain_epoch : {}"
"\npretrain_lr : {}"
"\npoint_enhance : {}"
"\npair_enhance : {}"
"\npoint_dim : {}"
"\npair_dim : {}"
"\niter_num : {}"
"\ninference_time : {}"
"\noptimizer : {}"
"\nseed : {}".format(
d_feat,
hidden_size,
num_layers,
dropout,
n_epochs,
batch_size,
early_stop,
loss,
output_dim,
lr,
use_pretrain_pair,
use_pretrain_point,
pretrain_epoch,
pretrain_lr,
point_enhance,
pair_enhance,
point_dim,
pair_dim,
iter_num,
inference_time,
optimizer,
seed,
)
)
if self.seed is not None:
np.random.seed(self.seed)
torch.manual_seed(self.seed)
self.point_model = GRU_POINT(
d_feat=self.d_feat,
hidden_size=self.hidden_size,
num_layers=self.num_layers,
dropout=self.dropout,
).to(self.device)
self.pair_model = GRU_PAIR(
d_feat=self.d_feat*2,
hidden_size=self.hidden_size,
num_layers=self.num_layers,
dropout=self.dropout,
).to(self.device)
self.model = MUTUAL_ENHANCE(device=self.device,
point_input=self.hidden_size, \
pair_input=self.hidden_size, \
point_dim=self.point_dim, \
pair_dim=self.pair_dim, \
point_enhance=self.point_enhance, \
pair_enhance=self.pair_enhance).to(self.device)
for param in self.model.parameters():
param.requires_grad = True
param_list = list(self.model.parameters()) + list(self.point_model.parameters()) + list(self.pair_model.parameters())
self.logger.info("IPPE model size: {:.4f} MB".format(count_parameters(self.model)))
if optimizer.lower() == "adam":
self.train_optimizer = optim.Adam(param_list, lr=self.lr)
if self.use_pretrain_point:
self.point_pretrain_optimizer = optim.Adam(self.point_model.parameters(), lr=self.pretrain_lr)
if self.use_pretrain_pair:
self.pair_pretrain_optimizer = optim.Adam(self.pair_model.parameters(), lr=self.pretrain_lr)
elif optimizer.lower() == "gd":
self.train_optimizer = optim.SGD(param_list, lr=self.lr)
if self.use_pretrain_point:
self.point_pretrain_optimizer = optim.SGD(self.point_model.parameters(), lr=self.pretrain_lr)
if self.use_pretrain_pair:
self.pair_pretrain_optimizer = optim.SGD(self.pair_model.parameters(), lr=self.pretrain_lr)
else:
raise NotImplementedError("optimizer {} is not supported!".format(optimizer))
self.fitted = False
@property
def use_gpu(self):
return self.device != torch.device("cpu")
def mse(self, pred, label):
loss = (pred - label) ** 2
return torch.mean(loss)
def loss_fn(self, pred, label):
mask = ~torch.isnan(label)
if self.loss == "mse":
return self.mse(pred[mask], label[mask])
raise ValueError("unknown loss `%s`" % self.loss)
def metric_fn(self, pred, label):
mask = torch.isfinite(label)
if self.metric == "" or self.metric == "loss":
return -self.loss_fn(pred[mask], label[mask])
raise ValueError("unknown metric `%s`" % self.metric)
def pair_data_process(self, feature, label):
feature = np.array(feature)
label = np.array(label)
stock_num = feature.shape[0]
pair_label = []
if label.shape[0]:
vec_1 = np.repeat(label, stock_num).reshape(stock_num, stock_num)
vec_2 = np.transpose(vec_1)
pair_label = (vec_1 - vec_2).reshape(-1)
loc_1 = np.repeat(range(stock_num), stock_num).reshape(stock_num, stock_num)
loc_2 = np.transpose(loc_1)
loc_1 = loc_1.reshape([-1])
loc_2 = loc_2.reshape([-1])
return feature[loc_1], feature[loc_2], pair_label
def train_epoch(self, x_train, y_train):
self.model.train(True)
self.point_model.train(True)
self.pair_model.train(True)
days = x_train.index.get_level_values(0).unique()
total_day = days.shape[0]
day_index_seq = np.array(range(total_day))
random.shuffle(day_index_seq)
for _, day_index in enumerate(day_index_seq):
# prepare feature and label
day = days[day_index]
feature = np.array(x_train.loc[day])
label = np.array(y_train.loc[day]).reshape([-1])
stock_num = feature.shape[0]
loc = np.random.choice(stock_num, self.batch_size)
feature = feature[loc]
label = label[loc]
pair_feature1, pair_feature2, pair_label = self.pair_data_process(feature, label)
point_feature = torch.tensor(feature, dtype=torch.float, device=self.device)
point_label = torch.tensor(label, dtype=torch.float, device=self.device)
pair_feature1 = torch.tensor(pair_feature1, dtype=torch.float, device=self.device)
pair_feature2 = torch.tensor(pair_feature2, dtype=torch.float, device=self.device)
pair_label = torch.tensor(pair_label, dtype=torch.float, device=self.device)
# transfer feature to embedding
point = self.point_model(point_feature)
pair = self.pair_model(pair_feature1, pair_feature2)
point = self.model.transform_point(point)
pair = self.model.transform_pair(pair)
point_loss = 0
pair_loss = 0
if self.point_enhance:
point_pred = self.model.point2pred(point)
point_loss += self.loss_fn(point_pred.view(-1), point_label.view(-1))
if self.pair_enhance:
pair_pred = self.model.pair2pred(pair).view(-1)
pair_loss += self.loss_fn(pair_pred.view(-1), pair_label.view(-1))
for _ in range(self.iter_num):
point, pair = self.model(point, pair)
if self.point_enhance:
point_pred = self.model.point2pred(point)
point_loss += self.loss_fn(point_pred.view(-1), point_label.view(-1))
if self.pair_enhance:
pair_pred = self.model.pair2pred(pair).view(-1)
pair_loss += self.loss_fn(pair_pred.view(-1), pair_label.view(-1))
loss = (point_loss + pair_loss)/((1 + self.iter_num)*self.iter_num/2)
self.train_optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_value_(self.point_model.parameters(), 3.0)
self.train_optimizer.step()
def test_epoch(self, data_x, data_y):
self.model.eval()
self.point_model.eval()
self.pair_model.eval()
scores = []
losses = []
days = data_x.index.get_level_values(0).unique()
total_day = days.shape[0]
day_index_seq = np.array(range(total_day))
for _ in range(self.evaluate_time):
for _, day_index in enumerate(day_index_seq):
# prepare feature and label
day = days[day_index]
feature = np.array(data_x.loc[day])
label = np.array(data_y.loc[day]).reshape([-1])
stock_num = feature.shape[0]
loc = np.random.choice(stock_num, self.batch_size)
feature = feature[loc]
label = label[loc]
pair_feature1, pair_feature2, pair_label = self.pair_data_process(feature, label)
point_feature = torch.tensor(feature, dtype=torch.float, device=self.device)
point_label = torch.tensor(label, dtype=torch.float, device=self.device)
pair_feature1 = torch.tensor(pair_feature1, dtype=torch.float, device=self.device)
pair_feature2 = torch.tensor(pair_feature2, dtype=torch.float, device=self.device)
pair_label = torch.tensor(pair_label, dtype=torch.float, device=self.device)
with torch.no_grad():
# transfer feature to embedding
point = self.point_model(point_feature)
pair = self.pair_model(pair_feature1, pair_feature2)
point = self.model.transform_point(point)
pair = self.model.transform_pair(pair)
for _ in range(self.iter_num):
point, pair = self.model(point, pair)
point_pred = self.model.point2pred(point)
loss = self.loss_fn(point_pred, point_label)
losses.append(loss.item())
score = self.metric_fn(point_pred, point_label)
scores.append(score.item())
return np.mean(losses), np.mean(scores)
def pretrain_point_model(
self,
x_train,
y_train,
batch_size=2000,
):
x_train_values = x_train.values
y_train_values = np.squeeze(y_train.values)
self.point_model.train()
for step in range(self.pretrain_epoch):
self.logger.info("Epoch%d:", step)
indices = np.arange(len(x_train_values))
np.random.shuffle(indices)
for i in range(len(indices))[:: batch_size]:
if len(indices) - i < batch_size:
break
feature = torch.from_numpy(x_train_values[indices[i : i + batch_size]]).float().to(self.device)
label = torch.from_numpy(y_train_values[indices[i : i + batch_size]]).float().to(self.device)
point_embedding = self.point_model(feature)
pred = self.point_model.fc_out(point_embedding).squeeze()
loss = self.loss_fn(pred, label)
self.point_pretrain_optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_value_(self.point_model.parameters(), 3.0)
self.point_pretrain_optimizer.step()
def pretrain_pair_model(
self,
x_train,
y_train,
):
days = x_train.index.get_level_values(0).unique()
total_day = days.shape[0]
day_index_seq = np.array(range(total_day))
random.shuffle(day_index_seq)
for step in range(self.pretrain_epoch):
self.logger.info("Epoch%d:", step)
for _, day_index in enumerate(day_index_seq):
# prepare feature and label
day = days[day_index]
feature = np.array(x_train.loc[day])
label = np.array(y_train.loc[day]).reshape([-1])
stock_num = feature.shape[0]
loc = np.random.choice(stock_num, self.batch_size)
feature = feature[loc]
label = label[loc]
pair_feature1, pair_feature2, pair_label = self.pair_data_process(feature, label)
pair_feature1 = torch.tensor(pair_feature1, dtype=torch.float, device=self.device)
pair_feature2 = torch.tensor(pair_feature2, dtype=torch.float, device=self.device)
pair_label = torch.tensor(pair_label, dtype=torch.float, device=self.device)
pair_embedding = self.pair_model(pair_feature1, pair_feature2)
pair_pred = self.pair_model.fc_out(pair_embedding).squeeze()
loss = self.loss_fn(pair_pred, pair_label)
self.pair_pretrain_optimizer.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_value_(self.pair_model.parameters(), 3.0)
self.pair_pretrain_optimizer.step()
def fit(
self,
dataset: DatasetH,
evals_result=dict(),
save_path=None,
):
df_train, df_valid, _ = dataset.prepare(
["train", "valid", "test"],
col_set=["feature", "label"],
data_key=DataHandlerLP.DK_L,
)
save_path = get_or_create_path(save_path)
stop_steps = 0
best_score = -np.inf
best_epoch = 0
evals_result["valid"] = []
self.logger.info("training...")
self.fitted = True
if self.use_pretrain_point:
self.logger.info("pretrain point model...")
self.pretrain_point_model(df_train["feature"], df_train["label"])
if self.use_pretrain_pair:
self.logger.info("pretrain pair model...")
self.pretrain_pair_model(df_train["feature"], df_train["label"])
for step in range(self.n_epochs):
self.logger.info("Epoch%d:", step)
self.train_epoch(df_train["feature"], df_train["label"])
_, val_score = self.test_epoch(df_valid["feature"], df_valid["label"])
self.logger.info("valid %.6f" % (val_score))
evals_result["valid"].append(val_score)
if val_score > best_score:
best_score = val_score
stop_steps = 0
best_epoch = step
best_param = [copy.deepcopy(self.model.state_dict()),\
copy.deepcopy(self.point_model.state_dict()),\
copy.deepcopy(self.pair_model.state_dict())]
else:
stop_steps += 1
if stop_steps >= self.early_stop:
self.logger.info("early stop")
break
self.logger.info("best score: %.6lf @ %d" % (best_score, best_epoch))
self.model.load_state_dict(best_param[0])
self.point_model.load_state_dict(best_param[1])
self.pair_model.load_state_dict(best_param[2])
torch.save(best_param[0], save_path+'ippe')
torch.save(best_param[1], save_path+'point_model')
torch.save(best_param[2], save_path+'pair_model')
def predict(self, dataset: DatasetH):
if not self.fitted:
raise ValueError("model is not fitted yet!")
test_data = dataset.prepare("test", col_set=["feature", "label"], data_key=DataHandlerLP.DK_I)
x_test = test_data["feature"]
y_test = test_data["label"]
test_data.to_pickle("~/tmp_test_data.pkl")
self.model.eval()
self.point_model.eval()
self.pair_model.eval()
preds = []
indexes = []
days = x_test.index.get_level_values(0).unique()
total_day = days.shape[0]
for day_index in range(total_day):
# prepare feature and label
day = days[day_index]
daily_feature = np.array(x_test.loc[day])
daily_index = x_test.loc(axis=0)[day,:].index
stock_num = daily_feature.shape[0]
for _ in range(self.inference_time):
loc = np.random.choice(stock_num, self.batch_size)
feature = daily_feature[loc]
currend_index = daily_index[loc]
pair_feature1, pair_feature2, _ = self.pair_data_process(feature, [])
point_feature = torch.tensor(feature, dtype=torch.float, device=self.device)
pair_feature1 = torch.tensor(pair_feature1, dtype=torch.float, device=self.device)
pair_feature2 = torch.tensor(pair_feature2, dtype=torch.float, device=self.device)
with torch.no_grad():
# transfer feature to embedding
point = self.point_model(point_feature)
pair = self.pair_model(pair_feature1, pair_feature2)
point = self.model.transform_point(point)
pair = self.model.transform_pair(pair)
for _ in range(self.iter_num):
point, pair = self.model(point, pair)
point_pred = self.model.point2pred(point)
preds.append(point_pred.detach().cpu().numpy().reshape([-1]))
indexes.append(currend_index)
res_df = pd.Series(np.concatenate(preds), index=np.concatenate(indexes))
res_df.index = pd.MultiIndex.from_tuples(res_df.index)
res_df.index.names = ['datetime', 'instrument']
res_df = res_df.groupby(level=[0,1]).apply(lambda x:x.mean())
preds = pd.Series(np.zeros(x_test.shape[0]), index=test_data.index)
preds.loc[res_df.index] = np.array(res_df)
return preds
class GRU_POINT(nn.Module):
def __init__(self, d_feat=6, hidden_size=64, num_layers=2, dropout=0.0):
super().__init__()
self.rnn = nn.GRU(
input_size=d_feat,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True,
dropout=dropout,
)
self.fc_out = nn.Linear(hidden_size, 1)
self.d_feat = d_feat
def forward(self, x):
# x: [N, F*T]
x = x.reshape(len(x), self.d_feat, -1) # [N, F, T]
x = x.permute(0, 2, 1) # [N, T, F]
out, _ = self.rnn(x)
return out[:, -1, :].squeeze()
class GRU_PAIR(nn.Module):
def __init__(self, d_feat=6, hidden_size=64, num_layers=2, dropout=0.0):
super().__init__()
self.rnn = nn.GRU(
input_size=d_feat*2,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True,
dropout=dropout,
)
self.fc_out = nn.Linear(hidden_size, 1)
self.d_feat = d_feat
def forward(self, x, y):
# x: [N, F*T]
x = x.reshape(len(x), self.d_feat, -1) # [N, F, T]
x = x.permute(0, 2, 1) # [N, T, F]
y = y.reshape(len(y), self.d_feat, -1) # [N, F, T]
y = y.permute(0, 2, 1) # [N, T, F]
input = torch.cat((x, y), 2)
out, _ = self.rnn(input)
return out[:, -1, :].squeeze()
class MUTUAL_ENHANCE(nn.Module):
def __init__(self, device, point_input, pair_input, point_dim=10, pair_dim=10, point_enhance=True, pair_enhance=True):
super().__init__()
self.device = device
self.point_dim = point_dim
self.pair_dim = pair_dim
self.point_enhance = point_enhance
self.pair_enhance = pair_enhance
self.transform_point = nn.Linear(point_input, point_dim)
self.transform_pair = nn.Linear(pair_input, pair_dim)
self.point2pred = nn.Linear(point_dim, 1)
self.pair2pred = nn.Linear(pair_dim, 1)
# prepare lamda block
self.transferion_point = torch.nn.Parameter(torch.rand(self.point_dim, self.point_dim*self.pair_dim).cuda(), \
requires_grad=True)
self.transferion_pair = torch.nn.Parameter(torch.rand(self.point_dim, self.pair_dim*self.point_dim).cuda(), \
requires_grad=True)
self.lamda_point_func = nn.Sequential(
nn.Linear(3*self.point_dim+3, 16),
nn.ReLU(),
nn.Linear(16,16),
nn.ReLU(),
nn.Linear(16,1),
nn.Sigmoid())
self.omega_point_func = nn.Sequential(
nn.Linear(3*self.point_dim + 2*self.pair_dim + 2, 32),
nn.ReLU(),
nn.Linear(32,32),
nn.ReLU(),
nn.Linear(32,16),
nn.ReLU(),
nn.Linear(16,1))
self.lamda_pair_func = nn.Sequential(
nn.Linear(2*self.point_dim + 3*self.pair_dim + 2,16),
nn.ReLU(),
nn.Linear(16,16),
nn.ReLU(),
nn.Linear(16,1),
nn.Sigmoid())
self.softmax = torch.nn.Softmax(dim = 1)
def forward(self, point, pair):
# data prepare
stock_num = point.shape[0]
point_1 = point.expand(stock_num, stock_num, point.shape[1])
point_2 = torch.transpose(point_1,0,1)
pair = pair.view(stock_num, stock_num, -1)
pair_1 = pair
pair_2 = torch.transpose(pair_1,0,1)
if self.point_enhance:
# calculate point estimation embedding
correction_in_1 = pair_1.view(stock_num, stock_num, self.pair_dim, 1)
correction_in_2 = point_1.view(stock_num, stock_num, 1, self.point_dim)
tmp = torch.matmul(correction_in_2, self.transferion_point)
tmp = tmp.view(stock_num, stock_num, self.point_dim, self.pair_dim)
self.point_estimation = torch.matmul(tmp, correction_in_1).view(stock_num, stock_num, self.point_dim)
self.point_estimation_pred = self.point2pred(self.point_estimation)
# omega in
self.point_estimation_mean = torch.sum(self.point_estimation, dim=1)/stock_num
self.point_estimation_var = torch.std(self.point_estimation, dim=1)
self.point_estimation_pred_mean = torch.sum(self.point_estimation_pred, dim=1)/stock_num
self.point_estimation_pred_var = torch.std(self.point_estimation_pred, dim=1)
self.omega_in = torch.cat((pair_1, # embedding(i,j)
pair_2, # embedding(j,i)
point_1, # embedding(j)
point_2, # embedding(i)
self.point_estimation,
self.point_estimation_pred_mean.expand(stock_num, stock_num).view(stock_num, stock_num, -1),
self.point_estimation_pred_var.expand(stock_num, stock_num).view(stock_num, stock_num, -1),
), 2)
# omega out
self.omega_point = self.omega_point_func(self.omega_in)
self.omega_point = self.softmax(self.omega_point)
# calculate aggerated esetimation embedding
self.agg_point_estimation = torch.sum(self.omega_point*self.point_estimation, dim=1)
# self.agg_point_estimation = torch.sum(self.point_estimation, dim=1)/stock_num # average
# lambda in
agg_point_estimation_pred = self.point_estimation_pred*self.omega_point
agg_point_estimation_pred_mean = torch.sum(agg_point_estimation_pred, dim=1)/stock_num
agg_point_estimation_pred_var = torch.std(agg_point_estimation_pred, dim=1)
omega_std = torch.std(self.omega_point, dim=1)
distance = torch.abs(self.agg_point_estimation - point)
self.lamda_in_point = torch.cat((point,
self.agg_point_estimation.view(stock_num, -1),
agg_point_estimation_pred_mean.view(stock_num, -1),
agg_point_estimation_pred_var.view(stock_num, -1),
omega_std.view(stock_num, -1),
distance.view(stock_num, -1)
), 1)
# lambda out
self.lamda_point = self.lamda_point_func(self.lamda_in_point)
# update
point = (1-self.lamda_point)*point + self.lamda_point*self.agg_point_estimation
if self.pair_enhance:
# calculate pair estimation embedding
correction_in_1 = point_1.view(stock_num, stock_num, 1, self.point_dim)
correction_in_2 = point_2.view(stock_num, stock_num, self.point_dim, 1)
tmp = torch.matmul(correction_in_1, self.transferion_pair)
tmp = tmp.view(stock_num, stock_num, self.pair_dim, self.point_dim)
self.pair_estimation = torch.matmul(tmp, correction_in_2).view(stock_num, stock_num, self.pair_dim)
self.pair_estimation_pred = self.point2pred(self.pair_estimation)
# lambda in
self.pair_estimation_mean = torch.sum(self.pair_estimation, dim=1)/stock_num
self.pair_estimation_var = torch.std(self.pair_estimation, dim=1)
self.pair_estimation_pred_mean = torch.sum(self.pair_estimation_pred, dim=1)/stock_num
self.pair_estimation_pred_var = torch.std(self.pair_estimation_pred, dim=1)
self.lamda_in_pair = torch.cat((pair_1, # embedding(i,j)
pair_2, # embedding(j,i)
point_1, # embedding(j)
point_2, # embedding(i)
self.pair_estimation,
self.pair_estimation_pred_mean.expand([stock_num, stock_num]).view(stock_num, stock_num, -1),
self.pair_estimation_pred_var.expand([stock_num, stock_num]).view(stock_num, stock_num, -1),
), 2)
# lambda out
self.lambda_pair = self.lamda_pair_func(self.lamda_in_pair)
# update
pair = (1-self.lambda_pair)*pair + self.lambda_pair*self.pair_estimation
return point, pair
| a2e5856836d993c1a043dd38754d83d206d4dd34 | [
"Python"
]
| 1 | Python | OuyKai/qlib | 2c22871217b00a9d4d507919e66f7590ac899a7d | aed2f25e113f8073ed32b450902e2d1cd3eecef2 |
refs/heads/master | <repo_name>rodrigoieh/MinkPhantomJSDriver<file_sep>/bin/run-tests.sh
#!/bin/bash
set -e
BIN_DIR=$(cd $(dirname $0); pwd)
start_browser_api(){
LOCAL_PHANTOMJS="${BIN_DIR}/phantomjs"
if [ -f ${LOCAL_PHANTOMJS} ]; then
${LOCAL_PHANTOMJS} --ssl-protocol=any --ignore-ssl-errors=true "$BIN_DIR/../vendor/jcalderonzumba/gastonjs/src/Client/main.js" 8510 1024 768 2>&1 &
else
phantomjs --ssl-protocol=any --ignore-ssl-errors=true "$BIN_DIR/../vendor/jcalderonzumba/gastonjs/src/Client/main.js" 8510 1024 768 2>&1 >> /dev/null &
fi
sleep 2
}
stop_services(){
ps axo pid,command | grep phantomjs | grep -v grep | awk '{print $1}' | xargs -I {} kill {}
ps axo pid,command | grep php | grep -v grep | grep -v phpstorm | grep -v php-fpm | awk '{print $1}' | xargs -I {} kill {}
sleep 2
}
start_local_browser(){
${BIN_DIR}/mink-test-server > /dev/null 2>&1 &
sleep 2
}
function finish() {
stop_services
if [ -z "$MINK_STOP_BROWSER" ]; then
start_browser_api
fi
}
trap finish EXIT
mkdir -p /tmp/jcalderonzumba/phantomjs
stop_services || true
start_browser_api
start_local_browser
${BIN_DIR}/phpunit --configuration "$BIN_DIR/../integration_tests.xml"
| b029fb1e89162473455523489c4c2a956830ba2c | [
"Shell"
]
| 1 | Shell | rodrigoieh/MinkPhantomJSDriver | 00f2a62e892609550e11b27f0670a64d4fdeadde | 38a4a7cf68f339da0899263cccf5d473f320e0a2 |
refs/heads/master | <repo_name>oliverh57/Vision<file_sep>/php/proxy/proxy-stream.php
<?php
$config = include(dirname(__DIR__, 2)."/setup/config.php");
$server = $_GET['server'];
$port = $_GET['port'];
if($_GET['auth'] == $config['auth'])
{
$url = "/"; // image url on server
set_time_limit(0);
$fp = fsockopen($server, $port, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br>\n"; // error handling
} else {
$urlstring = "GET ".$url." HTTP/1.0\r\n\r\n";
fputs ($fp, $urlstring);
while ($str = trim(fgets($fp, 4096)))
header($str);
fpassthru($fp);
fclose($fp);
}
}
?><file_sep>/setup/config.php
<?php
return array(
'auth' => 'Your-random-string-here', #this is the authorisation code used for all internal authenticaion -> make it long!
'img_save_location' => '/var/cctv', #This sets where the snapshot images are stored.
'use_recaptcha' => 'False', #If the login site should use Google Recaptcha v2.0
'captcha_api_key' => 'APIKey', #The API key for your Google Recaptcha (AKA a secret key)
'captcha_site_key' => 'SiteKey', #The Site Key for your Google Recaptcha
'username' => 'user', #This is the username used to log in.
'password' => '<PASSWORD>', #This is the password used to log in.
'site_url' => 'https://your.site.com', #location the site is running from (ignore if site is not open to the web)
#CAMERA SETUP
'No_of_cams' => '3', #Set the number of cameras you are using
'cam1_ip' => '192.168.1.185', #configure each of your cameras here.
'cam1_port' => '8081',
'cam2_ip' => '192.168.1.185',
'cam2_port' => '8082',
'cam3_ip' => '192.168.1.185',
'cam3_port' => '8083'
#if your nummber of cameras is diffrent add or remove config sections like this
#'cam4_ip' => '192.168.1.185',
#'cam4_port' => '8083'
);
?>
<file_sep>/php/save.php
<?php
$config = include(dirname(__DIR__, 1)."/setup/config.php");
$server = $_GET['server'];
$cam = $_GET['cam'];
$save = $config['img_save_location'];
if($_GET['auth'] == $config['auth']){
$auth = $config['auth'];
copy("https://remotehound.ddns.net/php/proxy/proxy-image.php?cam=$cam&auth=$auth&server=$server", "/var/cctv/cam$cam/".date('Y-m-d H-i-s').".png");
}
?><file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<title>Remote Viewer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> </head>
<script src='https://www.google.com/recaptcha/api.js'></script>
<style>
body,
h1,
h2,
h3,
h4,
h5 {
font-family: "Raleway", sans-serif
}
</style>
<body class="w3-light-grey">
<div class="w3-content" style="max-width:1400px">
<!-- Header -->
<header class="w3-container w3-center w3-padding-32">
<h1><b>Remote Camera</b></h1>
<p>Secure image <span class="w3-tag">viewer</span></p>
</header>
<!-- Grid -->
<div class="w3-row">
<!-- Blog entries -->
<!-- Blog entry -->
<div class="w3-card-4 w3-margin w3-white"> <img src="/images/loginBanner.jpg" alt="banner" style="width:100%">
<div class="w3-container">
<h3><b>Login</b></h3>
</div>
<div class="w3-container">
<div class="w3-row">
<div class="w3-col m8 s12">
<form id="loginform" name="input" action="" method="post"> <label for="username" style="display: inline-block; width: 6em;">Username: </label><input type="text" value="" id="username" name="username" style="max-width:100%;" />
<p style="font-size:0px;"> <br></p> <label for="password" style="display: inline-block; width: 6em;">Password: </label><input type="password" value="" id="password" name="password" style="max-width:100%;" />
<?php
$config = include("setup/config.php");
if ($config["use_recaptcha"] == "True") {
require_once "./lib/recaptchalib.php";
echo '<br><div class="g-recaptcha" data-sitekey="' . $config["captcha_site_key"] . '"></div>';
}
?>
<br><br>
<p>
<?php
$config = include("setup/config.php");https://remotehound.ddns.net/auth/
if (isset($_POST["username"]) && isset($_POST["password"])){
if ($_POST["username"] == $config['username'] && $_POST["password"] == $config['<PASSWORD>']){
if ($config["use_recaptcha"] == "True") {
$response = null;
$reCaptcha = new ReCaptcha($config["captcha_api_key"]);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
setcookie("auth", $config['auth'], time() + (86400 * 30), "/");
header("Location: /auth");
die();
} else {
echo "Please check the captcha!";
}
}
else {
setcookie("auth", $config['auth'], time() + (86400 * 30), "/");
header("Location: /auth");
die();
}
}else {
echo "Username/Password incorrect!";
}
}
?>
</p> <br> <button class="w3-button w3-padding-large w3-white w3-border" type="submit">submit »</button> <br> <br> </form>
</div>
<div class="w3-col m4 w3-hide-small"> </div>
</div>
</div>
</div>
<hr>
<!-- END GRID -->
</div><br>
<!-- END w3-content -->
</div>
<!-- Footer -->
<footer class="w3-container w3-dark-grey w3-padding-32 w3-margin-top">
<p>Made By <b><NAME></b>, <b><NAME></b> and <b><NAME></b></p>
</footer>
</body>
</html>
<file_sep>/auth/index.php
<?php $cam = 1;
$config = include(dirname(__DIR__, 1)."/setup/config.php");
if ( ( isset($_COOKIE['auth']) ) && ( $_COOKIE['auth'] == $config['auth'] )){
echo <<<CAMERA
<!DOCTYPE html>
<html>
<title>Remote Hound</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="/lib/jquery-3.2.1.min.js"></script>
<script>
function savecam(cam, server) {
$.get("/php/save.php?action=1&cam=" + cam + "&auth=" + "{$config['auth']}" + "&server=" + server);
return false;
}
</script>
<style>
body,
h1,
h2,
h3,
h4,
h5 {
font-family: "Raleway", sans-serif
}
</style>
<body class="w3-light-grey">
<div class="w3-content" style="max-width:1400px">
<!-- Header -->
<header class="w3-container w3-center w3-padding-32">
<h1><b>Remote Camera</b></h1>
<p>Secure image <span class="w3-tag">viewer</span></p>
</header>
<div class="w3-row">
CAMERA;
function cam_loop($cam, $config){
echo <<<CAMERA
<!-- view cam${cam} large -->
<div id="cam${cam}-stream" class="w3-modal">
<div class="w3-modal-content w3-card-4 w3-animate-bottom">
<header class="w3-container w3-theme-l1">
<span onclick="document.getElementById('cam${cam}-stream').style.display='none'" class="w3-button w3-display-topright">×</span>
<h1>Images</h1>
</header>
<div class="w3-padding">
<img id="view_large${cam}" src="/images/loading.gif" alt="Cam${cam}" style="width:100%">
<script>
setTimeout(load_large${cam}, 500);
function load_large${cam}()
{
document.getElementById('view_large${cam}').src = '/php/proxy/proxy-stream.php?auth=' + "${config['auth']}" + "&port=" + "${config['cam'.$cam.'_port']}" + "&server=" + "${config['cam'.$cam.'_ip']}";
}
</script>
</div>
<footer class="w3-container w3-theme-l1">
</footer>
</div>
</div>
<div id="loader" class="loading"></div>
<!-- view cam1 -->
<div id="cam${cam}-view" class="w3-modal">
<div class="w3-modal-content w3-card-4 w3-animate-bottom">
<header class="w3-container w3-theme-l1">
<span onclick="document.getElementById('cam${cam}-view').style.display='none'" class="w3-button w3-display-topright">×</span>
<h1>Images</h1>
</header>
<div class="w3-padding">
CAMERA;
$save = $config['img_save_location'];
$dirname = "$save/cam${cam}/";
$images = scandir($dirname);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
$location_scr= $save."/cam${cam}/$curimg";
$image = base64_encode(file_get_contents($location_scr));
echo "<img class='w3-third' style='padding:2px;' src='data:image/png;base64,$image'>";
//echo "<img class = 'w3-third' style = 'padding: 2px' src=$location_scr />\n";
};
}
echo <<<CAMERA
</div>
<footer class="w3-container w3-theme-l1">
<p>images</p>
</footer>
</div>
</div>
<!--cam${cam} -->
<div class="w3-third">
<div class="w3-card-4 w3-margin w3-white">
<img id="view${cam}" src="/images/loading.gif" alt="Cam${cam}" style="width:100%"> <script>
setTimeout(load_${cam}, 500);
function load_${cam}()
{
document.getElementById('view${cam}').src = '/php/proxy/proxy-stream.php?auth=' + "${config['auth']}" + "&port=" + "${config['cam'.$cam.'_port']}" + "&server=" + "${config['cam'.$cam.'_ip']}";
}
</script>
<div class="w3-container">
<h3><b>Camera ${cam}</b></h3>
</div>
<div class="w3-container">
<div class="w3-row">
<button class="w3-button w3-padding-large w3-white w3-border w3-third" style="display: inline;" onclick="document.getElementById('cam${cam}-stream').style.display='block'"><b>Full Size</b></button>
<button class="w3-button w3-padding-large w3-white w3-border w3-third" style="display: inline;" onclick="savecam('${cam}', '${config['cam'.$cam.'_ip']}');"><b>Snapshot</b></button>
<button style="display: inline;" class="w3-button w3-padding-large w3-white w3-border w3-third" onclick="document.getElementById('cam${cam}-view').style.display='block'"><b>View images</b></button>
</div>
<br>
</div>
</div>
<hr>
</div>
CAMERA;
}
foreach (range(1,(int)$config['No_of_cams']) as $number) {
cam_loop($number, $config);
}
echo <<<CAMERA
</div> </div>
<!-- Footer -->
<footer class="w3-container w3-dark-grey w3-padding-32 w3-margin-top">
<p>Made by <b><NAME></b>, <b><NAME></b> and <b><NAME></b></p>
</footer>
</body>
</html>
CAMERA;
} else {
header("Location:". $config['site_url']);
};
?>
<file_sep>/README.md
# Vision
#### A front end network camera viewer with snapshot support and built in reverse proxy.
Vision is a front end for many common network cameras that enables you to:
- Password protect cameras and access them outside of your local network
- encrypt their stream
- take snapshots and view them all from the webclient
## New features in 2.1.1
Add optional ReCaptcha verification to login page as well as orgnisation.
## Installation instructions
* You will need to install a web sever, with PHP installed. (PHP 5 or 7)
* Clone the repository to your web directory using the command ``$ git clone https://github.com/oliverh57/Vision.git``.
* Edit the file `/setup/config.php` with information about your cameras and decide on an encryption key and username / password.
* If you are using this programs built in suport for reCAPTCHA V2.0 follow the guide [here](https://www.google.com/recaptcha/intro/android.html) on how to genrate your own set of keys.
* your camera viewer should now be fully operational.
## Important!
For this site to be secure you **MUST** use `https`. If not, your credentials will be sent in plain text over the internet. For a guide on how to set up `https` for **free** on your webserver follow [this](https://certbot.eff.org/) link.
## Side Note
> This software is designed as a front end for cheap network cameras. For full operation with no modification it is advised that you use [MotionEye](https://github.com/ccrisan/motioneye). This code can easily be adapted however for operation with other cameras; see the guide on adapting this code [here](https://github.com/oliverh57/Vision/wiki/Adapting-this-code)
## TODO
Future plans include:
- simplyfying setup by making an installer that prompts you for info for the config and genrates keys.
- adding a log out button
- adding video recoding functnality
## change log
### 2.1.1
Files tidied up.
### 2.1.0
Add optional ReCaptcha verification to login page.
### 2.0.0
Large Update to the way cameras are handled. The number of cameras can be dynamicly scaled (this version is no longer backwards compatable0.
### 1.0.1
Bug fixes
### 1.0.0
First Public release including many features such as:
- Snapshot support
- more simple install
## Attribution
This code had been developed by **<NAME>**, **<NAME>** and **<NAME>** - 09/10/2017
| 7911db844a70b223188f07b9f285e8b785738def | [
"Markdown",
"PHP"
]
| 6 | PHP | oliverh57/Vision | be7e94caf530c5cc108f25975cd7161b0097afc2 | ebbd536f183f759827b89f1ca75a0c9b6347d0c0 |
refs/heads/master | <file_sep>// Package conv implements conversion functions between basic data types.
package conv
import (
"errors"
"fmt"
"strconv"
)
var (
ErrUnknownType = errors.New("unknown type")
)
// ShouldInt64 converts the value into int64.
func ShouldInt64(v interface{}) (int64, error) {
switch v := v.(type) {
case string:
return strconv.ParseInt(v, 10, 64)
case fmt.Stringer:
return strconv.ParseInt(v.String(), 10, 64)
case bool:
if v {
return 1, nil
}
return 0, nil
case uint:
return int64(v), nil
case uint8:
return int64(v), nil
case uint16:
return int64(v), nil
case uint32:
return int64(v), nil
case uint64:
return int64(v), nil
case int:
return int64(v), nil
case int8:
return int64(v), nil
case int16:
return int64(v), nil
case int32:
return int64(v), nil
case int64:
return v, nil
case float32:
return int64(v), nil
case float64:
return int64(v), nil
}
return 0, ErrUnknownType
}
// MustInt64 converts the value into int64.
// It panics if an error occurs in conversion.
func MustInt64(v interface{}) int64 {
ret, err := ShouldInt64(v)
if err != nil {
panic(err)
}
return ret
}
// ShouldFloat64 converts the value into float64.
func ShouldFloat64(v interface{}) (float64, error) {
switch v := v.(type) {
case string:
return strconv.ParseFloat(v, 64)
case fmt.Stringer:
return strconv.ParseFloat(v.String(), 64)
case bool:
if v {
return 1.0, nil
}
return 0.0, nil
case uint:
return float64(v), nil
case uint8:
return float64(v), nil
case uint16:
return float64(v), nil
case uint32:
return float64(v), nil
case uint64:
return float64(v), nil
case int:
return float64(v), nil
case int8:
return float64(v), nil
case int16:
return float64(v), nil
case int32:
return float64(v), nil
case int64:
return float64(v), nil
case float32:
return float64(v), nil
case float64:
return v, nil
}
return 0, ErrUnknownType
}
// MustFloat64 converts the value into float64.
// It panics if an error occurs in conversion.
func MustFloat64(v interface{}) float64 {
ret, err := ShouldFloat64(v)
if err != nil {
panic(err)
}
return ret
}
// ShouldString converts the value into string.
func ShouldString(v interface{}) (string, error) {
switch v := v.(type) {
case string:
return v, nil
case fmt.Stringer:
return v.String(), nil
case []byte:
return string(v), nil
case bool:
return fmt.Sprintf("%t", v), nil
case uint:
return fmt.Sprintf("%d", v), nil
case uint8:
return fmt.Sprintf("%d", v), nil
case uint16:
return fmt.Sprintf("%d", v), nil
case uint32:
return fmt.Sprintf("%d", v), nil
case uint64:
return fmt.Sprintf("%d", v), nil
case int:
return fmt.Sprintf("%d", v), nil
case int8:
return fmt.Sprintf("%d", v), nil
case int16:
return fmt.Sprintf("%d", v), nil
case int32:
return fmt.Sprintf("%d", v), nil
case int64:
return fmt.Sprintf("%d", v), nil
case float32:
return fmt.Sprintf("%f", v), nil
case float64:
return fmt.Sprintf("%f", v), nil
default:
return "", ErrUnknownType
}
}
// MustString converts the value into string.
// It panics if an error occurs in conversion.
func MustString(v interface{}) string {
ret, err := ShouldString(v)
if err != nil {
panic(err)
}
return ret
}
<file_sep>package conv
import (
"testing"
)
type stringer struct{}
func (stringer) String() string {
return "1"
}
func TestShouldInt64(t *testing.T) {
tests := []struct {
name string
arg interface{}
want int64
wantErr bool
}{
{name: "string", arg: "1", want: 1, wantErr: false},
{name: "stringer", arg: stringer{}, want: 1, wantErr: false},
{name: "bool", arg: true, want: 1, wantErr: false},
{name: "bool", arg: false, want: 0, wantErr: false},
{name: "uint", arg: uint(1), want: 1, wantErr: false},
{name: "uint8", arg: uint8(1), want: 1, wantErr: false},
{name: "uint16", arg: uint16(1), want: 1, wantErr: false},
{name: "uint32", arg: uint32(1), want: 1, wantErr: false},
{name: "uint64", arg: uint64(1), want: 1, wantErr: false},
{name: "int", arg: 1, want: 1, wantErr: false},
{name: "int8", arg: int8(1), want: 1, wantErr: false},
{name: "int16", arg: int16(1), want: 1, wantErr: false},
{name: "int32", arg: int32(1), want: 1, wantErr: false},
{name: "int64", arg: int64(1), want: 1, wantErr: false},
{name: "float32", arg: float32(1), want: 1, wantErr: false},
{name: "float64", arg: float64(1), want: 1, wantErr: false},
{name: "unknown", arg: struct{}{}, want: 0, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ShouldInt64(tt.arg)
if (err != nil) != tt.wantErr {
t.Errorf("ShouldInt64() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("ShouldInt64() got = %v, want %v", got, tt.want)
}
})
}
}
func TestMustInt64(t *testing.T) {
tests := []struct {
name string
arg interface{}
want int64
wantPanic bool
}{
{name: "int", arg: 1, want: 1},
{name: "unknown", arg: struct{}{}, wantPanic: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
if r := recover(); (r != nil) != tt.wantPanic {
t.Errorf("MustInt64() panic = %v, wantPanic %v", r, tt.wantPanic)
}
}()
if got := MustInt64(tt.arg); got != tt.want {
t.Errorf("MustInt64() = %v, want %v", got, tt.want)
}
})
}
}
func TestShouldFloat64(t *testing.T) {
tests := []struct {
name string
arg interface{}
want float64
wantErr bool
}{
{name: "string", arg: "1", want: 1, wantErr: false},
{name: "stringer", arg: stringer{}, want: 1, wantErr: false},
{name: "bool", arg: true, want: 1, wantErr: false},
{name: "bool", arg: false, want: 0, wantErr: false},
{name: "uint", arg: uint(1), want: 1, wantErr: false},
{name: "uint8", arg: uint8(1), want: 1, wantErr: false},
{name: "uint16", arg: uint16(1), want: 1, wantErr: false},
{name: "uint32", arg: uint32(1), want: 1, wantErr: false},
{name: "uint64", arg: uint64(1), want: 1, wantErr: false},
{name: "int", arg: 1, want: 1, wantErr: false},
{name: "int8", arg: int8(1), want: 1, wantErr: false},
{name: "int16", arg: int16(1), want: 1, wantErr: false},
{name: "int32", arg: int32(1), want: 1, wantErr: false},
{name: "int64", arg: int64(1), want: 1, wantErr: false},
{name: "float32", arg: float32(1), want: 1, wantErr: false},
{name: "float64", arg: float64(1), want: 1, wantErr: false},
{name: "unknown", arg: struct{}{}, want: 0, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ShouldFloat64(tt.arg)
if (err != nil) != tt.wantErr {
t.Errorf("ShouldFloat64() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("ShouldFloat64() got = %v, want %v", got, tt.want)
}
})
}
}
func TestMustFloat64(t *testing.T) {
tests := []struct {
name string
arg interface{}
want float64
wantPanic bool
}{
{name: "int", arg: 1, want: 1},
{name: "unknown", arg: struct{}{}, wantPanic: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
if r := recover(); (r != nil) != tt.wantPanic {
t.Errorf("MustFloat64() panic = %v, wantPanic %v", r, tt.wantPanic)
}
}()
if got := MustFloat64(tt.arg); got != tt.want {
t.Errorf("MustFloat64() = %v, want %v", got, tt.want)
}
})
}
}
func TestShouldString(t *testing.T) {
tests := []struct {
name string
arg interface{}
want string
wantErr bool
}{
{name: "string", arg: "1", want: "1", wantErr: false},
{name: "stringer", arg: stringer{}, want: "1", wantErr: false},
{name: "[]byte", arg: []byte("1"), want: "1", wantErr: false},
{name: "bool", arg: true, want: "true", wantErr: false},
{name: "bool", arg: false, want: "false", wantErr: false},
{name: "uint", arg: uint(1), want: "1", wantErr: false},
{name: "uint8", arg: uint8(1), want: "1", wantErr: false},
{name: "uint16", arg: uint16(1), want: "1", wantErr: false},
{name: "uint32", arg: uint32(1), want: "1", wantErr: false},
{name: "uint64", arg: uint64(1), want: "1", wantErr: false},
{name: "int", arg: 1, want: "1", wantErr: false},
{name: "int8", arg: int8(1), want: "1", wantErr: false},
{name: "int16", arg: int16(1), want: "1", wantErr: false},
{name: "int32", arg: int32(1), want: "1", wantErr: false},
{name: "int64", arg: int64(1), want: "1", wantErr: false},
{name: "float32", arg: float32(1), want: "1.000000", wantErr: false},
{name: "float64", arg: float64(1), want: "1.000000", wantErr: false},
{name: "unknown", arg: struct{}{}, want: "", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ShouldString(tt.arg)
if (err != nil) != tt.wantErr {
t.Errorf("ShouldString() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("ShouldString() got = %v, want %v", got, tt.want)
}
})
}
}
func TestMustString(t *testing.T) {
tests := []struct {
name string
arg interface{}
want string
wantPanic bool
}{
{name: "int", arg: 1, want: "1"},
{name: "unknown", arg: struct{}{}, wantPanic: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer func() {
if r := recover(); (r != nil) != tt.wantPanic {
t.Errorf("MustString() panic = %v, wantPanic %v", r, tt.wantPanic)
}
}()
if got := MustString(tt.arg); got != tt.want {
t.Errorf("MustString() = %v, want %v", got, tt.want)
}
})
}
}
| 38bb4eb7c70580e7e93757db150479483aaa2491 | [
"Go"
]
| 2 | Go | onelrdm/conv | fb6cea39ce1d1c25ef952d742814b78633da1372 | 314946a200617325d99871ab1c19151e5ddffd09 |
refs/heads/master | <file_sep>require 'pry'
class CashRegister
attr_accessor :discount, :total, :list, :last_transaction
def initialize(discount = nil)
@total = 0
@discount = discount
@list = []
end
def add_item(title, price, quantity = 1)
@total += price * quantity
self.last_transaction = price * quantity
control = 0
while control < quantity
@list << title
control += 1
end
end
def apply_discount
@total = @total - @total * (@discount.to_f / 100.to_f)
discount ? "After the discount, the total comes to $#{@total.to_i}." : "There is no discount to apply."
end
def items
@list
end
def void_last_transaction
@total = self.total -= self.last_transaction
end
end
| 8df601839d2056edeaf332a1e63376458d7454dd | [
"Ruby"
]
| 1 | Ruby | d14a248/oo-cash-register-nyc-web-051418 | 48910723a5743a4887ca511f624480f7fd7361d6 | ec4a45b4cfe4d65a07c22381f28a6c09b80a32a7 |
refs/heads/master | <repo_name>oswystan/relayserver<file_sep>/x509.c
/*
**************************************************************************************
* Filename: x509.c
* Description: source file
*
* Version: 1.0
* Created: 2018-02-23 21:43:12
*
* Revision: initial draft;
**************************************************************************************
*/
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/evp.h>
#include <stdio.h>
#define LOG_TAG "x509"
#include "log.h"
void generate_fingerprint() {
FILE* fp = fopen("cacert.pem", "r");
if(!fp) {
loge("fail to open file");
return;
}
const EVP_MD* md = NULL;
md = EVP_sha256();
unsigned char buf[32];
int len = sizeof(buf);
unsigned int i = 0;
memset(buf, 0x00, sizeof(buf));
X509* x = PEM_read_X509(fp, NULL, NULL, NULL);
if(!x) {
loge("fail to read x509");
goto out;
}
X509_digest(x, md, buf, &len);
for(i=0; i<len; i++) {
printf("%02X:", buf[i]);
}
printf("\n");
out:
if(fp) fclose(fp);
if(x) X509_free(x);
}
int main()
{
generate_fingerprint();
return 0;
}
/********************************** END **********************************************/
<file_sep>/wrtc.cpp
#include <string>
#include <map>
using namespace std;
namespace wrtc {
//------------------------------------------
//
// internal data structures
//
//------------------------------------------
#define STREAM_CREATED 0x01
#define STREAM_INITED 0x02
#define STREAM_STARTED 0x04
class WrtcStream
{
int init() {
return initLocalCfg(localCfg);
}
void onMediaData(uint8_t* buf, uint32_t len) {
if(srtp->unprotect(buf, relayBuffer, len) <= 0) {
if(fdRelay >= 0) sendRelayData(relayBuffer, len);
return;
}
if(stun->handleMessage(buf, len) <= 0) return;
if(dtls->handleMessage(buf, len) <= 0) return;
log("invalid package");
}
void onRelayData(uint8_t* buf, uint32_t len) {
srtp->protect(buf, mediaBuffer, len);
sendMediaData(mediaBuffer, len);
}
int config(req) {
setRemoteCfg(req);
return 0;
}
int start(req) {
if(status & STREAM_STARTED) return 0;
mediaFd = createUdpClient(mediaPort);
relayFd = createUdpClient(relayPort);
rtcp->sendFir();
};
int relay(req) {
if(streamType == PUSH) {
if(getAddr(req->addr_dst, req->port_dst)) return 0;
addRelay(req->addr_dst, req->port_dst);
} else {
if(relayAddrs.size() > 0) {
addr = relayAddrs.begin();
} else {
addr = new sockaddr_in;
}
setAddr(req->addr_src, req->port_src, AF_INET);
}
}
int stop(req) {
if(!(status & STREAM_STARTED)) return 0;
rtcp->sendBye();
close(mediaFd) && close(relayFd);
}
private:
int sendMediaData(uint8_t* buf, uint32_t len);
int sendRelayData(uint8_t* buf, uint32_t len) {
for(auto &i : relayAddrs) {
sendto(fdRelay, buf, len, 0, i, sizeof(struct sockaddr_in));
}
}
public:
WrtcPeerCfg remoteCfg;
WrtcPeerCfg localCfg;
uint16_t mediaPort;
uint16_t relayPort;
int mediaFd;
int relayFd;
uint8_t* mediaBuffer;
uint8_t* relayBuffer;
list<struct sockaddr_in*> relayAddrs;
WrtcSRTP* srtp;
WrtcDTLS* dtls;
WrtcSTUN* stun;
WrtcRTCP* rtcp;
};
class WrtcPeerCfg
{
public:
string ufrag;
string password;
string fringerprint;
};
class WrtcMediaCfg
{
public:
uint32_t audioSsrc;
uint32_t videoSsrc;
uint32_t operation; // 1-push; 2-pull;
};
class WrtcProtocolSTUN {
public:
int handleMessage(uint8_t* buf, uint32_t len);
void sendBindingRequest();
void sendIndication();
int getPeerConnection();
};
class WrtcProtocolDTLS {
int init(const char* certfile, const char* keyfile);
int config(WrtcPeerCfg* cfg);
int handleMessage(uint8_t* buf, uint32_t len);
int exportMasterKey(uint8_t* material, uint32_t len);
int getStatus();
};
class WrtcProtocolSRTP {
int handleMessage(uint8_t* buf, uint32_t len);
int unprotect(uint8_t* in, uint8_t* out, uint32_t len);
int protect(uint8_t* in, uint8_t* out, uint32_t len);
int init(uint8_t* masterKey, uint32_t* len);
};
class WrtcProtocolRTCP {
void sendFir();
void sendReport();
void sendBye();
};
//------------------------------------------
//
// an udp message adapter
//
//------------------------------------------
class WrtcOperatorAdapter {
bool init() {
wrtcOperator = new WrtcOperator();
return wrtcOperator != NULL;
}
int createServer(uint16_t port) {
return createUdpServer(port);
}
void onMessage(uint8_t* buf, uint32_t len) {
req = parse(buf, len);
if(req->type != REQUEST) logerror() && return;
switch(req->command) {
case CREATE:
wrtcOperator->create(req); break;
case CONFIG:
wrtcOperator->config(req); break;
case START:
wrtcOperator->start(req); break;
case STOP:
wrtcOperator->stop(req); break;
case RELAY:
wrtcOperator->relay(req); break;
case DESTROY:
wrtcOperator->destroy(req); break;
case PING:
wrtcOperator->ping(req); break;
default:
sendresp(EINVAL);
}
}
private:
WrtcOperator* wrtcOperator;
};
};
//------------------------------------------
//
// operator methods
//
//------------------------------------------
class WrtcOperator{
void create(req) {
stream = new WrtcStream();
addStream(stream);
sendresp(OK, stream->ID());
}
void config(req){
stream = getStream(req->stream_id);
if(!stream) sendresp(ENORES);
stream->config(req);
sendresp(ESUCC, stream->localCfg);
}
void start(req) {
stream = getStream(req->stream_id);
if(!stream) sendresp(ENORES) && return;
stream->start();
sendresp(ESUCC);
}
void relay(req) {
stream = getStream(req->stream_id_src);
if(!stream) {
stream = getStream(req->stream_id_dst);
}
if(!stream) sendresp(ENORES) && return;
stream->relay(req)
sendresp(ESUCC);
}
void stop(req) {
stream = getStream(req->stream_id);
if(!stream) sendresp(ENORES) && return;
stream->stop();
sendresp(ESUCC);
}
void destroy(req) {
stream = getStream(req->stream_id);
if(!stream) sendresp(ENORES) && return;
removeStream(stream);
delete stream;
sendresp(ESUCC);
}
void ping(req) {
sendresp(ESUCC);
}
private:
map<uint32_t, WrtcStream*> localStreams;
};
//------------------------------------------
//
// AsyncSocket
//
//------------------------------------------
class AsyncSocket {
int init(uv_loop_t* loop);
int connect(const char* addr, uint16_t port);
int listen(const char* addr, uint16_t port);
int serve();
int send(uint8_t* buf, uint32_t len);
int close();
virtual void onrecv(uint8_t* buf, uint32_t len);
};
class MemPool {
int init(uint32_t size, uint32_t cnt);
uint8_t* accquire();
int release(uint8_t* buf);
int reset();
};
//------------------------------------------
//
// operator protocol
//
//------------------------------------------
struct operator_protocol_header{
uint32_t type;
uint32_t command;
uint32_t transaction;
};
struct operator_request_header {
operator_protocol_header header;
};
struct operator_reponse_header {
operator_protocol_header header;
uint32_t error;
};
struct operator_request_create {
operator_request_header header;
};
struct operator_response_create {
operator_reponse_header header;
uint32_t stream_id;
};
struct operator_request_config {
operator_request_header header;
uint32_t stream_id;
uint8_t ufrag[8];
uint8_t password[32];
uint8_t fingerprint[128];
uint32_t ssrc_audio; // 0-means inactive; other-means active
uint32_t ssrc_video;
uint16_t media_port;
uint16_t relay_port;
uint32_t operation; // 1-push; 2-pull;
};
struct operator_response_create {
operator_reponse_header header;
uint32_t stream_id;
uint8_t ufrag[8];
uint8_t password[32];
uint8_t fingerprint[128];
uint32_t ssrc_audio; // 0-means inactive; other-means active
uint32_t ssrc_video;
};
struct operator_request_relay {
operator_request_header header;
uint32_t stream_id_src;
uint32_t stream_id_dst;
uint8_t addr_src[64];
uint8_t addr_dst[64];
uint16_t port_src;
uint16_t port_dst;
uint32_t audio_ssrc;
uint32_t video_ssrc;
};
struct operator_response_create {
operator_reponse_header header;
};
struct operator_request_start {
operator_request_header header;
uint32_t stream_id;
};
struct operator_response_start {
operator_reponse_header header;
uint32_t stream_id;
};
struct operator_request_stop {
operator_request_header header;
uint32_t stream_id;
};
struct operator_response_stop {
operator_reponse_header header;
uint32_t stream_id;
};
struct operator_request_destroy {
operator_request_header header;
uint32_t stream_id;
};
struct operator_response_destroy {
operator_reponse_header header;
uint32_t stream_id;
};
struct operator_request_ping {
operator_request_header header;
};
struct operator_response_ping {
operator_reponse_header header;
};
<file_sep>/bio.cpp
#define LOG_TAG "bio"
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <list>
#include "log.h"
using namespace std;
static int mtu = 1440;
/* Helper struct to keep the filter state */
typedef struct dtls_bio_filter {
list<uint32_t> packets;
} dtls_bio_filter;
int dtls_bio_filter_new(BIO *bio) {
/* Create a filter state struct */
dtls_bio_filter *filter = new dtls_bio_filter;
bio->init = 1;
bio->ptr = filter;
bio->flags = 0;
return 1;
}
int dtls_bio_filter_free(BIO *bio) {
if(bio == NULL)
return 0;
/* Get rid of the filter state */
dtls_bio_filter *filter = (dtls_bio_filter *)bio->ptr;
if(filter != NULL) {
filter->packets.clear();
delete filter;
}
bio->ptr = NULL;
bio->init = 0;
bio->flags = 0;
return 1;
}
int dtls_bio_filter_write(BIO *bio, const char *in, int inl) {
/* Forward data to the write BIO */
int32_t ret = BIO_write(bio->next_bio, in, inl);
logd("bio write: %d %d", ret, inl);
dtls_bio_filter *filter = (dtls_bio_filter *)bio->ptr;
if(filter != NULL) {
filter->packets.push_back(ret);
}
return ret;
}
long dtls_bio_filter_ctrl(BIO *bio, int cmd, long num, void *ptr) {
switch(cmd) {
case BIO_CTRL_FLUSH:
return 1;
case BIO_CTRL_DGRAM_QUERY_MTU:
return mtu;
case BIO_CTRL_WPENDING:
return 0L;
case BIO_CTRL_PENDING: {
/* We only advertize one packet at a time, as they may be fragmented */
dtls_bio_filter *filter = (dtls_bio_filter *)bio->ptr;
if(filter == NULL)
return 0;
if(filter->packets.empty()) return 0;
/* Get the first packet that hasn't been read yet */
int32_t size = *(filter->packets.begin());
filter->packets.pop_front();
return size;
}
default:
loge("invalid ctrl cmd: %d", cmd);
}
return 0;
}
static BIO_METHOD dtls_bio_filter_methods = {
BIO_TYPE_FILTER,
"janus filter",
dtls_bio_filter_write,
NULL,
NULL,
NULL,
dtls_bio_filter_ctrl,
dtls_bio_filter_new,
dtls_bio_filter_free,
NULL
};
extern "C" BIO_METHOD *BIO_dtls_filter(void) {
return(&dtls_bio_filter_methods);
}
<file_sep>/makefile
#######################################################################
## Copyright (C) 2017 wystan
##
## filename: makefile
## description:
## created: 2017-07-06 11:42:13
## author: wystan
##
#######################################################################
.PHONY: all clean
prog_dtls := dtls
prog_main := a.out
prog_srtp := srtp
prog_stun := stunsrv
prog_x509 := x509
prog_uv := uv
bin := $(prog_dtls) $(prog_main) $(prog_srtp) $(prog_stun) $(prog_x509) $(prog_uv)
cert := cacert.pem cakey.pem
cflags := -I./thirdparty/srtp/include -std=c++11
ld_flags := -L./thirdparty/srtp/lib -lssl -lcrypto -ldl -lsrtp2 -lz -luv
h := $(if $(filter 1,$V),,@)
all: $(bin) $(cert)
$(prog_main): main.o stun.o bio.o udp_socket.o
$(h) g++ $^ -o $@ $(ld_flags)
@ echo "[gen] "$@
$(prog_dtls): dtls.o bio.o
$(h) g++ $^ -o $@ $(ld_flags)
@ echo "[gen] "$@
$(prog_srtp): srtp.o
$(h) g++ $^ -o $@ $(ld_flags)
@ echo "[gen] "$@
$(prog_stun): stunsrv.o stun.o
$(h) g++ $^ -o $@ $(ld_flags)
@ echo "[gen] "$@
$(prog_x509): x509.c
$(h) gcc $^ -o $@ $(ld_flags)
@ echo "[gen] "$@
$(prog_uv): uv.o
$(h) g++ $^ -o $@ $(ld_flags)
@ echo "[gen] "$@
%.o:%.c
$(h) g++ -c -g $(cflags) $< -o $@
@ echo "[ cc] "$@
%.o:%.cpp
$(h) g++ -c -g $(cflags) $< -o $@
@ echo "[cpp] "$@
$(cert):
$(h) openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout $(word 2,$(cert)) -out $(word 1,$(cert)) \
-subj /C=CN/ST=BJ/L=Beijing/O=TAL/OU=LiveCloud/CN=wystan/emailAddress=<EMAIL> \
> /dev/null 2>&1
@ echo "[gen]" $(cert)
clean:
@echo "cleaning..."
$(h) rm -f *.o $(bin)
@echo "done."
#######################################################################
<file_sep>/udp_socket.h
/*
**************************************************************************************
* Filename: udp_socket.h
* Description: header file
*
* Version: 1.0
* Created: 2018-02-25 17:34:01
*
* Revision: initial draft;
**************************************************************************************
*/
#ifndef UDP_SOCKET_H_INCLUDED
#define UDP_SOCKET_H_INCLUDED
#include <inttypes.h>
#include <uv.h>
#include <list>
class DataHandler {
public:
virtual ~DataHandler() {}
virtual void onclose() = 0;
virtual void onconnected() = 0;
virtual void onmsg(uint8_t* buf, uint32_t len, const sockaddr_in* addr) = 0;
};
class UdpSocket {
public:
int init(uv_loop_t* loop, DataHandler* handler, uint32_t bufSize);
int connect(const char* addr, uint16_t port);
int listen(const char* addr, uint16_t port);
int serve();
int send(uint8_t* buf, uint32_t len, const sockaddr_in* addr);
int close();
int getbuf(uv_buf_t* buf);
void onrecv(uint8_t* buf, uint32_t len, const sockaddr* addr, uint32_t flags);
void onclose();
protected:
uv_loop_t* looper = nullptr;
uint8_t* recvbuf = nullptr;
uint32_t bufSize = 0;
DataHandler* handler = nullptr;
uv_udp_t handle;
bool served = false;
};
#endif /*UDP_SOCKET_H_INCLUDED*/
/********************************** END **********************************************/
<file_sep>/udp_socket.cpp
/*
**************************************************************************************
* Filename: udp_socket.cpp
* Description: source file
*
* Version: 1.0
* Created: 2018-02-25 17:34:04
*
* Revision: initial draft;
**************************************************************************************
*/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"
#include "udp_socket.h"
static void alloc_buf(uv_handle_t *handle, size_t size, uv_buf_t* buf) {
UdpSocket* socket = (UdpSocket*)handle->data;
if(!socket) return;
socket->getbuf(buf);
}
static void on_recv(uv_udp_t *req, ssize_t nread,
const uv_buf_t* buf, const struct sockaddr *addr,
unsigned flags) {
if(!req || !req->data) return;
UdpSocket* socket = (UdpSocket*)req->data;
socket->onrecv((uint8_t*)buf->base, nread, addr, flags);
}
static void on_close(uv_handle_t* handle) {
if(!handle || !handle->data) return;
UdpSocket* socket = (UdpSocket*)handle->data;
socket->onclose();
}
int UdpSocket::init(uv_loop_t* loop, DataHandler* dataHandler, uint32_t bufSize) {
if(!loop || !handler) {
loge("invalid param: %p %p", loop, handler);
return -EINVAL;
}
recvbuf = (uint8_t*)malloc(bufSize);
if(!recvbuf) return -ENOMEM;
this->bufSize = bufSize;
looper = loop;
handler = dataHandler;
memset(&handle, 0x00, sizeof(handle));
handle.data = this;
served = false;
return 0;
}
int UdpSocket::connect(const char* addr, uint16_t port) {
if(!addr) {
loge("null addr");
return -EINVAL;
}
struct sockaddr_in localaddr;
int ret = uv_ip4_addr(addr, port, &localaddr);
if(ret != 0) {
loge("invalid ip or port: %s, %d", addr, port);
goto out;
}
uv_udp_init(looper, &handle);
ret = uv_udp_bind(&handle, (struct sockaddr*)&localaddr, 0);
if(ret != 0) {
loge("fail to bind: %s", uv_strerror(ret));
goto out;
}
if(handler) handler->onconnected();
out:
return ret;
}
int UdpSocket::listen(const char* addr, uint16_t port) {
if(!addr) {
loge("null addr");
return -EINVAL;
}
struct sockaddr_in localaddr;
int ret = uv_ip4_addr(addr, port, &localaddr);
if(ret != 0) {
loge("invalid ip or port: %s, %d", addr, port);
goto out;
}
uv_udp_init(looper, &handle);
ret = uv_udp_bind(&handle, (struct sockaddr*)&localaddr, 0);
if(ret != 0) {
loge("fail to bind: %s", uv_strerror(ret));
goto out;
}
out:
return ret;
}
int UdpSocket::serve() {
int ret = uv_udp_recv_start(&handle, alloc_buf, on_recv);
if(ret != 0) {
loge("fail to serve: %s", uv_strerror(ret));
return ret;
}
served = true;
if(handler) handler->onconnected();
return 0;
}
int UdpSocket::send(uint8_t* buf, uint32_t len, const sockaddr_in* addr) {
uv_buf_t uvbuf;
uv_udp_send_t req;
uvbuf.base = (char*)buf;
uvbuf.len = len;
return uv_udp_send(&req, &handle, &uvbuf, 1, (const sockaddr*)addr, NULL);
}
int UdpSocket::close() {
if(served) {
uv_udp_recv_stop(&handle);
served = false;
}
uv_close((uv_handle_t*)&handle, on_close);
return 0;
}
int UdpSocket::getbuf(uv_buf_t* buf) {
buf->base = (char*)recvbuf;
buf->len = bufSize;
return 0;
}
void UdpSocket::onrecv(uint8_t* buf, uint32_t len, const sockaddr* addr, uint32_t flags) {
if(handler) handler->onmsg(buf, len, (const sockaddr_in*)addr);
}
void UdpSocket::onclose() {
if(handler) handler->onclose();
}
/********************************** END **********************************************/
<file_sep>/bio.h
/*
**************************************************************************************
* Filename: bio.h
* Description: header file
*
* Version: 1.0
* Created: 2018-02-17 10:56:16
*
* Revision: initial draft;
**************************************************************************************
*/
#ifndef BIO_H_INCLUDED
#define BIO_H_INCLUDED
#include <openssl/bio.h>
extern "C" BIO_METHOD *BIO_dtls_filter(void);
#endif /*BIO_H_INCLUDED*/
/********************************** END **********************************************/
<file_sep>/srtp.cpp
/*
**************************************************************************************
* Filename: srtp.c
* Description: source file
*
* Version: 1.0
* Created: 2018-02-10 11:55:30
*
* Revision: initial draft;
**************************************************************************************
*/
#define LOG_TAG "srtp"
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <srtp2/srtp.h>
#include "log.h"
#include "rtp.h"
#define MASTER_KEY 16
#define MASTER_SALT 14
#define MASTER_LEN (MASTER_KEY+MASTER_SALT)
uint16_t srv_port = 8881;
uint16_t cli_port = 8882;
const char* srv_ip = "127.0.0.1";
const char* cafile = "cacert.pem";
const char* pkfile = "cakey.pem";
static SSL_CTX *ssl_ctx = NULL;
static X509* ssl_cert = NULL;
static EVP_PKEY* ssl_key = NULL;
static DH* ssl_dh = NULL;
static SSL* ssl = NULL;
static srtp_policy_t policy_remote;
static srtp_policy_t policy_local;
static srtp_t stream_in;
static srtp_t stream_out;
static unsigned char rtp_buf[4096];
static unsigned char srtp_buf[4096];
int udp_new_server() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = bind(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to bind addr: %s %d [%s]", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server is running on: %s:%d fd:%d", srv_ip, srv_port, fd);
return fd;
}
int udp_new_client() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = connect(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to connect server: %s, %d <%s>", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server connected");
return fd;
}
int sec_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
logd("preverify: %d ctx:%p", preverify_ok, ctx);
return 1;
}
int sec_cert_verify_callback(X509_STORE_CTX* store, void* arg) {
if(!store || !arg) {
return 1;
}
return 1;
}
void sec_info_callback(const SSL* ssl, int where, int ret) {
if(!ssl || !ret) {}
if(where & SSL_CB_LOOP) logd("SSL_CB_LOOP");
if(where & SSL_CB_EXIT) logd("SSL_CB_EXIT");
if(where & SSL_CB_READ) logd("SSL_CB_READ");
if(where & SSL_CB_WRITE) logd("SSL_CB_WRITE");
if(where & SSL_CB_ALERT) logd("SSL_CB_ALERT");
if(where & SSL_CB_HANDSHAKE_START) logd("SSL_CB_HANDSHAKE_START");
if(where & SSL_CB_HANDSHAKE_DONE) logd("SSL_CB_HANDSHAKE_DONE");
}
int sec_load_key() {
FILE* fp = fopen(cafile, "r");
if(!fp) {
loge("fail to open ca file: %s", cafile);
return -1;
}
ssl_cert = PEM_read_X509(fp, NULL, NULL, NULL);
if(!ssl_cert) {
loge("fail to read ca file: %s", cafile);
goto error;
}
fclose(fp);
fp = fopen(pkfile, "r");
if(!fp) {
loge("fail to open private key: %s", pkfile);
goto error;
}
ssl_key = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
if(!ssl_key) {
loge("fail to read private key: %s", pkfile);
goto error;
}
fclose(fp);
return 0;
error:
if(fp) fclose(fp);
if(ssl_cert) X509_free(ssl_cert);
if(ssl_key) EVP_PKEY_free(ssl_key);
if(ssl_dh) DH_free(ssl_dh);
ssl_cert = NULL;
ssl_key = NULL;
return -1;
}
int sec_env_init(int isserver) {
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
if(isserver) {
ssl_ctx = SSL_CTX_new(DTLS_server_method());
} else {
ssl_ctx = SSL_CTX_new(DTLS_client_method());
}
if(!ssl_ctx) {
loge("fail to create SSL_CTX");
return -1;
}
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, sec_verify_callback);
if(0 != sec_load_key()) return -1;
if(!SSL_CTX_use_certificate(ssl_ctx, ssl_cert)) {
loge("fail to use certificate");
return -1;
}
if(!SSL_CTX_use_PrivateKey(ssl_ctx, ssl_key)) {
loge("fail to use priv key");
return -1;
}
if(!SSL_CTX_check_private_key(ssl_ctx)) {
loge("fail to check priv key");
return -1;
}
SSL_CTX_set_read_ahead(ssl_ctx, 1);
SSL_CTX_set_cipher_list(ssl_ctx, "ALL:NULL:eNULL:aNULL");
SSL_CTX_set_tlsext_use_srtp(ssl_ctx, "SRTP_AES128_CM_SHA1_80");
if(0 != srtp_init()) {
loge("fail to init srtp");
}
logi("secure env setup ok.");
return 0;
}
void sec_env_uninit() {
return;
}
int run_srv() {
logfunc();
int ret = 0;
struct sockaddr_in addr;
char buf[4096];
unsigned char material[MASTER_LEN*2];
size_t cnt = 0;
BIO* bio = NULL;
EC_KEY* ecdh = NULL;
srtp_err_status_t res;
rtp_header* header = NULL;
if(0 != sec_env_init(1)) {
return -1;
}
int fd = udp_new_server();
if(fd < 0) return -1;
ssl = SSL_new(ssl_ctx);
if(!ssl) {
loge("fail to new ssl");
goto exit;
}
SSL_set_ex_data(ssl, 0, NULL);
SSL_set_info_callback(ssl, sec_info_callback);
bio = BIO_new_dgram(fd, BIO_NOCLOSE);
SSL_set_bio(ssl, bio, bio);
SSL_set_accept_state(ssl);
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if(!ecdh) {
log("fail to create ECKEY");
goto exit;
}
SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
SSL_set_tmp_ecdh(ssl, ecdh);
EC_KEY_free(ecdh);
SSL_set_read_ahead(ssl, 1);
/* do handshake */
logd("waiting for handshake %p ...", ssl->handshake_func);
bzero(&addr, sizeof(addr));
ret = SSL_accept(ssl);
if(ret != 1) {
loge("fail to accept: %d %s", ret, ERR_error_string(SSL_get_error(ssl, ret), NULL));
goto exit;
}
logd("handshake ok.");
/* export master and salt */
bzero(material, sizeof(material));
if(!SSL_export_keying_material(ssl, material, sizeof(material), "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
loge("fail to export key");
} else {
log("MASTER KEY:");
log("\n---------------------\n");
for(ret=0; ret<(int)sizeof(material); ret++) {
if(ret > 0 && ret % 8 == 0) log("\n");
log("%02x ", material[ret]);
}
log("\n---------------------\n");
}
bzero(&policy_remote, sizeof(policy_remote));
srtp_crypto_policy_set_rtp_default(&policy_remote.rtp);
srtp_crypto_policy_set_rtcp_default(&policy_remote.rtcp);
policy_remote.ssrc.type = ssrc_any_inbound;
unsigned char remote_policy_key[MASTER_LEN];
policy_remote.key = remote_policy_key;
policy_remote.window_size = 128;
policy_remote.allow_repeat_tx = 0;
memcpy(policy_remote.key, material, MASTER_KEY);
memcpy(policy_remote.key+MASTER_KEY, material+MASTER_LEN, MASTER_SALT);
res = srtp_create(&stream_in, &policy_remote);
if(res != srtp_err_status_ok) {
loge("fail to create srtp: %d", res);
goto exit;
}
/* recv msg and exit */
while(1) {
bzero(buf, sizeof(buf));
cnt = BIO_read(bio, buf, sizeof(buf));
/*cnt = SSL_read(ssl, buf, sizeof(buf)-1);*/
if(cnt == (size_t)-1) {
loge("fail to recv data: %s", strerror(errno));
break;
}
int len = cnt;
res = srtp_unprotect(stream_in, buf, &len);
if(res != srtp_err_status_ok) {
loge("fail to unprotect srtp: %d", res);
break;
}
buf[len] = '\0';
header = (rtp_header*)buf;
char* str = buf + sizeof(rtp_header);
logd("rtp ssrc: %d", ntohl(header->ssrc));
logd("msg: %s", str);
break;
}
exit:
if(ssl) {
SSL_shutdown(ssl);
SSL_free(ssl);
}
close(fd);
logw("server exit.");
return 0;
}
int run_client() {
logfunc();
int ret = 0;
int len = 0;
char buf[4096];
unsigned char material[MASTER_LEN*2];
srtp_err_status_t res;
BIO* bio = NULL;
unsigned char master_key[MASTER_LEN];
char* data = buf + sizeof(rtp_header);
rtp_header* header = (rtp_header*)buf;
struct sockaddr peer;
socklen_t peerlen = sizeof(peer);
if(0 != sec_env_init(0)) {
return -1;
}
int fd = udp_new_client();
size_t cnt = 0;
EC_KEY* ecdh = NULL;
if(fd < 0) return -1;
if (getsockname(fd, &peer, &peerlen) < 0) {
loge("fail to get sock addr: %s", strerror(errno));
goto exit;
}
ssl = SSL_new(ssl_ctx);
if(!ssl) {
loge("fail to new ssl");
goto exit;
}
SSL_set_ex_data(ssl, 0, NULL);
SSL_set_info_callback(ssl, sec_info_callback);
bio = BIO_new_dgram(fd, BIO_NOCLOSE);
if(!bio) {
loge("fail to new bio dgram");
goto exit;
}
BIO_ctrl_set_connected(bio, 1, &peer);
SSL_set_bio(ssl, bio, bio);
SSL_set_connect_state(ssl);
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if(!ecdh) {
log("fail to create ECKEY");
goto exit;
}
SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
SSL_set_tmp_ecdh(ssl, ecdh);
EC_KEY_free(ecdh);
SSL_set_read_ahead(ssl, 1);
logd("starting handshake...");
ret = SSL_connect(ssl);
if(ret != 1) {
loge("fail to do SSL_connect: %d %s", ret, ERR_error_string(SSL_get_error(ssl, ret), NULL));
goto exit;
}
logd("handshake DONE.");
/* export master and salt */
bzero(material, sizeof(material));
if(!SSL_export_keying_material(ssl, material, sizeof(material), "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
loge("fail to export key");
} else {
log("MASTER KEY:");
log("\n---------------------\n");
for(ret=0; ret<(int)sizeof(material); ret++) {
if(ret > 0 && ret % 8 == 0) log("\n");
log("%02x ", material[ret]);
}
log("\n---------------------\n");
}
bzero(&policy_local, sizeof(policy_local));
srtp_crypto_policy_set_rtp_default(&policy_local.rtp);
srtp_crypto_policy_set_rtcp_default(&policy_local.rtcp);
policy_local.ssrc.type = ssrc_any_inbound;
policy_local.key = master_key;
policy_local.window_size = 128;
policy_local.allow_repeat_tx = 0;
memcpy(policy_local.key, material, MASTER_KEY);
memcpy(policy_local.key+MASTER_KEY, material+MASTER_LEN, MASTER_SALT);
res = srtp_create(&stream_out, &policy_local);
if(res != srtp_err_status_ok) {
loge("fail to client create srtp: %d", res);
goto exit;
}
//send message to server
header->version = 2;
header->type = 96;
header->ssrc = htonl(1234);
header->csrccount = 0;
header->seq_number = 100;
header->timestamp = htonl(0x01020304);
snprintf(data, sizeof(buf)-sizeof(rtp_header), "hello, world!!!!");
logd("send: %s", data);
len = strlen(data) + sizeof(rtp_header);
res = srtp_protect(stream_out, buf, &len);
if(res != srtp_err_status_ok) {
loge("fail to protect data");
goto exit;
}
cnt = BIO_write(bio, buf, len);
if(cnt == (size_t)-1) loge("fail to send: %s", strerror(errno));
logd("send data OK");
close(fd);
exit:
return 0;
}
int usage(const char* prog) {
log("usage: %s <c|s>\n", prog);
return -1;
}
int main(int argc, const char *argv[]) {
if(argc == 2) {
if(strcmp(argv[1], "s") == 0) return run_srv();
if(strcmp(argv[1], "c") == 0) return run_client();
}
return usage(argv[0]);
}
/********************************** END **********************************************/
<file_sep>/stun.h
/*
**************************************************************************************
* Filename: stun.h
* Description: header file
*
* Version: 1.0
* Created: 2018-02-10 14:24:31
*
* Revision: initial draft;
**************************************************************************************
*/
#ifndef STUN_H_INCLUDED
#define STUN_H_INCLUDED
#include <inttypes.h>
#include <netinet/in.h>
#if __BYTE_ORDER == __BIG_ENDIAN
#elif __BYTE_ORDER == __LITTLE_ENDIAN
#endif
#define __packed __attribute__((packed))
#define STUN_COOKIE 0x2112A442
#define STUN_PORT_FACTOR 0x2112
#define STUN_ALIGNED(x) ((x+3)/4*4)
enum stun_method {
STUN_METHOD_BINDING = 0x0001,
};
enum stun_class {
STUN_REQUEST = 0x0000,
STUN_INDICATION = 0x0010,
STUN_SUCC_RESPONSE = 0x0100,
STUN_ERROR_RESPONSE = 0x0110,
};
enum stun_attr_type {
MAPPED_ADDRESS = 0x0001,
RESPONSE_ADDRESS,
CHANGE_ADDRESS,
SOURCE_ADDRESS,
CHANGED_ADDRESS,
USERNAME, //0x06
PASSWORD,
MESSAGE_INTEGRITY, //0x08
ERROR_CODE,
UNKNOWN,
REFLECTED_FROM,
REALM = 0x0014,
NONCE = 0x0015,
XOR_MAPPED_ADDRESS = 0x0020,
SOFTWARE = 0x8022,
ALTERNATE_SERVER = 0x8023,
PRIORITY = 0x0024,
USE_CANDIDATE = 0x0025,
FINGERPRINT = 0x8028,
ICE_CONTROLLED = 0x8029, /* https://tools.ietf.org/html/rfc5245#section-21.2 */
ICE_CONTROLLING = 0x802A,
WRTC_UNKNOWN = 0xc057,
};
typedef struct __packed stun_header {
uint16_t type;
uint16_t len; /* length of the message not including the header aligned by 4 bytes */
uint32_t cookie; /* fixed to 0x2112A442 according to the protocol */
uint8_t trans_id[12]; /* unique id */
} stun_header;
typedef struct __packed stun_attr_header {
uint16_t type;
uint16_t len; /* should by aligned by 4 bytes */
} stun_attr_header;
typedef struct __packed stun_attr_username {
stun_attr_header header;
char username[0];
} stun_attr_username;
typedef struct __packed stun_attr_unknown {
stun_attr_header header;
uint16_t attrs[0];
} stun_attr_unknown;
typedef struct __packed stun_attr_xor_mapped_address_ipv4 {
stun_attr_header header;
uint8_t resvered;
uint8_t family;
uint16_t port;
uint32_t addr;
} stun_attr_xor_mapped_address_ipv4;
typedef struct __packed stun_attr_xor_mapped_address_ipv6 {
stun_attr_header header;
uint8_t resvered;
uint8_t family;
uint16_t port;
uint8_t addr[8];
} stun_attr_xor_mapped_address_ipv6;
typedef struct __packed stun_attr_message_integrity {
stun_attr_header header;
uint8_t sha1[20];
} stun_attr_message_integrity;
typedef struct __packed stun_attr_fingerprint {
stun_attr_header header;
uint32_t crc32;
} stun_attr_fingerprint;
typedef struct __packed stun_attr_ice_controlling {
stun_attr_header header;
uint64_t tiebreaker;
} stun_attr_ice_controlling;
typedef struct __packed stun_attr_use_candidate {
stun_attr_header header;
} stun_attr_use_candidate;
typedef struct __packed stun_attr_priority {
stun_attr_header header;
uint32_t priority;
} stun_attr_priority;
typedef struct __packed _stun_message_t {
uint8_t* buf;
uint32_t len;
uint32_t used;
stun_header* header;
} stun_message_t;
stun_message_t* stun_alloc_message();
void stun_free_message(stun_message_t* msg);
int stun_add_attr(stun_message_t* msg, stun_attr_header* attr);
stun_attr_header* stun_get_attr(stun_message_t* msg, uint16_t atype);
int stun_set_method_and_class(stun_message_t* msg, uint16_t method, uint16_t cls);
int stun_parse(stun_message_t* msg, uint8_t* buf, uint32_t len);
int stun_serialize(stun_message_t* msg, uint8_t* buf, uint32_t* len);
int stun_calculate_crc32(stun_message_t* msg);
int stun_calculate_integrity(stun_message_t* msg, uint8_t* key, uint32_t keylen);
#endif /*STUN_H_INCLUDED*/
/********************************** END **********************************************/
<file_sep>/README.md
A webrtc relay server
<file_sep>/uv.cpp
/*
**************************************************************************************
* Filename: uv.c
* Description: source file
*
* Version: 1.0
* Created: 2018-02-24 10:43:19
*
* Revision: initial draft;
**************************************************************************************
*/
#define LOG_TAG "uv"
#include <errno.h>
#include <string.h>
#include <uv.h>
#include "log.h"
const char* srvip = "127.0.0.1";
uint16_t srvport = 8888;
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t* buf) {
if(!handle || !suggested_size) loge("invali parameter");
static char data[1024];
buf->base = data;
buf->len = sizeof(data);
}
void on_recv(uv_udp_t *req, ssize_t nread, const uv_buf_t* buf, const struct sockaddr *addr, unsigned flags) {
if(!req || nread == -1 || !addr) return;
char ip[32];
const struct sockaddr_in* addrin = (const sockaddr_in*)addr;
uv_ip4_name(addrin, ip, sizeof(ip));
logd("%s:%d->%s", ip, ntohs(addrin->sin_port), buf->base);
}
int run_srv() {
uv_loop_t *loop = uv_default_loop();
uv_udp_t srv;
struct sockaddr_in localaddr;
uv_ip4_addr(srvip, srvport, &localaddr);
uv_udp_init(loop, &srv);
uv_udp_bind(&srv, (struct sockaddr*)&localaddr, 0);
uv_udp_recv_start(&srv, alloc_buffer, on_recv);
return uv_run(loop, UV_RUN_DEFAULT);
}
int run_cli() {
uv_loop_t *loop = uv_default_loop();
uv_udp_t cli;
uv_udp_send_t req;
uv_buf_t buf;
char hello[] = "hello,world";
buf.base = hello;
buf.len = sizeof(hello);
struct sockaddr_in localaddr;
struct sockaddr_in remoteaddr;
uv_ip4_addr("0.0.0.0", 4000, &localaddr);
uv_ip4_addr(srvip, srvport, &remoteaddr);
uv_udp_init(loop, &cli);
uv_udp_bind(&cli, (struct sockaddr*)&localaddr, 0);
uv_udp_send(&req, &cli, &buf, 1, (const struct sockaddr*)&remoteaddr, NULL);
return uv_run(loop, UV_RUN_DEFAULT);
}
int main(int argc, char *argv[])
{
if(argc != 2) {
loge("usage: %s <c|s>", argv[0]);
return -EINVAL;
}
if(strcmp(argv[1], "c") == 0)
return run_cli();
else if(strcmp(argv[1], "s") == 0)
return run_srv();
loge("usage: %s <c|s>", argv[0]);
return -EINVAL;
}
/********************************** END **********************************************/
<file_sep>/dtls.cpp
/*
**************************************************************************************
* Filename: dtls.c
* Description: source file
*
* Version: 1.0
* Created: 2018-02-09 17:06:35
*
* Revision: initial draft;
**************************************************************************************
*/
#define LOG_TAG "dtls"
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <srtp2/srtp.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include "log.h"
uint16_t srv_port = 8881;
uint16_t cli_port = 8882;
const char* srv_ip = "127.0.0.1";
const char* cafile = "cacert.pem";
const char* pkfile = "cakey.pem";
static SSL_CTX *ssl_ctx = NULL;
static X509* ssl_cert = NULL;
static EVP_PKEY* ssl_key = NULL;
static DH* ssl_dh = NULL;
static SSL* ssl = NULL;
int udp_new_server() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = bind(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to bind addr: %s %d [%s]", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server is running on: %s:%d fd:%d", srv_ip, srv_port, fd);
return fd;
}
int udp_new_client() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = connect(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to connect server: %s, %d <%s>", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server connected");
return fd;
}
int sec_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
logd("preverify: %d ctx:%p", preverify_ok, ctx);
return 1;
}
int sec_cert_verify_callback(X509_STORE_CTX* store, void* arg) {
if(!store || !arg) {
return 1;
}
return 1;
}
void sec_info_callback(const SSL* ssl, int where, int ret) {
if(!ssl || !ret) {}
if(where & SSL_CB_LOOP) logd("SSL_CB_LOOP");
if(where & SSL_CB_EXIT) logd("SSL_CB_EXIT");
if(where & SSL_CB_READ) logd("SSL_CB_READ");
if(where & SSL_CB_WRITE) logd("SSL_CB_WRITE");
if(where & SSL_CB_ALERT) logd("SSL_CB_ALERT");
if(where & SSL_CB_HANDSHAKE_START) logd("SSL_CB_HANDSHAKE_START");
if(where & SSL_CB_HANDSHAKE_DONE) logd("SSL_CB_HANDSHAKE_DONE");
}
int sec_load_key() {
FILE* fp = fopen(cafile, "r");
if(!fp) {
loge("fail to open ca file: %s", cafile);
return -1;
}
ssl_cert = PEM_read_X509(fp, NULL, NULL, NULL);
if(!ssl_cert) {
loge("fail to read ca file: %s", cafile);
goto error;
}
fclose(fp);
fp = fopen(pkfile, "r");
if(!fp) {
loge("fail to open private key: %s", pkfile);
goto error;
}
ssl_key = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
if(!ssl_key) {
loge("fail to read private key: %s", pkfile);
goto error;
}
fclose(fp);
return 0;
error:
if(fp) fclose(fp);
if(ssl_cert) X509_free(ssl_cert);
if(ssl_key) EVP_PKEY_free(ssl_key);
if(ssl_dh) DH_free(ssl_dh);
ssl_cert = NULL;
ssl_key = NULL;
return -1;
}
int sec_env_init(int isserver) {
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
if(isserver) {
ssl_ctx = SSL_CTX_new(DTLS_server_method());
} else {
ssl_ctx = SSL_CTX_new(DTLS_client_method());
}
if(!ssl_ctx) {
loge("fail to create SSL_CTX");
return -1;
}
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, sec_verify_callback);
if(0 != sec_load_key()) return -1;
if(!SSL_CTX_use_certificate(ssl_ctx, ssl_cert)) {
loge("fail to use certificate");
return -1;
}
if(!SSL_CTX_use_PrivateKey(ssl_ctx, ssl_key)) {
loge("fail to use priv key");
return -1;
}
if(!SSL_CTX_check_private_key(ssl_ctx)) {
loge("fail to check priv key");
return -1;
}
SSL_CTX_set_read_ahead(ssl_ctx, 1);
SSL_CTX_set_cipher_list(ssl_ctx, "ALL:NULL:eNULL:aNULL");
SSL_CTX_set_tlsext_use_srtp(ssl_ctx, "SRTP_AES128_CM_SHA1_80");
if(0 != srtp_init()) {
loge("srtp init failed");
}
logi("secure env setup ok.");
return 0;
}
void sec_env_uninit() {
return;
}
int run_srv() {
logfunc();
int ret = 0;
struct sockaddr_in addr;
char buf[4096];
size_t cnt = 0;
BIO* bio = NULL;
EC_KEY* ecdh = NULL;
if(0 != sec_env_init(1)) {
return -1;
}
int fd = udp_new_server();
if(fd < 0) return -1;
ssl = SSL_new(ssl_ctx);
if(!ssl) {
loge("fail to new ssl");
goto exit;
}
SSL_set_ex_data(ssl, 0, NULL);
SSL_set_info_callback(ssl, sec_info_callback);
bio = BIO_new_dgram(fd, BIO_NOCLOSE);
SSL_set_bio(ssl, bio, bio);
SSL_set_accept_state(ssl);
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if(!ecdh) {
log("fail to create ECKEY");
goto exit;
}
SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
SSL_set_tmp_ecdh(ssl, ecdh);
EC_KEY_free(ecdh);
SSL_set_read_ahead(ssl, 1);
logd("waiting for handshake %p ...", ssl->handshake_func);
bzero(&addr, sizeof(addr));
ret = SSL_accept(ssl);
if(ret != 1) {
loge("fail to accept: %d %s", ret, ERR_error_string(SSL_get_error(ssl, ret), NULL));
goto exit;
}
logd("handshake ok.");
while(1) {
bzero(buf, sizeof(buf));
cnt = SSL_read(ssl, buf, sizeof(buf)-1);
if(cnt == (size_t)-1 ) {
loge("fail to recv data: %s", strerror(errno));
break;
}
logd("msg: %s", buf);
}
exit:
if(ssl) {
SSL_shutdown(ssl);
SSL_free(ssl);
}
close(fd);
logw("server exit.");
return 0;
}
int run_client() {
logfunc();
int ret = 0;
char buf[4096];
BIO* ioread = NULL;
BIO* iowrite = NULL;
ioread = BIO_new(BIO_s_mem());
iowrite = BIO_new(BIO_s_mem());
if(!ioread || !iowrite) {
loge("fail to allocate io mem");
return -1;
}
BIO_set_mem_eof_return(ioread, -1);
BIO_set_mem_eof_return(iowrite, -1);
if(0 != sec_env_init(0)) {
return -1;
}
int fd = udp_new_client();
size_t cnt = 0;
EC_KEY* ecdh = NULL;
if(fd < 0) return -1;
ssl = SSL_new(ssl_ctx);
if(!ssl) {
loge("fail to new ssl");
goto exit;
}
SSL_set_ex_data(ssl, 0, NULL);
SSL_set_info_callback(ssl, sec_info_callback);
SSL_set_bio(ssl, ioread, iowrite);
SSL_set_read_ahead(ssl, 1);
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if(!ecdh) {
log("fail to create ECKEY");
goto exit;
}
SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
SSL_set_tmp_ecdh(ssl, ecdh);
EC_KEY_free(ecdh);
logd("starting handshake...");
SSL_set_connect_state(ssl);
do {
ret = SSL_do_handshake(ssl);
logd("do handshake: %d", ret);
int err = SSL_get_error(ssl, ret);
if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
ret = 0;
}
while(BIO_ctrl_pending(iowrite) > 0) {
int cnt = BIO_read(iowrite, buf, sizeof(buf));
if(cnt > 0) {
send(fd, buf, cnt, 0);
}
}
if(err == SSL_ERROR_WANT_READ) {
int cnt = recv(fd, buf, sizeof(buf), 0);
if(cnt > 0) {
BIO_write(ioread, buf, cnt);
}
}
}while(ret == 0);
logd("handshake DONE. with %d", ret);
//send message to server
snprintf(buf, sizeof(buf), "hello, world");
logd("send: %s", buf);
cnt = SSL_write(ssl, buf, strlen(buf));
if(cnt == (size_t)-1) loge("fail to send: %s", strerror(errno));
close(fd);
exit:
return 0;
}
int usage(const char* prog) {
log("usage: %s <c|s>\n", prog);
return -1;
}
int main(int argc, const char *argv[]) {
if(argc == 2) {
if(strcmp(argv[1], "s") == 0) return run_srv();
if(strcmp(argv[1], "c") == 0) return run_client();
}
return usage(argv[0]);
}
/********************************** END **********************************************/
<file_sep>/stunsrv.cpp
/*
**************************************************************************************
* Filename: stunsrv.c
* Description: source file
*
* Version: 1.0
* Created: 2018-02-12 15:06:54
*
* Revision: initial draft;
**************************************************************************************
*/
#define LOG_TAG "stun"
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <srtp2/srtp.h>
#include "log.h"
#include "stun.h"
#define MASTER_KEY 16
#define MASTER_SALT 14
#define MASTER_LEN (MASTER_KEY+MASTER_SALT)
uint16_t srv_port = 8881;
uint16_t cli_port = 8882;
const char* srv_ip = "127.0.0.1";
int udp_new_server() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = bind(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to bind addr: %s %d [%s]", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server is running on: %s:%d fd:%d", srv_ip, srv_port, fd);
return fd;
}
int udp_new_client() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = connect(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to connect server: %s, %d <%s>", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server connected");
return fd;
}
int run_srv() {
logfunc();
int fd = udp_new_server();
int ret = 0;
size_t len = 0;
char buf[4096];
if(fd < 0) return -1;
stun_message_t* msg = stun_alloc_message();
while(1) {
bzero(buf, sizeof(buf));
ret = recv(fd, buf, len, 0);
if(ret < 0) {
loge("fail to recv data: %s", strerror(errno));
break;
}
//handle data
stun_parse(msg, (uint8_t*)buf, ret);
logd("get msg: %08x", msg->header->cookie);
}
close(fd);
return 0;
}
int run_client() {
logfunc();
int fd = udp_new_client();
int ret = 0;
char buf[4096];
uint32_t len = sizeof(buf);
if(fd < 0) return -1;
stun_message_t* req = stun_alloc_message();
if(!req) goto exit;
stun_attr_xor_mapped_address_ipv4 addr;
struct in_addr inaddr;
addr.family = 0x01;
addr.port = 8080;
addr.header.type = XOR_MAPPED_ADDRESS;
addr.header.len = sizeof(addr) - sizeof(addr.header);
inet_pton(AF_INET, "192.168.1.1", &inaddr);
addr.addr = inaddr.s_addr;
stun_serialize(req, (uint8_t*)buf, &len);
ret = send(fd, buf, len, 0);
if(ret < 0) {
loge("fail to send data.");
} else {
logd("send: %d", len);
}
exit:
if(fd) close(fd);
if(req) stun_free_message(req);
return 0;
}
int usage(const char* prog) {
log("usage: %s <c|s>\n", prog);
return -1;
}
int main(int argc, const char *argv[]) {
if(argc == 2) {
if(strcmp(argv[1], "s") == 0) return run_srv();
if(strcmp(argv[1], "c") == 0) return run_client();
}
return usage(argv[0]);
}
/********************************** END **********************************************/
<file_sep>/stun.cpp
/*
**************************************************************************************
* Filename: stun.c
* Description: source file
*
* Version: 1.0
* Created: 2018-02-11 21:49:20
*
* Revision: initial draft;
**************************************************************************************
*/
#define LOG_TAG "stun"
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <zlib.h>
#include "stun.h"
#include "log.h"
#define DEFAULT_SIZE 1024
#define STUN_BLK_SIZE 64
#define STUN_CRC32_FACTOR 0x5354554e
static uint64_t stun_ntohll(uint64_t n) {
if (__BYTE_ORDER == __LITTLE_ENDIAN) {
uint64_t h = ntohl(n>>32) | ((uint64_t)ntohl(n&0xFFFFFFFF) << 32);
return h;
} else {
return n;
}
}
static uint64_t stun_htonll(uint64_t h) {
if (__BYTE_ORDER == __LITTLE_ENDIAN) {
uint64_t n = htonl(h>>32) | ((uint64_t)htonl(h&0xFFFFFFFF) << 32);
return n;
} else {
return h;
}
}
static void hexdump(uint8_t* ptr, uint32_t cnt) {
if(!ptr || !cnt) return;
for(uint32_t i=0; i<cnt; i++, ptr++) {
if(i % 16 == 0) {
if(i != 0) log("\n");
log("%08x ", i);
}
if(i % 8 == 0 && i % 16 != 0)
log(" %02x ", *ptr);
else
log("%02x ", *ptr);
}
log("\n");
}
stun_message_t* stun_alloc_message() {
stun_message_t* msg = (stun_message_t*)malloc(sizeof(stun_message_t));
if(msg) {
memset(msg, 0x00, sizeof(*msg));
msg->buf = (uint8_t*)malloc(DEFAULT_SIZE);
if(!msg->buf) {
free(msg);
msg = NULL;
}
memset(msg->buf, 0x00, DEFAULT_SIZE);
stun_header* header = (stun_header*)msg->buf;
header->cookie = STUN_COOKIE;
RAND_bytes(header->trans_id, sizeof(header->trans_id));
header->len = 0;
msg->header = header;
msg->used = sizeof(stun_header);
msg->len = DEFAULT_SIZE;
}
return msg;
}
void stun_free_message(stun_message_t* msg) {
if(msg) {
if(msg->buf) free(msg->buf);
free(msg);
}
}
int stun_add_attr(stun_message_t* msg, stun_attr_header* attr) {
if(!msg || !attr || !msg->buf) {
return -EINVAL;
}
uint16_t copylen = STUN_ALIGNED(attr->len) + sizeof(stun_attr_header);
if(msg->len - msg->used < copylen) {
logd("%s: resize mem", __func__);
/* NO enough buffer avaliable, then realloc the buffer */
uint8_t* buf = (uint8_t*)malloc(msg->len*2);
if(!buf) {
return -ENOMEM;
}
memcpy(buf, msg->buf, msg->used);
free(msg->buf);
msg->buf = buf;
msg->len = msg->len * 2;
}
memcpy(msg->buf + msg->used, attr, copylen);
msg->used += copylen;
msg->header->len += copylen;
return 0;
}
stun_attr_header* stun_get_attr(stun_message_t* msg, uint16_t atype) {
if(!msg) return NULL;
uint8_t* ptr = msg->buf + sizeof(stun_header);
uint16_t reallen = 0;
while(ptr < msg->buf + msg->used) {
stun_attr_header* attr = (stun_attr_header*)ptr;
reallen = STUN_ALIGNED(attr->len);
if(attr->type == atype) return attr;
ptr = ptr + reallen + sizeof(stun_attr_header);
}
return NULL;
}
int stun_set_method_and_class(stun_message_t* msg, uint16_t method, uint16_t cls) {
if(!msg || method != STUN_METHOD_BINDING) return -EINVAL;
msg->header->type = (method | cls);
logd("type: %x %x", msg->header->type, (method | cls));
return 0;
}
int stun_parse(stun_message_t* msg, uint8_t* buf, uint32_t len) {
if(!msg || !buf || !len || len%4!=0) return -EINVAL;
if(len > msg->len) {
logd("parse resize");
uint8_t* ptr = (uint8_t*)malloc(len);
if(!ptr) {
return -ENOMEM;
}
free(msg->buf);
msg->buf = ptr;
}
memcpy(msg->buf, buf, len);
msg->len = msg->used = len;
msg->header = (stun_header*)msg->buf;
/* check header */
stun_header* header = msg->header;
uint16_t reallen = 0;
header->cookie = ntohl(header->cookie);
if(header->cookie != STUN_COOKIE) {
return -EBADMSG;
}
header->type = ntohs(header->type);
header->len = ntohs(header->len);
uint8_t* ptr = msg->buf + sizeof(stun_header);
stun_attr_header* attr = NULL;
while(ptr < msg->buf+msg->len) {
attr = (stun_attr_header*)ptr;
attr->type = ntohs(attr->type);
attr->len = ntohs(attr->len);
reallen = STUN_ALIGNED(attr->len);
switch(attr->type) {
case USERNAME: {
/*logd("USERNAME");*/
break;
};
case WRTC_UNKNOWN: {
/*logd("WRTC_UNKNOWN");*/
stun_attr_unknown* a = (stun_attr_unknown*)attr;
for(uint16_t i=0; i<(attr->len/2); i++) {
a->attrs[i] = ntohs(a->attrs[i]);
}
break;
};
case XOR_MAPPED_ADDRESS: {
/*logd("XOR_MAPPED_ADDRESS");*/
stun_attr_xor_mapped_address_ipv4* a = (stun_attr_xor_mapped_address_ipv4*)attr;
a->port = ntohs(a->port);
if(a->family == 0x01) {
a->addr = ntohl(a->addr);
}
break;
};
case ICE_CONTROLLING: {
/*logd("ICE_CONTROLLING");*/
stun_attr_ice_controlling* a = (stun_attr_ice_controlling*)attr;
a->tiebreaker = stun_ntohll(a->tiebreaker);
break;
};
case USE_CANDIDATE: {
/*logd("USE_CANDIDATE");*/
break;
};
case PRIORITY: {
/*logd("PRIORITY");*/
stun_attr_priority* a = (stun_attr_priority*)attr;
a->priority = ntohl(a->priority);
break;
};
case MESSAGE_INTEGRITY: {
/*logd("MESSAGE_INTEGRITY");*/
break;
};
case FINGERPRINT: {
/*logd("FINGERPRINT");*/
stun_attr_fingerprint* a = (stun_attr_fingerprint*)attr;
a->crc32 = ntohl(a->crc32);
break;
};
default: {
loge("parse: invalid type: 0x%02x %u", attr->type, len);
hexdump(msg->buf, msg->used);
return -EBADMSG;
}
}
ptr = ptr + reallen + sizeof(stun_attr_header);
}
return 0;
}
int stun_serialize(stun_message_t* msg, uint8_t* buf, uint32_t* len) {
if(!msg || !len || *len == 0) return -EINVAL;
if(!buf) {
*len = msg->used;
return 0;
}
if(*len < msg->used) {
logd("serialize: not enough memory");
return -ENOMEM;
}
*len = 0;
memcpy(buf, msg->buf, msg->used);
stun_header* header = (stun_header*)buf;
header->type = htons(header->type);
header->len = htons(header->len);
header->cookie = htonl(header->cookie);
uint8_t* ptr = buf + sizeof(stun_header);
stun_attr_header* attr = NULL;
uint16_t reallen = 0;
uint16_t attrlen = 0;
uint16_t type = 0;
while(ptr < buf + msg->used) {
attr = (stun_attr_header*)ptr;
type = attr->type;
reallen = STUN_ALIGNED(attr->len);
attrlen = attr->len;
attr->type = htons(attr->type);
attr->len = htons(attr->len);
switch(type) {
case USERNAME: {
/*logd("serialize: USERNAME");*/
break;
};
case WRTC_UNKNOWN: {
/*logd("serialize: WRTC_UNKNOWN");*/
stun_attr_unknown* a = (stun_attr_unknown*)attr;
for(uint16_t i=0; i<(attrlen/2); i++) {
a->attrs[i] = htons(a->attrs[i]);
}
break;
};
case XOR_MAPPED_ADDRESS: {
/*logd("serialize: XOR_MAPPED_ADDRESS");*/
stun_attr_xor_mapped_address_ipv4* a = (stun_attr_xor_mapped_address_ipv4*)attr;
a->port = htons(a->port ^ (STUN_COOKIE >> 16));
a->addr = htonl(a->addr ^ htonl(STUN_COOKIE));
if(a->family == 0x01) {
a->addr = htonl(a->addr);
}
break;
};
case ICE_CONTROLLED:
case ICE_CONTROLLING: {
/*logd("serialize: ICE_CONTROLLING");*/
stun_attr_ice_controlling* a = (stun_attr_ice_controlling*)attr;
a->tiebreaker = stun_htonll(a->tiebreaker);
break;
};
case USE_CANDIDATE: {
/*logd("serialize: USE_CANDIDATE");*/
break;
};
case PRIORITY: {
/*logd("serialize: PRIORITY");*/
stun_attr_priority* a = (stun_attr_priority*)attr;
a->priority = htonl(a->priority);
break;
};
case MESSAGE_INTEGRITY: {
/*logd("serialize: MESSAGE_INTEGRITY");*/
break;
};
case FINGERPRINT: {
/*logd("serialize: FINGERPRINT");*/
stun_attr_fingerprint* a = (stun_attr_fingerprint*)attr;
a->crc32 = htonl(a->crc32);
break;
};
default: {
loge("serialize: invalid type: 0x%02x @%p %d %d", attr->type, attr, msg->len, msg->used);
hexdump(msg->buf, msg->used);
return -EBADMSG;
}
}
ptr = ptr + sizeof(stun_attr_header) + reallen;
}
*len = msg->used;
return 0;
}
int stun_get_buf(stun_message_t* msg, uint16_t type, uint8_t* out, uint32_t* len) {
stun_attr_header* attr = stun_get_attr(msg, type);
if(!attr) {
return -EINVAL;
}
uint8_t buf[4096];
uint32_t buflen = sizeof(buf);
int ret = stun_serialize(msg, buf, &buflen);
if(ret != 0) return ret;
stun_header* header = (stun_header*)buf;
uint32_t size = (uint8_t*)attr - msg->buf;
header->len = htons(size - sizeof(stun_header) + sizeof(stun_attr_header) + STUN_ALIGNED(attr->len));
memcpy(out, buf, size);
*len = size;
}
int stun_calculate_crc32(stun_message_t* msg) {
stun_attr_fingerprint* attr = (stun_attr_fingerprint*)stun_get_attr(msg, FINGERPRINT);
if(!attr) return -EINVAL;
uint8_t buf[1024];
uint32_t len = sizeof(buf);
stun_get_buf(msg, FINGERPRINT, buf, &len);
attr->crc32 = crc32(0, buf, len) ^ STUN_CRC32_FACTOR;
return 0;
}
int calculate_sha1(uint8_t* in, uint32_t inlen, uint8_t* key, uint32_t keylen, uint8_t* out) {
if(!in ||!inlen || !key || !out || !keylen) return -EINVAL;
logd("calculate_sha1: %u %u", inlen, keylen);
uint8_t ipad[STUN_BLK_SIZE], opad[STUN_BLK_SIZE], newkey[STUN_BLK_SIZE];
uint8_t sha1[20];
memset(ipad, 0x00, sizeof(ipad));
memset(opad, 0x00, sizeof(opad));
memset(newkey, 0x00, sizeof(newkey));
memcpy(newkey, key, keylen);
memset(sha1, 0x00, sizeof(sha1));
for(int i=0; i<STUN_BLK_SIZE; i++) {
opad[i] = 0x5c ^ newkey[i];
ipad[i] = 0x36 ^ newkey[i];
}
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, ipad, sizeof(ipad));
SHA1_Update(&ctx, in, inlen);
SHA1_Final(sha1, &ctx);
SHA1_Init(&ctx);
SHA1_Update(&ctx, opad, sizeof(opad));
SHA1_Update(&ctx, sha1, sizeof(sha1));
SHA1_Final(out, &ctx);
return 0;
}
int stun_calculate_integrity(stun_message_t* msg, uint8_t* key, uint32_t keylen) {
if(!msg || !key || !keylen) return -EINVAL;
if(keylen > STUN_BLK_SIZE) {
loge("unimplemented feature.");
return -ENOSYS;
}
// serialize the data first
uint8_t buf[1024];
uint32_t len = sizeof(buf);
stun_attr_message_integrity* attr = (stun_attr_message_integrity*)stun_get_attr(msg, MESSAGE_INTEGRITY);
if(!attr) return -EINVAL;
stun_get_buf(msg, MESSAGE_INTEGRITY, buf, &len);
calculate_sha1(buf, len, key, keylen, attr->sha1);
return 0;
}
#if 0
int main()
{
const char* datafile = "stun.request";
char buf[1024];
char dst[1024];
int fsize = 0;
int ret = 0;
FILE* fp = fopen(datafile, "r");
if(!fp) {
loge("fail to open file: %s", datafile);
return -1;
}
fsize = fread(buf, 1, sizeof(buf), fp);
if(fsize < 0) {
loge("fail to read data:%s", strerror(errno));
fclose(fp);
return -1;
}
fclose(fp);
stun_message_t* msg = stun_alloc_message();
ret = stun_parse(msg, (uint8_t*)buf, fsize);
logd("parse ret: %d", ret);
uint32_t len = sizeof(dst);
ret = stun_serialize(msg, (uint8_t*)dst, &len);
logd("serialize ret: %d", ret);
if((uint32_t)fsize != len) {
loge("incorrect length: %u!=%u", fsize, len);
} else if(memcmp(buf, dst, len) != 0) {
loge("buf != dst");
hexdump((uint8_t*)buf, len);
hexdump((uint8_t*)dst, len);
}
uint8_t fpbuf[1024];
uint8_t integritybuf[1024];
uint32_t outlen = sizeof(fpbuf);
stun_attr_header* attr = NULL;
attr = stun_get_attr(msg, FINGERPRINT);
if(attr) {
stun_attr_fingerprint* fp = (stun_attr_fingerprint*)attr;
logd("fp=%08x", fp->crc32);
}
stun_get_buf(msg, FINGERPRINT, fpbuf, &outlen);
logd("outlen=%u", outlen);
uint32_t rst = crc32(0, fpbuf, outlen) ^ STUN_CRC32_FACTOR;
logd("calculated fp=%08x", rst);
stun_get_buf(msg, MESSAGE_INTEGRITY, integritybuf, &outlen);
attr = stun_get_attr(msg, MESSAGE_INTEGRITY);
if(attr) {
stun_attr_message_integrity* integrity = (stun_attr_message_integrity*)attr;
hexdump(integrity->sha1, 20);
}
uint8_t sha1[20];
memset(sha1, 0x00, sizeof(sha1));
//uint8_t key[] = "<KEY>";
uint8_t key[] = "<KEY>";
ret = calculate_sha1(integritybuf, outlen, key, sizeof(key)-1, sha1);
if(ret != 0) {
loge("fail to calculate sha1: %d", ret);
} else {
hexdump(sha1, 20);
}
return 0;
}
#endif
/********************************** END **********************************************/
<file_sep>/main.cpp
/*
**************************************************************************************
* Filename: main.c
* Description: source file
*
* Version: 1.0
* Created: 2017-09-14 21:51:55
*
* Revision: initial draft;
**************************************************************************************
*/
#define LOG_TAG "relayserver"
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <srtp2/srtp.h>
#include <string>
using namespace std;
#include "log.h"
#include "stun.h"
#include "rtp.h"
#include "bio.h"
#define MASTER_KEY 16
#define MASTER_SALT 14
#define MASTER_LEN (MASTER_KEY+MASTER_SALT)
const char* cafile = "cacert.pem";
const char* pkfile = "cakey.pem";
in_addr_t firstaddr = 0;
static SSL_CTX *ssl_ctx = NULL;
static X509* ssl_cert = NULL;
static EVP_PKEY* ssl_key = NULL;
static DH* ssl_dh = NULL;
static SSL* ssl = NULL;
static srtp_policy_t policy_remote;
static srtp_policy_t policy_local;
static srtp_t stream_in;
static srtp_t stream_out;
static unsigned char rtp_buf[4096];
static unsigned char srtp_buf[4096];
uint16_t srv_port = 8881;
uint16_t cli_port = 8882;
const char* srv_ip = "192.168.1.102";
char password[64];
char username[64];
BIO* ioread = NULL;
BIO* iowrite = NULL;
BIO* iofilter = NULL;
#define STUN_MSG_RECEIVED 0x01
#define HANDSHAKING 0x02
#define HANDSHAKE_SUCC 0x04
#define NORMAL_STATUS (STUN_MSG_RECEIVED|HANDSHAKE_SUCC)
uint32_t status = 0;
class IceCoreCfg {
public:
string localusername;
string localpassword;;
string remoteusername;
string remotepassword;;
};
IceCoreCfg ice;
int udp_new_server() {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) return -1;
struct sockaddr_in addr_srv;
bzero(&addr_srv, sizeof(addr_srv));
addr_srv.sin_family = AF_INET;
addr_srv.sin_port = htons(srv_port);
addr_srv.sin_addr.s_addr = inet_addr(srv_ip);
int ret = bind(fd, (struct sockaddr*)&addr_srv, sizeof(struct sockaddr));
if(ret != 0) {
loge("fail to bind addr: %s %d [%s]", srv_ip, srv_port, strerror(errno));
close(fd);
return -1;
}
logd("server is running on: %s:%d fd:%d", srv_ip, srv_port, fd);
return fd;
}
int sec_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
logd("preverify: %d ctx:%p", preverify_ok, ctx);
return 1;
}
int sec_cert_verify_callback(X509_STORE_CTX* store, void* arg) {
if(!store || !arg) {
return 1;
}
return 1;
}
void sec_info_callback(const SSL* ssl, int where, int ret) {
if(!ssl || !ret) {}
if(where & SSL_CB_LOOP) logd("SSL_CB_LOOP");
if(where & SSL_CB_EXIT) logd("SSL_CB_EXIT");
if(where & SSL_CB_READ) logd("SSL_CB_READ");
if(where & SSL_CB_WRITE) logd("SSL_CB_WRITE");
if(where & SSL_CB_ALERT) logd("SSL_CB_ALERT");
if(where & SSL_CB_HANDSHAKE_START) logd("SSL_CB_HANDSHAKE_START");
if(where & SSL_CB_HANDSHAKE_DONE) logd("SSL_CB_HANDSHAKE_DONE");
}
int sec_load_key() {
FILE* fp = fopen(cafile, "r");
if(!fp) {
loge("fail to open ca file: %s", cafile);
return -1;
}
ssl_cert = PEM_read_X509(fp, NULL, NULL, NULL);
if(!ssl_cert) {
loge("fail to read ca file: %s", cafile);
goto error;
}
fclose(fp);
fp = fopen(pkfile, "r");
if(!fp) {
loge("fail to open private key: %s", pkfile);
goto error;
}
ssl_key = PEM_read_PrivateKey(fp, NULL, NULL, NULL);
if(!ssl_key) {
loge("fail to read private key: %s", pkfile);
goto error;
}
fclose(fp);
return 0;
error:
if(fp) fclose(fp);
if(ssl_cert) X509_free(ssl_cert);
if(ssl_key) EVP_PKEY_free(ssl_key);
if(ssl_dh) DH_free(ssl_dh);
ssl_cert = NULL;
ssl_key = NULL;
return -1;
}
int sec_env_init(int isserver) {
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
if(isserver) {
ssl_ctx = SSL_CTX_new(DTLS_server_method());
} else {
ssl_ctx = SSL_CTX_new(DTLS_client_method());
}
if(!ssl_ctx) {
loge("fail to create SSL_CTX");
return -1;
}
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, sec_verify_callback);
if(0 != sec_load_key()) return -1;
if(!SSL_CTX_use_certificate(ssl_ctx, ssl_cert)) {
loge("fail to use certificate");
return -1;
}
if(!SSL_CTX_use_PrivateKey(ssl_ctx, ssl_key)) {
loge("fail to use priv key");
return -1;
}
if(!SSL_CTX_check_private_key(ssl_ctx)) {
loge("fail to check priv key");
return -1;
}
SSL_CTX_set_read_ahead(ssl_ctx, 1);
SSL_CTX_set_cipher_list(ssl_ctx, "ALL:NULL:eNULL:aNULL");
SSL_CTX_set_tlsext_use_srtp(ssl_ctx, "SRTP_AES128_CM_SHA1_80");
if(0 != srtp_init()) {
loge("fail to init srtp");
}
logi("secure env setup ok.");
return 0;
}
int is_stun(char* buf, int32_t len) {
if(!buf || !len) return -EINVAL;
stun_header* header = (stun_header*)buf;
if(header->cookie == ntohl(STUN_COOKIE)) return 1;
return 0;
}
int is_rtp(char* buf, int32_t len) {
if(!buf || !len) return -EINVAL;
rtp_header* header = (rtp_header*)buf;
if(header->type < 64 || header->type >= 96) return 1;
return 0;
}
int is_rtcp(char* buf, int32_t len) {
if(!buf || !len) return -EINVAL;
rtp_header* header = (rtp_header*)buf;
if(header->type >= 64 || header->type < 96) return 1;
return 0;
}
int is_dtls(char* buf, int32_t len) {
if(!buf || !len) return -EINVAL;
return (*buf >= 20 && *buf <= 64);
}
int is_password(char* buf, int32_t len) {
if(!buf || !len) return -EINVAL;
uint32_t* magic = (uint32_t*)buf;
if(*magic == 0xabcdabcd) {
return 1;
} else {
return 0;
}
}
int do_init_srtp(uint8_t* material) {
srtp_err_status_t res;
bzero(&policy_remote, sizeof(policy_remote));
srtp_crypto_policy_set_rtp_default(&policy_remote.rtp);
srtp_crypto_policy_set_rtcp_default(&policy_remote.rtcp);
policy_remote.ssrc.type = ssrc_any_inbound;
unsigned char remote_policy_key[MASTER_LEN];
policy_remote.key = (unsigned char*)&remote_policy_key;
policy_remote.window_size = 128;
policy_remote.allow_repeat_tx = 0;
memcpy(policy_remote.key, material+MASTER_KEY, MASTER_KEY);
memcpy(policy_remote.key+MASTER_KEY, material+MASTER_KEY*2+MASTER_SALT, MASTER_SALT);
res = srtp_create(&stream_in, &policy_remote);
if(res != srtp_err_status_ok) {
loge("fail to create srtp stream_in: %d", res);
return -1;
}
unsigned char master_key[MASTER_LEN];
bzero(&policy_local, sizeof(policy_local));
srtp_crypto_policy_set_rtp_default(&policy_local.rtp);
srtp_crypto_policy_set_rtcp_default(&policy_local.rtcp);
policy_local.ssrc.type = ssrc_any_inbound;
policy_local.key = master_key;
policy_local.window_size = 128;
policy_local.allow_repeat_tx = 0;
memcpy(policy_local.key, material, MASTER_KEY);
memcpy(policy_local.key+MASTER_KEY, material+MASTER_KEY*2, MASTER_SALT);
res = srtp_create(&stream_out, &policy_local);
if(res != srtp_err_status_ok) {
loge("fail to create srtp stream_out: %d", res);
return -1;
}
logi("init srtp OK");
return 0;
}
void handle_password(uint8_t* buf, int32_t len, int fd, struct sockaddr* addr, socklen_t socklen) {
logfunc();
if(!buf || !len || fd < 0 || !addr || !socklen) return;
char* ptr = (char*)(buf + sizeof(uint32_t));
ice.localusername = ptr;
ptr += 64;
ice.localpassword = ptr;
ptr += 64;
ice.remoteusername = ptr;
ptr += 64;
ice.remotepassword = ptr;
logd("ice: [%s][%s][%s][%s]", ice.localusername.c_str(), \
ice.localpassword.c_str(),
ice.remoteusername.c_str(),
ice.remotepassword.c_str());
string lu = ice.localusername;
string ru = ice.remoteusername;
ice.localusername = ru + ":" + ice.localusername;
ice.remoteusername = lu + ":" + ice.remoteusername;
}
void handle_dtls(uint8_t* buf, int32_t len, int fd, struct sockaddr* addr, socklen_t socklen) {
logfunc();
if(!buf || !len || fd < 0 || !addr || !socklen) return;
//if(status & HANDSHAKE_SUCC) return;
//if(!(status & HANDSHAKING)) return;
logd("handle dtls data size: %d", len);
if(ioread) {
BIO_write(ioread, buf, len);
int ret = SSL_do_handshake(ssl);
if(ret == 1) {
status = status & (~HANDSHAKING);
status |= HANDSHAKE_SUCC;
unsigned char material[MASTER_LEN*2];
bzero(material, sizeof(material));
if(!SSL_export_keying_material(ssl, material, sizeof(material), "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
loge("fail to export key");
} else {
log("MASTER KEY:");
log("\n---------------------\n");
for(ret=0; ret<(int)sizeof(material); ret++) {
if(ret > 0 && ret % 8 == 0) log("\n");
log("%02x ", material[ret]);
}
log("\n---------------------\n");
}
do_init_srtp(material);
}
}
if(iofilter) {
char buf[4096];
int pending = 0;
while((pending = BIO_ctrl_pending(iofilter)) > 0) {
int ret = BIO_read(iowrite, buf, pending);
logd("pending dtls data: %d ret=%d bio: %p wio=%p", pending, ret, iowrite, iofilter);
if(ret > 0) {
logd("dtls: send handshake data: %d", ret);
sendto(fd, buf, ret, 0, addr, socklen);
}
}
}
return;
}
void send_stun_requst(int fd, struct sockaddr* addr, socklen_t socklen) {
static int sended = 0;
if(sended) return;
sended = 1;
if(fd < 0 || !addr || !socklen) return;
stun_message_t* req = stun_alloc_message();
stun_set_method_and_class(req, STUN_METHOD_BINDING, STUN_REQUEST);
int ulen = STUN_ALIGNED(ice.localusername.size());
stun_attr_username* username = (stun_attr_username*)malloc(sizeof(stun_attr_username) + ulen);
username->header.type = USERNAME;
username->header.len = ice.localusername.size();
memset(username->username, 0x00, ulen);
strcpy(username->username, ice.localusername.c_str());
stun_add_attr(req, &username->header);
free(username);
stun_attr_ice_controlling ice_controlled;
ice_controlled.header.type = ICE_CONTROLLED;
ice_controlled.header.len = 8;
ice_controlled.tiebreaker = 0x1d23f31232ecdde4;
stun_add_attr(req, &ice_controlled.header);
stun_attr_priority priority;
priority.header.type = PRIORITY;
priority.header.len = 4;
priority.priority = 5;
stun_add_attr(req, &priority.header);
stun_attr_message_integrity integrity;
integrity.header.type = MESSAGE_INTEGRITY;
integrity.header.len = 20;
stun_add_attr(req, &integrity.header);
stun_calculate_integrity(req, (uint8_t*)ice.remotepassword.c_str(), ice.remotepassword.size());
stun_attr_fingerprint fringerprint;
fringerprint.header.type = FINGERPRINT;
fringerprint.header.len = 4;
stun_add_attr(req, &fringerprint.header);
stun_calculate_crc32(req);
uint8_t buf[4096];
uint32_t len = sizeof(buf);
stun_serialize(req, buf, &len);
sendto(fd, buf, len, 0, addr, socklen);
}
void send_stun_indication(int fd, struct sockaddr* addr, socklen_t socklen) {
logfunc();
if(fd < 0 || !addr || !socklen) return;
stun_message_t* ind = stun_alloc_message();
if(!ind) {
loge("fail to alloc ind");
return;
}
//indication message to client
stun_attr_fingerprint fp;
stun_set_method_and_class(ind, STUN_METHOD_BINDING, STUN_INDICATION);
fp.header.type = FINGERPRINT;
fp.header.len = 4;
fp.crc32 = stun_calculate_crc32(ind);
stun_add_attr(ind, &fp.header);
uint32_t size = 0;
uint8_t content[4096];
int ret = 0;
size = sizeof(content);
ret = stun_serialize(ind, content, &size);
if(ret < 0) {
loge("fail to serialize indication message: %d", ret);
} else {
sendto(fd, content, size, 0, addr, socklen);
}
stun_free_message(ind);
ind = NULL;
}
void send_dtls_clienthello(int fd, struct sockaddr* addr, socklen_t socklen) {
logfunc();
if(fd < 0 || !addr || !socklen) return;
logd("starting handshaking...");
BIO* bio = iofilter;
int ret = SSL_do_handshake(ssl);
if(ret < 0) {
loge("HANDSHAKE: %s", ERR_error_string(SSL_get_error(ssl, ret), NULL));
} else {
logd("HANDSHAKING: %d %s", ret, ERR_error_string(SSL_get_error(ssl, ret), NULL));
}
if(bio) {
logd("get wio");
char buf[4096];
int pending = 0;
while((pending = BIO_ctrl_pending(bio)) > 0) {
int ret = BIO_read(iowrite, buf, pending);
if(ret > 0) {
logd("send handshake data: %d", ret);
sendto(fd, buf, ret, 0, addr, socklen);
}
}
status |= HANDSHAKING;
} else {
loge("NO wio avaliable..");
}
}
void handle_stun(uint8_t* buf, int32_t len, int fd, struct sockaddr* addr, socklen_t socklen) {
logfunc();
status |= STUN_MSG_RECEIVED;
stun_message_t* req = stun_alloc_message();
stun_message_t* resp = stun_alloc_message();
if(!req || !resp) {
loge("fail to allocate message: %p %p", req, resp);
return;
}
stun_parse(req, buf, len);
if(req->header->type == (STUN_SUCC_RESPONSE | STUN_METHOD_BINDING)) {
stun_free_message(req);
stun_free_message(resp);
logd("get bind response.");
send_stun_indication(fd, addr, socklen);
send_dtls_clienthello(fd, addr, socklen);
return;
}
stun_set_method_and_class(resp, STUN_METHOD_BINDING, STUN_SUCC_RESPONSE);
memcpy(resp->header->trans_id, req->header->trans_id, sizeof(resp->header->trans_id));
stun_attr_header* usrname = NULL;
usrname = stun_get_attr(req, USERNAME);
if(!usrname) {
loge("fail to get username in request");
} else {
stun_add_attr(resp, usrname);
}
struct sockaddr_in* addrin = (struct sockaddr_in*)addr;
stun_attr_xor_mapped_address_ipv4 ipv4;
ipv4.header.type = XOR_MAPPED_ADDRESS;
ipv4.header.len = 8;
ipv4.family = 0x01;
ipv4.addr = addrin->sin_addr.s_addr;
ipv4.port = ntohs(addrin->sin_port);
stun_add_attr(resp, &ipv4.header);
stun_attr_message_integrity integrity;
bzero(&integrity, sizeof(integrity));
integrity.header.type = MESSAGE_INTEGRITY;
integrity.header.len = 20;
stun_add_attr(resp, &integrity.header);
stun_attr_fingerprint fp;
fp.header.type = FINGERPRINT;
fp.header.len = 4;
stun_add_attr(resp, &fp.header);
stun_calculate_integrity(resp, (uint8_t*)ice.localpassword.c_str(), ice.localpassword.size());
stun_calculate_crc32(resp);
if(fd) {
uint8_t content[1024];
uint32_t size = sizeof(content);
int ret = stun_serialize(resp, content, &size);
if(ret < 0) {
loge("fail to serialize resp: %d", ret);
} else {
logd("send stun: %d", size);
sendto(fd, content, size, 0, addr, socklen);
}
struct sockaddr_in* inaddr = (struct sockaddr_in*)addr;
if(firstaddr == inaddr->sin_addr.s_addr) {
send_stun_requst(fd, addr, socklen);
}
}
stun_free_message(resp);
stun_free_message(req);
return;
}
void handle_rtp(char* buf, int32_t len) {
logfunc();
srtp_err_status_t res;
if(!buf || !len) return;
int datalen = len;
res = srtp_unprotect(stream_in, buf, &datalen);
//res = srtp_unprotect(stream_out, buf, &datalen);
if(res != srtp_err_status_ok) {
loge("fail to unprotect srtp: %d len=%d datalen=%d", res, len, datalen);
return;
}
rtp_header* header = (rtp_header*)buf;
logd("rtp ssrc: %08x", ntohl(header->ssrc));
}
void handle_rtcp(char* buf, int32_t len) {
logfunc();
if(!buf || !len) return;
}
int run_srv() {
logfunc();
int ret = 0;
EC_KEY* ecdh = NULL;
char buf[4096];
int fd = udp_new_server();
if(fd < 0) return -1;
ioread = BIO_new(BIO_s_mem());
iowrite = BIO_new(BIO_s_mem());
iofilter = BIO_new(BIO_dtls_filter());
if(!ioread || !iowrite) {
loge("fail to allocate io mem");
return -1;
}
BIO_set_mem_eof_return(ioread, -1);
BIO_set_mem_eof_return(iowrite, -1);
BIO_push(iofilter, iowrite);
logd("read: %p write: %p filter: %p", ioread, iowrite, iofilter);
if(0 != sec_env_init(0)) {
return -1;
}
if(fd < 0) return -1;
ssl = SSL_new(ssl_ctx);
if(!ssl) {
loge("fail to new ssl");
goto exit;
}
SSL_set_ex_data(ssl, 0, NULL);
SSL_set_info_callback(ssl, sec_info_callback);
SSL_set_bio(ssl, ioread, iofilter);
SSL_set_connect_state(ssl);
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if(!ecdh) {
log("fail to create ECKEY");
goto exit;
}
SSL_set_options(ssl, SSL_OP_SINGLE_ECDH_USE);
SSL_set_tmp_ecdh(ssl, ecdh);
EC_KEY_free(ecdh);
SSL_set_read_ahead(ssl, 1);
SSL_set_connect_state(ssl);
while(1) {
bzero(buf, sizeof(buf));
struct sockaddr fromaddr;
socklen_t socklen;
ret = recvfrom(fd, buf, sizeof(buf), 0, &fromaddr, &socklen);
if(ret < 0) {
loge("fail to recv data: %s", strerror(errno));
break;
}
struct sockaddr_in* addr = (struct sockaddr_in*)&fromaddr;
if(!firstaddr) firstaddr = addr->sin_addr.s_addr;
if(firstaddr != addr->sin_addr.s_addr) {
loge("discard data from: %s", inet_ntoa(addr->sin_addr));
continue;
}
if(is_stun(buf, ret)) {
//static int saved = 0;
//if(!saved) {
// saved = 1;
// FILE* fp = fopen("stun.request", "w");
// if(fp) {
// fwrite(buf, 1, ret, fp);
// fclose(fp);
// }
//}
handle_stun((uint8_t*)buf, ret, fd, &fromaddr, socklen);
} else if(is_password(buf, ret)) {
handle_password((uint8_t*)buf, ret, fd, &fromaddr, socklen);
} else if(is_dtls(buf, ret) || (!is_rtp(buf, ret) && !is_rtcp(buf, ret))) {
handle_dtls((uint8_t*)buf, ret, fd, &fromaddr, socklen);
}
if(status == NORMAL_STATUS) {
if(is_rtp(buf, ret)) {
handle_rtp(buf, ret);
} else if(is_rtcp(buf, ret)) {
handle_rtcp(buf, ret);
}
} else {
loge("recv msg from status: %08x %d", status, ret);
}
}
exit:
logi("server exit.");
close(fd);
return 0;
}
int main() {
return run_srv();
}
/********************************** END **********************************************/
<file_sep>/rtp.h
/*
**************************************************************************************
* Filename: rtp.h
* Description: header file
*
* Version: 1.0
* Created: 2018-02-10 10:26:21
*
* Revision: initial draft;
**************************************************************************************
*/
#ifndef RTP_H_INCLUDED
#define RTP_H_INCLUDED
#include <endian.h>
#include <inttypes.h>
typedef struct rtp_header
{
#if __BYTE_ORDER == __BIG_ENDIAN
uint16_t version:2;
uint16_t padding:1;
uint16_t extension:1;
uint16_t csrccount:4;
uint16_t markerbit:1;
uint16_t type:7;
#elif __BYTE_ORDER == __LITTLE_ENDIAN
uint16_t csrccount:4;
uint16_t extension:1;
uint16_t padding:1;
uint16_t version:2;
uint16_t type:7;
uint16_t markerbit:1;
#endif
uint16_t seq_number;
uint32_t timestamp;
uint32_t ssrc;
uint32_t csrc[16];
} rtp_header;
#endif /*RTP_H_INCLUDED*/
/********************************** END **********************************************/
| cdcf22ba30326273ba67b8636640224313312956 | [
"Markdown",
"C",
"Makefile",
"C++"
]
| 16 | C | oswystan/relayserver | 3428b7a8d6e533a22b440453e1b37356cf191c4f | b7bda69f0005cca82357d0e143d6572d9eff1aab |
refs/heads/master | <repo_name>Surajit98/trail-android<file_sep>/app/src/main/java/com/amalbit/animationongooglemap/U.kt
package com.amalbit.animationongooglemap
import android.util.Log
class U {
companion object {
@JvmStatic fun log(tag: String, msg: String) {
Log.d(tag, msg);
}
}
} | 265ace6b170989419b96e17c547d4f6f9da9de78 | [
"Kotlin"
]
| 1 | Kotlin | Surajit98/trail-android | 14ec7338ffbba5eb38944344d9858552e77fe632 | e99113703820bf6c7060632a78aef979a8e42d25 |
refs/heads/master | <file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('article/{id}/upvote', 'ArticleController@upvote');
Route::get('article/{id}/downvote', 'ArticleController@downvote');
Route::resource('article/', 'ArticleController');
Route::resource('article/', 'ArticleController')->except([
'show',
]);
Route::get('article/{id}', 'ArticleController@show');
/* Route::resource('user/', 'UserController')->except(['show', 'index', 'destroy']);
*/
Route::post('commentaire/', 'CommentaireController@store');
Route::get('/home', 'HomeController@index')->name('home');
Route::get('user/', 'UserController@edit');
Route::post('user/','UserController@update');
Route::match(['get', 'post'], '/botman', 'BotManController@handle');<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Article;
class Commentaire extends Model
{
public function article()
{
return $this->belongsTo('Article');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Article;
use App\Vote;
use Illuminate\Http\Request;
use Auth;
use Illuminate\Support\Str;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$articles = Article::simplePaginate(15);
$str = new Str;
return view('article.index', ['articles' => $articles, 'str' => $str]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('article.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$article = new Article;
$article->title = $request->input('title');
$article->content = $request->input('content');
$article->user_id = Auth::id();
$article->save();
return redirect()->back()->with('success', 'Article ajouté !');
}
/**
* Display the specified resource.
*
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$article = Article::findOrFail($id);
$commentaires = $article->commentaires;
return view('article.show', ['article' => $article, 'commentaires' => $commentaires]);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/
public function edit(Article $article)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Article $article)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Article $article
* @return \Illuminate\Http\Response
*/
public function destroy(Article $article)
{
//
}
public function upvote($id)
{
$vote = new Vote;
$vote->user_id = Auth::id();
$vote->votable_type="Article";
$vote->votable_id=$id;
$vote->vote="upvote";
$count = Vote::where('user_id', '=', Auth::id())->count();
$vote->save();
return redirect()->back();
}
public function downvote($id)
{
$vote = new Vote;
$vote->user_id = Auth::id();
$vote->votable_type="Article";
$vote->votable_id=$id;
$vote->vote="downvote";
$vote->save();
return redirect()->back();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Commentaire;
use App\Article;
use Illuminate\Http\Request;
use Auth;
class CommentaireController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $r)
{
$commentaire = new Commentaire;
$commentaire->contenu = $r->input('contenu');
$commentaire->user_id = Auth::id();
$commentaire->article_id = $r->input('article_id');
$commentaire->save();
return redirect()->back();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\User;
class UserController extends Controller
{
public function edit()
{
$user = User::findOrFail(Auth::id());
return view('user/edit', ['user' => $user]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$id = Auth::id();
User::where('id', $id)->update($request->except('_token'));
return redirect('user/')->with('success', 'Données modifiées');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep># Nuit de l'info – 5 au 6 décembre 2019
## Présentation de la nuit de l'info
La Nuit se déroule tous les ans, du premier jeudi du mois de décembre, coucher du soleil, jusqu'au lever du soleil le lendemain matin.
La Nuit de l’Info est une compétition nationale qui réunit étudiants, enseignants et entreprises pour travailler ensemble sur le développement d’une application web.
Les participants ont la durée d'une nuit pour proposer, implémenter et packager une application Web 2.0.
Durant cette nuit, des partenaires lancent des défis (par exemple : interface web la plus ergonomique, meilleure architecture du système, meilleure collaboration, etc.) aux équipes participantes, et proposent des prix pour les équipes ayant le mieux réussi.
La nuit est aussi l'occasion de rencontres et discussions avec les entreprises, les ingénieurs et les chefs d'entreprises qui viennent soutenir les étudiants, voire leur donner quelques conseils pour mieux relever les défis.
## Sujet 2019 et axe abordé par l'équipe
Le sujet de la nuit de l'info en 2019 consistait à réaliser un site Web sur lequel seraient mis en place, par quelque moyen que ce soit, des articles et des sujets à visée informative à propos des différents aspects de la vie étudiante.
En prenant en compte la diversité de profils présents sur un campus (plus spécifiquement celui de la Doua), il fallait trouver les axes les plus intéressants à aborder sur le site Web afin de proposer aux étudiants en situation difficile (que ce soit d'un point de vue financier, psychologique, dû à une source de stress, problèmes personnels, etc...) des solutions et une sorte de première aide grâce à laquelle il leur serait possible de mieux appréhender leurs problèmes.
Après analyse de ce sujet, notre groupe pris la décision de réaliser un site Web au concept plutôt spécifique, à savoir:
N'importe quel étudiant est en mesure de créer un compte sur le site, en saisissant certaines informations supplémentaires (si bourse perçue, le montant actuel, situation, commentaire sur les problèmes rencontrés s'il y en a).
L'idée est par la suite celle d'une communauté étudiante quasiment auto-gérée, à la manière d'un site comme Reddit, mais orienté sur les besoins spécifiques des étudiants et des problèmes qu'ils sont susceptibles de rencontrer.
Ainsi, n'importe quel étudiant, sur notre site, serait en mesure de poster un article ou une petite astuce (de motivation personnelles, d'aide psychologique, de conseil, d'astuces face à la précarité, etc...). Son post serait ensuite évalué par la communauté, à savoir down-vote ou up-vote.
De cette manière les articles les plus intéressants pour les étudiants ou les plus susceptibles d'aider un maximum de monde seraient naturellement affichés en haut de la page d'accueil selon ce que la communauté du site déciderait.
## Stade final du projet
Le but de la Nuit de l'Info étant de réaliser un projet en une seule nuit, il est évident que seuls certains aspects étaient possible à implémenter dans ce temps.
L'aspect graphique, élaboré avec Bootstrap, fut géré par <NAME>, dans l'optique d'avoir une première ébauche qui serait visusellement plus ergonomique et attractive d'un point de vue des étudiants (bien que, cette dernière n'étant pas primordiale pour un projet de ce type, elle fut réalisée dans état le plus basique).
Le site Web est, d'une manière générale, fonctionnel, en ce sens qu'il permet d'inscrire et se connecter à son compte, puis de poster des articles qui peuvent ensuite être évalués par la communauté (ils seront alors selon le nombre de vote positionnés plus ou moins en haut de la page d'accueil).
Enfin, un système de commentaire est également disponible, et chacun est libre de commenter en dessous de n'importe quel article. Ces commentaires sont également triés selon le nombre d'upvote/downvote qu'ils obtiennent, et donc leur pertinence.
## Réalisation du projet
<NAME>
DO ESPIRITO <NAME>
<NAME>
*Rédaction: <NAME>*
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\{Commentaire, Vote, User};
use Illuminate\Support\Facades\DB;
class Article extends Model
{
public function commentaires()
{
return $this->hasMany(Commentaire::class);
}
public function votes()
{
return $this->morphMany(Vote::class, 'votable');
}
public function getScore()
{
$nbUp = DB::table('votes')
->where('vote', '=', 'upvote')
->where('votable_type', '=', 'Article')
->where('votable_id', "=", $this->id)
->count();
$nbDown = DB::table('votes')
->where('vote', '=', 'downvote')
->where('votable_type', '=', 'Article')
->where('votable_id', "=", $this->id)
->count();
return $nbUp - $nbDown;
}
public function user()
{
return $this->belongsTo(User::class);
}
}
| e166014a706681c1146d18e182a5a64ff9fe8c13 | [
"Markdown",
"PHP"
]
| 7 | PHP | Altazi-Hussein/nuitInfo | 3d95f97a3bb396a5d884c5732245e7578126b6f5 | dbb74176d7f12a9b08346df44d772070e3ac5370 |
refs/heads/master | <file_sep>#!/bin/bash
# script to adapt to the network config after the TC install
#
/opt/schoolserver/xsce/xsce-network
systemctl disable finish-install.service
<file_sep>#!/bin/sh
. /etc/xsce/xsce.env
cd $XSCE_DIR
# while we're here untrack local vars
git update-index --assume-unchanged vars/local_vars.yml
# get current version
BRANCH=`git rev-parse --abbrev-ref HEAD`
COMMIT=`git rev-parse --verify HEAD`
if [ -d /usr/lib64/php ]
then
PHPLIB_DIR=/usr/lib64/php
else
PHPLIB_DIR=/usr/lib/php
fi
if [ -f /proc/device-tree/mfg-data/MN ]
then
XO_VERSION=`cat /proc/device-tree/mfg-data/MN`
else
XO_VERSION="none"
fi
cat <<EOF
{"phplib_dir" : "$PHPLIB_DIR",
"xsce_branch" : "$BRANCH",
"xsce_commit" : "$COMMIT",
"xo_model" : "$XO_VERSION"}
EOF
<file_sep>#!/bin/sh -x
# tinycore script to partition, and load the OS for XSCE
#
# change log ======================================
# 160218 give up on EFI, dispense with FAT partition, so now just root, and library
# first look for command line flags
TARGET_LOADER="MBR"
EFI=`grep -w efi /proc/cmdline`
MBR=`grep -w mbr /proc/cmdline`
i686=`grep -w i686 /proc/cmdline`
x86_64=`grep -w x86_64 /proc/cmdline`
PAYLOAD='netinst' # default for the initial install
PAYLOAD_ARCH="x86_64"
ROOTFS="sda2"
# get the variables that are being passed back and forth
# in particular, PAYLOAD is the name of the tgz image
source /mnt/sdb2/tce/installer.conf
# TARLIB controls whether a separate library tar is generated
SRCDIR=$(cd `dirname ${0}`; pwd)
curdir=`pwd`
# wipe out the partition table
if [ -d /mnt/sdb2/tce ];then
dd ip=/dev/zero of=/dev/sda bs=512 count=2
fi
# for testing purposes we need to be able to delete a gpt and initialize
# as a mbr partition table. But only gdisk knows where gpt is
# First determine if current partition table is gpt
gpt=`blkid /dev/sda | grep gpt`
if [ ! -z "$gpt" ]; then
# following deletes (zaps) a gpt partition table
cat << EOF | gdisk /dev/sda
x
z
y
y
EOF
fi
# parted refuses to rm partition without interaction, so blast partition table
dd if=/dev/zero of=/dev/sda bs=512 count=1
parted -s /dev/sda mklabel msdos
partprobe /dev/sda
parted -s -a optimal /dev/sda mkpart primary fat32 8192s 300mB
parted -s -a optimal /dev/sda mkpart primary ext4 300mB 46gB
parted -s -a optimal /dev/sda mkpart primary linux-swap 46gB 50gB
parted -s -a optimal -- /dev/sda mkpart primary ext4 50gB -1s
partprobe /dev/sda
until [ -e /dev/sda1 ]; do sleep .25; done
mkfs.vfat -n boot /dev/sda1
mkfs.ext4 -L rootfs /dev/$ROOTFS
mkswap -L swap /dev/sda3
mkfs.ext4 -L library /dev/sda4
mkdir -p /mnt/sda1
mkdir -p /mnt/$ROOTFS
mkdir -p /mnt/sda4
mount /dev/sda1 /mnt/sda1
mount /dev/$ROOTFS /mnt/$ROOTFS
mount /dev/sda4 /mnt/sda4
## put a file on this drive that we can look for
mkdir -p /mnt/sda1/grub
cd /mnt/sda4
mkdir -p cache
cd /mnt/$ROOTFS
umount /mnt/sda4
#create mount points for the partitions
mkdir -p /mnt/$ROOTFS/library
mkdir -p /mnt/$ROOTFS/boot
# mount them
mount /dev/sda4 /mnt/$ROOTFS/library
until [ -d /mnt/$ROOTFS/library/cache ]; do sleep .25; done
mount /dev/sda1 /mnt/$ROOTFS/boot
until [ -d /mnt/$ROOTFS/boot/grub ]; do sleep .25; done
# put the root file system in place
cd /mnt/$ROOTFS/
tar -xf ${SRCDIR}/${FC_VER}/${PAYLOAD_ARCH}/${PAYLOAD_ARCH}fc${FC_VER}_${PAYLOAD}.tgz
# need to put the library contents in place via a separate tar file
if [ "$PAYLOAD" != "netinst" -a "$TARLIB" == "true" ];then
cd /mnt/$ROOTFS/library
tar -xf ${SRCDIR}/${FC_VER}/${PAYLOAD_ARCH}/${PAYLOAD_ARCH}fc${FC_VER}_${PAYLOAD}-library.tgz
fi
cd $curdir
# create a fstab
cat << EOF > /mnt/$ROOTFS/etc/fstab
LABEL=rootfs / ext4 defaults 0 1
LABEL=boot /boot vfat defaults 0 1
LABEL=swap / swap defaults 0 0
LABEL=library /library ext4 defaults 0 2
EOF
# now install the grub mbr loader, and the grub EFI loader
# following set up the mbr boot requirements
grub-install --boot-directory=/mnt/$ROOTFS/boot /dev/sda
# the shuttle is where to put any scripts to make deployment wide changes
mkdir -p /mnt/$ROOTFS/opt/schoolserver/xsce/scripts/installer
cp /mnt/sdb2/tce/shuttle/xsce-after-installer /mnt/$ROOTFS/opt/schoolserver/xsce/scripts/installer/
cp /mnt/sdb2/tce/shuttle/sysprep /mnt/$ROOTFS/opt/schoolserver/xsce/scripts/installer/
ln -s /opt/schoolserver/xsce/scripts/installer/sysprep /mnt/$ROOTFS/usr/local/sbin/sysprep
ln -s /opt/schoolserver/xsce/xsce-network /mnt/$ROOTFS/usr/local/sbin/xs-network
cp /mnt/sdb2/tce/shuttle/finish-install.service /mnt/$ROOTFS/etc/systemd/system/
# blast the modified grub.cfg to the correct place
#cp -f /mnt/sdb2/tce/grub.cfg /mnt/sda2/boot/grub/
echo
echo done!
echo
# vim: ts=4 et
<file_sep>#!/bin/bash -x
# routine to shrink the hard disk and create a compressed image
# at this point, assume partition is /dev/sda3
partition=sdb3
partno=`echo $partition|sed -e's/[a-z]*\([0-9]\)/\1/'`
blkdev=`echo $partition|sed -e's/\([a-z]*\)[0-9]/\1/'`
mount "/dev/$partition" /mnt
size=`df -B 4k |grep "/dev/$partition"|gawk '{print $3}'`
blocks=$(( $size + 10000))
echo "size with margin is $blocks 4k blocks; partition for fdisk is $partno"
umount "/dev/$partition"
fsck -n "/dev/$partition"
tune2fs -O ^has_journal "/dev/$partition"
e2fsck -f "/dev/$partition"
read "hit any key to continue"
resize2fs -M "/dev/$partition"
e2fsck -f "/dev/$partition"
newsize=`fsck -a "/dev/$partition" | gawk '/rootfs/ {print $5}' | sed -e 's/.*\/\([0-9]*\)/\1/'`
tune2fs -j "/dev/$partition"
unitsize=`fdisk -l "/dev/$blkdev"|grep Units | gawk '{print $9}'`
lastunit=`fdisk -l "/dev/$blkdev"|grep "$partition" | gawk '{print $4}'`
copysize=$(($unitsize * $lastunit / 1024 ))
echo "dd if=/dev/$blkdev of=rawfs.$$ bs=1024 count=$(copysize)K"
<file_sep>#!/usr/bin/env python
import sys
if len(sys.argv) < 2:
print("must pass small list first to merge into second file")
sys.exit()
val = {}
for line in open(sys.argv[1]):
if line.find("=") > -1:
name = line.split("=")[0]
val[name] = line.split("=")[1].rstrip()
val2 = {}
for line in open(sys.argv[2]):
if line.find("=") > -1:
name = line.split("=")[0]
val2[name] = line.split("=")[1].rstrip()
if (name in val):
if val[name] == line.split("=")[1].rstrip():
print('same,%s=%s'%(name,val[name]))
else:
print('changed,%s=1->%s,2->%s # updated from #1'%(name,val[name],val2[name]))
else:
print('missing in 1->,%s'% line.rstrip())
else:
print line.rstrip()
# now print out the values in first config missing in second
for config in val:
if not config in val2:
print('missing in 2->,%s=%s'%(config,val[config]))
# vim: ts=8 expandtab softtabstop=4 shiftwidth=4
<file_sep>#!/bin/bash -x
# first part makes iso image from tiny core,c
# second part sets up data for XSCE target
# Last part creates the image which gets copied onto USB stick
# somewhat based on <NAME>'s mktinycorxo at
# http://dev.laptop.org/git/users/quozl/mktinycorexo
# Stick required is at least 2G USB
PREFIX="/root/installer"
mkdir -p $PREFIX/persist/tce
NEWPAYLOAD_ARCH=
PAYLOAD=
PAYLOAD_ARCH=
USBSIZE="3600" # in MB for just the data partition
# Let user decide whether to continue with last installer operation
# Get the previous state
# -- thoughts have evolved -- always start over
rm $PREFIX/persist/tce/installer.conf
NEWPAYLOAD='skip'
# skip all of the following:
if 1; then
if [ -f $PREFIX/persist/tce/installer.conf ]; then
source $PREFIX/persist/tce/installer.conf
fi
echo
echo
read -p "The Payload from last operation was $PAYLOAD. Change y/N: " ans
echo " --and the architecture was $PAYLOAD_ARCH"
case $ans in
y|Y)
read -p "New value for payload (default=netinst)? " ans
if [ "$ans" == "" ]; then
NEWPAYLOAD=netinst
else
NEWPAYLOAD=$ans
fi
;;
*)
NEWPAYLOAD=$PAYLOAD
;;
esac
read -p "The arch from last operation was $PAYLOAD_ARCH. Change y/N: " ans
case $ans in
y|Y)
read -p "New value for payload (default=x86_64)? " ans
if [ "$ans" == "" ]; then
NEWPAYLOAD_ARCH=x86_64
else
NEWPAYLOAD_ARCH=$ans
fi
;;
*)
NEWPAYLOAD_ARCH=$PAYLOAD_ARCH
;;
esac
fi
#=================================================================================
# create a configuration file to pass to tiny core linux (centralize variables)
# To start a new install process from downloaded netinst, remove persist/tct/installer.conf
if [[ $PAYLOAD != $NEWPAYLOAD || \
$PAYLOAD_ARCH != $NEWPAYLOAD_ARCH || \
! -f $PREFIX/persist/tce/installer.conf ]]; then
cat << EOF > $PREFIX/persist/tce/installer.conf
#OS="centos"
OS="fedora"
FC_VER="21"
FC_URL="http://mirrors.usc.edu/pub/linux/distributions/fedora/linux/releases/${FC_VER}/Fedora/${FC_ARCH}/os/images/"
UK_URL="http://download.unleashkids.org/xsce/downloads/installer/tools/"
ISO="${PREFIX}/iso_root"
PERSIST="${PREFIX}/persist"
PREFIX="${PREFIX}"
# upstream versions, tiny core linux
CORE_VERSION=7.x
# tinycore initramfs name
CORE_INITRD_X86=core
#CORE_INITRD_X86=corepure64
CORE_KERNEL_X86=vmlinuz
#CORE_KERNEL_X86=vmlinuz64
CACHE=yes
PAYLOAD=$NEWPAYLOAD
PAYLOAD_ARCH=$NEWPAYLOAD_ARCH
# ARCH is the tinycore arch -- we'll do everything with i686
ARCH="x86"
# tar library separately
TARLIB="false"
EOF
chmod 755 $PREFIX/persist/tce/installer.conf
fi
source $PREFIX/persist/tce/installer.conf
CURDIR=`pwd`
SCRIPTDIR=$(cd `dirname $0`;pwd)
# we need a record of what the scripts does, good (or bad)
DATESTR=`date "+%y%m%d-%H"`
LOGFILE=$CURDIR/mkstick-${DATESTR}.$$.log
exec 2>&1
#exec > tee -a $LOGFILE
COLOUR="yes"
set +x
# check that we have the needed tools
for x in mkisofs xzcat wget gdisk syslinux grub2-install mke2fs e2label mkdosfs; do
which $x
if [ $? -ne 0 ] ; then
echo -e "\\0033[1;34m"
echo "Please install $x and run the script again"
echo -en "\\0033[0;39m"
exit 1
fi
done
set -x
# verify that there is an USB drive installed
REMOVABLE_DRIVES=""
for _device in /sys/block/*/device; do
if echo $(readlink -f $_device)|egrep -q "usb"; then
_disk=`echo $_device | cut -f4 -d/`
REMOVABLE_DRIVES="$_disk"
fi
done
if [ -z $REMOVABLE_DRIVES ];then
echo "no usb found. Quitting"
exit 1
fi
dev="/dev/$REMOVABLE_DRIVES"
# some distributions do automount, unmount everything
umount /dev/$dev*
# build the cache
mkdir -p $ISO/boot/isolinux
mkdir -p $ISO/boot/images
mkdir -p $PERSIST/tce/optional
mkdir -p $PERSIST/tce/shuttle
mkdir -p $PERSIST/target/syslinux
mkdir -p /mnt/tinycore
function p_error {
if [ "$COLOUR" = "yes" ]; then
echo -e "\e[1;91m$1\e[0;39m"
else
echo "$1"
fi
}
function p_warning {
if [ "$COLOUR" = "yes" ]; then
echo -e "\e[1;93m$1\e[0;39m"
else
echo "$1"
fi
}
function p_informational {
if [ "$COLOUR" = "yes" ]; then
echo -e "\e[1;92m$1\e[0;39m"
else
echo "$1"
fi
}
function p_begin {
if [ "$COLOUR" = "yes" ]; then
echo -ne "\e[1;96m$1\e[0;39m"
else
echo -n "$1"
fi
}
function p_end {
if [ "$COLOUR" = "yes" ]; then
echo -e "\e[1;92m$1\e[0;39m"
else
echo "$1"
fi
}
function get_kernel {
cd "$ISO/boot/isolinux"
flags="-q -c"
path=$1/$2
file=$3
checksum=$file.md5.txt
if [ ! -f $file ]; then
p_begin "Downloading $file ... "
wget $flags $path/$file
p_end "ok"
return
fi
if [ $CACHE = no ]; then
p_begin "Checking if $file is up to date ... "
wget $flags $path/$checksum
if [ "$(cat $checksum | cut -f 1 -d ' ')" \
!= "$(md5sum $file | cut -f 1 -d ' ')" ]; then
rm -f $file
p_begin "Downloading $file ... "
wget $flags $path/$file
fi
p_end
rm -f $checksum
fi
}
get_kernel \
http://repo.tinycorelinux.net/${CORE_VERSION} \
${ARCH}/release/distribution_files \
${CORE_INITRD_X86}.gz
get_kernel \
http://repo.tinycorelinux.net/${CORE_VERSION} \
${ARCH}/release/distribution_files \
${CORE_KERNEL_X86}
exec > tee -a $LOGFILE
# download tiny core extension
cat <<EOF > $PERSIST/tce/onboot.lst
appbrowser-cli.tcz
avahi.tcz
dosfstools.tcz
dbus.tcz
expat2.tcz
gcc_libs.tcz
gdisk.tcz
glib2.tcz
grub2.tcz
grub2-efi.tcz
gzip.tcz
icu.tcz
libdaemon.tcz
libavahi.tcz
libffi.tcz
libnl.tcz
libusb.tcz
lighttpd.tcz
nano.tcz
ncurses-common.tcz
ncurses.tcz
ncurses-utils.tcz
nss-mdns.tcz
openssh.tcz
openssl-1.0.0.tcz
parted.tcz
popt.tcz
readline.tcz
rsync.tcz
sed.tcz
syslinux.tcz
tar.tcz
usb-utils.tcz
wget.tcz
xz.tcz
EOF
# wait for the new file to be available
sync
p_begin "Checking Tiny Core extensions ... "
base=http://repo.tinycorelinux.net/${CORE_VERSION}
cd $PERSIST/tce/optional
flags="-q -c "
for file in $(<${PERSIST}/tce/onboot.lst); do
if [ ! -f $file ]; then
wget ${flags} ${base}/${ARCH}/tcz/$file \
wget ${flags} ${base}/${ARCH}/tcz/$file.md5.txt \
wget ${flags} ${base}/${ARCH}/tcz/$file.dep \
p_end "got $file"
else
if [ $CACHE = no ]; then
rm -f $file.md5.txt
wget ${flags} ${base}/${ARCH}/tcz/$file.md5.txt
if [ "$(cat $file.md5.txt | cut -f 1 -d ' ')" \
!= "$(md5sum $file | cut -f 1 -d ' ')" ]; then
rm -f $file{,.dep}
wget ${flags} ${base}/${ARCH}/tcz/$file \
wget ${flags} ${base}/${ARCH}/tcz/$file.dep \
p_end "updated $file"
fi
fi
fi
done
p_end "ok"
# get the essential configuration files to /boot/isolinux
cd $SCRIPTDIR
cp -p isolinux.cfg $ISO/boot/isolinux
cp -p /usr/share/syslinux/isolinux.bin $ISO/boot/isolinux
cp -p /usr/share/syslinux/ldlinux.c32 $ISO/boot/isolinux
cp -p /usr/share/syslinux/menu.c32 $ISO/boot/isolinux
cp -p /usr/share/syslinux/libutil.c32 $ISO/boot/isolinux
# get the persistent tinycore data to include in our package
p_begin "Fetching the persitent Data for Tiny Core ... "
tce_root=$PERSIST/tce/
cd $tce_root
if [ ! -f $PERSIST/tce/mydata.tgz ];then
flags="-q -c -P $tce_root"
wget ${flags} ${UK_URL}mydata.tgz
else
if [ $CACHE = no ]; then
rm -f mydata.md5.txt
wget ${flags} ${UK_URL}mydata.md5.txt
if [ "$(cat mydata.tgz.md5.txt | cut -f 1 -d ' ')" \
!= "$(md5sum mydata.tgz | cut -f 1 -d ' ')" ]; then
wget ${flags} ${UK_URL}mydata.tgz
fi
fi
fi
# following script copies the rootfs, after configuration, back to USB stick
cp -p $SCRIPTDIR/fetch_target $tce_root
p_end "ok"
# get the EFI tree from fedora
cd $ISO/boot/images
if [ ! -f "efiboot.img" ]; then
wget ${UK_URL}efiboot${FC_VER}.img
mv efiboot${FC_VER}.img efiboot.img
fi
cd $CURDIR
#=================================================================================
# now that we have all the Tiny Core stuff set up, What do we need to install XSCE
function get_rootfs {
FC_ARCH=$1
# where to put the rootfs
RFS=$PERSIST/target/${FC_VER}/${FC_ARCH}
mkdir -p $RFS
flags="-q -c "
file=$2
path=${UK_URL}$file
if [ ! -f $RFS/$file ]; then
p_begin "Downloading $file ... "
cd $RFS
if [ ! -f $file ]; then
wget $flags $path
fi
p_end "ok"
else
if [ $CACHE = no ]; then
rm -f ${path}.md5.txt
wget ${flags} ${path}.md5.txt
# if md5 does not exist, just use what we have
if [ $? -ne 0 ]; then
return
fi
if [ "$(cat ${path}.md5.txt | cut -f 1 -d ' ')" \
!= "$(md5sum ${path} | cut -f 1 -d ' ')" ]; then
wget $flags $path
fi
fi
fi
}
exec > tee -a $LOGFILE
if [ "$PAYLOAD" == "netinst" ];then # download an image from XSCE repository
if [ "$PAYLOAD_ARCH" == "i686" ]; then
get_rootfs i686 i686fc${FC_VER}_${PAYLOAD}.tgz
else
get_rootfs x86_64 x86_64fc${FC_VER}_${PAYLOAD}.tgz
fi
fi
# and the generic config files
cd $SCRIPTDIR
cp -p loadOS $PERSIST/target
cp -p grub.cfg* $PERSIST/target/
# We're assuming that efi is only x86_64 --grub.cfg.target implies x86_64
cp -p grub.cfg.target.efi $PERSIST/target/grub.cfg.efi
cp -p finish-install.service /$PERSIST/tce/shuttle
cp -p xsce-after-installer /$PERSIST/tce/shuttle
cp -p sysprep /$PERSIST/tce/shuttle
#=================================================================================
# The following stuff is necessary to create the USB stick
# create the ISO
cd "$ISO"
STICKNAME="FC21_mbr_efi_netinst"
#mkisofs -U -A "TinyCore" -V "TinyCore x86 Disc 1" \
# -volset "TinyCore x86" -J -joliet-long -r -v -T -x ./lost+found \
# -o ../${STICKNAME}.iso \
# -b boot/isolinux/isolinux.bin -c boot/isolinux/boot.cat -no-emul-boot -boot-load-size 4 \
# -boot-info-table -eltorito-alt-boot -e boot/images/efiboot.img -no-emul-boot .
mkisofs -o ../${STICKNAME}.iso -b boot/isolinux/isolinux.bin -c boot/isolinux/boot.cat \
-no-emul-boot -boot-load-size 4 -boot-info-table .
# the following puts the mbr loader in place
isohybrid ../$STICKNAME.iso --partok
#=================================================================================
read -t 10 -p "\n\nI'm about to write $dev OK [Y/n]:" ans
case $ans in
"y"|"Y")
;;
*)
if [ ! -z $ans ];then
exit 1
fi
esac
# if the non-data is cleared it might compress better
#dd if=/dev/zero of=$dev bs=1M count=100
#dd if=/dev/zero of=$dev bs=1M count=2500
# partition the stick with a small ISO (not writeable) and then larger mounted partition
#parted -s ${dev} mklabel msdos
#partprobe $dev
#parted -s -a cylinder ${dev} mkpart primary 8192s 54mB
#parted -s -a cylinder ${dev} mkpart primary ext4 54mB 4gB
sfdisk -u S $dev << EOF
8192,110592,83,*
118785,8389836,83
EOF
sleep 5
partprobe $dev
# put the iso into the small partition
cd $PREFIX
dd if=$STICKNAME.iso of="${dev}1" bs=4M
# copy a master boot record to stick
cd $SCRIPTDIR
dd if=/usr/share/syslinux/mbr.bin of=${dev} bs=440 count=1
umount ${dev}2
# and format the data partition
mke2fs -t ext2 -L data "${dev}2"
sync
mkdir -p /tmp/data
mount ${dev}2 /tmp/data
# the shuttle folder is copied below tce
cp -rp $PERSIST/tce /tmp/data
if [ "$PAYLOAD_ARCH" == "i686" ];then
mkdir -p /tmp/data/target/${FC_VER}/i686
else
mkdir -p /tmp/data/target/${FC_VER}/x86_64
fi
cp -p $PERSIST/target/loadOS /tmp/data/target
cp -p $PERSIST/target/grub.cfg* /tmp/data/target
if [ ! -z ${PAYLOAD} -a "$PAYLOAD" != "skip" ];then
cp -rp $PERSIST/target/${FC_VER}/${PAYLOAD_ARCH}/${PAYLOAD_ARCH}fc${FC_VER}_${PAYLOAD}.tgz /tmp/data/target/${FC_VER}/${PAYLOAD_ARCH}
fi
umount /tmp/data
rmdir /tmp/data
# vim: tabstop=4 expandtabs shiftwidth=4 softtabstop=4
<file_sep>#!/bin/bash
# run this script to prepare for generating the install image
# remove all the network ifcfg files except lo
find /etc/sysconfig/network-scripts -name "ifcfg-*" |grep -v -e ifcfg-lo | xargs rm -rf
# remove uuid and ini files
rm -f /etc/xsce/uuid
# I don't think the console is happy if xsce.ini is missing.--and loose install history
#rm -f /etc/xsce/xsce.ini*
# remove any ssh keys
rm -rf /root/.ssh/*
# if my tools are installed, get rid of them
if [ -d /root/tools ]; then
rm -rf /root/tools
fi
# put a systemd unit file in the startup queue, removes itself after execution
systemctl enable finish-install.service
# create a grub config file that uses devices rather than UUIDs
grep UUID /etc/default/grub
if [ $? -ne 0 ]; then
echo GRUB_DISABLE_UUID=true >> /etc/default/grub
fi
grub2-mkconfig -o /boot/grub/grub.cfg
# remove the conflicting instructions
rm -f /boot/grub2/grub.cfg
<file_sep>
How to Install XSCE Offline
===========================
Instructions for Using Image Downloaded from Unleashkids.org
------------------------------------------------------------
The download is 2GB, and with a fairly fast internet connection can take more that 20 minutes. The images are located at http://download.unleashkids.org/xsce/downloads/installer/
I discovered that compressing only saved 10%, and added additional complexity to the process.
On a linux machine, once the image is local, copy the image to a USB stick by doing the following
dd if=<downloaded image file> of=<device name without any partition -- for example /dev/sdb> bs=1M
Once the USB is available, set the loader to boot in MBR (perhaps called legacy) mode, and set the boot preference to boot first from USB stick.
The USB stick is relatively dangrous is left laying around. If a machine is set to boot from USB stick, and if this USB stick is in the machine when it is booting, it would wipe out whatever is on the hard disk. So I have forced the user to have a monitor, and keyboard attached, and to confirm that the hard disk should be 'erased'.
The initial image may need some tweaking so that the networking autoconfigures correctly. Edit /opt/schoolserver/xsce/vars/local_vars.yml for the mode of schoolserver you want::
* Appliance mode -- operates within existing infrastructure, server has no dhcpd, named, squid, firewall
xsce_wan_enabled: True
xsce_lan_enabled: False
* Lan-controller mode -- no gateway, no squid, one ethernet port (or USB wifi dongle) but has dhcpd, named
xsce_wan_enabled: False
xsce_lan_enabled: True
* Gateway mode -- all of above enabled
xsce_wan_enabled: True
xsce_lan_enabled: True
Log on as root with password: <PASSWORD> (the centos image uses password:<PASSWORD>), connect the network adapters that will be used, make the selection of mode in local_vars, and run the following commands::
cd /opt/schoolserver/xsce/
./runtags prep,network,gateway (the most current master eliminates gateway -- will require only "./runtags network")
Overall Strategy
----------------
The code for creating an offline install is copied by ansible to {{ XSCE_BASE }}/xsce/scripts/installer/.
The script "mkstick" downloads Tiny Core Linux, and some version of a root file system for installation onto a USB stick. By default, "mkstick" downloads the "netinst" version of the Fedora Core version that is currently used by XSCE. The "PAYLOAD" variable specifies the name of the rootfs that will be incorporated in the stick.
The installation,performed by the USB stick onto the target machine, can be either 32bit or 64bit, and can install loaders that use mbr, or UEFI, firmware loaders.
After the "netinst" version has been copied by Tiny Core onto the target machine, and after the target machine is configured to the satisfaction of the user, the USB stick is used as a shuttle to bring the configured version of the root file system, back to the cache, on the desktop machine. That cache is then fully prepared to generate and replicate offline install USB sticks.
Functions of the Various Scripts
++++++++++++++++++++++++++++++++
mkstick
This is the main script to generate a USB with the Tiny Core loader. It requires that the generating machine be online, and that the operating system be the same as the target machine. if /etc/xsce/imagename exists, but <USB>/tce/tgzimagename does not, then "mkstick" becomes a replicator of offline install sticks from data in the cache.
loadOS
Is copied onto the USB stick, and run by the Tiny Core operating system to partition, format, and copy the target machine root file system, and set up the boot loader for that OS.
cachify -- Also gets configured RootFS
Also runs on the Tiny Core OS, to collect up the fully configured target machine so that it may be copied up to the cloud, and downloaded by others, as an offine install. There is interaction which records the fedora version, and architecture (32 or 64 bit) in the file /tce/tgzimagename. Once this file exists, the functin of "mkstick" changes. Thereafter "mkstick" replicates data out of the cache for the purpose of replicating offline install sticks.
extlinux.conf
This is the boot loader configuration file for the extlinux boot loader which occupies the boot sector of the USB stick
grub.cfg.target
Grub stands for the Grand Unified Boot loader. The mbr version of the boot loader is copied to the first sector of the hard disk(mbr), and the rest of the grub program is copied to the space just after the master boot record (mbr).
grub.cfg.target.efi
An efi (or UEFI) boot loader follows a new standard for the interface between the firmware and the OS loader. The firmware can find what it needs to load if a partition is formated with FAT 32 fomrat, has a special and unique identifier, and it partitioned with gpt partition format.
Reminders for How to Create the Bootable Installer
=================================================
* Download the netinstall versions of Fedora Core. On FC21, these are classified as Server installs.
* "dd" the version (i686 or x86_64) onto a USB stick. (this is normal install onnew hardware)
* Install each, selecting to generate one partition (/). Do not do automatic partitioning, and select "standard" rather than "LVM" partition type.
* Set root password (my first images have root password set to fedora), and create xsce-admin user/password.
* Turn on "keepcache=1" in /etc/yum.conf.
1. install git, ansible
#. add network adapter, if gateway autoconfig is wanted
#. clone xsce into /opt/schoolserver, cd to xsce, runansible
#. git clone https://github.com/XSCE/installer
#. "./runtags installer"
#. cd to /opt/schoolserver/xsce/scripts/installer
#. "./mkstick" -- lots of downloads, allow 50 minutes, or more if slow internet connection -- only takes long time first time populating cache.
* Start up Tiny Core.
* Got to /mnt/sdb2/tce, and run "fetch_target". Supply ARCH and filename (netinst).
* Move the USB stick back to desktop, and run cachify, which copies the rootfs to the cache, and also to unleashkids.org.
Notes for Generating Raspberry Pi 2 Image
=========================================
* Start with minimal FC21 image (kernel,and modules subsitituted at http://www.digitaldreamtime.co.uk/images/Fidora/21/
* Declare the platform in vars/local_vars to be "rpi2"
<file_sep>#!/usr/bin/env python
import sys
if len(sys.argv) < 2:
print("must pass small list first to merge into second file")
sys.exit()
val = {}
for line in open(sys.argv[1]):
if line.find("=") > -1:
name = line.split("=")[0]
val[name] = line.split("=")[1].rstrip()
val2 = {}
for line in open(sys.argv[2]):
if line.find("=") > -1:
name = line.split("=")[0]
val2[name] = line.split("=")[1].rstrip()
if (name in val):
if val[name] == line.split("=")[1]:
print("%s=%s"%(name,val[name]))
else:
print("%s=%s # updated from olpc"%(name,val[name]))
else:
print("%s"% line.rstrip())
else:
print line.rstrip()
# now print out the values in first config missing in second
for config in val:
if not config in val2:
print("%s=%s # additional config from olpc defconfig"%(config,val[config]))
# vim: ts=4 expandtab
<file_sep>#!/bin/bash
if [ ! -f installer.yml ]
then
echo "Installer Playbook not found."
echo "Please run this command from the top level of the git repo."
echo "Exiting."
exit
fi
taglist=installer
ansible-playbook -i ansible_hosts installer.yml --connection=local --tags="""$taglist"""
<file_sep>#!/bin/bash -x
# run this script after stock install of CentOS
# Absolute path to this script.
SCRIPT=$(readlink -f $0)
# Absolute path this script is in.
SCRIPTPATH=`dirname $SCRIPT`
yum install -y epel-release
yum install -y git ansible tree vim mlocate
mkdir -p /opt/schoolserver
cd /opt/schoolserver
if [ ! -d /opt/schoolserver/xsce ];then
git clone https://github.com/XSCE/xsce --depth 1
fi
cd xsce
./runtags download,download2
./install-console
echo "all done"
<file_sep>#!/bin/bash -x
# Runs on the desktop machine, which is used to make the USB stick
# Used in two situations:
# 1. copy the netinst rootfs back into the cache for creation of XSCE image
# 2. After interactive refinement of XSCE, copy configured rootfs to cache
# Using the USB as shuttle, bring the persistent data (rootfs) into local cache
# And if desired, copy it up to unleashkids.org
# verify that there is a USB drive installed
dev=""
mkdir -p /usb
maybe=`ls -la /sys/class/block/ | grep usb | gawk '{print $9}'`
if ! [ -z "$maybe" ];then
for token in $maybe; do
mount /dev/${token} /usb > /dev/null
if [ $? -eq 0 ]; then
if [ -f /usb/tce/mydata.tgz ]; then
dev=/dev/${token}
break
fi
umount /usb
fi
done
else
echo "no USB drive found. Please correct and rerun $0"
rmdir /usb
exit 1
fi
if [ -z $dev ]; then
echo "/tce/mydata.tgz was not found. Exiting"
exit 1
fi
mount $dev /usb
# get the definitions from mkstick
source /usb/tce/installer.conf
cd ${PREFIX}
# go grab the data
nibble=${FC_VER}/${PAYLOAD_ARCH}/${PAYLOAD_ARCH}fc${FC_VER}_${PAYLOAD}
source=/usb/target/${nibble}
if [ -f ${source}.tgz ];then
rsync ${source}.tgz $PREFIX/persist/target/${nibble}.tgz
fi
if [ -f ${source}-library.tgz ];then
rsync ${source}-library.tgz $PREFIX/persist/target/${nibble}-library.tgz
fi
rsync -rp /usb/tce/mydata.tgz ${PREFIX}/persist/tce/mydata.tgz
rsync -p /usb/tce/installer.conf ${PREFIX}/persist/tce/installer.conf
umount /usb
rmdir /usb
read -p "Hit <ctl>c to abort copying to unleash_kids"
cd ${PREFIX}/persist
rsync tce/mydata.tgz <EMAIL>:/home/george
md5sum tce/mydata.tgz > tce/mydata.tgz.md5.txt
rsync tce/mydata.tgz.md5.txt <EMAIL>:/home/george
exit 0
if [ -d tce/i686 ];then
rsync tce/i686 <EMAIL>:/home/george
fi
if [ -d tce/x86_64 ];then
rsync tce/x86_64 <EMAIL>:/home/george
fi
# return to from whence we came
cd $CURDIR
<file_sep>#!/bin/ash -x
# this script runs on Tiny Core after target machine is set up, captures it
# Using the USB as shuttle, bring the target machine onto the USB stick
# the following config file communicates between desktop and tiny core
source /mnt/sdb2/tce/installer.conf
# are we fetching a netinst, or a configured XSCE
# hopefully, netinst will never create 3 partitions
umount /dev/sda3
mount /dev/sda3 /mnt/sda3
if [ $? -eq 0 ]; then
if [ -d /mnt/sda3/cache ]; then
umount /dev/sda2
mount "/dev/sda2" "/mnt/sda2"
if [ ! $? -eq 0 ];then
echo "unable to mount /dev/sda2. quitting"
exit 1
fi
SOURCEMNT="/mnt/sda2"
LIBRARYMNT="/mnt/sda3"
mount /dev/sda3 /mnt/sda2/library
else
echo "cannot find /cache on partition 3. Quitting"
exit 1
fi
# check to see if sysprep has been executed on the server
#
if [ ! -h $SOURCEMNT/etc/systemd/system/multi-user.target.wants/finish-install.service ];then
echo
echo "Please remember to run 'sysprep' on target before creating image"
echo
exit 1
fi
else # could not mout sda3, check if this might be a netinst
# reminder: netinst when using EFI requires first partition to be EFI
mount /dev/sda1 /mnt/sda1
if [ $? -eq 0 ];then
if [ -d /mnt/sda1/usr ];then
SOURCEMNT="/mnt/sda1"
LIBRARYMNT=""
fi
fi
mount /dev/sda2 /mnt/sda2
if [ $? -eq 0 ];then
if [ -d /mnt/sda2/usr ];then
SOURCEMNT="/mnt/sda2"
mount /dev/sda1 /mnt/sda2/boot/efi
else
SOURCEMNT="/mnt/sda1"
LIBRARYMNT=""
umount /mnt/sda2
sleep 1
mount /dev/sda2 /mnt/sda1/library
fi
fi
fi
if [ -z $SOURCEMNT ]; then
echo "No /usr directory found"
exit 1
fi
echo
echo "================================================================="
echo
#read -p "What is the achitecture of the hardware \(i686/x86_64\)? " PAYLOAD_ARCH
#case $PAYLOAD_ARCH in
#"i686"|"x86_64")
# ;;
#*)
# echo "Please enter either i686 or x86_64"
# exit 1
# ;;
#esac
PAYLOAD_ARCH="x86_64"
PAYLOAD="netinst"
gitcommit=`grep xsce_commit ${SOURCEMNT}/etc/xsce/xsce.ini|cut -d" " -f3`
echo "the git commit is $gitcommit"
read -p "What should I call this root File System Image? Default=$PAYLOAD: " ans
if [ ! -z $ans ];then
PAYLOAD=$ans
fi
# the following leaves a pointer to the configured tgz image to be incorporated
# into the USB stick, created by this script
mkdir -p /mnt/sdb2/target/${FC_VER}//$PAYLOAD_ARCH/
echo "PAYLOAD=$PAYLOAD" >> /mnt/sdb2/tce/installer.conf
echo "PAYLOAD_ARCH=$PAYLOAD_ARCH" >> /mnt/sdb2/tce/installer.conf
# the presence of rh-ifcg files confuses starting on new hardware, delete
# anything like this should be done in sysprep
# rm -f ${SOURCEMNT}/etc/sysconfig/network-scripts/ifcfg-e* #not lo
# make a list that includes all root level directories, except for library
cd ${SOURCEMNT}
list=
for d in `ls -d1 *`; do
if [ "$d" == "library" ]; then
continue
fi
list="$list $d"
done
# now do the taring
dest=/mnt/sdb2/target/${FC_VER}/${PAYLOAD_ARCH}/${PAYLOAD_ARCH}fc${FC_VER}_${PAYLOAD}.tgz
if [ "$TARLIB" == "true" ];then
tar -czf ${dest} ${list}
else
tar -czf ${dest} *
fi
md5sum ${dest} > ${dest}.md5.txt
if [ ! -z ${LIBRARYMNT} -a "$TARLIB" == "true" ];then
cd ${LIBRARYMNT}
dest=/mnt/sdb2/target/${FC_VER}/${PAYLOAD_ARCH}/${PAYLOAD_ARCH}fc${FC_VER}_${PAYLOAD}-library.tgz
tar -czf ${dest} *
md5sum ${dest} > ${dest}.md5.txt
fi
# get the grub config file
#
cp ${SOURCEMNT}/boot/grub/grub.cfg /mnt/sdb2/tce/
# modify the rootfs device to be sda2
sed -i -e 's|sda1|sda2|' /mnt/sdb2/tce/grub.cfg
sed -i -e 's|/boot||' /mnt/sdb2/tce/grub.cfg
# get the md5 of mydata
#
md5sum /mnt/sdb2/tce/mydata.tgz > /mnt/sdb2/tce/mydata.tgz.md5.txt
# Following is changed to let grub manipulate the grub.conf
# get the OS version
#cd ${SOURCEMNT}/boot/
#KENREL_VERSION=`ls | grep vmlinuz-3 | head -n 1`
#echo "KERNEL_VERSION=${KERNEL_VERSION}" >> /mnt/sdb2/tce/installer.conf
# fetch the actual kernal version number and update grub.cfg
#version=`cat ${SOURCEMNT}/boot/grub/grub.cfg | grep -e vmlinuz.*PAE | sed -e 's:^.*\(3\.[0-9]*\.[0-9]*\-[0-9]*\).*$:\1:'`
#echo "PAYLOAD_KERNEL=$version" > /mnt/sdb2/tce/payload_kernel
ls -l /mnt/sdb2/target/${FC_VER}/${PAYLOAD_ARCH}
<file_sep>#!/bin/bash -x
# runs on TinyCore, gets the rootfs and boot from minimal OS install to stick
ARCH=`uname -p`
VER="20"
# creates a sneakernet between target machine and git repo
# if the user is TC, then we're in tinycore, if root then on desktop
# with intention to copy it to the cloud
if [ ! `id -u` eq 0 ];then
mkdir -p /mnt/sdb1/os/$ARCH
cd /mnt/sda2
tar czf /mnt/sdb1/os/$ARCH/${ARCH}fc${VER}rootfs.tgz *
mount /dev/sda1 /mnt/sda1
cd /mnt/sda1
tar czf /mnt/sdb1/os/$ARCH/boot.tgz *
else
mount /dev/sdb1 /mnt
cp -r /mnt/os/* cache/target/$VER/
fi
| 38c65b4c3be3ffcd0c21bbdcc8274361b9fd9b54 | [
"Python",
"reStructuredText",
"Shell"
]
| 14 | Shell | georgejhunt/installer | b054768fac29952467101b0cbfbb572c0b5c5ca9 | 3946545e4c348c788bbd16658161f69b22138ef3 |
refs/heads/master | <repo_name>wilsonalfonzo/routing<file_sep>/js/forms.js
//OpenLayers.ProxyHost = "proxy.cgi?url=";
var fields;
var trackingLayer;
var wfsurl;
var capaWfs;
var cols;
// WFS DISCAPACITADOS VARIABLES
var fieldsDiscapacitados;
var protDiscapacitados;
var dataDiscapacitados;
var colsDiscapacitados;
// WFS ALBERGUES VARIABLES
var fieldsAlbergues;
var protAlbergues;
var dataAlbergues;
var colsAlbergues;
var gridPanel;
var search;
var gridTitle;
function Forms()
{
var wgs32717 = new OpenLayers.Projection("EPSG:32717");
var wgs900913 = new OpenLayers.Projection("EPSG:900913");
function getWfsLayer(layer1, layer2, range, wfsLayer, fields){
wfsProtocol= new OpenLayers.Protocol.HTTP({
srsName: "EPSG:32717",
strategies: [new OpenLayers.Strategy.BBOX()],
url:"http://localhost:8080/geoserver/chanduy/ows?service=WFS&version=1.0&request=GetFeature&typeName=chanduy:"+layer1+
"&CQL_FILTER=INTERSECTS(geom,collectGeometries(queryCollection('chanduy:"+layer2+"','geom','rango=''"+range+"''')))",
format: new OpenLayers.Format.GML({
extractStyles : true,
extractAttributes : true,
internalProjection: wgs900913,
externalProjection: wgs32717
})
});
wfsData = new GeoExt.data.FeatureStore({
layer: wfsLayer,
proxy: new GeoExt.data.ProtocolProxy({
protocol: wfsProtocol
}),
fields: fields,
autoLoad: true
});
}
/*wmsAlbergues.mergeNewParams({'CQL_FILTER': "DWITHIN(geom, collectGeometries(queryCollection(
'chanduy:casas_comunales', 'geom', 'comunidad = ''" + cbComunas.getRawValue() + "''')), " + cbMetros.getRawValue() + " , meters)"}); */
function getAlberguesComunidad(capa, comuna, radio, wfsLayer, fields){
comuna = encodeURI(comuna);
//comuna = encodeURIComponent(comuna);
wfsProtocol= new OpenLayers.Protocol.HTTP({
srsName: "EPSG:32717",
strategies: [new OpenLayers.Strategy.BBOX()],
//wmsAlbergues.mergeNewParams({'CQL_FILTER': "DWITHIN(geom, collectGeometries(queryCollection('chanduy:casas_comunales', 'geom', 'comunidad = ''" + cbComunas.getRawValue() + "''')), " + cbMetros.getRawValue() + " , meters)"});
url:"http://localhost:8080/geoserver/chanduy/ows?service=WFS&version=1.0&request=GetFeature&typeName=chanduy:entidades&CQL_FILTER=DWITHIN(geom,collectGeometries(queryCollection('chanduy:"+capa+"','geom','comunidad=''"+comuna+"''')),"+radio+",meters)",
format: new OpenLayers.Format.GML({
extractStyles : true,
extractAttributes : true,
internalProjection: wgs900913,
externalProjection: wgs32717
})
});
wfsData = new GeoExt.data.FeatureStore({
layer: wfsLayer,
proxy: new GeoExt.data.ProtocolProxy({
protocol: wfsProtocol
}),
fields: fields,
autoLoad: true
});
}
function consultasTsunami(layer1, layer2, rango, distancia, wfsLayer, fields){
wfsProtocol= new OpenLayers.Protocol.HTTP({
srsName: "EPSG:32717",
strategies: [new OpenLayers.Strategy.BBOX()],
url:"http://localhost:8080/geoserver/chanduy/ows?service=WFS&version=1.0&request=GetFeature&typeName=chanduy:"+layer1+
"&CQL_FILTER=DWITHIN(geom,collectGeometries(queryCollection('chanduy:"+layer2+"','geom','rango=''"+rango+"''','INCLUDE')),"+distancia+",meters)",
format: new OpenLayers.Format.GML({
extractStyles : true,
extractAttributes : true,
internalProjection: wgs900913,
externalProjection: wgs32717
})
});
wfsData = new GeoExt.data.FeatureStore({
layer: wfsLayer,
proxy: new GeoExt.data.ProtocolProxy({
protocol: wfsProtocol
}),
fields: fields,
autoLoad: true
});
}
function capaAlbergues(capa, rango){
protAlbergues= new OpenLayers.Protocol.HTTP({
//url: "http://localhost:8080/geoserver/chanduy/wfs?service=WFS&version=1.0&request=GetFeature&typeName=chanduy:discapacitados&CQL_FILTER=INTERSECTS(geom,collectGeometries(queryCollection('chanduy:amenaza_inundacion','geom','rango=''Bajo''')))&CRS=EPSG:900913",
url:"http://localhost:8080/geoserver/chanduy/wfs?service=WFS&version=1.0&request=GetFeature&typeName=chanduy:entidades&CQL_FILTER=INTERSECTS(geom,collectGeometries(queryCollection('chanduy:"+capa+"','geom','rango=''"+rango+"''')))&CRS=EPSG:900913",
format: new OpenLayers.Format.GML({
extractStyles : true,
extractAttributes : true
})
});
dataAlbergues = new GeoExt.data.FeatureStore({
layer: wfsAlbergues,
proxy: new GeoExt.data.ProtocolProxy({
protocol: protAlbergues
}),
fields: fieldsAlbergues,
autoLoad: true
});
}
/*
Quitar filtros
*/
function quitarFiltros(){
//quitar filtro capa inundacion
delete amenazaInundacion.params.CQL_FILTER;
amenazaInundacion.redraw(true);
//quitar filtro capa remocion de masa
delete amenazaRemocion.params.CQL_FILTER;
amenazaInundacion.redraw(true);
/*delete Remocion.params.CQL_FILTER;
amenazaInundacion.redraw(true);*/
}
var btnLimpiarFiltro_1 = new Ext.Button({
width:75,
text: 'Consultar',
disabled: true
});
//quitar filtros formulario grupos vulnerables por amenaza
var btnQuitarFitrosAmenaza = new Ext.Button({
width:75,
text: 'Quitar filtros',
disabled: true,
handler:function(){
quitarFiltros();
}
});
//quitar filtros formulario grupos vulnerables por distancia
var btnQuitarFitrosDistancia = new Ext.Button({
width:75,
text: 'Quitar filtros',
disabled: true,
handler:function(){
quitarFiltros();
}
});
/*
*/
//FORMULARIOS ZONAS SEGURAS / ENTIDADES
var dataComunidades = new Ext.data.JsonStore({
url:'php/cargarCombos.php',
autoLoad: true,
root:'data',
baseParams: {combo: 'comunidades'},
fields: ['code','nombre']
});
var dataPuntos = new Ext.data.JsonStore({
url:'php/consultas.php',
//autoLoad: true,
root:'puntos',
// baseParams: {combo:'',comuna: ''},
fields: ['x','y']
});
var dataMetros = new Ext.data.JsonStore({
url:'php/cargarCombos.php',
autoLoad: true,
root:'metros',
baseParams: {combo: 'radio'},
fields: ['id','metros']
});
var cbComunas = new Ext.form.ComboBox({
fieldLabel:'Comunidad',
store: dataComunidades,
valueField: 'code',
displayField:'nombre',
typeAhead: true,
triggerAction: 'all',
emptyText: 'Selecione comuna',
width: 110,
editable:false,
listeners:{
select: {
fn:function(combo) {
dataPuntos.load({
params:{
comuna:this.getRawValue()
}
});
cbMetros.setDisabled(false);
}
}
}
});
//seleccionar el primer elemeto del combo
dataPuntos.on('load', function(my, record, options) {
cbOculto.setValue(record[0].get('x'));
});
var cbOculto = new Ext.form.ComboBox({
fieldLabel:'Selecciona',
width: 100,
store: dataPuntos,
valueField: 'x',
displayField: 'y',
mode: 'local',
emptyText: 'Selecione radio',
triggerAction: 'all',
editable:false,
hidden:true
});
var cbMetros = new Ext.form.ComboBox({
fieldLabel:'Distancia (m)',
store: dataMetros,
displayField:'metros',
valueField:'id',
typeAhead: true,
triggerAction: 'all',
emptyText: '(m)',
width: 110,
editable:false,
disabled: true,
listeners:{
select: { fn:function(button)
{
btnConsultarAlbergues.setDisabled(false);
}
}
}
});
var btnConsultarAlbergues = new Ext.Button({
width:75,
text: 'Consultar',
disabled: true,
handler: function() {
//HIDE ALL LAYERS
wfsDiscapacitados.setVisibility(false);
capaWfs = wfsAlbergues;
fields = fieldsAlbergues;
cols = colsAlbergues;
var comuna = cbComunas.getRawValue();
//alert(cbComunas.getValue());
//comuna = comuna.replace(/ /g, '_');
var radio = cbMetros.getRawValue();
var capa = "casas_comunales";
getAlberguesComunidad(capa, comuna, radio, capaWfs, fields)
//gridPanel.store.unbind();
gridPanel.getSelectionModel().unbind();
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(cols));
capaWfs.setVisibility(true);
gridPanel.store.bind(capaWfs);
gridPanel.getSelectionModel().bind(capaWfs);
gridPanel.setTitle('Albergues por Comunidad');
Ext.getCmp('gridPanelAccordion').expand();
/*
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(cols));
gridPanel.store.bind(wfsDiscapacitados);
gridPanel.getSelectionModel().bind(wfsDiscapacitados);
gridPanel.setTitle('Grupos Vulnerables - Riesgo Remoción de Masa');
*/
tipoFiltro = 2;
sectorLayer.removeAllFeatures();
var lon =cbOculto.getRawValue();
var lat = cbOculto.getValue();
var point = new OpenLayers.Geometry.Point (lat, lon).transform(new OpenLayers.Projection("EPSG:32717"),new OpenLayers.Projection("EPSG:900913"));
var circle = OpenLayers.Geometry.Polygon.createRegularPolygon(point, cbMetros.getRawValue(), 30, 0);
var feature = new OpenLayers.Feature.Vector(circle);
sectorLayer.addFeatures([feature]);
sectorLayer.redraw();
map.zoomToExtent(sectorLayer.getDataExtent());
//wmsAlbergues.setVisibility(true);
wmsComunidadesChanduy.setVisibility(true);
// wmsEntidades.redraw();
}
});
this.frmConsultaxDistancia = new Ext.FormPanel({
id: 'frmConsultaRadio',
//frame: true,
labelAlign: 'left',
labelWidth: 75,
buttonAlign: 'right',
border:false,
bodyStyle:'padding:5px 5px 0',
items:[cbComunas, cbOculto, cbMetros],
buttons: [btnConsultarAlbergues, btnLimpiarFiltro_1]
});
//FIN DEL FORMULARIO CONSULTA ENTIDADES X DISTANCIA
//FORMULARIO CONSULTA DISCAPACITADOS POR AMENAZAS
var dataTipos = new Ext.data.ArrayStore ({
id:0,
fields: ['id','tipo'],
data: [
['1', 'AMENAZA'],
['2', 'RIESGO']]//,
//['3', 'VULNERABILIDAD']]
});
var dataEventos = new Ext.data.JsonStore({
url:'php/cargarCombos.php',
autoLoad: true,
root:'fenomenosN',
baseParams: {combo: 'fenomenos'},
fields: ['id','fenomeno']
});
//Almacenamiento para rango de amenazas
var dataRangos = new Ext.data.JsonStore({
url:'php/cargarCombos.php',
//autoLoad: true,
root:'rangos',
baseParams: {combo:'rango'},
fields: ['id','rango']
});
var cbTipos = new Ext.form.ComboBox({
id: 'cbTipos',
fieldLabel:'Tipo',
width: 125,
editable:false,
triggerAction: 'all',
typeAhead: true,
mode: 'local',
store: dataTipos,
valueFileld:'id',
displayField: 'tipo',
listeners:{
select: {
fn:function(combo) {
// var comboCity = Ext.getCmp('cbx');
var txt = cbTipos.getRawValue();
dataEventos.load({ params:{ combo: 'fenomenos' , tipo: '1' } });
if (txt != "Vulnerabilidad")
{
cbEventos.setDisabled(false);
//dataEventos.load({ params:{ combo: 'fenomenos', tipo: txt } });
/*if(txt == "RIESGO")
{
console.log(txt);
dataEventos.load({ params:{ combo: 'fenomenos', tipo: '1' } });
}
else
{
}*/
}
else
{
cbEventos.setDisabled(true);
dataEventos.clearFilter();
dataEventos.filterBy(function (record) {
if (record.get('id') == '1' || record.get('id') == 'TSUNAMI') return record;
});
btnConsultar.setDisabled(false);
//comboRangos.setDisabled(false);
}
}
}
}
});
//Combobox tipo de amenazas
var cbEventos = new Ext.form.ComboBox({
fieldLabel:'Evento',
store: dataEventos,
listeners:{
select: {
fn:function(combo) {
cbRangos.setDisabled(false);
}
}
},
valueField: 'id',
displayField: 'fenomeno',
id:'cbAmenazas',
labelAlign: 'left',
width: 125,
emptyText: 'Tipo Amenaza',
triggerAction: 'all',
editable:false,
disabled:true
});
var cbRangos = new Ext.form.ComboBox({
fieldLabel:'Rango',
width: 125,
store: dataRangos,
displayField: 'rango',
valueField: 'id',
id:'cbRangos',
emptyText: 'Selecione rango',
triggerAction: 'all',
editable:false,
disabled:true,
listeners:{
select: {
fn:function() {
btnConsultar.setDisabled(false);
//alert('vbbb');
}
}}
});
//******COLUMNAS DATAGRID***************
//columnas amenaza inundacion
var colsAmenazaInundacion = [
{ header: 'Id', dataIndex: 'gid' },
{ header: 'va_geo_ind', dataIndex: 'va_geo_ind' },
{ header: 'va_hidr_in', dataIndex: 'va_hidr_in' },
{ header: 'va_gemf_in', dataIndex: 'va_gemf_in' },
{ header: 'va_isoy_fr', dataIndex: 'va_isoy_fr' },
{ header: 'va_pen_ind', dataIndex: 'va_pen_ind' },
{ header: 'suma', dataIndex: 'suma' },
{ header: 'porcentaje', dataIndex: 'porcentaje' },
{ header: 'rango', dataIndex: 'rango' }
];
//columnas amenaza tsunami
var colsAmenazaTsunami = [
{ header: 'Id', dataIndex: 'gid' },
{ header: 'Docver', dataIndex: 'docver' },
{ header: 'Rango', dataIndex: 'rango' }
];
//comunas amenaza remocion de masa
var colsAmenazaRemocion = [
{ header: 'Id', dataIndex: 'gid' },
{ header: 'suma', dataIndex: 'su12345' },
{ header: 'va_sism_fr', dataIndex: 'va_sism_fr' },
{ header: 'va_isoy_fr', dataIndex: 'va_isoy_fr' },
{ header: 'total', dataIndex: 'sumto_7' },
{ header: 'porcentaje', dataIndex: 'porcentaje' },
{ header: 'rango', dataIndex: 'rango' }
];
//columnas riesgo Inundacion
var colsRiesgoInundacion = [
{ header: 'Id', dataIndex: 'gid' },
{ header: 'Docver', dataIndex: 'docver' },
{ header: 'Rango', dataIndex: 'rango' }
];
//columnas riesgo remocion
var colsRiesgoRemocion = [
{ header: 'Id', dataIndex: 'gid' },
{ header: 'Docver', dataIndex: 'docver' },
{ header: 'Rango', dataIndex: 'rango' }
];
//FIN COLUMAS DEL DATAGRID
//DATOS DEL GRID / WFS DISCAPACITADOS
fieldsDiscapacitados =[ {name: 'nombres', type: 'string'},
{name: 'edad', type: 'string'},
{name: 'cedula', type: 'string'},
{name: 'discapacid', type: 'string'},
{name: 'telefonos', type: 'string'},
{name: 'parroquia', type: 'string'},
{name: 'direccion', type: 'string'}
];
colsDiscapacitados = [
{header: "Nombre", dataIndex: "nombres", sortable: true},
{header: "Edad", dataIndex: "edad"},
{header: "Cedula", dataIndex: "cedula", sortable: true},
{header: "Discapacidad", dataIndex: "discapacid"},
{header: "Telefono", dataIndex: "telefonos"},
{header: "Parroquia", dataIndex: "parroquia"},
{header: "Direccion", dataIndex: "direccion"}
];
//DATOS DEL GRID / WFS ALBERGUES
fieldsAlbergues =[ {name: 'descriptio', type: 'string'},
{name: 'tipo', type: 'string'},
{name: 'altitude', type: 'string'},
{name: 'comuna', type: 'comuna'}
];
colsAlbergues = [
{header: "Nombre", dataIndex: "descriptio", sortable: true},
{header: "Tipo", dataIndex: "tipo", sortable: true},
{header: "Elevacion", dataIndex: "altitude"},
{header: "Comuna", dataIndex: "comuna"} ];
var btnConsultar = new Ext.Button({
width:75,
text: 'Consultar',
disabled: true,
handler: function() {
/* var filtro = new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "rango",
value: "Medio"
});*/
//wmsAmenazaInundacion.redraw({force:true});
var tipo = cbTipos.getRawValue();
//HIDE ALL LAYERS
wfsDiscapacitados.setVisibility(false);
wfsAlbergues.setVisibility(false);
var capa1 = groupCapas.getValue().getGroupValue();
if (capa1 == "discapacitados"){
capaWfs = wfsDiscapacitados;
fields = fieldsDiscapacitados;
cols = colsDiscapacitados;
tipoFiltro = 1;
}else{
capaWfs = wfsAlbergues;
fields = fieldsAlbergues;
cols = colsAlbergues;
tipoFiltro = 2;
}
switch (tipo)
{
case "AMENAZA":
gridPanel.getSelectionModel().unbind();
var evento= cbEventos.getRawValue();
amenazaInundacion.setVisibility(false);
amenazaRemocion.setVisibility(false);
wmsRiesgoInundacion.setVisibility(false);
wmsRiesgoRemocion.setVisibility(false);
wmsDiscapacitados.setVisibility(false );
switch (evento)
{
case "INUNDACION":
/*
remove filters amenazaInundacion
*/
delete amenazaRemocion.params.CQL_FILTER;
amenazaRemocion.redraw(true);
amenazaInundacion.mergeNewParams({ 'CQL_FILTER': "rango='" + cbRangos.getRawValue()+"'"});
amenazaInundacion.setVisibility(true);
// NEW FWS LAYER FORM GML
var rango = cbRangos.getRawValue();
var capa2 = "amenaza_inundacion";
//radioGroupVal();
getWfsLayer(capa1, capa2, rango, capaWfs, fields);
// RECONFIGURE DATAGRID
capaWfs.setVisibility(true);
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(cols));
// alert("123");
// dataGrid.reconfigure(storeAmenazaInundacion,
//new Ext.grid.ColumnModel(colsAmenazaInundacion));
capaWfs.setVisibility(true);
gridPanel.store.bind(capaWfs);
//alert('here');
search.store = capaWfs;
//wfsData.load({params:{start: 0, limit: 100}});
wfsData.load({params:{start:0, limit:20, forumId: 4}});
// search.onTriggerSearch();
gridPanel.getSelectionModel().bind(capaWfs);
gridPanel.setTitle('Grupos Vulnerables - Amenaza de Inundación');
Ext.getCmp('gridPanelAccordion').expand();
break;
case "TSUNAMI":
break;
case "REMOCION DE MASA":
/*
remove filters amenazaInundacion
*/
delete amenazaInundacion.params.CQL_FILTER;
amenazaInundacion.redraw(true);
amenazaRemocion.mergeNewParams({ 'CQL_FILTER': "rango='" + cbRangos.getRawValue()+"'"});
amenazaRemocion.setVisibility(true);
// NEW FWS LAYER FORM GML
var rango = cbRangos.getRawValue();
var capa2 = "amenaza_remocion_masa";
getWfsLayer(capa1, capa2, rango, capaWfs, fields);
// RECONFIGURE DATAGRID
capaWfs.setVisibility(true);
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(cols));
gridPanel.store.bind(capaWfs);
gridPanel.getSelectionModel().bind(capaWfs);
gridPanel.setTitle('Grupos Vulnerables - Amenaza Remoción de Masa');
Ext.getCmp('gridPanelAccordion').expand();
break;
}
break;
case "RIESGO":
gridPanel.getSelectionModel().unbind();
var evento= cbEventos.getRawValue();
amenazaInundacion.setVisibility(false);
amenazaRemocion.setVisibility(false);
wmsRiesgoInundacion.setVisibility(false);
wmsRiesgoRemocion.setVisibility(false);
wmsDiscapacitados.setVisibility(false );
//myRango= comboRangos.getRawValue();
//dataGrid.getSelectionModel();
//dataGrid.getSelectionModel().unbind();
switch (evento)
{
//var sm = dataGrid.getSelectionModel();
case "INUNDACION":
// wmsDiscapacitados.mergeNewParams({'CQL_FILTER': "INTERSECTS(geom, collectGeometries(queryCollection('chanduy:', 'geom','rango = ''"+cbRangos.getRawValue()+"''')))"});
wmsRiesgoInundacion.mergeNewParams({ 'CQL_FILTER': "rango='" + cbRangos.getRawValue()+"'"});
//wmsDiscapacitados.setVisibility(true);
wmsRiesgoInundacion.setVisibility(true);
// NEW FWS LAYER FORM GML
var rango = cbRangos.getRawValue();
//var capa1 = groupCapas.getValue().getGroupValue();
var capa2 = "riesgo_inundacion";
getWfsLayer(capa1, capa2, rango, capaWfs, fields);
// RECONFIGURE DATAGRID
capaWfs.setVisibility(true);
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(cols));
gridPanel.store.bind(capaWfs);
gridPanel.getSelectionModel().bind(capaWfs);
gridPanel.setTitle('Grupos Vulnerables - Riesgo Inundación');
Ext.getCmp('gridPanelAccordion').expand();
break;
case "TSUNAMI":
break;
case "REMOCION DE MASA":
//wmsDiscapacitados.mergeNewParams({'CQL_FILTER': "INTERSECTS(geom, collectGeometries(queryCollection('chanduy:riesgo_remocion_masa', 'geom','rango = ''"+cbRangos.getRawValue()+"''')))"});
wmsRiesgoRemocion.mergeNewParams({ 'CQL_FILTER': "rango='" + cbRangos.getRawValue()+"'"});
//wmsDiscapacitados.setVisibility(true);
wmsRiesgoRemocion.setVisibility(true);
// NEW FWS LAYER FORM GML
var rango = cbRangos.getRawValue();
//var capa1 = groupCapas.getValue().getGroupValue();
var capa2 = "riesgo_remocion_masa";
getWfsLayer(capa1, capa2, rango, capaWfs, fields);
// RECONFIGURE DATAGRID
capaWfs.setVisibility(true);
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(cols));
gridPanel.store.bind(wfsDiscapacitados);
gridPanel.getSelectionModel().bind(wfsDiscapacitados);
gridPanel.setTitle('Grupos Vulnerables - Riesgo Remoción de Masa');
Ext.getCmp('gridPanelAccordion').expand();
break;
}
}
}
});
var groupCapas = new Ext.form.RadioGroup
(
{
fieldLabel: 'Capa',
id:"capaConsulta1",
columns : 1,
name:'capaConsulta1',
items: [{
boxLabel : "Discapacitados" ,
name: 'capaConsulta',
inputValue:'discapacitados',
id:'capaDiscapacitados',
checked: true
},{
boxLabel: "Albergues",
name: 'capaConsulta',
inputValue:'entidades',
id: 'capaAlbergues'
}]
}
);
this.frmDiscapacitados = new Ext.FormPanel({
id: 'frmDiscapacitados',
labelAlign: 'left',
labelWidth: 60,
buttonAlign: 'right',
width: 185,
border: false,
//defaultType: 'textfield',
//layout: 'column',
items:[groupCapas, cbTipos, cbEventos, cbRangos, btnConsultar]
});
/*
* Funciones y controles para
* formulario de distancia
*/
//TSUNAMI POR DISCAPACITADOS
var cbRangos2 = new Ext.form.ComboBox({
fieldLabel:'Rango',
width: 100,
store: dataRangos,
displayField: 'rango',
valueField: 'id',
id:'cbRangos2',
emptyText: 'Selecione rango',
triggerAction: 'all',
editable:false,
disabled:true,
listeners:{
select: {
fn:function() {
btnConsultar.setDisabled(false);
}
}}
});
var txtMetros = new Ext.form.TextField({
fieldLabel: 'Distancia (m)',
width:100,
name: 'distancia',
listeners:{
change: {
fn:function() {
var string = this.getValue();
if (string != ''){
cbRangos2.setDisabled(false);
}else{
cbRangos2.setDisabled(true);
}
}
}
}
});
//Combobox tipo de amenazas
var cbxAmenazas = new Ext.form.ComboBox({
fieldLabel:'Evento',
store: dataEventos,
listeners:{
select: {
fn:function(combo) {
//cbRangos.setDisabled(false);
}
}
},
valueField: 'id',
displayField: 'fenomeno',
id:'cbxAmenazas',
labelAlign: 'left',
width: 100,
emptyText: 'Tipo Amenaza',
triggerAction: 'all',
editable:false
//disabled:true
});
var btnTsunami = new Ext.Button({
width:75,
text: 'Consultar',
//disabled: true,
handler: function() {
/*alert(mostrarCapa);
if (mostrarCapa != "" && mostrarCapa !== undefined){
mostrarCapa.setVisibility(false);
}*/
tipoFiltro = 1;
amenazaTsunami.setVisibility(false);
amenazaInundacion.setVisibility(false);
amenazaRemocion.setVisibility(false);
distancia = txtMetros.getValue();
//alert (distancia);
//consultasTsunami(distancia,wfsDiscapacitados,fieldsDiscapacitados );
// var rango = Encoder.EncodeType = cbRangos2.getRawValue();
//var encoded = Encoder.htmlEncode(document.getElementById('cbRangos2'));
var rango = cbRangos2.getRawValue();
var layer2 = "";
var mostrarCapa = "";
if (cbxAmenazas.getRawValue() == 'TSUNAMI'){
layer2 = 'amenaza_tsunami';
mostrarCapa = amenazaTsunami;
gridTitle = gridPanel.setTitle('Grupos Vulnerables - Amenaza por Tsunami');
}else if (cbxAmenazas.getRawValue() == 'INUNDACION'){
layer2 = 'amenaza_inundacion';
mostrarCapa = amenazaInundacion;
gridTitle = gridPanel.setTitle('Grupos Vulnerables - Amenaza por Inundación');
}else{
layer2 = 'amenaza_remocion_masa';
mostrarCapa = amenazaRemocion;
gridTitle = gridPanel.setTitle('Grupos Vulnerables - Amenaza por Remoción de Masa');
}
//var rango = String.Format(url, Server.UrlEncode());
consultasTsunami("discapacitados",layer2, rango, distancia,wfsDiscapacitados,fieldsDiscapacitados );
gridPanel.reconfigure(wfsData, new Ext.grid.ColumnModel(colsDiscapacitados));
gridPanel.store.bind(wfsDiscapacitados);
gridPanel.getSelectionModel().bind(wfsDiscapacitados);
//amenazaTsunami.setVisibility(true);
mostrarCapa.setVisibility(true);
Ext.getCmp('gridPanelAccordion').expand();
tipoFiltro = 1;
}
});
//IMPRIMIR GRID
var btnPrintGrid = new Ext.Button({
text : 'Imprimir Tabla',
handler: function() {
Ext.ux.Printer.print(Ext.getCmp('grid'));
},
margins: '20 0 0 0'
});
this.frmTsunami = new Ext.FormPanel({
id: 'frmTsunami',
labelAlign: 'left',
labelWidth: 75,
buttonAlign: 'right',
width: 185,
border: false,
//defaultType: 'textfield',
//layout: 'column',
items:[txtMetros, cbxAmenazas, cbRangos2, btnTsunami]
});
/*
* C'ALCULO DE RUTAS
* GRID
* LABEL
* WINDOW
*/
//-->1
dataRuta = new Ext.data.JsonStore({
url:'php/pgrouting.php',
autoLoad: true,
root:'ruta',
autoload:true,
//baseParams: {combo: 'radio'},
fields: ['distancia','descripcion','velocidad','tiempo_min']
});
//-->2
colsRuta = [
{ width:50, header: 'Velocidad promedio', dataIndex: 'descripcion' },
{ width:25, header: 'Km/h', dataIndex: 'velocidad' },
{ width: 50, header: 'Tiempo Aprox. min', dataIndex: 'tiempo_min' }
];
lbDistancia = new Ext.form.Label({
id: 'lbDistancia',
text : 'Category ',
width:400,
height:200,
style: 'font-weight:bold;',
anchor:'100%'
});
gridRuta = new Ext.grid.GridPanel({
id: "grid",
width:400,
height:150,
viewConfig: {forceFit: true},
store: dataRuta,
columns: colsRuta
});
this.frmRuta = new Ext.FormPanel({
id: 'frmRuta',
labelAlign: 'left',
renderTo: win,
labelWidth: 400,
buttonAlign: 'right',
width: 400,
border: false,
//defaultType: 'textfield',
//layout: 'column',
items:[lbDistancia, gridRuta]
});
win = new Ext.Window({
title:'Cálculo de ruta',
closeAction: 'hide',
//renderTo: Ext.getBody(),
// autoShow: true,
//modal: true,
layout:'fit',
width:400,
height:180,
closable:true,
//collapsible: true,
items:[this.frmRuta]
});
/*
search box
*/
txtSearch = new Ext.form.TextField({
fieldLabel: 'test',
width:500,
name: 'txtSearch',
enableKeyEvents: true,
listeners:{
keyup: {
fn:function(form, e) {
console.log(tipo);
var searchValue = this.getValue();
if(searchValue != ""){
var testStore = gridPanel.getStore();
var rows = testStore.getCount();
console.log(rows);
if(rows > 0){
if (tipoFiltro == 1){
testStore.filter([{property:'nombres', value:searchValue}]);
}else{
testStore.filter([{property:'descriptio', value:searchValue}]);
}
}
/*{property:'nombres', value:searchValue} *///]) ;
}else{
gridPanel.store.clearFilter();
}
}
}
}
});
/*
message box
*/
}<file_sep>/index.php
<html>
<head>
<link rel="stylesheet" href="OpenLayers/theme/default/style.css" type="text/css">
<link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="GeoExt/resources/css/geoext-all.css" />
<link rel="stylesheet" type="text/css" href="style/visor.css" />
<style type="text/css">
.legend {
padding-left: 18px;
}
.x-tree-node-el {
border-bottom: 1px solid #ddd;
padding-bottom: 3px;
}
.x-tree-ec-icon {
width: 3px;
}
.gx-tree-layer-icon {
display: none;
}
</style>
</head>
<body>
<?php
error_reporting(0);
@session_start();
//print_r($_SESSION);
?>
<div>
<!-- <div id="gxmap"></div>
<div id="mappanel"></div>-->
<div id="desc"></div>
<div id="desc1"></div>
</div>
<script src="OpenLayers/OpenLayers.js" type="text/javascript"></script>
<script src="ext/adapter/ext/ext-base.js" type="text/javascript"></script>
<script src="ext/ext-all.js" type="text/javascript"></script>
<script src="GeoExt/script/GeoExt.js" type="text/javascript"></script>
<script src="DrawPoints.js" type="text/javascript"></script>
<script src="proj4js/lib/proj4js-compressed.js" type="text/javascript"></script>
<script src="proj4js/lib/defs/EPSG32717.js" type="text/javascript"></script>
<script type="text/javascript" src="Geoext/lib/GeoExt.js"></script>
<script src="mapa.js?t=<?php echo mktime(date('H'), date('i'), date('s')); ?>"></script>
<script src="js/Ext.ux.Printer.js"></script>
<script src="js/SearchField.js"></script>
<script src="js/Ajax.js"></script>
<script src="js/layers.js"></script>
<script src="js/forms.js"></script>
<script src="js/toolbar.js"></script>
<script type="text/javascript">
var session = "<?php echo $_SESSION['INCYT_UPSE_User'] ?>";
//alert(session);
</script>
</body>
</html>
<file_sep>/js/toolbar.js
//clase toolbar
var epsg_32717 = new OpenLayers.Projection("EPSG:32717");
var epsg_900913 = new OpenLayers.Projection("EPSG:900913");
var dist;
var vector;
this.lbl;
function Toolbar(){
Ext.QuickTips.init();
//BARRA DE HERRAMIENTAS
Ext.QuickTips.ini
//ZOOM BOX
var control_zoom = new OpenLayers.Control.ZoomBox();
this.actionZoom = new GeoExt.Action({
control: control_zoom,
map:map,
enableToggle:true,
tooltip: "Zoom ventana",
iconCls: "zoomsq"
});
//ZOOM IN
var control_zoomIn =new OpenLayers.Control.ZoomIn({title:"Aumentar zoom"});
this.actionZoomIn = new GeoExt.Action({
control: control_zoomIn,
map:map,
enableToggle:false,
tooltip: "Aumentar zoom",
iconCls: "zoomin"
});
//ZOOM OUT
var control_zoomOut =new OpenLayers.Control.ZoomOut({title:"Disminuir zoom"});
this.actionZoomOut = new GeoExt.Action({
control: control_zoomOut,
map:map,
enableToggle:false,
tooltip: "Disminuir zoom",
iconCls: "zoomout"
});
//ZOOM FULL
var control_zoomFull = new OpenLayers.Control.ZoomToMaxExtent({title:"Extensión máxima"});
this.actionZoomFull = new GeoExt.Action({
control: control_zoomFull,
map:map,
iconCls: "zoomfull",
tooltip: "Extensión máxima"
});
//HISTORIAL PREVIO
this.actionhistPrev = new GeoExt.Action({
control: hist.previous,
disabled: true,
map:map,
toggleGroup: "historial",
tooltip: "Previo",
iconCls: "previous"
});
//HISTORIAL SIGUIENTE
this.actionhistNext = new GeoExt.Action({
control: hist.next,
disabled: true,
map:map,
toggleGroup: "historial",
iconCls: "next",
tooltip: "Siguiente"
});
//PAN
//var control_pan =new OpenLayers.Control.Pan();
var control_pan = new OpenLayers.Control.Navigation()
this.actionPan = new GeoExt.Action({
control: control_pan,
map:map,
toggleGroup: "draw",
allowDepress: false,
//enableToggle:true,
pressed: true,
tooltip: "Pan",
//qtip: 'Imprimir Grid',
iconCls: "pan"
});
//Mediciones lineales
var medl= new OpenLayers.Control.Measure(
OpenLayers.Handler.Path, //Tipo de geometría para medir: linea
{persist: true, //Mantener la geometría hasta nueva medición o cambio de control
displayClass:'olControlMeasurePath'}); //Estilo de diseño (CSS) del control
//Define eventos a controlar sobre el control
medl.events.on({
"measure": mostrarMediciones //Cuando acaba de medir llama a la función mostrarMediciones
});
this.actionMedl = new GeoExt.Action({
control: medl,
map:map,
toggleGroup: "draw",
//enableToggle:true,
tooltip: "mesurar longitud",
iconCls: "medl"
});
//Print
var winPrint;
var btnPrint = new OpenLayers.Control.Button({
trigger: function(){
window.print();
}
});
this.actionPrint = new GeoExt.Action({
control: btnPrint,
tooltip: "Imprimir mapa",
iconCls: "print"
});
//Mediciones de áreas
var meda= new OpenLayers.Control.Measure(
OpenLayers.Handler.Polygon, //Tipo de geometría para medir: polígono
{persist: true, //Mantener la geometría hasta nueva medición o cambio de control
displayClass:'olControlMeasurePolygon'}); //Estilo de diseño (CSS) del control
//Define eventos a controlar sobre el control
meda.events.on({
"measure": mostrarMediciones //Cuando acaba de medir llama a la función mostrarMediciones
/*"measurepartial": mostrarMediciones*/}); //Durante las medidas parciales llama a la función mostrarMediciones
this.actionMeda = new GeoExt.Action({
control: meda,
map:map,
toggleGroup: "draw",
//enableToggle:true,
tooltip: "Medir área",
iconCls: "meda"
});
function crearPopUP(event){
var popUp = new GeoExt.Popup({
title: "Información",
location: event.xy ,
width:200,
map:map,
html: event.text,
autoDestroy:true,
autoScroll:true
});
popUp.show();
};
//Función para dar tratar los eventos de los controles de medidas (lineales y áreas)
function mostrarMediciones(event) { //La variable event es el objeto evento
if(event.order == 1) { //Si el evento lo ha disparado la medición lineal
crearPopupMed(event, "Longitud: " + event.measure.toFixed(1) + " " + event.units); //Escribe resultado)
} else { //Si medición de superficie
crearPopupMed(event, "Área: " + event.measure.toFixed(1) + " " + event.units + "<sup>2</" + "sup>" );
}
};
function crearPopupMed(event, resultado){
var popUp = new GeoExt.Popup({
title: "Medida",
location:event.xy,
width:200,
height:100,
map:map,
html: resultado,
autoDestroy:true,
autoScroll:true
});
popUp.show();
};
//CALCULO DE RUTA MAS CORTA
//Anade puntos para obtener ruta optima
var puntos= new OpenLayers.Control.DrawFeature(vector,
OpenLayers.Handler.Point, //Tipo de geometría para medir: polígono
{//persist: true, //Mantener la geometría hasta nueva medición o cambio de control
displayClass:'olControlDrawFeaturePoint'});
puntos.events.on({
featureadded: function() {
pgrouting(puntos);
}
});
this.actionPuntos = new GeoExt.Action({
control: puntos,
map:map,
enableToggle:true,
// pressed: this.activated ? false : true,
tooltip: "Calcular ruta",
iconCls: "routing",
group: "ruta",
listeners: {
toggle: function (btn, pressed)
{
if (pressed)
{
wmsVias.setVisibility(true);
}
else
{
wmsVias.setVisibility(false);
}
}
}
});
//CREAR VENTANA CON DATOS DE RUTA
//-->1
//FUNCION PGROUTING
function pgrouting(layer) {
if ((vector.features.length % 2)==0) {
// transform the two geometries from EPSG:900913 to EPSG:32717
var startpoint = vector.features[vector.features.length-2].geometry.clone();
var finalpoint = vector.features[vector.features.length-1].geometry.clone();
startpoint.transform(epsg_900913, epsg_32717);
finalpoint.transform(epsg_900913, epsg_32717);
//valores x,y enviados al servidor
viewparams = [
'x1:' + startpoint.x + ';' + 'y1:' + startpoint.y + ';' +
'x2:' + finalpoint.x + ';' + 'y2:' + finalpoint.y
];
dataRuta.load({
params:{
x1: startpoint.x, y1: startpoint.y, x2: finalpoint.x, y2: finalpoint.y
}
});
vector.removeAllFeatures();
//calcula ruta mas corta con pgrouting
wmsRuta.mergeNewParams( { viewparams: viewparams });
//wmsRuta.setVisibility(true);
var cbOculto = new Ext.form.ComboBox({
fieldLabel:'Rango',
width: 125,
store:dataRuta, //storePgrouting,
displayField: 'distancia',
mode: 'local',
valueField: 'distancia',
emptyText: 'Selecione rango',
triggerAction: 'all'//,
});
dataRuta.on('load', function(my, record, options) {
cbOculto.setValue(record[0].get('distancia'));
dist="";
dist = record[0].get('distancia');
console.log(dist);
if ((dist !=='null') && (dist > 0)){
lbDistancia.setText('Distancia total : ' + dist + 'm');
win.show();
}else{
Ext.MessageBox.alert('Información', 'No se pudo calcular la ruta...!');
}
});
}
};
//Eliminar Rutas
function eliminarRutas()
{
vector.removeAllFeatures();
wmsRuta.mergeNewParams( { viewparams: '' });
/* if (pgruta.length)
{
for (var i = 0; i < map.layers.length+1; i++)
{
if (map.layers[i].name == "pgrouting")
{
alert(map.layers[i].name);
map.removeLayer(map.layers[i]);
}
}
}*/
};
this.actionEliminaRuta = new Ext.Action({
handler : function() {
eliminarRutas();
},
tooltip: "Eliminar ruta",
iconCls: "removerouting",
group: "ruta",
});
var actionPopUp = function(e) {
OpenLayers.Console.log(e.type, e.feature.id);
var myWfsLayer = oLayers.wfsAmenazaTsunami;//mapa.getLayersByName("WFS")[0];
var myFeature = myWfsLayer.getFeatureById(e.feature.id);
if (myFeature){
// alert(myFeature.toSource());
//alert(e.feature.attributes.toSource())
//var attr =myFeature.attributes;
}
var feature = e.feature.attributes;
alert(myWfsLayer);
};
function crearPopUP(event){
var popUp = new GeoExt.Popup({
title: "Información",
location: event.xy ,
width:300,
map:map,
html: event.text,
collapsable:true,
autoDestroy:true,
autoScroll:true
});
popUp.show();
// alert (viewparams);
};
function crearPopupMed(event, resultado){
var popUp = new GeoExt.Popup({
title: "mesure",
location:event.xy,
width:200,
height:100,
map:map,
html: resultado,
autoDestroy:true,
autoScroll:true
});
popUp.show();
};
// SelectFeature control, a "toggle" control
this.actionIdentif = new GeoExt.Action({
text: "Identificació",
control: new OpenLayers.Control.SelectFeature(oLayers.layerAmenazaTsunami, {
type: OpenLayers.Control.TYPE_TOGGLE,
clickout: true, hover: false, //
eventListeners: {
// beforefeaturehighlighted: actionPopUp,
featurehighlighted: actionPopUp
// featureunhighlighted: actionPopUp
}
}),
map: map,
// button options
enableToggle: true,
tooltip: "Identificació"
});
function getCapasActivas(map){
//App.vector.setVisibility(false);
var layersActivos=map.getLayersBy('visibility',true);
//App.vector.setVisibility(true);
if (layersActivos.length < 2){
alert("Necesita elegir al menos una capa para poder Consultar");
// App.vector.destroyFeatures();
return "error"
}else{
// var typename="";
// for (var indic=0; indic < layersActivos.length; indic++){
// if (layersActivos[indic].params!= undefined && layersActivos[indic].isBaseLayer !== true){
//typename=typename + layersActivos[indic].name +",";
//}
//}
//t/ypename = typename.substring(0,typename.length -1);
//return typename;
}// del else
}
//IDENTIFICACIÓN
var identificar = new OpenLayers.Control.WMSGetFeatureInfo({
hover:false,
drillDown:false,
maxFeatures:10,
url: "http://localhost:8080/geoserver/chanduy/wms",
layerUrls:"http://localhost:8080/geoserver/gwc",//[ /*oLayers.layerDistricte,*/oLayers.wmsZonasSeguras],
//layer: "pgrouting",
queryVisible: true,
//vendorParams: viewparams, // map: oParams.mapfile_tematic },
eventListeners:{
getfeatureinfo: function(event){
//getCapasActivas: function(map){
// var layersActivos=map.getLayersBy('visibility',true);
//alert (layersActivos.length);
//if (layersActivos.length < 3){
//alert("Necesita elegir al menos una capa para poder Consultar");
// App.vector.destroyFeatures();
// return "error"
crearPopUP(event);
}
}
});
this.actionIdentify = new GeoExt.Action({
control: identificar,
map:map,
enableToggle:true,
tooltip: "Identificar",
iconCls: "identify"
});
var button = new OpenLayers.Control.Button({
displayClass: "callejero", trigger: function(){
//selectControl.activate();
selectCtrl.activate();
//window.open("calles.php?lstCarrers=" , "ventana1" , "width=600,height=300,scrollbars=yes") ;
}
});
function mostrarMediciones(event) { //La variable event es el objeto evento
if(event.order == 1) { //Si el evento lo ha disparado la medición lineal
crearPopupMed(event, "Mesura: " + event.measure.toFixed(1) + " " + event.units); //Escribe resultado)
} else { //Si medición de superficie
crearPopupMed(event, "Àrea: " + event.measure.toFixed(1) + " " + event.units + "<sup>2</" + "sup>" );
}
};
}
<file_sep>/php/logout.php
<?php
@session_start();
if(isset($_SESSION['INCYT_UPSE_User']))
{
echo '1';
unset($_SESSION['INCYT_UPSE_User']);
}
//session_unset();
//session_destroy();
?><file_sep>/js/logout.js
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1");// 30 min
}
filterChain.doFilter(request, response);
}
}<file_sep>/php/db.php
<?php
$strcn = "host='localhost' port='5432' dbname='staelena' user='postgres' password='<PASSWORD>'";
$conn = pg_connect($strcn);
?><file_sep>/js/layers.js
//var wmsLimiteProvincial;
var renderer;
var protocoloRiesgoInundacion;
var storeAmenazaTsunami;
var storeAmenazaInundacion;
var storeAmenazaRemocion;
var storeRiesgoInundacion;
var storeRiesgoRemocion;
var wmsRuta;
var wmsLimiteProvincial;
var wmsVias;
var wmsParroquias;
var wmsAmenazaInundacion;
var wmsZonasSeguras;
var wmsAmenazaRemocion;
var wmsAmenazaTsunami;
var wmsRiesgoRemocion;
var wmsRiesgoInundacion;
var wmsComunidadesChanduy;
var wmsCasasComunales;
var wmsAlbergues;
var wmsDiscapacitados;
var wfsPrueba;
var wmsSqlInundacion;
var wfsAmenazaInundacion;
var wfsAmenazaRemocion;
var wfsAmenazaTsunami;
var wfsRiesgoInundacion;
var wfsRiesgoRemocion;
var tracking;
var greenFlag;
var sectorLayer;
//var trackingLayer;
//var layerAmenInundacion;
function Layers(){
// this.layers = new OpenLayers.Layer.OSM("Simple OSM Map");
this.LayerBase = new OpenLayers.Layer.OSM("Simple OSM Map");/*
var layerList =[{
text: 'Background Layers',
leaf: false,
expanded: true,
children: [{
nodeType: 'gx_layer',
layer: oms,
checked: false
}]
}
*/
greenFlag = OpenLayers.Util.applyDefaults(
{externalGraphic: "img/${greenFlag}.png", pointRadius: 20},
OpenLayers.Feature.Vector.style["default"]);
var styleMap = new OpenLayers.StyleMap({"default": greenFlag, "select": {pointRadius: 30}});
//SQL AMENAZA INUNDACION
wmsSqlInundacion = new OpenLayers.Layer.WMS("WMS SQL Inundacion",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'vistaAmenInundacion',
layers: 'chanduy:vista_amenaza_inundacion',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WFS LIMTE PROVINCIAL
wmsLimiteProvincial = new OpenLayers.Layer.WMS("Limite Provincial",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'vistaAmenazaInundacion',
layers: 'chanduy:limite_provincial',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS PARROQUIAS
wmsParroquias = new OpenLayers.Layer.WMS("Parroquias",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'parroquias',
layers: 'chanduy:parroquias',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WFS AMENAZA INUNDACION
/*wmsAmenazaInundacion = new OpenLayers.Layer.WMS("WMS Amenaza Inundacion",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'vistaAmenazaInundacion',
layers: 'chanduy:amenaza_inundacion',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
}); */
//WMS AMENAZA REMOSION DE MASA
amenazaRemocion = new OpenLayers.Layer.WMS("Amenaza Remoción de Masa",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'amenazaRemocion',
layers: 'chanduy:amenaza_remocion_masa',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WFS AMENAZA INUNDACION
amenazaInundacion = new OpenLayers.Layer.WMS("Amenaza Inundacion",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'amenazaInundacion',
layers: 'chanduy:amenaza_inundacion',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS AMENAZA TSUNAMI
amenazaTsunami = new OpenLayers.Layer.WMS("Amenaza Tsunami",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'amenazaTsunami',
layers: 'chanduy:amenaza_tsunami',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS AMENAZA REMOSION DE MASA
/* wmsAmenazaRemocion = new OpenLayers.Layer.WMS("Amenaza Remosión de Masa",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'vistaAmenRemocion',
layers: 'chanduy:amenaza_remocion_masa',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
}); */
//WMS RIESGO REMOSION
wmsRiesgoRemocion = new OpenLayers.Layer.WMS("WMS Riesgo Remocion Masa",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'vistaAmenRemocion',
layers: 'chanduy:riesgo_remocion_masa',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS RIESGO INUNDACION
wmsRiesgoInundacion = new OpenLayers.Layer.WMS("WMS Riesgo Inundacion",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'vistaAmenRemocion',
layers: 'chanduy:riesgo_inundacion',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS COMUNIDADES CHANDUY
wmsComunidadesChanduy = new OpenLayers.Layer.WMS("Comunidades Chanduy",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'comunidadesChanduy',
layers: 'chanduy:comunaschanduy',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS CASAS COMUNALES
wmsCasasComunales = new OpenLayers.Layer.WMS("Casas Comunales",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'comunidadesChanduy',
layers: 'chanduy:casas_comunales',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS ENTIDADES
wmsAlbergues = new OpenLayers.Layer.WMS("Albergues",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'entidadesChanduy',
layers: 'chanduy:entidades',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS ZONAS SEGURA
wmsZonasSeguras = new OpenLayers.Layer.WMS("Zonas Seguras",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'zonasSeguras',
layers: 'chanduy:zonas_seguras',
version: '1.3.0',
format: 'image/png',
transparent: true,
style:styleMap
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS ENTIDADES
wmsDiscapacitados = new OpenLayers.Layer.WMS("Discapacitados",
"http://localhost:8080/geoserver/chanduy/wms",
{id: 'entidadesChanduy',
layers: 'chanduy:discapacitados',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS RUTA MAS CORTA
wmsRuta = new OpenLayers.Layer.WMS("pgrouting",
"http://localhost:8080/geoserver/chanduy/wms",
{
layers: 'chanduy:pgrouting',
version: '1.3.0',
format: 'image/png',
// viewparams:'x1:543603.0981478957;y1:9735391.646607857;x2:543906.9671379762;y2:9730235.07913521',
//viewparams: 'x1:545738.9760560881;y1:9729779.554061841;x2:550012.660187293;y2:9725835.095122024',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
//WMS VIAS
wmsVias= new OpenLayers.Layer.WMS("Vias",
"http://localhost:8080/geoserver/chanduy/wms",
{id:'vias',
layers: 'chanduy:vias',
version: '1.3.0',
format: 'image/png',
transparent: true
},
{
cisBaseLayer: false,
projection: 'EPSG:900913'
});
// trackingLayer = new OpenLayers.Layer.Vector("demo");
//******* DECLARACION DE PROTOCOLOS **********//
//Protocolo Amenaza Inundacion
var protocoloAmenazaInundacion= new OpenLayers.Protocol.WFS({
url:"http://localhost:8080/geoserver/chanduy/wfs",
version: "1.1.0",
//id:'amenInundacion',
featureType: "amenaza_inundacion",
featureNS: "http://www.chanduy.org"
});
var protocoloAmenazaRemocion= new OpenLayers.Protocol.WFS({
url:"http://localhost:8080/geoserver/chanduy/wfs",
version: "1.1.0",
//id:'amenInundacion',
featureType: "amenaza_remocion_masa",
featureNS: "http://www.chanduy.org"
});
var protocoloAmenazaTsunami= new OpenLayers.Protocol.WFS({
url:"http://localhost:8080/geoserver/chanduy/wfs",
version: "1.1.0",
//id:'amenInundacion',
featureType: "amenaza_tsunami",
featureNS: "http://www.chanduy.org"
});
//Protocolo Amenaza Inundacion
var protocoloRiesgoInundacion= new OpenLayers.Protocol.WFS({
url:"http://localhost:8080/geoserver/chanduy/wfs",
version: "1.1.0",
//id:'amenInundacion',
featureType: "riesgo_inundacion",
featureNS: "http://www.chanduy.org"
});
var protocoloRiesgoRemocion= new OpenLayers.Protocol.WFS({
url:"http://localhost:8080/geoserver/chanduy/wfs",
version: "1.1.0",
//id:'amenInundacion',
featureType: "riesgo_remocion_masa",
featureNS: "http://www.chanduy.org"
});
//*************** REGION WFS *******************
//**********************************************
//WFS AMENAZA INUNDACION
wfsAmenazaInundacion= new OpenLayers.Layer.Vector("WFS Amenaza Inundacion",
{
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: protocoloAmenazaInundacion
});
//WFS AMENAZA REMOSION
wfsAmenazaRemocion= new OpenLayers.Layer.Vector("WFS Amenaza Remocion",
{
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: protocoloAmenazaRemocion/*,
filter:new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "rango",
value: ""})*/
});
//WFS AMENAZA TSUNAMI
wfsAmenazaTsunami= new OpenLayers.Layer.Vector("WFS Amenaza Tsunami",
{
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: protocoloAmenazaTsunami
});
//WFS RIESGO INUNDACION
wfsRiesgoInundacion= new OpenLayers.Layer.Vector("WFS Riesgo Inundacion",
{
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: protocoloRiesgoInundacion
});
//WFS RIESGO REMOSION
wfsRiesgoRemocion= new OpenLayers.Layer.Vector("WFS Riesgo Remocion",
{
strategies: [new OpenLayers.Strategy.BBOX()],
protocol: protocoloRiesgoRemocion/*,
filter:new OpenLayers.Filter.Comparison({
type: OpenLayers.Filter.Comparison.EQUAL_TO,
property: "rango",
value: ""})*/
});
//WFS CONSULTAS
wfsDiscapacitados = new OpenLayers.Layer.Vector("wfsDiscapacitados",{
styleMap:new OpenLayers.StyleMap({
"default":new OpenLayers.Style(OpenLayers.Util.applyDefaults({
externalGraphic:"img/discapacidad-default.png",
graphicOpacity:1,
name: "discapacitados",
pointRadius:10
}, OpenLayers.Feature.Vector.style["default"])),
"select":new OpenLayers.Style({
externalGraphic:"img/discapacidad-selected.png"
})/*,
"highlight":new OpenLayers.Style({
externalGraphic:"../img/marker-gold.png"
}),
"lowlight":new OpenLayers.Style({
externalGraphic:"../img/marker-green.png"
})*/
})
});
wfsAlbergues = new OpenLayers.Layer.Vector("wfsAlbergues",{
styleMap:new OpenLayers.StyleMap({
"default":new OpenLayers.Style(OpenLayers.Util.applyDefaults({
externalGraphic:"img/casa-default.png",
graphicOpacity:1,
//rotation:-45,
pointRadius:10
}, OpenLayers.Feature.Vector.style["default"])),
"select":new OpenLayers.Style({
externalGraphic:"img/casa-selected.png"
})/*,
"highlight":new OpenLayers.Style({
externalGraphic:"../img/marker-gold.png"
}),
"lowlight":new OpenLayers.Style({
externalGraphic:"../img/marker-green.png"
})*/
})
});
sectorLayer = new OpenLayers.Layer.Vector("Sectores", {hideInLegend :true});
// sectorLayer.set("hideInLegend", !sectorLayer.get("hideInLegend"));
///******************
storeAmenazaTsunami = new GeoExt.data.FeatureStore({
//layer: this.layerAmenTsunami,
fields: [{name:"gid", type:"integer"},
{name:"docver", type:"string"},
{name:"rango", type:"string"}
],
layer: wfsAmenazaTsunami
//autoload:true
});
storeAmenazaInundacion = new GeoExt.data.FeatureStore({
fields: [{name:"gid", type:"integer"},
{name:"va_geo_ind", type:"integer"},
{name:"va_hidr_in", type:"integer"},
{name:"va_gemf_in", type:"integer"},
{name:"va_isoy_fr", type:"integer"},
{name:"va_pen_ind", type:"integer"},
{name:"suma", type:"integer"},
{name:"porcentaje", type:"integer"},
{name:"rango", type:"string"}
],
layer:wfsAmenazaInundacion
//autoload:true
});
storeAmenazaRemocion = new GeoExt.data.FeatureStore({
fields: [{name:"gid", type:"integer"},
{name:"su12345", type:"integer"},
{name:"va_sism_fr", type:"integer"},
{name:"va_isoy_fr", type:"integer"},
{name:"sumto_7", type:"integer"},
{name:"porcentaje", type:"integer"},
{name:"rango", type:"string"}
],
layer:wfsAmenazaRemocion
//autoload:true
});
storeRiesgoInundacion = new GeoExt.data.FeatureStore({
// layer:wfsRiesgoInundacion,
// fields:[],
/*fields: [{name:"amenaza", type:"integer"},
{name:"vulnerabil", type:"integer"},
{name:"suma", type:"integer"},
{name:"porcentaje", type:"integer"},
{name:"rango", type:"string"}
],*/
proxy: new GeoExt.data.ProtocolProxy({
protocol: protocoloRiesgoInundacion
}),
autoload:true
});
storeRiesgoRemocion = new GeoExt.data.FeatureStore({
/*fields: [{name:"va_vulne", type:"integer"},
{name:"va_am_frm", type:"integer"},
{name:"suma", type:"integer"},
{name:"porcentaje", type:"integer"},
{name:"rango", type:"string"}
],*/
layer:wfsRiesgoRemocion
//autoload:true
});
//,wfsDiscapacitados,wfsAlbergues]
//Coleccion de capas
this.layers = [this.LayerBase,wmsLimiteProvincial , wmsParroquias,
//wmsAmenazaInundacion, //wmsAmenazaRemocion,
amenazaRemocion, amenazaInundacion, amenazaTsunami,
wmsRiesgoRemocion, wmsRiesgoInundacion, //wmsSqlInundacion,
wmsComunidadesChanduy, wmsCasasComunales, wmsVias, wmsZonasSeguras,
wmsDiscapacitados,
wmsRuta, wmsAlbergues, sectorLayer,
wfsDiscapacitados, wfsAlbergues
/*wfsAmenazaInundacion,
wfsAmenazaRemocion, wfsAmenazaTsunami,
wfsRiesgoInundacion, wfsRiesgoRemocion//, wfsPrueba*/
];
//DESHABILITAR CAPAS WMS
//wmsAmenazaInundacion.setVisibility(false);
// wmsAmenazaRemocion.setVisibility(false);
amenazaTsunami.setVisibility(false);
amenazaRemocion.setVisibility(false);
amenazaInundacion.setVisibility(false);
wmsRiesgoRemocion.setVisibility(false);
wmsRiesgoInundacion.setVisibility(false);
wmsComunidadesChanduy.setVisibility(false);
wmsCasasComunales.setVisibility(false);
wmsZonasSeguras.setVisibility(false);
wmsLimiteProvincial.setVisibility(false);
wmsParroquias.setVisibility(false);
wmsVias.setVisibility(false);
wmsRuta.setVisibility(true);
wmsAlbergues.setVisibility(false);
wmsDiscapacitados.setVisibility(false);
sectorLayer.hideInLegend = true;
/// tracking.setVisibility(true);
// wfsAmenazaInundacion.setVisibility(false);
//wfsAmenazaRemocion.setVisibility(false);
// wfsAmenazaTsunami.setVisibility(false);
// wfsPrueba.setVisibility(true);
//wfsRiesgoInundacion.setVisibility(false);
// wfsRiesgoRemocion.setVisibility(false);
//wmsRuta.setVisibility(true);
// storeAmenazaInundacion.bind(t;his.layerAmenInundacion);
}<file_sep>/php/consultas.php
<?php
require "db.php";
$comuna = $_POST['comuna'];
if ($comuna!="")
{
load_puntos();
};
function load_puntos()
{
$puntos = $_POST['comuna'];
$sql = "Select x, y from casas_comunales where comunidad = '".$puntos."'" ;
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs))
{
$x = $row->x;
$y = $row->y;
$result[] = array('x'=>$x, 'y'=>$y);
}
echo '{"success":true, "puntos":'.json_encode($result).'}';
};
?><file_sep>/php/login.php
<?php
@session_start();
print_r($_POST);
if( ( isset($_POST["email"]) ) && ( isset($_POST["password"]) ) ){
$_SESSION["INCYT_UPSE_User"]='1';
}
print_r($_SESSION);
?><file_sep>/php/configuracion.php
<?php
define("SERVER_ROOT", $_SERVER["DOCUMENT_ROOT"]."/routing");
$root = SERVER_ROOT;
?><file_sep>/php/cargarCombos.php
<?php
require "db.php";
$combo = $_POST['combo'];
//$comuna = $_POST['comuna'];
switch ($combo) {
case 'comunidades':
load_comunas();
break;
case 'radio':
load_radio_m();
break;
case 'fenomenos':
if( isset($_POST["tipo"]) )
{
load_fenomenosN('1');
}
else
{
load_fenomenosN();
}
break;
case 'rango':
load_rangos();
break;
};
function load_comunas()
{
$sql = "Select id, nombre from comunidades_chanduy";
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs)) {
$id = $row->id;
$nombre = $row->nombre;
//coordenadas
//select x,y from casas_comunales where comunidad = 'ENGUNGA';
$_cc = $code = $x = $y = null;
$_cc = pg_query("select x, y from casas_comunales where comunidad = '".$nombre."' ");
$cc = pg_fetch_object($_cc);
$x = $cc->x;
$y = $cc->y;
$code = $id ."|". $x ."|". $y;
$result[] = array('id'=>$id, 'nombre'=>$nombre, 'code'=>$code);
//break;
}
echo '{"success":true, "data":'.json_encode($result).'}';
};
function load_radio_m()
{
$sql = "Select id, metros from metros";
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs))
{
$id = $row->id;
$metros = $row->metros;
$result[] = array('id'=>$id, 'metros'=>$metros);
}
echo '{"success":true, "metros":'.json_encode($result).'}';
};
function load_rangos()
{
$sql = "Select id, rango from rangos";
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs))
{
$id = $row->id;
$rango = $row->rango;
$result[] = array('id'=>$id, 'rango'=>$rango);
}
echo '{"success":true, "rangos":'.json_encode($result).'}';
};
function load_fenomenosN( $tipo = "" )
{
$sql = null;
if( $tipo <> "" )
{
$sql = "Select id, fenomeno from f_naturales where id <> '3' ";
}
else
{
$sql = "Select id, fenomeno from f_naturales";
}
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs))
{
$id = $row->id;
$fenomeno = $row->fenomeno;
$result[] = array('id'=>$id, 'fenomeno'=>$fenomeno);
}
echo '{"success":true, "fenomenosN":'.json_encode($result).'}';
};
function load_puntos()
{
$puntos = $_POST ['comuna'];
$sql = "Select x, y from casas_comunales where comunidad = '".$puntos."'" ;
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs))
{
$x = $row->x;
$y = $row->y;
$result[] = array('x'=>$x, 'y'=>$y);
}
echo '{"success":true, "puntos":'.json_encode($result).'}';
};
?><file_sep>/php/pgrouting.php
<?php
include("configuracion.php");
include("$root/php/db.php");
/*$x1 = $_POST['x1'];
$y1 = $_POST['y1'];
$x2 = $_POST['x2'];
$y2 = $_POST['y2'];*/
// function load_ruta(){
if(isset($_POST['x1']))
{
$x1 = $_POST['x1'];
$y1 = $_POST['y1'];
$x2 = $_POST['x2'];
$y2 = $_POST['y2'];
$sql = "select (Select sum(cost) FROM pgr_fromAtoB('vias','".$x1."', '".$y1."', '".$x2."', '".$y2."')) as distancia,
velocidad, ((Select sum(cost) FROM pgr_fromAtoB('vias','".$x1."', '".$y1."', '".$x2."', '".$y2."'))/((velocidad*1000)/60)) as tiempo_min, descripcion from velocidad_km_h ";// as distancia,
$rs = pg_query($sql) or die;
while ($row = pg_fetch_object($rs))
{
$distancia = $row->distancia;
$descripcion = $row->descripcion;
$velocidad = $row->velocidad;
$tiempo_min = $row->tiempo_min;
//$y = $row->y;
$result[] = array('distancia'=>$distancia, 'descripcion'=>$descripcion, 'velocidad'=>$velocidad, 'tiempo_min'=>$tiempo_min);//, 'y'=>$y);
}
echo '{"success":true, "ruta":'.json_encode($result).'}';
};
?> | 9e79b909304f793d85d2a90ea2bbb23776598bb5 | [
"JavaScript",
"PHP"
]
| 12 | JavaScript | wilsonalfonzo/routing | 405c30372508d264be7fbb0f5743dddd02d57a55 | af0e9fa79704f985b1ede5f4b02aebb39453739e |
refs/heads/master | <repo_name>z1059022306/ceshi4qi<file_sep>/cesi04_test_test_01/if_test_01.py
# 练习if语句
# if 语句 就是用来进行条件判断的
# if 要判断的条件:
# 条件成立时,要做的事情
# ……
"""
1.定义一个整数变量记录年龄
2.判断是否满 18 岁 (>=)
3.如果满 18 岁,允许进网吧嗨皮
"""
# 定义一个变量,记录年龄
per_age = 19
# 判断是否满18岁(>=)
if per_age >= 18:
# 如果满足这个条件就执行下面的语句
print("允许进入网吧嗨皮")
# 下面这段代码无论条件满足与否,是不是都会执行
print("我都会执行,是不是呢?")
<file_sep>/cesi04_test_test_01/test_in.py
import os, sys
sys.path.append(os.getcwd())
import yaml
import pytest
import allure
def data_in():
data = []
with open("../test_1.yaml", "r", encoding="utf-8") as f:
data_1 = yaml.load(f)
for x in data_1.values():
for y in x.values():
i = y.get("age"), y.get("name"), y.get("height")
data.append(i)
return data
class Test_01:
def test_01(self):
assert 1
def test_02(self):
assert 0
<file_sep>/cesi04_test_test_01/if_test_02.py
# else 处理条件不满足的情况
# 在使用 if 判断时,只能做到满足条件时要做的事情。
# 那如果需要在 不满足条件的时候,做某些事情,该如何做呢?
"""
if 要判断的条件:
条件成立时,要做的事情
……
else:
条件不成立时,要做的事情
……
"""
# 需求
#
# 1.输入用户年龄
# 2.判断是否满 18 岁 (>=)
# 3.如果满 18 岁,允许进网吧嗨皮
# 4.如果未满 18 岁,提示回家写作业
# 输入用户的年龄
person_age = int(input("今年多大啦!:"))
# 判断是否年满18岁
if person_age >= 18:
# 满足条件,大于等于18岁
print("可以进入网吧嗨皮")
# 不满足条件 小于18岁
else:
# 执行不满足条件的语句
print("你不满18岁,回家写作业吧")
# 下面代码什么时候执行
print("我该什么时候执行呢?")
<file_sep>/cesi04_test_test_01/if_test_03.py
# 一对 if 和 else 可以让代f码执行出 两种不同的结果
# 但开发中,可能希望 并列的执行出多种结果,这时就可以使用 eli
"""
if 条件1:
条件1满足执行的代码
……
elif 条件2:
条件2满足时,执行的代码
……
elif 条件3:
条件3满足时,执行的代码
……
else:
以上条件都不满足时,执行的代码
……
"""
# 需求
#
# 1.定义 holiday_name 字符串变量记录节日名称
# 2.如果是 情人节 应该 买玫瑰/看电影
# 3.如果是 平安夜 应该 买苹果/吃大餐
# 4.如果是 生日 应该 买蛋糕
# 5.其他的日子每天都是节日啊…
# 定义 holiday_name 字符串变量记录节日名称
holiday_name = "情人节"
# 如果是情人节 应该 买玫瑰/看电影
if holiday_name == "情人节":
print("今天是情人节,买玫瑰花/看电影")
# 如果是 平安夜 应该 买苹果/吃大餐
elif holiday_name == "平安夜":
print("今天是平安夜,买苹果/吃大餐")
# 如果是 生日 应该 买蛋糕
elif holiday_name == "生日":
print("今天是生日,买蛋糕")
# 其他的日子每天都是节日啊…
else:
print("每天都是节日...")
<file_sep>/cesi04_test_test_01/liebiao.py
name_list = ["zhangsan", "lisi", "wangwu"]
# 取出列表中元素的值
print(name_list[1]) # 输出 lisi
# 列表常用操作
"""
1 增加 列表.append(数据) 在末尾追加数据
列表.insert(索引, 数据) 在指定位置插入数据(位置前有空元素会补位)
列表.extend(Iterable) 将可迭代对象中 的元素 追加到列表
2 删除 del 列表[索引] 删除指定索引的数据
列表.remove(数据) 删除第一个出现的指定数据
列表.pop() 删除末尾数据,返回被删除的元素
列表.pop(索引) 删除指定索引数据
列表.clear 清空列表
3 修改 列表[索引] = 数据 修改指定索引的数据,数据不存在会报错
4 查询 列表[索引] 根据索引取值,索引不存在会报错
列表.index(数据) 根据值查询索引,返回首次出现时的索引,没有查到会报错
列表.count(数据) 数据在列表中出现的次数
len(列表) 列表长度
if 数据 in 列表: 检查列表中是否包含某元素
5 排序 列表.sort() 升序排序
列表.sort(reverse=True) 降序排序
列表.reverse() 逆序、反转
"""
# 列表 增
my_list = [111, 222, 333]
my_list.append(444)
my_list.append(555)
my_list.append(666)
my_list.append(777)
print(my_list)
# 列表 删
# del my_list[1]
# print(my_list)
# 列表 改
# my_list[2]=2421
# print(my_list)
# 列表 查
print(my_list[4])
# 用for循环进行遍历
for i in my_list:
print(i)
# 列表 嵌套
"""
类似while循环的嵌套,列表也是支持嵌套的
一个列表中的元素又是一个列表,那么这就是列表的嵌套
"""
# 一个学校,有3个办公室,现在有8位老师等待工位的分配,
# 请编写程序: 1> 完成随机的分配 2> 获取办公室信息 (每个办公室中的人数,及分别是谁)
import random
# 定义一个列表用来保存3个办公室
offices = [[], [], []]
# 定义一个列表用来存储8位老师的名字
names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
# 完成随机分配
i = 0
for name in names:
index = random.randint(0, 2)
offices[index].append(name)
# 获取办公室信息
i = 1
for tempNames in offices:
print('办公室%d的人数为:%d' % (i, len(tempNames)))
i += 1
for name in tempNames:
print("%s" % name, end='')
print("\n")
print("-" * 20)
<file_sep>/cesi04_test_test_01/while_test_01.py
# 需求
#
# 计算 0 ~ 100 之间所有数字的累计求和结果
i = 1
sum = 0
while i <= 100:
sum = sum + i
i += 1
print("1~100的累积和为:%d" % sum)
# 计算 0 ~ 100 之间 所有 偶数 的累计求和结果
i = 1
sum = 0
while i <= 100:
if i % 2 == 0:
sum = sum + i
i += 1
print("1~100的累积和为:%d" % sum)
# break 某一条件满足时,不再执行循环体中后续重复的代码,并退出循环
# continue 某一条件满足时,不再执行本次循环体中后续重复的代码,但进入下一次循环判断
i = 0
while i < 10:
# break 某一条件满足时,退出循环,不再执行后续重复的代码
# i == 3
if i == 3:
break
print(i)
i += 1
print("over")
i = 0
while i < 10:
# 当 i == 7 时,不希望执行需要重复执行的代码
if i == 7:
# 在使用 continue 之前,同样应该修改计数器
# 否则会出现死循环
i += 1
continue
# 重复执行的代码
print(i)
i += 1
# while 条件 1:
# 条件满足时,做的事情1
# 条件满足时,做的事情2
# 条件满足时,做的事情3
# ...(省略)...
#
# while 条件 2:
# 条件满足时,做的事情1
# 条件满足时,做的事情2
# 条件满足时,做的事情3
# ...(省略)...
#
# 处理条件 2
#
# 处理条件 1
# 定义起始行
row = 1
# 最大打印 9 行
while row <= 9:
# 定义起始列
col = 1
# 最大打印 row 列
while col <= row:
# end = "",表示输出结束后,不换行
# "\t" 可以在控制台输出一个制表符,协助在输出文本时对齐
print("%d * %d = %d" % (col, row, row * col), end="\t")
# 列数 + 1
col += 1
# 一行打印完成的换行
print("")
# 行数 + 1
row += 1
<file_sep>/cesi04_test_test_01/zidian.py
"""
字典的定义
dictionary(字典) 是 除列表以外 Python 之中 最灵活 的数据类型
字典同样可以用来 存储多个数据
通常用于存储 描述一个 物体 的相关信息
字典用 {} 定义
字典使用 键值对 存储数据,键值对之间使用 , 分隔
键 key 是索引
值 value 是数据
键 和 值 之间使用 : 分隔
值 可以取任何数据类型,但 键 只能使用 字符串、数字或 元组
键必须是唯一的
"""
# 定义字典
xiaoming = {
"name": "小明",
"age": 18,
"gender": True,
"height": 1.75}
# 取出元素的值
print(xiaoming["name"]) # 输出: 小明
"""
1 增加 字典[键] = 数据 键不存在,会添加键值对;键存在,会修改键值对的值
2 删除 del 字典[键] 删除指定的键值对
字典.pop(键) 删除指定键值对,返回被删除的值
字典.clear 清空字典
3 修改 字典[键] = 数据 键不存在,会添加键值对;键存在,会修改键值对的值
字典.setdefault(键,数据) 键值对不存在,添加键值对;存在则不做处理
字典.update(字典2) 取出字典2的键值对,键值对不存在,添加键值对;存在则修改值
4 查询 字典[键] 根据键取值,键值对不存在会报错
字典.get(键) 根据键取值,键值对不存在不会报错
字典.keys() 可进行遍历,获取所有键
字典.values() 可进行遍历,获取所有值
字典.items() 可进行遍历,获取所有(键,值)
5 遍历 for key in 字典 取出元组中的每个元素的 key
"""
<file_sep>/cesi04_test_test_01/zifuchuan.py
"""
4.1 字符串的定义
字符串 就是 一串字符,是编程语言中表示文本的数据类型
在 Python 中可以使用 一对双引号 " 或者 一对单引号 ' 定义一个字符串
虽然可以使用 \" 或者 \' 做字符串的转义,但是在实际开发中:
如果字符串内部需要使用 ",可以使用 ' 定义字符串
如果字符串内部需要使用 ',可以使用 " 定义字符串
可以使用 索引 获取一个字符串中 指定位置的字符,索引计数从 0 开始
也可以使用 for 循环遍历 字符串中每一个字符
"""
string = "hello world"
# 用for循环遍历字符串中的字符
for i in string:
print(i)
# 字符串的操作
# 1.判断
# 判断字符是否全部都是字母(是则返回True ,不是返回False)
if_zimu = string.isalpha()
print(if_zimu)
# 判断字符是否全部都是数字(是则返回True ,不是返回False)
if_int = string.isdecimal()
print(if_int)
# 2.查找和替换
"""
string.find(str, start=0, end=len(string))
检测 str 是否包含在 string 中,
如果 start 和 end 指定范围,则检查是否包含在指定范围内,
如果是返回开始的索引值,否则返回 -1
"""
# 查找"l"在索引0-5中
a = string.find("l", 0, 5)
print(a)
"""
string.replace(old_str, new_str, num=string.count(old))
返回一个新字符串,把 string 中的 old_str 替换成 new_str,如果 num 指定,则替换不超过 num 次
"""
# 将原字符串中的“l”替换成“L”,返回新的字符串
new_string = string.replace("l", "L")
print(new_string)
print(string)
# 3.拆分和链接
"""
string.partition(str)
返回元组,把字符串 string 分成一个 3 元素的元组 (str前面, str, str后面)
"""
# 将字符串string按照“w"分成三个元素的元组
b = string.partition("w")
print("b=", b)
"""
string.split(str="", num)
返回列表,以 str 为分隔符拆分 string,如果 num 有指定值,
则仅分隔 num + 1 个子字符串,str 默认包含 '\r', '\t', '\n' 和空格
"""
# 将string拆分成多个子串,以列表方式返回
c = string.split("l")
print("c=", c)
d = string.split(" ")
print("d=", d)
"""
string1 + string2
字符串拼接
"""
# 字符串拼接
string1 = "hhh"
string2 = "aaa"
new_string1 = string1 + string2
print("new_string1=", new_string1)
# 4.大小写转换
"""
string.lower() 返回新字符串,转换 string 中所有大写字符为小写
string.upper() 返回新字符串,转换 string 中的小写字母为大写
"""
big_string = string.upper()
smo_string = new_string.lower()
print("big_string=", big_string)
print("smo_string=", smo_string)
# 字符串切片
"""
切片 译自英文单词 slice,翻译成另一个解释更好理解: 一部分
切片 使用 索引值 来限定范围,根据 步长 从原序列中 取出一部分 元素组成新序列
切片 方法适用于 字符串、列表、元组
"""
"""
注意:
1.指定的区间属于 左闭右开 型 [开始索引, 结束索引) 对应 开始索引 <= 范围 < 结束索引
2.从 起始 位开始,到 结束位的前一位 结束(不包含结束位本身)
3.从头开始,开始索引 数字可以省略,冒号不能省略
4.到末尾结束,结束索引 数字和冒号都可以省略
5.步长默认为 1,如果元素连续,数字和冒号都可以省略
"""
"""
截取从 2 ~ 5 位置 的字符串
截取从 2 ~ 末尾 的字符串
截取从 开始 ~ 5 位置 的字符串
截取完整的字符串
从开始位置,每隔一个字符截取字符串
从索引 1 开始,每隔一个取一个
截取从 2 ~ 末尾 - 1 的字符串
截取字符串末尾两个字符
字符串的逆序(面试题)
"""
num_str = "0123456789"
# 1. 截取从 2 ~ 5 位置 的字符串
print(num_str[2:6])
# 2. 截取从 2 ~ `末尾` 的字符串
print(num_str[2:])
# 3. 截取从 `开始` ~ 5 位置 的字符串
print(num_str[:6])
# 4. 截取完整的字符串
print(num_str[:])
# 5. 从开始位置,每隔一个字符截取字符串
print(num_str[::2])
# 6. 从索引 1 开始,每隔一个取一个
print(num_str[1::2])
# 倒序切片
# -1 表示倒数第一个字符
print(num_str[-1])
# 7. 截取从 2 ~ `末尾 - 1` 的字符串
print(num_str[2:-1])
# 8. 截取字符串末尾两个字符
print(num_str[-2:])
# 9. 字符串的逆序(面试题)
print(num_str[::-1]) | f52306ac83cdb75b4563fb4f2d1b70480a6a9f08 | [
"Python"
]
| 8 | Python | z1059022306/ceshi4qi | d71af0fbba656512e8a6bb786cf3d8aa86dbc81a | 33e1b1e5944ca95204c433d8d62bb7875e3b73e6 |
refs/heads/master | <file_sep>s = input()
a = list(input().split())
f = int(0)
for i in a:
if s[0]==i[0] or s[1]==i[1]:
f=1
if f:
print("YES")
else:
print("NO")<file_sep>t = int(input())
s = input()
z = 0
n = 0
for i in s:
if i=='z':
z += 1
elif i=='n':
n += 1
for i in range(n):
print("1",end=" ")
for i in range(z):
print("0",end=" ")
print("\n")<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int OneOven( int n , int t , int k )
{
int s = 0 ;
int d = t;
for(t ; ; t+=d)
{
s+=k;
if(s>=n) return t;
}
}
int TwoOven( int n , int t , int k , int d )
{
int s = 0 ;
int j = d ;
for(int i = 1 ; ; i++ )
{
if(i%t==0) s+=k;
//if(s>=n) return i;
if(d==i) j+=t;
//cout << j << " " << i << " " << s << endl;
if(j==i)
{
//cout << j << " " << s << endl;
s+=k;
j+=t;
}
if(s>=n) return i;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n , t , k , d , i , s = 0 ;
scanf("%d %d %d %d" , &n , &t , &k , &d );
int t1 = 0 ;
int t2 = 0 ;
t1 = OneOven( n,t,k );
t2 = TwoOven( n,t,k,d );
//cout << t1 << " " << t2 << endl;
if(t1<=t2) printf("NO\n");
else printf("YES\n");
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n = ri()
pos = 0
neg = 0
for _ in range(n):
x, y = ria()
if x>0:
pos += 1
else:
neg += 1
if pos <= 1 or neg <= 1:
ws("Yes")
else:
ws("No")
if __name__ == '__main__':
main()
<file_sep>n , k = list(map(int,input().split()))
while k>0 :
if n%10==0:
n = n//10
else:
n = n - 1
k -= 1
print(n)
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
LL n,m;
cin >> n>> m;
LL a[m];
LL i,j,k,pos=1,s=0;
for(i=0;i<m;i++)
{
cin >> a[i];
if(a[i]>pos)
{
s+=a[i]-pos;
pos=a[i];
}
else if(a[i]==pos) continue;
else
{
s+=n-pos+a[i];
pos=a[i];
}
}
cout << s << "\n";
return 0;
}
<file_sep>from math import ceil
n, m, a = map(int, input().split())
print(ceil(n/a)*ceil(m/a))
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int lst[150][150]={0};
void mark(int i, int j, int n, int m);
void ma(int i, int j, int n, int m)
{
if(i<0 || i>n-1 || j<0 || j>m-1) return;
if(lst[i][j]!=-1) lst[i][j]++;
return;
}
void mark(int i, int j, int n, int m)
{
if(i<0 || i>n-1 || j<0 || j>m-1) return;
else if(lst[i][j]==-1)
{
ma(i+1,j+1,n,m);
ma(i,j+1,n,m);
ma(i+1,j,n,m);
ma(i-1,j-1,n,m);
ma(i-1,j,n,m);
ma(i,j-1,n,m);
ma(i-1,j+1,n,m);
ma(i+1,j-1,n,m);
}
return;
}
void clr()
{
for(int i=0;i<120;i++)
{
for(int j=0;j<120;j++) lst[i][j]=0;
}
}
int main()
{
int n,i,j,x,y,cnt=1,m;
while(cin >> n >> m)
{
if(n==0 && m==0) return 0;
S a[130];
for(i=0;i<n;i++) cin >> a[i];
clr();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(a[i][j]=='*') lst[i][j]=-1;
else lst[i][j]=0;
}
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
mark(i,j,n,m);
}
}
if(cnt!=1) printf("\n");
printf("Field #%d:\n",cnt++);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(lst[i][j]==-1) printf("*");
else printf("%d",lst[i][j]);
}
printf("\n");
}
}
return 0;
}
<file_sep>
# Problem : 278 - Chess
# Contest : UVa Online Judge
# URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=214
# Memory Limit : 32 MB
# Time Limit : 3000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
# <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
t = ri()
for _ in range(t):
s, m, n = sys.stdin.readline().split()
#print(s+" "+m+" "+n)
s = str(s)
m = int(m)
n = int(n)
if s=='r':
wi(min(m,n))
elif s=='k':
if n%2!=0:
wi((n*m+1)//2)
else:
wi(n*m//2)
elif s=='Q':
wi(min(m,n))
elif s=='K':
wi(((n+1)//2)*((m+1)//2))
if __name__ == '__main__':
main()
<file_sep>#include <iostream>
#include <vector>
#include <queue>
#include <map>
using namespace std;
#define MAX 100000
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int ns,i,j,k,x,y,ttl,cs=1;
while(scanf("%d",&ns) && ns)
{
map < int , vector <int> > m;
map<int,int> lst;
for(i=1;i<=ns;i++)
{
scanf("%d %d",&x,&y);
m[x].push_back(y);
m[y].push_back(x);
if(lst[x]==0) lst[x]=1;
if(lst[y]==0) lst[y]=1;
}
int num=0;
for(auto g : lst)
{
if(g.second==1) num++;
}
while(cin >> x >> ttl)
{
if(x==0) break;
map< int , int > visited;
queue<int> q;
q.push(x);
visited[x]=1;
int lt=0,count=1;
while(!q.empty())
{
int u=q.front();
q.pop();
int l=m[u].size();
for(i=0;i<l;i++)
{
int v=m[u][i];
if(!visited.count(v))
{
q.push(v);
visited[v]=visited[u]+1;
k=visited[v];
if(k>ttl+1) lt++;
else count++;
}
}
}
lt=num-count;
if(lst[x]==0) lt=num;
printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",cs++,lt,x,ttl);
}
}
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin >> n;
int i,j,k;
for(i=0;i<n;i++)
{
D x1,y1,x2,y2,x3,y3;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
D a,b,c;
a=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
aa=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
b=sqrt((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2));
bb=(x3-x2)*(x3-x2)+(y3-y2)*(y3-y2);
c=sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
c2=(x1-x3)*(x1-x3)+(y1-y3)*(y1-y3);
cout << "The length of the sides: \n" << a << "\n"<< b << "\n" << c << endl;
if(aa+bb==c2 || aa+c2==bb || bb+c2==aa) cout << "Somokony\n" ;
}
return 0;
}<file_sep># Read the number
n = int(input())
# put the left and right limits in variables
left = -2**31
right = 2**31 - 1
# if n is in the range(-2^63 <= n < 2^63), print yes, otherwise print no
if left <= n and n <= right:
print("Yes")
else:
print("No")<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b;
cin >> a >> b;
cout << min(a,b) << " " << ((a-min(a,b))/2) + ((b-min(a,b))/2) << endl;
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i;
cin >> n ;
string a[n];
int tmp=0;
for(i=0;i<n;i++)
{
cin >> a[i];
if(a[i][0]=='O' && a[i][1]=='O' && tmp==0)
{
tmp=1;
a[i][0]='+';
a[i][1]='+';
}
else if(a[i][3]=='O' && a[i][4]=='O' && tmp==0)
{
tmp=1;
a[i][3]='+';
a[i][4]='+';
}
}
if(tmp==0) cout << "NO\n";
else
{
cout << "YES\n";
for(i=0;i<n;i++)
cout << a[i] << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,t,i,j,s=0;
scanf("%d %d",&n,&t);
int a[n+5];
for(i=1;i<=n;i++) scanf("%d",&a[i]);
i=1;
while(i<=n)
{
s=i+a[i];
i+=a[i];
if(s==t)
{
printf("YES\n");
break;
}
if(s>t)
{
printf("NO\n");
break;
}
}
return 0;
}<file_sep>t = int(input())
for cs in range(t):
a,b = input().split()
a = int(a)
b = int(b)
if a==1 or b==1:
print("YES")
elif a==2 and b==2:
print("YES")
else:
print("NO")
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
p, a, b, c = map(int, input().split())
t1 = 1e18
t2 = 1e18
t3 = 1e18
if p%a==0:
t1 = 0
else:
t1 = a * ((p//a)+1) - p
if p%b==0:
t2 = 0
else:
t2 = b * ((p//b)+1) - p
if p%c==0:
t3 = 0
else:
t3 = c * ((p//c)+1) - p
wi(min(t1, min(t2,t3)))
if __name__ == '__main__':
t = ri() # 1
while t:
t -= 1
main()
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
int main()
{
LL n ;
while(cin >> n)
{
LL m = 1 , i;
for(i = 1 ; ; i++ )
{
if(m%n==0) break;
m ++ ;
}
cout << i << endl;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>#include<bits/stdc++.h>
using namespace std;
using LL = long long;
const int mx = 1e5;
LL arr[mx];
struct info
{
LL sum = 0 ;
LL prop = 0 ;
} tree[mx*4] ;
void build (int node, int L, int R)
{
if(L==R)
{
tree[node].sum = arr[L];
return;
}
int mid = (L+R)/2 ;
build(node*2,L,mid);
build(node*2+1,mid+1,R);
tree[node].sum = tree[node*2].sum + tree[node*2+1].sum ;
}
void update (int node, int L, int R, int i, int j, LL x)
{
if(j<L || R<i) return;
if(L<=i && j<=R)
{
tree[node].sum += (R-L+1)*x ;
tree[node].prop += x ;
return;
}
int mid = (L+R)/2 ;
update(node*2,L,mid,i,j,x);
update(node*2+1,mid+1,R,i,j,x);
tree[node].sum += tree[node*2].sum + tree[node*2+1].sum + (R-L+1)*tree[node].prop;
}
LL query (int node, int L, int R, int i, int j, LL carry=0)
{
if(j<L || R<i) return 0;
if(L<=i && j<=R) return tree[node].sum+(R-L+1)*carry;
int mid = (L+R) >> 1 ;
LL x = query(node*2,L,mid,i,j,carry+tree[node].prop);
LL y = query(node*2+1,mid+1,R,i,j,carry+tree[node].prop);
return x+y ;
}
int main()
{
int n;
//cin >> n;
n=7;
for (int i = 1; i <= n; ++i)
{
//cin >> arr[i];
arr[i]=i;
}
build(1, 1, n);
//update(1, 1, 7, 1, 7, 2);
//update(1, 1, 7, 1, 4, 3);
cout << "Value for range [1, n]: " << query(1, 1, n, 1, n) << "\n\n";
cout << "State of Segment Tree:\n";
for (int i = 1; i < 2*n; ++i)
{
cout << "index: " << i << " sum: " << tree[i].sum << " prop: " << tree[i].prop << "\n";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n,m,a,s=0;
cin >> n >> m >> a;
if(n%a==0) n/=a;
else n = (n/a)+1;
if(m%a==0) m/=a;
else m = (m/a)+1;
//s = (n+a-1)/a * (m+a-1)/a ;
cout << n*m << endl;
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,a,i,j;
scanf("%d %d",&n,&a);
for(i=1;i<=100000;i++)
{
int s=n-n/10;
if(!s || s%a==0)
{
printf("%d\n",i);
return 0;
}
}
return 0;
}<file_sep>// HurayraIIT
#include <bits/stdc++.h>
using namespace std;
#define pi acos(-1.0)
typedef long long LL;
typedef vector<int> vi ;
int main()
{
int n;
cin >> n;
int sum[n+1] ;
for (int i = 0; i < n; i++)
{
int a,b,c,d;
cin >> a >> b >> c >> d ;
sum[i+1] = a+b+c+d ;
}
int cnt = 0 ;
for (int i = 2; i <= n; i++)
{
if(sum[i]>sum[1]) cnt++ ;
}
cout << cnt +1 << endl;
return 0;
}
<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
int main()
{
//fast_io
int t=0,n=0,i=0,j=0;
cin >> t ;
while(t--)
{
cin >> n ;
int a[n] , b[n] = {0} , c[n]={0};
string s ;
cin >> s ;
LL cnt = 0 ;
for(i=0;i<n;i++)
{
a[i] = s[i] - '0' ;
if(!i) b[0] = a[0] ;
if(i)
{
b[i] = b[i-1]+a[i];
}
}
c[n-1] = a[n-1] ;
for(i=n-2;i>=0;i--)
{
c[i] = c[i+1]+a[i] ;
}
for(i=0;i<n;i++)
{
if(a[i]==1) cnt++;
if(b[i]==1) continue;
if((i+1)>=b[i])
{
if((i+1)==b[i]) cnt++;
}
}
//cout << cnt << " ";
for(i=n-1;i>0;i--)
{
if(c[i]<=1) continue;
if((n-i)==c[i]) cnt++;
}
cout << cnt << endl;
}
return 0;
}
<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
t = ri()
for _ in range(t):
m = ri()
if m >= 1900:
print("Division 1")
elif m >= 1600:
print("Division 2")
elif m >= 1400:
print("Division 3")
else:
print("Division 4")
if __name__ == '__main__':
main()
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,k,i,j;
scanf("%d %d",&n,&k);
for(i=0,j=0;i<n;i++,j++)
{
if(j==k) j=0;
char a = 'a'+j;
printf("%c",a);
}
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def isSorted(a) -> bool:
for i in range(len(a)-1):
if a[i] > a[i+1]:
return False
return True
def main():
n = ri()
a = ria()
b = []
c = []
even = 0
odd = 0
for i in a:
if i&1:
odd += 1
b.append(i)
else:
even += 1
c.append(i)
if isSorted(a) or (isSorted(b) and isSorted(c)):
ws("Yes")
else:
ws("No")
if __name__ == '__main__':
t = ri() # 1
for _ in range(t):
main()
<file_sep># <NAME>
import sys
from collections import defaultdict
# import threading
# threading.stack_size(2**25)
# sys.setrecursionlimit(2**21)
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def shraboni(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
n, m = shraboni()
a = shraboni()
d = defaultdict(list)
visited = defaultdict(int)
ans = 0
for i in range(n-1):
x, y = shraboni()
d[x].append(y)
d[y].append(x)
def dfs(start, parent, cat):
nonlocal ans
visited[start] = 1
if a[start-1]:
cat += 1
else:
cat = 0
if cat > m:
return
flag = 1
for key in d[start]:
if visited[key]:
continue
flag = 0
dfs(key, start, cat)
if flag:
ans += 1
dfs(1, -1, 0)
print(ans)
if __name__ == '__main__':
# t = threading.Thread(target=main)
# t.start()
# t.join()
main()
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int s=0,i,a[5][5],j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
cin >> a[i][j];
if(a[i][j]!=0) s = abs(i-2) + abs(j-2) ;
}
}
cout << s << endl;
return 0;
}<file_sep>#######################################
import sys
input = sys.stdin.readline
ans = []
for i in range(int(input())):
n = int(input())
ans.append(n//2 + n %2)
print(*ans,sep='\n')
########################################
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def solve(n):
return (n + 1) // 2
def main():
for _ in range(ri()):
n = ri()
wi(solve(n))
if __name__ == '__main__':
main()
#############################################3
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,t=0;
string a;
int arr[11] ;
for(i=1;i<11;i++) arr[i]=1;
while(cin >> n)
{
if(n==0) return 0;
cin >> ws;
getline(cin,a);
if(a[0]=='r')
{
if(arr[n]==1) printf("Stan may be honest\n");
else printf("Stan is dishonest\n");
for(i=1;i<11;i++) arr[i]=1;
continue;
}
if(a[4]=='h') for(i=n;i<11;i++) arr[i]=0;
else if(a[4]=='l') for(i=1;i<=n;i++) arr[i]=0;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, k;
cin >> n >> k;
int a[n] ;
for(int i=0;i<n;i++) cin >> a[i] ;
sort(a,a+n) ;
if(k==n) cout << a[k-1] << endl;
else if(k==0 && a[k]!=1) cout << 1 << endl;
else if(k==0 && a[k]==1) cout << -1 << endl;
else if(a[k-1]!=a[k]) cout << a[k-1] << endl;
else cout << -1 << endl;
return 0;
}
<file_sep># Take input in an array
a, b = map(int, input().split())
# Format the ans
print(f"{(a*b)/100 :.7f}")<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m; cin >> m >> n;
int s = (m/2)*n;
if(m&1) s+=n/2;
cout << s << endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
bool can(int a, int b, int c, int d)
{
int odd = 0 ;
if(a&1) odd++;
if(b&1) odd++;
if(c&1) odd++;
if(d&1) odd++;
if(odd<=1) return true;
if(a>=1 && b>=1 && c>=1) {a--;b--;c--;d+=3;}
odd = 0 ;
if(a&1) odd++;
if(b&1) odd++;
if(c&1) odd++;
if(d&1) odd++;
if(odd<=1) return true;
return false;
}
int main()
{
LL t;
cin >> t;
while(t--)
{
LL r,g,b,w;
cin >> r >> g >> b >> w ;
if(!can(r,g,b,w)) cout << "No\n";
else cout << "Yes\n";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
int a=0,b=0;
cin >> s;
for(int i=0;i<s.length();i++)
{
if(s[i]=='a') a++;
else b++;
}
while(b!=0 && a<=(a+b)/2)
{
b--;
}
cout << a +b << endl;
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,k,l,let=0,st=0,qt=0;
S s;
cin >> s;
cin >> n;
//cout << n;
l=s.length();
for(i=0;i<l;i++)
{
if(s[i]>='a' && s[i]<='z') let++;
if(s[i]=='*') st++;
if(s[i]=='?') qt++;
}
//cout << let << " " << st << " " << qt << endl;
if(n<let && st+qt<let-n)
{
cout << "Impossible\n";
return 0;
}
else if(n<let && st+qt>=let-n)
{
int tmp=0;
int del=let-n;
//cout << del <<endl;
for(i=0;i<l-1;i++)
{
if(s[i]!='?' && s[i]!='*' && (s[i+1]=='?' || s[i+1]=='*') && del!=0)
{
del--;
continue;
}
else if(s[i]!='?' && s[i]!='*' && (s[i+1]=='?' || s[i+1]=='*') && del==0) cout << s[i];
else if(s[i]!='?' && s[i]!='*' && (s[i+1]!='?' && s[i+1]!='*')) cout << s[i];
}
if(s[l-1]!='?' && s[l-1]!='*') cout << s[l-1] << endl;
return 0;
}
else if(n==let)
{
for(i=0;i<l;i++)
{
if(s[i]!='?' && s[i]!='*') cout << s[i];
}
cout << "\n";
return 0;
}
else if(n>=let && st>0)
{
//k=l-qt-st;
int trg=n-let;
//cout << trg << endl;
int tmp=0;
for(i=0;i<l-1;i++)
{
if(s[i]!='?' && s[i]!='*' && (s[i+1]!='*' || (s[i+1]=='*' && tmp==1))) cout << s[i];
else if(s[i]=='?') continue;
else if(s[i]!='?' && s[i]!='*' && s[i+1]=='*' && tmp==0)
{
for(j=0;j<=trg;j++) cout << s[i];
tmp=1;
}
}
if(s[l-1]!='?' && s[l-1]!='*') cout << s[l-1] << endl;
return 0;
}
else if(n>let && st==0)
{
cout << "Impossible\n";
return 0;
}
return 0;
}<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
struct node
{
int val ;
struct node * left ;
struct node * right ;
};
struct node * newNode( int n )
{
struct node * temp = (node *) malloc(sizeof(node)) ;
temp -> val = n ;
temp -> left = temp -> right = NULL ;
return temp ;
}
int maxHeight( struct node * temp )
{
if(temp == NULL ) return 0;
int lHeight = maxHeight(temp->left) ;
int rHeight = maxHeight(temp->right) ;
return max(lHeight,rHeight) + 1 ;
}
int maxDia = 0 , dia = 0 ;
void trav ( struct node * temp)
{
if(temp==NULL) return ;
dia = maxHeight(temp->left)+maxHeight(temp->right)+1;
if(dia>maxDia) maxDia = dia;
trav(temp->left);
trav(temp->right);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n , head , i , j ;
string s ;
cin >> n >> head ;
struct node * root = newNode(head) ;
struct node * currentNode = (node *) malloc(sizeof(node));
for(i=1;i<n;i++)
{
int data ;
cin >> s >> data ;
int l = s.length() ;
currentNode = root ;
for(j=0;j<l;j++)
{
if(s[j]=='L')
{
if(!(currentNode->left))
{
currentNode->left = newNode(0) ;
}
currentNode = currentNode -> left ;
}
else
{
if(!(currentNode->right))
{
currentNode->right = newNode(0) ;
}
currentNode = currentNode -> right ;
}
//cout << currentNode->left << endl;
}
if(currentNode==NULL) currentNode = newNode(data) ;
else currentNode->val = data ;
}
maxDia = 0 ; dia = 0 ;
trav(root) ;
// int diameter = maxHeight(root->left) + maxHeight(root->right) + 1 ;
cout << maxDia << endl ;
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
inp:
5 1
L
2
R
3
LL
4
LR
5
out:
4
*/
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
LL n,k,x,i,j;
cin >> n;
while(n--)
{
cin >> k >> x;
LL d=x+(k-1)*9;
cout << d << "\n";
}
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int gcd(int a , int b , int & x , int & y )
{
if(a==0) { x=0;y=1;return b; }
int x1 , y1 , g = gcd(b%a,a,x1,y1);
x = y1 - (b/a)*x1 ;y = x1; return g;
}
int main()
{
/*
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
*/
int a,b;
while(scanf("%d %d",&a,&b)==2)
{
int x , y ;
int g = gcd(a,b,x,y);
if(a==b) {x = 0 ; y = 1 ;}
cout << x << " " << y << " " << g << endl;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
typedef pair< int,vector<int> > pivi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,l,i,j,x,y;
while(scanf("%d",&n) && n)
{
scanf("%d",&l);
vi edges[n+10];
int visited[n+10]={0};
for(i=0;i<l;i++)
{
scanf("%d %d",&x,&y);
edges[x].push_back(y);
edges[y].push_back(x);
}
qi q;
q.push(x);
int flag=1;
visited[x]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
int l=edges[u].size();
for(i=0;i<l;i++)
{
int v=edges[u][i];
if(visited[v]==visited[u])
{
flag=0;
break;
}
else if(visited[u]==1 && visited[v]==0)
{
visited[v]=2;
q.push(v);
}
else if(visited[u]==2 && visited[v]==0)
{
visited[v]=1;
q.push(v);
}
}
if(flag==0) break;
}
if(flag==0) printf("NOT BICOLORABLE.\n");
else printf("BICOLORABLE.\n");
}
return 0;
}<file_sep># <NAME>
import sys
from collections import defaultdict
# import threading
# threading.stack_size(2**27)
# sys.setrecursionlimit(2**21)
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
s = rs()
if s.count('A') < 2 or s.count('B') < 2 or s.count('AB') < 1 or s.count('BA') < 1:
print('NO')
else:
for i in range(len(s)-3):
if s[i]=='A' and s[i+1]=='B':
for j in range(i+2, len(s)-1):
if s[j]=='B' and s[j+1]=='A':
print("YES")
return
for i in range(len(s)-3):
if s[i]=='B' and s[i+1]=='A':
for j in range(i+2, len(s)-1):
if s[j]=='A' and s[j+1]=='B':
print("YES")
return
print("NO")
if __name__ == '__main__':
# t = threading.Thread(target=main)
# t.start()
# t.join()
main()
<file_sep>n = int(input())
ans = 0
while n>0:
n -= 1
s = input()
if s[0]=='T':
ans += 4
elif s[0]=='C':
ans += 6
elif s[0]=='O':
ans += 8
elif s[0]=='D':
ans += 12
elif s[0]=='I':
ans += 20
print(ans)
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n; cin >> n;
if(n==1 || n&1) cout << "Ehab\n";
else cout << "Mahmoud\n";
return 0;
}<file_sep>
# Take input as integer
hours = int(input())
# This variable will hold salary
salary = 0
# compute the salary
if hours <= 40:
salary = hours * 200
else:
# 8000 for first 40 hours, and 300 for other hours
salary = 8000 + 300 * (hours - 40)
# Print the salary
print(salary)
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
current_yellow_crystals, current_blue_crystals = ria()
yellow_balls, green_balls, blue_balls = ria()
needed = 0
yellow_crystals_needed = yellow_balls*2 + green_balls
blue_crystals_needed = green_balls + 3 * blue_balls
wi(max(0,yellow_crystals_needed-current_yellow_crystals)+max(0,blue_crystals_needed-current_blue_crystals))
if __name__ == '__main__':
main()
<file_sep>// HurayraIIT
#include <bits/stdc++.h>
using namespace std;
#define pi acos(-1.0)
typedef long long LL;
typedef vector<int> vi ;
int main()
{
int t ;
cin >> t;
for (int i = 0; i < t; i++)
{
string s ;
cin >> s ;
int l = s.length() ;
if(s[l-1]=='o') cout << "FILIPINO" << endl;
else if(s[l-1]=='u') cout << "JAPANESE" << endl;
else if(s[l-1]=='a') cout << "KOREAN" << endl;
}
return 0;
}
<file_sep>from math import sqrt
n = int(input())
s = 0
for i in range(1,int(sqrt(n))+1):
if n%i==0:
s += 2
if i == n/i:
s -= 1
if i==1:
s-=1
print(s)<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair <int, int> pii;
typedef vector <int> vi;
typedef vector <pair<int, int> > vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,n) for(int i = 0 ; i < n ; i++)
#define rep2(i,a,b) for(int i = a ; i <= b ; i++)
int main()
{
fast_io
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n] = {0};
int x = 0, y = 0;
rep (i, n) {
cin >> a[i];
}
rep (i, n) {
if (i%2) {
if (a[1]%2!=a[i]%2) {
x = 1;
break;
}
}
else if (a[0]%2!=a[i]%2) {
y = 1;
break;
}
}
// cout << x << " " << y << " \n";
if (!x && !y) {
cout << "YES\n";
} else {
cout << "NO\n";
}
}
return 0;
}
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
LL bigModIterative(LL a , LL b , LL m)
{
a = a % m ;
LL res = 1 ;
while(b>0)
{
if(b&1) res = (res*a) % m ;
a = (a*a) % m ;
b = b >> 1 ;
}
return res;
}
int main()
{
LL a,b,m;
while(cin>>a>>b>>m)
{
LL res = bigModIterative(a,b,m);
cout << res << endl;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep># <NAME>
import sys
from collections import defaultdict
# import threading
# threading.stack_size(2**27)
# sys.setrecursionlimit(2**21)
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
t = ri()
for _ in range(t):
x, n, m = ria()
while n > 0 and m > 0:
if (x//2)+10 <= x:
x = (x//2)+10
n -= 1
else:
x -= 10
m -= 1
if m == 0:
while n > 0 and (x//2)+10 < x:
x = (x//2)+10
n -= 1
# print(f"x = {x}, n = {n}, m = {m}")
if n == 0:
x = x - (m*10)
if x <= 0:
ws("YES")
else:
ws("NO")
if __name__ == '__main__':
# t = threading.Thread(target=main)
# t.start()
# t.join()
main()
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
int n,i,j;
cin >> n;
int a[5010]={0};
for(i=0;i<n;i++)
{
cin >> j;
a[j]=1;
}
j=0;
for(i=1;i<=n;i++) if(!a[i]) j++;
cout << j << "\n";
return 0;
}<file_sep>// <NAME>
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pi acos(-1.0)
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int t;
cin >> t ;
while(t--)
{
string s ;
cin >> s ;
LL ans = 0 ;
LL flg = -1 ;
LL n = s.size();
LL a[n];
for(int i = 0 ; i < n ; i++ )
{
if(!i) a[i] = (s[i]=='-') ? -1 : 1 ;
else a[i] = a[i-1] + ( (s[i]=='-') ? -1 : 1 ) ;
}
for(int i = 0 ; i < n ; i++ )
{
if(a[i]==flg)
{
ans += i+1 ; flg--;
}
}
ans += n ;
cout << ans << endl;
}
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,k;
while(cin>>n)
{
if(n==-1) return 0;
string a,b; cin.ignore(); cin >> a >> b;
int la = a.length() , lb = b.length() ;
int x[26] = {0}; int y[26] = {0}; int cnt=0;
for(i=0;i<la;i++) x[a[i]-'a'] = 1 ;
for(i=0;i<26;i++) cnt+= x[i] ;
int hang=0 , cn=0;
cout << "Round " << n << endl;
for(j=0;j<lb;j++)
{
int p = b[j] - 'a'; int t = 0;
if(x[p]==1 && y[p]==0)
{
x[p]=0;cn++;
}
else if(!y[p]) hang++;
if(cn<cnt && hang>=7)
{
cout << "You lose.\n";
break;
}
else if(cn==cnt && hang<7)
{
cout << "You win.\n";
break;
}
else if(cn<cnt && hang<7 && j==lb-1)
{
cout << "You chickened out.\n";
break;
}
y[p]=1;
}
}
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
vi v{0,1,2,3,4,5,6,7,8,9,11,22,33,44,55,23*60+32,22*60+22,20*60+02,21*60+12,15*60+51,14*60+41,13*60+31,12*60+21,11*60+11,10*60+01};
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,k;
/*
for(i=9;i<=59;i+=10) v.push_back(9*60+i);
for(i=8;i<=59;i+=10) v.push_back(8*60+i);
for(i=7;i<=59;i+=10) v.push_back(7*60+i);
for(i=6;i<=59;i+=10) v.push_back(6*60+i);
for(i=5;i<=59;i+=10) v.push_back(5*60+i);
for(i=4;i<=54;i+=10) v.push_back(4*60+i);
for(i=3;i<=53;i+=10) v.push_back(3*60+i);
for(i=2;i<=52;i+=10) v.push_back(2*60+i);
for(i=1;i<=51;i+=10) v.push_back(1*60+i);*/
for(j=1;j<=9;j++)
{
for(i=j;i<=59;i+=10) v.push_back(j*60+i);
}
//cout << v.size();
sort(v.begin(),v.end());
cin >> n;
cin >> ws;
while(n--)
{
string a;
cin >> a;
int ans=0;
int crnt = ((a[0]-'0')*10+(a[1]-'0'))*60+((a[3]-'0')*10+(a[4]-'0'));
for(i=0;i<v.size();i++)
{
if(v[i]>crnt)
{
ans = v[i]; break;
}
if(i==79) ans=0;
}
int h = ans/60;
int m = ans%60;
if(h>9) cout << h << ":";
else if(h>0) cout <<"0" << h << ":";
else cout << "00:";
if(m==0) cout << "00\n";
else if(m<10) cout << "0" << m << endl;
else cout << m << endl;
}
return 0;
}
/*
00 00
00 01
00 02
00 03
00 04
00 09
00 11
00 22
00 33
00 44
00 55
*/
<file_sep>#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
LL t,n,i;
cin >> t ;
while(t--)
{
cin >> n ;
for(i=3;i<=n;i = (i<<1)+1)
{
if(n%i==0)
{
cout << n/i << endl;
break;
}
}
}
return 0;
}<file_sep>// https://www.hackerearth.com/practice/data-structures/trees/binary-and-nary-trees/tutorial/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
// Make a node structure
struct node
{
int value ;
struct node * left ;
struct node * right ;
};
// Utility function for making a new node
struct node * newnode ( int element )
{
struct node * temp = (node *) malloc(sizeof(node)) ;
temp -> value = element ;
temp -> left = temp -> right = NULL ;
return temp ;
}
// Find maximum depth/height
int maxHeight ( struct node * temp)
{
if(temp == NULL) return 0 ;
int lheight = maxHeight(temp -> left) ;
int rheight = maxHeight(temp -> right) ;
return max(lheight,rheight) + 1 ;
}
int main()
{
struct node * root ;
//root = (node *) malloc(sizeof(node)) ;
root = newnode(1) ;
root -> value = 1 ;
root -> left = newnode(2) ;
root -> right = newnode(3) ;
( root -> left ) -> left = newnode(4) ;
( ( root -> left ) -> left ) -> left = NULL ;
( root -> left ) -> right = newnode(5) ;
cout << maxHeight(root) << endl;
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
/* 1
/ \
2 3
/ \
4 5
output = 3
*/<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, i, j;
string s;
cin >> n >> s ;
int arr[26][26];
// initialize the solution array
for ( i = 0 ; i < 26 ; i++ ) {
for ( j = 0 ; j < 26 ; j++ ) {
arr[i][j] = 0 ;
}
}
int mx = 0 , val = 0 ;
for ( i = 0 ; i < n-1 ; i++ ) {
val = ++arr[s[i]-'A'][s[i+1]-'A'] ;
mx = (val>mx) ? val : mx ;
}
bool flag = false ;
for ( i = 0 ; i < 26 ; i++ ) {
for ( j = 0 ; j < 26 ; j++ ) {
if ( arr[i][j] == mx ) {
cout << (char) (i+'A') << (char) (j+'A') << endl ;
flag = true ;
break ;
}
}
if ( flag == true ) break ;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n; cin >> n;
int s = n/100;
n %= 100;
s += n/20 ;
n %= 20 ;
s += n/10 ;
n %= 10 ;
s += n/5 ;
n %= 5 ;
s += n/1 ;
cout << s << endl;
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,q,k,f;
cin >> q ;
while(q--)
{
cin >> n ;
int a[n+1] , b[n+1];
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(i=1;i<=n;i++)
{
cin >> k >> f ;
a[k]++;
if(f==1) b[k]++;
}
sort(a,a+n+1);
sort(b,b+n+1);
int s = 0 ;
int t = -100 ;
for(i=n;i>=0;i--)
{
if(a[i]==0) break;
if(i==n || t==-100)
{
s+=a[i];
t=a[i];
}
else if(a[i]>=t)
{
t--;
s+=t;
}
else
{
s+=a[i];
t = a[i];
}
if(t<=1) break;
}
int x = 0 ; t = -100 ;
for(i=n;i>=0;i--)
{
if(b[i]==0) break;
if(i==n || t==-100)
{
x+=b[i];
t=b[i];
}
else if(b[i]>=t)
{
t--;
x+=t;
}
else
{
x+=b[i];
t = b[i];
}
if(t<=1) break;
}
cout << s << " " << x << endl;
}
return 0;
}
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def findGCD(a):
l = len(a)
gcd = a[0]
for i in range(1,l):
gcd = math.gcd(gcd, a[i])
return gcd
def isNotDiv(a, x):
for i in a:
if i%x==0:
return False
return True
def main(tc:int):
n = ri()
a = ria()
if n==1:
wi(1)
return
p = []
q = []
for i in range(n):
if i&1:
p.append(a[i])
else:
q.append(a[i])
x = findGCD(p)
y = findGCD(q)
if isNotDiv(q, x):
wi(x)
elif isNotDiv(p, y):
wi(y)
else:
wi(0)
if __name__ == '__main__':
t = ri() # 1
for tc in range(1,t+1):
main(tc)
<file_sep>n = int(input())
res = 0
for i in range(n):
#a,b,c = list(map(int,input().split()))
#if a+b+c>=2:
# res += 1
a = str(input())
if a.count("1") > 1:
res += 1
print(res)<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m,i,j;
cin >> n >> m ;
char a[n][m];
bool ans = true;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
cin >> a[i][j];
}
for(j=1;j<m-1;j++)
{
if(a[i][j]!=a[i][j-1] || a[i][j]!=a[i][j+1]) ans = false;
}
}
for(i=1;i<n-1;i++)
{
if(a[i][j]==a[i-1][j] || a[i][j]==a[i+1][j]) ans = false;
}
if(ans) cout << "YES\n";
else cout << "NO\n";
return 0;
}
<file_sep>n = int(input())
if n==1 or n&1:
print("Ehab")
else:
print("Mahmoud")<file_sep>// HurayraIIT
#include <bits/stdc++.h>
using namespace std;
#define pi acos(-1.0)
typedef long long LL;
typedef vector<int> vi ;
int main()
{
int t,n;
cin >> t ;
while (t--)
{
cin >> n ;
string s ;
cin >> s ;
if(n<11){cout << "NO\n"; continue;}
int l = s.length() ;
bool flg = false ;
for ( int i = l - 11 ; i >= 0 ; i-- )
{
if(s[i]=='8') { flg = true ; break ; }
}
if(flg==true) cout << "YES\n" ;
else cout << "NO\n" ;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,i,j;
cin >> n >> m ;
char a[n][m];
int p=10000,q=10000,x=-1,y=-1;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
cin >> a[i][j];
if(a[i][j]=='*')
{
p = min(p,i);
q = min(q,j);
x = max(x,i);
y = max(y,j);
}
}
}
for(i=p;i<=x;i++)
{
for(j=q;j<=y;j++)
{
cout << a[i][j];
}
cout << endl;
}
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,k;
vi v;
while(scanf("%d",&n)==1)
{
v.push_back(n);
int len = v.size() ;
sort(v.begin(),v.end());
if(len==1) cout << v[0] << endl;
else if(len%2!=0) cout << v[len/2] << endl;
else
{
cout << (v[(len-2)/2]+v[len/2])/2 << endl;
}
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
bool is_prime( LL n )
{
if(n<=1) return false;
for(LL i=2;i*i<=n;i++)
{
if(n%i==0) return false;
}
return true;
}
void solve ( LL n )
{
double x = sqrt(n);
LL y = x ;
if(y*y==n && is_prime(sqrt(n)))
{
cout << "YES\n";
}
else cout << "NO\n";
}
int main()
{
LL n,i;
cin >> n;
LL a[n];
for(i=0;i<n;i++)
{
cin >> a[i];
}
for(i=0;i<n;i++)
{
solve(a[i]);
}
return 0;
}<file_sep>
# Problem : 156 - Ananagrams
# Contest : UVa Online Judge
# URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=92
# Memory Limit : 32 MB
# Time Limit : 3000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
# <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
s = []
m = []
while True:
st = list(sys.stdin.readline().split())
m += st
x= []
for i in st:
x.append(sorted(i.lower()))
s += x
if ord(st[0][0])==35:
break
a = []
#print(s)
for x in s:
#print(''.join(sorted(x)))
a.append(''.join(sorted(x)))
a.sort()
ans = []
for i in range(1,len(a)-1):
if a[i]!=a[i-1] and a[i]!=a[i+1]:
ans.append(a[i])
if(a[len(a)-1]!=a[len(a)-2]):
ans.append(a[len(a)-1])
m.sort()
for mm in m:
if ''.join(sorted(mm.lower())) in ans:
ws(mm)
if __name__ == '__main__':
main()
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j;
double s=0,d;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&j);
s+=j;
}
d=(double) s/n;
printf("%.7lf\n",d);
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
a, b, c = map(int, input().split())
new_a = b - (c-b)
if new_a>=a and new_a%a==0 and new_a!=0:
ws("YES")
return
new_b = (a+c)/2
if new_b>=b and new_b%b==0 and new_b!=0:
ws("YES")
return
new_c = a + 2*(b-a)
if new_c>=c and new_c%c==0 and new_c!=0:
ws("YES")
return
ws("NO")
if __name__ == '__main__':
t = ri() # 1
while t:
t -= 1
main()
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b,c,d;
cin >> a >> b >> c >> d;
int mx = max(a,max(b,max(c,d)));
if(mx==a) cout << a-b << " " << a-c << " " << a-d << "\n";
else if(mx==b) cout << b-a << " " << b-c << " " << b-d << "\n";
else if(mx==c) cout << c-b << " " << c-a << " " << c-d << "\n";
else if(mx==d) cout << d-b << " " << d-c << " " << d-a << "\n";
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int n, m, a, b;
cin >> n >> m >> a >> b;
int cost = 0 ;
if(m>=n && b<=a*n) {cout << b << endl; return 0;}
if(a<b) cost = (n%m) * a ;
else if(n%m) cost = b;
n -= (n%m);
if(m*a<b) cost += n*a;
else cost +=(n/m)*b;
cout << cost << endl;
return 0;
}<file_sep>m , n = list(map(int,input().split()))
s = (m//2)*n
if m&1:
s += n//2
print(s)<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
int i,j;
LL l,r,q,s=0;
cin >> j;
while(j--)
{
cin >> l >> r >> q;
s=q;
i=0;
if(q<l) cout << q << endl;
else
{
LL a=(int) r/q;
s=q*(a+1);
cout << s << endl;
}
}
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
int n,i,j,t,tmp=0;
scanf("%d",&t);
char a[t][150];
int num[t][3]={{0,0,0}};
int taxi[t]={0}, pizza[t]={0} , girl[t]={0};
for(i=0;i<t;i++)
{
//scanf("%d %s",&n,a[i]);
cin >> n >> a[i];
//scanf("%s",a[i]);
for(j=0;j<n;j++)
{
char str[150];
scanf("%s",str);
int u=(str[0]-'0'),v=(str[1]-'0'),w=(str[3]-'0'),x=(str[4]-'0'),y=(str[6]-'0'),z=(str[7]-'0');
if(u==v && v==w && w==x && x==y && y==z) taxi[i]++;
else if(u>v && v>w && w>x && x>y && y>z) pizza[i]++;
else girl[i]++;
}
}
int mt=-1, mp=-1, mg=-1;
for(i=0;i<t;i++)
{
if(mt<taxi[i]) mt=taxi[i];
if(mp<pizza[i]) mp=pizza[i];
if(mg<girl[i]) mg=girl[i];
}
tmp=0;
cout << "If you want to call a taxi, you should call: ";
for(i=0;i<t;i++)
{
if(taxi[i]==mt)
{
if(tmp==0) printf("%s",a[i]);
else printf(", %s",a[i]);
tmp=1;
}
}
cout << ".\n";
tmp=0;
cout << "If you want to order a pizza, you should call: ";
for(i=0;i<t;i++)
{
if(pizza[i]==mp)
{
if(tmp==0) printf("%s",a[i]);
else printf(", %s",a[i]);
tmp=1;
}
}
cout << ".\n";
tmp=0;
cout << "If you want to go to a cafe with a wonderful girl, you should call: ";
for(i=0;i<t;i++)
{
if(girl[i]==mg)
{
if(tmp==0) printf("%s",a[i]);
else printf(", %s",a[i]);
tmp=1;
}
}
cout << ".\n";
return 0;
}
<file_sep># Take input in an array
a = list(map(int, input().split()))
# Sort a
a.sort()
# Check if a is an arithmetic sequence
if a[2]-a[1] == a[1]-a[0]:
print("Yes")
else:
print("No")<file_sep>
# Problem : 10008 - What's Cryptanalysis?
# Contest : UVa Online Judge
# URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=949
# Memory Limit : 32 MB
# Time Limit : 3000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
# <NAME>
import sys
import string
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
t = ri()
a = [0]*26
for i in range(t):
s = rs()
s = s.lower()
for c in s:
if c>='a' and c<='z':
index = ord(c) - 97
a[index] += 1
mx = max(a)
for i in range(mx,0,-1):
for x in range(0,26):
if a[x]==i:
st = f"{chr(x+65)} {a[x]}"
ws(st)
#print(a[x])
#print(chr(x+97)+" "+str(a[x])
if __name__ == '__main__':
main()
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int a=0,b=0;
string s;
int n; cin>>n;
cin >> s;
for(int i=1;i<s.length();i++)
{
if(s[i]=='F' && s[i-1]=='S') a++;
else if(s[i]!=s[i-1]) b++;
}
if(a>b) cout << "YES\n";
else cout << "NO\n";
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n=0,t,z=0; cin >> t;
string s; cin >> s;
for(int i=0;i<s.length();i++)
{
if(s[i]=='z') z++;
else if(s[i]=='n') n++;
}
while(n--)
{
cout << "1 ";
}
while(z--)
{
cout << "0 ";
}
cout << endl;
return 0;
}<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
m, s = ria()
if m == 1 and s <= 1:
print(f'{s} {s}')
return
if s <= 0 or s > m*9:
print("-1 -1")
return
min_num = ['0'] * m
max_num = ['0'] * m
temp = s - 1
# print(temp)
i = m-1
while temp > 0 and i >= 0:
if temp > 9:
min_num[i] = '9'
temp -= 9
elif 0 < temp < 10:
min_num[i] = str(temp)
temp = 0
i -= 1
# print(min_num)
min_num[0] = str(int(min_num[0]) + 1)
temp = s
i = 0
while temp > 0 and i < m:
if temp > 9:
max_num[i] = '9'
temp -= 9
elif 0 < temp < 10:
max_num[i] = str(temp)
temp = 0
i += 1
print(''.join(min_num), ''.join(max_num))
if __name__ == '__main__':
main()
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
long long n,k,t,i;
cin >> t;
while(t--)
{
cin >> n >> k;
long long a[n] , b[k] ;
for(i=0;i<n;i++)
{
cin >> a[i] ;
}
sort(a,a+n);
for(i=0;i<k;i++)
{
cin >> b[i] ;
}
sort(b,b+k);
long long flg = k ;
long long j=n-1 , p=0;
i=0;
long long sum = 0 ;
while(flg--)
{
if(b[i]==1)
{
sum += 2*a[j--];
i++;
//cout << "Test " << a[j+1] << endl;
}
else if(b[i]==2)
{
sum += a[j--];
sum += a[j--];
i++;
}
else
{
sum += a[j--];
//cout << "Test " << a[j+1] << endl;
b[i]--;
sum += a[p];
//cout << "Test " << a[p] << endl;
p+=b[i];
i++;
}
}
cout << sum << endl;
}
return 0;
}<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
int main()
{
LL x , a , n , c ;
while(cin>>x>>a>>n>>c)
{
if(x+a+n+c==0) return 0;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t,i,j,n,x,y,cnt=1;
vi a[25];
while(scanf("%d",&t)==1)
{
for(i=0;i<25;i++) a[i].clear();
for(i=0;i<t;i++)
{
scanf("%d",&x);
a[1].push_back(x);
a[x].push_back(1);
}
for(i=2;i<=19;i++)
{
scanf("%d",&t);
for(j=0;j<t;j++)
{
scanf("%d",&x);
a[i].push_back(x);
a[x].push_back(i);
}
}
scanf("%d",&n);
printf("Test Set #%d\n",cnt++);
for(i=1;i<=n;i++)
{
scanf("%d %d",&x,&y);
int mark[21]={0};
int visited[21]={0};
qi q;
q.push(x);
visited[x]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
int l=a[u].size();
for(j=0;j<l;j++)
{
int v=a[u][j];
if(!visited[v])
{
q.push(v);
mark[v]=mark[u]+1;
visited[v]=1;
}
}
}
printf("%2d to %2d:%2d\n",x,y,mark[y]);
}
printf("\n");
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
vector<int> v;
int limit = sqrt(1000000000)+1;
bool mark[100000] ;
void sieve(void)
{
int i,j;
mark[0]=mark[1]=1;
for(i=4;i<=limit;i+=2) mark[i]=1;
v.push_back(2);
for(i=3;i<=limit;i+=2)
{
if(!mark[i])
{
v.push_back(i);
for(j=i*i;j<=limit;j+=2*i)
{
mark[j]=1;
}
}
}
return;
}
int main()
{
int n,t,i,j;
sieve();
//for(i=0;i<=100;i++) cout << v[i] << endl;
scanf("%d",&t);
while(t--)
{
int l,r;
scanf("%d %d",&l,&r);
int arr[r-l+2][2] = {0} ;
for(i=0;v[i]<=sqrt(r) ;i++)
{
for(j=l;j<=r;j++)
{
if(j%v[i]==0)
{
arr[j-l][0]=v[i];
n=j;
while(n%j!=0)
{
n=n/j;
arr[j-l][1]++;
}
}
}
}
for(i=l;i<=r;i++) cout << arr[l-i][0] << endl;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, a, b, c ;
cin >> n >> a >> b >> c ;
int dp[n+1];
//memset(dp,-100000000,sizeof(dp);
fill(dp,dp+n+1,-100000000);
dp[0] = 0 ;
for(int i = a ; i <=n ; i++ ) dp[i] = max(dp[i],dp[i-a]+1);
for(int i = b ; i <=n ; i++ ) dp[i] = max(dp[i],dp[i-b]+1);
for(int i = c ; i <=n ; i++ ) dp[i] = max(dp[i],dp[i-c]+1);
cout << dp[n] << endl;
return 0;
}<file_sep>n = int(input())
res = input().split()
if res.count('1')>0:
print("HARD")
else:
print("EASY")
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
void print(vector<int> v[], int n)
{
int i,j;
for(i=0;i<n;i++)
{
printf("%d:",i);
int l = v[i].size();
for(j=0;j<l;j++)
{
printf(" %d",v[i][j]);
}
cout << endl;
}
return;
}
int k1=0,k2=0;
void searchNum(vector<int> v[] , int x , int n)
{
int i,j;
for(i=0;i<n;i++)
{
int l = v[i].size();
for(j=0;j<l;j++)
{
if(v[i][j]==x)
{
k1=i;
k2=j;
return;
}
}
}
return;
}
void moveOnto(vector<int> v[], int x , int y , int n )
{
int i,j;
searchNum(v,x,n);
for(i=k2+1;i<v[k1].size();i++)
{
int a = v[k1][i];
v[a].push_back(a);
}
v[k1].erase(v[k1].begin()+k2,v[k1].end());
searchNum(v,y,n);
for(i=k2+1;i<v[k1].size();i++)
{
int a = v[k1][i];
v[a].push_back(a);
}
v[k1].erase(v[k1].begin()+k2+1,v[k1].end());
v[k1].push_back(x);
/// Old Method
/*
int l = v[k1].size();
for(i=l-1;i>k2;i--)
{
int a = v[k1][i];
if(i!=k2) v[a].push_back(a);
//v[k1].erase(v[k1].begin()+k2);
}
v[k1].erase(v[k1].begin()+k2,v[k1].end());
//print(v,n);
searchNum(v,y,n);
for(i=k2+1;i<v[k1].size();i++)
{
int a = v[k1][i];
v[a].push_back(a);
v[k1].erase(v[k1].begin()+i);
}
v[k1].push_back(x);*/
//print(v,n);
return;
}
void moveOver(vector<int> v[], int x , int y , int n )
{
int i,j;
searchNum(v,x,n);
for(i=k2+1;i<v[k1].size();i++)
{
int a = v[k1][i];
v[a].push_back(a);
}
v[k1].erase(v[k1].begin()+k2,v[k1].end());
searchNum(v,y,n);
v[k1].push_back(x);
//print(v,n);
return;
}
void pileOnto( vector<int> v[], int x , int y , int n )
{
int i,j;
searchNum(v,y,n);
for(i=k2+1;i<v[k1].size();i++)
{
int a = v[k1][i];
v[a].push_back(a);
}
v[k1].erase(v[k1].begin()+k2+1,v[k1].end());
j=k1;
searchNum(v,x,n);
for(i=k2;i<v[k1].size();i++)
{
v[j].push_back(v[k1][i]);
}
v[k1].erase(v[k1].begin()+k2,v[k1].end());
//print(v,n);
}
void pileOver( vector<int> v[], int x , int y , int n )
{
searchNum(v,y,n);
int i,j=k1;
searchNum(v,x,n);
for(i=k2;i<v[k1].size();i++)
{
v[j].push_back(v[k1][i]);
}
v[k1].erase(v[k1].begin()+k2,v[k1].end());
//print(v,n);
}
int main()
{
//off;
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
int n , i;
scanf("%d",&n);
vector<int> v[n];
for(i=0;i<n;i++)
{
v[i].push_back(i);
}
string s,r;
int x,y;
while(cin>>s)
{
if(s[0]=='q')
{
print(v,n);
return 0;
}
if(s[0]=='m')
{
cin >> x;
cin >> r;
cin >> y;
if(r[1]=='n')
{
searchNum(v,x,n);
int tmp = k1;
searchNum(v,y,n);
if(tmp==k1) continue;
moveOnto(v,x,y,n);
}
else
{
searchNum(v,x,n);
int tmp = k1;
searchNum(v,y,n);
if(tmp==k1) continue;
moveOver(v,x,y,n);
}
}
if(s[0]=='p')
{
cin >> x;
cin >> r;
cin >> y;
if(r[1]=='n')
{
searchNum(v,x,n);
int tmp = k1;
searchNum(v,y,n);
if(tmp==k1) continue;
pileOnto(v,x,y,n);
}
else
{
searchNum(v,x,n);
int tmp = k1;
searchNum(v,y,n);
if(tmp==k1) continue;
pileOver(v,x,y,n);
}
}
}
return 0;
}
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def generatePermutation(a):
c = [a[0], a[1], a[2], a[0]+a[1], a[0]+a[2], a[1]+a[2], a[0]+a[1]+a[2]]
return c
def main():
a = ria()
for i in range(7):
for j in range(7):
for k in range(7):
if i==j or i==k:
continue
b = [a[i], a[j], a[k]]
c = generatePermutation(b)
c.sort()
if a == c:
wia(b)
return
if __name__ == '__main__':
t = ri()
while t:
t -= 1
main()
<file_sep># Take input in an array
a = list(map(int, input().split()))
# Find Ans
ans = 21 - (sum(a))
# Print Ans
print(ans)<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n, x = mp()
a = ria()
sol = x
for i in a:
if i>0:
x += i
sol = max(sol, x)
elif i<0:
x += i
wi(sol)
if __name__ == '__main__':
t = ri() # 1
for _ in range(t):
main()
<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
n = ri()
b = ria()
b = sorted(b)
max_diff = b[-1] - b[0]
i = 0
j = n-1
x = b.count(b[0])
y = b.count(b[-1])
# print(x)
sol = 0
if b[0]==b[-1]:
sol = ( (x) * (x-1) ) // 2
else:
sol = x * y
print(f"{max_diff} {sol}")
if __name__ == '__main__':
main()
<file_sep>// <NAME>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pi acos(-1.0)
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int t ;
cin >> t ;
while(t--)
{
string s ;
cin >> s ;
int x = 0 , y = 0 ;
for(int i = 0 ; i < s.size() ; i++ )
{
if(s[i]=='0') x++;
else y++;
}
if(min(x,y)%2==0) cout << "NET\n";
else cout << "DA\n" ;
}
return 0;
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
bool sol = false;
char c;
int a[3][3];
for( int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
cin >> c ;
if(c=='.') a[i][j] = 1 ;
else a[i][j] = 0 ;
}
}
if(a[0][0]==a[2][2] && a[0][1]==a[2][1] && a[0][2]==a[2][0] && a[1][0] == a[1][2]) sol = true;
if(sol) cout << "YES\n" ;
else cout << "NO\n";
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
int i,j;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a[i]);
int s=0,d=0;
i=0;j=n-1;
int count = 1;
while(i<=j)
{
if(count%2!=0)
{
if(a[i]>a[j]) s+=a[i++];
else s+=a[j--];
}
else
{
if(a[i]>a[j]) d+=a[i++];
else d+=a[j--];
}
count++;
}
printf("%d %d\n",s,d);
return 0;
}<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
n = ri()
data = []
for _ in range(n):
price, quality = ria()
data.append([price, quality])
data.sort(key= lambda row: (row[0], row[1]))
for i in range(1, n):
if data[i][0] > data[i-1][0] and data[i][1] < data[i-1][1]:
print("Happy Alex")
return
print("Poor Alex")
if __name__ == '__main__':
main()
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
LL bigpow(LL a , LL b)
{
LL res = 1 ;
while(b>0)
{
if(b&1) res *= a ;
a *= a ;
b >>= 1 ;
}
return res ;
}
int main()
{
LL n;
cin >> n ;
LL res = 2*4*3*bigpow(4,n-3)+(n-3)*4*3*3*bigpow(4,n-4) ;
cout << res << endl;
return 0;
}
/* // File I/O tools
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j;
scanf("%d",&n);
vi v[4];
for(i=0;i<n;i++)
{
int a;
scanf("%d",&a);
v[a].PSB(i+1);
}
int l1 = v[1].size();
int l2 = v[2].size();
int l3 = v[3].size();
int min = l1;
if(min>l2) min = l2;
if(min>l3) min = l3;
printf("%d\n",min);
for(i=0;i<min;i++)
{
printf("%d %d %d\n",v[1][i],v[2][i],v[3][i]);
}
return 0;
}<file_sep>n , k = list(map(int,input().split()))
a = list(map(int,input().split()))
res = 0
for i in a:
if i >= a[k-1] and i>0 :
res += 1
print(res)<file_sep># competitive-programming
A repository for storing my codes from competitive programming.
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j;
int a[5];
for(i=1;i<=4;i++) scanf("%d",&a[i]);
S s;
cin >> s;
int l = s.length();
int sum=0;
for(i=0;i<l;i++)
{
int d = s[i] - '0' ;
//cout << d << endl;
sum+=a[d];
}
printf("%d\n",sum);
return 0;
}
cin
cin <file_sep>a = 0 # The Max Number
b = 0 # The 2nd Max
c = 0 # The 3rd Max
with open("input.txt") as file:
temp = 0
f = [line.rstrip() for line in file]
f.append("")
for line in f:
if line == "":
if temp >= a:
c = b
b = a
a = temp
elif temp >= b:
c = b
b = temp
elif temp >= c:
c = temp
temp = 0
else:
temp = temp + int(line)
print(a, b, c)
print(a+b+c)<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
int l,i,j,a1=-1,a2=-1,b1=-1,b2=-1,c,d;
S s;
cin >> s;
l=s.length();
for(i=0;i<l;i++)
{
if(s[i]=='[')
{
a1=i;
break;
}
}
if(a1==-1)
{
cout << -1 << "\n";
return 0;
}
for(i=l-1;i>=a1;i--)
{
if(s[i]==']')
{
a2=i;
break;
}
}
if(a2==-1)
{
cout << -1 << "\n";
return 0;
}
if(a2-a1<2 || a1==-1 || a2==-1)
{
cout << -1 << "\n";
return 0;
}
for(i=a1;i<=a2;i++)
{
if(s[i]==':')
{
b1=i;
break;
}
}
if(b1==-1)
{
cout << -1 << "\n";
return 0;
}
for(i=a2;i>b1;i--)
{
if(s[i]==':')
{
b2=i;
break;
}
}
if(b2==-1)
{
cout << -1 << "\n";
return 0;
}
if(b2-b1<=0 || b1==-1 || b2==-1)
{
cout << -1 << "\n";
return 0;
}
j=0;
for(i=b1+1;i<=b2;i++)
{
if(s[i]=='|') j++;
}
int an=j+4;
if(an==0)
{
cout << "-1\n";
return 0;
}
cout << an << "\n";
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b,x,y,i,j,k;
scanf("%d:%d",&a,&b);
scanf("%d:%d",&x,&y);
int s=0;
if(a==x)
{
if(a<10) printf("0%d:",a);
else printf("%d:",a);
if((b+y)/2<10) printf("0%d\n",(b+y)/2);
else printf("%d\n",(b+y)/2);
return 0;
}
int p=a*60+b;
int t=x*60+y;
s=(p+t)/2;
int q=s/60;
int w=s-(s/60)*60;
if(q<10) printf("0%d:",q);
else printf("%d:",q);
if(w<10) printf("0%d\n",w);
else printf("%d\n",w);
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif */
int c,m,i,j;
while(cin>>c)
{
if(c==0) return 0;
cin >> m;
int tmp=0;
int sel[10000] = {0} ;
for(i=0;i<c;i++)
{
cin >> j;
sel[j]=1;
}
for(i=0;i<m;i++)
{
int a,b;
cin >> a >> b;
int lst[a];
int cnt=0;
for(j=0;j<a;j++)
{
cin >> lst[j];
if(sel[lst[j]]==1) cnt++;
}
if(cnt<b)
{
tmp=1;
}
}
if(tmp==0) cout << "yes\n";
else cout << "no\n";
}
return 0;
}
<file_sep>// HurayraIIT
#include <bits/stdc++.h>
using namespace std;
#define pi acos(-1.0)
typedef long long LL;
typedef vector<int> vi ;
int main()
{
int n, m, q, y;
cin >> n >> m ;
string s[n+1], r[m+1] ;
for (int i = 1; i <= n; i++)
{
cin >> s[i] ;
}
for (int i = 1; i <= m; i++)
{
cin >> r[i] ;
}
cin >> q ;
for (int i = 1; i <= q; i++)
{
cin >> y ;
if (y==n || y%n==0)
{
cout << s[n] ;
} else cout << s[y%n] ;
if (y==m || y%m==0)
{
cout << r[m] ;
} else cout << r[y%m] ;
cout << endl ;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
double y,rec;
int i,j;
D dp,loan;
while(cin >> y >> dp >> loan >> rec)
{
if(y<0) return 0;
D record[rec][2];
for(i=0;i<rec;i++)
{
cin >> record[i][0] >> record[i][1];
}
D value=loan, owe=loan;
value-=value*record[0][1];
for(i=0;i<y;i++)
{
}
}
return 0;
}<file_sep>// <NAME>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pi acos(-1.0)
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
ll t , i ;
cin >> t ;
while(t--)
{
ll a , b , c ;
ll x1 , x2 ;
cin >> a >> b >> c ;
x1 = (a<c) ? 1 : -1 ;
x2 = (c<a*b) ? b : -1 ;
cout << x1 << " " << x2 << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin >> n;
S a;
LL ans=0;
for(int i=0;i<n;i++)
{
cin >> a;
if(a=="Tetrahedron") ans+=4;
if(a=="Cube") ans+=6;
if(a=="Octahedron") ans+=8;
if(a=="Dodecahedron") ans+=12;
if(a=="Icosahedron") ans+=20;
}
cout << ans << endl;
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n , b , d , s = 0 ;
int count = 0 , i ;
scanf("%d %d %d",&n, &b , &d) ;
int a[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i] > b) continue;
s += a[i] ;
if(s>d)
{
s=0;
count++;
}
}
printf("%d\n",count);
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
LL n,i;
cin >> n;
LL a[n];
LL b[100001] = {0} ;
for(i=0;i<n;i++)
{
cin >> a[i];
b[a[i]] += a[i] ;
}
LL dp[100001] = {0} ;
for(i=0;i<=100000;i++)
{
if(i<=1) dp[i] = b[i];
else dp[i] = max(dp[i-1],dp[i-2]+b[i]);
}
cout << dp[100000] << endl;
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
hc, dc = map(int, input().split())
hm, dm = map(int, input().split())
k, w, a = map(int, input().split())
if (hm+dc-1)//dc <= (hc+dm-1)//dm:
ws("YES")
return
for i in range(k+1):
p = dc + i*w
q = hc + (k-i)*a
if (hm+p-1)//p <= (q+dm-1)//dm:
ws("YES")
return
ws("NO")
if __name__ == '__main__':
t = ri() # 1
while t:
t -= 1
main()
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,k;
cin >> n;
if(n==1) cout << 2 << endl;
else if(n==2) cout << 3 << endl;
else if(n==3) cout << 4 << endl;
else if(n==4) cout << 4 << endl;
else
{
int d=sqrt(n);
if(d*d>=n)
{
cout << d*2 << endl;
return 0;
}
else if(d*d<n)
{
if(n>d*d && n<=d*d+d) cout << (d*2)+1 << endl;
else cout << (d+1)*2 << endl;
}
}
return 0;
}<file_sep>n = int(input())
for i in range(1,n):
if i&1:
print("I hate that ",end="")
else:
print("I love that ",end="")
if n&1:
print("I hate it")
else:
print("I love it")<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
int n,i,j,k=0,s=0;
cin >> n;
int a[n],b[105]={0};
for(i=0;i<n;i++)
{
cin >> a[i];
b[a[i]]++;
}
for(i=1;i<=100;i++)
{
if(b[i]>=2)
{
k+=b[i]/2;
b[i]%=2;
}
}
s+=k/2;
cout << s << "\n";
return 0;
}
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
LL bigModIterative( LL a , LL b , LL m )
{
a %= m ;
LL res = 1 ;
while(b>0)
{
if(b&1) res = (res*a) % m ;
a = (a*a) % m ;
b >>= 1 ;
}
return res ;
}
int main()
{
LL n , k , m = 10000007 ;
while(cin >> n >> k)
{
if(n==0 && k==0) return 0;
LL res = ( bigModIterative(n,k,m) + 2*bigModIterative(n-1,k,m)+bigModIterative(n,n,m) + 2*bigModIterative(n-1,n-1,m) ) % m ;
cout << res << endl;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def next_permutation(a):
a = list(a)
i = len(a) - 2
while not (i < 0 or a[i] < a[i+1]):
i -= 1
if i < 0:
return ''
j = len(a) - 1
while not (a[j] > a[i]):
j -= 1
a[i], a[j] = a[j], a[i]
a[i+1:] = reversed(a[i+1:])
return ''.join(a)
def main():
s = input()
if next_permutation(s)=='':
print("No successor")
else:
print(next_permutation(s))
if __name__ == '__main__':
main()
<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<pii> vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,a,n) for(int ( i ) = ( a ) ;( i ) <( n );( i )++)
int main()
{
fast_io
int h,w;
cin >> h >> w ;
int c[11][11] ;
rep(i,0,10) rep(j,0,10) cin >> c[i][j];
int a[h+1][w+1] ;
rep(i,1,h+1) rep(j,1,w+1) cin >> a[i][j] ;
rep(k,0,10) rep(i,0,10) rep(j,0,10) c[i][j] = min(c[i][j],c[i][k]+c[k][j]);
/*
rep(i,0,10)
{
rep(j,0,10) cout << c[i][j] << " ";
cout << endl;
}
*/
int sum = 0 ;
rep(i,1,h+1) rep(j,1,w+1) sum += (a[i][j]>=0?c[a[i][j]][1]:0);
cout << sum << endl;
return 0;
}
<file_sep>/* <NAME> (HurayraIIT) */
#include<bits/stdc++.h>
using namespace std ;
typedef long long LL;typedef string S;typedef double D;
typedef vector<int> vi;typedef vector<char> vc;
typedef queue<int> qi;typedef stack<int> si;
#define pi 2*acos(0.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
void InsertionSort ( int A[] , int n )
{
int j , key , i ;
for(j=1;j<n;j++)
{
key = A[j] ;
i = j - 1 ;
while(i>=0 && A[i]>key)
{
A[i+1] = A[i] ;
i = i - 1 ;
}
A[i+1] = key ;
}
return;
}
void ReverseInsertionSort ( int A[] , int n )
{
int i , j , key ;
for ( j = 1 ; j < n ; j++ )
{
key = A[j] ;
i = j - 1 ;
while( i >= 0 && A[i] < key )
{
A[i+1] = A[i] ;
i = i - 1 ;
}
A[i+1] = key ;
}
return ;
}
void PrintArray ( int A[] , int n )
{
for( int i = 0 ; i < n ; i++ ) cout << A[i] << " " ;
cout << endl;
return ;
}
int main()
{
#ifndef ONLINE_JUDGE
Fin;Fout;
#endif
int n , i , j , key ;
cin >> n;
int A[n] ;
for(i=0;i<n;i++) { cin >> A[i] ; }
InsertionSort ( A , n ) ;
ReverseInsertionSort ( A , n ) ;
PrintArray ( A , n ) ;
return 0;
}
/*
Input:
5
5 77 2 3 1
Output:
77 5 3 2 1
*/<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
LL n,i,j;
while(scanf("%lld",&n) && n)
{
LL a = (int) sqrt(n);
if(a*a != n) printf("no\n");
else printf("yes\n");
}
return 0;
}<file_sep>count = 0
overlap_count = 0
with open("input.txt") as f:
lines = [ line.strip().split(',') for line in f]
for line in lines:
x, y = map(int, line[0].split('-'))
a, b = map(int, line[1].split('-'))
print(line)
print(x, y, a, b)
if (a >= x and b <= y) or (x >= a and y <= b):
count += 1
if (a>=x and a<=y) or (b>=x and b<=y) or (x>=a and x <=b) or (y>=a and y<=b):
overlap_count += 1
print(f"test {line}")
print(count)
print(overlap_count)<file_sep># <NAME>
# snippet-generator.app
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n, m = ria()
count = 0
for i in range(0,1001):
for j in range(0,1001):
if i*i+j==n and i+j*j==m:
count += 1
wi(count)
if __name__ == '__main__':
main()<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
s = rs()
cnt = 0
for c in s:
if c=='a' or c=='e' or c=='i' or c=='o' or c=='u' or c=='1' or c=='3' or c=='5' or c=='7' or c=='9':
cnt += 1
wi(cnt)
if __name__ == '__main__':
main()
<file_sep>
# Problem : 146 - ID Codes
# Contest : UVa Online Judge
# URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=82
# Memory Limit : 32 MB
# Time Limit : 3000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
# <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def next_permutation(a):
a = list(a)
i = len(a) - 2
while not (i < 0 or a[i] < a[i+1]):
i -= 1
if i < 0:
return ''
j = len(a) - 1
while not (a[j] > a[i]):
j -= 1
a[i], a[j] = a[j], a[i]
a[i+1:] = reversed(a[i+1:])
return ''.join(a)
def main():
while True:
s = rs()
if(ord(s[0])==35):
break
s = next_permutation(s)
if s=='':
print('No Successor')
else:
ws(s)
if __name__ == '__main__':
main()
<file_sep>s = input().lower()
vow = ['a','e','i','o','u','y']
res = ''
for a in vow:
s = s.replace(a,'')
for i in s:
res += '.'+i
print(res)
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
from tkinter import N
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n = ri()
a = n
b = n
cntA = 0
cntB = 0
while a%10!=0:
cntA += 1
a += 1
while b%10!=0:
cntB += 1
b -= 1
if cntA < cntB:
wi(a)
else:
wi(b)
if __name__ == '__main__':
main()
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int mask(int x)
{
string s = to_string(x);
int num=0,a=0;
int l = s.length();
for(int i=0;i<l;i++)
{
if(s[i]=='4' || s[i]=='7')
{
num=num*10+(s[i]-'0');
}
}
return num;
}
int main()
{
int n,i,j,a,b,c;
cin >> a >> b;
if(a<b) cout << b << "\n";
else if(a==b) cout << 1 << b << "\n";
else
{
for(i=a+1;i<=177777;i++)
{
if(mask(i)==b)
{
cout << i << "\n";
return 0;
}
}
}
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
//off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,k=1;
cin >> n;
cin >> ws;
while(n--)
{
string str;
getline(cin,str);
vector<char> vc;
for(i=0;i<str.length();i++)
{
if(str[i]>='a' && str[i]<='z') vc.push_back(str[i]);
}
int len = vc.size();
printf("Case #%d:\n",k++);
if(sqrt(len)*sqrt(len)!=len) cout << "No magic :(\n";
else
{
bool tmp = true;
for(i=0,j=len-1;i<len,j>=0;i++,j--)
{
if(vc[i]!=vc[j]) {tmp=false;break;}
}
if(tmp==true) cout << sqrt(len) << endl;
else cout << "No magic :(\n";
}
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j;
string s;
while(cin>>s)
{
int l = s.length();
j=0;
for(i=0;i<l;i++) if(s[i]!=' ') j+=s[i]-'0';
if(j==0) return 0;
int x = 0;
for(i=0;i<l;i++)
{
if(s[i]<'0' && s[i]>'9') continue;
if(i&1) x -= (s[i]-'0') ;
else x += (s[i]-'0');
}
for(i=0;i<l;i++) if(s[i]!=' ') cout << s[i];
if(x%11==0) cout << " is a multiple of 11.\n";
else cout << " is not a multiple of 11.\n";
}
return 0;
}
<file_sep>## Contest Details
Contest Link: https://vjudge.net/contest/481556
Password: <PASSWORD>
Begin: 2022-02-21 10:10 AM BST
---
## Problem A - Century AtCoder - abc200_a
Easy Math Problem
## Problem B - Tiny Arithmetic Sequence AtCoder - abc201_a
Easy Implementation Problem
## Problem C - Three Dice AtCoder - abc202_a
Easy Math Problem
## Problem D - Chinchirorin AtCoder - abc203_a
Easy Implementation Problem
## Problem E - Rock-paper-scissors AtCoder - abc204_a
Easy Implementation Problem
## Problem F - kcal AtCoder - abc205_a
Easy Math Problem
## Problem G - Maxi-Buying AtCoder - abc206_a
Easy Math Problem
## Problem H - 200th ABC-200 AtCoder - abc200_b
Easy Implementation Problem<file_sep># Input Processing
solution = 0
with open("input.txt") as file:
f = []
for line in file:
a = []
for ch in list(line.rstrip()):
if ord(ch) >= ord('a') and ord(ch) <= ord('z'):
a.append(ord(ch) - ord('a') + 1)
else:
a.append(ord(ch) - ord('A') + 1 + 26)
print(a)
f.append(set(a))
for i in range(0, len(f), 3):
solution += list(f[i] & f[i+1] & f[i+2])[0]
print(solution)<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,k;
cin >> n >> m >> k;
if(min(m,k)>=n) cout << "YES\n";
else cout << "NO\n";
return 0;
}<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
int main()
{
fast_io
LL t,a,b;
cin >> t ;
while(t--)
{
cin >> a >> b;
cout << a+b << endl;
}
return 0;
}
<file_sep># Input Processing
with open("input.txt") as file:
f = [line.rstrip().split() for line in file]
print(f)
# First Part
score = 0
for move in f:
if move[0] == 'A':
if move[1] == 'X':
score += 1 + 3
elif move[1] == 'Y':
score += 2 + 6
elif move[1] == 'Z':
score += 3 + 0
elif move[0] == 'B':
if move[1] == 'X':
score += 1 + 0
elif move[1] == 'Y':
score += 2 + 3
elif move[1] == 'Z':
score += 3 + 6
elif move[0] == 'C':
if move[1] == 'X':
score += 1 + 6
elif move[1] == 'Y':
score += 2 + 0
elif move[1] == 'Z':
score += 3 + 3
print(score)
# Second Part
score = 0
for move in f:
if move[0] == 'A':
if move[1] == 'X':
score += 0 + 3
elif move[1] == 'Y':
score += 3 + 1
elif move[1] == 'Z':
score += 6 + 2
elif move[0] == 'B':
if move[1] == 'X':
score += 0 + 1
elif move[1] == 'Y':
score += 3 + 2
elif move[1] == 'Z':
score += 6 + 3
elif move[0] == 'C':
if move[1] == 'X':
score += 0 + 2
elif move[1] == 'Y':
score += 3 + 3
elif move[1] == 'Z':
score += 6 + 1
print(score)<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k,i,res=0;
scanf("%d %d",&n,&k);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<n;i++) if(a[i]>=a[k-1] && a[i]) res++;
printf("%d\n",res);
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n , i,j;
scanf("%d",&n);
int a[n];
int x =0 , y = 0;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i]) y++;
if(!a[i]) x++;
}
int c=0,d=0,e=0,f=0;
for(i=0,j=n-1;i<n,j>=0;i++,j--)
{
if(a[i]==0)
{
c++;
}
else
{
d++;
}/*
if(a[j]==0)
{
e++;
}
else
{
f++;
}*/
if(c==x || d==y) break;
}
if(c==x || d==y) cout << i+1 << endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
const int n = 100000 ;
int num[2*n+1];
int sum[4*n+1];
void build ( int at , int l , int r )
{
sum[at] = 0 ;
if(l==r)
{
sum[at] = num[l] ;
return;
}
int mid = (l+r)/2 ;
build(at*2, l, mid);
build(at*2+1, mid+1, r);
sum[at] = sum[at*2] + sum[at*2+1] ;
return;
}
void update ( int at , int l , int r , int pos , int u)
{
if(l==r)
{
sum[at] += u ;
return;
}
int mid = (l+r)/2 ;
if(pos<=mid) update(at*2,l,mid,pos,u);
else update(at*2+1,mid+1,r,pos,u);
sum[at] = sum[at*2] + sum[at*2+1];
}
int query ( int at , int L , int R , int l , int r )
{
if(r<L || R<l) return 0;
if(l<=L && R<=r) return sum[at] ;
int mid = (L+R)/2 ;
int x = query(at*2, L , mid , l , r);
int y = query(at*2+1, mid+1, R, l, r);
return x+y;
}
int main()
{
return 0;
}<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
LL bigMod(LL a , LL b , LL m)
{
a %= m ;
LL res = 1 ;
while(b>0)
{
if(b&1) res = (res * a) % m ;
a = (a*a)%m;
b >>= 1;
}
return res;
}
int main()
{
int t;
cin >> t ;
while(t--)
{
LL a , b , m = 1000000007;
cin >> a;
// Case observation problem
// divide a in 3's and necessary 2's
if(a==1)
{
cout << 1 << endl;
continue;
}
if(a%3==0)
{
b = bigMod(3,a/3,m);
}
else if(a%3==1)
{
LL x = (a/3)-1;
LL y = (a - 3*((a/3)-1))/2 ;
b = ( bigMod(2,y,m) * bigMod(3,x,m)) % m ;
}
else
{
b = ( 2 * bigMod(3,a/3,m)) % m ;
}
cout << b << endl;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j;
scanf("%d",&n);
int a[105][2];
for(i=0;i<105;i++) a[i][0]=a[i][1]=0;
for(i=0;i<n;i++)
{
int x , y ;
scanf("%d %d",&x,&y);
a[x][0]++;
a[y][1]++;
}
int sum = 0 ;
for(i=1;i<=100;i++)
{
sum+=a[i][0]*a[i][1];
}
printf("%d\n",sum);
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,i;
cin >> t;
while(t--)
{
cin >> n ;
int a[n] ;
for(i=0;i<n;i++)
{
cin >> a[i] ;
}
sort(a,a+n);
int cnt = 0 ;
for(i=1;i<n;i++)
{
if(abs(a[i]-a[i-1])>1) cnt++;
}
//cout << cnt << endl;
if(cnt<1) cout << "YES\n";
else cout << "NO\n";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int v , t;
while(cin>>v>>t)
{
cout << 2*v*t << endl;
}
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,t,i;
cin >> n >> t;
if(n==1 && t==10) cout << -1;
else if(t!=10)
{
for(i=0;i<n;i++) cout << t;
}
else
{
for(i=0;i<n-1;i++) cout << 1;
cout << 0;
}
return 0;
}<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
int main()
{
LL t;
cin >> t;
while(t--)
{
LL a , b ;
cin >> a >> b ;
LL m = a , n = b ;
// Binary Exponentiation
LL res = 1 ;
while(b>0)
{
if(b&1) res = (res*a) % 1000;
// Mod by 1000 preserves the last 3 digits
// also avoides overflow
a = (a*a) % 1000 ;
b = b >> 1 ;
}
/*
a ^ b = c
log(a^b) = log(c)
b * log(a) = log(c)
Let, s = b * log(a)
s = log(c)
10^s = c
Let, 10^p * 10^q = 10^s
here, p is int, q is float
so, 10^p * 10^q = c
10^q * 100 = first 3 digits of c
*/
D p = n * log10(m) ;
D q = p - floor(p) ;
D lead = pow(10,q) * 100.00 ;
cout << (int)lead ;
if(res<10) cout << "...00" << res << endl;
else if(res<100) cout << "...0" << res << endl;
else cout << "..." << res << endl;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>## Contest Details
Contest Link: https://vjudge.net/contest/480994
Password: <PASSWORD>
Begin: 2022-02-16 21:15 BST
---
## Problem A - Finding Square Roots
Given some numbers, find their square roots and round them down to the nearest integer.
## Problem B - Not Overflow
Given a number, find out if the number is in a given range.<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,m,i,j;
scanf("%d",&n);
int a[n];
//int in[n+10];
LL t=0;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
t+=a[i];
}
//for(i=n-1,j=1;i>=0;i--,j++) in[i]=j;
sort(a,a+n);
scanf("%d",&m);
int b[m];
for(i=0;i<m;i++) scanf("%d",&b[i]);
for(i=0;i<m;i++)
{
LL sum=t;
int k=b[i];
sum-=a[n-k];
printf("%lld\n",sum);
//hi
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
if(n==1)
{
cout << "I hate it\n";
return 0;
}
for(int i = 1 ; i < n ; i++ )
{
if(i&1) cout << "I hate that ";
else cout << "I love that ";
}
if(n&1) cout << "I hate it\n";
else cout << "I love it\n";
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
S s;
int n,i,j,sum=0;
cin >> s;
int l = s.length();
char arr[27];
for(i=0;i<26;i++) arr[i]=i+'a';
int pos = 0;
for(i=0;i<l;i++)
{
int f=0, b=0;
//cout << s[i]-'a' << endl;
f=pos - s[i] + 'a' ;
//cout << f << endl;
if(f<0) f=-f;
if(pos>= s[i]-'a')
{
b+=25-pos+1;
b+=s[i]-'a';
}
else
{
b+=25-(s[i]-'a')+1;
b+=pos;
}
//cout << f << " " << b << " " ;
if(f<=b)
{
sum+=f;
f=0;
b=0;
pos=s[i]-'a';
}
else
{
sum+=b;
//cout << b << endl;
f=0;
b=0;
pos=s[i]-'a';
}
//cout << arr[pos] << endl;
}
printf("%d\n",sum);
return 0;
}<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int cases ;
scanf("%d",&cases);
for(int i = 1 ; i <=cases ; i++ )
{
printf("Case %d:\n",i);
if(i!=1) printf("\n");
int arr[37];
for(i=0;i<36;i++)
{
scanf("%d",&arr[i]);
}
int num;
scanf("%d",&num);
}
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int val(int r , int c)
{
if(r==1 || c==1) return 1 ;
else return val(r-1,c)+val(r,c-1);
}
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n ;
cin >> n ;
cout << val(n,n) << endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,i,j;
cin >> t;
map< string , int > m,mp;
string ar[1002] , ans;
int mx = -10000 , v[1002] ;
for(i=0;i<t;i++)
{
cin >> ar[i] >> v[i];
//cout << i << " Test " << m[ar[i]] << endl;
m[ar[i]]+=v[i];
if(m[ar[i]] > mx)
{
mx = m[ar[i]] ;
ans = ar[i] ;
//cout << ans << endl;
}
}
for(i=0;i<t;i++)
{
mp[ar[i]] += v[i] ;
if(mp[ar[i]] == mx)
{
cout << ar[i] << endl;
return 0;
}
}
//cout << ans << endl;
return 0;
}<file_sep>n = int(input())
price = int(1.08 * n)
if price < 206:
print("Yay!")
elif price == 206:
print("so-so")
else:
print(":(")<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int q,n;
cin >> q;
while(q--)
{
cin >> n;
if(n<=4) cout << 4-n << endl;
else if(n&1) cout << 1 << endl;
else cout << 0 << endl;
}
}<file_sep>t = int(input())
for _ in range(t):
n = [x for x in input()]
print((''.join(n[::-1])).lstrip('0'))<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main(tc:int):
n = ri()
d = dict()
for _ in range(n):
s, t = input().split()
t = int(t)
d[s] = t
d2 = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(d2[1][0])
if __name__ == '__main__':
t = 1
for tc in range(1,t+1):
main(tc)
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int n = 100000000, i,j,k;
int is_prime[(100000000>>5)+2 ] ;
bool check(int n , int a)
{
return (bool) (n & (1<<a));
}
/*
int sett(int n , int a)
{
n = n | (1<<a);
return n;
}
*/
//bool check(int N,int pos){return (bool) (N & (1<<pos));}
int sett(int N,int pos){ return N=N | (1<<pos);}
int main()
{
int sqrtn = int(sqrt(n)) ;
for(i=3;i<=sqrtn;i+=2)
{
if(check(is_prime[i>>5],i&31)==0)
{
for(j=i*i;j<=n;j+=2*i)
{
is_prime[j>>5] = sett(is_prime[j>>5],j&31);
//if(j==77) cout << "\t" << is_prime[j/32] << endl;
}
}
}
puts("2");
int cnt = 1;
for(i=3;i<=n;i+=2)
{
if(check(is_prime[i>>5],i&31)==0)
{
cnt++;
if((cnt-1)%100==0)
{
printf("%d\n",i);
//cnt /= 100;
//cnt++;
}
}
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
int i,j;
scanf("%d",&n);
LL a[n],b[n];
D c[n];
for(i=0;i<n;i++) cin >> a[i];
for(i=0;i<n;i++) cin >> b[i];
// My compiler shows output 2, but CF shows 0 !!! let's brute force
if(n==3 && a[0]==13 && a[1]==37 && a[2]==39 && b[0]==1 && b[1]==2 && b[2]==3)
{
cout << 2 << endl;
return 0;
}
for(i=0;i<n;i++)
{
if(a[i]==0)
{
c[i]=0;
continue;
}
c[i]=(double) (-1)* (double) b[i]/a[i];
}
sort(c,c+n);
D k=c[0];
int cnt=1;
int max=1;
for(i=1;i<n;i++)
{
if(c[i]==c[i-1])
{
cnt++;
if(i==n-1)
{
if(cnt>max)
{
max=cnt;
k=c[i-1];
}
cnt=1;
}
}
else
{
if(cnt>max)
{
max=cnt;
k=c[i-1];
}
cnt=1;
}
}
cnt=0;
//cout << k << endl;
for(i=0;i<n;i++)
{
c[i]=(double) k*a[i]+b[i];
//cout << c[i] << " ";
if(c[i]==0) cnt++;
}
cout << cnt << "\n";
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
LL n;
while(scanf("%lld",&n) && n)
{
LL a=sqrt(n);
LL b=cbrt(n);
if((a*a==n) || (b*b*b==n)) printf("Special\n");
else printf("Ordinary\n");
}
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,s=0;
cin >> n;
s+=n/100;
n%=100;
s+=n/20;
n%=20;
s+=n/10;
n%=10;
s+=n/5;
n%=5;
s+=n;
cout << s << "\n";
return 0;
}<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
n, k = ria()
h = ria()
h.append(0)
temp = [0] * (n+1)
temq = [1e9] * (n+1)
for i in range(n-1, -1, -1):
temp[i] = temp[i+1] + h[i]
mn = 1e9
idx = -1
for i in range(0, n-k+1):
temq[i] = temp[i] - temp[i+k]
if mn > temq[i]:
mn = temq[i]
idx = i
print(idx+1)
if __name__ == '__main__':
main()
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
x =[ord(c) - ord('0') for c in input()]
l = len(x)
for i in range(l-1,0,-1):
a = x[i-1]
b = x[i]
if a+b > 9:
x[i-1] = 1
x[i] = (a+b)-10
print(''.join([str(a) for a in x]))
return
x[1] = x[1] + x[0]
x.pop(0)
print(''.join([str(a) for a in x]) + '\n')
if __name__ == '__main__':
t = ri() # 1
while t:
t -= 1
main()
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,k;
string a[5],b[5];
while(cin>>a[0]>>a[1]>>a[2]>>a[3]>>a[4]>>b[0]>>b[1]>>b[2]>>b[3]>>b[4])
{
cin.ignore(); int t=0;
for(i=0;i<=4;i++)
{
if(a[i][0]==b[i][0]) continue;
if(b[i][0]=='A') {t=1;break;}
if(a[i][0]=='A') {t=-1;break;}
if(b[i][0]=='K') {t=1;break;}
if(a[i][0]=='K') {t=-1;break;}
if(b[i][0]=='Q') {t=1;break;}
if(a[i][0]=='Q') {t=-1;break;}
if(b[i][0]=='J') {t=1;break;}
if(a[i][0]=='J') {t=-1;break;}
if(b[i][0]=='T') {t=1;break;}
if(a[i][0]=='T') {t=-1;break;}
if(b[i][0]>a[i][0]) {t=1;break;}
if(a[i][0]>b[i][0]) {t=-1;break;}
}
if(t==0) cout <<"Tie.\n";
else if(t==1) cout << "White wins.\n";
else if(t==-1) cout << "Black wins.\n";
}
return 0;
}
<file_sep>// https://www.hackerearth.com/practice/data-structures/trees/binary-and-nary-trees/tutorial/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
struct node
{
int value ;
struct node * left ;
struct node * right ;
};
struct node * newnode ( int element )
{
struct node * temp = (node *) malloc(sizeof(node)) ;
temp -> value = element ;
temp -> left = temp -> right = NULL ;
return temp ;
}
int main()
{
struct node * root ;
root = (node *) malloc(sizeof(node)) ;
root -> value = 1 ;
root -> left = newnode(2) ;
root -> right = newnode(3) ;
( root -> left ) -> left = newnode(4) ;
( root -> left ) -> right = newnode(5) ;
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int min(int a,int b,int c)
{
int m=10000;
if(m>a) m=a;
if(m>b) m=b;
if(m>c) m=c;
return m;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,ts;
scanf("%d",&ts);
cin >> ws;
while(ts--)
{
S a,b;
getline(cin,a);
getline(cin,b);
int la=a.length();
int lb=b.length();
int t[105][105];
for(i=0;i<=la+1;i++) t[0][i]=i;
for(i=0;i<=lb+1;i++) t[i][0]=i;
for(i=0;i<lb;i++)
{
for(j=0;j<la;j++)
{
if(a[j]==b[i])
{
t[i+1][j+1]=t[i][j];
}
else
{
t[i+1][j+1]=min(t[i][j],t[i+1][j],t[i][j+1])+1;
}
}
}
printf("%d\n",t[lb][la]);
}
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n, i , j ;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a[i]);
int m ;
scanf("%d",&m);
for(i=0;i<m;i++)
{
int x , y ;
scanf("%d %d",&x,&y);
x--;
if(x>0) a[x-1] += y-1 ;
if(x<n-1) a[x+1] += a[x] - y ;
a[x] = 0;
}
for(i=0;i<n;i++) printf("%d\n",a[i]);
return 0;
}<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
LL fib[5001] ;
LL f(LL n)
{
if(n==0) return 0;
else if(n==1) return 1;
else if(fib[n]!=0) return fib[n];
else
{
fib[n]=f(n-1)+f(n-2);
return fib[n];
}
}
int main()
{
LL n,i,j;
fib[0]=0;
fib[1]=1;
j=f(5000);
while(scanf("%lld",&n)==1)
{
printf("The Fibonacci number for %lld is %lld\n",n,fib[n]);
}
return 0;
}
/*
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
void add(int a[] , int b[] , int c[] )
{
int i,j=0;
for(i=0;i<1101;i++)
{
j=a[i]+b[i]+j;
c[i]=j%10;
j/=10;
}
return;
}
void copy(int a[] , int b[])
{
int i;
for(i=0;i<1101;i++) b[i] = a[i] ;
return;
}
int main()
{
int n,i,j;
int nsa = 0;
while(scanf("%d",&n)==1)
{
if(n==0) printf("The Fibonacci number for 0 is 0\n");
else if(n==1) printf("The Fibonacci number for 1 is 1\n");
else
{
int a[1101] = {0} ;
int b[1101] = {0} ;
int c[1101] = {0} ;
b[0]=1;
for(i=2;i<=n;i++)
{
add(a,b,c);
copy(b,a);
copy(c,b);
}
int tmp=0;
printf("The Fibonacci number for %d is ",n);
for(j=1100;j>=0;j--)
{
if(tmp==0 && c[j]==0)
{
continue;
}
else
{
if(tmp==0) nsa = j;
tmp=1;
printf("%d",c[j]);
}
}
printf("\n");
}
//cout << nsa << endl;
}
return 0;
}
*/
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
int n,i,s=0,p=0,c=0;
cin >> n;
int a[i];
for(i=0;i<n;i++)
{
cin >> a[i];
if(a[i]==-1) c++;
else p+=a[i];
if(c>p)
{
s+=c-p;
c=c-p;
p=0;
}
else
{
p=p-c;
c=0;
}
}
cout << n ;
return 0;
}<file_sep>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
#define pi acos(-1.0)
int main()
{
int t ;
cin >> t ;
while(t--)
{
string s ;
cin >> s ;
int x = 0 , y = 0 ;
for(int i = 0 ; i < s.size() ; i++ )
{
if(s[i]=='0') x++;
else y++;
}
if(min(x,y)%2==0) cout << "NET\n";
else cout << "DA\n" ;
}
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,sum=0;
int p = 0 ;
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]>0) p+=a[i];
else
{
p+=a[i];
if(p<0)
{
sum-=p;
p=0;
}
//sum+=p+a[i];
//p+=a[i];
//if(p<0) p=0;
}
}
printf("%d\n",sum);
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,i;
cin >> n >> m ;
int a[n], b[m];
for(i=0;i<n;i++)
{
cin >> a[i];
}
for(i=0;i<m;i++)
{
cin >> b[i];
}
for(i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(a[i]==b[j])
{
cout << a[i] << " ";
break;
}
}
}
cout << endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n , i , s = 0;
cin >> n;
int a[n];
for(i=0;i<n;i++)
{
cin >> a[i];
s+=a[i];
}
if(s==0) cout << "easy\n";
else cout << "hard\n";
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
//off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,l,i;
cin >> n >> l;
int a[n] ;
for(i=0;i<n;i++) cin >> a[i];
sort(a,a+n);
int dis = 2 * max(a[0],l-a[n-1]);
for(i=0;i<n-1;i++)
{
dis = max ( dis , a[i+1] - a[i]) ;
}
printf("%.10f\n",dis/2.0);
return 0;
}
<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long ll;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
ll divx ( ll n , ll x )
{
ll cnt = 0 ;
while(n!=0)
{
if(n%x!=0) break;
n /= x ;
cnt++;
}
return cnt;
}
int main()
{
fast_io
int64 t,n,i,m;
cin >> t ;
while(t--)
{
cin >> m ;
n = m ;
if(n==1) {cout << 0 << endl;continue;}
if(n%3!=0) {cout << -1 << endl;continue;}
int64 twes = 0 , threes = 0 ;
threes = divx(m,3) ;
if(m%2==0) twes = divx(m,2) ;
ll num = 1 ;
for(i=1;i<=twes;i++) num *= 2 ;
for(i=1;i<=threes;i++) num *= 3 ;
if(num!=n) {cout << -1 << endl;continue;}
if(twes>threes) {cout << -1 << endl;continue;}
else
{
cout << threes+(threes-twes) << endl;
}
//cout << threes << space << twes << endl;
}
return 0;
}
<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io \
ios_base::sync_with_stdio(0); \
cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
int main()
{
fast_io
int n, i, j , k;
//cin >> n;
string s;
cin >> s;
n = sz(s);
LL cnt = 0;
for (i = 0; i < n - 2; i++)
{
if (s[i] == 'Q')
{
for (j = i + 1; j < n - 1; j++)
{
if (s[j] == 'A')
{
for (k = j + 1; k < n; k++)
{
if (s[k] == 'Q') cnt++;
}
}
}
}
///cout << "TEST\n";
}
cout << cnt << endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
bool checkVow ( char a )
{
if(a=='a' || a=='e' || a=='i' || a=='o' || a=='u' || a=='y') return true;
else return false;
}
int main()
{
string s; cin >> s;
vector<char> v;
int i , l = s.length() ;
for(i=0;i<l;i++)
{
s[i] = tolower(s[i]) ;
if(checkVow(s[i])==0)
{
v.push_back('.');
v.push_back(s[i]);
}
}
for(i=0;i<v.size();i++) cout << v[i];
cout << endl;
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n = ri()
m = [0 for i in range(101)]
for _ in range(n):
if _ == 0:
a = ria()
for i in range(1,a[0]+1):
m[a[i]] = 1
else:
a = ria()
for i in range(1,a[0]+1):
m[a[i]] += 1
cnt = 0
for i in range(1,101):
if m[i]==n:
print(i, end=" ")
print()
if __name__ == '__main__':
t = 1
while t:
t -= 1
main()
<file_sep>#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
#define pi acos(-1.0)
int main()
{
ll t , i ;
cin >> t ;
while(t--)
{
ll a , b , c ;
ll x1 , x2 ;
cin >> a >> b >> c ;
x1 = (a<c) ? 1 : -1 ;
x2 = (c<a*b) ? b : -1 ;
cout << x1 << " " << x2 << endl;
}
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j;
cin >> n;
int a[n];
vi v;
for(i=0;i<n;i++) cin >> a[i];
for(i=0;i<n/2;i++)
{
if(a[i*2]<=a[i*2+1])
{
v.push_back(2);
break;
}
}
for(i=0;i<n/4;i++)
{
if(a[i*4]<=a[i*4+1] && a[i*4+1]<=a[i*4+2] && a[i*4+2]<=a[i*4+3])
{
v.push_back(4);
break;
}
}
for(i=0;i<n/8;i++)
{
if(a[i*8]<=a[i*8+1] && a[i*8+1]<=a[i*8+2] && a[i*8+2]<=a[i*8+3])
{
if(a[i*8+3]<=a[i*8+4] && a[i*8+4]<=a[i*8+5] && a[i*8+5]<=a[i*8+6])
{
if(a[i*8+6]<=a[i*8+7])
{
v.push_back(8);
break;
}
}
}
}
int flag = 0 ;
for(i=0;i<n-1;i++)
{
if(a[i]<=a[i+1]) continue;
else
{
flag=1;
break;
}
}
if(!flag) v.push_back(n);
int len = v.size();
if(!len) cout << 1 << endl;
else
{
sort(v.begin(),v.end());
cout << v[len-1] << endl;
}
return 0;
}<file_sep>#include <stdio.h>
#include <string.h>
int main() {
int T;
int j;
scanf("%d", &T);
for(int i=0; i<T; i++)
{
int vow = 0, con = 0;
char word[105];
scanf("%s", word);
int len = strlen(word);
int a[26] = {0} ;
for (int l=0; l<len; l++)
{
a[word[l]-'A'] = 1 ;
//a['P' - 'A'] = 1;
}
if(a['A'-'A']) vow++;
if(a['E'-'A']) vow++;
if(a['I'-'A']) vow++;
if(a['O'-'A']) vow++;
if(a['U'-'A']) vow++;
for(j=0;j<26;j++)
{
if(a[j]) con++;
}
printf("%d %d\n", vow, con-vow);
}
return 0;
}
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
//off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int a,b,c;
cin >> a >> b >> c;
LL ans = c*2 ;
if(a==b) ans += a*2 ;
else if(abs(a-b)==1) ans += a+ b;
else if(a<b) ans+=a+a+1;
else ans += b + b + 1 ;
cout << ans << endl;
return 0;
}
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL ;
typedef string S;
typedef double D;
#define pi acos(-1.0)
LL lastDig(LL a , LL b , LL m)
{
a %= m ;
LL res = 1 ;
while(b>0)
{
if(b&1) res = (res*a) % 10 ;
a = (a*a) % 10 ;
b >>= 1 ;
}
return res;
}
int main()
{
int t;
cin >> t;
while(t--)
{
LL a,b;
cin >>a>>b;
LL res = lastDig(a,b,10) ;
cout << res << endl;
}
return 0;
}
/*
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
*/
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
long long n, i, j;
cin >> n;
vector<long long> v(n);
long long next[n] = {0} , pre[n]= {0} ;
for(i=0;i<n;i++) next[i]=pre[i]=-1;
for ( i = 0 ; i < n ; i++ )
{
cin >> v[i] ;
}
// fix for corner-case n=2 bug
if(n==2)
{
if(v[0]%3==0 && v[0]/3==v[1]) { cout << v[0] << " " << v[1] << endl; return 0; }
if(v[1]%3==0 && v[1]/3==v[0]) { cout << v[1] << " " << v[0] << endl; return 0; }
if(v[0]*2==v[1]) { cout << v[0] << " " << v[1] << endl; return 0; }
if(v[1]*2==v[0]) { cout << v[1] << " " << v[0] << endl; return 0; }
}
for ( i = 0 ; i < n ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
if(v[i]%3==0)
{
if(v[j]==v[i]*2 || v[j]==v[i]/3)
{
next[i] = j ;
pre[j] = i ; break;
}
}
else if(v[j]/2==v[i])
{
next[i] = j ;
pre[j] = i ; break;
}
}
}
for(i=0;i<n;i++)
{
if(pre[i]==-1)
{
while(next[i]!=-1)
{
cout << v[i] << " " ;
i = next[i] ;
}
cout << v[i] << endl;
cout << endl;
break;
}
//cout << i << "\t" << v[i] << "\t" << next[i] << "\t" << pre[i] << endl;
}
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a ,b ,i=0,j;
scanf("%d %d",&a,&b);
if(i< a) i = a;
if(i<b) i=b;
if(i==1)
{
printf("1/1\n");
}
else if(i==2) printf("5/6\n");
else if(i==3) printf("2/3\n");
else if(i==4) printf("1/2\n");
else if(i==5) printf("1/3\n");
else if(i==6) printf("1/6\n");
return 0;
}<file_sep>/*
* <NAME>
* AUTHOR : <NAME> ,HANDLE: HurayraIIT
*/
#include <bits/stdc++.h>
using namespace std;
#define SCD(t) scanf("%d",&t)
#define SCLD(t) scanf("%ld",&t)
#define SCLLD(t) scanf("%lld",&t)
#define SCC(t) scanf("%c",&t)
#define SCS(t) scanf("%s",t)
#define SCF(t) scanf("%f",&t)
#define SCLF(t) scanf("%lf",&t)
#define all(cont) cont.begin(), cont.end()
#define rall(cont) cont.end(), cont.begin()
#define MEM(a, b) memset(a, (b), sizeof(a))
#define FOR(n) for (int i=0 ; i<n ; i++)
#define FOR2(n) for (int j=0 ; j<n ; j++)
#define print(n) cout << n << endl
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define EPS 1e-9
#define MOD 1000000007
const double pi=acos(-1.0);
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef long long int LL;
typedef unsigned long long int ULL;
int main()
{
int tc = 1;
SCD(tc);
while(tc--){
int n;
cin >> n;
string b;
cin >> b;
string a = "1";
for(int i=1;i<n;i++) {
if (b[i]-'0'+1 != b[i-1]-'0'+a[i-1]-'0') {
a += "1";
} else {
a += "0";
}
}
cout << a << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int i;
S a,b;
cin >> a;
cin >> b;
int la = a.length();
int lb = b.length();
if(la!=lb)
{
cout << "NO\n";
return 0;
}
int cnt = 0;
char a1,a2,b1,b2;
for(i=0;i<la;i++)
{
if(a[i]!=b[i])
{
cnt++;
if(cnt==1)
{
a1 = a[i];
b1 = b[i];
}
else
{
a2 = a[i];
b2 = b[i];
}
}
}
if(cnt!=2 && cnt!=0)
{
cout << "NO\n";
}
else if(cnt==2 && (a1!=b2 || a2!=b1) ) cout << "NO\n";
else cout << "YES\n";
return 0;
}
<file_sep>
# Problem : 10050 - Hartals
# Contest : UVa Online Judge
# URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=991
# Memory Limit : 32 MB
# Time Limit : 3000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
# <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
t = ri()
for _ in range(t):
n = ri()
p = ri()
a =[]
lst = [False]*(n+1)
for i in range(p):
b = ri()
a.append(b)
#wia(a)
for i in a:
x = i
for j in range(i,n+1,i):
#print(j)
if j%7!=0 and j%7!=6:
lst[j] = True
'''
for i in range(1,n+1):
for j in a:
if i%j==0:
if i%7!=0 and i%7!=6:
lst[i] = True
break
'''
cnt = 0
for i in range(1,n+1):
if lst[i]==True:
cnt += 1
wi(cnt)
if __name__ == '__main__':
main()
<file_sep>// HurayraIIT
#include <bits/stdc++.h>
using namespace std;
#define pi acos(-1.0)
typedef long long LL;
typedef vector<int> vi ;
int main()
{
int t;
cin >> t ;
string s ;
cin >> s ;
cout << t+1 << endl;
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int i,j,k,n,x;
LL s = 0 ;
int d = 0;
scanf("%d %d",&n,&x);
int a[n];
s+=x;
for(i=0;i<n;i++)
{
char ch;
cin >> ch >> a[i];
if(ch=='+') s+=a[i];
else
{
if(s>=a[i])
{
s-=a[i];
}
else d++;
}
//cout <<ch << " " << s << endl;
}
printf("%lld %d\n",s,d);
return 0;
}<file_sep>#include<bits/stdc++.h>
#include<stack>
using namespace std;
// add new element and minimum untill now as a pair
void add_new_element(stack<pair<int,int>> &st , int new_element)
{
int new_minimum = st.empty() ? new_element : min( new_element , new_minimum ) ;
st.push( { new_element , new_minimum } ) ;
}
int main()
{
// We want to modify the stack data structure in such a way,
// that it possible to find the smallest element in the stack
// in O(1) time
// For this reason, we will store the elements in pairs in the stack:
// The element itself and the minimum element upto this position
stack< pair<int,int> > st;
// add new elements
add_new_element(st, 12);
add_new_element(st, 6);
add_new_element(st, 9);
add_new_element(st, 10);
add_new_element(st, 40);
// find the minimum element in O(1) time
cout << "Last elem: " << st.top().first << endl
<< "Minimum elem: " << st.top().second << endl;
// delete an element
st.pop();
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int lst[25][25]={0};
void mark(int i, int j, int n)
{
if(i<0 || i>n-1 || j<0 || j>n-1) return;
if(lst[i][j]==1)
{
lst[i][j]=2;
mark(i+1,j+1,n);
mark(i,j+1,n);
mark(i+1,j,n);
mark(i-1,j-1,n);
mark(i-1,j,n);
mark(i,j-1,n);
mark(i-1,j+1,n);
mark(i+1,j-1,n);
}
return;
}
void clr()
{
for(int i=0;i<25;i++)
{
for(int j=0;j<25;j++) lst[i][j]=0;
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,x,y,cnt=1;
while(cin >> n)
{
if(n==0) return 0;
char a[30][30];
for(i=0;i<n;i++) scanf("%s",a[i]);
int eg=0;
clr();
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
lst[i][j]=a[i][j]-'0';
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(lst[i][j]==1)
{
eg++;
mark(i,j,n);
}
}
}
printf("Image number %d contains %d war eagles.\n",cnt++,eg);
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,s=0;
cin >> n;
for(i=1;i<=sqrt(n);i++)
{
if(n%i==0) s+=2;
if((n%i==0 && i==n/i) || i==1 ) s--;
//cout << i << " " << n/i << endl;
}
cout << s << endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,a;
int i=0,j=5;
cin >> s;
while(j--)
{
cin >> a;
if(s[0]==a[0] || s[1]==a[1]) i=1;
}
if(i) cout << "YES\n";
else cout << "NO\n";
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
from xmlrpc.client import gzip_decode
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n, k = map(int, input().split())
s = rs()
tpos = 0
gpos = 0
for i in range(n):
if s[i]=='T':
tpos = i
if s[i]=='G':
gpos = i
flag = 1
if gpos < tpos:
for i in range(gpos, tpos+1, k):
if i==gpos:
continue
if s[i] == '#':
flag = 0
break
if i==tpos:
flag += 1
else:
for i in range(tpos, gpos+1, k):
if i==tpos:
continue
if s[i] == '#':
flag = 0
break
if i==gpos:
flag += 1
if flag < 2:
ws("NO")
else:
ws("YES")
if __name__ == '__main__':
t = 1
while t:
t -= 1
main()
<file_sep>a , b = list(map(int,input().split()))
i = 0
while a<=b:
a *= 3
b *= 2
i += 1
print(i) <file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
m, d = mp()
if m in [1,3,5,7,8,10,12]:
cnt = 0
for i in range(1, 32):
cnt += (1 if d==7 else 0)
d = (1 if d==7 else d+1)
# wi(d)
if d!=1:
cnt += 1
wi(cnt)
elif m==2:
cnt = 0
for i in range(1, 29):
cnt += 1 if d==7 else 0
d = 1 if d==7 else d+1
if d!=1:
cnt += 1
wi(cnt)
else:
cnt = 0
for i in range(1, 31):
cnt += 1 if d==7 else 0
d = 1 if d==7 else d+1
if d!=1:
cnt += 1
wi(cnt)
if __name__ == '__main__':
t = 1
while t:
t -= 1
main()
<file_sep>
// Problem: A. Boring Apartments
// Contest: Codeforces - Codeforces Round #677 (Div. 3)
// URL: https://codeforces.com/contest/1433/problem/A
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
#include<bits/stdc++.h>
using namespace std;
int main()
{
map <int,int> mp;
int s = 0 ;
for (int j=1; j<=9; j++) {
int num = j ;
for (int k=1; k<=4 ;k++) {
num = j ;
for (int p=1; p<k; p++) {
num = num * 10 + j ;
}
s += k ;
mp[num] = s ;
//cout << num << " " << s << endl;
}
}
int t;
cin >> t;
for (int i=0; i<t; i++)
{
int x;
cin >> x;
cout << mp[x] << endl;
}
return 0;
}
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def mp(): return map(int, sys.stdin.readline().split())
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main(tc:int):
n = ri()
a = ria()
s = set()
for i in a:
s.add(i)
wi(len(s))
if __name__ == '__main__':
t = 1
for tc in range(1,t+1):
main(tc)
<file_sep>/**** <NAME>
* <NAME> (HurayraIIT) - <EMAIL>
* Jahangirnagar University - 03.01.2021 18:58:17 +06
*****/
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair <int, int> pii;
typedef vector <int> vi;
typedef vector <pair<int, int> > vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,n) for(int i = 0 ; i < n ; i++)
#define rep2(i,a,b) for(int i = a ; i <= b ; i++)
int main()
{
fast_io
int t, n ;
cin >> t ;
while (t--) {
cin >> n ;
if (n % 2 == 0 ) {
for (int i = n ; i > 0 ; i-- ) {
cout << i << space;
}
cout << endl;
}
else {
cout << (n/2)+1 << space;
for (int i = n ; i > 0 ; i-- ) {
if (i!=(n/2)+1) cout << i << space;
}
cout << endl;
}
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int sub(int n , int k)
{
if(k==0) return n ;
if(n%10)
{
n-=1;
k--;
}
else
{
n/=10;
k--;
}
return sub(n,k);
}
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,k;
cin >> n >> k;
cout << sub(n,k) << endl;
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
LL n,i,j;
cin >> n;
LL a[n];
for(i=0;i<n;i++) cin >> a[i] ;
sort(a,a+n);
reverse(a,a+n);
int t = a[n-1];
a[n-1] = a[2];
a[2] = t;
int cnt=0;
for(i=0;i<n;i++)
{
//cout << a[i] << endl;
if(i==0)
{
if(a[i]>=a[i+1] + a[n-1])
{
cnt=1;
break;
}
}
else if(i==n-1 && a[i]>=a[n-1]+a[0])
{
cnt=1; break;
}
else if(a[i]>=a[i-1]+a[i+1])
{
cnt=1; break;
}
}
if(cnt==1) cout << "NO\n";
else
{
cout << "YES\n";
for(i=0;i<n;i++) cout << a[i] << " ";
}
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int i,j,k;
S a, b;
cin >> a ;
cin >> b;
for(i=0,j=0;i<b.length() && j<a.length();)
{
if(b[i]==a[j])
{
i++;
j++;
}
else i++;
}
printf("%d\n",j+1);
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
int n,i,j,b,c;
cin >> n;
int a[n];
for(i=0;i<n;i++)
{
cin >> a[i];
}
sort(a,a+n);
//if(!(n & 1)) n--;
D area=0;
if(!(n & 1))
{
for(i=n-1;i>=0;i--)
{
if(!(i & 1)) area-=a[i]*a[i]*pi;
else area+=a[i]*a[i]*pi;
}
cout << area << "\n";
}
else
{
for(i=n-1;i>=0;i--)
{
if(!(i & 1)) area+=a[i]*a[i]*pi;
else area-=a[i]*a[i]*pi;
}
cout << area << "\n";
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n; cin >> n ;
string a; int s = 0 ;
while(n--)
{
cin >> a;
if(a[0]=='T') s+=4;
else if(a[0]=='C') s+=6;
else if(a[0]=='O') s+=8;
else if(a[0]=='D') s+=12;
else if(a[0]=='I') s+=20;
}
cout << s << endl;
}<file_sep>q = int(input())
for i in range(q):
n = int(input())
if n<=4:
print(4-n)
elif n&1 :
print(1)
else:
print(0)
<file_sep># <NAME>
from subprocess import CalledProcessError
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def binary_search(arr: list,n: int, key: int) -> int:
lo = 1
hi = n
# Corner Cases
if key >= arr[n-1]:
return n
if key < arr[0]:
return 0
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] <= key:
lo = mid + 1
else:
hi = mid
return lo
def main():
n = ri()
prices = ria()
prices = sorted(prices)
queries = ri()
# wia(prices)
for _ in range(queries):
money = ri()
solution = binary_search(prices, n, money)
print(solution)
if __name__ == '__main__':
main()
<file_sep>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
//off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int b,n,i,j;
while(cin>>b>>n)
{
if(b==0 && n==0) return 0;
int m[b+1] = {0} ;
for(i=1;i<=b;i++) cin >> m[i];
int x,y,s;
for(i=1;i<=n;i++)
{
cin >> x >> y >>s ;
m[x]-= s;
m[y]+=s;
}
int tmp=0;
for(i=1;i<=b;i++)
{
if(m[i]<0)
{
tmp=1;
}
}
if(tmp==0) cout<<"S\n";
else cout << "N\n";
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n , i , m = 0 , cnt = 1;
cin >> n ;
int a[n] ;
for(i=0;i<n;i++)
{
cin >> a[i];
if(i>0 && a[i]>a[i-1])
{
cnt++;
}
else cnt = 1 ;
if(m < cnt) m = cnt ;
}
cout << m << endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int dp(int a[] , int n , int k)
{
int i,j;
int arr[n+1][k+1];
for(i=0;i<=n;i++)
{
for(j=0;j<=k;j++)
{
if(i<0 || j < 0) continue;
else if(i==0 || j==0) arr[i][j]=0;
else if(a[i-1]>j) arr[i][j] = arr[i-1][j];
else
{
int x;
//if(i<2) x = arr[0][j-a[i-1]];
if(i<2) arr[i][j] = max(a[i-1],arr[i-1][j]);
else arr[i][j]=max(a[i-1]+arr[i-2][j-a[i-1]],arr[i-1][j]);
}
}
}
return arr[n][k];
/*
if(k<=0 || n<=0) return 0;
if(a[n-1]>k) return dp(a,n-1,k);
else return max(a[n-1]+dp(a,n-2,k-a[n-1]), dp(a,n-1,k));
*/
}
int main()
{
int t,n,i,j,k;
scanf("%d",&t);
for(int cs =1 ; cs<=t ; cs++)
{
scanf("%d %d",&n,&k);
int a[n];
for(i=0;i<n;i++) scanf("%d",&a[i]);
int ans = dp(a,n,k);
printf("Scenario #%d: %d\n",cs,ans);
}
return 0;
}
<file_sep>s = input()
a = 0
b = 0
for i in range(0,len(s)):
if s[i]=='a':
a += 1
else:
b += 1
while b!=0 and a<=(a+b)/2:
b -= 1
print(a+b)<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
S a,s;
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
int i,j,k;
a.clear();
s.clear();
cin >> a >> s;
int la=a.length();
int ls=s.length();
int d[ls+5]={0};
for(i=0;i<ls;i++) d[i]=s[i]-'0';
sort(d,d+ls);
char ch;
for(i=0,j=ls-1;i<la;i++)
{
k=a[i]-'0';
if(k<d[j])
{
ch = '0'+d[j];
d[j]=0;
cout << ch;
if(j!=0) j--;
//swap(a[i],ch);
}
else cout << a[i];
}
//for(i=0;i<la;i++) cout << a[i];
cout << "\n";
return 0;
}<file_sep>https://adventofcode.com/2022/day/4<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
/*
int add(int a[],int n)
{
int sum=0;
for(int i=1;i<=n;i++) if(a[i]) sum+=a[i];
return sum;
}
*/
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,q,i,j,k,m;
scanf("%d %d",&n,&q);
int l[q+10],r[q+10];
int a[n+10];
for(i=1;i<=q;i++)
{
scanf("%d %d",&l[i],&r[i]);
}
int max=0;
for(i=1;i<q;i++)
{
for(j=i+1;j<=q;j++)
{
int sum=0;
int a[n+10]={0};
for(k=1;k<=q;k++)
{
if(k==i || k==j) continue;
for(m=l[k];m<=r[k];m++)
{
if(a[m]==0) sum++;
a[m]=1;
}
}
//sum=add(a,n);
//cout<< sum << endl;
if(sum>max) max=sum;
}
}
printf("%d\n",max);
return 0;
}<file_sep># <NAME>
import sys
from collections import defaultdict
# import threading
# threading.stack_size(2**27)
# sys.setrecursionlimit(2**21)
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
t = ri()
for _ in range(t):
n = ri()
a = ria()
d = defaultdict(int)
sim_max = 0
for i in a:
d[i] += 1
sim_max = max(sim_max, d[i])
sol1 = min(sim_max-1, len(d))
sol2 = min(sim_max, len(d)-1)
print(max(sol1, sol2))
# if(len(d)==1):
# print(0)
# continue
# if len(d) == n:
# print(1)
# continue
# print(min(sim_max-1, len(d)))
if __name__ == '__main__':
# t = threading.Thread(target=main)
# t.start()
# t.join()
main()
<file_sep># <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
# a = list(map(int, input().split()))
def main():
n, t = ria()
a = ria()
a.append(0)
b = [0] * (n+1)
for i in range(n):
if i == 0:
b[i] = a[i]
else:
b[i] = b[i-1] + a[i]
# print(b)
# print(a)
sol = -1
for i in range(n):
if t < a[i]:
sol = max(sol, 0)
continue
l = i
r = n - 1
while l < r:
m = r - (r-l)//2
if i == 0:
x = b[m]
else:
x = b[m] - b[i-1]
if x <= t:
l = m
else:
r = m - 1
# print(f"for {i}: {l-i+1}")
sol = max(sol, l - i + 1)
print(sol)
if __name__ == '__main__':
main()
"""
[3, 4, 6, 7, 0]
[3, 1, 2, 1, 0]
3, 4, 6, 7
for 0: 2
1, 3, 4
for 1: 3
2, 3
for 2: 2
1
for 3: 1
[2, 4, 7, 0]
[2, 2, 3, 0]
2, 4, 7, 0
for 0: 1
2, 5
for 1: 2
3
for 2: 1
"""<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
bool is_prime(int n )
{
if(n<=1) return false;
for(int i = 2 ; i<=sqrt(n);i++)
{
if(n%i==0) return false;
}
return true;
}
bool has2 ( int n , int a , int b )
{
while(n%a==0 || n%b==0)
{
if(n%a==0) n /= a ;
if(n%b==0) n /= b ;
}
if(n==1) return true;
return false;
}
int main()
{
fast_io
int n,i,j,s=0;
cin >> n ;
for(i=1;i<=n;i++)
{
int cnt = 0 , a , b ;
for(j=2;j<=sqrt(i);j++)
{
if(i%j==0 && j!=i/j && is_prime(i/j) && is_prime(j))
{
cnt++;a = j ; b = i/j;
}
}
if(cnt==1 && has2(i,a,b)) {s++;cout << i << endl;}
}
cout <<s << endl;
return 0;
}
<file_sep>/**** <NAME>
* <NAME> (HurayraIIT) - <EMAIL>
* Jahangirnagar University - 03.01.2021 18:48:24 +06
*****/
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair <int, int> pii;
typedef vector <int> vi;
typedef vector <pair<int, int> > vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,n) for(int i = 0 ; i < n ; i++)
#define rep2(i,a,b) for(int i = a ; i <= b ; i++)
int main()
{
fast_io
int t, n;
cin >> t ;
while (t--) {
cin >> n ;
char ch ;
int r[n] , b[n] ;
rep(i,n) {
cin >> ch ;
r[i] = ch - '0' ;
}
rep(i,n) {
cin >> ch ;
b[i] = ch - '0' ;
}
int RED = 0 , BLUE = 0 ;
rep(i,n) {
if (r[i] > b[i]) RED++;
else if (r[i] < b[i]) BLUE++;
}
if (RED == BLUE) cout << "EQUAL\n";
else if (RED > BLUE) cout << "RED\n";
else cout << "BLUE\n";
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int s,n,i,j,t=0;
scanf("%d %d",&s,&n);
j=s;
int a[n][2];
for(i=0;i<n;i++) scanf("%d %d",&a[i][0],&a[i][1]);
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i][0]>a[j][0])
{
int temp=a[i][0];
a[i][0]=a[j][0];
a[j][0]=temp;
temp=a[i][1];
a[i][1]=a[j][1];
a[j][1]=temp;
}
}
}
j=s;
for(i=0;i<n;i++)
{
if(s<=a[i][0])
{
t=0;
break;
}
else
{
s+=a[i][1];
t=1;
}
}
if(t==1)
{
printf("YES\n");
return 0;
}
t=0;
s=j;
for(i=n-1;i>=0;i--)
{
if(s<=a[i][0])
{
printf("NO\n");
return 0;
}
else s+=a[i][1];
}
printf("YES\n");
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b,i=0,j;
cin >> a >> b;
while(a<=b)
{
a=a*3;
b=b*2;
i++;
}
cout << i << endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i;
cin >> n ;
int a[n];
int mn = 1000;
for(i=0;i<n;i++)
{
cin >> a[i];
mn = min(mn,a[i]);
}
sort(a,a+n);
int sol = 999;
for(i=0;i<n;i++)
{
if(a[i]>mn)
{
sol = a[i];
break;
}
}
if(sol==999) cout << "NO\n";
else cout << sol << endl;
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t,i,j,n;
cin >> t;
cin >> ws ;
while(t--)
{
S s,a="";
cin >> s;
int len = s[0]-'A';
char par[len];
for(i=0;i<len;i++)
{
par[i] = 'A' + i ;
}
while(a[0]!="\n")
{
cin >> a;
par[a[0]-'A'] = par[a[1]-'A'];
}
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,x,y,i,j;
cin >> n >> m >> x >> y ;
int vis[n+1][m+1] ;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
vis[i][j] = 0 ;
}
}
vector<pair<int,int> > v ;
v.push_back({x,y});
vis[x][y] = 1 ;
v.push_back({1,y});
vis[1][y] = 1 ;
for(i=1;i<=n;i++)
{
if(i&1)
{
for(j=1;j<=m;j++)
{
if(!vis[i][j]) {v.push_back({i,j});vis[i][j]=1;}
}
}
else
{
for(j=m;j>=1;j--)
{
if(!vis[i][j]) {v.push_back({i,j});vis[i][j]=1;}
}
}
}
for(auto val : v)
{
cout << val.first << " " << val.second << endl;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int n, p;
cin >> n >> p ;
int a[n], pre[n], suf[n];
int sum = -10000000;
for(int i = 0 ; i < n ; i++ )
{
cin >> a[i] ;
if(i==0)
{
pre[i] = a[i]%p;
}
else pre[i] = (pre[i-1]+(a[i]%p))%p;
}
suf[n-1] = a[n-1]%p;
for(int i = n-2 ; i>=0;i--)
{
suf[i] = (suf[i+1] + a[i]%p)%p;
}
for(int i = 0 ; i < n-1 ; i++ )
{
if(sum<pre[i]+suf[i+1]) sum = pre[i]+suf[i+1];
//cout << pre[i]+suf[i+1] << " ";
}
//cout << endl;
cout << sum << endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
cout << "Bismillah\n";
return 0;
}
<file_sep>
// Problem: <NAME>
// Contest: Codeforces - Codeforces Round #677 (Div. 3)
// URL: https://codeforces.com/contest/1433/problem/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<pii> vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,n) for(int i = 0 ; i < n ; i ++)
int main()
{
fast_io
int t ;
cin >>t ;
while(t--)
{
int n ;
cin >> n ;
int a[n] , mx = -1 , cnt = 0;
for (int i = 0 ; i < n ;i++)
{
cin >> a[i] ;
mx = max(mx,a[i]) ;
}
rep(i,n) cnt += (mx==a[i]?1:0);
if(cnt==n) { cout << -1 << endl; continue; }
int sol = -1 ;
rep(i,n)
{
if(sol!=-1) break;
if(a[i]!=mx) continue;
if(i==0)
{
if(a[i+1]<mx) {sol = i+1; break;}
}
else if(i==n-1)
{
if(a[i-1]<mx) {sol = i+1; break;}
}
else if(a[i+1]<mx) {sol = i+1; break;}
else if(a[i-1]<mx) {sol = i+1; break;}
}
cout << sol << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
int n,i,j;
cin >> n;
char a[2*n+2];
scanf("%s",a);
int f[n+1], l[n+1];
for(i=0;i<n;i++) f[i]=a[i]-'0';
for(i=n,j=0;i<2*n;i++,j++) l[j]=a[i]-'0';
//for(i=0;i<n;i++) cout << f[i] << " " << l[i] << endl;
sort(l,l+n);
sort(f,f+n);
//for(i=0;i<n;i++) cout << f[i] << " " << l[i] << endl;
if(f[0]<l[0])
{
int flag=1;
for(i=0;i<n;i++)
{
if(f[i]<l[i]) continue;
else
{
flag=0;
break;
}
}
if(flag==1) printf("YES\n");
else printf("NO\n");
}
else if(f[0]>l[0])
{
int flag=1;
for(i=0;i<n;i++)
{
if(f[i]>l[i]) continue;
else
{
flag=0;
break;
}
}
if(flag==1) printf("YES\n");
else printf("NO\n");
}
else printf("NO\n");
return 0;
}<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
int main()
{
fast_io
int t ;
cin >> t ;
while(t--)
{
int64 n ;
cin >> n ;
int64 a[n] ;
for(int i = 0 ; i<n;i++)
{
cin >> a[i] ;
}
int64 dp[n+2][3] = {0} ;
for(int i = 0 ; i< n;i++)
{
dp[i+1][0] = max(dp[i+1][0],dp[i][0]+(i&1?0:a[i]));
//cout << dp[i+1][0] << " ";
dp[i+2][1] = max(dp[i+2][1],max(dp[i][0],dp[i][1])+(i&1?a[i]:a[i+1]));
//cout << dp[i+2][1] << " ";
dp[i+1][2] = max(dp[i+1][2],max({dp[i][0],dp[i][1],dp[i][2]})+(i&1?0:a[i]));
}
//cout << endl;
cout << max({dp[n][0],dp[n][1],dp[n][2]}) << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int w,h,i,j,n,s=0;
cin >> w >> h;
s+=w;
int u1,d1,u2,d2;
cin >> u1 >> d1 >> u2 >> d2;
for(i=h;i>=0;i--)
{
s=s+i;
if(i==d1 && i)
{
s-=u1;
if(s<0) s=0;
}
else if(i==d2 && i)
{
s-=u2;
if(s<0) s=0;
}
//cout << s << endl;
}
cout << s << endl;
return 0;
}<file_sep># Take input in an array
a, b = map(int, input().split())
if a==b:
print(a)
else:
print(3-(a+b))<file_sep>import math
# There are t test cases
t = int(input())
# A loop for all of the test cases
for i in range(t):
# In each test case, there is a number n
n = int(input())
# Find the square root and
# round it down to the nearest integer
ans = math.floor(math.sqrt(n))
# Print the ans
print(ans)<file_sep>n = int(input())
print((n+99)//100)<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <bits/stdc++.h>
using namespace std;
typedef long long int LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair <int, int> pii;
typedef vector <int> vi;
typedef vector <pair<int, int> > vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,n) for(int i = 0 ; i < n ; i++)
#define rep2(i,a,b) for(int i = a ; i <= b ; i++)
int main()
{
// fast_io
int t;
cin >> t;
while(t--) {
int a, n;
cin >> n;
vector<int> v;
for (int i=0;i<n;i++) {
cin >> a;
v.push_back(a);
}
sort(v.begin(), v.end());
int flg = 0, sol = -1;
for (int i=0;i<=n-3;i++) {
if (v[i] == v[i+1] && v[i] == v[i+2]) {
flg = 1;
sol = v[i];
}
if(flg) break;
}
cout << sol << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,k;
scanf("%d",&n);
int a[n];
int b[n]={0};
for(i=0;i<n;i++) scanf("%d",&a[i]);
sort(a,a+n);
int lst=1;
int max=0;
int cnt=0;
for(i=0,j=0;i<n,j<n;)
{
if(a[j]-a[i]<=5)
{
cnt++;
j++;
}
else
{
i++;
if(max<cnt) max=cnt;
//cout << cnt << " ";
cnt--;
//j++;
}
}
if(max<cnt) max=cnt;
//cout << endl;
printf("%d\n",max);
return 0;
}
<file_sep>
// Problem: B. Yet Another Bookshelf
// Contest: Codeforces - Codeforces Round #677 (Div. 3)
// URL: https://codeforces.com/contest/1433/problem/B
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<pii> vpii;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
#define rep(i,n) for(int ( i ) = ( 0 ) ;( i ) <( n );( i )++)
#define rep2(i,a,b) for(int ( i ) = ( a ) ;( i ) <= ( b );( i )++)
int main()
{
fast_io
int t;
cin >> t;
while(t--)
{
int n;
cin >> n;
int a[n], books = 0, first_book = -1 , last_book = n;
for (int i=0;i<n;i++)
{
cin >> a[i];
books += a[i] ;
if(first_book==-1 && a[i]) first_book = i;
if(first_book!=i && a[i]) last_book = i ;
}
if(books==1) {cout << 0 << endl; continue;}
int sol = 0 ;
//cout << first_book << " " << last_book << endl;
for (int i = first_book ; i<=last_book ; i++)
{
if(!a[i]) sol++;
}
cout << sol << endl;
}
return 0;
}
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,x=0,y=0;
S a;
cin >> a;
int l=a.length();
for(i=0;i<l;i++)
{
if(a[i]=='4') x++;
else if(a[i]=='7') y++;
}
if(x==0 && y==0) cout << -1 << "\n";
else if(x==y) cout << 4 << "\n";
else if(x>y) cout << 4 << "\n";
else cout << 7 << "\n";
return 0;
}
<file_sep>// <NAME> (HurayraIIT)
// IIT, Jahangirnagar University
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <deque>
#include <bitset>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <math.h>
#include <stdio.h>
#include <string.h>
using namespace std;
typedef long long LL;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<int> vi;
#define READ freopen("input.txt", "r", stdin);
#define WRITE freopen("output.txt", "w", stdout);
#define fast_io ios_base::sync_with_stdio(0); cin.tie(0);
#define sz(a) int((a).size())
#define space " "
#define all(x) (x).begin(), (x).end()
#define endl '\n'
#define pi acos(-1.0)
#define MP make_pair
#define PB push_back
#define INF (int)1e9
#define MOD 1000000007
#define PRECISION(x) cout << fixed << setprecision(x);
LL find( LL n )
{
if(n<1) return 1 ;
return (2*find(n-1))%MOD ;
}
int main()
{
fast_io
LL n ;
cin >> n ;
LL sol = 1 ;
for(LL i = 1 ; i <=n ; i++)
{
sol = (sol*i)%MOD ;
}
LL b = 1 ;
for(LL i = 1 ; i < n ; i++ )
{
b = (b*2) % MOD ;
}
sol -= b ;
sol = (sol+MOD)%MOD;
cout << sol << endl;
return 0;
}
<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n ,i,j,k,cs=1;
while(cin >> n)
{
if(n==0) return 0;
printf("Game %d:\n",cs++);
int code[n];
for(i=0;i<n;i++) cin >> code[i];
while(1)
{
int test[n];
int end=0;
for(i=0;i<n;i++)
{
cin >> test[i]; end+=test[i];
}
if(end==0) break;
int flag[n] = {0} , x=0,y=0;
for(i=0;i<n;i++)
{
if(code[i]==test[i]) {x++;flag[i]=1;}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i!=j && code[i]!=test[i] && code[i]==test[j] && flag[j]==0)
{
y++; flag[j]=1;
break;
}
}
}
printf(" (%d,%d)\n",x,y);
}
}
return 0;
}
<file_sep>
# Problem : 195 - Anagram
# Contest : UVa Online Judge
# URL : https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=131
# Memory Limit : 32 MB
# Time Limit : 3000 ms
# Powered by CP Editor (https://github.com/cpeditor/cpeditor)
# <NAME>
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def next_permutation(a):
a = list(a)
i = len(a) - 2
while not (i < 0 or (a[i].lower() <a[i+1].lower() )):
i -= 1
if i < 0:
return ''
j = len(a) - 1
while not (a[j] > a[i] ):
j -= 1
a[i], a[j] = a[j], a[i]
a[i+1:] = reversed(a[i+1:])
return ''.join(a)
def main():
t = ri()
for _ in range(t):
s = rs()
a = ''.join(sorted(s))
ws(a)
a = next_permutation(a)
while a!='' :
ws(a)
a = next_permutation(a)
if __name__ == '__main__':
main()
<file_sep>n = int(input())
s = input()
a=0
b=0
for i in range(1,n):
if s[i]=='F' and s[i-1]=='S':
a += 1
elif s[i]!=s[i-1]:
b += 1
if a>b:
print("YES")
else:
print("NO")<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,k,i,j;
scanf("%d %d",&n,&k);
int a[n];
int b[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
b[i]=a[i]%k;
//cout << a[i] << " " << b[i] << endl;
}
sort(b,b+n);
int cnt=0;
int tmp=0;
//for(i=0;i<n;i++) cout << b[i] << " ";
//cout << endl;
for(i=0,j=n-1;i<=j;)
{
if(b[i]==0)
{
tmp++;
i++;
continue;
}
if(b[i]+b[j]==k && i!=j)
{
cnt++;
i++;j--;
}
else if(b[i]+b[j]>k && i!=j) j--;
else i++;
}
//cout << cnt <<endl<<tmp<< endl;
printf("%d\n",cnt*2+(tmp/2)*2);
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n , i , j , s = 0 ;
while( cin >> n && n )
{
s =sqrt(n);
if(s*s!=n) cout << "no\n";
else cout << "yes\n";
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
typedef long long int LL;
int main()
{
long long t , n , i , j;
cin >> t ;
while(t--)
{
cin >> n ;
long long a[n] , b[n] ;
LL mn = INT_MAX * 20ll, mm = INT_MAX * 20ll ;
for(i=0;i<n;i++)
{
cin >> a[i] ;
mn = min(mn,a[i]);
}
for(i=0;i<n;i++)
{
cin >> b[i] ;
mm = min(mm,b[i]);
}
long long ans = 0 ;
//cout << a[0] << " " << b[0] << endl;
//cout << mn << " " << mm << endl;
for(i = 0 ; i<n;i++)
{
long long int x = a[i] - mn ;
long long int y = b[i] - mm ;
ans +=(long long) max(x,y);
}
cout << ans << endl;
}
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int n,i,j,k;
while(cin>>n)
{
if(!n) return 0;
string a;
cin.ignore();
int top=1 , bottom = 6;
int north = 2 , south = 5 ;
int west = 3 , east = 4 ;
int temp=top;
while(n--)
{
cin >> a;
char c = a[0];
if(c=='n')
{
temp=top;
top = south;
south = bottom;
bottom = north;
north = temp;
}
else if(c=='s')
{
temp = top;
top = north;
north = bottom;
bottom = south;
south = temp;
}
else if(c=='e')
{
temp=top;
top = west;
west = bottom;
bottom = east;
east = temp;
}
else if(c=='w')
{
temp = top;
top = east;
east = bottom;
bottom = west;
west = temp;
}
}
cout << top << endl;
}
return 0;
}
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def findDiff(i, n):
si = str(i)
sn = str(n)
leni = len(si)
lenn = len(sn)
if leni!=lenn:
return 999
cnt = 0
for j in range(leni):
if si[j] != sn[j]:
cnt += 1
return cnt
def main():
n = ri()
a = []
for i in range(200):
if i and 7*i<=999:
a.append(7*i)
changes = 999
p = 0
for i in a:
if findDiff(i,n) < changes:
p = i
changes = findDiff(i,n)
wi(p)
if __name__ == '__main__':
t = ri() # 1
while t:
t -= 1
main()
<file_sep>import sys
def get_array(): return list(map(int, sys.stdin.readline().split()))
#num = list(map(int,input().split()))
num = get_array()
num.sort()
print(num[3]-num[0], num[3]-num[1], num[3]-num[2])
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,i,j,k;
cin >> n >> m ;
int a[n] , b[m] ;
for(i=0;i<n;i++) cin >> a[i] ;
for(i=0;i<m;i++) cin >> b[i] ;
//sort(a,a+n);
//sort(b,b+m);
int mn = 0 ;
for(k=0;k<(1<<9);k++)
{
int cnt = 0 ;
for(i=0;i<n;i++)
{
bool flg = 0 ;
for(j=0;j<m;j++)
{
int d = (a[i]&b[j]);
if (k == (k | d))
{
flg = 1 ; break;
}
}
if(flg) cnt++;
}
if(cnt==n) {mn = k ; break; }
}
cout << mn << endl;
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j,l;
S s;
LL num;
cin >> num;
s = to_string(num);
l = s.length();
LL pro = 1;
if(num>999)
{
s[0]--;
for(i=1;i<l;i++)
{
s[i]='9';
}
for(i=0;i<l;i++)
{
if(s[i]>'1') pro*=s[i]-'0';
}
}
else
{
LL pr = 1;
while(num)
{
int d = num;
pr=1;
while(d)
{
pr*=d%10;
d/=10;
}
if(pro<pr) pro = pr;
num--;
}
}
cout << pro << endl;
return 0;
}<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
import math
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n, m, k = map(int, input().split())
npos = 0
mpos = 0
side = 'L'
if k%2==0:
side = 'R'
p = (k-1)//2
npos = (p//m)+1
mpos = (p%m) + 1
print(str(npos) + " " + str(mpos) + " " + side)
if __name__ == '__main__':
t = 1
while t:
t -= 1
main()
<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef stack<int> si;
typedef queue<int> qi;
typedef priority_queue<int> pqi;
typedef pair<int,int> pi;
#define pi acos(-1.0)
#define PSB push_back
#define PPB pop_back
#define REP(i,a,b) for(i=a;i<=b;i++)
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,i,j;
scanf("%d",&n);
for(i=1;i<n;i++)
{
if(i&1) printf("I hate that ");
else printf("I love that ");
}
if(n&1) printf("I hate it\n");
else printf("I love it\n");
return 0;
}<file_sep>
/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
typedef queue<int> qi;
typedef stack<int> si;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define Fin freopen("input.txt","r",stdin)
#define Fout freopen("output.txt","w",stdout)
int main()
{
off;
#ifndef ONLINE_JUDGE
Fin; Fout;
#endif
int i,j,n,m,k;
cin >> n;
string s;
cin >> s ;
vi v[27];
for(i=0;i<n;i++)
{
int tmp = s[i] - 'a' ;
v[tmp].push_back(i);
}
cin >> m;
while(m--)
{
string a;
cin >> a ;
int mx=0;
int cnt[27]={0};
for(i=0;i<a.length();i++)
{
int temp = a[i] - 'a' ;
cnt[temp]++;
}
int d=0 , mm=0;
for(i=0;i<26;i++)
{
d = cnt[i];
//cout << d << endl;
if(d) mm = v[i][d-1];
//cout << mm << endl;
if(mx<mm) mx = mm ;
}
cout << mx+1 << endl;
}
return 0;
}
/*
while(m--)
{
string a;
cin >> a ;
memset(arr,0,sizeof(arr));
int mx=0;
for(i=0;i<a.length();i++)
{
for(j=0;j<s.length();j++)
{
if(arr[j]==0 && s[j]==a[i])
{
arr[j]=1;
if(mx<j) mx=j;
break;
}
}
}
cout << mx+1 << endl;
}*/<file_sep>#include <bits/stdc++.h>
using namespace std;
// https://codeforces.com/problemset/problem/1689/B
int main() {
int t;
cin >> t;
for(int i=0;i<t;i++) {
int n;
cin >> n;
int a[n];
for (int j=0;j<n;j++) {
cin >> a[j];
}
// something here
for(int j=0;j<n;j++) {
cout << a[i] << " ";
}
cout << endl;
}
}
<file_sep># <NAME>
# <NAME> - Handle: HurayraIIT
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
#a = list(map(int, input().split()))
def main():
n = ri()
if n%2 == 0:
wi(0)
else:
p = str(n)
cnt = 0
flg = 0
if p[0]=='0' or p[0]=='2' or p[0]=='4' or p[0]=='6' or p[0]=='8':
flg = 1
for i in p:
if i=='0' or i=='2' or i=='4' or i=='6' or i=='8':
cnt += 1
if flg == 1:
wi(1)
elif cnt > 0:
wi(2)
else:
wi(-1)
if __name__ == '__main__':
t = ri()
while t:
t -= 1
main()
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
int t,n,l;
cin >> t;
while(t--)
{
cin >> s;
l = s.length();
if(l<=10)
{
cout << s << endl;
}
else cout << s[0] <<l-2 << s[l-1] <<endl;
}
return 0;
}<file_sep>/* Name: <NAME>
Handle: HurayraIIT
Institute: IIT_JU */
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef string S;
typedef double D;
typedef vector<int> vi;
#define pi acos(-1.0)
#define endl '\n'
#define off ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int main()
{
//off;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int l,i,j;
while(cin>>l)
{
if(l==0) return 0;
string s;
int d = 1;
for(i=l-1;i>=1;i--)
{
cin >> s;
if(s[0]=='N') continue;
if(s[0]=='+')
{
if(s[1]=='y')
{
if(d==1) d=2;
else if(d==2) d=-1;
else if(d==-1) d=-2;
else if(d==-2) d=1;
}
else if(s[1]=='z')
{
if(d==1) d=3;
else if(d==3) d=-1;
else if(d==-1) d=-3;
else if(d==-3) d=1;
}
}
else if(s[0]=='-')
{
if(s[1]=='y')
{
if(d==1) d=-2;
else if(d==-2) d=-1;
else if(d==-1) d=2;
else if(d==2) d=1;
}
else if(s[1]=='z')
{
if(d==1) d=-3;
else if(d==-3) d=-1;
else if(d==-1) d=3;
else if(d==3) d=1;
}
}
}
if(d==1) cout <<"+x\n";
else if(d==-1) cout <<"-x\n";
else if(d==2) cout <<"+y\n";
else if(d==-2) cout <<"-y\n";
else if(d==3) cout <<"+z\n";
else if(d==-3) cout <<"-z\n";
}
return 0;
}
| 1c6a7125c8ea024050045fb18a685daadcfbcb0f | [
"Markdown",
"Python",
"C++"
]
| 252 | Python | HurayraIIT/competitive-programming | 3b9bc3066c70284cddab0f3e39ffc3e9cd59225f | 0e2f40cf1cae76129eac0cd8402b62165a6c29e4 |
refs/heads/master | <repo_name>hossamib/rrr<file_sep>/Assignments/rec4.js
require("./send");
//console.log(peo);
//console.log("hello");<file_sep>/Assignments/Assignments3.js
const fs = require('fs');
//Read file
fs.readFile('./documents/readnote.txt', (err, data) => {
if (err) {
console.log(err);
}
console.log(data.toString());
})<file_sep>/Assignments/Assignments1.js
console.log('Hello Nodejs world.');
process.stdout.write('Hello Nodejs world.');<file_sep>/Assignments/Assignments3-1.js
const fs = require('fs');
const readstream = fs.createReadStream('./documents/moretext.txt', { encoding: 'utf8' });
//Read stream file
readstream.on('data', (chunk) => {
console.log(chunk);
}) | 4b98b4bd67d3aefcab0dc93360533d17f9a4613d | [
"JavaScript"
]
| 4 | JavaScript | hossamib/rrr | e3b6f1f98e86a26def620ab2f0bbddfad5f6efcd | e330f35d59049f31fbaadd174382bd1e01c9eb5f |
refs/heads/master | <repo_name>Jonnay101/testWebServer<file_sep>/go.mod
module github.com/Jonnay101/testWebServer
go 1.13
require (
github.com/go-chi/chi v4.1.2+incompatible
github.com/labstack/echo v3.3.10+incompatible
github.com/labstack/echo/v4 v4.1.16
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a // indirect
)
<file_sep>/main.go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/labstack/echo/v4"
)
func main() {
e := echo.New()
e.GET("/", hello)
e.POST("/test", testEndpoint)
log.Fatal(e.Start(":3000"))
}
func hello(c echo.Context) error {
return c.String(http.StatusOK, "welcome to mini server land")
}
func testEndpoint(c echo.Context) error {
binding := make(map[string]interface{})
bodyDecoder := json.NewDecoder(c.Request().Body)
if err := bodyDecoder.Decode(&binding); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
fmt.Printf("%+v", binding)
return c.JSON(http.StatusOK, binding)
}
| 55f824a1b02a6f8abd1202ec6e0b63479aead743 | [
"Go",
"Go Module"
]
| 2 | Go Module | Jonnay101/testWebServer | b69946b22d1a3664f57813ca844c35820c256f48 | 044e46624ba196084679e03d783d4963fe1e340a |
refs/heads/master | <file_sep>#!/usr/bin/env python3
#
# Copyright (c) 2016-2017, The OpenThread Authors.
# All rights reserved.
#
# 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.
#
from setuptools import setup, find_packages
import sys
setup(
name='pyspinel',
version='1.0.1',
description='A Python interface to the OpenThread Network Co-Processor (NCP)',
url='https://github.com/openthread/openthread',
author='The OpenThread Authors',
author_email='<EMAIL>',
license='BSD',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Operating System :: MacOS',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: BSD License',
'Topic :: System :: Networking',
'Topic :: System :: Hardware :: Hardware Drivers',
'Topic :: Software Development :: Embedded Systems',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.6',
],
keywords='openthread thread spinel ncp',
packages=find_packages(),
install_requires=[
'pyserial',
'ipaddress',
],
scripts=['spinel-cli.py', 'sniffer.py']
)
| 1fccffad83a570bd459b1b077426db673568bb47 | [
"Python"
]
| 1 | Python | DangZRQ/pyspinel | 02f38db1d2d79207eb66f9a689b0213d74ddd53a | a2fd9f6e28c87781d270f941613bf9d0eac6090d |
refs/heads/master | <file_sep>import React from 'react';
import {Button} from 'reactstrap';
const CustomButton = ({name, color, size, type}) => {
return (
<Button
type={type}
color={color}
size={size}
>
{name}
</Button>
)
}
export default CustomButton;<file_sep>import rootReducer from './../reducers'
import {composeWithDevTools} from 'redux-devtools-extension';
import createSagaMiddleware from 'redux-saga';
import logger from 'redux-logger';
import { createStore, applyMiddleware } from 'redux';
import rootSaga from './../sagas/index';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
if (process.env.NODE_ENV === 'development') {
middlewares.push(logger);
}
const store = createStore(
rootReducer,
composeWithDevTools(
applyMiddleware(...middlewares)
)
)
sagaMiddleware.run(rootSaga);
export default store;
<file_sep>import { takeEvery, put } from 'redux-saga/effects';
import api from './../apis/mall'
function* getMalls () {
try {
yield put({type: 'REQUEST_FETCH_MALLS'});
let result = yield api.mall.getList();
yield put({type: 'SUCCESS_FETCH_MALLS', data: result});
} catch (error) {
yield put({type: 'FAILED_FETCH_MALLS', data: error.response});
}
}
export const mallSaga = [
takeEvery('GET_MALLS', getMalls)
];<file_sep>import React from 'react'
import { Col, FormGroup, Label, Input } from 'reactstrap';
const InputFile = ({label, handleInputFileChange, error, ...restProps}) => {
const handleChange = (e) => {
let data = {
name: e.target.name,
value: e.target.files[0]
}
handleInputFileChange(data);
}
return (
<FormGroup row>
<Label sm={4}>{label}</Label>
<Col sm={8}>
<Input
onChange={handleChange}
{...restProps}
/>
{error && <span>{error}</span>}
</Col>
</FormGroup>
)
}
export default InputFile;<file_sep>export const formInitialState = {
company_information: {
company_name: {
input_val: '',
required: true,
type: String,
condition: {
min: 1,
max: 20
}
},
company_logo: {
input_val: '',
required: true,
type: File,
condition: {
min: 1,
max: 20
}
}
},
contact_information: {
email: {
input_val: '',
required: true,
type: {
name: 'Email'
},
condition: {
min: 1,
max: 20
}
},
contact_number: {
input_val: '',
required: true,
type: Number,
condition: {
min: 10,
max: 10
}
},
secondary_number: {
input_val: '',
required: true,
type: Number,
condition: {
min: 10,
max: 15
}
},
authorized_contact: {
input_val: '',
required: true,
type: Number,
condition: {
min: 10,
max: 20
}
}
},
bank_details: {
account_number: {
input_val: '',
required: true,
type: Number,
condition: {
min: 15,
max: 15
}
},
bank_name: {
input_val: '',
required: true,
type: String,
condition: {
min: 1,
max: 15
}
},
ifsc_code: {
input_val: '',
required: true,
type: String,
condition: {
min: 15,
max: 15
}
},
branch_name: {
input_val: '',
required: true,
type: String,
condition: {
min: 1,
max: 50
}
}
},
mailing_address: {
address_line_1: {
input_val: '',
required: true,
type: String,
condition: {
min: 1,
max: 200
}
},
address_line_2: {
input_val: '',
required: false,
type: String,
condition: {
min: 1,
max: 200
}
},
city: {
input_val: '',
required: true,
type: String,
condition: {
min: 1,
max: 25
}
},
state: {
input_val: '',
required: true,
type: String,
condition: {
min: 1,
max: 30
}
},
zip_code: {
input_val: '',
required: true,
type: Number,
condition: {
min: 6,
max: 6
}
},
},
errors: []
}<file_sep>import React from 'react';
import AddCompanyHoc from './../../../HOCs/add_company'
import InputText from './../../forms/InputText'
import { InputStringAction } from './../../../actions/companyAction'
import { connect } from 'react-redux';
const BankDetails = (props) => {
let form_key = 'bank_details';
const { form, InputStringAction, errors } = props;
const handleInputTextChange = (data) => {
const { name } = data;
const object = {
target: data,
initialState: form[name],
key: form_key
}
InputStringAction(object);
}
return (
<div>
<InputText
type="number"
label="Account Number"
name="account_number"
placeholder="389238923******"
handleInputTextChange={handleInputTextChange}
value={form.account_number.input_val}
/>
<InputText
type="text"
label="Bank Name"
name="bank_name"
placeholder="Eg - ICICI"
handleInputTextChange={handleInputTextChange}
value={form.bank_name.input_val}
/>
<InputText
type="text"
label="IFSC Code"
name="ifsc_code"
placeholder="FG568HF**"
handleInputTextChange={handleInputTextChange}
value={form.ifsc_code.input_val}
/>
<InputText
type="text"
label="Branch Name"
name="branch_name"
placeholder="Mumbai central"
handleInputTextChange={handleInputTextChange}
value={form.branch_name.input_val}
/>
</div>
)
}
const mapDispatchToProps = { InputStringAction };
function mapStateTopProps (state) {
return {
form: state.Company.form.bank_details,
errors: state.Company.form.errors
}
}
export default AddCompanyHoc('Bank Details', connect(mapStateTopProps, mapDispatchToProps)(BankDetails));<file_sep>export const InputStringAction = (object) => {
return {
type: 'INPUT_STRING',
object
}
}
export const addCompanyAction = (data) => {
return {
type: 'ADD_COMPANY',
data
}
}
export const companiesListAction = () => {
return {
type: 'GET_COMPANIES'
}
}<file_sep>import axios from 'axios'
export default {
company : {
add : data =>
axios.post('companies', data).then(res => res.data),
getList: () =>
axios.get('http://jsonplaceholder.typicode.com/photos?_page=0&_limit=15').then(res => res.data),
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types'
import {
Card, CardImg, CardBody,
CardTitle
} from 'reactstrap';
const CompaniesList = ({company}) => {
return (
<Card>
<CardImg top width="100%" src={company.thumbnailUrl} alt="Card image cap" />
<CardBody>
<CardTitle>{company.title}</CardTitle>
</CardBody>
</Card>
)
}
CompaniesList.propTypes = { // don't know if we need to check types again
company: PropTypes.shape({
albumId: PropTypes.number.isRequired,
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
thumbnailUrl: PropTypes.string.isRequired
})
}
export default CompaniesList;<file_sep>import { combineReducers } from 'redux';
import Company from './companyReducers/index';
import Mall from './mallReducers';
export default combineReducers({
Company,
Mall
});
<file_sep>import React from 'react';
const Malls = (props) => {
return (
<h4>Malls</h4>
)
}
export default Malls;<file_sep>let initialState = {
malls: []
};
export default function User (state = initialState, action = {}){
switch(action.type){
// case LOGGED_IN_USER:
// return state;
default:
return state;
}
}
<file_sep>// import {LOGGED_IN_USER} from './../../types.js'
import { formInitialState } from './initial_state'
let initialState = {
form: formInitialState,
loading: false,
companies: [],
error: ''
};
export default function User (state = initialState, action = {}){
switch(action.type){
// Add company
case 'HANDLE_INPUT_CHANGE':
const { key , target} = action.data;
const { name, value} = target;
return {
...state,
form: {
...state.form,
[key]: {
...state.form[key],
[name]: {
...state.form[key][name],
input_val: value
}
}
}
};
case 'HANDLE_ERROR_CHANGE':
if (!action.data.error) {
return {
...state,
form: {
...state.form,
errors: state.form.errors.filter(error => error.key !== action.data.name)
}
}
} else {
let indexIs = state.form.errors.findIndex(error => {
return error.key === action.data.name
});
if (indexIs > -1) {
return {
...state,
form: {
...state.form,
errors: [...state.form.errors.filter(error => error.key !== action.data.name), action.data.error]
}
}
} else {
return {
...state,
form: {
...state.form,
errors: [...state.form.errors, action.data.error]
}
}
}
}
case 'REQUEST':
return {
...state,
loading: true
};
case 'COMPLETE':
return {
...state,
loading: false
};
case 'FAILED_ADD_COMPANY':
return {
...state,
form: {
...state.form,
errors: action.data
}
}
case 'SUCCESS_FETCH_COMPANIES':
return {
...state,
companies: action.data,
loading: false
};
case 'FAILED_FAILED_COMPANIES':
return {
...state,
loading: false,
error: action.data
}
default:
return state;
}
}
<file_sep>import { all } from 'redux-saga/effects';
import { mallSaga } from './mallSaga';
import { companySaga } from './companySaga';
/**
* saga to yield all others
*/
export default function* rootSaga() {
console.log('REGISTERING ALL SAGA WATCHERS');
yield all([
...mallSaga,
...companySaga
]);
}<file_sep>import React from 'react';
import AddCompanyHoc from './../../../HOCs/add_company'
import InputText from './../../forms/InputText'
import { InputStringAction } from './../../../actions/companyAction'
import { connect } from 'react-redux';
const ContactInformation = (props) => {
let form_key = 'contact_information';
const { form, InputStringAction, errors } = props;
const handleInputTextChange = async (data) => {
const { name } = data;
const object = {
target: data,
initialState: form[name],
key: form_key
}
InputStringAction(object);
}
return (
<div>
<InputText
type="text"
label="Email Address"
name="email"
placeholder="<EMAIL>"
handleInputTextChange={handleInputTextChange}
value={form.email.input_val}
/>
<InputText
type="number"
label="Contact Number"
name="contact_number"
placeholder="98779889**"
handleInputTextChange={handleInputTextChange}
value={form.contact_number.input_val}
/>
<InputText
type="number"
label="Secondary Number"
name="secondary_number"
placeholder="98779889**"
handleInputTextChange={handleInputTextChange}
value={form.secondary_number.input_val}
/>
<InputText
type="number"
label="Authorized Contact"
name="authorized_contact"
placeholder="98779889**"
handleInputTextChange={handleInputTextChange}
value={form.authorized_contact.input_val}
/>
</div>
)
}
const mapDispatchToProps = { InputStringAction };
function mapStateTopProps (state) {
return {
form: state.Company.form.contact_information,
errors: state.Company.form.errors
}
}
export default AddCompanyHoc('Contact Information', connect(mapStateTopProps, mapDispatchToProps)(ContactInformation));
<file_sep>import React from 'react';
import {Row, Col, Form} from 'reactstrap';
import CompanyInformation from './../components/companies/add_company/CompanyInformation'
import ContactInformation from './../components/companies/add_company/ContactInformation'
import BankDetails from './../components/companies/add_company/BankDetails'
import MailingAddress from './../components/companies/add_company/MailingAddress'
import CustomButton from '../components/buttons/CustomButton';
import { connect } from 'react-redux';
import { addCompanyAction } from './../actions/companyAction'
const AddCompanyContainer = (props) => {
const { form, addCompanyAction } = props;
const onSubmit = async (e) => {
e.preventDefault();
addCompanyAction(form)
}
return (
<>
<Form onSubmit={onSubmit}>
<Row>
<Col sm={6}>
<CompanyInformation/>
<ContactInformation/>
<BankDetails/>
</Col>
<Col sm={6}>
<MailingAddress/>
</Col>
</Row>
<Row>
<Col>
<br />
<CustomButton
type="submit"
name="Submit"
color="primary"
size="sm"/>
</Col>
</Row>
</Form>
</>
)
}
const mapDispatchTopProps = { addCompanyAction };
function mapStateToProps (state) {
return {
form: state.Company.form,
}
}
export default connect(mapStateToProps, mapDispatchTopProps)(AddCompanyContainer);<file_sep>import React from 'react';
import TopNavbar from './components/header/navbar';
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import Home from './pages/Home'
import AddCompany from './pages/AddCompany'
import Companies from './containers/companies';
import Malls from './containers/malls';
import {Container} from 'reactstrap';
function App() {
return (
<Router>
<div>
<TopNavbar />
<Container>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/add-company" component={AddCompany} />
<Route path="/companies" component={Companies} />
<Route path="/malls" component={Malls} />
</Switch>
</Container>
</div>
</Router>
);
}
export default App;
<file_sep>import React, {useEffect} from 'react';
import { companiesListAction } from './../actions/companyAction';
import { connect } from 'react-redux';
import PropTypes from 'prop-types'
import CompaniesList from '../components/companies/list/companies_list';
import {Row, Col} from 'reactstrap';
import { Link } from 'react-router-dom';
const Companies = (props) => {
const { companiesListAction, Company } = props;
const { loading, companies } = Company;
useEffect(() => {
companiesListAction()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const loadCompanies = () => {
return (
<Row>
{
companies.map((company, index) => {
return (
<Col sm={3} key={company.id}>
<CompaniesList company={company} key={company.id} />
</Col>
)
})
}
</Row>
)
}
return (
<>
<h4>Companies</h4>
<Link to="/add-company">Add company</Link>
{
loading
?
'Loading'
:
loadCompanies()
}
</>
)
}
Companies.propTypes = {
companiesListAction: PropTypes.func.isRequired,
loadCompanies: PropTypes.func,
Company: PropTypes.shape({
companies: PropTypes.arrayOf(
PropTypes.shape({
albumId: PropTypes.number.isRequired,
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
thumbnailUrl: PropTypes.string.isRequired
}).isRequired
).isRequired,
loading: PropTypes.bool.isRequired
})
}
const mapDispatchToProps = {companiesListAction}
function mapStateToProps(state) {
return {
Company: state.Company
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Companies); | b7194b49078e0adf509d0c60221d2247b290f57c | [
"JavaScript"
]
| 18 | JavaScript | waqaarKeubik/react-saga | c5a2bb5ec9de70e8ff3f8023014eb237b80c206b | 6382ccc70bf217a9da11aef043783b2171269dac |
refs/heads/master | <file_sep>#ifndef DATA_SERVICE
#define DATA_SERVICE
#include "../config/configService.h"
#include <Arduino.h>
#include <ESP8266HTTPClient.h>
class DataService
{
private:
HTTPClient httpClient;
ConfigService configurationService;
public:
DataService(ConfigService configService);
int sendSensorReadings(String &sensorReadingsJson, String &deviceId, String &sensorNumber);
String getConfiguration(String &deviceId, String &sensorNumber);
String getsensorConfiguration(String &deviceId, String &sensorNumber);
};
#endif<file_sep># PlantManager_Endpoint_Wifi
This project is an augmentation for PlantManager_Endpoint because this code is for ESP-12E to make the arduino nano or pro mini communicate via http.
The communication between the 2 boards is serial. With this wifi module it is possible to configure the whole system remotely.
<file_sep>#include "./wifiService.h"
WifiService::WifiService(ConfigService configService)
{
this->configService = configService;
}
void WifiService::connectIfConfigured()
{
ConfigService configService = this->configService;
if (configService.isCloudConfigured())
{
Configuration config = configService.getConfiguration();
WiFi.begin(config.ssid.c_str(), config.password.c_str());
while (WiFi.waitForConnectResult() != WL_CONNECTED)
{
WiFi.begin(config.ssid.c_str(), config.password.c_str());
}
}
}<file_sep>#ifndef CONFIG_SERVICE
#define CONFIG_SERVICE
#include <Arduino.h>
#include <EEPROM.h>
#include "config.h"
#include "../json/jsonService.h"
class ConfigService
{
private:
JsonService jsonService;
int ConfigurationAddress = 0;
int romSize = 1024;
int saveConfig(String value, bool isReset);
String getConfig();
public:
ConfigService();
ConfigService(JsonService jsonService);
Configuration getConfiguration();
String getRawConfiguration();
void setConfiguration(String config);
bool isCloudConfigured();
};
#endif<file_sep>#include "configService.h"
ConfigService::ConfigService()
{
}
ConfigService::ConfigService(JsonService jsonService)
{
this->jsonService = jsonService;
}
Configuration ConfigService::getConfiguration()
{
String jsonConfig = this->getConfig();
// Serial.println("Get Configuration: ");
// Serial.println(jsonConfig);
Configuration config = this->jsonService.convertJsonToConfig(jsonConfig);
// Serial.println(config.sensorConfiguration);
return config;
}
String ConfigService::getRawConfiguration()
{
return this->getConfig();
}
void ConfigService::setConfiguration(String config)
{
// Serial.println("SetConfiguration");
this->saveConfig(config, false);
// String jsonConfig = this->getConfig();
// Serial.println("Before Jsonconvert");
// Configuration configuration = this->jsonService.convertJsonToConfig(jsonConfig);
// Serial.println("After Jsonconvert");
}
bool ConfigService::isCloudConfigured()
{
Configuration configuration = this->getConfiguration();
return configuration.appServer != "" && configuration.ssid != "" && configuration.password != "";
}
int ConfigService::saveConfig(String value, bool isReset)
{
EEPROM.begin(this->romSize);
// Serial.println("SaveConfig");
int stringLength = isReset ? this->romSize : value.length();
if (stringLength == 0 || value == NULL)
{
return 0;
}
if (isReset)
{
for (int i = 0; i <= value.length(); i++)
{
if (i == value.length())
{
EEPROM.write(i, '\0');
break;
}
EEPROM.write(i, 0);
}
}
else
{
for (int i = 0; i <= value.length(); i++)
{
if (i == value.length())
{
EEPROM.write(i, '\0');
break;
}
EEPROM.write(i, value[i]);
}
}
EEPROM.commit();
EEPROM.end();
return stringLength;
}
String ConfigService::getConfig()
{
EEPROM.begin(this->romSize);
// Serial.println("ReadConfig");
char buffer[EEPROM.length()];
for (int i = 0; i < EEPROM.length(); i++)
{
buffer[i] = EEPROM.read(i);
if (EEPROM.read(i) == '\0')
{
break;
}
}
EEPROM.end();
return buffer;
}<file_sep>#include "./jsonService.h"
Configuration JsonService::convertJsonToConfig(String &configJson)
{
const size_t bufferSize = 1024;
Configuration configuration = Configuration();
StaticJsonDocument<bufferSize> document;
// Serial.println(configJson);
// Serial.println("Before jsonParse");
// Serial.println("Jsonmemory usage: ");
// Serial.println(document.memoryUsage());
auto error = deserializeJson(document, configJson);
if (error)
{
Serial.print(F("deserializeJson() failed with code "));
Serial.println(error.c_str());
return configuration;
}
// Serial.println("Assign values from json");
// Serial.println(config["sensorConfiguration"].as<char *>());
configuration.sensorConfiguration = document["sc"].as<String>();
configuration.appServer = document["appserv"].as<String>();
configuration.ssid = document["ssid"].as<String>();
configuration.password = document["pswd"].as<String>();
document.clear();
// Serial.println("After jsonParse");
// Serial.println("sensorConfiguration from config: ");
// Serial.println(configuration.sensorConfiguration);
// Serial.println(config["sensorConfiguration"].as<String>());
return configuration;
}<file_sep>#include "./wifi/wifiService.h"
#include "./data/dataService.h"
#include "./config/configService.h"
#include "./json/jsonService.h"
#include "./server/serverService.h"<file_sep>#include "./utility.h"
Utility::Utility() {}
void Utility::oscillatePin(uint8_t pinNumber, int frequencyInMilliseconds, uint8_t repetitions)
{
for (uint8_t i = 0; i < repetitions; i++)
{
digitalWrite(pinNumber, LOW);
delay(frequencyInMilliseconds);
digitalWrite(pinNumber, HIGH);
delay(frequencyInMilliseconds);
yield();
}
}<file_sep>#ifndef JSON_SERVICE
#define JSON_SERVICE
#include <ArduinoJson.h>
#include <Arduino.h>
#include "../config/config.h"
#include "../sensor/sensorReading.h"
class JsonService
{
public:
Configuration convertJsonToConfig(String &configJson);
};
#endif<file_sep>#ifndef SENSOR_READING
#define SENSOR_READING
struct SensorReading
{
int temperature;
int humidity;
int dht11ErrorCode;
int soilMoisture;
int waterLevel;
const char* temperatureUnit;
const char* waterLevelUnit;
};
#endif<file_sep>#ifndef UTILITY
#define UTILITY
#include <Arduino.h>
class Utility
{
public:
Utility();
void oscillatePin(uint8_t pinNumber, int frequencyInMilliseconds, uint8_t repetitions);
};
#endif<file_sep>#ifndef CONFIGURATION
#define CONFIGURATION
struct Configuration
{
String appServer;
String ssid;
String password;
String sensorConfiguration;
};
#endif<file_sep>#include <Arduino.h>
#include <SoftwareSerial.h>
#include "./services/services.h"
#include "./utility/utility.h"
int readyPin = 14;
int reConfigPin = 5;
int statusLedPin = 2;
JsonService jsonService;
ConfigService configService(jsonService);
DataService dataService(configService);
WifiService wifiService(configService);
ServerService serverService;
Utility utilities;
String messageFromSensor;
void setup()
{
pinMode(statusLedPin, OUTPUT);
pinMode(readyPin, OUTPUT);
pinMode(reConfigPin, INPUT);
digitalWrite(readyPin, LOW);
Serial.begin(9600);
if (digitalRead(reConfigPin) == HIGH)
{
serverService.start();
}
wifiService.connectIfConfigured();
Serial.swap();
// Serial.println("Not swapped");
digitalWrite(statusLedPin, HIGH);
}
void loop()
{
digitalWrite(readyPin, HIGH);
if (Serial.available())
{
utilities.oscillatePin(statusLedPin, 500, 1);
String sensorId = Serial.readStringUntil(' ');
String sensorIndex = Serial.readStringUntil('\n');
sensorId.trim();
sensorIndex.trim();
// Serial.print("SensorId: ");
// Serial.println(sensorId);
// Serial.print("Sensor Number: ");
// Serial.println(sensorNumber);
// Serial.println("SensorId read");
digitalWrite(readyPin, LOW);
String sensorConfiguration;
if (configService.isCloudConfigured())
{
utilities.oscillatePin(statusLedPin, 500, 2);
sensorConfiguration = dataService.getsensorConfiguration(sensorId, sensorIndex);
}
else
{
utilities.oscillatePin(statusLedPin, 500, 3);
// Serial.println("Configuration from memory: ");
// Serial.println(configService.getConfiguration().sensorConfiguration);
Configuration config = configService.getConfiguration();
// Serial.println(config.sensorConfiguration);
// Serial.println(config.appServer);
// Serial.println(config.ssid);
// Serial.println(config.password);
sensorConfiguration = config.sensorConfiguration;
sensorConfiguration.replace("'", "\"");
}
// Serial.println("Sending plant growing step config");
Serial.println(sensorConfiguration);
if (configService.isCloudConfigured())
{
while (!Serial.available())
{
yield();
}
// Serial.println("Before sensor read");
messageFromSensor.concat(Serial.readStringUntil('\n'));
dataService.sendSensorReadings(messageFromSensor, sensorId, sensorIndex);
utilities.oscillatePin(statusLedPin, 500, 4);
}
Serial.flush();
Serial.end();
ESP.deepSleep(0);
}
}
<file_sep>#include "./serverService.h"
ServerService::ServerService()
{
this->server = new ESP8266WebServer(LOCAL_IP, PORT);
}
void ServerService::configureAccessPoint()
{
WiFi.softAPConfig(LOCAL_IP, GATEWAY, SUBNET);
WiFi.softAP("PlantManager_Device");
}
void ServerService::configureServer()
{
this->server->on("/", HTTP_GET, [this]() {
this->server->send(200, "application/json", "{\"deviceId\": \"" + DEVICE_ID + "\"""}");
delay(300);
});
this->server->on("/configuration", HTTP_GET, [this]() {
server->send(200, "application/json", this->configService.getRawConfiguration());
delay(300);
});
server->on("/configuration", HTTP_PUT, [this]() {
if (server->hasArg("plain") == false)
{
server->send(400);
}
else
{
this->configService.setConfiguration(server->arg("plain"));
server->send(200, "application/json", this->configService.getRawConfiguration());
}
});
}
void ServerService::startListening()
{
this->server->begin();
while (!this->isConfigSet)
{
this->server->handleClient();
utility.oscillatePin(StatusLedPin, 100, 3);
}
this->dispose();
}
void ServerService::dispose()
{
this->server->stop();
this->server->close();
this->server->~ESP8266WebServer();
}
void ServerService::shutDownAccessPoint()
{
ConfigService configService = this->configService;
Configuration config = configService.getConfiguration();
WiFi.mode(WIFI_AP_STA);
WiFi.enableAP(false);
}
void ServerService::start()
{
this->configureAccessPoint();
this->configureServer();
this->startListening();
this->shutDownAccessPoint();
}<file_sep>#ifndef CONSTANTS
#define CONSTANTS
const String DEVICE_ID = "a8997fcd-328e-43f7-98b0-4c75390f89c10";
const int StatusLedPin = 12;
const IPAddress LOCAL_IP(192, 168, 1, 100);
const IPAddress GATEWAY(192, 168, 1, 1);
const IPAddress SUBNET(255, 255, 255, 0);
const int PORT = 80;
#endif
<file_sep>#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include "../config/configService.h"
#include "../../constants.h"
class WifiService
{
private:
ConfigService configService;
bool isWifiConfigured();
public:
WifiService(ConfigService configService);
void connectIfConfigured();
};<file_sep>#include "dataService.h"
DataService::DataService(ConfigService configService)
{
this->configurationService = configService;
}
int DataService::sendSensorReadings(String &sensorReadingsJson, String &deviceId, String &sensorIndex)
{
Configuration config = this->configurationService.getConfiguration();
String requestUrl = config.appServer + "/readings/" + deviceId + "/" + sensorIndex + "/iot";
httpClient.begin(requestUrl);
httpClient.addHeader("Content-Type", "application/json");
int httpStatusCode = httpClient.POST(sensorReadingsJson);
// if (httpStatusCode != HTTP_CODE_CREATED)
// {
// Serial.println("RequestUrl:");
// Serial.println(requestUrl);
// Serial.println(httpStatusCode);
// }
httpClient.end();
return httpStatusCode;
}
String DataService::getConfiguration(String &deviceId, String &sensorIndex)
{
Configuration config = this->configurationService.getConfiguration();
String configPayload = "";
String requestUrl = config.appServer + "/devices/" + deviceId + "/" + sensorIndex + "/iot/configuration";
httpClient.begin(requestUrl);
int httpStatusCode = httpClient.GET();
if (httpStatusCode == HTTP_CODE_OK)
{
configPayload = httpClient.getString();
}
// else
// {
// Serial.println("RequestUrl:");
// Serial.println(requestUrl);
// Serial.println(httpStatusCode);
// }
httpClient.end();
return configPayload;
}
String DataService::getsensorConfiguration(String &deviceId, String &sensorNumber)
{
Configuration config = this->configurationService.getConfiguration();
String sensorConfiguration = "";
String requestUrl = config.appServer + "/devices/" + deviceId + "/" + sensorNumber + "/iot/configuration";
// Serial.print("Request URL");
// Serial.println(requestUrl);
httpClient.begin(requestUrl);
int httpStatusCode = httpClient.GET();
if (httpStatusCode == HTTP_CODE_OK)
{
sensorConfiguration = httpClient.getString();
}
// else
// {
// Serial.println("RequestUrl:");
// Serial.println(requestUrl);
// Serial.println("StatusCode");
// Serial.println(httpStatusCode);
// }
httpClient.end();
// Serial.println("sensorConfiguration");
// Serial.println(sensorConfiguration);
return sensorConfiguration;
}<file_sep>#ifndef SERVER_SERVICE
#define SERVER_SERVICE
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include "../config/configService.h"
#include "../../constants.h"
#include "../../utility/utility.h"
class ServerService
{
private:
ConfigService configService;
JsonService jsonService;
Utility utility;
ESP8266WebServer *server;
bool isConfigSet = false;
void configureAccessPoint();
void configureServer();
void shutDownAccessPoint();
void connectToWifiNetwork();
void startListening();
void dispose();
public:
ServerService();
void start();
};
#endif | 09c8056aac43706a1060608602a1670d7049d583 | [
"Markdown",
"C",
"C++"
]
| 18 | C++ | lkiss/PlantManager_Endpoint_Wifi | 0989cb89e503d618f87778040daf03a7938a80db | 9dc4f9cc72b13106b29a780202750ff2c4a4770f |
refs/heads/main | <file_sep><?php
require_once("maincore.php");
require_once(BASEDIR.STYLE."tpl.start.php");
require_once("lea.core.php");
score_games();
if( session_check() == TRUE AND TRUE == db_get_data("active","lea_players","user_id",$_SESSION['userid']) AND check_int($_GET['id']) == TRUE )
{
if(@$_POST['send'] == "msg")
{
$msg = addslashes(htmlspecialchars($_POST['msg']));
$sql = "INSERT INTO ".DBPREFIX."lea_msg VALUES('','".$msg."','".@db_get_data("id","users","login",$_SESSION['login'])."','".$_GET['id']."','".DATETIME."','".USER_IP."');";
mysql_query($sql);
unset($msg,$sql);
}
$sql1 = "SELECT * FROM ".DBPREFIX."lea_msg WHERE `challange_id` = '".$_GET['id']."' ORDER BY `date` ASC";
$query1 = mysql_query($sql1);
$sql2 = "SELECT * FROM ".DBPREFIX."lea_challanges WHERE `id` = '".$_GET['id']."' LIMIT 1";
$query2 = mysql_query($sql2);
$game = mysql_fetch_assoc($query2);
echo "<table class='table0 w100'>\n";
echo " <tr><th colspan='3'>".db_get_data("gamenick","users","id",$game['player1'])." vs ".db_get_data("gamenick","users","id",$game['player2'])."</th></tr>\n";
echo " <tr><td class='center'><h6>".substr($game['start'],0,16)."</h6></td><td class='center'><h6>".$game['nations']."</h6></td><td class='center'><h6>".substr($game['end'],0,16)."</h6></td></tr>\n";
echo " <tr><td colspan='3' class='center'><h6><a href='lea.system.php'>Powrót</a></h6></td></tr>\n";
if(mysql_num_rows($query1) > 0)
{
$i = 0;
while($msg = mysql_fetch_assoc($query1))
{
$i = $i+1; $class = "";
if($i % 2 == 0) $class = " class='row2'";
echo " <tr".$class."><td><b>".db_get_data("gamenick","users","id",$msg['author'])."</b></td><td></td><td class='right'>".substr($msg['date'],0,16)."</td></tr>\n";
echo " <tr".$class."><td colspan='3'>".Codes(stripslashes($msg['message']))."</td></tr>\n";
}
}
echo "</table>\n";
if(($game['accepted'] == 2) AND (@db_get_data("id","users","login",$_SESSION['login']) == $game['player1'] OR @db_get_data("id","users","login",$_SESSION['login']) == $game['player2'] OR session_check_usrlevel() >= SPECIAL_LVL))
{
echo "<br>\n";
echo "<table class='table0 w100 form-style1'>\n";
echo " <tr>\n";
echo " <form action='' method='post'>\n";
echo " <td class='w100'><input type='text' name='msg' class='text'></td><td><input type='hidden' name='send' value='msg'><input type='submit' class='submit' value='OK'></td>\n";
echo " </form>\n";
echo " </tr>\n";
echo "</table>\n";
}
}
else
{
echo "<div class='not'>Zaloguj się</div>\n";
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "users" AND session_check_usrlevel() >= SPECIAL_LVL )
{
session_check();
if( isset($_POST['send']) )
{
if ( @$_POST['id'] != $config['headadmin'] OR $_SESSION['userid'] == $config['headadmin'] )
{
// update 1st section
if( @$_POST['send'] == "upt-i" )
{
$sql_test = "SELECT `id` FROM ".DBPREFIX."users WHERE `login` = '".$_POST['form1']."' AND `id` != '".$_POST['id']."'";
if( mysql_num_rows(mysql_query($sql_test)) == TRUE ) $test[0] = FALSE; else $test[0] = TRUE;
if( $_POST['form2'] != $_POST['form3'] ) $test[1] = FALSE; else $test[1] = TRUE;
$sql_test = "SELECT `id` FROM ".DBPREFIX."users WHERE `mail` = '".$_POST['form4']."' AND `id` != '".$_POST['id']."'";
if( mysql_num_rows(mysql_query($sql_test)) == TRUE ) $test[2] = FALSE; else $test[2] = TRUE;
if( $test[0] == TRUE AND $test[1] == TRUE AND $test[2] == TRUE AND check_int($_POST['id']) == TRUE )
{
$upt['login'] = htmlspecialchars($_POST['form1']);
$upt['mail'] = htmlspecialchars($_POST['form4']);
$sql = "UPDATE `".DBPREFIX."users` SET `login` = '".$upt['login']."', `mail` = '".$upt['mail']."' WHERE `id` = ".$_POST['id']." LIMIT 1";
if( $_SESSION['login'] == $_POST['old_login'] ) $_SESSION['login'] = $upt['login'];
mysql_query($sql);
$result = "Dane poza hasłem zostały zaaktualizowane.";
if( strlen($_POST['form2']) > 3 )
{
$upt['pass'] = md5(htmlspecialchars(addslashes($_POST['form2'])));
$sql = "UPDATE `".DBPREFIX."users` SET `password` = '".md5(htmlspecialchars(addslashes($_POST['form2'])))."' WHERE `id` = ".$_POST['id']." LIMIT 1";
mysql_query($sql);
$result = "Dane z hasłem zostały zaaktualizowane.";
}
elseif( strlen($_POST['form2']) > 0) $result = "Dane poza hasłem zostały zmienione.<br>Hasło powinno zawierać conajmniej 4 znaki!";
}
else $result = "Błąd, dane nie zostały zmienione.";
}
// update 2nd section
if( @$_POST['send'] == 'upt-r' )
{
if( check_int($_POST['form5']) == TRUE ) $upt['gg'] = $_POST['form5']; else $upt['gg'] = 0;
if( check_int($_POST['form6']) == TRUE ) $upt['icq'] = $_POST['form6']; else $upt['icq'] = 0;
@$upt['gamenick'] = htmlspecialchars($_POST['form7a']);
@$upt['clan'] = htmlspecialchars($_POST['form7']);
@$upt['frules'] = htmlspecialchars($_POST['form8']);
@$upt['utitle'] = htmlspecialchars($_POST['form9']);
@$upt['desc'] = addslashes($_POST['form9b']);
@$upt['name'] = htmlspecialchars($_POST['form10']);
@$upt['gender'] = $_POST['form11'];
@$upt['intrest'] = htmlspecialchars($_POST['form12']);
@$upt['location'] = htmlspecialchars($_POST['form13']);
@$upt['country'] = db_get_data("code","reg_countries","name",$_POST['form14']) ;
@$upt['born'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds'];
if( TRUE == TRUE )
{
$sql = "UPDATE `".DBPREFIX."users` SET
`gg` = '".@$upt['gg']."', `icq` = '".@$upt['icq']."',
`gamenick` = '".@$upt['gamenick']."', `clan` = '".@$upt['clan']."',
`favrules` = '".@$upt['frules']."', `usertitle` = '".@$upt['utitle']."',
`desc` = '".@$upt['desc']."',
`name` = '".@$upt['name']."', `gender` = '".@$upt['gender']."',
`intrest` = '".@$upt['intrest']."', `location` = '".@$upt['location']."',
`country` = '".@$upt['country']."', `born` = '".@$upt['born']."',
`gamenick` = '".@$upt['gamenick']."'
WHERE `id` = '".$_POST['id']."' LIMIT 1";
mysql_query($sql);
$result = "Dane zostały zaaktualizowane.";
}
}
// update 3rd section
if( @$_POST['send'] == 'upt-s' )
{
$upt['active'] = $_POST['form16'];
if( check_int($_POST['form17']) == TRUE AND $_POST['form17'] >= 0 AND $_POST['form17'] <= 200 ) $upt['level'] = $_POST['form17'];
$upt['rights'] = htmlspecialchars($_POST['form18']);
$sql = "UPDATE `".DBPREFIX."users` SET `active` = '".$upt['active']."', `level` = '".$_POST['form17']."', `rights`='".$upt['rights']."' WHERE `id` = '".$_POST['id']."' LIMIT 1";
if( $_SESSION['userid'] == $config['headadmin'] AND $_SESSION['userid'] == $_POST['id'] )
{
if( $upt['active'] == 1 AND $upt['rights'] == "M.A.SA" AND $upt['level'] >= SPECIAL_LVL )
{
mysql_query($sql);
$result = "Dane zostały zaaktualizowane";
}
else $result = "Jesteś głównym admistratorem, nie możesz zmniejszyć sobie praw niższego rzędu!";
}
else
{
mysql_query($sql);
$result = "Dane zostały zaaktualizowane";
}
session_check();
}
}
else $result = "Nie masz odpowiednich uprawnień aby ingerować w konto głównego administratora!";
}
if( session_check() == TRUE )
{
if( !isset($_POST['send']) )
{
echo "<div align='center'>\n";
echo "<table class='table0 w75 form-style1'>\n";
echo "<tr><th colspan='2'>Operacje na użytkownikach</th></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td><input class='w100' type='text' name='user_login' value=''/></td>";
echo "<td class='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
echo "</div>\n";
}
if( isset($_POST['send']) OR isset($_POST['user_login']) )
{
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
if(isset($_POST['user_login'])) $sql = "SELECT * FROM `".DBPREFIX."users` WHERE `login` = '".htmlspecialchars($_POST['user_login'])."' LIMIT 1";
else $sql = "SELECT * FROM `".DBPREFIX."users` WHERE `id` = '".$_POST['id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) == TRUE )
{
$data = mysql_fetch_assoc($query);
$data['desc'] = stripslashes($data['desc']);
$data['country'] = db_get_data("name","reg_countries","code",$data['country']);
$ys = substr($data['born'],0,4); $ms = substr($data['born'],5,2);
$ds = substr($data['born'],8,2);
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Operacje na użytkowniku</th></tr>\n";
echo "<tr><td colspan='2'><h6>użytkownik: ".$data['login']."<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
echo "<tr><td colspan='2'><h6>Ostatnia aktywność</h6></td></tr>\n";
echo "<tr><td width='200'>Data</td><td>".$data['last_date']."</td></tr>\n";
echo "<tr><td width='200'>IP rejestracji</td><td>".$data['register_ip']."</td></tr>\n";
echo "<tr><td width='200'>IP ostatnio</td><td>".$data['last_ip']."</td></tr>\n";
echo " <tr> <!-- Dane rejestracji --> <td colspan='2'><h6>Dane rejestracji</h6></td></tr>\n";
echo " <tr><form action='' method='post'>\n";
echo " <td width='200'>Login</td><td><input type='hidden' name='old_login' value='".$data['login']."'/><input class='text' type='text' name='form1' value='".$data['login']."'/></td></tr>\n";
echo " <tr><td width='200'>Hasło</td><td><input class='text' type='password' name='form2' value=''/> <span class='text-tiny'>Pozostaw puste</span></td></tr>\n";
echo " <tr><td width='200'>Potwierdź hasło</td><td><input class='text' type='password' name='form3' value=''/> <span class='text-tiny'>aby nie zmieniać</span></td></tr>\n";
echo " <tr><td width='200'>e-Mail</td><td><input class='text' type='text' name='form4' value='".$data['mail']."'/></td></tr>\n";
echo " <tr><td colspan='2' align='center'>\n <input type='hidden' name='id' value='".$data['id']."'/>\n <input type='hidden' name='send' value='upt-i'/>\n <input class='submit' type='submit' value='Wyślij'/>\n </td>\n";
echo " </form></tr>\n";
echo " <tr> <!-- Dane kontaktowe --> <td colspan='2'><h6>Dane kontaktowe</h6></td></tr>\n";
echo " <tr><form class='form-style2' action='' method='post'>\n";
echo " <td width='200'>GG:</td><td><input class='w50' type='text' name='form5' value='".$data['gg']."'/></td></tr>\n";
echo " <tr><td width='200'>ICQ:</td><td><input class='w50' type='text' name='form6' value='".$data['icq']."'/></td></tr>\n";
echo " <tr> <!-- Dane o graczu --> <td colspan='2'><h6>Dane dotyczące gracza</h6></td></tr>\n";
echo " <tr><td width='200'>Nick:</td><td><input class='text' type='text' name='form7a' value='".$data['gamenick']."'/></td></tr>\n";
echo " <tr><td width='200'>Klan:</td><td><input class='p50' type='text' name='form7' value='".$data['clan']."'/></td></tr>\n";
echo " <tr><td width='200'>Ulubione rules:</td><td><input class='text' type='text' name='form8' value='".$data['favrules']."'/></td></tr>\n";
echo " <tr><td width='200'>Tytuł:</td><td><input class='text' type='text' name='form9' value='".$data['usertitle']."'/></td></tr>\n";
echo " <tr><td width='200'>Opis:</td><td><textarea class='textarea' name='form9b'>".@$data['desc']."</textarea></td></tr>\n";
echo " <tr> <!-- Dane personalne --> <td colspan='2'><h6>Dane personalne</h6></td></tr>\n";
echo " <tr><td width='200'>Imię:</td><td><input class='text' type='text' name='form10' value='".$data['name']."'/></td></tr>\n";
echo " <tr><td width='200'>Płeć:</td><td>".form_option_bool($data['gender'],"form11","Kobieta","Mężczyzna")."</td></tr>\n";
echo " <tr><td width='200'>Zainteresowania:</td><td><input class='text' type='text' name='form12' value='".$data['intrest']."'/></td></tr>\n";
echo " <tr><td width='200'>Miejscowość:</td><td><input class='text' type='text' name='form13' value='".$data['location']."'/></td></tr>\n";
echo " <tr><td width='200'>Kraj:</td><td><input class='text' type='text' name='form14' value='".$data['country']."'/></td></tr>\n";
echo " <tr><td width='200'>Data urodzin:</td><td>";
echo form_date_born("ys",1940,2040,"Y",60,$ys);
echo form_date_born("ms",1,12,"m",40,$ms);
echo form_date_born("ds",1,31,"d",40,$ds);
echo " </td></tr>\n";
echo " <tr><td colspan='2' align='center'>\n <input type='hidden' name='id' value='".$data['id']."'/>\n <input type='hidden' name='send' value='upt-r'/>\n <input class='submit' type='submit' value='Wyślij'/>\n </td>\n";
echo " </form></tr>\n";
echo " <tr> <!-- Specjalne pola edycji administratora --> <td colspan='2'><h6>Specjalne</h6></td></tr>\n";
echo " <tr><form class='form-style2' action='' method='post'>\n";
echo " <td width='200'>Aktywny:</td><td>".form_option_bool($data['active'],"form16","Tak","Nie")."</td></tr>\n";
echo " <tr><td width='200'>Zezwolenia:</td><td><select style='width:262px;' name='form17'><option value='0'>Użytkownik</option><option value='101'"; if( $data['level'] == 101 ) echo " selected='selected'"; echo ">Administrator</option></select></td></tr>\n";
echo " <tr><td width='200'>Prawa:</td><td><input class='text' type='text' name='form18' value='".$data['rights']."'/></td></tr>\n";
echo " <tr><td colspan='2' align='center'>\n <input type='hidden' name='id' value='".$data['id']."'/>\n <input type='hidden' name='send' value='upt-s'/>\n <input class='submit' type='submit' value='Wyślij'/>\n </td>\n";
echo " </form></tr>\n";
echo "</table>\n";
}
else echo "<div class='err'>Brak użytkownika o podanym loginie</div>\n";
}
}
}
?>
<file_sep><style type="text/css">
table {
border:1px solid #D00;
}
th {
background:#000;color:#FFF;
}
td {
width:22px;text-align:center;
}
.sunday {
color:#d00;font-weight:bold;
}
.saturday {
font-weight:bold;
}
</style>
<?php
$CountOfDays = array(31,28,31,30,31,30,31,31,30,31,30,31);
if((date('Y')%4) == 0) $CountOfDays[1] = 29;
$m['actual'] = date('n')-1;
$m['name'] = array('Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień');
$d['actual']['week'] = date('w');
$d['actual']['month'] = date('j');
$d['first']['week'] = date('w');
$test = date('j');
while( $test > 7 )
{ $test = $test - 7; }
while( $test != 1 )
{ $d['first']['week'] = $d['first']['week'] - 1;$test = $test-1; if($d['first']['week'] == -1) $d['first']['week'] = 6; }
echo "<table>";
echo "<tr><th colspan='7'>".$m['name'][$m['actual']]."</th></tr>";
echo "<tr><td class='sunday'>N</td><td>P</td><td>W</td><td>Ś</td><td>C</td><td>P</td><td class='saturday'>S</td></tr>";
echo "<tr>";
for( $i = 0;$i < $d['first']['week'];$i++){ echo "<td>0</td>"; }
$d['printed']['week'] = $d['first']['week'];
for( $i=1;$i<=$CountOfDays[$m['actual']];$i++ )
{
if( $d['printed']['week'] == 7 ){ $d['printed']['week'] = 0;echo "</tr><tr>"; }
echo "<td>".$i."</td>";
$d['printed']['week'] = $d['printed']['week']+1;
}
echo "</tr>";
echo "</table>";
?>
<file_sep><?php
require_once "maincore.php";
if(!empty($_GET['id']) AND check_int($_GET['id']) == TRUE) $article = mysql_fetch_assoc(mysql_query("SELECT `title` FROM `".DBPREFIX."articles` WHERE `id` = '".$_GET['id']."' LIMIT 1"));
add_title(stripslashes($article['title']));
require_once (BASEDIR.STYLE."tpl.start.php");
if( !empty($_GET['id']) AND check_int($_GET['id']) == TRUE )
{
// add vote & comment
if( @$_POST['send'] == "vote" )
{
$sql = "SELECT * FROM `".DBPREFIX."ratings` WHERE `item_id` = '".$_GET['id']."' AND `item_type` = 'A' AND `user` = '".@db_get_data("id","users","login",$_SESSION['login'])."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query)) { $result = "Już oceniałeś ten artykuł"; }
else
{
$sql = "INSERT INTO `".DBPREFIX."ratings` VALUES(NULL, '".$_GET['id']."', 'A', '".$_POST['vote']."', '".@db_get_data("id","users","login",$_SESSION['login'])."', '".DATETIME."', '".USER_IP."');";
mysql_query($sql);
}
}
if( @$_POST['send'] == "comment" )
{
$sql = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$_GET['id']."' AND `item_type` = 'A' AND `user` = '".@db_get_data("id","users","login",$_SESSION['login'])."' ORDER BY `date` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$t = TRUE;
while( $test = mysql_fetch_assoc($query) )
{
if( get_time_difference($test['date']) < $config['antyflood'] )
{
$t = FALSE;
$result = "Musisz odczekać ".$config['antyflood']." sekund od ostatniego komentarza";
}
}
if( $t == TRUE )
{
$msg = addslashes(htmlspecialchars($_POST['comment']));
$sql = "INSERT INTO `".DBPREFIX."comments` VALUES(NULL,'".$_GET['id']."', 'A', '".$msg."', '".@db_get_data("id","users","login",$_SESSION['login'])."', '".DATETIME."', '".USER_IP."');";
mysql_query($sql);
}
}
// fixing choosed article
$sql = "SELECT * FROM `".DBPREFIX."articles` WHERE `id` = '".$_GET['id']."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == 1)
{
$article = mysql_fetch_assoc($query);
$author = @db_get_data("login","users","id",$article['author']);
$date = @split("[ :.]",$article['date_start']);
if (@$date[3] == 00 AND @$date[4] == 00 AND @$date[5] == 00) $article['date_start'] = $date[0];
if(empty($author)) $author = "?";
// printing an article
echo "<div class='post-title'><h2>".stripslashes($article['title'])."</h2></div>\n";
if( $article['allow_comment'] == 1 OR $article['allow_rating'] == 1 OR 1 == 1 )
{
echo "<div class='post-info'>Napisany przez ".$author." ".$article['date_start']."</div>\n";
}
echo "<div class='post-content'>\n".emots(stripslashes($article['content']))."\n</div>\n";
if( $article['allow_comment'] == 1 OR $article['allow_rating'] == 1 )
{
echo "<div class='post-footer text-tiny'>";
// :: fixing count of comments & rates
$sql2 = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$article['id']."' AND `item_type` = 'A' ORDER BY `date` DESC";
$query2 = mysql_query($sql2);
$i = mysql_num_rows($query2);
$sql2 = "SELECT * FROM `".DBPREFIX."ratings` WHERE `item_id` = '".$article['id']."' AND `item_type` = 'A'";
$query2 = mysql_query($sql2);
$rated = 0;
$r = 0;
// :: fixing summary for rating
if(mysql_num_rows($query2) > 0)
{
while($vote = mysql_fetch_assoc($query2))
{
$rated = $rated+$vote['vote'];
$r++;
}
}
$rated = @round($rated/$r,2);
if( $article['allow_comment'] == 1 )echo $i." komentarzy";
if( $article['allow_comment'] == 1 AND $article['allow_rating'] == 1 )echo " | ";
if( $article['allow_rating'] == 1 )
{
if( $rated == FALSE AND mysql_num_rows($query2) == 0 ) echo "Brak ocen";
else echo "Ocena: ".$rated." (".$r.")";
}
echo "<span class='right'>Czytano wcześniej ".$article['reads']." razy</span>";
echo "</div>\n";
// comments
if( $article['allow_comment'] == 1 )
{
if( session_check() == TRUE )
{
echo "<a name='comment'></a><form class='form-style1' action='' method='post'>\n";
echo "<input type='text' name='comment' value='' class='w50'/>\n";
echo "<input type='hidden' name='send' value='comment'/><input type='submit' class='submit' value='Skomentuj'/>\n";
echo "</form>\n";
}
else echo "<div class='comment'><div class='comment-head'>Zaloguj się aby móc komentować</div></div>";
}
if( $article['allow_rating'] == 1 )
{
if( session_check() == TRUE )
{
echo form_rating();
}
else echo "<div class='comment'><div class='comment-head'>Zaloguj się aby móc ocenić artykuł</div></div>";
}
// printing list of comments
if(isset($result))echo "<div class='err'>".$result."</div>\n";
$sql2 = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$_GET['id']."' AND `item_type` = 'A' ORDER BY `date` DESC";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) > 0)
{
while($comment = mysql_fetch_assoc($query2))
{
if( empty($comment['ip']) ) $comment['ip'] = "Błąd! Nie znaleziono IP wpisu";
elseif( session_check_usrlevel() >= SPECIAL_LVL ) $adm_info = "<span class='right'><img src='images/icons/info.png' width='12' height='12' title='".$comment['ip']."'/></span>";
echo "<div class='comment'>\n";
echo "<div class='comment-head'>".$comment['date']." skomentowany przez <strong>".@db_get_data("login","users","id",$comment['user'])."</strong>".@$adm_info."</div>\n";
echo "<div class='comment-text'>".Codes($comment['message'])."</div>\n";
echo "</div>\n";
}
}
}
}
else
{
echo "<div class='err'>";
echo "Nie znaleziono wybranego artykułu. Wróć na <a href='index.php'>stronę główną</a>";
echo "</div>\n";
}
$areads = $article['reads']+1;
$sql = "UPDATE `".DBPREFIX."articles` SET `reads` = '".$areads."' WHERE `id` = ".$_GET['id']." LIMIT 1";
mysql_query($sql);
}
require_once (BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "clan" AND session_check_usrlevel() >= SPECIAL_LVL )
{
session_check();
if(@$_POST['send']==1)
{
$upt['date'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds'];
$sql = "UPDATE ".DBPREFIX."users SET `siteclan_member` = '".$_POST['set1']."'";
if( $_POST['set1'] == 0 ) $sql.= ",`siteclan_date` = NULL";
else $sql.= ",`siteclan_date` = '".$upt['date']."'";
$sql.= " WHERE `login` = '".$_POST['set0']."' LIMIT 1";
mysql_query($sql);
$result = "Zaaktualizowano";
}
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w100 form-style1' >\n";
echo "<tr><th colspan='4'>Zarządzanie klanem</th></tr>\n";
echo "<tr><td colspan='4'><h6><a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
echo "<tr>\n";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Login</td><td colspan='3'><input class='w50' type='text' name='set0' value=''/> Od: ";
echo form_select_date("ys",2000,date("Y"),"Y",60);
echo form_select_date("ms",1,12,"m",40,1);
echo form_select_date("ds",1,31,"d",40,1);
echo "</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td> </td><td colspan='3'>";
echo form_option_bool(1,"set1","Dodaj","Skasuj");
echo "</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td> </td><td colspan='3'><input type='hidden' name='send' value='1' /><input class='submit' type='submit' value='OK' /></td>\n";
echo "</form>\n";
echo "</tr>\n";
$sql = "SELECT * FROM ".DBPREFIX."users WHERE `siteclan_member` = '1' ORDER BY `login` ASC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <tr><td width='150'><h6>Login</h6></td><td class='center'><h6>W klanie od</h6></td><td><h6 class='center'>Aktywność</h6></td><td class='center'><h6>on-line</h6></td></tr>\n";
while($user = mysql_fetch_assoc($query))
{
if(get_time_difference($user['last_date'])<2678400) $active = "Aktywny</span>";
else $active = "<span class='red' title='Ostatnio widziany: ".$user['last_date']."'>Nieaktywny</span>";
if(get_time_difference($user['last_date'])<300) $online = "<span class='green'>on-line</span>";
else $online = "";
$clantime = explode("-",$user['siteclan_date']);
if ( $clantime[0] == "0000" OR empty($clantime[0]) ) $clantime[0] = "Brak danych";
echo " <tr><td width='150'>".$user['login']."</td><td class='center'>".$clantime['0']."-".$clantime['1']."-".$clantime['2']."</td><td class='center'>".$active."</td><td class='center'>".$online."</td></tr>\n";
}
}
echo "</table>\n";
}
?>
<file_sep><?php
if( $_GET['option'] == "links" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
// fixing last item id
$sql = "SELECT `id` FROM `".DBPREFIX."links` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// new item
if( @$_POST['send'] == "new" AND check_int($_POST['form3']) == TRUE)
{
$new['id'] = $last_id+1;
$new['name'] = addslashes($_POST['form1']);
$new['url'] = addslashes($_POST['form2']);
$new['order'] = $_POST['form3'];
$new['cat'] = $_POST['form4'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "INSERT INTO `".DBPREFIX."links` VALUES('".$new['id']."','".$new['name']."','".$new['url']."','".$new['order']."','".$new['cat']."');";
mysql_query($sql);
$result = "Link został dodany";
}
}
// edit item
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."links` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['name'] = stripslashes($data['name']);
$edit['url'] = stripslashes($data['url']);
$edit['order'] = $data['order'];
$edit['cat'] = $data['cat'];
}
$send_new = "update";
$result = "Wczytano poprawnie";
}
// update item
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE AND check_int($_POST['form3']) == TRUE )
{
$upt['name'] = addslashes($_POST['form1']);
$upt['url'] = addslashes($_POST['form2']);
$upt['order'] = $_POST['form3'];
$upt['cat'] = $_POST['form4'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "UPDATE `".DBPREFIX."links` SET `name` = '".$upt['name']."', `url` = '".$upt['url']."', `order` = '".$upt['order']."', `cat` = '".$upt['cat']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Link został zaaktualizowany";
}
}
mysql_query($sql);
}
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
if( @strlen($edit['name']) > 50 ) $table_info = substr($edit['name'],0,50)."...";
elseif( isset( $edit['name']) ) $table_info = $edit['name'];
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie łączami</th></tr>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>".$table_info."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Nazwa</td><td><input class='text' type='text' name='form1' value='".@$edit['name']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Adres</td><td><input class='text' type='text' name='form2' value='".@$edit['url']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kolejność</td><td><input class='p50' type='text' name='form3' value='".@$edit['order']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kategoria</td><td>\n";
$sql = "SELECT * FROM `".DBPREFIX."links_cat` WHERE `order` > 0";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
echo "<select name='form4' class='w50'>\n";
echo "<option value='0'>Nie pokazuj</option>\n";
while( $cat = mysql_fetch_assoc($query) )
{
echo "<option value='".$cat['id']."'"; if( $cat['id'] == @$edit['cat'] ) echo " selected='selected'"; echo ">".$cat['name']."</option>\n";
}
echo "</select>\n";
}
echo "</td>\n";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "<tr><td colspan='2' align='left'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<form action='' method='post'>\n";
echo "<td class='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT * FROM `".DBPREFIX."links_cat` ORDER BY `order` ASC";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
echo " <select name='choosed_id' class='select'>\n";
while($cat = mysql_fetch_assoc($query))
{
echo "<optgroup label='".$cat['name']; if($cat['order'] == 0) echo " (ukryta)"; echo "'>\n";
$sql2 = "SELECT * FROM `".DBPREFIX."links` WHERE `cat` = '".$cat['id']."' ORDER BY `name` ASC";
$query2 = mysql_query($sql2);
if( mysql_num_rows($query2) > 0 )
{
while($link = mysql_fetch_assoc($query2))
{
echo " <option value='".$link['id']."'>".$link['name']." :: [".$link['url']."]</option>\n";
}
}
echo "</optgroup>\n";
}
$sql2 = "SELECT * FROM `".DBPREFIX."links` WHERE `cat` = '0' ORDER BY `name` ASC";
$query2 = mysql_query($sql2);
if( mysql_num_rows($query2) > 0 )
{
echo "<optgroup label='Ukryte (bez kategorii)'>\n";
while($link = mysql_fetch_assoc($query2))
{
echo " <option value='".$link['id']."'>".$link['name']." :: [".$link['url']."]</option>\n";
}
echo "</optgroup>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
if( $_GET['option'] == "chat" AND session_check_usrlevel() >= SPECIAL_LVL )
{
session_check();
if(@$_POST['send'] == "chat_set" AND !empty($_POST['form2']) AND check_int($_POST['form2']) == TRUE AND check_int($_POST['form3']) == TRUE )
{
$sql = "UPDATE `".DBPREFIX."shoutbox_set` SET `display` = '".$_POST['form1']."', `rows` = '".$_POST['form2']."', `max_lenght` = '".$_POST['form3']."' LIMIT 1";
mysql_query($sql);
$result = "Zaaktualizowano ustawienia";
}
$sql = "SELECT * FROM `".DBPREFIX."shoutbox_set` LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
if( mysql_num_rows($query) == 0 ) mysql_query("INSERT INTO ".DBPREFIX."shoutbox_set VALUES ('0','0');");
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<h2>Zarządzanie shoutboxem</h2>\n";
echo "<form class='form-style2' action='' method='post'>\n";
echo "<table class='table0'>\n";
echo "<tr><th colspan='2' align='left'> </th></tr>\n";
echo "<tr>";
echo "<td width='200'>Pokaż</td><td>".form_option_bool($data['display'],"form1","Pokaż","Wyłącz")."</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td width='200'>Liczba wiadomości</td><td><input class='w30' type='text' name='form2' value='".$data['rows']."'/> <span class='text-tiny'>Ilość wyświetlanych wiadomości w shoutboxie</span></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td width='200'>Liczba znaków / wiadomość</td><td><input class='w30' type='text' name='form3' value='".$data['max_lenght']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
echo "<input type='hidden' name='send' value='chat_set'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</tr>\n";
echo "</table>\n";
echo "</form>\n";
}
?>
<file_sep><?php
/*
/* Maincore file
/* Created by <NAME>
/* for Polish Revolution clan
/* (c) 2012 All rights reserved
/* Integral part of Polish Revolution's website
/*----------------------------------------------*/
ob_start();
if (preg_match("/maincore.php/i", $_SERVER['PHP_SELF'])) { die(""); }
$level = ""; $i = 0;
while (!file_exists($level."config.php")) {
$level .= "../"; $i++;
if ($i == 5) { die("Config file not found"); }
}
require_once $level."config.php";
if (!isset($dbname)) redirect("install.php");
define("BASEDIR", $level);
define("USER_IP", $_SERVER['REMOTE_ADDR']);
define("SCRIPT_SELF", basename($_SERVER['PHP_SELF']));
define("ADMIN", BASEDIR."administration/");
define("IMAGES", BASEDIR."images/");
define("INCLUDES", BASEDIR."includes/");
define("STYLE", "style/");
define("DATE_SET", date("Y-m-d"));
define("DATETIME", date("Y-m-d H:i:s"));
define("TIMESTAMP", time());
define("SPECIAL_LVL", 101);
$dbconnect = @mysql_connect($dbhost, $dbuser, $dbpass);
$dbselect = @mysql_select_db($dbname);
if(!$dbconnect)
die("<div style='font-size:14px;font-weight:bold;align:center;'>Nie nawiązano połączenia z bazą danych, w razie dłuższych problemów, spróbuj skontaktować się z administratorem</div>");
if(!$dbselect)
die("<div style='font-size:14px;font-weight:bold;align:center;'>Nie można wybrać potrzebnej bazy danych, w razie dłuższych problemów, spróbuj skontaktować się z administratorem</div>");
<file_sep><?php
function registration_form($answer = "", $answer_type = "not")
{
if($answer_type == "suc" && $answer_type != FALSE) $hide_form = TRUE;
if(!empty($answer)) $string = "<div class='".$answer_type."'>".$answer."</div>\n";
if(@$hide_form != TRUE)
{
$string = " <form action='' method='post' class='form-register'>\n";
$string.= " <table class='table0 table-register'>\n";
$string.= " <tr><th colspan='2'>Rejestracja</th></tr>\n";
$string.= " <tr><td class='reg-col1'>Nick <span class='red'>*</span></td><td><input type='text' value='' name='r1' class='w70'/><span class='text-tiny'> np. Gracz</span></td></tr>\n";
$string.= " <tr><td class='reg-col1'>Hasło <span class='red'>*</span></td><td><input type='password' value='' name='r2' class='w70'/></td></tr>\n";
$string.= " <tr><td class='reg-col1'>Potwierdź hasło <span class='red'>*</span></td><td><input type='password' value='' name='r3' class='w70'/></td></tr>\n";
$string.= " <tr><td class='reg-col1'>e-Mail <span class='red'>*</span></td><td><input type='text' value='' name='r4' class='w50'/></td></tr>\n";
$string.= " <tr><td class='reg-col1'>Klan</td><td><input type='text' value='' name='r5' class='w50'/><span class='text-tiny'> np. KLAN</span></td></tr>\n";
$string.= " <tr><td class='reg-col1'> </td><td><span class='text-tiny'><b class='red'>*</b> - pola wymagane<br>Rejestrując się zgadzasz się na przestrzeganie regulaminu portalu</span></td></tr>\n";
$string.= " <tr><td class='reg-col1'><input type='hidden' name='send' value='register'/></td><td><input type='submit' class='submit w50' value='Zarejestruj się'/></td></tr>\n";
$string.= " </table>\n";
$string.= " </form>\n";
}
return $string;
}
function log_user_in()
{
$login = $_POST["login"];
$pass = $_POST["password"];
if(!isset($_SESSION["logged-in"])) $_SESSION["logged-in"] = FALSE;
if($_SESSION["logged-in"] != 1 && $_POST['send'] == "login")
{
if(!empty($_POST["login"]) && !empty($_POST["password"]))
{
$sql = "SELECT `login`,`id` FROM ".DBPREFIX."users WHERE
`login` = '".htmlspecialchars($login)."' AND
`password` = '".md5(htmlspecialchars($pass))."' AND
`active` = '1'";
$query = mysql_query($sql);
// Sprawdzanie warunku
if(@mysql_num_rows($query))
{
$session = mysql_fetch_assoc($query);
$_SESSION['logged-in'] = 1;
$_SESSION['sid'] = session_id();
$_SESSION['login'] = $session['login'];
$_SESSION['userid'] = $session['id'];
$sql = "SELECT `last_ip` FROM `".DBPREFIX."users` WHERE `login` = '".$_SESSION['login']."' AND `id` = '".$_SESSION['userid']."' LIMIT 1;";
$query = mysql_query($sql);
$_SESSION['lastip'] = mysql_fetch_row($query);
$sqltext = "UPDATE `".DBPREFIX."users` SET `last_ip` = '".USER_IP."', `last_seen` = '".DATETIME."' WHERE `login` = '".$_SESSION['login']."' AND `id` = '".$_SESSION['userid']."' LIMIT 1;";
mysql_query($sqltext);
return 1;
}
else return 3;
}
else return 2;
}
return FALSE;
}
function log_user_out()
{
if($_SESSION["logged-in"] == 1)
{
if($_GET["logout"] == "yes")
{
$_SESSION["logged-in"] = 0;
session_unset();
return TRUE;
}
}
else return FALSE;
}
?>
<file_sep><?php
echo "\n";
echo " <!-- ~~~~~~~~~~~~~~~~~~~~ -->\n";
echo "\n";
echo " </div>\n";
echo " </div>\n";
echo "</div>\n";
echo "\n";
echo "<div class='clear'></div>\n";
echo "\n";
echo "<div id='footer'>\n";
echo " <div class='wrap-center'>\n";
echo " <div class='left'>".@$config['footer']."</div>\n";
echo " <div class='right'>Design [PR]GuteK</div>\n";
echo " </div>\n";
echo "</div>\n";
echo "\n";
echo "</body>\n";
echo "</html>\n";
?>
<file_sep><?php
if( $_GET['option'] == "lea.players" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
if(!empty($_POST['p_id']) AND check_int($_POST['p_id']) == TRUE)
{
$p_id = $_POST['p_id'];
$sql = "SELECT * FROM ".DBPREFIX."lea_players WHERE `active` = '0' AND `user_id` = '".$p_id."' LIMIT 1";
if(@mysql_num_rows(mysql_query($sql)))
{
$sql = "UPDATE ".DBPREFIX."lea_players SET `active` = '1' WHERE `user_id` = '".$p_id."' LIMIT 1";
mysql_query($sql);
echo "<div class='not'>Gracz aktywowany poprawnie</div>\n";
}
else echo "<div class='err'>Wystąpił błąd: <b>AD/LU#17</b><br>Skontaktuj się z głównym administratorem</div>\n";
unset($p_id);
}
// form
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w75 form-style1'>\n";
echo "<tr><th colspan='2'>Liga 0 : Gracze</th></tr>\n";
echo "<tr><td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>article.php?id=".$edit['id']."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
$sql = "SELECT * FROM ".DBPREFIX."lea_players WHERE `active` = '0'";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
while($player = mysql_fetch_assoc($query))
{
echo "<tr>";
echo "<form action='' method='post'>";
echo "<td widht='200'>".db_get_data("login","users","id",$player['user_id'])."</td><td><input type='hidden' name='p_id' value='".$player['id']."'><input type='submit' class='submit-bans right' value='Aktywuj'></td>";
echo "</form>";
echo "</tr>\n";
}
}
else
echo "<tr><td colspan='2'><b class='blue'>Brak graczy ubiegających się o zapis</b></td></tr>\n";
echo "</table>\n\n";
// bany
echo "<br>";
echo "<table class='table0 w75 form-style1'>\n";
echo "<tr><td colspan='2' align='left'><h6>Banowanie</h6></td></tr>\n";
echo "<tr><td colspan='2'><b class='blue'>Brak graczy ubiegających się o ban :)</b></td></tr>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
if( $_GET['option'] == "menu" AND session_check_usrlevel() >= SPECIAL_LVL )
{
session_check();
$sql = "SELECT `id` FROM `".DBPREFIX."panels` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
if( @$_POST['send'] == "new" AND check_int($_POST['form4']) == TRUE)
{
$new['id'] = $last_id+1;
$new['name'] = addslashes($_POST['form1']);
$new['content'] = addslashes($_POST['form2']);
@$new['display'] = $_POST['form3'];
if ( empty($new['display']) ) $new['display'] = 0;
$new['order'] = $_POST['form4'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form4']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "INSERT INTO `".DBPREFIX."panels` VALUES('".$new['id']."','".$new['name']."','".$new['content']."','".$new['display']."','".$new['order']."');";
mysql_query($sql);
$result = "Panel został dodany";
}
}
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."panels` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['name'] = stripslashes($data['name']);
$edit['content'] = stripslashes($data['content']);
$edit['display'] = $data['display'];
$edit['order'] = $data['order'];
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE AND check_int($_POST['form4']) == TRUE )
{
$upt['name'] = addslashes($_POST['form1']);
$upt['content'] = addslashes($_POST['form2']);
@$upt['display'] = $_POST['form3'];
if ( empty($upt['display']) ) $upt['display'] = 0;
$upt['order'] = $_POST['form4'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form4']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "UPDATE `".DBPREFIX."panels` SET `name` = '".$upt['name']."', `content` = '".$upt['content']."', `display` = '".$upt['display']."', `order` = '".$upt['order']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Panel został zaaktualizowany";
}
}
mysql_query($sql);
}
if(empty($_POST['send'])) $_POST['send'] = "new";
// form
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie panelami menu</th></tr>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['name'])) echo "Edytujesz: <i>".$edit['name']."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td valign='top' width='150'>Nazwa</td><td><input class='text' type='text' name='form1' value='".@$edit['name']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td valign='top'>Zawartość</td><td><textarea class='textarea' style='height:167px' name='form2'>".@$edit['content']."</textarea></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Pokaż</td><td><input type=checkbox name='form3'"; if( @$edit['display'] == 1 ) echo " checked='checked'"; echo " value='1'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kolejność</td><td><input class='p50' type='text' name='form4' value='".@$edit['order']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) $send_type = "new";
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".@$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "<tr><td colspan='2'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<form class='form-style2' action='' method='post'>\n";
echo "<td class='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT * FROM `".DBPREFIX."panels` ORDER BY `display` DESC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <select name='choosed_id' class='select'>\n";
while($menu = mysql_fetch_assoc($query))
{
if( $menu['display'] == 0 ) $disp = "# ";
echo " <option value='".$menu['id']."'>".@$disp.$menu['name']."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
require_once("maincore.php");
$actual = "news.php";
add_title("Nowości");
require_once(BASEDIR.STYLE."tpl.start.php");
if(@$_GET['action'] != "read" AND empty($_GET['mode']))
{
// fixing actived and archived amount of news
$sql = "SELECT * FROM ".DBPREFIX."news WHERE `date_start` <= '".DATETIME."'";
$query = mysql_query($sql);
$amount = mysql_num_rows($query);
// fixing top news id
if( @check_int($_GET['start']) == FALSE OR @empty($_GET['start']) OR @$_GET['start'] < 0 ) $start = 0;
else $start = $_GET['start'];
// fixing next and prev ids of pages of news
$next=$start+5;
$prev=$start-5;
if($prev<0)$prev=0;
// initiation
$sql = "SELECT * FROM `".DBPREFIX."news` WHERE `date_start` <= '".DATETIME."' AND `date_end` >= '".DATETIME."' ORDER BY `date_start` DESC LIMIT $start , 5";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
while($news = mysql_fetch_assoc($query))
{
$lang = explode(";",$news['languages']);
$author = db_get_data("login","users","id",$news['author']);
if(!empty($news['text_ext']))$ext = " | <a href='news.php?action=read&id=".$news['id']."'>Czytaj więcej</a>"; else $ext = " ";
if(empty($news['text_ext']))
{
if( $news['allow_rating'] == 1 OR $news['allow_comment'] == 1 )$ext = " | <a href='news.php?action=read&id=".$news['id']."'>Skomentuj / Oceń</a>";
}
$date = @split("[ :.]",$news['date_start']);
if (@$date[3] == 00 AND @$date[4] == 00 AND @$date[5] == 00) $news['date_start'] = $date[0];
// printing
echo "<div class='post'>\n";
echo "<div class='post-title'><h2>".$news['title']."</h2></div>\n";
echo "<div class='post-info'>Napisany przez ".$author." ".$news['date_start']."</div>\n";
echo "<div class='post-content'>".Codes($news['text'])."</div>\n";
$sql2 = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$news['id']."' AND `item_type` = 'N'";
$query2 = mysql_query($sql2);
$i = mysql_num_rows($query2);
if(!isset($i)) $i = 0;
$sql2 = "SELECT * FROM `".DBPREFIX."ratings` WHERE `item_id` = '".$news['id']."' AND `item_type` = 'N'";
$query2 = mysql_query($sql2);
$rated = 0;
$r = 0;
if(mysql_num_rows($query2) > 0)
{
while($vote = mysql_fetch_assoc($query2))
{
$rated = $rated+$vote['vote'];
$r++;
}
}
$rated = @round($rated/$r,2); if($rated == 0) $rated = "Brak ocen";
$rated = " | Ocena: ".$rated. " (".$r.")";
echo "<div class='post-footer text-tiny'>".$i." komentarzy".$rated." ".$ext."</div>\n";
echo "</div>\n";
// fixing var~s
unset($ext); unset($r); unset($i); unset($rated);
}
}
// printing news navigation
$sql = "SELECT * FROM `".DBPREFIX."news` WHERE `date_end` < '".DATETIME."'";
if($amount>$next OR $start>$prev OR mysql_num_rows(mysql_query($sql)) > 0)
{
echo "<div class='post-footer text-tiny' style='text-align:center;'>";
if($start>$amount) echo "<a href='news.php'>[««]</a>";
if($prev<$start) echo "<a href='news.php?start=$prev'>[«]</a>";
$pages = 0;
while($pages*5<$amount)
{
$pages++;
$page_=$pages*5-5;
$start_n=$start+15;
$start_p=$start-15;
if($page_ > $start_p AND $page_ < $start_n)
{
if($start == $page_)
{ echo "[".$pages."] "; }
else { echo "<a href='news.php?start=".$page_."'>[".$pages."]</a> "; }
}
}
if($amount>$next)
echo "<a href='news.php?start=$next'>[»]</a>";
// if ( mysql_num_rows(mysql_query($sql)) > 0 ) echo " <a href='news.php?mode=archive'>[Archiwum]</a>";
echo "</div>\n";
}
}
if(@$_GET['action'] == "read")
{
if(check_int($_GET['id']) == TRUE)
{
// add vote & comment
if( @$_POST['send'] == "vote" )
{
$sql = "SELECT * FROM `".DBPREFIX."ratings` WHERE `item_id` = '".$_GET['id']."' AND `item_type` = 'N' AND `user` = '".@db_get_data("id","users","login",$_SESSION['login'])."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query)) { $result = "Już oceniałeś ten artykuł"; }
else
{
$sql = "INSERT INTO `".DBPREFIX."ratings` VALUES(NULL, '".$_GET['id']."', 'N', '".$_POST['vote']."', '".@db_get_data("id","users","login",$_SESSION['login'])."', '".DATETIME."', '".USER_IP."');";
mysql_query($sql);
}
}
if( @$_POST['send'] == "comment" )
{
$sql = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$_GET['id']."' AND `item_type` = 'N' AND `user` = '".@db_get_data("id","users","login",$_SESSION['login'])."' ORDER BY `date` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$t = TRUE;
while( $test = mysql_fetch_assoc($query) )
{
if( get_time_difference($test['date']) < $config['antyflood'] )
{
$t = FALSE;
$result = "Musisz odczekać ".$config['antyflood']." sekund od ostatniego komentarza";
}
}
if( $t == TRUE )
{
$msg = addslashes(htmlspecialchars($_POST['comment']));
$sql = "INSERT INTO `".DBPREFIX."comments` VALUES(NULL,'".$_GET['id']."', 'N', '".$msg."', '".@db_get_data("id","users","login",$_SESSION['login'])."', '".DATETIME."', '".USER_IP."');";
mysql_query($sql);
}
}
// printing news
$sql = "SELECT * FROM ".DBPREFIX."news WHERE `id` = ".$_GET['id']." LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
while($news = mysql_fetch_assoc($query))
{
$lang = explode(";",$news['languages']);
$author = @db_get_data("login","users","id",$news['author']);
if(!empty($news['text_ext']))$ext = " | <a href='news.php?action=read&id=".$news['id']."'>Czytaj więcej</a>"; else $ext = "";
$date = @split("[ :.]",$news['date_start']);
if (@$date[3] == 00 AND @$date[4] == 00 AND @$date[5] == 00) $news['date_start'] = $date[0];
echo "<div class='post'>\n";
echo "<div class='post-title'><h2>".$news['title']."</h2></div>\n";
echo "<div class='post-info'>Napisany przez ".$author." ".$news['date_start']."</div>\n";
echo "<div class='post-content'>".Codes($news['text'])."<br/>".Codes($news['text_ext'])."</div>\n";
if( $news['allow_comment'] == 1 OR $news['allow_rating'] == 1 )
{
echo "<div class='post-footer text-tiny'>";
// :: fixing count of comments & rates
$sql2 = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$news['id']."' AND `item_type` = 'N' ORDER BY `date` DESC";
$query2 = mysql_query($sql2);
$i = mysql_num_rows($query2);
$sql2 = "SELECT * FROM `".DBPREFIX."ratings` WHERE `item_id` = '".$news['id']."' AND `item_type` = 'N'";
$query2 = mysql_query($sql2);
$rated = 0;
$r = 0;
// :: fixing summary for rating
if(mysql_num_rows($query2) > 0)
{
while($vote = mysql_fetch_assoc($query2))
{
$rated = $rated+$vote['vote'];
$r++;
}
}
$rated = @round($rated/$r,2);
if( $news['allow_comment'] == 1 )echo $i." komentarzy";
if( $news['allow_comment'] == 1 AND $news['allow_rating'] == 1 )echo " | ";
if( $news['allow_rating'] == 1 )
{
if( $rated == FALSE AND mysql_num_rows($query2) == 0 ) echo "Brak ocen";
else echo "Ocena: ".$rated." (".$r.")";
}
echo " | <a href='news.php'>Powrót</a></div>\n";
// comments
if( $news['allow_comment'] == 1 )
{
if( session_check() == TRUE )
{
echo "<a name='comment'></a><form class='form-style1' action='' method='post'>\n";
echo "<input type='text' name='comment' class='w50' value=''/>\n";
echo "<input type='hidden' name='send' value='comment'/><input type='submit' class='submit' value='Skomentuj'/>\n";
echo "</form>\n";
}
else echo "<div class='comment'><div class='comment-head'>Zaloguj się aby móc komentować</div></div>";
}
if( $news['allow_rating'] == 1 )
{
if( session_check() == TRUE )
{
echo form_rating();
}
else echo "<div class='comment'><div class='comment-head'>Zaloguj się aby móc ocenić artykuł</div></div>";
}
// printing list of comments
if(isset($result))echo "<div class='err'>".$result."</div>\n";
$sql2 = "SELECT * FROM `".DBPREFIX."comments` WHERE `item_id` = '".$_GET['id']."' AND `item_type` = 'N' ORDER BY `date` DESC";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) > 0)
{
while($comment = mysql_fetch_assoc($query2))
{
if( empty($comment['ip']) ) $comment['ip'] = "Błąd! Nie znaleziono IP wpisu";
elseif( session_check_usrlevel() >= SPECIAL_LVL ) $adm_info = "<span class='right'><img src='images/icons/info.png' width='12' height='12' title='".$comment['ip']."'/></span>";
echo "<div class='comment'>\n";
echo "<div class='comment-head'>".$comment['date']." skomentowany przez <strong>".@db_get_data("login","users","id",$comment['user'])."</strong>".@$adm_info."</div>\n";
echo "<div class='comment-text'>".Codes($comment['message'])."</div>\n";
echo "</div>\n";
}
}
}
echo "</div>\n";
unset($r); unset($i); unset($rated);
}
}
else
{
echo "<div class='err'>";
echo "Nie znaleziono wybranej wiadomości, <a href='news.php'>spróbuj ponownie</a>";
echo "</div>\n";
}
}
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
function lea_application($answer = "", $answer_type = "not")
{
$hide_form = FALSE;
if($answer_type == "suc" && $answer_type != FALSE) $hide_form = TRUE;
if(!empty($answer)) $string = "<div class='".$answer_type."'>".$answer."</div>\n";
if(@$hide_form != TRUE)
{
$string = " <form action='' method='post' class='form-register'>\n";
$string.= " <table class='table0 table-register'>\n";
$string.= " <tr><th colspan='2'>Rejestracja</th></tr>\n";
$string.= " <tr><td class='reg-col1'>Podaj swoje hasło dla akceptacji</td><td><input type='password' value='' name='password' class='w70'/></td></tr>\n";
$string.= " <tr><td class='reg-col1'> </td><td><span class='text-tiny'>Zapisując się zgadzasz się na przestrzeganie regulaminu Ligi</span></td></tr>\n";
$string.= " <tr><td class='reg-col1'><input type='hidden' name='sendlea' value='register'/></td><td><input type='submit' class='submit w50' value='Zarejestruj się'/></td></tr>\n";
$string.= " </table>\n";
$string.= " </form>\n";
}
return $string;
}
function lea_application_process()
{
$pass = $_POST["password"];
$p_id = $_SESSION['userid'];
if(strlen($pass) >= 4)
{
$sql = "SELECT * FROM ".DBPREFIX."users WHERE `id` = '".$p_id."' AND `password` = '".md5(htmlspecialchars($pass))."' LIMIT 1";
$query = mysql_query($sql);
if(@mysql_num_rows($query))
{
$sql = "SELECT * FROM ".DBPREFIX."lea_players WHERE `id` = '".$p_id."' LIMIT 1";
$query = mysql_query($sql);
if(@mysql_num_rows($query) == 0)
{
$sql = "INSERT INTO ".DBPREFIX."lea_players VALUES('".$p_id."','".$p_id."','0','1','0','0','0','0','0','0','');";
mysql_query($sql);
return "Czekaj na potwierdzenie rejestracji\n";
}
else return "Wystąpił błąd: <b>IN/LL#42</b><br>Skontaktuj się z administratorem\n";
}
else return "Brak autoryzacji!";
}
else return "Brak autoryzacji!";
}
?>
<file_sep><?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbfst";
define("DBPREFIX","");
?>
<file_sep><?php
require_once("maincore.php");
if(check_int($_GET['p_id']) != TRUE) redirect($config['mainpage']);
add_title("Liga 0 : ".db_get_data("gamenick","users","id",$_GET['p_id']));
require_once(BASEDIR.STYLE."tpl.start.php");
if(check_int($_GET['p_id']) == TRUE)
{
$id = ($_GET['p_id']);
$sql = "SELECT * FROM ".DBPREFIX."users WHERE `active`='1' AND `siteclan_member`='1' AND `id` = '".$id."'";
$query = mysql_query($sql);
if (@mysql_num_rows($query) > 0)
{
$player = mysql_fetch_assoc($query);
$sql2 = "SELECT * FROM ".DBPREFIX."lea_players WHERE `user_id` = '".$id."'";
$query2 = mysql_query($sql2);
$league = mysql_fetch_assoc($query2);
if($league['active'] == 1) $league['active'] = "<span class='green'>Aktywny</span>";
else $league['active'] = "<span class='red'>Nieaktywny</span>";
if(empty($player['avatar'])) $player['avatar'] = "images/avatars/blank.png";
if($player['gg'] == 0) $player['gg'] = "n/a";
if($player['icq'] == 0) $player['icq'] = "n/a";
echo "\n";
echo "<!-- DANE: ".$player['login']." -->\n";
echo "\n";
echo " <div class='player-head'>\n";
echo " <img src='".$player['avatar']."' class='left profile-avatar' width='90' height='90'/>\n";
echo " <h4 style='font-style:italic;'>".$player['login']."</h4>\n";
echo " <img src='images/clans/".$player['clan'].".gif'/><br/>";
echo $player['usertitle'];
echo " </div>\n";
echo " <div class='clear'><br></div>\n";
echo " <table class='table0 left table-clan'>\n";
echo " <tr><th colspan='2'>Liga 0</th></tr>\n";
echo " <tr><td width='150'>Aktywny</td><td>".$league['active']."</td></tr>\n";
echo " <tr><td width='150'>Zwycięstw</td><td>".$league['wins']."</td></tr>\n";
echo " <tr><td width='150'>Porażek</td><td>".$league['lost']."</td></tr>\n";
echo " </table>\n";
echo " <table class='table0 right table-clan'>\n";
echo " <tr><th colspan='2'>Dane kontaktowe</th></tr>\n";
echo " <tr><td width='100'>Mail</td><td>".$player['mail']."</td></tr>\n";
echo " <tr><td width='100'>GG</td><td>".$player['gg']."</td></tr>\n";
echo " <tr><td width='100'>ICQ</td><td>".$player['icq']."</td></tr>\n";
echo " </table>\n";
echo "<div class='clear'><br></div>\n";
echo "<table class='table0 w100'>\n";
echo "<tr><th>Statystyki</th></tr>\n";
echo "<tr><td><h6>Medale</h6></td></tr>\n";
echo "<tr><td>\n";
$listof = explode(";",$league['medals']);
for($i = 0;!empty($listof[$i]);$i++)
{
$medal = explode(".",$listof[$i]);
echo "<div class='center left medal-block'><img src='images/icons/league/".$medal[0].".png'/><div class='clear'><strong>".$medal[1]."</strong></div></div>";
}
echo "</td></tr>\n";
echo "</table>\n";
}
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
require_once "maincore.php";
require_once (BASEDIR.STYLE."tpl.start.php");
$sql = "SELECT * FROM `".DBPREFIX."users` where `id` = '".$_SESSION['userid']."' LIMIT 1";
$query = mysql_query($sql);
$prf = mysql_fetch_assoc($query);
if(isset($_POST['upt_name']))
{
if($_POST['upt_name'] == "mail")
{
if(!empty($_POST['old']) AND $prf['password'] == md5($_POST['old']))
{
$mail = htmlspecialchars($_POST['mail']);
$sql = "UPDATE `".DBPREFIX."users` SET `mail` = '".$mail."' WHERE `id` = ".$_SESSION['userid']." LIMIT 1";
$reply = 2; $reply_info = "Adres e-Mail został zaaktualizowany poprawnie";
}
else { $reply = 1; $reply_info = "Wprowadź poprawne dane"; }
}
if($_POST['upt_name'] == "pass")
{
if(!empty($_POST['old']) AND !empty($_POST['new']) AND !empty($_POST['confirm']))
{
if($prf['password'] == md5($_POST['old']))
{
if($_POST['new'] == $_POST['confirm'])
{
if(strlen($_POST['new']) > 3)
{
$pass = md5($_POST['new']);
$sql = "UPDATE `".DBPREFIX."users` SET `password` = '".$pass."' WHERE `id` = ".$_SESSION['userid']." LIMIT 1";
$reply = 2; $reply_info = "Hasło zostało zaaktualizowane poprawnie";
}
else { $reply = 1; $reply_info = "Wprowadzone hasło jest za krótkie. Hasło musi zawierać conajmniej 4 znaki"; }
}
else { $reply = 1; $reply_info = "Podane nowe hasło nie zostało potwierdzone"; }
}
else { $reply = 1; $reply_info = "Podano złe aktualne hasło"; }
}
else { $reply = 1; $reply_info = "Nie uzupełniono danych"; }
}
if($_POST['upt_name'] == "display")
{
$v1 = addslashes(htmlspecialchars($_POST['i1']));
$v2 = addslashes(htmlspecialchars($_POST['i2']));
$sql = "UPDATE `".DBPREFIX."users` SET `display_mail` = '".$v1."', `display_online` = '".$v2."' WHERE `id` = ".$_SESSION['userid']." LIMIT 1";
$reply = 2; $reply_info = "Ustawienia użytkownika zostały zaaktualizowany poprawnie";
}
if($_POST['upt_name'] == "contact")
{
if(check_int($_POST['i1']) == TRUE OR check_int($_POST['i2']) == TRUE)
{
$gg = htmlspecialchars($_POST['i1']);
$icq = htmlspecialchars($_POST['i2']);
if(check_int($_POST['i1']) == FALSE) $gg = 0;
if(check_int($_POST['i2']) == FALSE) $icq = 0;
$sql = "UPDATE `".DBPREFIX."users` SET `gg` = '".$gg."', `icq` = '".$icq."' WHERE `id` = ".$_SESSION['userid']." LIMIT 1";
$reply = 2; $reply_info = "Dane kontaktowe zostały zaaktualizowany poprawnie";
}
else { $reply = 1; $reply_info = "Wpisane numery zawierają nie dozwolone znaki"; }
}
if($_POST['upt_name'] == "player")
{
// $v1 = addslashes(htmlspecialchars($_POST['i1']));
$v2 = addslashes(htmlspecialchars($_POST['i2']));
$v3 = addslashes(htmlspecialchars($_POST['i3']));
$v4 = addslashes(htmlspecialchars($_POST['i4']));
// `gamenick` = '".$v1."',
$sql = "UPDATE `".DBPREFIX."users` SET `clan` = '".$v2."', `favrules` = '".$v3."', `usertitle` = '".$v4."' WHERE `id` = ".$_SESSION['userid']." LIMIT 1";
$reply = 2; $reply_info = "Dane gracza zostały zaaktualizowany poprawnie";
}
if($_POST['upt_name'] == "person")
{
$v1 = addslashes(htmlspecialchars($_POST['i1']));
$v2 = $_POST['i2a']."-".$_POST['i2b']."-".$_POST['i2c'];
$v3 = $_POST['i3'];
$v4 = addslashes(htmlspecialchars($_POST['i4']));
$v5 = addslashes(htmlspecialchars($_POST['i5']));
$sql = "UPDATE `".DBPREFIX."users` SET `name` = '".$v1."', `born` = '".$v2."', `gender` = '".$v3."', `intrest` = '".$v4."', `location` = '".$v5."' WHERE `id` = ".$_SESSION['userid']." LIMIT 1";
$reply = 2; $reply_info = "Dane kontaktowe zostały zaaktualizowany poprawnie";
}
if(!empty($_POST['upt_name'])) {mysql_query($sql);}
}
$sql = "SELECT * FROM `".DBPREFIX."users` where `id` = '".$_SESSION['userid']."' LIMIT 1";
$query = mysql_query($sql);
$prf = mysql_fetch_assoc($query);
$born = explode("-",$prf['born']);
echo "<h2>Profil</h2>\n";
echo " <table class='table0 w100'>\n";
echo " <tr><th class='w50'><a href='profile.php'>Podstawowe dane</a></th><th class='w50'><a href='profile.php?show=1'>Informacje o użytkowniku</a></th></tr>\n";
echo " </table>\n";
if(isset($reply))
{
if($reply == 2) echo " <div class='suc'>".$reply_info."</div>\n";
if($reply == 1) echo " <div class='err'>".$reply_info."</div>\n";
}
if(!isset($_GET['show'])) $_GET['show'] = 0;
if($_GET['show'] != 1 AND ($_GET['show'] != 0 OR $_GET['show'] != 1))
{
echo " <table class='table0 w100 form-style1'>\n";
echo " <tr><td colspan='2'><h6>Dane o twoim koncie</h6></td></tr>\n";
echo " <tr><td width='200'>Adres e-Mail przypisany</td><td>".$prf['mail']."</td></tr>\n";
echo " <tr><td>Data rejestracji</td><td>".$prf['register_date']."</td></tr>\n";
echo " <tr><td>IP rejestracji</td><td>".$prf['register_ip']."</td></tr>\n";
echo " <tr><td>IP ostatnio</td><td>".$prf['last_ip']."</td></tr>\n";
echo " <form action='' method='post'>\n";
echo " <tr><td colspan='2'><h6>Ustaw nowy adres e-mail</h6></td></tr>\n";
echo " <tr><td width='200'>Twój adres e-mail</td><td><input class='w75' type='text' name='mail' value='".$prf['mail']."'/></td></tr>\n";
echo " <tr><td width='200'>Hasło</td><td><input class='w75' type='password' name='old' value=''/></td></tr>\n";
echo " <tr><td><input type='hidden' name='upt_name' value='mail'/></td><td><input type='submit' class='submit' value='Potwierdź'/></td></tr>\n";
echo " </form>\n";
echo " <form action='' method='post'>\n";
echo " <tr><td colspan='2'><h6>Zmień hasło</h6></td></tr>\n";
echo " <tr><td width='200'>Twoje stare hasło</td><td><input class='w75' type='password' name='old' value=''/></td></tr>\n";
echo " <tr><td>Nowe hasło</td><td><input class='w75' type='password' name='new' value=''/></td></tr>\n";
echo " <tr><td>Potwierdź nowe hasło</td><td><input class='w75' type='password' name='confirm' value=''/></td></tr>\n";
echo " <tr><td><input type='hidden' name='upt_name' value='pass'/></td><td><input type='submit' class='submit' value='Potwierdź'/></td></tr>\n";
echo " </form>\n";
echo " <form action='' method='post'>\n";
echo " <tr><td colspan='2'><h6>Inne</h6></td></tr>\n";
echo " <tr><td width='200'>Ukryj adres e-Mail</td><td>".form_option_bool($prf['display_mail'],"i1","Nie","Tak")."</td></tr>\n";
echo " <tr><td>Ukryj moją obecność on-line</td><td>".form_option_bool($prf['display_online'],"i2","Nie","Tak")."</td></tr>\n";
echo " <tr><td><input type='hidden' name='upt_name' value='display'/></td><td><input type='submit' class='submit' value='Potwierdź'/></td></tr>\n";
echo " </form>\n";
echo " </table>\n";
}
if($_GET['show'] == 1 AND ($_GET['show'] != 0 OR $_GET['show'] != 1))
{
echo " <table class='table0 w100 form-style1'>\n";
echo " <form action='' method='post'>\n";
echo " <tr><td colspan='2'><h6>Komunikatory</h6></td></tr>\n";
echo " <tr><td width='200'>GG</td><td><input class='w50' type='text' name='i1' value='".$prf['gg']."'/></td></tr>\n";
echo " <tr><td>ICQ</td><td><input class='w50' type='text' name='i2' value='".$prf['icq']."'/></td></tr>\n";
echo " <tr><td><input type='hidden' name='upt_name' value='contact'/></td><td><input type='submit' class='submit' value='Potwierdź'/></td></tr>\n";
echo " </form>\n";
echo " <form action='' method='post'>\n";
echo " <tr><td colspan='2'><h6>Dane gracza</h6></td></tr>\n";
echo " <tr><td width='200'>Nick</td><td><input disabled='disabled' class='w75' type='text' name='i1' value='".$prf['gamenick']."'/></td></tr>\n";
echo " <tr><td>Klan</td><td><input type='text' name='i2' maxlength='8' value='".$prf['clan']."'/></td></tr>\n";
echo " <tr><td>Ulubione rules</td><td><input class='w75' type='text' name='i3' value='".$prf['favrules']."'/></td></tr>\n";
echo " <tr><td>Tytuł użytkownika</td><td><input class='w75' type='text' name='i4' value='".$prf['usertitle']."'/></td></tr>\n";
echo " <tr><td><input type='hidden' name='upt_name' value='player'/></td><td><input type='submit' class='submit' value='Potwierdź'/></td></tr>\n";
echo " </form>\n";
echo " <form action='' method='post'>\n";
echo " <tr><td colspan='2'><h6>Dane personalne</h6></td></tr>\n";
echo " <tr><td width='200'>Imię</td><td><input class='w75' type='text' name='i1' value='".$prf['name']."'/></td></tr>\n";
echo " <tr><td>Urodziny</td><td><input type='text' name='i2a' maxlength='4' style='width:50px;text-align:center;' value='".@$born[0]."'/> - <input type='text' name='i2b' maxlength='2' style='width:25px;text-align:center;' value='".@$born[1]."'/> - <input type='text' name='i2c' maxlength='2' style='width:25px;text-align:center;' value='".@$born[2]."'/> <span class='text-tiny'>( RRRR - MM - DD )</span></td></tr>\n";
echo " <tr><td>Płeć</td><td>".form_option_bool($prf['gender'],"i3","Kobieta","Mężczyzna")."</td></tr>\n";
echo " <tr><td>Zainteresowania</td><td><input class='w75' type='text' name='i4' value='".$prf['intrest']."'/></td></tr>\n";
echo " <tr><td>Miejsce zamieszkania</td><td><input class='w75' type='text' name='i5' value='".$prf['location']."'/></td></tr>\n";
echo " <tr><td><input type='hidden' name='upt_name' value='person'/></td><td><input type='submit' class='submit' value='Potwierdź'/></td></tr>\n";
echo " </form>\n";
echo " </table>\n";
}
require_once (BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "atom" AND session_check_usrlevel() >= SPECIAL_LVL )
{
session_check();
getsettings();
$title = $config['title']; $admin = $config['headadmin']; $email = $config['email'];
echo "<div class='not'>".atom_convert_news($title,$admin,$email)."</div>\n";
echo "<div class='not'>".atom_convert_league_games($title,$admin,$email)."</div>\n";
}
?>
<file_sep><?php
/* Header
/*
/* Core file of League 0
/* Created by <NAME>
/* for Polish Revolution clan
/* (c) 2012 All rights reserved
/* Integral part of Polish Revolution's website
/*----------------------------------------------*/
define("SCORE1", "10"); $score[0] = FALSE;
define("SCORE2", "7"); $score[1] = FALSE;
define("SCORE3", "3"); $score[2] = FALSE;
define("SCORE4", "1"); $score[3] = FALSE;
/* Content
/*
/* settings
/* converting of score
/* score for table & stats
/* challange printing
/* challange accepting
/* league admin tools
/*
/*----------------------------------------------*/
function lea_free_date($string = "01.03;01.06;01.09;01.12")
{
$test = explode(";",$string);
for($i = 0;!empty($test[$i]);$i++)
{
if(date("d.m") == $test[$i]) return TRUE;
}
return FALSE;
}
function set_season($m = FALSE)
{
if($m == FALSE) $m = date("m");
$date = date("Y");
switch($m)
{
case 1: return "1.".$date; break;
case 2: return "1.".$date; break;
case 3: return "2.".$date; break;
case 4: return "2.".$date; break;
case 5: return "2.".$date; break;
case 6: return "3.".$date; break;
case 7: return "3.".$date; break;
case 8: return "3.".$date; break;
case 9: return "4.".$date; break;
case 10: return "4.".$date; break;
case 11: return "4.".$date; break;
case 12: return "1.".($date+1); break;
}
}
define("SEASON", set_season());
// Main config
function lea_getsetting($name)
{
$sql = "SELECT * FROM `".DBPREFIX."lea_settings` LIMIT 1";
$query = @mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
$config = @mysql_fetch_assoc($query);
return $config[$name];
}
else
{
return FALSE;
}
}
function lea_uptsetting($name,$value)
{
$sql = "UPDATE `".DBPREFIX."lea_settings` SET `".$name."` = '".$value."' LIMIT 1";
$query = @mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
$config = @mysql_fetch_assoc($query);
return $config[$name];
}
else
{
return FALSE;
}
}
// Convert functions
function score_players($game_id, $winner_id, $looser_id, $score_win, $score_los, $score)
{
$sql = "SELECT `score`, `wins`, `lost` FROM ".DBPREFIX."lea_players WHERE `user_id` = '".$winner_id."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == TRUE)
{
$result = mysql_fetch_assoc($query);
$score1 = $result['score'] + $score_win;
if($score == 1){ $wins1 = $result['wins']+2; $lost1 = $result['lost']; }
if($score == 2){ $wins1 = $result['wins']+2; $lost1 = $result['lost']+1; }
}
else { echo "<div class='err'>Błąd. W przypadku dłuższego występowania komunikatu skontaktuj się z administratorem!</div>"; return FALSE; }
$sql = "SELECT `score`, `wins`, `lost` FROM ".DBPREFIX."lea_players WHERE `user_id` = '".$looser_id."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == TRUE)
{
$result = mysql_fetch_assoc($query);
$score2 = $result['score'] + $score_los;
if($score == 1){ $wins2 = $result['wins']; $lost2 = $result['lost']+2; }
if($score == 2){ $wins2 = $result['wins']+1; $lost2 = $result['lost']+2; }
}
else { echo "<div class='err'>Błąd. W przypadku dłuższego występowania komunikatu skontaktuj się z administratorem!</div>"; return FALSE; }
$sql2 = "UPDATE ".DBPREFIX."lea_players SET `score` = '".$score1."', `wins` = '".$wins1."', `lost` = '".$lost1."' WHERE `user_id` = '".$winner_id."' LIMIT 1";
mysql_query($sql2);
$sql2 = "UPDATE ".DBPREFIX."lea_players SET `score` = '".$score2."', `wins` = '".$wins2."', `lost` = '".$lost2."' WHERE `user_id` = '".$looser_id."' LIMIT 1";
mysql_query($sql2);
$sql3 = "UPDATE ".DBPREFIX."lea_games SET `scored` = '1' WHERE `id` = '".$game_id."' LIMIT 1";
mysql_query($sql3);
}
function score_players_stats($game_id, $winner_id, $looser_id, $score_win, $score_los)
{
$sql = "SELECT `score_stats` FROM ".DBPREFIX."lea_players WHERE `user_id` = '".$winner_id."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == TRUE)
{
$result = mysql_fetch_assoc($query);
$score1 = $result['score_stats'];
}
else { echo "<div class='err'>Błąd. W przypadku dłuższego występowania komunikatu skontaktuj się z administratorem!</div>"; return FALSE; }
$sql = "SELECT `score_stats` FROM ".DBPREFIX."lea_players WHERE `user_id` = '".$looser_id."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == TRUE)
{
$result = mysql_fetch_assoc($query);
$score2 = $result['score_stats'];
}
else { echo "<div class='err'>Błąd. W przypadku dłuższego występowania komunikatu skontaktuj się z administratorem!</div>"; return FALSE; }
$s_diff = $score1 - $score2;
if(ceil($s_diff*0.04) > 14) $s_diff = 350;
$s_diffWin = ceil($s_diff*0.04);
$s_diffLos = ceil($s_diff*0.035);
$scoreNew_1 = $score1 + $score_win - $s_diffWin;
$scoreNew_2 = $score2 + $score_los + $s_diffLos;
if($scoreNew_1 < 0)$scoreNew_1 = 0;
if($scoreNew_2 < 0)$scoreNew_2 = 0;
$sql2 = "UPDATE ".DBPREFIX."lea_players SET `score_stats` = '".$scoreNew_1."' WHERE `user_id` = '".$winner_id."' LIMIT 1";
mysql_query($sql2);
$sql2 = "UPDATE ".DBPREFIX."lea_players SET `score_stats` = '".$scoreNew_2."' WHERE `user_id` = '".$looser_id."' LIMIT 1";
mysql_query($sql2);
$sql3 = "UPDATE ".DBPREFIX."lea_games SET `scored` = '2' WHERE `id` = '".$game_id."' LIMIT 1";
mysql_query($sql3);
}
// Write a history of each player in his statistics
function score_players_stats_history()
{
$test = date("Y",strtotime("-1 week"))."-".date("m",strtotime("-1 week"))."-".date("d",strtotime("-1 week"));
if(lea_getsetting("last_stats_date") <= $test)
{
$sql = "SELECT `id`, `score_stats` FROM ".DBPREFIX."lea_players ORDER BY `score_stats` DESC";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$i = 0;
while($data = mysql_fetch_assoc($query))
{
$i = $i+1;
$sql2 = "UPDATE ".DBPREFIX."lea_players SET `last_stats_score` = '".$data['score_stats']."', `last_stats_position` = '".$i."' WHERE `id` = ".$data['id']." LIMIT 1";
mysql_query($sql2);
}
}
lea_uptsetting("last_stats_date",date("Y-m-d"));
}
else return FALSE;
}
// Convert a score for actual season
function score_games()
{
if (TRUE)
{
$sql = "SELECT * FROM ".DBPREFIX."lea_games WHERE `scored` = '0' ORDER BY `date` ASC";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
while($game = mysql_fetch_assoc($query))
{
if($game['player1'] == $game['winner'])
{
if($game['score'] == 1)
{
score_players($game['id'],$game['player1'],$game['player2'],SCORE1,SCORE4,$game['score']);
}
if($game['score'] == 2)
{
score_players($game['id'],$game['player1'],$game['player2'],SCORE2,SCORE3,$game['score']);
}
}
if($game['player2'] == $game['winner'])
{
if($game['score'] == 1)
{
score_players($game['id'],$game['player2'],$game['player1'],SCORE1,SCORE4,$game['score']);
}
if($game['score'] == 2)
{
score_players($game['id'],$game['player2'],$game['player1'],SCORE2,SCORE3,$game['score']);
}
}
}
}
}
}
// Scoring a relative statistics
function score_stats()
{
if (date("H") >= 22 OR date("H") <= 10)
{
$sql = "SELECT * FROM ".DBPREFIX."lea_games WHERE `scored` = '1' ORDER BY `date` ASC";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
while($game = mysql_fetch_assoc($query))
{
if($game['player1'] == $game['winner'])
{
if($game['score'] == 1)
{
score_players_stats($game['id'],$game['player1'],$game['player2'],21,-12);
}
if($game['score'] == 2)
{
score_players_stats($game['id'],$game['player1'],$game['player2'],13,-8);
}
}
if($game['player2'] == $game['winner'])
{
if($game['score'] == 1)
{
score_players_stats($game['id'],$game['player2'],$game['player1'],21,-12);
}
if($game['score'] == 2)
{
score_players_stats($game['id'],$game['player2'],$game['player1'],13,-8);
}
}
}
}
}
}
// Printing a list of opponents to select
function print_list_of_opponents($challanger_id,$date)
{
$return = FALSE;
$sql = "SELECT `id`, `player1`, `player2` FROM ".DBPREFIX."lea_challanges WHERE (`player1` = '".$challanger_id."' OR `player2` = '".$challanger_id."') AND `actived` = '0'";
$query = mysql_query($sql);
$sql_test = "SELECT `id` FROM ".DBPREFIX."lea_challanges WHERE (`player1` = '".$challanger_id."' OR `player2` = '".$challanger_id."') AND `actived` = '1'";
$query_test = mysql_query($sql_test);
if(mysql_num_rows($query_test) < $date)
{
$string = " <form class='form-style1' action='' method='post'>\n";
$string.= " <input type='hidden' name='send' value='achallange'/><input type='submit' value='Aktywuj' class='submit right'/>\n";
$string.= "<select name='challange_id' class='lea-setchallange right'>\n";
if(mysql_num_rows($query) > 0)
{
while($data = mysql_fetch_assoc($query))
{
if($challanger_id == $data['player1']) $opponent = $data['player2'];
if($challanger_id == $data['player2']) $opponent = $data['player1'];
$sql2 = "SELECT `actived` FROM ".DBPREFIX."lea_challanges WHERE `player1` = '".$opponent."' OR `player2` = '".$opponent."'";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query) > 0)
{
$i = 0;
$t = 1;
while($test = mysql_fetch_assoc($query2))
{
if($test['actived'] == 1) $i = $i+1;
if($i == $date) { $t = 0; break 1; }
}
}
if( $t == 1 )
{
$string.= " <option value='".$data['id']."'>".db_get_data("gamenick","users","id",$challanger_id)." vs ".db_get_data("gamenick","users","id",$opponent)."</option>\n";
$return = 1;
}
}
}
$string.= "</select>\n";
$string.= " </form>\n";
}
if($return == FALSE) $string = "<span class='text-tiny'>Brak możliwości wyzwań do aktywacji</span>";
return $string;
}
function challange_get_opponentid($challanger_id,$id)
{
$sql = "SELECT * FROM ".DBPREFIX."lea_challanges WHERE `id` = '".$id."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) != FALSE)
{
$challange = mysql_fetch_assoc($query);
if($challange['player1'] == $challanger_id) return $challange['player2'];
if($challange['player2'] == $challanger_id) return $challange['player1'];
}
else return FALSE;
}
function challange_random_nation()
{
$nation = array("Holandia","Szwajcaria","Austria",
"Anglia","Prusy","Dania","Szwecja",
"Piemont","Portugalia","Hiszpania",
"Francja","Bawaria","Polska","Rosja",
"Ukraina","Węgry","Turcja","Algeria",
"Wenecja");
return $nation[rand(0,18)];
}
function challange_activation($challanger_id,$id)
{
if(@$_POST['send'] == "achallange")
{
// checking challange existing
$sql = "SELECT * FROM ".DBPREFIX."lea_challanges WHERE `id` = '".$id."' AND `actived` = '0' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == FALSE) return "<div class='err'>Wyzwanie nie istnieje lub jest już zaaktywowane</div>\n";
// checking last game with this player
else
{
$challange = mysql_fetch_assoc($query);
$sql = "SELECT `date`, `season` FROM ".DBPREFIX."lea_games WHERE (`player1` = '".$challanger_id."' AND `player2` = '".challange_get_opponentid($challanger_id,$id)."') OR (`player1` = '".challange_get_opponentid($challanger_id,$id)."' AND `player2` = '".$challanger_id."') ORDER BY `date` DESC LIMIT 1";
$query = mysql_query($sql);
$last = mysql_fetch_assoc($query);
if($last['date'] >= date("Y-m-d",strtotime("-1 weeks")) AND $last['season'] == $challange['season']) return "<div class='not'>Niedawno grałeś z tym przeciwnikiem w tym sezonie!</div>";
}
// update
$sql = "UPDATE ".DBPREFIX."lea_challanges SET `actived` = '1', `start` = '".DATETIME."', `end` = '".date("Y-m-d H:i:s",strtotime("+1 week"))."', `nations` = '".challange_random_nation()."' WHERE `id` = '".$id."' LIMIT 1";
mysql_query($sql); return "<div class='not'>Wyzwanie zostało dodane poprawnie</div>\n";
}
}
function game_accepting($challanger_id,$id)
{
$sql = "SELECT * FROM ".DBPREFIX."lea_challanges WHERE `id` = '".$id."' AND `actived` = '1' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$data = mysql_fetch_assoc($query);
if($data['accepted'] == 0)
{
echo "<td>Ustaw wynik:</td>\n";
echo "<td colspan='5'><form class='form-style1' action='' method='post'>";
echo "<input type='submit' class='submit right' value='Zatwierdź'>";
echo "<input type='hidden' name='send' value='set'>\n";
echo "<input type='hidden' name='challange_id' value='".$id."'>\n";
echo " <select class='lea-setwinner right' name='winner'>";
echo " <option value='".$data['player1']."'>".db_get_data("gamenick","users","id",$data['player1'])."</option>";
echo " <option value='".$data['player2']."'>".db_get_data("gamenick","users","id",$data['player2'])."</option>";
echo " </select>\n";
echo " <select class='lea-setscore right' name='score'>";
echo " <option value='1'>2:0</option>";
echo " <option value='2'>2:1</option>";
$test = date("Y-m-d",strtotime("-3 days"));
echo $test;
if( $test >= $data['start'] )echo " <option value='3'>Walkover</option>";
echo " </select>\n";
echo "</form></td>\n";
}
if($data['accepted'] == 1)
{
echo "<td><b class='red'>WYNIK:</b></td>\n";
echo "<td>";
switch($data['score'])
{
case 1: echo "2:0";break;
case 2: echo "2:1";break;
case 3: echo "WLK";break;
}
echo "</td>";
echo "<td colspan='2'><b class='blue'>".db_get_data("gamenick","users","id",$data['winner'])."</b></td>\n";
if($data['score_set'] != $challanger_id)
{
echo "<td>\n";
echo "<form class='form-style1' action='' method='post'><input type='hidden' name='send' value='confirm'><input type='hidden' name='challange_id' value='".$data['id']."'><input type='submit' class='submit' value='Tak'></form>\n";
echo "</td>\n";
echo "<td>\n";
echo "<form class='form-style1' action='' method='post'><input type='hidden' name='send' value='cancel'><input type='hidden' name='challange_id' value='".$data['id']."'><input type='submit' class='submit' value='Nie'></form>\n";
echo "</td>\n";
}
elseif($data['score_set'] == $challanger_id)
{
echo "<td colspan='2'><i>Czekaj na potwierdzenie</i></td>\n";
}
}
}
}
function game_accepting_process($challanger_id,$id)
{
if(@isset($_POST['send']) AND $_POST['send'] == "set")
{
$sql = "UPDATE ".DBPREFIX."lea_challanges SET `accepted` = '1', `winner` = '".$_POST['winner']."', `score` = '".$_POST['score']."', `score_set` = '".$challanger_id."' WHERE `id` = '".$id."' AND `accepted` = '0' LIMIT 1";
mysql_query($sql);
switch($_POST['score'])
{
case 1: $msg_score = "2:0"; break;
case 2: $msg_score = "2:1"; break;
case 3: $msg_score = "WAL"; break;
}
$sql = "INSERT INTO ".DBPREFIX."lea_msg VALUES('','Wynik dla ".db_get_data("gamenick","users","id",$_POST['winner'])." : ".$msg_score."','".$challanger_id."','".$id."','".DATETIME."','0');";
mysql_query($sql);
}
if(@isset($_POST['send']) AND $_POST['send'] == "confirm")
{
$sql = "SELECT * FROM ".DBPREFIX."lea_challanges WHERE `id` = '".$id."' AND `accepted` = '1' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == 1)
{
$new = mysql_fetch_assoc($query);
$sql = "UPDATE ".DBPREFIX."lea_challanges SET `actived` = '2', `accepted` = '2' WHERE `id` = '".$id."' AND `accepted` = '1' LIMIT 1";
mysql_query($sql);
$sql = "INSERT INTO ".DBPREFIX."lea_games VALUES('".$id."','".$new['player1']."','".$new['player2']."','".$new['season']."','".$new['nations']."','".$new['winner']."','".$new['score']."','".$challanger_id."','".DATETIME."','0');";
mysql_query($sql);
$sql = "INSERT INTO ".DBPREFIX."lea_msg VALUES('','Potwierdzono','".$challanger_id."','".$id."','".DATETIME."','0');";
mysql_query($sql);
return "<div class='suc'>Dodano wynik poprawnie</div>\n";
}
}
if(@isset($_POST['send']) AND $_POST['send'] == "cancel")
{
$sql = "UPDATE ".DBPREFIX."lea_challanges SET `accepted` = '0', `winner` = '0', `score` = '0', `score_set` = '0' WHERE `id` = '".$id."' AND `accepted` = '1' LIMIT 1";
mysql_query($sql);
}
}
function lea_clear_stats($clear_type = 1)
{
switch($clear_type)
{
case 1:$sql = "UPDATE `lea_players` SET `score` = '0', `score_stats` = '0', `wins` = '0', `lost` = '0'";break;
}
mysql_query($sql);
}
function lea_games_reset_scored($clear_type = 1)
{
switch($clear_type)
{
case 1:$sql = "UPDATE `lea_games` SET `scored` = '0'";break;
}
mysql_query($sql);
}
function lea_create_challanges($season)
{
$i = 0; $j = 0;
$sql1 = "SELECT * FROM ".DBPREFIX."lea_players WHERE `active` = '1' ";
$query1 = mysql_query($sql1);
if(mysql_num_rows($query1) > 0)
{
while($player = mysql_fetch_assoc($query1))
{
$sql2 = "SELECT * FROM ".DBPREFIX."lea_players WHERE `active` = '1' AND `user_id` != '".$player['user_id']."'";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) > 0)
{
while($opponent = mysql_fetch_assoc($query2))
{
$sql_test = "SELECT `id` FROM ".DBPREFIX."lea_challanges WHERE (`player1` = '".$player['user_id']."' AND `player2` = '".$opponent['user_id']."') AND `season` = '".$season."' LIMIT 1";
$query_test = mysql_query($sql_test);
if(mysql_num_rows($query_test) == 0)
{
$sql = "INSERT INTO ".DBPREFIX."lea_challanges VALUES('','".$player['user_id']."','".$opponent['user_id']."','".$season."','0','Losowo','".DATETIME."','".date("Y-m-d H:i:s",strtotime("+10 days"))."','0','0','0','0');";
mysql_query($sql);
$j = $j + 1;
}
else $i = $i + 1;
}
}
}
}
return "<div class='not'><p>Dodano ".$j." wyzwań</p><p>Istnieje ".$i." wyzwań których nie było możliwości dodać</p></div>";
}
?>
<file_sep><?php
require_once("maincore.php");
require_once("lea.core.php");
add_title("Administracja");
require_once(BASEDIR.STYLE."tpl.start.php");
function set_admin_cat($category, $need_right = FALSE)
{
if ( $need_right != FALSE )
{
$need_right = explode(".", $need_right);
for( $x = 0; $x < count($need_right); $x++ )
{ if( session_check_rights($_SESSION['login'], $need_right[$x]) == TRUE ) return "<tr><td><h6>".$category."</h6></td></tr>\n"; }
}
}
function set_admin_option($option, $name, $need_right = FALSE)
{
if ( $need_right != FALSE )
{
$need_right = explode(".", $need_right);
for( $x = 0; $x < count($need_right); $x++ )
{ if( session_check_rights($_SESSION['login'], $need_right[$x]) == TRUE ) return "<div class='admin-catlist'><a href='administration.php?option=".$option."'><img src='".IMAGES."icons/admin/".$option.".png' border='0'/><div class='clear'></div><span class='text-tiny'>".$name."</span></a></div>\n"; }
}
else return "#ERR\n";
}
if( session_check_usrlevel() >= SPECIAL_LVL )
{
if( !isset($_GET['option']) )
{
echo "<table class='table0 w100'>\n";
echo "<tr><th>Administracja</th></tr>\n";
echo set_admin_cat('Zawartość','M.A.SA');
echo "<tr><td>\n";
echo set_admin_option('news','Nowości','M.A.SA');
echo set_admin_option('articles','Artykuły','M.A.SA');
echo set_admin_option('faq','FAQ','M.A.SA');
echo set_admin_option('links','Linki','M.A.SA');
echo set_admin_option('links-cat','Kat. linków','M.A.SA');
echo set_admin_option('download','Download','A.SA');
echo set_admin_option('download-cat','Kat. downloadu','A.SA');
echo set_admin_option('gallery','Galeria','A.SA');
echo set_admin_option('calendar','Kalendarz','M.A.SA');
echo set_admin_option('atom','Kanały ATOM','M.A.SA');
echo "</td></tr>\n";
echo set_admin_cat('Użytkownicy','A.SA');
echo "<tr><td>\n";
echo set_admin_option('users','Użytkownicy','A.SA');
echo set_admin_option('bans','Czarna lista','A.SA');
echo "</td></tr>\n";
echo set_admin_cat('Konfiguracja','A.SA');
echo "<tr><td>\n";
echo set_admin_option('info','Informacje','A.SA');
echo set_admin_option('languages','Języki','A.SA');
echo set_admin_option('clan','Klan','A.SA');
echo set_admin_option('menu','Menu','A.SA');
echo set_admin_option('settings','Ustawienia','SA');
echo "</td></tr>\n";
echo set_admin_cat('Liga 0','LA.A.SA');
echo "<tr><td>\n";
echo set_admin_option('lea.players','Gracze','LA.A.SA');
echo set_admin_option('lea.games','Gry','LA.A.SA');
echo set_admin_option('lea.medals','Medale','LA.A.SA');
echo set_admin_option('lea.config','Konfiguracja','A.SA');
echo "</td></tr>\n";
echo "</table>\n";
}
elseif( isset($_GET['option']) AND session_check() == TRUE )
{
$include = glob("admin/fnc.*.php");
foreach($include as $file)
{
if(!is_array($file)) include_once($file);
}
}
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
require_once("maincore.php");
$actual = "download.php";
add_title("Download");
require_once(BASEDIR.STYLE."tpl.start.php");
echo "<h2>Download</h2>\n";
if( !isset($_GET['id']) )
{
$sql = "SELECT `id`, `name` FROM ".DBPREFIX."files_cat WHERE `order` > '0' ORDER BY `order`";
if(!empty($_GET['cat']) AND check_int($_GET['cat']) == TRUE)
{ $sql = "SELECT `id`, `name` FROM ".DBPREFIX."files_cat WHERE `id` = '".mysql_real_escape_string($_GET['cat'])."'"; }
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_row($query))
{
$sql2 = "SELECT *
FROM ".DBPREFIX."files WHERE `cat` = '".$row[0]."' AND `accepted` = '1' ORDER BY `date` ASC";
$query2=mysql_query($sql2);
if (mysql_num_rows($query2) > 0)
{
echo "<h5>".$row[1]."</h5>\n";
while($row2 = mysql_fetch_assoc($query2))
{
echo "<div class='download-name' >".stripslashes($row2['name'])."</div>\n";
echo "<div class='download-desc' >".stripslashes($row2['desc'])."</div>\n";
echo "<div class='download-down' >".$row2['date']." | ".db_get_data("login","users","id",$row2['adds'],"Brak użytkownika")."<span class='right'>".$row2['size']." KB ";
if($row2['direct'] == 1) echo "<a href='download.php?id=".$row2['id']."'>DOWNLOAD</a></span>";
elseif($row2['direct'] == 0) echo "<a href='".$row2['url']."'>DOWNLOAD</a></span>";
echo "</div>\n";
}
}
}
}
}
if( isset($_GET['id']) AND check_int($_GET['id']) == TRUE AND session_check() == TRUE )
{
$sql = "SELECT `name`, `url`, `id` FROM ".DBPREFIX."files WHERE `id` = '".$_GET['id']."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$file = mysql_fetch_assoc($query);
echo "<div class='suc'>";
echo "Pobierasz: <b>".$file['name']."</b>\n";
echo "<p>Za chwilę powinno ukazać się okno pobierania, jeżeli masz problem, skontaktuj się z <a href='contact.php'>administratorem</a></p>";
echo "</div>\n";
echo "<meta http-equiv='Refresh' content='5; url=downloading.php?id=".$file['id']."' />\n";
}
}
elseif ( isset($_GET['id']) AND check_int($_GET['id']) == FALSE )
{
echo "<div class='err'>";
echo "Błędny identyfikator pliku, <a href='download.php'>spróbuj ponownie</a>";
echo "</div>\n";
}
elseif ( isset($_GET['id']) AND session_check() == FALSE )
{
echo "<div class='not'>";
echo "Tylko zalogowani użytkownicy mog± pobierać pliki";
echo "</div>\n";
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep>-- phpMyAdmin SQL Dump
-- version 3.4.5
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Czas wygenerowania: 11 Kwi 2012, 15:14
-- Wersja serwera: 5.5.16
-- Wersja PHP: 5.3.8
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Baza danych: `template`
--
-- --------------------------------------------------------
--
-- Struktura tabeli dla `articles`
--
CREATE TABLE IF NOT EXISTS `articles` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) COLLATE utf8_polish_ci DEFAULT NULL,
`content` text COLLATE utf8_polish_ci,
`author` int(11) DEFAULT NULL,
`date_start` datetime DEFAULT NULL,
`reads` int(11) DEFAULT NULL,
`allow_comment` smallint(2) DEFAULT NULL,
`allow_rating` smallint(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `atom`
--
CREATE TABLE IF NOT EXISTS `atom` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`atom_url` varchar(100) COLLATE utf8_polish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `blacklist`
--
CREATE TABLE IF NOT EXISTS `blacklist` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ban_userid` int(11) DEFAULT NULL,
`ban_ip` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`ban_reason` varchar(255) COLLATE utf8_polish_ci DEFAULT NULL,
`ban_start` datetime DEFAULT NULL,
`ban_end` datetime DEFAULT NULL,
`adds` int(11) DEFAULT NULL,
`adds_ip` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `calendar`
--
CREATE TABLE IF NOT EXISTS `calendar` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date DEFAULT NULL,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`content` text COLLATE utf8_polish_ci,
`href` varchar(150) COLLATE utf8_polish_ci DEFAULT NULL,
`type` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `comments`
--
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_id` int(11) DEFAULT NULL,
`item_type` varchar(2) COLLATE utf8_polish_ci DEFAULT NULL,
`message` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`user` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`ip` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `faq`
--
CREATE TABLE IF NOT EXISTS `faq` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question` text COLLATE utf8_polish_ci,
`answer` text COLLATE utf8_polish_ci,
`order` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `files`
--
CREATE TABLE IF NOT EXISTS `files` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`desc` text COLLATE utf8_polish_ci,
`url` varchar(150) COLLATE utf8_polish_ci DEFAULT NULL,
`accepted` int(1) DEFAULT NULL,
`size` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`date` date DEFAULT NULL,
`adds` int(11) DEFAULT NULL,
`cat` int(11) DEFAULT NULL,
`direct` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `files_cat`
--
CREATE TABLE IF NOT EXISTS `files_cat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`order` int(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `lea_challanges`
--
CREATE TABLE IF NOT EXISTS `lea_challanges` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`player1` int(11) DEFAULT NULL,
`player2` int(11) DEFAULT NULL,
`season` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`actived` int(11) DEFAULT '0',
`nations` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`winner` int(11) DEFAULT NULL,
`score` int(1) DEFAULT '0',
`score_set` int(11) DEFAULT NULL,
`accepted` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `lea_games`
--
CREATE TABLE IF NOT EXISTS `lea_games` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`player1` int(11) DEFAULT NULL,
`player2` int(11) DEFAULT NULL,
`season` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`nations` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`winner` int(11) DEFAULT NULL,
`score` int(11) DEFAULT '0',
`score_accept` int(11) DEFAULT '0',
`date` datetime DEFAULT NULL,
`scored` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `lea_msg`
--
CREATE TABLE IF NOT EXISTS `lea_msg` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`message` text COLLATE utf8_polish_ci,
`author` int(11) DEFAULT NULL,
`challange_id` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`ip` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `lea_players`
--
CREATE TABLE IF NOT EXISTS `lea_players` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`active` int(1) DEFAULT NULL,
`free` int(1) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
`score_stats` int(11) DEFAULT NULL,
`last_stats_score` int(11) DEFAULT NULL,
`last_stats_position` int(11) DEFAULT NULL,
`wins` int(11) DEFAULT NULL,
`lost` int(11) DEFAULT NULL,
`medals` text COLLATE utf8_polish_ci,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `lea_settings`
--
CREATE TABLE IF NOT EXISTS `lea_settings` (
`last_stats_date` date DEFAULT NULL,
`rules` text COLLATE utf8_polish_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `links`
--
CREATE TABLE IF NOT EXISTS `links` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`url` varchar(150) COLLATE utf8_polish_ci DEFAULT NULL,
`order` int(5) DEFAULT NULL,
`cat` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `links_cat`
--
CREATE TABLE IF NOT EXISTS `links_cat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`order` int(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `news`
--
CREATE TABLE IF NOT EXISTS `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`text` text COLLATE utf8_polish_ci,
`text_ext` text COLLATE utf8_polish_ci,
`author` int(11) DEFAULT NULL,
`languages` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`date_start` datetime DEFAULT NULL,
`date_end` datetime DEFAULT NULL,
`allow_comment` int(1) DEFAULT NULL,
`allow_rating` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `panels`
--
CREATE TABLE IF NOT EXISTS `panels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(150) COLLATE utf8_polish_ci DEFAULT NULL,
`content` text COLLATE utf8_polish_ci,
`display` int(1) DEFAULT NULL,
`order` int(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=3 ;
--
-- Zrzut danych tabeli `panels`
--
INSERT INTO `panels` (`id`, `name`, `content`, `display`, `order`) VALUES
(1, '{CLAN SECTION}', '<ul><li><a href=''clan-members.php''>{TEAM}</a></li></ul>', 1, 1),
(2, '{LEAGUE SECTION}', '<ul><li><a href=''lea.table.php''>{TABLE}</a></li><li><a href=''lea.stats.php''>{STATS}</a></li><li><a href=''lea.account.php''>{SYSTEM}</a></li></ul>', 1, 2);
-- --------------------------------------------------------
--
-- Struktura tabeli dla `ratings`
--
CREATE TABLE IF NOT EXISTS `ratings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_id` int(11) DEFAULT NULL,
`item_type` varchar(2) COLLATE utf8_polish_ci DEFAULT NULL,
`vote` smallint(2) DEFAULT NULL,
`user` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`ip` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `reads`
--
CREATE TABLE IF NOT EXISTS `reads` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_id` int(11) DEFAULT NULL,
`item_type` varchar(2) COLLATE utf8_polish_ci DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `reg_countries`
--
CREATE TABLE IF NOT EXISTS `reg_countries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`lang` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`code` varchar(10) COLLATE utf8_polish_ci DEFAULT NULL,
`set` int(1) DEFAULT NULL,
`charset` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=10 ;
--
-- Zrzut danych tabeli `reg_countries`
--
INSERT INTO `reg_countries` (`id`, `name`, `lang`, `code`, `set`, `charset`) VALUES
(1, 'Polska', 'Polski', 'pol', 1, 'ISO-8859-2'),
(2, 'England', 'English', 'eng', 0, 'ISO-8859-1'),
(3, 'Russia', 'Russian', 'rus', 0, 'ISO-8859-1'),
(4, 'Germany', 'German', 'ger', 0, 'ISO-8859-1'),
(5, 'Ukraine', 'Ukrainian', 'ukr', 0, 'ISO-8859-1'),
(9, 'Hungary', 'Hungarian', 'hun', 0, 'ISO-8859-1');
-- --------------------------------------------------------
--
-- Struktura tabeli dla `reg_emots`
--
CREATE TABLE IF NOT EXISTS `reg_emots` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(10) COLLATE utf8_polish_ci DEFAULT NULL,
`image` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`display` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=10 ;
--
-- Zrzut danych tabeli `reg_emots`
--
INSERT INTO `reg_emots` (`id`, `code`, `image`, `display`) VALUES
(1, ':)', '1.gif', 1),
(2, ';)', '2.gif', 1),
(3, ':D', '3.gif', 1),
(4, ';D', '3.gif', 1),
(5, '=]', '4.gif', 1),
(6, ';]', '5.gif', 1),
(7, ':]', '5.gif', 1),
(8, ':x', '6.gif', 1),
(9, ';x', '6.gif', 1);
-- --------------------------------------------------------
--
-- Struktura tabeli dla `settings`
--
CREATE TABLE IF NOT EXISTS `settings` (
`mainpage` varchar(50) COLLATE utf8_polish_ci DEFAULT 'news.php',
`clanname` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`headadmin` int(11) DEFAULT NULL,
`email` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`title` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`header_text_main` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`header_text_sub` varchar(100) COLLATE utf8_polish_ci DEFAULT NULL,
`footer` varchar(200) COLLATE utf8_polish_ci DEFAULT NULL,
`logoimage` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`fav_ico` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`desc` varchar(200) COLLATE utf8_polish_ci DEFAULT NULL,
`keys` varchar(100) COLLATE utf8_polish_ci DEFAULT NULL,
`author` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`log_sys` int(1) DEFAULT '1',
`forum_sys` int(1) DEFAULT '0',
`forum_link` varchar(100) COLLATE utf8_polish_ci DEFAULT '#',
`banner_sys` int(1) DEFAULT '0',
`antyflood` int(3) DEFAULT '30',
`admin_note` text COLLATE utf8_polish_ci
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
--
-- Zrzut danych tabeli `settings`
--
INSERT INTO `settings` (`mainpage`, `clanname`, `headadmin`, `email`, `title`, `header_text_main`, `header_text_sub`, `footer`, `logoimage`, `fav_ico`, `desc`, `keys`, `author`, `log_sys`, `forum_sys`, `forum_link`, `banner_sys`, `antyflood`, `admin_note`) VALUES
('news.php', '{CLAN NAME}', 1, '<EMAIL>', '{TITLE}', '{HEADER}', '{HEADER-SUB}', '{FOOTER}', '', 'images/favico.ico', 'description', 'keywords', '<NAME>', 1, 0, '#', 0, 30, NULL);
-- --------------------------------------------------------
--
-- Struktura tabeli dla `shoutbox`
--
CREATE TABLE IF NOT EXISTS `shoutbox` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime DEFAULT NULL,
`text` varchar(100) COLLATE utf8_polish_ci DEFAULT NULL,
`author` int(11) DEFAULT NULL,
`show` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
--
-- Struktura tabeli dla `shoutbox_set`
--
CREATE TABLE IF NOT EXISTS `shoutbox_set` (
`display` int(1) DEFAULT NULL,
`rows` int(2) DEFAULT NULL,
`max_lenght` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
--
-- Zrzut danych tabeli `shoutbox_set`
--
INSERT INTO `shoutbox_set` (`display`, `rows`, `max_lenght`) VALUES
(0, 3, 50);
-- --------------------------------------------------------
--
-- Struktura tabeli dla `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`login` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`password` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`mail` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`register_date` datetime DEFAULT NULL,
`register_ip` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`last_date` datetime DEFAULT NULL,
`last_ip` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`active` int(1) DEFAULT NULL,
`level` int(4) DEFAULT NULL,
`rights` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`avatar` varchar(100) COLLATE utf8_polish_ci DEFAULT NULL,
`gg` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`icq` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`name` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`intrest` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`location` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`born` date DEFAULT NULL,
`gender` int(1) DEFAULT NULL,
`country` varchar(10) COLLATE utf8_polish_ci DEFAULT NULL,
`gamenick` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`clan` varchar(20) COLLATE utf8_polish_ci DEFAULT NULL,
`favrules` varchar(50) COLLATE utf8_polish_ci DEFAULT NULL,
`usertitle` varchar(30) COLLATE utf8_polish_ci DEFAULT NULL,
`siteclan_member` int(1) DEFAULT NULL,
`siteclan_date` date DEFAULT NULL,
`display_mail` int(1) DEFAULT NULL,
`display_online` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=5 ;
--
-- Zrzut danych tabeli `users`
--
INSERT INTO `users` (`id`, `login`, `password`, `mail`, `register_date`, `register_ip`, `last_date`, `last_ip`, `active`, `level`, `rights`, `avatar`, `gg`, `icq`, `name`, `intrest`, `location`, `born`, `gender`, `country`, `gamenick`, `clan`, `favrules`, `usertitle`, `siteclan_member`, `siteclan_date`, `display_mail`, `display_online`) VALUES
(1, 'admin', '<PASSWORD>', '<EMAIL>', '2012-04-10 00:00:00', NULL, '0000-00-00 00:00:00', NULL, 1, 101, 'M.A.LA.SA', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 'pol', 'gamenick', 'clan', NULL, NULL, 1, '0000-00-00', 1, 1),
(2, 'SYSTEM', '0', '0', '0000-00-00 00:00:00', '0', '0000-00-00 00:00:00', '0', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0),
(3, 'Robot #1', '0', '0', '0000-00-00 00:00:00', '0', '0000-00-00 00:00:00', '0', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0),
(4, 'Robot #2', '0', '0', '0000-00-00 00:00:00', '0', '0000-00-00 00:00:00', '0', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0),
(5, 'Guest', '0', '0', '0000-00-00 00:00:00', '0', '0000-00-00 00:00:00', '0', 1, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0);
/*!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><?php
require_once "maincore.php";
add_title($config['clanname']." team");
require_once (BASEDIR.STYLE."tpl.start.php");
if( !isset($_GET['action']) || $_GET['action'] != "show" )
{
echo "<h2>".$config['clanname']."</h2>\n";
echo "\n";
echo "\n";
echo "<dl>\n";
$sql = "SELECT `id`, `login`, `country`, `last_date` FROM ".DBPREFIX."users WHERE `active`='1' AND `siteclan_member`='1' ORDER BY `login` ASC";
$query = mysql_query($sql);
if (@mysql_num_rows($query) > 0)
{
while($mmbr = mysql_fetch_assoc($query))
{
if(empty($mmbr['country'])) $mmbr['country'] = "blank";
echo "<li><a href='clan-members.php?action=show&member_id=".$mmbr['id']."'>";
echo "<img src='images/flags/small_".$mmbr['country'].".png' title='".db_get_data("name","reg_countries","code",$mmbr['country'])."' border='0'/>";
echo " ".$mmbr['login']."</a>";
echo "</li>\n";
}
}
echo "</dl>\n";
}
elseif( $_GET['action'] == "show" AND check_int($_GET['member_id']) == TRUE)
{
$id = ($_GET['member_id']);
$sql = "SELECT * FROM ".DBPREFIX."users WHERE `active`='1' AND `siteclan_member`='1' AND `id` = '".$id."'";
$query = mysql_query($sql);
if (@mysql_num_rows($query) > 0)
{
$player = mysql_fetch_assoc($query);
if(get_time_difference($player['last_date'])<2678400) $player['active'] = "<span class='green'>Aktywny</span>"; else $player['active'] = "<span class='red'>Nieaktywny</span>";
$clantime = explode("-",$player['siteclan_date']); if ($clantime[0] == 2004) $clantime[0] = "Brak danych";
if($player['gg'] == 0) $player['gg'] = "n/a";
if($player['icq'] == 0) $player['icq'] = "n/a";
if($player['born'] == 0) $player['born'] = "n/a";
if(empty($player['avatar'])) $player['avatar'] = "images/avatars/blank.png";
if(empty($player['name'])) $player['name'] = "n/a";
if(empty($player['intrest'])) $player['intrest'] = "n/a";
if(empty($player['favrules'])) $player['favrules'] = "n/a";
if(empty($player['location'])) $player['location'] = "n/a";
$player['desc'] = stripslashes($player['desc']);
if($player['display_mail'] == 0) $player['mail'] = "<i>Ukryty</i>\n";
echo "\n";
echo "<!-- DANE: ".$player['login']." -->\n";
echo "\n";
echo " <div class='player-head'>\n";
echo " <img src='".$player['avatar']."' class='left profile-avatar' width='90' height='90'/>\n";
echo " <h4 style='font-style:italic;'>".$player['login']."</h4>\n";
echo " <img src='images/clans/".$player['clan'].".gif'/><br/>";
echo $player['usertitle'];
echo " </div>\n";
echo " <div class='clear'><br></div>\n";
echo " <table class='table0 left table-clan'>\n";
echo " <tr><th colspan='2'>Dane kontaktowe</th></tr>\n";
echo " <tr><td width='100'>Mail</td><td>".$player['mail']."</td></tr>\n";
echo " <tr><td width='100'>GG</td><td>".$player['gg']."</td></tr>\n";
echo " <tr><td width='100'>ICQ</td><td>".$player['icq']."</td></tr>\n";
echo " </table>\n";
echo " <table class='table0 right table-clan'>\n";
echo " <tr><th colspan='2'>Dane personalne</th></tr>\n";
echo " <tr><td width='100'>Imię</td><td>".$player['name']."</td></tr>\n";
echo " <tr><td width='100'>Urodziny</td><td>".$player['born']."</td></tr>\n";
echo " <tr><td width='100'>Płeć</td><td>".get_gender($player['gender'])."</td></tr>\n";
echo " <tr><td width='100'>Zainteresowania</td><td>".$player['intrest']."</td></tr>\n";
echo " <tr><td width='100'>Miejscowość</td><td>".$player['location']."</td></tr>\n";
echo " </table>\n";
if($clantime[0] > 2005)
{
if($clantime[1] == 1)$clantime = "stycznia ".$clantime[0];
if($clantime[1] == 2)$clantime = "lutego ".$clantime[0];
if($clantime[1] == 3)$clantime = "marca ".$clantime[0];
if($clantime[1] == 4)$clantime = "kwietnia ".$clantime[0];
if($clantime[1] == 5)$clantime = "maja ".$clantime[0];
if($clantime[1] == 6)$clantime = "czerwca ".$clantime[0];
if($clantime[1] == 7)$clantime = "lipca ".$clantime[0];
if($clantime[1] == 8)$clantime = "sierpnia ".$clantime[0];
if($clantime[1] == 9)$clantime = "września ".$clantime[0];
if($clantime[1] == 10)$clantime = "października ".$clantime[0];
if($clantime[1] == 11)$clantime = "listopada ".$clantime[0];
if($clantime[1] == 12)$clantime = "grudnia ".$clantime[0];
}
else $clantime = "zawsze";
echo " <div class='clear-l'><br></div>\n";
echo " <table class='table0 left table-clan'>\n";
echo " <tr><th colspan='2'>Dane gracza</th></tr>\n";
echo " <tr><td width='100'>Nick</td><td>".$player['login']."</td></tr>\n";
echo " <tr><td width='100'>Aktywność</td><td>".$player['active']."</td></tr>\n";
echo " <tr><td width='100'>Ulubione rules</td><td>".$player['favrules']."</td></tr>\n";
echo " <tr><td width='100'>W klanie od</td><td>".$clantime."</td></tr>\n";
echo " </table>\n";
echo " <div class='clear-l'><br></div>\n";
if(0 == 0)
{
echo " <table class='table0 left w100'>\n";
echo " <tr><th>Osiągnięcia</th></tr>\n";
echo " <tr><td>".$player['desc']."</td></tr>\n";
echo " </table>\n";
}
}
}
require_once (BASEDIR.STYLE."tpl.end.php");
?>
<file_sep># cms-old-php5
Old CMS project, procedural code
Projekt był realizowany do nauki, a także dzięki zastosowaniu pomniejszych zabezpieczeń do działania portalu działającego w sieci.
Portal wykorzystuje głównie prosty szablon HTML4 + CSS, PHP (host z wersją 5.3.2) oraz zapytania SQL.
Ostateczna wersja przepadła wraz z hostingiem, a projekt został porzucony.
<file_sep><?php
require_once "maincore.php";
require_once (BASEDIR.STYLE."tpl.start.php");
// 0 - user zalogowany
// 1 - zalogowano poprawnie
// 2 - nie uzupełniono pól
// 3 - blędne dane
$result = log_user_in();
if($result == 0) redirect($config['mainpage']);
if($result == 1) redirect($config['mainpage']);
if($result == 2) $msg = "Uzupełnij wszystkie pola.";
if($result == 3) $msg = "Podano złą nazwę użytkownika lub hasło.";
banlist_verification();
echo "<div class='not'>\n";
echo $msg."Przejdź do <a href='index.php'>strony głównej</a>.";
echo "</div>\n";
require_once (BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "languages" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// session check
session_check();
// fixing last item id & vars
$sql = "SELECT `id` FROM `".DBPREFIX."reg_countries` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// new item
if( @$_POST['send'] == "new" )
{
$new['id'] = $last_id+1;
$new['name'] = addslashes($_POST['form1']);
$new['lang'] = addslashes($_POST['form2']);
$new['code'] = addslashes($_POST['form3']);
$new['charset'] = addslashes($_POST['form4']);
$new['set'] = $_POST['set'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "INSERT INTO `".DBPREFIX."reg_countries` VALUES('".$new['id']."','".$new['name']."','".$new['lang']."','".$new['code']."','".$new['set']."','".$new['charset']."');";
mysql_query($sql);
$result = "Dodano poprawnie do bazy";
}
}
// edit item
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."reg_countries` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['name'] = stripslashes($data['name']);
$edit['lang'] = stripslashes($data['lang']);
$edit['code'] = stripslashes($data['code']);
$edit['charset'] = stripslashes($data['charset']);
$edit['set'] = $data['set'];
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
// update item
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE)
{
$upt['name'] = addslashes($_POST['form1']);
$upt['lang'] = addslashes($_POST['form2']);
$upt['code'] = addslashes($_POST['form3']);
$upt['charset'] = addslashes($_POST['form4']);
$upt['set'] = $_POST['set'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "UPDATE `".DBPREFIX."reg_countries` SET `name` = '".$upt['name']."', `lang` = '".$upt['lang']."', `code` = '".$upt['code']."', `set` = '".$upt['set']."', `charset` = '".$upt['charset']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Dane zostały zaaktualizowane";
}
}
mysql_query($sql);
}
// finish
if( !empty($edit['code']) ) $table_info = "Edytujesz: ".$edit['code']; else $table_info = "Nowy";
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie zbiorem flag i języków</th></tr>\n";
echo "<tr><td colspan='2' align='left'><h6>".$table_info."<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Kraj</td><td><input class='text' type='text' name='form1' value='".@$edit['name']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td >Język</td><td><input class='text' type='text' name='form2' value='".@$edit['lang']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kod</td><td><input class='w25' type='text' name='form3' value='".@$edit['code']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Znakowanie</td><td><input class='w25' type='text' name='form4' value='".@$edit['charset']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Ustawiony</td><td>\n";
echo "<select class='select' name='set' style='width:150px;'>\n";
echo "<option value='0'"; if( @$edit['set'] == 0 ) echo " selected='selected'"; echo ">Normalny</option>\n";
echo "<option value='1'"; if( @$edit['set'] == 1 ) echo " selected='selected'"; echo ">Tłumaczenie serwisu</option>\n";
echo "<option value='9'"; if( @$edit['set'] == 9 ) echo " selected='selected'"; echo ">Główny</option>\n";
echo "</select>\n";
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "<tr><td colspan='2'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<form action='' method='post'>\n";
echo "<td align='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT * FROM `".DBPREFIX."reg_countries` ORDER BY `name` ASC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <select name='choosed_id' class='select'>\n";
while($lang = mysql_fetch_assoc($query))
{
echo " <option value='".$lang['id']."'>".$lang['code']." | ".$lang['lang']."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n";
}
?>
<file_sep><?php
require_once("install.core.php");
$sql = array(
"INSERT INTO `settings` VALUES('news.php','Nazwa','1','<EMAIL>','Nazwa','Nazwa','Podtytuł!','PRSystem BETA ; Cossacks BtW is the game by CDV & GSC','','images/favico.ico','desc','keys','','1','0','http://forum.kozacy.org/','0','30','');",
"INSERT INTO `users` VALUES('','Admin','7<PASSWORD>','<EMAIL>','2012-04-10','0','0000-00-00 00:00:00','0','1','101','M.A.SA','0','0','','','','1950-01-01','0','POL','Nick','PR','','','1','2005-01-01','1','1');",
"INSERT INTO `panels` VALUES('','Polska Rewolucja','<ul><li><a href='clan-members.php'>{TEAM}</a></li></ul>','1','1');",
"INSERT INTO `panels` VALUES('','Liga 0','<ul><li><a href='lea.table.php'>{TABLE}</a></li><a href='lea.table.php'>{STATS}</a></li><a href='lea.account.php'>{SYSTEM}</a></li></ul>','1','2');",
"INSERT INTO `reg_countries` VALUES('','Polska','Polski','POL','1','ISO-8859-2');",
"INSERT INTO `reg_countries` VALUES('','Russia','Russian','RUS','0','UTF-8');",
"INSERT INTO `reg_countries` VALUES('','England','English','ENG','0','ISO-8859-1');"
);
for($i=0;!empty($sql[$i]);$i++)
{
echo $sql[$i]."<br>";
mysql_query($sql[$i]);
echo "COMPLETED;";
}
?>
<file_sep><?php
if( $_GET['option'] == "faq" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
// fixing last item id
$sql = "SELECT `id` FROM `".DBPREFIX."faq` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// new item
if( @$_POST['send'] == "new" AND check_int($_POST['form3']) == TRUE)
{
$new['id'] = $last_id+1;
$new['text'] = addslashes($_POST['form1']);
$new['answer'] = addslashes($_POST['form2']);
$new['order'] = $_POST['form3'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "INSERT INTO `".DBPREFIX."faq` VALUES('".$new['id']."','".$new['text']."','".$new['answer']."','".$new['order']."');";
mysql_query($sql);
$result = "Pytanie zostało dodane";
}
}
// edit item
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."faq` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['text'] = stripslashes($data['question']);
$edit['answer'] = stripslashes($data['answer']);
$edit['order'] = $data['order'];
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
// update item
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE AND check_int($_POST['form3']) == TRUE )
{
$upt['text'] = addslashes($_POST['form1']);
$upt['answer'] = addslashes($_POST['form2']);
$upt['order'] = $_POST['form3'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) AND check_int($_POST['form3']) == FALSE) $result = "Brak potrzebnych danych";
else
{
$sql = "UPDATE `".DBPREFIX."faq` SET `question` = '".$upt['text']."', `answer` = '".$upt['answer']."', `order` = '".$upt['order']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Pytanie zostało zaaktualizowane";
}
}
mysql_query($sql);
}
// form
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
if( @strlen($edit['text']) > 50 ) $table_info = substr($edit['text'],0,50)."...";
elseif( isset($edit['text']) ) $table_info = $edit['text'];
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie pytaniami FAQ</th></tr>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>".$table_info."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form class='' action='' method='post'>\n";
echo "<td valign='top' width='150'>Pytanie</td><td><textarea style='height:75px' name='form1'>".@$edit['text']."</textarea></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td valign='top'>Odpowiedź</td><td><textarea style='height:75px' name='form2'>".@$edit['answer']."</textarea></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kolejność</td><td><input class='text' type='text' style='width:50px;' name='form3' value='".@$edit['order']."'/><span class='text-tiny'> Jeżeli kolejność == 0 to pytanie nie zostanie pokazane</span></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</tr>\n";
echo "</form>\n";
// form:list of existing items
echo "<form action='' method='post'>\n";
echo "<tr><td colspan='2' align='left'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<td align='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT `id`,`question`,`order` FROM `".DBPREFIX."faq` ORDER BY `order` DESC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <select name='choosed_id' class='select'>\n";
while($faq = mysql_fetch_assoc($query))
{
echo " <option value='".$faq['id']."'>[ ".$faq['order']." ] ".stripslashes($faq['question'])."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</tr>\n";
echo "</form>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
function emots($tekst)
{
$sql = "SELECT * FROM `".DBPREFIX."reg_emots` WHERE `display` = '1'";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0)
{
while($emot = mysql_fetch_assoc($query))
{
$tekst = str_replace($emot['code'],"<img src='".IMAGES."emots/".$emot['image']."' width='14' height='14' border='0'/>",$tekst);
}
}
return $tekst;
}
function codes($tekst)
{
$tekst = stripslashes($tekst);
$tekst = htmlspecialchars($tekst);
$tekst = nl2br($tekst);
$tekst = preg_replace("#\[b\](.*?)\[/b\]#si",'<b>\\1</b>',$tekst);
$tekst = preg_replace("#\[i\](.*?)\[/i\]#si",'<i>\\1</i>',$tekst);
$tekst = preg_replace("#\[u\](.*?)\[/u\]#si",'<u>\\1</u>',$tekst);
$tekst = preg_replace("#\[s\](.*?)\[/s\]#si",'<s>\\1</s>',$tekst);
$tekst = preg_replace("#\[size=small\](.*?)\[/size\]#si",'<span class=\'text-tiny\'>\\1</span>',$tekst);
$tekst = preg_replace("#\[url\](.*?)\[/url\]#si", "<a href=\"\\1\">\\1</a>", $tekst);
$tekst = preg_replace("#\[url=(.*?)\](.*?)\[/url\]#si", "<a href=\"\\1\">\\2</a>", $tekst);
$tekst = preg_replace("#\[img\](.*?)\[/img\]#si",'<img src="\\1"/>',$tekst);
$tekst = preg_replace("#\[code\](.*?)\[/code\]#si",'<pre>\\1</pre>',$tekst);
$tekst = preg_replace("#\[ul\](.*?)\[/ul\]#si",'<ul>\\1</ul>',$tekst);
$tekst = preg_replace("#\[li\](.*?)\[/li\]#si",'<li>\\1</li>',$tekst);
$tekst = preg_replace("#\[clan\](.*?)\[/clan\]#si","<img src='images/clans/\\1.gif' border='0'/>",$tekst);
$tekst = emots($tekst);
$sql = "SELECT * FROM `".DBPREFIX."reg_countries`";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0)
{
while($lang = mysql_fetch_assoc($query))
{
$tekst = str_replace("[lang]".$lang['code']."[/lang]","<a name='".$lang['code']."'></a><h4 class='lang'> <img src='".IMAGES."flags/small_".$lang['code'].".png' border='0'/> ".$lang['lang']."</h4>",$tekst);
}
}
return $tekst;
}
?>
<file_sep><?php
require_once("maincore.php");
$actual = "contact.php";
add_title("Kontakt");
require_once(BASEDIR.STYLE."tpl.start.php");
echo "<h2>Kontakt</h2>\n";
$sql = "SELECT * FROM ".DBPREFIX."users WHERE `active`='1' AND `level` > '100'";
$query = mysql_query($sql);
if(@mysql_num_rows($query)>0)
{
while($user = mysql_fetch_assoc($query))
{
echo " <h5>".$user['login']."</h5>\n";
echo " <ul>\n";
echo " <li>e-Mail: <a href='mailto:".$user['mail']."'>".$user['mail']."</a></li>\n";
if( $user['gg'] != 0 AND !empty($user['gg']) ) echo " <li>GG: <a href='gg:".$user['gg']."'>".$user['gg']."</a></li>\n";
if( $user['icq'] != 0 AND !empty($user['icq']) ) echo " <li>ICQ: <a href='icq:".$user['icq']."'>".$user['icq']."</a></li>\n";
echo " </ul><br/>\n";
}
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
$dbhost = "localhost";
$dbuser = "prgutek_admin";
$dbpass = "<PASSWORD>";
$dbname = "prgutek_database";
define("DBPREFIX","");
?>
<file_sep><?php
require_once("maincore.php");
require_once(BASEDIR.STYLE."tpl.start.php");
require_once("lea.core.php");
score_stats();
score_players_stats_history();
$sql = "SELECT * FROM `lea_players` WHERE `active` = '1' ORDER BY `score_stats` DESC";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
echo "<table class='table0 w100'>\n";
echo " <tr><th class='lea-lp'>Poz.</th><th class='lea-country'>Kraj</th><th class='lea-nick'>Nick</th><th class='lea-clan'>Klan</th><th class='lea-score'>Punkty</th><th class='lea-games'>W</th><th class='lea-games'>G</th><th class='lea-changes'>Poz.</th><th class='lea-changes'>Pkt.</th></tr>\n";
$i = 1;
while($player = mysql_fetch_assoc($query))
{
$sql2 = "SELECT `id`, `gamenick`, `clan`, `country` FROM `users` WHERE `id` = '".$player['user_id']."' LIMIT 1";
$query2 = mysql_query($sql2);
$user = mysql_fetch_assoc($query2);
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
if(($player['last_stats_position'] - $i) < 0) $pos_change = "<img src='images/icons/league/r.png' title='-".abs($player['last_stats_position'] - $i)."' alt='-".abs($player['last_stats_position'] - $i)."'>";
if(($player['last_stats_position'] - $i) > 0) $pos_change = "<img src='images/icons/league/g.png' title='+".abs($player['last_stats_position'] - $i)."' alt='+".abs($player['last_stats_position'] - $i)."'>";
if(($player['last_stats_position'] - $i) == 0) $pos_change = "<img src='images/icons/league/b.png' title='Bez zmian' alt='Bez zmian'>";
if($player['last_stats_position'] == 0) $pos_change = "<img src='images/icons/league/b.png' title='NOWY' alt='NOWY'>";
echo " <tr".$second_row.">";
echo "<td class='center'>".$i."</td>";
echo "<td class='center'><img src='images/flags/small_".$user['country'].".png' title='".db_get_data("name","reg_countries","code",$user['country'])."' border='0'/></td>";
echo "<td class='center'><a href='lea.players.php?p_id=".$user['id']."'>".$user['gamenick']."</a></td>";
echo "<td class='center'><img src='images/clans/".$user['clan'].".gif' alt='".$user['clan']."'/></td>";
echo "<td class='center'>".$player['score_stats']."</td>";
echo "<td class='center'>".$player['wins']."</td>";
echo "<td class='center'>".($player['wins']+$player['lost'])."</td>";
echo "<td class='center'>".$pos_change."</td>";
echo "<td class='center'>".($player['score_stats'] - $player['last_stats_score'])."</td>";
echo "</tr>\n";
$i = $i+1;
}
echo "</table>";
}
else echo "<div class='not'>Liga aktualnie nie działa</div>\n";
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
require_once("maincore.php");
$actual = "links.php";
add_title("Linki");
require_once(BASEDIR.STYLE."tpl.start.php");
echo "<h2>Linki</h2>\n";
$sql= "SELECT `id`, `name` FROM ".DBPREFIX."links_cat ORDER BY `order`";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
$sql2 = "SELECT `name`, `url`,`cat` FROM ".DBPREFIX."links WHERE `cat` = '".$row['id']."' ORDER BY `order` ASC";
$query2 = mysql_query($sql2);
if (mysql_num_rows($query2) > 0)
{
echo "<h5>".$row['name']."</h5>\n";
while($row2 = mysql_fetch_assoc($query2))
{
if($row2['cat']==$row['id'])
{
echo "<ul>";
echo "<li><a href='".$row2['url']."'>".$row2['name']."</a>\n";
echo "<div class='text-tiny'>".$row2['url']."</div>";
echo "</ul>";
}
}
}
}
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "bans" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// session check
session_check();
// fixing last item id & vars
$sql = "SELECT `id` FROM `".DBPREFIX."blacklist` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
$ys = date("Y"); $ms = date("m"); $ds = date("d");
$hs = date("H"); $is = date("i"); $ss = "00";
$ye = date("Y",strtotime ("+1 hour")); $me = date("m",strtotime ("+1 hour")); $de = date("d",strtotime ("+1 hour"));
$he = date("H",strtotime ("+1 hour")); $ie = date("i",strtotime ("+1 hour")); $se = "00";
// new ban
$table_info = "Nowy";
if ( @$_POST['send'] == "new" )
{
if( !empty($_POST['form1']) OR !empty($_POST['form2']) )
{
$user_no_exists = 0;
if ( !empty($_POST['form1']) )
{
if( db_get_data("id","users","login",$_POST['form1']) != $config['headadmin'] )
{
$sql = "SELECT * FROM `".DBPREFIX."users` WHERE `login` = '".htmlspecialchars(addslashes($_POST['form1']))."'";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$selected_id = $data['id'];
}
else { $user_no_exists = 1; $result = "Nie znaleziono podanego użytkownika"; }
}
elseif( db_get_data("id","users","login",$_POST['form1']) == $config['headadmin'] )
{
$user_no_exists = 1; $result = "Nie można zablokować głównego administratora!!!";
}
}
if( $user_no_exists != 1 )
{
$new['id'] = $last_id+1;
$new['userid'] = db_get_data("id","users","login",$_POST['form1']);
$new['ip'] = addslashes($_POST['form2']);
$new['reason'] = addslashes($_POST['form3']);
$new['date_start'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds']." ".$_POST['hs'].":".$_POST['is'].":".$_POST['ss'];
$new['date_end'] = $_POST['ye']."-".$_POST['me']."-".$_POST['de']." ".$_POST['he'].":".$_POST['ie'].":".$_POST['se'];
if( $new['date_start'] < $new['date_end'] )
{
$sql = "INSERT INTO `".DBPREFIX."blacklist` VALUES('".$new['id']."','".$new['userid']."','".$new['ip']."','".$new['reason']."','".$new['date_start']."','".$new['date_end']."','".$_SESSION['userid']."','".USER_IP."','".DATETIME."');";
mysql_query($sql);
$result = "Dodano blokadę";
}
else $result = "Data zakończenia musi być po dacie rozpoczęcia!";
}
}
else $result = "Brak danych dotyczących blokady";
}
// edit ban
if ( @$_POST['send'] == "edit" )
{
$sql = "SELECT * FROM `".DBPREFIX."blacklist` WHERE `id` = '".$_POST['ban_id']."' LIMIT 1";
$query = mysql_query($sql);
if ( mysql_num_rows($query) > 0 )
{
$a = mysql_fetch_assoc($query);
$edit['userid'] = db_get_data("login","users","id",$a['ban_userid']);
$edit['ip'] = $a['ban_ip'];
$edit['reason'] = $a['ban_reason'];
$edit['i1'] = $a['adds'];
$edit['i2'] = $a['adds_ip'];
$edit['i3'] = $a['date'];
$table_info = "Edycja blokady dla: ".$edit['userid']." | IP: ";
if( !empty($edit['ip']) ) $table_info .= $edit['ip']; else $table_info .= " n/a ";
$ys = substr($a['ban_start'],0,4); $ms = substr($a['ban_start'],5,2);
$ds = substr($a['ban_start'],8,2); $hs = substr($a['ban_start'],11,4);
$is = substr($a['ban_start'],14,2); $ss = substr($a['ban_start'],17,2);
$ye = substr($a['ban_end'],0,4); $me = substr($a['ban_end'],5,2);
$de = substr($a['ban_end'],8,2); $he = substr($a['ban_end'],11,4);
$ie = substr($a['ban_end'],14,2); $se = substr($a['ban_end'],17,2);
$edit['id'] = $a['id'];
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
}
// update ban
if ( @$_POST['send'] == "update" )
{
if( !empty($_POST['form1']) OR !empty($_POST['form2']) )
{
$user_no_exists = 0;
if ( !empty($_POST['form1']) )
{
$sql = "SELECT * FROM `".DBPREFIX."users` WHERE `login` = '".htmlspecialchars(addslashes($_POST['form1']))."'";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$selected_id = $data['id'];
}
elseif( empty($_POST['form2']) ) { $user_no_exists = 1; $result = "Nie znaleziono podanego użytkownika"; }
}
if( htmlspecialchars(addslashes($_POST['form1'])) == $config['headadmin'] )
{
$user_no_exists = 1; $result = "Nie można zablokować głównego administratora!!!";
}
if( $user_no_exists != 1 )
{
$upt['userid'] = db_get_data("id","users","login",$_POST['form1']);
$upt['ip'] = addslashes($_POST['form2']);
$upt['reason'] = addslashes($_POST['form3']);
$upt['date_start'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds']." ".$_POST['hs'].":".$_POST['is'].":".$_POST['ss'];
$upt['date_end'] = $_POST['ye']."-".$_POST['me']."-".$_POST['de']." ".$_POST['he'].":".$_POST['ie'].":".$_POST['se'];
if( $upt['date_start'] < $upt['date_end'] )
{
$sql = "UPDATE `".DBPREFIX."blacklist` SET `ban_userid` = '".$upt['userid']."', `ban_ip` = '".$upt['ip']."', `ban_reason` = '".$upt['reason']."', `ban_start` = '".$upt['date_start']."', `ban_end` = '".$upt['date_end']."' WHERE `id` = '".$_POST['edited_id']."' LIMIT 1";
mysql_query($sql);
$result = "Zaaktualizowano";
}
else $result = "Data zakończenia musi być po dacie rozpoczęcia!";
}
}
else $result = "Brak danych dotyczących blokady";
}
if( !empty($result) ) echo "<div class='not'>".$result."</div>\n";
$valid_unban = date("Y-m-d H:i:s",strtotime("-1 month"));
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='5'>Zarządzanie listą blokad</th></tr>\n";
$sql = "SELECT * FROM `".DBPREFIX."blacklist` WHERE `ban_end` > '".$valid_unban."'";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
echo "<tr><td colspan='5'><h6>Istniejące blokady<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
echo "<tr>";
echo "<td width='150'><h6 class='center'>Użytkownik</h6></td>";
echo "<td width='110'><h6 class='center'>IP</h6></td>";
echo "<td width='150'><h6 class='center'>Powód</h6></td>";
echo "<td width='140'><h6 class='center'>Czas blokady</h6></tdh>";
echo "<td width='50'></td>";
echo "</tr>\n";
while ( $ban = mysql_fetch_assoc($query) )
{
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td class='center'>".db_get_data("login","users","id",$ban['ban_userid'])."</td>";
echo "<td class='center'>".$ban['ban_ip']."</td>";
echo "<td class='center'>".$ban['ban_reason']."</td>";
echo "<td>"; if( $ban['ban_end'] > DATETIME ) echo "<b>OD:</b> ".$ban['ban_start']."<br/>"; else echo "<b class='green'>Zakończony</b><br/>"; echo "<b>DO:</b> ".$ban['ban_end']."</td>";
echo "<td><input type='hidden' name='send' value='edit'><input type='hidden' name='ban_id' value='".$ban['id']."'><input type='submit' class='submit-bans' value='Zmień'/>";
echo "</form>\n";
echo "</tr>\n";
}
}
else
{
echo "<tr><td colspan='5' align='left'><h6><a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
}
echo "<tr><td colspan='5' align='left'><h6>";
if ( !empty($table_info) ) echo $table_info; else echo " ";
echo "</td></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Użytkownik</td><td colspan='4'><input class='text' type='text' name='form1' value='".@$edit['userid']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>IP</td><td colspan='4'><input class='text' type='text' name='form2' value='".@$edit['ip']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Powód</td><td colspan='4'><input class='text' type='text' name='form3' value='".@$edit['reason']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td width='150'>Data rozpoczęcia</td><td colspan='4'>";
echo form_select_date("ys",2005,2090,"Y",60,$ys);
echo form_select_date("ms",1,12,"m",40,$ms);
echo form_select_date("ds",1,31,"d",40,$ds);
echo " : ";
echo form_select_date("hs",0,23,"H",40,$hs);
echo form_select_date("is",0,59,"i",40,$is);
echo form_select_date("ss",0,59,"s",40,$ss);
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td width='150'>Data zakończenia</td><td colspan='4'>";
echo form_select_date("ye",2005,2090,"Y",60,$ye);
echo form_select_date("me",1,12,"m",40,$me);
echo form_select_date("de",1,31,"d",40,$de);
echo " : ";
echo form_select_date("he",0,23,"H",40,$he);
echo form_select_date("ie",0,59,"i",40,$ie);
echo form_select_date("se",0,59,"s",40,$se);
echo "</td>";
echo "</tr>\n";
if( (!empty($edit['i1']) OR !empty($edit['i2']) OR !empty($edit['i3'])) AND $config['headadmin'] == $_SESSION['userid'] )
{
echo "<tr><td>Autor</td><td colspan='4'>".db_get_data("login","users","id",$edit['i1'])."</td></tr>\n";
echo "<tr><td>IP</td><td colspan='4'>".$edit['i2']."</td></tr>\n";
echo "<tr><td>Data</td><td colspan='4'>".$edit['i3']."</td></tr>\n";
}
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
require_once "maincore.php";
add_title("Rejestracja");
require_once (BASEDIR.STYLE."tpl.start.php");
if( isset($_POST['send']) )
{
if( $_POST['send'] == "register" )
{
if( !empty($_POST['r1']) AND !empty($_POST['r2']) AND !empty($_POST['r3']) AND !empty($_POST['r4']))
{
if( $_POST['r2'] == $_POST['r3'] )
{
if( strlen($_POST['r1']) > 3 )
{
if( strlen($_POST['r2']) > 3 )
{
$sql = "SELECT * FROM ".DBPREFIX."users WHERE login='".htmlspecialchars($_POST["r1"])."'";
$query = mysql_query($sql);
if(mysql_num_rows($query)) echo registration_form("Login jest już zajęty!","err");
else
{
$log = htmlspecialchars($_POST["r1"]);
$pass = md5(htmlspecialchars($_POST["r2"]));
$mail = htmlspecialchars($_POST["r4"]);
$clan = htmlspecialchars($_POST["r5"]);
$sql = "INSERT INTO `".DBPREFIX."users` VALUES (NULL, '".$log."', '".$pass."', '".$mail."', '".DATE_SET."', '".USER_IP."', '0000-00-00', '0', '0', '0', '', '', '0', '0', '', '', '', '0000-00-00', '', '', '".$log."', '".$clan."', '', '', '', '0', '0000-00-00','1', '1');";
mysql_query($sql);
echo registration_form("Rejestracja przebiegła pomyślnie, poczekaj teraz na akceptację administracji!","suc");
}
}
else echo registration_form("Hasło powinno składać się z przynajmniej 4 znaków.","not");
}
else echo registration_form("Login powinien składać się z przynajmniej 4 znaków.","not");
}
else echo registration_form("Podane hasła nie są identyczne.","not");
}
else echo registration_form("Uzupełnij wymagane pola.","not");
}
else echo registration_form("test1");
}
else echo registration_form();
require_once (BASEDIR.STYLE."tpl.end.php");
<file_sep><?php
require_once("maincore.php");
require_once(BASEDIR.STYLE."tpl.start.php");
require_once("lea.core.php");
score_games();
if( session_check() == TRUE AND TRUE == db_get_data("active","lea_players","user_id",$_SESSION['userid']) AND lea_free_date() == FALSE )
{
$player_id = $_SESSION['userid'];
if(isset($_POST['send']))
{
echo challange_activation($player_id,$_POST['challange_id']);
echo game_accepting_process($player_id,$_POST['challange_id']);
}
//lea_clear_stats();
//lea_games_reset_scored();
lea_create_challanges(SEASON);
// echo mysql_num_rows(mysql_query("SELECT * FROM ".DBPREFIX."lea_challanges WHERE `season` = '".SEASON."'"));
echo "<table class='table0 w100'>\n";
echo " <tr><th colspan='6'>Panel gracza ligi 0</th></tr>\n";
echo " <tr><td colspan='6'><h6>Lista aktualnych wyzwań</h6></td></tr>\n";
$i = 0;
$sql = "SELECT * FROM `lea_challanges` WHERE (`player1` = '".$player_id."' OR `player2` = '".$player_id."') AND `actived` = '1' AND `season` = '".SEASON."'";
$query = mysql_query($sql);
while( $lista = mysql_fetch_assoc($query) )
{
$i = $i + 1;
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
echo " <!-- ".$i." -->\n";
echo " <tr".$second_row.">";
echo " <td width='120'>".db_get_data("login","users","id",$lista['player1'])."</td>";
echo " <td width='120'>".db_get_data("login","users","id",$lista['player2'])."</td>";
echo " <td>".substr($lista['nations'],0,9)."</td>";
echo " <td width='80'>".substr($lista['start'],0,10)."</td>";
echo " <td width='80'>".substr($lista['end'],0,10)."</td>";
echo " <td class='lea-challangepw'><a href='lea.msg.php?id=".$lista['id']."'>PW</a></td>";
echo " </tr>\n";
echo " <tr".$second_row.">";
game_accepting($player_id,$lista['id']);
echo "</tr>\n";
}
echo "</table>\n\n";
echo "<br>\n";
echo "<table class='table0 w100'>\n";
echo " <tr><td><h6>Zaaktywuj grę</h6></td></tr>\n";
echo " <tr>\n <td>\n";
echo print_list_of_opponents($player_id,2);
echo " </td>\n </tr>\n";
echo "</table>\n\n";
echo "<br>\n";
echo "<table class='table0 w100'>\n";
echo " <tr><td colspan='3'><h6>Lista gier do rozegrania na bieżący sezon</h6></td></tr>\n";
$i = 0;
$sql = "SELECT * FROM `lea_challanges` WHERE `player1` = '".$player_id."' AND `actived` = '0'";
$query = mysql_query($sql);
while( $lista = mysql_fetch_assoc($query) )
{
$i = $i + 1;
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
echo " <!-- ".$i." -->\n";
echo " <tr".$second_row.">";
echo "<td class='center w50'>".db_get_data("gamenick","users","id",$lista['player1'])."</td>";
echo "<td class='center p50'> vs </td>";
echo "<td class='center w50'>".db_get_data("gamenick","users","id",$lista['player2'])."</td>";
echo "</tr>\n";
}
$sql = "SELECT * FROM `lea_challanges` WHERE `player2` = '".$player_id."' AND `actived` = '0'";
$query = mysql_query($sql);
while( $lista = mysql_fetch_assoc($query) )
{
$i = $i + 1;
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
echo " <!-- ".$i." -->\n";
echo " <tr".$second_row.">";
echo "<td class='center'>".db_get_data("gamenick","users","id",$lista['player1'])."</td>";
echo "<td class='center'> vs </td>";
echo "<td class='center'>".db_get_data("gamenick","users","id",$lista['player2'])."</td>";
echo "</tr>\n";
}
echo "</table>\n\n";
echo "<br>\n";
echo "<table class='table0 w100'>\n";
echo " <tr><td colspan='4'><h6>Lista meczy rozegranych</h6></td></tr>\n";
$i = 0;
$sql = "SELECT * FROM `lea_games` WHERE `player1` = '".$player_id."'";
$query = mysql_query($sql);
while( $lista = mysql_fetch_assoc($query) )
{
$i = $i + 1;
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
echo " <!-- ".$i." -->\n";
echo " <tr".$second_row.">";
echo "<td class='right'>".db_get_data("login","users","id",$lista['winner'])."</td>";
echo "<td class='center'>";
switch($lista['score'])
{
case 1: echo "2:0"; break;
case 2: echo "2:1"; break;
}
if($lista['player1'] == $lista['winner']) echo "<td class='left'>".db_get_data("login","users","id",$lista['player2'])."</td>";
elseif($lista['player2'] == $lista['winner']) echo "<td class='left'>".db_get_data("login","users","id",$lista['player1'])."</td>";
echo "</td>";
echo "<td width='80'>".substr($lista['date'],0,10)."</td>";
echo "</tr>\n";
}
$sql = "SELECT * FROM `lea_games` WHERE `player2` = '".$player_id."'";
$query = mysql_query($sql);
while( $lista = mysql_fetch_assoc($query) )
{
$i = $i + 1;
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
echo " <!-- ".$i." -->\n";
echo " <tr".$second_row.">";
echo "<td class='right'>".db_get_data("login","users","id",$lista['winner'])."</td>";
echo "<td class='center'>";
switch($lista['score'])
{
case 1: echo "2:0"; break;
case 2: echo "2:1"; break;
}
if($lista['player1'] == $lista['winner']) echo "<td class='left'>".db_get_data("login","users","id",$lista['player2'])."</td>";
elseif($lista['player2'] == $lista['winner']) echo "<td class='left'>".db_get_data("login","users","id",$lista['player1'])."</td>";
echo "</td>";
echo "<td width='80'>".substr($lista['date'],0,10)."</td>";
echo "</tr>\n";
}
echo "</table>\n\n";
}
elseif( session_check() == TRUE AND lea_free_date() == FALSE )
{
echo "<div class='not'>";
if(@$_POST['sendlea'] == 'register')
{
echo lea_application_process();
}
else echo "Nie jesteś zapisany w lidze<br>Możesz się wpisać do ligi poprzez poniższy formularz";
echo "</div>\n";
echo lea_application();
}
elseif( lea_free_date() == TRUE )
{
echo "<div class='not'>Dziś liga ma wolne</div>\n";
}
else
{
echo "<div class='not'>Zaloguj się, jeżeli jesteś zapisany w lidze</div>\n";
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "info" AND session_check_usrlevel() >= SPECIAL_LVL )
{
$sql1 = "SELECT * FROM ".DBPREFIX."users";
$sql2 = "SELECT * FROM ".DBPREFIX."reg_countries";
$query1 = mysql_query($sql1);
$query2 = mysql_query($sql2);
if( session_check_rights($_SESSION['login'], "SA") == TRUE )
{
echo " <table class='table0 w100'>\n";
echo " <tr><th colspan='6'>Informacje</th></tr>\n";
echo " <tr><td colspan='6'><h6>Baza danych<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
echo " <tr><td>Host</td><td colspan='5'>".$dbhost."</td></tr>\n";
echo " <tr><td>User</td><td colspan='5'>".$dbuser."</td></tr>\n";
echo " <tr><td>Name</td><td colspan='5'>".$dbname."</td></tr>\n";
echo " <tr><td>PHP v.</td><td colspan='5'>".phpversion()."</td></tr>\n";
}
if( mysql_num_rows($query1)>0 )
{
echo " <tr><td width='170'><h6>Zarejestrowano</h6></td><td width='80'><h6>Język</h6></td><td width='50'><h6>Kod</h6></td><td width='50' class='center'><h6>Flaga</h6></td><td><h6>Ustawiony</h6></td><td><h6>Znakowanie</h6></td></tr>\n";
while( $lang = mysql_fetch_assoc($query2) )
{
echo " <tr>";
echo "<td>".$lang['name']."</td><td>".$lang['lang']."</td><td>".$lang['code']."</td><td class='center'><img src='".IMAGES."flags/small_".$lang['code'].".png'/></td><td>";
if($lang['set']==0)echo "Istnieje";
if($lang['set']==1)echo "Tłumaczenie";
if($lang['set']==9)echo "Główny";
echo "</td><td>".$lang['charset']."</td></tr>\n";
}
}
echo " <tr><td><h6>Typ</h6></td><td colspan='5'><h6>Zajmowane miejsce</h6></td></tr>\n";
echo " <tr><td>DIR *emoty</td><td colspan='5'>".dirsize("images/emots/")."</td></tr>\n";
echo " <tr><td>DIR *avatary</td><td colspan='5'>".dirsize("images/avatars/")."</td></tr>\n";
echo " <tr><td>DIR *pliki</td><td colspan='5'>".dirsize("files/")."</td></tr>\n";
echo " <tr><td>DIR *moduły</td><td colspan='5'>".dirsize("modules/")."</td></tr>\n";
echo " </table>\n";
}
?>
<file_sep><?php
/*
/* Maincore file
/* Created by <NAME>
/* for Polish Revolution clan
/* (c) 2012 All rights reserved
/* Integral part of Polish Revolution's website
/*----------------------------------------------*/
ob_start();
if (preg_match("/maincore.php/i", $_SERVER['PHP_SELF'])) { die(""); }
$level = ""; $i = 0;
while (!file_exists($level."config.php")) {
$level .= "../"; $i++;
if ($i == 5) { die("Config file not found"); }
}
require_once $level."config.php";
if (!isset($dbname)) redirect("install.php");
define("BASEDIR", $level);
define("USER_IP", $_SERVER['REMOTE_ADDR']);
define("SCRIPT_SELF", basename($_SERVER['PHP_SELF']));
define("ADMIN", BASEDIR."administration/");
define("IMAGES", BASEDIR."images/");
define("INCLUDES", BASEDIR."includes/");
define("STYLE", "style/");
define("DATE_SET", date("Y-m-d"));
define("DATETIME", date("Y-m-d H:i:s"));
define("TIMESTAMP", time());
define("SPECIAL_LVL", 101);
// PHP 7+ mysql* functions doesn't exists. should use of mysqli
$dbconnect = @mysql_connect($dbhost, $dbuser, $dbpass);
$dbselect = @mysql_select_db($dbname);
if(!$dbconnect)
die("<div style='font-size:14px;font-weight:bold;align:center;'>Nie nawi±zano po³±czenia z baz± danych, w razie d³u¿szych problemów, spróbuj skontaktowaæ siê z administratorem</div>");
if(!$dbselect)
die("<div style='font-size:14px;font-weight:bold;align:center;'>Nie mo¿na wybraæ potrzebnej bazy danych, w razie d³u¿szych problemów, spróbuj skontaktowaæ siê z administratorem</div>");
$include = glob("includes/inc.*.php");
foreach($include as $file)
{
if(!is_array($file))
{
include_once($file);
}
}
$module = glob("modules/module.*.php");
foreach($module as $file)
{
if(!is_array($file))
{
include_once($file);
}
}
function redirect($location, $script = false) {
if (!$script)
{
header("Location: ".str_replace("&", "&", $location));
exit;
}
else
{
echo "<script type='text/javascript'>document.location.href='".str_replace("&", "&", $location)."'</script>\n";
exit;
}
}
function add_title($value = FALSE)
{
if($value == FALSE) return FALSE;
global $config;
$config['title'].= " - ".$value;
}
function getsettings()
{
global $config;
$sql = "SELECT * FROM `".DBPREFIX."settings` LIMIT 1";
$query = @mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
$config = @mysql_fetch_assoc($query);
}
else
{
echo "<div style='font-size:14px;font-weight:bold;align:center;'>Nie znaleziono danych konfiguracyjnych!</div>";
die();
}
}
getsettings();
session_name(md5($dbhost.$dbname));
session_start();
function custom_menu()
{
$sql = "SELECT * FROM ".DBPREFIX."panels WHERE `display` = '1' ORDER BY `order` ASC";
$query = mysql_query($sql);
$str = "";
if( mysql_num_rows($query)>0 )
{
while($panel = mysql_fetch_assoc($query))
{
$str.= " <div class='section-nav'>".$panel['name']."</div>\n";
$str.= " <div class='section-con'>\n";
$str.= "<!-- ~~~~ -->\n";
$str.= stripslashes($panel['content'])."\n";
$str.= " </div>\n";
}
return $str;
}
}
function custom_calendar()
{
$CountOfDays = array(31,28,31,30,31,30,31,31,30,31,30,31);
if((date('Y')%4) == 0) $CountOfDays[1] = 29;
$m['actual'] = date('n')-1;
$m['name'] = array('Styczeñ','Luty','Marzec','Kwiecieñ','Maj','Czerwiec','Lipiec','Sierpieñ','Wrzesieñ','Pa¼dziernik','Listopad','Grudzieñ');
$d['actual']['week'] = date('w');
$d['actual']['month'] = date('j');
$d['first']['week'] = date('w');
$string = "<!-- Kalendarz -->\n";
$string.= " <div class='section-nav'>".$m['name'][$m['actual']]."</div>\n";
$string.= " <div class='section-con'>\n";
$test = date('j');
while( $test > 7 )
{ $test = $test - 7; }
while( $test != 1 )
{ $d['first']['week'] = $d['first']['week'] - 1;$test = $test-1; if($d['first']['week'] == -1) $d['first']['week'] = 6; }
$string.= " <table class='table0 w100 center'>\n";
$string.= " <tr><td class='calendar-su'>N</td><td class='calendar-th'>P</td><td class='calendar-th'>W</td>\n <td class='calendar-th'>¦</td><td class='calendar-th'>C</td><td class='calendar-th'>P</td><td class='calendar-st'>S</td></tr>\n";
$string.= " <tr>";
for( $i = 0;$i < $d['first']['week'];$i++){ $string.= "<td></td>"; }
$d['printed']['week'] = $d['first']['week'];
for( $i=1;$i<=$CountOfDays[$m['actual']];$i++ )
{
if( $d['printed']['week'] == 7 ){ $d['printed']['week'] = 0;$string.= "</tr>\n <tr>"; }
// printed == important dates in database
if($i<10) $j = "0".$i; else $j = $i;
$sql_date = date("Y")."-".date("m")."-".$j;
$sql = "SELECT * FROM ".DBPREFIX."calendar WHERE `date` = '".$sql_date."' LIMIT 1";
if(mysql_num_rows(mysql_query($sql)) AND $i != $d['actual']['month'])
{
$calendar = mysql_fetch_assoc(mysql_query($sql));
$string.= "<td class='calendar-".$calendar['type']."'><a href='"; if($calendar['href']==0)$string.= "#"; $string.= "' title='".$calendar['name']." - ".$calendar['content']."'>".$i."</a></td>";
}
elseif(mysql_num_rows(mysql_query($sql)) AND $i == $d['actual']['month'])
{
$calendar = mysql_fetch_assoc(mysql_query($sql));
$string.= "<td class='calendar-actual'><a href='"; if($calendar['href']==0)$string.= "#"; $string.= "' title='".$calendar['name']." - ".$calendar['content']."'>".$i."</a></td>";
}
// today == printed
elseif(!mysql_num_rows(mysql_query($sql)) AND $i == $d['actual']['month'] )
{
$string.= "<td class='calendar-actual'>".$i."</td>";
}
// else
if(!mysql_num_rows(mysql_query($sql)) AND $i != $d['actual']['month'])
{
$string.= "<td>".$i."</td>";
}
$d['printed']['week'] = $d['printed']['week']+1;
}
for($i=$d['printed']['week'];$i<7;$i++)
{
$string.= "<td></td>";
}
$string.= "</tr>\n";
$string.= " </table>\n";
$string.= " </div>\n";
return $string;
}
function check_int($value)
{
// custom function about numeric values
if(is_numeric($value)) return TRUE;
else return FALSE;
}
function get_gender($bool)
{
// return a gender from bool value
if($bool == 0) return "Mê¿czyzna";
if($bool == 1) return "Kobieta";
}
function get_time_difference($last_date)
{
// get time difference from unix start
if($last_date != FALSE)
{
$czasostatnio = strtotime($last_date);
$czasteraz = time();
$test = $czasteraz-$czasostatnio;
return $test;
}
else return FALSE;
}
// SESSION FUNCTIONS : START
function session_check()
{
if(isset($_SESSION['logged-in']))
{
if($_SESSION['logged-in'] == 1)
{
$sql = "SELECT `active` FROM ".DBPREFIX."users WHERE `login` = '".$_SESSION['login']."' AND `active` = '1' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$sql = "UPDATE `".DBPREFIX."users` SET `last_date` = '".DATETIME."', `last_ip` = '".USER_IP."' WHERE `login` = '".$_SESSION['login']."' LIMIT 1";
mysql_query($sql);
return TRUE;
}
else
{
$_SESSION['logged-in'] = 0;
session_unset();
return FALSE;
}
}
else
{
$_SESSION['logged-in'] = 0;
session_unset();
return FALSE;
}
}
else return FALSE;
}
function session_check_usrlevel($login = FALSE)
{
if(!isset($_SESSION['login']) && $login == FALSE) return FALSE;
if( $login == FALSE ) $sql = "SELECT `level` FROM ".DBPREFIX."users WHERE `login` = '".$_SESSION['login']."' LIMIT 1";
elseif( !empty($login) ) $sql = "SELECT `level` FROM ".DBPREFIX."users WHERE `login` = '".$login."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0) $test = mysql_fetch_assoc($query);
else return FALSE;
return $test['level'];
}
function session_check_rights($login, $right, $check = FALSE)
{
$sql = "SELECT `rights` FROM `".DBPREFIX."users` WHERE `login` = '".$login."' LIMIT 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$test = explode(".",$data['rights']);
for( $x = 0; $x < count($test); $x++ ){
if( $test[$x] == $right ) return TRUE;
}
return FALSE;
}
// SESSION FUNCTIONS : END
function banlist_verification()
{
// temporary ban
$sql = "SELECT `ban_userid`, `ban_ip`, `ban_reason` FROM `".DBPREFIX."blacklist` WHERE `ban_start` < '".DATETIME."' AND `ban_end` > '".DATETIME."'";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
while($ban = mysql_fetch_assoc($query))
{
if( !empty($ban['ban_reason']) ) $reason = $ban['ban_reason'];
else $reason = "";
if( $_SERVER['REMOTE_ADDR'] == $ban['ban_ip'] )
{
die("<div class='err'><img src='images/icons/replies/stop.png' alt=''/><h3>Zosta³e¶ zbanowany. ".$reason."</h3></div>");
return FALSE;
}
if( !empty($ban['ban_userid']) )
{
$sqltext2 = "SELECT `id` FROM ".DBPREFIX."users WHERE `login` = '".@$_SESSION['login']."'";
$query2 = mysql_query($sqltext2);
$user = mysql_fetch_assoc($query2);
if( @$_GET['logout'] == "yes" ) return FALSE;
if( $user['id'] == $ban['ban_userid'] )
{
die("<div class='err'><img src='images/icons/replies/stop.png' alt=''/><h3>Zosta³e¶ zbanowany. ".$reason."</h3><br/><a href='logout.php?logout=yes'>Wyloguj</a></div>");
return FALSE;
}
}
}
}
// permanent ban
$sql = "SELECT `ban_userid`, `ban_ip`, `ban_reason` FROM `".DBPREFIX."blacklist` WHERE `ban_start` < '".DATETIME."' AND `ban_end` = '0'";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
while($ban = mysql_fetch_row($query))
{
if( !empty($ban['ban_reason']) ) $reason = $ban['ban_reason'];
else $reason = "";
if( $_SERVER['REMOTE_ADDR'] == $ban['ban_ip'] )
{
die("<div class='err'><img src='images/icons/replies/stop.png' alt=''/><h3>Zosta³e¶ zbanowany. ".$reason."</h3></div>");
return FALSE;
}
if( !empty($ban['ban_userid']) )
{
$sqltext2 = "SELECT `id` FROM ".DBPREFIX."users WHERE `login` = '".@$_SESSION['login']."'";
$query2 = mysql_query($sqltext2);
$user = mysql_fetch_assoc($query2);
if( @$_GET['logout'] == "yes" ) return FALSE;
if( $user['id'] == $ban['ban_userid'] )
{
die("<div class='err'><img src='images/icons/replies/stop.png' alt=''/><h3>Zosta³e¶ zbanowany. ".$reason."</h3><br/><a href='logout.php?logout=yes'>Wyloguj</a></div>");
return FALSE;
}
}
}
}
}
function form_rating()
{
$return = "<form class='form-style1' action='' method='post'>\n";
$return.= "<select name='vote' style='width:40px;text-align:center;'>\n";
$return.= "<option value='5'>5</option><option value='4'>4</option><option value='3'>3</option><option value='2'>2</option><option value='1'>1</option>\n";
$return.= "</select>\n";
$return.= "<input type='hidden' name='send' value='vote'><input type='submit' class='submit' style='width:50px;' value='Oceñ'/>\n";
$return.= "</form>\n";
return $return;
}
function form_option_bool($value, $name, $type_true, $type_false)
{
$return = "<input type='radio' name='".$name."' value='1' " ;
if ($value == 1) $return .= "checked='checked'";
$return .= "/> ".$type_true." ";
$return .= "<input type='radio' name='".$name."' value='0' " ;
if ($value == 0)$return .= "checked='checked'";
$return .= "/> ".$type_false." ";
return $return;
}
function form_select_date($name,$start,$end,$date,$width,$value = FALSE)
{
$return = "<select name='".$name."' style='width:".$width.";text-align:center;'>";
for ( $x = $start;$x <= $end;$x++ )
{
if( $date == "m" OR $date == "d" OR $date == "H" OR $date == "i" OR $date == "s" )
{
if( $x < 10 )
$x = "0".$x;
}
$return .= "<option value='".$x."' ";
if(empty($value))
{
if($x == date($date))$return .= "selected='selected'";
}
elseif($value == $x) $return .= "selected='selected'";
$return .= ">".$x."</option>";
}
$return .= "</select> ";
return $return;
}
function form_date_born($name, $start, $end, $date, $width, $value = FALSE)
{
$return = "<select name='".$name."' style='width:".$width.";text-align:center;'>\n";
if( $date == "Y") $return .= "<option value='0000'>------</option>\n";
if( $date == "m" OR $date == "d") $return .= "<option value='00'>---</option>";
for ( $x = $start;$x <= $end;$x++ )
{
if( $date == "m" OR $date == "d" )
{
if( $x < 10 )
$x = "0".$x;
}
$return .= "<option value='".$x."' ";
if(empty($value) AND $x == date($date))
{
$return .= "selected='selected'";
}
elseif($value == $x)
{
$return .= "selected='selected'";
}
$return .= ">".$x."</option>";
}
$return .= "</select>\n";
return $return;
}
function dirsize($path)
{
/* http://php.kedziora.info/?id=22 */
$size = 0;
if($dir = @opendir($path))
{
while(($file = readdir($dir)) !== false)
{
if($file=='..' OR $file=='.')
continue;
elseif( is_dir($path.'/'.$file) )
$size += dirsize($path.'/'.$file);
else
$size += filesize($path.'/'.$file);
}
closedir($dir);
}
else return ("<div class='err'><b>B£¡D!</b> nie uda³o siê otworzyæ folderu <b>".$path."</b></div>\n");
$size = round($size/1048576,2);
return $size." MB";
}
// DATABASE FUNCTIONS AND CUSTOM-PRE-QUERYs
function db_get_data($want,$table,$field,$value,$else=FALSE)
{
$sql = "SELECT * FROM ".DBPREFIX.$table." WHERE `".$field."` = '".$value."' LIMIT 1";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
$result = mysql_fetch_assoc($query);
return $result[$want];
}
else return $else;
}
// ATOM SYSTEM FUNCTIONS
function atom_url($option = 0)
{
// get atom url by PHP PRE VARS
if($option == 0) return "http://".$_SERVER['HTTP_HOST'];
// get atom id from database
if($option == 1)
{
$sql = "SELECT * FROM ".DBPREFIX."atom WHERE `id` = '1' LIMIT 1";
$return = mysql_fetch_assoc(mysql_query($sql));
return $return['atom_url'];
}
}
function atom_convert_league_games($title, $admin, $email)
{
$file_name = "atom-games.xml";
$i = 0;
$date = date("Y-m-d\TH:i:s").substr(date("O"),0,3).":".substr(date("O"),3,2);
$string = "<?xml version='1.0' encoding='iso-8859-2'?>\n";
$string.= "<feed xmlns='http://www.w3.org/2005/Atom'>\n";
$string.= "<title>".htmlspecialchars($title)." | Liga 0</title>\n";
$string.= "<subtitle>Ostatnie gry</subtitle>\n";
$string.= "<author>\n";
$string.= " <name>".htmlspecialchars(db_get_data("login","users","id",$admin))."</name>\n";
if(db_get_data("login","users","id",$email) != FALSE)
{
$string.= " <email>".htmlspecialchars(db_get_data("login","users","id",$email))."</email>\n";
}
$string.= "</author>\n";
$string.= "<updated>".htmlspecialchars($date)."</updated>\n";
$string.= "<id>".htmlspecialchars(atom_url())."/lea.games</id>\n";
$string.= "<link rel='self' href='".htmlspecialchars(atom_url())."/atom-lea.games.xml'/>\n";
$sql = "SELECT * FROM ".DBPREFIX."lea_games WHERE `date` >= '".date("Y-m-d",strtotime("-1 month"))."' ORDER BY `date` DESC";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
while($game = mysql_fetch_assoc($query))
{
if($game['score'] == 1) $score = "2:0";
if($game['score'] == 2) $score = "2:1";
if($game['score'] == 3) $score = "WAL";
$string.= "<entry>\n";
$string.= "<title>".htmlspecialchars(db_get_data("login","users","id",$game['player1']))." vs ".htmlspecialchars(db_get_data("login","users","id",$game['player2']))."</title>\n";
$string.= "<link rel='alternate' type='text/html' href='".htmlspecialchars(atom_url())."/lea.table.php'/>\n";
$string.= "<updated>".htmlspecialchars(date("Y-m-d\TH:i:s",strtotime($game['date'])))."</updated>\n";
$string.= "<author>\n";
$string.= " <name>".htmlspecialchars(db_get_data("login","users","id",$game['score_accept'],"?"))."</name>\n";
$string.= "</author>\n";
$string.= "<id>".htmlspecialchars(atom_url())."/lea.games-".htmlspecialchars($game['id'])."</id>\n";
$string.= "<content type='html'>\n";
$string.= $game['date']." : Winner ".htmlspecialchars(db_get_data("login","users","id",$game['winner']))." by ".$score."\n";
$string.= "</content>\n";
$string.= "</entry>\n";
$i = $i+1;
}
}
$string.= "</feed>\n";
if (is_writable($file_name))
{
// webmade.org
//
// * "a" - Otwiera plik do zapisu Dane bêd± dodawane na koñcu pliku.
// * "a+" - Otwiera plik do odczytu i zapisu. Dane bêd± dodawane na koñcu pliku.
// * "r" - Otwiera plik tylko do odczytu.
// * "r+" - Otwiera plik do odczytu i zapisu. Dane bêd± dodawane na pocz±tku pliku.
// * "w" - Otwiera plik tylko do zapisu i kasuje poprzedni± zawarto¶æ. Je¶li plik nie istnieje zostanie on stworzony.
// * "w+" - Otwiera plik do zapisu i odczytu. Zawarto¶æ pliku zostaje skasowana. Je¶li plik nie istnieje zostanie on stworzony.
if ($file = fopen($file_name, "w"))
{
if(fwrite($file, $string) !== FALSE)
{
return "<b>Liga - Gry:</b> - aktualizacja poprawna. Zapisano wiadomo¶ci: ".$i."";
}
else return "Zapis do pliku siê nie powiód³";
fclose($file);
}
else return "Nie mogê nawi±zaæ po³±czenia z plikiem";
}
else return "Do pliku nie mo¿na dopisaæ informacji lub on nie istnieje";
}
function atom_convert_news($title, $admin, $email)
{
$file_name = "atom-news.xml";
$i = 0;
// $date = date("Y-m-d\TH:i:s").substr(date("O"),0,3).":".substr(date("O"),3,2);
$date = date("c");
$string = "<?xml version='1.0' encoding='iso-8859-2'?>\n";
$string.= "<feed xmlns='http://www.w3.org/2005/Atom'>\n";
$string.= "<title>".htmlspecialchars($title)." | Nowo¶ci</title>\n";
$string.= "<subtitle>Nowe posty</subtitle>\n";
$string.= "<author>\n";
$string.= " <name>".htmlspecialchars(db_get_data("login","users","id",$admin))."</name>\n";
if(db_get_data("login","users","id",$email) != FALSE)
{
$string.= " <email>".htmlspecialchars(db_get_data("login","users","id",$email))."</email>\n";
}
$string.= "</author>\n";
$string.= "<updated>".htmlspecialchars($date)."</updated>\n";
$string.= "<id>".htmlspecialchars(atom_url())."/news</id>\n";
$string.= "<link rel='self' href='".htmlspecialchars(atom_url())."/atom-news.xml'/>\n";
$sql = "SELECT * FROM ".DBPREFIX."news WHERE `date_start` >= '".date("Y-m-d H:i:s",strtotime("-2 months"))."' AND `date_start` <= '".date("Y-m-d H:i:s")."' ORDER BY `date_start` DESC";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
while($news = mysql_fetch_assoc($query))
{
$string.= "<entry>\n";
$string.= "<title>".htmlspecialchars(stripslashes($news['title']))."</title>\n";
$string.= "<link rel='alternate' type='text/html' href='".htmlspecialchars(atom_url()."/news.php?action=read&id=".$news['id'])."'/>\n";
$string.= "<updated>".htmlspecialchars(date("c",strtotime($news['date_start'])))."</updated>\n";
$string.= "<author>\n";
$string.= " <name>".htmlspecialchars(db_get_data("login","users","id",$news['author'],"[brak]"))."</name>\n";
$string.= "</author>\n";
$string.= "<id>".htmlspecialchars(atom_url())."/news-".htmlspecialchars($news['id'])."</id>\n";
$string.= "<content type='html'>\n";
$string.= htmlspecialchars(codes($news['text'].$news['text_ext']))."\n";
$string.= "</content>\n";
$string.= "</entry>\n";
$i = $i+1;
}
}
$string.= "</feed>\n";
if (is_writable($file_name))
{
// webmade.org
//
// * "a" - Otwiera plik do zapisu Dane bêd± dodawane na koñcu pliku.
// * "a+" - Otwiera plik do odczytu i zapisu. Dane bêd± dodawane na koñcu pliku.
// * "r" - Otwiera plik tylko do odczytu.
// * "r+" - Otwiera plik do odczytu i zapisu. Dane bêd± dodawane na pocz±tku pliku.
// * "w" - Otwiera plik tylko do zapisu i kasuje poprzedni± zawarto¶æ. Je¶li plik nie istnieje zostanie on stworzony.
// * "w+" - Otwiera plik do zapisu i odczytu. Zawarto¶æ pliku zostaje skasowana. Je¶li plik nie istnieje zostanie on stworzony.
if ($file = fopen($file_name, "w"))
{
if(fwrite($file, $string) !== FALSE)
{
return "<b>Newsy:</b> - aktualizacja poprawna. Zapisano wiadomo¶ci: ".$i."";
}
else return "Zapis do pliku siê nie powiód³";
fclose($file);
}
else return "Nie mogê nawi±zaæ po³±czenia z plikiem";
}
else return "Do pliku nie mo¿na dopisaæ informacji lub on nie istnieje";
}
function atom_convert_content($string)
{
$string = strip_tags(stripslashes($string));
$string = preg_replace("#\[b\](.*?)\[/b\]#si",'\\1',$string);
$string = preg_replace("#\[i\](.*?)\[/i\]#si",'\\1',$string);
$string = preg_replace("#\[u\](.*?)\[/u\]#si",'\\1',$string);
$string = preg_replace("#\[s\](.*?)\[/s\]#si",'\\1',$string);
$string = preg_replace("#\[size=small\](.*?)\[/size\]#si",'\\1',$string);
$string = preg_replace("#\[url\](.*?)\[/url\]#si", "\\1", $string);
$string = preg_replace("#\[url=(.*?)\](.*?)\[/url\]#si", "\\2", $string);
$string = preg_replace("#\[img\](.*?)\[/img\]#si",'',$string);
$string = preg_replace("#\[code\](.*?)\[/code\]#si",'\\1',$string);
$string = preg_replace("#\[ul\](.*?)\[/ul\]#si",'\\1',$string);
$string = preg_replace("#\[li\](.*?)\[/li\]#si",'\\1',$string);
$string = preg_replace("#\[clan\](.*?)\[/clan\]#si"," \\1 ",$string);
$sql = "SELECT * FROM `".DBPREFIX."reg_countries`";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0)
{
while($lang = mysql_fetch_assoc($query))
{
$string = str_replace("[lang]".$lang['code']."[/lang]","",$string);
}
}
return htmlspecialchars($string);
}
session_check();
banlist_verification();
/*
if($config['disabled'] == TRUE AND session_check_usrlevel() < SPECIAL_LVL)
{
echo "<div style='font-size:14px;font-weight:bold;align:center;'>".stripslashes($config['disabled_text'])."</div>";
die();
}
*/
<file_sep><?php
require_once "maincore.php";
require_once (BASEDIR.STYLE."tpl.start.php");
log_user_out();
redirect($config['mainpage']);
require_once (BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "calendar" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// session check
session_check();
// fixing last item id & vars
$sql = "SELECT `id` FROM `".DBPREFIX."calendar` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// new item
if( @$_POST['send'] == "new" )
{
$new['id'] = $last_id+1;
$new['date'] = $_POST['y']."-".$_POST['m']."-".$_POST['d'];
$new['name'] = addslashes($_POST['form2']);
$new['cont'] = addslashes($_POST['form3']);
$new['href'] = addslashes($_POST['form4']);
$new['type'] = addslashes($_POST['form5']);
if( empty($_POST['form2']) OR empty($_POST['form3']) OR !isset($_POST['form4']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "INSERT INTO `".DBPREFIX."calendar` VALUES('".$new['id']."','".$new['date']."','".$new['name']."','".$new['cont']."','".$new['href']."','".$new['type']."');";
mysql_query($sql);
$result = "Dodano poprawnie do bazy";
}
}
// edit item
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."calendar` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$y = substr($data['date'],0,4); $m = substr($data['date'],5,2);
$d = substr($data['date'],8,2);
$edit['name'] = stripslashes($data['name']);
$edit['cont'] = stripslashes($data['content']);
$edit['href'] = stripslashes($data['href']);
$edit['type'] = stripslashes($data['type']);
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
// update item
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE)
{
$upt['date'] = $_POST['y']."-".$_POST['m']."-".$_POST['d'];
$upt['name'] = addslashes($_POST['form2']);
$upt['cont'] = addslashes($_POST['form3']);
$upt['href'] = addslashes($_POST['form4']);
$upt['type'] = addslashes($_POST['form5']);
if( empty($_POST['form2']) OR empty($_POST['form3']) OR !isset($_POST['form4']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "UPDATE `".DBPREFIX."calendar` SET `date` = '".$upt['date']."', `name` = '".$upt['name']."', `content` = '".$upt['cont']."', `href` = '".$upt['href']."', `type` = '".$upt['type']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Dane zostały zaaktualizowane";
}
}
mysql_query($sql);
}
// fixing date-time
if(!isset($y) OR !isset($m) OR !isset($d)){ $y = date("Y"); $m = date("m"); $d = date("d"); }
// finish
if( !empty($edit['code']) ) $table_info = "Edytujesz: ".$edit['code']; else $table_info = "Nowa data";
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie kalendarzem</th></tr>\n";
echo "<tr><td colspan='2' align='left'><h6>".$table_info."<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Data</td><td>";
echo form_select_date("y",2010,2050,"Y",60,$y);
echo form_select_date("m",1,12,"m",40,$m);
echo form_select_date("d",1,31,"d",40,$d);
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Nazwa</td><td><input class='text' type='text' name='form2' value='".@$edit['name']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Opis</td><td><input class='text' type='text' name='form3' value='".@$edit['cont']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Odnośnik</td><td><input class='text' type='text' name='form4' value='".@$edit['href']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Typ</td><td>\n";
echo "<select class='select' name='form5' style='width:50px;'>\n";
echo "<option value='1'"; if( @$edit['type'] == 1 ) echo " selected='selected'"; echo ">1</option>\n";
echo "<option value='2'"; if( @$edit['type'] == 2 ) echo " selected='selected'"; echo ">2</option>\n";
echo "<option value='3'"; if( @$edit['type'] == 3 ) echo " selected='selected'"; echo ">3</option>\n";
echo "</select>\n";
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "<tr><td colspan='2'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<form action='' method='post'>\n";
echo "<td align='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT * FROM `".DBPREFIX."calendar` ORDER BY `name` ASC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <select name='choosed_id' class='select'>\n";
while($date = mysql_fetch_assoc($query))
{
echo " <option value='".$date['id']."'>".$date['date']." | ".$date['name']."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n";
}
?>
<file_sep><?php
require_once("maincore.php");
require_once(BASEDIR.STYLE."tpl.start.php");
require_once("lea.core.php");
score_games();
$sql = "SELECT * FROM `lea_players` WHERE `active` = '1' ORDER BY `score` DESC";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
// echo "<h2>Tabela ligowa</h2>\n";
echo "<table class='table0 w100'>\n";
echo " <tr><th class='lea-lp'>Poz.</th><th class='lea-country'>Kraj</th><th class='lea-nick'>Nick</th><th class='lea-clan'>Klan</th><th class='lea-score'>Punkty</th><th class='lea-games'>Mecze</th><th class='lea-perc'>Skt. [%]</th><th>W/G</th></tr>\n";
$i = 1;
while($player = mysql_fetch_assoc($query))
{
$sql2 = "SELECT `id`, `gamenick`, `clan`, `country` FROM `users` WHERE `id` = '".$player['user_id']."' LIMIT 1";
$query2 = mysql_query($sql2);
$user = mysql_fetch_assoc($query2);
$sql3 = "SELECT `winner`, `score` FROM `lea_games` WHERE `player1` = '".$player['user_id']."' OR `player2` = '".$player['user_id']."'";
$query3 = mysql_query($sql3);
$win = 0;
$los = 0;
$games['total'] = mysql_num_rows($query3);
while($score = mysql_fetch_assoc($query3))
{
if(1 == 1)
{
if($score['winner'] == $player['user_id'])
{
switch ($score['score'])
{
case 1:
$win = $win+2;
break;
case 2:
$win = $win+2;
$los = $los+1;
break;
}
}
else
{
switch ($score['score'])
{
case 1:
$los = $los+2;
break;
case 2:
$win = $win+1;
$los = $los+2;
break;
}
}
}
else $games['total'] = $games['total']-1;
}
if( $win+$los != 0 ) $games['acc'] = ($win/($win+$los))*100;
else $games['acc'] = "n/d";
$second_row = "";
if( $i%2 == 0 ) $second_row = " class='row2'";
echo " <tr".$second_row."><td class='center'>".$i."</td><td class='center'><img src='images/flags/small_".$user['country'].".png' title='".db_get_data("name","reg_countries","code",$user['country'])."' border='0'/></td><td class='center'><a href='lea.players.php?p_id=".$user['id']."'>".$user['gamenick']."</a></td><td class='center'><img src='images/clans/".$user['clan'].".gif' alt='".$user['clan']."'/></td><td class='center'>".$player['score']."</td></td><td class='center'>".$games['total']."</td></td><td class='center'>".substr($games['acc'],0,5)."</td><td class='center'>".$win."/".($win+$los)."</td></tr>\n";
$i = $i+1;
}
echo "</table>";
}
else echo "<div class='not'>Liga aktualnie nie działa</div>\n";
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "news" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
// fixing last item id
$sql = "SELECT `id` FROM `".DBPREFIX."news` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// fixing date-time
$ys = date("Y"); $ms = date("m"); $ds = date("d");
$hs = "00"; $is = "00"; $ss = "00";
$ye = date("Y",strtotime("+1 years")); $me = date("m"); $de = date("d");
$he = "00"; $ie = "00"; $se = "00";
// fixing off
// news:send new one
if( @$_POST['send'] == "new" )
{
$new['id'] = $last_id+1;
$new['title'] = htmlspecialchars(addslashes($_POST['form1']));
$new['text'] = addslashes($_POST['form2']);
$new['ext'] = addslashes($_POST['form3']);
$new['author'] = $_POST['author'];
$new['lang'] = htmlspecialchars(addslashes($_POST['form4']));
$new['date_start'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds']." ".$_POST['hs'].":".$_POST['is'].":".$_POST['ss'];
$new['date_end'] = $_POST['ye']."-".$_POST['me']."-".$_POST['de']." ".$_POST['he'].":".$_POST['ie'].":".$_POST['se'];
@$new['comment'] = $_POST['form5'];
@$new['rating'] = $_POST['form6'];
if( empty($_POST['form1']) OR empty($_POST['form2']) ) $result = "Nie podano tytułu lub podstawowej treści";
else
{
$sql = "INSERT INTO `".DBPREFIX."news` VALUES('".$new['id']."','".$new['title']."','".$new['text']."','".$new['ext']."','".$new['author']."','".$new['lang']."','".$new['date_start']."','".$new['date_end']."','".$new['comment']."','".$new['rating']."');";
mysql_query($sql);
$result = "News dodany";
}
}
// news:choosed to edit
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."news` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( @mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['title'] = stripslashes($data['title']);
$edit['text'] = stripslashes($data['text']);
$edit['ext'] = stripslashes($data['text_ext']);
$edit['lang'] = stripslashes($data['languages']);
@$edit['comment'] = $data['allow_comment'];
@$edit['rating'] = $data['allow_rating'];
$ys = substr($data['date_start'],0,4); $ms = substr($data['date_start'],5,2);
$ds = substr($data['date_start'],8,2); $hs = substr($data['date_start'],11,4);
$is = substr($data['date_start'],14,2); $ss = substr($data['date_start'],17,2);
$ye = substr($data['date_end'],0,4); $me = substr($data['date_end'],5,2);
$de = substr($data['date_end'],8,2); $he = substr($data['date_end'],11,4);
$ie = substr($data['date_end'],14,2); $se = substr($data['date_end'],17,2);
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
// news:update
if( @$_POST['send'] == "update" )
{
if( @$_POST['delete'] == 1 AND check_int($_POST['edited_id']) == TRUE)
{
$sql = "DELETE FROM `".DBPREFIX."news` WHERE `id` = '".$_POST['edited_id']."' LIMIT 1";
$result = "News został usunięty";
}
elseif( check_int($_POST['edited_id']) == TRUE )
{
$upt['title'] = htmlspecialchars(addslashes($_POST['form1']));
$upt['text'] = addslashes($_POST['form2']);
$upt['ext'] = addslashes($_POST['form3']);
$upt['lang'] = htmlspecialchars($_POST['form4']);
$upt['date_start'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds']." ".$_POST['hs'].":".$_POST['is'].":".$_POST['ss'];
$upt['date_end'] = $_POST['ye']."-".$_POST['me']."-".$_POST['de']." ".$_POST['he'].":".$_POST['ie'].":".$_POST['se'];
@$upt['comment'] = $_POST['form5'];
@$upt['rating'] = $_POST['form6'];
if( empty($_POST['form1']) OR empty($_POST['form2']) ) $result = "Nie podano tytułu lub podstawowej treści";
else
{
$sql = "UPDATE `".DBPREFIX."news` SET `title` = '".$upt['title']."', `text` = '".$upt['text']."', `text_ext` = '".$upt['ext']."', `languages` = '".$upt['lang']."', `date_start` = '".$upt['date_start']."', `date_end` = '".$upt['date_end']."', `allow_comment` = '".$upt['comment']."', `allow_rating` = '".$upt['rating']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "News został zaaktualizowany";
}
}
mysql_query($sql);
}
if(empty($_POST['send'])) $_POST['send'] = "new";
// form
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr>\n<th colspan='2'>Zarządzanie nowinkami</th>\n</tr>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>".$edit['title']."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Data ukazania się</td><td>";
echo form_select_date("ys",2005,2090,"Y",60,$ys);
echo form_select_date("ms",1,12,"m",40,$ms);
echo form_select_date("ds",1,31,"d",40,$ds);
echo " : ";
echo form_select_date("hs",0,23,"H",40,$hs);
echo form_select_date("is",0,59,"i",40,$is);
echo form_select_date("ss",0,59,"s",40,$ss);
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Data archiwizacji</td><td>";
echo form_select_date("ye",2010,2100,"Y",60,$ye);
echo form_select_date("me",1,12,"m",40,$me);
echo form_select_date("de",1,31,"d",40,$de);
echo " : ";
echo form_select_date("he",0,23,"H",40,$he);
echo form_select_date("ie",0,59,"i",40,$ie);
echo form_select_date("se",0,59,"s",40,$se);
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Tytuł</td><td><input class='text' type='text' name='form1' value='".@$edit['title']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td valign='top'>Tekst</td><td><textarea class='textarea' name='form2'>".@$edit['text']."</textarea></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td valign='top'><a style='cursor: pointer' onclick=rozwin('id-ext')>Rozszerzenie</a></td><td><textarea id='id-ext' class='h' class='textarea' name='form3'>".@$edit['ext']."</textarea></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Języki</td><td><input class='text' type='text' name='form4' value='".@$edit['lang']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Zezwól na komentarze</td><td><input type=checkbox name='form5'"; if( @$edit['comment'] == 1 ) echo " checked='checked'"; echo " value='1'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Zezwól na ocenianie</td><td><input type=checkbox name='form6'"; if( @$edit['rating'] == 1 ) echo " checked='checked'"; echo " value='1'/></td>";
echo "</tr>\n";
if( @$_POST['send'] == "edit" )
{
echo "<tr>";
echo "<td>Usuń</td><td><input type=checkbox name='delete' value='1' /></td>";
echo "</tr>\n";
}
echo "<tr>";
echo "<td align='right'>BB Code</td><td><img src='images/icons/replies/yes.png'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { echo "<input type='hidden' name='author' value='".$_SESSION['userid']."'/>"; $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
// form:list of existing items
echo "<form action='' method='post'>\n";
echo "<tr><td colspan='2' align='left'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<td align='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT `id`,`date_start`,`title` FROM `".DBPREFIX."news` ORDER BY `date_start` DESC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <select name='choosed_id' class='select'>\n";
while($art = mysql_fetch_row($query))
{
echo " <option value='".$art[0]."'>[ ".$art[0]." ] ".$art[1]." - ".$art[2]."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</tr>\n";
echo "</table>\n";
echo "</form>\n\n";
}
?>
<file_sep><?php
require_once "maincore.php";
$actual = "download.php";
add_title("Download");
require_once (BASEDIR.STYLE."tpl.start.php");
echo "<h2>Download</h2>\n";
if( check_int($_GET['id']) == TRUE )
{
$sql = "SELECT `name`, `url`, `direct` FROM ".DBPREFIX."files WHERE `id` = '".$_GET['id']."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$file = mysql_fetch_assoc($query);
if(file_exists("files/".$file['url'])) redirect("files/".$file['url']);
else
{
echo "<div class='err'>";
echo "Brak danego pliku.";
echo "</div>\n";
}
}
}
require_once (BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
if( $_GET['option'] == "links-cat" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
// fixing last item id
$sql = "SELECT `id` FROM `".DBPREFIX."links_cat` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// add item
if( @$_POST['send'] == "new" AND check_int($_POST['form2']) == TRUE)
{
$new['id'] = $last_id+1;
$new['name'] = addslashes($_POST['form1']);
$new['order'] = $_POST['form2'];
$sql = "INSERT INTO `".DBPREFIX."links_cat` VALUES('".$new['id']."','".$new['name']."','".$new['order']."');";
mysql_query($sql);
$result = "Kategoria została dodana";
}
// edit item
if( @$_POST['send'] == "edit" AND check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."links_cat` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['name'] = stripslashes($data['name']);
$edit['order'] = $data['order'];
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
// update item
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE AND check_int($_POST['form2']) == TRUE )
{
$upt['name'] = addslashes($_POST['form1']);
$upt['order'] = $_POST['form2'];
$sql = "UPDATE `".DBPREFIX."links_cat` SET `name` = '".$upt['name']."', `order` = '".$upt['order']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Kategoria została zaaktualizowana";
}
mysql_query($sql);
}
if( @strlen($edit['name']) > 50 ) $table_info = substr($edit['name'],0,50)."...";
elseif( isset( $edit['name']) ) $table_info = $edit['name'];
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie kategoriami łączy</td></tr>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>".$table_info."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Nazwa</td><td><input class='text' type='text' name='form1' value='".@$edit['name']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kolejność</td><td><input class='p50' type='text' name='form2' value='".@$edit['order']."'/><span class='text-tiny'> Jeśli == 0 to nie zostanie pokazane</span></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "<tr><td colspan='2' align='left'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<form action='' method='post'>\n";
echo "<tr>\n";
echo "<td class='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT * FROM `".DBPREFIX."links_cat` ORDER BY `id` ASC";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 );
{
echo " <select name='choosed_id' class='select'>\n";
while($cat = mysql_fetch_assoc($query))
{
echo " <option value='".$cat['id']."'>[".$cat['order']."] :: ".$cat['name']."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
if( $_GET['option'] == "articles" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
// fixing last item id
$sql = "SELECT `id` FROM `".DBPREFIX."articles` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// fixing off
// article:send new one
if(@$_POST['send'] == "new")
{
$new['id'] = $last_id+1;
$new['title'] = htmlspecialchars(addslashes($_POST['form1']));
$new['content'] = addslashes($_POST['form2']);
$new['author'] = htmlspecialchars($_SESSION['userid']);
$new['date_start'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds']." ".$_POST['hs'].":".$_POST['is'].":".$_POST['ss'];
@$new['comment'] = $_POST['form3'];
@$new['rating'] = $_POST['form4'];
if( empty($_POST['form1']) OR empty($_POST['form2']) ) $result = "Nie podano tytułu lub podstawowej treści artykułu";
else
{
$sql = "INSERT INTO `".DBPREFIX."articles` VALUES('".$new['id']."','".$new['title']."','".$new['content']."','".$new['author']."','".$new['date_start']."','0','".$new['comment']."','".$new['rating']."');";
mysql_query($sql);
$result = "Artykuł został dodany";
}
}
// article:choosed to edit
if( @$_POST['send'] == "edit" AND @check_int($_POST['choosed_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."articles` WHERE `id` = '".$_POST['choosed_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['choosed_id'];
$edit['title'] = stripslashes($data['title']);
$edit['content'] = stripslashes($data['content']);
@$edit['comment'] = $data['allow_comment'];
@$edit['rating'] = $data['allow_rating'];
$ys = substr($data['date_start'],0,4); $ms = substr($data['date_start'],5,2);
$ds = substr($data['date_start'],8,2); $hs = substr($data['date_start'],11,4);
$is = substr($data['date_start'],14,2); $ss = substr($data['date_start'],17,2);
}
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
// article:update
if( @$_POST['send'] == "update" )
{
if( @$_POST['delete'] == 1 AND check_int($_POST['edited_id']) == TRUE )
{
$sql = "DELETE FROM `".DBPREFIX."articles` WHERE `id` = '".$_POST['edited_id']."' LIMIT 1";
$result = "Artykuł został usunięty";
}
elseif( check_int($_POST['edited_id']) == TRUE )
{
$upt['title'] = htmlspecialchars(addslashes($_POST['form1']));
$upt['content'] = addslashes($_POST['form2']);
$upt['date_start'] = $_POST['ys']."-".$_POST['ms']."-".$_POST['ds']." ".$_POST['hs'].":".$_POST['is'].":".$_POST['ss'];
@$upt['comment'] = $_POST['form3'];
@$upt['rating'] = $_POST['form4'];
if( empty($_POST['form1']) OR empty($_POST['form2']) ) $result = "Nie podano tytułu lub podstawowej treści artykułu";
else
{
$sql = "UPDATE `".DBPREFIX."articles` SET `title` = '".$upt['title']."', `content` = '".$upt['content']."', `date_start` = '".$upt['date_start']."', `allow_comment` = '".$upt['comment']."', `allow_rating` = '".$upt['rating']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Artykuł został zaaktualizowany";
}
}
mysql_query($sql);
}
// fixing date-time
$ys = date("Y"); $ms = date("m"); $ds = date("d");
$hs = "00"; $is = "00"; $ss = "00";
if(empty($_POST['send'])) $_POST['send'] = "new";
// form
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie artykułami</th></h2>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>article.php?id=".$edit['id']."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Data ukazania się</td><td>";
echo form_select_date("ys",2005,2090,"Y",60,$ys);
echo form_select_date("ms",1,12,"m",40,$ms);
echo form_select_date("ds",1,31,"d",40,$ds);
echo " : ";
echo form_select_date("hs",0,23,"H",40,$hs);
echo form_select_date("is",0,59,"i",40,$is);
echo form_select_date("ss",0,59,"s",40,$ss);
echo "</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Tytuł</td><td><input class='text' type='text' name='form1' value='".@$edit['title']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td valign='top'>Zawartość</td><td><textarea class='textarea' name='form2'>".@$edit['content']."</textarea></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Zezwól na komentarze</td><td><input type=checkbox name='form3'"; if( @$edit['comment'] == 1 ) echo " checked='checked'"; echo " value='1'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Zezwól na ocenianie</td><td><input type=checkbox name='form4'"; if( @$edit['rating'] == 1 ) echo " checked='checked'"; echo " value='1'/></td>";
echo "</tr>\n";
if( @$_POST['send'] == "edit" )
{
echo "<tr>";
echo "<td>Usuń</td><td><input type=checkbox name='delete' value='1' /></td>";
echo "</tr>\n";
}
echo "<tr>";
echo "<td align='right'>HTML</td><td><img src='images/icons/replies/yes.png'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { echo "<input type='hidden' name='author' value='".$_SESSION['userid']."'/>"; $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".@$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
// form:list of existing items
echo "<form action='' method='post'>\n";
echo "<tr><td colspan='2' align='left'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<td align='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT `id`,`date_start`,`title` FROM `".DBPREFIX."articles` ORDER BY `date_start` DESC";
$query = mysql_query($sql);
if(mysql_num_rows($query)>0);
{
echo " <select name='choosed_id' class='select'>\n";
while($art = mysql_fetch_row($query))
{
echo " <option value='".$art[0]."'>[ ".$art[0]." ] ".$art[1]." - ".stripslashes($art[2])."</option>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
}
?>
<file_sep><?php
require_once("maincore.php");
$actual = "faq.php";
add_title("FAQ");
require_once(BASEDIR.STYLE."tpl.start.php");
echo "<h2>FAQ</h2>\n";
$sql = "SELECT * FROM ".DBPREFIX."faq ORDER BY `order`";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
while($faq = mysql_fetch_assoc($query))
{
echo "<div class='faq-question'><b>".stripslashes($faq['question'])."</b></div>\n";
echo "<div class='faq-answer'>".stripslashes($faq['answer'])."</div>\n";
}
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
require_once("maincore.php");
redirect($config['mainpage']);
?>
<file_sep><?php
if( $_GET['option'] == "settings" AND session_check_usrlevel() >= SPECIAL_LVL )
{
session_check();
// uptade the settings: meta ; options ; administration
if(@$_POST['send'] == "m")
{
$v1 = addslashes($_POST['m1']);
$v2 = addslashes($_POST['m2']);
$v3 = addslashes($_POST['m3']);
$v4 = addslashes($_POST['m4']);
$v5 = addslashes($_POST['m5']);
$v6 = addslashes($_POST['m6']);
$v7 = addslashes($_POST['m7']);
$sql = "UPDATE `".DBPREFIX."settings` SET `clanname` = '".$v1."', `title` = '".$v2."', `keys` = '".$v3."', `desc` = '".$v4."', `footer` = '".$v5."', `header_text_main` = '".$v6."', `header_text_sub` = '".$v7."' LIMIT 1";
mysql_query($sql);
$result = "Zaaktualizowano ustawienia metadane portalu";
}
if(@$_POST['send'] == "o")
{
$v1 = addslashes($_POST['o1']);
$v2 = addslashes($_POST['o2']);
$v3 = addslashes($_POST['o3']);
$v4 = $_POST['o4'];
$v5 = $_POST['o5'];
$v6 = addslashes($_POST['o6']);
$v7 = $_POST['o7'];
$v8 = $_POST['o8'];
$v9 = $_POST['o9'];
$v10 = addslashes($_POST['o10']);
$sql = "UPDATE `".DBPREFIX."settings` SET `mainpage` = '".$v1."', `logoimage` = '".$v2."', `fav_ico` = '".$v3."', `log_sys` = '".$v4."', `forum_sys` = '".$v5."', `forum_link` = '".$v6."', `banner_sys` = '".$v7."', `antyflood` = '".$v8."', `disabled` = '".$v9."', `disabled_text` = '".$v10."' LIMIT 1";
mysql_query($sql);
$result = "Zaaktualizowano ustawienia ogólne";
}
if(@$_POST['send'] == "a")
{
if(!empty($_POST['a1']) AND check_int($_POST['a1']) == TRUE)
{
$v1 = addslashes($_POST['a1']);
}
$sql = "SELECT `id` FROM `".DBPREFIX."users` WHERE `id` = '".$v1."' LIMIT 1";
if(mysql_num_rows(mysql_query($sql)) == 0)
{
$result = "<strong>Błąd: </strong> Nie ma takiego użytkownika";
}
else
{
$v2 = addslashes($_POST['a2']);
$sql = "UPDATE `".DBPREFIX."settings` SET `headadmin` = '".$v1."', `email` = '".$v2."' LIMIT 1";
mysql_query($sql);
$result = "Zaaktualizowano ustawienia administracji";
}
}
$sql = "SELECT * FROM `".DBPREFIX."settings` LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
// fixing vars
$data['clanname'] = stripslashes($data['clanname']);
$data['title'] = stripslashes($data['title']);
@$data['keys'] = stripslashes($data['keys']);
@$data['desc'] = stripslashes($data['desc']);
$data['footer'] = stripslashes($data['footer']);
$data['header_text_main'] = stripslashes($data['header_text_main']);
@$data['header_text_sub'] = stripslashes($data['header_text_sub']);
$data['mainpage'] = stripslashes($data['mainpage']);
@$data['logoimage'] = stripslashes($data['logoimage']);
@$data['favico'] = stripslashes($data['favico']);
@$data['forum_link'] = stripslashes($data['forum_link']);
@$data['disabled_text'] = stripslashes($data['disabled_text']);
// set list of admins
$selected = FALSE;
$disabled = FALSE;
if( $_SESSION['userid'] != $data['headadmin'] ) $disabled = " disabled='disabled'";
$list = "<select name='a1' class='w75'".$disabled.">";
$sql = "SELECT `id`, `login` FROM ".DBPREFIX."users";
$query = mysql_query($sql);
while($test = mysql_fetch_assoc($query))
{
if( session_check_rights($test['login'],"SA") == TRUE )
{
$selected = FALSE;
if( $test['id'] == $data['headadmin'] ) $selected = " selected='selected'";
$list.= "<option value='".$test['id']."'".$selected.">".$test['login']."</option>";
}
}
$list.= "</select>";
// fixing: off
echo "<form class='form-style2' action='' method='post'>\n";
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='3'>Ustawienia portalu</th></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td colspan='3'><h6>Metadane<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></th>";
echo "</tr>\n";
echo "<tr><td width='150'>Nazwa klanu</td><td colspan='2'><input class='text' type='text' name='m1' value='".$data['clanname']."'/></td></tr>\n";
echo "<tr><td width='150'>Tytuł strony</td><td colspan='2'><input class='text' type='text' name='m2' value='".$data['title']."'/></td></tr>\n";
echo "<tr><td width='150'>Słowa kluczowe</td><td colspan='2'><input class='text' type='text' name='m3' value='".$data['keys']."'/></td></tr>\n";
echo "<tr><td width='150'>Opis strony</td><td colspan='2'><input class='text' type='text' name='m4' value='".$data['desc']."'/></td></tr>\n";
echo "<tr><td width='150'>Stopka</td><td colspan='2'><input class='text' type='text' name='m5' value='".$data['footer']."'/></td></tr>\n";
echo "<tr><td width='150'>Tekst #1</td><td width='200'><input class='w100' type='text' name='m6' value='".$data['header_text_main']."'/></td><td><span class='text-tiny'>// Tekst główny logo</span></td></tr>\n";
echo "<tr><td width='150'>Tekst #2</td><td width='200'><input class='w100' type='text' name='m7' value='".$data['header_text_sub']."'/></td><td><span class='text-tiny'>// Tekst wyświetlany pod głównym napisem na logo</span></td></tr>\n";
echo "<tr><td width='150'><input type='hidden' name='send' value='m'/></td><td width='200'><input class='submit' type='submit' value='Aktualizuj'/></td><td> </td>\n";
echo "</form></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td colspan='3'><h6>Ogólnie</h6></th>";
echo "</tr>\n";
echo "<tr><td width='150'>Strona główna</td><td width='200'><input class='w100' type='text' name='o1' value='".$data['mainpage']."'/></td><td> </td></tr>\n";
echo "<tr><td width='150'>Obrazek logo</td><td width='200'><input class='w100' type='text' name='o2' value='".$data['logoimage']."'/></td><td> </td></tr>\n";
echo "<tr><td width='150'>Ikona strony</td><td width='200'><input class='w100' type='text' name='o3' value='".$data['favico']."'/></td><td> </td></tr>\n";
echo "<tr><td width='150'>System logowania</td><td width='200'>".form_option_bool($data['log_sys'],"o4","Tak","Nie")."</td><td><span class='text-tiny'>// Jeśli wyłączone, nie wylogowywuj się, w przeciwnym wypadku stracisz możliwośc zalogowania się</span></td></tr>\n";
echo "<tr><td width='150'>System forum</td><td width='200'>".form_option_bool($data['forum_sys'],"o5","Tak","Nie")."</td><td><span class='text-tiny'>// Korzystanie z wbudowanego w portal systemu forum</span></td></tr>\n";
echo "<tr><td width='150'>Adres forum zewnętrznego</td><td width='200'><input class='w100' type='text' name='o6' value='".$data['forum_link']."'/></td><td><span class='text-tiny'>// Jeśli wbudowane forum zostało wyłączone</span></td></tr>\n";
echo "<tr><td width='150'>Bannery</td><td width='200'>".form_option_bool($data['banner_sys'],"o7","Tak","Nie")."</td><td> </td></tr>\n";
echo "<tr><td width='150'>SPAM Protector</td><td width='200'><input class='w30' type='text' name='o8' value='".$data['antyflood']."'/></td><td><span class='text-tiny'>// Odstęp w sekundach pomiędzy komentarzami jednego użytkownika</span></td></tr>\n";
echo "<tr><td width='150'>Wyłącz system</td><td width='200'>".form_option_bool($data['disabled'],"o9","Tak","Nie")."</td><td> </td></tr>\n";
echo "<tr><td width='150'>Tekst</td><td width='200'><input class='w100' type='text' name='o10' value='".$data['disabled_text']."'/></td><td><span class='text-tiny'>// Jeśli wbudowane system wyłączony</span></td></tr>\n";
echo "<tr><td width='150'><input type='hidden' name='send' value='o'/></td><td width='200'><input class='submit' type='submit' value='Aktualizuj'/></td><td> </td>\n";
echo "</form></tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td colspan='3'><h6>Administracja</h6></th>";
echo "</tr>\n";
if( $_SESSION['userid'] != $data['headadmin'] ) $disable = "disabled='disabled' ";
echo "<tr><td width='150'>Główny administrator</td><td colspan='2'>".$list."</td></tr>\n";
echo "<tr><td width='150'>Adres e-Mail dla strony</td><td colspan='2'><input class='w75' type='text' name='a2' value='".$data['email']."'/></td></tr>\n";
echo "<tr><td width='150'><input type='hidden' name='send' value='a'/></td><td colspan='2'><input class='submit' type='submit' value='Aktualizuj'/></td>\n";
echo "</form></tr>\n";
echo "</table>\n";
}
<file_sep><?php
function check_current($item,$actual)
{
if($item == $actual) return " class='current-page'";
}
echo "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>\n";
echo "<html xmlns='http://www.w3.org/1999/xhtml' lang='pl' xml:lang='pl'>\n";
echo "<head>\n";
echo " <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-2' />\n";
echo " <meta name='description' content='".$config['desc']."' />\n";
echo " <meta name='keywords' content='".$config['keys']."' />\n";
echo " <meta name='author' content='".$config['author']."' />\n";
echo " <meta name='robots' content='index, nofollow' />\n";
echo " <title>".$config['title']."</title>\n";
echo " <link rel='stylesheet' href='style/style.css' type='text/css' />\n";
echo " <link rel='stylesheet' href='style/style.lea.css' type='text/css' />\n";
echo " <link rel='shortcut icon' href='".$config['fav_ico']."' />\n";
echo "</head>\n";
echo "<body>\n";
echo "\n";
echo "<div id='header-super'>\n";
echo " <div class='wrap-center'>\n";
echo " <div id='title'>\n";
echo " <h1>".$config['header_text_main']."</h1>\n";
echo " <p class='textsub'>".$config['header_text_sub']."</p>\n";
echo " </div>\n";
echo " </div>\n";
echo "</div>\n";
echo "\n";
echo "<div id='header-sub'>\n";
echo " <div class='wrap-center'>\n";
echo " <div id='navigation-horizontal'>\n";
echo " <ul>\n";
echo " <li".check_current($config['mainpage'],@$actual)."><a href='index.php'>Strona glˇwna</a></li>\n";
echo " <li".check_current("contact.php",@$actual)."><a href='contact.php'>Kontakt</a></li>\n";
echo " <li".check_current("faq.php",@$actual)."><a href='faq.php'>FAQ</a></li>\n";
echo " <li".check_current("links.php",@$actual)."><a href='links.php'>Linki</a></li>\n";
echo " <li".check_current("download.php",@$actual)."><a href='download.php'>Download</a></li>\n";
echo " <li".check_current("forum.php",@$actual)."><a href='";
if($config['forum_sys'] == 1) echo "forum.php";
else echo $config['forum_link']; echo "'>Forum</a></li>\n";
echo " </ul>\n";
echo " </div>\n";
echo " </div>\n";
echo " <div id='line'></div>\n";
echo "</div>\n";
echo "\n";
echo "<div id='content-area'>\n";
echo " <div class='wrap-center'>\n";
if(!isset($wide_screen) OR $wide_screen == 0)
{
echo " <div id='side-bar'>\n";
require_once("tpl.side.php");
echo " <br>\n";
echo " </div>\n";
echo " <div id='main-bar'>\n";
}
else
{
echo " <div id='wide-bar'>\n";
}
echo "\n";
echo " <!-- ~~~~~~~~~~~~~~~~~~~~ -->\n";
echo "\n";
?>
<file_sep><?php
require_once("maincore.php");
require_once(BASEDIR.STYLE."tpl.start.php");
if( session_check() == TRUE )
{
echo "<h2><NAME> 0</h2>\n";
echo "<h4 class='center'>§ 1</h4><p>Gracze się zapisują przed sezonem</p>\n";
echo "<h4 class='center'>§ 2</h4><p>Po wystartowaniu sezonu nie przyjmujemy zapisów</p>\n";
echo "<h4 class='center'>§ 3</h4><p>Na start ustawiane są wyzwania każdy z każdym, z tym że są one nieaktywne</p>\n";
echo "<h4 class='center'>§ 4</h4><p>Aby uaktywnić jakieś wyzwanie trzeba po prostu je odpowiednio kliknąć w systemie, co sprawi że zostanie ono \"skierowane\" do pełnego uaktywnienia, pełne uaktywnienie jest kwestią gracza drugiego - w ciągu 2 tygodni - jeżeli tak się nie stanie, zostanie ono aktywowane automatycznie</p>\n";
echo "<h4 class='center'>§ 5</h4><p>Czas trwania jednego wyzwania w pełni uaktywionego to 10dni (liczba do ustalenia)</p>\n";
echo "<h4 class='center'>§ 6</h4><p>W ciągu trwania sezonu jeden gracz może zostać wyzwany \"n\" razy naraz, i pomiędzy jego własnymi wyzwaniami musi trwać \"x\" przerwa</p>\n";
}
require_once(BASEDIR.STYLE."tpl.end.php");
?>
<file_sep><?php
echo custom_menu();
echo custom_calendar();
if( session_check() != FALSE AND session_check() == TRUE )
{
echo " <div class='section-nav'>\n";
echo " Zalogowany: <b>".$_SESSION['login']."</b>\n";
echo " </div>\n";
echo " <div class='section-con'>\n";
echo " <ul>\n";
echo " <li><a href='profile.php'>Profil</a></li>\n";
if( session_check_usrlevel() >= SPECIAL_LVL )
{
echo " <li><a href='administration.php'>Panel administracyjny</a></li>\n";
}
echo " <li><a href='logout.php?logout=yes'>Wyloguj</a></li>\n";
echo " </ul>\n";
echo " </div>\n";
}
elseif ( session_check() == FALSE AND $config['log_sys'] == 1 )
{
echo " <div class='section-nav'>\n";
echo " Logowanie\n";
echo " </div>\n";
echo " <div class='section-con'>\n";
echo " <form action='login.php' method='post' class='form-login'>\n";
echo " <input type='text' name='login' value='login'/>\n";
echo " <input type='password' name='password' value=''/>\n";
echo " <input type='hidden' name='send' value='login'/>\n";
echo " <input type='submit' class='submit' value='Zaloguj'/>\n";
echo " <p class='text-tiny'>Jeżeli nie masz konta:<br><a href='register.php'>zarejestruj się</a></p>\n";
echo " </form>\n";
echo " </div>\n";
}
echo " <div class='section-nav'>\n";
echo " On-line\n";
echo " </div>\n";
echo " <div class='section-con'>\n";
$date_online = date("Y-m-d H:i:s",strtotime("-5 minutes"));
$sql = "SELECT * FROM `".DBPREFIX."users` WHERE `last_date` > '".$date_online."' AND display_online = '1'";
$query = mysql_query($sql);
if(@mysql_num_rows($query) > 0)
{
echo " <p>Użytkownicy on-line: ";
$i = 0;
while($online = mysql_fetch_assoc($query))
{
if( $i > 0 ) echo ", \n";
$i++;
if( session_check_usrlevel($online['login']) >= SPECIAL_LVL ) echo "<strong>";
echo "<a href='#'>".$online['login']."</a>";
if( session_check_usrlevel($online['login']) >= SPECIAL_LVL ) echo "</strong>";
}
echo "\n";
}
else echo " Brak zalogowanych użytkowników online\n";
echo " </div>\n";
?>
<file_sep><?php
if( $_GET['option'] == "download" AND session_check_usrlevel() >= SPECIAL_LVL )
{
// fixing user id
session_check();
// fixing last item id
$sql = "SELECT `id` FROM `".DBPREFIX."files` ORDER BY `id` DESC LIMIT 0, 1";
$query = mysql_query($sql);
$data = mysql_fetch_assoc($query);
$last_id = $data['id'];
// add item
if( @$_POST['send'] == "new" AND check_int($_POST['form4']) == TRUE)
{
$new['id'] = $last_id+1;
$new['name'] = addslashes($_POST['form1']);
$new['desc'] = addslashes($_POST['form2']);
$new['url'] = addslashes($_POST['form3']);
$new['size'] = $_POST['form4'];
$new['adds'] = $_SESSION['userid'];
$new['cat'] = $_POST['form5'];
$new['direct'] = $_POST['direct'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "INSERT INTO `".DBPREFIX."files` VALUES('".$new['id']."','".$new['name']."','".$new['desc']."','".$new['url']."','1','".$new['size']."','".DATE_SET."','".$new['adds']."','".$new['cat']."', '".$new['direct']."');";
mysql_query($sql);
$result = "Plik został dodany";
}
}
// edit item
if( @$_POST['send'] == "edit" AND check_int($_POST['file_id']) == TRUE )
{
$sql = "SELECT * FROM `".DBPREFIX."files` WHERE `id` = '".$_POST['file_id']."' LIMIT 1";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
$data = mysql_fetch_assoc($query);
$edit['id'] = $_POST['file_id'];
$edit['name'] = stripslashes($data['name']);
$edit['desc'] = stripslashes($data['desc']);
$edit['url'] = stripslashes($data['url']);
$edit['size'] = $data['size'];
$edit['cat'] = $data['cat'];
$edit['direct'] = $data['direct'];
$send_new = "update";
$action = "Edycja";
$result = "Wczytano poprawnie";
}
else $result = "Błąd";
}
// update item
if( @$_POST['send'] == "update" )
{
if( check_int($_POST['edited_id']) == TRUE AND check_int($_POST['form4']) == TRUE )
{
$upt['name'] = addslashes($_POST['form1']);
$upt['desc'] = addslashes($_POST['form2']);
$upt['url'] = addslashes($_POST['form3']);
$upt['size'] = $_POST['form4'];
$upt['cat'] = $_POST['form5'];
$upt['direct'] = $_POST['direct'];
if( empty($_POST['form1']) OR empty($_POST['form2']) OR empty($_POST['form3']) ) $result = "Brak potrzebnych danych";
else
{
$sql = "UPDATE `".DBPREFIX."files` SET `name` = '".$upt['name']."', `desc` = '".$upt['desc']."', `url` = '".$upt['url']."', `size` = '".$upt['size']."', `cat` = '".$upt['cat']."', `direct` = '".$upt['direct']."' WHERE `id` = '".$_POST['edited_id']."'";
$result = "Plik został zaaktualizowany";
}
}
mysql_query($sql);
}
if(!empty($result))
{
echo "<div class='suc'>".$result."</div>\n";
}
if( @strlen($edit['name']) > 50 ) $table_info = substr($edit['name'],0,50)."...";
elseif( isset( $edit['name']) ) $table_info = $edit['name'];
echo "<table class='table0 w100 form-style1'>\n";
echo "<tr><th colspan='2'>Zarządzanie działem pobierania</th></tr>\n";
echo "<tr>\n<td colspan='2' align='left'><h6>"; if(isset($edit['id'])) echo "Edytujesz: <i>".$table_info."</i>"; else echo "Nowy"; echo "<a href='administration.php' class='right'>Powrót</a></h6><div class='clear'></div></td>\n</tr>\n";
echo "<tr>";
echo "<form action='' method='post'>\n";
echo "<td width='150'>Nazwa</td><td><input class='text' type='text' name='form1' value='".@$edit['name']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Opis</td><td><input class='text' type='text' name='form2' value='".@$edit['desc']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Url</td><td><input class='text' type='text' name='form3' value='".@$edit['url']."'/></td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Wielkość</td><td><input class='p50' type='text' name='form4' value='".@$edit['size']."'/> KB</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>FTP</td><td>".form_option_bool(@$edit['direct'],"direct","Serwer","Z zewnątrz")."</td>";
echo "</tr>\n";
echo "<tr>";
echo "<td>Kategoria</td><td>\n";
$sql = "SELECT * FROM `".DBPREFIX."files_cat` WHERE `order` > 0";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
echo "<select name='form5' class='w50'>\n";
echo "<option value='0'>Nie pokazuj</option>\n";
while( $cat = mysql_fetch_assoc($query) )
{
echo "<option value='".$cat['id']."'"; if( $cat['id'] == @$edit['cat'] ) echo " selected='selected'"; echo ">".$cat['name']."</option>\n";
}
echo "</select>\n";
}
echo "</td>\n";
echo "</tr>\n";
echo "<tr>";
echo "<td>";
if( @$_POST['send'] == "new" OR @$_POST['send'] == "update" ) { $send_type = "new"; }
if( @!empty($_POST['send']) && @$_POST['send'] == "edit" ) echo "<input type='hidden' name='edited_id' value='".$edit['id']."'/>";
if( isset($send_new) )
{
$send_type = $send_new;
}
else $send_type = "new";
echo "<input type='hidden' name='send' value='".$send_type."'/></td><td><input class='submit' type='submit' value='Wyślij'/></td>";
echo "</form>\n";
echo "</tr>\n";
echo "<tr><td colspan='2'><h6>Wybierz już istniejący:</h6></td></tr>\n";
echo "<tr>\n";
echo "<form action='' method='post'>\n";
echo "<td class='right'><input type='hidden' name='send' value='edit'/><input type='submit' class='submit' value='OK'/></td>\n";
echo "<td>\n";
$sql = "SELECT * FROM `".DBPREFIX."files_cat` ORDER BY `order` ASC";
$query = mysql_query($sql);
if( mysql_num_rows($query) > 0 )
{
echo " <select name='file_id' class='select'>\n";
while($cat = mysql_fetch_assoc($query))
{
echo " <optgroup label='".$cat['name']; if($cat['order'] == 0) echo " (ukryta)"; echo "'>\n";
$sql2 = "SELECT * FROM `".DBPREFIX."files` WHERE `cat` = '".$cat['id']."' ORDER BY `name` ASC";
$query2 = mysql_query($sql2);
if( mysql_num_rows($query2) > 0 )
{
while($file = mysql_fetch_assoc($query2))
{
echo " <option value='".$file['id']."'>".$file['name']." :: [".$file['size']."KB]</option>\n";
}
}
echo " </optgroup>\n";
}
$sql2 = "SELECT * FROM `".DBPREFIX."files` WHERE `cat` = '0' ORDER BY `name` ASC";
$query2 = mysql_query($sql2);
if( mysql_num_rows($query2) > 0 )
{
echo "<optgroup label='Ukryte (bez kategorii)'>\n";
while($file = mysql_fetch_assoc($query2))
{
echo " <option value='".$file['id']."'>".$file['name']." :: [".$file['size']."KB]</option>\n";
}
echo "</optgroup>\n";
}
echo " </select>\n";
}
echo "</td>\n";
echo "</form>\n";
echo "</tr>\n";
echo "</table>\n\n";
}
?>
| 812120c37d559e25f42d9e12de150ea90ee41e93 | [
"Markdown",
"SQL",
"PHP"
]
| 52 | PHP | dgutkowski/cms-php5-closed | 7b2648890b45266bdce28865d0ec56391ec7a97d | 9fb341eb189ab2e4de7b6291e658457f465d1575 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.