branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>import { Component, OnInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
logIndex: number = 0
name: string;
oldName: string;
logIt(msg: string) {
console.log(`#${this.logIndex++} ${msg}`);
}
constructor() {
this.logIt('name的属性在constructor里的值是:' + name); // 除了使用简单的值,对局部变量进行初始化之外,这里应该什么都不做
}
ngOnChanges(changes: SimpleChanges): void { //该组件若设置了数据绑定输入属性时调用,或被绑定的输入属性的值发生变化时调用.若没有数据绑定输入属性则该方法不会被调用.
let name = changes['name'].currentValue;
this.logIt('name的属性在constructor里的值是:' + name);
}
ngOnInit() {
this.logIt('ngOnInit');// 初始化数据或者请求数据应该放在这里.切勿不要将dom的操作放在这里
}
ngDoCheck(): void {
this.logIt('ngDoCheck'); // 发生Angular无法或者不愿意自己检测的变化时做出的反应. 我的理解是,初次调用时因为数据渲染,之后将会被频繁被调用的一个钩子,即便只是点击了input框也会被调用.
//用特定事件发生时才触发业务逻辑.例子
if (this.name !== this.oldName) {
console.log(`从${this.oldName}变为${this.name}`);
this.oldName = this.name;
}
}
ngAfterContentInit(): void {// 当把内容投影进组件之后调用
this.logIt('ngAfterContentInit');
}
ngAfterContentChecked(): void { //每次完成被投影组件内容的变更检测之后调用.
this.logIt('ngAfterContentChecked');
}
ngAfterViewInit(): void { //每次做完组件视图和子视图之后调用.对dom的操作应该放在这里
this.logIt('ngAfterViewInit');
}
ngAfterViewChecked(): void {// 每次做完组件视图和子视图变更检测时候调用
this.logIt('ngAfterViewChecked');
}
ngOnDestroy(): void { // 组件销毁时被调用
this.logIt('ngOnDestroy');
}
}
<file_sep>import { GoodsResolve } from './guard/goods.resolve';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { OrderComponent } from './components/order/order.component';
import { SellerListComponent } from './components/seller-list/seller-list.component';
import { BuyerListComponent } from './components/buyer-list/buyer-list.component';
import { Code404Component } from './components/code404/code404.component';
import { CustomerComponent } from './components/customer/customer.component';
import { PermissionGuard } from './guard/permission.guard';
import { FocusGuard } from './guard/focus.guard';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'customer', component: CustomerComponent , outlet:'aux'},
{
path: 'order/:id', component: OrderComponent, data: [{ isPro: true }], children: [
{ path: '', component: BuyerListComponent },
{ path: 'seller/:id', component: SellerListComponent },
],
canActivate:[PermissionGuard],
canDeactivate:[FocusGuard],
resolve:{
goods:GoodsResolve, //当进到order路由的时候我需要携带一个名字叫goods的数据,该数据由GoodsResolve提供.
//xxx:XxxResolve, // 名字为xxx的数据需要XxxResolve提供.
}
},
{ path: '**', component: Code404Component },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit, Input, SimpleChange, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
_data: Array<string>
changeLog: Array<string> = [];
childMes: string = 'this is child';
birthDate:Date = new Date();
@Input() major: number;
@Input() minor: number;
@Input() runNewMinor: Function;
@Input() home: any;
@Input() set childData(data: Array<string>) { //childData是我们用来接收父组件传递过来的数据的一个变量,我们用setter来截取到这个变量,然后做一些修改,childData这个变量名,
//它是取决于父组件app.component.html里面的[childData]="parentData",不能随便改动
this._data = data || ['css', 'js']; //如果data为false的值(如空字符串,undefined,null),给_data赋值为['css','js']。
}
@Output() message = new EventEmitter<string>() //这里的message是可以自己定义的.需要注意这里OutPut的名字.需要跟向父组件传递的名字保持一致
putToPatent() {
this.message.emit('This is child');
}
run() {
alert("this is child's function")
}
ngOnChanges(changes: { [propKey: string]: SimpleChange }) { //changes是一个SimpleChanges类型的参数,键值为属性名的数组
let log: string[] = [];
for (let key in changes) {
if (key == 'major' || key == 'minor') {
let changedProp = changes[key]; //首次加载页面ngOnChanges方法也会执行,此时changedProp 有两个个属性,currentVue,firstChange.
//当第二次触发ngOnChanges,changeProp有三个属性,分别是previousValue,currentValue,firstChange.只有第一次firstChange是true,之后firstChange都是false.
let from = JSON.stringify(changedProp.previousValue);
let to = JSON.stringify(changedProp.currentValue);
if (changedProp.isFirstChange()) {
log.push(`Initial value of ${key} set to ${to}`);
} else {
let from = JSON.stringify(changedProp.previousValue);
log.push(`${key} changed from ${from} to ${to}`);
}
}
}
this.changeLog.push(log.join(', '));
}
get child(): Array<string> { //用get重新获取重置过后的_data变量
return this._data;
}
constructor() { }
ngOnInit() {
}
}
// export declare class SimpleChange {
// previousValue: any;
// currentValue: any;
// firstChange: boolean;
// constructor(previousValue: any, currentValue: any, firstChange: boolean);
// isFirstChange(): boolean;
// }
<file_sep>/* 这个文件是Angular 根模块,告诉Angular如何组装应用 */
//BrowserModule,是浏览器解析模块
import { BrowserModule } from '@angular/platform-browser';
//Angular核心模块
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
//路由配置模块
import { AppRoutingModule } from './app-routing.module';
//组件
import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';
import { ChildComponent } from './components/child/child.component';
import { MultiplePipe } from './pipt/multiple.pipe';
import { OrderComponent } from './components/order/order.component';
import { Code404Component } from './components/code404/code404.component';
import { BuyerListComponent } from './components/buyer-list/buyer-list.component';
import { SellerListComponent } from './components/seller-list/seller-list.component';
import { CustomerComponent } from './components/customer/customer.component';
import { PermissionGuard } from './guard/permission.guard';
import { FocusGuard } from './guard/focus.guard';
import { GoodsResolve } from './guard/goods.resolve';
import { ProductComponent } from './components/product/product.component';
import { ProductService } from './services/product.service';
import { Product2Component } from './components/product2/product2.component';
import { LoggerService } from './services/logger.service';
/*@NgModule装饰器,接受一个元数据对象,告诉Angular如何编译和启动应用*/
@NgModule({
declarations: [ //配置当前项目运行的组件,指令,管道
AppComponent, HomeComponent, ChildComponent, MultiplePipe, OrderComponent, Code404Component, BuyerListComponent, SellerListComponent, CustomerComponent, ProductComponent, Product2Component
],
imports: [ //配置当前模块运行依赖的其他模块
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [PermissionGuard, FocusGuard, GoodsResolve, ProductService,LoggerService],//配置项目所需要的服务
bootstrap: [AppComponent] // 指定应用的主视图(称为根组件),通过引导根AppModule来启动项目,这里一般写的就是根组件
})
// 导出根模块
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-order',
templateUrl: './order.component.html',
styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
private orderName: string;
private orderId: number;
private isPro: boolean;
private goods: Goods;
constructor(private routeInfo: ActivatedRoute) { };
focus: boolean = false;
ngOnInit() {
this.routeInfo.queryParams.subscribe((queryParam: Params) => {
this.orderName = queryParam['name'];//在查询参数中传递数据
})
this.routeInfo.params.subscribe((params: Params) => {
this.orderId = params['id'];//在路由配置中传递数据
});
this.routeInfo.data.subscribe((data: { goods: Goods }) => {
this.goods = data.goods;
});
this.isPro = this.routeInfo.snapshot.data[0]['isPro']
// this.orderName = this.routeInfo.snapshot.queryParams['name'] //参数快照
}
isFocus() {
return this.focus
}
}
export class Goods {
constructor(public name: string, public id: number) {
}
}
<file_sep>import { LoggerService } from './logger.service';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(public loggerService:LoggerService) { }
getProduct():Product{
this.loggerService.log('getStock方法被调用');
return new Product('童装',1);
}
}
export class Product {
constructor(public name: string, public id: number) { }
}
<file_sep>import { Goods } from './../components/order/order.component';
import { Resolve, ActivatedRouteSnapshot, Router } from '@angular/router';
import { Injectable } from '@angular/core';
@Injectable() //有这个装饰器就表示当前类可以使用依赖注入.之所以在component页面 只是用@Component也可以在构造函数注入依赖,是因为@Component已经继承了Injectable
export class GoodsResolve implements Resolve<Goods> {
constructor(private router: Router) { //要使依赖注入生效就添加@Injectable装饰器
}
resolve(route: ActivatedRouteSnapshot) {
let orderId = route.params['id'];
if (orderId == 1) {
return new Goods('女装', 1)//成功获取订单为1的话我们就返回相关的商品信息,否则就导航到首页.
} else {
this.router.navigate(['/home'])
}
}
}
<file_sep>import { ChildComponent } from './components/child/child.component';
import { Component, ViewChild } from '@angular/core'; //引入核心模块里面的component
import { Router } from '@angular/router';
//@Component 装饰器会指出紧随其后的那个类是个组件类,并为其指定元数据.至于加上@Component 装饰器,它才变成了组件.
@Component({
selector: 'app-root',//是css装饰器,通过标签的使用方式.来创建并插入改组件的一个实例,比如在index.html包含<app-root></app-root>就插入了该组件的实例视图
templateUrl: './app.component.html',//模板:这里插入一个外联html模板.也可以用template属性提供内联的html.
styleUrls: ['./app.component.scss'],//该模板所使用的的css
providers: []//当前组件所需的服务提供商的一个数组
})
export class AppComponent {
constructor(private route:Router){
}
parentData: Array<string> = [
'angular', 'react', 'vue'
]
major: number = 1;
minor: number = 2;
message: string;
value:string;
@ViewChild(ChildComponent, { static: false }) childDom: ChildComponent
messageFromChild(message) {
this.message = message;
}
newMinor() {
this.minor++;
console.log(this.childDom.childMes);
this.childDom.run()
}
newMajor() {
this.major++;
}
toOrder(){
this.route.navigate(['/order',2])
}
}
<file_sep>import { LoggerService } from './logger.service';
import { ProductService, Product } from 'src/app/services/product.service';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AnotherProductService implements ProductService {
getProduct(): import("./product.service").Product {
return new Product('男装', 2)
}
constructor(public loggerService: LoggerService) { }
}
<file_sep>import { CanDeactivate, ActivatedRoute, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { OrderComponent } from '../components/order/order.component';
export class FocusGuard implements CanDeactivate<OrderComponent>{
canDeactivate(component: OrderComponent) {
if (component.isFocus()) {
return true
}else
return window.confirm('是否关注卖家');
}
}
<file_sep>
import { Component, OnInit } from '@angular/core';
import { Product, ProductService } from 'src/app/services/product.service';
import { AnotherProductService } from 'src/app/services/another-product.service';
@Component({
selector: 'app-product2',
templateUrl: './product2.component.html',
styleUrls: ['./product2.component.scss'],
providers: [{ provide: ProductService, useClass: AnotherProductService }]
})
export class Product2Component implements OnInit {
product2: Product
constructor(private productService: ProductService) { }
ngOnInit() {
this.product2 = this.productService.getProduct();
}
}
|
fd7e6f1db514878cda66b44948c140e4e4a6a425
|
[
"TypeScript"
] | 11
|
TypeScript
|
LarissaLin/Angular
|
35514ab09bef146e5f31d065cab71936209155e0
|
50df9e255c8b4776daeb1445881a56af4cb3adae
|
refs/heads/master
|
<repo_name>sirakoff/hackerbay-backend-task<file_sep>/test/test.js
let chai = require('chai');
let chaiHttp = require('chai-http');
let should = chai.should();
let app = require('../index.js');
chai.use(chaiHttp);
describe('GET /thumbnail', () => {
let token = "";
let url = "http://images.unsplash.com/profile-1451435888837-4755067c2a33";
before((done) => {
chai.request(app)
.post('/login')
.send({
username: 'dan',
password: '<PASSWORD>'
}).end((err, res) => {
// console.log(res);
token = res.body.token;
done();
});
});
it('it should return 401', (done) => {
chai.request(app)
.get('/thumbnail')
.end((err, res) => {
res.should.have.status(401);
done();
});
});
it('it should return 500', (done) => {
chai.request(app)
.get('/thumbnail?url=http://google.notfound')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
res.should.have.status(500);
done();
});
});
it('it should return an Image', (done) => {
chai.request(app)
.get(`/thumbnail?url=${url}`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
res.headers['content-type'].should.contain('image');
res.should.have.status(200);
done();
});
});
it('it should return an error message', (done) => {
chai.request(app)
.get(`/thumbnail?url=`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
res.body.message.should.eq("`url` is a required parameter and must be valid");
res.should.have.status(400);
done();
});
});
});
describe('POST /login', () => {
it('it should return 404', (done) => {
chai.request(app).get('/not-found').end((err, res) => {
res.should.have.status(404);
return done();
});
});
it('it should return 400', (done) => {
chai.request(app)
.post('/login')
.send({
username: 'dan',
password: ''
})
.end((err, res) => {
res.should.have.status(400);
done();
});
});
it('it should return 400', (done) => {
chai.request(app)
.post('/login')
.send({
username: '',
password: '<PASSWORD>'
})
.end((err, res) => {
res.should.have.status(400);
done();
});
});
it('it should return a token', (done) => {
chai.request(app)
.post(`/login`)
.send({
username: 'dan',
password: '<PASSWORD>'
})
.end((err, res) => {
res.body.should.include.keys("token");
res.should.have.status(200);
done();
});
});
});
describe('POST /patch', () => {
let token = "";
let body = {
"patch": [
{ "op": "replace", "path": "/baz", "value": "boo" }
],
"doc": {
"baz": "qux",
"foo": "bar"
}
};
before((done) => {
chai.request(app)
.post('/login')
.send({
username: 'dan',
password: '<PASSWORD>'
}).end((err, res) => {
// console.log(res);
token = res.body.token;
done();
});
});
it('it should return 401', (done) => {
chai.request(app)
.post('/patch')
.send(body)
.end((err, res) => {
res.should.have.status(401);
done();
});
});
it('it should return an error', (done) => {
chai.request(app)
.post(`/patch`)
.set('Authorization', `Bearer ${token}`)
.send({})
.end((err, res) => {
res.should.have.status(400);
done();
});
});
it('it should return an error', (done) => {
chai.request(app)
.post(`/patch`)
.set('Authorization', `Bearer ${token}`)
.send({
patch: {},
doc:{}
})
.end((err, res) => {
res.should.have.status(400);
done();
});
});
it('it should return a patched object', (done) => {
chai.request(app)
.post('/patch')
.set('Authorization', `Bearer ${token}`)
.send(body)
.end((err, res) => {
res.body.doc.should.deep.eq({
"baz": "boo",
"foo": "bar"
});
res.should.have.status(200);
done();
});
});
});
<file_sep>/index.js
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const expressJWT = require('express-jwt');
const morgan = require('morgan');
const jsonpatch = require('jsonpatch');
const sharp = require('sharp');
const https = require('https');
const http = require('http');
const fs = require('fs');
const log = require('./log');
const app = express();
const isURL = (str) => {
const urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
const url = new RegExp(urlRegex, 'i');
return str.length < 2083 && url.test(str);
};
app.use(morgan('tiny'));
app.use(bodyParser.json());
let { JWT_SECRET = '' } = process.env;
const { PORT = '9000' } = process.env;
if (!JWT_SECRET && fs.existsSync('/run/secrets/JWT_SECRET')) {
JWT_SECRET = fs.readFileSync('/run/secrets/JWT_SECRET');
} else if(!JWT_SECRET) {
JWT_SECRET = 'secret';
}
sharp.cache(false);
app.disable('x-powered-by');
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({
message: 'Username and password fields are required'
});
}
return res.json({
token: jwt.sign({ username }, JWT_SECRET, {
expiresIn: '5h'
})
});
});
app.post('/patch', expressJWT({ secret: JWT_SECRET }), (req, res) => {
if (!req.user) return res.status(401).json({});
const { patch, doc } = req.body;
if (!patch || !doc) {
return res.status(400).json({
message: '`patch` & `doc` fields are required.'
});
}
try {
return res.json({
doc: jsonpatch.apply_patch(doc, patch)
});
// eslint-disable-next-line keyword-spacing
} catch(e) {
// console.log(e);
return res.status(400).json({
message: e.message
});
}
});
app.get('/thumbnail', expressJWT({ secret: JWT_SECRET }), (req, res, next) => {
if (!req.user) return res.status(401).json({});
const { url } = req.query;
if (!url || !isURL(url)) {
return res.status(400).json({
message: '`url` is a required parameter and must be valid'
});
}
return ((/^https/.test(url)) ? https : http).get(url, (stream) => {
const { statusCode } = res;
if (statusCode !== 200) {
const error = new Error(`Request Failed.\n Status Code: ${statusCode}`);
return next(error);
}
const resize = sharp().resize({
// fit: "inside",
width: 50,
height: 50
});
res.set('Cache-Control', 'max-age=360');
res.set('Expires', new Date(Date.now() + (360 * 1000)).toUTCString());
res.set('Content-Type', stream.headers['content-type']);
res.set('Accept-Ranges', 'bytes');
stream.on('error', (err) => {
if (global.gc) global.gc();
next(err);
});
resize.on('info', (info) => {
res.set('Content-Length', info.size);
});
resize.on('end', () => {
if (global.gc) global.gc();
});
stream.on('timeout', () => {
if (global.gc) global.gc();
res.status(504).end();
});
resize.on('error', (err) => {
if (global.gc) global.gc();
next(err);
});
res.on('error', (err) => {
next(err);
});
return stream.pipe(resize).pipe(res);
}).on('error', (err) => {
log.error(err);
next(err);
});
});
app.use('*', (req, res) => {
res.status(404);
return res.json({});
});
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
log.error(err);
if (err.name === 'UnauthorizedError') return res.status(401).json({});
res.status(500);
return res.json({
error: true
});
});
app.listen(PORT, () => {
log.info(`Hackerbay Backend Task started on 0.0.0.0:${PORT}`);
});
module.exports = app;
<file_sep>/README.md
# Hackerbay Backend Task
Stateless Node.js microservice with the following features:
- Authentication
- JSON patching
- Image Thumbnail Generation
# Docker Installation
`docker run -d -e PORT=9000 -e JWT_SECRET=secret -p 9000:9000 sirakoff/backend-task`
# Node Installation
`npm install`
`npm start`
# Documentation
(https://documenter.getpostman.com/view/585517/RzfdophP)<file_sep>/Dockerfile
FROM node:alpine
WORKDIR /usr/src/app
COPY . ./
RUN apk add --no-cache --virtual .deps python g++ make && \
npm set progress=false && \
npm config set depth 0 && \
npm install --production && \
npm cache clean --force && \
rm -rf /var/cache/apk/* && \
apk del .deps
EXPOSE 9000
CMD [ "npm", "start" ]
|
4b5da4b87f265093564ca8cbcd13a94385e91edf
|
[
"JavaScript",
"Dockerfile",
"Markdown"
] | 4
|
JavaScript
|
sirakoff/hackerbay-backend-task
|
b4df7032ce894a3866c49614e771ce3a7c35c7d0
|
dae5ec63b7e60fa701f6fa4d3d773b739f39f726
|
refs/heads/master
|
<repo_name>spbisya/CassowarylayoutIzya<file_sep>/app/src/main/java/com/okunev/cassowarylayout/Mainscreen.java
package com.okunev.cassowarylayout;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import no.agens.cassowarylayout.CassowaryLayout;
import no.agens.cassowarylayout.ViewIdResolver;
public class Mainscreen extends AppCompatActivity {
int k;
ArrayList<String> parents = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
HashMap<Integer, HashMap<Integer, HashMap<String, String>>> allElements =
new HashMap<>();
ArrayList<String> CONSTRAINTS = new ArrayList<>();
ArrayList<TextView> views = new ArrayList<>();
HashMap<String, TextView> textViewHashMap = new HashMap<>();
CassowaryLayout cassowaryLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cassowaryLayout = new CassowaryLayout(this, viewIdResolver);
cassowaryLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
k = getIntent().getIntExtra("game", 1);
int id = 1000;
// backgroundImageView = new TextView(this);
// backgroundImageView.setText("backgroundImageView");
// backgroundImageView.setId(id++);
// backgroundImageView.setBackgroundColor(Color.RED);
// backgroundImageView.setTag("backgroundImageView");
// cassowaryLayout.addView(backgroundImageView);
//
try {
firstScreens("mainscreen");
} catch (JSONException e) {
e.printStackTrace();
}
Random rand = new Random();
for (String name : names) {
TextView tv = new TextView(this);
tv.setText(name);
tv.setId(id++);
tv.setBackgroundColor(Color.rgb(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
tv.setTextColor(Color.RED);
views.add(tv);
cassowaryLayout.addView(tv);
textViewHashMap.put(name, tv);
}
cassowaryLayout.setupSolverAsync(CONSTRAINTS.toArray(new CharSequence[CONSTRAINTS.size()]));
setContentView(cassowaryLayout);
}
private ViewIdResolver viewIdResolver = new ViewIdResolver() {
@Override
public int getViewIdByName(String viewName) {
// if ("backgroundImageView".equals(viewName)) {
// return backgroundImageView.getId();
// }
return textViewHashMap.get(viewName).getId();
// else if ("hintLabel".equals(viewName)) {
// return hintLabel.getId();
// }
// else if ("buyButton".equals(viewName)) {
// return buyButton.getId();
// }
// else if ("priceLabel".equals(viewName)) {
// return priceLabel.getId();
// }
// else if ("ticketCostLabel".equals(viewName)) {
// return ticketCostLabel.getId();
// }
// else if ("topContainer".equals(viewName)) {
// return topContainer.getId();
// }
// else if ("logoImageView".equals(viewName)) {
// return logoImageView.getId();
// }
// return 0;
}
@Override
public String getViewNameById(int id) {
// ArrayList<TextView> greta = new ArrayList<>(textViewHashMap.values());
// for(int kli=0;kli<greta.size();kli++){
// if(id==greta.get(kli).getId()){
// return greta.get(kli).getText().toString();
// }
// }
ArrayList<TextView> greta = new ArrayList<>(textViewHashMap.values());
for (int kli = 0; kli < greta.size(); kli++) {
if (id == greta.get(kli).getId()) return names.get(kli);
}
return "";
}
};
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("lotteries.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public HashMap<Integer, HashMap<String, String>> parse(JSONArray constraints_json) throws JSONException {
HashMap<Integer, HashMap<String, String>> constrains0 = new HashMap<>();
for (int i = 0; i < constraints_json.length(); i++) {
JSONObject constrK = constraints_json.getJSONObject(i);
HashMap<String, String> constrains = new HashMap<>();
try {
constrains.put("attribute1", constrK.get("attribute1").toString());
} catch (Exception l) {
constrains.put("attribute1", "0");
}
try {
constrains.put("attribute2", constrK.get("attribute2").toString());
} catch (Exception l) {
constrains.put("attribute2", "0");
}
try {
constrains.put("constant", constrK.get("constant").toString());
} catch (Exception l) {
constrains.put("constant", "0");
}
constrains.put("from_object", constrK.get("from_object").toString());
try {
constrains.put("multiplier", constrK.get("multiplier").toString());
} catch (Exception l) {
constrains.put("multiplier", "0");
}
try {
constrains.put("offset", constrK.get("offset").toString());
} catch (Exception l) {
constrains.put("offset", "0");
}
try {
constrains.put("relation", constrK.get("relation").toString());
} catch (Exception l) {
constrains.put("relation", "0");
}
constrains.put("to_object", constrK.get("to_object").toString());
try {
constrains.put("type", constrK.get("type").toString());
} catch (Exception l) {
constrains.put("type", "0");
}
constrains0.put(i, constrains);
}
return constrains0;
}
public void firstScreens(String screen) throws JSONException {
String jsonData = loadJSONFromAsset();
JSONArray games = new JSONArray(jsonData);
JSONObject firstgame = games.getJSONObject(k);//В теории, для других игр изменяем 0 на нужное число.
//А потом молимся, чтобы ticketDataTemp не был null
JSONObject ticketDataTemp = firstgame.getJSONObject("ticketDataTemp");
JSONObject buyTicket = ticketDataTemp.getJSONObject("mainscreen");//ticketDataTemp.getJSONObject("buyTicket");
JSONArray elements = buyTicket.getJSONArray("elements");
for (int i = 0; i < elements.length(); i++) {
JSONObject layout = elements.getJSONObject(i);
JSONArray constraints_json = layout.getJSONArray("constraints");
parents.add(layout.get("parent_name").toString());
names.add(layout.get("name").toString());
HashMap<Integer, HashMap<String, String>> constrains0 = new HashMap<>();
for (int k = 0; k < constraints_json.length(); k++) {
JSONObject constrK = constraints_json.getJSONObject(k);
HashMap<String, String> constrains = new HashMap<>();
constrains.put("attribute1", constrK.get("attribute1").toString());
constrains.put("attribute2", constrK.get("attribute2").toString());
constrains.put("constant", constrK.get("constant").toString());
constrains.put("from_object", constrK.get("from_object").toString());
constrains.put("multiplier", constrK.get("multiplier").toString());
constrains.put("offset", constrK.get("offset").toString());
constrains.put("relation", constrK.get("relation").toString());
constrains.put("to_object", constrK.get("to_object").toString());
constrains.put("type", constrK.get("type").toString());
constrains0.put(k, constrains);
}
allElements.put(i, constrains0);
}
for (int i = 0; i < allElements.size(); i++) {
ConstraintsResolver constraintsResolver = new ConstraintsResolver(allElements.get(i), parents.get(i), names.get(i));
ArrayList<String> constr = constraintsResolver.resolve();
for (String s : constr)
CONSTRAINTS.add(s);
}
}
}
<file_sep>/app/src/main/java/com/okunev/cassowarylayout/MainActivity.java
package com.okunev.cassowarylayout;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import no.agens.cassowarylayout.CassowaryLayout;
import no.agens.cassowarylayout.ViewIdResolver;
public class MainActivity extends AppCompatActivity {
CassowaryLayout cassowaryLayout;
TextView backgroundImageView;
Button b1,b2,b4,b6,b14,b16,b18,b20,b30;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Game.class);
intent.putExtra("sex", 1);
startActivity(intent);
}
});
b2 = (Button)findViewById(R.id.b2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Game.class);
intent.putExtra("sex", 2);
startActivity(intent);
}
});
b4 = (Button)findViewById(R.id.b4);
b4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Game.class);
intent.putExtra("sex", 4);
startActivity(intent);
}
});
b6 = (Button)findViewById(R.id.b6);
b6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Game.class);
intent.putExtra("sex", 6);
startActivity(intent);
}
});
b14 = (Button)findViewById(R.id.b14);
b14.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Game.class);
intent.putExtra("sex", 14);
startActivity(intent);
}
});
b16 = (Button)findViewById(R.id.b16);
b16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Game.class);
intent.putExtra("sex", 16);
startActivity(intent);
}
});
b18 = (Button)findViewById(R.id.b18);
b18.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Game.class);
intent.putExtra("sex", 18);
startActivity(intent);
}
});
b20 = (Button)findViewById(R.id.b20);
b20.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Game.class);
intent.putExtra("sex", 20);
startActivity(intent);
}
});
b30 = (Button)findViewById(R.id.b30);
b30.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"huy pesda",Toast.LENGTH_LONG).show();
}
});
cassowaryLayout = new CassowaryLayout(this, viewIdResolver);
cassowaryLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
int id = 1000;
backgroundImageView = new TextView(this);
backgroundImageView.setText("backgroundImageView");
backgroundImageView.setGravity(Gravity.BOTTOM);
backgroundImageView.setId(id++);
backgroundImageView.setBackgroundColor(Color.CYAN);
backgroundImageView.setTag("backgroundImageView");
String[] CONSTRAINTS = {
"backgroundImageView.x == 0",
"backgroundImageView.y == 0",
"backgroundImageView.y2==container.height",
"backgroundImageView.x2==container.width"
};
// Toast.makeText(this, ""+allElements.get(1).get(0).size(),Toast.LENGTH_LONG).show();
cassowaryLayout.addView(backgroundImageView);
cassowaryLayout.setupSolverAsync(CONSTRAINTS);
}
private ViewIdResolver viewIdResolver = new ViewIdResolver() {
@Override
public int getViewIdByName(String viewName) {
if ("backgroundImageView".equals(viewName)) {
return backgroundImageView.getId();
}
return 0;
}
@Override
public String getViewNameById(int id) {
if (id == backgroundImageView.getId()) {
return "backgroundImageView";
}
return "";
}
};
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("lotteries.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
<file_sep>/app/src/main/java/com/okunev/cassowarylayout/ConstraintsResolver.java
package com.okunev.cassowarylayout;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by 777 on 1/19/2016.
*/
public class ConstraintsResolver {
String viewTag = null;
HashMap<Integer, HashMap<String, String>> allConstraints = new HashMap<>();
ArrayList<String> constrains = new ArrayList<>();
int attr1, attr2, constant, offset, relation, type;
String multiplier;
String from_object, to_object;
Boolean height = false, width = false, top = false, right = false, left = false, bottom = false;
String parent = "",name = "";
public ConstraintsResolver(HashMap<Integer, HashMap<String, String>> allConstraints, String parent,String name) {
this.allConstraints = allConstraints;
this.parent = parent;
this.name = name;
}
public ArrayList<String> resolve() {
constrains = new ArrayList<>();
for (int i = 0; i < allConstraints.size(); i++) {
HashMap<String, String> constrainI = allConstraints.get(i);
attr1 = Integer.parseInt(constrainI.get("attribute1"));
attr2 = Integer.parseInt(constrainI.get("attribute2"));
constant = Integer.parseInt(constrainI.get("constant"));
from_object = constrainI.get("from_object");
multiplier = constrainI.get("multiplier");
offset = Integer.parseInt(constrainI.get("offset"));
relation = Integer.parseInt(constrainI.get("relation"));
to_object = constrainI.get("to_object");
type = Integer.parseInt(constrainI.get("type"));
viewTag = from_object;
if (parent.equals("null")) parent = "container";
if (to_object.equals("superView")||to_object.equals("null")) to_object = "container";
typeResolver(type);
}
if (height == false) {
if (top == false | bottom == false)
if(name.equals("null")) {
constrains.add(viewTag + ".height==40dp");
}
else{
constrains.add(name + ".height==40dp");
}
}
if (width == false) {
if (left == false | right == false)
if(name.equals("null")) {
constrains.add(viewTag + ".width==" + parent + ".width");
}
else{
constrains.add(name + ".width==" + parent + ".width");
}
}
return constrains;
}
public void typeResolver(int type) {
switch (type) {
case 0:
// не нашёл в json
break;
case 1:
constrains.add(resolveType1(attr1, constant));
break;
case 2:
if (to_object.equals("container"))
constrains.add(resolveType2Container(attr1, attr2, constant));
else
constrains.add(resolveType2(attr1, attr2, constant));
break;
case 3:
constrains.add(resolveType3(attr1, constant));
break;
case 4:
constrains.add(from_object + ".x == 0");
constrains.add(from_object + ".y == 0");
constrains.add(from_object + ".y2==" + parent + ".height");
constrains.add(from_object + ".x2==" + parent + ".width");
height = true;
width = true;
break;
case 5:
constrains.add(resolveType5(attr1, attr2));
break;
case 6:
constrains.add(from_object + ".centerY==" + parent + ".centerY");
constrains.add(from_object + ".centerX==" + parent + ".centerX");
break;
case 7:
constrains.add(resolveType7(attr1,constant));
break;
case 8:
constrains.add(resolveType8(attr1, attr2, multiplier));
break;
case 9:
// Не нашёл в json
break;
}
}
public String resolveType2(int attr1, int attr2, int constant) {
switch (attr1) {
case 3:
top = true;
String s = from_object + ".top==";
switch (attr2) {
case 3:
s += to_object + ".top" + ((constant >= 0) ? "+" + constant : "" + constant) + "dp";
break;
case 4:
s += to_object + ".bottom" + ((constant >= 0) ? "+" + constant : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return s;
break;
case 4:
bottom = true;
String l = from_object + ".bottom==";
switch (attr2) {
case 3:
l += to_object + ".top" + ((constant >= 0) ? "+" + constant : "" + constant) + "dp";
break;
case 4:
l += to_object + ".bottom" + ((constant >= 0) ? "+" + constant : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return l;
break;
case 5:
left = true;
String five = from_object + ".left==";
switch (attr2) {
case 5:
five += to_object + ".left" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
case 6:
five += to_object + ".right" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return five;
break;
case 6:
right = true;
String six = from_object + ".right==";
switch (attr2) {
case 5:
six += to_object + ".left" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
case 6:
six += to_object + ".right" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return six;
break;
}
return "1";
}
public String resolveType2Container(int attr1, int attr2, int constant) {
switch (attr1) {
case 3:
top = true;
String s = from_object + ".top==";
switch (attr2) {
case 3:
s += "" + constant + "dp";
break;
case 4:
s += "container.height" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return s;
break;
case 4:
bottom = true;
String l = from_object + ".bottom==";
switch (attr2) {
case 3:
l += "" + constant + "dp";
break;
case 4:
l += "container.height" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return l;
break;
case 5:
left = true;
String five = from_object + ".left==";
switch (attr2) {
case 5:
five += to_object + ".left" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
case 6:
five += to_object + ".right" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return five;
break;
case 6:
right = true;
String six = from_object + ".right==";
switch (attr2) {
case 5:
six += to_object + ".left" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
case 6:
six += to_object + ".right" + ((constant >= 0) ? ("+" + constant) : "" + constant) + "dp";
break;
}
if (attr1 > 0)
return six;
break;
}
return "3";
}
public String resolveType8(int attr1, int attr2, String multiplier) {
switch (attr1) {
case 8:
height = true;
String s = from_object + ".height==";
switch (attr2) {
case 7:
s += to_object + ".width*" + multiplier;
if (attr1 > 0)
return s;
break;
case 8:
s += to_object + ".height*" + multiplier;
if (attr1 > 0)
return s;
break;
}
break;
case 7:
width = true;
String l = from_object + ".width==";
switch (attr2) {
case 7:
l += to_object + ".width*" + multiplier;
if (attr1 > 0)
return l;
break;
case 8:
l += to_object + ".height*" + multiplier;
if (attr1 > 0)
return l;
break;
}
break;
}
return "4";
}
public String resolveType1(int attr1, int constant) {
switch (attr1) {
case 7:
width = true;
if (attr1 > 0)
return from_object + ".width==" + constant + "dp";
break;
case 8:
height = true;
if (attr1 > 0)
return from_object + ".height==" + constant + "dp";
break;
}
return "5";
}
public String resolveType3(int attr1, int constant) {
switch (attr1) {
case 9:
if (attr1 > 0)
return from_object + ".centerX==" + parent + ".centerX" + ((constant >= 0) ? "+" + constant : "" + constant) + "dp";
break;
case 10:
if (attr1 > 0)
return from_object + ".centerY==" + parent + ".centerY" + ((constant >= 0) ? "+" + constant : "" + constant) + "dp";
break;
}
return "6";
}
public String resolveType5(int attr1, int attr2) {
switch (attr1) {
case 6:
right = true;
String s = from_object + ".right==";
switch (attr2) {
case 6:
s += to_object + ".right";
if (attr1 > 0) return s;
break;
}
break;
case 8:
height = true;
String l = from_object + ".height==";
switch (attr2) {
case 8:
l += to_object + ".height";
if (attr1 > 0) return l;
break;
}
break;
}
return "7";
}
public String resolveType7(int attr1, int constant) {
switch (attr1) {
case 3:
top=true;
if (attr1 > 0)
return from_object + ".top=="+((constant >= 0) ? "" + constant : "" + constant) + "dp";
break;
case 4:
bottom=true;
if (attr1 > 0)
return from_object + ".bottom==" + to_object + ".height" + ((constant >= 0) ? "-" + constant : "+" + Math.abs(constant)) + "dp";
break;
case 5:
left=true;
if (attr1 > 0) return from_object + ".left==" + constant + "dp";
break;
case 6:
right=true;
if (attr1 > 0)
return from_object + ".right==" + to_object + ".width" + ((constant >= 0) ? "-" + constant : "+" + Math.abs(constant)) + "dp";
break;
}
return "8";
}
}
|
79bb5149abb471c91def1d0d423708f3a9037e44
|
[
"Java"
] | 3
|
Java
|
spbisya/CassowarylayoutIzya
|
d410efee51943155bab38d39386b2c33e9b69a60
|
c868c301841d5c298297da2aacbe8ca5d70ddb49
|
refs/heads/master
|
<repo_name>Maehmaciel/FuncCargo<file_sep>/CadastroFuncionariosEmpresa/src/java/Aula/CriaJson.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Aula;
import java.io.StringReader;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import javax.json.JsonWriter;
/**
*
* @author professor
*/
public class CriaJson {
public String transformaEmJson(Pessoa p)
{
//return "{nome:"+p.getNome()+",idade:"+p.getIdade()+"}";
/*JsonObjectBuilder construtor=Json.createObjectBuilder();
construtor.add("nome", p.getNome());
construtor.add("idade",p.getIdade());
JsonObject objeto= construtor.build();*/
JsonObject objeto=Json.createObjectBuilder().
add("nome",p.getNome()).
add("idade",p.getIdade()).
build();
return transformaEmJson(objeto);
}
public String transformaEmJson(JsonObject objeto)
{
StringWriter sw=new StringWriter(1000);
JsonWriter escritor=Json.createWriter(sw);
escritor.writeObject(objeto);
return sw.toString();
}
public Pessoa transformaEmPessoa(String json)
{
StringReader leitor=new StringReader(json);
JsonReader jr=Json.createReader(leitor);
JsonObject objeto=jr.readObject();
return transformaEmPessoa(objeto);
}
public Pessoa transformaEmPessoa(JsonObject objeto)
{
Pessoa p=new Pessoa();
p.setNome(objeto.getString("nome"));
p.setIdade(objeto.getInt("idade"));
return p;
}
public static void main(String[] args) {
CriaJson criador=new CriaJson();
Pessoa p=new Pessoa();
p.setIdade(30);
p.setNome("Thiago");
System.out.println(criador.transformaEmJson(p));
String tjson="{\"nome\":\"Pedro\",\"idade\":40}";
Pessoa p2=criador.transformaEmPessoa(tjson);
System.out.println("Nome: "+p2.getNome()+" idade: "+p2.getIdade());
}
}
|
d532fdb1245e6594f0b87cddae4e790f11fd5482
|
[
"Java"
] | 1
|
Java
|
Maehmaciel/FuncCargo
|
1e70d172b12470cdabfcb11a4238727e152b93e5
|
7512a639767fb2e3dfcd6ff46cedff4b9d5d6af9
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 2 Assignment"""
from datetime import datetime
import urllib2
import logging
import csv
import argparse
import sys
# 'http://s3.amazonaws.com/cuny-is211-spring2015/birthdays100.csv'
parser = argparse.ArgumentParser()
parser.add_argument('--url', help='display a url with a csv')
args = parser.parse_args()
logging.basicConfig(filename='errors.log', level=logging.ERROR)
logger = logging.getLogger('assignment2')
def downloadData(url=''):
'''
Takes in a string of url and returns info from it.
'''
response = urllib2.urlopen(url)
return response
def processData(info):
'''
Takes in CSV and returns dictionary with id as the key and
name and birthday in a tuple as the value
'''
csvFile = csv.reader(open(info))
dictInfo = {}
for row in csvFile:
idnum = row[0]
name = row[1]
date = row[2]
try:
bday = datetime.strptime(date, '%d/%m/%Y')
dictInfo[idnum] = (name, bday)
except ValueError:
logging.error(
'Error processing line #{0} for ID #{1}'.format(
int(idnum) + 1, idnum))
return dictInfo
def displayPerson(id, personData):
'''
If the ID number is valid, a sentence with information
is printed out.
'''
try:
bday = datetime.strftime(personData[id][1], '%Y-%m-%d')
print 'Person #{0} is {1} with a birthday of {2}.'.format(
id, personData[id][0], bday)
except:
print 'No user found with that id'
if not args.url:
sys.exit()
else:
try:
loop = True
while loop:
csvData = downloadData(args.url)
personData = processData(csvData)
idpick = int(raw_input('Pick an id number: '))
print idpick
if idpick > 0:
displayPerson(idpick, personData)
else:
loop = False
except URLError:
sys.exit()
|
96040ef716a262686fb326b9ace549fa0d71821c
|
[
"Python"
] | 1
|
Python
|
moshun8/IS211_Assignment2
|
9dc88459a21814f0a18c208f2164cb8f63f22f0c
|
b0cea9ad9b15880d8d2f963106b93f4dc400f12b
|
refs/heads/master
|
<file_sep>Flask
Flask-SQLAlchemy
SQLAlchemy>=0.6
Flask-WTF
Flask-OpenID
Flask-OAuth
Markdown
Flask-Assets
Flask-Mail
<file_sep># -*- coding: utf-8 -*-
from hashlib import md5
from werkzeug import generate_password_hash, check_password_hash
from lastuserapp.models import db, BaseMixin
from lastuserapp.utils import newid, newsecret, newpin
class User(db.Model, BaseMixin):
__tablename__ = 'user'
userid = db.Column(db.String(22), unique=True, nullable=False, default=newid)
fullname = db.Column(db.Unicode(80), default=None, nullable=False)
username = db.Column(db.Unicode(80), unique=True, nullable=True)
pw_hash = db.Column(db.String(80), nullable=True)
description = db.Column(db.Text, default='', nullable=False)
def __init__(self, password=<PASSWORD>, **kwargs):
self.password = <PASSWORD>
super(User, self).__init__(**kwargs)
def _set_password(self, password):
if password is None:
self.pw_hash = None
else:
self.pw_hash = generate_password_hash(password)
password = property(fset=_set_password)
def password_is(self, password):
if self.pw_hash is None:
return False
return check_password_hash(self.pw_hash, password)
def __repr__(self):
return '<User %s "%s">' % (self.username or self.userid, self.fullname)
def profileid(self):
if self.username:
return self.username
else:
return self.userid
def displayname(self):
return self.fullname or self.username or self.userid
def add_email(self, email, primary=False):
# TODO: Need better handling for primary email id
useremail = UserEmail(user=self, email=email, primary=primary)
db.session.add(useremail)
return useremail
def del_email(self, email):
setprimary=False
useremail = UserEmail.query.filter_by(user=self, email=email).first()
if useremail:
if useremail.primary:
setprimary=True
db.session.delete(useremail)
if setprimary:
for emailob in UserEmail.query.filter_by(user_id=self.id).all():
if emailob is not useremail:
emailob.primary=True
break
@property
def email(self):
"""
Returns primary email address for user.
"""
# Look for a primary address
useremail = UserEmail.query.filter_by(user_id=self.id, primary=True).first()
if useremail:
return useremail
# No primary? Maybe there's one that's not set as primary?
useremail = UserEmail.query.filter_by(user_id=self.id).first()
if useremail:
# XXX: Mark at primary. This may or may not be saved depending on
# whether the request ended in a database commit.
useremail.primary=True
return useremail
# This user has no email address. Return a blank string instead of None
# to support the common use case, where the caller will use unicode(user.email)
# to get the email address as a string.
return u''
class UserEmail(db.Model, BaseMixin):
__tablename__ = 'useremail'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref= db.backref('emails', cascade="all, delete-orphan"))
_email = db.Column('email', db.Unicode(80), unique=True, nullable=False)
md5sum = db.Column(db.String(32), unique=True, nullable=False)
primary = db.Column(db.Boolean, nullable=False, default=False)
def __init__(self, email, **kwargs):
super(UserEmail, self).__init__(**kwargs)
self._email = email
self.md5sum = md5(self._email).hexdigest()
@property
def email(self):
return self._email
email = db.synonym('_email', descriptor=email)
def __repr__(self):
return u'<UserEmail %s of user %s>' % (self.email, repr(self.user))
def __unicode__(self):
return unicode(self.email)
def __str__(self):
return str(self.__unicode__())
class UserEmailClaim(db.Model, BaseMixin):
__tablename__ = 'useremailclaim'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref = db.backref('emailclaims', cascade="all, delete-orphan"))
_email = db.Column('email', db.Unicode(80), nullable=True)
verification_code = db.Column(db.String(44), nullable=False, default=newsecret)
md5sum = db.Column(db.String(32), unique=True, nullable=False)
def __init__(self, email, **kwargs):
super(UserEmailClaim, self).__init__(**kwargs)
self.verification_code = newsecret()
self._email = email
self.md5sum = md5(self._email).hexdigest()
@property
def email(self):
return self._email
email = db.synonym('_email', descriptor=email)
def __repr__(self):
return u'<UserEmailClaim %s of user %s>' % (self.email, repr(self.user))
def __unicode__(self):
return unicode(self.email)
def __str__(self):
return str(self.__unicode__())
class UserPhone(db.Model, BaseMixin):
__tablename__ = 'userphone'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref = db.backref('phones', cascade="all, delete-orphan"))
primary = db.Column(db.Boolean, nullable=False, default=False)
_phone = db.Column('phone', db.Unicode(80), unique=True, nullable=False)
gets_text = db.Column(db.Boolean, nullable=False, default=True)
def __init__(self, phone, **kwargs):
super(UserPhone, self).__init__(**kwargs)
self._phone = phone
@property
def phone(self):
return self._phone
phone = db.synonym('_phone', descriptor=phone)
def __repr__(self):
return u'<UserPhone %s of user %s>' % (self.phone, repr(self.user))
def __unicode__(self):
return unicode(self.phone)
def __str__(self):
return str(self.__unicode__())
class UserPhoneClaim(db.Model, BaseMixin):
__tablename__ = 'userphoneclaim'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref = db.backref('phoneclaims', cascade="all, delete-orphan"))
_phone = db.Column('phone', db.Unicode(80), unique=True, nullable=False)
gets_text = db.Column(db.Boolean, nullable=False, default=True)
verification_code = db.Column(db.Unicode(4), nullable=False, default=newpin)
def __init__(self, phone, **kwargs):
super(UserPhoneClaim, self).__init__(**kwargs)
self.verification_code = newpin()
self._phone = phone
@property
def phone(self):
return self._phone
phone = db.synonym('_phone', descriptor=phone)
def __repr__(self):
return u'<UserPhoneClaim %s of user %s>' % (self.phone, repr(self.user))
def __unicode__(self):
return unicode(self.phone)
def __str__(self):
return str(self.__unicode__())
class PasswordResetRequest(db.Model, BaseMixin):
__tablename__ = 'passwordresetrequest'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id)
reset_code = db.Column(db.String(44), nullable=False, default=newsecret)
def __init__(self, **kwargs):
super(PasswordResetRequest, self).__init__(**kwargs)
self.reset_code = newsecret()
class UserExternalId(db.Model, BaseMixin):
__tablename__ = 'userexternalid'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref = db.backref('externalids', cascade="all, delete-orphan"))
service = db.Column(db.String(20), nullable=False)
userid = db.Column(db.String(250), nullable=False) # Unique id (or OpenID)
username = db.Column(db.Unicode(80), nullable=True)
oauth_token = db.Column(db.String(250), nullable=True)
oauth_token_secret = db.Column(db.String(250), nullable=True)
oauth_token_type = db.Column(db.String(250), nullable=True)
__table_args__ = ( db.UniqueConstraint("service", "userid"), {} )
__all__ = ['User', 'UserEmail', 'UserEmailClaim', 'PasswordResetRequest', 'UserExternalId',
'UserPhone', 'UserPhoneClaim']
<file_sep># -*- coding: utf-8 -*-
from flask import g
import flaskext.wtf as wtf
from lastuserapp.models import Permission, Resource, ResourceAction, getuser
from lastuserapp.utils import valid_username
class AuthorizeForm(wtf.Form):
"""
OAuth authorization form. Has no fields and is only used for CSRF protection.
"""
pass
class ConfirmDeleteForm(wtf.Form):
"""
Confirm a delete operation
"""
delete = wtf.SubmitField('Delete')
cancel = wtf.SubmitField('Cancel')
class RegisterClientForm(wtf.Form):
"""
Register a new OAuth client application
"""
title = wtf.TextField('Application title', validators=[wtf.Required()],
description="The name of your application")
description = wtf.TextAreaField('Description', validators=[wtf.Required()],
description="A description to help users recognize your application")
owner = wtf.TextField('Organization name', validators=[wtf.Required()],
description="Name of the organization or individual who owns this application")
website = wtf.html5.URLField('Application website', validators=[wtf.Required(), wtf.URL()],
description="Website where users may access this application")
redirect_uri = wtf.html5.URLField('Redirect URI', validators=[wtf.Required(), wtf.URL()],
description="OAuth2 Redirect URI")
notification_uri = wtf.html5.URLField('Notification URI', validators=[wtf.Optional(), wtf.URL()],
description="LastUser resource provider Notification URI. When another application requests access to "
"resources provided by this app, LastUser will post a notice to this URI with a copy of the access "
"token that was provided to the other application. Other notices may be posted too.")
resource_uri = wtf.html5.URLField('Resource URI', validators=[wtf.Optional(), wtf.URL()],
description="URI at which this application provides resources as per the LastUser Resource API")
allow_any_login = wtf.BooleanField('Allow anyone to login', default=True,
description="If your application requires access to be restricted to specific users, uncheck this")
class PermissionForm(wtf.Form):
"""
Create or edit a permission
"""
name = wtf.TextField('Permission name', validators=[wtf.Required()],
description='Name of the permission as a single word in lower case. '
'This is passed to the application when a user logs in. '
'Changing the name will not automatically update it everywhere. '
'You must reassign the permission to users who had it with the old name')
title = wtf.TextField('Title', validators=[wtf.Required()],
description='Permission title that is displayed to users')
description = wtf.TextAreaField('Description',
description='An optional description of what the permission is for')
def validate_name(self, field):
if not valid_username(field.data):
raise wtf.ValidationError("Name contains invalid characters.")
edit_id = getattr(self, 'edit_id', None)
existing = Permission.query.filter_by(name=field.data, allusers=True).first()
if existing and existing.id != edit_id:
raise wtf.ValidationError("A global permission with that name already exists")
existing = Permission.query.filter_by(name=field.data, user=g.user).first()
if existing and existing.id != edit_id:
raise wtf.ValidationError("You have another permission with the same name")
class UserPermissionAssignForm(wtf.Form):
"""
Assign permissions to a user
"""
username = wtf.TextField("User", validators=[wtf.Required()],
description = 'Lookup a user by their username or email address')
perms = wtf.SelectMultipleField("Permissions", validators=[wtf.Required()])
def validate_username(self, field):
existing = getuser(field.data)
if existing is None:
raise wtf.ValidationError, "User does not exist"
self.user = existing
class UserPermissionEditForm(wtf.Form):
"""
Edit a user's permissions
"""
perms = wtf.SelectMultipleField("Permissions", validators=[wtf.Required()])
class ResourceForm(wtf.Form):
"""
Edit a resource provided by an application
"""
name = wtf.TextField('Resource name', validators=[wtf.Required()],
description="Name of the resource as a single word in lower case. "
"This is provided by applications as part of the scope "
"when requesting access to a user's resources.")
title = wtf.TextField('Title', validators=[wtf.Required()],
description='Resource title that is displayed to users')
description = wtf.TextAreaField('Description',
description='An optional description of what the resource is')
siteresource = wtf.BooleanField('Site resource',
description='Enable if this resource is generic to the site and not owned by specific users')
trusted = wtf.BooleanField('Trusted applications only',
description='Enable if access to the resource should be restricted to trusted '
'applications. You may want to do this for sensitive information like billing data')
def validate_name(self, field):
if not valid_username(field.data):
raise wtf.ValidationError("Name contains invalid characters.")
edit_id = getattr(self, 'edit_id', None)
existing = Resource.query.filter_by(name=field.data).first()
if existing and existing.id != edit_id:
raise wtf.ValidationError("A resource with that name already exists")
class ResourceActionForm(wtf.Form):
"""
Edit an action associated with a resource
"""
name = wtf.TextField('Action name', validators=[wtf.Required()],
description="Name of the action as a single word in lower case. "
"This is provided by applications as part of the scope in the form "
"'resource/action' when requesting access to a user's resources. "
"Read actions are implicit when applications request just 'resource' "
"in the scope and do not need to be specified as an explicit action.")
title = wtf.TextField('Title', validators=[wtf.Required()],
description='Action title that is displayed to users')
description = wtf.TextAreaField('Description',
description='An optional description of what the action is')
def validate_name(self, field):
if not valid_username(field.data):
raise wtf.ValidationError("Name contains invalid characters.")
existing = ResourceAction.query.filter_by(name=field.data, resource=self.edit_resource).first()
if existing and existing.id != self.edit_id:
raise wtf.ValidationError("An action with that name already exists for this resource")
<file_sep># -*- coding: utf-8 -*-
from lastuserapp.models import db, User, BaseMixin
from lastuserapp.utils import newid, newsecret
class Client(db.Model, BaseMixin):
"""OAuth client applications"""
__tablename__ = 'client'
#: User who owns this client
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref = db.backref('clients', cascade="all, delete-orphan"))
#: Human-readable title
title = db.Column(db.Unicode(250), nullable=False)
#: Long description
description = db.Column(db.Text, nullable=False, default='')
#: Human-readable owner name
owner = db.Column(db.Unicode(250), nullable=False)
#: Website
website = db.Column(db.Unicode(250), nullable=False)
#: Redirect URI
redirect_uri = db.Column(db.Unicode(250), nullable=False)
#: Notification URI
notification_uri = db.Column(db.Unicode(250), nullable=True)
#: Resource URI
resource_uri = db.Column(db.Unicode(250), nullable=True)
#: Active flag
active = db.Column(db.Boolean, nullable=False, default=True)
#: Allow anyone to login to this app?
allow_any_login = db.Column(db.Boolean, nullable=False, default=True)
#: OAuth client key/id
key = db.Column(db.String(22), nullable=False, unique=True, default=newid)
#: OAuth client secret
secret = db.Column(db.String(44), nullable=False, default=newsecret)
#: Trusted flag: trusted clients are authorized to access user data
#: without user consent, but the user must still login and identify themself.
#: When a single provider provides multiple services, each can be declared
#: as a trusted client to provide single sign-in across the services
trusted = db.Column(db.Boolean, nullable=False, default=False)
class UserFlashMessage(db.Model, BaseMixin):
"""
Saved messages for a user, to be relayed to trusted clients.
"""
__tablename__ = 'userflashmessage'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref=db.backref("flashmessages", cascade="delete, delete-orphan"))
seq = db.Column(db.Integer, default=0, nullable=False)
category = db.Column(db.Unicode(20), nullable=False)
message = db.Column(db.Unicode(250), nullable=False)
class Resource(db.Model, BaseMixin):
"""
Resources are provided by client applications. Other client applications
can request access to user data at resource servers by providing the
`name` as part of the requested `scope`.
"""
__tablename__ = 'resource'
# Resource names are unique across client apps
name = db.Column(db.Unicode(20), unique=True, nullable=False)
client_id = db.Column(db.Integer, db.ForeignKey('client.id'), nullable=False)
client = db.relationship(Client, primaryjoin=client_id == Client.id,
backref = db.backref('resources', cascade="all, delete-orphan"))
title = db.Column(db.Unicode(250), nullable=False)
description = db.Column(db.Text, default='', nullable=False)
siteresource = db.Column(db.Boolean, default=False, nullable=False)
trusted = db.Column(db.Boolean, default=False, nullable=False)
class ResourceAction(db.Model, BaseMixin):
"""
Actions that can be performed on resources. There should always be at minimum
a 'read' action.
"""
__tablename__ = 'resourceaction'
name = db.Column(db.Unicode(20), nullable=False)
resource_id = db.Column(db.Integer, db.ForeignKey('resource.id'), nullable=False)
resource = db.relationship(Resource, primaryjoin=resource_id == Resource.id,
backref = db.backref('actions', cascade="all, delete-orphan"))
title = db.Column(db.Unicode(250), nullable=False)
description = db.Column(db.Text, default='', nullable=False)
# Action names are unique per client app
__table_args__ = ( db.UniqueConstraint("name", "resource_id"), {} )
class AuthCode(db.Model, BaseMixin):
"""Short-lived authorization tokens."""
__tablename__ = 'authcode'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id)
client_id = db.Column(db.Integer, db.ForeignKey('client.id'), nullable=False)
client = db.relationship(Client, primaryjoin=client_id == Client.id,
backref = db.backref("authcodes", cascade="all, delete-orphan"))
code = db.Column(db.String(44), default=newsecret, nullable=False)
_scope = db.Column('scope', db.Unicode(250), nullable=False)
redirect_uri = db.Column(db.Unicode(250), nullable=False)
used = db.Column(db.Boolean, default=False, nullable=False)
@property
def scope(self):
return self._scope.split(u' ')
@scope.setter
def scope(self, value):
self._scope = u' '.join(value)
scope = db.synonym('_scope', descriptor=scope)
def add_scope(self, additional):
if isinstance(additional, basestring):
additional = [additional]
self.scope = list(set(self.scope).union(set(additional)))
class AuthToken(db.Model, BaseMixin):
"""Access tokens for access to data."""
__tablename__ = 'authtoken'
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True) # Null for client-only
user = db.relationship(User, primaryjoin=user_id == User.id)
client_id = db.Column(db.Integer, db.ForeignKey('client.id'), nullable=False)
client = db.relationship(Client, primaryjoin=client_id == Client.id,
backref=db.backref("authtokens", cascade="all, delete-orphan"))
token = db.Column(db.String(22), default=newid, nullable=False, unique=True)
token_type = db.Column(db.String(250), default='bearer', nullable=False) # 'bearer', 'mac' or a URL
secret = db.Column(db.String(44), nullable=True)
_algorithm = db.Column('algorithm', db.String(20), nullable=True)
_scope = db.Column('scope', db.Unicode(250), nullable=False)
validity = db.Column(db.Integer, nullable=False, default=0) # Validity period in seconds
refresh_token = db.Column(db.String(22), default=newid, nullable=False)
# Only one authtoken per user and client. Add to scope as needed
__table_args__ = ( db.UniqueConstraint("user_id", "client_id"), {} )
def __init__(self, **kwargs):
super(AuthToken, self).__init__(**kwargs)
self.token = newid()
self.refresh_token = newid()
self.secret = newsecret()
@property
def scope(self):
return self._scope.split(u' ')
@scope.setter
def scope(self, value):
self._scope = u' '.join(value)
scope = db.synonym('_scope', descriptor=scope)
def add_scope(self, additional):
if isinstance(additional, basestring):
additional = [additional]
self.scope = list(set(self.scope).union(set(additional)))
@property
def algorithm(self):
return self._algorithm
@algorithm.setter
def algorithm(self, value):
if value is None:
self._algorithm = None
self.secret = None
elif value in ['hmac-sha-1', 'hmac-sha-256']:
self._algorithm = value
else:
raise ValueError, "Unrecognized algorithm '%s'" % value
algorithm = db.synonym('_algorithm', descriptor=algorithm)
class Permission(db.Model, BaseMixin):
__tablename__ = 'permission'
#: User who created this permission
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id,
backref = db.backref('permissions_created', cascade="all, delete-orphan"))
#: Name token
name = db.Column(db.Unicode(80), nullable=False)
#: Human-friendly title
title = db.Column(db.Unicode(250), nullable=False)
#: Description of what this permission is about
description = db.Column(db.Text, default='', nullable=False)
#: Is this permission available to all users and client apps?
allusers = db.Column(db.Boolean, default=False, nullable=False)
# This model's name is in plural because it defines multiple permissions within each instance
class UserClientPermissions(db.Model, BaseMixin):
__tablename__ = 'userclientpermissions'
# User who has these permissions
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship(User, primaryjoin=user_id == User.id, backref='permissions')
# Client app they are assigned on
client_id = db.Column(db.Integer, db.ForeignKey('client.id'), nullable=False)
client = db.relationship(Client, primaryjoin=client_id == Client.id,
backref=db.backref('permissions', cascade="all, delete-orphan"))
# The permissions as a string of tokens
permissions = db.Column(db.Unicode(250), default=None, nullable=False)
# Only one assignment per user and client
# TODO: Also define context for permission:
# a. User1 has permissions x, y (without context) in app1
# b. User1 has permissions a, b, c in context p in app1
__table_args__ = ( db.UniqueConstraint("user_id", "client_id"), {} )
__all__ = ['Client', 'UserFlashMessage', 'Resource', 'ResourceAction', 'AuthCode', 'AuthToken',
'Permission', 'UserClientPermissions']
|
96fb25022f7c3b2f7989ce40d9f7f74247845fb7
|
[
"Python",
"Text"
] | 4
|
Text
|
lifeeth/lastuser
|
b920462dede9322cb80f8466d451eddf41a4c44a
|
f1e31a5c14d8f31e07a1bc489a42a836fecc1729
|
refs/heads/master
|
<file_sep># 2020.12.01
# https://programmers.co.kr/learn/courses/30/lessons/42840
"""
문제 해결의 아이디어:
모의고사의 문제 번호를 1번학생(a), 2번학생(b), 3번학생(c)의 답안의 수로 나눈
나머지를 찾고, 이 나머지가 세 학생의 연속적인 답안의 인덱스에 해당한다는것을 생각하여 해결했다.
"""
def solution(answers):
answer = {'1':0, '2':0, '3':0}
a = [1, 2, 3, 4, 5]
b = [2, 1, 2, 3, 2, 4, 2, 5,]
c = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5,]
for idx, val in enumerate(answers):
a_check = idx % len(a)
b_check = idx % len(b)
c_check = idx % len(c)
if val == a[a_check]:
answer['1'] += 1
if val == b[b_check]:
answer['2'] += 1
if val == c[c_check]:
answer['3'] += 1
max_val = max(answer.values())
sol = []
for i in answer:
if answer[i] == max_val:
sol.append(int(i))
sol.sort()
return sol<file_sep>-- 최솟값 구하기
-- https://programmers.co.kr/learn/courses/30/lessons/59038
SELECT DATETIME AS '시간' FROM ANIMAL_INS ORDER BY DATETIME ASC LIMIT 1
-- 동물 수 구하기
-- https://programmers.co.kr/learn/courses/30/lessons/59406
SELECT COUNT(*) AS COUNT FROM ANIMAL_INS<file_sep># 2020.12.01
# https://programmers.co.kr/learn/courses/30/lessons/12903
"""
문제 해결의 아이디어:
글자의 수를 2로 나눈 나머지를 통해서 0일경우 짝수, 0이 아닐경우 홀수로 하여
인덱싱을 통해서 문제를 해결하였다.
"""
def solution(s):
div_s = len(s)/2
answer = 0
if len(s)%2 == 0:
answer = s[int(div_s-1):int(div_s+1)]
else:
answer = s[int(div_s-0.5)]
return answer<file_sep># 2020.12.05
# https://programmers.co.kr/learn/courses/30/lessons/12906
"""
문제 해결의 아이디어:
문제에서 주어진 리스트(arr)에서 첫번째 값을 리스트(answer)에 넣고,
반복문을 통해서 리스트(arr)의 2번째 값부터 이전 인덱스의 값과 같은지 확인하여
같지 않을 경우에만 리스트(answer)에 추가하여 반환했습니다.
"""
def solution(arr):
answer = []
answer.append(arr[0])
for i in range(1,len(arr)):
if arr[i] != arr[i-1]:
answer.append(arr[i])
return answer<file_sep># 2020.12.04
# https://programmers.co.kr/learn/courses/30/lessons/68935
"""
문제 해결의 아이디어:
10진법으로 주어지는 n을 3진법으로 바꾸고 앞뒤반전을 시키라고 했는데,
이 과정은 반복문을 사용하여 3으로 나눈 나머지를 문자열로 바꿔서 차례대로 더해주면 자연스럽게 처리가 된다.
"""
def solution(n):
num = n
temp = ''
while True:
if n < 3:
return n
val = divmod(num,3)
if val[0] >= 3:
num = val[0]
temp += str(val[1])
else:
temp += str(val[1])
temp += str(val[0])
break
reversed_num = str(int(temp))
sol = 0
length = len(reversed_num)-1
for i in reversed_num:
sol += int(i)*(3**length)
length -= 1
return sol<file_sep># 2020.12.07
# https://programmers.co.kr/learn/courses/30/lessons/12918
"""
문제 해결의 아이디어:
문자열로 "0123" 이렇게 s가 구성될수 있기에 int로 변환을 해주고, 그 값의 길이를 확인하여 적절한 반환값을 넘겨주었습니다.
만약에 s가 "a123"과 같이 문자가 섞인 값으로 구성되면 int로 형변환할때 오류를 발생시키기에 try, except 를 사용하여 처리했습니다.
새롭게 안것들:
isalpha함수: 문자열이 문자로 구성되어 있는지 아닌지를 확인하여 True 또는 False로 반환합니다.
isdigit함수: 문자열이 숫자로 구성되어 있는지 아닌지를 확인하여 True 또는 False로 반환힙니다.
"""
def solution(s):
try:
convert_s = int(s)
if len(str(convert_s)) == 4 or len(str(convert_s)) == 6:
return True
else:
return False
except Exception:
return False<file_sep># 2020.12.02
# https://programmers.co.kr/learn/courses/30/lessons/12901
# 풀이1
"""
문제 해결의 아이디어:
분명 파이썬이라면 달력에 관한 내장 라이브러리가 있을것이라 확신했기에 문제를 보자마자 라이브러리를 찾았습니다.
(파이썬의 내장라이브러리인 calendar를 사용하여 풀었습니다.)
다만 이렇게 풀려고, 코딩테스트를 하는것은 아니니 라이브러리 사용없이 푸는 풀이2를 추가합니다.
"""
import calendar
def solution(a, b):
dic = {'0':'MON','1':'TUE','2':'WED','3':'THU','4':'FRI','5':'SAT','6':'SUN'}
day = str(calendar.weekday(2016, a, b))
answer = dic[day]
return answer
# 풀이2
"""
문제 해결의 아이디어:
임의의 월(a), 일(b)에 대해서 각 달의 길이를 더하여 총 길이를 7(일주일)로 나누고
나머지를 이용하여 요일에 매칭하였습니다.
"""
def solution(a, b):
dic = {'1':'FRI','2':'SAT','3':'SUN','4':'MON','5':'TUE','6':'WED','0':'THU'}
day_end = {'1':31,'2':29,'3':31,'4':30,'5':31,'6':30,'7':31,'8':31,'9':30,'10':31,'11':30,'12':31}
day = 0
for month in range(1,a+1):
if month != a:
day += day_end[str(month)]
else:
day += b
key = str(day%7)
answer = dic[key]
return answer
<file_sep># https://programmers.co.kr/learn/courses/30/lessons/64061
"""
문제 해결의 아이디어:
반복문을 사용하여 moves로 받는 리스트를 순회하면서 가장 최상단부터 숫자를 뽑는다.
다음 반복문이 진행될때마다. 가장 끝에있는 숫자[-1]와 그 보다 한칸 앞에 있는 숫자[-2]를 비교하여
같으면 이 둘을 제거한다.
"""
def solution(board, moves):
answer = 0
temp =[]
for move in moves:
for row in board:
if row[move-1] != 0:
temp.append(row[move-1])
row[move-1]=0
if len(temp) >=2 and temp[-2] == temp[-1]:
temp.pop()
temp.pop()
answer += 2
break
return answer<file_sep>-- 모든 레코드 조회하기
-- https://programmers.co.kr/learn/courses/30/lessons/59034
SELECT * FROM ANIMAL_INS
-- 최댓값 구하기
-- https://programmers.co.kr/learn/courses/30/lessons/59415
SELECT DATETIME FROM ANIMAL_INS ORDER BY DATETIME DESC LIMIT 1
-- 역순 정렬하기
-- https://programmers.co.kr/learn/courses/30/lessons/59035
SELECT NAME,DATETIME FROM ANIMAL_INS ORDER BY ANIMAL_ID DESC
-- 아픈 동물 찾기
-- https://programmers.co.kr/learn/courses/30/lessons/59036
SELECT ANIMAL_ID,NAME FROM ANIMAL_INS WHERE INTAKE_CONDITION = 'SICK' ORDER BY ANIMAL_ID
-- 어린 동물 찾기
-- https://programmers.co.kr/learn/courses/30/lessons/59037
SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE INTAKE_CONDITION != 'Aged'
-- 동물의 아이디와 이름
-- https://programmers.co.kr/learn/courses/30/lessons/59403
SELECT ANIMAL_ID, NAME FROM ANIMAL_INS
-- 이름이 없는 동물의 아이디
-- https://programmers.co.kr/learn/courses/30/lessons/59039
SELECT ANIMAL_ID FROM ANIMAL_INS WHERE NAME IS NULL
-- 여러 기준으로 정렬하기
-- https://programmers.co.kr/learn/courses/30/lessons/59404
SELECT ANIMAL_ID, NAME, DATETIME FROM ANIMAL_INS ORDER BY NAME ASC, DATETIME DESC
-- 상위 n개 레코드
-- https://programmers.co.kr/learn/courses/30/lessons/59405
SELECT NAME FROM ANIMAL_INS ORDER BY DATETIME ASC LIMIT 1
-- 이름이 있는 동물의 아이디
-- https://programmers.co.kr/learn/courses/30/lessons/59407
SELECT ANIMAL_ID FROM ANIMAL_INS WHERE NAME IS NOT NULL<file_sep># 2020.12.06
# https://programmers.co.kr/learn/courses/30/lessons/12912
"""
문제 해결의 아이디어:
sum과 range를 활용하여 문제를 푼다.
"""
def solution(a, b):
if b>a:
answer = sum(range(a,b+1))
else:
answer = sum(range(b,a+1))
return answer<file_sep># https://programmers.co.kr/learn/courses/30/lessons/42576
"""
문제 해결의 아이디어:
내장 라이브러리 collections을 사용하여 풀었습니다.
"""
import collections
def solution(participant, completion):
participant = collections.Counter(participant)
completion = collections.Counter(completion)
player = list((participant - completion).keys())[0]
return player<file_sep># 2020.12.06
# https://programmers.co.kr/learn/courses/30/lessons/12910
"""
문제 해결의 아이디어:
나누어 떨어지면 나머지가 0인것을 활용하여 문제를 해결한다.
"""
def solution(arr, divisor):
answer = []
if divisor == 1:
arr.sort()
return arr
for i in arr:
if i%divisor == 0:
answer.append(i)
if len(answer) == 0:
answer.append(-1)
answer.sort()
return answer<file_sep># 2020.12.06
# https://programmers.co.kr/learn/courses/30/lessons/12916
"""
문제 해결의 아이디어:
반복문을 사용하여 같은 문제에서 주어진 글자면, 해당 글자를 키로 하는 딕셔너리의 값에 1을 더해주고
조건문을 사용하여 반환값을 결정한다.
"""
def solution(s):
dic = {'p':0, 'y':0}
for i in s:
if i == "p" or i == "P":
dic['p'] += 1
elif i == "y" or i == "Y":
dic['y'] += 1
if dic['p'] == dic['y']:
return True
elif dic['p'] != dic['y']:
return False<file_sep># https://programmers.co.kr/learn/courses/30/lessons/68644
"""
문제 해결의 아이디어:
반복문을 통해서 리스트내의 숫자를 선택합니다. 인덱스와 값을 사용하기 위해서 enumerate를 사용하고,
선택한 숫자와 다른 인덱스의 값들을 차례대로 더해서 빈 배열(answer)에 담습니다.
중복을 제거하기 위해서 set()자료구조를 사용하고, 리스트로 반환합니다.
"""
def solution(numbers):
answer = []
for key, value in enumerate(numbers):
if key == len(numbers)-1:
pass
else:
for index in range(key+1, len(numbers)):
answer.append(value + numbers[index])
answer = list(set(answer))
answer.sort()
return answer<file_sep># https://programmers.co.kr/learn/courses/30/lessons/42748
"""
문제 해결의 아이디어:
리스트는 순회가 가능한 자료구조이며, 리스트 안에 리스트를 넣어서도 순회가 가능함
commands로 리스트를 받고, 내부의 리스트를 선택하여 인덱싱을 통해서 숫자를 선택합니다.
"""
def solution(array, commands):
answer = []
for data_list in commands:
pick = array[data_list[0]-1:data_list[1]]
pick.sort()
answer.append(pick[data_list[2]-1])
return answer<file_sep># coding-test
## 설명
프로그래머스와 리트코드에서 코딩테스트 문제를 풀고, 문제해결의 아이디어와 문제풀이를 업로드하는 저장소입니다.
* 프로그래머스 https://programmers.co.kr
* 리트코드 https://leetcode.com
<file_sep># https://programmers.co.kr/learn/courses/30/lessons/42862
"""
문제 해결의 아이디어:
체육복을 잃어버린 학생이 체육복을 가져왔을경우 본인이 입어야 하기에 빌려줄수 없다.
따라서 lost로 받는 리스트와 reserve로 받는 리스트에 같은 숫자(학생)가 있는지 확인하여 제거하고
lost로 받는 리스트에 있는 학생을 반복문으로 순회하면서 reserve로 받는 리스트내에 1작은 숫자가 있는지 확인하고
없으면 1큰 숫자가 있는지 확인하면서 최대값(n)을 구한다.
"""
def solution(n, lost, reserve):
n -= len(lost)
dupl=[i for i in lost if i in reserve]
n+=len(dupl)
for lost_num in dupl:
reserve.remove(lost_num)
lost.remove(lost_num)
for lost_num in lost:
if lost_num-1 in reserve:
reserve.remove(lost_num-1)
n+=1
elif lost_num+1 in reserve:
reserve.remove(lost_num+1)
n+=1
return n
|
f465aef44343eace66ac741c3cdf76897c5177db
|
[
"Markdown",
"SQL",
"Python"
] | 17
|
Python
|
taeha7b/coding-test
|
f0cdcf46239fa71b9dca5dbd29d8c69ed0ab1f77
|
7cdf74b177f969707db3d7d7133830e3fbeafbc4
|
refs/heads/master
|
<repo_name>ComicScrip/express-contact<file_sep>/index.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const nodemailer = require('nodemailer');
const PORT = process.env.PORT || 5000;
const app = express();
app.use(express.json());
app.use(cors());
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.GMAIL_ACCOUNT,
pass: <PASSWORD>.GMAIL_<PASSWORD>,
},
});
app.post('/contact', (req, res) => {
const { name, email, message } = req.body;
const { apiKey } = req.query;
if (apiKey !== process.env.API_KEY) {
res.status(401);
res.json({ error: 'wrong API key' });
}
if (!name) {
res.status(422);
return res.json({ error: 'name is empty' });
}
if (!email) {
res.status(422);
return res.json({ error: 'email is empty' });
}
if (!message) {
res.status(422);
return res.json({ error: 'message is empty' });
}
const mailOptions = {
from: process.env.GMAIL_ACCOUNT,
to: process.env.GMAIL_ACCOUNT,
subject: `Demande de contact de ${name}`,
text: `${name} (${email}) vous a fait une demande de contact : \n\n${message}`,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
console.error(error);
res.status(500);
res.json({
errorMessage:
'There was a problem while sending the contact request email to the admin',
});
} else {
console.log('Email sent: ' + info.response);
res.json({ message: 'demande de contact envoyée avec succès' });
}
});
});
app.listen(PORT, () => {
console.log(`server listenting on port ${PORT}`); // eslint-disable-line
});
|
368c6b0f73fed3642a09d04903c58ece5894afe5
|
[
"JavaScript"
] | 1
|
JavaScript
|
ComicScrip/express-contact
|
fded4aaf50fe7ad8ff7247cae98dbf5d910593d9
|
c2329f74300b6fca2e5aebaa0b27424054bcf9f5
|
refs/heads/master
|
<repo_name>afewvowels/CPP-PRG-03-17-Math-Tutor<file_sep>/PRG-3-17-Math-Tutor/main.cpp
//
// main.cpp
// PRG-3-17-Math-Tutor
//
// Created by <NAME> on 10/6/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
// Write a program that can be used as a math tutor for a young student. The program
// should display two random numbers to be added, such as
// 247
// +129
// ----
// The program should then pause while the student works on the problem. When the
// student is ready to check the answer, he or she can press a key and the program will
// display the correct solution.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 999;
int intNumber1;
int intNumber2;
int intNumberGuess;
int intNumberSum;
unsigned seed = time(0);
srand(seed);
intNumber1 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
intNumber2 = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
intNumberSum = intNumber1 + intNumber2;
cout << setw(4) << right << intNumber1 << endl;
cout << "+" << setw(3) << right << intNumber2 << endl;
cout << "----" << endl;
cin >> intNumberGuess;
cout << setw(4) << right << intNumberSum << endl;
return 0;
}
|
950860ed26920e06e7763961e4b3f0d8e7f3185c
|
[
"C++"
] | 1
|
C++
|
afewvowels/CPP-PRG-03-17-Math-Tutor
|
1bba4316bc6e5592eee562a01095afaa15eb50cd
|
51682e28630b2b9dabfdd5d458f70474219554a9
|
refs/heads/master
|
<repo_name>cardro/flaskTest<file_sep>/flaskr/__init__.py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
@app.route('/hello')
def hello():
return 'Hello, World!'
from flaskr import t11
@app.route('/ryan')
def ryan():
return t11.test1()
return app<file_sep>/flaskr/t11.py
from flask import current_app
def test1():
return "yolo"<file_sep>/flaskr/hello.py
import os
from flask import Flask
app = Flask(__name__, instance_relative_config=True)
# def create_app(test_config=None):
# # create and configure the app
# app = Flask(__name__, instance_relative_config=True)
# @app.route('/hello')
# def hello():
# return 'Hello, World!'
# from flaskr import t11
@app.route('/ryan')
def ryan():
return "cool"
|
497277a2217a99f3a8f0a943855dc7a305a4752e
|
[
"Python"
] | 3
|
Python
|
cardro/flaskTest
|
3554c45eb5579c843d7a464ae9bbc32359b7c2ba
|
d73f157d291f1625555d2fbed6fdba74de10b13a
|
refs/heads/master
|
<repo_name>ankitanallana/Bash-Scripts<file_sep>/delete_repos_org.sh
#!/bin/bash
orgname="$1"
filename="$2"
exec 3< $filename
while [[ ! $orgname ]]
do
read -p "Please enter an organisation under your organisation " orgname
done
while [[ ! $filename ]]
do
read -p "Please enter a filename to read the list of repos from " filename
done
echo $orgname
input_flag=""
if [[ $filename ]]
then
read -p "Press i to enter into interactive mode or any key to delete all repos in $filename : " input_flag
fi
if [ "$input_flag" == "i" ]
then
while IFS= read -u 3 -r repo
do
read -p "Do you want to delete repo $repo? Enter y/n : " ip
if [ "$ip" == "y" ]
then
curl -i -X DELETE -H 'Authorization: token {token}' 'https://{hostname}/api/v3/repos/'$orgname'/'$repo
fi
done
else
echo "Deleting all repos in "$filename
while IFS= read -r repo
do
curl -i -X DELETE -H 'Authorization: token {token}' 'https://{hostname}/api/v3/repos/'$orgname'/'$repo
done < "$filename"
fi
echo "End of script"<file_sep>/add_dirs.sh
#!/bin/bash
#Outer loop for 4 pages of results (we have 120 repos)
for count in {1..4}
do
echo PAGE $count
for i in {0..29}
do
#retrieve all repos by page. By default, 30 results are returned PER PAGE
clone_url=$(curl -H 'Authorization: token <token>' https://hostname/api/v3/orgs/{org-name}/repos?page=$count | jq ".[$i]" | jq '.clone_url')
repo_name=$(curl -H 'Authorization: token <token>' https://hostname/api/v3/orgs/{org-name}/repos?page=$count | jq ".[$i]" | jq '.name')
#remove quotes from both strings
repo_name=${repo_name#\"}
repo_name=${repo_name%\"}
echo REPO $repo_name
clone_url=${clone_url#\"}
clone_url=${clone_url%\"}
echo CLONE URL $clone_url
#pick a location of your choice
cd /
cd Users/{YourName}/Desktop
mkdir MSD_Fall2017
cd MSD_Fall2017/
#clone the repository to your local
git clone $clone_url
echo CLONED $repo_name
#create directories inside repos
cd $repo_name
mkdir HW1
echo "Place Homework 1 in this directory" > hw1/readme.txt
mkdir HW2
echo "Place Homework 2 in this directory" > hw2/readme.txt
mkdir HW3
echo "Place Homework 3 in this directory" > hw3/readme.txt
mkdir HW4
echo "Place Homework 4 in this directory" > hw4/readme.txt
mkdir HW5
echo "Place Homework 5 in this directory" > hw5/readme.txt
git add -A
git commit -m "Created directories for Homeworks"
git push
done
done
#end
<file_sep>/sample_bash.sh
#!/bin/bash
echo Will now create repos within organization
echo Creating repos section 1
name="student-10"
for i in {1..9}
do
repo_name=$name$i
#echo $repo_name
curl -i -H 'Authorization: token <token>' -d '{"name": "'"$repo_name"'","auto_init": true,"private": true}' "https://hostname/api/v3/orgs/{org-name}/repos" >> output_log.txt
echo created $repo_name
done
name="student-1"
for i in {10..60}
do
repo_name=$name$i
#echo $repo_name
curl -i -H 'Authorization: token <token>' -d '{"name": "'"$repo_name"'","auto_init": true,"private": true}' "https://hostname/api/v3/orgs/{org-name}/repos" >> output_log.txt
echo created $repo_name
done
echo Creating repos section 2
name="student-20"
for i in {1..9}
do
repo_name=$name$i
#echo $repo_name
curl -i -H 'Authorization: token <token>' -d '{"name": "'"$repo_name"'","auto_init": true,"private": true}' "https://hostname/api/v3/orgs/{org-name}/repos" >> output_log.txt
echo created $repo_name
done
name="student-2"
for i in {10..60}
do
repo_name=$name$i
#echo $repo_name
curl -i -H 'Authorization: token <token>' -d '{"name": "'"$repo_name"'","auto_init": true,"private": true}' "https://hostname/api/v3/orgs/{org-name}/repos" >> output_log.txt
echo created $repo_name
done
echo End of program Please check log
<file_sep>/README.md
# README.md
This script was used to create repos within an organization under a GitHub enterprise account.
To use this script, you first need an OAuth token. This can be obtained by opening up your terminal and executing the following command:
`curl -i -u <username> -d '{"scopes":["repo","user"], "note":"getting-started"}' https://hostname/api/v3/authorizations`
where:
* `<username>` is your username within the organisation
* `hostname` is your enterprise GitHub URL
* Parameters for `scopes` can be found [here](https://developer.github.com/apps/building-integrations/setting-up-and-registering-oauth-apps/about-scopes-for-oauth-apps/)
The OAuth token is generated and displayed just **ONCE**. Please treat this as a password (since this uniquely authenticates you) and store it somewhere safe.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
### sample_script.sh
At lines 13, 23, 35, 45 please make note of the arguments.
* `<token>` is where you replace with the OAuth token that you obtained in the previous step
* `{org-name}` is the organisation where you wish to create your repositories.
* `hostname` is your GitHub Enterprise URL
Output generated by the cURL commands have been saved in a file called `output_log.txt`
To run this file, simply navigate to the path where the file is present and execute the following command:
`sh sample_script.sh`
The [GitHub Developer Guide](https://developer.github.com/v3/guides/getting-started/) was one of the most helpful resources !
|
f0e193d045e5dcf99683668ae4d5192fcbb689da
|
[
"Markdown",
"Shell"
] | 4
|
Shell
|
ankitanallana/Bash-Scripts
|
72267e6ba002078d104de0ccc219f2e2ced8208f
|
dea5939c49a84b7169f4ac9cf997a7d58ea913b5
|
refs/heads/master
|
<repo_name>alencosoft/FitbodTest-GreggBaron<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.fitbod.my.test"
minSdkVersion 25
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:27.1.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.0.1'
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
testImplementation 'org.mockito:mockito-core:2.13.0'
testImplementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
testImplementation 'org.mockito:mockito-inline:2.13.0'
testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
}
task copyResourcesToClasses(type: Copy) {
from "${projectDir}/src/test/resources"
into "${buildDir}/intermediates/javac/debug/compileDebugJavaWithJavac/classes/com/fitbod/my/test"
}
<file_sep>/app/src/main/java/com/fitbod/my/test/ExerciseListAdapter.kt
package com.fitbod.my.test
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
class ExerciseListAdapter(
private val context: Context,
private var dataSource: MutableMap<String,
MutableList<String>>) : BaseAdapter() {
// Inflater object framework base class
private val inflater: LayoutInflater
= context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getItem(position: Int): MutableList<String> {
val dataSourceKeys : MutableSet<String> = dataSource.keys
return dataSource[dataSourceKeys.elementAt(position)] as MutableList<String>
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
// Get view for row item
val rowView = inflater.inflate(R.layout.exercise_list_view, parent, false)
// Exercise Name
val exerciseNameTextView = rowView.findViewById(R.id.exercise_name) as TextView
// Exercise Number of Records
val exerciseNumRecordsTextView = rowView.findViewById(R.id.exercise_num_records) as TextView
// RM Lbs Number
val rmLbsNumberTextView = rowView.findViewById(R.id.rm_lbs_number) as TextView
// rm_lbs_label (Literally, just "lbs")
val rmLbsLabelTextView = rowView.findViewById(R.id.rm_lbs_lable) as TextView
val listItem: List<String>? = getItem(position)
// Populate the various textFields
if (listItem != null) {
exerciseNameTextView.text = listItem[0]
var exerciseNumRecords : String = listItem[2] + " " +
this.context.getResources().getString(R.string.rm_record)
if(listItem[2].toInt() > 1) {
exerciseNumRecords += this.context.getResources().getString(R.string.plural)
}
exerciseNumRecordsTextView.text = exerciseNumRecords
rmLbsNumberTextView.text = listItem[1]
rmLbsLabelTextView.text = this.context.getResources().getString(R.string.lbs_literal)
}
return rowView
}
// Always a good idea to refresh the adapter when new data arrives
fun changeDataSource(newDataSource : MutableMap<String, MutableList<String>>) {
dataSource = newDataSource
this.notifyDataSetChanged()
}
// These are NOT needed but the compiler complains since it's a requirement
// of base interface "adapter" that the base class "BaseAdapter" implements. uggh
override fun getCount(): Int { return dataSource.size }
override fun getItemId(position: Int): Long { return position.toLong() }
}<file_sep>/app/src/main/java/com/fitbod/my/test/ChartActivity.kt
package com.fitbod.my.test
import android.content.Context
import android.content.Intent
import android.graphics.Canvas
import android.os.Bundle
import android.support.v7.app.AppCompatActivity;
import android.view.Menu
import android.view.View
import kotlinx.android.synthetic.main.activity_chart.*
// The intent used in MainActivity to launch this activity
fun Context.chartActivityIntent(headerArrayValues : ArrayList<String>): Intent {
return Intent(this, ChartActivity::class.java).apply {
putExtra(HEADER_VALUES, headerArrayValues)
}
}
private const val HEADER_VALUES = "headerArrayValues"
class ChartActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chart)
// From MainActivity
val headerArrayValues : ArrayList<String> = intent.getStringArrayListExtra(HEADER_VALUES)
val exerciseName = headerArrayValues[0]
setSupportActionBar(chart_toolbar)
supportActionBar?.title = exerciseName
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Init all of the Views
val chartFragmentLayout = findViewById(R.id.fragment) as android.support.constraint.ConstraintLayout
val my_canvas = myCanvas(this)
my_canvas.addHeaderArray(headerArrayValues)
chartFragmentLayout.addView(my_canvas)
}
// Dummy options menu to display the icon
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
class myCanvas(context: Context) : View(context) {
private lateinit var mHeaderArrayValues : ArrayList<String>
fun addHeaderArray(headerArrayValues : ArrayList<String>) {
mHeaderArrayValues = headerArrayValues
mHeaderArrayValues.add(context.getResources().getString(R.string.lbs_literal))
}
// We don't want any conditionals or helper methods. To do so would mean we'd have to Unit Test
// this class which we don't want to do.
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// The 'brains' behind the activity's positioning
val mChartPositionCalculator : IChartCalc = ChartPositionCalculator(
context,
mHeaderArrayValues,
canvas
)
// Draw Header Text
mChartPositionCalculator.drawHeaderText()
// Draw the Left Labels (RM Weights) and Horizontal Lines
for(idx in 0..3) {
mChartPositionCalculator.drawLeftLabel(idx)
mChartPositionCalculator.drawHorizontalLine(idx)
}
// Draw the Bottom Labels (Dates) and Vertical Lines
for(idx in 0..4) {
mChartPositionCalculator.drawBottomLabel(idx)
mChartPositionCalculator.drawVerticalLine(idx)
}
// Draw the Plotted graph circles (Values) and connecting lines
mChartPositionCalculator.drawPlottedCirclesLines()
}
}
}
<file_sep>/app/src/main/java/com/fitbod/my/test/ChartPositionCalculator.kt
package com.fitbod.my.test
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
// The Header Array Values
private const val HEADER_EXERCISE_NAME : Int = 0
private const val HEADER_ONE_REP_MAX_WEIGHT : Int = 1
private const val HEADER_ONE_REP_MAX_COUNT : Int = 2
private const val HEADER_LBS_STRING_LITERAL : Int = 3
// The 'gutter' white space between the bottom labels (ie; the Textfields under the graph)
private const val MIN_SPACE_ALLOWED_BETWEEN_TEXTFIELDS : Int = 40
/**
* The interface which only exposes certain public methods. Every object/class that uses this class
* should be of type IChartCalc
*/
interface IChartCalc {
fun drawLeftLabel(whichone : Int)
fun drawHorizontalLine(whichone: Int)
fun drawBottomLabel(whichone : Int)
fun drawVerticalLine(whichone : Int)
fun drawHeaderText()
fun drawPlottedCirclesLines()
}
class ChartPositionCalculator constructor(
context : Context,
headerArrayValues : ArrayList<String>,
canvas : Canvas) : IChartCalc {
// The Header data (similar to the list in MainActivity)
private val mHeaderArrayValues : ArrayList<String> = headerArrayValues
// The canvas and context objects from ChartActivity
private val mCanvas : Canvas = canvas
private val mContext : Context = context
// Component position arrays (Specs)
private var mGraphSpecs : ComponentSpecs = ComponentSpecs(context)
private var mGutterAboveGraphSpecs : ComponentSpecs = ComponentSpecs(context)
private var mGutterBelowGraphSpecs : ComponentSpecs = ComponentSpecs(context)
private var mGutterLeftGraphSpecs : ComponentSpecs = ComponentSpecs(context)
private var mMarginSpecs : ComponentSpecs = ComponentSpecs(context)
private var mCanvasSpecs : ComponentSpecs = ComponentSpecs(context)
// The Header labels
private var mHeaderLabels : MutableList<String> = mutableListOf()
private var mHeaderLabelsSpecs : MutableList<ComponentSpecs> = mutableListOf()
// The Graph labels (left and bottom of Graph)
private var mGraphLabelsBottom : MutableList<String> = mutableListOf()
private var mGraphLabelsBottomSpecs : MutableList<ComponentSpecs> = mutableListOf()
private var mGraphLabelsLeft : MutableList<Int> = mutableListOf()
private var mGraphLabelsLeftFinal : MutableList<String> = mutableListOf()
private var mGraphLabelsLeftSpecs : MutableList<ComponentSpecs> = mutableListOf()
// Is device orientation portrait or landscape?
private var mIsDeviceOrientationPortrait : Boolean = true
// Represents the 'weight' values that are evenly spaced for the Left Label strings
private var mLeftLabelSpacingValue : Int = 0
// The graph lines, plotted lines and plotted circles
private var mGraphLineSpecs : ComponentSpecs = ComponentSpecs(context)
private var mPlottedLineSpecs : ComponentSpecs = ComponentSpecs(context)
private var mPlottedCircleSpecs : ComponentSpecs = ComponentSpecs(context)
init {
startCalculations()
}
/** The initial chart data comes from the DataSingleton class. It's raw form is a MutableMap:
*
* Example: {Sep 15=270, Sep 21=275, Sep 28=280, Oct 4=280, Oct 11=285}
*
* This map is converted into 2 separate arrays with their raw form looking like this:
*
* - Bottom Labels: [Sep 15, Sep 21, Sep 28, Oct 4, Oct 11]
* - Left Labels: [270, 275, 280, 280, 285]
*
* And, finally, the displayed 'Left' labels look like this:
*
* - Final Left Labels: [270 lbs, 275 lbs, 280 lbs, 285 lbs]
*
* The layout process is:
*
* STEP 1: Set the various class objects/variables.
* STEP 2: Set the specs for 'margins' and 'gutters' (both horizontal and vertical).
* STEP 3: Set Left Label text and specs
* STEP 4: Set Header label text and specs
* STEP 5: Make the remaining space fit for the Bottom Labels (or adjust margins/gutters/text size
* to make it all fit).
* STEP 6: Set initial heights of Header textFields and Graph.
* STEP 7: Finally, make the vertical dimensions fit total height
* STEP 8: Drink champagne as we're done! :)
*/
private fun startCalculations() {
// STEP 1: Set the various class objects/variables
setGraphData(mHeaderArrayValues[HEADER_EXERCISE_NAME])
setCanvasHeightAndWidth()
setGraphLineSpecs()
setPlottedLineAndCircleSpecs()
// STEP 2: Set margin and gutter specs
setMarginAndGutterSpecs()
// STEP 3: Set Left Label text and specs
setLeftLabelFinalText()
setAllLabelInitSpecs()
// STEP 4: Set Header label text and specs
setHeaderLabelTextAndSpecs()
// STEP 5: Make the remaining space fit for the Bottom Labels (or adjust margins/gutters/text size
// to make it all fit).
setGraphHorizontalSize()
makeHorizontalLayoutFit()
// STEP 6: Calculate initial heights
setGraphHeight()
// STEP 7: Make the vertical dimensions fit total height
makeVerticalLayoutFit()
}
/**
* Break down the mutable map of chart data into X and Y axis values
* An example of one item looks like this: 'Sep 15=270'
*/
private fun setGraphData(exerciseName : String) {
val graphData: MutableMap<String, Int> = DataSingleton.getInstance().doGetGraphData(exerciseName)
graphData.forEach {
mGraphLabelsBottom.add(it.key)
mGraphLabelsLeft.add(it.value)
}
}
/**
* Easier to store these vales than to continue calling the framework for the device drawable size.
*/
private fun setCanvasHeightAndWidth() {
mCanvasSpecs.setAllPositions(0, 0, mCanvas.getHeight(), mCanvas.getWidth())
// Since we have the height/width values let's set the device orientation now.
// NOTE: The default orientation is set to 'true'
if(mCanvasSpecs.getHeight() < mCanvasSpecs.getWidth()) {
mIsDeviceOrientationPortrait = false
}
}
/**
* The Graph lines
*/
private fun setGraphLineSpecs() {
mGraphLineSpecs.setPaintObject(PAINT_GRAPH_GRID_LINES)
}
/**
* The plotted lines and circles
*/
private fun setPlottedLineAndCircleSpecs() {
mPlottedLineSpecs.setPaintObject(PAINT_PLOTTED_LINES)
mPlottedCircleSpecs.setPaintObject(PAINT_PLOTTED_CIRCLES)
}
/**
* 4 margins, of course, and 3 gutters (above, left and below graph).
* I came up with these values based on the provided mockup.
*/
private fun setMarginAndGutterSpecs() {
mMarginSpecs.setAllPositions(
0,
0,
(.05 * mCanvasSpecs.getWidth()).toInt(),
(.05 * mCanvasSpecs.getWidth()).toInt())
mGutterAboveGraphSpecs.setAllPositions(
0,
0,
(.05 * mCanvasSpecs.getWidth()).toInt(),
(.05 * mCanvasSpecs.getWidth()).toInt())
mGutterLeftGraphSpecs.setAllPositions(
0,
0,
(.05 * mCanvasSpecs.getWidth()).toInt(),
(.05 * mCanvasSpecs.getWidth()).toInt())
mGutterBelowGraphSpecs.setAllPositions(
0,
0,
(.05 * mCanvasSpecs.getWidth()).toInt(),
(.05 * mCanvasSpecs.getWidth()).toInt())
}
/**
* This is probably the most important part of calculating the chart layout. Each of the Left labels
* (below graph labels) must fit in the space available with some 'gutter' space between the labels so they
* don't just appear like one long string of text.
*/
private fun setLeftLabelFinalText() {
val maxWeightValue = mGraphLabelsLeft.max() as Int
var minWeightValue = mGraphLabelsLeft.min() as Int
// Set the Left Label text strings so that each one is equally spaced in value. The Left label
// value difference between the max and min must be divisible by 3 and 5 (or 15)
do {
minWeightValue--
} while ((maxWeightValue - minWeightValue).rem(15) != 0)
// Now store the calculated Left label values (strings)
mLeftLabelSpacingValue = ((maxWeightValue - minWeightValue) / 3).toInt()
for (idx in 0..3) {
mGraphLabelsLeftFinal.add(
(mGraphLabelsLeft.max() as Int -
(mLeftLabelSpacingValue * idx)).toString() +
" " +
mContext.getResources().getString(R.string.lbs_literal))
}
}
/**
* The initial specifications for Left Labels
*/
private fun setAllLabelInitSpecs() {
// Left labels
for (idx in 0..3) {
mGraphLabelsLeftSpecs.add(ComponentSpecs(mContext))
mGraphLabelsLeftSpecs[idx].setPaintObject(PAINT_LABEL_TEXT)
mGraphLabelsLeftSpecs[idx].setTextSize(52f)
mGraphLabelsLeftSpecs[idx].setAllPositions(0, mMarginSpecs.getWidth(), 0, 0)
}
// Bottom Labels
for (idx in 0..4) {
mGraphLabelsBottomSpecs.add(ComponentSpecs(mContext))
mGraphLabelsBottomSpecs[idx].setPaintObject(PAINT_LABEL_TEXT)
mGraphLabelsBottomSpecs[idx].setTextSize(52f)
mGraphLabelsBottomSpecs[idx].setAllPositions(0, 0, 0, 0)
}
}
/**
* Set the Header label positioning and strings
*/
private fun setHeaderLabelTextAndSpecs() {
// Set the 4 text strings
mHeaderLabels.add(HEADER_EXERCISE_NAME, mHeaderArrayValues[HEADER_EXERCISE_NAME])
mHeaderLabels.add(HEADER_ONE_REP_MAX_WEIGHT, mHeaderArrayValues[HEADER_ONE_REP_MAX_WEIGHT])
// We need to make adjustments for the 'Number of RM Records' text
var exerciseNumRecords: String = mHeaderArrayValues[HEADER_ONE_REP_MAX_COUNT] + " " +
mContext.getResources().getString(R.string.rm_record)
if (mHeaderArrayValues[HEADER_ONE_REP_MAX_COUNT].toInt() > 1) {
exerciseNumRecords += mContext.getResources().getString(R.string.plural)
}
mHeaderLabels.add(HEADER_ONE_REP_MAX_COUNT, exerciseNumRecords)
mHeaderLabels.add(HEADER_LBS_STRING_LITERAL, mContext.getResources().getString(R.string.lbs_literal))
// Add all 4 textField specs
for(idx in 0..3) { mHeaderLabelsSpecs.add(ComponentSpecs(mContext)) }
// Initialize all 4 paint specs
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].setPaintObject(PAINT_HEADER_TEXT_LARGE)
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].setPaintObject(PAINT_HEADER_TEXT_LARGE)
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].setPaintObject(PAINT_HEADER_TEXT_SMALL)
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].setPaintObject(PAINT_HEADER_TEXT_SMALL)
setTextSizeForAllLabels(52f)
// Initialize all 4 position specs
// 1) Exercise Name
var bounds = Rect()
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getPaintObject().getTextBounds(
mHeaderLabels[HEADER_EXERCISE_NAME],
0, (mHeaderLabels[HEADER_EXERCISE_NAME]).toString().length,
bounds)
var deviceOrientationAdjustmentHeight : Double = 1.0
if(mIsDeviceOrientationPortrait) {
deviceOrientationAdjustmentHeight = 1.5
}
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].setAllPositions(
(mMarginSpecs.getHeight() * deviceOrientationAdjustmentHeight).toInt() + (bounds.height() / 2),
mMarginSpecs.getWidth(),
0,
0)
// 2) RM Max Weight
bounds = Rect()
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].getPaintObject().getTextBounds(
mHeaderLabels[HEADER_ONE_REP_MAX_WEIGHT],
0, (mHeaderLabels[HEADER_ONE_REP_MAX_WEIGHT]).toString().length,
bounds)
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].setAllPositions(
(mMarginSpecs.getHeight() * deviceOrientationAdjustmentHeight).toInt() + (bounds.height() / 2),
mCanvasSpecs.getWidth() - mMarginSpecs.getWidth() - bounds.width(),
0,
0)
// 3) RM Count
val boundsOfExerciseNameTextField = Rect()
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getPaintObject().getTextBounds(
mHeaderLabels[HEADER_EXERCISE_NAME],
0, (mHeaderLabels[HEADER_EXERCISE_NAME]).toString().length,
boundsOfExerciseNameTextField)
bounds = Rect()
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].getPaintObject().getTextBounds(
mHeaderLabels[HEADER_ONE_REP_MAX_COUNT],
0, (mHeaderLabels[HEADER_ONE_REP_MAX_COUNT]).toString().length,
bounds)
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].setAllPositions(
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getTop() +
boundsOfExerciseNameTextField.height() +
(bounds.height() * .25).toInt(),
mMarginSpecs.getWidth(),
0,
0)
// 4) 'lbs' string literal
bounds = Rect()
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].getPaintObject().getTextBounds(
mHeaderLabels[HEADER_LBS_STRING_LITERAL],
0, (mHeaderLabels[HEADER_LBS_STRING_LITERAL]).toString().length,
bounds)
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].setAllPositions(
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getTop() +
boundsOfExerciseNameTextField.height() +
(bounds.height() * .25).toInt(),
mCanvasSpecs.getWidth() - mMarginSpecs.getWidth() - bounds.width(),
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getTop() +
boundsOfExerciseNameTextField.height() +
(bounds.height() * 1.25).toInt(),
0)
}
/**
* Text size for labels has changed due to changes while making everything fit horizontally
*/
private fun setTextSizeForAllLabels(textSize : Float) {
for (idx in 0..3) {
mGraphLabelsLeftSpecs[idx].setTextSize(textSize)
}
for (idx in 0..4) {
mGraphLabelsBottomSpecs[idx].setTextSize(textSize)
}
var largeTextAdjustment : Double = 1.1
var smallTextAdjustment : Double = 0.9
if(mIsDeviceOrientationPortrait) {
largeTextAdjustment = 1.25
smallTextAdjustment = 1.0
}
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].setTextSize((textSize * largeTextAdjustment).toFloat())
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].setTextSize((textSize * largeTextAdjustment).toFloat())
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].setTextSize((textSize * smallTextAdjustment).toFloat())
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].setTextSize((textSize * smallTextAdjustment).toFloat())
}
/**
* Helper method that gets the max width for all 4 Left labels
*/
private fun getLeftLabelMaxWidth() : Int {
var maxWidth = 0
for(idx in 0..3) {
val measuredTextWidth : Int =
(mGraphLabelsLeftSpecs[idx].getPaintObject().measureText(mGraphLabelsLeftFinal[idx])).toInt()
if(measuredTextWidth > maxWidth) {
maxWidth = measuredTextWidth
}
}
return maxWidth
}
/**
* We should now have all the information we need to calculate the actual Graph 'box' horizontal dimensions.
*/
private fun setGraphHorizontalSize() {
mGraphSpecs.setLeft(
mMarginSpecs.getWidth() +
getLeftLabelMaxWidth() +
mGutterLeftGraphSpecs.getWidth())
mGraphSpecs.setRight(
mCanvasSpecs.getWidth() -
(mMarginSpecs.getWidth() * 1.5).toInt())
}
/**
* One of the most complex methods here. We may need to adjust sizes of the vertical 'gutters' and
* label text sizes to make sure everything fits on the screen (especially when the device is in
* portrait view)
*/
private fun makeHorizontalLayoutFit() {
var widthOfText : Int
var totalSpaceUsedByText : Int
var numPassesThroughDoLoop : Int = 0
var textSize : Float = mGraphLabelsBottomSpecs[0].getTextSize()
do {
numPassesThroughDoLoop += 1
widthOfText = 0
for (idx in 0..4) {
widthOfText +=
mGraphLabelsBottomSpecs[idx].getPaintObject().measureText(mGraphLabelsBottom[idx]).toInt()
}
widthOfText += (MIN_SPACE_ALLOWED_BETWEEN_TEXTFIELDS * 4) + mMarginSpecs.getWidth()
val xValueAtStartOfFirstText : Int =
mGraphSpecs.getLeft() -
(mGraphLabelsBottomSpecs[0].getPaintObject().measureText(mGraphLabelsBottom[0]) / 2).toInt()
val xValueAtEndOfLastText : Int =
mGraphSpecs.getRight() -
(mGraphLabelsBottomSpecs[4].getPaintObject().measureText(mGraphLabelsBottom[4]) / 2).toInt()
totalSpaceUsedByText = xValueAtEndOfLastText - xValueAtStartOfFirstText
if (widthOfText > totalSpaceUsedByText) {
when {
// Adjust the gutter sizes first
numPassesThroughDoLoop == 1 -> {
mGutterLeftGraphSpecs.setRight(mGutterLeftGraphSpecs.getRight() - 1)
}
// Adjust the text size second
numPassesThroughDoLoop == 2 -> {
textSize -= 1f
setTextSizeForAllLabels(textSize)
numPassesThroughDoLoop = 0
}
}
setGraphHorizontalSize()
}
} while(widthOfText > totalSpaceUsedByText)
}
/**
* Takes into account all of the 'gutters', 'margins' and Header height.
*/
private fun setGraphHeight() {
// Top of Graph
mGraphSpecs.setTop(mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].getBottom() +
mGutterAboveGraphSpecs.getHeight())
// Make each graph section a "square" if possible
if(mIsDeviceOrientationPortrait) {
mGraphSpecs.setBottom(mGraphSpecs.getTop() + ((mGraphSpecs.getWidth() / 4) * 3))
// Set Graph height based on heights of other components
} else {
val bounds = Rect()
mGraphLabelsBottomSpecs[0].getPaintObject().getTextBounds(mGraphLabelsBottom[0],
0, (mGraphLabelsBottom[0]).toString().length,
bounds)
mGraphSpecs.setBottom(
mCanvasSpecs.getHeight() -
(mMarginSpecs.getHeight() / 2) -
bounds.height() -
mGutterBelowGraphSpecs.getHeight())
}
}
/**
* Another complex method that adjusts gutter and graph heights to make the layout fit. This
* is really only necessary if the device is in landscape view.
*/
private fun makeVerticalLayoutFit() {
var totalHeight : Int
var numPassesThroughDoLoop : Int = 0
val bounds = Rect()
mGraphLabelsBottomSpecs[0].getPaintObject().getTextBounds(mGraphLabelsBottom[0],
0, (mGraphLabelsBottom[0]).toString().length,
bounds)
do {
numPassesThroughDoLoop += 1
totalHeight =
(mMarginSpecs.getHeight() * 1.5).toInt() +
(mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].getBottom() -
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getTop()) +
mGutterAboveGraphSpecs.getHeight() +
mGraphSpecs.getHeight() +
mGutterBelowGraphSpecs.getHeight() +
bounds.height()
if(totalHeight > mCanvasSpecs.getHeight()) {
when {
// Adjust the gutter sizes first
numPassesThroughDoLoop < 4 -> {
mGraphSpecs.setBottom(mGraphSpecs.getBottom() - 1)
}
// Adjust the graph height second
numPassesThroughDoLoop == 4 -> {
mGutterAboveGraphSpecs.setBottom(mGutterAboveGraphSpecs.getBottom() - 1)
mGutterBelowGraphSpecs.setBottom(mGutterBelowGraphSpecs.getBottom() - 1)
numPassesThroughDoLoop = 0
}
}
}
} while (totalHeight > mCanvasSpecs.getHeight())
}
/** #########################################################################
######################## PUBLIC ACCESSORS ########################
######################################################################### */
override fun drawLeftLabel(whichone : Int) {
val bounds = Rect()
val paint : Paint = mGraphLabelsLeftSpecs[whichone].getPaintObject()
paint.getTextBounds(mGraphLabelsLeftFinal[whichone],
0, (mGraphLabelsLeftFinal[whichone]).toString().length,
bounds)
val yValue =
(mGraphSpecs.getTop() + ((mGraphSpecs.getHeight() / 3) * whichone) + (bounds.height() / 2)).toFloat()
mCanvas.drawText(
mGraphLabelsLeftFinal[whichone],
mGraphLabelsLeftSpecs[whichone].getLeft().toFloat(),
yValue,
paint)
}
override fun drawHorizontalLine(whichone: Int) {
val yValue = (mGraphSpecs.getTop() + ((mGraphSpecs.getHeight() / 3) * whichone)).toFloat()
val xValueStart = mGraphSpecs.getLeft() - (mGutterLeftGraphSpecs.getWidth() / 2).toFloat()
val xValueEnd = mCanvasSpecs.getWidth().toFloat() - mMarginSpecs.getWidth().toFloat()
mCanvas.drawLine(
xValueStart,
yValue,
xValueEnd,
yValue,
mGraphLineSpecs.getPaintObject())
}
override fun drawBottomLabel(whichone : Int) {
val bounds = Rect()
val paint : Paint = mGraphLabelsBottomSpecs[whichone].getPaintObject()
paint.getTextBounds(mGraphLabelsBottom[0],
0, (mGraphLabelsBottom[0]).toString().length,
bounds)
val horizontalSpacing = mGraphSpecs.getWidth() / 4
var yValue = (mGraphSpecs.getBottom() +
mGutterBelowGraphSpecs.getHeight() +
bounds.height()).toFloat()
val centeredXValue =
((horizontalSpacing * whichone).toFloat() +
mGraphSpecs.getLeft().toFloat() -
(bounds.width() / 2).toFloat()).toFloat()
mCanvas.drawText(
mGraphLabelsBottom[whichone],
centeredXValue,
yValue,
paint)
}
override fun drawVerticalLine(whichone : Int) {
val horizontalSpacing = mGraphSpecs.getWidth() / 4
val xForGridLines = ((horizontalSpacing * whichone) + mGraphSpecs.getLeft()).toFloat()
val bottomOfGridLines =
(mGraphSpecs.getTop() +
mGraphSpecs.getHeight() +
(mGutterBelowGraphSpecs.getHeight() / 2)).toFloat()
mCanvas.drawLine(
xForGridLines,
mGraphSpecs.getTop().toFloat(),
xForGridLines,
bottomOfGridLines,
mGraphLineSpecs.getPaintObject())
}
override fun drawHeaderText() {
mCanvas.apply {
// Exercise Name
drawText(
mHeaderLabels[HEADER_EXERCISE_NAME], // The text
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getLeft().toFloat(), // X position
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getTop().toFloat(), // Y Postion
mHeaderLabelsSpecs[HEADER_EXERCISE_NAME].getPaintObject()) // Paint object
// Exercise RM Value (weight)
drawText(
mHeaderLabels[HEADER_ONE_REP_MAX_WEIGHT], // The text
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].getLeft().toFloat(), // X position
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].getTop().toFloat(), // Y position
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_WEIGHT].getPaintObject()) // Paint object
// Number of RM Records
drawText(
mHeaderLabels[HEADER_ONE_REP_MAX_COUNT], // The text
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].getLeft().toFloat(), // X position
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].getTop().toFloat(), // Y position
mHeaderLabelsSpecs[HEADER_ONE_REP_MAX_COUNT].getPaintObject()) // Paint object
// String Literal 'lbs'
drawText(
mHeaderLabels[HEADER_LBS_STRING_LITERAL], // The text
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].getLeft().toFloat(), // X position
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].getTop().toFloat(), // Y position
mHeaderLabelsSpecs[HEADER_LBS_STRING_LITERAL].getPaintObject()) // Paint object
}
}
override fun drawPlottedCirclesLines() {
val graphMaxLabelValue = mGraphLabelsLeft.max() as Int
val graphVerticalLineSpacing = mGraphSpecs.getWidth() / 4
var previousXPlotPoint : Float = 0f
var previousYPlotPoint : Float = 0f
mCanvas.apply {
for (idx in 0..4) {
val xPlotPoint = ((graphVerticalLineSpacing * idx).toFloat() + mGraphSpecs.getLeft()).toFloat()
val graphPointAsPercentageOfGraphMax = (
(graphMaxLabelValue.toFloat() - mGraphLabelsLeft[idx]).toFloat() /
(mLeftLabelSpacingValue * 3).toFloat())
val yPlotPoint =
((mGraphSpecs.getHeight().toFloat() *
graphPointAsPercentageOfGraphMax.toFloat()) +
mGraphSpecs.getTop().toFloat()).toFloat()
drawCircle(
xPlotPoint,
yPlotPoint,
mContext.getResources().getDimension(R.dimen.graph_circle_radius),
mPlottedCircleSpecs.getPaintObject())
if (idx > 0) {
drawLine(
xPlotPoint,
yPlotPoint,
previousXPlotPoint,
previousYPlotPoint,
mPlottedLineSpecs.getPaintObject())
}
previousXPlotPoint = xPlotPoint
previousYPlotPoint = yPlotPoint
}
}
}
}<file_sep>/app/src/test/java/com/fitbod/my/test/DataSingletonTest.kt
package com.fitbod.my.test
import org.junit.Test
import org.junit.Assert.*
import org.junit.jupiter.api.TestInstance
import java.io.InputStream
/**
* Test DataSingleton class
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DataSingletonTest {
@Test
fun `Singleton is truly single` () {
// Set up the test instances
val firstInstance = DataSingleton
val secondInstance = DataSingleton
// Get the instance values for each
val constructors = DataSingleton::class.java.declaredConstructors
constructors.forEach {
it.isAccessible = true
return@forEach
}
// Compare them... They should be the same
assertSame(firstInstance, secondInstance)
}
@Test
fun `Inject VALID CSV and verify` () {
val inputStream : InputStream = this.javaClass.getResourceAsStream("workoutData.txt")
val workoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().createMutableMapFromCSV(inputStream)
assertFalse(workoutList.isNullOrEmpty())
}
@Test
fun `Inject INVALID CSV and verify` () {
val inputStream : InputStream = this.javaClass.getResourceAsStream("failsValidityCheck.txt")
val workoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().createMutableMapFromCSV(inputStream)
assertTrue(workoutList.isNullOrEmpty())
}
@Test
fun `Calculate One Rep Max - VALID` () {
// Setup injected data
val inputArray1 = listOf<String>("1507705200000", "Oct 11 2017", "Back Squat", "1", "10", "100", "0")
val inputArray2 = listOf<String>("1507705200000", "Oct 11 2017", "Back Squat", "1", "10", "100", "0")
val inputMap : MutableMap<Int, List<String>> = mutableMapOf()
inputMap.put(1, inputArray1)
inputMap.put(2, inputArray2)
// What we expect to get returned
val expectedString = "{1=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 100, 130]," +
" 2=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 100, 130]}"
// Call the test method 'calculateRM()' and get the result
val actualString : String = (DataSingleton.getInstance().calculateRM(inputMap)).toString()
// Yay! They match! (Unless someone's piddled around with my code
assertEquals(expectedString, actualString)
}
@Test
fun `Calculate One Rep Max - INVALID` () {
// Setup injected data
val inputArray1 = listOf<String>("1507705200000", "Oct 11 2017", "Back Squat", "1", "10", "100", "0")
val inputArray2 = listOf<String>("1507705200000", "Oct 11 2017", "Back Squat", "1", "10", "100", "0")
val inputMap : MutableMap<Int, List<String>> = mutableMapOf()
inputMap.put(1, inputArray1)
inputMap.put(2, inputArray2)
// What we expect to get returned
val nonExpectedString = "{1=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 100, 130]," +
" 2=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 100, 50000000]}"
// Call 'calculateRM()' and get the result
val actualString : String = (DataSingleton.getInstance().calculateRM(inputMap)).toString()
// Yay! They match! (Unless someone's piddled around with my code)
assertNotEquals(nonExpectedString, actualString)
}
@Test
fun `Integration Test 1 - Get VALID RM` () {
// Inject a valid CSV
val inputStream : InputStream = this.javaClass.getResourceAsStream("integrationTest.txt")
val workoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().createMutableMapFromCSV(inputStream)
assertFalse(workoutList.isNullOrEmpty())
// Call the test method 'calculateRM()' and get the result
val actualString : String = (DataSingleton.getInstance().calculateRM(workoutList)).toString()
// What we expect to get returned
val expectedString = "{1=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 45, 60]," +
" 2=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 135, 180]," +
" 3=[1507705200000, Oct 11 2017, Back Squat, 1, 3, 185, 195]," +
" 4=[1507705200000, Oct 11 2017, Back Squat, 1, 6, 245, 280]," +
" 5=[1507705200000, Oct 11 2017, Back Squat, 1, 6, 245, 280]," +
" 6=[1507705200000, Oct 11 2017, Back Squat, 1, 6, 245, 280]," +
" 7=[1507705200000, Oct 11 2017, Back Squat, 1, 6, 245, 280]," +
" 8=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 4, 45, 45]," +
" 9=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 4, 125, 135]," +
" 10=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 185, 190]," +
" 11=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 205, 210]," +
" 12=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 225, 230]," +
" 13=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 225, 230]," +
" 14=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 225, 230]," +
" 15=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 225, 230]," +
" 16=[1507186800000, Oct 05 2017, Barbell Bench Press, 1, 2, 225, 230]}"
// Yay! They match! (Unless someone's piddled around with my code)
assertEquals(expectedString, actualString)
}
@Test
fun `Integration Test 2 - Get VALID exercise map` () {
// Inject a valid CSV
val inputStream : InputStream = this.javaClass.getResourceAsStream("integrationTest.txt")
val workoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().createMutableMapFromCSV(inputStream)
assertFalse(workoutList.isNullOrEmpty())
// Call the 'calculateRM()' and get the result
val updatedWorkoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().calculateRM(workoutList)
assertFalse(updatedWorkoutList.isNullOrEmpty())
// Call 'getExerciseMap()' and get the result
// First, set the bool that confirms the One Rep Max value has been set
DataSingleton.getInstance().setRMHasBeenCalculated(true)
val actualString : String = (DataSingleton.getInstance().getExerciseMap(updatedWorkoutList)).toString()
// What we expect to get returned
val expectedString = "{Back Squat=[Back Squat, 280, 4], " +
"Barbell Bench Press=[Barbell Bench Press, 230, 5]}"
// Yay! They match! (Unless someone's piddled around with my code)
assertEquals(expectedString, actualString)
}
@Test
fun `Integration Test 3 - Get INVALID exercise map` () {
// Inject an INVALID CSV
val inputStream : InputStream = this.javaClass.getResourceAsStream("failsValidityCheck.txt")
val workoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().createMutableMapFromCSV(inputStream)
assertTrue(workoutList.isNullOrEmpty()) // Doesn't break the app
// Call the test method 'calculateRM()' and get the result
val updatedWorkoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().calculateRM(workoutList)
assertTrue(updatedWorkoutList.isNullOrEmpty()) // Doesn't break the app
// Call 'getExerciseMap()' and get the result
// First, set the bool that confirms the One Rep Max value has been set
DataSingleton.getInstance().setRMHasBeenCalculated(true)
val exerciseMap : MutableMap<String, MutableList<String>> =
DataSingleton.getInstance().getExerciseMap(updatedWorkoutList)
assertTrue(exerciseMap.isNullOrEmpty()) // Doesn't break the app
}
@Test
fun `Integration Test 4 - Get VALID graph data` () {
// Inject a valid CSV
val inputStream : InputStream = this.javaClass.getResourceAsStream("integrationTest2.txt")
val workoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().createMutableMapFromCSV(inputStream)
assertFalse(workoutList.isNullOrEmpty())
// Call the test method 'calculateRM()' and get the result
val updatedWorkoutList : MutableMap<Int, List<String>> =
DataSingleton.getInstance().calculateRM(workoutList)
assertFalse(updatedWorkoutList.isNullOrEmpty())
// Call 'getGraphData()' and get the result
val actualString : String =
(DataSingleton.getInstance().getGraphData("Back Squat", updatedWorkoutList)).toString()
// What we expect to get returned
val expectedString = "{Oct 11=60, Oct 12=195, Oct 13=280, Oct 14=280}"
// Yay! They match! (Unless someone's piddled around with my code)
assertEquals(expectedString, actualString)
}
}
<file_sep>/app/src/main/java/com/fitbod/my/test/ComponentSpecs.kt
package com.fitbod.my.test
import android.content.Context
import android.graphics.Paint
import android.support.v4.content.ContextCompat
// The Color objects
private const val COLOR_PRIMARY : Int = 0
private const val COLOR_SECONDARY : Int = 1
private const val COLOR_GRAPH_LINES : Int = 2
private const val COLOR_GRAPH_PLOTS : Int = 3
// The Paint objects
const val PAINT_LABEL_TEXT : Int = 0
const val PAINT_HEADER_TEXT_LARGE : Int = 1
const val PAINT_HEADER_TEXT_SMALL : Int = 2
const val PAINT_GRAPH_GRID_LINES : Int = 3
const val PAINT_PLOTTED_CIRCLES : Int = 4
const val PAINT_PLOTTED_LINES : Int = 5
class ComponentSpecs constructor(context : Context) {
// The Color and Paint Objects
private var mColorsList : MutableList<Int> = mutableListOf()
private var mPaintObjectList : MutableList<Paint> = mutableListOf()
// Positions
private var mTop : Int = -1
private var mLeft : Int = -1
private var mBottom : Int = -1
private var mRight : Int = -1
// Paint object
private var mPaint : Paint = Paint()
init {
setColorAndPaintObjects(context)
}
/**
* All of the Color and Paint objects needed to draw the screen. All of these array locations (indices)
* are declared as constants to help ensure type safety. The companion getter is getPaintObject(index).
*/
private fun setColorAndPaintObjects(context : Context) {
mColorsList.add(COLOR_PRIMARY, ContextCompat.getColor(context, R.color.colorPrimary))
mColorsList.add(COLOR_SECONDARY, ContextCompat.getColor(context, R.color.colorSecondary))
mColorsList.add(COLOR_GRAPH_LINES, ContextCompat.getColor(context, R.color.colorListDivider))
mColorsList.add(COLOR_GRAPH_PLOTS, ContextCompat.getColor(context, R.color.colorToolbarBackground))
var paint : Paint = Paint()
paint.color = mColorsList[COLOR_PRIMARY]
paint.textAlign = Paint.Align.LEFT
mPaintObjectList.add(PAINT_LABEL_TEXT, paint)
paint = Paint()
paint.color = mColorsList[COLOR_PRIMARY]
paint.textAlign = Paint.Align.LEFT
mPaintObjectList.add(PAINT_HEADER_TEXT_LARGE, paint)
paint = Paint()
paint.color = mColorsList[COLOR_SECONDARY]
paint.textAlign = Paint.Align.LEFT
mPaintObjectList.add(PAINT_HEADER_TEXT_SMALL, paint)
paint = Paint()
paint.color = mColorsList[COLOR_GRAPH_LINES]
paint.strokeWidth = context.getResources().getDimension(R.dimen.line_stroke_width)
mPaintObjectList.add(PAINT_GRAPH_GRID_LINES, paint)
paint = Paint()
paint.color = mColorsList[COLOR_GRAPH_PLOTS]
paint.style = Paint.Style.FILL
mPaintObjectList.add(PAINT_PLOTTED_CIRCLES, paint)
paint = Paint()
paint.color = mColorsList[COLOR_GRAPH_PLOTS]
paint.strokeWidth = context.getResources().getDimension(R.dimen.line_stroke_width)
mPaintObjectList.add(PAINT_PLOTTED_LINES, paint)
}
/** #########################################################################
######################## PUBLIC ACCESSORS ########################
######################################################################### */
fun setAllPositions(top : Int, left : Int, bottom : Int, right : Int) {
mTop = top
mLeft = left
mBottom = bottom
mRight = right
}
fun setTop(top : Int) { mTop = top }
fun getTop() : Int { return mTop }
fun setLeft(left : Int) { mLeft = left }
fun getLeft() : Int { return mLeft }
fun setBottom(bottom : Int) { mBottom = bottom }
fun getBottom() : Int { return mBottom }
fun setRight(right : Int) { mRight = right }
fun getRight() : Int { return mRight }
fun getHeight() : Int {
if(mTop == -1 || mBottom == -1) { return -1 }
return mBottom - mTop
}
fun getWidth() : Int {
if(mLeft == -1 || mRight == -1) { return -1 }
return mRight - mLeft
}
fun setPaintObject(whichOne : Int) { mPaint = mPaintObjectList.get(whichOne) }
fun getPaintObject() : Paint { return mPaint }
fun setTextSize(textSize : Float) { mPaint.setTextSize(textSize) }
fun getTextSize() : Float { return mPaint.getTextSize() }
}<file_sep>/app/src/main/java/com/fitbod/my/test/DataSingleton.kt
package com.fitbod.my.test
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.*
// All of the entries in the Raw and calculated mutable map.
private const val WORKOUT_LIST_DATE_EPOCH : Int = 0
private const val WORKOUT_LIST_DATE_STRING : Int = 1
private const val WORKOUT_LIST_EXERCISE_NAME : Int = 2
private const val WORKOUT_LIST_SETS : Int = 3
private const val WORKOUT_LIST_REPS : Int = 4
private const val WORKOUT_LIST_WEIGHT : Int = 5
private const val WORKOUT_LIST_RM : Int = 6
// Brzycki formula constants. The formula looks like this:
// weight / ((37 / 36) - ((1 / 36) * reps)) or:
// weight / (1.0278 - (.0278 * reps))
// Represents the 37/36 portion of the formula (ie; 1.0278)
private const val BRZYCKI_FORMULA_VALUE_ONE : Double = 1.0278
// Represents the 1/36 portion of the formula (ie; .0278)
private const val BRZYCKI_FORMULA_VALUE_TWO : Double = .0278
class DataSingleton private constructor() : CoroutineScope
{
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main
// Make the date format a static value. Easier to modify later if needed:
private val mSimpleDateFormat : SimpleDateFormat = SimpleDateFormat("MMM dd yyyy")
// Final conversion data object (usable Map/List - data from CSV):
private var mWorkoutList: MutableMap<Int, List<String>> = mutableMapOf()
// Final exercise list (usable Map/List - contains caluclated RMs):
private var mExerciseMap : MutableMap<String, MutableList<String>> = mutableMapOf()
// We only want to calculate RMs once.
private var mHasRMBeenCalculated : Boolean = false
/**
* <p>Put all of the data from CSV into a MutableMap (mWorkoutList). Below is what the MutableMap looks like:</p>
*
* <p>{1=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 45, 60],
* 2=[1507705200000, Oct 11 2017, Back Squat, 1, 10, 135, 180],
* 3=[1507705200000, Oct 11 2017, Back Squat, 1, 3, 185, 195] ... }</p>
*
* <ul>Map explanation:
* <li>First, is an integer (the map key). This is very similar to a database primary key. Why have this?
* Because we could have the same exercise with the same exact data but representing 2 different
* sets or maybe even a morning workout and an evening workout.
* How would they be distinguishable?</li>
* <li>The actual data or map value (List<String>):
* <ul>
* <li>Long: represents the date as an number (milliseconds since epoch)</li>
* <li>String: the date of the workout.
* Really not needed but helps for testing and debugging.</li>
* <li>String: the exercise (ie; Back Squat)</li>
* <li>Int: Number of sets</li>
* <li>Int: Number of reps</li>
* <li>Int: Weight of barbell/dumbbell/machine...</li>
* <li>Int: One Rep Max (RM)</li>
* </ul>
* </li>
* </ul>
*/
fun createMutableMapFromCSV(inputStream: InputStream) : MutableMap<Int, List<String>>
{
// Represents separated lines of the CSV (ie; row). Note: Each line is read until a "hard return" is reached.
val workoutList : List<String> = inputStream.bufferedReader().readLines()
// We need to be sure the data is valid. If 'invalid' silently do nothing
if (validateCSVdata(workoutList) == false) { return mutableMapOf() }
// The "Id" representing a row:
var id : Int = 0
// Each row but represented as an Array:
var tempArray : List<String>
// Cycle through each line (row)
workoutList.forEach {
// Split the line into separate Array elements:
tempArray = it.split(",")
// Re-initiate this local variable each time to clear out old data.
// TODO: declare this variable above the loop and empty it each time. This will save cycles when iterating
// over large amounts of data.
val inputArray : MutableList<String> = mutableListOf()
// Convert CSV dates to sortable dates (ie; Long numbers representing milliseconds since epoch)
val date : Date = mSimpleDateFormat.parse(tempArray[0])
val dateToLong = date.getTime()
inputArray.add(dateToLong.toString())
// Simply "stuff" the rows data into the remaining 5 columns/array items:
// 1) date (ie; Sep 5, 2018)
// 2) exercise (ie; Back Squat)
// 3) sets
// 4) reps
// 5) weight
for(iter in 0..4) { inputArray.add(tempArray[iter]) }
// Now add the RM placeholder value of "0". This value is calculated asynchronously in "calculateRM()"
inputArray.add("0")
// Increment the rows "Id"
id++
// Finally "stuff" all of it into the class level MutableMap var:
mWorkoutList.put( id, inputArray )
}
inputStream.close()
return mWorkoutList
}
private fun validateCSVdata(workoutList : List<String>) : Boolean {
// Each row but represented as an Array:
var tempArray : List<String>
workoutList.forEach {
// Split the line into separate Array elements:
tempArray = it.split(",")
// Check for failure
if(tempArray.size != 5) {
return false
}
}
// Success
return true
}
/**
* <p>This is the way to create a Singleton in Kotlin. The "companion object" is fully accessible (public). However,
* in my opinion, accessing just the class instance is the best approach for this object. "Globbing" on getters
* and setters inside the companion object goes beyond the intent of the object. Instead, use getters/setters
* as class level functions instead (see further below for examples).</p>
*/
companion object
{
private val mDataSingletonInstance : DataSingleton = DataSingleton()
@Synchronized
fun getInstance(): DataSingleton
{
return mDataSingletonInstance
}
}
/** #########################################################################
######################## PUBLIC ACCESSORS ########################
######################################################################### */
/**
* This is set as an async coroutine from MainActivity. It calculates the 'One Rep Max' using
* the Brzycki formula. The formula looks like this:
*
* weight / ((37 / 36) - ((1 / 36) * reps)) or:
* weight / (1.0278 - (.0278 * reps))
*
* Both of the immutable vales are declared as constants:
*
* BRZYCKI_FORMULA_VALUE_ONE = 1.0278
* BRZYCKI_FORMULA_VALUE_TWO = .0278
*/
fun calculateRM(workoutList : MutableMap<Int, List<String>>) : MutableMap<Int, List<String>> {
// This is why this method is so expensive and why we need to make this method an async one.
// We have to iterate through the entire list of workout entries and calculate the 'One Rep Max'
// for each of them.
workoutList.forEach {
// First, get the 'value' portion of the map (a mutable list)
val arrayWorkoutList = it.value as MutableList<String>
// Calculate the 'One Rep Max'
val rmValue =
5 * ((arrayWorkoutList[WORKOUT_LIST_WEIGHT].toDouble() /
(BRZYCKI_FORMULA_VALUE_ONE -
(BRZYCKI_FORMULA_VALUE_TWO * arrayWorkoutList[WORKOUT_LIST_REPS].toInt()))).toInt() / 5)
// Stuff this newly calculated value into the array
arrayWorkoutList[WORKOUT_LIST_RM] = rmValue.toString()
// Finally, put the array back in the mutable map at the 'key' spot.
workoutList[it.key] = arrayWorkoutList
}
return workoutList
}
fun setRMHasBeenCalculated(isCalculated : Boolean) { mHasRMBeenCalculated = isCalculated }
fun getRMHasBeenCalculated() : Boolean { return mHasRMBeenCalculated }
fun getIsCSVEmpty() : Boolean { return mWorkoutList.isEmpty() }
/**
* We do it this way for testing purposes
*/
fun doCalculateRM() { mWorkoutList = calculateRM(mWorkoutList) }
fun doGetExerciseMap() : MutableMap<String, MutableList<String>> {
return getExerciseMap(mWorkoutList)
}
fun doGetGraphData(exerciseName : String) : MutableMap<String, Int> {
return getGraphData(exerciseName, mWorkoutList)
}
/**
* <p>A lazy way to only include one set of data. In this function we only want one of each exercise. This is
* achieved using a hash map (MutableList). Since each exercise is a key and there can only be one of each key
* simply traversing the list and "trying" to add a new key is the best and easiest approach. If a key already
* exists when trying to add a new one, we simply check the RM value to see if it is greater (or equal to)
* the one that already exists.</p>
*
* <p>Here is an example output:
* {Back Squat=[Back Squat, 310, 2],
* Barbell Bench Press=[Barbell Bench Press, 245, 1],
* Deadlift=[Deadlift, 360, 1]}</p>
*/
fun getExerciseMap(injectedWorkoutList : MutableMap<Int, List<String>>) : MutableMap<String, MutableList<String>> {
// This is pretty expensive so only do it once:
if (mHasRMBeenCalculated) {
mExerciseMap.clear()
// The map where we try to add each exercise:
var workoutList: List<String>
var tempList: MutableList<String>
// Walk the class level map (mWorkoutList) of exercises:
injectedWorkoutList.forEach {
// Copy the List from mWorkoutList (this is the value part of the key/value pair)
workoutList = it.value
// Build the list with only necessary fields (ie; Exercise Name, RM, and Number of Records)
val myExerciseList: MutableList<String> = mutableListOf()
myExerciseList.add(workoutList[WORKOUT_LIST_EXERCISE_NAME]) // Exercise Name
myExerciseList.add(workoutList[WORKOUT_LIST_RM]) // RM
myExerciseList.add("1") // Number of Records
// Does the key already exist?
// If TRUE, we need to check for a new RM record.
// If FALSE, simply add the new record and move on to the next mWorkoutList item.
if (mExerciseMap.containsKey(workoutList[WORKOUT_LIST_EXERCISE_NAME])) {
// Make a copy of the exerciseMap value:
tempList = mExerciseMap[workoutList[WORKOUT_LIST_EXERCISE_NAME]] as MutableList<String>
// Is the new RM > than the old one? If so, make the new RM the record.
// For clarity: myExerciseList[1] = RM
// myExerciseList[2] = Number of Records
if (myExerciseList[1].toInt() > tempList[1].toInt()) {
tempList[1] = myExerciseList[1] // New RM Record value
tempList[2] = "1" // Reset the Number of Records value
// Insert the potentially modified MutableList into the MutableMap value:
mExerciseMap[workoutList[WORKOUT_LIST_EXERCISE_NAME]] = tempList
// Is the new RM = to the old one? If so, increment the Number of Records.
} else if (myExerciseList[1].toInt().equals(tempList[1].toInt())) {
tempList[2] = (tempList[2].toInt() + 1).toString()
// Insert the potentially modified MutableList into the MutableMap value:
mExerciseMap[workoutList[2]] = tempList
}
// Key DOES NOT exist so add it and move on
} else {
mExerciseMap.put(workoutList[WORKOUT_LIST_EXERCISE_NAME], myExerciseList)
}
}
}
// Yay! We're done
return mExerciseMap
}
/**
* The plotted points on the graph in ChartActivity. The returned value is a mutable map where
* the 'key' is the Date and the 'value' is the RM weight. The returned map looks like this:
*
* {Sep 15=270, Sep 21=275, Sep 28=280, Oct 4=280, Oct 11=280}
*/
fun getGraphData(exercise: String, injectedWorkoutList : MutableMap<Int, List<String>>) : MutableMap<String, Int> {
// A temporary map used to hold graph data
val graphData : MutableMap<Long, Int> = mutableMapOf()
// We need to make some changes to the WorkoutList class map so make a copy instead
// of a pointer:
val copyWorkoutList: MutableMap<Int, List<String>> = injectedWorkoutList.toMutableMap()
// Remove all of the map entries that DON'T have the correct Exercise Name:
copyWorkoutList.entries.removeAll { (_, value) -> value[WORKOUT_LIST_EXERCISE_NAME] != exercise }
// Sort the remaining List items by date in descending order (ie; newer dates first)
var sortedWorkoutList: Map<Int, List<String>> =
copyWorkoutList.toList().sortedByDescending { (_, value) -> value[0] }.toMap()
// Now we can cycle through the filtered and sorted map
var idx : Int = 0
sortedWorkoutList.forEach {
val workoutList : List<String> = it.value
val workoutListDateTime : Long = workoutList[WORKOUT_LIST_DATE_EPOCH].toLong()
val workoutListRM : Int = workoutList[WORKOUT_LIST_RM].toInt()
// Does the graph data item date already exist in the map? If so, see if the corresponding
// RM is greater than the one already in the map. If that's true then replace the current
// RM value with the current one.
if(graphData.containsKey(workoutListDateTime)){
val graphDataValue : Int = graphData[workoutListDateTime] as Int
if(workoutListRM > graphDataValue) {
graphData[workoutListDateTime] = workoutListRM
}
// A new date (new map entry). Add it unless we already have 5.
} else {
// Break and Continue don't work with Kotlin for statements yet. So, if we already 5 graph
// entries make sortedWorkoutList empty. In essence, this is like driving down the
// highway at 55 mph and slamming the car into park. But, it's the only way to stop the loop
// and save cycles/performance.
if(idx >= 5) {
sortedWorkoutList = mapOf()
// Simply add the new map entry
} else {
graphData.put(workoutListDateTime, workoutListRM)
idx++
}
}
}
// Sort the graph data by date in ascending order (older dates first).
val sortedGraphData: Map<Long, Int> = graphData.toList().sortedBy { (key, _) -> key }.toMap()
// Initialize the graph map that will be returned.
val returnGraphData: MutableMap<String, Int> = mutableMapOf()
// Adjust the date into it's display-ready string
sortedGraphData.forEach{
val simpleDateFormat = SimpleDateFormat("MMM d")
val displayDate : String = simpleDateFormat.format(Date(it.key))
returnGraphData.put(displayDate, it.value)
}
// Yay! We're done
return returnGraphData
}
}
<file_sep>/app/src/main/java/com/fitbod/my/test/MainActivity.kt
package com.fitbod.my.test
import android.os.Bundle
import android.support.v7.app.AppCompatActivity;
import android.view.Menu
import android.widget.ListView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.InputStream
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Try to get the file based on the name in Resources (Strings)
if(DataSingleton.getInstance().getIsCSVEmpty()) {
val inputStream = try {
getAssets().open(getString(R.string.csv_filename))
// Oops, the file doesn't exist.
} catch (e: IOException) {
throw e
}
// Breakdown CSV into a usable Map
DataSingleton.getInstance().createMutableMapFromCSV(inputStream as InputStream)
}
// The list adapter with data injected
val adapter = createAndPopulateExerciseList(DataSingleton.getInstance().doGetExerciseMap())
setSupportActionBar(toolbar)
supportActionBar?.title = ""
// This is expensive so only do this once...
if( ! DataSingleton.getInstance().getRMHasBeenCalculated()) {
// Calculates RMs -> Asynchronous launch of a Global Coroutine
GlobalScope.launch(Dispatchers.Main) {
DataSingleton.getInstance().doCalculateRM()
DataSingleton.getInstance().setRMHasBeenCalculated(true)
adapter.changeDataSource(DataSingleton.getInstance().doGetExerciseMap())
adapter.notifyDataSetChanged()
}
}
}
// The setup for the list
private fun createAndPopulateExerciseList(
theList: MutableMap<String,
MutableList<String>>) : ExerciseListAdapter {
val listView = findViewById<ListView>(R.id.exercise_list_view)
val adapter = ExerciseListAdapter(this, theList)
listView.adapter = adapter
listView.setOnItemClickListener { _, _, position, _ -> exerciseOnClick(theList, position) }
return adapter
}
// Our callback when someone "clicks" a list item
private fun exerciseOnClick(
theList: MutableMap<String,
MutableList<String>>,
position: Int) {
val dataSourceKeys : MutableSet<String> = theList.keys
val dataList : ArrayList<String> = theList[dataSourceKeys.elementAt(position)] as ArrayList<String>
startActivity(chartActivityIntent(dataList))
}
// Just a dummy menu so it looks like mockup
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
}
|
cfd0139187efb619b62662e2a6259b8fe8a1d400
|
[
"Kotlin",
"Gradle"
] | 8
|
Gradle
|
alencosoft/FitbodTest-GreggBaron
|
80f2dd0ae1cf369bf554590ae6a45e3d39f6b452
|
a31f99d9691877866b4548c1309edc1d77af8e08
|
refs/heads/main
|
<repo_name>msociety/react-utils<file_sep>/hooks/useMouseEnterLeave.js
import { useEffect } from "react";
const useMouseEnterLeave = (ref, { onMouseEnter = null, onMouseLeave = null, timeAfterLeave = 400 }) => {
useEffect(() => {
let leavingTimeout = null;
const mouseLeaveHandler = event => {
leavingTimeout = setTimeout(() => {
if (leavingTimeout) {
leavingTimeout = null;
onMouseLeave(event);
}
}, timeAfterLeave);
};
const mouseEnterHandler = event => {
leavingTimeout = null;
if (onMouseEnter) {
onMouseEnter(event);
}
};
if (ref.current) {
if (onMouseEnter || onMouseLeave) {
ref.current.addEventListener("mouseenter", mouseEnterHandler);
}
if (onMouseLeave) {
ref.current.addEventListener("mouseleave", mouseLeaveHandler);
}
}
return () => {
if (ref.current) {
if (onMouseEnter || onMouseLeave) {
ref.current.removeEventListener("mouseenter", mouseEnterHandler);
}
if (onMouseLeave) {
ref.current.removeEventListener("mouseleave", mouseLeaveHandler);
}
}
};
}, [ref, onMouseEnter, onMouseLeave]);
};
export default useMouseEnterLeave;
<file_sep>/hooks/useElementSize.js
import { useState, useEffect, useRef } from 'react';
// Based on https://github.com/infodusha/react-hook-size
const useElementSize = ref => {
const obs = useRef();
const [, setIgnored] = useState(0);
const [size, setSize] = useState({ width: null, height: null });
useEffect(() => {
function observe(entries) {
const { width, height } = entries[0].contentRect;
setSize(s => (s.width !== width || s.height !== height ? { width, height } : s));
}
obs.current = new window.ResizeObserver(observe);
return () => obs.current.disconnect();
}, []);
useEffect(() => {
const forceUpdate = () => setIgnored(c => c + 1);
const item = ref.current;
if (item) {
obs.current.observe(item);
window.setTimeout(forceUpdate, 0);
}
return () => item && obs.current.unobserve(item);
}, [obs, ref]);
return size;
};
export default useElementSize;
<file_sep>/README.md
# React Utils
hooks, components, etc...
|
1bc34ee3b0a8ec3b3c999ed2272f16386c812e3f
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
msociety/react-utils
|
ddf3d32dc3cb633581ca22a120cb769c14d4612d
|
5db396e63504550ee1cbff39822493ba71638155
|
refs/heads/master
|
<file_sep>> "An Outlook Add-In to build an agenda."
# Agenda Builder
<p align="center">
<img src="readme_assets/demo.gif" width="800">
</p>
## Development
Start development server:
```terminal
npm run dev-server
```
[Sideload add-in for testing](https://docs.microsoft.com/en-us/outlook/add-ins/sideload-outlook-add-ins-for-testing)
## License
MIT © [](https://github.com/)
<file_sep>/**
* Collection of helper functions to use the JS Office API.
*
* @file This files exports function which are simplifying the
* interaction between the Agenda Builder and the JS Office Mailbox API.
* @license MIT
*/
/**
* Calls Office.context.mailbox.item.body.getAsync to get the result and returns
* it using promise to enable async/await pattern.
*
* @return {Promise<Office.AsyncResult<string>>} the result as a Promise
*/
export const getAsyncMailBody = async (): Promise<Office.AsyncResult<string>> => {
return new Promise(resolve => {
Office.context.mailbox.item.body.getAsync(
"html",
function callback(result) {
resolve(result);
}
);
});
}<file_sep>/**
* The Agenda Builder's theme.
*
* @file Color palette of the Agenda Builder's theme. Can be used as
* a fabric theme. It should also be used for custom components.
*
* @license MIT
*/
import { IPalette } from "@uifabric/styling";
export const palette: Partial<IPalette> = {
themePrimary: '#038387',
themeLighterAlt: '#f0fafa',
themeLighter: '#c7ebec',
themeLight: '#9bd9db',
themeTertiary: '#4bb4b7',
themeSecondary: '#159196',
themeDarkAlt: '#02767a',
themeDark: '#026367',
themeDarker: '#02494c',
neutralLighterAlt: '#f8f8f8',
neutralLighter: '#f4f4f4',
neutralLight: '#eaeaea',
neutralQuaternaryAlt: '#dadada',
neutralQuaternary: '#d0d0d0',
neutralTertiaryAlt: '#c8c8c8',
neutralTertiary: '#bab8b7',
neutralSecondary: '#a3a2a0',
neutralPrimaryAlt: '#8d8b8a',
neutralPrimary: '#323130',
neutralDark: '#605e5d',
black: '#494847',
white: '#ffffff',
};
<file_sep>/**
* HTML Generator for IDayJSON -> HTML Table.
*
* @file This files exports the getTable function which is
* used to generate a table for a given day of an agenda.
* @license MIT
*/
import moment = require("react-event-agenda/node_modules/moment");
import { IDayJSON } from "react-event-agenda/dist/models/DayModel";
/**
* Creates a html table for the given day of an agenda.
*
* @param {IDayJSON} day - the day to generate the table for
* @param {string} oldBody - old html body to keep styling
* @return {string} table as a html string
*/
export const getTable = (dayData: IDayJSON, oldBody?: string): string => {
let table = '';
let tableCells;
if (oldBody) {
tableCells = oldBody ? oldBody.match(/<td[\s\S]*?<\/td>/g) : undefined;
//Remove non agenda table cells which are before the agenda tables
for (let i = 0; i < tableCells.length - 1 && !tableCells[i + 1].includes('Topic');) {
tableCells.shift();
}
}
//generate table rows
dayData.tracks[0].items.forEach(item => {
const time = `${moment(item.start).format("HH:mm")} - ${moment(item.end).format("HH:mm")}`;
const titleAndDescription = `<b>${item.title ? item.title : ' '}</b>${item.description ? `<br/>${item.description}` : ' '}`;
const speaker = item.speaker ? item.speaker : ' ';
//create table data cells
const tdTime = !oldBody ? getInitialTimeTdStyle(time) : replaceChildrenOfFirstNodeWithTextNode(tableCells[3] ? tableCells[3] : tableCells[0], time);
const tdTopic = !oldBody ? getInitialTitleAndDescriptionTdStyle(titleAndDescription) : replaceChildrenOfFirstNodeWithTextNode(tableCells[4] ? tableCells[4] : tableCells[1], titleAndDescription);
const tdSpeaker = !oldBody ? getInitialSpeakerTdStyle(speaker) : replaceChildrenOfFirstNodeWithTextNode(tableCells[5] ? tableCells[5] : tableCells[2], speaker);
//put table row together
table = table + `<tr style='height:10.6pt'>
${tdTime}
${tdTopic}
${tdSpeaker}
</tr>`;
});
//generate table header data cells
const day = moment(dayData.startTime).format('ddd, MMM D');
const tdDayHeader = !oldBody ? getInitialDayHeaderTdStyle(day) : replaceChildrenOfFirstNodeWithTextNode(tableCells[0], day);
const tdTopicHeader = !oldBody ? getInitialTopicHeaderTdStyle() : replaceChildrenOfFirstNodeWithTextNode(tableCells[1], 'Topic');
const tdSpeakerHeader = !oldBody ? getInitialSpeakerHeaderTdStyle() : replaceChildrenOfFirstNodeWithTextNode(tableCells[2], 'Speaker');
// put everything together
table = `<table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0
style='border-collapse:collapse'>
<tr style='height:20pt'>
${tdDayHeader}
${tdTopicHeader}
${tdSpeakerHeader}
</tr>
${table}
</table>`;
return table;
}
/**
* Replaces the children of the first child with a text node child with the given html string.
* Deletes all siblings of the first child with a text node child.
*
* @param {string} htmlString - the whole HTML string
* @param {string} newHtmlToInsert - HTML to insert instead of the first child with a text node child
* @returns {string} the new HTML String
*/
const replaceChildrenOfFirstNodeWithTextNode = (htmlString: string, newHtmlToInsert: string) => {
var el = document.createElement('tr');
el.innerHTML = htmlString;
let curEl = el.children[0];
while (curEl.hasChildNodes()) {
if(curEl.tagName === 'B' || curEl.tagName === 'I' || curEl.tagName === 'U' ) {
const curElParent = curEl.parentElement;
const childNodes: Array<Node> = Array.from(curEl.childNodes);
curEl.replaceWith(...childNodes);
curEl = curElParent;
}
if (hasTextChild(curEl) ) {
break;
}
curEl = curEl.children[0];
}
curEl.innerHTML = newHtmlToInsert;
//remove all siblings
const curElParent = curEl.parentElement;
curElParent.innerHTML = '';
curElParent.appendChild(curEl);
return el.innerHTML;
}
/**
* Check if the given el has a direct text node child.
*
* @param {Element} el
*/
const hasTextChild = (el: Element) => {
const textChild = Array.from(el.childNodes).find(child => {
return (child.nodeType === Node.TEXT_NODE || child.nodeName === 'sef' || child.nodeName === 'I' || child.nodeName === 'U')
&& child.textContent.replace(/(\r\n|\n|\r)/gm, "") !== " " //check that the text node is not a line break
});
if (textChild !== undefined) return true;
return false;
}
//Initial Table Styling
const getInitialDayHeaderTdStyle = (day: string) => {
return `<td width=161 valign=top style='width:120.5pt; padding:0cm 5.4pt 0cm 5.4pt;height:20pt'>${day}</td>`;
}
const getInitialTopicHeaderTdStyle = () => {
return `<td width=268 valign=top style='width:201.1pt; padding:0cm 5.4pt 0cm 5.4pt;height:20pt'>Topic</td>`;
}
const getInitialSpeakerHeaderTdStyle = () => {
return `<td width=186 valign=top style='width:139.5pt; padding:0cm 5.4pt 0cm 5.4pt;height:20pt'>Speaker</td>`;
}
const getInitialTimeTdStyle = (time: string) => {
return `<td width=160 valign=top style='width:120pt;border:none;border-bottom:solid #C9C9C9 1.0pt; padding:0cm 5.4pt 0cm 5.4pt;height:10.05pt'>${time}</td>`;
}
const getInitialTitleAndDescriptionTdStyle = (content: string) => {
return `<td width=268 valign=top style='width:200pt;border:none;border-bottom:solid #C9C9C9 1.0pt; padding:0cm 5.4pt 0cm 5.4pt;height:10.05pt'>${content}</td>`;
}
const getInitialSpeakerTdStyle = (speaker: string) => {
return `<td width=186 valign=top style='width:140pt;border:none;border-bottom:solid #C9C9C9 1.0pt; padding:0cm 5.4pt 0cm 5.4pt;height:10.05pt'>${speaker}</td>`
}<file_sep>/**
* Collection of utility functions to work with JS string.
*
* @file This files exports functions which can be reused in
* the Agenda Builders react components to work with JS strings.
* @license MIT
*/
/**
* Replaces the last occurrence of the given string
*
* @param find
* @param replace
* @param sourceString
*/
export const replaceLast = (find: string, replace: string, sourceString: string) => {
var lastIndex = sourceString.lastIndexOf(find);
if (lastIndex === -1) {
return sourceString;
}
var beginString = sourceString.substring(0, lastIndex);
var endString = sourceString.substring(lastIndex + find.length);
return beginString + replace + endString;
}
/**
* Returns the word for a number, e.g. for 0 it returns "First".
* Only works for numbers smaller than 4 and bigger or equal 0.
*
* @param number
*/
export const numberToWord = (number: number) => {
switch (number) {
case 0:
return "First"
case 1:
return "Second"
case 2:
return "Third"
case 3:
return "Fourth"
default:
return "unknown"
}
}
|
7361840a8c0003164c3598b9ee4c0173b12abb86
|
[
"Markdown",
"TypeScript"
] | 5
|
Markdown
|
schachdavid/agenda-builder-add-in
|
700d0facadc95a62c1501935a3f45ea9fbc2ba8f
|
87912bbdbdaafdac967b4ffa67baa3fa50dd3976
|
refs/heads/master
|
<file_sep><?php
/**
* Created by raheel.
* Date: 4/4/2017
*/
class Home extends MY_Controller
{
function __construct()
{
parent::__construct();
}
function index(){
die("hello from ci hmvc and my base URL is : ".base_url());
}
}
|
0682b1202c8fcf00ee2dce9512d4cb314c9a5944
|
[
"PHP"
] | 1
|
PHP
|
zohaibtariq/ci-hmvc
|
468d943fd78515bc940042f2afedf04b8d018695
|
be40183e71111cba5a95e091b035fb62b4da2365
|
refs/heads/master
|
<repo_name>brianyamasaki/JavaGameFramework<file_sep>/gameEngine/src/main/java/com/yamasaki/game_sprites/VerticalWallImage.java
package com.yamasaki.game_sprites;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
public class VerticalWallImage extends SpriteImage {
private final int WIDTH = 20;
private final int HEIGHT = 200;
public VerticalWallImage(String filename) {
super(filename);
this.width = WIDTH;
this.height = HEIGHT;
this.setupCollisions(this.width, this.height);
}
/**
* This sets up the sprite to have collision physics
* Note that polygon is centered around 0,0
*/
private void setupCollisions(int width, int height) {
this.hasCollisions = true;
this.pointsCollisions = new ArrayList<Point>();
this.pointsCollisions.add(new Point(0, 0));
this.pointsCollisions.add(new Point(width, 0));
this.pointsCollisions.add(new Point(width, height));
this.pointsCollisions.add(new Point(0, height));
this.rectCollisions = new Rectangle(0, 0, width, height);
// static objects don't check for any collisions, but must maintain physics
this.collidesWith = new int[0];
}
}<file_sep>/gameEngine/src/main/java/com/yamasaki/AppState.java
package com.yamasaki;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import com.yamasaki.game_sprites.Sprite;
public class AppState {
private static int appWidth;
private static int appHeight;
private static int iScene;
private static AppContent appContent;
private static AffineTransform initialTransform;
private static ArrayList<ArrayList<Sprite>> spriteLists;
public AppState(ActionListener listener) {
AppState.iScene = 0;
}
public static void setAppSize(int width, int height) {
AppState.appWidth = width;
AppState.appHeight = height;
}
public static int getAppWidth() {
return AppState.appWidth;
}
public static int getAppHeight() {
return AppState.appHeight;
}
public static void setAppContent(AppContent appContent) {
AppState.appContent = appContent;
}
public static AppContent getAppContent() {
return AppState.appContent;
}
public static void setSceneIndex(int i) {
AppState.iScene = i;
appContent.setScene(i);
}
public static int getSceneIndex() {
return AppState.iScene;
}
/**
* Store initial transform to detect screen scaling by some windowing environments
* Windows will double the screen size by pixels on high res devices and this is the way we know
* @param g2
*/
public static void setInitialTransform(Graphics2D g2) {
AppState.initialTransform = g2.getTransform();
}
/**
* get the initial transform to detect screen scaling
* @return
*/
public static AffineTransform getInitialTransform() {
return AppState.initialTransform;
}
public static void addToSpriteList(ArrayList<Sprite> spriteList) {
AppState.spriteLists.add(spriteList);
}
public static ArrayList<Sprite> getSpriteList(int i) {
return AppState.spriteLists.get(i);
}
public static void addDynamicSprite(Sprite sprite) {
AppState.spriteLists.get(1).add(sprite);
}
public static void clearSpriteLists() {
AppState.spriteLists = new ArrayList<ArrayList<Sprite>>();
}
}<file_sep>/README.md
# Java Game Framework
This is a basic Java game application using the Swing framework, using Java SE 7 and later.
## Created on Visual Studio Code
I've created this in Microsoft's free Visual Studio Code editor with free Java extensions as described in the [Java in VSCode web page](https://code.visualstudio.com/docs/languages/java). Please install the extensions as described before attempting to run the app.
Simply open the folder that is the root of the git project into Visual Studio Code and it will find everything and compile them for you. The easiest way to start running or debugging the app is to find the public static main in App.java and right above the function will be links to Run and Debug. Click on those and you're off and running.
The code _may_ run as written on other Java IDEs, but that hasn't been tested and isn't supported as part of this project.
## Created with the Maven Archetype extension
Created by the Maven extension for Visual Studio Code to create the project. Use the VSCode Command palette and run Maven: Execute commands to do various things, including automatically creating JARs (though I haven't figured out how to configure this correctly for JAR creation).
<file_sep>/HowItWorks.md
# How This Game Framework Works
## App.java
The game starts from App.java, which creates a window frame with title bar and close buttons. A Menubar and App Content window gets created and added at this time. If you don't want to Menu Bar, comment out the code that creates it.
All Keyboard events get collected at this point and gets passed down to the AppContent window.
## AppMenuBar.java
This is where you describe your menus.
## AppContent.java
This is the content of the top level window frame. This window goes through various Scenes of the Game, from Introduction screen to Game Over.
## AppState.java
This object substitutes for global state to pass data to and from various parts of the application.
## Scenes
Many game frameworks have the concept of a scene, which describes the complete contents and actions of the game window. In this example, I have included an Intro Scene, a Game Scene and a Game Over Scene.
## Sprites
Sprites are a fundamental concept of games that describe any object, explosion, character or even puffs of smoke. Sprites can move, animate, disappear and collide all at once or simply be a background image, it all depends how you define them.
<file_sep>/gameEngine/src/main/java/com/yamasaki/sound/GameSounds.java
package com.yamasaki.sound;
public class GameSounds
{
private String laser1FilePath = "gameEngine/assets/sounds/laser_1.wav";
private String laser2FilePath = "gameEngine/assets/sounds/laser_2.wav";
// private AudioPlayer effectsAudio;
// private AudioPlayer effectsAudio2;
// private AudioPlayer backgroundAudio;
public GameSounds()
{
}
public void playLaser1Sounds()
{
Runnable runnable = new AudioPlayer(laser1FilePath, false);
Thread thread = new Thread(runnable);
thread.start();
}
public void playLaser2Sounds()
{
Runnable runnable = new AudioPlayer(laser2FilePath, false);
Thread thread = new Thread(runnable);
thread.start();
}
}
<file_sep>/gameEngine/src/main/java/com/yamasaki/game_sprites/Projectile.java
package com.yamasaki.game_sprites;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
public class Projectile extends Sprite {
private final double speed = 10;
private final long msMax = 6000;
private AffineTransform transform;
private long msTime;
public Projectile(int x, int y, double theta) {
super(x, y, theta);
this.calcSpeed();
this.transform = this.createTransform(x, y, theta);
this.msTime = System.currentTimeMillis();
}
private void calcSpeed() {
this.dx = Math.sin(theta) * speed;
this.dy = Math.cos(theta) * speed;
}
@Override
public void draw(Graphics2D g2) {
super.draw(g2);
AffineTransform savedTransform;
savedTransform = g2.getTransform();
g2.setTransform(this.transform);
Color colorSave = g2.getColor();
g2.setColor(Color.white);
g2.fillArc(-5, -5, 10, 10, 0, 360);
g2.setColor(colorSave);
g2.setTransform(savedTransform);
}
@Override
public void update() {
super.update();
this.x += (int) Math.round(this.dx);
this.y -= (int) Math.round(this.dy);
this.transform = this.createTransform(x, y, theta);
if (System.currentTimeMillis() - this.msTime > this.msMax) {
this.toRemove = true;
}
}
}<file_sep>/gameEngine/src/main/java/com/yamasaki/game_sprites/BackgroundStar.java
package com.yamasaki.game_sprites;
public class BackgroundStar extends Sprite {
public BackgroundStar(SpriteImage spriteImage, int x, int y, double theta) {
super(spriteImage, x, y, theta);
}
}<file_sep>/gameEngine/src/main/java/com/yamasaki/game_sprites/ShipImage.java
package com.yamasaki.game_sprites;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
public class ShipImage extends SpriteImage {
public ShipImage(String filename) {
super(filename);
this.width = 50;
this.height = 70;
this.xImageFrames = 4;
this.yImageFrames = 1;
this.msFrameDelay = 100;
this.msTotalAnimation = this.msFrameDelay * this.xImageFrames;
this.setupCollisions();
}
/**
* This sets up the sprite to have collision physics
* Note that polygon is centered around 0,0
*/
private void setupCollisions() {
this.hasCollisions = true;
this.pointsCollisions = new ArrayList<Point>();
// ship is just a triangle
this.pointsCollisions.add(new Point(this.width / 2, 0));
this.pointsCollisions.add(new Point(this.width, 58));
this.pointsCollisions.add(new Point(0, 58));
this.rectCollisions = new Rectangle(0, 0, this.width, this.height);
// ship collides with static and dynamic objects
this.collidesWith = new int[2];
this.collidesWith[0] = 0;
this.collidesWith[1] = 1;
}
}<file_sep>/gameEngine/src/main/java/com/yamasaki/game_sprites/SpriteImage.java
package com.yamasaki.game_sprites;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.util.ArrayList;
public class SpriteImage {
protected String filename;
protected Image image;
protected int xImageFrames;
protected int yImageFrames;
protected int width;
protected int height;
protected int msFrameDelay;
protected int msTotalAnimation;
protected boolean hasCollisions;
protected ArrayList<Point> pointsCollisions;
protected Rectangle rectCollisions;
protected int[] collidesWith;
public SpriteImage(String filename) {
this.filename = filename;
Toolkit toolkit = Toolkit.getDefaultToolkit();
this.image = toolkit.createImage(filename);
// initialize to be static image
this.xImageFrames = 1;
this.yImageFrames = 1;
this.msFrameDelay = 0;
this.msTotalAnimation = 0;
// initialize to not have collision polygon
this.hasCollisions = false;
this.pointsCollisions = new ArrayList<Point>();
// Sub class must enter width, height and msFrame
// Sub class must also enter xImageFrames
// Sub class must enter xImageFrames and yImageFrames
}
protected Image getImage() {
return this.image;
}
protected int getImageWidth() {
return this.width;
}
protected int getImageHeight() {
return this.height;
}
protected Rectangle getFrame(int x, int y) {
return new Rectangle(x * this.width, y * this.height, this.width, this.height);
}
protected int getFrameDelay() {
return this.msFrameDelay;
}
protected int getTotalAnimation() {
return this.msTotalAnimation;
}
}
|
47710b6c0f5c05d4e3c3b7838f6ce5f61693471b
|
[
"Markdown",
"Java"
] | 9
|
Java
|
brianyamasaki/JavaGameFramework
|
a269e0e63cc5c1bf1bc1dd16c27683801e039b6b
|
ce01eaacad19890b398596095e5d0f97a7660883
|
refs/heads/main
|
<repo_name>hiltzaile/hiltzaile<file_sep>/komutlar/yetkili-uyar.js
const Discord = require('discord.js');
exports.run = (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let sunucu = message.guild;
let uyarilacak = message.mentions.users.first();
let sebep = args.slice(1).join(' ');
if (message.mentions.users.size < 1) return message.channel.send('👎 Uyaracağın Kişiyi Etiketlemelisin.\nÖrnek Kullanım : `.uyar @kişi sebep`').catch(console.error);
if (sebep.length < 1) return message.channel.send('👎 Uyarı Sebebini Yazmalısın.\nÖrnek Kullanım : `.uyar @kişi sebep`');
if (sebep.length < 3) return message.channel.send('👎 En Az 3 Harf Girmelisin.\nÖrnek Kullanım : `.uyar @kişi sebep`');
message.channel.send('✅ **Kişiyi başarıyla uyardım, özel mesajlarında uyarısı gözükecektir.**')
return uyarilacak.send(`${sunucu} Sunucusunda __\`${sebep}\`__ Sebebiyle Uyarıldın.`);
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['uyarı', 'uyarıver'],
permlevel: 0
};
exports.help = {
name: 'uyar',
description: 'Belirtilen kullanıcıyı özel mesajlarında gözükecek şekilde uyarır.',
usage: 'uyarı'
};
<file_sep>/komutlar/eğlence-tersyazı.js
const discord = require('discord.js')
exports.run = async (bot, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
if (args.length < 1) {
return message.reply(' <a:uzaylih_hyr:700331725238173747> Doğru kullanım .ters <yazı>')
}
await message.channel.send(args.join(' ').split('').reverse().join(''));
};
exports.conf = {
aliases: [ 'ters' ],
enabled: true,
guildOnly: false,
permLevel: 0
};
exports.help = {
name: 'tersyaz',
description: 'Gönderdiğiniz mesajın ters çevrilmiş halini yazar.',
usage: 'tersyaz <yazı>'
};<file_sep>/komutlar/yardım-menüsü-sunucu-kur.js
const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
var prefix = ayarlar.prefix;
exports.run = (client, message, args) => {
let davet = "www.pornhub.com"
let pages = [
'Sunucu Kurulum Komutları Menüsüne Hoşgeldiniz\n\nKomutları Görmek İçin :rewind: ve :fast_forward: emojilerini kullabilirsin.',
`\n** 🎩 [${prefix}normalsunucukur](${davet})** : Sunucudaki Bütün Odaları Silerek 0'dan Sunucu Kurar\n** 🎩 [${prefix}normalsunucukur2](${davet})** : Sunucudaki Bütün Odaları Silerek 0'dan Sunucu Kurar. (2) `
];
let page = 1;
const embed = new Discord.RichEmbed()
.setColor('GREEN')
.setFooter(`Sayfa ${page} / ${pages.length}`)
.setDescription(pages[page-1])
message.channel.send(embed).then(msg => {
msg.react('⏪')
.then(r => {
msg.react('⏩')
//Filter
const backwardsFilter = (reaction, user) => reaction.emoji.name === '⏪' && user.id === message.author.id;
const forwardsFilter = (reaction, user) => reaction.emoji.name === '⏩' && user.id === message.author.id;
const backwards = msg.createReactionCollector(backwardsFilter, { time: 100000 });
const forwards = msg.createReactionCollector(forwardsFilter, { time: 100000 });
forwards.on('collect', r => {
if(page === pages.length) return;
page++;
embed.setDescription(pages[page-1]);
embed.setColor('GREEN')
embed.setFooter(`Sayfa ${page} / ${pages.length}`)
msg.edit(embed)
})
backwards.on('collect', r => {
if(page === 1) return;
page--;
embed.setColor('GREEN')
embed.setDescription(pages[page-1]);
embed.setFooter(`Sayfa ${page} / ${pages.length}`)
msg.edit(embed)
})
})
})
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ["sunucukur"],
permLevel: 0
};
exports.help = {
name: 'sunucu-kur',
description: 'Yardım Listesini Gösterir',
usage: 'sayfalıyardım'
};<file_sep>/komutlar/genel-discrim.js
const Discord = require('discord.js');
const fs = require('fs');
exports.run = async (client, msg, args) => {
if(msg.author.bot || msg.channel.type === "dm") return;
if (!msg.guild) {
return msg.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
if(args[0].length > 4) return msg.reply(' 👎 4 haneli bir rakam girmelisin.\n Örnek Kullanım : `.discrim 8198`');
const discrim = args[0] || msg.author.discriminator;
const users = client.users.filter(user => user.discriminator === discrim).map(user => user.tag);
if (users < 1) {
return msg.reply('<a:uzaylih_hyr:700331725238173747> Sistemde Bulunmayan Bir Tag Girdiniz.\n Örnek Kullanım : `.discrim 8198`');
} else {
msg.channel.send(`${users.join('\n')}`, {split: true, code: "md"})
}
}
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0,
};
exports.help = {
name: 'discrim'
};<file_sep>/komutlar/yetkili-istek-ayarla.js
const Discord = require('discord.js');
const db = require('quick.db')
exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`** 👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
var kanal = message.guild.channels.get(args.join(' ')) || message.mentions.channels.first()
if (!kanal) {
message.reply(" 👎 Lütfen bir kanal etiketleyiniz.")
} else {
db.set(`onk_${message.guild.id}`, kanal.name)
message.reply(`✅ Önerilerin gönderileceği kanal ${kanal} olarak ayarlandı.`)
}
if (args[0] === "sıfırla") {
db.delete(`onk_${message.guild.id}`)
message.reply("✅ Önerilerin gönderileceği kanal sıfırlandı.")
}
}
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
}
exports.help = {
name: 'öneri-kanal',
description: 's',
usage: 's'
};<file_sep>/komutlar/yetkili-mute.js
const Discord = require("discord.js");
const ms = require("ms");
module.exports.run = async (bot, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
//!tempmute @user 1s/m/h/d
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if(!tomute) return message.reply("👎 Bir Kullanıcı Gir.");
let muterole = message.guild.roles.find(`name`, "Muted");
//start of create role
if(!muterole){
try{
muterole = await message.guild.createRole({
name: "Muted",
color: "#000000",
permissions:[]
})
message.guild.channels.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
}catch(e){
console.log(e.stack);
}
}
//end of create role
let mutetime = args[1];
if(!mutetime) return message.reply("👎 Süreyi Girmeyi Unuttun! \nsaniye(s), Dakika(m), Saat(h), Gün(d) \n Örnek Kullanım : `.mute @kullanıcı 1m`");
await(tomute.addRole(muterole.id));
message.reply(`✅ <@${tomute.id}> Adlı Kişi ${ms(ms(mutetime))} Saniye Kadar Mutelendi!`);
setTimeout(function(){
tomute.removeRole(muterole.id);
message.channel.send(`✅ <@${tomute.id}> Adlı Kişinin Mutesi Kalktı!`);
}, ms(mutetime));
//yarrak kafalı gloss
}
exports.conf = {
enabled: true,
aliases: ['sustur',"mute"],
permLevel: 0
};
exports.help = {
name: 'mute',
description: 's',
usage: 'tekrar'
};<file_sep>/komutlar/yetkili-unban.js
const Discord = require('discord.js');
const client = new Discord.Client();
exports.run = (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let guild = message.guild
client.unbanAuth = message.author;
let user = args[0];
if (!user) return message.reply('👎 Banı kaldırılacak kişinin ID numarasını yazmalısın.\nÖrnek Kullanım : `.unban sebep id`').catch(console.error);
message.guild.unban(user);
message.reply("✅ Başarıyla ban kaldırıldı!")
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'unban',
description: 'İstediğiniz kişinin banını kaldırır.',
usage: 'unban [kullanıcı] [sebep]'
};<file_sep>/komutlar/kayıt-sistemi-kayıt.js
const Discord = require('discord.js');
const db = require('quick.db')
const ayarlar = require('../ayarlar.json');
exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let hgmsj = await db.fetch(`codeminghgmsj_${message.guild.id}`)
let alınacakrol = await db.fetch(`codemingkalınacakrol_${message.guild.id}`)
let isimsistemi = await db.fetch(`codemingkisim_${message.guild.id}`)
let kayıtkanalı = await db.fetch(`codemingkkanal_${message.guild.id}`)
let logk = await db.fetch(`codemingklogkanal_${message.guild.id}`)
let verilecekrol = await db.fetch(`codemingkverilecekrol_${message.guild.id}`)
if(!kayıtkanalı) return
if(message.channel.id !== kayıtkanalı) return message.reply(' 👎 Sadece Kayıt Kanalından Kayıt Olabilirsiniz.').then(mete => mete.delete(7000))
if(message.member.roles.has(verilecekrol)) return message.reply(" 👎 Zaten kayıt olmuşsunuz.")
if(!isimsistemi) {
let isim = args[0]
let yaş = args[1]
if(!isim) return message.channel.send(' 👎 Seni kayıt etmem için bir isim girmelisin Örnek: `.kayıt Mahmut 18`').then(mete => mete.delete(7000))
if(isNaN(yaş)) return message.channel.send(' 👎 Yaş sadece sayılardan oluşabilir.').then(mete => mete.delete(7000))
if(yaş.length > 2) return message.channel.send(" 👎 Yaş max 2 karaketerden oluşabilir.")
message.member.setNickname('['+isim+']['+yaş+']')
if(verilecekrol) message.member.addRole(verilecekrol)
if(alınacakrol) message.member.removeRole(alınacakrol)
if(logk) client.channels.get(logk).send("<@!"+message.author.id+'> İçin Kayıt İşlemi Başarı İle Tamamlandı. :clipboard:')
//eğer alınacak rol verisi varsa o rolü al? h tamam ben 2. nin ifini 1 e eklemisim Jalahakdhaus
// noldu en bastaki ifte ! olmucak mi
/// bura wtf
// mete mc atın rolünü yükseltsene hallettim
} else {
if(!isimsistemi.includes("-yas-")) {
let isim = args[0]
if(!isim) return message.channel.send(' 👎 Seni kayıt etmem için bir isim girmelisin Örnek: `.kayıt Mahmut`').then(mete => mete.delete(7000))
let risim = isimsistemi.replace("-uye-", isim)
message.member.setNickname(risim)
if(verilecekrol) message.member.addRole(verilecekrol)
if(alınacakrol) message.member.removeRole(alınacakrol)
if(logk) client.channels.get(logk).send("<@!"+message.author.id+'> İçin Kayıt İşlemi Başarı İle Tamamlandı. :clipboard:')
} else {
let isim = args[0]
let yaş = args[1]
if(!isim) return message.channel.send('< 👎 Seni kayıt etmem için bir isim girmelisin Örnek: `.kayıt Mahmut 18`').then(mete => mete.delete(7000))
if(isNaN(yaş)) return message.channel.send(' 👎 Yaş sadece sayılardan oluşabilir.').then(mete => mete.delete(7000))
if(yaş.length > 2) return message.channel.send(" 👎 Yaş max 2 karaketerden oluşabilir.")
let risim = isimsistemi.replace("-uye-", isim).replace("-yas-", yaş)
message.member.setNickname(risim)
if(verilecekrol) message.member.addRole(verilecekrol)
if(alınacakrol) message.member.removeRole(alınacakrol)
if(logk) client.channels.get(logk).send("<@!"+message.author.id+'> İçin Kayıt İşlemi Başarı İle Tamamlandı. :clipboard:')
// oha lan tahmin ettiğimden kolay oldu jxzhczxc
// kaç dk oldu
// 17 dakika 47 saniye zxfjhgsdıfeds
}// kanwkenwiaj bitti mi tamami ile
// bot.js hg msj ve sora test okey go go bot.js go
}
//okey
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'kayıt',
description: 'taslak',
usage: 'kayıt'
};<file_sep>/komutlar/yardım-menüsü-genel.js
const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
var prefix = ayarlar.prefix;
exports.run = (client, message, args) => {
let davet = "www.pornhub.com"
let pages = [
'Genel Komut Menüsüne Hoşgeldiniz\n\nKomutları Görmek İçin :rewind: ve :fast_forward: emojilerini kullabilirsin.',
`\n** <👀 [${prefix}say](${davet})** : Sunucudaki üye istatistiğini gösterir.\n** 👀 [${prefix}emojiler](${davet})** : Sunucudaki emojileri listeler.\n** 👀 [${prefix}discrim](${davet})** : Discriminizdeki kişileri gösterir.\n** 👀 [${prefix}avatar](${davet})** : Avatarınızı gösterir.\n** 👀 [${prefix}havadurumu <şehir>](${davet})** : Belirttiğiniz şehrin haavadurumunu gösterir.\n** 👀 [${prefix}say](${davet})** : Yılbaşına kalan süreyi gösterir.\n** 👀 [${prefix}wikipedia](${davet})** : Yazdığınız şeyi wikipedia üzerinde arar.\n** 👀 [${prefix}atatürk-sözleri](${davet})** : Rastgele Atatürk sözleri paylaşır.\n** 👀 [${prefix}öneri](${davet})** : Bulunduğunuz sunucu için öneri yaparsınız.`
];
let page = 1;
const embed = new Discord.RichEmbed()
.setColor('GREEN')
.setFooter(`Sayfa ${page} / ${pages.length}`)
.setDescription(pages[page-1])
message.channel.send(embed).then(msg => {
msg.react('⏪')
.then(r => {
msg.react('⏩')
//Filter
const backwardsFilter = (reaction, user) => reaction.emoji.name === '⏪' && user.id === message.author.id;
const forwardsFilter = (reaction, user) => reaction.emoji.name === '⏩' && user.id === message.author.id;
const backwards = msg.createReactionCollector(backwardsFilter, { time: 100000 });
const forwards = msg.createReactionCollector(forwardsFilter, { time: 100000 });
forwards.on('collect', r => {
if(page === pages.length) return;
page++;
embed.setDescription(pages[page-1]);
embed.setColor('GREEN')
embed.setFooter(`Sayfa ${page} / ${pages.length}`)
msg.edit(embed)
})
backwards.on('collect', r => {
if(page === 1) return;
page--;
embed.setColor('GREEN')
embed.setDescription(pages[page-1]);
embed.setFooter(`Sayfa ${page} / ${pages.length}`)
msg.edit(embed)
})
})
})
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['askjlccccccccccccccccccccccccccccccccasdljk'],
permLevel: 0
};
exports.help = {
name: 'genel',
description: 'Yardım Listesini Gösterir',
usage: 'sayfalıyardım'
};<file_sep>/komutlar/bot-bilgi-ping.js
const Discord = require('discord.js');
exports.run = (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
if(new Date().getTime() - message.createdTimestamp < 100) return message.channel.send(` 👌 Gecikme: ${new Date().getTime() - message.createdTimestamp}ms`)
if(new Date().getTime() - message.createdTimestamp < 500) return message.channel.send(`👍 Gecikme: ${new Date().getTime() - message.createdTimestamp}ms`)
if(new Date().getTime() - message.createdTimestamp > 500) return message.channel.send(` 👎 Gecikme: ${new Date().getTime() - message.createdTimestamp}ms`)
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['pong'],
permLevel: 0
};
exports.help = {
name: 'ping',
description: 'Botun pingini gösterir.',
usage: 'ping'
};<file_sep>/komutlar/yetkili-görselkanal.js
const Discord = require('discord.js'),
db = require('quick.db'),
ayarlar = require('../ayarlar.json'),
prefix = ayarlar.prefix
exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`** 👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
const ibrahim = message.mentions.channels.first()
if(!ibrahim) return message.reply(` 👎 Bir Kanal Etiketlemelisin.`)
await db.set(`FrenzyGörselKanal_${message.guild.id}`,ibrahim.id)
message.reply(` <a:uzaylih_evt:700331722012622929> Sadece görsel atılabilir kanalını ${ibrahim} olarak ayarladım.`)
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'görselkanal',
description: 'Frenzy Code',
usage: 'görselkanal #kanal'
};
<file_sep>/komutlar/genel-say.js
const Discord = require('discord.js');
const db = require('quick.db');
exports.run = (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
const embed = new Discord.RichEmbed()
.setColor('GREEN')
.setAuthor(message.author.tag, message.author.avatarURL)
.setTitle(`Üye Sayısı!`)
.setDescription(`Sunucuda **${message.guild.memberCount}** adet kullanıcı, ${message.guild.channels.size} adet kanal ,${message.guild.members.filter(m => m.user.bot).size} adet bot bulunmakta!`)
message.channel.send(embed)
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['sunucusay'],
permLevel: 0
};
exports.help = {
name: 'say',
description: 'Sunucuyu sayarsınız.',
usage: 'sunucu-say'
};<file_sep>/komutlar/yetkili-otorol-kapat.js
const Discord = require('discord.js');
const db = require('quick.db')
const ayarlar = require('../ayarlar.json'),
prefix = ayarlar.prefix
exports.run = async(client, message, args) =>{
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let frenzy_ibrahim = await db.fetch(`Frenzy?Code?OtorolRol_${message.guild.id}`) || await db.fetch(`Frenzy?Code?OtorolKanal_${message.guild.id}`)
if(!frenzy_ibrahim) return message.reply(`👎 Bu sistem zaten kapalı durumda. Açmak için **${prefix}otorol rol kanal**`)
db.delete(`Frenzy?Code?OtorolRol_${message.guild.id}`)
db.delete(`Frenzy?Code?OtorolKanal_${message.guild.id}`)
message.reply(`✅ Otorol kapatıldı!\nYeni gelen kullanıcılara hiç bir rol vermeyeceğim.`)
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['otorol-kapat'],
permLevel: 0
};
exports.help = {
name: 'otorolkapat',
description: 'Otorol Sistemi - Frenzy Code',
usage: 'otorolkapat'
};
<file_sep>/komutlar/yetkili-reklam-kick.js
const db = require('quick.db')
const Discord = require('discord.js')
exports.run = async (bot, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) { // ✅
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
if (!args[0]) return message.reply('👎 Hatalı Kullanım \n Örnek Kulanım : `.reklamkick aç/kapat`')
if (args[0] == 'aç') {
let açıkkapalı = await db.fetch(`reklamkick_${message.guild.id}`)
if(açıkkapalı) return message.reply(`👎 Sistem Zaten Açık`)
db.set(`reklamkick_${message.guild.id}`, 'acik')
message.reply(`✅ Reklam Kick Sistemi Başarı İle Açıldı`)
}
if (args[0] == 'kapat') {
let açıkkapalı = await db.fetch(`reklamkick_${message.guild.id}`)
if(!açıkkapalı) return message.reply(`👎 Sistem Zaten Kapalı`)
db.delete(`reklamkick_${message.guild.id}`, 'kapali')
message.reply(`✅ Reklam Kick Sistemi Başarı İle Kapatıldı`)
}
}
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['reklam-kick'],
permLevel: 0
};
exports.help = {
name: 'reklamkick',
description: 'Reklam kick sistemini açıp kapatır',
usage: 'reklamkick aç/kapat'
};<file_sep>/komutlar/bot-bilgi-komut-sayısı.js
const Discord = require('discord.js');
exports.run = function(client, message, args) {
if(message.author.bot || message.channel.type === "dm") return;
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
const embed = new Discord.RichEmbed()
.setDescription('💋 Toplam **__' + client.commands.size + '__** Komutum Var!')
message.channel.send(embed)
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['komutsay'],
permLevel: 0
};
exports.help = {
name: 'komutsayısı'
};<file_sep>/komutlar/yetkili-otorol.js
const Discord = require('discord.js');
const db = require('quick.db')
const ayarlar = require('../ayarlar.json'),
prefix = ayarlar.prefix
exports.run = async(client, message, args) =>{
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let frenzy_ibrahim = await db.fetch(`Frenzy?Code?OtorolRol_${message.guild.id}`) || await db.fetch(`Frenzy?Code?OtorolKanal_${message.guild.id}`)
if(frenzy_ibrahim) return message.reply(`👎 Bu sistem zaten aktif durumda. Kapatmak için **${prefix}otorolkapat**`)
let frenzy_role = message.mentions.roles.first()
let frenzy_kanal = message.mentions.channels.first()
if(!frenzy_kanal || !frenzy_role) return message.reply(`👎 Otorol sistemini ayarlamak için **rol ve kanal** belirtmelisin.\nÖrnek Kullanım : \`.otorol @üye #otorol \``)
db.set(`Frenzy?Code?OtorolRol_${message.guild.id}`,frenzy_role.id)
db.set(`Frenzy?Code?OtorolKanal_${message.guild.id}`,frenzy_kanal.id)
message.reply(`✅ Otorol aktif edildi!\nYeni gelen kullanıcılara <@&${frenzy_role.id}> rolünü vereceğim.`)
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['otorolayarla'],
permLevel: 0
};
exports.help = {
name: 'otorol',
description: 'Otorol Sistemi - Frenzy Code',
usage: 'otorol rol kanal'
};<file_sep>/komutlar/yetkili-slowmode.js
const Discord = require('discord.js');
exports.run = async(client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
} if (message.channel.type !== "text") return;
const limit = args[0] ? args[0] : 0;
if(!limit) {
message.reply('👎 Yanlış Kullanım \nÖrnek Kullanım : `.yavaş-mod 3`')
return
}
if (limit > 120) {
return message.reply(`👎 **120'den Fazla Yavaş-Mod Açamazsın!**`)
}
message.reply(`✅ **Yavaş Mod __${limit}__ saniye olarak ayarlandı!**`)
var request = require('request');
request({
url: `https://discordapp.com/api/v6/channels/${message.channel.id}`,
method: "PATCH",
json: {
rate_limit_per_user: limit
},
headers: {
"Authorization": `Bot ${client.token}`
},
})};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ["slow-mode", 'yavaşmod'],
permLevel: 0
};
exports.help = {
name: 'yavaş-mod',
description: 'Slowmode Ayarlar',
usage: 'yavaş-mod',
};<file_sep>/komutlar/yetkili-son-üye.js
const Discord = require("discord.js");
const db = require("quick.db");
module.exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let veri = await db.fetch(`sonüye_${message.guild.id}`)
let miran = args[0]
if(miran !== "aç" && miran !== "kapat") return message.reply("👎 Yanlış Kullanım!\n Örnek Kullanım : `.son-üye aç/kapat`")
if(miran === 'aç') {
if(veri === 'acik') return message.reply("👎 Son Üye Sistemi Zaten Açık.\nKapatmak İçin : `.son-üye kapat`")
message.reply("<a:uzaylih_evt:700331722012622929> **Son Üye Kanalı Başarıyla Oluşturuldu.**")
let role = message.guild.roles.find("name", "@everyone");
let kanal = message.guild.createChannel(`Son Üye`, "voice").then(c => {
c.overwritePermissions(role, {
CONNECT: false,
});
let kanals = client.channels.get(kanal) // Berk - Miran ~ CodEming ÇALMAYIN
db.set(`sonüye_${message.guild.id}`, 'acik')
db.set(`codeming_${message.guild.id}`, c.id)
})
}
if(miran === 'kapat') {
if(!veri) return message.reply("👎 Son Üye Sistemi Zaten Kapalı.\nAçmak İçin : `.son-üye aç`")
let kanals = client.channels.get(db.fetch(`codeming_${message.guild.id}`))
if(!kanals) {
message.reply("<a:uzaylih_evt:700331722012622929> **Son Üye Sistemi Başarıyla Kapatıldı.**")
db.delete(`sonüye_${message.guild.id}`)
db.delete(`codeming_${message.guild.id}`)
return
}
message.reply("<a:uzaylih_evt:700331722012622929> **Son Üye Sistemi Başarıyla Kapatıldı.**")
db.delete(`sonüye_${message.guild.id}`)
db.delete(`codeming_${message.guild.id}`)
// Berk - Miran ~ CodEming ÇALMAYIN
kanals.delete()
}
};
module.exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0,
};
module.exports.help = {
name: "son-üye",
description: "üye-durum",
usage: "üye-durum"
};<file_sep>/komutlar/kayıt-sistemi-giriş-sistemi.js
const Discord = require('discord.js');
const db = require('quick.db')
const ayarlar = require('../ayarlar.json');
exports.run = (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**< 👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let codeming = args.slice(0).join(" ")
if(codeming.length < 5) return message.channel.send(' 👎 Giriş Sistemi İçin En Az 5 Karakter Belirtebilirsin.\n Örnek: `.giriş-sistemi Hoşgeldin -uye- Bu Kayıt Olmak İçin .kayıt İsim Yaş`')
message.reply('✅ Sunucuya Yeni Üye Katılınca '+codeming+' Kayıt Kanalına Bu Şekilde Karşılama Mesajı Atacağım.')
db.set(`codeminghgmsj_${message.guild.id}`,codeming)
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'giriş-sistemi',
description: 'taslak',
usage: 'giriş-sistemi'
};<file_sep>/komutlar/yetkili-sayaç-ayarla.js
const Discord = require('discord.js'),
db = require('quick.db'),
ayarlar = require('../ayarlar.json'),
prefix = ayarlar.prefix
exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
const frenzy_sayı = args[1]
const frenzy_kanal = message.mentions.channels.first()
if(!frenzy_sayı || !frenzy_kanal) return message.reply(`👎 Sayaç Sistemini Ayarlamak İçin Lütfen Sayı ve Kanal Belirtiniz.\n Örnek Kullanım : \`${prefix}sayaç #kanal 100\``)
if(isNaN(frenzy_sayı)) return message.reply(`👎 Sayaç Sistemini Ayarlamak İçin Sayıyı Sadece Rakamlardan Yazmalısın!\n Örnek Kullanım : \`${prefix}sayaç #kanal 100\``)
await db.set(`FrenzyCode+SayaçSayı_${message.guild.id}`,frenzy_sayı)
await db.set(`FrenzyCode+SayaçKanal_${message.guild.id}`,frenzy_kanal.id)
message.reply(`✅ **Sayaç Başarıyla Ayarlandı!**`)
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'sayaç',
description: 'Sayaç Sistemi - Frenzy Code',
usage: 'sayaç <sayı> <#kanal>'
};<file_sep>/komutlar/yetkili-embed.js
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`** 👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let wasait = args.slice(0).join(' ');
if (wasait.length < 1) return message.channel.send(' 👎 Herhangi Bir Yazı Yazmalısın.\nÖrnek Kullanım : `.embed yazı`');
const CodEmingembed = new Discord.RichEmbed()
.setColor('RANDOM')
.setDescription(`${wasait}`)
message.channel.send(CodEmingembed);
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};
exports.help = {
name: 'embed',
description: 'Yazdığınızı Mesajı Embedli Atar.',
usage: 'embed',
category: 'Kullanıcı'
}; <file_sep>/komutlar/yetkili-sunucu-avatar-değiş.js
const Discord = require("discord.js"); //Dcs Ekibi
exports.run = (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
const avatar = args[0]
if (!avatar) return message.channel.send("👎 Bir Link Girmelisin!")
const dcs_e = new Discord.RichEmbed()
.setTitle("Sunucu Resmi Değiştirildi")
.setColor("GREEN")
.setTimestamp()
.setImage(avatar)
message.channel.send(dcs_e)
message.guild.setIcon(avatar)
}
exports.conf = {
enabled: true,
guildOnly: true,
aliases: [],
permLevel: 0,
};
exports.help = {
name: 'sunucu-avatar-değiştir',
};<file_sep>/komutlar/yetkili-bot-güvenlik.js
const Discord = require('discord.js');
const db = require('quick.db')
const ayarlar = require('../ayarlar.json')
exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let aktif = await db.fetch(`bottemizle_${message.guild.id}`)
if (aktif) {
db.delete(`bottemizle_${message.guild.id}`)
message.reply('✅ Sistem Başarıyla Kapatıldı. Artık Sunucuya Eklenen Botlar Kicklenmeyecek.\n Açmak İçin : `.bot-güvenlik`')
}
if (!aktif) {
db.set(`bottemizle_${message.guild.id}`, 'aktif')
message.reply('✅ Sistem Başarıyla Açıldı. Artık Sunucuya Eklenen Botlar Otomatik Olarak Kicklenecek.\n Kapatmak İçin : `.bot-güvenlik`')
}
};
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['botgüvenlik'],
permLevel: 0
};
exports.help = {
name: 'bot-güvenlik',
description: 'Sunucuya bot eklendiğinde atılmasını sağlayan sistemi başarıyla aktifleştirirsiniz/kapatırsınız.',
usage: 'bot-güvenlik'
};<file_sep>/komutlar/yetkili-sayaç-kapat.js
const Discord = require('discord.js'),
db = require('quick.db'),
ayarlar = require('../ayarlar.json'),
prefix = ayarlar.prefix
exports.run = async (client, message, args) => {
if(message.author.bot || message.channel.type === "dm") return;
if(!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`**👎 Bu Komutu Kullanmak İçin __Yönetici__ Yetkisine Sahip Olmalısın.**`)
if (!message.guild) {
return message.author.send('bu komut sadece sunucularda kullanılabilir.**');
}
let frenzysayı = await db.fetch(`FrenzyCode+SayaçSayı_${message.guild.id}`)
let frenzykanal = await db.fetch(`FrenzyCode+SayaçKanal_${message.guild.id}`)
if(!frenzysayı && !frenzykanal) return message.reply(`👎 Sayaç Sistemi Zaten Kapalı **Açmak İçin** : \`${prefix}sayaç-ayarla #kanal 100\``)
db.delete(`FrenzyCode+SayaçSayı_${message.guild.id}`)
db.delete(`FrenzyCode+SayaçKanal_${message.guild.id}`)
message.reply(`✅ Sayaç Başarıyla Kapatıldı!!`)
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['sayaçkapat'],
permLevel: 0
};
exports.help = {
name: 'sayaç-kapat',
description: 'Sayaç Sistemi',
usage: 'sayaç-kapat'
};
<file_sep>/komutlar/yardım-menüsü-eğlence.js
const Discord = require('discord.js');
const ayarlar = require('../ayarlar.json');
var prefix = ayarlar.prefix;
exports.run = (client, message, args) => {
let davet = "www.pornhub.com"
let pages = [
'Eğlence Komutları Menüsüne Hoşgeldiniz\n\nKomutları Görmek İçin :rewind: ve :fast_forward: emojilerini kullabilirsin.',
`\n** 🧶 [${prefix}ağla](${davet})** : Botu ağlatırsınız.\n** 🧶 [${prefix}kekoyazı](${davet})** : Yazığınız yazıyı keko yazısına çevirir.\n** 🧶 [${prefix}nahçek](${davet})** : Etiketlediğiniz kişiye nah çekersiniz.\n** 🧶 [${prefix}tabletreis](${davet})** : Tablet reis kutu açılımı yapar.\n** 🧶 [${prefix}tersyazı](${davet})** : Yazığınız yazıyı ters çevirir.`
];
let page = 1;
const embed = new Discord.RichEmbed()
.setColor('GREEN')
.setFooter(`Sayfa ${page} / ${pages.length}`)
.setDescription(pages[page-1])
message.channel.send(embed).then(msg => {
msg.react('⏪')
.then(r => {
msg.react('⏩')
//Filter
const backwardsFilter = (reaction, user) => reaction.emoji.name === '⏪' && user.id === message.author.id;
const forwardsFilter = (reaction, user) => reaction.emoji.name === '⏩' && user.id === message.author.id;
const backwards = msg.createReactionCollector(backwardsFilter, { time: 100000 });
const forwards = msg.createReactionCollector(forwardsFilter, { time: 100000 });
forwards.on('collect', r => {
if(page === pages.length) return;
page++;
embed.setDescription(pages[page-1]);
embed.setColor('GREEN')
embed.setFooter(`Sayfa ${page} / ${pages.length}`)
msg.edit(embed)
})
backwards.on('collect', r => {
if(page === 1) return;
page--;
embed.setColor('GREEN')
embed.setDescription(pages[page-1]);
embed.setFooter(`Sayfa ${page} / ${pages.length}`)
msg.edit(embed)
})
})
})
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ["eglence"],
permLevel: 0
};
exports.help = {
name: 'eğlence',
description: 'Yardım Listesini Gösterir',
usage: 'sayfalıyardım'
};
|
b04f6b9bab0366b6897e8a88e8b755a5f5d0c3c3
|
[
"JavaScript"
] | 25
|
JavaScript
|
hiltzaile/hiltzaile
|
40e882e58011fedeb4b7a20446a0f03ead957dd0
|
667120bfe3654006385ea054c9fa0e86a9498f4f
|
refs/heads/master
|
<repo_name>therackstar/SiliconFeelings<file_sep>/app/server.js
#!/usr/bin/env node
// Setup ========================================================================
var express = require('express'),
mongoose = require('mongoose'),
config = require('config'),
app = express(),
path = require('path'),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
// Configure Aapplication ======================================================
app.configure(function() {
app.use(express.favicon(path.resolve(__dirname, '../public/images/favicon.ico')));
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static('public'));
app.use(app.router);
});
app.configure('development', function() {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Routes =======================================================================
require('../config/routes')(app);
// Connections ==================================================================
require('../config/connections')(io);
// Connect to Database ==========================================================
mongoose.connect(config.database.uri, function(err, res) {
if (err) {
console.log ('ERROR connecting to: ' + config.database.uri + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + config.database.uri);
}
});
// Begin Listening ==============================================================
server.listen(config.express.port, function(error) {
if (error) {
console.log("Unable to listen for connections: " + error);
process.exit(10);
}
console.log("Express is listening on port: " + config.express.port);
});
|
5ad7be98c2449963497380595a131ee030cf6be4
|
[
"JavaScript"
] | 1
|
JavaScript
|
therackstar/SiliconFeelings
|
348c565b09e8bb54c60001fbe36c6f494dc318c0
|
3f56d5c98d5c5892be457607799e955cf8feedac
|
refs/heads/master
|
<file_sep>require 'spec_helper'
describe ClcRubyApi do
it 'has a version number' do
expect(ClcRubyApi::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
it 'logs in successfully' do
Client.login("joeschmo", "savvis123!")
expect.(response).to be_success
end
# it 'logs in with wrong credentials' do
# Client.login("Barack", "POTUS")
# end
end
<file_sep>require "rest-client"
module Client
end
<file_sep>$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'clc_ruby_api'
require 'rspec'
<file_sep>require "clc_ruby_api/version"
require "rest-client"
module ClcRubyApi
createServerRequest = {
:name => "DFT",
:groupId => "a163d30b196f436aac885f2e28ad28b9",
:sourceServerId => "UBUNTU-14-64-TEMPLATE",
:cpu => 1,
:memoryGB => 2,
:type => "standard",
}
CLC_API = "https://api.ctl.io"
def self.setToken(token)
$token = token
end
def self.login(username, password)
begin
response = RestClient.post("https://api.ctl.io/v2/authentication/login",
{:username => username,
:password => <PASSWORD>
}.to_json,
:content_type => :json, :accept => :json
)
rescue => e
puts e.response
end
$token = JSON.parse(response)['bearerToken']
end
def self.getServerDetails(accountAlias, serverId)
begin
response = RestClient.get("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}", :authorization => "Bearer #{$token}")
rescue => e
puts e
end
JSON.parse(response)
end
def self.createServer(accountAlias, payload = {})
response = RestClient.post("https://api.ctl.io/v2/servers/#{accountAlias}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
puts response
JSON.parse(response)
end
def self.deleteServer(accountAlias, serverId)
response = RestClient.delete("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}", :authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getServerCredentials(accountAlias, serverId)
response = RestClient.get("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}/credentials", :authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setServerCpuOrMemory(accountAlias, serverId, payload = {} )
payload = [{:op => "set", :member => "memory", :value => "4"}, {:op => "set", :member => "memory", :value => "4"}]
response = RestClient.patch("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}",
payload.to_json,
:content_type => :json,
:accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setServerCredentials(accountAlias, serverId, payload = {})
payload = [{:op => "set", :member => "password", :value => {:current => "ZH5Sn{YCZqv){T{B", :password => "<PASSWORD>!"}}]
response = RestClient.patch("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.setServerCustomsFields(accountAlias, serverId, payload = {})
payload = {:op => op, :member => member, :value => {:value => {:id => id, :value => value}}},
response = RestClient.patch("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.setServerDescriptionOrGroup(accountAlias, serverId, payload = {})
payload = {:op => op, :member => member, :value => {:value => value}},
response = RestClient.patch("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.setServerDisks(accountAlias, serverId, payload = {})
payload = {:op => op, :member => member, :value => {:value => {:diskId => diskId, :sizeGB => sizeGB}}},
response = RestClient.patch("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.getQueueStatus(accountAlias, serverId)
response = RestClient.get("https://api.ctl.io/v2/operations/#{acctAlias}/status/#{statusId}",
:authorization => "Bearer #{$token}"
)
end
def self.addPublicIpAddress(accountAlias, serverId, payload = {})
portArray = {
:protocol => protocol,
:port => port,
:portTo => portTo
}
payload = {
:ports => portArray,
:sourceRestrictions => {:cidr => cidr}
},
response = RestClient.post("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}/publicIPAddresses",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.getPublicIpAddress(accountAlias, serverId, publicIP)
response = RestClient.get("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}/publicIPAddresses/#{publicIP}", :authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.deletePublicIpAddress(accountAlias, serverId, publicIP)
response = RestClient.get("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}/publicIPAddresses/#{publicIP}", :authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.updatePublicIpAddress(accountAlias, serverId, publicIP, payload = {})
portArray = {
:protocol => protocol,
:port => port,
:portTo => portTo
}
payload = {
:ports => portArray,
:sourceRestrictions => {:cidr => cidr}
}
response = RestClient.post("https://api.ctl.io/v2/servers/#{accountAlias}/#{serverId}/publicIPAddresses",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.archiveServer(accountAlias, serverIds = {})
response = RestClient.post("https://api.ctl.io/v2/operations/#{accountAlias}/servers/archive",
serversIds.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.createSnapshot(accountAlias, payload = {})
payload = {
:snapshotExpirationDays => snapshotExpirationDays,
:serverIds => serverIds
}
response = RestClient.post("https://api.ctl.io/v2/operations/{accountAlias}/servers/createSnapshot",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
end
def self.executeServer(accountAlias, payload = {})
payload = {
:servers => servers,
:package => package
}
response = RestClient.post("https://api.ctl.io/v2/operations/#{accountAlias}/servers/executePackage",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.restoreServer(accountAlias, targetGroupId)
response = RestClient.post("https://api.ctl.io/v2/servers/{accountAlias}/{serverId}/restore",
{:targetGroupId => targetGroupId}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setPowerOperation(accountAlias, powerOperation, serverIds)
response = RestClient.post("https://api.ctl.io/v2/operations/#{accountAlias}/servers/#{powerOperation}",
{:serverIds => serverIds}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setMaintenanceMode(accountAlias, servers)
response = RestClient.post("https://api.ctl.io/v2/operations/#{accountAlias}/servers/setMaintenance",
{:servers => servers}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.archiveGroup(accountAlias, groupId, payload)
payload = {:rel => rel,
:href => href,
:id => id
}
response = RestClient.post("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}/archive",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => authorization
)
JSON.parse(response)
end
def self.restoreGroup(accountAlias, groupId, targetGroupId)
response = RestClient.post("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}/restore",
{:targetGroupId => targetGroupId}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
end
def self.createGroup(accountAlias, payload)
payload = {
:name => name,
:parentGroupId => parentGroupId
}
response = RestClient.post("https://api.ctl.io/v2/groups/#{accountAlias}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.deleteGroup(accountAlias, groupId)
response = RestClient.delete("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getGroup(accountAlias, groupId)
response = RestClient.get("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getGroupBillingDetails(accountAlias, groupId)
response = RestClient.get("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}/billing",
:authorization => authorization)
JSON.parse(response)
end
def self.getGroupMonitorinfStatistics(accountAlias, groupId)
response = RestClient.get("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}/statistics?start=#{datetime}&sampleInterval=dd:hh:mm:ss",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setCustomFields(accountAlias, groupId, patchOperation)
response = RestClient.get("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}",
{:patchOperation => patchOperation}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setGroupNameOrDescription(accountAlias, groupId, patchOperation)
response = RestClient.patch("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}",
{:patchOperation => patchOperation}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.setGroupParent(accountAlias, groupId, patchOperation)
response = RestClient.patch("https://api.ctl.io/v2/groups/#{accountAlias}/#{groupId}",
{:patchOperation => patchOperation}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getCustomGroups(accountAlias)
response = RestClient.get("https://api.ctl.io/v2/accounts/#{accountAlias}/customFields",
:authorization => "Bearer #{$token}"
)
JSON.parse(response)
end
def self.getDataCenter(accountAlias, datacenters)
response = RestClient.get("https://api.ctl.io/v2/datacenters/#{accountAlias}/#{dataCenter}?groupLinks=true|false",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getDataCentereploymentCapalities(accountAlias, datacenter)
response = RestClient.get("https://api.ctl.io/v2/datacenters/#{accountAlias}/#{dataCenter}/deploymentCapabilities",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getDataCenterList(accountAlias)
response = RestClient.get("https://api.ctl.io/v2/datacenters/#{accountAlias}",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getCustomFields(accountAlias)
response = RestClient.get("https://api.ctl.io/v2/accounts/#{accountAlias}/customFields",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.createAntiAffinityPolicy(accountAlias)
response = RestClient.get("https://api.ctl.io/v2/antiAffinityPolicies/#{accountAlias}",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.deleteAntiAffinityPolicy(accountAlias, policyId, payload)
payload = {
:name => name,
:location => location
}
response = RestClient.get("https://api.ctl.io/v2/antiAffinityPolicies/#{accountAlias}/#{policyId}",
payload.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.UpdateAntiAffinityPolicy(accountAlias, policyId, name)
response = RestClient.get("https://api.ctl.io/v2/antiAffinityPolicies/#{accountAlias}/#{policyId}",
{:name => name}.to_json,
:content_type => :json, :accept => :json,
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getAntiAffinityPolicy(accountAlias, policyId)
response = RestClient.get("https://api.ctl.io/v2/antiAffinityPolicies/#{accountAlias}/#{policyId}",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
def self.getAntiAffinityPolicies(accountAlias)
response = RestClient.get("https://api.ctl.io/v2/antiAffinityPolicies/#{accountAlias}",
:authorization => "Bearer #{$token}")
JSON.parse(response)
end
end
<file_sep>source 'https://rubygems.org'
# Specify your gem's dependencies in clc_ruby_api.gemspec
gemspec
|
a44b31974815e82cb92d9d5023c8aab9600f3ec7
|
[
"Ruby"
] | 5
|
Ruby
|
tonycapone/clc-ruby-api
|
46e5af2e6e75ce767779e9ac14d19edbbf116357
|
8e1505afb8f9a1416a2dc6e7403e00aeb96a0756
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node* next;
} LinkedList;
LinkedList* llCreate() {
return NULL;
}
void llDisplay(LinkedList* ll) {
LinkedList* p = ll;
printf("[");
while(p != NULL) {
// printf("%d, ", (*p).value);
printf("%d, ", p->value);
p = (*p).next;
}
printf("]\n");
}
void llAdd(LinkedList** ll, int value) {
LinkedList* nn = (LinkedList*)malloc(1 * sizeof(LinkedList));
nn->value = value;
nn->next = NULL;
LinkedList* p = *ll;
if (p != NULL) {
while(p->next != NULL) {
p = (*p).next;
}
p->next = nn;
} else {
*ll = nn;
}
}
int main() {
LinkedList* ll = llCreate();
llDisplay(ll);
printf("add 5\n");
llAdd(&ll, 5);
llDisplay(ll);
printf("add 2\n");
llAdd(&ll, 2);
llDisplay(ll);
printf("add 8\n");
llAdd(&ll, 8);
llDisplay(ll);
}
<file_sep>#ifndef HCOMPRESS_H_
#define HCOMPRESS_H_
struct tnode;
tnode* createFreqTable(char* filename);
tnode* createHuffmanTree(tnode* leafNodes);
void encodeFile(String filename);
void decodeFile(String filename);
#endif
<file_sep>#include <stdio.h>
#include "hcompress.h"
struct tnode {
double weight;
int c;
struct tnode* left;
struct tnode* right;
struct tnode* parent;
}
int main(int argc, char *argv[]) {
// Check the make sure the input parameters are correct
if (argc != 3) {
printf("Error: The correct format is \"hcompress -e filename\" or
\"hcompress -d filename.huf\"\n"); fflush(stdout);
exit(1);
}
// Create the frequency table by reading the generic file
struct tnode* leafNodes = createFreqTable("decind.txt");
// Create the huffman tree from the frequency table
struct tnode* treeRoot = createHuffmanTree(leafNodes);
// encode
if (strcmp(argv[1], "-e") == 0) {
// Pass the leafNodes since it will process bottom up
encodeFile(argv[2], leafNodes);
} else { // decode
// Pass the tree root since it will process top down
decodeFile(argv[2], treeRoot);
}
return 0;
}
|
fca2fd5cfad3140bba1b99078a2c1aa0ba8c1ffa
|
[
"C"
] | 3
|
C
|
quaranpn4020/cs252
|
47fd19d122d37a109993e3037f3dbf7fe752d819
|
59d09ddad4ed35085397ba1ac90915ee16172868
|
refs/heads/master
|
<file_sep>var request = require('request'),
later = require('later'),
htmlParser = require('htmlparser2');
var config = require('./config');
(function() {
var slackNotification = function(param){
var opt = {
uri: config.slackService,
method: 'POST',
json: {
"text":"AQI推送 PM:"+param.aqiCity+":"+param.aqiNumber+" 空气质量:"+param.aqiContext+"-"+param.aqiInfo,
"attachments":[{'image_url': param.aqiImage}]
}
};
request(opt,function(error, response, body){});
}
var aqi = function (cityUrl,aqiResult) {
var index = 0;
request(cityUrl, function (err, response, body) {
var parser = new htmlParser.Parser({
onopentag : function (name,attribs) {
if (attribs.id === "aqiwgtvalue") {
index++;
aqiResult.aqiInfo = attribs.title;
} else if (attribs.id === "aqiwgtinfo") {
index++;
}
},
ontext: function(context){
if (index == 1) {
aqiResult.aqiNumber = context;
} else if (index == 2){
aqiResult.aqiContext = context;
}
},
onclosetag:function(){
if (index == 2){ index = 0; }
}
});
parser.write(body);
parser.end();
var imageUrl = body.match(/(http:\/\/wgt.aqicn.org\/aqiwgt\/\d+\/[a-zA-Z0-9_-]+.png)/i);
if (imageUrl.length > 0){ aqiResult.aqiImage = imageUrl[0];}
slackNotification(aqiResult);
});
};
switch(process.env.NODE_ENV){
case 'production':
var schedule = later.parse.cron(config.cronExpress);
later.date.localTime();
later.setInterval(function(){
config.city.forEach(function(element){
var result = {
aqiCity : element,
aqiNumber : null,
aqiInfo : null,
aqiContext : null,
aqiImage : null
};
var temp = 'http://aqicn.org/city/'+element+'/'+config.lang;
aqi(temp);
});
},schedule);
return;
default :
var result = {
aqiCity : 'beijing',
aqiNumber : null,
aqiInfo : null,
aqiContext : null,
aqiImage : null
};
aqi('http://aqicn.org/city/beijing/cn',result);
return;
}
})();
<file_sep># The Air Quality Reminder For Slack
## Introduction
You can configuration reminder with cron express and notify slack
## TODO
It can notify every it can be reached, and can monitor record
## Run
`npm install`
`node index.js`
|
49e94115fcdd084a57c4122e9bffb4f28adfa258
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
marlinl/aqi2slack
|
0b8c8881a03850bd38687104dda37975582b4d68
|
45a0d25e5c32799d7605ba640aabf93867af309a
|
refs/heads/master
|
<file_sep>$(function() {
$.ajax({
url: "../json/show-1.json",
success: function(response) {
// console.log(response);
var div1 = $('#main div[class=main-cont]');
//遍历生产商品展示
$(response).each(function(_index, _value) {
// console.log(_value.src);
var temp1 = response[_index],
var div2 = $('<div class="show clearfix"></div>').appendTo(div1);
$(temp1).each(function(index, value) {
var temp2 = temp1[index];
var div3 = $('<div class="frame"></div>').appendTo(div2);
var span = $('<span></span>').appendTo(div3);
var imgA = $('<a></a>').appendTo(div3);
var img = $('<img />').prop('src', temp2.src).appendTo(div3);
var ul = $('<ul></ul>').appendTo(div3);
var name = $('<li></li>').appendTo(ul);
var nameA = $('<a></a>').html(temp2.name).appendTo(name);
var street = $('<li></li>').html(temp2.street).appendTo(ul);
var num = $('<li></li>').html(temp2.num).appendTo(ul);
var manage = $('<li></li>').html(temp2.manage).appendTo(ul);
})
})
}
});
})<file_sep>$(function(){
//头部客户服务
$('.serve').mouseover(function(){
$('.help').css('display', 'block').css('z-index','10');
$(this).css('background', 'antiquewhite').css('border','1px solid gray').css('border-bottom','1px solid white');
}).mouseout(function(){
$(this).css('background', '').css('border','0');
$('.help').css('display', 'none').css('z-index','0');
});
//头部语言栏
$('.language').mouseover(function(){
$(this).css('border','0').css('overflow','visible').css('z-index','10');
$('.language ul').css('border','1px solid gray');
}).mouseout(function(){
$('.language').css('border','1px solid gray').css('overflow','hidden').css('z-index','0');
$('.language ul').css('border','0');
});
//搜索分站
$('.market').mouseover(function(){
$(this).css('border','1px solid gray').css('background-position', '-65px -475px');
$('.market ul').css('display', 'block').css('z-index','10');
}).mouseout(function(){
$('.market').css('border','0').css('background-position', '-65px -445px');;
$('.market ul').css('display', 'none').css('z-index','0');
});
//搜索栏箭头
$('.find-cont span').mouseover(function(){
$('.find-cont ul').css('display', 'block').css('z-index','10');
$(this).css('background-position', '0 -440px');
}).mouseout(function(){
$('.find-cont div').mouseover(function(){
$('.find-cont ul').css('display', 'block').css('z-index','10');
$('.find-cont span').css('background-position', '0 -440px');
}).mouseout(function(){
$('.find-cont ul').css('display', 'none').css('z-index','0');
$('.find-cont span').css('background-position', '0 -470px');
})
$('.find-cont ul').css('display', 'none').css('z-index','0');
$(this).css('background-position', '0 -470px');
});
//导航栏商铺商品
$('.commodity').mouseover(function(){
$('.commodity .menu').css('display', 'block').css('z-index','10');
}).mouseout(function(){
$('.commodity .menu').css('display', 'none').css('z-index','0');
});
//商品二级菜单
$('.menu').mouseover(function(){
$('.commodity .secMenu').css('display', 'block').css('z-index','10');
}).mouseout(function(){
$('.commodity .secMenu').mouseover(function(){
$('.commodity .secMenu').css('display', 'block').css('z-index','10');
}).mouseout(function(){
$('.commodity .secMenu').css('display', 'none').css('z-index','0');
})
$('.commodity .secMenu').css('display', 'none').css('z-index','0');
});
//导航采购
$('.buy').mouseover(function(){
$('.buy-cont').show().css('z-index','10');
}).mouseout(function(){
$('.buy-cont').hide().css('z-index','0');
});
//导航外贸服务
$('.trade').mouseover(function(){
$('.trade-cont').show().css('z-index','10');
}).mouseout(function(){
$('.trade-cont').hide().css('z-index','0');
});
//导航商铺服务
$('.shopServe').mouseover(function(){
$('.shopServe-cont').show().css('z-index','10');
}).mouseout(function(){
$('.shopServe-cont').hide().css('z-index','0');
});
//轮播图第三部分一如改变背景
$('.bazaar .last a').mouseover(function(){
var index = $(this).index();
if(index==0){
$('.bazaar .last span').eq(index).css('background-position','-442px -139px');
}else if(index==1){
$('.bazaar .last span').eq(index).css('background-position','-442px -160px');
}else if(index==2){
$('.bazaar .last span').eq(index).css('background-position','-443px -182px');
}
}).mouseout(function(){
$('.bazaar .last span').eq(0).css('background-position','-462px -139px');
$('.bazaar .last span').eq(1).css('background-position','-462px -160px');
$('.bazaar .last span').eq(2).css('background-position','-463px -182px');
});
//信用平台导航诚信
$('.nav-cont .zhengxin').mouseover(function(){
$('.zx-cont').css('display', 'block').css('z-index', '100');
}).mouseout(function(){
$('.zx-cont').mouseover(function(){
$('.zx-cont').css('display', 'block').css('z-index', '100');
}).mouseout(function(){
$('.zx-cont').css('display', 'none').css('z-index', '0');
})
$('.zx-cont').css('display', 'none').css('z-index', '0');
});
//论坛新闻显示
$('.newsTitle a').mouseover(function(){
var index = $(this).index();
// console.log(index);
$(this).addClass('active').siblings().removeClass('active');
$('.news-deta ul').eq(index).show().siblings().hide();
})
})
<file_sep>$(function(){
var timer = null;
var index = 0;
var length = $('.banner li').length - 1;
setInterval(function(){
index++;
if(index>length){
index = 0;
}
banner(index);
},2000);
function banner(num){
$('.banner .page a').eq(index).addClass('active').siblings().removeClass('active');
$('.banner li').eq(num).show().siblings().hide();
}
//点击页码切换
$('.banner .page a').click(function(){
clearInterval(timer);
timer = null;
index = $(this).index();
$(this).addClass('active').siblings().removeClass('active');
time = setInterval(banner(index),2000)
})
})
<file_sep>$(function(){
// console.log($('.main-sec3 li').length)
//主体li隔行变色
var length = $('.main-sec3 li').length;
for(var i=0; i<length; i++){
if(i%2 != 0){
$('.main-sec3 li').eq(i).css('background', '#f1f1f1')
}
}
$('.main-sec3 li').eq(length-1).css('border-bottom','5px solid #e3e4e8').css('border-radius', '5px');
$('.main-sec3 li').eq(0).css('border-top','1px solid #e3e4e8').css('border-radius', '5px');
})
<file_sep>$(function(){
var timer = null;
var index = 0;
var distance = -$('.banner li').width();
timer = setInterval(banner,2000);
function banner(){
$('.banner-img').css('left', distance);
if(distance == 0){
distance = -$('.banner li').width();
}
$('.page a').eq(index).addClass('active').siblings().removeClass('active');
index++;
if(index>2){
index = 0;
distance = -$('.banner li').width();
}
distance*=index;
}
$('.page a').click(function(){
clearInterval(timer);
timer = null;
index = $(this).index();
distance*=index;
$('.banner-img').css('left', distance);
if(distance == 0){
distance = -$('.banner li').width();
}
$(this).addClass('active').siblings().removeClass('active');
timer = setInterval(banner,2000);
})
})
<file_sep>$(function(){
//sec3点击
$('.choice-l a').click(function(){
$(this).addClass('active').siblings().removeClass('active');
})
$('.choice .show-show').click(function(){
$('.show-1').css('z-index', '10');
$('.show-2').hide().css('z-index', '1');
changePage(1);
})
$('.choice .show-show-2').click(function(){
$('.show-1').css('z-index', '1');
$('.show-2').show().css('z-index', '10');
})
//sec5点击
//点击上下页切换上下页
var index = 0;
var pageLength = $('.main-cont .pageNum').length;
var show = $('.main-cont .show');
$('.main-cont .pageBack').click(function(){
// alert('上');
index--;
if(index<0){
index = 0;
return;
}
changePage(index);
})
$('.main-cont .pageNext').click(function(){
// alert('下');
index++;
if(index> pageLength-1){
index = pageLength-1;
}
changePage(index);
})
//点击页码切换上下页
$('.page .pageNum').click(function(){
//1开始...
var index = $(this).index() - 1;
// console.log(index);
changePage(index);
})
//点击确定直接跳转
$('.go').click(function(){
var index = $('.go input').val() - 1;
if(index<0){
alert('请输入正确数字');
}else if(index > pageLength-1){
alert('请输入正确数字');
}else{
changePage(index);
}
})
function changePage(num){
show.eq(num).show().siblings(".show").hide();
$('.choice span').html(num+1 + '/3');
$('.page .pageNum a').eq(num).addClass('active').parent().siblings().children('.pageNum a').removeClass('active');
}
})
|
424611f8d16309bbb1f3e9d02c994a8b89b8cbe0
|
[
"JavaScript"
] | 6
|
JavaScript
|
bellmit/yiwugou-1
|
9346b2550ef3787031fa39115141e0e5e1e9c8ff
|
85256ef1121ed82b919ba0ee610c0afe56b2dc7d
|
refs/heads/main
|
<repo_name>borisskert/spring-javafx<file_sep>/src/test/java/de/borisskert/examples/springjavafx/TestBeanConfiguration.java
package de.borisskert.examples.springjavafx;
import javafx.application.Application;
import javafx.application.HostServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestBeanConfiguration {
@Bean
Application application() {
return new JavaFxApplication();
}
@Bean
HostServices hostServices(Application application) {
return application.getHostServices();
}
}
<file_sep>/README.md
# Spring-JavaFX
This example shows how to build a JavaFX application using Spring Framework.
## Further links
* [<NAME>'s Spring Tips](https://spring.io/blog/2019/01/16/spring-tips-javafx)
<file_sep>/src/main/java/de/borisskert/examples/springjavafx/StageListener.java
package de.borisskert.examples.springjavafx;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URL;
@Component
public class StageListener implements ApplicationListener<StageReadyEvent> {
private final String applicationTitle;
private final Resource fxml;
private final ApplicationContext context;
public StageListener(
@Value("${spring.application.ui.title}") String applicationTitle,
@Value("${classpath:/ui.fxml}") Resource fxml,
ApplicationContext context
) {
this.applicationTitle = applicationTitle;
this.fxml = fxml;
this.context = context;
}
@Override
public void onApplicationEvent(StageReadyEvent stageReadyEvent) {
try {
Stage stage = stageReadyEvent.getStage();
URL url = this.fxml.getURL();
FXMLLoader fxmlLoader = new FXMLLoader(url);
fxmlLoader.setControllerFactory(context::getBean);
Parent root = fxmlLoader.load();
Scene scene = new Scene(root, 600, 600);
stage.setScene(scene);
stage.setTitle(this.applicationTitle);
stage.show();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
42a6f8325cc18007d9bc6daaf780d57346dcf370
|
[
"Markdown",
"Java"
] | 3
|
Java
|
borisskert/spring-javafx
|
24fdf07c9d194f08a6f784f6755a37aa224c5daf
|
a8ccd09aed6aede316932d6e42a160c7139fb83c
|
refs/heads/master
|
<repo_name>ozancakar20/GZS<file_sep>/Görsel + Veritabanı (C##)/Gaz_Sensoru/Veritabanı.cs
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 Gaz_Sensoru
{
public partial class Veritabanı : Form
{
public Veritabanı()
{
InitializeComponent();
}
// SqlConnection baglan = new SqlConnection("Data Source=casper\\sqlexpress;Initial Catalog=gazSensoru;Integrated Security=True");
private void Veritabanı_Load(object sender, EventArgs e)
{
butonLedYak frm = new butonLedYak();
frm.verileriGoster();
}
private void Veritabanı_FormClosed(object sender, FormClosedEventArgs e)
{
}
}
}
<file_sep>/Arduino Kodu/gaz_sensoru.ino
//7 6 5 4 3 2 1 0 E RW RS V0 VDD VSS 15 16
#include<LiquidCrystal.h>
LiquidCrystal lcd(3,4,5,6,7,8);
const int pinGaz=A1;
const int buzzer=13;
const int led=12;
void setup()
{
lcd.begin(16,2);
pinMode(pinGaz,INPUT);
pinMode(buzzer,OUTPUT);
pinMode(led,OUTPUT);
Serial.begin(9600);
lcd.clear();
lcd.home();
lcd.print(" GAZ DURUMU");
lcd.setCursor(0,1);
lcd.print(" NORMAL");
}
void loop()
{
int gazOku=analogRead(pinGaz);
// Serial.println(gazOku);
int okunan=Serial.read();
if(okunan=='a')
{
digitalWrite(led,HIGH);
}
if(okunan=='b'){
digitalWrite(led,LOW);
}
if(gazOku<300)
{
Serial.print("a");
lcd.clear();
lcd.home();
lcd.print(" GAZ DURUMU");
lcd.setCursor(0,1);
lcd.print(" NORMAL");
}
else
{
Serial.print("b");
lcd.clear();
lcd.home();
lcd.print(" GAZ DURUMU");
lcd.setCursor(0,1);
lcd.print(" KACAK VAR");
digitalWrite(buzzer,HIGH);
delay(300);
digitalWrite(buzzer,LOW);
delay(200);
}
delay(1000);
}<file_sep>/Görsel + Veritabanı (C##)/Gaz_Sensoru/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Data.SqlClient;
namespace Gaz_Sensoru
{
public partial class butonLedYak : Form
{
public butonLedYak()
{
InitializeComponent();
}
SqlConnection baglan = new SqlConnection("data source=ACER-BILGISAYAR;initial catalog=gazSensoru;integrated security=True;");
Veritabanı vrtbn = new Veritabanı();
public void verileriGoster()
{
vrtbn.listView1.Items.Clear();
baglan.Open();
SqlCommand komut = new SqlCommand("Select *from Kayitlar2",baglan);
SqlDataReader oku = komut.ExecuteReader();
while(oku.Read())
{
ListViewItem ekle = new ListViewItem();
ekle.Text = oku["tarih"].ToString();
ekle.SubItems.Add(oku["veri"].ToString());
vrtbn.listView1.Items.Add(ekle);
}
baglan.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
string [] portlar = SerialPort.GetPortNames();
foreach (string port in portlar)
{
comboBox1.Items.Add(port);
}
CheckForIllegalCrossThreadCalls = false;
verileriGoster();
}
private void btnBaglan_Click(object sender, EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
MessageBox.Show("Bağlantı daha önce Kurulmuş!!!", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button3);
}
else
{
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Parity = Parity.None;
serialPort1.PortName = comboBox1.Text;
serialPort1.Open();
MessageBox.Show("Bağlantı Kuruldu");
}
}
catch (Exception)
{
MessageBox.Show("Cihazın Bağlı olduğu portu seçiniz", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3);
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[1];
serialPort1.Read(buffer, 0, 0);
string gelen = serialPort1.ReadExisting();
// MessageBox.Show(gelen);
string uyari="";
if (gelen == "a")
{
uyari = "Gaz Durumu Normal";
listBox1.Items.Add(uyari);
this.BackColor = Color.Turquoise;
}
if(gelen=="b")
{
uyari = "Dikkat Gaz Kaçağı var";
listBox1.Items.Add(uyari);
this.BackColor = Color.Red;
}
string tarih = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
baglan.Open();
SqlCommand komut = new SqlCommand("insert into Kayitlar2 (tarih,veri) Values('" + tarih + "','" +uyari+ "')", baglan);
komut.ExecuteNonQuery();
baglan.Close();
}
private void hakkındaToolStripMenuItem_Click(object sender, EventArgs e)
{
Hakkında hkn = new Hakkında();
hkn.ShowDialog();
}
private void çıkışToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
vrtbn.ShowDialog();
verileriGoster();
}
long id = 0;
private void button2_Click(object sender, EventArgs e)
{
if (vrtbn.listView1.SelectedItems.Count != 0)
{
id = long.Parse(vrtbn.listView1.SelectedItems[0].Text);
{
DialogResult sonuc = MessageBox.Show("Veri Silinsin mi?", "Silinecek", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button3);
if (sonuc == DialogResult.OK)
{
baglan.Open();
SqlCommand komut = new SqlCommand("Delete From Kayitlar2 where sira=(" + id + ")", baglan);
komut.ExecuteNonQuery();
baglan.Close();
verileriGoster();
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
string tarih = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
lblTarih.Text = tarih;
}
int sayi = 0;
private void button2_Click_1(object sender, EventArgs e)
{
if (sayi == 1)
{
serialPort1.Write("b");
lblLed.Text = "Led Sönük";
btnLedYak.Text = "Yak";
sayi--;
return;
}
if (sayi == 0)
{
serialPort1.Write("a");
lblLed.Text = "Led Yanıyor";
btnLedYak.Text = "Söndür";
sayi++;
}
}
private void butonLedYak_FormClosing(object sender, FormClosingEventArgs e)
{
System.Environment.Exit(5);
}
}
}
<file_sep>/README.md
# GZS
Arduino ile Duman / Gaz Ölçümü (Veritabanı bağlantısı + Masaüstü arayüzü ile)
<file_sep>/Görsel + Veritabanı (C##)/Gaz_Sensoru/Giris.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Gaz_Sensoru
{
public partial class Giris : Form
{
public Giris()
{
InitializeComponent();
}
SqlConnection baglan = new SqlConnection("data source=ACER-BILGISAYAR;initial catalog=gazSensoru;integrated security=True;");
butonLedYak frm = new butonLedYak();
private void button1_Click(object sender, EventArgs e)
{
try
{
baglan.Open();
SqlCommand komut = new SqlCommand("Select *from giris where ad=@adi AND sifre=@sifresi", baglan);
komut.Parameters.AddWithValue("@adi", textBox1.Text.Trim());
komut.Parameters.AddWithValue("@sifresi", textBox2.Text.Trim());
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(komut);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
butonLedYak af = new butonLedYak();
af.Show();
this.Hide();
}
else
{
if (textBox1.Text != "A")
MessageBox.Show("Kullanıcı Adı veya Şifre Hatalı");
baglan.Close();
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}
private class anaForm : butonLedYak
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}
|
ed80179d260872d7558134c0e1ffe29ce9d4cc7e
|
[
"Markdown",
"C#",
"C++"
] | 5
|
C#
|
ozancakar20/GZS
|
fae1cc690134f46c61e3b01fd2e10e00f2120abd
|
9eeebc32257eece8beef735027d944f9708b4bcb
|
refs/heads/master
|
<repo_name>yuri-coder/BoringRepository3<file_sep>/client/src/app/pet.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
@Injectable()
export class PetService {
constructor(private http:HttpClient) { }
all(cb){
this.http.get("/api/pets")
.subscribe(data=>cb(data));
}
create(pet, cb){
this.http.post("/api/pets/new", pet)
.subscribe(data=>cb(data));
}
findById(id, cb){
this.http.get("/api/pets/"+id)
.subscribe(data=>cb(data));
}
update(pet, cb){
this.http.put("/api/pets/"+pet._id+"/update", pet)
.subscribe(data=>cb(data));
}
destroy(id, cb){
this.http.delete("/api/pets/"+id+"/destroy")
.subscribe(data=>cb(data));
}
like(id, cb){
this.http.get("/api/pets/"+id+"/like")
.subscribe(data=>cb(data));
}
}
<file_sep>/client/src/app/editpet/editpet.component.ts
import { Component, OnInit } from '@angular/core';
import { PetService } from "../pet.service";
import {Router, ActivatedRoute} from "@angular/router";
@Component({
selector: 'app-editpet',
templateUrl: './editpet.component.html',
styleUrls: ['./editpet.component.css']
})
export class EditpetComponent implements OnInit {
private pet:any;
private errors:any;
constructor(private ps:PetService, private router:Router, private route:ActivatedRoute) { }
ngOnInit() {
this.pet = {};
this.errors = [];
this.route.params.subscribe(params => this.ps.findById(params["id"], (data)=>{
if(data.errors){
this.router.navigate([""]);
}
else{
//this.pet = data;
this.pet = {
_id: data._id,
name: data.name,
description: data.description,
type: data.type,
skill1: data.skills[0],
skill2: data.skills[1],
skill3: data.skills[2]
}
}
}));
}
create(){
this.errors = [];
let skillList = [];
if(this.pet.skill1 != "" && !(skillList.includes(this.pet.skill1))){
skillList.push(this.pet.skill1);
}
if(this.pet.skill2 != "" && !(skillList.includes(this.pet.skill2))){
skillList.push(this.pet.skill2);
}
if(this.pet.skill3 != "" && !(skillList.includes(this.pet.skill3))){
skillList.push(this.pet.skill3);
}
let petToCreate = {
_id: this.pet._id,
name: this.pet.name,
description: this.pet.description,
type: this.pet.type,
skills: skillList
};
this.ps.update(petToCreate, (data)=>{
if(data.errors){
console.log(data.errors);
for(let error in data.errors){
this.errors.push(data.errors[error].message);
}
}
else{
this.router.navigate(["/details/" + this.pet._id]);
}
});
}
cancel(){
this.router.navigate(["/details/" + this.pet._id]);
}
}
<file_sep>/config/routes.js
//let CommentController = require("../controllers/CommentController.js");
//let ListingController = require("../controllers/ListingController.js");
let PetController = require("../controllers/PetController.js");
let path = require("path");
module.exports =(app)=>{
app.get("/api/pets",PetController.all);
app.get("/api/pets/:id",PetController.findById);
app.post("/api/pets/new",PetController.create);
app.put("/api/pets/:id/update",PetController.update);
app.delete("/api/pets/:id/destroy",PetController.destroy);
app.get("/api/pets/:id/like",PetController.like);
// ********************************************************
// Users
// ********************************************************
//app.post("/api/register",UserController.register);
//app.post("/api/login",UserController.login);
// ********************************************************
// Listings
// ********************************************************
//app.get("/api/listings",ListingController.all);
//app.post("/api/listings/new",ListingController.create);
//app.get("/api/listings/:id",ListingController.findById);
//app.get("/api/listings/lotd",ListingController.lotd);
//app.get("/api/listings/:id",ListingController.findById);
//app.put("/api/listings/:id/update",ListingController.update);
//app.delete("/api/listings/:id/destroy",ListingController.destroy);
// ********************************************************
// Comments
// ********************************************************
//app.get("/api/comments",CommentController.all);
//app.post("/api/comments/:id/new",CommentController.create);
//app.get("/api/comments/:id",CommentController.findById);
// ********************************************************
// Angular
// ********************************************************
app.all("*", (req,res,next) => {
res.sendFile(path.resolve("./client/dist/index.html"))
});
}<file_sep>/client/src/app/petinfo/petinfo.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { PetService } from "../pet.service";
@Component({
selector: 'app-petinfo',
templateUrl: './petinfo.component.html',
styleUrls: ['./petinfo.component.css']
})
export class PetinfoComponent implements OnInit {
private pet:any;
private liked:any;
constructor(private ps:PetService, private router:Router, private route:ActivatedRoute) { }
ngOnInit() {
this.liked = false;
this.pet = {};
this.route.params.subscribe(params => this.ps.findById(params["id"], (data)=>{
if(data.errors){
this.router.navigate([""]);
}
else{
this.pet = data;
}
}));
}
like(){
this.ps.like(this.pet._id, (data)=>{
if(data.errors){
console.log(data.errors);
}
else{
this.pet = data;
this.liked = true;
}
});
}
adopt(){
this.ps.destroy(this.pet._id, (data)=>{
console.log(data);
this.router.navigate([""]);
});
}
}
<file_sep>/controllers/PetController.js
let Pet = require("mongoose").model("Pet");
class PetController{
all(req,res){
console.log("In PetController all");
Pet.find({},(err, pets)=>{
if(pets){
return res.json(pets);
}
else{
return res.json({errors:"Failed to get pets"});
}
});
}
findById(req,res){
console.log("In PetController findById");
Pet.findOne({_id:req.params.id}, (err, pet)=>{
if(pet){
return res.json(pet);
}
else{
return res.json({errors: "Failed to retrieve pet!"});
}
});
}
create(req,res){
console.log("In PetController create");
Pet.findOne({name:req.body.name}, (err,pet)=>{
if(pet){
return res.json({errors:{err:{message:"A pet with this name already exists!"}}});
}
else{
let newPet = new Pet(req.body);
newPet.likes = 0;
newPet.save((err)=>{
if(err){
return res.json({errors:newPet.errors});
}
else{
return res.json(newPet);
}
});
}
});
}
update(req,res){
console.log("In PetController udpate");
Pet.findOne({_id:req.params.id}, (err, pet)=>{
if(err){
return res.json({errors:"Failed to retrieve pet!"});
}
else{
Pet.findOne({name:req.body.name}, (err,pet2)=>{
if(pet2 && (pet2._id != req.params.id)){
console.log(pet2._id);
console.log(pet._id);
return res.json({errors:{err:{message:"A pet with this name already exists!"}}});
}
else{
pet.name = req.body.name;
pet.type = req.body.type;
pet.description = req.body.description;
pet.skills = req.body.skills;
pet.save(err=>{
if(err){
return res.json({errors:err});
}
else{
return res.json(pet);
}
});
}
});
}
});
}
destroy(req,res){
console.log("Goodbye, Mitty");
Pet.remove({_id:req.params.id}, (err)=>{
if(err){
return res.json(false);
}
else{
return res.json("Miiiiiiii~!");
}
});
}
like(req,res){
Pet.findOne({_id:req.params.id}, (err,pet)=>{
if(err){
return res.json({errors:"Failed to retrieve pet!"});
}
else{
pet.likes = Number(pet.likes) + 1;
pet.save(err=>{
if(err){
return res.json({errors:err});
}
else{
return res.json(pet);
}
});
}
});
}
}
// class UserController{
// all(req,res){
// User.find({},(err,users)=>{
// if(users){
// return res.json(users);
// }else{
// return res.json({errors:"Failed to retrieve users"});
// }
// });
// }
// register(req,res){
// User.findOne({email:req.body.email},(err,user)=>{
// if(user){
// return res.json({errors:"A user with this email already exists!"});
// }else{
// let newUser = new User(req.body);
// newUser.save((err)=>{
// if(err){
// return res.json({errors:newUser.errors});
// }else{
// req.session.user_id = newUser._id;
// return res.json(newUser);
// }
// });
// }
// });
// }
// login(req,res){
// User.findOne({email:req.body.email},(err,user)=>{
// if(!user){
// return res.json({errors:"No user with this email was found."});
// }else{
// if(req.body.password == <PASSWORD>.password){
// req.session.user_id = user._id;
// return res.json(user);
// }else{
// return res.json({errors:"Invalid Credentials."});
// }
// }
// });
// }
// }
// class ListingController{
// all(req,res){
// Listing.find({})
// .populate({
// path:"user",
// model:"User"
// })
// .exec((err,listings)=>{
// if(listings){
// return res.json(listings);
// }else{
// return res.json({errors:"Failed to retrieve listings."});
// }
// });
// }
// findById(req,res){
// Listing.findOne({_id:req.params.id})
// .populate({
// path:"user",
// model:"User"
// })
// .exec((err,listing)=>{
// if(listing){
// return res.json(listing);
// }else{
// return res.json({errors:"Failed to populate listing."});
// }
// });
// }
// create(req,res){
// let listing = new Listing(req.body);
// listing.user = req.session.user_id;
// listing.save((err)=>{
// if(err){
// return res.json({errors:listing.errors});
// }else{
// User.findOne({_id:req.session.user_id},(err,user)=>{
// if(user){
// user.listings.push(listing);
// user.save(err=>{
// if(err){
// return res.json({errors:user.errors});
// }else{
// return res.json(listing);
// }
// })
// }else{
// return res.json({errors:"Failed to lookup user."});
// }
// });
// }
// });
// }
// update(req,res){
// Listing.findOne({_id:req.params.id},(err,listing)=>{
// if(err){
// return res.json({errors:err});
// }else{
// listing.title = req.body.title;
// listing.description = req.body.description;
// listing.price = req.body.price;
// listing.location = req.body.location;
// listing.src = req.body.src;
// listing.save(err=>{
// if(err){
// return res.json({errors:err});
// }else{
// return res.json(listing);
// }
// });
// }
// });
// }
// destroy(req,res){
// Listing.remove({_id:req.params.id},(err)=>{
// if(err){
// return res.json(false);
// }else{
// return res.json(true);
// }
// });
// }
// lotd(req,res){
// Listing.find({})
// .populate({
// path:"user",
// model:"User"
// })
// .exec((err,listings)=>{
// if(listings){
// let index = Math.floor(Math.random() * listings.length);
// let listing = listings[index];
// return res.json(listing);
// }else{
// return res.json({errors:"Failed to retrieve listings."});
// }
// });
// }
// }
module.exports = new PetController();<file_sep>/models/Pet.js
let mongoose = require('mongoose');
let ObjectId = mongoose.Schema.Types.ObjectId;
mongoose.model('Pet',new mongoose.Schema({
name:{type:String, required:[true, "Really? You didn't think to give your pet a name? Idiot..."],minlength:[3, "Quit being lazy and give your pet a name at least 3 character long!"],maxlength:[255, "Jesus, surely your pet doesn't need to have that long of a name... limit it to 255 characters!"]},
description:{type:String,required:[true, "Even boring pets need a description..."],minlength:[3, "Wow, what a deep and meaningful description... try to make it at least 3 characters, ok?"],maxlength:[255, "Look, we don't want your pet's life story. Just limit it to 255 characters"]},
type:{type:String,required:[true, "Seriously, we need to know what kind of pet this is..."],minlength:[3, "Erm... can you make this 3 characters long please?"],maxlength:[255, "Either you typed gibberish or put WAY too many adjectives here. Limit it to 255 characters, yeah?"]},
likes:{type:Number},
skills:{
type: [{type:String, maxlength:255}],
validate: [arrayLimit, "Okay okay, we get it, your pet has a bajillion skills... but please only list 3!"]
}
},{timestamps:true}));
function arrayLimit(val){
return val.length <= 3;
}<file_sep>/client/src/app/addpet/addpet.component.ts
import { Component, OnInit } from '@angular/core';
import { PetService } from "../pet.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-addpet',
templateUrl: './addpet.component.html',
styleUrls: ['./addpet.component.css']
})
export class AddpetComponent implements OnInit {
private pet:any;
private errors:any;
constructor(private ps:PetService, private router:Router) { }
init(){
this.pet = {
name:"",
description:"",
type:"",
skill1:"",
skill2:"",
skill3:""
};
this.errors = [];
}
ngOnInit() {
this.init();
}
create(){
this.errors = [];
let skillList = [];
if(this.pet.skill1 != "" && !(skillList.includes(this.pet.skill1))){
skillList.push(this.pet.skill1);
}
if(this.pet.skill2 != "" && !(skillList.includes(this.pet.skill2))){
skillList.push(this.pet.skill2);
}
if(this.pet.skill3 != "" && !(skillList.includes(this.pet.skill3))){
skillList.push(this.pet.skill3);
}
let petToCreate = {
name: this.pet.name,
description: this.pet.description,
type: this.pet.type,
skills: skillList
};
this.ps.create(petToCreate, (data)=>{
if(data.errors){
console.log(data.errors);
for(let error in data.errors){
this.errors.push(data.errors[error].message);
}
}
else{
this.router.navigate([""]);
}
});
}
cancel(){
this.router.navigate([""]);
}
}
<file_sep>/client/src/app/allpets/allpets.component.ts
import { Component, OnInit } from '@angular/core';
import { PetService } from "../pet.service";
import {Router} from '@angular/router';
@Component({
selector: 'app-allpets',
templateUrl: './allpets.component.html',
styleUrls: ['./allpets.component.css']
})
export class AllpetsComponent implements OnInit {
private pets:any;
private petsDict:any;
constructor(private ps:PetService, private router:Router) { }
ngOnInit() {
this.pets = [];
this.petsDict = {};
this.ps.all((data)=>{
this.pets = data;
this.sortPets();
});
}
sortPets(){
for(let pet of this.pets){
if(this.petsDict[pet.type.toLowerCase()]){
this.petsDict[pet.type.toLowerCase()].push(pet);
}
else{
this.petsDict[pet.type.toLowerCase()] = [pet];
}
}
console.log(this.petsDict);
this.pets = [];
console.log("Before for");
for(let i in this.petsDict){
console.log("In i");
console.log(i);
for(let j of this.petsDict[i]){
console.log("in j");
console.log(j);
this.pets.push(j);
}
}
console.log(this.pets);
}
details(id){
this.router.navigate(["/details/" + id]);
}
edit(id){
this.router.navigate(["/edit/"+id]);
}
}
|
b93f574baf7fb59e8d2e04393950b9cf4f8dc7ff
|
[
"JavaScript",
"TypeScript"
] | 8
|
TypeScript
|
yuri-coder/BoringRepository3
|
7a7a0a90d9b68a10a8886dc95aeba89d7db17985
|
b3fd629a5ffbe5240e5ddebed60de475f9248a75
|
refs/heads/master
|
<file_sep>print("_____________")
print("SELMAT DATANG")
print("-------------")
print("--PERKALIAN--")
print("by TraperWaze")
print(" ")
#
first=input("Masukkan angka : ")
second=input("Kalikan dengan : ")
print("HASIL: ")
print(str(first)+" x "+str(second)+ " = "+ str(first*second))
print(" ")
<file_sep>n=float(input("Angka yang akan dibagi: "))
divider=float(input("Angka pembagi: "))
result=n/divider
print(str(n)+" / "+str(divider)+" = "+str(result))
<file_sep>c = input("Masukkan nomor: ")
a = input("Tambah dengan: ")
b=c+a
print("HASIL = "+ str(b))
|
c3b1c4c83f4594de0fbddc34affa820410e0c619
|
[
"Python"
] | 3
|
Python
|
traperwaze/pythonify
|
882a6d2e55f7965ba7a27785d16409180e3adada
|
ea96dfdbcf07b3773fc50534ab0346e3c2d08255
|
refs/heads/master
|
<repo_name>mattgd/reddit-DadJokes-Alexa<file_sep>/index.js
'use strict';
const Alexa = require('ask-sdk-core');
const snoowrap = require('snoowrap');
const reddit = new snoowrap({
userAgent: 'App for /r/dadjokes Alexa skill.',
clientId: process.env.REDDIT_CLIENT_ID,
clientSecret: process.env.REDDIT_CLIENT_SECRET,
refreshToken: process.env.REDDIT_REFRESH_TOKEN
});
const DAD_JOKES_SUBREDDIT = 'dadjokes'
const SKILL_NAME = 'Reddit Dad Jokes';
const REPROMPT_PHRASE = 'Would you like to hear another joke?';
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* @param min The minimum value.
* @param max The maximum value.
* @returns A random number between min and max.
*/
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
/**
* Returns a Promise which resolves as a joke from the r/dadjokes subreddit.
*/
const getJoke = () => new Promise(resolve => {
reddit.getSubreddit(DAD_JOKES_SUBREDDIT).getHot().then(listing => {
const submissionIdx = getRandomInt(0, listing.length);
const submission = listing[submissionIdx];
var title = submission.title.trim();
if (!/[.!?,;:]$/.test(title)) {
title += '.';
}
const joke = `${title} ${submission.selftext.trim()}`;
resolve(joke);
});
});
// Core functionality for Dad Jokes skill
const GetJokeHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
// Checks request type
return request.type === 'LaunchRequest'
|| (request.type === 'IntentRequest'
&& (request.intent.name === 'GetJokeIntent'
|| request.intent.name === 'AMAZON.YesIntent'));
},
async handle(handlerInput) {
const joke = await getJoke();
const speakText = `${joke} <break time="2s"/> ${REPROMPT_PHRASE}`
return handlerInput.responseBuilder
.speak(speakText)
.withSimpleCard(SKILL_NAME, joke)
.reprompt(REPROMPT_PHRASE)
.getResponse();
},
};
const HelpHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' &&
request.intent.name === 'AMAZON.HelpHandler';
},
handle(handlerInput) {
return handlerInput.responseBuilder
.speak('To hear a joke, ask <NAME> for a joke.')
.getResponse();
},
};
const CancelAndStopIntentHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest'
&& (request.intent.name === 'AMAZON.CancelIntent'
|| request.intent.name === 'AMAZON.StopIntent'
|| request.intent.name === 'AMAZON.NoIntent');
},
handle(handlerInput) {
return handlerInput.responseBuilder.getResponse();
}
};
const SessionEndedRequestHandler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'SessionEndedRequest';
},
handle(handlerInput) {
console.log(`Session ended with reason: ${handlerInput.requestEnvelope.request.reason}`);
return handlerInput.responseBuilder.getResponse();
},
};
const ErrorHandler = {
canHandle() {
return true;
},
handle(handlerInput, error) {
console.log(`Error handled: ${error.message}`);
console.log(`Error stack: ${error.stack}`);
const errorJoke = 'I applied to be a server years ago. To this day, I\'m still waiting.';
return handlerInput.responseBuilder
.speak(errorJoke)
.reprompt(errorJoke)
.getResponse();
},
};
const skillBuilder = Alexa.SkillBuilders.custom();
exports.handler = skillBuilder
.addRequestHandlers(
CancelAndStopIntentHandler,
GetJokeHandler,
HelpHandler,
SessionEndedRequestHandler
)
.addErrorHandlers(ErrorHandler)
.lambda();<file_sep>/README.md
# reddit-DadJokes-Alexa
An Alexa skill for reading out reddit.com/r/dadjokes posts.
|
5d067710eeaa25792aa5a689e3b789f09dfd0f04
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
mattgd/reddit-DadJokes-Alexa
|
3474e082e9cd60575d3c4b8527c93e49a3961538
|
ccd4a117eaa64e1457f50093bbebaa0c9bb7f12b
|
refs/heads/master
|
<repo_name>Bithrop/cs325-game-prototypes<file_sep>/HW0/js/main.js
"use strict";
function make_main_game_state( game )
{
function preload() {
// Load an image and call it 'logo'.
game.load.image( 'Ghost2', 'assets/Ghost2.png' );
game.load.image('sky', 'assets/sky3.png');
game.load.image('luigi2', 'assets/luigi2.png');
}
var bouncy;
var luigi;
function create() {
//Adding a sky backround
var sky = this.add.image(0,1, 'sky');
// Create a sprite at the center of the screen using the 'logo' image.
bouncy = game.add.sprite( game.world.centerX, game.world.centerY, 'Ghost2' );
//add a luigi to later be killed
luigi = game.add.sprite(500,500,'luigi2');
luigi.scale.setTo(0.1,0.1);
// Anchor the sprite at its center, as opposed to its top-left corner.
// so it will be truly centered.
bouncy.anchor.setTo( 0.5, 0.5 );
// Turn on the arcade physics engine for this sprite.
game.physics.enable( bouncy, Phaser.Physics.ARCADE );
// Make it bounce off of the world bounds.
bouncy.body.collideWorldBounds = true;
bouncy.scale.setTo(0.05,0.05);
// Add some text using a CSS style.
// Center it in X, and position its top 15 pixels from the top of the world.
var style = { font: "25px Verdana", fill: "#9999ff", align: "center" };
var text = game.add.text( game.world.centerX, 15, "Kill all Luigis.", style );
text.anchor.setTo( 0.5, 0.0 );
}
function update() {
// Accelerate the 'logo' sprite towards the cursor,
// accelerating at 500 pixels/second and moving no faster than 500 pixels/second
// in X or Y.
// This function returns the rotation angle that makes it visually match its
// new trajectory.
bouncy.rotation = game.physics.arcade.accelerateToPointer( bouncy, game.input.activePointer, 100, 100, 400 );
//update for overlap
game.physics.arcade.overlap(bouncy, luigi, killLuigi(luigi), null, this);
}
return { "preload": preload, "create": create, "update": update };
}
function killLuigi(luigi)
{
luigi.scale.setTo(1,1);
//var text = game.add.text(game.world.centerX , 20 , "You did it!", style);
//luigi.kill;
}
window.onload = function() {
// You might want to start with a template that uses GameStates:
// https://github.com/photonstorm/phaser/tree/v2.6.2/resources/Project%20Templates/Basic
// You can copy-and-paste the code from any of the examples at http://examples.phaser.io here.
// You will need to change the fourth parameter to "new Phaser.Game()" from
// 'phaser-example' to 'game', which is the id of the HTML element where we
// want the game to go.
// The assets (and code) can be found at: https://github.com/photonstorm/phaser/tree/master/examples/assets
// You will need to change the paths you pass to "game.load.image()" or any other
// loading functions to reflect where you are putting the assets.
// All loading functions will typically all be found inside "preload()".
var game = new Phaser.Game( 800, 600, Phaser.AUTO, 'game' );
game.state.add( "main", make_main_game_state( game ) );
game.state.start( "main" );
};
<file_sep>/HW4/js/main.js
"use strict";
function make_main_game_state( game )
{
function preload() {
// Load an image and call it 'logo'.
game.load.image( 'logo', 'assets/phaser.png' );
game.load.spritesheet('chicken', 'assets/chicken.png', 32, 32);
game.load.image( 'egg', 'assets/egg.png' );
//game.load.audio('cock', 'assets/Cockadoodledoo-sound.mp3');
game.load.image('farm', 'assets/farm.png');
game.load.spritesheet('farmer', 'assets/oldman_walk_sheet.png', 64, 64);
game.load.image('bullet', 'assets/new_bullet.png');
game.load.image('crow', 'assets/raven-black0001.png');
game.load.image('peas1', 'assets/peas3.png' );
}
var bouncy;
var cursors;
var score = 0;
var speed = 5;
var noise;
var farm;
var farmer;
var crow;
var crows;
//for shooting stuff
var bullets;
var fireRate = 100;
var nextFire = 0;
var texts;
var peas;
var wave = 1;
var waveText;
var style;
var crowSpeed = 300;
function create() {
// Create a sprite at the center of the screen using the 'logo' image.
//noise = game.add.audio('cock');
farm = game.add.sprite(game.world.centerX, game.world.centerY, 'farm');
farm.anchor.setTo( 0.5, 0.5 );
//noise.addMarker('cock', 0, 5.0);
bouncy = game.add.sprite( game.world.centerX, game.world.centerY, 'farmer' );
peas = game.add.sprite( game.world.centerX, 500, 'peas1' );
peas.anchor.setTo(0.5,0.5);
peas.scale.setTo(0.05,0.05);
game.physics.enable(peas, Phaser.Physics.ARCADE);
// Anchor the sprite at its center, as opposed to its top-left corner.
// so it will be truly centered.
bouncy.anchor.setTo( 0.5, 0.5 );
bouncy.enableBody = true;
//used for reseting eggs, may make more.
//for testing
// Turn on the arcade physics engine for this sprite.
game.physics.enable( bouncy, Phaser.Physics.ARCADE);
// Make it bounce off of the world bounds.
bouncy.body.collideWorldBounds = true;
bouncy.angle = 45;
// Add some text using a CSS style.
// Center it in X, and position its top 15 pixels from the top of the world.
style = { font: "25px Verdana", fill: "#9912rq", align: "center" };
cursors = game.input.keyboard.createCursorKeys();
//shooting stuff for create
bullets = game.add.group();
bullets.enableBody = true;
bullets.physicsBodyType = Phaser.Physics.ARCADE;
bullets.createMultiple(50, 'bullet');
bullets.setAll('checkWorldBounds', true);
bullets.setAll('outOfBoundsKill', true);
//crow = game.add.sprite( 500, 500, 'crow' );
//crow.scale.setTo(0.1,0.1);
//game.physics.enable(crow, Phaser.Physics.ARCADE);
//game.physics.arcade.moveToXY(crow,0,0,400);
crows = game.add.group();
createCrows();
//var style = { font: "25px Verdana", fill: "#9999ff", align: "center" };
texts = game.add.text( game.world.centerX, 15, "Score: " + score, style );
texts.anchor.setTo( 0.5, 0.0 );
waveText = game.add.text( 60, 15, "Wave " + wave, style );
waveText.anchor.setTo( 0.5, 0.0 );
}
function fire() {
if (game.time.now > nextFire && bullets.countDead() > 0)
{
nextFire = game.time.now + fireRate;
var bullet = bullets.getFirstDead();
bullet.reset(bouncy.x - 8, bouncy.y - 8);
bullet.scale.setTo(0.75,0.75);
game.physics.arcade.moveToPointer(bullet, 300);
}
}
function createCrows()
{
for(var i = 0; i < wave; i++)
{
var crow = crows.create(i * 100, 100, 'crow');
crow.scale.setTo(0.1,0.1);
game.physics.enable(crow, Phaser.Physics.ARCADE);
game.physics.arcade.moveToXY(crow,game.world.centerX,500,crowSpeed);
}
}
function collisionHandler(bullet, crow)
{
bullet.kill();
crow.kill();
score = score + 10;
texts.setText("Score: " + score);
if (crows.countLiving() == 0)
{
crowSpeed += 10;
wave++;
waveText.setText("Wave " + wave);
createCrows();
}
}
function GameOver (peas, crow)
{
crows.removeAll();
peas.kill()
var overText = game.add.text( game.world.centerX, game.world.centerY, "Game Over: \n The crows eat your peas!", style );
overText.anchor.setTo( 0.5, 0.0 );
}
function update() {
//bouncy.body.setZeroVelocity;
bouncy.rotation = game.physics.arcade.angleToPointer(bouncy);
//if statements for checking if it should switch to be going down, up, left or right
if(cursors.left.isDown)
{
bouncy.x -= speed
console.log("help");
//bouncy.body.moveLeft(400);
}
if(cursors.right.isDown)
{
bouncy.x += speed;
console.log("help");
//bouncy.body.moveLeft(400);
}
if(cursors.up.isDown)
{
bouncy.y -= speed;
console.log("help2");
//bouncy.body.moveLeft(400);
}
if(cursors.down.isDown)
{
bouncy.y += speed;
console.log("help2");
//bouncy.body.moveLeft(400);
}
//if statements that actually move the player
if (game.input.activePointer.isDown)
{
fire();
}
//testing for kill
game.physics.arcade.overlap(bullets, crows, collisionHandler, null, this);
game.physics.arcade.overlap(peas, crows, GameOver, null, this);
}
return { "preload": preload, "create": create, "update": update };
}
window.onload = function() {
// You might want to start with a template that uses GameStates:
// https://github.com/photonstorm/phaser/tree/v2.6.2/resources/Project%20Templates/Basic
// You can copy-and-paste the code from any of the examples at http://examples.phaser.io here.
// You will need to change the fourth parameter to "new Phaser.Game()" from
// 'phaser-example' to 'game', which is the id of the HTML element where we
// want the game to go.
// The assets (and code) can be found at: https://github.com/photonstorm/phaser/tree/master/examples/assets
// You will need to change the paths you pass to "game.load.image()" or any other
// loading functions to reflect where you are putting the assets.
// All loading functions will typically all be found inside "preload()".
var game = new Phaser.Game( 800, 600, Phaser.AUTO, 'game' );
game.state.add( "main", make_main_game_state( game ) );
game.state.start( "main" );
};
|
d6682124e0959b90ad77ae2aef20732b81521e6a
|
[
"JavaScript"
] | 2
|
JavaScript
|
Bithrop/cs325-game-prototypes
|
f4432fb96891d24875979bbb7ee5302c0fddbf29
|
843146f592cb88323a7d8b6558c9b34cdc094c7b
|
refs/heads/master
|
<repo_name>alexpwls/dinosaur-project<file_sep>/README.md
# Project: Dinosaurs ![alt text][logo]
[logo]: https://alexpwls.github.io/personal-blog-website/images/favicon/favicon-16x16.png "Purple dot"
Demo link: [https://alexpwls.github.io/dinosaur-project/index.html](https://alexpwls.github.io/dinosaur-project/index.html "Project: Dinosaurs demo link")
---
## Description:
Project one from the Udacity Intermediate JavaScript nanodegree. Create a dinosaur comparison infographic.
## How to install?
Nothing fancy required to install this site, only a browser to render the HTML and CSS content.<file_sep>/app.js
const dinos = {
"Dinos": [{
"species": "Triceratops",
"weight": 13000,
"height": 114,
"diet": "Herbavor",
"where": "North America",
"when": "Late Cretaceous",
"fact0": "First discovered in 1889 by <NAME>",
"img": "triceratops.png"
}, {
"species": "Tyrannosaurus Rex",
"weight": 11905,
"height": 144,
"diet": "Carnivor",
"where": "North America",
"when": "Late Cretaceous",
"fact0": "The largest known skull measures in at 5 feet long.",
"img": "tyrannosaurus-rex.png"
}, {
"species": "Anklyosaurus",
"weight": 10500,
"height": 55,
"diet": "Herbavor",
"where": "North America",
"when": "Late Cretaceous",
"fact0": "Anklyosaurus survived for approximately 135 million years.",
"img": "anklyosaurus.png"
}, {
"species": "Brachiosaurus",
"weight": 70000,
"height": "372",
"diet": "Herbavor",
"where": "North America",
"when": "Late Jurasic",
"fact0": "An asteroid was named 9954 Brachiosaurus in 1991.",
"img": "brachiosaurus.png"
}, {
"species": "Stegosaurus",
"weight": 11600,
"height": 79,
"diet": "Herbavor",
"where": "North America, Europe, Asia",
"when": "Late Jurasic to Early Cretaceous",
"fact0": "The Stegosaurus had between 17 and 22 seperate places and flat spines.",
"img": "stegosaurus.png"
}, {
"species": "Elasmosaurus",
"weight": 16000,
"height": 59,
"diet": "Carnivor",
"where": "North America",
"when": "Late Cretaceous",
"fact0": "Elasmosaurus was a marine reptile first discovered in Kansas.",
"img": "elasmosaurus.png"
}, {
"species": "Pteranodon",
"weight": 44,
"height": 20,
"diet": "Carnivor",
"where": "North America",
"when": "Late Cretaceous",
"fact0": "Actually a flying reptile, the Pteranodon is not a dinosaur.",
"img": "pteranodon.png"
}, {
"species": "Pigeon",
"weight": 0.5,
"height": 9,
"diet": "Herbavor",
"where": "World Wide",
"when": "Holocene",
"fact0": "All birds are living dinosaurs.",
"img": "pigeon.png"
}]
}
/**
* @description Represents a dinosaur
* @constructor
* @param {string} species - The species of the dino
* @param {string} weight - The weight of the dino
* @param {string} height - The height of the dino
* @param {string} diet - The diet oof the dino
* @param {string} where - Where the dino lived
* @param {string} when - When the dino lived
* @param {string} fact0 - Fact about the dino
* @param {string} img - Image from the dino
*/
function Dino(species, weight, height, diet, where, when, fact0, img) {
this.species = species;
this.weight = weight;
this.height = height;
this.diet = diet;
this.where = where;
this.when = when;
this.fact0 = fact0;
this.img = img;
}
/**
* @description Create Dino Compare Method 1: check if weight is different
*/
function checkWeight(results, humanObject) {
for (result of results) {
if (result.weight > humanObject.weight) {
result.fact1 = result.species + " is heavier than " + humanObject.species
} else {
result.fact1 = result.species + " is not heavier than " + humanObject.species
}
}
}
/**
* @description Create Dino Compare Method 2: check if height is different
*/
function checkHeight(results, humanObject) {
for (result of results) {
let humanInches = Number(humanObject.feet) * 12 + Number(humanObject.inches)
if (result.height > humanInches) {
result.fact2 = result.species + " is bigger than " + humanObject.species
} else {
result.fact2 = result.species + " is not bigger than " + humanObject.species
}
}
}
/**
* @description Create Dino Compare Method 3: check if Diet is similar
*/
function checkDiet(results, humanObject) {
for (result of results) {
if (result.diet == humanObject.diet) {
result.fact3 = result.species + " shares the same diet with " + humanObject.species
} else {
result.fact3 = result.species + " does not share the same diet with " + humanObject.species
}
}
}
/**
* @description Add data to tiles and return HTML
*/
function gridItemDinoHTML(result, randomNumber) {
let fact = ""
if (result.species == "Pigeon") {
fact = "All birds are living dinosaurs."
} else if (randomNumber == 0) {
fact = result.fact0
} else if (randomNumber == 1) {
fact = result.fact1
} else if (randomNumber == 2) {
fact = result.fact2
} else {
fact = result.fact3
}
let html = `<div class="grid-item">
<h3>${result.species}</h3>
<p>${fact}</p>
<img src="images/${result.img}">
</div>`;
return html;
}
function gridItemHumanHTML(result) {
let html = `<div class="grid-item">
<h3>${result.species}</h3>
<img src="images/${result.img}">
</div>`;
return html;
}
/**
* @description Generate Tiles for each Dino and Human in results array and inserts in DOM
*/
function setupTiles(results) {
const grid = document.getElementById("grid");
let count = 0;
for (result of results) {
if (count == 4) {
grid.insertAdjacentHTML("beforeend", gridItemHumanHTML(result));
count = count + 1;
} else {
let randomNumber = Math.floor(Math.random() * 4);
grid.insertAdjacentHTML("beforeend", gridItemDinoHTML(result, randomNumber));
count = count + 1;
}
}
}
/**
* @description Remove form from screen
*/
function removeForm() {
const form = document.getElementById("dino-compare");
form.style.display = "none";
}
/**
* On button click, prepare and display infographic
*/
document.getElementById("btn").addEventListener("click", function() {
/**
* @description Use IIFE to get human data from form
*/
let humanObject = {};
(function(human) {
human.img = "human.png"
human.species = document.getElementById("name").value;
human.feet = document.getElementById("feet").value;
human.inches = document.getElementById("inches").value;
human.weight = document.getElementById("weight").value;
human.diet = document.getElementById("diet").value;
})(humanObject);
removeForm();
/**
* @description Gather all dino and human data in single array
*/
let results = dinos.Dinos.map(dino => new Dino(dino.species, dino.weight, dino.height, dino.diet, dino.where, dino.when, dino.fact0, dino.img));
results.splice(4, 0, humanObject);
/**
* @description Checks for comparisons between human and dino and creates additional facts about the dinos
*/
checkWeight(results, humanObject);
checkHeight(results, humanObject);
checkDiet(results, humanObject);
setupTiles(results);
});
|
58531d454cb6246172a5ac5e70ca3d49d2e0db86
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
alexpwls/dinosaur-project
|
1f4066171d21cb136383c59b4dd14f63bcc6f54a
|
c5c2975be98190bcb9fd88ce0135e74de3f72ddd
|
refs/heads/master
|
<repo_name>oss05/Internship<file_sep>/Internship/dboxjs/core-master/lib/bk/bars/utils/averageLines.js
/*eslint-disable*/
// TODO: Update example
function AverageLines(options) {
var vm = this;
vm._config = options.config;
vm._chart = options.chart;
vm._data = options.data;
vm._scales = options.scales;
}
AverageLines.prototype.draw = function (){
var vm = this;
//Remove all
vm._chart._svg.selectAll("line.avg-line").remove();
if(vm._config.plotOptions && vm._config.plotOptions.bars && Array.isArray(vm._config.plotOptions.bars.averageLines) && vm._config.plotOptions.bars.averageLines.length >0 ){
//draw line
vm._chart._svg.selectAll("line.avg-line")
.data(vm._config.plotOptions.bars.averageLines)
.enter().append("line")
.attr("class", ".avg-line")
.attr('x1', 0)
.attr('x2', function(d){
return vm._chart._width;
})
.attr('y1', function(d){
return vm._scales.y(d.data.raw);
})
.attr('y2', function(d){
return vm._scales.y(d.data.raw);
})
.attr('stroke', function(d){ return d.color })
.attr("stroke-width", function(d){
var strokeWidth = '3px';
if(d.strokeWidth) strokeWidth = d.strokeWidth;
return strokeWidth;
})
.style('display', function(d){
if(d.enabled) return 'block';
else return 'none';
})
//Add text
vm._chart._svg.selectAll("text.avg-line")
.data(vm._config.plotOptions.bars.averageLines)
.enter().append("text")
.attr("class", "avg-line")
.attr("x", vm._chart._width)
.attr("y", function(d){
return vm._scales.y(d.data.raw);
})
.style("text-anchor", "start")
.style("fill", function(d){ return d.color } )
.style("font-size", function(d){
var size = '14px';
if(d.fontSize) size = d.fontSize;
return size;
})
.text(function(d){
return d.data.raw.toFixed(1);
})
.style('display', function(d){
if(d.enabled) return 'block';
else return 'none';
});
/* @TODO ADD LEGEND FOR AVERAGE LINES
vm._chart._svg.selectAll("rect.avg-line")
.append('rect')
.attr("class", "avg-line")
.attr("x", function(d) { return vm._scales.x(0); })
.attr("width", vm._chart._width)
.attr("y", function(d) { return 0 })
.attr("height", function(d) { return vm._chart._height - vm._scales.y(d.y); });*/
}
}
AverageLines.prototype.drawLegend = function(){
if(vm._config.plotOptions && vm._config.plotOptions.bars
&& vm._config.plotOptions.bars.averageLines && Array.isArray(vm._config.plotOptions.bars.averageLines)
&& vm._config.plotOptions.bars.averageLines.length >0 ){
var avgLinesLegend = d3.select(vm._config.bindTo).append("div")
.attr("class", "container-average-lines")
.append('div')
.attr("class", "legend-average-lines")
.style('padding-left','15px')
.style('padding-right','15px');
var legendContent = avgLinesLegend.selectAll('.legend-content')
.data(vm._config.plotOptions.bars.averageLines)
.enter().append('div')
.attr("class","legend-content")
.style("float","left")
.style('margin-right','5px');
legendContent.append("div")
.style('width','10px')
.style('height', '10px')
.style('float', 'left')
.style('margin-right','3px')
.style('margin-bottom','3px')
.style("background", function(d){ console.log(d); return d.color; })
.style('color','white')
.style('font-weight','bold')
.style('cursor','pointer')
.text(function(d){
return d.enabled ? '✓' : '';
})
.on('click',function(d){
d.enabled = d.enabled ? false : true;
d3.select(this).text(d.enabled ? '✓' : '');
});
legendContent.append("span")
.text(function(d){ return d.title; });
}
}
export default function averageLines(options) {
return new AverageLines(arguments.length ? options : null);
}
/*eslint-enable*/<file_sep>/Internship/dboxjs/core-master/lib/bk/bars/lineAndCircles.js
/*eslint-disable*/
function LineAndCircles(options) {
var vm = this;
vm._config = options.config;
vm._chart = options.chart;
vm._data = options.data;
vm._scales = options.scales;
}
LineAndCircles.prototype.draw = function (){
var vm = this;
vm._chart._svg.selectAll(".dot")
.data(vm._data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 5)
.attr("cx", function(d) { return vm._scales.x(d.x)+vm._scales.x.rangeBand()/2; })
.attr("cy", function(d) { return vm._scales.y(d.y); })
.style("fill", function(d) { return d.color; })
.style("stroke", function(d) { return d.color; })
.on('mouseover', function(d,i){
if(vm._config.data.mouseover){
vm._config.data.mouseover.call(vm, d,i)
}
vm._chart._tip.show(d, d3.select(this).node())
})
.on('mouseout',function(d,i){
if(vm._config.data.mouseout){
vm._config.data.mouseout.call(vm, d,i)
}
vm._chart._tip.hide(d, d3.select(this).node())
})
vm._chart._svg.selectAll('line.stem')
.data(vm._data)
.enter()
.append('line')
.classed('stem', true)
.attr('x1', function(d){
return vm._scales.x(d.x)+vm._scales.x.rangeBand()/2;
})
.attr('x2', function(d){
return vm._scales.x(d.x)+vm._scales.x.rangeBand()/2;
})
.attr('y1', function(d){
return vm._scales.y(d.y);
})
.attr('y2', vm._chart._height)
.attr('stroke', function(d){
return d.color;
})
/*vm._chart._svg.selectAll('circle')
.data(vm._data)
.enter()
.append('circle')
.attr('cx', function(d) {
return vm._scales.x(d.x);
})
.attr('cy', function(d) {
return vm._scales.y(d.y);
})
.attr('r', 6)
.attr('fill', function(d){
return d.color;
})
.style('cursor', 'pointer')*/
}
LineAndCircles.prototype.select = function(selector){
var vm = this;
var select = false;
vm._chart._svg.selectAll('.dot')
.each(function(d){
if(d.x === selector || d.y === selector){
select = d3.select(this);
}
})
return select;
}
export default function lineAndCircles(options) {
return new LineAndCircles(arguments.length ? options : null);
}
/*eslint-enable*/<file_sep>/Internship/dboxjs/core-master/lib/helper.js
import * as d3 from 'd3';
var d3Tip = require('d3-tip');
export default function () {
var vm = this; // Hard binded to chart
var Helper = {
chart: {
config: vm._config,
width: vm._width,
height: vm._height,
style: vm._addStyle,
fullSvg: function () {
return vm._fullSvg;
},
svg: function () {
return vm._svg;
},
},
utils: {
d3: {}
}
};
Helper.utils.d3.tip = d3Tip;
Helper.utils.generateScale = function (data, config) {
var scale = {};
var domains;
if (!config.range) {
throw 'Range is not defined';
}
// Used in bars.js when we want to create a groupBy or stackBy bar chart
if (config.groupBy && config.groupBy == 'parent') {
// Axis of type band
domains = data.map(function (d) {
return d[config.column];
});
} else if (config.stackBy && config.stackBy == 'parent') {
domains = data[0].map(function (d) {
return d.data[config.column];
});
} else if (config.groupBy == 'children') {
// GroupBy Columns
domains = config.column;
} else if (config.groupBy == 'data') {
// Considering the highest value on all the columns for each groupBy column
domains = [0, d3.max(data, function (d) {
return d3.max(config.column, function (column) {
return d[column];
});
})];
} else if (config.stackBy == 'data') {
// Using a d3.stack()
domains = [0, d3.max(data, function (serie) {
return d3.max(serie, function (d) {
return d[1];
});
})];
} else if (config.groupBy == undefined && config.type == 'band') {
// In case the axis is of type band and there is no groupby
domains = data.map(function (d) {
return d[config.column];
});
} else if (config.type === 'linear') {
// Axis of type numeric
if (config.minZero) {
domains = [0, d3.max(data, function (d) {
return +d[config.column];
})];
} else {
domains = d3.extent(data, function (d) {
return +d[config.column];
});
}
} else {
// Axis of type band
domains = data.map(function (d) {
return d[config.column];
});
}
if (config.domains && Array.isArray(config.domains)) {
domains = config.domains;
}
if (config.type) {
switch (config.type) {
case 'linear':
scale = d3.scaleLinear()
.rangeRound(config.range)
.domain(domains)
.nice();
break;
case 'time':
scale = d3.scaleTime()
.range(config.range);
// .domain(domains);
break;
case 'ordinal':
scale = d3.scaleBand()
.rangeRound(config.range)
.padding(0.1)
.domain(domains);
break;
case 'band':
scale = d3.scaleBand()
.rangeRound(config.range)
.domain(domains)
.padding(0.1);
break;
case 'quantile':
scale = d3.scaleBand()
.rangeRound(config.range)
.padding(0.1)
.domain(data.map(function (d) {
return d[config.column];
}));
if (!config.bins) {
config.bins = 10;
}
scale = d3.scaleQuantile()
.range(d3.range(config.bins));
break;
default:
scale = d3.scaleLinear()
.rangeRound(config.range)
.domain(domains)
.nice();
break;
}
} else {
scale = d3.scaleLinear()
.rangeRound(config.range)
.domain(domains)
.nice();
}
return scale;
};
Helper.utils.format = function (d, decimals) {
var value = '';
if (vm._config.formatPreffix) {
value += vm._config.formatPreffix;
}
if (decimals) {
if (d === 0 || d % 1 === 0) {
value += d3.format(',.0f')(d);
} else {
value += d3.format(',.' + decimals + 'f')(d);
}
} else {
if (d === 0 || d % 1 == 0) {
value += d3.format(',.0f')(d);
} else if (d < 1 && d > 0) {
if (d < 0.01) {
value += d3.format('>,.2')(d);
} else {
value += d3.format(',.2f')(d);
}
} else {
value += d3.format(',.1f')(d);
}
}
if (vm._config.formatSuffix) {
value += vm._config.formatSuffix;
}
return value;
};
// wrap function used in x axis labels
Helper.utils.wrap = function (text, width, tooltip) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr('y'),
dy = parseFloat(text.attr('dy')) || 0,
tspan = text.text(null).append('tspan').attr('x', 0).attr('y', y).attr('dy', dy + 'em');
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(' '));
line = [word];
tspan = text.append('tspan').attr('x', 0).attr('y', y).attr('dy', ++lineNumber * lineHeight + dy + 'em').text(word);
if (lineNumber > 0) {
if (words.length > 0 && tspan.node().getComputedTextLength() > width) {
if (tooltip) {
text
.on('mouseover', tooltip.show)
.on('mouseout', tooltip.hide);
}
let i = 1;
while (tspan.node().getComputedTextLength() > width) {
tspan.text(function () {
return tspan.text().slice(0, -i) + '...';
});
++i;
}
}
words = [];
} else {
let i = 1;
while (tspan.node().getComputedTextLength() > width) {
tspan.text(function () {
return tspan.text().slice(0, -i) + '...';
});
++i;
}
}
}
}
});
};
Helper.utils.sortAscending = function (a, b) {
if (!Number.isNaN(+a) && !Number.isNaN(+b)) {
// If both values are numbers use numeric value
return Number(a) - Number(b);
} else if (!Number.isNaN(+a) && Number.isNaN(+b)) {
return -1;
} else if (Number.isNaN(+a) && !Number.isNaN(+b)) {
return 1;
} else if (a <= b) {
return -1;
} else {
return 1;
}
};
Helper.utils.sortDescending = function (a, b) {
if (!Number.isNaN(+b) && !Number.isNaN(+a)) {
// If both values are numbers use numeric value
return Number(b) - Number(a);
} else if (!Number.isNaN(+b) && Number.isNaN(+a)) {
return -1;
} else if (Number.isNaN(+b) && !Number.isNaN(+a)) {
return 1;
} else if (b <= a) {
return -1;
} else {
return 1;
}
};
return Helper;
}
<file_sep>/Internship/dboxjs/core-master/lib/bk/timeline/timeline.js
/* Simple timeline example
* Single and multiline timelines
*/
import * as d3 from 'd3';
import * as textures from 'textures';
export default function(config) {
var parseDate = d3.timeParse('%Y-%m-%d');
function Timeline(config){
var vm = this;
vm._config = config ? config : {};
vm._config.area = false;
vm._data = [];
vm._scales ={};
vm._axes = {};
vm._line = d3.line()
.curve(d3.curveMonotoneX)
.x(function(d) { return vm._scales.x(d.x); })
.y(function(d) { return vm._scales.y(d.y); });
vm._area = d3.area()
.curve(d3.curveMonotoneX)
.x(function(d) {
if (d.alreadyScaled && d.alreadyScaled === true){
return d.x;
}else{
return vm._scales.x(d.x);
}
})
.y1(function(d) {
if (d.alreadyScaled && d.alreadyScaled === true){
return d.y;
}else{
return vm._scales.y(d.y);
}
});
}
//-------------------------------
//User config functions
Timeline.prototype.x = function(col){
var vm = this;
vm._config.x = col;
return vm;
}
Timeline.prototype.y = function(col){
var vm = this;
vm._config.y = col;
return vm;
}
Timeline.prototype.series = function(arr){
var vm = this;
vm._config.series = arr;
return vm;
}
Timeline.prototype.colors = function(arr){
var vm = this;
vm._config.colors = arr;
return vm;
}
Timeline.prototype.timeParse = function(timeParse){
var vm = this;
parseDate= d3.timeParse(timeParse);
return vm;
}
Timeline.prototype.area = function(area){
var vm = this;
vm._config.area = area;
return vm;
}
Timeline.prototype.color = function(col){
var vm = this;
vm._config.color = col;
return vm;
}
Timeline.prototype.end = function(){
var vm = this;
return vm._chart;
}
//-------------------------------
//Triggered by the chart.js;
Timeline.prototype.chart = function(chart){
var vm = this;
vm._chart = chart;
return vm;
}
Timeline.prototype.data = function(data){
var vm = this;
vm._data = data.map(function(d){
d.x = parseDate(d[vm._config.x]);
delete(d[vm._config.x]);
return d;
});
vm._lines = vm._config.y ? vm._config.y : vm._config.series;
vm._lines = vm._lines.map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {x: d.x, y: +d[name]};
})
};
});
return vm;
}
Timeline.prototype.scales = function(s){
var vm = this;
vm._scales = s;
return vm;
}
Timeline.prototype.axes = function(a){
var vm = this;
vm._axes = a;
return vm;
}
Timeline.prototype.domains = function(){
var vm = this;
vm._xMinMax = d3.extent(vm._data, function(d) { return d.x; });
vm._yMinMax = [
d3.min(vm._lines, function(c) { return d3.min(c.values, function(v) { return v.y; }); }),
d3.max(vm._lines, function(c) { return d3.max(c.values, function(v) { return v.y; }); })
];
vm._scales.x.domain(vm._xMinMax)
vm._scales.y.domain(vm._yMinMax)
//console.log(vm._scales.x.domain(), vm._chart._scales.x.domain())
vm._chart._scales = vm._scales;
return vm;
};
Timeline.prototype.draw = function(){
var vm = this;
var lines = vm._chart._svg.selectAll(".lines")
.data(vm._lines)
.enter().append("g")
.attr("class", "lines");
var path = vm._chart._svg.selectAll(".lines").append("path")
.attr("class", "line")
.attr("d", function(d) {
return vm._line(d.values);
})
.style("stroke", function(d, i ){
return vm._config.colors[i];
})
.style("fill", 'none');
//var t = textures.lines().thicker();
//vm._chart._svg.call(t);
if(vm._config.area === true){
vm._area.y0(vm._scales.y(vm._yMinMax[0]));
var areas = vm._chart._svg.selectAll(".areas")
.data(vm._lines)
.enter().append("g")
.attr("class", "areas");
var pathArea = vm._chart._svg.selectAll(".areas").append("path")
.attr("class", "area")
.attr("d", function(d) {
return vm._area(d.values);
})
.attr("fill", function(d, i ){
return vm._config.colors[i];
});
}
/*path.each(function(d) { d.totalLength = this.getTotalLength(); })
.attr("stroke-dasharray", function(d) { return d.totalLength + " " + d.totalLength; })
.attr("stroke-dashoffset", function(d) { return d.totalLength; })
.transition()
.duration(5000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);*/
return vm;
}
return new Timeline(config);
}
/*import chart from './chart.js';
function Timeline(config) {
var vm = this;
vm._config = config;
vm._chart;
vm._scales = {};
vm._axes = {};
}
Timeline.prototype = timeline.prototype = {
generate:function(){
var vm = this, q;
vm.draw();
vm.setScales();
vm.setAxes();
q = vm._chart.loadData();
q.await(function(error,data){
if (error) {
//console.log(error)
throw error;
return false;
}
vm.setData(data);
vm.setDomains();
vm.drawAxes();
console.log("generate", vm._data);
vm.drawData();
})
},
draw : function(){
var vm = this
vm._chart = chart(vm._config);
},
setScales: function(){
var vm = this;
vm._scales.x = d3.scaleTime()
.range([0, vm._chart._width]);
vm._scales.y = d3.scaleLinear()
.range([vm._chart._height, 0]);
vm._scales.color = d3.scaleOrdinal(d3.schemeCategory20c);
},
setAxes : function(){
var vm = this;
vm._axes.x = d3.svg.axis()
.scale(vm._scales.x)
.orient("bottom");
vm._axes.y = d3.svg.axis()
.scale(vm._scales.y)
.orient("left");
if(vm._config.yAxis && vm._config.yAxis.ticks
&& vm._config.yAxis.ticks.enabled === true && vm._config.yAxis.ticks.style ){
switch(vm._config.yAxis.ticks.style){
case 'straightLine':
vm._axes.y
.tickSize(-vm._chart._width,0);
break;
}
}
if( vm._config.yAxis.ticks.format){
console.log('Set tick format');
vm._axes.y.tickFormat(vm._config.yAxis.ticks.format);
}
},
setData:function(data){
var vm = this;
var keys = d3.keys(data[0]).filter(function(key) { return key !== "date"; });
var series = keys.map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {x: d.date, y: +d[name]};
})
};
});
vm._data = series;
},
setDomains:function(){
var vm = this;
vm._scales.color.domain(vm._data.map(function(serie){
return serie.name;
}));
vm._scales.x.domain([
d3.min(vm._data, function(c) { return d3.min(c.values, function(v) { return v.x; }); }),
d3.max(vm._data, function(c) { return d3.max(c.values, function(v) { return v.x; }); })
]);
vm._scales.y.domain([
d3.min(vm._data, function(c) { return d3.min(c.values, function(v) { return v.y; }); }),
d3.max(vm._data, function(c) { return d3.max(c.values, function(v) { return v.y; }); })
]);
},
drawAxes:function(){
var vm = this;
vm._chart._svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + vm._chart._height + ")")
.call(vm._axes.x)
.append("text")
.attr("class", "label")
.attr("x", vm._chart._width)
.attr("y", -6)
.style("text-anchor", "end")
.text("");
var yAxis = vm._chart._svg.append("g")
.attr("class", "y axis")
.call(vm._axes.y)
if(vm._config.yAxis && vm._config.yAxis.text){
yAxis.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("x", -vm._chart._height/2)
.attr("y", -vm._config.size.margin.left + 10)
.attr("dy", ".71em")
.style("text-anchor", "middle")
.style("font-size","14px")
.text(vm._config.yAxis.text);
}
},
drawData : function(){
var vm = this;
var line = d3.svg.line()
.interpolate(vm._config.data.interpolation)
.defined(function(d) { return d; })
.x(function(d) { return vm._scales.x(d.x); })
.y(function(d) { return vm._scales.y(d.y); });
var series = vm._chart._svg.selectAll(".series")
.data(vm._data)
.enter().append("g")
.attr("class", "series")
series.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke-dasharray",function(d){ if(d.name == "Nacional"){
return ("10,5");
}})
.style("stroke", function(d) {
if(d.color){ return d.color; }
else { return vm._scales.color(d.key); }
}) //return vm._scales.color(d.name); })
.style("stroke-width", 3);
series.selectAll('.dot')
.data(function(d){return d.values})
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3)
.attr("cx", function(d) { return vm._scales.x(d.x); })
.attr("cy", function(d) { return vm._scales.y(d.y); })
.style("fill", function(d) {
if(d.color){ return d.color; }
else { return vm._scales.color(d.key); }
})//return vm._scales.color(d.name); })
.style("stroke", function(d) {
if(d.color){ return d.color; }
else { return vm._scales.color(d.key); }
}) // return vm._scales.color(d.name); })
.on('mouseover', function(d,i){
if(vm._config.data.mouseover){
vm._config.data.mouseover.call(vm, d,i)
}
vm._chart._tip.show(d, d3.select(this).node())
})
.on('mouseout',function(d,i){
if(vm._config.data.mouseout){
vm._config.data.mouseout.call(vm, d,i)
}
vm._chart._tip.hide(d, d3.select(this).node())
});
//series.selectAll('.dot-inside')
// .data(function(d){return d.values})
//.enter().append("circle")
// .attr("class", "dot-inside")
// .attr("r", 4)
// .attr("cx", function(d) { return vm._scales.x(d.x); })
// .attr("cy", function(d) { return vm._scales.y(d.y); })
// .style("fill", 'black')//return vm._scales.color(d.name); })
// .style("stroke", function(d) { return d.color;}) // return vm._scales.color(d.name); })
// .on('mouseover', function(d,i){
// if(vm._config.data.mouseover){
// vm._config.data.mouseover.call(vm, d,i)
// }
// vm._chart._tip.show(d, d3.select(this).node())
// })
// .on('mouseout',function(d,i){
// if(vm._config.data.mouseout){
// vm._config.data.mouseout.call(vm, d,i)
// }
// vm._chart._tip.hide(d, d3.select(this).node())
// });
//series.append("text")
// .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
// .attr("transform", function(d) { return "translate(" + vm._scales.x(d.value.x) + "," + vm._scales.y(d.value.y) + ")"; })
// .attr("x", 3)
// .attr("dy", ".35em")
// .text(function(d) { return d.name; });
}
}
export default function timeline(config) {
return new Timeline(arguments.length ? config : null);
}*/
<file_sep>/Internship/dboxjs/core-master/lib/bk/map/map.js
/*
* Simple Scatter chart
*/
import geoMexico from './geoMexico.js';
export default function(config) {
function Map(config) {
var vm = this;
vm._config = config ? config : {};
vm._data = [];
vm._scales = {};
vm._axes = {};
vm._tip = vm.utils.d3.tip().attr('class', 'd3-tip');
vm._centers = {
"Aguascalientes":"1006",
"Baja California":"2001",
"Baja California Sur":"3009",
"Campeche":"4009",
"Coahuila de Zaragoza":"5021",
"Colima":"6002",
"Chiapas":"7094",
"Chihuahua":"8004",
"Distrito Federal":"9009",
"Durango":"10028",
"Guanajuato":"11003",
"Guerrero":"12042",
"Hidalgo":"13037",
"Jalisco":"14093",
"México":"15121",
"<NAME>":"16079",
"Morelos":"17030",
"Nayarit":"18015",
"Nuevo León":"19013",
"Oaxaca":"20325",
"Puebla":"21170",
"Querétaro":"22015",
"Quintana Roo":"23002",
"San <NAME>":"24017",
"Sinaloa":"25006",
"Sonora":"26066",
"Tabasco":"27012",
"Tamaulipas":"28035",
"Tlaxcala":"29011",
"Veracruz de Ignacio de la Llave":"30192",
"Yucatán":"31097",
"Zacatecas":"32010"
};
vm._edo_zoom = {
"1":10,
"2":3,
"3":3,
"4":4,
"5":3,
"6":10,
"7":5,
"8":2,
"9":12,
"10":4,
"11":8,
"12":5,
"13":8,
"14":5,
"15":6,
"16":6,
"17":10,
"18":6,
"19":4,
"20":5,
"21":6,
"22":9,
"23":5,
"24":6,
"25":4,
"26":2,
"27":7,
"28":3,
"29":10,
"30":4,
"31":4,
"32":4
};
vm._formatWithZeroDecimals = d3.format(",.0f");
vm._formatWithOneDecimal = d3.format(",.1f");
vm._formatWithTwoDecimals = d3.format(",.2f");
vm._formatWithThreeDecimals = d3.format(",.3f");
vm._format = {};
vm._format.total = vm._formatWithZeroDecimals;
vm._format.percentage = function(d){return d3.format(",.1f")(d) + '%';} ;
vm._format.change = d3.format(",.1f");
vm._geo = null;
vm._geoMexico = null;
}
//-------------------------------
//User config functions
Map.prototype.z = function(col) {
var vm = this;
vm._config.z = col;
return vm;
}
Map.prototype.tip = function(tip){
var vm = this;
vm._config.tip = tip;
vm._tip.html(vm._config.tip);
return vm;
}
Map.prototype.onclick = function(onclick){
var vm = this;
vm._config.onclick = onclick;
return vm;
}
Map.prototype.end = function() {
var vm = this;
//@Todo Review
vm.setChartType();
return vm._chart;
}
//-------------------------------
//Triggered by the chart.js;
Map.prototype.chart = function(chart) {
var vm = this;
vm._chart = chart;
return vm;
}
Map.prototype.setChartType = function(){
var vm = this;
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geo){
switch(vm._config.plotOptions.map.geo){
case 'mexico':
vm._geo = geoMexico(vm._chart, vm._config);
break;
}
}
},
Map.prototype.data = function(data) {
var vm = this;
if(vm._config.data.filter){
data = data.filter(vm._config.data.filter);
}
vm._data = data;
vm._quantiles = vm._setQuantile(data);
vm._minMax = d3.extent(data, function(d) { return +d[vm._config.z]; })
vm._config.plotOptions.map.min = vm._minMax [0];
vm._config.plotOptions.map.max = vm._minMax [1];
vm._geo._config = vm._config;
vm._geo._data = data;
vm._geo._quantiles = vm._quantiles;
vm._geo._minMax = vm._minMax
vm._geo._getQuantileColor = vm._getQuantileColor;
return vm;
}
Map.prototype.scales = function(s) {
var vm = this;
vm._scales = s;
return vm;
}
Map.prototype.axes = function(a) {
var vm = this;
vm._axes = a;
return vm;
}
Map.prototype.domains = function() {
var vm = this;
return vm;
};
Map.prototype.draw = function(){
var vm = this;
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'states'){
vm._geo.drawStates();
}
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'municipalities'){
vm._geo.drawMunicipalities();
}
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'zones'){
vm._geo.drawZones();
}
//vm._drawLegend();
}
Map.prototype._setQuantile = function(data){
var vm = this;
var values = [];
var quantile = [];
if(vm._config.plotOptions.map.quantiles && vm._config.plotOptions.map.quantiles.predefinedQuantiles
&& vm._config.plotOptions.map.quantiles.predefinedQuantiles.length > 0){
return vm._config.plotOptions.map.quantiles.predefinedQuantiles;
}
data.forEach(function(d){
values.push(+d[vm._config.z]);
});
values.sort(d3.ascending);
//@TODO use quantile scale instead of manual calculations
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.quantiles && vm._config.plotOptions.map.quantiles.buckets){
if(vm._config.plotOptions.map.quantiles.ignoreZeros === true){
var aux = _.dropWhile(values, function(o) { return o <= 0 });
//aux.unshift(values[0]);
quantile.push(values[0]);
quantile.push(0);
for(var i = 1; i <= vm._config.plotOptions.map.quantiles.buckets - 1; i++ ){
quantile.push( d3.quantile(aux, i* 1/(vm._config.plotOptions.map.quantiles.buckets - 1) ) )
}
}else{
quantile.push( d3.quantile(values, 0) )
for(var i = 1; i <= vm._config.plotOptions.map.quantiles.buckets; i++ ){
quantile.push( d3.quantile(values, i* 1/vm._config.plotOptions.map.quantiles.buckets ) )
}
}
}else{
quantile = [ d3.quantile(values, 0), d3.quantile(values, 0.2), d3.quantile(values, 0.4), d3.quantile(values, 0.6), d3.quantile(values, 0.8), d3.quantile(values,1) ];
}
//@TODO - VALIDATE WHEN ZEROS NEED TO BE PUT ON QUANTILE 1 AND RECALCULATE NON ZERO VALUES INTO THE REST OF THE BUCKETS
if( vm._config.plotOptions.map.quantiles && vm._config.plotOptions.map.quantiles.buckets
&& vm._config.plotOptions.map.quantiles.buckets === 5){
if( quantile[1] === quantile[2] && quantile[2] === quantile[3] && quantile[3] === quantile[4] && quantile[4] === quantile[5]){
quantile = [ d3.quantile(values, 0), d3.quantile(values, 0.2) ];
}
}
return quantile;
}
Map.prototype._getQuantileColor = function(d){
var vm = this;
var total = parseFloat(d[vm._config.z]);
//@TODO use quantile scale instead of manual calculations
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.quantiles && vm._config.plotOptions.map.quantiles.colors){
if(vm._quantiles.length > 2){
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.min !== undefined && vm._config.plotOptions.map.max !== undefined){
if(total < vm._config.plotOptions.map.min || total > vm._config.plotOptions.map.max){
console.log('outOfRangeColor', total, vm._config.plotOptions.map.min ,vm._config.plotOptions.map.max)
return vm._config.plotOptions.map.quantiles.outOfRangeColor;
}
}else{
if(total < vm.minMax[0] || total > vm.minMax[1]){
console.log('outOfRangeColor', total, vm._config.plotOptions.map.min ,vm._config.plotOptions.map.max)
return vm._config.plotOptions.map.quantiles.outOfRangeColor;
}
}
if(total <= vm._quantiles[1]){
return vm._config.plotOptions.map.quantiles.colors[0];//"#f7c7c5";
}else if(total <= vm._quantiles[2]){
return vm._config.plotOptions.map.quantiles.colors[1];//"#e65158";
}else if(total <= vm._quantiles[3]){
return vm._config.plotOptions.map.quantiles.colors[2];//"#c20216";
}else if(total <= vm._quantiles[4]){
return vm._config.plotOptions.map.quantiles.colors[3];//"#750000";
}else if(total <= vm._quantiles[5]){
return vm._config.plotOptions.map.quantiles.colors[4];//"#480000";
}
}
}
if(vm._quantiles.length == 2){
/*if(total === 0 ){
return d4theme.colors.quantiles[0];//return '#fff';
}else if(total <= vm._quantiles[1]){
return d4theme.colors.quantiles[1];//return "#f7c7c5";
}*/
if(total <= vm._quantiles[1]){
return vm._config.plotOptions.map.quantiles.colors[0];//"#f7c7c5";
}
}
}
return new Map(config);
}<file_sep>/Internship/dboxjs/core-master/lib/bk/bars/barchart.js
/*
* Simple Bar chart
*/
import * as d3 from "d3";
export default function(config) {
function Bars(config) {
var vm = this;
vm._config = config ? config : {};
vm._data = [];
vm._config.colorScale = d3.schemeCategory20c;
vm._config._format = function(d){
if(d % 1 == 0){
return d3.format(",.0f")(d);
} else if(d < 1 && d > 0) {
return d3.format(",.2f")(d);
} else {
return d3.format(",.1f")(d);
}
};
vm._scales = {};
vm._axes = {};
//vm._tip = vm.utils.d3.tip().attr('class', 'd3-tip tip-bars').html(vm._config.data.tip || function(d){ return d;});
vm._tip = vm.utils.d3.tip()
.attr('class', 'd3-tip tip-treemap')
.direction('n')
.html(vm._config.tip || function(d){ return vm._config._format(d[vm._config.y])});
}
//-------------------------------
//User config functions
Bars.prototype.x = function(columnName) {
var vm = this;
vm._config.x = columnName;
return vm;
}
Bars.prototype.y = function(columnName) {
var vm = this;
vm._config.y = columnName;
return vm;
}
Bars.prototype.color = function(columnName) {
var vm = this;
vm._config.color = columnName;
return vm;
}
Bars.prototype.end = function() {
var vm = this;
return vm._chart;
}
Bars.prototype.colorScale = function(colorScale) {
var vm = this;
if(Array.isArray(colorScale)) {
vm._config.colorScale = colorScale;
} else {
vm._scales.color = colorScale;
vm._config.colorScale = colorScale.range();
}
return vm;
}
Bars.prototype.format = function(format) {
var vm = this;
if (typeof format == 'function' || format instanceof Function)
vm._config._format = format;
else
vm._config._format = d3.format(format);
return vm;
}
//-------------------------------
//Triggered by the chart.js;
Bars.prototype.chart = function(chart) {
var vm = this;
vm._chart = chart;
return vm;
}
Bars.prototype.data = function(data) {
var vm = this;
vm._data = data.map(function(d) {
if(d[vm._config.x] == Number(d[vm._config.x]))
d[vm._config.x] = +d[vm._config.x];
if(d[vm._config.y] == Number(d[vm._config.y]))
d[vm._config.y] = +d[vm._config.y];
return d;
});
return vm;
}
Bars.prototype.scales = function(s) {
var vm = this;
//vm._scales = s;
/* Use
* vm._config.x
* vm._config.xAxis.scale
* vm._config.y
* vm._config.yAxis.scale
* vm._data
*/
/* Generate x scale */
var config = {
column: vm._config.x,
type: vm._config.xAxis.scale,
range: [0, vm._chart._width],
minZero: true
};
vm._scales.x = vm._chart.generateScale(vm._data, config);
/* Generate y scale */
config = {
column: vm._config.y,
type: vm._config.yAxis.scale,
range: [vm._chart._height, 0],
minZero: true
};
vm._scales.y = vm._chart.generateScale(vm._data, config);
vm._chart._scales.x = vm._scales.x;
vm._chart._scales.y = vm._scales.y;
if(!vm._scales.color)
vm._scales.color = d3.scaleOrdinal(vm._config.colorScale);
return vm;
}
Bars.prototype.axes = function(a) {
var vm = this;
vm._axes = a;
return vm;
}
Bars.prototype.domains = function() {
var vm = this;
return vm;
};
Bars.prototype.draw = function() {
var vm = this;
vm._chart._svg.call(vm._tip);
if(vm._config.xAxis.enabled) {
vm._chart._svg.append("g")
.attr("class", "xAxis axis")
.attr("transform", "translate(0," + vm._chart._height + ")")
.call(d3.axisBottom(vm._scales.x)
.tickValues(vm._config.xAxis.tickValues)
.tickFormat(vm._config.xAxis.tickFormat)
);
//vm._chart._svg.selectAll(".xAxis.axis text").attr("transform", "translate(0,10)rotate(-20)");
}
if(vm._config.yAxis.enabled) {
if(vm._config.yAxis.position == 'right') {
var yAxis = d3.axisRight(vm._scales.y)
.ticks(vm._config.yAxis.ticks)
.tickValues(vm._config.yAxis.tickValues)
.tickFormat(vm._config.yAxis.tickFormat);
} else {
var yAxis = d3.axisLeft(vm._scales.y)
.ticks(vm._config.yAxis.ticks)
.tickValues(vm._config.yAxis.tickValues)
.tickFormat(vm._config.yAxis.tickFormat);
}
var axisY = vm._chart._svg.append("g")
.attr("class", "yAxis axis");
if(vm._config.yAxis.position == 'right')
axisY.attr("transform", "translate(" + vm._chart._width + ",0)");
axisY.call(yAxis);
/*
Axis Title
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Frequency");
*/
}
vm._chart._svg.selectAll(".bar")
.data(vm._data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return vm._config.xAxis.scale == 'linear' && vm._config.yAxis.scale == 'linear'? 0 : vm._scales.x(d[vm._config.x]); })
.attr("y", function(d) { return vm._scales.y(d[vm._config.y]);})
.attr("width", function(d){ return vm._scales.x.bandwidth ? vm._scales.x.bandwidth() : vm._scales.x(d[vm._config.x]) })
.attr("height", function(d) { return vm._chart._height - vm._scales.y(d[vm._config.y]); })
.attr("fill", function(d){ return vm._scales.color(d[vm._config.color])})
.style("opacity", 0.9)
.on('mouseover', function(d) {
vm._tip.show(d, d3.select(this).node());
})
.on('mouseout', function() {
vm._tip.hide();
})
.on('click', function() {
});
return vm;
}
return new Bars(config);
}
<file_sep>/Internship/dboxjs/core-master/lib/bk/bars/quantilesAndCircles.js
/*eslint-disable*/
function QuantilesAndCircles(options) {
var vm = this;
vm._config = options.config;
vm._chart = options.chart;
vm._data = options.data;
vm._scales = options.scales;
}
QuantilesAndCircles.prototype.getAverages = function(){
var vm = this;
var auxArray = [], auxArray2= [];
var idx = 0;
var averageArray = [];
vm._data.forEach(function(d){
auxArray2.push(d.y);
auxArray[idx] = auxArray2;
if(vm._scales.q(d.x) != idx){
auxArray2 = [];
idx = vm._scales.q(d.x);
}
/* if(vm._scales.q(d.x) == idx){
auxArray2.push(d.y);
auxArray[idx] = auxArray2;
}else{
auxArray2.push(d.y);
auxArray[idx] = auxArray2;
auxArray2 = [];
idx = vm._scales.q(d.x)
}
*/
})
//console.log(auxArray);
auxArray.forEach(function(d,i){
averageArray[i] = {y:d3.mean(d),x:i};
});
//console.log(averageArray);
return averageArray;
}
QuantilesAndCircles.prototype.draw = function (){
var vm = this;
var averages = [];
averages = this.getAverages();
vm._chart._svg.selectAll(".recta")
.data(averages)
.enter().append("rect")
.attr("class", "recta")
.attr("x", function(d) {
return vm._scales.x ( d.x ) + vm._scales.x.rangeBand()/16;
})
.attr("y", function(d){
return vm._scales.y(d.y);
})
.attr("width",vm._scales.x.rangeBand())
.attr("height",function(d){
return vm._scales.y(0) - vm._scales.y(d.y);
})
.style("fill", '#f4f4f4')
.on('mouseover', function(d,i){
//vm._config.data.mouseover.call(vm, d,i);
});
vm._chart._svg.selectAll(".recta2")
.data(averages)
.enter().append("rect")
.attr("class", "recta2")
.attr("x", function(d) {
//console.log("x",d.x)
return vm._scales.x ( d.x ) + vm._scales.x.rangeBand()/16;
})
.attr("y", function(d){
return vm._scales.y(d.y);
})
.attr("width",vm._scales.x.rangeBand())
.attr("height",function(d){
return 5;
})
.style("fill", '#ffcd32');
/*.text(function(d){
console.log(d);
return d.country
})
.style("fill", '#000');*/
vm._chart._svg.selectAll(".dot")
.data(vm._data,function(d){
return d.key;
})
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 12)
.attr("cx", function(d) { //console.log('X',d.x, vm._scales.q(d.x));
return vm._scales.x ( vm._scales.q(d.x) ) +vm._scales.x.rangeBand()/2; })
.attr("cy", function(d) { return vm._scales.y(d.y); })
.style("fill", '#b4b4b4')
.style("fill-opacity",'0.4')
.on('mouseover', function(d,i){
vm._config.data.mouseover.call(this, d,i);
});
vm._chart._svg.selectAll(".dot2")
.data(vm._data,function(d){
return d.key;
})
.enter()
.append("circle")
.attr("class", "dot2")
.attr("r", 8)
.attr("cx", function(d) { //console.log('X',d.x, vm._scales.q(d.x));
return vm._scales.x ( vm._scales.q(d.x) ) +vm._scales.x.rangeBand()/2; })
.attr("cy", function(d) { return vm._scales.y(d.y); })
.style("fill", '#7f7f7f')
.style("fill-opacity",'0.4')
.on('mouseover', function(d,i){
vm._config.data.mouseover.call(vm, d,i);
});
/*vm._chart._svg.selectAll('line.stem')
.data(vm._data)
.enter()
.append('line')
.classed('stem', true)
.attr('x1', function(d){
return vm._scales.x(d.x)+vm._scales.x.range()/2;
})
.attr('x2', function(d){
return vm._scales.x(d.x)+vm._scales.x.range()/2;
})
.attr('y1', function(d){
return vm._scales.y(d.y);
})
.attr('y2', vm._chart._height)
.attr('stroke', '#7A7A7A')*/
vm._chart._svg.selectAll('circle')
.data(vm._data)
.enter()
.append('circle')
.attr('cx', function(d) {
return vm._scales.x(d.x);
})
.attr('cy', function(d) {
return vm._scales.y(d.y);
})
.attr('r', 6)
.attr('fill', '#ccc')
.style('cursor', 'pointer')
}
QuantilesAndCircles.prototype.renameAxis = function (axis){
var vm = this;
console.log('Domain',vm._scales.q.domain().length)
console.log('Range',vm._scales.q.range())
console.log('Treshold',vm._scales.q.quantiles());
var rangeValues = vm._scales.q.range();
var domainValues = vm._scales.q.domain();
var treshold = vm._scales.q.quantiles();
axis.selectAll("text")
.text(function(d){
if(treshold[d] == undefined){
return treshold[d - 1].toFixed(2) + " - " + d3.max(domainValues).toFixed(2);
}
if(d==0){
return d3.min(domainValues).toFixed(2) + " - " + treshold[d].toFixed(2);
}
return treshold[d - 1].toFixed(2) + " - " + treshold[d].toFixed(2);
})
}
export default function quantilesAndCircles(options) {
return new QuantilesAndCircles(arguments.length ? options : null);
}
/*eslint-enable*/<file_sep>/Internship/dboxjs/core-master/lib/bk/bars/columns.js
/*eslint-disable*/
function Columns(options) {
var vm = this;
vm._config = options.config;
vm._chart = options.chart;
vm._data = options.data;
vm._scales = options.scales;
}
Columns.prototype.draw = function (){
var vm = this;
/*var width = vm._scales.x.range()[1];
var dates = vm._data.map(function(d){
return d.x;
});
var bandWidth = d3.scaleOrdinal()
.domain(dates)
.rangeRoundBands(vm._scales.x.range(), 0.1)
.rangeBand(); */
vm._chart._svg.selectAll(".bar")
.data(vm._data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return vm._scales.x(d.x); })
.attr("width", vm._scales.x.rangeBand())
.attr("y", function(d) { return vm._scales.y(d.y); })
.attr("height", function(d) { return vm._chart._height - vm._scales.y(d.y); })
.attr("fill", function(d){return d.color;})
.on('mouseover', function(d,i){
if(vm._config.data.mouseover){
vm._config.data.mouseover.call(vm, d,i)
}
vm._chart._tip.show(d, d3.select(this).node())
})
.on('mouseout',function(d,i){
if(vm._config.data.mouseout){
vm._config.data.mouseout.call(vm, d,i)
}
vm._chart._tip.hide(d, d3.select(this).node())
});
}
Columns.prototype.select = function (selector){
var vm = this;
var select = false;
vm._chart._svg.selectAll('.bar')
.each(function(d){
if(d.x === selector || d.y === selector){
select = d3.select(this);
}
})
return select;
}
export default function columns(options) {
return new Columns(arguments.length ? options : null);
}
/*eslint-enable*/<file_sep>/Internship/dboxjs/core-master/lib/bk/area/stackedArea.js
/*eslint-disable*/
// TODO: Update example
/* Stacked Area example
*/
import * as d3 from "d3";
function StackedArea(config) {
var vm = this;
vm._config = config;
vm._chart;
vm._scales = {};
vm._axes = {};
}
StackedArea.prototype = stackedArea.prototype = {
generate:function(){
var vm = this, q;
vm.draw();
vm.setScales();
vm.setAxes();
q = vm._chart.loadData();
q.await(function(error,data){
if (error) throw error;
//console.log(error,data);
vm.setData(data);
vm.drawData();
})
},
select: function(datum){
return d3.selectAll(".layer").data(datum);
},
draw : function(){
var vm = this
vm._chart = chart(vm._config);
},
setScales: function(){
var vm = this;
vm._scales.x = d3.scaleOrdinal()
.rangePoints([0, vm._chart._width]);
vm._scales.y = d3.scaleLinear()
.range([vm._chart._height, 0]);
if(vm._config.colorScale)
vm._scales.color = vm._config.colorScale;
if(!vm._config.colorScale)
vm._scales.color = d3.scaleOrdinal(d3.schemeCategory20);
},
setAxes : function(){
var vm = this;
vm._axes.x = d3.svg.axis()
.scale(vm._scales.x)
.orient("bottom");
vm._axes.y = d3.svg.axis()
.scale(vm._scales.y)
.orient("left");
},
setData:function(data){
var vm = this;
vm._data = data;
},
setDomains:function(){
var vm = this;
vm._scales.x.domain(vm._data.map(function(d) { return d.x; }));
vm._scales.y.domain([0, d3.max(vm._data, function(d) { return d.y0 + d.y; })]);
if(vm._config.percentage)
vm._scales.y.domain([0, 100]);
},
drawAxes:function(){
var vm = this;
vm._chart._svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + vm._chart._height + ")")
.call(vm._axes.x)
.append("text")
.attr("class", "label")
.attr("x", vm._chart._width)
.attr("y", -6)
.style("text-anchor", "end");
vm._chart._svg.append("g")
.attr("class", "y axis")
.call(vm._axes.y)
.append("text")
.attr("class", "label")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end");
},
drawData : function(){
var vm = this;
var total = d3.nest()
.key(function(d){ return d.x; })
.rollup(function(leaves){
return d3.sum(leaves, function(j){ return j.y; });
}).entries(vm._data);
var stack = d3.layout.stack()
.offset("zero")
.values(function(d) { return d.values; })
.x(function(d) { return d.x; })
.y(function(d) { return d.y; });
var nest = d3.nest()
.key(function(d) { return d.key; });
var area = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return vm._scales.x(d.x); })
.y0(function(d) { return vm._scales.y(d.y0); })
.y1(function(d) { return vm._scales.y(d.y0 + d.y); });
if(vm._config.percentage){
var area = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return vm._scales.x(d.x); })
.y0(function(d) { return vm._scales.y((d.y0) * 100 / getChild(total, d.x+'').values); })
.y1(function(d) { return vm._scales.y((d.y0 + d.y) * 100 / getChild(total, d.x+'').values); });
}
var nestedData = nest.entries(vm._data).sort(function(a,b){ return a.values[a.values.length - 1].y > b.values[b.values.length -1].y ? -1 : 1;});
var layers = stack(nestedData);
vm.setDomains();
vm.drawAxes();
vm._chart._svg.selectAll(".layer")
.data(layers, function(d){return d.key;})
.enter().append("path")
.attr("class", "layer")
.attr("d", function(d) { return area(d.values); })
.style("fill", function(d, i) { return vm._scales.color(i); })
.on("click", function(d, i){
vm._config.data.onclick.call(this, d, i); })
.on("mouseover", function(d, i){
vm._config.data.onmouseover.call(this, d, i); })
.on("mouseout", function(d, i){
vm._config.data.onmouseout.call(this, d, i); });
}
}
function getChild(data, key){
var obj = {};
data.forEach(function(d){
if(d.key === key){
obj = d;
}
});
return obj;
}
export default function stackedArea(config){
return new StackedArea(arguments.length ? config : null);
}
/*eslint-enable*/
<file_sep>/Internship/dboxjs/core-master/lib/bk/map/map-bkup.js
/*
Map.prototype = map.prototype = {
generate:function(){
var vm = this, q;
vm.init();
q = vm._chart.loadData();
q.await(function(error,data){
if (error) {
throw error;
return false;
}
// @TODO DRAW SVG UNTIL CHART FINISHED LOADING DATA
//vm.draw();
vm._setChartType();
vm.setData(data);
vm.drawData();
vm._chart.dispatch.on("load.chart", vm._config.events.load(vm));
})
},
init : function(){
var vm = this
vm._chart = chart(vm._config);
},
//@TODO DRAW SVG UNTIL CHART FINISHED LOADING DATA
// draw : function(){
// var vm = this
// vm._chart.draw();
//},
_setChartType:function(){
var vm = this;
var params ={
"config" : vm._config,
"chart" : vm._chart,
}
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geo){
switch(vm._config.plotOptions.map.geo){
case 'mexico':
vm.geo = geoMexico(params);
break;
}
}
},
setData:function(data){
var vm = this;
if(vm._config.data.filter){
data = data.filter(vm._config.data.filter);
}
vm._data = data;
vm.quantiles = vm._setQuantile(data);
vm.minMax = d3.extent(data, function(d) { return d.z; })
vm._config.plotOptions.map.min = vm.minMax [0];
vm._config.plotOptions.map.max = vm.minMax [1];
vm.geo._config = vm._config;
vm.geo._data = data;
vm.geo.quantiles = vm.quantiles;
vm.geo.minMax = vm.minMax
vm.geo._getQuantileColor = vm._getQuantileColor;
},
_setQuantile: function(data){
var vm = this;
var values = [];
var quantile = [];
if(vm._config.plotOptions.map.quantiles.predefinedQuantiles.length > 0){
return vm._config.plotOptions.map.quantiles.predefinedQuantiles;
}
data.forEach(function(d){
values.push(d.z);
});
values.sort(d3.ascending);
//@TODO use quantile scale instead of manual calculations
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.quantiles && vm._config.plotOptions.map.quantiles.buckets){
if(vm._config.plotOptions.map.quantiles.ignoreZeros === true){
var aux = _.dropWhile(values, function(o) { return o <= 0 });
//aux.unshift(values[0]);
quantile.push(values[0]);
quantile.push(0);
for(var i = 1; i <= vm._config.plotOptions.map.quantiles.buckets - 1; i++ ){
quantile.push( d3.quantile(aux, i* 1/(vm._config.plotOptions.map.quantiles.buckets - 1) ) )
}
}else{
quantile.push( d3.quantile(values, 0) )
for(var i = 1; i <= vm._config.plotOptions.map.quantiles.buckets; i++ ){
quantile.push( d3.quantile(values, i* 1/vm._config.plotOptions.map.quantiles.buckets ) )
}
}
}else{
quantile = [ d3.quantile(values, 0), d3.quantile(values, 0.2), d3.quantile(values, 0.4), d3.quantile(values, 0.6), d3.quantile(values, 0.8), d3.quantile(values,1) ];
}
//@TODO - VALIDATE WHEN ZEROS NEED TO BE PUT ON QUANTILE 1 AND RECALCULATE NON ZERO VALUES INTO THE REST OF THE BUCKETS
if( vm._config.plotOptions.map.quantiles.buckets === 5){
if( quantile[1] === quantile[2] && quantile[2] === quantile[3] && quantile[3] === quantile[4] && quantile[4] === quantile[5]){
quantile = [ d3.quantile(values, 0), d3.quantile(values, 0.2) ];
}
}
return quantile;
},
_getQuantileColor: function(d){
var vm = this;
var total = parseFloat(d.z);
//@TODO use quantile scale instead of manual calculations
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.quantiles && vm._config.plotOptions.map.quantiles.colors){
if(vm.quantiles.length > 2){
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.min !== undefined && vm._config.plotOptions.map.max !== undefined){
if(total < vm._config.plotOptions.map.min || total > vm._config.plotOptions.map.max){
console.log('outOfRangeColor', total, vm._config.plotOptions.map.min ,vm._config.plotOptions.map.max)
return vm._config.plotOptions.map.quantiles.outOfRangeColor;
}
}else{
if(total < vm.minMax[0] || total > vm.minMax[1]){
console.log('outOfRangeColor', total, vm._config.plotOptions.map.min ,vm._config.plotOptions.map.max)
return vm._config.plotOptions.map.quantiles.outOfRangeColor;
}
}
if(total <= vm.quantiles[1]){
return vm._config.plotOptions.map.quantiles.colors[0];//"#f7c7c5";
}else if(total <= vm.quantiles[2]){
return vm._config.plotOptions.map.quantiles.colors[1];//"#e65158";
}else if(total <= vm.quantiles[3]){
return vm._config.plotOptions.map.quantiles.colors[2];//"#c20216";
}else if(total <= vm.quantiles[4]){
return vm._config.plotOptions.map.quantiles.colors[3];//"#750000";
}else if(total <= vm.quantiles[5]){
return vm._config.plotOptions.map.quantiles.colors[4];//"#480000";
}
}
}
if(vm.quantiles.length == 2){
//if(total === 0 ){
// return d4theme.colors.quantiles[0];//return '#fff';
//}else if(total <= vm.quantiles[1]){
// return d4theme.colors.quantiles[1];//return "#f7c7c5";
//}
if(total <= vm.quantiles[1]){
return vm._config.plotOptions.map.quantiles.colors[0];//"#f7c7c5";
}
}
},
drawData : function(){
var vm = this;
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'states'){
vm.geo.drawStates();
}
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'municipalities'){
vm.geo.drawMunicipalities();
}
vm._drawLegend();
},
_drawLegend: function(){
var vm = this;
var quantiles = [], legendWidth, legendFill;
if(typeof vm._config.legend === 'object'){
legendWidth = vm._config.legend.width ? vm._config.legend.width : 150;
legendFill = vm._config.legend.fill ? vm._config.legend.fill : 'white';
}
vm._chart._svg.select('.legend').remove();
vm._chart._legend = vm._chart._svg.append('g')
.classed('legend',true);
vm.quantilesWithFormat = [];
vm.quantiles.forEach(function(q){
vm.quantilesWithFormat.push(vm.format[vm._config.plotOptions.map.units](q))
})
//@Todo - Make it dynamic according to the buckets number in the config
if(vm.quantiles.length>2){
quantiles = [
{color: vm._config.plotOptions.map.quantiles.outOfRangeColor, value: 'Fuera de rango seleccionado', text: 'Fuera de rango seleccionado' },
//@TODO - ADD NA VALUES --- {color: '#808080', value: 'N/A' },
{color: vm._config.plotOptions.map.quantiles.colors[0], value: vm.quantiles[1], text: vm.quantilesWithFormat[0] +' a '+ vm.quantilesWithFormat[1] },
{color: vm._config.plotOptions.map.quantiles.colors[1], value: vm.quantiles[2], text: vm.quantilesWithFormat[1] +' a '+ vm.quantilesWithFormat[2] },
{color: vm._config.plotOptions.map.quantiles.colors[2], value: vm.quantiles[3], text: vm.quantilesWithFormat[2] +' a '+ vm.quantilesWithFormat[3] },
{color: vm._config.plotOptions.map.quantiles.colors[3], value: vm.quantiles[4], text: vm.quantilesWithFormat[3] +' a '+ vm.quantilesWithFormat[4] },
{color: vm._config.plotOptions.map.quantiles.colors[4], value: vm.quantiles[5], text: vm.quantilesWithFormat[4] +' a '+ vm.quantilesWithFormat[5] },
];
}
//START GENERATING SHADOW
var defs = vm._chart._svg.append("defs");
var filter = defs.append("filter")
.attr("id", "drop-shadow")
.attr("x",0)
.attr("y",0)
.attr("height", "120%");
filter.append("feoffset")
.attr("in", "SourceGraphic")
.attr("dx", 5)
.attr("dy", 5)
.attr("result", "offOut");
filter.append("feColorMatrix")
.attr("result","matrixOut")
.attr("in","offOut")
.attr("type","matrix")
.attr("values","0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.4 0");
filter.append("feGaussianBlur")
.attr("in", "matrixOut")
.attr("result", "blurOut")
.attr("stdDeviation", 5);
filter.append("feblend")
.attr("in", "SourceGraphic")
.attr("in2", "blurOut")
.attr("mode", "normal");
var feMerge = filter.append("feMerge");
feMerge.append("feMergeNode")
.attr("in", "offsetBlur")
feMerge.append("feMergeNode")
.attr("in", "SourceGraphic");
//FINISH GENERATING SHADOW
vm._chart._legend
.append('rect')
.attr('class','back-rect')
.attr('x', 5)
.attr('y', (vm._chart._height - (20 * quantiles.length)+ 10) - 20)
.attr('width', legendWidth + 15)
.attr('height', (20 * quantiles.length) + 60 )
.style('fill', legendFill)
.attr('rx', 5)
.attr('ry', 5)
.style("filter", "url(#drop-shadow)")
vm._chart._legend.selectAll('.rect-info')
.data(quantiles)
.enter().append('circle')
.attr('cx', 28)
.attr('cy', function(d,i){
i++;
var y = (vm._chart._height - (20 * quantiles.length)) + (i*20);
return y + 25;
})
.attr('r', 9)
//.enter().append('rect')
//.attr('class','rect-info')
//.attr('x', 10)
//.attr('y', function(d,i){
// i++;
// var y = (vm._chart._height - (20 * quantiles.length)) + (i*20);
// return y;
//})
//.attr('width', 18)
//.attr('height', 18)
.style('fill', function(d){
return d.color;
})
.style('stroke', '#A7A7A7');
vm._chart._legend.append('rect')
.attr('width', legendWidth - 5)
.attr('height', (20 * quantiles.length) + 17)
.attr('x', 14)
.attr('y', (vm._chart._height - (20 * quantiles.length)) + 24)
.attr('fill', 'rgba(0,0,0,0)')
.attr('stroke', '#AEADB3')
.attr('stroke-dasharray', '10,5')
.attr('stroke-linecap', 'butt')
.attr('stroke-width', '3')
vm._chart._legend.selectAll('text')
.data(quantiles)
.enter().append('text')
.text(function(d, i){
return d.text ;
})
.attr("font-family", "Roboto")
.attr("font-size", "12pts")
.style("fill","#aeadb3")
.style("font-weight", "bold")
.attr('x', 43)
.attr('y', function(d,i){
i++;
var y = 15 + (vm._chart._height - (20 * quantiles.length)) + (i*20);
return y + 15;
})
.call(wrap, legendWidth);
vm._chart._legend
.append("text")
.attr("x",10)
.attr("y",(vm._chart._height - (20 * quantiles.length)) + 12)
.text(vm._config.legend.title)
.attr("font-family", "Roboto")
.attr("font-size", "11px")
.style("fill","#aeadb3")
.style("font-weight", "bold")
.call(wrap, legendWidth);
},
update :function(config){
var vm = this, q;
vm._config = config;
vm._chart._config = config;
q = vm._chart.loadData();
q.await(function(error,data){
if (error) {
throw error;
return false;
}
vm.setData(data);
vm.redrawData();
vm._chart.dispatch.on("load.chart", vm._config.events.load(vm));
})
},
redrawData: function (){
var vm = this;
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'states'){
vm.geo.redrawStates();
}
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'municipalities'){
vm.geo.redrawMunicipalities();
}
vm._drawLegend();
},
filterByMinMax: function(minMax){
var vm = this;
vm._config.plotOptions.map.min = minMax[0];
vm._config.plotOptions.map.max = minMax[1];
vm.geo._config.plotOptions.map.min = minMax[0];
vm.geo._config.plotOptions.map.max = minMax[1];
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'states'){
vm.geo.filterByMinMaxStates();
}
if(vm._config.plotOptions && vm._config.plotOptions.map && vm._config.plotOptions.map.geoDivision == 'municipalities'){
vm.geo.filterByMinMaxMunicipalities();
}
},
set: function(option,value){
var vm = this;
if(option === 'config') {
vm._config = value;
}else{
vm._config[option] = value ;
}
},
select:function(selector){
var vm = this;
var select = false;
vm._chart._svg.selectAll('path')
.each(function(d){
if(d.id === selector){
select = d3.select(this);
}
});
return select;
},
triggerMouseOver:function(selector){
var vm = this;
vm._chart._svg.selectAll('circle')
.each(function(d){
if(d.x === selector || d.y === selector || d.z === selector){
vm._chart._tip.show(d,d3.select(this).node())
}
})
},
triggerMouseOut:function(selector){
var vm = this;
vm._chart._svg.selectAll('circle')
.each(function(d){
if(d.x === selector || d.y === selector || d.z === selector){
vm._chart._tip.hide(d,d3.select(this).node())
}
})
},
redraw: function(){
var vm = this;
vm._chart.destroy();
vm.generate();
}
}
Map.prototype.resetStates = function(){
var vm = this;
vm.geo.resetStates();
}
function wrap(text, width) {
text.each(function() {
var text = d3.select(this)
var dy1 = 0;
if ((width - text.text().length) < 150){
dy1 = - 6;
}
var words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 8, // ems
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("y"))/10;
var tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy1 + "px");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + "px").text(word).attr("font-size", "11px");
}
}
});
}
export default function map(config) {
return new Map(arguments.length ? config : null);
}
*/<file_sep>/README.md
# Internship
Repositorio dedicado al internship d3 JS
|
efcd94745b595a391c31f494655eb99063b5f32b
|
[
"JavaScript",
"Markdown"
] | 11
|
JavaScript
|
oss05/Internship
|
c8467c4d475b335f7689c9e623db412be25b1b83
|
941a2b701fcb626fd8076dc74e60926e02a4fb15
|
refs/heads/main
|
<repo_name>dhruvg1999/fetcher<file_sep>/src/App.js
import React from "react";
import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
loaded: false
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/photos?_start=0&_limit=50")
.then((res) => res.json())
.then((json) => {
this.setState({
data: json,
loaded: true
});
})
}
render() {
const { loaded, data } = this.state;
if (!loaded) return <div>
<h1>Loading....</h1> </div> ;
return (
<div className = "App">
{
data.map((item) => (
<div key = { item.id }>
<h1>{ item.title }</h1>
<img src={ item.url } alt="" id="image"></img>
</div>
))
}
</div>
);
}
}
export default App;
|
a9b0609ab318bc91e609e1446134a737952324a1
|
[
"JavaScript"
] | 1
|
JavaScript
|
dhruvg1999/fetcher
|
bd025f0a2278fc92ed8f2e1133079e0fdca43e5d
|
5a36cf77c7181c73c6aa1a773ec6e01873bab6f4
|
refs/heads/main
|
<file_sep> $(document).ready(function() {
var expandThisID ="";
var slideThis = "";
var divPosition = 0;
// slide active accordion header up to position
function slideACC () {
if ($("div").parent().attr("class") == "panel-group") {
expandThisID = $(this).data("section");
divPosition = 100;
slideThis = "#"+expandThisID;
}
$('html, body').animate({
scrollTop: $(slideThis).offset().top - divPosition
}, 1000);
}
$(".panel-default").click(function() {
setTimeout(slideACC(),800);
});
})
<file_sep># heal-public
<file_sep>$(document).ready(function(){
$('.dropdown-submenu a.dropdown-submenu-toggle').on("click", function(e){
var subMenu = $(this).next('.dropdown-menu.second');
var allSubMenu = $('.dropdown-menu.second');
$(allSubMenu).each(function(){
if($(this).is(subMenu)){
if ($(this).is(":visible")) {
//console.log("hiding " + thisMenu )
// $(this).hide()
$(this).removeClass('on');
} else {
//console.log("showing " + thisMenu)
// $(this).show();
$(this).addClass('on');
}
} else {
//console.log("hiding " + thisMenu)
// $(this).hide();
$(this).removeClass('on');
}
});
// $(allSubMenu).each(function(){
// if($(this).is(subMenu)){
// if ($(this).is(":visible")) {
// //console.log("hiding " + thisMenu )
// $(this).hide()
// } else {
// //console.log("showing " + thisMenu)
// $(this).show();
// }
// } else {
// //console.log("hiding " + thisMenu)
// $(this).hide();
// }
// });
e.stopPropagation();
e.preventDefault();
});
// Event handler to toggle icon on FAQ accordion show-hide
$( ".panel-collapse" ).on( "show.bs.collapse hide.bs.collapse", function() {
var icon = $( this ).siblings( ".panel-heading").find( ".fas" );
// $( icon ).toggleClass( "fa-chevron-circle-down" );
$( icon ).toggleClass( "rotate-chevron" );
});
/* options */
var readMore = $('.read-more');
var readLess = $('.read-less');
var speed = "1000"; // possible values: milliseconds, "slow", "fast"
var easing = "linear" // possible values: "linear", "swing"
/* handle click of "read more" button */
readMore.on('click', function(){
var divToShow = "#hide-"+$(this).data("name");
$(divToShow).slideDown(speed, easing);
$(this).toggleClass("readMoreOff");
});
/* handle click of "read less" button */
readLess.on('click', function() {
var divToHide = "#hide-"+$(this).data("name");
var parentDiv = "#read-"+$(this).data("name");
$(divToHide).slideUp(speed, easing);
$(parentDiv).toggleClass("readMoreOff");
});
//SCROLL UP ANIMATION - BOTTOM ARROW
$("#upArrow").click(function() {
var targetDiv = $(this).data("link");
var divPosition = $("#"+targetDiv).offset().top - 100;
$('html, body').animate({scrollTop: divPosition}, "slow");
});
//TOOLTIPS
function openTooltip (thisTooltip) {
var child = $(thisTooltip).children();
$(child).toggleClass("visible");
}
/* open tooltip on Click*/
$('.tooltipBtn').click(function(){
openTooltip(this);
});
// Open Mail Chimp Modal via link
$('a[href$="#mailChimpModal"]').on( "click", function() {
$('#mailChimpModal').modal('show');
});
})
<file_sep><!DOCTYPE html>
<html lang="en-US">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-153394354-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-153394354-1');
// gtag('event', 'Outbound URL');
</script>
<!-- END GA Code-->
<!--tracker-->
<script>
/**
* Function that captures a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var captureOutboundLink = function(url){
gtag('event', 'click', {
'event_category' : 'outbound',
'event_label' : url,
'transport_type' : 'beacon'
// 'event_callback': function(){document.location = url;}
})
}
</script>
<!--link tracker-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Massachusetts | HEALing Communities Study</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/7813ede11b.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/heal-public/assets/css/main.css">
<link rel="stylesheet" href="/heal-public/assets/css/state.css">
</head>
<body>
<nav class="navbar navbar-default" id="nav">
<div class="container-fluid bg-gradient">
<div class="navbar-header" id="brandHeader">
<a class="navbar-brand navbar-left" href="/heal-public/index.html">
<img src="/heal-public/assets/images/HEAL-header.jpg" alt="" id="headImg">
</a>
</div>
<div class="navbar-header" id="ham">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-right" id="navbar-collapse">
<ul class="nav navbar-nav">
<li class="">
<a href="/heal-public/index.html">
<span class="fa fa-home"></span>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Find Local Resources <span class="caret"></span></a>
<ul class="dropdown-menu" id="local">
<!-- <li><a href="/heal-public/find-local-resources.html">Find Local Resources</a></li> -->
<li class="dropdown-submenu">
<a href="#" class="dropdown-submenu-toggle">Kentucky <span class="caret"></span></a>
<ul class="dropdown-menu second">
<li class="first"><a href="/heal-public/sites/kentucky.html">Kentucky</a></li>
<li class="subNav"><a href="/heal-public/communities/kyboyd.html">Boyd</a></li>
<li class="subNav"><a href="/heal-public/communities/kyboyle.html">Boyle</a></li>
<li class="subNav"><a href="/heal-public/communities/kyclark.html">Clark</a></li>
<li class="subNav"><a href="/heal-public/communities/kyfayette.html">Fayette</a></li>
<li class="subNav"><a href="/heal-public/communities/kyfloyd.html">Floyd</a></li>
<li class="subNav"><a href="/heal-public/communities/kyfranklin.html">Franklin</a></li>
<li class="subNav"><a href="/heal-public/communities/kykenton.html">Kenton</a></li>
<li class="subNav"><a href="/heal-public/communities/kymadison.html">Madison</a></li>
</ul>
</li> <!--end kentucky-->
<li class="dropdown-submenu">
<a class="dropdown-submenu-toggle" href="#">Massachusetts <span class="caret"></span></a>
<ul class="dropdown-menu second">
<li class="first"><a href="/heal-public/sites/massachusetts.html">Massachusetts</a></li>
<li class="subNav"><a href="/heal-public/communities/mabourne-and-sandwich.html">Bourne & Sandwich</a></li>
<li class="subNav"><a href="/heal-public/communities/mabrockton.html">Brockton</a></li>
<li class="subNav"><a href="/heal-public/communities/magloucester.html">Gloucester</a></li>
<li class="subNav"><a href="/heal-public/communities/maholyoke.html">Holyoke</a></li>
<li class="subNav"><a href="/heal-public/communities/malowell.html">Lowell</a></li>
<li class="subNav"><a href="/heal-public/communities/maplymouth.html">Plymouth</a></li>
<li class="subNav"><a href="/heal-public/communities/masalem.html">Salem</a></li>
<li class="subNav"><a href="/heal-public/communities/mashirley-and-townsend.html">Shirley & Townsend</a></li>
</ul>
</li> <!---end massachusetts-->
<li class="dropdown-submenu">
<a class="dropdown-submenu-toggle" href="#">New York <span class="caret"></span></a>
<ul class="dropdown-menu second">
<li class="first"><a href="/heal-public/sites/new_york.html">New York</a></li>
<li class="subNav"><a href="/heal-public/communities/nycayuga.html">Cayuga</a></li>
<li class="subNav"><a href="/heal-public/communities/nycolumbia.html">Columbia</a></li>
<li class="subNav"><a href="/heal-public/communities/nyerie.html">Erie (Buffalo)</a></li>
<li class="subNav"><a href="/heal-public/communities/nygreene.html">Greene</a></li>
<li class="subNav"><a href="/heal-public/communities/nylewis.html">Lewis</a></li>
<li class="subNav"><a href="/heal-public/communities/nyputnam.html">Putnam</a></li>
<li class="subNav"><a href="/heal-public/communities/nysuffolk.html">Suffolk (Brookhaven)</a></li>
<li class="subNav"><a href="/heal-public/communities/nyulster.html">Ulster</a></li>
</ul>
</li> <!--end new york -->
<li class="dropdown-submenu">
<a class="dropdown-submenu-toggle" href="#ohio">Ohio <span class="caret"></span></a>
<ul class="dropdown-menu second" id="ohio">
<li class="first"><a href="/heal-public/sites/ohio.html">Ohio</a></li>
<li class="subNav"><a href="/heal-public/communities/ohashtabula.html">Ashtabula County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohathens.html">Athens County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohcuyahoga.html">Cuyahoga County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohdarke.html">Darke County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohgreene.html">Greene County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohguernsey.html">Guernsey County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohhamilton.html">Hamilton County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohlucas.html">Lucas County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohscioto.html">Scioto County</a></li>
</ul>
</li> <!--end ohio -->
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">About Opioid Use Disorder <span class="caret"></span></a>
<ul class="dropdown-menu" id="about">
<li><a href="/heal-public/about-oud/oud-addiction.html">Opioid Use Disorder & Addiction</a></li>
<li><a href="/heal-public/about-oud/moud.html">Medications for Opioid Use Disorder</a></li>
<li><a href="/heal-public/about-oud/naloxone.html">Naloxone</a></li>
<li><a href="/heal-public/about-oud/stigma.html">Stigma</a></li>
</ul>
</li>
<li class="">
<a href="/heal-public/take-action.html">
Take Action
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron stateJumbo" id="mass">
<div class="container-fluid">
<img src="/heal-public/assets/images/mass-upper.jpg" alt="" class="stateImg">
<h1 class="white stateBannerH1 text-sm-center" id="massH1">Massachusetts</h1>
</div>
</div>
<div class="container-fluid bg-magenta topGrad" id="stateGrad">
</div>
<div class="container state-content-1">
<div class="row">
<div class="col-sm-12 col-md-8 px-2 px-lg-1">
<h1 class="purple mt-0 mb-2 text-sm-left">State Snapshot</h1>
<p class="stateTopText mb-2">Boston Medical Center’s research team brings decades of experience treating people with substance use disorder to ending the opioid overdose epidemic across Massachusetts. In collaboration with HEAL communities’ grassroots coalitions, we’re committed to bridging the gaps that prevent people with opioid use disorder from accessing quality care and treatment.</p>
<button class="red bold mx-2 read-more readMoreTrans" id="read-state" data-name="state">Read More</button>
<div class="cs-word-hidden" id="hide-state">
<p class="mb-2">The Massachusetts HEALing Communities Study is an incredible opportunity for Boston Medical Center to participate in the unprecedented NIH HEAL Initiative<sup>SM</sup> to stem the national opioid crisis. The progress and findings from this research study will inform evidence-based solutions to reduce opioid overdose deaths.</p>
<button class="red bold mx-2 read-less" id="read-state-less" data-name="state">Read Less...</button>
</div>
</div> <!--end column-->
<div class="col-sm-12 col-md-4 px-0 mx-2 stateTopQuote">
<p class="ml-2 bold med-gray">"We are using an approach founded on evidence-based practices. By engaging communities in a program implementation process that works, we aim to get people into treatment, help them stay in treatment, and ultimately help them live a healthier life. We have good tools in the toolbox and this research study will help determine how our communities can reach as many people as possible with them."</p>
<p class=" pl-md-2 pr-md-4 pr-lg-2 stateTopQuoteName text-sm-right"><NAME>,<br>Project Director,<br>Boston Medical Center</p>
</div> <!--end column-->
</div>
</div>
<div class="container state-content-2">
<div class="row">
<div class="col-sm-12 col-md-6 px-md-0 stateFactoidOne stateFact">
<p class="py-3 px-3 px-md-2 px-lg-5 py-lg-5 text-sm-center factoidContent">Massachusetts is ranked among the <span class="magenta bold factCallOut">top 10 states</span> with the highest rates of opioid overdose deaths. <span class="tooltipBtn">1<span class="tooltiptext">1. National Institute on Drug Abuse. (2017). Opioid Summaries by State. Retrieved from <a href='https://www.drugabuse.gov/drugs-abuse/opioids/opioid-summaries-by-state' target='_blank' onclick="handleOutboundLinkClicks('https://www.drugabuse.gov/drugs-abuse/opioids/opioid-summaries-by-state');">here</a>.</span></span></p>
</div> <!--end factoid 1-->
<div class="col-sm-12 col-md-6 px-md-0 stateFactoidTwo stateFact">
<p class="py-3 px-3 px-md-2 px-lg-5 py-lg-5 text-sm-center factoidContent">Since 2015, there has been a 40% <span class="magenta bold factCallOut">decrease</span> in the number of number of <span class="magenta bold factCallOut">opioids prescribed</span> to Massachusetts residents.<span class="tooltipBtn">2<span class="tooltiptext">2. Massachusetts Department of Public Health (2020). MA Prescription Monitoring Program County-Level Data Measures (2019 Quarter 4). Retrieved from <a href='https://www.mass.gov/doc/prescription-monitoring-program-pmp-data-february-2020/download' target='_blank' onclick="handleOutboundLinkClicks('https://www.mass.gov/doc/prescription-monitoring-program-pmp-data-february-2020/download');">here</a>.</span></span></p>
</div> <!--end factoid 2-->
</div>
</div>
<div class="container state-content-3">
<div class="row">
<div class="col-sm-12 col-md-12 px-2 px-lg-0">
<h1 class="purple mt-3 mb-2 mt-lg-0 text-sm-left">Hope in HEALing</h1>
</div>
<div class="col-sm-12 col-md-3 px-2 px-lg-0">
<h2 class="coral mt-0 mb-2 text-sm-left">Our Grant</h2>
</div>
<div class="col-sm-12 col-md-9 px-2 px-lg-1">
<p class="mt-md-1 mb-1 text-sm-left">
Guided by shared decision-making and ownership in local communities, Boston Medical Center will work with community stakeholders to bridge gaps in prevention, treatment, and recovery services by testing the implementation of a suite of tailored programs.
</p>
<p class="mb-1 text-sm-left">
Key components of our approach include engaging with communities in a process to:
</p>
<ol>
<li class="mb-1 mx-2">Identify local needs and existing resources.</li>
<li class="mb-1 mx-2">Select and implement a range of evidence-based practices to reduce opioid overdose deaths.</li>
<li class="mb-1 mx-2">Communicate messages to reduce the stigma of opioid use disorder and increase the number of individuals receiving and adhering to medication for opioid use disorder.</li>
<li class="mb-2 mx-2">Accelerate access to low-threshold initiation of medication for opioid use disorder for individuals at high risk during hospitalization, incarceration, or detoxification.</li>
</ol>
<p class="mb-1 text-sm-left">
Each component is based on evidence that informs the strategies to reduce the negative impact of opioid use disorder, initiate and maintain people with opioid use disorder in treatment, and ultimately save lives.
</p>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-3 px-2 px-md-0">
<h2 class="coral mt-1 mt-md-0 mb-2 text-sm-left">What We Hope to Learn</h2>
</div>
<div class="col-sm-12 col-md-9 px-2 px-lg-1">
<p class="mt-md-1 mb-1 text-sm-left">
At Boston Medical Center, we’re committed to learning how best to work with communities to implement evidence-based interventions most effectively in order to reduce opioid overdose deaths. With an awareness that the solutions to reducing opioid overdose deaths are generated by collaborations between researchers and community partners, our aim is to optimize community-based strategies for addressing gaps in the prevention, care, and treatment for people with opioid use disorder.
</p>
<p class="mb-1 text-sm-left">
The ultimate effectiveness and sustainability of the Massachusetts HEALing Communities Study lies in the participating communities. Boston Medical Center is committed to facilitating an ongoing reciprocal relationship with HEAL communities that amplifies the impact of knowledge gained from this research study.
</p>
</div>
</div>
</div>
<div class="container state-content-4">
<div class="row">
<div class="col-sm-12 col-md-3 px-2 px-lg-0">
<h2 class="coral text-sm-left mt-0 mb-2">Our Communities in the HEALing Communities Study</h2>
</div>
<div class="col-sm-12 col-md-9 px-2 px-lg-1">
<div class="stateMapContain">
<img src="/heal-public/assets/images/mass_map.png" alt="Map of Healing Communities in Massachusetts" class="w-100 stateMapImg">
</div>
<div class="mt-4 mb-2">
<h3 class="purple bold mt-0 mb-2">Wave One</h3>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/mabourne-and-sandwich.html"><p>Bourne & Sandwich</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/mabrockton.html"><p>Brockton</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/magloucester.html"><p>Gloucester</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/maholyoke.html"><p>Holyoke</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/malowell.html"><p>Lowell</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/maplymouth.html"><p>Plymouth</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/masalem.html"><p>Salem</p></a>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<a class="underline" href="/heal-public/communities/mashirley-and-townsend.html"><p>Shirley & Townsend</p></a>
</div>
</div>
</div>
<div class="mt-4 mb-2">
<h3 class="purple bold mt-0 mb-2">Wave Two - Coming 2022</h3>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Berkeley, Dighton, & Freetown</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Athol, Greenfield, Montague, & Orange</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Belchertown & Ware</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Lawrence</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>North Adams</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Pittsfield</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Springfield</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 mb-1">
<p>Weymouth</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container state-content-5">
<div class="row">
<div class="col-sm-12 col-md-3 px-2 px-lg-0">
<h2 class="coral mt-0 mb-2 mt-md-1 text-sm-left">Study Contact</h2>
</div>
<div class="col-sm-12 col-md-9 px-2 px-lg-1">
<div class="">
<h3 class="purple bold mt-0">Principal Investigator</h3>
<h5 class="fw-normal"><NAME>, MD, MA, MPH</h5>
<h6 class="">HEALing Communities Study</h6>
<p class="">
Chief, Section of General Internal Medicine, Boston Medical Center<br>
Vice Chair for Public Health, Department of Medicine<br>
<NAME>, MD Professor in General Internal Medicine and Professor of Community Health Science, Boston University Schools of Medicine and Public Health
</p>
<a href="mailto:<EMAIL>" class=""><EMAIL></a>
</div>
<div class="">
<h3 class="purple bold">Project Director</h3>
<h5 class="fw-normal"><NAME>, MA, MPH</h5>
<h6 class="">HEALing Communities Study</h6>
<a href="mailto:<EMAIL>" class=""><EMAIL></a>
</div>
</div>
</div>
</div>
<div class="container-fluid stateBottomImg">
<img src="/heal-public/assets/images/mass-lower.jpg" alt="Workers gathered around a pickup truck" class="w-100">
</div>
<div class="container-fluid footer">
<div class="row text-sm-center" id="arrowRow">
<span class="fa-stack fa-2x mx-auto" id="upArrow" data-link="nav">
<i class="fas fa-circle coral fa-stack-2x"></i>
<i class="far fa-chevron-up fa-stack-1x"></i>
</span>
</div><!-- end row -->
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-2 col-lg-2 px-2 px-lg-0">
<div class="row special">
<div class="col-xs-12 col-sm-6 col-md-12">
<a href="https://heal.nih.gov/research/research-to-practice/healing-communities" target="external" onclick="captureOutboundLink('https://heal.nih.gov/research/research-to-practice/healing-communities');">
<svg id="footImg" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 100 1200 1000"><defs><style>.cls-1{font-size:408.82px;}.cls-1,.cls-2{fill:#fff;font-family:Montserrat-Bold, Montserrat;font-weight:700;}.cls-2{font-size:211.05px;}.cls-3{letter-spacing:-0.08em;}</style></defs><title>NIH HEAL Initiative Logo White</title><text class="cls-1" transform="translate(17 738.16)">HEAL</text><text class="cls-1" transform="translate(17 738.16)">HEAL</text><text class="cls-2" transform="translate(28.38 972.66)">INITI<tspan class="cls-3" x="508.63" y="0">A</tspan><tspan x="654.47" y="0">TIVE</tspan></text><text class="cls-2" transform="translate(28.33 374.76)">NIH</text></svg>
</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-12">
<p class="footText mb-2" id="nih">NIH HEAL Initiative and Helping to End Addiction Long-term are service marks of the U.S. Department of Health and Human Services.</p>
</div>
<div class="col-xs-12 mb-2 mb-md-0">
<p class="footText">
<a href="/heal-public/privacy.html">Privacy Policy</a>
</p>
<p class="footText">
<a href="/heal-public/terms.html">Terms of Use</a>
</p>
<p class="footText">
<a href="/heal-public/accessibility.html">Accessibility</a>
</p>
</div>
</div>
</div><!-- end col -->
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 px-2 px-lg-4">
<div class="row">
<div class="col-xs-12 col-md-12 col-lg-12 text-sm-left">
<a href="/heal-public/index.html">
<p class="bold lg mb-2">Home</p>
</a>
</div><!-- end col -->
<div class="col-xs-12 col-md-12 col-lg-12 text-sm-left">
<p class="bold lg footOrng mb-1">Find Local Resources</p>
</div><!-- end col -->
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/kentucky.html"><p class="bold footNav med">Kentucky</p></a>
<p class="footText"><a href="/heal-public/communities/kyboyd.html">Boyd</a></p>
<p class="footText"><a href="/heal-public/communities/kyboyle.html">Boyle</a></p>
<p class="footText"><a href="/heal-public/communities/kyclark.html">Clark</a></p>
<p class="footText"><a href="/heal-public/communities/kyfayette.html">Fayette</a></p>
<p class="footText"><a href="/heal-public/communities/kyfloyd.html">Floyd</a></p>
<p class="footText"><a href="/heal-public/communities/kyfranklin.html">Franklin</a></p>
<p class="footText"><a href="/heal-public/communities/kykenton.html">Kenton</a></p>
<p class="footText"><a href="/heal-public/communities/kymadison.html">Madison</a></p>
</div><!-- end col -->
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/massachusetts.html"><p class="bold footNav med">Massachusetts</p></a>
<p class="footText"><a href="/heal-public/communities/mabourne-and-sandwich.html">Bourne & Sandwich</a></p>
<p class="footText"><a href="/heal-public/communities/mabrockton.html">Brockton</a></p>
<p class="footText"><a href="/heal-public/communities/magloucester.html">Gloucester</a></p>
<p class="footText"><a href="/heal-public/communities/maholyoke.html">Holyoke</a></p>
<p class="footText"><a href="/heal-public/communities/malowell.html">Lowell</a></p>
<p class="footText"><a href="/heal-public/communities/maplymouth.html">Plymouth</a></p>
<p class="footText"><a href="/heal-public/communities/masalem.html">Salem</a></p>
<p class="footText"><a href="/heal-public/communities/mashirley-and-townsend.html">Shirley & Townsend</a></p>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/new_york.html"><p class="bold footNav med">New York</p></a>
</p>
<p class="footText"><a href="/heal-public/communities/nycayuga.html">Cayuga</a></p>
<p class="footText"><a href="/heal-public/communities/nycolumbia.html">Columbia</a></p>
<p class="footText"><a href="/heal-public/communities/nyerie.html">Erie (Buffalo)</a></p>
<p class="footText"><a href="/heal-public/communities/nygreene.html">Greene</a></p>
<p class="footText"><a href="/heal-public/communities/nylewis.html">Lewis</a></p>
<p class="footText"><a href="/heal-public/communities/nyputnam.html">Putnam</a></p>
<p class="footText"><a href="/heal-public/communities/nysuffolk.html">Suffolk (Brookhaven)</a></p>
<p class="footText"><a href="/heal-public/communities/nyulster.html">Ulster</a></p>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/ohio.html"><p class="bold footNav med">Ohio</p></a>
<p class="footText"><a href="/heal-public/communities/ohashtabula.html">Ashtabula County</a></p>
<p class="footText"><a href="/heal-public/communities/ohathens.html">Athens County</a></p>
<p class="footText"><a href="/heal-public/communities/ohcuyahoga.html">Cuyahoga County</a></p>
<p class="footText"><a href="/heal-public/communities/ohdarke.html">Darke County</a></p>
<p class="footText"><a href="/heal-public/communities/ohgreene.html">Greene County</a></p>
<p class="footText"><a href="/heal-public/communities/ohguernsey.html">Guernsey County</a></p>
<p class="footText"><a href="/heal-public/communities/ohhamilton.html">Hamilton County</a></p>
<p class="footText"><a href="/heal-public/communities/ohlucas.html">Lucas County</a></p>
<p class="footText"><a href="/heal-public/communities/ohscioto.html">Scioto County</a></p>
</div>
</div><!-- end row -->
</div>
<div class="col-xs-12 col-sm-12 col-md-2 col-lg-2 px-2 px-lg-0 pad">
<div class="row">
<div class="col-xs-12 mt-2 mb-1 mt-md-0"><p class="bold footOrng lg">About Opioid Use Disorder</p></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/oud-addiction.html"><p class="bold med">Opioid Use Disorder & Addiction</p></a></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/moud.html"><p class="bold med">Medications for Opioid Use Disorder</p></a></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/naloxone.html"><p class="bold med">Naloxone</p></a></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/stigma.html"><p class="bold med">Stigma</p></a></div>
<div class="col-xs-12 mt-3"><a href="/heal-public/take-action.html"><p class="bold lg">Take Action</p></a></div>
</div>
</div>
</div><!-- end row -->
</div><!-- end container -->
</div><!-- end container-fluid -->
<script src="/heal-public/assets/js/jquery.min.js" type="text/javascript"></script>
<script src="/heal-public/assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="/heal-public/assets/js/custom.js" type="text/javascript"></script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en-US">
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-153394354-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-153394354-1');
// gtag('event', 'Outbound URL');
</script>
<!-- END GA Code-->
<!--tracker-->
<script>
/**
* Function that captures a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var captureOutboundLink = function(url){
gtag('event', 'click', {
'event_category' : 'outbound',
'event_label' : url,
'transport_type' : 'beacon'
// 'event_callback': function(){document.location = url;}
})
}
</script>
<!--link tracker-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Naloxone | HEALing Communities Study</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/7813ede11b.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/heal-public/assets/css/main.css">
<link rel="stylesheet" href="/heal-public/assets/css/about.css">
</head>
<body>
<nav class="navbar navbar-default" id="nav">
<div class="container-fluid bg-gradient">
<div class="navbar-header" id="brandHeader">
<a class="navbar-brand navbar-left" href="/heal-public/index.html">
<img src="/heal-public/assets/images/HEAL-header.jpg" alt="" id="headImg">
</a>
</div>
<div class="navbar-header" id="ham">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse navbar-right" id="navbar-collapse">
<ul class="nav navbar-nav">
<li class="">
<a href="/heal-public/index.html">
<span class="fa fa-home"></span>
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Find Local Resources <span class="caret"></span></a>
<ul class="dropdown-menu" id="local">
<!-- <li><a href="/heal-public/find-local-resources.html">Find Local Resources</a></li> -->
<li class="dropdown-submenu">
<a href="#" class="dropdown-submenu-toggle">Kentucky <span class="caret"></span></a>
<ul class="dropdown-menu second">
<li class="first"><a href="/heal-public/sites/kentucky.html">Kentucky</a></li>
<li class="subNav"><a href="/heal-public/communities/kyboyd.html">Boyd</a></li>
<li class="subNav"><a href="/heal-public/communities/kyboyle.html">Boyle</a></li>
<li class="subNav"><a href="/heal-public/communities/kyclark.html">Clark</a></li>
<li class="subNav"><a href="/heal-public/communities/kyfayette.html">Fayette</a></li>
<li class="subNav"><a href="/heal-public/communities/kyfloyd.html">Floyd</a></li>
<li class="subNav"><a href="/heal-public/communities/kyfranklin.html">Franklin</a></li>
<li class="subNav"><a href="/heal-public/communities/kykenton.html">Kenton</a></li>
<li class="subNav"><a href="/heal-public/communities/kymadison.html">Madison</a></li>
</ul>
</li> <!--end kentucky-->
<li class="dropdown-submenu">
<a class="dropdown-submenu-toggle" href="#">Massachusetts <span class="caret"></span></a>
<ul class="dropdown-menu second">
<li class="first"><a href="/heal-public/sites/massachusetts.html">Massachusetts</a></li>
<li class="subNav"><a href="/heal-public/communities/mabourne-and-sandwich.html">Bourne & Sandwich</a></li>
<li class="subNav"><a href="/heal-public/communities/mabrockton.html">Brockton</a></li>
<li class="subNav"><a href="/heal-public/communities/magloucester.html">Gloucester</a></li>
<li class="subNav"><a href="/heal-public/communities/maholyoke.html">Holyoke</a></li>
<li class="subNav"><a href="/heal-public/communities/malowell.html">Lowell</a></li>
<li class="subNav"><a href="/heal-public/communities/maplymouth.html">Plymouth</a></li>
<li class="subNav"><a href="/heal-public/communities/masalem.html">Salem</a></li>
<li class="subNav"><a href="/heal-public/communities/mashirley-and-townsend.html">Shirley & Townsend</a></li>
</ul>
</li> <!---end massachusetts-->
<li class="dropdown-submenu">
<a class="dropdown-submenu-toggle" href="#">New York <span class="caret"></span></a>
<ul class="dropdown-menu second">
<li class="first"><a href="/heal-public/sites/new_york.html">New York</a></li>
<li class="subNav"><a href="/heal-public/communities/nycayuga.html">Cayuga</a></li>
<li class="subNav"><a href="/heal-public/communities/nycolumbia.html">Columbia</a></li>
<li class="subNav"><a href="/heal-public/communities/nyerie.html">Erie (Buffalo)</a></li>
<li class="subNav"><a href="/heal-public/communities/nygreene.html">Greene</a></li>
<li class="subNav"><a href="/heal-public/communities/nylewis.html">Lewis</a></li>
<li class="subNav"><a href="/heal-public/communities/nyputnam.html">Putnam</a></li>
<li class="subNav"><a href="/heal-public/communities/nysuffolk.html">Suffolk (Brookhaven)</a></li>
<li class="subNav"><a href="/heal-public/communities/nyulster.html">Ulster</a></li>
</ul>
</li> <!--end new york -->
<li class="dropdown-submenu">
<a class="dropdown-submenu-toggle" href="#ohio">Ohio <span class="caret"></span></a>
<ul class="dropdown-menu second" id="ohio">
<li class="first"><a href="/heal-public/sites/ohio.html">Ohio</a></li>
<li class="subNav"><a href="/heal-public/communities/ohashtabula.html">Ashtabula County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohathens.html">Athens County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohcuyahoga.html">Cuyahoga County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohdarke.html">Darke County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohgreene.html">Greene County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohguernsey.html">Guernsey County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohhamilton.html">Hamilton County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohlucas.html">Lucas County</a></li>
<li class="subNav"><a href="/heal-public/communities/ohscioto.html">Scioto County</a></li>
</ul>
</li> <!--end ohio -->
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">About Opioid Use Disorder <span class="caret"></span></a>
<ul class="dropdown-menu" id="about">
<li><a href="/heal-public/about-oud/oud-addiction.html">Opioid Use Disorder & Addiction</a></li>
<li><a href="/heal-public/about-oud/moud.html">Medications for Opioid Use Disorder</a></li>
<li><a href="/heal-public/about-oud/naloxone.html">Naloxone</a></li>
<li><a href="/heal-public/about-oud/stigma.html">Stigma</a></li>
</ul>
</li>
<li class="">
<a href="/heal-public/take-action.html">
Take Action
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="jumbotron abJumbo">
<div class="container-fluid">
<!-- <img src="/heal-public/assets/images/purple.jpg" alt="" class="abImg"> -->
<span class="abBannerH1 text-sm-center"><h1 class="white">Naloxone</h1></span>
</div>
</div>
<div class="container-fluid bg-magenta topGrad">
</div>
<div class="container-fluid" id="about-content">
<div class="container">
<h1 class="purple mt-0 mb-2 text-sm-left" id="ab-small-title">Naloxone</h1>
<div class="row lang-btn">
<div class="col-sm-12 px-2 px-lg-1">
<a href="/heal-public/assets/docs/naloxone-spanish.pdf" target="_blank"><button class="btn bg-red white w-50 w-md-50 w-lg-25 mb-2">En Español</button></a>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-3 px-2 px-lg-1">
<h2 class="coral mt-0 mb-2 text-sm-left">
Carry naloxone (Narcan<sup>®</sup>). Help save a life.
</h2>
</div>
<div class="col-sm-12 col-md-9 px-2 px-lg-1 mb-lg-1">
<p class=" mb-1">Naloxone (also known as NARCAN<sup style="font-weight:600;">®</sup> Nasal Spray) is a medicine that can save someone’s life if they are overdosing on opioids—whether it’s a prescription opioid, heroin, or a drug containing fentanyl.</p>
<button class="red bold mx-2 read-more readMoreTrans" id="read-comm" data-name="comm">Read More</button>
<div class="cs-word-hidden mb-2" id="hide-comm">
<p class=" mb-1">Naloxone quickly blocks and reverses the effects of an overdose. You can tell it is working because it quickly helps a person breathe normally. It is not a treatment for opioid addiction.</p>
<p class="">Signs of an opioid overdose include:</p>
<ul>
<li class="mb-1">Being unconscious</li>
<li class="mb-1">Very slow or shallow breathing</li>
<li class="mb-1">Limp body</li>
<li class="mb-2">Not responding when called, touched, or shaken</li>
</ul>
<p class=" mb-1">Carry naloxone with you every day. You can be a first responder. You can save a life.</p>
<button class="red bold mx-2 px-0 read-less" id="read-comm-less" data-name="comm">Read Less...</button>
</div>
<p style="margin-block-start: 0.5rem !important;">Click each of the questions below to learn more about naloxone. </p>
</div>
</div>
<div class="row">
<div class="col-12 col-lg-10 col-lg-offset-1">
<div class="row mb-5">
<div class="panel-group mx-2 mt-2" id="naloxone-acc" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="button" data-toggle="collapse" href="#nalOne" aria-expanded="true" aria-controls="nalOne" id="nalheadOne">
<h3 class="panel-title d-flex accHead purple">
<a>Where can I get naloxone?</a>
<i class="fas fa-chevron-circle-up purple accChevron"></i>
</h3>
</div>
<div id="nalOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="nalheadOne">
<div class="panel-body py-2">
<p class="px-md-2">
It is available in many pharmacies with or without a personal prescription. <a href="/heal-public/find-local-resources.html">Find locations in your community</a> by using the maps on our community pages.</p>
<p class="px-md-2">Each community currently involved in the HEALing Communities Study has a map with local resources, including pharmacies and other locations that provide naloxone. </p>
<p class="px-md-2"><span class="bold dk-gray">Don’t see your community on our website?</span> Use the resources below to find naloxone in your state.</p>
<ul>
<li class="mb-1"><span class="bold dk-gray">Kentucky:</span> Use the map from <a href="https://odcp.ky.gov/Stop-Overdoses/Pages/Locations.aspx" target=_blank">Stop Overdoses</a> to find locations in Kentucky.</li>
<li class="mb-1"><span class="bold dk-gray">Massachusetts:</span> Learn <a href="https://www.mass.gov/service-details/how-to-get-naloxone" target=_blank">how to get naloxone</a> in Massachusetts.</li>
<li class="mb-1"><span class="bold dk-gray">New York:</span> All pharmacies in the state can provide naloxone. For a complete list and additional information about overdose trainings, visit <a href="https://www.health.ny.gov/diseases/aids/general/opioid_overdose_prevention/docs/pharmacy_directory.pdf" target=_blank">NY State Department of Health: Directory of Pharmacies Dispensing Naloxone with Standing Orders</a>.</li>
<li class="mb-1"><span class="bold dk-gray">Ohio:</span> Naloxone is available throughout the state. Check the <a href="https://odh.ohio.gov/wps/portal/gov/odh/know-our-programs/violence-injury-prevention-program/resources/list-project-dawn-sites" target="_blank">website of Project DAWN</a> – Deaths Avoided With Naloxone – to find naloxone in your county or through mail order.</li>
</ul>
<p class="px-md-2"><span class="bold dk-gray">Can’t find a location near you that has naloxone?</span> You might be able to order it through the mail from <a href="" target="_blank">NEXT Naloxone</a> (not available in MA).</p>
</div>
</div>
</div> <!--end panel-->
<div class="panel panel-default">
<div class="panel-heading" role="button" data-toggle="collapse" href="#nalTwo" aria-expanded="false" aria-controls="nalTwo" id="nalheadTwo">
<h3 class="panel-title d-flex accHead purple">
<a>Why should I carry naloxone?</a>
<i class="fas fa-chevron-circle-down purple accChevron"></i>
</h3>
</div>
<div id="nalTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="nalheadTwo">
<div class="panel-body py-2">
<p class="px-md-2"><span class="bold dk-gray">If you or a loved one struggle with opioid use, you should have naloxone nearby.</span> Ask your family and friends to carry it and let them know where your naloxone is, in case they need to use it.</p>
<p class="px-md-2">People who previously used opioids and have stopped are at higher risk for an overdose. This includes people who have completed a detox program or have recently been released from jail, a residential treatment center, or the hospital. These people now have a lower tolerance for opioids and can overdose more easily.</p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="button" data-toggle="collapse" href="#nalThree" aria-expanded="false" aria-controls="nalThree" id="nalheadThree">
<h3 class="panel-title d-flex accHead purple">
<a>Who can use naloxone?</a>
<i class="fas fa-chevron-circle-down purple accChevron"></i>
</h3>
</div>
<div id="nalThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="nalheadThree">
<div class="panel-body py-2">
<p class="px-md-2 ">Anyone—including you—can give naloxone to someone who is overdosing from a prescription opioid medicine, heroin, or a drug containing fentanyl. NARCAN<sup style="font-weight:600;">®</sup> Nasal Spray is a ready-to-use, needle-free medicine that can be used without any special training. It requires no assembly and is sprayed into one nostril while the person lies on their back. The spray bottle (atomizer) is small and can fit in your pocket, purse, or glove compartment. <span class="bold dk-gray">Carry two spray bottles in case a second dose is needed.</span></p>
<p class="px-md-2 ">Carrying naloxone does not mean that you are encouraging people to misuse opioids or other drugs. It just means that you are ready to save a life if they overdose.</p>
<p class="px-md-2 ">For more information on laws that protect people who prescribe, carry, and use naloxone, please visit the <a href="http://www.pdaps.org/datasets/laws-regulating-administration-of-naloxone-1501695139" target="_blank">Prescription Drug Abuse Policy System website</a>.</p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="button" data-toggle="collapse" href="#nalFour" aria-expanded="false" aria-controls="nalFour" id="nalheadFour">
<h3 class="panel-title d-flex accHead purple">
<a>How safe is naloxone?</a>
<i class="fas fa-chevron-circle-down purple accChevron"></i>
</h3>
</div>
<div id="nalFour" class="panel-collapse collapse" role="tabpanel" aria-labelledby="nalheadFour">
<div class="panel-body py-2">
<p class="px-md-2 ">Naloxone is very safe and saves lives. It can be given to anyone showing signs of an opioid overdose, even if you are not sure if they have used opioids. Naloxone is not addictive and cannot be used to get high.</p>
<p class="px-md-2 ">NARCAN<sup style="font-weight:600;">®</sup> Nasal Spray is an easy-to-use nasal spray packaged with two spray bottles (atomizers) in case a second dose is needed. A Quick Start guide in the box gives instructions and should be read in advance. People receiving naloxone kits that include a syringe and naloxone ampules or vials should receive a brief training on how to use it.</p>
<p class="px-md-2 ">Naloxone</p>
<ul>
<li class="mb-1">has been proven to be extremely safe, with no negative effects on the body if the person has not used opioids;</li>
<li class="mb-1">can also be used on pregnant women in overdose situations; and</li>
<li class="mb-1">does not cause any life-threatening side effects.</li>
</ul>
<p class="px-md-2 ">People with physical dependence on opioids may have signs of withdrawal within minutes after they are given naloxone, but this is normal and good because it means that the naloxone is helping the person to breathe again. Normal withdrawal symptoms can include headaches, changes in blood pressure, anxiety, rapid heart rate, sweating, nausea, vomiting, and tremors. These symptoms are not life threatening but can be uncomfortable.</p>
</div>
</div>
</div> <!--end panel-->
<div class="panel panel-default">
<div class="panel-heading" role="button" data-toggle="collapse" href="#nalFive" aria-expanded="false" aria-controls="nalFive" id="nalheadFive">
<h3 class="panel-title d-flex accHead purple">
<a>How do I administer naloxone?</a>
<i class="fas fa-chevron-circle-down purple accChevron"></i>
</h3>
</div>
<div id="nalFive" class="panel-collapse collapse" role="tabpanel" aria-labelledby="nalheadFive">
<div class="panel-body py-2">
<p class="px-md-2">To learn how to administer naloxone, check out the following resources: </p>
<ul>
<li class="mb-1">Take a training from <a href="https://getnaloxonenow.org/#gettraining" target="_blank">Get Naloxone Now</a>.</li>
<li class="mb-1">Download the Narcan Now app from the <a href="https://play.google.com/store/apps/details?id=com.adaptpharma.narcannow&hl=en_US" target="_blank">Google Play</a> or <a href="https://apps.apple.com/us/app/narcan-now/id1076163137" target="_blank">Apple store</a>.</li>
<li class="mb-1"><a href="https://www.narcan.com/patients/how-to-use-narcan/" target="_blank">Watch a naloxone training video.</a></li>
<li class="mb-1"><a href="https://www.health.ny.gov/publications/12028.pdf" target="_blank">Get step-by-step instructions for using naloxone nasal spray.</a></li>
<li class="mb-1"><a href="https://www.health.ny.gov/publications/9866.pdf" target="_blank">Learn how to respond and call for emergency services once naloxone is given.</a></li>
</ul>
</div>
</div>
</div> <!--end panel-->
<div class="panel panel-default">
<div class="panel-heading" role="button" data-toggle="collapse" href="#nalSix" aria-expanded="false" aria-controls="nalSix" id="nalheadSix">
<h3 class="panel-title d-flex accHead purple">
<a>How long before I know naloxone is working?</a>
<i class="fas fa-chevron-circle-down purple accChevron"></i>
</h3>
</div>
<div id="nalSix" class="panel-collapse collapse" role="tabpanel" aria-labelledby="nalheadSix">
<div class="panel-body py-2">
<p class="px-md-2">Naloxone begins working within minutes after it is given and should help the person wake up and breathe again. After administering naloxone, put the person in the recovery position, on their side with arms forward, and upper leg bent at the knee in front of the body, somewhat like a sleep position. Further instructions can be found in the box with the NARCAN<sup style="font-weight:600;">®</sup> Nasal Spray product, or online by searching for "recovery position."</p>
<ul>
<li class="mb-1">If the person does not respond to the first dose of naloxone within two to three minutes, a second dose should be given, after putting the person on their back again.
<ul><li><span class="dk-gray bold">Important:</span> If using NARCAN® Nasal Spray, a second dose requires a second spray bottle (atomizers).</li></ul></li>
<li class="mb-1">Naloxone works for 30 to 90 minutes, but because many opioids remain in the body longer than that, it is possible for a person to show signs of an overdose after naloxone wears off. Therefore, <span class="dk-gray bold">one of the most important steps is to call 911 so the person can receive medical attention</span> to monitor their breathing and treat these possible effects. Wait for emergency personnel to arrive and be sure to tell them about the products and doses you gave the patient. Be sure to throw away all used spray bottles and naloxone products.</li>
</ul>
</div>
</div>
</div> <!--end panel-->
</div> <!--end panel group-->
</div> <!--end row-->
</div>
</div>
</div>
</div>
<div class="container-fluid bg-gradient" style="max-height: 25px;">
</div>
<div class="container-fluid footer">
<div class="row text-sm-center" id="arrowRow">
<span class="fa-stack fa-2x mx-auto" id="upArrow" data-link="nav">
<i class="fas fa-circle coral fa-stack-2x"></i>
<i class="far fa-chevron-up fa-stack-1x"></i>
</span>
</div><!-- end row -->
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-2 col-lg-2 px-2 px-lg-0">
<div class="row special">
<div class="col-xs-12 col-sm-6 col-md-12">
<a href="https://heal.nih.gov/research/research-to-practice/healing-communities" target="external" onclick="captureOutboundLink('https://heal.nih.gov/research/research-to-practice/healing-communities');">
<svg id="footImg" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 100 1200 1000"><defs><style>.cls-1{font-size:408.82px;}.cls-1,.cls-2{fill:#fff;font-family:Montserrat-Bold, Montserrat;font-weight:700;}.cls-2{font-size:211.05px;}.cls-3{letter-spacing:-0.08em;}</style></defs><title>NIH HEAL Initiative Logo White</title><text class="cls-1" transform="translate(17 738.16)">HEAL</text><text class="cls-1" transform="translate(17 738.16)">HEAL</text><text class="cls-2" transform="translate(28.38 972.66)">INITI<tspan class="cls-3" x="508.63" y="0">A</tspan><tspan x="654.47" y="0">TIVE</tspan></text><text class="cls-2" transform="translate(28.33 374.76)">NIH</text></svg>
</a>
</div>
<div class="col-xs-12 col-sm-6 col-md-12">
<p class="footText mb-2" id="nih">NIH HEAL Initiative and Helping to End Addiction Long-term are service marks of the U.S. Department of Health and Human Services.</p>
</div>
<div class="col-xs-12 mb-2 mb-md-0">
<p class="footText">
<a href="/heal-public/privacy.html">Privacy Policy</a>
</p>
<p class="footText">
<a href="/heal-public/terms.html">Terms of Use</a>
</p>
<p class="footText">
<a href="/heal-public/accessibility.html">Accessibility</a>
</p>
</div>
</div>
</div><!-- end col -->
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 px-2 px-lg-4">
<div class="row">
<div class="col-xs-12 col-md-12 col-lg-12 text-sm-left">
<a href="/heal-public/index.html">
<p class="bold lg mb-2">Home</p>
</a>
</div><!-- end col -->
<div class="col-xs-12 col-md-12 col-lg-12 text-sm-left">
<p class="bold lg footOrng mb-1">Find Local Resources</p>
</div><!-- end col -->
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/kentucky.html"><p class="bold footNav med">Kentucky</p></a>
<p class="footText"><a href="/heal-public/communities/kyboyd.html">Boyd</a></p>
<p class="footText"><a href="/heal-public/communities/kyboyle.html">Boyle</a></p>
<p class="footText"><a href="/heal-public/communities/kyclark.html">Clark</a></p>
<p class="footText"><a href="/heal-public/communities/kyfayette.html">Fayette</a></p>
<p class="footText"><a href="/heal-public/communities/kyfloyd.html">Floyd</a></p>
<p class="footText"><a href="/heal-public/communities/kyfranklin.html">Franklin</a></p>
<p class="footText"><a href="/heal-public/communities/kykenton.html">Kenton</a></p>
<p class="footText"><a href="/heal-public/communities/kymadison.html">Madison</a></p>
</div><!-- end col -->
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/massachusetts.html"><p class="bold footNav med">Massachusetts</p></a>
<p class="footText"><a href="/heal-public/communities/mabourne-and-sandwich.html">Bourne & Sandwich</a></p>
<p class="footText"><a href="/heal-public/communities/mabrockton.html">Brockton</a></p>
<p class="footText"><a href="/heal-public/communities/magloucester.html">Gloucester</a></p>
<p class="footText"><a href="/heal-public/communities/maholyoke.html">Holyoke</a></p>
<p class="footText"><a href="/heal-public/communities/malowell.html">Lowell</a></p>
<p class="footText"><a href="/heal-public/communities/maplymouth.html">Plymouth</a></p>
<p class="footText"><a href="/heal-public/communities/masalem.html">Salem</a></p>
<p class="footText"><a href="/heal-public/communities/mashirley-and-townsend.html">Shirley & Townsend</a></p>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/new_york.html"><p class="bold footNav med">New York</p></a>
</p>
<p class="footText"><a href="/heal-public/communities/nycayuga.html">Cayuga</a></p>
<p class="footText"><a href="/heal-public/communities/nycolumbia.html">Columbia</a></p>
<p class="footText"><a href="/heal-public/communities/nyerie.html">Erie (Buffalo)</a></p>
<p class="footText"><a href="/heal-public/communities/nygreene.html">Greene</a></p>
<p class="footText"><a href="/heal-public/communities/nylewis.html">Lewis</a></p>
<p class="footText"><a href="/heal-public/communities/nyputnam.html">Putnam</a></p>
<p class="footText"><a href="/heal-public/communities/nysuffolk.html">Suffolk (Brookhaven)</a></p>
<p class="footText"><a href="/heal-public/communities/nyulster.html">Ulster</a></p>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 text-sm-left ">
<a href="/heal-public/sites/ohio.html"><p class="bold footNav med">Ohio</p></a>
<p class="footText"><a href="/heal-public/communities/ohashtabula.html">Ashtabula County</a></p>
<p class="footText"><a href="/heal-public/communities/ohathens.html">Athens County</a></p>
<p class="footText"><a href="/heal-public/communities/ohcuyahoga.html">Cuyahoga County</a></p>
<p class="footText"><a href="/heal-public/communities/ohdarke.html">Darke County</a></p>
<p class="footText"><a href="/heal-public/communities/ohgreene.html">Greene County</a></p>
<p class="footText"><a href="/heal-public/communities/ohguernsey.html">Guernsey County</a></p>
<p class="footText"><a href="/heal-public/communities/ohhamilton.html">Hamilton County</a></p>
<p class="footText"><a href="/heal-public/communities/ohlucas.html">Lucas County</a></p>
<p class="footText"><a href="/heal-public/communities/ohscioto.html">Scioto County</a></p>
</div>
</div><!-- end row -->
</div>
<div class="col-xs-12 col-sm-12 col-md-2 col-lg-2 px-2 px-lg-0 pad">
<div class="row">
<div class="col-xs-12 mt-2 mb-1 mt-md-0"><p class="bold footOrng lg">About Opioid Use Disorder</p></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/oud-addiction.html"><p class="bold med">Opioid Use Disorder & Addiction</p></a></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/moud.html"><p class="bold med">Medications for Opioid Use Disorder</p></a></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/naloxone.html"><p class="bold med">Naloxone</p></a></div>
<div class="col-xs-12"><a href="/heal-public/about-oud/stigma.html"><p class="bold med">Stigma</p></a></div>
<div class="col-xs-12 mt-3"><a href="/heal-public/take-action.html"><p class="bold lg">Take Action</p></a></div>
</div>
</div>
</div><!-- end row -->
</div><!-- end container -->
</div><!-- end container-fluid -->
<script src="/heal-public/assets/js/jquery.min.js" type="text/javascript"></script>
<script src="/heal-public/assets/js/bootstrap.min.js" type="text/javascript"></script>
<script src="/heal-public/assets/js/custom.js" type="text/javascript"></script>
</body>
</html>
|
196635e4b8e3a371126b6c48ec889da1f8cc6ef5
|
[
"JavaScript",
"HTML",
"Markdown"
] | 5
|
JavaScript
|
chelsg73/heal-public
|
fc283a9fa7084a5463e50b4b12f61a7542c185b8
|
24e65a054e1f91e6da6b16c4251c0d7186efb566
|
refs/heads/master
|
<file_sep>player1 = { x = 160, y = 710, w = 20, h = 20, speed = 150, angle = 0, active = true, dead = false, deadDur = 0, highlight = false, head = nil, shirt = nil, pants = nil, animation = { angle = 0, step = 0 }, exitAngle }
player2 = { x = -100, y = -100, w = 20, h = 20, speed = 200, angle = 0, timer = 0, attack = false, animation = { angle = 0, step = 0} }
player3 = { x = -100, y = -100, w = 20, h = 20, speed = 200, angle = 0, timer = 0, attack = false, animation = { angle = 0, step = 0} }
function spawnDot()
local spawnPoint = math.random(1, 11)
dot.x = dotSpawns[spawnPoint][1] - 25
dot.y = dotSpawns[spawnPoint][2] - 25
end
function attack(player)
local x = player.x - (player.w * 5)
local y = player.y - (player.h * 5)
local w = player.w * 10
local h = player.h * 10
local hit = false
for i = 1, numberOfNPCs, 1 do
if CheckCollision(x, y, w, h, npcs[i].x, npcs[i].y, npcs[i].w, npcs[i].h) then
killNPC(npcs[i])
hit = true
end
end
if CheckCollision(x, y, w, h, player1.x, player1.y, player1.w, player1.h) then
-- The swede was found by player
player1.dead = true
player1.deadDur = 8
love.audio.play(attackSound)
return true
end
if hit then
love.audio.play(attackSound)
else
love.audio.play(missSound)
end
end
function playerReset()
local spawnPoint = math.random(1, 5)
player1.x = npcSpawns[spawnPoint][1]
player1.y = npcSpawns[spawnPoint][2]
player1.head = headColors[math.random(1, 4)]
player1.shirt = shirtColors[math.random(1, 3)]
player1.pants = pantsColors[math.random(1, 3)]
player1.dead = false
player1.exitAngle = math.random() * 2 * math.pi
end
function highlightPlayer(dt)
highlight.time = highlight.time + dt
player1.active = false
if highlight.time > 2 then
player1.highlight = true
end
end
function moveUp(player, dt)
player.animation.step = player.animation.step + dt * 10
player.animation.angle = math.sin(player.animation.step) / 4
for i, box in ipairs(collision) do
if CheckCollision(box.x, box.y, box.w, box.h, player.x, player.y - (player.speed*dt), player.w, player.h) then
return
end
end
player.y = player.y - player.speed * dt
end
function moveRight(player, dt)
player.animation.step = player.animation.step + dt * 10
player.animation.angle = math.sin(player.animation.step) / 4
for i, box in ipairs(collision) do
if CheckCollision(box.x, box.y, box.w, box.h, player.x + (player.speed*dt), player.y, player.w, player.h) then
return
end
end
player.x = player.x + player.speed * dt
end
function moveDown(player, dt)
player.animation.step = player.animation.step + dt * 10
player.animation.angle = math.sin(player.animation.step) / 4
for i, box in ipairs(collision) do
if CheckCollision(box.x, box.y, box.w, box.h, player.x, player.y + (player.speed*dt), player.w, player.h) then
return
end
end
player.y = player.y + player.speed * dt
end
function moveLeft(player, dt)
player.animation.step = player.animation.step + dt * 10
player.animation.angle = math.sin(player.animation.step) / 4
for i, box in ipairs(collision) do
if CheckCollision(box.x, box.y, box.w, box.h, player.x - (player.speed*dt), player.y, player.w, player.h) then
return
end
end
player.x = player.x - player.speed * dt
end
-- Collision detection taken function from http://love2d.org/wiki/BoundingBox.lua
-- Returns true if two boxes overlap, false if they don't
-- x1,y1 are the left-top coords of the first box, while w1,h1 are its width and height
-- x2,y2,w2 & h2 are the same, but for the second box
function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
return x1 < x2+w2 and
x2 < x1+w1 and
y1 < y2+h2 and
y2 < y1+h1
end
function love.load(arg)
if arg[#arg] == "-debug" then require("mobdebug").start() end
love.mouse.setVisible(false) -- make default mouse invisible
-- NPC
require('palette')
math.randomseed(os.time())
npcs = {}
numberOfNPCs = 30
for i = 1, numberOfNPCs, 1 do
newNPC()
end
-- load ttf file font. set 20px font-size
scoreFont = love.graphics.newFont("assets/1942.ttf", 15);
timerFont = love.graphics.newFont("assets/1942.ttf", 30);
map = love.graphics.newImage("assets/bg.png")
folder = love.graphics.newImage("assets/folder.png")
head = love.graphics.newImage("assets/head.png")
shirt = love.graphics.newImage("assets/body.png")
pants = love.graphics.newImage("assets/legs.png")
russian = love.graphics.newImage("assets/ryss.png")
german = love.graphics.newImage("assets/tysk.png")
warnRussian = love.graphics.newImage("assets/warRus.png")
warnGerman = love.graphics.newImage("assets/warGer.png")
warnRusScore = love.graphics.newImage("assets/warRusScore.png")
warnGerScore = love.graphics.newImage("assets/warGerScore.png")
warnBoth = love.graphics.newImage("assets/warBoth.png")
warnHighlight = love.graphics.newImage("assets/warHL.png")
missionSuccess = love.graphics.newImage("assets/infoSweSuccess.png")
missionFailed = love.graphics.newImage("assets/warSweFail.png")
infoDot = love.graphics.newImage("assets/infoMission.png")
attackSound = love.audio.newSource("assets/attack.mp3")
hr1Sound = love.audio.newSource("assets/homerun1.mp3")
hr2Sound = love.audio.newSource("assets/homerun2.mp3")
missSound = love.audio.newSource("assets/miss.mp3")
plingSound = love.audio.newSource("assets/pling.mp3")
playerReset()
overlay = { timer = 0, show = false, sprite = infoDot }
highlight = { time = 0 }
score = { p1 = 0, p2 = 0, p3 = 0 }
dot = { x, y, w = 50, h = 50, timer = 0, success = false, gotScore = false }
dotCountdown = overlay.timer
spawnTimer = 0
local joysticks = love.joystick.getJoysticks()
joystick = joysticks[1]
collision = {
{x = 0, y = 0, w = 1366, h = 14},
{x = 0, y = 0, w = 14, h = 768},
{x = 1352, y = 0, w = 14, h = 768},
{x = 0, y = 754, w = 1366, h = 14},
{x = 0, y = 96, w = 103, h = 81},
{x = 184, y = 96, w = 185, h = 81},
{x = 449, y = 96, w = 84, h = 81},
{x = 964, y = 96, w = 104, h = 81},
{x = 1150, y = 96, w = 216, h = 81},
{x = 0, y = 258, w = 103, h = 511},
{x = 184, y = 258, w = 185, h = 81},
{x = 450, y = 258, w = 83, h = 81},
{x = 614, y = 258, w = 84, h = 81},
{x = 778, y = 258, w = 105, h = 307},
{x = 964, y = 258, w = 105, h = 307},
{x = 1150, y = 258, w = 215, h = 307},
{x = 184, y = 420, w = 185, h = 145},
{x = 183, y = 645, w = 185, h = 123},
{x = 450, y = 645, w = 248, h = 123},
{x = 779, y = 645, w = 290, h = 123},
{x = 1150, y = 645, w = 215, h = 123}
}
--love.window.setFullscreen(true, "desktop")
spawnDot()
end
function love.update(dt)
-- Handle joystick movement
if not joystick then
love.graphics.print("No joystick detected")
else
love.graphics.print("Joystick detected")
end
if joystick and player1.active and player1.dead == false then
if joystick:isDown(5) then
moveUp(player1, dt)
elseif joystick:isDown(6) then
moveRight(player1, dt)
elseif joystick:isDown(7) then
moveDown(player1, dt)
elseif joystick:isDown(8) then
moveLeft(player1, dt)
else
player1.animation.angle = 0
end
end
if love.keyboard.isDown('w') then
moveUp(player2, dt)
elseif love.keyboard.isDown('d') then
moveRight(player2, dt)
elseif love.keyboard.isDown('s') then
moveDown(player2, dt)
elseif love.keyboard.isDown('a') then
moveLeft(player2, dt)
else
player2.animation.angle = 0
end
if love.keyboard.isDown('lalt') and player2.timer > 0 and player2.attack == false then
player2.attack = true
player2.timer = 3
love.audio.play(attackSound)
if attack(player2) then
score.p2 = score.p2 + 10
overlay.show = true
overlay.sprite = warnGerScore
overlay.timer = 2
love.audio.play(hr1Sound)
love.audio.play(hr2Sound)
end
end
if love.keyboard.isDown('ralt') and player3.timer > 0 and player3.attack == false then
player3.attack = true
player3.timer = 3
if attack(player3) then
score.p3 = score.p3 + 10
overlay.show = true
overlay.sprite = warnRusScore
overlay.timer = 2
love.audio.play(hr1Sound)
love.audio.play(hr2Sound)
end
end
if love.keyboard.isDown('up') then
moveUp(player3, dt)
elseif love.keyboard.isDown('right') then
moveRight(player3, dt)
elseif love.keyboard.isDown('down') then
moveDown(player3, dt)
elseif love.keyboard.isDown('left') then
moveLeft(player3, dt)
else
player3.animation.angle = 0
end
for i = 1, numberOfNPCs, 1 do
updateNPC(npcs[i], dt)
end
if joystick and joystick:isDown(13) then
highlightPlayer(dt)
pling = true
else
if pling then
love.audio.play(plingSound)
end
pling = false
highlight.time = 0
player1.active = true
player1.highlight = false
end
overlay.timer = overlay.timer - dt
spawnTimer = spawnTimer + dt
if spawnTimer > 10 then
-- Slumpa om det blir ryss/tysk eller bada
choice = math.random(1, 3)
if choice == 1 and player2.timer <= 0 then
player2.x = 30
player2.y = 50
player2.timer = 1000
player2.attack = false
overlay.sprite = warnGerman
overlay.show = true
overlay.timer = 2
elseif choice == 2 and player3.timer <= 0 then
player3.x = 1300
player3.y = 210
player3.timer = 1000
player3.attack = false
overlay.sprite = warnRussian
overlay.show = true
overlay.timer = 2
elseif choice == 3 and player2.timer <= 0 and player3.timer <= 0 then
player2.x = 30
player2.y = 50
player3.x = 1300
player3.y = 210
player2.attack = false
player3.attack = false
player2.timer = 1000
player3.timer = 1000
overlay.sprite = warnBoth
overlay.show = true
overlay.timer = 2
end
spawnTimer = 0
end
if player2.timer < 0 then
player2.x = -100
player2.y = -100
else
player2.timer = player2.timer - dt
end
if player3.timer < 0 then
player3.x = -100
player3.y = -100
else
player3.timer = player3.timer - dt
end
if dot.timer > 0 then
dot.timer = dot.timer - dt
if CheckCollision(dot.x, dot.y, dot.w, dot.h, player1.x, player1.y, player1.w, player1.h) then
dot.success = true
end
end
if dot.success == false and dot.timer < 0 then
score.p1 = score.p1 - 1
overlay.show = true
overlay.timer = 2
overlay.sprite = missionFailed
end
if dotCountdown > 0 then
dotCountdown = dotCountdown - dt
elseif dot.timer <= 0 then
dot.timer = math.random(10, 20)
overlay.show = true
overlay.timer = 2
if dot.success then
score.p1 = score.p1 + 2
overlay.sprite = missionSuccess
dot.success = false
end
dotCountdown = 2
spawnDot()
end
if player1.dead and player1.deadDur < 0 then
playerReset()
end
-- Player death animation
if player1.dead then
player1.deadDur = player1.deadDur - dt
player1.x = player1.x + dt * 500 * math.cos(player1.exitAngle)
player1.y = player1.y + dt * 500 * math.sin(player1.exitAngle)
player1.animation.step = player1.animation.step + dt * 10
player1.animation.angle = player1.animation.step * 10
end
-- I always start with an easy way to exit the game
if love.keyboard.isDown('escape') or
joystick and joystick:isDown(4) then
love.event.push('quit')
end
if love.keyboard.isDown(" ") then
love.window.setFullscreen(false, "desktop")
end
end
function love.draw()
love.graphics.draw(map)
for i = 1, numberOfNPCs, 1 do
drawNPC(npcs[i])
end
if dot.timer > 0 then
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(folder, dot.x + 10, dot.y + 15)
end
love.graphics.setColor(player1.shirt)
love.graphics.draw(shirt, player1.x + 10, player1.y + 10, player1.animation.angle, 1, 1, 10, 10)
love.graphics.setColor(player1.pants)
love.graphics.draw(pants, player1.x + 10, player1.y + 10, player1.animation.angle, 1, 1, 10, 0)
love.graphics.setColor(player1.head)
love.graphics.draw(head, player1.x + 10, player1.y + 10, player1.animation.angle, 1, 1, 7, 19)
love.graphics.setColor(255,255,255,255)
love.graphics.draw(german, player2.x + 10, player2.y + 10, player2.animation.angle, 1, 1, 20, 50)
love.graphics.draw(russian, player3.x + 10, player3.y + 10, player3.animation.angle, 1, 1, 20, 50)
if overlay.show and overlay.timer > 0 then
love.graphics.setColor(255, 255, 255, 220)
love.graphics.draw(overlay.sprite, 246, 522)
end
if player1.active == false then
love.graphics.setColor(255, 255, 255, 220)
love.graphics.draw(warnHighlight, 246, 522)
end
if player1.highlight then
love.graphics.setColor(255, 0, 0, 180)
love.graphics.circle("fill", player1.x + 10, player1.y + 10, 30)
end
-- Show some score
love.graphics.setFont(scoreFont);
love.graphics.setColor(0, 0, 0, 255)
love.graphics.print(""..score.p1, 1320, 325)
love.graphics.print(""..score.p2, 1320, 345)
love.graphics.print(""..score.p3, 1320, 365)
-- set font before draw text
love.graphics.setFont(timerFont);
love.graphics.setColor(255, 85, 85, 255)
love.graphics.print(""..math.floor(dot.timer), 1290, 450)
-- Helper when placing objects
local x, y = love.mouse.getPosition() -- get the position of the mouse
--love.graphics.print(""..x..", "..y, 10, 10)
love.graphics.setColor(255, 255, 255, 255)
end
function love.quit()
print("Thanks for playing! Come back soon!")
end
function newNPC()
local npc = {}
local spawnPoint = math.random(1, 5);
npc.x = npcSpawns[spawnPoint][1]
npc.y = npcSpawns[spawnPoint][2]
npc.w = 20
npc.h = 20
npc.speed = 150
npc.exitAngle = math.random()*2*math.pi
npc.action = {}
npc.action.duration = 0
npc.action.type = "stop"
npc.outfit = {}
npc.outfit.headColor = headColors[math.random(1, 4)]
npc.outfit.shirtColor = shirtColors[math.random(1, 3)]
npc.outfit.pantsColor = pantsColors[math.random(1, 3)]
npc.animation = {}
npc.animation.angle = 0
npc.animation.step = 0
table.insert(npcs, npc)
end
function updateNPC(npc, dt)
npc.action.duration = npc.action.duration - dt
--NEW ACTION
if(npc.action.duration <= 0) then
if(npc.action.type == "dead") then
local spawnPoint = math.random(1, 5);
npc.x = npcSpawns[spawnPoint][1]
npc.y = npcSpawns[spawnPoint][2]
end
local newAction = math.random(1, 5)
if(newAction == 1) then
npc.action.type = "up"
elseif(newAction == 2) then
npc.action.type = "right"
elseif(newAction == 3) then
npc.action.type = "down"
elseif(newAction == 4) then
npc.action.type = "left"
else
npc.action.type = "stop"
end
local newDuration = math.random(1, 2)
npc.action.duration = newDuration
end
--DO ACTION
if(npc.action.type == "up") then
moveUp(npc, dt)
elseif(npc.action.type == "right") then
moveRight(npc, dt)
elseif(npc.action.type == "down") then
moveDown(npc, dt)
elseif(npc.action.type == "left") then
moveLeft(npc, dt)
elseif(npc.action.type == "dead") then
npc.x = npc.x + dt * 500 * math.cos(npc.exitAngle)
npc.y = npc.y + dt * 500 * math.sin(npc.exitAngle)
else
npc.x = npc.x
npc.y = npc.y
end
--UPDATE ANIMATION
if(npc.action.type ~= "stop" and npc.action.type ~= "dead") then
--npc.animation.step = npc.animation.step + dt * 10
--npc.animation.angle = math.sin(npc.animation.step) / 4
elseif(npc.action.type == "dead") then
npc.animation.step = npc.animation.step + dt * 10
npc.animation.angle = npc.animation.step * 10
else
npc.animation.angle = 0
end
end
function drawNPC(npc)
love.graphics.setColor(npc.outfit.pantsColor)
love.graphics.draw(pants, npc.x + 10, npc.y + 10, npc.animation.angle, 1, 1, 10, 0)
love.graphics.setColor(npc.outfit.shirtColor)
love.graphics.draw(shirt, npc.x + 10, npc.y + 10, npc.animation.angle, 1, 1, 10, 10)
love.graphics.setColor(npc.outfit.headColor)
love.graphics.draw(head, npc.x + 10, npc.y + 10, npc.animation.angle, 1, 1, 7, 19)
end
function killNPC(npc)
npc.action.type = "dead"
npc.action.duration = 15
end<file_sep># En Svensk Tiger säger...
 - Fixa en liten logga med tigerhuvudet... och handen
ESTS is a multiplayer game that takes place in a Swedish city during World War II.
Three players take control of a Swedish spy, a German and a Russian soldier.
The task of the spy is to stay hidden in the crowds while he has to
collect secret documents.
The mission of the soldiers is to find the spy among the civilians before the second soldier does
as well as preventing the spy from collecting the secret documents.
This 2D game was made by [<NAME>](https://github.com/happystinson) and [<NAME>](https://github.com/mcassel) during the [BOSS Jam 2015](https://boss.bthstudent.se/bossjam/boss-jam-2015/).
## Interpretation of the theme
**Theme**: En svensk tiger (a Swedish tiger)
We chose to focus on the use of "a Swedish tiger" as propaganda during World War II
to prevent secret information from ending in foreign spies' hands.
The game includes a blue and yellow tiger who gives feedback to the players.
## Controls
- `Esc` to quit the game
- `Space` to exit fullscreen mode
### Player 1 (The Swedish Spy)
- `Left joystick` to move the character (or is it the directional pad? (buttons 5-8))
- Hold `Joystick button 13` to highlight the spy
- `Joystick button 4` to quit the game
### Player 2 (The German Soldier)

- `W` to move up
- `A` to move left
- `S` to move down
- `D` to move right
- `Left alt` to use bat
### Player 3 (The Russian Soldier)

- `Up` to move up
- `Left` to move left
- `Down` to move down
- `Right` to move right
- `Right alt` to use bat
## Gameplay
[](https://youtu.be/Z9a-X7awcNE)

## Requirements
### LÖVE 0.9.2
The game requires LÖVE version 0.9.2 which is found at their [downloads page](https://bitbucket.org/rude/love/downloads/).
Pick either the executable or compressed archive for your desired platform.
### Joystick or Controller
The game won't start if there's no joystick/controller present.
## Credits
- Collision detection used is [BoundingBox](https://love2d.org/wiki/BoundingBox.lua) from LÖVE wiki
- Font used is [1942 Report](https://www.fontsquirrel.com/fonts/1942-report) by <NAME> and found at [Font Squirrel](https://www.fontsquirrel.com/)<file_sep>-- Configuration
function love.conf(t)
t.version = "0.9.2" -- The LÖVE version this game was made for (string)
t.window.title = "En svensk tiger säger... Game by Mike & Happy for BOSS Jam 2015" -- The title of the window the game is in (string)
t.window.width = 1366
t.window.height = 768
t.window.fsaa = 16
t.modules.math = false
t.modules.physics = false
t.modules.system = false
t.modules.thread = false
end
|
178a0c2e6fba96abc18c940de26fec91f03793d2
|
[
"Markdown",
"Lua"
] | 3
|
Lua
|
HappyStinson/en-svensk-tiger
|
e653f8839774dbc34a584598e03b7299dc6edfae
|
10cad6f67cedc0d8d6b8f9aac1f8bf61240dc173
|
refs/heads/master
|
<file_sep>class NumberParser {
/**
* Our "production" code to be tested.
* @param {string} numbers
* @returns {number}
*/
sum(numbers) {
let [a, b] = numbers.split(",");
let result = Number.parseInt(a) + Number.parseInt(b);
return result;
}
}
/*
I'm using the module.exports for comparability with Node syntax for modules.
This way we won't have to use any transpiler to run this code.
*/
module.exports = NumberParser;
|
77780dca138154c8a0589369589dec9aa219b65e
|
[
"JavaScript"
] | 1
|
JavaScript
|
elisherer/aout3-samples
|
c4a15decc5f8b0727e61dab628eb901116b4ad70
|
4c1747f91ea38085e676bf1dafda968ab51114f0
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Headers
#
create_group('headers', 'Заголовки')
class HeaderWidget(Widget):
header = models.CharField("Текст заголовка", max_length=255, blank=True, default="Заголовок")
class Meta:
abstract = True
@add2group('H1', 'headers')
class H1(HeaderWidget):
pass
@add2group('H2', 'headers')
class H2(HeaderWidget):
pass
@add2group('H3', 'headers')
class H3(HeaderWidget):
pass
<file_sep>{% extends "layout.html" %}
{% block site %}
<header>
Вход в систему
</header>
<div class="padded">
{% if form.errors %}
<p>Такого пользователя не существует или введен неверный пароль. Пожалуйста, попробуйте еще раз.</p>
{% endif %}
<form method="post" action="/login/">
{% csrf_token %}
<table style="font-size: 120%; margin-bottom: 10px;">
<tr>
<td>Имя пользователя:</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>Пароль:</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="Войти" style="font-size: 120%;" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
</div>
{% endblock %}<file_sep># -*- coding: utf-8 -*-
from django.db import models
class Domain(models.Model):
name = models.CharField("Доменное имя (без www)", max_length=255)
site = models.ForeignKey("Site", verbose_name='Сайт')
def __unicode__(self):
return self.name + ' (' + self.site.name + ')'
class Meta:
verbose_name = 'Домен'
verbose_name_plural = 'Домены'
class Site(models.Model):
name = models.CharField("Название", max_length=255)
def save(self, *args, **kwargs):
if self.id is None:
domain = Domain()
domain.name = str(self.id).zfill(4) + '.firmir.local'
domain.site = self
domain.save()
super(Site, self).save(*args, **kwargs)
def __unicode__(self):
return str(self.id) + ': ' + self.name
class Meta:
verbose_name = 'Сайт (аккаунт)'
verbose_name_plural = 'Сайты (аккаунты)'<file_sep># -*- coding: utf-8 -*-
from catalog.models import Product, Property
from django.db import connection
class CacheTable():
cursor = connection.cursor()
table = 'catalog_cache_table'
PROPERTY_FIELD_TYPE = (
'varchar(255) DEFAULT NULL',
'double DEFAULT NULL',
'tinyint(1) DEFAULT NULL',
)
def create_table(self):
# получаем список свойств
sql = self.cursor.execute("""
SELECT slug, type from catalog_property
""")
prop = self.cursor.fetchall()
# формируем строку создания таблицы
c = ""
for i in prop:
a = i[0]
if i[1] == 1:
b = self.PROPERTY_FIELD_TYPE[0]
elif i[1] == 2:
b = self.PROPERTY_FIELD_TYPE[1]
elif i[1] == 3:
b = self.PROPERTY_FIELD_TYPE[2]
elif i[1] == 4:
b = self.PROPERTY_FIELD_TYPE[0]
c += "`%s` %s, " % (a, b)
c += "PRIMARY KEY (`id`)"
# выполняем запрос на создание таблицы
sql = self.cursor.execute("CREATE TABLE `%s` (`id` int(11) NOT NULL AUTO_INCREMENT, `product_id` int(11) NOT NULL, %s) ENGINE=MyISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;" % (self.table, c))
def fill_table(self):
# TODO: заполнять таблицу полностью
# получаем список продуктов
sql = self.cursor.execute("""
SELECT id FROM catalog_product
""")
prod = self.cursor.fetchall()
for i in prod:
sql = self.cursor.execute("INSERT INTO %s (product_id) VALUE (%d);" % (self.table, i[0]))
def add_property(self, name, type):
sql = self.cursor.execute("ALTER TABLE %s add `%s` %s;" % (self.table, name, self.PROPERTY_FIELD_TYPE[type]))
def remove_property(self, name):
sql = self.cursor.execute("ALTER TABLE %s DROP COLUMN `%s`;" % (self.table, name))
<file_sep># -*- coding: utf-8 -*-
import re
from models import Hash
class HashingMiddleware:
link_pattern = re.compile(r"""<a\s*(?P<attr1>.*?)hashed_link=""(?P<attr2>.*?)\s*(?:href=['"](?P<url>.*?)['"]){0,1}(?P<attr3>.*?)>""")
def process_response(self, request, response):
try:
if request.user.is_staff == True:
return response
else:
# Hashing links
response.content = self.link_pattern.sub(self._hash_link, response.content)
return response
except AttributeError:
# redirect detected
return response
def _hash_link(self, m):
link = m.group('url')
hashed_link = Hash.link2hash(link)
return '<a href="#" hash-string="{0}" {1} {2} {3}>'.format(hashed_link, m.group('attr1'), m.group('attr2'), m.group('attr3'))<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
create_group('media', 'Мультимедиа')
@add2group('Изображение', 'media')
class SimpleImage(Widget):
image = models.ImageField("Изображение", upload_to='media_widgets/image')
alt = models.CharField(max_length=255, blank=True, default="")
title = models.CharField(max_length=255, blank=True, default="")
link = models.CharField(u'Ссылка', max_length=255, blank=True, default="")
@add2group('Видео', 'media')
class SimpleVideo(Widget):
video = models.FileField("Видео", upload_to='media_widgets/video')
alt = models.CharField(max_length=255, blank=True, default="")
title = models.CharField(max_length=255, blank=True, default="")
<file_sep>from django.http import HttpResponse
from django.template import RequestContext
def staff_required(fn):
def new(request, *args, **kwargs):
context = RequestContext(request)
if not context['user'].is_staff:
return HttpResponse('Access Denied', status=403)
return fn(request, *args, **kwargs)
return new<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Images and galleries
#
create_group('images', 'Картинки и галереи')
@add2group('Изображение', 'images')
class SingleImage(Widget):
image = models.ImageField("Изображение", upload_to='image_widget')
has_border = models.BooleanField("Border", default=False)
is_zoomable = models.BooleanField("Увеличивается при клике", default=False)
is_scalable = models.BooleanField("Ресайзится вместе с окном браузера", default=False)
description_top = models.TextField("Описание сверху", blank=True, null=True, editable=False)
description_bottom = models.TextField("Описание снизу", blank=True, null=True, editable=False)
description_below = models.TextField("Описание под картинкой", blank=True, null=True, editable=False)
alt = models.CharField(max_length=255, blank=True, default="")
title = models.CharField(max_length=255, blank=True, default="")
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
from tinymce import models as tinymce_model
#
# Lists
#
create_group('lists', 'Списки')
@add2group('Простой список', 'lists')
class SimpleList(Widget):
LIST_CHOICES = (
(1, 'Маркированный'),
(2, 'Нумерованный'),
)
content = tinymce_model.HTMLField("Список (каждый пункт с новой строки)", blank=True, default="Пункт 1\nПункт 2\nПункт 3")
list_type = models.PositiveIntegerField("Тип списка", choices=LIST_CHOICES, default='1')
def get_items(self):
result = []
for string in self.content.split("\n"):
string = string.replace('<li>', '').replace('</li>', "\n")
if string.isspace() or string == '':
pass
else:
result.append(string)
return result
@add2group('Нумерованный список', 'lists')
class NumericList(SimpleList):
def save(self, *args, **kwargs):
if self.id is None:
self.list_type = '2'
self.type = 'SimpleList'
super(SimpleList, self).save(*args, **kwargs)
class Meta:
proxy = True
#
#
#@add2group('Маркированный список', 'lists')
#class UnorderedList(SimpleList):
#
# def save(self, *args, **kwargs):
# if self.id is None:
# self.list_type = '1'
# self.type = 'SimpleList'
# super(SimpleList, self).save(*args, **kwargs)
#
# class Meta:
# proxy = True
<file_sep># -*- coding: utf-8 -*-
from django.core.urlresolvers import RegexURLResolver
import url_maps
class LameRegexURLResolver(RegexURLResolver):
def _get_url_patterns(self):
return self.urlconf_module
def dispatch(request):
section_type = request.current_section.type.slug
subpath = request.current_section.subpath
url_map = url_maps.__dict__[section_type]
resolver = LameRegexURLResolver('', url_map)
func, args, kwargs = resolver.resolve(subpath)
kwargs['request'] = request
return func(*args, **kwargs)<file_sep># -*- coding: utf-8 -*-
from django.test import TestCase
from catalogapp import api
from django.core.exceptions import ValidationError
class TestGoods(TestCase):
good_valid_attrs = {"name": "name", "section_id": 1, "articul": "articul"}
good_valid_initial = {"slug": "slug", "price_in": 1, "price_out": 2,
"shortdesc": 'desc', "label": "label"}
def test_add(self):
sps_array = [{
"field_type": "BooleanField",
"name": "boolfield",
"slug": "bool_slug",
"default_value": True,
"description": "Some desc",
},
{
"field_type": "CharField",
"name": "charfield",
"slug": "char_slug",
"default_value": "some string",
"description": "Some desc",
},]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
initial = {"slug": "slug", "price_in": 1, "price_out": 2,
"boolfield": False, "charfield": "xxx"}
good_id = api.goods.create(name="name", section_id=1, initial=initial)
self.assertTrue(isinstance(good_id, unicode))
def test_get(self):
sps_array = [{
"field_type": "BooleanField",
"name": "boolfield",
"slug": "bool_slug",
"default_value": True,
"description": "Some desc",
},
{
"field_type": "CharField",
"name": "charfield",
"slug": "char_slug",
"default_value": "some string",
"description": "Some desc",
},]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
initial = {"slug": "slug", "price_in": 1, "price_out": 2,
"boolfield": False, "charfield": "xxx"}
good_id = api.goods.create(name="name", section_id=1, initial=initial)
good = api.goods.get(id=good_id)
self.assertEqual(good.name, "name")
def test_delete(self):
initial = {"slug": "slug", "price_in": 1, "price_out": 2,
"boolfield": False, "charfield": "xxx"}
good_id = api.goods.create(name="name", section_id=1, initial=initial)
api.goods.delete(good_id)
self.assertEqual(api.goods.Good.objects.count(), 0)
def test_boolean(self):
sps_array = [{
"field_type": "BooleanField",
"name": "boolfield",
"slug": "bool_slug",
"default_value": True,
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
# Тестируем верное значение True
initial = self.good_valid_initial.copy()
initial['boolfield'] = True
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
# Тестируем верное значение False
initial = self.good_valid_initial.copy()
initial['boolfield'] = False
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
# Тестируем не верное значение "wrong"
initial = self.good_valid_initial.copy()
initial['boolfield'] = "wrong"
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
self.assertRaises(ValidationError, api.goods.create, **create_attr)
def test_charfield(self):
sps_array = [{
"field_type": "CharField",
"name": "charfield",
"slug": "char_slug",
"default_value": "",
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
# Тестируем верное значение "test"
initial = self.good_valid_initial.copy()
initial['charfield'] = "test"
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
def test_integer(self):
sps_array = [{
"field_type": "IntegerField",
"name": "integerfield",
"slug": "integer_slug",
"default_value": 0,
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
# Тестируем верное значение 5
initial = self.good_valid_initial.copy()
initial['integerfield'] = 5
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
# Тестируем не верное значение "wrong"
initial = self.good_valid_initial.copy()
initial['integerfield'] = "wrong"
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
self.assertRaises(ValidationError, api.goods.create, **create_attr)
def test_textfield(self):
sps_array = [{
"field_type": "TextField",
"name": "textfield",
"slug": "text_slug",
"default_value": "",
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
# Тестируем верное значение "test"
initial = self.good_valid_initial.copy()
initial['textfield'] = "test"
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
def test_choicefield(self):
sps_array = [{
"field_type": "ChoiceField",
"name": "choicefield",
"slug": "choice_slug",
"choices": [(1, 'Choice 1'), (2, 'Choice 2')],
"default_value": "",
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
# Тестируем верное значение 1
initial = self.good_valid_initial.copy()
initial['choicefield'] = 1
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
# Тестируем не верное значение 3
initial = self.good_valid_initial.copy()
initial['choicefield'] = 3
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
self.assertRaises(ValidationError, api.goods.create, **create_attr)
def test_multiplechoicefield(self):
sps_array = [{
"field_type": "MultipleChoiceField",
"name": "mchoicefield",
"slug": "mchoice_slug",
"choices": [(1, 'Choice 1'), (2, 'Choice 2')],
"default_value": "",
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
# Тестируем верное значение 1
initial = self.good_valid_initial.copy()
initial['mchoicefield'] = 1
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
# Тестируем верное значение [1, 2]
initial = self.good_valid_initial.copy()
initial['mchoicefield'] = "1,2"
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
good = api.goods.create(**create_attr)
# Тестируем не верное значение 3
initial = self.good_valid_initial.copy()
initial['mchoicefield'] = 3
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
self.assertRaises(ValidationError, api.goods.create, **create_attr)
# Тестируем не верное значение [1, 3]
initial = self.good_valid_initial.copy()
initial['mchoicefield'] = "1,3"
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = initial
self.assertRaises(ValidationError, api.goods.create, **create_attr)
def test_default_value(self):
sps_array = [{
"field_type": "CharField",
"name": "charfield",
"slug": "char_slug",
"default_value": "default",
"description": "Some desc",
}]
section_id = api.sections.create("Name", "slug")
api.sections.addFields(section_id, sps_array)
create_attr = self.good_valid_attrs.copy()
create_attr['initial'] = self.good_valid_initial
good_id = api.goods.create(**create_attr)
good = api.goods.get(good_id)
self.assertEqual(good.charfield, "default")
def tearDown(self):
# В отличие от sqlite3 (не знаю про другие базы), монга не чистит после каждого теста
# Сделаем чтобы прибирала за собой
api.goods.Good.objects.all().delete()<file_sep># -*- coding: utf-8 -*-
import datetime
from django.db import models
from theming import Template
class Client(models.Model):
name = models.CharField("Имя контрагента", max_length=255)
info = models.TextField("Данные контрагента", blank=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Клиент'
verbose_name_plural = 'Клиенты'
class Site(models.Model):
STATE_CHOICES = (
(0, 'Тестовый режим'),
(1, 'Активный режим'),
(2, 'Заблокирован администратором'),
)
name = models.CharField("Название", max_length=255)
state = models.PositiveIntegerField("Состояние", choices=STATE_CHOICES, default=0)
test_until = models.DateField("Тест по", blank=True, null=True)
active_until = models.DateField("Активен по", blank=True, null=True)
client = models.ForeignKey("Client", verbose_name='Контрагент')
template = models.ForeignKey(Template, verbose_name='Шаблон', blank=True, null=True)
def save(self, *args, **kwargs):
if self.id is None:
self.test_until = datetime.date.today() + datetime.timedelta(days=7)
super(Site, self).save(*args, **kwargs)
domain = Domain()
domain.name = str(self.id).zfill(4) + '.17777.ru'
domain.site = self
domain.save()
else:
super(Site, self).save(*args, **kwargs)
def activate(self):
if not self.active_until:
self.active_until = datetime.date.today() + datetime.timedelta(days=365)
else:
self.active_until = self.active_until + datetime.timedelta(days=365)
self.state = 1
def __unicode__(self):
return str(self.id) + ': ' + self.name
class Meta:
verbose_name = 'Сайт (аккаунт)'
verbose_name_plural = 'Сайты (аккаунты)'
class Domain(models.Model):
name = models.CharField("Доменное имя (без www)", max_length=255)
site = models.ForeignKey("Site", verbose_name='Сайт')
def __unicode__(self):
return self.name + ' (' + self.site.name + ')'
class Meta:
verbose_name = 'Домен'
verbose_name_plural = 'Домены'
<file_sep>{% extends "layout.html" %}
{% block head %}
<script type="text/javascript" src="{{ STATIC_URL }}js/jstree/_lib/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/jstree/jquery.jstree.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/jstree/_lib/jquery.cookie.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/jstree/_lib/jquery.hotkeys.js"></script>
{% endblock %}
{% block site %}
{% if user.is_staff and user == document.owner %}
<div id="structure">
{% include "tree.html" %}
</div>
{% else %}
<div id="index">
{% load vars %}
{% assign tree document.get_parts_tree %}
{% include "tree_user.html" %}
</div>
{% endif %}
<div id="document">
{% block document %}
{{ part }}
{% endblock %}
</div>
{% endblock %}<file_sep># -*- coding: utf8 -*-
from django.db import models
class TextOnPage(models.Model):
url = models.CharField('привязать к URL', max_length=255)
caption = models.CharField('Заголовок', max_length=255, blank=True)
desc = models.TextField('Полное описание', blank=True)
class Meta:
verbose_name = 'Текст на странице'
verbose_name_plural = 'Тексты на страницах'
def __unicode__(self):
return '({0}): {1}'.format(self.url, self.caption)
<file_sep># -*- coding: utf-8 -*-
import json
from models import Product, Pricing
class Basket:
session = None
def __init__(self, session):
if session.get('basket') is None:
session['basket'] = "{}"
self.session = session
def _get_key(self, product_id, size_id=0):
"""
Creates key for basket item.
Key for basket item is the string of "product_id:size_id"
"""
return str(product_id)
def _get_ids(self, key):
"""
Returns product id and size id for given key
"""
return int(key)
def _save(self, obj):
"""
Serializes and saves the basket into session
"""
result = json.dumps(obj)
self.session['basket'] = result
return result
def _load(self):
"""
Loads basket from session and deserializes it
"""
string = self.session['basket']
return json.loads(string)
#
# Adding, deleting and changing basket items
#
def _change_count(self, product_id, size_id=0, count=1):
"""
Adds or delete the Product (optionally with its Size) to basket (-/+ 1)
"""
size_id = int(size_id)
# Checking if given product and size (if specified) are exist
# It will throw an exception if no product/size exist
product = Product.objects.get(pk=product_id)
if size_id:
size = product.sizes.get(pk=size_id)
else:
size = None
del product
del size
# Getting basket contents
basket = self._load()
# Key for basket item is the string of "product_id:size_id"
key = self._get_key(product_id, size_id)
# Checking if this combination is already exist in basket
if count > 0:
if key in basket:
if type(basket[key]) is list:
# Items with sizes: adding an item to the list
basket[key].append(size_id)
else:
# Items w/o sizes: adding count
basket[key] = int(basket[key]) + 1
else:
# Creating new record
if size_id:
basket[key] = [size_id]
else:
basket[key] = 1
elif count < 0:
if key in basket:
if type(basket[key]) is list:
index = basket[key].index(size_id)
del basket[key][index]
else:
basket[key] -= 1
if not basket[key]:
del basket[key]
else:
pass
# Saving the basket
self._save(basket)
if not basket.get(key):
return 0
elif type(basket[key]) is list:
return len(basket[key])
else:
return basket[key]
def add(self, product_id, size_id=0):
""" Adds one position with given size """
return self._change_count(product_id, size_id, 1)
def delete(self, product_id, size_id=0):
""" Deletes one position with given size """
return self._change_count(product_id, size_id, -1)
def change_size(self, product_id, old_size_id, new_size_id):
"""
Changes the size for given product.
Assumes that:
- item with key product:OLD_size DOES exist in basket.
- item with key product:NEW_size DOES NOT exist in basket.
"""
product_id = int(product_id)
old_size_id = int(old_size_id)
new_size_id = int(new_size_id)
# Checking for existance
product = Product.objects.get(pk=product_id)
old_size = product.sizes.get(pk=old_size_id)
new_size = product.sizes.get(pk=new_size_id)
del product
del old_size
del new_size
# Getting basket contents
basket = self._load()
key = self._get_key(product_id, old_size_id)
index = basket[key].index(old_size_id)
# Changing key
basket[key][index] = new_size_id
# Saving
self._save(basket)
return basket
def clear(self):
"""
Clears whole user basket
"""
self._save({})
#
# Basket items lists, properties and summaries
#
def _get_price(self, product, size):
"""
Calculates the price for the product by its size
"""
if size is None:
return product.discounted()
else:
pricing = Pricing.objects.get(product=product, size=size)
return pricing.discounted()
def _get_item(self, product_id, size_id, count):
"""
Returns extended basket item with information about price, summary, sizes, etc.
"""
product = Product.objects.get(pk=product_id)
if size_id:
size = product.sizes.get(pk=size_id)
else:
size = None
price = self._get_price(product, size)
count = int(count)
return {
'0': product.id, # dirty hack for sorting by product ID...
'1': size_id, # ... and then by its size
'product': product,
'count': count,
'price': price,
'summary': price * count,
'url': product.section.path + product.slug,
'current_size_id': size_id,
'sizes_list': product.sizes.all(),
'pricing_list': Pricing.objects.filter(product=product)
}
def get_list(self):
"""
Returns list of basket items with extended information
"""
basket = self._load()
result = []
for key, val in basket.iteritems():
if type(val) is list:
for size_id in val:
item = self._get_item(key, size_id, 1)
result.append(item)
else:
item = self._get_item(key, 0, val)
result.append(item)
result.sort()
return result
def get_count(self, product_id):
"""
Returns count of basket item with given product_id (any sizes)
"""
basket = self._load()
key = self._get_key(product_id)
if not basket.get(key):
return 0
if type(basket[key]) is list:
return len(basket[key])
else:
return int(basket[key])
def get_summary_info(self):
"""
Returns summary price and count of all items in basket
"""
basket = self._load()
summary_count = 0
summary_price = 0
for key, val in basket.iteritems():
if type(val) is list:
product = Product.objects.get(pk=key)
for size_id in val:
size = product.sizes.get(pk=size_id)
price = self._get_price(product, size)
summary_price += price
summary_count += len(val)
else:
count = val
product = Product.objects.get(pk=key)
price = self._get_price(product, None)
summary_price += int(count) * price
summary_count += int(count)
return {
'summary_count': summary_count,
'summary_price': summary_price
}
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
create_group('common', 'Другие')
@add2group('Горизонтальная черта', 'common')
class Hr(Widget):
pass<file_sep>/*
* Aphaline API
*/
Aphaline.API = {
/* Core */
Core: {
variants_available: function() {
return [
{ 'name': 'default', 'caption': 'Просмотр' },
{ 'name': 'edit', 'caption': 'Редактирование' }
]
}
},
/* Widgets */
Widgets: {
list: function() {
var result = null;
$.ajax({
async: false,
type: 'GET',
url: '/api/widgets/list/',
dataType: 'json',
processData: false,
success: function(reply) {
result = reply;
}
});
return result;
},
create: function(widget_type, zone_id, order, callback) {
$.get(
'/api/widgets/create/' + widget_type + '/',
{
//v: 'apiedit',
zone_id: zone_id,
order: order
},
callback
);
},
move: function(widget_id, zone_id, order, callback) {
$.get(
'/api/widgets/move/' + widget_id + '/',
{
zone_id: zone_id,
order: order
},
callback
);
},
delete: function(widget_id, callback) {
$.get('/api/widgets/delete/' + widget_id + '/', callback);
}
},
Legacy: {
form: function(model, id, data, callback, errback) {
if (id)
var url = '/api/aphaline/' + model + '/form/' + id + '/'
else
var url = '/api/aphaline/' + model + '/form/'
var response = null;
$.ajax({
async: false,
type: 'POST',
url: url,
data: data,
//processData: false,
success: function(reply) {
if (reply.error && errback) errback(reply.error);
else if (callback) callback(reply);
response = reply;
},
error: function(a, e) {
if (errback) errback({message: 'ParseError'});
return false;
}
});
return response;
},
delete: function(model, id, callback, errback) {
var url = '/api/aphaline/' + model + '/delete/' + id + '/'
var response = null;
$.ajax({
async: false,
type: 'POST',
url: url,
processData: false,
success: function(reply) {
if (reply.error && errback) errback(reply.error);
else if (callback) callback(reply);
response = reply;
},
error: function(a, e) {
if (errback) errback({message: 'ParseError'});
return false;
}
});
return response;
}
}
/* Nothing more yet... */
}<file_sep># -*- coding: utf-8 -*-
import pytils
from django.db import models
from utils.models import SortableModel
from widgets.models import Zone
from utils.tree import build_tree
from tinymce import models as tinymce_model
class Section(SortableModel):
order_isolation_fields = ('parent',)
subpath = ''
caption = models.CharField("Название (наименование, имя)", max_length=255)
path = models.CharField("Путь URL", max_length=255)
type = models.ForeignKey('SectionType', verbose_name="Тип")
parent = models.ForeignKey('Section', verbose_name="Родительский раздел",
blank=True, null=True, related_name='children')
is_enabled = models.BooleanField(default=True)
zone = models.OneToOneField(Zone, null=True, blank=True)
def __unicode__(self):
return self.path
def save(self, *args, **kwargs):
if self.id == None:
zone = Zone()
zone.save()
self.zone = zone
super(Section, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone.delete()
super(Section, self).delete(*args, **kwargs)
def get_slug(self):
return self.path.split('/')[-2]
def has_children(self):
return Section.objects.filter(parent=self)[:1].count() == 1
def get_descendants(self):
return Section.objects.filter(path__startswith=self.path).exclude(pk=self.pk)
def create_child(self, caption, slug='', section_type=None):
return self.__class__.create_section(self, caption, slug, section_type)
def create_sibling(self, caption, slug='', section_type=None):
# @todo check if user tries to create sibling of the root
return self.__class__.create_section(self.parent, caption,
slug, section_type)
@staticmethod
def create_section(parent, caption, slug='', section_type=None):
section = Section()
section.caption = caption
if slug == '':
slug = pytils.translit.slugify(caption)
if section_type is None:
section.type = parent.type.inherit_type
else:
section.type = section_type
while True:
section.path = parent.path + slug + '/'
if not Section.objects.filter(path=section.path):
break
else:
slug += '_'
section.parent = parent
section.save()
return section
@staticmethod
def get_structure():
nodes = Section.objects.filter(is_enabled=True).values()
return build_tree(nodes)
@staticmethod
def get_node_by_path(path):
node = Section.objects.filter(is_enabled=True).extra(
select={ "subpath": "SUBSTR(%s, LENGTH(path)+1)" },
select_params=(path,),
where=["""
path = (
SELECT max(path)
FROM structure_section
WHERE locate(path, %s) = 1
AND is_enabled = 1
)
"""],
params=(path,)
)[0]
return node
def change_slug(self, slug):
old_path = self.path
children = self.get_descendants()
while True:
self.path = self.parent.path + slug + '/'
if not Section.objects.filter(path=self.path):
break
else:
slug += '_'
self.save()
for child in children:
child.path = child.path.replace(old_path, self.path)
child.save()
def change_parent(self, parent, order=None):
""" Moves section to another parent """
if parent != self.parent:
# Setting order of widget to last in old zone
# for other widgets to rearrange
self.move(-1)
# Changing zone and setting new order
self.parent = parent
self.order = 0
self.save()
if order is not None:
self.move(order)
else:
self.move(-1)
old_path = self.path
children = self.get_descendants()
slug = self.get_slug()
while True:
self.path = parent.path + slug + '/'
if not Section.objects.filter(path=self.path):
break
else:
slug += '_'
self.save()
for child in children:
child.path = child.path.replace(old_path, self.path)
child.save()
class SectionType(SortableModel):
caption = models.CharField("Название (по-человечески)", max_length=255)
slug = models.CharField("Идентификатор (slug)", max_length=255)
description = tinymce_model.HTMLField("Описание", blank=True)
inherit_type = models.ForeignKey('SectionType',
verbose_name="Тип потомков по умолчанию",
blank=True, null=True,
on_delete=models.SET_NULL)
def __unicode__(self):
return self.caption
<file_sep>def aphaline_edit_mode(request):
return { 'aphaline_edit_mode': request.session.get('aphaline_edit_mode') }<file_sep># -*- coding: utf-8 -*-
from datetime import date
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from models import Article
from utils.shortcuts import paginate
ARTICLES_ON_PAGE = 10
def index(request, page=None):
context = RequestContext(request)
paginate(
context, 'articles',
Article.objects.order_by('-date_written'),
count=ARTICLES_ON_PAGE, page=page,
root=request.current_section.path
)
return render_to_response('articles/index.html', context)
def section(request, section, page=None):
context = RequestContext(request)
paginate(
context, 'articles',
query=context['section'].article_set.all(),
count=ARTICLES_ON_PAGE, page=page,
root=request.current_section.path+section+'/'
)
return render_to_response('articles/section.html', context)
def article(request, article, section = None):
article = get_object_or_404(Article, name=article)
context = RequestContext(request)
context['article'] = article
return render_to_response('articles/article.html', context)
<file_sep># -*- coding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
def index(request):
context = RequestContext(request)
return render_to_response('index.html', context)
def text(request):
context = RequestContext(request)
return render_to_response('text.html', context)
<file_sep>import os
from settings_db import DATABASES
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Derter', '<EMAIL>'),
('Succubi', '<EMAIL>'),
)
MANAGERS = ADMINS
TIME_ZONE = 'Asia/Yekaterinburg'
LANGUAGE_CODE = 'ru-RU'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.split(SITE_ROOT)[0]
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/work/media/mario/'
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/admin-media/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
SECRET_KEY = <KEY>'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'django.template.loaders.app_directories.load_template_source'
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'debug_toolbar.middleware.DebugToolbarMiddleware',
'structure.middleware.StructureMiddleware',
'aphaline.middleware.AphalineMiddleware',
'seo.middleware.HashingMiddleware',
)
ROOT_URLCONF = 'mario.urls'
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates'),
#'/usr/local/lib/python2.7/dist-packages/debug_toolbar/templates/',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.sitemaps',
#'debug_toolbar',
'genericm2m',
'seo',
'mptt',
'structure',
'articles',
'widgets',
# 'catalogapp',
'common',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# CACHES = {
# 'default': {
# 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
# 'LOCATION': '127.0.0.1:11211',
# }
# }
LOGIN_REDIRECT_URL = '/'
FIELD_TYPES = ('BooleanField', 'CharField', 'IntegerField',
'TextField', 'ChoiceField', 'MultipleChoiceField')
MONGODB_MANAGED_MODELS = ["catalogapp.Good"]
# DATABASE_ROUTERS = ["django_mongodb_engine.router.MongoDBRouter"]
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"utils.context_processors.seo_tags",
"utils.context_processors.phone",
"utils.context_processors.current_section",
"utils.context_processors.structure",
"aphaline.context_processors.aphaline_edit_mode",
)
INTERNAL_IPS = ('10.10.10.1',)
DEBUG_TOOLBAR_PANELS = (
'debug_toolbar.panels.timer.TimerDebugPanel',
'debug_toolbar.panels.sql.SQLDebugPanel',
)
<file_sep># -*- coding: utf8 -*-
import datetime
from django.db import models
from django import forms
class Chat(models.Model):
"""
Chat
"""
name = models.CharField('Имя', max_length=20)
message = models.TextField('Сообщение')
time = models.DateTimeField('Время', default=datetime.datetime.now())
session = models.CharField('Сессия', max_length=32)
status = models.BooleanField('Закрыто', default=False, blank=True)
class Meta:
verbose_name = 'Чат'
verbose_name_plural = 'Чаты'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
super(Chat, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
super(Chat, self).delete(*args, **kwargs)
class ChatForm(forms.ModelForm):
"""
ChatForm
"""
message = forms.CharField(label='Сообщение', widget=forms.Textarea(attrs={'cols':'20','rows':'2'}))
class Meta:
model = Chat
class LoginForm(forms.ModelForm):
"""
LoginForm
"""
login = forms.CharField(label='Ваше имя?', widget=forms.TextInput(attrs={'size':'20', 'id':'login'}))
class Meta:
model = Chat
<file_sep>{% load vars %}
<span class="h2">Статьи</span>
<div class="leftMenu">
{% for group in groups.values %}
<div class="leftMenu_group{% if section %} group_hide{% endif %}">
<p><a href="#"><span>{{ group.caption }}</span></a></p>
{% if group.nodes %}
<ul>
{% for subgroup in group.nodes.values %}
{% if subgroup.nodes %}
<li class="leftMenu_innerMenu">
<a href="/articles/{{ gg.name }}/" class="dashedBorder">{{ subgroup.caption }}</a>
<ul>
{% for ggg in subgroup.nodes.values %}
{% ifequal ggg.name section.name %}
{% if not article.caption %}
<li class="cur"><span class="inlineBlock">{{ ggg.caption }}</span></li>
{% else %}
<li class="cur"><a href="/articles/{{ ggg.name }}/"><span class="inlineBlock">{{ ggg.caption }}</span></a></li>
{% endif %}
{% else %}
<li><a href="/articles/{{ ggg.name }}/">{{ ggg.caption }}</a></li>
{% endifequal %}
{% endfor %}
</ul>
<ins></ins>
</li>
{% else %}
{% ifequal subgroup.name section.name %}
{% if not article.caption %}
<li class="cur"><span class="inlineBlock">{{ subgroup.caption }}</span></li>
{% else %}
<li class="cur"><a href="/articles/{{ subgroup.name }}/"><span class="inlineBlock">{{ subgroup.caption }}</span></a></li>
{% endif %}
{% else %}
<li><a href="/articles/{{ subgroup.name }}/">{{ subgroup.caption }}</a></li>
{% endifequal %}
{% endif %}
{% endfor %}
</ul>
{% endif %}
</div>
{% endfor %}
</div>
<script type="text/javascript">
$('.cur').parents('.group_hide').removeClass('group_hide');
$('.cur').parents('.leftMenu_innerMenu').addClass('show');
</script>
<file_sep>{% extends "articles/article_layout.html" %}
{% load zones %}
{% load vars %}
{% block article_content %}
{% if user.is_staff and aphaline_edit_mode %}
<p><a href="#"
aph-adder="yes"
aph-model="Article"
class="adder_link">
Добавить новость или статью
</a>
</p>
{% endif %}
<!-- zone ... -->
{% for article in articles %}
<div class="articles_listItem"
aph-block-type="gde"
aph-model="Article"
aph-id="{{ article.id }}"
aph-redirect-url="{{ current_section.path }}{{ article.name }}/">
<h2>
<a href="{{ current_section.path }}{{ article.name }}">{{ article.caption }}</a>
</h2>
<p class="description">
{{ article.shortdesc|safe }}
</p>
</div>
{% endfor %}
{% include "generic/pagination.html" %}
{% endblock %}<file_sep>$(document).ready(function() {
$('#logo_wrapper').css('cursor', 'pointer').click(function() {
window.location.href = '/';
});
// $('#catalog_typeselect').find('dt').find('span').click(function() {
// $(this).parent().next('dd').toggle();
// //$(this).parent().next('dd').show();
// })
})<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.core.paginator import Paginator
def paginate(context, result_key, query, count, page, root):
if page == '1' or page == 1:
return HttpResponseRedirect(root)
elif page is None:
page = 1
else:
page = int(page)
p = Paginator(query, count)
if p.num_pages >= page and page is not 0:
context['pagination'] = {}
context['pagination']['current_page'] = page
context['pagination']['root'] = root
context['pagination']['page_range'] = p.page_range
context['pagination']['num_pages'] = p.num_pages
context[result_key] = p.page(page).object_list
if p.page(page).has_previous() == True:
context['pagination']['previous_page'] = p.page(page).previous_page_number()
if p.page(page).has_next() == True:
context['pagination']['next_page'] = p.page(page).next_page_number()
else:
raise Http404
def render_template(request, page, context):
template = request.site.siteparams.template
path = template.slug + '/' + page + '.html'
return render_to_response(path, context)
<file_sep># -*- coding: utf-8 -*-
from models import Section
class StructureMiddleware:
def process_request(self, request):
request.current_section = Section.get_node_by_path(request.path)
request.structure = Section.get_structure()
<file_sep># -*- coding: utf8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt
from models import Chat
from models import ChatForm, LoginForm
from chat import ChatClass
from decorator import is_session
import datetime
@is_session
def get_message(request):
context = RequestContext(request)
chat = ChatClass(request.session)
context['messages'] = Chat.objects.filter(session=chat.get_session()).order_by('-id')
return render_to_response('chat/get_message.html', context)
@is_session
@csrf_exempt
def save_message(request):
context = RequestContext(request)
chat = ChatClass(request.session)
if request.method == 'POST':
send = Chat(
name = chat.get_login(),
message = unicode(request.POST['message']),
time = datetime.datetime.now(),
session = chat.get_session()
)
send.save()
return get_message(request)
<file_sep>## -*- coding: utf-8 -*-
#
#from django.contrib import admin
#from models import Section, Good
#
#admin.site.register(Section)
#admin.site.register(Good)<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Tables
#
create_group('tables', 'Таблицы')
@add2group('Таблица', 'tables')
class Table(Widget):
TABLE_CHOICES = (
(1, 'Таблица 1'),
(2, 'Таблица 2'),
(3, 'Таблица 3'),
)
content = models.TextField("Содержимое тега TABLE (без него самого)", blank=True, default="")
table_type = models.PositiveIntegerField("Тип таблицы", choices=TABLE_CHOICES, default=1)
@add2group('Таблица 2', 'tables')
class Table_2(Table):
def save(self, *args, **kwargs):
if self.id is None:
self.table_type = 2
self.type = 'Table'
super(Table, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Таблица 3', 'tables')
class Table_3(Table):
def save(self, *args, **kwargs):
if self.id is None:
self.table_type = 3
self.type = 'Table'
super(Table, self).save(*args, **kwargs)
class Meta:
proxy = True
<file_sep>/*
* Interface and event handling
*/
Aphaline.Interface = (function() {
var selected_widget = null;
var selected_adder = null;
var is_move_mode = false;
var aph_adder = '<div class="aph-widget-adder"><div></div></div>';
var aph_widget = '<div class="aph-widget"></div>';
var global_panel = null;
var variants_panel = null;
var widget_panel = null;
// Simple actions
var selectWidget = function(widget_obj) {
widget_obj.addClass('selected');
selected_widget = widget_obj;
widget_panel.showAll();
}
var deselectWidget = function() {
if (selected_widget == null)
return;
selected_widget.removeClass('selected');
selected_widget = null;
widget_panel.hide();
}
var selectAdder = function(adder_obj) {
adder_obj.addClass('selected');
selected_adder = adder_obj;
}
var deselectAdder = function() {
if (selected_adder == null)
return;
selected_adder.removeClass('selected')
selected_adder = null;
}
var enterMoveMode = function() {
$('.aph-widget-adder').addClass('movemode');
selected_widget.prev('.aph-widget-adder').removeClass('movemode').addClass('invisible');
selected_widget.next('.aph-widget-adder').removeClass('movemode').addClass('invisible');
selected_widget.find('.aph-widget-adder').removeClass('movemode').addClass('invisible');
is_move_mode = true;
return false;
}
var leaveMoveMode = function() {
$('.aph-widget-adder').removeClass('movemode').removeClass('invisible');
is_move_mode = false;
return false;
}
/*
* Event handlers
*/
// Widgets
var widgetClickHandler = function(evt) {
if (is_move_mode)
leaveMoveMode();
deselectAdder();
var target = $(evt.currentTarget);
if (selected_widget == null) {
// No widget selected yet
selectWidget(target);
}
else if (target[0] == selected_widget[0]) {
// This widget is already selected
deselectWidget(target);
}
else {
// Another widget is selected
deselectWidget(selected_widget);
selectWidget(target);
}
return false;
}
var widgetDblClickHandler = function(evt) {
if (is_move_mode)
leaveMoveMode();
deselectAdder();
var target = $(evt.currentTarget);
if (selected_widget == null) {
selectWidget(target);
}
Aphaline.Actions.editWidget();
return false;
}
var widgetMouseHandler = function(evt) {
if (selected_adder == null) {
var target = $(evt.currentTarget);
if (evt.type == 'mouseover') {
target.addClass('hover');
}
else {
target.removeClass('hover');
}
return false;
}
}
// Adders
var adderClickHandler = function(evt) {
/* Moving widget */
if (is_move_mode) {
var target = $(evt.currentTarget);
Aphaline.Actions.moveWidget(target);
deselectWidget();
leaveMoveMode();
}
/* Showing "adder" menu */
else {
deselectWidget();
var target = $(evt.currentTarget);
selectAdder(target);
target.removeClass('hover');
Aphaline.WidgetList.show(evt.pageX, evt.pageY);
}
return false;
}
var adderMouseHandler = function(evt) {
if (selected_adder == null) {
if (evt.type == 'mouseover') {
var target = $(evt.currentTarget);
target.siblings('.aph-widget-adder').removeClass('hover');
target.addClass('hover');
}
else {
var target = $(evt.currentTarget);
target.removeClass('hover');
}
}
}
// Common interface handlers
var commonClickHandler = function(evt) {
if (selected_adder != null) {
Aphaline.WidgetList.hide();
deselectAdder();
}
}
var outsideClickHandler = function() {
if (is_move_mode)
leaveMoveMode();
Aphaline.WidgetList.hide();
deselectWidget();
deselectAdder();
}
var zoneMouseHandler = function(evt) {
if (selected_adder == null) {
var target = $(evt.currentTarget);
if (evt.type == 'mouseover') {
target.addClass('hover');
}
else {
target.removeClass('hover');
}
}
}
var commonKeypressHandler = function(evt) {
// Deleting widet by "delete" key
if (evt.keyCode == 46 && selected_widget != null) {
return Aphaline.Actions.deleteWidget();
}
}
// List item click handler (adding widget)
var listItemClickHandler = function(evt, item) {
var zone = selected_adder.parent('.aph-zone').eq(0);
//var zone_type = zone.attr('aph-zone-id');
//var zone_pid = zone.attr('aph-zone-pid');
//var zone_sid = zone.attr('aph-zone-sid');
var zone_id = zone.attr('aph-zone-id');
var order = 1 + zone.children('.aph-widget-adder').index(selected_adder);
//Aphaline.Actions.createWidget(selected_adder, item.name, zone_type, zone_pid, zone_sid, order);
Aphaline.Actions.createWidget(selected_adder, item.name, zone_id, order);
return false;
}
// Toolbar initialization
var initToolbar = function() {
// Creating panels
globals_panel = Aphaline.Toolbar.createPanel('globals');
structure_panel = Aphaline.Toolbar.createPanel('structure');
variants_panel = Aphaline.Toolbar.createPanel('variants');
widget_panel = Aphaline.Toolbar.createPanel('widget');
// Creating default buttons
globals_panel
.createButton('quit', 'Выход', Aphaline.Actions.quit)
.showAll()
;
structure_panel
.createButton('structure', 'Структура сайта', Aphaline.Actions.toggleStructure)
.showAll()
;
// Creating buttons for available view variants
var variants = Aphaline.API.Core.variants_available();
for (var i in variants) {
// Preparing
var variant = variants[i];
var old_addr = window.location.href.replace(/\?.*/, '');
var addr = old_addr + '?v=' + variant.name;
var callback = function(addr) { return function() {
window.location.href = addr;
} } (addr);
var prefixed_name = 'v_' + variant.name;
// Creating the button
variants_panel.createButton(prefixed_name, variant.caption, callback);
// Disabling the button with current variant
// if (gup('v') == variant.name || (gup('v') == '' && variant.name == 'default'))
// variants_panel.getButton(prefixed_name).disable();
}
if ($.cookie('aphaline_edit_mode') != 1)
variants_panel.getButton('v_default').activate();
else
variants_panel.getButton('v_edit').activate();
variants_panel.showAll();
// Buttons for widgets editing
widget_panel
.createButton('edit', 'Редактировать', Aphaline.Actions.editWidget)
.createButton('move', 'Переместить', enterMoveMode)
.createButton('delete', 'Удалить', Aphaline.Actions.deleteWidget)
;
}
/*
* The final object
*/
return {
init: function() {
// Make a border for zones
$('[aph-zone-id]').addClass('aph-zone')
// Render adders
$('[aph-zone-id]').append(aph_adder);
$('[aph-widget-type]').before(aph_adder);
// Render widgets
$('[aph-widget-type]').wrap(aph_widget);
// Handle events
$('body')
.bind('widgetlist_item_click', listItemClickHandler)
.bind('click', commonClickHandler)
.delegate('.aph-widget', 'click' , widgetClickHandler)
.delegate('.aph-widget', 'dblclick' , widgetDblClickHandler)
.delegate('.aph-widget-adder', 'click', adderClickHandler)
.delegate('.aph-widget', 'mouseover mouseout', widgetMouseHandler)
.delegate('.aph-zone', 'mouseover mouseout', zoneMouseHandler)
;
$('[aph-zone-id]')
.delegate('.aph-widget-adder', 'mouseover mouseout', adderMouseHandler)
;
$(window)
.bind('click', outsideClickHandler)
.bind('keypress', commonKeypressHandler)
;
// Initializing toolbar
initToolbar();
},
update: function() {
deselectWidget();
deselectAdder();
$('[aph-zone-id]').each(function() {
if (!$(this).hasClass('aph-zone')) {
$(this).addClass('aph-zone');
$(this).append(aph_adder);
$(this).find('[aph-widget-type]')
.before(aph_adder)
.wrap(aph_widget)
;
}
});
},
selectWidget: selectWidget,
deselectWidget: deselectWidget,
selectAdder: selectAdder,
deselectAdder: deselectAdder,
enterMoveMode: enterMoveMode,
leaveMoveMode: leaveMoveMode,
getSelectedAdder: function() {
return selected_adder;
},
getSelectedWidget: function() {
return selected_widget;
}
}
})();<file_sep># -*- coding: utf8 -*-
import hashlib
import datetime
from django.db import models
from django import forms
class User(models.Model):
"""
User
"""
STATUS_CHOICES = (
('user', 'Пользователь'),
('manager', 'Менеджер'),
)
login = models.CharField(u'Логин', max_length=20, unique=True)
password = models.CharField(u'<PASSWORD>', max_length=32)
email = models.EmailField(u'E-Mail', blank=True)
status = models.CharField(u'Статус', max_length=7, choices=STATUS_CHOICES, blank=True)
class Meta:
verbose_name = u'Пользователь'
verbose_name_plural = u'Пользователи'
def __unicode__(self):
return '%s' % self.login
def save(self, *args, **kwargs):
if not self.id:
self.password = <PASSWORD>(str(self.password)).<PASSWORD>()
else:
try:
user = User.objects.get(login=self.login)
pwd = <PASSWORD>(str(self.password)).<PASSWORD>()
if user.password != pwd:
self.password = pwd
except:
pass
if not self.status:
self.status = u'user'
super(User, self).save(*args, **kwargs)
class UserForm(forms.ModelForm):
"""
registration Form
"""
login = forms.CharField(label=u'Логин', widget=forms.TextInput(attrs={'size': '20', 'id': 'login'}), min_length=3, max_length=20)
password = forms.CharField(label=u'Пароль', widget=forms.TextInput(attrs={'size': '20', 'id': 'pwd'}), min_length=4, max_length=20)
class Meta:
model = User
def clean_login(self):
login = self.cleaned_data['login']
count = len(login)
if not count:
raise forms.ValidationErrors(u'Логин пуст')
elif count < 3:
raise forms.ValidationErrors(u'Логин менее 3 символов')
elif count > 20:
raise forms.ValidationErrors(u'Логин более 20 символов')
return login
def clean_password(self):
pwd = self.cleaned_data['password']
count = len(pwd)
if not count:
raise forms.ValidationErrors(u'Пароль пуст')
elif count < 4:
raise forms.ValidationErrors(u'Пароль менее 4 символов')
elif count > 20:
raise forms.ValidationErrors(u'Пароль более 20 символов')
return pwd
class Chat(models.Model):
"""
Chat
"""
name = models.CharField(u'Имя', max_length=20)
message = models.TextField(u'Сообщение')
time = models.DateTimeField(u'Время', default=datetime.datetime.now())
session = models.CharField(u'Сессия', max_length=32)
class Meta:
verbose_name = u'Чат'
verbose_name_plural = u'Чаты'
def __unicode__(self):
return '(%s) - %s' % (self.name, self.message)
<file_sep># -*- coding: utf-8 -*-
# from seo.models import Metatag
#from common.models import Phone
from se.models import Globals, Phoneflora
from widgets.models import Zone
# def seo_tags(request):
# try:
# return { 'metatag': Metatag.objects.get(name=request.path) }
# except:
# return {}
def phone(request):
try:
phone = Globals.objects.get(prop_slug='phone')
return {'phone': phone.value}
except:
return {'phone': ''}
def footer_zone(request):
try:
zone_id = Globals.objects.get(prop_slug='footer-zone').value
zone = Zone.objects.get(pk=zone_id)
return {'footer_zone': zone}
except:
return {'footer_zone': None}
def current_section(request):
return { 'current_section': request.current_section }
def structure(request):
return { 'structure': request.structure }
def phone_flora(request):
return { 'phone_flora': Phoneflora.objects.get(pk=1)}
<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from documents.models import Document
from django.contrib.auth.models import User
def index(request):
context = RequestContext(request)
if context['user'].is_anonymous():
return HttpResponseRedirect('/login/')
else:
return HttpResponseRedirect('/home/')
def home(request):
context = RequestContext(request)
if context['user'].is_anonymous():
return HttpResponseRedirect('/login/')
else:
context['documents'] = Document.objects.filter(owner=context['user'])
return render_to_response('home.html', context)<file_sep>$(document).ready(function() {
$('#change_collection').click(function(event) {
$.fancybox({
'width' : '90%',
'height' : '90%',
'autoScale' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'type' : 'iframe',
'overlayOpacity' : 0.9,
'href' : $(this).attr('href'),
'onClosed' : function() {
location.reload();
}
});
return false;
});
$('ul#collection_list a+div').css('display', 'none');
$('ul#collection_list a').click(function(event) {
var id = $(this).attr('id');
if($('#' + id + '+div').text()){
$('#' + id).next().slideToggle();
}else{
$.ajax({
async: true,
type: 'POST',
url: '/api/add_action/catalog/' + $('input[type=hidden]').val() + '/',
data: {
'current_section' : $(this).attr('href')
},
success: function(data){
$('#' + id).next().slideToggle();
$('#' + id + '+div').html(data);
}
});
}
return false;
});
function check() {
$('.collection_catalog_image').each(function(event) {
$(this).unbind('click');
$(this).click(function() {
var currentThis = $(this)
if($(this).hasClass('check')){
$.ajax({
async: true,
type: 'POST',
url: '/api/add_action/del/' + $('input[type=hidden]').val() + '/' + $(this).attr('wtp_id') + '/',
data: {
'current_section' : $(this).attr('href')
},
success: function(data){
currentThis.removeClass('check');
}
});
}else{
$.ajax({
async: true,
type: 'POST',
url: '/api/add_action/add/' + $('input[type=hidden]').val() + '/' + $(this).attr('wtp_id') + '/',
data: {
'current_section' : $(this).attr('href')
},
success: function(data){
currentThis.addClass('check');
}
});
}
});
});
}
interval_collection = setInterval(check, 100);
});
<file_sep># -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, url
index = patterns('se.views',
url(r'^$', 'index'),
)
text = patterns('se.views',
url(r'^$', 'text'),
)
qa = patterns('se.views',
url(r'^$', 'questanswer'),
url(r'^(page-(?P<page>\d+)){0,1}/$', 'questanswer'),
)
feedback = patterns('se.views',
url(r'^$', 'feedbackflora'),
url(r'^(page-(?P<page>\d+)){0,1}/$', 'feedbackflora'),
)
news = patterns('se.views',
url(r'^$', 'news'),
url(r'^(page-(?P<page>\d+)/){0,1}$', 'news'),
url(r'^(item-(?P<item_news>\d+)){0,1}/$', 'news'),
url(r'^(?P<slug>[-_a-zA-Z0-9.]+)/$', 'news'),
)
article = patterns('se.views',
url(r'^$', 'article'),
url(r'^(page-(?P<page>\d+)/){0,1}$', 'article'),
url(r'^(item-(?P<item_news>\d+)){0,1}/$', 'article'),
url(r'^(?P<slug>[-_a-zA-Z0-9.]+)/$', 'article'),
)
catalog = patterns('se.views',
url(r'^(?:page-(?P<page>\d+)/){0,1}$', 'catalog_list'),
url(r'^(?:item-(?P<position_id>\d+))/$', 'catalog_item'),
url(r'^all/$', 'catalog_all'),
# url(r'^tag/(?P<tag>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'tag'),
# url(r'^add_to_basket/(?P<position_id>\d+)/$', 'add_to_basket'),
# url(r'^del_from_basket/(?P<position_id>\d+)/$', 'del_from_basket'),
)
form = patterns('se.views',
url(r'^$', 'form'),
url(r'^rem/$', 'rem_from_basket'),
url(r'^(item-(?P<position_id>\d+))/add/(?P<redirect>\w+)/$', 'add_to_basket'),
url(r'^(item-(?P<position_id>\d+))/del/(?P<redirect>\w+)/$', 'del_from_basket'),
)
<file_sep># -*- coding: utf-8 -*-
# Import models and models stuff
from django.db import models
from model_utils.managers import InheritanceManager
from django_mongodb_engine.contrib import MongoDBManager
from djangotoolbox.fields import EmbeddedModelField, ListField
import cPickle as pickle
import copy
from django.core import exceptions
class Section(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
def get_fields_ids(self):
return BaseField.objects.filter(section=self).values_list('id', flat=True)
def get_fields(self):
return BaseField.objects.filter(section=self).select_subclasses()
def __unicode__(self):
return self.name
class BaseField(models.Model):
""" Базовый класс для кастомных полей
Он не абстрактный, чтобы не плодить кучу таблиц,
но требует переопределения атрибутов"""
name = models.CharField(max_length=255)
slug = models.SlugField()
section = models.ForeignKey(Section)
default_value = models.CharField(max_length=255)
description = models.TextField()
objects = InheritanceManager()
# Представление поля в виде django филда
django_field = None # You MUST define it in subclass
# Атрибуты Django филда
django_field_attrs = {}
def create_django_field(self, model):
""" Создаем новый Django Field """
# И передаем ему дополнительные аргументы
new_field = getattr(models, self.django_field)(**self.django_field_attrs)
# Устанавливаем атрибуты поля из его имени
new_field.set_attributes_from_name(self.name)
# Устанавливаем модель полю
new_field.model = model
return new_field
def add_field(self, model_instance):
""" Функция добавления поля """
new_field = self.create_django_field(model_instance.__class__)
# Добавляем поле в мета модели
model_instance._meta.add_field(new_field)
def __unicode__(self):
return self.name
class BooleanField(BaseField):
django_field = 'BooleanField'
class CharField(BaseField):
django_field = 'CharField'
django_field_attrs = {'max_length': 255}
class IntegerField(BaseField):
django_field = 'IntegerField'
class TextField(BaseField):
django_field = 'TextField'
class ChoiceField(BaseField):
choices_store = models.TextField()
django_field = 'IntegerField'
django_field_attrs = {'max_length': 255}
def _get_choices(self):
if not hasattr(self, '_choices') or self._choices is None:
self._choices = pickle.loads(str(self.choices_store))
return self._choices
def _set_choices(self, value):
self._choices = value
self.choices_store = pickle.dumps(self._choices)
choices = property(_get_choices, _set_choices)
def add_field(self, model_instance):
self.django_field_attrs['choices'] = self.choices
super(ChoiceField, self).add_field(model_instance)
class MultipleChoiceField(BaseField):
""" InheritanceManager не поддерживает наследование более 1 уровня,
поэтому не наследуемся, а копи-пастим ChoiceField """
choices_store = models.TextField()
django_field = 'CommaSeparatedIntegerField'
django_field_attrs = {'max_length': 255}
def _get_choices(self):
if not hasattr(self, '_choices') or self._choices is None:
self._choices = pickle.loads(str(self.choices_store))
return self._choices
def _set_choices(self, value):
self._choices = value
self.choices_store = pickle.dumps(self._choices)
choices = property(_get_choices, _set_choices)
def validation(self, value):
""" CommaSeparatedIntegerField не поддерживает валидацию чойзов,
поэтому она тут. Не уверен, что это верно """
values = value.split(",")
for v in values:
if not v in map(lambda x: str(x[0]), self.choices):
raise exceptions.ValidationError("Invalid choice: %s" % v)
def add_field(self, model_instance):
""" Переопределяем метод добавления филда к модели, присунув наш
валидатор """
if not self.django_field_attrs.has_key('validation'):
self.django_field_attrs['validators'] = []
self.django_field_attrs['validators'].append(self.validation)
super(MultipleChoiceField, self).add_field(model_instance)
class Brand(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
def __unicode__(self):
return self.name
class Good(models.Model):
""" Класс продуктов """
name = models.CharField(max_length=255)
slug = models.SlugField()
section_id = models.IntegerField()
articul = models.CharField(max_length=255, blank=True)
label = models.CharField(max_length=255, blank=True)
shortdesc = models.TextField(blank=True)
price_in = models.IntegerField()
price_out = models.IntegerField()
brands = ListField()
objects = MongoDBManager()
def __init__(self, *args, **kwargs):
self._meta = copy.deepcopy(self._meta)
# Достаем section, можем брать как из args, так и из kwargs
section_id = None
if len(args)>=4:
section_id = args[3]
else:
section_id = kwargs.get('section_id')
# Добавляем поля раздела
kwargs = self._set_extra_fields(section_id, kwargs)
super(Good, self).__init__(*args, **kwargs)
def _set_extra_fields(self, section_id, kwargs):
if not section_id is None:
section = Section.objects.get(id=section_id)
# Достаем все специфичные поля раздела
fields = section.get_fields()
for field in fields:
field.add_field(self)
if not field.name in kwargs:
kwargs[field.name] = field.default_value
return kwargs
def __unicode__(self):
return self.name
def save(self):
super(Good, self).save()
if self.articul is None or self.articul == "":
self.articul = self.id
self.save()<file_sep># -*- coding: utf8 -*-
import os
from django.db import models
from django.conf import settings
from structure.models import Section as StructureSection
from widgets.models import Zone
from utils.models import SortableModel
IMAGE_OPTIONS = [{'type': 'p', 'size': 150, 'quality': 100},
{'type': 'w', 'size': 263, 'quality': 100},
{'type': 'w', 'size': 345, 'quality': 100},
{'type': 'w', 'size': 49, 'quality': 100},
{'type': 'h', 'size': 257, 'quality': 100}]
def thumbnail(path, image_options, action=True):
"""
path - путь до изображения
image_options - словарь содержащий параметры
action - Действие (True - create, False - delete)
"""
original_image_name = path.split('/')[-1]
original_image_path = path.split('/')[0:-1]
original_image_path = '/'.join(original_image_path)
name, ext = original_image_name.split('.')
if action:
import Image
width, height = Image.open(settings.MEDIA_ROOT +'/'+ path).size
fp = open(settings.MEDIA_ROOT + path, 'rb')
im = Image.open(fp)
if type(image_options) is list:
for options in image_options:
if options['type'] == 'p':
if type(options['size']) is tuple:
im.thumbnail((options['size'][0], options['size'][1]), Image.ANTIALIAS)
im.save('%s/%s/%s_%sx%s.%s' %
(settings.MEDIA_ROOT, original_image_path, name, options['size'][0], \
options['size'][1], ext), quality=options['quality'])
else:
im.thumbnail((options['size'], options['size']), Image.ANTIALIAS)
im.save('%s/%s/%s_%sx%s.%s' %
(settings.MEDIA_ROOT, original_image_path, name, options['size'], \
options['size'], ext), quality=options['quality'])
elif options['type'] == 'w':
factor = height / (width / options['size'])
im.resize((options['size'], factor), Image.ANTIALIAS).save('%s/%s/%s_width_%s.%s'
% (settings.MEDIA_ROOT, original_image_path, name,\
options['size'], ext), quality=options['quality'])
elif options['type'] == 'h':
factor = width / (height / options['size'])
im.resize((factor, options['size']), Image.ANTIALIAS).save('%s/%s/%s_height_%s.%s'
% (settings.MEDIA_ROOT, original_image_path, name,\
options['size'], ext), quality=options['quality'])
else:
image_options.append({'type': 'original'})
for options in image_options:
if options['type'] == 'p':
if type(options['size']) is tuple:
path = '%s/%s/%s_%sx%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'][0], options['size'][1], ext)
else:
path = '%s/%s/%s_%sx%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'], options['size'], ext)
elif options['type'] == 'w':
path = '%s/%s/%s_width_%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'], ext)
elif options['type'] == 'h':
path = '%s/%s/%s_height_%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'], ext)
else:
path = '%s/%s/%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, ext)
if os.path.exists(path):
os.remove(path)
class Section(StructureSection):
class Meta:
proxy = True
verbose_name = 'Раздел'
verbose_name_plural = 'Разделы'
class Catalog(models.Model):
"""
docstring for Catalog
"""
section = models.OneToOneField(Section, verbose_name='Раздел сайта', related_name='catalog')
class Meta:
verbose_name = 'Каталог'
verbose_name_plural = 'Каталоги'
def __unicode__(self):
return unicode(self.section.caption)
class Manufacturer(models.Model):
"""
docstring for Manufacturer
"""
name = models.CharField('Название', max_length=255)
desc = models.TextField('Описание', blank=True)
class Meta:
verbose_name = 'Производитель'
verbose_name_plural = 'Производители'
def __unicode__(self):
pass
class Type(models.Model):
"""
docstring for Type
"""
pass
class Meta:
verbose_name = 'Тип'
verbose_name_plural = 'Типы'
def __unicode__(self):
pass
class Product(models.Model):
"""
Product
"""
STATUS_CHOICES = (
('1', 'Снят с производства'),
('2', 'Под заказ'),
('3', 'В наличии'),
('4', 'Ожидается поступление'),
)
DELIVERY_PERIOD_CHOICES = (
('1', 'A'),
('2', 'B'),
('3', 'C'),
('4', 'D'),
)
UNIT_CHOICES = (
('1', 'ед. - единица'),
('2', 'изд.'),
('3', 'кг.'),
('4', 'л. - литр'),
('5', 'м.'),
('6', 'м.(квадратный)'),
('7', 'м.(кубический)'),
('8', 'набор'),
('9', 'метр погонный'),
('10', 'рул. - рулон'),
('11', 'т. - тонна'),
('12', 'упак. - упаковка'),
('13', 'ч. - час'),
('14', 'шт.'),
('15', 'меш. - мешок'),
)
name = models.CharField('Имя продукта', max_length=255,)
desc_full = models.TextField('Полное описание', blank=True)
desc_short = models.CharField('Краткое описание', max_length=255, blank=True)
articul = models.CharField('Артикул', max_length=30, blank=True)
slug = models.SlugField('Slug', max_length=255, blank=True)
count_in_the_presence = models.FloatField('Кол-во в наличии', blank=True, default=0)
price = models.DecimalField('Цена', max_digits=10, decimal_places=2, blank=True, null=True)
discount = models.PositiveIntegerField('Скидка %', blank=True, null=True, default=0)
status = models.PositiveIntegerField('Статус', choices=STATUS_CHOICES, blank=True, null=True)
unit = models.PositiveIntegerField('Единицы измерения', choices=UNIT_CHOICES, blank=True, null=True)
delivery_period = models.PositiveIntegerField('Срок доставки', choices=DELIVERY_PERIOD_CHOICES, blank=True, null=True)
count_like = models.PositiveIntegerField('Кол-во "лайков"', blank=True, null=True, default=0)
is_publish = models.BooleanField('Публиковать?', blank=True, default=True)
is_action = models.BooleanField('Акция?', blank=True, default=True)
catalog = models.ForeignKey(Catalog, verbose_name='К какому каталогу?', blank=True, null=True)
manufacturer = models.ForeignKey(Manufacturer, verbose_name='Какой производитель?', blank=True, null=True)
types = models.ManyToManyField(Type, verbose_name='Тип', blank=True, null=True)
picture = models.ManyToManyField('Picture', verbose_name='Изображения', blank=True, null=True)
class Meta:
verbose_name = 'Продукт'
verbose_name_plural = 'Продукты'
def __unicode__(self):
return '%s' % self.name
def save(self, *args, **kwargs):
super(Product, self).save(*args, **kwargs)
if self.articul == '':
self.articul = 'A-' + str(self.id)
super(Product, self).save(*args, **kwargs)
def discounted(srlf):
if self.discount == 0:
return self.price
else:
return self.price - (self.price * self.discount/100)
class Picture(models.Model):
picture = models.ImageField('Изображение', upload_to='catalog/pictures/')
name = models.CharField('Название', max_length=255, blank=True)
alt = models.CharField('alt', max_length=255, blank=True)
title = models.CharField('title', max_length=255, blank=True)
link = models.CharField('Ссылка', max_length=255, blank=True)
class Meta:
verbose_name = 'Изображение'
verbose_name_plural = 'Изображения'
def __unicode__(self):
if self.name == '':
return 'noname'
else:
return self.name
def save(self, *args, **kwargs):
if self.id is None:
super(Picture, self).save(*args, **kwargs)
original_image = Picture.objects.get(pk=self.id).picture
thumbnail(original_image.name, IMAGE_OPTIONS)
def delete(self, *args, **kwargs):
original_image = Picture.objects.get(pk=self.id).picture
thumbnail(original_image.name, IMAGE_OPTIONS, False)
super(Picture, self).delete(*args, **kwargs)
<file_sep># -*- coding: utf8 -*-
from django.contrib import admin
from models import *
admin.site.register(User)
admin.site.register(Chat)<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from models import Article
def article_create(request):
return HttpResponse('Creating article')
def article_edit(request, id):
return HttpResponse('Editing article')
def article_delete(request, id):
return HttpResponse('Deleting article')
<file_sep>#import re
from utils import dict2htmlattrs
def aphaline_render_zone(fn):
def new(self, context=None):
result = fn(self, context)
user = context.get('user')
edit_mode = context.get('aphaline_edit_mode')
if edit_mode and user is not None and user.is_staff:
definition = {
'aph-zone-id': self.id
}
result = '<div ' + dict2htmlattrs(definition) + '>' + result + '</div>'
return result
return new
def aphaline_render_widget(fn):
def new(widget, context=None):
result = fn(widget, context)
user = context.get('user', None)
edit_mode = context.get('aphaline_edit_mode')
if edit_mode and user is not None and user.is_staff:
definition = {
'aph-widget-id': widget.id,
'aph-widget-type': widget.type
}
result = '<div ' + dict2htmlattrs(definition) + '>' + result + '</div>'
return result
return new<file_sep># -*- coding: utf-8 -*-
from catalogapp.models import Section, BaseField
from django.conf import settings
import specfields
def create(name, slug):
section = Section(name=name, slug=slug)
section.save()
return section.id
def delete(id):
try:
section = Section.objects.get(id=id)
except Section.DoesNotExist:
return False
section.delete()
return True
def rename(id, new_name, new_slug=None):
try:
section = Section.objects.get(id=id)
except Section.DoesNotExist:
return False
section.name = new_name
if not new_slug is None:
section.slug = new_slug
section.save()
return section.id
def get(id):
return Section.objects.get(id=id)
def list(**filters):
return Section.objects.filter(**filters)
def listIn(ids):
return Section.objects.filter(id__in=ids)
def addFields(section_id, sps_array):
result = []
section = Section.objects.get(id=section_id)
for field in sps_array:
if field['field_type'] in settings.FIELD_TYPES:
field['section'] = section
id = specfields.create(**field)
result.append(id)
else:
return False
return result
def removeFields(section_id, ids_array):
section = Section.objects.get(id=section_id)
for id in ids_array:
try:
field = BaseField.objects.get(id=id)
field.delete()
except BaseField.DoesNotExist:
return False
return True
def getFields(section_id):
section = Section.objects.get(id=section_id)
fields = section.get_fields()
return fields<file_sep># -*- coding: utf-8 -*-
import re
from models import Hash
class HashingMiddleware:
link_pattern = re.compile(r"""<a\s*(?:href=['"](.*?)['"]){0,1}(.*?)hashed_link(.*?)>""")
widget_pattern = re.compile(r"""<div id='hashed-widget-(\d+)'></div>""")
def process_response(self, request, response):
try:
if request.user.is_staff == True:
return response
else:
# Hashing links
response.content = self.link_pattern.sub(self._hash_link, response.content)
# Hashing widgets
response.content = self.widget_pattern.sub(self._hash_widget, response.content)
return response
except AttributeError:
# redirect detected
return response
def _hash_link(self, m):
link = m.group(1)
hashed_link = Hash.link2hash(link)
return '<a href="#"%shash-string="%s"%s>' % (m.group(2), hashed_link, m.group(3))
def _hash_widget(self, m):
widget_id = m.group(1)
hashed_widget = Hash.widget2hash(widget_id)
return '<div class="hashed-widget" hash-string="%s"></div>' % (hashed_widget,)<file_sep># -*- coding: utf8 -*-
from django.contrib import admin
from models import Chat
admin.site.register(Chat)
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Globals, Position, QuestAnswer, Image, News, File, SpecialOffer, Feedback, FeedbackFlora, Tag, Pictures
# from utils.colorfield import ColorPickerWidget
class GlobalsAdmin(admin.ModelAdmin):
list_display = ('prop_name', 'value')
class QuestAnswerAdmin(admin.ModelAdmin):
list_display = ('author', 'question', 'publication_date', 'moderator', 'is_public',)
# filter_horizontal = ('tags',)
class NewsAdmin(admin.ModelAdmin):
list_display = ('caption', 'announce', 'text', 'date',)
prepopulated_fields = {'slug': ('caption',) }
class ReservationAdmin(admin.ModelAdmin):
list_display = ('sender', 'publication_date')
class PositionAdmin(admin.ModelAdmin):
list_display = ('article', 'caption')
filter_horizontal = ('tags',)
class TagAdmin(admin.ModelAdmin):
list_display = ('tag', 'name',)
ordering = ('tag',)
prepopulated_fields = {'name': ('tag',)}
admin.site.register(Globals, GlobalsAdmin)
admin.site.register(Position, PositionAdmin)
admin.site.register(QuestAnswer, QuestAnswerAdmin)
admin.site.register(Image)
admin.site.register(News, NewsAdmin)
admin.site.register(File)
admin.site.register(SpecialOffer)
admin.site.register(Feedback)
admin.site.register(FeedbackFlora)
admin.site.register(Tag, TagAdmin)
admin.site.register(Pictures)
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Section, SectionType
class SectionAdmin(admin.ModelAdmin):
list_display = ('caption', 'path', 'id')
prepopulated_fields = {'path': ('caption',)}
class SectionTypeAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('caption',)}
admin.site.register(Section, SectionAdmin)
admin.site.register(SectionType, SectionTypeAdmin)
<file_sep># -*- coding: utf-8 -*-
from django.db import models
class Phone(models.Model):
url_part = models.CharField(verbose_name="Корень категории с которой в глубь будет виден данный телефон", max_length=255)
phone = models.CharField(verbose_name="Phone number", max_length=255)
def __unicode__(self):
return self.phone
class IconCollection(models.Model):
section = models.ForeignKey('self', blank=True)
caption = models.CharField('Название', max_length=255)
slug = models.SlugField('SLUG', max_length=255)
icon = models.ImageField('Иконка', upload_to='imagesssss')
class Meta:
verbose_name_plural = 'Коллекция иконок'
def __unicode__(self):
return self.caption
<file_sep># -*- coding: utf-8 -*-
from seo.models import Metatag
from common.models import Phone
def seo_tags(request):
try:
return { 'metatag': Metatag.objects.get(name=request.path) }
except:
return {}
def phone(request):
try:
phone = Phone.objects.extra(
where=["url_part=(SELECT max(url_part) from globals_phone WHERE locate(url_part, %s)=1)"],
params=[request.path]
)[0]
return {'phone':phone}
except:
return {'phone':''}
def current_section(request):
return { 'current_section': request.current_section }
def structure(request):
return { 'structure': request.structure }<file_sep>from django import template
class AssignNode(template.Node):
def __init__(self, name, value):
self.name = name
self.value = value
def render(self, context):
context[self.name] = self.value.resolve(context, True)
return ''
class CreateArrayNode(template.Node):
def __init__(self, name):
self.name = name
def render(self, context):
context[self.name] = []
return ''
class AddToArrayNode(template.Node):
def __init__(self, name, value):
self.name = name
self.value = value
def render(self, context):
context[self.name].append(self.value.resolve(context, True))
return ''
def do_assign(parser, token):
bits = token.split_contents()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
value = parser.compile_filter(bits[2])
return AssignNode(bits[1], value)
def do_create_array(parser, token):
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError("'%s' tag takes one argument" % bits[0])
return CreateArrayNode(bits[1])
def do_add_to_array(parser, token):
bits = token.split_contents()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
value = parser.compile_filter(bits[2])
return AddToArrayNode(bits[1], value)
register = template.Library()
register.tag('assign', do_assign)
register.tag('create_array', do_create_array)
register.tag('add_to_array', do_add_to_array)
<file_sep># -*- coding: utf-8 -*-
import re
from django import template
register = template.Library()
@register.tag
def render_zone(parser, token):
bits = token.split_contents()
if len(bits) != 2:
raise template.TemplateSyntaxError("'%s' tag takes one argument" % bits[0])
return Zone(bits[1])
class Zone(template.Node):
def __init__(self, zone):
self.zone = zone
def render(self, context):
# global brackets
# zone_tag = self.nodelist.render(context)
self.zone = template.Variable(self.zone).resolve(context)
return self.zone.render(context)
<file_sep># -*- coding: utf-8 -*-
import datetime
import urllib
from django.db import models
from django.utils.encoding import smart_str
from widgets.models import Zone
class Group(models.Model):
name = models.SlugField("URL Slug", max_length=255, unique=True)
caption = models.CharField("Название", max_length=255)
group = models.ForeignKey("Group", related_name="subs", null=True,
blank=True, verbose_name="Группа")
def __unicode__(self):
if self.group:
return self.group.__unicode__() + ' / ' + self.caption
else:
return self.caption
def slug(self):
if self.group:
return self.group.slug() + '/' + self.name
else:
return self.name
class Article(models.Model):
name = models.SlugField("URL Slug", max_length=255, blank=True)
caption = models.CharField("Заголовок", max_length=255)
shortdesc = models.TextField("Краткое описание", blank=True)
date_written = models.DateField("Дата написания", default=datetime.datetime.now)
publish = models.BooleanField("Публиковать?", default=False)
author = models.CharField("<NAME>", null=True, blank=True, max_length=255)
label_text = models.CharField("Текст метки", null=True, blank=True, max_length=255)
label_color = models.CharField("Цвет метки", null=True, blank=True, max_length=6)
group = models.ForeignKey(Group, null=True, blank=True, verbose_name="Группа")
tags = models.ManyToManyField('Tag', blank=True)
zone = models.OneToOneField(Zone, null=True, blank=True)
seo_link_1 = models.ForeignKey('Article', related_name='back_seo_link_1',
null=True, blank=True, on_delete=models.SET_NULL)
seo_link_2 = models.ForeignKey('Article', related_name='back_seo_link_2',
null=True, blank=True, on_delete=models.SET_NULL)
seo_link_order = models.PositiveIntegerField(default=0)
seo_link_chunk = models.PositiveIntegerField(default=0)
def seo_link(self):
last_chunk = self.__class__.objects.values('seo_link_chunk') \
.order_by('-seo_link_chunk')[0]
last_chunk = last_chunk['seo_link_chunk']
# print 'last_chunk: ' + str(last_chunk)
last_order = self.__class__.objects.values('seo_link_order') \
.filter(seo_link_chunk=last_chunk) \
.order_by('-seo_link_order')[0]
last_order = last_order['seo_link_order']
# print 'last_order: ' + str(last_order)
if last_order == 10:
# Creating new chunk
self.seo_link_chunk = last_chunk + 1
self.seo_link_order = 1
# print 'last_order == 10'
elif last_order == 1:
# Second element will link to first only
self.seo_link_chunk = last_chunk
self.seo_link_order = 2
self.seo_link_1 = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=last_order
)
# print 'last_order == 1'
elif 2 <= last_order <= 8:
# Default linking
self.seo_link_chunk = last_chunk
self.seo_link_order = last_order + 1
self.seo_link_1 = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=last_order
)
self.seo_link_2 = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=last_order - 1
)
# print 'last_order in 2..8'
elif last_order == 9:
self.seo_link_chunk = last_chunk
self.seo_link_order = 10
self.seo_link_1 = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=last_order
)
self.seo_link_2 = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=last_order - 1
)
# Finishing chunk
first = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=1
)
second = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=2
)
nine = self.__class__.objects.get(
seo_link_chunk=last_chunk,
seo_link_order=9
)
first.seo_link_1 = nine
first.seo_link_2 = self
second.seo_link_2 = self
first.save()
second.save()
# print 'last_order == 9'
def save(self, *args, **kwargs):
# Creating zone for new article
if self.id == None:
zone = Zone()
zone.save()
self.zone = zone
super(Article, self).save(*args, **kwargs)
self.seo_link()
super(Article, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone.delete()
super(Article, self).delete(*args, **kwargs)
def __unicode__(self):
if self.group:
return self.group.__unicode__() + ' / ' + self.caption
else:
return '(No group) / ' + self.caption
def slug(self):
if self.group:
return self.group.slug() + '/' + self.name
else:
return self.name
def get_absolute_url(self):
slug = self.slug()
slug = slug.split('/')[1:]
slug = '/'.join(slug)
if slug:
return "/articles/%s/" % (slug)
else:
return '/'
class Tag(models.Model):
name = models.SlugField("URL Slug", max_length=255)
tag = models.CharField("Имя тэга", max_length=30)
def __unicode__(self):
return self.tag + ' (' + self.name + ')'<file_sep># -*- coding: utf-8 -*-
from models import ZoneProductHead, ZoneProductFoot
def zone_product_head(request):
return {'zone_product_head': ZoneProductHead.objects.get(pk=1)}
def zone_product_foot(request):
return {'zone_product_foot': ZoneProductFoot.objects.get(pk=1)}<file_sep># -*- coding: utf-8 -*-
#import hashlib
#import random
from core import *
from django import template
from django.db import models
from utils.sortable import SortableModel
from aphaline.decorators import aphaline_render_widget, aphaline_render_zone
class Zone(models.Model):
"""
Zone is the place where widgets could be inserted.
Don't try to get widgets using "widget_set", because
it will return instances of "Widget" class.
Use "Widget.objects.filter(zone=current_zone)" instead.
"""
@aphaline_render_zone
def render(self, context=None):
""" Renders zone (recursively, admin-compatible (?)) """
result = ''
widgets = Widget.objects.filter(zone=self)
if context is None:
context = template.Context()
for widget in widgets:
result += widget.render(context)
return result
def __unicode__(self):
return '#' + str(self.id)
class Widget(SortableModel):
"""
Widget is a piece of content with own type, template and properties.
It must be placed into zone.
"""
zone = models.ForeignKey('Zone', verbose_name="Зона для виджета")
type = models.CharField("Widget type (lowercase classname)", max_length=255,
null=True, blank=True)
is_hashed = models.BooleanField(default=False)
is_commentable = models.BooleanField(default=False)
base_objects = WidgetManager()
objects = WidgetLeafManager()
order_isolation_fields = ('zone',)
own_template = None
def __unicode__(self):
return self.type + '#' + str(self.id)
def save(self, *args, **kwargs):
# Setting type
if self.type is None:
self.type = self.__class__.__name__
# Saving
super(Widget, self).save(*args, **kwargs)
def as_leaf_class(self):
""" Method to return derived class instance """
widget_type = self.type
child_class = globals()[widget_type]
if widget_type == 'Widget':
return self
else:
return child_class.objects.get(pk=self.id)
@aphaline_render_widget
def render(self, context=None):
widget_type = self.type.lower()
if context is None:
context = template.Context()
context.push()
try:
context['current_widget'] = self.__getattribute__(widget_type)
except:
context['current_widget'] = self
if self.own_template is not None:
tpl = 'widgets/' + self.own_template + '.html'
else:
tpl = 'widgets/' + widget_type + '.html'
render = template.loader.render_to_string(tpl, context)
context.pop()
return render
def move_to_zone(self, zone, order=None):
""" Moves widget to given zone """
if zone != self.zone:
# Setting order of widget to last in old zone
# for other widgets to rearrange
self.move(-1)
# Changing zone and setting new order
self.zone = zone
self.order = 0
self.save()
if order is not None:
self.move(order)
else:
self.move(-1)
# Patch for ordering (subclasses used to order within subclass objects)
def _get_class(self):
return Widget
from set_grid import *
from set_headers import *
from set_text import *
from set_lists import *
# from set_tables import *
from set_media import *
from set_common import *
# from set_upload import *
<file_sep>$(document).ready(function() {
$('<div rel="hideLink" style="display:none;"></div>').appendTo($('body'));
var i = 0;
$('.catalogItem__small dt a, .catalogItem dt a').each(function() {
i++
$('<a href="' + $(this).attr('href') + '" id="popUp' + i + '" rel="hidePopUp">' + $(this).text() + '</a>').appendTo('div[rel=hideLink]');
$(this).attr('id', 'Up' + i);
$(this).unbind('click').click(function() {
$.fancybox.showActivity;
$('#pop' + $(this).attr('id')).click();
return false;
});
$(this).parent().parent().find('.photo a').unbind('click').attr('id', 'Up' + i).click(function() {
$.fancybox.showActivity;
$('#pop' + $(this).attr('id')).click();
return false;
});
});
$('a[rel=hidePopUp]').each(function() {
$(this).fancybox({
'width' : '85%',
'height' : '95%',
'autoScale' : false,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'type' : 'iframe',
'overlayOpacity' : 0.7,
'href' : $(this).attr('href') + '?ajax=1',
'title' : $(this).text(),
});
});
});<file_sep>def dict2htmlattrs(d):
return " ".join(["%s='%s'" % (k, v) for k, v in d.items()])<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# ...
#
create_group('icon', 'Иконка')
@add2group('Иконка', 'icon')
class SingleIcon(Widget):
icon = models.ImageField("Изображение", upload_to='images/icon', blank=True, null=True)
title = models.CharField('Текст заголовка', max_length=255, blank=True, null=True)
url = models.CharField('URL (без http)', max_length=255, blank=True, null=True)
description = models.TextField("Описание", blank=True, null=True)
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget, Zone
from grouping import create_group, add2group
create_group('grids', 'Сетка')
class GridWidget(Widget):
own_template = "grid"
GRID_CHOICES = (
(1, '100'),
(2, '50/50'),
(3, '66/33'),
(4, '33/66'),
(5, '33/33/33'),
)
grid_type = models.PositiveIntegerField("Grid type", choices=GRID_CHOICES)
grid_zone_1 = models.OneToOneField(Zone, related_name='grid_zone_1',
verbose_name='Zone 1', null=True, blank=True,
editable=False)
grid_zone_2 = models.OneToOneField(Zone, related_name='grid_zone_2',
verbose_name='Zone 2', null=True, blank=True,
editable=False)
grid_zone_3 = models.OneToOneField(Zone, related_name='grid_zone_3',
verbose_name='Zone 3', null=True, blank=True,
editable=False)
def columns(self):
cols = self.type.split('_')[1:]
remind = 0
result = []
for i in cols:
j = remind
remind = remind + int(i)
result.append((i, j))
return result
def save(self, *args, **kwargs):
if self.id is None:
zone_1 = Zone()
zone_1.save()
self.grid_zone_1 = zone_1
zone_2 = Zone()
zone_2.save()
self.grid_zone_2 = zone_2
zone_3 = Zone()
zone_3.save()
self.grid_zone_3 = zone_3
self.type = 'Grid_' + '_'.join(self.GRID_CHOICES[self.grid_type-1][1].split('/'))
super(GridWidget, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.grid_zone_1.delete()
self.grid_zone_2.delete()
self.grid_zone_3.delete()
super(GridWidget, self).delete(*args, **kwargs)
@add2group('100', 'grids')
class Grid_100(GridWidget):
def save(self, *args, **kwargs):
if (self.grid_type is None):
self.grid_type = 1
super(Grid_100, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('50/50', 'grids')
class Grid_50_50(GridWidget):
def save(self, *args, **kwargs):
if (self.grid_type is None):
self.grid_type = 2
super(Grid_50_50, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('66/33', 'grids')
class Grid_66_33(GridWidget):
def save(self, *args, **kwargs):
if (self.grid_type is None):
self.grid_type = 3
super(Grid_66_33, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('33/66', 'grids')
class Grid_33_66(GridWidget):
def save(self, *args, **kwargs):
if (self.grid_type is None):
self.grid_type = 4
super(Grid_33_66, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('33/33/33', 'grids')
class Grid_33_33_33(GridWidget):
def save(self, *args, **kwargs):
if (self.grid_type is None):
self.grid_type = 5
super(Grid_33_33_33, self).save(*args, **kwargs)
class Meta:
proxy = True
<file_sep>function basket_edit_add(position_id, size_id)
{
$.get("/api/basket/add/" + position_id + "/" + size_id + "/?rnd="+Math.random(), function(d) { window.location.reload() });
}
function basket_edit_del(position_id, size_id)
{
$.get("/api/basket/delete/" + position_id + "/" + size_id + "/?rnd="+Math.random(), function(d) { window.location.reload() });
}
function change_size(position_id, old_size_id, new_size_id)
{
$.get("/api/basket/change_size/" + position_id + "/" + old_size_id + "/" + new_size_id + "/?rnd="+Math.random(), function(d) { window.location.reload() });
}
<file_sep># -*- coding: utf-8 -*-
from models import Product, Catalog, Section, Pricing, ShoeSize
from django.db.models import Max, Min
def filter(request):
cs = request.current_section
non_sized_prices = Product.objects.filter(section__path__startswith=cs.path).aggregate(Min("price"), Max("price"))
sized_prices = Pricing.objects.filter(product__section__path__startswith=cs.path).aggregate(Min("price"), Max("price"))
sizes = ShoeSize.objects.filter(pricing__product__section__path__startswith=cs.path).distinct()
if non_sized_prices['price__max'] > sized_prices['price__max']:
price_max = non_sized_prices['price__max']
else:
price_max = sized_prices['price__max']
if non_sized_prices['price__min'] > sized_prices['price__min']:
price_min = non_sized_prices['price__min']
else:
price_min = sized_prices['price__min']
if not price_min: price_min = 0
if not price_max: price_max = 0
if not sizes: sizes = None
return {'filter': {'price_max': int(price_max), 'price_min': int(price_min), 'size': sizes }}
def nova(request):
products = Product.objects.all().order_by('-date')
for product in products:
if product.nova():
return {'nova': True}
return {}<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Section, SectionType
admin.site.register(Section)
admin.site.register(SectionType)
<file_sep>from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
#from filebrowser.sites import site
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include('filebrowser.urls')),
url(r'^admin/', include(admin.site.urls)),
# url(r'^admin/filebrowser/', include('filebrowser.urls')),
# url(r'^admin/filebrowser/', include(site.urls)),
url(r'^tinymce/', include('tinymce.urls')),
# Aphaline API
url(r'^api/aphaline/(\w+)/form/(?:(\d+)/){0,1}$', 'aphaline.api.form'),
url(r'^api/aphaline/(\w+)/change/(?:(\d+)/){0,1}$', 'aphaline.api.change'),
url(r'^api/aphaline/(\w+)/delete/(\d+)/$', 'aphaline.api.delete'),
# Login / logout
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
# Widgets API
url(r'^api/widgets/list/$', 'widgets.views.list'),
url(r'^api/widgets/create/(.*?)/$', 'widgets.views.create'),
url(r'^api/widgets/move/(.*?)/$', 'widgets.views.move'),
url(r'^api/widgets/delete/(.*?)/$', 'widgets.views.delete'),
url(r'^api/widgets/get/(.*?)/$', 'widgets.views.get'),
url(r'^api/widgets/form/(.*?)/$', 'widgets.views.form'),
url(r'^api/widgets/change/(.*?)/$', 'widgets.views.change'),
# Structure API and admin page
url(r'^api/structure/admin/$', 'structure.views.admin_page'),
url(r'^api/structure/list/$', 'structure.views.section_list'),
url(r'^api/structure/create/$', 'structure.views.create'),
url(r'^api/structure/rename/$', 'structure.views.rename'),
url(r'^api/structure/delete/(.*?)/$', 'structure.views.delete'),
url(r'^api/structure/move/$', 'structure.views.move'),
# Position move
url(r'^api/catalog/move/(\d+)/(\d+)/$', 'se.views.move_position'),
url(r'^tag/(?P<tag>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'se.views.tag'),
url(r'^.*?/$', 'structure.dispatcher.dispatch'),
url(r'^$', 'structure.dispatcher.dispatch'),
)
<file_sep>var IndexGallery = Base.extend({
constructor: function() {
this._container = $(".index_gallery");
this._gallery = $(".index_gallery_list");
this._pics = $(".illustrations li");
//this._gallery.empty();
// $.getJSON('/json/', function(data) {
// json = new Array();
// json = data;
// for (var i = 0; i < data.length; i++) {
// $('.illustrations').append('<li id="illustration_' + i + '><img src="media/' + data[i].big_sharp_picture + '" alt="" /><ins></ins></li>');
// $('.index_gallery_list').append('<li class="index_gallery_item index_gallery_item__selected" rel="illustration_' + i + '"><span class="title"><a href="#">' + i + 'Кирпич</a></span><span class="text colored_bgColor"><NAME><br/><a href="#" class="blackLink">Кирпич</a></span></li>')
// };
// });
// $.getJSON('/json/', function(data) {
// json = new Array();
// json = data
// // for (var i = 0; i < json.length; i++) {
// // $('.illustrations').append('<li id="illustration_' + i '"><img src="' + i['big_sharp_picture'] + '" alt="" /><ins></ins></li>')
// // };
// for (var i = 0; i < json.length; i++) {
// $('.illustrations').append('<li id="illustration_' + i '"><img src="' + i['big_sharp_picture'] + '" alt="" /><ins></ins></li>')
// $('.index_gallery_list').append('<li class="index_gallery_item index_gallery_item__selected" rel="illustration_1"><span class="title"><a href="#">' + i + 'Кирпич</a></span><span class="text colored_bgColor"><NAME><br/><a href="#" class="blackLink">Кирпич</a></span></li>')
// };
// });
this.updateItems();
this._itemsCount = this._items.length;
if ($("body").hasClass(IndexGallery.enabledClass)) {
this.loadInit();
}
},
loadInit: function() {
var _this = this;
$(window).load(function() {
_this._pics.each(function() {
$(this).css({
visibility: "visible",
display: "none"
});
});
_this._container.css({ visibility: "visible" });
_this.updateSelectedPic();
_this.updateHeight();
_this.register();
});
$(window).resize(function() {
_this.updateHeight();
});
},
register: function() {
var number = this.getSelectedNumber();
var _this = this;
this._gallery.jcarousel({
scroll: 1,
start: number,
buttonNextHTML: "<div><span></span></div>",
buttonPrevHTML: "<div><span></span></div>",
itemFallbackDimension: 750,
wrap: "circular",
itemFirstInCallback: {
onBeforeAnimation: function(arg, selected, index, state){
if (state != "init") {
selected = $(selected);
_this.updateIllustration(state, selected);
_this.updateFooterGallery(state);
$(".footer_gallery .jcarousel-"+state).trigger("click");
}
}
}
});
},
updateItems: function() {
this._items = this._gallery.find(".index_gallery_item");
},
updateSelectedPic: function() {
var oldSelected = this._pics.filter("." + IndexGallery.selectedPicClass);
var newSelected = $("#" + this.getSelected().attr("rel"));
if (oldSelected.length != 0)
oldSelected
.removeClass(IndexGallery.selectedPicClass)
.hide();//("slow");
newSelected
.addClass(IndexGallery.selectedPicClass)
.show();//.fadeIn("slow");
$(".illustrations li img").attr('src', '#');
this.applySrcFromPresrc(newSelected);
this.applySrcFromPresrc(newSelected.prev());
this.applySrcFromPresrc(newSelected.next());
},
applySrcFromPresrc: function(item) {
var presrc = item.find('img').attr('presrc');
item.find('img').attr('src', presrc);
},
updateIllustration: function(direction, item) {
this.updateItems();
var selected = this.getSelected();
if (item.length != 0) {
selected.removeClass(IndexGallery.selectedClass);
item.addClass(IndexGallery.selectedClass);
this.updateSelectedPic();
}
},
updateFooterGallery: function(direction) {
var selected = $("." + FooterGallery.selectedClass);
var item = direction == "prev" ? selected.prev() : selected.next();
if (item.length != 0) {
selected.removeClass(FooterGallery.selectedClass);
item.addClass(FooterGallery.selectedClass);
}
},
updateHeight: function() {
var height = $(window).height() - 248;
height = height < 200 ? 200 : height;
this._container.css({ height: height });
},
getSelected: function() {
return this._items.filter("." + IndexGallery.selectedClass);
},
getSelectedNumber: function() {
var counter = 0;
var number = 1;
this._items.each(function() {
counter++;
if ($(this).hasClass(IndexGallery.selectedClass))
number = counter;
});
return number;
}
}, {
selectedClass: "index_gallery_item__selected",
selectedPicClass: "illustrations_item__selected",
enabledClass: "index_gallery_enabled"
});<file_sep># -*- coding: utf-8 -*-
from django.db import models
class Title(models.Model):
TITLE_POSITION_CHOICES = (
(1, '#-^--'),
(2, '-#^--'),
(3, '--^#-'),
(4, '--^-#')
)
position = models.PositiveIntegerField('Позиция', choices= TITLE_POSITION_CHOICES)
title = models.CharField('Заголовок', max_length=255, blank=True)
class Meta:
verbose_name = 'Шаблон заголовков'
verbose_name_plural = 'Шаблоны заголовков'
def __unicode__(self):
return '%s (%s)' % (self.title, self.get_position_display())
class ChangeTitle(models.Model):
path = models.CharField('PATH', max_length=255)
title = models.CharField('Заголовок', max_length=255)
class Meta:
verbose_name = 'Заголовок'
verbose_name_plural = 'Заголовки'
def __unicode__(self):
return self.title
<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from set_filter import *
from models import Group, Catalog, Manufacturer, TypeA, TypeB, Product, Picture, GroupingUnit, Alphabet, ManufacturerZoneUrl, CatalogBrandType
import json
def index(request):
context = RequestContext(request)
context['groups'] = Group.objects.all()
context['alphabet'] = Alphabet.objects.filter(is_action=True).order_by('letter')
return render_to_response('catalog/index.html', context)
def catalogue(request, slug, product=None, set=None):
context = RequestContext(request)
if set:
context['current_set'] = get_object_or_404(Set, slug=set)
context['products_set'] = set_catalog(slug, set)
return render_to_response('catalog/catalog_set.html', context)
context['catalog'] = get_object_or_404(Catalog, slug=slug)
if product:
context['product'] = get_object_or_404(Product, catalog=context['catalog'], slug=product)
context['image'] = context['product'].picture.all()[0]
#if ajax popupwindow request
if request.GET.has_key('ajax'):
return render_to_response('catalog/catalog_items_ajax.html', context)
return render_to_response('catalog/catalog_items.html', context)
else:
context['types_a'] = TypeA.objects.filter(catalog=context['catalog'], show_on_site=True)
context['types_b'] = TypeB.objects.filter(catalog=context['catalog'], show_on_site=True)
context['manufacturers'] = Manufacturer.objects.filter(catalog=context['catalog'], show_on_site=True)
try:
context['products'] = get_catalog(slug)
context['set'] = True
except:
context['products'] = Product.objects.filter(catalog=context['catalog'])[0:6]
return render_to_response('catalog/catalog.html', context)
def type_or_brand(request, catalog, type_or_brand, product=None, set=None):
"""
В данной функции идёт обработка приходящего урла с выявлением, Тип это или Производитель.
"""
context = RequestContext(request)
context['catalog'] = get_object_or_404(Catalog, slug=catalog)
context['type_or_brand_slug'] = type_or_brand
context['catalog_slug'] = catalog
try:
if Manufacturer.objects.get(catalog=context['catalog'], slug=type_or_brand):
if set:
context['current_set'] = get_object_or_404(Set, slug=set)
context['products_set'] = set_brand(catalog, type_or_brand, set)
return render_to_response('catalog/catalog_set.html', context)
context['catalog'] = get_object_or_404(Manufacturer, catalog=context['catalog'], slug=type_or_brand)
#Уникальность зон для производителя
zones = context['catalog'].get_zone(request.path)
context['zone_title'] = zones['zone_title']
context['zone_medium_one'] = zones['zone_medium_one']
context['zone_medium_two'] = zones['zone_medium_two']
context['type_or_brand_products'] = [type.type.all() for type in CatalogBrandType.objects.filter(catalog=get_object_or_404(Catalog, slug=catalog), brand=context['catalog'])][0]
context['manufacturer'] = True
except:
try:
if TypeA.objects.get(catalog=context['catalog'], slug=type_or_brand):
if set:
context['current_set'] = get_object_or_404(Set, slug=set)
context['products_set'] = set_type(catalog, type_or_brand, set)
return render_to_response('catalog/catalog_set.html', context)
context['catalog'] = get_object_or_404(TypeA, catalog=context['catalog'], slug=type_or_brand)
context['type_or_brand_products'] = [brand.brand for brand in CatalogBrandType.objects.filter(catalog=get_object_or_404(Catalog, slug=catalog), type=context['catalog'])]
context['type'] = True
except:
if get_object_or_404(TypeB, catalog=context['catalog'], slug=type_or_brand):
if set:
context['current_set'] = get_object_or_404(Set, slug=set)
context['products_set'] = set_type(catalog, type_or_brand, set)
return render_to_response('catalog/catalog_set.html', context)
context['catalog'] = get_object_or_404(TypeB, catalog=context['catalog'], slug=type_or_brand)
context['type_or_brand_products'] = [brand.brand for brand in CatalogBrandType.objects.filter(catalog=get_object_or_404(Catalog, slug=catalog), type=context['catalog'])]
context['type'] = True
if product:
if context.has_key('brand'):
context['product'] = get_object_or_404(Product, manufacturer=context['brand'], slug=product)
elif context.has_key('types'):
context['product'] = get_object_or_404(Product, types=context['types'], slug=product)
context['image'] = context['product'].picture.all()[0]
#if ajax popupwindow request
if request.GET.has_key('ajax'):
return render_to_response('catalog/catalog_items_ajax.html', context)
return render_to_response('catalog/catalog_items.html', context)
return render_to_response('catalog/catalog_type_or_brand.html', context)
def brand_type(request, catalog, brand, type, product=None, set=None):
context = RequestContext(request)
if set:
context['current_set'] = get_object_or_404(Set, slug=set)
#context['products_set'] = set_brand_and_type(catalog, type_or_brand, set)
return render_to_response('catalog/catalog_set.html', context)
context['catalog'] = get_object_or_404(Catalog, slug=catalog)
context['manufacturer'] = get_object_or_404(Manufacturer, catalog=context['catalog'], slug=brand)
context['type'] = get_object_or_404(TypeA, catalog=context['catalog'], slug=type)
if product:
context['product'] = get_object_or_404(Product, types=context['type'], manufacturer=context['manufacturer'], slug=product)
pics = context['product'].picture.all()
if pics: context['image'] = pics[0]
#if ajax popupwindow request
if request.GET.has_key('ajax'):
return render_to_response('catalog/catalog_items_ajax.html', context)
return render_to_response('catalog/catalog_items.html', context)
return render_to_response('catalog/catalog_type_or_brand.html', context)
def brand_type_set(request, catalog, brand, type, set, product=None, current_set=None):
context = RequestContext(request)
if current_set:
context['current_set'] = get_object_or_404(Set, slug=set)
#context['products_set'] = set_brand_and_type(catalog, type_or_brand, current_set)
return render_to_response('catalog/catalog_set.html', context)
context['catalog'] = get_object_or_404(Catalog, slug=catalog)
context['manufacturer'] = get_object_or_404(Manufacturer, catalog=context['catalog'], slug=brand)
context['type'] = get_object_or_404(TypeA, catalog=context['catalog'], slug=type)
if product:
context['product'] = get_object_or_404(Product, types=context['type'], manufacturer=context['manufacturer'], slug=product)
try:
context['image'] = context['product'].picture.all()[0]
except:
pass
#if ajax popupwindow request
if request.GET.has_key('ajax'):
return render_to_response('catalog/catalog_items_ajax.html', context)
return render_to_response('catalog/catalog_items.html', context)
context['products'] =Product.objects.filter(types=context['type'], manufacturer=context['manufacturer'])
return render_to_response('catalog/catalog_type_or_brand.html', context)
def get_many_products(request):
if request.POST.get('data'):
context = RequestContext(request)
data = json.loads(data)
pos = data['position']
path = data['path'][1:-1].split('/')[1:]
if path:
length = len(path)
if length == 1:
# /production/catalog/
context['products'] = Product.objects.filter(catalog=get_object_or_404(Catalog, slug=path[0]))[pos, pos+6]
elif length == 2:
# /production/catalog/brand or type/
try:
brand = Manufacturer.objects.get(slug=path[1])
context['products'] = Product.objects.filter(catalog=get_object_or_404(Catalog, slug=path[0]), manufacturer=brand)[pos, pos+6]
except:
type = TypeA.objects.get(slug=path[1])
context['products'] = Product.objects.filter(catalog=get_object_or_404(Catalog, slug=path[0]), types=type)[pos, pos+6]
elif length == 3:
# /production/catalog/type/brand/
context['products'] = Product.objects.filter(catalog=get_object_or_404(Catalog, slug=path[0]),
types=get_object_or_404(TypeA, slug=path[1]),
manufacturer=get_object_or_404(Manufacturer, slug=path[3]))[pos, pos+6]
if len(context['products']) < 6:
pass
return render_to_response('catalog/many_products_ajax.html', context)
else:
return 'This is root, not path'
else:
return 'Not data'
#def grouping_unit(request, catalog, grouping_unit):
# context = RequestContext(request)
# context['catalog'] = get_object_or_404(Catalog, slug=catalog)
# context['unit'] = get_object_or_404(GroupingUnit, slug=grouping_unit)
# return render_to_response('catalog/grouping_unit.html', context)
#
#def product(request, product):
# context = RequestContext(request)
# context['product'] = get_object_or_404(Product, slug=product)
# context['image'] = context['product'].picture.all()[0]
# return render_to_response('catalog/catalog_items.html', context)
<file_sep>from section_tests import *
from specfield_tests import *
from good_tests import *
from brand_tests import *<file_sep># -*- coding: utf-8 -*-
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from utils.tree import build_tree
from utils.decorators import staff_required
from structure.models import Section, SectionType
from models import Position, QuestAnswer, Image, News, File, SpecialOffer, Feedback, Tag, FeedbackFlora, Pictures
from basket import Basket
from shortcuts import paginate
NEWS_ON_PAGE = 10
QA_ON_PAGE = 10
TOV_ON_PAGE = 12
TAG_ON_PAGE = 10
def index(request):
context = RequestContext(request)
context['title'] = u'Главная страница'
context['news'] = News.objects.filter(section=Section.objects.get(path='/news/')).order_by('-date')[:3]
context['tags'] = Tag.objects.all()
# files...
return render_to_response('flora/index.html', context)
def text(request):
context = RequestContext(request)
context['title'] = u'Главная страница'
return render_to_response('flora/text.html', context)
def form(request):
# return HttpResponse('Form page')
context = RequestContext(request)
context['title'] = u'Главная страница'
c = {}
c.update(csrf(request))
# forms = {}
# # kol = {}
# all_price = 0
# for key in request.session.keys():
# if is_numeric(key):
# tov = Position.objects.get(pk=key)
# price = tov.price_rozn*request.session[key]
# all_price += price
# forms[key] = {'tov':Position.objects.get(pk=key).get_all,
# 'kol':request.session[key],
# 'price':price}
# else:
# continue
# if len(forms) > 0:
# context['forms'] = forms
# context['all_price'] = all_price
context['c'] = c
context['title'] = u'Обратная связь'
context['fio_error'] = False
context['cont_error'] = False
context['mes_error'] = False
if request.method == 'POST':
if not request.POST.get('r_autor', ''):
context['fio_error'] = True
else:
context['r_autor'] = request.POST['r_autor']
if not request.POST.get('r_cont', ''):
context['cont_error'] = True
else:
context['r_cont'] = request.POST['r_cont']
if not request.POST.get('r_mes', ''):
context['mes_error'] = True
else:
context['r_mes'] = request.POST['r_mes']
if context['fio_error'] or context['cont_error'] or context['mes_error']:
return render_to_response('flora/form.html', context)
else:
# if context['forms']:
# send_mail(u'Заказ',
# u'Автор: ' + context['r_autor'] +
# u'.\r\n Контактная информация: ' + context['r_cont'] +
# u'. Сообщение: ' + context['r_mes'] +
# u'Заказал ' + '' + u'шт. товара, на сумму ' + str(context['all_price']),
# '<EMAIL>',
# ['<EMAIL>',],
# )
# reservation = Reservation(form=order['order'],sender = context['r_autor'], contact = context['r_cont'], message = context['r_mes'])
# reservation.save()
# return HttpResponseRedirect('/form/')
# else:
# send_mail(u'Заявка с сайта',
# u'Автор: ' + context['r_autor'] +
# u'.\r\n Контактная информация: ' + context['r_cont'] +
# u'. Сообщение: ' + context['r_mes'],
# '<EMAIL>',
# ['<EMAIL>',],
# )
form = Feedback(sender=context['r_autor'], contact=context['r_cont'], message=context['r_mes'])
form.save()
return HttpResponseRedirect('/form/')
else:
return render_to_response('flora/form.html', context)
def catalog_list(request, page=None):
context = RequestContext(request)
context['title'] = u'Портфолио'
paginate(
context, 'catalog',
Position.objects.filter(section=context['current_section']).order_by('order'),
count=TOV_ON_PAGE, page=page,
root=context['current_section'].path
)
basket = Basket(request.session)
for position in context['catalog']:
position.count_in_basket = basket.position_count(position.id)
return render_to_response('flora/catalog.html', context)
def catalog_item(request, position_id):
context = RequestContext(request)
context['title'] = u'Портфолио'
context['position'] = get_object_or_404(Position, pk=position_id)
context['position_image'] = Position.get_image(position_id)[0]
context['gallery'] = Pictures.get_image(position_id, 'Pictures')
basket = Basket(request.session)
context['position'].count_in_basket = basket.position_count(position_id)
return render_to_response('flora/catalog-item.html', context)
@staff_required
def catalog_all(request):
context = RequestContext(request)
context['title'] = u'Портфолио'
context['catalog_all'] = Position.objects.filter(section=context['current_section']).order_by('order')
return render_to_response('flora/catalog-all.html', context)
@staff_required
def move_position(request, id, new_order):
try:
position = Position.objects.get(pk=id)
position.move(new_order)
position.save()
return HttpResponse('OK')
except:
return HttpResponse('BAD')
def tag(request, tag, page=None):
context = RequestContext(request)
context['title'] = u'Tag'
context['tagview'] = get_object_or_404(Tag, name=tag)
paginate(
context, 'catalog',
query=Position.objects.filter(tags__name__exact=tag),
count=TAG_ON_PAGE, page=page,
root=request.current_section.path+tag+'/'
)
return render_to_response('flora/tag.html', context)
########BASKET########
##------ADD------
#def add_to_basket(request, position_id):
# context = RequestContext(request)
# basket = Basket(request)
# basket.add(position_id, 1)
#
# if request.GET.get('redirect_to'):
# return HttpResponseRedirect(request.GET['redirect_to'])
# else:
# import json
# return HttpResponse(json.dumps(basket.session['basket']))
#
##------DELETE------
#def del_to_basket(request, item_catalog=None, redirect=None):
# item_catalog = int(item_catalog)
# context = RequestContext(request)
# get_object_or_404(Position, pk=item_catalog)
#
# if request.session.get(item_catalog, None):
# if request.session[item_catalog] <= 1:
# del request.session[item_catalog]
# if redirect == 'form':
# return HttpResponseRedirect('/form/')
# else:
# return HttpResponseRedirect('../')
# else:
# request.session[item_catalog] -= 1
#
# if redirect == None:
# return HttpResponseRedirect('../#add')
# elif redirect == 'form':
# return HttpResponseRedirect('/form/')
# else:
# return HttpResponseRedirect('/')
#
##------REMOVE------
#def rem_to_basket(request):
# if request.session.get('basket', None):
# del request.session['basket']
# return HttpResponseRedirect('/form/')
# else:
# return HttpResponseRedirect('/form/')
#
#########END_BASKET########
def news(request, slug=None, item_news=None, page=None):
context = RequestContext(request)
context['title'] = u'Новости'
if slug is None and item_news is None and news:
paginate(
context, 'news',
News.objects.filter(section=context['current_section']).order_by('-date'),
count=NEWS_ON_PAGE, page=page,
root='/news/'
)
return render_to_response('flora/news.html', context)
elif item_news is None and slug is not None:
context['news'] = get_object_or_404(News, slug=slug)
return render_to_response('flora/news-item.html', context)
elif slug is None and item_news is not None:
context['news'] = get_object_or_404(News, pk=item_news)
return render_to_response('flora/news-item.html', context)
def article(request, slug=None, item_news=None, page=None):
context = RequestContext(request)
context['title'] = u'Статьи'
if slug is None and item_news is None:
paginate(
context, 'news',
News.objects.filter(section=context['current_section']).order_by('-date'),
count=NEWS_ON_PAGE, page=page,
root='/article/'
)
return render_to_response('flora/article.html', context)
elif item_news is None and slug is not None:
context['news'] = get_object_or_404(News, slug=slug)
return render_to_response('flora/article-item.html', context)
elif slug is None and item_news is not None:
context['news'] = get_object_or_404(News, pk=item_news)
return render_to_response('flora/article-item.html', context)
def questanswer(request, page=None):
context = RequestContext(request)
context['title'] = u'Вопрос-ответ'
if request.method == 'POST':
context['author_error'] = False
context['mes_error'] = False
if not request.POST.get('q_autor', ''):
context['author_error'] = True
else:
context['q_autor'] = request.POST['q_autor']
if not request.POST.get('q_mes', ''):
context['mes_error'] = True
else:
context['q_mes'] = request.POST['q_mes']
if context['author_error'] or context['mes_error']:
pass
else:
qa = QuestAnswer(author=context['q_autor'], question=context['q_mes'])
qa.save()
context['ok'] = True
paginate(
context, 'questanswer',
QuestAnswer.objects.order_by('-publication_date').filter(is_public=True),
count=QA_ON_PAGE, page=page,
root=context['current_section'].path
)
return render_to_response('flora/questanswer.html', context)
def feedbackflora(request, page=None):
context = RequestContext(request)
context['title'] = u'Отзыв'
if request.method == 'POST':
context['author_error'] = False
context['mes_error'] = False
if not request.POST.get('q_autor', ''):
context['author_error'] = True
else:
context['q_autor'] = request.POST['q_autor']
if not request.POST.get('q_mes', ''):
context['mes_error'] = True
else:
context['q_mes'] = request.POST['q_mes']
if context['author_error'] or context['mes_error']:
pass
else:
qa = FeedbackFlora(
author=context['q_autor'],
question=context['q_mes'],
work=request.POST.get('q_work', ''),
punkt=request.POST.get('q_punkt', ''),
)
qa.save()
context['ok'] = True
paginate(
context, 'feedbackflora',
FeedbackFlora.objects.order_by('-publication_date').filter(is_public=True),
count=QA_ON_PAGE, page=page,
root=context['current_section'].path
)
context['unanswered'] = FeedbackFlora.objects.order_by('-publication_date').filter(is_public=False)
return render_to_response('flora/questanswer.html', context)
<file_sep># -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from django.forms import ModelForm
from django.db.models import Model
from structure.models import Section
from catalog.models import *
# from questanswer.models import QuestAnswer
# from articles.models import Article
# from seo.models import Metatag
from utils.decorators import staff_required
@staff_required
def delete(request, model, id):
model_class = globals()[model]
if not issubclass(model_class, Model):
return HttpResponse('Invalid model', status=400)
model_class.objects.get(pk=id).delete()
return HttpResponse('Ok')
@staff_required
def form(request, model, id=None):
model_class = globals()[model]
if not issubclass(model_class, Model):
return HttpResponse('Invalid model', status=400)
class AutoForm(ModelForm):
class Meta:
model = model_class
# exclude = ('zone', 'order', 'type', 'is_hashed', 'is_commentable')
if id is not None:
item = model_class.objects.get(pk=id)
form = AutoForm(instance=item)
else:
id = ''
form = AutoForm(initial=dict(request.POST.items()))
path = request.GET.get('path', '')
result = """
<form method="post" enctype="multipart/form-data"
action="/api/aphaline/%s/change/%s/">
<table>
%s
<tr>
<td colspan="2" style="text-align: center">
<input type="hidden" name="current_section" value="%s" />
<input type="submit" name="submit_legacy" value="%s" />
</td>
</tr>
</table>
</form>
""" % (model, str(id), form.as_table(), path, u"Сохранить")
return HttpResponse(result)
@staff_required
def change(request, model, id=None):
model_class = globals()[model]
if not issubclass(model_class, Model):
return HttpResponse('Invalid model', status=400)
class AutoForm(ModelForm):
class Meta:
model = model_class
# exclude = ('zone', 'order', 'type', 'is_hashed', 'is_commentable')
if id is not None:
item = model_class.objects.get(pk=id)
form = AutoForm(request.POST, request.FILES, instance=item)
else:
form = AutoForm(request.POST, request.FILES)
form.save()
return HttpResponse('Ok')
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from widgets.models import Zone
class Article(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
is_active = models.BooleanField(default=False)
zone = models.OneToOneField(Zone, null=True, blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if self.id == None:
zone = Zone()
zone.save()
self.zone = zone
super(Article, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone.delete()
super(Article, self).delete(*args, **kwargs)
<file_sep># -*- coding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from models import Document
def root(request, document_id):
context = RequestContext(request)
context['document'] = get_object_or_404(Document, pk=document_id)
return render_to_response('root.html', context)
def part(request, document_id, path):
context = RequestContext(request)
context['document'] = get_object_or_404(Document, pk=document_id)
context['part'] = context['document'].get_part_by_path(path)
return render_to_response('part.html', context)
def structure(request, document_id):
context = RequestContext(request)
context['document'] = get_object_or_404(Document, pk=document_id)
context['structure'] = context['document'].get_parts_tree()
return render_to_response('structure.html', context)
def glossary(request, document_id):
context = RequestContext(request)
context['document'] = get_object_or_404(Document, pk=document_id)
return render_to_response('glossary.html', context)
<file_sep># -*- coding: utf-8 -*-
from catalogapp import models
from catalogapp.models import BaseField
def create(field_type, name, slug, section, default_value, description, choices=None):
# Get field class
field_class = getattr(models, field_type)
# Create new instance
new_field = field_class(
name=name, slug=slug, section=section,
default_value=default_value, description=description
)
# Only for Choice and MultipleChoice fields
if (field_type=='ChoiceField' or field_type=='MultipleChoiceField') and not choices is None:
new_field.choices = choices
new_field.save()
return new_field.id
def change(id, name, slug, default_value, description):
try:
field = BaseField.objects.get_subclass(id=id)
except BaseField.DoesNotExist:
return False
field.name = name
field.slug = slug
field.default_value = default_value
field.description = description
field.save()
return field.id
def get(id):
try:
basefield = BaseField.objects.get_subclass(id=id)
except BaseField.DoesNotExist:
return False
return basefield
def list(**filters):
return BaseField.objects.filter(**filters).select_subclasses()
def listIn(ids):
return BaseField.objects.filter(id__in=ids).select_subclasses()<file_sep>var Links = Base.extend({
render: function() {
this.renderBlankLinks();
},
renderBlankLinks: function() {
var blankLinks = $("a[target='_blank']");
blankLinks.each(function() {
$(this).addClass("blankLink");
$(this).wrapInner("<span></span>");
if ($(this).hasClass("blackLink")) $(this).addClass("blankLink__black");
if ($(this).hasClass("redLink")) $(this).addClass("blankLink__red");
if ($(this).hasClass("whiteLink")) $(this).addClass("blankLink__white");
});
}
});<file_sep># -*- coding: utf-8 -*-
from datetime import date
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from models import Group, Article, Tag
from utils.shortcuts import paginate
from utils.tree import build_tree
ARTICLES_ON_PAGE = 10
def index(request, page=None):
context = RequestContext(request)
# create_widgets_context(context, 'articles_index', 1, 1)
groups = Group.objects.all().order_by('id').values()
context['groups'] = build_tree(groups, 'group_id')
paginate(
context, 'articles',
Article.objects.order_by('-date_written'),
count=ARTICLES_ON_PAGE, page=page,
root=request.current_section.path
)
return render_to_response('articles/index.html', context)
def section(request, section, page=None):
context = RequestContext(request)
groups = Group.objects.all().order_by('id').values()
context['groups'] = build_tree(groups, 'group_id')
context['section'] = get_object_or_404(Group, name=section)
paginate(
context, 'articles',
query=context['section'].article_set.all(),
count=ARTICLES_ON_PAGE, page=page,
root=request.current_section.path+section+'/'
)
return render_to_response('articles/section.html', context)
def article(request, section, article):
article = get_object_or_404(Article, name=article)
context = RequestContext(request)
groups = Group.objects.all().order_by('id').values()
context['groups'] = build_tree(groups, 'group_id')
context['section'] = get_object_or_404(Group, name=section)
context['article'] = article
return render_to_response('articles/article.html', context)
def tag(request, tag, page=None):
context = RequestContext(request)
groups = Group.objects.all().order_by('id').values()
context['groups'] = build_tree(groups, 'group_id')
context['tagview'] = get_object_or_404(Tag, name=tag)
paginate(
context, 'articles',
query=Article.objects.filter(tags__name__exact=tag).order_by('-date_written'),
count=ARTICLES_ON_PAGE, page=page,
root=request.current_section.path+tag+'/'
)
return render_to_response('articles/tag.html', context)
<file_sep># -*- coding: utf-8 -*-
import os
from django.db import models
from django.conf import settings
from widgets.models import Zone
from pixelion.utils.sortable import SortableModel
IMAGE_OPTIONS = [ {'type': 'p', 'size': 150, 'quality': 100},
{'type': 'w', 'size': 263, 'quality': 100},
{'type': 'w', 'size': 345, 'quality': 100},
{'type': 'w', 'size': 49, 'quality': 100},
{'type': 'h', 'size': 257, 'quality': 100} ]
def thumbnail(path, image_options, action=True):
"""
path - путь до изображения
image_options - словарь содержащий параметры
action - Действие (True - create, False - delete)
"""
original_image_name = path.split('/')[-1]
original_image_path = path.split('/')[0:-1]
original_image_path = '/'.join(original_image_path)
name, ext = original_image_name.split('.')
if action:
import Image
width, height = Image.open(settings.MEDIA_ROOT +'/'+ path).size
fp = open(settings.MEDIA_ROOT + path, 'rb')
im = Image.open(fp)
if type(image_options) is list:
for options in image_options:
if options['type'] == 'p':
if type(options['size']) is tuple:
im.thumbnail((options['size'][0], options['size'][1]), Image.ANTIALIAS)
im.save('%s/%s/%s_%sx%s.%s' %
(settings.MEDIA_ROOT, original_image_path, name, options['size'][0], \
options['size'][1], ext), quality=options['quality'])
else:
im.thumbnail((options['size'], options['size']), Image.ANTIALIAS)
im.save('%s/%s/%s_%sx%s.%s' %
(settings.MEDIA_ROOT, original_image_path, name, options['size'], \
options['size'], ext), quality=options['quality'])
elif options['type'] == 'w':
factor = height / (width / options['size'])
im.resize((options['size'], factor), Image.ANTIALIAS).save('%s/%s/%s_width_%s.%s'
% (settings.MEDIA_ROOT, original_image_path, name,\
options['size'], ext), quality=options['quality'])
elif options['type'] == 'h':
factor = width / (height / options['size'])
im.resize((factor, options['size']), Image.ANTIALIAS).save('%s/%s/%s_height_%s.%s'
% (settings.MEDIA_ROOT, original_image_path, name,\
options['size'], ext), quality=options['quality'])
fp.close()
else:
image_options.append({'type': 'original'})
for options in image_options:
if options['type'] == 'p':
if type(options['size']) is tuple:
path = '%s/%s/%s_%sx%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'][0], options['size'][1], ext)
else:
path = '%s/%s/%s_%sx%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'], options['size'], ext)
elif options['type'] == 'w':
path = '%s/%s/%s_width_%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'], ext)
elif options['type'] == 'h':
path = '%s/%s/%s_height_%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, options['size'], ext)
else:
path = '%s/%s/%s.%s' % (settings.MEDIA_ROOT, original_image_path, name, ext)
if os.path.exists(path):
os.remove(path)
class Group(SortableModel):
name = models.CharField("Имя", max_length=255)
slug = models.SlugField("URL Slug", max_length=255)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Группа'
verbose_name_plural = 'Группы'
class Catalog(models.Model):
"""
docstring for Catalog
"""
group = models.ManyToManyField(Group, verbose_name="Группы")
name_short = models.CharField("Короткое имя", max_length=255)
slug = models.SlugField("URL Slug", max_length=255)
name_long = models.CharField("Название на главной", max_length=255, blank=True)
description = models.TextField("Описание", blank=True)
link_text = models.CharField("Текст ссылки", max_length=255, blank=True, default="Узнайте больше")
type_a_name = models.CharField('Тип A', max_length=255, blank=True,)
type_b_name = models.CharField('Тип B', max_length=255, blank=True,)
big_sharp_picture = models.ImageField("Большое четкое изображение на главную", upload_to="catalogs", blank=True)
big_blurry_picture = models.ImageField("Большое размытое изображение на внутреннюю", upload_to="catalogs", blank=True)
medium_thumb = models.ImageField("Среднее изображение в список каталогов", upload_to="catalogs", blank=True)
small_thumb = models.ImageField("Малое изображение во всплывающую панель", upload_to="catalogs", blank=True)
zone_title = models.OneToOneField(Zone, null=True, blank=True, editable=False)
zone_medium_one = models.OneToOneField(Zone, related_name="medium_one_zone", null=True, blank=True, editable=False)
zone_medium_two = models.OneToOneField(Zone, related_name="medium_two_zone", null=True, blank=True, editable=False)
class Meta:
verbose_name = 'Каталог'
verbose_name_plural = 'Каталоги'
def __unicode__(self):
return unicode(self.name_short)
def save(self, *args, **kwargs):
if self.id == None:
zone_title = Zone()
zone_title.save()
self.zone_title = zone_title
zone_medium_one = Zone()
zone_medium_one.save()
self.zone_medium_one = zone_medium_one
zone_medium_two = Zone()
zone_medium_two.save()
self.zone_medium_two = zone_medium_two
#alphabet
words = self.name_short.split()
for word in words:
letter = word[0].upper()
try:
current_letter = Alphabet.objects.get(letter=letter)
if not current_letter.is_action:
current_letter.is_action = True
current_letter.save()
except Alphabet.DoesNotExist:
letter = Alphabet(letter=letter, is_action=True)
letter.save()
super(Catalog, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone_title.delete()
self.zone_medium_one.delete();
self.zone_medium_two.delete();
class GroupingUnit(models.Model):
name = models.CharField('Название', max_length=255)
slug = models.SlugField('URL Slug')
description = models.TextField('Описание', blank=True)
show_on_site = models.BooleanField('Показать на сайте?', default=True)
big_blurry_picture = models.ImageField("Большое размытое изображение на внутреннюю", upload_to="groupings", blank=True)
medium_thumb = models.ImageField("Среднее изображение в список каталогов", upload_to="groupings", blank=True)
catalog = models.ManyToManyField(Catalog, verbose_name='Каталог')
def __unicode__(self):
return self.name
class Manufacturer(GroupingUnit):
class Meta:
verbose_name = 'Производитель'
verbose_name_plural = 'Производители'
def get_zone(self, path):
try:
zones = ManufacturerZoneUrl.objects.get(url=path)
return {'zone_title': zones.zone_title,
'zone_medium_one': zones.zone_medium_one,
'zone_medium_two': zones.zone_medium_two}
except:
zones = ManufacturerZoneUrl(url=path)
zones.save()
zones = ManufacturerZoneUrl.objects.get(url=path)
return {'zone_title': zones.zone_title,
'zone_medium_one': zones.zone_medium_one,
'zone_medium_two': zones.zone_medium_two}
class TypeA(GroupingUnit):
zone_title = models.OneToOneField(Zone, null=True, blank=True, editable=False)
zone_medium_one = models.OneToOneField(Zone, related_name="TypeA_medium_one_zone", null=True, blank=True, editable=False)
zone_medium_two = models.OneToOneField(Zone, related_name="TypeA_medium_two_zone", null=True, blank=True, editable=False)
class Meta:
verbose_name = 'ТипA'
verbose_name_plural = 'ТипыA'
def save(self, *args, **kwargs):
if self.id == None:
zone_title = Zone()
zone_title.save()
self.zone_title = zone_title
zone_medium_one = Zone()
zone_medium_one.save()
self.zone_medium_one = zone_medium_one
zone_medium_two = Zone()
zone_medium_two.save()
self.zone_medium_two = zone_medium_two
super(TypeA, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone_title.delete()
self.zone_medium_one.delete()
self.zone_medium_two.delete()
class TypeB(GroupingUnit):
zone_title = models.OneToOneField(Zone, null=True, blank=True, editable=False)
zone_medium_one = models.OneToOneField(Zone, related_name="TypeB_medium_one_zone", null=True, blank=True, editable=False)
zone_medium_two = models.OneToOneField(Zone, related_name="TypeB_medium_two_zone", null=True, blank=True, editable=False)
class Meta:
verbose_name = 'ТипB'
verbose_name_plural = 'ТипыB'
def save(self, *args, **kwargs):
if self.id == None:
zone_title = Zone()
zone_title.save()
self.zone_title = zone_title
zone_medium_one = Zone()
zone_medium_one.save()
self.zone_medium_one = zone_medium_one
zone_medium_two = Zone()
zone_medium_two.save()
self.zone_medium_two = zone_medium_two
super(TypeB, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone_title.delete()
self.zone_medium_one.delete()
self.zone_medium_two.delete()
class Product(models.Model):
"""
Product
"""
STATUS_CHOICES = (
(1, 'Снят с производства'),
(2, 'Под заказ'),
(3, 'В наличии'),
(4, 'Ожидается поступление'),
)
DELIVERY_PERIOD_CHOICES = (
(1, 'A'),
(2, 'B'),
(3, 'C'),
(4, 'D'),
)
UNIT_CHOICES = (
(1, 'ед. - единица'),
(2, 'изд.'),
(3, 'кг.'),
(4, 'л. - литр'),
(5, 'м.'),
(6, 'м.(квадратный)'),
(7, 'м.(кубический)'),
(8, 'набор'),
(9, 'метр погонный'),
(10, 'рул. - рулон'),
(11, 'т. - тонна'),
(12, 'упак. - упаковка'),
(13, 'ч. - час'),
(14, 'шт.'),
(15, 'меш. - мешок'),
)
name = models.CharField('Имя продукта', max_length=255,)
desc_full = models.TextField('Полное описание', blank=True)
desc_short = models.CharField('Краткое описание', max_length=255, blank=True)
articul = models.CharField('Артикул', max_length=30, blank=True)
slug = models.SlugField('Slug', max_length=255, blank=True)
count_in_the_presence = models.FloatField('Кол-во в наличии', blank=True, default=0)
price = models.DecimalField('Цена', max_digits=10, decimal_places=2, blank=True, null=True)
discount = models.PositiveIntegerField('Скидка %', blank=True, max_length=2, null=True, default=0)
status = models.PositiveIntegerField('Статус', choices=STATUS_CHOICES, blank=True, null=True)
unit = models.PositiveIntegerField('Единицы измерения', choices=UNIT_CHOICES, blank=True, null=True)
delivery_period = models.PositiveIntegerField('Срок доставки', choices=DELIVERY_PERIOD_CHOICES, blank=True, null=True)
count_like = models.PositiveIntegerField('Кол-во "лайков"', blank=True, null=True, default=0)
top_order = models.IntegerField('Рейтинг товара', blank=True, null=True, default=0)
is_publish = models.BooleanField('Публиковать?', blank=True, default=True)
is_action = models.BooleanField('Акция?', blank=True, default=True)
catalog = models.ForeignKey(Catalog, verbose_name='К какому каталогу?', blank=True, null=True)
manufacturer = models.ForeignKey(Manufacturer, verbose_name='Какой производитель?', blank=True, null=True)
types = models.ManyToManyField(TypeA, blank=True, null=True)
type_b = models.ManyToManyField(TypeB, blank=True, null=True)
picture = models.ManyToManyField('Picture', blank=True, null=True)
zone = models.OneToOneField(Zone, null=True, blank=True, editable=False)
class Meta:
verbose_name = 'Продукт'
verbose_name_plural = 'Продукты'
def __unicode__(self):
return '%s' % self.name
def save(self, *args, **kwargs):
if not self.discount:
self.discount = 0
if not self.count_in_the_presence:
self.count_in_the_presence = 0
if not self.price:
self.price = 0
super(Product, self).save(*args, **kwargs)
if self.articul == '':
self.articul = 'A-' + str(self.id)
super(Product, self).save(*args, **kwargs)
def discounted(self):
if self.discount == 0:
return self.price
else:
return self.price - (self.price * self.discount/100)
def get_unit(self):
unit = ('', 'ед. - единица', 'изд.', 'кг', 'л. - литр', 'м.', 'м<sup>2</sup>', 'м<sup>3</sup>', 'набор',
'метр погонный', 'рул. - рулон', 'т. - тонна', 'упак. - упаковка', 'ч. - час', 'шт.', 'меш. - мешок')
return unit[self.unit]
def get_url(self):
path = '/production/'
if self.catalog.slug:
path += self.catalog.slug + '/'
if self.manufacturer.slug:
path += self.manufacturer.slug + '/'
if self.types.all():
path += self.types.all()[0].slug + '/'
if self.setgroup_set.all():
path += 'set-' + self.setgroup_set.all()[0].set.slug + '/'
path += 'pos-' + self.slug + '/'
return path
class CatalogBrandType(models.Model):
brand = models.ForeignKey(Manufacturer, verbose_name='Производитель')
catalog = models.ForeignKey(Catalog, verbose_name='Каталог')
type = models.ManyToManyField(TypeA, verbose_name='Типы', blank=True, null=True)
class Meta:
verbose_name = 'Связь производителя с каталогом и типами'
verbose_name_plural = 'Связь производителя с каталогом и типами'
def __unicode__(self):
return '%s(%s)' % (self.brand.name, self.catalog.name_short)
class Picture(models.Model):
picture = models.ImageField('Изображение', upload_to='catalog/pictures/')
name = models.CharField('Название', max_length=255, blank=True)
alt = models.CharField('alt', max_length=255, blank=True)
title = models.CharField('title', max_length=255, blank=True)
link = models.CharField('Ссылка', max_length=255, blank=True)
class Meta:
verbose_name = 'Изображение'
verbose_name_plural = 'Изображения'
def __unicode__(self):
if self.name == '':
return 'noname'
else:
return self.name
def save(self, *args, **kwargs):
if self.id is None:
super(Picture, self).save(*args, **kwargs)
original_image = Picture.objects.get(pk=self.id).picture
thumbnail(original_image.name, IMAGE_OPTIONS)
super(Picture, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
original_image = Picture.objects.get(pk=self.id).picture
thumbnail(original_image.name, IMAGE_OPTIONS, False)
super(Picture, self).delete(*args, **kwargs)
def get_image(self):
original_image = Picture.objects.get(pk=self.id).picture
original_image_name = original_image.name.split('/')[-1]
original_image_path = '/'.join(original_image.name.split('/')[0:-1])
name, ext = original_image_name.split('.')
image= []
for option in IMAGE_OPTIONS:
if option['type'] == 'p':
image.append('%s%s/%s_%sx%s.%s' % (settings.MEDIA_URL, original_image_path, name, option['size'], option['size'], ext))
elif option['type'] == 'h':
image.append('%s%s/%s_height_%s.%s' % (settings.MEDIA_URL, original_image_path, name, option['size'], ext))
elif option['type'] == 'w':
image.append('%s%s/%s_width_%s.%s' % (settings.MEDIA_URL, original_image_path, name, option['size'], ext))
return image
#class instance of Zones
class Zones(models.Model):
zone = models.OneToOneField(Zone, null=True, blank=True)
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.id == None:
zone = Zone()
zone.save()
self.zone_title = zone
super(self.__class__.__name__, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone.delete()
super(self.__class__.__name__, self).delete(*args, **kwargs)
class ZoneProductHead(Zones):
pass
class ZoneProductFoot(Zones):
pass
class Alphabet(models.Model):
letter = models.CharField('Буква', max_length=1)
is_action = models.BooleanField('Активна?', default=True)
class Meta:
verbose_name = 'Алфавит'
verbose_name_plural = 'Алфавит'
def __unicode__(self):
if self.is_action:
return '%s' % (self.letter)
else:
return '!%s' % (self.letter)
class Set(models.Model):
name = models.CharField('Название', max_length=255)
slug = models.SlugField('SLUG', max_length=255, unique=True)
zone_one = models.OneToOneField(Zone, null=True, blank=True, editable=False)
zone_two = models.OneToOneField(Zone, related_name="two_zone", null=True, blank=True, editable=False)
zone_three = models.OneToOneField(Zone, related_name="three_zone", null=True, blank=True, editable=False)
zone_four = models.OneToOneField(Zone, related_name="four_zone", null=True, blank=True, editable=False)
top_order = models.IntegerField('Рейтинг сэта', blank=True, null=True, default=0)
picture = models.ManyToManyField(Picture, blank=True, null=True)
catalog = models.ForeignKey(Catalog)
brand = models.ForeignKey(Manufacturer, blank=True, null=True)
type_a = models.ForeignKey(TypeA, blank=True, null=True)
product = models.ManyToManyField(Product, verbose_name="Продукты", blank=True)
class Meta:
verbose_name = 'Сет'
verbose_name_plural = 'Сет'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if self.id == None:
zone_one = Zone()
zone_one.save()
self.zone_one = zone_one
zone_two = Zone()
zone_two.save()
self.zone_two = zone_two
zone_three = Zone()
zone_three.save()
self.zone_three = zone_three
zone_four = Zone()
zone_four.save()
self.zone_four = zone_four
super(Set, self).save(*args, **kwargs)
set = Set.objects.get(pk=self.id)
set_group = SetGroup(name="Основная группа", set=set)
set_group.save()
super(Set, self).save(*args, **kwargs)
def delete(self):
self.zone_one.delete()
self.zone_two.delete()
self.zone_three.delete()
self.zone_four.delete()
def get_url(self):
result = '/production/'
result += self.catalog.slug + '/'
if self.type_a:
result += self.type_a.slug + '/'
if self.brand:
result += self.brand.slug + '/'
result += 'set-' + self.slug
return result
class SetGroup(models.Model):
name = models.CharField('Название', max_length=255)
set = models.ForeignKey(Set, verbose_name='К какому сету?', blank=True, null=True)
product = models.ManyToManyField(Product, verbose_name="Продукты", blank=True)
class Meta:
verbose_name = 'Группа Сэта'
verbose_name_plural = 'Группы Сэтов'
def __unicode__(self):
return self.name
class ManufacturerZoneUrl(models.Model):
url = models.CharField('URL', max_length=255)
zone_title = models.OneToOneField(Zone, null=True, blank=True, editable=False)
zone_medium_one = models.OneToOneField(Zone, related_name="Manufacturer_medium_one_zone", null=True, blank=True, editable=False)
zone_medium_two = models.OneToOneField(Zone, related_name="Manufacturer_medium_two_zone", null=True, blank=True, editable=False)
class Meta:
verbose_name = 'Зона с привязкой к url для производителя'
verbose_name_plural = 'Зоны с привязкой к url для производителя'
def __unicode__(self):
return self.url
def save(self, *args, **kwargs):
if self.id == None:
zone_title = Zone()
zone_title.save()
self.zone_title = zone_title
zone_medium_one = Zone()
zone_medium_one.save()
self.zone_medium_one = zone_medium_one
zone_medium_two = Zone()
zone_medium_two.save()
self.zone_medium_two = zone_medium_two
super(ManufacturerZoneUrl, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone_title.delete()
self.zone_medium_one.delete()
self.zone_medium_two.delete()
super(ManufacturerZoneUrl, self).delete(*args, **kwargs)
<file_sep>from django.conf.urls.defaults import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Admin site
url(r'^admin/', include(admin.site.urls)),
# Authentication
url(r'^$', 'common.views.index'),
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/login/'}),
# Personal
url(r'^home/$', 'common.views.home'),
# Article
url(r'^articles/(.*?)/$', 'articles.views.article'),
# Documents
url(r'^document/(\d+)/$', 'documents.views.root'),
url(r'^document/(\d+)/structure/$', 'documents.views.structure'),
url(r'^document/(\d+)/glossary/$', 'documents.views.glossary'),
url(r'^document/(\d+)/(.*)/$', 'documents.views.part'),
# Documents API
url(r'^api/documents/create/$', 'documents.api.create_document'),
url(r'^api/documents/rename/(\d+)/$', 'documents.api.rename_document'),
url(r'^api/documents/delete/(\d+)$', 'documents.api.delete_document'),
# Parts API
url(r'^api/parts/list/$', 'documents.api.list_parts'),
url(r'^api/parts/create/$', 'documents.api.create_part'),
url(r'^api/parts/rename/(\d+)/$', 'documents.api.rename_part'),
url(r'^api/parts/delete/(\d+)/$', 'documents.api.delete_part'),
url(r'^api/parts/move/$', 'documents.api.move_part'),
# Widgets API
url(r'^api/widgets/list/$', 'widgets.views.list'),
url(r'^api/widgets/create/(.*?)/$', 'widgets.views.create'),
url(r'^api/widgets/move/(.*?)/$', 'widgets.views.move'),
url(r'^api/widgets/delete/(.*?)/$', 'widgets.views.delete'),
url(r'^api/widgets/get/(.*?)/$', 'widgets.views.get'),
url(r'^api/widgets/form/(.*?)/$', 'widgets.views.form'),
url(r'^api/widgets/change/(.*?)/$', 'widgets.views.change'),
)<file_sep># -*- coding: utf-8 -*-
from django.db import models
from django.db.models.query import QuerySet
class SubclassingQuerySet(QuerySet):
""" QuerySet extension for getting derived class instances instead of base """
def __getitem__(self, k):
result = super(SubclassingQuerySet, self).__getitem__(k)
if isinstance(result, models.Model):
return result.as_leaf_class()
else:
return result
def __iter__(self):
for item in super(SubclassingQuerySet, self).__iter__():
yield item.as_leaf_class()
class WidgetManager(models.Manager):
pass
class WidgetLeafManager(models.Manager):
""" Manager, based on SubclassingQuerySet """
def get_query_set(self):
return SubclassingQuerySet(self.model)<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import QuestAnswer, TagName, Alphabet
class QuestAnswerAdmin(admin.ModelAdmin):
# list_display = ('author', 'date_publication', 'moderator', 'is_public',)
filter_horizontal = ('tag',)
# prepopulated_fields = {'slug': ('name',)}
# pass
admin.site.register(QuestAnswer, QuestAnswerAdmin)
admin.site.register(TagName)
admin.site.register(Alphabet)
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Tables
#
create_group('tables', 'Таблицы')
@add2group('Таблица', 'tables')
class Table(Widget):
content = models.TextField("Содержимое тега TABLE (без него самого)", blank=True, default="")
<file_sep># -*- coding: utf8 -*-
from django.contrib import admin
from models import Catalog, Manufacturer, TypeA, TypeB, Product, Picture, Group, Alphabet, Set, SetGroup, CatalogBrandType
class ProductAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
filter_horizontal = ('types', 'picture', 'type_b')
class CatalogAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name_short',)}
class GroupAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class GroupingUnitAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class SetAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
# filter_horizontal = ('product', )
class SetGroupAdmin(admin.ModelAdmin):
# filter_horizontal = ('product',)
pass
admin.site.register(Group, GroupAdmin)
admin.site.register(Catalog, CatalogAdmin)
admin.site.register(Manufacturer, GroupingUnitAdmin)
admin.site.register(TypeA, GroupingUnitAdmin)
admin.site.register(TypeB, GroupingUnitAdmin)
admin.site.register(Product, ProductAdmin)
admin.site.register(Picture)
admin.site.register(Alphabet)
admin.site.register(Set, SetAdmin)
admin.site.register(SetGroup, SetGroupAdmin)
admin.site.register(CatalogBrandType)<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
from tinymce import models as tinymce_model
#
# Text
#
create_group('text', 'Текст')
@add2group('Параграф', 'text')
class SimpleText(Widget):
TEXT_TYPE_CHOICES = (
(1, 'Анонс'),
(2, 'Цитата'),
(3, 'Заметки'),
)
text = models.TextField("Текст", default="Text")
text_type = models.PositiveIntegerField("Тип текстового блока", choices=TEXT_TYPE_CHOICES, default=1)
@add2group('Таблица характеристик', 'text')
class CharsTable(Widget):
text = models.TextField("Текст", default="Свойство 1 :: Значение 1\nСвойство 2 :: Значение 2\nСвойство 3 :: Значение 3")
def get_pairs(self):
result = []
lines = self.text.split("\n")
for line in lines:
try:
kv = line.split("::")
result.append({ 'key': kv[0].strip(), 'value': kv[1].strip() })
except:
pass
return result
<file_sep># -*- coding: utf-8 -*-
from seo.models import Metatag
from structure.models import *
from catalog.models import Catalog, TypeA, TypeB, Manufacturer, Product, Set
def render_crumbs(path):
crumbs = []
collected_path = '/'
position = None
set = None
section = path[1:-1].split('/')[0]
other_path = path[1:-1].split('/')[1:]
length = len(other_path)
collected_path += section + '/'
try:
section = Section.objects.get(path=collected_path)
crumbs.append({'caption': section.caption, 'path': collected_path})
if section.type.slug == 'catalog' and length:
#есть ли в пути позиция
if other_path[-1].find('pos-') >= 0:
position = other_path.pop()
length = len(other_path)
#/catalog/
if length == 1:
collected_path += other_path[0] + '/'
catalog = Catalog.objects.get(slug=other_path[0])
crumbs.append({'caption': catalog.name_short, 'path': collected_path})
#/(type or manufacturer)/
if length == 2:
collected_path += other_path[0] + '/'
catalog = Catalog.objects.get(slug=other_path[0])
crumbs.append({'caption': catalog.name_short, 'path': collected_path})
collected_path += other_path[1] + '/'
type_or_manufacturer_path = other_path[1]
try:
try:
type_or_manufacturer = TypeA.objects.get(catalog=catalog, slug=type_or_manufacturer_path)
except:
type_or_manufacturer = TypeB.objects.get(catalog=catalog, slug=type_or_manufacturer_path)
except:
type_or_manufacturer = Manufacturer.objects.get(catalog=catalog, slug=type_or_manufacturer_path)
crumbs.append({'caption': type_or_manufacturer.name, 'path': collected_path})
#/type/brand/
if length == 3:
collected_path += other_path[0] + '/'
catalog = Catalog.objects.get(slug=other_path[0])
crumbs.append({'caption': catalog.name_short, 'path': collected_path})
collected_path += other_path[1] + '/'
manufacturer = Manufacturer.objects.get(catalog=catalog, slug=other_path[1])
crumbs.append({'caption': manufacturer.name, 'path': collected_path})
collected_path += other_path[2] + '/'
try:
type = TypeA.objects.get(catalog=catalog, slug=other_path[2])
except:
type = TypeB.objects.get(catalog=catalog, slug=other_path[2])
crumbs.append({'caption': type, 'path': collected_path})
#/type/brand/set/
if length == 4:
collected_path += other_path[0] + '/'
catalog = Catalog.objects.get(slug=other_path[0])
crumbs.append({'caption': catalog.name_short, 'path': collected_path})
collected_path += other_path[1] + '/'
manufacturer = Manufacturer.objects.get(catalog=catalog, slug=other_path[1])
crumbs.append({'caption': manufacturer.name, 'path': collected_path})
collected_path += other_path[2] + '/'
try:
type = TypeA.objects.get(catalog=catalog, slug=other_path[2])
except:
type = TypeB.objects.get(catalog=catalog, slug=other_path[2])
crumbs.append({'caption': type, 'path': collected_path})
collected_path += other_path[3] + '/'
set = Set.objects.get(catalog=catalog, slug=other_path[3][4:])
crumbs.append({'caption': set, 'path': collected_path})
if position:
position = Product.objects.get(catalog=catalog, slug=position[4:])
crumbs.append({'caption': position.name, 'path': 'pos'})
if set and length < 4:
set = Set.objects.get(slug=set[4:])
crumbs.append({'caption': set.name, 'path': 'pos'})
return crumbs
except:
return {}
def current_section(request):
return { 'current_section': request.current_section }
def current_path(request):
return { 'current_path': request.path }
def structure(request):
return { 'structure': request.structure }
def crumbs(request):
return {'crumbs': render_crumbs(str(request.path))}
def header_menu(request):
return {'header_menu': Section.objects.get(path='/').children.order_by('order').values()}
<file_sep># -*- coding: utf-8 -*-
from brick.widgets.models import *
def create_widgets_context(context, zone_type, zone_pid, zones_count=0):
context['widgets'] = {}
for i in xrange(zones_count):
widgets = Widget.objects.filter(
zone_type=zone_type,
zone_primary_id=zone_pid,
zone_secondary_id=i+1
)
context['widgets'][(zone_type, zone_pid, i+1)] = widgets
for widget in widgets:
subs_recursive(widget, context['widgets'], zone_type, zone_pid)
return context
def subs_recursive(widget, result, zone_type, zone_pid):
subs = widget.subs()
if subs:
zone_type = widget.sub_zones_type
zone_pid = widget.id
for i in subs:
widgets = subs[i]
result[(zone_type, zone_pid, i)] = widgets
for widget in widgets:
subs_recursive(widget, result, zone_type, zone_pid)
<file_sep>// Menu
$(document).ready(function(){
/*$("#menu li a").click(function() {
$(this).parent().parent().find("ul").fadeOut();
$("#menu li a").removeClass("nolink");
if ($(this).parent().parent().parent().attr("id")!="menu") $(this).parent().parent().parent().find("a:first").addClass("nolink")
if($(this).parent().find("ul").length!=0) {
if ($(this).parent().find("ul:first").css("display")=="none") {$(this).parent().find("ul:first").fadeIn(); $(this).addClass("nolink"); }
else {$(this).parent().find("ul:first").fadeOut(); $(this).removeClass("nolink"); }
return false;
}
});
$("#menu").mouseout(function() {
$("body").click(function() { $("#menu ul ul").fadeOut(); $("#menu li a").removeClass("nolink"); })
});
*/
if ($('#section-id').length) {
var id = $('#section-id').text();
//$('#menu ul:has(#item-'+id+')').show();
$('#item-'+id).parents('ul').show();
$('#item-'+id).children().show();
//$('#menu ul:has(#item-'+id+')').children('li').children('ul').show();
$('#item-'+id).children('a').css('font-style', 'italic').css('text-decoration', 'none');
}
});
<file_sep># -*- coding: utf-8 -*-
from django.test import TestCase
from catalogapp import api
class TestBrands(TestCase):
def test_create(self):
brand_id = api.brands.create("Brand name", "brand_slug")
self.assertTrue(isinstance(brand_id, int))
def test_delete(self):
brand1_id = api.brands.create("Brand name", "brand_slug")
brand2_id = api.brands.create("Brand name", "brand_slug")
self.assertTrue(api.brands.delete(brand1_id))
self.assertEqual(api.brands.Brand.objects.count(), 1)
self.assertFalse(api.brands.delete(brand1_id))
def test_rename(self):
brand_id = api.brands.create("Brand name", "brand_slug")
self.assertTrue(api.brands.rename(brand_id, "New name"))
brand = api.brands.get(brand_id)
self.assertEqual(brand.name, "New name")
self.assertEqual(brand.slug, "brand_slug")
self.assertTrue(api.brands.rename(brand_id, "New name", "new_slug"))
brand = api.brands.get(brand_id)
self.assertEqual(brand.name, "New name")
self.assertEqual(brand.slug, "new_slug")
def test_list(self):
brand1_id = api.brands.create("Brand name", "brand_slug")
brand2_id = api.brands.create("Brand name", "brand_slug")
brand3_id = api.brands.create("Other name", "brand_slug")
brands = api.brands.list(name="Brand name")
self.assertEqual(len(brands), 2)
self.assertTrue(brand1_id in [b.id for b in brands])
self.assertTrue(brand2_id in [b.id for b in brands])
self.assertFalse(brand3_id in [b.id for b in brands])
def test_listIn(self):
brand1_id = api.brands.create("Brand name", "brand_slug")
brand2_id = api.brands.create("Brand name", "brand_slug")
brand3_id = api.brands.create("Other name", "brand_slug")
brands = api.brands.listIn([brand2_id, brand3_id])
self.assertEqual(len(brands), 2)
<file_sep># -*- coding: utf8 -*-
"""
Set URL maps for every SectionType here.
Patterns will be applied to "subpaths".
Example: if your path is '/company/news/56/'
and '/company/news/' is a Section with "news" type,
'56/' will be checked with patterns defined in "news" variable.
"""
from django.conf.urls.defaults import patterns, include, url
index = patterns('',
url(r'^$', 'common.views.index')
)
text = patterns('',
url(r'^$', 'common.views.text')
)
catalog = patterns('catalog.views',
# Стартовая каталога /production/
url(r'^$', 'index'),
# Каталог /production/catalog/
url(r'^(?P<slug>[-a-zA-Z0-9_]+)/(pos-(?P<product>[-a-zA-Z0-9_]+)/)?$', 'catalogue'),
url(r'^(?P<slug>[-a-zA-Z0-9_]+)/(set-(?P<set>[-a-zA-Z0-9_]+)/)?$', 'catalogue'),
#Тип /production/catalog/type/
url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<type_or_brand>[-a-zA-Z0-9_]+)/(pos-(?P<product>[-a-zA-Z0-9_]+)/)?$', 'type_or_brand'),
url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<type_or_brand>[-a-zA-Z0-9_]+)/(set-(?P<set>[-a-zA-Z0-9_]+)/)?$', 'type_or_brand'),
#Тип+Бренд /production/brand/catalog/type/
url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<brand>[-a-zA-Z0-9_]+)/(?P<type>[-a-zA-Z0-9_]+)/(pos-(?P<product>[-a-zA-Z0-9_]+)/)?$', 'brand_type'),
url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<brand>[-a-zA-Z0-9_]+)/(?P<type>[-a-zA-Z0-9_]+)/(set-(?P<set>[-a-zA-Z0-9_]+)/)?$', 'brand_type'),
#Тип+Бренд+Коллекция /production/brand/catalog/type/set/
url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<brand>[-a-zA-Z0-9_]+)/(?P<type>[-a-zA-Z0-9_]+)/(set-(?P<set>[-a-zA-Z0-9_]+)/)?$', 'brand_type_set'),
url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<brand>[-a-zA-Z0-9_]+)/(?P<type>[-a-zA-Z0-9_]+)/(set-(?P<set>[-a-zA-Z0-9_]+))/(pos-(?P<product>[-a-zA-Z0-9_]+)/)?$', 'brand_type_set'),
# # Группа
# url(r'^groups/(?P<slug>[-a-zA-Z0-9_]+)/$', 'group'),
# #Позиция
# url(r'^product/(?P<product>[-a-zA-Z0-9]+)/$', 'product'),
# # Производитель/тип
# url(r'^(?P<catalog>[-a-zA-Z0-9_]+)/(?P<grouping_unit>[-a-zA-Z0-9_]+)/$', 'grouping_unit'),
)
qa = patterns('questanswer.views',
url(r'^$', 'questanswer'),
url(r'^page-(?P<page>[\d]+)/$', 'questanswer'),
url(r'^(?P<id>[\d]+)/$', 'question'),
url(r'^tag/(?P<slug>[-a-zA-Z0-9_]+)/$', 'tag'),
)<file_sep>from django.conf import settings
from models import Widget
try:
widgets = settings.WIDGETS
for group_name, params in widgets.iteritems():
package = __import__(params['package'], fromlist=True)
for name, verbose_name in params['items']:
Widget.subclasses[name] = package.__dict__[name]
except:
pass<file_sep>{% extends "articles/article_layout.html" %}
{% block article_content %}
<h1>{{ article.caption }}</h1>
{% load zones %}
{% render_zone article.zone %}
<ul class="path">
<li><a href="/">Главная</a></li>
<li><a href="/articles/">Статьи</a></li>
<li><a href="/articles/{{ section.name }}/">{{ section.caption }}</a></li>
</ul>
{% endblock %}<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Images and galleries
#
create_group('images', 'Картинки и галереи')
@add2group('Изображение', 'images')
class SingleImage(Widget):
image = models.ImageField(u"Изображение", upload_to='image')
alt = models.CharField(max_length=255, blank=True, default="")
title = models.CharField(max_length=255, blank=True, default="")
<file_sep># -*- coding: utf-8 -*-
import pytils
from django.db import models, connection
from structure.models import Section as StructureSection
from widgets.models import Zone
from utils.models import SortableModel
from common.thumbs import ImageWithThumbsField
from questanswer.models import QuestAnswer
from django.db.models import Q
from django.conf import settings
import datetime
class CatalogManager(models.Manager):
def search(self):
pass
def _split_join(s):
b = s.split('/')
b = '_'.join(b)[:-1]
b = s.split('-')
b = '_'.join(b)
return '%s' % b
NAME_TABLE = 'all_catalog'
class Section(StructureSection):
class Meta:
proxy = True
verbose_name = 'Раздел'
verbose_name_plural = 'Разделы'
class ShoeSizeSection(models.Model):
section = models.OneToOneField('Section',
verbose_name='Раздел сайта',
related_name='catalog_property')
sizes = models.ManyToManyField('ShoeSize', null=True, blank=True)
class Meta:
verbose_name = 'Размеры раздела'
verbose_name_plural = 'Размеры раздела'
def __unicode__(self):
return self.section.path
def save(self, *args, **kwargs):
super(ShoeSizeSection, self).save(*args, **kwargs)
if self.sizes:
products = Product.objects.filter(section__path__startswith=self.section.path)
for sizes in self.sizes:
pass
def delete(self, *args, **kwargs):
super(ShoeSizeSection, self).delete(*args, **kwargs)
class Catalog(models.Model):
section = models.OneToOneField('Section',
verbose_name='Раздел сайта',
related_name='catalog')
properties = models.ManyToManyField('Property',
verbose_name=u'Свойства',
blank=True)
def save(self, *args, **kwargs):
super(Catalog, self).save(*args, **kwargs)
def __unicode__(self):
return unicode(self.section.caption)
class Meta:
verbose_name = 'Каталог'
verbose_name_plural = 'Каталоги'
# @todo: Handle "Sections" and "Catalogs"
# separately for extended properties manipulation
class Product(SortableModel):
order_isolation_fields = ('section',)
name = models.CharField(u'Имя продукта', max_length=255,)
slug = models.SlugField(u'Slug', max_length=255, blank=True)
article = models.CharField(u'Артикул', max_length=255, blank=True,)
desc_short = models.CharField('Краткое описание продукта',
max_length=255,
blank=True,)
price = models.DecimalField(u'Цена', max_digits=10, decimal_places=2, blank=True, null=True,)
section = models.ForeignKey('Section', verbose_name=u'К какому разделу?')
catalog = models.ForeignKey('Catalog', verbose_name=u'К какому каталогу?', blank=True, null=True)
discount = models.PositiveIntegerField(u'Процент скидки', blank=True, null=True, default=0)
date = models.DateField('Дата добавления', blank=True, default=datetime.datetime.now())
is_special = models.BooleanField("Акция", default=False)
is_free_delivery = models.BooleanField("Бесплатная доставка", default=False)
is_exist = models.BooleanField("В наличии?", default=True)
on_main = models.BooleanField(u'Выводить на главную?', default=True)
is_enabled = models.BooleanField(u'Включена?', default=False)
wtp = models.ManyToManyField('self', verbose_name=u'С этим товаром так же покупают', blank=True, null=True, symmetrical=False, editable=False) # wtp - with this product
zone = models.OneToOneField(Zone, null=True, blank=True, editable=False)
upper_zone = models.OneToOneField(Zone, related_name="upper_zone", null=True, blank=True, editable=False)
sizes = models.ManyToManyField('ShoeSize', through='Pricing', null=True, blank=True, editable=False)
qa = models.ManyToManyField(QuestAnswer, verbose_name='Связь продукта с вопросами', null=True, blank=True)
class Meta:
ordering = ['-is_exist', 'order']
verbose_name = 'Продукт'
verbose_name_plural = 'Продукты'
def save(self, *args, **kwargs):
if self.id is None and not self.slug:
order_slug = slug = pytils.translit.slugify(self.name)
order = 0
while Product.objects.filter(slug=order_slug):
order += 1
order_slug = '{0}-{1}'.format(str(order), slug)
self.slug = order_slug
try:
product = Product.objects.get(slug=self.slug)
if product.id != self.id:
order_slug = slug = self.slug
order = 0
while Product.objects.filter(slug=order_slug):
order += 1
order_slug = '{0}-{1}'.format(str(order), slug)
self.slug = order_slug
except:
pass
if self.id == None:
zone = Zone()
zone.save()
self.zone = zone
upper_zone = Zone()
upper_zone.save()
self.upper_zone = upper_zone
# @todo: add the row to the render table
# Checking "catalog"
cs = self.section
if Catalog.objects.filter(section=cs):
self.catalog = Catalog.objects.get(section=cs)
elif Catalog.objects.filter(section=cs.parent):
self.catalog = Catalog.objects.get(section=cs.parent)
elif Catalog.objects.filter(section=cs.parent.parent):
self.catalog = Catalog.objects.get(section=cs.parent.parent)
else:
self.catalog = Catalog.objects.get(section=cs.parent.parent.parent)
if not self.is_exist:
product = Product.objects.get(pk=self.pk)
sizes = Pricing.objects.filter(product=product)
for size in sizes:
size.is_exist = False
size.save()
if not self.date:
self.date = datetime.datetime.now()
super(Product, self).save(*args, **kwargs)
if self.article == '':
self.article = 'A-' + str(self.id)
super(Product, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone.delete()
self.upper_zone.delete()
def __unicode__(self):
return self.name
def picture(self):
try:
return self.picture_set.all()[0].picture
except:
return None
def discounted(self):
if self.discount == 0:
return self.price
else:
return self.price - (self.price * self.discount / 100)
@staticmethod
def filter(catalog, from_price=None, to_price=None, size=None):
result = {}
products = []
section = Section.objects.filter(path__startswith=catalog)
for sec in section:
for p in Product.objects.filter(section=sec):
products.append(p)
if not size:
result = Product.objects.filter(section__path__startswith=catalog).\
filter(Q(price__range=(from_price, to_price)) | Q(pricing__price__range=(from_price, to_price))).distinct()
elif not from_price and not to_price:
result = Product.objects.filter(section__path__startswith=catalog).\
filter(pricing__size__in=size).distinct()
else:
result = Product.objects.filter(section__path__startswith=catalog).\
filter(pricing__size__in=size).\
filter(Q(price__range=(from_price, to_price)) | Q(pricing__price__range=(from_price, to_price))).distinct()
return result
def size_is_exists(self):
for size in self.pricing_set.all():
if size.is_exist:
return True
def position_pricing_if_exists(self):
if Pricing.objects.filter(product=self).order_by('size'):
return True
def nova(self):
if self.date:
delta = datetime.date.today() - self.date
if delta.days <= settings.DELTA_DATE:
return True
return False
class Property(models.Model):
TYPE_CHOICES = (
(1, 'Текстовый'),
(2, 'Числовой'),
(3, 'Да/нет'),
(4, 'Выбор значений'),
)
type = models.PositiveIntegerField("Какой тип", choices=TYPE_CHOICES)
name = models.CharField(u'Имя', max_length=255)
slug = models.SlugField(u'Slug', max_length=255)
default = models.CharField(u'Значение по умолчанию', max_length=255, blank=True,)
description = models.TextField(u'Описание', blank=True)
is_filter = models.BooleanField('Является фильтром', default=False)
is_important = models.BooleanField('Является важной', default=False)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if self.id is None:
# @todo: create the column for rendered section table
pass
# @todo: check the type of the field to change rendered-column type
# @todo: change default value somehow o_O
# @old @todo: handle options change as well
super(Property, self).save(*args, **kwargs)
class Meta:
verbose_name = 'Свойство'
verbose_name_plural = 'Свойства'
class Choice(models.Model):
property = models.ForeignKey('Property', verbose_name='Свойство', limit_choices_to={'type': 4})
value = models.CharField("Вариант", max_length=255, blank=True)
is_default = models.BooleanField('По умолчанию?', default=False)
description = models.TextField(u'Описание', blank=True)
def __unicode__(self):
return self.value
def save(self, *args, **kwargs):
super(Choice, self).save(*args, **kwargs)
class Meta:
verbose_name = 'Вариант'
verbose_name_plural = 'Варианты'
class PropertyValue(models.Model):
position = models.ForeignKey('Product', verbose_name=u'Позиция')
def __unicode__(self):
return self.property.name + ': ' + unicode(self.value)
def save(self, *args, **kwargs):
# @todo: put the value into the render table
super(PropertyValue, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
# @todo: throw the value out of the render table
super(PropertyValue, self).delete(*args, **kwargs)
class Meta:
abstract = True
verbose_name = 'Значение свойства'
verbose_name_plural = 'Значения свойств'
class CharPropertyValue(PropertyValue):
property = models.ForeignKey('Property', verbose_name=u'Свойство', limit_choices_to={'type': 1})
value = models.CharField("Значение", max_length=255)
class NumericPropertyValue(PropertyValue):
property = models.ForeignKey('Property', verbose_name=u'Свойство', limit_choices_to={'type': 2})
value = models.FloatField("Значение (число)")
class BooleanPropertyValue(PropertyValue):
property = models.ForeignKey('Property', verbose_name=u'Свойство', limit_choices_to={'type': 3})
value = models.BooleanField("Значение (да/нет)")
class MultipleChoicePropertyValue(PropertyValue):
property = models.ForeignKey('Property', verbose_name=u'Свойство', limit_choices_to={'type': 4})
value = models.ForeignKey('Choice', verbose_name=u'Вариант значения')
# # # Additional stuff
class Picture(models.Model):
name = models.CharField("Подпись", max_length=255, blank=True)
picture = ImageWithThumbsField("Изображение", upload_to='catalog/pictures',
sizes=((130, 130), (50, 50), (300, 400)))
product = models.ForeignKey(Product, verbose_name='Позиция')
class Meta:
verbose_name = 'Изображение'
verbose_name_plural = 'Изображения'
class NewCollection(models.Model):
name = models.CharField('Название', max_length=255)
slug = models.SlugField('URL-slug', max_length=255, blank=True)
desc = models.TextField(u'Описание', blank=True)
picture = models.ImageField(u'Изображение', upload_to='collection/pictures', blank=True)
is_active = models.BooleanField('Активна?', default=True)
products = models.ManyToManyField(Product, verbose_name='Позиции',
blank=True, null=True, editable=False)
zone_top = models.OneToOneField(Zone, related_name='Zone Top', null=True, blank=True, editable=False)
zone_bottom = models.OneToOneField(Zone, related_name='Zone Bottom', null=True, blank=True, editable=False)
class Meta:
verbose_name = 'Новая Коллекция'
verbose_name_plural = 'Новые Коллекции'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if (self.slug == ''):
self.slug = pytils.translit.slugify(self.name)
if self.id == None:
zone_top = Zone()
zone_top.save()
self.zone_top = zone_top
zone_bottom = Zone()
zone_bottom.save()
self.zone_bottom = zone_bottom
super(NewCollection, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone_top.delete()
self.zone_bottom.delete()
super(Action, self).delete(*args, **kwargs)
class ShoeSize(models.Model):
mm = models.PositiveIntegerField('Размер в мм')
cm = models.PositiveIntegerField('Размер в см')
st = models.PositiveIntegerField('Размер стандарт')
def __unicode__(self):
return str(self.mm) + '/' + str(self.cm) + '/' + str(self.st)
class Meta:
ordering = ('mm', )
verbose_name = 'Размер'
verbose_name_plural = 'Размеры'
class Pricing(models.Model):
size = models.ForeignKey(ShoeSize, verbose_name='Размер')
product = models.ForeignKey(Product, verbose_name='Позиция')
is_exist = models.BooleanField('Наличие', default=True)
price = models.DecimalField('Цена', max_digits=10, decimal_places=2, blank=True, null=True)
def discounted(self):
# Not discounted
if not self.product.discount:
# Size price
if self.price:
return self.price
# Product price
else:
return self.product.price
# Discounted
else:
# Size discounted price
if self.price:
return self.price - (self.price * self.product.discount / 100)
# Product discounted price
else:
return self.product.discounted()
class Meta:
verbose_name = 'Цена за размер'
verbose_name_plural = 'Цены за размер'
class Action(models.Model):
name = models.CharField('Название', max_length=255)
slug = models.SlugField('URL-slug', max_length=255, blank=True)
desc = models.TextField(u'Описание', blank=True)
picture = models.ImageField(u'Изображение', upload_to='action/pictures', blank=True)
is_active = models.BooleanField('Активна?', default=True)
products = models.ManyToManyField(Product, verbose_name='Позиции',
blank=True, null=True, editable=False)
zone_top = models.OneToOneField(Zone, related_name='Zone_Action_Top', null=True, blank=True, editable=False)
zone_bottom = models.OneToOneField(Zone, related_name='Zone_Action_Bottom', null=True, blank=True, editable=False)
class Meta:
verbose_name = 'Акция'
verbose_name_plural = 'Акции'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
if (self.slug == ''):
self.slug = pytils.translit.slugify(self.name)
if self.id == None:
zone_top = Zone()
zone_top.save()
self.zone_top = zone_top
zone_bottom = Zone()
zone_bottom.save()
self.zone_bottom = zone_bottom
super(Action, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone_top.delete()
self.zone_bottom.delete()
super(Action, self).delete(*args, **kwargs)
from order import Order
<file_sep>document.documentElement.className = document.documentElement.className.replace('nojs', 'js');
$LAB
.script("Front/Common/Scripts/Vendors/jquery.js")
.script("Front/Common/Scripts/Vendors/jquery_ui_core.js")
.script("Front/Common/Scripts/Vendors/jquery_ui_widget.js")
.script("Front/Common/Scripts/Vendors/jquery_ui_mouse.js")
.script("Front/Common/Scripts/Vendors/jquery_ui_slider.js")
.script("Front/Common/Scripts/Vendors/Base.js")
.script("Front/Common/Scripts/Vendors/jquery_print.js")
.script("Front/Common/Scripts/Vendors/jquery_cookie.js")
.script("Front/Common/Scripts/Vendors/jquery_easing.js")
.script("Front/Common/Scripts/Vendors/jquery_colorbox.js")
.script("Front/Common/Scripts/Vendors/jquery_disable_text_select.js")
.script("Front/Common/Scripts/Ie/IeFinder.js")
.script("Front/Colored/Scripts/Colored.js")
.script("Front/Content/Scripts/SlideGallery/SlideGallery.js")
.script("Front/Content/Scripts/SlideGallery/SlideGalleryConstants.js")
.script("Front/Content/Scripts/SlideGallery/SlideGalleryControl.js")
.script("Front/Content/Scripts/SlideGallery/SlideGalleryArea.js")
.script("Front/Common/Scripts/RenderHelper.js")
.script("Front/Catalog/Scripts/RangeInput.js")
.script("Front/Common/Scripts/Run.js")<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Text
#
create_group('text', 'Текст')
@add2group('Параграф', 'text')
class Paragraph(Widget):
text = models.TextField("Текст", default="Text")
@add2group('Анонс', 'text')
class Announce(Widget):
text = models.TextField("Текст", default="Text")
@add2group('Цитата', 'text')
class Quote(Widget):
text = models.TextField("Текст", default="Text")
@add2group('Заметка', 'text')
class Note(Widget):
text = models.TextField("Текст", default="Text")
<file_sep>var AlphabetFilter = Base.extend({
constructor: function(){
this._links = $(".alphabet_filter a");
this._renderContainer = $(".alphabet_result_container");
this._renderBlock = $(".alphabet_result");
},
registerHandlers: function(){
var self = this;
this._links.click(function(){
var link = $(this);
self.removeSelected();
self.addSelected(link);
var symbol = self.getSymbol(link);
self.hideResult(function(){
self.sendSymbol(symbol);
});
return false;
});
},
hideResult: function(complete){
this._renderContainer.slideUp({
complete: complete
});
},
renderResult: function(html){
this._renderBlock.html(html);
this._renderContainer.slideDown();
},
sendSymbol: function(symbol){
var self = this;
$.ajax({
url: "get_symbol.php",
type: "POST",
dataType: "json",
data: { symbol: $.toJSON(symbol) },
success: function(data){
self.renderResult(data);
}
});
},
getSymbol: function(link){
return link.text();
},
removeSelected: function(){
this._links.removeClass("selected");
},
addSelected: function(link){
link.addClass("selected");
}
});<file_sep># -*- coding: utf-8 -*-
import md5
import random
from django.db import models
from widgets.models import Widget
class Metatag(models.Model):
name = models.CharField(verbose_name="Metatag URL Slug", max_length=255, unique=True)
title = models.TextField(verbose_name="Metatag Title", null=True, blank=True)
description = models.TextField(verbose_name="Metatag Description", null=True, blank=True)
keywords = models.TextField(verbose_name="Metatag Keywords", null=True, blank=True)
def __unicode__(self):
return self.name
class Hash(models.Model):
type = models.CharField(max_length=32)
key = models.CharField(max_length=255)
hash_string = models.CharField(max_length=32)
@staticmethod
def link2hash(link):
try:
hash_string = Hash.objects.values('hash_string') \
.get(type='link', key=link)['hash_string']
return str(hash_string)
except:
hash_string = Hash.encrypt(link)
new_hash = Hash(type='link', key=link, hash_string=hash_string)
new_hash.save()
return hash_string
@staticmethod
def widget2hash(widget_id):
widget_id = str(widget_id)
try:
hash_string = Hash.objects.values('hash_string') \
.get(type='widget', key=widget_id)['hash_string']
return str(hash_string)
except:
hash_string = Hash.encrypt(widget_id)
new_hash = Hash(type='widget', key=widget_id, hash_string=hash_string)
new_hash.save()
return hash_string
@staticmethod
def hash2link(hash_string):
try:
link = Hash.objects.values('key').get(hash_string=hash_string)['key']
return link
except:
return '#'
@staticmethod
def hash2widget(hash_string):
try:
widget_id = Hash.objects.values('key').get(hash_string=hash_string)['key']
widget = Widget.objects.get(pk=widget_id).as_leaf_class()
return widget.render(force_unhashed=True)
except:
return ''
@staticmethod
def encrypt(key):
return md5.new(str(random.random()) + str(key)).hexdigest()
<file_sep># -*- coding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from catalogapp.models import Section
def index(request):
context = RequestContext(request)
context['sections'] = Section.objects.order_by('id')[0:]
return render_to_response('catalog/index.html', context)
def section(request, section):
context = RequestContext(request)
context['section'] = section = get_object_or_404(Section, slug=section)
return render_to_response('catalog/landing.html', context)<file_sep># -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from models import TagName
def search(request):
result = {}
alphabet = json.loads(request.POST['alphabet'])
for tag in TagName.objects.all():
length = tag.name.split()
if length <= 0:
pass
elif length == 1:
if tag.name[0].lower() == alphabet.lower() and tag.name.lower() != u'для' and tag.name.lower() != u'на':
name = '|' + tag.name[1:]
name = {'caption': name, 'path': tag.slug}
if result.has_key(1):
result[1].append(name)
else:
result[1] = [name]
else:
words = tag.name.split()
count = 0
for word in words:
count += 1
if word[0].lower() == alphabet.lower() and word.lower() != u'для' and word.lower() != u'на':
if word[0] == alphabet:
repl = ' |'
else:
repl = ' ||'
name = ' '.join(tag.name.split()[:count-1]) + repl + word[1:] + ' ' + ' '.join(tag.name.split()[count:])
name = {'caption': name, 'path': tag.slug}
if result.has_key(count):
result[count].append(name)
else:
result[count] = [name]
return HttpResponse(json.dumps(result)) <file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
create_group('common', 'Другие')
@add2group('Контейнер', 'common')
class Container(Widget):
sub_zones_type = 'container'
sub_zones_count = 1
@add2group('HR', 'common')
class Hr(Widget):
pass<file_sep># -*- coding: utf8 -*-
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('chat.views',
url(r'^chat/reg/$', 'reg'),
url(r'^$', 'index'),
)<file_sep># -*- coding: utf-8 -*-
import re
class AphalineMiddleware:
aph_pattern = re.compile(r"""aph-[-_a-zA-Z]+=['"](.*?)['"]""")
def process_request(self, request):
if request.GET.get('v') == 'edit':
request.session['aphaline_edit_mode'] = True
elif request.GET.get('v') == 'default':
request.session['aphaline_edit_mode'] = False
elif request.session.get('aphaline_edit_mode') is None:
request.session['aphaline_edit_mode'] = False
def process_response(self, request, response):
try:
if request.user.is_staff == False or not request.session.get('aphaline_edit_mode'):
response.content = self.aph_pattern.sub('', response.content)
if request.user.is_staff == False:
return response
elif (
request.session.get('aphaline_edit_mode') is None
or request.session['aphaline_edit_mode'] == False
):
response.set_cookie('aphaline_edit_mode', 0)
return response
else:
response.set_cookie('aphaline_edit_mode', 1)
return response
except AttributeError:
# redirect detected
return response <file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
create_group('common', 'Другие')
@add2group('Социальные виджеты', 'common')
class Social(Widget):
pass
<file_sep># -*- coding: utf8 -*-
from models import *
from django.shortcuts import get_object_or_404
#first
def get_catalog(catalog):
set = {}
catalog = get_object_or_404(Catalog, slug=catalog)
products = Product.objects.filter(catalog=catalog)
for product in products:
for setgroup in product.setgroup_set.all():
set[setgroup.set.id] = setgroup.set
return set.values()
def get_brand(catalog, brand):
set = {}
catalog = get_object_or_404(Catalog, slug=catalog)
brand = get_object_or_404(Manufacturer, slug=catalog)
products = Product.objects.filter(catalog=catalog, manufacturer=brand)
for product in products:
for setgroup in product.setgroup_set.all():
set[setgroup.set.id] = setgroup.set
return set.values()
def get_type(catalog, type):
set = {}
catalog = get_object_or_404(Catalog, slug=catalog)
type = get_object_or_404(TypeA, slug=catalog)
products = Product.objects.filter(catalog=catalog, types=type)
for product in products:
for setgroup in product.setgroup_set.all():
set[setgroup.set.id] = setgroup.set
return set.values()
def get_brand_and_type(brand, type):
set = {}
catalog = get_object_or_404(Catalog, slug=catalog)
type = get_object_or_404(TypeA, slug=catalog)
brand = get_object_or_404(Manufacturer, slug=catalog)
products = Product.objects.filter(catalog=catalog, types=type, manufacturer=brand)
for product in products:
for setgroup in product.setgroup_set.all():
set[setgroup.set.id] = setgroup.set
return set.values()
#second
def set_catalog(catalog, set):
result = []
set = Set.objects.get(slug=set)
catalog = get_object_or_404(Catalog, slug=catalog)
for setgroup in set.setgroup_set.all():
products = {}
for product in setgroup.product.filter(catalog=catalog):
products[product.id] = product
result.append({'setgroup': setgroup.name, 'products': products.values()})
return result
def set_brand(catalog, brand, set):
result = []
set = Set.objects.get(slug=set)
catalog = get_object_or_404(Catalog, slug=catalog)
brand = get_object_or_404(Manufacturer, catalog=catalog, slug=brand)
for setgroup in set.setgroup_set.all():
products = {}
for product in setgroup.product.filter(catalog=catalog, manufacturer=brand):
products[product.id] = product
result.append({'setgroup': setgroup.name, 'products': products.values()})
return result
def set_type(catalog, type, set):
result = []
set = Set.objects.get(slug=set)
catalog = get_object_or_404(Catalog, slug=catalog)
type = get_object_or_404(TypeA, catalog=catalog, slug=type)
for setgroup in set.setgroup_set.all():
products = {}
for product in setgroup.product.filter(catalog=catalog, types=type):
products[product.id] = product
result.append({'setgroup': setgroup.name, 'products': products.values()})
return result
# def set_brand_and_type(catalog, brand, type, set):
# result = []
# set = Set.objects.get(slug=set)
# catalog = get_object_or_404(Catalog, slug=catalog)
# type = get_object_or_404(TypeA, catalog=catalog, slug=type)
# brand = get_object_or_404(Manufacturer, catalog=catalog, slug=brand)
# for setgroup in set.setgroup_set.all():
# products = {}
# for product in setgroup.product.filter(catalog=catalog, types=type, manufacturer=brand):
# products[product.id] = product
# result.append({'setgroup': setgroup.name, 'products': products.values()})
# return result
<file_sep># -*- coding: utf-8 -*-
from models import Metatag
def seo_tags(request):
try:
return { 'metatag': Metatag.objects.get(name=request.path) }
except:
return {}
def phone(request):
return {'phone': Metatag.get_property(request.path, 'phone')}
def background(request):
return {'background': Metatag.get_property(request.path, 'image')}<file_sep># -*- coding: utf-8 -*-
from django.db import models
from pixelion.apps.widgets.models import Widget
class SimpleText(Widget):
TEXT_TYPE_CHOICES = (
(1, 'Обычный текст'),
(2, 'Цитата'),
(3, 'Заметка'),
)
text = models.TextField("Текст", default="")
text_type = models.PositiveIntegerField("Тип текстового блока", choices=TEXT_TYPE_CHOICES, default=1)
class Cite(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = '2'
self.type = 'SimpleText'
super(Cite, self).save(*args, **kwargs)
class Meta:
proxy = True
class Tip(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = '3'
self.type = 'SimpleText'
super(Tip, self).save(*args, **kwargs)
class Meta:
proxy = True
class CharsTable(Widget):
text = models.TextField("Текст", default="Свойство 1 :: Значение 1\nСвойство 2 :: Значение 2\nСвойство 3 :: Значение 3")
def get_pairs(self):
result = []
lines = self.text.split("\n")
for line in lines:
try:
kv = line.split("::")
result.append({ 'key': kv[0].strip(), 'value': kv[1].strip() })
except:
pass
return result
<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from utils.shortcuts import paginate
from models import Product, Section, Catalog, Pricing, NewCollection
from models import BooleanPropertyValue, CharPropertyValue, NumericPropertyValue, MultipleChoicePropertyValue, Property, Choice, Action
from order import Order, OrderForm
from title.models import Title, ChangeTitle
from seo.models import Metatag
from utils.decorators import staff_required
from utils.tree import build_tree
from structure.models import SectionType
from questanswer.models import QuestAnswer
#from questanswer.mail_sender import send_mail
from basket import Basket
import json
PRODUCTS_ON_PAGE = 32
COLLECTIONS_ON_PAGE = 10
def get_default_context(request):
"""
Gets default context variables for catalog:
- Subtree of catalog section
- "New collections"
"""
context = RequestContext(request)
catalog_order = Section.objects.values('order').get(path='/catalog/')['order']
context['catalog_tree'] = context['structure'][1]['nodes'][catalog_order]['nodes']
return context
def get_extended_properties(product):
# Calculating "extended" properties
props = product.catalog.properties.all()
# Filling properties with their values
charpvs = CharPropertyValue.objects.filter(position=product)
numpvs = NumericPropertyValue.objects.filter(position=product)
boolpvs = BooleanPropertyValue.objects.filter(position=product)
mulpvs = MultipleChoicePropertyValue.objects.filter(position=product)
properties = {}
for p in props:
if p.type == 4:
properties[p.name] = {'val': p.choice_set.get(is_default=True).value, 'val_desc': p.choice_set.get(is_default=True).description, 'obj': p.description}
elif p.type == 3:
properties[p.name] = {'val': p.default and "Да" or "Нет", 'val_desc': p.description, 'obj': p.description}
else:
properties[p.name] = {'val' :p.default, 'val_desc': p.description, 'obj': p.description}
for p in charpvs:
properties[p.property.name] = {'val': p.value, 'val_desc': p.value.description, 'obj': p.property.description}
for p in numpvs:
properties[p.property.name] = {'val': p.value, 'val_desc': p.value.description, 'obj': p.property.description}
for p in boolpvs:
properties[p.property.name] = {'val': p.value and "Да" or "Нет", 'val_desc': p.value.description, 'obj': p.property.description}
for p in mulpvs:
properties[p.property.name] = {'val': p.value.value, 'val_desc': p.value.description, 'obj': p.property.description}
return properties
# Index page
def index(request):
context = get_default_context(request)
context['catalog_positions'] = Product.objects.filter(is_exist=True,
on_main=True,
is_enabled=True
).order_by('?')[:8]
return render_to_response('catalog/index.html', context)
# Catalog list (any sub-section)
def catalog_list(request, page=None):
context = get_default_context(request)
# Getting catalog for the section
# @todo improve! o___O
cs = context['current_section']
if cs.path != '/catalog/':
if Catalog.objects.filter(section=cs):
context['catalog'] = Catalog.objects.get(section=cs)
elif Catalog.objects.filter(section=cs.parent):
context['catalog'] = Catalog.objects.get(section=cs.parent)
elif Catalog.objects.filter(section=cs.parent.parent):
context['catalog'] = Catalog.objects.get(section=cs.parent.parent)
else:
context['catalog'] = Catalog.objects.get(section=cs.parent.parent.parent)
context['catalog_properties'] = context['catalog'].properties.all()
else:
context['catalog'] = None
context['catalog_properties'] = []
for p in context['catalog_properties']:
if p.type == 4:
fv = request.GET.getlist(p.slug)
if fv is not None:
arr = []
for v in fv:
arr.append(int(v))
p.filtered_values = arr
else:
fv = request.GET.get(p.slug)
if fv is not None:
p.filtered_value = fv
# Is it terminal section or not?
if context['current_section'].has_children():
# Non-terminal section
context['subsections'] = context['current_section'].children.filter(is_enabled=True)
current_path = context['current_section'].path
descendants_ids = Section.objects.filter(path__startswith=current_path).values('id')
descendants_ids = [x['id'] for x in descendants_ids]
if context['aphaline_edit_mode']:
paginate(
context, 'catalog_positions',
Product.objects.filter(section__in=descendants_ids) \
.filter(is_exist=True).order_by('-is_enabled', '-order'),
count=PRODUCTS_ON_PAGE, page=page,
root=context['current_section'].path
)
else:
paginate(
context, 'catalog_positions',
Product.objects.filter(section__in=descendants_ids) \
.filter(is_exist=True, is_enabled=True).order_by('-order'),
count=PRODUCTS_ON_PAGE, page=page,
root=context['current_section'].path
)
return render_to_response('catalog/list_nonterminal.html', context)
else:
if context['aphaline_edit_mode']:
paginate(
context, 'catalog_positions',
Product.objects.filter(section=context['current_section']).order_by('-is_enabled', '-is_exist', '-order'),
count=PRODUCTS_ON_PAGE, page=page,
root=context['current_section'].path
)
else:
paginate(
context, 'catalog_positions',
Product.objects.filter(section=context['current_section'], is_enabled=True).order_by('-is_exist', '-order'),
count=PRODUCTS_ON_PAGE, page=page,
root=context['current_section'].path
)
return render_to_response('catalog/list_terminal.html', context)
# Catalog item
def catalog_item(request, slug):
context = get_default_context(request)
product = get_object_or_404(Product, slug=slug)
context['catalog'] = product.catalog
context['catalog_properties'] = context['catalog'].properties.all()
for size in product.pricing_set.all():
if size.is_exist:
context['size_is_exist'] = size.size_id
break
for p in context['catalog_properties']:
if p.type == 4:
fv = request.GET.getlist(p.slug)
if fv is not None:
p.filtered_values = fv
else:
fv = request.GET.get(p.slug)
if fv is not None:
p.filtered_value = fv
context['catalog_position'] = product
context['catalog_position_wtp'] = product.wtp.all()
context['catalog_position_pricing'] = Pricing.objects.filter(product=product).order_by('size')
context['catalog_position_images'] = product.picture_set.all()
context['properties'] = get_extended_properties(product)
context['crumbs'].append({
'caption': product.name,
'path': context['current_section'].path + product.slug + '/'
})
basket = Basket(request.session)
context['order_count'] = basket.get_count(product.id)
#title
if not Metatag.objects.filter(name=context['current_section'].path + product.slug + '/') \
and product.catalog_id == 10: #пока что только для каталога Обувь
if not ChangeTitle.objects.filter(path=context['current_section'].path + product.slug + '/'):
word_1 = Title.objects.filter(position=1).order_by('?')[0].title
while True:
word_2 = Title.objects.filter(position=2).order_by('?')[0].title
if word_2.lower() != word_1.lower():
break
while True:
word_3 = Title.objects.filter(position=3).order_by('?')[0].title
if word_3.lower() != word_1.lower() and word_3.lower() != word_2.lower():
break
while True:
word_4 = Title.objects.filter(position=4).order_by('?')[0].title
if word_4.lower() != word_1.lower() and word_4.lower() != word_2.lower() and word_4.lower() != word_3.lower():
break
title = ChangeTitle(path=context['current_section'].path + product.slug + '/', title='%s %s %s %s %s' % (word_1, word_2, context['catalog_position'].name, word_3, word_4))
title.save()
context['catalog_position'].title = '%s %s %s %s %s' % (word_1, word_2, context['catalog_position'].name, word_3, word_4)
else:
context['catalog_position'].title = ChangeTitle.objects.filter(path=context['current_section'].path + product.slug + '/')[0].title
#title
if request.method == 'POST':
context['author_error'] = False
context['mes_error'] = False
if not request.POST.get('q_autor', ''):
context['author_error'] = True
else:
context['q_autor'] = request.POST['q_autor']
if not request.POST.get('q_mes', ''):
context['mes_error'] = True
else:
context['q_mes'] = request.POST['q_mes']
if context['author_error'] or context['mes_error']:
pass
else:
qa = QuestAnswer(author = context['q_autor'], question = context['q_mes'])
# send_mail(context['q_autor'], context['q_mes'])
qa.save()
qa.product_set.add(product)
context['ok'] = True
context['unanswered'] = product.qa.order_by('-date_publication').filter(is_public=False)
context['questanswer'] = product.qa.order_by('-date_publication').filter(is_public=True)
if 'ajax' in request.GET:
return render_to_response('catalog/position_ajax.html', context)
else:
return render_to_response('catalog/position.html', context)
@staff_required
def catalog_all(request):
context = get_default_context(request)
context['catalog_all'] = Product.objects.filter(section=context['current_section']).order_by('-order')
return render_to_response('catalog/catalog_all.html', context)
@staff_required
def move_position(request, id, new_order):
try:
product = Product.objects.get(pk=id)
product.move(new_order)
product.save()
return HttpResponse('OK')
except:
return HttpResponse('BAD')
@staff_required
def catalog_shuffle(request):
import random
context = get_default_context(request)
catalog = Product.objects.filter(section=context['current_section'])
count = range(1, len(catalog)+1)
for position in catalog:
current_random = count.pop((random.randint(1, len(count)))-1)
position.move(current_random)
position.save()
return HttpResponseRedirect('../')
def collections_list(request, page=None):
context = get_default_context(request)
context['collections'] = NewCollection.objects.filter(is_active=True)
paginate(
context, 'collections',
NewCollection.objects.filter(is_active=True).order_by('-id'),
count=COLLECTIONS_ON_PAGE, page=page,
root=context['current_section'].path
)
context['disables'] = NewCollection.objects.filter(is_active=False).order_by('-id')
return render_to_response('collections/collections.html', context)
def collections_item(request, slug, page=None):
context = get_default_context(request)
context['collection'] = get_object_or_404(NewCollection, slug=slug)
context['crumbs'].append({
'caption': context['collection'].name,
'path': slug,
})
paginate(
context, 'positions',
query=NewCollection.objects.get(slug=slug).products.all().filter(is_enabled=True),
count=PRODUCTS_ON_PAGE, page=page,
root=context['current_section'].path+slug+'/'
)
return render_to_response('collections/collections-item.html', context)
def basket_list(request):
context = get_default_context(request)
basket = Basket(request.session)
basket_items = basket.get_list()
if request.method == 'GET':
# Showing basket to user
context['basket'] = basket_items
context['form'] = OrderForm()
else:
# Checking and posting the order
form = OrderForm(request.POST)
if form.is_valid():
# Valid order
# Saving to the model
order = Order()
form_cd = form.cleaned_data
summary_info = basket.get_summary_info()
context['fields'] = order.send_mail(form_cd, basket_items, summary_info, request.session)
basket.clear()
return render_to_response('basket/good.html', context)
else:
# Invalid order: repeating form
context['basket'] = basket_items
context['form'] = form
return render_to_response('basket/index.html', context)
@staff_required
def wtp(request, pk):
context = get_default_context(request)
# type = SectionType.objects.get(slug='catalog')
nodes = Section.objects.filter(is_enabled=True).values()
context['structure'] = build_tree(nodes)
context['pk'] = pk
return render_to_response('wtp/index.html', context)
@staff_required
def wtp_catalog(request, pid):
context = get_default_context(request)
product = Product.objects.get(pk=pid)
wtp_pid = []
for wtp in product.wtp.all():
wtp_pid.append(wtp.id)
context['wtp_pid'] = wtp_pid
context['catalog'] = Product.objects.filter(section=Section.get_node_by_path(request.POST['current_section'])).order_by('-order')
return render_to_response('wtp/catalog.html', context)
#return HttpResponse(request.POST['current_section'])
@staff_required
def wtp_add(request, pid, wtp_pid):
context = get_default_context(request)
product = Product.objects.get(pk=pid)
wtp_product = Product.objects.get(pk=wtp_pid)
product.wtp.add(wtp_product)
return HttpResponse('Product #%s add in %s' % (wtp_pid, pid))
@staff_required
def wtp_del(request, pid, wtp_pid):
context = get_default_context(request)
product = Product.objects.get(pk=pid)
wtp_product = Product.objects.get(pk=wtp_pid)
product.wtp.remove(wtp_product)
return HttpResponse('Product #%s delete %s' % (wtp_pid, pid))
@staff_required
def collection_index(request, id):
context = get_default_context(request)
nodes = Section.objects.filter(is_enabled=True).values()
context['structure'] = build_tree(nodes)
context['collection_id'] = id
return render_to_response('change_collection/index.html', context)
@staff_required
def collection_catalog(request, id):
context = get_default_context(request)
product_in_collecion = NewCollection.objects.get(pk=id)
collecion_id = []
for product in product_in_collecion.products.all():
collecion_id.append(product.id)
context['collecion_id'] = collecion_id
context['catalog'] = Product.objects.filter(section=Section.get_node_by_path(request.POST['current_section'])).order_by('-order')
return render_to_response('change_collection/catalog.html', context)
@staff_required
def collection_add(request, id, add_id):
context = get_default_context(request)
collection = NewCollection.objects.get(pk=id)
product = Product.objects.get(pk=add_id)
collection.products.add(product)
return HttpResponse('Product #%s add in %s collection' % (add_id, id))
@staff_required
def collection_del(request, id, del_id):
context = get_default_context(request)
collection = NewCollection.objects.get(pk=id)
product = Product.objects.get(pk=del_id)
collection.products.remove(product)
return HttpResponse('Product #%s delete %s collection' % (del_id, id))
def filter(request):
context = get_default_context(request)
catalog = request.POST['catalog']
price_max = request.POST['price_max']
price_min = request.POST['price_min']
size = json.loads(request.POST['size'])
context['product'] = Product.filter(str(catalog), int(price_min), int(price_max), size).values()
return render_to_response('catalog/product.html', context)
@staff_required
def change_property(request):
context = get_default_context(request)
try:
product = Product.objects.get(pk=request.POST['position'])
mulcpv = MultipleChoicePropertyValue.objects.filter(position=product)
property = Property.objects.get(pk=request.POST['property'])
mulcpv = mulcpv.get(property=property)
choise = Choice.objects.get(pk=request.POST['choise'])
mulcpv.value = choise
mulcpv.save()
except:
product = Product.objects.get(pk=request.POST['position'])
property = Property.objects.get(pk=request.POST['property'])
choise = Choice.objects.get(pk=request.POST['choise'])
mulcpv = MultipleChoicePropertyValue(property=property, value=choise)
product.multiplechoicepropertyvalue_set.add(mulcpv)
product.save()
return HttpResponse(request.POST['choise'] + '||' +request.POST['property'] + '||' +request.POST['position'] + '||')
def glossarium(request):
context = get_default_context(request)
propertys = Property.objects.all().order_by('name')
choices = Choice.objects.filter(property__in=propertys).order_by('value')
result = {}
for property in propertys:
if property.description:
result[property.name] = {'name': property.name, 'description': property.description}
for choice in choices:
if choice.description:
i = 1
name = choice.value
if result.has_key(name):
name = choice.value + str(i)
while result.has_key(name):
i += 1
name = choice.value + str(i)
result[name] = {'name': choice.value, 'property': choice.property.name, 'description': choice.description}
keys = result.keys()
keys.sort()
context['return_resul'] = []
for key in keys:
context['return_resul'].append(result[key])
return render_to_response('catalog/glossarium.html', context)
#def action(request):
# context = get_default_context(request)
# action = Product.objects.filter(is_exist=True, is_enabled=True).order_by('id')
# context['result'] = []
# for a in action:
# if a.position_pricing_if_exists() and a.size_is_exists():
# result.append(a)
# return render_to_resonse('catalog/action.html', context)
def action_list(request, page=None):
context = get_default_context(request)
context['actions'] = Action.objects.filter(is_active=True)
paginate(
context, 'actions',
Action.objects.filter(is_active=True).order_by('-id'),
count=COLLECTIONS_ON_PAGE, page=page,
root=context['current_section'].path
)
context['disables'] = Action.objects.filter(is_active=False).order_by('-id')
return render_to_response('action/action.html', context)
def action_item(request, slug, page=None):
context = get_default_context(request)
context['action'] = get_object_or_404(Action, slug=slug)
context['crumbs'].append({
'caption': context['action'].name,
'path': slug,
})
paginate(
context, 'positions',
query=Action.objects.get(slug=slug).products.all().filter(is_enabled=True),
count=PRODUCTS_ON_PAGE, page=page,
root=context['current_section'].path+slug+'/'
)
return render_to_response('action/action-item.html', context)
@staff_required
def action_index(request, id):
context = get_default_context(request)
nodes = Section.objects.filter(is_enabled=True).values()
context['structure'] = build_tree(nodes)
context['action_id'] = id
return render_to_response('change_action/index.html', context)
@staff_required
def action_catalog(request, id):
context = get_default_context(request)
product_in_actions = Action.objects.get(pk=id)
action_id = []
for product in product_in_actions.products.all():
action_id.append(product.id)
context['action_id'] = action_id
context['catalog'] = Product.objects.filter(section=Section.get_node_by_path(request.POST['current_section'])).order_by('-order')
return render_to_response('change_action/catalog.html', context)
@staff_required
def action_add(request, id, add_id):
context = get_default_context(request)
action = Action.objects.get(pk=id)
product = Product.objects.get(pk=add_id)
action.products.add(product)
return HttpResponse('Product #%s add in %s action' % (add_id, id))
@staff_required
def action_del(request, id, del_id):
context = get_default_context(request)
action = Action.objects.get(pk=id)
product = Product.objects.get(pk=del_id)
action.products.remove(product)
return HttpResponse('Product #%s delete %s action' % (del_id, id))
def nova(request):
context = get_default_context(request)
products = Product.objects.filter(is_exist=True).order_by('-date', '-order')
context['positions'] = []
for product in products:
if product.nova():
context['positions'].append(product)
return render_to_response('catalog/nova.html', context)
<file_sep># -*- coding: utf-8 -*-
import json
from math import ceil
from itertools import izip_longest
from operator import attrgetter
from django.http import HttpResponse
from models import Catalog
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
def search(request):
result = {}
alphabet = json.loads(request.POST['alphabet'])
catalogs = Catalog.objects.all().order_by('name_short')
for catalog in catalogs:
length = catalog.name_short.split()
l = len(length)
if l <= 0:
continue
elif l == 1:
if catalog.name_short[0].lower() == alphabet.lower() and catalog.name_short.lower() != u'для' and catalog.name_short.lower() != u'на':
name = '|' + catalog.name_short[1:]
name = {'caption': name, 'path': catalog.slug}
if result.has_key(1):
result[1].append(name)
else:
result[1] = [name]
else:
words = catalog.name_short.split()
count = 0
for word in words:
count += 1
if word[0].lower() == alphabet.lower() and word.lower() != u'для' and word.lower() != u'на':
if word[0] == alphabet:
repl = ' |'
else:
repl = ' ||'
name = ' '.join(catalog.name_short.split()[:count-1]) + repl + word[1:] + ' ' + ' '.join(catalog.name_short.split()[count:])
name = {'caption': name, 'path': catalog.slug}
if result.has_key(count):
result[count].append(name)
else:
result[count] = [name]
plain_list = []
for i in result.values():
plain_list.extend(i)
rows = int(ceil(float(len(plain_list))/3))
matrix = grouper(rows, plain_list)
matrix = list(map(lambda *x:x, *matrix))
final_result = []
for i in matrix:
final_result.extend(i)
return HttpResponse(json.dumps(final_result))<file_sep># -*- coding: utf8 -*-
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
import json
from models import TestText
def index(request):
context = RequestContext(request)
context['sample'] = TestText.objects.all().order_by('?')[0]
return render_to_response('livesearch/index.html', context)
@csrf_exempt
def livesearch(request):
# try:
translation = {}
context = RequestContext(request)
results = TestText.objects.filter(text__icontains=request.POST['search'])
for result in results:
translation[result.id] = {
'perevod': result.perevod,
'text': result.text,
}
return HttpResponse(json.dumps(translation))
# except:
# return HttpResponse(json.dumps({}))<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from json import dumps
from catalog.models import Catalog
def index(request):
context = RequestContext(request)
context['catalogs'] = Catalog.objects.all()
return render_to_response('index.html', context)
def text(request):
context = RequestContext(request)
context['catalogs'] = Catalog.objects.all()
return render_to_response('text.html', context)
def json(request):
items = Catalog.objects.values('big_sharp_picture', 'name_long', 'description', 'link_text', 'small_thumb', 'name_short')
for i in xrange(len(items)):
items[i]['id'] = i
json_list = list(items)
json = dumps(json_list)
return HttpResponse(json)<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from catalog.models import Section
def get_default_context(request, _path):
"""
Gets default context variables for catalog:
- Subtree of catalog section
- "New collections"
"""
context = RequestContext(request)
catalog_order = Section.objects.values('order').get(path=_path)['order']
context['catalog_tree'] = context['structure'][1]['nodes'][catalog_order]['nodes']
return context
def text(request):
context = get_default_context(request, request.path)
return render_to_response('text.html', context)<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Client, Site, Domain
from theming import Template, FontTheme, ColorTheme
from utils.colorfield import ColorPickerWidget
admin.site.register(Client)
admin.site.register(Site)
admin.site.register(Domain)
admin.site.register(Template)
class ColorAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == 'color':
kwargs['widget'] = ColorPickerWidget
return super(ColorAdmin, self).formfield_for_dbfield(db_field, **kwargs)
class FontAdmin(admin.ModelAdmin):
list_display = ('caption', 'font_theme')
admin.site.register(ColorTheme, ColorAdmin)
admin.site.register(FontTheme, FontAdmin)
<file_sep>Aphaline.Structure = {
var dom = '';
}<file_sep># -*- coding: utf-8 -*-
from django.db import models
from widgets.models import Zone
class Phone(models.Model):
url_part = models.CharField(verbose_name=u"Корень категории с которой вглубь будет виден данный телефон", max_length=255)
phone = models.CharField(verbose_name=u"Phone number", max_length=255)
def __unicode__(self):
return self.phone
class Meta:
verbose_name_plural = u'Телефонный номер'
class Banner(models.Model):
img = models.ImageField(u'Картинка', upload_to="img/")
url_part = models.CharField(verbose_name=u"Корень категории с которой вглубь будет показана данная картинка", max_length=255)
url = models.CharField(u'Ссылка', max_length=255, blank=True)
def __unicode__(self):
return self.url_part
class Meta:
verbose_name_plural = u'Баннер'
class Footer(models.Model):
zone = models.OneToOneField(Zone, null=True, blank=True)
<file_sep># -*- coding: utf-8 -*-
from django.test import TestCase
from catalogapp import api
from catalogapp import models
class SectionsTest(TestCase):
def __init__(self, *args, **kwargs):
super(SectionsTest, self).__init__(*args, **kwargs)
# Set test sps_array
self.sps_array = [{
"field_type": "BooleanField",
"name": "boolfield",
"slug": "bool_slug",
"default_value": True,
"description": "Some desc",
},
{
"field_type": "TextField",
"name": "charfield",
"slug": "char_slug",
"default_value": "some string",
"description": "Some desc",
},]
def test_create(self):
result_id = api.sections.create("Name", "slug")
self.assertTrue(isinstance(result_id, int))
def test_delete(self):
result_id = api.sections.create("Name", "slug")
result = api.sections.delete(result_id)
self.assertTrue(result)
def test_rename(self):
# Test name
result_id = api.sections.create("Name", "slug")
api.sections.rename(result_id, "New name")
section = api.sections.get(result_id)
self.assertEqual(section.name, "New name")
self.assertEqual(section.slug, "slug")
# Test name + slug
api.sections.rename(result_id, "New name 2", "someslug")
section = api.sections.get(result_id)
self.assertEqual(section.name, "New name 2")
self.assertEqual(section.slug, "someslug")
def test_addFields(self):
section_id = api.sections.create("Name", "slug")
result = api.sections.addFields(section_id, self.sps_array)
self.assertEqual(result, [1, 2])
def test_removeFields(self):
# Create 4 fields
section_id = api.sections.create("Name", "slug")
result = api.sections.addFields(section_id, self.sps_array)
result = api.sections.addFields(section_id, self.sps_array)
# Direct access to field objects only for test
c = models.BaseField.objects.filter(section__id=section_id).count()
self.assertEqual(c, len(self.sps_array)*2)
result = api.sections.removeFields(section_id, [1,3])
# Direct access to field objects only for test
c = models.BaseField.objects.filter(section__id=section_id)
self.assertEqual(len(c), len(self.sps_array)*2-2)
self.assertEqual(c[0].id, 2)
self.assertEqual(c[1].id, 4)
def test_getFields(self):
section_id = api.sections.create("Name", "slug")
# Create 4 fields
result = api.sections.addFields(section_id, self.sps_array)
result = api.sections.addFields(section_id, self.sps_array)
fields = api.sections.getFields(section_id)
self.assertEqual(len(fields), len(self.sps_array)*2)
def test_list(self):
api.sections.create("Name", "slug")
api.sections.create("Name", "slug2")
sections = api.sections.list(name='Name')
self.assertEqual(len(sections), 2)
def test_listIn(self):
ids = []
section_id = api.sections.create("Name", "slug")
ids.append(section_id)
api.sections.create("Name", "slug2")
api.sections.create("Name", "slug")
section_id = api.sections.create("Name", "slug2")
ids.append(section_id)
sections = api.sections.listIn(ids)
self.assertEqual(len(sections), 2)<file_sep>//function parseJSON(data) {
// return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))();
//}
var auto = [];
function livesearch(){
var search = $("#livesearch").val();
if(search.length >= 2){
$.ajax({
type: 'POST',
url: "/api/livesearch/",
data: {'search': search},
success: function(response){
if(response){
var html = '';
auto = [];
response = JSON.parse(response)
$.each(response, function() {
html += 'Слово: ' + this.text.replace(search, '<span style="background:green;">' + search + '</span>') + ', перевод: ' + this.perevod + '<br />';
auto.push(this.text);
});
console.log(auto);
$("#livesearch").autocomplete(auto, {
width: 200,
});
$("#liveoutput").html(html);
}else{
$('#liveoutput').html('')
}
},
error:function(e,r,s){
$("#liveoutput").html('Error' + e.responseText);
}
});
}else{
$("#liveoutput").html("");
}
return false;
}
$(document).ready(function() {
$("#livesearch").keyup(livesearch);
$("#livesearch").change(function(){
window.setTimeout(livesearch, 110);
});
});<file_sep><html>
<head>
<title>{% block title %}{% endblock %}</title>
{% block script %}
<link href="{{ STATIC_URL }}css/chat/style.css" rel="stylesheet" type="text/css"/>
<link href="{{ STATIC_URL }}css/chat/user.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/user.js"></script>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html><file_sep>var RenderHelper = Base.extend({},{
setColoredBorder: function(items){
items.addClass("colored_border");
},
listItems: function(lists){
lists.each(function(){
var list = $(this);
var count = 1;
list.find(">li").each(function(){
var item = $(this);
var num = $("<span class='item_num colored_bgColor colored_text'>"+count+".</span>");
num.prependTo(item);
count++;
});
});
},
renderTable: function(tables){
tables.each(function(){
var table = $(this);
table.attr('cellpadding','0').attr('cellspacing','0');
table.find("tr:last-child td").css("border-bottom","0");
table.find("tr td:last-child, tr th:last-child").css("border-right","0");
table.find("tr").mouseenter(function(){
$(this).addClass("hover");
}).mouseleave(function(){
$(this).removeClass("hover");
});
});
},
pseudoHover: function(elmHover, elmClass, className){
elmHover.mouseenter(function(){
elmClass.addClass(className);
}).mouseleave(function(){
elmClass.removeClass(className);
});
},
slideContent: function(link, content, pre){
link.click(function(){
pre();
content.slideToggle();
return false;
});
},
sizeCloud: function(items){
items.each(function(){
var rand = Math.floor(Math.random() * (11));
$(this).addClass("size"+rand);
});
}
});<file_sep># -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from models import Hash
def hashes2links(request):
if request.raw_post_data:
hashes = json.loads(request.raw_post_data)
result = {}
for h in hashes:
result[h] = Hash.hash2link(h)
return HttpResponse(json.dumps(result))
else:
return HttpResponse(json.dumps({}))<file_sep># -*- coding: utf-8 -*-
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Derter', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'firmir',
'USER': 'root',
'PASSWORD': '<PASSWORD>',
'HOST': 'localhost',
'PORT': '',
}
}
TIME_ZONE = 'Asia/Yekaterinburg'
LANGUAGE_CODE = 'ru-RU'
SITE_ID = 1
USE_I18N = False
USE_L10N = False
MEDIA_ROOT = '/work/media/firmir/sitefront/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/work/dev/firmir/sitefront/static/'
STATIC_URL = '/static/'
# ADMIN_MEDIA_PREFIX = '/static/admin-media/'
STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
SECRET_KEY = '6v5876rc^%*Ce56r7^V^&rv976rvC%sddb*5vdVBD*Ydsv7tdbntbvdcsTRDVUY%Dv8'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (
'/work/dev/firmir/sitefront/templates/',
'/work/dev/firmir/sitefront/widgets/templates/',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'pixelion.apps.widgets',
'widgets'
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# Widgets subclasses hierarchy
WIDGETS = {
# "headers": {
# "verbose_name": "Заголовки",
# "package": "widgets.headers",
# "items": [
# ("H1", "Заголовок 1"),
# ("H2", "Заголовок 2"),
# ("H3", "Заголовок 3"),
# ]
# },
"grid": {
"verbose_name": "Сетка",
"package": "widgets.grid",
"items": [
("Grid_100", "100"),
("Grid_50_50", "50/50"),
("Grid_66_33", "66/33"),
("Grid_33_66", "33/66"),
("Grid_33_33_33", "33/33/33"),
]
},
"text": {
"verbose_name": "Текст",
"package": "widgets.text",
"items": [
("SimpleText", "Абзац"),
("Cite", "Цитата"),
("Tip", "Заметка"),
("CharsTable", "Таблица характеристик"),
]
},
"lists": {
"verbose_name": "Списки",
"package": "widgets.lists",
"items": [
("NumericList", "Нумерованный список"),
("UnorderedList", "Маркированный список"),
]
}
}
<file_sep>Aphaline = {}
require(
["api", "widgetlist", "toolbar", "editor", "actions", "legacy", "interface"],
function() {
require.ready(function() {
Aphaline.Interface.init();
});
}
);
<file_sep>// Menu
$(document).ready(function(){
// Tables
$("#text table:not(.not-decorated), #position table:not(.not-decorated)").each(function() {
if ($(this).find("th").length==0) {
$(this).find("tr:nth-child(odd)").addClass("odd");
$(this).find("tr:nth-child(even)").addClass("even");
$(this).find("td").css("border-width","1px 1px 0 0").css("border-style","solid");
$(this).find("tr td:first-child").css("border-width","1px 1px 0 1px");
$(this).find("tr:last-child td").css("border-width","1px 1px 1px 0");
$(this).find("tr:last-child td:first-child").css("border-width","1px");
}
else {
$(this).find("tr:nth-child(odd)").addClass("even");
$(this).find("tr:nth-child(even)").addClass("odd");
$(this).find("td").css("border-width","0 1px 1px 0").css("border-style","solid");
$(this).find("tr td:first-child").css("border-width","0 1px 1px 1px");
$(this).find("th").css("border-width","1px 1px 1px 0").css("border-style","solid");
$(this).find("th:first").css("border-width","1px");
}
});
$("#catalog table td").css("border-style","dashed");
$("#catalog table th").css("border-bottom","0");
$("#catalog table th:last-child").css("border-width","0");
// Template2 news/specials h2
// if ($("#template2").length!=0 || $("#template5").length!=0) {
// if ($("#news").length==0 && $("#specials").length==0) {
// $(".collapse").hide();
// }
// else if ($("#news").length==0) {
// $(".right .collapse:first").hide();
// $(".right .collapse:last").removeClass("span-8").addClass("span-16");
// $("#specials li").css("width","50%").css("float","left");
// // }
// // else if ($("#specials").length==0) {
// // $(".right .collapse:last").hide();
// // $(".right .collapse:first").removeClass("span-8").addClass("span-16");
// // }
// }
// Temp
});
<file_sep><table cellpadding="0" cellspacing="0" class="chars_table">
{% for pair in current_widget.get_pairs %}
<tr>
<th><span>{{ pair.key }}</span></th>
<td>{{ pair.value }}</td>
</tr>
{% endfor %}
</table><file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from questanswer.models import QuestAnswer
from utils.shortcuts import paginate
from structure.models import Section, SectionType
from django.core.context_processors import csrf
from django.conf import settings
from mail_sender import send_mail
QA_ON_PAGE = 30
def questanswer(request, page=None):
context = RequestContext(request)
context['title'] = u'Вопрос-ответ'
if request.method == 'POST':
context['author_error'] = False
context['mes_error'] = False
if not request.POST.get('q_autor', ''):
context['author_error'] = True
else:
context['q_autor'] = request.POST['q_autor']
if not request.POST.get('q_mes', ''):
context['mes_error'] = True
else:
context['q_mes'] = request.POST['q_mes']
if context['author_error'] or context['mes_error']:
pass
else:
qa = QuestAnswer(author = context['q_autor'], question = context['q_mes'])
send_mail(context['q_autor'], context['q_mes'])
qa.save()
context['ok'] = True
context['unanswered'] = QuestAnswer.objects.order_by('-date_publication').filter(is_public=False)
paginate(
context, 'questanswer',
QuestAnswer.objects.order_by('-date_publication').filter(is_public=True),
count=QA_ON_PAGE, page=page,
root=context['current_section'].path
)
return render_to_response('qa/questanswer.html', context)
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from structure.models import Section, SectionType
from utils.tree import build_tree
import pytils
class Document(models.Model):
caption = models.CharField(max_length=100)
owner = models.ForeignKey(User)
title = models.CharField(max_length=100, blank=True, default='')
description = models.TextField(blank=True, default='')
def save(self, *args, **kwargs):
if not self.title:
self.title = self.caption
if self.id is None:
super(Document, self).save(*args, **kwargs)
section_type = SectionType.objects.get(pk=1)
Part.objects.create(caption=self.caption, document=self, path='/', type=section_type)
else:
super(Document, self).save(*args, **kwargs)
def __unicode__(self):
return self.caption
def create_part(self, parent, caption, slug='', section_type=None):
section_type = SectionType.objects.get(pk=1)
part = Part.create_section(self, parent, caption, slug, section_type)
return part
def get_parts_tree(self):
nodes = Part.objects.filter(document=self).values()
return build_tree(nodes)
def get_part_by_path(self, path):
path = '/' + path + '/'
node = Part.objects.extra(
select={ "subpath": "SUBSTR(%s, LENGTH(path)+1)" },
select_params=(path,),
where=["""
path = (
SELECT max(path)
FROM structure_section ss
INNER JOIN documents_part dp
ON ss.id = dp.section_ptr_id
WHERE locate(ss.path, %s) = 1
AND dp.document_id = %s
)
"""],
params=(path, self.id)
)[0]
return node
class Part(Section):
order_isolation_fields = ('document', 'parent')
document = models.ForeignKey(Document)
# x_x
@staticmethod
def create_section(document, parent, caption, slug='', section_type=None):
section = Part()
section.caption = caption
if slug == '':
slug = pytils.translit.slugify(caption)
if section_type is None:
section.type = parent.type.inherit_type
else:
section.type = section_type
while True:
section.path = parent.path + slug + '/'
if not Section.objects.filter(path=section.path):
break
else:
slug += '_'
section.parent = parent
section.document = document
section.save()
return section<file_sep>from django.db import models
from django.db.models import F
class SortableModel(models.Model):
"""
Abstract model which makes an inherited model's records sortable
by calling instance.move(position)
"""
order = models.IntegerField(default=0)
# List of fields which isolates orderings in subsets.
# For example, if there is "parent" field, order must be
# calculated within objects having same parent.
order_isolation_fields = None
class Meta:
abstract = True
ordering = ['order']
def save(self, *args, **kwargs):
"""
Assigns last order to position if it doesn't have an order already
"""
try:
if not self.order or self.order == 0:
isolation_filters = self._calc_isolation_filters()
last = self._get_class().objects \
.filter(**isolation_filters) \
.values('order') \
.order_by('-order')[0]
self.order = last['order'] + 1
except IndexError:
self.order = 1
finally:
super(SortableModel, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
"""
Decreases order for items with greater order on delete
"""
isolation_filters = self._calc_isolation_filters()
try:
last = self._get_class().objects \
.filter(**isolation_filters) \
.values('order') \
.order_by('-order')[0]['order']
super(SortableModel, self).delete(*args, **kwargs)
self._get_class().objects \
.filter(**isolation_filters) \
.filter(order__range=(self.order, last)) \
.update(order=F('order')-1)
except IndexError:
# There were no objects
super(SortableModel, self).delete(*args, **kwargs)
def move(self, to):
"""
Moves item to given position
"""
to = int(to)
if to < 1 and to != -1:
to = 1
orig = self._get_class().objects.get(pk=self.pk).order # self.order
if to == orig:
return
isolation_filters = self._calc_isolation_filters()
last = self._get_class().objects \
.filter(**isolation_filters) \
.values('order') \
.order_by('-order')[0]['order']
if to > last or to == -1:
to = last
shift, range = to < orig and (1, (to, orig-1)) or (-1, (orig+1, to))
self._get_class().objects \
.filter(**isolation_filters) \
.filter(order__range=range) \
.update(order=F('order')+shift)
self.order = to
self.save()
def _get_class(self):
return self.__class__
def _calc_isolation_filters(self):
"""
Returns a dict with arguments to pass to .filter()
to isolate ordering calculations
"""
isolation_filters = {}
if self.order_isolation_fields is not None:
for field in self.order_isolation_fields:
isolation_filters[field] = self.__getattribute__(field)
return isolation_filters
<file_sep># -*- coding: utf8 -*-
from models import TextOnPage
def textonpage(request):
try:
return {'textonpage': TextOnPage.objects.get(url=request.path)}
except:
return {}<file_sep>var Time = Base.extend({
constructor: function(){
this._hours = $(".footer_time_hours");
this._minutes = $(".footer_time_minutes");
this._time = $(".footer_time");
this.run();
},
run: function(){
var _this = this;
setInterval(function(){
_this.updateTime();
},1000);
},
updateTime: function(){
var date = new Date();
this._hours.text(this.leadingZero(date.getHours()));
this._minutes.text(this.leadingZero(date.getMinutes()));
this._time.toggleClass("footer_time__even");
},
leadingZero: function(num){
return num < 10 ? "0" + num : num;
}
});<file_sep>$(document).ready(function() {
if (readCookie('wrote_qa') != '') {
cur_date = new Date();
msg_date = new Date(readCookie('wrote_qa'));
diff = cur_date.getMinutes() - msg_date.getMinutes();
//alert(diff);
if (diff < 1) {
$('#q_form').hide();
$('#q_thankyou').show();
}
}
$('#q_submit').click( function() {
author = $('#q_autor').val();
message = $('#q_mes').val();
// Создаем запрос
query = {
id: '', query: [
{ type: 'insert',
rel: 'qa',
id: '',
rows: [
{ field: { name:'author', value:author.replace(/&/g, '%26') } },
{ field: { name:'message', value:message.replace(/&/g, '%26') } }
]
}
] };
query = $.toJSON(query);
callback = function() {
// Пишем куку
document.cookie = 'wrote_qa='+new Date();
// Перезагружаем страничку
window.location.reload();
}
$.post('/index.php?port=direct', 'query=' + query, callback);
return false;
});
});<file_sep>var FooterGallery = Base.extend({
constructor: function(){
this._container = $(".footer_gallery");
this._gallery = this._container.find(".footer_gallery_list");
this._items = this._gallery.find(".footer_gallery_item");
if ($("body").hasClass(FooterGallery.enabledClass))
this.register();
},
register: function(){
var _this = this;
var wrap = $("body").hasClass(IndexGallery.enabledClass) ? "circular" : null;
this._gallery.jcarousel({
scroll: 1,
start: _this.getSelectedNumber(),
itemFallbackDimension: 180,
wrap: wrap
});
this.registerItems();
$(".service_menu__power").click(function(){
$(this).toggleClass("selected");
_this._container.stop(false, true).slideToggle({ easing: "easeOutQuart", duration: 800 });
});
},
registerItems: function(){
this._items.each(function(){
var item = $(this);
// Delaying
var deferred = function(item) { return function() {
var img = item.find("img");
if (img.width() || !img.attr('src')) {
clearInterval(item.data('deferred_interval'));
}
var left = (item.width() - img.width())/2;
var border = item.find("."+FooterGallery.borderClass);
var fade = item.find("."+FooterGallery.fadeClass);
fade.css({
left: left,
width: img.width(),
height: img.height()
});
border.css({
left: left,
width: img.width() - 6,
height: img.height() - 6
});
}} (item);
item.data('deferred_interval', setInterval(deferred, 100));
}).click(function(){
if (!$(this).hasClass(FooterGallery.selectedClass))
window.location = $(this).find("a").attr("href");
});
},
getSelectedNumber: function(){
var counter = 0;
var number = 1;
this._items.each(function(){
counter++;
if ($(this).hasClass(FooterGallery.selectedClass))
number = counter;
});
return number - 2;
}
},{
selectedClass: "footer_gallery_item__selected",
borderClass: "footer_gallery_item_border",
fadeClass: "footer_gallery_item_fade",
enabledClass: "footer_gallery_enabled"
});<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Title, ChangeTitle
class TitleAdmin(admin.ModelAdmin):
list_display = ('title', 'position')
list_filter = ('position',)
admin.site.register(Title, TitleAdmin)
admin.site.register(ChangeTitle)
<file_sep># -*- coding: utf-8 -*-
import datetime
import Image
import ImageEnhance
import os
from django.db import models
from django.conf import settings
from structure.models import Section
# from utils.colorfield import ColorPickerWidget
from utils.thumbs import ImageWithThumbsField
from tinymce import models as tinymce_model
from widgets.models import Zone
from utils.sortable import SortableModel
def add_watermark(image, watermark, opacity=1):
import Image
import ImageEnhance
assert opacity >= 0 and opacity <= 1
if opacity < 1:
if watermark.mode != 'RGBA':
self.watermark = watermark.convert('RGBA')
else:
watermark = watermark.copy()
alpha = watermark.split()[3]
alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
watermark.putalpha(alpha)
layer = Image.new('RGBA', image.size, (0,0,0,0))
layer.paste(watermark, (0, (image.size[1]/2)-(watermark.size[1]/2)))
return Image.composite(layer, image, layer)
def thumbnail(path, sizes, watermark=None, ratio=False):
"""
Функция создания превью с возможностью наложения водяных знаков.
При этом фото лежит в любой папке, а превью помещаются на уровень выше.
-path - Полный путь до изображения
-sizes - Список, содержащий кортежи со значениями высоты и ширины
-watermark - Полный путь до водяного знака
"""
import Image
import os
original_path = path
path_to_save = '/'.join(path.split('/')[0:-2])
splitted_name = (path.split('/')[-1]).split('.')
name, ext = '.'.join(splitted_name[:-1]), splitted_name[-1]
if watermark:
fp = open(path, "rb")
im = Image.open(fp)
size = sizes.pop(0)
im.thumbnail((size[0], size[1]), Image.ANTIALIAS)
im.save('%s/%s.%s' % (path_to_save, name, ext), quality=100)
fp.close()
fp = open(path_to_save + '/' + name + '.' + ext, "rb")
im_1000 = Image.open(fp)
mark = Image.open(watermark)
result = add_watermark(im_1000, mark)
result.save('%s/%s.%s' % (path_to_save, name, ext), quality=100)
#result.save('{0}/{1}.{2}x{3}.{4}'.format(path_to_save, name, size[0], size[1], ext), quality=100)
result.save('%s/%s.%sx%s.%s' % (path_to_save, name, size[0], size[1], ext), quality=100)
fp.close()
for size in sizes:
fp = open(path_to_save + '/' + name + '.' + ext, "rb")
im_1000 = Image.open(fp)
im_1000.thumbnail((size[0], size[1]), Image.ANTIALIAS)
im_1000.save('%s/%s.%sx%s.%s' % (path_to_save, name, size[0], size[1], ext), quality=100)
#im_1000.save('{0}/{1}.{2}x{3}.{4}'.format(path_to_save, name, size[0], size[1], ext), quality=100)
fp.close()
if os.path.exists(path_to_save + '/' + name + '.' + ext):
os.remove(path_to_save + '/' + name + '.' + ext)
else:
for size in sizes:
im = Image.open(path)
im.thumbnail((size[0], size[1]), Image.ANTIALIAS)
im.save('%s/%s.%sx%s.%s' % (path_to_save, name, size[0], size[1], ext), quality=100)
#im.save('{0}/{1}.{2}x{3}.{4}'.format(path_to_save, name, size[0], size[1], ext), quality=100)
def get_image_url(url, sizes):
result = {}
url_thumbnail = '/'.join(url.split('/')[0:-2])
splitted_name = (url.split('/')[-1]).split('.')
name, ext = '.'.join(splitted_name[:-1]), splitted_name[-1]
for size in sizes:
#result.update({ u'{0}x{1}'.format(size[0], size[1]) : u'{0}/{1}.{2}x{3}.{4}'.format(url_thumbnail, name, size[0], size[1], ext)})
key = <KEY> (size[0], size[1])
value = '%s/%s.%sx%s.%s' % (url_thumbnail, name, size[0], size[1], ext)
result.update({ key : value })
return result
# Общие свойства сайта
class Globals(models.Model):
prop_slug = models.SlugField("Идентификатор свойства", max_length=32)
prop_name = models.CharField("Название свойства", max_length=255)
value = models.CharField("Значение", max_length=255)
class Meta:
verbose_name='Общее свойство'
verbose_name_plural='Общие свойства'
def __unicode__(self):
return self.prop_name
# Позиция каталога
class Position(SortableModel):
order_isolation_fields = ('section',)
caption = models.CharField(verbose_name="Заголовок", max_length=255,)
desc_short = models.TextField(verbose_name="Краткое описание", blank=True,)
desc_full = tinymce_model.HTMLField(verbose_name="Полное (развернутое) описание", editable=False, blank=True,)
is_exists = models.BooleanField(verbose_name="В наличии?", default=True,)
article = models.CharField(verbose_name="Артикул", blank=True, max_length=255,)
price_opt = models.DecimalField(verbose_name="Цена оптовая", max_digits=12, decimal_places=2, blank=True, null=True, editable=False)
price_rozn = models.DecimalField(verbose_name="Цена розничная", max_digits=12, decimal_places=2, blank=True, null=True)
section = models.ForeignKey(Section, verbose_name="Раздел каталога")
picture = models.ImageField("Изображение", upload_to='images/original/', blank=True, null=True)
tags = models.ManyToManyField('Tag', verbose_name='Метки', blank=True)
zone = models.OneToOneField(Zone, null=True, blank=True, editable=False)
def save(self, *args, **kwargs):
if self.id == None:
zone = Zone()
zone.save()
self.zone = zone
super(Position, self).save(*args, **kwargs)
if self.article == '':
self.article = 'A-' + str(self.id)
super(Position,self).save(*args,**kwargs)
if self.picture:
import Image
sizes = [
(1000, 1000),
(300, 300),
(150, 150),
]
image = Position.objects.get(pk=self.id)
path = image.picture.path
watermark = settings.MEDIA_ROOT + 'watermark/1000.png'
thumbnail(path, sizes, watermark)
def delete(self, *args, **kwargs):
self.zone.delete()
super(Position, self).delete(*args, **kwargs)
class Meta:
verbose_name='Товар'
verbose_name_plural='Товары'
def __unicode__(self):
return self.caption
@staticmethod
def get_image(position_id):
image = Position.objects.get(pk=position_id)
sizes = [
(1000, 1000),
(300, 300),
(150, 150),
]
result = []
s = get_image_url(image.picture.name, sizes)
result.append({'id': image.id, 'picture': s})
return result
def get_thumb(self):
return get_image_url(self.picture.url, [(150,150)])['150x150']
# Тэги
class Tag(models.Model):
tag = models.CharField("Имя тэга", max_length=30)
name = models.SlugField("URL Slug", max_length=255)
def __unicode__(self):
return self.tag + ' (' + self.name + ')'
class Meta:
verbose_name = u'Тэг'
verbose_name_plural = u'Тэги'
# Позиция "вопрос-ответа"
class QuestAnswer(models.Model):
author = models.CharField(verbose_name="Пользователь оставивший запись", max_length=255, default="Гость", editable=False)
publication_date = models.DateTimeField(verbose_name="Дата написания", null=True, blank=True, default=datetime.datetime.now,)
question = tinymce_model.HTMLField(verbose_name="Вопрос", )
moderator = models.CharField(verbose_name="Имя модератора", max_length=255, blank=True, default="Менеджер",)
answer = tinymce_model.HTMLField(verbose_name="Ответ", blank=True)
# tags = models.ManyToManyField('Tag', blank=True,)
is_public = models.BooleanField("Опубликовать?", default=False,)
class Meta:
verbose_name='Вопрос-ответ'
verbose_name_plural='Вопросы-ответы'
def __unicode__(self):
return self.question
#Позиция "отзыв"
class FeedbackFlora(models.Model):
author = models.CharField(u"ФИО", max_length=255, default="Гость")
punkt = models.CharField(u'Населённый пункт', max_length=255, blank=True)
work = models.CharField(u'Место работы', max_length=255, blank=True)
question = tinymce_model.HTMLField(u"Текст сообщения", )
publication_date = models.DateTimeField(u"Дата написания", null=True, blank=True, default=datetime.datetime.now,)
moderator = models.CharField(u"Имя модератора", max_length=255, blank=True, default="Менеджер",)
answer = tinymce_model.HTMLField(u"Ответ", blank=True)
is_public = models.BooleanField(u"Опубликовать?", default=False,)
class Meta:
verbose_name='Отзыв'
verbose_name_plural='Отзывы'
def __unicode__(self):
return self.question
# Изображение
class Image(models.Model):
caption = models.CharField(verbose_name="Название изображения", max_length=255,)
picture = ImageWithThumbsField(upload_to='images', sizes=((125,125),(200,200),(1000,1000)))
class Meta:
verbose_name='Изображение'
verbose_name_plural='Изображения'
# Новость
class News(models.Model):
caption = models.CharField(verbose_name="Заголовок", max_length=255,)
slug = models.SlugField("URL", max_length=255, blank=True)
announce = models.CharField(verbose_name="Краткий анонс", max_length=255, blank=True,)
text = tinymce_model.HTMLField(verbose_name="Текст", blank=True,)
date = models.DateTimeField(verbose_name="Дата написания", null=True, blank=True, default=datetime.datetime.now,)
section = models.ForeignKey(Section, verbose_name=u'Раздел')
zone = models.OneToOneField(Zone, null=True, blank=True, editable=False)
class Meta:
verbose_name='Новость'
verbose_name_plural='Новости'
def save(self, *args, **kwargs):
if self.id == None:
zone = Zone()
zone.save()
self.zone = zone
super(News, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
self.zone.delete()
super(News, self).delete(*args, **kwargs)
# Файл
class File(models.Model):
caption = models.CharField(verbose_name="Название файла", max_length=255, blank=True,)
files = models.FileField(upload_to='uploads')
class Meta:
verbose_name='Файл'
verbose_name_plural='Файлы'
# Специальное предложение
class SpecialOffer(models.Model):
caption = models.CharField(verbose_name="Заголовок спец.предложения", max_length=255,)
picture = ImageWithThumbsField(upload_to='images', sizes=((125,125),(200,200)), blank=True, null=True)
description = tinymce_model.HTMLField(verbose_name="Описание спец.предложения", blank=True,)
price = models.DecimalField(verbose_name="Цена", blank=True, max_digits=12, decimal_places=2,)
url_link = models.CharField(verbose_name="URL на указанную акцию", blank=True, max_length=255)
is_active = models.BooleanField("Данная акция активна?", default=False,)
class Meta:
verbose_name='Специальное предложение'
verbose_name_plural='Специальные предложения'
def __unicode__(self):
return self.caption
@staticmethod
def get_specialoffer():
return SpecialOffer.objects.filter(is_active=True)
# "Заявка с сайта"
class Feedback(models.Model):
sender = models.CharField("ФИО отправителя", max_length=255,)
contact = tinymce_model.HTMLField("Контактная информация (# телефона, адрес, эл.адрес и т.д.)",)
message = tinymce_model.HTMLField("Тело сообщения",)
class Meta:
verbose_name='Заявка'
verbose_name_plural='Заявки'
class Pictures(models.Model):
picture = models.ImageField('Изображение', upload_to='gallery_pictures/original/')
caption = models.CharField(u'Альтернативая подпись', max_length=255, blank=True)
model = models.CharField(u'Модель', max_length=50)
relaition_id = models.IntegerField(u'привязать к id')
class Meta:
verbose_name=u'Галерея'
verbose_name_plural=u'Галереи'
def __unicode__(self):
return self.picture.url
def save(self, *args, **kwargs):
super(Pictures, self).save(*args, **kwargs)
import Image
sizes = [
(1000, 1000),
(300, 300),
(150, 150),
]
image = Pictures.objects.get(pk=self.id)
path = image.picture.path
watermark = settings.MEDIA_ROOT + 'watermark/1000.png'
thumbnail(path, sizes, watermark)
@staticmethod
def get_image(position_id, image_model):
images = Pictures.objects.filter(relaition_id=position_id).filter(model=image_model)
sizes = [
(1000, 1000),
(300, 300),
(150, 150),
]
result = []
for image in images:
s = get_image_url(image.picture.name, sizes)
result.append({'id': image.id, 'picture': s})
return result
# Common zone
class Phoneflora(models.Model):
zone = models.OneToOneField(Zone, null=True, blank=True)
<file_sep>var Run = function() {
var colored = new Colored($(".colored_menu a"));
colored.init();
$(".openGallery_link, .cBox").colorbox({
maxWidth: '90%',
maxHeight: '90%',
rel:'openGallery'
});
var slideGalleryArea = new SlideGalleryArea();
$(".slideGallery").each(function(){
slideGalleryArea.registerGallery($(this));
});
// Render helper actions
RenderHelper.setColoredBorder($("h2, h3, .tip, blockquote"));
RenderHelper.listItems($(".content ul, .content ol"));
RenderHelper.renderTable($(".content table"));
RenderHelper.pseudoHover($(".catalogPosition_photo .photo"), $(".catalogPosition_photo"), "catalogPosition_photo__hover");
RenderHelper.pseudoHover($(".catalogPosition_photo .zoom"), $(".catalogPosition_photo"), "catalogPosition_photo__hover");
RenderHelper.sizeCloud($(".alphabet_result_cloud a"));
$(".catalogList_item").each(function(){
var photo = $(this).find(".photo a");
var title = $(this).find("dt a");
RenderHelper.pseudoHover(photo, $(this), "catalogList_item__hover");
RenderHelper.pseudoHover(title, $(this), "catalogList_item__hover");
});
$(".catalogItem").each(function(){
var photo = $(this).find(".photo a");
var title = $(this).find("dt a");
var price = $(this).find(".price span");
RenderHelper.pseudoHover(photo, photo.parent(), "colored_border");
RenderHelper.pseudoHover(title, photo.parent(), "colored_border");
RenderHelper.pseudoHover(photo, $(this), "catalogItem__hover");
RenderHelper.pseudoHover(title, $(this), "catalogItem__hover");
RenderHelper.pseudoHover(photo, price, "colored_bgColor");
RenderHelper.pseudoHover(title, price, "colored_bgColor");
});
$(".catalogItem__small").each(function(){
var photo = $(this).find(".photo img");
var title = $(this).find("dt a");
var price = $(this).find(".price");
RenderHelper.pseudoHover(photo, photo, "colored_border");
RenderHelper.pseudoHover(title, photo, "colored_border");
RenderHelper.pseudoHover(photo, $(this), "catalogItem__small_hover");
RenderHelper.pseudoHover(title, $(this), "catalogItem__small_hover");
RenderHelper.pseudoHover(photo, price, "colored_bgColor");
RenderHelper.pseudoHover(title, price, "colored_bgColor");
});
var slideAllow = true;
$(".catalogPosition_link__paramsShow").click(function(){
var paramsVisible = $(".catalogPosition_params").css("display") == "block";
var likeVisible = $(".catalogPosition_like").css("display") == "block";
if (slideAllow) {
if (!paramsVisible && likeVisible) {
$(".catalogPosition_like").slideToggle({complete: function(){
$(".catalogPosition_params").slideToggle({complete: function(){ slideAllow = true; }});
}});
} else {
$(".catalogPosition_params").slideToggle({complete: function(){ slideAllow = true; }});
}
}
slideAllow = false;
return false;
});
$(".catalogPosition_link__likeShow").click(function(){
var paramsVisible = $(".catalogPosition_params").css("display") == "block";
var likeVisible = $(".catalogPosition_like").css("display") == "block";
if (slideAllow) {
if (paramsVisible && !likeVisible) {
$(".catalogPosition_params").slideToggle({complete: function(){
$(".catalogPosition_like").slideToggle({complete: function(){ slideAllow = true; }});
}});
} else {
$(".catalogPosition_like").slideToggle({complete: function(){ slideAllow = true; }});
}
}
slideAllow = false;
return false;
});
var FilterLink = Base.extend({
constructor: function(link, content){
this._slideAllow = true;
var _this = this;
link.click(function(){
if (_this._slideAllow) {
this._slideAllow = false;
content.slideToggle({
complete: function(){
_this._slideAllow = true;
}
});
link.parent().toggleClass("filter_list_item__selected");
}
return false;
});
}
});
new FilterLink($(".color_filter_link"),$(".color_filter"));
new FilterLink($(".price_filter_link"),$(".price_filter"));
new FilterLink($(".purpose_filter_link"),$(".purpose_filter"));
var alphabetFilter = new AlphabetFilter();
alphabetFilter.registerHandlers();
var filters = new Filters();
filters.registerHandlers();
new FooterSearch();
new Time();
new FooterGallery();
new IndexGallery();
$(".submit").click(function(){
$(this).parents("form").submit();
return false;
});
// Window
$(".window").click(function(event){
event.stopPropagation();
});
$(".footer_question .close").click(function(){
$(".service_menu__question a").click();
});
$(".service_menu__question a").click(function(){
var li = $(this).parents("li");
$(".footer_question").stop(true, true).fadeToggle("slow");
li.toggleClass("selected");
return false;
});
$(".header_phone_call").click(function(){
$(".header_call").fadeToggle("slow");
return false;
});
$(".header_call .close").click(function(){
$(".header_phone_call").click();
});
}
$(document).ready(function() {
$("body").addClass("loading");
Run();
$("body").removeClass("loading");
});<file_sep>Aphaline.Actions = {
createWidget: function(selected_adder, name, zone_id, order) {
var callback = function(data) {
var new_element = $(data);
var aph_adder = '<div class="aph-widget-adder"><div></div></div>';
var aph_widget = '<div class="aph-widget"></div>';
new_element.find('[aph-zone-id]').addClass('aph-zone').append(aph_adder);
selected_adder
.after(aph_adder)
.before(aph_adder)
.wrap(aph_widget)
.replaceWith(new_element)
;
Aphaline.Interface.deselectAdder();
Aphaline.Interface.selectWidget(new_element.parent());
Aphaline.Actions.editWidget();
}
Aphaline.API.Widgets.create(name, zone_id, order, callback);
return false;
},
editWidget: function() {
var widget = Aphaline.Interface.getSelectedWidget();
Aphaline.Editor.openWidgetForm(widget);
},
moveWidget: function(item) {
var widget = Aphaline.Interface.getSelectedWidget();
var widget_id = widget.children('[aph-widget-id]').attr('aph-widget-id');
var zone = item.parent('.aph-zone');
var zone_id = zone.attr('aph-zone-id');
var order = 1 + zone.children('.aph-widget-adder').index(item);
var same_zone = item.siblings('.aph-widget.selected')[0];
if (item.prevAll('.aph-widget.selected')[0])
order--;
var callback = function() {
var aph_adder = '<div class="aph-widget-adder"><div></div></div>';
if (same_zone) {
item.before(widget);
zone.children('.aph-widget-adder').remove();
zone.append(aph_adder);
zone.children('.aph-widget').before(aph_adder);
}
else {
var start_zone = widget.parent('.aph-zone');
item.before(widget);
zone.children('.aph-widget-adder').remove();
zone.append(aph_adder);
zone.children('.aph-widget').before(aph_adder);
start_zone.children('.aph-widget-adder').remove();
start_zone.append(aph_adder);
start_zone.children('.aph-widget').before(aph_adder);
}
}
Aphaline.API.Widgets.move(widget_id, zone_id, order, callback);
},
deleteWidget: function() {
selected_widget = Aphaline.Interface.getSelectedWidget();
if (confirm("Are you sure?")) {
var id = selected_widget.children('[aph-widget-id]').attr('aph-widget-id');
var callback = function() {
var widget_to_delete = selected_widget;
Aphaline.Interface.deselectWidget();
$(widget_to_delete).prev('.aph-widget-adder').remove();
$(widget_to_delete).remove();
}
Aphaline.API.Widgets.delete(id, callback);
}
return false;
},
/*
* Structure
*/
toggleStructure: function() {
window.location.href = '/api/structure/admin/';
},
/*
* Other
*/
quit: function() {
window.location.href = '/logout/';
return false;
}
}<file_sep># -*- coding: utf8 -*-
import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from models import Chat
from models import ChatForm, LoginForm
from chat import ChatClass
from decorator import is_session
@csrf_exempt
def login(request, name=None):
context = RequestContext(request)
if request.method == 'GET':
context['form'] = LoginForm()
else:
session = ChatClass(request.session, unicode(request.POST['login']))
return HttpResponseRedirect('room/')
return render_to_response('chat/login.html', context)
@is_session
@csrf_exempt
def room(request):
context = RequestContext(request)
context['form'] = ChatForm()
return render_to_response('chat/room.html', context)
def clear(request):
context = RequestContext(request)
chat = ChatClass(request.session)
chat.clear()
return render_to_response('chat/logout.html', context)
<file_sep># -*- coding: utf8 -*-
from django.contrib import admin
from models import Catalog, Manufacturer, Type, Product, Picture
class ProductAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
filter_horizontal = ('types', 'picture')
admin.site.register(Catalog)
admin.site.register(Manufacturer)
admin.site.register(Type)
admin.site.register(Product, ProductAdmin)
admin.site.register(Picture)
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Catalog, Section, Product, Property, Choice, Picture, Pricing, ShoeSize, NewCollection, Choice, Action, ShoeSizeSection
from order import Order
from models import CharPropertyValue, NumericPropertyValue, BooleanPropertyValue, MultipleChoicePropertyValue
class LinkedInline(admin.options.InlineModelAdmin):
template = "admin/tabular_links.html"
admin_model_path = None
def __init__(self, *args, **kwargs):
super(LinkedInline, self).__init__(*args, **kwargs)
if self.admin_model_path is None:
self.admin_model_path = self.model.__name__.lower()
class CharPVInline(admin.TabularInline):
model = CharPropertyValue
class NumericPVInline(admin.TabularInline):
model = NumericPropertyValue
class BooleanPVInline(admin.TabularInline):
model = BooleanPropertyValue
class MultipleChoicePVInline(admin.TabularInline):
model = MultipleChoicePropertyValue
class PictureInline(admin.TabularInline):
model = Picture
extra = 5
class ProductInline(LinkedInline):
model = Product
fields = ( 'name', 'slug', 'article', 'price', 'is_exist', 'is_enabled' )
class ChoiceInline(admin.TabularInline):
model = Choice
class PricingInline(admin.TabularInline):
model = Pricing
extra = 15
class CatalogAdmin(admin.ModelAdmin):
list_display = ('section', )
filter_horizontal = ('properties',)
class SectionAdmin(admin.ModelAdmin):
list_display = ('caption', 'path', )
inlines = [ ProductInline, ]
ordering = ('order', 'path')
class ProductAdmin(admin.ModelAdmin):
list_display = ('name', 'slug', 'article', 'price')
list_editable = ('slug', 'article', 'price')
list_filter = ('section__path', )
ordering = ('order',)
inlines = [ PricingInline, PictureInline, CharPVInline, NumericPVInline, BooleanPVInline, MultipleChoicePVInline ]
prepopulated_fields = {'slug': ('name',)}
filter_horizontal = ('wtp',)
class PropertyAdmin(admin.ModelAdmin):
list_display = ('name', 'type', 'slug', 'default', 'description')
prepopulated_fields = {'slug': ('name',)}
inlines = [ ChoiceInline, ]
class NewCollectionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
class ShoeSizeSectionAdmin(admin.ModelAdmin):
filter_horizontal = ('sizes',)
pass
admin.site.register(Catalog, CatalogAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Product, ProductAdmin)
admin.site.register(Property, PropertyAdmin)
admin.site.register(ShoeSize)
admin.site.register(NewCollection, NewCollectionAdmin)
admin.site.register(Order)
admin.site.register(Choice)
admin.site.register(Action)
admin.site.register(ShoeSizeSection, ShoeSizeSectionAdmin)<file_sep>Aphaline.Editor = (function() {
var w = $('\
<div id="aph-editor"> \
<div class="aph-wrapper"> \
<div class="aph-header"> \
Редактирование \
</div> \
<div class="aph-x">X</div> \
<div class="aph-container"></div> \
</div> \
</div> \
');
var shadow = $('<div id="aph-shadow"></div>');
var header = w.find('.aph-header');
var x = w.find('.aph-x');
var container = w.find('.aph-container');
$('body').append(w);
$('body').append(shadow);
var selected_widget = null;
var empty = function() {
editing_widget = null;
container.empty();
}
var load = function(url) {
container.load(url);
}
var show = function() {
shadow.show();
w.show();
selected_widget = Aphaline.Interface.getSelectedWidget();
return false;
}
var hide = function() {
shadow.hide();
w.hide();
return false;
}
container.delegate('input[type=submit][name="submit_legacy"]', 'click', function() {
container.find('form').ajaxSubmit(function(data) {
window.location.reload();
});
return false;
});
container.delegate('input[type=submit][name="submit_widget_form"]', 'click', function() {
container.find('form').ajaxSubmit(function(data) {
$(selected_widget).html(data);
Aphaline.Interface.update();
hide();
});
return false;
});
container.delegate('input[type=button][name="submit_and_add_widget"]', 'click', function() {
container.find('form').ajaxSubmit(function(data) {
$(selected_widget).html(data);
Aphaline.Interface.update();
hide();
var selected_adder = $(selected_widget).next('.aph-widget-adder');
var zone = selected_adder.parent('.aph-zone');
var zone_id = zone.attr('aph-zone-id');
var order = 1 + zone.children('.aph-widget-adder').index(selected_adder);
var name = $(selected_widget).find('[aph-widget-type]').attr('aph-widget-type');
Aphaline.Actions.createWidget(selected_adder, name, zone_id, order);
});
return false;
});
x.click(function() {
hide();
return false;
});
shadow.click(function() { return false });
var editing_widget = null;
return {
openWidgetForm: function(widget, title) {
hide();
empty();
editing_widget = widget;
title = title || 'Редактирование';
header.text(title);
var widget_id = widget.children('[aph-widget-id]').attr('aph-widget-id');
var url = '/api/widgets/form/'+widget_id+'/';
container.load(url, show);
},
openContent: function(content, title) {
hide();
empty();
editing_widget = null;
title = title || 'Редактирование';
header.text(title);
container.html(content);
show();
}
}
})();<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Article, Group, Tag
class ArticleAdmin(admin.ModelAdmin):
filter_horizontal = ('tags',)
class TagAdmin(admin.ModelAdmin):
list_display = ('tag', 'name',)
ordering = ('tag',)
admin.site.register(Article, ArticleAdmin)
admin.site.register(Group)
admin.site.register(Tag, TagAdmin)
<file_sep># -*- coding: utf-8 -*-
from models import Position
class Basket:
session = None
def __init__(self, session):
if session.get('basket') is None:
session['basket'] = {}
self.session = session
def _get_position(self, position_id):
# Position must have "price" attribute!
return Position.objects.get(pk=position_id)
def add(self, position_id, count):
if self.session['basket'].get(position_id) is None:
self._get_position(position_id) # Check if position exist
self.session['basket'][position_id] = 1
else:
self.session['basket'][position_id] += 1
return self.session['basket'][position_id]
def delete(self, position_id, count):
if self.session['basket'].get(position_id) is None:
return 0
elif self.session['basket'][position_id] == 0:
return 0
else:
self.session['basket'][position_id] -= 1
return self.session['basket'][position_id]
def clear(self):
self.session['basket'] = {}
def order(self, request):
# Проверяем заполнение формы
fields = ('r_autor', 'r_cont', 'r_mes')
empty_fields = []
for field in fields:
if not request.POST.get(field):
empty_fields.append(field)
# Если есть ошибки, возвращаем ошибки
if empty_fields:
return empty_fields
# Если все ок, то:
else:
# Сохраняем заказ в БД
self._save_order(request)
# Отправляем письмо
self._send_mail(request)
return False
def position_count(self, position_id):
if self.session['basket'].get(position_id) is None:
return 0
else:
return self.session['basket'][position_id]
def position_info(self, position_id):
if self.session['basket'].get(position_id):
return {
'count': self.session['basket'][position_id],
'sum': self._get_position(position_id).price_rozn * self.session['basket'][position_id]
}
else:
return { 'count': 0, 'sum': 0 }
def list(self):
result = {}
for position_id in self.session['basket'].keys():
info = self.position_info(position_id)
info['position'] = self._get_position(position_id)
result[position_id] = info
return result
def get_summary_info(self):
result = {
'summary_count': 0,
'summary_price': 0
}
for position_id in self.session['basket'].keys():
info = self.position_info(position_id)
result['summary_count'] += info['count']
result['summary_price'] += info['price']
return result<file_sep># -*- coding: utf8 -*-
from django.contrib import admin
from models import TestText
admin.site.register(TestText)
<file_sep>import brands
import goods
import sections
import specfields<file_sep># -*- coding: utf-8 -*-
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pim.views.home', name='home'),
# url(r'^mario/', include('pim.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^tinymce/', include('tinymce.urls')),
# url(r'glossarium/', 'catalog.views.glossarium'),
# Login / logout
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
# Aphaline API
url(r'^api/aphaline/(\w+)/form/(?:(\d+)/){0,1}$', 'aphaline.api.form'),
url(r'^api/aphaline/(\w+)/change/(?:(\d+)/){0,1}$', 'aphaline.api.change'),
url(r'^api/aphaline/(\w+)/delete/(\d+)/$', 'aphaline.api.delete'),
# Widgets API
url(r'^api/widgets/list/$', 'widgets.views.list'),
url(r'^api/widgets/create/(.*?)/$', 'widgets.views.create'),
url(r'^api/widgets/move/(.*?)/$', 'widgets.views.move'),
url(r'^api/widgets/delete/(.*?)/$', 'widgets.views.delete'),
url(r'^api/widgets/get/(.*?)/$', 'widgets.views.get'),
url(r'^api/widgets/form/(.*?)/$', 'widgets.views.form'),
url(r'^api/widgets/change/(.*?)/$', 'widgets.views.change'),
# Hashing API
url(r'^api/hashing/links/$', 'seo.views.hashes2links'),
# Structure API and admin page
url(r'^api/structure/admin/$', 'structure.views.admin_page'),
url(r'^api/structure/list/$', 'structure.views.section_list'),
url(r'^api/structure/create/$', 'structure.views.create'),
url(r'^api/structure/rename/$', 'structure.views.rename'),
url(r'^api/structure/delete/(.*?)/$', 'structure.views.delete'),
url(r'^api/structure/move/$', 'structure.views.move'),
# Position move
url(r'^api/catalog/move/(\d+)/(\d+)/$', 'catalog.views.move_position'),
#WTP
url(r'^api/wtp/(\d+)/$', 'catalog.views.wtp'),
url(r'^api/wtp/wtp_catalog/(\d+)/$', 'catalog.views.wtp_catalog'),
url(r'^api/wtp/add/(\d+)/(\d+)/$', 'catalog.views.wtp_add'),
url(r'^api/wtp/del/(\d+)/(\d+)/$', 'catalog.views.wtp_del'),
#add, delete or change item collection
url(r'^api/add_collection/(\d+)/$', 'catalog.views.collection_index'),
url(r'^api/add_collection/catalog/(\d+)/$', 'catalog.views.collection_catalog'),
url(r'^api/add_collection/add/(\d+)/(\d+)/$', 'catalog.views.collection_add'),
url(r'^api/add_collection/del/(\d+)/(\d+)/$', 'catalog.views.collection_del'),
#add, delete or change item action
url(r'^api/add_action/(\d+)/$', 'catalog.views.action_index'),
url(r'^api/add_action/catalog/(\d+)/$', 'catalog.views.action_catalog'),
url(r'^api/add_action/add/(\d+)/(\d+)/$', 'catalog.views.action_add'),
url(r'^api/add_action/del/(\d+)/(\d+)/$', 'catalog.views.action_del'),
#Карта сайта
url(r'^sitemap/$', 'structure.views.sitemap'),
# Basket API
url(r'^api/basket/add/(\d+)/(\d+)/$', 'catalog.api.add'),
url(r'^api/basket/change_size/(\d+)/(\d+)/(\d+)/$', 'catalog.api.change_size'),
url(r'^api/basket/clear/$', 'catalog.api.clear'),
url(r'^api/basket/delete/(\d+)/(\d+)/$', 'catalog.api.delete'),
url(r'^basket/$', 'catalog.views.basket_list'),
#filter
url(r'filter/', 'catalog.views.filter'),
#change_property
url(r'api/property/', 'catalog.views.change_property'),
url(r'^.*?/$', 'structure.dispatcher.dispatch'),
url(r'^$', 'structure.dispatcher.dispatch'),
)
<file_sep># -*- coding: utf-8 -*-
import os
from django.db import models
from utils.colorfield import ColorField
PATH_CSS = ''
class Template(models.Model):
name = models.CharField("Название шаблона (человеческое)", max_length=255)
slug = models.SlugField("Имя папки шаблона", max_length=255)
def __unicode__(self):
return self.name + ' (' + self.slug + ')'
class Meta:
verbose_name = 'Шаблон'
verbose_name_plural = 'Шаблоны'
class ColorTheme(models.Model):
caption = models.CharField(u'Имя цветовой темы', max_length=255, unique=True)
body = ColorField(u'Задний фон', max_length=6, blank=True)
menuUlUl = ColorField(u'Меню (выпадающее меню)', max_length=6, blank=True)
container = ColorField(u'Контейнер', max_length=6, blank=True)
container_left = ColorField(u'Левая граница контейнера', max_length=6, blank=True)
container_right = ColorField(u'Правая граница контейнера', max_length=6, blank=True)
text_bg = models.CharField(u'Прозрачный?', max_length=11, blank=True, choices=(('transparent', 'Установить прозрачный фон'), ('inherit', 'Наследовать значение родителя')))
header_box_bg = ColorField(u'Задний фон бокса заголовка и Голосовалки', max_length=6, blank=True)
header_box = ColorField(u'Текст в заголовке', max_length=6, blank=True)
voteresults = ColorField(u'Задний фон результатов ответа', max_length=6, blank=True)
voteresults_indicator = ColorField(u'Индикатор в результатах голосования', max_length=6, blank=True)
specials_hover = ColorField(u'Задний фон нажатых ссылок спецпредложения', max_length=6, blank=True)
news_data_span = ColorField(u'Задний фон у новостей', max_length=6, blank=True)
tr_odd_td = ColorField(u'Заливка нечётных ячеек', max_length=6, blank=True)
tr_even_td = ColorField(u'Заливка чётных ячеек', max_length=6, blank=True)
catalog_th = ColorField(u'Задний фон заголовка таблицы каталога', max_length=6, blank=True)
catalog_th_odd_td = ColorField(u'Заливка нечётных ячеек таблицы в каталоге', max_length=6, blank=True)
catalog_th_even_td = ColorField(u'Заливка чётных ячеек таблицы в каталоге', max_length=6, blank=True)
footer_background = ColorField(u'Заливка футера', max_length=6, blank=True)
footer_color = ColorField(u'Цвет текста футера', max_length=6, blank=True)
footer_a = ColorField(u'Ссылки футера', max_length=6, blank=True)
footer_a_hover = ColorField(u'Ссылки футера при наведении', max_length=6, blank=True)
container_color = ColorField(u'Текст контейнера', max_length=6, blank=True)
specials_a = ColorField(u'Цвет текста ссылки спец предложения', max_length=6, blank=True)
a_color = ColorField(u'Любая другая ссылка', max_length=6, blank=True)
a_hover = ColorField(u'Любая другая ссылка при наведении мыши', max_length=6, blank=True)
b_or_strong = ColorField(u'Тега b или тега strong', max_length=6, blank=True)
menu_a = ColorField(u'Ссылок в меню', max_length=6, blank=True)
specials_price = ColorField(u'Специальных цен', max_length=6, blank=True)
news_date_span = ColorField(u'Цвет даты у новостей', max_length=6, blank=True)
voteresults_small = ColorField(u'Маленький текст в результатах голосования', max_length=6, blank=True)
catalog_body = ColorField(u'Цвет границы каталога', max_length=6, blank=True)
news_date = ColorField(u'Граница даты новостей', max_length=6, blank=True)
text_td = ColorField(u'Текст в ячейках таблицы', max_length=6, blank=True)
text_th = ColorField(u'Текст в заголовке таблицы', max_length=6, blank=True)
class Meta:
verbose_name = 'Цветовая тема'
verbose_name_plural = 'Цветовые темы'
ordering = ['caption']
def __unicode__(self):
return self.caption
def save(self, *args, **kwargs):
f = open(PATH_CSS + "colors_new.css", "w")
f.write('''body {background-color:%s;}
#menu ul, #menu ul ul {background:%s;}
.container {background: %s;border-left: 1px solid %s;border-right: 1px solid %s;}
#text_bg {background: %s;}
.header_box_bg, #voteresults p {background: %s;}
.header_box * {color: %s !important;}
#voteresults li {background: %s;}
#voteresults .indicator {background-color: %s;}
#specials a:hover {background: %s;}
#news .date span {background: %s;}
tr.odd td {background-color: %s;}
tr.even td {background-color: %s;}
#catalog th {background-color: %s;}
#catalog tr.odd td {background-color: %s;}
#catalog tr.even td {background-color: %s;}
#footer {background: %s; color: %s;}
#footer a {color: %s;}
#footer a:hover {color: %s;}
.container {color: %s;}
#specials a {color: %s;}
a {color: %s;}
a:hover {color: %s;}
b, strong {color: %s;}
#menu a {color: %s;}
#specials .price {color: %s;}
#news .date span {color: %s;}
#voteresults small {color: %s;}
#specials li img {border: 0;}
#catalog_body {border-color: %s;}
#news .date {border-color: %s;}
#text td {border-color: %s;}
#text th {border-color: %s;}
'''
%
(
self.body,
self.menuUlUl,
self.container,
self.container_left,
self.container_right,
self.text_bg,
self.header_box_bg,
self.header_box,
self.voteresults,
self.voteresults_indicator,
self.specials_hover,
self.news_data_span,
self.tr_odd_td,
self.tr_even_td,
self.catalog_th,
self.catalog_th_odd_td,
self.catalog_th_even_td,
self.footer_background,
self.footer_color,
self.footer_a,
self.footer_a_hover,
self.container_color,
self.specials_a,
self.a_color,
self.a_hover,
self.b_or_strong,
self.menu_a,
self.specials_price,
self.news_date_span,
self.voteresults_small,
self.catalog_body,
self.news_date,
self.text_td,
self.text_th,
)
)
f.close()
super(ColorTheme, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
# if os.path.exists(PATH_CSS + self.slug + '.css'):
# os.remove(PATH_CSS + self.slug + ".css",)
if os.path.exists(PATH_CSS + 'colors_new.css'):
os.remove(PATH_CSS + "colors_new.css",)
super(ColorTheme, self).delete(*args, **kwargs)
class FontTheme(models.Model):
FONT_CHOICES = (
(u'Arial, Arial, Helvetica, sans-serif', u'Arial, Arial, Helvetica, sans-serif'),
(u'Arial Black, Arial Black, Gadget, sans-serif', u'Arial Black, Arial Black, Gadget, sans-serif'),
(u'Comic Sans MS, Comic Sans MS, cursive', u'Comic Sans MS, Comic Sans MS, cursive'),
(u'Courier New, Courier New, Courier, monospace', u'Courier New, Courier New, Courier, monospace'),
(u'Georgia, Georgia, serif', u'Georgia, Georgia, serif'),
(u'Impact, Impact, Charcoal, sans-serif', u'Impact, Impact, Charcoal, sans-serif'),
(u'Lucida Console, Monaco, monospace', u'Lucida Console, Monaco, monospace'),
(u'Lucida Sans Unicode, Lucida Grande, sans-serif', u'Lucida Sans Unicode, Lucida Grande, sans-serif'),
(u'Palatino Linotype, Book Antiqua, Palatino, serif', u'Palatino Linotype, Book Antiqua, Palatino, serif'),
(u'Tahoma, Geneva, sans-serif', u'Tahoma, Geneva, sans-serif'),
(u'Times New Roman, Times, serif', u'Times New Roman, Times, serif'),
(u'Trebuchet MS, Helvetica, sans-serif', u'Trebuchet MS, Helvetica, sans-serif'),
(u'Verdana, Verdana, Geneva, sans-serif', u'Verdana, Verdana, Geneva, sans-serif'),
(u'Webdings, Webdings (Webdings, Webdings)', u'Webdings, Webdings (Webdings, Webdings)'),
(u'Wingdings, Zapf Dingbats (Wingdings, Zapf Dingbats)', u'Wingdings, Zapf Dingbats (Wingdings, Zapf Dingbats)'),
(u'MS Sans Serif, Geneva, sans-serif', u'MS Sans Serif, Geneva, sans-serif'),
(u'MS Serif, New York, serif', u'MS Serif, New York, serif'),
)
caption = models.CharField('Имя шаблона', max_length=255,)
font_theme = models.CharField('Выбор шрифта', max_length=100, choices=FONT_CHOICES,)
def __unicode__(self):
return self.caption
class Meta:
verbose_name = 'Шрифтовая тема'
verbose_name_plural = 'Шрифтовые темы'
def save(self, *args, **kwargs):
f = open(PATH_CSS + "font_new.css", "w")
f.write('body {font-family:%s;}' % self.font_theme)
f.close()
super(FontTheme, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
if os.path.exists(PATH_CSS + 'font_new.css'):
os.remove(PATH_CSS + "font_new.css",)
super(FontTheme, self).delete(*args, **kwargs)<file_sep># -*- coding: utf-8 -*-
"""
Set URL maps for every SectionType here.
Patterns will be applied to "subpaths".
Example: if your path is '/company/news/56/'
and '/company/news/' is a Section with "news" type,
'56/' will be checked with patterns defined in "news" variable.
"""
from django.conf.urls.defaults import patterns, include, url
index = patterns('',
url(r'^$', 'structure.section_type.index')
)
text = patterns('',
url(r'^$', 'structure.section_type.text')
)
# articles = patterns('articles.views',
# url(r'^(page-(?P<page>\d+)/){0,1}$', 'index'),
# url(r'^tag/(?P<tag>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'tag'),
# url(r'^(?P<section>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'section'),
# url(r'^(?P<section>[-_a-zA-Z0-9.]+)/(?P<article>[-_a-zA-Z0-9.]+)/$', 'article'),
# )
# production = patterns('catalogapp.views',
# url(r'^$', 'index'),
# url(r'^(?P<section>[-_a-zA-Z0-9.]+)/$', 'section'),
# )
<file_sep># -*- coding: utf-8 -*-
"""
Set URL maps for every SectionType here.
Patterns will be applied to "subpaths".
Example: if your path is '/company/news/56/'
and '/company/news/' is a Section with "news" type,
'56/' will be checked with patterns defined in "news" variable.
"""
from django.conf.urls.defaults import patterns, include, url
index = patterns('',
url(r'^$', 'catalog.views.index')
)
collections = patterns('catalog.views',
url(r'^$', 'collections_list'),
url(r'^(page-(?P<page>\d+)){0,1}/$', 'collections_list'),
url(r'^(?P<slug>.*?)/(page-(?P<page>\d+)){0,1}/$', 'collections_item'),
url(r'^(?P<slug>.*?)/$', 'collections_item'),
)
specials = patterns('catalog.views',
url(r'^$', 'action_list'),
url(r'^(page-(?P<page>\d+)){0,1}/$', 'action_list'),
url(r'^(?P<slug>.*?)/(page-(?P<page>\d+)){0,1}/$', 'action_item'),
url(r'^(?P<slug>.*?)/$', 'action_item'),
)
catalog = patterns('catalog.views',
url(r'^$', 'catalog_list'),
url(r'^all/$', 'catalog_all'),
url(r'^shuffle/$', 'catalog_shuffle'),
url(r'^(page-(?P<page>\d+)){0,1}/$', 'catalog_list'),
url(r'^(?P<slug>.*?)/$', 'catalog_item'),
)
text = patterns('',
url(r'^$', 'common.views.text')
)
qa = patterns('questanswer.views',
url(r'^$', 'questanswer'),
url(r'^(page-(?P<page>\d+)){0,1}/$', 'questanswer'),
)
articles = patterns('articles.views',
url(r'^(page-(?P<page>\d+)/){0,1}$', 'index'),
url(r'^tag/(?P<tag>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'tag'),
url(r'^(?P<article>[-_a-zA-Z0-9.]+)/$', 'article'),
url(r'^(?P<section>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'section'),
url(r'^(?P<section>[-_a-zA-Z0-9.]+)/(?P<article>[-_a-zA-Z0-9.]+)/$', 'article'),
)
glossarium = patterns('catalog.views',
url(r'^$', 'glossarium'),
)
novinki = patterns('catalog.views',
url(r'^$', 'nova')
)
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from models import Widget
from grouping import create_group, add2group
from utils.thumbs import ImageWithThumbsField
from tinymce import models as tinymce_model
create_group('common', 'Другие')
def resize(path, path_in, size):
original_image_name = path.split('/')[-1]
name, ext = original_image_name.split('.', 1)
import Image
width, height = Image.open(path).size
factor = float(height) / (float(width) / float(size))
fp = open(path, 'rb')
im = Image.open(fp)
im.resize((size, int(factor)), Image.ANTIALIAS).save('%s/%s.%sx%s.%s' % ( path_in, name, size, size, ext), quality=100)
fp.close()
@add2group('Спец.предложение', 'common')
class SpecialOffer(Widget):
image = models.ImageField('Изображение', upload_to='specialoffer_widgets/image/', blank=True, null=True)
title = models.CharField('Заголовок', max_length=255,)
desc = tinymce_model.HTMLField('Описание', max_length=255, blank=True,)
link = models.CharField('Ссылка', max_length=255, blank=True,)
def save(self, *args, **kwargs):
super(SpecialOffer, self).save(*args, **kwargs)
if self.image:
path = settings.MEDIA_ROOT + self.image.name
path_in = settings.MEDIA_ROOT + 'specialoffer_widgets/image'
size_w = 250
resize(path, path_in, size_w)
def get_thumb(self):
splitted_name = self.image.name.split('.', 1)
name, ext = '.'.join(splitted_name[:-1]), splitted_name[-1]
new_name = '%s.250x250.%s' % (name, ext)
return settings.MEDIA_URL + new_name
<file_sep># -*- coding: utf-8 -*-
from catalogapp.models import Brand
def create(name, slug):
brand = Brand(name=name, slug=slug)
brand.save()
return brand.id
def delete(id):
try:
brand = Brand.objects.get(id=id)
except Brand.DoesNotExist:
return False
brand.delete()
return True
def rename(id, new_name, new_slug=None):
try:
brand = Brand.objects.get(id=id)
except Brand.DoesNotExist:
return False
brand.name = new_name
if not new_slug is None:
brand.slug = new_slug
brand.save()
return brand.id
def list(**filters):
return Brand.objects.filter(**filters)
def listIn(ids):
return Brand.objects.filter(id__in=ids)
def get(id):
return Brand.objects.get(id=id)<file_sep># -*- coding: utf-8 -*-
from django.db import models
import datetime
class QuestAnswer(models.Model):
author = models.CharField(verbose_name="Пользователь оставивший запись", max_length=255, default="Гость",)
date_publication = models.DateTimeField(verbose_name="Дата написания", null=True, blank=True, default=datetime.datetime.now,)
question_short = models.CharField(verbose_name="Краткий вопрос", max_length=255, blank=True)
question = models.TextField(verbose_name="Вопрос")
moderator = models.CharField(verbose_name="Имя модератора", max_length=255, blank=False)
position = models.CharField(verbose_name="Должность модератора", max_length=255, blank=False)
answer = models.TextField(verbose_name="Ответ", blank=True)
is_public = models.BooleanField("Опубликовать?", default=False)
tag = models.ManyToManyField("TagName", verbose_name="Тэг", blank=True, null=True)
def __unicode__(self):
return self.author
class Meta:
verbose_name = u'Вопрос-ответ'
verbose_name_plural = u'Вопрос-ответ'
class TagName(models.Model):
name = models.CharField("Тэг", max_length=255, blank=False)
slug = models.SlugField("Слаг", max_length=255, blank=False)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
#alphabet
### прикрутить юникод
words = self.name.split()
for word in words:
letter = word[0].upper()
try:
current_letter = Alphabet.objects.get(letter=letter)
if not current_letter.is_action:
current_letter.is_action = True
current_letter.save()
except Alphabet.DoesNotExist:
letter = Alphabet(letter=letter, is_action=True)
letter.save()
super(TagName, self).save(*args, **kwargs)
class Alphabet(models.Model):
letter = models.CharField('Буква', max_length=1)
is_action = models.BooleanField('Активна?', default=True)
class Meta:
verbose_name = 'Алфавит'
verbose_name_plural = 'Алфавит'
def __unicode__(self):
if self.is_action:
return '%s' % (self.letter)
else:
return '!%s' % (self.letter)<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
create_group('upload', 'Загрузка')
@add2group('Файл', 'upload')
class UploadFile(Widget):
title = models.CharField('Заголовок', max_length=255, blank=True)
caption = models.CharField('Название', max_length=50, blank=True)
file = models.FileField(upload_to='upload_widget/file')<file_sep>var WindowControl = Base.extend({
constructor: function(){
this._window = $(window);
this._body = $('body');
},
getWidth: function(){
return this._window.width();
},
getHeight: function(){
return this._window.height();
},
getScrollTop: function(){
return this._window.scrollTop();
},
getScrollLeft: function(){
return this._window.scrollLeft();
},
setScrollTop: function(value){
this._window.scrollTop(value);
},
setScrollLeft: function(){
this._window.scrollLeft(value);
},
addScrollHandler: function(scrollHandler){
this._window.scroll(function(){ scrollHandler(); });
},
addResizeHandler: function(resizeHandler){
this._window.resize(function(){ resizeHandler(); });
},
addClickHandler: function(clickHandler){
this._body.click(function(){ clickHandler(); });
}
});<file_sep># -*- coding: utf-8 -*-
from django.db import models
import datetime
class QuestAnswer(models.Model):
author = models.CharField(verbose_name="Пользователь оставивший запись", max_length=255, default="Гость",)
date_publication = models.DateTimeField(verbose_name="Дата написания", null=True, blank=True, default=datetime.datetime.now,)
question = models.TextField(verbose_name="Вопрос", )
moderator = models.CharField(verbose_name="Имя модератора", max_length=255, blank=True, default="Менеджер")
answer = models.TextField(verbose_name="Ответ", blank=True)
is_public = models.BooleanField("Опубликовать?", default=False,)
class Meta:
verbose_name = u'Вопрос-ответ'
verbose_name_plural = u'Вопрос-ответ'
def __unicode__(self):
return self.question[:20]
<file_sep># -*- coding: utf-8 -*-
from models import Section
class StructureMiddleware:
def process_request(self, request):
try:
request.current_section = Section.get_node_by_path(request.path)
request.structure = Section.get_structure()
except:
request.current_section = None
request.structure = {}
<file_sep>var RangeInput = Base.extend({
constructor: function(range, step, onSlide) {
this._range = range;
this._min = this._range.find("input.min");
this._max = this._range.find("input.max");
this._line = this._range.find(".rangeInput_line");
this._step = typeof step == "undefined" ? 1 : step;
this._minTip = null;
this._maxTip = null;
this._slider = this.createRange();
this._onSlide = onSlide;
},
createRange: function() {
var _this = this;
var defaultMin = parseInt(_this._min.attr("rel"));
var defaultMax = parseInt(_this._max.attr("rel"));
return this._line.slider({
range: true,
min: defaultMin,
max: defaultMax,
values: [ _this.getVal().min, _this.getVal().max ],
step: _this._step,
create: function(){
$(".ui-slider-range").addClass("colored_bgColor");
_this._minTip = $("<span class='rangeInput_tip rangeInput_tip__min'>"+_this.getVal().min+"</span>").appendTo($(".ui-slider-handle").get(0));
_this._maxTip = $("<span class='rangeInput_tip rangeInput_tip__max'>"+_this.getVal().max+"</span>").appendTo($(".ui-slider-handle").get(1));
_this.updateTipLeft();
},
stop: function(){
_this._onSlide();
},
slide: function(event, ui) {
_this.updateTipLeft();
_this._minTip.text(ui.values[0]);
_this._maxTip.text(ui.values[1]);
_this._min.val(ui.values[0]);
_this._max.val(ui.values[1]);
_this._min.change();
_this._max.change();
}
});
},
updateTipLeft: function(){
this._minTip.css("left",this.calcLeft(this._minTip)+"px");
this._maxTip.css("left",this.calcLeft(this._maxTip)+"px");
},
calcLeft: function(elm){
return (-1)*(elm.width()+12-7)/2;
},
getVal: function() {
var valueMin = this.filterVal(this._min);
var valueMax = this.filterVal(this._max);
return {min: valueMin, max: valueMax};
},
filterVal: function(field) {
var defaultValue = parseInt(field.attr("rel"));
var value = parseInt(field.val());
return isNaN(value) || value < 1 ? defaultValue : value;
}
});<file_sep># -*- coding: utf8 -*-
from django.db import models
import md5
import random
def gets_path_without_last_chunk(url):
url_split = url.split('/')[1:-2]
url_join = '/'.join(url_split)
if len(url_join) > 1:
return '/%s/' % url_join
else:
return '/'
class Metatag(models.Model):
name = models.CharField(u'URL Slug', max_length=255, unique=True)
title = models.CharField(u'Title', max_length=255, null=True, blank=True)
description = models.CharField(u'Description', max_length=255, null=True, blank=True)
keywords = models.CharField(u'Keywords', max_length=255, null=True, blank=True)
phone = models.CharField(u'Номер телефона (наследуется)', max_length=255, blank=True)
image = models.ImageField(u'Фоновая картинка (наследуется)', upload_to='background_image', blank=True)
def __unicode__(self):
return self.name
@staticmethod
def get_property(url, property):
"""
return current property.
- url: string
- property: string
"""
try:
while True:
obj = Metatag.objects.extra(
where=["name=(SELECT max(name) from seo_metatag WHERE locate(name, %s)=1)"],
params=[url]
)[0]
if obj.__dict__[property] == '':
if url == '/':
return ''
url = gets_path_without_last_chunk(url)
else:
return obj.__dict__[property]
except:
return ''
class Meta:
verbose_name = u'Метатэг'
verbose_name_plural = u'Метатэги'
class Hash(models.Model):
type = models.CharField(max_length=32)
key = models.CharField(max_length=255)
hash_string = models.CharField(max_length=32)
@staticmethod
def link2hash(link):
try:
hash_string = Hash.objects.values('hash_string') \
.get(type='link', key=link)['hash_string']
return str(hash_string)
except:
hash_string = Hash.encrypt(link)
new_hash = Hash(type='link', key=link, hash_string=hash_string)
new_hash.save()
return hash_string
@staticmethod
def hash2link(hash_string):
try:
link = Hash.objects.values('key').get(hash_string=hash_string)['key']
return link
except:
return '#'
@staticmethod
def encrypt(key):
return md5.new(str(random.random()) + str(key)).hexdigest()
<file_sep># -*- coding: utf8 -*-
from django.db import models
class TestText(models.Model):
text = models.TextField('Text')
perevod = models.TextField('Перевод')
class Meta:
verbose_name = 'Text'
verbose_name_plural = 'Texts'
def __unicode__(self):
return self.text
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Phone, IconCollection
class PhoneAdmin(admin.ModelAdmin):
list_display = ('phone', 'url_part')
ordering = ('url_part',)
fields = ('phone', 'url_part')
class IconCollectionAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('caption',)}
admin.site.register(Phone, PhoneAdmin)
admin.site.register(IconCollection, IconCollectionAdmin)
<file_sep>from django.http import HttpResponseRedirect, Http404
from django.core.paginator import Paginator, InvalidPage, EmptyPage
def paginate(context, result_key, query, count, page, root):
if page == '1' or page == 1:
return HttpResponseRedirect(root)
elif page is None:
page = 1
else:
page = int(page)
p = Paginator(query, count)
if p.num_pages >= page and page is not 0:
context['pagination'] = {}
context['pagination']['current_page'] = page
context['pagination']['root'] = root
context['pagination']['page_range'] = p.page_range
context['pagination']['num_pages'] = p.num_pages
context[result_key] = p.page(page).object_list
if p.page(page).has_previous() == True:
context['pagination']['previous_page'] = p.page(page).previous_page_number()
if p.page(page).has_next() == True:
context['pagination']['next_page'] = p.page(page).next_page_number()
else:
raise Http404
<file_sep>{% if current_widget.image %}
<div class="just_image border_bottom">
<div class="img" style="text-align:center;">
{% if current_widget.link %}
<a href="{{ current_widget.link }}">
{% endif %}
<img src="{{ MEDIA_URL }}{{ current_widget.image }}" alt="{{ current_widget.alt }}" title="{{ current_widget.title }}"/>
{% if current_widget.link %}
</a>
{% endif %}
</div>
</div>
{% endif %}<file_sep># -*- coding: utf-8 -*-
import json
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.forms import ModelForm
from utils.decorators import staff_required
from models import *
@staff_required
def create(request, widget_type):
try:
widget_class = globals()[widget_type]
except KeyError:
return HttpResponse('Invalid widget type', status=400)
if not issubclass(widget_class, Widget):
return HttpResponse('Invalid widget type', status=400)
if request.GET.get('zone_id', None) is None:
return HttpResponse('Zone ID is required', status=400)
try:
zone = Zone.objects.get(pk=request.GET.get('zone_id'))
except DoesNotExist:
return HttpResponse('Zone with given ID is not exist', status=400)
widget = widget_class(zone=zone)
widget.save()
order = request.GET.get('order', None)
if order is not None:
widget.move(int(order))
context = RequestContext(request)
return HttpResponse(widget.render(context))
@staff_required
def delete(request, id):
try:
widget = Widget.objects.filter(pk=id)[0]
widget.delete()
widget = Widget.objects.get(pk=id)
widget.delete()
return HttpResponse("Widget #" + str(id) + " is deleted")
except:
return HttpResponse("No such widget")
@staff_required
def move(request, id):
try:
widget = Widget.objects.get(pk=id)
order = request.GET.get('order', None)
zone = Zone.objects.get(pk=request.GET['zone_id'])
widget.move_to_zone(zone, order)
return HttpResponse("Okay")
except:
return HttpResponse("Error", 500)
@staff_required
def list(request):
from grouping import get_groups
data = get_groups()
data = json.dumps(data)
return HttpResponse(data)
@staff_required
def get(request, id):
try:
widget = Widget.objects.get(pk=id).as_leaf_class()
except:
return HttpResponse("No such widget")
context = RequestContext(request)
return HttpResponse(widget.render(context))
@staff_required
def form(request, id):
try:
widget = Widget.objects.get(pk=id).as_leaf_class()
except:
return HttpResponse("No such widget")
class WidgetForm(ModelForm):
class Meta:
model = widget.__class__
exclude = ('zone', 'order', 'type')
path = request.GET.get('path', '')
form = WidgetForm(instance=widget)
result = """
<form method="post" enctype="multipart/form-data"
action="/api/widgets/change/%s/">
<table>
%s
<tr>
<td colspan="2" style="text-align: center">
<input type="hidden" name="current_section" value="%s" />
<input type="submit" name="submit_widget_form" value="Save" />
<input type="button" name="submit_and_add_widget"
value="Save and add another" />
</td>
</tr>
</table>
</form>
""" % (str(id), form.as_table(), path)
return HttpResponse(result)
@staff_required
def change(request, id):
try:
widget = Widget.objects.get(pk=id).as_leaf_class()
except:
return HttpResponse("No such widget")
class WidgetForm(ModelForm):
class Meta:
model = widget.__class__
exclude = ('zone', 'order', 'type')
form = WidgetForm(request.POST, request.FILES, instance=widget)
form.save()
context = RequestContext(request)
return HttpResponse(widget.render(context))
<file_sep>from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
# url(r'^app/', include('app.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
# url(r'^tinymce/', include('tinymce.urls')),
# url(r'^chat/$', 'chat.views.login'),
# url(r'^chat/(.*?)/$', 'chat.views.chat'),
# url(r'^meta/$', 'chat.views.meta'),
#login, logout
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
#chat
url(r'^chat/$', 'chat.views.login'),
url(r'^chat/room/$', 'chat.views.room'),
url(r'^chat/clear/$', 'chat.views.clear'),
url(r'^api/chat/message/$', 'chat.api.get_message'),
url(r'^api/chat/get/$', 'chat.api.save_message'),
#LiveSearch
url(r'^search/$', 'livesearch.views.index'),
url(r'^api/livesearch/$', 'livesearch.views.livesearch'),
# Aphaline API
url(r'^api/aphaline/(\w+)/form/(?:(\d+)/){0,1}$', 'aphaline.api.form'),
url(r'^api/aphaline/(\w+)/change/(?:(\d+)/){0,1}$', 'aphaline.api.change'),
url(r'^api/aphaline/(\w+)/delete/(\d+)/$', 'aphaline.api.delete'),
# Widgets API
url(r'^api/widgets/list/$', 'widgets.views.list'),
url(r'^api/widgets/create/(.*?)/$', 'widgets.views.create'),
url(r'^api/widgets/move/(.*?)/$', 'widgets.views.move'),
url(r'^api/widgets/delete/(.*?)/$', 'widgets.views.delete'),
url(r'^api/widgets/get/(.*?)/$', 'widgets.views.get'),
url(r'^api/widgets/form/(.*?)/$', 'widgets.views.form'),
url(r'^api/widgets/change/(.*?)/$', 'widgets.views.change'),
# Structure API and admin page
url(r'^api/structure/admin/$', 'structure.views.admin_page'),
url(r'^api/structure/list/$', 'structure.views.section_list'),
url(r'^api/structure/create/$', 'structure.views.create'),
url(r'^api/structure/rename/$', 'structure.views.rename'),
url(r'^api/structure/delete/(.*?)/$', 'structure.views.delete'),
url(r'^api/structure/move/$', 'structure.views.move'),
# API aplhabet search
url(r'^api/search/alphabet/$', 'catalog.alphabet_search.search'),
url(r'^api/search/alphabet_tag/$', 'questanswer.alphabet_search.search'),
# Json index page
url(r'^json/$', 'common.views.json'),
#
url(r'^.*?/$', 'structure.dispatcher.dispatch'),
url(r'^$', 'structure.dispatcher.dispatch')
)
<file_sep># -*- coding: utf-8 -*-
from seo.models import Metatag
from common.models import Phone, Banner, Footer
from catalog.basket import Basket
from structure.models import *
def _split_join(s):
c = []
b = s.split('/')[1:-1]
i = 0
path = '/'
while i < len(b):
path += b[i]+'/'
section = Section.objects.get(path=path)
c.append({'caption': section.caption, 'path': path})
i +=1
return c
def seo_tags(request):
try:
return { 'metatag': Metatag.objects.get(name=request.path) }
except:
return {}
def phone(request):
try:
phone = Phone.objects.extra(
where=["url_part=(SELECT max(url_part) from common_phone WHERE locate(url_part, %s)=1)"],
params=[request.path]
)[0]
return {'phone':phone}
except:
return {'phone':''}
def banner(request):
try:
banner = Banner.objects.extra(
where=["url_part=(SELECT max(url_part) from common_banner WHERE locate(url_part, %s)=1)"],
params=[request.path]
)
return {'banner':banner}
except:
return {'banner':''}
def current_section(request):
return { 'current_section': request.current_section }
def current_path(request):
return { 'current_path': request.path }
def structure(request):
return { 'structure': request.structure }
def footer(request):
return {'footer': Footer.objects.get(pk=1)}
def crumbs(request):
return {'crumbs': _split_join(str(request.current_section))}
def basket_summary_info(request):
basket = Basket(request.session)
return basket.get_summary_info()
def main_links(request):
return {'main_links':
{
'table_size' : Section.objects.get(pk=44),
'payment' : Section.objects.get(pk=45),
'contacts' : Section.objects.get(pk=46),
'news_and_articles' : Section.objects.get(pk=47),
'q_and_a' : Section.objects.get(pk=48),
'action' : Section.objects.get(pk=49),
'glossarium' : Section.objects.get(pk=155),
'nova' : Section.objects.get(pk=157)
}
}
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Text
#
create_group('text', 'Текст')
@add2group('Параграф', 'text')
class SimpleText(Widget):
TEXT_TYPE_CHOICES = (
(1, 'Обычный текст'),
(2, 'Цитата'),
(3, 'Заметка'),
)
text_type = models.PositiveIntegerField("Тип текстового блока", choices=TEXT_TYPE_CHOICES, default=1)
text = models.TextField("Текст", default="Text")
@add2group('Цитата', 'text')
class Cite(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = 2
self.type = 'SimpleText'
super(Cite, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Заметка', 'text')
class Remark(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = 3
self.type = 'SimpleText'
super(Remark, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Таблица характеристик', 'text')
class CharsTable(Widget):
text = models.TextField("Текст", default="Свойство 1 :: Значение 1\nСвойство 2 :: Значение 2\nСвойство 3 :: Значение 3")
def get_pairs(self):
result = []
lines = self.text.split("\n")
for line in lines:
try:
kv = line.split("::")
result.append({ 'key': kv[0].strip(), 'value': kv[1].strip() })
except:
pass
return result
<file_sep>from lists import *
from text import *
from grid import *<file_sep># -*- coding: utf-8 -*-
from catalogapp.models import Good
def create(name, section_id, articul='', initial={}):
""" Создание нового объекта класса Good
Используй его если необходима проверка на корректность передаваемых
атрибутов """
good = Good(name=name, section_id=section_id, articul='', **initial)
good.full_clean()
good.save()
return good.id
def delete(id):
try:
good = Good.objects.get(id=id)
except Good.DoesNotExist:
return False
good.delete()
return True
def change(id, data):
try:
good = Good.objects.get(id=id)
except Good.DoesNotExist:
return False
for key in data:
setattr(good, key, data[key])
good.save()
return good.id
def list(**filters):
return Good.objects.filter(**filters)
def listIn(ids):
return Good.objects.filter(id__in=ids)
def get(id):
return Good.objects.get(id=id)<file_sep>var RenderHelper = Base.extend({},{
doubleClearing: function(parent, tag){
parent.find(tag+":odd").next().addClass("clear");
}
});<file_sep>if (!Aphaline) Aphaline = {};
/*
* Adder "menu": widgets and groups list
*/
Aphaline.WidgetList = (function() {
var repr = null;
var typeset = null;
var last_widget = null;
var getWidgetTypeset = function() {
// Retrieves widget groups and classes from the server
return Aphaline.API.Widgets.list();
};
var clean = function() {
repr.empty();
}
var addItem = function(item, clazz) {
if (item == null) {
// empty "last widget" case
return;
}
var obj = $('<li></li>');
obj
.addClass('item')
.attr('title', item.name)
.text(item.title)
.data('meta', item)
;
if (clazz) {
obj.addClass(clazz);
}
repr.append(obj);
}
var addGroup = function(group) {
var obj = $('<li></li>');
obj
.addClass('group')
.attr('title', group.slug)
.text(group.group)
.data('meta', group)
;
repr.append(obj);
}
var addBackButton = function() {
var obj = $('<li></li>');
obj
.addClass('back')
.attr('title', 'Назад')
.text('Назад')
;
repr.append(obj);
}
var renderIndex = function() {
clean();
addItem(last_widget, 'last_widget');
for (var i in typeset)
addGroup(typeset[i]);
return false;
}
var renderSub = function(group) {
clean();
addBackButton();
for (var i in group.items)
addItem(group.items[i]);
return false;
}
var setLastWidget = function(widget) {
last_widget = widget;
$.cookie('last_widget_name', widget.name);
$.cookie('last_widget_title', widget.title);
}
var itemClickHandler = function(evt) {
var item = $(evt.target).data().meta;
setLastWidget(item);
// Item click event handling is external
$('body').trigger('widgetlist_item_click', item);
Aphaline.WidgetList.hide();
return false;
}
var groupClickHandler = function(evt) {
var group = $(evt.target).data().meta;
renderSub(group);
return false;
}
return {
init: function() {
// Getting typeset
typeset = getWidgetTypeset();
// Creating the window
repr = $('<ul></ul>');
repr
.attr('id', 'aph-widget-adder-window')
// Binding events
.delegate('.item', 'click', itemClickHandler)
.delegate('.group', 'click', groupClickHandler)
.delegate('.back', 'click', renderIndex)
;
if ($.cookie('last_widget_name')) {
last_widget = {
name: $.cookie('last_widget_name'),
title: $.cookie('last_widget_title')
}
}
// Inserting the window to the body
$('body').append(repr);
},
show: function(x, y) {
// Checks if initialised
if (!repr)
this.init();
// Constructs the list...
renderIndex();
// ... and shows the window in given position
var position = {}
position.top = y + 10 + 'px';
position.left = x + 10 + 'px';
// if ($('#container').height() < 400 ||
// y < $('#container').height() - 400)
// {
// position.top = y + 10 + 'px';
// position.bottom = 'auto';
// }
// else {
// position.bottom = $('#container').height() - y + 10 + 'px';
// position.top = 'auto';
// }
// if (x < $('#container').width() - 250) {
// position.left = x + 10 + 'px';
// position.right = 'auto';
// }
// else {
// position.right = $('#container').width() - x - 10 + 'px';
// position.left = 'auto';
// }
repr
.css(position)
.show()
;
},
hide: function() {
if (!repr)
return;
else
repr.hide();
}
}
})()<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Headers
#
create_group('headers', 'Заголовки')
class HeaderWidget(Widget):
BORDER_CHOICES = (
(1, 'Оранжевый'),
(2, 'Синий'),
(3, 'Черный'),
(4, 'Морской волны'),
(5, 'Зеленый'),
)
FONT_CHOICES = (
(1, 'Tahoma'),
(2, 'Arial'),
)
header = models.CharField("Текст заголовка", max_length=255, blank=True, default="Заголовок")
border = models.PositiveIntegerField("Цвет подчеркивания", choices=BORDER_CHOICES, default=1)
font_style = models.PositiveIntegerField("Шрифт", choices=FONT_CHOICES, default=1)
free_border = models.CharField("Специальный цвет подчеркивания (rrggbb)", max_length=6, blank=True)
is_span = models.BooleanField("SPAN", default=False)
is_bold = models.BooleanField("Bold", default=False)
is_italic = models.BooleanField("Italic", default=False)
class Meta:
abstract = True
@add2group('Заголовок 1', 'headers')
class H1(HeaderWidget):
link_href = models.CharField("Адрес ссылки", max_length=255, blank=True)
link_text = models.CharField("Текст ссылки", max_length=255, blank=True)
@add2group('Заголовок 2', 'headers')
class H2(HeaderWidget):
link_href = models.CharField("Адрес ссылки", max_length=255, blank=True)
link_text = models.CharField("Текст ссылки", max_length=255, blank=True)
icon = models.ImageField("Иконка", upload_to="icons", blank=True)
@add2group('Заголовок 3', 'headers')
class H3(HeaderWidget):
icon = models.ImageField("Иконка", upload_to="icons", blank=True)
is_dashed = models.BooleanField("Подчеркивание пунктиром", default=False)
@add2group('Заголовок 4', 'headers')
class H4(HeaderWidget):
icon = models.ImageField("Иконка", upload_to="icons", blank=True)
is_dashed = models.BooleanField("Подчеркивание пунктиром", default=False)
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Section, Good
admin.site.register(Section)
admin.site.register(Good)<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Article
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {'name': ('caption',)}
admin.site.register(Article, ArticleAdmin)
<file_sep>from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'app.views.home', name='home'),
# url(r'^app/', include('app.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^tinymce/', include('tinymce.urls')),
url(r'^chat/$', 'chat.views.login'),
url(r'^chat/(.*?)/$', 'chat.views.chat'),
url(r'^meta/$', 'chat.views.meta'),
# Aphaline API
url(r'^api/aphaline/(\w+)/form/(?:(\d+)/){0,1}$', 'aphaline.api.form'),
url(r'^api/aphaline/(\w+)/change/(?:(\d+)/){0,1}$', 'aphaline.api.change'),
url(r'^api/aphaline/(\w+)/delete/(\d+)/$', 'aphaline.api.delete'),
# Widgets API
url(r'^api/widgets/list/$', 'widgets.views.list'),
url(r'^api/widgets/create/(.*?)/$', 'widgets.views.create'),
url(r'^api/widgets/move/(.*?)/$', 'widgets.views.move'),
url(r'^api/widgets/delete/(.*?)/$', 'widgets.views.delete'),
url(r'^api/widgets/get/(.*?)/$', 'widgets.views.get'),
url(r'^api/widgets/form/(.*?)/$', 'widgets.views.form'),
url(r'^api/widgets/change/(.*?)/$', 'widgets.views.change'),
# Structure API and admin page
url(r'^api/structure/admin/$', 'structure.views.admin_page'),
url(r'^api/structure/list/$', 'structure.views.section_list'),
url(r'^api/structure/create/$', 'structure.views.create'),
url(r'^api/structure/rename/$', 'structure.views.rename'),
url(r'^api/structure/delete/(.*?)/$', 'structure.views.delete'),
url(r'^api/structure/move/$', 'structure.views.move'),
url(r'^.*?/$', 'structure.dispatcher.dispatch'),
url(r'^$', 'structure.dispatcher.dispatch'),
)
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import Phone, Banner
class PhoneAdmin(admin.ModelAdmin):
list_display = ('phone', 'url_part')
ordering = ('url_part',)
fields = ('phone', 'url_part')
class BannerAdmin(admin.ModelAdmin):
list_display = ('img', 'url_part', 'url')
admin.site.register(Phone, PhoneAdmin)
admin.site.register(Banner, BannerAdmin)<file_sep># -*- coding: utf-8 -*-
from django.db import models
def gets_path_without_last_chunk(url):
url_split = url.split('/')[1:-2]
url_join = '/'.join(url_split)
if len(url_join) > 1:
return '/%s/' % url_join
else:
return '/'
class Metatag(models.Model):
name = models.CharField(u'URL Slug', max_length=255, unique=True)
title = models.CharField(u'Title', max_length=255, null=True, blank=True)
description = models.CharField(u'Description', max_length=255, null=True, blank=True)
keywords = models.CharField(u'Keywords', max_length=255, null=True, blank=True)
phone = models.CharField(u'Номер телефона (наследуется)', max_length=255, blank=True)
image = models.ImageField(u'Фоновая картинка (наследуется)', upload_to='background_image', blank=True)
def __unicode__(self):
return self.name
@staticmethod
def get_property(url, property):
"""
return current property.
- url: string
- property: string
"""
try:
while True:
obj = Metatag.objects.extra(
where=["name=(SELECT max(name) from seo_metatag WHERE locate(name, %s)=1)"],
params=[url]
)[0]
if obj.__dict__[property] == '':
if url == '/':
return ''
url = gets_path_without_last_chunk(url)
else:
return obj.__dict__[property]
except:
return ''
class Meta:
verbose_name = u'Метатэг'
verbose_name_plural = u'Метатэги'
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Headers
#
create_group('headers', 'Заголовки')
class HeaderWidget(Widget):
HEADER_TYPE_CHOICES = (
(1, 'H1'),
(2, 'H2'),
(3, 'H3'),
)
header_type = models.PositiveIntegerField("Тип заголовка", choices=HEADER_TYPE_CHOICES, default=1)
header = models.CharField("Текст заголовка", default="Заголовок", max_length=255)
@add2group('Заголовок 1', 'headers')
class H1(HeaderWidget):
def save(self, *args, **kwargs):
if self.id is None:
self.header_type = '1'
self.type = 'HeaderWidget'
super(H1, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Заголовок 2', 'headers')
class H2(HeaderWidget):
def save(self, *args, **kwargs):
if self.id is None:
self.header_type = '2'
self.type = 'HeaderWidget'
super(H2, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Заголовок 3', 'headers')
class H3(HeaderWidget):
def save(self, *args, **kwargs):
if self.id is None:
self.header_type = '3'
self.type = 'HeaderWidget'
super(H3, self).save(*args, **kwargs)
class Meta:
proxy = True
<file_sep>from django.conf.urls.defaults import patterns, include, url
from django.contrib.sitemaps import Sitemap, GenericSitemap, FlatPageSitemap
from articles.models import Article
from structure.models import Section
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
generic_sitemaps = {
'generic': GenericSitemap({
'queryset': Article.objects.all()
}, priority=0.6)
}
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mario.views.home', name='home'),
# url(r'^mario/', include('mario.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': generic_sitemaps}),
url(r'^admin/', include(admin.site.urls)),
# Login / logout
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
# Aphaline API
url(r'^api/aphaline/(\w+)/form/(?:(\d+)/){0,1}$', 'aphaline.api.form'),
url(r'^api/aphaline/(\w+)/change/(?:(\d+)/){0,1}$', 'aphaline.api.change'),
url(r'^api/aphaline/(\w+)/delete/(\d+)/$', 'aphaline.api.delete'),
# Hashing API
url(r'^api/hashing/links/$', 'seo.views.hashes2links'),
url(r'^api/hashing/widgets/$', 'seo.views.hashes2widgets'),
# Widgets API
url(r'^api/widgets/list/$', 'widgets.views.list'),
url(r'^api/widgets/create/(.*?)/$', 'widgets.views.create'),
url(r'^api/widgets/move/(.*?)/$', 'widgets.views.move'),
url(r'^api/widgets/delete/(.*?)/$', 'widgets.views.delete'),
url(r'^api/widgets/get/(.*?)/$', 'widgets.views.get'),
url(r'^api/widgets/form/(.*?)/$', 'widgets.views.form'),
url(r'^api/widgets/change/(.*?)/$', 'widgets.views.change'),
# Structure API and admin page
url(r'^api/structure/admin/$', 'structure.views.admin_page'),
url(r'^api/structure/list/$', 'structure.views.section_list'),
url(r'^api/structure/create/$', 'structure.views.create'),
url(r'^api/structure/rename/$', 'structure.views.rename'),
url(r'^api/structure/delete/(.*?)/$', 'structure.views.delete'),
url(r'^api/structure/move/$', 'structure.views.move'),
# # Articles page
# url(r'^articles/(page-(?P<page>\d+)/){0,1}$', 'mario.articles.views.index'),
# url(r'^articles/tag/(?P<tag>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'mario.articles.views.tag'),
# url(r'^articles/(?P<section>[-_a-zA-Z0-9.]+)/(page-(?P<page>\d+)/){0,1}$', 'mario.articles.views.section'),
# url(r'^articles/(?P<section>[-_a-zA-Z0-9.]+)/(?P<article>[-_a-zA-Z0-9.]+)/$', 'mario.articles.views.article'),
# # Catalog pages
# url(r'^catalog/$', 'mario.catalogapp.views.index'),
# url(r'^catalog/(?P<section>[-_a-zA-Z0-9.]+)/$', 'mario.catalogapp.views.section'),
# Any page
# url(r'^.*/$', 'common.views.index'),
url(r'^.*?/$', 'structure.dispatcher.dispatch'),
url(r'^$', 'structure.dispatcher.dispatch'),
)
<file_sep># -*- coding: utf-8 -*-
from seo.models import Metatag
from structure.models import *
def _split_join(s):
c = []
b = s.split('/')[1:-1]
i = 0
path = '/'
while i < len(b):
path += b[i]+'/'
section = Section.objects.get(path=path)
c.append({'caption': section.caption, 'path': path})
i +=1
return c
def current_section(request):
return { 'current_section': request.current_section }
def current_path(request):
return { 'current_path': request.path }
def structure(request):
return { 'structure': request.structure }
def crumbs(request):
return {'crumbs': _split_join(str(request.current_section))}
<file_sep>var RenderVisual = Base.extend({
render: function() {
this.renderTables();
this.renderCapitalText();
this.renderLeftMenu();
},
renderTables: function() {
this.renderColorTable();
this.renderTextTable();
this.renderSimpleTable();
},
renderColorTable: function() {
var tables = $(".tableColored");
tables.each(function() {
var table = $(this);
table
.attr("cellspacing", "0")
.attr("cellpadding", "0");
if (table.find("th").length != 0) {
table.find("th:first").parents("tr:first").find("th").addClass("firstRow");
table.find("th:last-child").addClass("lastCol");
var max_count = 0;
table.find("tr").each(function() {
var count = $(this).find("th").length;
if (count > max_count) max_count = count;
});
table.find("tr").each(function() {
var count = $(this).find("th").length;
if (count < max_count) $(this).find(".lastCol").removeClass("lastCol");
});
}
table.find("td:first").parents("tr:first").find("td").addClass("firstRow");
table.find("td:last-child").addClass("lastCol");
table.find("tr:odd td").addClass("even");
table.find("tr").mouseenter(
function() {
$(this).addClass("hover");
}).mouseleave(function() {
$(this).removeClass("hover");
});
});
},
renderTextTable: function() {
var tables = $(".tableText");
tables.each(function() {
var table = $(this);
table.attr("cellspacing", "0").attr("cellpadding", "0");
table.find("th:last-child").addClass("lastCol");
table.find("td:last-child").addClass("lastCol");
table.find("tr").mouseenter(
function() {
$(this).addClass("hover");
}).mouseleave(function() {
$(this).removeClass("hover");
});
});
},
renderSimpleTable: function() {
var tables = $(".tableSimple");
tables.each(function() {
var table = $(this);
table
.attr("cellspacing", "0")
.attr("cellpadding", "0");
table.find("tr:last-child").addClass("lastRow");
table.find("tr:even td").addClass("even");
});
},
renderCapitalText: function() {
var capital = $("p.capital");
capital.each(function() {
var cap_obj = $(this);
var cap_text = cap_obj.text();
var cap_letter = cap_text.charAt(0);
var new_cap_text = cap_text.substr(1, cap_text.length - 1);
cap_obj.text(new_cap_text);
$('<ins class="r">' + cap_letter + '</ins>').prependTo(this);
});
},
renderLeftMenu: function() {
$(".leftMenu p a").click(function(){
$(this).parents(".leftMenu_group").toggleClass("group_hide");
return false;
});
$(".leftMenu_innerMenu").each(function() {
var item = $(this);
item.find(">a, >ins").click(function() {
item.toggleClass("show");
return false;
});
});
}
});<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from models import Article
def article(request, slug):
return HttpResponse('Article ' + slug)<file_sep>{% load zones %}
{% load vars %}
<html>
<head>
<title>
{% if not metatag.title %}
{% block title %}{{ current_section.caption }}{% endblock %}
{% else %}
{{ metatag.title }}
{% endif %}
</title>
{# Metatag decription and keywords #}
{% if metatag.description %}
<meta name="description" content="{{ metatag.description }}"/>
{% endif %}
{% if metatag.keywords %}
<meta name="keywords" content="{{ metatag.keywords }}"/>
{% endif %}
<meta name='yandex-verification' content='790e182da6400c6f' />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/common.css"/>
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/typography.css"/>
</head>
<body>
<div id="container">
<div id="content">
{% assign parent current_section.parent %}
{% if parent.path == '/' %}
{% assign items current_section.children.all %}
{% else %}
{% assign items parent.children.all %}
{% endif %}
{% if items %}
<ul id="text_submenu">
{% for item in items %}
{% if item != current_section %}
<li><a href="{{ item.path }}">{{ item.caption }}</a></li>
{% else %}
<li>{{ item.caption }}</li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
{% render_zone current_section.zone %}
</div>
</div>
<!-- Yandex.Metrika counter --><div style="display:none;"><script type="text/javascript">(function(w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter859209 = new Ya.Metrika({id:859209, clickmap:true, accurateTrackBounce:true, webvisor:true}); } catch(e) { } }); })(window, "yandex_metrika_callbacks");</script></div><script src="//mc.yandex.ru/metrika/watch.js" type="text/javascript" defer="defer"></script><noscript><div><img src="//mc.yandex.ru/watch/859209" style="position:absolute; left:-9999px;" alt="" /></div></noscript><!-- /Yandex.Metrika counter -->
</body>
</html>
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Text
#
create_group('text', 'Текст')
@add2group('Параграф', 'text')
class SimpleText(Widget):
TEXT_TYPE_CHOICES = (
(1, 'Обычный'),
(2, 'Примечание'),
(3, 'Заметка'),
(4, 'Цитата'),
)
is_bold = models.BooleanField("Bold", default=False)
is_italic = models.BooleanField("Italic", default=False)
is_capital = models.BooleanField("Буквица", default=False)
is_alert = models.BooleanField("Пометка", default=False)
alert_text = models.CharField("Текст пометки", max_length=255, blank=True)
top_border = models.BooleanField("Верхняя граница", default=False)
bottom_border = models.BooleanField("Нижняя граница", default=True)
font_color = models.CharField("Цвет текста (rrggbb)", max_length=6, blank=True)
bg_color = models.CharField("Цвет фона (rrggbb)", max_length=6, blank=True)
text = models.TextField("Текст", default="Text")
text_type = models.PositiveIntegerField("Тип текстового блока", choices=TEXT_TYPE_CHOICES, default=1)
@add2group('Сноска', 'text')
class FootNote(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = '2'
self.type = 'SimpleText'
super(SimpleText, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Заметка', 'text')
class Tip(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = '3'
self.type = 'SimpleText'
super(SimpleText, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Цитата', 'text')
class Blockquote(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.text_type = '4'
self.type = 'SimpleText'
super(SimpleText, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Малый анонс', 'text')
class SmallAnnounce(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.is_italic = True
self.type = 'SimpleText'
super(SimpleText, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Большой анонс', 'text')
class BigAnnounce(SimpleText):
def save(self, *args, **kwargs):
if self.id is None:
self.is_bold = True
self.is_capital = True
self.type = 'SimpleText'
super(SimpleText, self).save(*args, **kwargs)
class Meta:
proxy = True
@add2group('Таблица характеристик', 'text')
class CharsTable(Widget):
text = models.TextField("Текст", default="Свойство 1 :: Значение 1\nСвойство 2 :: Значение 2\nСвойство 3 :: Значение 3")
def get_pairs(self):
result = []
lines = self.text.split("\n")
for line in lines:
try:
kv = line.split("::")
result.append({ 'key': kv[0].strip(), 'value': kv[1].strip() })
except:
pass
return result
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from models import Widget
from grouping import create_group, add2group
#
# Headers
#
create_group('headers', 'Заголовки')
@add2group('Заголовок', 'headers')
class HeaderWidget(Widget):
HEADER_TYPE_CHOICES = (
(1, 'H1'),
(2, 'H2'),
(3, 'H3'),
)
header_type = models.PositiveIntegerField("Тип заголовка", choices=HEADER_TYPE_CHOICES, default=1)
header = models.CharField("Текст заголовка", default="Заголовок", max_length=255)
<file_sep># -*- coding: utf8 -*-
import json
import hashlib
import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response, get_object_or_404
from models import *
TIME_DELTA = 600 #seconds = 10 min
def dumps(dict):
return json.dumps(dict)
def loads(str):
return json.loads(str)
def time_now():
return datetime.datetime.now()
def index(req):
return HttpResponse('OK')
# def reg(req):
# context = RequestContext(req)
# context['form'] = UserForm()
# return render_to_response('chat/reg.html', context)
@csrf_exempt
def login(req):
context = RequestContext(req)
if req.method == 'POST':
form = UserForm(req.POST)
if form.is_valid():
cd = form.cleaned_data
try:
user = User.objects.get(login=cd['login'])
pwd = <PASSWORD>(cd['login']).<PASSWORD>()
return HttpResponse('ok')
if user.password != pwd:
context['error_pwd'] = u'Пароль не верен'
return render_to_response('chat/login.html', context)
else:
session = req.session
time_now = time_now()
session[hashlib.md5(time_now).hexdigest()] = dumps({
'time': time_now,
'id': user.id
})
return HttpResponseRedirect('chat/%s/' % (session['hash'],))
except:
context['error_login'] = u'Пользователь с логином %s не существует' % cd['login']
return render_to_response('chat/login.html', context)
context['form'] = form
return render_to_response('chat/login.html', context)
context['form'] = UserForm()
return render_to_response('chat/login.html', context)
def chat(req, hash):
context = RequestContext(req)
try:
auth = load(req.session[hash])
time_delta = time_now() - auth['time']
if time_delta > TIME_DELTA:
del req.session['hash']
return HttpResponse('Сессия закрыта')
else:
return HttpResponse('Приветствуем')
except:
return HttpResponseRedirect('/chat/')
def meta(req):
val = req.session.items()
val.sort()
html=[]
for k,v in val:
html.append('<tr><td>%s</td><td>%s</td></tr>'%(k,v))
return HttpResponse('<table>%s</table>'%'\n'.join(html))
<file_sep>var ie_lt7 = $(".ie_lt7").length != 0;
var ie_lt8 = $(".ie_lt8").length != 0;
var ie_lt9 = $(".ie_lt9").length != 0;<file_sep># -*- coding: utf8 -*-
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
import datetime
def send_mail(author, question, date=datetime.datetime.now()):
context = {}
context['author'] = author
context['question'] = question
context['date'] = date
subject, from_email, to = 'На сайт pim66.ru поступил новый вопрос.', settings.MAIL_FROM, settings.MAIL_TO
html_content = render_to_string('qa/send_form.html', context)
msg = EmailMultiAlternatives(subject, '', from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()<file_sep># -*- coding: utf-8 -*-
import hashlib
import datetime
import models
class ChatClass:
session = None
def __init__(self, session, login=None):
if session.get('time_session') is None:
session['time_session'] = hashlib.md5(str(datetime.datetime.now())).hexdigest()
session['login'] = login
self.session = session
def get_session(self):
return self.session['time_session']
def get_login(self):
return self.session['login']
def open_chat(self):
pass
def close_chat(self):
pass
def clear(self):
del self.session['time_session']
del self.session['login']
<file_sep># -*- coding: utf-8 -*-
from django.conf import settings
from models import Widget, Zone
def widgets_list():
"""
Returns widget groups and clases list
"""
try:
return settings.WIDGETS
except:
return {}
def create_widget(widget_type, zone_id, order=None):
"""
Creates widget in given zone with given order
@param widget_type: Widget type (class name)
@param zone_id: Zone ID
@param order: Order (or None for last position)
"""
widget_class = Widget.subclasses[widget_type]
zone = Zone.objects.get(pk=zone_id)
widget = widget_class.objects.create(zone=zone)
if order is not None:
widget.move(int(order))
def delete_widget(widget_id):
"""
Deletes widget with its subclasses data
@param widget_id: Widget ID
"""
widget = Widget.objects.filter(pk=widget_id)[0]
widget.delete()
def move_widget(widget_id, order=None, zone_id=None):
"""
Moves widget to given order and/or zone
@param widget_id: Widget ID
@param order: Order (or -1 for last position)
@param zone_id: Zone ID
"""
widget = Widget.objects.get(pk=widget_id)
if zone_id is None:
zone = widget.zone
else:
zone = Zone.objects.get(pk=zone_id)
widget.move_to_zone(zone, order)
def get_widget_as_dict(widget_id):
"""
Returns widget data as dictionary
@param widget_id: Widget ID
"""
widget = Widget.objects.get(pk=widget_id).as_leaf_class()
dict_widget = widget.__dict__
del dict_widget['_state']
return dict_widget
<file_sep>from django.http import HttpResponse
from management.models import Domain
class MultiSiteMiddleware:
def process_request(self, request):
if request.path.startswith('/admin/'):
return
try:
host = request.get_host().rsplit(':', 1)[0].replace('www.', '')
domain = Domain.objects.get(name=host)
except:
return HttpResponse("Invalid site")
request.site = domain.site
return
<file_sep># -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
from django import forms
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
class Order(models.Model):
name = models.CharField(u'<NAME>', max_length=255)
email = models.EmailField(u'e-mail покупателя', blank=True)
phone = models.CharField(u'Телефон покупателя', max_length=50)
#address block
index = models.CharField(u'Индекс', max_length=6, blank=True)
city = models.CharField(u'Город', max_length=255, blank=True)
street = models.CharField(u'Улица', max_length=100, blank=True)
house = models.CharField(u'Дом', max_length=10, blank=True)
apartment = models.CharField(u'Квартира', max_length=30, blank=True)
#address block
comment = models.TextField(u'Комментарий', blank=True)
order_human_form = models.TextField(u'Заказ (человеческий вид)', blank=True)
order_native_form = models.TextField(u'Заказ (машинный вид)', blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
super(Order, self).save(*args, **kwargs)
return self.id
def send_mail(self, form, basket, basket_info, session):
context = {}
#Наполняем контекст значениями из формы для рендинга в шаблоне ответа
context['name'] = form['name']
context['email'] = form['email']
context['phone'] = form['phone']
context['index'] = form['index']
context['city'] = form['city']
context['street'] = form['street']
context['house'] = form['house']
context['apartment'] = form['apartment']
context['comment'] = form['comment']
#Добавляем информацию о товарах из корзины и о текущей сумме заказа
context['basket'] = basket
context['basket_info'] = basket_info
#Сохраняем заказ в базе и получаем ID текущего заказа. Помещаем ID так же в контекст
order = Order(
name = form['name'],
email = form['email'],
phone = form['phone'],
index= form['index'],
city = form['city'],
street = form['street'],
house = form['house'],
apartment = form['apartment'],
comment = form['comment'],
order_human_form = render_to_string('basket/send_form.html', context),
order_native_form = session['basket']
)
num_order = order.save()
context['num_order'] = num_order
#Формируем всё что необходимо для отправки письма, рендерим форму и отправляем письмо.
subject, from_email, to = 'Заказ №' + str(num_order) + ' с сайта pim66.ru', settings.MAIL_FROM, settings.MAIL_TO
html_content = render_to_string('basket/send_form.html', context)
msg = EmailMultiAlternatives(subject, '', from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
class Meta:
verbose_name = u'Заказ'
verbose_name_plural = u'Заказы'
class OrderForm(forms.ModelForm):
name = forms.CharField(label=u'ФИО:', widget=forms.TextInput(attrs={'size':'44'}))
email = forms.EmailField(label=u'E-mail:', widget=forms.TextInput(attrs={'size':'33'}), required=False)
phone = forms.CharField(label=u'Телефон:', widget=forms.TextInput(attrs={'value':'+7'}))
index = forms.CharField(label=u'Индекс', widget=forms.TextInput(attrs={'size':'11'}), required=False)
house = forms.CharField(label=u'Дом', widget=forms.TextInput(attrs={'size':'11'}), required=False)
apartment = forms.CharField(label=u'Квартира', widget=forms.TextInput(attrs={'size':'11'}), required=False)
comment = forms.CharField(label=u'Комментарий', required=False, widget=forms.Textarea)
class Meta:
model = Order
<file_sep>def build_tree(nodes, parent_key='parent_id'):
# create empty tree to fill
tree = {}
# fill in tree starting with roots (those with no parent)
build_tree_recursive(tree, None, nodes, parent_key)
return tree
def build_tree_recursive(tree, parent_id, nodes, parent_key):
# find children
children = [n for n in nodes if n[parent_key] == parent_id]
# build a subtree for each child
for child in children:
id = child['order']
# start new subtree
tree[id] = child
tree[id]['nodes'] = {}
# call recursively to build a subtree for current node
build_tree_recursive(tree[id]['nodes'], child['id'], nodes, parent_key)<file_sep>$(document).ready(function() {
var current_path = window.location.pathname;
if (current_path == '/production/') {
var url = '/api/search/alphabet/';
};
if (current_path.split('/')[1] == 'qa') {
var url = '/api/search/alphabet_tag/';
};
function selected(){
$('.alphabet_filter').find('a.colored_bgColor').each(function(){
if($(this).hasClass('selected')){
$(this).removeClass('selected');
}
});
}
var alphabet = '';
$('.alphabet_filter').find('a.colored_bgColor').each(function(){
$(this).unbind('click');
$(this).click(function() {
selected();
if(alphabet != $(this).text()){
alphabet = $(this).text();
self = $(this);
$('.alphabet_result_container').slideUp(function() {
$.ajax({
async: true,
type: 'POST',
url: url,
data: {
'alphabet': $.toJSON(alphabet),
},
success: function(data) {
var data = JSON.parse(data);
var html = '<div class="alphabet_result_letter colored_bgColor">' + alphabet + '</div>';
var alpha_str = '<span class="colored_bgColor">' + alphabet + '</span>';
var alpha_str_lower = '<span class="colored_bgColor">' + alphabet.toLowerCase() + '</span>';
$.each(data, function() {
if (!this.caption) {
html += '<span class="alphabet_result_item"> </span>';
}
else {
//$.each(this, function() {
if (current_path.split('/')[1] == 'qa') {
tag_path = '/qa/tag/';
}
else {
tag_path = '';
};
var istr = '<span class="alphabet_result_item"><a href="' + tag_path + this.path + '/" class="whiteLink">' + this.caption + '</a></span>';
html += istr.replace('||', alpha_str_lower).replace('|', alpha_str);
//});
}
});
self.addClass('selected');
$('.alphabet_result_letter').text(alphabet);
$('.alphabet_result').html(html);
$('.alphabet_result_container').slideDown();
}
});
});
}else{
$('.alphabet_result_container').slideUp();
alphabet = '';
}
return false;
});
});
});<file_sep>var interval = 10000;
var intervalID;
function keyValue(evt)
{
if(!evt) evt = event;
if(evt.keyCode == 13 && evt.ctrlKey) sendMessage();
}
function trim(message)
{
var messageTrim = message.value.replace(/^\s+/, "").replace(/\s+$/, "");;
if(messageTrim.length)
return messageTrim;
else
return false;
}
function sendMessage()
{
var message = window.document.getElementById('id_message');
if(!message.value)
{
message.className = 'error';
alert('Поле отправки пусто. Введите сообщение!');
message.focus();
}
else if(!trim(message))
{
message.className = 'error';
alert('Вы не ввели текст сообщения. Введите сообщение!');
message.value = '';
message.focus();
}
else
{
$.post("/api/chat/get/",
{
'message': $('textarea').val(),
'csrfmiddlewaretoken': $('input').val()
},
function (out){
getMessage();
Interval(interval);
}
);
message.value = '';
message.focus();
Interval(interval);
return false;
}
}
function getMessage(){
$("#window_chat").load("/api/chat/message/");
}
function Interval(time){
if(intervalID){
clearInterval(intervalID)
}
intervalID = setInterval(getMessage, interval);
}
function locate(href){
location.replace(href);
}
$(document).ready(function() {
window.document.getElementById('button').onclick = sendMessage;
window.document.getElementById('id_message').onkeydown = keyValue;
getMessage();
Interval(interval);
});
<file_sep># -*- coding: utf-8 -*-
from django.contrib import admin
from models import QuestAnswer
class QuestAnswerAdmin(admin.ModelAdmin):
list_display = ('author', 'date_publication', 'moderator', 'is_public',)
admin.site.register(QuestAnswer, QuestAnswerAdmin)
<file_sep>import os
from settings_db import DATABASES
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Derter', '<EMAIL>'),
('Succubi', '<EMAIL>'),
)
MANAGERS = ADMINS
TIME_ZONE = 'Asia/Yekaterinburg'
LANGUAGE_CODE = 'ru-RU'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
APPEND_SLASH = True
SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.split(SITE_ROOT)[0]
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = '/work/media/uralbrick/' #os.path.join(PROJECT_ROOT, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin-media/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
# '/home/succubi/Desktop/uralbrick/media',
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
SECRET_KEY = <KEY>'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
#'debug_toolbar.middleware.DebugToolbarMiddleware',
'structure.middleware.StructureMiddleware',
'aphaline.middleware.AphalineMiddleware',
)
ROOT_URLCONF = 'uralbrick.urls'
TEMPLATE_DIRS = (
os.path.join(SITE_ROOT, 'templates'),
#'/usr/local/lib/python2.7/dist-packages/debug_toolbar/templates/',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'tinymce',
'django.contrib.admin',
#'debug_toolbar',
#'genericm2m',
'seo',
'structure',
'widgets',
'catalogapp',
'articles',
)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# CACHES = {
# 'default': {
# 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
# 'LOCATION': '127.0.0.1:11211',
# }
# }
LOGIN_REDIRECT_URL = '/'
#FIELD_TYPES = ('BooleanField', 'CharField', 'IntegerField',
# 'TextField', 'ChoiceField', 'MultipleChoiceField')
#MONGODB_MANAGED_MODELS = ["catalogapp.Good"]
#DATABASE_ROUTERS = ["django_mongodb_engine.router.MongoDBRouter"]
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"utils.context_processors.seo_tags",
"utils.context_processors.phone",
"utils.context_processors.current_section",
"utils.context_processors.structure",
"utils.context_processors.background",
"aphaline.context_processors.aphaline_edit_mode",
)
#INTERNAL_IPS = ('10.10.10.1',)
#DEBUG_TOOLBAR_PANELS = (
# 'debug_toolbar.panels.timer.TimerDebugPanel',
# 'debug_toolbar.panels.sql.SQLDebugPanel',
#)
TINYMCE_JS_URL = STATIC_URL + "tiny_mce/tiny_mce.js"
TINYMCE_JS_ROOT = STATIC_URL + "tiny_mce"
TINYMCE_SPELLCHECKER=False
TINYMCE_PLUGINS = [
]
TINYMCE_DEFAULT_CONFIG={
'theme' : "simple", #simple, advanced
'plugins' : ",".join(TINYMCE_PLUGINS), # django-cms
'language' : 'ru',
"theme_advanced_buttons1" : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect,|,spellchecker",
"theme_advanced_buttons2" : "cut,copy,paste,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,cleanup,code,|,forecolor,backcolor,|,insertfile,insertimage",
"theme_advanced_buttons3" : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr",
'theme_advanced_toolbar_location' : "top",
'theme_advanced_toolbar_align' : "left",
'theme_advanced_statusbar_location' : "bottom",
'theme_advanced_resizing' : True,
'table_default_cellpadding': 2,
'table_default_cellspacing': 2,
'cleanup_on_startup' : False,
'cleanup' : False,
'paste_auto_cleanup_on_paste' : False,
'paste_block_drop' : False,
'paste_remove_spans' : False,
'paste_strip_class_attributes' : False,
'paste_retain_style_properties' : "",
'forced_root_block' : False,
'force_br_newlines' : False,
'force_p_newlines' : False,
'remove_linebreaks' : False,
'convert_newlines_to_brs' : False,
'inline_styles' : False,
'relative_urls' : False,
'formats' : {
'alignleft' : {'selector' : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' : 'align-left'},
'aligncenter' : {'selector' : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' : 'align-center'},
'alignright' : {'selector' : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' : 'align-right'},
'alignfull' : {'selector' : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' : 'align-justify'},
'strikethrough' : {'inline' : 'del'},
'italic' : {'inline' : 'em'},
'bold' : {'inline' : 'strong'},
'underline' : {'inline' : 'u'}
},
'pagebreak_separator' : "",
# Drop lists for link/image/media/template dialogs
'template_external_list_url': 'lists/template_list.js',
'external_link_list_url': 'lists/link_list.js',
'external_image_list_url': 'lists/image_list.js',
'media_external_list_url': 'lists/media_list.js',
#
#'file_browser_callback':'tinyDjangoBrowser'
}
<file_sep>groups = {}
def create_group(slug, name):
if slug not in groups:
groups[slug] = { 'group': name, 'slug': slug, 'items': [] }
def add2group(title, group):
def decorate(cls):
obj = { 'name': cls.__name__, 'title': title }
if group not in groups:
return cls
else:
groups[group]['items'].append(obj)
return cls
return decorate
def get_groups():
return groups<file_sep># -*- coding: utf-8 -*-
import json
import pytils
from django.http import HttpResponse
from utils.decorators import staff_required
from models import Document, Part
from structure.models import SectionType
def _split_join(s):
b = s.split('-')
b = '/'.join(b)
return '/%s/' % b
def ch(node):
node['data'] = node['caption']
del node['caption']
keys = ('id', 'path', 'is_enabled', 'type_id', 'parent_id', 'order', 'zone_id')
node['attr'] = dict([(x,node[x]) for x in keys])
for x in keys:
del node[x]
node['children'] = node['nodes'].values()
del node['nodes']
for child in node['children']:
ch(child)
@staff_required
def create_document(request):
document_caption = request.GET.get('caption')
Document.objects.create(caption=document_caption,
title=document_caption,
owner=request.user)
return HttpResponse('Ok')
@staff_required
def delete_document(request, document_id):
doc = Document.objects.get(pk=document_id)
doc.delete()
return HttpResponse('Ok')
@staff_required
def rename_document(request, document_id):
doc = Document.objects.get(pk=document_id)
new_caption = request.POST.get('caption', 'Без имени')
doc.caption = new_caption
return HttpResponse('Ok')
@staff_required
def create_part(request):
try:
if not request.POST.get('pid', ''):
return HttpResponse('You did not specify a parent ID.')
else:
parent = Part.objects.get(pk = request.POST['pid'])
except:
return HttpResponse('The specified ID # ' + request.POST['pid'] + ' does not exist.', status=400)
document = parent.document
if not request.POST.get('caption', ''):
return HttpResponse('Name is not specified for the new section.')
else:
caption = unicode(request.POST['caption'])
if request.POST.get('slug', ''):
slug = request.POST['slug']
else:
slug = ''
try:
if request.POST.get('type', ''):
section_type = SectionType.objects.get(pk = request.POST['type'])
else:
section_type = None
except:
return HttpResponse('Current type <b>' + request.POST['type'] + '</b> does not exist.', status=400)
document.create_part(parent, caption, slug, section_type)
return HttpResponse('OK')
@staff_required
def list_parts(request):
document_id = request.POST.get('document_id', 0)
document = Document.objects.get(pk=document_id)
structure = document.get_parts_tree()
index_page = structure.values().pop()
ch(index_page)
result = json.dumps(index_page)
return HttpResponse(result)
@staff_required
def rename_part(request, section_id):
try:
section = Part.objects.get(pk=section_id)
except:
return HttpResponse('Section with ID # ' + request.POST['id'] + ' does not exist.')
if not request.POST.get('caption', ''):
return HttpResponse('Caption is not passed.')
else:
caption = request.POST['caption']
if request.POST.get('slug', ''):
slug = request.POST['slug']
else:
try:
slug = pytils.translit.slugify(caption)
except:
return HttpResponse('In the transliteration of the title was an error, try again, or change the title.', status=400)
section.caption = caption
section.change_slug(slug)
section.save()
return HttpResponse('OK')
@staff_required
def delete_part(request, section_id):
try:
section = Part.objects.get(pk=section_id)
section.delete()
return HttpResponse('Section number ' + str(section_id) + ' has been deleted.')
except:
return HttpResponse('The current section does <u>not exist</u> or it has already been <u>removed</u>.', status=400)
@staff_required
def move_part(request):
try:
section_to_move = Part.objects.get(pk=request.POST['id'])
new_parent = Part.objects.get(pk=request.POST['newpid'])
new_order = request.POST.get('order')
section_to_move.change_parent(new_parent, new_order)
return HttpResponse('OK')
except:
return HttpResponse('Move failed', status=400)
<file_sep># -*- coding: utf8 -*-
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
def change_page_settings(fn):
def new(request, *args, **kwargs):
context = RequestContext(request)
if request.session.get('time_session') is None:
return HttpResponse('Access Denied<br /><a href="../">Войти</a>', status=403)
return fn(request, *args, **kwargs)
return new<file_sep>var initMainFrame = function() {
$(".mainframe tr td.mf_col:first-child").addClass("mf_first");
$($(".mf_col h2").get(0)).css("margin-top", "0");
$(".colors_blocks li span a").wrap('<table cellspacing="0" cellpadding="0"><tr><td></td></tr></table/>');
$(".mf_col h2:first-child").addClass("first");
}
var initSimpleSubmenu = function() {
$(".simple_submenu li.cur").prev().addClass("no_border");
$(".simple_submenu").prev().css("margin-bottom", "0");
}
var hoverThis = function(obj) {
if (obj.attr("id") != "") var name = obj.attr("id"); else var name = obj.attr("class");
obj.mouseenter(
function() {
$(this).addClass("hover").addClass(name + "_hover");
}).mouseleave(function() {
$(this).removeClass("hover").removeClass(name + "_hover");
})
}
var hoverParent = function(parent_obj, hover_obj) {
hover_obj.each(function() {
var tmp = $(this).parents(parent_obj);
$(this).mouseenter(
function() {
$(this).parents(parent_obj).addClass("hover");
}).mouseleave(function() {
$(this).parents(parent_obj).removeClass("hover");
});
});
}
var closeButton = function(close_obj) {
close_obj.find(".close").click(function() {
close_obj.hide();
return false;
});
}
var lastThis = function(parent_obj, target_obj) {
parent_obj.find(target_obj + ":last-child").addClass("last");
parent_obj.find(target_obj + ":last").addClass("last");
}
var initTip = function(bind_type, tip_body, tip_objs, margin_x, margin_y) {
var timeout = 0;
if (tip_body.find(".close").length != 0) var is_close = true; else var is_close = false;
tip_objs.bind(bind_type,
function() {
clearTimeout(timeout);
tip_body
.css("left", ($(this).offset().left - $("#site").offset().left + margin_x) + "px")
.css("top", ($(this).offset().top - $("#site").offset().top + margin_y) + "px").show(200);
if (tip_body.hasClass("arp_icon")) {
tip_body.css("left", ($(this).offset().left - $("#site").offset().left + margin_x + $(this).width() - 7) + "px");
}
}).mouseleave(function() {
if (!is_close) timeout = setTimeout(function() {
tip_body.hide();
}, 100);
});
if (bind_type != "click") tip_objs.click(function() {
return false;
});
tip_body.mouseenter(
function() {
clearTimeout(timeout);
}).mouseleave(function() {
if (!is_close) timeout = setTimeout(function() {
tip_body.hide();
}, 100);
});
}
var randomFontSize = function(obj, from, to) {
var old_size = 16;
obj.each(function() {
var new_size = old_size;
while (new_size == old_size) {
new_size = Math.floor(Math.random() * (to - from + 1)) + from;
}
$(this).css("font-size", new_size + "px");
old_size = new_size;
});
}
var mf_last_margin = function() {
$(".mainframe .mf_col").each(function() {
var childs = $(this).find("h2");
$(childs[childs.length - 1]).css("margin-bottom", 0);
});
}
var initSlideContent = function(bind_type, parent_obj, slide_button, slide_content, class_obj) {
parent_obj.find(slide_button).bind(bind_type, function() {
parent_obj.find(slide_content).slideToggle(0);
parent_obj.find(class_obj).toggleClass("slide_button_show");
return false;
});
}
var initOutsideLinks = function() {
$(".simple_outside_links li.cur ins").each(function() {
var ins = $(this);
var span = ins.next();
var li = ins.parent();
ins.animate({width:(span.width() + 10)}, 1000, "", function() {
li.addClass("selected");
});
});
}
var capitalText = function(capital_objs) {
capital_objs.each(function() {
var cap_obj = $(this);
var cap_text = cap_obj.text();
var cap_letter = cap_text.charAt(0);
var new_cap_text = cap_text.substr(1, cap_text.length - 1);
cap_obj.text(new_cap_text);
$('<ins class="r">' + cap_letter + '</ins>').prependTo(this);
});
}
var initTextGallery = function(tg_objs, global_IE) {
tg_objs.each(function() {
var tg_obj = $(this);
var tg_counter = 0;
var lis = tg_obj.find("li");
var big_pic = tg_obj.find(".overflow");
var li_first = tg_obj.find("li:first-child");
var nextPoint = function(li) {
lis.removeClass("cur");
li.addClass("cur");
if (big_pic.find("img").length != 0) {
var img = big_pic.find("img");
var old_height = img.height();
}
big_pic.html(li.find("span").html());
var img = big_pic.find("img");
var new_height = img.height();
img.hide();
big_pic
.css("height", old_height + "px")
.animate({
height:new_height
}, 500, "", function() {
img.fadeIn(500);
});
tg_obj.find(".panel a").attr("href", li.find("a").attr("rel"));
big_pic.find("img").click(function() {
if (li.next().length != 0) var next_li = li.next(); else var next_li = li_first;
nextPoint(next_li);
return false;
});
}
nextPoint(li_first);
lis.find("a").click(function() {
var a = $(this);
var ul = a.parents("ul");
var li = a.parents("li");
if (!li.hasClass("cur")) {
nextPoint(li);
}
return false;
});
});
}
var alertText = function(text) {
text.each(function() {
$('<span class="alert_text">важно</span>').prependTo(this);
});
}
var imageLeft = function(text) {
text.each(function() {
$('<div class="clear"></div>').appendTo(this);
});
}
var initSimpleImages = function(images) {
images.each(function() {
var image_obj = $(this).find("img");
image_obj.wrap('<table cellspacing="0" cellpadding="0"><tr><td></td></tr></table>');
});
}
var initColorHeighter = function(chs) {
chs.each(function() {
var ch_obj = $(this).find("a");
ch_obj.wrap('<table cellspacing="0" cellpadding="0"><tr><td style="height:' + $(this).height() + 'px;"></td></tr></table>');
});
}
var initAutoRemark = function() {
initTip("click", $(".arp_cont"), $(".auto_remark"), -1, 27);
initTip("mouseenter", $(".arp_icon"), $(".auto_remark"), 0, -11);
}
var initLists = function() {
$("ul.number_marker").each(function() {
var lis = $(this).find("li");
var count = 0;
lis.each(function() {
count++;
$("<ins>" + count + ".</ins>").prependTo(this);
});
});
}
var getCommentFrameHTML = function(id) {
return '<div class="panel"><div class="panel_relative"><div class="panel_rep"><p class="view_comments"><a href="#">18 комментариев</a></p><p class="add_comment"><a href="#">добавить</a></p><p class="like"><a href="#">мне нравиться</a></p></div><div class="stripe"></div></div><div class="panel_top"><div class="png"></div></div><div class="panel_bottom"><div class="png"></div></div></div>';
}
var hideAllComments = function() {
$(".is_comment .panel").hide();
}
var initComment = function(comments_obj) {
comments_obj.each(function() {
var comment_obj = $(this);
var comment_id = comment_obj.attr("id");
var frame_html = getCommentFrameHTML(comment_id);
var is_animate = false;
var timeout = 0;
$(frame_html).appendTo(this);
var comment_border = comment_obj.find(".border");
var comment_panel = comment_obj.find(".panel");
comment_obj.mouseenter(
function() {
clearTimeout(timeout);
if (!is_animate) {
hideAllComments();
is_animate = true;
comment_panel.animate({width:159,right:-170}, 200, "",
function() {
is_animate = false;
}).show();
}
}).mouseleave(function() {
if (!is_animate) {
timeout = setTimeout(function() {
is_animate = true;
comment_panel.animate({width:0,right:-8}, 200, "",
function() {
is_animate = false;
}).hide();
}, 100);
}
});
});
}
var initTableColored = function(){
$(".tableColored").each(function(){
var table = $(this);
table.attr("cellspacing","0").attr("cellpadding","0");
if (table.find("th").length!=0) {
table.find("th:first").parents("tr:first").find("th").addClass("tableColored-th-firstRow");
table.find("th:last-child").addClass("tableColored-th-lastCol");
var max_count = 0;
table.find("tr").each(function(){
var count = $(this).find("th").length;
if (count>max_count) max_count = count;
});
table.find("tr").each(function(){
var count = $(this).find("th").length;
if (count<max_count) $(this).find(".tableColored-th-lastCol").removeClass("tableColored-th-lastCol");
});
}
table.find("td:first").parents("tr:first").find("td").addClass("tableColored-td-firstRow");
table.find("td:last-child").addClass("tableColored-td-lastCol");
table.find("tr:odd td").addClass("tableColored-td_even");
table.find("tr").mouseenter(function(){
$(this).addClass("tableColored-tr_hover");
}).mouseleave(function(){
$(this).removeClass("tableColored-tr_hover");
});
});
}
var initTableText = function(){
$(".tableText").each(function(){
var table = $(this);
table.attr("cellspacing","0").attr("cellpadding","0");
table.find("th:last-child").addClass("tableText-th-lastCol");
table.find("td:last-child").addClass("tableText-td-lastCol");
table.find("tr").mouseenter(function(){
$(this).addClass("tableText-tr_hover");
}).mouseleave(function(){
$(this).removeClass("tableText-tr_hover");
});
});
}
var initTableSimple = function(){
$(".tableSimple").each(function(){
var table = $(this);
table.attr("cellspacing","0").attr("cellpadding","0");
table.find("tr:last-child").addClass("tableSimple-tr-lastRow");
table.find("tr:even td").addClass("tableSimple-td_even");
});
}
<file_sep># -*- coding: utf-8 -*-
from django.http import HttpResponse
from basket import Basket
def add(request, product_id, size_id=0):
basket = Basket(request.session)
new_count = basket.add(product_id, size_id)
return HttpResponse(str(new_count))
def delete(request, product_id, size_id=0):
basket = Basket(request.session)
new_count = basket.delete(product_id, size_id)
return HttpResponse(str(new_count))
def change_size(request, product_id, old_size_id, new_size_id):
basket = Basket(request.session)
basket.change_size(product_id, old_size_id, new_size_id)
return HttpResponse('OK')
def clear(request):
basket = Basket(request.session)
basket.clear()
return HttpResponse('OK')
<file_sep># -*- coding: utf-8 -*-
from django.test import TestCase
from catalogapp import api
from catalogapp import models
class SpecFieldsTest(TestCase):
def test_create(self):
api.sections.create("Name", "slug")
section = api.sections.get(1)
test_query = {
"field_type": "BooleanField",
"name": "Bool Field",
"slug": "bool_slug",
"section": section,
"default_value": True,
"description": "Some desc",
}
result_id = api.specfields.create(**test_query)
result = api.specfields.get(result_id)
self.assertEqual(type(result), models.BooleanField)
del test_query['field_type']
test_query['default_value'] = str(test_query['default_value'])
for attr in test_query:
self.assertEqual(getattr(result, attr), test_query[attr])
def test_change(self):
api.sections.create("Name", "slug")
section = api.sections.get(1)
test_query = {
"field_type": "BooleanField",
"name": "Bool Field",
"slug": "bool_slug",
"section": section,
"default_value": True,
"description": "Some desc",
}
result_id = api.specfields.create(**test_query)
new_name = "new name"
new_slug = "new_slug"
new_default = "False"
new_desc = "new desc"
result_id = api.specfields.change(result_id, new_name, new_slug,
new_default, new_desc)
result = api.specfields.get(result_id)
self.assertEqual(result.name, new_name)
self.assertEqual(result.slug, new_slug)
self.assertEqual(result.default_value, new_default)
self.assertEqual(result.description, new_desc)<file_sep>check_link_hashes = function() {
var hashes = {}
var hash_list = []
$('a[hash-string]').each(function() {
hash_string = $(this).attr('hash-string');
hashes[hash_string] = $(this);
hash_list.push(hash_string);
});
if (hash_list.length) {
$.ajax({
async: true,
type: 'POST',
url: '/api/hashing/links/',
data: $.toJSON(hash_list),
dataType: 'json',
processData: false,
success: function(data) {
for (var i in data) {
hashes[i].attr('href', data[i]);
hashes[i].removeAttr('hash-string');
}
}
});
}
}
check_widget_hashes = function() {
var hashes = {}
var hash_list = []
$('.hashed-widget').each(function() {
hash_string = $(this).attr('hash-string');
hashes[hash_string] = $(this);
hash_list.push(hash_string);
});
if (hash_list.length) {
$.ajax({
async: true,
type: 'POST',
url: '/api/hashing/widgets/',
data: $.toJSON(hash_list),
dataType: 'json',
processData: false,
success: function(data) {
for (var i in data) {
hashes[i].replaceWith(data[i]);
}
}
});
}
}
$(document).ready(function() {
check_link_hashes();
check_widget_hashes();
})
|
72a3f41a94202d6d378c222c5cfa9e68155109bb
|
[
"JavaScript",
"Python",
"HTML"
] | 196
|
Python
|
vakhov/python-django-projects
|
6f296aa75d7692eb5dcb68ef4ce20cadee9dc9e6
|
c312b8bcd94aa448a2678c156ff4936e4a68f668
|
refs/heads/master
|
<repo_name>h4g0/esc-trabalhos<file_sep>/assignment4/ex1.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=24:r432
#PBS -l walltime=02:00:00
#PBS -V
module load gcc/5.3.0
cd assignment4
metrics="instructions,cache-misses,branch-misses,cpu-migrations,branches"
make
#perf stat -e $metrics ./bin/sort 1 1 100000000 > tests/perf_stat_sort1.txt
#perf stat -e $metrics ./bin/sort 2 1 100000000 > tests/perf_stat_sort2.txt
#perf stat -e $metrics ./bin/sort 3 1 100000000 > tests/perf_stat_sort3.txt
#perf stat -e $metrics ./bin/sort 4 1 100000000 > tests/perf_stat_sort4.txt
#perf record -F 99 ./bin/sort 1 1 100000000
#perf report -n --stdio > tests/per_report_sort1.txt
#perf record -F 99 ./bin/sort 2 1 100000000
#perf report -n --stdio > tests/per_report_sort2.txt
#perf record -F 99 ./bin/sort 3 1 100000000
#perf report -n --stdio > tests/per_report_sort3.txt
#perf record -F 99 ./bin/sort 4 1 100000000
#perf report -n --stdio > tests/per_report_sort4.txt
perf record -F 99 -ag ./bin/sort 1 1 100000000
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > tests/sort1.svg
perf record -F 99 -ag ./bin/sort 2 1 100000000
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > tests/sort2.svg
perf record -F 99 -ag ./bin/sort 3 1 100000000
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > tests/sort3.svg
perf record -F 99 -ag ./bin/sort 4 1 100000000
perf script | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > tests/sort4.svg
<file_sep>/assignment1/src/esc-nas/run_tests_system_ser.py
import os
programs = ["is","mg","cg"]
sizes = ["S","W","A","B","C","D"]
repetitions = [100,10,10,1,1,1]
compilers = [('gnuO3','5.3.0')]
tests = 5
commands = list()
for n in compilers:
compiler,version = n
for i in programs:
for x in range(len(sizes)):
command = 'qsub -v \"repetitions=' + str(repetitions[x]) + ',tests=' + str(tests) + ',test_file=' + str(i) + '.' + str(sizes[x]) + '.' + str(compiler) + '.' + str(version) + ',test_exe=' + str(i) + '.' + str(sizes[x]) + '.x,' + 'compiler=' + compiler + ',version=' + version + '\" ser_pbs/system_ser.pbs'
print(command)
commands.append(command)
print(len(commands))
for i in commands:
os.system(i)
<file_sep>/assignment3/src/msdSEQ.c
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sdt.h>
#define NR_BUCKETS 128
#define MAX_DIGITS 4
int *digits_power;
int get_max_digit_size(int nr_buckets,int size) {
int max_size = 1;
for(int i = 0; i < size;i++)
max_size *= nr_buckets;
return max_size;
}
int get_digit(int number,int digit){
return (number / digits_power[MAX_DIGITS - digit - 1]) % NR_BUCKETS;
}
void sequential_radix_sort(int* array,int begining,int end,int digit) {
DTRACE_PROBE2(seq,start_seq_radix,end - begining,digit);
if(end <= begining + 1){
DTRACE_PROBE2(seq,finish_seq_radix,end - begining,digit);
return ;
}
if(digit == MAX_DIGITS){
DTRACE_PROBE2(seq,finish_seq_radix,end - begining,digit);
return ;
}
int count[NR_BUCKETS];
int inserted[NR_BUCKETS];
int start[NR_BUCKETS + 1];
DTRACE_PROBE2(seq,start_sorting_into_buckets,end - begining,digit);
DTRACE_PROBE2(seq,start_allocate_temp_array,end - begining,digit);
int *temp = malloc((end - begining) * sizeof(int));
DTRACE_PROBE2(seq,finish_allocate_temp_array,end - begining,digit);
#pragma ivdep
for(int i = 0; i < NR_BUCKETS; i++){
count[i] = 0;
inserted[i] = 0;
start[i] = 0;
}
start[NR_BUCKETS] = 0;
DTRACE_PROBE2(seq,start_count_digits,end - begining,digit);
for(int i = begining; i < end;i++){
count[get_digit(array[i],digit)]++;
}
DTRACE_PROBE2(seq,finish_count_digits,end - begining,digit);
for(int i = 1; i < NR_BUCKETS + 1;i++){
start[i] += start[i-1] + count[i-1];
}
DTRACE_PROBE2(seq,start_insert_into_buckets,end - begining,digit);
for(int i = begining;i < end;i++){
int msdigit = get_digit(array[i],digit);
temp[start[msdigit] + inserted[msdigit]++] = array[i];
}
DTRACE_PROBE2(seq,finish_insert_into_buckets,end - begining,digit);
DTRACE_PROBE2(seq,start_copy_to_main_array,end - begining,digit);
#pragma ivdep
for(int i = 0; i < end - begining;i++)
array[begining + i] = temp[i];
free(temp);
DTRACE_PROBE2(seq,finish_copy_to_main_array,end - begining,digit);
DTRACE_PROBE2(seq,finish_sorting_into_buckets,end - begining,digit);
for(int i = 1; i < NR_BUCKETS + 1; i++) {
sequential_radix_sort(array,begining + start[i-1] ,begining + start[i],digit + 1);
}
DTRACE_PROBE2(seq,finish_seq_radix,end - begining,digit);
}
void radix_sort(int *array,int size){
sequential_radix_sort(array,0,size,1);
}
void s_radix_sort(int *array,int size){
sequential_radix_sort(array,0,size,2);
}
void init(){
digits_power = malloc(MAX_DIGITS * sizeof(int));
int initial_power = 1;
for(int i = 0; i < MAX_DIGITS;i++) {
digits_power[i] = initial_power;
initial_power *= NR_BUCKETS;
}
return ;
}
int test_sorted(int *test_array,int size) {
for(int i = 1; i < size; i++) {
if(test_array[i-1] > test_array[i]){
printf("%d|%d:%d|%d\n",i-1,test_array[i-1],i,test_array[i]);
return 1;
}
}
return 0;
}
void sort_double(double *array,int size) {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] < array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
}
}
}
}
int main(int argc,char **argv){
init();
int size = atoi(argv[1]);
int nr_tests = atoi(argv[2]);
int k = nr_tests;
double times[nr_tests];
int *test_array = malloc(size * sizeof(int));
for(int test = 0; test < nr_tests; test++) {
for(int i = 0; i < size; i++)
test_array[i] = abs(rand() % 2097152);
double start = omp_get_wtime();
radix_sort(test_array,size);
double end = omp_get_wtime();
times[test] = end - start;
}
sort_double(times,nr_tests);
double average = 0;
for(int i = 0; i < k; i++)
average += times[i];
average /= k;
printf("%f\n",average);
return 0;
}
<file_sep>/assignment1/src/esc-nas/run_tests_system.py
import os
programs = ["mg","ep"]
sizes = ["S","W","A","B","C","D"]
repetitions = [1000,1000,100,100,10,1]
compilers = ['gnuO3']
tests = 5
commands = list()
for compiler in compilers:
for i in programs:
for x in range(len(sizes)):
command = 'qsub -v \"repetitions=' + str(repetitions[x]) + ',tests=' + str(tests) + ',test_file=' + str(i) + '.' + str(sizes[x]) + '.' + str(compiler) + ',test_exe=' + str(i) + '.' + str(sizes[x]) + '.x\" system_pbs/test_systemOMP.pbs'
print(command)
commands.append(command)
print(len(commands))
for i in commands:
os.system(i)
<file_sep>/assignment1/src/esc-nas/Makefile
clean:
rm *pbs.e* *pbs.o*
clean_results:
rm tests/omp/cpu/* tests/omp/memory/* tests/omp/io/* || true
rm tests/ser/cpu/* tests/ser/memory/* tests/ser/io/* || true
rm tests/mpi/cpu/* tests/mpi/memory/* tests/mpi/io/* || true
rm tests/hybrid/cpu/* tests/hybrid/memory/* tests/hybrid/io/* || true
rm tests_part_2/omp/cpu/* tests_part_2/omp/memory/* tests_part_2/omp/io/* || true
rm tests_part_2/ser/cpu/* tests_part_2/ser/memory/* tests_part_2/ser/io/* || true
rm tests_part_2/mpi/cpu/* tests_part_2/mpi/memory/* tests_part_2/mpi/io/* || true
rm tests_part_2/hybrid/cpu/* tests_part_2/hybrid/memory/* tests_part_2/hybrid/io/* || true
<file_sep>/assignment4/compute_metrics.py
def compute_metrics(instructions,cycles,LLC_loads,LLC_load_misses,L1_dcache_loads,L1_dcache_load_misses,dTLB_load_misses,branch_misses,branches):
print(f"instructions per cycle {instructions / cycles}")
print(f"L1 cache miss ration {L1_dcache_loads / L1_dcache_load_misses}")
print(f"L1 cache miss rate PTI {L1_dcache_loads / (instructions / 1000)}")
print(f"LLC cache miss ration {LLC_loads / LLC_load_misses}")
print(f"LLC cache miss rate PTI {LLC_load_misses / (instructions / 1000)}")
print(f"Data TLB miss rate PTI {dTLB_load_misses / (instructions / 1000)}")
print(f"Branch mispredict ratio {branch_misses/branches}")
print(f"Branch mispredict rate PTI {branch_misses / (instructions / 1000)}")
metrics = list()
metrics.append(instructions / cycles)
metrics.append(L1_dcache_loads / L1_dcache_load_misses)
metrics.append(L1_dcache_loads / (instructions / 1000))
metrics.append(LLC_loads / LLC_load_misses)
metrics.append(LLC_load_misses / (instructions / 1000))
metrics.append(dTLB_load_misses / (instructions / 1000))
metrics.append(branch_misses/branches)
metrics.append(branch_misses / (instructions / 1000))
return metrics
def print_metrics(metrics):
for i in range(len(metrics[0])):
row_elements = [str(round(m[i],3)) for m in metrics]
row_elements = " & ".join(row_elements)
print(f"{row_elements} \\\\")
def main():
metrics = list()
print("\n--------------------------------2048-----------------------------------\n")
aux = compute_metrics(60861147730,145812500000,2144100000,437700000,1531700000,438200000,2421900000,4400000,8756400000)
metrics.append(aux)
print("")
aux = compute_metrics(22086293233,16049600000,97500000,80900000,191000000,81200000,12800000,4200000,2309400000)
metrics.append(aux)
print("\n--------------------------------512-----------------------------------\n")
aux = compute_metrics(980082628,953000000,8700000,1,8900000,1,9000000,200000,143900000)
metrics.append(aux)
print("")
aux = compute_metrics(377841466,183900000,1700000,1,1800000,1,400000,200000,44100000)
metrics.append(aux)
print_metrics(metrics)
main()
<file_sep>/assignment1/src/esc-nas/ser_pbs/testSER_intelO2.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=32:r641
#PBS -l walltime=02:00:00
#PBS -V
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
cd esc-nas/NPB3.3.1/NP3.3-SER_INTELO2
#cp config/NAS.samples/suite.def.is config/suite.def
#cp config/NAS.samples/suite.def.is config/suite.def
#cp config/NAS.samples/make.def.gcc_x86 config/make.def
##make clean
##make suite
cd ..
cd ..
##repetitions=1
##tests=5
#define file name and executable
##test_file="is_D_intelO2"
##test_exe="is.D.x"
cpu="tests/ser/cpu/$test_file.txt"
memory="tests/ser/memory/$test_file.txt"
io="tests/ser/io/$test_file.txt"
sar 1 >> $cpu &
sar -r 1 >> $memory &
sar -b 1 >> $io &
for((d = 0; d < tests; d++))
do
for((i = 0; i < repetitions; i++))
do
./NPB3.3.1/NP3.3-SER_INTELO2/bin/$test_exe
done
echo "#test $d" >> $cpu
echo "#test $d" >> $memory
echo "#test $d" >> $io
done
<file_sep>/assignment1/src/esc-nas/run_tests_ser.py
import os
programs = ["is","mg","cg"]
sizes = ["B","C"]
repetitions = [1,1]
compilers = [('gnuO3','5.3.0'),('gnuO2','5.3.0'),('gnuO1','5.3.0'),
('gnuO3','6.1.0'),('gnuO2','6.1.0'),('gnuO1','6.1.0'),
('gnuO3','7.2.0'),('gnuO2','7.2.0'),('gnuO1','7.2.0'),
('intelO3','2019'),('intelO2','2019'),('intelO1','2019')]
tests = 5
commands = list()
for n in compilers:
compiler,version = n
for i in programs:
for x in range(len(sizes)):
command = 'qsub -v \"repetitions=' + str(repetitions[x]) + ',tests=' + str(tests) + ',test_file=' + str(i) + '.' + str(sizes[x]) + '.' + str(compiler) + '.' + str(version) + ',test_exe=' + str(i) + '.' + str(sizes[x]) + '.x,' + 'compiler=' + compiler + ',version=' + version + '\" ser_pbs/ser.pbs'
print(command)
commands.append(command)
print(len(commands))
for i in commands:
os.system(i)
<file_sep>/assignment4/ex5.sh
metrics=("instructions")
period=100000
make
for metric in ${metrics[@]};
do
echo $metric
perf record -e $metric -c $period ./bin/naive 1 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric -c $period ./bin/naive 2 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric -c $period ./bin/naive 1 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric -c $period ./bin/naive 2 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
done
echo "sampling"
for metric in ${metrics[@]};
do
echo $metric
perf record -e $metric ./bin/naive 1 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 2 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 1 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 2 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
done
<file_sep>/assignment3/Makefile
default: msdMPI.o msdOMP.o msdSEQ.o omp.o seq.o mpi.o
/usr/local/bin/mpicc -O3 -o bin/mpi mpi.o msdMPI.o
gcc -O3 -o bin/omp omp.o msdOMP.o -fopenmp
gcc -O3 -o bin/seq seq.o msdSEQ.o -fopenmp
rm *.o*
msdMPI.o:src/msdMPI.c
/usr/local/bin/mpicc -c src/msdMPI.c -fopenmp
msdOMP.o:src/msdOMP.c
gcc -c src/msdOMP.c -fopenmp
msdSEQ.o:src/msdSEQ.c
gcc -c src/msdSEQ.c
omp.o :src/omp.d msdOMP.o
dtrace -G -64 -s src/omp.d msdOMP.o
seq.o:src/seq.d msdSEQ.o
dtrace -G -64 -s src/seq.d msdSEQ.o
mpi.o:src/mpi.d msdMPI.o
dtrace -G -64 -s src/mpi.d msdMPI.o
clean:
rm bin/*
<file_sep>/assignment4/Makefile
compiler = g++
options = -ggdb -O3
default: naive/naive.c sd/main.o sd/sort.o sd/sort.h
export SORT=true
$(compiler) $(options) -o bin/sort sd/main.o sd/sort.o sd/sort.h
$(compiler) $(options) -o bin/naive naive/naive.c
rm sd/*.o
sd/main.o: sd/main.c sd/sort.h
g++ -c sd/main.c
mv main.o sd
sd/sort.o: sd/sort.c sd/sort.h
g++ -c sd/sort.c
mv sort.o sd
clean:
rm bin/*
<file_sep>/assignment1/src/esc-nas/mpi_pbs/system_mpi.pbs
#!/bin/bash
#PBS -l nodes=2:ppn=48:r662
#PBS -l walltime=02:00:00
#PBS -V
module load gcc/5.3.0
if [[ $compiler == "intel_mpich2_eth" ]];
then
echo "compiler 1"
module load intel/mpich2_eth/$version
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
elif [[ $compiler == "intel_mpich_eth" ]];
then
echo "compiler 2"
module load intel/mpich_eth/$version
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
elif [[ $compiler == "gnu_mpich_eth" ]];
then
echo "compiler 3"
module load gnu/mpich_eth/$version
elif [[ $compiler == "gnu_mpich2_eth" ]];
then
echo "compiler 4"
module load gnu/mpich2_eth/$version
elif [[ $compiler == "intel_eth" ]];
then
echo "compiler 5"
module load intel/openmpi_eth/$version
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
elif [[ $compiler == "gnu_eth" ]]
then
echo "compiler 6"
module load gnu/openmpi_eth/$version
fi
cd esc-nas
#cp config/NAS.samples/suite.def.is config/suite.def
#cp config/NAS.samples/make.def.gcc_x86 config/make.def
##repetitions=1
##tests=5
#define file name and executable
##test_file="is_D_gnuO1"
##test_exe="is.D.x"
cpu="tests_part_2/mpi/cpu/$test_file.txt"
memory="tests_part_2/mpi/memory/$test_file.txt"
io="tests_part_2/mpi/io/$test_file.txt"
sar 1 >> $cpu &
sar -r 1 >> $memory &
sar -b 1 >> $io &
for((d = 0; d < tests; d++))
do
for((i = 0; i < repetitions; i++))
do
if [[ $compiler == "gnu_eth" ]];
then
mpirun -np $cores -mca btl self,sm,tcp ./NPB3.3.1/NPB3.3-MPI/$compiler.$version/$test_exe
else
mpirun -np $cores ./NPB3.3.1/NPB3.3-MPI/$compiler.$version/$test_exe
fi
done
echo "#test $d" >> $cpu
echo "#test $d" >> $memory
echo "#test $d" >> $io
done
<file_sep>/assignment3/src/msdOMP.c
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/sdt.h>
#define NR_BUCKETS 128
#define MAX_DIGITS 4
int *digits_power;
int get_max_digit_size(int nr_buckets,int size) {
int max_size = 1;
for(int i = 0; i < size;i++)
max_size *= nr_buckets;
return max_size;
}
int get_digit(int number,int digit){
return (number / digits_power[MAX_DIGITS - digit - 1]) % NR_BUCKETS;
}
void sequential_radix_sort(int* array,int begining,int end,int digit,int bucket) {
DTRACE_PROBE3(omp,start_seq_radix,end - begining,digit,bucket);
if(end <= begining + 1)
return ;
if(digit == MAX_DIGITS)
return ;
int count[NR_BUCKETS];
int inserted[NR_BUCKETS];
int start[NR_BUCKETS + 1];
DTRACE_PROBE3(omp,start_sorting_into_buckets,end - begining,digit,bucket);
DTRACE_PROBE3(omp,start_allocate_temp_array,end - begining,digit,bucket);
int *temp = malloc((end - begining) * sizeof(int));
DTRACE_PROBE3(omp,finish_allocate_temp_array,end - begining,digit,bucket);
#pragma ivdep
for(int i = 0; i < NR_BUCKETS; i++){
count[i] = 0;
inserted[i] = 0;
start[i] = 0;
}
start[NR_BUCKETS] = 0;
DTRACE_PROBE3(omp,start_count_digits,end - begining,digit,bucket);
for(int i = begining; i < end;i++){
count[get_digit(array[i],digit)]++;
}
DTRACE_PROBE3(omp,finish_count_digits,end - begining,digit,bucket);
for(int i = 1; i < NR_BUCKETS + 1;i++){
start[i] += start[i-1] + count[i-1];
}
DTRACE_PROBE3(omp,start_insert_into_buckets,end - begining,digit,bucket);
for(int i = begining;i < end;i++){
int msdigit = get_digit(array[i],digit);
temp[start[msdigit] + inserted[msdigit]++] = array[i];
}
DTRACE_PROBE3(omp,finish_insert_into_buckets,end - begining,digit,bucket);
DTRACE_PROBE3(omp,start_copy_to_main_array,end - begining,digit,bucket);
#pragma ivdep
for(int i = 0; i < end - begining;i++)
array[begining + i] = temp[i];
free(temp);
DTRACE_PROBE3(omp,finish_copy_to_main_array,end - begining,digit,bucket);
DTRACE_PROBE3(omp,finish_sorting_into_buckets,end - begining,digit,bucket);
for(int i = 1; i < NR_BUCKETS + 1; i++) {
sequential_radix_sort(array,begining + start[i-1] ,begining + start[i],digit + 1,bucket);
}
DTRACE_PROBE3(omp,finish_seq_radix,end - begining,digit,bucket);
}
void parallel_radix_sort(int* array,int begining,int end,int digit) {
DTRACE_PROBE3(omp,start_par_radix,end - begining,digit,0);
if(end <= begining + 1){
DTRACE_PROBE3(omp,finish_par_radix,end - begining,digit,0);
return ;
}
if(digit == MAX_DIGITS){
DTRACE_PROBE3(omp,finish_par_radix,end - begining,digit,0);
return ;
}
int count[NR_BUCKETS];
int inserted[NR_BUCKETS];
int start[NR_BUCKETS];
int *temp = malloc((end - begining) * sizeof(int));
DTRACE_PROBE3(omp,start_sorting_into_buckets,end - begining,digit,0);
#pragma ivdep
for(int i = 0; i < NR_BUCKETS; i++){
count[i] = 0;
inserted[i] = 0;
start[i] = 0;
}
DTRACE_PROBE3(omp,start_count_digits,end - begining,digit,0);
int task_size = (end - begining)/NR_BUCKETS;
for(int task = 0; task < NR_BUCKETS;task++) {
#pragma omp task shared(array,count,task_size)
{
int task_start = task * task_size ;
int task_end = (task + 1) * task_size ;
if(task == NR_BUCKETS - 1)
task_end = end;
{
int task_counts[NR_BUCKETS];
for(int i = 0; i < NR_BUCKETS; i++)
task_counts[i] = 0;
for(int i = task_start; i < task_end;i++){
task_counts[get_digit(array[i],digit)]++;
}
for(int i = 0; i < NR_BUCKETS;i++){
#pragma omp atomic
count[i] += task_counts[i];
}
}
}
}
#pragma omp taskwait
for(int i = 1; i < NR_BUCKETS;i++){
start[i] += start[i-1] + count[i-1];
}
DTRACE_PROBE3(omp,finish_count_digits,end - begining,digit,0);
DTRACE_PROBE3(omp,start_insert_into_buckets,end - begining,digit,0);
for(int task = 0; task < NR_BUCKETS;task++) {
#pragma task shared(array,temp,inserted,task_size)
{
int task_start = task * task_size ;
int task_end = (task + 1) * task_size ;
if(task == NR_BUCKETS - 1)
task_end = end;
for(int i = task_start;i < task_end;i++){
int msdigit = get_digit(array[i],digit);
int insert_pos;
#pragma omp atomic capture
{
insert_pos = inserted[msdigit];
inserted[msdigit]++;
}
temp[start[msdigit] + insert_pos] = array[i];
}
}
}
#pragma omp taskwait
DTRACE_PROBE3(omp,finish_insert_into_buckets,end - begining,digit,0);
DTRACE_PROBE3(omp,start_copy_to_main_array,end - begining,digit,0);
#pragma ivdep
for(int i = 0; i < end - begining;i++)
array[begining + i] = temp[i];
free(temp);
DTRACE_PROBE3(omp,finish_copy_to_main_array,end - begining,digit,0);
DTRACE_PROBE3(omp,finish_sorting_into_buckets,end - begining,digit,0);
for(int i = 0; i < NR_BUCKETS; i++) {
#pragma omp task shared(array)
sequential_radix_sort(array,start[i],begining + start[i] + count[i],digit + 1,i + 1);
}
#pragma omp taskwait
DTRACE_PROBE3(omp,finish_par_radix,end - begining,digit,0);
}
void radix_sort(int *array,int size){
parallel_radix_sort(array,0,size,1);
}
void s_radix_sort(int *array,int size){
sequential_radix_sort(array,0,size,2,0);
}
void init(){
digits_power = malloc(MAX_DIGITS * sizeof(int));
int initial_power = 1;
for(int i = 0; i < MAX_DIGITS;i++) {
digits_power[i] = initial_power;
initial_power *= NR_BUCKETS;
}
return ;
}
int test_sorted(int *test_array,int size) {
for(int i = 1; i < size; i++) {
if(test_array[i-1] > test_array[i]){
printf("%d|%d:%d|%d\n",i-1,test_array[i-1],i,test_array[i]);
return 1;
}
}
return 0;
}
void sort_double(double *array,int size) {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] < array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
}
}
}
}
int main(int argc,char **argv){
init();
int size = atoi(argv[1]);
int nr_tests = atoi(argv[2]);
int k = 5;
double times[nr_tests];
int *test_array = malloc(size * sizeof(int));
for(int test = 0; test < nr_tests; test++) {
for(int i = 0; i < size; i++)
test_array[i] = abs(rand() % 2097152);
double start = omp_get_wtime();
#pragma omp parallel
#pragma omp single
radix_sort(test_array,size);
double end = omp_get_wtime();
times[test] = end - start;
}
sort_double(times,nr_tests);
double average = 0;
for(int i = 0; i < 5; i++)
average += times[i];
average /= k;
printf("%f\n",average);
return 0;
}
<file_sep>/assignment1/src/esc-nas/ser_pbs/compile_ser.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=1:r662
#PBS -l walltime=00:20:00
#PBS -V
cd esc-nas/NPB3.3.1/NPB3.3-SER
compilers=("gnu,5.3.0" "gnu,6.1.0" "gnu,7.2.0" "intel,2019")
options=("O3" "O2" "O1")
for i in ${compilers[@]};
do
IFS=',' read comp version <<< "$i"
for v in ${options[@]};
do
compiler=$comp$v
rm bin/*
if [[ $compiler = "intelO3" ]];
then
echo "compiler 1"
cp config/intelO3.def config/make.def
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
elif [[ $compiler = "intelO2" ]];
then
echo "compiler 2"
cp config/intelO2.def config/make.def
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
elif [[ $compiler = "intelO1" ]];
then
echo "compiler 3"
cp config/intelO1.def config/make.def
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
elif [[ $compiler = "gnuO3" ]];
then
echo "compiler 4"
cp config/gnuO3.def config/make.def
module load gcc/$version
elif [[ $compiler = "gnuO2" ]];
then
echo "compiler 5"
cp config/gnuO2.def config/make.def
module load gcc/$version
elif [[ $compiler = "gnuO1" ]]
then
echo "compiler 6"
cp config/gnuO1.def config/make.def
module load gcc/$version
fi
echo $compiler.$version
rm -r $compiler.$version
mkdir $compiler.$version
make clean
make suite
mv bin/* $compiler.$version
done
done
<file_sep>/assignment4/naive/naive.c
//
// Naive matrix multiplication
//
//
// Author: <NAME>
// Date: 10 June 2013
//
// Copyright (c) 2013 <NAME>
//
#include <stdlib.h>
#include <stdio.h>
void initialize_matrices(float **matrix_a,float **matrix_b,float **matrix_r,int msize)
{
int i, j ;
for (i = 0 ; i < msize ; i++) {
#pragma GCC ivdep
for (j = 0 ; j < msize ; j++) {
matrix_a[i][j] = (float) rand() / RAND_MAX ;
matrix_b[i][j] = (float) rand() / RAND_MAX ;
matrix_r[i][j] = 0.0 ;
}
}
}
void multiply_matrices(float **matrix_a,float **matrix_b,float **matrix_r,int msize)
{
int i, j, k ;
for (i = 0 ; i < msize ; i++) {
for (j = 0 ; j < msize ; j++) {
float sum = 0.0 ;
#pragma GCC ivdep
for (k = 0 ; k < msize ; k++) {
sum = sum + (matrix_a[i][k] * matrix_b[k][j]) ;
}
matrix_r[i][j] = sum ;
}
}
}
void multiply_matrices_loop_interchange(float **matrix_a,float **matrix_b,float **matrix_r,int msize)
{
int i, j, k ;
for (i = 0 ; i < msize ; i++) {
for (k = 0 ; k < msize ; k++) {
#pragma GCC ivdep
for (j = 0 ; j < msize ; j++) {
matrix_r[i][j] += (matrix_a[i][k] * matrix_b[k][j]) ;
}
}
}
}
int main(int argc, char* argv[])
{
if(argc < 3){
printf("./sort version(1 naive,2 loop nest interchange) size\n");
exit(0);
}
int version = atoi(argv[1]);
int msize = atoi(argv[2]);
float **matrix_a = (float**) malloc(msize * sizeof(float*));
float **matrix_b = (float**) malloc(msize * sizeof(float*));
float **matrix_r = (float**) malloc(msize * sizeof(float*));
for(int i = 0; i < msize;i++){
matrix_a[i] = (float *) malloc(msize * sizeof(float));
matrix_b[i] = (float *) malloc(msize * sizeof(float));
matrix_r[i] = (float *) malloc(msize * sizeof(float));
}
initialize_matrices(matrix_a,matrix_b,matrix_r,msize) ;
if(version == 1)
multiply_matrices(matrix_a,matrix_b,matrix_r,msize) ;
else
multiply_matrices_loop_interchange(matrix_a,matrix_b,matrix_r,msize) ;
return( EXIT_SUCCESS ) ;
}
<file_sep>/assignment4/ex4.sh
metrics=( "cpu-cycles" "cpu-clock" "L1-dcache-load-misses" "cache-references" "cache-misses" "LLC-loads" "LLC-load-misses" "dTLB-load-misses" "branches" "branch-misses")
period=100000
make
for metric in ${metrics[@]};
do
echo $metric
perf record -e $metric -c $period ./bin/naive 1 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric -c $period ./bin/naive 2 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric -c $period ./bin/naive 1 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric -c $period ./bin/naive 2 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
done
<file_sep>/assignment3/run_tests.sh
make
scripts=("cpc_probes1.d" "cpc_probes2.d" "cpc_probes3.d" "cpc_probes4.d" "sched_probes.d" "sysinfo_probes.d" "vminfo.d" "plockstat.d")
sizes=(1000000 5000000 10000000)
cores=8
repetitions=5
kbest=5
for size in ${sizes[@]};
do
for s in ${scripts[@]};
do
echo tests/seq-$s-$size.txt
./dtrace_scripts/$s '"seq"' -c "./bin/seq $size $repetitions $kbest" > tests/seq-$s-$size.txt
done
echo tests/seq-custom_probes_seq-$size.txt
./bin/seq $size $repetitions $kbest &
pid=$!
dtrace -p $pid -s dtrace_scripts/custom_probes_seq.d > tests/seq-custom_probes_seq-$size.txt
done
for((c = 1; c <= $cores; c*=2))
do
export OMP_NUM_THREADS=$c
for size in ${sizes[@]};
do
for s in ${scripts[@]};
do
echo tests/omp-$c-$s-$size.txt
./dtrace_scripts/$s '"omp"' -c "./bin/omp $size $repetitions $kbest" > tests/omp-$c-$s-$size.txt
done
echo tests/omp-$c-custom_probes_omp-$size.txt
./bin/omp $size $repetitions $kbest &
pid=$!
dtrace -p $pid -s dtrace_scripts/custom_probes_omp.d > tests/omp-custom_probes_omp-$c-$size.txt
done
done
for((c = 1; c <= $cores; c*=2))
do
for size in ${sizes[@]};
do
for s in ${scripts[@]};
do
echo tests/pt-$c-$s-$size.txt
./dtrace_scripts/$s '"pt"' -c "./bin/pt $size $repetitions $kbest $c" > tests/pt-$c-$s-$size.txt
done
echo tests/pt-$c-custom_probes_pt-$size.txt
./bin/pt $size $repetitions $kbest $c &
pid=$!
dtrace -p $pid -s dtrace_scripts/custom_probes_pt.d > tests/omp-custom_probes_pt-$c-$size.txt
done
done
for((c = 1; c <= $cores; c*=2))
do
for size in ${sizes[@]};
do
for s in ${scripts[@]};
do
echo tests/cpp-$c-$s-$size.txt
./dtrace_scripts/$s '"cpp"' -c "./bin/cpp $size $repetitions $kbest $c" > tests/cpp-$c-$s-$size.txt
done
echo tests/cpp-$c-custom_probes_cpp-$size.txt
./bin/cpp $size $repetitions $kbest $c &
pid=$!
dtrace -p $pid -s dtrace_scripts/custom_probes_cpp.d > tests/cpp-custom_probes_cpp-$c-$size.txt
done
done
scripts=("cpc_probes1.d" "cpc_probes2.d" "cpc_probes3.d" "cpc_probes4.d" "sched_probes.d" "sysinfo_probes.d" "vminfo.d" "plockstat.d" "libmpi_probes.d")
for((c = 1; c <= $cores; c*=2))
do
for size in ${sizes[@]};
do
for s in ${scripts[@]};
do
echo tests/mpi-$c-$s-$size.txt
./dtrace_scripts/$s '"mpi"' -c "/usr/local/bin/mpirun -np $c ./bin/mpi $size $repetitions $kbest"
##/usr/local/bin/mpirun -np $c dtrace -s dtrace_scripts/$s -c './bin/mpi $size $repetitions $kbest' >> tests/mpi-$c-$s-$size.txt
done
echo tests/omp-$c-custom_probes_omp-$size.txt
/usr/local/bin/mpirun -np $c ./bin/mpi $size $repetitions $kbest &
pid=$!
dtrace -p $pid -s dtrace_scripts/custom_probes_mpi.d > tests/mpi-custom_probes_mpi-$c-$size.txt
done
done
<file_sep>/assignment4/ex2.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=24:r431
#PBS -l walltime=02:00:00
#PBS -V
cd assignment4
metrics=( "cpu-cycles" "cpu-clock" "L1-dcache-load-misses" "L1-dcache-loads" "L1-dcache-store-misses" "instructions" "cache-misses" "branch-misses" "cpu-migrations" "branches" "L1-dcache-loads" "L1-dcache-load-misses" "L1-dcache-stores" "L1-dcache-store-misses" "L1-icache-loads" "LLC-loads" "LLC-load-misses" "LLC-store-misses" "dTLB-load-misses" "iTLB-load-misses" "branch-loads" "branch-load-misses")
module load gcc/5.3.0
make
for metric in ${metrics[@]};
do
echo $metric >> 2048_1.txt
perf record -e $metric ./bin/naive 1 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 2048_1.txt
echo $metric >> 2048_2.txt
perf record -e $metric ./bin/naive 2 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 2048_2.txt
echo $metric >> 512_1.txt
perf record -e $metric ./bin/naive 1 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 512_1.txt
echo $metric >> 512_2.txt
perf record -e $metric ./bin/naive 2 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 512_2.txt
echo $metric >> 128_1.txt
perf record -e $metric ./bin/naive 1 128
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 128_1.txt
echo $metric >> 128_2.txt
perf record -e $metric ./bin/naive 2 128
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 128_2.txt
echo $metric >> 32_1.txt
perf record -e $metric ./bin/naive 1 32
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 32_1.txt
echo $metric >> 32_2.txt
perf record -e $metric ./bin/naive 2 32
perf report --stdio --show-nr-samples --dsos=naive | grep "Event" >> 32_2.txt
done
<file_sep>/assignment1/src/esc-nas/run_tests_system_hybrid.py
import os
##working mpi implementations
## gnu mpich2 eth - 1.5
## intel mpich2 eht - 1.5
##
programs = ["sp-mz","bt-mz"]
sizes = ["S","W","A","B","C"]
repetitions = [10,1,1,1,1]
compilers = [('gnu_eth','1.8.4')]
tests = 5
nr_cores = 2
cores_machine = 32
commands = list()
for n in compilers:
compiler,version = n
for i in programs:
for x in range(len(sizes)):
command = 'qsub -v \"repetitions=' + str(repetitions[x]) + ',tests=' + str(tests) + ',test_file=' + str(i) + '.' + str(sizes[x]) + '.' + str(compiler) + '.' + str(version) + ',test_exe=' + str(i) + '.' + str(sizes[x]) + '.' + str(nr_cores) + ',' + 'compiler=' + compiler + ',version=' + version + ',cores=' + str(nr_cores) + ",cores_machine=" + str(cores_machine) + '\" hybrid_pbs/system_hybrid.pbs'
print(command)
commands.append(command)
print(len(commands))
for i in commands:
os.system(i)
<file_sep>/assignment1/src/esc-nas/mpi_pbs/compile_mpi.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=1:r662
#PBS -l walltime=00:20:00
#PBS -V
module load gcc/5.3.0
cd esc-nas/NPB3.3.1/NPB3.3-MPI
compilers=("gnu_mpich_eth,1.2.7" "gnu_mpich2_eth,1.5" "intel_eth,1.6.3" "intel_mpich_eth,1.2.7" "intel_mpich2_eth,1.5" "intel_eth,1.8.2" "gnu_eth,1.8.2" "gnu_eth,1.6.3")
for i in ${compilers[@]};
do
IFS=',' read compiler version <<< "$i"
rm bin/*
if [[ $compiler = "intel_mpich_eth" ]];
then
echo "compiler 1"
cp config/mpich.def config/make.def
module load intel/mpich_eth/$version
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
elif [[ $compiler = "gnu_mpich_eth" ]];
then
echo "compiler 2"
cp config/mpich.def config/make.def
module load gnu/mpich_eth/$version
elif [[ $compiler = "gnu_mpich2_eth" ]];
then
echo "compiler 2"
cp config/mpich.def config/make.def
module load gnu/mpich2_eth/$version
elif [[ $compiler = "intel_mpich2_eth" ]];
then
echo "compiler 2"
cp config/mpich.def config/make.def
module load intel/mpich2_eth/$version
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
elif [[ $compiler = "intel_eth" ]];
then
echo "compiler 3"
cp config/openmpi.def config/openmpi.def
module load intel/openmpi_eth/$version
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
elif [[ $compiler = "gnu_eth" ]]
then
echo "compiler 4"
cp config/openmpi.def config/openmpi.def
module load gnu/openmpi_eth/$version
fi
echo $compiler.$version
rm -r $compiler.$version
mkdir $compiler.$version
make clean
make suite
mv bin/* $compiler.$version
done
<file_sep>/assignment3/src/msdPT.c
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/sdt.h>
#define NR_BUCKETS 128
#define MAX_DIGITS 4
int *digits_power;
unsigned thread_count;
pthread_mutex_t mutex_digit[NR_BUCKETS];
int get_max_digit_size(int nr_buckets,int size) {
int max_size = 1;
for(int i = 0; i < size;i++)
max_size *= nr_buckets;
return max_size;
}
int get_digit(int number,int digit){
return (number / digits_power[MAX_DIGITS - digit - 1]) % NR_BUCKETS;
}
void sequential_radix_sort(int* array,int begining,int end,int digit,int bucket) {
DTRACE_PROBE3(pt,start_seq_radix,end - begining,digit,bucket);
if(end <= begining + 1)
return ;
if(digit == MAX_DIGITS)
return ;
int count[NR_BUCKETS];
int inserted[NR_BUCKETS];
int start[NR_BUCKETS + 1];
DTRACE_PROBE3(pt,start_sorting_into_buckets,end - begining,digit,bucket);
DTRACE_PROBE3(pt,start_allocate_temp_array,end - begining,digit,bucket);
int *temp = malloc((end - begining) * sizeof(int));
DTRACE_PROBE3(pt,finish_allocate_temp_array,end - begining,digit,bucket);
#pragma ivdep
for(int i = 0; i < NR_BUCKETS; i++){
count[i] = 0;
inserted[i] = 0;
start[i] = 0;
}
start[NR_BUCKETS] = 0;
DTRACE_PROBE3(pt,start_count_digits,end - begining,digit,bucket);
for(int i = begining; i < end;i++){
count[get_digit(array[i],digit)]++;
}
DTRACE_PROBE3(pt,finish_count_digits,end - begining,digit,bucket);
for(int i = 1; i < NR_BUCKETS + 1;i++){
start[i] += start[i-1] + count[i-1];
}
DTRACE_PROBE3(pt,start_insert_into_buckets,end - begining,digit,bucket);
for(int i = begining;i < end;i++){
int msdigit = get_digit(array[i],digit);
temp[start[msdigit] + inserted[msdigit]++] = array[i];
}
DTRACE_PROBE3(pt,finish_insert_into_buckets,end - begining,digit,bucket);
DTRACE_PROBE3(pt,start_copy_to_main_array,end - begining,digit,bucket);
#pragma ivdep
for(int i = 0; i < end - begining;i++)
array[begining + i] = temp[i];
free(temp);
DTRACE_PROBE3(pt,finish_copy_to_main_array,end - begining,digit,bucket);
DTRACE_PROBE3(pt,finish_sorting_into_buckets,end - begining,digit,bucket);
for(int i = 1; i < NR_BUCKETS + 1; i++) {
sequential_radix_sort(array,begining + start[i-1] ,begining + start[i],digit + 1,bucket);
}
DTRACE_PROBE3(pt,finish_seq_radix,end - begining,digit,bucket);
}
void sort2arrays(int *array,int *array2,int size,int reverse) {
if(reverse) {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] > array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
array2[i] += array2[v];
array2[v] = array2[i] - array2[v];
array2[i] -= array2[v];
}
}
}
}
else {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] < array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
array2[i] += array2[v];
array2[v] = array2[i] - array2[v];
array2[i] -= array2[v];
}
}
}
}
}
void work_allocation(int nprocesses,int *start,int *count,int size) {
int remaining = size;
int reverse = 1;
while(remaining > 0) {
if(remaining > nprocesses) {
sort2arrays(count + (size - remaining)
,start + (size - remaining)
,nprocesses,reverse);
reverse = 1 - reverse;
remaining -= nprocesses;
}
else {
sort2arrays(count + (size - remaining)
,start + (size - remaining)
,remaining,reverse);
remaining = 0;
}
}
return ;
}
void *count_digits(void *args){
int **arguments = (int**) args;
int *array = arguments[0];
int *count = arguments[1];
int digit = *arguments[2];
int t_start = *arguments[3];
int t_end = *arguments[4];
int task_counts[NR_BUCKETS];
for(int i = 0; i < NR_BUCKETS; i++)
task_counts[i] = 0;
for(int i = t_start; i < t_end;i++)
task_counts[get_digit(array[i],digit)]++;
for(int i = 0; i < NR_BUCKETS;i++){
pthread_mutex_lock(&mutex_digit[i]);
count[i] += task_counts[i];
pthread_mutex_unlock(&mutex_digit[i]);
}
}
void *insert_into_buckets(void *args){
int **arguments = (int**) args;
int *array = arguments[0];
int *temp = arguments[1];
int *start = arguments[2];
int *inserted = arguments[3];
int digit = *arguments[4];
int t_start = *arguments[5];
int t_end = *arguments[6];
for(int i = t_start;i < t_end;i++){
int msdigit = get_digit(array[i],digit);
int insert_pos;
pthread_mutex_lock(&mutex_digit[msdigit]);
insert_pos = inserted[msdigit];
inserted[msdigit]++;
pthread_mutex_unlock(&mutex_digit[msdigit]);
temp[start[msdigit] + insert_pos] = array[i];
}
}
void *n_sorts(void *args){
int **arguments = (int**) args;
int *array = arguments[0];
int *count = arguments[1];
int *start = arguments[2];
int digit = *arguments[3];
int t_start = *arguments[4];
int t_end = *arguments[5];
//printf("%d %d\n",t_start,t_end);
for(int i=t_start; i < t_end;i++)
sequential_radix_sort(array,start[i],start[i] + count[i],digit + 1,i + 1);
}
void parallel_radix_sort(int* array,int begining,int end,int digit) {
DTRACE_PROBE3(pt,start_par_radix,end - begining,digit,0);
if(end <= begining + 1){
DTRACE_PROBE3(pt,finish_par_radix,end - begining,digit,0);
return ;
}
if(digit == MAX_DIGITS){
DTRACE_PROBE3(pt,finish_par_radix,end - begining,digit,0);
return ;
}
long thread;
pthread_t *thread_handles;
thread_handles = malloc(thread_count * sizeof(pthread_t));
int count[NR_BUCKETS];
int inserted[NR_BUCKETS];
int start[NR_BUCKETS];
int task_start[thread_count];
int task_end[thread_count];
DTRACE_PROBE3(pt,start_sorting_into_buckets,end - begining,digit,0);
int *temp = malloc((end - begining) * sizeof(int));
DTRACE_PROBE3(pt,start_count_digits,end - begining,digit,0);
#pragma ivdep
for(int i = 0; i < NR_BUCKETS; i++){
count[i] = 0;
inserted[i] = 0;
start[i] = 0;
}
int max_arguments = 10;
int *argument[thread_count][max_arguments];
int task_size = (end - begining)/thread_count;
for(int task = 0; task < thread_count;task++) {
task_start[task] = task * task_size ;
task_end[task] = (task + 1) * task_size ;
if(task == thread_count - 1)
task_end[task] = end;
argument[task][0] = array;
argument[task][1] = &count[0];
argument[task][2] = &digit;
argument[task][3] = &task_start[task];
argument[task][4] = &task_end[task];
//#pragma omp task shared(array,count,task_size)
pthread_create(&thread_handles[task],NULL,count_digits,&argument[task]);
//count_digits(&argument[task]);
}
//#pragma omp taskwait
for(int task = 0;task < thread_count;task++){
pthread_join(thread_handles[task],NULL);
}
DTRACE_PROBE3(pt,finish_count_digits,end - begining,digit,0);
for(int i = 1; i < NR_BUCKETS;i++){
start[i] += start[i-1] + count[i-1];
}
DTRACE_PROBE3(pt,start_insert_into_buckets,end - begining,digit,0);
for(int task = 0; task < thread_count;task++) {
task_start[task] = task * task_size ;
task_end[task] = (task + 1) * task_size ;
if(task == thread_count - 1)
task_end[task] = end;
argument[task][0] = array;
argument[task][1] = temp;
argument[task][2] = &start[0];
argument[task][3] = &inserted[0];
argument[task][4] = &digit;
argument[task][5] = &task_start[task];
argument[task][6] = &task_end[task];
//#pragma task shared(array,temp,inserted,task_size)
pthread_create(&thread_handles[task],NULL,insert_into_buckets,&argument[task]);
//insert_into_buckets(&argument[task]);
}
//#pragma omp taskwait
for(int task = 0;task < thread_count;task++){
pthread_join(thread_handles[task],NULL);
}
DTRACE_PROBE3(pt,finish_insert_into_buckets,end - begining,digit,0);
DTRACE_PROBE3(pt,start_copy_to_main_array,end - begining,digit,0);
#pragma ivdep
for(int i = 0; i < end - begining;i++)
array[begining + i] = temp[i];
free(temp);
DTRACE_PROBE3(pt,finish_copy_to_main_array,end - begining,digit,0);
DTRACE_PROBE3(pt,finish_sorting_into_buckets,end - begining,digit,0);
task_size = NR_BUCKETS/thread_count;
DTRACE_PROBE3(pt,start_workload_distribution,end - begining,digit,0);
work_allocation(thread_count,start,count,NR_BUCKETS);
DTRACE_PROBE3(pt,finish_workload_distribution,end - begining,digit,0);
for(int task = 0; task < thread_count;task++) {
task_start[task] = task * task_size ;
task_end[task] = (task + 1) * task_size ;
if(task == thread_count - 1)
task_end[task] = NR_BUCKETS;
//printf("%d %d\n",task_start,task_end);
argument[task][0] = array;
argument[task][1] = &count[0];
argument[task][2] = &start[0];
argument[task][3] = &digit;
argument[task][4] = &task_start[task];
argument[task][5] = &task_end[task];
pthread_create(&thread_handles[task],NULL,n_sorts,&argument[task]);
//sequential_radix_sort(array,start[i],begining + start[i] + count[i],digit + 1);
}
//#pragma omp taskwait
for(int task = 0;task < thread_count;task++){
pthread_join(thread_handles[task],NULL);
}
free(thread_handles);
DTRACE_PROBE3(pt,finish_par_radix,end - begining,digit,0);
}
void radix_sort(int *array,int size){
parallel_radix_sort(array,0,size,1);
}
void s_radix_sort(int *array,int size){
sequential_radix_sort(array,0,size,1,0);
}
void init(){
digits_power = malloc(MAX_DIGITS * sizeof(int));
int initial_power = 1;
for(int i = 0; i < MAX_DIGITS;i++) {
digits_power[i] = initial_power;
initial_power *= NR_BUCKETS;
}
return ;
}
int test_sorted(int *test_array,int size) {
for(int i = 1; i < size; i++) {
if(test_array[i-1] > test_array[i]){
printf("%d|%d:%d|%d\n",i-1,test_array[i-1],i,test_array[i]);
return 1;
}
}
return 0;
}
void sort_double(double *array,int size) {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] < array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
}
}
}
}
int main(int argc,char **argv){
init();
int size = atoi(argv[1]);
int nr_tests = atoi(argv[2]);
int k = atoi(argv[3]);
unsigned default_threads = 4;
if(argc > 2)
thread_count = atoi(argv[4]);
else
thread_count = default_threads;
for(int i = 0; i < thread_count;i++){
if(pthread_mutex_init(&mutex_digit[i],NULL) != 0){
printf("error initializing mutexes\n");
exit(-1);
}
}
double times[nr_tests];
int *test_array = malloc(size * sizeof(int));
for(int test = 0; test < nr_tests; test++) {
for(int i = 0; i < size; i++)
test_array[i] = abs(rand() % 2097152);
double start = omp_get_wtime();
#pragma omp parallel
#pragma omp single
radix_sort(test_array,size);
double end = omp_get_wtime();
times[test] = end - start;
printf("sorted %d\n",test_sorted(test_array,size));
/*for(unsigned i = 0; i < size;i++)
printf("%d\n",test_array[i]);*/
}
sort_double(times,nr_tests);
double average = 0;
for(int i = 0; i < 5; i++)
average += times[i];
average /= k;
printf("%f\n",average);
return 0;
}
<file_sep>/assignment4/ex2.sh
metrics=( "cpu-cycles" "cpu-clock" "L1-dcache-load-misses" "L1-dcache-loads" "L1-dcache-store-misses" "instructions" "cache-misses" "branch-misses" "cpu-migrations" "branches" "L1-dcache-loads" "L1-dcache-load-misses" "L1-dcache-stores" "L1-dcache-store-misses" "L1-icache-loads" "LLC-loads" "LLC-load-misses" "LLC-store-misses" "dTLB-load-misses" "iTLB-load-misses" "branch-loads" "branch-load-misses")
make
for metric in ${metrics[@]};
do
echo $metric
perf record -e $metric ./bin/naive 1 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 2 2048
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 1 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 2 512
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 1 128
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 2 128
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 1 32
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
perf record -e $metric ./bin/naive 2 32
perf report --stdio --show-nr-samples --dsos=naive | grep "Event"
done
<file_sep>/README.md
# esc-trabalhos
<file_sep>/assignment1/src/esc-nas/omp_pbs/omp.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=32:r641
#PBS -l walltime=02:00:00
#PBS -V
if [[ $compiler = "intelO3" ]];
then
echo "compiler 1"
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
elif [[ $compiler = "intelO2" ]];
then
echo "compiler 2"
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
elif [[ $compiler = "intelO1" ]];
then
echo "compiler 3"
source /share/apps/intel/parallel_studio_xe_2019/compilers_and_libraries_2019/linux/bin/compilervars.sh intel64
module load gcc/5.3.0
elif [[ $compiler = "gnuO3" ]];
then
echo "compiler 4"
module load gcc/$version
elif [[ $compiler = "gnuO2" ]];
then
echo "compiler 5"
module load gcc/$version
elif [[ $compiler = "gnuO1" ]]
then
echo "compiler 6"
module load gcc/$version
fi
echo $compiler.$version
cd esc-nas
#cp config/NAS.samples/suite.def.is config/suite.def
#cp config/NAS.samples/make.def.gcc_x86 config/make.def
##repetitions=1
##tests=5
#define file name and executable
##test_file="is_D_gnuO1"
##test_exe="is.D.x"
cpu="tests/omp/cpu/$test_file.txt"
memory="tests/omp/memory/$test_file.txt"
io="tests/omp/io/$test_file.txt"
sar 1 >> $cpu &
sar -r 1 >> $memory &
sar -b 1 >> $io &
for((d = 0; d < tests; d++))
do
for((i = 0; i < repetitions; i++))
do
./NPB3.3.1/NPB3.3-OMP/$compiler.$version/$test_exe
done
echo "#test $d" >> $cpu
echo "#test $d" >> $memory
echo "#test $d" >> $io
done
<file_sep>/assignment1/src/esc-nas/omp_pbs/testSER.pbs
#!/bin/bash
#PBS -l nodes=1:ppn=32:r641
#PBS -l walltime=01:00:00
#PBS -V
module load gcc/5.3.0
cd esc-nas/NPB3.3.1/NPB3.3-SER
#cp config/NAS.samples/suite.def.is config/suite.def
cp config/NAS.samples/make.def_gcc_x86 config/make.def
make clean
make suite
cd ..
cd ..
repetitions=20
tests=5
#define file name and executable
test_file="is_B_gnuO3"
test_exe="is.B.x"
cpu="tests/ser/cpu/$test_file.txt"
memory="tests/ser/memory/$test_file.txt"
io="tests/ser/io/$test_file.txt"
sar 1 > $cpu &
sar -r 1 > $memory &
sar -b 1 > $io &
for((d = 0; d < tests; d++))
do
echo "#test $d" >> $cpu
echo "#test $d" >> $memory
echo "#test $d" >> $io
for((i = 0; i < repetitions; i++))
do
./NPB3.3.1/NPB3.3-OMP/bin/$test_exe
done
done
<file_sep>/assignment3/src/cpp.h
/*
* Generated by dtrace(8).
*/
#ifndef _CPP_H
#define _CPP_H
#include <unistd.h>
#ifdef __cplusplus
extern "C" {
#endif
#if _DTRACE_VERSION
#define CPP_FINISH_COPY_TO_MAIN_ARRAY(arg0, arg1, arg2) \
__dtrace_cpp___finish_copy_to_main_array(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_FINISH_COPY_TO_MAIN_ARRAY_ENABLED() \
__dtraceenabled_cpp___finish_copy_to_main_array()
#else
#define CPP_FINISH_COPY_TO_MAIN_ARRAY_ENABLED() \
__dtraceenabled_cpp___finish_copy_to_main_array(0)
#endif
#define CPP_FINISH_PAR_RADIX(arg0, arg1, arg2) \
__dtrace_cpp___finish_par_radix(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_FINISH_PAR_RADIX_ENABLED() \
__dtraceenabled_cpp___finish_par_radix()
#else
#define CPP_FINISH_PAR_RADIX_ENABLED() \
__dtraceenabled_cpp___finish_par_radix(0)
#endif
#define CPP_FINISH_SEQ_RADIX(arg0, arg1, arg2) \
__dtrace_cpp___finish_seq_radix(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_FINISH_SEQ_RADIX_ENABLED() \
__dtraceenabled_cpp___finish_seq_radix()
#else
#define CPP_FINISH_SEQ_RADIX_ENABLED() \
__dtraceenabled_cpp___finish_seq_radix(0)
#endif
#define CPP_FINISH_SORTING_INTO_BUCKETS(arg0, arg1, arg2) \
__dtrace_cpp___finish_sorting_into_buckets(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_FINISH_SORTING_INTO_BUCKETS_ENABLED() \
__dtraceenabled_cpp___finish_sorting_into_buckets()
#else
#define CPP_FINISH_SORTING_INTO_BUCKETS_ENABLED() \
__dtraceenabled_cpp___finish_sorting_into_buckets(0)
#endif
#define CPP_FINISH_WORKLOAD_DISTRIBUTION(arg0, arg1, arg2) \
__dtrace_cpp___finish_workload_distribution(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_FINISH_WORKLOAD_DISTRIBUTION_ENABLED() \
__dtraceenabled_cpp___finish_workload_distribution()
#else
#define CPP_FINISH_WORKLOAD_DISTRIBUTION_ENABLED() \
__dtraceenabled_cpp___finish_workload_distribution(0)
#endif
#define CPP_START_COPY_TO_MAIN_ARRAY(arg0, arg1, arg2) \
__dtrace_cpp___start_copy_to_main_array(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_START_COPY_TO_MAIN_ARRAY_ENABLED() \
__dtraceenabled_cpp___start_copy_to_main_array()
#else
#define CPP_START_COPY_TO_MAIN_ARRAY_ENABLED() \
__dtraceenabled_cpp___start_copy_to_main_array(0)
#endif
#define CPP_START_PAR_RADIX(arg0, arg1, arg2) \
__dtrace_cpp___start_par_radix(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_START_PAR_RADIX_ENABLED() \
__dtraceenabled_cpp___start_par_radix()
#else
#define CPP_START_PAR_RADIX_ENABLED() \
__dtraceenabled_cpp___start_par_radix(0)
#endif
#define CPP_START_SEQ_RADIX(arg0, arg1, arg2) \
__dtrace_cpp___start_seq_radix(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_START_SEQ_RADIX_ENABLED() \
__dtraceenabled_cpp___start_seq_radix()
#else
#define CPP_START_SEQ_RADIX_ENABLED() \
__dtraceenabled_cpp___start_seq_radix(0)
#endif
#define CPP_START_SORTING_INTO_BUCKETS(arg0, arg1, arg2) \
__dtrace_cpp___start_sorting_into_buckets(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_START_SORTING_INTO_BUCKETS_ENABLED() \
__dtraceenabled_cpp___start_sorting_into_buckets()
#else
#define CPP_START_SORTING_INTO_BUCKETS_ENABLED() \
__dtraceenabled_cpp___start_sorting_into_buckets(0)
#endif
#define CPP_START_WORKLOAD_DISTRIBUTION(arg0, arg1, arg2) \
__dtrace_cpp___start_workload_distribution(arg0, arg1, arg2)
#ifndef __sparc
#define CPP_START_WORKLOAD_DISTRIBUTION_ENABLED() \
__dtraceenabled_cpp___start_workload_distribution()
#else
#define CPP_START_WORKLOAD_DISTRIBUTION_ENABLED() \
__dtraceenabled_cpp___start_workload_distribution(0)
#endif
extern void __dtrace_cpp___finish_copy_to_main_array(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___finish_copy_to_main_array(void);
#else
extern int __dtraceenabled_cpp___finish_copy_to_main_array(long);
#endif
extern void __dtrace_cpp___finish_par_radix(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___finish_par_radix(void);
#else
extern int __dtraceenabled_cpp___finish_par_radix(long);
#endif
extern void __dtrace_cpp___finish_seq_radix(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___finish_seq_radix(void);
#else
extern int __dtraceenabled_cpp___finish_seq_radix(long);
#endif
extern void __dtrace_cpp___finish_sorting_into_buckets(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___finish_sorting_into_buckets(void);
#else
extern int __dtraceenabled_cpp___finish_sorting_into_buckets(long);
#endif
extern void __dtrace_cpp___finish_workload_distribution(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___finish_workload_distribution(void);
#else
extern int __dtraceenabled_cpp___finish_workload_distribution(long);
#endif
extern void __dtrace_cpp___start_copy_to_main_array(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___start_copy_to_main_array(void);
#else
extern int __dtraceenabled_cpp___start_copy_to_main_array(long);
#endif
extern void __dtrace_cpp___start_par_radix(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___start_par_radix(void);
#else
extern int __dtraceenabled_cpp___start_par_radix(long);
#endif
extern void __dtrace_cpp___start_seq_radix(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___start_seq_radix(void);
#else
extern int __dtraceenabled_cpp___start_seq_radix(long);
#endif
extern void __dtrace_cpp___start_sorting_into_buckets(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___start_sorting_into_buckets(void);
#else
extern int __dtraceenabled_cpp___start_sorting_into_buckets(long);
#endif
extern void __dtrace_cpp___start_workload_distribution(int, int, int);
#ifndef __sparc
extern int __dtraceenabled_cpp___start_workload_distribution(void);
#else
extern int __dtraceenabled_cpp___start_workload_distribution(long);
#endif
#else
#define CPP_FINISH_COPY_TO_MAIN_ARRAY(arg0, arg1, arg2)
#define CPP_FINISH_COPY_TO_MAIN_ARRAY_ENABLED() (0)
#define CPP_FINISH_PAR_RADIX(arg0, arg1, arg2)
#define CPP_FINISH_PAR_RADIX_ENABLED() (0)
#define CPP_FINISH_SEQ_RADIX(arg0, arg1, arg2)
#define CPP_FINISH_SEQ_RADIX_ENABLED() (0)
#define CPP_FINISH_SORTING_INTO_BUCKETS(arg0, arg1, arg2)
#define CPP_FINISH_SORTING_INTO_BUCKETS_ENABLED() (0)
#define CPP_FINISH_WORKLOAD_DISTRIBUTION(arg0, arg1, arg2)
#define CPP_FINISH_WORKLOAD_DISTRIBUTION_ENABLED() (0)
#define CPP_START_COPY_TO_MAIN_ARRAY(arg0, arg1, arg2)
#define CPP_START_COPY_TO_MAIN_ARRAY_ENABLED() (0)
#define CPP_START_PAR_RADIX(arg0, arg1, arg2)
#define CPP_START_PAR_RADIX_ENABLED() (0)
#define CPP_START_SEQ_RADIX(arg0, arg1, arg2)
#define CPP_START_SEQ_RADIX_ENABLED() (0)
#define CPP_START_SORTING_INTO_BUCKETS(arg0, arg1, arg2)
#define CPP_START_SORTING_INTO_BUCKETS_ENABLED() (0)
#define CPP_START_WORKLOAD_DISTRIBUTION(arg0, arg1, arg2)
#define CPP_START_WORKLOAD_DISTRIBUTION_ENABLED() (0)
#endif
#ifdef __cplusplus
}
#endif
#endif /* _CPP_H */
<file_sep>/assignment3/src/msdCPP.cpp
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
#include <vector>
#include<thread>
#include<mutex>
#include<bits/stdc++.h>
#include<sys/sdt.h>
#include "cpp.h"
#define NR_BUCKETS 128
#define MAX_DIGITS 4
int *digits_power;
unsigned thread_count;
std::mutex bucket_mutex[NR_BUCKETS];
int get_max_digit_size(int nr_buckets,int size) {
int max_size = 1;
for(int i = 0; i < size;i++)
max_size *= nr_buckets;
return max_size;
}
int get_digit(int number,int digit){
return (number / digits_power[MAX_DIGITS - digit - 1]) % NR_BUCKETS;
}
void sequential_radix_sort(int* array,int begining,int end,int digit,int bucket) {
CPP_START_SEQ_RADIX(end - begining,digit,bucket);
if(end <= begining + 1)
return ;
if(digit == MAX_DIGITS)
return ;
int start[NR_BUCKETS + 1];
std::vector<std::vector<int>> buckets;
for(unsigned i = 0; i < NR_BUCKETS;i++)
buckets.push_back(std::vector<int>());
CPP_START_SORTING_INTO_BUCKETS(end - begining,digit,bucket);
for(int i = begining;i < end;i++){
int msdigit = get_digit(array[i],digit);
buckets[msdigit].push_back(array[i]);
}
start[0] = 0;
for(int i = 1; i < NR_BUCKETS + 1;i++)
start[i] = start[i-1] + buckets[i-1].size();
int pos_array = 0;
CPP_START_COPY_TO_MAIN_ARRAY(end - begining,digit,bucket);
for(int i = 0; i < NR_BUCKETS;i++)
for(int j = 0; j < buckets[i].size();j++)
array[begining + pos_array++] = buckets[i][j];
CPP_FINISH_COPY_TO_MAIN_ARRAY(end - begining,digit,bucket);
CPP_FINISH_SORTING_INTO_BUCKETS(end - begining,digit,bucket);
for(int i = 1; i < NR_BUCKETS + 1; i++) {
sequential_radix_sort(array,begining + start[i-1] ,begining + start[i],digit + 1,bucket);
}
CPP_FINISH_SEQ_RADIX(end - begining,digit,bucket);
}
void sort2arrays(int *array,int *array2,int size,int reverse) {
if(reverse) {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] > array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
array2[i] += array2[v];
array2[v] = array2[i] - array2[v];
array2[i] -= array2[v];
}
}
}
}
else {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] < array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
array2[i] += array2[v];
array2[v] = array2[i] - array2[v];
array2[i] -= array2[v];
}
}
}
}
}
void work_allocation(int nprocesses,int *start,int *count,int size) {
int remaining = size;
int reverse = 1;
while(remaining > 0) {
if(remaining > nprocesses) {
sort2arrays(count + (size - remaining)
,start + (size - remaining)
,nprocesses,reverse);
reverse = 1 - reverse;
remaining -= nprocesses;
}
else {
sort2arrays(count + (size - remaining)
,start + (size - remaining)
,remaining,reverse);
remaining = 0;
}
}
return ;
}
void insert_into_buckets(int *array,int digit,int begining,int end,std::vector<std::vector<int>> *buckets){
int element;
for(int i = begining;i < end;i++){
element = array[i];
int msdigit = get_digit(element,digit);
bucket_mutex[msdigit].lock();
(*buckets)[msdigit].push_back(element);
bucket_mutex[msdigit].unlock();
}
}
void *n_sorts(void *args){
int **arguments = (int**) args;
int *array = arguments[0];
int *count = arguments[1];
int *start = arguments[2];
int digit = *arguments[3];
int t_start = *arguments[4];
int t_end = *arguments[5];
for(int i=t_start; i < t_end;i++)
sequential_radix_sort(array,start[i],start[i] + count[i],digit + 1,i);
}
class insertion_into_buckets{
public:
void operator()(int *array,int digit,int begining,int end,std::vector<std::vector<int>> *buckets){
insert_into_buckets(array,digit,begining,end,buckets);
}
};
class recursive_call{
public:
void operator()(int *array,int *start,int *count,int digit,int begining,int end){
for(int i = begining; i < end;i++)
sequential_radix_sort(array,start[i],start[i] + count[i],digit,i);
}
};
void parallel_radix_sort(int* array,int begining,int end,int digit) {
CPP_START_PAR_RADIX(end - begining,digit,0);
if(end <= begining + 1){
CPP_FINISH_PAR_RADIX(end - begining,digit,0);
return ;
}
if(digit == MAX_DIGITS){
CPP_FINISH_PAR_RADIX(end - begining,digit,0);
return ;
}
std::vector<std::vector<int>> buckets;
for(unsigned i = 0; i < NR_BUCKETS;i++)
buckets.push_back(std::vector<int>());
int start[NR_BUCKETS];
int count[NR_BUCKETS];
int task_start[thread_count];
int task_end[thread_count];
CPP_START_SORTING_INTO_BUCKETS(end - begining,digit,0);
std::thread Insertions[thread_count];
int task_size = (end - begining)/thread_count;
for(int task = 0; task < thread_count;task++) {
task_start[task] = task * task_size + begining;
task_end[task] = (task + 1) * task_size + begining;
if(task == thread_count - 1)
task_end[task] = end;
//std::thread t(insert_into_buckets,array,digit,task_start[task],task_end[task],buckets);
Insertions[task] = std::thread(insertion_into_buckets(),array,digit,task_start[task],task_end[task],&buckets);
}
for(int i = 0; i < thread_count;i++)
Insertions[i].join();
for(int i = 0; i < NR_BUCKETS;i++)
count[i] = buckets[i].size();
start[0] = begining;
for(int i = 1; i < NR_BUCKETS;i++){
start[i] = start[i-1] + count[i-1];
}
CPP_START_COPY_TO_MAIN_ARRAY(end - begining,digit,0);
int pos_array=begining,bucket_size;
int *curr_bucket;
for(int bucket = 0; bucket < NR_BUCKETS;bucket++){
curr_bucket = &buckets[bucket][0];
bucket_size = buckets[bucket].size();
#pragma GCC IVDEP
for(int i = 0; i < bucket_size;i++)
array[pos_array++] = curr_bucket[i];
}
CPP_FINISH_COPY_TO_MAIN_ARRAY(end - begining,digit,0);
CPP_FINISH_SORTING_INTO_BUCKETS(end - begining,digit,0);
task_size = NR_BUCKETS/thread_count;
CPP_START_WORKLOAD_DISTRIBUTION(end - begining,digit,0);
work_allocation(thread_count,start,count,NR_BUCKETS);
CPP_FINISH_WORKLOAD_DISTRIBUTION(end - begining,digit,0);
std::thread RecursiveCalls[thread_count];
for(int task = 0; task < thread_count;task++) {
task_start[task] = task * task_size ;
task_end[task] = (task + 1) * task_size ;
if(task == thread_count - 1)
task_end[task] = NR_BUCKETS;
//std::thread t(insert_into_buckets,array,digit,task_start[task],task_end[task],buckets);
RecursiveCalls[task] = std::thread(recursive_call(),array,start,count,digit + 1,task_start[task],task_end[task]);
}
for(int i = 0; i < thread_count;i++)
RecursiveCalls[i].join();
CPP_FINISH_PAR_RADIX(end - begining,digit,0);
}
void radix_sort(int *array,int size){
parallel_radix_sort(array,0,size,1);
}
void s_radix_sort(int *array,int size){
sequential_radix_sort(array,0,size,1,0);
}
void init(){
digits_power = (int *) malloc(MAX_DIGITS * sizeof(int));
int initial_power = 1;
for(int i = 0; i < MAX_DIGITS;i++) {
digits_power[i] = initial_power;
initial_power *= NR_BUCKETS;
}
return ;
}
int test_sorted(int *test_array,int size) {
for(int i = 1; i < size; i++) {
if(test_array[i-1] > test_array[i]){
printf("%d|%d:%d|%d\n",i-1,test_array[i-1],i,test_array[i]);
return 1;
}
}
return 0;
}
void sort_double(double *array,int size) {
for(int i = 0; i < size;i++) {
for(int v = i; v < size;v++) {
if(array[v] < array[i]){
array[i] += array[v];
array[v] = array[i] - array[v];
array[i] -= array[v];
}
}
}
}
int main(int argc,char **argv){
init();
int size = atoi(argv[1]);
int nr_tests = atoi(argv[2]);
int k = atoi(argv[3]);
unsigned default_threads = 4;
if(argc > 4)
thread_count = atoi(argv[4]);
else
thread_count = default_threads;
double times[nr_tests];
int *test_array = (int *) malloc(size * sizeof(int));
for(int test = 0; test < nr_tests; test++) {
for(int i = 0; i < size; i++)
test_array[i] = abs(rand() % 2097152);
double start = omp_get_wtime();
#pragma omp parallel
#pragma omp single
radix_sort(test_array,size);
double end = omp_get_wtime();
times[test] = end - start;
printf("sorted %d\n",test_sorted(test_array,size));
/*for(unsigned i = 0; i < size;i++)
printf("%d\n",test_array[i]);
*/
}
sort_double(times,nr_tests);
double average = 0;
for(int i = 0; i < k; i++)
average += times[i];
average /= k;
printf("%f\n",average);
return 0;
}
|
545aaa3e5094728ff005797ef89f40d8cba5f485
|
[
"Markdown",
"Makefile",
"Python",
"C",
"C++",
"Shell"
] | 27
|
Shell
|
h4g0/esc-trabalhos
|
c2eec1a3546c257cc173373fc3257efb5e55fd0e
|
bccfd5049f1d5bad2511df0017892fac1af5305b
|
refs/heads/master
|
<repo_name>CrevolutionRoboticsProgramming/OffseasonVision2019<file_sep>/src/main.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <functional>
#include <yaml-cpp/yaml.h>
#include <opencv2/opencv.hpp>
#include <boost/asio.hpp>
#include "Config.hpp"
#include "MJPEGWriter/MJPEGWriter.h"
#include "Thread.hpp"
#include "Contour.hpp"
#include "UDPHandler.hpp"
std::string configDir{"resources/config.yaml"};
SystemConfig systemConfig{};
VisionConfig visionConfig{};
UvccamConfig uvccamConfig{};
RaspicamConfig raspicamConfig{};
template <typename T>
T getYamlValue(YAML::Node yaml, std::string category, std::string setting)
{
if (yaml[setting])
return yaml[setting].as<T>();
if (!yaml[category] || !yaml[category][setting])
{
std::cout << "Could not find setting " << setting << " in category " << category << '\n';
return T{};
}
return yaml[category][setting].as<T>();
}
void parseConfigs(YAML::Node yamlConfig)
{
std::vector<Config *> configs{};
configs.push_back(std::move(&systemConfig));
configs.push_back(std::move(&visionConfig));
configs.push_back(std::move(&uvccamConfig));
configs.push_back(std::move(&raspicamConfig));
for (Config *config : configs)
{
for (Setting *setting : config->settings)
{
if (dynamic_cast<IntSetting *>(setting) != nullptr)
{
dynamic_cast<IntSetting *>(setting)->value = getYamlValue<int>(yamlConfig, config->getTag(), setting->getTag());
}
else if (dynamic_cast<BoolSetting *>(setting) != nullptr)
{
dynamic_cast<BoolSetting *>(setting)->value = getYamlValue<bool>(yamlConfig, config->getTag(), setting->getTag());
}
else if (dynamic_cast<StringSetting *>(setting) != nullptr)
{
std::string value = getYamlValue<std::string>(yamlConfig, config->getTag(), setting->getTag());
if (value != std::string{})
dynamic_cast<StringSetting *>(setting)->value = value;
}
}
}
if (systemConfig.verbose.value)
std::cout << "Parsed Configs\n";
}
std::string getCurrentConfig()
{
std::vector<Config *> configs{};
configs.push_back(std::move(&systemConfig));
configs.push_back(std::move(&visionConfig));
configs.push_back(std::move(&uvccamConfig));
configs.push_back(std::move(&raspicamConfig));
YAML::Node currentConfig;
for (Config *config : configs)
{
for (Setting *setting : config->settings)
{
if (dynamic_cast<IntSetting *>(setting) != nullptr)
{
currentConfig[config->getTag()][setting->getTag()] = dynamic_cast<IntSetting *>(setting)->value;
}
else if (dynamic_cast<BoolSetting *>(setting) != nullptr)
{
currentConfig[config->getTag()][setting->getTag()] = dynamic_cast<BoolSetting *>(setting)->value;
}
else if (dynamic_cast<StringSetting *>(setting) != nullptr)
{
currentConfig[config->getTag()][setting->getTag()] = dynamic_cast<StringSetting *>(setting)->value;
}
}
}
YAML::Emitter configEmitter;
configEmitter.SetMapFormat(YAML::Block);
configEmitter << currentConfig;
return configEmitter.c_str();
}
bool streamProcessingVideo{false};
// Streamer
class : public Thread
{
public:
void stop() override
{
system("pkill mjpg_streamer");
Thread::stop();
}
private:
void run() override
{
std::ostringstream command;
// Configures camera settings
command << "v4l2-ctl -c exposure_auto=" << uvccamConfig.exposureAuto.value << " -c exposure_absolute=" << uvccamConfig.exposure.value;
system(command.str().c_str());
if (systemConfig.verbose.value)
std::cout << "Configured Exposure\n";
command = std::ostringstream{};
command << "cd ../mjpg-streamer-master/mjpg-streamer-experimental/ && ./mjpg_streamer -i 'input_uvc.so -r "
<< uvccamConfig.width.value << "x" << uvccamConfig.height.value << " -e " << uvccamConfig.everyNthFrame.value
<< "' -o 'output_http.so -p " << systemConfig.videoPort.value << "'";
system(command.str().c_str());
}
} streamThread;
// Vision Processing
class : public Thread
{
private:
void run() override
{
cv::Mat morphElement{cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3, 3))};
UDPHandler robotUDPHandler{9999};
boost::asio::ip::udp::endpoint robotEndpoint{boost::asio::ip::address::from_string("10.28.51.2"), systemConfig.robotPort.value};
std::ostringstream pipeline;
pipeline << "rpicamsrc shutter-speed=" << raspicamConfig.shutterSpeed.value << " exposure-mode=" << raspicamConfig.exposureMode.value
<< " ! video/x-raw,width=" << raspicamConfig.width.value << ",height=" << raspicamConfig.height.value << ",framerate="
<< raspicamConfig.fps.value << "/1 ! appsink";
cv::VideoCapture processingCamera{pipeline.str(), cv::CAP_GSTREAMER};
MJPEGWriter mjpegWriter{systemConfig.videoPort.value};
if (systemConfig.verbose.value && !processingCamera.isOpened())
std::cout << "Could not open processing camera!\n";
cv::Mat streamFrame;
cv::Mat processingFrame;
for (int frameNumber{1}; !stopFlag; ++frameNumber)
{
if (!processingCamera.isOpened())
continue;
if (processingCamera.grab())
processingCamera.read(processingFrame);
else
continue;
if (processingFrame.empty())
continue;
if (systemConfig.verbose.value && frameNumber % 10 == 0)
std::cout << "Grabbed Frame " + std::to_string(frameNumber) + '\n';
if (streamProcessingVideo)
{
if (!mjpegWriter.isOpened())
{
mjpegWriter.write(processingFrame);
mjpegWriter.start();
}
}
else if (mjpegWriter.isOpened())
mjpegWriter.stop();
// Writes frame to be streamed when not tuning
if (streamProcessingVideo && !systemConfig.tuning.value)
mjpegWriter.write(processingFrame);
// Extracts the contours
std::vector<std::vector<cv::Point>> rawContours;
std::vector<Contour> contours;
cv::cvtColor(processingFrame, processingFrame, cv::COLOR_BGR2HSV);
cv::inRange(processingFrame, cv::Scalar{visionConfig.lowHue.value, visionConfig.lowSaturation.value, visionConfig.lowValue.value}, cv::Scalar{visionConfig.highHue.value, visionConfig.highSaturation.value, visionConfig.highValue.value}, processingFrame);
cv::erode(processingFrame, processingFrame, morphElement, cv::Point(-1, -1), 2);
cv::dilate(processingFrame, processingFrame, morphElement, cv::Point(-1, -1), 2);
// Writes vision processing frame to be streamed if requested
if (streamProcessingVideo && systemConfig.tuning.value)
{
// Writes the frame prepared last iteration
mjpegWriter.write(streamFrame);
// Begins preparing the new frame
processingFrame.copyTo(streamFrame);
cv::cvtColor(streamFrame, streamFrame, cv::COLOR_GRAY2BGR);
}
cv::Canny(processingFrame, processingFrame, 0, 0);
cv::findContours(processingFrame, rawContours, cv::noArray(), cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
for (std::vector<cv::Point> pointsVector : rawContours)
{
Contour newContour{pointsVector};
if (newContour.isValid(visionConfig.minArea.value, visionConfig.maxArea.value, visionConfig.minRotation.value, visionConfig.allowableError.value))
{
contours.push_back(newContour);
}
}
std::vector<std::array<Contour, 2>> pairs{};
// Least distant contour initialized with -1 so it's not confused for an actual contour and can be tested for not being valid
int leastDistantContour{-1};
// Now that we've identified compliant targets, we find their match (if they have one)
for (int origContour{0}; origContour < contours.size(); ++origContour)
{
// We identify the left one first because why not
if (contours.at(origContour).angle > 0)
{
// Iterates through all of the contours and compares them against the original
for (int compareContour{0}; compareContour < contours.size(); ++compareContour)
{
//If the contour to compare against isn't the original
// and the contour is angled left
// and the contour is right of the original
// and (if the least distant contour hasn't been set
// OR this contour is closer than the last least distant contour)
// then this contour is the new least distant contour
if (compareContour != origContour && contours.at(compareContour).angle < 0 && contours.at(origContour).rotatedBoundingBoxPoints[0].x < contours.at(compareContour).rotatedBoundingBoxPoints[0].x)
{
//We viewingCamera if it's closer to the original contour after checking if the
// index is negative since passing a negative number to a vector will
// throw an OutOfBounds exception
if (leastDistantContour == -1)
{
leastDistantContour = compareContour;
}
else if (contours.at(compareContour).rotatedBoundingBoxPoints[0].x - contours.at(origContour).rotatedBoundingBoxPoints[0].x < contours.at(leastDistantContour).rotatedBoundingBoxPoints[0].x)
{
leastDistantContour = compareContour;
}
}
}
// If we found the second contour, add the pair to the list
if (leastDistantContour != -1)
{
pairs.push_back(std::array<Contour, 2>{contours.at(origContour), contours.at(leastDistantContour)});
break;
}
}
}
if (pairs.size() == 0)
continue;
std::array<Contour, 2> closestPair{pairs.back()};
for (int p{0}; p < pairs.size(); ++p)
{
double comparePairCenter{((std::max(pairs.at(p).at(0).rotatedBoundingBox.center.x, pairs.at(p).at(1).rotatedBoundingBox.center.x) - std::min(pairs.at(p).at(0).rotatedBoundingBox.center.x, pairs.at(p).at(1).rotatedBoundingBox.center.x)) / 2) + std::min(pairs.at(p).at(0).rotatedBoundingBox.center.x, pairs.at(p).at(1).rotatedBoundingBox.center.x)};
double closestPairCenter{((std::max(closestPair.at(0).rotatedBoundingBox.center.x, closestPair.at(1).rotatedBoundingBox.center.x) - std::min(closestPair.at(0).rotatedBoundingBox.center.x, closestPair.at(1).rotatedBoundingBox.center.x)) / 2) + std::min(closestPair.at(0).rotatedBoundingBox.center.x, closestPair.at(1).rotatedBoundingBox.center.x)};
if (std::abs(comparePairCenter) - (raspicamConfig.width.value / 2) <
std::abs(closestPairCenter) - (raspicamConfig.width.value / 2))
{
closestPair = std::array<Contour, 2>{pairs.at(p).at(0), pairs.at(p).at(1)};
}
}
// For clarity
double centerX{closestPair.at(0).rotatedBoundingBox.center.x + ((closestPair.at(1).rotatedBoundingBox.center.x - closestPair.at(0).rotatedBoundingBox.center.x) / 2)};
double centerY{closestPair.at(0).rotatedBoundingBox.center.y + ((closestPair.at(1).rotatedBoundingBox.center.y - closestPair.at(0).rotatedBoundingBox.center.y) / 2)};
double horizontalAngleError{-((processingFrame.cols / 2.0) - centerX) / processingFrame.cols * raspicamConfig.horizontalFov.value};
robotUDPHandler.sendTo(std::to_string(horizontalAngleError), robotEndpoint);
// Preps frame to be streamed
if (streamProcessingVideo && systemConfig.tuning.value)
{
cv::rectangle(streamFrame, closestPair.at(0).boundingBox, cv::Scalar{0, 127.5, 255}, 2);
cv::rectangle(streamFrame, closestPair.at(1).boundingBox, cv::Scalar{0, 127.5, 255}, 2);
cv::rectangle(streamFrame, cv::Rect{cv::Point2i{std::min(closestPair.at(0).boundingBox.x, closestPair.at(1).boundingBox.x), std::min(closestPair.at(0).boundingBox.y, closestPair.at(1).boundingBox.y)}, cv::Point2i{std::max(closestPair.at(0).boundingBox.x + closestPair.at(0).boundingBox.width, closestPair.at(1).boundingBox.x + closestPair.at(1).boundingBox.width), std::max(closestPair.at(0).boundingBox.y + closestPair.at(0).boundingBox.height, closestPair.at(1).boundingBox.y + closestPair.at(1).boundingBox.height)}}, cv::Scalar{0, 255, 0}, 2);
cv::line(streamFrame, cv::Point{centerX, centerY - 10}, cv::Point{centerX, centerY + 10}, cv::Scalar{0, 255, 0}, 2);
cv::line(streamFrame, cv::Point{centerX - 10, centerY}, cv::Point{centerX + 10, centerY}, cv::Scalar{0, 255, 0}, 2);
cv::putText(streamFrame, "Horizontal Angle of Error: " + std::to_string(horizontalAngleError), cv::Point{0, 10}, cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar{255, 255, 255});
}
std::this_thread::sleep_for(std::chrono::milliseconds{10});
}
mjpegWriter.stop();
}
} processVisionThread;
int main()
{
parseConfigs(YAML::LoadFile(configDir));
streamThread.start();
processVisionThread.start();
UDPHandler communicatorUDPHandler{systemConfig.receivePort.value};
while (true)
{
if (communicatorUDPHandler.getMessage() != "")
{
std::string configsLabel{"CONFIGS:"};
// If we were sent configs
if (communicatorUDPHandler.getMessage().find(configsLabel) != std::string::npos)
{
parseConfigs(YAML::Load(communicatorUDPHandler.getMessage().substr(configsLabel.length()).c_str()));
// Puts the system on read-write mode
system("sudo mount -o remount,rw /");
// Writes the changes to file
remove(configDir.c_str());
std::ofstream file;
file.open(configDir);
if (!file.is_open())
std::cout << "Failed to open configuration file\n";
file << getCurrentConfig() << '\n';
file.close();
// Puts the system back on read-only
system("sudo mount -o remount,ro /");
if (systemConfig.verbose.value)
std::cout << "Updated Configurations\n";
if (!systemConfig.tuning.value)
{
streamThread.stop();
processVisionThread.stop();
while (streamThread.isRunning || processVisionThread.isRunning)
{
std::cout << "Waiting for streaming and vision processing streams to end...\n";
std::this_thread::sleep_for(std::chrono::milliseconds{500});
}
if (!streamProcessingVideo)
streamThread.start();
processVisionThread.start();
}
}
else if (communicatorUDPHandler.getMessage() == "get config")
{
std::string configTag{"CONFIGS:\n"};
communicatorUDPHandler.reply(configTag + getCurrentConfig());
if (systemConfig.verbose.value)
std::cout << "Sent Configurations\n";
}
else if (communicatorUDPHandler.getMessage() == "switch camera")
{
bool newStreamProcessingVideo = !streamProcessingVideo;
if (!newStreamProcessingVideo)
streamThread.start();
else
streamThread.stop();
streamProcessingVideo = newStreamProcessingVideo;
if (systemConfig.verbose.value)
std::cout << "Switched Camera Stream\n";
}
else if (communicatorUDPHandler.getMessage() == "restart program")
{
if (systemConfig.verbose.value)
std::cout << "Restarting program...\n";
streamThread.stop();
processVisionThread.stop();
break;
}
else if (communicatorUDPHandler.getMessage() == "reboot")
{
if (systemConfig.verbose.value)
std::cout << "Rebooting...\n";
system("sudo reboot -h now");
}
else
{
std::cout << "Received unknown command via UDP: " + communicatorUDPHandler.getMessage() + '\n';
}
communicatorUDPHandler.clearMessage();
}
std::this_thread::sleep_for(std::chrono::milliseconds{250});
}
return 0;
}
<file_sep>/src/Contour.cpp
#include <iostream>
#include "Contour.hpp"
Contour::Contour()
{
}
Contour::Contour(std::vector<cv::Point> &pointsVector)
: pointsVector{pointsVector}
{
}
bool Contour::isValid(double minArea, double maxArea, double minRotation, int error)
{
// Approximates a closed polygon with error 3 around the contour and assigns it to newPoly
cv::Mat newPoly;
cv::approxPolyDP(cv::Mat(pointsVector), newPoly, error, true);
// Saves the dimensions of the contour
area = cv::contourArea(pointsVector);
rotatedBoundingBox = cv::minAreaRect(newPoly);
// If the area of the contour is less than the specified minimum area, delete it
if (area < minArea || area > maxArea)
return false;
// Draws a rotated rectangle around the contour and assigns its points to points[]
rotatedBoundingBox.points(rotatedBoundingBoxPoints);
// Finds the indices of the highest and second-lowest points of the rotated rectangle
int highestPoint{0}, secondLowestPoint{0};
for (int i{0}; i < 4; ++i)
{
int pointsHigherThan{0}, pointsLowerThan{0};
for (int o{0}; o < 4; ++o)
{
if (rotatedBoundingBoxPoints[i].y < rotatedBoundingBoxPoints[o].y)
++pointsHigherThan;
if (rotatedBoundingBoxPoints[i].y > rotatedBoundingBoxPoints[o].y)
++pointsLowerThan;
}
if (pointsHigherThan == 3)
highestPoint = i;
else if (pointsLowerThan == 2)
secondLowestPoint = i;
}
// Uses the highest and second-lowest points to calculate the rectangle's rotation
// OpenCV provides a function for this, but it's not consistent with what edge is counted as the top and which indices count for which corners
angle = std::atan((rotatedBoundingBoxPoints[secondLowestPoint].y - rotatedBoundingBoxPoints[highestPoint].y) / (rotatedBoundingBoxPoints[highestPoint].x - rotatedBoundingBoxPoints[secondLowestPoint].x)) * 180 / 3.1415926;
// If the angle isn't steep enough, delete the contour
if ((angle < 0 && angle > -minRotation) || (angle > 0 && angle < minRotation))
{
//std::cout << "Bad angle: " << angle << "\n\n";
return false;
}
// Saves a bounding box for the contour
boundingBox = cv::boundingRect(newPoly);
return true;
}<file_sep>/run.sh
#!/bin/sh
while [ true ]
do
make
./OffseasonVision2019
sleep 5
done
<file_sep>/include/Config.hpp
#pragma once
#include <vector>
#include "Setting.hpp"
class Config
{
private:
std::string mTag;
public:
std::vector<Setting *> settings{};
Config(std::string tag)
{
mTag = tag;
}
std::string getTag()
{
return mTag;
}
};
class SystemConfig : public Config
{
public:
BoolSetting verbose{"verbose"};
BoolSetting tuning{"tuning"};
IntSetting videoPort{"videoPort"};
IntSetting robotPort{"robotPort"};
IntSetting receivePort{"receivePort"};
SystemConfig() : Config("system")
{
settings.push_back(std::move(&verbose));
settings.push_back(std::move(&tuning));
settings.push_back(std::move(&videoPort));
settings.push_back(std::move(&robotPort));
settings.push_back(std::move(&receivePort));
}
};
class VisionConfig : public Config
{
public:
IntSetting lowHue{"lowHue"};
IntSetting lowSaturation{"lowSaturation"};
IntSetting lowValue{"lowValue"};
IntSetting highHue{"highHue"};
IntSetting highSaturation{"highSaturation"};
IntSetting highValue{"highValue"};
IntSetting erosionDilationPasses{"erosionDilationPasses"};
IntSetting minArea{"minArea"};
IntSetting maxArea{"maxArea"};
IntSetting minRotation{"minRotation"};
IntSetting allowableError{"allowableError"};
VisionConfig() : Config("vision")
{
settings.push_back(std::move(&lowHue));
settings.push_back(std::move(&lowSaturation));
settings.push_back(std::move(&lowValue));
settings.push_back(std::move(&highHue));
settings.push_back(std::move(&highSaturation));
settings.push_back(std::move(&highValue));
settings.push_back(std::move(&erosionDilationPasses));
settings.push_back(std::move(&minArea));
settings.push_back(std::move(&maxArea));
settings.push_back(std::move(&minRotation));
settings.push_back(std::move(&allowableError));
}
};
class UvccamConfig : public Config
{
public:
IntSetting width{"width"};
IntSetting height{"height"};
IntSetting everyNthFrame{"everyNthFrame"};
IntSetting exposure{"exposure"};
IntSetting exposureAuto{"exposureAuto"};
UvccamConfig() : Config("uvccam")
{
settings.push_back(std::move(&width));
settings.push_back(std::move(&height));
settings.push_back(std::move(&everyNthFrame));
settings.push_back(std::move(&exposure));
settings.push_back(std::move(&exposureAuto));
}
};
class RaspicamConfig : public Config
{
public:
IntSetting width{"width"};
IntSetting height{"height"};
IntSetting fps{"fps"};
IntSetting shutterSpeed{"shutterSpeed"};
IntSetting exposureMode{"exposureMode"};
IntSetting horizontalFov{"horizontalFov"};
RaspicamConfig() : Config("raspicam")
{
settings.push_back(std::move(&width));
settings.push_back(std::move(&height));
settings.push_back(std::move(&fps));
settings.push_back(std::move(&shutterSpeed));
settings.push_back(std::move(&exposureMode));
settings.push_back(std::move(&horizontalFov));
}
};
|
c92c34564b37989460fdeac000f35a6f19fd41d6
|
[
"C++",
"Shell"
] | 4
|
C++
|
CrevolutionRoboticsProgramming/OffseasonVision2019
|
29791fca986333ca803349c6f78dfff7ee3b2a52
|
b6f1dd3383fc2afbd6b8e24346cae32911a7f804
|
refs/heads/master
|
<file_sep>package lightoutpuzzlesolver;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
class lightout
{
int mat[][];
int x,y;
int n;
JLabel l[][];
Panel p,p2;
Label count;
Button sol;
Random random;
JFrame f;
int cnt,cnt2;
// another class object which is used to check if solution exist for given combinations
solve solv;
lightout()
{
cnt2=0;
f=new JFrame();
sol=new Button(" SOLVE ");
String x;
n=0;
// taking size of board until its greater than 0
while(n<=0)
{
try{
x=JOptionPane.showInputDialog(f,"Enter size of BOARD ");
this.n=Integer.parseInt(x);
}
catch(Exception e)
{n=0;}
}
mat=new int[n][n];
l=new JLabel[n][n];
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
solv.f1.dispose();
System.exit(0);
}
});
setvalue();
p.setBounds(0,0,100*n,100*n);
p2=new Panel();
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
p2.setBounds(0,100*n,100*n,100);
p2.add(sol);
p2.add(count);
sol.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
solv=new solve(mat,n);
solv.f1.setVisible(true);
}
});
f.add(p2);
f.add(p);
f.setLayout(null);
f.setSize(100*n,100*n+100);
f.setVisible(true);
}
void setvalue()
{
random=new Random();
p=new Panel();
p.setLayout(new GridLayout(n,n,5,5));
boolean xx=true;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
l[i][j]=new JLabel();
int ii = random.nextInt(10);
if(ii<5)
{
mat[i][j]=0;
l[i][j].setBackground(Color.GREEN);
l[i][j].setOpaque(true);
p.add(l[i][j]);
}
else
{
mat[i][j]=1;
xx=false;
l[i][j].setBackground(Color.black);
l[i][j].setOpaque(true);
p.add(l[i][j]);
}
l[i][j].addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int x=-1,y=0;
for(int i=0;i<n;i++)
{ for(int j=0;j<n;j++)
if(e.getSource()==l[i][j])
{
x=i;
y=j;
break;
}
if(x!=-1)
break;
}
flip(x,y);
cnt--;
cnt2++;
count.setText("Steps remaining : "+cnt);
if(checkwin())
{
JDialog d=new JDialog(f ,"game Finished in "+cnt2+" moves", true);
d.setSize(300,100);
JButton b=new JButton("exit");
d.add(b);
b.setBounds(10,10,150,50);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f.dispose();
solv.f1.dispose();
System.exit(0);
}
});
d.setVisible(true);
}
if(cnt==0)
{
JDialog d=new JDialog(f," YOU LOSE ",true);
d.setSize(300,100);
JButton b=new JButton(" coninue playing");
d.add(b);
b.setBounds(10,10,200,50);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d.dispose();
}
});
d.setVisible(true);
}
}
});
}
}
// if solution doesn't exit or board is solved already call again the setvalue function
solv=new solve(mat,n);
if(solv.f==10000||xx)
setvalue();
else
{
cnt=solv.f;
count=new Label("Steps remaining : "+cnt);
}
}
// flipping all 5 if exist piesce of board
void flip(int i,int j)
{
int dr[]={0,1,-1,0,0};
int dc[]={0,0,0,1,-1};
for(int k=0;k<5;k++)
{
int x=i+dr[k];
int y=j+dc[k];
if(x>=0&&y>=0&&x<n&&y<n)
{
changebackground(x,y);
mat[x][y]=mat[x][y]==1?0:1;
}
}
}
void changebackground(int x,int y)
{
if(mat[x][y]==1)
l[x][y].setBackground(Color.green);
else
l[x][y].setBackground(Color.black);
}
// checking if they win
boolean checkwin()
{
boolean f=true;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(mat[i][j]==1)
f=false;
return f;
}
}
class solve
{
JFrame f1;
JLabel ll[][];
int dup[][]; // it is the duplicate of main matrix
int tans[][]; // it is matrix that contain temporary changed values of main matrix each time
int pans[][]; // it contain actual solution
int n;
int f;
int mat[][];
solve(int m[][],int nn)
{
f1=new JFrame();
n=nn;
mat=m;
f1.setLayout(new GridLayout(n,n,5,5));
f1.setSize(100*n,100*n);
ll=new JLabel[n][n];
dup=new int[n][n];
makecopy();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
ll[i][j]=new JLabel();
ll[i][j].setOpaque(true);
ll[i][j].setBackground(Color.black);
ll[i][j].setForeground(Color.white);
f1.add(ll[i][j]);
}
f1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f1.dispose();
}
});
findsol();
}
private void findsol()
{
f=10000;
int ff=0;
for(int i=0;i<(1<<n);i++)
{
ff=0;
makecopy();
for(int j=0;j<n;j++)
{
if((i&(1<<j))!=0)
{
flipp(0,j);
tans[0][j]=1;
ff++;
}
}
for(int j=1;j<n;j++)
{
for(int k=0;k<n;k++)
{
if(dup[j-1][k]==1)
{
flipp(j,k);
tans[j][k]=1;
ff++;
}
}
}
boolean valid=true;
for(int j=0;j<n;j++)
{
if(dup[n-1][j]==1)
valid=false;
}
if(valid&&ff<=f)
{
pans=tans;
f=ff;
}
}
if(f!=10000)
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(pans[i][j]==1)
ll[i][j].setText(" click me ");
}
private void makecopy()
{
tans=new int[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
dup[i][j]=mat[i][j];
tans[i][j]=0;
}
}
void flipp(int i,int j)
{
int dr[]={0,1,-1,0,0};
int dc[]={0,0,0,1,-1};
for(int k=0;k<5;k++)
{
int x=i+dr[k];
int y=j+dc[k];
if(x>=0&&y>=0&&x<n&&y<n)
{
dup[x][y]=dup[x][y]==1?0:1;
}
}
}
}
public class LightOutPuzzleSolver
{
public static void main(String ar[])
{
new lightout();
}
}
|
c0e987e66e64580e2fb425531f09e9724c40a7f8
|
[
"Java"
] | 1
|
Java
|
adityans1923/LightOutPuzzleSolver
|
81b62fe605665b1bfcc3e872db831e89c1eb4ec8
|
1e1de753a165a3c3b6bfecdb88bd2b85551427da
|
refs/heads/master
|
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MainMenuManager : MonoBehaviour
{
[SerializeField]
private Button vuforiaButton;
[SerializeField]
private Button arFoundationButton;
[SerializeField]
private Button reactButton;
[SerializeField]
private Button blockchainButton;
[SerializeField]
private Button blobStorageButton;
[SerializeField]
private GameObject featureNotImplementedPanel;
[SerializeField]
private Button okayButton;
private void Awake()
{
vuforiaButton.onClick.AddListener(LinkToVuforia);
arFoundationButton.onClick.AddListener(LinkToArFoundation);
reactButton.onClick.AddListener(LinkToReact);
okayButton.onClick.AddListener(DisablePanel);
blockchainButton.onClick.AddListener(LinkToBlockchain);
blobStorageButton.onClick.AddListener(LinkToBlobStorage);
}
private void LinkToVuforia() {
PlayerPrefs.SetString("lastLoadedScene", SceneManager.GetActiveScene().name);
SceneManager.LoadScene("VuforiaPrototype");
}
private void LinkToArFoundation()
{
PlayerPrefs.SetString("lastLoadedScene", SceneManager.GetActiveScene().name);
SceneManager.LoadScene("Prototype2");
}
private void LinkToBlockchain()
{
PlayerPrefs.SetString("lastLoadedScene", SceneManager.GetActiveScene().name);
SceneManager.LoadScene("BlockchainConnection");
}
private void LinkToBlobStorage()
{
PlayerPrefs.SetString("lastLoadedScene", SceneManager.GetActiveScene().name);
SceneManager.LoadScene("BlobStorage");
}
private void LinkToReact()
{
featureNotImplemented();
}
private void featureNotImplemented() {
featureNotImplementedPanel.SetActive(true);
}
private void DisablePanel()
{
featureNotImplementedPanel.SetActive(false);
}
}
<file_sep># Avanade_Unity
## 1. To further develop this project
1. Clone the project
2. Create a ServerSettings.cs Class file which contains all of the sensitive server settings information by using the template provided on the project website http://students.cs.ucl.ac.uk/2019/group38/appendices.html
3. Fill in the blanks in the ServerSettings.cs with the information required.
4. Copy and paste the ServerSettings.cs file into your ```Assets/Scripts/``` folder along with the other scripts
5. Import project into Unity
6. And you're set to further develop on this application!
## 2. To deploy the application
1. Simply download the apk and install it on your android device with Nougat 7.0 or higher that supports Google ARCore.
Link to download: https://github.com/kuliyhog/Avanade_Unity/blob/master/Prototype02042020.apk
<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class BackButtonScript : MonoBehaviour
{
[SerializeField]
private Button backButton;
private void Awake()
{
backButton.onClick.AddListener(UnloadScene);
}
private void UnloadScene() {
string sceneName = PlayerPrefs.GetString("lastLoadedScene");
SceneManager.LoadScene(sceneName);
}
}
<file_sep>using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using TMPro;
using Nethereum.Web3;
using ServerSettings;
using BCI;
using System.Threading.Tasks;
using Nethereum.Web3.Accounts.Managed;
public class BlobStorageInteraction : MonoBehaviour
{
[SerializeField]
private Button retrieveFromBlockchainButton;
[SerializeField]
private Button downloadButton;
[SerializeField]
private TextMeshProUGUI consoleMessage;
private void Awake()
{
downloadButton.onClick.AddListener(Download);
retrieveFromBlockchainButton.onClick.AddListener(DisplayData);
}
// Function to getHash from blockchain and display the results
private async void DisplayData()
{
var result = await RetrieveFromBlockchain();
if (result != null)
{
consoleMessage.text = "GetHash/Download Link: " + result;
}
else {
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
}
}
// Function to download file and display contents
private async void Download()
{
string downloadLink = await RetrieveFromBlockchain();
UnityWebRequest www = new UnityWebRequest(downloadLink);
www.downloadHandler = new DownloadHandlerBuffer();
www.SendWebRequest();
while (!www.isDone)
await Task.Delay(100);
if (www.isNetworkError || www.isHttpError)
{
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
Debug.Log(www.error);
}
else
{
// Show results as text
consoleMessage.text = "File Contents: " + www.downloadHandler.text;
Debug.Log(www.downloadHandler.text);
}
}
// Function to retreive data form the blockchain
private async Task<string> RetrieveFromBlockchain()
{
QuorumSettings qs = new QuorumSettings();
WalletSettings ws = new WalletSettings();
try
{
var account = await BlockchainContractInteraction.GetAccount();
var managedAccount = new ManagedAccount(account.Address, ws.Password);
var web3Managed = new Web3(managedAccount, qs.UrlWithAccessKey);
var web3 = new Web3(account, qs.UrlWithAccessKey);
var contract = web3.Eth.GetContract(qs.ContractAbi, qs.ContractAddress);
var functionSet = contract.GetFunction("getHash");
var result = await functionSet.CallAsync<string>(2);
return result;
}
catch (System.Exception e) {
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
Debug.Log(e);
return null;
}
}
}<file_sep>using UnityEngine;
using UnityEngine.UI;
public class ToggleVisibility : MonoBehaviour
{
[SerializeField]
private Button toggleVisibilityButton;
[SerializeField]
private GameObject prefabHouse;
void Awake()
{
toggleVisibilityButton.onClick.AddListener(TogglePrefab);
}
private void TogglePrefab()
{
bool isActive = prefabHouse.activeSelf;
prefabHouse.SetActive(!isActive);
}
}
<file_sep>using System;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Nethereum.Web3;
using ServerSettings;
using System.Threading.Tasks;
using Nethereum.Web3.Accounts;
using Nethereum.HdWallet;
using Nethereum.Web3.Accounts.Managed;
namespace BCI {
public class BlockchainContractInteraction : MonoBehaviour
{
[SerializeField]
private Button runScriptButton;
[SerializeField]
private Button retrieveAccBalButton;
[SerializeField]
private Button retrieveHashButton;
[SerializeField]
private Button transferEthButton;
[SerializeField]
private TextMeshProUGUI consoleMessage;
private void Awake()
{
runScriptButton.onClick.AddListener(RopstenContractInteraction);
retrieveAccBalButton.onClick.AddListener(GetAccountBalance);
retrieveHashButton.onClick.AddListener(QuorumContractInteraction);
transferEthButton.onClick.AddListener(TransferEther);
}
// setup a wallet and get an account for the transactions
static public async Task<Account> GetAccount()
{
RopstenSettings rp = new RopstenSettings();
WalletSettings ws = new WalletSettings();
MetamaskSettings ms = new MetamaskSettings();
var words = ws.Words;
var password = <PASSWORD>;
var wallet = new Wallet(words, password);
var account = new Wallet(words, password).GetAccount(0);
return account;
}
private async void GetAccountBalance()
{
RopstenSettings rs = new RopstenSettings();
var account = await GetAccount();
try
{
/* Get Account balance*/
var web3 = new Web3(rs.Url);
var balance = await web3.Eth.GetBalance.SendRequestAsync(account.Address);
var etherAmount = Web3.Convert.FromWei(balance.Value);
var print = $"Account Balance of {account.Address} on Ropsten Test Network\nBalance in Wei: {balance.Value}\nBalance in Ether: {etherAmount}";
consoleMessage.text = print;
}
catch (System.Exception e)
{
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
Debug.Log(e);
}
}
// transfer 0.01ether from sender to receiver
private async void TransferEther()
{
MetamaskSettings ms = new MetamaskSettings();
RopstenSettings rp = new RopstenSettings();
try
{
var account = await GetAccount();
var web3 = new Web3(account, rp.Url);
var balance = await web3.Eth.GetBalance.SendRequestAsync(account.Address);
var balance2 = await web3.Eth.GetBalance.SendRequestAsync(ms.PublicKey);
var print = "The account balance of Sender " + account.Address + "is: " + balance.Value + "\nThe account balance of Receiver " + ms.PublicKey + " is: " + balance2.Value;
consoleMessage.text = print;
var toAddress = ms.PublicKey;
var transactionReceipt = await web3.Eth.GetEtherTransferService()
.TransferEtherAndWaitForReceiptAsync(toAddress, 0.01m, 2);
consoleMessage.text = print;
print = $"Transaction {transactionReceipt.TransactionHash} for amount of 0.01 Ether completed";
consoleMessage.text = print;
balance = await web3.Eth.GetBalance.SendRequestAsync(account.Address);
balance2 = await web3.Eth.GetBalance.SendRequestAsync(ms.PublicKey);
await Task.Delay(2000);
print = "New account balance of Sender " + account.Address + "is: " + balance.Value + "\nNew account balance of Receiver " + ms.PublicKey + " is: " + balance2.Value;
consoleMessage.text = print;
}
catch (System.Exception e)
{
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
Debug.Log(e);
}
}
private async void RopstenContractInteraction()
{
RopstenSettings rp = new RopstenSettings();
try
{
var account = await GetAccount();
var web3 = new Web3(account, rp.Url);
var abi = rp.ContractAbi;
var contract = web3.Eth.GetContract(abi, rp.ContractAddress);
var functionSet = contract.GetFunction("getHash");
var result = await functionSet.CallAsync<string>(22);
var print = "getHash(22) contract function returns: " + result;
consoleMessage.text = print;
}
catch (System.Exception e)
{
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
Debug.Log(e);
}
}
private async void QuorumContractInteraction()
{
QuorumSettings qs = new QuorumSettings();
WalletSettings ws = new WalletSettings();
var account = await GetAccount();
var managedAccount = new ManagedAccount(account.Address, ws.Password);
var web3Managed = new Web3(managedAccount, qs.UrlWithAccessKey);
try
{
var blockNumber = await web3Managed.Eth.Blocks.GetBlockNumber.SendRequestAsync();
var print = "Current BlockNumber: " + blockNumber.Value;
var balance = await web3Managed.Eth.GetBalance.SendRequestAsync(account.Address);
print += "\n" + "Account Balance of " + account.Address + " on Quorum: " + Web3.Convert.FromWei(balance.Value);
var contract = web3Managed.Eth.GetContract(qs.ContractAbi, qs.ContractAddress);
var functionSet = contract.GetFunction("getLatestFileIndex");
var result = await functionSet.CallAsync<int>();
print += $"\ngetLatestFileIndex(): " + result;
consoleMessage.text = print;
}
catch (Exception e)
{
consoleMessage.text = "Error: Check Debug Log\nPossibly no internet access!";
Debug.Log(e);
}
}
}
}
|
d2db6e60e7140c7cd0109810524f9df8c1cd9f98
|
[
"Markdown",
"C#"
] | 6
|
C#
|
kuliyhog/Avanade_Unity
|
29ddf67b3fcd0f0f1bb730e52f55b7011bbac990
|
f3c1929946ca05d0e2ba78041e4f3faafe8f24be
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, NetInfo } from 'react-native';
import IconIoni from 'react-native-vector-icons/Ionicons';
import GridView from 'react-native-super-grid';
import Box from './Box';
import Search from './Search';
export default class Principal extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
pokemon: [],
url: 'https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json',
error: false,
connected: true
}
this.arrayholder = [];
}
handleConnectivityChange = () => {
NetInfo.isConnected.fetch().done((isConnected) => {
if (isConnected) {
this.setState({ connected: true });
} else {
this.setState({ connected: false });
}
});
this.getPokemon();
}
static navigationOptions = {
headerStyle: { backgroundColor: '#388E3C' },
headerLeft:
<View style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 20 }}>
<TouchableOpacity style={{ marginRight: 30 }}
onPress={() => alert("hola2")}>
<IconIoni
name="md-menu"
size={32}
color="white" />
</TouchableOpacity>
<Text style={{ fontSize: 20, color: 'white', fontWeight: 'bold' }}>Pokedex</Text>
</View>
}
componentDidMount() {
NetInfo.isConnected.fetch().done((isConnected) => {
if (isConnected) {
this.setState({ connected: true });
} else {
this.setState({ connected: false });
}
});
this.getPokemon();
}
componentWillUnmount() {
}
getPokemon = () => {
this.setState({ loading: true });
fetch(this.state.url).then(res => res.json())
.then(res => {
this.setState(
{
pokemon: res.pokemon,
loading: false
});
this.arrayholder = res.pokemon;
}).catch(function (error) {
this.setState({ error: true });
});
}
searchFilterFunction = text => {
const newData = this.arrayholder.filter(item => {
const itemData = item.name.toUpperCase();
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
this.setState({ pokemon: newData });
};
render() {
if (!this.state.connected) {
return (<View style={styles.containerError}>
<Text style={{ fontSize: 20, fontWeight: 'bold', textAlign: 'center' }}>Conéctate a Internet</Text>
<Text style={{ fontSize: 18, textAlign: 'center' }}>No tienes Internet. Comprueba la conexión</Text>
<TouchableOpacity
onPress={this.handleConnectivityChange}
style={{
width: 'auto',
paddingVertical: 5,
paddingHorizontal: 10,
backgroundColor: 'transparent',
justifyContent: 'center'
}}>
<Text style={{ fontSize: 18, color:'#1565c0',textAlign: "center" }}>REINTENTAR</Text>
</TouchableOpacity>
</View>)
}
return (
<View style={styles.container}>
<View style={styles.containerTop}>
<Search handleSearch={this.searchFilterFunction} />
</View>
{
this.state.loading
? (
<View style={styles.containerError}>
<Text style={{ fontSize: 18, textAlign: 'center' }}>Descargando Pokemones...</Text>
</View>
)
: (
<GridView
itemDimension={160}
items={this.state.pokemon}
style={styles.gridView}
renderItem={item => (
<Box key={item.id} id={item.id} name={item.name} img={item.img} num={item.num} types={item.type} navigation={this.props.navigation} />
)}
/>
)
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white'
},
containerError: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
padding: 10
},
containerTop: {
backgroundColor: 'white'
},
gridView: {
paddingTop: 5,
flex: 1
}
});
<file_sep>import React, { Component } from 'react';
import {Platform, Text} from 'react-native';
import {createStackNavigator, DrawerNavigator } from 'react-navigation';
import { YellowBox } from 'react-native';
import Principal from './Principal';
import Description from './Description';
export default class Navigation extends Component {
constructor(props) {
super(props);
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated'])
}
render() {
return (
<AppStackNavigator />
);
}
}
const AppStackNavigator = createStackNavigator({
Principal: {
screen: Principal
},
Description:{
screen: Description
}
});
<file_sep>import React, {Component} from 'react';
import {StyleSheet, View, TextInput} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return(
<View style={styles.containerSaerch}>
<Icon
name="search"
size={18}
style={styles.iconSearch}
/>
<TextInput
placeholder='Busque su Pokemon...'
placeholderTextColor='gray'
underlineColorAndroid="transparent"
style={styles.inputSearch}
onChangeText={this.props.handleSearch}
/>
</View>
);
}
}
const styles = StyleSheet.create({
containerSaerch: {
flexDirection: 'row',
borderColor: '#388E3C',
backgroundColor: 'white',
borderWidth: 1,
borderRadius: 4,
marginHorizontal: 10,
marginVertical: 10
},
iconSearch: {
marginTop: 12,
marginLeft: 12,
marginRight: 4
},
inputSearch: {
flex: 1,
height: 42,
fontSize: 14,
backgroundColor: 'white',
color: 'black',
borderRadius: 4
},
});
|
f0326b52d7c60b068970ef6e35da5cc46367d65c
|
[
"JavaScript"
] | 3
|
JavaScript
|
luismy10/ApiPokemonReactNative
|
fe4cce3b0bc36bf3d98396a75d8c4c1f3865c3df
|
547eff9e2d7ea0d144edf6fda6f6ef2746e5279b
|
refs/heads/master
|
<repo_name>tec-csf/TC2017-PF-Otono-2019-tlacuachis<file_sep>/secuencial/NQueen-Secuencial.c
/*Proyecto Final de Algoritmos
<NAME> - A01025211
<NAME> - A01025210
Descripción: Problema de las N Reinas resuelto secuencialmente
*/
#include <omp.h>
#include <stdio.h>
#include <stdbool.h>
//Variables globales
int n = 0; //Tamaño del tablero
int soluciones = 0;
bool imprimir = false;
//Metodo para imprimir
void print(int arr[]){
printf("Soulcion %d \n", soluciones);
for(int i =0; i<n;i++){
for(int j = 0; j<n; j++){
if(arr[i] == j){ //Si el valor en mi hilera es el mismo que en mi columna (Hay una reinas)
printf("Q ");
}
else{ printf("0 ");}
}
printf("\n");
}
}
//Metodo complementario a Reinas
void InsertarReinas(int arr[], int row, int col){
//Tenemos que comprobar en cada hilera si podemos insertar a una reina
//Para que cumpla la regla, ninguna reina se puede atacar entre si (siguiendo las reglas del ajedrez), por lo que hay comprobar ataques verticales y diagonales.
for(int i = 0; i<row; i++){
//Ataques verticales
if (arr[i] == col){ //Si la reina se enucentra en la misma columna, nos salimos
//printf("V Ouch! en la hilera %d",row);
return;
}
//Ataques diagonales (Hay que utilizar la formula de diagonal)
if((abs(arr[i] - col) == (row-i))){
//printf("Q Ouch! en la hilera %d",row);
return;
}
}
//Si ninguna de esos dos ataques se cumplen, podemos asumir que es seguro colocar la reina en esta columna en la hilera actual.
arr[row] = col;
//Checamos si hay mas hileras o si llegamos a la hilera final
if(row == n-1){//Si llegamos a la ultima hilera y pusimos una reina, podemos asumir que la tabla es una solucion.
soluciones++; //Le sumamos 1 a las soluciones
//Aqui imprimimos la tabla, si el usuario eligio imprimirla
if(imprimir == true){
print(arr);
}
}
else{ //Si aun quedan mas hileras, vamos a la siguiente hilera, tratando de encontrar una solucion poniendo una reina en cada columna de la siguiente hilera.
for(int i = 0; i<n; i++){
InsertarReinas(arr, row+1, i);
}
}
}//Terminar metodo
//Metodo principal
void Reinas(int arr[]){
for (int i = 0; i<n; i++){
//Vamos a probar poniendo una reina en cada columna de la primer fila.
//printf("Buscando solucion en el tablero donde la reina empieza en la hilera 0 y columna %d \n", i);
InsertarReinas(arr, 0, i); //Donde: arr (Arreglo/tablero), 0 (row 0 en donde vamos a probar acada reina), i (columna en donde ponemos la primer reina.)
}
}//terminar metodo
//Main
int main(int argc, const char* argv[]){
//Inilizacion al ejecutar el programa ./a.out
if(argc < 3){
printf("Error!: Ejecutar como ./a.out <tamaño del tablero> <0/1 para imprimir tablas o no> \n");
return 0;
}
//Asignar el tama;o del tablero
n = atoi(argv[1]); //Donde argv[1] (string) es el numero que el usuario asigna al ejectuar el programa
//Si se imprimen las soluciones o no.
int option = atoi(argv[2]);
if(option == 1){
imprimir = true;
}
//Declarar arreglo
int arr[n];
//Llamar al metodo
double start = omp_get_wtime();
Reinas(arr);
double finish = omp_get_wtime();
printf("Soluciones con un tablero de %d x %d : %d con un tiempo de ejecucion de: %f \n",n,n,soluciones, finish-start);
}<file_sep>/paralelo/NQueen-Paralelo.c
/*Proyecto Final de Algoritmos
<NAME> - A01025211
<NAME> - A01025210
Descripción: Problema de las N Reinas resuelto paralelizado
*/
#include <omp.h>
#include <stdio.h>
#include <stdbool.h>
//Variables globales
int n = 0; //Tamaño del tablero
int soluciones = 0;
bool imprimir = false;
//Metodo para imprimir
void print(int arr[]){
printf("Soulcion %d \n", soluciones);
for(int i =0; i<n;i++){
for(int j = 0; j<n; j++){
if(arr[i] == j){ //Si el valor en mi hilera es el mismo que en mi columna (Hay una reinas)
printf("Q ");
}//Close if
else{
printf("0 ");
}//Close else
}//Close for
printf("\n");
}//Close for
}//Close print()
//Metodo complementario a Reinas
void InsertarReinas(int arr[], int row, int col, int t_id){
/*Tenemos que comprobar en cada hilera si podemos insertar a una reina.
Para que cumpla la regla, ninguna reina se puede atacar entre si (siguiendo las reglas del ajedrez),
por lo que hay comprobar ataques verticales y diagonales.*/
for(int i = 0; i < row; i++){
//Ataques verticales
if (arr[i] == col){ //Si la reina se encuentra en la misma columna, nos salimos
//printf("V Ouch! en la hilera %d",row);
return;
}//Close if
//Ataques diagonales (Hay que utilizar la formula de diagonal)
if((abs(arr[i] - col) == (row-i))){
//printf("Q Ouch! en la hilera %d",row);
return;
}//Close if
}//Close for
/*Si ninguna de esos dos ataques se cumplen, podemos asumir que es seguro colocar la reina en esta
columna en la hilera actual.*/
arr[row] = col;
//Checamos si hay mas hileras o si llegamos a la hilera final
if(row == n-1){//Si llegamos a la ultima hilera y pusimos una reina, podemos asumir que la tabla es una solucion.
#pragma omp atomic
soluciones++; //Le sumamos 1 a las soluciones
//Aqui imprimimos la tabla, si el usuario eligio imprimirla
if(imprimir == true){
#pragma omp critical
{
/*Si el usuario decide imprimir las soluciones, imprimira la solucion encontrada, la igual que el
thread que la encontro.*/
printf("Thread %d encontro una solucion! \n",t_id);
print(arr);
}//Close pragma
}//Close if
}//Close if
/*Si aun quedan mas hileras, vamos a la siguiente hilera, tratando de encontrar una solucion poniendo una
reina en cada columna de la siguiente hilera.*/
else{
for(int i = 0; i<n; i++){
InsertarReinas(arr, row+1, i,t_id);
}//Clos for
}//Close else
}//Close InsertarReinas()
//Metodo principal
void Reinas(){
int t_id; //Variable para obtener el ID de cada thread
int i;
//AQUI MODIFICAMOS EL TIPO DE SCHEDULE, Aqui es donde implementamos nuestro parallel for.
#pragma omp parallel for schedule(guided,1) private(t_id)
for (i = 0; i<n; i++){
t_id = omp_get_thread_num(); //Obtenemos el id del thread
//Vamos a probar poniendo una reina en cada columna de la primer fila.
//printf("Buscando solucion en el tablero donde la reina empieza en la hilera 0 y columna %d \n", i);
int arr[n]; //A diferencia del secuencial, le asignamos un tablero a cada thread.
//Donde: arr (Arreglo/tablero), 0 (row 0 en donde vamos a probar acada reina), i (columna en donde ponemos la primer reina.)
InsertarReinas(arr, 0, i, t_id);
}//Close for
}//Close Reinas()
//Main
int main(int argc, const char* argv[]){
//Inilizacion al ejecutar el programa ./a.out
if(argc < 4){
printf("Error!: Ejecutar como ./a.out <tamaño del tablero> <numero de threads> <0/1 para imprimir tablas o no> \n");
return 0;
}//Close if
//Asignar el tama;o del tablero
n = atoi(argv[1]); //Donde argv[1] (string) es el numero que el usuario asigna al ejectuar el programa
//Obtener numero de threads
int threads = atoi(argv[2]);
omp_set_num_threads(threads);
//Si se imprimen las soluciones o no.
int option = atoi(argv[3]);
if(option == 1){
imprimir = true;
}//Close if
//Llamar al metodo
double start = omp_get_wtime();
Reinas();
double finish = omp_get_wtime();
printf("Soluciones con un tablero de %d x %d : %d con un tiempo de ejecucion de: %f \n",n,n,soluciones, finish-start);
}//Close main()<file_sep>/README.md
# *Problema de las N Reinas*
---
#### Materia: *Análisis y Diseño de Algoritmos (TC2017)*
#### Semestre: *Otoño 2019*
##### Campus: *Santa Fe*
##### Integrantes:
1. *<NAME>* *A01025211*
2. *<NAME>* *A01025210*
---
## 1. Aspectos generales
### 1.1 Requerimientos
A continuación se mencionan los requerimientos mínimos del proyecto, favor de tenerlos presente para que cumpla con todos.
* El equipo tiene la libertad de elegir el problema a resolver.
* El proyecto deberá utilizar [OpenMP](https://www.openmp.org/) para la implementación del código paralelo.
* Todo el código y la documentación del proyecto debe alojarse en este repositorio de GitHub. Favor de mantener la estructura de carpetas propuesta.
### 1.2 Estructura del repositorio
El proyecto debe seguir la siguiente estructura de carpetas:
```
- / # Raíz de todo el proyecto
- README.md # este archivo
- secuencial # Carpeta con la solución secuencial
- paralelo # Carpeta con la solución paralela
- docs # Carpeta con los documentos, tablas, gráficas, imágenes
```
### 1.3 Documentación del proyecto
Como parte de la entrega final del proyecto, se debe incluir la siguiente información:
* Descripción del problema a resolver.
* Descripción de la solución secuencial con referencia (enlace) al código secuencial alojado en la carpeta [secuencial](secuencial/).
* Análisis de los inhibidores de paralelismo presente y una explicación de cómo se solucionaron.
* Descripción de la solución paralela con referencia (enlace) al código paralelo alojado en la carpeta [paralelo](paralelo/).
* Tabla de resultados con los tiempos de ejecución medidos para cada variante de la solución secuencial vs. la solución paralela, teniendo en cuenta: 5 tamaños diferentes de las entradas, 5 opciones diferentes de números de CPU (threads), 4 ocpiones diferentes de balanceo (*auto, guided, static, dynamic*).
* Gráfica(s) comparativa(s) de los resultados obtenidos en las mediciones.
* Interpretación de los resultados obtenidos.
* Guía paso a paso para la ejecución del código y replicar los resultados obtenidos.
* El código debe estar documentado siguiendo los estándares definidos para el lenguaje de programación seleccionado.
## 2. Descripción del problema
*El problema de las N Reinas consiste en posicionar una cantidad de Reinas en un tablero de ajedrez de tal forma de que no se pueden atacar. Es decir, ninguna reina podra hacer toparse con otra al moverse horizontal/verticalmente/diagonalmente, siguiendo las reglas del ajedrez. La cantidad de reinas depende del tamaño del tablero.*
## 3. Solución secuencial
*Primero que nada, hay dos opciones de resolver este problema: Utilizando Backtracking y Recursividad, nosotros elegimos Recursividad ya que el metodo recursivo (mas adelante) puede ser asignado a cada thread durante la paralelizacion. El programa recibe como entrada el tamaño del tablero de ajedrez y un 0 o 1 para determinar si el usuario desea imprimir las soluciones como una matriz. En base al tamaño dado del tablero, se inicializa un arreglo de ese tamaño. De ahí, el programa llama a la función “Reinas()” donde se va a inicializar un ciclo for y dentro de ese ciclo va a llamar a la función “InsertarReinas()”. Esta función recibe como entrada el arreglo con el cuál va a trabajar, la fila, y la columna. Esencialmente, el ciclo for de “Reinas()” posiciona una reina en cada columna de la primera fila al llamar a “InsertarReinas()”. Dentro de “InsertarReinas()” se tiene que comprobar en cada hilera si se puede insertar una reina. Pero para que cumple con la regla, ninguna reina se podrá atacar entre si (siguiendo las reglas del ajedrez), por lo que hay que verificar ataques verticales y diagonales. En ese momento, se inicializa un ciclo for, donde si la reina se encuentra en la misma columna que otra, se sale. También aplica lo mismo si hay un ataque diagonal. Si ninguno de esos ataques se cumple, el programa puede asumir que es seguro colocar la reina en esa columna en la hilera actual. Al final, el programa revisa si hay más hileras o si llegó a la hilera final. Si el programa llegó a la hilera final y colocó una reina, asume que es una solución y la imprime (si el usuario puso un 1 como entrada). Si aun quedan mas hileras, se mueve a la siguiente, tratando de encontrar una solución posicionando una reina en cada columna de la siguiente hilera. El programa seguirá así hasta que haya determinado si ya no hay más hileras. Esta solución mantiene una complejidad O(n) por solo tener un ciclo for en el metodo de "InsertarReinas()" y "Reinas()".*
## 4. Análisis de los inhibidores del paralelismo
*El programa paralelo contiene 4 metodos:
print (el cual imprime el tablero)
InsertarReina (funcion recursiva donde tratamos de resolver el tablero con la primer reina ya colocada)
Reinas (mi loop principal donde inserto una reina por columna en la primer hilera y se la asigno a un thread)
y el Main()
El print y el main quedan fuera de la idea de ser paralelizados, ya que el main no se puede paralelizar y no requiero repartir la funcion de imprimir entre varios threads, ya que es opcional y no afecta el rendimiendo del programa a menos que sea activado. Incluso si estuviese activado, en una funcion relativamente sencilla y rapida, no vale la pena paralelizar y no es necesario.
InsertarReina es mi metodo recursivo, el cual no hace sentido paralelizar (a parte de ser muy complicado poder paralelizar recursividad) ya que es el metodo que se le va a asignar a cada thread creado, por lo que nos queda la funcion Reinas().
Esta funcion es perfecta para paralelizar, no solo incluye un for si no que, en el for, puedo asignarle un tablero y el metodo recursivo a cada thread distinto.*
## 5. Solución paralela
*El programa recibe como entrada el tamaño del tablero de ajedrez, el numero de threads en el cual se ejecutaran las partes más importantes del código, y un 0 o 1 para determinar si el usuario desea imprimir las soluciones como una matriz. En base al tamaño dado del tablero, se inicializa un arreglo de ese tamaño. De ahí, el programa llama a la función “Reinas()” donde se va a inicializar un ciclo for cubierto por una pragma que privatiza la variable de “t_Id” (la que guarda el número de cada thread) y incluye un scheduler de tipo static, auto, dynamic, o guided. Los tipos de schedulers se tiene que cambiar manualmente en el código. Dentro de ese ciclo va a llamar a la función “InsertarReinas()”. Pero antes, inicializa un arreglo separado para cada thread. “InsertarReinas()” recibe como entrada el arreglo con el cuál va a trabajar, la fila, la columna, y el respectivo thread. Esencialmente, el ciclo for de “Reinas()” posiciona una reina en cada columna de la primera fila al llamar a “InsertarReinas()”. Dentro de “InsertarReinas()” se tiene que comprobar en cada hilera si se puede insertar una reina. Pero para que cumple con la regla, ninguna reina se podrá atacar entre si (siguiendo las reglas del ajedrez), por lo que hay que verificar ataques verticales y diagonales. En ese momento, se inicializa un ciclo for, donde si la reina se encuentra en la misma columna que otra, se sale. También aplica lo mismo si hay un ataque diagonal. Si ninguno de esos ataques se cumple, el programa puede asumir que es seguro colocar la reina en esa columna en la hilera actual. Al final, el programa revisa si hay más hileras o si llegó a la hilera final. Si el programa llegó a la hilera final y colocó una reina, asume que es una solución y la imprime (si el usuario puso un 1 como entrada) junto con el número de thread en el que se ejecutó. Si aun quedan mas hileras, se mueve a la siguiente, tratando de encontrar una solución posicionando una reina en cada columna de la siguiente hilera. Cuando el thread enucentra una solucion, le asigno una seccion "atomica", donde le da acceso a una parte especifica de la memoria (en esta caso es mi int de soluciones) para que modifique especificamente esa variable (sin locks) si ese thread en especifico encuentra una solucion. Mi funcion de print le asigno una seccion critica, ya que solo quiero que ese thread en especifico imprima la solucion (si es que encuentra alguna). El programa seguirá así hasta que haya determinado si ya no hay más hileras. Esta solución mantiene una complejidad O(n!) al ser recursivo".*
## 6. Tabla de resultados
[Ver Excel en la carpeta de "docs"]
## 7. Gráfica(s) comparativa(s)
[Ver Excel en la carpeta de "docs"]
## 8. Interpretación de los resultados
*Generalmente, paralelizar un programa que resuelve un problema, es mucho más eficiente que dejarlo como secuencial. Pero en este caso, depende mucho de la cantidad de threads siendo utilizadas y el tamaño del tablero de ajedrez. Como se puede ver en las gráficas de tamaño de tablero 6 y 8, paralelizar el programa y incluir cualquier numero de threads, estos siendo 2, 4, 8, 16, y 32, es inecesario. La versión secuencial corre más rápido que el paralelizado, en todos los casos. Dejando el programa como secuencial es la mejor opción, seguramente por el hecho de que los tableros de 6x6 y 8x8 son más pequeños comparados con los otros. Ahora bien, para los casos de los tableros de 10x10 y 12x12, lo mejor sería usar la versión paralelizada. Para el tablero de tamaño 10x10, es mucho mejor usar la versión paralizada con el scheduler de tipo guided, utilizando 16 threads. Esta versión corre y finaliza con 0.0031304 segundos, mientras que la versión secuencial corre y finaliza con 0.008442. Para el tablero de 12x12, la mejor versión es la paralelizada con el scheduler tipo static, también utilizando 16 threads. Esta versión corre y finaliza en 0.0586962 segundos, mientras que la versión secuencial corre y finaliza en 0.234226. Finalmente, el tablero de 14x14, el más grande, obvio es más eficiente siendo paralelizado. Especificamente, la versión paralelizada con el scheduler tipo guided, utilizando 32 threads es el mejor. Es el que corre y finaliza en menor tiempo, 1.928452 segundos. La versión secuencial corre y finaliza en 9.1787602 segundos, casi 10 veces más. Para concluir, la cuestión de cuál versión es mejor para utilizar depende enteramente del tamaño del tablero, el tipo de scheduler, y la cantidad de threads utilizadas. Mientras más grande sea el tablero, mejor es utilizar una versión paralela.*
## 9. Guía paso a paso
*Para cambiar de tipo de scheduler en la versión paralela, simplemente hay que cambiar en la linea 89 la palabra "guided" por "static", "dynamic", o "auto". Para compilar el secuencial, escriba "gcc -fopenmp NQueen-Secuencial.c -o NQueen-Secuencial" en la terminal, dentro del folder en el cual está guardado el archivo. Para correrlo, escriba "./NQueen-Secuencial <tamaño del tablero (6, 8, 10, 12, 14)> <0 u 1 si desea imprimir los resultados como matrices>". Para compilar el paralelo, escriba "gcc -fopenmp NQueen-Paralelo.c -o NQueen-Paralelo" en la terminal, dentro del folder en el cual está guardado el archivo. Para correrlo, escriba "./NQueen-Paralelo <tamaño del tablero> <número de threads> <0 u 1 si desea imprimir los resultados como matrices>".*
## 10. Referencias
*<NAME> & Meadows, Larry. (na). A "Hands-On" Introduction to OpenMP* [PDF file]. Retrived from https://www.openmp.org/wp-content/uploads/omp-hands-on-SC08.pdf
(n.d.). Retrieved November 24, 2019, from https://www.ibm.com/support/knowledgecenter/SSGH2K_12.1.0/com.ibm.xlc121.aix.doc/compiler_ref/ruomprun1.html.(n.d.).
Retrieved November 24, 2019, from http://jakascorner.com/blog/2016/06/omp-for-scheduling.html.(n.d.).
Retrieved November 24, 2019, from https://www.youtube.com/watch?v=wGbuCyNpxIg.Admin. (2019, October 1). OpenMP* Loop Scheduling.
Retrieved November 25, 2019, from https://software.intel.com/en-us/articles/openmp-loop-scheduling.AmirAmir 39711 gold badge33 silver badges1010 bronze badges, GillesGilles 7, & <NAME> 58.4k99 gold badges9797 silver badges145145 bronze badges. (1966, January 1). difference between omp critical and omp single.
Retrieved November 24, 2019, from https://stackoverflow.com/questions/33441767/difference-between-omp-critical-and-omp-single.Esraa, E. E. E. (1966, February 1). Optimizing N-queen with openmp c.
Retrieved November 24, 2019, from https://stackoverflow.com/questions/34141909/optimizing-n-queen-with-openmp-c.N Queen Problem: Backtracking-3. (2019, October 16).
Retrieved November 24, 2019, from https://www.geeksforgeeks.org/n-queen-problem-backtracking-3/.Printing all solutions in N-Queen Problem. (2019, July 19).
Retrieved November 24, 2019, from https://www.geeksforgeeks.org/printing-solutions-n-queen-problem/.Victoraldecoa. (n.d.). victoraldecoa/N-Queens-Solver_OpenMP_Example.
Retrieved November 24, 2019, from https://github.com/victoraldecoa/N-Queens-Solver_OpenMP_Example/blob/master/src/nqueens-openmp.c.*
|
72dd60d2d79bcca6e3eabb50247fb5003eebd41b
|
[
"Markdown",
"C"
] | 3
|
C
|
tec-csf/TC2017-PF-Otono-2019-tlacuachis
|
4f4d129985768bd03d7f6084809f45b03057feaf
|
67db7100907385bd98d691d3fcc2361c8484c6c0
|
refs/heads/master
|
<file_sep>export class Day {
public matin = {
debut: String,
fin: String
};
public soir = {
debut: String,
fin: String
}
constructor (matDeb, matFin, soirDeb, soirFin){
this.matin.debut = matDeb;
this.matin.fin = matFin;
this.soir.debut = soirDeb;
this.soir.fin = soirFin;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Time } from '@angular/common';
import { Day } from '../models/day.model';
@Component({
selector: 'app-schedule',
templateUrl: './schedule.component.html',
styleUrls: ['./schedule.component.css']
})
export class ScheduleComponent implements OnInit {
start = this.convertStgToTime('7:00');
end = this.convertStgToTime('20:45');
rngOfDayMin = this.convInMin(this.end) - this.convInMin(this.start);
rangeOfDay = this.convInTime(this.rngOfDayMin);
day = new Day('8:30', '13:00', '15:30', '20:45');
morningShift = document.getElementById('mornShift');
afternoonShit = document.getElementById('afternShift');
daycont = document.getElementById('day')
constructor() { }
ngOnInit() {
console.log(this.day);
}
convInMin (time: Time): number {
return time.hours * 60 + time.minutes;
}
convInTime (entry: number): Time{
const result: Time = {hours : null, minutes : null};
const hours = Math.floor(entry / 60);
const minutes = Math.floor(((entry / 60) - hours) * 60);
result.hours = hours;
result.minutes = minutes;
return result;
}
convertStgToTime (text: string): Time {
const splitText = text.split(':');
return {
hours : parseInt(splitText[0], 10),
minutes: parseInt(splitText[1], 10)
};
}
settingBarLenght()
}
|
e2af92e73844d0d4165dfab5e97d72e16f900d43
|
[
"TypeScript"
] | 2
|
TypeScript
|
laviagicien/planning
|
a0c0186bfe262b8f9a2badfe98e4a3e1f176f009
|
a79dffeb67a73b77b0b68f44f01a5f50285cd9e3
|
refs/heads/master
|
<file_sep>namespace Desafio___Tetris.Model
{
public class Board
{
public static readonly int LineCount = 16;
public static readonly int ColumnCount = 10;
public RetanguloTabuleiro[][] Matrix { get; set; }
public Board()
{
}
}
}<file_sep>using Desafio___Tetris.Labels;
using System;
using System.Windows.Forms;
namespace Desafio___Tetris.View
{
internal class ScoreView
{
internal FormPanels FormPanels { get; set; }
private Panel _output { get; set; }
internal Panel Output
{
get => _output;
set
{
Control.ControlCollection collection = _output == null ? FormPanels.ScorePanel.Controls : _output.Controls;
int c = collection.Count;
for (int i = 0; i < c; i++)
{
//must be the 1st index as Controls are being deleted from collection while added to placeholder
value.Controls.Add(collection[0]);
}
_output = value;
}
}
private int _level { get; set; }
internal int Level
{
get => _level;
set
{
_level = value;
FormPanels.LevelLabel.Text = value.ToString();
FormPanels.LevelLabel.Refresh();
}
}
private int _pieceCounter { get; set; }
internal int PieceCounter
{
get => _pieceCounter;
set
{
_pieceCounter = value;
FormPanels.PieceCounterLabel.Text = value.ToString();
FormPanels.PieceCounterLabel.Refresh();
}
}
private int _points { get; set; }
internal int Points
{
get => _points;
set
{
_points = value;
FormPanels.ScoreLabel.Text = value.ToString();
FormPanels.ScoreLabel.Refresh();
}
}
private double _speed { get; set; }
internal double Speed
{
get => _speed;
set
{
_speed = value;
FormPanels.SpeedLabel.Text = string.Format(strings.ScoreView_Speed__0___lines_s_, Math.Round(1000 / value, 2));
FormPanels.SpeedLabel.Refresh();
}
}
internal ScoreView()
{
}
}
}<file_sep>using System.Drawing;
using System.Windows.Forms;
namespace Desafio___Tetris.Labels
{
internal sealed class LabelPause : Label
{
internal LabelPause()
{
Anchor = AnchorStyles.Bottom;
AutoSize = true;
BackColor = Color.Transparent;
Font = new Font("Webdings",
30F,
FontStyle.Regular,
GraphicsUnit.Point);
Name = "labelPause";
Size = new Size(87, 61);
TabIndex = 0;
Text = '<'.ToString();
TextAlign = ContentAlignment.MiddleCenter;
}
}
}<file_sep>using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.IO;
namespace Desafio___Tetris.Conexoes
{
public class ConexaoOleDb:AbsConexao
{
public override string PastaBase => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\"));
public override string Caminho => "Conexao\\conexao.udl";
public override DbConnection DbConnection { get; set; }
public override string ConnectionString { get => $"File Name={PastaBase}{Caminho}"; set => throw new NotImplementedException(); }
public override string Database => throw new NotImplementedException();
public override string DataSource => throw new NotImplementedException();
public override string ServerVersion => throw new NotImplementedException();
public override ConnectionState State => throw new NotImplementedException();
/*
public override DbConnection OpenDbConnection()
{
OleDbConnection oleDbConnection;
try
{
oleDbConnection = new OleDbConnection(ConnectionString);
oleDbConnection.Open();
}
catch (Exception ex)
{
throw new Exception("OleDBConnection - " + ex.ToString());
}
return oleDbConnection;
}
*/
public ConexaoOleDb()
{
DbConnection = new OleDbConnection();
DbConnection.Open();
}
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
throw new NotImplementedException();
}
public override void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
public override void Close()
{
throw new NotImplementedException();
}
protected override DbCommand CreateDbCommand()
{
throw new NotImplementedException();
}
public override void Open()
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Desafio___Tetris.Conexoes;
using Desafio___Tetris.Model;
namespace Desafio___Tetris.DAO
{
public class PontuacaoDaoOleDb:AbsPontuacaoDao
{
public PontuacaoDaoOleDb()
{
}
public override void Insert(Pontuacao p)
{
MemoryStream ms = new MemoryStream();
byte[] photoAray = new byte[ms.Length];
Conexao conexao = new Conexao();
p.Tabuleiro.Save(ms, ImageFormat.Jpeg);
ms.Position = 0;
ms.Read(photoAray, 0, photoAray.Length);
try
{
OleDbDataReader result;
DbConnection connection = conexao.DbConnection;
conexao.VerifyDbConnection();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Clear()
.AppendLine("USE TETRIS ")
.AppendLine("INSERT INTO ")
.AppendLine(" DBO.PONTUACAO ")
.AppendLine(" ( ")
.AppendLine(" NOME, ")
.AppendLine(" SCORE, ")
.AppendLine(" NIVEL, ")
.AppendLine(" TEMPO_JOGO, ")
.AppendLine(" QTD_PECAS, ")
.AppendLine(" DATA_SCORE, ")
.AppendLine(" TABULEIRO) ")
.AppendLine(" VALUES ")
.AppendLine(" (?, ")
.AppendLine(" ?, ")
.AppendLine(" ?, ")
.AppendLine(" ?, ")
.AppendLine(" ?, ")
.AppendLine(" ?, ")
.AppendLine(" ?); ");
using OleDbCommand command = (OleDbCommand)connection.CreateCommand();
command.CommandText = stringBuilder.ToString();
command.Parameters.AddWithValue("@NOME", p.Nome);
command.Parameters.AddWithValue("@SCORE", p.Score);
command.Parameters.AddWithValue("@NIVEL", p.Nivel);
command.Parameters.AddWithValue("@TEMPO_JOGO", p.TempoJogo);
command.Parameters.AddWithValue("@QTD_PECAS", p.QtdPecas);
command.Parameters.AddWithValue("@DATA_SCORE", p.DataScore);
command.Parameters.AddWithValue("@TABULEIRO", photoAray);
result = command.ExecuteReader();
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
finally
{
conexao.DbConnection.Close();
}
}
public override Pontuacao ImagemPorId(int id)
{
Conexao conexao = new Conexao();
try
{
DbConnection connection = conexao.DbConnection;
conexao.VerifyDbConnection();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Clear()
.AppendLine("USE TETRIS ")
.AppendLine("SELECT ")
.AppendLine(" NOME, ")
.AppendLine(" DATA_SCORE, ")
.AppendLine(" TABULEIRO ")
.AppendLine("FROM ")
.AppendLine(" DBO.PONTUACAO WITH(NOLOCK) ")
.AppendLine(" WHERE ")
.AppendLine(" ID = ? ");
using OleDbCommand command = (OleDbCommand)connection.CreateCommand();
command.CommandText = stringBuilder.ToString();
command.Parameters.AddWithValue("@ID", id);
OleDbDataReader result = command.ExecuteReader();
result.Read();
MemoryStream ms = new MemoryStream((byte[])result["TABULEIRO"]);
Pontuacao p = new Pontuacao
{
Id = id,
Nome = result["NOME"].ToString(),
DataScore = (DateTime)result["DATA_SCORE"],
Tabuleiro = new Bitmap(ms)
};
return p;
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
finally
{
conexao.DbConnection.Close();
}
}
public override List<Pontuacao> ListaTodos()
{
Conexao conexao = new Conexao();
List<Pontuacao> lp = new List<Pontuacao>();
try
{
DbConnection connection = conexao.DbConnection;
conexao.VerifyDbConnection();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Clear()
.AppendLine("USE TETRIS ")
.AppendLine("SELECT ")
.AppendLine(" ID, ")
.AppendLine(" NOME, ")
.AppendLine(" SCORE, ")
.AppendLine(" NIVEL, ")
.AppendLine(" TEMPO_JOGO, ")
.AppendLine(" QTD_PECAS, ")
.AppendLine(" DATA_SCORE, ")
.AppendLine(" TABULEIRO ")
.AppendLine("FROM ")
.AppendLine(" DBO.PONTUACAO WITH(NOLOCK) ")
.AppendLine(" ORDER BY ")
.AppendLine(" SCORE ")
.AppendLine(" DESC ");
using OleDbCommand command = (OleDbCommand)connection.CreateCommand();
command.CommandText = stringBuilder.ToString();
OleDbDataReader result = command.ExecuteReader();
while (result.Read())
{
MemoryStream ms = new MemoryStream((byte[])result["TABULEIRO"]);
Pontuacao p = new Pontuacao()
{
Id = (int)result["ID"],
Nome = result["NOME"].ToString(),
Score = (int)result["SCORE"],
Nivel = (int)result["NIVEL"],
TempoJogo = TimeSpan.Parse(result["TEMPO_JOGO"].ToString() ?? throw new InvalidOperationException()),
QtdPecas = (int)result["QTD_PECAS"],
DataScore = (DateTime)result["DATA_SCORE"],
Tabuleiro = new Bitmap(ms)
};
lp.Add(p);
}
return lp;
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
finally
{
conexao.DbConnection.Close();
}
}
public override List<Pontuacao> ListaTodosTlp()
{
Conexao conexao = new Conexao();
List<Pontuacao> lp = new List<Pontuacao>();
try
{
DbConnection connection = conexao.DbConnection;
conexao.VerifyDbConnection();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Clear()
.AppendLine("USE TETRIS ")
.AppendLine("SELECT ")
.AppendLine(" ID, ")
.AppendLine(" NOME, ")
.AppendLine(" SCORE, ")
.AppendLine(" NIVEL, ")
.AppendLine(" TEMPO_JOGO, ")
.AppendLine(" QTD_PECAS, ")
.AppendLine(" DATA_SCORE ")
.AppendLine("FROM ")
.AppendLine(" DBO.PONTUACAO WITH(NOLOCK) ")
.AppendLine(" ORDER BY ")
.AppendLine(" SCORE ")
.AppendLine(" DESC ");
using OleDbCommand command = (OleDbCommand)connection.CreateCommand();
command.CommandText = stringBuilder.ToString();
OleDbDataReader result = command.ExecuteReader();
while (result.Read())
{
Pontuacao p = new Pontuacao()
{
Id = (int)result["ID"],
Nome = result["NOME"].ToString(),
Score = (int)result["SCORE"],
Nivel = (int)result["NIVEL"],
TempoJogo = TimeSpan.Parse(result["TEMPO_JOGO"].ToString() ?? throw new InvalidOperationException()),
QtdPecas = (int)result["QTD_PECAS"],
DataScore = (DateTime)result["DATA_SCORE"],
};
lp.Add(p);
}
return lp;
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
finally
{
conexao.DbConnection.Close();
}
}
}
}
<file_sep>using Desafio___Tetris.Conexoes;
using Desafio___Tetris.View;
using System;
using System.Data.Common;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
using Desafio___Tetris.Labels;
namespace Desafio___Tetris
{
public partial class Form1 : Form
{
private Game Game { get; set; }
//private FormPontuacaoSelect Fs { get; set; }
private BoardView BoardView { get; set; }
private GameView GameView { get; set; }
private TimeView TimeView { get; set; }
private PieceView CurrentPieceView { get; set; }
private PieceView NextPieceView { get; set; }
private ScoreView ScoreView { get; set; }
public Form1()
{
InitializeComponent();
FormPanels formPanels = new();
if (formPanels == null) throw new ArgumentNullException(nameof(formPanels));
BoardView = new BoardView
{
Panel = panelTabuleiro
};
CurrentPieceView = new PieceView()
{
Panel = panelAtual
};
NextPieceView = new PieceView()
{
Panel = panelProx
};
ScoreView = new ScoreView
{
FormPanels = formPanels,
Output = scorePlaceHolderPanel
};
TimeView = new TimeView
{
FormPanels = formPanels,
Panel = pausePlaceHolderPanel
};
GameView = new GameView()
{
BoardView = BoardView,
TimeView = TimeView,
CurrentPieceView = CurrentPieceView,
NextPieceView = NextPieceView,
ScoreView = ScoreView,
TrackBar = trackBarNivel
};
}
private void Form1_Load(object sender, EventArgs e)
{
Conexao conexao = new Conexao();
DbConnection dbConnection = conexao.DbConnection;
conexao.VerifyDbConnection();
if (dbConnection != null)
{
buttonPontuacao.Visible = true;
FormPontuacaoTlp formPontuacaoTlp = new FormPontuacaoTlp
{
TopMost = true
};
formPontuacaoTlp.Show();
}
conexao.DbConnection.Close();
}
private void ButtonNJ_Click(object sender, EventArgs e)
{
Tetris();
}
private void ButtonPause_Click(object sender, EventArgs e)
{
GameView.Pause();
}
protected override bool ProcessDialogKey(Keys keyData)
{
switch (keyData)
{
case (Keys.Up):
labelKey.Text = char.ToString((char)0xe1);
GameView.RotacionaPeca();
break;
case (Keys.Down):
labelKey.Text = char.ToString((char)0xe2);
GameView.MoveAbaixo();
break;
case (Keys.Left):
labelKey.Text = char.ToString((char)0xdf);
GameView.MoveEsquerda();
break;
case (Keys.Right):
labelKey.Text = char.ToString((char)0xe0);
GameView.MoveDireita();
break;
};
// return the key to the base class if not used.
//return base.ProcessDialogKey(keyData);
return true;
}
public void Tetris()
{
buttonPause.Enabled = true;
trackBarNivel.Enabled = false;
GameView.Start();
MessageBox.Show(strings.Form1_Tetris_Game_Over);
SalvaPontuacao();
buttonPause.Enabled = false;
trackBarNivel.Enabled = true;
}
private void SalvaPontuacao()
{
FormPontuacaoInsert fp = new FormPontuacaoInsert(GameView);
Conexao conexao = new Conexao();
DbConnection dbConnection = conexao.DbConnection;
conexao.VerifyDbConnection();
if (dbConnection != null)
{
fp.ShowDialog();
}
conexao.DbConnection.Close();
}
private void ButtonTGD_Click(object sender, EventArgs e)
{
MessageBox.Show("https://github.com/tiago-ifrs/Desafio---Tetris" +
"\n" +
"<EMAIL>",
"Tetris 21");
}
private void ButtonPrint_Click(object sender, EventArgs e)
{
string minhasImagens = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
SaveFileDialog sfd = new SaveFileDialog();
ImageFormat formato = ImageFormat.Jpeg;
Bitmap captureBitmap = new Bitmap(panelTabuleiro.Width, panelTabuleiro.Height);
Rectangle captureRectangle = new Rectangle(0, 0, panelTabuleiro.Width, panelTabuleiro.Height);
panelTabuleiro.DrawToBitmap(captureBitmap, captureRectangle);
sfd.Filter = "Imagens|*.png;*.bmp;*.jpg";
sfd.InitialDirectory = minhasImagens;
sfd.DefaultExt = "*.jpg";
if (sfd.ShowDialog() != DialogResult.OK) return;
string ext = Path.GetExtension(sfd.FileName)?.ToLower();
switch (ext)
{
case ".jpg":
formato = ImageFormat.Jpeg;
break;
case ".bmp":
formato = ImageFormat.Bmp;
break;
case ".png":
formato = ImageFormat.Png;
break;
}
captureBitmap.Save(sfd.FileName ?? throw new InvalidOperationException(), formato);
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (Game.Time.Paused)
{
Game.Time.Paused = false;
Game.Over = true;
}
Application.Exit();
}
private void ButtonPontuacao_Click(object sender, EventArgs e)
{
FormPontuacaoTlp formPontuacaoTlp = new FormPontuacaoTlp
{
TopMost = true
};
formPontuacaoTlp.Show();
}
private void TrackBarNivel_ValueChanged(object sender, EventArgs e)
{
labelTBNivel.Text = trackBarNivel.Value.ToString();
}
}
}<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.Model.Pecas;
namespace Desafio___Tetris
{
/// <summary>
/// class Game must be public because of insertion
/// </summary>
public class Game
{
internal Time Time { get; set; }
internal Piece CurrentPiece { get; set; }
internal Piece NextPiece { get; set; }
internal Score Score { get; set; }
internal Board Board{ get; set; }
internal bool Over { get; set; }
internal int StartLevel
{
get => Score.StartLevel;
init => Score.StartLevel = value;
}
internal Game()
{
Time = new Time
{
Paused = false
};
this.Board = new Board();
this.Score = new Score();
this.Over = false;
//this.CurrentPiece = new Piece();
this.CurrentPiece = null;
this.NextPiece = null;
}
}
}
<file_sep>using System.Drawing;
using System.Windows.Forms;
namespace Desafio___Tetris.Labels
{
internal class FormPanels : FormLabels
{
public Panel ScorePanel { get; set; }
public FormPanels()
{
ScorePanel = new Panel();
ScorePanel.ResumeLayout(false);
ScorePanel.PerformLayout();
ScorePanel.Controls.Add(ScoreCaptionLabel);
ScorePanel.Controls.Add(ScoreLabel);
ScorePanel.Controls.Add(PieceCounterCaptionLabel);
ScorePanel.Controls.Add(GameTimerLabel);
ScorePanel.Controls.Add(LevelCaptionLabel);
ScorePanel.Controls.Add(GameTimerCaptionLabel);
ScorePanel.Controls.Add(PieceCounterLabel);
ScorePanel.Controls.Add(LevelLabel);
ScorePanel.Controls.Add(SpeedCaptionLabel);
ScorePanel.Controls.Add(SpeedLabel);
ScorePanel.Location = new Point(748, 13);
ScorePanel.Name = "ScorePanel";
ScorePanel.Size = new Size(242, 198);
ScorePanel.TabIndex = 24;
ScorePanel.SuspendLayout();
}
}
}
<file_sep>using System.Collections.Generic;
using System.Drawing;
namespace Desafio___Tetris.Model.Pecas
{
public class J : PieceAbstract
{
private int _rot;
public J()
{
Rot = 0;
}
public override Color Cor => Color.Gold;
public override List<int[]> Linhas { get; set; }
public sealed override int Rot
{
get => _rot;
set
{
_rot = value;
switch (value)
{
case 0:
this.Linhas = new List<int[]>{
new int[]{ 0,1 },
new int[]{ 0,1 },
new int[]{ 1,1 }
};
break;
case 1:
this.Linhas = new List<int[]>{
new int[]{ 1,1,1 },
new int[]{ 0,0,1 },
};
break;
case 2:
this.Linhas = new List<int[]>{
new int[]{ 1,1 },
new int[]{ 1,0 },
new int[]{ 1,0 }
};
break;
case 3:
this.Linhas = new List<int[]>{
new int[]{ 1,0,0 },
new int[]{ 1,1,1 },
};
break;
}
}
}
}
}
<file_sep>using Desafio___Tetris.Model;
using System.Drawing;
using System.Windows.Forms;
namespace Desafio___Tetris.View
{
internal class PieceView
{
internal Panel Panel { get; set; }
private Piece _piece { get; set; }
internal int Width { get; set; }
internal int Height { get; set; }
public Piece Piece
{
get => _piece;
set
{
_piece = value;
if (value != null)
{
//cria os quadradinhos redimensionados conforme o tamanho da peça
this.ColumnCount = Piece.ColumnCount(Piece.LineCount - 1);
//int width = Panel.Width / ColumnCount;
//int height = Panel.Height / Piece.LineCount;
RetanguloTabuleiro[][] rt = new RetanguloTabuleiro[Piece.LineCount][];
Panel.Controls.Clear();
for (int i = 0; i < Piece.LineCount; i++)
{
rt[i] = new RetanguloTabuleiro[ColumnCount];
for (int j = 0; j < ColumnCount; j++)
{
rt[i][j] = new RetanguloTabuleiro();
rt[i][j].Location = new Point(j * (Width), i * (Height));
rt[i][j].Size = new Size(Width - 1, Height - 1);
rt[i][j].BackColor = Piece.CorPonto(i, j);
Panel.Controls.Add(rt[i][j]);
}
}
Panel.Size = new Size(Width * ColumnCount, Height * Piece.LineCount);
}
//this.AtualizaPeca();
}
}
private Size Size { get; set; }
/*
private Tabuleiro _tabuleiro { get; set; }
public Tabuleiro Tabuleiro
{
get => _tabuleiro;
set
{
_tabuleiro = value;
if (value != null)
{
//altura e largura do 1º quadradinho do tabuleiro:
this.Height = Tabuleiro.Matrix[0][0].Height;
this.Width = Tabuleiro.Matrix[0][0].Width;
}
}
}
private Panel _panel { get; set; }
public Panel Panel //ap = atual ou proximo
{
get => _panel;
set
{
_panel = value;
//Inicializa(value, Piece.LineCount, ColumnCount, Height, Width);
}
}
*/
private int ColumnCount { get; set; }
public PieceView()
{
}
public void Inicializa(Panel pai, int qy, int qx, int alt, int larg)
{
}
public void AtualizaPeca(Panel panel)
{
panel.Controls.Clear();
var nova = new RetanguloTabuleiro[Piece.LineCount][];
for (int i = 0; i < Piece.LineCount; i++)
{
nova[i] = new RetanguloTabuleiro[Piece.ColumnCount(Piece.LineCount - 1)];
for (int j = 0; j < Piece.ColumnCount(Piece.LineCount - 1); j++)
{
int xform = j * Size.Width;
int yform = i * Size.Height;
nova[i][j] = new RetanguloTabuleiro
{
Size = this.Size,
Location = new Point(xform, yform),
Valor = Piece.Ponto(i, j),
BorderStyle = BorderStyle.FixedSingle,
BackColor = Piece.CorPonto(i, j)
};
panel.Controls.Add(nova[i][j]);
}
}
panel.Size = new Size(panel.Controls[0].Width * Piece.ColumnCount(Piece.LineCount - 1), panel.Controls[0].Height * Piece.LineCount);
}
}
}
<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.Model.Pecas;
namespace Desafio___Tetris.Colisao
{
public sealed class ColisaoY : AbsColisao
{
public ColisaoY(Board tabuleiro, Piece peca, int yorig, int ydest, int xdest)
{
Peca = peca;
Tabuleiro = tabuleiro;
Ydest = ydest;
Xdest = xdest;
Ycoli = -1;
Xcoli = -1;
this.Detecta();
}
public override void Detecta()
{
int ul = Peca.LineCount - 1;
int uc = Peca.ColumnCount(ul);
for (int ypec = 0; ypec <= ul && (Ydest - ypec) >= 0; ypec++)
{
for (int xpec = 0; xpec < uc; xpec++)
{
if ((Tabuleiro.Matrix[Ydest - ypec][Xdest + xpec].Valor & Peca.Ponto(ul - ypec, xpec)) == 0)
{
if (Peca.Ponto(ul - ypec, xpec) == 1)
{
/*TESTE*/
//Matrix[Ydest - ypec][xtab + xpec].Valor = 0;
//Tabuleiro.Matrix[Ydest - ypec][Xdest + xpec].BackColor = Color.Transparent;
//Tabuleiro.Matrix[Ydest - ypec][Xdest + xpec].Refresh();
}
}
else //houve colisão
{
/*TESTE*/
//Matrix[Ydest - ypec][xtab + xpec].Valor = 0;
//Tabuleiro.Matrix[Ydest - ypec][Xdest + xpec].BackColor = Color.Black;
//Tabuleiro.Matrix[Ydest - ypec][Xdest + xpec].Refresh();
Ycoli = Ydest - ypec;
Xcoli = Xdest + xpec;
//return this;
Colisao = this;
return;
//return true;
}
}
}
//não houve colisão
Colisao = this;
return;
}
public override AbsColisao Colisao { get; set; }
public override int Ycoli { get; set; }
public override int Xcoli { get; set; }
public override Board Tabuleiro { get; set; }
public override Piece Peca { get; set; }
public override int Ydest { get; set; }
public override int Xdest { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Desafio___Tetris.DAO;
using Desafio___Tetris.Model;
namespace Desafio___Tetris
{
public partial class FormPontuacaoSelect : Form
{
public FormPontuacaoSelect()
{
InitializeComponent();
}
private void FormScore_Load(object sender, EventArgs e)
{
AbsPontuacaoDao pd = new PontuacaoDao().AbsPontuacaoDao;
List<Pontuacao> lp = pd.ListaTodos();
bSPontuacao.DataSource = lp;
dataGridView1.DataSource = bSPontuacao;
}
}
}
<file_sep>using System.Collections.Generic;
using Desafio___Tetris.Model;
namespace Desafio___Tetris.DAO
{
public abstract class AbsPontuacaoDao
{
public AbsPontuacaoDao()
{
}
public abstract void Insert(Pontuacao p);
public abstract Pontuacao ImagemPorId(int id);
public abstract List<Pontuacao> ListaTodos();
public abstract List<Pontuacao> ListaTodosTlp();
}
}
<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.View;
namespace Desafio___Tetris.Presenter
{
internal class PiecePresenter
{
private Piece _piece { get; set; }
public Piece Piece
{
get => _piece;
set
{
_piece = value;
if (PieceView != null)
{
PieceView.Piece = value;
}
}
}
private PieceView _PieceView { get; set; }
public PieceView PieceView
{
get => _PieceView;
set
{
_PieceView=value;
value.Width = this.Width;
value.Height = this.Height;
}
}
public int Height { get; set; }
public int Width { get; set; }
public PiecePresenter()
{
}
}
}<file_sep>using System;
using System.Configuration;
namespace Desafio___Tetris.DAO
{
public class PontuacaoDao
{
public AbsPontuacaoDao AbsPontuacaoDao { get; set; }
public PontuacaoDao()
{
string dbt = this.GetType().ToString()+
ConfigurationManager.AppSettings.Get("DbType");
AbsPontuacaoDao = Activator.CreateInstance(Type.GetType(dbt) ?? throw new InvalidOperationException()) as AbsPontuacaoDao;
}
}
}
<file_sep>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Desafio___Tetris
{
class Validador
{
public static IEnumerable<ValidationResult> GValidationResults(object obj)
{
List<ValidationResult> validationResults = new List<ValidationResult>();
ValidationContext context = new ValidationContext(obj, null, null);
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(obj, context, validationResults,
true);
return validationResults;
}
}
}
<file_sep>using System.Windows.Forms;
namespace Desafio___Tetris.View
{
public class BoardView
{
public Panel Panel { get; set; }
public BoardView()
{
}
}
}
<file_sep>using System.Collections.Generic;
using System.Drawing;
namespace Desafio___Tetris.Model.Pecas
{
public abstract class PieceAbstract
{
public abstract Color Cor { get; }
public abstract int Rot { get; set; }
public abstract List<int[]> Linhas { get; set; }
public PieceAbstract()
{
}
}
}
<file_sep>using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace Desafio___Tetris.Model
{
internal class Time
{
internal bool Paused { get; set; }
internal Stopwatch Stopwatch { get; set; }
internal Timer Timer { get; set; }
internal TimeSpan TimeSpan { get; set; }
/// <summary>
/// Wait
/// CA1822: Mark members as static
/// </summary>
/// <param name="ms">Time in milliseconds</param>
internal static void Wait(int ms)
{
DateTime start = DateTime.Now;
while ((DateTime.Now - start).TotalMilliseconds < ms)
Application.DoEvents();
}
internal void Start()
{
Stopwatch.Start();
Timer.Start();
}
internal void Stop()
{
Stopwatch.Stop();
Timer.Stop();
}
internal void Pause(bool paused)
{
Paused = paused;
while (Paused)
{
Wait(1000);
}
}
internal Time()
{
Timer = new Timer();
Stopwatch = new Stopwatch();
}
}
}<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.View;
namespace Desafio___Tetris.Presenter
{
internal class ScorePresenter
{
internal Score Score { get; init; }
internal int Points
{
get => Score.Points;
set
{
Score.Points = value;
ScoreView.Points = value;
}
}
internal int Level
{
get => Score.Level;
set
{
Score.Level = value;
ScoreView.Level = value;
}
}
internal double Speed
{
get => Score.Speed;
set
{
Score.Speed = value;
ScoreView.Speed = value;
}
}
internal int PieceCounter
{
get => Score.PieceCounter;
set
{
Score.PieceCounter = value;
ScoreView.PieceCounter = value;
}
}
private ScoreView _ScoreView { get; init; }
internal ScoreView ScoreView
{
get => _ScoreView;
init
{
_ScoreView = value;
///initialize ScoreView
ScoreView.Level = Score.Level;
ScoreView.Points = Score.Points;
ScoreView.Speed = Score.Speed;
}
}
internal ScorePresenter()
{
}
}
}
<file_sep>using System.Collections.Generic;
using System.Drawing;
namespace Desafio___Tetris.Model.Pecas
{
public class O : PieceAbstract
{
public O()
{
this.Linhas = new List<int[]>
{
new int[] { 1,1 },
new int[] { 1,1 }
};
}
public override Color Cor => Color.DarkOrange;
public override int Rot { get; set; }
public sealed override List<int[]> Linhas { get; set; }
}
}
<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.Model.Pecas;
namespace Desafio___Tetris.Colisao
{
public abstract class AbsColisao
{
public abstract AbsColisao Colisao { get; set; }
public abstract int Ycoli { get; set; }
public abstract int Xcoli { get; set; }
public abstract Board Tabuleiro { get; set; }
public abstract Piece Peca { get; set; }
public abstract int Ydest { get; set; }
public abstract int Xdest { get; set; }
public abstract void Detecta();
}
}
<file_sep>using System;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
namespace Desafio___Tetris.Model
{
public class Pontuacao
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Nome não pode ser nulo"), Display(Name = "Digite seu nome")]
public string Nome { get; set; }
[Required]
public int Score { get; set; }
[Required]
public int Nivel { get; set; }
[Required]
public TimeSpan TempoJogo { get; set; }
[Required]
public int QtdPecas { get; set; }
[Required]
public DateTime DataScore { get; set; }
[Required]
public Bitmap Tabuleiro { get; set; }
public Pontuacao()
{
}
}
}
<file_sep>using System;
using System.Windows.Forms;
namespace Desafio___Tetris.Labels
{
internal class FormLabels
{
internal Label GameTimerCaptionLabel { get; set; }
internal Label GameTimerLabel { get; set; }
internal Label LevelCaptionLabel { get; set; }
internal Label LevelLabel { get; set; }
internal Label PieceCounterCaptionLabel { get; set; }
internal Label PieceCounterLabel { get; set; }
internal Label ScoreCaptionLabel { get; set; }
internal Label ScoreLabel { get; set; }
internal Label SpeedCaptionLabel { get; set; }
internal Label SpeedLabel { get; set; }
internal FormLabels()
{
GameTimerCaptionLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(4, 100),
Name = "gameTimerCaptionLabel",
Size = new System.Drawing.Size(135, 25),
TabIndex = 18,
Text = strings.FormLabels_FormLabels_Elapsed_Time
};
GameTimerLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(145, 100),
Name = "gameTimerLabel",
Size = new System.Drawing.Size(22, 25),
TabIndex = 19,
Text = TimeSpan.Zero.ToString()
};
LevelCaptionLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(4, 25),
Name = "levelCaptionLabel",
Size = new System.Drawing.Size(51, 25),
TabIndex = 14,
Text = strings.FormLabels_FormLabels_Level
};
LevelLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(61, 25),
Name = "levelLabel",
Size = new System.Drawing.Size(22, 25),
TabIndex = 15,
Text = 0.ToString()
};
PieceCounterCaptionLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(4, 75),
Name = "pieceCounterCaptionLabel",
Size = new System.Drawing.Size(55, 25),
TabIndex = 21,
Text = strings.FormLabels_FormLabels_Pieces
};
PieceCounterLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(65, 75),
Name = "pieceCounterLabel",
Size = new System.Drawing.Size(22, 25),
TabIndex = 22,
Text = 0.ToString()
};
ScoreCaptionLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(3, 0),
Name = "scoreCaptionLabel",
Size = new System.Drawing.Size(56, 25),
TabIndex = 11,
Text = strings.FormLabels_FormLabels_Score
};
ScoreLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(65, 0),
Name = "scoreLabel",
Size = new System.Drawing.Size(22, 25),
TabIndex = 12,
Text = 0.ToString()
};
SpeedCaptionLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(4, 50),
Name = "speedCaptionLabel",
Size = new System.Drawing.Size(98, 25),
TabIndex = 16,
Text = strings.FormLabels_FormLabels_Speed
};
SpeedLabel = new Label
{
AutoSize = true,
Location = new System.Drawing.Point(108, 50),
Name = "speedLabel",
Size = new System.Drawing.Size(22, 25),
TabIndex = 17,
Text = 0.ToString()
};
}
}
}
<file_sep>using System.Windows.Forms;
using Desafio___Tetris.Presenter;
namespace Desafio___Tetris.View
{
/// <summary>
/// GameView
/// Must be public because it's referenced in 2 different forms
/// </summary>
public class GameView
{
internal GamePresenter GamePresenter { get; set; }
internal TimePresenter TimePresenter { get; set; }
internal TrackBar TrackBar { get; init; }
internal BoardView BoardView { get; init; }
internal TimeView TimeView { get; init; }
internal ScoreView ScoreView { get; init; }
internal PieceView CurrentPieceView { get; init; }
internal PieceView NextPieceView { get; init; }
internal void Start()
{
GamePresenter = new GamePresenter
{
GameView = this
};
}
internal void Pause()
{
TimePresenter.Pause();
}
internal void RotacionaPeca()
{
GamePresenter.RotacionaPeca();
}
internal void MoveAbaixo()
{
GamePresenter.MoveAbaixo();
}
internal void MoveEsquerda()
{
GamePresenter.MoveEsquerda();
}
internal void MoveDireita()
{
GamePresenter.MoveDireita();
}
internal GameView()
{
}
}
}<file_sep>using System.Data.Common;
namespace Desafio___Tetris.Conexoes
{
public abstract class AbsConexao : DbConnection
{
public abstract string PastaBase { get; }
public abstract string Caminho { get;}
public abstract DbConnection DbConnection { get; set; }
//public abstract string ConnectionString { get; }
//public abstract DbConnection OpenDbConnection();
}
}
<file_sep>using Desafio___Tetris.Colisao;
using Desafio___Tetris.Model;
using Desafio___Tetris.Model.Pecas;
using Desafio___Tetris.View;
using System.Collections.Generic;
using System.Threading;
namespace Desafio___Tetris.Presenter
{
internal class GamePresenter
{
private int Ytab { get; set; } // coordenada y do tabuleiro
private int Xtab { get; set; } // coordenada x do tabuleiro
private int Yoffset { get; set; }
public bool Over { get; set; }
private BoardPresenter BoardPresenter { get; set; }
public GameView _GameView { get; set; }
public GameView GameView
{
get => _GameView;
set
{
_GameView = value;
this.Game = new Game
{
//GamePresenter = this,
StartLevel = _GameView.TrackBar.Value
};
BoardPresenter = new BoardPresenter
{
Board = Game.Board,
BoardView = GameView.BoardView
};
BoardPresenter.Inicia();
ScorePresenter = new ScorePresenter
{
Score = Game.Score, //Score must be set first
ScoreView = GameView.ScoreView
};
TimePresenter = new TimePresenter
{
TimeView = GameView.TimeView, //TimeView must be set first
Time = Game.Time
};
GameView.GamePresenter = this;
GameView.TimePresenter = TimePresenter;
CurrentPiecePresenter = new PiecePresenter
{
Width = BoardPresenter.Width,
Height = BoardPresenter.Height,
Piece = Game.CurrentPiece,
PieceView = GameView.CurrentPieceView
};
NextPiecePresenter = new PiecePresenter
{
Width = BoardPresenter.Width,
Height = BoardPresenter.Height,
Piece = Game.NextPiece,
PieceView = GameView.NextPieceView
};
while (!Over)
{
Percorre();
}
}
}
private TimePresenter TimePresenter { get; set; }
private PiecePresenter CurrentPiecePresenter { get; set; }
private PiecePresenter NextPiecePresenter { get; set; }
private ScorePresenter ScorePresenter { get; set; }
internal Game Game { get; set; }
internal GamePresenter()
{
}
public void RotacionaPeca()
{
int ulAnt = CurrentPiecePresenter.Piece.LineCount - 1;
int ucAnt = CurrentPiecePresenter.Piece.ColumnCount(ulAnt);
int rotAnt = CurrentPiecePresenter.Piece.Rot;
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab); // precisa limpar o espaço da peça antes de rotacionar
if (CurrentPiecePresenter.Piece.Rot < 4)
{
CurrentPiecePresenter.Piece.Rot++;
}
else
{
CurrentPiecePresenter.Piece.Rot = 0;
}
/*
* DETECTAR COLISÃO HORIZONTAL ANTES DE DESENHAR
* AS COLISÕES PODEM ACONTECEM NO LADO DIREITO, POIS XTAB É O PONTO DE ORIGEM DO DESENHO DA PEÇA
*/
int ulPos = CurrentPiecePresenter.Piece.LineCount - 1;
int ucPos = CurrentPiecePresenter.Piece.ColumnCount(ulPos);
if (Xtab + ucPos >= Board.ColumnCount)
{
//Direita = new ColisaoX(Tabuleiro, At, Ytab + Yoffset, Xtab, Xtab - ucPos - ucAnt); //detectar colisão uma linha abaixo?
ColisaoX direita = new ColisaoX(BoardPresenter.Board, CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab, Xtab - ucPos + ucAnt);
if (direita.Xcoli == -1)//não houve colisão
{
//mantém a rotação
//move a peça para a esquerda
Xtab -= ucPos - ucAnt;
}
else
{
CurrentPiecePresenter.Piece.Rot = rotAnt; //recupera a rotação anterior, impedindo o movimento
}
}
/* DESENHA QUALQUER UMA DAS DUAS */
BoardPresenter.DesenhaY(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
}
public void MoveAbaixo()
{
if ((Ytab + Yoffset) < Board.LineCount - 1)
{
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
ColisaoY baixo = new ColisaoY(BoardPresenter.Board, CurrentPiecePresenter.Piece, Ytab + Yoffset, Ytab + Yoffset + 1, Xtab);
if (baixo.Ycoli == -1)//não houve colisão
{
Yoffset++;
}
BoardPresenter.DesenhaY(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
}
}
public void MoveEsquerda()
{
if (Xtab > 0)
{
/* Colisão X não vai limpar a peça
* precisa limpar para fazer o teste
*/
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
ColisaoX esquerda = new ColisaoX(BoardPresenter.Board, CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab, Xtab - 1);
if (esquerda.Xcoli == -1)//não houve colisão
{
Xtab--;
}
BoardPresenter.DesenhaY(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
}
}
public void MoveDireita()
{
int ul = CurrentPiecePresenter.Piece.LineCount - 1;
int uc = CurrentPiecePresenter.Piece.ColumnCount(ul);
if (Xtab + uc < Board.ColumnCount)
{
/* Colisão X não vai limpar a peça
* precisa limpar para fazer o teste
*/
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
ColisaoX direita = new ColisaoX(BoardPresenter.Board, CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab, Xtab + uc);
if (direita.Xcoli == -1)//não houve colisão
{
Xtab++;
}
BoardPresenter.DesenhaY(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
}
}
private void GeraProx()
{
CurrentPiecePresenter.Piece ??= new Piece();
if (NextPiecePresenter.Piece != null)
{
//NextPiece.Ap = panelAtual;
CurrentPiecePresenter.Piece = NextPiecePresenter.Piece;
//CurrentPiece.AtualizaPeca();
}
NextPiecePresenter.Piece = new Piece();
}
public void Percorre()
{
GeraProx();
//condições iniciais:
Yoffset = 0;
Xtab = (Board.ColumnCount - CurrentPiecePresenter.Piece.ColumnCount(CurrentPiecePresenter.Piece.LineCount - 1)) / 2; // Centraliza a peça
Atualiza();
ScorePresenter.PieceCounter++;
for (Ytab = 0; ((Ytab + Yoffset) < Board.LineCount) && !Over; Ytab++) // percorre as linhas do tabuleiro. precisa testar a colisão a cada entrada no loop
{
/*
* NO LOOP PRINCIPAL, O PONTO DE COLISÃO É O PRÓPRIO PONTO A SER DESENHADO
* NO CASO DE SETA ABAIXO, O YTAB FOI INCREMENTADO FORA DO LOOP
*
* CASO DO LOOP FOR:
* PEÇA JÁ ESTÁ DESENHADA NA LINHA ANTERIOR, PODE IR PARA A ATUAL?
*/
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab - 1 + Yoffset, Xtab); //precisa limpar A ANTERIOR para fazer o teste
ColisaoY colisaoY = new ColisaoY(BoardPresenter.Board, CurrentPiecePresenter.Piece, Ytab + Yoffset, Ytab + Yoffset, Xtab);
if (colisaoY.Ycoli == -1)//não houve colisão
{
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab + Yoffset - 1, Xtab);
BoardPresenter.DesenhaY(CurrentPiecePresenter.Piece, Ytab + Yoffset, Xtab);
}
else
{
BoardPresenter.LimpaPeca(CurrentPiecePresenter.Piece, Ytab + Yoffset - 1, Xtab);
BoardPresenter.DesenhaY(CurrentPiecePresenter.Piece, Ytab + Yoffset - 1, Xtab);
if (colisaoY.Ycoli < CurrentPiecePresenter.Piece.LineCount - 1)
{
this.Over = true;
TimePresenter.Over();
}
break;
}
Time.Wait((int)ScorePresenter.Speed);
}
//return false;
}
public void Atualiza()
{
List<int> indices = new List<int>();
List<List<int>> vetlin = new List<List<int>>();
for (int j = 0; j < Board.LineCount; j++)
{
List<int> vetcol = new List<int>();
for (int i = 0; i < Board.ColumnCount; i++)
{
vetcol.Add(BoardPresenter.Board.Matrix[j][i].Valor);
}
vetlin.Add(vetcol);
if (!vetlin[j].Contains(0))
{
indices.Add(j);
}
}
foreach (int t in indices)
{
BoardPresenter.Deleta(t);
ScorePresenter.Points += 10;
//ScoreView.Score = Score.Points;
Thread.Sleep((int)Score.Times[ScorePresenter.Level]);
}
if (indices.Count > 0)
{
ScorePresenter.Level = Game.StartLevel + ((int)ScorePresenter.Points / 100);
if (ScorePresenter.Level < Score.Times.Length)
{
ScorePresenter.Speed = Score.Times[ScorePresenter.Level];
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;
using Desafio___Tetris.DAO;
using Desafio___Tetris.Model;
using Desafio___Tetris.View;
namespace Desafio___Tetris
{
public partial class FormPontuacaoInsert : Form
{
private Bitmap CaptureBitmap { get; }
private Game Game { get; }
private Panel Panel { get; set; }
private BoardView BoardView { get; }
private ScoreView ScoreView { get; }
public FormPontuacaoInsert(GameView gameView)
{
BoardView = gameView.BoardView;
Game = gameView.GamePresenter.Game;
ScoreView = gameView.ScoreView;
CaptureBitmap = new Bitmap(BoardView.Panel.Width, BoardView.Panel.Height);
InitializeComponent();
}
private void ButtonOK_Click(object sender, EventArgs e)
{
Pontuacao po = new()
{
Nome = textBoxNome.Text,
Score = Game.Score.Points,
Nivel = Game.Score.Level,
QtdPecas = Game.Score.PieceCounter,
TempoJogo = Game.Time.TimeSpan,
DataScore = DateTime.Now,
Tabuleiro = CaptureBitmap
};
IEnumerable<ValidationResult> results = Validador.GValidationResults(po);
string s = string.Empty;
foreach (ValidationResult variable in results)
{
s += variable.ErrorMessage + '\n';
}
if (results.Any()) //existem erros de validação
{
MessageBox.Show(s);
}
else
{
AbsPontuacaoDao pd = new PontuacaoDao().AbsPontuacaoDao;
pd.Insert(po);
Close();
}
}
private void FormPontuacaoInsert_Load(object sender, EventArgs e)
{
Bitmap bitmapPictureBoxImage = new Bitmap(pictureBoxTabuleiro.Width, pictureBoxTabuleiro.Height);
Rectangle captureRectangle = new Rectangle(0, 0, BoardView.Panel.Width, BoardView.Panel.Height);
BoardView.Panel.DrawToBitmap(CaptureBitmap, captureRectangle);
Graphics g = Graphics.FromImage(bitmapPictureBoxImage);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(CaptureBitmap, 0, 0, pictureBoxTabuleiro.Width, pictureBoxTabuleiro.Height);
pictureBoxTabuleiro.Image = bitmapPictureBoxImage;
Panel = ScoreView.Output;
ScoreView.Output = panelPlacarInsert;
}
private void FormPontuacaoInsert_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void FormPontuacaoInsert_Validated(object sender, EventArgs e)
{
}
private void FormPontuacaoInsert_FormClosed(object sender, FormClosedEventArgs e)
{
ScoreView.Output = Panel;
}
}
}<file_sep>using System.Drawing;
using System.Windows.Forms;
namespace Desafio___Tetris
{
public sealed class RetanguloTabuleiro : Panel
{
public int Valor { get; set; }
public RetanguloTabuleiro()
{
Valor = 0;
//BackColor = Color.White;
}
}
}<file_sep>using Desafio___Tetris.Labels;
using System;
using System.Windows.Forms;
namespace Desafio___Tetris.View
{
internal class TimeView
{
internal FormPanels FormPanels { get; init; }
private LabelPause LabelPause { get; }
private Panel _panel { get; init; }
internal Panel Panel
{
get => _panel;
init
{
_panel = value;
Panel.Controls.Add(LabelPause);
}
}
private TimeSpan _timeSpan { get; set; }
internal TimeSpan TimeSpan
{
get => _timeSpan;
set
{
_timeSpan = value;
FormPanels.GameTimerLabel.Text = $@"{value.Hours:00}:{value.Minutes:00}:{value.Seconds:00}";
FormPanels.GameTimerLabel.Refresh();
}
}
internal void Play()
{
LabelPause.Text = char.ToString((char)0x34);
LabelPause.Refresh();
}
internal void Pause()
{
LabelPause.Text = char.ToString((char)0x3b);
LabelPause.Refresh();
}
internal void Over()
{
LabelPause.Text = char.ToString((char)0x3c);
LabelPause.Refresh();
}
internal TimeView()
{
LabelPause = new LabelPause();
}
}
}<file_sep>using System;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using Desafio___Tetris.DAO;
using Desafio___Tetris.Model;
namespace Desafio___Tetris
{
public sealed class LabelNome : Label
{
public int Id { get; set; }
public LabelNome(int id)
{
this.Id = id;
this.ForeColor = Color.Blue;
Font = new Font(this.Font, FontStyle.Underline);
Click += new EventHandler(NomePopup);
MouseHover += new EventHandler(CursorEvento);
}
private void CursorEvento(object sender, EventArgs e)
{
((Control) this).Cursor = Cursors.Hand;
}
private void NomePopup(object sender, EventArgs e)
{
Pontuacao p;
AbsPontuacaoDao pd = new PontuacaoDao().AbsPontuacaoDao;
p = pd.ImagemPorId(Id);
PictureBox pictureBox = new PictureBox
{
AutoSize = true,
Image = p.Tabuleiro
};
Form form = new Form
{
AutoSize = true,
Text = p.Nome + " em " + p.DataScore.ToString(CultureInfo.CurrentCulture),
TopMost = true
};
form.Controls.Add(pictureBox);
form.ShowDialog();
}
}
}
<file_sep>using System;
using System.Configuration;
using System.Data;
using System.Data.Common;
namespace Desafio___Tetris.Conexoes
{
public class Conexao
{
private AbsConexao AbsConexao { get; set; }
public DbConnection DbConnection { get; set; }
public Conexao()
{
string dbt = this.GetType().ToString() +
ConfigurationManager.AppSettings.Get("DbType");
AbsConexao = (AbsConexao)Activator.CreateInstance(Type.GetType(dbt) ?? throw new InvalidOperationException());
DbConnection = AbsConexao.DbConnection;
}
/*
public DbConnection Abre()
{
DbConnection = OpenDbConnection();
return DbConnection;
}
*/
public void VerifyDbConnection()
{
if (DbConnection == null)
{
throw new Exception(" VerifyDBConnection - is null ");
}
if (DbConnection.State != ConnectionState.Open)
{
throw new Exception(" VerifyDBConnection - connection state is " + DbConnection.State.ToString());
}
}
}
}
<file_sep>using System;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.IO;
namespace Desafio___Tetris.Conexoes
{
public class ConexaoSqLite : AbsConexao
{
public override string PastaBase => Path.GetFullPath(AppContext.BaseDirectory);
public override string Caminho => $"{Database}.db";
public override string ConnectionString { get => $"Data Source={DataSource}"; set => throw new NotImplementedException(); }
public override string Database => "tetris";
public override string DataSource => $"{PastaBase}{Caminho}";
public override string ServerVersion => throw new NotImplementedException();
public override ConnectionState State => DbConnection.State;
public override DbConnection DbConnection { get; set; }
public ConexaoSqLite()
{
DbConnection = new SQLiteConnection(ConnectionString);
DbConnection.Open();
if (!File.Exists(DataSource))
{
SQLiteConnection.CreateFile(DataSource);
}
using SQLiteCommand sQLiteCommand = new SQLiteCommand();
sQLiteCommand.Connection = (SQLiteConnection)DbConnection;
sQLiteCommand.CommandText = strings.SQLite_Create;
try
{
sQLiteCommand.ExecuteNonQuery();
}
catch (Exception e)
{
throw new Exception("Erro sqlite" + e.Message);
}
}
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
throw new NotImplementedException();
}
public override void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
public override void Close()
{
try
{
if (DbConnection == null) return;
if (State != ConnectionState.Closed)
{
DbConnection.Close();
}
DbConnection.Dispose();
}
catch (Exception ex)
{
throw new Exception(this.GetType().ToString() + ex.ToString());
}
}
protected override DbCommand CreateDbCommand()
{
throw new NotImplementedException();
}
public override void Open()
{
try
{
DbConnection.Open();
}
catch (Exception ex)
{
throw new Exception(this.GetType().ToString() + ex.ToString());
}
}
}
}<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.View;
using System;
using System.Drawing;
namespace Desafio___Tetris.Presenter
{
public class BoardPresenter
{
public BoardPresenter()
{
//this.Board = new Board();
}
public BoardView BoardView { get; set; }
public Board Board { get; set; }
internal int Width { get; set; }
internal int Height { get; set; }
public void Inicia()
{
Height = BoardView.Panel.Height / Board.LineCount;
Width = BoardView.Panel.Width / Board.ColumnCount;
int menor = Math.Min(Width, Height);
//Inicializa(Board.LineCount, Board.ColumnCount, menor, menor);
Board.Matrix = new RetanguloTabuleiro[Board.LineCount][];
BoardView.Panel.Controls.Clear();
for (int i = 0; i < Board.LineCount; i++)
{
Board.Matrix[i] = new RetanguloTabuleiro[Board.ColumnCount];
for (int j = 0; j < Board.ColumnCount; j++)
{
Board.Matrix[i][j] = new RetanguloTabuleiro();
int xform = j * menor;
int yform = i * menor;
Board.Matrix[i][j].Valor = 0;
Board.Matrix[i][j].BackColor = Color.White;
Board.Matrix[i][j].Location = new Point(xform, yform);
Board.Matrix[i][j].Size = new Size(menor - 1, menor - 1);
BoardView.Panel.Controls.Add(Board.Matrix[i][j]);
}
}
BoardView.Panel.Size = new Size(menor * Board.ColumnCount, menor * Board.LineCount);
}
public void Deleta(int ytab)
{
if (ytab > 0) // evita erro de indice ao mover valor da linha anterior
{
for (int i = 0; ytab - i > 0; i++) // de baixo pra cima
// precisa mover até a linha 1 e não somente até o tamanho da peça
{
for (int j = 0; j < Board.ColumnCount; j++)
{
Board.Matrix[ytab - i][j].Valor = Board.Matrix[ytab - i - 1][j].Valor;
Board.Matrix[ytab - i][j].BackColor = Board.Matrix[ytab - i - 1][j].BackColor;
Board.Matrix[ytab - i][j].Refresh();
}
}
for (int j = 0; j < Board.ColumnCount; j++)
{
Board.Matrix[0][j].Valor = 0;
Board.Matrix[0][j].BackColor = Color.White;
Board.Matrix[0][j].Refresh();
}
}
}
public bool DesenhaY(Piece p, int ytab, int xtab)
{
int ul = p.LineCount - 1;
int uc = p.ColumnCount(ul);
int ypec = ul;
int y = ytab;
int qtdY = Math.Min(y, ul); //tratamento para evitar IndexOutofRangeException
if (ytab < Board.LineCount) //evita erros de índice
{
for (; qtdY >= 0; y--, ypec--, qtdY--)
{
for (int xpec = 0; xpec < uc && (xtab + xpec) < Board.ColumnCount; xpec++)
{
if (p.Ponto(ypec, xpec) == 1)
{
if (Board.Matrix[y][xtab + xpec].Valor == 0)
{
Board.Matrix[y][xtab + xpec].BackColor = p.CorPonto(ypec, xpec);
}
if (Board.Matrix[y][xtab + xpec].Valor == 1) //colisão
{
//return false;
}
}
Board.Matrix[y][xtab + xpec].Valor |= p.Ponto(ypec, xpec);
Board.Matrix[y][xtab + xpec].Refresh();
}
}
}
return false;
}
public void LimpaPeca(Piece p, int ytab, int xtab)
{
/*
NÃO PRECISA DETECTAR COLISÃO
FUNÇÃO DE LIMPEZA
CHAMADA PELA DETECÇÃO DE COLISÃO
*/
int ul = p.LineCount - 1;
int uc = p.ColumnCount(ul);
for (int ypec = ul; ypec >= 0 && ytab >= 0; ypec--, ytab--)
{
for (int xpec = 0; xpec < uc; xpec++)
{
if (p.Ponto(ypec, xpec) == 1)
{
Board.Matrix[ytab][xtab + xpec].Valor = 0;
Board.Matrix[ytab][xtab + xpec].BackColor = Color.White;
Board.Matrix[ytab][xtab + xpec].Refresh();
}
}
}
}
}
}
<file_sep>using Desafio___Tetris.Model;
using Desafio___Tetris.View;
using System;
namespace Desafio___Tetris.Presenter
{
internal class TimePresenter
{
private Time _Time { get; init; }
internal Time Time
{
get => _Time;
init
{
_Time = value;
Time.Timer.Tick += Timer_Tick;
TimeView.Play();
Time.Start();
}
}
internal TimeView TimeView { get; init; }
private void Timer_Tick(object sender, EventArgs e)
{
TimeView.TimeSpan = Time.TimeSpan = Time.Stopwatch.Elapsed;
}
internal void Pause()
{
if (Time.Paused == false)
{
Time.Stop();
TimeView.Pause();
Time.Pause(true);
}
else
{
Time.Pause(false);
Time.Start();
TimeView.Play();
}
}
internal void Over()
{
Time.Stop();
TimeView.Over();
}
internal TimePresenter()
{
}
}
}<file_sep>namespace Desafio___Tetris.Model
{
public class Score
{
#region TimesRegion
public static readonly int[] Times =
{
854,
800,
724,
680,
610,
543,
500, //2/s
333, //3/s
250, //4/s
200, //5/s
166, //6/s
143, //7/s
125, //8/s
111, //9/s
100, //10/s
91, //11/s
83, //12/s
77, //13/s
71, //14/s
67, //15/s
50 //20/s
};
#endregion
public int Points { get; set; }
public int Level { get; set; }
public int StartLevel { get; set; }
public double Speed { get; set; }
public int PieceCounter { get; set; }
public Score()
{
Level = StartLevel;
PieceCounter = 0;
Points = 0;
Speed = Times[StartLevel];
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using Desafio___Tetris.DAO;
using Desafio___Tetris.Model;
namespace Desafio___Tetris
{
public partial class FormPontuacaoTlp : Form
{
public FormPontuacaoTlp()
{
InitializeComponent();
}
private void FormPontuacaoTLP_Load(object sender, EventArgs e)
{
AbsPontuacaoDao pd = new PontuacaoDao().AbsPontuacaoDao;
List<Pontuacao> lp = pd.ListaTodosTlp();
foreach(Pontuacao p in lp)
{
tableLayoutPanel1.RowCount++;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
tableLayoutPanel1.Controls.Add(new LabelNome(p.Id) { Text = p.Nome }, 0, tableLayoutPanel1.RowCount);
tableLayoutPanel1.Controls.Add(new Label() { Text = p.Score.ToString() }, 1, tableLayoutPanel1.RowCount);
tableLayoutPanel1.Controls.Add(new Label() { Text = p.Nivel.ToString() }, 2, tableLayoutPanel1.RowCount);
tableLayoutPanel1.Controls.Add(new Label() { Text = p.TempoJogo.ToString() }, 3, tableLayoutPanel1.RowCount);
tableLayoutPanel1.Controls.Add(new Label() { Text = p.QtdPecas.ToString() }, 4, tableLayoutPanel1.RowCount);
tableLayoutPanel1.Controls.Add(new Label() { Text = p.DataScore.ToString(CultureInfo.CurrentCulture), AutoSize=true }, 5, tableLayoutPanel1.RowCount);
}
}
}
}
<file_sep>using System.Collections.Generic;
using System.Drawing;
namespace Desafio___Tetris.Model.Pecas
{
public class I : PieceAbstract
{
private int _rot;
public override List<int[]> Linhas { get; set; }
public I()
{
Rot = 0;
}
public override Color Cor => Color.DarkBlue;
public sealed override int Rot
{
get => _rot;
set
{
_rot = value;
switch (value)
{
case 0:
this.Linhas = new List<int[]>
{
new int[] { 1 },
new int[] { 1 },
new int[] { 1 },
new int[] { 1 }
};
break;
case 1:
this.Linhas = new List<int[]>{
new int[] { 1,1,1,1 }
};
break;
case 2:
this.Linhas = new List<int[]>{
new int[] { 1 },
new int[] { 1 },
new int[] { 1 },
new int[] { 1 }
};
break;
case 3:
this.Linhas = new List<int[]>{
new int[] { 1,1,1,1 },
};
break;
}
}
}
}
}
|
753329e6fd38936d1146359412408d75d07c5263
|
[
"C#"
] | 38
|
C#
|
tiago-ifrs/Desafio---Tetris
|
4a40f34e8f98a833c312497a3d1b473278a80dc1
|
060d5795c388ba82fb060a40806f58af51c48808
|
refs/heads/master
|
<repo_name>15056158Celest/MedicineReminder<file_sep>/app/src/main/java/comfirebasestudentapp/example/a15056158/medicinereminder/addMed.java
package comfirebasestudentapp.example.a15056158.medicinereminder;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi")
public class addMed extends AppCompatActivity {
private TextView textView;
private String userId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_med);
}
protected void onStart(){
super.onStart();
}
public void addNewRecordButtonClicked(View view){
EditText medNameEditText = (EditText)findViewById(R.id.editTextName);
EditText medDosageEditText = (EditText)findViewById(R.id.editTextDosage);
EditText medTimeEditText = (EditText)findViewById(R.id.editTextTime);
EditText medDateEditText = (EditText)findViewById(R.id.editTextDate);
EditText medRemarksEditText = (EditText)findViewById(R.id.edit_textRemarks);
//TODO 02: Send the HttpRequest to createNewEntry.php
Toast.makeText(addMed.this, "Submitted", Toast.LENGTH_SHORT).show();
HttpRequest request = new HttpRequest("http://10.0.2.2/meds/addMeds.php");
request.setMethod("POST");
request.addData("med_name",medNameEditText.getText().toString());
request.addData("med_dosage",medDosageEditText.getText().toString());
request.addData("med_time",medTimeEditText.getText().toString());
request.addData("med_date",medDateEditText.getText().toString());
request.addData("remarks",medRemarksEditText.getText().toString());
request.execute();
try{
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.activity_add_med, container, false);
return rootView;
}
}
}
<file_sep>/app/src/main/java/comfirebasestudentapp/example/a15056158/medicinereminder/MedList.java
package comfirebasestudentapp.example.a15056158.medicinereminder;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class MedList extends AppCompatActivity {
Intent intent;
ArrayList<medication> medList = new ArrayList<medication>();
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_med_list);
}
public void onResume(){
super.onResume();
medList.clear();
// Check if there is network access
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
HttpRequest request = new HttpRequest("http://10.0.2.2/meds/getMedication.php");
request.setMethod("GET");
request.execute();
try{
String jsonString = request.getResponse();
System.out.println(">>" + jsonString);
JSONArray jsonArray = new JSONArray(jsonString);
// Populate the arraylist personList
for(int i=0 ; i < jsonArray.length(); i++){
JSONObject jObj = jsonArray.getJSONObject(i);
System.out.println(jObj.getString("med_name"));
medication medication = new medication();
medication.setId(jObj.getInt("id"));
medication.setmed_name(jObj.getString("med_name"));
medication.setmed_dosage(jObj.getString("med_dosage"));
medication.setmed_time(jObj.getString("med_time"));
medication.setmed_date(jObj.getString("med_date"));
medication.setremarks(jObj.getString("remarks"));
medList.add(medication);
}
}catch (Exception e){
e.printStackTrace();
}
medicationAdapter arrayAdapter = new medicationAdapter(this, R.layout.listview, medList);
listView = (ListView) findViewById(R.id.listViewMeds);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int arg2, long arg3) {
medication medication = (medication)parent.getItemAtPosition(arg2);
intent = new Intent(getApplicationContext(), EditMedInfoActivity.class);
intent.putExtra("com.example.MAIN_MESSAGE", Integer.toString(medication.getId()));
startActivity(intent);
}
});
} else {
// AlertBox
showAlert();
}
}
private void showAlert(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("No network connection!")
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MedList.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = builder.create();
// show it
alertDialog.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_med_list, container,
false);
return rootView;
}
}
}
<file_sep>/app/src/main/java/comfirebasestudentapp/example/a15056158/medicinereminder/medication.java
package comfirebasestudentapp.example.a15056158.medicinereminder;
/**
* Created by 15056158 on 5/8/2017.
*/
public class medication {
private int id;
private String med_name;
private String med_dosage;
private String med_time;
private String med_date;
private String med_to_take;
private String remarks;
public medication(){
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getmed_name() {
return med_name;
}
public void setmed_name(String med_name) {
this.med_name = med_name;
}
public String getmed_dosage() {
return med_dosage;
}
public void setmed_dosage(String med_dosage) {
this.med_dosage = med_dosage;
}
public String getmed_time() {
return med_time;
}
public void setmed_time(String med_time) {
this.med_time = med_time;
}
public String getMed_date() {
return med_date;
}
public void setmed_date(String med_date) {
this.med_date = med_date;
}
public String getremarks() {
return remarks;
}
public void setremarks(String remarks) {
this.remarks = remarks;
}
public String toString(){
return getmed_name() + " " + getmed_dosage() + " " + getmed_time() + " " + getMed_date() + " " + getremarks() ;
}
}
|
e2afd6758ebc544fd3e13ebc48ad0477f46309ff
|
[
"Java"
] | 3
|
Java
|
15056158Celest/MedicineReminder
|
76eb20ebbb5ba87d947b23dc7185bcf8dc4a129f
|
a51eefa5d1ed498362af7bb2ea42f3edb89d1bbb
|
refs/heads/main
|
<repo_name>noufal85/Udacity-Data-Streaming-Project1<file_sep>/consumers/faust_stream.py
"""Defines trends calculations for stations"""
import logging
import faust
logger = logging.getLogger(__name__)
# Faust will ingest records from Kafka in this format
class Station(faust.Record):
stop_id: int
direction_id: str
stop_name: str
station_name: str
station_descriptive_name: str
station_id: int
order: int
red: bool
blue: bool
green: bool
# Faust will produce records to Kafka in this format
class TransformedStation(faust.Record):
station_id: int
station_name: str
order: int
line: str
def transform(station):
line = ""
if station.red:
line = "red"
elif station.blue:
line = "blue"
elif station.blue:
line = "green"
return TransformedStation(
station.station_id,
station.station_name,
station.order,
line
)
app = faust.App("stations-stream", broker="kafka://localhost:9092", store="memory://")
topic = app.topic("org.chicago.cta.jdbc.source.stations", value_type=Station)
out_topic = app.topic("faust_table", partitions=1)
table = app.Table(
"faust_table",
default=TransformedStation,
partitions=1,
changelog_topic=out_topic,
)
@app.agent(topic)
async def stationevent(stationevents):
stationevents.add_processor(transform)
async for se in stationevents:
table[se.station_id] = se
if __name__ == "__main__":
app.main()
|
f8d8f9e3092c73b72769f0a6e96a21da9bea9c81
|
[
"Python"
] | 1
|
Python
|
noufal85/Udacity-Data-Streaming-Project1
|
b6b57e992cd105d36892b3e3d91ddf126e8d4146
|
77dca1b73266e291772ccb16cd51c1c3fdd7743f
|
refs/heads/master
|
<repo_name>adrienlepert/rails-task-manager<file_sep>/config/routes.rb
Rails.application.routes.draw do
# get 'task/index'
# get 'task/show'
# get 'task/create'
# get 'task/update'
# get 'task/destroy'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :tasks
end
|
4e7f0c82509db13239e556f7ab1083d5319da478
|
[
"Ruby"
] | 1
|
Ruby
|
adrienlepert/rails-task-manager
|
abf72f834b796f28adc910238390ae437d22c22a
|
6a3bc85a2079de74436c1ea9e0bbc7caf38f26a4
|
refs/heads/master
|
<repo_name>danbriechle/LaughTracks<file_sep>/spec/features/users_sees_comedian_new_page_spec.rb
RSpec.describe 'Comedian New Page' do
context 'As a visitor' do
it 'shows a form to input a new comedian, that form works, then redirects to /comedians ' do
visit '/comedians/new'
fill_in 'Name', with: 'James'
fill_in 'Age', with: '4'
fill_in 'City', with: 'Jamestown'
click_on 'Submit'
expect(page).to have_content('James')
expect(page).to have_content(4)
expect(page).to have_content('Jamestown')
expect(current_path).to eq('/comedians')
end
end
end
<file_sep>/spec/models/comedian_spec.rb
RSpec.describe Comedian do
describe 'Validations' do
describe 'Required Field(s)' do
it 'should be invalid if missing a name' do
comic = Comedian.create(age: 48)
expect(comic).to_not be_valid
end
it 'should be invalid if missing an age' do
comic = Comedian.create(name: '<NAME>')
expect(comic).to_not be_valid
end
end
end
end
RSpec.describe Comedian do
describe 'ClassMethods' do
describe '.average_age' do
it'should return the average age of all commedians' do
Comedian.create(name: 'dave', age: 40, city: "new york")
Comedian.create(name: 'john', age: 20, city: "denver")
actual_result = Comedian.average_age
expected_result = 30
expect(actual_result).to eq(expected_result)
end
end
end
end
<file_sep>/spec/models/special_spec.rb
RSpec.describe Special do
describe 'Validations' do
describe 'Required Field(s)' do
it 'should be invalid if missing a name' do
special = Special.create
expect(special).to_not be_valid
end
end
end
end
RSpec.describe Special do
describe 'ClassMethods' do
describe '.average_runtime' do
it'should return the average runtime of all specials' do
Special.create(name: "daves really funny", runtime: 20, img: "../../app/public/image/dave.png")
Special.create(name: "john is not funny", runtime: 10, img: "../../app/public/image/john.png")
actual_result = Special.average_runtime
expected_result = 15
expect(actual_result).to eq(expected_result)
end
end
end
end
<file_sep>/db/seeds.rb
require './app/models/comedian'
require './app/models/special'
Comedian.destroy_all
Special.destroy_all
cf = Comedian.create(name: "<NAME>", age: 56, city: "Glasgow")
mb = Comedian.create(name: "<NAME>", age: 40, city: "Shrewsbury")
is = Comedian.create(name: "<NAME>", age: 35, city: "New York City")
rp = Comedian.create(name: "<NAME>", age: 48, city: "Toronto")
aa = Comedian.create(name: "<NAME>", age: 35, city: "Columbia")
jj = Comedian.create(name: "<NAME>", age: 41, city: "Sydney")
db = Comedian.create(name: "<NAME>", age: 56, city: "San Diego")
cp = Comedian.create(name: "<NAME>", age: 40, city: "Contra Costa")
bb = Comedian.create(name: "<NAME>", age: 50, city: "Canton")
rm = Comedian.create(name: "<NAME>", age: 45, city: "Las Vegas")
cd = Comedian.create(name: "<NAME>", age: 38, city: "Montclair")
ct = Comedian.create(name: "<NAME>", age: 47, city: "Anlanta")
cf.specials.create(name: "<NAME>'s Comedy Special", runtime: 12, img: "image/dave.png")
cf.specials.create(name: "<NAME>'s Other Comedy Special", runtime: 3, img: "image/dave.png")
mb.specials.create(name: "<NAME>'s Comedy Special", runtime: 25, img: "image/dave.png")
is.specials.create(name: "Iliza Shelsinger's Comedy Special", runtime: 24, img: "image/dave.png")
is.specials.create(name: "Iliza Shelsinger's Very Short Comedy Special", runtime: 1, img: "image/dave.png")
rp.specials.create(name: "<NAME>'s Comedy Special", runtime: 14, img: "image/dave.png")
aa.specials.create(name: "<NAME>'s Comedy Special", runtime: 9, img: "image/dave.png")
jj.specials.create(name: "<NAME>'s Comedy Special", runtime: 6, img: "image/dave.png")
db.specials.create(name: "<NAME> Comedy Special", runtime: 12, img: "image/dave.png")
cp.specials.create(name: "<NAME>'s Comedy Special", runtime: 19, img: "image/dave.png")
bb.specials.create(name: "<NAME> Comedy Special", runtime: 18, img: "image/dave.png")
rm.specials.create(name: "<NAME> Comedy Special", runtime: 6, img: "image/dave.png")
cd.specials.create(name: "<NAME> Comedy Special", runtime: 1, img: "image/dave.png")
ct.specials.create(name: "<NAME>'s Comedy Special", runtime: 14, img: "image/dave.png")
<file_sep>/spec/features/user_sees_comedian_show_page_spec.rb
RSpec.describe 'Comedian Show Page' do
context 'As a visitor' do
it 'shows comedian list with name, age and city' do
ben = Comedian.create(name: 'ben', age: 27, city: "denver")
dave = Comedian.create(name: 'dave', age: 40, city: "new york")
visit '/comedians'
within "#comic-#{ben.id}" do
expect(page).to have_content(ben.name)
expect(page).to have_content("Age: - #{ben.age}")
expect(page).to have_content(ben.city)
end
within "#comic-#{dave.id}" do
expect(page).to have_content(dave.name)
expect(page).to have_content("Age: - #{dave.age}")
expect(page).to have_content(dave.city)
end
end
it 'shows comedian list with specials names' do
dave = Comedian.create(name: 'dave', age: 40, city: "new york") #a comedian is a play list
dave.specials.create(name: "daves really funny")
ben = Comedian.create(name: 'ben', age: 27, city: "denver")
ben.specials.create(name: "bens really funny")
visit '/comedians'
within "#comic-#{ben.id}" do
expect(page).to have_content("bens really funny")
end
within "#comic-#{dave.id}" do
expect(page).to have_content("daves really funny")
end
end
it 'shows a comedians specials run time length and thumbnail image' do
dave = Comedian.create(name: 'dave', age: 40, city: "new york") #a comedian is a play list
davesspecial = dave.specials.create(name: "daves really funny", runtime: 12, img: "../../app/public/image/dave.png")
visit '/comedians'
within "#comic-#{dave.id}" do
expect(page).to have_css("img[src='#{davesspecial.img}']")
expect(page).to have_content(davesspecial.runtime)
end
end
it 'shows a statistics area with avg age, avg runtime & unique cities list' do
dave = Comedian.create(name: 'dave', age: 40, city: "New York") #a comedian is a play list
dave.specials.create(name: "daves really funny", runtime: 20, img: "../../app/public/image/dave.png")
john = Comedian.create(name: 'john', age: 20, city: "Denver") #a comedian is a play list
john.specials.create(name: "john is not funny", runtime: 10, img: "../../app/public/image/john.png")
visit '/comedians'
within ".statistics" do
expect(page).to have_content("Average Age 30")
expect(page).to have_content("Average Runtime 15")
expect(page).to have_content("New York", "Denver")
end
end
it 'can be querried for a list of all comedians by age' do
dave = Comedian.create(name: 'dave', age: 40, city: "new york")
ben = Comedian.create(name: 'ben', age: 27, city: "denver")
visit '/comedians?age=40'
expect(page).to have_content(dave.name)
expect(page).not_to have_content(ben.name)
end
it 'shows a count of all the specials in the stats section and each comedian has a total specials count'do
dave = Comedian.create(name: 'dave', age: 40, city: "New York")
dave.specials.create(name: "daves really funny", runtime: 20, img: "../../app/public/image/dave.png")
john = Comedian.create(name: 'john', age: 20, city: "Denver")
john.specials.create(name: "<NAME>", runtime: 10, img: "../../app/public/image/john.png")
visit '/comedians'
within "#comic-#{john.id}" do
expect(page).to have_content("Total Specials: 1")
end
within ".statistics" do
expect(page).to have_content("Total Specials: 2")
end
end
it 'recalculates averages based upon querry' do
dave = Comedian.create(name: 'dave', age: 40, city: "New York")
dave.specials.create(name: "<NAME>", runtime: 20, img: "../../app/public/image/dave.png")
john = Comedian.create(name: 'john', age: 20, city: "Denver")
john.specials.create(name: "<NAME>", runtime: 10, img: "../../app/public/image/john.png")
visit '/comedians?age=40'
within ".statistics" do
expect(page).to have_content("Average Age 40")
expect(page).to have_content("Average Runtime 20")
expect(page).to have_content("New York")
end
end
end
end
<file_sep>/db/migrate/20181129175745_adds_img_to_specials.rb
class AddsImgToSpecials < ActiveRecord::Migration[5.2]
def change
add_column :specials, :img, :string
end
end
|
d005db85b42d756c7b603b2722b702cb94b8c18e
|
[
"Ruby"
] | 6
|
Ruby
|
danbriechle/LaughTracks
|
adb93ae09fcecf5f96eca2b640881faf58436a85
|
d5c8db1ec345a5fd4e07729c74ee6fad77ac0f99
|
refs/heads/main
|
<file_sep>package confirma.noitificacao;
import confirma.domain.Cliente;
public interface Notificador {
void notificar(Cliente cliente, String mensagem);
}
<file_sep>package confirma.noitificacao;
import confirma.domain.Cliente;
import confirma.domain.Produto;
public class EmissaoNotaFiscal {
private Notificador notificador;
public void emitir(Cliente cliente, Produto produto) {
// TODO emite a nota fiscal aqui...
notificador.notificar(cliente, "Nota fiscal " + produto.getNome() + "Disponível");
}
}
|
a52ece0959e6c382c530676e7c828b18a9d510d3
|
[
"Java"
] | 2
|
Java
|
sumaeta/Notifica-o-de-compra
|
cbe67c997ca713ae99f09f234e82d5e22cde375f
|
b85c69a554da39febffdc426a56a784c9d8f0896
|
refs/heads/master
|
<repo_name>ArmanSauyenov/Inherritance_BooksAndTransport<file_sep>/Vehicles/Classes/Transport.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicles.Classes
{
public enum Vehicle { MersedesBenz, BMW, Lexus, Toyota, Volvo, Kia, Hyundai }
public abstract class Transport
{
protected static Random rand = new Random();
public Vehicle Marks { get; set; }
public string Number { get; set; }
public int Speed { get; set; }
public int CarryCap { get; set; }
public abstract void PrintInfo();
public abstract int CarryingCapacity();
}
}
<file_sep>/Inheritance_BooksAndTransport/Generator.cs
using Inheritance_BooksAndTransport.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance_BooksAndTransport
{
public enum Book { SomeBook, AnyBook, GoodBook, BestBook, NewBook }
public enum Publish { PublisherOne, PublisherTwo, PublisherThree, PublisherFour, PublisherFive }
public enum Author { BestAuthor, GoodAuthor, NewAuthor, PopularAuthor, OldAuthor }
public enum Mag { EnglandMagazine, RussiaMagazine, GreeceMagazine, KazakhstanMagazine, JapanMagazine }
public enum Link { www_best_com, www_new_com, www_old_com, www_world_com, www_metropol_com }
public class Generator
{
private Random rand = new Random();
public List<Publishings> pub;
public Generator()
{
pub = new List<Publishings>();
}
public void GenerateBook()
{
Books b = new Books();
b.SourceName = ((Book)rand.Next(0, 5)).ToString();
b.AuthorName = ((Author)rand.Next(0, 5)).ToString();
b.PublishDate = DateTime.Now.AddMonths(-rand.Next(1, 24));
b.Publishment = ((Publish)rand.Next(0, 5)).ToString();
pub.Add(b);
}
public void GenerateArticle()
{
Articles a = new Articles();
a.SourceName = ((Book)rand.Next(0, 5)).ToString();
a.AuthorName = ((Author)rand.Next(0, 5)).ToString();
a.MagazineName = ((Mag)rand.Next(0, 5)).ToString();
a.MagNumber = rand.Next(0, 300);
a.PublishDate = DateTime.Now.AddMonths(-rand.Next(1, 24));
pub.Add(a);
}
public void GenerateWeb()
{
WebSites w = new WebSites();
w.SourceName = ((Book)rand.Next(0, 5)).ToString();
w.AuthorName = ((Author)rand.Next(0, 5)).ToString();
w.Link = ((Link)rand.Next(0, 5)).ToString();
w.Annotation = "Not available";
pub.Add(w);
}
public void PrintAll()
{
foreach (Publishings item in pub)
{
item.PrintInfo();
}
}
public void FindAuthor(string aut)
{
foreach (Publishings item in pub)
{
if (item.AuthorName == aut)
Console.WriteLine($" Author was found {item.AuthorName}");
else
Console.WriteLine("Invalid author name");
}
}
}
}
<file_sep>/Transport/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Transports
{
class Program
{
static void Main(string[] args)
{
Generator g = new Generator();
g.GeneratorCar();
g.GeneranorBike();
g.GeneranorTruck();
g.PrintAll();
Console.WriteLine("Pls enter a cappacity");
int value = Int32.Parse(Console.ReadLine());
g.FindTransByCappacity(value);
}
}
}
<file_sep>/Transport/Classes/Truck.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Transport.Classes
{
public class Truck : Transport
{
public int Trailer;
public override int CarryingCapacity()
{
if ((Trailer = rand.Next(0, 1)) == 1)
{
return CarryCap *= 2;
}
else
{
return CarryCap = rand.Next(100, 1000);
}
}
public override void PrintInfo()
{
Console.WriteLine($"Bike's mark {Marks}\n Bike's number {Number}\n Bike's speed {Speed}\n " +
$"Bike's carry cappacity {CarryingCapacity()} ");
}
}
}
<file_sep>/Transport/Classes/Car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Transport.Classes
{
public class Car : Transport
{
public override int CarryingCapacity()
{
return CarryCap = rand.Next(300, 600);
}
public override void PrintInfo()
{
Console.WriteLine($"Car's mark {Marks}\n Car's number {Number}\n Car's speed {Speed}\n " +
$"Car's carry cappacity {CarryingCapacity()} ");
}
}
}
<file_sep>/Inheritance_BooksAndTransport/Classes/Publishings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance_BooksAndTransport
{
public abstract class Publishings
{
public string SourceName { get; set; }
public string AuthorName { get; set; }
public abstract void PrintInfo();
}
}
<file_sep>/Inheritance_BooksAndTransport/Classes/WebSites.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance_BooksAndTransport.Classes
{
public class WebSites : Publishings
{
public string Link { get; set; }
public string Annotation { get; set; }
public override void PrintInfo()
{
Console.WriteLine($"Source: {SourceName} \nAuthor: {AuthorName} \n" +
$"Link: {Link} \nAnnotation: {Annotation} \n");
}
}
}
<file_sep>/Inheritance_BooksAndTransport/Classes/Books.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance_BooksAndTransport
{
public class Books : Publishings
{
private string _publishment;
public DateTime PublishDate { get; set; }
public string Publishment
{
get { return _publishment; }
set { _publishment = value; }
}
public override void PrintInfo()
{
Console.WriteLine($"Source: {SourceName} \nAuthor: {AuthorName} \n" +
$"Publish date: {PublishDate} \nPublishment: {Publishment} \n");
}
}
}
<file_sep>/Transports/Generator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Transports
{
class Generator
{
}
}
<file_sep>/Vehicles/Classes/Trucks.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicles.Classes
{
public class Truck : Transport
{
public int Trailer;
public override int CarryingCapacity()
{
if ((Trailer = rand.Next(0, 1)) == 1)
{
return CarryCap *= 2;
}
else
{
return CarryCap = rand.Next(100, 1000);
}
}
public override void PrintInfo()
{
Console.WriteLine($"Truck's mark: {Marks}\n Truck's number: {Number}\n Truck's speed: {Speed}\n " +
$"Truck's carry cappacity: {CarryingCapacity()} ");
}
}
}
<file_sep>/Transport/Classes/Bike.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Transport.Classes
{
public class Bike : Transport
{
public int Carriage;
public override int CarryingCapacity()
{
if ((Carriage = rand.Next(0, 1)) == 0)
{
return CarryCap = 0;
}
else
{
return CarryCap = rand.Next(10, 100);
}
}
public override void PrintInfo()
{
Console.WriteLine($"Bike's mark {Marks}\n Bike's number {Number}\n Bike's speed {Speed}\n " +
$"Bike's carry cappacity {CarryingCapacity()} ");
}
}
}
<file_sep>/Inheritance_BooksAndTransport/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance_BooksAndTransport
{
class Program
{
static void Main(string[] args)
{
Generator gen = new Generator();
gen.GenerateBook();
gen.GenerateArticle();
gen.GenerateWeb();
gen.PrintAll();
gen.FindAuthor("Au3");
}
}
}
<file_sep>/Inheritance_BooksAndTransport/Classes/Articles.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance_BooksAndTransport.Classes
{
public class Articles : Publishings
{
public string MagazineName { get; set; }
public int MagNumber { get; set; }
public DateTime PublishDate { get; set; }
public override void PrintInfo()
{
Console.WriteLine($"Source: {SourceName} \nAuthor: {AuthorName} \n" +
$"Magazine name: {MagazineName} \nMagazine number: {MagNumber} \n" +
$"Publish date: {PublishDate} \n");
}
}
}
<file_sep>/Transport/Generator.cs
using Transports.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Transports
{
public class Generator
{
private static Random rand = new Random();
public List<Transports> transport;
public Generator()
{
transport = new List<Transport>();
}
public void GeneratorCar()
{
for (int i = 0; i < 5; i++)
{
Car car = new Car();
car.Marks = (Vehicle)rand.Next(0, 4);
car.Number = Convert.ToString(rand.Next(1000, 9999));
car.Speed = rand.Next(60, 150);
car.CarryCap = car.CarryingCapacity();
transport.Add(car);
}
}
public void GeneranorBike()
{
for (int i = 0; i < 5; i++)
{
Bike bike = new Bike();
bike.Marks = (Vehicle)rand.Next(0, 4);
bike.Number = Convert.ToString(rand.Next(1000, 9999));
bike.Speed = rand.Next(60, 250);
bike.CarryCap = bike.CarryingCapacity();
transport.Add(bike);
}
}
public void GeneranorTruck()
{
for (int i = 0; i < 5; i++)
{
Truck truck = new Truck();
truck.Marks = (Vehicle)rand.Next(0, 4);
truck.Number = Convert.ToString(rand.Next(1000, 9999));
truck.Speed = rand.Next(60, 250);
truck.CarryCap = truck.CarryingCapacity();
transport.Add(truck);
}
}
public void PrintAll()
{
foreach (Transport item in transport)
{
item.PrintInfo();
}
}
public void FindTransByCappacity(int m)
{
foreach (Transport item in transport)
{
if (m <= item.CarryCap)
{
item.PrintInfo();
}
else
Console.WriteLine("There is no matches in yor request");
}
}
}
}
<file_sep>/Vehicles/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vehicles
{
class Program
{
static void Main(string[] args)
{
Generator gen = new Generator();
gen.GeneratorCar();
gen.GeneranorBike();
gen.GeneranorTruck();
gen.PrintAll();
Console.WriteLine("Please enter a cappacity");
int value = Int32.Parse(Console.ReadLine());
gen.FindTransByCappacity(value);
}
}
}
|
2f17ea17a5467fd7dec43a3d07243d17e1c3b45c
|
[
"C#"
] | 15
|
C#
|
ArmanSauyenov/Inherritance_BooksAndTransport
|
4bb699175a1cb7696e5f6d038046bbcfd0eed33c
|
aecf20610fb8239db64df06b09df779604af4693
|
refs/heads/master
|
<repo_name>frankverhoeven/tactician<file_sep>/src/Handler/Middleware/EventManagerMiddleware.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\Middleware;
use FrankVerhoeven\Tactician\Event\CommandFailedEvent;
use FrankVerhoeven\Tactician\Event\CommandHandledEvent;
use FrankVerhoeven\Tactician\Event\CommandReceivedEvent;
use League\Tactician\Middleware;
use Zend\EventManager\EventManagerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class EventManagerMiddleware implements Middleware
{
/**
* @var EventManagerInterface
*/
private $eventManager;
/**
* @param EventManagerInterface $eventManager
*/
public function __construct(EventManagerInterface $eventManager)
{
$this->eventManager = $eventManager;
}
/**
* @param object $command
* @param callable $next
* @return mixed
* @throws \Throwable
*/
public function execute($command, callable $next)
{
try {
$this->eventManager->triggerEvent(new CommandReceivedEvent($command));
$result = $next($command);
$this->eventManager->triggerEvent(new CommandHandledEvent($command));
return $result;
} catch (\Throwable $exception) {
$this->eventManager->triggerEvent(new CommandFailedEvent($command));
throw $exception;
}
}
}
<file_sep>/test/ConfigProviderTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest;
use FrankVerhoeven\Tactician\ConfigProvider;
use PHPUnit\Framework\TestCase;
/**
* @author <NAME> <<EMAIL>>
*/
final class ConfigProviderTest extends TestCase
{
public function testProvidesConfig(): void
{
$provider = new ConfigProvider();
self::assertInternalType('array', $provider());
}
}
<file_sep>/src/Handler/Middleware/EventManagerMiddlewareFactory.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\Middleware;
use Psr\Container\ContainerInterface;
use Zend\EventManager\EventManagerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class EventManagerMiddlewareFactory
{
/**
* @param ContainerInterface $container
* @return EventManagerMiddleware
*/
public function __invoke(ContainerInterface $container): EventManagerMiddleware
{
return new EventManagerMiddleware(
$container->get(EventManagerInterface::class)
);
}
}
<file_sep>/test/Handler/CommandHandlerMapper/ConfigMapperFactoryTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\CommandHandlerMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ConfigMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ConfigMapperFactory;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class ConfigMapperFactoryTest extends TestCase
{
public function testCreatesConfigMapper(): void
{
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::once())
->method('get')
->with('config')
->willReturn(['command_handlers' => []]);
$factory = new ConfigMapperFactory();
self::assertInstanceOf(ConfigMapper::class, $factory($container));
}
}
<file_sep>/test/Handler/Middleware/EventManagerMiddlewareTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\Middleware;
use FrankVerhoeven\Tactician\Event\CommandFailedEvent;
use FrankVerhoeven\Tactician\Event\CommandHandledEvent;
use FrankVerhoeven\Tactician\Event\CommandReceivedEvent;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddleware;
use PHPUnit\Framework\TestCase;
use Zend\EventManager\EventManagerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class EventManagerMiddlewareTest extends TestCase
{
/**
* @var EventManagerMiddleware
*/
private $middleware;
/**
* @var EventManagerInterface
*/
private $eventManager;
protected function setUp()
{
$this->middleware = new EventManagerMiddleware(
$this->eventManager = $this->createMock(EventManagerInterface::class)
);
}
public function testExecute(): void
{
$command = new \stdClass();
$next = $this->createPartialMock(\stdClass::class, ['__invoke']);
$this->eventManager->expects(self::exactly(2))
->method('triggerEvent')
->withConsecutive(
[new CommandReceivedEvent($command)],
[new CommandHandledEvent($command)]
);
$next->expects(self::once())
->method('__invoke')
->with($command)
->willReturn('value');
self::assertEquals('value', $this->middleware->execute($command, $next));
}
public function testExecuteFailed(): void
{
$command = new \stdClass();
$next = $this->createPartialMock(\stdClass::class, ['__invoke']);
$this->eventManager->expects(self::exactly(2))
->method('triggerEvent')
->withConsecutive(
[new CommandReceivedEvent($command)],
[new CommandFailedEvent($command)]
);
$next->expects(self::once())
->method('__invoke')
->with($command)
->willThrowException(new \Exception());
$this->expectException(\Exception::class);
$this->middleware->execute($command, $next);
}
}
<file_sep>/src/CommandBusFactory.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddleware;
use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandBusFactory
{
/**
* @param ContainerInterface $container
* @return CommandBus
*/
public function __invoke(ContainerInterface $container): CommandBus
{
return new CommandBus([
$container->get(EventManagerMiddleware::class),
$container->get(CommandHandlerMiddleware::class),
]);
}
}
<file_sep>/test/Event/CommandFailedEventTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Event;
use FrankVerhoeven\Tactician\Event\CommandEventInterface;
use FrankVerhoeven\Tactician\Event\CommandFailedEvent;
use PHPUnit\Framework\TestCase;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandFailedEventTest extends TestCase
{
public function testConstructor(): void
{
$event = new CommandFailedEvent($command = new \stdClass());
self::assertSame($command, $event->command());
self::assertEquals(\stdClass::class . CommandEventInterface::FAILED, $event->getName());
}
}
<file_sep>/src/ConfigProvider.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CombinedConfigAndReplacingMapperFactory;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ConfigMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ConfigMapperFactory;
use FrankVerhoeven\Tactician\Handler\Locator\ContainerLocatorFactory;
use FrankVerhoeven\Tactician\Handler\Middleware\CommandHandlerMiddlewareFactory;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddleware;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddlewareFactory;
use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\ClassNameExtractor;
use League\Tactician\Handler\CommandNameExtractor\CommandNameExtractor;
use League\Tactician\Handler\Locator\HandlerLocator;
use League\Tactician\Handler\MethodNameInflector\InvokeInflector;
use League\Tactician\Handler\MethodNameInflector\MethodNameInflector;
/**
* @author <NAME> <<EMAIL>>
*/
final class ConfigProvider
{
/**
* @return array
*/
public function __invoke(): array
{
return [
'dependencies' => [
'invokables' => [
CommandNameExtractor::class => ClassNameExtractor::class,
MethodNameInflector::class => InvokeInflector::class,
],
'factories' => [
CommandBus::class => CommandBusFactory::class,
CommandHandlerMapperInterface::class => CombinedConfigAndReplacingMapperFactory::class,
CommandHandlerMiddleware::class => CommandHandlerMiddlewareFactory::class,
ConfigMapper::class => ConfigMapperFactory::class,
EventManagerMiddleware::class => EventManagerMiddlewareFactory::class,
HandlerLocator::class => ContainerLocatorFactory::class,
],
],
];
}
}
<file_sep>/test/Handler/CommandHandlerMapper/CombinedConfigAndReplacingMapperFactoryTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\CommandHandlerMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CombinedConfigAndReplacingMapperFactory;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CombinedMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ConfigMapper;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class CombinedConfigAndReplacingMapperFactoryTest extends TestCase
{
public function testCreatesCombinedMapper(): void
{
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::once())
->method('get')
->with(ConfigMapper::class)
->willReturn($this->createMock(CommandHandlerMapperInterface::class));
$factory = new CombinedConfigAndReplacingMapperFactory();
self::assertInstanceOf(CombinedMapper::class, $factory($container));
}
}
<file_sep>/test/Handler/CommandHandlerMapper/CombinedMapperTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\CommandHandlerMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CombinedMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use League\Tactician\Exception\MissingHandlerException;
use PHPUnit\Framework\TestCase;
/**
* @author <NAME> <<EMAIL>>
*/
final class CombinedMapperTest extends TestCase
{
/**
* @var CombinedMapper
*/
private $mapper;
/**
* @var CommandHandlerMapperInterface
*/
private $innerMapper1;
/**
* @var CommandHandlerMapperInterface
*/
private $innerMapper2;
protected function setUp()
{
$this->mapper = new CombinedMapper([
$this->innerMapper1 = $this->createMock(CommandHandlerMapperInterface::class),
$this->innerMapper2 = $this->createMock(CommandHandlerMapperInterface::class),
]);
}
public function testHandlerFoundByFirstMapper(): void
{
$commandName = 'command';
$this->innerMapper1->expects(self::once())
->method('getHandlerNameForCommandName')
->with($commandName)
->willReturn($handlerName = 'handler');
$this->innerMapper2->expects(self::never())
->method('getHandlerNameForCommandName');
self::assertEquals($handlerName, $this->mapper->getHandlerNameForCommandName($commandName));
}
public function testHandlerFoundBySecondMapper(): void
{
$commandName = 'command';
$this->innerMapper1->expects(self::once())
->method('getHandlerNameForCommandName')
->with($commandName)
->willThrowException(MissingHandlerException::forCommand($commandName));
$this->innerMapper2->expects(self::once())
->method('getHandlerNameForCommandName')
->with($commandName)
->willReturn($handlerName = 'handler');
self::assertEquals($handlerName, $this->mapper->getHandlerNameForCommandName($commandName));
}
public function testHandlerNotFound(): void
{
$commandName = 'command';
$this->innerMapper1->expects(self::once())
->method('getHandlerNameForCommandName')
->with($commandName)
->willThrowException(MissingHandlerException::forCommand($commandName));
$this->innerMapper2->expects(self::once())
->method('getHandlerNameForCommandName')
->with($commandName)
->willThrowException(MissingHandlerException::forCommand($commandName));
$this->expectException(MissingHandlerException::class);
$this->mapper->getHandlerNameForCommandName($commandName);
}
}
<file_sep>/test/Handler/Middleware/CommandHandlerMiddlewareFactoryTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\Middleware;
use FrankVerhoeven\Tactician\Handler\Middleware\CommandHandlerMiddlewareFactory;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\CommandNameExtractor;
use League\Tactician\Handler\Locator\HandlerLocator;
use League\Tactician\Handler\MethodNameInflector\MethodNameInflector;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandHandlerMiddlewareFactoryTest extends TestCase
{
public function testCreatesCommandHandlerMiddleware(): void
{
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::exactly(3))
->method('get')
->withConsecutive(
[CommandNameExtractor::class],
[HandlerLocator::class],
[MethodNameInflector::class]
)
->willReturnOnConsecutiveCalls(
$this->createMock(CommandNameExtractor::class),
$this->createMock(HandlerLocator::class),
$this->createMock(MethodNameInflector::class)
);
$factory = new CommandHandlerMiddlewareFactory();
self::assertInstanceOf(CommandHandlerMiddleware::class, $factory($container));
}
}
<file_sep>/src/Event/CommandReceivedEvent.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Event;
use Zend\EventManager\Event;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandReceivedEvent extends Event implements CommandEventInterface
{
use CommandEventTrait;
/**
* @param object $command
*/
public function __construct(object $command)
{
$this->command = $command;
parent::__construct(\get_class($command) . CommandEventInterface::RECEIVED);
}
}
<file_sep>/src/Handler/CommandHandlerMapper/ReplaceCommandWithHandlerMapper.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\CommandHandlerMapper;
/**
* @author <NAME> <<EMAIL>>
*/
final class ReplaceCommandWithHandlerMapper implements CommandHandlerMapperInterface
{
/**
* @inheritdoc
*/
public function getHandlerNameForCommandName(string $commandName): string
{
return \str_replace('Command', 'Handler', $commandName);
}
}
<file_sep>/src/Handler/CommandHandlerMapper/ConfigMapperFactory.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\CommandHandlerMapper;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class ConfigMapperFactory
{
/**
* @param ContainerInterface $container
* @return ConfigMapper
*/
public function __invoke(ContainerInterface $container): ConfigMapper
{
return new ConfigMapper(
$container->get('config')['command_handlers'] ?? []
);
}
}
<file_sep>/src/Handler/Locator/ContainerLocator.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\Locator;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use League\Tactician\Handler\Locator\HandlerLocator;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class ContainerLocator implements HandlerLocator
{
/**
* @var CommandHandlerMapperInterface
*/
private $commandHandlerMapper;
/**
* @var ContainerInterface
*/
private $container;
/**
* @param CommandHandlerMapperInterface $commandHandlerMapper
* @param ContainerInterface $container
*/
public function __construct(
CommandHandlerMapperInterface $commandHandlerMapper,
ContainerInterface $container
) {
$this->commandHandlerMapper = $commandHandlerMapper;
$this->container = $container;
}
/**
* @inheritdoc
*/
public function getHandlerForCommand($commandName)
{
return $this->container->get(
$this->commandHandlerMapper->getHandlerNameForCommandName($commandName)
);
}
}
<file_sep>/test/Handler/Middleware/EventManagerMiddlewareFactoryTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\Middleware;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddleware;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddlewareFactory;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Zend\EventManager\EventManagerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class EventManagerMiddlewareFactoryTest extends TestCase
{
public function testCreatesEventManagerMiddleware(): void
{
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::once())
->method('get')
->with(EventManagerInterface::class)
->willReturn($this->createMock(EventManagerInterface::class));
$factory = new EventManagerMiddlewareFactory();
self::assertInstanceOf(EventManagerMiddleware::class, $factory($container));
}
}
<file_sep>/test/Handler/CommandHandlerMapper/ConfigMapperTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\CommandHandlerMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ConfigMapper;
use League\Tactician\Exception\MissingHandlerException;
use PHPUnit\Framework\TestCase;
/**
* @author <NAME> <<EMAIL>>
*/
final class ConfigMapperTest extends TestCase
{
public function testGetHandlerNameForCommandName(): void
{
$mapper = new ConfigMapper(['command' => 'handler']);
self::assertEquals('handler', $mapper->getHandlerNameForCommandName('command'));
}
public function testGetHandlerNameForCommandNameException(): void
{
$this->expectException(MissingHandlerException::class);
(new ConfigMapper([]))->getHandlerNameForCommandName('command');
}
}
<file_sep>/src/Handler/Locator/ContainerLocatorFactory.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\Locator;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class ContainerLocatorFactory
{
/**
* @param ContainerInterface $container
* @return ContainerLocator
*/
public function __invoke(ContainerInterface $container): ContainerLocator
{
return new ContainerLocator(
$container->get(CommandHandlerMapperInterface::class),
$container
);
}
}
<file_sep>/src/Handler/CommandHandlerMapper/CombinedConfigAndReplacingMapperFactory.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\CommandHandlerMapper;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class CombinedConfigAndReplacingMapperFactory
{
/**
* @param ContainerInterface $container
* @return CombinedMapper
*/
public function __invoke(ContainerInterface $container): CombinedMapper
{
return new CombinedMapper([
$container->get(ConfigMapper::class),
new ReplaceCommandWithHandlerMapper(),
]);
}
}
<file_sep>/src/Event/CommandEventInterface.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Event;
use Zend\EventManager\EventInterface;
/**
* @author <NAME> <<EMAIL>>
*/
interface CommandEventInterface extends EventInterface
{
public const RECEIVED = '.received';
public const HANDLED = '.handled';
public const FAILED = '.failed';
/**
* @return object
*/
public function command(): object;
}
<file_sep>/src/Handler/CommandHandlerMapper/CommandHandlerMapperInterface.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\CommandHandlerMapper;
use League\Tactician\Exception\MissingHandlerException;
/**
* @author <NAME> <<EMAIL>>
*/
interface CommandHandlerMapperInterface
{
/**
* Retrieve the name of the command handler for the provided command name.
*
* @param string $commandName Command name
* @return string Command handler name
* @throws MissingHandlerException
*/
public function getHandlerNameForCommandName(string $commandName): string;
}
<file_sep>/test/Handler/Locator/ContainerLocatorFactoryTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\Locator;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use FrankVerhoeven\Tactician\Handler\Locator\ContainerLocator;
use FrankVerhoeven\Tactician\Handler\Locator\ContainerLocatorFactory;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class ContainerLocatorFactoryTest extends TestCase
{
public function testCreatesContainerLocator(): void
{
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::once())
->method('get')
->with(CommandHandlerMapperInterface::class)
->willReturn($this->createMock(CommandHandlerMapperInterface::class));
$factory = new ContainerLocatorFactory();
self::assertInstanceOf(ContainerLocator::class, $factory($container));
}
}
<file_sep>/src/Event/CommandEventTrait.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Event;
/**
* @author <NAME> <<EMAIL>>
*/
trait CommandEventTrait
{
/**
* @var object
*/
protected $command;
/**
* @return object
*/
public function command(): object
{
return $this->command;
}
}
<file_sep>/src/Handler/CommandHandlerMapper/CombinedMapper.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\CommandHandlerMapper;
use League\Tactician\Exception\MissingHandlerException;
/**
* @author <NAME> <<EMAIL>>
*/
final class CombinedMapper implements CommandHandlerMapperInterface
{
/**
* @var CommandHandlerMapperInterface[]
*/
private $commandHandlerMappers;
/**
* @param CommandHandlerMapperInterface[] $commandHandlerMappers List of mappers that are executed in the order in
* which they are provided. First handler name that
* is found will be used.
*/
public function __construct(array $commandHandlerMappers)
{
$this->commandHandlerMappers = \array_map(
function (CommandHandlerMapperInterface $commandHandlerMapper) {
return $commandHandlerMapper;
},
$commandHandlerMappers
);
}
/**
* @inheritdoc
*/
public function getHandlerNameForCommandName(string $commandName): string
{
$handlerName = null;
foreach ($this->commandHandlerMappers as $commandHandlerMapper) {
try {
$handlerName = $commandHandlerMapper->getHandlerNameForCommandName($commandName);
break;
} catch (MissingHandlerException $exception) {
}
}
if (null === $handlerName) {
throw MissingHandlerException::forCommand($commandName);
}
return $handlerName;
}
}
<file_sep>/test/CommandBusFactoryTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest;
use FrankVerhoeven\Tactician\CommandBusFactory;
use FrankVerhoeven\Tactician\Handler\Middleware\EventManagerMiddleware;
use League\Tactician\CommandBus;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Middleware;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandBusFactoryTest extends TestCase
{
public function testCreatesConfigMapper(): void
{
$container = $this->createMock(ContainerInterface::class);
$container->expects(self::exactly(2))
->method('get')
->withConsecutive(
[EventManagerMiddleware::class],
[CommandHandlerMiddleware::class]
)
->willReturn($this->createMock(Middleware::class));
$factory = new CommandBusFactory();
self::assertInstanceOf(CommandBus::class, $factory($container));
}
}
<file_sep>/test/Handler/Locator/ContainerLocatorTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\Locator;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\CommandHandlerMapperInterface;
use FrankVerhoeven\Tactician\Handler\Locator\ContainerLocator;
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class ContainerLocatorTest extends TestCase
{
/**
* @var ContainerLocator
*/
private $locator;
/**
* @var CommandHandlerMapperInterface
*/
private $mapper;
/**
* @var ContainerInterface
*/
private $container;
protected function setUp()
{
$this->locator = new ContainerLocator(
$this->mapper = $this->createMock(CommandHandlerMapperInterface::class),
$this->container = $this->createMock(ContainerInterface::class)
);
}
public function testGetHandlerForCommand(): void
{
$this->mapper->expects(self::once())
->method('getHandlerNameForCommandName')
->with($command = 'command')
->willReturn($handlerName = 'handlerName');
$this->container->expects(self::once())
->method('get')
->with($handlerName)
->willReturn($handler = 'handler');
self::assertEquals($handler, $this->locator->getHandlerForCommand($command));
}
}
<file_sep>/test/Handler/CommandHandlerMapper/ReplaceCommandWithHandlerMapperTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Handler\CommandHandlerMapper;
use FrankVerhoeven\Tactician\Handler\CommandHandlerMapper\ReplaceCommandWithHandlerMapper;
use PHPUnit\Framework\TestCase;
/**
* @author <NAME> <<EMAIL>>
*/
final class ReplaceCommandWithHandlerMapperTest extends TestCase
{
/**
* @param string $commandName
* @param string $handlerName
*
* @dataProvider commandNamesDataProvider
*/
public function testGetHandlerNameForCommandName(string $commandName, string $handlerName): void
{
$mapper = new ReplaceCommandWithHandlerMapper();
self::assertEquals($handlerName, $mapper->getHandlerNameForCommandName($commandName));
}
/**
* @return array
*/
public function commandNamesDataProvider(): array
{
return [
['Command', 'Handler'],
['/App/UpdateCommand', '/App/UpdateHandler'],
['/App/Command/Update', '/App/Handler/Update'],
['/App/Command/UpdateCommand', '/App/Handler/UpdateHandler'],
];
}
}
<file_sep>/src/Handler/Middleware/CommandHandlerMiddlewareFactory.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\Middleware;
use League\Tactician\Handler\CommandHandlerMiddleware;
use League\Tactician\Handler\CommandNameExtractor\CommandNameExtractor;
use League\Tactician\Handler\Locator\HandlerLocator;
use League\Tactician\Handler\MethodNameInflector\MethodNameInflector;
use Psr\Container\ContainerInterface;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandHandlerMiddlewareFactory
{
/**
* @param ContainerInterface $container
* @return CommandHandlerMiddleware
*/
public function __invoke(ContainerInterface $container): CommandHandlerMiddleware
{
return new CommandHandlerMiddleware(
$container->get(CommandNameExtractor::class),
$container->get(HandlerLocator::class),
$container->get(MethodNameInflector::class)
);
}
}
<file_sep>/test/Event/CommandReceivedEventTest.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\TacticianTest\Event;
use FrankVerhoeven\Tactician\Event\CommandEventInterface;
use FrankVerhoeven\Tactician\Event\CommandReceivedEvent;
use PHPUnit\Framework\TestCase;
/**
* @author <NAME> <<EMAIL>>
*/
final class CommandReceivedEventTest extends TestCase
{
public function testConstructor(): void
{
$event = new CommandReceivedEvent($command = new \stdClass());
self::assertSame($command, $event->command());
self::assertEquals(\stdClass::class . CommandEventInterface::RECEIVED, $event->getName());
}
}
<file_sep>/README.md
# Tactician for Zend Expressive
[](https://travis-ci.com/frankverhoeven/tactician)
[](https://coveralls.io/github/frankverhoeven/tactician?branch=master)
<file_sep>/src/Handler/CommandHandlerMapper/ConfigMapper.php
<?php
declare(strict_types=1);
namespace FrankVerhoeven\Tactician\Handler\CommandHandlerMapper;
use League\Tactician\Exception\MissingHandlerException;
/**
* @author <NAME> <<EMAIL>>
*/
final class ConfigMapper implements CommandHandlerMapperInterface
{
/**
* @var string[]
*/
private $commandToHandlerMap;
/**
* @param string[] $commandToHandlerMap
*/
public function __construct(array $commandToHandlerMap)
{
$this->commandToHandlerMap = $commandToHandlerMap;
}
/**
* @inheritdoc
*/
public function getHandlerNameForCommandName(string $commandName): string
{
if (!isset($this->commandToHandlerMap[$commandName])) {
throw MissingHandlerException::forCommand($commandName);
}
return $this->commandToHandlerMap[$commandName];
}
}
|
b53c9f86d5f48d416f4de4b5352b8d6cb3a20fbe
|
[
"Markdown",
"PHP"
] | 31
|
PHP
|
frankverhoeven/tactician
|
5610c8ad6216b630013b63989d4de5734caf5176
|
48254753913d91a0c34fe87af612106d117ef5c3
|
refs/heads/master
|
<repo_name>TaffarelXavier/converter-classe-para-funcao<file_sep>/utils/ConverterHtmlToReact.js
const handleEstrutuaReactNextJs = entrada => {
let reactApp = `import React, { useState } from 'react';
import Head from 'next/head';
const App = () => {`;
reactApp += `
return (
<>
<Head>
<title>Título aqui</title>
</Head>
${entrada}
</>
);
\n\n }`;
reactApp += "\n\nexport default App;";
return reactApp;
};
function cleanPropertyName(name) {
// turn things like 'align-items' into 'alignItems'
name = name.replace(/(-.)/g, function(v) {
return v[1].toUpperCase();
});
return name;
}
function handleConvertHtmlToReact(entrada) {
let regexImg = /((<img\s+[^>]*src="([^"]*)")[^\/>]*>|\<img?[^\/]>)/g;
let removeTagScript = /<script[^>]*>|<\/(script|scripts)>/gi;
let removeTagScriptWithContent = /<script[^>]*>(.*?)<\/(script|scripts)>/gms;
let removeTagStyle = /<style>(.*?)<\/(style)>/gms;
let removeAllComment = /<!--[\s\S]*?-->/g;
let removeDoctype = /<!(DOCTYPE|doctype)[^>[]*(\[[^]]*\])?>/;
let replaceheadByHead = [/<head[^>]*>/, /<\/head\>/]; //Array Two items
let removeTagHtml = /<(html)\s[^>]*>|<\/(html)>/gm; //Array Two items
let metaUpdateCharset = /charset/g;
const regexCssStyle = /style=((".*?"|'.*?'|[^"'][^\s]*))/g;
const replaceTagMeta = /(<meta[^>]+)>/g;
const replaceTagInput = /(<input[^\/>]+)>/g;
const replaceTagLink = /(<link[^>]+)>/g;
const replaceTagBodyByMain = /<(body)\s[^>]*>|<\/(body)>/g;
const replaceBr = /<br\s\S[^\/]+>|<br\s+>|<br>/gm;
const replaceCrossOrigin = /crossorigin\=/gm;
const autofocus = /autofocus\=/gm;
const replaceHr = /(<hr>|<hr\s+>)/gm;
/***
*
*
* |
*/
entrada = entrada.replace(regexImg, " $2 />");
entrada = entrada.replace(removeTagHtml, "");
entrada = entrada.replace(replaceTagMeta, "$1/>");
entrada = entrada.replace(replaceTagLink, "$1/>");
entrada = entrada.replace(replaceTagBodyByMain, "$1");
entrada = entrada.replace(removeTagScriptWithContent, "");
entrada = entrada.replace(removeTagScript, "");
entrada = entrada.replace(replaceheadByHead[0], "<Head>");
entrada = entrada.replace(replaceheadByHead[1], "</Head>");
entrada = entrada.replace(removeAllComment, "");
entrada = entrada.replace(removeDoctype, "");
entrada = entrada.replace(replaceTagInput, "$1 />");
entrada = entrada.replace(removeTagStyle, ""); //Remove a tag style e todo seu conteúdo
//entrada = entrada.replace(/\r?\n|\r/g, ""); //Remove the line breaks
entrada = entrada.replace(/class\=/g, "className=");
entrada = entrada.replace(metaUpdateCharset, "charSet");
entrada = entrada.replace(replaceCrossOrigin, "crossOrigin=");
entrada = entrada.replace(replaceBr, "<br/>");
entrada = entrada.replace(autofocus, "autoFocus=");
entrada = entrada.replace(replaceHr, "<hr/>");
entrada = entrada.replace(regexCssStyle, function(ev) {
let stilos = cleanPropertyName(
ev.replace(/style=\"|\"/gs, "")
.replace(/\;/g, ",")
.replace(/px/g,'')
);
return `style={{${stilos}}}`;
});
return handleEstrutuaReactNextJs(entrada);
}
export default handleConvertHtmlToReact;
<file_sep>/utils/ConverterClassToFunction.js
/*
this.setState\(state\s+\=\>\s+\(\{\n+\s+.*?\n+\s+?\}\)\)\;
*/
/**
*
* @param {*} entrada
*/
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
const converterClassToFunction = entrada => {
//
let arr = entrada.split("\n");
if (!entrada.length) return "O código está em branco";
let saida = "";
let className = "";
arr.map((linha, index) => {
let classe = linha.match(/class\s+(\w+)/);
if (Boolean(linha.match(/this\.props\.\w+/gm))) {
//
saida += linha.replace(/this\.(props\.(\w+))/gm, "$1") + "\n";
} else if (Boolean(classe)) {
//
className = classe[1];
saida += `const ${className} = (props) => {\n`;
} else if (Boolean(linha.match(/\s+?render\(\)\s+{/gm))) {
//
saida += "\n";
} else if (Boolean(linha.match(/constructor\(.*?\)\s+\{/gm))) {
//
linha.replace(/constructor\(.*?\)\s+\{/gm, "");
} else if (Boolean(linha.match(/super\(props\)\;/gm))) {
//
linha.replace(/super\(props\)\;/gm, "");
} else if (Boolean(linha.match(/\s+?this\.state\s+\=/gm))) {
//Meus hooks:
let objHooks = linha
.replace(/\s+?this\.state\s+\=/gm, "")
.trim()
.replace(/^\{/, "");
var properties = objHooks.replace("};", "").split(", ");
let obj = "\n";
properties.forEach(function(property) {
//
let tup = property.split(":");
let objHook = tup[0].trim();
let valorInicialHook = tup[1];
//Para verificar se o valor é array
if (valorInicialHook.match(/(\[\])|(\[\s+\])/)) {
obj += `\tconst [${objHook}, set${objHook.capitalize()}] = useState(${valorInicialHook.trim()});\n`;
} else {
//demais valores:
obj += `\tconst [${objHook}, set${objHook.capitalize()}] = useState(${valorInicialHook.trim()});\n`;
}
});
saida += obj + "\n";
} else if (
Boolean(linha.match(/(\s+?this\.\w+|(this\.\w+\(\))|state\.\w+)/gm))
) {
//
let data = linha.match(/(\s+?this\.\w+|(this\.\w+\(\))|state\.\w+)/gm);
if (data) {
data.map(el => {
if (el.trim().startsWith("state")) {
saida += el.replace(/state.(\w+)/, "{$1}");
} else if (el.trim().startsWith("this")) {
saida += el.replace(/this\.(\w+)/, "{$1}");
}
});
}
} else {
saida += linha + "\n";
}
});
let text = saida.replace(/\}\n\}/, "\n}\n");
text += `export default ${className};`;
return text.replace(/\)\;.*[\}].*\)\;/gms,');\n}\n');
};
export default converterClassToFunction; <file_sep>/components/HtmlToReact/index.js
import React, { useState } from "react";
import Head from "./Head";
import ConverterHtmlToReact from "../../utils/ConverterHtmlToReact";
import { CopyToClipboard } from "react-copy-to-clipboard";
const App = () => {
const [entrada, setCodigo] = useState("");
const [copiado, setCopy] = useState(false);
const [saida, setSaida] = useState("");
const handleConvert = ev => {
setCodigo(ev.target.value);
};
const handleClick = ev => {
setSaida(ConverterHtmlToReact(entrada));
};
return (
<>
<Head />
<div id="general-container">
<header className="header-page">
<div className="logo">
<a href="#">
<img src="assets/img/logo.svg" alt="logo do site" height="90" />
</a>
</div>
</header>
<main>
<header className="description">
<h1>Conversor de HTML para React JS em JavaScript.</h1>
{/* <h3>Converta classes...</h3> */}
</header>
<section className="converter">
<div className="class-container">
<form action="" method="post" className="runcode">
<section className="desc-and-sub">
<label htmlFor="">
<strong>Copy your code here!</strong>
</label>
<button type="button" onClick={handleClick} className="btn">
Convert
</button>
</section>
<textarea
name=""
id=""
cols="50"
rows="50"
autoFocus
required
value={entrada}
onChange={ev => setCodigo(ev.target.value)}
spellCheck="false"
></textarea>
</form>
</div>
<div className="class-container">
<form action="" method="post" className="runcode">
<section className="desc-and-sub">
<label htmlFor="">
<strong>Your converted code.</strong>
</label>
<CopyToClipboard text={saida} onCopy={() => setCopy(true)}>
<button type="button" className="btn">
Copy to clipboard
</button>
</CopyToClipboard>
</section>
<textarea
name=""
id=""
cols="50"
rows="50"
spellCheck="false"
value={saida}
onChange={ev => setSaida(ev.target.value)}
></textarea>
</form>
</div>
</section>
</main>
<footer>
<section className="sect">
<h3>O Projeto</h3>
<p>
Este projeto é um conversor de codigos HTML, CSS e JavaScript para
React...
</p>
</section>
<section className="sect">
<h4>Seja um colaboradador deste projeto:</h4>
<a
href="https://github.com/TaffarelXavier/converter-classe-para-funcao"
target="_blank"
>
projeto github
</a>
</section>
<section className="copyright">©2020 - <NAME></section>
</footer>
</div>
</>
);
};
export default App;
<file_sep>/pages/index.js
import React, { useState } from "react";
import { Container, Row, Col, Button } from "react-bootstrap";
import Form from "react-bootstrap/Form";
import { CopyToClipboard } from "react-copy-to-clipboard";
import Highlight from "react-highlight";
import converterClassToFunction from "../utils/ConverterClassToFunction";
import Head from "next/head";
export default () => {
const [iniciado, setIniciado] = useState(false);
const [
entrada,
setEntrada
] = useState(`class HelloMessage extends React.Component {
render() {
return (
<div>
Olá, {this.props.name}!
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="Taylor" />,
document.getElementById('hello-example')
);`);
const [textFormated, setTextFormated] = useState("");
const [copiado, setCopy] = useState(false);
const handleChange = ev => {
let entrada = ev.target.value;
setEntrada(entrada);
};
const handlerConvert = () => {
setIniciado(true);
setTextFormated(converterClassToFunction(entrada));
};
return (
<>
<Head>
<title>Conveter Classe para Função em React JS</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/dracula.min.css" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="<KEY>"
crossorigin="anonymous"
/>
<meta property="og:site_name" content="Converter classe para função javascript" />
<meta property="og:title" content="Converter classe para função javascript" />
<meta property="og:description" content="Converter uma classe para função javascript no padrão es6 de javascript." />
<meta
property="og:image"
content="https://github.com/TaffarelXavier/convert-class-to-function-react-js/blob/master/icon.png?raw=true"
/>
<meta property="og:type" content="website" />
</Head>
<Container>
<Row style={{ marginBottom: 40, marginTop: 40 }}>
<Col>
<h2>
Conversor de <b>classe</b> para <b>função</b> em javascript.
</h2>
</Col>
</Row>
<Row>
<Col md={6}>
<Form>
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Label>
<b>Before:</b>
</Form.Label>
<Form.Control
as="textarea"
rows="15"
value={entrada}
autoFocus
onChange={handleChange}
/>
</Form.Group>
<Button onClick={handlerConvert}>Converter</Button>
</Form>
</Col>
<Col md={6}>
{textFormated !== "" && iniciado ? (
<>
<label>
<b>After:</b>
</label>
<Highlight innerHTML={false}>{textFormated}</Highlight>
<CopyToClipboard text={textFormated} onCopy={() => setCopy(true)}>
<Button variant="primary" className="btn-block" type="submit">
Copiar para área de transferência
</Button>
</CopyToClipboard>
</>
) : (
<>
<label>
<b>After:</b>
</label>
<Highlight>
{`const HelloMessage = (props) => {
return (
<div>
Olá, {props.name}!
</div>
);
}
export default HelloMessage;`}
</Highlight>
</>
)}
</Col>
</Row>
<Row style={{ marginTop: 60 }}>
<Col>
<a
href="https://github.com/TaffarelXavier/converter-classe-para-funcao"
target="_blank"
>
Seja um colaboradador deste projeto:
<img
src="https://symbols.getvecta.com/stencil_81/41_github-tile.7833f77ccf.svg"
width={20}
/>
</a>
</Col>
</Row>
</Container>
</>
);
};
<file_sep>/pages/converter.js
import React, { useState } from "react";
import { Container, Row, Col, Button } from "react-bootstrap";
import Form from "react-bootstrap/Form";
import { CopyToClipboard } from "react-copy-to-clipboard";
import Highlight from "react-highlight";
import converterClassToFunction from "../utils/ConverterClassToFunction";
export default () => {
const [
entrada,
setEntrada
] = useState(`class HelloMessage extends React.Component {
render() {
return (
<div>
Olá, {this.props.name}!
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="Taylor" />,
document.getElementById('hello-example')
);`);
const [textFormated, setTextFormated] = useState("");
const [copiado, setCopy] = useState(false);
const handleChange = ev => {
let entrada = ev.target.value;
setEntrada(entrada);
setTextFormated(converterClassToFunction(entrada));
};
const handlerConvert = () => {
setTextFormated(converterClassToFunction(entrada));
};
return (
<Container>
<Row style={{ marginBottom: 40, marginTop: 40 }}>
<Col>
<h2>
Conversor de <b>classe</b> para <b>função</b> em javascript.
</h2>
</Col>
</Row>
<Row>
<Col md={6}>
<Form>
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Label>
<b>Before:</b>
</Form.Label>
<Form.Control
as="textarea"
rows="15"
value={entrada}
autoFocus
onChange={handleChange}
/>
</Form.Group>
<Button onClick={handlerConvert}>Converter</Button>
</Form>
</Col>
<Col md={6}>
{textFormated !== "" ? (
<>
<label>
<b>After:</b>
</label>
<Highlight innerHTML={false}>{textFormated}</Highlight>
<CopyToClipboard text={textFormated} onCopy={() => setCopy(true)}>
<Button variant="primary" className="btn-block" type="submit">
Copiar para área de transferência
</Button>
</CopyToClipboard>
</>
) : (
<></>
)}
</Col>
</Row>
<Row style={{ marginTop: 60 }}>
<Col>
<a href="https://github.com/TaffarelXavier/converter-classe-para-funcao" target="_blank">
Seja um colaboradador deste projeto:
<img
src="https://symbols.getvecta.com/stencil_81/41_github-tile.7833f77ccf.svg"
width={20}
/>
</a>
</Col>
</Row>
</Container>
);
};
<file_sep>/README.md
# Converter Classe para Função de Javascript
## Before:
``` javascript
class HelloMessage extends React.Component {
render() {
return (
<div>
Olá, {this.props.name}!
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="Taylor" />,
document.getElementById('hello-example')
);
```
## After:
``` javascript
const HelloMessage = (props) => {
return (
<div>
Olá, {props.name}!
</div>
);
}
export default HelloMessage;
```<file_sep>/components/HtmlToReact/Head.js
import React from "react";
import Head from "next/head";
const HeadApp = () => {
return (
<>
<Head>
<title>Convert HTML to React</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/dracula.min.css"
/>
<link rel="stylesheet" href="/assets/css/index.css" />
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="<KEY>"
crossorigin="anonymous"
/>
<meta property="og:site_name" content="Convert HTML to React." />
<meta property="og:title" content="Convert HTML to React." />
<meta
property="og:url"
content="https://reactconverter.now.sh/html-to-react"
/>
<meta property="og:locale" content="pt_br" />
<meta property="og:image:width" content="128" />
<meta property="og:image:height" content="128" />
<meta
property="og:description"
content="Cole algum código html no editor, e o programa o converterá para código react js."
/>
<meta
property="og:image"
content="https://reactconverter.now.sh/html-to-react.jpeg"
/>
<meta property="og:type" content="website" />
</Head>
</>
);
};
export default HeadApp;
<file_sep>/pages/html-to-react.js
import HtmlToReact from "../components/HtmlToReact";
export default HtmlToReact;
|
756de5f2142e059d99d6b7f7ef3beb957a493991
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
TaffarelXavier/converter-classe-para-funcao
|
6f91cb1a6ab02a4ab2837c438f57ed09fe77b41f
|
4aefb68cc5e19a0d8a42e559eca989913381e4c2
|
refs/heads/master
|
<file_sep>Piece = require('./../piece');
GameBoard = require('./../board');
class King extends Piece {
constructor(param) {
super(param);
this.type = "King";
this.init();
}
isValidMove(startx,starty,x,y) {
if(x > GameBoard.length || y > GameBoard.height) {
return false;
}
if(startx - x <= 1 && startx - x >= -1 && starty - y <= 1 && starty - y >= -1) {
return true;
} else {
return false;
}
}
getPath(startx,starty,x,y) {
var path = [];
path.push({x:startx,y:starty},{x:x,y:y})
return path;
}
}
module.exports = King;<file_sep># chess
To run you need Node js installed,
then cd into the chess folder,
<code>run npm install</code>
then <code>node server</code>
<file_sep>Piece = require('./../piece');
GameBoard = require('./../board');
ClassConstructor = require('./constructor');
class Pawn extends Piece {
constructor(param) {
super(param);
this.type = "Pawn";
this.upgrades = ["Queen","Bishop","Rook","Knight"];
this.init();
this.firstMove = true;
}
isValidMove(startx,starty,x,y) {
if(x > GameBoard.length || y > GameBoard.height) {
return false;
}
if(this.colour == "White") {
if(startx == x && starty == y+1 && !GameBoard.positionOccupied(x,y)) {
return true;
}
if(startx == x+1 && starty == y+1 && GameBoard.positionOccupied(x,y) && GameBoard.positionOccupied(x,y).colour != this.colour) {
return true;
}
if(startx == x-1 && starty == y+1 && GameBoard.positionOccupied(x,y) && GameBoard.positionOccupied(x,y).colour != this.colour) {
return true;
}
if(startx == x && starty == y+2 && this.firstMove && !GameBoard.positionOccupied(x,y)) {
return true;
}
} else if(this.colour == "Black") {
if(startx == x && starty == y-1 && !GameBoard.positionOccupied(x,y)) {
return true;
}
if(startx == x+1 && starty == y-1 && GameBoard.positionOccupied(x,y) && GameBoard.positionOccupied(x,y).colour != this.colour) {
return true;
}
if(startx == x-1 && starty == y-1 && GameBoard.positionOccupied(x,y) && GameBoard.positionOccupied(x,y).colour != this.colour) {
return true;
}
if(startx == x && starty == y-2 && !GameBoard.positionOccupied(x,y)&& this.firstMove) {
return true;
}
}
return false;
}
getPath(startx,starty,x,y) {
var path = [];
var diff = starty-y;
for(var i=0;i<diff;i++) {
path.push({x:x,y:y+i});
}
for(var i=0;i>diff;i--) {
path.push({x:x,y:y+i});
}
path.push({x:startx,y:starty});
return path;
}
requestUpgrade(socket) {
socket.emit('chooseUpgradePiece', {piece:this,choices:this.upgrades});
}
upgrade(type) {
var newPieceClass = ClassConstructor(type);
new newPieceClass({x:this.x,y:this.y,colour:this.colour});
this.remove();
}
}
module.exports = Pawn;<file_sep>GameBoard = require('./board');
Player = require('./player');
Piece = require('./piece');
Rook = require('./classes/rook');
King = require('./classes/king');
Knight = require('./classes/knight');
Pawn = require('./classes/pawn');
Queen = require('./classes/queen');
Bishop = require('./classes/bishop');
Player.sendUpdate = function() {
for(var i in SOCKET_LIST) {
var socket = SOCKET_LIST[i];
socket.emit('players', Player.getObjArray());
}
}
Player.leaveUpdate = function(player) {
for(var i in SOCKET_LIST) {
var socket = SOCKET_LIST[i];
socket.emit('playerLeave', player);
}
}
Piece.sendUpdate = function() {
for(var i in SOCKET_LIST) {
var socket = SOCKET_LIST[i];
socket.emit('pieces', Piece.list);
}
}
Piece.takePieceUpdate = function(piece) {
for(var i in SOCKET_LIST) {
var socket = SOCKET_LIST[i];
socket.emit('takePiece', piece);
}
}
GameBoard.turnUpdate = function() {
for(var i in SOCKET_LIST) {
var socket = SOCKET_LIST[i];
socket.emit('turnUpdate', {});
}
}
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var fs = require('fs');
app.get('/',function(req,res) {
res.sendFile(__dirname + '/client/index.html');
});
app.use ('/client',express.static(__dirname + '/client'));
serv.listen(2000);
console.log("server started");
var SOCKET_LIST = {};
var io = require('socket.io')(serv,{});
io.sockets.on('connection', function(socket){
socket.id = Math.random();
SOCKET_LIST[socket.id] = socket;
var address = socket.request.connection.remoteAddress;
socket.on('signIn', function(data){
if(GameBoard.gameInProgress || Player.list.length >= 2) {
socket.emit('signInResponse', {success:false});
return;
}
for(var i=0;i<Player.list.length;i++) {
var p = Player.list[i];
if(p.name == data.username) {
socket.emit('signInResponse', {success:false,name:data.username});
return;
}
}
Player.onConnect(socket,data.username,address);
socket.emit('signInResponse', {success:true});
});
socket.on('disconnect', function(){
if(GameBoard.gameInProgress && Player.fromSocket(socket)) {
Player.leaveUpdate(Player.fromSocket(socket).id);
}
delete SOCKET_LIST[socket.id];
Player.onDisconnect(socket);
});
});
<file_sep>Rook = require('./classes/rook');
Piece = require('./piece');
Player = require('./player');
ClassConstructor = require('./classes/constructor');
GameBoard = {};
GameBoard.layout = [["BRook","BKnight","BBishop","BQueen","BKing","BBishop","BKnight","BRook"],
["BPawn","BPawn","BPawn","BPawn","BPawn","BPawn","BPawn","BPawn"],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["","","","","","","",""],
["WPawn","WPawn","WPawn","WPawn","WPawn","WPawn","WPawn","WPawn"],
["WRook","WKnight","WBishop","WQueen","WKing","WBishop","WKnight","WRook"]];
GameBoard.height = GameBoard.layout.length-1;
GameBoard.length = GameBoard.layout[0].length-1;
GameBoard.gameInProgress = false;
GameBoard.swapTurn = function () {
for(var i=0;i<Player.list.length;i++) {
Player.list[i].turn = !Player.list[i].turn
}
GameBoard.turnUpdate();
}
GameBoard.init = function() {
if(!Player.allPlayersReady()) {
return;
}
for(var i=0;i<GameBoard.layout.length;i++) {
for(var j=0;j<GameBoard.layout[i].length;j++) {
var colour;
var type;
if(GameBoard.layout[i][j].substr(0,1) == "W") {
colour = "White";
} else if(GameBoard.layout[i][j].substr(0,1) == "B") {
colour = "Black";
}
type = GameBoard.layout[i][j].substr(1);
if(type != "") {
var newPieceClass = ClassConstructor(type);
new newPieceClass({x:j,y:i,colour:colour});
}
}
}
GameBoard.gameInProgress = true;
}
GameBoard.positionOccupied = function(x,y) {
for(var i=0;i<Piece.list.length;i++) {
if(Piece.list[i].x == x && Piece.list[i].y == y) {
return Piece.list[i];
}
}
return false;
}
//checks for check and checkmate
GameBoard.calcCheck = function(piecemoved) {
var kings = Piece.getKings();
for(var i=0;i<kings.length;i++) {
var player = Player.fromColour(kings[i].colour);
if(GameBoard.kingInCheck(kings[i])) {
player.inCheck = true;
console.log("player " + player.name + " in check");
if(GameBoard.inCheckMate(player,piecemoved)) {
Player.inCheckMate(player);
}
}
}
}
GameBoard.kingInCheck = function(king) {
for(var i=0;i<Piece.list.length;i++) {
var piece = Piece.list[i];
if(piece.colour == king.colour) {
continue;
}
var availMoves = piece.getAllValidMoves();
for(var j=0;j<availMoves.length;j++) {
var move = availMoves[j];
if(move.x == king.x && move.y == king.y && piece.colour != king.colour) {
return true;
}
}
}
return false;
}
GameBoard.doesEvadeCheck = function(player,piece,x,y) {
var result = false;
var kings = Piece.getKings();
var king = {};
for(var i=0;i<kings.length;i++) {
if(kings[i].colour == player.colour) {
king = kings[i];
}
}
const tempx = piece.x
const tempy = piece.y
var occtempx;
var occtempy;
var occPiece = {}
if(GameBoard.positionOccupied(x,y)) {
occPiece = GameBoard.positionOccupied(x,y)
occtempx = occPiece.x;
occtempy = occPiece.y;
occPiece.x = 100;
occPiece.y = 100;
}
piece.x = x;
piece.y = y;
if(GameBoard.kingInCheck(king)) {
result = false;
} else {
result = true;
}
piece.x = tempx;
piece.y = tempy;
if(occPiece != {}) {
occPiece.x = occtempx;
occPiece.y = occtempy;
}
return result;
}
GameBoard.kingSelfCheck = function(piece,x,y) { //not working
var result = false;
var kings = Piece.getKings();
var king = {};
for(var i=0;i<kings.length;i++) {
if(kings[i].colour == piece.colour) {
king = kings[i];
}
}
const tempx = piece.x
const tempy = piece.y
var occtempx;
var occtempy;
var occPiece = {}
if(GameBoard.positionOccupied(x,y)) {
occPiece = GameBoard.positionOccupied(x,y)
occtempx = occPiece.x;
occtempy = occPiece.y;
occPiece.x = 100;
occPiece.y = 100;
}
piece.x = x;
piece.y = y;
if(GameBoard.kingInCheck(king)) {
result = true;
} else {
result = false;
}
piece.x = tempx;
piece.y = tempy;
if(occPiece != {}) {
occPiece.x = occtempx;
occPiece.y = occtempy;
}
return result;
}
GameBoard.inCheckMate = function(player,piecemoved) {
//check for possible move
for(var i=0;i<Piece.list.length;i++) {
var piece = Piece.list[i];
if(piece.colour == player.colour) {
var moves = piece.getAllValidMoves();
for(var j=0;j<moves.length;j++) {
if(GameBoard.doesEvadeCheck(player,piece,moves[j].x,moves[j].y)) {
return false;
}
}
}
}
return true;
}
GameBoard.filterLegalMoves = function (piece,_moves) {
var moves = [];
for(var i=0;i<_moves.length;i++) {
if(GameBoard.kingSelfCheck(piece,_moves[i].x,_moves[i].y)) {
moves.push({x:_moves[i].x,y:_moves[i].y,legal:false});
} else {
moves.push({x:_moves[i].x,y:_moves[i].y,legal:true});
}
}
return moves;
}
GameBoard.isLegalMove = function(piece,x,y) {
if(GameBoard.kingSelfCheck(piece,x,y)) {
return false;
} else {
return true;
}
}
module.exports = GameBoard;
|
c6c6c5cad1ce8f3fc59e4a5432e9222348c03d46
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
joetheplatypus/chess
|
f038e70c726038fdaebf532629a309e71649e5fd
|
ac8571b2d80e361cf7bddfb8389e9c6ec3c14e5c
|
refs/heads/master
|
<repo_name>GerganaL/Spring-Advanced<file_sep>/musicdb/musicdb/src/main/java/bg/softuni/musicdb/model/binding/AlbumBindingModel.java
package bg.softuni.musicdb.model.binding;
public class AlbumBindingModel {
//TODO
}
|
a9bce8c4f5b03aa95ca1b9876a4acd80c0de3312
|
[
"Java"
] | 1
|
Java
|
GerganaL/Spring-Advanced
|
f5724484306c69f90f704c0071df51089b43c41b
|
ba863f8f0d492d1c51bc7f2af6614fc0d6afa40f
|
refs/heads/master
|
<file_sep>const request = require('supertest');
const app = require('../../index');
const expect = require('chai').expect;
const MESSAGE = require('../../MESSAGE.json');
const instance = require('../instance');
const Question = require('../../db/question');
const Qcategory = require('../../db/Qcategory');
const api = '/question';
const categoryAPI = '/qcategory';
describe('QUESTION API TEST', function() {
before(function() {
Question.destroy({
where: {},
});
Qcategory.destroy({
where: {},
});
});
let category, questionId;
/* Create a category to use test */
before(function() {
request(app)
.post(categoryAPI)
.set('authorization', 'Bearer ' + instance.token)
.send({
name: instance.name,
})
.then(function(res) {
category = res.body.list[0].id;
}).
catch(err => {
console.error(err);
});
});
describe('Read Question', function() {
it('should read question list', function(done) {
request(app)
.get(api)
.set('authorization', 'Bearer ' + instance.token)
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_READ_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_READ_SUCCESS_MESSAGE);
done();
})
.catch(done);
});
});
describe('Create Question', function() {
it('should create question failure when missing question', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
answer: instance.answer,
category: category,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_ADD_QUESTION_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_ADD_QUESTION_MESSAGE);
done();
})
.catch(done);
});
it('should create question failure when missing answer', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
question: instance.question,
category: category,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_ADD_ANSWER_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_ADD_ANSWER_MESSAGE);
done();
})
.catch(done);
});
it('should create question failure when missing category', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
question: instance.question,
answer: instance.answer,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_ADD_CATEGORY_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_ADD_CATEGORY_MESSAGE);
done();
})
.catch(done);
});
it('should create question success', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
question: instance.question,
answer: instance.answer,
category: category,
})
.expect(200)
.then(function(res) {
questionId = res.body.list[0].id;
expect(res.body.code).eq(MESSAGE.QUESTION_ADD_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_ADD_SUCCESS_MESSAGE);
expect(res.body.list[0].question).to.equal(instance.question);
expect(res.body.list[0].answer).to.equal(instance.answer);
expect(res.body.list[0].category).to.equal(category);
done();
})
.catch(done);
});
});
describe('Update Question', function() {
it(`should update question failure when id isn't exist`, function(done) {
request(app)
.put(api + '/' + instance.nonExistId)
.set('authorization', 'Bearer ' + instance.token)
.send({
question: instance.question,
answer: instance.answer,
category: category,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_UPDATE_ID_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_UPDATE_ID_MESSAGE);
done();
})
.catch(done);
});
it(`should update question failure when missing question`, function(done) {
request(app)
.put(api + '/' + questionId)
.set('authorization', 'Bearer ' + instance.token)
.send({
answer: instance.updateAnswer,
category: category,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_UPDATE_QUESTION_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_UPDATE_QUESTION_MESSAGE);
done();
})
.catch(done);
});
it(`should update question failure when missing answer`, function(done) {
request(app)
.put(api + '/' + questionId)
.set('authorization', 'Bearer ' + instance.token)
.send({
question: instance.updateQuestion,
category: category,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_UPDATE_ANSWER_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_UPDATE_ANSWER_MESSAGE);
done();
})
.catch(done);
});
it(`should update question failure when missing category`, function(done) {
request(app)
.put(api + '/' + questionId)
.set('authorization', 'Bearer ' + instance.token)
.send({
answer: instance.updateAnswer,
question: instance.updateQuestion,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_UPDATE_CATEGORY_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_UPDATE_CATEGORY_MESSAGE);
done();
})
.catch(done);
});
it(`should update question success`, function(done) {
// const data = ;
request(app)
.put(api + '/' + questionId)
.set('authorization', 'Bearer ' + instance.token)
.send({
question: instance.updateQuestion,
answer: instance.updateAnswer,
category: category,
})
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.QUESTION_UPDATE_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.QUESTION_UPDATE_SUCCESS_MESSAGE);
expect(res.body.list[0].id).to.equal(questionId);
expect(res.body.list[0].question).to.equal(instance.updateQuestion);
expect(res.body.list[0].answer).to.equal(instance.updateAnswer);
expect(res.body.list[0].category).to.equal(category);
done();
})
.catch(done);
});
});
describe('Remove Question', function() {
it(`should delete question failure when id isn't exist`, function(done) {
request(app)
.delete(api + '/' + instance.nonExistId)
.set('authorization', 'Bearer ' + instance.token)
.expect(400)
.then(function(res) {
expect(res.body.code).to.eq(MESSAGE.QUESTION_DELETE_ID_CODE);
expect(res.body.message).to.eq(MESSAGE.QUESTION_DELETE_ID_MESSAGE);
done();
})
.catch(done);
});
it(`should delete question success`, function(done) {
request(app)
.delete(api + '/' + questionId)
.set('authorization', 'Bearer ' + instance.token)
.expect(200)
.then(function(res) {
expect(res.body.code).to.eq(MESSAGE.QUESTION_DELETE_SUCCESS_CODE);
expect(res.body.message).to.eq(MESSAGE.QUESTION_DELETE_SUCCESS_MESSAGE);
done();
})
.catch(done);
});
});
/* Delete the category */
after(function(done) {
request(app)
.delete(categoryAPI + '/' + category)
.set('authorization', 'Bearer ' + instance.token)
.then(function() {
done();
})
.catch(done);
});
});
<file_sep>// jwt
const jwt = require('jsonwebtoken');
const config = require('../config');
const MESSAGE = require('../MESSAGE.json');
const auth = (req, res, next) => {
let token = req.headers["authorization"];
if (!token) {
console.log(MESSAGE.AUTH_NO_TOKEN_MESSAGE);
return res.status(401).send({
code: MESSAGE.AUTH_NO_TOKEN_CODE,
message: MESSAGE.AUTH_NO_TOKEN_MESSAGE,
});
}
try {
// remove 'Bearer ' from string;
token = token.slice(7);
const decode = jwt.verify(token, config.privateKey);
req.user = decode;
next();
} catch (err) {
console.error(err);
return res.status(400).send({
code: MESSAGE.AUTH_INVALID_TOKEN_CODE,
message: MESSAGE.AUTH_INVALID_TOKEN_MESSAGE,
});
}
};
module.exports = auth;
<file_sep>const expect = require('chai').expect;
const MESSAGE = require('../../MESSAGE.json');
const sinon = require('sinon');
const checkRole = require('../../middleware/checkRole');
describe('MIDDLEWARE/CHECKROLE TEST CASES', function() {
describe('Check the role', function() {
it('should failure when the role is user', function() {
const spy = sinon.spy();
const mockResponse = () => {
const res = {};
res.status = sinon.stub().returns(res);
res.send = sinon.stub().returns(res);
return res;
};
var res = mockResponse();
checkRole({
user: { role: 1, }
}, res, spy);
expect(res.status.calledWith(403)).to.eq(true);
expect(res.send.calledWith({
code: MESSAGE.CHECKROLE_FORBIDDEN_CODE,
message: MESSAGE.CHECKROLE_FORBIDDEN_MESSAGE,
})).to.eq(true);
expect(spy.calledOnce).to.eq(false);
});
it('should success when the role is admin', function() {
const spy = sinon.spy();
checkRole({user: { role: 0, }}, {}, spy);
expect(spy.calledOnce).to.eq(true);
});
});
});
<file_sep>[](https://david-dm.org/chesterchenn/colors-api)
This project was used with [Express](https://expressjs.com/).<file_sep>/* 登录页面 */
const express = require('express');
const router = express.Router();
const User = require('../db/userSequelize');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const config = require('../config');
const MESSAGE = require('../MESSAGE.json');
const bcrypt = require('bcrypt');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
/**
* @api {post} /login login
* @apiName login
* @apiGroup Login
*
* @apiParam {String} user user name
* @apiParam {String} password user <PASSWORD>
*
* @apiSuccess {String} code code of the response.
* @apiSuccess {String} message message of the response.
* @apiSuccess {String} user user of the user.
* @apiSuccess {Number} role role of the user.
* @apiSuccess {String} token token of the user.
*
* @apiError {String} code code of the Error.
* @apiError {String} message message of the Error.
*/
router.route('/')
.post((req, res, next) => {
const user = req.body.user;
const password = <PASSWORD>;
User.findOne({
raw: true,
where: { user, }
}).then(task => {
bcrypt.compare(password, task.password, (err, result) => {
if (err) {
console.error(err);
err.message = MESSAGE.LOGIN_READ_FAILURE_MESSAGE;
err.code = MESSAGE.LOGIN_READ_FAILURE_CODE;
return next(err);
}
if (result) {
const token = jwt.sign({
id: task.id,
user: task.user,
role: task.role,
}, config.privateKey);
res.status(200).send({
code: MESSAGE.LOGIN_READ_SUCCESS_CODE,
message: MESSAGE.LOGIN_READ_SUCCESS_MESSAGE,
user: task.user,
role: task.role,
token,
});
}
if (!result) {
const err = new Error(MESSAGE.LOGIN_READ_FAILURE_MESSAGE);
err.code = MESSAGE.LOGIN_READ_FAILURE_CODE;
console.error(err);
return next(err);
}
});
}).catch(err => {
console.error(err);
err.code = MESSAGE.LOGIN_READ_FAILURE_CODE;
err.message = MESSAGE.LOGIN_READ_FAILURE_MESSAGE;
return next(err);
});
});
module.exports = router;
<file_sep>module.exports = {
answer: 'This is a Answer!',
cname: '测试名称',
hex: '#000000',
name: 'testName',
nonExistId: -1111,
password: '<PASSWORD>',
question: 'This is a problem?',
shortPasswd: '<PASSWORD>',
updateAnswer: '这是一个回答!',
updateCname: '更新名称',
updateHex: '#FFFFFF',
updatePassword: '<PASSWORD>',
updateQuestion: '这是一个问题?',
updateName: 'Update Name',
admin: 'admin',
adminPasswd: '<PASSWORD>',
// You should have own token in here. The token just an example.
token: '<KEY>',
expiredToken: '<KEY>',
};
<file_sep>const request = require('supertest');
const app = require('../../index');
const expect = require('chai').expect;
const instance = require('../instance');
const MESSAGE = require('../../MESSAGE.json');
const Category = require('../../db/categorySequelize');
const api = '/category';
describe('CATEGORY API TEST', function() {
before(function() {
Category.destroy({
where: {},
});
});
let instanceId = '';
describe('Read category list', function() {
it('should read category', function(done) {
request(app)
.get(api)
.set('authorization', 'Bearer ' + instance.token)
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_READ_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_READ_SUCCESS_MESSAGE);
done();
})
.catch(done);
});
});
describe('Create category', function() {
it('should create category failure when missing name', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
cname: instance.cname,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_ADD_NAME_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_ADD_NAME_MESSAGE);
done();
})
.catch(done);
});
it('should create category failure when missing cname', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
name: instance.name,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_ADD_CNAME_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_ADD_CNAME_MESSAGE);
done();
})
.catch(done);
});
it('should create category success', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
name: instance.name,
cname: instance.cname,
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.then(function(res) {
instanceId = res.body.list[0].id;
expect(res.body.code).eq(MESSAGE.CATEGORY_ADD_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_ADD_SUCCESS_MESSAGE);
expect(res.body.list[0].name).to.equal(instance.name);
expect(res.body.list[0].cname).to.equal(instance.cname);
done();
})
.catch(done);
});
});
describe('Update Category', function() {
it(`should update category failure when id isn't exist`, function(done) {
request(app)
.put(api + '/' + instance.nonExistId)
.set('authorization', 'Bearer ' + instance.token)
.send({
name: instance.updateName,
cname: instance.updateCname,
})
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_UPDATE_ID_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_UPDATE_ID_MESSAGE);
done();
})
.catch(done);
});
it(`should update category failure when missing name`, function(done) {
request(app)
.put(api + '/' + instanceId)
.set('authorization', 'Bearer ' + instance.token)
.send({
cname: instance.updateCname,
})
.expect('Content-Type', /json/)
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_UPDATE_NAME_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_UPDATE_NAME_MESSAGE);
done();
})
.catch(done);
});
it(`should update category failure when missing cname`, function(done) {
request(app)
.put(api + '/' + instanceId)
.set('authorization', 'Bearer ' + instance.token)
.send({
name: instance.updateName,
})
.expect('Content-Type', /json/)
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_UPDATE_CNAME_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_UPDATE_CNAME_MESSAGE);
done();
})
.catch(done);
});
it(`should update category success`, function(done) {
request(app)
.put(api + '/' + instanceId)
.set('authorization', 'Bearer ' + instance.token)
.send({
name: instance.updateName,
cname: instance.updateCname,
})
.expect('Content-Type', /json/)
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.CATEGORY_UPDATE_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.CATEGORY_UPDATE_SUCCESS_MESSAGE);
expect(res.body.list[0].id).to.equal(instanceId);
expect(res.body.list[0].name).to.equal(instance.updateName);
expect(res.body.list[0].cname).to.equal(instance.updateCname);
done();
})
.catch(done);
});
});
describe('Remove Category', function() {
it(`should delete category failure when id isn't exist`, function(done) {
request(app)
.delete(api + '/' + instance.nonExistId)
.set('authorization', 'Bearer ' + instance.token)
.expect(400)
.then(function(res) {
expect(res.body.message).to.eq(MESSAGE.CATEGORY_DELETE_ID_MESSAGE);
expect(res.body.code).to.eq(MESSAGE.CATEGORY_DELETE_ID_CODE);
done();
})
.catch(done);
});
it('should delete category success', function(done) {
request(app)
.delete(api + '/' + instanceId)
.set('authorization', 'Bearer ' + instance.token)
.expect('Content-Type', /json/)
.expect(200)
.then(function(res) {
expect(res.body.message).to.eq(MESSAGE.CATEGORY_DELETE_SUCCESS_MESSAGE);
expect(res.body.code).to.eq(MESSAGE.CATEGORY_DELETE_SUCCESS_CODE);
done();
})
.catch(done);
});
});
});
<file_sep>/* question category model*/
const Sequelize = require('sequelize');
const sequelize = require('./sequelize');
class Qcategory extends Sequelize.Model {}
Qcategory.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
},
createdAt: {
type: Sequelize.DATE,
defaultValue: new Date(),
field: 'created_at',
}
}, {
tableName: 'question_category',
sequelize,
});
module.exports = Qcategory;
<file_sep>/* question model*/
const Sequelize = require('sequelize');
const sequelize = require('./sequelize');
const Qcategory = require('./Qcategory');
class Question extends Sequelize.Model {}
Question.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
question: {
type: Sequelize.TEXT,
allowNull: false,
},
answer: {
type: Sequelize.TEXT,
allowNull: false,
},
category: {
type: Sequelize.INTEGER,
references: {
model: Qcategory,
key: 'id',
},
},
createdAt: {
type: Sequelize.DATE,
defaultValue: new Date(),
field: 'created_at',
}
}, {
tableName: 'question',
sequelize,
});
module.exports = Question;
<file_sep>/* 颜色页面 */
const express = require('express');
const router = express.Router();
const Colors = require('../db/colorsSequelize');
const Category = require('../db/categorySequelize');
const bodyParser = require('body-parser');
const MESSAGE = require('../MESSAGE.json');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.route('/')
.get((req, res, next) => {
const current = ~~req.query.current || 1;
const perPage = ~~req.query.perPage || 10;
Colors.findAndCountAll({
limit: perPage,
offset: (current - 1) * perPage,
raw: true
}).then(task => {
res.status(200).send({
code: MESSAGE.COLORS_READ_SUCCESS_CODE,
message: MESSAGE.COLORS_READ_SUCCESS_MESSAGE,
current,
perPage,
count: task.count,
list: task.rows,
});
}).catch(err => {
console.error(err);
err.code = MESSAGE.COLORS_READ_FAILURE_CODE;
err.message = MESSAGE.COLORS_READ_FAILURE_MESSAGE;
return next(err);
});
})
.post((req, res, next) => {
const body = req.body;
if (!body.name) {
const err = new Error(MESSAGE.COLORS_ADD_NAME_MESSAGE);
err.code = MESSAGE.COLORS_ADD_NAME_CODE;
return next(err);
}
if (!body.cname) {
const err = new Error(MESSAGE.COLORS_ADD_CNAME_MESSAGE);
err.code = MESSAGE.COLORS_ADD_CNAME_CODE;
return next(err);
}
if (!body.hex) {
const err = new Error(MESSAGE.COLORS_ADD_LACKHEX_MESSAGE);
err.code = MESSAGE.COLORS_ADD_LACKHEX_CODE;
return next(err);
}
Category.findByPk(body.categoryId).then(cateResult => {
if (!cateResult) {
const err = new Error(MESSAGE.COLORS_ADD_CATEGORY_MESSAGE);
err.code = MESSAGE.COLORS_ADD_CATEGORY_CODE;
return next(err);
}
Colors.create({
hex: body.hex,
name: body.name,
fontColor: body.fontColor,
cname: body.cname,
categoryId: body.categoryId,
})
.then(task => {
const plainTask = task.get({
plain: true
});
res.status(200).send({
code: MESSAGE.COLORS_ADD_SUCCESS_CODE,
message: MESSAGE.COLORS_ADD_SUCCESS_MESSAGE,
list: [plainTask],
});
})
.catch(err => {
if (err.errors[0].type === 'unique violation') {
err.message = MESSAGE.COLORS_ADD_HEX_MESSAGE;
err.code = MESSAGE.COLORS_ADD_HEX_CODE;
}
return next(err);
});
}).catch(err => {
console.error(err);
err.code = MESSAGE.COLORS_ADD_FAILURE_CODE;
err.message = MESSAGE.COLORS_ADD_FAILURE_MESSAGE;
});
});
router.route('/:id')
.put((req, res, next) => {
const id = req.params.id;
const body = req.body;
Colors.findByPk(id).then(result => {
if (result === null) {
const err = new Error(MESSAGE.COLORS_UPDATE_ID_MESSAGE);
err.code = MESSAGE.COLORS_UPDATE_ID_CODE;
return next(err);
}
Category.findByPk(body.categoryId).then(cateResult => {
if (!cateResult) {
const err = new Error(MESSAGE.COLORS_UPDATE_CATEGORY_MESSAGE);
err.code = MESSAGE.COLORS_UPDATE_CATEGORY_CODE;
return next(err);
}
if (!body.name) {
const err = new Error(MESSAGE.COLORS_UPDATE_NAME_MESSAGE);
err.code = MESSAGE.COLORS_UPDATE_NAME_CODE;
return next(err);
}
if (!body.cname) {
const err = new Error(MESSAGE.COLORS_UPDATE_CNAME_MESSAGE);
err.code = MESSAGE.COLORS_UPDATE_CNAME_CODE;
return next(err);
}
if (!body.hex) {
const err = new Error(MESSAGE.COLORS_UPDATE_LACKHEX_MESSAGE);
err.code = MESSAGE.COLORS_UPDATE_LACKHEX_CODE;
return next(err);
}
Colors.update({
hex: body.hex,
name: body.name,
fontColor: body.fontColor,
cname: body.cname,
categoryId: body.categoryId,
}, {
returning: true, where: { id: id }
})
.then(Colors.findByPk(id).then(oldTask => {
oldTask.reload().then(task => {
const plainTask = task.get({
plain: true
});
res.status(200).send({
code: MESSAGE.COLORS_UPDATE_SUCCESS_CODE,
message: MESSAGE.COLORS_UPDATE_SUCCESS_MESSAGE,
list: [plainTask],
});
});
}))
.catch(err => {
console.error(err);
if (err.errors[0].type === 'unique violation') {
err.message = MESSAGE.COLORS_ADD_HEX_MESSAGE;
err.code = MESSAGE.COLORS_ADD_HEX_CODE;
}
return next(err);
});
});
})
.catch(err => {
console.error(err);
err.code = MESSAGE.COLORS_UPDATE_FAILURE_CODE;
err.message = MESSAGE.COLORS_UPDATE_FAILURE_MESSAGE;
return next(err);
});
})
.delete((req, res, next) => {
const deleteId = req.params.id;
Colors.findByPk(deleteId).then(result => {
if (!result) {
const err = new Error(MESSAGE.COLORS_DELETE_ID_MESSAGE);
err.code = MESSAGE.COLORS_DELETE_ID_CODE;
return next(err);
}
Colors.destroy({
where: { id: deleteId }
})
.then(() => {
res.status(200).send({
message: MESSAGE.COLORS_DELETE_SUCCESS_MESSAGE,
code: MESSAGE.COLORS_DELETE_SUCCESS_CODE,
});
})
.catch(err => {
console.error(err);
err.code = MESSAGE.COLORS_DELETE_FAILURE_CODE;
err.message = MESSAGE.COLORS_DELETE_FAILURE_MESSAGE;
return next(err);
});
});
});
module.exports = router;
<file_sep>const request = require('supertest');
const app = require('../../index');
const expect = require('chai').expect;
const MESSAGE = require('../../MESSAGE.json');
const instance = require('../instance');
const User = require('../../db/userSequelize');
const api = '/user';
const sinon = require('sinon');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
describe('USER API TEST', function() {
before(function() {
sinon.stub(console, "error");
User.destroy({
where: {
user: {
[Op.ne]: 'admin',
}
},
});
});
let userId = '';
describe('Create user', function() {
it('should create user success', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
user: instance.name,
password: <PASSWORD>,
})
.expect(200)
.then(function(res) {
userId = res.body.list[0].id;
expect(res.body.code).eq(MESSAGE.USER_ADD_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.USER_ADD_SUCCESS_MESSAGE);
expect(res.body.list[0].user).to.equal(instance.name);
done();
})
.catch(done);
});
it('should create user failure when no user', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
password: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_ADD_NO_USER_CODE);
expect(res.body.message).eq(MESSAGE.USER_ADD_NO_USER_MESSAGE);
done();
})
.catch(done);
});
it('should create user failure when no password', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
user: instance.name,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_ADD_NO_PASSWD_CODE);
expect(res.body.message).eq(MESSAGE.USER_ADD_NO_PASSWD_MESSAGE);
done();
})
.catch(done);
});
it('should create user failure when password length too short', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
user: instance.name,
password: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_ADD_PASSWD_LENGTH_CODE);
expect(res.body.message).eq(MESSAGE.USER_ADD_PASSWD_LENGTH_MESSAGE);
done();
})
.catch(done);
});
it('should create user failure when user is exist', function(done) {
request(app)
.post(api)
.set('authorization', 'Bearer ' + instance.token)
.send({
user: instance.name,
password: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_ADD_USER_EXIST_CODE);
expect(res.body.message).eq(MESSAGE.USER_ADD_USER_EXIST_MESSAGE);
done();
})
.catch(done);
});
});
describe('Read user list', function() {
it('should read user list success', function(done) {
request(app)
.get(api)
.set('authorization', 'Bearer ' + instance.token)
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_READ_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.USER_READ_SUCCESS_MESSAGE);
done();
})
.catch(done);
});
});
describe('Update user', function() {
it('should update password failure when user is not exist', function(done) {
request(app)
.put(api + '/' + instance.nonExistId)
.set('authorization', 'Bearer ' + instance.token)
.send({
oldPassword: <PASSWORD>,
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_USER_NO_EXIST_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_USER_NO_EXIST_MESSAGE);
done();
})
.catch(done);
});
it('should update password failure when no old password', function(done) {
request(app)
.put(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.send({
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_OLD_PASSWD_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_OLD_PASSWD_MESSAGE);
done();
})
.catch(done);
});
it('should update password failure when no new password', function(done) {
request(app)
.put(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.send({
oldPassword: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_NEW_PASSWD_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_NEW_PASSWD_MESSAGE);
done();
})
.catch(done);
});
it('should update password failure when new password too short', function(done) {
request(app)
.put(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.send({
oldPassword: <PASSWORD>,
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_NEW_PASSWD_LENGTH_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_NEW_PASSWD_LENGTH_MESSAGE);
done();
})
.catch(done);
});
it('should update password failure when new password was difference', function(done) {
request(app)
.put(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.send({
oldPassword: <PASSWORD>,
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_NEW_PASSWD_DIFF_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_NEW_PASSWD_DIFF_MESSAGE);
done();
})
.catch(done);
});
it('should update password failure when old password was error', function(done) {
request(app)
.put(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.send({
oldPassword: <PASSWORD>,
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_OLD_PASSWD_COMPARE_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_OLD_PASSWD_COMPARE_MESSAGE);
done();
})
.catch(done);
});
it('should update password success', function(done) {
request(app)
.put(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.send({
oldPassword: <PASSWORD>,
password: <PASSWORD>,
confirmPassword: <PASSWORD>,
})
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_UPDATE_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.USER_UPDATE_SUCCESS_MESSAGE);
done();
})
.catch(done);
});
});
describe('Remove User', function() {
it('should delete user failure when user is not exist', function(done) {
request(app)
.delete(api + '/' + instance.nonExistId)
.set('authorization', 'Bearer ' + instance.token)
.expect(400)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_DELETE_ID_CODE);
expect(res.body.message).eq(MESSAGE.USER_DELETE_ID_MESSAGE);
done();
})
.catch(done);
});
it('should delete user success', function(done) {
request(app)
.delete(api + '/' + userId)
.set('authorization', 'Bearer ' + instance.token)
.expect(200)
.then(function(res) {
expect(res.body.code).eq(MESSAGE.USER_DELETE_SUCCESS_CODE);
expect(res.body.message).eq(MESSAGE.USER_DELETE_SUCCESS_MESSAGE);
done();
})
.catch(done);
});
});
after(function() {
sinon.restore();
});
});
<file_sep>/* 问题分类页面 */
const express = require('express');
const router = express.Router();
const Qcategory = require('../db/Qcategory');
const bodyParser = require('body-parser');
const MESSAGE = require('../MESSAGE.json');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.route('/')
/* get question category list */
.get((req, res, next) => {
const current = ~~req.query.current || 1;
const perPage = ~~req.query.perPage || 10;
Qcategory.findAndCountAll({
limit: perPage,
offset: (current - 1) * perPage,
raw: true,
}).then(result => {
res.status(200).send({
code: MESSAGE.QCATEGORY_READ_SUCCESS_CODE,
message: MESSAGE.QCATEGORY_READ_SUCCESS_MESSAGE,
current,
perPage,
count: result.count,
list: result.rows,
});
}).catch(err => {
console.error(err);
err.code = MESSAGE.QCATEGORY_READ_FAILURE_CODE;
err.message = MESSAGE.QCATEGORY_READ_FAILURE_CODE;
return next(err);
});
})
/* Add question category */
.post((req, res, next) => {
const body = req.body;
if (!body.name) {
const err = new Error(MESSAGE.QCATEGORY_ADD_NAME_MESSAGE);
err.code = MESSAGE.QCATEGORY_ADD_NAME_CODE;
return next(err);
}
Qcategory.create({
name: body.name,
})
.then(task => {
const plainTask = task.get({
plain: true
});
res.status(200).send({
code: MESSAGE.QCATEGORY_ADD_SUCCESS_CODE,
message: MESSAGE.QCATEGORY_ADD_SUCCESS_MESSAGE,
list: [plainTask],
});
})
.catch(err => {
console.error(err);
err.code = MESSAGE.QCATEGORY_ADD_FAILURE_CODE;
err.message = MESSAGE.QCATEGORY_ADD_FAILURE_MESSAGE;
return next(err);
});
});
router.route('/:id')
/* Update question category */
.put((req, res, next) => {
const id = req.params.id;
const body = req.body;
Qcategory.findByPk(id).then(result => {
if (result === null) {
const err = new Error(MESSAGE.QCATEGORY_UPDATE_ID_MESSAGE);
err.code = MESSAGE.QCATEGORY_UPDATE_ID_CODE;
return next(err);
}
if (!body.name) {
const err = new Error(MESSAGE.QCATEGORY_UPDATE_NAME_MESSAGE);
err.code = MESSAGE.QCATEGORY_UPDATE_NAME_CODE;
return next(err);
}
Qcategory.update({
name: body.name,
}, {
where: { id: id }
})
.then(Qcategory.findByPk(id).then(oldTask => {
oldTask.reload().then(task => {
const plainTask = task.get({ plain: true });
res.status(200).send({
code: MESSAGE.QCATEGORY_UPDATE_SUCCESS_CODE,
message: MESSAGE.QCATEGORY_UPDATE_SUCCESS_MESSAGE,
list: [plainTask],
});
});
}))
.catch(err => {
console.error(err);
err.code = MESSAGE.QCATEGORY_UPDATE_FAILURE_CODE;
err.message = MESSAGE.QCATEGORY_UPDATE_FAILURE_MESSAGE;
return next(err);
});
})
.catch(err => {
console.error(err);
next(err);
});
})
/* Delete question category */
.delete((req, res, next) => {
const id = req.params.id;
Qcategory.findByPk(id).then(result => {
if (!result) {
const err = new Error(MESSAGE.QCATEGORY_DELETE_ID_MESSAGE);
err.code = MESSAGE.QCATEGORY_DELETE_ID_CODE;
return next(err);
}
Qcategory.destroy({
where: { id: id }
})
.then(() => {
res.status(200).send({
message: MESSAGE.QCATEGORY_DELETE_SUCCESS_MESSAGE,
code: MESSAGE.QCATEGORY_DELETE_SUCCESS_CODE,
});
})
.catch(err => {
console.error(err);
err.code = MESSAGE.QCATEGORY_DELETE_FAILURE_CODE;
err.message = MESSAGE.QCATEGORY_DELETE_FAILURE_MESSAGE;
return next(err);
});
})
.catch(err => next(err));
});
module.exports = router;
<file_sep>// Colors Sequelize Model
const Sequelize = require('sequelize');
const sequelize = require('./sequelize');
const Category = require('./categorySequelize');
class Colors extends Sequelize.Model {}
Colors.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
},
hex: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
cname: {
type: Sequelize.STRING,
allowNull: false,
field: 'c_name',
},
fontColor: {
type: Sequelize.BOOLEAN,
defaultValue: 1,
field: 'font_color',
},
categoryId: {
type: Sequelize.INTEGER,
references: {
model: Category,
key: 'id',
},
field: 'category_id'
},
createdAt: {
type: Sequelize.DATE,
defaultValue: new Date(),
field: 'created_at'
}
}, {
indexes: [{
unique: true,
fields: ['hex']
}],
tableName: 'colors',
sequelize,
});
module.exports = Colors;
<file_sep>/* 颜色分类页面 */
const express = require('express');
const router = express.Router();
const Category = require('../db/categorySequelize');
const bodyParser = require('body-parser');
const MESSAGE = require('../MESSAGE.json');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
router.route('/')
// get category list
.get((req, res, next) => {
const current = ~~req.query.current || 1;
const perPage = ~~req.query.perPage || 10;
Category.findAndCountAll({
limit: perPage,
offset: (current - 1) * perPage,
raw: true,
}).then(result => {
res.status(200).send({
code: MESSAGE.CATEGORY_READ_SUCCESS_CODE,
message: MESSAGE.CATEGORY_READ_SUCCESS_MESSAGE,
current,
perPage,
count: result.count,
list: result.rows,
});
}).catch(err => {
console.error(err);
err.code = MESSAGE.CATEGORY_READ_FAILURE_CODE;
err.message = MESSAGE.CATEGORY_READ_FAILURE_CODE;
return next(err);
});
})
// Add a category
.post((req, res, next) => {
const body = req.body;
if (!body.name) {
const err = new Error(MESSAGE.CATEGORY_ADD_NAME_MESSAGE);
err.code = MESSAGE.CATEGORY_ADD_NAME_CODE;
return next(err);
}
if (!body.cname) {
const err = new Error(MESSAGE.CATEGORY_ADD_CNAME_MESSAGE);
err.code = MESSAGE.CATEGORY_ADD_CNAME_CODE;
return next(err);
}
Category.create({
name: body.name,
cname: body.cname,
})
.then(task => {
const plainTask = task.get({
plain: true
});
res.status(200).send({
code: MESSAGE.CATEGORY_ADD_SUCCESS_CODE,
message: MESSAGE.CATEGORY_ADD_SUCCESS_MESSAGE,
list: [plainTask],
});
})
.catch(err => {
console.error(err);
err.code = MESSAGE.CATEGORY_ADD_FAILURE_CODE;
err.message = MESSAGE.CATEGORY_ADD_FAILURE_MESSAGE;
return next(err);
});
});
router.route('/:id')
// Update a category
.put((req, res, next) => {
const id = req.params.id;
const body = req.body;
Category.findByPk(id).then(result => {
if (result === null) {
const err = new Error(MESSAGE.CATEGORY_UPDATE_ID_MESSAGE);
err.code = MESSAGE.CATEGORY_UPDATE_ID_CODE;
return next(err);
}
if (!body.name) {
const err = new Error(MESSAGE.CATEGORY_UPDATE_NAME_MESSAGE);
err.code = MESSAGE.CATEGORY_UPDATE_NAME_CODE;
return next(err);
}
if (!body.cname) {
const err = new Error(MESSAGE.CATEGORY_UPDATE_CNAME_MESSAGE);
err.code = MESSAGE.CATEGORY_UPDATE_CNAME_CODE;
return next(err);
}
Category.update({
name: body.name,
cname: body.cname,
}, {
where: { id: id }
})
.then(Category.findByPk(id).then(oldTask => {
oldTask.reload().then(task => {
const plainTask = task.get({ plain: true });
res.status(200).send({
code: MESSAGE.CATEGORY_UPDATE_SUCCESS_CODE,
message: MESSAGE.CATEGORY_UPDATE_SUCCESS_MESSAGE,
list: [plainTask],
});
});
}))
.catch(err => {
console.error(err);
err.code = MESSAGE.CATEGORY_UPDATE_FAILURE_CODE;
err.message = MESSAGE.CATEGORY_UPDATE_FAILURE_MESSAGE;
return next(err);
});
})
.catch(err => {
console.error(err);
next(err);
});
})
// Delete a category
.delete((req, res, next) => {
const id = req.params.id;
Category.findByPk(id).then(result => {
if (!result) {
const err = new Error(MESSAGE.CATEGORY_DELETE_ID_MESSAGE);
err.code = MESSAGE.CATEGORY_DELETE_ID_CODE;
return next(err);
}
Category.destroy({
where: { id: id }
})
.then(() => {
res.status(200).send({
message: MESSAGE.CATEGORY_DELETE_SUCCESS_MESSAGE,
code: MESSAGE.CATEGORY_DELETE_SUCCESS_CODE,
});
})
.catch(err => {
console.error(err);
err.code = MESSAGE.CATEGORY_DELETE_FAILURE_CODE;
err.message = MESSAGE.CATEGORY_DELETE_FAILURE_MESSAGE;
return next(err);
});
})
.catch(err => next(err));
});
module.exports = router;
<file_sep>/* Example */
const NODE_ENV = process.env.NODE_ENV;
const test = {
database: 'testdb',
user: 'user',
host: '127.0.0.1',
password: '<PASSWORD>',
timezone: 'Asia/Shanghai',
privateKey: 'key',
}
const dev = {
database: 'db',
user: 'user',
host: '127.0.0.1',
password: '<PASSWORD>',
timezone: 'Asia/Shanghai',
privateKey: 'key',
}
let config = (NODE_ENV && NODE_ENV === 'test') ? test : dev;
module.exports = config;
|
8ae8d7fd136d58540a9fb305e87d06a8b15a6aeb
|
[
"JavaScript",
"Markdown"
] | 15
|
JavaScript
|
chesterchenn/colors-api
|
deaad4b915116bcc2420024c1b5243524c0415a0
|
9660cdda98a59ef32ba8873ceabf7aa514af2aac
|
refs/heads/master
|
<repo_name>Dr102/smstwillio<file_sep>/test.php
<?php
echo "hello wold from php " ;
?>
<file_sep>/send.php
<?php
// this line loads the library
require('twilio/Services/Twilio.php');
$account_sid = '<KEY>';
$auth_token = '0<PASSWORD>';
$status = status ();
if(isset($_POST['submit'])){
$sms = trim($_POST['msg']);
$bulk = trim($_POST['numbers']);
$numbers = explode("\n", $bulk);
$numbers = array_filter($numbers, 'trim'); // remove any extra \r characters left behind
foreach ($numbers as $number) {
$data = send_sms($number,$sms);
$stat = $data->last_response->status;
if( $stat == 'queued')echo "<div class='done'>SMS sent TO ".$number."</div>"; $send = true;
//print_r ($data);
}
}
if(isset($_POST['dial_num'])){
$num = trim($_POST['dial_num']);
call($num);
}
function status (){
global $account_sid;
global $auth_token;
$status = new Services_Twilio($account_sid, $auth_token);
$account = $status->accounts->get("<KEY>");
return $account->status;
}
function send_sms($num, $sms){
global $account_sid;
global $auth_token;
$client = new Services_Twilio($account_sid, $auth_token);
try {
$client->account->messages->create(array(
'To' => $num,
'From' => "+18622608245",
'Body' => $sms,
));
}
catch (Exception $e) {
$send = false;
echo "<div class='error'>Error sending to ".$num."</div>";
}
return $client;
}
function call($num){
global $account_sid;
global $auth_token;
$client = new Services_Twilio($account_sid, $auth_token);
try {
// Initiate a new outbound call
$call = $client->account->calls->create(
// Step 4: Change the 'From' number below to be a valid Twilio number
// that you've purchased or verified with Twilio.
"+19292442587",
// Step 5: Change the 'To' number below to whatever number you'd like
// to call.
$num,
// Step 6: Set the URL Twilio will request when the call is answered.
"http://demo.twilio.com/welcome/voice/"
);
echo "Started call: " . $call->sid;
}
catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="index, follow" name="robots">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway:100,200,300,400,700,900' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<style type="text/css">
.done{
color: #555;
font-family: Tahoma,Geneva,Arial,sans-serif;
font-size: 11px;
padding: 10px 10px 10px 10px;
margin: 10px;
background-color: #ecfff1;
border: 1px solid #a6f5c9;
}
.error{
color:#555;
font-family:Tahoma,Geneva,Arial,sans-serif;font-size:11px;
padding:10px 10px 10px 10px;
margin:10px;
background-color: #ffecec;
border:1px solid #f5aca6;
}
</style>
</head>
<body>
<form class="form-horizontal" action='' method="POST" style="">
<fieldset>
<!-- Form Name -->
<legend>Sending SMS <b style="color:<? if($status == 'active'){echo 'green'; }else {echo 'red';}?>;"><?=$status?></b></legend>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="textarea">Phone Numbers</label>
<div class="col-md-4">
<textarea class="form-control" id="numbers" name="numbers" placeholder="+1..........."></textarea>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="textarea">Your SMS</label>
<div class="col-md-4">
<textarea class="form-control" id="msg" name="msg"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton">Send</label>
<div class="col-md-4">
<button id="submit" name="submit" class="btn btn-primary">Send</button>
</div>
</div>
<!--<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:70%">
70%
</div>
</div>-->
</fieldset>
</form>
</body>
</html>
|
9b9ec5e5953ac6d15e405bc6aa700ca0eb2d403a
|
[
"PHP"
] | 2
|
PHP
|
Dr102/smstwillio
|
68b913edd9fe3d8c7de6400bdaec884e68e8502b
|
9b5475ccdc05f31fc56bc77775bd6b3299e3b64e
|
refs/heads/master
|
<file_sep># -*- coding:utf8 -*-
'''
index page.
'''
__all__ = []
__version__ = '0.0.1'
__author__ = 'GalaIO'
from flask import Blueprint
import app
# 通过实例化一个 Blueprint 类对象可以创建蓝本。
user = Blueprint('user', __name__)
# 动态加载到app的路由链表中
app.fetchRoute(user, '/user')
from . import views<file_sep># -*- coding:utf8 -*-
'''
Apply command for user to control flask.
'''
from config import Config, root_dir
import os
from app import create_app, db
from app.models import tables
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from app.models import Role, User
# 动态创建app实例,然后继续使用
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
# 创建命令行管理
manager = Manager(app, with_default_commands=True)
# 创建数据库迁移管理
migrate = Migrate(app, db)
# 吧数据模型导入python解释器用于测试
def make_shell_context():
tables['app'] = app
tables['db'] = db
return tables
manager.add_command("shell", Shell(make_context=make_shell_context))
# 添加数据迁移命令
manager.add_command('db', MigrateCommand)
# 添加测试命令
@manager.command
def test():
'''Run the unit tests.'''
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@manager.command
def update():
# 自动更新需求库
print 'output requirements file.....'
os.system('pip freeze > requirements.txt')
# 添加自动生成生产环境配置命令
@manager.command
def config():
'''根据配置自动生成 生产环境配置,只支持nginx uwsgi'''
if not os.path.exists('logs'):
os.mkdir('logs')
if not os.path.exists('pids'):
os.mkdir('pids')
# 利用bash命令删除所有的xml 和 conf文件,这些就是nginx和uwsgi的配置文件
os.system('rm *-nginx.conf')
os.system('rm *-uwsgi.xml')
# 执行数据迁移和更新
os.system('python manage.py db migrate')
os.system('python manage.py db upgrade')
# 执行角色更新
'''print 'insert Roles.....'
Role.insert_roles()
# 刷新用户信息,主要是一些自动填写的信息,比如头像等
users = User.query.all()
print 'insert users.....'
for user in users:
user.generate_avatar_url()
db.session.add(user)
db.session.commit()'''
nginx_conf =\
'''server {
listen 80;
server_name %s;
access_log %s;
error_log %s;
location / {
include uwsgi_params;
uwsgi_pass localhost:%d;
}
location /static/ {
root %s;
}
}''' % (Config.HOST, os.path.join(os.path.join(root_dir, 'logs'), 'nginx.log'), os.path.join(os.path.join(root_dir, 'logs'), 'nginx.err'), Config.PORT, os.path.join(root_dir, 'app'))
'''
如果需要在uwsgi中使用多线程必须,添加下面两个字段,
一个是threads 一个是enable-threads否则不能运行,为了提高性能肯定是越多进程越多线程的好。
'''
uwsgi_conf =\
'''<uwsgi>
<pythonpath>%s</pythonpath>
<module>manage</module>
<callable>app</callable>
<socket>%s:%d</socket>
<master/>
<processes>%d</processes>
<threads>%d</threads>
<enable-threads/>
<memory-report/>
<daemonize>logs/uwsgi.log</daemonize>
<buffer-size>16384</buffer-size>
<pidfile>pids/uwsgi.pid</pidfile>
</uwsgi>'''% (root_dir, Config.ACCESSIPS, Config.PORT, 4, 4)
print 'output nginx config file.....'
file = open(Config.HOST+'-nginx.conf', 'w')
file.truncate()
file.write(nginx_conf)
file.close()
print 'output uwsgi config file.....'
file = open(Config.HOST+'-uwsgi.xml', 'w')
file.truncate()
file.write(uwsgi_conf)
file.close()
# 添加默认执行启动服务器的命令
@manager.command
def default_server():
app.run(debug=True, host=Config.ACCESSIPS, port=Config.PORT)
# 启动主进程
if __name__ == '__main__':
manager.run(default_command=default_server.__name__)<file_sep># -*- coding:utf8 -*-
'''
Main Form.
'''
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo, ValidationError
from ..models import Post
import re
class PostForm(Form):
title = StringField('博文标题', validators=[Required(), Length(0, 120)])
tags = StringField('博文标签', validators=[Required(), Length(0,120)])
body = TextAreaField('有什么好的想法?', validators=[Required()])
submit = SubmitField('提交')
def validate_tags(self, filed):
regx = r'^[0-9a-zA-Z;+&\u4E00-\u9FA5]*$'
pattern = re.compile(regx, re.S)
if pattern.match(filed.data) == None:
raise ValidationError('标签栏只包含英文单词、汉子和半角;、+、&。')
tag_list = filed.data.split(';')
for tag in tag_list:
if len(tag) > 10:
raise ValidationError('单个标签长度不得大于10字节。')
if len(tag) < 1:
raise ValidationError(';不能连续使用和用于结尾。')
<file_sep>#! /bin/bash
echo "kill uwsgi........"
if [ ! -f "pids/uwsgi.pid" ]; then
echo "please run the uwsgi server first or kill handly!"
exit 0
fi
uwsgi_pid=$(cat pids/uwsgi.pid)
echo "uwsgi pid is $uwsgi_pid"
kill -9 $uwsgi_pid
echo "kill success..."
<file_sep>#! /bin/bash
# 加密密钥
#export SECRET_KE=
# 服务器绑定二级域名 端口 和过滤IP地址设置
#export WEBSERVER_HOST=
#export WEBSERVER_PORT=
export WEBSERVER_ACCESSIP=127.0.0.1
# 注册发送邮件服务器
#export MAIL_SERVE=
#export MAIL_SERVERPORT=
#export MAIL_USERNAME=
#export MAIL_PASSWORD=
#export MAIL_ADDR=
# Database地址
#export DEV_DATABASE_URL=
#export TEST_DATABASE_URL=
#export DATABASE_URL=
python manage.py config
if [ -f "*-nginx.conf" ]; then
echo "generate nginx conf failed!"
exit 0
fi
echo "generate nginx conf success!"
if [ -f "*-uwsgi.xml" ]; then
echo "generate uwsgi conf failed!"
exit 0
fi
echo "generate uwsgi conf success!"
cp *-nginx.conf /etc/nginx/conf.d/
echo "migrate nginx conf to /etc/nginx/conf.d/....."
/usr/sbin/nginx -s reload
echo "reload nginx....."
uwsgi -x *-uwsgi.xml
echo "success load uwsgi!!!"
<file_sep># -*- coding:utf8 -*-
'''
index page.
'''
__all__ = []
__version__ = '0.0.1'
__author__ = 'GalaIO'
from flask import Blueprint
import app
from ..models import Permission
# 通过实例化一个 Blueprint 类对象可以创建蓝本。
auth = Blueprint('auth', __name__)
# 动态加载到app的路由链表中
app.fetchRoute(auth, '/auth')
# 把权限条件填充到模板中
@auth.app_context_processor
def inject_permission():
return dict(Permission=Permission)
from . import views<file_sep># 基于Flask的博客系统搭建
最近在学习python,然后呢,python的用处还很多,原来计划搞机器学习和数据挖掘的,不幸.....看到python可以开发后端,一时技痒,就学习了,当时从网上找了很多资料,还有就是当时要参加比赛,所以肯定是越快上手越好,越小越好,后来选择了flask,现在静下心来看《FlaskWeb开发:基于Python的Web应用开发实战》一书,然后随着书本逐步学习flask并且逐步完善本博客系统。[GalaCoding](https://github.com/GalaIO/GalaCoding)现在开源,并托管在github上。希望大家可以多多交流~~
#### 与Flasky的区别
在《FlaskWeb开发:基于Python的Web应用开发实战》一书中,实现的简单博客功能,包括用户认证、登录、注册系统,博客编写页面,评论功能,用户资料主页,用户关注等功能。
我在学习的基础上增加了一些功能:
- 博客关注功能,新增了推荐和关注页面,也就是说,广场的形式就是推送目前较新的博客,推荐是推荐关注的博主的最新博文,关注是关心的博客的动态;
- 添加了态度评论,即可以给博客和评论进行点赞,表示赞同和不赞同;- - 添加了云标签,可以通过热门标签来获得网站的动态。
修改的功能:
- 对网站进行了改版,页面的更换,样式的修改;
- 对于用户头像,采用离线缓存**Gravatar**的两种类型头像,然后使用邮箱地址的一个映射函数,让用户获取默认头像;
- 修改了posts表的模型,去掉html_body属性,也就是说服务端不缓存Markdown的html版本,在浏览器端使用[marked]()来形成实时编辑和预览,以及渲染的工作;
后期新增功能:
- 添加评论的评论功能,实现盖楼评论;
- 修改博客编辑页面,使其更友好,支持更多的markdown的类型;
- 增加图片墙的功能,让用户可以上传图片;
- 支持markdown文档上传,生成博客的功能。
#### 一、启动
###### 1.安装环境
如果使用这个模板很简单,首先你需要下载源码(这是当然的),然后安装python2.7环境,对于linux用户,python2.7是标配的,windows需要根据版本下载python安装程序就好了。下面给出ubuntu下的python安装。
```bash
$sudo apt-get install -y python python-pip
```
然后需要安装依赖库,你也可以在虚拟环境中安装哦,这样更方便一点。
```bash
$sudo pip install -r requirements.txt
```
所有与环境相关的配置,都在**config.py**文件中,不过你不用修改它,因为这些配置信息都来自于系统的环境变量,你可以设置环境变量来大概修改配置的目的,同时满足了隐私。值得一提是,我们提供了一个脚本来自动的初始化配置信息和加载必要的环境变量,为了保护隐私,我给注释了但是使用者必须填写,具体操作在第八节,我先说明一下需要配置的环境变量。
```bash
# 加密密钥
#export SECRET_KE=
# 服务器绑定二级域名 端口 和过滤IP地址设置
#export WEBSERVER_HOST=
#export WEBSERVER_PORT=
export WEBSERVER_ACCESSIP=127.0.0.1
# 注册发送邮件服务器
#export MAIL_SERVE=
#export MAIL_SERVERPORT=
#export MAIL_USERNAME=
#export MAIL_PASSWORD=
#export MAIL_ADDR=
# Database地址
#export DEV_DATABASE_URL=
#export TEST_DATABASE_URL=
#export DATABASE_URL=
```
设置好后,可以直接运行**run.sh**进行测试(第八节),当然你也可以手动的把环境变量输入(这是必须的),然后直接运行manage.py脚本进行测试。
>最好的一个选择是,配置好run.sh下的环境变量,使用sudo执行,然后再进行下列命令,因为这时候系统已经保存有这些环境变量了。也可以把他们放在自己的bash.rc配置文件中。
###### 2.数据库迁移
使用flask-migrate后,数据库迁移变得so easy,同时本步骤是必须的,有可能你下载下来的**master**版本是已经生成数据库了,默认的是SQLLite,但是你可以把miratation文件夹和sqllite文件删除,来重新迁移数据库,也就是重新建表。
迁移工程初始化,该步骤可以初始化一个迁移工程为后续做准备。
```bash
$python manage.py db init
```
初始化后,需要实行migrate指令,来生成迁移脚本,也就是说迁移工具自动生成配置数据库的脚本,该步骤必须显示调用。
```bash
$python manage.py db migrate -m "init version"
```
生成迁移脚本了,那么就开始正式迁移了,运行下面命令即可,如果没有数据库表,该命令会显式创建,同时运行迁移脚本,迁移数据库。
```bash
$python manage.py db upgrade
```
好了,现在数据库迁移完成了,可以进行下一步了。
###### 3.启动前准备
现在虽说基本建好环境了,但是对了本博客系统实现了简单的权限管理,所以必须显式的建立权限角色,否则会出现绑定角色失败,用户只能沦为无权限状态。不过新建角色也很简单。
```bash
$python manage.py shell
>>> Role.insert_roles()
>>> Role.query.all()
[<Role u'Moderator'>, <Role u'Administrator'>, <Role u'User'>]
>>>
```
还有就是建立一个初始的超级管理员,步骤如下:
```bash
$python manage.py shell
>>> u = User(username='GalaIO', email='*****<EMAIL>', role=Role.query.filter_by(name='Administrator').first(), password='***')
>>> u.generate_avatar_url()
>>> u
<User 'GalaIO'>
>>> db.session.add(u)
>>> db.session.commit()
```
现在你只需要完成邮件验证就好了,当然这个你也可以通过后台数据库操作。
还有为了支持匿名评论功能,需要主动的添加一个匿名用户,如果没有设置,系统会报异常来提示的。操作也很简单。
```bash
$python manage.py shell
>>> User.insert_Anonymous()
```
这时就可以匿名评论了,实现匿名功能随后细聊,匿名用户比较特殊,只可以评论,同时也只有名字属性,其他属性为None。
###### 4.运行
flask-script支持以下面命令启动应用。
```bash
$python manage.py runserver
```
这时候就可以完美访问你的服务器了,但是需要注意的是这时只能本机访问,如果需要外部计算机访问,可以添加参数,指定所有IP可访问,即0.0.0.0,同时可指定绑定的端口号。
```bash
$python manage.py runserver -h 0.0.0.0 -p 8000
* Restarting with stat
* Debugger is active!
* Debugger pin code: 113-835-817
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
```
如果需要更多功能选项,可以访问如下命令来查看。
```bash
$python manage.py runserver --help
```
值得一提是,本博客实现了一个默认命令,也就是说直接执行:
```bash
$python manage.py
```
也可以运行服务器,而端口和可访问的ip段在**Config**类中定义,可以修改。
#### 二、在shell环境中使用flask和数据库
这个比较简单,在键入命令后,在后台模板会自动把app实例、sqlalchemy实例、数据库定义自动的加载到shell中,你可以在其中自由做测试,或者手动添加、修改数据库等。博客建立的所有模型,在这个交互环境中都有映射。
```bash
$python manage.py shell
>>> app
<Flask 'app'>
>>> db
<SQLAlchemy engine='sqlite:///C:\\Users\\GalaIO\\Desktop\\GalaIO\\flask_pro\\data-dev.sqlite'>
>>> System
<class 'app.models.System'>
>>>
```
#### 三、使用数据库迁移工具
数据库迁移已经建立了一个基本版本,如果需要更新数据库模型,如果移动到新的部署环境,可以直接运行下面命令来同步数据库。也就是说如果初次建立后,如果更新了数据库模型,那么你可以使用如下命令来更新数据库,一个是生成迁移脚本,一个执行升级功能,但是需要注意新增表和属性好办,如果删除了现有的表和属性,那么你得手动处理migrate命令生成的脚本是否正确。
```bash
$python manage.py db migrate
$python manage.py db upgrade
```
#### 四、修改配置文件
该结构框架提供了灵活的修改模式,如果添加一些配置项,可以添加在**Config**类中,如果想在生产环境和开发、测试环境使用不同的参数,需要在扩展类中进行修改,不过最通用的参数使用系统的环境变量。
这时一个从环境变量中引用密钥的例子,**or**的作用是在环境变量不起作用时,拥有替代方案。
```python
import os
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess'
```
在配置文件可以同代项**app.config**字典中添加键值对,满足flask扩展库和全局通用量的需要,这些代码应写在如下:
```python
@staticmethod
def init_app(app):
# you should write here
pass
```
也就是说,我们的**SECRET_KEY**和**DATABASE_URL**默认从环境变量中引用,否则就使用默认字符串,或者在本地目录新建、寻找数据库。
同时我们还在Config中添加了,如下几个字段,由于配置生产环境时候,具体配置看8节。
```python
HOST = 'blog.liketobe.cn'
PORT = 8080
ACCESSIPS = '127.0.0.1'
```
#### 五、增加模型
数据模型文件存在app目录下,添加数据模型很简单,只需要按照按照例子添加一个类就可以了,后台会自动完成,同时若想学习更多的**SQLalchemy**的**ORM**操作,可以访问<a href="http://www.sqlalchemy.org/support.html">SQLAlchemy官网</a>来获取资源。
```python
# test model
@addModel
class System(db.Model):
name = db.Column(db.String(64), primary_key=True)
def __repr__(self):
return '<System %r>' % self.name
```
#### 六、模板与静态文件
**flask**会自动分发和处理对于**static**下的静态文件,一般包括**css**样式、**js**脚本、**img**图片等等。
**templates**目录下是所有的模板文件,由程序控制渲染展示给用户,这些都是flask的基础知识,这里不阐述,需要说明的是,我们提供了一个默认的根目录的模板**index.html**,还有常见错误类型**404.html**、**500.html**。如果想换成自己的样式,必须进行替换和更改,同时不影响你的其他创作。
#### 七、添加新的路由映射
模板提供了一个**index**路由的例子,可以先复制直接修改使用。值得提醒的是,可以把**errors**文件夹删除,因为他们定义的是全局的错误路由处理,主要修改的是**views.py**脚本,如果需要增加新的类声明的,在该文件夹下进行,最后当然需要在**__init__.py**中修改蓝图的名字,记得与包文件名一致,这些都是好的编码习惯哦。
#### 八、自动生成配置文件
使用python直接负责后台可能会有弊端,一般构造一个生产环境,现在是一个比较简单的,它会生成nginx和uwsgi的配置文件,这都是自动的,然后分别把配置文件放到相应的目录即可。更重要的是在其中会执行pip的依赖库备份,还有自动迁移和更新数据库。
```python
# 利用bash命令删除所有的xml 和 conf文件,这些就是nginx和uwsgi的配置文件
os.system('rm *-nginx.conf')
os.system('rm *-uwsgi.xml')
# 执行数据迁移和更新
os.system('python manage.py db migrate')
os.system('python manage.py db upgrade')
# 执行角色更新
Role.insert_roles()
# 自动更新需求库
os.system('pip freeze > requirements.txt')
```
命令执行如下:
```bash
$python manage.py conf
```
执行上述命令就会发现在本地目录出现一个****-nginx.conf和****-uswgi.xml两个文件,现在你需要电脑安装好这两个程序,一个是反向代理服务器nginx,另一个是python的通用网关接口uwsgi。安装命令如下:
```bash
$sudo apt-get install nginx
$sudo apt-get install uwsgi
```
把****-nginx.conf移动到nginx的配置文件,并且重新加载nginx的配置。
```bash
$sudo cp ./****-nginx.conf /etc/nginx/con.f/
$sudo /usr/sbin/nginx -s reload
```
启动uwsgi服务器,并手动设置log文件。
```bash
$sudo uwsgi -x ****-uwsgi.xml -d ./****.log
```
这样就简单搭建了生产环境。
>值得一提:我们提供了run.sh和exit.sh的脚本,用于自动运行和退出。如果有必须,可以使用chmod命令来给run.sh、exit.sh添加执行权限。
>
##### 九、添加新的库
在开发中往往需要添加新的库,但是需要说明的一点,希望大家进入虚拟环境中,使用pip安装,安装环境也打包了,当然这是windows上的虚拟环境,因为在虚拟环境安装会默认安装到**venv/Lib/site-packages/**中,我们程序每次动态吧改路径链入我们的库搜索路径,所以可以直接运行,就像步骤一说的一样。
如果安装了新的库,记得更新一下依赖库列表哦。运行如下命令。
```bash
$pip freeze > requirements.txt
```
<file_sep># -*- coding:utf8 -*-
'''
Flash message define here.
'''
# 退出message
log_out = '成功退出。'
# 错误用户名和密码
wrong_username_password = '用户名或密码错误。'
# 可以登录
access_to_login = '你现在可以登录了!'
# 发送确认邮件通知
send_register_confirm = '注册确认已经发到您的邮箱了~'
# 认证完成
confirm_ok = '您已成功完成认证!'
# 认证失效
confirm_invalid = '认证连接无效或已超时!'
# 重发认证令牌
confirm_resend = '新的认证邮件已发送~'
reset_password_ok = '重设密码成功!'
reset_password_err = '<PASSWORD>!'
user_not_found = '该用户未找到!'
update_profile_ok = '您的资料已更新!'
post_update_ok = '博客内容已更新!'
post_create_ok = '博文已更新!'
post_remark_again_err = '你已经评论过了~'
follow_youself_err = '你不能关注自己!'
follow_again_err = '你已经关注过此人!'
follow_ok = '关注成功!'
unfollow_youself_err = '你不能取消关注自己!'
unfollow_again_err = '你已经取消关注过此人!'
unfollow_ok = '取消关注成功!'
concern_ok = '关注文章成功!'
concern_again_err = '你已经关注过此文章!'
unconcern_ok = '取消关注文章成功!'
unconcern_again_err = '你已经取消关注过此文章!'
comment_remark_again_err = '你已经评论过了~'
comment_cannot_access = '你无权评论!'
<file_sep># -*- coding:utf8 -*-
'''
User Form.
'''
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo, ValidationError
from ..models import User, Role
from flask import current_app
class CommentForm(Form):
comment = TextAreaField('记录你的声音', validators=[Required()])
submit = SubmitField('提交')
def validate_comment(self, filed):
if len(filed.data) > current_app.config['COMMENT_MAX_LEN']:
ValidationError('评论不可超过'+ current_app.config['COMMENT_MAX_LEN'] +'个字符!!')
<file_sep># -*- coding:utf8 -*-
'''
index route.
'''
from flask import render_template, redirect, url_for, abort, flash, request, current_app
from . import user
from ..models import User, Role, Post, Permission
from flask.ext.login import login_required, current_user
from .forms import EditProfileForm, EditProfileAdminForm
from .. import db
from .. import messages
from ..decorators import admin_required, permission_required
# 定义路由函数
@user.route('/<username>', methods=['GET', 'POST'])
def profile(username):
tmp_user = User.query.filter_by(username=username).first()
if tmp_user is None:
abort(404)
page = request.args.get('page', 1, type=int)
pagination = tmp_user.posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
return render_template('user/user.html', user=tmp_user, posts=posts, pagination=pagination)
# 用户编辑资料页
@user.route('/edit', methods=['GET', 'POST'])
@login_required
def edit():
form = EditProfileForm()
if form.validate_on_submit():
current_user.name = form.name.data
current_user.location = form.location.data
current_user.about_me = form.about_me.data
db.session.add(current_user)
flash(messages.update_profile_ok)
return redirect(url_for('user.profile', username=current_user.username))
form.about_me.data = current_user.about_me
form.location.data = current_user.location
form.name.data = current_user.name
return render_template('user/edit.html', form=form)
# 直接索引用户资料页,同时需要管理员权限
@user.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_admin(id):
user = User.query.get_or_404(id)
form = EditProfileAdminForm(user)
if form.validate_on_submit():
# 不能修改邮件
# user.email = form.email.data
user.username = form.username.data
user.confirmed = form.confirmed.data
user.role = Role.query.get(form.role.data)
user.name = form.name.data
user.location = form.location.data
user.about_me = form.about_me.data
db.session.add(user)
flash(messages.update_profile_ok)
return redirect(url_for('user.profile', username=user.username))
form.email.data = user.email
form.username.data = user.username
form.confirmed.data = user.confirmed
form.role.data = user.role_id
form.name.data = user.name
form.location.data = user.location
form.about_me.data = user.about_me
return render_template('user/edit.html', form=form, user=user)
@user.route('/follow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
def follow(username):
if current_user.username == username:
flash(messages.follow_youself_err)
return redirect(url_for('user.profile', username=username))
user = User.query.filter_by(username=username).first()
if user is None:
flash(messages.user_not_found)
return redirect('main.index')
if current_user.is_following(user):
flash(messages.follow_again_err)
return redirect(url_for('user.profile', username=username))
# 过滤完成,允许关注
current_user.follow(user)
flash(messages.follow_ok)
return redirect(url_for('user.profile', username=username))
@user.route('/unfollow/<username>')
@login_required
@permission_required(Permission.FOLLOW)
def unfollow(username):
if current_user.username == username:
flash(messages.unfollow_youself_err)
return redirect(url_for('user.profile', username=username))
user = User.query.filter_by(username=username).first()
if user is None:
flash(messages.user_not_found)
return redirect('main.index')
if not current_user.is_following(user):
flash(messages.unfollow_again_err)
return redirect(url_for('user.profile', username=username))
# 过滤完成,允许取消关注
current_user.unfollow(user)
flash(messages.unfollow_ok)
return redirect(url_for('user.profile', username=username))
@user.route('/manage')
@login_required
@permission_required(Permission.MODERATE_USERS)
def manage():
page = request.args.get('page', 1, type=int)
pagination = User.query.order_by(User.last_seen.desc()).paginate(
page, per_page=current_app.config['USERS_PER_PAGE'],
error_out=False)
users = pagination.items
return render_template('user/manage.html', users=users, pagination=pagination)
@user.route('/delete/<username>')
@login_required
@permission_required(Permission.MODERATE_USERS)
def delete(username):
u = User.query.filter_by(username=username).first()
if u is None:
flash(messages.user_not_found)
else:
# 依次删除用户及其文章,否则文章会存在空用户索引
posts = u.posts.all()
for post in posts:
db.session.delete(post)
db.session.delete(u)
return redirect(url_for('user.manage'))
<file_sep># -*- coding:utf8 -*-
'''
index route.
'''
from flask import render_template, redirect, url_for, abort, flash, request, current_app
from . import comment
from ..models import User, Role, Post, Permission, Comment
from flask.ext.login import login_required, current_user
from .forms import CommentForm
from .. import db
from .. import messages
from ..decorators import admin_required, permission_required
'''
# 赞同某评论
@comment.route('/agree/<int:id>')
@login_required
@permission_required(Permission.COMMENT)
def agree(id):
'''
# 删除某评论
# 文章所属人、评论人和管理员都可以删除评论
@comment.route('/delete/<int:id>')
@login_required
def delete(id):
comment = Comment.query.get_or_404(id)
access = current_user == comment.post.author or current_user == comment.author or current_user.can(Permission.MODERATE_ARTICLES)
post_id = request.args.get('post_id')
if access == False and comment.post_id != post_id:
abort(404)
# 通过过滤条件
db.session.delete(comment)
return redirect(url_for('main.post', id=post_id))
@comment.route('/remark/<int:id>')
@login_required
def remark(id):
comment = Comment.query.get_or_404(id)
post_id = int(request.args.get('post_id'))
attitude = int(request.args.get('attitude'))
if comment.post_id != post_id:
abort(404)
# 通过过滤条件
if False == comment.remark_it(attitude, current_user.id):
flash(messages.comment_remark_again_err)
return redirect(url_for('main.post', id=post_id))
<file_sep># -*- coding:utf8 -*-
'''
index route.
'''
from flask import render_template, redirect, url_for, request, current_app, abort, flash
from . import main
from forms import PostForm
from ..comment.forms import CommentForm
from ..models import Permission, Post, Concern_posts, Comment, Tag, PostTag
from flask.ext.login import current_user, login_required
from .. import db
from .. import messages
import json
from datetime import datetime
# 定义路由函数
@main.route('/', methods=['GET', 'POST'])
def index():
# 加载数据库所有文章
page = request.args.get('page', 1, type=int)
shows = request.args.get('shows')
if current_user.is_authenticated and shows is not None and shows == 'recommend':
pagination = current_user.recommend_posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
elif current_user.is_authenticated and shows is not None and shows == 'concern':
pagination = current_user.concern_posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
elif current_user.is_authenticated and shows is not None and shows == 'home':
pagination = current_user.posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
else:
pagination = Post.query.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
return render_template('index.html', posts=posts, pagination=pagination, shows=shows)
# 索引文章的链接
@main.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
post = Post.query.get_or_404(id)
post.viewed_count = post.viewed_count + 1
db.session.add(post)
form = CommentForm()
if not current_user.can(Permission.COMMENT):
flash(messages.comment_cannot_access)
else:
if form.validate_on_submit():
comment = Comment(author_id=current_user.id, body=form.comment.data, post=post, agree_count=0, disagree_count=0)
db.session.add(comment)
db.session.commit()
page = request.args.get('page', 1, type=int)
pagination = Comment.query.filter_by(post_id=post.id).order_by(Comment.timestamp.desc()).paginate(
page, per_page=current_app.config['COMMENTS_PER_PAGE'],
error_out=False)
comments = pagination.items
return render_template('post.html', form=form, post=post, comments=comments, pagination=pagination)
# 编辑文章
@main.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit(id):
post = Post.query.get_or_404(id)
if current_user != post.author and \
not current_user.can(Permission.ADMINISTER):
abort(403)
form = PostForm()
if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
post.body = form.body.data
post.title = form.title.data
# 更新
post.update_tags(form.tags.data)
post.tags_txt = form.tags.data
post.timestamp = datetime.utcnow()
db.session.add(post)
flash(messages.post_update_ok)
return redirect(url_for('main.post', id=post.id))
form.body.data = post.body
form.title.data = post.title
form.tags.data = post.tags_txt
return render_template('edit.html', form=form)
# 编辑文章
@main.route('/new', methods=['GET', 'POST'])
@login_required
def new():
form = PostForm()
if not current_user.can(Permission.WRITE_ARTICLES):
abort(403)
if form.validate_on_submit():
post = Post(body=form.body.data, title=form.title.data, viewed_count=0, author=current_user._get_current_object(), tags_txt=form.tags.data)
db.session.add(post)
tags = form.tags.data.split(';')
for tag in tags:
ttag = Tag.query.filter_by(content=tag).first()
if ttag is not None:
ttag.refer_count = ttag.refer_count + 1
else:
ttag = Tag(content=tag, refer_count=1)
post_tag = PostTag(post=post, tag=ttag)
db.session.add(ttag)
db.session.add(post_tag)
flash(messages.post_create_ok)
db.session.commit()
return redirect(url_for('main.index', shows='home'))
if None == form.body.data:
form.body.data = '# 标题\n\n内容'
if None == form.title.data:
form.title.data = '输入博文名字'
if None == form.tags.data:
form.tags.data = '标签通过;隔开。'
return render_template('edit.html', form=form)
# 编辑文章
@main.route('/delete/<int:id>', methods=['GET'])
@login_required
def delete(id):
post = Post.query.get_or_404(id)
if current_user != post.author and \
not current_user.can(Permission.ADMINISTER):
abort(403)
u = post.author
Post.delete(post)
return redirect(url_for('user.profile', username=u.username))
# 关注谋篇文章
@main.route('/concern/<int:id>')
@login_required
def concern(id):
post = Post.query.get_or_404(id)
is_concern = request.args.get('action')
if is_concern == 'concern':
if current_user.concern(post):
flash(messages.concern_ok)
else:
flash(messages.concern_again_err)
elif is_concern == 'unconcern':
if current_user.unconcern(post):
flash(messages.unconcern_ok)
else:
flash(messages.unconcern_again_err)
else:
pass
return redirect(url_for('main.post', id=id))
@main.route('/remark/<int:id>')
@login_required
def remark(id):
post = Post.query.get_or_404(id)
attitude = int(request.args.get('attitude'))
# 通过过滤条件
if False == post.remark_it(attitude, current_user.id):
flash(messages.post_remark_again_err)
return redirect(url_for('main.post', id=post.id))
@main.route('/tags/<tagname>')
def tags(tagname):
tag = Tag.query.filter_by(content=tagname).first()
if tag is None:
abort(404)
page = request.args.get('page', 1, type=int)
pagination = tag.posts.order_by(Post.timestamp.desc()).paginate(
page, per_page=current_app.config['POSTS_PER_PAGE'],
error_out=False)
posts = pagination.items
return render_template('index.html', posts=posts, pagination=pagination)
# 获取热门标签
@main.route('/json/tags/hot', methods=['GET', 'POST'])
def tags_hot():
hots = Tag.query.order_by(Tag.refer_count.desc()).paginate(
1, per_page=current_app.config['TAGS_HOT_NUM'],
error_out=False).items
hots_json = []
for hot in hots:
tmp = dict(name=hot.content, post_count=hot.refer_count)
hots_json.append(tmp)
hots_json = json.dumps(hots_json)
rsp = dict(status='ok', err_code=10000)
return render_template('json/tags.json', rsp=rsp, hots_json=hots_json)<file_sep># -*- coding:utf8 -*-
'''
Add database models.
'''
from . import db
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from flask.ext.login import UserMixin, AnonymousUserMixin
from . import login_manager
from datetime import datetime
# 使用flask-login模块自动加载用户信息
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
# 模型字典,用于向外展示数据库模型
tables = {}
# 动态更新模型字典的修饰器
# 不需要改变类或者函数的行为,在一些处理以后,直接返回好了,不要包装函数了
def addModel(model):
tables[model.__name__] = model
return model
# 建立关注的关联模型
@addModel
class Follow(db.Model):
__tablename__ = 'follows'
follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True, index=True)
followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True, index=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
# 建立用户和关注着博客的多对多关系模型
@addModel
class Concern_posts(db.Model):
__tablename__ = 'concern_posts'
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True, index=True)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), primary_key=True, index=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
# 评论主要是 对文章评论、对评论进行评论,这些都是文本式评论,还有一种是态度评论,比如赞同、反对等
@addModel
class Remark_Attitude:
AGREE_WITH = 0x01
DISAGREE_WITH = 0x02
# 扩展
@addModel
class Remark(db.Model):
__tablename__ = 'remarks'
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'), index=True)
attitude = db.Column(db.Integer)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
@addModel
class RemarkPost(db.Model):
__tablename__ = 'remarkposts'
id = db.Column(db.Integer, primary_key=True)
owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), index=True)
attitude = db.Column(db.Integer)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
# 子评论表,用来表示对一篇文章的评论层级,层级不超过2,评论的自引用
@addModel
class SubComment(db.Model):
__tablename__ = 'subcomment'
id = db.Column(db.Integer, primary_key=True, index=True)
for_comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'), index=True)
from_comment_id = db.Column(db.Integer, db.ForeignKey('comments.id'), index=True)
# 增加与博文多对一关系、与用户多对一关系的评论系统
@addModel
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True, index=True)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), index=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
agree_count = db.Column(db.Integer, default=0)
disagree_count = db.Column(db.Integer, default=0)
body = db.Column(db.Text)
# 子评论
subcomments = db.relationship('SubComment', foreign_keys=[SubComment.for_comment_id], backref=db.backref('comment', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
def obtain_subcomments(self):
return Comment.query.join(SubComment, SubComment.for_comment_id==Comment.id).filter(SubComment.for_comment_id==self.id)
# 简评 态度评论
remarks = db.relationship('Remark', foreign_keys=[Remark.comment_id], backref=db.backref('comment', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
def remark_count(self, type):
# return Remark.query.filter_by(comment_id=self.id, attitude=type).count()
if Remark_Attitude.AGREE_WITH == type:
return self.agree_count
elif Remark_Attitude.DISAGREE_WITH == type:
return self.disagree_count
else:
return 0
def remark_it(self, type, user_id):
remark = Remark.query.filter_by(comment_id=self.id, owner_id=user_id).first()
if remark is not None:
return False
if Remark_Attitude.AGREE_WITH == type or Remark_Attitude.DISAGREE_WITH == type:
remark = Remark(comment_id=self.id, owner_id=user_id, attitude=type)
db.session.add(remark)
if Remark_Attitude.AGREE_WITH == type:
self.agree_count = self.agree_count + 1
else:
self.disagree_count = self.disagree_count + 1
return True
else:
return False
# USer model
@addModel
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
# 每个用户的email是唯一的,只能通过数据库删,否则终身不变
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
name = db.Column(db.String(64))
location = db.Column(db.String(64))
about_me = db.Column(db.Text())
member_since = db.Column(db.DateTime(), default=datetime.utcnow)
last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
# 文章的反向引用
posts = db.relationship('Post', backref='author', lazy='dynamic')
# 更新用户登录时间
def ping(self):
self.last_seen = self.member_since
self.member_since = datetime.utcnow()
db.session.add(self)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
# 存储密码的散列值,不存储用户密码,为了保护用户密码的隐私性
password_hash = db.Column(db.String(64))
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
# 邮箱验证是否有效
confirmed = db.Column(db.Boolean, default=False)
def generate_confirmation_token(self, expiration=3600):
s = Serializer(current_app.config['SECRET_KEY'], expiration)
return s.dumps({'confirm': self.id})
@staticmethod
def parse_confirm_token(token):
s = Serializer(current_app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return None
return data.get('confirm')
def confirm(self, token):
s = Serializer(current_app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return False
if data.get('confirm') != self.id:
return False
self.confirmed = True
db.session.add(self)
return True
# 添加权限验证
def can(self, permissions):
return self.role is not None and (self.role.permission & permissions) == permissions
def is_administrator(self):
return self.can(Permission.ADMINISTER)
# 用户图像,存储用户头像的url,而非二进制格式
avatar_url = db.Column(db.String(100), unique=True, index=True)
# 生成avatar的hashurl,使用http://www.gravatar.com/avatar的生成头像的服务
# 计算md5是计算密集型,会占用大量cpu,一般初始化新用户时,会执行一次
def generate_avatar_url(self):
# self.avatar_url = 'https://www.gravatar.com/avatar/'+hashlib.md5(self.email.encode('utf-8')).hexdigest()
total = 0
for i in range(1, len(self.email)):
total = total + ord(self.email[i])
self.avatar_url = '/static/avatar/avatar{0}.png'.format(total%200)
# 生成不同尺寸的url,这时经常被调用
def avatar_url_auto(self, size=100, default='idention', rating='g'):
# return '{0}?s={1}&d={2}&r={3}'.format(self.avatar_url, size, default, rating)
return self.avatar_url
# 定义索引和反向索引
followed = db.relationship('Follow', foreign_keys=[Follow.follower_id], backref=db.backref('follower', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
followers = db.relationship('Follow', foreign_keys=[Follow.followed_id], backref=db.backref('followed', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
# 与关注相关的操作函数
def follow(self, user):
if not self.is_following(user):
f = Follow(follower=self, followed=user)
db.session.add(f)
def unfollow(self, user):
f = self.followed.filter_by(followed_id=user.id).first()
if f:
db.session.delete(f)
def is_following(self, user):
return self.followed.filter_by(
followed_id=user.id).first() is not None
def is_followed_by(self, user):
return self.followers.filter_by(
follower_id=user.id).first() is not None
@property
def recommend_posts(self):
return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter(Follow.follower_id == self.id)
#定义关注着文章的反向引用
concerns = db.relationship('Concern_posts', foreign_keys=[Concern_posts.user_id], backref=db.backref('user', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
@property
def concern_posts(self):
return Post.query.join(Concern_posts, Concern_posts.post_id==Post.id)
def concern(self, post):
if not self.is_concerning(post):
c = Concern_posts(user=self, post=post)
db.session.add(c)
return True
else:
return False
def unconcern(self, post):
c = self.concerns.filter_by(post_id=post.id).first()
if c:
db.session.delete(c)
return True
else:
return False
def is_concerning(self, post):
return self.concerns.filter_by(post_id=post.id).first() is not None
# 添加评论的反向引用
comments = db.relationship('Comment', foreign_keys=[Comment.author_id], backref='author', lazy='dynamic')
# 简评 态度评论
remarks = db.relationship('Remark', foreign_keys=[Remark.owner_id], backref=db.backref('owner', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
def remark_count(self, type):
return Remark.query(owner_id=self.id, attitude=type).count()
# 简评 态度评论
remarkposts = db.relationship('RemarkPost', foreign_keys=[RemarkPost.owner_id], backref=db.backref('owner', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
def remarkPost_count(self, type):
return RemarkPost.query(owner_id=self.id, attitude=type).count()
@staticmethod
def insert_Administartor():
role = Role.query.filter_by(name='Administrator').first()
if role is None:
raise Exception('you should run Role.insert_roles()!!')
user = User(username=current_app.config['ADMIN_USERNAME'], email=current_app.config['ADMIN_EMAIL'], role=role, password=current_app.config['ADMIN_<PASSWORD>'])
user.generate_avatar_url()
db.session.add(user)
db.session.commit()
# 匿名用户很特殊,由于username、email、id等不会重复,所以只有一个属性那就是名字,主要用于匿名用户评论的,没有其他用途
@staticmethod
def insert_Anonymous():
role = Role.query.filter_by(name='User').first()
if role is None:
raise Exception('you should run Role.insert_roles()!!')
user = User(username='Anonymous', role=role)
db.session.add(user)
db.session.commit()
@property
def is_anonymous(self):
return False
@staticmethod
def delete(user):
# 删除用户的评论
for comment in user.comments:
db.session.delete(comment)
# 删除用户的文章
for post in user.posts:
Post.delete(post)
db.session.delete(user)
def __repr__(self):
return '<User %r>' % self.username
# 为了保证一致性,添加一个匿名用户,由于系统支持匿名用户评论,所以支持id和username属性,不支持别的属性会报错
class AnonymousUser(AnonymousUserMixin):
@property
def id(self):
anonymous_user = User.query.filter_by(username='Anonymous').first()
if anonymous_user is None:
raise Exception('please run User.insert_Anonymous()!!!')
return anonymous_user.id
@property
def username(self):
anonymous_user = User.query.filter_by(username='Anonymous').first()
if anonymous_user is None:
raise Exception('please run User.insert_Anonymous()!!!')
return anonymous_user.username
def can(self, permissions):
return False
def is_administrator(self):
return False
def is_anonymous(self):
return True
# 向flask-login管理添加默认的匿名类
login_manager.anonymous_user = AnonymousUser
# 使用权限来管理角色,同时通过一对多的关系,来对应相应用户
class Permission:
FOLLOW = 0x01
COMMENT = 0x02
WRITE_ARTICLES = 0x04
MODERATE_ARTICLES = 0x08
MODERATE_USERS = 0x10
ADMINISTER = 0xff
# 角色数据库,用于分配权限
@addModel
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True, index=True)
name = db.Column(db.String(64), unique=True, index=True)
default = db.Column(db.Boolean, default=False, index=True)
permission = db.Column(db.Integer)
users = db.RelationshipProperty('User', backref='role', lazy='dynamic')
@staticmethod
def insert_roles():
roles = {
'User': (Permission.FOLLOW | Permission.COMMENT | Permission.WRITE_ARTICLES, True),
'Moderator': (Permission.FOLLOW | Permission.COMMENT | Permission.WRITE_ARTICLES | Permission.MODERATE_ARTICLES, False),
'Administrator': (0xff, False)
}
for role_name in roles:
role = Role.query.filter_by(name=role_name).first()
if role is None:
role = Role(name = role_name)
role.permission = roles[role_name][0]
role.default = roles[role_name][1]
db.session.add(role)
db.session.commit()
def __repr__(self):
return '<Role %r>' % self.name
@addModel
class PostTag(db.Model):
__tablename__ = 'posttags'
id = db.Column(db.Integer, primary_key=True, index=True)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), index=True)
tag_id = db.Column(db.Integer, db.ForeignKey('tags.id'), index=True)
@addModel
class Tag(db.Model):
__tablename__ = 'tags'
id = db.Column(db.Integer, primary_key=True, index=True)
content = db.Column(db.String(10))
refer_count = db.Column(db.Integer, default=0)
posttags = db.relationship('PostTag', foreign_keys=[PostTag.tag_id], backref=db.backref('tag', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
@property
def posts(self):
return Post.query.join(PostTag, PostTag.post_id==Post.id).filter(PostTag.tag_id==self.id)
@addModel
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True, index=True)
body = db.Column(db.Text)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'), index=True)
#定义关注着文章的反向引用
concern_users = db.relationship('Concern_posts', foreign_keys=[Concern_posts.post_id], backref=db.backref('post', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
def is_concerned_by(self, user):
return self.concern_users.filter_by(user_id=user.id).first() is not None
# 添加评论的反向引用
comments = db.relationship('Comment', foreign_keys=[Comment.post_id], backref='post', lazy='dynamic')
# 简评 态度评论
remarkposts = db.relationship('RemarkPost', foreign_keys=[RemarkPost.post_id], backref=db.backref('post', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
def remarkPost_count(self, type):
return RemarkPost.query.filter_by(post_id=self.id, attitude=type).count()
viewed_count = db.Column(db.Integer)
posttags = db.relationship('PostTag', foreign_keys=[PostTag.post_id], backref=db.backref('post', lazy='joined'),
lazy='dynamic', cascade='all, delete-orphan')
@property
def tags(self):
return Tag.query.join(PostTag, PostTag.tag_id==Tag.id).filter(PostTag.post_id==self.id)
def update_tags(self, new_tags):
old_tags = self.tags_txt.split(';')
new_tags = new_tags.split(';')
# 建立新标签
for tag in new_tags:
# 检查标签是否有增删的情况
if tag not in old_tags:
tTag = Tag.query.filter_by(content=tag).first()
if tTag is None:
tTag = Tag(content=tag, refer_count=1)
post_tag = PostTag(post=self, tag=tTag)
db.session.add(tTag)
db.session.add(post_tag)
else:
tPost_tag = PostTag.query.filter_by(tag_id=tTag.id, post_id=self.id).first()
if tPost_tag is None:
post_tag = PostTag(post=self, tag=tTag)
tTag.refer_count = tTag.refer_count + 1
db.session.add(post_tag)
else:
tTag.refer_count = tTag.refer_count - 1
db.session.delete(tPost_tag)
db.session.add(tTag)
# 删除就标签
for tag in old_tags:
if tag not in new_tags:
tTag = Tag.query.filter_by(content=tag).first()
tPost_tag = PostTag.query.filter_by(tag_id=tTag.id, post_id=self.id).first()
tTag.refer_count = tTag.refer_count - 1
db.session.delete(tPost_tag)
db.session.add(tTag)
# 冗余信息
tags_txt = db.Column(db.String(128))
agree_count = db.Column(db.Integer, default=0)
disagree_count = db.Column(db.Integer, default=0)
title = db.Column(db.String(128))
def remark_count(self, type):
# return Remark.query.filter_by(comment_id=self.id, attitude=type).count()
if Remark_Attitude.AGREE_WITH == type:
return self.agree_count
elif Remark_Attitude.DISAGREE_WITH == type:
return self.disagree_count
else:
return 0
def remark_it(self, type, user_id):
remark = RemarkPost.query.filter_by(post_id=self.id, owner_id=user_id).first()
if remark is not None:
return False
if Remark_Attitude.AGREE_WITH == type or Remark_Attitude.DISAGREE_WITH == type:
remark = RemarkPost(post_id=self.id, owner_id=user_id, attitude=type)
db.session.add(remark)
if Remark_Attitude.AGREE_WITH == type:
self.agree_count = self.agree_count + 1
else:
self.disagree_count = self.disagree_count + 1
return True
else:
return False
@staticmethod
def delete(post):
# 删除所有的评论
for comment in post.comments:
db.session.delete(comment)
# 删除文章,不用管remark,因为是关联表在建立引用关系时,使用cascade='all, delete-orphan' 属性让sqlalchemy自动处理其关系
tags = post.tags_txt.split(';')
# 更新标签数量
for tag in tags:
tTag = Tag.query.filter_by(content=tag).first()
tTag.refer_count = tTag.refer_count - 1
db.session.add(tTag)
db.session.delete(post)
# 文章的摘要,默认取第一段落内容
@property
def abstarct(self):
end = self.body.find('##')
if end > -1 and end < current_app.config['POSTS_ABSTRACT_NUM']:
return self.body[:end]
end = self.body.find('```')
if end > -1 and end < current_app.config['POSTS_ABSTRACT_NUM']:
return self.body[:end]
return self.body[:current_app.config['POSTS_ABSTRACT_NUM']]
def __repr__(self):
return '<Post %r>' % self.title
<file_sep># -*- coding:utf8 -*-
'''
This config the root_dir, security key, database url....
'''
import sys
import os
# 得到本工程的文件位置, 绝对地址
root_dir = os.path.abspath(os.path.dirname(__file__))
# 设置默认编码是utf-8
reload(sys)
sys.setdefaultencoding('utf-8')
from flask import Flask
# 核心设置,包括加密密钥和设置sqlalchemy自动提交
class Config:
# 散列值和安全令牌密钥设置
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string!!!'
# sqlalchemy的自动提交设置
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
# 服务器绑定二级域名 端口 和过滤IP地址设置
HOST = os.environ.get('WEBSERVER_HOST')
PORT = int(os.environ.get('WEBSERVER_PORT'))
ACCESSIPS = os.environ.get('WEBSERVER_ACCESSIP')
# 注册发送邮件服务器
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = int(os.environ.get('MAIL_SERVERPORT'))
# MAIL_USE_TLS = True
MAIL_USE_TLS = False
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
MAIL_SUBJECT_PREFIX = '[GalaCoding]'
MAIL_SENDER = '%s <%s>' % (MAIL_USERNAME, os.environ.get('MAIL_ADDR'))
# 超级管理员信息
ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL')
ADMIN_USERNAME = os.environ.get('ADMIN_USERNAME')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD')
# 常用常量
POSTS_PER_PAGE = 30
USERS_PER_PAGE = 30
COMMENTS_PER_PAGE = 30
TAGS_HOT_NUM = 10
POSTS_ABSTRACT_NUM = 500
COMMENT_MAX_LEN = 1000
# init_app 可以在创建flask应用时,获取到一些app上下文,同时自定义设置参数,一般就是更新app.config吧
@staticmethod
def init_app(app):
pass
# 默认开发配置
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
'sqlite:///' + os.path.join(root_dir, 'data-dev.sqlite')
# 默认测试配置
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
'sqlite:///' + os.path.join(root_dir, 'data-test.sqlite')
# 默认生产配置
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(root_dir, 'data.sqlite')
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}<file_sep># -*- coding:utf8 -*-
'''
index page.
'''
__all__ = []
__version__ = '0.0.1'
__author__ = 'GalaIO'
from flask import Blueprint
import app
from ..models import Remark_Attitude
# 通过实例化一个 Blueprint 类对象可以创建蓝本。
comment = Blueprint('comment', __name__)
# 动态加载到app的路由链表中
app.fetchRoute(comment, '/comment')
# 把简评模型条件填充到模板中
@comment.app_context_processor
def inject_permission():
return dict(Remark_Attitude=Remark_Attitude)
from . import views<file_sep># -*- coding:utf8 -*-
'''
User Form.
'''
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, SelectField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo, ValidationError
from ..models import User, Role
class EditProfileForm(Form):
name = StringField('真实姓名', validators=[Required(), Length(1, 64, '长度必须为1-64。')])
location = StringField('居住地', validators=[Required(), Length(1, 64, '长度必须为1-64。')])
about_me = TextAreaField('关于我')
submit = SubmitField('提交')
class EditProfileAdminForm(Form):
email = StringField('邮箱', validators=[Required(), Length(1, 64, '长度必须为1-64。'), Email()])
username = StringField('用户名', validators=[
Required(), Length(1, 64, '长度必须为1-64。'), Regexp('^[A-Z][A-Za-z0-9_.]*$', 0,
'用户名第一个字母必须大写,且只能由字母,'
'数字,下划线,点组成。')])
password = StringField('密码', validators=[
Required(), Length(1, 16, '长度必须为1-16。'), Regexp('^[A-Za-z0-9_.]*$', 0,
'密码第只能由字母,数字,下划线,点组成。')])
name = StringField('真实姓名', validators=[Length(0, 64, '长度必须为1-64。')])
confirmed = BooleanField('是否验证')
location = StringField('居住地', validators=[Length(0, 64, '长度必须为1-64。')])
about_me = TextAreaField('关于我')
# 选择角色
role = SelectField('角色', coerce=int)
submit = SubmitField('修改')
def __init__(self, user, *args, **kwargs):
super(EditProfileAdminForm, self).__init__(*args, **kwargs)
self.role.choices = [(role.id, role.name) for role in Role.query.order_by(Role.name).all()]
self.user = user
def validate_email(self, filed):
if self.user.email == filed.data:
return
else:
raise ValidationError('暂时不支持修改邮箱地址!')
def validate_username(self, filed):
# 允许管理员修改 用户名,但是不能修改邮箱
if self.user.username == filed.data:
return
if User.query.filter_by(username=filed.data).first():
raise ValidationError('改用户名已被占用。')<file_sep># -*- coding:utf8 -*-
'''
index page.
'''
__all__ = []
__version__ = '0.0.1'
__author__ = 'GalaIO'
from flask import Blueprint
import app
# 通过实例化一个 Blueprint 类对象可以创建蓝本。
main = Blueprint('main', __name__)
# 动态加载到app的路由链表中
app.fetchRoute(main)
'''
@app.fetchBlueprints(None)
def createBuleprint():
return Blueprint('main', __name__)
'''
from . import views, errors<file_sep># -*- coding:utf8 -*-
'''
The flask app, include models, templates, static file and route mapper.
'''
__all__ = []
__version__ = '0.0.1'
__author__ = 'GalaIO'
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from config import config, root_dir
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager
from flask.ext.mail import Mail
from flask.ext.moment import Moment
# 定义了数据库实例,在随后初始化,传入app上下文
db = SQLAlchemy()
# 实例化bootstrap
bootstrap = Bootstrap()
# 实例化登陆管理类
login_manager = LoginManager()
# session protection属性可以设为None basic strong,可以提高不同安全等级防止用户会话遭篡改
# 如果是 strong,flask-login会监控客户端ip和浏览器的代理信息,发现异动就登出用户
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
# 初始化邮箱类
mail = Mail()
# 初始化本地化时间类
moment = Moment()
# 蓝图表,可以动态加载进去
route_list = []
# 提供一个函数简化操作
def fetchRoute(blueprint, prefix=None):
tmpList = [blueprint, prefix]
route_list.append(tmpList)
# 延迟创建app, 为了让视图和模型与创建分开
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# 初始化一些flask扩展库,依赖于flask的app上下文环境
db.init_app(app)
# 初始化bootstrap
bootstrap.init_app(app)
# 初始化登陆管理
login_manager.init_app(app)
# 初始化邮件
mail.init_app(app)
# 初始化moment
moment.init_app(app)
# 附加路由和自定义的错误页面
app_dir = os.path.join(root_dir, 'app')
# 逐个执行各个路由映射脚本,添加到route_list中
for routes in os.listdir(app_dir):
rou_path = os.path.join(app_dir, routes)
if (not os.path.isfile(rou_path)) and routes != 'static' and routes != 'templates':
__import__('app.' + routes)
# 从route_list中引入蓝图
for blueprints in route_list:
if blueprints[1] != None:
app.register_blueprint(blueprints[0], url_prefix = blueprints[1])
else:
app.register_blueprint(blueprints[0])
#返回app实例,让外部模块继续使用
return app<file_sep># -*- coding:utf8 -*-
'''
Login Form.
'''
from flask.ext.wtf import Form
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Length, Email, Regexp, EqualTo, ValidationError
from ..models import User
class LoginForm(Form):
email = StringField('邮箱', validators=[Required(), Length(1, 64, '长度必须为1-64。'), Email()])
password = PasswordField('密码', validators=[Required(), Length(1, 16, '长度必须为1-16。')])
remember_me = BooleanField('保持登录状态')
submit = SubmitField('登录')
class RegistrationForm(Form):
email = StringField('邮箱', validators=[Required(), Length(1, 64, '长度必须为1-64。'), Email()])
username = StringField('用户名', validators=[
Required(), Length(1, 64, '长度必须为1-64。'), Regexp('^[A-Z][A-Za-z0-9_.]*$', 0,
'用户名第一个字母必须大写,且只能由字母,'
'数字,下划线,点组成。')])
password = PasswordField('密码', validators=[
Required(), Length(1, 16, '长度必须为1-16。'), Regexp('^[A-Za-z0-9_.]*$', 0,
'密码第只能由字母,数字,下划线,点组成。')])
password_verify = PasswordField('<PASSWORD>', validators=[
Required(), Length(1, 16, '长度必须为1-16。'), EqualTo('password', '必须和密码一致。')])
submit = SubmitField('注册')
def validate_email(self, filed):
if User.query.filter_by(email=filed.data).first():
raise ValidationError('该邮箱已被注册。')
def validate_username(self, filed):
if User.query.filter_by(username=filed.data).first():
raise ValidationError('改用户名已被占用。')
class ResetPassword(Form):
password = PasswordField('原密码', validators=[Required(), Length(1, 16, '长度必须为1-16。')])
new_password = <PASSWORD>Field('新密码', validators=[
Required(), Length(1, 16, '长度必须为1-16。'), Regexp('^[A-Za-z0-9_.]*$', 0,
'密码第只能由字母,数字,下划线,点组成。')])
submit = SubmitField('提交')
class ForgetPassword(Form):
email = StringField('邮箱', validators=[Required(), Length(1, 64, '长度必须为1-64。'), Email()])
submit = SubmitField('提交')
class ResetPasswordByConfirm(Form):
new_password = PasswordField('新密码', validators=[
Required(), Length(1, 16, '长度必须为1-16。'), Regexp('^[A-Za-z0-9_.]*$', 0,
'密码第只能由字母,数字,下划线,点组成。')])
submit = SubmitField('提交')
<file_sep>"""init
Revision ID: 6388fc0f2211
Revises: None
Create Date: 2016-05-11 17:19:55.222000
"""
# revision identifiers, used by Alembic.
revision = '6<PASSWORD>'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('roles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('default', sa.Boolean(), nullable=True),
sa.Column('permission', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_roles_default'), 'roles', ['default'], unique=False)
op.create_index(op.f('ix_roles_id'), 'roles', ['id'], unique=False)
op.create_index(op.f('ix_roles_name'), 'roles', ['name'], unique=True)
op.create_table('tags',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('content', sa.String(length=10), nullable=True),
sa.Column('refer_count', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_tags_id'), 'tags', ['id'], unique=False)
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('email', sa.String(length=64), nullable=True),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('name', sa.String(length=64), nullable=True),
sa.Column('location', sa.String(length=64), nullable=True),
sa.Column('about_me', sa.Text(), nullable=True),
sa.Column('member_since', sa.DateTime(), nullable=True),
sa.Column('last_seen', sa.DateTime(), nullable=True),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.Column('password_hash', sa.String(length=64), nullable=True),
sa.Column('confirmed', sa.Boolean(), nullable=True),
sa.Column('avatar_url', sa.String(length=100), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['roles.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_avatar_url'), 'users', ['avatar_url'], unique=True)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('follows',
sa.Column('follower_id', sa.Integer(), nullable=False),
sa.Column('followed_id', sa.Integer(), nullable=False),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('follower_id', 'followed_id')
)
op.create_index(op.f('ix_follows_followed_id'), 'follows', ['followed_id'], unique=False)
op.create_index(op.f('ix_follows_follower_id'), 'follows', ['follower_id'], unique=False)
op.create_table('posts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('body', sa.Text(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('author_id', sa.Integer(), nullable=True),
sa.Column('viewed_count', sa.Integer(), nullable=True),
sa.Column('tags_txt', sa.String(length=128), nullable=True),
sa.Column('agree_count', sa.Integer(), nullable=True),
sa.Column('disagree_count', sa.Integer(), nullable=True),
sa.Column('title', sa.String(length=128), nullable=True),
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_posts_author_id'), 'posts', ['author_id'], unique=False)
op.create_index(op.f('ix_posts_id'), 'posts', ['id'], unique=False)
op.create_index(op.f('ix_posts_timestamp'), 'posts', ['timestamp'], unique=False)
op.create_table('comments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('post_id', sa.Integer(), nullable=True),
sa.Column('author_id', sa.Integer(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.Column('agree_count', sa.Integer(), nullable=True),
sa.Column('disagree_count', sa.Integer(), nullable=True),
sa.Column('body', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['author_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_comments_author_id'), 'comments', ['author_id'], unique=False)
op.create_index(op.f('ix_comments_id'), 'comments', ['id'], unique=False)
op.create_index(op.f('ix_comments_post_id'), 'comments', ['post_id'], unique=False)
op.create_table('concern_posts',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('post_id', sa.Integer(), nullable=False),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'post_id')
)
op.create_index(op.f('ix_concern_posts_post_id'), 'concern_posts', ['post_id'], unique=False)
op.create_index(op.f('ix_concern_posts_user_id'), 'concern_posts', ['user_id'], unique=False)
op.create_table('posttags',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('post_id', sa.Integer(), nullable=True),
sa.Column('tag_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.ForeignKeyConstraint(['tag_id'], ['tags.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_posttags_id'), 'posttags', ['id'], unique=False)
op.create_index(op.f('ix_posttags_post_id'), 'posttags', ['post_id'], unique=False)
op.create_index(op.f('ix_posttags_tag_id'), 'posttags', ['tag_id'], unique=False)
op.create_table('remarkposts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('owner_id', sa.Integer(), nullable=True),
sa.Column('post_id', sa.Integer(), nullable=True),
sa.Column('attitude', sa.Integer(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_remarkposts_owner_id'), 'remarkposts', ['owner_id'], unique=False)
op.create_index(op.f('ix_remarkposts_post_id'), 'remarkposts', ['post_id'], unique=False)
op.create_table('remarks',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('owner_id', sa.Integer(), nullable=True),
sa.Column('comment_id', sa.Integer(), nullable=True),
sa.Column('attitude', sa.Integer(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['comment_id'], ['comments.id'], ),
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_remarks_comment_id'), 'remarks', ['comment_id'], unique=False)
op.create_index(op.f('ix_remarks_owner_id'), 'remarks', ['owner_id'], unique=False)
op.create_table('subcomment',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('for_comment_id', sa.Integer(), nullable=True),
sa.Column('from_comment_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['for_comment_id'], ['comments.id'], ),
sa.ForeignKeyConstraint(['from_comment_id'], ['comments.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_subcomment_for_comment_id'), 'subcomment', ['for_comment_id'], unique=False)
op.create_index(op.f('ix_subcomment_from_comment_id'), 'subcomment', ['from_comment_id'], unique=False)
op.create_index(op.f('ix_subcomment_id'), 'subcomment', ['id'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_subcomment_id'), table_name='subcomment')
op.drop_index(op.f('ix_subcomment_from_comment_id'), table_name='subcomment')
op.drop_index(op.f('ix_subcomment_for_comment_id'), table_name='subcomment')
op.drop_table('subcomment')
op.drop_index(op.f('ix_remarks_owner_id'), table_name='remarks')
op.drop_index(op.f('ix_remarks_comment_id'), table_name='remarks')
op.drop_table('remarks')
op.drop_index(op.f('ix_remarkposts_post_id'), table_name='remarkposts')
op.drop_index(op.f('ix_remarkposts_owner_id'), table_name='remarkposts')
op.drop_table('remarkposts')
op.drop_index(op.f('ix_posttags_tag_id'), table_name='posttags')
op.drop_index(op.f('ix_posttags_post_id'), table_name='posttags')
op.drop_index(op.f('ix_posttags_id'), table_name='posttags')
op.drop_table('posttags')
op.drop_index(op.f('ix_concern_posts_user_id'), table_name='concern_posts')
op.drop_index(op.f('ix_concern_posts_post_id'), table_name='concern_posts')
op.drop_table('concern_posts')
op.drop_index(op.f('ix_comments_post_id'), table_name='comments')
op.drop_index(op.f('ix_comments_id'), table_name='comments')
op.drop_index(op.f('ix_comments_author_id'), table_name='comments')
op.drop_table('comments')
op.drop_index(op.f('ix_posts_timestamp'), table_name='posts')
op.drop_index(op.f('ix_posts_id'), table_name='posts')
op.drop_index(op.f('ix_posts_author_id'), table_name='posts')
op.drop_table('posts')
op.drop_index(op.f('ix_follows_follower_id'), table_name='follows')
op.drop_index(op.f('ix_follows_followed_id'), table_name='follows')
op.drop_table('follows')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_index(op.f('ix_users_avatar_url'), table_name='users')
op.drop_table('users')
op.drop_index(op.f('ix_tags_id'), table_name='tags')
op.drop_table('tags')
op.drop_index(op.f('ix_roles_name'), table_name='roles')
op.drop_index(op.f('ix_roles_id'), table_name='roles')
op.drop_index(op.f('ix_roles_default'), table_name='roles')
op.drop_table('roles')
### end Alembic commands ###
<file_sep># -*- coding:utf8 -*-
'''
web error control..
'''
from flask import render_template
from . import main
# 向程序全局注册404 错误处理,其他路由处理可以省掉
@main.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
# 向程序全局注册404 错误处理,其他路由处理可以省掉
@main.app_errorhandler(403)
def page_not_found(e):
return render_template('403.html'), 403
# 向程序全局注册500 错误处理,其他路由处理可以省掉
@main.app_errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
|
6c993d7fa11475bc861d6e5b8d534816b1fdb85d
|
[
"Markdown",
"Python",
"Shell"
] | 21
|
Python
|
GalaIO/GalaCoding
|
35639ce6598d17519432fd988ca47da985665307
|
9d4d205f817d40347470fc2fc1a23d745282865e
|
refs/heads/master
|
<file_sep>import React from 'react';
import Movie from "./movie";
import * as d3 from 'd3';
import {FormattedMessage} from 'react-intl';
import MovieDetail from './movieDetail';
export default class MoviesList extends React.Component {
constructor(){
super();
this.state={
movies:[],
act:{}
}
}
componentDidMount(){
if(navigator.language==="es"){
fetch("https://gist.githubusercontent.com/josejbocanegra/f784b189117d214578ac2358eb0a01d7/raw/2b22960c3f203bdf4fac44cc7e3849689218b8c0/data-es.json")
.then(res => {
return res.json();
}).then(res => {
this.setState({ movies: res });
this.drawChart(this.state.movies);
localStorage.setItem('movies', res);
});
}
else if(navigator.language==="en"){
fetch("https://gist.githubusercontent.com/josejbocanegra/8b436480129d2cb8d81196050d485c56/raw/48cc65480675bf8b144d89ecb8bcd663b05e1db0/data-en.json")
.then(res => {
return res.json();
}).then(res => {
this.setState({ movies: res });
this.drawChart(this.state.movies);
localStorage.setItem('movies', res);
});
}
}
drawChart(data) {
console.log(data);
const width = 700;
const height = 500;
const margin = { top:10, left:100, bottom: 40, right: 10};
const iwidth = width - margin.left - margin.right;
const iheight = height - margin.top -margin.bottom;
const svg = d3.select(this.refs.canvas).append("svg");
svg.attr("width", width);
svg.attr("height", height);
let g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
const y = d3.scaleLinear()
.domain([0, 10000000])
.range([iheight, 0]);
const x = d3.scaleBand()
.domain(data.map(d => d.id) )
.range([0, iwidth])
.padding(0.1);
const bars = g.selectAll("rect").data(data);
bars.enter().append("rect")
.attr("class", "bar")
.style("fill", "red")
.attr("x", d => x(d.id))
.attr("y", d => y(d.views))
.attr("height", d => iheight - y(d.views))
.attr("width", x.bandwidth())
g.append("g")
.classed("x--axis", true)
.call(d3.axisBottom(x))
.attr("transform", `translate(0, ${iheight})`);
g.append("g")
.classed("y--axis", true)
.call(d3.axisLeft(y));
}
render() {
return (
<div ref ="canvas" className="container">
<div className="row">
<div className="col-9">
<table className="table">
<thead className="thead-light">
<tr>
<th scope="col">#</th>
<th scope="col"><FormattedMessage id="name"/></th>
<th scope="col"><FormattedMessage id="directedBy"/></th>
<th scope="col"><FormattedMessage id="country"/></th>
<th scope="col"><FormattedMessage id="budget"/></th>
<th scope="col"><FormattedMessage id="releaseDate"/> </th>
<th scope="col"><FormattedMessage id="views"/></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{this.state.movies.map( (e,i) => <Movie key={i} movie={e}/>)}
</tbody>
</table>
</div>
<div className="col-3">
{ this.state.movies.map( (e,i) => <MovieDetail key={i} movie={e}/>)}
</div>
</div>
</div>
);
}
}<file_sep>import React from 'react';
import {FormattedMessage} from 'react-intl';
export default class MovieDetail extends React.Component {
render() {
return (
<div className="card">
<img src={this.props.movie.poster} className="card-img-top" alt="poster"></img>
<div class="card-body">
<h5 class="card-title">
<FormattedMessage id="description"/>
</h5>
<p class="card-text">
{this.props.movie.description}
</p>
<p class="card-text">
<FormattedMessage id="cast"/>: {this.props.movie.cast}
</p>
</div>
</div>
);
}
}<file_sep>import React from 'react';
import {FormattedDate, FormattedNumber, FormattedPlural, FormattedMessage} from 'react-intl';
export default class Movie extends React.Component {
getMillion = ()=>{
if (this.props.movie.budget === 1){
return <FormattedMessage id="Million"/>
}
else{
return <FormattedMessage id="Millions"/>
}
}
render() {
return (
<tr>
<th scope="row">{this.props.movie.id}</th>
<td>{this.props.movie.name}</td>
<td>{this.props.movie.directedBy}</td>
<td>{this.props.movie.country}</td>
<td>{this.props.movie.budget} <FormattedPlural value = {this.props.movie.salary} one={this.getMillion()} other={this.getMillion()}/> </td>
<td>
<FormattedDate
value={new Date(this.props.movie.date)}
year='numeric'
month='numeric'
day='numeric'
/>
</td>
<td> <FormattedNumber value={this.props.movie.views}/></td>
<td>
<button className="btn btn-primary" >
<FormattedMessage id="but"/>
</button>
</td>
</tr>
);
}
}
|
9d58a14c321ddfcdc4e544435b5b04a17107e22d
|
[
"JavaScript"
] | 3
|
JavaScript
|
dianyQuintero/parcial2web
|
53ef7283471fbb42c7a3e3e27713681e3fe3b50b
|
095fa6fc4ee761d5dbf1b46eeec303721b6040dc
|
refs/heads/master
|
<repo_name>LarsonYong/Tetris<file_sep>/more.js
var cubeW=20;
var canvas=document.getElementById('can');
var ctx=canvas.getContext('2d');
var score=document.getElementById('score');
var canWidth=canvas.width;
var canHeight=canvas.height;
var nextInfo = {}, staticCube= [];
var next_canvas = document.getElementById('can2');
var ctx2 =next_canvas.getContext('2d');
var cubeColor =['#E91E63', '#7986CB', '#26C6DA', '#FFF176', '#4CAF50', '#1B5E20', '#6D4C41'];
var Z_r = [[5,6,10,11], [7,10,11,14], [9,10,14,15], [6,9,10,13]];
var T_r = [[6,9,10,11], [6,10,11,14], [9,10,11,14], [6,9,10,14]];
var Zn_r = [[6,7,9,10], [6,10,11,15], [10,11,13,14], [5,9,10,14]];
var L_r = [[5,9,10,11], [6,7,10,14], [9,10,11,15], [6,10,13,14]];
var Ln_r = [[7,9,10,11], [6,10,14,15], [9,10,11,13], [5,6,10,14]];
var I_r = [[8,9,10,11], [2,6,10,14], [8,9,10,11], [2,6,10,14]];
var O_r = [[5,6,9,10], [5,6,9,10], [5,6,9,10], [5,6,9,10]];
var cubeArr=[Z_r, T_r, Zn_r, L_r, Ln_r, I_r, O_r];
var nextCubeInfo = {};
var curCubeInfo = {};
var current_cube = [0,0];
var next_cube = [0,0];
window.onload=function () {
drawline();
current_cube = initCube();
initCurCube();
drawLcube_current(curCubeInfo.cube);
next_cube = initCube();
drawLcube_next(next_cube);
};
function drawline() {
ctx.lineWidth=1;
ctx.strokeStyle='#ddd';
for(var i=0;i<(canWidth/cubeW);i++)
{
ctx.moveTo(cubeW*i,0);
ctx.lineTo(cubeW*i,canHeight);
}
ctx.stroke();
for(var j=0;j<(canHeight/cubeW);j++)
{
ctx.moveTo(0,cubeW*j);
ctx.lineTo(canHeight,cubeW*j);
}
ctx.stroke();
}
function initCube() {
var type_index = Math.floor(Math.random()* cubeArr.length);
var shape_index = Math.floor(Math.random() * 4);
return [type_index, shape_index]
}
function initCurCube() {
curCubeInfo.cube = current_cube;
curCubeInfo.top = 0;
curCubeInfo.left = 100;
curCubeInfo.cubeType = cubeArr[curCubeInfo.cube[0]][0];
curCubeInfo.cubeShape = cubeArr[curCubeInfo.cube[0]][1];
curCubeInfo.position = [];
for (var i =0; i<(curCubeInfo.cubeShape.length); i++) {
var location = [curCubeInfo.cubeShape[i]%4, Math.floor((curCubeInfo.cubeShape[i])/4)];
curCubeInfo.position.push(calcExacPoint(location))
}
console.log(curCubeInfo)
}
function drawLcube_next(next_cube) {
ctx2.lineWidth = 1;
console.log(cubeArr[next_cube[0]][next_cube[1]]);
ctx2.strokeStyle='#000';
var cubeInfo = cubeArr[next_cube[0]][next_cube[1]];
for(var i=0; i<(cubeInfo.length); i++) {
var location = [(cubeInfo[i])%4, Math.floor((cubeInfo[i])/4)];
//[1, 1]
drawSCube(1, location, next_cube[0], 0);
}
}
function drawLcube_current() {
ctx.lineWidth = 1;
ctx.strokeStyle='#000';
var cubeInfo = curCubeInfo.cube;
console.log("Cube type: ", cubeInfo);
console.log("Cube shapes: ", cubeArr[cubeInfo[0]]);
console.log("Selected cube shape: ", cubeArr[cubeInfo[0]][cubeInfo[1]]);
console.log("Small cube start point: ", cubeArr[cubeInfo[0]][cubeInfo[1]][0]);
// for(var i=0; i<(cubeArr[cubeInfo[0]][cubeInfo[1]].length); i++) {
// var location = [(cubeArr[cubeInfo[0]][cubeInfo[1]][i])%4, Math.floor((cubeArr[cubeInfo[0]][cubeInfo[1]][i])/4)];
//
// drawSCube(0, location, cubeInfo[0]);
// }
for (var i = 0; i <(curCubeInfo.position.length); i++) {
drawSCube(0, curCubeInfo.position[i], curCubeInfo.cubeType)
}
}
function calcExacPoint(location) {
var x_index = location[0] * 20 + curCubeInfo.left;
var y_index = location[1] * 20 + curCubeInfo.top;
return [x_index, y_index]
}
function drawSCube(type ,position, color_index) {
// 0 for current cube, 1 for next cube
if (type == 0) {
ctx.beginPath();
// ctx.moveTo(position[0][0],position[0][1]);
// ctx.lineTo(position[1][0], position[1][1]);
// ctx.lineTo(position[2][0],position[2][1]);
// ctx.lineTo(position[3][0], position[3][1]);
ctx.moveTo((location[0]*20 + curCubeInfo.left), location[1]*20 + curCubeInfo.top);
ctx.lineTo(((location[0]*20) + 20+ curCubeInfo.left), location[1]*20 + curCubeInfo.top);
ctx.lineTo(((location[0]*20) + 20+ curCubeInfo.left), (location[1]*20 + 20+ curCubeInfo.top));
ctx.lineTo((location[0]*20+ curCubeInfo.left), (location[1]*20 + 20+ curCubeInfo.top));
ctx.lineTo((location[0]*20+ curCubeInfo.left), location[1]*20+ curCubeInfo.top);
ctx.fillStyle= cubeColor[color_index];
ctx.fill();
ctx.stroke();
}else {
ctx2.beginPath();
ctx2.moveTo((position[0]*20 ), position[1]*20);
ctx2.lineTo(((position[0]*20) + 20), position[1]*20);
ctx2.lineTo(((position[0]*20) + 20), (position[1]*20 + 20));
ctx2.lineTo((position[0]*20), (position[1]*20 + 20));
ctx2.lineTo((position[0]*20), position[1]*20);
ctx2.fillStyle= cubeColor[color_index];
ctx2.fill();
ctx2.stroke();
}
}
function moveUP(cur_cube) {
clearCurEle(cur_cube);
if (cur_cube[1] <=2) {
cur_cube[1] = cur_cube[1] + 1
}else {
cur_cube[1] = 0
}
drawLcube_current(cur_cube);
}
function clearNextEle() {
ctx2.clearRect(0,0,100,100)
}
function clearCurEle() {
var cubeInfo = curCubeInfo.cube;
for(var i=0; i<(cubeArr[cubeInfo[0]][cubeInfo[1]].length); i++) {
var location = [(cubeArr[cubeInfo[0]][cubeInfo[1]][i])%4, Math.floor((cubeArr[cubeInfo[0]][cubeInfo[1]][i])/4)];
console.log("clear location", location);
console.log(location);
ctx.fillRect(location[0]*20+ curCubeInfo.top,location[1]*20 + curCubeInfo.left,20,20);
ctx.clearRect(location[0]*20 + curCubeInfo.left,location[1]*20 + curCubeInfo.left,20,20);
}
}
window.onkeydown=function (evt)
{
switch(evt.keyCode)
{
// case 37: //左
// moveLeft();
// break;
case 38: //上
moveUP(current_cube);
break;
// case 39: //右
// moveRight();
// break;
// case 40: //下
// movedown();
// break;
}
};<file_sep>/moost.js
let cubeW=20;
let canvas=document.getElementById('can');
let ctx=canvas.getContext('2d');
let score=document.getElementById('score');
let canWidth=canvas.width;
let canHeight=canvas.height;
let nextInfo = {}, staticCube= [];
let next_canvas = document.getElementById('can2');
let ctx2 =next_canvas.getContext('2d');
let cubeColor =['#E91E63', '#7986CB', '#26C6DA', '#FFF176', '#4CAF50', '#1B5E20', '#6D4C41'];
let Z_r = [[5,6,10,11], [7,10,11,14], [9,10,14,15], [6,9,10,13]];
let T_r = [[6,9,10,11], [6,10,11,14], [9,10,11,14], [6,9,10,14]];
let Zn_r = [[6,7,9,10], [6,10,11,15], [10,11,13,14], [5,9,10,14]];
let L_r = [[5,9,10,11], [6,7,10,14], [9,10,11,15], [6,10,13,14]];
let Ln_r = [[7,9,10,11], [6,10,14,15], [9,10,11,13], [5,6,10,14]];
let I_r = [[8,9,10,11], [2,6,10,14], [8,9,10,11], [2,6,10,14]];
let O_r = [[5,6,9,10], [5,6,9,10], [5,6,9,10], [5,6,9,10]];
let cubeArr=[Z_r, T_r, Zn_r, L_r, Ln_r, I_r, O_r];
let nextCubeInfo = {};
let curCubeInfo = {};
let current_cube = [0,0];
let next_cube = [0,0];
window.onload=function () {
drawline();
initcurCube();
drawCurCube();
initnextCube();
drawNextCube();
// myinter=setInterval('moveDown()',300);
};
function initcurCube() {
//init current cube and save
current_cube = getRandomCube();
initCurCubeInfo()
}
function initnextCube() {
//init next cube
next_cube = getRandomCube()
}
function drawline() {
ctx.lineWidth=1;
ctx.strokeStyle='#dbd5db';
for(let i=0;i<(canWidth/cubeW);i++)
{
ctx.moveTo(cubeW*i,0);
ctx.lineTo(cubeW*i,canHeight);
}
ctx.stroke();
for(let j=0;j<(canHeight/cubeW);j++)
{
ctx.moveTo(0,cubeW*j);
ctx.lineTo(canHeight,cubeW*j);
}
ctx.stroke();
}
function getRandomCube() {
//generate random cube and return
let type_index = Math.floor(Math.random()* cubeArr.length);
let shape_index = Math.floor(Math.random() * 4);
return [type_index, shape_index]
}
function initCurCubeInfo() {
//save current cube info
curCubeInfo.cubeTypeIndex = current_cube[0];
curCubeInfo.cubeType = cubeArr[current_cube[0]];
curCubeInfo.cubeShapeIndex = current_cube[1];
curCubeInfo.cubeShape = curCubeInfo.cubeType[current_cube[1]];
curCubeInfo.top = -60;
curCubeInfo.left = 80;
curCubeInfo.position = [];
let selectedCubeShape = curCubeInfo.cubeShape;
for (let i =0; i<(selectedCubeShape.length); i++) {
let location = [selectedCubeShape[i]%4, Math.floor((selectedCubeShape[i])/4)];
curCubeInfo.position.push(calcExacPoint(location))
}
console.log(curCubeInfo)
}
function cubeShapetopostion(){
var selectedCubeShape = curCubeInfo.cubeShape;
curCubeInfo.position = [];
for (var i =0; i<(selectedCubeShape.length); i++) {
var location = [selectedCubeShape[i]%4, Math.floor((selectedCubeShape[i])/4)];
curCubeInfo.position.push(calcExacPoint(location))
}
// console.log(curCubeInfo);
// console.log(curCubeInfo.position)
}
function nextCubeShapetopostion(){
var selectedCubeShape = nextCubeInfo.cubeShape;
nextCubeInfo.position = [];
for (var i =0; i<(selectedCubeShape.length); i++) {
var location = [selectedCubeShape[i]%4, Math.floor((selectedCubeShape[i])/4)];
nextCubeInfo.position.push(calcExacPoint(location))
}
// console.log(nextCubeInfo);
// console.log(nextCubeInfo.position)
}
function calcExacPoint(location) {
let x_index = (location[0] + 1) * 20 + curCubeInfo.left;
let y_index = (location[1] + 1) * 20 + curCubeInfo.top;
return [x_index, y_index]
}
function drawSCube(type,location, color_index) {
//0 for current cube, 1 for next cube
if (type === 0) {
ctx.beginPath();
ctx.moveTo(location[0], location[1]);
ctx.lineTo(location[0] + 20, location[1]);
ctx.lineTo(location[0] + 20, location[1] + 20);
ctx.lineTo(location[0], location[1] + 20);
ctx.lineTo(location[0], location[1]);
ctx.fillStyle= cubeColor[color_index];
ctx.fill();
ctx.stroke();
}else {
ctx2.beginPath();
ctx2.moveTo((location[0]*20 + 20), location[1]*20+ 20);
ctx2.lineTo(((location[0]*20) + 40), location[1]*20 + 20);
ctx2.lineTo(((location[0]*20) + 40), (location[1]*20 + 40));
ctx2.lineTo((location[0]*20 + 20), (location[1]*20 + 40));
ctx2.lineTo((location[0]*20 + 20), location[1]*20 + 20);
ctx2.fillStyle= cubeColor[color_index];
ctx2.fill();
ctx2.stroke();
}
}
function drawCurCube() {
ctx.lineWidth = 1;
ctx.strokeStyle='#fff';
for (let i = 0; i <(curCubeInfo.position.length); i++) {
drawSCube(0, curCubeInfo.position[i], current_cube[0])
}
}
function drawNextCube() {
ctx2.fillRect(20,20,80,100);
ctx2.clearRect(20,20,80,80);
ctx2.lineWidth = 1;
console.log(cubeArr[next_cube[0]][next_cube[1]]);
ctx2.strokeStyle='#fff';
let cubeInfo = cubeArr[next_cube[0]][next_cube[1]];
for(let i=0; i<(cubeInfo.length); i++) {
let location = [(cubeInfo[i])%4, Math.floor((cubeInfo[i])/4)];
//[1, 1]
drawSCube(1, location, next_cube[0], 0);
}
}
function clearCurEle() {
ctx.lineWidth=1;
ctx.strokeStyle='#ddd';
let position = curCubeInfo.position;
for (let i =0; i < (position.length); i++) {
ctx.clearRect(position[i][0], position[i][1], cubeW, cubeW);
ctx.strokeRect(position[i][0], position[i][1],cubeW, cubeW);
}
}
function drawDcube(location) {
ctx.beginPath();
ctx.moveTo(location[0], location[1]);
ctx.lineTo(location[0] + 20, location[1]);
ctx.lineTo(location[0] + 20, location[1] + 20);
ctx.lineTo(location[0], location[1] + 20);
ctx.lineTo(location[0], location[1]);
ctx.fillStyle= '#555';
ctx.fill();
ctx.stroke();
}
function drawStaticCube() {
for (let i =0; i< curCubeInfo.position.length; i++) {
drawDcube(curCubeInfo.position[0]);
drawDcube(curCubeInfo.position[1]);
drawDcube(curCubeInfo.position[2]);
drawDcube(curCubeInfo.position[3]);
}
}
function pushNextCube() {
current_cube = next_cube;
initCurCubeInfo();
initnextCube();
}
function checkhorizontalValid() {
nextCubeShapetopostion();
let valid = 0;
for (let i=0; i <(nextCubeInfo.position.length); i++) {
//nextCubeInfo.position[i][0] >= 280 || nextCubeInfo.position[i][0] <= 0
if (nextCubeInfo.position[i][0] >= 280 || nextCubeInfo.position[i][0] <= 0 || staticCube[nextCubeInfo.position] === 1){
valid =1;
}
//nextCubeInfo.position[i][0] === 480
//staticCube[nextCubeInfo.position] === 1
}
return valid
}
function checkVerticalValid() {
nextCubeShapetopostion();
let valid = 0;
for (let i=0; i <(nextCubeInfo.position.length); i++) {
console.log();
if (nextCubeInfo.position[i][1] === 480 ||staticCube[nextCubeInfo.position[i]] === 1){
valid =1;
}
}
console.log(valid);
return valid
}
function checkRotate() {
}
function drawLcube_next(next_cube) {
ctx2.lineWidth = 1;
console.log(cubeArr[next_cube[0]][next_cube[1]]);
ctx2.strokeStyle='#000';
let cubeInfo = cubeArr[next_cube[0]][next_cube[1]];
for(let i=0; i<(cubeInfo.length); i++) {
let location = [(cubeInfo[i])%4, Math.floor((cubeInfo[i])/4)];
//[1, 1]
drawSCube(1, location, next_cube[0], 0);
}
}
function drawLcube_current() {
ctx.lineWidth = 1;
ctx.strokeStyle='#000';
let cubeInfo = curCubeInfo.cube;
// console.log("Cube type: ", cubeInfo);
// console.log("Cube shapes: ", cubeArr[cubeInfo[0]]);
// console.log("Selected cube shape: ", cubeArr[cubeInfo[0]][cubeInfo[1]]);
// console.log("Small cube start point: ", cubeArr[cubeInfo[0]][cubeInfo[1]][0]);
for (let i = 0; i <(curCubeInfo.position.length); i++) {
drawSCube(0, curCubeInfo.position[i], curCubeInfo.cubeType)
}
}
function moveDown() {
clearCurEle();
nextCubeInfo = curCubeInfo;
nextCubeInfo.top = curCubeInfo.top + 20;
if (!checkVerticalValid()) {
curCubeInfo = nextCubeInfo;
drawCurCube();
}else {
staticCube[nextCubeInfo.position[0]] = 1;
staticCube[nextCubeInfo.position[1]] = 1;
staticCube[nextCubeInfo.position[2]] = 1;
staticCube[nextCubeInfo.position[3]] = 1;
console.log(staticCube);
drawStaticCube();
curCubeInfo = nextCubeInfo;
pushNextCube();
drawNextCube();
cubeShapetopostion();
drawCurCube();
}
}
function moveUp() {
let curShapeIndex = curCubeInfo.cubeShapeIndex;
var nextShapeIndex = 0;
if (curShapeIndex <= 2) {
nextShapeIndex = curShapeIndex + 1
}else {
nextShapeIndex = 0;
}
nextCubeInfo = curCubeInfo;
nextCubeInfo.cubeShape = cubeArr[current_cube[0]][nextShapeIndex];
nextCubeShapetopostion();
}
function moveRight() {
}
function moveLeft() {
}
window.onkeydown=function (evt)
{
switch(evt.keyCode)
{
case 37: //Left
moveLeft();
break;
case 38: //Up
moveUP();
break;
case 39: //Right
moveRight();
break;
case 40: //Down
moveDown();
break;
}
};<file_sep>/less.js
var Z = [5,6,10,11];
var T = [6,9,10,11];
var Zn = [6,7,9,10];
var L = [5,9,10,11];
var Ln = [7,9,10,11];
var I = [2,6,10,14];
var O = [5,6,9,10];
var cubeArr = [Z, T, Zn, L, Ln, I, O];
var Z_r = [[5,6,10,11], [7,10,11,14], [9,10,14,15], [6,9,10,13]];
var T_r = [[6,9,10,11], [6,10,11,14], [9,10,11,14], [6,9,10,14]];
var Zn_r = [[6,7,9,10], [6,10,11,15], [10,11,13,14], [5,9,10,14]];
var L_r = [[5,9,10,11], [6,7,10,14], [9,10,11,15], [6,10,13,14]];
var Ln_r = [[7,9,10,11], [6,10,14,15], [9,10,11,13], [5,6,10,14]];
var I_r = [[8,9,10,11], [2,6,10,14], [8,9,10,11], [2,6,10,14]];
var O_r = [[5,6,9,10], [5,6,9,10], [5,6,9,10], [5,6,9,10]];
var cubeW=20;
var canvas=document.getElementById('can');
var ctx=canvas.getContext('2d');
var score=document.getElementById('score');
var canWidth=canvas.width;
var canHeight=canvas.height;
var nextInfo = {};
var next_canvas = document.getElementById('can2');
var ctx2 =next_canvas.getContext('2d');
var rotate_counter = 0;
window.onload=function()
{
drawline();
// for(var i=0;i<(canWidth/cubeW);i++)
// {
// staticCube[i]=[];
// for(var j=0;j<(canHeight/cubeW);j++)
// {
// staticCube[i][j]=0;
// }
// }
// initCube();
drawCube();
// myinter=setInterval('movedown()',200);
}
function drawline()
{
ctx.lineWidth=1;
ctx.strokeStyle='#ddd';
for(var i=0;i<(canWidth/cubeW);i++)
{
ctx.moveTo(cubeW*i,0);
ctx.lineTo(cubeW*i,canHeight);
}
ctx.stroke();
for(var j=0;j<(canHeight/cubeW);j++)
{
ctx.moveTo(0,cubeW*j);
ctx.lineTo(canHeight,cubeW*j);
}
ctx.stroke();
}
function drawCube() {
var index = Math.floor(Math.random()* cubeArr.length);
ctx2.lineWidth = 1;
console.log(index);
console.log(cubeArr[index]);
ctx2.strokeStyle='#000';
nextInfo.CubeNow = cubeArr[index];
nextInfo.CubeIndex = index;
for(var i=0; i<(cubeArr[index].length); i++) {
// var location = [Math.floor((cubeArr[index][i])/4), (cubeArr[index][i])%4];
var location = [(cubeArr[index][i])%4, Math.floor((cubeArr[index][i])/4)];
//[1, 1]
console.log("location: ", location);
drawSCube(location);
}
}
function drawSCube(location) {
ctx2.beginPath();
ctx2.moveTo((location[0]*20), location[1]*20);
ctx2.lineTo(((location[0]*20) + 20), location[1]*20);
ctx2.lineTo(((location[0]*20) + 20), (location[1]*20 + 20));
ctx2.lineTo((location[0]*20), (location[1]*20 + 20));
ctx2.lineTo((location[0]*20), location[1]*20);
ctx2.stroke();
}
function clearEle(location) {
}
function moveUP() {
rotate_counter = rotate_counter + 1;
nextInfo.index
}
window.onkeydown=function (evt)
{
switch(evt.keyCode)
{
// case 37: //左
// moveLeft();
// break;
case 38: //上
moveUP();
break;
// case 39: //右
// moveRight();
// break;
// case 40: //下
// movedown();
// break;
}
}
|
6b109e611b6c39cfb64b9fd41e49bd7d5aeadeab
|
[
"JavaScript"
] | 3
|
JavaScript
|
LarsonYong/Tetris
|
303e6d6057150fb979a6db975a35af2e005b7780
|
c0c393184a82bb51104112d618a6bacb0da77f14
|
refs/heads/main
|
<file_sep>package com.example.myapplication;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SecondActivity extends AppCompatActivity {
Button end;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
end = findViewById(R.id.end);
end.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SecondActivity.this,MainActivity.class));
}
});
}
@Override
public void onBackPressed(){
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit").setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).setNegativeButton("No", null).show();
}
}
|
7207dbee58f37b0deb604ef29c5d68b52e5128ba
|
[
"Java"
] | 1
|
Java
|
FreylGit/android
|
98fbfc952b25b29ad2306ee519ee04d8e7368730
|
035bead68cd1c5b4b6b4e91f2911a38c105ba533
|
refs/heads/master
|
<repo_name>DustinRoundy/Starwars<file_sep>/src/app/character/character.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import {Character} from "../models/character";
@Pipe({
name: 'character'
})
export class CharacterPipe implements PipeTransform {
transform(characters: any, args?: any): any {
return characters.filter((character: Character) =>
character.name.toLowerCase().includes(args.toLowerCase())
);
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { SidenavContentComponent } from './sidenav/sidenav-content/sidenav-content.component';
import { ForceChangeDialogComponent } from './shared/force/force-change-dialog/force-change-dialog.component';
import {HttpClientModule} from "@angular/common/http";
import {HttpClientInMemoryWebApiModule} from "angular-in-memory-web-api";
import {InMemoryDataService} from "./in-memory-data.service";
import {RouterModule} from "@angular/router";
import { WelcomeComponent } from './welcome/welcome.component';
import { SidenavContainerComponent } from './sidenav/sidenav-container/sidenav-container.component';
import {CharacterModule} from "./character/character.module";
import {FormsModule} from "@angular/forms";
import {MaterialModule} from "./material/material.module";
import {CommonModule} from "@angular/common";
import {AngularFireModule} from "@angular/fire";
import {environment} from "../environments/environment";
import { SignUpComponent } from './auth/sign-up/sign-up.component';
import {AngularFireAuthModule} from "@angular/fire/auth";
// import {CharacterService} from "./character/character.service";
@NgModule({
declarations: [
AppComponent,
SidenavContentComponent,
WelcomeComponent,
SidenavContainerComponent,
SignUpComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
RouterModule.forRoot([]),
BrowserAnimationsModule,
FormsModule,
MaterialModule,
CharacterModule,
HttpClientModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireAuthModule,
HttpClientInMemoryWebApiModule.forRoot(
InMemoryDataService, { dataEncapsulation: false}
)
],
providers: [],
entryComponents: [ForceChangeDialogComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/shared/force/force.component.ts
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {MatDialog} from "@angular/material";
import {ForceChangeDialogComponent} from "./force-change-dialog/force-change-dialog.component";
@Component({
selector: 'dr-force',
templateUrl: './force.component.html',
styleUrls: ['./force.component.sass']
})
export class ForceComponent implements OnInit {
@Input() forceStrength: number;
@Output() onForceChange: EventEmitter<number> = new EventEmitter();
constructor(private dialog: MatDialog) {
}
ngOnInit() {
}
onForceClick() {
let dialogRef = this.dialog.open(ForceChangeDialogComponent, {
width: '400px',
data: { force: this.forceStrength }
});
dialogRef.afterClosed().subscribe(force => {
if (force) {
this.onForceChange.emit(force);
}
});
}
width() {
return this.forceStrength * 12;
}
}
<file_sep>/README.md
# Starwars Characters
This project is a simple angular app to demonstrate the usage of components in Angular
## Demo
A demo can be found [here.](https://starwars-characters-4a1c7.firebaseapp.com/welcome)
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
<file_sep>/src/app/character/character-detail/character-detail.component.ts
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {Character} from "../../models/character";
import {CharacterService} from "../character.service";
import {CharacterListComponent} from "../character-list/character-list.component";
import { Location } from '@angular/common';
@Component({
selector: 'dr-character-detail',
templateUrl: './character-detail.component.html',
styleUrls: ['./character-detail.component.sass']
})
export class CharacterDetailComponent implements OnInit {
character: Character;
constructor(private activatedRoute: ActivatedRoute, private characterService: CharacterService, private location: Location) {
}
ngOnInit() {
this.activatedRoute.data.subscribe(data => {
// this.characterService.getCharacters().subscribe((characters: Character[]) => {
// this.character = characters.find((character: Character) => character.id == params.id);
// });
console.log(data.character);
this.character = data.character;
})
}
delete(character: Character):void {
this.characterService.deleteCharacter(character).subscribe();
console.log("delete");
console.log(character);
// CharacterListComponent.getCharacters();
// this.location.back();
}
}
<file_sep>/src/app/auth/sign-up/sign-up.component.ts
import { Component, OnInit } from '@angular/core';
import {AngularFireAuth} from "@angular/fire/auth";
import {Router} from "@angular/router";
import {auth} from "firebase";
@Component({
selector: 'dr-sign-up',
templateUrl: './sign-up.component.html',
styleUrls: ['./sign-up.component.sass']
})
export class SignUpComponent implements OnInit {
email: string;
password: string;
constructor(private angularFireAuth: AngularFireAuth, private router: Router) { }
ngOnInit() {
}
signUp(){
this.angularFireAuth.auth.createUserWithEmailAndPassword(this.email, this.password)
.then(user => {
console.log(user);
})
.catch(error => {
console.log(error);
});
}
signIn(){
this.angularFireAuth.auth.signInWithEmailAndPassword(this.email, this.password)
.then(user => {
if(user) {
this.router.navigate(['/characters']);
}
})
}
signInWithGoogle() {
this.angularFireAuth.auth.signInWithPopup(new auth.GoogleAuthProvider()).then(user => {
console.log(user);
if (user) {
this.router.navigate(['/characters'])
}
});
}
}
<file_sep>/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {WelcomeComponent} from "./welcome/welcome.component";
import {SidenavContainerComponent} from "./sidenav/sidenav-container/sidenav-container.component";
import {CharacterDetailComponent} from "./character/character-detail/character-detail.component";
import {CharacterResolveGuard} from "./character/character-resolve.guard";
import {CanActivateContentGuard} from "./auth/can-activate-content.guard";
import {SignUpComponent} from "./auth/sign-up/sign-up.component";
const routes: Routes = [
{
path:'characters',
component: SidenavContainerComponent,
canActivate: [CanActivateContentGuard],
children: [
{
path: ':id',
resolve: { character: CharacterResolveGuard },
component: CharacterDetailComponent,
}
]
},
{
path: 'welcome',
component: WelcomeComponent,
},
{
path: 'signup',
component: SignUpComponent,
},
{
path: '**',
redirectTo: 'welcome',
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/app/shared/shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {ForceComponent} from "./force/force.component";
import {ForceChangeDialogComponent} from "./force/force-change-dialog/force-change-dialog.component";
import {FormsModule} from "@angular/forms";
import {MaterialModule} from "../material/material.module";
@NgModule({
declarations: [
ForceComponent,
ForceChangeDialogComponent
],
imports: [
CommonModule,
FormsModule,
MaterialModule
],
exports: [
FormsModule,
MaterialModule,
ForceChangeDialogComponent,
ForceComponent,
]
})
export class SharedModule { }
<file_sep>/src/app/character/character.service.ts
import { Injectable } from '@angular/core';
import { Character} from "../models/character";
import {HttpClient} from "@angular/common/http";
import {Observable, of} from "rxjs";
import {Hero} from "../../../../../toh-pt5/src/app/hero";
import {switchMap, take} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class CharacterService {
private Url = 'api/characters/';
constructor(private httpClient: HttpClient) {
this.playingWithObservable();
}
getCharacters(): Observable<Character[]>{
return this.httpClient.get<Character[]>(this.Url);
}
getCharacter(id: number): Observable<Character>{
// return this.httpClient.get<Character[]>(this.Url).pipe(
// switchMap((characters: Character[]) =>
// of(characters.find((character: Character) => character.id == id)
// ))
// )
return this.httpClient.get<Character>(`${this.Url}${id}`);
}
updateCharacter (character: Character): Observable<any> {
return this.httpClient.put(this.Url, character);
}
addCharacter (character: Character): Observable<Character> {
return this.httpClient.post<Character>(this.Url, character);
}
deleteCharacter (character: Character | number): Observable<Character> {
const id = typeof character === 'number' ? character : character.id;
const url = `${this.Url}${id}`;
console.log(url);
return this.httpClient.delete<Hero>(url);
}
playingWithObservable() {
let ourObservable = Observable.create(observer => {
observer.next(1);
observer.next(2);
observer.next(3);
setTimeout(() => {
observer.next(4);
observer.complete();
}, 1000);
});
ourObservable.subscribe(value => {
console.log(value);
});
ourObservable.pipe(
take(1)
).subscribe(value => {
console.log(value);
})
}
}
<file_sep>/src/app/shared/force/force-change-dialog/force-change-dialog.component.ts
import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";
@Component({
selector: 'dr-force-change-dialog',
templateUrl: './force-change-dialog.component.html',
styleUrls: ['./force-change-dialog.component.sass']
})
export class ForceChangeDialogComponent implements OnInit {
force: number;
constructor(private dialogRef: MatDialogRef<ForceChangeDialogComponent>, @Inject(MAT_DIALOG_DATA) private data) { }
ngOnInit() {
this.force = this.data.force;
}
onNoClick() {
this.dialogRef.close();
}
}
<file_sep>/src/app/character/character-resolve.guard.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {Observable, of} from 'rxjs';
import {Character} from "../models/character";
import {CharacterService} from "./character.service";
@Injectable({
providedIn: 'root'
})
export class CharacterResolveGuard implements Resolve<Character> {
constructor(private characterService: CharacterService){
}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> | Promise<any> | any {
// route.params.id
return this.characterService.getCharacter(route.params.id);
}
}
<file_sep>/src/app/app.component.ts
import {Component, OnDestroy, OnInit} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit, OnDestroy{
title = 'sample-app';
ngOnInit() {
console.log('OnInit!');
}
ngOnDestroy() {
console.log('destroy!')
}
}
<file_sep>/src/app/auth/can-activate-content.guard.spec.ts
import { TestBed, async, inject } from '@angular/core/testing';
import { CanActivateContentGuard } from './can-activate-content.guard';
describe('CanActivateContentGuard', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [CanActivateContentGuard]
});
});
it('should ...', inject([CanActivateContentGuard], (guard: CanActivateContentGuard) => {
expect(guard).toBeTruthy();
}));
});
<file_sep>/src/app/character/character.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {CharacterPipe} from "./character.pipe";
import {CharacterDetailComponent} from "./character-detail/character-detail.component";
import {MaterialModule} from "../material/material.module";
import {SharedModule} from "../shared/shared.module";
import {CharacterListComponent} from "./character-list/character-list.component";
@NgModule({
declarations: [
CharacterListComponent,
CharacterPipe,
CharacterDetailComponent,
],
imports: [
CommonModule,
MaterialModule,
SharedModule
],
exports: [
CharacterListComponent,
CharacterDetailComponent,
CharacterPipe,
]
})
export class CharacterModule { }
<file_sep>/src/app/character/character-list/character-list.component.ts
import { Component, OnInit } from '@angular/core';
import {Character} from "../../models/character";
import {CharacterService} from "../character.service";
import {Observable} from "rxjs";
import {Router} from "@angular/router";
@Component({
selector: 'dr-character-list',
templateUrl: './character-list.component.html',
styleUrls: ['./character-list.component.sass']
})
export class CharacterListComponent implements OnInit {
constructor(private characterService: CharacterService, private router: Router) {
}
hideDetails = true;
characterFilter: string = '';
dateToRemember: Date = new Date(1999, 12, 12);
characterArray: Character[] = [];
ngOnInit() {
this.getCharacters();
// this.characterArray = [];
}
toggleDetails(): void {
this.hideDetails = this.hideDetails != true;
}
updateForce(character: Character, $event) {
character.force = $event;
this.characterService.updateCharacter(character);
}
getCharacters(): void {
this.characterService.getCharacters()
.subscribe(characters => this.characterArray = characters);
}
goToCharacter(id: number){
this.router.navigate([`characters/${id}`]);
console.log(`characters/${id}`);
}
}
<file_sep>/src/app/auth/auth.service.ts
import { Injectable } from '@angular/core';
import {AngularFireAuth} from "@angular/fire/auth";
import {map} from "rxjs/operators";
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private angularFireAuth: AngularFireAuth) { }
isAuthenticated() {
return this.angularFireAuth.authState.pipe(
map(user => user && user.uid ? true : false)
);
}
}
<file_sep>/src/app/models/character.ts
export interface Character {
id: number;
name: string;
height?: number;
mass?: number;
hair_color?: string;
eye_color?: string;
skin_color?: string;
birth_year?: string;
gender?: string;
force?: number;
avatar?: string;
img?: string;
homeworld?: string;
films?: string[];
species?: string[];
vehicles?: string[];
starships?: string[];
created?: string;
edited?: string;
url?: string;
}
|
51311532d6f83a5b4c9928158cde9bdcccddc638
|
[
"Markdown",
"TypeScript"
] | 17
|
TypeScript
|
DustinRoundy/Starwars
|
874e01e8a7297efaa5a9b1c8ba15cf358f2220f0
|
d4f60f1d63a0c3e8bffb2e9ec7932d5a33bbc39f
|
refs/heads/master
|
<repo_name>IMCG/Dat3M<file_sep>/dartagnan/src/main/java/com/dat3m/dartagnan/parsers/program/visitors/boogie/PthreadsFunctions.java
package com.dat3m.dartagnan.parsers.program.visitors.boogie;
import static com.dat3m.dartagnan.expression.op.COpBin.EQ;
import static com.dat3m.dartagnan.expression.op.COpBin.NEQ;
import static com.dat3m.dartagnan.program.atomic.utils.Mo.SC;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import com.dat3m.dartagnan.expression.Atom;
import com.dat3m.dartagnan.expression.ExprInterface;
import com.dat3m.dartagnan.expression.IConst;
import com.dat3m.dartagnan.expression.IExpr;
import com.dat3m.dartagnan.parsers.BoogieParser.Call_cmdContext;
import com.dat3m.dartagnan.parsers.BoogieParser.ExprContext;
import com.dat3m.dartagnan.program.Register;
import com.dat3m.dartagnan.program.atomic.event.AtomicLoad;
import com.dat3m.dartagnan.program.atomic.event.AtomicStore;
import com.dat3m.dartagnan.program.event.Assume;
import com.dat3m.dartagnan.program.event.CondJump;
import com.dat3m.dartagnan.program.event.Event;
import com.dat3m.dartagnan.program.event.Label;
import com.dat3m.dartagnan.program.event.Load;
import com.dat3m.dartagnan.program.event.Store;
import com.dat3m.dartagnan.program.memory.Location;
import com.dat3m.dartagnan.program.utils.EType;
import com.google.common.base.Joiner;
public class PthreadsFunctions {
public static List<String> PTHREADFUNCTIONS = Arrays.asList(
"pthread_create",
"pthread_join",
"pthread_mutex_init",
"pthread_mutex_lock",
"pthread_mutex_unlock");
public static void handlePthreadsFunctions(VisitorBoogie visitor, Call_cmdContext ctx) {
String name = ctx.call_params().Define() == null ? ctx.call_params().Ident(0).getText() : ctx.call_params().Ident(1).getText();
if(name.contains("pthread_create")) {
pthread_create(visitor, ctx);
return;
}
if(name.contains("pthread_join")) {
pthread_join(visitor, ctx);
return;
}
if(name.contains("pthread_mutex_init")) {
mutexInit(visitor, ctx);
return;
}
if(name.contains("pthread_mutex_lock")) {
mutexLock(visitor, ctx);
return;
}
if(name.contains("pthread_mutex_unlock")) {
mutexUnlock(visitor, ctx);
return;
}
throw new UnsupportedOperationException(name + " funcition is not part of " + Joiner.on(",").join(PTHREADFUNCTIONS));
}
private static void pthread_create(VisitorBoogie visitor, Call_cmdContext ctx) {
String namePtr = ctx.call_params().exprs().expr().get(0).getText();
// This names are global so we don't use currentScope.getID(), but per thread.
Register threadPtr = visitor.programBuilder.getOrCreateRegister(visitor.threadCount, namePtr);
String threadName = ctx.call_params().exprs().expr().get(2).getText();
ExprInterface callingValue = (ExprInterface)ctx.call_params().exprs().expr().get(3).accept(visitor);
visitor.mainCallingValues.clear();
visitor.mainCallingValues.add(callingValue);
visitor.pool.add(threadPtr, threadName);
Location loc = visitor.programBuilder.getOrCreateLocation(threadPtr + "_active");
visitor.programBuilder.addChild(visitor.threadCount, new AtomicStore(loc.getAddress(), new IConst(1), SC));
}
private static void pthread_join(VisitorBoogie visitor, Call_cmdContext ctx) {
String namePtr = ctx.call_params().exprs().expr().get(0).getText();
// This names are global so we don't use currentScope.getID(), but per thread.
Register callReg = visitor.programBuilder.getOrCreateRegister(visitor.threadCount, namePtr);
if(visitor.pool.getPtrFromReg(callReg) == null) {
throw new UnsupportedOperationException("pthread_join cannot be handled");
}
Location loc = visitor.programBuilder.getOrCreateLocation(visitor.pool.getPtrFromReg(callReg) + "_active");
Register reg = visitor.programBuilder.getOrCreateRegister(visitor.threadCount, null);
Label label = visitor.programBuilder.getOrCreateLabel("END_OF_T" + visitor.threadCount);
visitor.programBuilder.addChild(visitor.threadCount, new AtomicLoad(reg, loc.getAddress(), SC));
visitor.programBuilder.addChild(visitor.threadCount, new Assume(new Atom(reg, EQ, new IConst(0)), label));
}
private static void mutexInit(VisitorBoogie visitor, Call_cmdContext ctx) {
ExprContext lock = ctx.call_params().exprs().expr(0);
ExprContext value = ctx.call_params().exprs().expr(1);
IExpr lockAddress = (IExpr)lock.accept(visitor);
IExpr val = (IExpr)value.accept(visitor);
if(lockAddress != null) {
visitor.programBuilder.addChild(visitor.threadCount, new Store(lockAddress, val, null));
}
}
private static void mutexLock(VisitorBoogie visitor, Call_cmdContext ctx) {
Register register = visitor.programBuilder.getOrCreateRegister(visitor.threadCount, null);
IExpr lockAddress = (IExpr)ctx.call_params().exprs().accept(visitor);
Label label = visitor.programBuilder.getOrCreateLabel("END_OF_T" + visitor.threadCount);
if(lockAddress != null) {
LinkedList<Event> events = new LinkedList<>();
events.add(new Load(register, lockAddress, null));
events.add(new CondJump(new Atom(register, NEQ, new IConst(0)),label));
events.add(new Store(lockAddress, new IConst(1), null));
for(Event e : events) {
e.addFilters(EType.LOCK, EType.RMW);
visitor.programBuilder.addChild(visitor.threadCount, e);
}
}
}
private static void mutexUnlock(VisitorBoogie visitor, Call_cmdContext ctx) {
Register register = visitor.programBuilder.getOrCreateRegister(visitor.threadCount, null);
IExpr lockAddress = (IExpr)ctx.call_params().exprs().accept(visitor);
Label label = visitor.programBuilder.getOrCreateLabel("END_OF_T" + visitor.threadCount);
if(lockAddress != null) {
LinkedList<Event> events = new LinkedList<>();
events.add(new Load(register, lockAddress, null));
events.add(new CondJump(new Atom(register, NEQ, new IConst(1)),label));
events.add(new Store(lockAddress, new IConst(0), null));
for(Event e : events) {
e.addFilters(EType.LOCK, EType.RMW);
visitor.programBuilder.addChild(visitor.threadCount, e);
}
}
}
}
<file_sep>/dartagnan/src/main/java/com/dat3m/dartagnan/program/memory/Address.java
package com.dat3m.dartagnan.program.memory;
import com.google.common.collect.ImmutableSet;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
import com.microsoft.z3.IntExpr;
import com.microsoft.z3.Model;
import com.dat3m.dartagnan.expression.ExprInterface;
import com.dat3m.dartagnan.expression.IConst;
import com.dat3m.dartagnan.program.Register;
import com.dat3m.dartagnan.program.event.Event;
public class Address extends IConst implements ExprInterface {
private final int index;
private Integer constValue;
Address(int index){
super(index);
this.index = index;
}
@Override
public ImmutableSet<Register> getRegs(){
return ImmutableSet.of();
}
@Override
public IntExpr toZ3Int(Event e, Context ctx){
return toZ3Int(ctx);
}
@Override
public IntExpr getLastValueExpr(Context ctx){
return toZ3Int(ctx);
}
public IntExpr getLastMemValueExpr(Context ctx){
return ctx.mkIntConst("last_val_at_memory_" + index);
}
@Override
public BoolExpr toZ3Bool(Event e, Context ctx){
return ctx.mkTrue();
}
@Override
public String toString(){
return "&mem" + index;
}
@Override
public int hashCode(){
return index;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
return index == ((Address)obj).index;
}
@Override
public IntExpr toZ3Int(Context ctx){
return ctx.mkIntConst("memory_" + index);
}
@Override
public int getIntValue(Event e, Context ctx, Model model){
return Integer.parseInt(model.getConstInterp(toZ3Int(ctx)).toString());
}
public boolean hasConstValue() {
return constValue != null;
}
public Integer getConstValue() {
return constValue;
}
public void setConstValue(Integer value) {
this.constValue = value;
}
}
<file_sep>/svcomp/src/main/java/com/dat3m/svcomp/options/SVCOMPOptions.java
package com.dat3m.svcomp.options;
import static java.util.stream.IntStream.rangeClosed;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;
import com.dat3m.dartagnan.utils.options.BaseOptions;
import com.google.common.collect.ImmutableSet;
public class SVCOMPOptions extends BaseOptions {
protected Set<String> supportedFormats = ImmutableSet.copyOf(Arrays.asList("c", "i"));
protected List<Integer> bounds = rangeClosed(1, 10000).boxed().collect(Collectors.toList());
protected String optimization = "O0";
protected boolean witness;
protected boolean cegar;
public SVCOMPOptions(){
super();
Option catOption = new Option("cat", true,
"Path to the CAT file");
catOption.setRequired(true);
addOption(catOption);
Option cegarOption = new Option("cegar", false,
"Use CEGAR");
addOption(cegarOption);
Option witnessOption = new Option("w", "witness", false,
"Creates a violation witness");
addOption(witnessOption);
Option optOption = new Option("o", "optimization", true,
"Optimization flag for LLVM compiler");
addOption(optOption);
}
public void parse(String[] args) throws ParseException, RuntimeException {
super.parse(args);
if(supportedFormats.stream().map(f -> programFilePath.endsWith(f)). allMatch(b -> b.equals(false))) {
throw new RuntimeException("Unrecognized program format");
}
CommandLine cmd = new DefaultParser().parse(this, args);
if(cmd.hasOption("optimization")) {
optimization = cmd.getOptionValue("optimization");
}
witness = cmd.hasOption("witness");
cegar = cmd.hasOption("cegar");
}
public String getOptimization(){
return optimization;
}
public boolean getGenerateWitness(){
return witness;
}
public boolean getCegar(){
return cegar;
}
public List<Integer> getBounds() {
return bounds;
}
}
<file_sep>/porthos/src/main/java/com/dat3m/porthos/utils/options/PorthosOptions.java
package com.dat3m.porthos.utils.options;
import com.dat3m.dartagnan.utils.options.BaseOptions;
import com.dat3m.dartagnan.wmm.utils.Arch;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.Set;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;
public class PorthosOptions extends BaseOptions {
private String sourceModelFilePath;
private Arch source;
protected Set<String> supportedFormats = ImmutableSet.copyOf(Arrays.asList("pts"));
public PorthosOptions(){
super();
Option sourceCatOption = new Option("scat", true,
"Path to the CAT file of the source memory model");
sourceCatOption.setRequired(true);
addOption(sourceCatOption);
Option targetCatOption = new Option("tcat", true,
"Path to the CAT file of the target memory model");
targetCatOption.setRequired(true);
addOption(targetCatOption);
Option sourceOption = new Option("s", "source", true,
"Source architecture {none|arm|arm8|power|tso}");
sourceOption.setRequired(true);
addOption(sourceOption);
}
public void parse(String[] args) throws ParseException, RuntimeException {
super.parse(args);
if(supportedFormats.stream().map(f -> programFilePath.endsWith(f)). allMatch(b -> b.equals(false))) {
throw new RuntimeException("Unrecognized program format");
}
CommandLine cmd = new DefaultParser().parse(this, args);
sourceModelFilePath = cmd.getOptionValue("scat");
targetModelFilePath = cmd.getOptionValue("tcat");
source = Arch.get(cmd.getOptionValue("source"));
target = Arch.get(cmd.getOptionValue("target"));
}
public String getSourceModelFilePath(){
return sourceModelFilePath;
}
public Arch getSource(){
return source;
}
}
<file_sep>/benchmarks/genmc/fib_bench0.c
#include <assert.h>
#include <pthread.h>
#include <stdatomic.h>
atomic_int x = ATOMIC_VAR_INIT(1);
atomic_int y = ATOMIC_VAR_INIT(1);
#ifndef NUM
#define NUM 5
#endif
void *thread_1(void* arg)
{
for (int i = 0; i < NUM; i++) {
int prev_x = atomic_load_explicit(&x, memory_order_acquire);
int prev_y = atomic_load_explicit(&y, memory_order_acquire);
atomic_store_explicit(&x, prev_x + prev_y, memory_order_release);
}
return NULL;
}
void *thread_2(void* arg)
{
for (int i = 0; i < NUM; i++) {
int prev_x = atomic_load_explicit(&x, memory_order_acquire);
int prev_y = atomic_load_explicit(&y, memory_order_acquire);
atomic_store_explicit(&y, prev_x + prev_y, memory_order_release);
}
return NULL;
}
void *thread_3(void *arg)
{
if (atomic_load_explicit(&x, memory_order_acquire) > 144 ||
atomic_load_explicit(&y, memory_order_acquire) > 144)
assert(0);
return NULL;
}
int main()
{
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, thread_1, NULL);
pthread_create(&t2, NULL, thread_2, NULL);
pthread_create(&t3, NULL, thread_3, NULL);
return 0;
}
<file_sep>/svcomp/src/main/java/com/dat3m/svcomp/SVCOMPRunner.java
package com.dat3m.svcomp;
import static com.dat3m.dartagnan.utils.Compilation.compile;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.commons.cli.HelpFormatter;
import com.dat3m.dartagnan.parsers.program.ProgramParser;
import com.dat3m.dartagnan.program.Program;
import com.dat3m.svcomp.options.SVCOMPOptions;
import com.dat3m.svcomp.utils.SVCOMPSanitizer;
import com.dat3m.svcomp.utils.SVCOMPWitness;
public class SVCOMPRunner {
public static void main(String[] args) {
SVCOMPOptions options = new SVCOMPOptions();
try {
options.parse(args);
}
catch (Exception e){
if(e instanceof UnsupportedOperationException){
System.out.println(e.getMessage());
}
new HelpFormatter().printHelp("SVCOMP Runner", options);
System.exit(1);
return;
}
File file = new SVCOMPSanitizer(options.getProgramFilePath()).run(1);
String path = file.getAbsolutePath();
// File name contains "_tmp.c"
String name = path.substring(path.lastIndexOf('/'), path.lastIndexOf('_'));
int bound = 1;
String output = "BPASS";
while((output.equals("BPASS") || output.equals("BFAIL"))) {
try {
compile(file, options.getOptimization());
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(0);
}
// If not removed here, file is not removed when we reach the timeout
// File can be safely deleted since it was created by the SVCOMPSanitizer
// (it not the original C file) and we already created the Boogie file
file.delete();
ArrayList<String> cmd = new ArrayList<String>();
cmd.add("java");
cmd.add("-jar");
cmd.add("dartagnan/target/dartagnan-2.0.6-jar-with-dependencies.jar");
cmd.add("-i");
cmd.add("./output/" + name + "-" + options.getOptimization() + ".bpl");
cmd.add("-cat");
cmd.add(options.getTargetModelFilePath());
cmd.add("-t");
cmd.add("none");
cmd.add("-unroll");
cmd.add(String.valueOf(bound));
if(options.getCegar()) {
cmd.add("-cegar");
}
ProcessBuilder processBuilder = new ProcessBuilder(cmd);
try {
Process proc = processBuilder.start();
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
proc.waitFor();
} catch(InterruptedException e) {
System.out.println(e.getMessage());
System.exit(0);
}
while(read.ready()) {
output = read.readLine();
}
if(proc.exitValue() == 1) {
BufferedReader error = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while(error.ready()) {
System.out.println(error.readLine());
}
System.exit(0);
}
} catch(IOException e) {
System.out.println(e.getMessage());
System.exit(0);
}
bound++;
file = new SVCOMPSanitizer(options.getProgramFilePath()).run(bound);
}
output = output.contains("PASS") ? "PASS" : "FAIL";
System.out.println(output);
if(options.getGenerateWitness() && output.contains("FAIL")) {
try {
Program p = new ProgramParser().parse(new File("./output/" + name + "-" + options.getOptimization() + ".bpl"));
new SVCOMPWitness(p, options).write();;
} catch (IOException e) {
e.printStackTrace();
}
}
file.delete();
return;
}
}
<file_sep>/dartagnan/src/main/java/com/dat3m/dartagnan/program/event/Jump.java
package com.dat3m.dartagnan.program.event;
import com.dat3m.dartagnan.program.utils.EType;
import com.dat3m.dartagnan.wmm.utils.Arch;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
public class Jump extends Event {
protected Label label;
protected Label label4Copy;
public Jump(Label label){
if(label == null){
throw new IllegalArgumentException("Jump event requires non null label event");
}
this.label = label;
this.label.addListener(this);
addFilters(EType.ANY, EType.JUMP);
}
protected Jump(Jump other) {
super(other);
this.label = other.label4Copy;
Event notifier = label != null ? label : other.label;
notifier.addListener(this);
}
public Label getLabel(){
return label;
}
@Override
public String toString(){
return "goto " + label;
}
@Override
public void notify(Event label) {
if(this.label == null) {
this.label = (Label)label;
} else if (oId > label.getOId()) {
this.label4Copy = (Label)label;
}
}
// Unrolling
// -----------------------------------------------------------------------------------------------------------------
@Override
public void unroll(int bound, Event predecessor) {
if(label.getOId() < oId){
if(bound > 1) {
predecessor = copyPath(label, successor, predecessor);
}
Event next = predecessor;
if(bound == 1) {
next = new BoundEvent();
predecessor.setSuccessor(next);
}
if(successor != null) {
successor.unroll(bound, next);
}
return;
}
super.unroll(bound, predecessor);
}
@Override
public Jump getCopy(){
return new Jump(this);
}
// Compilation
// -----------------------------------------------------------------------------------------------------------------
@Override
public int compile(Arch target, int nextId, Event predecessor) {
cId = nextId++;
if(successor == null){
throw new RuntimeException("Malformed Jump event");
}
return successor.compile(target, nextId, this);
}
// Encoding
// -----------------------------------------------------------------------------------------------------------------
@Override
public BoolExpr encodeCF(Context ctx, BoolExpr cond) {
if(cfEnc == null){
cfCond = (cfCond == null) ? cond : ctx.mkOr(cfCond, cond);
label.addCfCond(ctx, cfVar);
cfEnc = ctx.mkAnd(ctx.mkEq(cfVar, cfCond), encodeExec(ctx));
cfEnc = ctx.mkAnd(cfEnc, successor.encodeCF(ctx, ctx.mkFalse()));
}
return cfEnc;
}
}
<file_sep>/include/assert.h
extern void __VERIFIER_assert(int exp);
extern void assert (int exp) {__VERIFIER_assert(exp);};
<file_sep>/dartagnan/src/test/java/com/dat3m/dartagnan/SvCompTestLoops.java
package com.dat3m.dartagnan;
import com.dat3m.dartagnan.parsers.cat.ParserCat;
import com.dat3m.dartagnan.utils.ResourceHelper;
import com.dat3m.dartagnan.wmm.Wmm;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.dat3m.dartagnan.utils.ResourceHelper.TEST_RESOURCE_PATH;
@RunWith(Parameterized.class)
public class SvCompTestLoops extends AbstractSvCompTest {
@Parameterized.Parameters(name = "{index}: {0} bound={2}")
public static Iterable<Object[]> data() throws IOException {
Wmm wmm = new ParserCat().parse(new File(ResourceHelper.CAT_RESOURCE_PATH + "cat/svcomp.cat"));
List<Object[]> data = new ArrayList<>();
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/array-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/array-2.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/bubble_sort-1.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/bubble_sort-2.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/cggmp2005.bpl", wmm, 5});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/count_up_down-2.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/gcnr2008.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/invert_string-1.bpl", wmm, 3});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/invert_string-3.bpl", wmm, 6});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/matrix-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/matrix-2.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/multivar_1-2.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/n.c40.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/nec11.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/nec40.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/phases_2-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/phases_2-2.bpl", wmm, 5});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/simple_2-2.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/simple_3-1.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/sum_array-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/sum01_bug02_sum01_bug02_base.case.bpl", wmm, 5});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/sum01_bug02.bpl", wmm, 7});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/sum01-1.bpl", wmm, 11});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/sum04-1.bpl", wmm, 9});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/sum04-2.bpl", wmm, 9});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/terminator_01.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/terminator_02-1.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/terminator_03-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/trex01-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/trex02-2.bpl", wmm, 1});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/trex03-1.bpl", wmm, 2});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/underapprox_1-1.bpl", wmm, 7});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/underapprox_1-2.bpl", wmm, 7});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/underapprox_2-1.bpl", wmm, 7});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/underapprox_2-2.bpl", wmm, 7});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/veris.c_NetBSD-libc_loop.bpl", wmm, 3});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/veris.c_sendmail_tTflag_arr_one_loop.bpl", wmm, 11});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/verisec_NetBSD-libc_loop.bpl", wmm, 9});
data.add(new Object[]{TEST_RESOURCE_PATH + "boogie/loops/vnew2.bpl", wmm, 7});
return data;
}
public SvCompTestLoops(String path, Wmm wmm, int bound) {
super(path, wmm, bound);
}
}<file_sep>/ui/src/main/java/com/dat3m/ui/result/ReachabilityResult.java
package com.dat3m.ui.result;
import static com.dat3m.dartagnan.utils.Result.FAIL;
import com.dat3m.dartagnan.Dartagnan;
import com.dat3m.dartagnan.program.Program;
import com.dat3m.dartagnan.utils.Graph;
import com.dat3m.dartagnan.utils.Result;
import com.dat3m.dartagnan.wmm.Wmm;
import com.dat3m.dartagnan.wmm.utils.Arch;
import com.dat3m.ui.utils.UiOptions;
import com.dat3m.ui.utils.Utils;
import com.microsoft.z3.Context;
import com.microsoft.z3.Solver;
public class ReachabilityResult implements Dat3mResult {
private final Program program;
private final Wmm wmm;
private final UiOptions options;
private Graph graph;
private String verdict;
public ReachabilityResult(Program program, Wmm wmm, UiOptions options){
this.program = program;
this.wmm = wmm;
this.options = options;
run();
}
public Graph getGraph(){
return graph;
}
public String getVerdict(){
return verdict;
}
private void run(){
if(validate()){
Context ctx = new Context();
Solver solver = ctx.mkSolver();
Result result = Dartagnan.testProgram(solver, ctx, program, wmm, options.getTarget(), options.getSettings());
buildVerdict(result);
if(options.getSettings().getDrawGraph() && Dartagnan.canDrawGraph(program.getAss(), result == FAIL)){
graph = new Graph(solver.getModel(), ctx, program, options.getSettings().getGraphRelations());
}
ctx.close();
}
}
private void buildVerdict(Result result){
StringBuilder sb = new StringBuilder();
sb.append("Condition ").append(program.getAss().toStringWithType()).append("\n");
sb.append(result).append("\n");
verdict = sb.toString();
}
private boolean validate(){
Arch target = program.getArch() == null ? options.getTarget() : program.getArch();
if(target == null) {
Utils.showError("Missing target architecture.");
return false;
}
program.setArch(target);
return true;
}
}
<file_sep>/dartagnan/src/main/java/com/dat3m/dartagnan/expression/ExprInterface.java
package com.dat3m.dartagnan.expression;
import com.google.common.collect.ImmutableSet;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
import com.microsoft.z3.IntExpr;
import com.microsoft.z3.Model;
import com.dat3m.dartagnan.program.Register;
import com.dat3m.dartagnan.program.event.Event;
public interface ExprInterface {
IConst reduce();
IntExpr toZ3Int(Event e, Context ctx);
BoolExpr toZ3Bool(Event e, Context ctx);
IntExpr getLastValueExpr(Context ctx);
int getIntValue(Event e, Context ctx, Model model);
boolean getBoolValue(Event e, Context ctx, Model model);
ImmutableSet<Register> getRegs();
}
<file_sep>/benchmarks/genmc/szymanski0.c
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include <stdatomic.h>
/* Full memory barrier */
#ifdef NIDHUGG
# define smp_mb() asm volatile ("mfence" ::: "memory")
#elif NIDHUGG_POWER
# define smp_mb() asm volatile ("sync" ::: "memory")
#else
# define smp_mb() atomic_thread_fence(memory_order_seq_cst)
#endif
atomic_int x;
atomic_int flag1;
atomic_int flag2;
void __VERIFIER_assume(int);
void *thread_1(void *unused)
{
atomic_store_explicit(&flag1, 1, memory_order_relaxed);
smp_mb();
__VERIFIER_assume(atomic_load_explicit(&flag2, memory_order_relaxed) < 3);
atomic_store_explicit(&flag1, 3, memory_order_relaxed);
smp_mb();
if (atomic_load_explicit(&flag2, memory_order_relaxed) == 1) {
atomic_store_explicit(&flag1, 2, memory_order_relaxed);
smp_mb();
__VERIFIER_assume(atomic_load_explicit(&flag2, memory_order_relaxed) == 4);
}
atomic_store_explicit(&flag1, 4, memory_order_relaxed);
smp_mb();
__VERIFIER_assume(atomic_load_explicit(&flag2, memory_order_relaxed) < 2);
/* Critical section start */
atomic_store_explicit(&x, 0, memory_order_relaxed);
atomic_load_explicit(&x, memory_order_relaxed);
assert(atomic_load_explicit(&x, memory_order_relaxed) <= 0);
smp_mb();
/* Critical section end */
__VERIFIER_assume(2 > atomic_load_explicit(&flag2, memory_order_relaxed) ||
atomic_load_explicit(&flag2, memory_order_relaxed) > 3);
atomic_store_explicit(&flag1, 0, memory_order_relaxed);
return NULL;
}
void *thread_2(void *unused)
{
atomic_store_explicit(&flag2, 1, memory_order_relaxed);
smp_mb();
__VERIFIER_assume(atomic_load_explicit(&flag1, memory_order_relaxed) < 3);
atomic_store_explicit(&flag2, 3, memory_order_relaxed);
smp_mb();
if (atomic_load_explicit(&flag1, memory_order_relaxed) == 1) {
atomic_store_explicit(&flag2, 2, memory_order_relaxed);
smp_mb();
__VERIFIER_assume(atomic_load_explicit(&flag1, memory_order_relaxed) == 4);
}
atomic_store_explicit(&flag2, 4, memory_order_relaxed);
smp_mb();
__VERIFIER_assume(atomic_load_explicit(&flag1, memory_order_relaxed) < 2);
/* Critical section start */
atomic_store_explicit(&x, 1, memory_order_relaxed);
atomic_load_explicit(&x, memory_order_relaxed);
assert(atomic_load_explicit(&x, memory_order_relaxed) >= 1);
smp_mb();
/* Critical section end */
__VERIFIER_assume(2 > atomic_load_explicit(&flag1, memory_order_relaxed) ||
atomic_load_explicit(&flag1, memory_order_relaxed) > 3);
atomic_store_explicit(&flag2, 0, memory_order_relaxed);
return NULL;
}
int main()
{
pthread_t t1, t2;
if (pthread_create(&t1, NULL, thread_1, NULL))
abort();
if (pthread_create(&t2, NULL, thread_2, NULL))
abort();
if (pthread_join(t1, NULL))
abort();
if (pthread_join(t2, NULL))
abort();
#ifdef NIDHUGG_PRINT_COMPLETE_EXECS
printf("Full execution encountered\n");
#endif
return 0;
}
<file_sep>/README.md
# Dat3M: Memory Model Aware Verification
<p align="center">
<img src="ui/src/main/resources/dat3m.png">
</p>
This tool suite is currently composed of two tools
* **Dartagnan:** a tool to check state reachability under weak memory models, and
* **Porthos:** a tool to check state inclusion under weak memory models.
Requirements
======
* [Maven](https://maven.apache.org/) (if you want to build the tools. If not see the [release](https://github.com/hernanponcedeleon/Dat3M/releases) section)
* [SMACK](https://github.com/smackers/smack) (only to verify C programs)
Installation
======
Set the path and shared libraries variables (replace the latter by DYLD_LIBRARY_PATH in **MacOS**)
```
export PATH=<Dat3M's root>/:$PATH
export LD_LIBRARY_PATH=<Dat3M's root>/lib/:$LD_LIBRARY_PATH
```
To build the tools run
```
mvn install:install-file -Dfile=lib/z3-4.3.2.jar -DgroupId=com.microsoft -DartifactId="z3" -Dversion=4.3.2 -Dpackaging=jar
mvn clean install -DskipTests
```
Unit Tests
======
We provide a set of unit tests that can be run by
```
mvn test
```
**Note:** there are almost 40K tests, running them takes more than 3 hs.
Usage
======
Dat3M comes with a user interface (UI) where it is easy to select the tool to use (Dartagnan or Porthos), import, export and modify both the program and the memory model and select the options for the verification engine (see below).
You can start the UI by running
```
java -jar ui/target/ui-2.0.6-jar-with-dependencies.jar
```
<p align="center">
<img src="ui/src/main/resources/ui.jpg">
</p>
Dartagnan supports programs written in the .litmus or .bpl (Boogie) formats. For Porthos, programs shall be written in the .pts format which is explained [here](porthos/pts.md).
If SMACK was correctly installed, C programs can be converted to Boogie using the following script:
```
smack -t -bpl <new Boogie file> <C file>
```
Additionally, you can run Dartagnan and Porthos from the console.
For checking reachability (Dartagnan):
```
java -jar dartagnan/target/dartagnan-2.0.6-jar-with-dependencies.jar -cat <CAT file> -i <program file> [options]
```
For checking state inclusion (Porthos):
```
java -jar porthos/target/porthos-2.0.6-jar-with-dependencies.jar -s <source> -scat <CAT file> -t <target> -tcat <CAT file> -i <program file> [options]
```
The -cat,-scat,-tcat options specify the paths to the CAT files.
For programs written in the .pts format, \<source> and \<target> specify the architectures to which the program will be compiled.
They must be one of the following:
- none
- tso
- power
- arm
- arm8
Other optional arguments include:
- -m, --mode {knastertarski, idl, kleene}: specifies the encoding for fixed points. Knaster-tarski (default mode) uses the encoding introduced in [2]. Mode idl uses the Integer Difference Logic iteration encoding introduced in [1]. Kleene mode uses the Kleene iteration encoding using one Boolean variable for each iteration step.
- -a, --alias {none, andersen, cfs}: specifies the alias-analysis used. Option andersen (the default one) uses a control-flow-insensitive method. Option cfs uses a control-flow-sensitive method. Option none performs no alias analysis.
- -unroll: unrolling bound for the BMC.
Dartagnan supports input non-determinism, assumptions and assertions using the [SVCOMP](https://sv-comp.sosy-lab.org/2020/index.php) commands "__VERIFIER_nondet_X", "__VERIFIER_assume" and "__VERIFIER_assert".
Authors and Contact
======
**Maintainer:**
* [<NAME>](mailto:<EMAIL>)
**Former Developers:**
* [<NAME>](mailto:<EMAIL>)
* [<NAME>](mailto:<EMAIL>)
Please feel free to contact us in case of questions or to send feedback.
References
======
[1] <NAME>, <NAME>, <NAME>, <NAME>: **Portability Analysis for Weak Memory Models. PORTHOS: One Tool for all Models**. SAS 2017.
[2] <NAME>, <NAME>, <NAME>, <NAME>: **BMC with Memory Models as Modules**. FMCAD 2018.
[3] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>: **BMC for Weak Memory Models: Relation Analysis for Compact SMT Encodings**. CAV 2019.
[4] <NAME>, <NAME>, <NAME>, <NAME>: **Dartagnan: Bounded Model Checking for Weak Memory Models (Competition Contribution)**. TACAS 2020.
<file_sep>/benchmarks/genmc/dekker_f0.c
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include <stdatomic.h>
atomic_int x;
atomic_int y;
atomic_int c;
void *thread_1(void *unused)
{
atomic_store_explicit(&y, 1, memory_order_relaxed);
atomic_thread_fence(memory_order_seq_cst);
if (!atomic_load_explicit(&x, memory_order_relaxed)) {
atomic_store_explicit(&c, 1, memory_order_relaxed);
assert(atomic_load_explicit(&c, memory_order_relaxed) == 1);
}
return NULL;
}
void *thread_2(void *unused)
{
atomic_store_explicit(&x, 1, memory_order_relaxed);
atomic_thread_fence(memory_order_seq_cst);
if (!atomic_load_explicit(&y, memory_order_relaxed)) {
atomic_store_explicit(&c, 0, memory_order_relaxed);
assert(atomic_load_explicit(&c, memory_order_relaxed) == 0);
}
return NULL;
}
int main()
{
pthread_t t1, t2;
if (pthread_create(&t1, NULL, thread_1, NULL))
abort();
if (pthread_create(&t2, NULL, thread_2, NULL))
abort();
return 0;
}
<file_sep>/benchmarks/genmc/peterson-sc0.c
#include <stdlib.h>
#include <pthread.h>
#include <assert.h>
#include <stdatomic.h>
atomic_bool flag1; /* Boolean flags */
atomic_bool flag2;
atomic_int turn; /* Atomic integer that holds the ID of the thread whose turn it is */
atomic_bool x; /* Boolean variable to test mutual exclusion */
void __VERIFIER_assume(int);
void *thread_1(void *arg)
{
atomic_store_explicit(&flag1, 1, memory_order_seq_cst);
atomic_store_explicit(&turn, 1, memory_order_seq_cst);
__VERIFIER_assume(atomic_load_explicit(&flag2, memory_order_seq_cst) != 1 ||
atomic_load_explicit(&turn, memory_order_seq_cst) != 1);
/* critical section beginning */
atomic_store_explicit(&x, 0, memory_order_seq_cst);
assert(atomic_load_explicit(&x, memory_order_seq_cst) <= 0);
atomic_load_explicit(&x, memory_order_seq_cst);
/* critical section ending */
atomic_store_explicit(&flag1, 0, memory_order_seq_cst);
return NULL;
}
void *thread_2(void *arg)
{
atomic_store_explicit(&flag2, 1, memory_order_seq_cst);
atomic_store_explicit(&turn, 0, memory_order_seq_cst);
__VERIFIER_assume(atomic_load_explicit(&flag1, memory_order_seq_cst) != 1 ||
atomic_load_explicit(&turn, memory_order_seq_cst) != 0);
/* critical section beginning */
atomic_store_explicit(&x, 1, memory_order_seq_cst);
assert(atomic_load_explicit(&x, memory_order_seq_cst) >= 1);
atomic_load_explicit(&x, memory_order_seq_cst);
/* critical section ending */
atomic_store_explicit(&flag2, 0, memory_order_seq_cst);
return NULL;
}
int main()
{
pthread_t t1, t2;
if (pthread_create(&t1, NULL, thread_1, NULL))
abort();
if (pthread_create(&t2, NULL, thread_2, NULL))
abort();
if (pthread_join(t1, NULL))
abort();
if (pthread_join(t2, NULL))
abort();
#ifdef NIDHUGG_PRINT_COMPLETE_EXECS
printf("Full execution encountered\n");
#endif
return 0;
}
<file_sep>/include/stdatomic.h
typedef enum memory_order {
memory_order_relaxed = __ATOMIC_RELAXED,
memory_order_consume = __ATOMIC_CONSUME,
memory_order_acquire = __ATOMIC_ACQUIRE,
memory_order_release = __ATOMIC_RELEASE,
memory_order_acq_rel = __ATOMIC_ACQ_REL,
memory_order_seq_cst = __ATOMIC_SEQ_CST
} memory_order;
typedef _Atomic(_Bool) atomic_bool;
typedef _Atomic(char) atomic_char;
typedef _Atomic(signed char) atomic_schar;
typedef _Atomic(unsigned char) atomic_uchar;
typedef _Atomic(short) atomic_short;
typedef _Atomic(unsigned short) atomic_ushort;
typedef _Atomic(int) atomic_int;
typedef _Atomic(unsigned int) atomic_uint;
typedef _Atomic(long) atomic_long;
typedef _Atomic(unsigned long) atomic_ulong;
typedef _Atomic(long long) atomic_llong;
typedef _Atomic(unsigned long long) atomic_ullong;
#define ATOMIC_VAR_INIT(VALUE) (VALUE)
#define NULL 0
<file_sep>/dartagnan/src/main/java/com/dat3m/dartagnan/program/event/CondJump.java
package com.dat3m.dartagnan.program.event;
import com.dat3m.dartagnan.expression.BExpr;
import com.dat3m.dartagnan.program.Register;
import com.dat3m.dartagnan.program.event.utils.RegReaderData;
import com.dat3m.dartagnan.program.utils.EType;
import com.dat3m.dartagnan.wmm.utils.Arch;
import com.google.common.collect.ImmutableSet;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
public class CondJump extends Jump implements RegReaderData {
private final BExpr expr;
private final ImmutableSet<Register> dataRegs;
public CondJump(BExpr expr, Label label){
super(label);
if(expr == null){
throw new IllegalArgumentException("CondJump event requires non null expression");
}
this.expr = expr;
dataRegs = expr.getRegs();
addFilters(EType.BRANCH, EType.COND_JUMP, EType.REG_READER);
}
protected CondJump(CondJump other) {
super(other);
this.expr = other.expr;
this.dataRegs = other.dataRegs;
}
@Override
public ImmutableSet<Register> getDataRegs(){
return dataRegs;
}
@Override
public String toString(){
return "if(" + expr + "); then goto " + label;
}
// Unrolling
// -----------------------------------------------------------------------------------------------------------------
@Override
public CondJump getCopy(){
return new CondJump(this);
}
// Compilation
// -----------------------------------------------------------------------------------------------------------------
@Override
public int compile(Arch target, int nextId, Event predecessor) {
cId = nextId++;
if(successor == null){
throw new RuntimeException("Malformed CondJump event");
}
return successor.compile(target, nextId, this);
}
// Encoding
// -----------------------------------------------------------------------------------------------------------------
@Override
public BoolExpr encodeCF(Context ctx, BoolExpr cond) {
if(cfEnc == null){
cfCond = (cfCond == null) ? cond : ctx.mkOr(cfCond, cond);
BoolExpr ifCond = expr.toZ3Bool(this, ctx);
label.addCfCond(ctx, ctx.mkAnd(ifCond, cfVar));
cfEnc = ctx.mkAnd(ctx.mkEq(cfVar, cfCond), encodeExec(ctx));
cfEnc = ctx.mkAnd(cfEnc, successor.encodeCF(ctx, ctx.mkAnd(ctx.mkNot(ifCond), cfVar)));
}
return cfEnc;
}
}
|
f3b0f63fae1edae9446c85bd95e5d67c51a27a43
|
[
"Markdown",
"Java",
"C"
] | 17
|
Java
|
IMCG/Dat3M
|
030845b2f46386a48b4597734215bc5ed9f433e4
|
10437ec4424e24a9dfda59241898ba9e2d464a47
|
refs/heads/main
|
<file_sep>import java.util.Scanner;
public class TugasPraktikum4Nomor1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[n];
int fpb = 0;
for (int i = 0; i < n; i++) {
array[i] = input.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int min = Math.min(array[i], array[j]);
for (int k = 1; k <= min; k++) {
if ((array[i] % k == 0) && (array[j] % k == 0)) {
fpb = k;
}
}
if (fpb == 1) {
System.out.println(array[i] + " " + array[j]);
}
// System.out.printf("FPB dari %d dan %d adalah %d\n", array[i], array[j], fpb);
}
}
}
}
<file_sep>import java.util.Scanner;
import java.util.Random;
public class TugasPraktikum5Nomor2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
String serialNumber = generateSerial(n, m);
System.out.println(serialNumber);
}
public static String generateSerial(int n, int m) {
Random rndm = new Random();
StringBuilder strBuild = new StringBuilder();
int[][] num = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
num[i][j] = rndm.nextInt(10);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m; j++) {
if (j < m) {
strBuild = strBuild.append(num[i][j]); // append --> menambahkan String yang ditentukan
} else if (j == m) {
strBuild = strBuild.append(i == n - 1 ? "" : "-");
}
}
}
String str = strBuild.toString(); // Mengembalikan objek String dari StringBuilder
return str;
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum3Nomor1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int x = input.nextInt();
int y = input.nextInt();
int a = 0, b = 0;
if (x < y){
a = x;
b = y;
}
else{
a = y;
b = x;
}
for (int i = a; i <= b; i++){
if (i < 0){
if (i % 2 == 0){
System.out.printf("%d genap negatif\n", i);
}
else{
System.out.printf("%d ganjil negatif\n", i);
}
}
else if (i == 0){
System.out.printf("%d nol\n", i);
}
else{
if (i % 2 == 0){
System.out.printf("%d genap positif\n", i);
}
else{
System.out.printf("%d ganjil positif\n", i);
}
}
}
}
catch (Exception e){
System.out.println("Inputan Tidak Valid!");
}
input.close();
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum3Nomor5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
while (input.hasNext()){
float M = input.nextFloat();
if (0 <= M && M <= 360){
float second = M * 240; // 1° = 4 menit = 240 detik
float minute;
float hour = 6; // 0° = 06:00:00
float remainder;
hour += (int) second / 3600;
remainder = (int)second % 3600;
minute = (int)remainder / 60;
remainder = (int)remainder % 60;
second = (int)remainder;
if ((hour >= 4 && hour <= 9) && (minute >= 0 && minute <= 59) && (second >= 0 && second <= 59)){ // Pagi = 04:00:00 - 09:59:59
System.out.println("Selamat Pagi");
}
else if ((hour >= 10 && hour <= 13) && (minute >= 0 && minute <= 59) && (second >= 0 && second <= 59)){ // Siang = 10:00:00 - 13:59:59
System.out.println("Selamat Siang");
}
else if ((hour >= 14 && hour <= 17) && (minute >= 0 && minute <= 59) && (second >= 0 && second <= 59)){ // Sore = 14:00:00 - 17:59:59
System.out.println("Selamat Sore");
}
else if ((hour >= 18 && hour < 24) && (minute >= 0 && minute <= 59) && (second >= 0 && second <= 59)){ // Malam = 18:00:00 - 03:59:59
System.out.println("Selamat Malam");
}
else{
if (hour == 24){ // 24:00:00 ---> 00:00:00
hour = 00;
System.out.println("Sel<NAME>");
}
else{ // >=25:00:00 ---> >=01:00:00
float remainingHour = hour - 24;
hour = 00;
for (int i = 1; i <= remainingHour; i++){
hour += 1;
}
if (hour < 4) {
System.out.println("Sel<NAME>");
}
else{
System.out.println("<NAME>");
}
}
}
System.out.printf("%02.0f:%02.0f:%02.0f\n", hour, minute, second);
}
else{
System.out.println("Inputan Tidak Valid!");
break;
}
}
}
catch (Exception e){
System.out.println("Inputan Tidak Valid!");
}
input.close();
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum1Nomor2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Cara 1
int second;
second = input.nextInt();
int minute;
int hour;
hour = second / (60 * 60);
second = second - ((60 * 60) * hour);
minute = second / 60;
second = second - (60 * minute);
System.out.printf("%02d:%02d:%02d%n", hour, minute, second);
// Cara 2
/*
int second;
second = input.nextInt();
int minute;
int hour;
int remainder;
hour = second / 3600;
remainder = second % 3600;
minute = remainder / 60;
remainder = remainder % 60;
second = remainder;
System.out.printf("%02d:%02d:%02d%n", hour, minute, second);
*/
}
}<file_sep>import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
public class TugasPraktikum8Nomor1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inputNamaFile = input.nextLine();
String namaFile = inputNamaFile + ".txt";
String inputCopiedFile = input.nextLine();
String copiedFile = inputCopiedFile + ".txt";
copy(namaFile, copiedFile);
input.close();
}
public static void copy(String sourceFile, String copiedFile) {
File file = new File(sourceFile);
if (!file.exists() || !file.isFile()) {
System.out.println();
System.out.println("\"Gagal\"");
return;
} else {
String copiedFileName = sourceFile.replace(sourceFile, copiedFile);
try (BufferedReader bufferedReader = new BufferedReader(new FileReader((sourceFile)))) {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter((copiedFileName)));
String line = new String();
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedWriter.close();
System.out.println();
System.out.println("\"Berhasil\"");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum2Nomor2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("** Menu **");
System.out.println("1. Mencari Luas Bangun Datar");
System.out.println("2. Mencari Volume Bangun Ruang");
System.out.println("\nInput angka sesuai dengan Menu tang diinginkan : ");
int menu = input.nextInt();
switch (menu){
case 1:
System.out.println("** Pilih Bangun Datar **");
System.out.println("1. Persegi");
System.out.println("2. Persegi Panjang");
System.out.println("3. Segitiga");
System.out.println("4. Lingkaran");
System.out.println("5. Jajar Genjang");
System.out.println("6. Trapesium");
System.out.println("7. Belah Ketupat");
System.out.println("8. Layang-Layang");
System.out.println("\nInput angka sesuai dengan nomor bangun datar yang diinginkan : ");
int pilihBangunDatar = input.nextInt();
switch (pilihBangunDatar){
case 1:
System.out.println("Input Sisi");
double s = input.nextDouble();
double luasPersegi = s * s;
System.out.printf("Luas Persegi = %.1f", luasPersegi);
break;
case 2:
System.out.println("Input Panjang");
double p = input.nextDouble();
System.out.println("Input Lebar");
double l = input.nextDouble();
double luasPersegiPanjang = p * l;
System.out.printf("Luas Persegi Panjang = %.1f", luasPersegiPanjang);
break;
case 3:
System.out.println("Input Alas");
double a = input.nextDouble();
System.out.println("Input Tinggi");
double t = input.nextDouble();
double luasSegitiga = (a * t) / 2;
System.out.printf("Luas Segitiga = %.1f", luasSegitiga);
break;
case 4:
System.out.println("Input Jari-jari");
double r = input.nextDouble();
double luasLingkaran = Math.PI * Math.pow(r, 2);
System.out.printf("Luas Lingkaran = %.1f", luasLingkaran);
break;
case 5:
System.out.println("Input Alas");
a = input.nextDouble();
System.out.println("Input Tinggi");
t = input.nextDouble();
double luasJajarGenjang = a * t;
System.out.printf("Luas Jajar Genjang = %.1f", luasJajarGenjang);
break;
case 6:
System.out.println("Input a");
a = input.nextDouble();
System.out.println("Input b");
double b = input.nextDouble();
System.out.println("Input Tinggi");
t = input.nextDouble();
double luasTrapesium = ((a + b) * t) / 2;
System.out.printf("Luas Trapesium = %.1f", luasTrapesium);
break;
case 7:
System.out.println("Input Diagonal 1");
double d1 = input.nextDouble();
System.out.println("Input Diagonal 2");
double d2 = input.nextDouble();
double luasBelahKetupat = (d1 * d2) / 2;
System.out.printf("Luas Belah Ketupat = %.1f", luasBelahKetupat);
break;
case 8:
System.out.println("Input Diagonal 1");
d1 = input.nextDouble();
System.out.println("Input Diagonal 2");
d2 = input.nextDouble();
double luasLayangLayang = (d1 * d2) / 2;
System.out.printf("Luas Belah Ketupat = %.1f", luasLayangLayang);
break;
default:
System.out.println("Masukkan pilihan dengan benar");
break;
}
break;
case 2 :
System.out.println("** Pilih Bangun Ruang **");
System.out.println("1. Kubus");
System.out.println("2. Balok");
System.out.println("3. Tabung");
System.out.println("4. Kerucut");
System.out.println("5. Bola");
System.out.println("6. Prisma");
System.out.println("7. Limas");
System.out.println("\nInput angka sesuai dengan nomor bangun ruang yang diinginkan : ");
int pilihBangunRuang = input.nextInt();
switch (pilihBangunRuang){
case 1:
System.out.println("Input Sisi");
double s = input.nextDouble();
double volumeKubus = Math.pow(s, 3);
System.out.printf("Volume Kubus = %.1f", volumeKubus);
break;
case 2:
System.out.println("Input Panjang");
double p = input.nextDouble();
System.out.println("Input Lebar");
double l = input.nextDouble();
System.out.println("Input Tinggi");
double t = input.nextDouble();
double volumeBalok = p * l * t;
System.out.printf("Volume Balok = %.1f", volumeBalok);
break;
case 3:
System.out.println("Input Tinggi");
t = input.nextDouble();
System.out.println("Input Jari-Jari");
double r = input.nextDouble();
double volumeTabung = Math.PI * Math.pow(r, 2) * t;
System.out.printf("Volume Tabung = %.1f", volumeTabung);
break;
case 4:
System.out.println("Input Tinggi");
t = input.nextDouble();
System.out.println("Input Jari-Jari");
r = input.nextDouble();
double volumeKerucut = (Math.PI * Math.pow(r, 2) * t) / 3;
System.out.printf("Volume Kerucut = %.1f", volumeKerucut);
break;
case 5:
System.out.println("Input Jari-Jari");
r = input.nextDouble();
double volumeBola = (Math.PI * Math.pow(r, 3) * 4) / 3;
System.out.printf("Volume Bola = %.1f", volumeBola);
break;
case 6:
System.out.println("Input Panjang Alas");
p = input.nextDouble();
System.out.println("Input Lebar Alas");
l = input.nextDouble();
System.out.println("Input Tinggi");
t = input.nextDouble();
double volumePrisma = (p * l) * t;
System.out.printf("Volume Prisma = %.1f", volumePrisma);
break;
case 7:
System.out.println("Input Panjang Alas");
p = input.nextDouble();
System.out.println("Input Lebar Alas");
l = input.nextDouble();
System.out.println("Input Tinggi");
t = input.nextDouble();
double volumeLimas = ((p * l) * t) / 3;
System.out.printf("Volume Prisma = %.1f", volumeLimas);
break;
default:
System.out.println("Masukkan pilihan dengan benar");
break;
}
break;
default:
System.out.println("Masukkan pilihan dengan benar");
break;
}
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum5Nomor3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int hari = input.nextInt();
myDay(hari);
}
static void myDay(int a) {
int tahun, bulan;
tahun = a / 365;
a -= (365 * tahun);
bulan = a / 30;
a -= (30 * bulan);
System.out.printf("%d tahun\n%d bulan\n%d hari", tahun, bulan, a);
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum5Nomor1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
int num2 = input.nextInt();
int fpb = cariFPB(num1, num2);
System.out.printf("FPB dari %d dan %d = %d", num1, num2, fpb);
}
static int cariFPB(int a, int b) {
int fpb = 0;
int min = Math.min(a, b);
for (int i = 1; i <= min; i++) {
if ((a % i == 0) && (b % i == 0)) {
fpb = i;
}
}
return fpb;
}
}
<file_sep>import java.util.Scanner;
public class TugasPraktikum4Nomor2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = input.nextInt();
int j = input.nextInt();
int k = input.nextInt();
int[][] matriksA = new int[i][j];
int[][] matriksB = new int[j][k];
int[][] hasil = new int[i][k];
System.out.println("Input Matriks A");
for (int x = 0; x < i; x++) {
for (int y = 0; y < j; y++) {
matriksA[x][y] = input.nextInt();
}
}
System.out.println("Input Matriks B");
for (int x = 0; x < j; x++) {
for (int y = 0; y < k; y++) {
matriksB[x][y] = input.nextInt();
}
}
for (int x = 0; x < hasil.length; x++) {
for (int y = 0; y <= matriksA.length; y++) { // matriksA.length == baris matriksA == 3
for (int z = 0; z < matriksA[0].length; z++) { // matriksA[0].length == kolom matriksA == 2
hasil[x][y] += (matriksA[x][z] * matriksB[z][y]);
}
}
}
System.out.println("Hasil Pekalian Matriks :");
for (int x = 0; x < i; x++) {
for (int y = 0; y < k; y++) {
System.out.printf("%d\t", hasil[x][y]);
}
System.out.println();
}
}
}
<file_sep>import java.util.InputMismatchException;
import java.util.Scanner;
public class TugasPraktikum2Nomor1{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int ganjil = 0;
int genap = 0;
int positif = 0;
int negatif = 0;
try{
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();
d = input.nextInt();
e = input.nextInt();
}
catch (InputMismatchException message_error){
System.out.println("Inputan Tidak Valid");
}
finally{
// a
if (a % 2 == 0){
genap++;
if (a > 0){
positif++;
}
else if (a < 0){
negatif++;
}
}
else{
ganjil++;
if (a > 0){
positif++;
}
else if (a < 0){
negatif++;
}
}
// b
if (b % 2 == 0){
genap++;
if (b > 0){
positif++;
}
else if (b < 0){
negatif++;
}
}
else{
ganjil++;
if (b > 0){
positif++;
}
else if (b < 0){
negatif++;
}
}
// c
if (c % 2 == 0){
genap++;
if (c > 0){
positif++;
}
else if (c < 0){
negatif++;
}
}
else{
ganjil++;
if (c > 0){
positif++;
}
else if (c < 0){
negatif++;
}
}
// d
if (d % 2 == 0){
genap++;
if (d > 0){
positif++;
}
else if (d < 0){
negatif++;
}
}
else{
ganjil++;
if (d > 0){
positif++;
}
else if (d < 0){
negatif++;
}
}
// e
if (e % 2 == 0){
genap++;
if (e > 0){
positif++;
}
else if (e < 0){
negatif++;
}
}
else{
ganjil++;
if (e > 0){
positif++;
}
else if (e < 0){
negatif++;
}
}
System.out.println(genap + " Angka Genap");
System.out.println(ganjil + " Angka Ganjil");
System.out.println(positif + " Angka Positif");
System.out.println(negatif + " Angka Negatif");
}
}
}
|
f09a5ebf3ee78010926cb4eec4c076aa57f1b68e
|
[
"Java"
] | 11
|
Java
|
Riofuad/LABPP2020
|
3e5c997c426ecbc0bd0ed2aab9559672406f02e6
|
41db733aa99fbc0c267c573899722f956b8f7491
|
refs/heads/master
|
<repo_name>mjc-gh/jquery.map.js<file_sep>/README.markdown
jQuery.map.js v2
=============
Overview
--------
This is a simple jQuery Google Maps API v3 wrapper. It provides map initialization as well as the methods to add a set of markers, center and zoom the map. You can also access the Google "map object" directly for more advanced usage.
[See Google's doc for more details](http://code.google.com/apis/maps/documentation/javascript/basics.html)
Please see the demo.html file for demos and code examples. If you would like to see a feature or find a bug submit an issue.
_This plugin is used on [MyLatLng.com](http://mylatlng.com)._
Position Notes
--------------
Any method that takes a positional option can either be a google.maps.LatLng object, an Array or an Object
// array
var position = [12.34, 56.78];
// object
var position = {lat:12.34, lng:56.78}
This means you don't have to create new google.maps.LatLng and can just pass objects or array to the various methods.
Documentation
-------------
This plugin had a complete rewrite in 2/12 and docs need to be written. Refer to the demo page for the time being.
<file_sep>/jquery.map.js
(function($){
var chart_api_url = location.protocol +"//chart.googleapis.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|";
var colors = $.gmapColors = {
blue: '6C97FF', green: '01C000', organge: 'FD8E08',
yellow: 'FEEC5A', purple: 'C296F1', brown: 'CA9B7D'
};
// latlng alias for future use
var LatLng;
function is_google_latlng(obj){
if (typeof obj.lat == 'function')
return true;
return false;
};
function get_map_data(elem){
var data = elem.data('gmap');
if (!data)
$.error('Map is not initialized');
return data;
}
function gmap_error(){
$.error('Map is not initialized.');
}
function create_latlng(arg,lng){
LatLng = LatLng || google.maps.LatLng;
return lng ? new LatLng(arg, lng) : arg.length ?
new LatLng(arg[0], arg[1]) : new LatLng(arg.lat, arg.lng);
}
function create_icon(color){
return new google.maps.MarkerImage(chart_api_url + (colors[color] || color));
}
function positions_to_lat_lng(obj){
var props = Array.prototype.slice.call(arguments, 1);
for (var i = 0, prop; prop = props[i]; i++){
if (obj[prop] && !is_google_latlng(obj[prop]))
obj[prop] = create_latlng(obj[prop]);
}
}
function remove_marker(markers, id){
if (markers[id]){
google.maps.event.clearInstanceListeners(markers[id]);
markers[id].setMap(null);
delete markers[id];
}
}
function create_marker(elem, map, id, opts){
if (opts.color){
opts.icon = create_icon(opts.color);
}
var options = { map:map, zIndex:1 };
jQuery.extend(options, opts);
positions_to_lat_lng(options, 'position');
var marker = new google.maps.Marker(options);
google.maps.event.addListener(marker, 'click', function(ev){
// trigger map marker click event
elem.trigger('gmap.click', [id, marker]);
if (opts.infoWindow){
var info_window = new google.maps.InfoWindow();
if (opts.infoWindow.content)
info_window.setContent(opts.infoWindow.content);
// so if we don't have content yet, google doesnt show the window
// the window will be shown once content is set though (don't need to call open again)
info_window.open(map, marker);
// trigger info window open event passing the info window and opts
// this makes it possible to modify the original options and add in content
elem.trigger('gmap.open', [id, info_window, opts]);
}
});
return marker;
}
var methods = {
get:function(){
var data = $(this).data('gmap');
return data ? data.map : null;
},
init:function(opts){
return this.each(function(){
var elem = $(this)
var data = elem.data('gmap');
if (!data) {
var options = jQuery.extend({
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false, zoom: 14
}, opts);
// convert center to google lat lng if needed
positions_to_lat_lng(options, 'center');
// if no center was provided
if (!options.center)
options.center = create_latlng(38.89, -77.02);
// create map, bind events
var map = new google.maps.Map(this, options);
google.maps.event.addListener(map, 'idle', function(){
elem.trigger('gmap.idle', [map]);
});
// store data
elem.data('gmap', {map:map, options:options, markers:{}});
}
});
},
add:function(id, options){
return this.each(function(){
var elem = $(this);
var data = get_map_data(elem);
data.markers[id] = create_marker(elem, data.map, id, options);
});
},
remove:function(ids){
if (!ids || !ids.length) return;
return this.each(function(){
var elem = $(this);
var data = get_map_data(elem);
if (typeof ids == 'string')
ids = [ids];
for (var i = 0, id; id = ids[i]; i++)
remove_marker(data.markers, id);
});
},
center:function(geo) {
if (!geo) return;
return this.each(function(){
var elem = $(this);
var data = get_map_data(elem);
var center = is_google_latlng(geo) ? geo : create_latlng(geo);
data.map.setCenter(center);
data.options.center = center;
});
},
zoom:function(level){
if (!level) return;
return this.each(function(){
var elem = $(this);
var data = get_map_data(elem);
data.map.setZoom(level);
data.options.zoom = level;
});
},
search:function(str){
var elem = $(this);
var data = get_map_data(elem);
var geocoder = new google.maps.Geocoder;
var promise = $.Deferred();
geocoder.geocode({ address: str }, function(results, status){
var args = [results, status];
if (status.match(/ok|zero/i))
promise.resolveWith(promise, args);
else
promise.rejectWith(promise, args);
});
return promise;
},
markers:function(){
var elem = $(this);
var data = get_map_data(elem);
return data.markers;
}
};
$.gmapIcon = function(color){
return create_icon(color);
}
$.fn.gmap = function(method){
// Method calling logic
if (!google || !google.maps) {
$.error('No Google Maps Loaded; Cannot Initialize');
} else if (!method) {
return methods.get.apply(this);
} else if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method == 'object') {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.gmap');
}
}
})(jQuery);
|
d7c9e8f3c06e86abdf55546435790418a47ab10c
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
mjc-gh/jquery.map.js
|
1a06fa57edca3a8be940105580561475b735b31e
|
ead90df4ce811b91f2b30b25b8704c5658a31b1c
|
refs/heads/master
|
<repo_name>WVKIA/Java-MultiThread<file_sep>/src/PhilosopherEating/FixedDiningPhilosophers.java
package PhilosopherEating;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedDiningPhilosophers {
public static void main(String[] args) throws IOException {
int ponder = 0; //size == 0 lock will be happen in time
int size = 3;
ExecutorService executorService = Executors.newCachedThreadPool();
Chopstick[] sticks = new Chopstick[size];
for (int i = 0; i < size; i++) {
sticks[i] = new Chopstick();
}
for (int i = 0; i < size; i++) {
if(i < size -1){
//前几个都是同一边
executorService.execute(new Philosopher(sticks[i],sticks[(i+1)],i,ponder));
}else {
//最后一个先拿反方向
executorService.execute(new Philosopher(sticks[0],sticks[i],i,ponder));
}
}
System.out.println("Press enter to quit");
System.in.read();
executorService.shutdownNow();
}
}
<file_sep>/src/Sychronized/NotifyVsNotifyAll.java
package Sychronized;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by wk on 2017/8/17.
*/
class Blocker {
//同步代码块 等待呼叫
synchronized void waitingCall() {
try {
while (!Thread.interrupted()) {
//等待,释放锁,进入锁等待队列,直到notify或notifyAll唤醒
wait();
System.out.println(Thread.currentThread() + " ");
}
} catch (InterruptedException e) {
// OK to exit this way
}
}
//唤醒
synchronized void prod() {
notify();
}
//唤醒所有
synchronized void prodAll() {
notifyAll();
}
}
/**
* 任务类
*/
class Task implements Runnable {
static Blocker blocker = new Blocker();
//执行等待wait
@Override
public void run() {
blocker.waitingCall();
}
}
class Task2 implements Runnable {
static Blocker blocker = new Blocker();
/**
* 执行等待wait
*/
@Override
public void run() {
blocker.waitingCall();
}
}
public class NotifyVsNotifyAll {
public static void main(String[] args) throws InterruptedException {
//执行器
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
executorService.execute(new Task());
}
executorService.execute(new Task2());
//定时器
Timer timer = new Timer();
//定时器方法
timer.scheduleAtFixedRate(new TimerTask() {
boolean prod = true;
@Override
//交替执行notify和notifyAll
public void run() {
//如果true,唤醒notify
if (prod) {
System.out.println("\nNotify()");
Task.blocker.prod();
prod = false;
//否则,唤醒notifyAll
} else {
System.out.println("\nnotifyAll()");
Task.blocker.prodAll();
prod = true;
}
}
//每0.4秒执行一次
}, 400, 400); //run every 4 second
TimeUnit.SECONDS.sleep(5);
timer.cancel();//取消定时
System.out.println("\nTime canceled");
TimeUnit.MICROSECONDS.sleep(500);
System.out.println("Task2.blocker.proAll()");
//任务2唤醒all
Task2.blocker.prodAll();
TimeUnit.MILLISECONDS.sleep(500
);
System.out.println("\nShutting down");
//停止所有线程
executorService.shutdownNow(); // Interrupt all tasks
}
}
<file_sep>/src/ConcurrentPackage/HorseRace.java
package ConcurrentPackage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
/**
* 马 类
*/
class Horse implements Runnable{
private static int counter = 0;
private final int id =counter++;
private int strides = 0;
private static Random random = new Random(47);
//栅栏
private static CyclicBarrier barrier;
public Horse(CyclicBarrier barrier) {
this.barrier = barrier;
}
//同步方法获取当前总共步数
public synchronized int getStrides() {
return strides;
}
@Override
public void run() {
try {
while (!Thread.interrupted()){
synchronized (this){
strides += random.nextInt(3);
}
//阻塞直到所有任务都到达栅栏CycliBarrier
barrier.await();
}
}catch (InterruptedException e){
// A legitimate way to exit
}catch (BrokenBarrierException e){
//This one we want to know about
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return "Horse "+id +" ";
}
/**
* 使用*号模拟当前马匹的总路程
* @return
*/
public String tracks(){
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < getStrides(); i++) {
stringBuilder.append("*");
}
stringBuilder.append(id);
stringBuilder.append("("+getStrides()+")");
return stringBuilder.toString();
}
}
public class HorseRace {
//结束步数
static final int FINISH_LINE = 75;
private List<Horse> horses = new ArrayList<>();
private ExecutorService executorService = Executors.newCachedThreadPool();
private CyclicBarrier barrier;
public HorseRace(int nHorse,final int pause) {
//栅栏动作作为匿名内部类创建
barrier = new CyclicBarrier(nHorse, new Runnable() {
@Override
public void run() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < FINISH_LINE; i++) {
stringBuilder.append("=");
}
System.out.println(stringBuilder);
for (Horse h :
horses) {
System.out.println(h.tracks());
}
//打印每匹马当前步数
for (Horse hourse :
horses) {
//如果有一匹等于或超过限制步数,获胜!结束所有任务
if (hourse.getStrides() >= FINISH_LINE){
System.out.println(hourse+" won!");
executorService.shutdownNow();
return;
}
}
try {
TimeUnit.MILLISECONDS.sleep(pause);
}catch (InterruptedException e){
System.out.println("barrier-action sleep interrupted");
}
}
});
for (int i = 0; i < nHorse; i++) {
Horse horse = new Horse(barrier);
horses.add(horse);
executorService.execute(horse);
}
}
public static void main(String[] args) {
int nhouts = 7;
int pause = 200;
new HorseRace(nhouts,pause);
}
}
<file_sep>/src/PhilosopherEating/Philosopher.java
package PhilosopherEating;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* 哲学家
*/
public class Philosopher implements Runnable{
//左筷子
private Chopstick left;
//右筷子
private Chopstick right;
private final int id;
//思考因子
private final int ponderFacter;
private Random random = new Random(47);
//暂停用作思考的时间
private void pause() throws InterruptedException {
if (ponderFacter == 0) return;
TimeUnit.MILLISECONDS.sleep(random.nextInt(ponderFacter * 250));
}
public Philosopher(Chopstick left, Chopstick right, int id, int ponderFacter) {
this.left = left;
this.right = right;
this.id = id;
this.ponderFacter = ponderFacter;
}
@Override
public void run() {
try {
while (!Thread.interrupted()){
System.out.println(this+" "+"Thinking");
//思考
pause();
//philosopher becomes hungry
System.out.println(this+" "+" rabbing right");
//拿右筷子
right.take();
System.out.println(this+" "+"rabbing left");
//拿左筷子
left.take();
System.out.println(this+" "+"eating");
//吃饭
pause();
//丢掉右筷子
right.drop();
//丢掉左筷子
left.drop();
}
}catch (InterruptedException e){
System.out.println(this+" "+"eating via interrupted");
}
}
@Override
public String toString() {
return "Philosopher "+ id;
}
}
<file_sep>/src/Sychronized/ThreadTestA.java
package MultiThread;
public class ThreadTestA {
public static void main(String[] args) {
Object o = new Object();
final printEvenOdd pe = new printEvenOdd();
Thread a= new Thread(){
@Override
public void run() {
pe.Even();
}
};
Thread b = new Thread() {
@Override
public void run() {
pe.Odd();
}
};
a.start();
b.start();
}
}
// 交替输出奇偶数
class printEvenOdd {
private Object LOCK = new Object();
private int num = 0;
// 同理,这个synchronized括号里面的可以是this、TA.class等等
public void Even() {
while (num < 50) {
synchronized (LOCK) {
if (num % 2 == 0) {
System.out.println(Thread.currentThread().getName() + " run " + num++);
LOCK.notify();
} else {
try {
System.out.println(Thread.currentThread().getName() + " wait ");
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void Odd() {
while (num < 50) {
synchronized (LOCK) {
if (num % 2 != 0) {
System.out.println(Thread.currentThread().getName() + " run " + num++);
LOCK.notify();
} else {
try {
System.out.println(Thread.currentThread().getName() + " wait ");
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
<file_sep>/src/PhilosopherEating/Chopstick.java
package PhilosopherEating;
/**
* 筷子
*/
public class Chopstick {
//是否被拿着
private boolean tasken = false;
//同步方法 拿筷子
public synchronized void take() throws InterruptedException {
//如果this始终被拿着,则等待
while (tasken){
wait();
}
//设置true,被拿
tasken =true;
}
//同步方法 丢掉筷子
public synchronized void drop(){
tasken = false;
//唤醒其他线程
notifyAll();
}
}
|
ff2d2d2838548fffffe9f26016779bf274d9e362
|
[
"Java"
] | 6
|
Java
|
WVKIA/Java-MultiThread
|
167b0e83a2b5cfa31038939608c776117e890a0b
|
3a2e1433db035ab26118229a17e112d172f60d8e
|
refs/heads/master
|
<repo_name>cpe202fall2018/lab0-cpcampbe<file_sep>/planets.py
def weight_on_planets():
weight = input("What do you weigh on earth? ")
intWeight = int(weight)
print ("\nOn Mars you would weigh", intWeight * .38,
"pounds.\nOn Jupiter you would weigh", intWeight * 2.34, "pounds.")
if __name__ == '__main__':
weight_on_planets()
|
a368d7686cf8114ad66232c567592a75454ae4b8
|
[
"Python"
] | 1
|
Python
|
cpe202fall2018/lab0-cpcampbe
|
f4c37609633821bf0e172d95318e084720a0d49e
|
a67c81741a3d5634a29cd34d59f1b8f266732f8a
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace CurrencyConverterAPI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
int i = int.Parse(txtAmount.Text);
if (fromComboBox.SelectedItem == "Rupee" && toComboBox.SelectedItem == "Dollar")
{
int conv = i / 103;
txtDisplay.Text = conv + "\t $";
}
if (fromComboBox.SelectedItem == "Dollar" && toComboBox.SelectedItem == "Rupee")
{
int conv = i * 103;
txtDisplay.Text = conv + "\t Rupee";
}
if (fromComboBox.SelectedItem == "Euro" && toComboBox.SelectedItem == "Dollar")
{
int conv = i * 2;
txtDisplay.Text = conv + "\t $";
}
if (fromComboBox.SelectedItem == "Dollar" && toComboBox.SelectedItem == "Euro")
{
int conv = i / 2;
txtDisplay.Text = conv + "\t Euro";
}
if (fromComboBox.SelectedItem == "Rupee" && toComboBox.SelectedItem == "Euro")
{
int conv = i / 115;
txtDisplay.Text = conv + "\t Euro";
}
if (fromComboBox.SelectedItem == "Euro" && toComboBox.SelectedItem == "Rupee")
{
int conv = i * 115;
txtDisplay.Text = conv + "\t Rupee";
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label6_Click(object sender, EventArgs e)
{
}
private void txtAmount_TextChanged(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
}
}
|
67cc1cac9917706ef118e6081d31cefc6c398ad7
|
[
"C#"
] | 1
|
C#
|
kanarekha/Currency-Converter-Static
|
e8901abb81a68e6b472b7a8c857d0eb6245b4188
|
373422c6129369ca0e80433bd62eb51c5ed07143
|
refs/heads/master
|
<file_sep>namespace JMMServer.API.Model
{
public class Search
{
public string query { get; set; }
}
}
<file_sep>using JMMServer.PlexAndKodi;
using JMMServer.PlexAndKodi.Kodi;
using Nancy;
using Nancy.Security;
using JMMServer.API.Model;
namespace JMMServer.API
{
public class APIv2_common_Module : Nancy.NancyModule
{
public APIv2_common_Module() : base("/api")
{
this.RequiresAuthentication();
Get["/filters/get"] = _ => { return GetFilters(); };
Get["/metadata/{type}/{id}"] = x => { return GetMetadata(x.type, x.id); };
Get["/metadata/{type}/{id}/nocast"] = x => { return GetMetadata(x.type, x.id, true); };
//Get["/Search/{uid}/{limit}/{query}"] = parameter => { return Search_Kodi(parameter.uid, parameter.limit, parameter.query); };
//Get["/Search/{uid}/{limit}/{query}/{searchTag}"] = parameter => { return SearchTag(parameter.uid, parameter.limit, parameter.query); };
//Get["/ToggleWatchedStatusOnEpisode/{uid}/{epid}/{status}"] = parameter => { return ToggleWatchedStatusOnEpisode_Kodi(parameter.uid, parameter.epid, parameter.status); };
//Get["/VoteAnime/{uid}/{id}/{votevalue}/{votetype}"] = parameter => { return VoteAnime_Kodi(parameter.uid, parameter.id, parameter.votevalue, parameter.votetype); };
//Get["/TraktScrobble/{animeid}/{type}/{progress}/{status}"] = parameter => { return TraktScrobble(parameter.animeid, parameter.type, parameter.progress, parameter.status); };
}
IProvider _prov_kodi = new KodiProvider();
CommonImplementation _impl = new CommonImplementation();
private object GetFilters()
{
API.APIv1_Legacy_Module.request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
if (user != null)
{
return _impl.GetFilters(_prov_kodi, user.JMMUserID.ToString());
}
else
{
return new APIMessage(500, "Unable to get User");
}
}
private object GetMetadata(string typeid, string id, bool nocast=false)
{
API.APIv1_Legacy_Module.request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
if (user != null)
{
return _impl.GetMetadata(_prov_kodi, user.JMMUserID.ToString(), typeid, id, null, nocast);
}
else
{
return new APIMessage(500, "Unable to get User");
}
}
}
}
<file_sep>using Nancy;
using Nancy.Security;
using System;
using JMMServer.API.Model;
using Nancy.ModelBinding;
using JMMServer.Entities;
using JMMContracts;
using System.Collections.Generic;
using System.Threading;
using System.Globalization;
using JMMServer.Commands;
using JMMServer.PlexAndKodi;
using JMMServer.Repositories;
using System.Linq;
using Newtonsoft.Json;
using System.IO;
using JMMServer.Repositories.Direct;
using JMMServer.Utilities;
using JMMServer.Tasks;
using Nancy.Responses;
namespace JMMServer.API
{
//As responds for this API we throw object that will be converted to json/xml or standard http codes (HttpStatusCode)
public class APIv2_core_Module : Nancy.NancyModule
{
public static int version = 1;
//class will be found automagicly thanks to inherits also class need to be public (or it will 404)
//routes are named with twitter api style
//every function with summary is implemented
//private funtions are the ones for api calls directly and internal ones are support function for private ones
public APIv2_core_Module() : base("/api")
{
// As this module requireAuthentication all request need to have apikey in header.
this.RequiresAuthentication();
// 1. import folders
Get["/folder/list"] = x => { return GetFolders(); };
Get["/folder/count"] = x => { return CountFolders(); };
Post["/folder/add"] = x => { return AddFolder(); };
Post["/folder/edit"] = x => { return EditFolder(); };
Post["/folder/delete"] = x => { return DeleteFolder(); };
Get["/folder/import"] = _ => { return RunImport(); };
// 2. upnp
Post["/upnp/list"] = x => { return ListUPNP(); };
Post["/upnp/add"] = x => { return AddUPNP(); };
Post["/upnp/delete"] = x => { return DeleteUPNP(); };
// 3. Settings
Post["/config/port/set"] = _ => { return SetPort(); };
Get["/config/port/get"] = _ => { return GetPort(); };
Post["/config/imagepath/set"] = _ => { return SetImagepath(); };
Get["/config/imagepath/get"] = _ => { return GetImagepath(); };
Get["/config/export"] = _ => { return ExportConfig(); };
Post["/config/import"] = _ => { return ImportConfig(); };
// 4. AniDB
Post["/anidb/set"] = _ => { return SetAniDB(); };
Get["/anidb/get"] = _ => { return GetAniDB(); };
Get["/anidb/test"] = _ => { return TestAniDB(); };
Get["/anidb/votes/sync"] = _ => { return SyncAniDBVotes(); };
Get["/anidb/list/sync"] = _ => { return SyncAniDBList(); };
Get["/anidb/update"] = _ => { return UpdateAllAniDB(); };
// 5. MyAnimeList
Post["/mal/set"] = _ => { return SetMAL(); };
Get["/mal/get"] = _ => { return GetMAL(); };
Get["/mal/test"] = _ => { return TestMAL(); };
//Get["/mal/votes/sync"] = _ => { return SyncMALVotes(); }; <-- not implemented as CommandRequest
// 6. Trakt
Post["/trakt/set"] = _ => { return SetTraktPIN(); };
Get["/trakt/get"] = _ => { return GetTrakt(); };
Get["/trakt/create"] = _ => { return CreateTrakt(); };
Get["/trakt/sync"] = _ => { return SyncTrakt(); };
Get["/trakt/update"] = _ => { return UpdateAllTrakt(); };
// 7. TvDB
Get["/tvdb/update"] = _ => { return UpdateAllTvDB(); };
// 8. Actions
Get["/remove_missing_files"] = _ => { return RemoveMissingFiles(); };
Get["/stats_update"] = _ => { return UpdateStats(); };
Get["/mediainfo_update"] = _ => { return UpdateMediaInfo(); };
Get["/hash/sync"] = _ => { return HashSync(); };
// 9. Misc
Get["/myid/get"] = _ => { return MyID(); };
Get["/news/get"] = _ => { return GetNews(5); };
// 10. User
Get["/user/list"] = _ => { return GetUsers(); };
Post["/user/create"] = _ => { return CreateUser(); };
Post["/user/delete"] = _ => { return DeleteUser(); };
Post["/user/password"] = _ => { return ChangePassword(); };
Post["/user/password/{uid}"] = x => { return ChangePassword(x.uid); };
// 11. Queue
Get["/queue/get"] = _ => { return GetQueue(); };
Get["/queue/pause"] = _ => { return PauseQueue(); };
Get["/queue/start"] = _ => { return StartQueue(); };
Get["/queue/hash/get"] = _ => { return GetHasherQueue(); };
Get["/queue/hash/pause"] = _ => { return PauseHasherQueue(); };
Get["/queue/hash/start"] = _ => { return StartHasherQueue(); };
Get["/queue/hash/clear"] = _ => { return ClearHasherQueue(); };
Get["/queue/general/get"] = _ => { return GetGeneralQueue(); };
Get["/queue/general/pause"] = _ => { return PauseGeneralQueue(); };
Get["/queue/general/start"] = _ => { return StartGeneralQueue(); };
Get["/queue/general/clear"] = _ => { return ClearGeneralQueue(); };
Get["/queue/images/get"] = _ => { return GetImagesQueue(); };
Get["/queue/images/pause"] = _ => { return PauseImagesQueue(); };
Get["/queue/images/start"] = _ => { return StartImagesQueue(); };
Get["/queue/images/clear"] = _ => { return ClearImagesQueue(); };
// 12. Files
Get["/file/list"] = _ => { return GetAllFiles(); };
Get["/file/count"] = _ => { return CountFiles(); };
Get["/file/{id}"] = x => { return GetFileById(x.id); };
Get["/file/recent"] = x => { return GetRecentFiles(10); };
Get["/file/recent/{max}"] = x => { return GetRecentFiles((int)x.max); };
Get["/file/unrecognised"] = x => { return GetUnrecognisedFiles(10); };
Get["/file/unrecognised/{max}"] = x => { return GetUnrecognisedFiles((int)x.max); };
// 13. Episodes
Get["/ep/list"] = _ => { return GetAllEpisodes(); ; };
Get["/ep/{id}"] = x => { return GetEpisodeById(x.id); };
//Get["/ep/{id}/image"] = x => { return GetEpisodeImage(x.id); };
Get["/ep/recent"] = x => { return GetRecentEpisodes(10); };
Get["/ep/recent/{max}"] = x => { return GetRecentEpisodes((int)x.max); };
Post["/ep/watch"] = x => { return MarkEpisodeWatched(true); };
Post["/ep/unwatch"] = x => { return MarkEpisodeWatched(false); };
Post["/ep/vote"] = x => { return VoteOnEpisode(); };
Post["/ep/trakt"] = x => { return EpisodeScrobble(); };
// 14. Series
Get["/serie/list"] = _ => { return GetAllSeries(); ; };
Get["/serie/count"] = _ => { return CountSerie(); ; };
Get["/serie/{id}"] = x => { return GetSerieById(x.id); ; };
Get["/serie/recent"] = _ => { return GetRecentSeries(10); };
Get["/serie/recent/{max}"] = x => { return GetRecentSeries((int)x.max); };
Post["/serie/search"] = x => { return SearchForSerie(); };
Post["/serie/search/{limit}"] = x => { return SearchForSerie((int)x.limit); };
Get["/serie/byfolder/{id}"] = x => { return GetSerieByFolderId(x.id, 10); };
Get["/serie/byfolder/{id}/{max}"] = x => { return GetSerieByFolderId(x.id, x.max); };
Post["/serie/watch/{type}/{max}"] = x => { return MarkSerieWatched(true, x.max, x.type); };
Post["/serie/unwatch/{type}/{max}"] = x => { return MarkSerieWatched(false, x.max, x.type); };
Post["/serie/vote"] = x => { return VoteOnSerie(); };
Get["/serie/{id}/art"] = x => { return GetSerieArt((int)x.id); };
// 15. WebUI
Get["/dashboard"] = _ => { return GetDashboard(); };
Get["/webui/update/stable"] = _ => { return WebUIStableUpdate(); };
Get["/webui/latest/stable"] = _ => { return WebUILatestStableVersion(); };
Get["/webui/update/unstable"] = _ => { return WebUIUnstableUpdate(); };
Get["/webui/latest/unstable"] = _ => { return WebUILatestUnstableVersion(); };
Get["/webui/config"] = _ => { return GetWebUIConfig(); };
Post["/webui/config"] = _ => { return SetWebUIConfig(); };
// 16. OS-based operations
Get["/os/folder/base"] = _ => { return GetOSBaseFolder(); };
Post["/os/folder"] = x => { return GetOSFolder(x.folder); };
Get["/os/drives"] = _ => { return GetOSDrives(); };
// 17. Cloud accounts
Get["/cloud/list"] = _ => { return GetCloudAccounts(); };
Get["/cloud/count"] = _ => { return GetCloudAccountsCount(); };
Post["/cloud/add"] = x => { return AddCloudAccount(); };
Post["/cloud/delete"] = x => { return DeleteCloudAccount(); };
Get["/cloud/import"] = _ => { return RunCloudImport(); };
// 18. Images
Get["/cover/{id}"] = x => { return GetCover(x.id); };
Get["/fanart/{id}"] = x => { return GetFanart(x.id); };
Get["/poster/{id}"] = x => { return GetPoster(x.id); };
Get["/banner/{id}"] = x => { return GetImage((int)x.id, 4, false); };
Get["/fanart/{id}"] = x => { return GetImage((int)x.id, 7, false); };
Get["/image/{type}/{id}"] = x => { return GetImage((int)x.id, (int)x.type, false); };
// 19. Logs
Get["/log/get"] = x => { return GetLog(10, 0); };
Get["/log/get/{max}/{position}"] = x => { return GetLog((int)x.max, (int)x.position); };
Post["/log/rotate"] = x => { return SetRotateLogs(); };
Get["/log/rotate"] = x => { return GetRotateLogs(); };
Get["/log/rotate/start"] = x => { return StartRotateLogs(); };
// 20. Dev
#if DEBUG
Get["/dev/contracts/{entity?}"] = x => { return ExtractContracts((string)x.entity); };
#endif
}
JMMServiceImplementationREST _rest = new JMMServiceImplementationREST();
#region 1.Import Folders
/// <summary>
/// List all saved Import Folders
/// </summary>
/// <returns></returns>
private object GetFolders()
{
List<Contract_ImportFolder> list = new JMMServiceImplementation().GetImportFolders();
return list;
}
/// <summary>
/// return number of Import Folders
/// </summary>
/// <returns></returns>
private object CountFolders()
{
Counter count = new Counter();
count.count = new JMMServiceImplementation().GetImportFolders().Count;
return count;
}
/// <summary>
/// Add Folder to Import Folders Repository
/// </summary>
/// <returns></returns>
private object AddFolder()
{
try
{
Contract_ImportFolder folder = this.Bind();
if (folder.ImportFolderLocation != "")
{
try
{
Contract_ImportFolder_SaveResponse response = new JMMServiceImplementation().SaveImportFolder(folder);
if (string.IsNullOrEmpty(response.ErrorMessage))
{
return APIStatus.statusOK();
}
else
{
return new APIMessage(500, response.ErrorMessage);
}
}
catch
{
return APIStatus.internalError();
}
}
else
{
return new APIMessage(400, "Bad Request: The Folder path must not be Empty");
}
}
catch (ModelBindingException)
{
return new APIMessage(400, "Bad binding");
}
}
/// <summary>
/// Edit folder giving fulll ImportFolder object with ID
/// </summary>
/// <returns></returns>
private object EditFolder()
{
ImportFolder folder = this.Bind();
if (!String.IsNullOrEmpty(folder.ImportFolderLocation) && folder.ImportFolderID != 0)
{
try
{
if (folder.IsDropDestination == 1 && folder.IsDropSource == 1)
{
return new APIMessage(409, "The Folder Can't be both Destination and Source Simultaneously");
}
else
{
if (folder.ImportFolderID != 0 & folder.ToContract().ImportFolderID.HasValue)
{
Contract_ImportFolder_SaveResponse response = new JMMServiceImplementation().SaveImportFolder(folder.ToContract());
if (!string.IsNullOrEmpty(response.ErrorMessage))
{
return new APIMessage(500, response.ErrorMessage);
}
else
{
return APIStatus.statusOK();
}
}
else
{
return new APIMessage(409, "The Import Folder must have an ID");
}
}
}
catch
{
return APIStatus.internalError();
}
}
else
{
return new APIMessage(400, "ImportFolderLocation and ImportFolderID missing");
}
}
/// <summary>
/// Delete Import Folder out of Import Folder Repository
/// </summary>
/// <returns></returns>
private object DeleteFolder()
{
ImportFolder folder = this.Bind();
if (folder.ImportFolderID != 0)
{
string res = Importer.DeleteImportFolder(folder.ImportFolderID);
if (res == "")
{
return APIStatus.statusOK();
}
else
{
return new APIMessage(500, res);
}
}
else
{
return new APIMessage(400, "ImportFolderID missing");
}
}
/// <summary>
/// Run Import action on all Import Folders inside Import Folders Repository
/// </summary>
/// <returns></returns>
private object RunImport()
{
MainWindow.RunImport();
return APIStatus.statusOK();
}
#endregion
#region 2.UPNP
private object ListUPNP()
{
UPNPLib.UPnPDeviceFinder discovery = new UPNPLib.UPnPDeviceFinder();
UPnPFinderCallback call = new UPnPFinderCallback();
discovery.StartAsyncFind(discovery.CreateAsyncFind("urn:schemas-upnp-org:device:MediaServer:1", 0, call));
//TODO APIv2 ListUPNP: Need a tweak as this now should return it as list?
return APIStatus.notImplemented();
}
private object AddUPNP()
{
//TODO APIv2 AddUPNP: implement this
return APIStatus.notImplemented();
}
private object DeleteUPNP()
{
//TODO APIv2 DeleteUPN: implement this
return APIStatus.notImplemented();
}
#endregion
#region 3.Settings
/// <summary>
/// Set JMMServer Port
/// </summary>
/// <returns></returns>
private object SetPort()
{
Creditentials cred = this.Bind();
if (cred.port != 0)
{
ServerSettings.JMMServerPort = cred.port.ToString();
return APIStatus.statusOK();
}
else
{
return new APIMessage(400, "Port Missing");
}
}
/// <summary>
/// Get JMMServer Port
/// </summary>
/// <returns></returns>
private object GetPort()
{
dynamic x = new System.Dynamic.ExpandoObject();
x.port = int.Parse(ServerSettings.JMMServerPort);
return x;
}
/// <summary>
/// Set Imagepath as default or custom
/// </summary>
/// <returns></returns>
private object SetImagepath()
{
ImagePath imagepath = this.Bind();
if (imagepath.isdefault)
{
ServerSettings.ImagesPath = ServerSettings.DefaultImagePath;
return APIStatus.statusOK();
}
else
{
if (!String.IsNullOrEmpty(imagepath.path) && imagepath.path != "")
{
if (Directory.Exists(imagepath.path))
{
ServerSettings.ImagesPath = imagepath.path;
return APIStatus.statusOK();
}
else
{
return new APIMessage(404, "Directory Not Found on Host");
}
}
else
{
return new APIMessage(400, "Path Missing");
}
}
}
/// <summary>
/// Return ImagePath object
/// </summary>
/// <returns></returns>
private object GetImagepath()
{
ImagePath imagepath = new ImagePath();
imagepath.path = ServerSettings.ImagesPath;
imagepath.isdefault = ServerSettings.ImagesPath == ServerSettings.DefaultImagePath;
return imagepath;
}
/// <summary>
/// Return body of current working settings.json - this could act as backup
/// </summary>
/// <returns></returns>
private object ExportConfig()
{
try
{
return ServerSettings.appSettings;
}
catch
{
return APIStatus.internalError("Error while reading settings.");
}
}
private object ImportConfig()
{
Contract_ServerSettings settings = this.Bind();
string raw_settings = settings.ToJSON();
string path = Path.Combine(ServerSettings.ApplicationPath, "temp.json");
File.WriteAllText(path, raw_settings, System.Text.Encoding.UTF8);
try
{
ServerSettings.LoadSettingsFromFile(path, true);
return APIStatus.statusOK();
}
catch
{
return APIStatus.internalError("Error while importing settings");
}
}
#endregion
#region 4.AniDB
/// <summary>
/// Set AniDB account with login, password and client port
/// </summary>
/// <returns></returns>
private object SetAniDB()
{
Creditentials cred = this.Bind();
if (!String.IsNullOrEmpty(cred.login) && cred.login != "" && !String.IsNullOrEmpty(cred.password) && cred.password != "")
{
ServerSettings.AniDB_Username = cred.login;
ServerSettings.AniDB_Password = <PASSWORD>;
if (cred.port != 0)
{
ServerSettings.AniDB_ClientPort = cred.port.ToString();
}
return APIStatus.statusOK();
}
else
{
return new APIMessage(400, "Login and Password missing");
}
}
/// <summary>
/// Test AniDB Creditentials
/// </summary>
/// <returns></returns>
private object TestAniDB()
{
JMMService.AnidbProcessor.ForceLogout();
JMMService.AnidbProcessor.CloseConnections();
Thread.Sleep(1000);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(ServerSettings.Culture);
JMMService.AnidbProcessor.Init(ServerSettings.AniDB_Username, ServerSettings.AniDB_Password,
ServerSettings.AniDB_ServerAddress,
ServerSettings.AniDB_ServerPort, ServerSettings.AniDB_ClientPort);
if (JMMService.AnidbProcessor.Login())
{
JMMService.AnidbProcessor.ForceLogout();
return APIStatus.statusOK();
}
else
{
return APIStatus.unauthorized();
}
}
/// <summary>
/// Return login/password/port of used AniDB
/// </summary>
/// <returns></returns>
private object GetAniDB()
{
Creditentials cred = new Creditentials();
cred.login = ServerSettings.AniDB_Username;
cred.password = ServerSettings.AniDB_Password;
cred.port = int.Parse(ServerSettings.AniDB_ClientPort);
return cred;
}
/// <summary>
/// Sync votes bettween Local and AniDB and only upload to MAL
/// </summary>
/// <returns></returns>
private object SyncAniDBVotes()
{
//TODO APIv2: Command should be split into AniDb/MAL sepereate
CommandRequest_SyncMyVotes cmdVotes = new CommandRequest_SyncMyVotes();
cmdVotes.Save();
return APIStatus.statusOK();
}
/// <summary>
/// Sync AniDB List
/// </summary>
/// <returns></returns>
private object SyncAniDBList()
{
MainWindow.SyncMyList();
return APIStatus.statusOK();
}
/// <summary>
/// Update all series infromation from AniDB
/// </summary>
/// <returns></returns>
private object UpdateAllAniDB()
{
Importer.RunImport_UpdateAllAniDB();
return APIStatus.statusOK();
}
#endregion
#region 5.MyAnimeList
/// <summary>
/// Set MAL account with login, password
/// </summary>
/// <returns></returns>
private object SetMAL()
{
Creditentials cred = this.Bind();
if (!String.IsNullOrEmpty(cred.login) && cred.login != "" && !String.IsNullOrEmpty(cred.password) && cred.password != "")
{
ServerSettings.MAL_Username = cred.login;
ServerSettings.MAL_Password = <PASSWORD>;
return APIStatus.statusOK();
}
else
{
return new APIMessage(400, "Login and Password missing");
}
}
/// <summary>
/// Return current used MAL Creditentials
/// </summary>
/// <returns></returns>
private object GetMAL()
{
Creditentials cred = new Creditentials();
cred.login = ServerSettings.MAL_Username;
cred.password = ServerSettings.MAL_<PASSWORD>;
return cred;
}
/// <summary>
/// Test MAL Creditionals against MAL
/// </summary>
/// <returns></returns>
private object TestMAL()
{
if (Providers.MyAnimeList.MALHelper.VerifyCredentials())
{
return APIStatus.statusOK();
}
else
{
return APIStatus.unauthorized();
}
}
#endregion
#region 6.Trakt
/// <summary>
/// Set Trakt PIN
/// </summary>
/// <returns></returns>
private object SetTraktPIN()
{
Creditentials cred = this.Bind();
if (!String.IsNullOrEmpty(cred.token) && cred.token != "")
{
ServerSettings.Trakt_PIN = cred.token;
return APIStatus.statusOK();
}
else
{
return new APIMessage(400, "Token missing");
}
}
/// <summary>
/// Create AuthToken and RefreshToken from PIN
/// </summary>
/// <returns></returns>
private object CreateTrakt()
{
if (Providers.TraktTV.TraktTVHelper.EnterTraktPIN(ServerSettings.Trakt_PIN) == "Success")
{
return APIStatus.statusOK();
}
else
{
return APIStatus.unauthorized();
}
}
/// <summary>
/// Return trakt authtoken
/// </summary>
/// <returns></returns>
private object GetTrakt()
{
Creditentials cred = new Creditentials();
cred.token = ServerSettings.Trakt_AuthToken;
cred.refresh_token = ServerSettings.Trakt_RefreshToken;
return cred;
}
/// <summary>
/// Sync Trakt Collection
/// </summary>
/// <returns></returns>
private object SyncTrakt()
{
if (ServerSettings.Trakt_IsEnabled && !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
{
CommandRequest_TraktSyncCollection cmd = new CommandRequest_TraktSyncCollection(true);
cmd.Save();
return APIStatus.statusOK();
}
else
{
return new APIMessage(204, "Trak is not enabled or you missing authtoken");
}
}
/// <summary>
/// Update All information from Trakt
/// </summary>
/// <returns></returns>
private object UpdateAllTrakt()
{
Providers.TraktTV.TraktTVHelper.UpdateAllInfo();
return APIStatus.statusOK();
}
#endregion
#region 7.TvDB
/// <summary>
/// Update all information from TvDB
/// </summary>
/// <returns></returns>
private object UpdateAllTvDB()
{
Importer.RunImport_UpdateTvDB(false);
return APIStatus.statusOK();
}
#endregion
#region 8.Actions
/// <summary>
/// Scans your import folders and remove files from your database that are no longer in your collection.
/// </summary>
/// <returns></returns>
private object RemoveMissingFiles()
{
MainWindow.RemoveMissingFiles();
return APIStatus.statusOK();
}
/// <summary>
/// Updates all series stats such as watched state and missing files.
/// </summary>
/// <returns></returns>
private object UpdateStats()
{
Importer.UpdateAllStats();
return APIStatus.statusOK();
}
/// <summary>
/// Updates all technical details about the files in your collection via running MediaInfo on them.
/// </summary>
/// <returns></returns>
private object UpdateMediaInfo()
{
MainWindow.RefreshAllMediaInfo();
return APIStatus.statusOK();
}
/// <summary>
/// Sync Hashes - download/upload hashes from/to webcache
/// </summary>
/// <returns></returns>
private object HashSync()
{
MainWindow.SyncHashes();
return APIStatus.statusOK();
}
#endregion
#region 9.Misc
/// <summary>
/// return userid as it can be needed in legacy implementation
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
private object MyID()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
dynamic x = new System.Dynamic.ExpandoObject();
if (user != null)
{
x.userid = user.JMMUserID;
return x;
}
else
{
x.userid = 0;
return x;
}
}
/// <summary>
/// Return newest posts from
/// </summary>
/// <returns></returns>
private object GetNews(int max)
{
var client = new System.Net.WebClient();
client.Headers.Add("User-Agent", "jmmserver");
client.Headers.Add("Accept", "application/json");
var response = client.DownloadString(new Uri("http://jmediamanager.org/wp-json/wp/v2/posts"));
List<dynamic> news_feed = JsonConvert.DeserializeObject<List<dynamic>>(response);
List<WebNews> news = new List<WebNews>();
int limit = 0;
foreach (dynamic post in news_feed)
{
limit++;
WebNews wn = new WebNews();
wn.author = post.author;
wn.date = post.date;
wn.link = post.link;
wn.title = System.Web.HttpUtility.HtmlDecode((string)post.title.rendered);
wn.description = post.excerpt.rendered;
news.Add(wn);
if (limit >= max) break;
}
return news;
}
#endregion
#region 10.User
/// <summary>
/// return Dictionary int = id, string = username
/// </summary>
/// <returns></returns>
private object GetUsers()
{
return new CommonImplementation().GetUsers();
}
/// <summary>
/// Create user from Contract_JMMUser
/// </summary>
/// <returns></returns>
private object CreateUser()
{
Request request = this.Request;
Entities.JMMUser _user = (Entities.JMMUser)this.Context.CurrentUser;
if (_user.IsAdmin == 1)
{
Contract_JMMUser user = this.Bind();
user.Password = <PASSWORD>(<PASSWORD>);
user.HideCategories = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
user.PlexUsers = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
if (new JMMServiceImplementation().SaveUser(user) == "")
{
return APIStatus.statusOK();
}
else
{
return APIStatus.internalError();
}
}
else
{
return APIStatus.adminNeeded();
}
}
/// <summary>
/// change current user password
/// </summary>
/// <returns></returns>
private object ChangePassword()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
return ChangePassword(user.JMMUserID);
}
/// <summary>
/// change given user (by uid) password
/// </summary>
/// <returns></returns>
private object ChangePassword(int uid)
{
Request request = this.Request;
Entities.JMMUser _user = (Entities.JMMUser)this.Context.CurrentUser;
if (_user.IsAdmin == 1)
{
JMMUser user = this.Bind();
if (new JMMServiceImplementation().ChangePassword(uid, user.Password) == "")
{
return APIStatus.statusOK();
}
else
{
return APIStatus.internalError();
}
}
else
{
return APIStatus.adminNeeded();
}
}
/// <summary>
/// Delete user from his ID
/// </summary>
/// <returns></returns>
private object DeleteUser()
{
Request request = this.Request;
JMMUser _user = (JMMUser)this.Context.CurrentUser;
if (_user.IsAdmin == 1)
{
JMMUser user = this.Bind();
if (new JMMServiceImplementation().DeleteUser(user.JMMUserID) == "")
{
return APIStatus.statusOK();
}
else
{
return APIStatus.internalError();
}
}
else
{
return APIStatus.adminNeeded();
}
}
#endregion
#region 11.Queue
/// <summary>
/// Return current information about Queues (hash, general, images)
/// </summary>
/// <returns></returns>
private object GetQueue()
{
Dictionary<string, QueueInfo> queues = new Dictionary<string, QueueInfo>();
queues.Add("hash", (QueueInfo)GetHasherQueue());
queues.Add("general", (QueueInfo)GetGeneralQueue());
queues.Add("image", (QueueInfo)GetImagesQueue());
return queues;
}
/// <summary>
/// Pause all running Queues
/// </summary>
/// <returns></returns>
private object PauseQueue()
{
JMMService.CmdProcessorHasher.Paused = true;
JMMService.CmdProcessorGeneral.Paused = true;
JMMService.CmdProcessorImages.Paused = true;
return APIStatus.statusOK();
}
/// <summary>
/// Start all queues that are pasued
/// </summary>
/// <returns></returns>
private object StartQueue()
{
JMMService.CmdProcessorHasher.Paused = false;
JMMService.CmdProcessorGeneral.Paused = false;
JMMService.CmdProcessorImages.Paused = false;
return APIStatus.statusOK();
}
/// <summary>
/// Return information about Hasher queue
/// </summary>
/// <returns></returns>
private object GetHasherQueue()
{
QueueInfo queue = new QueueInfo();
queue.count = ServerInfo.Instance.HasherQueueCount;
queue.state = ServerInfo.Instance.HasherQueueState;
queue.isrunning = ServerInfo.Instance.HasherQueueRunning;
queue.ispause = ServerInfo.Instance.HasherQueuePaused;
return queue;
}
/// <summary>
/// Return information about General queue
/// </summary>
/// <returns></returns>
private object GetGeneralQueue()
{
QueueInfo queue = new QueueInfo();
queue.count = ServerInfo.Instance.GeneralQueueCount;
queue.state = ServerInfo.Instance.GeneralQueueState;
queue.isrunning = ServerInfo.Instance.GeneralQueueRunning;
queue.ispause = ServerInfo.Instance.GeneralQueuePaused;
return queue;
}
/// <summary>
/// Return information about Images queue
/// </summary>
/// <returns></returns>
private object GetImagesQueue()
{
QueueInfo queue = new QueueInfo();
queue.count = ServerInfo.Instance.ImagesQueueCount;
queue.state = ServerInfo.Instance.ImagesQueueState;
queue.isrunning = ServerInfo.Instance.ImagesQueueRunning;
queue.ispause = ServerInfo.Instance.ImagesQueuePaused;
return queue;
}
/// <summary>
/// Pause Queue
/// </summary>
/// <returns></returns>
private object PauseHasherQueue()
{
JMMService.CmdProcessorHasher.Paused = true;
return APIStatus.statusOK();
}
/// <summary>
/// Pause Queue
/// </summary>
/// <returns></returns>
private object PauseGeneralQueue()
{
JMMService.CmdProcessorGeneral.Paused = true;
return APIStatus.statusOK();
}
/// <summary>
/// Pause Queue
/// </summary>
/// <returns></returns>
private object PauseImagesQueue()
{
JMMService.CmdProcessorImages.Paused = true;
return APIStatus.statusOK();
}
/// <summary>
/// Start Queue from Pause state
/// </summary>
/// <returns></returns>
private object StartHasherQueue()
{
JMMService.CmdProcessorHasher.Paused = false;
return APIStatus.statusOK();
}
/// <summary>
/// Start Queue from Pause state
/// </summary>
/// <returns></returns>
private object StartGeneralQueue()
{
JMMService.CmdProcessorGeneral.Paused = false;
return APIStatus.statusOK();
}
/// <summary>
/// Start Queue from Pause state
/// </summary>
/// <returns></returns>
private object StartImagesQueue()
{
JMMService.CmdProcessorImages.Paused = false;
return APIStatus.statusOK();
}
/// <summary>
/// Clear Queue and Restart it
/// </summary>
/// <returns></returns>
private object ClearHasherQueue()
{
try
{
JMMService.CmdProcessorHasher.Stop();
while (JMMService.CmdProcessorHasher.ProcessingCommands)
{
Thread.Sleep(200);
}
Thread.Sleep(200);
RepoFactory.CommandRequest.Delete(RepoFactory.CommandRequest.GetAllCommandRequestHasher());
JMMService.CmdProcessorHasher.Init();
return APIStatus.statusOK();
}
catch
{
return APIStatus.internalError();
}
}
/// <summary>
/// Clear Queue and Restart it
/// </summary>
/// <returns></returns>
private object ClearGeneralQueue()
{
try
{
JMMService.CmdProcessorGeneral.Stop();
while (JMMService.CmdProcessorGeneral.ProcessingCommands)
{
Thread.Sleep(200);
}
Thread.Sleep(200);
RepoFactory.CommandRequest.Delete(RepoFactory.CommandRequest.GetAllCommandRequestGeneral());
JMMService.CmdProcessorGeneral.Init();
return APIStatus.statusOK();
}
catch
{
return APIStatus.internalError();
}
}
/// <summary>
/// Clear Queue and Restart it
/// </summary>
/// <returns></returns>
private object ClearImagesQueue()
{
try
{
JMMService.CmdProcessorImages.Stop();
while (JMMService.CmdProcessorImages.ProcessingCommands)
{
Thread.Sleep(200);
}
Thread.Sleep(200);
RepoFactory.CommandRequest.Delete(RepoFactory.CommandRequest.GetAllCommandRequestImages());
JMMService.CmdProcessorImages.Init();
return APIStatus.statusOK();
}
catch
{
return APIStatus.internalError();
}
}
#endregion
#region 12.Files
/// <summary>
/// Get file info by its ID
/// </summary>
/// <param name="file_id"></param>
/// <returns></returns>
private object GetFileById(int file_id)
{
JMMServiceImplementation _impl = new JMMServiceImplementation();
VideoLocal file = _impl.GetFileByID(file_id);
return file;
}
/// <summary>
/// Get List of all files
/// </summary>
/// <returns></returns>
private object GetAllFiles()
{
JMMServiceImplementation _impl = new JMMServiceImplementation();
Dictionary<int, string> files = new Dictionary<int, string>();
foreach (VideoLocal file in _impl.GetAllFiles())
{
files.Add(file.VideoLocalID, file.FileName);
}
return files;
}
/// <summary>
/// return how many files collection have
/// </summary>
/// <returns></returns>
private object CountFiles()
{
JMMServiceImplementation _impl = new JMMServiceImplementation();
Counter count = new Counter();
count.count = _impl.GetAllFiles().Count;
return count;
}
/// <summary>
/// Return List<> of recently added files paths
/// </summary>
/// <param name="max_limit"></param>
/// <returns></returns>
private object GetRecentFiles(int max_limit)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
List<RecentFile> files = new List<RecentFile>();
foreach (VideoLocal file in _impl.GetFilesRecentlyAdded(max_limit))
{
RecentFile recent = new RecentFile();
recent.path = file.FileName;
recent.id = file.VideoLocalID;
if (file.EpisodeCrossRefs.Count() == 0)
{
recent.success = false;
}
else
{
recent.success = true;
}
files.Add(recent);
}
return files;
}
/// <summary>
/// Return list of paths of files that have benn makred as Unrecognised
/// </summary>
/// <param name="max_limit"></param>
/// <returns></returns>
private object GetUnrecognisedFiles(int max_limit)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Dictionary<int, string> files = new Dictionary<int, string>();
JMMServiceImplementation _impl = new JMMServiceImplementation();
int i = 0;
foreach (Contract_VideoLocal file in _impl.GetUnrecognisedFiles(user.JMMUserID))
{
i++;
files.Add(file.VideoLocalID, file.FileName);
if (i >= max_limit) break;
}
return files;
}
#endregion
#region 13.Episodes
/// <summary>
/// return all known anime series
/// </summary>
/// <returns></returns>
private object GetAllEpisodes()
{
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetAllEpisodes();
}
/// <summary>
/// Return information about episode by given ID for current user
/// </summary>
/// <param name="ep_id"></param>
/// <returns></returns>
private object GetEpisodeById(int ep_id)
{
if (ep_id != 0)
{
return GetEpisode(ep_id);
}
else
{
return APIStatus.badRequest();
}
}
internal Contract_AnimeEpisode GetEpisode(int ep_id)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetEpisode(ep_id, user.JMMUserID);
}
private object GetEpisodeImage(int ep_id)
{
if (ep_id != 0)
{
//_rest.GetImage("6/12", )
//GetEpisode(ep_id).
return APIStatus.notImplemented();
}
else
{
return APIStatus.badRequest();
}
}
/// <summary>
/// Get recent Episodes
/// </summary>
/// <param name="max_limit"></param>
/// <returns></returns>
private object GetRecentEpisodes(int max_limit)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetEpisodesRecentlyAdded(max_limit, user.JMMUserID);
}
/// <summary>
/// Set watch status (true) or unwatch (false) for episode that 'id' was given in post body
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
private object MarkEpisodeWatched(bool status)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
//we need just 'id'
Rating epi = this.Bind();
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.ToggleWatchedStatusOnEpisode(epi.id, status, user.JMMUserID);
}
/// <summary>
/// Set score for episode
/// </summary>
/// <returns></returns>
private object VoteOnEpisode()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Rating epi = this.Bind();
JMMServiceImplementation _impl = new JMMServiceImplementation();
_impl.VoteAnime(epi.id, (decimal)epi.score, (int)AniDBAPI.enAniDBVoteType.Episode);
return APIStatus.statusOK();
}
private object EpisodeScrobble()
{
return APIStatus.notImplemented();
}
#endregion
#region 14.Series
/// <summary>
/// Return number of series inside collection
/// </summary>
/// <returns></returns>
private object CountSerie()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
Counter count = new Counter();
count.count = _impl.GetAllSeries(user.JMMUserID).Count;
return count;
}
/// <summary>
/// return all series for current user
/// </summary>
/// <returns></returns>
private object GetAllSeries()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetAllSeries(user.JMMUserID);
}
/// <summary>
/// return information about serie with given ID
/// </summary>
/// <param name="series_id"></param>
/// <returns></returns>
private object GetSerieById(int series_id)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetSeries(series_id, user.JMMUserID);
}
/// <summary>
/// Return list of series inside given folder
/// </summary>
/// <param name="folder_id"></param>
/// <param name="max"></param>
/// <returns></returns>
private object GetSerieByFolderId(int folder_id, int max)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetSeriesFileStatsByFolderID(folder_id, user.JMMUserID, max);
}
/// <summary>
/// return Recent added series
/// </summary>
/// <param name="max_limit"></param>
/// <returns></returns>
private object GetRecentSeries(int max_limit)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.GetSeriesRecentlyAdded(max_limit, user.JMMUserID);
}
/// <summary>
/// Mark given number files of given type for series as un/watched
/// </summary>
/// <param name="status">true = watched, false = unwatched</param>
/// <param name="max_episodes">max number or episode to mark</param>
/// <param name="type">1 = episodes, 2 = credits, 3 = special, 4 = trailer, 5 = parody, 6 = other</param>
/// <returns></returns>
private object MarkSerieWatched(bool status, int max_episodes, int type)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
//we need just 'id'
Rating ser = this.Bind();
JMMServiceImplementation _impl = new JMMServiceImplementation();
return _impl.SetWatchedStatusOnSeries(ser.id, status, max_episodes, type, user.JMMUserID);
}
/// <summary>
/// Set score for serie
/// </summary>
/// <returns></returns>
private object VoteOnSerie()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Rating ser = this.Bind();
JMMServiceImplementation _impl = new JMMServiceImplementation();
_impl.VoteAnime(ser.id, (decimal)ser.score, (int)AniDBAPI.enAniDBVoteType.Anime);
return APIStatus.statusOK();
}
private object GetSerieArt(int serie_id)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
JMMServiceImplementation _impl = new JMMServiceImplementation();
AnimeSeries ser = RepoFactory.AnimeSeries.GetByID(serie_id);
if (ser == null) { return APIStatus.notFound404(); }
Contract_AnimeSeries cseries = ser.GetUserContract(user.JMMUserID);
if (cseries == null) { return APIStatus.accessDenied(); }
if (cseries.AniDBAnime != null && cseries.AniDBAnime.AniDBAnime != null)
{
//cseries.AniDBAnime.AniDBAnime.Banners
// TODO Apiv2 - This is all around aproche We dont need > Series then contract just to access this lets ask directly image with animeid = id but how?!
return cseries.AniDBAnime.AniDBAnime.Fanarts;
}
else
{
return APIStatus.internalError();
}
}
/// <summary>
/// Search for serie that contain given query
/// </summary>
/// <returns>first 100 results</returns>
private object SearchForSerie()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Search ser = this.Bind();
return Search(ser.query, 100, false, user.JMMUserID);
}
/// <summary>
/// Search for serie that contain given query, limit your results with variable
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
private object SearchForSerie(int limit)
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Search ser = this.Bind();
return Search(ser.query, limit, false, user.JMMUserID);
}
/// <summary>
/// search for tag with given query inside
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
private object SearchForTag()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Search ser = this.Bind();
return Search(ser.query, 100, true, user.JMMUserID);
}
internal object Search(string query, int limit, bool tag_search, int userid)
{
CommonImplementation _comm = new CommonImplementation();
IProvider _prov_kodi = new PlexAndKodi.Kodi.KodiProvider();
return _comm.Search(_prov_kodi, userid.ToString(), limit.ToString(), query, tag_search);
}
#endregion
#region 15.WebUI
/// <summary>
/// Return Dictionary with nesesery items for Dashboard inside Webui
/// </summary>
/// <returns></returns>
private object GetDashboard()
{
Dictionary<string, object> dash = new Dictionary<string, object>();
dash.Add("queue", GetQueue());
dash.Add("file", GetRecentFiles(10));
dash.Add("folder", GetFolders());
dash.Add("file_count", CountFiles());
dash.Add("serie_count", CountSerie());
return dash;
}
/// <summary>
/// Download the latest stable version of WebUI
/// </summary>
/// <returns></returns>
private object WebUIStableUpdate()
{
return WebUIGetUrlAndUpdate(WebUILatestStableVersion().version);
}
/// <summary>
/// Download the latest unstable version of WebUI
/// </summary>
/// <returns></returns>
private object WebUIUnstableUpdate()
{
return WebUIGetUrlAndUpdate(WebUILatestUnstableVersion().version);
}
/// <summary>
/// Get url for update and start update
/// </summary>
/// <param name="tag_name"></param>
/// <returns></returns>
internal object WebUIGetUrlAndUpdate(string tag_name)
{
try
{
var client = new System.Net.WebClient();
client.Headers.Add("Accept: application/vnd.github.v3+json");
client.Headers.Add("User-Agent", "jmmserver");
var response = client.DownloadString(new Uri("https://api.github.com/repos/japanesemediamanager/jmmserver-webui/releases/tags/" + tag_name));
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
string url = "";
foreach (dynamic obj in result.assets)
{
if (obj.name == "latest.zip")
{
url = obj.browser_download_url;
break;
}
}
//check if tag was parsed corrently as it make the url
if (url != "")
{
return WebUIUpdate(url);
}
else
{
return new APIMessage(204, "Content is missing");
}
}
catch
{
return APIStatus.internalError();
}
}
/// <summary>
/// Update WebUI with version from given url
/// </summary>
/// <param name="url">direct link to version you want to install</param>
/// <returns></returns>
internal object WebUIUpdate(string url)
{
//list all files from root /webui/ and all directories
string[] files = Directory.GetFiles("webui");
string[] directories = Directory.GetDirectories("webui");
try
{
//download latest version
var client = new System.Net.WebClient();
client.Headers.Add("User-Agent", "jmmserver");
client.DownloadFile(url, "webui\\latest.zip");
//create 'old' dictionary
if (!Directory.Exists("webui\\old")) { System.IO.Directory.CreateDirectory("webui\\old"); }
try
{
//move all directories and files to 'old' folder as fallback recovery
foreach (string dir in directories)
{
if (Directory.Exists(dir) && dir != "webui\\old")
{
string n_dir = dir.Replace("webui", "webui\\old");
Directory.Move(dir, n_dir);
}
}
foreach (string file in files)
{
if (File.Exists(file))
{
string n_file = file.Replace("webui", "webui\\old");
File.Move(file, n_file);
}
}
try
{
//extract latest webui
System.IO.Compression.ZipFile.ExtractToDirectory("webui\\latest.zip", "webui");
//clean because we already have working updated webui
Directory.Delete("webui\\old", true);
File.Delete("webui\\latest.zip");
return APIStatus.statusOK();
}
catch
{
//when extracting latest.zip failes
return new APIMessage(405, "MethodNotAllowed");
}
}
catch
{
//when moving files to 'old' folder failed
return new APIMessage(423, "Locked");
}
}
catch
{
//when download failed
return new APIMessage(499, "download failed");
}
}
/// <summary>
/// Check for newest stable version and return object { version: string, url: string }
/// </summary>
/// <returns></returns>
private ComponentVersion WebUILatestStableVersion()
{
ComponentVersion version = new ComponentVersion();
version = WebUIGetLatestVersion(true);
return version;
}
/// <summary>
/// Check for newest unstable version and return object { version: string, url: string }
/// </summary>
/// <returns></returns>
private ComponentVersion WebUILatestUnstableVersion()
{
ComponentVersion version = new ComponentVersion();
version = WebUIGetLatestVersion(false);
return version;
}
/// <summary>
/// Find version that match requirements
/// </summary>
/// <param name="stable">do version have to be stable</param>
/// <returns></returns>
internal ComponentVersion WebUIGetLatestVersion(bool stable)
{
var client = new System.Net.WebClient();
client.Headers.Add("Accept: application/vnd.github.v3+json");
client.Headers.Add("User-Agent", "jmmserver");
var response = client.DownloadString(new Uri("https://api.github.com/repos/japanesemediamanager/jmmserver-webui/releases/latest"));
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
ComponentVersion version = new ComponentVersion();
if (result.prerelease == "False")
{
//not pre-build
if (stable)
{
version.version = result.tag_name;
}
else
{
version.version = WebUIGetVersionsTag(false);
}
}
else
{
//pre-build
if (stable)
{
version.version = WebUIGetVersionsTag(true);
}
else
{
version.version = result.tag_name;
}
}
return version;
}
/// <summary>
/// Return tag_name of version that match requirements and is not present in /latest/
/// </summary>
/// <param name="stable">do version have to be stable</param>
/// <returns></returns>
internal string WebUIGetVersionsTag(bool stable)
{
var client = new System.Net.WebClient();
client.Headers.Add("Accept: application/vnd.github.v3+json");
client.Headers.Add("User-Agent", "jmmserver");
var response = client.DownloadString(new Uri("https://api.github.com/repos/japanesemediamanager/jmmserver-webui/releases"));
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(response);
foreach (dynamic obj in result)
{
if (stable)
{
if (obj.prerelease == "False")
{
foreach (dynamic file in obj.assets)
{
if ((string)file.name == "latest.zip")
{
return obj.tag_name;
}
}
}
}
else
{
if (obj.prerelease == "True")
{
foreach (dynamic file in obj.assets)
{
if ((string)file.name == "latest.zip")
{
return obj.tag_name;
}
}
}
}
}
return "";
}
/// <summary>
/// Read json file that is converted into string from .config file of jmmserver
/// </summary>
/// <returns></returns>
private object GetWebUIConfig()
{
if (!String.IsNullOrEmpty(ServerSettings.WebUI_Settings))
{
try
{
WebUI_Settings settings = JsonConvert.DeserializeObject<WebUI_Settings>(ServerSettings.WebUI_Settings);
return settings;
}
catch
{
return APIStatus.internalError("error while reading webui settings");
}
}
else
{
return APIStatus.notFound404();
}
}
/// <summary>
/// Save webui settings as json converted into string inside .config file of jmmserver
/// </summary>
/// <returns></returns>
private object SetWebUIConfig()
{
WebUI_Settings settings = this.Bind();
if (settings.Valid())
{
try
{
ServerSettings.WebUI_Settings = JsonConvert.SerializeObject(settings);
return APIStatus.statusOK();
}
catch
{
return APIStatus.internalError("error at saving webui settings");
}
}
else
{
return new APIMessage(400, "Config is not a Valid.");
}
}
#endregion
#region 16.OS-based operations
/// <summary>
/// Return OSFolder object that is a folder from which jmmserver is running
/// </summary>
/// <returns></returns>
private object GetOSBaseFolder()
{
OSFolder dir = new OSFolder();
dir.full_path = Environment.CurrentDirectory;
System.IO.DirectoryInfo dir_info = new DirectoryInfo(dir.full_path);
dir.dir = dir_info.Name;
dir.subdir = new List<OSFolder>();
foreach (DirectoryInfo info in dir_info.GetDirectories())
{
OSFolder subdir = new OSFolder();
subdir.full_path = info.FullName;
subdir.dir = info.Name;
dir.subdir.Add(subdir);
}
return dir;
}
/// <summary>
/// Return OSFolder object of directory that was given via
/// </summary>
/// <param name="folder"></param>
/// <returns></returns>
private object GetOSFolder(string folder)
{
OSFolder dir = this.Bind();
if (!String.IsNullOrEmpty(dir.full_path))
{
System.IO.DirectoryInfo dir_info = new DirectoryInfo(dir.full_path);
dir.dir = dir_info.Name;
dir.subdir = new List<OSFolder>();
foreach (DirectoryInfo info in dir_info.GetDirectories())
{
OSFolder subdir = new OSFolder();
subdir.full_path = info.FullName;
subdir.dir = info.Name;
dir.subdir.Add(subdir);
}
return dir;
}
else
{
return new APIMessage(400, "full_path missing");
}
}
/// <summary>
/// Return OSFolder with subdirs as every driver on local system
/// </summary>
/// <returns></returns>
private object GetOSDrives()
{
string[] drives = System.IO.Directory.GetLogicalDrives();
OSFolder dir = new OSFolder();
dir.dir = "/";
dir.full_path = "/";
dir.subdir = new List<OSFolder>();
foreach (string str in drives)
{
OSFolder driver = new OSFolder();
driver.dir = str;
driver.full_path = str;
dir.subdir.Add(driver);
}
return dir;
}
#endregion
#region 17.Cloud Accounts
private object GetCloudAccounts()
{
// TODO APIv2: Cloud
return APIStatus.notImplemented();
}
private object GetCloudAccountsCount()
{
// TODO APIv2: Cloud
return APIStatus.notImplemented();
}
private object AddCloudAccount()
{
// TODO APIv2: Cloud
return APIStatus.notImplemented();
}
private object DeleteCloudAccount()
{
// TODO APIv2: Cloud
return APIStatus.notImplemented();
}
private object RunCloudImport()
{
MainWindow.RunImport();
return APIStatus.statusOK();
}
#endregion
#region 18. Images
/// <summary>
/// Return image with given Id type and information if its should be thumb
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <param name="thumb"></param>
/// <returns></returns>
private object GetImage(int id, int type, bool thumb)
{
string contentType;
System.IO.Stream image = _rest.GetImage(type.ToString(), id.ToString(), thumb, out contentType);
Nancy.Response response = new Nancy.Response();
response = Response.FromStream(image, contentType);
return response;
}
private object GetFanart(int serie_id)
{
//Request request = this.Request;
//Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
//JMMServiceImplementation _impl = new JMMServiceImplementation();
//Contract_AnimeSeries ser = _impl.GetSeries(serie_id, user.JMMUserID);
//Currently hack this, as the end result should find image for series id not image id.
//TODO APIv2 This should return default image for series_id not image_id
string contentType;
System.IO.Stream image = _rest.GetImage("7".ToString(), serie_id.ToString(), false, out contentType);
if (image == null)
{
image = _rest.GetImage("11".ToString(), serie_id.ToString(), false, out contentType);
}
if (image == null)
{
image = _rest.GetImage("8".ToString(), serie_id.ToString(), false, out contentType);
}
else
{
image = _rest.BlankImage();
}
Nancy.Response response = new Nancy.Response();
response = Response.FromStream(image, contentType);
return response;
}
private object GetCover(int serie_id)
{
//TODO APIv2 This should return default image for series_id not image_id
string contentType;
System.IO.Stream image = _rest.GetImage("1".ToString(), serie_id.ToString(), false, out contentType);
if (image == null)
{
image = _rest.GetImage("5".ToString(), serie_id.ToString(), false, out contentType);
}
else
{
image = _rest.BlankImage();
}
Nancy.Response response = new Nancy.Response();
response = Response.FromStream(image, contentType);
return response;
}
private object GetPoster(int serie_id)
{
//TODO APIv2 This should return default image for series_id not image_id
string contentType;
System.IO.Stream image = _rest.GetImage("10".ToString(), serie_id.ToString(), false, out contentType);
if (image == null)
{
image = _rest.GetImage("9".ToString(), serie_id.ToString(), false, out contentType);
}
else
{
image = _rest.BlankImage();
}
Nancy.Response response = new Nancy.Response();
response = Response.FromStream(image, contentType);
return response;
}
#endregion
#region 19. Logs
/// <summary>
/// Run LogRotator with current settings
/// </summary>
/// <returns></returns>
private object StartRotateLogs()
{
MainWindow.logrotator.Start();
return APIStatus.statusOK();
}
/// <summary>
/// Set settings for LogRotator
/// </summary>
/// <returns></returns>
private object SetRotateLogs()
{
Request request = this.Request;
Entities.JMMUser user = (Entities.JMMUser)this.Context.CurrentUser;
Logs rotator = this.Bind();
if (user.IsAdmin == 1)
{
ServerSettings.RotateLogs = rotator.rotate;
ServerSettings.RotateLogs_Zip = rotator.zip;
ServerSettings.RotateLogs_Delete = rotator.delete;
ServerSettings.RotateLogs_Delete_Days = rotator.days.ToString();
return APIStatus.statusOK();
}
else
{
return APIStatus.adminNeeded();
}
}
/// <summary>
/// Get settings for LogRotator
/// </summary>
/// <returns></returns>
private object GetRotateLogs()
{
Logs rotator = new Logs();
rotator.rotate= ServerSettings.RotateLogs;
rotator.zip = ServerSettings.RotateLogs_Zip;
rotator.delete=ServerSettings.RotateLogs_Delete;
int day = 0;
if (!String.IsNullOrEmpty(ServerSettings.RotateLogs_Delete_Days))
{
int.TryParse(ServerSettings.RotateLogs_Delete_Days, out day);
}
rotator.days = day;
return rotator;
}
/// <summary>
/// return int position - current position
/// return string[] lines - lines from current log file
/// </summary>
/// <param name="lines">max lines to return</param>
/// <param name="position">position to seek</param>
/// <returns></returns>
private object GetLog(int lines, int position)
{
string log_file = LogRotator.GetCurrentLogFile();
if (string.IsNullOrEmpty(log_file))
{
return APIStatus.notFound404("Could not find current log name. Sorry");
}
if (!File.Exists(log_file))
{
return APIStatus.notFound404();
}
Dictionary<string, object> result = new Dictionary<string, object>();
FileStream fs = File.OpenRead(@log_file);
if (position >= fs.Length)
{
result.Add("position", fs.Length);
result.Add("lines", new string[] { });
return result;
}
List<string> logLines = new List<string>();
LogReader reader = new LogReader(fs, position);
for (int i=0; i<lines; i++)
{
string line = reader.ReadLine();
if (line == null) break;
logLines.Add(line);
}
result.Add("position", reader.Position);
result.Add("lines", logLines.ToArray());
return result;
}
#endregion
#region 20. Dev
/// <summary>
/// Dumps the contracts as JSON files embedded in a zip file.
/// </summary>
/// <param name="entityType">The type of the entity to dump (can be <see cref="string.Empty"/> or <c>null</c> to dump all).</param>
private object ExtractContracts(string entityType)
{
var zipStream = new ContractExtractor().GetContractsAsZipStream(entityType);
return new StreamResponse(() => zipStream, "application/zip").AsAttachment("contracts.zip");
}
#endregion
}
}
<file_sep>namespace JMMServer.API.Model
{
public class Rating
{
public int id { get; set; }
public int score { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JMMServer.API.Model
{
public class ArtCollection
{
public List<string> banner { get; set; }
public List<string> fanart { get; set; }
public List<string> thumb { get; set; }
public ArtCollection()
{
banner = new List<string>();
fanart = new List<string>();
thumb = new List<string>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JMMServer.API.Model
{
public class APIMessage
{
public int code { get; set; }
public string message { get; set; }
public APIMessage(int _code, string _message)
{
code = _code;
message = _message;
}
}
public static class APIStatus
{
public static APIMessage processing()
{
return new APIMessage(100, "processing");
}
public static APIMessage processing(string custom_message)
{
return new APIMessage(100, custom_message);
}
public static APIMessage statusOK()
{
return new APIMessage(200, "ok");
}
public static APIMessage statusOK(string custom_message)
{
return new APIMessage(200, custom_message);
}
public static APIMessage badRequest()
{
return new APIMessage(400, "Bad Request");
}
public static APIMessage badRequest(string custom_message)
{
return new APIMessage(400, custom_message);
}
public static APIMessage unauthorized()
{
return new APIMessage(401, "Unauthorized");
}
public static APIMessage adminNeeded()
{
return new APIMessage(403, "Admin rights needed");
}
public static APIMessage accessDenied()
{
return new APIMessage(403, "Access Denied");
}
public static APIMessage notFound404(string message="Not Found")
{
return new APIMessage(404, message);
}
public static APIMessage internalError(string custom_message="Internal Error")
{
return new APIMessage(500, custom_message);
}
public static APIMessage notImplemented()
{
return new APIMessage(501, "Not Implemented");
}
}
}
<file_sep>using JMMServer.API.Model;
using Nancy;
using System.Collections.Generic;
namespace JMMServer.API
{
public class APIv2_unauth_Module: Nancy.NancyModule
{
public APIv2_unauth_Module()
{
Get["/"] = _ => { return Response.AsRedirect("/webui/index.html"); };
Get["/api/version"] = x => { return GetVersion(); };
}
/// <summary>
/// Return current version of JMMServer
/// </summary>
/// <returns></returns>
private object GetVersion()
{
List<ComponentVersion> list = new List<ComponentVersion>();
ComponentVersion version = new ComponentVersion();
version.version = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString();
version.name = "jmmserver";
list.Add(version);
version = new ComponentVersion();
version.version = APIv2_core_Module.version.ToString();
version.name = "apiv2";
list.Add(version);
return list;
}
}
}
|
cb14af414137a2414f679a2ece8d812797450508
|
[
"C#"
] | 7
|
C#
|
monsieurtaco/jmmserver
|
d3f5727d41aa5e897ccd4593447690ed59332915
|
ed4f2060b5d0f9ea15aca82d4d4c08cf48f914c8
|
refs/heads/master
|
<file_sep>$(document).ready(function() {
// use this for paralax if needed
$(window).scroll(function() {
s = $(window).scrollTop() - 20;
w = $(window).width();
// sticky sidebar
console.log("working");
$('.title').css('margin-top', '-'+s+'%');
// parralax effects
// if (w > 800 && s < 800) {
// $('div.main-articles img').css('bottom', '-'+s/3+'px');
// };
});
// $('section.grid div div.article').on('click', function() {
// $('section.grid div').css('-webkit-column-count', '1');
// });
});<file_sep>(function() {
var app = angular.module('MyDirectives', []);
app.directive('sideBar', function() {
return {
restrict: 'E',
templateUrl: 'views/side-bar.html'
};
});
app.directive('landingPage', function() {
return {
restrict: 'E',
templateUrl: 'views/landing-page.html'
};
});
app.directive('comicsPage', function() {
return {
restrict: 'E',
templateUrl: 'views/comics-page.html'
};
});
app.directive('titleComics', function() {
return {
restrict: 'E',
templateUrl: 'views/title-comics.html'
};
});
app.directive('gridComics', function() {
return {
restrict: 'E',
templateUrl: 'views/grid-comics.html'
};
});
})();<file_sep>var http = require('http');
var express = require('express');
var fs = require('fs');
var path = require('path');
var app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.get('*', function(req, res) {
res.sendfile('public/main.html');
});
app.listen(8000);<file_sep>Angular Hamburger Toggle
------------------------
Angular directive of Material Design morphing hamburger menu toggle. It's based off of [Material Design Hamburger](https://github.com/swirlycheetah/material-design-hamburger).

###Features
* Two way bound state model.
* Tuned for Bootstrap.
* Super easy.
###[Demo](http://dbtek.github.io/angular-hamburger-toggle)
##Install
```bash
$ bower install angular-hamburger-toggle --save
```
##Usage
* Add dependency
```js
angular.module('myApp', ['ngHamburger']);
```
* Use directive
```html
<hamburger-toggle state="stateModel"></hamburger-toggle>
```
`state` attribute is for two way bound model that will be toggled. Initially can be `true`, `false` or `undefined`.
##Credits
[Material Design Hamburger](https://github.com/swirlycheetah/material-design-hamburger)
##Author
<NAME> - [@dbtek](https://twitter.com/dbtek)
<file_sep>(function() {
var initializing = true
var app = angular.module('MysiteApp', ['ngRoute', 'MyDirectives', 'ngAnimate', 'ngMaterial']);
// service created to pass boolean and json data between controllers.
app.service('sharedProperties', function ($http) {
var property = true;
return {
getProperty: function () {
return property;
},
setProperty: function(value) {
property = value;
},
getComics: function() {
return $http.get('src/data.json')
}
};
});
// controller for the landing page, used to check whether to the landing page is still being shown
app.controller('LandCtrl', function ($scope, $timeout, sharedProperties) {
$scope.showLanding = sharedProperties.getProperty();
$scope.isFlipped = false;
$scope.startBlocks = ["A","E","R","U","R","E","X"];
$scope.toggleLanding = function() {
$timeout(function() {
$scope.showLanding = false;
sharedProperties.setProperty(false);
}, 1500);
};
});
// controller for the comics, used to grab data from json file and start animations
app.controller('ComCtrl', function ($scope, $timeout, $mdSidenav, $http, sharedProperties) {
// $scope.toggleLeft = buildToggler('left');
$scope.boolChangeClass = true;
$scope.isSidenavOpen = false;
$scope.currentcomic = 0;
$scope.comics = [];
$scope.isDroped = false;
$scope.aerurex = [{"letter": "A", "valid": false, "id": 0}, {"letter": "E", "valid": false, "id": 1}, {"letter": "R", "valid": false, "id": 2}, {"letter": "U", "valid": false, "id": 3}, {"letter": "R", "valid": false, "id": 4}, {"letter": "E", "valid": false, "id": 5}, {"letter": "X", "valid": false, "id": 6}];
// watch for changes in shared boolean - this case indicating if landing page is still active
$scope.$watch(function() { return sharedProperties.getProperty(); }, function(newVal) {
if(initializing) {
initializing = false;
} else {
(function(){
$timeout(function() {
comicStart();
}, 0);
})();
}
}, true);
// change letter validity to true to signal "drop" animation of letter. Also retreive comics from service and allow comics to be shown
var comicStart = function () {
for(var i=0; i<$scope.aerurex.length; i++) {
(function(i){
$timeout(function() {
$scope.aerurex[i].valid = true;
if(i === 6) {
$scope.getComics();
$scope.dropComics();
};
}, i * 200);
})(i);
}
}
// watch for changes in sidenav bar and change var boolChangeClass to show this
$scope.$watch('isSidenavOpen', function(isSidenavOpen) {
$scope.boolChangeClass = !$scope.boolChangeClass;
});
$scope.checkDropValue = function(letterIndex) {
return $scope.aerurex[letterIndex].valid;
};
$scope.getComics = function() {
sharedProperties.getComics().success(function(data) {
// $scope.comics = data;
});
};
$scope.dropComics = function() {
$timeout(function() {
$scope.isDroped = true;
}, 500);
};
});
// app.controller('AppCtrl', function ($scope, $timeout, $mdSidenav, $mdUtil, $log, $http) {
// $scope.toggleLeft = buildToggler('left');
// $scope.boolChangeClass = true;
// $scope.isSidenavOpen = false;
// $scope.currentcomic = 0;
// $scope.comics = [];
// $scope.$watch('isSidenavOpen', function(isSidenavOpen) {
// $scope.boolChangeClass = !$scope.boolChangeClass;
// });
// // grabs content from data.json file
// $http.get('src/data.json').success(function(data) {
// $scope.comics = data;
// });
// function buildToggler(navID) {
// var debounceFn = $mdUtil.debounce(function(){
// $mdSidenav(navID)
// .toggle()
// .then(function () {
// $log.debug("toggle " + navID + " is done");
// });
// },300);
// return debounceFn;
// }
// $scope.selectComic = function(setComic) {
// $scope.currentcomic = setComic;
// $log.debug($scope.currentcomic);
// };
// $scope.isSelected = function(checkComic) {
// return $scope.currentcomic === checkComic;
// };
// });
// app.controller('LeftCtrl', function ($scope, $timeout, $mdSidenav, $log) {
// $scope.close = function () {
// $mdSidenav('left').close()
// .then(function () {
// $log.debug("close LEFT is done");
// });
// };
// });
})();
|
0631e52e71cdeb613d3e68d097fc371d7b3d4383
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
KopiSusu/Comic
|
b17ae20aaddea71ae77a308380e482a6b940b0f3
|
61cea310a9b875f1dbf04c3b2de6994236e7fa5b
|
refs/heads/main
|
<repo_name>leefreemanxyz/tdl<file_sep>/github-search-api/src/timestamp.ts
export function createTimestamps(message: string) {
return function (target: any, name: string, descriptor: PropertyDescriptor) {
const method = descriptor.value;
descriptor.value = async function (...args: any) {
const startTime = new Date(Date.now());
console.log(
`${message} started at: ${startTime.toLocaleString("en-GB")}`
);
const result = await method.apply(this, args);
const endTime = new Date(Date.now());
console.log(
`${message} completed at: ${endTime.toLocaleString("en-GB")}`
);
console.log(
`${message} took ${
endTime.getTime() - startTime.getTime()
}ms to complete.`
);
return result;
};
};
}
<file_sep>/github-search-api/src/routes/getUser.ts
import express, { NextFunction, Request, Response } from "express";
import { Github } from "../Github";
const router = express.Router();
router.get(
"/user/:id",
async (req: Request, res: Response, next: NextFunction) => {
const github = new Github();
try {
const response = await github.getUser(req.params.id);
res.send(response.data);
} catch (error) {
return next(error);
}
}
);
export { router as getUserRouter };
<file_sep>/github-search-app/cypress/integration/search.spec.js
describe("search", () => {
it("searches for a user and delivers a list of results", () => {
cy.visit("/");
cy.get('[data-testid="search-input"]').type("leefreemanxyz");
cy.get('[data-testid="user-result"]').its("length").should("be.gt", 0);
cy.get('[data-testid="total-count"]')
.invoke("text")
.then(parseFloat)
.should("be.gt", 0);
});
it("paginates next and previous", () => {
cy.visit("/?q=react");
cy.get('[data-testid="current-page"]').contains(1);
cy.get(".MuiPagination-ul > :last-child()").click();
cy.get('[data-testid="current-page"]').contains(2);
cy.get(".MuiPagination-ul > :first-child()").click();
cy.get('[data-testid="current-page"]').contains(1);
});
it("displays a UserCard with relevant details", () => {
cy.visit("/?q=leefreeman");
cy.get('[data-testid="username-leefreemanxyz"]').contains("leefreemanxyz");
cy.get('[data-testid="github-leefreemanxyz"]').should(
"have.attr",
"href",
"https://github.com/leefreemanxyz"
);
cy.get('[data-testid="twitter-leefreemanxyz"]').should(
"have.attr",
"href",
"https://twitter.com/leefreemanxyz"
);
cy.get('[data-testid="personal-leefreemanxyz"]').should(
"have.attr",
"href",
"https://leefreeman.xyz"
);
});
});
<file_sep>/github-search-app/src/hooks/useURLSearchParams.ts
import { useState, useCallback } from "react";
import { History, Location } from "history";
export type URLDispatch = {
type: "append" | "delete" | "set" | "sort";
payload: Payload;
};
type Payload = {
key: string;
value: string;
};
type CustomLocation = {
location: Location;
history: History;
};
export const useURLSearchParams = (customLocation: CustomLocation) => {
const { history, location } = customLocation;
const URLParams = new URLSearchParams(location.search);
const [params, setParams] = useState(URLParams);
const urlDispatch = useCallback(
({ type, payload }: URLDispatch) => {
const { key, value } = payload;
// Create new URLSearchParams object with updated values
params[type](key, value);
// Cleanup URL (empty query values)
params.forEach((_, key) => {
if (!params.get(key)) {
params.delete(key);
}
});
// Update the browser's URL
history.replace(`${location.pathname}?${params}`);
setParams(new URLSearchParams(params));
},
[history, params, location.pathname]
);
return { params, urlDispatch };
};
<file_sep>/README.md
# View app
[View app](https://tdl-7uvcq.ondigitalocean.app/). Search for your favourite GitHub users and view their profile. Wowee.
## Server
The GitHub API has a pretty low rate limit for unauthenticated requests. Hence, to avoid the user having to login, I've generated a personal account token for GitHub, but also, personal tokens really shouldn't be available in the browser, so I've written a small Express server through which requests can be proxied with the token attached.
The API makes available two endpoints of the GitHub Search API – further endpoints could be easily added to GitHub.ts, or just import the Octokit library.
Error handling middleware avoids sending stack traces to the client and decorators are used to time the onward requests to the GitHub API.
This type of data could definitely be cached (depending on the GitHub API's T&Cs which I have not read). It's easy enough to cache in memory or with a store like Redis (I've written a Redis cache decorator before for another project, which checks if an API response/object is in the cache before making the request, and either returning it if it's there or populating the cache after the request has returned).
It would also have been possible to create a magic endpoint that executes the search and then gets the user data before returning it but :woman_shrugging:.
(To run the server locally you'll need to `npm i`, supply your own environment variable for GITHUB_TOKEN and `npm run start` for development mode watching etc.)
## Client
To run: `npm i` and `npm run start`.
This is a Create React App with Material UI for component styling and React Query for API request management. This is the first time using it, and it evokes similar feelings to using SWR or Apollo Client => loading/error states are handled automatically and queries refetch when their dependent variables change (I've worked a lot with GraphQL/Apollo Client/Server in the past and wanted to try something different).
The URL is used to store the query state (via useURLSearchParams) which makes it easy to share with a friend!
useDebounce prevents the API being called on every keystroke.
I decided that the UserCard components should be able to fetch data about themselves. I could have sent them all in one request, but I would still have needed to split the user ids in Express because the GitHub API doesn't accept an array of ids for that endpoint (http2 requests can be fired concurrently, so we can always batch later if it needs optimising).
## Testing
I've used Testing Library to write a unit test of UserCard (`npm run test`) and written a couple of end-to-end tests with Cypress (`npm run cypress:open`).
## Deployment
This is deployed on Digital Ocean App Platform.
<file_sep>/github-search-api/src/Github.ts
import axios from "axios";
import { createTimestamps } from "./timestamp";
export class Github {
@createTimestamps("Search users")
async searchUsers(q: string) {
return await axios.get(`https://api.github.com/search/users?${q}`, {
headers: {
Authorization: `token ${process.env.GITHUB_TOKEN!}`,
},
});
}
@createTimestamps("Get user detail")
async getUser(id: string) {
return await axios.get(`https://api.github.com/users/${id}`, {
headers: {
Authorization: `token ${process.env.GITHUB_TOKEN!}`,
},
});
}
}
<file_sep>/github-search-api/src/routes/searchUsers.ts
import express, { NextFunction, Request, Response } from "express";
import { Github } from "../Github";
const router = express.Router();
const paramsToQueryString = (params: any, rest: any) => {
return Object.keys({ ...params, ...rest })
.map((key) => key + "=" + params[key])
.join("&");
};
router.get(
"/search/users",
async (req: Request, res: Response, next: NextFunction) => {
const qs = paramsToQueryString(req.query, { type: "user" });
const github = new Github();
try {
const response = await github.searchUsers(qs);
res.send(response.data);
} catch (error) {
return next(error);
}
}
);
export { router as searchUsersRouter };
|
ae823d73be864fabbfbe672a279d5ddc4942f990
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 7
|
TypeScript
|
leefreemanxyz/tdl
|
5ecdbd76c0aedf82c7e2d65cc2eece269f30f230
|
5f14dece661de013081ea5255919ef7f7fd9fb87
|
refs/heads/master
|
<file_sep>class CreateBitstream < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `bitstream` (
`bitstream_id` int(11) NOT NULL,
`bitstream_format_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`size_bytes` int(11) NOT NULL,
`checksum` varchar(255) NOT NULL,
`checksum_algorithm` varchar(255) NOT NULL,
`description` varchar(255),
`user_format_description` varchar(255),
`source` varchar(255),
`internal_id` int(11) NOT NULL,
`deleted` varchar(255) NOT NULL DEFAULT 'f',
`store_number` int(11) NOT NULL,
`sequence_id` int(11) NOT NULL,
PRIMARY KEY (`bitstream_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
drop_table :bitstream
end
end
<file_sep>class DspaceTools
def self.version
open(File.join(File.dirname(__FILE__), '..', 'VERSION')).read.strip
end
def self.password_authorization(params)
return nil unless (params[:email] && params[:password])
Eperson.where(email: params[:email],
password: <PASSWORD>.<PASSWORD>(params[:password])).first
end
def self.api_key_authorization(params, path)
return nil unless (params[:api_key] && params[:api_digest])
api_key = ApiKey.where(:public_key => params[:api_key]).first
digest = api_key ?
Digest::SHA1.hexdigest(path + api_key.private_key)[0..7] :
'bad_digest'
success = api_key && digest == params[:api_digest]
success ? api_key.eperson : nil
end
def self.last_updated
last_date = `git log --date=short --pretty=format:"%ad" -1`
last_date =~ /fatal/ ? "" : "Code updated on #{last_date}"
end
end
<file_sep>class CreateCommunities2item < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `communities2item` (
`id` int(11) NOT NULL auto_increment,
`community_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
drop_table :communities2item
end
end
<file_sep>FG.define do
factory :community do
community_id nil
sequence(:name) {|n| "community%s" % n}
short_description 'short desc'
introductory_text 'intro_text'
logo_bitstream_id 1
copyright_text 'Copyright'
side_bar_text 'sidebar'
admin 1
end
factory :collection do
collection_id nil
sequence(:name) {|n| "collection%s" % n}
short_description 'short_desc'
introductory_text 'intro_text'
logo_bitstream_id 1
template_item_id 1
provenance_description 'provenance'
license 'MIT'
copyright_text 'Copyright'
side_bar_text 'sidebar'
workflow_step_1 'wf1'
workflow_step_2 'wf2'
submitter 1
admin 1
end
factory :item do
item_id nil
submitter_id 1
in_archive 't'
withdrawn 'f'
last_modified Time.now - 100000000
owning_collection 31
end
factory :bitstream do
bitstream_id nil
bitstream_format_id 1
sequence(:name) {|n| "bitstream%s" % n}
size_bytes 1
checksum 123
checksum_algorithm 'MD5'
description 'desc'
user_format_description 'user format desc'
source 'source'
internal_id [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9].shuffle.join('')[0..8]
deleted 'f'
store_number 1
sequence_id 1
end
factory :bitstreamformat do
bitstream_format_id nil
mimetype 'application/octet-stream'
short_description 'unknown'
description 'unknown mimetype'
support_level 1
internal 'f'
end
factory :resourcepolicy do
sequence(:policy_id)
resource_type_id 2
resource_id nil
action_id 0
eperson_id nil
epersongroup_id nil
start_date nil
end_date nil
end
end
<file_sep>class DspaceToolsUi < Sinatra::Base
get '/rest/users.:format' do
rest_request(params)
end
get '/rest/users/:id.:format' do
rest_request(params)
end
get '/rest/items.:format' do
rest_request(params)
end
get '/rest/items/:id.:format' do
rest_request(params)
end
get '/rest/collections.:format' do
rest_request(params)
end
get '/rest/collections/:id.:format' do
rest_request(params)
end
get '/rest/communities/:id.:format' do
rest_request(params)
end
get '/rest/communities.:format' do
rest_request(params)
end
get '/rest/harvest.:format' do
rest_request(params)
end
get '/rest/harvest/:id.:format' do
rest_request(params)
end
get '/rest/bitstream/:id.:format' do
rest_request(params)
end
get '/rest/bitstream/:id' do
rest_request(params)
end
get '/rest/updates/items.:format' do
rest_request(params)
end
get '/rest/handle/:num1/:num2.:format' do
params["handle"] = "%s/%s" % [params["num1"], params["num2"]]
handle = Handle.where(:handle => params["handle"]).first
path = handle ? handle.path : nil
if path
redirect(handle.fullpath(request.fullpath, request.path_info), 303)
else
not_found
end
end
# takes handles in the following format
# /handle.xml?handle=http://hdl.handle.net/123/123
get '/rest/handle.:format' do
handle = params[:handle] ? Handle.where(:handle => params["handle"].
gsub("http://hdl.handle.net/", '')).first : nil
path = handle ? handle.path : nil
if path
redirect(handle.fullpath(request.fullpath, request.path_info), 303)
else
not_found
end
end
get '/rest/authentication_test.:format' do
rest_request(params)
end
get '/bitstream/handle/:num1/:num2/:filename' do
path = request.fullpath
RestClient.get(DspaceTools::Conf.dspace_repo + path)
end
end
<file_sep>class CreateApiKeys < ActiveRecord::Migration
Sinatra::Base.set :database, "mysql2://root:@localhost/dspace_api"
def up
create_table :api_keys do |t|
t.integer :eperson_id
t.string :app_name
t.string :public_key
t.string :private_key
t.timestamps
end
add_index :api_keys, :eperson_id, :name => 'idx_api_keys_1'
add_index :api_keys, :public_key, :name => 'idx_api_keys_2', :unique => true
end
def down
drop table :api_keys
end
end
<file_sep>require_relative '../environment'
exit if Sinatra::Base.settings.environment != :test
class Seeder
attr :common_dir, :env_dir
def initialize
@db = ActiveRecord::Base.connection
@common_dir = File.join(File.dirname(__FILE__), 'seed')
@env_dir = File.join(common_dir, Sinatra::Base.settings.environment.to_s)
@path = nil
end
def walk_path(path)
@path = path
files = Dir.entries(path).map {|e| e.to_s}.select {|e| e.match /csv$/}
files.each do |file|
table = file.gsub(/\.csv/, '')
data = get_data(table, file)
@db.execute("truncate table %s" % table)
@db.execute("insert into %s values %s" % [table, data]) if data
end
end
private
def get_data(table, file)
columns = @db.select_values("show columns from %s" % table)
ca_index = columns.index("created_at")
ua_index = columns.index("updated_at")
csv_args = {:col_sep => "\t"}
data = CSV.open(File.join(@path, file), csv_args).map do |row|
res = get_row(row, ca_index, ua_index)
(columns.size - res.size).times { res << 'null' }
res.join(",")
end rescue []
data.empty? ? nil : "(%s)" % data.join("), (")
end
def get_row(row, ca_index, ua_index)
res = []
row.each_with_index do |field, index|
if [ca_index, ua_index].include? index
res << 'now()'
else
res << @db.quote(field)
end
end
res
end
end
s = Seeder.new
s.walk_path(s.env_dir)
<file_sep>require './application.rb'
set :run, false
configure(:production) do
puts 'prod'
FileUtils.mkdir_p 'log' unless File.exists?('log')
log = File.new("log/sinatra.log", "a+")
$stdout.reopen(log)
$stderr.reopen(log)
end
use ActiveRecord::ConnectionAdapters::ConnectionManagement
run DspaceToolsUi
<file_sep>require 'spec_helper'
describe 'api' do
before(:all) do
@api_string = '&api_key=jdoe_again&api_digest='
@admin_api_string = '&api_key=admin&api_digest='
end
it 'should be possible to authorize by username and password' do
get('/rest/authentication_test.xml?email=<EMAIL>&password=<PASSWORD>')
last_response.status.should == 200
last_response.body.match('John').should be_true
end
it 'should not authorize with wrong username and password' do
get('/rest/authentication_test.xml?email=<EMAIL>@' +
'<EMAIL>&password=<PASSWORD>')
last_response.status.should == 401
last_response.body.match('Not authorized').should be_true
end
it 'should be possible to authorize by api_key and api_digest' do
path = '/rest/authentication_test.xml'
# using 2nd private key for jdoe
get("%s?%s%s" % [path, @api_string, ApiKey.digest(path, 'abcdef')])
last_response.status.should == 200
last_response.body.match('John').should be_true
end
it 'should not authorize by wrong api_key and api_digest' do
path = '/rest/authentication_test.xml'
get("%s?%s%s" % [path, @api_string, ApiKey.digest(path, 'bad_private_key')])
last_response.status.should == 401
last_response.body.match('Not authorized').should be_true
end
it 'should return data for item which is publicly accessible' do
stub_request(:get, /.*items\/1702.*/).
to_return(open(File.join(HTTP_DIR, '/item1702.xml')))
url = '/rest/items/1702.xml'
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('/items/entityId').text.should == '1702'
end
it 'should not show restricted item without authorization' do
url = '/rest/items/1704.xml'
get(url)
last_response.status.should ==401
url = '/rest/items/1782.xml'
get(url)
last_response.status.should ==401
end
it 'should show not authorized for unexisting items too' do
stub_request(:get, /.*items\/9999.*/).
to_return(open(File.join(HTTP_DIR, '/404_item.xml')))
url = '/rest/items/9999.xml'
get(url)
last_response.status.should == 401
end
it 'should show return not found for admin' do
stub_request(:get, /.*items\/9999.*/).
to_return(open(File.join(HTTP_DIR, '/404_item.xml')))
path = '/rest/items/9999.xml'
url = "%s?%s%s" % [path, @admin_api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 404
end
it 'should show return server errors for admin' do
stub_request(:get, /.*items\/9999.*/).
to_return(open(File.join(HTTP_DIR, '/500.xml')))
path = '/rest/items/9999.xml'
url = "%s?%s%s" % [path, @admin_api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 500
end
it 'should show restricted item to authorized user' do
path = '/rest/items/1704.xml'
stub_request(:get, /.*items\/1704.*/).
to_return(open(File.join(HTTP_DIR, '/item1704.xml')))
url = "%s?%s%s" % [path, @api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('/items/entityId').text.should == '1704'
end
it 'should show restricted item to authorized group' do
path = '/rest/items/1782.xml'
stub_request(:get, /.*items\/1782.*/).
to_return(open(File.join(HTTP_DIR, '/item1782.xml')))
url = "%s?%s%s" % [path, @api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('/items/entityId').text.should == '1782'
end
it 'should show restricted item to admins' do
path = '/rest/items/1782.xml'
stub_request(:get, /.*items\/1782.*/).
to_return(open(File.join(HTTP_DIR, '/item1782.xml')))
url = "%s?%s%s" % [path, @admin_api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('/items/entityId').text.should == '1782'
end
it 'should filter restricted information from returned document' do
stub_request(:get, /.*items\/1702.*/).
to_return(open(File.join(HTTP_DIR, '/item1702.xml')))
url = '/rest/items/1702.xml'
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('/items/entityId').text.should == '1702'
doc.xpath('//communityentityid').select do |element|
element.xpath('id').text == '6'
end.should be_empty
doc.xpath('//communityentityid').select do |element|
element.xpath('id').text == '4'
end.should_not be_empty
end
it 'should not abort if authentication not submitted' do
stub_request(:get, /.*items\/1702.*/).
to_return(open(File.join(HTTP_DIR, '/item1702.xml')))
url = '/rest/items/1702.xml'
get(url)
last_response.status.should == 200
last_response.body.match('Not authorized').should be_false
end
it 'should abort if authentication is attempted and failed' do
stub_request(:get, /.*items\/1702.*/).
to_return(open(File.join(HTTP_DIR, '/item1702.xml')))
url = '/rest/items/1702.xml'
['email=abc&password=abc', 'email=abc', 'password=abc',
'api_key=abc&api_digest=abc', 'api_key=abc', 'api_digest=abc',
'email=abc&api_key=abc', 'something=abc&password=abc'
].each do |p|
get("%s?%s" % [url, p])
last_response.status.should == 401
last_response.body.match('Not authorized').should be_true
end
end
it 'should filter restricted information from bulk queries' do
stub_request(:get, /communities/).
to_return(open(File.join(HTTP_DIR, '/communities.xml')))
url = '/rest/communities.xml'
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('//communities').select do |element|
element.xpath('id').text == '6'
end.should be_empty
doc.xpath('//communities').select do |element|
element.xpath('id').text == '4'
end.should_not be_empty
end
it 'should show collection to its admin' do
stub_request(:get, %r|collections/31|).
to_return(open(File.join(HTTP_DIR, '/collection31.xml')))
path = '/rest/collections/31.xml'
url = "%s?%s%s" % [path, @api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('//entityId').text.should == '31'
end
it 'should not show collection to a registered but not authorized user' do
path = '/rest/collections/31.xml'
jane_api_string = '&api_key=&janedoe456api_digest='
url = "%s?%s%s" % [path, jane_api_string, ApiKey.digest(path, '678990')]
get(url)
last_response.status.should == 401
end
it 'should not filter restricted information for admins' do
stub_request(:get, /communities/).
to_return(open(File.join(HTTP_DIR, '/communities.xml')))
path = '/rest/communities.xml'
url = "%s?%s%s" % [path, @admin_api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('//communities').select do |element|
element.xpath('id').text == '6'
end.should_not be_empty
doc.xpath('//communities').select do |element|
element.xpath('id').text == '4'
end.should_not be_empty
end
it 'should allow access to a resource without explicit permissions\\
only to admin' do
stub_request(:get, %r|bitstream/4833|).
to_return(open(File.join(HTTP_DIR, '/bitstream4833.xml')))
path = '/rest/bitstream/4833.xml'
url = "%s?%s%s" % [path, @admin_api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('//entityId').text.should == '4833'
url = "%s?%s%s" % [path, @api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 401
end
it 'should be able to translate handles into underlying object for\\
restricted data' do
stub_request(:get, %r|.*items/1704.*|).
to_return(open(File.join(HTTP_DIR, '/item1704.xml')))
path = '/rest/handle.xml'
url = "%s?%s%s&handle=http://hdl.handle.net/10776/2740" %
[path, @api_string, ApiKey.digest(path, 'abcdef')]
get(url)
last_response.status.should == 303
follow_redirect!
last_response.status.should == 200
doc = Nokogiri.parse(last_response.body)
doc.xpath('//entityId').text.should == '1704'
end
it 'should restrict file from viewing if not authorized' do
path = '/rest/handle.xml'
url1 = "%s?handle=http://hdl.handle.net/10776/2740" % [path]
url2 = "%s?%s%s&handle=http://hdl.handle.net/10776/2740" %
[path, @api_string, ApiKey.digest(path, 'bad_digest')]
[url1, url2].each do |url|
get(url)
last_response.status.should == 303
follow_redirect!
last_response.status.should == 401
last_response.body.match('Not authorized').should be_true
end
end
it 'should get publicly available bitstream' do
stub(Bitstream).find do
Bitstream.new(bitstream_id: 4761,
bitstream_format_id: 18,
name: 'DSpace_logo.png',
size_bytes: 21000,
internal_id: '123456789123456789123456789',
)
end
stub.proxy(Bitstream).new do |obj|
fdir = File.dirname(__FILE__)
obj.path.match(%r|/12/34/56/123456789123456789123456789$|).should be_true
stub(obj).path { |p| File.join(fdir, 'files', 'DSpace_logo_png') }
end
path = '/rest/bitstream/4761'
get(path)
lr = last_response
lr.status.should == 200
end
it 'should not get unauthorized bitstream' do
path = '/rest/bitstream/4832'
get(path)
last_response.status.should == 401
last_response.body.match('Not authorized').should be_true
end
it 'should get authorized bitstream' do
stub(Bitstream).find do
Bitstream.new(bitstream_id: 4832,
bitstream_format_id: 18,
name: 'DSpace_logo.png',
size_bytes: 21000,
internal_id: '123456789123456789123456789',
)
end
stub.proxy(Bitstream).new do |obj|
fdir = File.dirname(__FILE__)
obj.path.match(%r|/12/34/56/123456789123456789123456789$|).should be_true
stub(obj).path { |p| File.join(fdir, 'files', 'DSpace_logo_png') }
end
path = '/rest/bitstream/4832'
url = "%s?%s%s" % [path, @admin_api_string, ApiKey.digest(path, 'abcdef')]
get(url)
lr = last_response
lr.status.should == 200
end
it 'should return updates for items' do
timestamps = Item.connection.execute("select last_modified from item
order by last_modified desc limit 5").
to_a.flatten.map { |i| i.to_s.gsub(' UTC','.123-00') }
timestamps.size.should == timestamps.uniq.size
ts = timestamps.last
path = '/rest/updates/items.xml'
params = "community=4×tamp=#{URI.escape(ts)}"
url = "%s?%s%s%s" % [path, params, @admin_api_string,
ApiKey.digest(path, 'abcdef')
]
get(url)
res = Nokogiri.parse(last_response.body)
res.xpath('//items').size.should == 3
url.gsub!('community=4', 'community=6')
get(url)
res = Nokogiri.parse(last_response.body)
res.xpath('//items').size.should == 2
end
it 'should return an error if updates have no authentication' do
path = '/rest/updates/items.xml'
params = "community=4×tamp=2010-10-10"
url = "%s?%s" % [path, params ]
get(url)
last_response.status.should == 401
last_response.body.match('Not authorized').should be_true
end
it 'updates items should return all updates if ts is missing' do
path = '/rest/updates/items.xml'
url = "%s?%s%s" % [path, @admin_api_string,
ApiKey.digest(path, 'abcdef')
]
get(url)
res = Nokogiri.parse(last_response.body)
res.xpath('//items').size.should > 1000
end
it 'should return updates from all communities if no community given' do
timestamps = Item.connection.execute("select last_modified from item
order by last_modified desc limit 5").
to_a.flatten.map { |i| i.to_s.gsub(' UTC','.123-00') }
timestamps.size.should == timestamps.uniq.size
ts = timestamps.last
path = '/rest/updates/items.xml'
params = "timestamp=#{URI.escape(ts)}"
url = "%s?%s%s%s" % [path, params, @admin_api_string,
ApiKey.digest(path, 'abcdef')
]
get(url)
res = Nokogiri.parse(last_response.body)
res.xpath('//items').size.should == 4
end
it 'should handle badly formed timestamps' do
ts = 'bad timestamp'
path = '/rest/updates/items.xml'
params = "timestamp=#{URI.escape(ts)}"
url = "%s?%s%s%s" % [path, params, @admin_api_string,
ApiKey.digest(path, 'abcdef')
]
get(url)
res = Nokogiri.parse(last_response.body)
res.xpath('//items').size.should == 0
end
it 'should handle badly formed communities' do
timestamps = Item.connection.execute("select last_modified from item
order by last_modified desc limit 5").
to_a.flatten.
map { |i| i.to_s.gsub(' UTC','.123-00') }
ts = timestamps.last
path = '/rest/updates/items.xml'
params = "community=bad_community×tamp=#{URI.escape(ts)}"
url = "%s?%s%s%s" % [path, params, @admin_api_string,
ApiKey.digest(path, 'abcdef')
]
get(url)
res = Nokogiri.parse(last_response.body)
res.xpath('//items').size.should == 0
end
end
<file_sep>class CreateSessions < ActiveRecord::Migration
Sinatra::Base.set :database, "mysql2://root:@localhost/dspace_api"
def up
create_table :sessions do |t|
t.text :session_id
t.text :data
end
add_index :sessions, :session_id, :length => {:session_id => 100}, :name => 'idx_sessions_1'
end
def down
drop table :sessions
end
end
<file_sep>class Numeric
def to_human
return '0' if self == 0
units = %w{B KB MB GB TB}
e = (Math.log(self)/Math.log(1024)).floor
s = "%.3f" % (to_f / 1024**e)
s.sub(/\.?0*$/, units[e])
end
end
<file_sep>#!/usr/bin/env ruby
require 'zen-grids'
require 'rack/timeout'
require 'sinatra'
require 'sinatra/base'
require 'sinatra/flash'
require 'sinatra/redirect_with_flash'
require_relative 'environment'
require_relative 'routes'
require_relative 'routes_api'
class DspaceToolsUi < Sinatra::Base
include RestApi
configure do
mime_type :csv, 'application/csv'
register Sinatra::Flash
helpers Sinatra::RedirectWithFlash
Compass.add_project_configuration(File.join(File.dirname(__FILE__),
'config',
'compass.config'))
# Compass.configuration do |config|
# config.project_path = File.join(File.dirname(__FILE__), 'public')
# end
use Rack::MethodOverride
use Rack::Timeout
Rack::Timeout.timeout = 9_000_000
use Rack::Session::Cookie, :secret => DspaceTools::Conf.session_secret
set :scss, Compass.sass_engine_options
end
helpers do
include Sinatra::RedirectWithFlash
include Rack::Utils
alias_method :h, :escape_html
def get_dir_structure(dir)
res = []
Dir.entries(dir).each do |e|
if e.match /^[\d]{4}/
res << [e, get_dir_content(File.join(dir, e))]
end
end
res
end
def api_keys
@api_keys ||= ApiKey.where(eperson_id: session[:current_user_id])
end
def shorten(a_string, chars_num)
a_string.gsub!(/\s+/, ' ')
res = a_string[0..chars_num]
if res != a_string
res.gsub!(/\s[^\s]+$/, '...')
end
res
end
def api_url(resource, api_key, url_params = nil)
path = "/rest/%s.xml" % resource
params_str = '?'
if api_key
params_str += 'api_key='
params_str += "%s&api_digest=" % api_key.public_key
params_str += api_key.digest(path)
end
params_str += "&%s" % url_params if url_params
res = path
res += params_str unless params_str == '?'
res.gsub(%r|[/]+|, '/').gsub(/[&]+/, '&').gsub('?&', '?')
end
private
def get_dir_content(dir)
res = []
Dir.entries(dir).each do |e|
next if e.match /^[\.]{1,2}$/
res << [e, '']
if ['contents', 'dublin_core.xml'].include?(e)
res[-1][1] = open(File.join(dir, e), 'r:utf-8').read
end
end
res
end
end
end
run DspaceToolsUi.new if DspaceToolsUi.app_file == $0
<file_sep>class DspaceTools
class Uploader
attr_reader :params, :path, :incoming_path, :dir
def self.clean(days = 1)
tmp_dir = DspaceTools::Conf.tmp_dir
threshold = 86400 * days
now = Time.now.to_i
dirs = Dir.entries(tmp_dir)
dirs.select { |e| e.match /^dspace_[\d]{10}/ }.each do |dir|
path = File.join(tmp_dir, dir)
FileUtils.rm_rf(path) if (now - File.ctime(path).to_i) > threshold
end
end
def initialize(params)
error = DspaceTools::UploadError
@params = params
err_string = 'Collection is not selected'
raise(error.new(err_string)) if params[:collection_id].to_i == 0
@incoming_dir = @params[:dir] ||
raise(error.new('Directory is not selected'))
@incoming_path = File.join(DspaceTools::Conf.dropbox_dir, @incoming_dir)
@dir = get_dir
end
private
def get_dir
res = nil
until res
res = "dspace_%010d" % rand(9999999999)
@path = File.join(DspaceTools::Conf.tmp_dir, res)
@path = res = nil if File.exists?(@path)
end
res
end
end
end
<file_sep>class CreateItem < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `item` (
`item_id` int(11) NOT NULL,
`submitter_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`in_archive` varchar(255) NOT NULL DEFAULT 't',
`withdrawn` varchar(255) NOT NULL DEFAULT 'f',
`last_modified` datetime,
`owning_collection` int(11) NOT NULL,
PRIMARY KEY (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
drop_table :item
end
end
<file_sep>class CreateBitstreamFormat < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `bitstreamformatregistry` (
`bitstream_format_id` int(11) NOT NULL,
`mimetype` varchar(255) NOT NULL,
`short_description` varchar(128),
`description` text,
`support_level` int(11) default 1,
`internal` varchar(255),
PRIMARY KEY (`bitstream_format_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
drop_table :bitstreamformatregistry
end
end
<file_sep>class CreateCommunity < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `community` (
`community_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`short_description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`introductory_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`logo_bitstream_id` int(11),
`copyright_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`side_bar_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`admin` int(11) DEFAULT NULL,
PRIMARY KEY (`community_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
drop_table :community
end
end
<file_sep>class CreateHandle < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("
CREATE TABLE `handle` (
`handle_id` int(11) NOT NULL,
`handle` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`resource_type_id` int(11) NOT NULL,
`resource_id` int(11) NOT NULL,
PRIMARY KEY (`handle_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
")
add_index :handle, :handle, :unique => true
end
end
def down
drop_table :handle
end
end
<file_sep>class CreateCollection < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `collection` (
`collection_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`short_description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`introductory_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`logo_bitstream_id` int(11),
`template_item_id` int(11),
`provenance_description` varchar(255) COLLATE
utf8_unicode_ci DEFAULT NULL,
`license` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`copyright_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`side_bar_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`sidebar_text` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`workflow_step_1` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`workflow_step_2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`submitter` int(11) DEFAULT NULL,
`admin` int(11) DEFAULT NULL,
PRIMARY KEY (`collection_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
end
end
<file_sep>class DspaceTools
class Dropbox
attr_reader :dropbox_dir
def initialize
@dropbox_dir = Conf.dropbox_dir
end
def dirs
return @dirs if @dirs
@dirs = []
Dir.entries(@dropbox_dir).each do |e|
d_path = File.join(@dropbox_dir, e)
if dir?(d_path)
@dirs << OpenStruct.new(name: e, path: d_path, files: [])
Dir.entries(d_path).each do |f|
f_path = File.join(@dropbox_dir, @dirs.last.name, f)
@dirs.last.files << { name: f,
path: f_path,
size: File.size(f_path)
} if File.file?(f_path)
end
end
end
@dirs
end
private
def dir?(path)
File.directory?(path) && File.split(path).last.gsub('.', '') != ''
end
end
end
<file_sep>require "spec_helper"
describe DspaceTools::BulkUploader do
before(:all) do
u = DspaceTools::Uploader.new(PARAMS_1)
t = DspaceTools::Transformer.new(u)
user = Eperson.find(3)
@bu = DspaceTools::BulkUploader.new(t.path, 1, user)
end
it 'should initialize' do
@bu.class.should == DspaceTools::BulkUploader
end
it 'should have dspace command' do
@bu.dspace_command.class.should == String
@bu.dspace_command.should_not == ''
end
it 'should submit data with success' do
stub.proxy(@bu).dspace_command do |r|
mapfile = r.match(/-m ([^\s]*)/)[1].strip
r.match('2>&1').should be_true
"%s %s success" % [DSPACE_MOCK, mapfile]
end
mapfile = @bu.submit
open(File.join(DspaceTools::Conf.root_path,
'public', 'map_files', mapfile)).read.strip.should == '1 2'
end
it 'should give error if mapfile is empty' do
stub.proxy(@bu).dspace_command do |r|
mapfile = r.match(/-m ([^\s]*)/)[1].strip
"%s %s" % [DSPACE_MOCK, mapfile]
end
lambda { @bu.submit }.should raise_error
begin
@bu.submit
rescue DspaceTools::ImportError => e
e.message.match('DSpace upload failed: empty mapfile').should be_true
@bu.dspace_error.error.should == "upload failed with empty mapfile\n"
end
end
it 'should give show problem from ci failure' do
stub.proxy(@bu).dspace_command do |r|
"%s 2>&1" % DSPACE_MOCK
end
lambda { @bu.submit }.should raise_error
begin
@bu.submit
rescue RuntimeError => e
e.message.match('DSpace upload failed: empty mapfile').should be_true
@bu.dspace_error.error.match('(TypeError)').should be_true
end
end
end
<file_sep>class AnonymousGroup
end
class Bitstream < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'bitstream', primary_key: 'bitstream_id')
def self.resource_number
0
end
def self.find(id_num)
self.find_id(bitstream_id: id_num)
end
def path
ii = internal_id.to_s
File.join(DspaceTools::Conf.bitstream_path,
ii[0..1], ii[2..3], ii[4..5], ii)
end
def mime
bf = BitstreamFormat.find(bitstream_format_id)
bf.mimetype || 'application/octet-stream'
end
end
class BitstreamFormat < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'bitstreamformatregistry',
primary_key: 'bitstream_format_id')
def self.resource_number
nil
end
def self.find(id_num)
self.find_id(bitstream_format_id: id_num)
end
end
class Collection < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'collection', primary_key: 'collection_id')
has_many :collection_items,
class_name: 'CollectionItem', foreign_key: 'collection_id'
has_many :collections, through: :collection_items
def self.find(id_num)
self.find_id(:collection_id => id_num)
end
end
class CollectionItem < DspaceTools::DspaceDb::Base
self.table_name = 'collection2item'
belongs_to :collection,
class_name: 'Collection', foreign_key: 'collection_id'
belongs_to :item, class_name: 'Item', foreign_key: 'item_id'
end
class Community < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'community', primary_key: 'community_id')
has_many :community_items,
class_name: 'CommunityItem', foreign_key: 'community_id'
has_many :items, through: :community_items
def self.find(id_num)
self.find_id(community_id: id_num)
end
end
class CommunityItem < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'communities2item')
belongs_to :item, class_name: 'Item', foreign_key: 'item_id'
belongs_to :communities, class_name: 'Community', foreign_key: 'community_id'
end
class Eperson < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'eperson', primary_key: 'eperson_id')
has_many :eperson_groups, class_name: 'EpersonGroup'
has_many :groups, through: :eperson_groups
has_many :api_keys
has_many :dspace_errors
def self.find(id_num)
self.find_id(:eperson_id => id_num)
end
def admin?
!!groups.include?(Group.find(1))
end
private
def password; end
end
class EpersonGroup < DspaceTools::DspaceDb::Base
self.table_name = 'epersongroup2eperson'
belongs_to :group, class_name: 'Group', foreign_key: 'eperson_group_id'
belongs_to :eperson, class_name: 'Eperson', foreign_key: 'eperson_id'
end
class Group < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'epersongroup', primary_key: 'eperson_group_id')
has_many :eperson_groups,
class_name: 'EpersonGroup', foreign_key: 'eperson_group_id'
has_many :epersons, through: :eperson_groups
def self.find(id_num)
return AnonymousGroup.new if id_num == 0
self.find_id(eperson_group_id: id_num)
end
end
class Handle < DspaceTools::DspaceDb::Base
include Resource
self.table_params(table_name: 'handle', primary_key: 'handle_id')
def path
return nil unless resource_id
"/rest/%s%s" %
[DspaceTools::RESOURCE_TYPE[resource_type_id][:rest_path], resource_id]
end
def fullpath(original_fullpath, original_path)
format = original_path.split(".")[-1]
path_with_format = "%s.%s" % [path, format]
public_key_match = original_fullpath.match(/api_key=([^&]+)(&|$)/)
res = original_fullpath.gsub(original_path, path_with_format)
if public_key_match
ak = ApiKey.where(:public_key => public_key_match[1]).first
digest = res.match(/(api_digest=)([^&]+)(&|$)/)
if digest && ak.valid_digest?(digest[2], original_path)
res.gsub!(/(api_digest=)([^&])+(&|$)/,
'\1' + ak.digest(path_with_format) + '\3')
end
end
res
end
end
class Item < DspaceTools::DspaceDb::Base
self.table_params(table_name: 'item', primary_key: 'item_id')
has_many :collection_items,
class_name: 'CollectionItem', foreign_key: 'item_id'
has_many :community_items,
class_name: 'CommunityItem', foreign_key: 'item_id'
has_many :collections, through: :collection_items
has_many :communities, through: :community_items
def self.find(id_num)
self.find_id(:item_id => id_num)
end
def self.updates(timestamp, community=nil)
timestamp ||= '1900-01-01'
if community
Item.find_by_sql("
select distinct i.item_id, i.last_modified
from item as i
join communities2item ci
on i.item_id = ci.item_id
where ci.community_id = %s
and i.last_modified > %s order by i.last_modified" %
[community.to_i,
Item.connection.quote(timestamp)])
else
Item.select(:item_id, :last_modified).
where("last_modified > ?", timestamp).
order(:last_modified)
end
end
end
class Resourcepolicy < DspaceTools::DspaceDb::Base
include Resource
self.table_params(table_name: 'resourcepolicy', primary_key: 'policy_id')
def action
DspaceTools::ACTION[action_id]
end
def group
Group.find(epersongroup_id)
end
def eperson
Eperson.find(eperson_id)
end
end
<file_sep>require_relative '../spec_helper'
describe ApiKey do
it 'should instantiate' do
ak = ApiKey.where(eperson_id: 1).first
ak.class.should == ApiKey
end
it 'should be able to have more than one api key per eperson' do
aks = ApiKey.where(eperson_id: 1)
aks.size.should > 1
aks = ApiKey.where(eperson_id: 2)
aks.size.should == 1
end
it 'should be able to get digest as a class and instance methods' do
ApiKey.digest('onetwo', 'abcdef').should == '805d5daf'
ApiKey.where(eperson_id: 1)[1].digest('onetwo').should == '805d5daf'
end
it 'should generate public key' do
key = ApiKey.get_public_key
key.match(/[\h]{8}/).should_not be_nil
end
it 'should generate private key' do
key = ApiKey.get_private_key
key.match(/[\h]{16}/).should_not be_nil
end
end
describe Eperson do
it 'should instantiate' do
e = Eperson.where(email: '<EMAIL>').first
e.class.should == Eperson
e.firstname.should == 'John'
e.api_keys.size.should > 1
e.groups.size.should > 0
Eperson.resource_number.should == 7
end
it 'should have admin method' do
e = Eperson.where(email: '<EMAIL>').first
e.admin?.should == false
e = Eperson.where(email: '<EMAIL>').first
e.admin?.should be_true
end
end
describe Group do
it 'should have find method' do
g = Group.first
Group.find(g.eperson_group_id).should == g
end
it 'should have epsersons connected' do
g = Group.first
g.epersons[0].class.should == Eperson
g.epersons.size.should > 0
end
end
describe Handle do
it 'should not have a resource number' do
Handle.resource_number.should be_nil
end
it 'should instantiate' do
h = Handle.where(handle: '123/123').first
h.class.should == Handle
h.resource_type.should == Item
h.resource.should == Item.find(1)
h.path.should == '/rest/items/1'
end
it 'should modify path' do
h = Handle.where(handle: '123/123').first
original_fullpath = 'http://example.org/rest/handle.xml' +
'?handle=http://hdl.handle.net/123/123' +
'&api_key=jdoe_again&api_digest=8a5dabc2'
original_path = '/rest/handle.xml'
new_path = h.fullpath(original_fullpath, original_path)
new_path.should == 'http://example.org/rest/items/1.xml' +
'?handle=http://hdl.handle.net/123/123' +
'&api_key=jdoe_again&api_digest=bf0f9de3'
original_fullpath = 'http://example.org/rest/handle.xml' +
'?handle=http://hdl.handle.net/123/123&api_key=jdoe_again' +
'&api_digest=8a5dabc2&some_param=2'
original_path = '/rest/handle.xml'
new_path = h.fullpath(original_fullpath, original_path)
new_path.should == 'http://example.org/rest/items/1.xml' +
'?handle=http://hdl.handle.net/123/123&api_key=jdoe_again' +
'&api_digest=bf0f9de3&some_param=2'
end
end
describe Bitstream do
it 'should have 0 resource number' do
Bitstream.resource_number.should == 0
end
it 'should have find method' do
b = Bitstream.first
Bitstream.find(b.bitstream_id).should == b
end
it 'should have path' do
b = Bitstream.first
b.path.match(%r|^/tmp/\d\d/\d\d/\d\d/[\d]*$|).should be_true
end
it 'should have mime type' do
b = Bitstream.first
b.mime.should == 'application/octet-stream'
end
end
describe BitstreamFormat do
it 'should not have resource number' do
BitstreamFormat.resource_number.should be_nil
end
it 'should find it' do
bf = BitstreamFormat.first
BitstreamFormat.find(bf.bitstream_format_id).should == bf
end
end
describe Collection do
it 'should have find method' do
c = Collection.first
Collection.find(c.collection_id).should == c
end
end
describe Community do
it 'should have find method' do
c = Community.first
Community.find(c.community_id).should == c
end
end
describe CommunityItem do
it 'should connect items and communities' do
Community.find(6).items.size.should > 1
item = Community.find(6).items[0]
item.class.should == Item
item.communities.size.should > 0
end
end
describe Item do
it 'should have find method' do
item = Item.first
Item.find(item.item_id).should == item
end
it 'should find updates without timestamps or group' do
Item.updates(nil).size.should > 1000
Item.updates('bad_ts').size.should == 0
end
it 'should find updates with timestamp without group' do
ts = Item.all[-5].last_modified
Item.updates(ts).size.should == 4
end
it 'should not break with a wrong group' do
ts = Item.all[-5].last_modified
Item.updates(ts, 'huh').size.should == 0
end
it 'should return updates for a group' do
ts = Item.all[-5].last_modified
Item.updates(ts, 4).size.should == 3
end
end
describe Resourcepolicy do
it 'should have action, group, or epserson' do
r = Resourcepolicy.first
r.action.should == 'READ'
r.group.class.should == AnonymousGroup
r.eperson.should be_nil
r = Resourcepolicy.find(2)
r.eperson.class.should == Eperson
end
end
<file_sep>DspaceTools
===========
[![Continuous Integration Status][1]][2]
[![Dependency Status][3]][4]
[![Coverage Status][5]][6]
Description
-----------
DspaceTools app serves following purposes:
* It simplifies bulk upload to Dspace converting comma-separated lists of
terms into xml import files compatible with dspace.
* It adds authentication and authorization to Dspace restful API, hiding
restricted data from users who are not supposed to see it.
* It adds api_key/api_digest authentication mechanism to restful API
Requirements
------------
* Ruby v1.9.3 or higher
* Ruby Virtual Machine (rvm) is recommended for development
* Working DSpace with Postgresql in backend
* MySQL database
Running tests
-------------
Look at the content of [.travis.yml][7] in the project directory.
It is used by continuous integration server to create tests environment.
Install
-------
add ruby libraries needed for the project
gem install bundle
bundle
rake db:create:all
rake db:migrate #for development
rake db:migrate RACK_ENV=production #for production
rake db:migrate RACK_ENV=test #for test
to run it locally
rackup
to run in production specify production environment before your server
command. For example
RACK_ENV=production unicorn -c unicorn.conf -D
API description
---------------
[API][8]
[1]: https://secure.travis-ci.org/mbl-cli/DspaceTools.png
[2]: http://travis-ci.org/mbl-cli/DspaceTools
[3]: https://gemnasium.com/mbl-cli/DspaceTools.png
[4]: https://gemnasium.com/mbl-cli/DspaceTools
[5]: https://coveralls.io/repos/mbl-cli/DspaceTools/badge.png
[6]: https://coveralls.io/r/mbl-cli/DspaceTools
[7]: https://github.com/mbl-cli/DspaceTools/blob/master/.travis.yml
[8]: https://github.com/mbl-cli/DspaceTools/wiki/API
<file_sep>class DspaceTools::DspaceDb::Base
def self.resource_number
DspaceTools::RESOURCE_TYPE_IDS[self]
end
def self.find_id(hsh = {})
id = hsh.values[0].to_i
return nil unless id.is_a?(Fixnum) || id.to_s == hsh.values[0]
hsh.values[0] = id
self.where(hsh).first
end
def self.table_params(hsh)
self.table_name = hsh[:table_name] if hsh[:table_name]
self.primary_key = hsh[:primary_key] if hsh[:primary_key]
end
end
module Resource
def resource_type
DspaceTools::RESOURCE_TYPE[resource_type_id][:klass]
end
def resource
return nil unless resource_id
resource_type.find(resource_id)
end
end
<file_sep>class DspaceTools
class UploadError < RuntimeError; end
class CurrentUserError < RuntimeError; end
class CsvError < RuntimeError; end
class ImportError < RuntimeError; end
end
<file_sep>class CreateGroup < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("
CREATE TABLE `epersongroup` (
`eperson_group_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`eperson_group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
")
end
end
def down
drop_table :epersongroup
end
end
<file_sep>#!/usr/bin/env ruby
if ARGV[0] != ''
f = open(ARGV[0], 'w')
if ARGV[1] && ARGV[1].match('success')
f.write("1 2\n")
puts 'all worked fine'
else
puts 'upload failed with empty mapfile'
end
f.close
end
<file_sep>require "spec_helper"
describe DspaceTools::Uploader do
before(:all) do
DspaceTools::Uploader.clean(0)
end
it 'should initialize with a tmp directory' do
u = DspaceTools::Uploader.new(PARAMS_1)
u.incoming_path.match('upload').should be_true
u.dir.should ~ /dspace_[\d]{10}/
u.path.should ~ /tmp.*dspace/
end
end
<file_sep>module RestApi
def rest_request(params)
get_content_type(params)
@request_user = DspaceTools.api_key_authorization(params, request.path) ||
DspaceTools.password_authorization(params)
return bad_authentication if auth_requested?(params) && !@request_user
if request.path.match 'authentication_test'
authentication_worked(params['format']) || bad_authentication
else
handle_request
end
end
private
def auth_requested?(params)
params[:api_key] || params[:api_digest] ||
params[:email] || params[:password]
end
def handle_request
if params[:id] && params[:id].to_i.is_a?(Fixnum)
handle_single_request
else
handle_bulk_request
end
end
def handle_single_request
can_access_the_entity? ? perform_request : bad_authentication
end
def handle_bulk_request
if request.fullpath.match(%r|updates/items|)
perform_updates_request
else
perform_request
end
end
def can_access_the_entity?
resource_path = request.path.split('/')[2]
resource_number = DspaceTools::RESOURCE_TYPE_PATHS[resource_path]
auth = Resourcepolicy.where(resource_type_id: resource_number,
resource_id: params[:id])
entity_authorized?(auth)
end
def entity_authorized?(auth)
return true if @request_user && @request_user.admin?
permissions = auth.select do |r|
return true if DspaceTools::ACCESS_ACTIONS.include?(r.action_id) &&
(r.epersongroup_id && r.epersongroup_id == 0)
if @request_user
return true if DspaceTools::ACCESS_ACTIONS.include?(r.action_id) &&
(r.eperson_id && r.eperson_id == @request_user.eperson_id)
return true if DspaceTools::ACCESS_ACTIONS.include?(r.action_id) &&
(r.epersongroup_id && @request_user.groups.map(&:eperson_group_id).
include?(r.epersongroup_id))
end
end
false
end
def is_bitstream_file?
!params['format'] && request.fullpath.match('bitstream')
end
def bitstream_file
bts = Bitstream.find(params['id'])
headers(
'Content-Type' => bts.mime || 'application/octet-stream',
'Content-Length' => bts.size_bytes.to_s || '0',
'Content-Disposition' => "attachment; filename=\"#{bts.name}\"")
open(bts.path)
end
def perform_updates_request
if @request_user && @request_user.admin?
community = params[:community]
timestamp = params[:timestamp]
items = Item.updates(timestamp, community)
content_type 'text/xml', charset: 'utf-8'
items_to_xml(items)
else
bad_authentication
end
end
def items_to_xml(items)
builder = Nokogiri::XML::Builder.new do |xml|
xml.items_collection {
xml.count items.size
items.each do |item|
xml.items {
xml.id_ item.item_id
xml.entityReference "/items/%s" % item.item_id
xml.last_modified item.last_modified
xml.entityId item.item_id
}
end
}
end
builder.to_xml
end
def perform_request
return bitstream_file if is_bitstream_file?
begin
response = RestClient.get(DspaceTools::Conf.dspace_repo +
request.fullpath)
filter_response(response)
rescue RestClient::Exception => e
code = e.message.to_i
if code != 0
throw(:halt, [e.message.to_i, e.message])
else
throw(:halt, [500, 'Server problem'])
end
end
end
def filter_response(response)
return response if @request_user && @request_user.admin?
@doc = Nokogiri.parse(response.body)
[['//communities', Community],
['//communityentityid', Community], ['//collections', Collection],
['//collectionentityid', Collection], ['//items', Item],
['//itementityid', Item],
['//bitstream', Bitstream], ['//bitstreamentity', Bitstream],
['//bitstreamentityid', Bitstream]].
each { |path, klass| filter(path, klass) }
@doc.to_xml
end
def filter(an_xpath, klass)
entities = get_entities(an_xpath)
return if entities.empty?
permissions = Resourcepolicy.where("resource_type_id = %s
and action_id in (%s)
and (eperson_id is not null
or epersongroup_id is not null)
and resource_id in (%s)" %
[klass.resource_number,
DspaceTools::ACCESS_ACTIONS.join(','),
entities.keys.join(',')] )
process_permissions(permissions, entities)
remove_unauthorized_entities(entities)
end
def remove_unauthorized_entities(entities)
entities.each do |id, value|
if value[:remove]
value[:nodes].each {|node| node.remove}
end
end
end
def process_permissions(permissions, entities)
permissions.each do |r|
auth_group = auth_user = false
if r.epersongroup_id
auth_group = r.epersongroup_id == 0 ||
(@request_user &&
@request_user.groups.map(&:eperson_group_id).
include?(r.epersongroup_id))
end
if @request_user && r.eperson_id
auth_user = @request_user.id == r.eperson_id
end
entities[r.resource_id][:remove] = false if (auth_group || auth_user)
end
end
def get_entities(an_xpath)
@doc.xpath(an_xpath).inject({}) do |res, node|
id = node.xpath('id').text
id = node.xpath('entityId').text if id.empty?
unless id.empty?
id = id.to_i
res[id] ? res[id][:nodes] << node :
res[id] = { nodes: [node], remove: true }
end
res
end
end
def get_content_type(params)
if params['format'] == 'xml'
content_type 'text/xml', charset: 'utf-8'
elsif params['format'] == 'json'
content_type 'application/json', charset: 'utf-8'
else
content_type 'text/plain', charset: 'utf-8'
end
end
def authentication_worked(format)
return nil unless @request_user
if format == 'xml'
@request_user.to_xml
else
@request_user.to_json
end
end
def bad_authentication
throw(:halt, [401,
'Not authorized. ' +
'Did you submit correct email/password, ' +
'or API key/digest pair?'])
end
def not_found
throw(:halt, [404, "Unknown handle %s" % params['handle']])
end
end
<file_sep>class DspaceTools
class BulkUploader
attr :dspace_error
def initialize(path, collection_id, user)
@dspace_error = nil
@path = path
@collection_id = collection_id
@user = user
get_instance_vars
end
def submit
import_submission
copy_map_file_to_local
@map_file
end
def dspace_command
@dspace_command
end
private
def get_instance_vars
@map_file = Time.now().to_s[0..18].
gsub(/[\-\s]/,'_') + '_mapfile_' + @user.email.gsub(/[\.@]/, '_')
@map_path = File.join(DspaceTools::Conf.tmp_dir, @map_file)
@data = [DspaceTools::Conf.dspace_path,
@user.email,
@collection_id,
@path,
@map_path,]
@dspace_command =
"%s import ItemImport -w -a -e %s -c %s -s %s -m %s 2>&1" %
@data
@local_mapfile_path = File.join(DspaceTools::Conf.root_path,
'public',
'map_files')
end
def import_submission
begin
@dspace_output = `#{dspace_command}`
rescue RuntimeError => e
raise(DspaceTools::ImportError.new("DSpace upload failed: %s" %
e.message))
end
end
def copy_map_file_to_local
if File.exists?(@map_path) && open(@map_path).read.strip != ''
FileUtils.mv @map_path, @local_mapfile_path
else
@dspace_error = DspaceError.create!(eperson_id: @user.id,
collection_id: @collection_id,
error: @dspace_output)
raise(DspaceTools::ImportError.new(
'DSpace upload failed: empty mapfile'))
end
end
end
end
<file_sep>class CreateResourcepolicy < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("CREATE TABLE `resourcepolicy` (
`policy_id` int(11) NOT NULL,
`resource_type_id` int(11) NOT NULL,
`resource_id` int(11) NOT NULL,
`action_id` int(11) NOT NULL,
`eperson_id` int(11) DEFAULT NULL,
`epersongroup_id` int(11) DEFAULT NULL,
`start_date` datetime,
`end_date` datetime,
PRIMARY KEY (`policy_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci")
end
end
def down
drop_table :resourcepolicy
end
end
<file_sep>require 'sinatra'
require 'fileutils'
require 'bundler/setup'
require 'erb'
require 'haml'
require 'zen-grids'
require 'nokogiri'
require 'zip/zip'
require 'csv'
require 'active_record'
require 'rest-client'
require 'logger'
require 'redcloth'
class DspaceTools < Sinatra::Base
#set environment
environment = ENV['RACK_ENV'] || ENV['RAILS_ENV']
environment = (environment &&
['production', 'test', 'development'].include?(environment.downcase)) ?
environment.downcase.to_sym : :development
set :environment, environment
conf = open(File.join(File.dirname(__FILE__), 'config', 'config.yml')).read
conf_data = YAML.load(conf)
Conf = OpenStruct.new(
root_path: File.dirname(__FILE__),
tmp_dir: conf_data['tmp_dir'],
dropbox_dir: conf_data['dropbox_dir'],
bitstream_path: conf_data['bitstream_path'],
session_secret: conf_data['session_secret'],
dspace_repo: conf_data['dspace_repo'],
dspace_path: conf_data['dspace_path'],
dspacedb: conf_data['dspacedb'][settings.environment.to_s],
localdb: conf_data['localdb'][settings.environment.to_s],
valid_fields: YAML.load(open(File.join(File.dirname(__FILE__),
'config', 'valid_fields.yml')).
read).map { |f| f.strip },
)
##### Connect Databases #########
ActiveRecord::Base.logger = Logger.new(STDOUT, :debug)
ActiveRecord::Base.establish_connection(Conf.localdb)
Thread.new do
loop do
sleep(60*30);
ActiveRecord::Base.verify_active_connections!
end
end.priority = -10
class DspaceDb
class Base < ActiveRecord::Base
self.abstract_class = true
end
end
DspaceDb::Base.logger = Logger.new(STDOUT, :debug)
DspaceDb::Base.establish_connection(Conf.dspacedb)
#################################
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'app'))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'app', 'models'))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'app', 'routes'))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'lib'))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), 'lib', 'dspace_tools'))
require 'base'
Dir.glob(File.join(File.dirname(__FILE__), 'app', '**', '*.rb')) do |app|
require File.basename(app, '.*')
end
Dir.glob(File.join(File.dirname(__FILE__), 'lib', '**', '*.rb')) do |lib|
require File.basename(lib, '.*')
end
<file_sep>class DspaceTools
class Transformer
VALID_HEADERS = DspaceTools::Conf.valid_fields
RIGHTS_ARRAY = ['Rights', 'Rights Copyright', 'Rights License', 'Rights URI' ]
attr_reader :uploader, :path, :errors, :warnings
def initialize(uploader)
@errors = []
@warnings = []
@uploader = uploader
@path = File.join(@uploader.path, 'dspace')
@csv_data = parse_csv
check_integrity
transform if @errors.empty?
end
private
def check_integrity
success = has_required_fields && has_rights_field
if success
success = all_files_exist
find_extra_files
end
success
end
def all_files_exist
missing_files = files_list.select { |f| !File.exists?(File.join(@uploader.incoming_path, f)) }
if missing_files.empty?
true
else
@errors << "The following files are missed from archive: %s" % missing_files.join(", ")
false
end
end
def files_list
@csv_data.values_at("Filename").join("|").split("|")
end
def find_extra_files
known_files = files_list
known_files << @csv_file
dir_files = Dir.entries(@uploader.incoming_path).select { |f| f[0] != '.' }
extra_files = dir_files - known_files
@warnings << "The following files are extra in archive: %s" % extra_files.join(", ") unless extra_files.empty?
end
def has_required_fields
["filename", "title"].each do |field|
res = @csv_data.headers.select {|f| f.downcase == field}
if res.empty?
@errors << "No %s field in CSV file" % field.capitalize
elsif res.size > 1
@errors << "More than one %s fields" % field.capitalize
end
end
@errors.empty? ? true : false
end
def has_rights_field
res = @csv_data.headers.select { |f| RIGHTS_ARRAY.map { |f| f.downcase }.include? f.downcase }
if res.empty?
@errors << "One of these fields must me in archive: %s" % RIGHTS_ARRAY.join(", ")
false
else
true
end
end
def get_csv_file
csv_file = Dir.entries(@uploader.incoming_path).
select {|e| e.match(/\.csv$/)}[0]
raise DspaceTools::CsvError.new("Cannot find file with .csv extension") unless csv_file
csv_file
end
def parse_csv
@csv_file = get_csv_file
begin
csv_string = open(File.join(@uploader.incoming_path, @csv_file),
"r:utf-8").read
csv_string.encode!("UTF-8",
"ISO8859-1") unless csv_string.valid_encoding?
csv_string.gsub!(/\r\n?/, "\n")
options = { :col_sep => ",", :row_sep => "\n", :headers => true }
CSV.parse(csv_string, options)
rescue CSV::MalformedCSVError
raise DspaceTools::CsvError.new("Cannot parse CSV file")
end
end
def transform
count = -1
@csv_data.each do |row|
count += 1
path = File.join(@path, "%04d" % count)
FileUtils.mkdir_p(path)
file = open(File.join(path, 'dublin_core.xml'), 'w:utf-8')
file.puts build_xml_string(row)
copy_files(row['Filename'], path) if row['Filename']
file.close
end
end
def build_xml_string(data)
Nokogiri::XML::Builder.new do |xml|
xml.dublin_core do
data.each do |header, value|
next if header == "Filename" || value.nil? || value.empty?
element, qualifier = header.strip.downcase.split
qualifier = "none" if qualifier.nil?
xml.dcvalue(:element => element, :qualifier => qualifier) do
xml.text value
end
end
end
end.to_xml
end
def copy_files(filenames, path)
contents = open(File.join(path, "contents"), "w:utf-8")
filenames.split("|").each do |f|
FileUtils.cp(File.join(@uploader.incoming_path, f), path)
contents.write("%s\tbundle:ORIGINAL\n" % f)
end
contents.close
end
end
end
<file_sep>require "spec_helper"
describe DspaceTools::Transformer do
it 'should initialize with a new directory' do
u = DspaceTools::Uploader.new(PARAMS_1)
t = DspaceTools::Transformer.new(u)
t.path.should == File.join(u.path, 'dspace')
Dir.entries(t.path).include?('0000').should be_true
Dir.entries(t.path).include?('0001').should be_true
Dir.entries(t.path).include?('0002').should be_true
Dir.entries(File.join(t.path, '0000')).sort.should == [".", "..", "contents", "dublin_core.xml", "embryo128386.xhtml"]
end
end
<file_sep>class CreateDspaceErrors < ActiveRecord::Migration
Sinatra::Base.set :database, "mysql2://root:@localhost/dspace_api"
def up
create_table :dspace_errors do |t|
t.integer :eperson_id
t.integer :collection_id
t.text :error
t.timestamps
end
end
def down
drop table :dspace_errors
end
end
<file_sep>class DspaceToolsUi < Sinatra::Base
def user_collections(usr)
res = nil
if usr.admin?
res = Collection.all
else
atype = DspaceTools::ACTION_TYPE
groups = usr.groups.map(&:id).join(',')
write_actions = [atype['WRITE'],
atype['ADD'],
atype['ADMIN']].join(',')
q = "resource_type_id = %s
and (eperson_id = %s or epersongroup_id in (%s))
and action_id in (%s)"
q_params = [Collection.resource_number,
usr.id,
groups,
write_actions]
res = Resourcepolicy.select(:resource_id).
where(q % q_params).
map { |r| Collection.find(r.resource_id) }
end
res.sort_by(&:name)
end
def current_user
usr_id = session[:current_user_id]
@current_user ||= (usr_id ? Eperson.find(usr_id) : nil)
end
before %r@^(?!/(login|logout|css|rest|bitstream|favicon))@ do
session[:previous_location] = request.fullpath
redirect '/login' unless session[:current_user_id] &&
session[:current_user_id].to_i > 0
end
get '/css/:filename.css' do
scss :"sass/#{params[:filename]}"
end
get '/' do
haml :index
end
get '/login' do
haml :login
end
post '/login' do
eperson = DspaceTools.password_authorization(email: params[:email],
password: params[:password])
session[:current_user_id] = eperson.id if eperson
redirect session[:previous_location] || '/'
end
get '/logout' do
session[:current_user_id] = nil
redirect '/login'
end
get '/bulk_upload' do
usr = current_user
@collections = user_collections(usr)
@dropbox = DspaceTools::Dropbox.new
haml :bulk_upload
end
get '/formatting-rules' do
haml :rules
end
get 'template.csv' do
content_type :csv
send_file 'template.csv'
end
post '/upload' do
begin
DspaceTools::Uploader.clean(1)
u = DspaceTools::Uploader.new(params)
t = DspaceTools::Transformer.new(u)
if t.errors.empty?
session[:path] = t.path
session[:collection_id] = params['collection_id']
redirect '/upload_result', warning: t.warnings[0]
else
redirect '/bulk_upload', error: t.errors.join('<br/>')
end
rescue DspaceTools::CsvError => e
redirect '/bulk_upload', error: e.message
rescue DspaceTools::UploadError => e
redirect '/bulk_upload', error: e.message
end
end
post '/submit' do
begin
bu = DspaceTools::BulkUploader.new(session[:path],
session[:collection_id],
current_user)
@map_file = bu.submit
redirect '/upload_finished?map_file=' + ::URI.encode(@map_file)
rescue DspaceTools::ImportError => e
url = '/upload_result'
url += "?dspace_error_id=%s" % bu.dspace_error.id if bu.dspace_error
redirect url, error: e.message
end
end
get '/upload_result' do
haml :upload_result
end
get '/upload_finished' do
@map_file = params['map_file']
haml :upload_finished
end
get '/api_keys' do
haml :api_keys
end
post '/api_keys' do
ApiKey.create(eperson_id: session[:current_user_id],
app_name: params[:app_name],
public_key: ApiKey.get_public_key,
private_key: ApiKey.get_private_key)
redirect '/api_keys'
end
delete '/api_keys' do
key = ApiKey.where(public_key: params[:public_key]).first
key.destroy if key
redirect '/api_keys'
end
get '/api_examples' do
haml :api_examples
end
end
<file_sep>class ApiKey < ActiveRecord::Base
belongs_to :eperson
def self.digest(path, key)
Digest::SHA1.hexdigest(path.to_s + key.to_s)[0..7]
end
def self.get_public_key
key = 0
while true do
rand_max = 0xffffffff - 0x10000000
key = rand(rand_max).+(0x10000000).to_s(16)
break if ApiKey.where(:public_key => key).empty?
end
key
end
def self.get_private_key
rand_max = 0xffffffffffffffff - 0x1000000000000000
key = rand(rand_max).+(0x1000000000000000).to_s(16)
end
def digest(path)
ApiKey.digest(path, private_key)
end
def valid_digest?(a_digest, path)
digest(path) == a_digest
end
end
class DspaceError < ActiveRecord::Base
belongs_to :eperson
end
<file_sep>require 'spec_helper'
def credentials(username, password)
'Basic ' + Base64.encode64("#{username}:#{password}")
end
describe 'application.rb no login' do
it 'should return version number' do
DspaceTools.version.match(/[\d]+\.+[\d]+\.[\d]+/).should be_true
end
it 'should break on unknown user' do
get '/', {}, { 'HTTP_AUTHORIZATION' => credentials('unknown', 'bad_pass') }
last_response.redirect?.should be_true
follow_redirect!
last_response.successful?.should be_true
last_response.body.match('Email').should be_true
end
it 'should get login page' do
get('/login')
last_response.status.should == 200
last_response.body.match(/Email/).should be_true
end
end
describe 'application.rb with login' do
before(:each) do
post('/login', email: '<EMAIL>', password: '<PASSWORD>')
end
it 'should show the default index page' do
get '/'
last_response.status.should == 200
last_response.body.should include('Welcome')
end
it 'should upload file and show generated content' do
post('/upload', { dir: 'upload',
collection_id: 42 })
follow_redirect!
files_warning = 'Check the correctness of generated files'
last_response.body.should include(files_warning)
end
it 'should encode latin1 uploaded file to UTF-8' do
post('/upload', {
dir: 'upload_latin1',
collection_id: 42 })
follow_redirect!
files_warning = 'Check the correctness of generated files'
last_response.body.should include(files_warning)
end
it 'should generate error if there is no collection id' do
post('/upload', {
dir: 'upload',
collection_id: 0 })
follow_redirect!
files_warning = 'Check the correctness of generated files'
collection_warning = 'Collection is not selected'
last_response.body.should_not include(files_warning)
last_response.body.should include(collection_warning)
end
it 'should generate error if uploaded archive does not contain csv file' do
post('/upload', {
dir: 'no_csv',
collection_id: 42 })
follow_redirect!
files_warning = 'Check the correctness of generated files'
last_response.body.should_not include(files_warning)
last_response.body.should include('Cannot find file with .csv extension')
end
it 'should generate error if uploaded archive has invalid csv file' do
post('/upload', {
dir: 'bad_csv',
collection_id: 42 })
follow_redirect!
files_warning = 'Check the correctness of generated files'
last_response.body.should_not include(files_warning)
last_response.body.should include('Cannot parse CSV file')
end
it 'should generate error if uploaded archive is missing a Filename field' do
post('/upload', {
dir: 'typo_in_filename_field',
collection_id: 42 })
follow_redirect!
last_response.body.
should_not include('Check the correctness of generated files')
last_response.body.should include('No Filename field')
end
it 'should generate error if uploaded archive had more ' +
'than one Filename field' do
post('/upload', {
dir: 'two_filename_fields',
collection_id: 42 })
follow_redirect!
last_response.body.should_not
include('Check the correctness of generated files')
last_response.body.should include('More than one Filename fields')
end
it 'should generate error if a file is not found in archive' do
post('/upload', {
dir: 'missed_file',
collection_id: 42})
follow_redirect!
last_response.body.should_not
include('Check the correctness of generated files')
last_response.body.should
include('The following files are missed from archive: missed_file.xhtml')
end
it 'should generate a warning if there is an extra file in archive' do
post('/upload', {
dir: 'extra_file',
collection_id: 42 })
follow_redirect!
last_response.body.should
include('Check the correctness of generated files')
last_response.body.should
include('The following files are extra in archive: extra_file.xhtml')
end
it 'should generate an error if there is no title field' do
post('/upload', {
dir: 'no_title_field',
collection_id: 42 })
follow_redirect!
last_response.body.should_not
include('Check the correctness of generated files')
last_response.body.should include('No Title field')
end
it 'should generate an error if there is no rights field' do
post('/upload', {
dir: 'no_rights_field',
collection_id: 42 })
follow_redirect!
last_response.body.should_not
include('Check the correctness of generated files')
last_response.body.should
include('One of these fields must me in archive: Rights, ')
end
it 'should finish upload to dspace' do
u = DspaceTools::Uploader.new(PARAMS_1)
t = DspaceTools::Transformer.new(u)
session = {
current_user_id: 3,
collection_id: 42,
path: t.path,
}
stub.proxy(DspaceTools::BulkUploader).new do |obj|
stub.proxy(obj).dspace_command do |r|
mapfile = r.match(/-m ([^\\s]*)/)[1].strip
"%s %s %s" % [DSPACE_MOCK, mapfile, 'success']
end
end
post '/submit', {}, 'rack.session' => session
follow_redirect!
last_response.body.should include('Upload was successful')
end
it 'should not finish upload if mapfile is empty' do
u = DspaceTools::Uploader.new(PARAMS_1)
t = DspaceTools::Transformer.new(u)
session = {
current_user_id: 3,
collection_id: 42,
path: t.path,
}
stub.proxy(DspaceTools::BulkUploader).new do |obj|
stub.proxy(obj).dspace_command do |r|
mapfile = r.match(/-m ([^\\s]*)/)[1].strip
"%s %s" % [DSPACE_MOCK, mapfile]
end
end
post '/submit', {}, 'rack.session' => session
follow_redirect!
last_response.body.should_not include('Upload was successful')
last_response.body.should include('upload failed with empty mapfile')
end
it 'should not finish upload if dspace ci crashes' do
u = DspaceTools::Uploader.new(PARAMS_1)
t = DspaceTools::Transformer.new(u)
session = {
current_user_id: 3,
collection_id: 42,
path: t.path,
}
stub.proxy(DspaceTools::BulkUploader).new do |obj|
stub.proxy(obj).dspace_command do |r|
raise('CRASH!!')
end
end
post '/submit', {}, 'rack.session' => session
follow_redirect!
last_response.body.should_not include('Upload was successful')
last_response.body.should include('CRASH!!')
end
it 'should show api key page' do
get('/api_keys')
last_response.status.should == 200
last_response.body.match(/abcdef/).should be_true
end
it 'should create and delete api key' do
ApiKey.all.each {|a| a.destroy if a.app_name == 'new_app'}
keys_num = ApiKey.count
authorize '<EMAIL>', 'secret'
post('/api_keys', :app_name => 'new_app')
last_response.status.should == 302
follow_redirect!
last_response.status.should == 200
last_response.body.match(/new_app/).should be_true
(ApiKey.count - keys_num).should == 1
delete('/api_keys', :public_key => ApiKey.last.public_key)
last_response.status.should == 302
follow_redirect!
last_response.status.should == 200
last_response.body.match(/new_app/).should be_false
(ApiKey.count - keys_num).should == 0
end
it 'should logout a user' do
get('/')
last_response.body.match(/Doe/).should be_true
get('/logout')
last_response.redirect?.should be_true
follow_redirect!
last_response.successful?.should be_true
last_response.body.match(/Doe/).should be_false
last_response.body.match("Email").should be_true
end
end
<file_sep>require 'coveralls'
Coveralls.wear!
ENV["RACK_ENV"] = 'test'
require "rack/test"
require "webmock/rspec"
require "base64"
require "factory_girl"
require_relative "../application.rb"
module RSpecMixin
include Rack::Test::Methods
def app() DspaceToolsUi end
end
RSpec.configure do |c|
c.include RSpecMixin
c.mock_with :rr
end
unless defined?(SPEC_CONSTANTS)
DspaceTools::Conf.dropbox_dir = File.join(File.dirname(__FILE__), 'files')
FG = FactoryGirl
HTTP_DIR = File.join(File.dirname(__FILE__), "http")
PARAMS_1 = { dir: 'upload', collection_id: 42 }
SPEC_CONSTANTS = true
DSPACE_MOCK = File.join(File.dirname(__FILE__), 'bin', 'dspace_mock')
end
#FG.find_definitions
<file_sep>source 'https://rubygems.org'
gem 'rake', '~> 10.1'
gem 'sinatra', '~> 1.4'
gem 'sinatra-flash', '~> 0.3'
gem 'sinatra-redirect-with-flash', '~> 0.2'
gem 'sinatra-reloader', '~> 1.0'
gem 'sinatra-basic-auth', '~> 0.1'
gem 'sinatra-activerecord', '~> 1.2'
gem 'haml', '~> 4.0'
gem 'nokogiri', '~> 1.6'
gem 'rubyzip', '~> 0.9'
gem 'rack', '~> 1.5'
gem 'rack-test', '~> 0.6'
gem 'rack-timeout', '~> 0.0.4'
gem 'pg', '~> 0.16'
gem 'mysql2', '~> 0.3'
gem 'rest-client', '~> 1.6'
gem 'compass', '~> 0.12'
gem 'sass', '~> 3.2'
gem 'zen-grids', '~> 1.4'
gem 'RedCloth', '~> 4.2'
group :development do
gem 'debugger', '~> 1.6'
gem 'rerun', '~> 0.8'
gem 'rb-fsevent', '~> 0.9'
end
group :production do
gem 'unicorn', '~> 4.6'
end
group :test do
gem 'rspec', '~> 2.14'
gem 'rr', '~> 1.1'
gem 'webmock', '~> 1.13'
gem 'factory_girl', '~> 4.2'
gem 'coveralls', require: false
end
<file_sep>require_relative '../environment'
require_relative '../spec/spec_helper'
require_relative 'seeds'
exit if settings.environment != :test
FG.find_definitions
class HttpSeeder
HTTP_DIR = File.join(File.dirname(__FILE__), '..', 'spec', 'http')
def walk_xml
communities = {}
collections = {}
items = {}
bitstreams = {}
Dir.entries(HTTP_DIR).each do |file|
if file[-4..-1] == '.xml'
xml_text = open(File.join(HTTP_DIR, file)).
read.gsub(/.*(<\?xml)/m, '\1')
@doc = Nokogiri.parse(xml_text)
[
['//communityentityid', communities],
['//collectionentityid', collections],
['//itementityid', items],
['//bitstreamentityid', bitstreams]
].each {|i| collect_data(*i)}
end
end
[
[communities, :community, :community_id],
[collections, :collection, :collection_id],
[items, :item, :item_id],
[bitstreams, :bitstream, :bitstream_id],
].each {|data| create_records(*data)}
end
def make_fake_policies
FG.create(:resourcepolicy,
:resource_type_id => Community.resource_number,
:resource_id => 4, :epersongroup_id => 0)
FG.create(:resourcepolicy,
:resource_type_id => Community.resource_number,
:resource_id => 6, :eperson_id => 1)
FG.create(:resourcepolicy,
:resource_type_id => Collection.resource_number,
:resource_id => 6, :epersongroup_id => 0)
FG.create(:resourcepolicy,
:resource_type_id => Collection.resource_number,
:resource_id => 7, :eperson_id => 1, :epersongroup_id => nil)
FG.create(:resourcepolicy,
:resource_type_id => Collection.resource_number,
:action_id => 11, :resource_id => 31, :epersongroup_id => 2)
FG.create(:resourcepolicy,
:resource_type_id => Item.resource_number,
:resource_id => 1702, :epersongroup_id => 0)
FG.create(:resourcepolicy,
:resource_type_id => Item.resource_number,
:resource_id => 1704, :eperson_id => 1, :epersongroup_id => nil)
FG.create(:resourcepolicy,
:resource_type_id => Item.resource_number,
:resource_id => 1782, :epersongroup_id => 2)
FG.create(:resourcepolicy,
:resource_type_id => Bitstream.resource_number,
:resource_id => 4761, :epersongroup_id => 0)
FG.create(:resourcepolicy,
:resource_type_id => Bitstream.resource_number,
:resource_id => 4762, :epersongroup_id => 1)
FG.create(:resourcepolicy,
:resource_type_id => Bitstream.resource_number,
:resource_id => 4832, :eperson_id => 1)
end
def change_items_last_modified
Item.all[-5..-1].reverse.each_with_index do |item, i|
item.last_modified = Time.now - (i * 1000)
item.save!
end
end
def make_community_item
Item.all[-4..-2].each do |item|
c = Community.find(4)
CommunityItem.create(item_id: item.item_id,
community_id: c.community_id)
end
Item.all[-2..-1].each do |item|
c = Community.find(6)
CommunityItem.create(item_id: item.item_id,
community_id: c.community_id)
end
end
private
def collect_data(an_xpath, a_hash)
@doc.xpath(an_xpath).each do |node|
a_hash[node.xpath('id').text.to_i] = 1
end
end
def create_records(a_hash, a_type, id_name)
a_hash.keys.each do |i|
FG.create(a_type, id_name => i)
end
end
end
hs = HttpSeeder.new
hs.walk_xml
hs.make_fake_policies
hs.change_items_last_modified
hs.make_community_item
<file_sep>class DspaceTools
#TODO: remove these!
class Bitstream; end
class Bundle; end
class Site; end
# lets you look up type names from the type IDs
RESOURCE_TYPE = {
0 => { rest_path: "bitstream/", klass: Bitstream },
1 => { rest_path: nil },
2 => { rest_path: "items/", klass: Item },
3 => { rest_path: "collections/", klass: Collection },
4 => { rest_path: "communities/", klass: Community},
5 => { rest_path: nil },
6 => { rest_path: "groups/", klass: Group },
7 => { rest_path: "users/", klass: Eperson }
}
RESOURCE_TYPE_IDS = RESOURCE_TYPE.select{|key, value| value[:rest_path]}.inject({}) {|res, rt| res[rt[1][:klass]] = rt[0]; res}
RESOURCE_TYPE_PATHS= RESOURCE_TYPE.select{|key, value| value[:rest_path]}.inject({}) {|res, rt| res[rt[1][:rest_path][0..-2]] = rt[0]; res}
ACTION = [ "READ", "WRITE",
"OBSOLETE (DELETE)", "ADD", "REMOVE", "WORKFLOW_STEP_1",
"WORKFLOW_STEP_2", "WORKFLOW_STEP_3", "WORKFLOW_ABORT",
"DEFAULT_BITSTREAM_READ", "DEFAULT_ITEM_READ", "ADMIN" ]
ACTION_TYPE = ACTION.inject({}) { |res, type| res[type] = res.size; res }
ACCESS_ACTIONS = [ ACTION_TYPE["READ"], ACTION_TYPE["ADMIN"] ]
end
<file_sep>class CreateEperson < ActiveRecord::Migration
def up
if Sinatra::Base.settings.environment == :test
execute("
CREATE TABLE `eperson` (
`eperson_id` int(11) NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`firstname` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`lastname` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`can_log_in` tinyint default 1,
`require_certificate` tinyint default 0,
`self_registered` tinyint default 1,
`last_active` datetime,
`sub_frequency` int(11),
`phone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`language` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`eperson_id`),
UNIQUE KEY `idx_api_keys_2` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
")
end
end
def down
drop_table :eperson
end
end
|
8bbadd7f0cf639231b46311d77303a905fee362b
|
[
"Markdown",
"Ruby"
] | 43
|
Ruby
|
dimus/DspaceTools
|
7a5871985b44323637144cf327354676970872cf
|
777236f25f59eecbc160cb1f2c9dcf09f1776785
|
refs/heads/master
|
<repo_name>NicolasMarino/Dolar-API-Uruguay<file_sep>/README.md
# node-projects
<file_sep>/database/db.sql
CREATE DATABASE linksapp;
USE linksapp;
-- USERS TABLE
CREATE TABLE users(
id INT(11) NOT NULL,
username VARCHAR(16) NOT NULL,
password VARCHAR(60) NOT NULL,
fullname VARCHAR(100) NOT NULL
);
ALTER TABLE users
ADD PRIMARY KEY (id);
ALTER TABLE users
MODIFY id INT(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
DESCRIBE users;
-- LINKS TABLE
CREATE TABLE links (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(150) NOT NULL,
url VARCHAR(255) NOT NULL,
description TEXT,
user_id INT(11),
created_at timestamp NOT NULL DEFAULT current_timestamp,
CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id)
);
ALTER TABLE links
ADD COLUMN is_private BOOLEAN NOT NULL;
CREATE TABLE posts (
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(150) NOT NULL,
url VARCHAR(255) NOT NULL,
description TEXT,
contact VARCHAR(255) NOT NULL,
user_id INT(11),
created_at timestamp NOT NULL DEFAULT current_timestamp,
CONSTRAINT fk_user FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE datos_api(
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
datos MEDIUMTEXT
);
--OLD/ No funciona con update.
--ALTER TABLE datos_api
--ADD updated_at timestamp NOT NULL DEFAULT current_timestamp
-- funciona con update
ALTER TABLE datos_api CHANGE updated_at updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
|
4d46aed4a54c96537de25a1a8ef405c5d660bff7
|
[
"Markdown",
"SQL"
] | 2
|
Markdown
|
NicolasMarino/Dolar-API-Uruguay
|
f0d32655945f0e7f5dce7282ef4cb58d2f96fed7
|
01aa863c2a35ad6002b41f54b7a46ee20610959e
|
refs/heads/master
|
<file_sep>Dado("que acesso o site para realizar o desafio") do
@home.load
end
Quando("efetuado o clique no botões One, Two e Four") do
@home.click_btn
end
Quando("efetuado o clique no botões One, Two e Four dentro no Iframe") do
@home.scroll
@home.iframe_btn
end
Então("certifico que os botões não são mais visíveis") do
expect(page.has_button?("#btn_one")).to eq false
expect(page.has_button?("#btn_two")).to eq false
expect(page.has_button?("#btn_link")).to eq false
end
Quando("o campo nome é preechido") do
@home.name
end
Quando("efetuado o clique no botao One") do
click_button("One")
end
Quando("marcado o checkbox OptionThree") do
@home.checkbox
end
Quando("selecionado a opção ExampleTwo") do
@home.select_list
end
Entao("verifico a imagem do selenium no Iframe Image Asserts") do
expect(@home.img_visible).to have_css('img.img-responsive-center-block[alt="selenium"]')
end
<file_sep>Before do
@home = HomePage.new
end
After do
temp_shot = page.save_screenshot("log/screen.png")
screenshot = Base64.encode64(File.open(temp_shot).read)
embed(screenshot, "image/png", "Screenshot")
end
<file_sep># Test_webjup_Otavio
Teste - Automação QA
Configurando o Ambiente no Windows:
Obs.: Para ter uma melhor utilização de console, recomento a utilização do CMDER (https://cmder.net/ - Download full).
Caso opte pela utilização do mesmo deverá criar uma pasta no disco principal do sistema, (ex: tools) e adicionar está pasta ao path do sistema
Quando colocar no path inserir a variável de ambiente “C:\tools\cmder\vendor\git-for-windows\bin” e “C:\tools\cmder\vendor\git-for-windows\usr\bin”
1 - Instale o Ruby no Windows / Devkit
- Baixe em: http://rubyinstaller.org/downloads/.
- Baixar a opção Ruby + Devkit
- Executar o arquivo baixado e seguir as instruções clicando em ‘next’ (Seguir com a instalação padrão)
- No Console, digite o comando ruby –v, der tudo certo você vai ver a versão instalada.
Para prosseguir com a instalação do Devkit, no terminal digite o comando ridk install e utilizar a opção 3
3 - Instalando o Bundler
- No prompt de comando digite:
- gem install bundler
4 - Instalando Geckodriver
- Baixe em: https://github.com/mozilla/geckodriver/releases
- Descompacte o arquivo dentro de uma pasta path do sistema (Utilizo a pasta Windows)
5 - Instalando ChromeDriver
- Baixe em: https://chromedriver.storage.googleapis.com/index.html, baixar a versão 78.0.3904.70
- Descompacte o arquivo dentro de uma pasta path do sistema (Utilizo a pasta Windows)
Rodando a Automação:
1 - Faça o clone do repositorio no Git:
- git clone <url_do_reporitorio>
2 - Instale as dependencias do projeto com o comando:
- bundle init
3 - Por padrão a automação irá rodar em cima do browser Firefox, para rodar os testes digite o comando:
- cucumber
4 - Mas se desejar rodar a automação usando o Chrome. Digite o comando:
- cucumber -p chrome
5 – Para acessar os relatórios da execução acesse a pasta log o qual contém o arquivo report.html
<file_sep>class HomePage
include Capybara::DSL
def load
visit "/"
end
def click_btn
click_button("One")
click_button("Two")
click_button("Four")
end
def scroll
page.execute_script("window.scrollTo(0,2000)")
end
def iframe_btn
within_frame(page.find('iframe[src="buttons.html"]')) do
click_button("One")
click_button("Two")
click_button("Four")
end
end
def name
find("#first_name").set "Otavio"
end
def checkbox
check("OptionThree")
end
def select_list
drop = find("#select_box")
drop.find("option", text: "ExampleTwo").select_option
end
def img_visible
iframe_img = find("#panel_body_three")
end
end
|
0b858c6f71c8fe6a9c76d1c1e796fff8211e377a
|
[
"Markdown",
"Ruby"
] | 4
|
Ruby
|
vanzella25/Test_webjump_Otavio
|
06d884f7949c6ac2f2caf409a7cae64f9fcff107
|
a65be51ad14b429bd52ca0113773ca48a160836c
|
refs/heads/main
|
<file_sep>import * as functions from 'firebase-functions';
import * as dotenv from 'dotenv';
import * as admin from 'firebase-admin';
import axios from 'axios';
admin.initializeApp(functions.config().firebase);
dotenv.config();
const firestore = admin.firestore();
exports.createUser = functions.firestore
.document('people/{personID}')
.onCreate(async (snap, context) => {
const newValue = snap.data();
const isHuman = await validateHuman(newValue.token);
console.log('isHuman:', isHuman);
if (!isHuman) {
firestore.collection('people').doc(context.params.personID).delete();
}
});
async function validateHuman(response: string): Promise<boolean> {
try {
const { secret } = functions.config().captcha;
const { data } = await axios.post(
`https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${response}`
);
console.log('recaptcha response: ', data);
return data.success;
} catch ({ message }) {
console.log(message);
return false;
}
}
|
6817855d7de73da58b43816d72a3e5a0f60df5b5
|
[
"TypeScript"
] | 1
|
TypeScript
|
mackbrowne/petition
|
c74f9ca081666f52f57b8b4a1ca44bc4f8f995b2
|
0000eae78888d254f7aed0d891c20b984dbef137
|
refs/heads/main
|
<repo_name>caicohr/react-learning<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './App.css';
class Clock extends React.Component {//after the React.DOM finds this
constructor(props) {//First, initiate the value
super(props);
this.state = {date: new Date()};
}
componentDidMount() {//Third, After the component is rendered. They sometimes call it "Mounting"
this.thisisthetimerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {//Last to run. After this components unmounts
clearInterval(this.thisisthetimerID);
}
tick() {//This is in the DidMount() lifecycle method
this.setState({//sets the date to a new date. "the setState() call knows the state has changed"
date: new Date()
});
}
render() { //Second, renders the component whatever it is
return (
<div>
<h1>The time is {this.state.date.toLocaleTimeString()}</h1>
</div>
);
}
}
class Welcome extends React.Component {
render() {
return (
<div>
<h1>Hello, {this.props.name}</h1>
<p>You're {this.props.age}, right?</p>
</div>
);
}
}
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true,
name: '',
age: ''
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<div>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
</div>
);
}
}
function UserGreeting() {
return <h1>Aloha, User!</h1>;
}
function GuestGreeting() {
return <h1>Aloha! Please Login or Sign Up.</h1>
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />
}
return <GuestGreeting />
}
function UserIn(props) {
return <button onClick={props.onClick}>
Logout
</button>
}
function UserOut(props) {
return <button onClick={props.onClick}>
Login
</button>
}
class LoginStatus extends React.Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: false};
this.UserLoggedIn = this.UserLoggedIn.bind(this);
this.UserLoggedOut = this.UserLoggedOut.bind(this);
}
UserLoggedIn() {
this.setState({isLoggedIn: true});
}
UserLoggedOut() {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
<Greeting isLoggedIn={isLoggedIn}/>
{isLoggedIn
? <UserIn onClick = {this.UserLoggedOut}/>
: <UserOut onClick = {this.UserLoggedIn}/>
}
</div>
)
}
}
class WarningBanner extends React.Component {
constructor(props) {
super(props);
this.state = {
boolWarning: false
}
this.handleWarningButton = this.handleWarningButton.bind(this);
}
handleWarningButton() {
this.setState(state => ({//try to remember this syntax
boolWarning: !state.boolWarning
}));
}
render() {
return (
<div>
<button onClick={this.handleWarningButton}>
{
this.state.boolWarning
? 'Hide Warning'
: 'Show Warning'
}
</button>
<WarningDiv warn={this.state.boolWarning}/>
</div>
)
}
}
function WarningDiv(props) {
if (!props.warn) {
return null;
}
return (
<div>
WARNING!!!
</div>
)
}
class ListMaker extends React.Component {
render() {
const theList = this.props.inputList;
const listItems = theList.map((number) =>
<li key={number.toString()}>
{number}
</li>)
;
return (
<div>
<ul>
{listItems}
</ul>
</div>
)
}
}
function ShowList(props) {
const numbers = props.numbers;
const listList = numbers.map((num) =>
<li key={num.toString()}>
{num}
</li>
);
return (
<ul>{listList}</ul>
);
}
class FormPage extends React.Component {
constructor(props) {
super(props);
this.state = {
color: 'coconut',
isGoing: true,
numberOfGuests: 2
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(event) {
alert('Color: ' + this.state.color + ' Is Going: ' + this.state.isGoing + ' Number of Guests: ' + this.state.numberOfGuests);
event.preventDefault();
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite color:
<select value={this.state.color} onChange= {this.handleChange} name="color">
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
<br />
</label>
<label>
Is going:
<input type="checkbox" name="isGoing" checked={this.state.isGoing} onChange={this.handleChange}>
</input>
</label>
<br/>
<label>
Number of Guests:
<input
name="numberOfGuests"
type="number"
value={this.state.numberOfGuests}
onChange={this.handleChange}></input>
</label>
<input type="submit" value="Submit"/>
</form>
)
}
}
function WillBoil(props) {
if (props.celsius >= 100) {
return (
<p>The water would boil</p>
);
}
return (
<p>The water would not boil</p>
);
}
class OwnCalculator extends React.Component {
constructor(props) {
super(props);
this.state = {
temperature: '',
boolUnit: true
}
this.handleChange = this.handleChange.bind(this);
this.changeTemperatureUnit = this.changeTemperatureUnit.bind(this);
}
handleChange(e) {
this.setState({temperature: e.target.value});
}
changeTemperatureUnit() {
this.setState(previousState => ({
boolUnit: !previousState.boolUnit
}));
}
render() {
const temperature = this.state.temperature;
const celTemperature = toCelsius(temperature);
return (
this.state.boolUnit ?
<div>
<fieldset>
<legend>At what celsius temperature:</legend>
<input type="number" value={temperature} onChange={this.handleChange}></input> (This is {tryConvert(temperature,toFarenheit)} in farenheit)
<br />
<button onClick= {this.changeTemperatureUnit}>Change unit to Farenheit</button>
<WillBoil celsius={temperature}/>
</fieldset>
</div>
:
<div>
<fieldset>
<legend>At what farenheit temperature:</legend>
<input type="number" value={temperature} onChange={this.handleChange}></input> (This is {tryConvert(temperature,toCelsius)} in celsius)
<br />
<button onClick= {this.changeTemperatureUnit}>Change unit to Celsius</button>
<WillBoil celsius={celTemperature}/>
</fieldset>
</div>
)
}
}
function toCelsius(farenheit) {
return (farenheit - 32) * 5 / 9;
}
function toFarenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
class Calculator extends React.Component {
constructor(props){
super(props);
this.state = {
temperature: '',
scale: 'c'
}
this.handleFarenheitChange = this.handleFarenheitChange.bind(this);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
}
handleFarenheitChange(temperature) {
this.setState({temperature:temperature, scale:'f'});
}
handleCelsiusChange(temperature) {
this.setState({temperature: temperature, scale:'c'});
}
render() {
const temperature = this.state.temperature;
const scale = this.state.scale;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const farenheit = scale === 'c' ? tryConvert(temperature, toFarenheit) : temperature;
return (
<div>
<TemperatureInput scale="c" temperature={celsius} onTemperatureChange={this.handleCelsiusChange}/>
<TemperatureInput scale = "f" temperature={farenheit} onTemperatureChange={this.handleFarenheitChange}/>
<WillBoil celsius={celsius} />
</div>
)
}
}
const scaleNames = {
c: 'Celsius',
f: 'Farenheit'
};
class TemperatureInput extends React.Component {
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature} onChange={this.handleChange} />
</fieldset>
)
}
}
function tryConvert(temperature, convert) {
const input = parseFloat(temperature);
if (Number.isNaN(input)) {
return '';
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}
function Dialog(props) {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
{props.title}
</h1>
<p className="Dialog-message">
{props.message}
</p>
{props.children}
</FancyBorder>
);
}
function WelcomeDialog() {
return (
<Dialog
title="Welcome"
message="Thank you for visiting our spacecraft!"
/>
)
}
function GoodByeDialog() {
return (
<Dialog
title="Bye"
message = "Come back anytime"
/>
)
}
class SignUpDialog extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSignUp = this.handleSignUp.bind(this);
this.state = {name: ''}
}
handleChange(e) {
this.setState({name: e.target.value});
}
handleSignUp() {
alert("Welcome Aboad" + this.state.name + "!")
}
render() {
return (
<Dialog
title="Sign up"
message="You ready?"
>
<input value={this.state.name} onChange={this.handleChange}></input>
<button onClick={this.handleSignUp}>Sign me up!</button>
</Dialog>
)
}
}
class App extends React.Component {//second to run
render() {//find the Welcome component then the clock component will run
return (
<div>
<WelcomeDialog />
<SignUpDialog />
<p>Own Calclulator Style</p>
<OwnCalculator />
<p>React Style</p>
<Calculator />
<Welcome name="Ben" age="12"/>
<Welcome name="Ten" age ="18"/>
<Clock />
<Greeting isLoggedIn={false}/>
<LoginStatus />
<WarningBanner />
<ListMaker inputList={[1,2,3,4,5]}/>
<ShowList numbers={numbers}/>
<FormPage />
<Toggle />
<GoodByeDialog />
</div>
)
};
}
const numbers = [6,7,8,9,10];
ReactDOM.render(//first to run
<App />,
document.getElementById('root')
);<file_sep>/src/components/AddTodo.js
import React, { Component, PropTypes } from 'react';
export default class AddTodo extends Component {
constructor() {
super()
this.state = {clicked: false}
this.myRef = React.createRef()
this.handleClick = this.handleClick.bind(this)
}
render() {
return (
<div>
<input ref = {this.myRef} />
<button onClick = {() => this.handleClick()}>
Add
</button>
</div>
)
}
handleClick() {
const node = this.myRef
this.props.onAddClick(node)
}
}
|
f495dd536bd91cc04736d82d9b726c55f81f7fc7
|
[
"JavaScript"
] | 2
|
JavaScript
|
caicohr/react-learning
|
f103c9d38a43adf5c054460478b9584b83638e7d
|
b4b48bc6a65b1ecfb294ce5d2cc291c2366f0014
|
refs/heads/master
|
<file_sep>package fd.group;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import fd.group.account.AccountService;
import fd.group.dao.CategorieRepository;
import fd.group.dao.ProduitRepository;
import fd.group.entites.AppRole;
import fd.group.entites.AppUser;
import fd.group.entites.Categorie;
import fd.group.entites.Produit;
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
public class BoutiqueApplication implements CommandLineRunner {
@Autowired
private ProduitRepository produitRepository;
@Autowired
private CategorieRepository categorieRepository;
@Autowired
private AccountService accountService;
public static void main(String[] args) {
SpringApplication.run(BoutiqueApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (categorieRepository.findAll().isEmpty()) {
Stream.of("Ecran", "Portable Mobile", "Ordinateur", "Cable", "Accessoirs ordinateur et portable")
.forEach(c -> categorieRepository.save(new Categorie(null, c, null)));
}
if (produitRepository.findAll().isEmpty()) {
produitRepository.save(new Produit(null, "hp 650", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(3L, null, null)));
produitRepository.save(new Produit(null, "toshiba G700", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(3L, null, null)));
produitRepository.save(new Produit(null, "sharp", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(1L, null, null)));
produitRepository.save(new Produit(null, "lg", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(1L, null, null)));
produitRepository.save(new Produit(null, "nokia lumia", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(2L, null, null)));
produitRepository.save(new Produit(null, "samsung galaxy S8", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(2L, null, null)));
produitRepository.save(new Produit(null, "cable optique", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(4L, null, null)));
produitRepository.save(new Produit(null, "cable coaxial", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(4L, null, null)));
produitRepository.save(new Produit(null, "imprimante lazer L9000", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(5L, null, null)));
produitRepository.save(new Produit(null, "ecran tactile", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(5L, null, null)));
produitRepository.save(new Produit(null, "hp 630", Math.floor(Math.random() * 10000),
(int) Math.floor(Math.random() * 100), new Categorie(3L, null, null)));
}
categorieRepository.findAll().forEach(c -> System.out.println(c.getLibelle()));
if (accountService.findUserByUsername("admin") == null) {
accountService.saveUser(new AppUser(null, "admin", "admin", null));
accountService.saveUser(new AppUser(null, "user", "user", null));
accountService.saveRole(new AppRole(null, "ADMIN"));
accountService.saveRole(new AppRole(null, "USER"));
accountService.addRoleToUser("admin", "ADMIN");
accountService.addRoleToUser("user", "USER");
}
}
}
<file_sep>package fd.group.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import fd.group.entites.SecurityContant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
public class JWTAuthorization extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Headers",
"Origin,Accept,Content-Type,Authorization,Access-Control-Request-Method,Access-Control-Request-Headers");
response.addHeader("Access-Control-Expose-Headers",
"Access-Control-Allow-Origin,Authorization,Access-Control-Allow-Credentials");
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
String jwtToken = request.getHeader(SecurityContant.HEADER.getValeur());
if (jwtToken == null || !jwtToken.startsWith(SecurityContant.PREFIX_TOKEN.getValeur())) {
filterChain.doFilter(request, response);
return;
}
Claims claims = Jwts.parser().setSigningKey(SecurityContant.SECRET.getValeur())
.parseClaimsJws(jwtToken.replace(SecurityContant.PREFIX_TOKEN.getValeur(), "")).getBody();
String username = claims.getSubject();
List<Map<String, String>> authorities = (List<Map<String, String>>) claims.get("roles");
List<GrantedAuthority> roles = new ArrayList<>();
authorities.forEach(r -> {
roles.add(new SimpleGrantedAuthority(r.get("authority")));
});
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
null, roles);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, response);
}
}
}
<file_sep>package fd.group.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import fd.group.dao.CategorieRepository;
import fd.group.entites.Categorie;
@RestController
public class CategorieRestController {
@Autowired
private CategorieRepository categorieRepository;
@GetMapping("/allCategorie")
public List<Categorie> allCategorie() {
return categorieRepository.findAll();
}
@GetMapping("/findCategorie/{id}")
public Categorie findCategorie(@PathVariable("id") Long id) {
return categorieRepository.findById(id).get();
}
@GetMapping("/allCategoriePage")
public Page<Categorie> allCategoriePage(@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "taille", defaultValue = "11") int taille) {
return categorieRepository.findAll(PageRequest.of(page, taille));
}
@GetMapping("/allCategorieParMC")
public Page<Categorie> allCategorieParMC(@RequestParam("motcle") String motcle,
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "taille", defaultValue = "11") int taille) {
return categorieRepository.findByLibelleContains(motcle, PageRequest.of(page, taille, Sort.by("id")));
}
@PostMapping("/addCategorie")
public Categorie addCategorie(@RequestBody Categorie categorie) {
return categorieRepository.save(categorie);
}
@PostMapping("/editCategorie/{id}")
public Categorie editCategorie(@RequestBody Categorie categorie, @PathVariable Long id) {
categorie.setId(id);
return categorieRepository.save(categorie);
}
@GetMapping("/deleteCategorie/{id}")
public void deleteCategorie(@PathVariable Long id) {
categorieRepository.deleteById(id);
}
}
<file_sep>package fd.group.account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import fd.group.dao.RoleRepository;
import fd.group.dao.UserRepository;
import fd.group.entites.AppRole;
import fd.group.entites.AppUser;
@Service
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public AppUser saveUser(AppUser user) {
String hashPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(<PASSWORD>);
return userRepository.save(user);
}
@Override
public AppRole saveRole(AppRole role) {
return roleRepository.save(role);
}
@Override
public void addRoleToUser(String username, String rolename) {
AppUser user = userRepository.findByUsername(username);
AppRole role = roleRepository.findByRolename(rolename);
user.getRoles().add(role);
}
@Override
public AppUser findUserByUsername(String username) {
return userRepository.findByUsername(username);
}
}
|
a1358a57b187b87d91463b0aeed4c384b6b50ba2
|
[
"Java"
] | 4
|
Java
|
fodebailo/boutique
|
ee5e9bf050e469fdfb9f9d8e2d8d2593bbfb876e
|
2cccb7e6219ecb7491d4b4e287f76ebbedc0824a
|
refs/heads/master
|
<repo_name>oliverglue/vs_test<file_sep>/SQLQuery1.sql
select * from tas.dbo.InDocument
test
|
ac998424198bf2b9f6d88394bb4a5ee7c1d8f1ec
|
[
"SQL"
] | 1
|
SQL
|
oliverglue/vs_test
|
30b72317ebf07cea41fb12c75d3dd93fed06b00a
|
3fc6b971adac40b527b336df78f8c9b1d9d66dec
|
refs/heads/master
|
<file_sep>

# Github Search 🔍️
Feel free to check out the finall [result](https://mateuszkornecki.github.io/github-search/).
## About the project
This website was created during WTF - 'Co ten frontend course'. <br>
The main goal of this exercise was to create a simple search engine displaying basic information and repositories of the Github user.
## Tools and technologies I've used
- Semantic HTML5
- Sass (SCSS)
- Flexbox
- CSS Grid
- CSS Transitions
- Media queries
- Local Storage
- JS: DOM manipulations
- JS: Fetch API
- Git
- Figma
### Build with:
- [wtf-gulp-starter](https://github.com/maciejkorsan/wtf-gulp-starter)
## To run the website locally
**Requirements:**
- node.js (npm)
- gulp <br>
**Then, just run:** <br>
`npm install`<br>
`gulp`
**To publish you page using github pages use:**<br>
`npm run deploy`<br>
[bullet]: https://mateuszkornecki.github.io/assets/img/bullet.svg "test"
<file_sep>"use strict";
const searchInput = document.querySelector('.search__input--js');
const profilePage = document.querySelector('.profile--js');
//! CSS TRICK SOLUTION FOR 100vh on mobiles
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
const profileBuilder = () => {
profilePage.innerHTML = '';
searchInput.value = localStorage.getItem('User Name');
fetch(`https://api.github.com/users/${localStorage.getItem('User Name')}`)
.then(resp => resp.json())
.then(resp => {
let owner = resp;
if (owner.login != undefined) {
const ownerSection = document.createElement('section');
const ownerAvatar = document.createElement('img');
const ownerTextWrapper = document.createElement('div');
const ownerName = document.createElement('h2');
const ownerLogin = document.createElement('span');
const ownerBio = document.createElement('p');
ownerSection.classList.add('owner', 'owner--js');
ownerAvatar.className = 'owner__avatar';
ownerTextWrapper.className = 'owner__text-wrapper';
ownerName.className = 'owner__name';
ownerLogin.className = 'owner__login';
ownerBio.className = 'owner__bio';
ownerAvatar.src = owner.avatar_url;
ownerAvatar.alt = `${owner.name} avatar`;
profilePage.appendChild(ownerSection);
ownerSection.appendChild(ownerAvatar);
ownerSection.appendChild(ownerTextWrapper);
ownerTextWrapper.appendChild(ownerName);
ownerTextWrapper.appendChild(ownerLogin);
ownerTextWrapper.appendChild(ownerBio);
ownerName.innerHTML = owner.name;
ownerLogin.innerHTML = owner.login;
ownerBio.innerHTML = owner.bio;
}
})
.catch(err => {
console.log(err);
})
fetch(`https://api.github.com/users/${localStorage.getItem('User Name')}/repos?sort=full_name&direction=asc`)
.then(resp => resp.json())
.then(resp => {
let repos = resp;
const repositories = document.createElement('div');
repositories.classList.add('repos', 'repos--js');
profilePage.appendChild(repositories);
repos.forEach(repo => {
const repoSection = document.createElement('section');
const repoTextWrapper = document.createElement('div');
const repoName = document.createElement('h3');
const repoDescription = document.createElement('p');
const repoFooter = document.createElement('footer');
const repoLanguage = document.createElement('span');
const repoFooterTextWrapper = document.createElement('div');
const repoGithub = document.createElement('a');
//Display 'Live' only if it exist
if (repo.homepage) {
const repoLive = document.createElement('a');
repoLive.className = 'repo__live';
repoFooterTextWrapper.appendChild(repoLive);
repoLive.innerHTML = `<a class="repo__link" href="${repo.homepage}">Live</a>`;
}
repoSection.className = 'repo';
repoTextWrapper.className = 'repo__text-wrapper';
repoName.className = 'repo__title';
repoDescription.className = 'repo__description';
repoLanguage.className = 'repo__language';
repoFooter.className = 'repo__footer';
repoFooterTextWrapper.className = 'repo__footer-text-wrapper';
repoGithub.className = 'repo__github';
repositories.appendChild(repoSection);
repoSection.appendChild(repoTextWrapper);
repoTextWrapper.appendChild(repoName);
repoTextWrapper.appendChild(repoDescription);
repoSection.appendChild(repoFooter);
repoFooter.appendChild(repoLanguage);
repoFooter.appendChild(repoFooterTextWrapper);
repoFooterTextWrapper.appendChild(repoGithub);
repoName.innerHTML = repo.name;
repoDescription.innerHTML = repo.description;
repoGithub.innerHTML = `<a class="repo__link" href="${repo.svn_url}">Github</a>`;
localStorage.removeItem('User Name');
switch (repo.language) {
case 'HTML':
repoLanguage.innerHTML = `<img class="language__icon" src="assets/img/${repo.language}.png" alt="${repo.language} icon">`
break;
case 'JavaScript':
repoLanguage.innerHTML = `<img class="language__icon" src="assets/img/${repo.language}.png" alt="${repo.language} icon">`
break;
case 'CSS':
repoLanguage.innerHTML = `<img class="language__icon" src="assets/img/${repo.language}.png" alt="${repo.language} icon">`
break;
default:
repoLanguage.innerHTML = repo.language;
}
})
})
.catch(err => {
profilePage.innerHTML = '';
const p = document.createElement('p');
p.className = 'err';
profilePage.appendChild(p);
p.innerHTML = `Nie znaleziono użytkownika o nazwie <b> ${localStorage.getItem('User Name')} </b>`;
localStorage.removeItem('User Name');
})
}
//! if you are on second.html and localStorage record exist then print it
if (profilePage && localStorage.getItem('User Name')) {
profileBuilder();
}
searchInput.addEventListener('keyup', (e) => {
//! if enter is pressed print profile
let userName = searchInput.value;
if (e.keyCode === 13) {
localStorage.setItem('User Name', userName);
if (profilePage) {
profileBuilder();
} else {
//? "_top" - need to read more about that
window.open("second.html", "_top");
}
}
})
|
5fd43854cf6a7fa0cc49f5601a2d6fc09bf0399e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
mateuszkornecki/github-search
|
3d2221e31311c23ae8bc2b9c821bd22d010b241f
|
4a4bb56ac4925d3d425b23413bca62ae616f440b
|
refs/heads/master
|
<file_sep>export interface CategoriesGet {
drinks: ICategory[];
}
export interface ICategory {
strCategory: string;
}
<file_sep>import { CategoriesActions, ECategoriesActions } from '../actions/categories.actions';
import { initialCategoriesState, ICategoriesState } from '../state/categories.state';
export const categoriesReducers = (
state = initialCategoriesState,
action: CategoriesActions
): ICategoriesState => {
switch (action.type) {
case ECategoriesActions.LOAD_CATEGORIES: {
return {
...state,
categories: null
};
}
case ECategoriesActions.LOAD_CATEGORIES_SUCCESS: {
return {
...state,
categories: action.payload,
loading: true
};
}
case ECategoriesActions.LOAD_CATEGORIES_FAIL: {
return {
...state,
error: action.payload,
};
}
default:
return state;
}
};
<file_sep>import { createSelector } from '@ngrx/store';
import { IAppState } from '../state/app.state';
import { IDrinksState } from '../state/drinks.state';
const drinksState = (state: IAppState) => state.drinks;
export const selectDrinks = createSelector(
drinksState,
(state: IDrinksState) => state.drinks
);
<file_sep>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CategoriesGet } from '../models/category';
import { LoadedDrinks } from '../models/drink';
@Injectable({
providedIn: 'root'
})
export class CocktailService {
key = 'c';
constructor(private http: HttpClient) { }
getDrinksByCategory(category: string): Observable<LoadedDrinks> {
return this.http.get<any>('https://www.thecocktaildb.com/api/json/v1/1/filter.php?' + this.key + '=' + category);
}
getCategories(): Observable<CategoriesGet> {
const value = 'list';
return this.http.get<CategoriesGet>('https://www.thecocktaildb.com/api/json/v1/1/list.php?' + this.key + '=' + value);
}
}
<file_sep>import { ICategory } from 'src/app/models/category';
export interface ICategoriesState {
categories: ICategory[];
loading: boolean;
error: Error;
}
export const initialCategoriesState: ICategoriesState = {
categories: null,
loading: false,
error: null
};
<file_sep>import { IDrink } from 'src/app/models/drink';
export interface IDrinksState {
drinks: IDrink[];
loading: boolean;
error: Error;
}
export const initialDrinksState: IDrinksState = {
drinks: null,
loading: false,
error: null
};
<file_sep>import { createSelector } from '@ngrx/store';
import { IAppState } from '../state/app.state';
import { ICategoriesState } from '../state/categories.state';
const categoriesState = (state: IAppState) => state.categories;
export const selectCategories = createSelector(
categoriesState,
(state: ICategoriesState) => state.categories
);
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { HttpClientModule } from '@angular/common/http';
import { NgxInfiniteScrollerModule } from 'ngx-infinite-scroller';
import { AppComponent } from './app.component';
import { HeaderComponent } from './modules/header/header.component';
import { FiltersComponent } from './modules/filters/filters.component';
import { CocktailsComponent } from './modules/cocktails/cocktails.component';
import { categoriesReducers } from './store/reducers/categories.reducers';
import { CategoriesEffects } from './store/effects/categories.effects';
import { DrinksEffects } from './store/effects/drinks.effects';
import { drinksReducers } from './store/reducers/drinks.reducers';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FiltersComponent,
CocktailsComponent
],
imports: [
BrowserModule,
HttpClientModule,
NgxInfiniteScrollerModule,
StoreModule.forRoot({
categories: categoriesReducers,
drinks: drinksReducers
}),
EffectsModule.forRoot([
CategoriesEffects,
DrinksEffects
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Action } from '@ngrx/store';
import { ICategory } from '../../models/category';
export enum ECategoriesActions {
LOAD_CATEGORIES = '[CATEGORIES] Load Categories',
LOAD_CATEGORIES_SUCCESS = '[CATEGORIES] Load Categories Success',
LOAD_CATEGORIES_FAIL = '[CATEGORIES] Load Categories Fail',
}
export class LoadCategories implements Action {
readonly type = ECategoriesActions.LOAD_CATEGORIES;
constructor() { }
}
export class LoadCategoriesSuccess implements Action {
readonly type = ECategoriesActions.LOAD_CATEGORIES_SUCCESS;
constructor(public payload: ICategory[]) { }
}
export class LoadCategoriesFail implements Action {
readonly type = ECategoriesActions.LOAD_CATEGORIES_FAIL;
constructor(public payload: Error) { }
}
export type CategoriesActions =
| LoadCategories
| LoadCategoriesSuccess
| LoadCategoriesFail;
<file_sep>import { initialCategoriesState, ICategoriesState } from './categories.state';
import { IDrinksState, initialDrinksState } from './drinks.state';
export interface IAppState {
categories: ICategoriesState;
drinks: IDrinksState;
}
export const initialAppState: IAppState = {
categories: initialCategoriesState,
drinks: initialDrinksState
};
export function getInitialState(): IAppState {
return initialAppState;
}
<file_sep>import { Component, OnInit, OnDestroy, Output, Input, EventEmitter } from '@angular/core';
import { Subscription } from 'rxjs';
import { Store } from '@ngrx/store';
import { IAppState } from 'src/app/store/state/app.state';
import { selectCategories } from 'src/app/store/selectors/categories.selector';
import { LoadCategories } from 'src/app/store/actions/categories.actions';
import { ICategory } from 'src/app/models/category';
@Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: ['./filters.component.scss']
})
export class FiltersComponent implements OnInit, OnDestroy {
private subscription = new Subscription();
categories: ICategory[];
showedCategories: Array<string>;
@Output() сhangedCategories = new EventEmitter<ICategory[]>();
@Input() showMenu: boolean;
constructor(
private store: Store<IAppState>
) {
const categoriesSub = this.store.select(selectCategories).subscribe(result => {
if (result) {
this.categories = result;
const arr = [];
for (const item of this.categories) { arr.push(item.strCategory); }
this.showedCategories = arr;
}
});
this.subscription.add(categoriesSub);
}
ngOnInit(): void {
this.store.dispatch(new LoadCategories());
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
checkInShowedCategories(category: string): boolean {
if (this.showedCategories.includes(category)) {
return true;
} else { return false; }
}
changeShowedCategories(category: string): void {
if (this.checkInShowedCategories(category)) {
this.showedCategories = this.showedCategories.filter(item => item !== category);
} else { this.showedCategories.push(category); }
}
pressApply(): void {
const categoriesForLoad = this.categories.filter(item => this.checkInShowedCategories(item.strCategory));
this.сhangedCategories.emit(categoriesForLoad);
}
}
<file_sep>import { Component, OnInit, OnDestroy, OnChanges, Input } from '@angular/core';
import { Store } from '@ngrx/store';
import { Subscription } from 'rxjs';
import { IAppState } from 'src/app/store/state/app.state';
import { ICategory } from 'src/app/models/category';
import { LoadedDrinks } from 'src/app/models/drink';
import { LoadDrinks } from 'src/app/store/actions/drinks.actions';
import { selectDrinks } from 'src/app/store/selectors/drinks.selector';
import { selectCategories } from 'src/app/store/selectors/categories.selector';
@Component({
selector: 'app-cocktails',
templateUrl: './cocktails.component.html',
styleUrls: ['./cocktails.component.scss']
})
export class CocktailsComponent implements OnInit, OnDestroy, OnChanges {
private subscription = new Subscription();
@Input() categoriesForLoad: ICategory[];
allDrinks: LoadedDrinks[] = [];
currentCategory: string;
indexOfCurrentCategory: number;
loadingInProcess = true;
constructor(
private store: Store<IAppState>
) { }
ngOnInit(): void {
this.addCategoriesSub();
this.addDrinksSub();
}
ngOnChanges(): void {
this.allDrinks = [];
if (this.categoriesForLoad) {
this.loadingInProcess = true;
this.indexOfCurrentCategory = 0;
this.getDrinks();
window.scroll(0, 0);
}
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
addCategoriesSub(): void {
const categoriesSub = this.store.select(selectCategories).subscribe(result => {
if (result && !this.categoriesForLoad) {
this.categoriesForLoad = result;
this.indexOfCurrentCategory = 0;
this.getDrinks();
}
});
this.subscription.add(categoriesSub);
}
addDrinksSub(): void {
const drinksSub = this.store.select(selectDrinks).subscribe(result => {
if (result) {
const newItem = {
category: this.currentCategory,
drinks: result
};
this.allDrinks.push(newItem);
if (this.indexOfCurrentCategory === this.categoriesForLoad.length - 1) {
this.loadingInProcess = false;
}
}
});
this.subscription.add(drinksSub);
}
public onScrollDown(): void {
if (this.loadingInProcess) { this.loadNextCategory(); }
}
loadNextCategory(): void {
this.indexOfCurrentCategory++;
this.getDrinks();
}
getDrinks(): void {
this.currentCategory = this.categoriesForLoad[this.indexOfCurrentCategory].strCategory;
this.store.dispatch(new LoadDrinks(this.currentCategory));
}
}
<file_sep>import { ActionReducerMap } from '@ngrx/store';
import { IAppState } from '../state/app.state';
import { categoriesReducers } from './categories.reducers';
import { drinksReducers } from './drinks.reducers';
export const appReducers: ActionReducerMap<IAppState, any> = {
categories: categoriesReducers,
drinks: drinksReducers
};
<file_sep>import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { switchMap, catchError, mergeMap, map } from 'rxjs/operators';
import { of } from 'rxjs';
import { DrinksGet } from '../../models/drink';
import { CocktailService } from '../../service/cocktail.service';
import {
EDrinksActions,
LoadDrinks,
LoadDrinksSuccess,
LoadDrinksFail
} from '../actions/drinks.actions';
@Injectable()
export class DrinksEffects {
@Effect()
loadDrinks$ = this.actions$.pipe(
ofType<LoadDrinks>(EDrinksActions.LOAD_DRINKS),
switchMap((action) => {
return this.cocktailService.getDrinksByCategory(action.payload).pipe(
mergeMap(result => {
return [new LoadDrinksSuccess(result.drinks)];
}),
catchError((error: Error) => {
return of(new LoadDrinksFail(error));
})
);
})
);
constructor(
private cocktailService: CocktailService,
private actions$: Actions
) {}
}
<file_sep>export interface LoadedDrinks {
category: string;
drinks: IDrink[];
}
export interface DrinksGet {
drinks: IDrink[];
}
export interface IDrink {
strDrink: string;
strDrinkThumb: string;
idDrink: string;
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ICategory } from './models/category';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'Cocktail-DB';
categoriesForLoad: ICategory[];
showMenu: boolean = false;
constructor() { }
ngOnInit() { }
onOpenedMenu(value: boolean):void {
this.showMenu = value;
}
onChangedCategories(value: ICategory[]):void {
this.categoriesForLoad = value;
this.showMenu = false;
}
}
<file_sep>import { DrinksActions, EDrinksActions } from '../actions/drinks.actions';
import { initialDrinksState, IDrinksState } from '../state/drinks.state';
export const drinksReducers = (
state = initialDrinksState,
action: DrinksActions
): IDrinksState => {
switch (action.type) {
case EDrinksActions.LOAD_DRINKS: {
return {
...state,
drinks: null
};
}
case EDrinksActions.LOAD_DRINKS_SUCCESS: {
return {
...state,
drinks: action.payload,
loading: true
};
}
case EDrinksActions.LOAD_DRINKS_FAIL: {
return {
...state,
error: action.payload,
};
}
default:
return state;
}
};
<file_sep>import { Action } from '@ngrx/store';
import { IDrink } from '../../models/drink';
export enum EDrinksActions {
LOAD_DRINKS = '[DRINKS] Load Drinks',
LOAD_DRINKS_SUCCESS = '[DRINKS] Load Drinks Success',
LOAD_DRINKS_FAIL = '[DRINKS] Load Drinks Fail',
}
export class LoadDrinks implements Action {
readonly type = EDrinksActions.LOAD_DRINKS;
constructor(public payload: string) { }
}
export class LoadDrinksSuccess implements Action {
readonly type = EDrinksActions.LOAD_DRINKS_SUCCESS;
constructor(public payload: IDrink[]) { }
}
export class LoadDrinksFail implements Action {
readonly type = EDrinksActions.LOAD_DRINKS_FAIL;
constructor(public payload: Error) { }
}
export type DrinksActions =
| LoadDrinks
| LoadDrinksSuccess
| LoadDrinksFail;
<file_sep>import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { switchMap, catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { CategoriesGet } from '../../models/category';
import { CocktailService } from '../../service/cocktail.service';
import {
ECategoriesActions,
LoadCategories,
LoadCategoriesSuccess,
LoadCategoriesFail
} from '../actions/categories.actions';
@Injectable()
export class CategoriesEffects {
@Effect()
loadCategories$ = this.actions$.pipe(
ofType<LoadCategories>(ECategoriesActions.LOAD_CATEGORIES),
switchMap(() => this.cocktailService.getCategories()),
switchMap((categoriesGet: CategoriesGet) => {
return of(new LoadCategoriesSuccess(categoriesGet.drinks));
}),
catchError((error: Error) => {
return of(new LoadCategoriesFail(error));
})
);
constructor(
private cocktailService: CocktailService,
private actions$: Actions
) {}
}
<file_sep>import { Component, Output, Input, OnChanges, EventEmitter } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnChanges {
@Output() openedMenu = new EventEmitter<boolean>();
@Input() stopShowMenu: boolean;
showMenu: boolean = false;
constructor() { }
ngOnChanges(): void {
this.showMenu = this.stopShowMenu;
}
openMenu():void {
this.showMenu = true;
this.openedMenu.emit(true);
}
closeMenu():void {
this.showMenu = false;
this.openedMenu.emit(false);
}
}
|
bb8881369b736103c204be3cd554ab06b644f497
|
[
"TypeScript"
] | 20
|
TypeScript
|
liliia2/Drink-test
|
8ad81fc3a3b5435110b3fc101ddde0d5136518b6
|
65f3ef9eab93c025e46102fe94eee2205bec908b
|
refs/heads/master
|
<file_sep>from flask import Flask
app = Flask(__name__)
@app.route('/<string:paste_id>', methods=['GET'])
def get_paste(paste_id):
pass
@app.route('/', methods=['GET'])
def home_page():
pass
@app.route('/', methods=['POST'])
def post_paste(paste_txt):
pass<file_sep>import os
import unittest
class TestApp(unittest.TestCase):
def setUp(self):
pass
def test_get_paste(self):
pass
def test_post_paste(self):
pass
def test_home_page(self):
pass
if __name__ == "__main__":
unittest.main()
|
0198e22e6639a785988470853f91b5926a6637d0
|
[
"Python"
] | 2
|
Python
|
kdbeall/pypaste
|
24ae202ac771a879578538c9e2b4e35ce5fb0181
|
ad806b70c5e05a46dbfb7329a3a7ec165466a546
|
refs/heads/master
|
<repo_name>marnathali/Kaizenware<file_sep>/src/modelo/dao/UsuarioDAO.java
package modelo.dao;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import modelo.dao.utils.GenericDAO;
import modelo.dao.utils.Sesion;
import modelo.dto.Usuario;
public class UsuarioDAO extends GenericDAO {
private static UsuarioDAO instancia;
public static UsuarioDAO getInstancia() {
if (instancia == null) {
instancia = new UsuarioDAO();
}
return instancia;
}
private Sesion sesion;
private UsuarioDAO() {
super();
}
public List<Usuario> queryAll() {
return super.queryAll(Usuario.class);
}
public Usuario get(Serializable id) {
return (Usuario)super.get(Usuario.class, id);
}
public List<Usuario> getPorNombre(String nombre) {
this.sesion = Sesion.getInstancia();
Session session = this.sesion.openSession();
List<Usuario> usuario = null;
try{
usuario = session.createCriteria(Usuario.class).add(Restrictions.eq("nombre_usuario", nombre)).list();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
session.close();
}
return usuario;
}
public void save(Usuario Usuario) {
super.save(Usuario);
}
public void update(Usuario Usuario) {
super.update(Usuario);
}
public void saveOrUpdate(Usuario Usuario) {
super.saveOrUpdate(Usuario);
}
public void delete(Usuario Usuario) {
super.delete(Usuario);
}
}
<file_sep>/src/modelo/dao/utils/GenericDAO.java
package modelo.dao.utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
public abstract class GenericDAO {
private Sesion sesion;
public GenericDAO() {
this.sesion = Sesion.getInstancia();
}
public List queryAll(Class class1) {
Session session = this.sesion.openSession();
List<Object> data = new ArrayList<Object>();
try {
data = session.createCriteria(class1).list();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
session.close();
}
return data;
}
public Object get(Class class1, Serializable id) {
Session session = this.sesion.openSession();
Object object = null;
try{
object = session.get(class1, id);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
session.close();
}
return object;
}
public void save(Object object) {
Session session = this.sesion.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(object);
transaction.commit();
}
catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
public void update(Object object) {
Session session = this.sesion.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.update(object);
transaction.commit();
}
catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
public void saveOrUpdate(Object object) {
Session session = this.sesion.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.saveOrUpdate(object);
transaction.commit();
}
catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
finally {
session.close();
}
}
public void delete(Object object) {
Session session = this.sesion.openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.delete(object);
transaction.commit();
}
catch (Exception e) {
transaction.rollback();
}
finally {
session.close();
}
}
}
<file_sep>/src/modelo/dao/utils/Sesion.java
package modelo.dao.utils;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class Sesion {
private SessionFactory sessionFactory;
private static Sesion instancia;
public static Sesion getInstancia() {
if (instancia == null) {
instancia = new Sesion();
}
return instancia;
}
private Sesion() {
AnnotationConfiguration configuration = new AnnotationConfiguration();
try {
this.sessionFactory = configuration.configure("hibernate.cfg.xml").buildSessionFactory();
}
catch (Throwable ex) {
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public Session openSession() throws HibernateException {
return sessionFactory.openSession();
}
}
<file_sep>/src/modelo/dao/RolDAO.java
package modelo.dao;
import java.io.Serializable;
import java.util.List;
import modelo.dao.utils.GenericDAO;
import modelo.dto.Rol;
public class RolDAO extends GenericDAO {
private static RolDAO instancia;
public static RolDAO getInstancia() {
if (instancia == null) {
instancia = new RolDAO();
}
return instancia;
}
private RolDAO() {
super();
}
public List<Rol> queryAll() {
return super.queryAll(Rol.class);
}
public Rol get(Serializable id) {
return (Rol)super.get(Rol.class, id);
}
public void save(Rol Rol) {
super.save(Rol);
}
public void update(Rol Rol) {
super.update(Rol);
}
public void saveOrUpdate(Rol Rol) {
super.saveOrUpdate(Rol);
}
public void delete(Rol Rol) {
super.delete(Rol);
}
}
|
0cbb820013fadb5a7d759d847faf8a7a0f804002
|
[
"Java"
] | 4
|
Java
|
marnathali/Kaizenware
|
ab6c9615c2c98a57a066fa42fa9aa0946826cfd5
|
8cdd5e70657b0e8da8e0a45d89223727281c1ff8
|
refs/heads/master
|
<file_sep># puts numbers entered by user in order
ordered_numbers = []
number_count = 0
while number_count < 3
puts "Please enter a number:"
ordered_numbers.push(gets.chomp)
number_count += 1
end
puts
puts ordered_numbers.sort
# next: allow user to enter number of numbers
# *************************************************
# ** next: allow user to enter number of numbers **
# *************************************************<file_sep># greeting program
states_abbrv = {
"California" => "CA",
"Oregon" => "OR",
"Washington" => "WA",
"Nevada" => "NV"
}
puts "What is your first name?"
first_name = gets.chomp.capitalize
puts "What is your last name?"
last_name = gets.chomp.capitalize
puts "What city do you live in?"
city = gets.chomp.split(' ')
city.each do |c|
c.to_s.capitalize!
end
puts "What state do you live in?"
state = gets.chomp.capitalize
puts states_abbrv[state]
puts
puts "Your name is #{first_name + " " + last_name}"
puts "and you live in #{city[0]} #{city[1]}, #{states_abbrv[state]}."
# *******************************
# ** next: complete dictionary **
# *******************************
# "Alabama" => "AL"
# "Alaska AK
# "Arizona AZ
# "Arkansas AR
# "California CA
# "Colorado CO
# "Connecticut CT
# "Delaware DE
# "Florida FL
# "Georgia GA
# "Hawaii HI
# Idaho ID
# Illinois IL
# Indiana IN
# Iowa IA
# Kansas KS
# Kentucky KY
# Louisiana LA
# Maine ME
# Maryland MD
# Massachusetts MA
# Michigan MI
# Minnesota MN
# Mississippi MS
# Missouri MO
# Montana MT
# Nebraska NE
# Nevada NV
# New Hampshire NH
# New Jersey NJ
# New Mexico NM
# New York NY
# North Carolina NC
# North Dakota ND
# Ohio OH
# Oklahoma OK
# Oregon OR
# Pennsylvania PA
# Rhode Island RI
# South Carolina SC
# South Dakota SD
# Tennessee TN
# Texas TX
# Utah UT
# Vermont VT
# Virginia VA
# Washington WA
# West Virginia WV
# Wisconsin WI
# Wyoming WY
<file_sep># print all words to "99 bottles of beer on the wall"
bottle_count = 99
while bottle_count > 1
puts "#{bottle_count} bottles of beer on the wall!"
puts "#{bottle_count} bottles of beer!"
puts "Take one down, pass it around,"
bottle_count = bottle_count - 1
if bottle_count > 1
puts "#{bottle_count} bottles of beer on the wall."
puts
elsif
puts "1 bottle of beer on the wall."
puts
end
end
puts
puts "1 bottle of beer on the wall!"
puts "1 bottle of beer!"
puts "Take one down, pass it around,"
puts "No more bottles of beer on the wall!"
<file_sep># simple calculator program
puts "Please enter a number:"
number1 = gets.chomp.to_i
puts
puts "Please pick an operation:"
operator = gets.chomp
# require user to enter proper operator
until
operator == "+" ||
operator == "-" ||
operator == "*" ||
operator == "/" do
puts "Please enter an operator (+,-,*,/):"
operator = gets.chomp
end
puts
puts "Please enter another number:"
number2 = gets.chomp.to_i
# perform calculation
if operator == "+"
result = number1 + number2
elsif operator == "-"
result = number1 - number2
elsif operator == "*"
result = number1 * number2
elsif operator == "/"
result = number1.to_f / number2.to_f
end
puts
puts "Your answer is:"
puts result
|
9930f4b3de853d49a09161ce75f602d113cb3d3d
|
[
"Ruby"
] | 4
|
Ruby
|
radcliff/GA_studyhall
|
5974392fadc1e96eb8aaf7eacd479575823c945d
|
a69374381066f35d4a865f55ce5208ad15448b9a
|
refs/heads/master
|
<repo_name>Pod-Point/react-native-md-textinput<file_sep>/lib/Underline.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _reactNative = require('react-native');
var _reactNative2 = _interopRequireDefault(_reactNative);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Underline = function (_Component) {
_inherits(Underline, _Component);
function Underline(props) {
_classCallCheck(this, Underline);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Underline).call(this, props));
_this.state = {
lineLength: new _reactNative.Animated.Value(0)
};
_this.wrapperWidth = 0;
return _this;
}
_createClass(Underline, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
requestAnimationFrame(function () {
if (_this2.refs.wrapper == null) {
return;
}
var container = _this2.refs.wrapper; // un-box animated view
container.measure(function (left, top, width, height) {
_this2.wrapperWidth = width;
});
});
}
}, {
key: 'expandLine',
value: function expandLine() {
_reactNative.Animated.timing(this.state.lineLength, {
toValue: this.wrapperWidth,
duration: this.props.duration
}).start();
}
}, {
key: 'shrinkLine',
value: function shrinkLine() {
_reactNative.Animated.timing(this.state.lineLength, {
toValue: 0,
duration: this.props.duration
}).start();
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var borderColor = _props.borderColor;
var highlightColor = _props.highlightColor;
return _reactNative2.default.createElement(
_reactNative.View,
{
style: [styles.underlineWrapper, {
backgroundColor: borderColor
}],
ref: 'wrapper'
},
_reactNative2.default.createElement(_reactNative.Animated.View, {
style: [{
width: this.state.lineLength,
height: 2,
backgroundColor: highlightColor
}] })
);
}
}]);
return Underline;
}(_reactNative.Component);
exports.default = Underline;
Underline.propTypes = {
duration: _reactNative.PropTypes.number,
highlightColor: _reactNative.PropTypes.string,
borderColor: _reactNative.PropTypes.string
};
var styles = _reactNative.StyleSheet.create({
underlineWrapper: {
height: 2,
alignItems: 'center'
}
});<file_sep>/lib/TextField.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _reactNative = require('react-native');
var _reactNative2 = _interopRequireDefault(_reactNative);
var _Underline = require('./Underline');
var _Underline2 = _interopRequireDefault(_Underline);
var _FloatingLabel = require('./FloatingLabel');
var _FloatingLabel2 = _interopRequireDefault(_FloatingLabel);
var _ExtendedTextInput = require('./ExtendedTextInput');
var _ExtendedTextInput2 = _interopRequireDefault(_ExtendedTextInput);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var TextField = function (_Component) {
_inherits(TextField, _Component);
function TextField(props, context) {
_classCallCheck(this, TextField);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(TextField).call(this, props, context));
_this.state = {
isFocused: false,
text: props.value
};
return _this;
}
_createClass(TextField, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
if (this.props.value !== props.value) {
this.setState({
text: props.value
});
}
}
}, {
key: 'focus',
value: function focus() {
this.refs.input.focus();
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var label = _props.label;
var highlightColor = _props.highlightColor;
var duration = _props.duration;
var labelColor = _props.labelColor;
var borderColor = _props.borderColor;
var _onFocus = _props.onFocus;
var _onBlur = _props.onBlur;
var _onChangeText = _props.onChangeText;
var value = _props.value;
var dense = _props.dense;
return _reactNative2.default.createElement(
_reactNative.View,
{ style: dense ? styles.denseWrapper : styles.wrapper, ref: 'wrapper' },
_reactNative2.default.createElement(_ExtendedTextInput2.default, _extends({
style: dense ? styles.denseTextInput : styles.textInput,
onFocus: function onFocus() {
_this2.setState({ isFocused: true });
_this2.refs.floatingLabel.floatLabel();
_this2.refs.underline.expandLine();
_onFocus && _onFocus();
},
onBlur: function onBlur() {
_this2.setState({ isFocused: false });
!_this2.state.text.length && _this2.refs.floatingLabel.sinkLabel();
_this2.refs.underline.shrinkLine();
_onBlur && _onBlur();
},
onChangeText: function onChangeText(text) {
_this2.setState({ text: text });
_onChangeText && _onChangeText(text);
},
ref: 'input',
value: this.state.text
}, props)),
_reactNative2.default.createElement(_Underline2.default, {
ref: 'underline',
highlightColor: highlightColor,
duration: duration,
borderColor: borderColor
}),
_reactNative2.default.createElement(_FloatingLabel2.default, {
isFocused: this.state.isFocused,
ref: 'floatingLabel',
focusHandler: this.focus.bind(this),
label: label,
labelColor: labelColor,
highlightColor: highlightColor,
duration: duration,
dense: dense,
hasValue: this.state.text.length ? true : false
})
);
}
}]);
return TextField;
}(_reactNative.Component);
exports.default = TextField;
TextField.propTypes = {
duration: _reactNative.PropTypes.number,
label: _reactNative.PropTypes.string,
highlightColor: _reactNative.PropTypes.string,
onFocus: _reactNative.PropTypes.func,
onBlur: _reactNative.PropTypes.func,
onChangeText: _reactNative.PropTypes.func,
value: _reactNative.PropTypes.string,
dense: _reactNative.PropTypes.bool
};
TextField.defaultProps = {
duration: 200,
labelColor: '#9E9E9E',
borderColor: '#E0E0E0',
value: '',
dense: false,
underlineColorAndroid: 'rgba(0,0,0,0)'
};
var styles = _reactNative.StyleSheet.create({
wrapper: {
height: 72,
paddingTop: 30,
paddingBottom: 7,
position: 'relative'
},
denseWrapper: {
height: 60,
paddingTop: 28,
paddingBottom: 4,
position: 'relative'
},
textInput: {
fontSize: 18,
height: 34,
lineHeight: 34
},
denseTextInput: {
fontSize: 13,
height: 27,
lineHeight: 24,
paddingBottom: 3
}
});
|
e3657ee185d467320746b3d7fd874cddf2b8a27c
|
[
"JavaScript"
] | 2
|
JavaScript
|
Pod-Point/react-native-md-textinput
|
3024a779dd2fa0ef29b0380b4a2c67cc88950d12
|
703bde4039a6e0a4b3ab75f049c00fd373ad28bc
|
refs/heads/master
|
<repo_name>ebruispir/class-5-project-cookit<file_sep>/frontend/src/component/Filter.jsx
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelActions from '@material-ui/core/ExpansionPanelActions';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
const useStyles = makeStyles(theme => ({
root: {
width: '100%',
},
heading: {
fontSize: theme.typography.pxToRem(15),
},
secondaryHeading: {
fontSize: theme.typography.pxToRem(15),
color: theme.palette.text.secondary,
},
icon: {
verticalAlign: 'bottom',
height: 20,
width: 20,
},
details: {
alignItems: 'center',
},
column: {
flexBasis: '33.33%',
},
helper: {
borderLeft: `2px solid ${theme.palette.divider}`,
padding: theme.spacing(1, 2),
},
link: {
color: theme.palette.primary.main,
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
}));
const Filter = () => {
const classes = useStyles();
const [expanded, setExpanded] = React.useState(false);
const handleChange = panel => (event, isExpanded) => {
setExpanded(isExpanded ? panel : false);
};
return (
<div className={classes.root} className="mb-5">
<ExpansionPanel expanded={expanded === 'panel1'} onChange={handleChange('panel1')}>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Typography className={classes.heading}>Filter</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<Typography>
Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat. Aliquam eget
maximus est, id dignissim quam.
</Typography>
</ExpansionPanelDetails>
</ExpansionPanel>
</div>
);
};
export default Filter;
<file_sep>/frontend/src/component/EpicMenu.js
import React, { Component } from 'react';
import '../EpicMenu.css';
import firebase from 'firebase';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
import searchIcon from '../search-icon.png';
firebase.initializeApp({
apiKey: '<KEY>',
authDomain: 'cookit-39cc5.firebaseapp.com',
});
class EpicMenu extends Component {
constructor() {
super();
this.state = {
showForm: false,
showMenu: false,
isSignedIn: false,
};
this.uiConfig = {
signInFlow: 'popup',
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
],
callbacks: {
signInSuccess: () => false,
},
};
}
componentDidMount() {
firebase.auth().onAuthStateChanged((user) => {
this.setState({ isSignedIn: !!user });
console.log('user', user);
});
}
showForm() {
this.setState({
showForm: !this.state.showForm,
});
}
showMenu() {
this.setState({
showMenu: !this.state.showMenu,
});
}
render() {
const searchForm = this.state.showForm ? (
<form className="menu__search-form" method="POST">
<input className="menu__search-input" placeholder="Type and hit enter" />
</form>
) : (
''
);
const loginForm = this.state.showMenu ? (
<form className="login-form" method="POST">
<StyledFirebaseAuth uiConfig={this.uiConfig} firebaseAuth={firebase.auth()} />
</form>
) : (
''
);
const linksMarkup = this.props.links.map((link, index) => {
const linkMarkup = link.active ? (
<a className="menu__link menu__link--active" href={link.link}>
{link.label}
</a>
) : (
<a className="menu__link" href={link.link}>
{link.label}
</a>
);
return (
<li key={index} className="menu__list-item">
{linkMarkup}
</li>
);
});
return (
<nav className="menu">
<h1
style={{
backgroundImage: `url(${this.props.logo})`,
}}
className="menu__logo"
>
CookIt.
</h1>
<div className="menu__right">
<ul className="menu__list">{linksMarkup}</ul>
<button
onClick={this.showForm.bind(this)}
style={{
backgroundImage: `url(${searchIcon})`,
}}
className="menu__search-button"
/>
{searchForm}
<button onClick={this.showMenu.bind(this)} className="login-button">
Login
</button>
{loginForm}
</div>
</nav>
);
}
}
export default EpicMenu;
<file_sep>/frontend/src/functions.js
const fetch = require('node-fetch');
let apiKey = '<KEY>';
async function getRecipeByIngredients(ingredentsArray, setRecipes) {
let ingredientsString = ingredentsArray.join(',');
let recipesList = await (await fetch(`https://api.spoonacular.com/recipes/findByIngredients?apiKey=${apiKey}&ingredients=${ingredientsString}&number=10`)).json();
let recipes = recipesList.map(recipe => {
return {
image: recipe.image,
title: recipe.title,
missedIngredients: recipe.missedIngredients,
usedIngredients: recipe.usedIngredients,
unusedIngredients: recipe.unusedIngredients,
id: recipe.id,
}
});
setRecipes(recipes);
}
async function optimizeIngredients(recipe) {
let missedIngredientsArray = recipe.missedIngredients.map(item => item.name);
let unusedIngredientsArray = recipe.unusedIngredients.map(item => item.name);
let substitutesList = await Promise.all(await missedIngredientsArray.map(async (item) => await getSubstitute(item)));
let replacable = substitutesList.map(missedItem => {
//check if exists on sublist
if (missedItem !== 'no substitute') {
let substituteInUnused = 'no substitute';
for (item of missedItem.substitutes) {
let includes = 0;
for (let i of item.substitute.name) {
includes = unusedIngredientsArray.includes(i);
}
if (includes) {
substituteInUnused = item;
break;
}
}
if (substituteInUnused !== 'no substitute') {
return { name: missedItem.name, baseAmount: substituteInUnused.baseAmount, baseUnit: substituteInUnused.baseUnit, substitute: substituteInUnused.substitute }
} else
return 'no substitute'
} else
return 'no substitute'
})
let missedIngredients = recipe.missedIngredients.map(item => {
return {
amount: item.amount,
unit: item.unit,
name: item.name,
image: item.image,
id: item.id,
type: 'missed',
}
})
let usedIngredients = recipe.usedIngredients.map(item => {
return {
amount: item.amount,
unit: item.unit,
name: item.name,
image: item.image,
id: item.id,
type: 'used',
}
})
let removedAndReplaced = {};
for (let item of replacable) {
if (item !== 'no substitute') {
let index = missedIngredientsArray.indexOf(item.name);
let sourceUnit = missedIngredients[index].unit;
let sourceAmount = missedIngredients[index].amount;
console.log(sourceUnit, sourceAmount, item.baseUnit);
let targetConversion = await (await fetch(`https://api.spoonacular.com/recipes/convert?apiKey=${apiKey}ingredientName=${item.name}&sourceAmount=${sourceAmount}&sourceUnit=${sourceUnit}&targetUnit=${item.baseUnit}`)).json();
let mult = sourceAmount;
if (targetConversion.targetAmount) {
mult = targetConversion.targetAmount
}
let replacement = {};
replacement.name = item.substitute.name.join(',');
replacement.unit = item.substitute.unit.join(',');
replacement.amount = Number(mult) * Number(item.substitute.amount) / Number(item.baseAmount);
replacement.image = '';
replacement.id = '';
replacement.type = 'used';
usedIngredients.push(replacement);
removedAndReplaced = { removed: missedIngredients.splice(index, 1), replaced: replacement.name };
}
}
return { used: usedIngredients, missed: missedIngredients, removed: removedAndReplaced.removed, replaced: removedAndReplaced.replaced };
}
/// WORKS
async function getSubstitute(missedIngredient) {
let data = await (await fetch(`https://api.spoonacular.com/food/ingredients/substitutes?apiKey=${apiKey}&ingredientName=${missedIngredient}`)).json();
if (data.status === "success") {
let obj = {
name: missedIngredient,
substitutes: analyzeSubstitutesList(data.substitutes),
}
return obj;
}
else {
return 'no substitute'
}
}
/// WORKS
function analyzeSubstitutesList(substitutesList) {
if (substitutesList) {
let analyzedSubstitutes = substitutesList.map(item => {
let arr = item.split(' = ');
let words = arr[0].split(' ');
let subObj = {
baseAmount: words[0],
baseUnit: words[1],
substitute: '',
}
if (arr[1].includes(' and ') || arr[1].includes(' + ')) {
let arr2 = arr[1].includes(' and ') ? arr[1].split(' and ') : arr[1].split(' + ');
let amount = [];
let name = [];
let unit = [];
arr2.map(item => {
let words = item.split(' ');
amount.push(words.splice(0, 1));
unit.psuh(words.splice(0, 1))
name.push(words.join(' '));
})
subObj.substitute = { amount: amount, unit: unit, name: name };
}
else {
let words = arr[1].split(' ');
subObj.substitute = { amount: [words.splice(0, 1)], unit: [words.splice(0, 1)], name: [words.join(' ')] }
}
return subObj;
})
return analyzedSubstitutes;
}
}
/// WORKS P4
async function getRecipeInstructions(recipeId, setInstructions) {
let data = await (await fetch(`https://api.spoonacular.com/recipes/${recipeId}/analyzedInstructions?apiKey=${apiKey}`)).json();
let instructions = data[0].steps.map(item => item.step)
setInstructions(instructions);
}
export { getRecipeByIngredients, getRecipeInstructions, optimizeIngredients };<file_sep>/frontend/src/component/FirstSection.jsx
import React from 'react';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import Container from '@material-ui/core/Container';
import Image from '../recipe.jpg';
const FirstSection = () => {
return (
<>
<CssBaseline />
<Container
style={{
backgroundImage: 'url(' + Image + ')',
backgroundSize: 'cover',
height: '75vh',
position: 'relative',
maxWidth:"none"
}}
>
<div style={{ position: 'absolute', right: 90, bottom: 80 }}>
<h2 className="text-white" style={{ position: 'relative' }}>
Find the Perfect Recipe
</h2>
<Button
variant="contained"
color="primary"
href="#contained-buttons"
style={{
backgroundColor: 'red',
position: 'absolute',
right: 0,
bottom: -55,
}}
>
Link
</Button>
</div>
</Container>
</>
);
};
export default FirstSection;
<file_sep>/frontend/src/component/Recipes.jsx
import React, { useState, useEffect } from 'react';
import { Card, Icon } from 'antd';
import 'antd/dist/antd.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Badge } from 'react-bootstrap';
const { Meta } = Card;
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import CssBaseline from '@material-ui/core/CssBaseline';
import Image from '../recipe.jpg';
const Recipes = ({ recipes }) => {
return (
<>
<CssBaseline />
<Container
style={{
padding: 'auto',
}}
>
<Grid container spacing={6} style={{}}>
{recipes ? (
recipes.map(recipe => {
return (
<Grid item xs={12} sm={6} md={4} lg={4}>
<Card
style={{ width: 215 }}
cover={<img alt="example" src={recipe.image} />}
actions={[<Icon type="heart" />, <Icon type="double-right" />]}
>
<Meta title={recipe.title} />
<Badge variant="danger">{recipe.missedIngredients.length}</Badge>
<Badge variant="success">{recipe.usedIngredients.length}</Badge>
</Card>
</Grid>
);
})
) : (
<div>PLEASE TYPE IN INGREDIENTS</div>
)}
</Grid>
</Container>
</>
);
};
export default Recipes;
|
bc1a2e0b0006a31a8a670c0c1ab07f45543703c1
|
[
"JavaScript"
] | 5
|
JavaScript
|
ebruispir/class-5-project-cookit
|
d0cdeddde6d7c28cde4394739cf6cbde2af67fb4
|
db08cd9f66a6f8e9a90830002abb9957225bac92
|
refs/heads/master
|
<file_sep>package dbUtils;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class test {
// 需求:向user表插入一条数据
public void test1() {
// 第一步:创建queryRunner对象,用来操作sql语句
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
// 第二步:创建sql语句
String sql = "insert into user values(?,?,?,?)";
// 第三步:执行sql语句,params:是sql语句的参数
// 注意,给sql语句设置参数的时候,按照user表中字段的顺序
try {
int update = qr.update(sql,6,"狗蛋",18,"北京");
System.out.println(update);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 需求:修改id为2的数据
public void test2() {
// 第一步:创建queryRunner对象,用来操作sql语句
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
// 第二步:创建sql语句
String sql = "update user set name = ? where id = ?";
// 第三步:执行sql语句,params:是sql语句的参数
// 注意,给sql语句设置参数的时候,按照user表中字段的顺序
try {
int update = qr.update(sql, "小柳", 2);
System.out.println(update);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 需求:删除id为3的数据
public void test3() {
// 第一步:创建queryRunner对象,用来操作sql语句
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
// 第二步:创建sql语句
String sql = "delete from user where id = ?";
// 第三步:执行sql语句,params:是sql语句的参数
// 注意,给sql语句设置参数的时候,按照user表中字段的顺序
try {
int update = qr.update(sql, 3);
System.out.println(update);
} catch (SQLException e) {
e.printStackTrace();
}
}
//查询数据表中所有数据
public void test4() {
//创建连接
QueryRunner qr=new QueryRunner(new ComboPooledDataSource());
String sql="select * from user";
try {
List<User> user=qr.query(sql, new BeanListHandler<User>(User.class));
for(User u:user) {
System.out.println(u.getId()+"\t"+u.getName()+"\t"+u.getAge()+"\t"+u.getAddress());
}
JDBCUtils.closeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
test t=new test();
t.test1();
}
}
|
20e7e104a12d59e39e53f2008d59737cd5e80c40
|
[
"Java"
] | 1
|
Java
|
luoxiang01/dbUtilsTest
|
c06d6875de63881376780495a77c528e962f2f7a
|
532e3c7e2408385a1fbc3d6b7e98056d8422b5e5
|
refs/heads/master
|
<file_sep>using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BS_Notatnik
{
public partial class Form1 : Form
{
string filename;
bool isSaved;
string filePath;
private void saveFile()
{
var fileContent = openedFile.Text;
//var filePath = string.Empty;
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.InitialDirectory = "c:\\";
saveFileDialog.Filter = "Dokumenty tekstowe (*.txt)|*.txt|Wszystkie pliki (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
filePath = saveFileDialog.FileName;
using (StreamWriter writer = new StreamWriter(filePath, false))
{
writer.Write(fileContent);
}
}
}
if (filePath != "")
{
setFilename(Path.GetFileName(filePath));
isSaved = true;
setTitle(this.filename);
}
}
private void setFilePath(string newFilePath)
{
this.filePath = newFilePath;
}
private string getFilePath()
{
return this.filePath;
}
private void setFilename(string newFilename)
{
this.filename = newFilename;
setTitle(filename);
}
private string getFilename()
{
return this.filename;
}
private void setTitle(string filename)
{
if(this.isSaved)
this.Text = this.filename + " - BladeStudios Notatnik";
else
this.Text = "*" + this.filename + " - BladeStudios Notatnik";
}
public Form1()
{
InitializeComponent();
this.isSaved = true;
setFilename("Bez tytułu");
setFilePath("");
}
private void plikOtworz_Click(object sender, EventArgs e)
{
var fileContent = string.Empty;
//var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
openedFile.Text = fileContent;
if(filePath!="")
{
setFilename(Path.GetFileName(filePath));
this.isSaved = true;
this.setTitle(this.filename);
}
}
private void formResize(object sender, EventArgs e)
{
openedFile.Width = this.Width - 15;
openedFile.Height = this.Height - 65;
}
private void plikNowy_Click(object sender, EventArgs e)
{
//TODO - w przypadku zmian zapytanie czy zapisac zmiany
openedFile.Text = "";
setFilename("Bez tytułu");
}
private void plikNoweOkno_Click(object sender, EventArgs e)
{
Thread _thread = new Thread(() =>
{
Application.Run(new Form1());
});
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
}
private void plikZapisz_Click(object sender, EventArgs e)
{
if(this.getFilePath()=="")
{
saveFile();
}
else
{
var fileContent = openedFile.Text;
using (StreamWriter writer = new StreamWriter(filePath, false))
{
writer.Write(fileContent);
}
this.isSaved = true;
this.setTitle(this.filename);
}
}
private void plikZapiszJako_Click(object sender, EventArgs e)
{
saveFile();
}
private void openedFile_TextChanged(object sender, EventArgs e)
{
isSaved = false;
setTitle(this.filename);
}
private void plikZakoncz_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void edycjaZaznaczWszystko_Click(object sender, EventArgs e)
{
openedFile.SelectAll();
}
private void edycjaKopiuj_Click(object sender, EventArgs e)
{
Clipboard.SetText(openedFile.SelectedText);
}
private void edycjaWklej_Click(object sender, EventArgs e)
{
if(Clipboard.ContainsText())
{
openedFile.Paste();
}
}
private void edycjaWytnij_Click(object sender, EventArgs e)
{
Clipboard.SetText(openedFile.SelectedText);
openedFile.SelectedText = "";
}
private void edycjaUsun_Click(object sender, EventArgs e)
{
openedFile.SelectedText = "";
}
}
}
<file_sep># BS-Notatnik
My own version of Notepad
|
44307a862454be0532078d08eb73c3a95c6e2a90
|
[
"Markdown",
"C#"
] | 2
|
C#
|
BladeStudios/BS-Notatnik
|
82edb61b88cf154b24bd96feb23104284675854c
|
2dec0b925443ad4490e275802d1a913c2dd8df22
|
refs/heads/master
|
<repo_name>tuxiaomao/study_Java21days_1st<file_sep>/src/day01_环境准备/day01_2答案.java
package day01_环境准备;
public class day01_2答案 {
public static void main(String[] args){
System.out.println("HelloWorld");
}
}
|
731bf1c00441d4a7943b39bf90039856569d0b92
|
[
"Java"
] | 1
|
Java
|
tuxiaomao/study_Java21days_1st
|
8931b13277f7976378fe09b399d539188ed7e7f3
|
2a03cec274bf525c06071706ffcccf09d4c6f3f0
|
refs/heads/main
|
<repo_name>MikeVaida/CS50<file_sep>/Week2/string.c
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string s = get_string("Input: ");
printf("Output: ");
// int n = strlen(s); - this can be included in the for loop
// for (int i = 0; s[i] != '\0'; i++)
// for (int i = 0; i < strlen(s); i++) - this better written
for (int i = 0, n = strlen(s); i < n; i++)
{
printf("%c", s[i]);
}
printf("\n");
}
<file_sep>/Week2/hi.c
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// char c = '#';
// char c1 = 'H';
// char c2 = 'I';
// char c3 = '!';
string s = "HI!";
// printf("%s\n", s);
// printf("%c %c %c\n", s[0], s[1], s[2]);
printf("%i %i %i %i\n", s[0], s[1], s[2], s[3]);
}
<file_sep>/Week2/scores.c
#include <cs50.h>
#include <stdio.h>
const int TOTAL = 3;
float average(int x, int y[]);
int main(void)
{
// int score1 = 72;
// int score2 = 73;
// int score3 = 33;
// int scores[3];
// scores[0] = get_int("Scores: ");
// scores[1] = get_int("Scores: ");
// scores[2] = get_int("Scores: ");
int scores[TOTAL];
for (int i = 0; i < TOTAL; i++)
{
scores[i] = get_int("Score: ");
}
// printf("Average: %f\n", (score1 + score2 + score3) / (float) 3 or 3.0);
printf("Average: %.2f\n", average(TOTAL, scores));
}
float average(int x, int y[])
// x = length, TOTAL. y = the array, scores[]
{
int sum = 0;
for (int i = 0; i < x; i++)
{
sum += y[i];
}
return sum / (float) x;
}
<file_sep>/README.md
# CS50
CS50 Exercises
My first steps in learning computer programming.
- Week 0: Scratch
- Week 1: C
- Week 2: Arrays
- Week 3: Algorithms
- Week 4: Memory
- Week 5: Data Structures
- Week 6: Python
- Week 7: SQL
- Week 8: HTML, CSS, JavaScript
- Week 9: Flask
- Week 10: Ethics
<file_sep>/Week2/brick.c
#include <stdio.h>
// a simple program that casts a the # symbol to the numerical representation
int main(void)
{
char c = '#';
// printf("%c\n", c);
printf("%i\n", (int) c);
}
|
65b8cfedda15ea91ce599a5fdef2fe1a8eb46af5
|
[
"Markdown",
"C"
] | 5
|
C
|
MikeVaida/CS50
|
51565ac95c165ee19844217fe27048ddad4fe89a
|
2a0ab1cee0680f0c368ff60b41e7b60d27d0a9d3
|
refs/heads/master
|
<repo_name>Yu-Zhou-1/path-planning<file_sep>/scenes_models/scene_config.lua
function sysCall_init()
-- do some initialization here
L, W = 10, 2
generate_floor(L, W)
lookdown_viewport(L, W)
-- visualize_path({0,0,0.5,1,1,0.5,2,4,0.5})
delete_path()
end
function sysCall_nonSimulation()
-- is executed when simulation is not running
end
function sysCall_beforeSimulation()
-- is executed before a simulation starts
end
function sysCall_afterSimulation()
-- is executed before a simulation ends
end
function sysCall_cleanup()
-- do some clean-up here
end
function lookdown_viewport(L, W)
-- L: length of the floor
-- W: width of the floor
default_camera = sim.getObjectHandle('DefaultCamera')
sim.setObjectOrientation(default_camera, -1, {-math.pi, 0, math.pi})
hL = 4.327*math.ceil(L/5)
hW = 6.2*math.ceil(W/5)
-- sim.addStatusbarMessage(hL .. ' ' .. hW)
h = math.max(hL, hW) + 0.5
sim.setObjectPosition(default_camera, -1, {0, 0, h})
end
function generate_obstacles()
generate_circle = function()
end
generate_prism = function()
end
generate_prism_tree = function()
end
end
function visualize_path(path, color)
-- path
-- color
if not color then
color = {0.2, 0.2, 0.2}
end
if not _lineContainer then
_lineContainer=sim.addDrawingObject(sim.drawing_lines,3,0,-1,99999, color)
end
sim.addDrawingObjectItem(_lineContainer,nil)
if path then
local pc=#path/3
for i=1,pc-1,1 do
lineDat={path[(i-1)*3+1],path[(i-1)*3+2],path[(i-1)*3+3],path[i*3+1],path[i*3+2],path[i*3+3]}
sim.addDrawingObjectItem(_lineContainer,lineDat)
end
end
end
function delete_path()
if _lineContainer then
sim.removeDrawingObject(_lineContainer)
sim.addStatusbarMessage("The line was removed")
end
end
function generate_floor(L, W)
-- generate the floor
-- L: length > 0
-- W: width > 0
model = sim.getObjectHandle('ResizableFloor_5_25')
e1=sim.getObjectHandle('ResizableFloor_5_25_element')
e2=sim.getObjectHandle('ResizableFloor_5_25_visibleElement')
if (L <= 0) or (W <= 0) then
return
end
local sx=math.ceil(L/5)
local sy=math.ceil(W/5)
sim.addStatusbarMessage(sx .. " " .. sy)
local sizeFact=sim.getObjectSizeFactor(model)
sim.setObjectParent(e1,-1,true)
local child=sim.getObjectChild(model,0)
while child~=-1 do
sim.removeObject(child)
child=sim.getObjectChild(model,0)
end
local xPosInit=(sx-1)*-2.5*sizeFact
local yPosInit=(sy-1)*-2.5*sizeFact
local f1,f2
for x=1,sx,1 do
for y=1,sy,1 do
if (x==1)and(y==1) then
sim.setObjectParent(e1,model,true)
f1=e1
else
f1=sim.copyPasteObjects({e1},0)[1]
f2=sim.copyPasteObjects({e2},0)[1]
sim.setObjectParent(f1,model,true)
sim.setObjectParent(f2,f1,true)
end
local p=sim.getObjectPosition(f1, sim.handle_parent)
p[1]=xPosInit+(x-1)*5*sizeFact
p[2]=yPosInit+(y-1)*5*sizeFact
sim.setObjectPosition(f1,sim.handle_parent,p)
end
end
end
<file_sep>/server_joystick.py
import socket
import struct
import time
import cv2
import numpy
import pymavlink.mavutil as mavutil
from multiprocessing import Value
import multiprocessing
from multiprocessing import Value
import argparse
class Carame_Accept_Object:
def __init__(self,S_addr_port=("",65432)):
self.resolution=(640,480)
self.img_fps=30
self.addr_port=S_addr_port
self.Set_Socket(self.addr_port)
def Set_Socket(self,S_addr_port):
self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.server.bind(S_addr_port)
self.server.listen(5)
def getValue(cam_triggered):
trigger_threhold = 1500
while True:
the_connection = mavutil.mavlink_connection('/dev/ttyUSB0',baud=921600)
the_connection.wait_heartbeat()
cam_triggered_value = the_connection.messages['RC_CHANNELS'].chan9_raw
if cam_triggered_value > trigger_threhold:
with cam_triggered.get_lock():
cam_triggered.value = 1
else:
with cam_triggered.get_lock():
cam_triggered.value = 0
def check_option(object,client):
info=struct.unpack('lhh',client.recv(12))
if info[0]>888:
object.img_fps=int(info[0])-888
object.resolution=list(object.resolution)
object.resolution[0]=info[1]
object.resolution[1]=info[2]
object.resolution = tuple(object.resolution)
return 1
else:
return 0
def RT_Image(object,client,D_addr,filename,cam_triggered):
if(check_option(object,client)==0):
return
camera=cv2.VideoCapture(0)
img_param=[int(cv2.IMWRITE_JPEG_QUALITY),object.img_fps]
width = camera.get(cv2.CAP_PROP_FRAME_WIDTH)
height = camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = 30
camera.set(cv2.CAP_PROP_FPS, fps)
print(width, height, fps)
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
size = (int(width),int(height))
out=cv2.VideoWriter(filename, fourcc, int(fps), size)
while(1):
time.sleep(0.1)
_,object.img=camera.read()
cam_triggered_value = cam_triggered.value
if int(cam_triggered_value) > 0:
out.write(object.img)
object.img=cv2.resize(object.img,object.resolution)
_,img_encode=cv2.imencode('.jpg',object.img,img_param)
img_code=numpy.array(img_encode)
object.img_data=img_code.tostring()
try:
client.send(struct.pack("lhh",len(object.img_data),object.resolution[0],object.resolution[1])+object.img_data)
except:
camera.release()
out.release()
return
if __name__ == '__main__':
arg = argparse.ArgumentParser(description='load video and save')
arg.add_argument('--filename',type=str,default='out.avi',help='filename and filepath')
opt = arg.parse_args()
camera=Carame_Accept_Object()
cam_triggered = Value('d', 0)
while (1):
client,D_addr=camera.server.accept()
clientProcess=multiprocessing.Process(None,target=RT_Image,args=(camera,client,D_addr,opt.filename,cam_triggered,))
valueProcess = multiprocessing.Process(None,target=getValue, args=(cam_triggered, ))
clientProcess.start()
valueProcess.start()<file_sep>/README.md
# path-planning
Path planning algorithms basded on CoppliaSim platform.
<file_sep>/rc.py
import serial
serial_, baud = '/dev/ttyUSB0', '2000000'
ser = serial.Serial(serial_, str(baud))
def rc(channel_num):
"""
param: serial_, type=str, e.g '/dev/ttyUSB0'
param: baud, type=int e.g 9600
param: channel_num, type=int
"""
# ser = serial.Serial('/dev/ttyUSB0', '9600')
rc_channels_all = 5
data = ser.read(channel_num * 8)
rc_data_str = data.split()
rc_data = [[] for i in range(rc_channels_all)]
q = 0
for i in rc_data_str:
list_i = list(i)
n = len(list_i)
flag = 0
rc_data_ = []
for j in range(n):
if list_i[j] is not ":" :
flag = flag
else:
flag = flag + 1
continue
if flag > 0:
rc_data_.append(list_i[j])
rc_data[q] = int(''.join(rc_data_))
q += 1
return rc_data
if __name__ == '__main__':
import time
for i in range(1000):
a = rc(5)
time.sleep(0.01)
print(a)
ser.close()
<file_sep>/plugin.py
import rospy
import geometry_msgs.msg
from threading import Thread
from mavros_msgs.msg import HilSensor
from mavros_msgs.msg import HilGPS
from mavros_msgs.msg import HilStateQuaternion
from mavros_msgs.msg import HilActuatorControls
from mavros_msgs.msg import RCIn
from mavros_msgs.msg import HomePosition
from std_msgs.msg import Float32
import math
import numpy as np
import time
# import rc
# import serial
lla = np.zeros(3)
gyro_data = np.zeros(3)
acc_data = np.zeros(3)
mag_data = np.zeros(3)
v_ned = np.zeros(3)
quaternion_data = np.zeros(4)
local_position = np.zeros(3)
angular_velocity = np.zeros(3)
actuators_controls = np.zeros(4)
sim_time = 0.0
v_loc = np.zeros(3)
mode = 0
def plugin():
rospy.init_node('plugin', anonymous=True)
rospy.Subscriber('/gps_data', geometry_msgs.msg.Vector3, callback_gps)
rospy.Subscriber('/gyro_data', geometry_msgs.msg.Vector3, callback_gyro)
rospy.Subscriber("/acc_data", geometry_msgs.msg.Vector3, callback_acc)
rospy.Subscriber("/sim_ros_interface/mag_data", geometry_msgs.msg.Vector3, callback_mag)
rospy.Subscriber("/sim_ros_interface/local_velocity", geometry_msgs.msg.Vector3, callback_vel_loc)
rospy.Subscriber("/vehicleQuaternion", geometry_msgs.msg.Quaternion, callback_quaternion)
rospy.Subscriber("/sim_ros_interface/angular_velocity", geometry_msgs.msg.Vector3, callback_vel_a)
rospy.Subscriber("/simulationTime", Float32, callback_time)
rospy.Subscriber("/vehiclePosition", geometry_msgs.msg.Point, callback_loc_pos)
rospy.Subscriber("/sim_ros_interface/velocity_ned", geometry_msgs.msg.Vector3, callback_vel_ned)
rospy.Subscriber("/mavros/hil/actuator_controls", HilActuatorControls, callback_control)
pub_gps = rospy.Publisher('/mavros/hil/gps', HilGPS, queue_size=1)
pub_imu = rospy.Publisher('/mavros/hil/imu_ned', HilSensor, queue_size=1)
pub_state_quaternion = rospy.Publisher('/mavros/hil/state', HilStateQuaternion, queue_size=1)
pub_thread_1 = Thread(target=gps_publisher, name='gps_publisher', args=(pub_gps,))
pub_thread_1.start()
pub_thread_2 = Thread(target=imu_publisher, name='imu_publisher', args=(pub_imu,))
pub_thread_2.start()
pub_thread_3 = Thread(target=state_quaternion_publisher, name='state_quaternion_publisher', args=(pub_state_quaternion,))
pub_thread_3.start()
# publish control signal
pub_control_1 = rospy.Publisher('px4_control_1', Float32, queue_size=1)
pub_control_2 = rospy.Publisher('px4_control_2', Float32, queue_size=1)
pub_control_3 = rospy.Publisher('px4_control_3', Float32, queue_size=1)
pub_control_4 = rospy.Publisher('px4_control_4', Float32, queue_size=1)
pub_thread_4 = Thread(target=control_publisher, name='control_1_publisher',
args=(pub_control_1, pub_control_2, pub_control_3, pub_control_4,))
pub_thread_4.start()
pub_home = rospy.Publisher("/mavros/home_position/set", HomePosition, queue_size=1)
pub_thread_5 = Thread(target=home_publisher, name='home_publisher', args=(pub_home, ))
pub_thread_5.start()
rospy.spin()
def callback_gps(data):
global lla
"""latitude and longitude in degree, altitude in m"""
lla[0] = data.x
lla[1] = data.y
lla[2] = data.z
def callback_gyro(data):
global gyro_data
gyro_data[0] = data.x
gyro_data[1] = data.y
gyro_data[2] = data.z
def callback_acc(data):
"""Acceleration unit: mG, type: init16 in HilStateQuaternion, but the unit: m/s/s,
type: float in HilSensor
"""
global acc_data
acc_data[0] = data.x
acc_data[1] = data.y
acc_data[2] = data.z
def callback_mag(data):
global mag_data
"""magnetic data in Tesla"""
mag_data[0] = data.x * 10**(-4)
mag_data[1] = data.y * 10**(-4)
mag_data[2] = data.z * 10**(-4)
# rospy.loginfo(mag_data)
def callback_vel_loc(data):
"""velocity in aircraft frame m/s/s"""
global v_loc
v_loc[0] = data.x
v_loc[1] = data.y
v_loc[2] = data.z
def callback_vel_ned(data):
"""velocity in NED frame m/s/s"""
global v_ned
v_ned[0] = data.x
v_ned[1] = data.y
v_ned[2] = data.z
def callback_quaternion(data):
global quaternion_data
quaternion_data[0] = data.x
quaternion_data[1] = data.y
quaternion_data[2] = data.z
quaternion_data[3] = data.w
def callback_vel_a(data):
global angular_velocity
angular_velocity[0] = data.x
angular_velocity[1] = data.y
angular_velocity[2] = data.z
def callback_time(data):
global sim_time
sim_time = data.data
def callback_loc_pos(data):
global local_position
local_position[0] = data.x
local_position[1] = data.y
local_position[2] = data.z
def gps_publisher(pub):
global lla, v_ned, sim_time, v_loc
gps_data = HilGPS()
rate = rospy.Rate(100)
while not rospy.is_shutdown():
# gps_data.header.seq = int(1)
t = math.modf(time.time())
gps_data.header.stamp.secs = int(t[1])
gps_data.header.stamp.nsecs = int(t[0] * 10**9)
gps_data.header.frame_id = "NED"
"""the all frame_id can be found in https://mavlink.io/en/messages/common.html#MAV_FRAME_LOCAL_FRD"""
gps_data.fix_type = 4
gps_data.geo.latitude = lla[0]
gps_data.geo.longitude = lla[1]
gps_data.geo.altitude = -lla[2]
gps_data.ve = v_ned[0]
gps_data.vn = v_ned[1]
gps_data.vd = v_ned[2]
gps_data.ve = v_loc[0]
gps_data.eph = 0.8
gps_data.epv = 1.5
"""eph and epv means horizontal position error and vertical position error,unit is (m)"""
gps_data.cog = 65436
gps_data.satellites_visible = 10
pub.publish(gps_data)
rate.sleep()
def barometric(z, v):
"""calculate barometric pressure
param: z local position z up+, down-
param: v local velocity"""
alt_home = 0.0
lapse_rate = 0.0065
""""(kelvin/m)"""
temperature_msl = 288.0
"""mean sea level temperature(kelvin)"""
alt_msl = alt_home + z
temperature_local = temperature_msl - lapse_rate * alt_msl
pressure_ratio = (temperature_msl / temperature_local) ** 5.256
pressure_msl = 101325.0
"""pressure at mean sea level (Pa)"""
absolute_pressure = pressure_msl / pressure_ratio + np.random.normal(0, 1) * 5
density_ratio = (temperature_msl / temperature_local) ** 4.256
rho = 1.225 / density_ratio
"""calculate temperature in Celsius"""
baro_temperature = temperature_local - 273.0 + np.random.normal(0, 1) * 0.1
"""calculate differential pressure (Pa)"""
diff_pressure = 0.5 * rho * v**2 + np.random.normal(0, 1) * 1
"""calculate pressure altitude (m)"""
pressure_alt = 44307.7 * (1 - (absolute_pressure/100/1013.25) ** 0.190284) + np.random.normal(0, 1) * 0.1
return baro_temperature, absolute_pressure, diff_pressure, pressure_alt
def imu_publisher(pub):
"""the sensors data is in baselink frame(Forward, Left, Up),
MAVROS node transfroms them to aircraft frame (Forward, Right, Down). Since the imu frame in coppeliaSim is aircraft
frame, in this part, it needs to transform to FLU frame, thus x = data.x, y = data.y, z = data.z """
global gyro_data, acc_data, mag_data, sim_time, local_position, v_loc
imu_data = HilSensor()
rate = rospy.Rate(500)
while not rospy.is_shutdown():
imu_data.gyro.x = gyro_data[0]
imu_data.gyro.y = gyro_data[1]
imu_data.gyro.z = gyro_data[2]
imu_data.acc.x = acc_data[0]
imu_data.acc.y = acc_data[1]
imu_data.acc.z = acc_data[2]
imu_data.mag.x = mag_data[0]
imu_data.mag.y = mag_data[1]
imu_data.mag.z = mag_data[2]
barometric_sensor = barometric(-local_position[2], v_loc[2])
imu_data.temperature = barometric_sensor[0]
imu_data.abs_pressure = barometric_sensor[1]
imu_data.diff_pressure = barometric_sensor[2]
"""the pressure unit is Pascal"""
imu_data.pressure_alt = barometric_sensor[3]
imu_data.header.seq = int(1)
t = math.modf(time.time())
imu_data.header.stamp.secs = int(t[1])
imu_data.header.stamp.nsecs = int(t[0] * 10 ** 9)
imu_data.header.frame_id = 'FRD'
imu_data.fields_updated = int(2 ** 18-1)
# imu_data.fields_updated = 0
pub.publish(imu_data)
rate.sleep()
def state_quaternion_publisher(pub):
global angular_velocity, lla, v_ned, acc_data, quaternion_data, v_loc
state_quaternion = HilStateQuaternion()
rate = rospy.Rate(500)
while not rospy.is_shutdown():
state_quaternion.angular_velocity.x = angular_velocity[0]
state_quaternion.angular_velocity.y = angular_velocity[1]
state_quaternion.angular_velocity.z = angular_velocity[2]
state_quaternion.geo.latitude = lla[0]
state_quaternion.geo.longitude = lla[1]
state_quaternion.geo.altitude = -lla[2]
state_quaternion.orientation.w = quaternion_data[3]
state_quaternion.orientation.x = quaternion_data[0]
state_quaternion.orientation.y = quaternion_data[1]
state_quaternion.orientation.z = quaternion_data[2]
state_quaternion.linear_acceleration.x = acc_data[0]
state_quaternion.linear_acceleration.y = acc_data[1]
state_quaternion.linear_acceleration.z = acc_data[2]
state_quaternion.linear_velocity.x = v_loc[0]
state_quaternion.linear_velocity.y = v_loc[1]
state_quaternion.linear_velocity.z = v_loc[2]
state_quaternion.ind_airspeed = v_loc[0]
state_quaternion.true_airspeed = v_loc[0]
t = math.modf(time.time())
state_quaternion.header.stamp.secs = int(t[1])
state_quaternion.header.stamp.nsecs = int(t[0] * 10**9)
state_quaternion.header.seq = int(1)
pub.publish(state_quaternion)
rate.sleep()
def callback_control(data):
global actuators_controls, mode
j = 0
mode = data.mode
for i in data.controls:
if i < 0:
i = 0
actuators_controls[j] = i
j += 1
if j > 3:
break
rospy.loginfo(actuators_controls)
def control_publisher(pub1, pub2, pub3, pub4):
global actuators_controls, mode
rate = rospy.Rate(300)
while not rospy.is_shutdown():
if mode == 129:
pub1.publish(actuators_controls[0])
pub2.publish(actuators_controls[1])
pub3.publish(actuators_controls[2])
pub4.publish(actuators_controls[3])
rate.sleep()
def rc_publisher(pub):
# publish rc signal
rc_data = RCIn()
rc_input = np.zeros(12)
rate = rospy.Rate(3000)
while not rospy.is_shutdown():
rc_input[0:5] = rc.rc(5)
t = math.modf(time.time())
rc_data.header.stamp.secs = int(t[1])
rc_data.header.stamp.nsecs = int(t[0] * 10**9)
rc_data.channels = rc_input
rc_data.rssi = 128
rospy.loginfo(rc_data)
pub.publish(rc_data)
rate.sleep()
def home_publisher(pub):
data = HomePosition()
rate = rospy.Rate(100)
while not rospy.is_shutdown():
t = math.modf(time.time())
data.header.stamp.secs = int(t[1])
data.header.stamp.nsecs = int(t[0] * 10**9)
data.geo.latitude = 39.455
data.geo.longitude = 116.245
data.geo.altitude = 0
data.position.x = 0
data.position.y = 0
data.position.z = 0
data.orientation.x = 0
data.orientation.y = 0
data.orientation.z = 0
data.orientation.w = 1
data.approach.x = 0
data.approach.y = 0
data.approach.z = 0
pub.publish(data)
rate.sleep()
if __name__ == '__main__':
# serial_, baud = '/dev/ttyUSB0', '2000000'
# ser = serial.Serial(serial_, str(baud))
plugin()
|
16c7e3f31197cc4936b5edc6b1e10f1498b3962d
|
[
"Markdown",
"Python",
"Lua"
] | 5
|
Lua
|
Yu-Zhou-1/path-planning
|
668ef90e6dd12724447f19a2d469bbbefeee6716
|
e810808aec34f2c79eeb1156f57d9e928d4ba280
|
refs/heads/master
|
<repo_name>iamtimsmith/.blank<file_sep>/README.md
# .blank
A blank wordpress template with no styling. This contains everything needed to get a theme up and running and add your own styles.
### Files Included
This repo contains all of the basic files needed to get your Wordpress website up and running using standard wordpress setup. There are no styles or frameworks included in this download, which leaves control in your hands. You can use this theme as you'd like for your projects. It will allow you to set up a theme and just focus on styles and the only page you'll have to code is the frontpage.
<file_sep>/functions.php
<?php
// Register Nav Menus
function nav_menus() {
register_nav_menus( array(
'primary' => __( 'Primary Menu','text-domain' ),
'footer' => __( 'Footer Menu','text-domain' )
) );
}
add_action( 'init', 'nav_menus' );
// Add Theme Support
function theme_support() {
add_theme_support( 'custom-logo' );
}
add_action( 'after_setup_theme', 'theme_support' );
// Add Theme Styles
function add_styles() {
wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/css/style.css' );
}
add_action( 'wp_enqueue_scripts', 'add_styles' );
// Add Theme Scripts
function add_scripts() {
wp_enqueue_script( 'jquery', get_template_directory_uri().'/js/jquery.js', false );
}
add_action( 'wp_enqueue_scripts', 'add_scripts' );
// Remove UL from Menus
function wp_nav_menu_no_ul()
{
$options = array(
'echo' => false,
'container' => false,
'theme_location' => 'primary',
'fallback_cb'=> 'fall_back_menu'
);
$menu = wp_nav_menu($options);
echo preg_replace(array(
'#^<ul[^>]*>#',
'#</ul>$#'
), '', $menu);
}
function fall_back_menu(){
return;
}
<file_sep>/404.php
<?php get_header(); ?>
<h1>Oops!</h1>
<h4>We can't find what you're looking for.</h4>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
|
a78660e3f643cfc10f27ca868b8bf21e060d149d
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
iamtimsmith/.blank
|
0c02e3a5da8dc0c06ff39932f2f88aefd8889f8d
|
c251550c6719f767a007b87bb8ba9b35a179e1dd
|
refs/heads/master
|
<file_sep>import Log from "../Util";
import {IInsightFacade, InsightDataset, InsightDatasetKind, ResultTooLargeError} from "./IInsightFacade";
import {InsightError, NotFoundError} from "./IInsightFacade";
import {QueryHelper} from "./QueryHelper";
import {DatasetHelper} from "./DatasetHelper";
import * as fs from "fs-extra";
import {Dataset, SectionKeys} from "./Dataset";
import * as JSZip from "jszip";
import {TransformationHelper} from "./TransformationHelper";
/**
* This is the main programmatic entry point for the project.
* Method documentation is in IInsightFacade
*
*/
// interface Test {
// [key: string]: any;
// }
// const test: Test = {
// dept: "hello",
// 4: 1
// }
export default class InsightFacade implements IInsightFacade {
public static readonly MAXQUERYRESULTS: number = 5000;
constructor() {
Log.trace("InsightFacadeImpl::init()");
}
public addDataset(id: string, content: string, kind: InsightDatasetKind): Promise<string[]> {
if (!DatasetHelper.checkValidId(id, true)) {
return Promise.reject(new InsightError("Invalid dataset id"));
}
if (!DatasetHelper.checkValidZip(content)) {
return Promise.reject(new InsightError("Invalid dataset zip"));
}
if (!DatasetHelper.checkValidKind(kind)) {
return Promise.reject(new InsightError("Invalid dataset kind"));
}
let newZip = new JSZip();
return newZip.loadAsync(content, {base64: true})
.then((zip) => {
if (kind === InsightDatasetKind.Rooms) {
return this.addRooms(zip, id, kind).then((allCurDatasets: string[]) => {
return Promise.resolve(allCurDatasets);
}).catch((error) => {
return Promise.reject(error);
});
} else {
return this.addCourses(zip, id, kind).then((allCurDatasets: string[]) => {
return Promise.resolve(allCurDatasets);
}).catch((error) => {
return Promise.reject(error);
});
}
}).catch((error) => {
return Promise.reject(new InsightError("Invalid zip file"));
});
}
private addRooms(zip: JSZip, id: string, kind: InsightDatasetKind.Rooms): Promise<string[]> {
let roomsArray: any[];
let datasetObject: object;
if (!DatasetHelper.checkValidRoomsFolder(zip)) {
return Promise.reject(new InsightError("Rooms folder does not exist"));
}
const rooms = zip.folder("rooms");
if (!DatasetHelper.checkValidIndextHTM(rooms)) {
return Promise.reject(new InsightError("Invalid index.htm file"));
}
try {
return rooms.file("index.htm").async("string").then((indexHtm: string) => {
return DatasetHelper.getBuildings(zip, indexHtm).then((buildings: object[]) => {
roomsArray = buildings;
if (!roomsArray.length) {
return Promise.reject(new InsightError("No valid rooms in dataset"));
}
datasetObject = DatasetHelper.formDatasetObject(roomsArray, id, kind);
let datasetObjectString = JSON.stringify(datasetObject);
const dataDir: string = __dirname + "/../../data";
if (!fs.existsSync(dataDir)) {
fs.mkdirsSync(dataDir);
}
fs.writeFileSync(dataDir + "/" + id + ".json", datasetObjectString, "utf8");
let allCurDatasets: string[] = DatasetHelper.getAllCurDatasets(dataDir);
return Promise.resolve(allCurDatasets);
}).catch((error) => {
return Promise.reject(new InsightError("buildings error"));
});
}).catch((error) => {
return Promise.reject(new InsightError("Index.htm error"));
});
} catch (e) {
return Promise.reject(new InsightError());
}
}
private addCourses(zip: JSZip, id: string, kind: InsightDatasetKind.Courses): Promise<string[]> {
// Code help from documentation and StackOverflow
// https://stuk.github.io/jszip/documentation/api_jszip/load_async.html
// https://stackoverflow.com/questions/39322964/extracting-zipped-files-using-jszip-in-javascript
try {
let sections: object[] = [];
let datasetObject: object;
let sectionsPromise: any[] = [];
if (!DatasetHelper.checkValidCoursesFolder(zip)) {
return Promise.reject(new InsightError("Courses folder does not exist"));
}
const courses = zip.folder("courses");
courses.forEach((relativePath, file) => {
sectionsPromise.push(file.async("string"));
});
return Promise.all(sectionsPromise).then((sectionsArray: string[]) => {
sections = DatasetHelper.addSections(sectionsArray, id, kind);
if (!sections.length) {
return Promise.reject(new InsightError("No valid sections in dataset"));
}
datasetObject = DatasetHelper.formDatasetObject(sections, id, kind);
let datasetObjectString = JSON.stringify(datasetObject);
const dataDir: string = __dirname + "/../../data";
if (!fs.existsSync(dataDir)) {
fs.mkdirsSync(dataDir);
}
fs.writeFileSync(dataDir + "/" + id + ".json", datasetObjectString, "utf8");
let allCurDatasets: string[] = DatasetHelper.getAllCurDatasets(dataDir);
return Promise.resolve(allCurDatasets);
});
} catch (e) {
return Promise.reject(new InsightError());
}
}
public removeDataset(id: string): Promise<string> {
const dataDir: string = __dirname + "/../../data/" + id + ".json";
if (!DatasetHelper.checkValidId(id, false)) {
return Promise.reject(new InsightError("Invalid dataset id"));
}
if (!(fs.existsSync(dataDir))) {
return Promise.reject(new NotFoundError());
}
try {
fs.unlinkSync(dataDir);
return Promise.resolve(id);
} catch (e) {
return Promise.reject(e);
}
}
public performQuery(query: any): Promise<any[]> {
if (query === undefined || query === null) {
return Promise.reject(new InsightError("Query is null or undefined"));
}
if (!QueryHelper.checkValidWhere(query)) {
return Promise.reject(new InsightError("Missing or invalid WHERE in query"));
}
if (!QueryHelper.checkValidOptions(query)) {
return Promise.reject(new InsightError("Missing or invalid OPTIONS in query"));
}
if (!TransformationHelper.checkValidTransformation(query)) {
return Promise.reject(new InsightError("Invalid TRANSFORMATIONS in query"));
}
if (Object.keys(query).length > 3 ||
(Object.keys(query).length === 3 && !Object.keys(query).includes("TRANSFORMATIONS"))) {
return Promise.reject(new InsightError("Redundant keys in query"));
}
try {
const id: string = QueryHelper.getId(query);
const dataset = JSON.parse(fs.readFileSync("data/" + id + ".json", "utf8"));
let sections: any[] = dataset.data;
const kind = dataset.kind;
let booleanFilter: boolean[];
if (Object.keys(query["WHERE"]).length === 0) {
// empty WHERE matches all sections
booleanFilter = sections.map(() => true);
} else {
booleanFilter = QueryHelper.processFilter(id, kind, query["WHERE"], sections);
}
// remove the sections that do not satisfy the filter
sections = sections.filter((section, index) => booleanFilter[index]);
if (query.hasOwnProperty("TRANSFORMATIONS")) {
const transformResult =
TransformationHelper.processTransform(id, kind, query["TRANSFORMATIONS"], sections);
sections = TransformationHelper.processOptionsTransform(id, kind, query["OPTIONS"],
query["TRANSFORMATIONS"], transformResult);
} else {
if (sections.length > InsightFacade.MAXQUERYRESULTS) {
return Promise.reject(new ResultTooLargeError());
}
sections = QueryHelper.processOptions(id, kind, query["OPTIONS"], sections);
}
if (sections.length > InsightFacade.MAXQUERYRESULTS) {
throw new ResultTooLargeError();
}
return Promise.resolve(sections);
} catch (e) {
return Promise.reject(e);
}
}
public listDatasets(): Promise<InsightDataset[]> {
let datasets: InsightDataset[] = [];
let dataset: InsightDataset;
const dataDir: string = __dirname + "/../../data/";
try {
let datasetsRaw = fs.readdirSync(dataDir);
datasetsRaw.forEach( function (datasetRaw) {
let sectionKind: {"data": any, "kind": InsightDatasetKind, "rows": number} =
JSON.parse(fs.readFileSync(dataDir + datasetRaw, "utf8"));
// let dataset = new InsightDataset(datasetRaw, sectionKind[1], sectionKind[2]);
dataset = {
id: datasetRaw.split(".")[0],
kind: sectionKind.kind,
numRows: sectionKind.rows
};
datasets.push(dataset);
});
return Promise.resolve(datasets);
} catch (e) {
return Promise.resolve(datasets);
}
}
}
<file_sep>import {InsightDatasetKind, InsightError} from "./IInsightFacade";
import * as fs from "fs-extra";
import {RoomKeys, SectionKeys} from "./Dataset";
import Log from "../Util";
import {TransformationHelper} from "./TransformationHelper";
export class QueryHelper {
public static readonly MFIELDS: string[] =
[SectionKeys.Average, SectionKeys.Pass, SectionKeys.Fail, SectionKeys.Audit, SectionKeys.Year,
RoomKeys.Lat, RoomKeys.Lon, RoomKeys.Seats];
public static readonly SFIELDS: string[] =
[SectionKeys.Department, SectionKeys.Id, SectionKeys.Instructor, SectionKeys.Title, SectionKeys.Uuid,
RoomKeys.Fullname, RoomKeys.Shortname, RoomKeys.Number, RoomKeys.Name, RoomKeys.Address, RoomKeys.Type,
RoomKeys.Furniture, RoomKeys.Href];
// return true if WHERE exists, is a non-array object, empty or has exactly one valid key
public static checkValidWhere(query: any): boolean {
if (!Object.keys(query).includes("WHERE") || query["WHERE"] === null || query["WHERE"] === undefined ||
Array.isArray(query["WHERE"]) || query["WHERE"].constructor !== Object) {
return false;
}
if (Object.keys(query["WHERE"]).length === 0) {
return true;
}
return this.checkValidFilter(query["WHERE"]);
}
// return true if OPTIONS exists, is a non-array object, only contains key COLUMNS and possibly ORDER
public static checkValidOptions(query: any): boolean {
if (!Object.keys(query).includes("OPTIONS") || query["OPTIONS"] === null || query["OPTIONS"] === undefined ||
Array.isArray(query["OPTIONS"]) || query["OPTIONS"].constructor !== Object) {
return false;
}
const keys: string[] = Object.keys(query["OPTIONS"]);
if (keys.length === 1) {
return keys[0] === "COLUMNS";
}
if (keys.length === 2) {
return (keys[0] === "COLUMNS" && keys[1] === "ORDER") || (keys[0] === "ORDER" && keys[1] === "COLUMNS");
}
return false;
}
// take a query and return a valid dataset id
// if there is no valid id in query, throw InsightError
// if an id is valid but does not exist in dataset, throw InsightError
public static getId(query: any): string {
// convert query to a string, use regex match to get all ids
const ids: string[] = JSON.stringify(query).match(/[^"'_]+(?=_)/g);
if (ids.length === 0) {
throw new InsightError("Invalid dataset id in query");
}
for (const id of ids) {
if (id !== ids[0]) {
throw new InsightError("Invalid dataset id in query");
}
}
let allSpaces: boolean = true;
for (const c of ids[0]) {
if (c !== " ") {
allSpaces = false;
}
}
if (allSpaces) {
throw new InsightError("Invalid dataset id in query");
}
Log.trace(ids[0]);
if (!fs.existsSync("data/" + ids[0] + ".json")) {
throw new InsightError("Dataset does not exist");
}
return ids[0];
}
// REQUIRE: filter is a JS object, has exactly one key and the key is valid
// if any part of WHERE is invalid, throw InsightError
// if filter is empty, return an all true array
// otherwise, return a boolean array that indicates whether each section satisfies the filter
public static processFilter(id: string, kind: string, filter: any, sections: any[]): any[] {
const filterKey = Object.keys(filter)[0];
let booleanFilter: boolean[]; // a boolean array that indicates whether each section satisfies the filter
switch (filterKey) {
case "AND":
case "OR":
booleanFilter = this.performLogicComparison(id, kind, filter, sections);
break;
case "GT":
case "LT":
case "EQ":
booleanFilter = this.performMComparison(id, kind, filter, sections);
break;
case "IS":
booleanFilter = this.performSComparison(id, kind, filter, sections);
break;
case "NOT":
booleanFilter = this.performNegation(id, kind, filter, sections);
break;
}
return booleanFilter;
}
// REQUIRE: options is a JS object, has key COLUMNS (and possibly ORDER)
// return an array of sections with the keys in columns, sections are sorted if a valid ORDER exists
public static processOptions(id: string, kind: string, options: any, sections: any[]): any[] {
const columnFields: string[] = this.getColumnFields(id, kind, options["COLUMNS"]);
for (const section of sections) {
for (const key in section) {
if (columnFields.includes(key)) {
section[id + "_" + key] = section[key];
}
delete section[key];
}
}
if (!Object.keys(options).includes("ORDER")) {
return sections;
}
if (typeof options["ORDER"] === "string") {
return TransformationHelper.defaultSort(options["ORDER"], options["COLUMNS"], sections);
} else {
return TransformationHelper.customSort(options["ORDER"], options["COLUMNS"], sections);
}
}
private static performLogicComparison(id: string, kind: string, filter: any, sections: any[]): boolean[] {
const logicFunc: string = Object.keys(filter)[0]; // logicFunc is either "AND" or "OR"
// Logic comparison is not followed by an array
if (!Array.isArray(filter[logicFunc])) {
throw new InsightError(logicFunc + " is not followed by an array");
}
// Logic comparison is empty
if (filter[logicFunc].length === 0) {
throw new InsightError("Empty " + logicFunc);
}
let booleanFilter: boolean[];
for (const subFilter of filter[logicFunc]) {
if (!this.checkValidFilter(subFilter)) {
throw new InsightError("Invalid filter in " + logicFunc);
}
booleanFilter = this.combineFilter(logicFunc, booleanFilter,
this.processFilter(id, kind, subFilter, sections));
}
return booleanFilter;
}
private static performMComparison(id: string, kind: string, filter: any, sections: any[]): boolean[] {
const comparator: string = Object.keys(filter)[0];
// the comparison contains zero or more than one mkey
if (Object.keys(filter[comparator]).length !== 1) {
throw new InsightError(comparator + " contains zero or more than one mkey");
}
const mkey: string = Object.keys(filter[comparator])[0];
const mfield: string = this.getField(id, kind, mkey, "M");
// the value to compare is not a number
if (typeof filter[comparator][mkey] !== "number") {
throw new InsightError(
"Cannot compare number to " + typeof filter[comparator][mkey] + " in " + comparator
);
}
let booleanFilter: boolean[];
switch (comparator) {
case "GT":
booleanFilter = sections.map((section) => section[mfield] > filter[comparator][mkey]);
break;
case "LT":
booleanFilter = sections.map((section) => section[mfield] < filter[comparator][mkey]);
break;
case "EQ":
booleanFilter = sections.map((section) => section[mfield] === filter[comparator][mkey]);
break;
}
return booleanFilter;
}
private static performSComparison(id: string, kind: string, filter: any, sections: any[]): boolean[] {
// the comparison contains zero or more than one skey
if (Object.keys(filter["IS"]).length !== 1) {
throw new InsightError("IS contains zero or more than one skey");
}
const skey: string = Object.keys(filter["IS"])[0];
const sfield: string = this.getField(id, kind, skey, "S");
// the value to compare is not a string
if (typeof filter["IS"][skey] !== "string") {
throw new InsightError("Cannot compare string to " + typeof filter["IS"][skey] + " in IS");
}
let inputString: string = filter["IS"][skey];
// input string contains * in between
if (inputString.length > 2 && inputString.substring(1, inputString.length - 1).includes("*")) {
throw new InsightError("Invalid inputstring in IS");
}
let booleanFilter: boolean[];
if (inputString === "*" || inputString === "**") {
booleanFilter = sections.map(() => true);
} else if (inputString[0] === "*" && inputString[inputString.length - 1] === "*") {
booleanFilter = sections.map(
(section) => section[sfield].includes(inputString.substring(1, inputString.length - 1))
);
} else if (inputString[0] === "*") {
booleanFilter = sections.map(
(section) => section[sfield].endsWith(inputString.substring(1))
);
} else if (inputString[inputString.length - 1] === "*") {
booleanFilter = sections.map(
(section) => section[sfield].startsWith(inputString.substring(0, inputString.length - 1))
);
} else {
booleanFilter = sections.map((section) => section[sfield] === inputString);
}
return booleanFilter;
}
private static performNegation(id: string, kind: string, filter: any, sections: any[]): boolean[] {
if (!this.checkValidFilter(filter["NOT"])) {
throw new InsightError("Invalid filter in NOT");
}
let booleanFilter: boolean[] = this.processFilter(id, kind, filter["NOT"], sections);
for (let i in booleanFilter) {
booleanFilter[i] = !booleanFilter[i];
}
return booleanFilter;
}
// return true if filter is a non-empty, non-array JS object and has exactly one valid key
// otherwise, return false
private static checkValidFilter(filter: any): boolean {
if (filter === undefined || filter === null || Array.isArray(filter)) {
return false;
}
if (Object.keys(filter).length !== 1) {
return false;
}
return ["AND", "OR", "GT", "LT", "EQ", "IS", "NOT"].includes(Object.keys(filter)[0]);
}
// if booleanFilter1 is undefined, return booleanFilter2
// otherwise, return a boolean array resulting from applying logicFunc
// on booleanFilter1 and booleanFilter2 entry-wise
private static combineFilter(logicFunc: string, booleanFilter1: boolean[], booleanFilter2: boolean[]) {
if (booleanFilter1 === undefined) {
return booleanFilter2;
}
for (let i in booleanFilter1) {
switch (logicFunc) {
case "AND":
booleanFilter1[i] = (booleanFilter1[i] && booleanFilter2[i]);
break;
case "OR":
booleanFilter1[i] = (booleanFilter1[i] || booleanFilter2[i]);
break;
}
}
return booleanFilter1;
}
// REQUIRE: fieldType is "M", "S", or undefined, id is valid
// "M" refers mfield, "S" refers to sfield
// if key is not of the form id + "_" + a valid section key of type fieldType, throw InsightError
// otherwise return the field that follows the underscore
public static getField(id: string, kind: string, key: any, fieldType: string): string {
if (typeof key !== "string" || !key.includes("_") || key.substring(0, key.indexOf("_")) !== id) {
throw new InsightError("Invalid key");
}
const field: string = key.substring(key.indexOf("_") + 1);
if ((kind === InsightDatasetKind.Courses && !Object.values(SectionKeys).includes(field as SectionKeys)) ||
(kind === InsightDatasetKind.Rooms && !Object.values(RoomKeys).includes(field as RoomKeys))) {
throw new InsightError("Key does not belong to dataset kind");
}
if (fieldType === "M" && !this.MFIELDS.includes(field)) {
throw new InsightError("Expected mkey");
}
if (fieldType === "S" && !this.SFIELDS.includes(field)) {
throw new InsightError("Expected skey");
}
return field;
}
// if columns is not an array or is an empty array, throw InsightError
// otherwise, return an array of distinct fields that appear in query result
private static getColumnFields(id: string, kind: string, columns: any): string[] {
if (!Array.isArray(columns) || columns.length === 0) {
throw new InsightError("COLUMNS is must be a non-empty array");
}
let columnFields: string[] = [];
for (const key of columns) {
let field: string = this.getField(id, kind, key, undefined);
if (!columnFields.includes(field)) {
columnFields.push(field);
}
}
return columnFields;
}
}
<file_sep>import {InsightError, NotFoundError} from "./IInsightFacade";
// http code taken from https://nodejs.org/api/http.html#http_http_get_options_callback
// as per suggestion of TAs and other students on Piazza with minor adaptation
// such as returning a promise since get is async as per TA answer on Piazza
export class GeolocationHelper {
public static getLatLon(buildingInfo: any): Promise<any> {
return new Promise(function (resolve, reject) {
const httpLink = "http://cs310.students.cs.ubc.ca:11316/api/v1/project_team158/";
const httpFull = httpLink + encodeURIComponent(buildingInfo.address);
const http = require("http");
try {
http.get(httpFull, (res: any) => {
const {statusCode} = res;
const contentType = res.headers["content-type"];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error("Request Failed.\n" +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error("Invalid content-type.\n" +
`Expected application/json but received ${contentType}`);
}
if (error) {
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding("utf8");
let rawData = "";
res.on("data", (chunk: any) => {
rawData += chunk;
});
res.on("end", () => {
try {
const parsedData = JSON.parse(rawData);
if (parsedData.error) {
resolve (buildingInfo);
// reject (new InsightError("Cannot get geolocation"));
// throw new InsightError("Cannot get geolocation");
} else {
buildingInfo.lat = parsedData.lat;
buildingInfo.lon = parsedData.lon;
resolve (buildingInfo);
}
} catch (e) {
resolve (buildingInfo);
// reject (new InsightError("Parse error"));
// throw new InsightError();
}
});
});
// }).on("error", (e: any) => {
// return Promise.reject(e);
// // throw new InsightError();
// });
} catch (e) {
resolve (buildingInfo);
// reject (new InsightError("HTTP Get failed"));
// throw new InsightError();
}
});
}
}
<file_sep>import {InsightDatasetKind, InsightError} from "./IInsightFacade";
import * as fs from "fs-extra";
import {Dataset, RoomKeys, SectionKeys} from "./Dataset";
import * as JSZip from "jszip";
import {GeolocationHelper} from "./GeolocationHelper";
const parse5 = require("parse5");
export class DatasetHelper {
// return true if id does not contain underscore, is not undefined, is not null, or is not only whitespaces
// or the dataset already exists (for add)
public static checkValidId(id: any, add: boolean): boolean {
if (id === undefined || id === null) {
return false;
} else if (!(typeof id === "string")) {
return false;
} else if (id.includes("_") || !id.trim().length) {
return false;
} else if (fs.existsSync(__dirname + "/../../data/" + id + ".json") && add) {
return false;
} else {
return true;
}
}
// return true if kind is not Room or is not null or is not undefined
public static checkValidKind(kind: any): boolean {
if (kind === null || kind === undefined) {
return false;
} else {
return true;
}
}
// return true if zip is not undefined or is not null
public static checkValidZip(zip: any): boolean {
if (zip === undefined || zip === null) {
return false;
} else {
return true;
}
}
public static addSections(sectionsArray: any, id: any, kind: any): any[] {
let sections: object[] = [];
sectionsArray.forEach((file: any) => {
let sectionsRaw;
try {
sectionsRaw = JSON.parse(file);
sectionsRaw.result.forEach((sectionRaw: any) => {
let section: { [key in SectionKeys]?: any } = {
[SectionKeys.Department]: sectionRaw.Subject,
[SectionKeys.Id]: sectionRaw.Course,
[SectionKeys.Instructor]: sectionRaw.Professor,
[SectionKeys.Title]: sectionRaw.Title,
[SectionKeys.Uuid]: sectionRaw.id.toString(),
[SectionKeys.Average]: sectionRaw.Avg,
[SectionKeys.Pass]: sectionRaw.Pass,
[SectionKeys.Fail]: sectionRaw.Fail,
[SectionKeys.Audit]: sectionRaw.Audit,
[SectionKeys.Year]: sectionRaw.Section === "overall" ? 1900 : parseInt(sectionRaw.Year, 10)
};
sections.push(section);
});
} catch (e) {// do nothing
}
});
return sections;
}
// Code help from
// https://stackoverflow.com/questions/39939644/jszip-checking-if-a-zip-folder-contains-a-specific-file
// return true if "courses" folder exist in the zip file
public static checkValidCoursesFolder(zip: JSZip): boolean {
if (zip.folder(/courses/).length > 0) {
return true;
} else {
return false;
}
}
public static formDatasetObject(sections: object[], id: string, kind: InsightDatasetKind): any {
let retVal = {
data: sections,
kind: kind,
rows: sections.length
};
return retVal;
}
public static getAllCurDatasets(dataDir: string): string[] {
let allCurDatasetIds: string[] = [];
let datasetsRaw = fs.readdirSync(dataDir);
datasetsRaw.forEach( function (datasetRaw) {
allCurDatasetIds.push(datasetRaw.split(".")[0]);
});
return allCurDatasetIds;
}
public static getBuildings(zip: JSZip, content: string): Promise<object[]> {
try {
const parsedIndexHTM = parse5.parse(content);
let table = this.findTableBody(parsedIndexHTM);
if (table === null) {
return Promise.reject("Table does not exist");
} else {
// let buildings: string[] = this.findBuilding(zip, table);
// return Promise.resolve(buildings);
return DatasetHelper.findBuilding(zip, table).then((roomsArray: object[]) => {
return roomsArray;
}).catch((error) => {
return Promise.reject(error);
});
}
} catch (e) {
return Promise.reject(e);
}
}
public static checkValidRoomsFolder(zip: JSZip): boolean {
if (zip.folder(/rooms/).length > 0) {
return true;
} else {
return false;
}
}
public static checkValidIndextHTM(rooms: JSZip): boolean {
if (rooms.file("index.htm")) {
return true;
} else {
return false;
}
}
// Code help from https://www.youtube.com/watch?v=pL7-618Vlq8&ab_channel=NoaHeyl
public static findBuilding(zip: JSZip, tableBody: any): Promise<object[]> {
let rooms: object[] = [], roomsPromise: any[] = [], latLonPromise: any[] = [], buildingArrays: any[] = [];
const buildingCode = "views-field views-field-field-building-code";
const buildingAddress = "views-field views-field-field-building-address";
const buildingTitle = "views-field views-field-title";
try {
for (const row of tableBody) {
const buildingInfo = {shortname: "", href: "", fullname: "", address: "", lat: 0, lon: 0};
if (row.nodeName === "tr" && row.childNodes && row.childNodes.length > 0) {
for (const elt of row.childNodes) {
if (elt.nodeName === "td" && elt.attrs.length > 0) {
if (elt.attrs[0].value === buildingCode && elt.childNodes && elt.childNodes.length > 0) {
buildingInfo.shortname = elt.childNodes[0].value.trim();
}
if (elt.attrs[0].value === buildingTitle && elt.childNodes && elt.childNodes.length > 0) {
buildingInfo.href = elt.childNodes[1].attrs[0].value.trim();
if (elt.childNodes[1].childNodes && elt.childNodes[1].childNodes.length > 0) {
buildingInfo.fullname = elt.childNodes[1].childNodes[0].value.trim();
}
}
if (elt.attrs[0].value === buildingAddress && elt.childNodes && elt.childNodes.length > 0) {
buildingInfo.address = elt.childNodes[0].value.trim();
}
}
}
latLonPromise.push(GeolocationHelper.getLatLon(buildingInfo).then((updatedBuildingInfo: any) => {
// buildingInfo.lat = loc.lat;
// buildingInfo.lon = loc.lon;
buildingArrays.push(updatedBuildingInfo);
}).catch());
}
}
return Promise.all(latLonPromise).then((sth) => {
for (const building of buildingArrays) {
try {
if (building.lat !== 0) {
roomsPromise.push(this.processRooms(zip, building));
}
} catch (e) {
// if rooms can't be processed, skip this building
}
}
return Promise.all(roomsPromise).then((roomsArrays) => {
for (const roomsArray of roomsArrays) {
rooms = rooms.concat(roomsArray);
}
return Promise.resolve(rooms);
});
}).catch();
} catch (e) {
return Promise.reject(e);
}
}
private static processRooms(zip: JSZip, buildingInfo: any): Promise<object[]> {
let path = "rooms/campus/discover/buildings-and-classrooms/" + buildingInfo.shortname;
let roomsArray: any[] = [];
try {
return zip.file(path).async("string").then((buildingHtml: string) => {
const roomHtml = parse5.parse(buildingHtml);
let rooms = DatasetHelper.findRooms(roomHtml);
if (rooms) {
for (let room of rooms) {
let roomObject: { [key in RoomKeys]?: any } = {
[RoomKeys.Seats]: room[0],
[RoomKeys.Furniture]: room[1],
[RoomKeys.Type]: room[2],
[RoomKeys.Number]: room[3],
[RoomKeys.Address]: buildingInfo.address,
[RoomKeys.Fullname]: buildingInfo.fullname,
[RoomKeys.Shortname]: buildingInfo.shortname,
[RoomKeys.Name]: buildingInfo.shortname + "_" + room[3],
[RoomKeys.Href]: room[4],
[RoomKeys.Lat]: buildingInfo.lat,
[RoomKeys.Lon]: buildingInfo.lon
};
roomsArray.push(roomObject);
}
}
return Promise.resolve(roomsArray);
}).catch((error) => {
return Promise.reject(new InsightError());
});
} catch (e) {
return Promise.reject(new InsightError());
}
}
private static findTableBody(parsedIndexHTM: any): any {
let table = "";
if (parsedIndexHTM.childNodes && parsedIndexHTM.childNodes.length > 0) {
for (const node of parsedIndexHTM.childNodes) {
if (node.nodeName === "tbody") {
table = node.childNodes;
} else {
if (node.childNodes && node.childNodes.length > 0) {
table = this.findTableBody(node);
if (table) {
return table;
}
}
}
}
}
return table;
}
private static findRooms(buildingHtml: string): any[] {
let tableBody = DatasetHelper.findTableBody(buildingHtml);
if (tableBody) {
let rooms: object[] = [];
const roomNumber = "views-field views-field-field-room-number";
const roomSeats = "views-field views-field-field-room-capacity";
const roomFurniture = "views-field views-field-field-room-furniture";
const roomType = "views-field views-field-field-room-type";
let numberRoom = "", seats = 0, type = "", furniture = "", href = "";
for (const row of tableBody) {
if (row.nodeName === "tr" && row.childNodes && row.childNodes.length > 0) {
for (const elt of row.childNodes) {
if (elt.nodeName === "td" && elt.attrs.length > 0) {
if (elt.attrs[0].value === roomSeats && elt.childNodes && elt.childNodes.length > 0) {
seats = +elt.childNodes[0].value.trim();
}
if (elt.attrs[0].value === roomFurniture && elt.childNodes && elt.childNodes.length > 0) {
furniture = elt.childNodes[0].value.trim();
}
if (elt.attrs[0].value === roomType && elt.childNodes && elt.childNodes.length > 0) {
type = elt.childNodes[0].value.trim();
}
if (elt.attrs[0].value === roomNumber && elt.childNodes && elt.childNodes.length > 0) {
if (elt.childNodes[1].childNodes && elt.childNodes[1].childNodes.length > 0) {
numberRoom = elt.childNodes[1].childNodes[0].value.toString();
}
href = elt.childNodes[1].attrs[0].value;
}
}
}
rooms.push([seats, furniture, type, numberRoom, href]);
}
}
return rooms;
}
}
}
<file_sep>export class Section {
// JSO containing properties of the section
// content's keys are from CourseKeys
private content: any;
// takes a JSO that contains the keys in CourseKeys and initialize the content of this section
constructor(content: any) {
this.content = content;
}
// takes a key and return properties of this section
public get(key: string): any {
return this.content[key];
}
}
<file_sep>import {Section} from "./Section";
import {InsightDatasetKind} from "./IInsightFacade";
export class Dataset {
private id: string;
private kind: InsightDatasetKind;
private sections: any[];
constructor(id: string, kind: InsightDatasetKind, sections: any[]) {
this.id = id;
this.kind = kind;
this.sections = sections;
}
public getId(): string {
return this.id;
}
public getKind(): InsightDatasetKind {
return this.kind;
}
public getSections(): any[] {
return this.sections;
}
}
export enum RoomKeys {
Lat = "lat",
Lon = "lon",
Seats = "seats",
Fullname = "fullname",
Shortname = "shortname",
Number = "number",
Name = "name",
Address = "address",
Type = "type",
Furniture = "furniture",
Href = "href",
}
export enum SectionKeys {
Department = "dept",
Id = "id",
Instructor = "instructor",
Title = "title",
Uuid = "uuid",
Average = "avg",
Pass = "pass",
Fail = "fail",
Audit = "audit",
Year = "year",
}
<file_sep>import {InsightError} from "./IInsightFacade";
import {QueryHelper} from "./QueryHelper";
import Log from "../Util";
export class TransformationHelper {
// return true if TRANSFORMATION does not exists or it exists and only contains GROUP and APPLY
public static checkValidTransformation(query: any): boolean {
if (!Object.keys(query).includes("TRANSFORMATIONS")) {
return true;
}
if (query["TRANSFORMATIONS"] === null || query["TRANSFORMATIONS"] === undefined ||
Array.isArray(query["TRANSFORMATIONS"]) || query["TRANSFORMATIONS"].constructor !== Object) {
return false;
}
const keys: string[] = Object.keys(query["TRANSFORMATIONS"]);
return keys.length === 2 && keys[0] === "GROUP" && keys[1] === "APPLY";
}
// REQUIRE: TRANSFORM contains GROUP and APPLY keys
public static processTransform(id: string, kind: string, transform: any, sections: any[]): any {
const groups = this.getGroups(id, kind, transform["GROUP"], sections);
let applyResults: any[] = [];
for (const group of groups) {
applyResults.push(this.processApply(id, kind, transform["APPLY"], group));
}
const transformResult = {GROUP: groups, APPLY: applyResults};
return transformResult;
}
private static getGroups(id: string, kind: string, group: any, sections: any[]): any {
if (!Array.isArray(group) || group.length === 0) {
throw new InsightError("GROUP is must be a non-empty array");
}
let groups: {[key: string]: any[]} = {};
for (const section of sections) {
let sectionKeyByGroup: string = "";
for (const key of group) {
const field: string = QueryHelper.getField(id, kind, key, undefined);
sectionKeyByGroup = sectionKeyByGroup + section[field].toString() + "_dummy_string_";
}
if (!groups.hasOwnProperty(sectionKeyByGroup)) {
groups[sectionKeyByGroup] = [section];
} else {
groups[sectionKeyByGroup].push(section);
}
}
return Object.values(groups);
}
private static processApply(id: string, kind: string, apply: any, sections: any[]): any {
let applyKeys: string[] = [];
let applyResult: {[applyKey: string]: any} = {};
for (const applyRule of apply) {
if (applyRule === undefined || applyRule === null ||
Array.isArray(applyRule) || Object.keys(applyRule).length !== 1) {
throw new InsightError("Invalid APPLYRULE");
}
const applyKey: string = Object.keys(applyRule)[0];
if (applyKey.includes("_")) {
throw new InsightError("Applykey contains underscore");
}
if (applyKeys.includes(applyKey)) {
throw new InsightError("Repeated applykey");
}
applyKeys.push(applyKey);
if (applyRule[applyKey] === undefined || applyRule[applyKey] === null ||
Array.isArray(applyRule[applyKey]) || Object.keys(applyRule[applyKey]).length !== 1) {
throw new InsightError("Invalid APPLYRULE");
}
const token: string = Object.keys(applyRule[applyKey])[0];
const key = applyRule[applyKey][token];
let field: string;
if (token === "COUNT") {
field = QueryHelper.getField(id, kind, key, undefined);
} else {
field = QueryHelper.getField(id, kind, key, "M");
}
switch (token) {
case "MAX":
applyResult[applyKey] = this.applyMax(sections, field);
break;
case "MIN":
applyResult[applyKey] = this.applyMin(sections, field);
break;
case "SUM":
applyResult[applyKey] = this.applySum(sections, field);
break;
case "AVG":
applyResult[applyKey] = this.applyAvg(sections, field);
break;
case "COUNT":
applyResult[applyKey] = this.applyCount(sections, field);
break;
default:
throw new InsightError("Invalid apply token");
}
}
return applyResult;
}
public static processOptionsTransform(id: string, kind: string, options: any,
transform: any, transformResult: any): any[] {
const columns = options["COLUMNS"];
if (!Array.isArray(columns) || columns.length === 0) {
throw new InsightError("COLUMNS is must be a non-empty array");
}
const applyKeys: string[] = this.getApplyKeys(transform["APPLY"]);
const groupKeys: string[] = transform["GROUP"];
for (const column of columns) {
if ((column.includes("_") && !groupKeys.includes(column)) ||
(!column.includes("_") && !applyKeys.includes(column))) {
throw new InsightError("Invalid key in COLUMNS");
}
}
let groups = transformResult["GROUP"];
let applyResult = transformResult["APPLY"];
let sections = [];
for (const i in groups) {
let section: {[key: string]: any} = {};
for (const column of columns) {
if (column.includes("_")) {
section[column] = groups[i][0][QueryHelper.getField(id, kind, column, undefined)];
} else {
section[column] = applyResult[i][column];
}
}
sections.push(section);
}
if (options.hasOwnProperty("ORDER")) {
if (typeof options["ORDER"] === "string") {
return this.defaultSort(options["ORDER"], columns, sections);
} else {
return this.customSort(options["ORDER"], columns, sections);
}
} else {
return sections;
}
}
// REQUIRE: all apply keys are distinct
private static getApplyKeys(apply: any): string[] {
let applyKeys: string[] = [];
for (const applyRule of apply) {
applyKeys.push(Object.keys(applyRule)[0]);
}
return applyKeys;
}
// REQUIRE: field is a numeric key and exists in sections
private static applyMax(sections: any[], field: string): number {
let curMax = sections[0][field];
for (const section of sections) {
curMax = Math.max(curMax, section[field]);
}
return curMax;
}
// REQUIRE: field is a numeric key and exists in sections
private static applyMin(sections: any[], field: string): number {
let curMin = sections[0][field];
for (const section of sections) {
curMin = Math.min(curMin, section[field]);
}
return curMin;
}
// REQUIRE: field is a numeric key and exists in sections
private static applySum(sections: any[], field: string): number {
let curSum: number = 0;
for (const section of sections) {
curSum += section[field];
}
return curSum;
}
// REQUIRE: field is a numeric key and exists in sections
private static applyAvg(sections: any[], field: string): number {
const Decimal = require("decimal.js");
let sum = new Decimal(0);
for (const section of sections) {
sum = Decimal.add(sum, new Decimal(section[field]));
}
let avg = sum.toNumber() / sections.length;
return Number(avg.toFixed(2));
}
// REQUIRE: field is a key that exists in sections
private static applyCount(sections: any[], field: string): number {
let values = new Set();
for (const section of sections) {
if (!values.has(section[field])) {
values.add(section[field]);
}
}
return values.size;
}
public static defaultSort(sortKey: string, columns: string[], sections: any[]): any[] {
if (!columns.includes(sortKey)) {
throw new InsightError("ORDER key is not in COLUMNS");
}
sections.sort((section1, section2) => {
if (section1[sortKey] < section2[sortKey]) {
return -1;
}
return 1;
});
return sections;
}
public static customSort(order: any, columns: string[], sections: any[]): any[] {
const dir = order["dir"];
const keys = order["keys"];
if (!dir || (dir !== "UP" && dir !== "DOWN") || !keys || !Array.isArray(keys) || keys.length === 0) {
throw new InsightError("Invalid ORDER");
}
for (const key of keys) {
if (!columns.includes(key)) {
throw new InsightError("ORDER key is not in COLUMNS");
}
}
sections.sort((section1, section2) => {
let index = 0;
while (index < keys.length && section1[keys[index]] === section2[keys[index]]) {
index++;
}
if (index === keys.length) {
return 0;
}
if ((dir === "UP" && section1[keys[index]] < section2[keys[index]]) ||
(dir === "DOWN" && section1[keys[index]] > section2[keys[index]])) {
return -1;
}
return 1;
});
return sections;
}
}
<file_sep>import * as chai from "chai";
import {expect} from "chai";
import * as fs from "fs-extra";
import * as chaiAsPromised from "chai-as-promised";
import {InsightDataset, InsightDatasetKind, InsightError, NotFoundError} from "../src/controller/IInsightFacade";
import InsightFacade from "../src/controller/InsightFacade";
import Log from "../src/Util";
import TestUtil from "./TestUtil";
// import {NotFoundError} from "restify";
// This extends chai with assertions that natively support Promises
chai.use(chaiAsPromised);
// This should match the schema given to TestUtil.validate(..) in TestUtil.readTestQueries(..)
// except 'filename' which is injected when the file is read.
export interface ITestQuery {
title: string;
query: any; // make any to allow testing structurally invalid queries
isQueryValid: boolean;
result: any;
filename: string; // This is injected when reading the file
}
describe("InsightFacade Add/Remove/List Dataset", function () {
// Reference any datasets you've added to test/data here and they will
// automatically be loaded in the 'before' hook.
const datasetsToLoad: { [id: string]: string } = {
courses: "./test/data/courses.zip",
courses1: "./test/data/courses1.zip", // copy of courses, valid
courses2: "./test/data/courses2.zip", // empty folder, invalid
courses3: "./test/data/courses3.zip", // folder contains a file that is not JSON, invalid
courses4: "./test/data/courses4.zip", // folder contains only an empty JSON file, invalid
courses5: "./test/data/courses5.zip", // folder contains a JSON file that has a JSON array, invalid
courses6: "./test/data/courses6.txt", // not a zip file, invalid
courses7: "./test/data/courses7.zip", // no courses folder, invalid
courses8: "./test/data/courses8.zip", // 1 valid JSON file, 1 invalid png file, dataset valid
courses9: "./test/data/courses9.zip", // folder contains 1 valid JSON file, valid
courses10: "./test/data/courses10.zip", // folder contains 1 valid JSON, 1 invalid JSON, valid
courses11: "./test/data/courses11.zip", // folder contains 1 valid JSON file, 1 folder, valid
courses12: "./test/data/courses12.zip", // folder contains only 1 folder, invalid
rooms: "./test/data/rooms.zip", // folder named room, valid
rooms2: "./test/data/rooms2.zip", // folder named random, invalid
rooms3: "./test/data/rooms3.zip", // folder with no valid building, invalid
rooms4: "./test/data/rooms4.zip", // folder with building but no valid rooms, invalid
};
let datasets: { [id: string]: string } = {};
let insightFacade: InsightFacade;
const cacheDir = __dirname + "/../data";
before(function () {
// This section runs once and loads all datasets specified in the datasetsToLoad object
// into the datasets object
Log.test(`Before all`);
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir);
}
for (const id of Object.keys(datasetsToLoad)) {
datasets[id] = fs
.readFileSync(datasetsToLoad[id])
.toString("base64");
}
try {
insightFacade = new InsightFacade();
} catch (err) {
Log.error(err);
}
});
beforeEach(function () {
Log.test(`BeforeTest: ${this.currentTest.title}`);
});
after(function () {
Log.test(`After: ${this.test.parent.title}`);
});
afterEach(function () {
// This section resets the data directory (removing any cached data) and resets the InsightFacade instance
// This runs after each test, which should make each test independent from the previous one
Log.test(`AfterTest: ${this.currentTest.title}`);
try {
fs.removeSync(cacheDir);
fs.mkdirSync(cacheDir);
insightFacade = new InsightFacade();
} catch (err) {
Log.error(err);
}
});
// This is a unit test. You should create more like this!
it("Should add a valid dataset", function () {
const id: string = "courses";
const expected: string[] = [id];
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should add a valid dataset of kind Rooms", function () {
const id: string = "rooms";
const expected: string[] = [id];
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Rooms,
);
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should not add a Rooms type dataset whose folder is not named 'rooms'", function () {
const id: string = "rooms2";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Rooms,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a Rooms type dataset with no buildings", function () {
const id: string = "rooms3";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Rooms,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a Rooms type dataset with a building but no rooms", function () {
const id: string = "rooms4";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Rooms,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset whose folder is not named 'courses'", function () {
const id: string = "rooms";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset that is already added", function () {
const id: string = "courses";
const expectedAddResult: string[] = [id];
let addResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult).to.eventually.deep.equal(expectedAddResult).then(() => {
addResult = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult).to.be.rejectedWith(InsightError);
});
});
it("Should not add a dataset that is an empty folder", function () {
const id: string = "courses2";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset containing a file that is not JSON", function () {
const id: string = "courses3";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset containing only an empty JSON file", function () {
const id: string = "courses4";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset containing a JSON file that has a JSON array", function () {
const id: string = "courses5";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset that is not a zip file", function () {
const id: string = "courses6";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset that does not have 'courses' folder", function () {
const id: string = "courses7";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should add a dataset containing 1 valid file, 1 invalid file", function () {
const id: string = "courses8";
const expected: string[] = [id];
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should add a dataset that contains only 1 valid JSON file", function () {
const id: string = "courses9";
const expected: string[] = [id];
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should add a dataset that contains 1 valid JSON file, 1 invalid JSON file", function () {
const id: string = "courses10";
const expected: string[] = [id];
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should add a dataset that contains 1 valid JSON file, 1 folder", function () {
const id: string = "courses11";
const expected: string[] = [id];
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should not add a dataset whose id does not exist", function () {
const id: string = "courses100";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset with id that contains underscore", function () {
const id: string = "courses_1";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset whose id is only whitespace characters", function () {
const id: string = " ";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset whose id is null", function () {
const id: string = null;
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a null dataset", function () {
const id: string = "courses";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
null,
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset whose kind is null", function () {
const id: string = "courses";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
null,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset whose id is undefined", function () {
const id: string = undefined;
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add an undefined dataset", function () {
const id: string = "courses";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
undefined,
InsightDatasetKind.Courses,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not add a dataset whose kind is undefined", function () {
const id: string = "courses";
const futureResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
undefined,
);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should add two datasets, remove the first dataset, list the second dataset", function () {
const id: string = "courses";
const id1: string = "courses1";
let expectedAddResult: string[] = [id];
let addResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
expectedAddResult = [id, id1];
addResult = insightFacade.addDataset(
id1,
datasets[id1],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
const removeResult: Promise<
string
> = insightFacade.removeDataset(id);
return expect(removeResult)
.to.eventually.deep.equal(id)
.then(() => {
const listResult: Promise<
InsightDataset[]
> = insightFacade.listDatasets();
const expectedListResult: InsightDataset[] = [
{
id: id1,
kind: InsightDatasetKind.Courses,
numRows: 64612,
},
];
return expect(
listResult,
).to.eventually.deep.equal(expectedListResult);
});
});
});
});
it("Should add two datasets, remove the second dataset, list the first dataset", function () {
const id: string = "courses";
const id1: string = "courses1";
let expectedAddResult: string[] = [id];
let addResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
expectedAddResult = [id, id1];
addResult = insightFacade.addDataset(
id1,
datasets[id1],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
const removeResult: Promise<
string
> = insightFacade.removeDataset(id1);
return expect(removeResult)
.to.eventually.deep.equal(id1)
.then(() => {
const listResult: Promise<
InsightDataset[]
> = insightFacade.listDatasets();
const expectedListResult: InsightDataset[] = [
{
id: id,
kind: InsightDatasetKind.Courses,
numRows: 64612,
},
];
return expect(
listResult,
).to.eventually.deep.equal(expectedListResult);
});
});
});
});
it("Should not remove a dataset not added, no dataset in insightFacade", function () {
const id: string = "courses";
const futureResult: Promise<string> = insightFacade.removeDataset(id);
return expect(futureResult).to.be.rejectedWith(NotFoundError);
});
it("Should not remove a dataset not added, a dataset exists in insightFacade", function () {
const id: string = "courses";
const id1: string = "courses1";
let expectedAddResult: string[] = [id];
let addResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
const removeResult: Promise<string> = insightFacade.removeDataset(id1);
return expect(removeResult).to.be.rejectedWith(NotFoundError);
});
});
it("Should not remove a dataset whose id contains underscore", function () {
const id: string = "courses_1";
const futureResult: Promise<string> = insightFacade.removeDataset(id);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not remove a dataset whose id is only whitespace characters", function () {
const id: string = " ";
const futureResult: Promise<string> = insightFacade.removeDataset(id);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not remove a dataset whose id is null", function () {
const id: string = null;
const futureResult: Promise<string> = insightFacade.removeDataset(id);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should not remove a dataset whose id is undefined", function () {
const id: string = undefined;
const futureResult: Promise<string> = insightFacade.removeDataset(id);
return expect(futureResult).to.be.rejectedWith(InsightError);
});
it("Should list no datasets", function () {
const futureResult: Promise<
InsightDataset[]
> = insightFacade.listDatasets();
const expected: InsightDataset[] = [];
return expect(futureResult).to.eventually.deep.equal(expected);
});
it("Should a dataset, list one dataset", function () {
const id: string = "courses";
const expectedAddResult: string[] = [id];
const addResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
const listResult: Promise<
InsightDataset[]
> = insightFacade.listDatasets();
const expectedListResult: InsightDataset[] = [
{
id: "courses",
kind: InsightDatasetKind.Courses,
numRows: 64612,
},
];
return expect(listResult).to.eventually.deep.equal(
expectedListResult,
);
});
});
it("Should add two datasets, list two datasets", function () {
const id: string = "courses";
const id1: string = "courses1";
let expectedAddResult: string[] = [id];
let addResult: Promise<string[]> = insightFacade.addDataset(
id,
datasets[id],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
expectedAddResult = [id, id1];
addResult = insightFacade.addDataset(
id1,
datasets[id1],
InsightDatasetKind.Courses,
);
return expect(addResult)
.to.eventually.deep.equal(expectedAddResult)
.then(() => {
const listResult: Promise<
InsightDataset[]
> = insightFacade.listDatasets();
const expectedListResult: InsightDataset[] = [
{
id: "courses",
kind: InsightDatasetKind.Courses,
numRows: 64612,
},
{
id: "courses1",
kind: InsightDatasetKind.Courses,
numRows: 64612,
},
];
return expect(listResult).to.eventually.deep.equal(
expectedListResult,
);
});
});
});
});
/*
* This test suite dynamically generates tests from the JSON files in test/queries.
* You should not need to modify it; instead, add additional files to the queries directory.
* You can still make tests the normal way, this is just a convenient tool for a majority of queries.
*/
describe("InsightFacade PerformQuery", () => {
const datasetsToQuery: {
[id: string]: { path: string; kind: InsightDatasetKind };
} = {
courses: {
path: "./test/data/courses.zip",
kind: InsightDatasetKind.Courses,
},
rooms: {
path: "./test/data/rooms.zip",
kind: InsightDatasetKind.Rooms,
}
};
let insightFacade: InsightFacade;
let testQueries: ITestQuery[] = [];
// Load all the test queries, and call addDataset on the insightFacade instance for all the datasets
before(function () {
Log.test(`Before: ${this.test.parent.title}`);
// Load the query JSON files under test/queries.
// Fail if there is a problem reading ANY query.
try {
testQueries = TestUtil.readTestQueries();
} catch (err) {
expect.fail(
"",
"",
`Failed to read one or more test queries. ${err}`,
);
}
// Load the datasets specified in datasetsToQuery and add them to InsightFacade.
// Will fail* if there is a problem reading ANY dataset.
const loadDatasetPromises: Array<Promise<string[]>> = [];
insightFacade = new InsightFacade();
for (const id of Object.keys(datasetsToQuery)) {
const ds = datasetsToQuery[id];
const data = fs.readFileSync(ds.path).toString("base64");
loadDatasetPromises.push(
insightFacade.addDataset(id, data, ds.kind),
);
}
return Promise.all(loadDatasetPromises);
});
beforeEach(function () {
Log.test(`BeforeTest: ${this.currentTest.title}`);
});
after(function () {
Log.test(`After: ${this.test.parent.title}`);
});
afterEach(function () {
Log.test(`AfterTest: ${this.currentTest.title}`);
});
// Dynamically create and run a test for each query in testQueries
// Creates an extra "test" called "Should run test queries" as a byproduct. Don't worry about it
it("Should run test queries", function () {
describe("Dynamic InsightFacade PerformQuery tests", function () {
for (const test of testQueries) {
it(`[${test.filename}] ${test.title}`, function () {
const futureResult: Promise<
any[]
> = insightFacade.performQuery(test.query);
return TestUtil.verifyQueryResult(futureResult, test);
});
}
});
});
});
// This test generates tests from the JSON files in test/smalltest.
// These tests query on fake datasets (already processed) in /data
/*describe("Testing query on fake datasets", () => {
let insightFacade: InsightFacade;
let testQueries: ITestQuery[] = [];
// Load all the test queries
before(function () {
Log.test(`Before: ${this.test.parent.title}`);
// Load the query JSON files under test/queries.
// Fail if there is a problem reading ANY query.
try {
testQueries = TestUtil.readTestQueries("test/smalltest");
} catch (err) {
expect.fail(
"",
"",
`Failed to read one or more test queries. ${err}`,
);
}
insightFacade = new InsightFacade();
});
beforeEach(function () {
Log.test(`BeforeTest: ${this.currentTest.title}`);
});
after(function () {
Log.test(`After: ${this.test.parent.title}`);
});
afterEach(function () {
Log.test(`AfterTest: ${this.currentTest.title}`);
});
// Dynamically create and run a test for each query in testQueries
// Creates an extra "test" called "Should run test queries" as a byproduct. Don't worry about it
it("Should run test queries", function () {
describe("PerformQuery tests", function () {
for (const test of testQueries) {
it(`[${test.filename}] ${test.title}`, function () {
Log.trace(1);
const futureResult: Promise<
any[]
> = insightFacade.performQuery(test.query);
return TestUtil.verifyQueryResult(futureResult, test);
});
}
});
});
});*/
|
8f5745ce74fe20df178b118424934d9d31bae5f7
|
[
"TypeScript"
] | 8
|
TypeScript
|
KimDinh/CPSC-310-2020W2
|
e9cf359b229392bcc4729047c9ee9e2f26a52c85
|
56e6251761c3511ef62333a500328be088d65bdc
|
refs/heads/main
|
<repo_name>SelcanKaraturk/50-Projects<file_sep>/Project31-textEffect/script31.js
const textEl = document.getElementById('text');
const speedEl = document.getElementById('speed');
const text = 'I love Programming';
let idx = 1;
let speed = 300 / speedEl.value
writeText()
function writeText(){
textEl.innerText = text.slice(0, idx);
idx++;
if (idx > text.length) {
idx=1;
}
setTimeout(writeText, speed) //fonksiyon ne kadar süre sonra çalışacak 1s=1000ms
}
speedEl.addEventListener('input',(e) => speed =300/e.target.value);//HTML dökümanı üzerinde belirtilen elementi dinleyip, istenilen olay gerçekleştiğinde bir metod çalıştırmak için kullanılır.
|
14b65593c77e5d0c217aca64dd8943b9f6863cc4
|
[
"JavaScript"
] | 1
|
JavaScript
|
SelcanKaraturk/50-Projects
|
3f14120cf61eda566c2be980d7826808a5723701
|
d2992868ce22e64938b59dfd027b999ad36dc457
|
refs/heads/master
|
<repo_name>T-era/Trism<file_sep>/Trism_Slime.js
Trism.Slime = function(r, g, b) {
this.R = r;
this.G = g;
this.B = b;
this.rgb = function(lvl) {
var pow = Math.pow(0.92, lvl*lvl*lvl);
return "#" + toTwoChar(this.R) + toTwoChar(this.G) + toTwoChar(this.B);
function toTwoChar(v) {
var hexa = Math.floor(((v + 1) * 8 - 1) * pow);
return ("00" + hexa.toString(16)).slice(-2);
}
};
this.rating = Math.sqrt(100 / (r * g * b));
this.isWhite = function() {
return this.R == 31
&& this.G == 31
&& this.B == 31;
};
this.drawAt = function(context, x, y, width, heightLevel, lvl) {
var d = 1;
drawIn(this, x, y, width, heightLevel, lvl);
function drawIn(that, x, y, width, heightLevel, lvl) {
lvl = (lvl == undefined ? 2 : lvl);
context.beginPath();
context.moveTo(x - width, y);
context.fillStyle = that.rgb(lvl);
context.bezierCurveTo(x - width, y + heightLevel, x + width, y + heightLevel, x + width, y);
context.bezierCurveTo(x + width, y - heightLevel * 1.5, x - width, y - heightLevel * 1.5, x - width, y);
context.fill();
if (lvl > 0) {
d = d * d * .90;
var dx = width * (1 - d);
drawIn(that, x - dx / 3, y - dx / 3, width * d, heightLevel * d, lvl - 1);
}
}
}
}
Trism.createRandomSlime = function(arg) {
var powMin = arg.Min;
var powMax = arg.Max;
getPow = function() {
return powMin + Math.floor(Math.random() * (1 + powMax - powMin));
};
return new Trism.Slime(
getPow(),
getPow(),
getPow());
}
<file_sep>/Trism_HighlightEffect.js
Trism.HighlightEffect = function(canvas, context, barWidth) {
this.kickEffect = function(width, top, height, refleshDraw) {
new EffectAnimation(width, top, height, refleshDraw);
}
function EffectAnimation(width, top, height, refleshDraw) {
var tempX = -1;
motion();
function motion() {
if (stepNext()) {
setTimeout(motion, 1);
}
}
function stepNext() {
refleshDraw();
if (tempX - barWidth <= width + barWidth) {
tempX += 2;
for (var i = 0; i < height; i ++) {
var relX = (tempX - i) % height;
if (relX < 0) {}
else {
var phyX = tempX - i;
if (i != 0
&& i != height - 1) {
context.beginPath();
context.strokeStyle = "#ffffff";
context.moveTo(phyX, top + i);
context.lineTo(phyX + height, top + i);
context.stroke();
}
}
}
return true;
} else {
return false;
}
}
}
}<file_sep>/Trism_Resources.js
Trism.RandomSelect = function(source, size) {
size = size || 1;
if (size == 1) {
var index = Math.floor(Math.random() * source.length);
return source[index];
} else {
var indexes = [];
for (var i = 0; i < size; i ++) {
var index = Math.floor(Math.random() * source.length);
while(isIn(index, indexes)) {
index = (index + 1) % source.length;
}
indexes.push(index);
}
var selected = []
for (var i = 0, iMax = indexes.length; i < iMax; i ++) {
selected.push(source[indexes[i]]);
}
return selected;
}
function isIn(item, list) {
for (var i = 0, iMax = list.length; i < iMax; i ++) {
if (list[i] === item) {
return true;
}
}
return false;
}
};
Trism.Identities = [" 父の跡を追って、世界を救う旅に出る17歳の少年。\n そんなゲームが好きだった。\n"
, " 故郷の村を滅ぼした闇の力に対抗するために、自身の\nチカラを鍛えるために世界に挑戦する。\n そんな厨二病設定を自らに課した勇者(36歳)。"
, ' 世界中で唯一正統な継承権をもつ、八百屋"やおはち"の\n跡取り。\n'
, " まさお\n\n"
, " 美白に憧れる女子。\n\n 「てゆーかマジちょーうける!」"
, " 隣村からはるばる訪れた挑戦者。\n 往復のバス代がちょっとダメージだった。\n"
, " 将棋初級、脅威の実力者。\n 勝負が将棋じゃない、というハンデを負ってもなお戦意は\n旺盛。"
, " 界隈では、その存在を知らない者はモグリと言われる\nほどの猛者。\n バーゲンで鉢合わせすればおばちゃんたちも逃げ出す。"
, " 「将来性は抜群」誰よりもそう言われ続けてきたオトコ。\n\n 「...将来性は抜群」"
, " 恐ろしいことに、タカ派。\n Ex*leファン。\n"
, " 山も削るジハイドロジェンモノキサイドを武器とする狂戦士。\n 自らも強度の中毒症と化してしまったため、ジハイドロ\nジェンモノキサイドなしでは3日と生きられない。"
, " 遠い異国から訪れたドルイド。\n 法名はゲル・ドロンコ=ビチャリゴロス ンッヌワト・ナタデコ\nコイリ・マスカットフウミ・エ=ゥラ・ゼリー(「賢い者」の意)"];
<file_sep>/Trism_CanvasConsole.js
Trism.CanvasConsole = function(canvas) {
var parent = canvas.parentNode;
canvas.style.display = "none";
window.addEventListener("resize", centering, false);
function centering() {
canvas.style.left = (parent.offsetWidth - canvas.offsetWidth) / 2 + "px";
canvas.style.top = (parent.offsetHeight - canvas.offsetHeight) / 2 + "px";
}
var context = canvas.getContext('2d');
context.font = "40px Courier"
var nowActive = false;
this.show = function(message) {
if (message) {
context.stroke();
context.clearRect(0,0, canvas.width, canvas.height);
nowActive = true;
canvas.style.display = "block";
context.fillStyle = "#ffffff";
context.fillText(message, 0, 40);
centering();
}
}
this.setInactive = function() {
canvas.style.display = "none";
nowActive = false;
eraseCursol();
}
function setTimer(blink) {
setTimeout(function() {
if (nowActive) {
showCursol(blink);
}
setTimer(! blink);
}, 500);
};
setTimer(false);
function showCursol(blink) {
context.beginPath();
if (blink) {
context.fillStyle = "#ffffff";
} else {
context.fillStyle = "#888888";
}
context.moveTo(100, 60);
context.lineTo(120, 60);
context.lineTo(110, 70);
context.closePath();
context.fill();
}
function eraseCursol() {
context.beginPath();
context.clearRect(100, 60, 120, 70);
context.fill();
}
}<file_sep>/Trism_Messaging.js
Trism.MessageQueueCreator = function(messageDisp) {
var cueue = [];
this.Clear = function() {
cueue = [];
}
this.isEmpty = function() {
return cueue.length == 0;
}
this.ShowNext = function() {
cueue.shift();
if (cueue.length == 0) {
messageDisp.setInactive();
} else {
messageDisp.show(cueue[0]);
}
}
this.AddMessage = function(message) {
cueue.push(message);
messageDisp.show(cueue[0]);
}
this.AddMessages = function(messageList) {
for (var i = 0, iMax = messageList.length; i < iMax; i ++) {
cueue.push(messageList[i]);
}
messageDisp.show(cueue[0]);
}
}<file_sep>/Trism_CharactorInitializer.js
Trism.CharactorInitializer = function(id, callback) {
var div = document.getElementById(id);
div.style.display = "block";
var canvas = div.firstElementChild;
var context = canvas.getContext('2d');
context.clearAll = function() { context.clearRect(0,0, canvas.width, canvas.height); };
var range = { Min: 2, Max: 10 };
var choice = [
Trism.createRandomSlime(range),
Trism.createRandomSlime(range),
Trism.createRandomSlime(range)];
var comment = Trism.RandomSelect(Trism.Identities, 3);
var selectedIndex = 0;
Trism.SetKeyListener({
stepToL: function () {
selectedIndex = (selectedIndex + 2) % choice.length;
Repaint();
},
stepToR: function () {
selectedIndex = (selectedIndex + 1) % choice.length;
Repaint();
},
stepToUp: function() {},
stepToDown: function() {},
attackIt: function() {
div.style.display = "none";
callback(choice[selectedIndex]);
},
}
, { isEmpty: function() { return true; }}
);
Repaint();
function Repaint() {
var size = 240;
context.font = "30px Courier";
context.clearAll();
for (var i = 0, iMax = choice.length; i < iMax; i ++) {
choice[i].drawAt(context, 120 + i * size, 80, 80, 60);
}
context.beginPath();
context.strokeStyle = "#ffffff";
context.strokeRect(selectedIndex * size, 0, size, 160);
context.fillStyle = "#ffffff";
context.fillText("Rate: " + choice[selectedIndex].rating.toString().slice(0,4), 10, 200);
context.font = "24px Courier";
var lines = comment[selectedIndex].split("\n");
context.fillText(lines[0], 5, 236);
context.fillText(lines[1], 5, 270);
context.fillText(lines[2], 5, 304);
context.stroke();
}
}<file_sep>/Trism_Field.js
Trism.Field = function(canvas, contextYou, sHero) {
var context = canvas.getContext('2d')
context.clearAll = function() {
context.clearRect(0,0,canvas.width, canvas.height);
};
var STAGES = [{ Min: 1, Max: 10 }
, { Min: 6, Max: 16 }
, { Min: 12, Max: 26 }
, { Min: 23, Max: 31 }];
var SIZE = 5;
var SIZE_OF_ICON = 30;
var level = -1;
var score = 0;
var target;
var items;
var x;
var y;
StageUp();
function StageUp() {
context.clearRect(0,0,canvas.width, canvas.height);
level ++;
if (sHero.isWhite()) {
alert("Complete white!" + 100000 / score);
alert(score);
Trism.SetKeyListener();
}
if (level >= STAGES.length) {
alert("GAME OVER");
Trism.SetKeyListener();
} else {
items = createItems(SIZE, SIZE, STAGES[level]);
x = 2;
y = 2;
items[x][y] = null;
}
}
this.stepToL = function() {
this.stepTo(x - 1, y);
}
this.stepToR = function() {
this.stepTo(x + 1, y);
}
this.stepToUp = function() {
this.stepTo(x, y - 1);
}
this.stepToDown = function() {
this.stepTo(x, y + 1);
}
this.stepTo = function(toX, toY) {
if (toX == 2 && toY < 0) {
StageUp();
this.Draw();
return ;
} else if (toX < 0 || toY < 0
|| toX >= SIZE || toY >= SIZE) {
return ;
} else {
target = null;
if (items[toY][toX]) {
target = items[toY][toX];
} else {
x = toX;
y = toY;
}
this.Draw();
}
}
this.attackIt = function() {
if (target) {
score += sHero.rating;
var res = Trism.Fight(sHero, target);
if (res === false) {
alert("Lose");
} else if (res === true) {
var lvup = Trism.LevelUp();
lvup.event(sHero);
var message = Trism.RandomSelect(lvup.getMessages());
Trism.MessageQueue.AddMessages(message.split("\n"));
if (sHero.R > 31) sHero.R = 31;
if (sHero.G > 31) sHero.G = 31;
if (sHero.B > 31) sHero.B = 31;
items[target.y][target.x] = null;
target = null;
}
}
this.Draw();
}
this.Draw = function() {
context.clearAll();
for (var vy = 0, yMax = items.length; vy < yMax; vy ++) {
for (var vx = 0, xMax = items[vy].length; vx < xMax; vx ++) {
if (vx == x && vy == y) {
drawSlime(x, y, sHero);
} else {
drawSlime(vx, vy, items[vy][vx]);
}
}
}
if (target) {
contextYou.DiffStatus(sHero, target);
} else {
contextYou.ShowStatus(sHero);
}
drawBox();
}
function drawSlime(x, y, slime) {
context.beginPath();
if (slime) {
if (slime == sHero) {
context.fillStyle = "#ffffff";
context.fillRect(2 + (x + 0.5) * SIZE_OF_ICON , 2 + (y + 0.5) * SIZE_OF_ICON , SIZE_OF_ICON - 4, SIZE_OF_ICON - 4);
} else {
context.strokeStyle = "#000000";
}
context.fillStyle = slime.rgb(0);
context.arc((1 + x) * SIZE_OF_ICON , (1 + y) * SIZE_OF_ICON , SIZE_OF_ICON / 2 - 2, 0,7)
} else {
context.clearRect((x + 0.5) * SIZE_OF_ICON , (y + 0.5) * SIZE_OF_ICON , SIZE_OF_ICON , SIZE_OF_ICON );
}
context.stroke();
context.fill();
}
function createItems(sizeX, sizeY, powBand) {
var list = [];
for (var y = 0; y < sizeY; y ++) {
var subList = [];
for (var x = 0; x < sizeX; x ++) {
var newItem = new Trism.createRandomSlime(powBand);
newItem.x = x;
newItem.y = y;
subList.push(newItem);
}
list.push(subList);
}
return list;
}
function drawBox() {
context.beginPath();
context.strokeStyle = "#ffffff";
context.moveTo(2.5 * SIZE_OF_ICON - 1, SIZE_OF_ICON / 2 - 1);
context.lineTo(SIZE_OF_ICON / 2 - 1, SIZE_OF_ICON / 2 - 1);
context.lineTo(SIZE_OF_ICON / 2 - 1, SIZE_OF_ICON * (SIZE + 0.5) + 1);
context.lineTo(SIZE_OF_ICON * (SIZE + 0.5) + 1, SIZE_OF_ICON * (SIZE + 0.5) + 1);
context.lineTo(SIZE_OF_ICON * (SIZE + 0.5) + 1, SIZE_OF_ICON / 2 - 1);
context.lineTo(3.5 * SIZE_OF_ICON + 1, SIZE_OF_ICON / 2 - 1);
context.stroke();
}
};
<file_sep>/TrismMain.js
var Trism = {}
Trism.Init = function(idField, idYou, idConsole) {
var canvasField = document.getElementById(idField);
var canvasYou = document.getElementById(idYou);
var canvasConsole = document.getElementById(idConsole);
this.setDomEvent(canvasYou);
Trism.CharactorInitializer("init", function(arg) {
var field = new Trism.Field(canvasField, canvasYou.__context, arg)
field.Draw();
Trism.MessageQueue = new Trism.MessageQueueCreator(new Trism.CanvasConsole(canvasConsole));
Trism.SetKeyListener(field, Trism.MessageQueue);
});
}
Trism.setDomEvent = function(canvas) {
var context = canvas.getContext('2d');
var sizeX = 5;
var sizeY = 40;
var statusHighlight = new Trism.HighlightEffect(canvas, context, sizeY * 2);
Trism.rHighlight = function(slime) {
statusHighlight.kickEffect(sizeX * 32, 220, sizeY, function() { context.ShowStatus(slime); });
}
Trism.gHighlight = function(slime) {
statusHighlight.kickEffect(sizeX * 32, 260, sizeY, function() { context.ShowStatus(slime); });
}
Trism.bHighlight = function(slime) {
statusHighlight.kickEffect(sizeX * 32, 300, sizeY, function() { context.ShowStatus(slime); });
}
Trism.allHighlight = function(slime) {
statusHighlight.kickEffect(sizeX * 32, 220, sizeY * 3, function() { context.ShowStatus(slime); });
}
canvas.__context = context;
context.clearAll = function() { this.clearRect(0,0,canvas.width, canvas.height); };
context.font = "20px Courier"
context.ShowStatus = function(slime) {
this.clearAll();
slime.drawAt(context, 90, 140, 60, 45);
this.beginPath();
showBar('#aa0000', 220, slime.R);
showBar('#00aa00', 260, slime.G);
showBar('#0000aa', 300, slime.B);
this.stroke();
}
context.DiffStatus = function(stat1, stat2) {
this.clearAll();
stat2.drawAt(context, 120, 90, 45, 30);
stat1.drawAt(context, 70, 150, 60, 45);
this.beginPath();
showBar('#aa0000', 220, stat1.R, true);
showBar('#aa0000', 240, stat2.R, false);
showBar('#00aa00', 260, stat1.G, true);
showBar('#00aa00', 280, stat2.G, false);
showBar('#0000aa', 300, stat1.B, true);
showBar('#0000aa', 320, stat2.B, false);
this.stroke();
}
function showBar(color, y, value, half) {
var sy = (half === undefined) ? sizeY : sizeY / 2;
if (half !== undefined) {
if (half) {
context.fillStyle = "#666666"
} else {
context.fillStyle = "#444444"
}
context.fillRect(0, y, sizeX * 255, sy);
}
context.fillStyle = color;
context.fillRect(0, y, sizeX * value, sy);
context.fillStyle = "#ffffff";
context.fillText(value, 150, y+sy);
}
}
<file_sep>/Trism_Fight.js
Trism.Fight = function(me, enem) {
atkOnce();
if (isLose()) return false;
if (isWin()) {
return true;
}
function atkOnce() {
switch (Math.floor(Math.random() * 3)) {
case 0:
by(function(b) { return b.R; });
break;
case 1:
by(function(b) { return b.G; });
break;
case 2:
by(function(b) { return b.B; });
break;
}
function by(f) {
if (f(me) < f(enem)) {
me.R --;
me.G --;
me.B --;
} else if (f(me) > f(enem)) {
enem.R --;
enem.G --;
enem.B --;
}
}
}
function isLose() {
return (me.R <= 0
|| me.G <= 0
|| me.B <= 0
|| (me.R < enem.R
&& me.G < enem.G
&& me.B < enem.B));
}
function isWin() {
return (enem.R <= 0
|| enem.G <= 0
|| enem.B <= 0
|| (enem.R < me.R
&& enem.G < me.G
&& enem.B < me.B));
}
}
<file_sep>/Trism_LevelUp.js
(function () {
function StatusUp() {
this.getMessages = function() {
return [this._name + "の魔力があがった!"
, this._name + "の加護が増した!"
, this.SpecialMessage];
};
}
function StatusUpR() {
this._name = "火";
this.SpecialMessage = " 疲れを癒すために焚き火にあたろうとしたら\nやけどをした!\n......火の魔力が上がった!!";
this.event = function(slime) {
slime.R ++;
Trism.rHighlight(slime);
}
}
function StatusUpG() {
this._name = "風";
this.SpecialMessage = " 戦いの疲れか、風邪をひいてしまったようだ\n......風の魔力が上がったみたい!!";
this.event = function(slime) {
slime.G ++;
Trism.gHighlight(slime);
}
}
function StatusUpB() {
this._name = "水";
this.SpecialMessage = "雨降って水の魔力が上がる。";
this.event = function(slime) {
slime.B ++;
Trism.bHighlight(slime);
}
}
StatusUpR.prototype = new StatusUp();
StatusUpG.prototype = new StatusUp();
StatusUpB.prototype = new StatusUp();
function StatusUpAll() {
this.getMessages = function() {
return [" 「レベルが上がった!」\nとつぶやいてみた。\nなんとなく強くなった気がする!"
, " 神話的に有名な名剣を手に入れた!\nだがしかし、名剣はなぞの長広舌と鬱陶しい\nエンドレストークを披露した!!\n......目を覚ますと名剣はどこにもなかった。\n あまりの退屈に寝てしまったらしい。\n打ち切りになってしまったアニメへの想いを\n胸に旅路を続けた。"
, " 今気づいたんだけど、意外とデキル子だった!!"];
}
this.event = function(slime) {
slime.R ++;
slime.G ++;
slime.B ++;
Trism.allHighlight(slime);
}
}
var list = [
{ Rate: 32, Event: new StatusUpR() },
{ Rate: 32, Event: new StatusUpG() },
{ Rate: 32, Event: new StatusUpB() },
{ Rate: 4, Event: new StatusUpAll() },
];
var sumRate = 0;
for (var i = 0, iMax = list.length; i < iMax; i ++) {
sumRate += list[i].Rate;
}
Trism.LevelUp = function() {
var rnd = Math.floor(Math.random() * sumRate);
for (var i = 0, iMax = list.length; i < iMax; i ++) {
if (rnd < list[i].Rate) {
return list[i].Event;
}
rnd -= list[i].Rate;
}
throw "なんか間違った。";
}
})();
|
588fecbc0dcbe26d966ebf2134306694c2f76aae
|
[
"JavaScript"
] | 10
|
JavaScript
|
T-era/Trism
|
c5f3dd5c4db26e2da679e8b3a33a921d080d3dd4
|
a864d206e2608bd5412fddc560441e8cd7a50e09
|
refs/heads/master
|
<repo_name>miklbarre/website<file_sep>/src/Website/HomeBundle/Controller/HomeController.php
<?php
namespace Website\HomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\VarDumper\VarDumper;
class HomeController extends Controller {
public function indexAction () {
return $this->render("@WebsiteHome/index.html.twig");
}
public function speAction(Request $request) {
$date_debut = "2020-02-24 10:00";
$date_fin = "2020-02-24 10:20";
$objet = "Apprendre le PHP avec éééé ";
$lieu = "Maison";
$details = "Chapitre 2: connexion à une base de donnééééées";
$ics = "BEGIN:VCALENDAR\n";
$ics .= "VERSION:2.0\n";
$ics .= "PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n";
$ics .= "BEGIN:VEVENT\n";
$ics .= "DTSTART:".date('Ymd',strtotime($date_debut))."T".date('His',strtotime($date_debut))."\n";
$ics .= "DTEND:".date('Ymd',strtotime($date_fin))."T".date('His',strtotime($date_fin))."\n";
$ics .= "SUMMARY:".$objet."\n";
$ics .= "LOCATION:".$lieu."\n";
$ics .= "DESCRIPTION:".$details."\n";
$ics .= "END:VEVENT\n";
$ics .= "END:VCALENDAR\n";
return new Response($ics);
}
}<file_sep>/src/AppBundle/Services/CurlService.php
<?php
namespace AppBundle\Services;
class CurlService {
public function sendGetRequest ($url) {
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($curl);
}
}<file_sep>/src/Website/MusicBundle/WebsiteMusicBundle.php
<?php
namespace Website\MusicBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class WebsiteMusicBundle extends Bundle
{
}
<file_sep>/src/Website/HomeBundle/WebsiteHomeBundle.php
<?php
namespace Website\HomeBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class WebsiteHomeBundle extends Bundle
{
}
<file_sep>/src/Website/SerieBundle/WebsiteSerieBundle.php
<?php
namespace Website\SerieBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class WebsiteSerieBundle extends Bundle
{
}
<file_sep>/src/Website/MoviesBundle/Controller/MovieController.php
<?php
/**
* Created by PhpStorm.
* User: mickael
* Date: 31/08/17
* Time: 14:59
*/
namespace Website\MoviesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class MovieController extends Controller {
public function indexAction () {
return $this->render('@WebsiteMovies/index.html.twig');
}
public function getAllAction () {
$url = $this->getParameter('api_server').'movies/getAll';
$curlService = $this->get('website.curl_service');
$response = $curlService->sendGetRequest($url);
if(json_decode($response, true)) {
$movies = json_decode($response, true);
}
else {
$movies = array('data' => [], "draw" => 1, "recordsTotal" => 0, "recordsFiltered" => 0);
}
return new JsonResponse($movies);
}
}
<file_sep>/src/Website/SerieBundle/Controller/SeriesController.php
<?php
/**
* Created by PhpStorm.
* User: mickael
* Date: 10/09/17
* Time: 10:16
*/
namespace Website\SerieBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SeriesController extends Controller {
public function indexAction () {
$url = $this->getParameter('api_server').'series/getseries';
$curlService = $this->get('website.curl_service');
$response = $curlService->sendGetRequest($url);
$series = json_decode($response,true);
return $this->render('WebsiteSerieBundle::index.html.twig', array('series' => $series));
}
}<file_sep>/web/js/series/series.js
var series = function () {
return {
init: function (element) {
Main.init(element);
}
}
}();
<file_sep>/README.md
website
=======
A Symfony project created on August 30, 2017, 11:48 am.
<file_sep>/src/Website/MoviesBundle/WebsiteMoviesBundle.php
<?php
namespace Website\MoviesBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class WebsiteMoviesBundle extends Bundle
{
}
<file_sep>/src/Website/MusicBundle/Controller/MusicController.php
<?php
/**
* Created by PhpStorm.
* User: mickael
* Date: 01/09/17
* Time: 14:12
*/
namespace Website\MusicBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class MusicController extends Controller {
public function indexAction () {
return $this->render('@WebsiteMusic/index.html.twig');
}
public function getAllMusicsAction ()
{
$url = $this->getParameter('api_server') . 'musics/getallalbumbyartist';
$curlService = $this->get('website.curl_service');
$response = $curlService->sendGetRequest($url);
$musics = json_decode($response, true);
return new JsonResponse($musics);
}
}
|
b620f6b4a5f41d9b47618edeb9db26db5f0f60e9
|
[
"JavaScript",
"Markdown",
"PHP"
] | 11
|
PHP
|
miklbarre/website
|
c527de6fadce66babfd62e3373b7dc297374c63c
|
d3cf20abb458d74a30f4680a9f6f0da07ae72aa3
|
refs/heads/master
|
<file_sep>//
// UserLogInViewController.swift
// Final project
//
// Created by 徐乾智 on 4/30/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import VideoSplashKit
import Firebase
class UserLogInViewController: VideoSplashViewController, UITextFieldDelegate {
// MARK: - Outlets
@IBOutlet weak var userNameLabel: UILabel! {
didSet {
userNameLabel.textColor = UIColor.flatMint()
}
}
@IBOutlet weak var passwordLabel: UILabel! {
didSet {
passwordLabel.textColor = UIColor.flatMint()
}
}
@IBOutlet weak var userNameTextField: UITextField! {
didSet {
userNameTextField.autocorrectionType = .no
}
}
@IBOutlet weak var passwordTextField: UITextField! {
didSet {
passwordTextField.autocorrectionType = .no
passwordTextField.isSecureTextEntry = true
}
}
@IBOutlet weak var signinButton: UIButton! {
didSet {
signinButton.setTitleColor(UIColor.flatMint(), for: .normal)
}
}
@IBOutlet weak var registerButton: UIButton! {
didSet {
registerButton.setTitleColor(UIColor.flatMint(), for: .normal)
}
}
@IBOutlet weak var continueAsGuestButton: UIButton! {
didSet {
continueAsGuestButton.setTitleColor(UIColor.flatMint(), for: .normal)
}
}
// MARK: - Variables
// MARK - Inits
override func viewDidLoad() {
super.viewDidLoad()
let endEditTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(endEdit))
view.addGestureRecognizer(endEditTapGestureRecognizer)
userNameTextField.delegate = self
passwordTextField.delegate = self
let db = Firestore.firestore()
readFromFirebase(db: db, fromCollection: .count, fromDocument: "TotalCount")
insertVideo()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
userNameTextField.text = ""
passwordTextField.text = ""
}
// MARK: - Functions
@IBAction func signInButtonTapped(_ sender: UIButton) {
// Pull user data from firebase
if eventCounter == nil || recipeCounter == nil || userCounter == nil {
return
}
if (Users.count == 0) {
let db = Firestore.firestore()
for i in 0..<userCounter! {
readFromFirebase(db: db, fromCollection: .user, fromDocument: "User" + String(i))
}
}
if Events.count == 0 {
let db = Firestore.firestore()
for i in 0..<eventCounter! {
readFromFirebase(db: db, fromCollection: .event, fromDocument: "Event" + String(i))
}
}
if Recipes.count == 0 {
let db = Firestore.firestore()
for i in 0..<recipeCounter! {
readFromFirebase(db: db, fromCollection: .recipe, fromDocument: "Recipe" + String(i))
}
}
if let userIndex = userToIndex[userNameTextField.text!] {
if let userDict = Users[userIndex] as? Dictionary<String, Any> {
if let password = userDict["<PASSWORD>"] as? String {
if password == passwordTextField.text {
userIsLoggedIn = true
currentUser = userNameTextField.text
performSegue(withIdentifier: "SignInSegue", sender: self)
return
}
}
}
}
let alt = UIAlertController(title: "", message: "Invalid Log in", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
}))
self.present(alt, animated: true, completion: nil)
}
@IBAction func registerButtonTapped(_ sender: UIButton) {
if (Users.count == 0) {
let db = Firestore.firestore()
for i in 0..<userCounter! {
readFromFirebase(db: db, fromCollection: .user, fromDocument: "User" + String(i))
}
}
}
@IBAction func continueAsGuestButtonTapped(_ sender: UIButton) {
if eventCounter == nil || recipeCounter == nil || userCounter == nil {
return
}
if (Users.count == 0) {
let db = Firestore.firestore()
for i in 0..<userCounter! {
readFromFirebase(db: db, fromCollection: .user, fromDocument: "User" + String(i))
}
}
if Events.count == 0 {
let db = Firestore.firestore()
for i in 0..<eventCounter! {
readFromFirebase(db: db, fromCollection: .event, fromDocument: "Event" + String(i))
}
}
if Recipes.count == 0 {
let db = Firestore.firestore()
for i in 0..<recipeCounter! {
readFromFirebase(db: db, fromCollection: .recipe, fromDocument: "Recipe" + String(i))
}
}
if Recipes.count == 0 || Events.count == 0 || Users.count == 0 {
return
}
userIsLoggedIn = false
performSegue(withIdentifier: "SignInSegue", sender: self)
}
@IBAction func unwindToLoginPage(segue: UIStoryboardSegue) {}
func insertVideo() {
let url = NSURL.fileURL(withPath: Bundle.main.path(forResource: "test", ofType: "mov")!)
// let url = NSURL.fileURL(withPath: Bundle.main.path(forResource: "IMG_8550.MOV", ofType: "MOV")!)
self.videoFrame = view.frame
self.fillMode = .resizeAspectFill
self.alwaysRepeat = true
self.sound = false
self.startTime = 3.0
self.duration = 10.0
self.alpha = 0.7
self.backgroundColor = UIColor.black
self.contentURL = url
self.restartForeground = true
}
func textFieldDidEndEditing(_ textField: UITextField) {
if userCounter != nil {
if (Users.count == 0) {
for i in 0..<userCounter! {
let db = Firestore.firestore()
readFromFirebase(db: db, fromCollection: .user, fromDocument: "User" + String(i))
}
}
}
if eventCounter != nil {
if (Events.count == 0) {
for i in 0..<eventCounter! {
let db = Firestore.firestore()
readFromFirebase(db: db, fromCollection: .event, fromDocument: "Event" + String(i))
}
}
}
if recipeCounter != nil {
if (Recipes.count == 0) {
for i in 0..<recipeCounter! {
let db = Firestore.firestore()
readFromFirebase(db: db, fromCollection: .recipe, fromDocument: "Recipe" + String(i))
}
}
}
}
@objc func endEdit() {
if (userNameTextField.isEditing || passwordTextField.isEditing) {
view.endEditing(true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// NewRecipeDetailTableViewCell.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class NewRecipeTableViewCell: UITableViewCell {
// MARK: - Variables
var recipeName: String?
var recipeAuthor: String?
var recipeCategory: String?
var recipeCookTime: String?
var recipeServingNum: Int?
var recipeDescription: String?
var recipeIndex: Int?
var recipeIngredient: String?
var recipeProcedure: String?
// MARK: - Outlets
@IBOutlet weak var recipeImageView: UIImageView!
@IBOutlet weak var recipeTitleLabel: UILabel!
@IBOutlet weak var recipeInfoLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setRecipeImageView()
setRecipeAuthorLabel()
setRecipeTitleLabel()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setRecipeImageView() {
recipeImageView.image = UIImage(named: "duck-breast")
}
func setRecipeTitleLabel() {
// recipeTitleLabel.text = recipeName!
recipeTitleLabel.textAlignment = .left
recipeTitleLabel.textColor = .black
recipeTitleLabel.font = UIFont.systemFont(ofSize: 25)
}
func setRecipeAuthorLabel() {
// recipeInfoLabel.text = recipeCookTime!
recipeInfoLabel.textAlignment = .left
recipeInfoLabel.textColor = .black
recipeInfoLabel.font = UIFont.systemFont(ofSize: 15)
}
}
<file_sep>//
// NewRecipeDetailViewController.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class NewRecipeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
// MARK: - Variables
var recipeName: String?
var recipeAuthor: String?
var recipeCategory: String?
var recipeCookTime: String?
var recipeServingNum = 0
var recipeDescription = ""
var recipeIndex = 0
var recipeIngredient = ""
var recipeProcedure = ""
var allArr: [Int] = [Int]()
var currArr: [Int] = [Int]()
// MARK: - Outlets
@IBOutlet weak var recipeTableView: UITableView! {
didSet {
recipeTableView.delegate = self
recipeTableView.dataSource = self
}
}
@IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.barTintColor = themeColor
searchBar.delegate = self
searchBar.showsCancelButton = true
}
}
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
setUp()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return recipeCounter!
print(currArr)
print(Recipes)
return currArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewRecipeDetailTableViewCell") as? NewRecipeTableViewCell
// let position = recipeCounter! - indexPath.row - 1
let position = currArr[currArr.count - indexPath.row - 1]
if let recipe = Recipes[position] {
cell?.recipeTitleLabel.text = (recipe["Name"] as? String)!
cell?.recipeInfoLabel.text = (recipe["CookTime"] as? String)! + ", Serves " + String((recipe["Serves"] as? Int)!)
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let position = recipeCounter! - indexPath.row - 1
let position = currArr[currArr.count - indexPath.row - 1]
if let recipe = Recipes[position] {
recipeName = (recipe["Name"] as? String)!
recipeCookTime = (recipe["CookTime"] as? String)!
recipeServingNum = (recipe["Serves"] as? Int)!
recipeDescription = (recipe["Description"] as? String)!
recipeIndex = (recipe["Index"] as? Int)!
recipeIngredient = (recipe["Ingredient"] as? String)!
recipeProcedure = (recipe["Procedure"] as? String)!
recipeAuthor = (recipe["Author"] as? String)!
recipeCategory = (recipe["Category"] as? String)!
performSegue(withIdentifier: "RecipeTappedSegue", sender: self)
}
}
// MARK: - Functions
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
currArr = allArr
} else {
currArr = allArr.filter({index -> Bool in
if let cate = Recipes[index]!["Category"] as? String {
if let name = Recipes[index]!["Name"] as? String {
if let descript = Recipes[index]!["Description"] as? String {
if cate.lowercased().contains(searchText.lowercased()) || name.lowercased().contains(searchText.lowercased()) || descript.lowercased().contains(searchText.lowercased()) {
return true
}
}
}
}
return false
})
}
self.recipeTableView.reloadData()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
view.endEditing(true)
}
// func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
// switch selectedScope {
// case 0:
// currArr = allArr
// case 1:
// currArr = allArr.filter({index -> Bool in
// if let cate = Recipes[index]!["Category"] as? String {
// if cate.lowercased().contains("protein") {
// return true
// }
// }
// return false
// })
// case 2:
// currArr = allArr.filter({index -> Bool in
// if let cate = Recipes[index]!["Category"] as? String {
// if cate.lowercased().contains("vegetarian") {
// return true
// }
// }
// return false
// })
// case 3:
// currArr = allArr.filter({index -> Bool in
// if let cate = Recipes[index]!["Category"] as? String {
// if cate.lowercased().contains("bakery") {
// return true
// }
// }
// return false
// })
// default:
// break
// }
// }
func setUp() {
if #available(iOS 10.0, *) {
recipeTableView.refreshControl = UIRefreshControl()
recipeTableView.refreshControl?.addTarget(self, action: #selector(refreshHandler), for: .valueChanged)
}
}
@objc func refreshHandler() {
let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { [weak self] in
if #available(iOS 10.0, *) {
self?.recipeTableView.refreshControl?.endRefreshing()
}
self?.recipeTableView.reloadData()
})
for key in Recipes.keys {
if !allArr.contains(key) {
allArr.append(key)
}
}
for key in Recipes.keys {
if !currArr.contains(key) {
currArr.append(key)
}
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? RecipeDetailViewController {
dest.recipeName = recipeName!
dest.recipeCookTime = recipeCookTime!
dest.recipeCategory = recipeCategory!
dest.recipeAuthor = recipeAuthor
dest.recipeProcedure = recipeProcedure
dest.recipeServingNum = recipeServingNum
dest.recipeDescription = recipeDescription
dest.recipeIndex = recipeIndex
dest.recipeIngredient = recipeIngredient
}
}
}
<file_sep>//
// LikedRecipeTableViewController.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class LikedRecipeTableViewController: UITableViewController {
var recipeAtRow: [Int] = Array(repeating: 0, count: recipeCounter!)
var recipeName: String?
var recipeAuthor: String?
var recipeCategory: String?
var recipeCookTime: String?
var recipeServingNum: Int?
var recipeDescription: String?
var recipeIndex: Int?
var recipeIngredient: String?
var recipeProcedure: String?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let index: Int = userToIndex[currentUser!]!
if let recipes = Users[index]!["LikedRecipe"] as? [Int] {
return recipes.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LikedRecipeTableViewCell", for: indexPath) as? LikedRecipeTableViewCell
let userIndex: Int = userToIndex[currentUser!]!
if let recipes = Users[userIndex]!["LikedRecipe"] as? [Int] {
let position = recipes.count - indexPath.row - 1
cell?.recipeImageView.image = UIImage(named: "duck-breast")
let recipeIndex = recipes[position]
recipeAtRow[indexPath.row] = recipeIndex
cell?.recipeTitleLabel.text = Recipes[recipeIndex]!["Name"] as! String
cell?.recipeAuthor.text = Recipes[recipeIndex]!["Author"] as! String
}
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let position = recipeAtRow[indexPath.row]
if let recipe = Recipes[position] {
recipeName = (recipe["Name"] as? String)!
recipeCookTime = (recipe["CookTime"] as? String)!
recipeServingNum = (recipe["Serves"] as? Int)!
recipeDescription = (recipe["Description"] as? String)!
recipeIndex = (recipe["Index"] as? Int)!
recipeIngredient = (recipe["Ingredient"] as? String)!
recipeProcedure = (recipe["Procedure"] as? String)!
recipeAuthor = (recipe["Author"] as? String)!
recipeCategory = (recipe["Category"] as? String)!
performSegue(withIdentifier: "ShowRecipeDetailFromLiked", sender: self)
}
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? LikedRecipeDetailViewController {
dest.recipeName = recipeName!
dest.recipeCookTime = recipeCookTime!
dest.recipeCategory = recipeCategory!
dest.recipeAuthor = recipeAuthor
dest.recipeProcedure = recipeProcedure
dest.recipeServingNum = recipeServingNum
dest.recipeDescription = recipeDescription
dest.recipeIndex = recipeIndex
dest.recipeIngredient = recipeIngredient
}
}
}
<file_sep>//
// UploadRecipeViewController.swift
// Final project
//
// Created by 徐乾智 on 4/30/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class UploadRecipeViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
// -------------------------------
// This is where user input recipe information stored
private var dict: Dictionary<String, Any> = ["CookTime": "",
"Name": "",
"Serves": 0,
"Author": "",
"Description": "",
"Ingredient": "",
"Procedure": "",
"Category": ""]
var index = 0
var hours = 0
var mins = 0
var servingNum = 0
var recipeTitle: String?
var recipeDescription: String?
var recipeIngredients: String?
var recipeProcedure: String?
var recipeCategory: String?
// -------------------------------
// MARK: - Outlets
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
setUserProfileImageView(isSettingAttributes: true)
setRecipeTitleLabel(isSettingAttributes: true)
setRecipeTitleTextField(isSettingAttributes: true)
setRecipeCategoryLabel(isSettingAttributes: true)
setRecipeCategoryTextField(isSettingAttributes: true)
setRecipeDescriptionLabel(isSettingAttributes: true)
setRecipeDescriptionTextView(isSettingAttributes: true)
setCookingTimeLabel(isSettingAttributes: true)
setCookingTimeTextField(isSettingAttributes: true)
setServingNumberLabel(isSettingAttributes: true)
setServingNumberTextField(isSettingAttributes: true)
setIngredientLabel(isSettingAttributes: true)
setIngredientTextView(isSettingAttributes: true)
setProcedureLabel(isSettingAttributes: true)
setProcedureTextView(isSettingAttributes: true)
setUploadImageButton(isSettingAttributes: true)
setUploadCompleteButton(isSettingAttributes: true)
}
}
// MARK: - Variables
var userProfileImageView = UIImageView()
var recipeTitleLabel = UILabel()
var recipeTitleTextField = UITextField()
var recipeCategoryLabel = UILabel()
var recipeCategoryTextField = UITextField()
var recipeDescriptionLabel = UILabel()
var recipeDescriptionTextView = UITextView()
var cookingTimeLabel = UILabel()
var cookingTimeTextField = UITextField()
var servingNumberLabel = UILabel()
var servingNumberTextField = UITextField()
var cookingTimePickerView = UIPickerView()
var servingNumberPickerView = UIPickerView()
var ingredientLabel = UILabel()
var ingredientTextView = UITextView()
var procedureLabel = UILabel()
var procedureTextView = UITextView()
var uploadImageButton = UIButton()
var uploadCompleteButton = UIButton()
var currentHeightScrollable: CGFloat = 10
// MARK: - Inits
override func viewDidLoad() {
super.viewDidLoad()
cookingTimePickerView.delegate = self
cookingTimePickerView.dataSource = self
servingNumberPickerView.delegate = self
servingNumberPickerView.dataSource = self
let endEditTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(endEdit))
scrollView.addGestureRecognizer(endEditTapGestureRecognizer)
scrollView.backgroundColor = UIColor.flatMintColorDark()
setUserProfileImageView(isSettingAttributes: false)
setRecipeTitleLabel(isSettingAttributes: false)
setRecipeTitleTextField(isSettingAttributes: false)
setRecipeCategoryLabel(isSettingAttributes: false)
setRecipeCategoryTextField(isSettingAttributes: false)
setRecipeDescriptionLabel(isSettingAttributes: false)
setRecipeDescriptionTextView(isSettingAttributes: false)
setCookingTimeLabel(isSettingAttributes: false)
setCookingTimeTextField(isSettingAttributes: false)
setServingNumberLabel(isSettingAttributes: false)
setServingNumberTextField(isSettingAttributes: false)
setIngredientLabel(isSettingAttributes: false)
setIngredientTextView(isSettingAttributes: false)
setProcedureLabel(isSettingAttributes: false)
setProcedureTextView(isSettingAttributes: false)
setUploadImageButton(isSettingAttributes: false)
setUploadCompleteButton(isSettingAttributes: false)
scrollView.contentSize = CGSize(width: view.frame.width, height: currentHeightScrollable + 100)
// Do any additional setup after loading the view.
}
// MARK: - Functions
func setUserProfileImageView(isSettingAttributes: Bool) {
if isSettingAttributes {
userProfileImageView.image = UIImage(named: "user-profile")!
} else {
userProfileImageView.frame = CGRect(x: 20, y: 20, width: 60, height: 60)
currentHeightScrollable += userProfileImageView.frame.height + 30
scrollView.addSubview(userProfileImageView)
}
}
func setRecipeTitleLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
recipeTitleLabel.text = "Recipe Name"
recipeTitleLabel.textAlignment = .left
recipeTitleLabel.textColor = .black
recipeTitleLabel.font = UIFont.systemFont(ofSize: 30)
} else {
recipeTitleLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += recipeTitleLabel.frame.height
scrollView.addSubview(recipeTitleLabel)
}
}
func setRecipeTitleTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
recipeTitleTextField.borderStyle = .roundedRect
} else {
recipeTitleTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 40)
currentHeightScrollable += recipeTitleTextField.frame.height + 30
scrollView.addSubview(recipeTitleTextField)
}
}
func setRecipeCategoryLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
recipeCategoryLabel.text = "Describe your recipe category"
recipeCategoryLabel.textAlignment = .left
recipeCategoryLabel.textColor = .black
recipeCategoryLabel.font = UIFont.systemFont(ofSize: 30)
} else {
recipeCategoryLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += recipeCategoryLabel.frame.height
scrollView.addSubview(recipeCategoryLabel)
}
}
func setRecipeCategoryTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
recipeCategoryTextField.borderStyle = .roundedRect
} else {
recipeCategoryTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 40)
currentHeightScrollable += recipeCategoryTextField.frame.height + 30
scrollView.addSubview(recipeCategoryTextField)
}
}
func setRecipeDescriptionLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
recipeDescriptionLabel.text = "Recipe Description"
recipeDescriptionLabel.textAlignment = .left
recipeDescriptionLabel.textColor = .black
recipeDescriptionLabel.font = UIFont.systemFont(ofSize: 30)
} else {
recipeDescriptionLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += recipeDescriptionLabel.frame.height
scrollView.addSubview(recipeDescriptionLabel)
}
}
func setRecipeDescriptionTextView(isSettingAttributes: Bool) {
if isSettingAttributes {
recipeDescriptionTextView.isEditable = true
recipeDescriptionTextView.layer.borderColor = UIColor.lightGray.cgColor
recipeDescriptionTextView.layer.borderWidth = 0.5
recipeDescriptionTextView.layer.cornerRadius = 5.0
recipeDescriptionTextView.font = UIFont.systemFont(ofSize: 24)
} else {
recipeDescriptionTextView.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 300)
currentHeightScrollable += recipeDescriptionTextView.frame.height + 30
scrollView.addSubview(recipeDescriptionTextView)
}
}
func setCookingTimeLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
cookingTimeLabel.text = "Cooking Time"
cookingTimeLabel.textAlignment = .left
cookingTimeLabel.textColor = .black
cookingTimeLabel.font = UIFont.systemFont(ofSize: 30)
} else {
cookingTimeLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += cookingTimeLabel.frame.height
scrollView.addSubview(cookingTimeLabel)
}
}
func setCookingTimeTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
cookingTimeTextField.borderStyle = .roundedRect
cookingTimeTextField.inputView = cookingTimePickerView
} else {
cookingTimeTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += cookingTimeTextField.frame.height + 20
scrollView.addSubview(cookingTimeTextField)
}
}
func setServingNumberLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
servingNumberLabel.text = "Serves"
servingNumberLabel.textAlignment = .left
servingNumberLabel.textColor = .black
servingNumberLabel.font = UIFont.systemFont(ofSize: 30)
} else {
servingNumberLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += servingNumberLabel.frame.height
scrollView.addSubview(servingNumberLabel)
}
}
func setServingNumberTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
servingNumberTextField.borderStyle = .roundedRect
servingNumberTextField.inputView = servingNumberPickerView
} else {
servingNumberTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += servingNumberTextField.frame.height + 20
scrollView.addSubview(servingNumberTextField)
}
}
func setIngredientLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
ingredientLabel.text = "List ingredients needed"
ingredientLabel.textAlignment = .left
ingredientLabel.textColor = .black
ingredientLabel.font = UIFont.systemFont(ofSize: 30)
} else {
ingredientLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += ingredientLabel.frame.height
scrollView.addSubview(ingredientLabel)
}
}
func setIngredientTextView(isSettingAttributes: Bool) {
if isSettingAttributes {
ingredientTextView.isEditable = true
ingredientTextView.layer.borderColor = UIColor.lightGray.cgColor
ingredientTextView.layer.borderWidth = 0.5
ingredientTextView.layer.cornerRadius = 5.0
ingredientTextView.font = UIFont.systemFont(ofSize: 24)
} else {
ingredientTextView.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 300)
currentHeightScrollable += ingredientTextView.frame.height + 30
scrollView.addSubview(ingredientTextView)
}
}
func setProcedureLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
procedureLabel.text = "Describe the procedure"
procedureLabel.textAlignment = .left
procedureLabel.textColor = .black
procedureLabel.font = UIFont.systemFont(ofSize: 30)
} else {
procedureLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += procedureLabel.frame.height
scrollView.addSubview(procedureLabel)
}
}
func setProcedureTextView(isSettingAttributes: Bool) {
if isSettingAttributes {
procedureTextView.isEditable = true
procedureTextView.layer.borderColor = UIColor.lightGray.cgColor
procedureTextView.layer.borderWidth = 0.5
procedureTextView.layer.cornerRadius = 5.0
procedureTextView.font = UIFont.systemFont(ofSize: 24)
} else {
procedureTextView.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 300)
currentHeightScrollable += procedureTextView.frame.height + 30
scrollView.addSubview(procedureTextView)
}
}
func setUploadImageButton(isSettingAttributes: Bool) {
if isSettingAttributes {
uploadImageButton.setAttributedTitle(NSAttributedString(string: "Upload Image", attributes: [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue, NSAttributedString.Key.underlineColor: UIColor.flatMintColorDark()]), for: .normal)
uploadImageButton.setTitleColor(UIColor.blue, for: .normal)
uploadImageButton.contentHorizontalAlignment = .left
uploadImageButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
// uploadImageButton.addTarget(self, action: #selector(uploadImageButtonTapped), for: .touchUpInside)
} else {
uploadImageButton.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += uploadImageButton.frame.height + 15
scrollView.addSubview(uploadImageButton)
}
}
func setUploadCompleteButton(isSettingAttributes: Bool) {
if isSettingAttributes {
uploadCompleteButton.setTitle("Upload", for: .normal)
uploadCompleteButton.setTitleColor(UIColor.white, for: .normal)
uploadCompleteButton.backgroundColor = UIColor.flatMint()
uploadCompleteButton.addTarget(self, action: #selector(uploadCompleteButtonTapped), for: .touchUpInside)
} else {
uploadCompleteButton.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += uploadCompleteButton.frame.height
scrollView.addSubview(uploadCompleteButton)
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if (pickerView == cookingTimePickerView) {
return 2
} else {
return 1
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (pickerView == cookingTimePickerView) {
if component == 0 {
return 10
} else {
return 60
}
} else {
return 10
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (pickerView == cookingTimePickerView) {
return String(row)
} else {
return String(row + 1)
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (pickerView == cookingTimePickerView) {
var str = ""
if (component == 0) {
hours = row
} else {
mins = row
}
if (hours == 0) {
str = String(mins) + " mins"
} else if (mins == 0) {
str = String(hours) + " hours"
} else {
str = String(hours) + " hours, " + String(mins) + " mins"
}
cookingTimeTextField.text = str
} else {
servingNum = row + 1
servingNumberTextField.text = String(row + 1)
}
}
@objc func uploadCompleteButtonTapped() {
if (recipeTitleTextField.text == "" || recipeDescriptionTextView.text == "" || ingredientTextView.text == "" || procedureTextView.text == "" || cookingTimeTextField.text == "" || servingNumberTextField.text == "" || recipeCategoryTextField.text == "") {
let alt = UIAlertController(title: "", message: "Fill in all the blank before uploading", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
}))
self.present(alt, animated: true, completion: nil)
} else {
recipeTitle = recipeTitleTextField.text
recipeDescription = recipeDescriptionTextView.text
recipeIngredients = ingredientTextView.text
recipeProcedure = procedureTextView.text
recipeCategory = recipeCategoryTextField.text
var cookTime = ""
if (hours == 0) {
cookTime = String(mins) + " mins"
} else if (mins == 0) {
cookTime = String(hours) + " hours"
} else {
cookTime = String(hours) + " hours, " + String(mins) + " mins"
}
dict["CookTime"] = cookTime
dict["Name"] = recipeTitle
dict["Serves"] = servingNum
dict["Author"] = currentUser
dict["Description"] = recipeDescription
dict["Ingredient"] = recipeIngredients
dict["Procedure"] = recipeProcedure
dict["Category"] = recipeCategory
dict["Index"] = recipeCounter
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .recipe, toDocument: "Recipe" + String(recipeCounter!), withDictionary: dict)
Recipes[recipeCounter!] = dict
recipeCounter! += 1
let alt = UIAlertController(title: "", message: "Upload Successful", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
self.performSegue(withIdentifier: "RecipeUploadCompleteSegue", sender: self)
}))
self.present(alt, animated: true, completion: nil)
}
}
@objc func endEdit() {
// if (cookingTimeTextField.isEditing || servingNumberTextField.isEditing || recipeTitleTextField.isEditing || recipeCategoryTextField.isEditing) {
// view.endEditing(true)
// }
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// EventDetailViewController.swift
// Final project
//
// Created by 徐乾智 on 4/8/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class EventDetailViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
setEventImageView(isSettingAttributes: true)
setEventTitleLabel(isSettingAttributes: true)
setEventDateLabel(isSettingAttributes: true)
setEventTimeLabel(isSettingAttributes: true)
setLikeButton(isSettingAttributes: true)
setEventTextView(isSettingAttributes: true)
// Add subviews to scrollview
}
}
// MARK: - Variables
var eventIndex: Int?
var eventAddress: String?
var eventDescription: String?
var eventName: String?
var eventType: String?
var eventHost: String?
var eventLiked: Int?
var eventTime: Date?
var eventImageView = UIImageView()
var eventTitleLabel = UILabel()
var eventDateLabel = UILabel()
var eventTimeLabel = UILabel()
var likeButton = UIButton()
var eventTextView = UITextView()
var currentHeightScrollable: CGFloat = 0
let spacer: CGFloat = 20
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
// self.navigationItem.title = eventName
setEventImageView(isSettingAttributes: false)
setEventTitleLabel(isSettingAttributes: false)
setEventDateLabel(isSettingAttributes: false)
setEventTimeLabel(isSettingAttributes: false)
setLikeButton(isSettingAttributes: false)
setEventTextView(isSettingAttributes: false)
scrollView.contentSize = CGSize(width: view.frame.width, height: currentHeightScrollable)
// Do any additional setup after loading the view.
}
// MARK: - Functions
func setEventImageView(isSettingAttributes: Bool) {
if (isSettingAttributes) {
eventImageView.image = UIImage(named: "event")
} else {
eventImageView.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: view.frame.width)
currentHeightScrollable += eventImageView.frame.height + spacer
scrollView.addSubview(eventImageView)
}
}
func setEventTitleLabel(isSettingAttributes: Bool) {
if (isSettingAttributes) {
eventTitleLabel.text = eventName!
eventTitleLabel.textAlignment = .left
eventTitleLabel.textColor = .black
eventTitleLabel.numberOfLines = 0
eventTitleLabel.lineBreakMode = .byWordWrapping
eventTitleLabel.font = UIFont.systemFont(ofSize: 40)
eventTitleLabel.backgroundColor = UIColor.white
} else {
eventTitleLabel.frame = CGRect(x: 20, y: currentHeightScrollable, width: view.frame.width, height: 80)
currentHeightScrollable += eventTitleLabel.frame.height
scrollView.addSubview(eventTitleLabel)
}
}
func setEventDateLabel(isSettingAttributes: Bool) {
if (isSettingAttributes) {
if eventTime == nil {
eventDateLabel.text = "Loading..."
} else {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
dateFormatter.timeZone = NSTimeZone.local
eventDateLabel.text = dateFormatter.string(from: eventTime!)
}
eventDateLabel.textAlignment = .left
eventDateLabel.textColor = .lightGray
eventDateLabel.font = UIFont.systemFont(ofSize: 15)
eventDateLabel.backgroundColor = UIColor.white
} else {
eventDateLabel.frame = CGRect(x: 20, y: currentHeightScrollable, width: view.frame.width, height: 30)
currentHeightScrollable += eventDateLabel.frame.height
scrollView.addSubview(eventDateLabel)
}
}
func setEventTimeLabel(isSettingAttributes: Bool) {
if (isSettingAttributes) {
if eventTime == nil {
eventTimeLabel.text = "Loading..."
} else {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
dateFormatter.timeZone = NSTimeZone.local
eventTimeLabel.text = dateFormatter.string(from: eventTime!)
}
eventTimeLabel.textAlignment = .left
eventTimeLabel.textColor = .lightGray
eventTimeLabel.font = UIFont.systemFont(ofSize: 15)
eventTimeLabel.backgroundColor = UIColor.white
} else {
eventTimeLabel.frame = CGRect(x: 20, y: currentHeightScrollable, width: view.frame.width, height: 30)
currentHeightScrollable += eventTimeLabel.frame.height + spacer
scrollView.addSubview(eventTimeLabel)
}
}
func setLikeButton(isSettingAttributes: Bool) {
if isSettingAttributes {
likeButton.setTitle("Like this event", for: .normal)
likeButton.setTitleColor(UIColor.black, for: .normal)
likeButton.backgroundColor = UIColor.flatMintColorDark()
likeButton.addTarget(self, action: #selector(likeButtonTapped), for: .touchUpInside)
} else {
likeButton.frame = CGRect(x: 20, y: currentHeightScrollable, width: view.frame.width - 40, height: 50)
currentHeightScrollable += likeButton.frame.height + 30
scrollView.addSubview(likeButton)
}
}
func setEventTextView(isSettingAttributes: Bool) {
if (isSettingAttributes) {
eventTextView.textAlignment = .left
eventTextView.text = eventDescription!
eventTextView.textColor = .black
eventTextView.font = UIFont.systemFont(ofSize: 20)
eventTextView.isEditable = false
eventTextView.isScrollEnabled = true
eventTextView.isUserInteractionEnabled = false
eventTextView.backgroundColor = .white
} else {
eventTextView.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: generateHeightWithStringLenghth(text: eventDescription!))
currentHeightScrollable += eventTextView.frame.height
scrollView.addSubview(eventTextView)
}
}
@objc func likeButtonTapped() {
if currentUser == nil {
let alt = UIAlertController(title: "", message: "You need to log in first", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
} else {
let alt = UIAlertController(title: "", message: "Event added to your Like List!", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
let userIndex: Int = userToIndex[currentUser!]!
if Users[userIndex]!["LikedEvent"] as? String == "None" {
var lst = [Int]()
lst.append(self.eventIndex!)
Users[userIndex]!["LikedEvent"] = lst
var dict: Dictionary<String, Any> = Users[userIndex]!
dict["LikedEvent"] = lst
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .user, toDocument: "User" + String(userIndex), withDictionary: dict)
} else {
var lst = Users[userIndex]!["LikedEvent"] as! [Int]
if !lst.contains(self.eventIndex!) {
lst.append(self.eventIndex!)
Users[userIndex]!["LikedEvent"] = lst
var dict: Dictionary<String, Any> = Users[userIndex]!
dict["LikedEvent"] = lst
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .user, toDocument: "User" + String(userIndex), withDictionary: dict)
} else {
alt.message = "This event is already in your Like list"
}
}
}))
self.present(alt, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// CollectionViewCell.swift
// Final project
//
// Created by 徐乾智 on 4/23/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class RecipeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var recipeImage: UIImageView! {
didSet {
recipeImage.isUserInteractionEnabled = true
}
}
}
<file_sep>//
// LikedRecipeTableViewCell.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class LikedRecipeTableViewCell: UITableViewCell {
@IBOutlet weak var recipeImageView: UIImageView!
@IBOutlet weak var recipeTitleLabel: UILabel!
@IBOutlet weak var recipeAuthor: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setRecipeImageView()
setRecipeAuthorLabel()
setRecipeTitleLabel()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setRecipeImageView() {
recipeImageView.image = UIImage(named: "duck-breast")
}
func setRecipeTitleLabel() {
recipeTitleLabel.text = "Recipe Title"
recipeTitleLabel.textAlignment = .left
recipeTitleLabel.textColor = .black
recipeTitleLabel.font = UIFont.systemFont(ofSize: 25)
}
func setRecipeAuthorLabel() {
recipeAuthor.text = "XQZ"
recipeAuthor.textAlignment = .left
recipeAuthor.textColor = .black
recipeAuthor.font = UIFont.systemFont(ofSize: 15)
}
}
<file_sep>//
// UploadEventViewController.swift
// Final project
//
// Created by 徐乾智 on 4/30/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class UploadEventViewController: UIViewController {
// -------------------------------
// This is where user input event information stored
private var dict: Dictionary<String, Any> = ["Address": 0,
"EventName": 0,
"EventType": "",
"Host": "",
"Liked": 1000,
"Time": 0]
var index = 0
var eventTitle: String?
var eventAddress: String?
var eventDescription: String?
var selectedEventDate: Date?
var selectedEventTime: Date?
var eventType: String?
// -------------------------------
// MARK: - Outlets
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
let endEditTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(endEdit))
scrollView.addGestureRecognizer(endEditTapGestureRecognizer)
setUserProfileImageView(isSettingAttributes: true)
setEventTitleLabel(isSettingAttributes: true)
setEventTitleTextField(isSettingAttributes: true)
setEventTypeLabel(isSettingAttributes: true)
setEventTypeTextField(isSettingAttributes: true)
setEventAddressLabel(isSettingAttributes: true)
setEventAddressTextField(isSettingAttributes: true)
setEventDescriptionLabel(isSettingAttributes: true)
setEventDescriptionTextField(isSettingAttributes: true)
setEventDateLabel(isSettingAttributes: true)
setEventDateTextField(isSettingAttributes: true)
setEventTimeLabel(isSettingAttributes: true)
setEventTimeTextField(isSettingAttributes: true)
setEventDatePickerView(isSettingAttributes: true)
setEventTimePickerView(isSettingAttributes: true)
setUploadImageButton(isSettingAttributes: true)
setUploadCompleteButton(isSettingAttributes: true)
}
}
// MARK: - Variables
var userProfileImageView = UIImageView()
var eventTitleLabel = UILabel()
var eventTitleTextField = UITextField()
var eventTypeLabel = UILabel()
var eventTypeTextField = UITextField()
var eventAddressLabel = UILabel()
var eventAddressTextField = UITextField()
var eventDescriptionLabel = UILabel()
var eventDescriptionTextField = UITextView()
var eventDateLabel = UILabel()
var eventTimeLabel = UILabel()
var eventDateTextField = UITextField()
var eventTimeTextField = UITextField()
var eventDatePickerView = UIDatePicker()
var eventTimePickerView = UIDatePicker()
var uploadImageButton = UIButton()
var uploadCompleteButton = UIButton()
var currentHeightScrollable: CGFloat = 10
var currentDate = Date()
// MARK: - Inits
override func viewDidLoad() {
super.viewDidLoad()
scrollView.backgroundColor = UIColor.flatMintColorDark()
setUserProfileImageView(isSettingAttributes: false)
setEventTitleLabel(isSettingAttributes: false)
setEventTitleTextField(isSettingAttributes: false)
setEventTypeLabel(isSettingAttributes: false)
setEventTypeTextField(isSettingAttributes: false)
setEventAddressLabel(isSettingAttributes: false)
setEventAddressTextField(isSettingAttributes: false)
setEventDescriptionLabel(isSettingAttributes: false)
setEventDescriptionTextField(isSettingAttributes: false)
setEventDateLabel(isSettingAttributes: false)
setEventDateTextField(isSettingAttributes: false)
setEventTimeLabel(isSettingAttributes: false)
setEventTimeTextField(isSettingAttributes: false)
setEventDatePickerView(isSettingAttributes: false)
setEventTimePickerView(isSettingAttributes: false)
setUploadImageButton(isSettingAttributes: false)
setUploadCompleteButton(isSettingAttributes: false)
scrollView.contentSize = CGSize(width: view.frame.width, height: currentHeightScrollable + 400)
// Do any additional setup after loading the view.
}
// MARK: - Functions
func setUserProfileImageView(isSettingAttributes: Bool) {
if isSettingAttributes {
userProfileImageView.image = UIImage(named: "user-profile")!
} else {
userProfileImageView.frame = CGRect(x: 20, y: 20, width: 60, height: 60)
currentHeightScrollable += userProfileImageView.frame.height + 30
scrollView.addSubview(userProfileImageView)
}
}
func setEventTitleLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTitleLabel.text = "Event Title"
eventTitleLabel.textAlignment = .left
eventTitleLabel.textColor = .black
eventTitleLabel.font = UIFont.systemFont(ofSize: 24)
} else {
eventTitleLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += eventTitleLabel.frame.height
scrollView.addSubview(eventTitleLabel)
}
}
func setEventTitleTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTitleTextField.borderStyle = .roundedRect
} else {
eventTitleTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 40)
currentHeightScrollable += eventTitleTextField.frame.height + 30
scrollView.addSubview(eventTitleTextField)
}
}
func setEventTypeLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTypeLabel.text = "Describe your Event Type"
eventTypeLabel.textAlignment = .left
eventTypeLabel.textColor = .black
eventTypeLabel.font = UIFont.systemFont(ofSize: 24)
} else {
eventTypeLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += eventTypeLabel.frame.height
scrollView.addSubview(eventTypeLabel)
}
}
func setEventTypeTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTypeTextField.borderStyle = .roundedRect
} else {
eventTypeTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 40)
currentHeightScrollable += eventTypeTextField.frame.height + 30
scrollView.addSubview(eventTypeTextField)
}
}
func setEventAddressLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
eventAddressLabel.text = "Event Address"
eventAddressLabel.textAlignment = .left
eventAddressLabel.textColor = .black
eventAddressLabel.font = UIFont.systemFont(ofSize: 24)
} else {
eventAddressLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += eventAddressLabel.frame.height
scrollView.addSubview(eventAddressLabel)
}
}
func setEventAddressTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
eventAddressTextField.borderStyle = .roundedRect
} else {
eventAddressTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 40)
currentHeightScrollable += eventAddressTextField.frame.height + 30
scrollView.addSubview(eventAddressTextField)
}
}
func setEventDescriptionLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
eventDescriptionLabel.text = "Event Description"
eventDescriptionLabel.textAlignment = .left
eventDescriptionLabel.textColor = .black
eventDescriptionLabel.font = UIFont.systemFont(ofSize: 24)
} else {
eventDescriptionLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += eventDescriptionLabel.frame.height
scrollView.addSubview(eventDescriptionLabel)
}
}
func setEventDescriptionTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
eventDescriptionTextField.isEditable = true
eventDescriptionTextField.layer.borderColor = UIColor.lightGray.cgColor
eventDescriptionTextField.layer.borderWidth = 0.5
eventDescriptionTextField.layer.cornerRadius = 5.0
eventDescriptionTextField.font = UIFont.systemFont(ofSize: 20)
} else {
eventDescriptionTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 300)
currentHeightScrollable += eventDescriptionTextField.frame.height + 30
scrollView.addSubview(eventDescriptionTextField)
}
}
func setEventDateLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
eventDateLabel.text = "Choose event date"
eventDateLabel.textAlignment = .left
eventDateLabel.textColor = .black
eventDateLabel.font = UIFont.systemFont(ofSize: 15)
} else {
eventDateLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 30)
currentHeightScrollable += eventDateLabel.frame.height
scrollView.addSubview(eventDateLabel)
}
}
func setEventDateTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
eventDateTextField.borderStyle = .roundedRect
eventDateTextField.inputView = eventDatePickerView
} else {
eventDateTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += eventDateTextField.frame.height + 20
scrollView.addSubview(eventDateTextField)
}
}
func setEventTimeLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTimeLabel.text = "Choose event time"
eventTimeLabel.textAlignment = .left
eventTimeLabel.textColor = .black
eventTimeLabel.font = UIFont.systemFont(ofSize: 15)
} else {
eventTimeLabel.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width, height: 30)
currentHeightScrollable += eventTimeLabel.frame.height
scrollView.addSubview(eventTimeLabel)
}
}
func setEventTimeTextField(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTimeTextField.borderStyle = .roundedRect
eventTimeTextField.inputView = eventTimePickerView
} else {
eventTimeTextField.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += eventTimeTextField.frame.height + 20
scrollView.addSubview(eventTimeTextField)
}
}
func setEventDatePickerView(isSettingAttributes: Bool) {
if isSettingAttributes {
eventDatePickerView.datePickerMode = .date
eventDatePickerView.addTarget(self, action: #selector(eventDateChanged(datePicker:)), for: .valueChanged)
} else {
}
}
func setEventTimePickerView(isSettingAttributes: Bool) {
if isSettingAttributes {
eventTimePickerView.datePickerMode = .time
eventTimePickerView.addTarget(self, action: #selector(eventTimeChanged(datePicker:)), for: .valueChanged)
} else {
}
}
func setUploadImageButton(isSettingAttributes: Bool) {
if isSettingAttributes {
uploadImageButton.setAttributedTitle(NSAttributedString(string: "Upload Image", attributes: [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue, NSAttributedString.Key.underlineColor: UIColor.flatMintColorDark()]), for: .normal)
uploadImageButton.setTitleColor(UIColor.blue, for: .normal)
uploadImageButton.contentHorizontalAlignment = .left
uploadImageButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
// uploadImageButton.addTarget(self, action: #selector(uploadImageButtonTapped), for: .touchUpInside)
} else {
uploadImageButton.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += uploadImageButton.frame.height + 15
scrollView.addSubview(uploadImageButton)
}
}
func setUploadCompleteButton(isSettingAttributes: Bool) {
if isSettingAttributes {
uploadCompleteButton.setTitle("Upload", for: .normal)
uploadCompleteButton.setTitleColor(UIColor.white, for: .normal)
uploadCompleteButton.backgroundColor = UIColor.flatMint()
uploadCompleteButton.titleLabel?.font = UIFont.systemFont(ofSize: 25)
uploadCompleteButton.addTarget(self, action: #selector(uploadCompleteButtonTapped), for: .touchUpInside)
} else {
uploadCompleteButton.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += uploadCompleteButton.frame.height
scrollView.addSubview(uploadCompleteButton)
}
}
@objc func eventDateChanged(datePicker: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
eventDateTextField.text = dateFormatter.string(from: datePicker.date)
selectedEventDate = datePicker.date
}
@objc func eventTimeChanged(datePicker: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
eventTimeTextField.text = dateFormatter.string(from: datePicker.date)
selectedEventTime = datePicker.date
}
@objc func endEdit() {
// if (eventDateTextField.isEditing || eventTimeTextField.isEditing || eventAddressTextField.isEditing || eventTitleTextField.isEditing || eventTypeTextField.isEditing) {
// view.endEditing(true)
// }
view.endEditing(true)
}
@objc func uploadCompleteButtonTapped() {
if (eventTitleTextField.text == "" || eventDescriptionTextField.text == "" || eventDateTextField.text == "" || eventTimeTextField.text == "" || eventAddressTextField.text == "" || eventTypeTextField.text == "") {
let alt = UIAlertController(title: "", message: "Fill in all the blank before uploading", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
}))
self.present(alt, animated: true, completion: nil)
} else {
eventTitle = eventTitleTextField.text
eventDescription = eventDescriptionTextField.text
eventAddress = eventAddressTextField.text
eventType = eventTypeTextField.text
dict["Address"] = eventAddress
dict["Description"] = eventDescription
dict["EventName"] = eventTitle
dict["EventType"] = eventType
dict["Host"] = currentUser
dict["Liked"] = 1000
dict["Time"] = selectedEventDate
dict["Index"] = eventCounter
// TODO: Upload this event to firebase
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .event, toDocument: "Event" + String(eventCounter!), withDictionary: dict)
Events[eventCounter!] = dict
eventCounter! += 1
let alt = UIAlertController(title: "", message: "Upload Successful!", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
self.performSegue(withIdentifier: "EventUploadCompleteSegue", sender: self)
}))
self.present(alt, animated: true, completion: nil)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep># ios-final-project<file_sep>//
// ViewController.swift
// Final project
//
// Created by 徐乾智 on 4/8/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class EventViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Variables
// MARK: - Outlets
@IBOutlet weak var eventTable: UITableView!
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
eventTable.dataSource = self
eventTable.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "eventTableViewCell") as? EventTableViewCell {
cell.eventImage.image = UIImage(named: "event")!
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 350
}
// MARK: - Functions
@IBAction func eventTitleTapped(_ sender: UIButton) {
print("yes")
//performSegue(withIdentifier: "toShowEventDetail", sender: self)
}
}
class EventTableViewCell: UITableViewCell {
@IBOutlet weak var eventDescriptionField: UITextView!
@IBOutlet weak var eventImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// LikedRecipeDetailViewController.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import WebKit
class LikedRecipeDetailViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
// Set food image view
setFoodImageView(isSettingAttributes: true)
setFoodTypeLabel(isSettingAttributes: true)
// Set food title
setFoodTitleLabel(isSettingAttributes: true)
setFoodTimeLabel(isSettingAttributes: true)
setShortDescriptionTextView(isSettingAttributes: true)
setLikeButton(isSettingAttributes: true)
// Set video view
// Set ingredient text view
setIngredientLabel(isSettingAttributes: true)
setIngredientTextView(isSettingAttributes: true)
setProcedureLabel(isSettingAttributes: true)
// Set procedure text view
setProcedureTextView(isSettingAttributes: true)
}
}
// MARK: - Variables
var recipeName: String?
var recipeAuthor: String?
var recipeCategory: String?
var recipeCookTime: String?
var recipeServingNum: Int?
var recipeDescription: String?
var recipeIndex: Int?
var recipeIngredient: String?
var recipeProcedure: String?
var foodImageView = UIImageView()
var foodTypeLabel = UILabel()
var foodTitle = UILabel()
var foodTimeLabel = UILabel()
var videoView = WKWebView()
var shortDescriptionTextView = UITextView()
var likeButton = UIButton()
var ingredientLabel = UILabel()
var ingredientDescriptionTextView = UITextView()
var procedureLabel = UILabel()
var procedureDescriptionTextView = UITextView()
var spacer: CGFloat = 10
var currentHeightScrollable: CGFloat = 0
let screenHeightCorrection: CGFloat = 110
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
setFoodImageView(isSettingAttributes: false)
setFoodTypeLabel(isSettingAttributes: false)
setFoodTitleLabel(isSettingAttributes: false)
setFoodTimeLabel(isSettingAttributes: false)
setShortDescriptionTextView(isSettingAttributes: false)
setLikeButton(isSettingAttributes: false)
setIngredientLabel(isSettingAttributes: false)
setIngredientTextView(isSettingAttributes: false)
setProcedureLabel(isSettingAttributes: false)
setProcedureTextView(isSettingAttributes: false)
scrollView.contentSize = CGSize(width: view.frame.width, height: currentHeightScrollable)
}
// MARK: - Functions
func generateLongText(str: String) -> String {
var toReturn = ""
for _ in 0...50 {
toReturn.append(str)
}
return toReturn
}
func setFoodImageView(isSettingAttributes: Bool) {
if isSettingAttributes {
foodImageView.image = UIImage(named: "duck-breast")
} else {
foodImageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - screenHeightCorrection - 120)
currentHeightScrollable += foodImageView.frame.height
scrollView.addSubview(foodImageView)
}
}
func setFoodTypeLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
foodTypeLabel.text = recipeCategory!
foodTypeLabel.textAlignment = .left
foodTypeLabel.backgroundColor = UIColor.flatMintColorDark()
foodTypeLabel.textColor = .black
foodTypeLabel.font = UIFont.systemFont(ofSize: 15)
} else {
foodTypeLabel.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += foodTypeLabel.frame.height
scrollView.addSubview(foodTypeLabel)
}
}
func setFoodTitleLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
foodTitle.text = recipeName!
foodTitle.textAlignment = .left
foodTitle.backgroundColor = UIColor.flatMintColorDark()
foodTitle.textColor = .black
foodTitle.font = UIFont.systemFont(ofSize: 30)
foodTitle.numberOfLines = 3
foodTitle.lineBreakMode = .byTruncatingTail
} else {
foodTitle.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += foodTitle.frame.height
scrollView.addSubview(foodTitle)
}
}
func setFoodTimeLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
foodTimeLabel.text = recipeCookTime! + ", Serves " + String(recipeServingNum!)
foodTimeLabel.textAlignment = .left
foodTimeLabel.backgroundColor = UIColor.flatMintColorDark()
foodTimeLabel.textColor = .black
foodTimeLabel.font = UIFont.systemFont(ofSize: 15)
} else {
foodTimeLabel.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: 40)
currentHeightScrollable += foodTimeLabel.frame.height
scrollView.addSubview(foodTimeLabel)
}
}
func setVideoView(isSettingAttributes: Bool) {
if isSettingAttributes {
} else {
}
}
func setShortDescriptionTextView(isSettingAttributes: Bool) {
if isSettingAttributes {
shortDescriptionTextView.backgroundColor = .lightGray
shortDescriptionTextView.textAlignment = .left
shortDescriptionTextView.textColor = .black
shortDescriptionTextView.font = UIFont.systemFont(ofSize: 20)
shortDescriptionTextView.text = recipeDescription!
shortDescriptionTextView.isEditable = false
shortDescriptionTextView.isScrollEnabled = true
shortDescriptionTextView.isUserInteractionEnabled = false
} else {
shortDescriptionTextView.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: generateHeightWithStringLenghth(text: recipeDescription!))
currentHeightScrollable += shortDescriptionTextView.frame.height + 20
scrollView.addSubview(shortDescriptionTextView)
}
}
func setLikeButton(isSettingAttributes: Bool) {
if isSettingAttributes {
likeButton.setTitle("Like this recipe", for: .normal)
likeButton.setTitleColor(UIColor.black, for: .normal)
likeButton.backgroundColor = UIColor.flatMintColorDark()
likeButton.addTarget(self, action: #selector(likeButtonTapped), for: .touchUpInside)
} else {
likeButton.frame = CGRect(x: 10, y: currentHeightScrollable, width: view.frame.width - 20, height: 50)
currentHeightScrollable += likeButton.frame.height + 30
scrollView.addSubview(likeButton)
}
}
func setIngredientLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
let txt = NSAttributedString(string: " Ingredient", attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue, NSAttributedString.Key.underlineColor: UIColor.flatMintColorDark()])
ingredientLabel.attributedText = txt
ingredientLabel.textAlignment = .left
ingredientLabel.textColor = .black
ingredientLabel.font = UIFont.systemFont(ofSize: 30)
} else {
ingredientLabel.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: 100)
currentHeightScrollable += ingredientLabel.frame.height
scrollView.addSubview(ingredientLabel)
}
}
func setIngredientTextView(isSettingAttributes: Bool) {
if isSettingAttributes {
ingredientDescriptionTextView.backgroundColor = .white
ingredientDescriptionTextView.textAlignment = .left
ingredientDescriptionTextView.textColor = .black
ingredientDescriptionTextView.font = UIFont.systemFont(ofSize: 20)
ingredientDescriptionTextView.text = recipeIngredient!
ingredientDescriptionTextView.isEditable = false
ingredientDescriptionTextView.isScrollEnabled = true
ingredientDescriptionTextView.isUserInteractionEnabled = false
} else {
ingredientDescriptionTextView.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: generateHeightWithStringLenghth(text: recipeIngredient!))
currentHeightScrollable += ingredientDescriptionTextView.frame.height
scrollView.addSubview(ingredientDescriptionTextView)
}
}
func setProcedureLabel(isSettingAttributes: Bool) {
if isSettingAttributes {
let txt = NSAttributedString(string: " Procedure", attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.thick.rawValue, NSAttributedString.Key.underlineColor: UIColor.flatMintColorDark()])
procedureLabel.attributedText = txt
procedureLabel.textAlignment = .left
procedureLabel.textColor = .black
procedureLabel.font = UIFont.systemFont(ofSize: 30)
} else {
procedureLabel.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: 100)
currentHeightScrollable += procedureLabel.frame.height
scrollView.addSubview(procedureLabel)
}
}
func setProcedureTextView(isSettingAttributes: Bool) {
if isSettingAttributes {
procedureDescriptionTextView.backgroundColor = .white
procedureDescriptionTextView.textAlignment = .left
procedureDescriptionTextView.textColor = .black
procedureDescriptionTextView.font = UIFont.systemFont(ofSize: 20)
procedureDescriptionTextView.text = recipeProcedure!
procedureDescriptionTextView.isEditable = false
procedureDescriptionTextView.isScrollEnabled = true
procedureDescriptionTextView.isUserInteractionEnabled = false
} else {
procedureDescriptionTextView.frame = CGRect(x: 0, y: currentHeightScrollable, width: view.frame.width, height: generateHeightWithStringLenghth(text: recipeProcedure!))
currentHeightScrollable += procedureDescriptionTextView.frame.height
scrollView.addSubview(procedureDescriptionTextView)
}
}
@objc func likeButtonTapped() {
let alt = UIAlertController(title: "", message: "Recipe added to your like list!", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
}))
self.present(alt, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// DemoCell.swift
// FoldingCell
//
// Created by <NAME>. on 25/12/15.
// Copyright © 2015 <NAME>. All rights reserved.
//
import UIKit
import Firebase
class DemoCell: FoldingCell {
@IBOutlet weak var eventLikedNum: UILabel! {
didSet {
eventLikedNum.text = "2"
}
}
@IBOutlet weak var eventHostLabel: UILabel!
@IBOutlet weak var closedEventDateLabel: UILabel!
@IBOutlet weak var closedEventTimeLabel: UILabel!
@IBOutlet weak var closedEventTypeLabel: UILabel!
@IBOutlet weak var openEventTitleLabel: UILabel! { didSet { openEventTitleLabel.backgroundColor = UIColor.flatMintColorDark() } }
@IBOutlet weak var openEventDateLabel: UILabel!
@IBOutlet weak var openEventTimeLabel: UILabel!
@IBOutlet weak var openAddressLabel: UILabel!
@IBOutlet weak var openEventTypeLabel: UILabel!
var number: Int?
var currentVC: UIViewController?
override func awakeFromNib() {
foregroundView.layer.cornerRadius = 10
foregroundView.layer.masksToBounds = true
super.awakeFromNib()
}
override func animationDuration(_ itemIndex: NSInteger, type _: FoldingCell.AnimationType) -> TimeInterval {
let durations = [0.26, 0.2, 0.2]
return durations[itemIndex]
}
@IBAction func viewDetailButtonTapped(_ sender: UIButton) {
let position = eventCounter! - number! - 1
if let currVC = currentVC as? MainTableViewController {
if let event = Events[position] {
currVC.eventAddress = event["Address"] as? String
currVC.eventDescription = event["Description"] as? String
currVC.eventName = event["EventName"] as? String
currVC.eventType = event["EventType"] as? String
currVC.eventHost = event["Host"] as? String
currVC.eventLiked = event["Liked"] as? Int
currVC.eventIndex = event["Index"] as? Int
if let stamp = event["Time"] as? Timestamp {
print("reached here")
currVC.eventTime = stamp.dateValue()
}
}
currVC.performSegue(withIdentifier: "EventDetailSegue", sender: currVC)
}
}
}
// MARK: - Actions ⚡️
<file_sep>//
// ExperimentTableViewCell.swift
// Final project
//
// Created by 徐乾智 on 4/23/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class RecipeTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var currentSection: Int?
var numItemInSection: [Int] = [3, 5, 4, 2, 12, 10]
var currentVC: UIViewController?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if (indexPath.item < numItemInSection[currentSection!]) {
currentVC?.performSegue(withIdentifier: "ImageTappedSegue", sender: currentVC)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numItemInSection[currentSection!]
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// if (numItemInSection[currentSection!] >= 8) {
// if (indexPath.item == numItemInSection[currentSection!] - 1) {
// let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeEndCollectionViewCell", for: indexPath) as? RecipeEndCollectionViewCell
// cell1?.currentVC = currentVC!
// return cell1!
// } else {
// let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCollectionViewCell", for: indexPath) as? RecipeCollectionViewCell
// cell2?.recipeImage.image = UIImage(named: "duck-breast")!
// return cell2!
// }
// } else {
// let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCollectionViewCell", for: indexPath) as? RecipeCollectionViewCell
// cell?.recipeImage.image = UIImage(named: "duck-breast")!
// return cell!
// }
if (indexPath.item == numItemInSection[currentSection!] - 1) {
let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeEndCollectionViewCell", for: indexPath) as? RecipeEndCollectionViewCell
cell1?.currentVC = currentVC!
return cell1!
} else {
let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCollectionViewCell", for: indexPath) as? RecipeCollectionViewCell
cell2?.recipeImage.image = UIImage(named: "duck-breast")!
return cell2!
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// collectionView = recipeCollectionView
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBOutlet weak var recipeCollectionView: UICollectionView! {
didSet {
recipeCollectionView.delegate = self
recipeCollectionView.dataSource = self
}
}
}
<file_sep>//
// MapViewController.swift
// Final project
//
// Created by 徐乾智 on 4/8/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, CLLocationManagerDelegate, UISearchBarDelegate, MKMapViewDelegate {
@IBOutlet weak var refreshButton: UIButton! {
didSet {
refreshButton.setTitleColor(themeColor, for: .normal)
}
}
@IBOutlet weak var searchBar: UISearchBar! {
didSet {
searchBar.barTintColor = UIColor.flatMintColorDark()
searchBar.tintColor = .white
searchBar.showsCancelButton = true
}
}
@IBOutlet weak var mapView: MKMapView! {
didSet {
}
}
var locationManager = CLLocationManager()
override func viewDidLoad() {
mapView.delegate = self
searchBar.delegate = self
super.viewDidLoad()
setUp()
for eventIndex in Events.keys {
self.fetchLocationFromAddress(eventIndex: eventIndex)
}
}
override func viewDidAppear(_ animated: Bool) {
for eventIndex in Events.keys {
self.fetchLocationFromAddress(eventIndex: eventIndex)
}
}
// let initialLoc = CLLocation(latitude: 37.87, longitude: -122.26)
// let coordinateRegion = MKCoordinateRegion(center: initialLoc.coordinate, latitudinalMeters: 1500, longitudinalMeters: 1500)
// mapView.setRegion(coordinateRegion, animated: true)
//
// Do any additional setup after loading the view.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: locations.last!.coordinate.latitude, longitude: locations.last!.coordinate.longitude), latitudinalMeters: 1500, longitudinalMeters: 1500)
self.mapView.setRegion(region, animated: true)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Unable to access location")
}
@IBAction func refreshButtonTapped(_ sender: UIButton) {
for i in eventLocation.keys {
let annotation = MKPointAnnotation()
let name = Events[i]!["EventName"] as! String
let type = Events[i]!["EventType"] as! String
annotation.coordinate = (eventLocation[i]?.coordinate)!
annotation.title = name
annotation.subtitle = type
mapView.addAnnotation(annotation)
}
}
func setUp() {
mapView.showsUserLocation = true
if CLLocationManager.locationServicesEnabled() == true {
if CLLocationManager.authorizationStatus() == .restricted ||
CLLocationManager.authorizationStatus() == .denied ||
CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.startUpdatingLocation()
} else {
print("Please turn your location services on!")
}
}
func fetchLocationFromAddress(eventIndex: Int) {
let address = Events[eventIndex]!["Address"] as! String
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
eventLocation[eventIndex] = location
return
}
}
}
}
func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
locationManager.stopUpdatingLocation()
}
// func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
// if searchText == "" {
// return
// }
// for i in eventLocation.keys {
// let address = Events[i]!["Address"] as! String
// let title = Events[i]!["EventName"] as! String
// if address.lowercased().contains(searchText.lowercased()) || title.lowercased().contains(searchText.lowercased()) {
// if let coordinate = eventLocation[i]?.coordinate {
// print("reached here in did change")
// let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
// let region = MKCoordinateRegion(center: coordinate, span: span)
// self.mapView.setRegion(region, animated: true)
// }
//
// } else {
// return
// }
// }
// }
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
view.endEditing(true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if searchBar.text == "" {
return
}
for i in eventLocation.keys {
let searchText = searchBar.text!
let address = Events[i]!["Address"] as! String
let title = Events[i]!["EventName"] as! String
if address.lowercased().contains(searchText.lowercased()) || title.lowercased().contains(searchText.lowercased()) {
if let coordinate = eventLocation[i]?.coordinate {
let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
let region = MKCoordinateRegion(center: coordinate, span: span)
self.mapView.setRegion(region, animated: true)
}
return
} else {
continue
}
}
}
// func getCoordinate( eventIndex: Int,
// addressString : String,
// completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void ) {
// let geocoder = CLGeocoder()
// geocoder.geocodeAddressString(addressString) { (placemarks, error) in
// if error == nil {
// if let placemark = placemarks?[0] {
// let location = placemark.location!
// self.eventLocation![eventIndex] = location
// completionHandler(location.coordinate, nil)
// return
// }
// }
//
// completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
// }
//
// }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// RegisterAccountViewController.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class RegisterAccountViewController: UIViewController {
@IBOutlet weak var userNameTextField: UITextField! {
didSet {
userNameTextField.autocorrectionType = .no
}
}
@IBOutlet weak var passwordTextField: UITextField! {
didSet {
passwordTextField.autocorrectionType = .no
}
}
@IBOutlet weak var confirmPasswordTextField: UITextField! {
didSet {
confirmPasswordTextField.autocorrectionType = .no
}
}
@IBOutlet weak var registerButton: UIButton! {
didSet {
registerButton.backgroundColor = UIColor.flatMint()
}
}
@IBOutlet weak var quitButton: UIButton! {
didSet {
quitButton.backgroundColor = UIColor.flatMint()
}
}
@IBOutlet weak var uploadImageButton: UIButton! {
didSet {
uploadImageButton.backgroundColor = UIColor.flatMintColorDark()
}
}
override func viewWillAppear(_ animated: Bool) {
userNameTextField.text = ""
passwordTextField.text = ""
confirmPasswordTextField.text = ""
}
override func viewDidLoad() {
let endEditTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(endEdit))
view.addGestureRecognizer(endEditTapGestureRecognizer)
super.viewDidLoad()
view.backgroundColor = UIColor.flatMintColorDark()
// Do any additional setup after loading the view.
}
@IBAction func registerButtonTapped(_ sender: UIButton) {
if userNameTextField.text == "" {
let alt = UIAlertController(title: "", message: "Please type in your user name", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
return
} else if userToIndex.keys.contains(userNameTextField.text!) {
let alt = UIAlertController(title: "", message: "This user name has been used", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
return
} else if passwordTextField.text == "" || confirmPasswordTextField.text == "" {
let alt = UIAlertController(title: "", message: "Type in your password and confirm your password", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
return
} else if passwordTextField.text! != confirmPasswordTextField.text! {
let alt = UIAlertController(title: "", message: "Passwords typed does not match", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
return
} else {
let dict: Dictionary<String, Any> = ["UserName": userNameTextField.text,
"Password" : <PASSWORD>,
"LikedEvent" : "None",
"LikedRecipe" : "None",
"Index": userCounter]
Users[userCounter!] = dict
userToIndex[userNameTextField.text!] = userCounter
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .user, toDocument: "User" + String(userCounter!), withDictionary: dict)
userCounter! += 1
let alt = UIAlertController(title: "", message: "Register successful!", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
self.performSegue(withIdentifier: "UnwindToLoginFromRegister", sender: self)
}))
self.present(alt, animated: true, completion: nil)
}
}
@IBAction func quitButtonTapped(_ sender: UIButton) {
let alt = UIAlertController(title: "", message: "Quit register?", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {
(_)in
self.performSegue(withIdentifier: "UnwindToLoginFromRegister", sender: self)
}))
alt.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
}
@objc func endEdit() {
if (userNameTextField.isEditing || passwordTextField.isEditing || confirmPasswordTextField.isEditing) {
view.endEditing(true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// LikedEventTableViewCell.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class LikedEventTableViewCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var eventImageView: UIImageView!
@IBOutlet weak var eventTitleLabel: UILabel!
@IBOutlet weak var eventTimeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
setEventImageView()
setEventTitleLabel()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setEventImageView() {
eventImageView.image = UIImage(named: "event")
}
func setEventTitleLabel() {
eventTitleLabel.text = "Event Title"
eventTitleLabel.textAlignment = .left
eventTitleLabel.textColor = .black
eventTitleLabel.font = UIFont.systemFont(ofSize: 25)
}
func setEventTimeLabel() {
eventTimeLabel.text = "Event Time"
eventTimeLabel.textAlignment = .left
eventTimeLabel.textColor = .black
eventTimeLabel.font = UIFont.systemFont(ofSize: 15)
}
}
<file_sep>//
// EventDetailViewController.swift
// Final project
//
// Created by 徐乾智 on 4/8/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class EventDetailViewController: UIViewController {
var eventName: String = ""
@IBOutlet weak var eventTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
eventTitle.text = eventName
// Do any additional setup after loading the view.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// LikedEventTableViewController.swift
// Final project
//
// Created by 徐乾智 on 5/2/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class LikedEventTableViewController: UITableViewController {
var eventAtRow: [Int] = Array(repeating: 0, count: eventCounter!)
var eventIndex: Int?
var eventAddress: String?
var eventDescription: String?
var eventName: String?
var eventType: String?
var eventHost: String?
var eventLiked: Int?
var eventTime: Date?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let index: Int = userToIndex[currentUser!]!
if let events = Users[index]!["LikedEvent"] as? [Int] {
return events.count
}
return 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LikedEventTableViewCell", for: indexPath) as? LikedEventTableViewCell
let userIndex: Int = userToIndex[currentUser!]!
if let events = Users[userIndex]!["LikedEvent"] as? [Int] {
let position = events.count - indexPath.row - 1
cell?.eventImageView.image = UIImage(named: "event")
let eventIndex = events[position]
print(indexPath.row)
print(eventAtRow)
eventAtRow[indexPath.row] = eventIndex
cell?.eventTitleLabel.text = Events[eventIndex]!["EventName"] as! String
let temp = Events[eventIndex]!["Time"] as! Timestamp
let eventDate = temp.dateValue()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
dateFormatter.timeZone = NSTimeZone.local
cell?.eventTimeLabel.text = dateFormatter.string(from: eventDate)
}
return cell!
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let eventIndex = eventAtRow[indexPath.row]
if let event = Events[eventIndex] {
print(event)
eventAddress = event["Address"] as? String
eventDescription = event["Description"] as? String
eventName = event["EventName"] as? String
eventType = event["EventType"] as? String
eventHost = event["Host"] as? String
eventLiked = event["Liked"] as? Int
self.eventIndex = eventIndex as? Int
if let stamp = event["Time"] as? Timestamp {
eventTime = stamp.dateValue()
}
}
performSegue(withIdentifier: "ShowEvenDetailFromLiked", sender: self)
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? LikedEventDetailViewController {
dest.eventAddress = eventAddress
dest.eventName = eventName
dest.eventDescription = eventDescription
dest.eventType = eventType
dest.eventHost = eventHost
dest.eventLiked = eventLiked
dest.eventTime = eventTime
dest.eventIndex = eventIndex
}
}
}
<file_sep>//
// User.swift
// Final project
//
// Created by <NAME> on 4/22/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import Foundation
import Firebase
import CoreLocation
/* Structure to store user info and associated event info.*/
var themeColor: UIColor = UIColor.flatMintColorDark()
// MARK: - User data
var currentUser: String?
var userCounter: Int? {
didSet {
let dict = ["EventCount": eventCounter,
"RecipeCount": recipeCounter,
"UserCount": userCounter]
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .count, toDocument: "TotalCount", withDictionary: dict)
}
}
var userToIndex: Dictionary<String, Int> = [:]
var userIsLoggedIn = false
var Users: [Int: Dictionary<String, Any>] = [:]
// MARK: - Event data
public var eventLocation: Dictionary<Int, CLLocation> = [:]
var Events: [Int: Dictionary<String, Any>] = [:]
var tappedCellNum = -1
var eventCounter: Int? {
didSet {
let dict = ["EventCount": eventCounter,
"RecipeCount": recipeCounter,
"UserCount": userCounter]
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .count, toDocument: "TotalCount", withDictionary: dict)
}
}
// MARK: - Recipe Data
var Recipes: [Int: Dictionary<String, Any>] = [:]
var recipeCounter: Int? {
didSet {
let dict = ["EventCount": eventCounter,
"RecipeCount": recipeCounter,
"UserCount": userCounter]
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .count, toDocument: "TotalCount", withDictionary: dict)
}
}
// MARK: - Functions
public enum FirebaseCollection: String {
case user = "Users"
case event = "Events"
case recipe = "Recipes"
case count = "Count"
}
public func writeToFirebase(db: Firestore, toCollection collec: FirebaseCollection, toDocument doc: String, withDictionary dict: Dictionary<String, Any>) {
// let db = Firestore.firestore()
db.collection(collec.rawValue).document(doc).setData(dict) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
}
}
}
public func readFromFirebase(db: Firestore, fromCollection collec: FirebaseCollection, fromDocument doc: String) {
// let db = Firestore.firestore()
let docRef = db.collection(collec.rawValue).document(doc)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
if let dict = document.data() {
switch collec {
case .event:
let index = Int(String(doc.last!))
Events[index!] = dict
case .user:
let index = Int(String(doc.last!))
Users[index!] = dict
let user = dict["UserName"] as! String
userToIndex[user] = index
case .recipe:
let index = Int(String(doc.last!))
Recipes[index!] = dict
case .count:
eventCounter = dict["EventCount"] as! Int
recipeCounter = dict["RecipeCount"] as! Int
userCounter = dict["UserCount"] as! Int
}
}
} else {
print("Document does not exist")
}
}
}
public func generateHeightWithStringLenghth(text: String) -> CGFloat{
var counter: Int = 0
for char in text {
if char == "\n" {
counter += 1
}
}
print("the counter is " + String(counter))
return CGFloat(30 * counter + 50 * (text.count / 40 + 1))
}
<file_sep>//
// RecipeEndCollectionViewCell.swift
// Final project
//
// Created by 徐乾智 on 4/30/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class RecipeEndCollectionViewCell: UICollectionViewCell {
var currentVC: UIViewController?
@IBOutlet weak var viewAllButton: UIButton! {
didSet {
viewAllButton.setTitle("View All", for: .normal)
}
}
@IBAction func viewAllButtonTapped(_ sender: UIButton) {
currentVC?.performSegue(withIdentifier: "ViewAllSegue", sender: currentVC)
}
}
<file_sep>//
// ExperimentViewController.swift
// Final project
//
// Created by 徐乾智 on 4/23/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class RecipeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Outlets
@IBOutlet weak var recipeTableView: UITableView! {
didSet {
recipeTableView.delegate = self
recipeTableView.dataSource = self
}
}
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
setUp()
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 170
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RecipeTableViewCell", for: indexPath) as? RecipeTableViewCell
cell!.currentVC = self
cell!.currentSection = indexPath.section
return cell!
}
func numberOfSections(in tableView: UITableView) -> Int {
return 6
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "All"
case 1:
return "Protein"
case 2:
return "Seafood"
case 3:
return "Vegetarian"
case 4:
return "Breakfast"
case 5:
return "Dessert and Drink"
default:
return ""
}
}
// MARK: - Variables
// MARK: - Functions
func setUp() {
if #available(iOS 10.0, *) {
recipeTableView.refreshControl = UIRefreshControl()
recipeTableView.refreshControl?.addTarget(self, action: #selector(refreshHandler), for: .valueChanged)
}
}
@objc func refreshHandler() {
let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { [weak self] in
if #available(iOS 10.0, *) {
self?.recipeTableView.refreshControl?.endRefreshing()
}
self?.recipeTableView.reloadData()
})
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ViewAllSegue") {
}
}
}
<file_sep>//
// MainTableViewController.swift
//
// Copyright (c) 21/12/15. Ramotion Inc. (http://ramotion.com)
//
// 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.
import UIKit
import Firebase
import CoreLocation
class MainTableViewController: UITableViewController {
// Event information stored here
var eventAddress: String?
var eventDescription: String?
var eventName: String?
var eventType: String?
var eventHost: String?
var eventLiked: Int?
var eventTime: Date?
var eventIndex: Int?
enum Const {
static let closeCellHeight: CGFloat = 179
static let openCellHeight: CGFloat = 488
static let rowsCount = 5
}
var cellHeights: [CGFloat] = []
override func viewWillAppear(_ animated: Bool) {
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
let db = Firestore.firestore()
for index in 0...eventCounter! - 1 {
readFromFirebase(db: db, fromCollection: .event, fromDocument: "Event" + String(index))
}
setup()
}
func fetchLocationFromAddress(eventIndex: Int) {
let address = Events[eventIndex]!["Address"] as! String
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if error == nil {
if let placemark = placemarks?[0] {
let location = placemark.location!
eventLocation[eventIndex] = location
return
}
}
}
}
private func setup() {
cellHeights = Array(repeating: Const.closeCellHeight, count: Const.rowsCount)
tableView.estimatedRowHeight = Const.closeCellHeight
tableView.rowHeight = UITableView.automaticDimension
tableView.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "background"))
if #available(iOS 10.0, *) {
tableView.refreshControl = UIRefreshControl()
tableView.refreshControl?.addTarget(self, action: #selector(refreshHandler), for: .valueChanged)
}
}
@objc func refreshHandler() {
let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: { [weak self] in
if #available(iOS 10.0, *) {
self?.tableView.refreshControl?.endRefreshing()
}
self?.tableView.reloadData()
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? EventDetailViewController {
dest.eventAddress = eventAddress!
dest.eventName = eventName!
dest.eventDescription = eventDescription!
dest.eventType = eventType!
dest.eventHost = eventHost!
dest.eventLiked = eventLiked!
dest.eventTime = eventTime
dest.eventIndex = eventIndex!
}
// if sender is UIButton {
// if let dest = segue.destination as? EventDetailViewController {
// if let event = Events[tappedCellNum] {
// if let eventTitle = event["EventName"] as? String {
// dest.eventName = eventTitle
// }
// }
// }
// }
}
}
// MARK: - TableView
extension MainTableViewController {
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return Events.count
}
override func tableView(_: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard case let cell as DemoCell = cell else {
return
}
cell.backgroundColor = .clear
if cellHeights[indexPath.row] == Const.closeCellHeight {
cell.unfold(false, animated: false, completion: nil)
} else {
cell.unfold(true, animated: false, completion: nil)
}
cell.number = indexPath.row
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath) as! DemoCell
let position = eventCounter! - indexPath.row - 1
cell.currentVC = self
if let event = Events[position] {
if let eventName = event["EventName"] as? String {
cell.eventTitleLabel.text = eventName
cell.openEventTitleLabel.text = eventName
}
if let address = event["Address"] as? String {
cell.eventAddressLabel.text = address
cell.openAddressLabel.text = address
}
if let timestamp = event["Time"] as? Timestamp {
let date = timestamp.dateValue()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E MMM dd, yyyy"
dateFormatter.timeZone = NSTimeZone.local
cell.closedEventDateLabel.text = dateFormatter.string(from: date)
cell.openEventDateLabel.text = dateFormatter.string(from: date)
dateFormatter.dateFormat = "h:mm a"
cell.closedEventTimeLabel.text = dateFormatter.string(from: date)
cell.openEventTimeLabel.text = dateFormatter.string(from: date)
}
if let type = event["Type"] as? String {
cell.closedEventTypeLabel.text = type
cell.openEventTypeLabel.text = type
}
if let host = event["Host"] as? String {
cell.eventHostLabel.text = host
}
}
let durations: [TimeInterval] = [0.26, 0.2, 0.2]
cell.durationsForExpandedState = durations
cell.durationsForCollapsedState = durations
return cell
}
override func tableView(_: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeights[indexPath.row]
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! FoldingCell
if cell.isAnimating() {
return
}
var duration = 0.0
let cellIsCollapsed = cellHeights[indexPath.row] == Const.closeCellHeight
if cellIsCollapsed {
cellHeights[indexPath.row] = Const.openCellHeight
cell.unfold(true, animated: true, completion: nil)
duration = 0.5
} else {
cellHeights[indexPath.row] = Const.closeCellHeight
cell.unfold(false, animated: true, completion: nil)
duration = 0.8
}
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
tableView.beginUpdates()
tableView.endUpdates()
}, completion: nil)
// let position = eventCounter! - indexPath.row - 1
// if let event = Events[position] {
// eventAddress = event["Address"] as? String
// eventDescription = event["Description"] as? String
// eventName = event["EventName"] as? String
// eventType = event["Type"] as? String
// eventHost = event["Host"] as? String
// eventLiked = event["Liked"] as? Int
// if let stamp = event["Time"] as? Timestamp {
// eventTime = stamp.dateValue()
// }
// print("in did select row at")
// print(eventAddress)
// print(eventDescription)
// print(eventTime)
}
}
<file_sep>//
// EditInformationViewController.swift
// Final project
//
// Created by 徐乾智 on 5/4/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
import Firebase
class EditInformationViewController: UIViewController {
// MARK: Variables
var index: Int = userToIndex[currentUser!]!
var oldUserName: String = currentUser!
var oldPassword: String?
var likedRecipe: Any?
var likedEvent: Any?
// MARK: Outlets
@IBOutlet weak var userNameTextField: UITextField! {
didSet {
userNameTextField.text = currentUser!
}
}
@IBOutlet weak var passwordTextField: UITextField! {
didSet {
passwordTextField.text = Users[index]!["Password"] as? String
}
}
override func viewDidLoad() {
super.viewDidLoad()
let endEditTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(endEdit))
view.addGestureRecognizer(endEditTapGestureRecognizer)
view.backgroundColor = themeColor
oldPassword = Users[index]!["Password"] as? String
likedRecipe = Users[index]!["LikedRecipe"]
likedEvent = Users[index]!["LikedEvent"]
// Do any additional setup after loading the view.
}
// MARK: - Function
@IBAction func updateProfileButtonTapped(_ sender: UIButton) {
if (userNameTextField.text == "" || passwordTextField.text == "") {
let alt = UIAlertController(title: "", message: "You cannot have empty user name or password", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
} else if (userNameTextField.text == oldUserName && passwordTextField.text == oldPassword) {
self.performSegue(withIdentifier: "EditSuccessfulSegue", sender: self)
} else {
let alt = UIAlertController(title: "", message: "Are you sure you wish to update profile?", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {
(_)in
let dict: Dictionary<String, Any> = ["UserName": self.userNameTextField.text,
"Password": self.passwordTextField.text,
"LikedRecipe": self.likedRecipe,
"LikedEvent": self.likedEvent]
Users[self.index] = dict
let db = Firestore.firestore()
writeToFirebase(db: db, toCollection: .user, toDocument: "User" + String(self.index), withDictionary: dict)
self.performSegue(withIdentifier: "EditSuccessfulSegue", sender: self)
}))
alt.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
}
}
@objc func endEdit() {
if (userNameTextField.isEditing || passwordTextField.isEditing) {
view.endEditing(true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>//
// AccountViewController.swift
// Final project
//
// Created by 徐乾智 on 4/8/19.
// Copyright © 2019 徐乾智. All rights reserved.
//
import UIKit
class AccountViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var userProfileImageView: UIImageView! {
didSet {
if userIsLoggedIn {
userProfileImageView.image = UIImage(named: "user-profile")
} else {
userProfileImageView.image = UIImage(named: "account-icon")
}
}
}
@IBOutlet weak var editInformationButton: UIButton! {
didSet {
editInformationButton.addTarget(self, action: #selector(buttonTappedWithoutLogIn), for: .touchUpInside)
editInformationButton.addTarget(self, action: #selector(editInformationButtonTapped), for: .touchUpInside)
editInformationButton.setTitle(" " + "Edit Information", for: .normal)
editInformationButton.contentHorizontalAlignment = .left
editInformationButton.backgroundColor = UIColor.flatMintColorDark()
}
}
@IBOutlet weak var uploadEventButton: UIButton! {
didSet {
uploadEventButton.addTarget(self, action: #selector(buttonTappedWithoutLogIn), for: .touchUpInside)
uploadEventButton.addTarget(self, action: #selector(uploadEventButtonTapped), for: .touchUpInside)
uploadEventButton.setTitle(" " + "Upload Event", for: .normal)
uploadEventButton.contentHorizontalAlignment = .left
uploadEventButton.backgroundColor = UIColor.flatMintColorDark()
}
}
@IBOutlet weak var uploadRecipeButton: UIButton! {
didSet {
uploadRecipeButton.addTarget(self, action: #selector(buttonTappedWithoutLogIn), for: .touchUpInside)
uploadRecipeButton.addTarget(self, action: #selector(uploadRecipeButtonTapped), for: .touchUpInside)
uploadRecipeButton.setTitle(" " + "Upload Recipe", for: .normal)
uploadRecipeButton.contentHorizontalAlignment = .left
uploadRecipeButton.backgroundColor = UIColor.flatMintColorDark()
}
}
@IBOutlet weak var likedEventButton: UIButton! {
didSet {
likedEventButton.addTarget(self, action: #selector(buttonTappedWithoutLogIn), for: .touchUpInside)
likedEventButton.addTarget(self, action: #selector(likedEventButtonTapped), for: .touchUpInside)
likedEventButton.setTitle(" " + "Liked Event", for: .normal)
likedEventButton.contentHorizontalAlignment = .left
likedEventButton.backgroundColor = UIColor.flatMintColorDark()
}
}
@IBOutlet weak var likedRecipeButton: UIButton! {
didSet {
likedRecipeButton.addTarget(self, action: #selector(buttonTappedWithoutLogIn), for: .touchUpInside)
likedRecipeButton.addTarget(self, action: #selector(likedRecipeButtonTapped), for: .touchUpInside)
likedRecipeButton.setTitle(" " + "Liked Recipe", for: .normal)
likedRecipeButton.contentHorizontalAlignment = .left
likedRecipeButton.backgroundColor = UIColor.flatMintColorDark()
}
}
@IBOutlet weak var userNameButton: UIButton! {
didSet {
if userIsLoggedIn {
userNameButton.setTitle(" " + currentUser!, for: .normal)
} else {
userNameButton.setTitle(" " + "Guest", for: .normal)
}
userNameButton.setTitleColor(UIColor.black, for: .normal)
userNameButton.contentHorizontalAlignment = .left
userNameButton.backgroundColor = UIColor.white
userNameButton.titleLabel?.font = UIFont.systemFont(ofSize: 30)
}
}
@IBOutlet weak var logoutButton: UIButton! {
didSet {
if userIsLoggedIn {
logoutButton.setTitle("Log Out", for: .normal)
logoutButton.setTitleColor(UIColor.red, for: .normal)
} else {
logoutButton.setTitle("Sign In", for: .normal)
logoutButton.setTitleColor(UIColor.black, for: .normal)
}
logoutButton.contentHorizontalAlignment = .center
logoutButton.backgroundColor = UIColor.lightGray
logoutButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
}
}
@IBAction func logoutButtonTapped(_ sender: UIButton) {
if userIsLoggedIn {
let alt = UIAlertController(title: "", message: "Are you sure you want to log Out?", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {
(_)in
currentUser = nil
self.performSegue(withIdentifier: "unwindToLoginPage", sender: self)
}))
alt.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
} else {
self.performSegue(withIdentifier: "unwindToLoginPage", sender: self)
}
}
// MARK: - Init
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - Functions
@IBAction func unwindToAccount(segue: UIStoryboardSegue) {}
@objc func buttonTappedWithoutLogIn() {
if !userIsLoggedIn {
let alt = UIAlertController(title: "", message: "You need to log in first", preferredStyle: .alert)
alt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {
(_)in
alt.dismiss(animated: true, completion: nil)
}))
self.present(alt, animated: true, completion: nil)
}
}
@objc func editInformationButtonTapped() {
if userIsLoggedIn {
performSegue(withIdentifier: "EditInformationSegue", sender: self)
}
}
@objc func uploadEventButtonTapped() {
if userIsLoggedIn {
performSegue(withIdentifier: "UploadEventSegue", sender: self)
}
}
@objc func uploadRecipeButtonTapped() {
if userIsLoggedIn {
performSegue(withIdentifier: "UploadRecipeSegue", sender: self)
}
}
@objc func likedEventButtonTapped() {
if userIsLoggedIn {
performSegue(withIdentifier: "LikedEventSegue", sender: self)
}
}
@objc func likedRecipeButtonTapped() {
if userIsLoggedIn {
performSegue(withIdentifier: "LikedRecipeSegue", sender: self)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
dd4e0c66de51b2a12d4e7741dea88d06072cc040
|
[
"Swift",
"Markdown"
] | 25
|
Swift
|
Tanggy123/ios-final-project
|
2681936174da427f08d703ece16ab8a671221777
|
796f47608d68464ba85fe5fafb23d3e0e2d530ba
|
refs/heads/master
|
<file_sep>import pygame
import math
import random
# Color Constants
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
DARK_GREEN = (11, 46, 2)
BROWN = (41, 21, 2)
YELLOW = (239, 184, 16)
MAGENTA = (204, 0, 153)
LIGHT_BROWN = (153, 102, 34)
SKY_BLUE = (179, 255, 255)
OCEAN_BLUE = (26, 117, 255)
PEACH = (255, 204, 153)
COLORS = [RED, GREEN, BLUE, WHITE]
# Create Math Constant
PI = math.pi
# To convert from Degrees to Radians -> angle * (pi / 180)
# Game Constants
SIZE = (700, 500)
FPS = 60
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
# --------------------------------------------------------------------------- #
pygame.init()
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption('Pygame Lab')
FONT = pygame.font.SysFont('Calibri', 25, True, False)
clock = pygame.time.Clock()
running = True
# Setting up the classes
class Person:
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
self.y_speed = 0
def draw_person_on_raft(self):
pygame.draw.line(screen, self.color, (self.x + 68, self.y + 10), (self.x + 75, self.y + 35), 2)
pygame.draw.line(screen, self.color, (self.x + 68, self.y + 10), (self.x + 61, self.y + 35), 2)
pygame.draw.line(screen, self.color, (self.x + 68, self.y + 10), (self.x + 68, self.y - 15), 2)
pygame.draw.line(screen, self.color, (self.x + 68, self.y - 10), (self.x + 50, self.y), 2)
pygame.draw.circle(screen, self.color, (self.x + 69, self.y - 23), 8, width=0)
pygame.draw.line(screen, self.color, (self.x + 68, self.y - 10), (self.x + 82, self.y - 22), 2)
pygame.draw.arc(screen, RED, [self.x + 60, self.y - 30, 16, 8], 0, PI, 50)
pygame.draw.line(screen, self.color, (self.x + 75, self.y - 30), (self.x + 82, self.y - 22), 2)
def person_move(self):
self.y += self.y_speed
if self.y + 72 >= SCREEN_HEIGHT:
self.y = SCREEN_HEIGHT - 72
elif self.y <= 250:
self.y = 250
class Raft:
def __init__(self, x, y):
self.x = x
self.y = y
self.y_speed = 0
def raft_draw(self):
pygame.draw.rect(screen, BROWN, [self.x, self.y, 100, 72])
pygame.draw.line(screen, LIGHT_BROWN, (self.x, self.y + 22), (self.x + 99, self.y + 22), 2)
pygame.draw.line(screen, LIGHT_BROWN, (self.x, self.y + 48), (self.x + 99, self.y + 48), 2)
pygame.draw.line(screen, LIGHT_BROWN, (self.x + 50, self.y + 36), (self.x + 50, self.y - 72), 5)
pygame.draw.line(screen, LIGHT_BROWN, (self.x + 28, self.y + 10), (self.x + 70, self.y - 52), 5)
pygame.draw.arc(screen, BLUE, [self.x + 24, self.y - 40, 15, 50], -PI/2, PI/2, 2)
# pygame.draw.arc(screen, BLUE, [self.x + 64, self.y - 100, 15, 50], -PI / 2, PI / 2, 2)
for num in range(0, 50):
pygame.draw.arc(screen, BLUE, [self.x + 24 + (0.8 * num), self.y - 40 - (1.2 * num), 15, 50],
-PI / 2, PI / 2, 2)
pygame.draw.line(screen, LIGHT_BROWN, (self.x + 28, self.y - 40), (self.x + 70, self.y - 100), 5)
def raft_move(self):
self.y += self.y_speed
# For a 250 top movement bound, more general version in box class
if self.y + 72 >= SCREEN_HEIGHT:
self.y = SCREEN_HEIGHT - 72
elif self.y <= 250:
self.y = 250
class Ocean:
def __init__(self, x, y):
self.x = x
self.y = y
self.flow_rate = 5
self.flow_change = 0.1
self.flow_x = x
def flow(self):
for val in range(-15, 18):
pygame.draw.ellipse(screen, OCEAN_BLUE, [self.flow_x-(40*val), self.y-5, 60, 20])
self.flow_x += self.flow_rate
self.flow_rate -= self.flow_change
if abs(self.flow_rate) >= 5:
self.flow_change = -1 * self.flow_change
def main_ocean(self):
pygame.draw.rect(screen, OCEAN_BLUE, [0, self.y, SCREEN_WIDTH, SCREEN_HEIGHT])
class Sky:
def __init__(self, x, y):
self.x = x
self.y = y
self.cloud_shift = 1.5
def cloud(self):
for value in range(0, 3):
pygame.draw.ellipse(screen, WHITE, [self.x + (320 * value), self.y, 100, 30])
pygame.draw.ellipse(screen, WHITE, [self.x + 30 + (320 * value), self.y - 15, 60, 40])
pygame.draw.ellipse(screen, WHITE, [self.x + 40 + (320 * value), self.y + 10, 80, 35])
self.x -= self.cloud_shift
if self.x <= -160:
self.x += 320
@staticmethod
def sun():
pygame.draw.circle(screen, YELLOW, (0, 0), 89)
class Box:
def __init__(self, display, x, y, width, height, color):
self.display = display
self.x = x
self.y = y
self.width = width
self.height = height
self.x_speed = random.randint(3, 5)
self.y_speed = 0
self.color = color
def draw_box(self):
pygame.draw.rect(self.display, self.color, [self.x, self.y, self.width, self.height], width=0)
def draw_triangle(self):
pygame.draw.polygon(self.display, WHITE, [(self.x + 2, self.y), (self.x + self.width, self.y + self.height),
(self.x, self.y + self.height)], 0)
def update(self):
self.y += self.y_speed
if self.y + self.height >= SCREEN_HEIGHT:
self.y = SCREEN_HEIGHT - self.height
elif self.y <= 250:
self.y = 250
def move_box(self):
if self.x < 0:
self.y = random.randrange(250, SCREEN_HEIGHT, 25)
self.x = random.randrange(700, 800, 15)
self.x_speed = random.randint(1, 3)
self.x -= self.x_speed
def reset(self):
self.y = random.randrange(250, SCREEN_HEIGHT, 25)
self.x = random.randrange(700, 800, 15)
self.y_speed = random.randint(1, 5)
def is_collided(self, other):
for x_val in range(-self.width + 5, self.width - 5):
if self.x + x_val == other.x:
for y_val in range(-self.height, 20):
if self.y - y_val == other.y:
other.reset()
return True
else:
pass
else:
pass
class Score:
def __init__(self, display):
self.display = display
def draw_score(self, value):
score_value = FONT.render(f'Fish Caught : {value}', True, BLACK)
self.display.blit(score_value, [540, 10])
def draw_timer(self):
time_text = FONT.render(f'Time taken : {int(time_count)}', True, BLACK)
self.display.blit(time_text, [540, 60])
class EndScreen:
def __init__(self, display, x, y, color):
self.display = display
self.x = x
self.y = y
self.color = color
def game_end(self):
end_text = FONT.render(f'You caught 100 fish in {int(time_count)} seconds, good job!', True, WHITE)
self.display.fill(self.color)
self.display.blit(end_text, [self.x, self.y])
person = Person(100, 300, PEACH)
raft = Raft(100, 300)
ocean = Ocean(500, 250)
sky = Sky(300, 100)
fish_caught = Score(screen)
player_width = 100
player_height = 72
player = Box(screen, raft.x, raft.y, player_width, player_height, BLACK)
enemy_width = 20
enemy_list = []
counter = 0
time_count = 0
end = EndScreen(screen, 130, 240, OCEAN_BLUE)
at_end = False
for i in range(15):
y_coord = random.randrange(250, SCREEN_HEIGHT, 15)
random_x = random.randrange(700, 900, 5)
enemy_list.append(Box(screen, random_x, y_coord, enemy_width, enemy_width, OCEAN_BLUE))
while running:
# Get all input events (Keyboard, Mouse, Joystick, etc
time_count += (1/60)
for event in pygame.event.get():
# Look for specific event
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
raft.y_speed = -2
person.y_speed = -2
player.y_speed = -2
if event.key == pygame.K_DOWN:
raft.y_speed = 2
person.y_speed = 2
player.y_speed = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
if raft.y_speed > 0:
pass
else:
raft.y_speed = 0
person.y_speed = 0
player.y_speed = 0
if event.key == pygame.K_DOWN:
if raft.y_speed < 0:
pass
else:
raft.y_speed = 0
person.y_speed = 0
player.y_speed = 0
screen.fill(SKY_BLUE)
ocean.main_ocean()
ocean.flow()
sky.sun()
sky.cloud()
player.update()
raft.raft_move()
player.draw_box()
raft.raft_draw()
person.person_move()
person.draw_person_on_raft()
for enemy in enemy_list:
enemy.draw_box()
enemy.draw_triangle()
enemy.move_box()
if player.is_collided(enemy):
counter += 1
fish_caught.draw_score(counter)
fish_caught.draw_timer()
if counter >= 100:
end.game_end()
pygame.display.flip()
at_end = True
running = False
pygame.display.flip()
clock.tick(FPS)
if at_end:
end_clock = 0
while end_clock < 10000:
end_clock += 0.0005
# Runs when main game loop ends
pygame.quit()
<file_sep>import pygame
import math
import random
# Color Constants
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
COLORS = [RED, GREEN, BLUE, WHITE]
# Create Math Constant
PI = math.pi
# To convert from Degrees to Radians -> angle * (pi / 180)
# Game Constants
DISPLAY_WIDTH = 700
DISPLAY_HEIGHT = 500
SIZE = (DISPLAY_WIDTH, DISPLAY_HEIGHT)
FPS = 60
class Box:
def __init__(self, display, x, y, width, height, color):
self.display = display
self.x = x
self.y = y
self.width = width
self.height = height
self.x_speed = 0
self.y_speed = random.randint(3, 5)
self.color = color
def draw_box(self):
pygame.draw.rect(self.display, self.color, [self.x, self.y, self.width, self.height], width=0)
def update(self):
self.x += self.x_speed
if self.x + self.width >= DISPLAY_WIDTH:
self.x = DISPLAY_WIDTH - self.width
elif self.x <= 0:
self.x = 0
self.y += self.y_speed
if self.y + self.height >= DISPLAY_HEIGHT:
self.y = DISPLAY_HEIGHT - self.height
elif self.y <= 0:
self.y = 0
def drop_box(self):
if self.y > DISPLAY_HEIGHT:
self.x = random.randrange(0, DISPLAY_WIDTH, 5)
self.y = random.randrange(-100, 0, 5)
self.y_speed = random.randint(3, 5)
self.y += self.y_speed
def reset(self):
self.x = random.randrange(0, DISPLAY_WIDTH, 5)
self.y = random.randrange(-100, 0, 5)
self.y_speed = random.randint(3, 5)
def is_collided(self, other):
counter = 0
for x_val in range(-self.width + 5, self.width - 5):
if self.x + x_val == other.x:
for y_val in range(-self.width + 5, self.width - 5):
if self.y - y_val == other.y:
counter += 1
other.reset()
else:
pass
else:
pass
if counter == 3:
return True
# --------------------------------------------------------------------------- #
pygame.init()
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption('Pygame v1')
clock = pygame.time.Clock()
running = True
# Player Creation
player_width = 30
x_loc = (DISPLAY_WIDTH - player_width)/2
y_loc = DISPLAY_HEIGHT - 2*player_width
player = Box(screen, x_loc, y_loc, player_width, player_width, BLACK)
# Enemy Creation
enemy_width = 20
enemy_list = []
for i in range(10):
x_coord = random.randrange(0, DISPLAY_WIDTH, 5)
random_y = random.randrange(-100, 0, 5)
enemy_list.append(Box(screen, x_coord, random_y, enemy_width, enemy_width, RED))
while running:
# Get all input events (Keyboard, Mouse, Joystick, etc
# pressed_lft = pygame.mouse.get_pressed()[0]
# print(pressed_lft)
pos = pygame.mouse.get_pos()
# print(pos)
player.x = pos[0] - .5*player.width
player.y = pos[1]
for event in pygame.event.get():
# Look for specific event
if event.type == pygame.QUIT:
running = False
# if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_RIGHT:
# player.x_speed = 5
# if event.key == pygame.K_LEFT:
# player.x_speed = -5
# if event.key == pygame.K_UP:
# player.y_speed = -5
# if event.key == pygame.K_DOWN:
# player.y_speed = 5
# if event.type == pygame.KEYUP:
# if event.key == pygame.K_RIGHT:
# if player.x_speed < 0:
# pass
# else:
# player.x_speed = 0
# if event.key == pygame.K_LEFT:
# if player.x_speed > 0:
# pass
# else:
# player.x_speed = 0
# if event.key == pygame.K_UP:
# if player.y_speed > 0:
# pass
# else:
# player.y_speed = 0
# if event.key == pygame.K_DOWN:
# if player.y_speed < 0:
# pass
# else:
# player.y_speed = 0
elif event.type == pygame.MOUSEBUTTONDOWN:
pass
# Game logic (Objects fired, object movement) goes here
screen.fill(WHITE)
player.draw_box()
player.update()
for enemy in enemy_list:
enemy.draw_box()
enemy.drop_box()
if player.is_collided(enemy):
running = False
pygame.display.flip()
clock.tick(FPS)
# Runs when main game loop ends
pygame.quit()
|
5dc94bd465686c774aaf2c51beb435ca148ca319
|
[
"Python"
] | 2
|
Python
|
BlackIcePenguin/MotionTesting
|
dc3ebba562fa591084f4ecae4ccddadbe6744dfe
|
abd0870d8943a3d90cb2c95bb437b43842055081
|
refs/heads/master
|
<file_sep>function alerta() {
alert("Este é um alerta!!!");
}
function pressionou() {
alert("Tecla pressionada!!!");
}
|
070bdd1a2d4db04b424ae9b20fe292acd5826eb6
|
[
"JavaScript"
] | 1
|
JavaScript
|
eudemartonatto/WebApplication1
|
df38141bde4ca693c4ea1e9a33f055097423db62
|
89e1fca5e370cdbbabff6a0961764a07617e4341
|
refs/heads/master
|
<repo_name>basecamp/sentinel<file_sep>/config.go
package main
import (
"flag"
"gopkg.in/BlueDragonX/yamlcfg.v1"
"gopkg.in/yaml.v1"
"io/ioutil"
"os"
"strings"
)
const (
DefaultConfigFile = "config.yml"
)
type StringArray []string
func (strs *StringArray) String() string {
return strings.Join(*strs, ",")
}
func (strs *StringArray) Set(value string) error {
*strs = append(*strs, value)
return nil
}
// Root config object.
type Config struct {
Etcd EtcdConfig
Watchers WatchersConfig
Logging LoggingConfig
Exec []string `yaml:"-"`
}
// SetYAML parses the YAML tree into the object.
func (cfg *Config) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsMap("config", data)
if etcdData, ok := yamlcfg.GetMapItem(data, "etcd"); ok {
cfg.Etcd.SetYAML("etcd", etcdData)
} else {
cfg.Etcd = DefaultEtcdConfig()
}
if filesData, ok := yamlcfg.GetMapItem(data, "watchers"); ok {
cfg.Watchers.SetYAML("watchers", filesData)
} else {
cfg.Watchers = DefaultWatchersConfig()
}
if loggingData, ok := yamlcfg.GetMapItem(data, "logging"); ok {
cfg.Logging.SetYAML("logging", loggingData)
} else {
cfg.Logging = DefaultLoggingConfig()
}
return true
}
// Validate the config.
func (cfg *Config) Validate() []error {
errs := []error{}
errs = append(errs, cfg.Etcd.Validate()...)
errs = append(errs, cfg.Logging.Validate()...)
for _, watcher := range cfg.Watchers {
errs = append(errs, watcher.Validate()...)
}
return errs
}
// Load the Deckhand configuration file.
func LoadConfig() (cfg Config, err error) {
var file string
var exec StringArray
flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
flags.StringVar(&file, "config", DefaultConfigFile, "YAML configuration file")
flags.Var(&exec, "exec", "Execute a watcher and exit.")
flags.Parse(os.Args[1:])
data, err := ioutil.ReadFile(file)
if err != nil {
return
}
err = yaml.Unmarshal(data, &cfg)
cfg.Exec = exec
return
}
<file_sep>/config_logging.go
package main
import (
"gopkg.in/BlueDragonX/simplelog.v1"
"gopkg.in/BlueDragonX/yamlcfg.v1"
)
const (
DefaultLoggingSyslog = false
DefaultLoggingConsole = true
DefaultLoggingLevel = simplelog.NOTICE
)
// Store log related configuration.
type LoggingConfig struct {
Syslog bool
Console bool
Level int
}
// Get default logging config.
func DefaultLoggingConfig() LoggingConfig {
return LoggingConfig{
DefaultLoggingSyslog,
DefaultLoggingConsole,
DefaultLoggingLevel,
}
}
// SetYAML parses the YAML tree into the object.
func (cfg *LoggingConfig) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsMap("logging", data)
cfg.Syslog = yamlcfg.GetBool(data, "syslog", DefaultLoggingSyslog)
cfg.Console = yamlcfg.GetBool(data, "console", DefaultLoggingConsole)
levelStr := yamlcfg.GetString(data, "level", "")
if levelStr == "" {
cfg.Level = DefaultLoggingLevel
} else {
cfg.Level = simplelog.StringToLevel(levelStr)
}
return true
}
// Validate the logging configuration.
func (cfg *LoggingConfig) Validate() []error {
return []error{}
}
<file_sep>/config_watchers.go
package main
import (
"errors"
"fmt"
"gopkg.in/BlueDragonX/simplelog.v1"
"gopkg.in/BlueDragonX/yamlcfg.v1"
)
// Watcher template configuration.
type TemplateConfig struct {
Src string
Dest string
}
// Parse the YAML tree into the object.
func (cfg *TemplateConfig) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsMap(tag, data)
cfg.Src = yamlcfg.GetString(data, "src", "")
cfg.Dest = yamlcfg.GetString(data, "dest", "")
return true
}
// Validate the file config object.
func (cfg *TemplateConfig) Validate() []error {
errs := []error{}
if cfg.Src == "" {
errs = append(errs, errors.New("invalid value for template.src"))
} else if !fileIsReadable(cfg.Src) {
errs = append(errs, errors.New("invalid value for template.src: file is not readable"))
}
if cfg.Dest == "" {
errs = append(errs, errors.New("invalid value for template.dest"))
}
return errs
}
// An array of templates.
type TemplatesConfig []TemplateConfig
// Parse the YAML tree into the object.
func (cfg *TemplatesConfig) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsArray(tag, data)
templates := []TemplateConfig{}
for n, templateData := range data.([]interface{}) {
template := TemplateConfig{}
template.SetYAML(fmt.Sprintf("templates[%d]", n), templateData)
templates = append(templates, template)
}
*cfg = templates
return true
}
// Validate the file config object.
func (cfg *TemplatesConfig) Validate() []error {
errs := []error{}
for _, template := range *cfg {
errs = append(errs, template.Validate()...)
}
return errs
}
// Watcher configuration.
type WatcherConfig struct {
Name string
Prefix string
Watch []string
Context []string
Templates TemplatesConfig
Cmd []string
Shell bool
}
// Create a watcher from this config object.
func (cfg *WatcherConfig) CreateWatcher(client *Client, logger *simplelog.Logger) *Watcher {
// create renderer
templates := []Template{}
for _, templateCfg := range cfg.Templates {
templates = append(templates, NewTemplate(templateCfg.Src, templateCfg.Dest, logger))
}
var renderer *Renderer
if len(templates) > 0 {
renderer = NewRenderer(templates, logger)
}
// create command
var command []string
if len(cfg.Cmd) > 0 {
if cfg.Shell {
command = []string{"bash", "-c", cfg.Cmd[0]}
} else {
command = cfg.Cmd
}
}
// create watcher
return NewWatcher(cfg.Name, cfg.Prefix, cfg.Watch, cfg.Context, renderer, command, client, logger)
}
// Parse the YAML tree into the object.
func (cfg *WatcherConfig) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsMap(tag, data)
cfg.Name = tag
cfg.Prefix = yamlcfg.GetString(data, "prefix", "")
cfg.Watch = yamlcfg.GetStringArray(data, "watch", []string{})
cfg.Context = yamlcfg.GetStringArray(data, "context", []string{})
if templatesData, ok := yamlcfg.GetMapItem(data, "templates"); ok {
cfg.Templates.SetYAML("templates", templatesData)
}
cfg.Shell = false
if cmdValue, ok := yamlcfg.GetMapItem(data, "command"); ok {
if _, ok := cmdValue.([]interface{}); ok {
cfg.Cmd = yamlcfg.GetStringArray(data, "command", []string{})
} else {
shellCmd := yamlcfg.GetString(data, "command", "")
if shellCmd == "" {
cfg.Cmd = []string{}
} else {
cfg.Cmd = []string{shellCmd}
cfg.Shell = true
}
}
}
return true
}
// Validate the file config object.
func (cfg *WatcherConfig) Validate() []error {
errs := []error{}
if len(cfg.Watch) == 0 {
errs = append(errs, errors.New("invalid value for watcher.watch: no keys defined"))
}
if len(cfg.Context) == 0 && len(cfg.Templates) != 0 {
errs = append(errs, errors.New("invalid value for watcher.context: templates require context keys"))
}
errs = append(errs, cfg.Templates.Validate()...)
return errs
}
// An array of watchers.
type WatchersConfig []WatcherConfig
// Return the default watchers config.
func DefaultWatchersConfig() WatchersConfig {
return WatchersConfig{}
}
// Parse the YAML tree into the object.
func (cfg *WatchersConfig) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsMap(tag, data)
watchers := []WatcherConfig{}
for watcherName, watcherData := range data.(map[interface{}]interface{}) {
yamlcfg.AssertIsString("watcher", watcherName)
watcher := WatcherConfig{}
watcher.SetYAML(watcherName.(string), watcherData)
watchers = append(watchers, watcher)
}
*cfg = watchers
return true
}
// Validate the file config object.
func (cfg *WatchersConfig) Validate() []error {
errs := []error{}
for _, watcher := range *cfg {
errs = append(errs, watcher.Validate()...)
}
return errs
}
// Create a new watch manager from the configuration.
func (cfg *WatchersConfig) CreateWatchManager(client *Client, logger *simplelog.Logger) (manager *WatchManager, err error) {
watchers := []*Watcher{}
for _, watcherCfg := range *cfg {
watchers = append(watchers, watcherCfg.CreateWatcher(client, logger))
}
return NewWatchManager(watchers, client, logger), nil
}
<file_sep>/client.go
package main
import (
"github.com/coreos/go-etcd/etcd"
"github.com/peterbourgon/mergemap"
"gopkg.in/BlueDragonX/simplelog.v1"
"strings"
)
// Make a prefix from a path. The resulting prefix will begin with a / and not end in a /.
func makePrefix(path string) string {
return "/" + strings.Trim(path, "/")
}
// Join multiple key paths into one. The resulting path will be absolute.
func joinPaths(paths ...string) string {
path := ""
for _, part := range paths {
part = strings.Trim(part, "/")
if part != "" {
path = path + "/" + part
}
}
return path
}
// Return the base key name for a key path.
func keyName(path string) string {
parts := strings.Split(path, "/")
unclean := parts[len(parts)-1]
return strings.Replace(unclean, "-", "_", -1)
}
// Return a value containing node contents.
func nodeValue(node *etcd.Node) interface{} {
if node.Dir {
mapping := make(map[string]interface{})
for _, child := range node.Nodes {
name := keyName(child.Key)
mapping[name] = nodeValue(child)
}
return mapping
} else {
return node.Value
}
}
// etcd client wrapper.
type Client struct {
client *etcd.Client
logger *simplelog.Logger
prefix string
}
// Internal client creation.
func newClient(etcdClient *etcd.Client, logger *simplelog.Logger, prefix string) *Client {
return &Client{
etcdClient,
logger,
makePrefix(prefix),
}
}
// Create a new client.
func NewClient(uris []string, prefix string, logger *simplelog.Logger) *Client {
return newClient(etcd.NewClient(uris), logger, prefix)
}
// Create a new client with TLS enabled.
func NewTLSClient(uris []string, prefix string, logger *simplelog.Logger, tlsCert string, tlsKey string, tlsCaCert string) (client *Client, err error) {
var etcdClient *etcd.Client
if etcdClient, err = etcd.NewTLSClient(uris, tlsCert, tlsKey, tlsCaCert); err == nil {
client = newClient(etcdClient, logger, prefix)
}
return
}
// Create a mapping rooted at the prefix.
func (c *Client) nodeMapping(prefix string, node *etcd.Node) map[string]interface{} {
prefix = strings.Trim(prefix, "/") + "/"
path := strings.TrimPrefix(strings.Trim(node.Key, "/"), prefix)
path = strings.Replace(path, "-", "_", -1)
parts := strings.Split(path, "/")
base := parts[len(parts)-1]
dir := parts[:len(parts)-1]
mapping := map[string]interface{}{
base: nodeValue(node),
}
for i := len(dir) - 1; i >= 0; i-- {
mapping = map[string]interface{}{
parts[i]: mapping,
}
}
return mapping
}
// Return a key as a map value.
func (c *Client) GetMap(prefix, key string, recursive bool) (map[string]interface{}, error) {
key = joinPaths(prefix, key)
if response, err := c.client.Get(key, false, recursive); err == nil {
c.logger.Debug("get key '%s': %v", key, response.Node)
return c.nodeMapping(prefix, response.Node), nil
} else {
c.logger.Debug("get key '%s': %s", key, err)
return nil, err
}
}
// Return a series of keys merged into a single value.
func (c *Client) GetMaps(prefix string, keys []string, recursive bool) (mapping map[string]interface{}, err error) {
mapping = make(map[string]interface{})
for _, key := range keys {
if nodeMapping, err := c.GetMap(prefix, key, recursive); err == nil {
mapping = mergemap.Merge(mapping, nodeMapping)
} else {
break
}
}
return
}
<file_sep>/listener.go
package main
import (
"github.com/coreos/go-etcd/etcd"
"gopkg.in/BlueDragonX/simplelog.v1"
"strings"
"time"
)
const (
WatchRetry = 5
)
// A Listener waits for etcd key changes and sends watch events to its eventss.
type Listener struct {
Key string
prefix string
client *Client
logger *simplelog.Logger
stop chan bool
join chan bool
}
// Create a new listener. The listener immediately begins monitoring etcd for changes.
func NewListener(prefix, key string, client *Client, logger *simplelog.Logger) *Listener {
return &Listener{
key,
prefix,
client,
logger,
make(chan bool),
make(chan bool),
}
}
// Start the listener. Emit the name of the key to the provided channel when it changes.
func (w *Listener) Start(events []chan string) {
key := joinPaths(w.prefix, w.Key)
w.logger.Debug("watching '%s'", key)
go func() {
Loop:
for {
join := make(chan bool)
responses := make(chan *etcd.Response)
go func() {
for {
response, open := <-responses
if !open {
break
}
w.logger.Debug("key '%s' changed", response.Node.Key)
event := strings.Trim(strings.TrimPrefix(response.Node.Key, w.prefix), "/")
for _, eventChan := range events {
eventChan <- event
}
}
join <- true
close(join)
}()
_, err := w.client.client.Watch(key, 0, true, responses, w.stop)
<-join
if err == etcd.ErrWatchStoppedByUser {
break Loop
} else {
w.logger.Error("watch on '%s' failed: %s", key, err)
w.logger.Info("retrying in %ds", WatchRetry)
select {
case <-w.stop:
break Loop
case <-time.After(WatchRetry * time.Second):
}
}
}
for _, eventChan := range events {
close(eventChan)
}
w.join <- true
}()
}
// Stop a Listener.
func (w *Listener) Stop() {
w.stop <- true
select {
case <-w.join:
case <-time.After(200 * time.Millisecond):
}
}
<file_sep>/etcd.go
package main
import (
"github.com/coreos/go-etcd/etcd"
"strings"
)
// Return the base name of a node key.
func GetKeyName(key string) string {
keyParts := strings.Split(key, "/")
return keyParts[len(keyParts)-1]
}
// Find a node with the provided key name.
func FindNode(name string, node etcd.Node) *etcd.Node {
for _, node := range node.Nodes {
if GetKeyName(node.Key) == name {
return node
}
}
return nil
}
<file_sep>/main.go
package main
import (
"fmt"
"gopkg.in/BlueDragonX/simplelog.v1"
"os"
"os/signal"
"syscall"
)
// Run the app.
func main() {
// initialize logging
var err error
var logger *simplelog.Logger
if logger, err = simplelog.NewLogger(simplelog.CONSOLE, "sentinel"); err != nil {
fmt.Println("failed to create logger:", err)
os.Exit(1)
}
// load configuration
var cfg Config
if cfg, err = LoadConfig(); err != nil {
logger.Fatal("error parsing config: %s", err)
}
if errs := cfg.Validate(); len(errs) != 0 {
logger.Error("config file is invalid:")
for _, err = range errs {
logger.Error(" %s", err)
}
logger.Fatal("could not process config file")
}
// replace the logger
loggerDest := 0
if cfg.Logging.Syslog {
loggerDest |= simplelog.SYSLOG
}
if cfg.Logging.Console {
loggerDest |= simplelog.CONSOLE
}
oldLogger := logger
if logger, err = simplelog.NewLogger(loggerDest, "sentinel"); err != nil {
oldLogger.Fatal("failed to create logger:", err)
}
logger.SetLevel(cfg.Logging.Level)
// begin startup sequence
var client *Client
client, err = cfg.Etcd.CreateClient(logger)
if err != nil {
logger.Fatal("failed to create client: %s", err)
}
oldLogger.Close()
manager, err := cfg.Watchers.CreateWatchManager(client, logger)
if err != nil {
logger.Fatal("failed to create watch manager")
}
var exec []string
if len(cfg.Exec) > 0 {
exec = cfg.Exec
} else {
exec = []string{}
for name := range manager.Watchers {
exec = append(exec, name)
}
}
// exec
logger.Notice("executing watchers")
if err = manager.Execute(exec); err != nil {
logger.Fatal("failed to execute: %s", err)
}
if len(cfg.Exec) == 0 {
// run
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
logger.Notice("starting")
manager.Start()
logger.Notice("started")
<-signals
logger.Notice("stopping")
manager.Stop()
logger.Notice("stopped")
}
}
<file_sep>/renderer.go
package main
import (
"fmt"
"gopkg.in/BlueDragonX/go-hash.v1"
"gopkg.in/BlueDragonX/simplelog.v1"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
)
type Template struct {
Src string
Dest string
logger *simplelog.Logger
}
func NewTemplate(src, dest string, logger *simplelog.Logger) Template {
return Template{src, dest, logger}
}
// Return true if one file differs from another.
func (t *Template) differs(fileA, fileB string) bool {
var err error
var hashA, hashB string
if hashA, err = hash.File(fileA); err != nil {
t.logger.Warn("unable to hash %s", fileA)
return true
}
if hashB, err = hash.File(fileB); err != nil {
t.logger.Warn("unable to hash %s", fileB)
return true
}
return hashA != hashB
}
// Render the template to a temporary and return true if the original was changed.
func (t *Template) Render(context map[string]interface{}) (changed bool, err error) {
// create the destination directory
dir := filepath.Dir(t.Dest)
if err = os.MkdirAll(dir, 0777); err != nil {
return
}
// create a temp file to write
var tmp *os.File
prefix := fmt.Sprintf(".%s-", filepath.Base(t.Dest))
if tmp, err = ioutil.TempFile(dir, prefix); err != nil {
return
}
defer func() {
tmp.Close()
if !changed || err != nil {
os.Remove(tmp.Name())
}
}()
// add functions to the templates
funcs := template.FuncMap{
"replace": strings.Replace,
}
// render the template to the temp file
var tpl *template.Template
name := filepath.Base(t.Src)
if tpl, err = template.New(name).Funcs(funcs).ParseFiles(t.Src); err != nil {
return
}
if err = tpl.Execute(tmp, context); err != nil {
return
}
tmp.Close()
// return if the old and new files are the same
changed = t.differs(t.Dest, tmp.Name())
if !changed {
return
}
// replace the old file with the new one
err = os.Rename(tmp.Name(), t.Dest)
return
}
// A renderer generates files from a collection of templates.
type Renderer struct {
templates []Template
logger *simplelog.Logger
}
func NewRenderer(templates []Template, logger *simplelog.Logger) *Renderer {
item := &Renderer{
templates,
logger,
}
return item
}
func (renderer *Renderer) Render(context map[string]interface{}) (changed bool, err error) {
var oneChanged bool
for _, template := range renderer.templates {
if oneChanged, err = template.Render(context); err != nil {
return
}
if oneChanged {
renderer.logger.Debug("template '%s' rendered to '%s'", template.Src, template.Dest)
} else {
renderer.logger.Debug("template '%s' did not change", template.Dest)
}
changed = changed || oneChanged
}
return changed, nil
}
<file_sep>/watcher.go
package main
import (
"errors"
"fmt"
"gopkg.in/BlueDragonX/simplelog.v1"
"os/exec"
"strings"
)
// A watcher renders templates and executes command when key changes are detected.
type Watcher struct {
name string
prefix string
watch []string
context []string
renderer *Renderer
command []string
client *Client
logger *simplelog.Logger
}
// Create a new watcher.
func NewWatcher(name, prefix string, watch, context []string, renderer *Renderer, command []string, client *Client, logger *simplelog.Logger) *Watcher {
if prefix == "" {
prefix = client.prefix
}
return &Watcher{
name,
prefix,
watch,
context,
renderer,
command,
client,
logger,
}
}
// Run the watcher command.
func (watcher *Watcher) runCommand() error {
if len(watcher.command) == 0 {
watcher.logger.Debug("%s has no command, skipping", watcher.name)
return nil
}
cmdName := watcher.command[0]
cmdArgs := watcher.command[1:]
command := exec.Command(cmdName, cmdArgs...)
watcher.logger.Debug("%s calling command", watcher.name)
out, err := command.CombinedOutput()
if err != nil {
watcher.logger.Error("%s cmd failed: %s", watcher.name, err)
}
outStr := string(out)
if outStr != "" {
lines := strings.Split(outStr, "\n")
for _, line := range lines {
if err == nil {
watcher.logger.Debug("%s cmd: %s", watcher.name, line)
} else {
watcher.logger.Warn("%s cmd: %s", watcher.name, line)
}
}
}
return err
}
// Return the name of the watcher.
func (watcher *Watcher) Name() string {
return watcher.name
}
// Execute the watcher as if an event was receieved.
func (watcher *Watcher) Execute() error {
context, err := watcher.client.GetMaps(watcher.prefix, watcher.context, true)
if err != nil {
watcher.logger.Error("%s failed to retrieve context: %s", watcher.Name(), err)
return err
}
watcher.logger.Debug("context: %v\n", context)
changed := true
if watcher.renderer != nil {
changed, err = watcher.renderer.Render(context)
if err != nil {
watcher.logger.Error("%s failed to render: %s", watcher.Name(), err)
return err
}
}
if changed {
err = watcher.runCommand()
if err != nil {
watcher.logger.Error("%s failed to run command: %s", watcher.Name(), err)
return err
}
watcher.logger.Info("%s executed", watcher.Name())
} else {
watcher.logger.Info("%s skipped execution", watcher.Name())
}
return nil
}
// Execute the watcher when an event is received.
func (watcher *Watcher) Run(events chan string) {
for {
_, open := <-events
if !open {
break
}
watcher.Execute()
}
}
// Manage multiple watchers.
type WatchManager struct {
Watchers map[string]*Watcher
listeners map[string]*Listener
client *Client
logger *simplelog.Logger
}
// Create a new watch manager.
func NewWatchManager(watchers []*Watcher, client *Client, logger *simplelog.Logger) *WatchManager {
manager := &WatchManager{
make(map[string]*Watcher),
make(map[string]*Listener),
client,
logger,
}
for _, watcher := range watchers {
manager.Watchers[watcher.Name()] = watcher
for _, key := range watcher.watch {
if _, have := manager.listeners[key]; !have {
manager.listeners[key] = NewListener(watcher.prefix, key, client, logger)
}
}
}
return manager
}
// Execute the named watchers.
func (manager *WatchManager) Execute(watcherNames []string) error {
watchers := []*Watcher{}
for _, name := range watcherNames {
if watcher, ok := manager.Watchers[name]; ok {
watchers = append(watchers, watcher)
} else {
return errors.New(fmt.Sprintf("invalid watcher '%s'", name))
}
}
for _, watcher := range watchers {
watcher.Execute()
}
return nil
}
// Run all watchers against their listeners.
func (manager *WatchManager) Start() {
chans := make(map[string][]chan string)
addChan := func(key, watcher string) chan string {
if _, ok := chans[key]; !ok {
chans[key] = []chan string{}
}
events := make(chan string)
chans[key] = append(chans[key], events)
return events
}
for _, watcher := range manager.Watchers {
for _, key := range watcher.watch {
if _, ok := manager.listeners[key]; ok {
events := addChan(key, watcher.Name())
go watcher.Run(events)
}
}
}
for key, keyChans := range chans {
if listener, ok := manager.listeners[key]; ok {
listener.Start(keyChans)
}
}
}
// Stop all watchers.
func (manager *WatchManager) Stop() {
for _, listener := range manager.listeners {
listener.Stop()
}
}
<file_sep>/config_etcd.go
package main
import (
"errors"
"gopkg.in/BlueDragonX/simplelog.v1"
"gopkg.in/BlueDragonX/yamlcfg.v1"
)
const (
DefaultEtcdURI = "http://172.17.42.1:4001/"
DefaultEtcdPrefix = ""
DefaultEtcdTLSKey = ""
DefaultEtcdTLSCert = ""
DefaultEtcdTLSCACert = ""
)
// Store etcd related configuration.
type EtcdConfig struct {
URIs []string
Prefix string
TLSKey string
TLSCert string
TLSCACert string
}
//Get default etcd config.
func DefaultEtcdConfig() EtcdConfig {
return EtcdConfig{
[]string{DefaultEtcdURI},
DefaultEtcdPrefix,
DefaultEtcdTLSKey,
DefaultEtcdTLSCert,
DefaultEtcdTLSCACert,
}
}
// Create a client from the config.
func (cfg *EtcdConfig) CreateClient(logger *simplelog.Logger) (client *Client, err error) {
if cfg.IsTLS() {
client, err = NewTLSClient(cfg.URIs, cfg.Prefix, logger, cfg.TLSCert, cfg.TLSKey, cfg.TLSCACert)
} else {
client = NewClient(cfg.URIs, cfg.Prefix, logger)
}
return
}
// SetYAML parses the YAML tree into the object.
func (cfg *EtcdConfig) SetYAML(tag string, data interface{}) bool {
yamlcfg.AssertIsMap("etcd", data)
cfg.URIs = yamlcfg.GetStringArray(data, "uris", []string{})
uri := yamlcfg.GetString(data, "uri", "")
if uri != "" {
cfg.URIs = append(cfg.URIs, uri)
}
if len(cfg.URIs) == 0 {
cfg.URIs = append(cfg.URIs, DefaultEtcdURI)
}
cfg.Prefix = yamlcfg.GetString(data, "prefix", DefaultEtcdPrefix)
cfg.TLSKey = yamlcfg.GetString(data, "tls-key", DefaultEtcdTLSKey)
cfg.TLSCert = yamlcfg.GetString(data, "tls-cert", DefaultEtcdTLSCert)
cfg.TLSCACert = yamlcfg.GetString(data, "tls-ca-cert", DefaultEtcdTLSCACert)
return true
}
// Validate the configuration.
func (cfg *EtcdConfig) Validate() []error {
errs := []error{}
if len(cfg.URIs) == 0 || cfg.URIs[0] == "" {
errs = append(errs, errors.New("invalid value for etcd.uris"))
}
if cfg.Prefix == "" {
errs = append(errs, errors.New("invalid value for etcd.prefix"))
}
if cfg.IsTLS() {
if !fileIsReadable(cfg.TLSKey) {
errs = append(errs, errors.New("invalid etcd.tls-key: file is not readable"))
}
if !fileIsReadable(cfg.TLSCert) {
errs = append(errs, errors.New("invalid etcd.tls-cert: file is not readable"))
}
if !fileIsReadable(cfg.TLSCACert) {
errs = append(errs, errors.New("invalid etcd.tls-ca-cert: file is not readable"))
}
}
return errs
}
// Check if TLS is enabled.
func (cfg EtcdConfig) IsTLS() bool {
return cfg.TLSKey != "" && cfg.TLSCert != "" && cfg.TLSCACert != ""
}
|
9eb83566d65385f5c246a47583f8d3e8f7c21f9d
|
[
"Go"
] | 10
|
Go
|
basecamp/sentinel
|
daa156f833c3a9f96367c24e760dc27d664ab24c
|
c54526fb0caaee016553db58cd49fa8e5bf16f1b
|
refs/heads/master
|
<repo_name>Illidan877/python<file_sep>/短信验证/README.md
验证码 存redis
判断短信验证码是否正确
正确redis删掉
<file_sep>/定时任务/README.md
1. 安装定时任务包:
```
pip install django-crontab
```
2. 设置settings.py
```
INSTALLED_APPS = (
'django_crontab',
...
)
```
3. 创建应用下的 cron.py 添加任务
4. 在django项目的**settings.py**中添加以下命令
```python
CRONJOBS = (
('*/2* * * *', '你的app名.定时函数所在的py文件名.定时函数名'),
('*/2* * * *', '你的app名.定时函数所在的py文件名.定时函数名', '>>/路径/log.log'),
)
```
5. 启动/停止
1. python3 manage.py crontab add
2. python3 manage.py crontab show
3. python3 manage.py crontab remove(删除所有)
django-crontab 封装的crontab
| f1 | f2 | f3 | f4 | f5 |
| ---- | ---- | ---- | ---- | ---- |
| 分 | 时 | 日 | 月 | 周 |
| 1~59 | 0~23 | 1~31 | 1~12 | 0~6 |
用法:
1. *表示每分钟都要执行;
2. */n表示每n分钟执行一次;
3. [a-b]表示从第a分钟到第b分钟这段时间要执行;
4. a,b,c,...表示第a,b,c分钟要执行
<file_sep>/python/io/socket.md
# OSI模型
<table border="1"> <tr> <td>OSI七层网络模型</td> <td>TCP/IP四层概念模型</td> <td>对应协议</td> <td>作用</td> </tr> <tr> <td>应用层</td> <td rowspan="3">应用层</td> <td>FTP文件传输 NFS共享目录 http</td> <td>提供用户服务,具体功能有应用程序实现</td> </tr> <tr> <td>表示层</td> <td>Telnet远程访问</td> <td>数据的压缩优化加密</td> </tr> <tr> <td>会话层</td> <td>DSN分布式 SMTP电子邮件传输</td> <td>建立用户级的连接,选择适当的传输服务</td> </tr> <tr> <td>传输层</td> <td>传输层</td> <td>TCP UDP</td> <td> 提供传输服务</td> </tr> <tr> <td>网络层</td> <td>网络层</td> <td>IP ARP地址解析</td> <td> 路由选择,网络互联</td> </tr> <tr> <td>数据链路层</td> <td rowspan="2">网络接口层</td> <td></td> <td>进行数据交换,控制具体数据的发送</td> </tr> <tr> <td>物理层</td> <td></td> <td>提供数据传输的硬件保证,网卡接口,传输介质</td> </tr></table>
优点:
- 建立了统一的工作流程
- 分部清晰,各司其职,每个步骤分工明确
- 低了各个模块之间的耦合度,便于开发
# 三次握手

| 握手 | 端 | 数据包 | 端 |
| - | - | - | - |
| 第一次 | 客户端 | syn=1 seq=x | 服务端 |
| 第二次 | 服务端 | syn=1 ack=x+1 seq=y | 客户端 |
| 第三次 | 客户端 | ack=y+1 seq=x+1 | 服务端 |
- seq 本身的序列号
- ack 期望对方的序列号
四次挥手
# 四次挥手

| 挥手 | 端 | 数据包 | 端 |
| - | - | - | - |
| 第一次 | A | fin=1 seq=x | B |
| 第二次 | B | ack=x+1 seq=y | A |
| 第三次 | B | FIN=1 ack=y+1 seq = w | A |
| 第四次 | A | seq=x+1 ack=w+1 | B |
# tcp服务和udp服务有什么区别
| | tcp | upd |
| -------- | ------------------------------------ | ---------------------------- |
| 连接 | 基于连接 | 无连接 |
| 可靠性 | 可靠(无丢失,无失序,无差错,无重复) | 不可靠(会丢包 , 不保证顺序 ) |
| 资源 | 首部20字节 更占资源 | 首部8字节 |
| | 面向流模式(一连串无结构的字节流) | 面向报文(数据报模式) |
| 连接数量 | 每条tcp点到点 | UDP可以多对多 |
# sock编程
todo
<file_sep>/JWT/jwt_test.py
import json, base64, time, copy, hmac
class MyJWT(object):
@staticmethod
def encode(key='', payload=None, exp=200):
# header
dict_header = {'typ': 'JWT', 'alg': 'SHA256'}
str_header = json.dumps(dict_header, separators=(',', ':'), sort_keys=True)
b64_header = MyJWT.base64_encode(str_header)
# payload
dict_payload = copy.deepcopy(payload)
dict_payload['exp'] = str(time.time() + exp)
str_payload = json.dumps(dict_payload, separators=(',', ':'), sort_keys=True)
b64_payload = MyJWT.base64_encode(str_payload)
# sign
if isinstance(key, str):
b_key = key.encode()
str_signature = b64_header + '.' + b64_payload
h_signature = hmac.new(b_key, str_signature.encode(), digestmod=dict_header['alg'])
base_signature = h_signature.hexdigest()
return b64_header + '.' + b64_payload + '.' + base_signature
@staticmethod
def base64_encode(str_1):
return base64.urlsafe_b64encode(str_1.encode()).decode().replace('=', '')
@staticmethod
def decode(key='123', token=''):
str_header, str_payload, str_signature = token.split('.')
dict_header = json.loads(MyJWT.base64_decode(str_header))
header_payload = str_header + '.' + str_payload
h_signature = hmac.new(key.encode(), header_payload.encode(), digestmod=dict_header['alg'])
base_signature = h_signature.hexdigest()
if base_signature != str_signature:
return '内容被篡改'
dict_payload = json.loads(MyJWT.base64_decode(str_payload))
if int(float(dict_payload['exp'])) < int(time.time()):
return 'token超时'
del dict_payload['exp']
return dict_payload
@staticmethod
def base64_decode(str_1):
str_1 += '=' * (4 - len(str_1) % 4)
return base64.urlsafe_b64decode(str_1.encode()).decode()
# ------------------------
@staticmethod
def b64decode(b_s):
# 补全签发时 替换掉的 等号
b_s += '=' * (4 - len(b_s) % 4)
return base64.urlsafe_b64decode(b_s)
@staticmethod
def decode(str_jwt, str_key):
# 校验token
# 1, 检查签名 【前两项bs 再做一次hmac签名,与第三部分进行比较,若两者相等,校验成功;失败 raise】
# 2,检查时间戳是否过期 [过期则raise]
# 3,return payload明文 即payload字典对象
str_header, str_payload, str_sign = str_jwt.split('.')
if isinstance(str_key, str):
b_key = str_key.encode()
hm = hmac.new(b_key, str_header.encode() + b'.' + str_payload.encode(), digestmod='SHA256')
bs_new_sign = Jwt.b64encode(hm.digest()).decode()
if bs_new_sign != str_sign:
raise ('被篡改')
# 检查payload中的时间
json_payload = Jwt.b64decode(str_payload)
# json字符串 -> python对象
payload = json.loads(json_payload)
exp = payload['exp']
if time.time() > exp:
raise ('过期')
return payload
if __name__ == '__main__':
str_key = '123qwe'
str_token = MyJWT.encode(payload={'username': 'wwn', 'age': 16}, key=str_key, exp=100)
print(str_token)
# res_payload = Jwt.decode(str_jwt=str_token, str_key=str_key)
# print(res_payload)
<file_sep>/支付宝/README.md
- [JWT(Json-Web-Token)](https://github.com/Illidan877/flight/tree/master/JWT)
- [OAuth2.0](https://github.com/Illidan877/flight/tree/master/OAuth%202.0)
- [CBV(**class base views**)](https://github.com/Illidan877/flight/tree/master/CBV)
- [CORS(**class base views**)](https://github.com/Illidan877/flight/tree/master/CORS)
<file_sep>/短信验证/YTXSDK/test_api.py
from CCPRestSDK import REST
import configparser
# 主账号
accountSid = xxxxx
# 主账号Token
accountToken = xxxxx
# 应用Id
appId = xxxx
# 请求地址,格式如下,不需要http://
serverIP = 'app.cloopen.com'
# 端口
serverPort = '8883'
# REST版本号
softVersion = '2013-12-26'
# 流程
# 荣联云
# 注册
# 创建应用
# ACCOUNT SID
# appid
# AUTH TOKEN
# 参数
# 发送短信
# @param to 手机号
# @param datas 数据内容 格式为数组如{'12','34'} 不需要用''替换
# @param $tempId 模板Id
def send_template_SMS(to, datas, tempId):
# 初始化REST SDK
rest = REST(serverIP, serverPort, softVersion)
rest.setAccount(accountSid, accountToken)
rest.setAppId(appId)
return rest.sendTemplateSMS(to, datas, tempId)
if __name__ == '__main__':
# 手机号 {验证码 3分钟内有效}
send_template_SMS(17316184506, {"1234", 3}, 1)
<file_sep>/OAuth 2.0/README.md
## OAuth2.0
### 定义
- OAuth 的核心就是向第三方应用颁发令牌
- OAuth 引入了一个授权层,用来分离两种不同的角色:客户端和资源所有者。......资源所有者同意以后,资源服务器可以向客户端颁发令牌。客户端通过令牌,去请求数据。
### 四种获得令牌的流程
- 授权码(authorization-code)(常用)
- 隐藏式(implicit)
- 密码式(password)
- 客户端凭证(client credentials)
### 开发者平台注册
备案 以微博为例
1. 微链接 -->移动应用 -- > 立即接入 -- >应用分类 -> 选择网页应用
2. 应用信息
1. 基本信息 存 App Key ,App Secret
2. 高级信息 配置授权回调页面
### 授权(授权码模式)
1. 前端点击授权按钮发起请求
2. 拼接授权url 返回给前端, 前端跳转至授权界面.
```python
params = {
"response_type": 'code', #授权模式
'client_id': settings.WEIBO_CLIEND_ID, # App Key
'redirect_uri': settings.WEIBO_REDIRECT_URL, #回调路由
'scope': '', #获取权限 默认全开
}
url = "https://api.weibo.com/oauth2/authorize?" + urlencode(params)
```
3. 如果用户同意授权
1. 第三方平台会跳转至 备案2.2中配置的回调页面url
2. url中会拼接code授权码
3. 前端将code发给后台
4. 后台向第三方平法发post请求,用code换token
1. token返回内容
```python
{
'access_token': '<KEY>', #周旋了半天拿的就是它
'remind_in': '157679999',
'expires_in': 157679999, # 有效期
'uid': '5865720694', # 第三方中的用户id 即微博用户id 微信用户id
'isRealName': 'true'
}
```
```python
#发送请求 获取token
def get_access_token(code):
import requests
token_url = 'https://api.weibo.com/oauth2/access_token'
post_data = {
'client_id': settings.WEIBO_CLIEND_ID, # App Key
'client_secret': settings.WEIBO_CLIENT_SECRET, # App Secret
'grant_type': 'authorization_code', #授权类型 授权码模式
'redirect_uri': settings.WEIBO_REDIRECT_URL, # 回调url
'code': code # 授权码
}
try:
res = requests.post(token_url, data=post_data)
except Exception as e:
raise
if res.status_code == 200: # 如果为200 返回token
return json.loads(res.text)
raise
```
5. 得到token之后,等待用户绑定信息
- 查这个第三方(微博)之前是否登录过
- 没登录 立刻存表 等待用户注册 绑定账号 (不能发给前端 以免被截获)
- 登录过 查是否绑定
- 绑定了 直接登录签发token
- 没绑定 重定向到注册
- 创建用户 绑定第三方id (注意事务 绑定失败重新注册)
### 隐藏式(implicit)
```python
#todo
```
### 密码式(password)
```python
#todo
```
### 客户端凭证(client credentials)
```python
#todo
```<file_sep>/JWT/README.md
### 版本
- python-3.6.8
- pyjwt-1.7.1
- json base64 time copyhmac python3自带库
## base64(二进制可视化)HASH(加密)
### **base64**
**功能**: 二进制可视化.
原理:
1. 将字符串拆成每三个字符一组
2. 计算每一个字符对应的ASCII码二进制
3. 将8位的二进制码,按照每6位一组重新分组(不足6位的在后面补0)
4. 计算对应的十进制编码
5. 按照base64表,查看对应的字符(不足4位的在后面补=)
方法:
- b64encode()/b64decode()
- urlsafe_b64encode()/urlsafe_b64decode() # 功能同上 *进行url的字符串编码* +'替换成 '-',将'/'替换成'_'
### SHA-256
功能: 安全**散列**算法的一种(hash)
```python
s = hashlib.sha256()
s.update(b'xxxx')
s.digest()
```
- update() 在之前运算基础上累加计
#### python dict/set实现
- 根据key进行一次hash计算
- 增
- 计算数组中的位置 hash(key)=16进制定长计算出索引位置
1. 位置为空 则添加
2. hash小概率计算结果重复 则hash(key+索引)再次计算 然后重新分配(哈希碰撞)
- 删除
1. 找到当前位置 有值 伪删除
2. 找到当前位置 标记被删除过 向下探测链
- 扩容
空闲位置少于1/3进行自动扩容 重新排座位
### hmac(加盐)
功能**: 使用**散列**算法同时结合一个加密**密钥**
```python
h = hmac.new(key, str, digestmod='SHA256 ')
h.digest()
```
### RSA256 非对称加密
1. 加密: 公钥加密, 私钥解密
2. 签名: 私钥签名, 公钥验证
## JWT 组成
- header(多台服务器发送token时 解析alg得到指定加密方式)
```python
{'alg':'HS256','typ':'JWT'}
```
- payload
```python
{
'exp': xxx, # Expiration Time 此token的过期时间的时间戳
'iss': xxx,# (Issuer) Claim 指明此token的签发者
'aud': xxx, #(Audience) Claim 指明此token的
'iat': xxx, # (Issued At) Claim 指明此创建时间的时间戳
'aud': xxx, # (Audience) Claim 指明此token签发面向群体
...
'uid': 1
}
```
- signature 签名 **HS256(key , base64_header + '.' +base64_payload)**
- jwt结果 **base64(header) + '.' + base64(payload) + '.' + base64(sign)**
## JWT效验
1. 解析header, 确认alg
2. 重复JWT组成步骤3 比对signature 判断是否被篡改
3. 获取payload自定义内容
## 测试地址:
**https://jwt.io/**<file_sep>/OAuth 2.0/views.py
import base64
import hashlib, json
import random
from urllib.parse import urlencode
import redis
from django.conf import settings
from django.db import transaction
from django.http import JsonResponse
from django.views.generic.base import View
from authorization.views import make_token
from common.logging_check import logging_check
from users.models import Users, Address, WeiboUsers
from users.tasks import send_active_email
r = redis.Redis(host='127.0.0.1', port=6379, db=0, password='<PASSWORD>')
class UsersView(View):
def get(self, request):
return JsonResponse({'code': 200, 'data': 'hello'})
def post(self, request):
data = request.body
# 验证提交
if not data:
return JsonResponse({'code': 400, 'error': 'Please give me data'})
json_obj = json.loads(data.decode())
username = json_obj.get('uname')
password = json_obj.get('password')
email = json_obj.get('email')
phone = json_obj.get('phone')
# 验证表单内容
if not username and not password and not email and not phone:
return JsonResponse({'code': 400, 'error': {"message": 'Please give me data'}})
old_user = Users.objects.filter(username=username)
if old_user:
return JsonResponse({'code': 400, 'error': {"message": 'The username is existed'}})
m = hashlib.md5()
m.update(password.encode())
b64_password = m.hexdigest()
try:
Users.objects.create(username=username, password=<PASSWORD>, phone=phone, email=email)
except Exception as e:
return JsonResponse({'code': 200, 'error': {"message": '注册失败'}})
int_random = random.randint(1000, 9999)
code_str = username + "_" + str(int_random)
code_str_bs = base64.urlsafe_b64encode(code_str.encode()).decode()
r.set("email_active_%s" % (username), code_str)
active_url = 'http://127.0.0.1:7000/dadashop/templates/active.html?code=%s' % (code_str_bs)
send_active_email.delay(email, active_url)
return JsonResponse({'code': 200, "username": username, 'data': {'token': make_token(username)}})
def put(self, request):
return JsonResponse({'code': 200, 'data': 'hello'})
def delete(self, request):
return JsonResponse({'code': 200, 'data': 'hello'})
class AddressView(View):
@logging_check
def get(self, request, username, id):
all_user = Address.objects.filter(uid=request.myuser)
if not all_user:
return JsonResponse({'code': 200, 'data': {
"addresslist": [],
}})
res = []
for add in all_user:
res.append({
'id': 123456, # 地址id
'address': add.address,
'receiver': add.receiver,
'is_default': add.isDefault,
'tag': add.tag,
'receiver_mobile': add.receiver_mobile,
'postcode': add.postacode,
})
return JsonResponse({'code': 200, 'data': {
"addresslist": res,
}})
@logging_check
def post(self, request, username, id):
user = request.myuser
if username != user.username:
return JsonResponse({'code': 500, 'error': "The request is illegal"})
body = json.loads(request.body.decode())
receiver = body.get('receiver')
address = body.get('address')
receiver_phone = body.get('receiver_phone')
postcode = body.get('postcode')
tag = body.get('tag')
old_user = Address.objects.filter(uid_id=user)
if not old_user:
isdefault = True
else:
isdefault = False
Address.objects.create(
receiver=receiver,
address=address,
postacode=postcode,
receiver_mobile=receiver_phone,
tag=tag,
uid=user,
isDefault=isdefault
)
res = []
all_user = Address.objects.filter(uid=user)
for add in all_user:
res.append({
'id': 123456, # 地址id
'address': add.address,
'receiver': add.receiver,
'is_default': add.isDefault,
'tag': add.tag,
'receiver_mobile': add.receiver_mobile,
'postcode': add.postacode,
})
return JsonResponse({'code': 200, 'data': {
"addresslist": res,
}})
def put(self, request):
pass
def delete(self, request):
pass
def user_active(request):
if request.method != "GET":
return JsonResponse({'code': 400, 'error': 'Please user get !!'})
code = request.GET.get('code')
code_str = base64.urlsafe_b64decode(code.encode()).decode()
username, rcode = code_str.split('_')
old_data = r.get("email_active_%s" % (username)).decode()
if code_str != old_data:
return JsonResponse({'code': 500, 'error': 'Code is error'})
user = Users.objects.filter(username=username)[0]
user.isActive = True
user.save()
r.delete("email_active_%s" % (username))
return JsonResponse({'code': 200, 'data': '激活成功'})
class OAuthWeiboUrlView(View):
def get(self, request):
return JsonResponse({'code': 200, 'oauth_url': get_weibo_login_url()})
def get_weibo_login_url():
params = {
"response_type": 'code',
'client_id': settings.WEIBO_CLIEND_ID,
'redirect_uri': settings.WEIBO_REDIRECT_URL,
'scope': '',
}
weibo_url = "https://api.weibo.com/oauth2/authorize?"
url = weibo_url + urlencode(params)
return url
class OAuthWeiboView(View):
def get(self, request):
# 获取code
code = request.GET.get('code')
# 想微博发请求
try:
user_info = get_access_token(code)
except Exception as e:
return JsonResponse({'code': 202, 'error': {'message': "WeiBo server is busy--"}})
print(user_info)
wbuid = user_info.get('uid')
access_token = user_info.get('access_token')
try:
weibo_user = WeiboUsers.objects.get(wbuid=wbuid)
except Exception as e:
# 创建数据 暂时不绑定uid 等待用户注册
WeiboUsers.objects.create(wbuid=wbuid, access_token=access_token)
return JsonResponse({'code': 201, 'uid': wbuid})
else:
# 无报错 该用户之前用微博登录过
uid = weibo_user.uid
if uid:
token = make_token(uid.username)
# 之前绑定过 则认为当前为正常登录 照常签发token
return JsonResponse({'code': 200, 'data': {'token': token}, "username": uid.username})
else:
# 之前微博登录过 没有绑定 去注册 则认为当前去绑定微博和商城用户id
return JsonResponse({'code': 201, 'uid': wbuid})
def post(self, request):
data = request.body
# 验证提交
if not data:
return JsonResponse({'code': 400, 'error': 'Please give me data'})
json_obj = json.loads(data.decode())
username = json_obj.get('username')
password = json_obj.get('password')
email = json_obj.get('email')
phone = json_obj.get('phone')
wbid = json_obj.get('uid')
# 验证表单内容
if not username and not password and not email and not phone:
return JsonResponse({'code': 400, 'error': {"message": 'Please give me data'}})
old_user = Users.objects.filter(username=username)
if old_user:
return JsonResponse({'code': 400, 'error': {"message": 'The username is existed'}})
m = hashlib.md5()
m.update(password.encode())
b64_password = m.hexdigest()
with transaction.atomic():
Users.objects.create(username=username, password=<PASSWORD>, phone=phone, email=email)
wbuser = WeiboUsers.objects.get(wbuid=wbid)
wbuser.uid_id = Users.objects.get(username=username).id
wbuser.save()
# 邮箱激活
int_random = random.randint(1000, 9999)
code_str = username + "_" + str(int_random)
code_str_bs = base64.urlsafe_b64encode(code_str.encode()).decode()
r.set("email_active_%s" % (username), code_str)
active_url = 'http://127.0.0.1:7000/dadashop/templates/active.html?code=%s' % (code_str_bs)
send_active_email.delay(email, active_url)
return JsonResponse({'code': 200, "username": username, 'data': {'token': make_token(username)}})
def get_access_token(code):
import requests
token_url = 'https://api.weibo.com/oauth2/access_token'
post_data = {
'client_id': settings.WEIBO_CLIEND_ID,
'client_secret': settings.WEIBO_CLIENT_SECRET,
'grant_type': 'authorization_code',
'redirect_uri': settings.WEIBO_REDIRECT_URL,
'code': code
}
try:
res = requests.post(token_url, data=post_data)
except Exception as e:
raise
if res.status_code == 200:
return json.loads(res.text)
raise
<file_sep>/CORS/README.md
# CORS( CORS - Cross-origin resource sharing)
### 跨域
前端 (web,Android ,ios ) 和后端部署到不同服务器, ajax受限于同源策略(协议 域名 端口)
### 特点
1. 浏览器自动完成(在请求头中加入特殊头 或 发送特殊请求)
2. 服务器需要支持(响应头中需要有特殊头)
3. 除非验证当前用户状态,否则不需要前端支持. (我司前端小老哥干到离职都没发现是跨域)
<file_sep>/CBV/README.md
## CVB调研
### CBV和FBV的差别
- FBV : function base views, 就是在视图里使用函数处理请求
```python
def index(request):
if request.method == 'GET':
return JsonResponse({'code': 200})
```
- class-based views
````python
class HelloView(View):
def get(self, request):
return JsonResponse({'code':200})
````
### View方法的调用顺序
1. 装饰器会优先于view内函数,所以将权限判断放在装饰器中调用
2. __ init __()
- 将路由中的正则匹配内容 存入类中的kwargs字典中 ; 获取: self.kwargs[“mobile”]
3. as_view [入口]
- 装了属性view_class和view_initkwargs 和功能view()
- 把request以及参数封装传递给了Class.dispatch,然后调用Class.dispatch
- 请求的request数据获取
4. dispatch [分发]
- 它从request.method中获取请求类型(假设是GET),并进行反射,并交给我们在Class中写好的对应方法(GET)去执行.那么dispatch就相当于一个请求分发器,它在请求处理前执行
```python
def dispatch(self, request, *args, **kwargs):
# Try to dispatch to the right method; if a method doesn't exist,
# defer to the error handler. Also defer to the error handler if the
# request method isn't on the approved list.
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
```
5. http_method_not_allowed
- 前端大黄页
6. _allowed_methods
- 用列表迭代器,返回请求方法的名字
7. options
- 请求方法
<file_sep>/python/io/文件操作.md
## 文件读写
### 打开
- f = open()
- 打开文件
- 参数
- [str] 文件名
- [str] 打开方式
- [str] encodeing='utf-8'
- [int] buffering = 1 表示有行缓冲 (默认-1 走系统默认提供的缓冲机制)
- TextIOWrapper
### 读取
- f.read()
- 返回读取所有内容
- [int] 读取字节数
- 字符串
- f.readline()
- 返回读取一行内容
- [int] 读取字节数
- 字符串
- f.readlines()
- 返回所有行
- int 读取第n个字符和之前的所有行
- list
### 写入
- f.write()
- 写入文件
- [字符串/字节串] 写入内容
- int 写入字节数
### 关闭文件
- f.close()
### with操作
- with opent('file', 'r') as f:
f.read()
### 缓冲区
- f.flush()
- 该函数调用后会进行一次磁盘交互,将缓冲区中的内容写入到磁盘。
- None
- None
- 刷新缓冲区条件
- 缓冲区被写满
- 程序执行结束 或者文件对象被关闭
- 行缓冲遇到换行
- 调用f.flush()
### 文件偏移量
- f.tell()
- 获取文件偏移量大小
- None
- [int] 汉字*2
- f.seek()
- 修改偏移量
- 参数
- [int] offset 正数向前 负数向后
- [int] whence 0开头位置 1 当前位置 2结尾位置
- [int] offset
### 文件描述符
- f.fileno()
- 获取文件描述符
- None
- int
### 其他
- 获取文件大小
- os.path.getsize(file)
- 查看文件列表
- os.listdir(dir)
- 查看文件是否存在
- os.path.exists(file)
- 判断文件类型
- os.path.iffile(file)
- 删除文件
- os.remove(file)
|
e3c344dd0e19dddf4c842de0dd3f9062e5e1f826
|
[
"Markdown",
"Python"
] | 12
|
Markdown
|
Illidan877/python
|
7e00d313073e431cc9c4db58c6b2a25222aebbc6
|
a01bcfcaee6a7ee0e52c451961e22d5ed7a96583
|
refs/heads/master
|
<file_sep>package com.ycy.jsbridge.jsbridge;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class JSWebViewClient extends WebViewClient {
private JSBridge jsBridge;
JSWebViewClient(JSBridge jsBridge) {
super();
this.jsBridge = jsBridge;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO:这里可以拦截url自定义动作,比如打电话,发邮件
if (!TextUtils.isEmpty(url)) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
jsBridge.getActivity().startActivity(intent);
return true;
}
}
return false;
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//TODO:这里可以对错误进行处理,比如出错后显示错误页面
super.onReceivedError(view, request, error);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//TODO:这里可以对页面刚加载时处理,比如显示进度条
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
//TODO:这里可以对页面加载完成时处理,比如隐藏进度条
super.onPageFinished(view, url);
}
}<file_sep>package com.ycy.jsbridge.jsapi;
import com.ycy.jsbridge.jsbridge.JSBridge;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by YCY.
*/
public class JSBizDemo {
public void doBiz(JSBridge jsBridge, Long callId, JSONObject requestParams) throws JSONException {
String content = requestParams.optString("content");
JSONObject callbackParams = new JSONObject();
if ("ok".equals(content)) {
callbackParams.put("bizId", 1);
jsBridge.reportSuccess(callId, callbackParams);
} else {
callbackParams.put("bizErrorId", 11);
jsBridge.reportError(callId, callbackParams);
}
}
}
<file_sep>package com.ycy.jsbridge.jsapi;
import android.widget.Toast;
import com.ycy.jsbridge.jsbridge.JSBridge;
import org.json.JSONObject;
/**
* Created by YCY.
*/
public class JSUIControl {
public void showToast(JSBridge jsBridge, Long callId, JSONObject requestParams) {
String content = requestParams.optString("content");
Toast.makeText(jsBridge.getActivity(), content, Toast.LENGTH_LONG).show();
//回调JS
jsBridge.reportSuccess(callId);
}
}
<file_sep>## JSBridge
对js与android交互进行的封装,可自定义协议,没有js注入漏洞,安全可靠,兼容android所有系统版本
## 用法
//1.实例化JSBridge,配置WebView
JSBridge jsBridge = new JSBridge(this, webview);
jsBridge.configWebView();
//2.WebView 加载网页资源
webview.loadUrl("file:///android_asset/demo.html");
## 项目说明
1.js使用alert方式调用android接口:
var json = JSON.stringify({"content":"js call native!"});
alert("myjsbridge:///request?class=JSUIControl&method=showToast¶ms="+
encodeURIComponent(json)+"&callId=1");
2.android调用js:
//String callbackJS = "javascript:myjsbridge.callbackFromNative(1,0,{});"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//4.4及以上使用evaluateJavascript
this.mWebView.evaluateJavascript(callbackJS, null);
} else {
this.mWebView.loadUrl(callbackJS);
}
|
ff231356eda54d2091b75b9d4670a7025bb25806
|
[
"Markdown",
"Java"
] | 4
|
Java
|
snailycy/android_jsbridge
|
678b4040ec3899a41fbd784d17c0fab303ea854b
|
6f8b3859b96d710abd166e67cc462d183a282f34
|
refs/heads/main
|
<file_sep><?php
class FelInvoicePluginConfig
{
public function __construct() {
}
/**
* adds an input field for saving user authkey
*/
private function set_user_auth_keys() {
$auth_keys = array(
array("form_key"=>"fel_invoice_auth_user", "option_key"=>"fel_invoice_plugin_auth_user", "label"=>"FEL_USER", "placeholder"=>"82280363"),
array("form_key"=>"fel_invoice_auth_key", "option_key"=>"fel_invoice_plugin_auth_key", "label"=>"FEL_APIKEY", "placeholder"=>"XXjBo6QibrrpOgYtnp7nlOC"),
//array("form_key"=>"fel_invoice_app_listen", "option_key"=>"fel_invoice_plugin_app_listen", "label"=>"APP_LISTEN", "placeholder"=>"8080"),
);
foreach ($auth_keys as $auth) {
if (isset($_REQUEST[$auth['form_key']]) && get_option($auth['option_key']) != trim($_REQUEST[$auth['form_key']])) {
$value = trim($_REQUEST[$auth['form_key']]);
if (!add_option($auth['option_key'], $value)) {
update_option($auth['option_key'], $value);
}
}
$option_value = get_option($auth['option_key']);
$place_holder = isset($auth['placeholder']) ? $auth['placeholder'] : "Please enter the value you received from FelInvoice";
echo '<p class="fel-invoice-config"><label for="' . $auth['form_key'] . '">' . $auth['label'] . '</label>';
echo '<input required type="text" name="' . $auth['form_key'] . '" id="' . $auth['form_key'] .
'" class="form-control" value="' . $option_value . '" placeholder="' . $place_holder. '"></p>';
}
if (isset($_REQUEST["check_connection"]))
{
$api = new FelInvoiceConnect();
if($api->checkAuthKey()) {
echo '<p>Key authentication: Correct</p>';
} else {
echo '<p>Key authentication: Incorrect</p>';
}
}
}
/**
* generates form elements
*/
private function set_order_trigger_field() {
global $wpdb;
$order_status = wc_get_order_statuses();
$selected_value = get_option('_fel_invoice_trigerred_create_invoice');
if (isset($_REQUEST['_fel_invoice_trigerred_create_invoice']) && $selected_value != trim($_REQUEST['_fel_invoice_trigerred_create_invoice'])) {
$selected_value = trim($_REQUEST['_fel_invoice_trigerred_create_invoice']);
update_option('_fel_invoice_trigerred_create_invoice', $selected_value);
}
echo '<p class="fel-invoice-config"><label for="_fel_invoice_trigerred_create_invoice">Estado del pedido que crea una factura</label>';
echo '<select required name="_fel_invoice_trigerred_create_invoice" id="_fel_invoice_trigerred_create_invoice" class="form-control" placeholder="Select order state">';
foreach ($order_status as $key => $status) {
echo '<option value="'.$key.'"'.($selected_value == $key ? ' selected="selected"' : '').'>'.$status.'</option>';
}
echo '</select></p>';
$selected_value = get_option('_fel_invoice_trigerred_cancel_invoice');
if (isset($_REQUEST['_fel_invoice_trigerred_cancel_invoice'])) {
$selected_value = is_array($_REQUEST['_fel_invoice_trigerred_cancel_invoice']) ? $_REQUEST['_fel_invoice_trigerred_cancel_invoice'] : array($_REQUEST['_fel_invoice_trigerred_cancel_invoice']);
update_option('_fel_invoice_trigerred_cancel_invoice', $selected_value);
}
echo '<p class="fel-invoice-config"><label for="_fel_invoice_trigerred_cancel_invoice">Orden indica que cancela una factura</label>';
echo '<select required name="_fel_invoice_trigerred_cancel_invoice[]" id="_fel_invoice_trigerred_cancel_invoice" class="form-control" placeholder="Select order states" multiple="multiple">';
foreach ($order_status as $key => $status) {
echo '<option value="'.$key.'"'.(in_array($key, $selected_value) ? ' selected="selected"' : '').'>'.$status.'</option>';
}
echo '</select></p>';
}
public function buildMarkup(){
include __DIR__ . '/fel_invoice_plugin_configHTML.php';
}
}<file_sep><?php
require_once __DIR__ . '/../plugin/FelInvoiceRegisterOrder.php';
require_once __DIR__ . '/../api/FelInvoiceConnect.php';
/**
* is used for setting basic actions, e.g. adding FelInvoice to menu and in later versions this class
* might be used for upgrading to newer versions
* @author <NAME>
*
*/
class FelInvoiceInstaller {
private $supportMail = "<EMAIL>";
/**
* adds actions/filters
*/
public function registerEvents() {
add_action('admin_menu', array($this, 'addMenu'));
add_action('admin_head', array($this, 'addFelInvoiceStyle'));
}
private function unregisterWebhooksFromFelInvoice()
{
delete_option("fel_invoice_hook_token");
$connect = new FelInvoiceConnect();
//$connect->unregisterWebHooks();
}
/**
* it will be called, when the plugin is disabled
*/
public function tearDown() {
//wp_mail($this->supportMail, "Deactivate", "Plugin deactivated: ".WEMALO_BASE);
$this->clearCronJob();
//unregister status update webhook
$this->unregisterWebhooksFromFelInvoice();
delete_option("fel_invoice_plugin_auth_key");
}
/**
* deactivates checking cron job
*/
private function clearCronJob() {
wp_clear_scheduled_hook('fel_invoice_creditcode_check');
}
/**
* sets up the wemalo plugin
*/
public function setUp() {
//wp_mail($this->supportMail, "Activate", "Plugin activated ".WEMALO_BASE);
delete_option('_fel_invoice_mail_content');
//create tables
//$this->createTables();
//set up cron job
//$this->setUpCronJob();
}
/**
* sets up cronJobs
*/
public function setUpCronJob() {
if (!wp_next_scheduled('fel_invoice_creditcode_check')) {
wp_schedule_event(time(), 'hourly', 'fel_invoice_creditcode_check');
}
add_action('fel_invoice_creditcode_check', array($this, 'checkDelayedCreditCode'));
}
/**
* checks order status of partially reserved orders
*/
public function checkDelayedCreditCode() {
$pluginOrder = new FelInvoiceRegisterOrder();
global $wpdb;
$table_name = $wpdb->prefix."fel_invoice_delayed_creditcodes";
$sql = "SELECT * FROM ".$table_name." WHERE is_precessed=0;";
$results = $wpdb->get_results($sql);
foreach($results as $row) {
$aw_delayed_prod_ids = json_decode($row->aw_delayed_prod_ids, true);
$aw_delayed_prod_ids = $pluginOrder->attachFelInvoiceCreditCode($row->order_id, $aw_delayed_prod_ids);
if(empty($aw_delayed_prod_ids)) {
$sql = "UPDATE ".$table_name." SET is_precessed=1, aw_delayed_prod_ids=%s WHERE id=".$row->id.";";
$sql = $wpdb->prepare($sql, json_encode($aw_delayed_prod_ids));
$wpdb->query($sql);
} else {
$sql = "UPDATE ".$table_name." SET is_precessed=0, aw_delayed_prod_ids=%s WHERE id=".$row->id.";";
$sql = $wpdb->prepare($sql, json_encode($aw_delayed_prod_ids));
$wpdb->query($sql);
}
}
}
/**
* creates database tables
*/
public function createTables() {
//create table for return-shippment
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$charset_collate = $wpdb->get_charset_collate();
//table for storing information about returned positions
$table_name = $wpdb->prefix."fel_invoice_delayed_creditcodes";
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
order_id mediumint(9) NOT NULL DEFAULT 0,
aw_delayed_prod_ids varchar(2047) NOT NULL DEFAULT '',
is_precessed tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY id (id)
) $charset_collate;";
dbDelta($sql);
}
/**
* create admin-menue for the plugin
*/
public function addMenu() {
add_menu_page('FelInvoice API - das Wordpress-Plugin für FelInvoice', 'FelInvoice', 'manage_options', __FILE__,
'fel_invoice_plugin_user', plugin_dir_url(__FILE__).'../images/felinvoice.png');
}
/**
* adds font icons in order table etc.
*/
public function addFelInvoiceStyle() {
echo '<style>
.widefat .column-order_status mark.return-booked:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
.widefat .column-order_status mark.return-booked:after{
content:"\e014";
color:#e37622;
}
.widefat .column-order_status mark.return-announced:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
.widefat .column-order_status mark.return-announced:after{
content:"\e001";
color:#e37622;
}
.widefat .column-order_status mark.reclam-booked:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
.widefat .column-order_status mark.reclam-booked:after{
content:"\e014";
color:#e37622;
}
.widefat .column-order_status mark.reclam-announced:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
.widefat .column-order_status mark.reclam-announced:after{
content:"\e001";
color:#e37622;
}
.widefat .column-order_status mark.fel-invoice-cancel:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
.widefat .column-order_status mark.fel-invoice-cancel:after{
content:"\e013";
color:#e37622;
}
.widefat .column-order_status mark.fel-invoice-fulfill:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
}
.widefat .column-order_status mark.fel-invoice-fulfill:after{
content:"\e019";
color:#e37622;
}
.widefat .column-order_status mark.fel-invoice-block:after{
font-family:WooCommerce;
speak:none;
font-weight:400;
font-variant:normal;
text-transform:none;
line-height:1;
-webkit-font-smoothing:antialiased;
margin:0;
text-indent:0;
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
text-align:center;
opacity: 0.5;
}
.widefat .column-order_status mark.fel-invoice-block:after{
content:"\e019";
color:#e37622;
}
.fel-invoice-table {
width:100%;
max-width:800px;
margin-top: 50px;
}
.fel-invoice-table thead {
display: table-header-group;
vertical-align: middle;
border-color: inherit;
}
.fel-invoice-table>tbody>tr>td, .fel-invoice-table>tbody>tr>th, .fel-invoice-table>tfoot>tr>td, .fel-invoice-table>tfoot>tr>th, .fel-invoice-table>thead>tr>td, .fel-invoice-table>thead>tr>th {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #ddd;
}
.fel-invoice-table>thead>tr>th {
vertical-align: bottom;
border-bottom: 2px solid #ddd;
border-top: 0;
}
</style>';
}
}
<file_sep><?php
/*
Plugin Name: FEL Invoice Synchronization
Plugin URI: https://thestores.site/
Description: FelInvoice API is being used for Shops using WooCommerce to communicate with FelInvoice
Version: 1.2.0
Author: Mario
Author URI: https://thestores.site/
Update Server: https://thestores.site/
Min WP Version: 3.0.1
Max WP Version: 5.4.0
License: GPL2
WC requires at least: 3.0.0
WC tested up to: 4.2.0
FelInvoice API is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
any later version.
*/
define("FEL_INVOICE_BASE", plugin_dir_url(__FILE__));
//register rest handler, actions and filters
require_once __DIR__ . '/api/FelInvoiceHandler.php';
require_once __DIR__ . '/pages/FelInvoicePluginConfig.php';
require_once __DIR__ .'/plugin/FelInvoiceInstaller.php';
require_once __DIR__ .'/plugin/FelInvoiceRegisterOrder.php';
require_once __DIR__ .'/plugin/FelInvoiceRegisterProduct.php';
$installer = new FelInvoiceInstaller();
$installer->registerEvents();
$regOrder = new FelInvoiceRegisterOrder();
$regOrder->registerEvents();
/*
$regProduct = new FelInvoiceRegisterProduct();
$regProduct->registerEvents();
$handler = new FelInvoiceHandler();
$handler->registerEvents();
*/
if(!function_exists('fel_invoice_plugin_user')){
function fel_invoice_plugin_user() {
$user = new FelInvoicePluginConfig();
$user->buildMarkup();
}
}
//create tables on activation
register_activation_hook( __FILE__, 'fel_invoice_activation' );
/**
* called for activating astroweb
*/
function fel_invoice_activation() {
$installer = new FelInvoiceInstaller();
$installer->setUp();
}
register_deactivation_hook(__FILE__, 'fel_invoice_deactivation');
/**
* called when plugin is being deactivated
*/
function fel_invoice_deactivation() {
$installer = new FelInvoiceInstaller();
$installer->tearDown();
}
function fel_invoice_register_plugin_styles() {
wp_register_style( 'astroweb', plugins_url( 'css/astrowebplugin-style.css', __FILE__ ) , array() , fel_invoice_css_js_suffix() );
wp_enqueue_style( 'astroweb' );
}
function fel_invoice_register_plugin_scripts() {
// make sure jQuery is loaded BEFORE our script as we are using it
wp_register_script( 'fel-invoice-order', plugins_url( 'js/astroweb.order.js', __FILE__ ), array( 'jquery' ) , fel_invoice_css_js_suffix() );
wp_enqueue_script( 'fel-invoice-order' );
wp_localize_script('fel-invoice-order', 'astrowebOrder', array('ajax_url' => admin_url('admin-ajax.php')));
}
// load JS and CSS files on admin pages only
add_action('admin_enqueue_scripts', 'fel_invoice_register_plugin_styles' );
add_action('admin_enqueue_scripts', 'fel_invoice_register_plugin_scripts' );
function fel_invoice_autoload($class) {
if ($class == "FelInvoiceInterface") {
require_once __DIR__ .'/plugin/FelInvoiceInterface.php';
}
}
function fel_invoice_css_js_suffix() {
$result = '';
$pluginInfo = get_plugin_data( __FILE__, $markup = false, $translate = false);
if (is_array($pluginInfo) && isset($pluginInfo['Version'])) {
$result = $pluginInfo['Version'];
}
return $result;
}
spl_autoload_register('fel_invoice_autoload');
<file_sep><div class="fel-invoice-container">
<h1>FelInvoice Plugin</h1>
<h2>Authentication key</h2>
<div>
<form method="post">
<?php $this->set_user_auth_keys(); ?>
<?php /*$this->update_webhooks();*/ ?>
<p>
<span id="authkeyarea_help" class="help-block">You will receive the authentication key in your fel account.</span>
</p>
<?php submit_button('Save', "primary", "api_base_url_editor", false); ?>
<?php submit_button('Check connection', "secondary", "check_connection", false); ?>
<p><br></p>
</form>
</div>
<h2>Custom Fields</h2>
<div>
<form method="post">
<?php
$this->set_order_trigger_field();
submit_button('Save', "primary", "api_base_url_editor");
?>
</form>
</div>
</div>
<?php
wp_enqueue_style('fel-invoice-css');
?>
<file_sep>/**
* contains functions for uploading documents to astroweb and working with orders
*/
(function($){
$(document).ready(function(){
/**
* Attachment upload start
*/
$("#_fel_invoice_attachment").on("change", function(){
if ($("#_fel_invoice_attachment").val() == "") {
$('#_fel_invoice_attachment_file').hide();
}
else {
$('#_fel_invoice_attachment_file').show();
$('#_fel_invoice_attachment_file').click(function(event) {
event.stopPropagation();
});
$('#_fel_invoice_attachment_file').click();
}
});
$('#fel_invoice_upload_order_refresh').on('click', function() {
location.href = location.href;
});
$('#_fel_invoice_attachment_file').on('change', prepareUpload);
/**
* celebrity mail
*/
$('#_fel_invoice_celeb_active').on('change', function() {
if ($('#_fel_invoice_celeb_active').prop('checked')) {
$('#fel-invoice-celeb-div').show();
}
else {
$('#fel-invoice-celeb-div').hide();
}
});
//event handler for sending email notifications for celebrity deliveries
$('#fel_invoice_send_celeb_mail').on('click', function() {
if ($('#_fel_invoice_celeb').val() == "") {
$('#_fel_invoice_celeb').focus().select();
}
else {
var data = new FormData();
data.append("action", "fel_invoice_celeb_mail");
data.append("post_id", $('#fel_invoice_order_id').val());
data.append("msg", $('#_fel_invoice_celeb').val());
$('#fel-invoice-celeb-div').fadeOut(750);
executeAjax(data, function(data, textStatus, jqXHR) {
$('#fel-invoice-celeb-div').show();
if(data.response == "SUCCESS"){
$('#fel-invoice-celeb-div').addClass('fel-invoice-alert');
$('#fel-invoice-celeb-div').addClass('fel-invoice-alert-success');
$('#fel-invoice-celeb-div').html('ok!');
}
else {
alert(data.error);
$('#fel-invoice-celeb-div').show();
}
});
}
});
//announce return
$('#fel-invoice-announce-return').on('click', function(e) {
if (confirm("Retoure anmelden?")) {
$('#order_status').val('wc-return-announced');
}
else {
e.preventDefault();
}
});
$('#fel-invoice-reclamation-return').on('click', function(e) {
if (confirm("Reklamation anmelden?")) {
$('#order_status').val('wc-reclam-announced');
}
else {
e.preventDefault();
}
});
/**
* dispatcher loading
*/
//load available dispatcher profiles
$('#fel-invoice-dispatcher-div').hide();
var data = new FormData();
data.append("action", "fel_invoice_load_dispatchers");
data.append("post_id", $('#fel_invoice_order_id').val());
var profiles = {};
if ($('#fel_invoice_order_id') && $('#fel_invoice_order_id').val() > 0) {
executeAjax(data, function(data, textStatus, jqXHR) {
$('#fel-invoice-dispatcher-div').show();
if(data.response == "SUCCESS") {
$('#_fel_invoice_dispatcher').html('');
$.each(data.items, function (i, item) {
$('#_fel_invoice_dispatcher').append($('<option>', {
value: item.value,
text : item.text
}));
});
$('#_fel_invoice_dispatcher').val(data.selectedDispatcher);
profiles = data.items;
dispatcherSelected($('#_fel_invoice_dispatcher').val(), data.selectedDispatcherProduct);
}
else {
// 2018-01-19, <NAME>: don't show an error if profiles could not be loaded
//alert(data.error);
}
});
}
$('#_fel_invoice_dispatcher').on('change', function() {
dispatcherSelected($('#_fel_invoice_dispatcher').val(), "");
});
/**
* called when a dispatcher was selected and adds dispatcher products to second select box
*/
function dispatcherSelected(selectedId, selectedProfile) {
var result = $.grep(profiles, function(e){ return e.value == selectedId; });
$('#_fel_invoice_dispatcher_product').html('');
if (result.length > 0) {
$.each(result, function (i, item) {
$.each(item.subarray, function (j, sub) {
$('#_fel_invoice_dispatcher_product').append($('<option>', {
value: sub.value,
text : sub.text
}));
});
});
}
$('#_fel_invoice_dispatcher_product').val(selectedProfile);
}
/**
* executes an ajax call
*/
function executeAjax(data, cb) {
$.ajax({
url: astrowebOrder.ajax_url,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
cb(data, textStatus, jqXHR);
}
});
}
/**
* prepares file upload and executes ajax call
*/
function prepareUpload(event) {
$('#fel_invoice_upload_message').html('uploading...');
$('#fel_invoice_upload_message').removeClass('fel-invoice-alert-danger');
$('#fel_invoice_upload_message').removeClass('fel-invoice-alert-success');
$('#fel_invoice_upload_message').show();
$('#fel_invoice_upload_order_refresh').hide();
var file = event.target.files;
var data = new FormData();
data.append("action", "fel_invoice_file_upload");
data.append("post_id", $('#fel_invoice_order_id').val());
data.append("fel_invoice_attachment_type", $('#_fel_invoice_attachment').val());
$.each(file, function(key, value)
{
data.append("fel_invoice_attachment_file", value);
});
executeAjax(data, function(data, textStatus, jqXHR) {
if(data.response == "SUCCESS"){
$('#fel_invoice_upload_message').html('ok!').delay(6000).fadeOut();
$('#fel_invoice_upload_order_refresh').show();
$('#_fel_invoice_attachment_file').hide();
$('#fel_invoice_upload_message').addClass('fel-invoice-alert-success');
}
else {
$('#fel_invoice_upload_message').html(data.error);
$('#fel_invoice_upload_message').addClass('fel-invoice-alert-danger');
}
});
}
});
})(jQuery);<file_sep><?php
require_once __DIR__.'/FelInvoiceConnect.php';
require_once __DIR__.'/FelInvoiceException.php';
require_once __DIR__.'/FelInvoiceBasic.php';
/**
* registers api rest calls
* @author <NAME>
*
*/
class FelInvoiceHandler extends FelInvoiceBasic {
private $products;
private $orders;
private $stock;
/**
* setting app actions
*/
public function registerEvents() {
add_action('rest_api_init', array( $this, 'register'));
}
/**
* registeres product routes
* @param string $namespace
*/
private function registerProductRoutes($namespace) {
$this->registerRoute($namespace, 'getall/(?P<timestamp>\d+)', 'getProducts');
$this->registerRoute($namespace, '(?P<post_id>\d+)/', 'getProductById');
}
/**
* registers stock routes
* @param string $namespace
*/
private function registerStockRoutes($namespace) {
$this->registerRoute($namespace, 'alt/set/(?P<post_id>\d+)', 'setAlternativeStock', 'PUT');
$this->registerRoute($namespace, 'set/(?P<post_id>\d+)', 'setStock', 'PUT');
$this->registerRoute($namespace, 'lot/(?P<post_id>\d+)', 'setLot', 'PUT');
}
/**
* registers a route
* @param string $namespace
* @param string $route
* @param string $callback
* @param string $method
*/
private function registerRoute($namespace, $route, $callback, $method="GET") {
register_rest_route( $namespace, $route, array(
'methods' => $method,
'callback' => array($this, $callback)
));
}
/**
* registers order routes
* @param String $namespace
*/
private function registerOrderRoutes($namespace) {
$this->registerRoute($namespace, 'all/(?P<max>\d+)/', 'getOrders');
$this->registerRoute($namespace, '(?P<order_id>\d+)', 'getOrder');
$this->registerRoute($namespace, 'return/announced/(?P<max>\d+)', 'getReturns');
$this->registerRoute($namespace, 'completed/(?P<order_id>\d+)', 'setOrderCompleted', 'PUT');
$this->registerRoute($namespace, 'downloaded/(?P<order_id>\d+)', 'setOrderDownloaded', 'PUT');
$this->registerRoute($namespace, 'track/(?P<order_id>\d+)', 'addTrackingInfo', 'PUT');
$this->registerRoute($namespace, 'return/booked/(?P<order_id>\d+)', 'returnOrderBooked', 'PUT');
$this->registerRoute($namespace, 'cancel/(?P<order_id>\d+)', 'cancelOrder', 'PUT');
$this->registerRoute($namespace, 'fulfillment/(?P<order_id>\d+)', 'fulfillment', 'PUT');
$this->registerRoute($namespace, 'addItemInformationInOrder/(?P<order_id>\d+)', 'addItemInformationInOrder', 'PUT');
$this->registerRoute($namespace, 'fulfillmentBlocked/(?P<order_id>\d+)', 'fulfillmentBlocked', 'PUT');
$this->registerRoute($namespace, 'transmit/(?P<order_id>\d+)', 'transmitOrder', 'PUT');
$this->registerRoute($namespace, 'hook/status', 'statusHook', 'POST');
$this->registerRoute($namespace, 'track', 'addTrackingInfo', 'POST');
}
/**
* called when status updates where submitted by astroweb backend
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function statusHook(WP_REST_Request $request) {
try {
//check if hook is activated
$hook = get_option("fel_invoice_hook_token");
$params = $request->get_params();
if ($hook) {
if ($hook === $params['token']) {
$eventData = $params['eventData'];
$status = $eventData['statusName'];
if ($status == "CANCELLED") {
return $this->generateOutput("skip ".$status);
}
$orderId = $eventData['externalId'];
//get current status from astroweb
$connect = new FelInvoiceConnect();
$json = $connect->getCurrentStatus($orderId);
if ($json) {
$this->orders->handleOrderStatus($orderId, $json, $status);
}
return $this->generateOutput("order:".$orderId." status: ".$status);
}
else {
return $this->generateOutput("token not valid ! ", "Webhook", false, 403, $params['token']);
}
}
return $this->generateOutput("no hook !", "Webhook", false, 404);
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* loads orders that were set to status return announced
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function getReturns(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->getOrders(false, $params['max']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* loads all orders since time
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function getOrders(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->getOrders(true, $params['max']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* loads order details by order id
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function getOrder(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->getOrder($params['order_id']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* sets an order as completed
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function setOrderCompleted(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->setOrderStatus($params['order_id'], 'wc-completed'));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* sets an order as downloaded
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function setOrderDownloaded(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->setOrderDownloaded($params['order_id'], null));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* adds tracking information to an order
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function addTrackingInfo(WP_REST_Request $request) {
try {
//check if hook is activated
$hook = get_option("fel_invoice_hook_token");
$params = $request->get_params();
if ($hook) {
if ($hook === $params['token']) {
$params = $params['eventData'];
$connect = new FelInvoiceConnect();
$json = $connect->getTrackingNumber($params['goodsOrderParcelId']);
if ($json != false) {
$carrier = "";
if (array_key_exists('goodsOrderExternalId', $params)){
$externalID = $params['goodsOrderExternalId'];
$carrier = $json->profileName;
$trackingNumber = $json->trackingNumber;
return $this->generateOutput($this->orders->addTrackingInfo($externalID, $trackingNumber, $carrier));
}else{
return $this->generateOutput("goodsOrderExternalId Not found", "Webhook", false, 403, $params['token']);
}
}else{
return $this->generateOutput("No tracking number found", "Webhook", false, 403, $params['token']);
}
}
else {
return $this->generateOutput("token not valid ! ", "Webhook", false, 403, $params['token']);
}
}
return $this->generateOutput("no hook !", "Webhook", false, 404);
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* adds item information to an order
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function addItemInformationInOrder(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
if (!key_exists('order_id', $params) || !$params['order_id']) {
return $this->generateOutput(null, 'order ID is required', false, 500);
}
if (!key_exists('posId', $params) || !$params['posId']) {
return $this->generateOutput(null, 'item ID (posId) is required', false, 500);
}
$order = wc_get_order($params['order_id']);
if (!$order) {
return $this->generateOutput(null, 'order '.$params['order_id'].' not found', false, 500);
}
$hasItem = false;
foreach($order->get_items() as $itemId => $item ){
if ($itemId == $params['posId']) {
$hasItem = true;
break;
}
}
if (!$hasItem) {
return $this->generateOutput(null, 'order '.$params['order_id'].' has no item '.$params['posId'], false, 500);
}
$this->orders->addSerialNumber($params['posId'], $params['serialNumber']);
$this->orders->addLot($params['posId'], $params['lot']);
$this->orders->addMetaSku($params['posId'], $params['sku']);
return $this->generateOutput(0);
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* books a returned order
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function returnOrderBooked(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->bookedReturnShipment($params['order_id'],
$params['product_id'], $params['quantity'], $params['choice'], $params['reason'],
$params['serialNumber'], $params['lot'], $params['sku']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* cancels an order
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function cancelOrder(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->setOrderCancelled($params['order_id']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* sets order status fulfillment
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function fulfillment(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->setOrderFulfillment($params['order_id']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* sets an order as fulfillment blocked (e.g. shipping label couldn't be created successfully)
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function fulfillmentBlocked(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
return $this->generateOutput($this->orders->setOrderFulfillment(
$params['order_id']), $params['reason']);
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* sets stock
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function setStock(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
$post_id = $params['post_id'];
$new_stock = $params['quantity'];
return $this->generateOutput($this->stock->newStock($post_id, $new_stock));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* sets alternative stock
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function setAlternativeStock(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
$post_id = $params['post_id'];
$new_stock = $params['quantity'];
return $this->generateOutput($this->stock->setBStock($post_id, $new_stock));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* adds lot information
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function setLot(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
$post_id = $params['post_id'];
$data = $params['data'];
return $this->generateOutput($this->stock->addLotInformation($post_id,
$data, $params['notReserved']));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* registers methods
*/
public function register() {
$namespace = 'rest/v1/astroweb';
$this->registerProductRoutes($namespace.'/product/');
$this->registerOrderRoutes($namespace.'/order/');
$this->registerStockRoutes($namespace.'/stock/');
$this->registerRoute($namespace, '/info', 'getPluginData');
$this->registerRoute($namespace, '/resetHook', 'resetWebHooks', 'POST');
}
/**
* re-registers to webhooks
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function resetWebHooks(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$data = array();
$connect = new FelInvoiceConnect();
$data['token'] = $connect->registerWebHooks();
return $this->generateOutput($data);
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* reads current plugin data (e.g. version number) and returns it
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function getPluginData(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$plugin_data = array();
if (function_exists('get_plugin_data')) {
$plugin_data = get_plugin_data(__DIR__.'/../FelInvoice.php');
}
$plugin_data['fel_invoice_hook_token'] = get_option("fel_invoice_hook_token");
$plugin_data['shop'] = get_option('fel_invoice_plugin_shop_name');
return $this->generateOutput($plugin_data);
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* returns product data
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function getProductById(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
$post = get_post($params['post_id']);
return $this->generateOutput($this->products->getProductData($post, true));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
/**
* loads products
* @param WP_REST_Request $request
* @return WP_REST_Response
*/
public function getProducts(WP_REST_Request $request) {
try {
$this->checkAuth($request);
$params = $request->get_params();
$timestamp = "";
if (array_key_exists("timestamp", $params)) {
$timestamp = $params['timestamp'];
}
return $this->generateOutput($this->products->getAllProducts($timestamp));
}
catch (Exception $e) {
return $this->handleError($e);
}
}
}<file_sep><?php
/**
* provides an interface for accessing functions from other plugins
* @author <NAME>
*
*/
class FelInvoiceInterface {
/**
* called for cancelling an order
* @param int $postId
* @return Boolean true if order was cancelled
* @throws Exception
*/
public function cancelOrder($postId) {
$handler = new FelInvoicePluginOrders();
return $handler->cancelOrder($postId);
}
/**
* sends an order to astroweb
* @param int $postId
* @param WC_Order $orderObj
* @throws Exception
*/
public function transmitOrder($postId, $orderObj=null) {
$handler = new FelInvoicePluginOrders();
$handler->transmitOrder($postId, $orderObj);
}
}<file_sep><?php
require_once __DIR__.'/FelInvoiceException.php';
require_once __DIR__.'/FelInvoiceBasic.php';
/**
* contains function for connecting against fel-invoice-connect api
* @author <NAME>
*
*/
class FelInvoiceConnect extends FelInvoiceBasic {
private $auth_user = "";
private $auth_key = "";
private $app_listen = 0;
private $headers = array('Content-Type'=>'application/xml;charset=UTF-8');
private $xmlOptions = array(
'options' => 0,
'data_is_url' => false,
'ns' => '',
'is_prefix' => false,
'namespace' => null
);
private $debugMode = false;
function __construct() {
$this->auth_user = get_option('fel_invoice_plugin_auth_user');
$this->auth_key = get_option('fel_invoice_plugin_auth_key');
$this->app_listen = get_option('fel_invoice_plugin_app_listen');
}
private function _setXmlOptions($options=0, $data_is_url=false, $ns='', $is_prefix=false, $namespace=null) {
$this->xmlOptions['options'] = $options;
$this->xmlOptions['data_is_url'] = $data_is_url;
$this->xmlOptions['ns'] = $ns;
$this->xmlOptions['is_prefix'] = $is_prefix;
$this->xmlOptions['namespace'] = $namespace;
}
// Define a function that converts array to xml.
private function _array_to_xml($array, $rootElement = null, $xml = null) {
$_xml = $xml;
// If there is no Root Element then insert root
if ($_xml === null) {
$_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>',
$this->xmlOptions['options'],
$this->xmlOptions['data_is_url'],
$this->xmlOptions['ns'],
$this->xmlOptions['is_prefix']
);
//$_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
}
// Visit all key value pair
foreach ($array as $k => $v) {
if($k === "@attributes") {
foreach($v as $key=>$value) {
$_xml->addAttribute($key, $value);
}
} else if($k === "@item_key") {
} else if($k === "@item_values") {
foreach($v as $value) {
$this->_array_to_xml($value, $array['@item_key'], $_xml->addChild($array['@item_key'], null, $this->xmlOptions['namespace']));
}
} else {
// If there is nested array then
if (is_array($v)) {
// Call function for nested array
$this->_array_to_xml($v, $k, $_xml->addChild($k, null, $this->xmlOptions['namespace']));
} else {
// Simply add child element.
$_xml->addChild($k, $v, $this->xmlOptions['namespace']);
}
}
}
return $_xml->asXML();
}
private function _xml_to_array($xml) {
try {
// Convert xml string into an object
$new = simplexml_load_string($xml);
// Convert into json
$con = json_encode($new);
// Convert into associative array
$retArray = json_decode($con, true);
} catch( Exception $ex ) {
return false;
}
return $retArray;
}
/**
* executes a get call
* @param string $serviceUrl
* @return array
*/
private function _GET($serviceUrl) {
return $this->setReturn(wp_remote_get(
$serviceUrl,
array('headers'=>$this->getHeader(),
'method'=>'GET', 'timeout'=>60)
));
}
/**
* executes a POST call
* @param string $serviceUrl
* @param string $postData
* @return array
*/
private function _POST($serviceUrl, $postData) {
$headers = $this->getHeader();
// $headers['Content-length'] = 137;
// $headers['Host'] = 'dev.api.ifacere-fel.com';
// $headers['Cache-Control'] = 'no-cache';
return $this->setReturn(wp_remote_post(
$serviceUrl,
array('headers'=>$headers, 'body' => $postData,
'method'=>'POST', 'timeout'=>60)
));
}
/**
* executes a delete call
* @param string $serviceUrl
* @param string $postData
* @return array
*/
private function _DELETE($serviceUrl, $postData) {
return $this->setReturn(wp_remote_post(
$serviceUrl,
array('headers'=>$this->getHeader(), 'body' => $postData,
'method'=>'DELETE', 'timeout'=>60)
));
}
/**
* executes a put call
* @param string $serviceUrl
* @param string $postData
* @return array
*/
private function _PUT($serviceUrl, $postData) {
return $this->setReturn(wp_remote_request(
$serviceUrl,
array('headers'=>$this->getHeader(), 'body' => $postData,
'method'=>'PUT', 'timeout'=>60)
));
}
/**
* returns headers array
* @return array
*/
private function getHeader() {
return $this->headers;
}
/**
* evaluates call response and returns an array with response information
* @param $response
* @return array|stdClass
*/
private function setReturn($response) {
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-response.txt', print_r($response, true));
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'response-body.txt', print_r($response['body'], true));
if (is_wp_error($response)) {
$ret = array(
'status' => 500,
'error' => $response->get_error_message()
);
return $ret;
}else {
if(strpos($response['headers']['content-type'], 'xml') !== false) {
$ret = $this->_xml_to_array($response['body']);
} else {
$ret = json_decode($response['body'], true);
}
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-response-array.txt', print_r($ret, true));
return $ret;
}
}
/**
* Mikalai-added
* returns check auth key
* @return bool
*/
public function checkAuthKey()
{
$ret = $this->getToken();
if(!empty($ret) && isset($ret['status']) && $ret['status']) {
return true;
} else {
return false;
}
}
/**
* Mikalai-added
* returns credit token object loaded from credits api
* @return object
*/
public function getToken() {
$request = array(
'usuario' => $this->auth_user,
'apikey' => $this->auth_key
);
$this->_setXmlOptions();
$request = $this->_array_to_xml($request, '<SolicitaTokenRequest/>');
$ret = $this->_POST('https://dev.api.ifacere-fel.com/fel-dte-services/api/solicitarToken', $request);
$ret_val = array(
'status' => false,
'data' => array(),
'message' => ''
);
if(isset($ret['error'])) {
$ret_val['message'] = $ret['error'];
} elseif (isset($ret['tipo_respuesta']) && $ret['tipo_respuesta'] == 1) {
$ret_val['message'] = 'error al token';
$ret_val['data'] = $ret;
} else {
$ret_val['status'] = true;
$ret_val['message'] = 'token';
$ret_val['data']['token'] = 'Bearer ' . $ret['token'];
$ret_val['data']['vigencia'] = $ret['vigencia'];
}
return $ret_val;
}
public function factura($order_id) {
$timeNow = $this->_get_now_time_hora();
$order = wc_get_order( $order_id );
$request = array(
'dte:GTDocumento' => array(
'dte:SAT' => array(
'@attributes' => array(
'ClaseDocumento' => "dte"
),
'dte:DTE' => array(
'@attributes' => array(
'ID' => "DatosCertificados"
),
'dte:DatosEmision' => array(
'@attributes' => array(
'ID' => "DatosEmision"
),
'dte:DatosGenerales' => array(
'@attributes' => array(
'CodigoMoneda' => "GTQ",
'FechaHoraEmision' => $timeNow,
//'NumeroAcceso' => '992996460',
'Tipo' => "FACT"
),
),
'dte:Emisor' => array(
'@attributes' => array(
'AfiliacionIVA' => 'GEN',
'CodigoEstablecimiento' => '1',
'NITEmisor' => '82280363',
'NombreComercial' => 'INNOVACIONES MEDICAS INTERNACIONALES, SOCIEDAD ANÓNIMA',
'NombreEmisor' => 'INNOVACIONES MEDICAS INTERNACIONALES, SOCIEDAD ANÓNIMA'
),
'dte:DireccionEmisor' => array(
'dte:Direccion' => $order->get_billing_address_1(),
'dte:CodigoPostal' => $order->get_billing_postcode(),
'dte:Municipio' => $order->get_billing_city(),
'dte:Departamento' => $order->get_billing_state(),
'dte:Pais' => $order->get_billing_country()
)
),
'dte:Receptor' => array(
'@attributes' => array(
'CorreoReceptor' => $order->get_billing_email(),
'IDReceptor' => '77253825', // '77253825',
'NombreReceptor' => $order->get_shipping_first_name().' '.$order->get_shipping_last_name()
),
'dte:DireccionReceptor' => array(
'dte:Direccion' => $order->get_shipping_address_1(),
'dte:CodigoPostal' => $order->get_shipping_postcode(),
'dte:Municipio' => $order->get_shipping_city(),
'dte:Departamento' => $order->get_shipping_state(),
'dte:Pais' => $order->get_shipping_country()
)
),
'dte:Frases' => array(
'dte:Frase' => array(
'@attributes' => array(
'CodigoEscenario' => "1",
'TipoFrase' => "1"
)
)
),
'dte:Items' => array(
'@item_key' => 'dte:Item',
'@item_values' => array()
),
'dte:Totales' => array(
'dte:TotalImpuestos' => array(
'dte:TotalImpuesto' => array(
'@attributes' => array(
'NombreCorto' => 'IVA',
'TotalMontoImpuesto' => $order->get_total_tax()
)
)
),
'dte:GranTotal' => $order->get_subtotal()
),
)
)
)
)
);
$items = $order->get_items();
list(
$request['dte:GTDocumento']['dte:SAT']['dte:DTE']['dte:DatosEmision']['dte:Items']['@item_values'],
$request['dte:GTDocumento']['dte:SAT']['dte:DTE']['dte:DatosEmision']['dte:Totales']['dte:TotalImpuestos']['dte:TotalImpuesto']['@attributes']['TotalMontoImpuesto']) = $this->_fill_items_from($items);
$this->_setXmlOptions(0, false, '', true, 'dte');
$xmlItems = $this->_array_to_xml($request, '<root/>');
$xmlItems = str_replace('<dte:GTDocumento xmlns:dte="dte">', '<dte:GTDocumento xmlns:dte="http://www.sat.gob.gt/dte/fel/0.2.0" xmlns:xd="http://www.w3.org/2000/09/xmldsig#" Version="0.1">', $xmlItems);
$xmlItems = str_replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="utf-8" standalone="no"?>', $xmlItems);
$xmlItems = str_replace('<root>', '', $xmlItems);
$xmlItems = str_replace('</root>', '', $xmlItems);
$xmlItems = trim($xmlItems);
$firmaDocumento = $this->_firmaDocumento($xmlItems);
if($firmaDocumento['status']) {
$registraDocumento = $this->_registraDocumento($firmaDocumento['data']['xml_dte']);
if($registraDocumento['status']) {
$xmlResponse = $registraDocumento['data']['xml_dte'];
//$response = $this->_xml_to_array($xmlResponse);
update_post_meta($order_id, '_fel_invoice_fecha_hora', $timeNow);
update_post_meta($order_id, '_fel_invoice_uuid', $registraDocumento['data']['uuid']);
return array(
'status' => true,
'message' => 'documento procesador correctamente',
'data' => array(
'response' => $registraDocumento['data']['xml_dte'],
'tipo_respuesta' => $registraDocumento['data']['tipo_respuesta'],
'uuid' => $registraDocumento['data']['uuid']
)
);
} else {
return array(
'status' => true,
'message' => 'error al registrar documento',
'data' => $registraDocumento
);
}
} else {
return array(
'status' => true,
'message' => 'error al firmar documento',
'data' => $firmaDocumento
);
}
}
public function notaCredito($order_id) {
$request = array(
'dte:GTDocumento' => array(
'@attributes' => array(
'xmlns:dte' => "http://www.sat.gob.gt/dte/fel/0.2.0",
'xmlns:xd' => "http://www.w3.org/2000/09/xmldsig#",
'Version' => "0.1"
),
'dte:SAT' => array(
'@attributes' => array(
'ClaseDocumento' => "dte"
),
'dte:DTE' => array(
'@attributes' => array(
'ID' => "DatosCertificados"
),
'dte:DatosEmision' => array(
'@attributes' => array(
'ID' => "DatosEmision"
),
'dte:DatosGenerales' => array(
'@attributes' => array(
'CodigoMoneda' => "GTQ",
'FechaHoraEmision' => 'req.body.datosGenerales.fechaEmision',
'Tipo' => "NCRE"
),
),
'dte:Emisor' => array(
'@attributes' => array(
'AfiliacionIVA' => 'req.body.emisor.afiliacionIVA',
'CodigoEstablecimiento' => 'req.body.emisor.codigoEstablecimiento',
'NITEmisor' => 'req.body.emisor.nit',
'NombreComercial' => 'req.body.emisor.NombreComercial',
'NombreEmisor' => 'req.body.emisor.nombreEmisor'
),
'dte:DireccionEmisor' => array(
'dte:Direccion' => 'req.body.emisor.direccionEmisor.direccion',
'dte:CodigoPostal' => 'req.body.emisor.direccionEmisor.codigoPostal',
'dte:Municipio' => 'req.body.emisor.direccionEmisor.municipio',
'dte:Departamento' => 'req.body.emisor.direccionEmisor.departamento',
'dte:Pais' => 'req.body.emisor.direccionEmisor.pais'
),
'dte:Receptor' => array(
'@attributes' => array(
'CorreoReceptor' => 'req.body.receptor.correoReceptor',
'IDReceptor' => 'req.body.receptor.idReceptor',
'NombreReceptor' => 'req.body.receptor.nombreReceptor'
),
'dte:DireccionReceptor' => array(
'dte:Direccion' => 'req.body.receptor.direccionReceptor.direccion',
'dte:CodigoPostal' => 'req.body.receptor.direccionReceptor.codigoPostal',
'dte:Municipio' => 'req.body.receptor.direccionReceptor.municipio',
'dte:Departamento' => 'req.body.receptor.direccionReceptor.departamento',
'dte:Pais' => 'req.body.receptor.direccionReceptor.pais'
)
),
'dte:Items' => array(
'dte:Item' => array()
),
'dte:Totales' => array(
'dte:TotalImpuestos' => array(
'dte:TotalImpuesto' => array(
'@attributes' => array(
'NombreCorto' => 'req.body.totales.totalImpuestos.nombreCorto',
'TotalMontoImpuesto' => 'req.body.totales.totalImpuestos.totalMontoImpuesto'
)
)
),
'dte:GranTotal' => 'req.body.totales.granTotal'
),
'dte:Complementos' => array(
'dte:Complemento' => array(
'@attributes' => array(
'IDComplemento' => "1",
'NombreComplemento' => "NOTA CREDITO",
'URIComplemento' => "http://www.sat.gob.gt/face2/ComplementoReferenciaNota/0.1.0"
),
'cno:ReferenciasNota' => array(
'@attributes' => array(
'xmlns:cno' => "http://www.sat.gob.gt/face2/ComplementoReferenciaNota/0.1.0",
'FechaEmisionDocumentoOrigen' => 'req.body.complementos.fechaEmisionDocumentoOrigen',
'MotivoAjuste' => 'req.body.complementos.motivoAjuste',
'NumeroAutorizacionDocumentoOrigen' => 'req.body.complementos.numeroAutorizacionDocumentoOrigen',
'Version' => "1"
)
)
)
)
),
)
)
)
)
);
$xmlItems = $this->_array_to_xml($request, '<root/>');
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-notacredito-.txt', $xmlItems);
$firmaDocumento = $this->_firmaDocumento($xmlItems);
}
public function notaAbono($order_id) {
$request = array(
'dte:GTDocumento' => array(
'@attributes' => array(
'xmlns:dte' => "http://www.sat.gob.gt/dte/fel/0.2.0",
'xmlns:xd' => "http://www.w3.org/2000/09/xmldsig#",
'Version' => "0.1"
),
'dte:SAT' => array(
'@attributes' => array(
'ClaseDocumento' => "dte"
),
'dte:DTE' => array(
'@attributes' => array(
'ID' => "DatosCertificados"
),
'dte:DatosEmision' => array(
'@attributes' => array(
'ID' => "DatosEmision"
),
'dte:DatosGenerales' => array(
'@attributes' => array(
'CodigoMoneda' => "GTQ",
'FechaHoraEmision' => 'req.body.datosGenerales.fechaEmision',
'Tipo' => "NABN"
),
),
'dte:Emisor' => array(
'@attributes' => array(
'AfiliacionIVA' => 'req.body.emisor.afiliacionIVA',
'CodigoEstablecimiento' => 'req.body.emisor.codigoEstablecimiento',
'NITEmisor' => 'req.body.emisor.nit',
'NombreComercial' => 'req.body.emisor.NombreComercial',
'NombreEmisor' => 'req.body.emisor.nombreEmisor'
),
'dte:DireccionEmisor' => array(
'dte:Direccion' => 'req.body.emisor.direccionEmisor.direccion',
'dte:CodigoPostal' => 'req.body.emisor.direccionEmisor.codigoPostal',
'dte:Municipio' => 'req.body.emisor.direccionEmisor.municipio',
'dte:Departamento' => 'req.body.emisor.direccionEmisor.departamento',
'dte:Pais' => 'req.body.emisor.direccionEmisor.pais'
),
'dte:Receptor' => array(
'@attributes' => array(
'CorreoReceptor' => 'req.body.receptor.correoReceptor',
'IDReceptor' => 'req.body.receptor.idReceptor',
'NombreReceptor' => 'req.body.receptor.nombreReceptor'
),
'dte:DireccionReceptor' => array(
'dte:Direccion' => 'req.body.receptor.direccionReceptor.direccion',
'dte:CodigoPostal' => 'req.body.receptor.direccionReceptor.codigoPostal',
'dte:Municipio' => 'req.body.receptor.direccionReceptor.municipio',
'dte:Departamento' => 'req.body.receptor.direccionReceptor.departamento',
'dte:Pais' => 'req.body.receptor.direccionReceptor.pais'
)
),
'dte:Items' => array(
'dte:Item' => array()
),
'dte:Totales' => array(
'dte:GranTotal' => 'req.body.totales.granTotal'
)
),
)
)
)
)
);
$xmlItems = $this->_array_to_xml($request, '<root/>');
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-notaabono-.txt', $xmlItems);
$firmaDocumento = $this->_firmaDocumento($xmlItems);
}
public function anulacion($order_id) {
$timeNow = $this->_get_now_time_hora();
$fechaHoraCreated = get_post_meta($order_id, '_fel_invoice_fecha_hora', true);
$fechaUUID = get_post_meta($order_id, '_fel_invoice_uuid', true);
if(!empty($fechaHoraCreated) && !empty($fechaUUID)) {
$request = array(
'ns:GTAnulacionDocumento' => array(
'ns:SAT' => array(
'ns:AnulacionDTE' => array(
'@attributes' => array(
'ID' => "DatosCertificados"
),
'ns:DatosGenerales' => array(
'@attributes' => array(
'ID' => "DatosAnulacion",
'NumeroDocumentoAAnular' => $fechaUUID,
'NITEmisor' => '82280363',
'IDReceptor' => '77253825',
'FechaEmisionDocumentoAnular' => $fechaHoraCreated,
'FechaHoraAnulacion' => $timeNow,
'MotivoAnulacion' => 'Anulacion'
)
)
)
)
)
);
$this->_setXmlOptions(0, false, '', true, 'ns');
$xmlCancel = $this->_array_to_xml($request, '<root/>');
$xmlCancel = str_replace('<ns:GTAnulacionDocumento xmlns:ns="ns">', '<ns:GTAnulacionDocumento xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:ns="http://www.sat.gob.gt/dte/fel/0.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="0.1">', $xmlCancel);
$xmlCancel = str_replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="utf-8"?>', $xmlCancel);
$xmlCancel = str_replace('<root>', '', $xmlCancel);
$xmlCancel = str_replace('</root>', '', $xmlCancel);
$xmlItems = trim($xmlCancel);
file_put_contents(dirname(__FILE__) . '/../debug/' . time() . '-anulacion-.txt', $xmlCancel);
$firmaDocumento = $this->_firmaDocumento($xmlCancel);
if ($firmaDocumento['status']) {
$anulaDocumento = $this->_anulaDocumento($firmaDocumento['data']['xml_dte']);
if ($anulaDocumento['status']) {
$xmlResponse = $anulaDocumento['data']['xml_dte'];
//$response = $this->_xml_to_array($xmlResponse);
update_post_meta($order_id, '_fel_invoice_fecha_hora_cancel', $timeNow);
update_post_meta($order_id, '_fel_invoice_uuid_cancel', $anulaDocumento['data']['uuid']);
return array(
'status' => true,
'message' => 'documento procesador correctamente',
'data' => array(
'response' => $anulaDocumento['data']['xml_dte'],
'tipo_respuesta' => $anulaDocumento['data']['tipo_respuesta'],
'uuid' => $anulaDocumento['data']['uuid']
)
);
} else {
return array(
'status' => true,
'message' => 'error al registrar documento',
'data' => $anulaDocumento
);
}
} else {
return array(
'status' => true,
'message' => 'error al firmar documento',
'data' => $firmaDocumento
);
}
}
}
private function _get_now_time_hora() {
$original_timezone = date_default_timezone_get();
// @codingStandardsIgnoreStart
date_default_timezone_set( 'America/Guatemala' );
//$ret_val = date('c');
$ret_val = date("c", strtotime(date("Y-m-d h:i:sa")));
date_default_timezone_set( $original_timezone );
return $ret_val;
}
private function _fill_items_from($items) {
$dteItems = array();
$line_index = 0;
$dump = '';
$total_tax = 0;
foreach ( $items as $item ) {
$line_index++;
$product = $item->get_product();
$sale_price = $product->get_sale_price() ? $product->get_sale_price() : $product->get_price();
$sale_price = number_format($sale_price, 4);
$tmp_tax1 = number_format($sale_price * $item->get_quantity() / 1.12, 4);
$tmp_tax2 = $sale_price * $item->get_quantity() - $tmp_tax1;
$total_tax += $tmp_tax2;
$dteItem = array(
'@attributes' => array(
'BienOServicio' => "B",
'NumeroLinea' => $line_index
),
'dte:Cantidad' => $item->get_quantity(),
'dte:UnidadMedida' => 'UN',
'dte:Descripcion' => $item->get_name(),
'dte:PrecioUnitario' => number_format($item->get_subtotal() / $item->get_quantity(), 4),
'dte:Precio' => $item->get_subtotal(),
'dte:Descuento' => $item->get_subtotal() - $item->get_total(),
'dte:Impuestos' => array(
'dte:Impuesto' => array(
'dte:NombreCorto' => 'IVA',
'dte:CodigoUnidadGravable' => 1,
'dte:MontoGravable' => $tmp_tax1,
'dte:MontoImpuesto' => $tmp_tax2
)
),
'dte:Total' => $item->get_subtotal()
);
$dteItems[] = $dteItem;
$dump.=print_r($product, true).'\n\r';
}
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-dump.txt', $dump);
return array($dteItems, $total_tax);
}
private function _firmaDocumento($xml, $token='') {
if(empty($token)) {
$token = $this->getToken();
$token = $token['data']['token'];
}
$this->headers = array(
'Content-Type' => 'application/xml;charset=UTF-8',
'Authorization' => $token
);
$request = '<?xml version="1.0" encoding="UTF-8"?><FirmaDocumentoRequest id="A3FD2363-05C2-AB7B-373D-56C08CF892B6"><xml_dte><![CDATA['.$xml.']]></xml_dte></FirmaDocumentoRequest>';
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-firma.txt', $request);
$ret = $this->_POST('https://dev.api.soluciones-mega.com/api/solicitaFirma', $request);
$ret_val = array(
'status' => false,
'data' => array(),
'message' => ''
);
if(isset($ret['error'])) {
$ret_val['message'] = $ret['error'];
} elseif (isset($ret['tipo_respuesta']) && $ret['tipo_respuesta'] == 1) {
$ret_val['message'] = 'error al firmar documento';
$ret_val['data'] = $ret;
} else {
$ret_val['status'] = true;
$ret_val['message'] = 'documento firmado';
$ret_val['data'] = $ret;
}
return $ret_val;
}
private function _registraDocumento($xml, $token='') {
if(empty($token)) {
$token = $this->getToken();
$token = $token['data']['token'];
}
$this->headers = array(
'Content-Type' => 'application/xml;charset=UTF-8',
'Authorization' => $token
);
$request = '<?xml version="1.0" encoding="UTF-8"?>
<RegistraDocumentoXMLRequest id="166437D6-0BE3-467C-947C-EC8018DB0A03">
<xml_dte>
<![CDATA['.$xml.']]>
</xml_dte>
</RegistraDocumentoXMLRequest>';
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-register.txt', $request);
$ret = $this->_POST('https://dev2.api.ifacere-fel.com/api/registrarDocumentoXML', $request);
$ret_val = array(
'status' => false,
'data' => array(),
'message' => ''
);
if(isset($ret['error'])) {
$ret_val['message'] = $ret['error'];
} elseif (isset($ret['tipo_respuesta']) && $ret['tipo_respuesta'] == 1) {
$ret_val['message'] = 'error al registrar documento';
$ret_val['data'] = $ret;
} else {
$ret_val['status'] = true;
$ret_val['message'] = 'documento registrado';
$ret_val['data'] = $ret;
}
return $ret_val;
}
private function _anulaDocumento($xml, $token='') {
if(empty($token)) {
$token = $this->getToken();
$token = $token['data']['token'];
}
$this->headers = array(
'Content-Type' => 'application/xml;charset=UTF-8',
'Authorization' => $token
);
$request = '<?xml version=\'1.0\' encoding=\'UTF-8\'?>
<AnulaDocumentoXMLRequest id="B10DC019-A68E-4977-85A8-848F623C518C">
<xml_dte><![CDATA['.$xml.']]></xml_dte>
</AnulaDocumentoXMLRequest>';
file_put_contents(dirname(__FILE__) . '/../debug/'.time().'-ann.txt', $request);
$ret = $this->_POST('https://dev2.api.ifacere-fel.com/api/anularDocumentoXML', $request);
$ret_val = array(
'status' => false,
'data' => array(),
'message' => ''
);
if(isset($ret['error'])) {
$ret_val['message'] = $ret['error'];
} elseif (isset($ret['tipo_respuesta']) && $ret['tipo_respuesta'] == 1) {
$ret_val['message'] = 'error al anula documento';
$ret_val['data'] = $ret;
} else {
$ret_val['status'] = true;
$ret_val['message'] = 'documento anula';
$ret_val['data'] = $ret;
}
return $ret_val;
}
}
<file_sep><?php
/**
* used for throwing specific api exceptions
* @author <NAME>
*
*/
class FelInvoiceException extends Exception {
private $returnCode = 500;
function __construct($message, $returnCode) {
parent::__construct($message);
$this->returnCode = $returnCode;
}
/**
* returns return code
* @return number
*/
public function getReturnCode() {
return $this->returnCode;
}
}<file_sep><?php
require_once __DIR__ . '/../api/FelInvoiceConnect.php';
/**
* handles filters and actions for products
* @author <NAME>
*
*/
class FelInvoiceRegisterProduct {
/**
* sets actions
*/
public function registerEvents() {
/*
add_action( 'woocommerce_product_after_variable_attributes', array($this, 'extendVariationsMetabox'), 20, 3 );
add_action( 'woocommerce_save_product_variation', array($this, 'saveProductVariation'), 20, 2 );
add_action( 'woocommerce_process_product_meta', array($this, 'updateProduct'), 10, 2 );
add_action('save_post', array($this, 'savePost'), 10, 3);
add_filter('woocommerce_product_data_tabs', array($this, 'addFelInvoiceTab'));
add_action('woocommerce_product_data_panels', array($this, 'loadFelInvoiceTabContent'));
// ADDING A CUSTOM COLUMN TITLE TO ADMIN PRODUCTS LIST
add_filter( 'manage_edit-product_columns', array($this, 'addFelInvoiceColumn'),11);
// ADDING THE DATA FOR EACH PRODUCTS BY COLUMN (EXAMPLE)
add_action( 'manage_product_posts_custom_column' , array($this, 'loadFelInvoiceColumnContent'), 10, 2 );
*/
}
/**
* loads astroweb tab
*/
public function loadFelInvoiceTabContent() {
$connect = new FelInvoiceConnect();
$sku_options = $connect->getProductNameList(true);
array_unshift($sku_options, '');
$id = get_the_ID();
echo '<div id="fel_invoice_product_data" class="panel woocommerce_options_panel hidden">';
woocommerce_wp_select(
array(
'id' => '_fel_invoice_sku',
'label' => 'FelInvoice Product',
'desc_tip' => 'true',
'value' => get_post_meta($id, '_fel_invoice_sku', true),
'description' => __( 'select matched product of AstroWeb', 'woocommerce' ),
'options' => $sku_options
)
);
echo '</div>';
}
/**
* adds a astroweb tab
* @param array $tabs
* @return array
*/
public function addFelInvoiceTab($tabs) {
$tabs['fel_invoice_tab'] = array(
'label' => 'FelInvoice',
'priority' => 150,
'class' => array('fel_invoice_product_data'),
'target' => 'fel_invoice_product_data'
);
return $tabs;
}
/**
* called when a post is being saved
* @param int $post_id
* @param WP_POST $post
* @param boolean $update
*/
public function savePost($post_id, $post, $update){
/*
$connect = new FelInvoiceConnect();
update_post_meta($post_id, '_fel_invoice_upd_connect', $connect->transmitProductData($post));
*/
return;
}
/**
* called when updating a product
* @param int $post_id
*/
public function updateProduct( $post_id ){
$connect = new FelInvoiceConnect();
$sku_options = $connect->getProductNameList(false);
array_unshift($sku_options, '');
$aw_sku = $_POST['_fel_invoice_sku'];
if( !empty( $aw_sku ) ) {
$prodid_name = $sku_options[$aw_sku];
update_post_meta($post_id, '_fel_invoice_sku', esc_attr($aw_sku));
if(!empty($prodid_name)) {
$patterns = explode('|||', $prodid_name);
if(!empty($patterns[0]) && !empty($patterns[1])) {
update_post_meta($post_id, '_fel_invoice_prodid', esc_attr($patterns[0]));
update_post_meta($post_id, '_fel_invoice_prodname', esc_attr($patterns[1]));
}
}
} else {
update_post_meta( $post_id, '_fel_invoice_sku', esc_attr( 0 ) );
update_post_meta( $post_id, '_fel_invoice_prodid', esc_attr( 0 ) );
update_post_meta( $post_id, '_fel_invoice_prodname', esc_attr( '' ) );
}
}
/**
* Save extra meta info for variable products
*
* @param int $variation_id
* @param int $i
* return void
*/
public function saveProductVariation( $variation_id, $i ){
$connect = new FelInvoiceConnect();
$sku_options = $connect->getProductNameList(false);
array_unshift($sku_options, '');
if ( isset( $_POST['variation_fel_invoice_sku'][$i] ) ) {
// sanitize data in way that makes sense for your data type
$custom_data = ( trim( $_POST['variation_fel_invoice_sku'][$i] ) === '' ) ? '' : sanitize_title( $_POST['variation_fel_invoice_sku'][$i] );
update_post_meta( $variation_id, '_fel_invoice_sku', $custom_data );
$prodid_name = $sku_options[$custom_data];
if(!empty($prodid_name)) {
$patterns = explode('|||', $prodid_name);
if(!empty($patterns[0]) && !empty($patterns[1])) {
update_post_meta( $variation_id, '_fel_invoice_prodid', $patterns[0] );
update_post_meta( $variation_id, '_fel_invoice_prodname', $patterns[1] );
}
}
} else {
update_post_meta( $variation_id, '_fel_invoice_sku', 0 );
update_post_meta( $variation_id, '_fel_invoice_prodid', 0 );
update_post_meta( $variation_id, '_fel_invoice_prodname', '' );
}
$this->savePost($variation_id, get_post($variation_id), true);
}
/**
* Add new inputs to each variation
*
* @param string $loop
* @param array $variation_data
*/
public function extendVariationsMetabox( $loop, $variation_data, $variation ){
$connect = new FelInvoiceConnect();
$sku_options = $connect->getProductNameList(true);
array_unshift($sku_options, '');
$aw_sku = get_post_meta( $variation->ID, '_fel_invoice_sku', true );
echo '<div class="variable_custom_field">
<p class="form-row form-row-first">
<label>Seriennummer aktiv:</label>
<select name="variation_fel_invoice_sku['.$loop.']">';
foreach($sku_options as $key=>$value) {
echo '<option value="'.$key.'"'.($key==$aw_sku ? " selected" : "").'>'.$value.'</option>';
}
echo '</select>
</p>
</div>';
}
/*
* Mikalai-added
*/
function addFelInvoiceColumn($columns)
{
// <img src="http://localhost:8080/woo/wp-content/plugins/fel-invoice-api/plugin/../images/felinvoice.png" alt="">
//add columns
return array_slice( $columns, 0, 4, true )
+ array( 'fel_invoice_sku' => __( '<img src="'.plugin_dir_url(__FILE__).'../images/felinvoice.png" alt="AstroWeb">', 'woocommerce') )
+ array_slice( $columns, 4, NULL, true );
}
/*
* Mikalai-added
*/
function loadFelInvoiceColumnContent( $column, $product_id )
{
global $post;
// HERE get the data from your custom field (set the correct meta key below)
$aw_prodname = get_post_meta( $product_id, '_fel_invoice_prodname', true);
switch ( $column )
{
case 'fel_invoice_sku' :
echo $aw_prodname; // display the data
break;
}
}
}<file_sep><?php
require_once __DIR__ . '/../api/FelInvoiceConnect.php';
require_once __DIR__ . '/FelInvoiceInstaller.php';
require_once __DIR__ . '/FelInvoiceRegisterAjaxOrder.php';
/**
* handles filters and actions for orders
* @author <NAME>
*
*/
class FelInvoiceRegisterOrder {
/**
* ajax handler
* @var FelInvoiceRegisterAjaxOrder
*/
private $ajaxHandler = null;
/**
* defines filters and actions
*/
public function registerEvents() {
//add_action('woocommerce_process_shop_order_meta', array($this, 'updateOrder'), 10, 1);
add_action('woocommerce_admin_order_data_after_order_details', array($this, 'addOrderFields'), 10, 3);
add_action('woocommerce_order_status_changed', array($this, 'statusChanged'), 10, 3);
/*
//new columns in orders view
add_filter('woocommerce_shop_order_search_fields', array($this, 'addCustomSearchFields'));
add_filter("manage_edit-shop_order_sortable_columns", array($this, 'sortCustomFields'));
add_action('manage_shop_order_posts_custom_column' , array($this, 'loadCustomColumnContent'), 10, 2 );
add_filter('manage_edit-shop_order_columns', array($this, 'addCustomOrderColumns'), 11);
add_action('pre_get_posts', array($this, 'orderByMetaFields'));
//adds a astroweb meta box for showing/storing additional information
add_action('add_meta_boxes', array($this, 'addFelInvoiceOrderBox'));
*/
//register ajax events
$this->ajaxHandler = new FelInvoiceRegisterAjaxOrder();
$this->ajaxHandler->registerEvents();
}
/**
* adds a custom astroweb order box
*/
function addFelInvoiceOrderBox()
{
add_meta_box(
'woocommerce-order-fel-invoice-orderbox',
'FelInvoice',
array($this, 'addFelInvoiceOrderBoxContent'),
'shop_order',
'side',
'default'
);
}
/**
* adds content to astroweb custom order box
* @param stdClass $post
*/
function addFelInvoiceOrderBoxContent($post) {
//load order
$order = wc_get_order($post->ID);
//we need to know the ajax url
echo '<input type="hidden" name="fel_invoice_order_id" id="fel_invoice_order_id" value="'.$post->ID.'" />';
$orderCreated = true;
if (!$order || $order->get_date_created() == null) {
//order not created. But we want to display skipping serial number checks
$orderCreated = false;
}
if ($orderCreated) {
//TODO: if not processing/fulfillment, some values should not be changable anymore
//priority
woocommerce_wp_select(
array(
'id' => '_fel_invoice_priority',
'label' => 'Priorität',
'class' => 'fel-invoice-select',
'desc_tip' => 'true',
'value' => get_post_meta($post->ID, '_fel_invoice_priority', true),
'description' => __( 'Priorität des Auftrages in FelInvoice', 'woocommerce' ),
'options' => array(
'3' => "Normal",
'2' => "Hoch",
'1' => "Sehr hoch"
)
)
);
woocommerce_wp_text_input(
array(
'id' => '_fel_invoice_linked_order',
'label' => 'Auftrag',
'desc_tip' => 'true',
'class' => 'fel-invoice-select',
'value' => get_post_meta($post->ID, '_fel_invoice_linked_order', true),
'description' => __('Verlinkter Auftrag, zum Beispiel für Austausch-Aufträge', 'woocommerce')
)
);
}
if ($orderCreated) {
echo '<hr />';
}
echo '<h4>Retoure</h4>';
$createWECheck = get_post_meta($post->ID, '_fel_invoice_return_we', true);
woocommerce_wp_checkbox(
array(
'id' => '_fel_invoice_return_we',
'label' => 'WE',
'desc_tip' => 'true',
'value' => $createWECheck,
'class' => 'fel-invoice-select',
'description' => __('Retoure auf Wareneingang', 'woocommerce'),
)
);
$createWACheck = get_post_meta($post->ID, '_fel_invoice_return_wa', true);
woocommerce_wp_checkbox(
array(
'id' => '_fel_invoice_return_wa',
'label' => 'WA',
'desc_tip' => 'true',
'value' => $createWACheck,
'class' => 'fel-invoice-select',
'description' => __('Retoure auf Warenausgang', 'woocommerce'),
)
);
$skipSerialNumberCheck = get_post_meta($post->ID, '_fel_invoice_return_checkserial', true);
woocommerce_wp_checkbox(
array(
'id' => '_fel_invoice_return_checkserial',
'label' => 'Kein SN-Check',
'desc_tip' => 'true',
'value' => $skipSerialNumberCheck,
'cbvalue' => 'yes',
'class' => 'fel-invoice-select',
'description' => __('Verhindert bei Retouren die Prüfung der Seriennummer', 'woocommerce'),
)
);
}
/**
* adds a custom search field
* @param array $search_fields
* @return array
*/
public function addCustomSearchFields($search_fields) {
$search_fields[] = 'FEL_INVOICE_PARTIALLY_REASON';
return $search_fields;
}
/**
* called for sorting custom columns
* @param array $columns
* @return array
*/
function sortCustomFields($columns)
{
$columns['fel-invoice-partially'] = 'FEL_INVOICE_PARTIALLY_REASON';
$columns['fel-invoice-download'] = 'FEL_INVOICE_DOWNLOAD_ORDERKEY';
$columns['fel-invoice-priority'] = '_fel_invoice_priority';
$columns['fel-invoice-fulfill'] = 'fulfillment-blocked';
return $columns;
}
/**
* called for displaying custom fields
* @param array $column
* @param int $post_id
*/
function loadCustomColumnContent($column, $post_id)
{
switch ($column)
{
case 'fel-invoice-fulfill':
echo get_post_meta($post_id, "fulfillment-blocked", true);
break;
case 'fel-invoice-partially':
echo get_post_meta($post_id, 'FEL_INVOICE_PARTIALLY_REASON', true);
break;
case 'fel-invoice-download':
echo get_post_meta($post_id, 'FEL_INVOICE_DOWNLOAD_ORDERKEY', true);
break;
case 'fel-invoice-priority':
$prio = get_post_meta($post_id, '_fel_invoice_priority', true);
if (is_array($prio)) {
if (array_key_exists(0, $prio)) {
if (!is_array($prio[0])) {
$prio = $prio[0];
}
else {
$prio = 3;
}
}
else {
$prio = 3;
}
}
echo ($prio > 0 && $prio < 4 ? $prio : 3);
break;
}
}
/**
* allows ordering by meta fields
* @param $query
*/
function orderByMetaFields($query) {
if(!is_admin()) {
return;
}
$orderby = $query->get('orderby');
switch ($orderby) {
case 'fulfillment-blocked':
$query->set('meta_query', 'fulfillment-blocked');
$query->set('orderby', 'meta_value');
break;
case '_fel_invoice_priority':
$query->set('meta_query', '_fel_invoice_priority');
$query->set('orderby', 'meta_value_num');
break;
}
}
/**
* adds custom order columns to admin view
* @param array $columns
* @return array
*/
function addCustomOrderColumns($columns)
{
$columns['fel-invoice-priority'] = "Prio";
$columns['fel-invoice-partially'] = "Grund";
$columns['fel-invoice-fulfill'] = "Blockiert";
$columns['fel-invoice-download'] = "Download";
return $columns;
}
/**
* checks whether order status can be changed to fulfillment
* @param int $post_id
* @throws Exception
*/
public function orderLoaded($post_id) {
$order = wc_get_order($post_id);
if ($order->get_status() == 'processing') {
//try to reserve goods
$reload = get_post_meta($post_id, "_fel-invoice-reload");
}
}
/**
* adds custom fields to order details
*/
public function addOrderFields() {
global $woocommerce, $post;
//notice
woocommerce_wp_textarea_input(
array(
'id' => '_fel_invoice_uuid',
'label' => __( 'Factura UUID (FelInvoice)', 'woocommerce' ),
'desc_tip' => 'true',
'value' => get_post_meta( $post->ID, '_fel_invoice_uuid', true ),
'description' => __( 'generated from FelInvoice.', 'woocommerce' ),
'custom_attributes' => array('readonly' => 'readonly'),
)
);
woocommerce_wp_textarea_input(
array(
'id' => '_fel_invoice_uuid_cancel',
'label' => __( 'Anula UUID (FelInvoice)', 'woocommerce' ),
'desc_tip' => 'true',
'value' => get_post_meta( $post->ID, '_fel_invoice_uuid_cancel', true ),
'description' => __( 'generated from FelInvoice.', 'woocommerce' ),
'custom_attributes' => array('readonly' => 'readonly'),
)
);
$this->orderLoaded($post->ID);
}
/**
* called when an order is being updated
* @param int $order_id
* @throws Exception
*/
public function updateOrder($post_id) {
return;
$woocommerce_text_field = $_POST['_fel_invoice_delivery'];
if( !empty( $woocommerce_text_field ) ) {
update_post_meta( $post_id, '_fel_invoice_delivery', esc_attr( $woocommerce_text_field ) );
}
update_post_meta($post_id, '_fel_invoice_linked_order', esc_attr($_POST['_fel_invoice_linked_order']));
$woocommerce_text_field = $_POST['_fel_invoice_return_note'];
if( !empty( $woocommerce_text_field ) ) {
update_post_meta( $post_id, '_fel_invoice_return_note', esc_attr( $woocommerce_text_field ) );
}
$woocommerce_text_field = isset( $_POST['_fel_invoice_order_blocked'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_fel_invoice_order_blocked', $woocommerce_text_field );
//save priority
$wasPriority = get_post_meta($post_id, '_fel_invoice_priority');
$currentPriority = (int)$_POST['_fel_invoice_priority'];
update_post_meta($post_id, '_fel_invoice_priority', $currentPriority);
//wareneingang check
update_post_meta($post_id, '_fel_invoice_return_we',
isset($_POST['_fel_invoice_return_we']) ? $_POST['_fel_invoice_return_we'] : "");
//warenausgang check
update_post_meta($post_id, '_fel_invoice_return_wa',
isset($_POST['_fel_invoice_return_wa']) ? $_POST['_fel_invoice_return_wa'] : "");
//skip serial number check
update_post_meta($post_id, '_fel_invoice_return_checkserial',
isset($_POST['_fel_invoice_return_checkserial']) ? $_POST['_fel_invoice_return_checkserial'] : "");
//send to connect?
$handler = new FelInvoicePluginOrders();
$orderObj = wc_get_order($post_id);
if ($_POST['order_status'] == "wc-processing") {
//save dispatcher and profile
if (isset($_POST['_fel_invoice_dispatcher']) && isset($_POST['_fel_invoice_dispatcher_product'])) {
update_post_meta($post_id, '_fel_invoice_dispatcher', $_POST['_fel_invoice_dispatcher']);
update_post_meta($post_id, '_fel_invoice_dispatcher_product', $_POST['_fel_invoice_dispatcher_product']);
}
}else if ($_POST['order_status'] == "wc-cancelled" || $_POST['order_status'] == "wc-fel-invoice-cancel") {
sleep(1);
$this->orderCancelled($post_id);
}else {
//update priority
if ($currentPriority != $wasPriority && $handler->isOrderDownloaded($post_id)) {
if (!$handler->getConnect()->updateOrderPriority($post_id, $currentPriority)) {
//reset priority on error
update_post_meta($post_id, '_fel_invoice_priority', $wasPriority);
}
}
}
if ($_POST['order_status'] == "wc-return-announced" || $_POST['order_status'] == "wc-reclam-announced") {
// 2018-02-09, <NAME>: handled by separat event
//check announced returns
/*$order = $handler->getReturnObject($post_id, $orderObj);
if ($order) {
//not sent to astroweb yet
if ($handler->getConnect()->transmitReturn($order, $post_id)) {
$handler->setOrderDownloaded($post_id, FelInvoicePluginOrders::$FEL_INVOICE_RETURN_ORDERKEY);
}
}*/
}else {
update_post_meta($post_id, "_fel-invoice-reload", 1);
}
}
public function statusChanged($order_id, $statusFrom, $statusTo) {
global $wpdb;
$felCreateInvoice = get_option('_fel_invoice_trigerred_create_invoice');
if(strpos($felCreateInvoice, $statusTo) !== false) {
$connect = new FelInvoiceConnect();
$connect->factura($order_id);
}
$felCancelInvoice = get_option('_fel_invoice_trigerred_cancel_invoice');
foreach($felCancelInvoice as $orderTriggered) {
if(strpos($orderTriggered, $statusTo) !== false) {
$connect = new FelInvoiceConnect();
$connect->anulacion($order_id);
break;
}
}
}
}<file_sep><?php
require_once __DIR__.'/FelInvoiceException.php';
/**
* contains basic methods for working with rest api
* @author <NAME>
*
*/
class FelInvoiceBasic {
/**
* checks whether authkey was set in header and matches option
* @param WP_REST_Request $request
* @throws FelInvoiceException
*/
protected function checkAuth($request) {
$headers = $request->get_headers();
if (array_key_exists("authkey", $headers)) {
if ($headers['authkey'][0] != get_option('fel_invoice_plugin_auth_key')) {
throw new FelInvoiceException("2: You don't have permissions accessing this site.", 500);
}
}
else {
throw new FelInvoiceException("2: You don't have permissions accessing this site.", 404);
}
}
/**
* generates json output
* @param array|string $data
* @param string $message
* @param bool $success
* @param int $code
* @param string $token
* @return WP_REST_Response
*/
protected function generateOutput($data=null, $message="", $success=true, $code=200, $token=""){
$result = array();
if ($data != null) {
$result['data'] = $data;
if ($token != "") {
$result['token'] = $token;
}
if (is_array($data) && array_key_exists("Error", $data)) {
$success = false;
if ($code == 200) {
$code = 418;
}
}
}
if ($message != "") {
$result['message'] = $message;
}
$result['success'] = $success;
return new WP_REST_Response($result, $code);
}
/**
* handles error messages
* @param Exception|FelInvoiceException $e
* @return WP_REST_Response
*/
protected function handleError($e) {
$code = 500;
if ($e instanceof FelInvoiceException) {
$code = $e->getReturnCode();
}
return $this->generateOutput(null, $e->getMessage(), false, $code);
}
}<file_sep>"use strict";
const { json } = require('body-parser');
const { debug } = require('request');
module.exports = (core,db,modules,module,controllers,models) => {
class Main {
constructor (){
}
static getInstance (){
if(typeof this.__instance == 'undefined'){
this.__instance = new Base();
}
return this.__instance;
}
// Solicitud de Token
static async token(){
let obj = {
SolicitaTokenRequest:{
usuario: process.env.FEL_USER,
apikey: process.env.FEL_APIKEY
}
};
let builder = new xml2js.Builder();
let xml = builder.buildObject(obj);
let xmlResult = await fetch('https://dev.api.ifacere-fel.com/fel-dte-services/api/solicitarToken', {
method: 'POST',
headers: {
'Content-Type': 'application/xml'
},
body: xml
}).then(response => response.text());
let parser = new xml2js.Parser();
return new Promise((resolve, reject) =>{
parser.parseString(xmlResult, function(err, result){
if(err || result.SolicitaTokenResponse.tipo_respuesta == 1){
reject({
status: false,
message: err.message,
data: result
});
}else{
resolve({
status: true,
message: 'token',
data: {
token: 'Bearer ' + result.SolicitaTokenResponse.token[0],
vigencia: result.SolicitaTokenResponse.vigencia[0]
}
});
}
});
});
}
// Solicitud de Firma electronica
static async firma(xml){
let token = await Main.token();
let xmlResult = await fetch('https://dev.api.soluciones-mega.com/api/solicitaFirma', {
method: 'POST',
headers: {
'Content-Type': 'application/xml;charset=UTF-8',
'Authorization': token.data.token
},
body: `<?xml version="1.0" encoding="UTF-8"?>
<FirmaDocumentoRequest id="A3FD2363-05C2-AB7B-373D-56C08CF892B6">
<xml_dte>
<![CDATA[
`+xml+`
]]>
</xml_dte>
</FirmaDocumentoRequest>`
}).then(response => response.text());
let parser = new xml2js.Parser();
return new Promise((resolve, reject) =>{
parser.parseString(xmlResult, function(err, result){
if(err || result.FirmaDocumentoResponse.tipo_respuesta == 1){
reject({
status: false,
message: 'error al firmar documento',
data: result
});
}else{
resolve({
status: true,
message: 'documento firmado',
data: result
});
}
});
});
}
// Solicitud de registro de documento
static async registra(xml){
let token = await Main.token();
let xmlResult = await fetch('https://dev2.api.ifacere-fel.com/api/registrarDocumentoXML', {
method: 'POST',
headers: {
'Content-Type': 'application/xml;charset=UTF-8',
'Authorization': token.data.token
},
body: `<?xml version="1.0" encoding="UTF-8"?>
<RegistraDocumentoXMLRequest id="166437D6-0BE3-467C-947C-EC8018DB0A03">
<xml_dte>
<![CDATA[
`+xml+`
]]>
</xml_dte>
</RegistraDocumentoXMLRequest>`
}).then(response => response.text());
let parser = new xml2js.Parser();
return new Promise((resolve, reject) =>{
parser.parseString(xmlResult, function(err, result){
if(err || result.RegistraDocumentoXMLResponse.tipo_respuesta == 1){
reject({
status: false,
message: 'error al registrar documento',
data: result
});
}else{
resolve({
status: true,
message: 'documento registrado',
data: result
});
}
});
});
}
// proceso de facturacion electronica
static async factura(req, res){
const obj = {
'dte:GTDocumento': {
$:{
'xmlns:dte': "http://www.sat.gob.gt/dte/fel/0.2.0",
'xmlns:xd': "http://www.w3.org/2000/09/xmldsig#",
'Version': "0.1"
},
'dte:SAT': {
$:{
'ClaseDocumento': "dte"
},
'dte:DTE': {
$:{
'ID': "DatosCertificados"
},
'dte:DatosEmision':{
$: {
'ID': "DatosEmision"
},
'dte:DatosGenerales': {
$: {
'CodigoMoneda': "GTQ",
'FechaHoraEmision': req.body.datosGenerales.fechaEmision,
'Tipo': "FACT"
}
},
'dte:Emisor': {
$: {
'AfiliacionIVA': req.body.emisor.afiliacionIVA,
'CodigoEstablecimiento': req.body.emisor.codigoEstablecimiento,
'NITEmisor': req.body.emisor.nit,
'NombreComercial': req.body.emisor.NombreComercial,
'NombreEmisor': req.body.emisor.nombreEmisor
},
'dte:DireccionEmisor': {
'dte:Direccion': req.body.emisor.direccionEmisor.direccion,
'dte:CodigoPostal': req.body.emisor.direccionEmisor.codigoPostal,
'dte:Municipio': req.body.emisor.direccionEmisor.municipio,
'dte:Departamento': req.body.emisor.direccionEmisor.departamento,
'dte:Pais': req.body.emisor.direccionEmisor.pais
}
},
'dte:Receptor': {
$: {
'CorreoReceptor': req.body.receptor.correoReceptor,
'IDReceptor': req.body.receptor.idReceptor,
'NombreReceptor': req.body.receptor.nombreReceptor
},
'dte:DireccionReceptor': {
'dte:Direccion': req.body.receptor.direccionReceptor.direccion,
'dte:CodigoPostal': req.body.receptor.direccionReceptor.codigoPostal,
'dte:Municipio': req.body.receptor.direccionReceptor.municipio,
'dte:Departamento': req.body.receptor.direccionReceptor.departamento,
'dte:Pais': req.body.receptor.direccionReceptor.pais
}
},
'dte:Frases': {
'dte:Frase': {
$: {
'CodigoEscenario': "1",
'TipoFrase': "1"
}
}
},
'dte:Items': {
'dte:Item':[]
},
'dte:Totales': {
'dte:TotalImpuestos': {
'dte:TotalImpuesto': {
$: {
'NombreCorto': req.body.totales.totalImpuestos.nombreCorto,
'TotalMontoImpuesto': req.body.totales.totalImpuestos.totalMontoImpuesto
}
}
},
'dte:GranTotal': req.body.totales.granTotal
}
}
}
}
}
};
var arrItems = obj['dte:GTDocumento']['dte:SAT']['dte:DTE']['dte:DatosEmision']['dte:Items']['dte:Item'] = [];
for(var key in req.body.items){
let item = req.body.items[key];
arrItems.push({
$: {
"BienOServicio": item.bienOServicio,
"NumeroLinea": key
},
"dte:Cantidad": item.cantidad,
"dte:UnidadMedida": item.unidadMedida,
"dte:Descripcion": item.descripcion,
"dte:PrecioUnitario": item.precioUnitario,
"dte:Precio": item.precio,
"dte:Descuento": item.descuento,
"dte:Impuestos": {
"dte:Impuesto": {
"dte:NombreCorto": item.impuestos.nombreCorto,
"dte:CodigoUnidadGravable": item.impuestos.codigoUnidadGravable,
"dte:MontoGravable": item.impuestos.montoGravable,
"dte:MontoImpuesto": item.impuestos.montoImpuesto
}
},
"dte:Total": item.total
});
}
const builder = new xml2js.Builder();
const xml = builder.buildObject(obj);
let firmaDocumento = await Main.firma(xml);
if(firmaDocumento.status === true){
let registraDocumento = await Main.registra(unescape(firmaDocumento.data.FirmaDocumentoResponse.xml_dte));
if(registraDocumento.status === true){
let xmlResponse = registraDocumento.data.RegistraDocumentoXMLResponse.xml_dte;
let result = await xml2js.parseStringPromise(xmlResponse, { mergeAttrs: true, attrkey: "attr" });
return {
status: true,
message: 'documento procesador correctamente',
data: {
response: result,
tipo_respuesta: registraDocumento.data.RegistraDocumentoXMLResponse.tipo_respuesta,
uuid: registraDocumento.data.RegistraDocumentoXMLResponse.uuid
}
}
}
else{
return {
status: true,
message: 'error al registrar documento',
data: registraDocumento
}
}
}else{
return {
status: true,
message: 'error al firmar documento',
data: firmaDocumento
}
}
}
// proceso de nota de credito
static async notaCredito(req, res){
const obj = {
'dte:GTDocumento': {
$:{
'xmlns:dte': "http://www.sat.gob.gt/dte/fel/0.2.0",
'xmlns:xd': "http://www.w3.org/2000/09/xmldsig#",
'Version': "0.1"
},
'dte:SAT': {
$:{
'ClaseDocumento': "dte"
},
'dte:DTE': {
$:{
'ID': "DatosCertificados"
},
'dte:DatosEmision':{
$: {
'ID': "DatosEmision"
},
'dte:DatosGenerales': {
$: {
'CodigoMoneda': "GTQ",
'FechaHoraEmision': req.body.datosGenerales.fechaEmision,
'Tipo': "NCRE"
}
},
'dte:Emisor': {
$: {
'AfiliacionIVA': req.body.emisor.afiliacionIVA,
'CodigoEstablecimiento': req.body.emisor.codigoEstablecimiento,
'NITEmisor': req.body.emisor.nit,
'NombreComercial': req.body.emisor.NombreComercial,
'NombreEmisor': req.body.emisor.nombreEmisor
},
'dte:DireccionEmisor': {
'dte:Direccion': req.body.emisor.direccionEmisor.direccion,
'dte:CodigoPostal': req.body.emisor.direccionEmisor.codigoPostal,
'dte:Municipio': req.body.emisor.direccionEmisor.municipio,
'dte:Departamento': req.body.emisor.direccionEmisor.departamento,
'dte:Pais': req.body.emisor.direccionEmisor.pais
}
},
'dte:Receptor': {
$: {
'CorreoReceptor': req.body.receptor.correoReceptor,
'IDReceptor': req.body.receptor.idReceptor,
'NombreReceptor': req.body.receptor.nombreReceptor
},
'dte:DireccionReceptor': {
'dte:Direccion': req.body.receptor.direccionReceptor.direccion,
'dte:CodigoPostal': req.body.receptor.direccionReceptor.codigoPostal,
'dte:Municipio': req.body.receptor.direccionReceptor.municipio,
'dte:Departamento': req.body.receptor.direccionReceptor.departamento,
'dte:Pais': req.body.receptor.direccionReceptor.pais
}
},
'dte:Items': {
'dte:Item':[]
},
'dte:Totales': {
'dte:TotalImpuestos': {
'dte:TotalImpuesto': {
$: {
'NombreCorto': req.body.totales.totalImpuestos.nombreCorto,
'TotalMontoImpuesto': req.body.totales.totalImpuestos.totalMontoImpuesto
}
}
},
'dte:GranTotal': req.body.totales.granTotal
},
'dte:Complementos': {
'dte:Complemento': {
$: {
'IDComplemento': "1",
'NombreComplemento': "NOTA CREDITO",
'URIComplemento': "http://www.sat.gob.gt/face2/ComplementoReferenciaNota/0.1.0"
},
'cno:ReferenciasNota': {
$: {
'xmlns:cno': "http://www.sat.gob.gt/face2/ComplementoReferenciaNota/0.1.0",
'FechaEmisionDocumentoOrigen': req.body.complementos.fechaEmisionDocumentoOrigen,
'MotivoAjuste': req.body.complementos.motivoAjuste,
'NumeroAutorizacionDocumentoOrigen': req.body.complementos.numeroAutorizacionDocumentoOrigen,
'Version': "1"
}
}
}
}
}
}
}
}
};
var arrItems = obj['dte:GTDocumento']['dte:SAT']['dte:DTE']['dte:DatosEmision']['dte:Items']['dte:Item'] = [];
for(var key in req.body.items){
let item = req.body.items[key];
arrItems.push({
$: {
"BienOServicio": item.bienOServicio,
"NumeroLinea": key
},
"dte:Cantidad": item.cantidad,
"dte:UnidadMedida": item.unidadMedida,
"dte:Descripcion": item.descripcion,
"dte:PrecioUnitario": item.precioUnitario,
"dte:Precio": item.precio,
"dte:Descuento": item.descuento,
"dte:Impuestos": {
"dte:Impuesto": {
"dte:NombreCorto": item.impuestos.nombreCorto,
"dte:CodigoUnidadGravable": item.impuestos.codigoUnidadGravable,
"dte:MontoGravable": item.impuestos.montoGravable,
"dte:MontoImpuesto": item.impuestos.montoImpuesto
}
},
"dte:Total": item.total
});
}
const builder = new xml2js.Builder();
const xml = builder.buildObject(obj);
let firmaDocumento = await Main.firma(xml);
if(firmaDocumento.status === true){
let registraDocumento = await Main.registra(unescape(firmaDocumento.data.FirmaDocumentoResponse.xml_dte));
if(registraDocumento.status === true){
let xmlResponse = registraDocumento.data.RegistraDocumentoXMLResponse.xml_dte;
let result = await xml2js.parseStringPromise(xmlResponse, { mergeAttrs: true, attrkey: "attr" });
return {
status: true,
message: 'documento procesador correctamente',
data: {
response: result,
tipo_respuesta: registraDocumento.data.RegistraDocumentoXMLResponse.tipo_respuesta,
uuid: registraDocumento.data.RegistraDocumentoXMLResponse.uuid
}
}
}
else{
return {
status: true,
message: 'error al registrar documento',
data: registraDocumento
}
}
}else{
return {
status: true,
message: 'error al firmar documento',
data: firmaDocumento
}
}
}
// proceso de nota de abono
static async notaAbono(req, res){
const obj = {
'dte:GTDocumento': {
$:{
'xmlns:dte': "http://www.sat.gob.gt/dte/fel/0.2.0",
'xmlns:xd': "http://www.w3.org/2000/09/xmldsig#",
'Version': "0.1"
},
'dte:SAT': {
$:{
'ClaseDocumento': "dte"
},
'dte:DTE': {
$:{
'ID': "DatosCertificados"
},
'dte:DatosEmision':{
$: {
'ID': "DatosEmision"
},
'dte:DatosGenerales': {
$: {
'CodigoMoneda': "GTQ",
'FechaHoraEmision': req.body.datosGenerales.fechaEmision,
'Tipo': "NABN"
}
},
'dte:Emisor': {
$: {
'AfiliacionIVA': req.body.emisor.afiliacionIVA,
'CodigoEstablecimiento': req.body.emisor.codigoEstablecimiento,
'NITEmisor': req.body.emisor.nit,
'NombreComercial': req.body.emisor.NombreComercial,
'NombreEmisor': req.body.emisor.nombreEmisor
},
'dte:DireccionEmisor': {
'dte:Direccion': req.body.emisor.direccionEmisor.direccion,
'dte:CodigoPostal': req.body.emisor.direccionEmisor.codigoPostal,
'dte:Municipio': req.body.emisor.direccionEmisor.municipio,
'dte:Departamento': req.body.emisor.direccionEmisor.departamento,
'dte:Pais': req.body.emisor.direccionEmisor.pais
}
},
'dte:Receptor': {
$: {
'CorreoReceptor': req.body.receptor.correoReceptor,
'IDReceptor': req.body.receptor.idReceptor,
'NombreReceptor': req.body.receptor.nombreReceptor
},
'dte:DireccionReceptor': {
'dte:Direccion': req.body.receptor.direccionReceptor.direccion,
'dte:CodigoPostal': req.body.receptor.direccionReceptor.codigoPostal,
'dte:Municipio': req.body.receptor.direccionReceptor.municipio,
'dte:Departamento': req.body.receptor.direccionReceptor.departamento,
'dte:Pais': req.body.receptor.direccionReceptor.pais
}
},
'dte:Items': {
'dte:Item':[]
},
'dte:Totales': {
'dte:GranTotal': req.body.totales.granTotal
}
}
}
}
}
};
var arrItems = obj['dte:GTDocumento']['dte:SAT']['dte:DTE']['dte:DatosEmision']['dte:Items']['dte:Item'] = [];
for(var key in req.body.items){
let item = req.body.items[key];
arrItems.push({
$: {
"BienOServicio": item.bienOServicio,
"NumeroLinea": key
},
"dte:Cantidad": item.cantidad,
"dte:UnidadMedida": item.unidadMedida,
"dte:Descripcion": item.descripcion,
"dte:PrecioUnitario": item.precioUnitario,
"dte:Precio": item.precio,
"dte:Descuento": item.descuento,
"dte:Total": item.total
});
}
const builder = new xml2js.Builder();
const xml = builder.buildObject(obj);
let firmaDocumento = await Main.firma(xml);
if(firmaDocumento.status === true){
let registraDocumento = await Main.registra(unescape(firmaDocumento.data.FirmaDocumentoResponse.xml_dte));
if(registraDocumento.status === true){
let xmlResponse = registraDocumento.data.RegistraDocumentoXMLResponse.xml_dte;
let result = await xml2js.parseStringPromise(xmlResponse, { mergeAttrs: true, attrkey: "attr" });
return {
status: true,
message: 'documento procesador correctamente',
data: {
response: result,
tipo_respuesta: registraDocumento.data.RegistraDocumentoXMLResponse.tipo_respuesta,
uuid: registraDocumento.data.RegistraDocumentoXMLResponse.uuid
}
}
}
else{
return {
status: true,
message: 'error al registrar documento',
data: registraDocumento
}
}
}else{
return {
status: true,
message: 'error al firmar documento',
data: firmaDocumento
}
}
}
// proceso de anulacion directa
static async anulacion(req, res){
let fechaHoraAnulacion = new Date();
const obj = {
'ns:GTAnulacionDocumento': {
$:{
'xmlns:ns': "http://www.sat.gob.gt/dte/fel/0.1.0",
'xmlns:xd': "http://www.w3.org/2000/09/xmldsig#",
'Version': "0.1"
},
'ns:SAT': {
'ns:AnulacionDTE': {
$:{
'ID': "DatosCertificados"
},
'ns:DatosGenerales': {
$: {
'ID': "DatosAnulacion",
'NumeroDocumentoAAnular': req.body.datosGenerales.numeroDocumentoAnular,
'NITEmisor': req.body.datosGenerales.nitEmisor,
'IDReceptor': req.body.datosGenerales.idReceptor,
'FechaEmisionDocumentoAnular': req.body.datosGenerales.fechaEmisionDocumentoAnular,
'FechaHoraAnulacion': fechaHoraAnulacion.toISOString(),
'MotivoAnulacion': req.body.datosGenerales.motivoAnulacion
}
}
}
}
}
};
const builder = new xml2js.Builder();
const xml = builder.buildObject(obj);
// console.log(xml);
let firmaDocumento = await Main.firma(xml);
if(firmaDocumento.status === true){
let token = await Main.token();
let xmlResult = await fetch('https://dev2.api.ifacere-fel.com/api/anularDocumentoXML', {
method: 'POST',
headers: {
'Content-Type': 'application/xml;charset=UTF-8',
'Authorization': token.data.token
},
body: `<?xml version='1.0' encoding='UTF-8'?>
<AnulaDocumentoXMLRequest id="B10DC019-A68E-4977-85A8-848F623C518C">
<xml_dte><![CDATA[
`+unescape(firmaDocumento.data.FirmaDocumentoResponse.xml_dte)+`
]]></xml_dte>
</AnulaDocumentoXMLRequest>`
}).then(response => response.text());
let xmlAnula = await xml2js.parseStringPromise(xmlResult, { mergeAttrs: false, attrkey: "attr" });
if(xmlAnula.AnulaDocumentoXMLResponse.tipo_respuesta == 1){
return {
status: false,
message: 'error al anular documento',
data: xmlAnula
};
}else{
let xmlResponse = xmlAnula.AnulaDocumentoXMLResponse.xml_dte;
let result = await xml2js.parseStringPromise(xmlResponse, { mergeAttrs: true, attrkey: "attr" });
return {
status: true,
message: 'documento anulado',
data: {
response: result,
tipo_respuesta: xmlAnula.AnulaDocumentoXMLResponse.tipo_respuesta,
uuid: xmlAnula.AnulaDocumentoXMLResponse.uuid
}
};
}
}else{
return {
status: true,
message: 'error al firmar documento',
data: firmaDocumento
}
}
}
};
return Main;
};<file_sep><?php
require_once __DIR__ . '/../api/FelInvoiceConnect.php';
/**
* registers ajax events and handles requests
* @author <NAME>
*
*/
class FelInvoiceRegisterAjaxOrder {
/**
* registers ajax events
*/
public function registerEvents() {
add_action('wp_ajax_fel_invoice_celeb_mail', array($this, 'sendCelebMail'));
add_action('wp_ajax_fel_invoice_load_dispatchers', array($this, 'loadDispatcherProfile'));
}
/**
* loads available dispatcher profiles from astroweb
*/
public function loadDispatcherProfile() {
$data = $this->getPostData();
$response = array();
$postId = $data['post_id'];
$response['selectedDispatcher'] = get_post_meta($postId, '_fel_invoice_dispatcher', true);
if ($response['selectedDispatcher'] == "") {
$response['selectedDispatcher'] = "auto";
}
$response['selectedDispatcherProduct'] = get_post_meta($postId, '_fel_invoice_dispatcher_product', true);
$handler = new FelInvoicePluginOrders();
$profiles = $handler->getConnect()->getAvailableDispatcherProfiles();
if (is_array($profiles)) {
$response['response'] = "SUCCESS";
$response['items'] = array();
$subarray = array();
$subarray[] = array("value" => "", "text" => "auto");
$response['items'][] = array("value" => "auto", "text" => "auto", "subarray" => $subarray);
foreach ($profiles as $dispatcher) {
$item = array("value" => $dispatcher->name, "text" => $dispatcher->name);
$subarray = array();
foreach ($dispatcher->profiles as $p) {
if ($p->matchId != "") {
$subarray[] = array("value" => $p->matchId, "text" => $p->name);
}
}
if (count($subarray) > 0) {
$item['subarray'] = $subarray;
$response['items'][] = $item;
}
}
}
else {
$response['response'] = "ERROR";
$response['error'] = $profiles;
}
echo json_encode($response);
die();
}
/**
* sends a celebrity notification mail
*/
public function sendCelebMail() {
$data = $this->getPostData();
update_post_meta($data['post_id'], '_fel_invoice_celeb_active', 'yes');
$response = array();
$celebMail = get_option("_fel_invoice_order_celeb_email");
$msg = $data['msg'];
$message = "Promi-Versand für Auftrag ".$data['post_id']."\r\nPromi-Text:\r\n\r\n";
$message .= $data['msg'];
$message .= "\r\n\r\nGesendet von: ".FEL_INVOICE_BASE;
if (wp_mail($celebMail, 'Promi-Versand für Auftrag '.$data['post_id'], $message)) {
$response['response'] = "SUCCESS";
$orderObj = wc_get_order($data['post_id']);
$orderObj->add_order_note("Promi-Versand versendet an ".$celebMail, 0, true);
//update astroweb order
$connect = new FelInvoiceConnect();
$connect->addOrderNote($data['post_id'], $data['msg']);
}
else {
global $ts_mail_errors;
global $phpmailer;
if (!isset($ts_mail_errors)) {
$ts_mail_errors = array();
}
if (isset($phpmailer)) {
$ts_mail_errors[] = $phpmailer->ErrorInfo;
}
$response['error'] = 'E-Mail nicht versendet. ';
if (count($ts_mail_errors) > 0) {
$response['error'] .= var_export($ts_mail_errors, true);
}
else {
$response['error'] .= "Bitte überprüfen Sie Ihre E-Mail-Einstellungen und Server-Logs.";
}
$response['response'] = "ERROR";
}
echo json_encode($response);
die();
}
/**
* gets post data from ajax call
* @return array
*/
private function getPostData() {
$posted_data = isset($_POST) ? $_POST : array();
$file_data = isset($_FILES) ? $_FILES : array();
return array_merge($posted_data, $file_data);
}
/**
* checks whether the given haystack ends witht he given needle
* @param string $haystack
* @param string $needle
* @return boolean
*/
private function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}
/**
* reads uploaded file as base 64
* @param array $obj
* @param string $inputName
* @param string $checkFileExtension
* @return array
*/
private function prepareFileUpload($obj, $inputName='fel_invoice_attachment_file',
$checkFileExtension='.pdf') {
$data = array();
$file = $obj[$inputName];
if ($file != null) {
if ($file['error'] == 0) {
if (!$checkFileExtension || $this->endsWith(strtolower($file["name"]), strtolower($checkFileExtension))) {
$fileName = pathinfo(basename($file["name"]), PATHINFO_FILENAME);
if ($fileName == "") {
$fileName = $file["name"];
}
$data['base64'] = base64_encode(fread(fopen($file["tmp_name"], "rb"), filesize($file["tmp_name"])));
$data['filename'] = $fileName;
$data['name'] = $file["name"];
$data['tmpname'] = $file['tmp_name'];
$data['response'] = "SUCCESS";
return $data;
}
else {
$data['error'] = $file["name"]." doesn't end with $checkFileExtension!";
}
}
else {
$fileErrors = array(
0 => "There is no error, the file uploaded with success.",
1 => "The uploaded file exceeds the upload_max_files in server settings.",
2 => "The uploaded file exceeds the MAX_FILE_SIZE from html form.",
3 => "The uploaded file uploaded only partially.",
4 => "No file was uploaded.",
6 => "Missing a temporary folder.",
7 => "Failed to write file to disk.",
8 => "A PHP extension stoped file to upload.");
if (in_array($file['error'], $fileErrors)) {
$data['error'] = $fileErrors[$file['error']];
}
else {
$data['error'] = 'File not uploaded correctly. Please check your server settings.';
}
}
}
else {
$data['error'] = 'No upload file available. Please check your server settings.';
}
$data['response'] = "ERROR";
return $data;
}
}
|
b3ca189e7bcb8afe52320d7dbd4492c1328da546
|
[
"JavaScript",
"PHP"
] | 14
|
PHP
|
devops-milan/wordpress-fel-invoice-sync
|
cd30bd1094bc817522efe15fdfb8703a0e2b6d8b
|
7f00f90067347a94cffdd56b967e97fb097888cc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.