branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>package cn.et.lesson03.sql;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.et.lesson02.Food;
public interface FoodMapper {
/**
* 根据名称查询所有的菜品信息
* @param foodName
* @return
*/
public List queryFood(String foodName,String price);
}
<file_sep>### set log levels ###
log4j.rootLogger = DEBUG , a
#log4j日志分为5种级别
# debug 调试(开发阶段)
# info 运行信息(测试或者运行阶段)
# warn 警告消息
# error 程序错误消息
# fatal 系统错误消息
# 通过5种级别输出的日志 打印在文件中
# int i=0;
# my.debug("定义了变量i")
# my.info("变量i设置了值10")
# my.warn("警告")
#
# 全局控制机制
# root=info
# 日志级别 fatal>error>warn>info>debug
### 输出到控制台 ###
log4j.appender.a = org.apache.log4j.ConsoleAppender
log4j.appender.a.Target = System.out
log4j.appender.a.layout = org.apache.log4j.PatternLayout
log4j.appender.a.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n<file_sep>package cn.et.lesson05.xml;
import java.io.IOException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import cn.et.lesson05.JavaRedis;
import redis.clients.jedis.Jedis;
public class RedisCache implements Cache {
/**
* ����redis����
*/
Jedis jedis=new Jedis("localhost",6379);
/*
* �����ID
*/
private String cacheId;
public RedisCache(String cacheId){
this.cacheId=cacheId;
}
public void clear() {
// jedis.flushDB();
}
public String getId() {
// TODO Auto-generated method stub
return cacheId;
}
/**
* mybatis�Զ�����getObject����Ƿ��д���
*/
public Object getObject(Object key) {
byte[] bt=jedis.get(JavaRedis.objectToByteArray(key));
try {
if(bt==null){
return null;
}
return JavaRedis.byteArrayToObject(bt);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public ReadWriteLock getReadWriteLock() {
// TODO Auto-generated method stub
return new ReentrantReadWriteLock();
}
public int getSize() {
// TODO Auto-generated method stub
return 0;
}
/*
* mybatis��ȡ����ʱ�����ݿ��ж�ȡ������ ͨ��putObject���õ�������
* */
public void putObject(Object key, Object value) {
//�redis
jedis.set(JavaRedis.objectToByteArray(key), JavaRedis.objectToByteArray(value));
}
/**
* mybatis ������� �Զ��ж��ڴ�ĵĴ�С �����Ƿ�ɾ��ijЩ���ھ�Զ����
*/
public Object removeObject(Object key) {
Object obj=getObject(key);
jedis.del(JavaRedis.objectToByteArray(key));
return obj;
}
}
<file_sep>package cn.et.lesson03.returnMap.xml;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
public class Testxml {
public static SqlSession getSession() throws IOException{
String resource = "cn/et/lesson03/returnMap/xml/mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//工厂类
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session=sqlSessionFactory.openSession();
return session;
}
@Test
public void testsave() throws IOException{
SqlSession session=getSession();
GradeMapper gm=session.getMapper(GradeMapper.class);
List<Grade> list=gm.queryAllGrade();
for(Grade l:list){
System.out.println(l.getGid()+"========"+l.getGname1());
}
System.out.println(list.size());
}
/**
* mybatis懒加载
* 关联的对象是访问其属性是才加载
* @throws IOException
*/
@Test
public void queryStudent() throws IOException{
SqlSession session=getSession();
StudentMapper gm=session.getMapper(StudentMapper.class);
Student s=gm.queryStudent("1");
System.out.println(s.getGrade().getGname1());
// System.out.println(s.getSname()+"="+s.getGrade().getGname1());
}
@Test
public void oneToMany() throws IOException{
SqlSession session=getSession();
GradeMapper gm=session.getMapper(GradeMapper.class);
Grade g=gm.queryGrade("3");
for(Student s:g.getStudentList()){
System.out.println(s.getSname());
}
System.out.println(g.getStudentList().size());
}
}
<file_sep>package cn.et.lesson02.xml;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.et.lesson02.Food;
public interface FoodMapper {
/**
* 根据名称查询所有的菜品信息
* @param foodName
* @return
*/
public List queryFood(String foodName,String price);
public List queryFoodByFoodName(@Param("foodName") String foodName);
/**
* 根据id删除
* @param foodId
*/
public void deleteFood(String foodId);
/**
* 插入food
*/
public void saveFood(Food food);
}
| b13bde4f5f6cb06edde26acb59c3b093b279da77 | [
"Java",
"Java Properties"
] | 5 | Java | RayaCL/myBatisLesson | a4d2afbc8ac139931772c9fd572c687279054521 | e580a9a749dee57daef5bc9bcc2a8f9b0b40e03c |
refs/heads/master | <file_sep>asgiref==3.2.3
certifi==2019.11.28
chardet==3.0.4
dj-static==0.0.6
Django==3.0.1
gunicorn==20.0.4
idna==2.8
pytz==2019.3
requests==2.22.0
sqlparse==0.3.0
static3==0.7.0
urllib3==1.25.7
<file_sep># weatherapp
This is a weather app.
All package needed is in requirements.txt.
# Operate in action


<file_sep># Generated by Django 3.0.1 on 2019-12-29 15:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('weather', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='city',
old_name='nmae',
new_name='name',
),
]
| e269580bb11ec6d3bccf1cc9d7e59bded7b0bc8f | [
"Markdown",
"Python",
"Text"
] | 3 | Text | daekony/weatherapp | ebe4802bca2e08c04dfb2a88f348cefb70f10573 | b64f450c756da57f5ca57e05e3e39587472885ca |
refs/heads/master | <file_sep>#[macro_use]
extern crate kserd_derive;
use kserd::*;
#[test]
fn struct_with_fields() {
#[derive(AsKserd)]
struct Simple {
a: u8,
b: String,
}
let simple = Simple {
a: 100,
b: "Hello, world!".to_string(),
};
let kserd = simple.as_kserd();
println!(
"{}",
kserd.as_str_with_config(format::FormattingConfig::default())
);
assert_eq!(kserd.id(), Some("Simple"));
let map = match kserd.val() {
Value::Cntr(map) => map,
_ => unreachable!(),
};
assert_eq!(map.get(&("a".into())), Some(&(100u64.as_kserd())));
assert_eq!(map.get(&("b".into())), Some(&("Hello, world!".as_kserd())));
}
#[test]
fn unit_struct() {
#[derive(AsKserd)]
struct AUnitStruct;
let val = AUnitStruct;
let kserd = val.as_kserd();
println!(
"{}",
kserd.as_str_with_config(format::FormattingConfig::default())
);
assert_eq!(kserd.id(), Some("AUnitStruct"));
assert_eq!(kserd.val(), &Value::Unit);
}
<file_sep>[package]
name = "kserd_derive"
version = "0.1.0"
authors = ["kurt <<EMAIL>>"]
edition = "2018"
description = "Proc macro for Kurt's Self-Explanatory Rust Data"
documentation = "https://docs.rs/kserd_derive/"
homepage = "https://github.com/kurtlawrence/kserd_derive"
repository = "https://github.com/kurtlawrence/kserd_derive"
readme = "README.md"
categories = [ "data-structures", "encoding", "parsing" ]
license = "MIT"
[badges]
travis-ci = { repository = "kurtlawrence/kserd_derive" }
codecov = { repository = "kurtlawrence/kserd_derive" }
[lib]
name = "kserd_derive"
proc-macro = true
[dependencies]
proc-macro2 = { version = "1.0", default-features = false }
quote = { version = "1.0", default-features = false, features = ["proc-macro"] }
syn = { version = "1.0", default-features = false, features = ["derive", "parsing",
"printing", "proc-macro", "visit"] }
[dev-dependencies]
kserd = { version = "0.1", default-features = false }
<file_sep>//! [](https://travis-ci.com/kurtlawrence/kserd_derive)
//! [](https://crates.io/crates/kserd_derive)
//! [](https://docs.rs/kserd_derive)
//! [](https://codecov.io/gh/kurtlawrence/kserd_derive)
//!
//! Proc macro derive for **K**urt's **S**elf **E**xplanatory **R**ust **D**ata.
//!
//! See the [rs docs.](https://docs.rs/kserd_derive/)
//! Look at progress and contribute on [github.](https://github.com/kurtlawrence/kserd_derive)
//!
//! The main source of information is at [kurtlawrence/kserd](https://github.com/kurtlawrence/kserd).
//!
//! ## IMPORTANT - WIP
//!
//! `kserd_derive` is a work in progress and not currently usable but is actively being developed.
extern crate proc_macro;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{
parse_macro_input, parse_quote, Data, DeriveInput, Fields, GenericParam, Generics, Ident, Index,
};
#[proc_macro_derive(AsKserd)]
pub fn derive_to_kserd(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
// Parse the input tokens into a syntax tree.
let input = parse_macro_input!(input as DeriveInput);
// Used in the quasi-quotation below as `#name`.
let name = input.ident;
// Add a bound `T: AsKserd` to every type parameter T.
let generics = add_trait_bounds(input.generics);
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
// Generate an expression call as_kserd() of each field.
let kserd_expr = to_kserd_expr(&input.data, &name);
let expanded = quote! {
// The generated impl.
impl #impl_generics kserd::AsKserd for #name #ty_generics #where_clause {
fn as_kserd<'a>(&'a self) -> kserd::Kserd<'a> {
#kserd_expr
}
}
};
// Hand the output tokens back to the compiler.
proc_macro::TokenStream::from(expanded)
}
/// Add a bound `T: AsKserd` to every type parameter T.
fn add_trait_bounds(mut generics: Generics) -> Generics {
for param in &mut generics.params {
if let GenericParam::Type(ref mut type_param) = *param {
type_param.bounds.push(parse_quote!(kserd::AsKserd));
}
}
generics
}
/// Generate an expression call as_kserd() of each field.
fn to_kserd_expr(data: &Data, input_name: &Ident) -> TokenStream {
match *data {
Data::Struct(ref data) => {
match data.fields {
Fields::Named(ref fields) => {
let names = fields.named.iter().map(|f| {
let name = &f.ident;
quote! { stringify!(#name).into() }
});
let values = fields.named.iter().map(|f| {
let name = &f.ident;
quote_spanned! { f.span() =>
self.#name.as_kserd()
}
});
let tokens = quote! {
let mut map: BTreeMap<kserd::KserdStr<'a>, kserd::Kserd<'a>> = BTreeMap::new();
#(map.insert(#names, #values);)*
kserd::Kserd::with_identity(stringify!(#input_name), Value::Cntr(map))
};
tokens
}
Fields::Unnamed(ref fields) => {
unimplemented!();
// // Expands to an expression like
// //
// // 0 + self.0.heap_size() + self.1.heap_size() + self.2.heap_size()
// let recurse = fields.unnamed.iter().enumerate().map(|(i, f)| {
// let index = Index::from(i);
// quote_spanned! {f.span()=>
// heapsize::HeapSize::heap_size_of_children(&self.#index)
// }
// });
// quote! {
// 0 #(+ #recurse)*
// }
}
Fields::Unit => {
unimplemented!();
// quote! {
// kserd::Kserd::with_identity(stringify!(#input_name), Value::Unit)
// }
}
}
}
Data::Enum(_) | Data::Union(_) => unimplemented!(),
}
}
<file_sep>[](https://travis-ci.com/kurtlawrence/kserd_derive)
[](https://crates.io/crates/kserd_derive)
[](https://docs.rs/kserd_derive)
[](https://codecov.io/gh/kurtlawrence/kserd_derive)
Proc macro derive for **K**urt's **S**elf **E**xplanatory **R**ust **D**ata.
See the [rs docs.](https://docs.rs/kserd_derive/)
Look at progress and contribute on [github.](https://github.com/kurtlawrence/kserd_derive)
The main source of information is at [kurtlawrence/kserd](https://github.com/kurtlawrence/kserd).
## IMPORTANT - WIP
`kserd_derive` is a work in progress and not currently usable but is actively being developed.
| 4423017de1cc6a95917d4e21b7ba63f05f904c4a | [
"TOML",
"Rust",
"Markdown"
] | 4 | Rust | kurtlawrence/kserd_derive | f9bf08b0d7b8f9453577341ae454366ef38dadc6 | f5d03b54e4c141cac7ea5071473a295a18decff1 |
refs/heads/master | <file_sep>//
// HomeViewController.swift
// NavigatingHomeScreenToLogin
//
// Created by <NAME> on 15/02/20.
// Copyright © 2020 Vali. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
lazy var sceneDelegate = self.view.window?.windowScene?.delegate as! SceneDelegate
@IBAction func tapOnLogOut(_ sender: Any) {
if self.sceneDelegate.loginNavigationController != nil{
self.sceneDelegate.window?.rootViewController = nil
self.sceneDelegate.window?.rootViewController = self.sceneDelegate.loginNavigationController
UserDefaults.standard.set(false, forKey: "Login")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
*/
}
| feb4a03d1a6fadf38548946cec540ebff35ab532 | [
"Swift"
] | 1 | Swift | skvalibabu/NavigateViewControllers | 33d4ca8242d173e3811f3dc0ab7cce62822ef9a0 | ed7935f662cc7837e0de291a7d85d4359e9e3ce7 |
refs/heads/master | <repo_name>passakornC/io-scouter<file_sep>/src/app/components/input/input.component.ts
import {Component, OnInit, Output} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {HttpService} from '../../services/http.service';
import {EventEmitter} from 'events';
import {Observable} from 'rxjs';
import {MessageService} from '../../services/message.service';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
constructor(private fb: FormBuilder,
private httpService: HttpService,
private messageService: MessageService) {
}
form = this.fb.group({
textInput: ['']
});
ngOnInit(): void {
}
check(): void {
const textInput = this.form.controls.textInput.value;
this.httpService.getIoProb(textInput).subscribe(response => {
this.messageService.announceMessage(response);
});
}
}
<file_sep>/src/app/components/output/output.component.ts
import {Component, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';
import {MessageService} from '../../services/message.service';
@Component({
selector: 'app-output',
templateUrl: './output.component.html',
styleUrls: ['./output.component.css']
})
export class OutputComponent implements OnInit, OnChanges {
data: any;
options: any;
ngOnChanges(changes: SimpleChanges): void {
console.log('change');
}
constructor(private messageService: MessageService) {
// initial chart
this.data = {
datasets: [
{
label: 'Percent of IO Probability Score',
backgroundColor: '#42A5F5',
borderColor: '#1E88E5',
barPercentage: 0.3,
data: [50]
}
]
};
this.options = {
legend: {
position: 'bottom'
}
};
}
ngOnInit(): void {
// update value
this.messageService.messageAnnounced$.subscribe(message => {
this.data = {
datasets: [
{
label: 'Percent of IO Probability Score',
backgroundColor: '#42A5F5',
borderColor: '#1E88E5',
barPercentage: 0.3,
data: [message.io_prob * 100]
}
]
};
});
}
}
<file_sep>/src/app/components/components.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {InputComponent} from './input/input.component';
import {HeaderComponent} from './header/header.component';
import {InputTextModule} from 'primeng/inputtext';
import {ButtonModule} from 'primeng/button';
import {ReactiveFormsModule} from '@angular/forms';
import { OutputComponent } from './output/output.component';
import {ChartModule} from 'primeng/chart';
@NgModule({
declarations: [
InputComponent,
HeaderComponent,
OutputComponent
],
exports: [
InputComponent,
HeaderComponent,
OutputComponent
],
imports: [
CommonModule,
InputTextModule,
ButtonModule,
ReactiveFormsModule,
ChartModule
]
})
export class ComponentsModule {
}
<file_sep>/src/app/pages/input-page/input-page.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {InputPageRoutingModule} from './input-page-routing.module';
import {InputPageComponent} from './input-page/input-page.component';
import {CardModule} from 'primeng/card';
import {PagesModule} from '../pages.module';
import {ComponentsModule} from '../../components/components.module';
@NgModule({
declarations: [
InputPageComponent
],
imports: [
CommonModule,
InputPageRoutingModule,
CardModule,
PagesModule,
ComponentsModule
]
})
export class InputPageModule {
}
<file_sep>/src/app/services/message.service.ts
import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessageService {
private messageSource = new BehaviorSubject<any>([]);
public messageAnnounced$ = this.messageSource.asObservable();
constructor() { }
public announceMessage(value: any): void {
this.messageSource.next(value);
}
}
| f01f88c0451678d1b8e035343e91e254dce3a866 | [
"TypeScript"
] | 5 | TypeScript | passakornC/io-scouter | cd4f15dbe0dbfb91a7f6115b60961a89eec5303d | 1e1c1623b07f108326ac9932922182aed712ec31 |
refs/heads/master | <file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts "Cleaning database..."
puts "Destroying users..."
Message.destroy_all
puts "Destroying users"
User.destroy_all
puts "Destroying channels"
Channel.destroy_all
puts "Creating base channels..."
channels = [
{name: "general"},
{name: "random"},
{name: "react"}
]
channels.each do |channel|
Channel.create channel
end
puts "Created channels!"
puts "Creating users...."
users = [
{email: "<EMAIL>", password: "<PASSWORD>"},
{email: "<EMAIL>", password: "<PASSWORD>"}
]
users.each do |user|
User.create user
end
puts "Created users!"
puts "Creating messages"
messages = [
{content: "hi", user: User.first, channel: Channel.first},
{content: "yo", user: User.first, channel: Channel.first},
{content: "no way!", user: User.first, channel: Channel.first},
{content: "how are things?", user: User.first, channel: Channel.first},
{content: "wasuppppp", user: User.first, channel: Channel.first}
]
messages.each do |message|
Message.create message
end
puts "Created messages!"
puts "Finished."
<file_sep>class Api::V1::MessagesController < ApplicationController
before_action :find_channel
def index
@messages = Message.where(channel: @channel)
render json: @messages # see Message.as_json method
end
def create
message = @channel.messages.build(content: params[:content])
message.user = current_user
message.save
render json: message # see Message.as_json method
end
private
def find_channel
@channel = Channel.find_by(name: params[:channel_id])
end
end
<file_sep>import { FETCH_MESSAGES, MESSAGE_POSTED, CHANNEL_SELECTED } from '../actions';
// export function(state = null, action) {
// switch (action.type) {
// case FETCH_MESSAGES: {
// return action.payload.messages;
// }
// case MESSAGE_POSTED: {
// const copiedState = state.slice(0);
// copiedState.push(action.payload);
// return copiedState;
// }
// case CHANNEL_SELECTED: {
// return []; // Channel has changed. Clearing view.
// }
// default:
// return state;
// }
// }
/* eslint no-bitwise:off */
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { selectChannel, fetchMessages } from '../actions/index';
import { Link } from 'react-router-dom';
class ChannelList extends Component {
componentWillReceiveProps(nextProps) {
if (nextProps.selectedChannel !== this.props.selectedChannel) {
this.props.fetchMessages(nextProps.selectedChannel);
}
}
// handleClick = (channel) => {
// this.props.selectChannel(channel);
// }
renderChannel = (channel) => {
return (
<Link to={`/channels/${channel}`} key={channel.id}>
<li
key={channel}
className={channel === this.props.selectedChannel ? 'active' : null}
role="presentation"
>
#{channel}
</li>
</Link>
);
}
render() {
return (
<div className="channels-container">
<span>Redux Chat</span>
<ul>
{this.props.channels.map(this.renderChannel)}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return {
channels: state.channels
// selectedChannel: state.selectedChannel not needed anymore as it's being taken from the route
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ selectChannel, fetchMessages }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ChannelList);
| 79fd2abade8c4fa11e714b9999a3403902046fc1 | [
"JavaScript",
"Ruby"
] | 3 | Ruby | kierand0yle/chat-rails-redux | 7baeae563a160cb50fad61a289af7209b7ad2969 | 8490d2b5e99365ed2d49a463e5e3ae58b47d6e1a |
refs/heads/master | <repo_name>chaolou/kubernetes<file_sep>/pkg/apiserver/authz.go
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiserver
import (
"errors"
"fmt"
"os"
"sync"
"time"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/auth/authorizer"
"k8s.io/kubernetes/pkg/auth/authorizer/abac"
"k8s.io/kubernetes/pkg/auth/authorizer/union"
)
// Attributes implements authorizer.Attributes interface.
type Attributes struct {
// TODO: add fields and methods when authorizer.Attributes is completed.
}
// alwaysAllowAuthorizer is an implementation of authorizer.Attributes
// which always says yes to an authorization request.
// It is useful in tests and when using kubernetes in an open manner.
type alwaysAllowAuthorizer struct{}
func (alwaysAllowAuthorizer) Authorize(a authorizer.Attributes) (err error) {
return nil
}
func NewAlwaysAllowAuthorizer() authorizer.Authorizer {
return new(alwaysAllowAuthorizer)
}
// alwaysDenyAuthorizer is an implementation of authorizer.Attributes
// which always says no to an authorization request.
// It is useful in unit tests to force an operation to be forbidden.
type alwaysDenyAuthorizer struct{}
func (alwaysDenyAuthorizer) Authorize(a authorizer.Attributes) (err error) {
return errors.New("Everything is forbidden.")
}
func NewAlwaysDenyAuthorizer() authorizer.Authorizer {
return new(alwaysDenyAuthorizer)
}
const (
ModeAlwaysAllow string = "AlwaysAllow"
ModeAlwaysDeny string = "AlwaysDeny"
ModeABAC string = "ABAC"
)
// Keep this list in sync with constant list above.
var AuthorizationModeChoices = []string{ModeAlwaysAllow, ModeAlwaysDeny, ModeABAC}
// NewAuthorizerFromAuthorizationConfig returns the right sort of union of multiple authorizer.Authorizer objects
// based on the authorizationMode or an error. authorizationMode should be a comma separated values
// of AuthorizationModeChoices.
func NewAuthorizerFromAuthorizationConfig(authorizationModes []string, authorizationPolicyFile string) (authorizer.Authorizer, error) {
if len(authorizationModes) == 0 {
return nil, errors.New("Atleast one authorization mode should be passed")
}
var authorizers []authorizer.Authorizer
authorizerMap := make(map[string]bool)
for _, authorizationMode := range authorizationModes {
if authorizerMap[authorizationMode] {
return nil, fmt.Errorf("Authorization mode %s specified more than once", authorizationMode)
}
// Keep cases in sync with constant list above.
switch authorizationMode {
case ModeAlwaysAllow:
authorizers = append(authorizers, NewAlwaysAllowAuthorizer())
case ModeAlwaysDeny:
authorizers = append(authorizers, NewAlwaysDenyAuthorizer())
case ModeABAC:
if authorizationPolicyFile == "" {
return nil, errors.New("ABAC's authorization policy file not passed")
}
abacAuthorizer, err := abac.NewFromFile(authorizationPolicyFile)
authorizerLock := &abac.PolicyAuthorizer{PL: &abacAuthorizer, Lock: &sync.RWMutex{}}
go checkAndReloadPolicyFile(authorizerLock, authorizationPolicyFile)
if err != nil {
return nil, err
}
authorizers = append(authorizers, authorizerLock)
default:
return nil, fmt.Errorf("Unknown authorization mode %s specified", authorizationMode)
}
authorizerMap[authorizationMode] = true
}
if !authorizerMap[ModeABAC] && authorizationPolicyFile != "" {
return nil, errors.New("Cannot specify --authorization-policy-file without mode ABAC")
}
return union.New(authorizers...), nil
}
func checkAndReloadPolicyFile(policyAuthz *abac.PolicyAuthorizer, file string) {
lastModifyTime := time.Now()
for {
func() {
defer func() {
if x := recover(); x != nil {
glog.Errorf("APIServer panic'd on checkAndReloadPolicyFile: %s, err: %v", file, x)
}
}()
//var info os.FileInfo
info, err := os.Stat(file)
if err != nil {
glog.Errorf("Stat authorizationPolicyFile: %s fail, err: %v, will retry to reload later", file, err)
return
}
if info.ModTime().After(lastModifyTime) {
lastModifyTime = info.ModTime()
newPolicyList, err := abac.NewFromFile(file)
if err != nil { // file format not correct
glog.Errorf("Stat authorizationPolicyFile: %s fail, err: %v, will retry to reload later", file, err)
return
}
glog.Infof("authorizationPolicyFile: %s is modified, reload finished, number of policy lines change from %d to %d", file, len(*policyAuthz.PL), len(newPolicyList))
policyAuthz.Lock.Lock()
*(policyAuthz.PL) = newPolicyList
policyAuthz.Lock.Unlock()
}
}()
time.Sleep(5 * time.Second)
}
}
| ae1d36833af20aa6095273eb1d397b7879febdd2 | [
"Go"
] | 1 | Go | chaolou/kubernetes | bdd7bbb0ff361178a608de6b3b3daca74a905ac9 | fb30a018921d9ab1511d32fa4c38d7b96acb606a |
refs/heads/master | <file_sep>/**
* Created by J.R(<EMAIL>)
* Created Date : 2020/03/17
*/
#include <unistd.h>
int main() {
for (;;)
getppid();
}<file_sep># linux-structure
도서 실습과 그림으로 배우는 리눅스 구조 실습
## Chapter 2
### C언어 실행 파일에서 시스템 콜 확인
```bash
$ strace -o hello.log ./hello
$ cat hello.log
```
### CPU 의 사용자 모드 점유 / 커널 모드 점유 확인하기
1초 단위로 측정 : `sar -P ALL 1`
<b>%user</b> 가 사용자 모드, <b>%system</b>이 커널 모드
무한정 도는 loop 프로그램으로 사용자 모드 점유 확인해보기
```bash
$ ./loop & # '&'는background 실행을 의미
$ sar -P ALL 1
$ ps -ef | grep loop # loop의 프로세스 ID(PID)를 찾기
$ kill [loop의 PID] # 찾은 PID를 통해서 프로세스 종료
```
시스템 콜(커널 모드 사용)을 하는 프로그램으로 커널 모드 점유 확인해보기
```bash
$ ./ppidloop &
$ sar -P ALL 1
$ ps -ef | grep ppidloop # ppidloop의 프로세스 ID(PID)를 찾기
$ kill [ppidloop의 PID] # 찾은 PID를 통해서 프로세스 종료
```
strace 로 확인한 프로세스 내의 시스템 콜에서 소요된 시간 확인하기
```bash
$ strace -T -o hello.log ./hello
$ cat hello.log
```
<b>ldd</b> : 프로그램이 어떠한 라이브러리를 링크하고 있는지 확인하기
echo 프로그램이 링크하고 있는 라이브러리 확인 : `$ ldd /bin/echo`
ppidloop 프로그램이 링크하고 있는 라이브러리 확인 : `$ ldd ppidloop`
## Chapter 3
리눅스에서 프로세스 생성 방법은 fork() 함수와 execve() 함수를 사용하여 만들 수 있다.
### fork() 함수
목적 : 같은 프로그램의 처리를 여러 개의 프로세스가 나눠서 처리하도록 한다.
fork() 함수를 실행하면 실행한 프로세스와 함께 새로운 프로세스 1개가 생성된다.
* 부모 프로세스 : 생성 전의 프로세스
* 자식 프로세스 : 새롭게 생성된 프로세스
리턴 값
* 부모 프로세스 : 자식 프로세스의 PID
* 자식 프로세스 : 0
### execve() 함수
목적 : 전혀 다른 프로그램을 실행할 때 사용
<file_sep>cmake_minimum_required(VERSION 3.15)
project(linux_structure C)
set(CMAKE_C_STANDARD 99)
## Chapter 2
add_executable(hello chapter2/hello.c)
add_executable(loop chapter2/loop.c)
add_executable(ppidloop chapter2/ppidloop.c)
## Chapter 3
add_executable(fork chapter3/fork.c)
add_executable(fork_and_exec chapter3/fork_and_exec.c)<file_sep>/**
* Created by J.R(<EMAIL>)
* Created Date : 2020/03/17
*/
int main() {
for(;;)
;
} | 4e23c120f690c6b0e9f06b88d18797b42474a83a | [
"Markdown",
"C",
"CMake"
] | 4 | C | JuJin1324/linux_structure | eba65e6abd9b2c44fdf577392a6aea5eb798f6d8 | 510ea9e64ccf02fef13c7e1044941eec128d62b6 |
refs/heads/master | <repo_name>Maxim-us/MxLivingLinks<file_sep>/email.php
<?php include_once( 'inc/header.php' ); ?>
<div class="container">
<div class="row">
<h1 class="text-center">Email</h1>
<div class="col-md-2">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error, tempore ea quia veritatis! Esse ut saepe tempore dolores id, eveniet, vel assumenda incidunt ducimus, eum velit rerum. Pariatur, atque quis!
</div>
<div class="col-md-10">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae eos aliquam ullam excepturi quam, cumque laborum assumenda earum pariatur suscipit omnis non voluptate alias hic, expedita ducimus, consectetur labore nisi.
</div>
</div>
</div>
<?php include_once( 'inc/footer.php' ); ?><file_sep>/README.txt
MxLivingLinks - плагин на jQuery, делает простой переход по ссылке более ярким.
ОПИСАНИЕ:
Есть 7 режимов перехода по ссылке:
1. defaultType – при переходе происходит плавное затухание страницы;
2. destroyBlocks – эффект сломанной странице при клике на ссылку;
3. drawBodyTopType – тело сайта уезжает вверх;
4. drawBodyBottomType – тело сайта уезжает вниз;
5. drawBodyLeftType – тело сайта уезжает влево;
6. drawBodyRightType – тело сайта уезжает вправо;
7. randomType – в случайном порядке плагин сам выбирает тип перехода.
ПОДКЛЮЧЕНИЕ:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="js/MxLivingLinks.js?v=1"></script>
<script>
$( document ).ready( function(){
$( window ).MxLivingLinks();
} );
</script>
НАСТРОЙКА:
<script>
$( document ).ready( function(){
$( window ).MxLivingLinks( {
speedDelay: 1000, // скорость анимации
excludeElements: [ // ссылки, которые плагин игнорирует
'.disabled',
'.dropdown-toggle'
],
typeAnimate: 'randomType', // тип перехода по ссылке
endColor: '#ddd' // цвет затухающего фона при переходе по ссылке
} );
} );
</script>
<file_sep>/js/MxLivingLinks.js
;( function(){
$.defaultSett = {
speedDelay: 600,
/* excluded from the set of elements */
excludeElements: [
'.dropdown-toggle'
],
/* type animation */
typeAnimate: 'defaultType', // Attenuation
/*
* 'destroyBlocks' - Destruction
* 'drawBodyTopType' - Move up
* 'drawBodyBottomType' - Move down
* 'drawBodyLeftType' - Move left
* 'drawBodyRightType' - Move right
* 'randomType' - Random type
*
*/
/* background color in the transition */
endColor: '#333'
};
$.fn.MxLivingLinks = function( params ){
var settings = $.extend( {}, $.defaultSett, params );
LivingLinks( this, settings );
};
function LivingLinks( root, settings ){
$( 'body' ).css( { 'opacity': '0' } );
$( 'body' ).animate( { 'opacity': '1' },settings.speedDelay );
$( 'a' ).each( function(){
$( this ).attr( 'onclick', 'return false' );
} );
$.each( settings.excludeElements, function( index, value ){
$( 'a' ).each( function(){
if( $( this ).is( value ) ){
$( this ).attr( 'data-mx-exclude', 'mxExclude' );
}
} );
} );
$( 'a' ).on( 'click', function(){
var thisLink = $( this ).attr( 'data-mx-exclude' );
if( thisLink !== 'mxExclude' ){
var thisHref = $( this ).attr( 'href' ),
speedDelay = settings.speedDelay,
endColor = settings.endColor;
switch( settings.typeAnimate ){
case 'defaultType':
defaultType( speedDelay, thisHref );
break;
case 'destroyBlocks':
destroyBlocks( speedDelay, thisHref );
break;
case 'drawBodyTopType':
drawBodyTopType( endColor, speedDelay, thisHref );
break;
case 'drawBodyBottomType':
drawBodyBottomType( endColor, speedDelay, thisHref );
break;
case 'drawBodyLeftType':
drawBodyLeftType( endColor, speedDelay, thisHref );
break;
case 'drawBodyRightType':
drawBodyRightType( endColor, speedDelay, thisHref );
break;
case 'randomType':
randomType( endColor, speedDelay, thisHref );
break;
default:
defaultType( speedDelay, thisHref );
//alert( 'Type undefined!' );
}
}
} );
}
} )( jQuery );
/******************* Function ***********************/
function defaultType( speedDelay, thisHref ){
$( 'body' ).animate( { 'opacity': '0' },speedDelay );
setTimeout( function(){
window.location.href = thisHref;
},speedDelay );
}
function destroyBlocks( speedDelay, thisHref ){
$( 'div' ).each( function(){
thisOffTop = $( this ).position().top;
thisOffLeft = $( this ).position().left;
$( this ).css( { 'top': thisOffTop + 'px', 'left': thisOffLeft + 'px' } );
} );
$( 'div' ).each( function(){
$( this ).css( 'position', 'fixed' );
$( this ).animate( { 'top': '-100', 'left': '-200px' },speedDelay );
} );
setTimeout( function(){
window.location.href = thisHref;
},speedDelay );
}
function drawBodyTopType( endColor, speedDelay, thisHref ){
$( 'html' ).animate( { backgroundColor: endColor },speedDelay );
var hBody = $( 'body' ).height();
if( hBody <= 600 ){
hBody = 600;
}
$( 'body' ).css( { 'position': 'absolute', 'width': '100%' } );
$( 'body' ).animate( { 'top': '-' + hBody + 'px' },speedDelay );
setTimeout( function(){
window.location.href = thisHref;
},speedDelay );
}
function drawBodyBottomType( endColor, speedDelay, thisHref ){
$( 'html' ).css( { 'overflow': 'hidden' } );
$( 'html' ).animate( { backgroundColor: endColor },speedDelay );
var hBody = $( 'body' ).height();
if( hBody <= 600 ){
hBody = 600;
}
$( 'body' ).css( { 'position': 'absolute', 'width': '100%' } );
$( 'body' ).animate( { 'top': hBody + hBody + 'px' },speedDelay );
setTimeout( function(){
window.location.href = thisHref;
},speedDelay );
}
function drawBodyLeftType( endColor, speedDelay, thisHref ){
$( 'html' ).css( { 'overflow': 'hidden' } );
$( 'html' ).animate( { backgroundColor: endColor },speedDelay );
var hBody = $( 'body' ).height();
if( hBody <= 600 ){
hBody = 600;
}
$( 'body' ).css( { 'position': 'absolute', 'width': '100%' } );
$( 'body' ).animate( { 'right': hBody + hBody + 'px' },speedDelay );
setTimeout( function(){
window.location.href = thisHref;
},speedDelay );
}
function drawBodyRightType( endColor, speedDelay, thisHref ){
$( 'html' ).css( { 'overflow': 'hidden' } );
$( 'html' ).animate( { backgroundColor: endColor },speedDelay );
var hBody = $( 'body' ).height();
if( hBody <= 600 ){
hBody = 600;
}
$( 'body' ).css( { 'position': 'absolute', 'width': '100%' } );
$( 'body' ).animate( { 'left': hBody + hBody + 'px' },speedDelay );
setTimeout( function(){
window.location.href = thisHref;
},speedDelay );
}
function RandomNumber( from, to ){
return Math.floor( ( Math.random() * ( to - from + 1 ) ) + from );
}
function randomType( endColor, speedDelay, thisHref ){
switch( RandomNumber( 0, 5 ) ){
case 0:
defaultType( speedDelay, thisHref );
break;
case 1:
destroyBlocks( speedDelay, thisHref );
break;
case 2:
drawBodyTopType( endColor, speedDelay, thisHref );
break;
case 3:
drawBodyBottomType( endColor, speedDelay, thisHref );
break;
case 4:
drawBodyLeftType( endColor, speedDelay, thisHref );
break;
case 5:
drawBodyRightType( endColor, speedDelay, thisHref );
break;
}
}<file_sep>/inc/footer.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/MxLivingLinks.js?v=<?php echo time();?>"></script>
<script>
$( document ).ready( function(){
$( window ).MxLivingLinks( {
speedDelay: 1000, // скорость анимации
excludeElements: [ // ссылки, которые плагин игнорирует
'.disabled',
'.dropdown-toggle'
],
typeAnimate: 'randomType', // тип перехода по ссылке
endColor: '#ddd' // цвет затухающего фона при переходе по ссылке
} );
} );
</script>
</body>
</html> | 6dd659b6b9ecea66db08bec19d38bb2f2ada8cd0 | [
"JavaScript",
"Text",
"PHP"
] | 4 | PHP | Maxim-us/MxLivingLinks | 483d12c5d418f4051a7a893e7dde513e7bcf5bde | bb8c524f8ff4863831a51caef4b51e53952f1c23 |
refs/heads/main | <file_sep>'use strict';
module.exports.hello = async event => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: 'Go Serverless v1.0! Your function executed successfully!',
input: event,
},
null,
2
),
};
};
module.exports.cfc = async event => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: 'Go Serverless v1.0! Your CFC function executed successfully! Shane, in this case we are actually returning values from a AWS Lambda function but the API route could just as easily be pointed to a CFC hosted on a CF Server as a Rest API or Web Service I suppose.',
input: event,
},
null,
2
),
};
};
| 18b704a8b6b5e4a654180f958def80eabb060281 | [
"JavaScript"
] | 1 | JavaScript | amusto/serverless-aws-api-project | c8ad1cac32170da0212f594d262a74514001f627 | 47e4b97a81738b1ac920075b4998beddcfdb225e |
refs/heads/master | <file_sep>//
// ViewController.swift
// TrackCheck
//
// Created by <NAME> on 9/13/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Foundation
enum Result<Value> {
case success(Value)
case failure(Error)
}
struct Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
}
func getPosts(for userId: Int, completion: ((Result<[Post]>) -> Void)?) {
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func showAlert(){
print("hello")
let alert = UIAlertController(title: "hello world", message: "this is my first app!", preferredStyle: .alert)
let action = UIAlertAction(title: "Awesome", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
| 1243a3509d91f31a9406b277ec9c16ae5ae40586 | [
"Swift"
] | 1 | Swift | ChrisMLee/trackcheck | b043adee44e354d2d4b66a04bdd5433a5d602da7 | f6b8a7f5dc90586138726f439734e1f42cfff437 |
refs/heads/master | <file_sep>angular.module('starter.controllers', [])
.controller('CardsCtrl', function($scope, Cards) {
$scope.cards = Cards.fetch();
$scope.like = function(eventName, eventObject, index) {
console.log(eventName, eventObject, index);
$scope.cards[index].likes++;
};
$scope.dislike = function(eventName, eventObject, index) {
console.log(eventName, eventObject, index);
$scope.cards[index].likes--;
};
$scope.cardDestroyed = function(eventName, eventObject, index) {
console.log(eventName, eventObject, index);
$scope.cards.push($scope.cards.splice(index, 1)[0]);
};
})
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
});
| dfc18f3a1f7ac68ff793fe05ffad38fe3552dc6e | [
"JavaScript"
] | 1 | JavaScript | m0sk1t/Dater | 3bb4f74112cee80850edcdeddae7114ff8080ae5 | 5998424eef031ffc3f3570417d893aa89bd05e9c |
refs/heads/master | <repo_name>reicht/Weekend_Blog<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
def initialize(target)
@target=target
@params = @target[:params]
end
def index
@posts = $post_list
render_template 'posts/index.html.erb'
end
def show
post = targetting
if post
@post = post
render_template 'posts/show.html.erb'
else
render_not_found
end
end
def create
body = @params[:body]
title = @params[:title]
Post.new(title, body)
redirect_to"/posts"
end
def update
post = targetting
if post
unless @params["body"].nil? || @params["body"].empty?
post.body = @params["body"]
end
unless @params["completed"].nil? || @params["completed"].empty?
post.completed = @params["completed"]
end
render post.to_json, status: "200 OK"
else
render_not_found
end
end
def destroy
post = targetting
if task
$post_list.delete(post)
render({ message: "Successfully Deleted Post" }.to_json)
else
render_not_found
end
end
def new
render_template "posts/new.html.erb"
end
def new_comment
@post = targetting
render_template "posts/new_comment.html.erb"
end
private
def targetting
$post_list.find { |post| post.id == @params[:id].to_i}
end
def render_not_found
return_message = {
message: "Post not found!",
status: '404'
}.to_json
render return_message, status: "404 NOT FOUND"
end
end
<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def initialize(target)
@target=target
@params = @target[:params]
end
def index
@post_list = $post_list
render_template 'comments/index.html.erb'
end
def show
# @comment = targetting
# @parent = $post_list[@comment.parent_id]
# render_template 'comments/show.html.erb'
end
def create
target = @params[:post].to_i
post = $post_list[target - 1]
Comment.new(@params["comment"],post )
redirect_to '/comments'
end
def update
comment = targetting
if comment
unless @params["body"].nil? || @params["body"].empty?
comment.body = @params["body"]
end
unless @params["completed"].nil? || @params["completed"].empty?
comment.completed = @params["completed"]
end
render comment.to_json, status: "200 OK"
else
render_not_found
end
end
def destroy
comment = targetting
if comment
$post_list.delete(comment)
render({ message: "Successfully Deleted Comment" }.to_json)
else
render_not_found
end
end
def new
render_template 'comments/new.html.erb'
end
private
def targetting
$comment_list.find { |comment| post.id == @params[:id].to_i}
end
def render_not_found
return_message = {
message: "Comment not found!",
status: '404'
}.to_json
render return_message, status: "404 NOT FOUND"
end
end
<file_sep>/app/models/post.rb
require 'json'
class Post
attr_accessor :title, :body, :id, :published, :comments, :comment_ids, :timestamp
def initialize(title, body, id = -1, published = false)
@timestamp = Time.now.strftime("at %H:%M %y/%m/%d")
@title = title
@body = body
@comments = []
@comment_ids = 0
if id == -1
@id = Post.get_id
else
@id = id
end
$post_list << self
end
def Post.setup(num)
id = Post.get_id
title = $starter_post_titles[num]
body = $starter_post_contents[num]
parent = Post.new(title, body, id)
3.times do |x|
Comment.setup(parent)
end
end
def not_found
return "Not Found".to_json
end
def to_json( _ = nil)
{
id: id,
body: body,
completed: completed
}.to_json
end
def comment_id
@comment_ids += 1
end
private
def Post.get_id
$post_ids += 1
end
end
<file_sep>/db/seed.rb
$post_ids = 0
$starter_post_titles = ["Words", "And", "Things"]
$starter_post_contents = ["Cheetah, Hyena, Shingles, Roofing, Piano, Separatists, Celebrated, Rockets, Gleaming, Waves",
"And, then, until, except, suddenly, although, but, therefore",
"Things are amazing because they are, if things aren't, then the thing isn't and thus isn't a thing.",
]
$starter_comments = [["Animals, Summer Work, Musical, Fourth of July, Ocean", "Connections", "Penguins should be here"],
["What?", "This seriously makes no sense", "I get it, you know words"],
["This is really true, things are.", "Many things aren't, like unicorns.", "Then are they things?"],
]
$post_list = []
$comment_list = {}
<file_sep>/app/models/comment.rb
require 'json'
class Comment
attr_accessor :body, :id, :parent_id, :timestamp
def initialize(body, parent, id = -1)
@timestamp = Time.now.strftime("at %H:%M %y/%m/%d")
@parent = parent
@parent_id = parent.id
@body = body
@parent.comments << self
if id == -1
@id = parent.comment_id
else
@id = id
end
end
def Comment.setup(parent)
@parent = parent
parent_comments = $starter_comments[parent.id-1]
id = Comment.get_id
body = parent_comments[id - 1]
Comment.new(body, parent, id)
end
def not_found
return "Not Found".to_json
end
def to_json( _ = nil)
{
id: id,
body: body,
parent_id: parent_id,
}.to_json
end
private
def Comment.get_id
@parent.comment_id
end
end
| 5fedfd4a29f195242a28b4d0f8a84f5138ccff14 | [
"Ruby"
] | 5 | Ruby | reicht/Weekend_Blog | 851208be25971775948c32b7e88ece5b92380869 | 846063101cc13e4d3b57305b14835c930ea4c819 |
refs/heads/master | <repo_name>jonkesler/JavaScriptQuiz<file_sep>/assets/script.js
var button = document.querySelector("#buttons");
var cardText = document.querySelector("#text");
var timeEl = document.querySelector(".time");
var mainEl = document.getElementById("main");
var footer = document.querySelector("#footer");
var Arr = 0;
var score = 0;
var secondsLeft = 0;
// var bId = event.srcElement.id;
// var bId = "";
var ans = "";
// var textArr = ["Start", "Question 1", "Save"];
// var btnArr = ["Welcome to my Quiz", "How much does it cost", "Why did you choose that"];
var btnArr = [
{
q:"What is Java Script?",
a: "Coffee",
b: "A web programing language",
c: "A font face",
d: "All of the above",
ans: "b"
},
{
q: "What does a Java Script loop do?",
a: "loops through a block of code",
b: "loops through websites",
c: "changes the look and feel of a site",
d: "None of the above",
ans: "a"
},
{
q: "What is an if statement?",
a: "a statement that has if in it",
b: "executes a block of code",
c: "executes a function",
d: "All of the above",
ans: "d"
},
{
q: "What does the script tag do?",
a: "defines a client-side script",
b: "define an html element",
c: "define a css element",
d: "causes an html error",
ans: "a"
}
]
// start button
// ===================================================
function start(){
var h5 = document.createElement ("h5");
h5.textContent = "Weclome to my Java Script Quiz! When you hit start you will be given 30 seconds to complete this show 4 questions Quiz."
text.appendChild(h5);
buttons.innerHTML = "";
var btn = "Start";
var bId = "s";
var li = document.createElement("li");
li.textContent = btn;
li.setAttribute("class", "btn");
li.setAttribute("type", "button");
li.setAttribute("id", "s");
buttons.appendChild(li);
}
button.addEventListener("click", function(event) {
event.preventDefault();
// crazy code visual editor suggested
const newLocal = event.srcElement.id;
var bId = newLocal;
console.log(bId);
firstQ();
setTime();
})
// setTime(); // time in seconds // timer
// ===================================================
// var secondsLeft = 10;
function setTime() {
var secondsLeft = 30;
var timerInterval = setInterval(function() {
secondsLeft--;
timeEl.textContent = "Time remaining " + secondsLeft;
if(secondsLeft === 0) {
clearInterval(timerInterval);
sendMessage();
}
}, 1000);
}
// // onClick check answer and increment score/decrement time & go to next question.
// // ===================================================
function firstQ() {
var bId = event.srcElement.id;
var Arr = 0;
console.log("checkAns"+ bId);
var ans = btnArr[Arr].ans;
console.log(ans);
if (bId = "s"){
Arr++;
console.log("ans=s");
console.log(Arr + "Arr Value");
renderCardText();
};
button.addEventListener("click", function(event) {
event.preventDefault();
// crazy code visual editor suggested
const newLocal = event.srcElement.id;
var bId = newLocal;
console.log(bId);
})
}
function checkAns() {
var ans;
if (ans === bId){
score++;
footer.textContent = "Correct! Your Score is " + score;
console.log("score " +score);
};
if (ans !== bId && bId !== "s") {
footer.textContent = "Sorry Incorrect! You will loose 3 Seconds and Your Score is " + score;
var subTime = (secondsLeft - 3);
secondsLeft = subTime;
console.log("seconds left" + secondsLeft);
}
Arr++;
renderCardText();
setTime();
console.log("Arr = " + Arr);
console.log("choice " + bId)
console.log("correct Answer " + ans)
document.body.innerHTML = "";
renderCardText();
};
// // Create text for HTML CardBody H5
// // ===================================================
function renderCardText() {
// text.innerHTML = "";
var h5 = document.createElement ("h5");
h5.textContent = btnArr[Arr].q;
text.appendChild(h5);
buttons.innerHTML = "";
// add Button 1
var btn = btnArr[Arr].a;
var li = document.createElement("li");
li.textContent = btn;
li.setAttribute("type", "button");
li.setAttribute("id", "a");
buttons.appendChild(li);
// add Button 2
var btn = btnArr[Arr].b;
var li = document.createElement("li");
li.textContent = btn;
li.setAttribute("type", "button");
li.setAttribute("id", "b");
buttons.appendChild(li);
// add Button 3
var btn = btnArr[Arr].c;
var li = document.createElement("li");
li.textContent = btn;
li.setAttribute("type", "button");
li.setAttribute("id", "c");
buttons.appendChild(li);
// add Button 4
var btn = btnArr[Arr].d;
var li = document.createElement("li");
li.textContent = btn;
li.setAttribute("type", "button");
li.setAttribute("id", "d");
buttons.appendChild(li);
}
// }
function sendMessage() {
timeEl.textContent = " ";
timeEl.textContent = "Time is Up!"
alert("you are out of time");
renderCardText();
}
// call timer - uncomment to run when page is loaded.
// Score page - collect score and intails.
// ===================================================
function renderScore(){
var h5 = document.createElement ("h5");
h5.textContent = "You got " + score + " correct!"
text.appendChild(h5);
// needs to be a text box with save button
li.textContent = btn;
li.setAttribute("type", "button");
li.setAttribute("id", "s");
buttons.appendChild(li);
}
start();
// }
// Working code
// renderCardText();
// function renderCardText() {
// for (var j=0; j < btnArr.length; j++) {
// // console.log(btnArr[j]);
// var quest = JSON.stringify.btnArr;
// var h5 = document.createElement ("h5");
// h5.textContent = btnArr[j].a + "test";
// text.appendChild(h5);
// }
// }
// console.log(btnArr[1].a)
// Create buttons for HTML
// ===================================================
// renderCardButtons();
// function renderCardButtons() {
// // Clear CardBody element
// buttons.innerHTML = "";
// // todoCountSpan.textContent = todos.length;
// //new li for each Text
// for (var i = 0; i < textArr.length; i++) {
// var btn = textArr[i];
// var li = document.createElement("li");
// li.textContent = btn;
// li.setAttribute("type", "button");
// buttons.appendChild(li);
<file_sep>/Notes.txt
Store quiz questions [what is java script] var question = [
Store quiz answers [1. coffee] { question : "what is java",
Store high scores [2. a programming language] a : "coffee",
Calculate user score b : "a prgramming language",
Create timer answer : "b"
**** https://www.youtube.com/watch?v=49pYIMygIcU **** },
Change questions on answer click { question : "what is script",
a : "x",
============================= b : "y",
answer : "a"
onClick -> Start Button },
-> timer starts ]
-> first question displayed to call use question[0].question
question[0].answer
onClick -> any answer (need different id's for each answer - maybe setup in a table or rows?)
-> add to user score if correct (5 points!)
-> alert Correct!
-> display next question
-> if incorrect
-> alert Incorrect!
-> subtract time (5 Seconds)
-> display next question
gameOv -> all questions answered
-> timer reaches 0
-> show score and ask user for initals
-> store initals and score to high scores
==================================
Notes: Use localStorage to store scores (toDo list) and show user when when page displays also use in score page.
Use onClick and the var id to decide which button clicked - 18-EventDelegation
==================================
->Clean / polished user interface
->Responsive to multiple screen sizes
->URL of GitHub page
->URL of gitHub repository
git@github.com:jonkesler/JavaScriptQuiz.git
->include in Readme describing project
->Readme
->follow format from 03 Homework - stay consistant
->include URL's
repository: <EMAIL>:jonkesler/JavaScriptQuiz.git
page: https://jonkesler.github.io/JavaScriptQuiz/<file_sep>/README.md
# JavaScriptQuiz
My Amazing Java Script Quiz
This site will quiz users on 4 basic Java Script questions. Once the start button is clicked a 30 second timer will start and if the user has not answered all 4 questions it will end the game. Once the 4 questions are answered, the user will be able to record their intials and have their score added to the high score list. At any time the user can view a list of high scores.
## GitHub Info
===================
Repository URL: <EMAIL>:jonkesler/JavaScriptQuiz.git
Web URL: https://jonkesler.github.io/JavaScriptQuiz/
| 80aea9bcd117fa1a9b3ef68f3667edf9be2f66f1 | [
"JavaScript",
"Text",
"Markdown"
] | 3 | JavaScript | jonkesler/JavaScriptQuiz | 19f412f28a37bb595cb7b998238bb897af5f4113 | 3528b2ce1fa88f728ec09a3276475db6a38dd854 |
refs/heads/master | <file_sep># Facial landmark detection.
Program finds face in the frame and then detects facial features like eyes, eyebrows, nose, lips, face boundary.
It can be used for face masking.
Snapchat and Instagram using it for creating different filters.
## Library Used
OpenCV
## How to use repository.
Run `Facial landmark detection.py` file.

<file_sep>
import dlib
import cv2
import numpy as np
import imutils
from imutils import face_utils
def main():
detector=dlib.get_frontal_face_detector()
predictor=dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
cap=cv2.VideoCapture(0)
while True:
ret,frame=cap.read()
frame=imutils.resize(frame,width=500)
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
rects=detector(gray,1)
for (i,rect) in enumerate(rects):
(x,y,w,h)=face_utils.rect_to_bb(rect)
#cv2.rectangle(frame,(x,y),(x+h,y+w),(0,255,0),2)
shape=predictor(gray,rect)
shape=face_utils.shape_to_np(shape)
for(x,y) in shape:
cv2.circle(frame,(x,y),1,(255,255,255),-1)
print(x,y)
cv2.imshow("Output",frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
cap.release()
main() | 95031423adaa78009fcc908cba4804332cd1d4e9 | [
"Markdown",
"Python"
] | 2 | Markdown | Nish2288/Facial-landmark-detection | de74b4ac5e5a757132f9e218cd25367026f70814 | bad32ea0b7490b3976d929d7c9a9490b14bc37c0 |
refs/heads/master | <repo_name>Baptoow/gossip<file_sep>/the_gossip_project/app/models/user.rb
class User < ApplicationRecord
has_many :gossips
has_many :cities
end
<file_sep>/the_gossip_project/config/routes.rb
Rails.application.routes.draw do
get '/team', to: 'static#team'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
<file_sep>/the_gossip_project/README.md
# README
RAPPORT D'ERREUR
Je continue de'avoir le meme problème:
RuntimeError in Static#team
Showing /home/baptoow/Documents/THP/Ruby/Rails_THP/Gossip_project_rails/the_gossip_project/app/views/layouts/application.html.erb where line #9 raised:
Webpacker configuration file not found /home/baptoow/Documents/THP/Ruby/Rails_THP/Gossip_project_rails/the_gossip_project/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /home/baptoow/Documents/THP/Ruby/Rails_THP/Gossip_project_rails/the_gossip_project/config/webpacker.yml
Extracted source (around line #9):
7
8
9
10
11
12
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
Rails.root: /home/baptoow/Documents/THP/Ruby/Rails_THP/Gossip_project_rails/the_gossip_project
Application Trace | Framework Trace | Full Trace
app/views/layouts/application.html.erb:9
--------
Quand j'éssaie d'installer webpacker on me dit d'installer yarn et quand j'essaie d'installer yarn on me dit que la version est trop vieille 0.22 et je n'arrive pas à la mettre à jour.
| be393e2ea49c22a9922dbb2b602454177f02d8ab | [
"Markdown",
"Ruby"
] | 3 | Ruby | Baptoow/gossip | 6848b8a940e83cc4c8baec583987933089912c18 | a11e2b8ec8e1fbd1ec89a6ac74531478f8eebe6c |
refs/heads/master | <repo_name>joyopeng/bigdata<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.bric.kagdatabkt"
minSdkVersion 17
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
//选择要添加的对应cpu类型的.so库。
abiFilters 'armeabi', 'armeabi-v7a', 'armeabi-v8a','x86'
// 还可以添加 'x86', 'x86_64', 'mips', 'mips64'
}
manifestPlaceholders = [
JPUSH_PKGNAME: "com.bric.kagdatabkt",
JPUSH_APPKEY : "6f5a6e1b4e0c70a1ed82cb38", //JPush上注册的包名对应的appkey.
JPUSH_CHANNEL: "developer-default", //暂时填写默认值即可.
]
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDir 'libs'
}
// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
}
repositories {
flatDir {
dirs 'libs'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile(name: 'photopicker-release', ext: 'aar')
compile(name: 'autoScrollViewPager-release', ext: 'aar')
// 此处以JPush 3.0.3 版本为例。
// 此处以JCore 1.1.1 版本为例。
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:26.+'
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'cn.jiguang.sdk:jpush:3.0.3'
compile 'cn.jiguang.sdk:jcore:1.1.1'
testCompile 'junit:junit:4.12'
}
<file_sep>/app/src/main/java/com/bric/kagdatabkt/LoginMainActivity.java
package com.bric.kagdatabkt;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Text;
import com.baidu.mapapi.model.LatLng;
import com.bric.kagdatabkt.utils.LocationService;
public class LoginMainActivity extends AppCompatActivity {
private static final String TAG = LoginMainActivity.class.getSimpleName();
private EditText login_name_edit;
private EditText login_password_edit;
private TextView login_forgetpassword;
private TextView login_register;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
initView();
}
private void initView() {
login_name_edit = (EditText) findViewById(R.id.login_name_edit);
login_password_edit = (EditText) findViewById(R.id.login_password_edit);
login_forgetpassword = (TextView) findViewById(R.id.login_forgetpassword);
login_register = (TextView) findViewById(R.id.login_register);
login_name_edit.setBackgroundResource(0);
login_password_edit.setBackgroundResource(0);
}
}
<file_sep>/app/src/main/java/com/bric/kagdatabkt/view/fragment/Settingfragment.java
package com.bric.kagdatabkt.view.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import com.bric.kagdatabkt.ChitangAddActivity;
import com.bric.kagdatabkt.MainActivity;
import com.bric.kagdatabkt.QiyexinxiAdd;
import com.bric.kagdatabkt.R;
/**
* Created by joyopeng on 17-9-13.
*/
public class Settingfragment extends Fragment implements View.OnClickListener {
private RelativeLayout setting_persion_info_item;
private RelativeLayout setting_login_password_item;
private RelativeLayout setting_get_qrcode_item;
private RelativeLayout setting_clear_cache_item;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.setting, null);
init(v);
addAction();
return v;
}
private void init(View v) {
setting_persion_info_item = (RelativeLayout) v.findViewById(R.id.setting_persion_info_item);
setting_login_password_item = (RelativeLayout) v.findViewById(R.id.setting_login_password_item);
setting_get_qrcode_item = (RelativeLayout) v.findViewById(R.id.setting_get_qrcode_item);
setting_clear_cache_item = (RelativeLayout) v.findViewById(R.id.setting_clear_cache_item);
}
private void addAction() {
setting_persion_info_item.setOnClickListener(this);
setting_login_password_item.setOnClickListener(this);
setting_get_qrcode_item.setOnClickListener(this);
setting_clear_cache_item.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.setting_persion_info_item: {
Intent addintent = new Intent(getActivity(), QiyexinxiAdd.class);
startActivity(addintent);
}
break;
case R.id.setting_login_password_item: {
}
break;
case R.id.setting_get_qrcode_item: {
}
break;
case R.id.setting_clear_cache_item: {
}
break;
default:
break;
}
}
}
<file_sep>/app/src/main/java/com/bric/kagdatabkt/DanganAddChoseActivity.java
package com.bric.kagdatabkt;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.bric.kagdatabkt.utils.ResourceUtils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.bric.kagdatabkt.utils.CommonConstField.DANGAN_CONTENT_TYPE_KEY;
/**
* Created by joyopeng on 17-9-14.
*/
public class DanganAddChoseActivity extends FragmentActivity {
private TextView base_toolbar_title;
private ListView typelistview;
private ArrayList<OperatorType> types = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.danganaddchose);
base_toolbar_title = (TextView) findViewById(R.id.base_toolbar_title);
base_toolbar_title.setText("东塘管理");
typelistview = (ListView) findViewById(R.id.typelistview);
typelistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent addintent = new Intent(DanganAddChoseActivity.this, DanganAddActivity.class);
addintent.putExtra(DANGAN_CONTENT_TYPE_KEY,types.get(i).key);
startActivity(addintent);
}
});
loadxmlData();
}
private void loadxmlData() {
Map<String, String> typeelement = ResourceUtils.getHashMapResource(this, R.xml.operate_type);
if (typeelement.size() > 0) {
Set<Map.Entry<String, String>> sets = typeelement.entrySet();
Iterator<Map.Entry<String, String>> its = sets.iterator();
while (its.hasNext()) {
Map.Entry<String, String> entry = its.next();
OperatorType type = new OperatorType();
type.key = Integer.parseInt(entry.getKey());
type.name = entry.getValue();
types.add(type);
}
}
ListViewAdapter adapter = new ListViewAdapter(this, types);
typelistview.setAdapter(adapter);
}
public class ListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<OperatorType> types;
public ListViewAdapter(Context context, ArrayList<OperatorType> maps) {
inflater = LayoutInflater.from(context);
types = maps;
}
@Override
public int getCount() {
return types.size();
}
@Override
public Object getItem(int position) {
return types.get(position);
}
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.operator_type_item, parent, false);
holder.type = convertView.findViewById(R.id.operator_type_id_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.type = convertView.findViewById(R.id.operator_type_id_text);
}
holder.type.setText(types.get(position).name);
return convertView;
}
private class ViewHolder {
TextView type;
}
}
private class OperatorType {
public String name;
public int key;
}
}
<file_sep>/app/src/main/java/com/bric/kagdatabkt/DanganAddActivity.java
package com.bric.kagdatabkt;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bric.kagdatabkt.utils.CommonConstField;
import com.bric.kagdatabkt.view.CustomDatePicker;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class DanganAddActivity extends FragmentActivity {
private TextView base_toolbar_title;
private String title;
private RelativeLayout document_item1;
private TextView document_item1_label;
private EditText document_item1_edit;
private ImageView document_item1_arrow;
private RelativeLayout document_item2;
private TextView document_item2_label;
private EditText document_item2_edit;
private ImageView document_item2_arrow;
private Button take_picture;
private RelativeLayout document_item3;
private TextView document_item3_label;
private EditText document_item3_edit;
private ImageView document_item3_arrow;
private RelativeLayout document_item4;
private TextView document_item4_label;
private EditText document_item4_edit;
private ImageView document_item4_arrow;
private RelativeLayout document_item5;
private TextView document_item5_label;
private EditText document_item5_edit;
private ImageView document_item5_arrow;
//common field
private TextView document_operator_label;
private EditText document_operator_edit;
private TextView document_media_label;
private EditText document_media_edit;
private ImageView document_media_add;
private TextView document_note_label;
private EditText document_note_edit;
private LinearLayout upload_image_view;
private ImageView preview_img1;
private ImageView preview_img2;
private ImageView preview_img3;
private ImageView preview_img4;
//date picker
private CustomDatePicker datePicker;
private String time;
private String date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dangancontent);
initView();
initprop();
initCommonprop();
setActionListener();
//
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
time = sdf.format(new Date());
date = time.split(" ")[0];
//设置当前显示的日期
document_item1_edit.setHint(date);
}
private void initView() {
base_toolbar_title = (TextView) findViewById(R.id.base_toolbar_title);
document_item1 = (RelativeLayout) findViewById(R.id.document_item1);
document_item1_label = (TextView) findViewById(R.id.document_item1_label);
document_item1_edit = (EditText) findViewById(R.id.document_item1_edit);
document_item1_arrow = (ImageView) findViewById(R.id.document_item1_arrow);
document_item2 = (RelativeLayout) findViewById(R.id.document_item2);
document_item2_label = (TextView) findViewById(R.id.document_item2_label);
document_item2_edit = (EditText) findViewById(R.id.document_item2_edit);
document_item2_arrow = (ImageView) findViewById(R.id.document_item2_arrow);
take_picture = (Button) findViewById(R.id.take_picture);
document_item3 = (RelativeLayout) findViewById(R.id.document_item3);
document_item3_label = (TextView) findViewById(R.id.document_item3_label);
document_item3_edit = (EditText) findViewById(R.id.document_item3_edit);
document_item3_arrow = (ImageView) findViewById(R.id.document_item3_arrow);
document_item4 = (RelativeLayout) findViewById(R.id.document_item4);
document_item4_label = (TextView) findViewById(R.id.document_item4_label);
document_item4_edit = (EditText) findViewById(R.id.document_item4_edit);
document_item4_arrow = (ImageView) findViewById(R.id.document_item4_arrow);
document_item5 = (RelativeLayout) findViewById(R.id.document_item5);
document_item5_label = (TextView) findViewById(R.id.document_item5_label);
document_item5_edit = (EditText) findViewById(R.id.document_item5_edit);
document_item5_arrow = (ImageView) findViewById(R.id.document_item5_arrow);
//common field
document_operator_label = (TextView) findViewById(R.id.document_operator_label);
document_operator_edit = (EditText) findViewById(R.id.document_operator_edit);
document_media_label = (TextView) findViewById(R.id.document_media_label);
document_media_edit = (EditText) findViewById(R.id.document_media_edit);
document_media_add = (ImageView) findViewById(R.id.document_media_add);
document_note_label = (TextView) findViewById(R.id.document_note_label);
document_note_edit = (EditText) findViewById(R.id.document_note_edit);
upload_image_view = (LinearLayout) findViewById(R.id.upload_image_view);
preview_img1 = (ImageView) findViewById(R.id.preview_img1);
preview_img2 = (ImageView) findViewById(R.id.preview_img2);
preview_img3 = (ImageView) findViewById(R.id.preview_img3);
preview_img4 = (ImageView) findViewById(R.id.preview_img4);
}
private void initprop() {
int typekey = getIntent().getIntExtra(CommonConstField.DANGAN_CONTENT_TYPE_KEY, 1);
switch (typekey) {
case CommonConstField.DANGAN_CONTENT_TYPE_XIAODU:
title = getResources().getString(R.string.title_chitang_xiaodu);
setXiaoduprop();
break;
case CommonConstField.DANGAN_CONTENT_TYPE_TOUMIAO:
title = getResources().getString(R.string.title_chitang_toumiao);
setToumiaoprop();
break;
case CommonConstField.DANGAN_CONTENT_TYPE_WEISHI:
title = getResources().getString(R.string.title_chitang_weishi);
setWeishiprop();
break;
case CommonConstField.DANGAN_CONTENT_TYPE_BURAO:
title = getResources().getString(R.string.title_chitang_bulao);
setBulaoprop();
break;
case CommonConstField.DANGAN_CONTENT_TYPE_JIANCE:
title = getResources().getString(R.string.title_chitang_jiance);
setJianceprop();
break;
case CommonConstField.DANGAN_CONTENT_TYPE_FANGSHUI:
title = getResources().getString(R.string.title_chitang_fangshui);
setFangshuiprop();
break;
}
document_item1_edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
initPicker();
}
});
String name = gettypeNameBykey(typekey);
base_toolbar_title.setText(name);
}
private void initCommonprop() {
//common field
document_operator_edit.setBackgroundResource(0);
document_note_edit.setBackgroundResource(0);
}
private void setXiaoduprop() {
document_item1_label.setText(R.string.label_chitang_xiaodudate);
document_item1_edit.setBackgroundResource(0);
document_item2_label.setText(R.string.label_chitang_xiaoduchi);
document_item2_edit.setEnabled(false);
document_item2_edit.setBackgroundResource(0);
document_item2_edit.setHint(R.string.hint_chitang_xiaoduchi);
document_item3.setVisibility(View.GONE);
document_item4_label.setText(R.string.label_chitang_xiaoduyongliang);
document_item4_edit.setBackgroundResource(0);
document_item4_edit.setHint(R.string.hint_chitang_xiaoduyongliang);
document_item4_arrow.setVisibility(View.GONE);
document_item5_label.setVisibility(View.GONE);
document_item5_edit.setVisibility(View.GONE);
document_item5_arrow.setVisibility(View.GONE);
}
private void setToumiaoprop() {
document_item1_label.setText(R.string.label_chitang_toumiaodate);
document_item1_edit.setBackgroundResource(0);
document_item2_label.setText(R.string.label_chitang_source);
document_item2_edit.setBackgroundResource(0);
document_item2_edit.setHint(R.string.hint_chitang_source);
document_item2_arrow.setVisibility(View.GONE);
document_item3_label.setText(R.string.label_chitang_miaozhong_catogery);
document_item3_edit.setEnabled(false);
document_item3_edit.setBackgroundResource(0);
document_item3_edit.setHint(R.string.hint_chitang_miaozhong_catogery);
document_item4_label.setText(R.string.label_chitang_miaozhong_amount);
document_item4_edit.setBackgroundResource(0);
document_item4_edit.setHint(R.string.hint_chitang_miaozhong_amount);
document_item4_arrow.setVisibility(View.GONE);
document_item5_label.setVisibility(View.GONE);
document_item5_edit.setVisibility(View.GONE);
document_item5_arrow.setVisibility(View.GONE);
}
private void setWeishiprop() {
document_item1_label.setText(R.string.label_chitang_weishidate);
document_item1_edit.setBackgroundResource(0);
document_item2_label.setText(R.string.label_chitang_weishichi);
document_item2_edit.setEnabled(false);
document_item2_edit.setBackgroundResource(0);
document_item2_edit.setHint(R.string.hint_chitang_weishichi);
document_item3_label.setText(R.string.label_chitang_weishisiliao);
document_item3_edit.setBackgroundResource(0);
document_item3_edit.setHint(R.string.hint_chitang_weishisiliao);
document_item3_arrow.setVisibility(View.GONE);
take_picture.setVisibility(View.VISIBLE);
document_item4_label.setText(R.string.label_chitang_weishigoumaishang);
document_item4_edit.setBackgroundResource(0);
document_item4_edit.setHint(R.string.hint_chitang_weishigoumaishang);
document_item4_arrow.setVisibility(View.GONE);
document_item5_label.setText(R.string.label_chitang_weishiamount);
document_item5_edit.setHint(R.string.hint_chitang_weishiamount);
document_item5_edit.setBackgroundResource(0);
document_item5_arrow.setVisibility(View.GONE);
}
private void setBulaoprop() {
document_item1_label.setText(R.string.label_chitang_pulaodate);
document_item1_edit.setBackgroundResource(0);
document_item2_label.setText(R.string.label_chitang_pulaocatogery);
document_item2_edit.setEnabled(false);
document_item2_edit.setBackgroundResource(0);
document_item2_edit.setHint(R.string.hint_chitang_pulaocatogery);
document_item3.setVisibility(View.GONE);
document_item4_label.setText(R.string.label_chitang_pulaoamount);
document_item4_edit.setBackgroundResource(0);
document_item4_edit.setHint(R.string.hint_chitang_pulaoamount);
document_item4_arrow.setVisibility(View.GONE);
document_item5.setVisibility(View.GONE);
}
private void setJianceprop() {
document_item1_label.setText(R.string.label_chitang_jiancedate);
document_item1_edit.setBackgroundResource(0);
document_item2_label.setText(R.string.label_chitang_jianceid);
document_item2_edit.setEnabled(false);
document_item2_edit.setBackgroundResource(0);
document_item2_edit.setHint(R.string.hint_chitang_xiaoduchi);
document_item3_label.setText(R.string.label_chitang_jiancexiangmu);
document_item3_edit.setBackgroundResource(0);
document_item3_edit.setHint(R.string.hint_chitang_jiancexiangmu);
document_item4_label.setText(R.string.label_chitang_jiancejieguo);
document_item4_edit.setHint(R.string.hint_chitang_jiancejieguo);
document_item4_edit.setBackgroundResource(0);
document_item5_label.setText("检测单位");
document_item5_edit.setBackgroundResource(0);
document_item5_edit.setHint("请输入检测单位名称");
document_item5_arrow.setVisibility(View.GONE);
}
private void setFangshuiprop() {
document_item1_label.setText(R.string.label_chitang_fangshuidate);
document_item1_edit.setBackgroundResource(0);
document_item2_label.setText(R.string.label_chitang_fangshuichi);
document_item2_edit.setEnabled(false);
document_item2_edit.setBackgroundResource(0);
document_item2_edit.setHint(R.string.hint_chitang_fangshuichi);
document_item3_label.setVisibility(View.GONE);
document_item3_edit.setVisibility(View.GONE);
document_item3_arrow.setVisibility(View.GONE);
document_item4_label.setVisibility(View.GONE);
document_item4_edit.setVisibility(View.GONE);
document_item4_arrow.setVisibility(View.GONE);
document_item5_label.setVisibility(View.GONE);
document_item5_edit.setVisibility(View.GONE);
document_item5_arrow.setVisibility(View.GONE);
}
private void setActionListener() {
document_media_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PhotoPickerIntent intent = new PhotoPickerIntent(DanganAddActivity.this);
intent.setSelectModel(SelectModel.MULTI);
intent.setShowCarema(true); // 是否显示拍照
intent.setMaxTotal(4); // 最多选择照片数量,默认为9
startActivityForResult(intent, 2);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
ArrayList<String> paths = data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT);
if (paths.size() > 0)
upload_image_view.setVisibility(View.VISIBLE);
for (int i = 0; i < paths.size(); i++) {
if (i == 0) {
preview_img1.setImageURI(Uri.fromFile(new File(paths.get(i))));
}
if (i == 1) {
preview_img2.setImageURI(Uri.fromFile(new File(paths.get(i))));
}
if (i == 2) {
preview_img3.setImageURI(Uri.fromFile(new File(paths.get(i))));
}
if (i == 3) {
preview_img4.setImageURI(Uri.fromFile(new File(paths.get(i))));
}
}
}
}
private String gettypeNameBykey(int key) {
String name = getResources().getString(R.string.title_chitang_xiaodu);
switch (key) {
case CommonConstField.DANGAN_CONTENT_TYPE_XIAODU:
name = getResources().getString(R.string.title_chitang_xiaodu);
break;
case CommonConstField.DANGAN_CONTENT_TYPE_TOUMIAO:
name = getResources().getString(R.string.title_chitang_toumiao);
break;
case CommonConstField.DANGAN_CONTENT_TYPE_WEISHI:
name = getResources().getString(R.string.title_chitang_weishi);
break;
case CommonConstField.DANGAN_CONTENT_TYPE_BURAO:
name = getResources().getString(R.string.title_chitang_bulao);
break;
case CommonConstField.DANGAN_CONTENT_TYPE_JIANCE:
name = getResources().getString(R.string.title_chitang_jiance);
break;
case CommonConstField.DANGAN_CONTENT_TYPE_FANGSHUI:
name = getResources().getString(R.string.title_chitang_fangshui);
break;
}
return name;
}
private void initPicker() {
/**
* 设置年月日
*/
datePicker = new CustomDatePicker(this, "请选择日期", new CustomDatePicker.ResultHandler() {
@Override
public void handle(String time) {
document_item1_edit.setText(time.split(" ")[0]);
}
}, "2007-01-01 00:00", time, document_item1_edit.getY() + document_item1_edit.getHeight());
datePicker.showSpecificTime(false); //显示时和分
datePicker.setIsLoop(false);
datePicker.setDayIsLoop(true);
datePicker.setMonIsLoop(true);
datePicker.show(date);
}
}
<file_sep>/app/src/main/java/com/bric/kagdatabkt/RootApplication.java
package com.bric.kagdatabkt;
import android.app.Application;
import com.baidu.mapapi.SDKInitializer;
import cn.jpush.android.api.JPushInterface;
/**
* Created by joyopeng on 17-9-18.
*/
public class RootApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
JPushInterface.setDebugMode(true);//正式版的时候设置false,关闭调试
JPushInterface.init(this);
JPushInterface.onResume(this);
SDKInitializer.initialize(this);
}
}
| d8c9ee9b8eb0aa3733ee4f871f0b9f460ff402d0 | [
"Java",
"Gradle"
] | 6 | Gradle | joyopeng/bigdata | e17ed8f259a92946d456a651fbb7ae923377dd5f | 9e71244b58c993134f8dbd521449958e00c91f48 |
refs/heads/main | <repo_name>slimsevernake/Dating-Telegram-Bot<file_sep>/src/scenes/Registration/regWelcMsg.js
module.exports = {
f(params) {
const regWelcMsg = new params.Scene('reg1')
const moment = require('moment')
regWelcMsg.enter(async(ctx) => {
ctx.replyWithHTML(ctx.i18n.t('greeting'), params.Extra.HTML().markup((m) =>
m.inlineKeyboard([
m.callbackButton('Так 👍', 'okay')
])
))
let user = await ctx.db.User.findOne({ chat_id: ctx.from.id })
if (!user) {
await ctx.db.User.create({ chat_id: ctx.from.id, name: ctx.from.first_name, last_login: moment().format('DD.MM.YYYY') })
console.log(`Here's new one - ${ctx.from.first_name}`)
}
})
regWelcMsg.action('okay', (ctx) => ctx.scene.enter(`reg2`))
return regWelcMsg
}
}<file_sep>/src/scenes/Registration/regDesc.js
module.exports = {
f(params) {
const regDesc = new params.Scene('reg7')
regDesc.enter((ctx) => ctx.replyWithHTML(ctx.i18n.t('reg.desc'), params.Extra.markup((m) =>
m.inlineKeyboard([
m.callbackButton(ctx.i18n.t('reg.desc_skip'), 'skip')
])
)))
regDesc.on('text', (ctx) => {
ctx.message.text = ctx.message.text.replace(/\./g, ' ');
ctx.scene.state.decsript = ctx.message.text.replace(/@/g, ' ');
ctx.scene.enter('reg8', ctx.scene.state)
})
regDesc.action('skip', (ctx) => {
ctx.scene.state.decsript = ''
ctx.scene.enter('reg8', ctx.scene.state)
})
regDesc.on('message', (ctx) => ctx.scene.reenter('reg7'))
return regDesc
}
}<file_sep>/src/handlers/userdeleting.js
const deleteUser = async(ctx, cli_id) => {
await ctx.db.Relation.deleteMany({ host_id: cli_id })
await ctx.db.Relation.deleteMany({ cli_id: cli_id })
await ctx.db.Profile.deleteOne({ chat_id: cli_id })
await ctx.db.User.deleteOne({ chat_id: cli_id })
console.log(`${cli_id} was deleted from DB, bye bye`)
}
module.exports = deleteUser<file_sep>/src/database/models/city.js
const mongoose = require('mongoose');
const cityScheme = mongoose.Schema({
city_name: {
type: String,
required: true
},
city_lat: {
type: String,
required: true
},
city_lng: {
type: String,
required: true
}
}, { versionKey: false });
// const City = mongoose.model('City', cityScheme)
module.exports = cityScheme<file_sep>/src/database/models/index.js
const Profile = require('./profile')
const Relation = require('./relation')
const City = require('./city')
const User = require(`./user`)
module.exports = {
Profile,
Relation,
City,
User
}<file_sep>/src/scenes/Registration/regAge.js
module.exports = {
f(params) {
const regAge = new params.Scene('reg2')
regAge.enter((ctx) => ctx.replyWithHTML(ctx.i18n.t('reg.age')))
regAge.on('text', async(ctx) => {
if (isNaN(parseInt(ctx.message.text))) {
ctx.replyWithHTML(ctx.i18n.t('reg.age_error'))
} else {
await ctx.db.User.updateOne({ chat_id: ctx.from.id }, { age: ctx.message.text })
ctx.scene.enter(`reg3`, { age: ctx.message.text })
}
})
return regAge
}
}<file_sep>/src/scenes/Action/actionMail.js
module.exports = {
f(params) {
const actionMail = new params.Scene('action_mail')
actionMail.enter((ctx) => { ctx.replyWithHTML(`${ctx.i18n.t('action.message')} <b>${ctx.scene.state.cli_info.name}</b>`) })
actionMail.on('text', async(ctx) => {
await ctx.db.Relation.create({
host_id: ctx.from.id,
cli_id: ctx.scene.state.cli_info.chat_id,
host_like: true,
cli_checked: false,
msg_text: ctx.message.text
})
await console.log(`User ${ctx.from.first_name} send msg to ${ctx.scene.state.cli_info.name}`)
await ctx.scene.state.relations.push(ctx.scene.state.cli_info.chat_id)
ctx.scene.enter('action_main', ctx.scene.state)
})
actionMail.on('message', (ctx) => { ctx.replyWithHTML(ctx.i18n.t('action.mail_error')) })
return actionMail
}
}<file_sep>/src/scenes/Likely/likelyMain.js
const scene = params => {
const likelyMain = new params.Scene('liked_main')
const login = require('../../handlers/login')
likelyMain.enter(async(ctx) => {
await ctx.reply(ctx.i18n.t('likely.start'))
cliShowing(ctx)
})
likelyMain.action('yes', async(ctx) => {
await ctx.db.Relation.updateOne({ cli_id: ctx.from.id, host_id: ctx.scene.state.likes[0].host_id }, { cli_checked: true })
await matchHandler(ctx, params)
ctx.scene.state.likes.shift()
if (ctx.scene.state.likes.length) {
cliShowing(ctx)
} else {
delete ctx.scene.state.host
delete ctx.scene.state.likes
login(ctx)
}
})
likelyMain.action('no', async(ctx) => {
await ctx.db.Relation.updateOne({ cli_id: ctx.from.id, host_id: ctx.scene.state.likes[0].host_id }, { cli_checked: true })
ctx.scene.state.likes.shift()
if (ctx.scene.state.likes.length) {
cliShowing(ctx)
} else {
delete ctx.scene.state.host
delete ctx.scene.state.likes
login.f(ctx)
}
})
likelyMain.action('report', async(ctx) => {
await ctx.db.Relation.create({
host_id: ctx.from.id,
cli_id: ctx.scene.state.likes[0].host_id,
host_like: false,
cli_checked: false,
})
ctx.scene.state.likes.shift()
if (ctx.scene.state.likes) {
cliShowing(ctx)
} else {
delete ctx.scene.state.host
delete ctx.scene.state.likes
login.f(ctx)
}
})
likelyMain.action('go_exit', (ctx) => login.f(ctx))
async function matchHandler(ctx, params) {
ctx.replyWithHTML(`${ctx.i18n.t('likely.climatch')} <a href="tg://user?id=${ctx.scene.state.host.chat_id}">${ctx.scene.state.host.name}</a>`)
try {
await ctx.telegram.sendMessage(ctx.scene.state.host.chat_id, `${ctx.i18n.t('likely.hostmatch')} <a href="tg://user?id=${ctx.from.id}">${ctx.from.first_name}</a>`, params.Extra.HTML())
} catch (err) {
if (err.response && err.response.error_code === 403) {
await params.userDeleting(ctx, ctx.scene.state.host.chat_id)
} else { console.log(err.message) }
}
}
return likelyMain
}
async function cliShowing(ctx) {
let profile = await ctx.db.Profile.find({ chat_id: ctx.scene.state.likes[0].host_id })
ctx.scene.state.host = profile[0]
if (ctx.scene.state.likes[0].msg_text == undefined) {
showProfile(ctx, `<b>${profile[0].name}, ${profile[0].age}</b>. ${profile[0].city} \n\n${profile[0].decsript}`, profile[0])
} else {
showProfile(ctx, `<b>${profile[0].name}, ${profile[0].age}</b>. ${profile[0].city} \n\n💌 Повідомелння від <b>${profile[0].name}</b>:\n${ctx.scene.state.likes[0].msg_text}`, profile[0])
}
}
async function showProfile(ctx, message, cli_info) {
const Extra = require('telegraf/extra')
try {
await ctx.replyWithPhoto(`${cli_info.avatar}`, Extra.markup((markup) => {
markup.resize()
}).caption(message).HTML().markup((m) =>
m.inlineKeyboard([
[
m.callbackButton(ctx.i18n.t('action.like'), 'yes'),
m.callbackButton(ctx.i18n.t('action.dislike'), 'no')
],
[m.callbackButton(ctx.i18n.t('action.report'), 'report'),
m.callbackButton(ctx.i18n.t('action.exit'), 'go_exit')
]
])
))
} catch {
await ctx.replyWithVideo(`${cli_info.avatar}`, Extra.markup((markup) => {
markup.resize()
}).caption(message).HTML().markup((m) =>
m.inlineKeyboard([
[
m.callbackButton(ctx.i18n.t('action.like'), 'yes'),
m.callbackButton(ctx.i18n.t('action.dislike'), 'no')
],
[m.callbackButton(ctx.i18n.t('action.report'), 'report'),
m.callbackButton(ctx.i18n.t('action.exit'), 'go_exit')
]
])
))
}
}
module.exports = scene<file_sep>/src/bot.js
const { Telegraf } = require("telegraf");
const I18n = require("telegraf-i18n");
const path = require("path");
const getScenes = require(`./handlers/scenes`);
const login = require(`./handlers/login`);
const { db } = require("./database");
const bot = new Telegraf(process.env.BOT_TOKEN);
bot.catch((error) => {
console.log("Oops", error);
});
const i18n = new I18n({
directory: path.resolve(__dirname, "locales"),
defaultLanguage: "ua",
defaultLanguageOnMissing: true,
});
bot.use(i18n.middleware());
bot.context.db = db;
bot.context.i18n = i18n;
getScenes(bot)
bot.on("message", ctx => login(ctx));
bot.on("callback_query", ctx => login(ctx));
db.connection.once("open", async() => {
console.log("Connected to MongoDB");
bot.launch().then(() => {
console.log("Bot has been started ...");
});
});<file_sep>/src/scenes/Registration/regIntr.js
module.exports = {
f(params) {
const regIntr = new params.Scene('reg4')
regIntr.enter((ctx) => {
ctx.replyWithHTML(ctx.i18n.t('reg.int'), params.Extra.markup((m) =>
m.inlineKeyboard([
m.callbackButton(ctx.i18n.t('reg.int_boys'), 'boys'),
m.callbackButton(ctx.i18n.t('reg.int_girls'), 'girls'),
m.callbackButton(ctx.i18n.t('reg.int_both'), 'both')
])
))
})
regIntr.action('boys', (ctx) => {
ctx.scene.state.interest = 1
ctx.scene.enter('reg5', ctx.scene.state)
})
regIntr.action('girls', (ctx) => {
ctx.scene.state.interest = 0
ctx.scene.enter('reg5', ctx.scene.state)
})
regIntr.action('both', (ctx) => {
ctx.scene.state.interest = 2
ctx.scene.enter('reg5', ctx.scene.state)
})
regIntr.on('message', (ctx) => ctx.scene.reenter('reg4'))
return regIntr
}
}<file_sep>/src/scenes/Registration/regAvatar.js
module.exports = {
f(params) {
const regAvatar = new params.Scene('reg8')
regAvatar.enter((ctx) => ctx.replyWithHTML(ctx.i18n.t('reg.avatar')))
regAvatar.on('photo', (ctx) => {
ctx.scene.state.avatar = ctx.message.photo[0].file_id
ctx.scene.enter('reg9', ctx.scene.state)
})
regAvatar.on('video', (ctx) => {
ctx.scene.state.avatar = ctx.message.video.file_id
ctx.scene.enter('reg9', ctx.scene.state)
})
regAvatar.on('message', (ctx) => {
ctx.reply(ctx.i18n.t('reg.avatar'))
})
return regAvatar
}
}<file_sep>/src/handlers/getprofile.js
const profileMenu = require('../scenes/Profile/profileMenu')
async function getProfile(ctx) {
ctx.scene.state.cli_info = {}
let profile = await ctx.db.Profile.find({
city: ctx.scene.state.host_info[0].city,
chat_id: { $ne: ctx.from.id },
is_active: true,
})
if (ctx.scene.state.relations.length) {
profile = profile.filter((e) => {
if (ctx.scene.state.relations.some((el) => e.chat_id == el)) {
return false
} else {
return true
}
})
}
profile.sort((a, b) => {
return b.attraction - a.attraction
})
for (let i = 0; i < profile.length; i++) {
if (profileValidate(ctx, profile[i])) {
ctx.scene.state.cli_info = profile[i]
break
}
}
sendProfile(ctx, ctx.scene.state.cli_info)
}
function profileValidate(ctx, cli_info) {
if (
ctx.scene.state.host_info[0].interest != cli_info.gender &&
ctx.scene.state.host_info[0].interest != 2
) {
return false
}
if (
ctx.scene.state.host_info[0].gender != cli_info.interest &&
cli_info.interest != 2
) {
return false
}
// Age validation
const host_age = ctx.scene.state.host_info[0].age
const cli_age = cli_info.age
if (ctx.scene.state.host_info[0].gender == 1) {
if (host_age < 16 && cli_age > 16) {
return false
} else if (host_age >= 16 && host_age < 19) {
if (cli_age < 16 || cli_age > 19) {
return false
}
} else if (host_age >= 19 && host_age <= 20) {
if (cli_age <= 16 || cli_age > 20) {
return false
}
} else if (host_age > 20 && host_age <= 25) {
if (cli_age < 18 || cli_age > 24) {
return false
}
} else if (host_age > 25) {
if (cli_age < 24) {
return false
}
}
} else {
if (host_age < 16 && cli_age > 18) {
return false
} else if (host_age >= 16 && host_age < 19) {
if (cli_age < 18 || cli_age > 20) {
return false
}
} else if (host_age >= 19 && host_age <= 20) {
if (cli_age < 20 || cli_age > 23) {
return false
}
} else if (host_age > 20 && host_age <= 25) {
if (cli_age < 23 || cli_age > 30) {
return false
}
} else if (host_age > 25) {
if (cli_age < 30) {
return false
}
}
}
return true
}
async function sendProfile(ctx, cli_info) {
const Extra = require('telegraf/extra')
try {
try {
await ctx.replyWithPhoto(
`${cli_info.avatar}`,
Extra.markup((markup) => {
markup.resize()
})
.caption(
`<b>${cli_info.name}, ${cli_info.age}</b>. ${cli_info.city} \n\n${cli_info.decsript}`
)
.HTML()
.markup((m) =>
m.inlineKeyboard([
[
m.callbackButton(ctx.i18n.t('action.like'), 'yes'),
m.callbackButton(ctx.i18n.t('action.mail'), 'mail'),
m.callbackButton(ctx.i18n.t('action.dislike'), 'no'),
],
[
m.callbackButton(ctx.i18n.t('action.report'), 'report'),
m.callbackButton(ctx.i18n.t('action.exit'), 'go_exit'),
],
])
)
)
} catch (err) {
await ctx.replyWithVideo(
`${cli_info.avatar}`,
Extra.markup((markup) => {
markup.resize()
})
.caption(
`<b>${cli_info.name}, ${cli_info.age}</b>. ${cli_info.city} \n\n${cli_info.decsript}`
)
.HTML()
.markup((m) =>
m.inlineKeyboard([
[
m.callbackButton(ctx.i18n.t('action.like'), 'yes'),
m.callbackButton(ctx.i18n.t('action.mail'), 'mail'),
m.callbackButton(ctx.i18n.t('action.dislike'), 'no'),
],
[
m.callbackButton(ctx.i18n.t('action.report'), 'report'),
m.callbackButton(ctx.i18n.t('action.exit'), 'go_exit'),
],
])
)
)
}
} catch {
// All of clients had been shown, getCityCoords
getCityCoords(ctx)
}
}
async function getCityCoords(ctx) {
const cyrillicToTranslit = require('cyrillic-to-translit-js')
const fetch = require('node-fetch')
let city = await ctx.db.City.find({
city_name: ctx.scene.state.host_info[0].city,
})
if (city.length) {
getNearlyCity(ctx, city[0].city_lat, city[0].city_lng)
} else {
try {
let adress = cyrillicToTranslit({ preset: 'uk' }).transform(
ctx.scene.state.host_info[0].city,
' '
)
let nameURL =
'https://maps.googleapis.com/maps/api/geocode/json?address=' +
adress +
'&key=<KEY>'
let response = await fetch(nameURL)
let commits = await response.json()
let coord = commits.results[0].geometry.location
await ctx.db.City.create({
city_name: ctx.scene.state.host_info[0].city,
city_lat: coord.lat,
city_lng: coord.lng,
})
getNearlyCity(ctx, coord.lat, coord.lng)
} catch {
console.log('Такого міста нема')
}
}
}
async function getNearlyCity(ctx, lat, lng) {
const geolib = require('geolib')
const scanedCities = ctx.scene.state.scaned_city
if (
ctx.scene.state.nearly_cities == undefined ||
!ctx.scene.state.nearly_cities.length
) {
let cities = await ctx.db.City.find({
city_name: { $ne: ctx.scene.state.host_info[0].city },
})
cities.forEach((e, i) => {
if (scanedCities.some((el) => el == e.city_name)) {
cities.splice(i, 1)
} else {
e.distance =
geolib.getDistance(
{ latitude: lat, longitude: lng },
{ latitude: e.city_lat, longitude: e.city_lng },
1
) / 1000
}
})
cities.sort((a, b) => a.distance - b.distance)
ctx.scene.state.nearly_cities = cities
} else {
ctx.scene.state.nearly_cities.splice(0, 1)
}
updateScaned(ctx, ctx.scene.state.nearly_cities)
}
async function updateScaned(ctx, cities) {
try {
ctx.scene.state.scaned_city.push(`${cities[0].city_name}`)
ctx.scene.state.host_info[0].city = cities[0].city_name
ctx.scene.enter('action_main', ctx.scene.state)
} catch {
await ctx.replyWithHTML(ctx.i18n.t('action.over'))
ctx.scene.enter('action_menu', ctx.scene.state)
}
}
module.exports = getProfile
<file_sep>/src/handlers/scenes.js
const scenes = bot => {
const session = require('telegraf/session')
const Stage = require('telegraf/stage')
const Scene = require('telegraf/scenes/base')
const Extra = require('telegraf/extra')
const userDeleting = require('../handlers/userdeleting')
const { enter, leave } = Stage
const params = { Scene, Extra, userDeleting }
// Registration scenes
const regWelcMsg = require('../scenes/Registration/regWelcMsg').f(params)
const regAge = require('../scenes/Registration/regAge').f(params)
const regGender = require('../scenes/Registration/regGender').f(params)
const regIntr = require('../scenes/Registration/regIntr').f(params)
const regCity = require('../scenes/Registration/regCity').f(params)
const regName = require('../scenes/Registration/regName').f(params)
const regDesc = require('../scenes/Registration/regDesc').f(params)
const regAvatar = require('../scenes/Registration/regAvatar').f(params)
const regConf = require('../scenes/Registration/regConf').f(params)
// Profile scenes
const profileMenu = require('../scenes/Profile/profileMenu')(params)
const profileAvatar = require('../scenes/Profile/profileAvatar').f(params)
const profileDescript = require('../scenes/Profile/profileDescript').f(params)
// Action scenes
const actionMain = require('../scenes/Action/actionMain')(params)
const actionMenu = require('../scenes/Action/actionMenu')(params)
const actionMail = require('../scenes/Action/actionMail').f(params)
// Action scenes
const likelyMain = require('../scenes/Likely/likelyMain')(params)
const stage = new Stage([
regWelcMsg,
regAge,
regGender,
regIntr,
regCity,
regName,
regDesc,
regAvatar,
regConf,
profileMenu,
profileAvatar,
profileDescript,
actionMain,
actionMenu,
actionMail,
likelyMain
], { ttl: 120 })
bot.use(session())
bot.use(stage.middleware())
}
module.exports = scenes<file_sep>/src/handlers/login.js
async function login(ctx) {
ctx.session.user = await ctx.db.Profile.find({ chat_id: ctx.from.id })
ctx.session.user.length ? updateLastLogin(ctx) : ctx.scene.enter('reg1')
}
async function updateLastLogin(ctx) {
const moment = require('moment')
await ctx.db.User.updateOne({ chat_id: ctx.from.id }, { last_login: moment().format('DD.MM.YYYY') })
getRelations(ctx)
}
async function getRelations(ctx) {
let relations = await ctx.db.Relation.find({ host_id: ctx.from.id }, { cli_id: 1, _id: 0 })
relations = relations.concat(await ctx.db.Relation.find({ cli_id: ctx.from.id, host_like: false }, { host_id: 1, _id: 0 }))
.concat(await ctx.db.Relation.find({ cli_id: ctx.from.id, cli_checked: true }, { host_id: 1, _id: 0 }))
ctx.session.relations = relations.map(e => e.host_id == undefined ? e = e.cli_id : e = e.host_id)
getLikes(ctx)
}
async function getLikes(ctx) {
const host_info = ctx.session.user
const relations = ctx.session.relations
const state = { host_info, relations, scaned_city: [`${host_info[0].city}`] }
if (host_info[0].likes) {
ctx.scene.enter('action_main', state)
} else {
ctx.scene.enter('prof_menu', state)
}
}
module.exports = login<file_sep>/src/scenes/Registration/regConf.js
module.exports = {
f(params) {
const regConf = new params.Scene('reg9')
const login = require('../../handlers/login')
regConf.enter(async(ctx) => {
try {
await ctx.replyWithPhoto(`${ctx.scene.state.avatar}`, params.Extra.markup((markup) => {
markup.resize()
}).caption(`<b>${ctx.scene.state.name}, ${ctx.scene.state.age}</b>. ${ctx.scene.state.city} \n\n${ctx.scene.state.decsript}`).HTML())
ctx.reply(ctx.i18n.t('reg.conf'), params.Extra.HTML().markup((m) =>
m.inlineKeyboard([
m.callbackButton(ctx.i18n.t('reg.well'), 'well'),
m.callbackButton(ctx.i18n.t('reg.edit'), 'edit')
])
))
} catch {
await ctx.replyWithVideo(`${ctx.scene.state.avatar}`, params.Extra.markup((markup) => {
markup.resize()
}).caption(`<b>${ctx.scene.state.name}, ${ctx.scene.state.age}</b>. ${ctx.scene.state.city} \n\n${ctx.scene.state.decsript}`).HTML())
ctx.reply(ctx.i18n.t('reg.conf'), params.Extra.HTML().markup((m) =>
m.inlineKeyboard([
m.callbackButton(ctx.i18n.t('reg.well'), 'well'),
m.callbackButton(ctx.i18n.t('reg.edit'), 'edit')
])
))
}
})
regConf.action('well', async(ctx) => {
await ctx.db.Profile.deleteOne({ chat_id: ctx.from.id })
await ctx.db.Profile.create({
name: ctx.scene.state.name,
chat_id: ctx.from.id,
gender: ctx.scene.state.gender,
interest: ctx.scene.state.interest,
city: ctx.scene.state.city,
age: ctx.scene.state.age,
decsript: ctx.scene.state.decsript,
avatar: ctx.scene.state.avatar,
is_active: true,
strikes: 0,
activities: 0,
activities_block: false,
likes: 0,
attraction: 0
})
await ctx.db.Relation.deleteMany({ cli_id: ctx.from.id })
let relations = await ctx.db.Relation.find({ host_id: ctx.from.id }, { cli_id: 1, _id: 0 })
ctx.scene.enter('action_main', { host_info: [ctx.scene.state], relations, scaned_city: [`${ctx.scene.state.city}`] })
})
regConf.action('edit', async(ctx) => {
await ctx.db.Profile.deleteOne({ chat_id: ctx.from.id })
await ctx.db.Profile.create({
name: ctx.scene.state.name,
chat_id: ctx.from.id,
gender: ctx.scene.state.gender,
interest: ctx.scene.state.interest,
city: ctx.scene.state.city,
age: ctx.scene.state.age,
decsript: ctx.scene.state.decsript,
avatar: ctx.scene.state.avatar,
is_active: true,
strikes: 0,
activities_block: false,
likes: 0,
attration: 0
})
await ctx.db.Relation.deleteMany({ cli_id: ctx.from.id })
login.f(ctx)
})
regConf.on('message', (ctx) => ctx.scene.reenter('reg9'))
return regConf
}
}<file_sep>/src/scenes/Registration/regGender.js
module.exports = {
f(params) {
const regGender = new params.Scene('reg3')
regGender.enter((ctx) => ctx.replyWithHTML(ctx.i18n.t('reg.sex'), params.Extra.markup((m) =>
m.inlineKeyboard([
m.callbackButton(ctx.i18n.t('reg.sex_boy'), 'boy'),
m.callbackButton(ctx.i18n.t('reg.sex_girl'), 'girl')
])
)))
regGender.action('boy', (ctx) => {
ctx.scene.state.gender = 1
ctx.scene.enter('reg4', ctx.scene.state)
})
regGender.action('girl', (ctx) => {
ctx.scene.state.gender = 0
ctx.scene.enter('reg4', ctx.scene.state)
})
regGender.on('message', (ctx) => ctx.scene.reenter('reg3'))
return regGender
}
}<file_sep>/src/scenes/Profile/profileAvatar.js
module.exports = {
f(params) {
const profileAvatar = new params.Scene('prof_menu2')
const login = require('../../handlers/login')
profileAvatar.enter((ctx) => ctx.replyWithHTML(ctx.i18n.t('reg.avatar')))
profileAvatar.on('photo', async(ctx) => {
await ctx.db.Profile.updateOne({ chat_id: ctx.from.id }, { avatar: ctx.message.photo[0].file_id })
await ctx.db.Relation.deleteMany({ cli_id: ctx.from.id })
login.f(ctx)
})
profileAvatar.on('video', async(ctx) => {
await ctx.db.Profile.updateOne({ chat_id: ctx.from.id }, { avatar: ctx.message.video.file_id })
await ctx.db.Relation.deleteMany({ cli_id: ctx.from.id })
login.f(ctx)
})
profileAvatar.on('message', (ctx) => {
ctx.reply(ctx.replyWithHTML(ctx.i18n.t('reg.avatar')))
})
return profileAvatar
}
}<file_sep>/src/database/models/user.js
const mongoose = require('mongoose');
const userScheme = mongoose.Schema({
chat_id: {
type: Number,
required: true
},
age: {
type: Number,
},
city: {
type: String,
},
last_login: {
type: String,
}
}, { versionKey: false });
module.exports = userScheme<file_sep>/src/database/models/relation.js
const mongoose = require('mongoose');
const relationScheme = mongoose.Schema({
host_id: {
type: Number,
required: true
},
cli_id: {
type: Number,
required: true
},
host_like: {
type: Boolean,
required: true
},
cli_checked: {
type: Boolean,
required: true
},
msg_text: {
type: String,
},
}, { versionKey: false });
// const Relation = mongoose.model('Relation', relationScheme)
module.exports = relationScheme<file_sep>/src/database/models/profile.js
const mongoose = require('mongoose');
const profileScheme = mongoose.Schema({
name: {
type: String,
required: true
},
chat_id: {
type: Number,
required: true
},
gender: {
type: Number,
required: true
},
interest: {
type: Number,
required: true
},
city: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
decsript: {
type: String
},
avatar: {
type: String,
required: true
},
is_active: {
type: Boolean,
required: true
},
strikes: {
type: Number,
required: true
},
activities_block: {
type: Boolean,
},
likes: {
type: Number,
},
attraction: {
type: Number,
}
}, { versionKey: false });
// const Profile = mongoose.model('Profile', profileScheme)
module.exports = profileScheme | 2ad011ce933109a04389671f5013703960c6e211 | [
"JavaScript"
] | 20 | JavaScript | slimsevernake/Dating-Telegram-Bot | 0fe57b41a4519663ba832d42bd260e1a14f642c5 | 51866321dd92f70a9672743a39d03c97489bfce9 |
refs/heads/master | <file_sep>namespace PSClassLib.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.tbDominioTipos",
c => new
{
id = c.Int(nullable: false, identity: true),
descricao = c.String(),
obs = c.String(),
})
.PrimaryKey(t => t.id);
CreateTable(
"dbo.tbDominio",
c => new
{
id = c.Int(nullable: false, identity: true),
descricao = c.String(),
data_inicio = c.DateTime(nullable: false),
data_fim = c.DateTime(nullable: false),
obs = c.String(),
id_usuario_inclusao = c.Int(nullable: false),
id_usuario_alteracao = c.Int(nullable: false),
data_inclusao = c.DateTime(nullable: false),
data_alteracao = c.DateTime(nullable: false),
tipo_dominio_id = c.Int(),
})
.PrimaryKey(t => t.id)
.ForeignKey("dbo.tbDominioTipos", t => t.tipo_dominio_id)
.Index(t => t.tipo_dominio_id);
}
public override void Down()
{
DropForeignKey("dbo.tbDominio", "tipo_dominio_id", "dbo.tbDominioTipos");
DropIndex("dbo.tbDominio", new[] { "tipo_dominio_id" });
DropTable("dbo.tbDominio");
DropTable("dbo.tbDominioTipos");
}
}
}
<file_sep>using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(UnibenApp01.Startup))]
namespace UnibenApp01
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using PSClassLib.Entities;
namespace PSClassLib.Concrete
{
public class UnibenContext: DbContext
{
public UnibenContext() : base("name=UnibenConnect")
{
}
public DbSet<Dominio> Dominios { get; set; }
public DbSet<DominioTipo> Dominio_Tipos { get; set; }
//public System.Data.Entity.DbSet<UnibenApp.Models.Dominio> Dominios { get; set; }
}
}
<file_sep>using PSClassLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PSClassLib.Abstract
{
interface IDominio
{
IQueryable<Dominio> Dominios { get; }
void inserir(Dominio dominio);
void alterar(Dominio dominio);
void excluir(Dominio dominio);
Dominio RetornarPorId(int id);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PSClassLib.Abstract;
using PSClassLib.Entities;
namespace PSClassLib.Concrete
{
public class EFDominio : IDominio
{
private UnibenContext unibenContext;
public EFDominio(UnibenContext context)
{
unibenContext = context;
}
public IQueryable<Dominio> Dominios
{
get
{
throw new NotImplementedException();
}
}
public void alterar(Entities.Dominio dominio)
{
unibenContext.SaveChanges();
}
public void excluir(Dominio dominio)
{
throw new NotImplementedException();
}
public void inserir(Dominio dominio)
{
throw new NotImplementedException();
}
public Entities.Dominio Retornar(int id)
{
throw new NotImplementedException();
}
public Dominio RetornarPorId(int id)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
namespace PSClassLib.Entities
{
[Table("tbDominio")]
public class Dominio
{
[Key]
public int id { get; set; }
//[MaxLength(150, ErrorMessage = "Máximo de 150 caracteres")]
//[MinLength(2, ErrorMessage = "Mínimo de 2 caracteres")]
[DisplayName("Descrição")]
[Required(ErrorMessage = "Preencher a Descrição")]
public string descricao { get; set; }
[DataType(DataType.Date, ErrorMessage = "Por favor, insira uma data válida no formato dd/mm/yyyy")]
//[Range(typeof(DateTime), "1/1/1800", "1/1/2900")]
//[RequiredToClose]
public DateTime data_inicio { get; set; }
[DataType(DataType.Date, ErrorMessage = "Por favor, insira uma data válida no formato dd/mm/yyyy")]
//[Range(typeof(DateTime), "1/1/1800", "1/1/2900")]
public DateTime data_fim { get; set; }
public string obs { get; set; }
[ScaffoldColumn(false)]
public int id_usuario_inclusao { get; set; }
[ScaffoldColumn(false)]
public int id_usuario_alteracao { get; set; }
[ScaffoldColumn(false)]
public DateTime data_inclusao { get; set; }
[ScaffoldColumn(false)]
public DateTime data_alteracao { get; set; }
public DominioTipo tipo_dominio { get; set; }
//[EmailAddress(ErrorMessage ="")]
}
}
<file_sep>using PSClassLib.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PSClassLib.Abstract
{
interface ITipo_Dominio
{
//IEnumerable<DominioTipo> RetornarTipos();
}
}
| 55b94a391f4720bc75fa5d0f7290a91d6a8aa8fe | [
"C#"
] | 7 | C# | RodCorrea/UnibenWeb | b9647f93ad819b55c8679aa5c5866be86b7f3cc4 | 8a7a6bd7f64e1829b349cc283e2e1f56f74fd8f3 |
refs/heads/master | <repo_name>Prashast09/RxJava<file_sep>/app/src/main/java/com/example/earthshaker/githubapi/GithubResponseConfig.java
package com.example.earthshaker.githubapi;
import com.google.gson.annotations.SerializedName;
/**
* Created by earthshaker on 14/5/17.
*/
public class GithubResponseConfig {
private String url;
private String body;
private String title;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
<file_sep>/app/src/main/java/com/example/earthshaker/githubapi/CardAdapter.java
package com.example.earthshaker.githubapi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by earthshaker on 14/5/17.
*/
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
List<GithubResponseConfig> mItems;
public CardAdapter(List<GithubResponseConfig> item) {
super();
mItems = new ArrayList<>(item);
}
public void setData(List<GithubResponseConfig> githubResponseConfigList) {
if (githubResponseConfigList == null) {
mItems = new ArrayList<>();
} else {
mItems = githubResponseConfigList;
}
notifyDataSetChanged();
}
public void clear() {
mItems.clear();
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.adapter_recycler_view, viewGroup, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
GithubResponseConfig githubResponseConfig = mItems.get(i);
viewHolder.title.setText(githubResponseConfig.getTitle());
viewHolder.url.setText(String.format("Url: %s", githubResponseConfig.getUrl()));
viewHolder.body.setText(String.format("Body: %s", githubResponseConfig.getBody()));
}
@Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView url;
public TextView title;
public TextView body;
public ViewHolder(View itemView) {
super(itemView);
url = (TextView) itemView.findViewById(R.id.url);
title = (TextView) itemView.findViewById(R.id.title);
body = (TextView) itemView.findViewById(R.id.body);
}
}
} | ede15fbb231efcd596c6b1e5103710749a6bbf50 | [
"Java"
] | 2 | Java | Prashast09/RxJava | 61cad6993ec1426e700f77f62dc80c44083498e8 | bbf9297d286231617e34829bf7807812bf3f39fc |
refs/heads/master | <file_sep>#include "stdio.h"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include<unordered_map>
using namespace std;
class Mouse;
class Monitor;
class Computer;
class ElementVisitor {
public:
virtual ~ElementVisitor(){};
virtual void VisitMouse(Mouse*) =0;
virtual void VisitMonitor(Monitor*)=0;
virtual void VisitComputer(Computer*)=0;
protected:
ElementVisitor(){};
};
class Element {
public:
virtual ~Element(){};
const string MyName() {return name_;};
virtual void Accept(ElementVisitor* visitor) = 0;
virtual void Power() {std::cout << "This device " << name_ <<" does not have Power!" << std::endl;};
virtual void NetPrice() {std::cout << "This device " << name_ << " is free!" << std::endl;};
virtual void Discount() {std::cout << "This device " << name_ << " does not have discount " <<std::endl;};
virtual void Move() {std::cout << "This device " << name_ << " can not be moved!" << std::endl;};
protected:
Element(const string& name): name_(name){};
private:
std::string name_;
};
class Mouse : public Element {
public:
Mouse(std::string name, int power) : Element(name), power_(power) {}
~Mouse(){}
void Power() override {
std::cout << "Mouse Power: " << power_ << std::endl;
}
void NetPrice() override {
std::cout << "Mouse net price is 19$" << std::endl;
}
void Move() override {
std::cout << "Mouse move 1, use 1 power" << std::endl;
power_--;
Power();
}
void Accept(ElementVisitor* visitor) override {
visitor->VisitMouse(this);
}
private:
int power_;
};
class Monitor: public Element {
public:
Monitor(std::string name) : Element(name){}
~Monitor(){}
void NetPrice() override {
std::cout <<"This Monitor is 100$" << std::endl;
}
void Discount() override {
std::cout << "This Monitor has discount 20$"<<std::endl;
}
void Accept(ElementVisitor* visitor) override{
visitor->VisitMonitor(this);
}
};
class Computer: public Element {
public:
Computer(std::string name, std::unordered_map<string, string> device_names): Element(name), power_(100){
for (auto kv : device_names) {
if (kv.first == "Mouse"){
devices_.push_back(new Mouse(kv.second, 10));
}else if (kv.first == "Monitor"){
devices_.push_back(new Monitor(kv.second));
}else{
std::cout << "No suching device!" << std::endl;
}
}
}
~Computer(){
for (Element* x : devices_){
free(x);
}
};
void Accept(ElementVisitor* visitor) override {
visitor->VisitComputer(this);
}
void Power() override{
std::cout << "Computer has Power: " << power_;
for (auto device : devices_){
device->Power();
}
}
void NetPrice() override{
std::cout << "This computer is 500$" << std::endl;
for (auto device : devices_){
device->NetPrice();
}
}
void Discount() override{
Element::Discount();
for (auto d: devices_) {
d->Discount();
}
}
void Move() override {
Element::Move();
for (auto d: devices_) {
d->Move();
}
}
private:
std::vector<Element*> devices_;
int power_;
};
class ComputerVisitor: public ElementVisitor{
public:
ComputerVisitor(){};
~ComputerVisitor(){};
void VisitMouse(Mouse* mouse) override {
for (int i= 0; i < 10; i++){
mouse->Move();
}
std::cout << "Mouse price: " << std::endl;
mouse->NetPrice();
};
void VisitMonitor(Monitor* monitor) override {
monitor->Discount();
};
void VisitComputer(Computer* computer) override {
computer->Power();
computer->NetPrice();
computer->Move();
computer->Discount();
};
};
int main(int argc, char** argv){
ComputerVisitor visitor;
Mouse mouse("mouse1", 10);
Monitor monitor("Monitoer1");
Computer computer("computer1", {{"Mouse", "mouse2"}, {"Monitor", "monitor2"}, {"keyboard", "keyboard"}});
mouse.Accept(&visitor);
monitor.Accept(&visitor);
computer.Accept(&visitor);
return 0;
}
<file_sep>#include "stdio.h"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
using namespace std;
// This is a fake class to represent the graph in the page
struct Graphic{
int x;
int y;
};
class SolverMemento{
public:
~SolverMemento(){}
private:
friend class ConstraintSolver;
SolverMemento(){}
};
class ConstraintSolver{
public:
static ConstraintSolver* GetInstance(){
static ConstraintSolver* solver = new ConstraintSolver();
return solver;
}
void Solve(){
std::cout << "Will solve the constraint between two targets." <<std::endl;
}
void AddConstraint(Graphic* start, Graphic* end){
std::cout << "Add a constraint between two target start and end"<<std::endl;
}
void RemoveConstraint(Graphic* start, Graphic* end){
std::cout << "Remove the constraint between the targets" << std::endl;
}
SolverMemento* CreateMeme(){
return new SolverMemento();
}
void SetMeme(SolverMemento* meme){
std::cout << "Change inner state based on meme" << std::endl;
};
private:
ConstraintSolver(){}
};
class MoveCommand {
public:
~MoveCommand(){
free(state_);
}
MoveCommand(Graphic* target, const int delta): target_(target), delta_(delta){};
void Execute(){
ConstraintSolver* solver = ConstraintSolver::GetInstance();
state_ = solver->CreateMeme();
std::cout << "This is the step to do target->move(delta)" << std::endl;
solver->Solve(); //Solve the process
}
void Undo(){
ConstraintSolver* solver = ConstraintSolver::GetInstance();
std::cout << "This is the step to do target->undo(delta)" << std::endl;
solver->SetMeme(state_);
solver->Solve();
}
private:
SolverMemento* state_;
Graphic* target_;
int delta_;
};
int main(int argc, char** argv){
Graphic g;
MoveCommand command(&g, 10);
command.Execute();
command.Undo();
return 1;
}
<file_sep>class node:
classification = None
def __init__(self, is_leaf,value, split_index, parent, children, height):
self.is_leaf = is_leaf
self.split_key = split_index
self.parent = parent
self.children = children
self.depth = height
self.value = value
def show(self):
print self.is_leaf
print self.split_key
class bi_node:
classification = None
def __init__(self,is_leaf, split_index, split_value, parent, left, right, height ):
self.is_leaf = is_leaf
self.split_key = split_index
self.split_value = split_value
self.parent = parent
self.left = left
self.right = right
self.depth = height
<file_sep>//
// main.c
// test2
//
// Created by XuLi on 8/17/17.
// Copyright © 2017 XuLi. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define SQ(x) ((x)*(x))
struct kdnode {
double coord_x;
double coord_y;
double coord_z;
int split;
double value;
struct kdnode* right_child;
struct kdnode* left_child;
struct kdnode* parent;
};
struct kdtree {
struct kdnode* root;
int demension;
double bbox[4];
// int col;
// int row;
};
void SWAP4(double *x,double *y)
{
double SWAP[4];
memcpy(SWAP,x,sizeof(double*)*4);
for(int i=0;i<4;i++)
{
x[i]=y[i];
y[i]=SWAP[i];
}
}
void SWAP5(double *x,double *y)
{
double SWAP[5];
memcpy(SWAP,x,sizeof(double)*5);
for(int i=0;i<5;i++)
{
x[i]=y[i];
y[i]=SWAP[i];
}
}
int partition(double points[][5], int a, int b, int direc)
{
int i = a;
double X = points[b][direc];
for (int j= a; j<b-1; j++)
{
if (X >= points[j][direc])
{
SWAP5(points[i], points[j]);
i++;
}
}
SWAP5(points[i], points[b]);
return i;
}
void quicksort (double points[][5], int a, int b, int direc)
{
if (a >= b)
{
return;
}
int q = partition(points,a,b,direc);
quicksort(points, a, q-1, direc);
quicksort(points, q+1, b, direc);
}
void putforward(double **points,int position, int b, int *size)
{
double p[4] ={points[position][0],points[position][1],points[position][2],points[position][3]};
for (int i= position; i<b; i++){
points[i][0] = points[i+1][0];
points[i][1] = points[i+1][1];
points[i][2] = points[i+1][2];
points[i][3] = points[i+1][3];
}
points[b][0] = p[0];
points[b][1] = p[1];
points[b][2] = p[2];
points[b][3] = p[3];
*size = *size -1;
}
void Median_Point (double forreturn[5], double Pointset[3][5],int direc)
{
quicksort(Pointset,0,9,direc);
forreturn[0] = Pointset[5][0];
forreturn[1] = Pointset[5][1];
forreturn[2] = Pointset[5][2];
forreturn[3] = Pointset[5][3];
forreturn[4] = Pointset[5][4];
}
void RandomSelect (double*midpoint, double** pointSet, int *size, int direc, int a, int b)
{
if ((b-a+1) > 10){
// srand(time(NULL));
//int *ridrepeat;
double result[10][5];
int ridrepeat[100];// = calloc((*size),sizeof(int));
int n = a + rand() % (b-a+1);
for (int i = 0; i< 10; i++)
{
while (ridrepeat[n] == -1)
{
n = a + rand() % (b-a+1);
}
for(int l=0; l<4; l++)
{
result[i][l] = pointSet[n][l];
// printf("%f,",result[i][l]);
}
result[i][4] = n;
ridrepeat[n] = -1;
n =a + rand() % (b-a+1);
}
Median_Point(midpoint,result,direc);
putforward(pointSet,(int)midpoint[4],b,size);
// free(ridrepeat);
}else{
midpoint[0] = pointSet[a+(b-a)/2][0];
midpoint[1] = pointSet[a+(b-a)/2][1];
midpoint[2] = pointSet[a+(b-a)/2][2];
midpoint[3] = a+(b-a)/2;
putforward(pointSet, a+(b-a)/2, b, size);
/* printf("the mid point is:\n");
for (int i=0; i<3; i++)
{
printf("%f,",midpoint[i]);
}
printf("\n");*/
return;
}
return;
}
int reorder(double **points, double value, int direc, int a, int b)
{
int left =a;
// printf("reorder begin! direc:%d, value:%f\n",direc,value);
for (int right = a; right<= b; right++)
{
if (points[right][direc] <= value)
{
SWAP4(points[left], points[right]);
left = left+1;
}
}
/* printf("reordering : %f, %d,%d,%d\n",value, a,b,left);
for (int right = a; right<= b+1; right++)
{
printf("%f,",points[right][direc]);
}
printf("\n");*/
return (left-1);
}
void node_create(struct kdnode *output, double x, double y, double z, int split,double value, struct kdnode* parent)
{
(*output).coord_x = x;
(*output).coord_y = y;
(*output).coord_z = z;
(*output).left_child = NULL;
(*output).right_child = NULL;
(*output).split = split;
(*output).value = value;
(*output).parent = parent;
}
void build_kdtree(struct kdnode* input_node, double** points, int countdirec, int* size,int a, int b, int* record)
{
/* for (int i=0; i< 100; i++)
{
printf("%d,",i);
for (int j=0; j<3; j++)
{
printf("%f,",points[i][j]);
}
printf("\n");
}
printf("\n");*/
if (b<=a)
{
struct kdnode node;
node_create(&node, points[a][0], points[a][1], points[a][2], countdirec, points[a][3], input_node);
int direct = countdirec;
// printf("the last , %d\n",direct);
printf("a point is:%d,%d\n",a,b);
*record = *record + 1;
switch (direct) {
case 0:
if (input_node->coord_x>=points[a][0])
{
(*input_node).left_child = (struct kdnode*) malloc(sizeof(struct kdnode));
// (*input_node).right_child = NULL;
memcpy((*input_node).left_child, &node,sizeof(struct kdnode));
printf("node:%f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("left child:%f,%f,%f\n",points[a][0], points[a][1], points[a][2]);
// printf("%d\n",direct);
}else{
(*input_node).right_child = (struct kdnode*) malloc(sizeof(struct kdnode));
// (*input_node).left_child = NULL;
memcpy((*input_node).right_child, &node,sizeof(struct kdnode));
printf("node:%f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("right child:%f,%f,%f\n",points[a][0], points[a][1],points[a][2]);
// printf("%d\n",direct);
}
break;
case 1:
if (input_node->coord_y>=points[a][1])
{
(*input_node).left_child = (struct kdnode*) malloc(sizeof(struct kdnode));
// (*input_node).right_child = NULL;
memcpy((*input_node).left_child, &node,sizeof(struct kdnode));
printf("node:%f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("left child:%f,%f,%f\n",points[a][0], points[a][1], points[a][2]);
printf("%d\n",direct);
}else{
(*input_node).right_child = (struct kdnode*) malloc(sizeof(struct kdnode));
// (*input_node).left_child = NULL;
memcpy((*input_node).right_child, &node,sizeof(struct kdnode));
printf("node:%f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("right child:%f,%f,%f\n",points[a][0], points[a][1], points[a][2]);
// printf("%d\n",direct);
}
break;
case 2:
if (input_node->coord_z>=points[a][2])
{
(*input_node).left_child = (struct kdnode*) malloc(sizeof(struct kdnode));
memcpy((*input_node).left_child, &node,sizeof(struct kdnode));
printf("node:%f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("left child:%f,%f,%f\n",points[a][0], points[a][1], points[a][2]);
// printf("%d\n",direct);
}else{
(*input_node).right_child = (struct kdnode*) malloc(sizeof(struct kdnode));
memcpy((*input_node).right_child, &node,sizeof(struct kdnode));
printf("node:%f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("right child:%f,%f,%f\n",points[a][0], points[a][1], points[a][2]);
// printf("%d\n",direct);
}
break;
default:
printf("error occurs when creating the leaf!\n");
exit(0);
break;
}
return;
}
/* if ((b-a+1) == 2)
{
struct kdnode node1;
struct kdnode node2;
node_create(&node1, points[0][0], points[0][1], countdirec, points[0][2], NULL, NULL, input_node);
node_create(&node1, points[1][0], points[1][1], countdirec, points[1][2], NULL, NULL, input_node);
if (points[1][countdirec] > points[0][countdirec])
{
input_node->left_child = &node1;
input_node->right_child = &node2;
}else{
input_node->right_child = &node2;
input_node->right_child = &node1;
}
return;
}*/
int direct = countdirec;
direct= (direct+1) % 3;
double value = points[b+1][direct];
printf("the value is: %f\n",value);
int split_index =0;
split_index = reorder(points, value, direct,a,b);
struct kdnode leftnode;
struct kdnode rightnode;
double left_midpoint[5]={0,0,0,0,0};
double right_midpoint[5]={0,0,0,0,0};
bool hasleft = true;
bool hasright = true;
if (split_index < a){
hasleft = false;
}
if (split_index >= b)
{
hasright = false;
}
printf("a point is:%d,%d,%d\n",a,split_index,b);
if (hasleft)
{
if (split_index == a)
{
// printf("node %f,%f,%f\n",input_node->coord_x,input_node->coord_y,input_node->coord_z);
// printf("left child:%f,%f,%f\n",points[a][0],points[a][1],points[a][2]);
// printf("a:%d,b:%d\n",a,split_index);
build_kdtree(input_node, points, direct, size,a,split_index,record);
}else{
// printf("a :%d,b: %d\n",a,b);
// printf("find randon from %d to %d",a,split_index);
printf("left normal\n");
RandomSelect(left_midpoint, points, size, direct,a,split_index);
printf("node %f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("left child:%f, %f, %f\n",left_midpoint[0],left_midpoint[1],left_midpoint[2]);
// printf("%d\n",direct);
// printf("a:%d,b:%d\n",a,split_index-1);
node_create(&leftnode, left_midpoint[0], left_midpoint[1], left_midpoint[2], direct, left_midpoint[3], input_node);
(*input_node).left_child = (struct kdnode*) malloc(sizeof(struct kdnode));
memcpy((*input_node).left_child, &leftnode,sizeof(struct kdnode));
*record = *record + 1;
build_kdtree((*input_node).left_child, points, direct, size,a,split_index-1,record);
}
}
// printf("recording:%d\n\n",*record);
printf("a point is:%d,%d,%d\n",a,split_index,b);
if (hasright)
{
if (b == split_index+1)
{
// printf("node %f,%f,%f\n",input_node->coord_x,input_node->coord_y,input_node->coord_z);
// printf("right child:%f,%f,%f\n",points[b][0],points[b][1],points[b][2]);
// printf("a:%d,b:%d\n",split_index+1,b);
build_kdtree(input_node, points, direct, size,split_index+1,b,record);
}else{
// printf("a point is:%d,%d,%d\n",a,split_index,b);
// printf("find randon from %d to %d",split_index+1,b);
printf("the right normal\n");
RandomSelect(right_midpoint, points, size, direct,split_index+1,b);
printf("node %f,%f,%f,",input_node->coord_x,input_node->coord_y,input_node->coord_z);
printf("right child:%f, %f,%f\n",right_midpoint[0],right_midpoint[1],right_midpoint[2]);
// printf("%d\n",direct);
// printf("a:%d,b:%d\n",split_index+1,b-1);
node_create(&rightnode, right_midpoint[0], right_midpoint[1],right_midpoint[2],direct, right_midpoint[3], input_node);
(*input_node).right_child = (struct kdnode*) malloc(sizeof(struct kdnode));
memcpy((*input_node).right_child, &rightnode,sizeof(struct kdnode));
*record = *record + 1;
build_kdtree((*input_node).right_child, points, direct, size,split_index+1,b-1,record);
}
}
return;
}
void kd_search(struct kdnode *node, int* a)
{
if (node)
{
printf("the node is:%f,%f,%f\n",(node->coord_x-1010000),(node->coord_y-1249900),(node->coord_z-700));
// printf("%d\n",*a);
*a = *a + 1;
kd_search(node->left_child, a);
kd_search(node->right_child,a);
}else{
return;
}
}
void kd_delete(struct kdnode* node)
{
if (node !=NULL )
{
if (node->left_child != NULL)
{
kd_delete(node->left_child);
free(node);
}
if (node->right_child != NULL)
{
kd_delete(node->right_child);
free(node);
}
}else return;
}
struct kdtree kdtree_create (int k, double** pointSet)
{
if (! (k > 0))
{
printf ("K must be larger than 0");
exit(0);
}
struct kdtree tree;
/* double tem_minx = 10000.0;
double tem_maxx = 0.0;
double tem_miny = 10000.0;
double tem_maxy = 0.0;
for (int i=0 ; i<col ; i++)
{
if (tem_maxy < pointSet[i][1])
{
tem_maxy = pointSet[i][1];
}
if (tem_miny > pointSet[(row-1)*col+i][1])
{
tem_miny = pointSet[(row-1)*col+i][1];
}
}
for (int i=0 ; i<row ; i++)
{
if (tem_minx > pointSet[i*col][0])
{
tem_minx = pointSet[i*col][0];
}
if (tem_maxx < pointSet[(i+1)*col-1][0])
{
tem_maxx = pointSet[(i+1)*col-1][0];
}
}
tree.boundary[0] = tem_minx;
tree.boundary[1] = tem_miny;
tree.boundary[2] = tem_maxx;
tree.boundary[3] = tem_maxy;
*/
tree.demension = k;
// tree.col = col;
// tree.row = row;
int remain_size = 100;
int b = 99;
double midpoint[5]={0,0,0,0,0};
int recording = 1;
RandomSelect(midpoint, pointSet, &remain_size,0,0,b);
b--;
struct kdnode root;
root.coord_x = midpoint[0];
root.coord_y = midpoint[1];
root.coord_z = midpoint[2];
root.value = midpoint[3];
int count_direc=2;
build_kdtree(&root, pointSet, count_direc, &remain_size,0,b,&recording);
tree.root = &root;
int num = 1;
kd_search(&root,&num);
printf("%d\n",num);
return tree;
}
void kd_free(struct kdtree* tree)
{
}
void kd_clean(struct kdtree* tree)
{
}
void kd_insert(struct kdtree* tree, double x, double y, void* value)
{
}
void kd_nearest(struct kdtree* tree, double x, double y)
{
}
void txt_point_reader(const char *filename, double**points)
{
FILE *fp;
size_t len = 0;
ssize_t read1;
char *line1 = NULL;
fp = fopen(filename,"r");
printf("open file %s\n",filename);
int i = 0;
if (fp == NULL)
{
printf("Can not find file\n");
exit (EXIT_FAILURE);
}
const char s[2] = ",";
double token1[4];
read1 = getline(&line1, &len, fp);
read1 = getline(&line1, &len, fp);
token1[0] = atof(strtok(line1,s));
token1[1] = atof(strtok(NULL,s));
token1[2] = atof(strtok(NULL,s));
token1[3] = atof(strtok(NULL,s));
points[i][0] = token1[0];
points[i][1] = token1[1];
points[i][2] = token1[2];
points[i][3] = token1[3];
i++;
while (i < 100)
{
read1 = getline(&line1, &len, fp);
token1[0] = atof(strtok(line1,s));
token1[1] = atof(strtok(NULL,s));
token1[2] = atof(strtok(NULL,s));
token1[3] = atof(strtok(NULL,s));
if ((token1[0] != points[i-1][0]) & (token1[1] != points[i-1][0]) & (token1[2] != points[i-1][0]))
{
points[i][0] = token1[0];
points[i][1] = token1[1];
points[i][2] = token1[2];
points[i][3] = token1[3];
i++;
}
}
fclose(fp);
if (line1)
free(line1);
return;
}
int main(int argc, const char * argv[]) {
double ** pointtest;
pointtest = (double**)malloc(100*sizeof(double*));
for (int i=0; i<100; i++)
{
pointtest[i] = (double*)malloc(4*sizeof(double));
}
txt_point_reader("/Users/lixu/workplace/Lidar/kdtree/test2/test2/test.txt",pointtest);
for (int i=0; i< 100; i++)
{
for (int j=0; j<4; j++)
{
printf("%f,",pointtest[i][j]);
}
printf("\n");
}
kdtree_create(3, pointtest);
//free the memory
for (int i =0; i<100;i++)
free(pointtest[i]);
free(pointtest);
return 0;
}
<file_sep>#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef struct {
int row,col;
double ** m;
} mat;
mat* matrix_init(int row, int col)
{
mat* new_ma = malloc(sizeof(mat));
new_ma->m = malloc(sizeof(double*)*row);
int i;
for (i=0; i<row; i++)
{
new_ma->m[i] = calloc(sizeof(double),col);
}
new_ma->row = row;
new_ma->col = col;
return new_ma;
}
mat* matrix_copy(int row, int col,mat* input)
{
if(input->row != row || input->col != col)
{
printf("input matrix is not %d * %d\n",row,col);
exit(0);
}
mat* new_ma;
new_ma = matrix_init(row,col);
int i,j;
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
{
new_ma->m[i][j] = input->m[i][j];
}
}
return new_ma;
}
// get the nth col of matrix, need be freed outside the function
double* get_col(mat* input,int n)
{
int row = input->row;
double *tmp = malloc(sizeof(double)*row);
int i;
for (i=0; i<row; i++)
{
tmp[i] = input->m[i][n];
}
return tmp;
}
// mat m[i][j] = m[j][i]
void matrix_transpose(mat * input)
{
int i,j;
if (input->row == input->col)
{
for (i=0;i<input->row;i++)
{
for(j=0;j<i;j++)
{
double tmp = input->m[i][j];
input->m[i][j] = input->m[j][i];
input->m[j][i] = tmp;
}
}
}else{
printf("can not transpose matrix\n");
}
}
//vector a = a+b
void vector_add(double *a, double *b,int n)
{
if(sizeof(a) != sizeof(b))
{
printf("two vector can not add up\n");
}else{
int i;
for (i=0;i<n;i++)
{
a[i] += b[i];
}
}
}
// vector a = a * s
void vector_mul(double *a, double s, int n)
{
int i;
for(i=0;i<n;i++)
{
a[i] = a[i] * s;
}
}
// matrix a = a+b
void matrix_add(mat* a, mat* b)
{
if (a->row != b->row || a->col != b-> col)
{
printf("two matrix can not add up.\n");
}else{
int i,j;
for (i=0;i<a->row;i++)
{
for(j=0;j<a->col;j++)
{
a->m[i][j] = a->m[i][j]+b->m[i][j];
}
}
}
}
// mat a * mat b
mat* matrix_mul(mat* input1, mat* input2)
{
int i,j,k;
mat* result = matrix_init(input1->row,input2->col);
if (input1->col == input2->row)
{
for (i=0;i<input1->row;i++)
{
for(j=0;j<input2->col;j++)
{
double tmp=0;
for(k=0;k<input1->col;k++)
{
tmp = tmp+(input1->m[i][k])*(input2->m[k][j]);
}
result->m[i][j] = tmp;
}
}
}else{
printf("col of m1 and row of m2 is not equal.\n");
}
return result;
}
// generate [I,0][0,x]
mat * matrix_reflector(mat *a, int n)
{
mat *result = matrix_init(a->row,a->col);
int i,j,k;
for (i=0;i<n;i++)
{
result->m[i][i] = 1;
}
for (j=n;j<a->row;j++)
{
for(k=n;k<a->col;k++)
{
result->m[j][k] = a->m[j][k];
}
}
return result;
}
//||input|| a double vector
double vnorm(double* input,int num)
{
int i;
double tmp=0;
for(i=0;i<num;i++)
{
tmp += input[i]*input[i];
}
return sqrt(tmp);
}
// I - 2 * v * v^T
mat *I_mul(double *v,int n)
{
mat *result = matrix_init(n,n);
int i,j;
for (i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
result->m[i][j] = -2*v[i]*v[j];
}
}
for (i=0;i<n;i++)
result->m[i][i] = 1+result->m[i][i];
return result;
}
void matrix_free(mat* input)
{
if(input->row && input->col)
{
int i;
for(i=0; i<input->row; i++)
{
free(input->m[i]);
}
free(input->m);
free(input);
}else{
printf("can not free matrix\n");
exit(0);
}
}
void matrix_show(mat *m)
{
int i,j;
for (i=0;i<m->row;i++)
{
for(j=0;j<m->col;j++)
{
printf("%f,",m->m[i][j]);
}
printf("\n");
}
}
void householder(mat *m, mat *R, mat *Q)
{
int i,j,k;
mat *q[m->row];
mat *tmp1 = m;
mat * tmp2;
// some where need to be parallized
// base on row cutting, column cutting or matrix cutting
double *e = malloc(sizeof(double)*(m->row));
double *n_col;
double n_norm;
for (i=0;i<m->row && i<m->col; i++)
{
tmp2 = matrix_reflector(tmp1,i);
if (tmp1 != m) matrix_free(tmp1);
tmp1 = tmp2;
n_col = get_col(tmp1,i);
n_norm = vnorm(n_col,m->row);
n_norm = (m->m[i][i]<0) ? -n_norm:n_norm;
for(j =0; j<m->row;j++){e[j]=0;}
e[i] = 1;
vector_mul(e,n_norm,m->row);
vector_add(n_col,e,m->row);
n_norm = vnorm(n_col,m->row);
vector_mul(n_col,(double)1/n_norm,m->row);
q[i]=I_mul(n_col,m->row);
tmp2 = matrix_mul(q[i],tmp1);
free(n_col);
if (tmp1!=m) matrix_free(tmp1);
tmp1 = tmp2;
}
free (e);
matrix_free(tmp1);
mat *tmp3=m;
mat *tmp4;
mat* tmp5=q[0];
for (i=0;i<m->row && i<m->col;i++)
{
if (i!=0) matrix_mul(tmp5,q[i]);
tmp4 = matrix_mul(q[i],tmp3);
if (tmp3!=m) matrix_free(tmp3);
tmp3 = tmp4;
matrix_show(tmp3);
}
R = tmp3;
matrix_show(tmp5);
}
int main(int argc, char* argv[])
{
double in[][3] = {
{ 12, -51, 4},
{ 6, 167, -68},
{ -4, 24, -41},
{ -1, 1, 0},
{2,0,3},
};
mat* x = matrix_init(5,3);
int i,j,k;
for (i=0;i<5;i++)
{
for(j=0;j<3;j++)
{
x->m[i][j] = in[i][j];
}
}
mat *R,*Q;
householder(x,R,Q);
matrix_free(x);
}
<file_sep>#include "stdio.h"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <unordered_map>
using namespace std;
class Observer{
public:
virtual ~Observer(){};
virtual void Update() = 0;
protected:
Observer(){};
};
class Subject {
public:
virtual ~Subject(){};
virtual void Register(Observer* observer){
observers_.push_back(observer);
};
virtual bool Remove(Observer* observer) {
bool found = false;
for (int i=0; i < observers_.size(); i++){
if (observers_[i] == observer){
found = true;
observers_.erase(observers_.begin() + i);
}
}
return found;
};
virtual void Notify(){
for (Observer* pt : observers_){
pt->Update();
}
};
protected:
Subject(){};
private:
std::vector<Observer*> observers_;
};
class Timer : public Subject {
public:
Timer(): timestamp_(0){};
int GetHour(){
return timestamp_ / 3600;
};
int GetMinute(){
return (timestamp_ % 3600) / 60;
};
int GetSecond() {
return timestamp_ % 60;
};
void Tick(){
timestamp_ ++;
Subject::Notify();
};
private:
int timestamp_;
};
class DigitClock : public Observer {
public:
DigitClock(Timer* timer){
timer_ = timer;
timer_->Register(this);
};
virtual ~DigitClock(){
timer_->Remove(this);
};
void Update() override {
int hour = timer_->GetHour();
int minute = timer_->GetMinute();
int second = timer_->GetSecond();
std::cout << "Hour: " << hour << " Minute: " << minute << " Second: " << second << std::endl;
}
private:
Timer* timer_;
};
class AnalogClock : public Observer{
public:
AnalogClock(Timer* timer){
timer_ = timer;
timer_->Register(this);
};
virtual ~AnalogClock(){
timer_->Remove(this);
};
void Update() override {
int hour = timer_->GetHour();
int minute = timer_->GetMinute();
int second = timer_->GetSecond();
int angle = hour * 30;
std::cout << "Angle: " << angle << std::endl;
}
private:
Timer* timer_;
};
int main(int argc, char** argv) {
Timer* timer = new Timer();
DigitClock* dclock = new DigitClock(timer);
AnalogClock* aclock = new AnalogClock(timer);
timer->Tick();
free(dclock);
free(aclock);
free(timer);
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class Context {
public:
Context() = default;
virtual ~Context();
virtual LookUp(const char*) const;
virtual Assign(BoolExpInterface*, bool);
};
class BoolExpInterface {
public:
virtual ~BoolExpInterface();
virtual bool Eval() = 0;
virtual BoolExpInterface* Replace(const char*, BoolExpInterface&) = 0;
virtual BoolExpInterface* Copy() const = 0;
protected:
BoolExpInterface() = default;
};
class VariableBool : public BoolExpInterface {
public:
VariableBool(const string& name):name_(name){};
virtual ~VariableBool();
protected:
string name_;
};
int main(int argc, char **argv) {
string bool_str = "(true and X) or (Y and (not X))";
BoolExpInterface* x = new VariableBool("X");
BoolExpINterface* y = new VariableBool("Y");
}
<file_sep>import sys
import collections
from node import node, bi_node
from DecisionTree import *
import random
forest_size = 100
#split the node based on the split info
def random_split (data,keys,n,depth):
if not keys:
n.is_leaf = True
return n
left_info = n.split_value['left']
right_info = n.split_value['right']
split_key = n.split_key
left_data = [row for row in data if row[split_key] in left_info]
right_data = [row for row in data if row[split_key] in right_info]
if left_data:
left_label = set([row['label'] for row in left_data])
if right_data:
right_label = set([row['label'] for row in right_data])
if ((not left_data) or (not right_data)):
n.split_key = None
n.split_value = None
n.is_leaf = True
n.classification = to_determinate(left_data + right_data)
return n
if (len(left_label) == 1 or len(keys) == 1):
left_child = bi_node(True,None,None, n,None,None,depth+1)
if len(left_label) == 1:
left_child.classification = list(left_label)[0]
if len(keys) == 1:
left_child.classification = to_determinate(left_data)
n.left = left_child
else:
random.shuffle(keys)
random_keys = keys[0:(int(len(keys)*0.6+1))]
split_info = get_split1([left_data,random_keys])
new_keys = [x for x in keys if x != split_info['index']]
left_child = bi_node(False,split_info['index'], split_info['value'],n,None,None,depth+1)
n.left = split1(left_data,new_keys,left_child,depth+1)
if (len(right_label) == 1 or len(keys) == 1):
right_child = bi_node(True,None,None, n,None,None,depth+1)
if len(right_label) == 1:
right_child.classification = list(right_label)[0]
if len(keys) == 1:
right_child.classification = to_determinate(right_data)
n.right = right_child
else:
random.shuffle(keys)
random_keys = keys[0:int(len(keys)*0.6+1)]
split_info = get_split1([right_data,keys])
new_keys = [x for x in keys if x != split_info['index']]
right_child = bi_node(False,split_info['index'], split_info['value'],n,None,None,depth+1)
n.right = split1(right_data,new_keys,right_child,depth+1)
return n
def forest_builder(data_dic):
keys = data_dic[1]
random.shuffle(keys)
random_key = keys[0:int(len(keys)*0.6+1)]
split_info = get_split1([data_dic[0],random_key])
root = bi_node(False,split_info['index'], split_info['value'], None,None,None,0)
keys = [i for i in data_dic[1] if i != split_info['index']]
return random_split(data_dic[0],keys,root,0)
def forest_predict (forest, data_dic):
data = data_dic[0]
keys = data_dic[1]
labels = [row['label'] for row in data]
label =list(set(labels))
l = len(label)
result = collections.Counter()
for i in range(0,l):
sub_dic = collections.Counter()
for j in range(0,l):
sub_dic[label[j]]=0
result[label[i]] = sub_dic
count =0
for row in data:
count += 1
clas = []
for one_tree in forest:
tmp_node = one_tree
while (not tmp_node.is_leaf):
split_index = tmp_node.split_key
split_value = tmp_node.split_value
if (row[split_index] in split_value['left']):
tmp_node = tmp_node.left
else:
tmp_node = tmp_node.right
clas.append(tmp_node.classification)
final_clas = max(set(clas),key=clas.count)
result[row['label']][final_clas] += 1
return result
if __name__ == '__main__':
train_file = sys.argv[1]
test_file = sys.argv[2]
train_data = filereader(train_file)
test_data = filereader(test_file)
forest = []
count = 0
for i in range(0,forest_size):
print count,"tree"
count +=1
forest.append(forest_builder(train_data))
# show_dTree(forest[i],'root')
result = forest_predict(forest,test_data)
sum_top = 0
total = 0
for row in result:
sum_top += result[row][row]
for k in result[row]:
total += result[row][k]
print sum_top/(float)(total)
print result
<file_sep>This is the code for big dataset learning.
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Point.h"
#include "KDTree.h"
void KDNode_init(KDNode *knode)
{
knode->dims = 0;
knode->axis = 0;
knode->left = NULL;
knode->right = NULL;
knode->data = NULL;
knode->pivot = 0.0f;
}
void KDList_init(KDList *klist,KDNode *node, double dis)
{
klist->node = node;
klist->dis = dis;
klist->next = NULL;
klist->last = NULL;
}
void KDList_insert(KDList **head, KDList **node)
{
if (*head == NULL)
{
// printf("insert is NULL %f\n", (*node)->dis);
*head = malloc(sizeof(KDList));
memcpy(*head,*node,sizeof(KDList));
(*head)->next = NULL;
(*head)->last = *head;
return;
}
// printf("insert node %f to",(*node)->dis);
KDList *search = *head;
int tmp = 0;
while (search != NULL)
{
// printf("%f,%f\n",(*node)->dis , search->dis);
if ((*node)->dis < search->dis)
{
(*node)->last = search->last;
(*node)->next = search;
if (tmp == 0)
{
*head = *node;
search->last->next = NULL;
}else{
search->last->next = *node;
}
search->last = *node;
return;
}else{
tmp = 1;
search = search->next;
}
}
(*node)->next= NULL;
(*node)->last = (*head)->last;
(*head)->last->next = *node;
(*head)->last = *node;
return;
}
void KDList_pop(KDList **head, KDList* popnode)
{
if (*head == NULL)
{
// printf("NULL in search path \n");
return;
}
if ((*head)->last == *head)
{
(*head)->last = NULL;
memcpy(popnode,*head, sizeof(KDList));
free (*head);
*head = NULL;
return;
}
KDList *tmp = *head;
memcpy(popnode, *head, sizeof(KDList));
*head = (*head)->next;
(*head)->last = tmp->last;
free(tmp);
tmp->last = NULL;
return;
}
void KDList_free(KDList** head)
{
if (*head == NULL)
return;
KDList *tmp = *head;
while (tmp->next != NULL)
{
tmp = tmp->next;
free(tmp->last);
tmp->last = NULL;
}
free(tmp);
return;
}
void list2array(Point* array, KDList* head)
{
KDList* tmp =head;
int count = 0;
while (tmp != NULL){
array[count].x = tmp->node->data->x;
array[count].y = tmp->node->data->y;
array[count].z = tmp->node->data->z;
tmp = tmp->next;
count ++;
// printf("count:%d\n",count);
}
KDList_free(&head);
}
int KDNode_insert (Point *point_list, int depth, int dims, int point_count, KDNode* knode)
{
knode->dims = dims;
knode->axis = depth % dims;
int l_depth = 0;
int r_depth = 0;
int depth_flag = 0;
if (point_count == 1)
{
knode->data = malloc (sizeof(Point));
Point_copy (knode->data,point_list);
depth_flag = depth;
}else{
int piv_idx = floor(point_count / 2);
switch(knode->axis)
{
case(0):
qsort(point_list, point_count, sizeof(Point), Point_compareX);
knode->pivot = (point_list[piv_idx].x + point_list[piv_idx+1].x) / 2;
break;
case(1):
qsort(point_list, point_count, sizeof(Point), Point_compareY);
knode->pivot = (point_list[piv_idx].y + point_list[piv_idx+1].y) / 2;
break;
case(2):
qsort(point_list, point_count, sizeof(Point), Point_compareZ);
knode->pivot = (point_list[piv_idx].z + point_list[piv_idx+1].z) / 2;
break;
default:
printf("DIM ERROR: failed to recognize axis %i\n",knode->axis);
break;
}
int new_count = point_count / 2;
int add_off = 0;
if (point_count % 2)
add_off ++;
knode->left = malloc(sizeof(KDNode));
KDNode_init(knode->left);
knode->right = malloc(sizeof(KDNode));
KDNode_init(knode->right);
l_depth = KDNode_insert(point_list, depth+1, dims, new_count,knode->left);
r_depth = KDNode_insert(&point_list[new_count],depth+1,dims,new_count+add_off,knode->right);
depth_flag = l_depth > r_depth ? l_depth : r_depth;
}
return depth_flag;
}
int KDNode_insert_node(Point *point_list, int depth, int dims, int point_count, KDNode* knode)
{
//printf("Allocating node at depth %i, pts: %i\n", depth, point_count);
//KDNode *knode = malloc(sizeof(KDNode));
//printf("Successfully allocated node\n");
//KDNode_init(knode);
knode->dims = dims;
knode->axis = depth % dims;
int l_depth = 0;
int r_depth = 0;
int depth_flag = 0;
//knode->left = NULL;
//knode->right = NULL;
//knode->data = NULL;
if (point_count == 1)
{
knode->data = malloc(sizeof(Point));
Point_copy(knode->data, point_list);
depth_flag = depth;
} else {
int piv_idx = floor(point_count / 2);
int new_count = point_count / 2 ;
// printf("point_count:%d\n",point_count);
switch(knode->axis)
{
case(0):
qsort(point_list, point_count, sizeof(Point), Point_compareX);
// printf("Creating pivot\n");
while ((new_count<point_count-1) && (point_list[new_count].x == point_list[new_count+1].x))
{
new_count++;
}
// printf("x new_count:%d\n",new_count);
knode->pivot = (point_list[piv_idx].x + point_list[piv_idx+1].x) / 2;
break;
case(1):
qsort(point_list, point_count, sizeof(Point), Point_compareY);
// printf("Creating pivot\n");
while ((new_count<point_count-1)&&(point_list[new_count].y == point_list[new_count+1].y))
{
new_count++;
}
// printf("y new_count:%d\n",new_count);
knode->pivot = (point_list[piv_idx].y + point_list[piv_idx+1].y) / 2;
break;
case(2):
qsort(point_list, point_count, sizeof(Point), Point_compareZ);
while ((new_count<point_count-1)&&(point_list[new_count].z == point_list[new_count+1].z))
{
new_count++;
}
// printf("z new_count:%d\n",new_count);
// printf("Creating pivot\n");
knode->pivot = (point_list[piv_idx].z + point_list[piv_idx+1].z) / 2;
break;
default:
printf("DIM ERROR: failed to recognize axis %i\n", knode->axis);
break;
}
// TODO: Check how this works on even and odd subsets
knode->data = malloc(sizeof(Point));
Point_copy(knode->data,&point_list[new_count]);
//int add_off = 0;
//if (point_count % 2 == 0) add_off++;
knode->left = malloc(sizeof(KDNode));
KDNode_init(knode->left);
//printf("left \n");
l_depth = KDNode_insert_node(point_list, depth+1, dims, new_count, knode->left);
if ((point_count - new_count - 1) != 0 )
{
knode->right = malloc(sizeof(KDNode));
KDNode_init(knode->right);
//printf("right \n");
r_depth = KDNode_insert_node(&point_list[new_count+1], depth+1, dims, point_count-new_count-1, knode->right);
}
// Set new depth flag
depth_flag = l_depth > r_depth ? l_depth : r_depth;
}
return depth_flag;
}
void KDList_full_insert(KDList **head,KDList **node)
{
if (*head == NULL)
{
return;
}
printf("start full insert\n");
KDList *search = *head;
int tmp = 0;
KDList *last_node = (*head)->last;
while (search != NULL)
{
if ((*node)->dis < (search)->dis)
{
(*node)->last = search->last;
(*node)->next = search;
if (tmp ==0)
{
*head = *node;
search->last->next = NULL;
}else{
search->last->next = *node;
}
search->last = *node;
(*head)->last = (*head)->last->last;
free(last_node);
(*head)->last->next = NULL;
return;
}else{
tmp = 1;
search = search->next;
}
}
(*node)->next= NULL;
(*node)->last = (*head)->last;
(*head)->last->next = *node;
(*head)->last = *node;
(*head)->last = (*head)->last->last;
free(last_node);
(*head)->last->next = NULL;
return;
}
void KDNode_search_knn(KDNode* knode, Point *pt, Point *best,int k)
{
if (knode == NULL )
{
return;
}
double thred_distance = 9999999999.0;
KDList* search_path=NULL;
KDList* neighbor = NULL;
int best_count = 0;
search_path = malloc(sizeof(KDList));
KDList* near = malloc(sizeof(KDList));
KDList* far = malloc(sizeof(KDList));
KDList* popnode = malloc(sizeof(KDList));
double dis = Point_distance(pt, knode->data);
KDList_init(search_path, knode, dis);
search_path->last = search_path;
int if_insert_popnode = 0;
while (search_path != NULL)
{
KDList_pop(&search_path, popnode);
// printf("the pop node is:%f\n", popnode->dis);
if (popnode->dis < thred_distance)
{
if (best_count < k)
{
KDList_insert(&neighbor,&popnode);
// printf("neighbor:%f\n",popnode->dis);
if_insert_popnode = 1;
best_count ++;
}else{
KDList_full_insert(&neighbor,&popnode);
if_insert_popnode = 1;
// printf("neighbor:%f\n",popnode->dis);
// printf("the head of neigh:%f\n",neighbor->dis);
thred_distance = neighbor->last->dis;
// printf("new thredhold is:%f\n",thred_distance);
}
}
printf("larger than the bigest element in list\n");
switch(popnode->node->axis)
{
case(0):
if (pt->x <= popnode->node->data->x)
{
if (popnode->node->left)
{
KDList_init(near, popnode->node->left, Point_distance(pt, popnode->node->left->data));
}else{
free(near);
near = NULL;
}
if (popnode->node->right)
{
KDList_init(far, popnode->node->right, Point_distance(pt, popnode->node->right->data));
}else{
free(far);
far = NULL;
}
}else{
if (popnode->node->left)
{
KDList_init(far, popnode->node->left, Point_distance(pt, popnode->node->left->data));
}else{
free(far);
far = NULL;
}
if (popnode->node->right)
{
KDList_init(near, popnode->node->right, Point_distance(pt, popnode->node->right->data));
}else{
free(near);
near = NULL;
}
}
break;
case(1):
if (pt->y <= popnode->node->data->y)
{
if (popnode->node->left)
{
KDList_init(near, popnode->node->left, Point_distance(pt, popnode->node->left->data));
}else{
free(near);
near = NULL;
}
if (popnode->node->right)
{
KDList_init(far, popnode->node->right, Point_distance(pt, popnode->node->right->data));
}else{
free(far);
far = NULL;
}
}else{
if (popnode->node->left)
{
KDList_init(far, popnode->node->left, Point_distance(pt, popnode->node->left->data));
}else{
free(far);
far = NULL;
}
if (popnode->node->right)
{
KDList_init(near, popnode->node->right, Point_distance(pt, popnode->node->right->data));
}else{
free(near);
near = NULL;
}
}
break;
case(2):
if (pt->z <= popnode->node->data->z)
{
if (popnode->node->left)
{
KDList_init(near, popnode->node->left, Point_distance(pt, popnode->node->left->data));
}else{
free(near);
near = NULL;
}
if (popnode->node->right)
{
KDList_init(far, popnode->node->right, Point_distance(pt, popnode->node->right->data));
}else{
free(far);
far = NULL;
}
}else{
if (popnode->node->left)
{
KDList_init(far, popnode->node->left, Point_distance(pt, popnode->node->left->data));
}else{
free(far);
far = NULL;
}
if (popnode->node->right)
{
KDList_init(near, popnode->node->right, Point_distance(pt, popnode->node->right->data));
}else{
free(near);
near = NULL;
}
}
break;
default:
printf("can not recognize the axis\n");
break;
}
// printf("find the near and far\n");
if(near)
{
// printf("near is:%f\n",near->dis);
KDList_insert(&search_path, &near);
// printf("insert near to the list\n");
near = NULL;
near = malloc(sizeof(KDList));
}else{
// printf("no near\n");
near = malloc(sizeof(KDList));
}
if(far)
{
if (far->dis < thred_distance)
{
printf("far is:%f\n",far->dis);
KDList_insert(&search_path, &far);
far = NULL;
far = malloc(sizeof(KDList));
}
}else{
// printf("no far\n");
far = malloc(sizeof(KDList));
}
if (if_insert_popnode ==1)
{
popnode = NULL;
popnode = malloc(sizeof(KDList));
}
if_insert_popnode = 0;
}
free(popnode);
list2array(best,neighbor);
return;
}
void KDNode_search_n(KDNode* knode, Point *pt, Point *best)
{
if (knode == NULL)
{
// printf("The knode is NULL in search function");
return;
}
KDNode search_path[2048];
KDNode* p_search = malloc(sizeof(KDNode));
memcpy(p_search, knode, sizeof(KDNode));
int path_index = 0;
while (p_search != NULL)
{
search_path[path_index] = *p_search;
printf("p_search:%f,%f,%f, axis:%d\n",p_search->data->x,p_search->data->y,p_search->data->z,p_search->axis);
// printf("axis:%d\n",p_search->axis);
// printf("left:%f,right:%f\n",p_search->left->data->x,p_search->right->data->x);
// printf("path:%f,%f,%f\n",search_path[path_index].data->x,search_path[path_index].data->y,search_path[path_index].data->z);
path_index++;
switch(p_search->axis)
{
case (0):
p_search = (pt->x <= p_search->data->x) ? p_search->left : p_search->right;
break;
case (1):
p_search = (pt->y <= p_search->data->y) ? p_search->left : p_search->right;
break;
case (2):
p_search = (pt->z <= p_search->data->z) ? p_search->left : p_search->right;
break;
default:
printf("can not recognize the axis\n");
break;
}
}
printf("path number:%d\n",path_index);
free(p_search);
path_index--;
double radius = Point_distance (pt, best);
// printf("path number:%d\n",path_index);
if (radius > Point_distance (pt,search_path[path_index].data))
{
best->x = search_path[path_index].data->x;
best->y = search_path[path_index].data->y;
best->z = search_path[path_index].data->z;
radius = Point_distance (pt,search_path[path_index].data);
}
// memcpy(best[best_index],search_path[path_index],sizeof(Point));
// best_index ++;
path_index--;
while (path_index > 0)
{
// printf("the index in search loop is:%d\n",path_index);
if (radius > Point_distance (pt,search_path[path_index].data))
{
best->x = search_path[path_index].data->x;
best->y = search_path[path_index].data->y;
best->z = search_path[path_index].data->z;
radius = Point_distance (pt,search_path[path_index].data);
}
// printf("radius:%f\n",radius);
if ((search_path[path_index].data->x > (pt->x - radius) && search_path[path_index].data->x < (pt->x + radius)) || (search_path[path_index].data->y > (pt->y-radius) && search_path[path_index].data->y < (pt->y+radius)) ||(search_path[path_index].data->z > (pt->z-radius) && search_path[path_index].data->z < (pt->z+radius)) )
{
// printf("recursion:\n");
switch(search_path[path_index].axis)
{
case (0):
if (pt->x <= knode->data->x)
{
KDNode_search_n(search_path[path_index].right, pt , best);
}else{
KDNode_search_n(search_path[path_index].left, pt, best);
}
break;
case (1):
if (pt->y <= knode->data->y)
{
KDNode_search_n(search_path[path_index].right, pt , best);
}else{
KDNode_search_n(search_path[path_index].left, pt, best);
}
break;
case (2):
if (pt->z <= knode->data->z)
{
KDNode_search_n(search_path[path_index].right, pt , best);
}else{
KDNode_search_n(search_path[path_index].left, pt, best);
}
break;
default:
printf("can not recognize the axis\n");
break;
}
//path_index--;
// printf("path number:%d\n",path_index);
}
path_index--;
}
return;
}
Point* KDNode_search(KDNode* knode, Point *pt, Point *best)
{
if (knode->data != NULL)
{
double d_n, d_best;
d_n = Point_distance(pt, knode->data);
d_best = Point_distance(pt, best);
if (d_n < d_best)
return knode->data;
else
return best;
} else { // Search nodes
Point *p1, *p2;
p1 = KDNode_search(knode->left, pt, best);
p2 = KDNode_search(knode->right, pt, best);
double d1, d2, d_best;
d1 = Point_distance(pt, p1);
d2 = Point_distance(pt, p2);
d_best = Point_distance(pt, best);
if (d_best < d1 && d_best< d2)
return best;
else if( d1 < d2 && d2 < d_best)
return p2;
else
return p1;
}
}
void KDNode_delete(KDNode *knode)
{
if (knode != NULL)
{
knode->axis = 0;
knode->dims = 0;
knode->pivot = 0.0f;
if (knode->data != NULL)
{
free(knode->data);
knode->data = NULL;
}
KDNode_delete(knode->left);
KDNode_delete(knode->right);
free(knode);
knode = NULL;
}
}
void KDNode_vis(KDNode *knode,int *k)
{
if (knode != NULL)
{
// printf("the node is:%.3f,%.3f,%.3f",(knode->data)->x,(knode->data)->y,(knode->data)->z);
// if (knode->left)
// printf(" left child is:%.3f,%.3f,%.3f",(knode->left->data)->x,(knode->left->data)->y,(knode->left->data)->z);
// if (knode->right)
// printf(" right child is:%.3f,%.3f,%.3f\n",(knode->right->data)->x,(knode->right->data)->y,(knode->right->data)->z);
*k = (*k)+1;
KDNode_vis(knode->left,k);
KDNode_vis(knode->right,k);
return;
}else{
return;
}
}
<file_sep>import sys
import collections
from node import node,bi_node
import random
#import node.py
def filereader(file_name):
data=[]
keys=[]
with open(file_name) as f:
for l in f:
line = l.strip().split(" ")
tmp = [x.split(':') for x in line]
tmplist = collections.Counter()
if (type(tmp[0][0]) is str):
tmplist['label'] = tmp[0][0]
else:
print "the first element should be label"
exit(1)
for i in tmp[1:]:
tmplist[i[0]] = i[1]
keys.append(i[0])
data.append(tmplist)
return [data,list(set(keys))]
# Get the gini value
#input:
# groups:list for each group, each elem is [] for label
def get_gini(groups):
total_size = float(sum([len(x) for x in groups]))
gini = 0
for group in groups:
size = float(len(group))
if size == 0:
continue
count = collections.Counter(group)
tsum = 0.0
for key in count:
tsum += (float(count[key])/size)*(float(count[key])/size)
gini += (size/total_size)*(1-tsum)
return gini
# get the combination of group base on value
def get_com(labels):
left = []
right = []
length = len(labels)
labels_list = list(set(labels))
if (length == 2):
left.append([labels_list[0]])
right.append([labels_list[1]])
return {'left':left,'right':right}
for i in range(1,length/2+1):
j = 0
com = [0]*i
while (j>=0):
com[j] += 1
if (com[j]>length):
j -= 1
else:
if (j== i-1):
tmp = set([labels_list[index-1] for index in com])
left.append(list(tmp))
right.append(list(labels-tmp))
else:
j +=1
com [j] = com[j-1]
return {'left':left,'right':right}
#get split base on minimum gini value
def get_split1(data_dic):
data = data_dic[0]
keys = data_dic[1]
tmp_dic = collections.Counter()
labels = [row['label'] for row in data]
gini = 1
split_return = {}
for index in keys:
split_attr = [row[index] for row in data]
tmp_dic = get_com(set(split_attr))
left = tmp_dic['left']
right = tmp_dic['right']
for i in range(0,len(left)):
group1 =[]
group2 =[]
for j in range(0,len(split_attr)):
if split_attr[j] in left[i]:
group1.append(labels[j])
if split_attr[j] in right[i]:
group2.append(labels[j])
groups = [group1,group2]
new_gini = get_gini(groups)
if gini > new_gini:
gini = new_gini
split_return = {'index':index,'value':{'left':left[i],'right':right[i]}}
return split_return
#get split base on minimum gini value
def get_split(data_dic):
data = data_dic[0]
keys = data_dic[1]
gini = 1
for index in keys:
split_attr = collections.Counter()
for elem in data:
if split_attr[elem['label']]:
split_attr[elem['label']].append(elem[index])
else:
split_attr[elem['label']] = [elem[index]]
after_group = []
for tmp_key in split_attr:
after_group.append(split_attr[tmp_key])
new_gini = get_gini(after_group)
if gini > new_gini:
gini = new_gini
split_return = index
return split_return
# return the most frequent class in node
def to_determinate(data):
group = [row['label'] for row in data]
return max(set(group),key=group.count)
#split the node based on the split info
def split1 (data,keys,n,depth):
if not keys:
n.is_leaf = True
return n
left_info = n.split_value['left']
right_info = n.split_value['right']
split_key = n.split_key
left_data = [row for row in data if row[split_key] in left_info]
right_data = [row for row in data if row[split_key] in right_info]
if left_data:
left_label = set([row['label'] for row in left_data])
if right_data:
right_label = set([row['label'] for row in right_data])
if ((not left_data) or (not right_data)):
n.split_key = None
n.split_value = None
n.is_leaf = True
n.classification = to_determinate(left_data + right_data)
return n
if (len(left_label) == 1 or len(keys) == 1):
left_child = bi_node(True,None,None, n,None,None,depth+1)
if len(left_label) == 1:
left_child.classification = list(left_label)[0]
if len(keys) == 1:
left_child.classification = to_determinate(left_data)
n.left = left_child
else:
split_info = get_split1([left_data,keys])
new_keys = [x for x in keys if x != split_info['index']]
left_child = bi_node(False,split_info['index'], split_info['value'],n,None,None,depth+1)
n.left = split1(left_data,new_keys,left_child,depth+1)
if (len(right_label) == 1 or len(keys) == 1):
right_child = bi_node(True,None,None, n,None,None,depth+1)
if len(right_label) == 1:
right_child.classification = list(right_label)[0]
if len(keys) == 1:
right_child.classification = to_determinate(right_data)
n.right = right_child
else:
split_info = get_split1([right_data,keys])
new_keys = [x for x in keys if x != split_info['index']]
right_child = bi_node(False,split_info['index'], split_info['value'],n,None,None,depth+1)
n.right = split1(right_data,new_keys,right_child,depth+1)
return n
#split the node based on the split info
def split (data,keys,n,depth):
if not keys:
n.classification = to_determinate(data)
n.is_leaf = True
print depth
return n
split_key = n.split_key
children_data = collections.Counter()
for row in data:
if children_data[row[split_key]]:
children_data[row[split_key]].append(row)
else:
children_data[row[split_key]] = [row]
children = []
for branch in children_data:
child = node(False,branch,None, n,[],depth+1)
split_info = get_split([children_data[branch],keys])
child_lab = list(set([row['label'] for row in children_data[branch]]))
if (len(child_lab) == 1):
child.classification = child_lab[0]
child.is_leaf = True
child.split_key = split_info
child.height = depth+1
new_keys = [i for i in keys if i != split_info]
children.append(split(children_data[branch],new_keys,child,depth+1))
n.children = children
print depth
return n
#show the decision tree
def show_dTree(root,key):
if (root.is_leaf):
print '-'*root.depth,key,root.classification,root.is_leaf
return
else:
count = 0
for child in root.children:
count += 1
print '-'*root.depth,key,root.split_key
show_dTree(child,'node'+str(count))
return
#show the decision tree
def show_dTree1(root,key):
if (root.is_leaf):
print '-'*root.depth,key,root.classification,root.is_leaf
return
else:
print '-'*root.depth,key,root.split_key
show_dTree1(root.left,'left')
show_dTree1(root.right,'right')
return
#build up decision tree
def decision_tree_builder1(data):
split_info = get_split1(data)
root = bi_node(False,split_info['index'],split_info['value'], None,None,None,0)
keys = [i for i in data[1] if i != split_info['index']]
return split1(data[0],keys,root,0)
# show_dTree(root)
#build up decision tree
def decision_tree_builder(data):
split_info = get_split(data)
root = node(False,None,split_info, None,[],0)
keys = [i for i in data[1] if i != split_info]
return split(data[0],keys,root,0)
# show_dTree(root)
# use to predict a new dataset
def predict1 (root, data_dic):
data = data_dic[0]
keys = data_dic[1]
labels = [row['label'] for row in data]
label =list(set(labels))
l = len(label)
result = collections.Counter()
for i in range(0,l):
sub_dic = collections.Counter()
for j in range(0,l):
sub_dic[label[j]]=0
result[label[i]] = sub_dic
for row in data:
tmp_node = root
counting =0
while (not tmp_node.is_leaf):
split_index = tmp_node.split_key
split_value = tmp_node.split_value
if (row[split_index] in split_value['left']):
tmp_node = tmp_node.left
else:
if (row[split_index] in split_value['right']):
tmp_node = tmp_node.right
else:
tmp_node=tmp_node.left
clas = tmp_node.classification
result[row['label']][clas] += 1
return result
# use to predict a new dataset
def predict (root, data_dic):
data = data_dic[0]
keys = data_dic[1]
labels = [row['label'] for row in data]
label =list(set(labels))
l = len(label)
result = collections.Counter()
for i in range(0,l):
sub_dic = collections.Counter()
for j in range(0,l):
sub_dic[label[j]]=0
result[label[i]] = sub_dic
for row in data:
tmp_node = root
counting =0
while (not tmp_node.is_leaf):
is_have = False
for child in tmp_node.children:
if (child.value == row[tmp_node.split_key]):
tmp_node = child
is_have = True
break
if not is_have:
tmp_node = random.choice(tmp_node.children)
break
clas = tmp_node.classification
result[row['label']][clas] += 1
return result
if __name__ == "__main__":
train_file = sys.argv[1]
test_file = sys.argv[2]
train_data = filereader(train_file)
test_data = filereader(test_file)
# print ("training\n")
#print train_data
# print ("testing\n")
# print test_data
# labels = set([elem['1'] for elem in train_data])
if len(train_data[0][0].keys()) > 10 :
tree = decision_tree_builder1(train_data)
result = predict1(tree,test_data)
show_dTree1(tree,'root')
else:
tree = decision_tree_builder(train_data)
show_dTree(tree,'root')
result = predict(tree,test_data)
print result
sum_top = 0
total = 0
for row in result:
sum_top += result[row][row]
for k in result[row]:
total += result[row][k]
print sum_top/(float)(total)
#result = predict(tree,[[{'2': '5', 'label': '3', '1': '3', '4': '2', '6': '2', '8': '2', '3': '1', '5': '1', '7': '1'}],['1','2','3','4','5','6','7','8']])
# gini = get_gini([[1,1,1,1,1,1,1,2,2,2],[1,1,2,2]])
<file_sep>#include <vector>
#include <fstream>
#include <iostream>
#include <typeinfo>
#include <math.h>
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "liblas/liblas.hpp"
#include "ogr_spatialref.h"
#include <cstring>
#include <sstream>
// if the point is the last return
/*class LastReturnFilter: public liblas::FilterI
{
public:
LastReturnFilter();
bool filter (const liblas::Point& p);
private:
LastReturnFilter(LastReturnFilter const& other);
LastReturnFilter& operator=(LastReturnFilter const& rhs);
};
LastReturnFilter::LastReturnFilter( ) : liblas::FilterI(eInclusion){}
bool LastReturnFilter::filter(const liblas::Point& p)
{
bool output = false;
if (p.GetReturnNumber() == p.GetNumberOfReturns()){
output = true;
}
if (GetType() == eExclusion && output == true)
{
output = false;
}else{
output = true;
}
return output;
}
*/
void Raster_writer (char const* out_file, double *data, int row,int col,double topleft_x, double topleft_y)
{
double affine[] = {topleft_x, 1, 0, topleft_y, 0, -1};
const char *pszFormat = "GTiff";
GDALAllRegister();
GDALDriver *poDriver;
char **papszMetadata;
poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
//if( poDriver == NULL )
// exit( 1 );
papszMetadata = poDriver->GetMetadata();
std::cout<< "the input parameter is:"<< out_file << '\n';
if( CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATE, FALSE ) )
printf( "Driver %s supports Create() method.\n", pszFormat );
if( CSLFetchBoolean( papszMetadata, GDAL_DCAP_CREATECOPY, FALSE ) )
printf( "Driver %s supports CreateCopy() method.\n", pszFormat );
GDALDataset *poDstDS;
char **papszOptions = NULL;
std::cout<< row << "," << col <<'\n';
/* for (int i = 0; i< row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << data[i * col + j] << ", ";
}
std::cout << std::endl;
}
*/
poDstDS = poDriver->Create( out_file,col, row, 1, GDT_Float64,papszOptions );
OGRSpatialReference oSRS;
char *pszSRS_WKT = NULL;
GDALRasterBand *poBand;
poDstDS->SetGeoTransform( affine );
oSRS.SetUTM( 15, TRUE );
oSRS.SetWellKnownGeogCS( "NAD83" );
oSRS.exportToWkt( &pszSRS_WKT );
poDstDS->SetProjection( pszSRS_WKT );
CPLFree( pszSRS_WKT );
poBand = poDstDS->GetRasterBand(1);
poBand->RasterIO( GF_Write, 0, 0, col,row,data,col,row, GDT_Float64, 0, 0 );
/*Once we're done, close properly the dataset */
GDALClose( (GDALDatasetH) poDstDS );
/* GDALDatasetH hDstDS;
GDALRasterBandH hBand;
OGRSpatialReferenceH hSRS;
GDALDriverH hDriver;
char *pszSRS_WKT = NULL;
char **papszOptions = NULL;
hDriver = GDALGetDriverByName("GTiff");
hDstDS = GDALCreate(hDriver, out_file, col, row, 1, GDT_Float32, papszOptions);
GDALSetGeoTransform(hDstDS, affine);
hSRS = OSRNewSpatialReference(NULL);
OSRImportFromProj4(hSRS, "+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs");
OSRExportToWkt(hSRS, &pszSRS_WKT);
OSRDestroySpatialReference(hSRS);
GDALSetProjection(hDstDS, pszSRS_WKT);
CPLFree(pszSRS_WKT);
hBand = GDALGetRasterBand(hDstDS,1);
GDALSetRasterNoDataValue(hBand, );
GDALRasterIO(hBand, GF_Write, 0, 0, col, row, data, col, row, GDT_Float32, 0, 0);
GDALClose(hDstDS);
*/
}
double mean_calculator(double *zvalue)
{
double sum = 0;
bool isNull = true;
int count = 0;
for (int i=0; i<10; i++)
{
if (zvalue[i] < DBL_MAX){
sum += zvalue[i];
count += 1;
isNull = false;
}
}
if (isNull){
return 0;
}else{
return (sum/count);
}
}
struct grid
{
int row_num;
int col_num;
double *data;
};
struct raster
{
grid Grid;
char *reference;
double affine [6];
};
int main(int argc, char* argv[] ){
for (int file_count =1; file_count<10; file_count++)
{
int DEM_Resolution = 1;
double *DEM_Raster; // the final dem raster
double **Raster_Zvalue; // the array of z value in each grid
double minX,minY,maxX,maxY;
std::ifstream ifs;
std::stringstream ss;
ss.str("");
ss.clear();
ss << file_count;
char path[1025] = {};
strcat (path,"Jean-Lafitte/LA_Jean-Lafitte_2013_00000");
strcat (path,const_cast<char*>(ss.str().c_str()));
strcat (path,".las");
std::cout << path << '\n';
ifs.open(path,std::ios::in | std::ios::binary);
// {
// std::cout << "Can not open file" << std::endl;
// exit(1);
// }
std::vector<liblas::FilterPtr> filters;
// liblas::FilterPtr lastreturn_filter = liblas::FilterPtr(new LastReturnFilter());
// filters.push_back(lastreturn_filter);
liblas::ReaderFactory f;
liblas::Reader reader = f.CreateWithStream(ifs);
// reader.SetFilters(filters);
liblas::Header const& header = reader.GetHeader();
std::cout << "Compressed: " << (header.Compressed() == true) ? "true":"false";
std::cout << "Signature: " << header.GetFileSignature() << '\n';
std::cout << "Points count:" << header.GetPointRecordsCount() << '\n';
std::cout << "Project ID" << header.GetProjectId() << '\n';
liblas::Bounds<double> CloudBounds = header.GetExtent();
std::cout << "X scale:"<< header.GetMaxX() << "," << header.GetMinX() << '\n';
std::cout << "X offset" << header.GetOffsetX() << '\n';
std::cout << "X Scale" << header.GetScaleX() << '\n';
minX = header.GetMinX();
minY = header.GetMinY();
maxX = header.GetMaxX();
maxY = header.GetMaxY();
int row_num = ceil((maxY - minY) / DEM_Resolution);// * 0.03048);
int col_num = ceil((maxX - minX) / DEM_Resolution);// * 0.03048);
std::cout <<"Output Raster is:" << row_num << "*" << col_num << '\n';
DEM_Raster = new double [row_num * col_num];
Raster_Zvalue = new double* [row_num * col_num];
for (int i=0; i<row_num * col_num ; i++)
{
Raster_Zvalue [i] = new double [10];
}
for (int i=0; i<row_num * col_num; i++)
{
for (int j=0; j<10;j++)
{
Raster_Zvalue[i][j] = DBL_MAX;
}
}
// std::vector<liblas::Point> PointCloud;
while (reader.ReadNextPoint())
{
liblas::Point const& p = reader.GetPoint();
if (p.GetReturnNumber() == p.GetNumberOfReturns())
{
double coord_x = p.GetX();
double coord_y = p.GetY();
double z_value = p.GetZ();
// std::cout << coord_x << "," << coord_y << "," << p.GetReturnNumber() << "," << p.GetNumberOfReturns() << std::endl;
int DEM_coord_y = floor((coord_x - minX) / DEM_Resolution);//* 0.03048);
int DEM_coord_x = floor((coord_y - minY) / DEM_Resolution);//* 0.03048);
// std::cout << DEM_coord_x << "," << DEM_coord_y << '\n';
if (z_value < Raster_Zvalue[DEM_coord_x * col_num + DEM_coord_y][9])
{
for (int m=0 ; m<10; m++)
{
if (z_value < Raster_Zvalue[DEM_coord_x * col_num + DEM_coord_y][m])
{
for (int n=9; n>m; n-- )
{
Raster_Zvalue[DEM_coord_x * col_num + DEM_coord_y][n] = Raster_Zvalue[DEM_coord_x * col_num + DEM_coord_y][n-1];
}
Raster_Zvalue[DEM_coord_x * col_num + DEM_coord_y][m] = z_value;
break;
}
}
}
}
}
for (int i=0; i<row_num; i++)
{
for (int j=0; j<col_num; j++)
{
DEM_Raster[i * col_num + j] = mean_calculator(Raster_Zvalue[i*col_num+j]);
}
}
char out_put[1024] = {};
strcat (out_put,"Output_");
std::cout << out_put<<'\n';
strcat (out_put,const_cast<char*>(ss.str().c_str()));
strcat (out_put,".tif");
Raster_writer(out_put , DEM_Raster, row_num, col_num, minX, maxY);
// release Raster_Zvalue
std:: cout << out_put << path << '\n';
for (int i=0 ; i<row_num*col_num ; i++)
{
delete [] Raster_Zvalue[i];
}
delete [] Raster_Zvalue;
// release DEM_Raster
delete [] DEM_Raster;
}
return 0;
}
<file_sep>#include <iostream>
#include "stdio.h"
#include "mpi.h"
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "math.h"
#include <sstream>
int main (int argc,char *argv[])
{
GDALDataset *poDataset;
GDALAllRegister();
poDataset = (GDALDataset *) GDALOpen( "./cumberlan.tif", GA_ReadOnly );
if ( poDataset == NULL )
{
std::cout<<"Error When TIFF File Open!"<<std::endl;
return -1;
};
GDALRasterBand *poBand;
poBand = poDataset->GetRasterBand(1);
int x_size = poDataset->GetRasterXSize();
int y_size = poDataset->GetRasterYSize();
int band_size = poDataset->GetRasterCount();
MPI_Init(&argc,&argv);
/* if (argc < 2){
std::cout<<"usage:"<<argv[0]<<"raster.tiff"<<std::endl;
return -1;
}
*/
int rank,process_count;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &process_count);
int tmp_processNum = process_count;
int cut_num=0;
//printf("the processor number is %d",process_count);
int k=-1;
while (tmp_processNum >0)
{
k+=2;
tmp_processNum -= k;
}
if (tmp_processNum==0){
cut_num = ceil(sqrt(process_count));
}else{
printf("ERROR! the processor is not binary square");
return -1;
};
MPI_Barrier(MPI_COMM_WORLD);
std::cout<<"Read Raster"<<std::endl;
int cell_xNum = (int)ceil(x_size/cut_num);
int cell_yNum = (int)ceil(y_size/cut_num);
if ((rank%cut_num)*cell_xNum > x_size)
cell_xNum = x_size - (cut_num-1)*cell_xNum;
if (floor(rank/cut_num)*cell_yNum > y_size)
cell_yNum = y_size - (cut_num-1)*cell_yNum;
printf ("Read From %d,%d,%d,%d\n",cell_xNum*(rank%cut_num),(int)cell_yNum*(floor(rank/cut_num)),cell_xNum,cell_yNum);
float *pafScanline = (float *) CPLMalloc(sizeof(float)*cell_xNum*cell_yNum);
int x_block = cell_xNum * (rank % cut_num);
int y_block = cell_yNum * floor(rank / cut_num);
printf("[%i] Rank has block dims: [%i, %i] of total [%i,%i]\n", rank, x_block, y_block, cell_xNum, cell_yNum);
poBand->RasterIO(GF_Read, 0, 0 ,cell_xNum,cell_yNum,pafScanline,cell_xNum,cell_yNum,GDT_Float32,0,0);
printf ("%d of %d\n", rank, process_count);
printf ("cut:%d,x:%d,y:%d\n",cut_num,x_size,y_size);
printf("%d pixel is %f\n",1,pafScanline[1]);
CPLFree(pafScanline);
MPI_Finalize();
GDALClose(poDataset);
return 0;
}
<file_sep>#ifndef KDTREE_H
#define KDTREE_H
#include <stdio.h>
#include <stdlib.h>
#include "Point.h"
typedef struct KDNode {
int axis;
int dims;
double pivot;
struct KDNode *left;
struct KDNode *right;
Point *data;
} KDNode;
typedef struct KDTree {
int dims;
int depth;
KDNode *root;
} KDTree;
typedef struct KDList{
KDNode *node;
double dis;
struct KDList *next;
struct KDList *last;
} KDList;
// Return the tree depth
void KDNode_init(KDNode *knode);
void KDList_init(KDList *klist, KDNode *node, double dis);
void KDList_insert(KDList **head, KDList **node);
void KDList_pop(KDList **head, KDList *popnode);
void KDList_free(KDList **head);
void KDList_full_insert(KDList **neightbor, KDList **popnode);
void list2array(Point *array, KDList* head);
int KDNode_insert(Point * point_list, int depth, int dims, int point_count, KDNode *knode);
int KDNode_insert_node(Point * point_list, int depth, int dims, int point_count, KDNode *knode);
Point* KDNode_search(KDNode* knode, Point *pt, Point *best);
void KDNode_delete(KDNode* knode);
void KDNode_vis(KDNode* knode, int *k);
void KDNode_search_n(KDNode* knode, Point *pt, Point *best);
void KDNode_search_knn(KDNode* kndoe, Point* pt, Point* best, int k);
#endif
<file_sep>#include <stdio.h>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
class TCPState;
class TCPConnection {
public:
TCPConnection(TCPState* connector);
~TCPConnection();
void ActiveOpen();
void PassiveOpen();
void Close();
void Send();
void Ack();
void Sync();
private:
TCPState* connector_;
void UpdateState(TCPState* new_connector);
friend class TCPState;
friend class EstablishTCP;
friend class ListenTCP;
friend class CloseTCP;
friend class SyncTCP;
};
class TCPState {
public:
virtual ~TCPState(){}
virtual void ActiveOpen(TCPConnection* connection){std::cout << "This connection does not support active open."<< std::endl;};
virtual void PassiveOpen(TCPConnection* connection){std::cout << "This connection does not support pasive open."<< std::endl;};
virtual void Close(TCPConnection* connection){std::cout << "This connection does not support close."<< std::endl;};
virtual void Send(TCPConnection* connection){std::cout << "This connection does not support send."<< std::endl;};
virtual void Ack(TCPConnection* connection){std::cout << "This connection does not support ack."<< std::endl;};
virtual void Sync(TCPConnection* connection){std::cout << "This connection does not support sync."<< std::endl;};
protected:
TCPState(){};
};
class EstablishTCP: public TCPState {
public:
EstablishTCP();
~EstablishTCP();
void ActiveOpen(TCPConnection* connection) override;
};
class ListenTCP: public TCPState {
public:
ListenTCP() {};
~ListenTCP() {};
void Send(TCPConnection* connection) override {
std::cout<<"ListenTCP send" << std::endl;
connection->UpdateState(this);
}
};
class CloseTCP: public TCPState {
public:
CloseTCP() {};
~CloseTCP() {};
void Close(TCPConnection* connection) override {
std::cout<<"CloseTCP close" << std::endl;
connection->UpdateState(this);
}
void ActiveOpen(TCPConnection* connection) override {
std::cout << "CloseTCP active open" << std::endl;
connection->UpdateState(new EstablishTCP());
}
};
EstablishTCP::EstablishTCP() {};
EstablishTCP::~EstablishTCP() {};
void EstablishTCP::ActiveOpen(TCPConnection* connection) {
std::cout<<"EstablishTCP active open" << std::endl;
connection->UpdateState(new ListenTCP());
}
TCPConnection::TCPConnection(TCPState* connector): connector_(connector) {}
TCPConnection::~TCPConnection(){
free(connector_);
}
void TCPConnection::ActiveOpen(){
connector_->ActiveOpen(this);
}
void TCPConnection::PassiveOpen(){
connector_->PassiveOpen(this);
}
void TCPConnection::Close(){
connector_->Close(this);
}
void TCPConnection::Send(){
connector_->Send(this);
}
void TCPConnection::Ack(){
connector_->Ack(this);
}
void TCPConnection::Sync(){
connector_->Sync(this);
}
void TCPConnection::UpdateState(TCPState* new_connector){
if (new_connector != connector_ && connector_ != nullptr){
free(connector_);
connector_ = nullptr;
}
connector_ = new_connector;
}
int main(int argc, char** argv) {
TCPConnection* connection = new TCPConnection(new EstablishTCP());
connection->ActiveOpen();
connection->Send();
connection->Close();
connection->ActiveOpen();
free(connection);
}
| 33d22067896a3f5901d139f6c62cd1e69166135b | [
"Markdown",
"C",
"Python",
"C++"
] | 15 | C++ | AkaLovAge/Learning | b932b1fdf6bbd719df2f29bf2c51b77c12668367 | 3dc5d5ca7af32060394a6a3e9d92422d5cc00201 |
refs/heads/master | <repo_name>alexander171294/RustMon<file_sep>/user-data-srv/Dockerfile
FROM node:14-alpine
WORKDIR /app
COPY . .
RUN npm i
RUn npm run build
EXPOSE 3000
CMD ["npm", "run", "start:prod"]<file_sep>/rustmon/src/environments/environment.prod.ts
export const environment = {
production: true,
uDataApi: 'https://rustmon.tercerpiso.net',
version: 'v1.5.1'
};
<file_sep>/user-data-srv/src/environment.ts
export const environment = {
steamApiKey: process.env.STEAM_API ? process.env.STEAM_API : 'FBE6A5C249453A8516A55AAD5F87973F', // https://steamcommunity.com/dev/apikey
ipstackApiKey: '', // https://ipstack.com/signup/free
redis: {
host: process.env.CACHE_HOST ? process.env.CACHE_HOST : 'localhost',
auth_pass: process.env.CACHE_AUTH ? process.env.CACHE_AUTH : '<PASSWORD>',
port: process.env.CACHE_PORT ? parseInt(process.env.CACHE_PORT) : 6379
},
secondsCacheUsers: process.env.CACHE_TTL ? parseInt(process.env.CACHE_TTL) : 604800, // 7 days of cache
}<file_sep>/user-data-srv/src/rustmap/rustmap.service.ts
import { HttpService } from "@nestjs/axios";
import { Injectable, Logger } from "@nestjs/common";
import { first } from "rxjs";
@Injectable()
export class RustMapService {
private readonly logger = new Logger(RustMapService.name);
private readonly rustmapURI = 'https://rustmaps.com/map/${size}_${seed}';
constructor(private http: HttpService) { }
public getRustData(size: string, seed: string): Promise<RustMapData> {
return new Promise<RustMapData>((res, rej) => {
const mapURL = this.rustmapURI.replace('${size}', size).replace('${seed}', seed);
this.http.get<string>(mapURL+'?embed=i').pipe(first()).subscribe(r => {
const result = new RustMapData(mapURL);
const mapDetails = /<meta name="og:description" content="([^"]+)">/.exec(r.data);
if(mapDetails) {
result.mapExists = true;
result.mapDetails = mapDetails[1];
result.mapImage = /<meta name="twitter:image" content="([^"]+)">/.exec(r.data)[1];
}
res(result);
}, e => {
rej(e);
});
});
}
}
export class RustMapData {
public mapExists: boolean = false;
public mapImage: string;
public mapDetails: string;
public mapURL: string;
constructor(url: string) {
this.mapURL = url;
}
}<file_sep>/rustmon/src/app/dashboard/prompt/prompt.service.ts
import { EventEmitter, Injectable } from '@angular/core';
import { first } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PromptService {
public readonly onPromptOpened = new EventEmitter<PromptData>();
private readonly onClose = new EventEmitter<string>();
constructor() { }
public openPrompt(d: PromptData) {
return new Promise((res, rej) => {
this.onPromptOpened.emit(d);
this.onClose.pipe(
first(),
).subscribe(d => {
if(d) {
res(d);
} else {
rej();
}
});
});
}
public close(data?: string) {
this.onClose.emit(data);
}
}
export class PromptData {
promptName: string;
promptPlaceholder?: string;
constructor(name: string, placeholder?: string) {
this.promptName = name;
this.promptPlaceholder = placeholder;
}
}
<file_sep>/rustmon/src/app/dashboard/prompt/prompt.module.ts
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PromptComponent } from './prompt.component';
@NgModule({
declarations: [PromptComponent],
imports: [
CommonModule,
FormsModule
],
exports: [PromptComponent]
})
export class PromptModule { }
<file_sep>/rustmon/src/app/api/MapDataDto.ts
export interface MapData {
mapExists: boolean;
mapURL: string;
mapImage?: string;
mapDetails?: string;
}<file_sep>/rustmon/src/app/utils/clipboard.ts
export class Clipboard {
public static writeText(textToCopy: string): boolean {
if(navigator.clipboard) {
navigator.clipboard.writeText(textToCopy);
return true;
} else {
const el = document.createElement('textarea');
el.value = textToCopy;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
try {
document.execCommand('copy');
} catch(e) {
document.body.removeChild(el);
return false;
}
document.body.removeChild(el);
return true;
}
}
}<file_sep>/user-data-srv/src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { ValveApiService } from './valve/valve-api.service';
import { IPGeocodeService } from './ipGeocode/ipgeocode.service';
import { HttpModule } from '@nestjs/axios';
import { CacheRedisService } from './redis/redis.service';
import { RustMapService } from './rustmap/rustmap.service';
@Module({
imports: [HttpModule],
controllers: [AppController],
providers: [ValveApiService, IPGeocodeService, CacheRedisService, RustMapService],
})
export class AppModule {}
<file_sep>/rustmon/src/app/dashboard/dashboard.module.ts
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DashboardComponent } from './dashboard.component';
import { RouterModule, Routes } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { UptimePipe } from './uptime.pipe';
import { UptimeFixedPipe } from './uptimeFixed.pipe';
import { PortRemovePipe } from './port-remove.pipe';
import { TableModule } from 'primeng/table';
import { InputSwitchModule } from 'primeng/inputswitch';
import { ContextMenuModule } from 'primeng/contextmenu';
import { ToastModule } from 'primeng/toast';
import { ConfirmDialogModule } from 'primeng/confirmdialog';
import { OverlayPanelModule } from 'primeng/overlaypanel';
import { SidebarModule } from 'primeng/sidebar';
import { ChatComponent } from './chat/chat.component';
import { PromptModule } from './prompt/prompt.module';
import { PlayersComponent } from './players/players.component';
import { ConfigComponent } from './config/config.component';
import { PlayerToolsComponent } from './player-tools/player-tools.component';
const routes: Routes = [
{
path: '',
pathMatch: 'full',
component: DashboardComponent
}
];
@NgModule({
declarations: [
DashboardComponent,
UptimePipe,
UptimeFixedPipe,
PortRemovePipe,
ChatComponent,
PlayersComponent,
ConfigComponent,
PlayerToolsComponent,
],
imports: [
CommonModule,
RouterModule.forChild(routes),
FormsModule,
TableModule,
InputSwitchModule,
ContextMenuModule,
ToastModule,
ConfirmDialogModule,
OverlayPanelModule,
SidebarModule,
PromptModule,
FontAwesomeModule,
]
})
export class DashboardModule { }
<file_sep>/rustmon/src/app/rustRCON/ChatMessage.ts
export class ChatMessage {
public Channel: number = 0;
public Message: string = '';
public UserId: string = '';
public Username: string = '';
public Color: string = '';
public Time: number = 0;
}
<file_sep>/rustmon/src/app/dashboard/config/config.component.ts
import { Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import { Subscription } from 'rxjs';
import { MapData } from 'src/app/api/MapDataDto';
import { UserDataService } from 'src/app/api/user-data.service';
import { RustService } from 'src/app/rustRCON/rust.service';
import { REType, RustEvent } from 'src/app/rustRCON/RustEvent';
@Component({
selector: 'app-config',
templateUrl: './config.component.html',
styleUrls: ['./config.component.scss']
})
export class ConfigComponent implements OnInit, OnDestroy {
@Output() close = new EventEmitter<void>();
public retryLoading: boolean = false;
public serverSeed: number = 0;
public worldSize: number = 0;
public serverName: string = '';
public serverDescription: string = '';
public serverUrl: string = '';
public serverImage: string = '';
public serverTags: string = '';
public serverMaxPlayers: number = 0;
// misc configs:
public globalChat: any;
public airdropMinplayers: number = 0;
public idlekick: number = 0;
public idlekickMode: any;
public idlekickAdmins: any;
public motd: any;
public pve: any;
public radiation: any;
public instantCraft: any;
public aiThink: any;
public npcEnable: any;
public stability: any;
public aiMove: any;
public chatEnabled: any;
public itemDespawn: any;
public respawnResetRange: any;
// security
public saveinterval: number = 0;
public fpsLimit: number = 0;
public serverSecure: any;
// batch
public batchCommand: string = '';
public populations = {
wolf: -1, // wolf.population
zombie: -1, // zombie.population
bear: -1, // bear.population
polarbear: -1, // polarbear.population
boar: -1, // boar.population
chicken: -1, // chicken.population
stag: -1, // stag.population
horse: -1, // horse.population
ridablehorse: -1, // ridablehorse.population
minicopter: -1, // minicopter.population
modulecar: -1, // modulecar.population
motorrowboat: -1, // motorrowboat.population
rhib: -1, // rhib.rhibpopulation
scraptransporthelicopter: -1, // scraptransporthelicopter.population
halloweenmurderer: -1, // halloween.murdererpopulation
halloweenscarecrow: -1, // halloween.scarecrowpopulation
hotairballoon: -1, // hotairballoon.population
}
public mapData?: MapData;
private subCfg?: Subscription;
public tab = 0;
constructor(private rustSrv: RustService,
private userDataSrv: UserDataService) { }
ngOnInit() {
this.subCfg = this.rustSrv.getEvtRust().subscribe((d: RustEvent) => {
if(d.type == REType.SRV_INFO) {
if(d.raw.indexOf('server.seed:') === 0) {
this.serverSeed = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
if(this.worldSize) {
this.getMap();
}
} else if(d.raw.indexOf('server.worldsize:') === 0) {
this.worldSize = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
if(this.serverSeed) {
this.getMap();
}
} else if(d.raw.indexOf('server.hostname:') === 0) {
this.serverName = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.description:') === 0) {
this.serverDescription = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.url:') === 0) {
this.serverUrl = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.headerimage:') === 0) {
this.serverImage = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.tags:') === 0) {
this.serverTags = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.maxplayers:') === 0) {
this.serverMaxPlayers = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('server.globalchat:') === 0) {
this.globalChat = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('airdrop.min_players:') === 0) {
this.airdropMinplayers = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('server.saveinterval:') === 0) {
this.saveinterval = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('server.idlekick:') === 0) {
this.idlekick = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('server.idlekickmode:') === 0) {
this.idlekickMode = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.idlekickadmins:') === 0) {
this.idlekickAdmins = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.motd:') === 0) {
this.motd = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.pve:') === 0) {
this.pve = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.radiation:') === 0) {
this.radiation = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('craft.instant:') === 0) {
this.instantCraft = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('ai.think:') === 0) {
this.aiThink = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('ai.npc_enable:') === 0) {
this.npcEnable = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('ai.move:') === 0) {
this.aiMove = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.stability:') === 0) {
this.stability = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('chat.enabled:') === 0) {
this.chatEnabled = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('server.itemdespawn:') === 0) {
this.itemDespawn = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('server.respawnresetrange:') === 0) {
this.respawnResetRange = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('fps.limit:') === 0) {
this.fpsLimit = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('server.secure:') === 0) {
this.serverSecure = d.raw.split(' ').slice(1).join(' ').split('"').join('');
} else if(d.raw.indexOf('wolf.population:') === 0) {
this.populations.wolf = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('zombie.population:') === 0) {
this.populations.zombie = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('bear.population:') === 0) {
this.populations.bear = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('polarbear.population:') === 0) {
this.populations.polarbear = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('boar.population:') === 0) {
this.populations.boar = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('chicken.population:') === 0) {
this.populations.chicken = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('stag.population:') === 0) {
this.populations.stag = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('horse.population:') === 0) {
this.populations.horse = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('ridablehorse.population:') === 0) {
this.populations.ridablehorse = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('minicopter.population:') === 0) {
this.populations.minicopter = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('modularcar.population:') === 0) {
this.populations.modulecar = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('motorrowboat.population:') === 0) {
this.populations.motorrowboat = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('rhib.rhibpopulation:') === 0) {
this.populations.rhib = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('scraptransporthelicopter.population:') === 0) {
this.populations.scraptransporthelicopter = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('halloween.murdererpopulation:') === 0) {
this.populations.halloweenmurderer = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('halloween.scarecrowpopulation:') === 0) {
this.populations.halloweenscarecrow = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else if(d.raw.indexOf('hotairballoon.population:') === 0) {
this.populations.hotairballoon = parseInt(d.raw.split(' ').slice(1).join(' ').split('"').join(''));
} else {
console.log('unknown config', d.raw);
}
}
});
this.rustSrv.sendCommand('server.seed', REType.SRV_INFO);
this.rustSrv.sendCommand('server.worldsize', REType.SRV_INFO);
this.rustSrv.sendCommand('server.hostname', REType.SRV_INFO);
this.rustSrv.sendCommand('server.description', REType.SRV_INFO);
this.rustSrv.sendCommand('server.url', REType.SRV_INFO);
this.rustSrv.sendCommand('server.tags', REType.SRV_INFO);
this.rustSrv.sendCommand('server.headerimage', REType.SRV_INFO);
this.rustSrv.sendCommand('server.maxplayers', REType.SRV_INFO);
// misc data
this.rustSrv.sendCommand('server.globalchat', REType.SRV_INFO);
this.rustSrv.sendCommand('server.idlekick', REType.SRV_INFO);
this.rustSrv.sendCommand('server.idlekickmode', REType.SRV_INFO);
this.rustSrv.sendCommand('server.idlekickadmins', REType.SRV_INFO);
this.rustSrv.sendCommand('server.motd', REType.SRV_INFO);
this.rustSrv.sendCommand('server.pve', REType.SRV_INFO);
this.rustSrv.sendCommand('server.radiation', REType.SRV_INFO);
this.rustSrv.sendCommand('craft.instant', REType.SRV_INFO);
this.rustSrv.sendCommand('ai.think', REType.SRV_INFO);
this.rustSrv.sendCommand('ai.npc_enable', REType.SRV_INFO);
this.rustSrv.sendCommand('ai.move', REType.SRV_INFO);
this.rustSrv.sendCommand('server.stability', REType.SRV_INFO);
this.rustSrv.sendCommand('chat.enabled', REType.SRV_INFO);
this.rustSrv.sendCommand('server.itemdespawn', REType.SRV_INFO);
this.rustSrv.sendCommand('server.respawnresetrange', REType.SRV_INFO);
// security
this.rustSrv.sendCommand('server.saveinterval', REType.SRV_INFO);
this.rustSrv.sendCommand('fps.limit', REType.SRV_INFO);
this.rustSrv.sendCommand('server.secure', REType.SRV_INFO);
// Population
this.rustSrv.sendCommand('wolf.population', REType.SRV_INFO);
this.rustSrv.sendCommand('zombie.population', REType.SRV_INFO);
this.rustSrv.sendCommand('bear.population', REType.SRV_INFO);
this.rustSrv.sendCommand('polarbear.population', REType.SRV_INFO);
this.rustSrv.sendCommand('boar.population', REType.SRV_INFO);
this.rustSrv.sendCommand('chicken.population', REType.SRV_INFO);
this.rustSrv.sendCommand('stag.population', REType.SRV_INFO);
this.rustSrv.sendCommand('horse.population', REType.SRV_INFO);
this.rustSrv.sendCommand('ridablehorse.population', REType.SRV_INFO);
this.rustSrv.sendCommand('minicopter.population', REType.SRV_INFO);
this.rustSrv.sendCommand('modularcar.population', REType.SRV_INFO);
this.rustSrv.sendCommand('motorrowboat.population', REType.SRV_INFO);
this.rustSrv.sendCommand('rhib.rhibpopulation', REType.SRV_INFO);
this.rustSrv.sendCommand('scraptransporthelicopter.population', REType.SRV_INFO);
this.rustSrv.sendCommand('halloween.murdererpopulation', REType.SRV_INFO);
this.rustSrv.sendCommand('halloween.scarecrowpopulation', REType.SRV_INFO);
this.rustSrv.sendCommand('hotairballoon.population', REType.SRV_INFO);
}
ngOnDestroy() {
this.subCfg?.unsubscribe();
}
save() {
this.apply();
this.rustSrv.sendCommand('server.writecfg');
}
apply() {
this.serverName = this.serverName.split('"').join('');
this.serverDescription = this.serverDescription.split('"').join('');
this.serverImage = this.serverImage.split('"').join('');
this.serverUrl = this.serverUrl.split('"').join('');
this.rustSrv.sendCommand(`server.hostname "${this.serverName}"`);
this.rustSrv.sendCommand(`server.description "${this.serverDescription}"`);
this.rustSrv.sendCommand(`server.url "${this.serverUrl}"`);
this.rustSrv.sendCommand(`server.tags "${this.serverTags}"`);
this.rustSrv.sendCommand(`server.headerimage "${this.serverImage}"`);
this.rustSrv.sendCommand(`server.maxplayers "${this.serverMaxPlayers}"`);
this.doClose();
}
doClose() {
this.close.emit();
}
getMap() {
if(!this.mapData) {
this.userDataSrv.getMap(this.serverSeed.toString(), this.worldSize.toString()).subscribe(r => {
this.mapData = r;
this.retryLoading = false;
});
}
}
mapRetry() {
this.retryLoading = true;
this.userDataSrv.mapInvalidateCache(this.serverSeed.toString(), this.worldSize.toString()).subscribe(r => {
this.getMap();
});
}
applyMisc() {
this.rustSrv.sendCommand(`server.globalchat "${this.globalChat}"`);
this.rustSrv.sendCommand(`server.idlekick "${this.idlekick}"`);
this.rustSrv.sendCommand(`server.idlekickmode "${this.idlekickMode}"`);
this.rustSrv.sendCommand(`server.idlekickadmins "${this.idlekickAdmins}"`);
this.rustSrv.sendCommand(`server.motd "${this.motd}"`);
this.rustSrv.sendCommand(`server.pve "${this.pve}"`);
this.rustSrv.sendCommand(`server.radiation "${this.radiation}"`);
this.rustSrv.sendCommand(`craft.instant "${this.instantCraft}"`);
this.rustSrv.sendCommand(`ai.think "${this.aiThink}"`);
this.rustSrv.sendCommand(`ai.npc_enable "${this.npcEnable}"`);
this.rustSrv.sendCommand(`ai.move "${this.aiMove}"`);
this.rustSrv.sendCommand(`server.stability "${this.stability}"`);
this.rustSrv.sendCommand(`chat.enabled "${this.chatEnabled}"`);
this.rustSrv.sendCommand(`server.itemdespawn "${this.itemDespawn}"`);
this.rustSrv.sendCommand(`server.respawnresetrange "${this.respawnResetRange}"`);
this.doClose();
}
saveMisc() {
this.applyMisc();
this.rustSrv.sendCommand('server.writecfg');
}
applySec() {
this.rustSrv.sendCommand(`fps.limit "${this.fpsLimit}"`);
this.rustSrv.sendCommand(`server.saveinterval "${this.saveinterval}"`);
this.rustSrv.sendCommand(`server.secure "${this.serverSecure}"`);
this.doClose();
}
saveSec() {
this.applySec();
this.rustSrv.sendCommand('server.writecfg');
}
applyPop() {
this.rustSrv.sendCommand(`wolf.population "${this.populations.wolf}"`);
this.rustSrv.sendCommand(`zombie.population "${this.populations.zombie}"`);
this.rustSrv.sendCommand(`bear.population "${this.populations.bear}"`);
this.rustSrv.sendCommand(`polarbear.population "${this.populations.polarbear}"`);
this.rustSrv.sendCommand(`boar.population "${this.populations.boar}"`);
this.rustSrv.sendCommand(`chicken.population "${this.populations.chicken}"`);
this.rustSrv.sendCommand(`stag.population "${this.populations.stag}"`);
this.rustSrv.sendCommand(`horse.population "${this.populations.horse}"`);
this.rustSrv.sendCommand(`ridablehorse.population "${this.populations.ridablehorse}"`);
this.rustSrv.sendCommand(`minicopter.population "${this.populations.minicopter}"`);
this.rustSrv.sendCommand(`modularcar.population "${this.populations.modulecar}"`);
this.rustSrv.sendCommand(`motorrowboat.population "${this.populations.motorrowboat}"`);
this.rustSrv.sendCommand(`rhib.rhibpopulation "${this.populations.rhib}"`);
this.rustSrv.sendCommand(`scraptransporthelicopter.population "${this.populations.scraptransporthelicopter}"`);
this.rustSrv.sendCommand(`halloween.murdererpopulation "${this.populations.halloweenmurderer}"`);
this.rustSrv.sendCommand(`halloween.scarecrowpopulation "${this.populations.halloweenscarecrow}"`);
this.rustSrv.sendCommand(`hotairballoon.population "${this.populations.hotairballoon}"`);
this.doClose();
}
savePop() {
this.applySec();
this.rustSrv.sendCommand('server.writecfg');
}
loadBatch() {
const oldBatch = localStorage.getItem('cfg-batch');
this.batchCommand = oldBatch ? oldBatch : '';
}
batchChange() {
localStorage.setItem('cfg-batch', this.batchCommand);
}
execBatch() {
this.batchCommand.split('\n').forEach(cmd => {
this.rustSrv.sendCommand(cmd);
})
}
}
<file_sep>/rustmon/src/app/rustRCON/Player.ts
import { DataResponse, VacResponse } from "../api/UserDataDto";
export class Player {
public SteamID: string = '';
public OwnerSteamID: string = '';
public DisplayName: string = '';
public Ping: number = 0;
public Address: string = '';
public ConnectedSeconds: number = 0;
public VoiationLevel: number = 0;
public CurrentLevel: number = 0;
public UnspentXp: number = 0;
public Health: number = 0;
}
export class PlayerWithStatus extends Player {
public online: boolean = false;
public country: string = '';
public vac?: VacResponse;
public steamData?: DataResponse;
public notes: string | undefined;
}
<file_sep>/rustmon/src/app/dashboard/player-tools/player-tools.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { PlayerToolsService } from './player-tools.service';
describe('PlayerToolsService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: PlayerToolsService = TestBed.get(PlayerToolsService);
expect(service).toBeTruthy();
});
});
<file_sep>/rustmon/src/app/rustRCON/rust.service.ts
import { SocketService } from '../utils/socket/socket.service';
import { Injectable, EventEmitter } from '@angular/core';
import { EventTypeSck } from '../utils/socket/EventSck';
import { RustEvent, REType } from './RustEvent';
import { RustEventsService } from './rust-events.service';
@Injectable({
providedIn: 'root'
})
export class RustService {
private evtRust: EventEmitter<RustEvent> = new EventEmitter<RustEvent>();
private readonly CONNAME = 'RustMon';
private connected: boolean = false;
private connectionString: string = '';
constructor(private sck: SocketService, private rustEvents: RustEventsService) { }
connect(serverIP: string, rconPort: number, rconPasswd: string): EventEmitter<RustEvent> {
this.connectionString = `${serverIP}`;
this.sck.connect('ws://' + serverIP + ':' + rconPort + '/' + rconPasswd).subscribe(evt => {
if (evt.eventType === EventTypeSck.CONNECTED) {
const re = new RustEvent();
re.type = REType.CONNECTED;
this.connected = true;
this.evtRust.emit(re);
}
if (evt.eventType === EventTypeSck.MESSAGE) {
this.processMessage(evt.eventData, JSON.parse(evt.eventData.data));
}
if (evt.eventType === EventTypeSck.DISCONNECTED) {
const re = new RustEvent();
re.type = REType.DISCONNECT;
this.evtRust.emit(re);
this.connected = false;
}
if (evt.eventType === EventTypeSck.ERROR) {
const re = new RustEvent();
re.type = REType.ERROR;
this.evtRust.emit(re);
this.connected = false;
}
});
return this.evtRust;
}
public frontThreadReady() {
this.getInfo();
this.chatTail(50);
this.sysInfo();
}
public sysInfo() {
this.sendCommand('global.sysinfo');
}
public getEvtRust() {
return this.evtRust;
}
getInfo() {
this.sendCommand('serverinfo', REType.GET_INFO);
}
players() {
this.sendCommand('global.playerlist', REType.PLAYERS);
}
chatTail(quantity: number) {
this.sendCommand('chat.tail ' + quantity, REType.CHAT_STACK);
}
sendCommand(command: string, cid?: REType) {
cid = cid ? cid : 0;
this.sck.sendMessage({
Message: command,
Identifier: cid,
Name: this.CONNAME
});
}
banList() {
this.sendCommand('banlistex', REType.BAN_LIST);
}
processMessage(message: MessageEvent, body: any) {
if (body.Identifier < 1000) {
console.log('==>', body);
}
const re = new RustEvent();
try {
re.data = JSON.parse(body.Message);
} catch (e) {
}
re.raw = body.Message;
re.type = body.Identifier;
re.rawtype = body.Type;
this.rustEvents.process(re);
this.evtRust.emit(re);
}
isConnected() {
return this.connected;
}
public getConnectionString() {
return this.connectionString;
}
}
<file_sep>/rustmon/src/app/login/connection-history.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ConnectionHistoryService {
private connections: ConectionData[] = [];
private STORAGE_KEY = 'sessions';
constructor() {
const sessions = JSON.parse(localStorage.getItem(this.STORAGE_KEY) as string);
if(sessions) {
this.connections = sessions;
}
}
public save(server: string, port: string, password: string) {
const conIdx = this.connections.findIndex(con => con.server == server);
let connection = new ConectionData();
if(conIdx >= 0) {
connection = this.connections[conIdx];
}
connection.password = <PASSWORD>;
connection.port = port;
connection.server = server;
connection.lastConn = (new Date()).getTime();
if(conIdx < 0) {
this.connections.push(connection);
}
this.saveServerList();
}
public getServerList(): ConectionData[] {
return this.connections.sort((a,b) => b.lastConn - a.lastConn);
}
private saveServerList(): void {
localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.connections));
}
}
export class ConectionData {
public server: string = '';
public port: string = '';
public password: string = '';
public lastConn: number = 0;
} <file_sep>/rustmon/src/app/rustRCON/rust-events.service.ts
import { Injectable } from '@angular/core';
import { MessageService } from 'primeng/api';
import { RustEvent } from './RustEvent';
@Injectable({
providedIn: 'root'
})
export class RustEventsService {
private reportList: Report[] = [];
constructor(private messageService: MessageService) {
this.loadReports();
}
public process(re: RustEvent) {
if(re.raw.indexOf('[PlayerReport]') > 0) {
this.parseReport(re);
}
}
private parseReport(re: RustEvent) {
const report = /\[PlayerReport\]\s([^\[]+)\[([^\]]+)\]\sreported\s([^\[]+)\[([^\]]+)\]\s-\s(.*)/.exec(re.raw) as RegExpExecArray;
const reportObj = new Report();
reportObj.reporter = {
steamID: report[2],
nick: report[1]
};
reportObj.reported = {
steamID: report[4],
nick: report[3]
};
reportObj.message = report[5];
this.notifyAndSaveReport(reportObj);
}
private notifyAndSaveReport(report: Report) {
this.messageService.add({severity: 'error', summary: `${report.reporter?.nick} F7 report: ${report.reported?.nick}`, detail: report.message});
this.reportList.push(report);
this.saveReports();
}
public saveReports() {
localStorage.setItem('reports', JSON.stringify(this.reportList));
}
public loadReports() {
const reports = JSON.parse(localStorage.getItem('reports') as string);
if(reports) {
this.reportList = reports;
}
}
}
export class Report {
public reporter?: PlayerReportData;
public reported?: PlayerReportData;
public message: string = '';
}
export class PlayerReportData {
public steamID: string = '';
public nick: string = '';
}
<file_sep>/user-data-srv/src/valve/valve-api.service.ts
import { first, Observable } from 'rxjs';
import { environment } from 'src/environment';
import { HttpService } from '@nestjs/axios';
import { AxiosResponse } from 'axios'
import { DataResponse, VacResponse } from 'src/UserDataDTO';
import { Injectable } from '@nestjs/common';
@Injectable()
export class ValveApiService {
public readonly steamBanApi = 'https://api.steampowered.com/ISteamUser/GetPlayerBans/v1?key=' + environment.steamApiKey + '&steamids=${STEAM_ID}&format=json';
public readonly steamUserApi = 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' + environment.steamApiKey + '&steamids==${STEAM_ID}&format=json';
constructor(private httpService: HttpService) { }
public getVacs(uid64: string): Observable<AxiosResponse<PlayerVacsResponse>> {
return this.httpService.get<PlayerVacsResponse>(
this.steamBanApi.replace('${STEAM_ID}', uid64)
).pipe(first());
}
public getUserData(uid64: string): Observable<AxiosResponse<PlayerDataResponse>> {
return this.httpService.get<PlayerDataResponse>(
this.steamUserApi.replace('${STEAM_ID}', uid64)
).pipe(first());
}
}
export class PlayerVacsResponse {
public players: VacResponse[];
}
export class PlayerDataResponse {
public response: {players: DataResponse[]};
}
<file_sep>/rustmon/src/app/dashboard/players/players.component.ts
import { PlayerStorageService } from './../../rustRCON/player-storage.service';
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { MenuItem } from 'primeng/api/menuitem';
import {MessageService, ConfirmationService} from 'primeng/api';
import { OverlayPanel } from 'primeng/overlaypanel';
import { Player, PlayerWithStatus } from 'src/app/rustRCON/Player';
import { RustService } from 'src/app/rustRCON/rust.service';
import { PromptData, PromptService } from '../prompt/prompt.service';
import { UserDataService } from 'src/app/api/user-data.service';
import { Clipboard } from 'src/app/utils/clipboard';
import { faEyeSlash, faStickyNote, faExclamationTriangle } from '@fortawesome/free-solid-svg-icons';
@Component({
selector: 'app-players',
templateUrl: './players.component.html',
styleUrls: ['./players.component.scss']
})
export class PlayersComponent implements OnInit {
@Input() playerList: PlayerWithStatus[] = [];
public selctedUser?: Player;
public userPopup = { x: 0, y: 0, opened: false };
@Input() onlyOnline?: boolean;
@Output() onlyOnlineEvt: EventEmitter<boolean> = new EventEmitter<boolean>();
public playerClicked?: PlayerWithStatus;
public icons = {
faExclamationTriangle,
faEyeSlash,
faStickyNote
}
public playerCols = [
{ field: 'ConnectedSeconds', header: 'Alive', width: '50px' },
{ field: 'DisplayName', header: 'Name', width: '300px'},
{ field: 'Health', header: 'HP', width: '52px' },
{ field: 'Address', header: 'IP', width: '130px' },
{ field: 'Ping', header: 'Lag', width: '30px' }
];
public selectedPlayer: PlayerWithStatus = new PlayerWithStatus();
ctxMenu: MenuItem[] = [
{ label: 'Admin/Mod', items: [
{ label: 'Make moderator', command: (event) => this.ctxAddMod(this.selectedPlayer) },
{ label: 'Remove moderation', command: (event) => this.ctxRemMod(this.selectedPlayer) },
{ label: 'Make Owner', command: (event) => this.ctxAddOwner(this.selectedPlayer) },
{ label: 'Remove Owner', command: (event) => this.ctxRemOwner(this.selectedPlayer) },
]},
{ label: 'Moderation', items: [
{ label: 'Ban', command: (event) => this.ctxBan(this.selectedPlayer) },
{ label: 'Unban', command: (event) => this.ctxUnban(this.selectedPlayer) },
{ label: 'Kick', command: (event) => this.ctxKick(this.selectedPlayer) },
]},
{ label: 'Chat', items: [
{ label: 'Mute', command: (event) => this.ctxMute(this.selectedPlayer) },
{ label: 'Unmute', command: (event) => this.ctxUnmute(this.selectedPlayer) },
]},
{ label: 'TeamInfo', command: (event) => this.ctxTeamInfo(this.selectedPlayer.SteamID) },
{ label: 'Steam', items: [
{ label: 'Open Profile', command: (event) => this.ctxSteamProfile(this.selectedPlayer) },
{ label: 'Copy SteamID', command: (event) => this.ctxSteamID(this.selectedPlayer)}
]},
];
constructor(private rustSrv: RustService,
private messageService: MessageService,
private confirmationService: ConfirmationService,
private promptSrv: PromptService,
private userDataSrv: UserDataService,
private playerStorageSrv: PlayerStorageService) { }
ngOnInit() {
}
ctxMute(player: PlayerWithStatus) {
this.rustSrv.sendCommand('mute ' + player.SteamID);
this.messageService.add({severity: 'success', summary: 'Muted', detail: player.SteamID + ' | ' + player.DisplayName});
}
ctxUnmute(player: PlayerWithStatus) {
this.rustSrv.sendCommand('unmute ' + player.SteamID);
this.messageService.add({severity: 'success', summary: 'Unmuted', detail: player.SteamID + ' | ' + player.DisplayName});
}
ctxAddOwner(player: PlayerWithStatus) {
this.confirmationService.confirm({
message: `Converting ${player.DisplayName} in owner, Are you sure?`,
accept: () => {
this.doOwner(player.SteamID, player.DisplayName);
this.messageService.add({severity: 'success', summary: 'Added admin', detail: player.SteamID + ' | ' + player.DisplayName});
}
});
}
ctxRemOwner(player: PlayerWithStatus) {
this.confirmationService.confirm({
message: `Are you sure that you want to remove ownership from ${player.DisplayName}?`,
accept: () => {
this.unOwner(player.SteamID);
this.messageService.add({severity: 'success', summary: 'Removed owner', detail: player.SteamID + ' | ' + player.DisplayName});
}
});
}
ctxAddMod(player: PlayerWithStatus) {
this.confirmationService.confirm({
message: `Converting ${player.DisplayName} in moderator, Are you sure?`,
accept: () => {
this.doMod(player.SteamID, player.DisplayName);
this.messageService.add({severity: 'success', summary: 'Added admin', detail: player.SteamID + ' | ' + player.DisplayName});
}
});
}
ctxRemMod(player: PlayerWithStatus) {
this.confirmationService.confirm({
message: `Are you sure that you want to remove moderator ${player.DisplayName}?`,
accept: () => {
this.unMod(player.SteamID);
this.messageService.add({severity: 'success', summary: 'Removed admin', detail: player.SteamID + ' | ' + player.DisplayName});
}
});
}
ctxBan(player: PlayerWithStatus) {
this.ban(player.SteamID, player.DisplayName);
}
ctxUnban(player: PlayerWithStatus) {
this.rustSrv.sendCommand('unban ' + player.SteamID);
this.messageService.add({severity: 'success', summary: 'Unbanned', detail: player.SteamID + ' | ' + player.DisplayName});
}
ctxKick(player: PlayerWithStatus) {
this.kick(player.SteamID);
}
ctxSteamProfile(player: PlayerWithStatus) {
window.open('https://steamcommunity.com/profiles/' + player.SteamID, '_blank');
}
ctxSteamID(player: PlayerWithStatus) {
if(Clipboard.writeText(player.SteamID)) {
this.messageService.add({severity: 'success', summary: 'Copied to clipboard.', detail: player.SteamID + ' | ' + player.DisplayName});
} else {
this.messageService.add({severity: 'info', summary: 'Clipboard disabled :(', detail: player.SteamID + ' | ' + player.DisplayName});
}
}
openUserPopup(user: any, event: any) {
this.selctedUser = user;
this.userPopup = {
x: event.clientX + 20,
y: event.clientY + 20,
opened: true
};
console.log(event.offsetX, event);
}
doOwner(steamID: string, name: string) {
this.userPopup.opened = false;
this.rustSrv.sendCommand('ownerid ' + steamID + ' ' + name);
}
doMod(steamID: string, name: string) {
this.userPopup.opened = false;
this.rustSrv.sendCommand('moderatorid ' + steamID + ' ' + name);
}
ban(steamID: string, name: string) {
this.userPopup.opened = false;
this.promptSrv.openPrompt(new PromptData('Write the reason:')).then(reason => {
this.rustSrv.sendCommand('banid ' + steamID + ' "' + name + '" "' + reason + '"');
this.messageService.add({severity: 'success', summary: 'Banned', detail: steamID + ' | ' + name});
});
}
kick(steamID: string) {
this.userPopup.opened = false;
this.promptSrv.openPrompt(new PromptData('Write the reason:')).then(reason => {
this.rustSrv.sendCommand('kick ' + steamID + ' "' + reason + '"');
this.messageService.add({severity: 'success', summary: 'Kicked', detail: steamID + ' | ' + name});
});
}
ctxTeamInfo(steamID: string) {
this.rustSrv.sendCommand('teaminfo ' + steamID);
}
unOwner(steamID: string) {
this.rustSrv.sendCommand('removeowner ' + steamID);
}
unMod(steamID: string) {
this.rustSrv.sendCommand('removemoderator ' + steamID);
}
changeOnlineFilter(evt: any) {
this.onlyOnlineEvt.emit(evt.checked);
}
showPlayerData(evt: any, player: PlayerWithStatus, op: OverlayPanel) {
this.playerClicked = player;
console.log(this.playerClicked);
op.toggle(evt);
}
clearCache(steamID: string) {
this.userDataSrv.clearCache(steamID).subscribe(result => {
if(result == 'OK') {
this.messageService.add({severity: 'success', summary: 'Cleared cache', detail: steamID});
} else {
this.messageService.add({severity: 'warning', summary: 'Error clearing cache', detail: result + ' - ' + steamID});
}
});
}
getStringFromInputEvent(evt: any): string {
return evt.target.value;
}
saveNote(note: string, steamID: string) {
this.playerStorageSrv.saveNote(steamID, note);
}
}
<file_sep>/rustmon/src/app/dashboard/dashboard.component.ts
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { Subscription } from 'rxjs';
import { environment } from 'src/environments/environment';
import { ChatMessage } from '../rustRCON/ChatMessage';
import { PlayerWithStatus } from '../rustRCON/Player';
import { PlayerStorageService } from '../rustRCON/player-storage.service';
import { RustService } from '../rustRCON/rust.service';
import { REType } from '../rustRCON/RustEvent';
import { ServerInfo } from '../rustRCON/ServerInfo';
import { ChatComponent } from './chat/chat.component';
import { PlayerToolsService } from './player-tools/player-tools.service';
import { PromptData, PromptService } from './prompt/prompt.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit, OnDestroy {
// data variable
public serverInfo: ServerInfo = new ServerInfo();
public chatMessages?: ChatMessage[];
public playerList?: PlayerWithStatus[];
public consoleMessages: string[] = [];
public connectionString: any;
// flags variables
public hasInfo = false;
public hasStack = false;
public openedConfig = false;
public showTeamMessages = true;
public playerToolsOpened = false;
public cogMenu = false;
public ready = false;
// grid filter:
public onlineFilter = true;
// form variables.
public message: string = '';
public command: string = '';
public version = environment.version;
private subscription?: Subscription;
@ViewChild('chatCompo', {static: false}) chatCompo?: ChatComponent;
@ViewChild('console', {static: false}) consoleBox: any;
constructor(private rustSrv: RustService,
private psSrv: PlayerStorageService,
private playerTool: PlayerToolsService,
private messageService: MessageService,
private router: Router,
private promptSrv: PromptService) { }
ngOnInit() {
this.connectionString = this.rustSrv.getConnectionString();
this.subscription = this.rustSrv.getEvtRust().subscribe(d => {
if (d.type === REType.UNKOWN) {
// show in console.
}
if (d.type === REType.GET_INFO) {
this.hasInfo = true;
this.serverInfo = d.data;
}
if (d.type === REType.CHAT_STACK) {
this.hasStack = true;
d.data.forEach((msg: any) => {
const betterChatPlugin = /\[([^\]]+)\]\s([^:]+):(.*)/gi.exec(msg.Message);
if(betterChatPlugin) {
msg.Message = betterChatPlugin[3].trim();
msg.Username = `[${betterChatPlugin[1]}] ${betterChatPlugin[2]}`;
} else {
const betterChatPlugin2 = /([^:]+):(.*)/gi.exec(msg.Message);
if(betterChatPlugin2 && betterChatPlugin2[1].trim() == msg.Username.trim()) {
msg.Message = betterChatPlugin2[2].trim();
msg.Username = `${betterChatPlugin2[1]}`;
}
}
});
this.chatMessages = d.data;
setTimeout(() => {
this.chatCompo?.goToDown();
}, 100);
}
if (d.type === REType.PLAYERS) {
this.playerList = this.psSrv.savePlayerList(d.data, this.onlineFilter);
const autokick = this.playerTool.getAutoKick();
if(autokick && autokick.ping > 0) {
this.playerList.forEach(user => {
if(user.Ping > autokick.ping) {
this.rustSrv.sendCommand('kick ' + user.SteamID + ' "' + autokick.message.replace('%ping', user.Ping.toString()) + '"');
}
});
}
this.ready = true;
}
if (d.rawtype === 'Chat') {
const betterChatPlugin = /\[([^\]]+)\]\s([^:]+):(.*)/gi.exec(d.data.Message);
if(betterChatPlugin) {
d.data.Message = betterChatPlugin[3].trim();
d.data.Username = `[${betterChatPlugin[1]}] ${betterChatPlugin[2]}`;
this.recordChatMessage(d.data);
} else {
const betterChatPlugin2 = /([^:]+):(.*)/gi.exec(d.data.Message);
if(betterChatPlugin2 && betterChatPlugin2[1].trim() == d.data.Username.trim()) {
d.data.Message = betterChatPlugin2[2].trim();
d.data.Username = `${betterChatPlugin2[1]}`;
this.recordChatMessage(d.data);
} else {
this.recordChatMessage(d.data);
}
}
}
if (d.type === REType.UNKOWN) {
this.consoleMessages.push(d.raw.trim());
setTimeout(() => {
this.consoleBox.nativeElement.scrollTop = this.consoleBox.nativeElement.scrollHeight;
}, 100);
}
if (d.type === REType.BAN_LIST) {
this.consoleMessages.push('Banlist: ' + d.raw);
setTimeout(() => {
console.log(this.consoleBox);
this.consoleBox.nativeElement.scrollTop = this.consoleBox.nativeElement.scrollHeight;
}, 100);
}
if (d.type === REType.DISCONNECT || d.type === REType.ERROR) {
console.log('ERROR', d);
this.messageService.add({severity: 'error', summary: 'Disconnected', detail: 'Disconnected from server.'});
this.router.navigateByUrl('/login');
}
});
this.rustSrv.frontThreadReady();
this.setRefreshCommands();
}
setRefreshCommands() {
setInterval(() => {
this.info();
}, 1000);
this.players();
setInterval(() => {
this.players();
}, 3500);
}
players() {
this.rustSrv.players();
}
info() {
this.rustSrv.getInfo();
}
ngOnDestroy() {
this.subscription?.unsubscribe();
}
send() {
this.rustSrv.sendCommand(this.command);
this.command = '';
}
sendMessage() {
this.rustSrv.sendCommand('say ' + this.message);
this.message = '';
}
chatKp(evt: any) {
if (evt.keyCode === 13) {
this.sendMessage();
}
}
sendCMD(cmd: string) {
this.rustSrv.sendCommand(cmd);
document.getElementById('commandInput')?.focus();
}
writeCMD(cmd: string) {
this.command = cmd;
document.getElementById('commandInput')?.focus();
}
testCommand() {
this.rustSrv.sendCommand(this.command);
this.command = '';
document.getElementById('commandInput')?.focus();
}
kp(evt: any) {
if(evt.keyCode == 13) {
this.testCommand();
}
}
restart() {
this.promptSrv.openPrompt(new PromptData('Seconds before restart.', '15')).then(time => {
this.promptSrv.openPrompt(new PromptData('Reason for restart.', 'restart for update')).then(reason => {
this.rustSrv.sendCommand(`restart ${time} "${reason}"`);
}).catch(e => {
// cancelled
});
}).catch(e => {
// cancelled
});
}
skipQueue() {
this.promptSrv.openPrompt(new PromptData('Put the 64 steamID', '76561100000000000')).then(steamID => {
this.rustSrv.sendCommand('skipqueue ' + steamID);
});
}
unban() {
this.promptSrv.openPrompt(new PromptData('Put the steamID')).then(steamID => {
this.rustSrv.sendCommand('unban ' + steamID);
});
}
banlist() {
this.rustSrv.banList();
}
config() {
this.openedConfig = true;
}
help() {
window.open('https://www.corrosionhour.com/rust-admin-commands/', "__blank");
}
changeFilterOnline(onlineFilter: boolean) {
this.onlineFilter = onlineFilter;
this.players();
}
github() {
window.open('https://github.com/alexander171294/RustMon', "__blank");
}
recordChatMessage(data: any) {
if(this.chatMessages) {
this.chatMessages.push(data);
setTimeout(() => {
this.chatCompo?.goToDown();
}, 100);
} else {
setTimeout(() => { this.recordChatMessage(data); }, 100); // chat stack not received, retry in 100ms
}
}
}
<file_sep>/rustmon/src/app/dashboard/chat/chat.component.ts
import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { OverlayPanel } from 'primeng/overlaypanel';
import { MenuItem, MessageService } from 'primeng/api';
import { ChatMessage } from 'src/app/rustRCON/ChatMessage';
import { RustService } from 'src/app/rustRCON/rust.service';
import { Clipboard } from 'src/app/utils/clipboard';
import { PromptData, PromptService } from '../prompt/prompt.service';
import { PlayerStorageService } from 'src/app/rustRCON/player-storage.service';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit {
ctxMenu: MenuItem[] = [
{ label: 'Chat', items: [
{ label: 'Mute', command: (event) => this.ctxMute(event) },
{ label: 'Unmute', command: (event) => this.ctxUnmute(event) },
]},
{ label: 'Moderation', items: [
{ label: 'Ban', command: (event) => this.ctxBan(event) },
{ label: 'Kick', command: (event) => this.ctxKick(event) },
]},
{ label: 'TeamInfo', command: (event) => this.ctxTeamInfo(event) },
{ label: 'Steam', items: [
{ label: 'Steam Profile', command: (event) => this.ctxSteamProfile(event) },
{ label: 'Copy STEAMID', command: (event) => this.ctxSteamID(event)},
]},
{ label: 'Copy Message', command: (event) => this.ctxMessage(event)}
];
@Input() chatMessages?: ChatMessage[];
@Input() showTeamMessages?: boolean;
clickedMessage?: ChatMessage;
contextMessage?: ChatMessage;
@ViewChild('chat', {static: true}) chatBox: any;
constructor(private rustSrv: RustService,
private messageService: MessageService,
private promptSrv: PromptService,
private playerStrg: PlayerStorageService) { }
ngOnInit() {
}
getAvatar(id: string) {
const user = this.playerStrg.getCachedUData(id);
return user.userData && user.userData.avatarmedium ? user.userData.avatarmedium : '/favicon.png';
}
showData(evt: any, message: ChatMessage, overlaypanel: OverlayPanel) {
this.clickedMessage = message;
overlaypanel.toggle(evt);
}
goToDown() {
this.chatBox.nativeElement.scrollTop = this.chatBox.nativeElement.scrollHeight;
}
ctxBan(evt: any) {
if(this.contextMessage) {
this.ban(this.contextMessage.UserId, this.contextMessage.Username);
}
this.contextMessage = undefined;
}
ctxKick(evt: any) {
if(this.contextMessage) {
this.kick(this.contextMessage.UserId, this.contextMessage.Username);
}
this.contextMessage = undefined;
}
ctxMute(evt: any) {
if(this.contextMessage) {
this.rustSrv.sendCommand('mute ' + this.contextMessage.UserId);
this.messageService.add({severity: 'success', summary: 'Muted', detail: this.contextMessage.UserId + ' | ' + this.contextMessage.Username});
}
this.contextMessage = undefined;
}
ctxUnmute(evt: any) {
if(this.contextMessage) {
this.rustSrv.sendCommand('unmute ' + this.contextMessage.UserId);
this.messageService.add({severity: 'success', summary: 'Unmuted', detail: this.contextMessage.UserId + ' | ' + this.contextMessage.Username});
}
this.contextMessage = undefined;
}
ctxTeamInfo(evt: any) {
if(this.contextMessage) {
this.rustSrv.sendCommand('teaminfo ' + this.contextMessage.UserId);
}
this.contextMessage = undefined;
}
ctxSteamProfile(evt: any) {
if(this.contextMessage) {
window.open('https://steamcommunity.com/profiles/' + this.contextMessage.UserId, '_blank');
}
this.contextMessage = undefined;
}
ctxSteamID(evt: any) {
if(this.contextMessage) {
if(Clipboard.writeText(this.contextMessage.UserId)) {
this.messageService.add({severity: 'success', summary: 'Copied to clipboard.', detail: this.contextMessage.UserId + ' | ' + this.contextMessage.Username});
} else {
this.messageService.add({severity: 'info', summary: 'Clipboard disabled :(.', detail: this.contextMessage.UserId + ' | ' + this.contextMessage.Username});
}
}
this.contextMessage = undefined;
}
ctxMessage(evt: any) {
if(this.contextMessage) {
const message = '['+this.contextMessage.UserId+']('+this.contextMessage.Username+'): ' + this.contextMessage.Message;
if(Clipboard.writeText(message)) {
this.messageService.add({severity: 'success', summary: 'Copied to clipboard.', detail: message});
} else {
this.messageService.add({severity: 'info', summary: 'Clipboard disabled :(', detail: message});
}
}
this.contextMessage = undefined;
}
ctxSelect(message: ChatMessage, $event: any) {
this.contextMessage = message;
}
ban(steamID: string, name: string) {
this.promptSrv.openPrompt(new PromptData('ban('+name+') Write the reason:')).then(reason => {
this.rustSrv.sendCommand('banid ' + steamID + ' "' + name + '" "' + reason + '"');
this.messageService.add({severity: 'success', summary: 'Banned', detail: this.contextMessage?.UserId + ' | ' + this.contextMessage?.Username});
});
}
kick(steamID: string, name: string) {
this.promptSrv.openPrompt(new PromptData('kick('+name+') Write the reason:')).then(reason => {
this.rustSrv.sendCommand('kick ' + steamID + ' "' + reason + '"');
this.messageService.add({severity: 'success', summary: 'Banned', detail: this.contextMessage?.UserId + ' | ' + this.contextMessage?.Username});
});
}
}
<file_sep>/rustmon/src/app/api/user-data.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { MapData } from './MapDataDto';
import { UserDataDTO } from './UserDataDto';
@Injectable({
providedIn: 'root'
})
export class UserDataService {
constructor(private http: HttpClient) { }
public getBatchUserData(items: UDataItem[]): Observable<UserDataDTO[]> {
return this.http.post<UserDataDTO[]>(`${environment.uDataApi}/udata`, items);
}
public getUserData(steamId: string, ip: string): Observable<UserDataDTO> {
return this.http.get<UserDataDTO>(`${environment.uDataApi}/udata?steamID=${steamId}&ip=${ip}`);
}
public clearCache(steamId: string): Observable<string> {
return this.http.get(`${environment.uDataApi}/invalidate?steamID=${steamId}`, {responseType: 'text'});
}
public getMap(seed: string, size: string) {
return this.http.get<MapData>(`${environment.uDataApi}/mapdata?seed=${seed}&size=${size}`);
}
public mapInvalidateCache(seed: string, size: string) {
return this.http.get<MapData>(`${environment.uDataApi}/mapdata/invalidate?seed=${seed}&size=${size}`);
}
}
export interface UDataItem {
steamID: string;
ip: string;
}
<file_sep>/rustmon/src/app/rustRCON/ServerInfo.ts
export class ServerInfo {
public Hostname: string = '';
public MaxPlayers: number = 0;
public Players: number = 0;
public Queued: number = 0;
public Joining: number = 0;
public EntityCount: number = 0;
public GameTime: string = '';
public Uptime: number = 0;
public Map: string = '';
public Framerate: number = 0;
public Memory: number = 0;
public Collections: number = 0;
public NetworkIn: number = 0;
public NetworkOut: number = 0;
public Restarting: boolean = false;
public SaveCreatedTime: string = '';
}
<file_sep>/rustmon/src/app/dashboard/player-tools/player-tools.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { PlayerToolsService } from './player-tools.service';
@Component({
selector: 'app-player-tools',
templateUrl: './player-tools.component.html',
styleUrls: ['./player-tools.component.scss']
})
export class PlayerToolsComponent implements OnInit {
@Output()
public close: EventEmitter<void> = new EventEmitter<void>();
public maxPingAllowed: number = 0;
public message: string = '';
public tab = 0;
constructor(private playerTool: PlayerToolsService) { }
ngOnInit() {
const autokick = this.playerTool.getAutoKick();
if(autokick) {
this.maxPingAllowed = autokick.ping;
this.message = autokick.message;
}
}
save() {
this.playerTool.saveAutoKick(this.maxPingAllowed, this.message);
this.close.emit();
}
}
<file_sep>/user-data-srv/src/UserDataDTO.ts
export class UserDataDTO {
public userData: DataResponse;
public vacData: VacResponse;
public countryCode: string;
public xCached?: boolean;
public xGeo?: string;
}
// https://developer.valvesoftware.com/wiki/Steam_Web_API#GetPlayerSummaries_.28v0002.29
export class DataResponse {
public SteamId: string;
public communityvisibilitystate: SteamVisibleStates;
public profilestate?: 1;
public personaname: string;
public commentpermission: number;
public profileurl: string;
public avatar: string;
public avatarmedium: string;
public avatarfull: string;
public avatarhash: string;
public personastate: SteamPersonaStates;
public realname: string;
public primaryclanid: string;
public timecreated: number;
public personastateflags: number;
public gameserverip: string;
public gameserversteamid: string;
public gameextrainfo: string;
public gameid: string;
public loccountrycode: string;
public locstatecode: string;
public loccityid: number;
}
// 1 - the profile is not visible to you (Private, Friends Only, etc), 3 - the profile is "Public", and the data is visible.
export enum SteamVisibleStates {
PRIVATE = 1,
PUBLIC = 3,
}
// 0 - Offline, 1 - Online, 2 - Busy, 3 - Away, 4 - Snooze, 5 - looking to trade, 6 - looking to play.
export enum SteamPersonaStates {
OFFLINE = 0,
ONLINE = 1,
BUSY = 2,
AWAY = 3,
SNOOZE = 4,
LOOKING_TRADE = 5,
LOOKING_PLAY = 6
}
export class VacResponse {
public SteamId: string;
public CommunityBanned: boolean;
public VACBanned: boolean;
public NumberOfVACBans: number;
public DaysSinceLastBan: number;
public NumberOfGameBans: number;
public EconomyBan: string;
}
<file_sep>/rustmon/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { RustService } from '../rustRCON/rust.service';
import { REType } from '../rustRCON/RustEvent';
import { HashParser } from '../utils/hasParser';
import { ConectionData, ConnectionHistoryService } from './connection-history.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
public serverIP: string = '';
public rconPort: number = 0;
public rconPasswd: string = '';
public loginLoading: boolean = false;
public connections: ConectionData[] = [];
public connectionSelected: number = 0;
constructor(private rustSrv: RustService,
private connectionHistory: ConnectionHistoryService,
private messageService: MessageService,
private router: Router) { }
ngOnInit() {
this.connections = this.connectionHistory.getServerList();
this.previousSessionLoad(null, 0);
if (window.location.hash) {
const params = HashParser.getHashParams();
if(params.server) {
this.serverIP = params.server;
}
if(params.rport) {
this.rconPort = parseInt(params.rport);
}
if(params.password) {
this.rconPasswd = params.password;
}
}
}
previousSessionLoad(evt: any, idConn: number) {
const conection = this.connections[idConn];
if(conection) {
this.serverIP = conection.server;
this.rconPort = parseInt(conection.port);
this.rconPasswd = conection.password;
}
}
kpConn(evt: any) {
if(evt.keyCode == 13) {
this.connect();
}
}
connect() {
this.loginLoading = true;
this.connectionHistory.save(this.serverIP, this.rconPort.toString(), this.rconPasswd);
const subscription = this.rustSrv.connect(this.serverIP, this.rconPort, this.rconPasswd).subscribe(d => {
if(d.type === REType.CONNECTED) {
subscription.unsubscribe();
this.router.navigateByUrl('/dashboard').then(navigated => {
if(navigated) {
this.loginLoading = false;
}
});
} else if (d.type === REType.DISCONNECT || d.type == REType.ERROR) {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Can\'t connect to server.'});
this.loginLoading = false;
subscription.unsubscribe();
}
});
}
}
<file_sep>/rustmon/src/app/utils/hasParser.ts
export class HashParser {
public static getHashParams(): {[key: string]: string} {
const parts = window.location.hash.split(';');
const kv = parts.filter(part => part.indexOf('=') >= 0).map(part => part.split('='));
const out: any = {};
kv.forEach(kvi => {
out[kvi[0]] = kvi[1];
})
return out;
}
}
<file_sep>/user-data-srv/src/queue/queue.util.ts
import { Logger } from '@nestjs/common';
export class Queue {
private readonly logger = new Logger('QueueHandler');
public inProgress: boolean = false;
public queue: Promise<any>[] = [];
public results: any[] = [];
public addToQueue(promise: Promise<any>): boolean {
if(!this.inProgress) {
this.queue.push(promise);
return true;
}
return false;
}
public processQueue(): Promise<any[]> {
if(this.inProgress) {
return;
}
return new Promise<any[]>((res, rej) => {
this.logger.debug("processing in queue " + this.queue.length)
if(!this.processNext(res)) {
this.logger.debug("Queue rejected, nothing to process");
rej(); // nada para procesar
}
});
}
private processNext(res) {
if(this.queue.length > 0) {
this.inProgress = true;
this.queue[0].then(uDataRes => {
this.results.push(uDataRes);
this.queue.splice(0, 1);
this.inProgress = false;
if(!this.processNext(res)) {
// nada para procesar, fin de la cola
this.logger.debug('finishing queue with results: ' + this.results.length);
res(this.results);
}
}).catch(err => {
this.processNext(res);
});
return true;
} else {
return false;
}
}
}<file_sep>/user-data-srv/src/ipGeocode/ipgeocode.service.ts
import { Observable } from 'rxjs';
import { environment } from 'src/environment';
import { HttpService } from '@nestjs/axios';
import { AxiosResponse } from 'axios'
import { Injectable } from '@nestjs/common';
@Injectable()
export class IPGeocodeService {
public readonly geocodeIpstackApi = 'https://api.ipstack.com/${IP}?access_key=' + environment.ipstackApiKey;
public readonly geocodeIPApi = 'http://ip-api.com/json/${IP}';
constructor(private http: HttpService) { }
// ipstack.com
public getIpStack(ip: string): Observable<AxiosResponse<IPData>> {
return this.http.get<IPData>(this.geocodeIpstackApi.replace('${IP}', ip));
}
// ip-api.com (free)
public getIpApi(ip: string): Observable<AxiosResponse<IPApiData>> {
return this.http.get<IPApiData>(this.geocodeIPApi.replace('${IP}', ip));
}
}
export class IPData {
public ip: string;
public hostname: string;
public type: string;
public continent_code: string;
public continent_name: string;
public country_code: string;
public country_name: string;
public region_code: string;
public region_name: string;
public city: string;
public zip: string;
public latitude: number;
public longitude: number;
public location: IPLocation;
public time_zone: IPTimeZone;
public currency: IPCurrency;
public connection: IPConnection;
public security: IPSecurity;
}
export class IPLocation {
public geoname_id: number;
public capital: string;
public languages: IPLangs[];
public country_flags: string;
public country_flag_emoji: string;
public country_flag_emoji_unicode: string;
public calling_code: string;
public is_eu: boolean;
}
export class IPLangs {
public code: string;
public name: string;
public native: string;
}
export class IPTimeZone {
public id: string; // "America/Los_Angeles",
public current_time: string;
public gmt_offset: number;
public code: string;
public is_daylight_saving: boolean;
}
export class IPCurrency {
public code: string;
public name: string;
public plural: string;
public symbol: string;
public symbol_native: string;
}
export class IPConnection {
public asn: string;
public isp: string;
}
export class IPSecurity {
public is_proxy: boolean;
public proxy_type?: string;
public is_crawler: boolean;
public crawler_name?: string;
public crawler_type?: string;
public is_toor: boolean;
public threat_level: string;
public threat_types?: string;
}
export class IPApiData {
public query: string;
public status?: string;
public country?: string;
public countryCode?: string;
public region?: string;
public regionName?: string;
public city?: string;
public zip?: string;
public lat?: number;
public long?: number;
public timezone?: string;
public isp?: number;
public org?: string;
public as?: string;
}
<file_sep>/rustmon/src/app/dashboard/uptime.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uptime'
})
export class UptimePipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
if (value < 60) {
return (value < 10 ? '0' + value : value) + 's';
}
const secs = value % 60;
value = Math.floor(value / 60);
if (value < 60) {
return (value < 10 ? '0' + value : value) + ':' + (secs < 10 ? '0' + secs : secs);
}
const mins = value % 60;
value = Math.floor(value / 60);
if (value < 24) {
return (value < 10 ? '0' + value : value) + ':' + (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
}
const horas = value % 24;
value = Math.floor(value / 24);
return value + 'd - ' + horas + ':' + (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
}
}
<file_sep>/rustmon/Dockerfile
### STAGE 1: Build ###
FROM node:16.10-alpine AS build
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm install
COPY . .
RUN npm run buildprod
### STAGE 2: Run ###
FROM nginx
COPY --from=build /usr/src/app/dist/rustmon /usr/share/nginx/html
COPY --from=build /usr/src/app/nginx.default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
<file_sep>/rustmon/src/app/dashboard/uptimeFixed.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uptimeFixed'
})
export class UptimeFixedPipe implements PipeTransform {
transform(value: any, ...args: any[]): any {
if (value < 0) {
return 'N/A';
}
if (value < 60) {
return '00:00:' + (value < 10 ? '0' + value : value);
}
const secs = value % 60;
value = Math.floor(value / 60);
if (value < 60) {
return '00:' + (value < 10 ? '0' + value : value) + ':' + (secs < 10 ? '0' + secs : secs);
}
const mins = value % 60;
value = Math.floor(value / 60);
if (value < 24) {
return (value < 10 ? '0' + value : value) + ':' + (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
}
const horas = value % 24;
value = Math.floor(value / 24);
return value + 'd - ' + horas + ':' + (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
}
}
<file_sep>/rustmon/src/app/utils/socket/socket.service.ts
import { Injectable, EventEmitter } from '@angular/core';
import { EventSck, EventTypeSck } from './EventSck';
@Injectable({
providedIn: 'root'
})
export class SocketService {
private ws?: WebSocket;
private socketEvent: EventEmitter<EventSck> = new EventEmitter<EventSck>();
constructor() { }
connect(url: string): EventEmitter<EventSck> {
this.ws = new WebSocket(url);
this.ws.onmessage = (d) => {
const event = new EventSck();
event.eventType = EventTypeSck.MESSAGE;
event.eventData = d;
this.socketEvent.emit(event);
};
this.ws.onclose = () => {
console.warn('closed');
const event = new EventSck();
event.eventType = EventTypeSck.DISCONNECTED;
this.socketEvent.emit(event);
};
this.ws.onerror = (e) => {
console.error('error', e);
const event = new EventSck();
event.eventType = EventTypeSck.ERROR;
event.eventData = e;
this.socketEvent.emit(event);
};
this.ws.onopen = (d) => {
const event = new EventSck();
event.eventType = EventTypeSck.CONNECTED;
event.eventData = d;
this.socketEvent.emit(event);
};
return this.socketEvent;
}
sendMessage(message: any) {
this.ws?.send(JSON.stringify(message));
}
}
<file_sep>/rustmon/src/app/rustRCON/player-storage.service.ts
import { Injectable } from '@angular/core';
import { UDataItem, UserDataService } from '../api/user-data.service';
import { UserDataDTO } from '../api/UserDataDto';
import { Player, PlayerWithStatus } from './Player';
@Injectable({
providedIn: 'root'
})
export class PlayerStorageService {
public userDataSteam: {[key: string]: UserDataDTO | undefined} = {};
public firstTime: boolean = true;
public isBatching: boolean = false;
constructor(private userDataSrv: UserDataService) { }
savePlayerList(players: Player[], onlyOnline: boolean): PlayerWithStatus[] {
const playersWS: PlayerWithStatus[] = [];
let oldPlayers = JSON.parse(localStorage.getItem('players') as string);
oldPlayers = oldPlayers ? oldPlayers : {};
const playersOnline: string[] = [];
players.forEach(el => {
oldPlayers[el.SteamID] = el;
playersOnline.push(el.SteamID);
});
if(this.firstTime) {
this.getBatchUserData(players).then((pdata) => {
pdata.forEach(data => {
this.userDataSteam[data.userData.steamid] = data;
});
this.firstTime = false;
}).catch(e => {
console.error(e);
});
let entries: unknown[][] = [];
if (onlyOnline) {
entries = Object.entries(players);
} else {
entries = Object.entries(oldPlayers);
}
return entries.map((t: unknown[]) => {
const player = t[1] as PlayerWithStatus;
player.online = onlyOnline || playersOnline.indexOf(t[0] as string) >= 0;
return player;
});
} else {
localStorage.setItem('players', JSON.stringify(oldPlayers));
Object.entries(oldPlayers).forEach(t => {
const addr = (t[1] as Player).Address.split(':')[0];
const id64 = (t[1] as Player).SteamID;
if(!this.userDataSteam[id64] && playersOnline.indexOf(t[0]) >= 0) { // si no esta en memoria y esta online
this.userDataSteam[id64] = this.getUserData(addr, id64);
}
if(this.userDataSteam[id64]) {
(t[1] as PlayerWithStatus).country = (this.userDataSteam[id64] != undefined && this.userDataSteam[id64]?.countryCode) ? (this.userDataSteam[id64] as UserDataDTO).countryCode.toLowerCase() : '';
(t[1] as PlayerWithStatus).vac = this.userDataSteam[id64]?.vacData;
(t[1] as PlayerWithStatus).steamData = this.userDataSteam[id64]?.userData;
}
(t[1] as PlayerWithStatus).notes = localStorage.getItem(`note-${id64}`);
if (onlyOnline) {
if (playersOnline.indexOf(t[0]) >= 0) {
(t[1] as PlayerWithStatus).online = true;
playersWS.push(t[1] as PlayerWithStatus);
}
} else {
(t[1] as PlayerWithStatus).online = playersOnline.indexOf(t[0]) >= 0;
playersWS.push(t[1] as PlayerWithStatus);
}
});
return playersWS;
}
}
public getCachedUData(id64: string): UserDataDTO {
if(this.userDataSteam[id64]) {
return this.userDataSteam[id64] as UserDataDTO;
} else {
return new UserDataDTO();
}
}
public getUserData(addr: string, id64: string): UserDataDTO {
this.userDataSrv.getUserData(id64, addr).subscribe(data => {
this.userDataSteam[id64] = data;
}, e => {
setTimeout(() => {
this.userDataSteam[addr] = undefined;
}, 1000)
});
return new UserDataDTO();
}
public getBatchUserData(allPlayers: any): Promise<UserDataDTO[]> {
if (this.isBatching) {
return Promise.reject('batch running');
}
this.isBatching = true;
const pys: UDataItem[] = [];
Object.entries(allPlayers).forEach((t: unknown[]) => {
const player = t[1] as Player;
const addr = player.Address.split(':')[0];
pys.push({
ip: addr,
steamID: player.SteamID
});
});
return new Promise<UserDataDTO[]>((res, rej) => {
this.userDataSrv.getBatchUserData(pys).subscribe(data => {
res(data);
}, e => {
rej(e);
});
});
}
public saveNote(id64: string, note: string) {
localStorage.setItem(`note-${id64}`, note);
}
}
<file_sep>/user-data-srv/src/app.controller.ts
import { Queue } from './queue/queue.util';
import { Body, Controller, Get, HttpException, HttpStatus, Logger, Post, Query, Response } from '@nestjs/common';
import { IPApiData, IPGeocodeService } from './ipGeocode/ipgeocode.service';
import { SteamVisibleStates, UserDataDTO } from './UserDataDTO';
import { PlayerDataResponse, PlayerVacsResponse, ValveApiService } from './valve/valve-api.service';
import { AxiosResponse } from 'axios';
import { CacheRedisService } from './redis/redis.service';
import { environment } from './environment';
import { Response as Res } from 'express';
import { RustMapService } from './rustmap/rustmap.service';
@Controller()
export class AppController {
private readonly logger = new Logger(AppController.name);
constructor(private valveApi: ValveApiService,
private geocode: IPGeocodeService,
private redis: CacheRedisService,
private rustMap: RustMapService) {}
@Get('udata')
async getUserData(@Query('steamID') steamID: string, @Query('ip') ip: string, @Response() res: Res) {
if(!steamID) {
throw new HttpException('steamID required param', HttpStatus.BAD_REQUEST);
}
try {
const user = await this.getIUserData(steamID, ip);
res.set({ 'x-cached': user.xCached ? 'yes' : 'no', 'x-geo': user.xGeo }).json(user);
} catch(e) {
throw new HttpException(e.msg, e.code);
}
}
@Post('udata')
async batchUserData(@Body() data: UDataItem[], @Response() res: Res) {
if(!data && Array.isArray(data)) {
throw new HttpException('body required, and must be an array', HttpStatus.BAD_REQUEST);
}
const queue = new Queue();
data.forEach(user => {
queue.addToQueue(this.getIUserData(user.steamID, user.ip));
});
queue.processQueue().then(result => {
res.json(result);
});
}
private async getIUserData(steamID: string, ip: string): Promise<UserDataDTO> {
const udata: UserDataDTO = await this.redis.getFromCache(steamID, true);
return new Promise((res, rej) => {
if(udata) {
udata.xCached = true;
res(udata);
return;
}
const result = new UserDataDTO();
this.valveApi.getUserData(steamID).subscribe((d: AxiosResponse<PlayerDataResponse>) => {
if(d.data.response.players.length == 0) {
rej({msg: 'SteamID not found', code: HttpStatus.NOT_FOUND })
} else {
result.userData = d.data.response.players[0];
this.valveApi.getVacs(steamID).subscribe((d: AxiosResponse<PlayerVacsResponse>) => {
result.vacData = d.data.players[0];
if((result.userData.communityvisibilitystate != SteamVisibleStates.PUBLIC || !result.userData.loccountrycode) && ip) {
if(ip.indexOf(':') > 0) {
ip = ip.split(':')[0];
}
this.logger.warn('Geocoding ip ' + ip)
this.geocode.getIpApi(ip).subscribe((d: AxiosResponse<IPApiData>) => {
this.logger.warn('Geocoded ok ' + JSON.stringify(d.data))
result.countryCode = d.data.countryCode;
this.saveInCache(steamID, result);
result.xCached = false;
result.xGeo = 'yes';
res(result);
}, e => {
this.logger.error("Error getting geoip", e);
this.saveInCache(steamID, result);
result.xCached = false;
result.xGeo = 'err';
res(result);
})
} else {
result.countryCode = result.userData.loccountrycode;
this.saveInCache(steamID, result);
result.xCached = false;
result.xGeo = 'steam-def';
res(result);
}
}, e => {
this.logger.error("Error getting vac", e)
rej({msg: 'Error getting vac', code: HttpStatus.BAD_GATEWAY });
});
}
}, e => {
this.logger.error("Error getting userdata", e);
rej({msg: 'Error getting user data', code: HttpStatus.BAD_GATEWAY });
});
});
}
private saveInCache(id64: string, result: UserDataDTO) {
this.redis.saveInCache(id64, environment.secondsCacheUsers, result);
}
@Get('invalidate')
async invalidateCache(@Query('steamID') steamID: string) {
return this.redis.invalidate(steamID) ? 'OK' : 'NOK';
}
@Get('mapdata')
async getMapData(@Query('seed') seed: number, @Query('size') worldSize: number) {
const mapKey = `map-${seed}-${worldSize}`;
const map = await this.redis.getFromCache(mapKey, true);
if(map) {
return map;
} else {
const mapDetails = await this.rustMap.getRustData(worldSize.toString(), seed.toString());
return mapDetails;
}
}
@Get('mapdata/invalidate')
async invalidateMapCache(@Query('seed') seed: number, @Query('size') worldSize: number) {
const mapKey = `map-${seed}-${worldSize}`;
return this.redis.invalidate(mapKey) ? 'OK' : 'NOK';
}
}
export interface UDataItem {
steamID: string;
ip: string;
}<file_sep>/README.md
# RustMon
Rust game admin tool for servers (RustMonitor)
## Run and build
Install dependencies:
`npm i`
Run local dev mode:
`ng serve`
Build redist package:
`ng build --prod`
or if you don't have angular installed
`npm run buildprod`
## Screenshots:
### Login

### Dashboard

### Server configurations


### Player details and search

### Player tools

# run with docker in server:
## Dashboard:
```
docker run -p 80:80 -itd alexander171294/rustmon:latest
```
Or see live instance in:
[rustmon.tercerpiso.net](https://rustmon.tercerpiso.net)
## Backend Service:
Api for get steam-profile, api-geolocalization, rustmap info:
First, in order to use your custom served api, you need to edit environment.prod.ts and change `http://rustmon-udata.tercerpiso.tech/` for your endpoint and rebuild docker image, or run ng build again with your changes.
Second, you need to start a redis service (it is used for cache user data).
Third, you need to run our docker image of rustmon-service with your api key and environments and expose in your endpoint:
```
docker run -p 80:3000 -e STEAM_API="YOUR-STEAM-API-KEY" -e CACHE_HOST="YOUR-REDIS-HOST" -e CACHE_AUTH="YOUR-REDIS-PASSWORD" -e CACHE_PORT="YOUR-REDIS-PORT" -itd alexander171294/rustmon-service:latest
```
### How to get my steam api key?
[See steam api key documentation](https://steamcommunity.com/dev/apikey)<file_sep>/rustmon/src/app/dashboard/player-tools/player-tools.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PlayerToolsService {
constructor() { }
public saveAutoKick(ping: number, message: string) {
localStorage.setItem('autokick', JSON.stringify({
ping,
message
}));
}
public getAutoKick(): AutoKick {
return JSON.parse(localStorage.getItem('autokick') as string);
}
}
export interface AutoKick {
ping: number;
message:string;
}<file_sep>/rustmon/src/app/utils/socket/EventSck.ts
export class EventSck {
public eventType?: EventTypeSck;
public eventData: any;
}
export enum EventTypeSck {
CONNECTED,
DISCONNECTED,
ERROR,
MESSAGE
}
<file_sep>/rustmon/src/app/dashboard/prompt/prompt.component.ts
import { PromptService } from './prompt.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-prompt',
templateUrl: './prompt.component.html',
styleUrls: ['./prompt.component.scss']
})
export class PromptComponent implements OnInit {
visible: boolean = false;
promptName: string = '';
promptPlaceholder: string = '';
promptInput: string = '';
constructor(private pSrv: PromptService) {
}
ngOnInit() {
this.pSrv.onPromptOpened.subscribe(d => {
this.promptName = d.promptName;
this.promptPlaceholder = d.promptPlaceholder ? d.promptPlaceholder : '';
this.visible = true;
this.promptInput = '';
setTimeout(() => {
document.getElementById('input_popup_prompt')?.focus();
}, 50);
});
}
cancel() {
this.pSrv.close();
this.visible = false;
}
ok() {
this.pSrv.close(this.promptInput);
this.visible = false;
}
kp(evt: any) {
if(evt.keyCode == 13) {
this.ok();
}
}
}
<file_sep>/user-data-srv/src/redis/redis.service.ts
import { Injectable, Logger } from '@nestjs/common';
import * as redis from 'redis';
import { Subject } from 'rxjs';
import { environment } from 'src/environment';
const crypto = require('crypto');
@Injectable()
export class CacheRedisService {
private readonly logger = new Logger(CacheRedisService.name);
private readonly redisClient: redis.RedisClient;
private onError: Subject<any> = new Subject<any>();
constructor() {
this.redisClient = redis.createClient({
host: environment.redis.host,
auth_pass: environment.redis.auth_pass,
port: environment.redis.port
});
this.redisClient.on('error', (err) => {
this.logger.error('Redis cache error ' + err.toString());
this.onError.next(err);
});
}
public getOnError(): Subject<any> {
return this.onError;
}
/**
*
* @param key the key to store in cache and recover
* @param ttl the time to live seconds (time in cache before auto-remove)
* @param data the data to save in cache
*/
public saveInCache(key: string, ttl: number, data: string | object): boolean {
if(typeof data == 'object') {
data = JSON.stringify(data);
}
return this.redisClient.setex(key, ttl, data);
}
/**
* @param key the key of value saved in cache
* @param asObject parse json or return string? if json is invalid, return the string
* @returns false, Object, String
*/
public getFromCache(key: string, asObject?: boolean): Promise<any> {
return new Promise<any>((res, rej) => {
this.redisClient.get(key, (err, data) => {
if(err) {
rej(err);
} else {
if(data) {
if(asObject) {
try {
const _data = JSON.parse(data);
if(_data) {
data = _data;
}
} catch(e) {}
}
res(data);
} else {
res(false);
}
}
});
});
}
/**
*
* @param key delete key and value from cache.
*/
public invalidate(key: string) {
return this.redisClient.del(key);
}
/**
* create hash md5 of data to generate key based on values:
* @param data data to checksum
*/
public checksum(data: string) {
return crypto.createHash('md5').update(data).digest('hex').toString();
}
/**
*
* @param key clear kvs.
*/
public flushAll() {
return this.redisClient.flushall();
}
}<file_sep>/rustmon/src/app/rustRCON/RustEvent.ts
export class RustEvent {
public type?: REType;
public data: any;
public raw: string = '';
public rawtype: string = '';
}
export enum REType {
CONNECTED = -3000,
ERROR = -2000,
DISCONNECT = -1000,
UNKOWN = 0,
GET_INFO = 1000,
CHAT_STACK = 1001,
PLAYERS = 1002,
BAN_LIST = 1003,
SRV_INFO = 1004,
}
<file_sep>/release.sh
echo Version number:
read version
docker build -t alexander171294/rustmon ./rustmon
docker tag alexander171294/rustmon:latest alexander171294/rustmon:$version
docker push alexander171294/rustmon
docker push alexander171294/rustmon:$version
docker build -t alexander171294/rustmon-service ./user-data-srv
docker tag alexander171294/rustmon-service:latest alexander171294/rustmon-service:$version
docker push alexander171294/rustmon-service
docker push alexander171294/rustmon-service:$version
git tag $version
git push origin --tags | 5d2a99cd3f3638dc2d96b5f27aeeb871cb532a54 | [
"Markdown",
"TypeScript",
"Dockerfile",
"Shell"
] | 42 | Dockerfile | alexander171294/RustMon | d20fb601258f57da552037045464cdd6c692c1d5 | 8d4fa0a6e8617db1ca20578beeaf7e6a1bab81cf |
refs/heads/main | <repo_name>Misil4/PHP-Basic<file_sep>/ejercicio11.php
<?php
// 11. Dado un array con números positivos y negativos, declarar una función que recoja el array como argumento y realice lo siguiente:
// La función deberá crear un array nuevo con los números positivos, ordenarlos de menor a mayor y devolver el array.
// Ejecutar la función y mostrar el array ordenado.
// Nota: No se pueden utilizar la clase ARRAY ni funciones predefinidas de JAVASCRIPT (PUSH, etc..).
// PISTA: El nuevo array deberá tener una dimensión tal que: Length(nuevo) = Length(viejo) - num_elementos_negativos
$arrayNum1 = array(12, -3, 34, 567, -19, 57, 0);
$berria = array();
for ($i =0;$i<count($arrayNum1);$i++) {
if ($arrayNum1[$i] >=0) {
$berria[$i] = $arrayNum1[$i];
}
}
sort($berria);
print_r($berria);
<file_sep>/ejercicio17.php
<?php
// Basándose en el ejercicio de JavaScript ejercicio9.js (Cálculo de suma con llevada de dos números almacenados en arrays) realizar lo siguiente:
// Resta con llevada de los siguientes números: 412 - 284 = 128
$elements = 3;
$array = array(4, 1, 2);
$array1 = array(2, 8, 4);
$array2 = array();
$llevada = 0;
$resta = 0;
for ($i = $elements - 1; $i >= 0; $i--) {
if ($array[$i] - $llevada >= $array1[$i]) {
$resta = $array[$i] - $array1[$i] - $llevada;
$llevada = 0;
} else {
$resta = 10 + $array[$i] - $array1[$i] - $llevada;
$llevada = 1;
}
$array2[$i] = $resta;
}
for ($i = 0; $i < count($array2); $i++) {
echo $array2[$i];
}
<file_sep>/ejercicio13.php
<?php
// 12. Dado el siguiente array de objetos.
$products = array(
'banana' => array(
'code:' => "SKI-203",
'name:' => "Banana",
'price:' => 200,
'qty:' => 31,
'imported:' => true,
'type:' => "Tropical"),
'pomelo' => array(
'code:'=> "SFI-233",
'name: '=>"Pomelo",
'price:'=> 55,
'qty:'=>325,
'imported:'=> false,
'type:' =>"Tropical"),
'Piña' => array(
'code:' =>"JKI-453",
'name:' =>"Piña",
'price:'=> 70,
'qty:'=> 125,
'imported:'=> false,
'type:'=> "Oceanic"),
'Coco' => array(
'code:' =>"CDC-113",
'name:' =>"Coco",
'price:'=> 120,
'qty:'=> 25,
'imported:'=> true,
'type:'=> "Oceanic"),
'Papaya' => array(
'code:'=> "SWI-265",
'name:'=> "Papaya",
'price:'=> 200,
'qty:'=> 725,
'imported:'=> true,
'type:'=> "Tropical"
)
);
foreach($products as $filtrar) {
if ($filtrar['qty:'] < 50) {
print_r($filtrar);
echo '<br>';
}
}
// Mostrar por pantalla todos los elementos cuya cantidad (qty) sea menor de 50 ((Declarar una función para ello))
<file_sep>/ejercicio18.php
<?php
$numero = 57;
$divisor = 8;
$cociente = 0;
$resto = 0;
$aux = $numero;
while ($aux >= $divisor) {
$cociente++;
$aux -= $divisor;
}
$resto = $aux;
echo $numero , " / " , $divisor , " = " , $cociente ,"(cociente), ", $resto,"(resto)";
?><file_sep>/ejercicio10.php
<?php
// 10. Dado un array, declarar una función que recoja el array como argumento y lo ordene de menor a mayor.
// Ejecutar la función y mostrar el array ordenado.
// Nota: No se pueden utilizar funciones predefinidas de JAVASCRIPT.
$arrayNum1 = array(12, 23, 34, 567, 19, 57);
$numelements = count($arrayNum1);
for ($i = 0; $i < $numelements-1; $i++) {
for ($j = $i+1; $j < $numelements; $j++) {
if ($arrayNum1[$i] > $arrayNum1[$j]) {
$k = $arrayNum1[$i];
$arrayNum1[$i] = $arrayNum1[$j];
$arrayNum1[$j] = $k;
}
}
}
for ($i = 0; $i < count($arrayNum1); $i++) {
echo $arrayNum1[$i]," ";
}
<file_sep>/ejercicio3.php
<?php
// 3.- Declarar una función que muestre los números impares de 0 a 100. Mostrar el resultado de la función
// Ejecutar la función.
for ($contador = 0;$contador<=100;$contador++) {
if ($contador%2!=0) {
echo $contador ,' es impar';
}
}
?><file_sep>/ejercicio4.php
<?php
// 4.- Declarar una función que muestre la tabla de multiplicar de la siguiente manera:
// 1 * 1 = 1
// 1 * 2 = 2
// ...
// ...
// 8 * 5 = 40
// ...
// 10 * 9 = 90
// 10 * 10 = 100
// Nota: Tiene que aparecer la tabla entera, en LÍNEAS SEPARADAS
// Ejecutar la funciónp
for ( $i = 1; $i < 11; $i++)
{
echo "tabla de el ", $i .'<br>';
for ($j = 0; $j < 11; $j++)
{
$bider = $i*$j;
echo $i, " * ", $j," = ", $bider .'<br/>';
}
}
?><file_sep>/ejercicio7.php
<?php
// 7. Declarar una función que sume cada elemento del primer array con cada elemento del segundo (en la misma posición) y devuelva el array con la suma de ambos.
// A continuación ejecutar la función y mostrar en pantalla el array de la Suma al completo.
$arrayNum1 = array(1, 23, 34);
$arrayNum2 = array(6, 7, 50);
$suma1 = $arrayNum1[0]+$arrayNum2[0];
$suma2 = $arrayNum1[1]+$arrayNum2[1];
$suma3 = $arrayNum1[2]+$arrayNum2[2];
echo "los resultados son: ".'<br>',$arrayNum1[0],"+",$arrayNum2[0],"=",$suma1.'<br>',$arrayNum1[1],"+",$arrayNum2[1],"=",$suma2.'<br>',$arrayNum1[2],"+",$arrayNum2[2],"=",$suma3.'<br>';
?><file_sep>/ejercicio5.php
<?php
// 5.- Declarar una función que recibe 2 números como parámetros, devuelve el mayor de los dos y si son iguales devuelve un mensaje.
// Mostrar el resultado de la función
// Ejecutar la función.
$num1 = 6;
$num2 = 5;
echo "los numeros son " , $num1 , " y " , $num2;
if ($num1 > $num2) {
echo '<br>' , "el numero mas grande es " , $num1;
}
else if ($num1 == $num2) {
echo '<br>', "son iguales";
}
else
echo '<br>', "el numero mas grande es ", $num2;
<file_sep>/ejercicio6.php
<?php
// 6. Declarar una función que sume los elementos del siguiente array y devuelva la suma (como VALOR DE RETORNO).
// A continuación ejecutar la función y mostrar en pantalla: 'Suma: XX"
$arrayNum = array(1, 23, 34);
echo "Numeros que componen el array";
for ($i = 0;$i<count($arrayNum);$i++) {
echo '<p>',$arrayNum[$i];
}
echo '<p>' ,"Resultado";
$suma = $arrayNum[0]+$arrayNum[1]+$arrayNum[2];
echo '<br>','<br>',$suma;
?><file_sep>/ejercicio1.php
<?php
$a = 12;
$b = 36;
$c = 3;
$suma = $a+$b+$c;
$media = $suma/3;
echo $media;
?>
<file_sep>/ejercicio9.php
<?php
// 9. Se dan dos números en forma de array. Se trata de declarar una función que los recoja como argumento, los sume y devuelva el array con el número SUMA.
// Ejemplo: 123 = [1,2,3]
// 458 = [4,5,6]
// SUMA: 581 = [5,8,1]
//
// NOTA: Por simplicidad los dos arrays deberán tener la misma dimensión.
// PISTA: La dimensión del array de devolución sera la dimensión de los arrays de entrada + 1. Además, habrá que tener en cuenta el acarreo (la llevada).
// Se trata de SUMAR TAL Y COMO LO HARÍAIS EN PAPEL, de derecha a izquierda.
//
//Ejecutaremos la función y sacaremos en pantalla un texto en la forma: '123 + 458 = 581' (En el caso del ejemplo)
//Podéis hacer pruebas con diferentes números. Como ejemplo se dan los números 976 y 385.
$elements = 3;
$array = array(6,8,2);
$array1 = array(4,7,9);
$array2 = array();
$llevada = 0;
$sumcifra = 0;
$resto = 0;
for ($i =$elements-1 ; $i >=0; $i--) {
$sumcifra = $array[$i] - $array1[$i]-$llevada;
$llevada = $sumcifra / 10;
$resto = $sumcifra % 10;
$array2[$i + 1] = $resto;
$array2[0] = $llevada;
}
for ($i = 0;$i<count($array2);$i++ ) {
echo $array2[$i];
break;
}
?>
<file_sep>/sueldo.php
<?php
class empleado
{
private $nombre;
private $sueldo;
public function __construct($izena, $sueldo)
{
$this->nombre = $izena;
$this->sueldo = $sueldo;
}
private function impuestos()
{
if ($this->sueldo > 3000) {
echo $this->nombre, ", tu sueldo es ", $this->sueldo, " y tienes que pagar impuestos";
} else {
echo "tu sueldo es ", $this->sueldo, " y no tienes que pagar impuestos";
}
}
}
$empleado1 = new empleado("iker", 3500);
$empleado1->impuestos();
<file_sep>/ejercicio8.php
<?php
// 8. Declarar una función en la que se pase el array siguiente como argumento. A continuación extraiga el elemento mayor y el menor del array,
// y devuelva la diferencia entre ambos valores.
// Ejecutar la función y mostrar el resultado.
// Ejemplo: var arrayNum1 = [1, 23, 34];
// La función devolvería 34-1 = 33
$arrayNum1 = array(12, 23, 34, 567, 19, 57);
$pequeño = $arrayNum1[0];
$grande = 0;
for ($i = 0; $i < count($arrayNum1); $i++) {
if ($arrayNum1[$i] > $grande) {
$grande = $arrayNum1[$i];
}
else if ($arrayNum1[$i] < $pequeño) {
$pequeño = $arrayNum1[$i];
}
}
echo $pequeño , " es el menor" . '<br>' , $grande , "es el mayor";
?><file_sep>/ejercicio2.php
<?php
// 2.- Declarar una función que recibe como parámetros a , b , c y opcion.
// Si opcion es true multiplica a y b y divide entre c. Mostrar el resultado de la función
// Ejecutar la función.
$a = 12;
$b = 36;
$c = 3;
$opcion = true;
if ($opcion) {
$operaketa = $a*$b/($c);
echo "el resultado es ", $operaketa;
}
?> | e36de9418f41ebe2aa1547838f881fdb4c9acc17 | [
"PHP"
] | 15 | PHP | Misil4/PHP-Basic | de880554f01cce7ab2bc38abd8f838a04d91b634 | 7fc9432eeabeb5a8bc31bd00f233f6c166c46a85 |
refs/heads/master | <file_sep>import { Component, Input, Output, EventEmitter } from '@angular/core';
import { IEvent } from './shared';
@Component({
selector: 'event-thumbnail',
templateUrl: './event-thumbnail.component.html',
styles: [`
.green {color: #003300 !important;},
.bold {font-weight: bold},
.thumbnail {min-height: 210 px},
.pad-left {margin-left: 10 px},
.well div {color: #bbb};
`]
})
export class EventThumbnailComponent {
@Input() event: IEvent
// @Output() eventClick = new EventEmitter();
// handleClickMe(): void {
// this.eventClick.emit(this.event.name);
// }
getStartTimeClass(): any {
const isEarlyStart = this.event && this.event.time === '8:00 am';
return {green: isEarlyStart, bold: isEarlyStart};
}
}
| e8a138a86897c3712716afa8683a2b345f74ec9d | [
"TypeScript"
] | 1 | TypeScript | LievStudio/ngFundamentals | b65aadf8d913d3f1c1a5b57d703dddfad9a20291 | fd1f83c02d3ab975ccb498e1c36dbe94e32e1f13 |
refs/heads/master | <file_sep>export default [
{
login: "floydprice",
id: 283,
node_id: "MDQ6VXNlcjI4Mw==",
avatar_url: "https://avatars.githubusercontent.com/u/283?v=4",
gravatar_id: "",
url: "https://api.github.com/users/floydprice",
html_url: "https://github.com/floydprice",
followers_url: "https://api.github.com/users/floydprice/followers",
following_url:
"https://api.github.com/users/floydprice/following{/other_user}",
gists_url: "https://api.github.com/users/floydprice/gists{/gist_id}",
starred_url:
"https://api.github.com/users/floydprice/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/floydprice/subscriptions",
organizations_url: "https://api.github.com/users/floydprice/orgs",
repos_url: "https://api.github.com/users/floydprice/repos",
events_url: "https://api.github.com/users/floydprice/events{/privacy}",
received_events_url:
"https://api.github.com/users/floydprice/received_events",
type: "User",
site_admin: false,
},
{
login: "sco",
id: 306,
node_id: "MDQ6VXNlcjMwNg==",
avatar_url: "https://avatars.githubusercontent.com/u/306?v=4",
gravatar_id: "",
url: "https://api.github.com/users/sco",
html_url: "https://github.com/sco",
followers_url: "https://api.github.com/users/sco/followers",
following_url: "https://api.github.com/users/sco/following{/other_user}",
gists_url: "https://api.github.com/users/sco/gists{/gist_id}",
starred_url: "https://api.github.com/users/sco/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/sco/subscriptions",
organizations_url: "https://api.github.com/users/sco/orgs",
repos_url: "https://api.github.com/users/sco/repos",
events_url: "https://api.github.com/users/sco/events{/privacy}",
received_events_url: "https://api.github.com/users/sco/received_events",
type: "User",
site_admin: false,
},
{
login: "vic",
id: 331,
node_id: "MDQ6VXNlcjMzMQ==",
avatar_url: "https://avatars.githubusercontent.com/u/331?v=4",
gravatar_id: "",
url: "https://api.github.com/users/vic",
html_url: "https://github.com/vic",
followers_url: "https://api.github.com/users/vic/followers",
following_url: "https://api.github.com/users/vic/following{/other_user}",
gists_url: "https://api.github.com/users/vic/gists{/gist_id}",
starred_url: "https://api.github.com/users/vic/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/vic/subscriptions",
organizations_url: "https://api.github.com/users/vic/orgs",
repos_url: "https://api.github.com/users/vic/repos",
events_url: "https://api.github.com/users/vic/events{/privacy}",
received_events_url: "https://api.github.com/users/vic/received_events",
type: "User",
site_admin: false,
},
{
login: "sbusso",
id: 346,
node_id: "MDQ6VXNlcjM0Ng==",
avatar_url: "https://avatars.githubusercontent.com/u/346?v=4",
gravatar_id: "",
url: "https://api.github.com/users/sbusso",
html_url: "https://github.com/sbusso",
followers_url: "https://api.github.com/users/sbusso/followers",
following_url: "https://api.github.com/users/sbusso/following{/other_user}",
gists_url: "https://api.github.com/users/sbusso/gists{/gist_id}",
starred_url: "https://api.github.com/users/sbusso/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/sbusso/subscriptions",
organizations_url: "https://api.github.com/users/sbusso/orgs",
repos_url: "https://api.github.com/users/sbusso/repos",
events_url: "https://api.github.com/users/sbusso/events{/privacy}",
received_events_url: "https://api.github.com/users/sbusso/received_events",
type: "User",
site_admin: false,
},
{
login: "rubenlozano",
id: 632,
node_id: "MDQ6VXNlcjYzMg==",
avatar_url: "https://avatars.githubusercontent.com/u/632?v=4",
gravatar_id: "",
url: "https://api.github.com/users/rubenlozano",
html_url: "https://github.com/rubenlozano",
followers_url: "https://api.github.com/users/rubenlozano/followers",
following_url:
"https://api.github.com/users/rubenlozano/following{/other_user}",
gists_url: "https://api.github.com/users/rubenlozano/gists{/gist_id}",
starred_url:
"https://api.github.com/users/rubenlozano/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/rubenlozano/subscriptions",
organizations_url: "https://api.github.com/users/rubenlozano/orgs",
repos_url: "https://api.github.com/users/rubenlozano/repos",
events_url: "https://api.github.com/users/rubenlozano/events{/privacy}",
received_events_url:
"https://api.github.com/users/rubenlozano/received_events",
type: "User",
site_admin: false,
},
{
login: "vigosan",
id: 767,
node_id: "MDQ6VXNlcjc2Nw==",
avatar_url: "https://avatars.githubusercontent.com/u/767?v=4",
gravatar_id: "",
url: "https://api.github.com/users/vigosan",
html_url: "https://github.com/vigosan",
followers_url: "https://api.github.com/users/vigosan/followers",
following_url:
"https://api.github.com/users/vigosan/following{/other_user}",
gists_url: "https://api.github.com/users/vigosan/gists{/gist_id}",
starred_url: "https://api.github.com/users/vigosan/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/vigosan/subscriptions",
organizations_url: "https://api.github.com/users/vigosan/orgs",
repos_url: "https://api.github.com/users/vigosan/repos",
events_url: "https://api.github.com/users/vigosan/events{/privacy}",
received_events_url: "https://api.github.com/users/vigosan/received_events",
type: "User",
site_admin: false,
},
{
login: "lgs",
id: 1573,
node_id: "MDQ6VXNlcjE1NzM=",
avatar_url: "https://avatars.githubusercontent.com/u/1573?v=4",
gravatar_id: "",
url: "https://api.github.com/users/lgs",
html_url: "https://github.com/lgs",
followers_url: "https://api.github.com/users/lgs/followers",
following_url: "https://api.github.com/users/lgs/following{/other_user}",
gists_url: "https://api.github.com/users/lgs/gists{/gist_id}",
starred_url: "https://api.github.com/users/lgs/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/lgs/subscriptions",
organizations_url: "https://api.github.com/users/lgs/orgs",
repos_url: "https://api.github.com/users/lgs/repos",
events_url: "https://api.github.com/users/lgs/events{/privacy}",
received_events_url: "https://api.github.com/users/lgs/received_events",
type: "User",
site_admin: false,
},
{
login: "acangiano",
id: 1687,
node_id: "MDQ6VXNlcjE2ODc=",
avatar_url: "https://avatars.githubusercontent.com/u/1687?v=4",
gravatar_id: "",
url: "https://api.github.com/users/acangiano",
html_url: "https://github.com/acangiano",
followers_url: "https://api.github.com/users/acangiano/followers",
following_url:
"https://api.github.com/users/acangiano/following{/other_user}",
gists_url: "https://api.github.com/users/acangiano/gists{/gist_id}",
starred_url:
"https://api.github.com/users/acangiano/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/acangiano/subscriptions",
organizations_url: "https://api.github.com/users/acangiano/orgs",
repos_url: "https://api.github.com/users/acangiano/repos",
events_url: "https://api.github.com/users/acangiano/events{/privacy}",
received_events_url:
"https://api.github.com/users/acangiano/received_events",
type: "User",
site_admin: false,
},
{
login: "cw",
id: 1692,
node_id: "MDQ6VXNlcjE2OTI=",
avatar_url: "https://avatars.githubusercontent.com/u/1692?v=4",
gravatar_id: "",
url: "https://api.github.com/users/cw",
html_url: "https://github.com/cw",
followers_url: "https://api.github.com/users/cw/followers",
following_url: "https://api.github.com/users/cw/following{/other_user}",
gists_url: "https://api.github.com/users/cw/gists{/gist_id}",
starred_url: "https://api.github.com/users/cw/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/cw/subscriptions",
organizations_url: "https://api.github.com/users/cw/orgs",
repos_url: "https://api.github.com/users/cw/repos",
events_url: "https://api.github.com/users/cw/events{/privacy}",
received_events_url: "https://api.github.com/users/cw/received_events",
type: "User",
site_admin: false,
},
{
login: "cheeaun",
id: 2296,
node_id: "MDQ6VXNlcjIyOTY=",
avatar_url: "https://avatars.githubusercontent.com/u/2296?v=4",
gravatar_id: "",
url: "https://api.github.com/users/cheeaun",
html_url: "https://github.com/cheeaun",
followers_url: "https://api.github.com/users/cheeaun/followers",
following_url:
"https://api.github.com/users/cheeaun/following{/other_user}",
gists_url: "https://api.github.com/users/cheeaun/gists{/gist_id}",
starred_url: "https://api.github.com/users/cheeaun/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/cheeaun/subscriptions",
organizations_url: "https://api.github.com/users/cheeaun/orgs",
repos_url: "https://api.github.com/users/cheeaun/repos",
events_url: "https://api.github.com/users/cheeaun/events{/privacy}",
received_events_url: "https://api.github.com/users/cheeaun/received_events",
type: "User",
site_admin: false,
},
{
login: "pfefferle",
id: 2373,
node_id: "MDQ6VXNlcjIzNzM=",
avatar_url: "https://avatars.githubusercontent.com/u/2373?v=4",
gravatar_id: "",
url: "https://api.github.com/users/pfefferle",
html_url: "https://github.com/pfefferle",
followers_url: "https://api.github.com/users/pfefferle/followers",
following_url:
"https://api.github.com/users/pfefferle/following{/other_user}",
gists_url: "https://api.github.com/users/pfefferle/gists{/gist_id}",
starred_url:
"https://api.github.com/users/pfefferle/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/pfefferle/subscriptions",
organizations_url: "https://api.github.com/users/pfefferle/orgs",
repos_url: "https://api.github.com/users/pfefferle/repos",
events_url: "https://api.github.com/users/pfefferle/events{/privacy}",
received_events_url:
"https://api.github.com/users/pfefferle/received_events",
type: "User",
site_admin: false,
},
{
login: "bjeanes",
id: 2560,
node_id: "MDQ6VXNlcjI1NjA=",
avatar_url: "https://avatars.githubusercontent.com/u/2560?v=4",
gravatar_id: "",
url: "https://api.github.com/users/bjeanes",
html_url: "https://github.com/bjeanes",
followers_url: "https://api.github.com/users/bjeanes/followers",
following_url:
"https://api.github.com/users/bjeanes/following{/other_user}",
gists_url: "https://api.github.com/users/bjeanes/gists{/gist_id}",
starred_url: "https://api.github.com/users/bjeanes/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/bjeanes/subscriptions",
organizations_url: "https://api.github.com/users/bjeanes/orgs",
repos_url: "https://api.github.com/users/bjeanes/repos",
events_url: "https://api.github.com/users/bjeanes/events{/privacy}",
received_events_url: "https://api.github.com/users/bjeanes/received_events",
type: "User",
site_admin: false,
},
{
login: "mikker",
id: 2819,
node_id: "MDQ6VXNlcjI4MTk=",
avatar_url: "https://avatars.githubusercontent.com/u/2819?v=4",
gravatar_id: "",
url: "https://api.github.com/users/mikker",
html_url: "https://github.com/mikker",
followers_url: "https://api.github.com/users/mikker/followers",
following_url: "https://api.github.com/users/mikker/following{/other_user}",
gists_url: "https://api.github.com/users/mikker/gists{/gist_id}",
starred_url: "https://api.github.com/users/mikker/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/mikker/subscriptions",
organizations_url: "https://api.github.com/users/mikker/orgs",
repos_url: "https://api.github.com/users/mikker/repos",
events_url: "https://api.github.com/users/mikker/events{/privacy}",
received_events_url: "https://api.github.com/users/mikker/received_events",
type: "User",
site_admin: false,
},
{
login: "mineiro",
id: 3123,
node_id: "MDQ6VXNlcjMxMjM=",
avatar_url: "https://avatars.githubusercontent.com/u/3123?v=4",
gravatar_id: "",
url: "https://api.github.com/users/mineiro",
html_url: "https://github.com/mineiro",
followers_url: "https://api.github.com/users/mineiro/followers",
following_url:
"https://api.github.com/users/mineiro/following{/other_user}",
gists_url: "https://api.github.com/users/mineiro/gists{/gist_id}",
starred_url: "https://api.github.com/users/mineiro/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/mineiro/subscriptions",
organizations_url: "https://api.github.com/users/mineiro/orgs",
repos_url: "https://api.github.com/users/mineiro/repos",
events_url: "https://api.github.com/users/mineiro/events{/privacy}",
received_events_url: "https://api.github.com/users/mineiro/received_events",
type: "User",
site_admin: false,
},
{
login: "fabricio",
id: 3382,
node_id: "MDQ6VXNlcjMzODI=",
avatar_url: "https://avatars.githubusercontent.com/u/3382?v=4",
gravatar_id: "",
url: "https://api.github.com/users/fabricio",
html_url: "https://github.com/fabricio",
followers_url: "https://api.github.com/users/fabricio/followers",
following_url:
"https://api.github.com/users/fabricio/following{/other_user}",
gists_url: "https://api.github.com/users/fabricio/gists{/gist_id}",
starred_url: "https://api.github.com/users/fabricio/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/fabricio/subscriptions",
organizations_url: "https://api.github.com/users/fabricio/orgs",
repos_url: "https://api.github.com/users/fabricio/repos",
events_url: "https://api.github.com/users/fabricio/events{/privacy}",
received_events_url:
"https://api.github.com/users/fabricio/received_events",
type: "User",
site_admin: false,
},
{
login: "mattam",
id: 3611,
node_id: "MDQ6VXNlcjM2MTE=",
avatar_url: "https://avatars.githubusercontent.com/u/3611?v=4",
gravatar_id: "",
url: "https://api.github.com/users/mattam",
html_url: "https://github.com/mattam",
followers_url: "https://api.github.com/users/mattam/followers",
following_url: "https://api.github.com/users/mattam/following{/other_user}",
gists_url: "https://api.github.com/users/mattam/gists{/gist_id}",
starred_url: "https://api.github.com/users/mattam/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/mattam/subscriptions",
organizations_url: "https://api.github.com/users/mattam/orgs",
repos_url: "https://api.github.com/users/mattam/repos",
events_url: "https://api.github.com/users/mattam/events{/privacy}",
received_events_url: "https://api.github.com/users/mattam/received_events",
type: "User",
site_admin: false,
},
{
login: "andriytyurnikov",
id: 3668,
node_id: "MDQ6VXNlcjM2Njg=",
avatar_url: "https://avatars.githubusercontent.com/u/3668?v=4",
gravatar_id: "",
url: "https://api.github.com/users/andriytyurnikov",
html_url: "https://github.com/andriytyurnikov",
followers_url: "https://api.github.com/users/andriytyurnikov/followers",
following_url:
"https://api.github.com/users/andriytyurnikov/following{/other_user}",
gists_url: "https://api.github.com/users/andriytyurnikov/gists{/gist_id}",
starred_url:
"https://api.github.com/users/andriytyurnikov/starred{/owner}{/repo}",
subscriptions_url:
"https://api.github.com/users/andriytyurnikov/subscriptions",
organizations_url: "https://api.github.com/users/andriytyurnikov/orgs",
repos_url: "https://api.github.com/users/andriytyurnikov/repos",
events_url: "https://api.github.com/users/andriytyurnikov/events{/privacy}",
received_events_url:
"https://api.github.com/users/andriytyurnikov/received_events",
type: "User",
site_admin: false,
},
{
login: "mamuso",
id: 3992,
node_id: "MDQ6VXNlcjM5OTI=",
avatar_url: "https://avatars.githubusercontent.com/u/3992?v=4",
gravatar_id: "",
url: "https://api.github.com/users/mamuso",
html_url: "https://github.com/mamuso",
followers_url: "https://api.github.com/users/mamuso/followers",
following_url: "https://api.github.com/users/mamuso/following{/other_user}",
gists_url: "https://api.github.com/users/mamuso/gists{/gist_id}",
starred_url: "https://api.github.com/users/mamuso/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/mamuso/subscriptions",
organizations_url: "https://api.github.com/users/mamuso/orgs",
repos_url: "https://api.github.com/users/mamuso/repos",
events_url: "https://api.github.com/users/mamuso/events{/privacy}",
received_events_url: "https://api.github.com/users/mamuso/received_events",
type: "User",
site_admin: true,
},
{
login: "oliyoung",
id: 4388,
node_id: "MDQ6VXNlcjQzODg=",
avatar_url: "https://avatars.githubusercontent.com/u/4388?v=4",
gravatar_id: "",
url: "https://api.github.com/users/oliyoung",
html_url: "https://github.com/oliyoung",
followers_url: "https://api.github.com/users/oliyoung/followers",
following_url:
"https://api.github.com/users/oliyoung/following{/other_user}",
gists_url: "https://api.github.com/users/oliyoung/gists{/gist_id}",
starred_url: "https://api.github.com/users/oliyoung/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/oliyoung/subscriptions",
organizations_url: "https://api.github.com/users/oliyoung/orgs",
repos_url: "https://api.github.com/users/oliyoung/repos",
events_url: "https://api.github.com/users/oliyoung/events{/privacy}",
received_events_url:
"https://api.github.com/users/oliyoung/received_events",
type: "User",
site_admin: false,
},
{
login: "evandrodutra",
id: 5218,
node_id: "MDQ6VXNlcjUyMTg=",
avatar_url: "https://avatars.githubusercontent.com/u/5218?v=4",
gravatar_id: "",
url: "https://api.github.com/users/evandrodutra",
html_url: "https://github.com/evandrodutra",
followers_url: "https://api.github.com/users/evandrodutra/followers",
following_url:
"https://api.github.com/users/evandrodutra/following{/other_user}",
gists_url: "https://api.github.com/users/evandrodutra/gists{/gist_id}",
starred_url:
"https://api.github.com/users/evandrodutra/starred{/owner}{/repo}",
subscriptions_url:
"https://api.github.com/users/evandrodutra/subscriptions",
organizations_url: "https://api.github.com/users/evandrodutra/orgs",
repos_url: "https://api.github.com/users/evandrodutra/repos",
events_url: "https://api.github.com/users/evandrodutra/events{/privacy}",
received_events_url:
"https://api.github.com/users/evandrodutra/received_events",
type: "User",
site_admin: false,
},
{
login: "standino",
id: 5509,
node_id: "MDQ6VXNlcjU1MDk=",
avatar_url: "https://avatars.githubusercontent.com/u/5509?v=4",
gravatar_id: "",
url: "https://api.github.com/users/standino",
html_url: "https://github.com/standino",
followers_url: "https://api.github.com/users/standino/followers",
following_url:
"https://api.github.com/users/standino/following{/other_user}",
gists_url: "https://api.github.com/users/standino/gists{/gist_id}",
starred_url: "https://api.github.com/users/standino/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/standino/subscriptions",
organizations_url: "https://api.github.com/users/standino/orgs",
repos_url: "https://api.github.com/users/standino/repos",
events_url: "https://api.github.com/users/standino/events{/privacy}",
received_events_url:
"https://api.github.com/users/standino/received_events",
type: "User",
site_admin: false,
},
{
login: "devraj",
id: 5961,
node_id: "MDQ6VXNlcjU5NjE=",
avatar_url: "https://avatars.githubusercontent.com/u/5961?v=4",
gravatar_id: "",
url: "https://api.github.com/users/devraj",
html_url: "https://github.com/devraj",
followers_url: "https://api.github.com/users/devraj/followers",
following_url: "https://api.github.com/users/devraj/following{/other_user}",
gists_url: "https://api.github.com/users/devraj/gists{/gist_id}",
starred_url: "https://api.github.com/users/devraj/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/devraj/subscriptions",
organizations_url: "https://api.github.com/users/devraj/orgs",
repos_url: "https://api.github.com/users/devraj/repos",
events_url: "https://api.github.com/users/devraj/events{/privacy}",
received_events_url: "https://api.github.com/users/devraj/received_events",
type: "User",
site_admin: false,
},
{
login: "marianoviola",
id: 6157,
node_id: "MDQ6VXNlcjYxNTc=",
avatar_url: "https://avatars.githubusercontent.com/u/6157?v=4",
gravatar_id: "",
url: "https://api.github.com/users/marianoviola",
html_url: "https://github.com/marianoviola",
followers_url: "https://api.github.com/users/marianoviola/followers",
following_url:
"https://api.github.com/users/marianoviola/following{/other_user}",
gists_url: "https://api.github.com/users/marianoviola/gists{/gist_id}",
starred_url:
"https://api.github.com/users/marianoviola/starred{/owner}{/repo}",
subscriptions_url:
"https://api.github.com/users/marianoviola/subscriptions",
organizations_url: "https://api.github.com/users/marianoviola/orgs",
repos_url: "https://api.github.com/users/marianoviola/repos",
events_url: "https://api.github.com/users/marianoviola/events{/privacy}",
received_events_url:
"https://api.github.com/users/marianoviola/received_events",
type: "User",
site_admin: false,
},
{
login: "terje",
id: 6210,
node_id: "MDQ6VXNlcjYyMTA=",
avatar_url: "https://avatars.githubusercontent.com/u/6210?v=4",
gravatar_id: "",
url: "https://api.github.com/users/terje",
html_url: "https://github.com/terje",
followers_url: "https://api.github.com/users/terje/followers",
following_url: "https://api.github.com/users/terje/following{/other_user}",
gists_url: "https://api.github.com/users/terje/gists{/gist_id}",
starred_url: "https://api.github.com/users/terje/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/terje/subscriptions",
organizations_url: "https://api.github.com/users/terje/orgs",
repos_url: "https://api.github.com/users/terje/repos",
events_url: "https://api.github.com/users/terje/events{/privacy}",
received_events_url: "https://api.github.com/users/terje/received_events",
type: "User",
site_admin: false,
},
{
login: "israelzuniga",
id: 6629,
node_id: "MDQ6VXNlcjY2Mjk=",
avatar_url: "https://avatars.githubusercontent.com/u/6629?v=4",
gravatar_id: "",
url: "https://api.github.com/users/israelzuniga",
html_url: "https://github.com/israelzuniga",
followers_url: "https://api.github.com/users/israelzuniga/followers",
following_url:
"https://api.github.com/users/israelzuniga/following{/other_user}",
gists_url: "https://api.github.com/users/israelzuniga/gists{/gist_id}",
starred_url:
"https://api.github.com/users/israelzuniga/starred{/owner}{/repo}",
subscriptions_url:
"https://api.github.com/users/israelzuniga/subscriptions",
organizations_url: "https://api.github.com/users/israelzuniga/orgs",
repos_url: "https://api.github.com/users/israelzuniga/repos",
events_url: "https://api.github.com/users/israelzuniga/events{/privacy}",
received_events_url:
"https://api.github.com/users/israelzuniga/received_events",
type: "User",
site_admin: false,
},
{
login: "timknight",
id: 6634,
node_id: "MDQ6VXNlcjY2MzQ=",
avatar_url: "https://avatars.githubusercontent.com/u/6634?v=4",
gravatar_id: "",
url: "https://api.github.com/users/timknight",
html_url: "https://github.com/timknight",
followers_url: "https://api.github.com/users/timknight/followers",
following_url:
"https://api.github.com/users/timknight/following{/other_user}",
gists_url: "https://api.github.com/users/timknight/gists{/gist_id}",
starred_url:
"https://api.github.com/users/timknight/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/timknight/subscriptions",
organizations_url: "https://api.github.com/users/timknight/orgs",
repos_url: "https://api.github.com/users/timknight/repos",
events_url: "https://api.github.com/users/timknight/events{/privacy}",
received_events_url:
"https://api.github.com/users/timknight/received_events",
type: "User",
site_admin: false,
},
{
login: "mdg",
id: 6962,
node_id: "MDQ6VXNlcjY5NjI=",
avatar_url: "https://avatars.githubusercontent.com/u/6962?v=4",
gravatar_id: "",
url: "https://api.github.com/users/mdg",
html_url: "https://github.com/mdg",
followers_url: "https://api.github.com/users/mdg/followers",
following_url: "https://api.github.com/users/mdg/following{/other_user}",
gists_url: "https://api.github.com/users/mdg/gists{/gist_id}",
starred_url: "https://api.github.com/users/mdg/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/mdg/subscriptions",
organizations_url: "https://api.github.com/users/mdg/orgs",
repos_url: "https://api.github.com/users/mdg/repos",
events_url: "https://api.github.com/users/mdg/events{/privacy}",
received_events_url: "https://api.github.com/users/mdg/received_events",
type: "User",
site_admin: false,
},
{
login: "alcides",
id: 7089,
node_id: "MDQ6VXNlcjcwODk=",
avatar_url: "https://avatars.githubusercontent.com/u/7089?v=4",
gravatar_id: "",
url: "https://api.github.com/users/alcides",
html_url: "https://github.com/alcides",
followers_url: "https://api.github.com/users/alcides/followers",
following_url:
"https://api.github.com/users/alcides/following{/other_user}",
gists_url: "https://api.github.com/users/alcides/gists{/gist_id}",
starred_url: "https://api.github.com/users/alcides/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/alcides/subscriptions",
organizations_url: "https://api.github.com/users/alcides/orgs",
repos_url: "https://api.github.com/users/alcides/repos",
events_url: "https://api.github.com/users/alcides/events{/privacy}",
received_events_url: "https://api.github.com/users/alcides/received_events",
type: "User",
site_admin: false,
},
{
login: "arjunghosh",
id: 7686,
node_id: "MDQ6VXNlcjc2ODY=",
avatar_url: "https://avatars.githubusercontent.com/u/7686?v=4",
gravatar_id: "",
url: "https://api.github.com/users/arjunghosh",
html_url: "https://github.com/arjunghosh",
followers_url: "https://api.github.com/users/arjunghosh/followers",
following_url:
"https://api.github.com/users/arjunghosh/following{/other_user}",
gists_url: "https://api.github.com/users/arjunghosh/gists{/gist_id}",
starred_url:
"https://api.github.com/users/arjunghosh/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/arjunghosh/subscriptions",
organizations_url: "https://api.github.com/users/arjunghosh/orgs",
repos_url: "https://api.github.com/users/arjunghosh/repos",
events_url: "https://api.github.com/users/arjunghosh/events{/privacy}",
received_events_url:
"https://api.github.com/users/arjunghosh/received_events",
type: "User",
site_admin: false,
},
{
login: "tiendung",
id: 8133,
node_id: "MDQ6VXNlcjgxMzM=",
avatar_url: "https://avatars.githubusercontent.com/u/8133?v=4",
gravatar_id: "",
url: "https://api.github.com/users/tiendung",
html_url: "https://github.com/tiendung",
followers_url: "https://api.github.com/users/tiendung/followers",
following_url:
"https://api.github.com/users/tiendung/following{/other_user}",
gists_url: "https://api.github.com/users/tiendung/gists{/gist_id}",
starred_url: "https://api.github.com/users/tiendung/starred{/owner}{/repo}",
subscriptions_url: "https://api.github.com/users/tiendung/subscriptions",
organizations_url: "https://api.github.com/users/tiendung/orgs",
repos_url: "https://api.github.com/users/tiendung/repos",
events_url: "https://api.github.com/users/tiendung/events{/privacy}",
received_events_url:
"https://api.github.com/users/tiendung/received_events",
type: "User",
site_admin: false,
},
];
// {"mode":"full","isActive":false}
| d82d435eae3958dcca3a57f4ec7a835bc43858a2 | [
"JavaScript"
] | 1 | JavaScript | amityadav06/github-analyzer | ad18cdacf462f531d3aee5cf1d41117700f73bbb | 0a2fe95abb7a230c82e673f13dde4ba8dc22ee6a |
refs/heads/master | <file_sep>package com.work.pm25;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
static final String TAG = MainActivity.class.getSimpleName();
private ImageView img_city_chosen;//手动选择城市
private TextView tv_city_name;//相应城市的名称
private boolean isGPSOpen = false;
/**
* ************* baidu map ******************************
*/
private LocationClient mLocationClient;
private MyLocationListener mLocationListener;
private String MAP_APP_KEY = "GrY3SWPzhy2akgS4USNTOin1";//我的百度地图的Key
private String baseMapApi = "http://api.map.baidu.com/geocoder?output=json&location=";
private String lastMapApi = "";
private String locationString = "";//url后面接的参数
private double latitude;//纬度
private double longitude;//经度
private String cityName;//在主页上显示的城市名称
private boolean hasCityChanged = false;//默认的城市名称是否已经改变
//最终示例
//http://api.map.baidu.com/geocoder?output=json&location=39.983228,116.491146&key=GrY3SWPzhy2akgS4USNTOin1
/**
* ***************** detect the pm2.5 ***********************************
*/
private String base_PM_URL = "http://www.pm25.in/api/querys/pm2_5.json";//Get token=<KEY>QyNQyq
private String last_PM_URL = "";
private String citySubmit = null;//发送给PM检测网站的城市名称
private int position_num = 0;//每个城市有多少个观测站点
private ArrayList<HashMap<String, String>> lists = new ArrayList<HashMap<String, String>>();
private GridView gridView;
private MyBaseAdapter mBaseAdapter;
private RelativeLayout relative_main_detail;
private TextView tv_error;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initBDLocation();
// if()
// autoGetCity();
//由于location需要时间,cityName也许呀时间来获取,虽然很短,但是比程序执行的时间慢
//所以得间隔一秒
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if (cityName.endsWith("市") || cityName.endsWith("县")) {
citySubmit = cityName.substring(0, cityName.length() - 1);
Log.d(TAG, "citySubmit " + citySubmit);
}
// doVolleyGetPM(encodeCity(citySubmit));
// doVolleyGetPM(citySubmit);
doVolleyGetPM("zhuhai");
}
};
Timer timer = new Timer();
timer.schedule(timerTask,1000);
// doVolleyGet("zhuhai");
//手动选择城市
img_city_chosen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CityChosenActivity.class);
startActivityForResult(intent, 2);//请求码为2
}
});
}
private void initView() {
img_city_chosen = (ImageView) findViewById(R.id.city_chosen);
tv_city_name = (TextView) findViewById(R.id.city_name);
relative_main_detail = (RelativeLayout) findViewById(R.id.main_detail);
tv_error = (TextView) findViewById(R.id.tv_nodata);//没有监测数据
gridView = (GridView) findViewById(R.id.grid_detail);
}
/**
* 获取用户所在城市的名称
* 1. 优先使用GPS定位
* 2. 如果用户硬是不开GPS,则使用IP定位的方法
*/
private String autoGetCity() {
String city_name = null;
return city_name;
}
/**
* 判断网络连接是否打开,且网络是否可用
* @return
*/
private boolean isNetConnected() {
return false;
}
/**
* @param city 传入的城市名称
* @return 返回经过UTF-8编码后的城市名称
*/
private String encodeCity(String city) {
try {
URLEncoder.encode(city, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return city;
}
/**
* 在更新了用户的位置之后,更改首页显示的城市
*/
private void changeUserCity() {
tv_city_name.setTextColor(Color.WHITE);
tv_city_name.setText(cityName);
}
/**
* 使用百度sdk开始定位
*/
private void initBDLocation() {
Log.v(TAG, "start to initLocation");
//初始化LocationClient类,LocationClient类必须在主线程中声明
mLocationClient = new LocationClient(MainActivity.this.getApplicationContext());
mLocationListener = new MyLocationListener();
// 注册监听函数,当没有注册监听函数时,无法发起网络请求。
mLocationClient.registerLocationListener(mLocationListener);
//配置定位SDK
LocationClientOption option = new LocationClientOption();
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式 1 2 3
// option.setOpenGps(true);
option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
option.setScanSpan(5000);// 设置发起定位请求的间隔时间为3000ms
option.setIsNeedAddress(true);//返回的定位结果包含地址信息
mLocationClient.setLocOption(option);
mLocationClient.start();
if (mLocationClient != null && mLocationClient.isStarted()) {
mLocationClient.requestLocation();
} else {
Log.d("LocSDK5", "locClient is null or not started");
}
}
/**
*
*/
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
Log.v("LocationActivity", "MyLocationListener-onReceiveLocation");
if (location == null) {
Log.d(TAG, "location is null");
return;
}
cityName = location.getCity();//获取城市名称
Log.d(TAG, "city " + cityName);
if (!hasCityChanged) { // 如果没有更改显示的城市的话,则更改
changeUserCity();//更改显示的城市名称
hasCityChanged = true;
}
StringBuffer sb = new StringBuffer(256);
sb.append("time : ");
sb.append(location.getTime());
sb.append("\nerror code : ");
sb.append(location.getLocType());
sb.append("\nlatitude : ");
latitude = location.getLatitude();//设置纬度
sb.append(location.getLatitude());
sb.append("\nlontitude : ");
longitude = location.getLongitude();//设置经度
sb.append(location.getLongitude());
sb.append("\nradius : ");
sb.append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation) {
sb.append("\nspeed : ");
sb.append(location.getSpeed());
sb.append("\nsatellite : ");
sb.append(location.getSatelliteNumber());
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
sb.append("\naddr : ");
sb.append(location.getAddrStr());
}
locationString = "&location=" + location.getLatitude() + ","
+ location.getLongitude() + "&key=GrY3SWPzhy2akgS4USNTOin1";
// lastMapApi = baseMapApi + locationString;
}
}
/**
* 如果该地区有 PM 2.5的检测数据,则
* 在获取到了PM2.5的检测数据后,开始显示
*/
private void startDisplayDetail(boolean hasData) {
if (hasData) {
tv_error.setVisibility(View.INVISIBLE);
gridView.setAdapter(new MyBaseAdapter(MainActivity.this));
//gridView.
} else {
gridView.setVisibility(View.INVISIBLE);
tv_error.setText("该城市还未有PM2.5数据");
}
}
class MyBaseAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyBaseAdapter(Context context) {
this.mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return lists.size();
}
@Override
public Object getItem(int position) {
return lists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.griditem, null);
TextView tv_home_district = (TextView) convertView.findViewById(R.id.home_district);
TextView tv_home_pollution_rating = (TextView) convertView.findViewById(R.id.home_pollution_rating);
TextView tv_home_level_num = (TextView) convertView.findViewById(R.id.home_level_num);
tv_home_district.setText(lists.get(position).get("position_name"));
tv_home_pollution_rating.setText(lists.get(position).get("quality"));
tv_home_level_num.setText(lists.get(position).get("pm2_5"));
return convertView;
}
}
/**
* PM2.5
* 根据传入的城市信息返回json数据
*
* @return
*/
private String doVolleyGetPM(String mcity) {
String result = null;
RequestQueue mrequestQueue = Volley.newRequestQueue(MainActivity.this);
last_PM_URL = base_PM_URL + "?city=" + mcity + "&token=" + "<KEY>";
Log.d(TAG, last_PM_URL);
StringRequest stringRequest = new StringRequest(Request.Method.GET, last_PM_URL, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.d(TAG, "PM2.5检测的结果为:" + s);
if (s.startsWith("{")) {//说明返回的是一个对象,也就是说这个地方没有监测数据
try {
JSONObject jsonObject = new JSONObject(s);
jsonObject.getString("error");
startDisplayDetail(false);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d(TAG+"a", last_PM_URL);
try {
JSONArray jsonArray = new JSONArray(s);
position_num = jsonArray.length();
Log.d(TAG, "观测站点个数为:" + position_num);
HashMap<String, String> map = null;
for (int i = 0; i < position_num; i++) {
map= new HashMap<>();
map.put("position_name", jsonArray.getJSONObject(i).getString("position_name"));
map.put("quality", jsonArray.getJSONObject(i).getString("quality"));
map.put("pm2_5", jsonArray.getJSONObject(i).getString("pm2_5"));
lists.add(map);
}
startDisplayDetail(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "错误的请求码:" + volleyError.toString());
}
});
mrequestQueue.add(stringRequest);//将StringRequest添加到RequestQueue
return result;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 根据上面发送过去的请求吗来区别
switch (requestCode) {
case 0://设置完GPS后:
autoGetCity();//再次获取城市信息
break;
case 2://手动选择城市之后,返回相应城市名称: 关闭自动获取城市
// data.getStringExtra("")
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>include ':app', ':pmdetection', ':mytool'
<file_sep>package util;
/**
* Created by KalinaRain on 2015/5/8.
*/
public class Utility {
}
| eb62fd49c541429c2b7b3a6c73dd34b806091b8c | [
"Java",
"Gradle"
] | 3 | Java | KalinaRain/MyWorkSpace | b9636f89108356247054376bd99b6ceba769d8da | b01a6b4d296a59c0be040392b00b3ebc91f37082 |
refs/heads/master | <file_sep>module.exports = {
theme: {
extend: {
colors: {
inherit: "inherit"
},
screens: {
dark: { raw: "(prefers-color-scheme: dark)" }
}
}
},
variants: {
margin: ["responsive", "last"]
},
plugins: [],
important: true
};
| 40a143b3e70d71323b742681be37656f98dbab6c | [
"JavaScript"
] | 1 | JavaScript | abhisheksarmah/sebastiandedeyne.com | ca58735097091a6b0dc3cf03677a974b847d72a9 | 8df2ae2d559e0cd7133d65d1e932cba0a7158845 |
refs/heads/master | <file_sep>import spacy
from spacy.tokens import Doc, Span, Token
from tqdm import tqdm
import time
import re
import pandas as pd
import numpy as np
import gensim
from nltk.stem import PorterStemmer
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem import SnowballStemmer
from sklearn.metrics import classification_report
from tensorflow.keras.utils import to_categorical
import random, os, sys
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.callbacks import *
from tensorflow.keras.initializers import *
from tensorflow.python.keras.layers import Layer
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import tensorflow.keras.backend as K
import sklearn.metrics as sklm
np.random.seed(1) # NumPy
import random
random.seed(2) # Python
from tensorflow.random import set_seed
set_seed(3) # Tensorflow
# preprocessing functions
def replace_usernames(text):
return re.sub(r'@[a-zA-Z0-9_]{1,15}', '_USER_', text)
def replace_hashtags(text):
return re.sub(r'#[a-zA-Z0-9_]*', '_HASHTAG_', text)
def replace_urls(text):
pattern = r'[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)'
pattern2 = r'https?:\/\/t.co\/[\w\d]*'
text = re.sub(pattern, '_URL_', text)
return re.sub(pattern2, '_URL_', text)
def replace_amps(text):
return re.sub(r'&', 'and', text)
def clean_text(text):
text = replace_usernames(text)
text = replace_hashtags(text)
text = replace_urls(text)
text = replace_amps(text)
return text
# Load spacy
start_time = time.time()
print("Loading Spacy Model")
nlp = spacy.load('en_core_web_lg')
print("{} seconds".format(time.time() - start_time))
# Custom spacy attributes
Doc.set_extension("num_drugs", default=0)
Doc.set_extension("num_pers", default=0)
Doc.set_extension("drug_VB_negated", default=False)
Token.set_extension("is_drug", default=False)
Token.set_extension("VB_to_drug", default=False)
Token.set_extension("emoji_text", default=None)
Token.set_extension("pos_rel_drug", default=0)
Token.set_extension("drug_verb_span", default=0)
# New spacy pipeline features
def extract_features(doc):
drug_pattern = '(dioralyte|solpadine|solpadol|icyhot|zanaflex|tramdol|moldavite|robex|novacaine|tramadol|pedialite|NeoCitran|dydramol|adderal|ciroc|im+odium|profen|excedrine|zanny|gaviscon|cod[ea]mol|panadol|ora[jg]el|ben[ea]dryl|percocet|mucinex|dayquil|nyquil|alieve|sudocrem|hydroco|propionate|fluticasone|liefern|medrol|klonopin|proai|arcoxia|spiriva|anacin|accolate|advai|alprazolam|lorazepam|symbicort|acetaminophen|methadone|oxyc|robitussin|fluoxetine|diazi?e?pam|advil|tylenol|steroid|ibuprofen|motrin|valium|panadol|code?ine|flonase|ativan|proza[ck]|vent[oia]lin|pred(ni|in)sone|xan([enya]x|s)|paracet(am|ma)ol|albuter[oa]l|clona[sz]epam)'
drug_pos = []
#Find all the drug tokens
for pos, token in enumerate(doc):
if re.match(drug_pattern, token.text, flags=re.I) is not None:
token._.is_drug = True
#record index of all drug tokens
drug_pos.append(pos)
#Count the PERSON entities
PERS_count = 0
for ent in doc.ents:
if ent.label_ == "PERSON":
PERS_count += 1
drug_count = 0
for pos, token in enumerate(doc):
#Count the drugs in the doc
drug_count += int(token._.is_drug)
#Label verb parent of drug
if token.pos_ == "VERB":
for child in token.children:
if child._.is_drug is True:
token._.VB_to_drug = True
#Is the verb negated?
if token._.VB_to_drug:
for child in token.children:
if child.dep_ == "neg":
doc._.drug_VB_negated = True
#label the token position relative to drug token
if len(drug_pos)>0:
dists = [abs(pos-x) for x in drug_pos]
ind = np.argmin(dists)
token._.pos_rel_drug = pos-drug_pos[ind]
#label all drugs within the verb_to_drug subtree
if token._.is_drug:
token = token.head
if token.pos_ != "VERB":
for child in token.subtree:
child._.drug_verb_span = 1
doc._.num_pers = PERS_count
doc._.num_drugs = drug_count
return doc
try:
nlp.add_pipe(extract_features, name='extract_features', last=True)
except Exception as e:
nlp.remove_pipe("extract_features")
nlp.add_pipe(extract_features, name='extract_features', last=True)
# Load Data
# TRAIN_DATA = "./data/train.csv"
# DEV_DATA = "./data/dev.csv"
# TEST_DATA = "./data/test.csv"
# Load Data
TRAIN_DATA = "./data/train_emoji.csv"
DEV_DATA = "./data/dev_emoji.csv"
TEST_DATA = "./data/test_emoji.csv"
# Load data
start_time = time.time()
print("Loading data...")
train = pd.read_csv(TRAIN_DATA)
dev = pd.read_csv(DEV_DATA)
test = pd.read_csv(TEST_DATA)
# Cleaning Text
train["Text"] = train["Text"].apply(lambda x: clean_text(x))
dev["Text"] = dev["Text"].apply(lambda x: clean_text(x))
test["Text"] = test["Text"].apply(lambda x: clean_text(x))
# Spacy Doc
train["Doc"] = train["Text"].apply(lambda x: nlp(x))
dev["Doc"] = dev["Text"].apply(lambda x: nlp(x))
test["Doc"] = test["Text"].apply(lambda x: nlp(x))
print("%s seconds" % (time.time() - start_time))
# Feature Extraction function
def create_emb(doc):
emb = []
for token in doc:
emb.append([int(token._.is_drug),
int(token._.VB_to_drug),
token._.pos_rel_drug,
token._.drug_verb_span])
return emb
train["Emb"] = train["Doc"].apply(lambda x: create_emb(x))
dev["Emb"] = dev["Doc"].apply(lambda x: create_emb(x))
test["Emb"] = test["Doc"].apply(lambda x: create_emb(x))
# Calculate class weights for model training
print("Calculating Label Weights")
start_time = time.time()
label_weights = {}
temp_weights = []
num_samples = len(train)
for i in range(1,4):
temp_weights.append(num_samples/train.loc[train["Intake"] == i].count()[0])
total_weight = sum(temp_weights)
for i in range(1,4):
label_weights[i-1] = temp_weights[i-1]/total_weight
print("%s seconds" % (time.time() - start_time))
label_weights
# Get word indexes
print("Indexing Words")
start_time = time.time()
ind = 1
word_index = {}
lemma_dict = {}
for doc in train["Doc"]:
for token in doc:
if token.text not in word_index and token.pos_ is not "PUNCT":
word_index[token.text] = ind
ind += 1
lemma_dict[token.text] = token.lemma_
print("%s seconds" % (time.time() - start_time))
# Load the embedding matrix
start_time = time.time()
import os
GLOVE_DIR = "../embeddings/"
print("Loading glove embedding matrix ...")
embeddings_index = {}
with open(os.path.join(GLOVE_DIR, 'glove.840B.300d.txt'), encoding="utf8") as f:
for line in f:
values = line.split(" ")
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
num_words = len(word_index) + 1
embedding_matrix_glove = np.zeros((num_words, 300))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix_glove[i] = embedding_vector
print("%s seconds" % (time.time() - start_time))
print("Loading paragram embedding matrix ...")
embeddings_index = {}
with open(os.path.join(GLOVE_DIR, 'paragram_300_sl999.txt'), encoding="utf8", errors="ignore") as f:
for line in f:
values = line.split(" ")
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
num_words = len(word_index) + 1
embedding_matrix_para = np.zeros((num_words, 300))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix_para[i] = embedding_vector
print("%s seconds" % (time.time() - start_time))
print("Loading fasttext embedding matrix ...")
embeddings_index = {}
with open(os.path.join(GLOVE_DIR, 'wiki-news-300d-1M.vec'), encoding="utf8") as f:
for line in f:
values = line.split(" ")
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
num_words = len(word_index) + 1
embedding_matrix_fast = np.zeros((num_words, 300))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix_fast[i] = embedding_vector
print("%s seconds" % (time.time() - start_time))
print("Loading twitter embedding matrix ...")
embeddings_index = {}
with open(os.path.join(GLOVE_DIR, 'glove.twitter.27B.200d.txt'), encoding="utf8") as f:
for line in f:
values = line.split(" ")
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
num_words = len(word_index) + 1
embedding_matrix_twitter = np.zeros((num_words, 200))
for word, i in word_index.items():
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix_twitter[i] = embedding_vector
print("%s seconds" % (time.time() - start_time))
# hyperparameters
max_length = 42
# Padding functions
def pad_seq_doc(df):
seqs = []
for doc in df["Doc"]:
word_seq = []
for token in doc:
if token.pos_ != "PUNCT" and token.text in word_index:
word_seq.append(word_index[token.text])
elif token.pos_ != "PUNCT":
word_seq.append(0)
seqs.append(word_seq)
return pad_sequences(seqs,maxlen=max_length)
def pad_seq_emb(df):
seqs = []
for emb_seq in df["Emb"]:
dif = max_length - len(emb_seq)
if dif >0:
padded_emb = [[0,0,-max_length,0] for x in range(max(0,dif))] + emb_seq
else:
padded_emb = emb_seq[:max_length]
seqs.append(padded_emb)
return seqs
def extract_doc_features(df):
features = []
for doc in df["Doc"]:
features.append([doc._.num_pers, doc._.num_drugs, doc._.drug_VB_negated])
return features
# Pad sequences
train_word_sequences = pad_seq_doc(train)
dev_word_sequences = pad_seq_doc(dev)
test_word_sequences = pad_seq_doc(test)
train_emb_sequences = np.array(pad_seq_emb(train))
dev_emb_sequences = np.array(pad_seq_emb(dev))
test_emb_sequences = np.array(pad_seq_emb(test))
train_features = np.array(extract_doc_features(train))
test_features = np.array(extract_doc_features(test))
dev_features = np.array(extract_doc_features(dev))
# Network functions
class Metrics(Callback):
def on_train_begin(self, logs={}):
self.precision = []
self.recall = []
self.f1s = []
def on_epoch_end(self, epoch, logs={}):
predict = [x.argmax() for x in np.asarray(self.model.predict(self.validation_data[0]))]
targ = [x.argmax() for x in self.validation_data[1]]
self.precision.append(sklm.precision_score(targ, predict, average="micro"))
self.recall.append(sklm.recall_score(targ, predict, average="micro"))
self.f1s.append(sklm.f1_score(targ, predict, average="micro"))
return
metrics = Metrics()
class LayerNormalization(Layer):
def __init__(self, eps=1e-6, **kwargs):
self.eps = eps
super(LayerNormalization, self).__init__(**kwargs)
def build(self, input_shape):
self.gamma = self.add_weight(name='gamma', shape=input_shape[-1:],
initializer=Ones(), trainable=True)
self.beta = self.add_weight(name='beta', shape=input_shape[-1:],
initializer=Zeros(), trainable=True)
super(LayerNormalization, self).build(input_shape)
def call(self, x):
mean = K.mean(x, axis=-1, keepdims=True)
std = K.std(x, axis=-1, keepdims=True)
return self.gamma * (x - mean) / (std + self.eps) + self.beta
def compute_output_shape(self, input_shape):
return input_shape
class ScaledDotProductAttention():
def __init__(self, d_model, attn_dropout=0.1):
self.temper = np.sqrt(d_model)
self.dropout = Dropout(attn_dropout)
def __call__(self, q, k, v, mask):
attn = Lambda(lambda x:K.batch_dot(x[0],x[1],axes=[2,2])/self.temper)([q, k])
if mask is not None:
mmask = Lambda(lambda x:(-1e+10)*(1-x))(mask)
attn = Add()([attn, mmask])
attn = Activation('softmax')(attn)
attn = self.dropout(attn)
output = Lambda(lambda x:K.batch_dot(x[0], x[1]))([attn, v])
return output, attn
class MultiHeadAttention():
# mode 0 - big martixes, faster; mode 1 - more clear implementation
def __init__(self, n_head, d_model, d_k, d_v, dropout, mode=0, use_norm=True):
self.mode = mode
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.dropout = dropout
if mode == 0:
self.qs_layer = Dense(n_head*d_k, use_bias=False)
self.ks_layer = Dense(n_head*d_k, use_bias=False)
self.vs_layer = Dense(n_head*d_v, use_bias=False)
elif mode == 1:
self.qs_layers = []
self.ks_layers = []
self.vs_layers = []
for _ in range(n_head):
self.qs_layers.append(TimeDistributed(Dense(d_k, use_bias=False)))
self.ks_layers.append(TimeDistributed(Dense(d_k, use_bias=False)))
self.vs_layers.append(TimeDistributed(Dense(d_v, use_bias=False)))
self.attention = ScaledDotProductAttention(d_model)
self.layer_norm = LayerNormalization() if use_norm else None
self.w_o = TimeDistributed(Dense(d_model))
def __call__(self, q, k, v, mask=None):
d_k, d_v = self.d_k, self.d_v
n_head = self.n_head
if self.mode == 0:
qs = self.qs_layer(q) # [batch_size, len_q, n_head*d_k]
ks = self.ks_layer(k)
vs = self.vs_layer(v)
def reshape1(x):
s = tf.shape(x) # [batch_size, len_q, n_head * d_k]
x = tf.reshape(x, [s[0], s[1], n_head, d_k])
x = tf.transpose(x, [2, 0, 1, 3])
x = tf.reshape(x, [-1, s[1], d_k]) # [n_head * batch_size, len_q, d_k]
return x
qs = Lambda(reshape1)(qs)
ks = Lambda(reshape1)(ks)
vs = Lambda(reshape1)(vs)
if mask is not None:
mask = Lambda(lambda x:K.repeat_elements(x, n_head, 0))(mask)
head, attn = self.attention(qs, ks, vs, mask=mask)
def reshape2(x):
s = tf.shape(x) # [n_head * batch_size, len_v, d_v]
x = tf.reshape(x, [n_head, -1, s[1], s[2]])
x = tf.transpose(x, [1, 2, 0, 3])
x = tf.reshape(x, [-1, s[1], n_head*d_v]) # [batch_size, len_v, n_head * d_v]
return x
head = Lambda(reshape2)(head)
elif self.mode == 1:
heads = []; attns = []
for i in range(n_head):
qs = self.qs_layers[i](q)
ks = self.ks_layers[i](k)
vs = self.vs_layers[i](v)
head, attn = self.attention(qs, ks, vs, mask)
heads.append(head); attns.append(attn)
head = Concatenate()(heads) if n_head > 1 else heads[0]
attn = Concatenate()(attns) if n_head > 1 else attns[0]
outputs = self.w_o(head)
outputs = Dropout(self.dropout)(outputs)
if not self.layer_norm: return outputs, attn
# outputs = Add()([outputs, q]) # sl: fix
return self.layer_norm(outputs), attn
def build_simple_LSTM(embedding_matrix, nb_words, embedding_size=300, extra_embs=[0,0,0,0], doc_features=[0,0,0]):
inp_words = Input(shape=(max_length,))
inputs = [inp_words]
if sum(extra_embs)>0:
inp_embs = Input(shape=(max_length,sum(extra_embs),))
inputs.append(inp_embs)
if sum(doc_features) > 0:
inp_docs = Input(shape=(sum(doc_Features),))
inputs.append(inp_docs)
x = Embedding(nb_words, embedding_size, trainable=False, embeddings_initializer=Constant(embedding_matrix),)(inp_words)
if sum(extra_embs) > 0:
x = Concatenate(axis=2)([x,inp_embs])
# x1 = Bidirectional(LSTM(32, return_sequences=False))(x)
x1 = LSTM(32, return_sequences=False)(x)
if sum(doc_features) > 0:
x1 = Concatenate()([x1,inp_docs])
d = Dropout(0.3)(x1)
predictions = Dense(3, activation='softmax')(d)
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer="adam", loss='categorical_crossentropy', metrics=['accuracy'])
return model
def build_yookim_CNN(embeddings_matrix, nb_words, embedding_size=300, extra_embs=[0,0,0,0], doc_features=[0,0,0]):
K.clear_session()
inp_words = Input(shape=(max_length,), dtype='int32')
inputs = [inp_words]
if sum(extra_embs)>0:
inp_embs = Input(shape=(max_length,sum(extra_embs),))
inputs.append(inp_embs)
if sum(doc_features) > 0:
inp_docs = Input(shape=(sum(doc_features),))
inputs.append(inp_docs)
x = Embedding(nb_words, embedding_size, trainable=False, embeddings_initializer=Constant(embedding_matrix),)(inp_words)
if sum(extra_embs) > 0:
x = Concatenate(axis=2)([x,inp_embs])
convs = []
filter_sizes = [3,4,5]
for fsz in filter_sizes:
l_conv = Conv1D(filters=128,kernel_size=fsz,activation='relu')(x)
l_pool = MaxPooling1D(5)(l_conv)
convs.append(l_pool)
l_merge = concatenate(convs, axis=1)
l_cov1= Conv1D(128, 5, activation='relu', data_format = 'channels_first')(l_merge)
l_pool1 = MaxPooling1D(5)(l_cov1)
l_cov2 = Conv1D(128, 5, activation='relu', data_format = 'channels_first')(l_pool1)
l_pool2 = MaxPooling1D(30)(l_cov2)
l_flat = Flatten()(l_pool2)
if sum(doc_features) > 0:
l_flat = Concatenate()([l_flat,inp_docs])
l_dense = Dense(128, activation='relu')(l_flat)
predictions = Dense(3, activation='softmax')(l_dense)
model = Model(inputs=inputs, outputs=predictions)
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=["acc"])
return model
def build_attention_LSTM(embeddings_matrix, nb_words, embedding_size=300, extra_embs=[0,0,0,0], doc_features=[0,0,0], binary=False, no_embeddings=False):
inputs = []
if not no_embeddings:
inp_words = Input(shape=(max_length,))
x = Embedding(nb_words, embedding_size, trainable=False, embeddings_initializer=Constant(embedding_matrix),)(inp_words)
inputs.append(inp_words)
if sum(extra_embs)>0:
inp_embs = Input(shape=(max_length,sum(extra_embs),))
if not no_embeddings:
x = Concatenate(axis=2)([x,inp_embs])
else: x = inp_embs
inputs.append(inp_embs)
if sum(doc_features) > 0:
inp_docs = Input(shape=(sum(doc_features),))
inputs.append(inp_docs)
# LSTM before attention layers
x = Bidirectional(LSTM(128, return_sequences=True))(x)
x = Bidirectional(LSTM(64, return_sequences=True))(x)
x, slf_attn = MultiHeadAttention(n_head=3, d_model=300, d_k=64, d_v=64, dropout=0.3)(x, x, x)
avg_pool = GlobalAveragePooling1D()(x)
max_pool = GlobalMaxPooling1D()(x)
conc = concatenate([avg_pool, max_pool],axis=1)
if sum(doc_features) > 0:
x1 = Concatenate()([conc,inp_docs])
conc = Dense(64, activation="relu")(conc)
if binary:
preds = Dense(2, activation="softmax")(conc)
else:
preds = Dense(3, activation="softmax")(conc)
model = Model(inputs=inputs, outputs=preds)
model.compile(
loss = "categorical_crossentropy",
optimizer = "adam")
return model
def build_model(embedding_matrix, nb_words, embedding_size=300, extra_embs=[0,0,0,0], model_type="simple", doc_features=[0,0,0], binary=False, no_embeddings=False):
if model_type == "simple":
return build_simple_LSTM(embedding_matrix, nb_words, embedding_size, extra_embs, doc_features)
elif model_type == "cnn":
return build_yookim_CNN(embedding_matrix, nb_words, embedding_size, extra_embs, doc_features)
elif model_type == "lstm":
return build_attention_LSTM(embedding_matrix, nb_words, embedding_size, extra_embs, doc_features, binary, no_embeddings)
def make_binary(value):
if value == 3:
return 2
else:
return 1
embedding_matrix = np.concatenate((embedding_matrix_twitter, embedding_matrix_para), axis=1)
embedding_matrix = np.concatenate((embedding_matrix, embedding_matrix_fast), axis=1)
embedding_matrix = np.concatenate((embedding_matrix, embedding_matrix_glove), axis=1)
# embedding_matrix = embedding_matrix_fast
no_embeddings = False
binary = False
if binary:
# To categorical
train["Binary"] = train["Intake"].apply(make_binary)
test["Binary"] = test["Intake"].apply(make_binary)
dev["Binary"] = dev["Intake"].apply(make_binary)
y_train = to_categorical(train['Binary'].values)[:,[1,2]]
y_dev = to_categorical(dev['Binary'].values)[:,[1,2]]
y_test = to_categorical(test['Binary'].values)[:,[1,2]]
outs = 2
outs_y = "Binary"
else:
outs = 3
outs_y = "Intake"
# To categorical
y_train = to_categorical(train['Intake'].values)[:,[1,2,3]]
y_dev = to_categorical(dev['Intake'].values)[:,[1,2,3]]
y_test = to_categorical(test['Intake'].values)[:,[1,2,3]]
# is_drug, VB_to_drug, pos_rel_drug, drug_verb_span
# num_pers,num_drugs,vb_negated
#semantic [1,0,0,0],[1,1,0] + emoji
#syntactic [0,1,0,0],[0,0,1]
# feat_dict = {"none": ([0,0,0,0],[0,0,0]),
# feat_dict= {"semantic": ([1,0,0,0],[1,1,0]),
# "syntactic": ([0,1,0,0],[0,0,1]),
# "pseudo1": ([0,0,1,0],[0,0,0]),
# "pseudo2": ([0,0,0,1],[0,0,0]),
feat_dict={"pseudo3": ([0,0,1,1],[0,0,0]),
# "semantic+syntactic": ([1,1,0,0],[1,1,1]),
# "semantic+pseudo1": ([1,0,1,0],[1,1,0]),
# "semantic+pseudo2": ([1,0,0,1],[1,1,0]),
# "semantic+pseudo3": ([1,0,1,1],[1,1,0]),
# "syntactic+pseudo1": ([0,1,1,0],[0,0,1]),
# "syntactic+pseudo2": ([0,1,0,1],[0,0,1]),
# "syntactic+pseudo3": ([0,1,1,1],[0,0,1]),
# "semantic+syntactic+pseudo1": ([1,1,1,0],[1,1,1]),
# "semantic+syntactic+pseudo2": ([1,1,0,1],[1,1,1]),
# "semantic+syntactic+pseudo3": ([1,1,1,1],[1,1,1]),
}
for feat_type in feat_dict.keys():
embeddings = "all"
embs = feat_dict[feat_type][0]
doc_features = feat_dict[feat_type][1]
embs_ind = [ind for ind,x in enumerate(embs) if x>0]
feats_ind = [ind for ind,x in enumerate(doc_features) if x>0]
batch_size = 32
num_epoch = 10
runs = 10
model_type = "lstm"
fp = "outputs/{}_{}_{}_{}".format(model_type,feat_type,embeddings,binary)
if no_embeddings:
fp += "_no-embeddings"
train_input = []
test_input = []
dev_input = []
if not no_embeddings:
train_input = [train_word_sequences]
test_input = [test_word_sequences]
dev_input = [dev_word_sequences]
if len(embs_ind) > 0:
train_input.append(train_emb_sequences[:,:,embs_ind])
test_input.append(test_emb_sequences[:,:,embs_ind])
dev_input.append(dev_emb_sequences[:,:,embs_ind])
if len(feats_ind) >0:
train_input.append(train_features[:,feats_ind])
test_input.append(test_features[:,feats_ind])
dev_input.append(dev_features[:,feats_ind])
with open(fp,"w") as f:
f.write("{}\n{} runs\n{} epochs each\nbatch size{}\nfeatures {}".format(model_type,runs,num_epoch,batch_size,embs))
print("Start training ...")
pred_prob = np.zeros((len(test_word_sequences),outs), dtype=np.float32)
start_time = time.time()
for run in range(runs):
print("\n\n\n\n RUN {}".format(run))
K.clear_session()
model = build_model(embedding_matrix, num_words, embedding_matrix.shape[1],extra_embs=embs, model_type=model_type, doc_features=doc_features, binary=binary, no_embeddings=no_embeddings)
# checkpoint = ModelCheckpoint(fp+".weights", monitor='val_loss', verbose=0, save_best_only=True, mode='min')
es = EarlyStopping(monitor='val_loss', min_delta=0, patience=2, verbose=0, mode='auto', restore_best_weights=True)
callbacks_list = [es]
model.fit(train_input,
y_train,
validation_data=[dev_input,y_dev],
batch_size=batch_size,
epochs=num_epoch,
class_weight=label_weights,
callbacks=callbacks_list,
verbose=3)
pred_prob += 1/runs * np.squeeze(model.predict(test_input, batch_size=batch_size, verbose=3))
del model
print("--- %s seconds ---" % (time.time() - start_time))
preds = [x.argmax() + 1 for x in pred_prob]
f.write("\n\n\nTest Results\n")
f.write(classification_report(test[outs_y].values, preds, digits=4))
tp11, fp12, fp13, fp21, tp22, fp23, fp31, fp32, tp33 = sklm.confusion_matrix(test[outs_y].values, preds).ravel()
P12 = (tp11 + tp22) / (tp11 + fp12 + fp13 + tp22 + fp21 + fp23)
R12 = (tp11 + tp22) / (tp11 + fp21 +fp31 + tp22 + fp12 + fp32)
F12 = (2 * P12 * R12) / (P12 + R12)
f.write("Micro Averaged:")
f.write("\nP:{:.4f}\tR:{:.4f}\tF:{:.4f}".format(P12,R12,F12))
<file_sep>import pandas as pd
import glob, os
df = pd.concat(map(pd.read_csv, glob.glob(os.path.join('', "data/train*.csv"))))
df = df.dropna()
df["Text"] = df['Text'].map(lambda x: x.encode('').decode('utf-8'))
df
s = df.shape[0]
train_index = int(s * 0.75)
dev_index = int(s * 0.8)
df
with open("train.csv", "w", encoding="utf-8") as f:
df.iloc[0:train_index].to_csv(f, encoding="utf-8")
with open("dev.csv", "w", encoding="utf-8") as f:
df.iloc[train_index:dev_index].to_csv(f)
with open("test.csv", "w", encoding="utf-8") as f:
df.iloc[dev_index:].to_csv(f)
<file_sep>
# coding: utf-8
# In[38]:
from bokeh.plotting import figure, output_file, show
import os
PATH = "outputs\size\\"
# In[39]:
x = []
y = []
for fp in os.listdir(PATH):
size = float(fp[-3:])
with open(PATH+fp,"r") as f:
val = float(f.read()[-6:])
x.append(size)
y.append(val)
# In[40]:
# output to static HTML file
output_file("size_evaluation.html")
# create a new plot with a title and axis labels
p = figure(title="Training Set Size vs F1", x_axis_label='% Train', y_axis_label='F1')
# add a line renderer with legend and line thickness
p.line(x, y, legend="F1", line_width=4)
p.circle(x, y, fill_color="blue", line_color="blue", size=6)
p.legend.location = "top_left"
p.xaxis.ticker = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
# show the results
show(p)
<file_sep># LING-5415
Final project repo for LING 5415 - Medication Intake Detection on Twitter
Running requires a directory ../embeddings containing the embedding sets.
python train.py
outputs go to the output directory, pretty much all combinations of outputs are already included there though.
Requires Tensorflow 2.0
<file_sep>import os
import re
import sys
import numpy as np
import pandas as pd
from keras.preprocessing.text import Tokenizer, text_to_word_sequence
from keras.utils.np_utils import to_categorical
from keras.preprocessing.sequence import pad_sequences
from utils.embeddings import load_glove
GLOVE_DIR = "../glove"
TRAIN_DATA = "./data/train.csv"
TEST_DATA = "./data/test.csv"
embedding_matrix, nb_words = load_glove()
#Load embeddings
embeddings_index = {}
with open(os.path.join(GLOVE_DIR, 'glove.6B.50d.txt'), encoding="utf8") as f:
for line in f:
values = line.split(" ")
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
# def clean_special_chars(text):
# punct = "/-'?!.,#$%\'()*+-/:;<=>@[\\]^_`{|}~" + '""“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\×™√²—–&'
# mapping = {"‘": "'", "₹": "e", "´": "'", "°": "", "€": "e", "™": "tm", "√": " sqrt ", "×": "x", "²": "2", "—": "-", "–": "-", "’": "'", "_": "-", "`": "'", '“': '"', '”': '"', '“': '"', "£": "e", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }
# text = re.sub(r'(\\\\){0,2}x[\d\w]{2}','',text)
# for p in mapping:
# text = text.replace(p, mapping[p])
#
# for p in punct:
# text = text.replace(p, " "+p+" ")
#
# specials = {'\u200b': ' ', '…': ' ... ', '\ufeff': '', 'करना': '', 'है': ''} # Other special characters that I have to deal with in last
# for s in specials:
# text = text.replace(s, specials[s])
# return text
def replace_usernames(text):
return re.sub(r'@[a-zA-Z0-9_]{1,15}','$USER',text)
def replace_hashtags(text):
return re.sub(r'#[a-zA-Z0-9_]*','$HASHTAG',text)
def replace_urls(text):
return re.sub(r'[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)','$URL',text)
def clean_text(text):
text = replace_usernames(text)
text = replace_hashtags(text)
text = replace_urls(text)
# text = clean_special_chars(text)
return text
df_train= pd.read_csv(TRAIN_DATA)
df_test= pd.read_csv(TEST_DATA)
df_train["Tweet"] = df_train["Tweet"].apply(lambda x: clean_text(x))
df_test["Tweet"] = df_test["Tweet"].apply(lambda x: clean_text(x))
texts = df_train["Tweet"]
# texts = df_test["Tweet"]
tokenizer = Tokenizer(num_words=None)
tokenizer.fit_on_texts(texts)
word_index = tokenizer.word_index
oov_count = 0
oov = []
for word in word_index:
if word not in embeddings_index.keys():
oov_count += 1
if word not in oov:
oov.append(word)
oov
print("Number OOV words:{}\nNumber of words in vocab:{}\nVocab Coverage:{}".format(oov_count,len(word_index),(len(word_index) - oov_count)/len(word_index)))
from collections import Counter
tokenized_texts = texts.apply(text_to_word_sequence)
tokenized_texts = list(tokenized_texts)
tokenized_texts
X = Counter([y for x in tokenized_texts for y in x])
X.most_common()
drugs = [r'dioralyte', r'solpadine', r'solpadol',
r'icyhot', r'zanaflex', r'tramdol',
r'moldavite', r'robex', r'novacaine',
r'tramadol', r'pedialite', r'NeoCitran',
r'dydramol', r'adderal', r'ciroc', r'im+odium',
r'profen', r'excedrine', r'zanny', r'gaviscon',
r'cod[ea]mol', r'panadol', r'ora[jg]el', r'ben[ea]dryl',
r'percocet', r'mucinex', r'dayquil',
r'nyquil', r'alieve', r'sudocrem',
r'hydroco', r'propionate', r'fluticasone',
r'liefern', r'medrol', r'klonopin',
r'proair', r'arcoxia', r'spiriva',
r'anacin', r'accolate', r'advair',
r'alprazolam', r'lorazepam',
r'symbicort', r'acetaminophen', r'methadone',
r'oxyc', r'robitussin', r'fluoxetine',
r'diazi?e?pam', r'advil', r'tylenol',
r'steroid', r'ibuprofen', r'motrin',
r'valium', r'panadol', r'code?ine',
r'flonase', r'ativan', r'proza[ck]',
r'vent[oia]lin', r'pred(ni|in)sone',
r'xan([enya]x|s)', r'paracet(am|ma)ol',
r'albuter[oa]l', r'clona[sz]epam']
failed = []
for word in X.most_common():
flag = False
for drug in drugs:
if re.search(drug,word[0],re.I):
flag = True
if not flag:
failed.append(word[0])
failed
failed = []
for tweet in texts:
flag = False
for drug in drugs:
if re.search(drug,tweet,re.I):
flag = True
if not flag:
failed.append(tweet)
len(failed)
failed
| e876b5abfa214b666459be941714520f6f0f66d0 | [
"Markdown",
"Python"
] | 5 | Python | irpepper/LING-5415 | a603e94dfa9b420a8e5a649ca469fd5942c04608 | 619de5c0a517e9df7771f5eaf126f7c06c0c38a0 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NordNet
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
Engine engine = new Engine();
Timer t = new Timer(engine.Engine, null, 0, 60000);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NordNet
{
public class NordnetConnection
{
public NordnetConnection()
{
}
public bool Connect()
{
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
namespace NordNet
{
class ConfigHelper
{
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NordNet
{
public class Engine
{
private NordnetConnection nordnetConnection;
public Engine()
{
nordnetConnection = new NordnetConnection();
}
public void Engine(Object state)
{
}
}
}
| d1c36482189a7f734e3c0fb478cd45795aa754e0 | [
"C#"
] | 4 | C# | KristianBjork/Nordnet | e2cc4f9f14c791ad1f53c7fe57366432b10c2759 | b75c15468dd38d270f7749bfcd58888259a9eca1 |
refs/heads/master | <file_sep>from time import time
class Board:
def __init__(self, size, board):
self.size = size
if board == None:
self.board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
else:
mat = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
for i in range(self.size):
for j in range(self.size):
mat[i][j] = board[i][j]
self.board = mat
def __repr__(self):
return "Board()"
def __str__(self):
print("\n")
for i in range(self.size):
for j in range(self.size):
if ( j == 2 ):
print(self.board[i][j], end=' ')
else:
print(self.board[i][j], end=' | ')
print("\n")
print()
def printMatrix(self):
print("\n")
for i in range(self.size):
for j in range(self.size):
if ( j == 2 ):
print(self.board[i][j], end=' ')
else:
print(self.board[i][j], end=' | ')
print("\n")
print()
def isMoveLeft(self):
for i in range(self.size):
for j in range(self.size):
if ( self.board[i][j] == '_' ):
return True
return False
def evaluate(self, user, computer):
for i in range(self.size):
if ( self.board[i][0] == self.board[i][1] and self.board[i][1] == self.board[i][2] ):
if ( self.board[i][0] == computer ):
return 1
elif ( self.board[i][0] == user ):
return -1
for i in range(self.size):
if ( self.board[0][i] == self.board[1][i] and self.board[1][i] == self.board[2][i] ):
if ( self.board[0][i] == computer ):
return 1
elif ( self.board[0][i] == user ):
return -1
# Diagonals
if ( self.board[0][0] == self.board[1][1] and self.board[1][1] == self.board[2][2] ):
if ( self.board[0][0] == computer ):
return 1
elif ( self.board[0][0] == user ):
return -1
if ( self.board[0][2] == self.board[1][1] and self.board[1][1] == self.board[2][0] ):
if ( self.board[0][2] == computer ):
return 1
elif ( self.board[0][2] == user ):
return -1
return 0
class TicTacToe:
def __init__(self, size, user, computer):
self.size = size
self.user = user
self.computer = computer
self.count1 = 0
def AlphaBetaPruning(self, board, aplha, beta, isComputer):
self.count1 += 1
score = board.evaluate(self.user, self.computer)
if ( score == 1 or score == -1 ):
return score
if ( not board.isMoveLeft() ):
return 0
if ( isComputer ):
best = -10
for i in range(self.size):
for j in range(self.size):
if ( board.board[i][j] == '_' ):
board.board[i][j] = self.computer
best = max(best, self.AlphaBetaPruning(board, alpha, beta, not isComputer))
board.board[i][j] = '_'
aplha = max(aplha, best)
if ( beta <= alpha ):
break
return best
else:
best = 10
for i in range(self.size):
for j in range(self.size):
if ( board.board[i][j] == '_' ):
board.board[i][j] = self.user
best = min(best, self.AlphaBetaPruning(board, alpha, beta, not isComputer))
board.board[i][j] = '_'
beta = min(beta, best)
if ( beta <= alpha ):
break
return best
def NextMoveAplhaBeta(self, board, alpha, beta):
BestValue = -10
Matrix = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
for i in range(self.size):
for j in range(self.size):
if ( board.board[i][j] == '_' ):
board.board[i][j] = self.computer
value = self.AlphaBetaPruning(board, alpha, beta, False)
if ( value > BestValue ):
MatrixObject = Board(self.size, board.board)
Matrix = MatrixObject.board
BestValue = value
board.board[i][j] = '_'
return MatrixObject
if __name__ == "__main__":
print("\n\tTic-Tac-Toe Game")
print("\tPlayer vs Computer\n")
user = 'X'
computer = 'O'
alpha = -10
beta = 10
while(True):
print("\t1. Play")
print("\t3. Exit")
algo = int(input(": "))
if ( algo >= 3 ):
break
Matrix = Board(3, None)
ttt = TicTacToe(3, user, computer)
turn = True
for i in range(9):
if ( turn ):
while(True):
print("Player's turn...")
x = int(input("x: "))
y = int(input("y: "))
if ( Matrix.board[x][y] != '_' ):
print("\tWrong Move!\n")
continue
Matrix.board[x][y] = user
# print(Matrix)
Matrix.printMatrix()
turn = False
break
else:
print("Computer's Turn")
t1 = int(round(time()*1000))
Matrix = ttt.NextMoveAplhaBeta(Matrix, alpha, beta)
t2 = int(round(time()*1000))
print("Total time taken: ", t2-t1)
Matrix.printMatrix()
turn = True
output = Matrix.evaluate(user, computer)
if ( output == -1 ):
print("\nPlayer Wins!")
break
elif ( output == 1 ):
print("\nComputer Wins!")
break
elif ( not Matrix.isMoveLeft() ):
print("\nMatch Draw!")
break
print("Moves: ", ttt.count1)<file_sep># AI
Human vs AI TicTacToe
Python implementation of AI game
<h2>Algorithm minimax and alpha beta pruning is used</h2>
<h3>It can be extended to any square size of the game</h3>
| 4fe5166618f285ea5a2d0372d30f54bf83fdc8d9 | [
"Markdown",
"Python"
] | 2 | Python | JnaneshD/AI | 9107f3a8b192d823a92e889885a25de628944155 | fadb41427c2f93f97d51a494bd07b412dce2fa4e |
refs/heads/master | <file_sep>package crudCabelereiro;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class CabelereiroDAO {
//CLASSE DAO AQUI INSERIMOS OS METODOS NECESSÁRIOS
//MÉTODO DE INSERT
public void inserir(Connection conn, Cabelereiro c) {
String
sqlInsert = "INSERT INTO cliente "
+ "(codCliente, nome, telefone, endereco, horario) values (?,?,?,?,?)";
try(PreparedStatement stm = conn.prepareStatement(sqlInsert);){
stm.setInt(1, c.getCodCliente());
stm.setString(2, c.getNome());
stm.setString(3, c.getTelefone());
stm.setString(4, c.getEndereco());
stm.setString(5, c.getHorario());
stm.execute();
}catch(Exception e){
e.printStackTrace();
String msg = e.getMessage();
System.out.println(msg);
try {
conn.rollback();
} catch(Exception e1) {
System.out.println(e1.getMessage());
}
}
}
//METODO DE DELETE
public void delete(Connection conn, Cabelereiro c) {
String sqlDelete = "DELETE FROM cliente WHERE codCliente = ?";
try(PreparedStatement stm = conn.prepareStatement(sqlDelete);){
stm.setInt(1, c.getCodCliente());
stm.execute();
}catch(Exception e){
e.printStackTrace();
try {
conn.rollback();
}catch(Exception e1){
String msg = e1.getMessage();
System.out.println("Deu erro: " + msg);
}
}
}
//METODO DE UPDATE
public void update(Connection conn, String novoTelefone, Cabelereiro c) {
String sqlUpdate =
"UPDATE cliente set telefone = ? where codCliente = ?";
try(PreparedStatement stm = conn.prepareStatement(sqlUpdate);){
stm.setString(1, novoTelefone);
stm.setInt(2, c.getCodCliente());
stm.execute();
}catch(Exception e){
e.printStackTrace();
try {
conn.rollback();
}catch(Exception e1) {
String msg = e1.getMessage();
System.out.println(msg);
}
}
}
//MÉTODO DE SELECT
public void select(Cabelereiro c) {
Conexao conection = new Conexao();
PreparedStatement stmt = null;
String sqlInsert = "SELECT codCliente, nome, telefone, endereco, horario from cliente";
try {
Connection conn = conection.conectar();
stmt = conn.prepareStatement(sqlInsert);
ResultSet result = stmt.executeQuery();
ResultSet rs = stmt.getResultSet();
while (result.next()) {
JOptionPane.showMessageDialog(null,
rs.getInt("codCliente") + ", Nome: " + rs.getString("nome") + ", telefone: "
+ rs.getString("telefone") + ", endereco: " + rs.getString("endereco")
+ ", horario: " + rs.getString("horario"));
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e);
} catch (Exception e) {
try {
conection.desconectar();
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println(e);
}
}
}
<file_sep>package crudCabelereiro;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class TelaCrud extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TelaCrud frame = new TelaCrud();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TelaCrud() {
CabelereiroDAO cD = new CabelereiroDAO();
Cabelereiro c = new Cabelereiro();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
this.setLocationRelativeTo(null); /*CENTRALIZA O CONTAINER*/
JButton btnInsert = new JButton("Insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new telaInsert().setVisible(true);
dispose();
}
});
contentPane.add(btnInsert);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Conexao.conectar();
int codigoDeletado = Integer.parseInt(JOptionPane.showInputDialog("Digite o codigo para ser deletado"));
c.setCodCliente(codigoDeletado);
cD.delete(Conexao.getConnection(), c);
JOptionPane.showMessageDialog(null, "Deletado");
Conexao.desconectar();
} catch (NullPointerException | SQLException e2) {
e2.printStackTrace();
}
}
});
contentPane.add(btnDelete);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Conexao.conectar();
String novoTelefone = JOptionPane.showInputDialog("Digite o novo telefone");
int codigo = Integer.parseInt(JOptionPane.showInputDialog("Digite o codigo do cliente"));
c.setCodCliente(codigo);
cD.update(Conexao.getConnection(), novoTelefone, c);
JOptionPane.showMessageDialog(null, "Atualizado");
Conexao.desconectar();
} catch (NullPointerException | SQLException e2) {
e2.printStackTrace();
}
}
});
contentPane.add(btnUpdate);
JButton btnSelect = new JButton("Select");
btnSelect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Conexao.conectar();
cD.select(c);
Conexao.desconectar();
} catch (NullPointerException | SQLException e2) {
e2.printStackTrace();
}
}
});
contentPane.add(btnSelect);
}
}
<file_sep>create database cabelereiro;
use cabelereiro;
create table cliente(
codCliente int not null auto_increment,
nome varchar(50) not null,
telefone varchar(15) not null,
endereco varchar(255) not null,
horario datetime not null,
-- keys
primary key(codCliente)
);
alter table cliente modify column horario varchar(50);
-- esqueci do valor do valor do corte
select * from cliente;
<file_sep>package crudCabelereiro;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
public class telaInsert extends JFrame {
private JPanel contentPane;
private JTextField txtCodCliente;
private JTextField txtNome;
private JTextField txtTelefone;
private JTextField txtEndereço;
private JTextField txtHorario;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
telaInsert frame = new telaInsert();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public telaInsert() {
Cabelereiro c = new Cabelereiro();
CabelereiroDAO cD = new CabelereiroDAO();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 426, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
this.setLocationRelativeTo(null); /*CENTRALIZA O CONTAINER*/
JLabel lblNewLabel = new JLabel("Codigo Cliente:");
contentPane.add(lblNewLabel);
txtCodCliente = new JTextField();
contentPane.add(txtCodCliente);
txtCodCliente.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Nome:");
contentPane.add(lblNewLabel_1);
txtNome = new JTextField();
contentPane.add(txtNome);
txtNome.setColumns(10);
JLabel lblTelefone = new JLabel("Telefone");
contentPane.add(lblTelefone);
txtTelefone = new JTextField();
txtTelefone.setColumns(10);
contentPane.add(txtTelefone);
JLabel lblEndereo = new JLabel("Endere\u00E7o:");
contentPane.add(lblEndereo);
txtEndereço = new JTextField();
txtEndereço.setColumns(10);
contentPane.add(txtEndereço);
JLabel lblHorario = new JLabel("Horario:");
contentPane.add(lblHorario);
txtHorario = new JTextField();
txtHorario.setColumns(10);
contentPane.add(txtHorario);
JButton btnInserir = new JButton("Inserir");
btnInserir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int codigo = Integer.parseInt(txtCodCliente.getText());
String nome = txtNome.getText();
String telefone = txtTelefone.getText();
String endereco = txtEndereço.getText();
String horario = txtHorario.getText();
c.setCodCliente(codigo);
c.setNome(nome);
c.setTelefone(telefone);
c.setEndereco(endereco);
c.setHorario(horario);
try {
Conexao.conectar();
cD.inserir(Conexao.getConnection(), c);
Conexao.desconectar();
} catch (NullPointerException | SQLException e2) {
e2.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Inserido");
}
});
contentPane.add(btnInserir);
JButton btnVoltar = new JButton("Voltar");
btnVoltar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new TelaCrud().setVisible(true);
dispose();
}
});
contentPane.add(btnVoltar);
this.setLocationRelativeTo(null); /*CENTRALIZA O CONTAINER*/
}
}
| 4e9f6c6e08d9736e07a9f2c8d8d0cb061493012f | [
"Java",
"SQL"
] | 4 | Java | dcrodrigues0/crudJava | 4e970abbec63805f943ae561fcd63560e96f9cf7 | 90311a88dfe7626340af9d670320479990bbfb6b |
refs/heads/master | <repo_name>ChaitraRp/ProxyServer<file_sep>/Makefile
CC=gcc
CFLAGS=
SRC= proxyserver.c
all: $(SRC)
$(CC) -o webproxy.o $(SRC)
.PHONY : clean
clean :
-rm -f *.o .cache
<file_sep>/readme.txt
#Contents
There is one folder:
- proxyServer
proxyServer has the following contents:
- proxyserver.c
- Makefile
- gethostbyname_test.c (A helper file)
- blocked_sites.txt
- DNSCache.txt
-------------------------------------------------------------------------------------
#How to run the code:
To run: type make on command line from proxyServer folder
To clean the object file: run make clean on command line from webServer folder
- ./webproxy 10001 45
where 10001 port number and 45 is optional cache timeout value if not provided it will set default cache time out to 20 second
-------------------------------------------------------------------------------------
#What has been implemented
- Proxy server that supports multiple client connections
- Multithreading via fork()
- Only supports GET method
- Parsing client requests into HTTP and URL structs
- Caching and cache timeout (MD5 of requested URL)
----> if cache is found, then serve request via cached page depending on cache expiry timeout
----> if cache is not found, then send request to server and serve the response sent by the server
- Hostname IP Address cache (DNSCache.txt - no expiration)
- Blocked websites (blocked_sites.txt)
- Error handling (400, 501)
-------------------------------------------------------------------------------------
#Extra credit
- Link Prefetch (link on every page that begins with href=" is collected and stored in cache folder)<file_sep>/proxyserver.c
//NETSYS PROGRAMMING ASSIGNMENT 2
//<NAME>
//-----------------------------------LIBRARIES--------------------------------------
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>
#include <memory.h>
#include <errno.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
//--------------------------------------#DEFINE------------------------------------
#define DEFAULT_CACHE_TIMEOUT 20
#define MAXCONN 20
#define MAXRECVBUFSIZE 10000
#define MAXREQBUFFERSIZE 1000
#define CACHEDIR ".cache"
#define DEFAULT_PORT "80"
//----------------------------------GLOBAL VARIABLES-------------------------------
long int cacheTimeout;
int proxySocket;
int debug = 1;
int http_debug = 0;
struct timeval timeout;
struct hostent *hp;
struct hostent *host;
char blockedSitesFilename[] = "blocked_sites.txt";
int count = 1;
//----------------------------------STRUCT FOR URL---------------------------------
typedef struct URL{
char *SERVICE, *DOMAIN, *PORT, *PATH;
} URL;
//--------------------------------STRUCT FOR HTTP REQUEST--------------------------
typedef struct http_request{
char *HTTP_COMMAND, *COMPLETE_PATH, *HTTP_VERSION, *HTTP_BODY;
URL* HTTP_REQ_URL;
} HTTP_REQUEST;
//------------------------------RECEIVE DATA FUNCTION------------------------------
//Reference: https://stackoverflow.com/questions/28098563/errno-after-accept-in-linux-socket-programming
//Reference: https://stackoverflow.com/questions/8874021/close-socket-directly-after-send-unsafe
int receiveData(int clientsockfd, char** data){
int dataLength = 0;
int dataReceived = 0;
int bytesReceived;
char tempData[MAXRECVBUFSIZE];
bzero(tempData, sizeof(tempData));
//timeout part
bzero(&timeout, sizeof(timeout));
timeout.tv_sec = 60;
setsockopt(clientsockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval));
*data = calloc(MAXRECVBUFSIZE, sizeof(char));
dataLength = MAXRECVBUFSIZE;
bzero(*data, dataLength);
//recv()
if((bytesReceived = recv(clientsockfd, *data, dataLength-1, 0)) < 0){
if(errno == EAGAIN || errno == EWOULDBLOCK){
perror("Error in recv(). Unable to receive data");
return -1;
}
}
dataReceived = bytesReceived;
//timeout part
timeout.tv_sec = 0;
timeout.tv_usec = 500000;
setsockopt(clientsockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval));
//collect all the data
while((bytesReceived = recv(clientsockfd, tempData, MAXRECVBUFSIZE-1, 0)) > 0){
*data = realloc(*data, (dataLength + bytesReceived)*sizeof(char));
dataLength = dataLength + bytesReceived;
memcpy(*data + dataReceived, tempData, bytesReceived+1);
dataReceived += bytesReceived;
bzero(tempData, sizeof(tempData));
}
if(bytesReceived == -1 && errno != EAGAIN && errno != EWOULDBLOCK){
perror("Error in recv(). Unable to receive data. Timeout");
return -1;
}
return dataReceived;
}
//------------------------------SEND ERROR MESSAGE----------------------------------
int sendErrorMessage(int clientsockfd, char* errorMsg, char* errorContent){
int errorMessageLength;
int errorContentLength;
if(errorMsg != NULL)
errorMessageLength = strlen(errorMsg);
else
errorMessageLength = 0;
if(errorContent != NULL)
errorContentLength = strlen(errorContent);
else
errorContentLength = 0;
char responseErrorMessage[errorMessageLength + errorContentLength + 5];
bzero(responseErrorMessage, sizeof(responseErrorMessage));
snprintf(responseErrorMessage, sizeof(responseErrorMessage), "%s\r\n%s\r\n", errorMsg, errorContent != NULL ? errorContent : "");
send(clientsockfd, responseErrorMessage, strlen(responseErrorMessage)+1, 0);
return 0;
}
//---------------------------------BLOCKED WEBSITE----------------------------------
//Ref: http://www.geekinterview.com/question_details/85833
void blockedWebsites(int clientsockfd, URL* urlData2, struct hostent *h){
char *address = urlData2->DOMAIN;
FILE *fp;
char line[200];
fp = fopen(blockedSitesFilename, "r");
if(!fp){
perror("Could not open file");
exit(0);
}
while(fgets(line, 200, fp) != NULL){
//printf("Line: %s\n", line);
if(strstr(line, address) || strstr(line, h->h_name)){
printf("--------------------------------------------\n");
printf("ERROR 403 Forbidden: Blocked URL\n");
char *responseError = "Blocked URL";
char errorContent[strlen("<html><body>ERROR 403 Forbidden: %s</body></html>") + strlen(responseError)+1];
bzero(errorContent, sizeof(errorContent));
snprintf(errorContent, sizeof(errorContent), "<html><body>ERROR 403 Forbidden: %s</body></html>", responseError);
char errorMessageHead[strlen("HTTP/1.1 403 Forbidden\r\nContent-Length: %lu")+10+1];
bzero(errorMessageHead, sizeof(errorMessageHead));
snprintf(errorMessageHead, sizeof(errorMessageHead), "HTTP/1.1 403 Forbidden\r\nContent-Length: %lu", sizeof(errorContent));
sendErrorMessage(clientsockfd, errorMessageHead, errorContent);
//exit(1);
}
}
fclose(fp);
}
//----------------------------PARSE URL STRUCT-------------------------------------
//Ref: https://paulschreiber.com/blog/2005/10/28/simple-gethostbyname-example/
int parseURL(int clientsockfd, char* path, URL* urlData){
char *reqURL;
char *reqDomain;
char *urlChunks;
char* portNum = NULL;
char *temp = strdup(path);
FILE *fp;
urlChunks = strtok_r(temp, ":/", &reqURL);
if(urlChunks != NULL)
urlData->SERVICE = strdup(urlChunks);
urlChunks = strtok_r(NULL, "/", &reqURL);
if(urlChunks != NULL){
char* urlDomain = strtok_r(urlChunks, ":", &reqDomain);
if(urlDomain != NULL){
urlData->DOMAIN = strdup(urlDomain);
while((urlDomain = strtok_r(NULL, ":", &reqDomain)) != NULL)
portNum = urlDomain;
if(portNum != NULL)
urlData->PORT = strdup(portNum);
}
}
if(reqURL != NULL)
urlData->PATH = strdup(reqURL);
if(http_debug == 1){
printf("****************************************************************\n");
printf("URL SERVICE: %s\n", urlData->SERVICE);
printf("URL DOMAIN: %s\n", urlData->DOMAIN);
printf("URL PORT: %s\n", urlData->PORT);
printf("URL PATH: %s\n", urlData->PATH);
printf("****************************************************************\n");
}
if(clientsockfd != -5){
if(urlData->DOMAIN != NULL){
hp = gethostbyname(urlData->DOMAIN);
//host = gethostbyaddr(urlData->DOMAIN, sizeof(urlData->DOMAIN), AF_INET);
if(!hp){
printf("SERVER NOT FOUND\n");
exit(1);
}
else if(strcmp("443", hp->h_name) != 0){
printf("%s = ", hp->h_name);
unsigned int i=0;
printf("%s\n", inet_ntoa(*(struct in_addr*)(hp->h_addr_list[0])));
fp = fopen("DNSCache.txt", "a");
fseek(fp, 0, SEEK_END);
fprintf(fp, "%s\t%s\n", urlData->DOMAIN, inet_ntoa(*(struct in_addr*)(hp->h_addr_list[0])));
/*while(hp->h_addr_list[i] != NULL){
printf( "%s ", inet_ntoa( *( struct in_addr*)( hp -> h_addr_list[i])));
i++;
}*/
}
}
blockedWebsites(clientsockfd, urlData, hp);
}
free(temp);
return 0;
}
//----------------------------PARSE HTTP_REQUEST-----------------------------------
int parseHTTPRequest(int clientsockfd, char* reqBuf, int reqBufLength, HTTP_REQUEST* httpStruct){
char tempBuf[reqBufLength];
char *temp1;
char *temp2;
char* reqBody;
bzero(tempBuf, sizeof(tempBuf)*sizeof(char));
if(reqBuf == NULL){
printf("Received empty request buffer\n");
return -1;
}
memcpy(tempBuf, reqBuf, reqBufLength*sizeof(char));
char* reqLine = strtok_r(tempBuf, "\r\n", &temp1);
char* reqVal = strtok_r(reqLine, " ", &temp2);
if(reqVal == NULL){
printf("Command not found\n");
return -1;
}
httpStruct->HTTP_COMMAND = strdup(reqVal);
reqVal = strtok_r(NULL, " ", &temp2);
if(reqVal != NULL){
httpStruct->COMPLETE_PATH = strdup(reqVal);
httpStruct->HTTP_REQ_URL = calloc(1, sizeof(URL));
parseURL(clientsockfd, httpStruct->COMPLETE_PATH, httpStruct->HTTP_REQ_URL);
}
reqVal = strtok_r(NULL, " ", &temp2);
if(reqVal == NULL){
printf("HTTP version not found\n");
return -1;
}
httpStruct->HTTP_VERSION = strdup(reqVal);
if((reqBody = strstr(reqBuf, "\r\n\r\n")) != NULL && strlen(reqBody) > 4)
httpStruct->HTTP_BODY = strdup(reqBody);
if(http_debug == 1){
printf("****************************************************************\n");
printf("HTTP COMMAND: %s\n", httpStruct->HTTP_COMMAND);
printf("HTTP PATH: %s\n", httpStruct->COMPLETE_PATH);
printf("HTTP VERSION: %s\n", httpStruct->HTTP_VERSION);
printf("****************************************************************\n");
}
return 0;
}
//--------------------------------INTERNAL ERROR------------------------------------
int internalError(int clientsockfd, char* errMsg){
char errorMessage[strlen("500 Internal Server Error: %s") + strlen(errMsg) + 1];
bzero(errorMessage, sizeof(errorMessage));
if(clientsockfd == -1)
return 1;
snprintf(errorMessage, sizeof(errorMessage), "500 Internal Server Error: %s", errMsg);
sendErrorMessage(clientsockfd, errorMessage, NULL);
return 0;
}
//-------------------------------ERROR HANDLING------------------------------------
int otherRequestErrors(int clientsockfd, HTTP_REQUEST httpReq){
if(strcmp(httpReq.HTTP_COMMAND, "GET") != 0){
if(strcmp(httpReq.HTTP_COMMAND, "HEAD") == 0 || strcmp(httpReq.HTTP_COMMAND, "POST") == 0 || strcmp(httpReq.HTTP_COMMAND, "PUT") == 0 || strcmp(httpReq.HTTP_COMMAND, "DELETE") == 0 || strcmp(httpReq.HTTP_COMMAND, "TRACE") == 0 || strcmp(httpReq.HTTP_COMMAND, "CONNECT") == 0){
char *responseError = "Unsupported method";
char errorContent[strlen("<html><body>501 Not Implemented %s: %s</body></html>") + strlen(responseError) + strlen(httpReq.HTTP_COMMAND)+1];
bzero(errorContent, sizeof(errorContent));
snprintf(errorContent, sizeof(errorContent), "<html><body>501 Not Implemented %s: %s</body></html>", responseError, httpReq.HTTP_COMMAND);
char errorMessageHead[strlen("HTTP/1.1 501 Not Implemented\r\nContent-Length: %lu")+10+1];
bzero(errorMessageHead, sizeof(errorMessageHead));
snprintf(errorMessageHead, sizeof(errorMessageHead), "HTTP/1.1 501 Not Implemented\r\nContent-Length: %lu", sizeof(errorContent));
sendErrorMessage(clientsockfd, errorMessageHead, errorContent);
return -1;
}
else{
char errorContent[strlen("<html><body>400 Bad Request: %s</body></html>") + strlen(httpReq.HTTP_COMMAND)+1];
bzero(errorContent, sizeof(errorContent));
snprintf(errorContent, sizeof(errorContent), "<html><body>400 Bad Request: %s</body></html>", httpReq.HTTP_COMMAND);
char errorMessageHead[strlen("HTTP/1.1 400 Bad Request\r\nContent-Length: %lu")+10+1];
bzero(errorMessageHead, sizeof(errorMessageHead));
snprintf(errorMessageHead, sizeof(errorMessageHead), "HTTP/1.1 400 Bad Request\r\nContent-Length: %lu", sizeof(errorContent));
sendErrorMessage(clientsockfd, errorMessageHead, errorContent);
return -1;
}
}
else if(!(strcmp(httpReq.HTTP_VERSION, "HTTP/1.0") == 0 || strcmp(httpReq.HTTP_VERSION, "HTTP/1.1") == 0)){
char errorContent[strlen("<html><body>400 Bad Request - Invalid HTTP-Version: %s</body></html>") + strlen(httpReq.HTTP_VERSION)+1];
bzero(errorContent, sizeof(errorContent));
snprintf(errorContent, sizeof(errorContent), "<html><body>400 Bad Request - Invalid HTTP-Version: %s</body></html>", httpReq.HTTP_VERSION);
char errorMessageHead[strlen("HTTP/1.1 400 Bad Request\r\nContent-Length: %lu")+10+1];
bzero(errorMessageHead, sizeof(errorMessageHead));
snprintf(errorMessageHead, sizeof(errorMessageHead), "HTTP/1.1 400 Bad Request\r\nContent-Length: %lu", sizeof(errorContent));
sendErrorMessage(clientsockfd, errorMessageHead, errorContent);
return -1;
}
else if(strcmp(httpReq.COMPLETE_PATH, "") == 0){
char errorContent[strlen("<html><body>400 Bad Request - Invalid URL: \"%s\"</body></html>") + strlen(httpReq.COMPLETE_PATH)+1];
bzero(errorContent, sizeof(errorContent));
snprintf(errorContent, sizeof(errorContent), "<html><body>400 Bad Request - Invalid URL: \"%s\"</body></html>", httpReq.COMPLETE_PATH);
char errorMessageHead[strlen("HTTP/1.1 400 Bad Request\r\nContent-Length: %lu")+10+1];
bzero(errorMessageHead, sizeof(errorMessageHead));
snprintf(errorMessageHead, sizeof(errorMessageHead), "HTTP/1.1 400 Bad Request\r\nContent-Length: %lu", sizeof(errorContent));
sendErrorMessage(clientsockfd, errorMessageHead, errorContent);
return -1;
}
return 0;
}
//-------------------------------COMPUTE MD5---------------------------------------
void computeMD5(char* cPath, int cPathLen, char *cPageName){
char MD5CmdBuffer[strlen("echo \"") + strlen("\" | md5sum") + cPathLen + 1];
FILE * fp;
bzero(MD5CmdBuffer, sizeof(MD5CmdBuffer));
strncpy(MD5CmdBuffer, "echo \"", sizeof(MD5CmdBuffer)-strlen(MD5CmdBuffer)-1);
strncat(MD5CmdBuffer, cPath, sizeof(MD5CmdBuffer)-strlen(MD5CmdBuffer)-1);
strncat(MD5CmdBuffer, "\" | md5sum", sizeof(MD5CmdBuffer)-strlen(MD5CmdBuffer)-1);
if(!(fp = popen(MD5CmdBuffer, "r"))){
perror("MD5 command error");
return;
}
if(fread(cPageName, 1, 32, fp) != 32){
perror("MD5 command error");
return;
}
pclose(fp);
}
//---------------------------------GET CACHE TIME----------------------------------
long int getTimeElapsedSinceCached(char* cacheFilename){
char getFileDateCommand[strlen("expr $(date +%s) - $(date -r ") + strlen(cacheFilename) + strlen(" +%s)") + 1];
char temp[50];
FILE *fp;
bzero(getFileDateCommand, sizeof(getFileDateCommand));
strncpy(getFileDateCommand, "expr $(date +%s) - $(date -r ", sizeof(getFileDateCommand)-strlen(getFileDateCommand)-1);
strncat(getFileDateCommand, cacheFilename, sizeof(getFileDateCommand)-strlen(getFileDateCommand)-1);
strncat(getFileDateCommand, " +%s)", sizeof(getFileDateCommand)-strlen(getFileDateCommand)-1);
if(!(fp = popen(getFileDateCommand, "r"))){
perror("get cache time error");
return -1;
}
if(fread(temp, 1, sizeof(temp), fp) == 0){
perror("error in getting cache page time");
return -1;
}
pclose(fp);
return strtol(temp, NULL, 10);
}
//-----------------------------SERVE DATA FROM SERVER-------------------------------
//Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ms737530(v=vs.85).aspx
//Reference: https://github.com/angrave/SystemProgramming/wiki/Networking,-Part-2:-Using-getaddrinfo
//Reference: https://stackoverflow.com/questions/40782933/why-are-there-multiple-results-from-getaddrinfo/40785761
int serveDataFromServer(int* serverSocketFd, HTTP_REQUEST* httpRequest){
struct addrinfo *results;
struct addrinfo hints;
int value;
FILE *fp;
bzero(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
char *portNumber = httpRequest->HTTP_REQ_URL->PORT;
if(portNumber == NULL)
portNumber = DEFAULT_PORT;
if((value = getaddrinfo(httpRequest->HTTP_REQ_URL->DOMAIN, portNumber, &hints, &results)) != 0){
printf("Unable to fetch from %s:%s\n", httpRequest->HTTP_REQ_URL->DOMAIN, portNumber);
printf("getaddrinfo() error: %s\n", gai_strerror(value));
return -1;
}
if(results !=NULL && results->ai_addr != NULL){
*serverSocketFd = socket(results->ai_addr->sa_family, results->ai_socktype, results->ai_protocol);
if(connect(*serverSocketFd, results->ai_addr, results->ai_addrlen) != 0){
perror("Error in connect()");
return -1;
}
char httpRequestBuffer[MAXREQBUFFERSIZE];
bzero(httpRequestBuffer, sizeof(httpRequestBuffer));
int httpRequestBufferSize = sizeof(httpRequestBuffer);
if(httpRequest->HTTP_BODY != NULL){
snprintf(httpRequestBuffer, httpRequestBufferSize, "%s %s %s\r\nHost: %s\r\nContent-Length: %lu\r\n\r\n%s",
httpRequest->HTTP_COMMAND,
httpRequest->COMPLETE_PATH,
httpRequest->HTTP_VERSION,
httpRequest->HTTP_REQ_URL->DOMAIN,
strlen(httpRequest->HTTP_BODY),
httpRequest->HTTP_BODY);
}
else{
snprintf(httpRequestBuffer, httpRequestBufferSize, "%s %s %s\r\nHost: %s\r\n\r\n",
httpRequest->HTTP_COMMAND,
httpRequest->COMPLETE_PATH,
httpRequest->HTTP_VERSION,
httpRequest->HTTP_REQ_URL->DOMAIN);
}
if(send(*serverSocketFd, httpRequestBuffer, sizeof(httpRequestBuffer), 0) < 0){
perror("Error in send()");
return -1;
}
}
freeaddrinfo(results);
return 0;
}
//----------------------------FETCH THE REQUESTED PAGE------------------------------
int fetchResponse(int* serversockfd, HTTP_REQUEST* req, char** responseBuf, int* responseBufLength, int clientsockfd){
char cachedPage[33];
char cacheExists = 0;
char isCacheValid = 0;
int cacheFileSize;
FILE* cacheFp;
bzero(cachedPage, sizeof(cachedPage));
computeMD5(req->COMPLETE_PATH, strlen(req->COMPLETE_PATH)+1, cachedPage);
char cachedPagePath[strlen(CACHEDIR) + strlen(cachedPage) + 2];
bzero(cachedPagePath, (strlen(CACHEDIR) + strlen(cachedPage) + 2)*sizeof(char));
snprintf(cachedPagePath, sizeof(cachedPagePath)*sizeof(char), "%s/%s", CACHEDIR, cachedPage);
//check if cached page exists and find out the cached page time
if(access(cachedPagePath, F_OK) == 0){
cacheExists = 1;
long int cachedPageTime = getTimeElapsedSinceCached(cachedPagePath);
if(cachedPageTime < cacheTimeout)
isCacheValid = 1;
}
//if cache exists and is valid then serve the request from the cache
if(cacheExists && isCacheValid){
if(debug)
printf("Fetching from cached data: %s\n", req->COMPLETE_PATH);
cacheFp = fopen(cachedPagePath, "rb");
if(fseek(cacheFp, 0, SEEK_END) < 0){
fclose(cacheFp);
internalError(clientsockfd, "Invalid cache file size");
return -1;
}
//check the cached file size
cacheFileSize = ftell(cacheFp);
if(cacheFileSize < 0){
fclose(cacheFp);
internalError(clientsockfd, "Cache file size not found");
return -1;
}
rewind(cacheFp);
*responseBuf = calloc(cacheFileSize, sizeof(char));
if((*responseBufLength = fread(*responseBuf, sizeof(char), cacheFileSize, cacheFp)) != cacheFileSize){
perror("Error in reading data from cached page");
internalError(clientsockfd, "Error in reading data from cached page");
fclose(cacheFp);
return -1;
}
fclose(cacheFp);
}
//This is in case cached page does not exist
else{
if(debug)
printf("Fetching from server: %s\n", req->COMPLETE_PATH);
if(serveDataFromServer(serversockfd, req) < 0){
printf("Server request error\n");
internalError(clientsockfd, "Server request error");
return -1;
}
if((*responseBufLength = receiveData(*serversockfd, responseBuf)) < 0){
perror("Server response error");
internalError(clientsockfd, "Server response error");
return -1;
}
close(*serversockfd);
//add this entry to cache directory
cacheFp = fopen(cachedPagePath, "wb+");
fwrite(*responseBuf, sizeof(char), *responseBufLength, cacheFp);
fclose(cacheFp);
}
return 0;
}
//--------------------------------CLEAN URL STRUCTURE------------------------------
void clearURLStruct(URL* tempURL){
if(tempURL->SERVICE != NULL)
free(tempURL->SERVICE);
if(tempURL->DOMAIN != NULL)
free(tempURL->DOMAIN);
if(tempURL->PORT != NULL)
free(tempURL->PORT);
if(tempURL->PATH != NULL)
free(tempURL->PATH);
}
//------------------------------CLEAN HTTP STRUCTURE--------------------------------
void cleanHTTPStructure(HTTP_REQUEST* temp){
if(temp->HTTP_COMMAND != NULL)
free(temp->HTTP_COMMAND);
if(temp->COMPLETE_PATH != NULL)
free(temp->COMPLETE_PATH);
if(temp->HTTP_VERSION != NULL)
free(temp->HTTP_VERSION);
if(temp->HTTP_BODY != NULL)
free(temp->HTTP_BODY);
if(temp->HTTP_REQ_URL != NULL){
clearURLStruct(temp->HTTP_REQ_URL);
free(temp->HTTP_REQ_URL);
}
}
//--------------------------LINK PREFETCH HELPER FUNCTION--------------------------
int linkPrefetchData(HTTP_REQUEST mainLink, char* subLink, char** destination){
int fullPathLength;
char* portNum;
if(subLink[0] == '/'){
if(mainLink.HTTP_REQ_URL->PORT != NULL)
portNum = mainLink.HTTP_REQ_URL->PORT;
else
portNum = "";
fullPathLength = strlen(mainLink.HTTP_REQ_URL->SERVICE) + strlen(mainLink.HTTP_REQ_URL->DOMAIN) + strlen(portNum) + strlen(subLink) + 5;
*destination = malloc((fullPathLength)*sizeof(char));
if(strlen(portNum) != 0){
snprintf(*destination, fullPathLength, "%s://%s:%s%s", mainLink.HTTP_REQ_URL->SERVICE, mainLink.HTTP_REQ_URL->DOMAIN, portNum, subLink);
}
else{
snprintf(*destination, fullPathLength, "%s://%s%s", mainLink.HTTP_REQ_URL->SERVICE, mainLink.HTTP_REQ_URL->DOMAIN, subLink);
}
}
else if(strstr(subLink, "://") != NULL)
*destination = strdup(subLink);
else{
int fullPathLength = strlen(mainLink.COMPLETE_PATH) + strlen(subLink) + 2;
*destination = malloc((fullPathLength)*sizeof(char));
snprintf(*destination, fullPathLength, "%s/%s", mainLink.COMPLETE_PATH, subLink);
}
return 0;
}
//----------------------------------LINK PREFETCH-----------------------------------
int linkPrefetch(HTTP_REQUEST mainPage, char* responseBuff){
char *mainResponse = strdup(responseBuff);
char *link;
char *link2;
while((link = strstr(mainResponse, "href=\"")) != NULL){
int linkLength = strlen(link);
int beginPtr = 6; //length of href="
for(; beginPtr <= linkLength && link[beginPtr] != '\"'; beginPtr++);
link2 = strndup(link+6, beginPtr-6);
HTTP_REQUEST httpLinkPrefetch;
bzero(&httpLinkPrefetch, sizeof(httpLinkPrefetch));
httpLinkPrefetch.HTTP_COMMAND = "GET";
httpLinkPrefetch.HTTP_VERSION = "HTTP/1.1";
linkPrefetchData(mainPage, link2, &httpLinkPrefetch.COMPLETE_PATH);
httpLinkPrefetch.HTTP_REQ_URL = calloc(1, sizeof(URL));
parseURL(-5, httpLinkPrefetch.COMPLETE_PATH, httpLinkPrefetch.HTTP_REQ_URL);
int serversockfd, responseLen;
char *responseBuff;
if(fetchResponse(&serversockfd, &httpLinkPrefetch, &responseBuff, &responseLen, -1) < 0)
continue;
//free all buffers
free(link2);
if(httpLinkPrefetch.COMPLETE_PATH != NULL)
free(httpLinkPrefetch.COMPLETE_PATH);
clearURLStruct(httpLinkPrefetch.HTTP_REQ_URL);
free(httpLinkPrefetch.HTTP_REQ_URL);
if(beginPtr + 1 < linkLength)
mainResponse = link + beginPtr + 1;
else
break;
}//end of while
return 0;
}
//-----------------------------------------MAIN-------------------------------------
//Reference: https://techoverflow.net/2013/04/05/how-to-use-mkdir-from-sysstat-h/
//Reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ms740496(v=vs.85).aspx
//Reference: http://beej.us/guide/bgnet/
int main(int argc, char* argv[]){
struct sockaddr_in serverAddress;
struct sockaddr_in clientAddress;
int clientLength, clientSock, serverSock;
bzero(&serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(atoi(argv[1]));
serverAddress.sin_addr.s_addr = INADDR_ANY;
mkdir(CACHEDIR, S_IRWXU);
//Usage rules
if(argc < 2){
printf("Usage: ./proxyserver <PORT NUMBER> [<CACHE TIMEOUT VALUE>]\n");
exit(1);
}
//Cache timeout settings
if(argc < 3)
cacheTimeout = DEFAULT_CACHE_TIMEOUT;
else
cacheTimeout = atoi(argv[2]);
printf("Cache timeout value: %lu\n", cacheTimeout);
//create socket, bind() and listen()
proxySocket = socket(PF_INET, SOCK_STREAM, 0);
if(bind(proxySocket, (struct sockaddr*)&serverAddress, (socklen_t)sizeof(serverAddress)) < 0){
perror("Error in bind()");
exit(1);
}
if(listen(proxySocket, MAXCONN) < 0){
perror("Error in listen()");
exit(1);
}
while(1){
//start accepting connections through proxy
clientSock = accept(proxySocket, (struct sockaddr*) &clientAddress,(socklen_t*) &clientLength);
//fork() for multiiple connections
if(fork() == 0){
char* requestBuffer;
int recvBytes;
//receive
recvBytes = receiveData(clientSock, &requestBuffer);
if(recvBytes <= 0){
perror("Error in recv()");
close(clientSock);
exit(0);
}
//create a HTTP Request struct
HTTP_REQUEST httprequest;
bzero(&httprequest, sizeof(httprequest));
if(parseHTTPRequest(clientSock, requestBuffer, recvBytes, &httprequest) < 0){
perror("Error in parseHTTPRequest()");
internalError(clientSock, "Unable to parse HTTP Request");
close(clientSock);
exit(0);
}
//create a response
if(!otherRequestErrors(clientSock, httprequest)){
char* otherResponse;
int otherResponseLength;
if(fetchResponse(&serverSock, &httprequest, &otherResponse, &otherResponseLength, clientSock) < 0){
cleanHTTPStructure(&httprequest);
close(clientSock);
exit(0);
}
//send response
if(send(clientSock, otherResponse, otherResponseLength, 0) < 0)
perror("Error in send()");
close(clientSock);
//link prefetch (extra credit)
debug = 1;
linkPrefetch(httprequest, otherResponse);
exit(0);
}
//clean up
else{
cleanHTTPStructure(&httprequest);
close(clientSock);
exit(0);
}
}
close(clientSock);
}
close(proxySocket);
} | 5a0766f1949493da094d12d72db49e9131280147 | [
"Text",
"C",
"Makefile"
] | 3 | Makefile | ChaitraRp/ProxyServer | 5cfc758f5618ebb290e0911ef5f2ffff52157667 | 4520469d1d11f732fa3d64c93dbf93bc867588eb |
refs/heads/master | <repo_name>kaush4l/ReactJS<file_sep>/src/Components/Projects.js
import React, { Component } from 'react';
export class Projects extends Component {
render() {
return (
<div className="w3-padding w3-white">
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
September 2018
</div>
<div className="w3-title w3-right w3-large">Resume Website</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Developer</div>
<div className="w3-serif w3-large">
<i>The resume was developed using ReactJS. Added state management and sharing data between
components. More features will be added as the learning progresses.<br />
<b>Link to the project https://kaush4l.github.io/ReactJS/.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
June 2018
</div>
<div className="w3-title w3-right w3-large">Indigo Application</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Lead developer</div>
<div className="w3-serif w3-large">
<i>Started a full stack application using Spring Boot, ReactJS, MongoDB, Axios, and REST Services.
The application is a basic application which takes date from REST services and stores them in the
database using the controller. The application uses all the latest technologies to keep the structure
up to date. The project will can be moulded basing on the ideas acquired.<br />
<b>Link to the project https://github.com/kaush4l/Indigo.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
July 2017
</div>
<div className="w3-title w3-right w3-large">Angular 4</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Developer</div>
<div className="w3-serif w3-large">
<i>Created a basic resume wesite using Angular 4. This was created to keep ahead
with the latest technology and learn about features of the new framework.
Many features have been impleneted and more yet to learn.<br />
<b>Link to the project: https://github.com/kaush4l/webPage.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
May 2017
</div>
<div className="w3-title w3-right w3-large">CagedSpace</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Developer</div>
<div className="w3-serif w3-large">
<i>CagedSpace was project developed for the museums of Charlotte. The goal was to implement a location
based Bluetooth tracker which can play the appropriate audio files based on the location of the person.
The intensity and sound for these files are calculated and put on server for appropriate playback.
The project used Angular2, Firebase, OAuth, and AWS for hosting of the project. After compleating, the
project was handover and code base has been locked.
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
Feburary 2017
</div>
<div className="w3-title w3-right w3-large">Complaint portal</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Developer</div>
<div className="w3-serif w3-large">
<i>Complaint portal is website which stores the complaint of the users while also displaying the
status of the complaint. This give users the power to track and update the new or existing complaints.
The website was secured using JSTL tags and was prone to basic attacks. The user accounts were safe guarded
using SALTING and HASHING. Security features were implemented and updated to keep the website safe.<br />
<b>Link to the project: https://github.com/kaush4l/Complaint-portal.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
December 2016
</div>
<div className="w3-title w3-right w3-large">Movie Recommender</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Hadoop developer</div>
<div className="w3-serif w3-large">
<i>A movie recommender system was written in Hadoop Mapreduce framework using the publicly
available movie lens dataset. This would use a tweaked version of Jaccard coefficiency to find
the user-user similarity and then suggest movie based on the most similar user. The project was
written in Hadoop MapReduce(Java) and Apache Spark(Python). <br />
<b>Link to the project: https://github.com/kaush4l/MovieLens-Movie-Recommander-system.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
September 2016
</div>
<div className="w3-title w3-right w3-large">PageRank</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Hadoop developer</div>
<div className="w3-serif w3-large">
<i>PageRank is hadoop project which calculates the pageRank of hyperlinked wiki pages.
The algorithm runs untill it get to the saturation point and displays the page ranks of the links.
The program was written using Hadoop MapReduce and Apache Spark(Python). The perfomance of both the
programs was comapred and an effective was calculated for the algorithm.<br />
<b>Link to the project: https://github.com/kaush4l/PageRank.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
May 2016
</div>
<div className="w3-title w3-right w3-large">LZW Compression</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Developer</div>
<div className="w3-serif w3-large">
<i>LZW is compression algorithm which compresses any dataset without any prior knowledge on the
dataset. The sample dataset achieved a compression ratio of 0.38. The higher the redundancy, the
higher the ratio. Using this algorithm we can compress any given data to get compressed files.<br />
<b>Link to the project: https://github.com/kaush4l/LZW-Compression.</b>
</i>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-container w3-third w3-padding">
<div className="w3-title w3-display-bottom w3-xlarge">
May 2016
</div>
<div className="w3-title w3-right w3-large">Android Applications</div>
</div>
<div className="w3-rest">
<div className="w3-xxlarge">Android Developer</div>
<div className="w3-serif w3-large">
<i>Mobile Application development has helped me learn build Android application and deploy them.
Many hybrid applications were also built using Framework 7, Cordova and Ionic. These application
were developed for Android, iOs and Windows simultaneously. Many applications were developed through
out the course which hepled in gaining good grip on the subject. Applications were also developed
to use technologies like FireBase developer API's.
</i>
</div>
</div>
</div>
</div>
);
}
}
<file_sep>/src/App.js
import React, { Component } from 'react';
import { Menu } from './Components/Menu';
import { Header } from './Components/Header';
import { ComponentController } from './Components/ComponentController';
import { Footer } from './Components/Footer';
import './App.css';
//The entry point to the application
class App extends Component {
// For the main class control the state of the children
constructor(props){
super(props);
this.state = {
clicked : "" // The default page to display
}
}
handleOptionsClick(i){
this.setState({
clicked: i
})
}
renderMenuItems(){
const menuItems = ["Dashboard","Education","Experience", "Projects"];
return (<>{menuItems.map((item) => <Menu value={item} key={item} onClick={() => this.handleOptionsClick(item)}/>)}</>)
}
render() {
return (
<div className="w3-light-grey">
<div className="Header">
<Header />
</div>
<div className="w3-container">
<div className="w3-quarter">
{this.renderMenuItems()}
</div>
<div className="w3-twothird">
<ComponentController value={this.state.clicked} />
</div>
</div>
<Footer />
</div>
);
}
}
export default App;
<file_sep>/src/Components/ComponentController.js
import React, { Component } from 'react';
import { Dashboard } from './Dashboard';
import { Education } from './Education';
import { Experience } from './Experience';
import { Projects } from './Projects';
import { Markdown } from './Markdown';
export class ComponentController extends Component {
render() {
const compSelected = this.props.value;
switch(compSelected){
case "Education":
return <Education />;
case "Experience":
return <Experience />;
case "Projects":
return <Projects />;
case "Markdown":
return <Markdown />
default:
return <Dashboard />;
}
}
}
<file_sep>/src/Components/Footer.js
import React, { Component } from 'react';
export class Footer extends Component {
render() {
return (
<div className="w3-display-container w3-padding w3-center w3-white w3-row">
<div className="w3-half w3-xxlarge w3-row">
<a href="https://www.facebook.com/kaush4l" ><i className="fa fa-facebook-square"/></a>
<a href="https://www.linkedin.com/in/kaush4l/"><i className="fa fa-linkedin-square"/></a>
<a href="https://www.instagram.com/kaush4l/"><i className="fa fa-instagram"/></a>
<a href="https://github.com/kaush4l"><i className="fa fa-git-square"/></a>
<a href="https://plus.google.com/118384595746583517041"><i className="fa fa-google-plus"/></a>
</div>
<div className="w3-third">
<div className="w3-xlarge w3-serif">Designed and developed by <NAME></div>
<div className="w3-small">Made using ReactJS and W3CSS</div>
</div>
</div>
);
}
}
<file_sep>/src/Components/Markdown.js
import React, { Component } from 'react';
import ReactMarkdown from 'react-markdown';
import mark from './MdFiles/Markdown.md';
export class Markdown extends Component {
constructor(props) {
super(props);
this.state = { markdown: null }
}
componentDidMount() {
fetch(mark).then((response) => response.text()).then((text) => this.setState({markdown: text}))
}
render() {
return (
<div className="w3-display-container w3-padding">
<ReactMarkdown source={this.state.markdown} transformImageUri={uri =>
`github.com/kaush4l/ReactJS/tree/master${uri}`} />
{/* renderers = {{ heading : P }} /> */}
</div>
);
}
}
<file_sep>/README.md
# Instructions to update the resume
## Update the dependencies
If the app fails to start it can be because of issues in the dependencies
* To update the dependencies run
~~~
npm aduit
npm audit fix --force
~~~
## Commands to host
Hosting ReactJS on github is done using gh-pages. All the changes are pushed to the branch called gh-pages and hosted from the branch.
Commands to push to gh-pages
~~~
npm run deploy // pushes changes to the gh-pages branch and hosts it from there
~~~
For any doubts [refer](https://medium.com/the-andela-way/how-to-deploy-your-react-application-to-github-pages-in-less-than-5-minutes-8c5f665a2d2a)
## TODO list
### Immediate
* A Home page with a theme or a gif picture like [this](https://christopher.su/)
* Update the experiences and projects(UI and content)
### Overkill
* Try moving the content to some cloud services so that I can just update there and page loads the data
* Try adding all the side projects so that they are easily accessible
* Make a generic theme and also try to host any material so that it can be shared
<file_sep>/src/Components/Header.js
import React, { Component } from 'react';
import logo from './logo.jpg';
import pdf from './Kaushal-Latest.pdf';
export class Header extends Component {
render() {
return (
<div className="w3-light-grey">
<header className="App-header w3-padding w3-row-padding">
<div className="w3-container">
<div className="w3-third w3-xxlarge">
<a href={pdf} target="_blank" rel="noopener noreferrer"><i className="fa fa-navicon"/></a>
</div>
{/* <div className="w3-half w3-hide-medium w3-xxlarge">
<a href="https://github.com/kaush4l?tab=repositories"><i className="fa fa-github w3-right">GitHub</i></a>
</div> */}
<div className="w3-right w3-hide-small">
<a href="https://www.linkedin.com/in/kaush4l/">
<img src={logo} alt={logo} className="w3-circle App-logo"/>
</a>
{/* <p className="w3-right w3-margin"><NAME></p></a> */}
</div>
</div>
<div className="clearFix"/>
</header>
</div>
);
}
}
<file_sep>/src/Components/Education.js
import React, { Component } from 'react';
import './Education.css';
export class Education extends Component {
render() {
return (
<div className="w3-display-container w3-padding w3-white">
<div className="w3-row w3-card">
<div className="w3-third w3-display-container">
<img className="w3-hover-opacity KeyboardLogo" src={require('./uncc.jpg')} alt="UNCC" />
<div className="w3-title">
<div className="w3-display-bottom w3-xxlarge">
2016-2017
</div>
<div className="w3-right">UNC Charlotte</div>
</div>
</div>
<div className="w3-twothird">
<div className="w3-xlarge w3-padding">
Master's of Computer Science
</div>
<div className="w3-padding">
The master's program has given me the opportunity to test my skills and apply
practical knowledge. I did various projects which helped me understand the programming
in a new perspective. I learned many new things and technologies. The hands on experience
while working on many projects gave me a chance to challange myself. Subjects like Algorithms
and data structures, Mobile Application development, Cloud Computing and Network based
applications gave working experience on different technologies. Working on various projects
gave me the confidence to understand the probelem and come up with different solutions to tackle it.
<br/><p className="w3-panel w3-sand w3-large w3-round w3-center w3-serif"><i>
Good, better, best. Never let it rest. 'Till your good is better and your better is the best.'</i>
</p>
</div>
</div>
</div>
<div className="w3-row w3-card">
<div className="w3-third w3-display-container">
<img className="w3-hover-opacity KeyboardLogo" src={require('./SRMUniversity.jpg')} alt="SRM" />
<div className="w3-title">
<div className="w3-display-bottom w3-xxlarge">
2011-2015
</div>
<div className="w3-right">SRM University</div>
</div>
</div>
<div className="w3-twothird">
<div className="w3-xlarge w3-padding">
Bachelor's Degree in Information Technology
</div>
<div className="w3-padding">
Learning has always been my interest. But this is the place that my interest turned
towards coding and found passion in doing it. Various courses that I had taken have helped
me lean many new things. Courses like Cryptography zealed my interest in understanding
logics and findings ways of solving problems. The best things I learned was to understand things
quickly. I was exposed to different tasks which helped me in moulding for a fast paced
environment. I leaned many things and have been trying to make myslef even better. Everyday is a
new challenge and a new day to lean things.
<br/><p className="w3-panel w3-sand w3-large w3-round w3-center w3-serif"><i>
I adore the quote "You're given only a litte spark of madness. You mustn't lose it." - <NAME>.</i>
</p>
</div>
</div>
</div>
</div>
);
}
}
<file_sep>/src/Components/Certifications.js
import React, { Component } from 'react';
export class Certifications extends Component {
render() {
return (
<div className="w3-display-container">
<img className="w3-hover-opacity KeyboardLogo" src={require('./IBM.png')} alt="cert" />
<div class="w3-display-bottomright w3-container"><p>Curam certification</p></div>
</div>
);
}
}
| c8ee1ee6a58c785912c2fe304b2a6450d6608e45 | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | kaush4l/ReactJS | f5c3bc704ef0fc0b1de65e1b02c9c66fa79bc9c3 | cfa95751814cf4cd24a5fb580adb9278fea5edfc |
refs/heads/main | <file_sep>package com.nagwa.listing.data.remote
import com.nagwa.listing.data.model.GetListOfFilesResponse
import io.reactivex.Observable
interface GetListOfFilesRemoteDataSource {
fun getListOfFiles(): Observable<List<GetListOfFilesResponse>>
}<file_sep>package com.nagwa.listing.data.remote
import com.nagwa.listing.data.model.GetListOfFilesResponse
import io.reactivex.Observable
import io.reactivex.Observer
import javax.inject.Inject
class GetListOfFilesRemoteDataSourceImpl @Inject constructor(private val service: GetListOfFilesService) :
GetListOfFilesRemoteDataSource {
override fun getListOfFiles(): Observable<List<GetListOfFilesResponse>> {
return service.getListOfFiles()
}
}<file_sep>package com.nagwa.listing.di
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
object NetworkModule {
@Provides
@Singleton
fun provideGson(): Gson {
val gsonBuilder = GsonBuilder()
return gsonBuilder.create()
}
@Provides
@Singleton
fun provideHttpClient(): OkHttpClient {
return OkHttpClient.Builder().build()
}
@Provides
@Singleton
fun provideRetrofit(gson: Gson, okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl("https://nagwa.free.beeceptor.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
}
}<file_sep>package com.nagwa.listing.data.remote
import com.nagwa.listing.data.model.GetListOfFilesResponse
import io.reactivex.Observable
import io.reactivex.Observer
import retrofit2.http.GET
interface GetListOfFilesService {
@GET("movies")
fun getListOfFiles(): Observable<List<GetListOfFilesResponse>>
}<file_sep>package com.nagwa.listing.presentation.view.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import java.util.*
import kotlin.collections.ArrayList
abstract class BaseRecyclerViewAdapter<T, V : BaseRecyclerViewAdapter.BaseRecyclerViewHolder<T>>() :
RecyclerView.Adapter<BaseRecyclerViewAdapter.BaseRecyclerViewHolder<T>>() {
private var mData: ArrayList<T>? = null
init {
this.mData = ArrayList<T>()
}
constructor(mData: ArrayList<T>, mLocale: Locale) : this() {
this.mData = ArrayList<T>()
addItems(mData)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseRecyclerViewHolder<T> {
val view: View = LayoutInflater.from(parent.context)
.inflate(getLayout(viewType), parent, false)
return getViewHolder(view, viewType)
}
override fun getItemViewType(position: Int): Int {
return super.getItemViewType(position)
}
override fun onBindViewHolder(holder: BaseRecyclerViewHolder<T>, position: Int) {
mData?.get(position)?.let { holder.onBind(it) }
// or make in bind take any not T
}
override fun getItemCount(): Int {
return mData?.size!!
}
protected abstract fun getLayout(type: Int): Int
protected abstract fun getViewHolder(view: View, type: Int): V
fun addItems(items: List<T>?) {
if (items != null) {
mData?.addAll(items)
}
notifyDataSetChanged()
}
fun setItems(items: List<T>?) {
mData!!.clear()
mData!!.addAll(items!!)
notifyDataSetChanged()
}
fun addItem(item: T) {
mData!!.add(item)
notifyDataSetChanged()
}
fun deleteItem(position: Int) {
mData!!.removeAt(position)
notifyDataSetChanged()
}
fun clearItems() {
mData!!.clear()
notifyDataSetChanged()
}
fun getData(): ArrayList<T>? {
return mData
}
abstract class BaseRecyclerViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun onBind(item: T)
}
}<file_sep>package com.nagwa.listing.di
import com.nagwa.listing.data.remote.GetListOfFilesRemoteDataSource
import com.nagwa.listing.data.remote.GetListOfFilesRemoteDataSourceImpl
import com.nagwa.listing.data.repository.GetListOfFilesRepositoryImpl
import com.nagwa.listing.domain.repository.GetListOfFilesRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
@InstallIn(ViewModelComponent::class)
@Module
abstract class GetFilesModule {
@Binds
abstract fun provideRepository(repository: GetListOfFilesRepositoryImpl): GetListOfFilesRepository
@Binds
abstract fun provideRemoteDataSourceModel(
remoteDataSource: GetListOfFilesRemoteDataSourceImpl
): GetListOfFilesRemoteDataSource
}<file_sep>package com.nagwa.listing.domain.usecase
import com.nagwa.listing.data.model.GetListOfFilesResponse
import com.nagwa.listing.domain.repository.GetListOfFilesRepository
import dagger.hilt.android.scopes.ViewModelScoped
import io.reactivex.Observable
import javax.inject.Inject
@ViewModelScoped
class GetListOfFilesUseCase @Inject constructor(private val repository: GetListOfFilesRepository) :
SuspendableUseCase<Unit, Observable<List<GetListOfFilesResponse>>> {
override fun execute(input: Unit?): Observable<List<GetListOfFilesResponse>> {
return repository.getListOfFiles()
}
}<file_sep>package com.nagwa.listing.data.repository
import com.nagwa.listing.data.model.GetListOfFilesResponse
import com.nagwa.listing.data.remote.GetListOfFilesRemoteDataSource
import com.nagwa.listing.domain.repository.GetListOfFilesRepository
import io.reactivex.Observable
import io.reactivex.Observer
import javax.inject.Inject
class GetListOfFilesRepositoryImpl @Inject constructor(private val remoteDataSource: GetListOfFilesRemoteDataSource) :
GetListOfFilesRepository {
override fun getListOfFiles(): Observable<List<GetListOfFilesResponse>> {
return remoteDataSource.getListOfFiles()
}
}<file_sep>package com.nagwa.listing.presentation.viewmodel
import androidx.lifecycle.ViewModel
import com.nagwa.listing.data.model.GetListOfFilesResponse
import com.nagwa.listing.domain.usecase.GetListOfFilesUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.BehaviorSubject
import javax.inject.Inject
@HiltViewModel
class GetListOfFilesViewModel @Inject constructor(private val useCase: GetListOfFilesUseCase) :
ViewModel() {
private var data: BehaviorSubject<List<GetListOfFilesResponse>> = BehaviorSubject.create()
private var mLoadingSubject: BehaviorSubject<Boolean> = BehaviorSubject.createDefault(false)
private var mCompositeDisposable: CompositeDisposable? = CompositeDisposable()
fun getListOfFiles() {
mLoadingSubject.onNext(true)
addDisposable(
useCase.execute()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.doFinally { mLoadingSubject.onNext(false) }
.subscribe {
data.onNext(it)
}
)
}
fun getData() = data
fun getLoadingSubject(): BehaviorSubject<Boolean> {
return mLoadingSubject
}
private fun addDisposable(disposable: Disposable?) {
check(!(disposable == null && mCompositeDisposable == null)) { " Disposable must be initialized" }
mCompositeDisposable?.add(disposable!!)
}
private fun disposeDisposable() {
if (mCompositeDisposable != null) {
mCompositeDisposable!!.dispose()
}
}
override fun onCleared() {
mLoadingSubject.onComplete()
data.onComplete()
disposeDisposable()
super.onCleared()
}
}<file_sep>package com.nagwa.listing.di
import com.nagwa.listing.data.remote.GetListOfFilesService
import com.nagwa.listing.presentation.view.adapter.GetListOfFilesAdapter
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import retrofit2.Retrofit
import javax.inject.Singleton
@InstallIn(ViewModelComponent::class)
@Module
class APIModule {
@Provides
fun provideApi(retrofit: Retrofit): GetListOfFilesService {
return retrofit.create(GetListOfFilesService::class.java)
}
@Provides
@Singleton
fun provideAdapter(): GetListOfFilesAdapter {
return GetListOfFilesAdapter()
}
}<file_sep>package com.nagwa.listing.data.model
import android.graphics.Bitmap
data class GetListOfFilesResponse(
val id: Int,
val type: String,
val url: String,
val name: String,
)<file_sep>package com.nagwa.listing.domain.repository
import com.nagwa.listing.data.model.GetListOfFilesResponse
import io.reactivex.Observable
import io.reactivex.Observer
interface GetListOfFilesRepository {
fun getListOfFiles(): Observable<List<GetListOfFilesResponse>>
}<file_sep>package com.nagwa.listing.presentation.view.activity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.nagwa.listing.R
import com.nagwa.listing.data.model.GetListOfFilesResponse
import com.nagwa.listing.presentation.view.adapter.GetListOfFilesAdapter
import com.nagwa.listing.presentation.viewmodel.GetListOfFilesViewModel
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_main.*
import javax.inject.Inject
@AndroidEntryPoint
class GetListOfFilesActivity : AppCompatActivity() {
@Inject
lateinit var adapter: GetListOfFilesAdapter
private val TAG = "GetListOfFilesActivity"
private val viewModel: GetListOfFilesViewModel by viewModels()
private var mCompositeDisposable: CompositeDisposable? = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initRecyclerView()
viewModel.getListOfFiles()
bindScreenData()
bindLoading()
}
private fun bindLoading() {
addDisposable(
viewModel.getLoadingSubject()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::loadingStatus)
)
}
private fun loadingStatus(status: Boolean) {
progressBar.visibility = if (status) View.VISIBLE else View.GONE
}
private fun bindScreenData() {
addDisposable(
viewModel.getData()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::updateUI)
)
}
private fun updateUI(data: List<GetListOfFilesResponse>) {
Log.d(TAG, "updateUI: $data")
adapter.setItems(data)
}
private fun initRecyclerView() {
recyclerView.adapter = adapter
}
private fun addDisposable(disposable: Disposable?) {
check(!(disposable == null && mCompositeDisposable == null)) { " Disposable must be initialized" }
mCompositeDisposable?.add(disposable!!)
}
private fun disposeDisposable() {
if (mCompositeDisposable != null) {
mCompositeDisposable!!.dispose()
}
}
override fun onDestroy() {
disposeDisposable()
super.onDestroy()
}
}<file_sep>package com.nagwa.listing.domain.usecase
interface SuspendableUseCase<I,O> {
fun execute(input: I?= null): O
}<file_sep>package com.nagwa.listing.presentation.view.adapter
import android.os.Handler
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.view.isVisible
import com.nagwa.listing.R
import com.nagwa.listing.data.model.GetListOfFilesResponse
import kotlinx.android.synthetic.main.item_pdf.view.*
import kotlinx.android.synthetic.main.item_vedio.view.*
import javax.inject.Inject
import kotlin.random.Random
class GetListOfFilesAdapter @Inject constructor() :
BaseRecyclerViewAdapter<GetListOfFilesResponse, BaseRecyclerViewAdapter.BaseRecyclerViewHolder<GetListOfFilesResponse>>(
) {
enum class Types {
PDF, VIDEO
}
enum class TypesValues(name: String) {
VIDEO("VIDEO")
}
override fun getItemViewType(position: Int): Int {
return if (getData()?.get(position)?.type == TypesValues.VIDEO.name) {
Types.VIDEO.ordinal
} else {
Types.PDF.ordinal
}
}
override fun getLayout(type: Int): Int {
return when (type) {
Types.PDF.ordinal -> R.layout.item_pdf
Types.VIDEO.ordinal -> R.layout.item_vedio
else -> R.layout.item_pdf
}
}
override fun getViewHolder(
view: View,
type: Int
): BaseRecyclerViewHolder<GetListOfFilesResponse> {
return when (type) {
Types.PDF.ordinal -> ListPdfViewHolder(view)
Types.VIDEO.ordinal -> ListVideoViewHolder(view)
else -> ListPdfViewHolder(view)
}
}
inner class ListPdfViewHolder(itemView: View) :
BaseRecyclerViewAdapter.BaseRecyclerViewHolder<GetListOfFilesResponse>(itemView) {
override fun onBind(item: GetListOfFilesResponse) {
itemView.pdfTitle.text = item.name
itemView.downloadPdf.setOnClickListener {
startDownload(itemView.pdf_progress_bar, itemView.pdfPercentage)
itemView.downloadPdf.isEnabled = false
}
}
}
inner class ListVideoViewHolder(itemView: View) :
BaseRecyclerViewAdapter.BaseRecyclerViewHolder<GetListOfFilesResponse>(itemView) {
override fun onBind(item: GetListOfFilesResponse) {
var position = 0
itemView.videoTitle.text = item.name
itemView.downloadVideo.setOnClickListener {
startDownload(itemView.video_progress_bar, itemView.videoPercentage)
itemView.downloadVideo.isEnabled = false
}
itemView.videoView.setOnClickListener {
if (itemView.videoView.isPlaying) {
position = itemView.videoView.currentPosition
itemView.videoView.pause()
} else if (!itemView.videoView.isPlaying && !itemView.playVideo.isVisible) {
itemView.videoView.seekTo(position)
itemView.videoView.start()
}
}
itemView.playVideo.setOnClickListener {
itemView.videoView.setVideoPath(item.url)
itemView.videoView.start()
itemView.playVideo.visibility = View.GONE
}
itemView.videoView.setOnCompletionListener {
itemView.playVideo.visibility = View.VISIBLE
}
}
}
private fun startDownload(progressBar: ProgressBar, textView: TextView) {
progressBar.visibility = View.VISIBLE
var progressStatus = 0
val handler = Handler()
progressBar.progress = 0
val filesToDownload = Random.nextInt(10, 200)
progressBar.max = filesToDownload
Thread {
while (progressStatus < filesToDownload) {
progressStatus += 1
Thread.sleep(50)
handler.post {
progressBar.progress = progressStatus
val percentage = ((progressStatus.toDouble()
/ filesToDownload) * 100).toInt()
textView.text = "Downloaded $percentage%"
}
}
}.start()
}
} | 149e163f2d724affb69745c0e355885fd34c7f4f | [
"Kotlin"
] | 15 | Kotlin | gomaa92/Listing | 32ad7ba02d10372c73b416600082ec3f52b2abee | 6b6ee4bc209acb0e51d30ee8ddb334cbccf04fb9 |
refs/heads/master | <repo_name>hennotto/youtube-dl<file_sep>/youtube_dl/version.py
__version__ = '2014.05.05'
| 9fca7467e2efcb55016169b19e11896e0183ff69 | [
"Python"
] | 1 | Python | hennotto/youtube-dl | e399853d0c5784257ffcb6fba147d0b47d3f9bb6 | 67fe8be77b6c002dae4a7c42536aea9679d7a525 |
refs/heads/master | <file_sep><?php
header( 'Location: /index.html' ) ;
/*require 'aws.phar';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = getenv('S3_BUCKET_NAME');
$keyname = 'game.js';
//Instantiate the client
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-2'
]);
try {
// Get the object
$gameText = $s3->getObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
));
$game="game.js";
file_put_contents($game, $gameText['Body']);
chmod($game, 0600);
*/
// Run game script
/*} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}*/
?><file_sep>
// create a PlayCanvas application
var canvas = document.getElementById('application');
var app = new pc.Application(canvas, {
keyboard: new pc.Keyboard(window)
});
app.start();
// fill the available space at full resolution
app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW);
app.setCanvasResolution(pc.RESOLUTION_AUTO);
//Set gravity
app.systems.rigidbody.setGravity(0, -9.8, 0);
//Load scripts
document.write('<script src="movement.js"></script>');
// ensure canvas is resized when window changes size
window.addEventListener('resize', function() {
app.resizeCanvas();
});
// create floor entity
var floor = new pc.Entity('floor');
floor.addComponent('model', {
type: 'box'
});
floor.setLocalScale(10,1,10);
floor.addComponent('collision', {
type: "box",
halfExtents: new pc.Vec3(5, 0.5, 5)
});
floor.addComponent('rigidbody', {
type: "static",
restitution: 0.5
});
//create player
var player = new pc.Entity();
player.addComponent('model', {
type: 'box'
});
player.addComponent("rigidbody", {
type: "dynamic",
mass: 1,
restitution: 0.5
});
player.addComponent("collision", {
type: "box",
halfExtents: new pc.Vec3(0.5, 0.5, 0.5)
});
// create camera entity
var camera = new pc.Entity('camera');
camera.addComponent('camera', {
clearColor: new pc.Color(0.1, 0.1, 0.1)
});
// create directional light entity
var light = new pc.Entity('light');
light.addComponent('light');
player.addComponent("script");
player.script.create("movement");
// add to hierarchy
app.root.addChild(floor);
app.root.addChild(player);
app.root.addChild(camera);
app.root.addChild(light);
player.setPosition(0, 0, 0);
// set up initial positions and orientations
floor.setPosition(0, 0, 0);
camera.setPosition(0, 15, 15);
camera.setEulerAngles(-45,0,0);
light.setEulerAngles(-45, 0, 0);
// register a global update event
app.on('update', function (deltaTime) {
});
<file_sep><?php
header('Content-Type: text/javascript');
readfile("../scripts/" . $_GET['script']);
?> | 15221713fabbee11a4a904e8bb787109d9df7369 | [
"JavaScript",
"PHP"
] | 3 | PHP | Askbackwards/PlayCanvasTesting | 1e57b54d6687f1f16ce4da6e209decf50fd7b0d2 | e81234f8c0a41d2b9db61cf7ba9dce50eb8f08d1 |
refs/heads/master | <repo_name>Zrna/react-redux-i18next-template<file_sep>/client/src/components/Navigation/Navigation.js
import React from 'react';
import { BrowserRouter as Router, Route, NavLink, Switch } from 'react-router-dom';
import { withTranslation } from 'react-i18next';
import './Navigation.css';
import HomePage from '../Home/Page';
import Component1 from '../Component1/Component1';
import Component2 from '../Component2/Component2';
import NotFound from '../NotFound/NotFound';
const Navigation = ({ i18n }) => {
const changeLanguage = lng => {
i18n.changeLanguage(lng);
};
return (
<Router>
<>
<NavLink to='/' className='navLink'> Home </NavLink>
<NavLink to='/component1' className='navLink'> Component 1 </NavLink>
<NavLink to='/component2' className='navLink'> Component 2 </NavLink>
<button onClick={() => changeLanguage('en')}>en</button>
<button onClick={() => changeLanguage('de')}>de</button>
<Switch>
<Route exact strict path='/' component={HomePage} />
<Route exact strict path='/component1' component={Component1} />
<Route exact strict path='/component2' component={Component2} />
<Route path='*' component={NotFound} />
</Switch>
</>
</Router>
);
};
export default withTranslation()(Navigation);
<file_sep>/README.md
# <> React Redux Template with i18next </>
## Description
React project template with custom Webpack and ESLint configuration.
Template also include Redux for state management and i18next for internationalization.
**If you don't need internationalization in your project, then check [react-redux-template](https://github.com/Zrna/react-redux-template).**
### Preview

## Installation
1. Download or clone the project
2. Go into the project `cd react-redux-i18next-template`
3. Run `npm install`
4. Run `npm start`
## Project structure
**All of the following scripts are described [here](https://github.com/Zrna/react-redux-i18next-template#scripts)**.
### Root
All the necessary config files are in the root of the project.
### Client
Client folder contains view of the app.
Containers and components examples are in the _client/src_ folder.
After running the `npm run build ` and/or `npm run host` script, a new folder named _dist_ will appear under the _client_ folder -> _client/dist_.
In the _dist_ folder you will have production build of your app.
### State
State folder contains state of the app.
Here are some basic Actions, Reducers and Store examples.
### Server.js
Server.js is used to run the dist folder locally.
## Translations
The project uses [i18next](https://www.i18next.com/) and [react-i18next](https://react.i18next.com/) for internationalization.
The i18next configuration file is located under the src folder -> _client/src/i18n.js_. More about configuration options you can find [here](https://www.i18next.com/overview/configuration-options).
The translation files are in the locales folder -> _client/public/locales_
### Setup
`Navigation.js` (_client/src/components/Navigation/Navigation.js_):
Using `withTranslation` HOC here is set the ability to change the language of the application using buttons.
Other components use `useTranslation` hook for translations.
Example:
import React from 'react';
import { useTranslation } from 'react-i18next';
const Component1 = () => {
const { t } = useTranslation();
return (
<div> {t('component.name1')} </div>
);
};
export default Component1;
`component.name1` is defined in translation.json file.
**en**: client/public/locales/en/translation.json -> `component.name1` = "Component 1"
and
**de**: client/public/locales/de/translation.json -> `component.name1` = "Komponente 1"
## Scripts
**Important!** Some scripts run other scripts so checkout the **package.json** file.
`npm start` - starts the project
`npm run lint` - checks for syntax errors
`npm run lint:fix` - solves syntax errors
`npm run clear:modules` - deletes the node_modules
`npm run build` - creates a dist directory with a production build of your app
`npm run host` - starts production build of your app locally
# Author
[<NAME>](https://github.com/Zrna)
| 74a24f6a69c16fc75774bccf026111c6a78b4190 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Zrna/react-redux-i18next-template | eb83b6cb063e137b31994acb15409013ee2757ee | 581ad4b516fd0dd7e1b6340899346dced3a5d51a |
refs/heads/master | <file_sep>//青蛙跳台阶
//斐波那契数列(0,[1,2,3,5,...])
//从下往上计算,避免重复计算
class Solution {
public:
int jumpFloor(int number) {
if(number <= 2){
return number;
}
int index1 = 1, index2=2;
int result;
for(int i = 3; i <= number; i++){
result = index1 + index2;
index1 = index2;
index2 = result;
}
return result;
}
};<file_sep>// 二维数组中的查找
// 选取数组中右上角的数字
// = x 结束
// > x 去除所在列
// < x 去除所在行
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int row = array.size();
int col = array[0].size();
for(int i = 0, j = col-1; i< row && j>=0;){
if(array[i][j] == target)
{
return true;
}
else if(array[i][j] > target)
{
j--;
}
else
{
i++;
}
}
return false;
}
};
<file_sep>// 变态跳台阶
// 每个台阶都有跳与不跳两种情况(除了最后一个台阶),
// 最后一个台阶必须跳。所以共用2^(n-1)中情况
class Solution {
public:
int jumpFloorII(int number) {
return 1<<(number-1);
}
};<file_sep>// 旋转数组的最小数字
// 结束条件:两指针相邻,且p2指的为最小元素
// 特殊情况:left,mid,high三个位置的元素相同时,采用顺序查找的方法
// 模拟指针移动
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
int low = 0;
int high = rotateArray.size() - 1;
int mid = 0;
while(rotateArray[low] >= rotateArray[high]){
if(low + 1 == high){
mid = high;
break;
}
mid = (low + high)/2;
if((rotateArray[mid] == rotateArray[low]) && (rotateArray[mid] == rotateArray[high]))
return findInOrder(rotateArray, low, high);
if(rotateArray[mid] >= rotateArray[low]){
low = mid;
}
if(rotateArray[mid] <= rotateArray[high]){
high = mid;
}
}
return rotateArray[mid];
}
int findInOrder(vector<int> rotateArray, int low, int high){
int result = rotateArray[low];
for(int i=low+1; i<=high; i++){
if(rotateArray[i] < result){
result = rotateArray[i];
}
}
return result;
}
};
// 二分查找
// 推荐使用非递归的方式,
// 因为递归每次调用递归时有用堆栈保存函数数据和结果。
// 能用循环的尽量不用递归。
//非递归查找
int BinarySearch(int *array, int n, int key)
{
if ( array == NULL || n == 0 )
return -1;
int low = 0;
int high = n - 1;
int mid = 0;
while ( low <= high )
{
mid = (low + high )/2;
if (array[mid] == key){
return mid;
}else if(array[mid] < key){
low = mid + 1;
}else{
high = mid -1;
}
}
return -1;
}
//递归
int BinarySearchRecursive(int *array, int low, int high, int key)
{
if ( low > high )
return -1;
int mid = ( low + high )/2;
if ( array[mid] == key )
return mid;
else if ( array[mid] < key )
return BinarySearchRecursive(array, mid+1, high, key);
else
return BinarySearchRecursive(array, low, mid-1, key);
}
int main(){
// int a[] = {3,4,5,1,2};
int a[] = {1,0,1,1,1};
vector<int> b(&a[0], &a[4]);
// vector<int> num = {2,2,2,2,1,2};
Solution s;
cout<< s.minNumberInRotateArray(b)<<endl;
return 0;
}<file_sep>// 用两个栈实现队列
#include<iostream>
#include<queue>
#include<stack>
#include<cstdlib>
using namespace std;
class Solution0
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int x;
if(stack2.empty()){
while(!stack1.empty()){
int temp = stack1.top();
stack2.push(temp);
stack1.pop();
}
}
x = stack2.top();
stack2.pop();
return x;
}
private:
stack<int> stack1;
stack<int> stack2;
};
// 用两个队列实现栈
// 每次只能从队列的头部删除元素
class Solution1
{
public:
void push(int node) {
queue1.push(node);
}
int pop() {
int x;
if(queue1.empty() && !queue2.empty()){
queue<int> tempQ = queue1;
queue1 = queue2;
queue2 = tempQ;
}
while(queue1.size() > 1){
int temp = queue1.front();
queue2.push(temp);
queue1.pop();
}
x = queue1.front();
queue1.pop();
return x;
}
private:
queue<int> queue1;
queue<int> queue2;
};
int main(){
Solution1 testQueue;
testQueue.push(1);
testQueue.push(2);
testQueue.push(3);
cout<<testQueue.pop()<<endl;
testQueue.push(4);
cout<<testQueue.pop()<<endl;
cout<<testQueue.pop()<<endl;
cout<<testQueue.pop()<<endl;
return 0;
}
<file_sep>// 斐波那契数列
// 从下往上计算,避免重复计算
class Solution {
public:
int Fibonacci(int n) {
if(n<=1){
return n;
}
int index1 = 0, index2=1;
int result;
for(int i = 2; i <= n; i++){
result = index1 + index2;
index1 = index2;
index2 = result;
}
return result;
}
};<file_sep>// 二进制中1的个数
// 位运算 &
class Solution {
public:
int NumberOf1(int n) {
int result = 0;
int flag = 1;
while(flag){
if(n&flag){
result++;
}
flag = flag<<1;
}
return result;
}
};
// 最优解
// 把一个整数减去1,再和原整数做与运算,
// 会把该整数最右边一个1变成0.那么一个整数的二进制有多少个1,就可以进行多少次这样的操作
class Solution {
public:
int NumberOf1(int n) {
int result = 0;
while(n){
n = n&(n-1);
result++;
}
return result;
}
};<file_sep>//矩形覆盖
// 与青蛙跳台阶代码相同
class Solution {
public:
int rectCover(int number) {
if(number <= 2){
return number;
}
int index1 = 1, index2=2;
int result;
for(int i = 3; i <= number; i++){
result = index1 + index2;
index1 = index2;
index2 = result;
}
return result;
}
};<file_sep>// 替换空格
// 替换空格
// 统计空格数
// 从后向前移动
// O(n)
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str == NULL || length<=0)
return;
int p1=0, p2=0;
int spaceNum = 0;
int i =0;
while(str[i] != '\0')
{
p1++;
if(str[i] == ' ')
spaceNum++;
i++;
}
p2 = p1 + spaceNum*2;
if(p2 > length)
return;
while(p1 >=0 && p1 <= p2)
{
if(str[p1] == ' '){
str[p2--] = '0';
str[p2--] = '2';
str[p2--] = '%';
}
else{
str[p2--] = str[p1];
}
p1--;
}
}
}; | 57de706a8da158401c80bcc9e0310d6c7a7fcae4 | [
"C++"
] | 9 | C++ | hehuihui1994/Sword2Offer | fc86b8bc8bb53e84a945dbc9d78391021039dc9f | 58a53ae6c8e24d2b41fc5ccd001e1fc66bb531fe |
refs/heads/master | <repo_name>Craituz/examen-POO<file_sep>/Examen2020/Examen2020/contexto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examen2020
{
class contexto : ICalculo_a_cobrar
{
Auto autito;
Camioneta caminetita;
Furgoneta furgoneta;
public void ICalculo_a_cobrar()
{
}
}
}
<file_sep>/Examen2020/Examen2020/Vehiculo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examen2020
{
class Vehiculo
{
public Vehiculo(string marca, string modelo, string año)
{
Marca = marca;
Modelo = modelo;
Año = año;
}
public string Marca { get; set; }
public string Modelo { get; set; }
public string Año { get; set; }
}
}
<file_sep>/Examen2020/Examen2020/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Examen2020;
namespace Examen2020
{
class Program
{
static void Main(string[] args)
{
/* Furgoneta furgoneta;
List<Furgoneta> list = new List<Furgoneta>();
list.Add(new Furgoneta(2,200,45));*/
List<Vehiculo> lista = new List<Vehiculo>();
lista.Add(new Vehiculo("Honda", "Arx2011", "2012"));
lista.Add(new Vehiculo("Honda", "Arx2011", "2012"));
lista.Add(new Vehiculo("Honda", "Arx2011", "2012"));
lista.Add(new Vehiculo("Honda", "Arx2011", "2012"));
foreach (var vehiculo in lista)
{
Console.WriteLine(""+lista);
}
}
}
}
<file_sep>/Examen2020/Examen2020/Furgoneta.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examen2020
{
class Furgoneta : Vehiculo,ICalculo_a_cobrar
{
Vehiculo v;
public Furgoneta(int num_asientos, int precio_Base, int precio_Asiento)
{
this.num_asientos = num_asientos;
this.precio_Base = precio_Base;
this.precio_Asiento = precio_Asiento;
}
public int num_asientos { get; set; }
public int precio_Base { get; set; }
public int precio_Asiento { get; set; }
public void ICalculo_a_cobrar()
{
int precio = precio_Asiento * num_asientos;
int resultado = precio + precio_Base;
Console.WriteLine("El valor a cobrar es:"+resultado);
}
}
}
<file_sep>/Examen2020/Examen2020/Auto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examen2020
{
class Auto: Vehiculo,ICalculo_a_cobrar
{
public int precioVehiculo { get; set; }
public void ICalculo_a_cobrar()
{
if (this.Modelo == "Sedan")
Console.WriteLine("valor a cobrar:" + precioVehiculo);
else
if (this.Modelo == "Hatchback")
Console.WriteLine("valor a cobrar:" + precioVehiculo * 0.10);
}
}
}
<file_sep>/Examen2020/Examen2020/Camioneta.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Examen2020
{
class Camioneta: Vehiculo,ICalculo_a_cobrar
{
public string TipoCabina { get; set; }
public void ICalculo_a_cobrar()
{
int cobro = 20000;
int cobros = 15000;
if (this.TipoCabina=="Cabina Doble")
Console.WriteLine("El valor a cobrar es:"+cobro);
else
if (this.TipoCabina == "Cabina Simple")
Console.WriteLine("El valor a cobrar es:"+cobros);
}
}
}
| 4a3f04a6a0f428c86976ac527291100e9c3ce3e8 | [
"C#"
] | 6 | C# | Craituz/examen-POO | 977c1dfecddeb7eaaf7434178808ec63d057750b | 2b96946e4a9fcf51f732590f142a9aba81ad4a2d |
refs/heads/master | <repo_name>jeandaisy/Boggle<file_sep>/src/Boggle.h
// This is a .h file you will edit and turn in.
// We have provided a skeleton for you,
// but you must finish it as described in the spec.
// Also remove these comments here and add your own.
// TODO: remove this comment header
#ifndef _boggle_h
#define _boggle_h
#include <iostream>
#include <string>
#include "lexicon.h"
#include "grid.h"
using namespace std;
class Boggle {
public:
Boggle(Lexicon& dictionary, string boardText = "");
char getLetter(int row, int col);
bool checkWord(string word);
bool humanWordSearch(string word);
bool humanWordSearchHelper(string word, Grid<bool> mark, int row, int col);
Set<string> computerWordSearch();
int getScoreHuman();
int getScoreComputer();
void human_scored(string word);
void print_board();
void human_turn();
void print_human_dict();
void print_machine_dict();
void gui_human_summary();
void computerWordSearchHelper(int row, int col,string s,Grid<bool> mark);
void gui_computer_summary();
void set_board(string letters16);
// TODO: add any other member functions/variables necessary
friend ostream& operator<<(ostream& out, Boggle& boggle);
void ramdomBoard();
private:
// TODO: add any other member functions/variables necessary
Grid<char> board;
Lexicon* dict;
Lexicon* dict_human = new Lexicon;
Lexicon* dict_machine = new Lexicon;
unsigned long human_score = 0;
unsigned long human_count = 0;
unsigned long machine_count = 0;
unsigned long machine_score = 0;
};
#endif // _boggle_h
<file_sep>/src/boggleplay.cpp
// This is a .cpp file you will edit and turn in.
// We have provided a skeleton for you,
// but you must finish it as described in the spec.
// Also remove these comments here and add your own.
// TODO: remove this comment header
#include "lexicon.h"
#include "Boggle.h"
#include "shuffle.h"
#include "simpio.h"
#include "bogglegui.h"
void playOneGame(Lexicon& dictionary) {
// TODO: implement
Boggle B(dictionary,"");
bool random = getYesOrNo("Do you want to generate a random board? ");
if(random){
B.ramdomBoard();
}else{
while(1){
cout<<"Type the 16 letters to appear on the board: ";
string board_letters;
getline(cin, board_letters);
if(board_letters.length()!=16){
cout<<"That is not a valid 16-letter board string. Try again."<<endl;
continue;
}
for(int i = 0; i < 16; i++){
if(!isalpha(board_letters[i])){
cout<<"That is not a valid 16-letter board string. Try again."<<endl;
continue;
}
}
B.set_board(board_letters);
break;
}
}
/*
// for testing purpose
string test_case1 = "WLWAOKSEMONAUETA";
string test_case2 = "OUVOOOZEDHHEJDKT";
B.set_board(test_case2);
*/
B.human_turn();
B.computerWordSearch();
B.gui_computer_summary();
if(B.getScoreComputer()>B.getScoreHuman()){
cout<<"Ha ha ha, I destroyed you. Better luck next time, puny human!"<<endl;
BoggleGUI::playSound("./../res/thats-pathetic.wav");
}
}
<file_sep>/src/Boggle.cpp
// This is a .cpp file you will edit and turn in.
// We have provided a skeleton for you,
// but you must finish it as described in the spec.
// Also remove these comments here and add your own.
// TODO: remove this comment header
#include "Boggle.h"
#include "bogglegui.h"
#include <shuffle.h>
#include <algorithm>
#include <string>
// letters on all 6 sides of every cube
static string CUBES[16] = {
"AAEEGN", "ABBJOO", "ACHOPS", "AFFKPS",
"AOOTTW", "CIMOTU", "DEILRX", "DELRVY",
"DISTTY", "EEGHNW", "EEINSU", "EHRTVW",
"EIOSST", "ELRTTY", "HIMNQU", "HLNNRZ"
};
// letters on every cube in 5x5 "Big Boggle" version (extension)
static string BIG_BOGGLE_CUBES[25] = {
"AAAFRS", "AAEEEE", "AAFIRS", "ADENNN", "AEEEEM",
"AEEGMU", "AEGMNN", "AFIRSY", "BJKQXZ", "CCNSTW",
"CEIILT", "CEILPT", "CEIPST", "DDLNOR", "DDHNOT",
"DHHLOR", "DHLNOR", "EIIITT", "EMOTTT", "ENSSSU",
"FIPRSY", "GORRVW", "HIPRRY", "NOOTUW", "OOOTTU"
};
const int MIN_BOGGLE_SIZE = 4;
/*In this constructor you initialize your Boggle board to use the given dictionary lexicon to look up words,
* and use the given 16-letter string to initialize the 16 board cubes from top-left to bottom-right.
* if the string is empty, you should generate a random shuffled board. Your method should be case-insensitive,
* it should accept the board text whether it is passed in upper, lower, or mixed case.
*/
void Boggle::ramdomBoard(){
board.resize(MIN_BOGGLE_SIZE,MIN_BOGGLE_SIZE);
int cube_array[16] = {0, 1, 2, 3 ,4, 5, 6, 7, 8, 9, 10, 11,12,13,14,15};
int side_array[6] = {0, 1, 2, 3, 4, 5};
shuffle(cube_array,16);
for(int i = 0; i < 16; i++){
int m = cube_array[i];
string S = CUBES[m];
shuffle(side_array,6);
int side_number = side_array[0];
char letter = S[side_number];
board.set(i/4,i%4, letter);
BoggleGUI::labelCube(i/4,i%4, letter,false);
}
}
Boggle::Boggle(Lexicon& dictionary, string boardText) {
// TODO: implement
// *dict = dictionary;
dict = &dictionary;
BoggleGUI::initialize(MIN_BOGGLE_SIZE,MIN_BOGGLE_SIZE);
}
void Boggle::set_board(string letters16){
board.resize(MIN_BOGGLE_SIZE,MIN_BOGGLE_SIZE);
BoggleGUI::initialize(MIN_BOGGLE_SIZE,MIN_BOGGLE_SIZE);
clearConsole();
for(int i = 0; i<MIN_BOGGLE_SIZE; i++){
for(int j = 0; j < MIN_BOGGLE_SIZE; j++){
int index = MIN_BOGGLE_SIZE*i + j;
board[i][j] = letters16[index];
BoggleGUI::labelCube(i, j, letters16[index], false);
}
}
}
/* In this function you should return the char that is stored in your Boggle board at the given 0-based row
* and column. If the row and/or column are out of bounds, you should throw an int exexception
*/
char Boggle::getLetter(int row, int col) {
// TODO: implement
if( row < 0|| row >= MIN_BOGGLE_SIZE ){
throw(row);
}
if( col < 0 || col >= MIN_BOGGLE_SIZE ){
throw(col);
}
char result = this->board.get(row, col);
return result;
}
/* In this function, you should check whether the given word string is suitable to search for on the board:
* that is, whether it is in the dictionary, long enough to be a valid Boggle word, and hs not already been
* found. You should return a boolean result of true if the word is suitable and otherwise you should return
* false. Your method should be case-insensitive, you should properly verify the word whethere it is passed
* in upper lower, or mixed case
*/
bool Boggle::checkWord(string word) {
transform(word.begin(),word.end(),word.begin(),::tolower);
if(word.length() < 4)
return false;
if(!dict->contains(word))
return false;
if(dict_human->contains(word))
return false;
return true;
}
bool Boggle::humanWordSearchHelper(string word, Grid<bool> mark, int row, int col){
//base case
if(word.empty() ) return true;
if( (row < 0) || (row >= MIN_BOGGLE_SIZE) ) return false;
if( (col < 0) || (col >= MIN_BOGGLE_SIZE) ) return false;
if(tolower(board[row][col]) != tolower(word[0]) || mark[row][col] == true) return false;
else{
mark[row][col] = true;
word = word.erase(0,1);
BoggleGUI::setHighlighted(row,col, true);
if( humanWordSearchHelper(word,mark,row,col+1) ) return true;
if( humanWordSearchHelper(word,mark,row,col-1) ) return true;
if( humanWordSearchHelper(word,mark,row-1,col+1) ) return true;
if( humanWordSearchHelper(word,mark,row-1,col-1) ) return true;
if( humanWordSearchHelper(word,mark,row-1,col) ) return true;
if( humanWordSearchHelper(word,mark,row+1,col-1) ) return true;
if( humanWordSearchHelper(word,mark,row+1,col+1) ) return true;
if( humanWordSearchHelper(word,mark,row+1,col) ) return true;
}
BoggleGUI::setHighlighted(row,col, false);
return false;
}
bool Boggle::humanWordSearch(string word) {
// TODO: implement
transform(word.begin(),word.end(),word.begin(),::tolower);
Grid<bool> mark = Grid<bool>(4,4,false);
string w = word;
for(int i = 0; i < MIN_BOGGLE_SIZE;i++){
for(int m = 0; m < MIN_BOGGLE_SIZE; m++){
if(humanWordSearchHelper(w,mark,i,m)) return true;
}
}
return false;
}
void Boggle::print_board(){
int counter = 0;
for(auto i:board){
cout<<i;
counter++;
if(counter%4==0)cout<<endl;
}
}
void Boggle::print_human_dict(){
Lexicon::iterator i;
for(i = (*dict_human).begin();i!=(*dict_human).end();i++){
if(i!=(*dict_human).begin()){
cout<<"\", ";
}else{
cout<<"\"";
}
cout<<*i<<"\"";
}
}
void Boggle::gui_human_summary(){
cout << "Your words ("<<human_count<<"): {";
print_human_dict();
cout<<"}"<<endl;
cout << "Your scores : ";
cout << human_score <<endl;
cout <<"Type a word (or Enter to stop): ";
}
void Boggle::human_turn(){
cout<<"It's your turn"<<endl;
gui_human_summary();
string human_input;
while(true){
getline(cin,human_input);
BoggleGUI::clearHighlighting();
if(human_input.empty()) break;
if(!checkWord(human_input)){
BoggleGUI::playSound("./../res/moo.wav");
clearConsole();
cout<<"You must enter an unfound 4+ letter word from the dictionary."<<endl;
print_board();
gui_human_summary();
continue;
}
if(!humanWordSearch(human_input)){
BoggleGUI::playSound("./../res/moo.wav");
clearConsole();
cout<<"That word can't be formed on this board."<<endl;
print_board();
gui_human_summary();
continue;
}
clearConsole();
cout<<"You found a new word! "<<"\""<<human_input<<"\""<<endl;
BoggleGUI::playSound("./../res/tinkerbell.wav");
print_board();
human_scored(human_input);
gui_human_summary();
}
return;
}
void Boggle::human_scored(string word){
if( checkWord(word) && humanWordSearch(word)){
dict_human->add(word);
human_count++;
human_score = human_score + word.length()-3;
}
}
int Boggle::getScoreHuman() {
// TODO: implement
Lexicon::iterator i;
for(i=dict_human->begin();i!=dict_human->end();i++)
human_score = human_score + (*i).length()-3;
return (int) human_score;
}
void Boggle::computerWordSearchHelper(int row, int col, string s, Grid<bool> mark){
//base case
if(!dict->containsPrefix(s)) return;
if( (row < 0) || (row >= MIN_BOGGLE_SIZE) ) return;
if( (col < 0) || (col >= MIN_BOGGLE_SIZE) ) return;
if(s.length() >= 8) return;
if(mark[row][col]==true) return;
s.push_back(board[row][col]);
mark[row][col] = true;
if(dict->contains(s) && (!dict_human->contains(s))
&& (!dict_machine->contains(s)) && s.length() >=4){
dict_machine->add(s);
machine_count++;
}
computerWordSearchHelper(row, col-1,s,mark);
computerWordSearchHelper(row, col+1,s,mark);
computerWordSearchHelper(row-1, col-1,s,mark);
computerWordSearchHelper(row-1, col,s,mark);
computerWordSearchHelper(row-1, col+1,s,mark);
computerWordSearchHelper(row+1, col-1,s,mark);
computerWordSearchHelper(row+1, col,s,mark);
computerWordSearchHelper(row+1, col+1,s,mark);
return;
}
Set<string> Boggle::computerWordSearch() {
// TODO: implement
Set<string> result;
Grid<bool> mark = Grid<bool>(4,4,false);
for(int i = 0; i < MIN_BOGGLE_SIZE;i++){
for(int m = 0; m < MIN_BOGGLE_SIZE; m++){
string w;
computerWordSearchHelper(i,m,w,mark);
}
}
Lexicon::iterator i;
for(i = (*dict_machine).begin();i!=(*dict_machine).end();i++){
result.add(*i);
}
return result;
}
int Boggle::getScoreComputer() {
// TODO: implement
Lexicon::iterator i;
for(i=dict_machine->begin();i!=dict_machine->end();i++)
machine_score = machine_score + (*i).length()-3;
return (int) machine_score;
}
void Boggle::gui_computer_summary(){
cout<<"It's my turn!"<<endl;
Lexicon::iterator i;
cout<<"My words ("<<dict_machine->size()<<"): {";
for(i = dict_machine->begin(); i!=dict_machine->end();i++){
if(i!=dict_machine->begin())cout<<", ";
cout<<"\""<<*i<<"\"";
}
cout<<"}"<<endl;
cout<<"My score: "<<machine_score<<endl;
}
ostream& operator<<(ostream& out, Boggle& boggle) {
// TODO: implement
return out;
}
| bd1ac1bded6549d9d364aca27a86bd26c3612bf1 | [
"C++"
] | 3 | C++ | jeandaisy/Boggle | 126bed55b3374c2eb2826342b3786628998fea53 | 908efc1d465748d350bbc40cabaacd1f7ae55f3f |
refs/heads/master | <repo_name>JacekDuszenko/jackson1337-BTreeServer4MacynaPWR<file_sep>/src/serverModel/Methods.java
package serverModel;
import javafx.scene.text.Text;
import java.util.List;
class Methods<T extends Comparable<T>> {
Methods() {
}
void print(Branch<T> b, StringBuilder main, String tab) {
T[] array = b.values;
main.append(tab);
for (int i = 0; i < b.n ; i++) {
main.append(array[i] + " ");
}
main.append('\n');
for (int i=0; i < b.n + 1;i++) {
String tab2 = tab;
if (b.C[i] != null) {
tab2 = " " + tab2;
print(b.C[i], main, tab2);
}
}
}
Branch search(T v, Branch t) {
int i = 0;
while (i < t.n && less(t.values[i], v)) {
i++;
}
if (i<t.n && eq(t.values[i], v)) {
return t;
}
if (t.leaf) {
return null;
}
return search(v, t.C[i]);
}
void insertNonFull(T v, Branch<T> t) {
// Initialize index as index of rightmost element
int i = t.n - 1;
// If this is a leaf node
if (t.leaf) {
// The following loop does two things
// a) Finds the location of new key to be inserted
// b) Moves all greater keys to one place ahead
while (i >= 0 && less(v, t.values[i])) {
t.values[i + 1] = t.values[i];
i--;
}
// Insert the new key at found location
t.values[i + 1] = v;
t.n++;
} else // If this node is not leaf
{
// Find the child which is going to have the new key
while (i >= 0 && less(v, t.values[i]))
i--;
// See if the found child is full
if (t.C[i + 1].n == 2 * t.t - 1) {
// If the child is full, then split it
splitChild(i + 1, t.C[i + 1], t);
// After split, the middle key of C[i] goes up and
// C[i] is splitted into two. See which of the two
// is going to have the new key
if (less(t.values[i + 1], v))
i++;
}
insertNonFull(v, t.C[i + 1]);
}
}
void splitChild(int i, Branch<T> y, Branch<T> t) {
// Create a new node which is going to store (t-1) keys
// of y
Branch<T> z = new Branch<>(y.t, y.leaf);
z.n = t.t - 1;
// Copy the last (t-1) keys of y to z
for (int j = 0; j < t.t - 1; j++)
z.values[j] = y.values[j + t.t];
// Copy the last t children of y to z
if (!y.leaf) {
for (int j = 0; j < t.t; j++)
z.C[j] = y.C[j + t.t];
}
// Reduce the number of keys in y
y.n = t.t - 1;
// Since this node is going to have a new child,
// create space of new child
for (int j = t.n; j >= i + 1; j--)
t.C[j + 1] = t.C[j];
// Link the new child to this node
t.C[i + 1] = z;
// A key of y will move to this node. Find location of
// new key and move all greater keys one space ahead
for (int j = t.n - 1; j >= i; j--)
t.values[j + 1] = t.values[j];
// Copy the middle key of y to this node
t.values[i] = y.values[t.t - 1];
// Increment count of keys in this node
t.n++;
}
int findValue(T v, Branch t) {
int idx = 0;
while (idx < t.n && less(t.values[idx], v)) {
++idx;
}
return idx;
}
void removeFromLeaf(int idx, Branch t) {
for (int i = idx + 1; i < t.n; ++i)
t.values[i - 1] = t.values[i];
// Reduce the count of keys
t.n--;
}
void removeFromNonLeaf(int idx, Branch<T> t) {
T k = t.values[idx];
// If the child that precedes k (C[idx]) has atleast t keys,
// find the predecessor 'pred' of k in the subtree rooted at
// C[idx]. Replace k by pred. Recursively delete pred
// in C[idx]
if (t.C[idx].n >= t.t) {
T pred = getPred(idx, t);
t.values[idx] = pred;
t.C[idx].remove(pred);
}
// If the child C[idx] has less that t keys, examine C[idx+1].
// If C[idx+1] has atleast t keys, find the successor 'succ' of k in
// the subtree rooted at C[idx+1]
// Replace k by succ
// Recursively delete succ in C[idx+1]
else if (t.C[idx + 1].n >= t.t) {
T succ = getSucc(idx, t);
t.values[idx] = succ;
t.C[idx + 1].remove(succ);
}
// If both C[idx] and C[idx+1] has less that t keys,merge k and all of C[idx+1]
// into C[idx]
// Now C[idx] contains 2t-1 keys
// Free C[idx+1] and recursively delete k from C[idx]
else {
//merge(idx, t);
t.C[idx].remove(k);
}
}
void fill(int idx, Branch<T> t) {
// If the previous child(C[idx-1]) has more than t-1 keys, borrow a key
// from that child
if (idx != 0 && t.C[idx - 1].n >= t.t)
borrowFromPrev(idx, t);
// If the next child(C[idx+1]) has more than t-1 keys, borrow a key
// from that child
else if (idx != t.n && t.C[idx + 1].n >= t.t)
borrowFromNext(idx, t);
// Merge C[idx] with its sibling
// If C[idx] is the last child, merge it with with its previous sibling
// Otherwise merge it with its next sibling
else {
if (idx != t.n)
merge(idx, t);
else
merge(idx - 1, t);
}
}
private T getPred(int idx, Branch<T> t) {
// Keep moving to the right most node until we reach a leaf
Branch<T> cur = t.C[idx];
while (!cur.leaf)
cur = cur.C[cur.n];
// Return the last key of the leaf
return cur.values[cur.n - 1];
}
private T getSucc(int idx, Branch<T> t) {
Branch<T> cur = t.C[idx + 1];
while (!cur.leaf)
cur = cur.C[0];
// Return the first key of the leaf
return cur.values[0];
}
private void borrowFromPrev(int idx, Branch<T> t) {
Branch<T> child = t.C[idx];
Branch<T> sibling = t.C[idx - 1];
// The last key from C[idx-1] goes up to the parent and key[idx-1]
// from parent is inserted as the first key in C[idx]. Thus, the loses
// sibling one key and child gains one key
// Moving all key in C[idx] one step ahead
for (int i = child.n - 1; i >= 0; --i)
child.values[i + 1] = child.values[i];
// If C[idx] is not a leaf, move all its child pointers one step ahead
if (!child.leaf) {
for (int i = child.n; i >= 0; --i)
child.C[i + 1] = child.C[i];
}
// Setting child's first key equal to keys[idx-1] from the current node
child.values[0] = t.values[idx - 1];
// Moving sibling's last child as C[idx]'s first child
if (!t.leaf)
child.C[0] = sibling.C[sibling.n];
// Moving the key from the sibling to the parent
// This reduces the number of keys in the sibling
t.values[idx - 1] = sibling.values[sibling.n - 1];
child.n += 1;
sibling.n -= 1;
}
private void borrowFromNext(int idx, Branch<T> t) {
Branch<T> child = t.C[idx];
Branch<T> sibling = t.C[idx + 1];
// keys[idx] is inserted as the last key in C[idx]
child.values[child.n] = t.values[idx];
// Sibling's first child is inserted as the last child
// into C[idx]
if (!child.leaf)
child.C[child.n + 1] = sibling.C[0];
//The first key from sibling is inserted into keys[idx]
t.values[idx] = sibling.values[0];
// Moving all keys in sibling one step behind
for (int i = 1; i < sibling.n; ++i)
sibling.values[i - 1] = sibling.values[i];
// Moving the child pointers one step behind
if (!sibling.leaf) {
for (int i = 1; i <= sibling.n; ++i)
sibling.C[i - 1] = sibling.C[i];
}
// Increasing and decreasing the key count of C[idx] and C[idx+1]
// respectively
child.n += 1;
sibling.n -= 1;
}
private void merge(int idx, Branch<T> t) {
Branch<T> child = t.C[idx];
Branch<T> sibling = t.C[idx + 1];
// Pulling a key from the current node and inserting it into (t-1)th
// position of C[idx]
child.values[t.t - 1] = t.values[idx];
// Copying the keys from C[idx+1] to C[idx] at the end
for (int i = 0; i < sibling.n; ++i)
child.values[i + t.t] = sibling.values[i];
// Copying the child pointers from C[idx+1] to C[idx]
if (!child.leaf) {
for (int i = 0; i <= sibling.n; ++i)
child.C[i + t.t] = sibling.C[i];
}
// Moving all keys after idx in the current node one step before -
// to fill the gap created by moving keys[idx] to C[idx]
for (int i = idx + 1; i < t.n; ++i)
t.values[i - 1] = t.values[i];
// Moving the child pointers after (idx+1) in the current node one
// step before
for (int i = idx + 2; i <= t.n; ++i)
t.C[i - 1] = t.C[i];
// Updating the key count of child and the current node
child.n += sibling.n + 1;
t.n--;
}
/******************************************************************************************************************/
//methods uses in both algorithm
private boolean less(Comparable k1, Comparable k2) {
return k1.compareTo(k2) < 0;
}
private boolean eq(Comparable k1, Comparable k2) {
return k1.compareTo(k2) == 0;
}
/******************************************************************************************************************/
//old algorithm
/*
private int k;
Methods(int k) {
this.k = k;
}
//unused old method to print out a tree
*/
/* void print(Branch<T> branch, Text text, String tab) {
List<Leaf<T>> list = branch.getBranch();
text.setText(text.getText() + tab);
for (int i = 0; i < list.size() && i < k; i++) {
text.setText(text.getText() + list.get(i).getIndex() + " ");
}
text.setText(text.getText() + '\n');
for (Leaf<T> l : list) {
String tab2 = tab;
if (l.getPointer() != null) {
tab2 = " " + tab2;
print(l.getPointer(), text, tab2);
}
}
}*//*
void research(Branch<T> b, T what, Text text) {
List<Leaf<T>> list = b.getBranch();
for (Leaf<T> l : list) {
if (text.getText().equals("")) {
if (l.getIndex().equals(what)) {
text.setText(what + " is here!");
}
} else {
break;
}
}
for (Leaf<T> l : list) {
if (!text.getText().equals("")) {
break;
} else if (l.getPointer() != null) {
research(l.getPointer(), what, text);
}
}
}
Branch<T> insert(Branch<T> b, T ind, int h) {
int j = 0;
Leaf<T> l = new Leaf<>(ind, null);
if (h == 0) {
while (j < b.getChildren()) {
if (ind.compareTo(((Leaf<T>) b.getBranch().get(j)).getIndex()) < 0) {
break;
}
j++;
}
} else {
*/
/*for (j = 0; j < b.getChildren(); j++) {
if ((j+1 == b.getChildren()) || less(ind, b.getBr()[j+1].getIndex())) {
Branch<T> u = insert(b.getBr()[j++].getPointer(),ind, h-1);
if (u == null) return null;
l.setIndex(u.getBr()[0].getIndex());
l.setPointer(u);
break;
}
}*//*
while (j < b.getChildren()) {
if (j + 1 == b.getChildren() || ind.compareTo(((Leaf<T>) b.getBranch().get(j + 1)).getIndex()) < 0) {
Branch<T> temp = insert(((Leaf<T>) b.getBranch().get(j++)).getPointer(), ind, h - 1);
if (temp == null) {
return null;
}
l.setIndex(((Leaf<T>) temp.getBranch().get(0)).getIndex());
l.setPointer(temp);
break;
}
j++;
}
}
*/
/* for (int i = b.getChildren(); i > j; i--)
b.getBr()[i] = b.getBr()[i-1];
b.getBr()[j] = l;*//*
if (j < b.getBranch().size()) {
b.getBranch().add(j, l);
} else {
b.getBranch().add(l);
}
b.setChildren(b.getChildren() + 1);
if (b.getChildren() <= k) return null;
return split(b);
}
private Branch<T> split(Branch<T> b) {
Branch<T> temp = new Branch<>(k / 2);
temp.setChildren(k / 2);
*/
/* for(int j=0; j < k/2; j++){
temp.getBr()[j] = b.getBr()[k/2 + j];
}*//*
temp.getBranch().addAll(b.getBranch().subList(k / 2 + 1, b.getBranch().size()));
b.getBranch().removeAll(b.getBranch().subList(k / 2 + 1, b.getBranch().size()));
b.setChildren(b.getChildren() - k / 2);
return temp;
}
void delete(Branch<T> b, T what, int h) {
}
String draw(Branch<T> b, int h, String s) {
StringBuilder sb = new StringBuilder();
List<Leaf<T>> list = b.getBranch();
if (h == 0) {
for (int j = 0; j < b.getChildren(); j++) {
sb.append(s + list.get(j).getIndex() + "\n");
}
} else {
for (int j = 0; j < b.getChildren(); j++) {
if (j > 0) {
sb.append(s + "(" + list.get(j).getIndex() + ")\n");
}
sb.append(draw(list.get(j).getPointer(), h - 1, s + " "));
}
}
return sb.toString();
}
*/
}
<file_sep>/run.sh
#zabijanie procesu 1099
fuser -k 1099/tcp
#kompilowanie klas
find -name "*.java" > nazwyKlasDoKompilowania.txt
javac @nazwyKlasDoKompilowania.txt
#/eof kompilowanie klas
#posrednik
cd src
rmic server.Server
cd -
#eof posrednik
#odpalanie rejestru
cd src
rmiregistry &
cd -
#eof rejestr
sleep .5
#odpalenie serwera
cd src
#xterm -e
java server.Server &
#eof odpalenie serwerka
#odpalenie klienta
sleep .5
#xterm -e
java client.Main
cd ..
#eof odpalenie klienta
<file_sep>/src/serverModel/Branch.java
package serverModel;
import java.util.ArrayList;
import java.util.List;
class Branch<T extends Comparable<T>> {
T[] values;
int t;
Branch<T>[] C;
int n;
boolean leaf;
Methods<T> m = new Methods<>();
public Branch(int t, boolean leaf) {
this.t = t;
this.leaf = leaf;
values = (T[]) new Comparable[2 * t - 1];
C = new Branch[2 * t];
n = 0;
}
//algorithm methods
String print() {
StringBuilder main = new StringBuilder("");
m.print(this, main, "-->");
System.out.println(main + " TO JEST MAIN");
return main.toString();
}
public void remove(T v) {
int idx = m.findValue(v, this);
// The key to be removed is present in this node
if (idx < n && values[idx].compareTo(v) == 0) {
// If the node is a leaf node - removeFromLeaf is called
// Otherwise, removeFromNonLeaf function is called
if (leaf)
m.removeFromLeaf(idx, this);
else
m.removeFromNonLeaf(idx, this);
} else {
// If this node is a leaf node, then the key is not present in tree
if (leaf) {
System.out.println("The value " + v + " is does not exist in the tree\n");
return;
}
// The key to be removed is present in the sub-tree rooted with this node
// The flag indicates whether the key is present in the sub-tree rooted
// with the last child of this node
boolean flag = (idx == n);
// If the child where the key is supposed to exist has less that t keys,
// we fill that child
if (C[idx].n < t)
m.fill(idx, this);
// If the last child has been merged, it must have merged with the previous
// child and so we recurse on the (idx-1)th child. Else, we recurse on the
// (idx)th child which now has atleast t keys
if (flag && idx > n)
C[idx - 1].remove(v);
else
C[idx].remove(v);
}
}
Branch search(T v) {
return m.search(v, this);
}
}
| 821468d8aa7bcbc3c5fdc3758903cc1bb557c860 | [
"Java",
"Shell"
] | 3 | Java | JacekDuszenko/jackson1337-BTreeServer4MacynaPWR | 127cc66eb45196ec984807799ba82ec3e01e248c | 02ff5c0a134004d030b7fa73202de4afa3f7c546 |
refs/heads/master | <file_sep>const expect = require('expect');
const { Users } = require('./users');
describe('Users', () => {
var users;
beforeEach(() => {
users = new Users();
users.users = [
{ id: '1', name: 'dick', room: 'node course'},
{ id: '2', name: 'nikki', room: 'react course'},
{ id: '3', name: 'dylan', room: 'node course'},
]
})
it('should add new user', () => {
var users = new Users();
var user = { id: '123', name: 'dick', room: 'the room' };
var resUser = users.addUser(user.id, user.name, user.room);
expect(users.users).toEqual([user]);
})
it('should return names for node course', () => {
var userList = users.getUserList('node course');
expect(userList).toEqual(['dick', 'dylan']);
})
it('should return names for react course', () => {
var userList = users.getUserList('react course');
expect(userList).toEqual(['nikki']);
})
it('should remove a user', () => {
const userId = '1';
expect(users.removeUser(userId).id).toBe(userId);
expect(users.users.length).toBe(2);
})
it('should not remove user', () => {
expect(users.removeUser('666')).toBeFalsy();
expect(users.users.length).toBe(3);
})
it('should find user', () => {
const userId = '2';
expect(users.getUser(userId).id).toBe(userId);
})
it('should not find user', () => {
expect(users.getUser('666')).toBeFalsy();
})
});
| a32100798dbe5098c1fc94b0893b795035301685 | [
"JavaScript"
] | 1 | JavaScript | richard2223/node-course-2-chat-app | caec8111d2e736675be0fc036c27d521483f697d | 9a577daaf155af83f6d51d1a555719811d8210a4 |
refs/heads/master | <file_sep><?php
namespace Dosi\TheseFondationBundle\Controller\Backend;
use Dosi\TheseFondationBundle\Entity\Candidat;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use APY\DataGridBundle\Grid\Source\Entity;
use APY\DataGridBundle\Grid\Action\RowAction;
use APY\DataGridBundle\Grid\Column\ActionsColumn;
class BackendController extends Controller
{
public function indexAction()
{
return $this->render('DosiTheseFondationBundle:Backend:index.html.twig',array());
}
public function candidatAction()
{
$source = new Entity('DosiTheseFondationBundle:Candidat');
$grid = $this->get('grid');
$grid->setSource($source);
$grid->hideColumns("id");
$grid->setDefaultOrder('nom', 'asc');
$grid->setLimits(array(20, 50, 100));
$grid->setPage(1);
$actionsColumn = new ActionsColumn('info_column_10', 'Actions');
$grid->addColumn($actionsColumn, 10);
// Attach a rowAction to the Actions Column
$rowAction = new RowAction('Voir', 'backend_candidat_view');
$rowAction->setColumn('info_column_10');
$grid->addRowAction($rowAction);
$grid->isReadyForRedirect();
$request = $this->get('request');
return $grid->getGridResponse($request->isXmlHttpRequest() ? 'DosiTheseFondationBundle:Backend:grid.html.twig' : 'DosiTheseFondationBundle:Backend:candidats.html.twig');
}
public function viewAction($id)
{
$em = $this->getDoctrine()->getManager();
$candidat = $em->getRepository('DosiTheseFondationBundle:Candidat')->find($id);
return $this->render('DosiTheseFondationBundle:Backend:view.html.twig',array('candidat'=>$candidat));
}
public function documentAction($id)
{
$em = $this->getDoctrine()->getManager();
$document = $em->getRepository('DosiTheseFondationBundle:Document')->find($id);
$filePath = $document->getAbsolutePath().'/'.$document->getHiddenName();
header('Content-Description: File Transfer');
header('Content-Type:'.mime_content_type($filePath));
header('Content-Disposition: inline; filename=' . $document->getName());
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
@ob_clean();
flush();
readfile($filePath);
die;
}
public function deleteAction($id)
{
$em = $this->getDoctrine()->getManager();
$candidat = $em->getRepository('DosiTheseFondationBundle:Candidat')->find($id);
if (!$candidat) {
throw $this->createNotFoundException('Unable to find Client entity.');
}
$em->remove($candidat);
$em->flush();
return $this->redirect($this->generateUrl('backend_candidat'));
}
public function histoAction()
{
$request = $this->get('request');
$id = $request->query->get('id');
$em = $this->getDoctrine()->getManager();
$now = new \DateTime('now');
$begin = new \DateTime('06/15/2015');
$end = $now;
$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($begin, $interval, $end);
$output = array();
$candidats = array();
foreach ($period as $dt)
{
$nb_cand = $em->getRepository('DosiTheseFondationBundle:Candidat')->getCandidatures($dt);
$candidats[] = array($dt->getTimeStamp()*1000,floatval($nb_cand));
}
$output['candidats'] = $candidats;
$output['title'] = 'Historique des candidatures';
echo json_encode($output);
die;
}
public function exportAction()
{
$em = $this->getDoctrine()->getManager();
$candidats = $em->getRepository('DosiTheseFondationBundle:Candidat')->findAll();
$titles= array('Date','Bourse <NAME>','Bourse <NAME>','Nom','Prénom','Adresse','Téléphone','Mail','Titre de la Thèse','Résumé','Adéquation','Grandes lignes du programme','Retombée','ED','Unité de Recherche','Directeur de thèse');
$content = '<table border=1>';
$content .= '<tr>';
foreach ($titles as $title) {
$content .= sprintf("<th>%s</th>", htmlentities($title, ENT_QUOTES));
}
$content .= '</tr>';
foreach($candidats as $candidat)
{
$content .= '<tr>';
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getDateCandidature()->format( 'd-m-Y' ), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getThesePB(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseJHF(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getNom(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getPrenom(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getAdresse(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTel(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getEmail(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseTitre(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseResume(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseAdeq(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseProg(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseRetour(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseStruct(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseUnite(), ENT_QUOTES));
$content .= sprintf("<td>%s</td>", htmlentities($candidat->getTheseDirecteur(), ENT_QUOTES));
$content .= '</tr>';
}
$content .= '</table>';
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: inline; filename=these-fondation.xls");
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($content));
@ob_clean();
flush();
echo $content;
}
}<file_sep><?php
namespace Dosi\TheseFondationBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class DocumentsType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file','file', array('label' => 'Fichier',"attr" => array(
"multiple" => "multiple",
)));
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Dosi\TheseFondationBundle\Entity\Document'
));
}
/**
* @return string
*/
public function getName()
{
return 'documents';
}
}
<file_sep><?php
namespace Dosi\TheseFondationBundle\Controller\Frontend;
use Dosi\TheseFondationBundle\Entity\Document;
use Dosi\TheseFondationBundle\Form\CandidatType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class CandidatController extends Controller
{
public function indexAction(Request $request)
{
$form = $this->createForm(new CandidatType());
$error = false;
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
$candidat = $form->getData();
$candidat->setDateCandidature(new \DateTime('now'));
$em = $this->getDoctrine()->getManager();
$candidat->getDiplomes()->upload();
$candidat->getLettreDirThese()->upload();
$candidat->getLettreDirUnite()->upload();
$em->persist($candidat);
$em->flush();
return $this->redirect($this->generateUrl('frontend_candidat_success'));
}
else
{
$candidat = $form->getData();
if(strlen($candidat->getTheseResume())>1400)
$error = "Votre résumé doit contenir au maximum 1400 caractères";
if(strlen($candidat->getTheseAdeq())>1400)
$error = "Votre partie adéquation doit contenir au maximum 1400 caractères";
if(strlen($candidat->getTheseProg())>9800)
$error = "Votre programme doit contenir au maximum 9800 caractères";
if(strlen($candidat->getTheseRetour())>1400)
$error = "Votre partie 'Retombée ...' doit contenir au maximum 1400 caractères";
}
}
return $this->render('DosiTheseFondationBundle:Frontend:index.html.twig', array('form' => $form->createView(),'error'=>$error));
}
public function successAction(Request $request)
{
return $this->render('DosiTheseFondationBundle:Frontend:success.html.twig');
}
}<file_sep><?php
namespace Dosi\TheseFondationBundle\Entity;
use APY\DataGridBundle\Grid\Mapping as GRID;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Candidat
*
* @ORM\Table(name="candidat")
* @ORM\HasLifecycleCallbacks
* @ORM\Entity(repositoryClass="Dosi\TheseFondationBundle\Entity\CandidatRepository")
* @GRID\Source(columns="id, nom, prenom, email, dateCandidature")
*/
class Candidat
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
* @Assert\Email()
* @GRID\Column(title="Email", size="150", type="text")
*/
protected $email;
/**
* @ORM\Column(type="string", length=55)
* @Assert\NotBlank()
* @GRID\Column(title="Nom", size="150", type="text")
*/
protected $nom;
/**
* @ORM\Column(type="string", length=55)
* @Assert\NotBlank()
* @GRID\Column(title="Prénom", size="150", type="text")
*/
protected $prenom;
/**
* @ORM\Column(type="string", length=55)
* @Assert\NotBlank()
*/
protected $adresse;
/**
* @ORM\Column(type="string", length=55)
* @Assert\NotBlank()
*/
protected $tel;
/**
* @var string
* @ORM\Column(name="these_titre", type="text")
*/
protected $these_titre;
/**
* @var string
* @ORM\Column(name="these_resume", type="text")
* @Assert\Length(
* min = "2",
* max = "1400",
* minMessage = "Votre résumé doit faire au moins {{ limit }} caractères",
* maxMessage = "Votre résumé ne peut pas être plus long que {{ limit }} caractères"
* )
*/
protected $these_resume;
/**
* @var string
* @Assert\Length(
* min = "2",
* max = "1400",
* minMessage = "Votre texte doit faire au moins {{ limit }} caractères",
* maxMessage = "Votre texte ne peut pas être plus long que {{ limit }} caractères"
* )
* @ORM\Column(name="these_adeq", type="text")
*/
protected $these_adeq;
/**
* @var string
* @ORM\Column(name="these_prog", type="text")
* @Assert\Length(
* min = "2",
* max = "9800",
* minMessage = "Votre programme doit faire au moins {{ limit }} caractères",
* maxMessage = "Votre programme ne peut pas être plus long que {{ limit }} caractères"
* )
*/
protected $these_prog;
/**
* @var string
* @ORM\Column(name="these_retour", type="text")
* @Assert\Length(
* min = "2",
* max = "1400",
* minMessage = "Votre texte doit faire au moins {{ limit }} caractères",
* maxMessage = "Votre texte ne peut pas être plus long que {{ limit }} caractères"
* )
*/
protected $these_retour;
/**
* @var string
* @ORM\Column(name="these_struct", type="text")
*/
protected $these_struct;
/**
* @var string
* @ORM\Column(name="these_unite", type="text")
*/
protected $these_unite;
/**
* @var string
* @ORM\Column(name="these_directeur", type="text")
*/
protected $these_directeur;
/**
* @ORM\Column(name="these_PB", type="boolean")
*/
protected $these_PB;
/**
* @ORM\Column(name="these_JHF", type="boolean")
*/
protected $these_JHF;
/**
* @var \DateTime
* @ORM\Column(name="date_candidature", type="datetime", nullable=true))
* @GRID\Column(title="Date de candidature", size="150", type="date", format="d/m/Y"),
*/
protected $dateCandidature;
/**
*
* @ORM\OneToOne(targetEntity="Dosi\TheseFondationBundle\Entity\Document", cascade={"persist"})
**/
protected $diplomes;
/**
*
* @ORM\OneToOne(targetEntity="Dosi\TheseFondationBundle\Entity\Document", cascade={"persist"})
**/
protected $lettre_dir_these;
/**
*
* @ORM\OneToOne(targetEntity="Dosi\TheseFondationBundle\Entity\Document", cascade={"persist"})
**/
protected $lettre_dir_unite;
/**
* Set email
*
* @param string $email
* @return Candidat
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set nom
*
* @param string $nom
* @return Candidat
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* @param string $prenom
* @return Candidat
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* @return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set dateCandidature
*
* @param \DateTime $dateCandidature
* @return Candidat
*/
public function setDateCandidature($dateCandidature)
{
$this->dateCandidature = $dateCandidature;
return $this;
}
/**
* Get dateCandidature
*
* @return \DateTime
*/
public function getDateCandidature()
{
return $this->dateCandidature;
}
/**
* Set adresse
*
* @param string $adresse
* @return Candidat
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* @return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set tel
*
* @param string $tel
* @return Candidat
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* @return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set these_titre
*
* @param string $theseTitre
* @return Candidat
*/
public function setTheseTitre($theseTitre)
{
$this->these_titre = $theseTitre;
return $this;
}
/**
* Get these_titre
*
* @return string
*/
public function getTheseTitre()
{
return $this->these_titre;
}
/**
* Set these_resume
*
* @param string $theseResume
* @return Candidat
*/
public function setTheseResume($theseResume)
{
$this->these_resume = $theseResume;
return $this;
}
/**
* Get these_resume
*
* @return string
*/
public function getTheseResume()
{
return $this->these_resume;
}
/**
* Set these_adeq
*
* @param string $theseAdeq
* @return Candidat
*/
public function setTheseAdeq($theseAdeq)
{
$this->these_adeq = $theseAdeq;
return $this;
}
/**
* Get these_adeq
*
* @return string
*/
public function getTheseAdeq()
{
return $this->these_adeq;
}
/**
* Set these_prog
*
* @param string $theseProg
* @return Candidat
*/
public function setTheseProg($theseProg)
{
$this->these_prog = $theseProg;
return $this;
}
/**
* Get these_prog
*
* @return string
*/
public function getTheseProg()
{
return $this->these_prog;
}
/**
* Set these_retour
*
* @param string $theseRetour
* @return Candidat
*/
public function setTheseRetour($theseRetour)
{
$this->these_retour = $theseRetour;
return $this;
}
/**
* Get these_retour
*
* @return string
*/
public function getTheseRetour()
{
return $this->these_retour;
}
/**
* Set these_struct
*
* @param string $theseStruct
* @return Candidat
*/
public function setTheseStruct($theseStruct)
{
$this->these_struct = $theseStruct;
return $this;
}
/**
* Get these_struct
*
* @return string
*/
public function getTheseStruct()
{
return $this->these_struct;
}
/**
* Set these_unite
*
* @param string $theseUnite
* @return Candidat
*/
public function setTheseUnite($theseUnite)
{
$this->these_unite = $theseUnite;
return $this;
}
/**
* Get these_unite
*
* @return string
*/
public function getTheseUnite()
{
return $this->these_unite;
}
/**
* Set these_directeur
*
* @param string $theseDirecteur
* @return Candidat
*/
public function setTheseDirecteur($theseDirecteur)
{
$this->these_directeur = $theseDirecteur;
return $this;
}
/**
* Get these_directeur
*
* @return string
*/
public function getTheseDirecteur()
{
return $this->these_directeur;
}
/**
* Set diplomes
*
* @param \Dosi\TheseFondationBundle\Entity\Document $diplomes
* @return Candidat
*/
public function setDiplomes(\Dosi\TheseFondationBundle\Entity\Document $diplomes = null)
{
$this->diplomes = $diplomes;
return $this;
}
/**
* Get diplomes
*
* @return \Dosi\TheseFondationBundle\Entity\Document
*/
public function getDiplomes()
{
return $this->diplomes;
}
/**
* Set lettre_dir_these
*
* @param \Dosi\TheseFondationBundle\Entity\Document $lettreDirThese
* @return Candidat
*/
public function setLettreDirThese(\Dosi\TheseFondationBundle\Entity\Document $lettreDirThese = null)
{
$this->lettre_dir_these = $lettreDirThese;
return $this;
}
/**
* Get lettre_dir_these
*
* @return \Dosi\TheseFondationBundle\Entity\Document
*/
public function getLettreDirThese()
{
return $this->lettre_dir_these;
}
/**
* Set lettre_dir_unite
*
* @param \Dosi\TheseFondationBundle\Entity\Document $lettreDirUnite
* @return Candidat
*/
public function setLettreDirUnite(\Dosi\TheseFondationBundle\Entity\Document $lettreDirUnite = null)
{
$this->lettre_dir_unite = $lettreDirUnite;
return $this;
}
/**
* Get lettre_dir_unite
*
* @return \Dosi\TheseFondationBundle\Entity\Document
*/
public function getLettreDirUnite()
{
return $this->lettre_dir_unite;
}
/**
* Set these_PB
*
* @param boolean $thesePB
* @return Candidat
*/
public function setThesePB($thesePB)
{
$this->these_PB = $thesePB;
return $this;
}
/**
* Get these_PB
*
* @return boolean
*/
public function getThesePB()
{
return $this->these_PB;
}
/**
* Set these_JHF
*
* @param boolean $theseJHF
* @return Candidat
*/
public function setTheseJHF($theseJHF)
{
$this->these_JHF = $theseJHF;
return $this;
}
/**
* Get these_JHF
*
* @return boolean
*/
public function getTheseJHF()
{
return $this->these_JHF;
}
/**
* Constructor
*/
public function __construct()
{
$this->diplomes = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add diplomes
*
* @param \Dosi\TheseFondationBundle\Entity\Document $diplomes
* @return Candidat
*/
public function addDiplome(\Dosi\TheseFondationBundle\Entity\Document $diplomes)
{
$this->diplomes[] = $diplomes;
return $this;
}
/**
* Remove diplomes
*
* @param \Dosi\TheseFondationBundle\Entity\Document $diplomes
*/
public function removeDiplome(\Dosi\TheseFondationBundle\Entity\Document $diplomes)
{
$this->diplomes->removeElement($diplomes);
}
}
<file_sep><?php
namespace Dosi\TheseFondationBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class DosiTheseFondationBundle extends Bundle
{
}
<file_sep><?php
namespace Dosi\TheseFondationBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Dosi\TheseFondationBundle\Form\DocumentType;
class CandidatType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('nom','text', array('label' => 'Nom :'));
$builder->add('prenom','text', array('label' => 'Prénom :'));
$builder->add('email', 'email', array('label' => 'Courriel :'));
$builder->add('adresse','textarea',array('label' => 'Adresse : ', 'attr' => array('class'=>'form-control editor','rows' => '3','cols' => '10'),'required' => true));
$builder->add('tel', 'text', array('label' => 'Téléphone :'));
$builder->add('these_titre','textarea',array('attr' => array('class'=>'form-control editor','rows' => '2','cols' => '10'),'required' => true));
$builder->add('these_resume','textarea',array('attr' => array('class'=>'form-control editor','rows' => '5','cols' => '10'),'required' => true,'max_length'=>"1400"));
$builder->add('these_adeq','textarea',array('attr' => array('class'=>'form-control editor','rows' => '5','cols' => '10'),'required' => true,'max_length'=>"1400"));
$builder->add('these_prog','textarea',array('attr' => array('class'=>'form-control editor','rows' => '20','cols' => '10'),'required' => true,'max_length'=>"9800"));
$builder->add('these_retour','textarea',array('attr' => array('class'=>'form-control editor','rows' => '15','cols' => '10'),'required' => true,'max_length'=>"1400"));
$builder->add('these_struct','textarea',array('attr' => array('class'=>'form-control editor','rows' => '2','cols' => '10'),'required' => true));
$builder->add('these_unite','textarea',array('attr' => array('class'=>'form-control editor','rows' => '3','cols' => '10'),'required' => true));
$builder->add('these_directeur','textarea',array('attr' => array('class'=>'form-control editor','rows' => '3','cols' => '10'),'required' => true));
$builder->add('these_PB','checkbox',array('required' => false));
$builder->add('these_JHF','checkbox',array('required' => false));
$builder->add('diplomes', new DocumentType());
$builder->add('lettre_dir_these', new DocumentType());
$builder->add('lettre_dir_unite', new DocumentType());
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Dosi\TheseFondationBundle\Entity\Candidat'
));
}
/**
* @return string
*/
public function getName()
{
return 'candidat';
}
}
<file_sep><?php
namespace Dosi\TheseFondationBundle\Entity;
use Doctrine\ORM\EntityRepository;
class CandidatRepository extends EntityRepository
{
public function getCandidatures($date)
{
$qb = $this->createQueryBuilder('p');
$qb->select('count(p.id)');
$end = new \DateTime();
$end->setTimestamp($date->getTimeStamp());
$end->setTime(23,59,59);
$qb->where("p.dateCandidature<=:date");
$qb->setParameter('date',$end, \Doctrine\DBAL\Types\Type::DATETIME);
return $qb->getQuery()->getSingleScalarResult();
}
} | dd166e502d52c2ae587234a4c1dd22ffdade585f | [
"PHP"
] | 7 | PHP | dardennj/uapv | 30d463a8d567e41c0a4fd410220c387e0177308c | edc2736462db9856abaf9c1cf86c5377e66c4ff8 |
refs/heads/master | <file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste;
import interfaces.models.IQuestionYesNo;
/**
*
* @author <NAME>
*/
/**
public class QuestionYesNo {
private String user_answer;
@Override
public String getUser_answer() {
return this.user_answer;
}
@Override
public void setUser_answer(String user_answer) {
this.user_answer = user_answer;
super.answer(this.user_answer);
}
}
*/<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.*;
import interfaces.controller.ITest;
import interfaces.controller.ITestStatistics;
import interfaces.exceptions.TestException;
import interfaces.models.IQuestion;
import java.util.logging.Level;
import java.util.logging.Logger;
import views.TestWindow;
/**
*
* @author <NAME>
*/
public class Teste{
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
/**
Test teste = new Test();
teste.loadFromJSONFile("C:\\FP\\PP_FinalProject\\teste_A.txt");
Receiver[] array = teste.getReceiver();
System.out.println(array[3].getType());
Question questao = array[3].getQuestion();
String resposta = questao.getCorrect_answer();
System.out.println(questao.getCorrect_answer());
System.out.println(questao.getClass());
*/
ITest demoTest = new Test();
try {
demoTest.loadFromJSONFile("C:\\FP\\PP_FinalProject\\teste_A.txt");
} catch (TestException ex) {
Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
}
TestWindow t = new TestWindow();
try {
t.startTest(demoTest);
} catch (TestException ex) {
Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Teste Efectuado");
System.out.println(demoTest.toString());
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste;
import com.google.gson.Gson;
import interfaces.controller.ITest;
import interfaces.controller.ITestStatistics;
import interfaces.exceptions.TestException;
import interfaces.models.IQuestion;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author <NAME>
*/
public class Test implements ITest{
private Receiver[] receiver;
public Test() {
}
public Receiver[] getReceiver() {
return receiver;
}
public void setReceiver(Receiver[] receiver) {
this.receiver = receiver;
}
BufferedReader reader = null;
@Override
public boolean loadFromJSONFile(String path) throws TestException {
try {
reader = new BufferedReader(new FileReader(path));
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
Gson gson = new Gson();
Receiver[] teste = gson.fromJson(reader, Receiver[].class);
this.receiver = teste;
return this.receiver == teste;
}
@Override
public boolean addQuestion(IQuestion q) throws TestException {
if(q == null){
throw new TestException("A questão que pretende adicionar não existe");
}else{
if(numberQuestions() >= this.receiver.length){
throw new TestException("Não existe mais espaço no teste");
}else{
int i=0;
while(this.receiver[i].getQuestion() != null && i<this.receiver.length){
i++;
}
this.receiver[i].setQuestion(q);
return true;
}
}
}
@Override
public IQuestion getQuestion(int pos) throws TestException {
if(pos < 0 || pos >= numberQuestions()){
throw new TestException("A posição indicada é inválida!");
}else{
if(this.receiver[pos].getQuestion() == null){
throw new TestException("Não existe ficheiro na posição indicada!");
}else{
return this.receiver[pos].getQuestion();
}
}
}
@Override
public boolean removeQuestion(int pos) {
if(numberQuestions() == 0){
System.out.println("Não existem questões no teste para serem removidas!");
return false;
}else{
if(pos < 0 || pos >= numberQuestions()){
System.out.println("A posição indicada para remover não existe!");
return false;
}
else{
this.receiver[pos]=null;
while(pos < receiver.length-1){
receiver[pos] = receiver[pos + 1];
pos++;
}
receiver[pos]=null;
return true;
}
}
}
@Override
public boolean removeQuestion(IQuestion q) {
if(numberQuestions() == 0){
System.out.println("Não existem questões no teste para serem removidas!");
return false;
}else{
if(q == null){
System.out.println("A posição indicada para remover não existe!");
return false;
}
else{
for(int i=0; i<receiver.length; i++){
if(this.receiver[i].getQuestion() == q){
this.receiver[i] = null;
while(i < receiver.length-1){
receiver[i] = receiver[i + 1];
i++;
}
receiver[i]=null;
return true;
}
if(i == receiver.length){
return false;
}
}
}
}
return false;
}
@Override
public int numberQuestions() {
int i=0;
while(i<receiver.length && receiver[i]!=null){
i++;
}
return i;
}
@Override
public boolean isComplete() {
int cont=0;
for(int i=0; i<this.receiver.length; i++){
IQuestion questao = receiver[i].getQuestion();
if(questao.isDone() == true){
cont++;
}
}
return cont==receiver.length;
}
@Override
public ITestStatistics getTestStatistics() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| b10dab6eb2c85135b3ab32ca0c6a2cdc6db081cb | [
"Java"
] | 3 | Java | Breaksert/ProjetoFinal | 8e1364d4c6fd35342de05c1dbcdb9e93afdef6ea | 625bd108a993f6990313d258851b6035f6a65f86 |
refs/heads/master | <repo_name>KellyOShaughnessy/Python-BST<file_sep>/README.md
# Python-BST
###*Overview:*
>BinaryTree.py contains a basic implementation of a binary search tree.
>An instance of a BinaryTree has a root node, and a size.
>Items of the tree are represented by nodes, which have a left child, right child, and a value.
>
>This tree also contains methods for printing postorder, inorder, and preorder traversals.
###Methods:
-->insert(val)
-->insert_list(val_list)
-->get_left(node)
-->get_right(node)
-->preorder_print(root)
-->inorder_print(root)
-->postorder_print(root)
###Testing:
Currently contains a main function with an example of how to create a binary search tree.
Therefore, it can be run like a python 2 script.
<file_sep>/binarysearchtree.py
#binarysearchtree.py
class Node(object):
"""Represents an item in a binary search tree.
Each node has a left child, right child, and a value"""
def __init__(self, val=None):
"""Creates a new node."""
self.left = None
self.right = None
self.value = val
def get_left(self):
"""Returns: left child of node n."""
return self.left
def get_right(self):
"""Returns: right child of node n."""
return self.right
def is_leaf(self):
"""Returns: True if node is a leaf, and False if node is not a leaf."""
return (self.right != None and self.left !=None)
class BST(object):
def __init__(self, root=None):
"""Initializer: A new instance of a binary search tree with a root
and a size.
Preconditions: size variable only remains accurate if nodes are added to
the tree using the insert method.
"""
self.root = root
if root is None:
self.size = 0
else:
self.size = 1
def insert(self,val):
"""Inserts unique node with value val into tree. No duplicate nodes."""
#accessing tree root
root = self.root
#adding node to tree
if root is None:
self.root = Node(val)
else:
if val < root.value:
left_tree = BST(root.left)
left_tree.insert(val)
elif val > root.value:
right_tree = BST(root.right)
right_tree.insert(val)
#update size of tree t
if root.value != val:
self.size += 1
def insert_list(self,val_list):
"""Inserts a list of unique values into tree."""
for val in val_list:
self.insert(val)
def contains(self,n):
"""Returns: True if node n is in the tree, else False"""
if self is None or n is None:
return False
elif self.root.value == n.value:
return True
else:
return self.right.contains(n) or self.left.contains(n)
def print_init_message(self, traversal):
"""Prints out information about the tree: which traversal is being
performeed, the root value of the tree, and the size of the tree.
"""
print "\nPrinting the %s traversal for the following tree:" % traversal
print " Root of tree: %s" % self.root.value
print " Size of tree %d" % self.size
def preorder_print(self,root):
"""Prints out the preorder traversal of the tree."""
if self.root == root:
self.print_init_message("preorder")
if root is not None:
print root.value
self.preorder_print(root.left)
self.preorder_print(root.right)
def inorder_print(self,root):
"""Prints out the inorder traversal of the tree."""
if self.root == root:
self.print_init_message("inorder")
if root is not None:
self.inorder_print(root.left)
print root.value
self.inorder_print(root.right)
def postorder_print(self,root):
"""Prints out the postorder traversal of the tree."""
if self.root == root:
self.print_init_message("postorder")
if root is not None:
self.preorder_print(root.right)
self.preorder_print(root.left)
print root.value
if __name__ == '__main__':
#initialize root
root = Node(10)
#create tree
bt = BST(root)
#build tree
bt.insert(5)
bt.insert(10)
bt.insert(6)
bt.insert(12)
bt.insert_list([3,8])
#print!
bt.preorder_print(root)
bt.inorder_print(root)
bt.postorder_print(root)
| 15988309c91703aa4e87c3f2b9ccc8e7460c4610 | [
"Markdown",
"Python"
] | 2 | Markdown | KellyOShaughnessy/Python-BST | a575f793edada29032f9afe87380715c65fe8c6a | ee8df094c1530590c4dd34a27a097353afb297c3 |
refs/heads/master | <file_sep>console.log("helloworld");
console.log("conflict 2")
console.log("conflict 3");
| e101dbcd74878919e7b61bb61b1f55147135c391 | [
"JavaScript"
] | 1 | JavaScript | changhow/ENG1003 | 087049ba92c38b8f11bce75f8b8d4ecab33f54de | 7dde67cea812c6f1032d5f97af3134a828553548 |
refs/heads/main | <repo_name>Ame-ly/goit-js-hw-07<file_sep>/task-5.js
const inputRef = document.querySelector('#name-input');
const titleRef = document.querySelector('#name-output');
inputRef.addEventListener('input', inputHandlerFocus);
function inputHandlerFocus(event) {
if (event.target.value) {
return (titleRef.textContent = event.target.value);
}
return (titleRef.textContent = 'незнакомец');
}
<file_sep>/task-2.js
const ingredients = [
'Картошка',
'Грибы',
'Чеснок',
'Помидоры',
'Зелень',
'Приправы',
];
const elementsRef = document.querySelector('#ingredients');
const createProduct = ingredient => {
const item = document.createElement('li');
item.textContent = ingredient;
return item;
};
const elements = ingredients.map(createProduct);
const title = document.createElement('h2');
title.textContent = 'Ингридиенты';
elementsRef.before(title);
elementsRef.append(...elements);
console.log(elementsRef);
// const searchNewRef = document.querySelector('#ingredients');
// ingredients.forEach(ingredientsItems);
// function ingredientsItems(el) {
// document.createElement('li').textContent = el;
// searchNewRef.appendChild(addList);
// }<file_sep>/task-6.js
const inputRef = document.querySelector('#validation-input');
inputRef.addEventListener('blur', checkInput);
// function checkInput(e) {
// const numberEvent = e.target.value.length;
// const numberRef = Number(inputRef.getAttribute('data-length'));
// numberEvent === numberRef
// ? (inputRef.className = 'valid')
// : (inputRef.className = 'invalid');
// if (numberEvent === 0) {
// inputRef.className = '';
// }
// }
function checkInput(e) {
const number = Number(inputRef.getAttribute('data-length'));
const length = e.currentTarget.value.length;
if (length === 0) {
inputRef.className = '';
} else if (length === number) {
updateClass('valid', 'invalid');
} else {
updateClass('invalid', 'valid');
}
}
inputRef.addEventListener('focus', () => {
inputRef.classList.remove('valid', 'invalid');
})
//или
// function checkInput(e) {
// const number = Number(inputRef.getAttribute('data-length'));
// const length = e.currentTarget.value.length;
// if (length === 0) {
// inputRef.className = '';
// } else if (length === number) {
// updateClass('valid', 'invalid');
// } else {
// updateClass('invalid', 'valid');
// }
// }
function updateClass(addClass, remClass) {
inputRef.classList.add(addClass);
inputRef.classList.remove(remClass);
}
// inputRef.onblur = function () {
// const number = inputRef.value.length;
// if (number === Number(inputRef.getAttribute('data-length'))) {
// inputRef.className = 'valid';
// } else if (number === 0) {
// inputRef.className = '';
// } else {
// inputRef.className = 'invalid';
// }
// };
// inputRef.onblur = function () {
// if (Number(inputRef.dataset.length) === Number(inputRef.value.length)) {
// inputRef.classList.remove('invalid');
// inputRef.classList.add('valid');
// } else if (inputRef.value.length === 0) {
// inputRef.classList.remove('valid');
// inputRef.classList.remove('invalid');
// } else {
// inputRef.classList.add('invalid');
// }
<file_sep>/task-8.js
const inputRef = document.querySelector('input[type="number"]');
const createBtnRef = document.querySelector('button[data-action="render"]');
const removeBtnRef = document.querySelector('button[data-action="destroy"]');
const boxesRef = document.querySelector('#boxes');
createBtnRef.addEventListener('click', createBoxes);
removeBtnRef.addEventListener('click', removeBoxes);
function createBoxes(amount) {
// boxesRef.style.
amount = inputRef.value;
let size = 30;
for (let i = 0; i < amount; i += 1) {
boxesRef.appendChild(
document.createElement('div')
).style = `width: ${size}px; height: ${size}px; background-color:
rgb(${createRandomColor()}, ${createRandomColor()}, ${createRandomColor()}); margin: auto`;
size += 10;
}
}
function removeBoxes() {
boxesRef.innerHTML = '';
inputRef.value = '';
}
function createRandomColor() {
return Math.floor(Math.random() * 256);
}
<file_sep>/task-1.js
const categoryRef = document.querySelector('ul#categories');
console.log(`В списке ${categoryRef.children.length} категории.`);
categoryRef.querySelectorAll('.item').forEach(el => {
console.log(`• Категория:${el.querySelector('h2').textContent}
• Количество элементов:${el.querySelector('ul').children.length}`);
});
<file_sep>/task-3.js
const images = [
{
url:
'https://images.pexels.com/photos/140134/pexels-photo-140134.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
alt: 'White and Black Long Fur Cat',
},
{
url:
'https://images.pexels.com/photos/213399/pexels-photo-213399.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
alt: 'Orange and White Koi Fish Near Yellow Koi Fish',
},
{
url:
'https://images.pexels.com/photos/219943/pexels-photo-219943.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
alt: 'Group of Horses Running',
},
];
const galleryRef = document.querySelector('#gallery');
galleryRef.classList.add('gallery-js');
const markupGallery = images
.map(
img =>
`<li class="gallery-card-js">
<img src="${img.url}"
alt="${img.alt}"
class="gallery-img-js">
</li>`,
)
.join('');
galleryRef.insertAdjacentHTML('beforeend', markupGallery);
//вариант 2
// const createGallery = ({ url, alt }) => {
// const imgTag = document.createElement('img');
// imgTag.src = url;
// imgTag.alt = alt;
// imgTag.classList.add('gallery-img-js');
// const liTag = document.createElement('li');
// liTag.appendChild(imgTag);
// liTag.classList.add('gallery-card-js');
// return liTag;
// };
// const galleryTemplate = images.map(createGallery);
// galleryRef.append(...galleryTemplate);
// console.log(galleryRef);
| 6f101afb30adbe58fb7042efd746e34909847d49 | [
"JavaScript"
] | 6 | JavaScript | Ame-ly/goit-js-hw-07 | 8f3793546b8c3681854a889f64ce7f7cf607970e | 3e6c35ea86d178adaaef133086bdc19278c1f893 |
refs/heads/master | <file_sep>//
// ViewController.swift
// LoverApp
//
// Created by sky on 2016/7/26.
// Copyright © 2016年 sky. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nextPage: UIButton!
@IBOutlet weak var secgirlButton: UIButton!
@IBOutlet weak var thirdgirlButton: UIButton!
var girlA = lover(loverNumber:0, name: "林志玲", sign: "射手座", girlImage: "lin.jpg")
var girlB = lover(loverNumber:1, name: "<NAME>", sign: "金牛座", girlImage: "gal.jpg")
var girlC = lover(loverNumber:2, name: "<NAME>", sign: "雙魚座", girlImage: "lily.jpg")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let NotiName = Notification.Name("update")
NotificationCenter.default.addObserver(self, selector: #selector(upload(noti:)), name: NotiName, object: nil)
nextPage.setTitle(girlA.name, for: [])
secgirlButton.setTitle(girlB.name, for: [])
thirdgirlButton.setTitle(girlC.name, for: [])
//將button的名稱傳入自訂的愛人名字
}
func upload(noti:Notification){
let NewloverNumber = noti.userInfo!["number"] as! Int
let newName = noti.userInfo!["name"] as! String
let newSign = noti.userInfo!["sign"] as! String
//let NewImage = noti.userInfo!["showimage"] as! String
if NewloverNumber == 0 {
girlA.loverNumber = NewloverNumber
girlA.name = newName
girlA.sign = newSign
//girlA.girlImage = NewImage
nextPage.setTitle(girlA.name, for: [])//After edit updates button title.
}else if NewloverNumber == 1{
girlB.loverNumber = NewloverNumber
girlB.name = newName
girlB.sign = newSign
//girlB.girlImage = NewImage
secgirlButton.setTitle(girlB.name, for: [])
}else{
girlC.loverNumber = NewloverNumber
girlC.name = newName
girlC.sign = newSign
//girlC.girlImage = NewImage
thirdgirlButton.setTitle(girlC.name, for: [])
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//傳送至下一頁的資訊
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destination as! SecViewController
if segue.identifier == "lineA"{
controller.loverNumber = girlA.loverNumber
controller.name = girlA.name
controller.sign = girlA.sign
controller.girlImage = girlA.girlImage
}else if segue.identifier == "lineB"{
controller.loverNumber = girlB.loverNumber
controller.name = girlB.name
controller.sign = girlB.sign
controller.girlImage = girlB.girlImage
}else{
controller.loverNumber = girlC.loverNumber
controller.name = girlC.name
controller.sign = girlC.sign
controller.girlImage = girlC.girlImage
}
}
}
<file_sep>//
// lover.swift
// LoverApp
//
// Created by sky on 2016/8/6.
// Copyright © 2016年 sky. All rights reserved.
//
import Foundation
class lover{
var loverNumber:Int!
var name:String!
var sign:String!
var girlImage:String!
init(loverNumber:Int, name:String, sign:String, girlImage:String) {
self.loverNumber = loverNumber
self.name = name
self.sign = sign
self.girlImage = girlImage
}
}
<file_sep>//
// EditViewController.swift
// LoverApp
//
// Created by sky on 2016/7/27.
// Copyright © 2016年 sky. All rights reserved.
//
import UIKit
class EditViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate{
//var saveData:String!
//var delegate:EditViewControllerDelegate? = nil
var name:String!
var sign:String!
var loverNumber:Int!
var girlImage:String!
@IBOutlet weak var nameEditLabel: UITextField!
@IBOutlet weak var signLabel: UITextField!
@IBOutlet weak var changeImage: UIImageView!
/*@IBAction func ImageButton(_ sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
self.present(imagePicker, animated: true, completion: nil)
}*/
override func viewDidLoad() {
super.viewDidLoad()
nameEditLabel.returnKeyType = .next
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(EditViewController.upload(_:)))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("info \(info)")
let image = info[UIImagePickerControllerOriginalImage]
self.changeImage.image = image as? UIImage
self.dismiss(animated:true, completion: nil)//回傳所選的照片到上一頁
super.viewDidLoad()
let size = CGSize(width: 640, height:
(image?.size.height)! * 640 / (image?.size.height)!)
UIGraphicsBeginImageContextWithOptions(size,false, 0)
changeImage.draw(CGRect(origin: CGPoint.zero,size: size))
//let resizeImage = UIGraphicsGetImageFromCurrentImageContext()
//UIGraphicsEndImageContext()
}*/
func upload(_ sender:AnyObject){
let NotiName = Notification.Name("update")
NotificationCenter.default.post(name: NotiName, object: nil, userInfo: ["number": loverNumber, "name": nameEditLabel.text!, "sign": signLabel.text!])
_ = self.navigationController?.popViewController(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
if let Newname = name{
nameEditLabel.text = Newname
self.title = Newname
}
if let Newsign = sign{
signLabel.text = Newsign
}
/*if let NewImage = girlImage{
self.changeImage.image = UIImage(named: NewImage)
}*/
} //將文字框的值顯示出來的功能
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nameEditLabel {
signLabel.becomeFirstResponder()
return false
}else{
signLabel.resignFirstResponder()
return true
}
}
}
<file_sep>//
// SecViewController.swift
// LoverApp
//
// Created by sky on 2016/7/27.
// Copyright © 2016年 sky. All rights reserved.
//
import UIKit
class SecViewController: UIViewController {
var name:String!
var sign:String!
var girlImage:String!
var loverNumber:Int!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var signLabel: UILabel!
@IBOutlet weak var imageforgirl: UIImageView!
@IBAction func pressedEditButton(_ sender: AnyObject) {
}
func upload(noti:Notification){
let newname = noti.userInfo!["name"] as! String
let newsign = noti.userInfo!["sign"] as! String
self.name = newname //這二個name、sign屬性要建立,否則無法更新資料
self.sign = newsign
self.nameLabel.text = newname
self.signLabel.text = newsign
//self.imageforgirl.image = UIImage(named: NewImage)
}
override func viewDidLoad() {
super.viewDidLoad()
if let newname = name{
nameLabel.text = newname
//self.title = newname
}
if let newsign = sign{
signLabel.text = newsign
}
if let newImage = girlImage{
imageforgirl.image = UIImage(named: newImage)//少了這行,圖片不會出現。
}
let NotiName = Notification.Name("update")
NotificationCenter.default.addObserver(self, selector: #selector(upload(noti:)), name: NotiName, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destination as! EditViewController
controller.name = name
controller.sign = sign
controller.loverNumber = loverNumber
//controller.girlImage = girlImage
}//將值傳回下一頁文字框的連結
}
| 020273b0b54d63447ee80f915422fb7feb43a91b | [
"Swift"
] | 4 | Swift | blue52/LoverApp | cdefaf06d082f4a9a2358d0f0777167bc6ca321a | 920cdb33dcfc52c9ef8deb5d2ce0f167afb1db5b |
refs/heads/master | <file_sep>$(document).ready(function () {
$(".dropdown").click(function () {
// slide dropdown
$(this).find(".dropdown-data").slideToggle(400);
//toggle icon
var icon = $(this).find(".dropdown-icon");
switch (icon.hasClass("down")) {
case true:
icon.removeClass("rotate");
icon.removeClass("down");
icon.addClass("up");
break;
case false:
icon.addClass("rotate");
icon.removeClass("up");
icon.addClass("down");
break;
default:
icon.addClass("rotate");
icon.removeClass("up");
icon.addClass("down");
break;
}
//click outside close dropdown
var dropDown = $(this);
$(document).click(function (e) {
if (!dropDown.is(e.target) && dropDown.has(e.target).length === 0) {
var isOpened = dropDown.find(".dropdown-data").css("display");
if (isOpened == "block") {
dropDown.find(".dropdown-data").slideUp(400);
icon.removeClass("rotate");
icon.removeClass("down");
icon.addClass("up");
}
}
});
// item selected
$(".dropdown-item").click(function () {
$(this)
.parent()
.find(".dropdown-item")
.css({ "background-color": "#fff", color: "#000" });
$(this)
.parent()
.find(".dropdown-item-icon")
.css({ visibility: "hidden" });
var dropDownText = $(this).parent().parent().find(".dropdown-text");
var item = $(this).find(".dropdown-item-text");
var valueItem = $(this).find(".dropdown-item-text").attr("value");
dropDownText.text(item.text());
dropDownText.attr("value", valueItem);
$(this).css({ "background-color": "#019160", color: "#fff" });
$(this).find(".dropdown-item-icon").css({ visibility: "visible" });
});
});
function RotateUp() {}
});
<file_sep>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using MySqlConnector;
using Dapper;
using System.Text.RegularExpressions;
using MISA.Core.Entities;
using MISA.Core.Interfaces.Services;
using MISA.Core.Interfaces.Repository;
using System.IO;
namespace MISA.CukCuk.Api.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class EmployeesController : BaseEntityController<Employee>
{
#region DECLARE
IEmployeeService _employeeService;
IEmployeeRepository _employeeRepository;
#endregion
#region Constructor
public EmployeesController(IEmployeeService employeeService, IEmployeeRepository employeeRepository) : base(employeeRepository, employeeService)
{
_employeeRepository = employeeRepository;
_employeeService = employeeService;
}
#endregion
#region Methods
/// <summary>
/// Tự sinh mã nhân viên mới
/// </summary>
/// <returns>Mã nhân viên mới dạng string</returns>
/// CreateBy: LQNHAT(13/08/2021)
[HttpGet("NewEmployeeCode")]
public IActionResult AutoNewEmployeeCode()
{
try
{
// 4. trả về client
var newEmployeeCode = _employeeRepository.NewCode();
return StatusCode(200, newEmployeeCode);
}
catch (Exception ex)
{
var msg = new
{
devMsg = ex.Message,
userMsg = Properties.ResourceVnEmployee.Exception_ErrorMsg,
};
return StatusCode(500, msg);
}
}
/// <summary>
/// Lọc danh sách nhân viên theo các tiêu chí và phân trang
/// </summary>
/// <param name="pageIndex">Index của trang hiện tại</param>
/// <param name="pageSize">Số bản ghi hiển thị trên 1 trang</param>
/// <param name="positionId">Id của vị trí cần tìm kiếm</param>
/// <param name="departmentId">Id của phòng ban cần tìm kiếm</param>
/// <param name="keysearch">Mã nhân viên, Họ và tên, SĐT cần tìm kiếm</param>
/// <returns>Danh sách các bản ghi theo điều kiện lọc</returns>
/// CreateBy: LQNHAT(14/08/2021)
[HttpGet("filter")]
public IActionResult GetEmployeesPaging(int pageIndex, int pageSize, string positionId, string departmentId, string keysearch)
{
try
{
// 4. trả về cho client
var employeesFilter = _employeeRepository.GetByPaging(pageIndex, pageSize, positionId, departmentId, keysearch);
//if (employeesFilter.Count() > 0)
//{
// return StatusCode(200, employeesFilter);
//}
//else
//{
// var msg = new
// {
// userMsg = Properties.ResourceVnEmployee.User_ErrorMsg_NoContent,
// };
// return StatusCode(204, msg);
//}
return StatusCode(200, employeesFilter);
}
catch (Exception ex)
{
var msg = new
{
devMsg = ex.Message,
userMsg = Properties.ResourceVnEmployee.Exception_ErrorMsg,
};
return StatusCode(500, msg);
}
}
[HttpPost("Import")]
public IActionResult Import(IFormFile formFile)
{
try
{
var serviceResult = _employeeService.ImportEmployee(formFile);
return Ok(serviceResult.Data);
}
catch (Exception ex)
{
var msg = new
{
devMsg = ex.Message,
userMsg = Properties.ResourceVnEmployee.Exception_ErrorMsg,
};
return StatusCode(500, msg);
}
}
[HttpGet("Export")]
public IActionResult ExportEmployee()
{
try
{
var serviceResult = _employeeService.ExportEmployee();
if (serviceResult.Data != null)
{
Stream stream = (Stream)serviceResult.Data;
stream.Position = 0;
string excelName = $"Employees.xlsx";
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName);
}
else
{
return Ok("Thuc hien khong thanh cong");
}
}
catch (Exception ex)
{
var msg = new
{
devMsg = ex.Message,
userMsg = Properties.ResourceVnEmployee.Exception_ErrorMsg,
};
return StatusCode(500, msg);
}
}
#endregion
}
}
<file_sep>using MISA.Core.Entities;
using MISA.Core.Interfaces.Repository;
using MISA.Core.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Services
{
public class PositionService : BaseService<Position>, IPositionService
{
#region DECLARE
IPositionRepository _positionRepository;
ServiceResult _serviceResult;
#endregion
#region Constructor
public PositionService(IPositionRepository positionRepository) : base(positionRepository)
{
_serviceResult = new ServiceResult();
_positionRepository = positionRepository;
}
#endregion
}
}
<file_sep>import Vue from 'vue'
import VueRouter from 'vue-router'
import Employee from '../view/employee/EmployeeList.vue'
import Customer from '../view/customer/CustomerList.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/employee',name:"Employee", component: Employee },
{ path: '/customer',name:"Customer", component: Customer}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
})
export default router<file_sep>using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MISA.Core.Entities;
using MISA.Core.Interfaces.Repository;
using MISA.Core.Interfaces.Services;
using MISA.Core.MISAEnum;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MISA.CukCuk.Api.Controllers
{
[Route("api/v1/[controller]")]
[ApiController]
public class CustomersController : BaseEntityController<Customer>
{
#region DECLARE
IBaseRepository<Customer> _baseRepository;
IBaseService<Customer> _customerService;
#endregion
#region Constructor
public CustomersController(IBaseRepository<Customer> baseRepository, IBaseService<Customer> customerService) : base(baseRepository, customerService)
{
_baseRepository = baseRepository;
_customerService = customerService;
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Entities
{
public class Employee : Base
{
#region Property
/// <summary>
/// Khóa chính
/// </summary>
public Guid EmployeeId { get; set; }
/// <summary>
/// Mã nhân viên
/// </summary>
[Required]
[CheckExist]
[Name("Mã nhân viên")]
public string EmployeeCode { get; set; }
/// <summary>
/// Họ
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Tên đệm và tên
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Họ và tên
/// </summary>
[Required]
[Name("Họ và tên")]
public string FullName { get; set; }
/// <summary>
/// Số giới tính
/// </summary>
public int? Gender { get; set; }
/// <summary>
/// Ngày sinh
/// </summary>
public DateTime? DateOfBirth { get; set; }
/// <summary>
/// Số điện thoại
/// </summary>
[Required]
[Name("Số điện thoại")]
public string PhoneNumber { get; set; }
/// <summary>
/// Email
/// </summary>
[Required]
[CheckEmail]
[Name("Email")]
public string Email { get; set; }
/// <summary>
/// Địa chỉ
/// </summary>
public string Address { get; set; }
/// <summary>
/// Số CMND/Căn cước
/// </summary>
[Required]
[Name("Số CMTND/Căn cước")]
public string IdentityNumber { get; set; }
/// <summary>
/// Ngày cấp CMND/Căn cước
/// </summary>
public DateTime? IdentityDate { get; set; }
/// <summary>
/// Địa điểm cấp CMND/Căn cước
/// </summary>
public string IdentityPlace { get; set; }
/// <summary>
/// Ngày gia nhập công ty
/// </summary>
public DateTime? JoinDate { get; set; }
/// <summary>
/// Id phòng ban
/// </summary>
public Guid DepartmentId { get; set; }
/// <summary>
/// Tên phòng ban
/// </summary>
[NotMap]
public string DepartmentName { get; set; }
/// <summary>
/// Id vị trí
/// </summary>
public Guid PositionId { get; set; }
/// <summary>
/// Tên chức vụ
/// </summary>
[NotMap]
public string PositionName { get; set; }
/// <summary>
/// Số của trạng thái công việc
/// </summary>
public int? WorkStatus { get; set; }
/// <summary>
/// Mã số thuế
/// </summary>
public string PersonalTaxCode { get; set; }
/// <summary>
/// Lương
/// </summary>
public int? Salary { get; set; }
/// <summary>
/// Tên giới tính
/// </summary>
//public string GenderName { get; set; }
[NotMap]
public List<string> ImportArrError { get; set; } = new List<string>();
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Entities
{
public class Customer : Base
{
#region Property
/// <summary>
/// Khóa chính
/// </summary>
[PrimaryKey]
[Name("ID khách hàng")]
public Guid CustomerId { get; set; }
/// <summary>
/// Mã khách hàng
/// </summary>
[CheckExist]
[Required]
[Name("Mã khách hàng")]
public string CustomerCode { get; set; }
/// <summary>
/// Tên họ
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Tên
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Họ và tên
/// </summary>
[Required]
[Name("Họ và tên")]
public string FullName { get; set; }
/// <summary>
/// Giới tính
/// </summary>
public int? Gender { get; set; }
/// <summary>
/// Địa chỉ
/// </summary>
public string Address { get; set; }
/// <summary>
/// Ngày sinh
/// </summary>
public DateTime? DateOfBirth { get; set; }
/// <summary>
/// Email
/// </summary>
[CheckEmail]
[Name("Email")]
public string Email { get; set; }
/// <summary>
/// Số điện thoại
/// </summary>
[Required]
[Name("Số điện thoại")]
public string PhoneNumber { get; set; }
#endregion
}
}
<file_sep>using MISA.Core.Entities;
using MISA.Core.Interfaces.Repository;
using MISA.Core.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Services
{
public class DepartmentService : BaseService<Department>, IDepartmentService
{
#region DECLARE
ServiceResult _serviceResult;
IDepartmentRepository _departmentRepository;
#endregion
#region Constructor
public DepartmentService(IDepartmentRepository departmentRepository) : base(departmentRepository)
{
_serviceResult = new ServiceResult();
_departmentRepository = departmentRepository;
}
#endregion
}
}
<file_sep>using Microsoft.AspNetCore.Http;
using MISA.Core.Entities;
using MISA.Core.Interfaces.Repository;
using MISA.Core.Interfaces.Services;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MISA.Core.Services
{
public class EmployeeService : BaseService<Employee>, IEmployeeService
{
#region DECLARE
IEmployeeRepository _employeeRepository;
ServiceResult _serviceResult;
#endregion
#region Constructor
public EmployeeService(IEmployeeRepository employeeRepository) : base(employeeRepository)
{
_serviceResult = new ServiceResult();
_employeeRepository = employeeRepository;
}
#endregion
#region Methods
public ServiceResult ExportEmployee()
{
var employees = _employeeRepository.Get();
var stream = new MemoryStream();
using (var package = new ExcelPackage(stream))
{
var workSheet = package.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells.LoadFromCollection(employees, true);
package.Save();
}
_serviceResult.Data = stream;
return _serviceResult;
}
public ServiceResult ImportEmployee(IFormFile formFile)
{
// Check file null
if (formFile == null || formFile.Length <= 0)
{
_serviceResult.Message = "File bị trống, xin vui lòng gửi lại file";
_serviceResult.MISACode = MISAEnum.EnumServiceResult.BadRequest;
return _serviceResult;
}
// Check file không đúng định dạng
if (!Path.GetExtension(formFile.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
{
_serviceResult.Message = "File gửi lên không đúng định dạng";
_serviceResult.MISACode = MISAEnum.EnumServiceResult.BadRequest;
return _serviceResult;
}
HashSet<string> contain = new HashSet<string>();
var employees = new List<Tuple<Employee, List<string>>>();
using (var stream = new MemoryStream())
{
formFile.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowCount = worksheet.Dimension.Rows;
for (int row = 3; row < rowCount; row++)
{
// lấy ra value
var employeeId = Guid.NewGuid();
var employeeCode = worksheet.Cells[row, 1].Value;
var fullName = worksheet.Cells[row, 2].Value;
var phoneNumber = worksheet.Cells[row, 5].Value;
var personalTaxCode = worksheet.Cells[row, 8].Value;
var email = worksheet.Cells[row, 9].Value;
var dateOfBirth = worksheet.Cells[row, 6].Value;
// check null
var employee = new Employee
{
EmployeeId = employeeId,
EmployeeCode = (employeeCode != null) ? employeeCode.ToString().Trim() : string.Empty,
FullName = (fullName != null) ? fullName.ToString().Trim() : string.Empty,
PhoneNumber = (phoneNumber != null) ? phoneNumber.ToString().Trim() : string.Empty,
PersonalTaxCode = (personalTaxCode != null) ? personalTaxCode.ToString().Trim() : string.Empty,
Email = (email != null) ? email.ToString().Trim() : string.Empty,
DateOfBirth = (dateOfBirth != null) ? FormatDateTime(dateOfBirth.ToString().Trim()) : null,
};
// validate trong file
if (!contain.Contains(employee.EmployeeCode) && !contain.Contains(employee.Email) && !contain.Contains(employee.PhoneNumber))
{
contain.Add(employee.EmployeeCode);
contain.Add(employee.PhoneNumber);
contain.Add(employee.Email);
employees.Add(Tuple.Create(employee, new List<string>()));
}
else
{
//if (contain.Contains(employee.EmployeeCode))
//{
// employee.ImportArrError.Add("Mã nhân viên đã tồn tại trong file");
//}
//if (contain.Contains(employee.Email))
//{
// employee.ImportArrError.Add("Email đã tồn tại trong file");
//}
//if (contain.Contains(employee.PhoneNumber))
//{
// employee.ImportArrError.Add("SDT đã tồn tại trong file");
//}
//employees.Add(Tuple.Create(employee, employee.ImportArrError));
List<string> notifications = new List<string>();
if (contain.Contains(employee.EmployeeCode))
{
notifications.Add("Mã nhân viên đã tồn tại trong file");
}
if (contain.Contains(employee.Email))
{
notifications.Add("Email đã tồn tại trong file");
}
if (contain.Contains(employee.PhoneNumber))
{
notifications.Add("SDT đã tồn tại trong file");
}
employees.Add(Tuple.Create(employee, notifications));
}
}
//contain.Clear();
}
}
_serviceResult.Data = employees;
return _serviceResult;
}
/// <summary>
/// Format datetime
/// </summary>
/// <param name="dateString"></param>
/// <returns></returns>
private static DateTime? FormatDateTime(string dateString)
{
var str = dateString.Replace('-', '/').Split("/");
switch (str.Length)
{
case 1:
return DateTime.Parse($"{str[0]}/01/01");
case 2:
return DateTime.Parse($"{str[1]}/{str[0]}/01");
case 3:
return DateTime.Parse($"{str[2]}/{str[1]}/{str[0]}");
default:
return null;
}
}
#endregion
}
}
<file_sep>using MISA.Core.Entities;
using MISA.Core.Interfaces.Repository;
using MISA.Core.Interfaces.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MISA.Core.Services
{
public class CustomerService : BaseService<Customer>, ICustomerService
{
#region DECLARE
ICustomerRepository _customerRepository;
ServiceResult _serviceResult;
#endregion
#region Constructor
public CustomerService(ICustomerRepository customerRepository) : base(customerRepository)
{
_serviceResult = new ServiceResult();
_customerRepository = customerRepository;
}
#endregion
}
}
<file_sep>using MISA.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Core.Interfaces.Services
{
public interface IBaseService<TEntity>
{
/// <summary>
/// Xử lý nghiệp vụ việc thêm mới 1 đối tượng vào db
/// </summary>
/// <param name="entity">Đối tượng truyền vào</param>
/// <returns>ServiceResult - lưu trạng thái kết quả sau khi xử lý nghiệp vụ và thao tác với db </returns>
/// CreateBy:LQNhat(09/08/2021)
ServiceResult Add(TEntity entity);
/// <summary>
/// Xử lý nghiệp vụ việc sửa thông tin 1 đối tượng vào db
/// </summary>
/// <param name="entity">Đối tượng truyền vào</param>
/// <param name="entityId">Id của đối tượng truyền vào</param>
/// <returns>ServiceResult - lưu trạng thái kết quả sau khi xử lý nghiệp vụ và thao tác với db </returns>
/// CreateBy:LQNhat(09/08/2021)
ServiceResult Update(TEntity entity, Guid entityId);
ServiceResult DeleteEntites(string entitesId);
}
}
| d467efa0b098f559168db72502e653490e38b51a | [
"JavaScript",
"C#"
] | 11 | JavaScript | lequynhat1999/MISA_CukCuk | 99131e89ad3ff8bb7f193a691ca6a30f4077d40c | f438bc7c189d56d384b6d20407f173e8c04b19f1 |
refs/heads/master | <file_sep>from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework import status
from api.models import *
from api.serializers import *
from rest_framework.response import Response
from rest_framework import viewsets, status
def get_candidate_instance(candidate_name):
if candidate_name == 'Bernie':
return Bernie()
elif candidate_name == 'Cruz':
return Cruz()
elif candidate_name == 'Hillary':
return Hillary()
elif candidate_name == 'Trump':
return Trump()
elif candidate_name == 'Democrat':
return Demo()
elif candidate_name == 'Republican':
return Rep()
def get_candidate(candidate_name):
if candidate_name == 'Bernie':
return Bernie
elif candidate_name == 'Cruz':
return Cruz
elif candidate_name == 'Hillary':
return Hillary
elif candidate_name == 'Trump':
return Trump
elif candidate_name == 'Democrat':
return Dem
elif candidate_name == 'Republican':
return Rep
def candidate_list(request, candidate_name):
if request.method == 'GET':
candidate = get_candidate(candidate_name).objects.all()[:50]
serializer = CandidateSerializer(candidate, many=True)
return Response(serializer.data)
elif request.method == 'POST':
candidate = get_candidate_instance(candidate_name)
serializer = CandidateSerializer(data=request.DATA)
if serializer.is_valid():
candidate.candidate = serializer.data['candidate']
candidate.created_at = serializer.data['created_at']
candidate.sentiment = serializer.data['sentiment']
candidate.text = serializer.data['text']
candidate.user = serializer.data['user']
candidate.tid = serializer.data['tid']
candidate.tone = serializer.data['tone']
candidate.save()
return Response(
status=status.HTTP_201_CREATED
)
@api_view(['GET'])
@permission_classes((AllowAny,))
def bernie_list(request):
return candidate_list(request, 'Bernie')
@api_view(['GET'])
@permission_classes((AllowAny,))
def cruz_list(request):
return candidate_list(request, 'Cruz')
@api_view(['GET'])
@permission_classes((AllowAny,))
def hillary_list(request):
return candidate_list(request, 'Hillary')
@api_view(['GET'])
@permission_classes((AllowAny,))
def trump_list(request):
return candidate_list(request, 'Trump')
@api_view(['GET'])
@permission_classes((AllowAny,))
def democrat_list(request):
return candidate_list(request, 'Democrat')
@api_view(['GET'])
@permission_classes((AllowAny,))
def republican_list(request):
return candidate_list(request, 'Republican')<file_sep>from django.conf.urls import patterns, include, url
from django.contrib import admin
from rest_framework import routers
from . import views
urlpatterns = [
url(r'^bernie/$', views.bernie_list, name='tweets_list'),
url(r'^hillary/$', views.hillary_list, name='tweets_list'),
url(r'^trump/$', views.trump_list, name='tweets_list'),
url(r'^cruz/$', views.cruz_list, name='tweets_list'),
url(r'^democrat/$', views.democrat_list, name='tweets_list'),
url(r'^republican/$', views.republican_list, name='tweets_list'),
]
<file_sep>#Tue Apr 19 17:35:07 MDT 2016
org.eclipse.core.runtime=2
org.eclipse.platform=4.4.0.v20140606-1215
<file_sep>from rest_framework import serializers
from api.objects import CandidateObject
from .models import *
class CandidateSerializer(serializers.Serializer):
candidate = serializers.CharField(required = True)
created_at = serializers.DateTimeField(required = True)
sentiment = serializers.FloatField(required = True)
text = serializers.CharField(required = True)
user = serializers.CharField(required = True)
tid = serializers.CharField(required = True)
def restore_object(self, attrs, instance = None):
if instance is not None:
instance.candidate = attrs.get('candidate', instance.candidate)
instance.created_at = attrs.get('created_at', instance.created_at)
instance.sentiment = attrs.get('sentiment', instance.sentiment)
instance.text = attrs.get('text', instance.text)
instance.user = attrs.get('user', instance.user)
instance.tid = attrs.get('tid', instance.tid)
return CandidateObject(**attrs)
<file_sep>import datetime
class CandidateObject(object):
candidate = 'Default'
created = datetime.datetime.now()
sentiment = 0
text = ''
def __init__(self, subject, content, **attrs):
if 'candidate' in attrs:
self.candidate = attrs['candidate']
if 'created_at' in attrs:
self.created = attrs['created_at']
if 'sentiment' in attrs:
self.sentiment = attrs['sentiment']
if 'text' in attrs:
self.text = attrs['text']
if 'user' in attrs:
self.user = attrs['user']
if 'tid' in attrs:
self.tid = attrs['tid']
self.candidate = candidate
self.created = created
self.sentiment = sentiment
self.text = text
self.user = user
self.tid = tid
<file_sep>CNN (Convolutional Neural Network) based text classifier, based off [this](http://arxiv.org/abs/1408.5882) and [this](https://github.com/flipkart-incubator/optimus), trained on 100k+ tweets with consistent accuracy of 84%.
# Model
Download [this](https://www.dropbox.com/s/umhp88624tomkm6/third.p?dl=0) (~700MB) and place in sample folder.
# Requirements:
- `sudo apt-get install unzip curl git gcc g++ python2.7 python-virtualenv build-essential python-dev python-setuptools libatlas-dev libatlas3gf-base gfortran libblas-dev liblapack-dev python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose`
- `pip install -U numpy scipy scikit-learn nltk; pip install theano flask gunicorn pandas; pip install -r requirements.txt`. Your scipy installation might be janky on ubuntu, just follow the error messages and google.
- Run `./downloadWordVecs.sh` (1.5 GB)
- Ready to go!
# Usage
Training:
Please use theano flags to fast-run this on a GPU. Saves the planet and your hair. Just prepend your python command with something like: `THEANO_FLAGS=mode=FAST_RUN,device=gpu`
`python train.py <model config file path> <training data file path> <file path to store classifier model> <true/false(preprocessing flag)>`
Testing:
`python test.py <model file path> <testing file path> <folder to store detailed output analysis> <preprocess? (true/false)> <load word vectors? (true/false)>`
Usage:
`import interface`
`predictTweet(“I love Theano”)`
`predictList([“I love Theano”, “I hate Theano”])`
Note, you can change the model used within interface.py.
| 8cc52071e05131594443b685e28353f5caf3a703 | [
"Markdown",
"Python",
"INI"
] | 6 | Python | collegebuff/Quitter-CSCI4448 | 471723e7c5625241bf4a281d93492700c1a1d5d6 | d1e691a369e4872ae4d3d8caaebeca6ee040ac64 |
refs/heads/main | <file_sep>class Solution {
public:
bool isValidBST_util(TreeNode* root, TreeNode *min, TreeNode *max){
if(root == NULL)
return true;
if(min !=NULL and root->val <= min->val)
return false;
if(max !=NULL and root->val >= max->val)
return false;
return isValidBST_util(root->left, min, root) && isValidBST_util(root->right, root, max);
}
bool isValidBST(TreeNode* root) {
return isValidBST_util(root, NULL, NULL);
}
};
<file_sep>vector<int> topKFrequent(vector<int>& nums, int k) {
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> min_heap;
unordered_map<int, int> occ;
for (int i =0; i < nums.size(); i++) {
occ[nums[i]]++;
}
auto itr = occ.begin();
while(itr != occ.end()) {
min_heap.push({itr->second, itr->first});
++itr;
if (k < min_heap.size()) {
min_heap.pop();
}
}
vector<int> result(k);
while (!min_heap.empty()) {
pair<int, int> element = min_heap.top();
min_heap.pop();
result[--k] = element.second;
}
return result;
}<file_sep>class Solution {
public:
int firstUniqChar(string s) {
map<char, int> charMap;
for(int i=0;i<s.length();i++) {
if(charMap.find(s[i]) != charMap.end()) {
charMap[s[i]] = s.length() + i;
} else {
charMap[s[i]] = i;
}
}
int minimum = INT_MAX;
map<char, int>:: iterator itr = charMap.begin();
for(;itr!=charMap.end();itr++) {
if(itr->second<s.length()&&itr->second < minimum) {
minimum = itr->second;
}
}
if(minimum == INT_MAX) return -1;
return minimum;
}
};
<file_sep>class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
bool isFound = false;
int val;
for(int i=0;i<nums1.size();i++) {
isFound = false;
val = nums1[i];
int j=0;
for(;j<nums2.size();j++) {
if(nums2[j] == nums1[i]) {
isFound = true;
}
if(isFound && nums2[j]>nums1[i]) {
nums1[i] = nums2[j];
break;
}
}
if(nums1[i] == val) {
nums1[i] = -1;
}
}
return nums1;
}
};<file_sep>class Solution {
public:
string removeOuterParentheses(string S) {
stack<char> st;
int numOfPops;
string target="";
int i=0;
while(i<S.length()) {
if(S[i]=='(') {
st.push('(');
if(st.size()>1) {
target+='(';
}
++i;
} else {
numOfPops = 0;
while(S[i]==')'&& st.size()>1) {
st.pop();
++numOfPops;
++i;
}
while(numOfPops>0) {
target+=')';
--numOfPops;
}
if(st.size()==1 && S[i]==')') {
st.pop();
++i;
}
}
}
return target;
}
};
<file_sep>class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if(heights.size()==0) {
return 0;
}
stack<int> bars;
int maxArea = -1, currentArea;
int i=0;
for(;i<heights.size();i++) {
if(bars.empty() || (heights[bars.top()] < heights[i])) {
bars.push(i);
}
else{
while(!bars.empty()&&heights[bars.top()] > heights[i]) {
int top = bars.top();
bars.pop();
if(bars.empty()) {
currentArea = heights[top]*i;
} else {
currentArea = heights[top] * (i - bars.top() -1);
}
if(currentArea > maxArea) {
// cout<<currentArea<<"***";
maxArea = currentArea;
}
}
bars.push(i);
}
}
while(!bars.empty()) {
int top = bars.top();
bars.pop();
if(bars.empty()) {
currentArea = heights[top]*i;
} else {
currentArea = heights[top] * (i - bars.top() -1);
}
if(currentArea > maxArea) {
maxArea = currentArea;
}
}
return maxArea;
}
};
//https://leetcode.com/problems/largest-rectangle-in-histogram/<file_sep>/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int sum;
bool hasLeftLeaf(TreeNode *r) {
if(!r->left&&!r->right) return true;
return false;
}
void sumOfLeftLeaf(TreeNode *root) {
if(!root) return;
if(root->left&&hasLeftLeaf(root->left)) {
sum+=root->left->val;
// cout<<"here for"<<root->left->val;
sumOfLeftLeaf(root->right);
} else {
sumOfLeftLeaf(root->left);
sumOfLeftLeaf(root->right);
}
}
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root || !root->left&&!root->right) return 0;
sum=0;
sumOfLeftLeaf(root);
return sum;
}
};
<file_sep>class Solution {
void rotateMat(vector<vector<int>> &matrix, int row, int rows, int col, int cols) {
if (row >= rows || col >= cols) {
return;
}
int temp;
for (int i = 0; i<(cols-col); i++) {
temp = matrix[row][col+i];
matrix[row][col+i] = matrix[rows-i][col];
matrix[rows-i][col] = matrix[rows][cols-i];
matrix[rows][cols-i] = matrix[row+i][cols];
matrix[row+i][cols] = temp;
}
rotateMat(matrix, row+1, rows-1, col+1, cols-1);
}
public:
void rotate(vector<vector<int>>& matrix) {
int row = 0, rows = matrix.size()-1, col = 0, cols = matrix[0].size()-1;
rotateMat(matrix, row, rows, col, cols);
return;
}
};<file_sep># Leetcode Problem Solutions
## Validate Stack Sequences
*Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack. This is from https://leetcode.com/problems/validate-stack-sequences/*
> Solution here: [stack-sequence](cpp/validateStackSequence.cpp)
## Next Greater Element I
*You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number. This is from https://leetcode.com/problems/next-greater-element-i/*
> Solution here: [next-greater-element](cpp/nextGreaterElement.cpp)
## Remove Outermost Parentheses
*A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. This is from https://leetcode.com/problems/remove-outermost-parentheses/*
> Solution here: [remove-parantheses](cpp/removeOuterMostParanthesis.cpp)
## Largest Rectangle in Histogram
*Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. This is from https://leetcode.com/problems/largest-rectangle-in-histogram/*
> Solution here: [rectangle-in-histogram](cpp/largestRectancleInHistogram.cpp)
## Daily Temperatures
*Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. This is from https://leetcode.com/problems/daily-temperatures/*
> Solution here: [daily-temperatures](cpp/dailyTemperature.cpp)
## Binary Search Tree Iterator
*Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. This is from https://leetcode.com/problems/binary-search-tree-iterator/*
> Solution here: [bst-iterator](cpp/treeIterator.cpp)
## Split Linked List in Parts
*Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".
The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.
The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later. This is from https://leetcode.com/problems/split-linked-list-in-parts/*
> Solution here: [split-linked-list](cpp/splitLinkedListInParts.cpp)
## Validate Binary Search Tree
*Given a binary tree, determine if it is a valid binary search tree (BST). This is from https://leetcode.com/problems/validate-binary-search-tree/*
> Solution here: [validate-bst](cpp/validateBinarySearchTree.cpp)
## Populating Next Right Pointers in Each Node
*Given a perfect binary tree, populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. This is from https://leetcode.com/problems/populating-next-right-pointers-in-each-node//*
> Solution here: [populate-next-pointer](cpp/populateNextPointer.cpp)
## Sum of left leaves
*Given a root of binary tree, return the sum of all left leaves. This is from https://leetcode.com/problems/sum-of-left-leaves/*
> Solution here: [sum-of-leaves](cpp/sumOfLeftLeaves.cpp)
## Tilt of Binary Tree
*Given the root of a binary tree, return the sum of every tree node's tilt.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if there the node does not have a right child. This is from https://leetcode.com/problems/binary-tree-tilt/*
> Solution here: [binary-tree-tilt](cpp/findTreeTilt.cpp)
## First Unique Charachter in a string
*Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. This is from: https://leetcode.com/problems/first-unique-character-in-a-string/*
> Solution here: [first-unique-charachter](cpp/uniqueCharachter.cpp)
## Design a Linked List
*Designing an implementation of Linked List. This is from: https://leetcode.com/problems/design-linked-list/*
> Solution here: [design-linked-list](cpp/designLinkedList.cpp)
## Top K frequent elements
*Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. This is from: https://leetcode.com/problems/top-k-frequent-elements/*
> Solution here: [top-k-elements](cpp/topKFrequentElements.cpp)
## Increasing Triplet Subsequence
*Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false. This is from: https://leetcode.com/problems/increasing-triplet-subsequence/*
> Solution here: [increasing-triplet](cpp/increasingTriplet.cpp)
## Rotate Image
*You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.This is from:https://leetcode.com/problems/rotate-image/*
> Solution here: [inline-rotation](cpp/rotateArray.cpp)
## Longest Palindromic Substring
*Given a string s, return the longest palindromic substring in s. A string is called a palindrome string if the reverse of that string is the same as the original string. This is from: https://leetcode.com/problems/longest-palindromic-substring*
> Solution here: [longest-palindromic-substring](cpp/longestPalindromeSubstring.cpp)
<file_sep>class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int n = nums.size();
vector<int> minLtoR(n);
vector<int> maxRtoL(n);
minLtoR[0] = nums[0];
for (int i = 1; i< n; i++) {
minLtoR[i] = min(minLtoR[i-1], nums[i]);
}
maxRtoL[n-1] = nums[n-1];
for (int i = n-2; i>-1; i--) {
maxRtoL[i] = max(maxRtoL[i+1], nums[i]);
}
for (int i=0; i < n; i++) {
if (minLtoR[i] < maxRtoL[i] && nums[i] != minLtoR[i] && nums[i] != maxRtoL[i])
return true;
}
return false;
}
};<file_sep>class Solution {
void print(vector<vector<int>> p, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
cout<<p[i][j]<<" ";
cout<<"\n";
}
}
public:
string longestPalindrome(string s) {
int n = s.length();
vector<vector<int>> LCS(n, vector<int>(n, 0));
int maxLength = 0;
string result = "";
for (int gap = 0; gap < n; gap++) {
for (int i=0; i < n-gap; i++) {
int j = i+gap;
if (gap == 0) {
LCS[i][j] = 1;
} else if (gap == 1) {
LCS[i][j] = (s[i] == s[j]);
} else {
LCS[i][j] = (s[i] == s[j] && (LCS[i+1][j-1] == 1));
}
if (LCS[i][j] == 1 && maxLength < gap+1) {
maxLength = gap+1;
result = s.substr(i, gap+1);
}
}
}
// print(LCS, n);
return result;
}
};<file_sep>class MyLinkedList {
struct Node {
int data;
Node *next;
Node *prev;
Node(int data) {
this->data = data;
this->next = NULL;
this->prev = NULL;
}
};
Node *head, *tail;
int size = 0;
Node* traverseFromHead(Node *head, int k) {
Node *tmp = head;
while(tmp && k>0) {
tmp = tmp->next;
--k;
}
return tmp;
}
public:
MyLinkedList() {
head = NULL;
tail = NULL;
size = 0;
}
int get(int index) {
if (index >= size) {
return -1;
}
Node *result = NULL;
result = traverseFromHead(head, index);
return result->data;
}
void addAtHead(int val) {
Node *newNode = new Node(val);
if (!head && !tail) {
head = newNode;
tail = head;
} else {
head->prev = newNode;
newNode->next = head;
head = newNode;
}
++size;
}
void addAtTail(int val) {
Node *newNode = new Node(val);
if (!head && !tail) {
head = newNode;
tail = head;
} else {
tail->next = newNode;
newNode->prev = tail;
tail = newNode;
}
++size;
}
void addAtIndex(int index, int val) {
if(index > size)
return;
if (index == 0) {
addAtHead(val);
return;
}
if (index == size) {
addAtTail(val);
return;
}
Node *result = NULL;
Node *newNode = new Node(val);
result = traverseFromHead(head, index);
newNode->prev =result->prev;
newNode->next = result;
if (result->prev) {
result->prev->next = newNode;
}
result->prev = newNode;
++size;
}
void deleteAtIndex(int index) {
if (index >= size)
return;
Node *result = NULL;
result = traverseFromHead(head, index);
if (result->prev)
result->prev->next = result->next;
if (result->next)
result->next->prev = result->prev;
if (index == 0)
head = head->next;
if (index == size -1) {
tail = tail->prev;
}
result->prev = NULL;
result->next = NULL;
delete(result);
--size;
}
};<file_sep>/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
int getLength(ListNode* head) {
int len =0;
while(head) {
head = head->next;
++len;
}
return len;
}
ListNode* findAt(ListNode* root, int pos) {
for(int i=0;i<pos;i++) {
root = root->next;
}
return root;
}
public:
vector<ListNode*> splitListToParts(ListNode* root, int k) {
vector<ListNode*> target;
int len = getLength(root);
int numOfNodes=1,extraNodes=0;
ListNode* ptr;
int i=0, addExtraNode;
if(k<len) {
numOfNodes= len/k;
extraNodes = len%k;
}
while(root) {
addExtraNode =0;
if(extraNodes>0) {
addExtraNode =1;
}
target.push_back(root);
ptr = findAt(root, numOfNodes+addExtraNode-1);
--extraNodes;
root = ptr->next;
ptr->next = NULL;
}
while(target.size()<k) {
target.push_back(NULL);
}
return target;
}
}; | a455d47bba6f19e390d8acd4cb62499767c7d33f | [
"Markdown",
"C++"
] | 13 | C++ | saloni1996/LeetCodeProblemSolutions | ba01f30b421f250d87ef92bd79879b027ce68dde | 84aa4e342c05ed32a6f39fa8a44212c215d4bed4 |
refs/heads/master | <repo_name>McCollum-A/PersonalWebsiteMccollum-A<file_sep>/BlogApp/models.py
from django.db import models
# Create your models here.
class Blog(models.Model):
BlogImage = models.ImageField(verbose_name="Title image for post", upload_to='BlogImages/')
BlogTitle = models.CharField(verbose_name="Blog title",max_length=100)
BlogPubDate = models.DateField(verbose_name="Publish date")
BlogCopy = models.TextField(verbose_name="Blog article content")
def SummaryTextLimit(self):
LimitChar = int((225-len(" ... Read More")))
LimitRead = self.BlogCopy
if len(LimitRead) > LimitChar:
while LimitRead[LimitChar] != ' ':
LimitChar -= 1
return self.BlogCopy[:LimitChar] + " ... Read More"
else:
return self.BlogCopy
def __str__(self):
return self.BlogTitle
<file_sep>/CreatedWorksApp/models.py
from django.db import models
class Works(models.Model):
StepFilter = "All"
WorksImage = models.ImageField(verbose_name="Project title image", upload_to='WorksImages/')
WorksImage2nd = models.ImageField(verbose_name="Second supporting image", upload_to='WorksImages/', default="null")
WorksImage3rd = models.ImageField(verbose_name="Third supporting image", upload_to='WorksImages/', default="null")
WorksTitle = models.CharField(verbose_name="Project title and name", max_length=100, default="Work Title")
WorksSummary = models.CharField(verbose_name="Brief project description", max_length=150, default="Enter home view tag")
WorksContent = models.TextField(verbose_name="Full project article", default="Enter content here")
class WorksFilterType(models.TextChoices):
DEVELOPMENT = 'Development'
ARTORDESIGN = 'ArtorDesign'
WorksFilterTypeChar = models.CharField(
max_length=13,
choices=WorksFilterType.choices,
default=WorksFilterType.DEVELOPMENT,
verbose_name="Content type for filter"
)
def __str__(self):
return self.WorksTitle
class Meta:
verbose_name = "Current project" # for some reason Django tacks an "s" on the end
<file_sep>/PortfolioApp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.allportfolio, name='allportfolio'),
path('<int:Portfolio_id>/', views.portfoliodetail, name='portfoliodetail')
]
<file_sep>/BlogApp/views.py
from django.shortcuts import render, get_object_or_404
from .models import Blog
# Create your views here.
def allblogs(request):
AllBlogs = Blog.objects.all()
return render(request, 'BlogApp/AllBlogs.html', {'AllBlogs': AllBlogs})
def blogentire(request, Blog_id):
BlogEntire = get_object_or_404(Blog, pk=Blog_id)
return render(request, 'BlogApp/Entire.html', {'BlogEntire': BlogEntire})
<file_sep>/PortfolioApp/views.py
from django.shortcuts import render, get_object_or_404
from .models import Portfolio
# Create your views here.
def allportfolio(request):
AllPortfolio = Portfolio.objects.all()
return render(request, 'PortfolioApp/allportfolio.html', {'AllPortfolio': AllPortfolio})
def portfoliodetail(request, Portfolio_id):
PortfolioDetail = get_object_or_404(Portfolio, pk=Portfolio_id)
return render(request, 'PortfolioApp/Detail.html', {'PortfolioDetail': PortfolioDetail})
<file_sep>/PortfolioApp/models.py
from django.db import models
class Portfolio(models.Model):
PortfolioImage = models.ImageField(verbose_name="Project title image", upload_to='PortfioloImages/')
PortfolioSummary = models.TextField(verbose_name="Project summary, single view", default="Explain the piece here")
PortfolioTitle = models.CharField(verbose_name="Project title or name", max_length=100, default="Project Title")
PortfolioTag = models.CharField(verbose_name="Project tag for gallery view", max_length=150)
PortfolioItemDate = models.CharField(verbose_name="Year of completion", max_length=9, default="2020")
class Meta:
verbose_name="Portfolio piece"
def __str__(self):
return self.PortfolioTitle
<file_sep>/CreatedWorksApp/views.py
from django.shortcuts import render, get_object_or_404
from .models import Works
# Create your views here.
def home(request):
AllWorks = Works.objects.all()
return render(request, 'CreatedWorksApp/home.html', {'AllWorks': AllWorks})
def projectabstract(request, Works_id):
ProjectAbstract = get_object_or_404(Works, pk=Works_id)
return render(request, 'CreatedWorksApp/Abstract.html', {'ProjectAbstract': ProjectAbstract})
<file_sep>/CreatedWorksApp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('<int:Works_id>/', views.projectabstract, name='projectabstract')
]
| 3c4d917993d8344c4532bfbc7ed7e9e9a8f37d93 | [
"Python"
] | 8 | Python | McCollum-A/PersonalWebsiteMccollum-A | 1c6984e523d32110330e5eb8947e75825e545d97 | 6ed51982d92b6bc9ac31cfe72b7776f533f62e93 |
refs/heads/master | <file_sep>package test;
import java.util.*;
public class Test1 {
public static Set<Class> getallDep(Class source){
Queue<Class> queue=new LinkedList<>();
queue.add(source);
Set<Class> visited=new HashSet<>();
while(!queue.isEmpty()){
Class cla=queue.poll();
List<Class> l=getAdj(cla);
visited.add(cla);
for(Class c:l){
if(!visited.contains(c)){
queue.add(c);
}
}
}
return visited;
}
private static List<Class> getAdj(Class cla) {
Class[] arr=cla.getInterfaces();
List<Class> list=new ArrayList<>();
for(Class c:arr){
list.add(c);
}
Class super1=cla.getSuperclass();
if(super1!=null && super1!=cla){
list.add(super1);
}
return list;
}
public static int[] merge(int[] a,int[] b){
int[]arr=new int[a.length+b.length];
int curr=0;
int as=0;
int bs=0;
while(as<a.length && bs < b.length){
if(a[as]<=b[bs]){
arr[curr++]=a[as++];
}else {
arr[curr++]=b[bs++];
}
}
while(as<a.length){
arr[curr++]=a[as++];
}
while(bs<b.length){
arr[curr++]=b[bs++];
}
return arr;
}
public static List<Integer> common(int[] a, int[] b){
//int[]arr=new int[a.length+b.length];
List<Integer> list=new ArrayList<>();
int curr=0;
int as=0;
int bs=0;
while(as<a.length && bs < b.length){
if(a[as]==b[bs]){
list.add(a[as]);
as++;
bs++;
}else if(a[as]<b[bs]){
as++;
}else {
bs++;
}
}
return list;
}
public static void main(String[] args) {
/**
List<Integer> res=common(new int[]{1,5,20},new int[]{5,11,25});
for(int i:res){
System.out.println(i);
}
*/
Set<Class> set=getallDep(TreeMap.class);
for(Class c:set){
System.out.println(c.getName());
}
}
}
<file_sep>package lc192;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
/**
* Two pointers.Check if pointers dont exceed bounds
*
*/
class BrowserHistory {
String homepage;
int c=-1;
int max=0;
List<String> history=new ArrayList<>();
public BrowserHistory(String homepage) {
this.homepage=homepage;
history.add(homepage);
c++;
}
public void visit(String url) {
c++;
max=c;
history.add(c,url);
}
public String back(int steps) {
//why c+1
int n=Math.min(steps,c+1);
c=c-n;
if(c<0){
c=0;
}
return history.get(c);
}
public String forward(int steps) {
int n=Math.min(steps,max-c);
if(n>history.size()-1){
n=history.size()-1;
}
c=c+n;
return history.get(c);
}
public static void main(String[] args) {
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.
browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7); //
}
}
<file_sep>package top100interview;
public class WordSearch {
public static void main(String[] args) {
WordSearch ws=new WordSearch();
char[][]board={{'A','B','C','E'},{'S','F','E','S'},{'A','D','E','E'}};
System.out.println(ws.exist(board,"ABCESEEEFS"));
}
boolean[][] visited;
public boolean exist(char[][] board, String word) {
if(word==null || word.trim().equals(""))return false;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
visited=new boolean[board.length][board[0].length];
if(dfs(board,word,i,j,0)){
return true;
}
}
}
return false;
}
boolean dfs(char[][] b,String word,int r, int c,int wpos){
if(wpos==word.length())return true;
if(r<0||r>=b.length||c<0|| c>=b[0].length|| visited[r][c])return false;
if(b[r][c]!=word.charAt(wpos))return false;
//return dfs(b,word,r,c,wpos+1);
wpos++;
visited[r][c]=true;
return dfs(b,word,r-1,c,wpos)
||dfs(b,word,r+1,c,wpos)
||dfs(b,word,r,c+1,wpos)
||dfs(b,word,r,c-1,wpos);
}
}
<file_sep>
package dp;
public class SameString {
public static void main(String[] args) {
}
static int dp1(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int l = 1; l < n; ++l)
{
for (int i = 0; i < n - l; ++i)
{
int j = i + l;
if (s.charAt(i) == s.charAt(j))
{
dp[i][j] = 0;
} else {
dp[i][j] = 0 /*code*/;
}
}
}
return 6;
}
}
<file_sep>package amazon.arrays;
/**
* https://leetcode.com/explore/interview/card/amazon/76/array-and-strings/2963/https://leetcode.com/explore/interview/card/amazon/76/array-and-strings/2963/
*/
public class ContainerWithMostWater {
public static void main(String[] args) {
int[] arr={1,1};
System.out.println(maxArea(arr));
}
/**
* start from left .find the highest index
* start from right find the hoghest index .
* Calculate the area.
* then move the pointers outward to get the max area
*/
public static int maxArea(int[] h) {
int max=Integer.MIN_VALUE;
for(int i=0;i<h.length-1;i++){
for(int j=i+1;j<h.length;j++){
int w=j-i;
int hi=Math.min(h[i],h[j]);
max=Math.max(max,hi);
}
}
return max;
}
}
<file_sep>public class Fibonacci {
int[] arr=new int[100];
//n=3
//fib(2) + fib(1)=1+2=2
// fib(2)=fib(0)+fib(1)=0+1=1
int fibRecursive(int n) {
System.out.println(n);
if(n<=0)throw new RuntimeException();
if( n==1){
return 0;
}
if(n==2){
return 1;
}
return fibRecursive(n-1)+fibRecursive(n-2);
}
void fibIterative(int n){
int counter=2;
int num1=0;
int num2=1;
if(n==0)return;
if(n>0 ) {
System.out.println(num1);
}
if(n>1) {
System.out.println(num2);
}
while(counter<n){
int num3 =num1+num2;
System.out.println(num3);
num1=num2;
num2=num3;
counter++;
}
}
public static void main(String[] args) {
Fibonacci fibonacci=new Fibonacci();
fibonacci.fibIterative(10);
System.out.println("recursive="+fibonacci.fibRecursive(10));
//hello
//
}
}
<file_sep>package graph;
//https://leetcode.com/problems/number-of-provinces/
/**
* There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b,
* and city b is connected directly with city c, then city a is connected indirectly with city c.
*
* A province is a group of directly or indirectly connected cities and no other cities outside of the group.
*
* You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected,
* and isConnected[i][j] = 0 otherwise.
*
* Return the total number of provinces.
*/
public class NumberOfProvinces {
}
<file_sep>package dp;
import java.util.HashMap;
import java.util.Map;
public class CoinChange {
int[] coins={5,1,2,10,25};
Map<Integer,Integer> map=new HashMap<>();
int[] dp;
public static void main(String[] args) {
CoinChange c = new CoinChange();
int target=10;
System.out.println(c.pattern(target));
}
/**
* for (int i = 1; i <= target; ++i) {
* for (int j = 0; j < ways.size(); ++j) {
* if (ways[j] <= i) {
* dp[i] = min(dp[i], dp[i - ways[j]] + cost / path / sum) ;
* }
* }
* }
*/
private int pattern (int target){
int ways=0;
dp=new int[target+1];
for(int i=1;i<=target;i++){
for(int j=0;j<coins.length;j++){
int way=coins[j];
if(way<=i){
dp[i]+= (i-way)==0?1:dp[i-way];
}
}
}
return dp[target];
}
private int change(int t) {
if(t==0)return 1;
if(t<0)return 0;
int sum=0;
Integer cache=map.get(t);
if(cache!=null)return map.get(t);
for(int i=0;i<coins.length;i++){
sum+=change(t-coins[i]);
}
map.put(t,sum);
return sum;
}
}
<file_sep>package lc191;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CheckBinaryCodesInAString {
public static void main(String[] args) {
System.out.println(hasAllCodes("00110",2));
}
public static boolean hasAllCodes(String s, int k) {
Map<String,Integer> codes=new HashMap<>();
int cur=0;
while(cur+k<=s.length()){
String str=s.substring(cur,cur+k);
codes.compute(str,(key,v)->v==null?1:v+1);
cur++;
}
int n= (int) Math.pow(2,k);
return n==codes.size();
}
}
<file_sep>package amazon;
/**
* https://leetcode.com/problems/flood-fill/
*/
public class FloodFill {
int tr;
int tc;
boolean[][]visited;
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
tr=image.length;
tc=image[0].length;
int oc=image[sr][sc];
visited=new boolean[tr][tc];
dfs(image,sr,sc,newColor,oc);
return image;
}
void dfs(int[][] image,int sr,int sc,int nc,int oc){
if(sr<0||sr>=tr||sc<0||sc>=tc||visited[sr][sc] )return;
visited[sr][sc]=true;
if(image[sr][sc]!=oc){
}else {
image[sr][sc]=nc;
}
if(sc-1>=0 && image[sr][sc-1]==oc)
{
dfs(image,sr,sc-1,nc,oc);
}
if(sc+1 <tc && image[sr][sc+1]==oc){
dfs(image,sr,sc+1,nc,oc);
}
if(sr+1 < tr && image[sr+1][sc]==oc){
dfs(image,sr+1,sc,nc,oc);
}
if(sr-1 >=0 && image[sr-1][sc]==oc) {
dfs(image,sr-1,sc,nc,oc);
}
}
}
| f22ef49b82fac3662b2375800a9fa986d17995f7 | [
"Java"
] | 10 | Java | sinharahul/codinginterview | aa91ff06337c05b288fff082c2234567db688925 | 40298024eea368539e2821e525f226e05968ab72 |
refs/heads/main | <repo_name>Tornado62/warplanes<file_sep>/Warplanes/Assets/WavingGrass/Scripts/moved.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class moved : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
public float move = 10f;
public float rotate = 50f;
public float up = 10f;
// Update is called once per frame
void Update()
{
if (Input.GetKey("w"))
{
transform.Translate(-Vector3.forward * move * Time.deltaTime);
}
if (Input.GetKey("s"))
{
transform.Translate(Vector3.forward * 5 * Time.deltaTime);
}
if (Input.GetKey("a"))
{
transform.Rotate(Vector3.up, -rotate * Time.deltaTime);
}
if (Input.GetKey("d"))
{
transform.Rotate(Vector3.up, rotate * Time.deltaTime);
}
if (Input.GetKey("r"))
{
transform.Rotate(Vector3.left, -rotate * Time.deltaTime);
}
if (Input.GetKey("f"))
{
transform.Rotate(Vector3.left, rotate * Time.deltaTime);
}
}
} | 1c553081c724850ddce5cdcfc2d28ce8fa885e29 | [
"C#"
] | 1 | C# | Tornado62/warplanes | a918b4b1087a2dfff5e9d01d5734b210b25c7097 | e34d04d8ad013162436aea66cc77fc95d478db61 |
refs/heads/master | <repo_name>lastmjs/mwad-functional-element<file_sep>/elements/calc-button.ts
import { html, customElement } from 'functional-element';
customElement('calc-button', ({ constructing, text }) => {
if (constructing) {
return {
text: ''
};
}
return html`
<style>
.number-button {
display: flex;
align-items: center;
text-align: center;
justify-content: center;
border: solid 1px black;
cursor: pointer;
font-size: calc(20px + 1vmin);
height: 100%;
}
</style>
<div class="number-button">${text}</div>
`;
});<file_sep>/README.md
# mwad-functional-element<file_sep>/elements/calc-screen.ts
import { html, customElement } from 'functional-element';
customElement('calc-screen', ({ constructing, screenValue }) => {
if (constructing) {
return {
screenValue: ''
};
}
return html`
<style>
.screen {
border: solid 1px black;
text-align: right;
font-size: calc(25px + 1vmin);
height: 100%;
}
</style>
<div class="screen">${screenValue}</div>
`;
});<file_sep>/elements/calc-buttons.ts
import { html, customElement } from 'functional-element';
import './calc-button';
customElement('calc-buttons', ({ element }) => {
return html`
<style>
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
height: 100%;
}
.button-column {
display: flex;
flex-direction: column;
}
calc-button {
flex: 1;
}
</style>
<div class="button-grid">
<div class="button-column">
<calc-button
@click=${() => addCharacter('7', element)}
.text=${'7'}
></calc-button>
<calc-button
@click=${() => addCharacter('4', element)}
.text=${'4'}
></calc-button>
<calc-button
@click=${() => addCharacter('1', element)}
.text=${'1'}
></calc-button>
<calc-button
@click=${() => addCharacter('0', element)}
.text=${'0'}
></calc-button>
</div>
<div class="button-column">
<calc-button
@click=${() => addCharacter('8', element)}
.text=${'8'}
></calc-button>
<calc-button
@click=${() => addCharacter('5', element)}
.text=${'5'}
></calc-button>
<calc-button
@click=${() => addCharacter('2', element)}
.text=${'2'}
></calc-button>
<calc-button
@click=${() => addCharacter('.', element)}
.text=${'.'}
></calc-button>
</div>
<div class="button-column">
<calc-button
@click=${() => addCharacter('9', element)}
.text=${'9'}
></calc-button>
<calc-button
@click=${() => addCharacter('6', element)}
.text=${'6'}
></calc-button>
<calc-button
@click=${() => addCharacter('3', element)}
.text=${'3'}
></calc-button>
<calc-button
@click=${() => calculate(element)}
.text=${'='}
></calc-button>
</div>
<div class="button-column">
<calc-button
@click=${() => clear(element)}
.text=${'clear'}
></calc-button>
<calc-button
@click=${() => addCharacter('*', element)}
.text=${'*'}
></calc-button>
<calc-button
@click=${() => addCharacter('/', element)}
.text=${'/'}
></calc-button>
<calc-button
@click=${() => addCharacter('+', element)}
.text=${'+'}
></calc-button>
<calc-button
@click=${() => addCharacter('-', element)}
.text=${'-'}
></calc-button>
</div>
</div>
`;
});
function addCharacter(character, element) {
element.dispatchEvent(new CustomEvent('character', {
detail: {
character
}
}));
}
function calculate(element) {
element.dispatchEvent(new CustomEvent('calculate'));
}
function clear(element) {
element.dispatchEvent(new CustomEvent('clear'));
}<file_sep>/elements/calc-app.ts
import { html, customElement } from 'functional-element';
import './calc-screen';
import './calc-buttons';
customElement('calc-app', ({ constructing, update, screenValue, resizeListenerSet }) => {
if (!resizeListenerSet) {
window.addEventListener('resize', () => {
update();
});
}
if (constructing) {
return {
screenValue: '',
resizeListenerSet: true
};
}
const desktopScreen = window.matchMedia('(min-width: 1024px)').matches;
return html`
<style>
.main-grid-container {
display: grid;
grid-template-rows: 10% 90%;
width: ${desktopScreen ? '80%' : '100%'};
height: ${desktopScreen ? '80%' : '100%'};
padding-right: ${desktopScreen ? '10%' : '0'};
padding-left: ${desktopScreen ? '10%' : '0'};
}
</style>
<div class="main-grid-container">
<calc-screen .screenValue=${screenValue}></calc-screen>
<calc-buttons
@character=${(e) => update(addToScreen(screenValue, e.detail.character))}
@calculate=${() => update(calculate(screenValue))}
@clear=${() => update({ screenValue: '' })}
>
</calc-buttons>
</div>
`;
});
function addToScreen(screenValue, newValue) {
return {
screenValue: screenValue === 'Syntax error' ? newValue : `${screenValue}${newValue}`
};
}
function calculate(screenValue) {
try {
const result = eval(screenValue);
return {
screenValue: result
};
}
catch(error) {
return {
screenValue: 'Syntax error'
};
}
} | c4bc284c362cb423dff018ecbe001da43427b30e | [
"Markdown",
"TypeScript"
] | 5 | TypeScript | lastmjs/mwad-functional-element | c6d28de65506908cba531a4b7a7657a9a888a79c | 0a8a7690542eec52d986b0c5fb4063a822ee3e8c |
refs/heads/main | <file_sep># php
Inicio Projetos
| f22df942c7b1e3a0f5027e7ebb9844ffacdb64d2 | [
"Markdown"
] | 1 | Markdown | PedroRNeto/php | a9f24923e364eab5fb4399c82764f00bc72bf81e | 090761903d7965cbe193c07256697904b616487d |
refs/heads/master | <file_sep># Avoiding common attacks.
## Reentry attack
To avoid reentry attack, i ensured before fund transfer to someone who fulfils the JobBounty.
His submission has been accepted set to true by the issuer and the bounty status is set to accepted.
Then funds is transfered.
<file_sep>var JobBounty = artifacts.require("./JobBounty.sol");
module.exports = function(deployer) {
deployer.deploy(JobBounty);
};<file_sep>const JobBounty = artifacts.require("./JobBounty.sol");
const getCurrentTime = require('./utils/time').getCurrentTime;
const assertRevert = require('./utils/assertRevert').assertRevert;
const dayInSeconds = 86400;
const increaseTimeInSeconds = require('./utils/time').increaseTimeInSeconds;
contract('JobBounty', function(accounts) {
let jobBountyInstance;
beforeEach(async() => {
jobBountyInstance = await JobBounty.new()
});
it("Should allow a user to issue a new job bounty", async() => {
let time = await getCurrentTime()
let tx = await jobBountyInstance.issueBounty("data",
time + (dayInSeconds * 2), { from: accounts[0], value: 500000000000 });
assert.strictEqual(tx.receipt.logs.length, 1, "issueBounty() call did not log 1 event");
assert.strictEqual(tx.logs.length, 1, "issueBounty() call did not log 1 event");
const logBountyIssued = tx.logs[0];
assert.strictEqual(logBountyIssued.event, "BountyIssued", "issueBounty() call did not log event BountyIssued");
assert.strictEqual(logBountyIssued.args.bounty_id.toNumber(), 0, "BountyIssued event logged did not have expected bounty_Id");
assert.strictEqual(logBountyIssued.args.issuer, accounts[0], "BountyIssued event logged did not have expected issuer");
assert.strictEqual(logBountyIssued.args.amount.toNumber(), 500000000000, "BountyIssued event logged did not have expected amount");
});
it("Should return an integer when calling issueBounty", async() => {
let time = await getCurrentTime()
let result = await jobBountyInstance.issueBounty.call("data",
time + (dayInSeconds * 2), { from: accounts[0], value: 500000000000 });
assert.strictEqual(result.toNumber(), 0, "issueBounty() call did not return correct id");
});
it("Should not allow a user to issue a bounty without sending ETH", async() => {
let time = await getCurrentTime()
assertRevert(jobBountyInstance.issueBounty("data",
time + (dayInSeconds * 2), { from: accounts[0] }), "Bounty issued without sending ETH");
});
it("Should not allow a user to issue a bounty when sending value of 0", async() => {
let time = await getCurrentTime()
assertRevert(jobBountyInstance.issueBounty("data",
time + (dayInSeconds * 2), { from: accounts[0], value: 0 }), "Bounty issued when sending value of 0");
});
it("Should not allow a user to issue a bounty with a deadline in the past", async() => {
let time = await getCurrentTime()
assertRevert(jobBountyInstance.issueBounty("data",
time - 1, { from: accounts[0], value: 0 }), "Bounty issued with deadline in the past");
});
it("Should not allow a user to issue a bounty with a deadline of now", async() => {
let time = await getCurrentTime()
assertRevert(jobBountyInstance.issueBounty("data",
time, { from: accounts[0], value: 0 }), "Bounty issued with deadline of now");
});
it("Should not allow a user to fulfil an existing bounty where the deadline has passed", async() => {
let time = await getCurrentTime()
await jobBountyInstance.issueBounty("data",
time + (dayInSeconds * 2), { from: accounts[0], value: 500000000000 });
await increaseTimeInSeconds((dayInSeconds * 2) + 1)
assertRevert(jobBountyInstance.fulfillBounty(0, "data", { from: accounts[1] }), "Fulfillment accepted when deadline has passed");
});
});<file_sep>import React, { Component } from "react";
import JobBountyContract from "./contracts/JobBounty.json";
import getWeb3 from "./utils/getWeb3";
// eslint-disable-next-line
import { setJSON, getJSON } from './utils/IPFS.js';
import Container from 'react-bootstrap/Container';
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import Button from 'react-bootstrap/Button';
import Table from 'react-bootstrap/Table';
import Jumbotron from 'react-bootstrap/Jumbotron';
import "./App.css";
const etherscanBaseUrl = "https://rinkeby.etherscan.io";
const ipfsBaseUrl = "https://ipfs.infura.io/ipfs";
class App extends Component {
constructor(props) {
super(props)
this.state = {
jobBountiesInstance: undefined,
bountyAmount: undefined,
bountyData: undefined,
bountyDescription: undefined,
bountyDeadline: undefined,
etherscanLink: "https://rinkeby.etherscan.io",
bounties: [],
account: null,
web3: null
}
this.handleIssueBounty = this.handleIssueBounty.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount = async() => {
try {
// Get network provider and web3 instance.
const web3 = await getWeb3();
// Use web3 to get the user's accounts.
const accounts = await web3.eth.getAccounts();
// Get the contract instance.
const networkId = await web3.eth.net.getId();
const deployedNetwork = JobBountyContract.networks[networkId];
const instance = new web3.eth.Contract(
JobBountyContract.abi,
deployedNetwork && deployedNetwork.address,
);
// Set web3, accounts, and contract to the state, and then proceed with an
// example of interacting with the contract's methods.
// this.setState({ web3, accounts, contract: instance }, this.runExample);
this.setState({ jobBountiesInstance: instance, web3: web3, account: accounts[0] });
this.addEventListener(this);
} catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
}
};
handleChange(event) {
switch (event.target.name) {
case "bountyData":
this.setState({ "bountyData": event.target.value });
break;
case "bountyDescription":
this.setState({ "bountyDescription": event.target.value });
break;
case "bountyDeadline":
this.setState({ "bountyDeadline": event.target.value });
break;
case "bountyAmount":
this.setState({ "bountyAmount": event.target.value });
break;
default:
break;
}
}
async handleIssueBounty(event) {
if (typeof this.state.jobBountiesInstance !== 'undefined') {
event.preventDefault();
const ipfsHash = await setJSON({ bountyData: this.state.bountyData });
let result = await this.state.jobBountiesInstance.methods.issueBounty(ipfsHash, this.state.bountyDescription, this.state.bountyDeadline).send({ from: this.state.account, value: this.state.web3.utils.toWei(this.state.bountyAmount, 'ether') })
this.setLastTransactionDetails(result)
}
}
setLastTransactionDetails(result) {
if (result.tx !== 'undefined') {
this.setState({ etherscanLink: etherscanBaseUrl + "/tx/" + result.tx });
} else {
this.setState({ etherscanLink: etherscanBaseUrl });
}
}
addEventListener(component) {
this.state.jobBountiesInstance.events.BountyIssued({ fromBlock: 0, toBlock: 'latest' })
.on('data', async function(event) {
//First get the data from ipfs and add it to the event
var ipfsJson = {}
try {
ipfsJson = await getJSON(event.returnValues.data);
} catch (e) {}
if (ipfsJson.bountyData !== undefined) {
event.returnValues['bountyData'] = ipfsJson.bountyData;
event.returnValues['ipfsData'] = ipfsBaseUrl + "/" + event.returnValues.data;
} else {
event.returnValues['ipfsData'] = "none";
event.returnValues['bountyData'] = event.returnValues['data'];
}
var newBountiesArray = component.state.bounties.slice()
newBountiesArray.push(event.returnValues)
component.setState({ bounties: newBountiesArray })
}).on('error', console.error);
}
render() {
if (!this.state.web3) {
return <div > Loading Web3, accounts, and contract... < /div>;
}
return ( <
div className = "App" >
<
Navbar collapseOnSelect expand = "lg"
variant = "light"
bg = "light" >
<
Navbar.Brand href = "#home" > Job Bounty < /Navbar.Brand> <
Navbar.Toggle / >
<
Navbar.Collapse id = "responsive-navbar-nav" >
<
Nav className = "ml-auto" >
<
Nav.Link href = "#features" > Home < /Nav.Link> < /
Nav > <
Nav >
<
Nav.Link href = "#deets" > About < /Nav.Link>< /
Nav > <
/Navbar.Collapse> < /
Navbar >
<
Jumbotron fluid >
<
Container >
<
h1 > Post | Submit | Bounties. < /h1> <br / > <
p >
This is a decentralized blockchain platform where one posts job bounty
for another person to do and get bounties or compensations, don 't be left out. < /
p > < /
Container > <
/Jumbotron> <
Container >
<
Row >
<
Col >
<
a href = { this.state.etherscanLink }
target = "_blank"
rel = "noopener noreferrer" > Recent Transaction Details < /a> < /
Col > <
/Row> <
br / >
<
Form onSubmit = { this.handleIssueBounty } >
<
Form.Group as = { Row }
controlId = "issueBounty" >
<
Form.Label column sm = "2" >
Issue Bounty <
/Form.Label> <
Col sm = "10" >
<
Form.Control type = "issueBounty"
name = "issueBounty"
value = { this.state.bountyData }
onChange = { this.handleChange }
placeholder = "Issue a job bounty" / >
<
/Col> < /
Form.Group >
<
Form.Group as = { Row }
controlId = "descriptionOfJobBounty" >
<
Form.Label column sm = "2" >
Description of bounty <
/Form.Label> <
Col sm = "10" >
<
Form.Control type = "text"
placeholder = "Description of the job bounty"
value = { this.state.bountyDescription }
onChange = { this.handleChange }
/ > < /
Col > < /
Form.Group >
<
Form.Group as = { Row }
controlId = "bountyDeadline" >
<
Form.Label column sm = "2" >
Deadline of bounty <
/Form.Label> <
Col sm = "10" >
<
Form.Control type = "text"
placeholder = "Time in seconds since epoch"
value = { this.state.bountyDeadline }
onChange = { this.handleChange }
/ > < /
Col > < /
Form.Group >
<
Form.Group as = { Row }
controlId = "bountyAmount" >
<
Form.Label column sm = "2" >
Amount of bounty <
/Form.Label> <
Col sm = "10" >
<
Form.Control type = "text"
placeholder = "Amount of bounty"
value = { this.state.bountyAmount }
onChange = { this.handleChange }
/ > < /Col > < /
Form.Group >
<
/Form>
<
br / >
<
Button variant = "primary"
type = "submit"
block >
Submit <
/Button>
<
br / >
<
hr / >
<
br / >
<
Table data = { this.state.bounties }
striped bordered hover >
<
thead >
<
tr >
<
th dataField = 'bounty_id' > ID < /th> <
th dataField = 'issuer' > Issuer < /th> <
th dataField = 'amount' > Amount < /th> <
th dataField = 'data' > Bounty Description < /th> <
th > Action < /th> < /tr > < /thead> <
tbody >
<
tr >
<
td > 0 < /td> <
td > 0x1234566 < /td> <
td > 1000000000 < /td> <
td > Saving data to ipfs < /td> <
td >
<
Button variant = "secondary" > View < /Button> <
Button variant = "warning" > Update < /Button> <
Button variant = "danger" > Delete < /Button> < /
td > < /
tr > < /
tbody > < /
Table > <
/
Container > <
/
div >
);
}
}
export default App;<file_sep># JobBounty
This is a bounty dApp where people can post or submit work.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. Run to compile the contract but ensure ganache is running in the background for local testing.
```
Truffle compile
```
Then
```
Truffle migrate --network rinkeyby
```
### Prerequisites
You need to have ganache cli or ganache app which comes in the truffle suit, and npm installed,
You can run ganache-cli in the terminal or open the ganache app
```
ganache-cli
```
Copy the genrated Mnemonic
Helps in Registration/login into matamask
### Installing
You can install project dependencies from the root directory
```
npm install
```
To run the application frontend,
```
cd client
npm install
npm run start
```
## Running the tests
You run tests on the root directory using truffle
### Break down into end to end tests
These tests the smart contracts methods
```
truffle test
```
## Deployment
The smart contract and frontend application is hosted on etherscan, github and heruko.
* [Etherscan](https://rinkeby.etherscan.io/) - To help track transactions and test net for the contracts
* [Github](https://github.com/otim22/JobBounty) - Repository for my code
* [Heruko]() - Live front app
## Built With
* [Truffle](https://www.trufflesuite.com/) - Tool for smart contract
* [Mythx](https://mythx.io/) - For security check
* [Metamask](https://metamask.io/) - For the browser interaction, this is a chrome extension.
* [React-bootstrap](https://react-bootstrap.github.io/) - The Frontend framework used
## Authors
* **<NAME>** - *Initial work* - [JobBounty](https://github.com/otim22/JobBounty)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
* [Consensys Academy](https://consensys.net/academy/) - For Delivering the course
* [African Blockchain Allaince](https://afriblockchain.org/) - For mediating the course
* [Cryptosavannah](https://cryptosavannah.com/) - For the logistics and support.
* My mentor @joshorig - For the priceless information he shared.<file_sep># Desisn pattern decisions
## Circuit Breaker
Used a circuit breaker pattern to help me incase of a bug crisis such that i can suppend the application so that it can be accessed and managed by an administrator of the system.
| 054b87a7dd8a69f4eaa14ae8c1ae65178779d1e4 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | otim22/JobBounty | 455250c509041c5d6b7867e7028ef83a5122b9f3 | 94eced9b8c91b9523f159e5c2c01f4016096196e |
refs/heads/master | <file_sep>import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.linear_model import SGDRegressor
import LinearReg as lreg
import functions as fx
from sklearn.model_selection import train_test_split
m = 1000
x = 5*np.random.rand(m,1)
y = 6 + 7*x + 0.1*np.random.randn(m,1)
X = np.c_[np.ones((m,1)), x]
# Train and test split
train_size = 0.8
test_size = 1 - train_size
X_train, X_test, Y_train, Y_test = train_test_split(X, y, train_size=train_size,test_size=test_size)
# SGD parameters
eta = 0.01
lamb = 0.001
epochs = 10000
batch_size = 300
def test_SGD_OLS_beta():
lr = lreg.LinearReg(eta = eta, lamb=0.0, eta_type ='linear',eta_scal=True)
_, _, _, beta_SGD, _ = lr.fit(X_train, Y_train, X_test, Y_test, Niter=epochs,batch_size=batch_size, solver='sgd')
SGD_sk = SGDRegressor(max_iter = epochs, penalty=None, alpha=0.0, eta0=eta,fit_intercept=False)
SGD_sk.fit(X_train,Y_train.ravel())
assert np.all(abs(beta_SGD.T - SGD_sk.coef_) < 0.25)
def test_SGD_Ridge_beta():
lr = lreg.LinearReg(eta = eta, lamb=lamb, eta_type ='linear',eta_scal=True)
_, _, _, beta_SGD, _ = lr.fit(X_train, Y_train, X_test, Y_test, Niter=epochs,batch_size=batch_size, solver='sgd')
SGD_sk = SGDRegressor(max_iter = epochs, penalty='l2', alpha=lamb, eta0=eta,fit_intercept=False)
SGD_sk.fit(X_train,Y_train.ravel())
assert np.all(abs(beta_SGD.T - SGD_sk.coef_) < 1e-1)
def test_SGD_OLS_MSE():
lr = lreg.LinearReg(eta = eta, lamb=0.0, eta_type ='linear',eta_scal=True)
_, _, _, _ , _ = lr.fit(X_train, Y_train, X_test, Y_test, Niter=epochs,batch_size=batch_size, solver='sgd')
pred_SGD_test = lr.predict(X_test)
MSE_test = lr.MSE(Y_test,pred_SGD_test)
SGD_sk = SGDRegressor(max_iter = epochs, penalty=None, alpha=0.0, eta0=eta,fit_intercept=False)
SGD_sk.fit(X_train,Y_train.ravel())
pred_SGD_test_sk = SGD_sk.predict(X_test)
MSE_test_sk = mean_squared_error(Y_test,pred_SGD_test_sk)
assert (abs(MSE_test - MSE_test_sk) < 1e-1)
def test_SGD_Ridge_MSE():
lr = lreg.LinearReg(eta = eta, lamb=lamb, eta_type ='linear',eta_scal=True)
_, _, _, _ , _ = lr.fit(X_train, Y_train, X_test, Y_test, Niter=epochs,batch_size=batch_size, solver='sgd')
pred_SGD_test = lr.predict(X_test)
MSE_test = lr.MSE(Y_test,pred_SGD_test)
SGD_sk = SGDRegressor(max_iter = epochs, penalty='l2', alpha=lamb, eta0=eta,fit_intercept=False)
SGD_sk.fit(X_train,Y_train.ravel())
pred_SGD_test_sk = SGD_sk.predict(X_test)
MSE_test_sk = mean_squared_error(Y_test,pred_SGD_test_sk)
assert (abs(MSE_test - MSE_test_sk) < 1e-1)
def test_SGD_OLS_R2():
lr = lreg.LinearReg(eta = eta, lamb=0.0, eta_type ='linear',eta_scal=True)
_, _, _, _ , _ = lr.fit(X_train, Y_train, X_test, Y_test, Niter=epochs,batch_size=batch_size, solver='sgd')
pred_SGD_test = lr.predict(X_test)
r2_test = lr.R2Score(Y_test,pred_SGD_test)
SGD_sk = SGDRegressor(max_iter = epochs, penalty=None, alpha=0.0, eta0=eta,fit_intercept=False)
SGD_sk.fit(X_train,Y_train.ravel())
pred_SGD_test_sk = SGD_sk.predict(X_test)
r2_test_sk = r2_score(Y_test,pred_SGD_test_sk)
assert (abs(r2_test - r2_test_sk) < 1e-1)
def test_SGD_Ridge_R2():
lr = lreg.LinearReg(eta = eta, lamb=lamb, eta_type ='linear',eta_scal=True)
_, _, _, _ , _ = lr.fit(X_train, Y_train, X_test, Y_test, Niter=epochs,batch_size=batch_size, solver='sgd')
pred_SGD_test = lr.predict(X_test)
r2_test = lr.R2Score(Y_test,pred_SGD_test)
SGD_sk = SGDRegressor(max_iter = epochs, penalty='l2', alpha=lamb, eta0=eta,fit_intercept=False)
SGD_sk.fit(X_train,Y_train.ravel())
pred_SGD_test_sk = SGD_sk.predict(X_test)
r2_test_sk = r2_score(Y_test,pred_SGD_test_sk)
assert (abs(r2_test - r2_test_sk) < 1e-1)<file_sep>import numpy as np
import sklearn.neural_network
import sklearn.model_selection
import sklearn.metrics
import NeuralNet as nn
import functions as fx
import functions_NN as lrf
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
m = 1000
x = 5*np.random.rand(m,1)
y = 6 + 7*x + 0.1*np.random.randn(m,1)
X = np.c_[np.ones((m,1)), x]
# Train and test split
train_size = 0.8
test_size = 1 - train_size
X_train, X_test, Y_train, Y_test = train_test_split(X, y, train_size=train_size,test_size=test_size)
# SGD parameters
epochs = 1000
batch_size = int(len(Y_train)/32)
n_features = X_train.shape[1]
eta = 0.001
lmb = 1e-4
activation = [lrf.leaky_relu, lrf.nooutact]
derivative = [lrf.leaky_relu_deriv, lrf.nooutact_deriv]
# Creating the network object and defining the hyperparameters
neural_net = nn.ANN(lmb = lmb, bias = 0.01, eta = eta, early_stop_tol = 1e-7,\
early_stop_nochange = 2000, mode = 'regression', regularization = 'l2')
# Adding layers
neural_net.add_layers(n_features=[n_features,20], n_neurons = [20,1] , n_layers=2)
# Training the network
neural_net.train(epochs, batch_size, X_train, Y_train, activation, derivative \
, X_test, Y_test, verbose = False)
# performance metrics
pred = neural_net.feed_out(X_test, activation)
reg = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=(20),activation='logistic',
batch_size=batch_size,learning_rate='adaptive',
learning_rate_init=eta,alpha=lmb,max_iter=epochs,tol=1e-5,
verbose=False)
reg = reg.fit(X_train, Y_train.ravel())
# performance metrics
pred_sk = reg.predict(X_test)
def test_NN_MSE():
test_loss = fx.MSE(pred.ravel(), Y_test.T)
test_loss_sk = mean_squared_error(Y_test.ravel(), pred_sk)
assert (abs(test_loss_sk - test_loss) < 1e-1)
def test_NN_R2():
test_r2 = fx.R2Score(pred.ravel(), Y_test.T)
test_r2_sk = reg.score(X_test, Y_test.ravel())
assert (abs(test_r2_sk - test_r2) < 1e-1)
<file_sep># FYS-STK4155
This repository includes all the project works for FYS-STK4155.
The project participants include:
<NAME> and
<NAME>
# Project-1
Report---> Contains our report file (PDF and Latex)
Results---> Contain all the results of project-1 (Figures and Tabels)
Tests---> Contain a Jupyther notebook with a highly commented python script that can be run to test and reproduce our implementation
Unit Tests---> Here we have a unit test Jupyther notebook that is used to check our implementations
src ---> Contain all the Jupyther notebook and python codes used in this project
<file_sep>import numpy as np
import MCLogReg as mclr
def test_accuracy():
logreg = mclr.MCLogReg()
pred_test = np.array([1,1,1,1])
y_test = np.array([1,1,0,0])
acc_test = logreg.compute_accuracy(pred_test, y_test)
assert (acc_test == 0.5)
<file_sep>## Functions
import numpy as np
from scipy.stats import t
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from scipy.stats import norm
from sklearn.model_selection import train_test_split
import scipy.linalg as scl
def FrankeFunction(x, y, noise_level=0):
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
noise = noise_level*np.random.randn(len(x),len(y))
return term1 + term2 + term3 + term4 + noise
def OridinaryLeastSquares(design, data, test):
inverse_term = np.linalg.inv(design.T.dot(design))
beta = inverse_term.dot(design.T).dot(data)
pred_test = test @ beta
pred_train = design @ beta
return beta, pred_test, pred_train
def OridinaryLeastSquares_SVD(design, data, test):
U, s, V = np.linalg.svd(design)
beta = V.T @ scl.pinv(scl.diagsvd(s, U.shape[0], V.shape[0])) @ U.T @ data
pred_test = test @ beta
pred_train = design @ beta
return beta, pred_test, pred_train
def RidgeRegression(design, data, test, _lambda=0):
inverse_term = np.linalg.inv(design.T @ design + _lambda*np.eye((design.shape[1])))
beta = inverse_term @ (design.T) @ (data)
pred_test = test @ beta
pred_train = design @ beta
return beta, pred_test, pred_train
def VarianceBeta_OLS(design, data, pred):
N,p = np.shape(design)
sigma = 1/(N-p-1) * np.sum((data - pred)**2)
Bvar = np.diag(np.linalg.inv(design.T @ design)*sigma)
conf95 = 1.96*np.sqrt(Bvar)
return Bvar, conf95
def VarianceBeta_Ridge(design, data, pred, _lambda=0):
N,p = np.shape(design)
sigma = 1/(N-p-1) * np.sum((data - pred)**2)
x = design.T @ design
W = np.linalg.inv(x + _lambda*np.eye(x.shape[0]))@x
Bvar = np.diag(sigma*W@np.linalg.inv(x + _lambda*np.eye(x.shape[0])).T)
conf95 = 1.96*np.sqrt(Bvar)
return Bvar, conf95
def MSE(y, ytilde):
return (np.sum((y-ytilde)**2))/y.size
def R2Score(y, ytilde):
return 1 - ((np.sum((y-ytilde)**2))/(np.sum((y-((np.sum(y))/y.size))**2)))
def MAE(y, ytilde):
return (np.sum(np.abs(y-ytilde)))/y.size
def MSLE(y, ytilde):
return (np.sum((np.log(1+y) - np.log(1+ytilde))**2))/y.size
def DesignDesign(x, y, power):
'''
This function employs the underlying pattern governing a design matrix
on the form [1,x,y,x**2,x*y,y**2,x**3,(x**2)*y,x*(y**2),y**3 ....]
x_power=[0,1,0,2,1,0,3,2,1,0,4,3,2,1,0,...,n,n-1,...,1,0]
y_power=[0,0,1,0,1,2,0,1,2,3,0,1,2,3,4,...,0,1,...,n-1,n]
'''
concat_x = np.array([0,0])
concat_y = np.array([0,0])
for i in range(power):
toconcat_x = np.arange(i+1,-1,-1)
toconcat_y = np.arange(0,i+2,1)
concat_x = np.concatenate((concat_x,toconcat_x))
concat_y = np.concatenate((concat_y,toconcat_y))
concat_x = concat_x[1:len(concat_x)]
concat_y = concat_y[1:len(concat_y)]
X,Y = np.meshgrid(x,y)
X = np.ravel(X)
Y = np.ravel(Y)
DesignMatrix = np.empty((len(X),len(concat_x)))
for i in range(len(concat_x)):
DesignMatrix[:,i] = (X**concat_x[i])*(Y**concat_y[i])
#DesignMatrix = np.concatenate((np.ones((len(X),1)),DesignMatrix), axis = 1)
return DesignMatrix
def create_X(x, y, n ):
if len(x.shape) > 1:
x = np.ravel(x)
y = np.ravel(y)
N = len(x)
l = int((n+1)*(n+2)/2) # Number of elements in beta
X = np.ones((N,l))
for i in range(1,n+1):
q = int((i)*(i+1)/2)
for k in range(i+1):
X[:,q+k] = (x**(i-k))*(y**k)
return X
def reshaper(k, data):
output = []
j = int(np.ceil(len(data)/k))
for i in range(k):
if i<k:
output.append(data[i*j:(i+1)*j])
else:
output.append(data[i*j:])
return np.asarray(output)
def k_fold_cv(k, indata, indesign, predictor, _lambda=0, shuffle=False):
'''
Usage: k-fold cross validation employing either RidgeRegression, OridinaryLeastSquares or ols_svd
Input: k = number of folds
indata = datapoints
indesign = user defined design matrix
predictor = RidgeRegression, OridinaryLeastSquares or ols_svd
_lambda = hyperparameter/penalty paramter/tuning parameter for RidgeRegression
shuffle = False, input data will not be shuffled
True, input data will be shuffled
output: r2_out/k = averaged out sample R2-score
mse_out/k = averaged out sample MSE
r2_in/k = averaged in sample R2-Score
mse_in/k = averaged in sample MSE
'''
mask = np.arange(indata.shape[0])
if shuffle:
np.random.shuffle(mask)
data = reshaper(k, indata[mask])
design = reshaper(k, indesign[mask])
r2_out = 0
r2_in = 0
mse_out = 0
mse_in = 0
for i in range(k):
train_design = design[np.arange(len(design))!=i] # Featch all but the i-th element
train_design = np.concatenate(train_design,axis=0)
train_data = data[np.arange(len(data))!=i]
train_data = np.concatenate(train_data,axis=0)
test_design = design[i]
test_data = data[i]
if _lambda != 0:
beta, pred_ts, pred_tr = predictor(train_design, train_data, test_design, _lambda)
else:
beta, pred_ts, pred_tr = predictor(train_design, train_data, test_design)
r2_out += R2Score(test_data, pred_ts)
r2_in += R2Score(train_data, pred_tr)
mse_out += MSE(test_data, pred_ts)
mse_in += MSE(train_data, pred_tr)
return r2_out/k, mse_out/k, r2_in/k, mse_in/k
<file_sep>#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import os
class LinearReg:
'''
Linear Regression
'''
def __init__(self, eta=0.1, eta_scal=False, eta_type ='linear', lamb=0, tol=1e-5, early_stop_tol = 0.0, early_stop_nochange=10):
self.eta = eta
self.eta_0 = eta
self.eta_f = 1.0e-6
self.eta_scal = eta_scal
self.eta_type = eta_type
self.lamb = lamb
self.early_stop_tol = early_stop_tol
self.early_stop_nochange = early_stop_nochange
self.beta = float()
def fit(self, xtrain, ytrain, xval, yval, Niter, batch_size = 1, solver='gd'):
self.xtrain = xtrain
self.ytrain = ytrain
self.xval = xval
self.yval = yval
self.batch_size = batch_size
self.beta = np.random.uniform(0, 1, self.xtrain.shape[1])
self.beta = self.beta.reshape(-1,1)
xaxis = []
self.cost = []
self.eta_vec = []
self.cost_val = []
indexes = np.arange(xtrain.shape[0])
self.xtrain_tmp = xtrain
self.ytrain_tmp = ytrain
self.xval_tmp = xval
self.yval_tmp = yval
for iter in range(Niter):
xaxis.append(iter+1)
if solver == 'sgd':
mbatch = np.int(self.xtrain.shape[0]/self.batch_size)
datapoints = np.random.choice(indexes, size=mbatch, replace=False)
self.xtrain_tmp = self.xtrain[datapoints,:]
self.ytrain_tmp = self.ytrain[datapoints]
if self.eta_scal and self.eta_type == 'linear':
factor = iter/(Niter-1)
self.learning_schedule_linear(factor)
elif self.eta_scal and self.eta_type == 'exp':
factor = iter/(Niter-1)
self.learning_schedule_exp(factor)
self.eta_vec.append(self.eta)
self.oneiteration_sgd()
self.costs()
elif solver == 'gd':
self.oneiteration_gd()
self.costs()
return self.cost_val, self.cost, xaxis, self.beta, self.eta_vec
def learning_schedule_linear(self,t):
self.eta = self.eta_0 + (self.eta_f - self.eta_0)*t
def learning_schedule_exp(self,t):
self.eta = self.eta_0*np.exp(np.log(self.eta_f/self.eta_0)*t)
def gradient_gd(self, X, Y):
m = len(Y)
Pred = X @ self.beta
grad = (2.0/m)*(X.T @ (Pred - Y) + self.lamb * self.beta)
return grad
def gradient_sgd(self, X, Y):
m = len(Y)
Pred = X @ self.beta
grad = 2 * (X.T @ (Pred - Y) + self.lamb * self.beta)
return grad
def cost_ols(self, X, Y):
m = len(Y)
Pred = X@self.beta
loss = (1.0/m)*(np.linalg.norm((Pred - Y), 2) ** 2)
return loss
def costs(self):
self.cost_val.append(self.cost_ols(self.xval_tmp, self.yval_tmp))
self.cost.append(self.cost_ols(self.xtrain_tmp, self.ytrain_tmp))
def oneiteration_gd(self):
self.beta -= self.eta*self.gradient_gd(self.xtrain_tmp, self.ytrain_tmp)
def oneiteration_sgd(self):
self.beta -= self.eta*self.gradient_sgd(self.xtrain_tmp, self.ytrain_tmp)
def reshaper(self, nk, data):
output = []
j = int(np.ceil(len(data)/nk))
for i in range(nk):
if i<nk:
output.append(data[i*j:(i+1)*j])
else:
output.append(data[i*j:])
return np.asarray(output)
def k_fold_reshaper(self, nk, indata, indesign, shuffle=True):
mask = np.arange(indata.shape[0])
if shuffle:
np.random.shuffle(mask)
data = self.reshaper(nk, indata[mask])
design = self.reshaper(nk, indesign[mask])
return data, design
def predict(self, X):
pred = X@self.beta
return pred
def FrankeFunction(self, x, y, noise_level=0):
term1 = 0.75*np.exp(-(0.25*(9*x-2)**2) - 0.25*((9*y-2)**2))
term2 = 0.75*np.exp(-((9*x+1)**2)/49.0 - 0.1*(9*y+1))
term3 = 0.5*np.exp(-(9*x-7)**2/4.0 - 0.25*((9*y-3)**2))
term4 = -0.2*np.exp(-(9*x-4)**2 - (9*y-7)**2)
noise = noise_level*np.random.randn(len(x),len(y))
return term1 + term2 + term3 + term4 + noise
def OridinaryLeastSquares(self, design, data, test):
inverse_term = np.linalg.inv(design.T@design)
alpha = (inverse_term@design.T)@data
pred_test = test @ alpha
pred_train = design @ alpha
return alpha, pred_test, pred_train
def RidgeRegression(self, design, data, test, _lambda=0):
inverse_term = np.linalg.inv(design.T @ design + _lambda*np.eye((design.shape[1])))
beta = inverse_term @ (design.T) @ (data)
pred_test = test @ beta
pred_train = design @ beta
return beta, pred_test, pred_train
def VarianceBeta_OLS(self, design, data, pred):
N,p = np.shape(design)
sigma = 1/(N-p-1) * np.sum((data - pred)**2)
Bvar = np.diag(np.linalg.inv(design.T @ design)*sigma)
conf95 = 1.96*np.sqrt(Bvar)
return Bvar, conf95
def VarianceBeta_Ridge(self, design, data, pred, _lambda=0):
N,p = np.shape(design)
sigma = 1/(N-p-1) * np.sum((data - pred)**2)
x = design.T @ design
W = np.linalg.inv(x + _lambda*np.eye(x.shape[0]))@x
Bvar = np.diag(sigma*W@np.linalg.inv(x + _lambda*np.eye(x.shape[0])).T)
conf95 = 1.96*np.sqrt(Bvar)
return Bvar, conf95
def MSE(self, y, ytilde):
m = y.shape[0]
return (1/m)*(np.sum((y-ytilde)**2))
def R2Score(self, y, ytilde):
m = y.shape[0]
return 1 - ((np.sum((y-ytilde)**2))/(np.sum((y-((np.sum(y))/m))**2)))
def DesignDesign(self, x, y, power):
concat_x = np.array([0,0])
concat_y = np.array([0,0])
for i in range(power):
toconcat_x = np.arange(i+1,-1,-1)
toconcat_y = np.arange(0,i+2,1)
concat_x = np.concatenate((concat_x,toconcat_x))
concat_y = np.concatenate((concat_y,toconcat_y))
concat_x = concat_x[1:len(concat_x)]
concat_y = concat_y[1:len(concat_y)]
X,Y = np.meshgrid(x,y)
X = np.ravel(X)
Y = np.ravel(Y)
DesignMatrix = np.empty((len(X),len(concat_x)))
for i in range(len(concat_x)):
DesignMatrix[:,i] = (X**concat_x[i])*(Y**concat_y[i])
return DesignMatrix
<file_sep>
# FYS-STK4155 project 2
In this project, we investigate regression and classification problems. We use the Franke function and the MNIST as data sets. To solve the regression problem, we use a fully connected neural network (NN) and Stochastic Gradient Descent (SGD)-based Ordinary Least Square (OLS) and Ridge regression methods. The classification problem is solved using NNs and multinominal logistic regression.
All the analysis presented in our report can be reproduced by using our python codes and the corresponding Jupyther notebook.
## Folder structure
Report ---> Contains our report file (PDF and Latex)
Figures ---> Contain all the results of project-2 (Figures and Tabels)
src ---> Contain all the python codes and the corresponding Jupyther notebooks
### Unit test codes:
test_MultiClass.py
test_NN_regression.py
test_linear_regression.py
### Linear regression codes:
Linear_Regression.ipynb
LinearReg.py
### NN regression codes:
NN_Regression.ipynb
NeuralNet.py
functions_NN.py
functions.py
### Softmax regression codes:
MultiClass_LogesticRegression.ipynb
MCLogReg.py
### NN classification codes:
MultiClass_NN.ipynb
NN_MC_classification.py
MCLogReg.py
## Running the codes
The Jupyther notebooks contain all the analysis we did in project-2 and they can be run cell by cell
The unit tests can be run by writting the following command:
```
pytest -v
```
## Authors
<NAME> and
<NAME>
<file_sep>#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import scipy.sparse as sparse
import os
class MCLogReg:
'''
Multi Class Logistic Regression (Softmax Regression)
'''
def __init__(self, eta=0.1, lamb=0, k=10, tol=1e-5, early_stop_tol = 0.0, early_stop_nochange=10):
self.eta = eta
self.lamb = lamb
self.k = k
self.early_stop_tol = early_stop_tol
self.early_stop_nochange = early_stop_nochange
self.beta = float()
def fit(self, xtrain, ytrain, xval, yval, Niter, batch_size = 200, solver='gd'):
self.xtrain = self.augment_feature_vector(xtrain)
self.ytrain = ytrain
self.xval = self.augment_feature_vector(xval)
self.yval = yval
self.beta = np.random.randn(self.k,self.xtrain.shape[1])
xaxis = []
self.cost = []
self.cost_val = []
indexes = np.arange(xtrain.shape[0])
self.xtrain_tmp = self.augment_feature_vector(xtrain)
self.ytrain_tmp = ytrain
self.xval_tmp = self.augment_feature_vector(xval)
self.yval_tmp = yval
for iter in range(Niter):
xaxis.append(iter+1)
if solver == 'sgd':
datapoints = np.random.choice(indexes, size=batch_size, replace=False)
self.xtrain_tmp = self.xtrain[datapoints,:]
self.ytrain_tmp = self.ytrain[datapoints]
self.oneiteration()
self.costs()
elif solver == 'gd':
self.oneiteration()
self.costs()
return self.cost_val, self.cost, xaxis, self.beta
def augment_feature_vector(self, X):
return np.hstack((np.ones([len(X), 1]), X))
def compute_probabilities(self, X):
score = self.beta@np.transpose(X)
exp_mat = np.exp(score - np.amax(score, axis = 0))
sum_vec = np.sum(exp_mat, axis = 0)
prob = exp_mat/sum_vec
return prob
def gradient_softmax(self, X, Y):
n = len(Y)
datag = [1]*n
H = self.compute_probabilities(X)
M = sparse.coo_matrix((datag, (Y, range(n))), shape=(self.k,n)).toarray()
first_term = ((M - H)@X)*(-1/n)
second_term = self.lamb*self.beta
grad = first_term + second_term
return grad
def compute_accuracy(self, predic, Y):
acc = np.mean(predic == Y)
return acc
def cost_softmax(self, X, Y):
n = len(Y)
data = [1]*n
H = self.compute_probabilities(X)
M = sparse.coo_matrix((data, (Y, range(n))), shape=(self.k,n)).toarray()
first_term = np.sum(M * np.log(H))*(-1/n)
second_term = self.lamb/2*np.sum(self.beta**2)
loss = first_term + second_term
return loss
def costs(self):
self.cost_val.append(self.cost_softmax(self.xval_tmp, self.yval_tmp.T))
self.cost.append(self.cost_softmax(self.xtrain_tmp, self.ytrain_tmp.T))
def oneiteration(self):
self.beta -= self.eta*self.gradient_softmax(self.xtrain_tmp, self.ytrain_tmp.T)
def predict(self, X):
X = self.augment_feature_vector(X)
probabilities = self.compute_probabilities(X)
classes = np.argmax(probabilities, axis = 0)
return classes
def reshaper(self, nk, data):
output = []
j = int(np.ceil(len(data)/nk))
for i in range(nk):
if i<nk:
output.append(data[i*j:(i+1)*j])
else:
output.append(data[i*j:])
return np.asarray(output)
def k_fold_reshaper(self, nk, indata, indesign, shuffle=True):
mask = np.arange(indata.shape[0])
if shuffle:
np.random.shuffle(mask)
data = self.reshaper(nk, indata[mask])
design = self.reshaper(nk, indesign[mask])
return data, design
<file_sep>import numpy as np
import scipy.sparse
'''
This file includes the activation functions and cost functions used by
NeuralNetwork.py
and
LogisticRegression.py
'''
def sigmoid(prediction):
'''
Sigmoid activation function, from logistic regression slides.
'''
return 1. / (1. + np.exp(-prediction))
def sigmoid_deriv(activation):
'''
Returns derivative of sigmoid activation function.
'''
derivative = activation*(1-activation)
return derivative
def relu(prediction):
'''
ReLU activation function.
'''
out = np.copy(prediction)
out[np.where(prediction < 0)]=0
out = np.clip(out,-300,300)
return out
def relu_deriv(prediction):
'''
Returns the derivative of ReLU.
'''
derivative = np.copy(prediction)
derivative[np.where(prediction < 0)] = 0
derivative[np.where(prediction >= 0)] = 1
return derivative
def leaky_relu(prediction):
'''
Leaky_ReLU activation function.
'''
out = np.copy(prediction)
out[np.where(prediction < 0)] = 0.01 * out[np.where(prediction < 0)]
out = np.clip(out,-300,300)
return out
def leaky_relu_deriv(prediction):
'''
Returns the derivative of Leaky_ReLU.
'''
derivative = np.copy(prediction)
derivative[np.where(prediction < 0)] = 0.01
derivative[np.where(prediction >= 0)] = 1
return derivative
def elu(prediction):
'''
ELU activation function.
'''
out = np.copy(prediction)
out[np.where(prediction < 0)] = 0.01 * (np.exp(out[np.where(prediction < 0)])-1)
out = np.clip(out,-300,300)
return out
def elu_deriv(prediction):
'''
Returns the derivative of ELU.
'''
derivative = np.copy(prediction)
derivative[np.where(prediction < 0)] = 0.01 * np.exp(derivative[np.where(prediction < 0)])
derivative[np.where(prediction >= 0)] = 1
return derivative
def nooutact(prediction):
'''
Can be used for activation in output layer in case of regression.
'''
return prediction
def nooutact_deriv(prediction):
out = np.ones(prediction.shape)
return out
def augment_feature_vector(X):
return np.hstack((np.ones([len(X), 1]), X))
def compute_probabilities(X, theta):
theta_XT = np.matmul(theta, np.transpose(X))
c = np.amax(theta_XT, axis = 0)
exp_matrix = np.exp(theta_XT - c)
sum_vector = np.sum(exp_matrix, axis = 0)
prob = exp_matrix/sum_vector
return prob
def gradient_softmax(X, Y, theta, lamb):
n = len(Y)
k = theta.shape[0]
data = [1]*n
H = compute_probabilities(X, theta)
M = sparse.coo_matrix((data, (Y, range(n))), shape=(k,n)).toarray()
first_term = np.matmul(M - H, X)*(-1/n)
second_term = lamb*theta
grad = first_term + second_term
return grad
def compute_accuracy(pred, Y):
acc = np.mean(pred == Y)
return acc
def cost_softmax(X, Y, theta, lamb):
n = len(Y)
k = theta.shape[0]
data = [1]*n
H = compute_probabilities(X, theta)
M = sparse.coo_matrix((data, (Y, range(n))), shape=(k,n)).toarray()
first_term = np.sum(M * np.log(H))*(-1/n)
second_term = lamb/2*np.sum(theta*theta)
loss = first_term + second_term
return loss
def cost_mse_ols(design, data, beta):
'''
Mean squared error
'''
return (data - design.dot(beta)).T*(data - design.dot(beta))
def cost_grad_ols(design, data, beta):
'''
Calculates the first derivative of MSE w.r.t beta.
'''
return (2/len(data))*design.T.dot(design.dot(beta)-data) #logistic regression slides
def cost_log_ols(prediction, data):
'''
Logisitic regression cost function
'''
length = data.shape[1]
prediction = prediction.ravel()
data = data.ravel()
calc = -data.dot(np.log(sigmoid(prediction)+ 1e-16)) - ((1 - data).dot(np.log(1 - sigmoid(prediction) + 1e-16)))
norm = calc/length
return norm
def gradient_ols(design, data, p):
'''
Gradient w.r.t log
'''
return np.dot(design.T, (p - data)) / data.shape[0]
def reshaper(k, data):
'''
Usage: Manages the data for k_fold_cv
Input: k = number of folds
data = shuffled input data or input design matrix
output: Splitted data
'''
output = []
j = int(np.ceil(len(data)/k))
for i in range(k):
if i<k:
output.append(data[i*j:(i+1)*j])
else:
output.append(data[i*j:])
return np.asarray(output)
def k_fold_reshaper(k, indata, indesign, shuffle=True):
'''
Usage: k-fold cross validation employing either RidgeRegression, OridinaryLeastSquares or ols_svd
Input: k = number of folds
indata = datapoints
indesign = user defined design matrix
predictor = RidgeRegression, OridinaryLeastSquares or ols_svd
_lambda = hyperparameter/penalty paramter/tuning parameter for RidgeRegression
shuffle = False, input data will not be shuffled
True, input data will be shuffled
output: r2_out/k = averaged out sample R2-score
mse_out/k = averaged out sample MSE
r2_in/k = averaged in sample R2-Score
mse_in/k = averaged in sample MSE
'''
mask = np.arange(indata.shape[0])
if shuffle:
np.random.shuffle(mask)
data = reshaper(k, indata[mask])
design = reshaper(k, indesign[mask])
return data,design
<file_sep>import numpy as np
from sklearn.metrics import f1_score
'''
This code is a slight modification of the code from FYS-STK4155 lecture note by <NAME>
https://compphysics.github.io/MachineLearning/doc/pub/week41/html/week41.html [accessed 25.10.2020]
'''
def to_categorical_numpy(integer_vector):
n_inputs = len(integer_vector)
n_categories = np.max(integer_vector) + 1
onehot_vector = np.zeros((n_inputs, n_categories))
onehot_vector[range(n_inputs), integer_vector] = 1
return onehot_vector
def accuracy_score_numpy(Y_test, Y_pred):
return np.sum(Y_test == Y_pred) / len(Y_test)
class MC_NN_classif:
def __init__(self, X_data,Y_data,n_hidden_neurons=50,n_categories=10,epochs=10,batch_size=100,eta=0.1,lmbd=0.0):
self.X_data_full = X_data
self.Y_data_full = Y_data
self.n_inputs = X_data.shape[0]
self.n_features = X_data.shape[1]
self.n_hidden_neurons = n_hidden_neurons
self.n_categories = n_categories
self.epochs = epochs
self.batch_size = batch_size
self.iterations = self.n_inputs // self.batch_size
self.eta = eta
self.lmbd = lmbd
self.create_biases_and_weights()
def create_biases_and_weights(self):
self.hidden_weights = np.random.randn(self.n_features, self.n_hidden_neurons)
self.hidden_bias = np.zeros(self.n_hidden_neurons) + 0.01
self.output_weights = np.random.randn(self.n_hidden_neurons, self.n_categories)
self.output_bias = np.zeros(self.n_categories) + 0.01
def feed_forward(self):
self.z_h = np.matmul(self.X_data, self.hidden_weights) + self.hidden_bias
self.a_h = self.sigmoid(self.z_h)
self.z_o = np.matmul(self.a_h, self.output_weights) + self.output_bias
exp_term = np.exp(self.z_o)
self.probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
def feed_forward_out(self, X):
z_h = np.matmul(X, self.hidden_weights) + self.hidden_bias
a_h = self.sigmoid(z_h)
z_o = np.matmul(a_h, self.output_weights) + self.output_bias
exp_term = np.exp(z_o)
probabilities = exp_term / np.sum(exp_term, axis=1, keepdims=True)
return probabilities
def backpropagation(self):
error_output = self.probabilities - self.Y_data
error_hidden = np.matmul(error_output, self.output_weights.T) * self.a_h * (1 - self.a_h)
self.output_weights_gradient = np.matmul(self.a_h.T, error_output)
self.output_bias_gradient = np.sum(error_output, axis=0)
self.hidden_weights_gradient = np.matmul(self.X_data.T, error_hidden)
self.hidden_bias_gradient = np.sum(error_hidden, axis=0)
if self.lmbd > 0.0:
self.output_weights_gradient += self.lmbd * self.output_weights
self.hidden_weights_gradient += self.lmbd * self.hidden_weights
self.output_weights -= self.eta * self.output_weights_gradient
self.output_bias -= self.eta * self.output_bias_gradient
self.hidden_weights -= self.eta * self.hidden_weights_gradient
self.hidden_bias -= self.eta * self.hidden_bias_gradient
def predict(self, X):
probabilities = self.feed_forward_out(X)
return np.argmax(probabilities, axis=1)
def predict_probabilities(self, X):
probabilities = self.feed_forward_out(X)
return probabilities
def train(self):
data_indices = np.arange(self.n_inputs)
for i in range(self.epochs):
for j in range(self.iterations):
chosen_datapoints = np.random.choice(data_indices, size=self.batch_size, replace=False)
self.X_data = self.X_data_full[chosen_datapoints]
self.Y_data = self.Y_data_full[chosen_datapoints]
self.feed_forward()
self.backpropagation()
def sigmoid(self,x):
return 1/(1 + np.exp(-x))
<file_sep>import numpy as np
import functions_NN as lrf
import functions as fx
from sklearn.metrics import f1_score
class ANN():
def __init__(self, lmb=0, bias=0, eta=0.0001, early_stop_tol = 0.0,\
early_stop_nochange=10, mode = 'classification', regularization = 'l2'):
self.lmb = lmb
self.bias = bias
self.eta = eta
self.regularization = regularization
self.mode = mode
self.early_stop_tol = early_stop_tol
self.early_stop_nochange = early_stop_nochange
self.n_layers = int()
self.layers = dict()
self.pred = dict()
self.act = dict()
def add_layers(self, n_neurons=[50,20], n_features=[20,1], n_layers=2):
self.n_layers = n_layers
for i in range(n_layers):
if i == 0:
layer_weights = np.random.randn(n_features[i], n_neurons[i])*np.sqrt(2/n_neurons[i])
else:
layer_weights = np.random.randn(n_features[i], n_neurons[i])*np.sqrt(2/n_neurons[i-1])
self.layers['w'+str(i)] = layer_weights
layer_bias = np.zeros(n_neurons[i]) + self.bias
self.layers['b'+str(i)] = layer_bias
def feed(self, design, activation=[lrf.sigmoid, lrf.sigmoid]):
for i in range(self.n_layers):
if i==0:
self.pred[str(i)] = np.matmul(design, self.layers['w'+str(i)]) + self.layers['b'+str(i)]
self.act[str(i)] = activation[i](self.pred[str(i)])
else:
self.pred[str(i)] = np.matmul(self.act[str(i-1)], self.layers['w'+str(i)]) + self.layers['b'+str(i)]
self.act[str(i)] = activation[i](self.pred[str(i)])
def back(self, design, data, derivative = [lrf.sigmoid_deriv, lrf.sigmoid_deriv]):
for i in np.arange(self.n_layers-1,-1,-1):
if i==self.n_layers-1:
if self.mode == 'regression':
error = (self.act[str(i)] - data)*derivative[i](self.act[str(i)])
if self.mode == 'classification':
error = (self.act[str(i)] - data)*derivative[i](self.act[str(i)])
else:
error = np.matmul(error, self.layers['w'+str(i+1)].T)\
* derivative[i](self.act[str(i)])
if i == 0:
gradients_weights = (np.matmul(design.T, error))/len(data)
gradients_bias = (np.sum(error, axis=0))/len(data)
else:
gradients_weights = (np.matmul(self.act[str(i-1)].T, error))/len(data)
gradients_bias = (np.sum(error, axis=0))/len(data)
if self.lmb>0.0:
if self.regularization == 'l2':
gradients_weights += self.lmb * self.layers['w'+str(i)]
self.layers['w'+str(i)] -= self.eta * gradients_weights
self.layers['b'+str(i)] -= self.eta * gradients_bias
def feed_out(self, design, activation=[lrf.sigmoid,lrf.sigmoid]):
for i in range(self.n_layers):
if i==0:
self.pred[str(i)] = np.matmul(design, self.layers['w'+str(i)])\
+ self.layers['b'+str(i)]
self.act[str(i)] = activation[i](self.pred[str(i)])
else:
self.pred[str(i)] = np.matmul(self.act[str(i-1)],\
self.layers['w'+str(i)]) + self.layers['b'+str(i)]
self.act[str(i)] = activation[i](self.pred[str(i)])
return self.act[str(self.n_layers-1)]
def costs(self):
return self.cost_val, self.cost_train
def coefs(self):
return self.layers
def train(self, epochs, batch_size, x, y, activation, derivative,\
xvalidation, yvalidation, verbose=False):
tmp = int(len(y)/batch_size)
Niter = min(200,tmp)
indexes = np.arange(len(y))
cost = np.empty([epochs])
self.cost_val = list()
self.cost_train = list()
for i in range(epochs):
for j in range(Niter):
datapoints = np.random.choice(indexes, size=batch_size, replace=False)
batch_x = x[datapoints,:]
batch_y = y[datapoints]
self.feed(batch_x, activation)
self.back(batch_x,batch_y, derivative)
pred_val = self.feed_out(xvalidation, activation)
pred_train = self.feed_out(batch_x, activation)
if self.mode == 'regression':
self.cost_val.append(fx.MSE(pred_val.ravel(),yvalidation.ravel()))
self.cost_train.append(fx.MSE(pred_train.ravel(),batch_y.ravel()))
if self.mode == 'classification':
self.cost_val.append(lrf.cost_log_ols(pred_val.ravel(),yvalidation.T))
self.cost_train.append(lrf.cost_log_ols(pred_train.ravel(),batch_y.T))
if i > self.early_stop_nochange:
avg_indx_full = np.arange(i-self.early_stop_nochange,i)
avg_indx_full.astype(int)
avg_indx = np.arange(i-5,i)
avg_indx.astype(int)
if -self.early_stop_tol<np.mean(np.array(self.cost_val)[avg_indx]) - np.mean(np.array(self.cost_val)[avg_indx_full]):
break
if verbose:
print('Epoch', i+1, 'loss', self.cost_val[i] )
<file_sep># FYS-STK4155 project 3
In this project, we integrate the Convolutional Neural Networks (CNNs) and Strengthen-Operate-Subtract (SOS) boosting algorithm to denoise a microseismic dataset.
All the analysis presented in our report can be reproduced by using our python codes and the corresponding Jupyther notebook.
## Folder structure
Report ---> Contains our report file (PDF and Latex)
plot_img ---> Contain all the results of project-3 (Figures)
src ---> Contain all the python codes and the corresponding Jupyther notebooks
model ---> Contain all the trained models
weights ---> Contain all the trained weights
data ---> Contain some of the test data sets
### Grid search
network_grid_search.ipynb
boost_grid_search.ipynb
### Test data prediction using trained network and SOS boosting
test_a.ipynb
test_b.ipynb
### Tools
functions.py
autoencoder_l2.py
### Unit test codes:
unit_test.py
## Running the codes
The Jupyther notebooks contain all the analysis we did in project-3 and they can be run cell by cell
Note that to do the grid search of the CNN hyperparamers is very computionally heavy.
For the readers that do not have powerful GPU to run the code, the trained models and weights from this project are provided in folders 'model' and 'weights', respectively.
The unit tests can be run by writting the following command:
```
pytest -v
```
## Authors
<NAME> and
<NAME>
| 1cb07111a8d1ed05200c25b5047a8bc14617a76f | [
"Markdown",
"Python"
] | 12 | Python | endrias34/FYS-STK4155 | fa76d9144d5a55a272e801fedb023507f037905a | 2971b62c4e9990c8f055e5c5a78c6240dea79c78 |
refs/heads/master | <file_sep>package com.dung.zoomimagedemo
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.graphics.Point
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
class MainActivity : AppCompatActivity() {
private var mCurrentAnimator: Animator? = null
private var mShortAnimationDuration: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Hook up clicks on the thumbnail views.
val thumb1View: View = findViewById(R.id.thumb_button_1)
thumb1View.setOnClickListener {
zoomImageFromThumb(thumb1View, getDrawable(R.drawable.aaa))
}
mShortAnimationDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
}
private fun zoomImageFromThumb(thumbView: View, imageResId: Drawable) {
mCurrentAnimator?.cancel()
val expandedImageView: ImageView = findViewById(R.id.expanded_image)
expandedImageView.setImageDrawable(imageResId)
val startBoundsInt = Rect()
val finalBoundsInt = Rect()
val globalOffset = Point()
thumbView.getGlobalVisibleRect(startBoundsInt)
findViewById<View>(R.id.container)
.getGlobalVisibleRect(finalBoundsInt, globalOffset)
startBoundsInt.offset(-globalOffset.x, -globalOffset.y)
finalBoundsInt.offset(-globalOffset.x, -globalOffset.y)
val startBounds = RectF(startBoundsInt)
val finalBounds = RectF(finalBoundsInt)
val startScale: Float
if ((finalBounds.width() / finalBounds.height() > startBounds.width() / startBounds.height())) {
// Extend start bounds horizontally
startScale = startBounds.height() / finalBounds.height()
val startWidth: Float = startScale * finalBounds.width()
val deltaWidth: Float = (startWidth - startBounds.width()) / 2
startBounds.left -= deltaWidth.toInt()
startBounds.right += deltaWidth.toInt()
} else {
// Extend start bounds vertically
startScale = startBounds.width() / finalBounds.width()
val startHeight: Float = startScale * finalBounds.height()
val deltaHeight: Float = (startHeight - startBounds.height()) / 2f
startBounds.top -= deltaHeight.toInt()
startBounds.bottom += deltaHeight.toInt()
}
thumbView.alpha = 0f
expandedImageView.visibility = View.VISIBLE
expandedImageView.pivotX = 0f
expandedImageView.pivotY = 0f
mCurrentAnimator = AnimatorSet().apply {
play(
ObjectAnimator.ofFloat(
expandedImageView,
View.X,
startBounds.left,
finalBounds.left
)
).apply {
with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top))
with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f))
with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f))
}
duration = mShortAnimationDuration.toLong()
interpolator = DecelerateInterpolator()
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
mCurrentAnimator = null
}
override fun onAnimationCancel(animation: Animator) {
mCurrentAnimator = null
}
})
start()
}
expandedImageView.setOnClickListener {
mCurrentAnimator?.cancel()
mCurrentAnimator = AnimatorSet().apply {
play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left)).apply {
with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top))
with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale))
with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale))
}
duration = mShortAnimationDuration.toLong()
interpolator = DecelerateInterpolator()
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
thumbView.alpha = 1f
expandedImageView.visibility = View.GONE
mCurrentAnimator = null
}
override fun onAnimationCancel(animation: Animator) {
thumbView.alpha = 1f
expandedImageView.visibility = View.GONE
mCurrentAnimator = null
}
})
start()
}
}
}
}
| 70a4db3ea2466d977d153af7f4c46e858ef16f7d | [
"Kotlin"
] | 1 | Kotlin | dungnvKOD/zoomImageDemo | 611a88b6314d425edd52677aac68bcae32d71e9f | 5d958ca20585028d315c47134fded45700a87b90 |
refs/heads/main | <repo_name>2102-feb08-net/diego-project1<file_sep>/Store.WebUI/Store.Data/Entities/project1rincongamezonestoreContext.cs
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
#nullable disable
namespace Store.DataAccess.Entities
{
public partial class project1rincongamezonestoreContext : DbContext
{
public project1rincongamezonestoreContext()
{
}
public project1rincongamezonestoreContext(DbContextOptions<project1rincongamezonestoreContext> options)
: base(options)
{
}
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Inventory> Inventories { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<OrderLine> OrderLines { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<Store> Stores { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");
modelBuilder.Entity<Customer>(entity =>
{
entity.ToTable("Customer", "GStore");
entity.HasIndex(e => e.Email, "UQ__Customer__A9D105344FC009C4")
.IsUnique();
entity.Property(e => e.CustomerId).HasColumnName("CustomerID");
entity.Property(e => e.Email)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.FirstName)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.LastName)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.Password)
.IsRequired()
.HasMaxLength(50);
});
modelBuilder.Entity<Inventory>(entity =>
{
entity.ToTable("Inventory", "GStore");
entity.Property(e => e.InventoryId)
.ValueGeneratedNever()
.HasColumnName("InventoryID");
entity.Property(e => e.ProductId).HasColumnName("ProductID");
entity.Property(e => e.StoreId).HasColumnName("StoreID");
entity.HasOne(d => d.Product)
.WithMany(p => p.Inventories)
.HasForeignKey(d => d.ProductId)
.HasConstraintName("FK_InventoryProductId");
entity.HasOne(d => d.Store)
.WithMany(p => p.Inventories)
.HasForeignKey(d => d.StoreId)
.HasConstraintName("FK_InventoryStoreId");
});
modelBuilder.Entity<Order>(entity =>
{
entity.ToTable("Order", "GStore");
entity.Property(e => e.OrderId).HasColumnName("OrderID");
entity.Property(e => e.CustomerId).HasColumnName("CustomerID");
entity.Property(e => e.OrderDate).HasColumnType("datetime");
entity.Property(e => e.OrderTotal).HasColumnType("numeric(10, 2)");
entity.Property(e => e.StoreId).HasColumnName("StoreID");
entity.HasOne(d => d.Customer)
.WithMany(p => p.Orders)
.HasForeignKey(d => d.CustomerId)
.HasConstraintName("FK_CustomerId");
entity.HasOne(d => d.Store)
.WithMany(p => p.Orders)
.HasForeignKey(d => d.StoreId)
.HasConstraintName("FK_StoreId");
});
modelBuilder.Entity<OrderLine>(entity =>
{
entity.ToTable("OrderLine", "GStore");
entity.Property(e => e.OrderLineId).HasColumnName("OrderLineID");
entity.Property(e => e.OrderId).HasColumnName("OrderID");
entity.Property(e => e.ProductId).HasColumnName("ProductID");
entity.Property(e => e.TotalPrice).HasColumnType("numeric(10, 2)");
entity.HasOne(d => d.Order)
.WithMany(p => p.OrderLines)
.HasForeignKey(d => d.OrderId)
.HasConstraintName("FK_OrderId");
entity.HasOne(d => d.Product)
.WithMany(p => p.OrderLines)
.HasForeignKey(d => d.ProductId)
.HasConstraintName("FK_ProductId");
});
modelBuilder.Entity<Product>(entity =>
{
entity.ToTable("Product", "GStore");
entity.Property(e => e.ProductId).HasColumnName("ProductID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.Price).HasColumnType("numeric(10, 2)");
entity.Property(e => e.Type).HasMaxLength(100);
});
modelBuilder.Entity<Store>(entity =>
{
entity.ToTable("Store", "GStore");
entity.Property(e => e.StoreId).HasColumnName("StoreID");
entity.Property(e => e.StoreAddress)
.IsRequired()
.HasMaxLength(100);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
<file_sep>/Store.WebUI/StoreTests/StoreLogicModelCustomer.cs
using System;
using Xunit;
namespace StoreTests
{
public class StoreLogicModelCustomer
{
[Fact]
public void ValidateNameNumericName()
{
// Arrange
string fname = "Cr00s";
string lname = "F13lds";
Store.Logic.Models.Customer tester = new Store.Logic.Models.Customer();
// Act & Assert
Assert.Throws<ArgumentException>(() => tester.ValidateName(fname, lname));
}
}
}
<file_sep>/Store.WebUI/Store.Data/Repositories/LocationRepository.cs
using Microsoft.EntityFrameworkCore;
using Store.DataAccess.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.DataAccess.Repositories
{
public class LocationRepository : Store.Logic.Interfaces.ILocationRepository
{
private readonly project1rincongamezonestoreContext _dbContext;
public LocationRepository(project1rincongamezonestoreContext dbContext)
{
_dbContext = dbContext;
}
public IEnumerable<Store.Logic.Models.Product> GetInventory(int id)
{
List<Inventory> storeInventory = _dbContext.Inventories.Where(sinv => sinv.StoreId == id).ToList();
List<Product> inventoryProducts = _dbContext.Inventories.Include(p => p.Product).Where(pinv => pinv.StoreId == id).Select(p => p.Product).ToList();
List<Store.Logic.Models.Product> inventory = new List<Store.Logic.Models.Product>();
foreach(Product p in inventoryProducts)
{
inventory.Add(new Logic.Models.Product { Id = p.ProductId, Type = p.Type, Name = p.Name, Price = p.Price});
System.Diagnostics.Debug.WriteLine("Product: " + p.ProductId + " Type: " + p.Type + " Name: " + p.Name + " Price: " + p.Price);
}
return inventory;
}
public void Save()
{
_dbContext.SaveChanges();
}
}
}
<file_sep>/Store.WebUI/Store.Logic/Interfaces/ICustomerRepository.cs
using Store.Logic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Logic.Interfaces
{
public interface ICustomerRepository
{
/// <summary>
/// Add Customer to Database.
/// </summary>
public void AddCustomer(Customer cust);
/// <summary>
/// Get customer from database given an email and password.
/// </summary>
public Customer GetCustomerByEmail(string email, string password);
/// <summary>
/// Get customer from database given an email.
/// </summary>
//public Customer GetCustomerByEmail(string mail);
/// <summary>
/// Get all customers from database.
/// </summary>
//public IEnumerable<Customer> GetCustomers();
/// <summary>
/// Save changes to Database.
/// </summary>
public void Save();
}
}
<file_sep>/Store.WebUI/Store.WebUI/Controllers/CustomerController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Store.Logic.Interfaces;
using Store.WebUI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Store.WebUI.Controllers
{
[ApiController]
public class CustomerController : ControllerBase
{
private ICustomerRepository _customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
[HttpPost("api/customer/registration")]
public void AddCustomer(WebCustomer customer)
{
// Store WebCustomer data into Logic Customer Model
Store.Logic.Models.Customer newCustomer = new Logic.Models.Customer(customer.FirstName, customer.LastName, customer.Email, customer.Password, customer.Admin);
// Call method AddCustomer from CustomerRepository
_customerRepository.AddCustomer(newCustomer);
//// Save form data in database
_customerRepository.Save();
}
// Get customer for login
[HttpGet("api/customer/login")]
public WebCustomer GetCustomer(string email, string password)
{
var customerData = _customerRepository.GetCustomerByEmail(email, password);
return new WebCustomer {
FirstName = customerData.FirstName,
LastName = customerData.LastName,
Email = customerData.Email,
Password = <PASSWORD>
};
}
}
}
<file_sep>/Store.WebUI/Store.WebUI/Controllers/ProductController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Store.DataAccess.Repositories;
using Store.Logic.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Store.WebUI.Controllers
{
[ApiController]
public class ProductController : ControllerBase
{
private IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
[HttpGet("api/product/all")]
public IEnumerable<Store.Logic.Models.Product> GetProducts()
{
return _productRepository.GetProducts();
}
}
}
<file_sep>/Store.WebUI/Store.Logic/Models/Customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Logic.Models
{
public class Customer
{
/// <summary>
/// Customer First Name.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Customer Last Name.
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Customer Id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Customer Email to login to store.
/// </summary>
public string Email { get; set; }
/// <summary>
/// Customer password to login to store.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Determines whether customer is an admin of the website.
/// </summary>
public bool Admin { get; set; }
/// <summary>
/// Empty Constructor for queries.
/// </summary>
public Customer()
{
}
/// <summary>
/// Constructor for use of UI.
/// </summary>
public Customer(string firstName, string lastName, string email, string password, bool admin)
{
if (ValidateName(firstName, lastName))
{
FirstName = firstName;
LastName = lastName;
Email = email;
Password = <PASSWORD>;
Admin = admin;
}
}
/// <summary>
/// Validate first name and last name provided by user input.
/// </summary>
public bool ValidateName(string fname, string lname)
{
// Validate customer name
if (fname is null || lname is null)
{
throw new ArgumentNullException("First and last name must not be empty.", nameof(fname));
}
foreach (char letter in fname)
{
if (!(Char.IsLetter(letter)))
{
throw new ArgumentException("Use letters only.", nameof(fname));
}
}
foreach (char letter in lname)
{
if (!(Char.IsLetter(letter)))
{
throw new ArgumentException("Use letters only.", nameof(lname));
}
}
return true;
}
}
}
<file_sep>/Store.WebUI/Store.Logic/Models/Location.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Logic.Models
{
class Location
{
/// <summary>
/// Location inventory of products, where the id serves as the key and the product is the value.
/// </summary>
private Dictionary<int, Product> _inventory = new Dictionary<int, Product>();
public Dictionary<int, Product> Inventory { get; }
/// <summary>
/// Location address.
/// </summary>
public string Address { get; set; }
/// <summary>
/// Location id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// List of location inventory ids.
/// </summary>
private List<int> _inventoryId = new List<int>();
public List<int> InventoryId { get; }
/// <summary>
/// Retrieve location inventory from a given supplier.
/// </summary>
public void RetrieveInventory(List<Product> supplier)
{
foreach (Product supplierItem in supplier)
{
_inventory.Add(supplierItem.Id, supplierItem);
}
}
/// <summary>
/// Update inventory.
/// Remove items in inventory as orders are processed and approved.
/// </summary>
public bool UpdateInventory(Dictionary<Product, int> order)
{
// Remove quantity of a specific product in inventory based on order
foreach (var item in _inventory)
{
foreach (var customerItem in order)
{
if (item.Value.Id == customerItem.Key.Id && ((item.Value.Quantity - customerItem.Key.Quantity) > 0))
{
item.Value.Quantity -= customerItem.Key.Quantity;
}
else
{
RejectOrder(customerItem.Key.Name, order);
return false;
}
}
}
return true;
}
/// <summary>
/// Reject Order.
/// Cancel an order due to shortage of specific item in inventory.
/// </summary>
public void RejectOrder(string item, Dictionary<Product, int> order)
{
Console.WriteLine("Order has been rejected due to the following out of stock item: " + item);
order.Clear();
}
}
}
<file_sep>/Store.WebUI/Store.WebUI/wwwroot/signin.js
'use strict';
// Set up
const registrationForm = document.getElementById('registration-form');
const successMessage = document.getElementById('error-msg');
const errorMessage = document.getElementById('success-msg');
// Event listener
registrationForm.addEventListener('submit', event => {
event.preventDefault();
successMessage.hidden = true;
errorMessage.hidden = true;
const signinForm = {
FirstName: registrationForm.elements['FirstName'].value,
LastName: registrationForm.elements['LastName'].value,
Email: registrationForm.elements['Email'].value,
Password: registrationForm.elements['Password'].value,
PassWordRepeat: registrationForm.elements['PasswordRepeat'].value,
Admin: false
};
// Password validation
if (signinForm.Password != signinForm.PassWordRepeat) {
console.log("Passwords must match.");
return false;
}
console.log(signinForm)
sendSignInForm(signinForm)
.then(() => {
successMessage.textContent = 'Signup successful';
successMessage.hidden = true;
alert("Signup successful");
setTimeout(() => { window.location = "index.html";}, 5000);
})
.catch(error => {
errorMessage.textContent = error.toString();
errorMessage.hidden = false;
});
});
<file_sep>/Store.WebUI/Store.Data/Repositories/CustomerRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Store.DataAccess.Entities;
namespace Store.DataAccess.Repositories
{
public class CustomerRepository : Store.Logic.Interfaces.ICustomerRepository
{
private readonly project1rincongamezonestoreContext _dbContext;
public CustomerRepository(project1rincongamezonestoreContext dbContext)
{
_dbContext = dbContext;
}
public void AddCustomer(Store.Logic.Models.Customer cust)
{
var entity = new Customer
{
FirstName = cust.FirstName,
LastName = cust.LastName,
Email = cust.Email,
Password = <PASSWORD>,
Admin = cust.Admin
};
_dbContext.Add(entity);
}
public Store.Logic.Models.Customer GetCustomerByEmail(string email, string password)
{
var customer = _dbContext.Customers.Where(c => c.Email == email && c.Password == password).First();
return new Store.Logic.Models.Customer {
FirstName = customer.FirstName,
LastName = customer.LastName,
Email = customer.Email,
Password = <PASSWORD>
};
}
public void Save()
{
_dbContext.SaveChanges();
}
}
}
<file_sep>/Store.WebUI/Store.WebUI/Models/WebCustomer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Store.WebUI.Models
{
public class WebCustomer
{
/// <summary>
/// Customer First Name.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Customer Last Name.
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Customer Email to login to store.
/// </summary>
public string Email { get; set; }
/// <summary>
/// Customer password to login to store.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Determines whether customer is an admin of the website.
/// </summary>
public bool Admin { get; set; }
}
}
<file_sep>/Store.WebUI/Store.Logic/Interfaces/IProductRepository.cs
using Store.Logic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Logic.Interfaces
{
public interface IProductRepository
{
/// <summary>
/// Get all Products from Database.
/// </summary>
public IEnumerable<Product> GetProducts();
///<summary>
/// Add Product to db.
/// </summary>
//public void AddProduct(Product item);
/// <summary>
/// Remove Product from db.
/// </summary>
//public void RemoveProduct(Product item);
/// <summary>
/// Save changes to database.
/// </summary>
public void Save();
}
}
<file_sep>/Store.WebUI/Store.WebUI/wwwroot/index.js
'use strict';
// Load all products
const homeTable = document.getElementById('product-table');
const storeTable = document.getElementById('store-product-table');
const errorMessage = document.getElementById('error-message');
loadProducts()
.then(products => {
for (const item of products) {
const row = homeTable.insertRow();
row.innerHTML = `<td>${item.id}</td>
<td>${item.type}</td>
<td>${item.name}</td>
<td>${item.price}</td>`;
}
homeTable.hidden = false;
})
.catch(error => {
errorMessage.textContent = error.toString();
errorMessage.hidden = false;
});
// Load store inventory
function loadInventory(store) {
const locStore = document.getElementById(store);
const storeId = locStore.value;
var url = storeId !== undefined ? `api/store/products?storeid=${storeId}` : 'api/store/products';
return fetch(url).then(response => {
if (!response.ok) {
throw new Error(`Network response not ok (${response.status})`);
}
return response.json();
})
.then(products => {
homeTable.hidden = true;
for (const item of products) {
const row = storeTable.insertRow();
row.innerHTML = `<td>${item.id}</td>
<td>${item.type}</td>
<td>${item.name}</td>
<td>${item.price}</td>`;
}
storeTable.hidden = false;
})
.catch(error => {
errorMessage.textContent = error.toString();
errorMessage.hidden = false;
});
}<file_sep>/Store.WebUI/Store.Logic/Interfaces/ILocationRepository.cs
using Store.Logic.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Logic.Interfaces
{
public interface ILocationRepository
{
///// <summary>
///// Add Location to database.
///// </summary>
//public void AddLocation(Location localStore);
///// <summary>
///// Remove Location from database.
///// </summary>
//public void RemoveLocation(Location localStore);
///// <summary>
///// Add Product to inventory.
///// </summary>
//public void AddProductToInventory(Product item);
///// <summary>
///// Remove Product from inventory.
///// </summary>
//public void RemoveProductFromInventory(Product item);
/// <summary>
/// Get products from inventory given the id of the store.
/// </summary>
public IEnumerable<Product> GetInventory(int id);
/// <summary>
/// Save changes to Database.
/// </summary>
public void Save();
}
}
<file_sep>/Store.WebUI/Store.Logic/Models/Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Store.Logic.Models
{
public class Product
{
/// <summary>
/// Type of product.
/// </summary>
public string Type { get; set; }
/// <summary>
/// Name of product.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Product Id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Price of product. In the inidvidual context it represents the unit price. In the context
/// of the customer it represents the total price given a specific quantity.
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// Quantity of product. Used by the customer.
/// </summary>
public int Quantity { get; set; }
/// <summary>
/// Empty constructor for queries.
/// </summary>
public Product()
{
}
}
}
<file_sep>/Store.WebUI/Store.Data/Entities/Product.cs
using System;
using System.Collections.Generic;
#nullable disable
namespace Store.DataAccess.Entities
{
public partial class Product
{
public Product()
{
Inventories = new HashSet<Inventory>();
OrderLines = new HashSet<OrderLine>();
}
public int ProductId { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public virtual ICollection<Inventory> Inventories { get; set; }
public virtual ICollection<OrderLine> OrderLines { get; set; }
}
}
<file_sep>/README.md
# GameZone Store
# Project Description #
GameZone Store is a webstore targeted at videogame retailers, with customer oriented navigation. Customers are able to register and login to the webstore.
Customers can also check products managed at the central store, and the three main locations. The products for the stores and locations are loaded from
a separate SQL database.
# Technologies #
* C#
* SQL Server
* Entitiy Framework
* HTML
* JavaScript
* Bootstrap 4.6.0
* ASP .NET Web API
# Features #
* Customer can signup/register to the webstore.
* Customer can login to the webstore.
* Customer can see the products managed by the main store and the three main locations.
To-do list:
* Implement functionality to allow customer to select a product and quantity after choosing a location from which to buy.
* Implement functionality to add selected products to a cart.
* Implement functionality to checkout products in cart.
# Getting started #
Use the command 'git clone' as shown below to copy the project from the repository.
* git clone https://github.com/2102-feb08-net/diego-project1.git
Create a SQL Database and an App Service in Azure Portal.
Copy the connection string from the SQL Database and add it to the connection strings in the App Service Configuration.
Open Microsoft SQL Server Management Studio and enter your credentials and SQL Database information.
Use the file GZStore_Schema_v1.sql to create the databse schema.
Open the project solution in Visual Studio.
Right click on Store.WebUI project and select the option 'Manage User Secrets.'
Add the database connection string to the user secrets.
Right-click on Store.WebUI project and select the option 'Publish.'
Follow the instructions and select your App Service when prompted.
Click on 'Publish' to launch the website.
Alternatively, the link below will lead you to the website.
* https://2102-rincon-gzstore.azurewebsites.net/index.html
* NOTE: The website will not be available if the App Service is stopped.
# Usage #
* On the navigation bar click on 'SignIn' and fill-in all fields to register to the store.
* On completion, a popup will be displayed to notify that signup was successful.
* On the navigation bar click on 'LogIn' and enter your email and password.
* On the navigation bar click on 'Location' and select any of the three locations to load its managed products.
<file_sep>/Store.WebUI/Store.WebUI/wwwroot/main.js
'use strict';
// Load all Store products
function loadProducts() {
return fetch('api/product/all').then(response => {
if (!response.ok) {
throw new Error(`Network response not ok (${response.status})`);
}
return response.json();
});
}
// Send new customer registration form
function sendSignInForm(signinForm) {
return fetch('api/customer/registration', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(signinForm)
}).then(response => {
if (!response.ok) {
throw new Error(`Network response not ok (${response.status})`);
}
});
}
// Load customer data
function loadCustomer(email, password) {
var url = email !== undefined && password !== undefined ? `api/customer/login?email=${email}&&password=${password}` : '/api/customer/login';
return fetch(url).then(response => {
if (!response.ok) {
throw new Error(`Network response not ok (${response.status})`);
}
return response.json();
});
}<file_sep>/Store.WebUI/Store.WebUI/Controllers/LocationController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Store.Logic.Interfaces;
namespace Store.WebUI.Controllers
{
[ApiController]
public class LocationController : ControllerBase
{
private ILocationRepository _locationRepository;
public LocationController(ILocationRepository locationRepository)
{
_locationRepository = locationRepository;
}
[HttpGet("api/store/products")]
public IEnumerable<Store.Logic.Models.Product> GetStoreProducts(int storeId)
{
return _locationRepository.GetInventory(storeId);
}
}
}
<file_sep>/Store.WebUI/Store.Data/Repositories/ProductRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Store.DataAccess.Entities;
namespace Store.DataAccess.Repositories
{
public class ProductRepository : Store.Logic.Interfaces.IProductRepository
{
private readonly project1rincongamezonestoreContext _dbContext;
public ProductRepository(project1rincongamezonestoreContext dbContext)
{
_dbContext = dbContext;
}
// Make the list of products
private List<Store.Logic.Models.Product> _products;
// Return list of products
public IEnumerable<Store.Logic.Models.Product> GetProducts() {
IQueryable<Product> items = _dbContext.Products;
_products = items.Select(p => new Store.Logic.Models.Product
{
Type = p.Type,
Name = p.Name,
Id = p.ProductId,
Price = p.Price
}).ToList();
return _products;
}
public void Save()
{
_dbContext.SaveChanges();
}
}
}
| abbd1a4c81dfd5d7a8ce7311c0019f4b7522af52 | [
"JavaScript",
"C#",
"Markdown"
] | 20 | C# | 2102-feb08-net/diego-project1 | b3356e993575b8b13c37a5ee56ed021b43ba5aab | 0e9e82c664988c48fcd032019df9148f82af886c |
refs/heads/master | <file_sep># coding=utf8
from flask import Flask
from flask_cors import CORS
from flask_restful import Api
from src.user.user import User
from src.games.recognizer.recognize import Recognizer
app = Flask(__name__)
api = Api(app)
CORS(app)
api.add_resource(User, '/users')
api.add_resource(Recognizer, '/games/recognizer')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=3000, debug=True)
<file_sep># coding:utf8
import numpy as np
from pandas import DataFrame
dataframe = DataFrame(np.ones((4,4)))
dict1 = {}
#去掉全0行
rows = {}
<file_sep># coding:utf8
import functools
import os
from PIL import Image, ImageEnhance
from pandas import DataFrame
from pytesser import image_to_string
from config import configs
from src.utils.distance import *
class AbstractParser():
def __init__(self):
pass
def parse(self):
pass
# 图片预处理装饰器
def preHandle(func):
@functools.wraps(func)
def decorator(image):
image = image.resize((300, 370), Image.BOX)
image = image.convert("L")
ret = func(image)
return ret
return decorator
# 加载训练图片dataframe
def load_dataset():
sample_dir = configs.get("recognizer_sample_dir")
files = os.listdir(sample_dir)
dataset = np.mat([])
index = []
for file in files:
image = Image.open(os.path.join(sample_dir, file))
row = image_to_vector(image)
index.append(file.replace(".png", ""))
if (dataset.size == 0):
dataset = np.mat(row)
else:
dataset = np.row_stack((dataset, row))
dataframe = DataFrame(dataset, index)
return dataframe
# 图片转矩阵,传入:图片对象,返回:矩阵
def image_to_matrix(image):
width, height = image.size
image = image.resize((300, 370), Image.BOX)
image = image.convert("L")
data = image.getdata(0)
data = np.matrix(data, dtype='float') / 255.0
matrix = np.reshape(data, (width, height))
return DataFrame(matrix)
# 矩阵转图片,传入:矩阵,返回:图片对象
def matrix_to_image(matrix):
matrix = matrix * 255.0
image = Image.fromarray(matrix.astype(np.uint8))
return image
# 图片转向量
def image_to_vector(image):
image = image.resize((300, 370), Image.BOX)
image = image.convert("L")
data = image.getdata(0)
vector = np.array(data, dtype='float') / 255.0
return vector
class PytesserParser(AbstractParser):
# 直接识别图片
def parse(self, image):
image = image.resize((300, 370), Image.BOX)
image = image.convert("L")
enhancer = ImageEnhance.Contrast(image)
image_enhancer = enhancer.enhance(4)
return image_to_string(image_enhancer)
class KnnParser(AbstractParser):
def parse(self, image):
vector = image_to_vector(image)
dataframe = load_dataset()
distances = {}
for index, row in dataframe.iterrows():
distances[index] = eucldist(vector, row)
result = min(distances.items(), key=lambda x: x[1])[0]
return result
if __name__ == '__main__':
parser = KnnParser()
result = parser.parse(Image.open('w:\\1.png'))
print result<file_sep>configs = {
'recognizer_sample_dir': 'w:\\myrepository\\hydra\\sample\\recognizer',
'upload_dir': 'w:\\myrepository\\hydra\\upload',
'allowed_extensions': set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']),
}
<file_sep>import numpy as np
""" Calculates the euclidean distance between 2 lists of coordinates. """
def eucldist(vector1, vector2):
return np.sqrt(np.sum((vector1 - vector2) ** 2))
<file_sep># coding=utf8
import json
import os
from flask import request
from flask_restful import Resource
from werkzeug.utils import secure_filename
from PIL import Image
from config import configs
from src.games.recognizer.image_parser import KnnParser
class Recognizer(Resource):
# 上传图片并识别
def post(self):
file = request.files['the_image']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file_path = os.path.join(configs.get("upload_dir"), filename)
file.save(file_path)
else:
return {"message": "illegal filename or empty file!"}
parser = KnnParser()
result = parser.parse(Image.open(file_path))
return {'result': result}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in configs.get("allowed_extensions")
<file_sep>from flask_restful import Resource
class User(Resource):
def get(self):
return [{
'name': 'zhaozhe',
'email': '<EMAIL>',
'website': 'www.imzhaozhe.com'
}]
| 0391e9fde5b1b214336491963b01763865e85b30 | [
"Python"
] | 7 | Python | zzl1787/hydra | ded008cf6529a24788e3bfd1656b25bbddfbfa06 | 27c0aeeeaea50153e5e40853d825a81fdc3f3034 |
refs/heads/master | <file_sep>import { AppService } from './../app.service';
import { Component, OnInit } from '@angular/core';
import { Config } from 'protractor';
@Component({
selector: 'app-ahri',
templateUrl: './ahri.component.html',
styleUrls: ['./ahri.component.css']
})
export class AhriComponent implements OnInit {
constructor(private service: AppService) { }
dataList = [];
ngOnInit() {
this.service.getData('/violet').subscribe((data: Config) => this.dataList = data.violet);
}
}
<file_sep>import { AhriComponent } from './../ahri/ahri.component';
import { VioletComponent } from './../violet/violet.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {RouterModule,Routes} from '@angular/router';
const router: Routes = [{
path: 'ahri', component: AhriComponent
},{
path: 'violet', component: VioletComponent
},{
path: '', redirectTo: 'violet', pathMatch: 'full'
}];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(router)
],
declarations: [],
exports: [RouterModule]
})
export class RouteModule { }
| 50302b2672468315aea0615475dc7bdd3aa815a3 | [
"TypeScript"
] | 2 | TypeScript | xujunBachlor/violet-web | dbf8fee3126f3fa8a12901a1ad7d0bd6059908df | baa0784f9856cbad7a5de02533a839e2d6cc6bbe |
refs/heads/master | <repo_name>EmanuelSamir/jobatrep<file_sep>/Documentación/Local Binary Pattern.md
## Local Binary Pattern applied to corrosion grade samples ISO 8501
* Conditions:
* N = 10
* P = 16
* SIGMA_START = 1
* HBINS = 20
* Grayscale processed
1. Grade A

2. Grade B

1. Grade C

2. Grade D

* Conditions
* N = 10
* P = 16
* SIGMA_START = 1
* HBINS = 20
* Red channel processed
1. Grade A

2. Grade B

3. Grade C

4. Grade D

Sample Test
<file_sep>/Documentación/Inform090819.md
### Análisis de imágenes
#### Objetivo
* Clasificar nivel de corrosión. Importante es detectar si hay corrosión nociva.
* Identificar a qué perfile posee corrosión para pode generar un aviso automáticamente.
* Detectar si pieza está faltante. (Posiblemente realizable mediante otras metodologías. e.g. GUI más intuitivo)
* Realizar acciones similares con demás partes: aisladores, conductores, ... etc
#### Proceso a seguir
Recolección de imágenes -> Obtener información familia de torre -> Detectar zonas de corrosión -> Detectar piezas faltantes -> Correlacionar perfiles afectados con códigos -> Realizar aviso
1. **Recolección de base de datos**
* Considerar:
* Machine Learning: Supervised (Dataset.. Debe ser grande y con etiquetas), **Unsupervised** (Dataset sin etiquetas), Reinforcement Learning (Acciones y Environment).

Dado que las fotos no tienen etiquetas, dónde está la corrosión, qué nivel es se considera técnicas de no-supervisado
* Para la toma de fotos se tiene como opciones: por Persona (Foto grande), **por Drone (varias fotos)** e Infrarrojo
* Foto grande: Una foto de más de 20 Mpx. Desventaja: NO ROBUSTA


- Varias fotos: Se debe hacer encajar las fotos o grabación. e.g. Foto panorámica. Puede utilizarse el dato de posición y orientación del drone (disponible?).

- Infrarrojo: Se leyó que se puede obtener información de fotos infrarrojas. Falta información.
2. Clasificación de qué familia de torre
* GPS datos. Las torres están categorizadas por posición?
* Correlación entre imagen y planos. Mayor Complejidad
3. Detección de corrosión: Se debe evitar que la propuesta sea ad hoc a cada foto. Generalizar.
* Se propone dividir esto en sub procesos
* Segmentación. Aprovechar lineas de perfiles (Hough Transform)

Falta perfeccionar.


* Análisis por color, textura, forma (poco).
* Color: HSI. Histograma

* Textura: Wavelet, GLMC. Entropía. Cuánto desorden hay?
* Redes Neuronales Convolucionales.
4. Detectar piezas faltantes -> Correlacionar perfiles afectados con códigos
Se sugiere una correlación entre imagen y planos
* 2D: Stitching. Planos por caras. Requiere solo fotos.
* Desventajas: Sombras. Torres 3D por lo que la parte trasera es importante pero se omite.
* Ventajas: Bajo costo computacional, más controlado (se puede ver errores fácilemente)
* 3D: Nube de puntos. Planos 3D. Requiere coordenadas (Drone puede proveer de estos datos?).
* Desventajas: Complejidad mucho mayor. No se tienen todos los planos. No se puede ver errores. Requiere cierta manipulación del Drone más cuidadosa
* Ventaja: Más completo, provee de mayor información. Matching posiblemente mejor.
* https://www.youtube.com/watch?v=ok2_1hEqEIk
- Manejo de informes: Metodología por Sprints. Trello al día para monitoreo diario.
- Qué tipo de informe presentaré<file_sep>/MeanShift.py
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
from matplotlib import pyplot as plt
from scipy.ndimage import gaussian_laplace, laplace, sobel, gaussian_filter
from scipy.interpolate import interp2d
from PIL import Image
from tqdm import tqdm
from skimage.color import rgb2hsv
# #############################################################################
# Generate sample data
centers = [[1, 1], [-1, -1], [1, -1]]
#X, _ = make_blobs(n_samples=10000, centers=centers, cluster_std=0.6)
image_file = 'tower.jpg'
img_rgb = np.array(Image.open(image_file))
height, width, channel = img_rgb.shape
hsv_img = rgb2hsv(img_rgb)
X = []
with tqdm(total=height*width) as pbar:
for i in range(height):
for j in range(width):
X.append([0.05*i,0.05*j,img_rgb[i,j,0],img_rgb[i,j,1],img_rgb[i,j,2],hsv_img[i,j,0],hsv_img[i,j,1],hsv_img[i,j,2]])
pbar.update(1)
# #############################################################################
# Compute clustering with MeanShift 0.1*i,0.05*j,
# The following bandwidth can be automatically detected using
X = np.array(X)
bandwidth = estimate_bandwidth(X, quantile=0.1, n_samples=100)
print(bandwidth)
ms = MeanShift(bandwidth=bandwidth, bin_seeding=True)
ms.fit(X)
labels = ms.labels_
cluster_centers = ms.cluster_centers_
labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)
print("number of estimated clusters : %d" % n_clusters_)
segmented_image = np.array(labels).reshape(height,width)
plt.figure(2)
plt.subplot(1, 2, 1)
plt.imshow(img_rgb)
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(segmented_image)
plt.axis('off')
plt.show()
# #############################################################################
# # Plot result
# import matplotlib.pyplot as plt
# from itertools import cycle
#
# plt.figure(1)
# plt.clf()
#
# colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
# for k, col in zip(range(n_clusters_), colors):
# my_members = labels == k
# cluster_center = cluster_centers[k]
# plt.plot(X[my_members, 0], X[my_members, 1], col + '.')
# plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
# markeredgecolor='k', markersize=14)
# plt.title('Estimated number of clusters: %d' % n_clusters_)
# plt.show()
<file_sep>/InterDataGenerator.py
import numpy as np
import matplotlib.pyplot as plt
import os
from PIL import Image
import random
import datetime
import logging
import pandas as pd
# from skimage.color import rgb2gray
import colorsys
from skimage.feature import greycomatrix, greycoprops
LEFTCLICK = 1
RIGHTCLICK = 3
NIMAGES = 15
class PixelPicking:
def __init__(self, image,ax, pointsCounter, Count):
self.image = image
self.Count = Count
self.ax = ax
self.color_rightclick = 'red'
self.color_leftclick = 'green'
self.xs_Tower = []
self.ys_Tower = []
self.xs_NoTower = []
self.ys_NoTower = []
self.cidmouse = image.figure.canvas.mpl_connect('button_press_event', self.mouseclickCall)
self.cidkey = image.figure.canvas.mpl_connect('key_press_event', self.keypressCall)
self.pointsCounter = pointsCounter
self.clicklst = []
self.shape = {}
self.sctlst = []
def mouseclickCall(self, event):
if event.button == LEFTCLICK: # Tower
# Append coordinates
self.xs_Tower.append(event.xdata)
self.ys_Tower.append(event.ydata)
sct = self.ax.scatter(self.xs_Tower[-1],self.ys_Tower[-1],s=10,color=self.color_leftclick)
self.sctlst.append(sct)
self.pointsCounter += 1
self.clicklst.append(LEFTCLICK)
self.ax.set_title('Image #' + str(self.Count) + " Total points: "+ str(self.pointsCounter))
self.image.figure.canvas.draw()
if event.button == RIGHTCLICK: # Tower
# Append coordinates
self.xs_NoTower.append(event.xdata)
self.ys_NoTower.append(event.ydata)
sct = self.ax.scatter(self.xs_NoTower[-1],self.ys_NoTower[-1],s=10,color=self.color_rightclick)
self.sctlst.append(sct)
self.pointsCounter += 1
self.clicklst.append(RIGHTCLICK)
self.ax.set_title('Image #' + str(self.Count) + " Total points: "+ str(self.pointsCounter))
self.image.figure.canvas.draw()
def keypressCall(self, event):
if event.key == 'r' and self.pointsCounter >= 1:
lastclick = self.clicklst[-1]
if lastclick == LEFTCLICK:
self.xs_Tower.pop(-1)
self.ys_Tower.pop(-1)
if lastclick == RIGHTCLICK:
self.xs_NoTower.pop(-1)
self.ys_NoTower.pop(-1)
self.clicklst.pop(-1)
self.pointsCounter -= 1
self.sctlst[-1].remove()
self.sctlst.pop(-1)
self.ax.set_title('Image #' + str(self.Count) + " Total points: "+ str(self.pointsCounter))
self.image.figure.canvas.draw()
def recoverData(self):
x_Tower, y_Tower, x_NoTower, y_NoTower = np.round(self.xs_Tower), np.round(self.ys_Tower), np.round(self.xs_NoTower), np.round(self.ys_NoTower)
return x_Tower, y_Tower, x_NoTower, y_NoTower, self.pointsCounter
def pixels2HSV(image, pix_y, pix_x):
h_params = []
s_params = []
v_params = []
r_params = []
g_params = []
b_params = []
for i, j in zip(pix_x, pix_y):
x = colorsys.rgb_to_hsv(image[i,j,0]/255., image[i,j,1]/255., image[i,j,2]/255.)#rgb2hsv(np.expand_dims(np.expand_dims(image[i,j,:], axis=0), axis=0))
#print(np.shape(x))
h_params.append(x[0])
s_params.append(x[1])
v_params.append(x[2])
r_params.append(image[i,j,0])
g_params.append(image[i,j,1])
b_params.append(image[i,j,2])
return h_params, s_params, v_params, r_params, g_params, b_params
def pixels2GLCM(image, pix_y, pix_x, window = 15):
distances = [2,3,4,5,6,7,8,9,10,11]
angles = [0, np.pi/4, np.pi/2]
contrast_params = []
dissimilarity_params= []
homogeneity_params= []
ASM_params = []
energy_params = []
correlation_params = []
gray = rgb2gray(image)
for i, j in zip(pix_x, pix_y):
# patch = rgb2gray(image[i-window:i+window, j-window:j+window,:].astype(float)).astype(int)
patch = gray[i-window:i+window, j-window:j+window]
glcm = greycomatrix(patch, distances, angles, 256)
dissimilarity_params.append(greycoprops(glcm, 'dissimilarity'))#[0, 0])
contrast_params.append(greycoprops(glcm, 'contrast'))#[0, 0])
homogeneity_params.append(greycoprops(glcm, 'homogeneity'))#[0, 0])
ASM_params.append(greycoprops(glcm, 'ASM'))#[0, 0])
energy_params.append(greycoprops(glcm, 'energy'))#[0, 0])
correlation_params.append(greycoprops(glcm, 'correlation'))#[0, 0])
return dissimilarity_params, contrast_params, homogeneity_params, ASM_params, energy_params, correlation_params
def rgb2gray(rgb):
x = np.round(np.dot(rgb[...,:3], [0.299, 0.587, 0.144]))
gray = np.clip(x.astype('int'),0,255)
return gray
def main():
# Read all image filenames
lst = os.listdir('.')
imageslst = [k for k in lst if '.JPG' in k]
random.shuffle(imageslst)
# Variables to save data. Count = how many images. images = each image used. pointsCounter = pixels counted
images = []
Count = 0
pointsCounter = 0
# dfcombined = Complete dataframe to be used
dfcombined = pd.DataFrame(columns = ['col-coord', 'row-coord', 'isTower', 'filename',
'h_params', 's_params', 'v_params',
'r_params', 'g_params', 'b_params',
'dissimilarity_params','contrast_params', 'homogeneity_params','ASM_params', 'energy_params', 'correlation_params'])
# For loop for first NIMAGES in shuffled image data
for imageName in imageslst[0:NIMAGES]:
Count += 1
print('###########################################')
print('######### Starting with #' + str(Count) + ' Image ########')
print('########################################### \n')
# Read image in list for each iter
im = np.array(Image.open(imageName))
# Open a figure for image plotting
f = plt.figure()
ax = f.add_subplot(111)
ax.set_title('Image #' + str(Count) + " Total point: " + str(pointsCounter) + '\n')
currentImage = ax.imshow(im)
# Function to save points through clicking manually
# Rigth click: isTower. Left Click: is not Tower. r: remove last point clicked
pixelpicking = PixelPicking(currentImage, ax, pointsCounter, Count)
ax.set_xlim(0,im[:,:,0].shape[1])
ax.set_ylim(0,im[:,:,0].shape[0])
plt.gca().invert_yaxis()
# Show image
plt.show()
print('When enough points were marked, close the window to continue \n')
images.append(im)
# Recover data selected through clicking
xs_Tower, ys_Tower, xs_NoTower, ys_NoTower, pointsCounter_ = pixelpicking.recoverData()
print('Total of points recovered in this step are: ' + str(pointsCounter_ - pointsCounter) + '\n')
pointsCounter = pointsCounter_
# Close figure
plt.close(f)
print('Pixels selected are recovered and about to be processed \n')
print('Saving data in a dataframe \n')
# Creating dataframe and fill it with data alreadyknown
df = pd.DataFrame(columns =['col-coord', 'row-coord', 'isTower'])
df['col-coord'] = np.concatenate([xs_Tower, xs_NoTower]).astype(int)
df['row-coord'] = np.concatenate([ys_Tower, ys_NoTower]).astype(int)
df['isTower'] = (len(xs_Tower)*['Yes'] + len(xs_NoTower)*['No'])
df['filename'] = (len(xs_Tower) + len(xs_NoTower)) * [imageName]
# Add data from color maps: rgb and hsv
print('HSV data collection \n')
h_params, s_params, v_params, r_params, g_params, b_params = pixels2HSV(im, df['col-coord'].astype(int), df['row-coord'].astype(int))
df['h_params'] = h_params
df['s_params'] = s_params
df['v_params'] = v_params
df['r_params'] = r_params
df['g_params'] = g_params
df['b_params'] = b_params
# Add data from GLCM arrays with patchs centered at pixels selected
print('GLCM parameters collection \n')
dissimilarity_params, contrast_params, homogeneity_params, ASM_params, energy_params, correlation_params = pixels2GLCM(im, df['col-coord'], df['row-coord'])
df['dissimilarity_params'] = dissimilarity_params
df['contrast_params'] = contrast_params
df['homogeneity_params'] = homogeneity_params
df['ASM_params'] = ASM_params
df['energy_params'] = energy_params
df['correlation_params'] = correlation_params
print('Merging temporal dataframe from this step with global dataframe \n')
dfcombined = pd.concat([dfcombined, df], ignore_index = True)
print('All images were already processed\n')
print(dfcombined[['col-coord','isTower','contrast_params','filename']])
filename_csv = 'df' + str(datetime.date.today())+ '_n' +str(Count) +'_p' +str(pointsCounter) + '.pkl'
dfcombined.to_pickle(r'./' + filename_csv)#, index = None, header=True)
print('Dataframe saved in csv with name: ', filename_csv,'\n')
print('Quitting')
if __name__ == "__main__":
main()
<file_sep>/Documentación/Mean Shift Implementation - Results.md
## Mean Shift Implementation - Results
Algorithms from library skilearn were applied to the image `tower.jpg`.
#### Forward Implementation to RGB Channels

#### Coordinates + RGB Channels

#### Weighted Coordinates + RGB Channels
* w = 0.5

* 0.3

* 0.15

#### Forward HSV implementation

#### Coordinates + HSV Channels

#### Weighted Coordinates + RGB Channels
* w = 0.5

* w = 0.3

* w = 0.05

#### RGB + HSV channels

#### RGB + HSV + coordinates

#### RGB + HSV + weighted coordinates
* w = 0.3

* w = 0.05

<file_sep>/Documentación/Inform220819.md
Neural Network for tower segmentation
#### df2019-08-19_n15_p2708.pkl
Only colors:



Colors and 42 GLCM parameters:
##### 200 random points



##### 1300 random points

ANOTHER PIC

<file_sep>/LBP.py
import numpy as np
from matplotlib import pyplot as plt
from scipy.ndimage import gaussian_laplace, laplace, sobel, gaussian_filter
from scipy.interpolate import interp2d
from PIL import Image
from tqdm import tqdm
N = 10
P = 16
SIGMA_START = 1
HBINS = 20
IMAGEFILE = 'Class_D.jpg'
def get_pixel(img, center, x, y):
new_value = 0
try:
if img(y,x) >= center:
new_value = 1
except:
pass
return new_value
def get_phase(L_x, L_y, x, y, radius):
L_x_ = L_x[radius - SIGMA_START]
L_y_ = L_y[radius - SIGMA_START]
# Extract patch
L_x_patch = L_x_[x-radius:x+radius+1,y-radius:y+radius+1]
L_y_patch = L_y_[x-radius:x+radius+1,y-radius:y+radius+1]
magnitude = (L_x_patch**2 + L_y_patch**2)**(1/2)
yy, xx = np.meshgrid(np.arange(-radius,radius+1), np.arange(-radius,radius+1))
distances = 1/2/np.pi/radius**2 * np.exp(-( ( (xx)**2 + (yy) **2)/2/radius**2))
theta = np.arctan2(L_x_patch,L_y_patch)
rows, cols = magnitude.shape
hist, bin_edges = np.histogram(
theta.reshape(rows*cols,),
weights = (distances * magnitude).reshape(rows*cols,),
bins = np.linspace(-np.pi, np.pi, num = HBINS)
)
return (np.diff(bin_edges)/2 + bin_edges[0:-1])[np.argmax(hist)]
def lbp_calculated_pixel(img, x, y, radius, L_x, L_y, th):
x_pad = x + N
y_pad = y + N
theta = get_phase(L_x, L_y, x_pad, y_pad, radius)
th.th.append(theta)
xp_v = x + radius * np.cos(2*np.pi*np.arange(P)/P + theta)
yp_v = y - radius * np.sin(2*np.pi*np.arange(P)/P + theta)
center = img(y,x)
val_ar = []
for i in range(P):
val_ar.append(get_pixel(img, center, xp_v[i], yp_v[i]))
val = val_ar * 2**np.arange(P)
return np.sum(val)
def show_output(output_list):
output_list_len = len(output_list)
figure = plt.figure()
for i in range(output_list_len):
current_dict = output_list[i]
current_img = current_dict["img"]
current_xlabel = current_dict["xlabel"]
current_ylabel = current_dict["ylabel"]
current_xtick = current_dict["xtick"]
current_ytick = current_dict["ytick"]
current_title = current_dict["title"]
current_type = current_dict["type"]
current_plot = figure.add_subplot(1, output_list_len, i+1)
if current_type == "gray":
current_plot.imshow(current_img, cmap = plt.get_cmap('gray'))
current_plot.set_title(current_title)
current_plot.set_xticks(current_xtick)
current_plot.set_yticks(current_ytick)
current_plot.set_xlabel(current_xlabel)
current_plot.set_ylabel(current_ylabel)
elif current_type == "red":
a = np.expand_dims(current_img,axis = 2)
print(a)
print(a.dtype)
print(a.shape)
b = (np.concatenate([a, np.zeros(a.shape, dtype = int),np.zeros(a.shape, dtype = int)], axis = 2))
print(b)
print(b.dtype)
print(b.shape)
current_plot.imshow(b)
current_plot.set_title(current_title)
current_plot.set_xticks(current_xtick)
current_plot.set_yticks(current_ytick)
current_plot.set_xlabel(current_xlabel)
current_plot.set_ylabel(current_ylabel)
elif current_type == "histogram":
current_plot.hist(current_img, bins = np.linspace(0,2**P - 1, 2**(P-2)))
current_plot.set_xlim([0,260])
current_plot.set_title(current_title)
current_plot.set_xlabel(current_xlabel)
current_plot.set_ylabel(current_ylabel)
ytick_list = [int(i) for i in current_plot.get_yticks()]
current_plot.set_yticklabels(ytick_list,rotation = 90)
plt.show()
def get_scale(img):
log_scales = []
L_x = []
L_y = []
for sigma in np.arange(SIGMA_START,N):
log_scales.append(gaussian_laplace(img, sigma = sigma, output = float))
L_x.append( np.pad(
sobel(gaussian_filter(img, sigma = sigma), axis = 1, output = float),
((N, N),(N, N)) , 'reflect' , reflect_type = 'odd'
))
L_y.append( np.pad(
sobel(gaussian_filter(img, sigma = sigma), axis = 0, output = float),
((N, N),(N, N)) , 'reflect' , reflect_type = 'odd'
))
radius_array = np.argmax(np.array(log_scales), axis = 0) + SIGMA_START
return radius_array, log_scales, L_x, L_y
class Angle:
def __init__(self):
self.th = []
def rgb2gray(rgb):
x = np.round(np.dot(rgb[...,:3], [0.299, 0.587, 0.144]))
gray = np.clip(x.astype('int'),0,255)
return gray
def main():
image_file = IMAGEFILE
img_rgb = np.array(Image.open(image_file))
height, width, channel = img_rgb.shape
img_gray = img_rgb[:,:,0]#rgb2gray(img_rgb)
img_gray_f = interp2d(np.arange(width), np.arange(height), img_gray)
img_lbp = np.zeros((height, width), np.uint8)
th = Angle()
radius_array, log_scales, L_x, L_y = get_scale(img_gray)
with tqdm(total=height*width) as pbar:
for i in range(height):
for j in range(width):
img_lbp[i, j] = lbp_calculated_pixel(img_gray_f, i, j, radius_array[i,j], L_x, L_y, th)
pbar.update(1)
hist_lbp = img_lbp.reshape(height*width,)
h, b = np.histogram(radius_array.reshape(height*width,), bins = np.arange(N))
print(h)
print(b)
print("---------")
h, b = np.histogram(th.th, bins = np.linspace(-np.pi, np.pi, num = HBINS))
print(h)
print(b)
output_list = []
output_list.append({
"img": img_rgb,
"xlabel": "xlabel",
"ylabel": "ylabel",
"xtick": [],
"ytick": [],
"title": "Coloured Image",
"type": "gray"
})
output_list.append({
"img": img_gray,
"xlabel": "xlabel",
"ylabel": "ylabel",
"xtick": [],
"ytick": [],
"title": "Red Image",
"type": "red"
})
output_list.append({
"img": img_lbp,
"xlabel": "xlabel",
"ylabel": "ylabel",
"xtick": [],
"ytick": [],
"title": "LBP Image",
"type": "gray"
})
output_list.append({
"img": hist_lbp,
"xlabel": "Bins",
"ylabel": "Number of pixels",
"xtick": None,
"ytick": None,
"title": "Histogram(LBP)",
"type": "histogram"
})
show_output(output_list)
print("LBP Program is finished")
if __name__ == '__main__':
main()
| 02e960dce65456be63c926acb079a8290d2f83a0 | [
"Markdown",
"Python"
] | 7 | Markdown | EmanuelSamir/jobatrep | 6d7b382305ef18ab02b14b5e7698243b4b7fa8f2 | 56e2113a4a887ea192f21a8ecde7ed658f349e1a |
refs/heads/master | <file_sep>Project Environment Setup
==========================
### Node and Express Environment
- [x] Node and Express should be installed on the local machine. The project file server.js should require express(), and should create an instance of their app using express.
- [x] The Express app instance should be pointed to the project folder with .html, .css, and .js files.
### Project Dependencies
- [x] The ‘cors’ package should be installed in the project from the command line, required in the project file server.js, and the instance of the app should be setup to use cors().
- [x] The body-parser package should be installed and included in the project.
### Local Server
- [x] Local server should be running and producing feedback to the Command Line through a working callback function.
### API Credentials
- [x] Create API credentials on OpenWeatherMap.com
APIs and Routes
===============
### APP API Endpoint
- [x] There should be a JavaScript Object named projectData initiated in the file server.jsto act as the app API endpoint.
### Integrating OpenWeatherMap API
- [x] The personal API Key for OpenWeatherMap API is saved in a named const variable.
- [x] The API Key variable is passed as a parameter to fetch() .#
- [x] Data is successfully returned from the external API.
### Return Endpoint Data/GET Route I: Server Side
- [x] There should be a GET route setup on the server side with the first argument as a string naming the route, and the second argument a callback function to return the JS object created at the top of server code.
### Return Endpoint Data/GET Route II: Client Side
- [x] There should be an asynchronous function to fetch the data from the app endpoint
### POST Route
- [x] You should be able to add an entry to the project endpoint using a POST route setup on the server side and executed on the client side as an asynchronous function.
- [x] The client side function should take two arguments, the URL to make a POST to, and an object holding the data to POST.
- [x] The server side function should create a new entry in the apps endpoint (the named JS object) consisting of the data received from the client side POST.
Dynamic UI
==========
### Naming HTML Inputs and Buttons For Interaction
- [ ] The input element with the placeholder property set to “enter zip code here” should have an id of zip.
- [ ] The textarea included in project HTML should have an id of feelings.
- [ ] The button included in project HTML should have an id of generate.
### Assigning Element Properties Dynamically
- [ ] The div with the id, entryHolder should have three child divs with the ids:
- date
- temp
- content
### Event Listeners
- [ ] Adds an event listener to an existing HTML button from DOM using Vanilla JS.
- [ ] In the file app.js, the element with the id of generate should have an addEventListener() method called on it, with click as the first parameter, and a named callback function as the second parameter.
### Dynamically Update UI
- [ ] Sets the properties of existing HTML elements from the DOM using Vanilla JavaScript.
- [ ] Included in the async function to retrieve that app’s data on the client side, existing DOM elements should have their innerHTML properties dynamically set according to data returned by the app route.
<file_sep>//**********SETUP AN EXPRESS SERVER*********//
//express to run server and routes
const express = require('express');
//Initiate an instance of express called app
app = express()
//Dependencies
const bodyParser = require('body-parser')
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
//Initialize the main project folder. Basically get the broswer side files.
app.use(express.static(__dirname+'/website'));
//set the port number
const port = process.env.PORT || 8080
//create a new varible that is the server, using the .listen() method on the app instance.
//It accepts two arguments, one is the port and the other is a callback functioin that initiates the action once the server is
//created
//spin up the server
const server = app.listen(port, listening)
const projectData = []
function listening(){
console.log('The server is running on port ' + port)
}
app.get('/',(req,res)=>{
res.render("index")
})
app.post('/post',(req,res)=>{
projectData.push(req.body)
})
app.get('/all',(req,res) =>{
res.send(projectData)
})
<file_sep>/* Global Variables */
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.toLocaleString('default', { month: 'long' }) +' '+ d.getDate()+'/'+ d.getFullYear();
//http://api.openweathermap.org/data/2.5/weather?zip=11368&appid=<KEY>
const baseURL = "https://api.openweathermap.org/data/2.5/weather?zip="
const ApiKey = "&appid=<KEY>"
document.getElementById("generate").addEventListener('click', OnClick);
function OnClick(e){
e.preventDefault()
const Feelings = document.getElementById('feelings').value
const ZipCode = document.getElementById("zip").value
weatherData = getWeather(baseURL,ZipCode,ApiKey) //Call to a function that fetches data from the web, returns an
// of type [temperature, city]'
weatherData.then((result) => {
let journal = {
temp : result[0], //accessing temperature as the first index
city : result[1], //accessing city as the second index
feelings : Feelings,
date : newDate
}
postData('/post',journal).then(updateUI())
})
document.querySelector('form').reset()
}
const getWeather = async (baseURL,ZipCode,ApiKey) => {
const res = await fetch(baseURL+ZipCode+ApiKey) //ASYNC part, wait until fetch gets the complete dataS
try {
const weatherData = await res.json() //convert to JSON but wait for res to receive the data first
const tempinKelvin = weatherData['main']['temp'] //recieve the weather data by accessing it from a json
const city = weatherData['name']
const tempinFaren = (tempinKelvin - 273.15) * 1.8 + 32 //convert to Farehnheit from Kelvin
return [tempinFaren.toFixed(2), city]
} catch(error){
console.log('Error retrieving data')
}
}
const postData = async (url='', data={}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
// Body data type must match "Content-Type" header
body: JSON.stringify(data),
})
try {
const newData = await response.json()
console.log('this is the post function with body',newData)
return newData
} catch(error){
console.log('Failure to post data')
}
}
const updateUI = async () => {
const response = await fetch('/all')
try{
const projectData = await response.json()
const TempHead = document.querySelector('.card-header')
const TextContent = document.querySelector('.card-body')
const Datefooter = document.querySelector('.card-footer')
const parentNode = document.getElementById('entry')
projectData.forEach((element) =>{
let cloneHead = TempHead.cloneNode(true)
let cloneBody = TextContent.cloneNode(true)
let cloneFooter = Datefooter.cloneNode(true)
cloneHead.innerHTML = element.city + ', ' + element.temp + 'F'
cloneBody.innerHTML = element.feelings
cloneFooter.innerHTML = element.date
parentNode.appendChild(cloneHead)
parentNode.appendChild(cloneBody)
parentNode.appendChild(cloneFooter)
})
}catch(error){
console('error',error);
}
}
| e30e0821a836b0babd75b84f7ba3ffa90c52ee46 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | phurpatshering79/weather-journal-app | bde9cfa4e134548c750c1a76ec5e61e4402cd930 | c7a38ccfef914d957e1870817592b02d95767759 |
refs/heads/master | <file_sep>import random
import pytest
import requests
from src.generate_data import get_man_page_urls
def test_get_man_page_urls(capsys):
all_man_pages = get_man_page_urls()
assert len(all_man_pages) == 11267
resp = requests.get(random.choice(all_man_pages))
assert resp.status_code == 200
<file_sep>import time
from concurrent.futures import ProcessPoolExecutor
def foo3(x, y, size=1000):
time.sleep(size/1000)
return [x * y * z for z in range(size)]
def foo2(x, size=100):
print(x)
time.sleep(size/1000)
with ProcessPoolExecutor() as executor:
return [executor.submit(foo3, x, y).result() for y in range(size)]
return [foo3(x, y, 1000) for y in range(size)]
def foo1(size=10):
time.sleep(1 / size)
return [foo2(x, 100) for x in range(size)]
def square(x: int) -> int:
time.sleep(.01)
return x ** 2
def add_n(x: int, n:int = 1) -> int:
time.sleep(.01)
return x + 1
def combine(x: int, n: int = 1) -> int:
return add_n(square(x), n)
if __name__ == "__main__":
start = time.time()
initial = range(10000)
with ProcessPoolExecutor() as executor:
next = list(executor.map(square, initial))
with ProcessPoolExecutor() as executor:
final = [executor.submit(add_n, x, 5) for x in next]
done = time.time()
print(f"Done, {start} -> {done} = {done - start}")
start = done
with ProcessPoolExecutor() as executor:
next = list(executor.map(square, initial))
final = [executor.submit(add_n, x, 5) for x in next]
done = time.time()
print(f"Done, {start} -> {done} = {done - start}")
start = done
with ProcessPoolExecutor() as executor:
final = [executor.submit(combine, x, 5) for x in next]
done = time.time()
print(f"Done, {start} -> {done} = {done - start}")
<file_sep>import time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from src.generate_data import parse_web_page
from src.utils import read_csv
def parallelize(func, iterable, use_thread=True, *args, **kwargs):
pool_executor = ThreadPoolExecutor if use_thread else ProcessPoolExecutor
with pool_executor() as executor:
data = list(executor.map(func, iterable))
return data
if __name__ == "__main__":
data = read_csv("data/summary/common.csv")
urls = [row["doc_url"] for row in data if row["doc_url"]]
selected_urls = urls[:100]
start = time.time()
norm_result = [parse_web_page(url) for url in selected_urls]
done = time.time()
print(f"Done, initial {start} -> {done} = {done - start}")
start = done
thread_result = parallelize(parse_web_page, selected_urls, use_thread=True)
done = time.time()
print(f"Done, Threading {start} -> {done} = {done - start}")
# start = time.time()
# parallelize(parse_web_page, selected_urls, use_thread=False)
# # parallelize(print, selected_urls, use_thread=False)
# done = time.time()
# print(f"Done, Processing {start} -> {done} = {done - start}")
<file_sep># tech_summarization [WIP]
Abstractive summarization of man pages and technical documentation to generate TLDR pages.
### Usage:
#### To create the data set:
```bash
$ export PYTHONPATH=$(pwd)
$ python src/generate_data.py
```
#### To host the app:
```bash
$ docker build -t tech_summarization .
$ docker-compose up
```<file_sep>version: "3.7"
services:
tech_summarization:
# build:
# context: .
image: tech_summarization
container_name: TechSummarization
restart: always
# environment:
# - DOCKER_HOST=tcp://docker:2376
# - DOCKER_CERT_PATH=/certs/client
# - DOCKER_TLS_VERIFY=1
ports:
- "8888:8888"
- "8501:8501"
volumes:
- ./:/project
entrypoint: jupyter notebook --allow-root --ip=0.0.0.0 --port=8888 --notebook-dir=.
<file_sep>pytest>=6,<7
beautifulsoup4>=4,<5
ohmeow-blurr==0.0.18
datasets==1.1.3
streamlit==0.72.0
<file_sep>import csv
from typing import Dict, Iterable, Any
def read_csv(path: str) -> Iterable[Dict[str, Any]]:
"""Reads csv and yeilds row as dict"""
csv.field_size_limit(int(1e7))
with open(path, "r", newline="") as f:
reader = csv.DictReader(f)
for row in reader:
yield row
def write_csv(
path: str, data: Iterable[Dict[str, Any]], header: Iterable[str] = None
) -> None:
"""Writes data into csv"""
if not header:
header = data[0].keys()
with open(path, "w+", newline="") as f:
writer = csv.DictWriter(f, header)
writer.writeheader()
writer.writerows(data)
<file_sep>FROM gcr.io/kaggle-images/python@sha256:00a659cc16b91a6956ef066063a9083b6a70859e5882046f3251632f4927149e
EXPOSE 8888 8501
WORKDIR /project
RUN pip install --upgrade pip
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
<file_sep>import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from pathlib import Path
data_dir = Path("/kaggle/input/tldr-summary-for-man-pages/")
all_df = pd.concat([pd.read_csv(file) for file in data_dir.glob("*.csv")], ignore_index=True)
docs = all_df.loc[:, ["man_entry","doc_text"]].apply(lambda row: row.man_entry if not pd.isna(row.man_entry) else row.doc_text, axis=1)
docs.dropna(inplace=True)
all_df.count()
summary = all_df.tldr_summary[docs.index]
summary.shape, summary.count()
processed_df = pd.DataFrame(dict(text=docs, summary=summary))
processed_df.head()
processed_df.count()
########### Creating Batch loaders
import nlp
import pandas as pd
from fastai.text.all import *
from transformers import *
from blurr.data.all import *
from blurr.modeling.all import *
pretrained_model_name = "facebook/bart-large-cnn"
hf_arch, hf_config, hf_tokenizer, hf_model = BLURR_MODEL_HELPER.get_hf_objects(pretrained_model_name,
model_cls=BartForConditionalGeneration)
hf_arch, type(hf_config), type(hf_tokenizer), type(hf_model)
hf_batch_tfm = HF_SummarizationBeforeBatchTransform(hf_arch, hf_tokenizer, max_length=[256, 130])
blocks = (HF_TextBlock(before_batch_tfms=hf_batch_tfm, input_return_type=HF_SummarizationInput), noop)
dblock = DataBlock(blocks=blocks,
get_x=ColReader('text'),
get_y=ColReader('summary'),
splitter=RandomSplitter())
dls = dblock.dataloaders(processed_df, bs=2)
len(dls.train.items), len(dls.valid.items)
b = dls.one_batch()
len(b), b[0]['input_ids'].shape, b[1].shape
dls.show_batch(dataloaders=dls, max_n=2)
text_gen_kwargs = { **hf_config.task_specific_params['summarization'], **{'max_length': 130, 'min_length': 30} }
text_gen_kwargs
###################### Training
model = HF_BaseModelWrapper(hf_model)
model_cb = HF_SummarizationModelCallback(text_gen_kwargs=text_gen_kwargs)
learn = Learner(dls,
model,
opt_func=ranger,
loss_func=CrossEntropyLossFlat(),
cbs=[model_cb],
splitter=partial(summarization_splitter, arch=hf_arch)).to_fp16()
learn.create_opt()
learn.freeze()
learn.lr_find(suggestions=True)
b = dls.one_batch()
preds = learn.model(b[0])
len(preds),preds[0], preds[1].shape
learn.fine_tune(1)
learn.show_results(learner=learn, max_n=2)
################# Saving and Prediction
model_file = Path('models/bart_tldr.pkl')
learn.export(fname=model_file)
inf_learn = load_learner(fname=model_file)
inf_learn.blurr_summarize(test_article)<file_sep>from pathlib import Path
import pytest
from src.generate_data import get_doc_url, get_man_entry, parse_single_tldr
@pytest.mark.parametrize(
"text,expected",
[
("", None),
("simpole", None),
("https://google.com", "https://google.com"),
(
"star something http://www.youtube.com then end with something",
"http://www.youtube.com",
),
],
)
def test_get_doc_url(text, expected):
assert get_doc_url(text) == expected
@pytest.mark.parametrize(
"path, cmd, url",
[
("7z.md", "7z", "https://www.7-zip.org/"),
("ab.md", "ab", "https://httpd.apache.org/docs/2.4/programs/ab.html"),
("arch.md", "arch", None),
# ("alias.md", "alias", None),
# TODO: arch and alias man entryies are messed up example:
# The a\x08ar\x08rc\x08ch\x08h command with no arguments == The arch command with no arguments
],
)
def test_parse_single_man_page(path, cmd, url):
base_path = "tldr_repo/pages/common"
result = parse_single_tldr(base_path / Path(path))
assert result["command"] == cmd
assert result["doc_url"] == url
assert result["man_entry"] == None or cmd in result["man_entry"]
assert cmd in result["tldr_summary"]
@pytest.mark.parametrize(
"cmd, expected",
[(None, None), ("asdf", None), ("git", "git"), ("alias", "alias")],
)
def test_get_man_entry(cmd, expected):
result = get_man_entry(cmd)
assert result == expected or expected in result
<file_sep>import streamlit as st
from fastai.learner import load_learner
from pathlib import Path
def _max_width_():
max_width_str = f"max-width: 1000px;"
st.markdown(
f"""
<style>
.reportview-container .main .block-container{{
{max_width_str}
}}
</style>
""",
unsafe_allow_html=True,
)
_max_width_()
model_path = Path("bart_tldr.pkl")
# @st.cache(max_entries=3)
def load_model(path):
return load_learner(path)
tech_doc = st.text_area(
label="Man Page Entry",
value="Pls enter technical document you want to summarize",
height=500,
)
model = load_learner(fname=model_path)
st.markdown(f"### Summary:\n\n{model.blurr_summarize(tech_doc)[0]}")
<file_sep>import logging
import re
import subprocess as sp
from concurrent.futures.process import ProcessPoolExecutor
from concurrent.futures.thread import ThreadPoolExecutor
from pathlib import Path
import requests
from bs4 import BeautifulSoup, SoupStrainer
from src.utils import write_csv
BASE_URL = "https://man7.org/linux/man-pages/"
ALL_MAN_PAGE = "https://man7.org/linux/man-pages/dir_all_by_section.html"
URL_PATTERN = r"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?"
def parse_web_page(url: str, filter_tag: str = None) -> BeautifulSoup:
"""Given URL returns Beuatiful Soup object to scrap further"""
html = ""
try:
response = requests.get(url, timeout=(5, 6))
html = response.text
except Exception as e:
logging.error(f"Request to page {url} failed with error: {e.args}")
return BeautifulSoup(html, "lxml", parse_only=SoupStrainer(filter_tag))
def get_man_page_urls(url: str = ALL_MAN_PAGE) -> list:
"""Specific method to find all man page html page link"""
soup = parse_web_page(url, filter_tag="a")
hrefs = [link.get("href") for link in soup if link.has_attr("href")]
match_refs = [re.search(r"man\d/.+.html$", ref) for ref in hrefs]
return [BASE_URL + ref.group() for ref in match_refs if ref]
def save_man_page_urls(path: str = "data/man_page_urls.csv") -> None:
urls = get_man_page_urls()
write_csv(
path,
[
dict(
command=re.search(r"[^/]+$", url).group().split(".")[0],
man_page_url=url,
)
for url in urls
],
)
def get_man_entry(command: str) -> str:
"""Executes man command to fetch man page entry"""
if not command:
return None
try:
man_entry = sp.check_output(
["man", command],
timeout=5,
text=True,
)
filter_output = sp.check_output(
["col", "-b"],
input=man_entry,
timeout=5,
text=True,
)
return filter_output
except sp.SubprocessError as e:
logging.debug(f"Failed to get man page for {command} with error: {e.args}")
return None
def parse_single_tldr(page: Path) -> dict:
command = page.name.replace(".md", "")
man_entry = get_man_entry(command)
tldr_summary = page.read_text()
doc_url = get_doc_url(tldr_summary)
doc_text = parse_web_page(doc_url).text if doc_url else None
return dict(
command=command,
doc_url=doc_url,
doc_text=doc_text,
man_entry=man_entry,
tldr_summary=tldr_summary,
)
def generate_tech_summary_data(path: str = "tldr_repo/pages/") -> None:
"""Extracts command, tldr summary and man page entry"""
path = Path(path)
for tldr_path in path.iterdir():
tldr_pages = list(tldr_path.glob("*.md"))
with ThreadPoolExecutor(max_workers=5) as executor:
summary_data = list(executor.map(parse_single_tldr, tldr_pages))
write_csv(f"data/summary/{tldr_path.name}.csv", summary_data)
def get_doc_url(tldr_summary: str) -> str or None:
match = re.search(URL_PATTERN, tldr_summary)
return match.group() if match else None
if __name__ == "__main__":
# save_man_page_urls()
generate_tech_summary_data()
| 1db26b4d2fc6568df4c541dc0189412b274ebf5e | [
"YAML",
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 12 | Python | PuneethaPai/tech_summarization | 94d8880d1a3cf0629d1959b099189171a59a1db9 | 4c960f2b6191d32bfcefc3aec094d1863cc60fca |
refs/heads/master | <file_sep>
extern crate baggie;
use baggie::Baggie;
#[test]
fn test_baggie_get() {
let mut bag = Baggie::new();
bag.insert("key1", "Value1".to_owned());
bag.insert("key2", vec!["value", "2"]);
bag.insert("key3", 3);
let val: Option<&String> = bag.get("key1");
assert_eq!(Some(&"Value1".to_owned()), val);
let val = bag.get::<Vec<&str>, _>("key2");
assert_eq!(Some(&vec!["value", "2"]), val);
let val = bag.get::<i32, _>("key3");
assert_eq!(Some(&3), val);
// Arbitrary tests...
assert_eq!(bag.len(), 3); // len
// keys()
let mut keys = bag.keys().collect::<Vec<&&str>>();
keys.sort();
assert_eq!(keys, vec![&"key1", &"key2", &"key3"]);
// contains_key()
assert!(!bag.contains_key("key-does-not-exist"));
// remove()
assert!(bag.contains_key("key1"));
bag.remove("key1");
assert!(!bag.contains_key("key1"));
// is_empty()
assert!(!bag.is_empty());
// clear()
bag.clear();
assert!(bag.is_empty());
// debug
println!("{:?}", &bag);
}
#[test]
fn test_baggie_get_mut() {
let mut bag = Baggie::new();
bag.insert("key1", "Value1".to_owned());
bag.insert("key2", vec!["value", "2"]);
bag.insert("key3", 3);
let val: &mut String = bag.get_mut("key1").unwrap();
assert_eq!(&mut "Value1".to_owned(), val);
*val = "new_value".to_string();
let val: &mut String = bag.get_mut("key1").unwrap();
assert_eq!(&mut "new_value".to_owned(), val);
}
<file_sep>[package]
name = "baggie"
version = "0.2.1"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
description = "Container for storing mixed / heterogeneous values in a common structure"
readme = "README.md"
keywords = ["heterogeneous", "bag", "collection", "hashmap"]
homepage = "https://github.com/milesgranger/baggie"
repository = "https://github.com/milesgranger/baggie"
license = "MIT"
exclude = ["/.gitignore", ".travis.yml", ".cargo/config"]
documentation = "https://docs.rs/crate/baggie/"
[dependencies]
<file_sep># baggie
---
[](https://travis-ci.com/milesgranger/baggie)
[](https://crates.io/crates/baggie)
[](https://coveralls.io/github/milesgranger/baggie?branch=master)
`Baggie` is simple interface for storing any type of element in a `HashMap`.
The crate has no dependencies, and is really just a helper around storing and
fetching `Any`s from a `HashMap`. It has no unsafe code and free of any unwraps
or similar misgivings.
The `Baggie` implements a subset of methods found in HashMap.
The downside of this crate is you must know the type of what you stored later on.
Typically this shouldn't be a problem, as you could keep some metadata structure
describing what types belong to what keys you've stored.
_Sometimes_ you might need a tool like this, but _most times_ you should be using an enum. :)
```rust
use baggie::Baggie;
let mut bag = Baggie::new();
// Insert any value type you wish...
bag.insert("key1", "Value1".to_owned());
bag.insert("key2", vec!["value", "2"]);
bag.insert("key3", 3);
// Get a reference
let val3 = bag.get::<i32, _>("key3");
assert_eq!(Some(&3), val3);
// Get a mutable reference
let val2: Option<&mut Vec<&str>> = bag.get_mut("key2");
match val2 {
Some(v) => *v = vec!["new", "value", "2"],
None => panic!()
}
let val2: &mut Vec<&str> = bag.get_mut("key2").unwrap();
assert_eq!(val2, &mut vec!["new", "value", "2"]);
```<file_sep>use std::collections::{HashMap, hash_map::Keys};
use std::any::Any;
use std::hash::Hash;
use std::borrow::Borrow;
/// struct for collecting values of any type with a string key
#[derive(Default, Debug)]
pub struct Baggie<K>
where K: Eq + Hash
{
data: HashMap<K, Box<Any>>
}
impl<K> Baggie<K>
where K: Eq + Hash + Default
{
/// Initialize an empty `Baggie`
pub fn new() -> Self {
Default::default()
}
/// Insert a value into the baggie.
pub fn insert<T: 'static>(&mut self, key: K, value: T) {
let value = Box::new(value);
self.data.insert(key.into(), value);
}
/// Get a reference to something in the baggie
pub fn get<T: 'static, Q: ?Sized>(&self, key: &Q) -> Option<&T>
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.get(key)?.downcast_ref::<T>()
}
/// Get a mutable reference to something in the baggie
pub fn get_mut<T: 'static, Q: ?Sized>(&mut self, key: &Q) -> Option<&mut T>
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.get_mut(key)?.downcast_mut::<T>()
}
/// An iterator visiting all keys in arbitrary order.
pub fn keys(&self) -> Keys<'_, K, Box<dyn Any>> {
self.data.keys()
}
/// Number of elements in the map
pub fn len(&self) -> usize {
self.data.len()
}
/// Clear the map of all key value pairs; but maintains allocated memory
pub fn clear(&mut self) {
self.data.clear()
}
/// Determine if the Baggie is empty
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// Returns true if the map contains a value for the given key.
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.contains_key(key)
}
/// Remove a key-value pair from the Baggie by key.
/// if the key value pair existed, the raw [`Box<dyn Any>`] value will be returned
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Box<dyn Any>>
where K: Borrow<Q>,
Q: Eq + Hash
{
self.data.remove(key)
}
}
<file_sep>#![warn(missing_docs)]
//! [`Baggie`] is simple interface for storing any type of element in a [`HashMap`]. The crate
//! has no dependencies, and is really just a helper around storing and fetching [`Any`]s from
//! a [`HashMap`]. It has no `unsafe` code and free of any `unwrap`s or similar misgivings.
//!
//! The [`Baggie`] implements a subset of methods found in [`HashMap`].
//!
//! The downside of this crate is you _must_ know the type of what you stored later on. Typically
//! this shouldn't be a problem, as you could keep some _metadata_ structure describing what types
//! belong to what keys you've stored.
//!
//! _Sometimes_ you might need a tool like this, but _most times_ you should be using an [`enum`]. :)
//!
//! ## Example
//! ```
//! use baggie::Baggie;
//!
//! let mut bag = Baggie::new();
//!
//! // Insert any value type you wish...
//! bag.insert("key1", "Value1".to_owned());
//! bag.insert("key2", vec!["value", "2"]);
//! bag.insert("key3", 3);
//!
//! // Get a reference
//! let val3 = bag.get::<i32, _>("key3");
//! assert_eq!(Some(&3), val3);
//!
//! // Get a mutable reference
//! let val2: Option<&mut Vec<&str>> = bag.get_mut("key2");
//! match val2 {
//! Some(v) => *v = vec!["new", "value", "2"],
//! None => panic!()
//! }
//! let val2: &mut Vec<&str> = bag.get_mut("key2").unwrap();
//! assert_eq!(val2, &mut vec!["new", "value", "2"]);
//!
//! ```
//! [`enum`]: https://doc.rust-lang.org/book/enums.html
//! [`HashMap`]: https://doc.rust-lang.org/std/collections/struct.HashMap.html
//! [`Any`]: https://doc.rust-lang.org/std/any/trait.Any.html
//! [`Baggie`]: struct.Baggie.html
mod baggie;
pub use self::baggie::Baggie;
| 1e274a0d1a59e0406e2650f44ab4beece44fb4de | [
"TOML",
"Rust",
"Markdown"
] | 5 | Rust | milesgranger/baggie | 96985d41c74e8a06a25ca5ea313a3b267497e955 | 101a0a68d19acf1cdcda83d562a7f4e770b882f2 |
refs/heads/master | <file_sep>#include "food.h"
food::food()
{
}
void food::act()
{
/*
* The fuck is this supposed to do?
*/
}
<file_sep>#include <list>
#include "item.h"
#include "area.h"
#include "food.h"
#include "anthill.h"
#include "ant.h"
#include "food.h"
#include "anthill.h"
#include "factory.h"
#include "environment.h"
#include "mainwindow.h"
#include <QLabel>
#include <random>
#include <iostream>
#include <typeinfo>
#include <ctime>
#include <QString>
#include <exception>
area::area()
{
// The usage of nullptr requires C++11 to compile.
north = nullptr;
south = nullptr;
west = nullptr;
east = nullptr;
itemList = new std::list<item*>;
xCoordinate = 0;
yCoordinate = 0;
pheromoneCount = 0;
}
// Getter
area* area::getNorth()
{
return this->north;
}
area* area::getSouth()
{
return this->south;
}
area* area::getWest()
{
return this->west;
}
area* area::getEast()
{
return this->east;
}
bool area::getIsWall()
{
return this->isWall;
}
int area::getXCoordinates()
{
return this->xCoordinate;
}
int area::getYCoordinates()
{
return this->yCoordinate;
}
std::list<item*>* area::getItemList()
{
return this->itemList;
}
int area::getPheromone()
{
return this->pheromoneCount;
}
// Setter
void area::setIsWall(bool wall)
{
isWall = wall;
}
void area::setCoordinates(int X, int Y)
{
this->xCoordinate = X;
this->yCoordinate = Y;
}
void area::setNorth(area *field)
{
this->north = field;
}
void area::setSouth(area *field)
{
this->south = field;
}
void area::setWest(area *field)
{
this->west = field;
}
void area::setEast(area *field)
{
this->east = field;
}
void area::setPheromone(int count)
{
this->pheromoneCount += count;
}
void area::act(int X, int Y, area *field, int place)
{
std::list <item*>::iterator iterate;
int deleteMe[field->itemList->size()], j = 0, tmpi = 0;
for (int i = 0; i < field->itemList->size(); ++i) {
deleteMe[i] = -1;
}
for (iterate = field->itemList->begin(); iterate != field->itemList->end(); ++iterate) {
if ((*iterate)->getTimeToLive() != 1 && !dynamic_cast<ant*>((*iterate))) {
deleteMe[j] = tmpi;
++j;
} else {
if (ant *tmpA = dynamic_cast<ant*>((*iterate))) {
area *tmpM;
if (tmpA->getCanMove() == true) {
try{
tmpM = tmpA->run(field);
if (tmpM == nullptr) {
throw std::runtime_error("Nullpointer");
}
tmpM->addBack((*iterate));
deleteMe[j] = tmpi;
++j;
} catch (std::exception& error) {
std::cerr << error.what() << " on Area Y: " << Y << " X: " << X << " . Skipping this turn." << std::endl;
}
}
}
else if (food *tmpF = dynamic_cast<food*>((*iterate))) {
}
else if (anthill *tmpH = dynamic_cast<anthill*>((*iterate))) {
}
else
std::cerr << "Cant no cast from itemlist on Area Y: " << Y << " X: " << X << std::endl;
}
++tmpi;
}
if (place == 1) {
field->itemList->push_back(factory::createFood());
food *_tmp;
_tmp = dynamic_cast<food*>(field->itemList->back());
static std::mt19937_64 gen(static_cast<int>(std::time(0)));
std::uniform_int_distribution<> distribution(5, 50);
_tmp->setFoodCount(-distribution(gen));
}
else if (place == 2) {
if (field->itemList->size() == 0) {
field->itemList->push_front(factory::createAnthill());
field->itemList->front()->setFoodCount(-10);
}
anthill *_tmp = dynamic_cast<anthill*>(field->itemList->front());
while (_tmp->getFoodCount() > 0) {
field->itemList->push_back(factory::createAnt());
ant *_tmp_;
_tmp_ = dynamic_cast<ant*>(field->itemList->back());
static std::mt19937_64 gen(static_cast<int>(std::time(0)));
std::uniform_int_distribution<> distribution(50, 300);
_tmp_->setTimeToLive(distribution(gen));
_tmp->setFoodCount(1);
}
}
iterate = field->itemList->begin();
j = 0;
int sizedel = (sizeof(deleteMe)/sizeof(deleteMe[0]));
for (unsigned int i = 0; i < (sizeof(deleteMe)/sizeof(deleteMe[0])); ++i) {
if (deleteMe[j] == i) {
field->itemList->erase(iterate);
++j;
--iterate;
}
if(i != sizedel - 1)
++iterate;
}
}
void area::moveMe()
{
std::list <item*>::iterator iterate;
const int listSize = this->itemList->size();
int deleteMe[listSize], i = 0, j = 0;
for (int i = 0; i < this->itemList->size(); ++i) {
deleteMe[i] = -1;
}
for (iterate = this->itemList->begin(); iterate != this->itemList->end(); ++iterate) {
if (dynamic_cast<ant*>((*iterate))) {
int ttl = 0;
if((ttl = (*iterate)->getTimeToLive()) >= 0) {
if (ttl == 0) {
deleteMe[j] = i;
++j;
} else {
(*iterate)->setCanMove(true);
(*iterate)->setTimeToLive(-1);
}
}
} else if (dynamic_cast<food*>((*iterate))) {
int foodC = 0;
if ((foodC = (*iterate)->getFoodCount()) > 0 ) {
} else {
deleteMe[j] = i;
++j;
}
}
++i;
}
iterate = this->itemList->begin();
j = 0;
int sizedel = (sizeof(deleteMe)/sizeof(deleteMe[0]));
for (unsigned int i = 0; i < (sizeof(deleteMe)/sizeof(deleteMe[0])); ++i) {
if (deleteMe[j] == i) {
this->itemList->erase(iterate);
++j;
--iterate;
}
if(i != sizedel - 1)
++iterate;
}
}
void area::addBack(item *element)
{
this->itemList->push_back(element);
}
int area::itemCount(int X, int Y, QGridLayout *layout)
{
int retAnt = 0;
std::list <item*>::iterator iterate;
int antCount = 0, foodCount = 0, hillCount = 0, tmpCount = 0;
for (iterate = this->itemList->begin(); iterate != this->itemList->end(); ++iterate) {
if (ant *tmpA = dynamic_cast<ant*>((*iterate)))
antCount++;
else if (food *tmpF = dynamic_cast<food*>((*iterate)))
foodCount += (*iterate)->getFoodCount();
else if (anthill *tmpH = dynamic_cast<anthill*>((*iterate)))
hillCount++;
else
std::cerr << "Cant no cast from itemlist on Area Y: " << Y << " X: " << X << std::endl;
}
/*
* Colors for the individual items on an area:
* Ants or empty: green
* Food: red
* Anthill: brown
*/
QLayoutItem *tmpItem = layout->itemAtPosition(Y, X);
QLabel *tmpLabel = dynamic_cast<QLabel*>(tmpItem->widget());
if (!tmpLabel)
std::cerr << "Can not cast from layout at Y: " << Y << " X: " << X << std::endl;
else {
bool checkForNumber = true;
int check = 0;
if (tmpLabel->text() != nullptr) {
check = tmpLabel->text().toInt(&checkForNumber, 10);
if (checkForNumber == false) {
check = 0;
}
}
int tmpAntCast = 0, tmpFoodCast = 0, tmpHillCast = 0;
if(typeid(*this->itemList->end()).name() == typeid(ant).name())
tmpAntCast = 1;
if(typeid(*this->itemList->begin()).name() == typeid(anthill).name())
tmpHillCast = 1;
if(typeid(*this->itemList->end()).name() == typeid(food).name())
tmpFoodCast = 1;
if (((antCount != 0) || check > 0) && tmpFoodCast == 0 && foodCount == 0) {
if (antCount == 0) {
tmpLabel->setText("");
tmpLabel->setStyleSheet("QLabel { background-color : rgb(0, 153, 0); color : rgb(255, 255, 255); }");
}
else if (antCount > 0) {
retAnt += antCount;
QString ants = QString("%1").arg(antCount);// QString::number(antCount);
tmpLabel->setText(ants);
tmpLabel->setStyleSheet("QLabel { background-color : rgb(0, 153, 0); color : rgb(255, 255, 255); }");
}
} else if ((foodCount != 0 || check > 0) && tmpAntCast == 0 && tmpHillCast == 0) {
if (foodCount == 0) {
tmpLabel->setStyleSheet("QLabel { background-color : rgb(0, 153, 0); color : rgb(255, 255, 255); }");
tmpLabel->setText("");
}
else {
QString foods = QString("%1").arg(foodCount);// QString::number(foodCount);
tmpLabel->setStyleSheet("QLabel { background-color : rgb(204, 0, 0); color : rgb(255, 255, 255); }");
tmpLabel->setText(foods);
}
}
if (hillCount != 0) {
tmpLabel->setStyleSheet("QLabel { background-color : rgb(170, 85, 0); color : rgb(255, 255, 255); }");
}
}
return retAnt;
}
<file_sep>#ifndef FACTORY_H
#define FACTORY_H
#include "ant.h"
#include "food.h"
#include "anthill.h"
class factory
{
private:
factory();
~factory();
public:
static factory *getInstance();
static ant *createAnt();
static food *createFood();
static anthill *createAnthill();
};
#endif // FACTORY_H
<file_sep>/*
* Basic ant simulation, with Qt as GUI.
* Authors: <NAME>, <NAME>
*/
#include "mainwindow.h"
#include <QApplication>
#include "area.h"
#include "environment.h"
#include "calcfields.h"
#include <QGridLayout>
#include <QDesktopWidget>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
QGridLayout *layout = new QGridLayout;
QWidget *mainWidget = new QWidget;
area *first = new area;
unsigned int height = 0, width = 0;
QDesktopWidget widget;
QRect resolution = widget.screenGeometry(widget.primaryScreen());
/*
* Values under 20 for square don't really make sense. 25 is nice, because
* we can fit 3 numbers in it quite nicely
*/
calcFields(resolution.width(), resolution.height() - 10, 25, 1, &width, &height);
layout = w.createPlayground(height, width, mainWidget);
/*
* Do not change the order of the line above and the two lines below.
* It works this way, doesn't the other way around. Don't ask.
*/
environment* playground = environment::getInstance();
playground->createEnvironment(first, width, height);
w.setCentralWidget(mainWidget);
bool running = true;
w.setFixedHeight(resolution.height());
w.setFixedWidth(resolution.width());
w.showFullScreen();
while (w.run() == true && running == true) { // Needs to close on close of the window
running = environment::actAll(height, width, first, layout, mainWidget);
QApplication::processEvents();
environment::moving(first, height, width);
}
delete first;
a.quit();
return 0;
}
<file_sep>#ifndef ANT_H
#define ANT_H
#include "item.h"
#include "area.h"
#include <list>
class ant : public item
{
private:
std::list<int> *areaList;
int lookFood(area *field);
int values[4];
public:
ant();
void act();
area *run(area *field);
void checkPheromone(area *field);
};
#endif // ANT_H
<file_sep>#include "factory.h"
#include "ant.h"
#include "anthill.h"
#include "food.h"
factory::factory()
{
}
factory::~factory()
{
}
factory* factory::getInstance()
{
static factory instance;
return &instance;
}
ant* factory::createAnt()
{
ant *tmp = new ant;
return tmp;
}
food* factory::createFood()
{
food *tmp = new food;
return tmp;
}
anthill* factory::createAnthill()
{
anthill *tmp = new anthill;
return tmp;
}
<file_sep>#ifndef CALCFIELDS_H
#define CALCFIELDS_H
/*
* calculates the maximum amount of drawable squares in both x and y direction
* x and y amount are returned by call by reference
* resX -> horizontal resolution of the window
* resY -> vertical resolution of the window
*
* square -> size in pixle of one field (since it is a square there is only one value needed)
* lineWidth -> line width in pixle for the grid in the window
*
* fieldsX -> amount of drawable fields in x direction (result)
* fieldsY -> amount of drawable fields in y direction (result)
*
* fieldsX * fieldsY = total amount of drawable fields
*/
void calcFields(int resX, int resY, int square, int lineWidth, unsigned int* fieldsX, unsigned int* fieldsY);
#endif // CALCFIELDS_H
<file_sep>#include "ant.h"
#include "area.h"
#include "anthill.h"
#include "food.h"
#include <random>
#include <list>
#include <ctime>
ant::ant()
{
areaList = new std::list<int>;
}
void ant::act()
{
/*
* 1. Has to look into the areas next to it.
* 1.1 Check for food
* 1.2 Check for anthill (list front)
* 2. If neither 1.1 and 1.2 appeal determine where to go
* 2.1 Is there a a nullptr in one of the adjacent areas
* 2.1.1 Change the likeliness of the areas
* 2.2 Determine where to go
* 3. Move
*
* Moved most of the features here to ant::run
*/
}
area* ant::run(area *field)
{
int north = 25, east = 25, south = 25, west = 25, _east = 0, _south = 0, _west = 0;
area *ret;
if (this->getPayload() == 0) { // Start Ant carries nothing
int go = this->lookFood(field); // Start looking for food in surroundin areas
if (go == 6)
ret = field->getNorth();
else if (go == 9)
ret = field->getEast();
else if (go == 12)
ret = field->getSouth();
else if (go == 3)
ret = field->getWest();
if (ret == nullptr) {
// This does nothing, but it actually fixes the problem with returning nullptr
}
else { // No food in the surrounding areas
ant::checkPheromone(field);
north = this->values[0];
east = this->values[1];
south = this->values[2];
west = this->values[3];
if (field->getNorth() == nullptr && field->getWest() == nullptr) { // Check for borders or corners
int tmp1 = north;
int tmp2 = west;
north = 0;
west = 0;
south += tmp1/2 + tmp2/2;
east += tmp1/2 + tmp2/2;
} else if (field->getNorth() == nullptr && field->getEast() == nullptr) {
int tmp1 = north;
int tmp2 = east;
north = 0;
east = 0;
south += tmp1/2 + tmp2/2;
west += tmp1/2 + tmp2/2;
} else if (field->getSouth() == nullptr && field->getWest() == nullptr) {
int tmp1 = south;
int tmp2 = west;
south = 0;
west = 0;
north += tmp1/2 + tmp2/2;;
east += tmp1/2 + tmp2/2;
} else if (field->getSouth() == nullptr && field->getEast() == nullptr) {
int tmp1 = south;
int tmp2 = east;
south = 0;
east = 0;
north += tmp1/2 + tmp2/2;
west += tmp1/2 + tmp2/2;
} else {
if (field->getNorth() == nullptr) {
int tmp = north;
north = 0;
east += tmp/3;
south += tmp/3;
west += tmp/3;
}
if (field->getEast() == nullptr) {
int tmp = east;
north += tmp/3;
east = 0;
south += tmp/3;
west += tmp/3;
}
if (field->getSouth() == nullptr) {
int tmp = south;
north += tmp/3;
east += tmp/3;
south = 0;
west += tmp/3;
}
if (field->getWest() == nullptr) {
int tmp = west;
north += tmp/3;
east += tmp/3;
south += tmp/3;
west = 0;
}
} // No borders and corners
if (this->areaList->size() == 0) {
this->areaList->push_front(0);
} else {
int tmpCo = this->areaList->back(); // Don't go back where you came from
if (tmpCo == 12) {
int tmp = south;
south = 0;
if(east > 0)
east += tmp/3;
else
tmp += tmp/3;
if(north > 0)
north += tmp/3;
else
tmp += tmp/3;
if(west > 0)
west += tmp/3;
else
tmp += tmp/3;
} else if (tmpCo == 3) {
int tmp = west;
west = 0;
if(north > 0)
north += tmp/3;
else
tmp += tmp/3;
if(south > 0)
south += tmp/3;
else
tmp += tmp/3;
if(east > 0)
east += tmp/3;
else
tmp += tmp/3;
} else if (tmpCo == 6) {
int tmp = north;
north = 0;
if(east > 0)
east += tmp/3;
else
tmp += tmp/3;
if(south > 0)
south += tmp/3;
else
tmp += tmp/3;
if(west > 0)
west += tmp/3;
else
tmp += tmp/3;
} else if (tmpCo == 9) {
int tmp = east;
east = 0;
if(west > 0)
west += tmp/3;
else
tmp += tmp/3;
if(south > 0)
south += tmp/3;
else
tmp += tmp/3;
if(north > 0)
north += tmp/3;
else
tmp += tmp/3;
}
} // Prepare random number generation
if (east > 0)
_east = north + east;
else
_south += north;
if (south > 0)
_south += _east + south;
else
_west += _east + north;
if (west > 0)
_west += _south + west;
static std::mt19937_64 gen(static_cast<int>(std::time(0)));
std::uniform_int_distribution<> distribution(1, north + east + south + west);
go = distribution(gen);
if (go <= north && north > 0) {
ret = field->getNorth();
this->areaList->push_back(12);
} else if (go <= _east && _east > north) {
ret = field->getEast();
this->areaList->push_back(3);
} else if (go <= _south && _south > _east) {
ret = field->getSouth();
this->areaList->push_back(6);
} else if (go <= _west && _west > _south) {
ret = field->getWest();
this->areaList->push_back(9);
}
}
} // End of ant carries nothing
else { // Ant finds it way back to the anthill
int goB = this->areaList->back();
if (goB == 0) { // Reached the anthill
if (anthill *tmp = dynamic_cast<anthill*>(field->getNorth()->getItemList()->front())) {
tmp->setFoodCount(-this->getPayload());
this->setPayload(0);
} else if (anthill *tmp = dynamic_cast<anthill*>(field->getEast()->getItemList()->front())) {
tmp->setFoodCount(-this->getPayload());
this->setPayload(0);
} else if (anthill *tmp = dynamic_cast<anthill*>(field->getSouth()->getItemList()->front())) {
tmp->setFoodCount(-this->getPayload());
this->setPayload(0);
} else if (anthill *tmp = dynamic_cast<anthill*>(field->getWest()->getItemList()->front())) {
tmp->setFoodCount(-this->getPayload());
this->setPayload(0);
} else if (anthill *tmp = dynamic_cast<anthill*>(field->getItemList()->front()))
tmp->setFoodCount(-this->getPayload());
this->setPayload(0);
static std::mt19937_64 gen(static_cast<int>(std::time(0)));
std::uniform_int_distribution<> distribution(1, 100);
int go = distribution(gen);
if (go <= 25) {
ret = field->getNorth();
this->areaList->push_back(12);
} else if (go <= 50) {
ret = field->getEast();
this->areaList->push_back(3);
} else if (go <= 75) {
ret = field->getSouth();
this->areaList->push_back(6);
} else if (go <= 100) {
ret = field->getWest();
this->areaList->push_back(9);
}
} else { // Has to move to get to anthill
field->setPheromone(2);
if (goB == 12)
ret = field->getSouth();
else if (goB == 3)
ret = field->getWest();
else if (goB == 6)
ret = field->getNorth();
else if (goB == 9)
ret = field->getEast();
this->areaList->pop_back();
}
} // End way back to anthill
this->setCanMove(false);
return ret;
}
int ant::lookFood(area *field)
{
int ret = this->areaList->back();
area *tmpN = field->getNorth(), *tmpE = field->getEast(), *tmpS = field->getSouth(), *tmpW = field->getWest();
if (tmpN != nullptr && tmpN->getItemList()->size() > 0) {
if (dynamic_cast<food*>(tmpN->getItemList()->back())) {
if (tmpN->getItemList()->back()->getFoodCount() > 4) {
tmpN->getItemList()->back()->setFoodCount(5);
this->setPayload(5);
} else {
int tmpLoad = tmpN->getItemList()->back()->getFoodCount();
tmpN->getItemList()->back()->setFoodCount(tmpLoad);
this->setPayload(tmpLoad);
}
}
} else if (tmpE != nullptr && tmpE->getItemList()->size() > 0) {
if (dynamic_cast<food*>(tmpE->getItemList()->back())) {
if (tmpE->getItemList()->back()->getFoodCount() > 4) {
tmpE->getItemList()->back()->setFoodCount(5);
this->setPayload(5);
} else {
int tmpLoad = tmpE->getItemList()->back()->getFoodCount();
tmpE->getItemList()->back()->setFoodCount(tmpLoad);
this->setPayload(tmpLoad);
}
}
} else if (tmpS != nullptr && tmpS->getItemList()->size() > 0) {
if (dynamic_cast<food*>(tmpS->getItemList()->back())) {
if (tmpS->getItemList()->back()->getFoodCount() > 4) {
tmpS->getItemList()->back()->setFoodCount(5);
this->setPayload(5);
} else {
int tmpLoad = tmpS->getItemList()->back()->getFoodCount();
tmpS->getItemList()->back()->setFoodCount(tmpLoad);
this->setPayload(tmpLoad);
}
}
} else if (tmpW != nullptr && tmpW->getItemList()->size() > 0) {
if (dynamic_cast<food*>(tmpW->getItemList()->back())) {
if (tmpW->getItemList()->back()->getFoodCount() > 4) {
tmpW->getItemList()->back()->setFoodCount(5);
this->setPayload(5);
} else {
int tmpLoad = tmpW->getItemList()->back()->getFoodCount();
tmpW->getItemList()->back()->setFoodCount(tmpLoad);
this->setPayload(tmpLoad);
}
}
}
if (this->getPayload() == 0)
ret = 0;
return ret;
}
void ant::checkPheromone(area *field)
{
int pheromones[4], tmppheromones[4], j = 0;
for (int i = 0; i < 4; ++i) {
tmppheromones[i] = 0;
pheromones[i] = 0;
this->values[i] = 25;
}
if(field->getNorth() != nullptr)
pheromones[0] = field->getNorth()->getPheromone() / 100;
if(field->getEast() != nullptr)
pheromones[1] = field->getEast()->getPheromone() / 100;
if(field->getSouth() != nullptr)
pheromones[2] = field->getSouth()->getPheromone() / 100;
if(field->getWest() != nullptr)
pheromones[3] = field->getWest()->getPheromone() / 100;
for (int i = 0; i < 4; ++i) {
if (pheromones[i] != 0) {
tmppheromones[i] = pheromones[i];
++j;
}
}
if (j > 0) {
for (int i = 0; i < 4; ++i) {
pheromones[i] += tmppheromones[i] / j;
for (int k = 0; k < 3; ++k) {
if (k != i) {
int tmp = i + k;
if(tmp > 3)
tmp -= 3;
pheromones[tmp] -= tmppheromones[tmp];
}
}
}
for (int i = 0; i < 4; ++i) {
if(j == 4)
j = 0;
this->values[i] += pheromones[i] / (4 - j);
}
} else {
for (int i = 0; i < 4; ++i)
this->values[i] = 25;
}
}
<file_sep>#ifndef ANTHILL_H
#define ANTHILL_H
#include "item.h"
class anthill : public item
{
private:
public:
anthill();
void act();
};
#endif // ANTHILL_H
<file_sep>#include "environment.h"
#include "area.h"
#include <random>
#include <unistd.h>
#include <ctime>
#include <QLabel>
#include <QWidget>
#include <QApplication>
#include <QPushButton>
environment::environment()
{
}
environment::~environment()
{
}
environment* environment::getInstance()
{
static environment instance;
return &instance;
}
void environment::createEnvironment(area *first, int width, int height)
{
area *tmpCurrentRow;
area *tmpPreviousRow;
tmpCurrentRow = first;
for (int i = 0; i < height; ++i) { // Determines the Y Coordinate.
if (i > 0) {
if (i == 1)
tmpPreviousRow = first;
else
tmpPreviousRow = getArea(first, 0, i - 1);
}
for (int j = 0; j < width; ++j) { // Determines the X Coordinate
area *field = new area;
field->setCoordinates(j, i);
if (j == 0 && i == 0)
delete field; // No reason to keep an unused field in the RAM since it's a duplicate to first
else if (j == 0) {
tmpPreviousRow->setSouth(field);
field->setNorth(tmpPreviousRow);
} else if (i == (height - 1) && j == 0)
field->setNorth(tmpPreviousRow);
else {
field->setWest(tmpCurrentRow);
tmpCurrentRow->setEast(field);
if (i > 0) {
tmpPreviousRow->setSouth(field);
field->setNorth(tmpPreviousRow);
}
}
if (j == 0)
tmpCurrentRow = getArea(first, 0, i);
else
tmpCurrentRow = field;
if (i > 0)
tmpPreviousRow = tmpPreviousRow->getEast();
} // End of for loop j
} // End of for loop i
}
area* environment::getArea(area *first, int xCoordinate, int yCoordinate)
{
area *tmpNode;
tmpNode = first;
for (int i = 0; i < yCoordinate; ++i)
tmpNode = tmpNode->getSouth();
for (int i = 0; i < xCoordinate; ++i){
tmpNode = tmpNode->getEast();
}
return tmpNode;
}
bool environment::actAll(int height, int width, area *first, QGridLayout *layout, QWidget *mainWidget)
{
bool spawned = false; // Only one food spawn per turn
int antCount = 0;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
area *tmpArea = getArea(first, j, i);
static std::mt19937_64 gen(static_cast<int>(std::time(0)));
std::uniform_int_distribution<> distribution(0, (15*height*width));
int place = 0;
if (i == (height / 2) && j == (width / 2))
place = 2;
else if (distribution(gen) < 1 && spawned == false) {
place = 1;
spawned = true;
}
tmpArea->act(j, i, tmpArea, place);
}
}
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
area *tmpArea = getArea(first, j, i);
antCount += tmpArea->itemCount(j, i, layout);
}
}
if (antCount == 0) {
QWidget *endScreen = new QWidget;
QGridLayout *endLayout = new QGridLayout;
QLabel *endText = new QLabel;
QPushButton *endButton = new QPushButton;
endText->setText("All ants are dead.");
endLayout->addWidget(endText, 0, 0);
endButton->setText("Quit");
endLayout->addWidget(endButton, 1, 0);
endScreen->setLayout(endLayout);
mainWidget->setFixedSize(mainWidget->width()/10, mainWidget->height()/10);
mainWidget->layout()->addWidget(endScreen);
return false;
} else if (antCount > 9000) {
// Spawn aardvark here
} else
return true;
}
void environment::moving(area *first, int height, int width)
{
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
area *tmp = getArea(first, j, i);
tmp->moveMe();
}
}
}
<file_sep>#ifndef FOOD_H
#define FOOD_H
#include "item.h"
class food : public item
{
private:
public:
food();
void act();
};
#endif // FOOD_H
<file_sep>#ifndef AREA_H
#define AREA_H
/*
* Manages the individual fields of the environment class
*/
#include <list>
#include "item.h"
#include "mainwindow.h"
class area
{
private:
// Pointer for movement directions
area *north;
area *south;
area *west;
area *east;
area *northEast;
area *northWest;
area *southEast;
area *southWest;
int xCoordinate;
int yCoordinate;
bool isWall; // Check if the ant can enter the next area
int surface; // Surface defines movement Speed and Vision of the ant
std::list<item*> *itemList;
int pheromoneCount; // Probability for next direction
public:
area();
area *getNorth();
area *getSouth();
area *getWest();
area *getEast();
void setNorth(area *field);
void setSouth(area *field);
void setWest(area *field);
void setEast(area *field);
void setIsWall(bool wall);
bool getIsWall();
void setCoordinates(int X, int Y);
int getXCoordinates();
int getYCoordinates();
static void act(int X, int Y, area *field, int place);
void moveMe();
void addBack(item *element);
int itemCount(int X, int Y, QGridLayout *layout);
std::list<item*>* getItemList();
int getPheromone();
void setPheromone(int count);
};
#endif // AREA_H
<file_sep>#ifndef ITEM_H
#define ITEM_H
/*
* Base class from which ant, anthill and food inherit
*/
class item
{
private:
int foodCount; // Amount of available Food in this area
bool canMove; // Determines if the ant already moved this turn
int sex; // Determines the gender of the ant
int timeToLive; /*
* Determines the amount of turns the ant can move, if
* it reaches zero, the Ant is dead
*/
bool hadSex; /*
* Relevant for drones, if this is true they die by the
* next turn
*/
int payload; // Relevant for workers, sets the amount of food they carry
public:
item();
virtual void act() = 0; // pure virtual
int getFoodCount();
bool getCanMove();
int getSex();
double getTimeToLive();
bool getHadSex();
int getPayload();
void setCanMove(bool move);
void setSex(int gender);
void setTimeToLive(int time);
void setHadSex(bool hump);
void setPayload(int load);
void setFoodCount(int eaten);
};
#endif // ITEM_H
<file_sep>#include "calcfields.h"
void calcFields(int resX, int resY, int square, int lineWidth, unsigned int* fieldsX, unsigned int* fieldsY)
{
unsigned int squareCountWidth;
unsigned int squareCountHeight;
//Max amount of possible fields width
squareCountWidth = ( resX / square );
do
{
squareCountWidth--;
} while ( ( (squareCountWidth * square) + ( (squareCountWidth + 1) * lineWidth) ) > resX ); // (squareCountWidth - 1) number of the divides
*fieldsX = squareCountWidth;
//Max amount of possible fields height
squareCountHeight = ( resY / square );
do
{
squareCountHeight--;
} while ( ( (squareCountHeight * square) + ( (squareCountHeight + 1) * lineWidth) ) > resY );
*fieldsY = squareCountHeight;
}
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGridLayout>
#include <QAction>
#include <QActionGroup>
#include <QMenu>
#include <QContextMenuEvent>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QGridLayout *createPlayground(int height, int width, QWidget *mainWidget);
void showPlayground(QWidget *mainWidget);
bool run();
public slots:
void noRun();
protected:
// void contextMenuEvent(QContextMenuEvent *event);
private:
bool running;
Ui::MainWindow *ui;
void createActions();
void createMenus();
QMenu *appMenu;
QActionGroup *alignmentGroup;
QAction *settingsAct;
QAction *quitAct;
private slots:
void settings();
void exitProgram();
};
#endif // MAINWINDOW_H
<file_sep>#include "item.h"
item::item()
{
foodCount = 0;
canMove = true;
sex = 0;
timeToLive = 1;
hadSex = false;
payload = 0;
}
int item::getFoodCount()
{
return this->foodCount;
}
bool item::getCanMove()
{
return this->canMove;
}
int item::getSex()
{
return this->sex;
}
double item::getTimeToLive()
{
return this->timeToLive;
}
bool item::getHadSex()
{
return this->hadSex;
}
int item::getPayload()
{
return this->payload;
}
void item::setCanMove(bool move)
{
this->canMove = move;
}
void item::setSex(int gender)
{
this->sex = gender;
}
void item::setHadSex(bool hump)
{
this->hadSex = hump;
}
void item::setPayload(int load)
{
this->payload = load;
}
void item::setFoodCount(int eaten)
{
this->foodCount -= eaten;
}
void item::setTimeToLive(int time)
{
this->timeToLive += time;
}
<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDesktopWidget>
#include <QLabel>
#include <QGridLayout>
#include <QtGui>
#include <QMenu>
#include <QMenuBar>
#include <QApplication>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
createActions();
createMenus();
running = true;
}
MainWindow::~MainWindow()
{
delete ui;
running = false;
}
void MainWindow::createMenus()
{
menuBar()->setFixedHeight(10);
appMenu = menuBar()->addMenu(tr("&File"));
appMenu->addAction(settingsAct);
appMenu->addAction(quitAct);
}
void MainWindow::createActions()
{
settingsAct = new QAction(tr("&Settings"), this);
quitAct = new QAction(tr("&Quit"), this);
connect(quitAct, SIGNAL(triggered()), this, SLOT(noRun()));
}
void MainWindow::settings()
{
}
void MainWindow::exitProgram()
{
}
QGridLayout* MainWindow::createPlayground(int height, int width, QWidget *mainWidget)
{
QGridLayout *layout = new QGridLayout;
layout->setSpacing(1);
layout->setMargin(0);
layout->setAlignment(Qt::AlignHCenter);
layout->setAlignment(Qt::AlignCenter);
mainWidget->setStyleSheet("background-color : rgb(0, 153, 0);");
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
QLabel *label = new QLabel("");
label->setStyleSheet("QLabel { background-color : rgb(0, 153, 0); color : rgb(255, 255, 255); }");
label->setFixedHeight(25);
label->setFixedWidth(25);
layout->addWidget(label, i, j);
}
}
mainWidget->setLayout(layout);
QDesktopWidget widget;
QRect resolution = widget.screenGeometry(widget.primaryScreen());
mainWidget->setFixedHeight(resolution.height());
mainWidget->setFixedWidth(resolution.width());
return layout;
}
bool MainWindow::run()
{
return this->running;
}
void MainWindow::noRun()
{
this->running = false;
this->close();
}
<file_sep>#include "anthill.h"
anthill::anthill()
{
}
void anthill::act()
{
/*
* Maybe do the ant creation and so on in here
*/
}
<file_sep>#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
/*
* Defines the whole Playground.
* Can also be used to get a specific field out of the playground.
*/
#include "area.h"
#include <QGridLayout>
#include <QWidget>
class environment
{
private:
environment();
~environment();
public:
void createEnvironment(area *first, int width, int height);
static area *getArea(area *first, int xCoordinate, int yCoordinate);
static environment* getInstance();
static bool actAll(int height, int width, area *first, QGridLayout *layout, QWidget *w);
static void moving(area *first, int height, int width);
};
#endif // ENVIRONMENT_H
<file_sep>Ant-Simulation-Qt
=================
<NAME>,
<NAME>
Ameisensimulation Konzept
Der Boden auf dem sich die Ameisen bewegen wird durch ein 2D Array bestehend aus Feldern der
Klasse „area“ realisiert. Klasse Spielfeld enthält diverse Einträge wie Anzahl der Ameisen auf dem
Feld, Futtermenge, Untergrundinformation und kann optional durch weitere Parameter, für ein
komplexeres Simulationsverhalten ergänzt werden.

Die folgende Grafik schlüsselt die weiteren Details zu den Ameisen genauer auf:

Das Bewegungsmuster der Ameisen soll zunächst zufällig von statten gehen. Sprich die
Wahrscheinlichkeit, dass die Ameise in das Feld links, rechts oder vor ihr wandert ist genau gleich
groß. Je mehr Ameisen den gleichen Pfad beschreiten desto höher ist auch die Wahrscheinlichkeit,
dass nachfolgende ihnen es gleich tun. Das Gleichgewicht wird als zur höchsten Ameisenfluktuation
gelenkt was in den meisten Fällen die Futterquelle sein sollte. Hat eine Ameise ihre Nutzlast
aufgenommen wandert sie einfachheitshalber auf direktem Weg zum Bau zurück. (Kann später noch
abgeändert werden) Ziel der Simulation soll das Überleben der Kolonie sein was natürlich von den
äußeren Einflüssen abhängig ist. Aufgrund der Komplexität wird dies zuerst nur von der Futtermenge
und Lebenserwartung abhängig sein.
| f2f3c244953c3621aad5d1b0a6e29c9f97c3199c | [
"Markdown",
"C",
"C++"
] | 20 | C++ | Trollmann/Ant-Simulation-Qt | fe77873bde6e10850986167164d8601883e15113 | 8916aecec2dc09a7c381f627071aa9e9fe012995 |
refs/heads/master | <repo_name>srisreedhar/Mizuho-Python-Programming<file_sep>/Session-6-Split-DataStructures/stringmethods.py
# collect info from the user and display
name= input("enter your name " ).upper()
office =input("enter your office ").title()
edu=input("enter your qualification ")
name=name.upper()
office=office.title()
edu=edu.lower()
print("""
Name is %s ,
you work in %s ,
you studied %s """%(name,office,edu))
<file_sep>/Session-18-NestedConditionals/nestedif.py
# ask user to enter a number between 1-5 and print the number in words
number=input("Enter a number between 1-5 :")
number=int(number)
# if number == 1:
# print("the number is one")
# else:
# print("its not one")
# Nested conditions
if number==1:
print("number is one")
elif number==2:
print("number is two")
elif number==3:
print("number is Three")
elif number==4:
print("number is Four")
elif number==5:
print("number is Five")
else:
print("The number is out of range")
<file_sep>/Session-4-input-print/typecasting.py
# Editor
# Simple Average
# Inputs
maths=input("Enter your Math marks ")
sci=input("Enter your science marks ")
soc=input("Enter your Social marks ")
# Computation / Calculation
maths=int(maths)
sci=int(sci)
soc=int(soc)
total= maths+sci+soc
avg=total/3
# Displaying results
print("the total is",total)
print("the average is",avg)
<file_sep>/Session-11-Counters-Dicts/Counters.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # counters - For Loop
>>>
>>> fruits = ['melon','papaya','grapes','apple','cherry','banana']
>>> len(fruits)
6
>>> counter=0
>>> counter
0
>>> for each in "abcdef":
print(each)
a
b
c
d
e
f
>>> for each in "abcdef":
print(1)
1
1
1
1
1
1
>>> counter
0
>>> counter=counter+1
>>> counter
1
>>> counter=counter+1
>>> counter
2
>>> counter=counter+1
>>> counter
3
>>> counter=0
>>> for each in "abcdef":
counter=counter+1
print(each,counter)
a 1
b 2
c 3
d 4
e 5
f 6
>>> counter
6
>>> len(fruits)
6
>>> numOfFruits=0
>>> for fruit in fruits:
numOfFruits=numOfFruits+1
>>> numOfFruits
6
>>> # a movie hall sells 100 tickets
>>> # below are the audience who attended the movie
>>> # ['a','b','c','d','e','f','g','h','i']
>>> # calculate how many tickets are left
>>>
>>>
>>>
>>>
>>>
>>> counter=0
>>> counter=counter+1
>>> counter
1
>>> counter+=1
>>> counter
2
>>> # find the product of first 10 natural numbers
>>> # n=[1,2,3,4,5,6,7,8,9,10]
>>>
>>> <file_sep>/Session-23-Flask/web/app.py
from flask import Flask
app = Flask(__name__)
# View Function
# AboutUS page
@app.route('/aboutus')
def aboutus():
return 'This is About US'
# home Page
@app.route('/')
def homePage():
return "This is a Home Page"
# courses offered
@app.route('/courses')
def coursePage():
return " This is course Page"
# contact us
@app.route('/contact')
def contactUS():
return " Contact US Page"
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/Session-5-Strings/input-formating.py
# application form
# Inputs
name=input("Enter your name: ")
age = input("Enter your year of birth: ")
edu = input("Enter your qualification: ")
# Process / compute
# display
print("""
Hi,
below are thedetails you've entered :
your Name is : %s ,
your year of Birth is : %s ,
your Qualification is : %s"""%(name,age,edu))
<file_sep>/Session-13-JupyterNotebook/ReadMe.md
## Jupyter NoteBook
Log on to [Jupyter WebSite](https://jupyter.org/install) for detailed instructions.
Simply, run below command to install the notebook
pip install notebook
This should install Jupyter notebook and all its dependencies on your system.
Please do refer to the installation video.
<file_sep>/Session-19-WordCount/Readme.md
"this Morning and yesterdays MORNING are not same. it was raining yesterday and now it is not raining same as yesterday".lower()
this - 1
MORNING - 1
Morning -1
yesterdays -1
raining - 2
yesterday -1
{
this : 1
morning : 2
yesterdays :1
raining : 2
yesterday :2
same:1+1
}
if there is no word - add word to dictionary and set its count as 1
if theres the word exists, then increment the value by 1<file_sep>/Session-5-Strings/IDLE-workout.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> age=input("-->")
-->10
>>> age
'10'
>>> new_age=int(age)
>>> new_age
10
>>> age=int(age)
>>> age
10
>>> type(str(1111))
<class 'str'>
>>>
>>> age=int(input("Enter a number -->"))
Enter a number -->60
>>> age
60
>>> age=int(input("Enter a number -->"))
Enter a number -->10.500
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
age=int(input("Enter a number -->"))
ValueError: invalid literal for int() with base 10: '10.500'
>>> age=int(input("Enter a number -->"))
Enter a number -->sreedhar
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
age=int(input("Enter a number -->"))
ValueError: invalid literal for int() with base 10: 'sreedhar'
>>>
>>> age=input("-->")
-->4444
>>> age
'4444'
>>>
>>>
>>> # prints
>>>
>>> print("what a beautiful morning this is")
what a beautiful morning this is
>>>
>>> print("This is line 1
SyntaxError: EOL while scanning string literal
>>> print("""This is line 1
this is line 2
this is line 3
this is ine4""")
This is line 1
this is line 2
this is line 3
this is ine4
>>>
>>> print("it is raining here")
it is raining here
>>>
>>> print('its raining here')
its raining here
>>>
>>> print('it's raining here')
SyntaxError: invalid syntax
>>> print("it's raining here")
it's raining here
>>>
>>>
>>> print('''
Hi,
Good Morning
Could you ask''',"sreedhar",''' to forward me
the ''',5,"th","video")
Hi,
Good Morning
Could you ask sreedhar to forward me
the 5 th video
>>>
>>>
>>>
>>> # string formatters
>>> # placeholders of values in print
>>>
>>> # %s -> strings
>>> # %d -> Integers
>>> # %f -> floats
>>> # %r -> raw strings
>>>
>>>
>>> # " %placeHOlder1 ....... %placeholder2... %placeholder3"%(value1,value2,value3)
>>>
>>> " His name is %s he is %s years old "%("Python",15)
' His name is Python he is 15 years old '
>>>
>>>
>>> " His name is %s he is %s years old "%(15,"Python")
' His name is 15 he is Python years old '
>>>
==== RESTART: C:/Users/User/Desktop/Mizuho/Programs/Session-5-/input-formating.py ===
Enter your name: sreedhar
Enter your year of birth: 2010
Enter your qualification: mba
Hi,
below are thedetails you've entered :
your Name is : sreedhar ,
your year of Birth is : 2010 ,
your Qualification is : mba
>>> <file_sep>/Session-17-Conditionals/simpleif.py
# simple If-else Condition
# collect 2 numbers from the user & print the greatest of these 2
number1 = input("enter any number1 :")
number2 = input("enter any number2 :")
number1=int(number1)
number2=int(number2)
# print the greatest of these 2
if number1>number2:
print(number1,"is greater")
else:
print(number2,"is greater")<file_sep>/Session-23-Flask/web/ReadMe.md
we need to create a website ?
- url
- webpage
- html,css,js,...
website.com/home
webpage-home
website.com/contactus
webpage-contactus / form
website.com/services
webpage- list of services
every webpage will have 2 parts
-page
-url of the page / address of that page
flask pocoo
Webpage - view
URL - route
DB tables - Models
create a simple website with 4 pages
- about us
- services ofered
- home Page
- contact us
@app.route('/')
- Route / URL of a webpage
- decorator
def hello_world():
return 'Hello, World!'
- View Functions / function that handles a view/webpage
<file_sep>/Session-24-FinalFlask/webapp/ReadMe.md
#### The indentation error has been fixed.
## Assigning multiple URLS to a single webpage
```
@app.route('/index')
@app.route('/home')
@app.route('/')
def aboutus():
return '<h1>This is About US</h1>'
```
# Working with Templates
Folder Structure :
```
Base Project Folder
- FlaskApp.py
- templates
- html pages
- home.html
- contactus.html
```
Create a HTML page/template
place the file in templates folder
import render_template into the app from flask
in the view function, use render_template to return the html page
from the tempaltes folder.
# # Jinja templating system
`{ % code/template tags %}`
`{{ variables }}`
<file_sep>/Session-29-DB/ReadMe.md
## Dealing DataBases with Python
###### A sample database with 11 tables, to practice.
[chinook SQLite sample DataBase to Practice](https://www.sqlitetutorial.net/sqlite-sample-database/)
### Sqlite DB links
[Sqlite DB WebSite](https://www.sqlite.org/index.html)
[Sqlite DB GUI Tool for handling DB](https://sqlitebrowser.org/)
` Use this GUI tool to load the Chinook DataBase`
### SQL syntaxes we used in the class
[SQL Create DB](https://www.w3schools.com/sql/sql_create_db.asp)
``` sql
CREATE DATABASE databasename;
```
[SQL Create Table](https://www.w3schools.com/sql/sql_create_table.asp)
``` sql
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
```
[SQL Insert Values into Table](https://www.w3schools.com/sql/sql_insert.asp)
```sql
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
```
[SQL Select from Table](https://www.sqlite.org/index.html)
```sql
SELECT column1, column2, ...
FROM table_name;
```
### Other Connectors
[Postgres Connector](https://www.postgresqltutorial.com/postgresql-python/connect/)
[MySQL Connector](https://pymysql.readthedocs.io/en/latest/user/examples.html)
[Oracle DataBases Connector](https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html#quick-start-cx-oracle-installation)
<file_sep>/Session-12-Dictionary/Dicts-1.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> languages={
"usa":"English",
"China":"Chineese",
"Japan":"Japaneese",
}
>>> languages
{'usa': 'English', 'China': 'Chineese', 'Japan': 'Japaneese'}
>>> # Adding values to a dictionary
>>> # india - Hindi
>>> #dictName['NewKey']=NewValue
>>>
>>> languages['india']='hindi'
>>> languages
{'usa': 'English', 'China': 'Chineese', 'Japan': 'Japaneese', 'india': 'hindi'}
>>>
>>> language['china']='chineese'
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
language['china']='chineese'
NameError: name 'language' is not defined
>>> languages['china']='chineese'
>>> languages
{'usa': 'English', 'China': 'Chineese', 'Japan': 'Japaneese', 'india': 'hindi', 'china': 'chineese'}
>>>
>>>
>>>
>>> marks={
"student1"=[20,30,50],
SyntaxError: invalid syntax
>>> marks={
"student1":[20,30,50],
"student2":[50,10,20],
"student3":[90,10,20]
}
>>>
>>> marks
{'student1': [20, 30, 50], 'student2': [50, 10, 20], 'student3': [90, 10, 20]}
>>>
>>> marks['student4']=[1,1,1]
>>> marks
{'student1': [20, 30, 50], 'student2': [50, 10, 20], 'student3': [90, 10, 20], 'student4': [1, 1, 1]}
>>>
>>>
>>>
>>> marks['student1']
[20, 30, 50]
>>> type(marks['student1'])
<class 'list'>
>>>
>>>
>>> type(languages['usa'])
<class 'str'>
>>>
>>>
>>> marks['student1'].append(111)
>>> marks
{'student1': [20, 30, 50, 111], 'student2': [50, 10, 20], 'student3': [90, 10, 20], 'student4': [1, 1, 1]}
>>> marks['student2'].append(111)
>>> marks['student3'].append(111)
>>> marks['student4'].append(111)
>>> marks['student5'].append(111)
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
marks['student5'].append(111)
KeyError: 'student5'
>>>
>>>
>>> marks.get('student1')
[20, 30, 50, 111]
>>> marks['student1']
[20, 30, 50, 111]
>>> marks['student5']
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
marks['student5']
KeyError: 'student5'
>>> marks.get('student5')
>>> marks.get('student5',"Check the key Name, it doesnt exist")
'Check the key Name, it doesnt exist'
>>> marks.get('student2',"Check the key Name, it doesnt exist")
[50, 10, 20, 111]
>>>
>>> marks.keys()
dict_keys(['student1', 'student2', 'student3', 'student4'])
>>>
>>> marks.values()
dict_values([[20, 30, 50, 111], [50, 10, 20, 111], [90, 10, 20, 111], [1, 1, 1, 111]])
>>> type(marks.keys())
<class 'dict_keys'>
>>>
>>>
>>>
>>> list,list()
(<class 'list'>, [])
>>>
>>> list(marks.keys())
['student1', 'student2', 'student3', 'student4']
>>> list(marks.keys())[0]
'student1'
>>> marks[list(marks.keys())[0]]
[20, 30, 50, 111]
>>> <file_sep>/Session-7-List-ListMethods/listMethods-2.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
>>> avengers=['ironman','spidey','spuerman','Mr.bean','AquaMan']
>>> avengers
['ironman', 'spidey', 'spuerman', 'Mr.bean', 'AquaMan']
>>> avengers.append("Sreedhar")
>>>
>>> avengers
['ironman', 'spidey', 'spuerman', 'Mr.bean', 'AquaMan', 'Sreedhar']
>>>
>>> avengers.remove('spuerman')
>>> avengers
['ironman', 'spidey', 'Mr.bean', 'AquaMan', 'Sreedhar']
>>>
>>> avengers.pop()
'Sreedhar'
>>> avengers
['ironman', 'spidey', 'Mr.bean', 'AquaMan']
>>> s=avengers.remove('spuerman')
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
s=avengers.remove('spuerman')
ValueError: list.remove(x): x not in list
>>> s=avengers.pop()
>>> s
'AquaMan'
>>> avengers
['ironman', 'spidey', 'Mr.bean']
>>>
>>> s=[]
>>> # s.append("Mr.bean")
>>> avengers[2]
'Mr.bean'
>>> # s.append(avengers[2])
>>> # s.append(avengers.pop())
>>>
>>> avengers=['ironman','spidey','superman','Mr.bean','AquaMan']
>>>
>>> avengers[3]
'Mr.bean'
>>>
>>> avengers.pop(3)
'Mr.bean'
>>> avengers.pop(1)
'spidey'
>>> avengers
['ironman', 'superman', 'AquaMan']
>>> s=[1,2,3,[4,5,[6,7,[8,[9,[10],11],12],13],14],15]
>>>
>>> # use Indexing to extract 3,5,7,9,10,11,14,15
>>> len(s)
5
>>> s[0]
1
>>> s[1]
2
>>> s[2]
3
>>> s[3]
[4, 5, [6, 7, [8, [9, [10], 11], 12], 13], 14]
>>> <file_sep>/Session-4-input-print/first.py
# Editor
# Simple Average
# Inputs
maths=input()
sci=input()
soc=input()
# Computation / Calculation
total= maths+sci+soc
# avg=total/3
# Displaying results
print("the total is",total)
#print("the average is",avg)
<file_sep>/Session-25-Project/ReadMe.md
Putting all together
- we need to generate a table that consists, min,max and description of
10days temparatures
- create the placeholder for table in frontend
- pass the table from the flask.app to frontend .
// Passing variables/arguments into urls
a URL takes an argument - url parameter
```
route/<parameter>
def viewFunction(parameter)
use parameter
fulldetails/<placename>
def viewfunction(placename) :
use placeName
# default-arguments
def defaultArgs(principle,tenure,rate=8):
```
generate list of max & a list of min values
```
def sampleView():
return render_template("templateName.html",mxl=max_list,mnl=min_list)
```
data: {{List_of_max_values}}
Chartjs Link
`https://www.chartjs.org/samples/latest/charts/bar/horizontal.html`
<file_sep>/Session-26-Comprehensions/ReadMe.md
### Use Data Structure Functions to create datastuctures
```
list - list()
tuple - tuple()
dict - dict()
set - set()
```
--------
#### Assignment
##### Converting lists into a dictionary
```
list1 = ["eisntein","tesla","darwin","sreedhar"]
list2=[1900,1859,1990,2000]
convert the 2 lists into a dictionary
sample- {'eintein':1900, ... }
```
--------
fruits = ['melon','papaya','grapes','apple','cherry','banana']
convert all the values into upper case and add them to a seprate list
X
```
upper=list()
for eachfruit in fruits:
upper.append(eachfruit.upper())
6 upper operations
6 append operations
x operations
```
6+6+x+... operations
# Comprehensions
writing loops inside of a datastructure
<file_sep>/Session-10-Practice/Data.md
# Please use below link to access data that we discusses in the class today
https://raw.githubusercontent.com/genomicsclass/dagdata/master/inst/extdata/msleep_ggplot2.csv
<file_sep>/Session-6-Split-DataStructures/split-string-methods.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> name="<NAME>"
>>> name
'<NAME>'
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'name']
>>>
>>> dir(name)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
>>>
>>> name.title()
'<NAME>'
>>>
>>> dir(111)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> # dunder methods
>>>
>>>
>>> name
'<NAME>'
>>> name2=" <NAME> "
>>> name2
' Srinivasa ramanujan '
>>>
>>> name.split()
['Nikola', 'tesla']
>>>
>>> name2.lstrip()
'Srinivasa ramanujan '
>>> name2.rstrip()
' Srinivasa ramanujan'
>>> name2.strip()
'Srinivasa ramanujan'
>>>
>>> row="2015-02-18,29136.07,29411.32,29126.91,29320.26,11000,29320.26"
>>>
>>> row
'2015-02-18,29136.07,29411.32,29126.91,29320.26,11000,29320.26'
>>>
>>> # .split(delimitter/seperator)
>>> # by default - space as delimitter
>>>
>>> row.split(",")
['2015-02-18', '29136.07', '29411.32', '29126.91', '29320.26', '11000', '29320.26']
>>>
>>> row.split(",")[0]
'2015-02-18'
>>>
>>> name
'<NAME>'
>>>
>>> name.split()
['Nikola', 'tesla']
>>> name.split()[0]
'Nikola'
>>> name.split()[1]
'tesla'
>>> name.split()[1]
'tesla'
>>>
>>> type(str(78.005))
<class 'str'>
>>>
>>> name.split()[1].upper()
'TESLA'
>>>
>>>
KeyboardInterrupt
>>> """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."""
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
>>>
>>>
>>> """Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."""
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
>>>
>>>
>>>
>>>
>>> para="""Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s
with the release of Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software like Aldus PageMaker including
versions of Lorem Ipsum."""
>>>
>>> para
"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem\n Ipsum has been the industry's standard dummy text ever since the 1500s, when an\n unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic\n typesetting, remaining essentially unchanged. It was popularised in the 1960s \n with the release of Letraset sheets containing Lorem Ipsum passages, and more \n recently with desktop publishing software like Aldus PageMaker including \n versions of Lorem Ipsum."
>>>
>>>
>>> para.split("\n")
['Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem', " Ipsum has been the industry's standard dummy text ever since the 1500s, when an", ' unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic', ' typesetting, remaining essentially unchanged. It was popularised in the 1960s ', ' with the release of Letraset sheets containing Lorem Ipsum passages, and more ', ' recently with desktop publishing software like Aldus PageMaker including ', ' versions of Lorem Ipsum.']
>>> para.split("\n")[1]
" Ipsum has been the industry's standard dummy text ever since the 1500s, when an"
>>>
>>> para.split("\n")[1].split()
['Ipsum', 'has', 'been', 'the', "industry's", 'standard', 'dummy', 'text', 'ever', 'since', 'the', '1500s,', 'when', 'an']
>>>
>>> para.split("\n")[1].split(11)
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
para.split("\n")[1].split(11)
TypeError: must be str or None, not int
>>> para.split("\n")[1].split()
['Ipsum', 'has', 'been', 'the', "industry's", 'standard', 'dummy', 'text', 'ever', 'since', 'the', '1500s,', 'when', 'an']
>>> para.split("\n")[1].split()[11]
'1500s,'
>>>
>>>
>>>
>>>
>>>
>>> 1,2,3,4,5,6,7
(1, 2, 3, 4, 5, 6, 7)
>>>
>>>
>>> <file_sep>/Sesson-22-FlaskIntro-args/args.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> sum([1,2,3,4,5,6,7,8,9,10])
55
>>>
>>> def nothing(*args):
return args
>>> nothing()
()
>>> nothing(1,2)
(1, 2)
>>> nothing(1,2,3,4,5,6,7,8,9,10)
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>>
>>> def plus(*numbers):
total=0
for number in numbers:
total=total+number
return total
>>> plus
<function plus at 0x000000098E83E948>
>>> plus(1)
1
>>> plus(1,2)
3
>>> plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
55
>>> # pass multiple strings and join them together
>>>
>>> # and return a sentence
>>>
>>>
>>>
>>> def simint(p,t,r):
'''
p -> principle
t -> time
r -> rate
formula -> (ptr)/100'''
return (p*t*r)/100
>>> def simint(p,t,r):
'''
p -> principle
t -> time
r -> rate
formula -> (ptr)/100
'''
return (p*t*r)/100
>>> def simint(p,t,r):
"""
p -> principle
t -> time
r -> rate
formula -> (ptr)/100
"""
return (p*t*r)/100
>>>
>>> <file_sep>/Session-23-Flask/web/app2.py
from flask import Flask
app = Flask(__name__)
# View Function
# AboutUS page
@app.route('/aboutus')
def aboutus():
return '<h1>This is About US</h1>'
# home Page
@app.route('/')
def homePage():
return """ <!DOCTYPE html>
<html>
<style>
body {
background-image: url('https://images-na.ssl-images-amazon.com/images/I/513MX-WVPGL._SL1000_.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
</style>
<body>
<h2>Welcome </h2>
<p>i do not want any text here</p>
</body>
</html>
"""
# courses offered
@app.route('/courses')
def coursePage():
return " <h1>This is course Page</h1>"
# contact us
@app.route('/contact')
def contactUS():
return " <h1>Contact US Page</h1>"
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/Session-9-Loops/loops.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> fruits = ['melon','papaya','grapes','apple','cherry','banana']
>>> fruits[0]
'melon'
>>> fruits[0].capitalize()
'Melon'
>>> fruits[1].capitalize()
'Papaya'
>>> fruits[2].capitalize()
'Grapes'
>>>
>>> # convert all the values in fruits nito upper case and add them to a seperate list
>>> fruits_upper=[]
>>> fruits[0].capitalize()
'Melon'
>>> fruits_upper.append(fruits[0].capitalize())
>>> fruits_upper
['Melon']
>>> fruits_upper.append(fruits[1].capitalize())
>>> fruits_upper.append(fruits[2].capitalize())
>>> fruits_upper
['Melon', 'Papaya', 'Grapes']
>>>
>>> # for - loop , looping every value in a collection and apply code on it
>>>
>>> fruits
['melon', 'papaya', 'grapes', 'apple', 'cherry', 'banana']
>>> for fruit in fruits:
print(fruit.upper())
MELON
PAPAYA
GRAPES
APPLE
CHERRY
BANANA
>>> # always apply/write code onthe temp variable
>>> # make sure the tempVariable is unique
>>>
>>>
>>> fruit
'banana'
>>>
>>> fruit=fruits[0]
>>> fruit.upper()
'MELON'
>>> fruit=fruits[1]
>>> fruit.upper()
'PAPAYA'
>>> fruit=fruits[2]
>>> fruit.upper()
'GRAPES'
>>>
>>>
>>> numbers=[9,1,8,2,7,4,7,5,2,0,1]
>>> numbers
[9, 1, 8, 2, 7, 4, 7, 5, 2, 0, 1]
>>> # add 100 to every value in the list
>>>
>>> for num in numbers:
print(num+100)
109
101
108
102
107
104
107
105
102
100
101
>>> # convert every number in numbers to string and add "$" to it
>>> # then append all converted values to a new list
>>>
>>> newlist=[]
>>> for num in numbers:
t=str(num)
c="$"+t
newlist.append(c)
>>> newlist
['$9', '$1', '$8', '$2', '$7', '$4', '$7', '$5', '$2', '$0', '$1']
>>>
>>> num
1
>>> t
'1'
>>> c
'$1'
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'c', 'fruit', 'fruits', 'fruits_upper', 'newlist', 'num', 'numbers', 't']
>>> newlist=[]
>>> newlist
[]
>>>
>>>
>>> for num in numbers:
t="$"+str(num)
newlist.append(t)
>>> newlist
['$9', '$1', '$8', '$2', '$7', '$4', '$7', '$5', '$2', '$0', '$1']
>>>
>>>
>>> newlist=[]
>>> newlist
[]
>>> for num in numbers:
newlist.append("$"+str(num))
>>> newlist
['$9', '$1', '$8', '$2', '$7', '$4', '$7', '$5', '$2', '$0', '$1']
>>> for num in numbers:
t=str(num)
c="$"+t
newlist.append(c)
SyntaxError: invalid syntax
>>>
>>> <file_sep>/Session-24-FinalFlask/webapp/weatherapp.py
from flask import Flask, render_template
import requests
import json
app = Flask(__name__)
@app.route('/')
def home_page():
return render_template("weatherdetail.html",name="sreedhar")
@app.route('/details')
def detailed_page():
url="http://api.openweathermap.org/data/2.5/forecast/daily?q=hyderabad,in&cnt=10&mode=json&units=metric&APPID=2d80cf7142a085e6c34f383205d35118"
#d=requests.get(url).json()
d=requests.get(url).text
data=json.loads(d)
mn=data.get('list')[0].get('temp').get('min')
mx=data.get('list')[0].get('temp').get('max')
return render_template("weatherdetail.html",maximun=mx)
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/Session-5-Strings/IDLE-workout-StringMethods.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # String
>>>
>>> # string methods
>>> # to change the case of strings
>>>
>>> # StringName.upper() -> upper case
>>> # StringName.lower() -> lower case
>>> # stringName.capitalize() -> capitalized case
>>>
>>> name="python is easy"
>>>
>>> name.upper()
'PYTHON IS EASY'
>>> name
'python is easy'
>>> # the results are non-persistent
>>> # over-riding
>>>
>>> name=name.upper()
>>> name
'PYTHON IS EASY'
>>>
>>> name.lower()
'python is easy'
>>> name
'PYTHON IS EASY'
>>> name=name.lower()
>>>
>>> 23456.upper()
SyntaxError: invalid syntax
>>>
>>>
>>> "23456".upper()
'23456'
>>>
>>> # Method - object specific
>>> # method is applied on the object
>>>
>>> # Function(Input) - dir(),type(), str(234)
>>> # Input.Function() <file_sep>/Session-7-List-ListMethods/listMethods-1.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> fruits=[]
>>> fruits
[]
>>> fruits=['banana','cherry','melon','pappaya']
>>> fruits
['banana', 'cherry', 'melon', 'pappaya']
>>>
>>> len(fruits)
4
>>> fruits[0]
'banana'
>>> fruits[1]
'cherry'
>>> fruits[2]
'melon'
>>> fruits[3]
'pappaya'
>>> fruits[4]
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
fruits[4]
IndexError: list index out of range
>>>
>>> numbers=['one','two',3,4,5]
>>>
>>>
>>> veg=["ocra",'eggplant','snakeguard']
>>>
>>> fruits
['banana', 'cherry', 'melon', 'pappaya']
>>>
>>>
>>> fruits[0]
'banana'
>>> fruits[0].upper()
'BANANA'
>>>
>>> fruits.upper()
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
fruits.upper()
AttributeError: 'list' object has no attribute 'upper'
>>>
>>>
>>> fruits
['banana', 'cherry', 'melon', 'pappaya']
>>> # adding a new value to a list
>>> # listName.append(Value)
>>>
>>> fruits.append('melon')
>>> fruits
['banana', 'cherry', 'melon', 'pappaya', 'melon']
>>> fruits.append("grape")
>>> fruits
['banana', 'cherry', 'melon', 'pappaya', 'melon', 'grape']
>>>
>>> veg
['ocra', 'eggplant', 'snakeguard']
>>>
>>> fruits.append(veg)
>>> fruits
['banana', 'cherry', 'melon', 'pappaya', 'melon', 'grape', ['ocra', 'eggplant', 'snakeguard']]
>>>
>>> len(fruits)
7
>>> fruits[5]
'grape'
>>> fruits[6]
['ocra', 'eggplant', 'snakeguard']
>>>
>>>
>>> fruits.extend(veg)
>>> fruits
['banana', 'cherry', 'melon', 'pappaya', 'melon', 'grape', ['ocra', 'eggplant', 'snakeguard'], 'ocra', 'eggplant', 'snakeguard']
>>>
>>> # fruits.remove(veg)
>>> # fruits.remove([1,2,3,4,5])
>>> fruits.remove(veg)
>>> fruits
['banana', 'cherry', 'melon', 'pappaya', 'melon', 'grape', 'ocra', 'eggplant', 'snakeguard']
>>> # fruits.remove('melon')
>>>
>>>
====== RESTART: C:/Users/User/Desktop/Mizuho/Programs/Session-7-/interview_list.py ======
Enter your Namesri
Enter your Year of birth2010
Enter your DegreemBA
Hi,
Your name is sri,
You're 10 years old and you've studied mBA
the list is ['sri', 2010, 'mBA']
>>>
====== RESTART: C:/Users/User/Desktop/Mizuho/Programs/Session-7-/interview_list.py ======
Enter your Name sree
Enter your Year of birth 2009
Enter your Degree mca
Hi,
Your name is sree,
You're 11 years old and you've studied mca
the list is ['2009', 'sree', 'mca']
>>>
====== RESTART: C:/Users/User/Desktop/Mizuho/Programs/Session-7-/interview_list.py ======
Enter your Name spidey
Enter your Year of birth 1891
Enter your Degree ba
Hi,
Your name is spidey,
You're 129 years old and you've studied ba
the list is ['1891', 'spidey', 1891, 'ba']
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> details
['1891', 'spidey', 1891, 'ba']
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'curent_year', 'details', 'dob', 'edu', 'name', 'yr']
>>> <file_sep>/Session3-Idle-WorkOut.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # LHS = RHS
>>> # VariableName = Values
>>> # lowercase - everything else
>>> # UPPERCASE - global declarations
>>>
>>> # camelCase - functions
>>> # UpperCamelCase - ClassNames
>>>
>>> # details of a person
>>> # name,age,edu,contact
>>> "<NAME>"
'<NAME>'
>>> name="<NAME>"
>>> name
'<NAME>'
>>> name="NokolaTesla"
>>> name
'NokolaTesla'
>>> # over riding - assigning new values to an old variable
>>> shareprice=3.45
>>> shareprice=3.49
>>> shareprice=6
>>>
>>> age=10
>>> edu="MBA"
>>> contact="1234567"
>>>
>>>
>>> name
'NokolaTesla'
>>> age
10
>>> edu
'MBA'
>>> contact
'1234567'
>>>
>>>
>>>
>>> # finding the average os 3 subject marks
>>> # 3 subject marks
>>> # o/p -> average of the 3 sub mrks
>>>
>>> # arrange/collect/define the inputs / data
>>> # compute - calculation
>>>
>>> # displaying results
>>>
>>> math=99
>>> sci=89
>>> soc=40
>>>
>>> total=math+sci+soc
>>>
>>> avg=total/3
>>>
>>> avg
76.0
>>>
>>>
>>>
>>> # calculating simple Interest
>>>
>>> # PTR/100
>>>
>>> princi=10000
>>> rate=8.5
>>> time=5
>>>
>>> roi=princi*time*rate/100
>>>
>>> roi
4250.0
>>>
>>> # builtin functions
>>> # function - collection of multiple commands stored in a variable/name
>>> # takes input - output
>>>
>>> # tesla()
>>> # roi()
>>> # sri()
>>>
>>>
>>> # functionName(Input/Value)
>>>
>>> # to find all the definations in the current session
>>>
>>> # dir()
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'age', 'avg', 'contact', 'edu', 'math', 'name', 'princi', 'rate', 'roi', 'sci', 'shareprice', 'soc', 'time', 'total']
>>>
>>> # __somename__ / underscoreUNDERSCORE somename underscoreUNDERSCORE
>>> # dunder methods - system
>>>
>>>
>>> TRAINER = "SRI"
>>> dir()
['TRAINER', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'age', 'avg', 'contact', 'edu', 'math', 'name', 'princi', 'rate', 'roi', 'sci', 'shareprice', 'soc', 'time', 'total']
>>>
>>> pythontrainer="sri"
>>> dir()
['TRAINER', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'age', 'avg', 'contact', 'edu', 'math', 'name', 'princi', 'pythontrainer', 'rate', 'roi', 'sci', 'shareprice', 'soc', 'time', 'total']
>>>
>>>
>>> edu
'MBA'
>>>
>>> # datatype checking
>>> # check what data is stored in a variable
>>>
>>> # type()
>>> # type(variableName/value)
>>>
>>> type(edu)
<class 'str'>
>>> type(age)
<class 'int'>
>>> type(TRAINER)
<class 'str'>
>>>
>>> type(1111.1111)
<class 'float'>
>>> type(True)
<class 'bool'>
>>>
>>>
>>> <file_sep>/Session2-Idle-WorkOut.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 4
4
>>> 1111
1111
>>> 89.567
89.567
>>> "text data"
'text data'
>>> in
SyntaxError: invalid syntax
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> list()
[]
>>> for
SyntaxError: invalid syntax
>>> 2+2
4
>>> 4+"good morning"
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
4+"good morning"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
>>>
>>> # Arithmetic Operators
>>> # add - +
>>> # subtraction -
>>> # division - /
>>> # multiply - *
>>> # operators - more than 1 operand
>>>
>>> # arithmetic operations -> applied on same input data/supported data
>>>
>>> 2+345+2.5+100
449.5
>>>
>>> # " string/text "
>>>
>>> 1111 + 9999
11110
>>> "1111" +"9999"
'11119999'
>>>
>>>
>>> "elon"+"musk"
'elonmusk'
>>> # concatenation
>>> # "elon"+"musk"
>>>
>>> "elon"+" "+"musk"
'elon musk'
>>>
>>> 'elon'+"999 111"+'musk'+" "+" is "
'elon999 111musk is '
>>> ''' 3 single quotes '''
' 3 single quotes '
>>>
>>> """ 3 double quotes """
' 3 double quotes '
>>>
>>>
>>> # Variables
>>>
>>> # create memory / store values in the program session/space
>>>
>>> # LHS = RHS
>>> # LeftHand Side = RightHand Side
>>>
>>> # VariableName = Value
>>>
>>> firstname="sri"
>>> lastname="sree"
>>> age=10
>>> email="srisree@"
>>> age=12
>>>
>>>
>>> age
12
>>> lastname
'sree'
>>> firstname + lastname
'srisree'
>>> # variables = aliases / label / identifier
>>>
>>> # basic calculations
>>> # multiplication
>>> # "text" * 3
>>> # " text" * float
>>> # "textis" / 3
>>>
>>> <file_sep>/Session-8-Sort-in-tuples/ListMethods-Final.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> avengers=['spidey','aquaman','wonderwoman','ironMan','birdman']
>>> # value exists in a list/collection
>>> # Membership checking operator
>>>
>>> # in -> membership
>>> # value in collection
>>>
>>> 'spidey' in avengers
True
>>> 'aquaman' in avengers
True
>>> 'Aquaman' in avengers
False
>>> # 'p' in 'python
>>> # 1 in '1990'
>>> # 1 in 1990
>>>
>>> # findout the index of a value in a list
>>> avengers.index('ironMan')
3
>>> # ListName.index(Value) -> integer
>>> avengers.append("ironman")
>>> avengers
['spidey', 'aquaman', 'wonderwoman', 'ironMan', 'birdman', 'ironman']
>>>
>>>
>>> numbers=[9,1,8,2,7,3,7,4,6,0,5]
>>> numbers
[9, 1, 8, 2, 7, 3, 7, 4, 6, 0, 5]
>>> # sorting
>>> # ascen / descen
>>>
>>> # ListName.sort()
>>>
>>> numbers.sort()
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9]
>>>
>>> numbers=[9,1,8,2,7,3,7,4,6,0,5]
>>> numbers
[9, 1, 8, 2, 7, 3, 7, 4, 6, 0, 5]
>>>
>>> # sorting in descending order
>>> # ListName.sort(reverse=True)
>>>
>>> numbers.sort(reverse=True)
>>> numbers
[9, 8, 7, 7, 6, 5, 4, 3, 2, 1, 0]
>>>
>>>
>>> numbers.sort(reverse=False)
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9]
>>>
>>> numbers.sort()
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9]
>>>
>>>
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9]
>>> numbers=[9,1,8,2,7,3,7,4,6,0,5]
>>>
>>>
>>> numbers
[9, 1, 8, 2, 7, 3, 7, 4, 6, 0, 5]
>>>
>>> # builtin function
>>> # sorted()
>>>
>>> sorted(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9]
>>> numbers
[9, 1, 8, 2, 7, 3, 7, 4, 6, 0, 5]
>>>
>>>
>>> avengers
['spidey', 'aquaman', 'wonderwoman', 'ironMan', 'birdman', 'ironman']
>>> # batman
>>>
>>> # inserting values at a defined index
>>> # ListName.insert(Value,Index)
>>>
>>> # ListName.insert(Index,value) -> .insert(where,what)
>>>
>>> avengers.insert(0,'batman')
>>> avengers
['batman', 'spidey', 'aquaman', 'wonderwoman', 'ironMan', 'birdman', 'ironman']
>>>
>>> # ListName.append(Value)
>>> # ListName.insert(Index,value)
>>> # ListName.remove(Value)
>>> # Listname.pop(index)
>>>
>>> "Nikola Tesla ".split()
['Nikola', 'Tesla']
>>>
>>> # joining
>>>
>>> # collection , delimitter
>>> # add all the values to the delimitter
>>>
>>> # "Delimitter".join(Collection)
>>>
>>> "".join(['Nikola', 'Tesla'])
'NikolaTesla'
>>> " ".join(['Nikola', 'Tesla'])
'Nikola Tesla'
>>>
>>> "\n".join(avengers)
'batman\nspidey\naquaman\nwonderwoman\nironMan\nbirdman\nironman'
>>> print("\n".join(avengers))
batman
spidey
aquaman
wonderwoman
ironMan
birdman
ironman
>>>
>>>
>>> # Tuple
>>>
>>> t=()
>>> type(t)
<class 'tuple'>
>>> sample=(1,2,3,4,)
>>> sample
(1, 2, 3, 4)
>>> # dir(sample)
>>>
>>> len(sample)
4
>>>
>>>
>>> t
()
>>>
>>> 1,2,3,4,5,6,7
(1, 2, 3, 4, 5, 6, 7)
>>>
>>>
>>> # list+tuple
>>> # tuple + tuple
>>>
>>> # in
>>>
>>>
>>>
>>>
>>> # Indexing in Lists
>>>
>>>
>>> <file_sep>/Session-10-Practice/indentation.py
fruits = ['melon','papaya','grapes','apple','cherry','banana']
# print length of a string , print the upper case of every string
##for fruit in fruits:
## print(len(fruit))
##print(fruit.upper())
for fruit in fruits:
print(len(fruit))
print(fruit.upper())
<file_sep>/Session-11-Counters-Dicts/dictionary-1.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> d={}
>>> d
{}
>>> type(d)
<class 'dict'>
>>>
>>> fruits={
"melon":5,
"grapes":10,"banana":10,
"cherry":200
}
>>> fruits
{'melon': 5, 'grapes': 10, 'banana': 10, 'cherry': 200}
>>> len(fruits)
4
>>> fruits={
"melon":5,
"grapes":['red','black'],
"banana":10,
"cherry":200
}
>>>
>>> fruits
{'melon': 5, 'grapes': ['red', 'black'], 'banana': 10, 'cherry': 200}
>>> len(fruits)
4
>>> fruits={
"melon":5,
"grapes":{'red':100,
'black':200},
"banana":10,
"cherry":200
}
>>>
>>> fruits
{'melon': 5, 'grapes': {'red': 100, 'black': 200}, 'banana': 10, 'cherry': 200}
>>> len(fruits)
4
>>>
>>> animals={
"name":"Sleep_total",
"Cheetah":12.1,
"Owl Monkey":17,
"Owl Monkey":17.17}
>>> animals
{'name': 'Sleep_total', 'Cheetah': 12.1, 'Owl Monkey': 17.17}
>>>
>>>
>>> <file_sep>/README.md
# Mizuho-Python-Programming
#### Python Work out Files
```
Every Session Folder will have respective class work out files.
Respective class files would have the data sets which have been discussed in classes
```
<file_sep>/Session-10-Practice/textData.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> """name,genus,vore,order,conservation,sleep_total,sleep_rem,sleep_cycle,awake,brainwt,bodywt
Cheetah,Acinonyx,carni,Carnivora,lc,12.1,NA,NA,11.9,NA,50"""
'name,genus,vore,order,conservation,sleep_total,sleep_rem,sleep_cycle,awake,brainwt,bodywt\nCheetah,Acinonyx,carni,Carnivora,lc,12.1,NA,NA,11.9,NA,50'
>>> rows="""name,genus,vore,order,conservation,sleep_total,sleep_rem,sleep_cycle,awake,brainwt,bodywt
Cheetah,Acinonyx,carni,Carnivora,lc,12.1,NA,NA,11.9,NA,50"""
>>>
>>>
>>> rows.split('\n')
['name,genus,vore,order,conservation,sleep_total,sleep_rem,sleep_cycle,awake,brainwt,bodywt', 'Cheetah,Acinonyx,carni,Carnivora,lc,12.1,NA,NA,11.9,NA,50']
>>> rows.split('\n')[0]
'name,genus,vore,order,conservation,sleep_total,sleep_rem,sleep_cycle,awake,brainwt,bodywt'
>>> rows.split('\n')[1]
'Cheetah,Acinonyx,carni,Carnivora,lc,12.1,NA,NA,11.9,NA,50'
>>>
>>>
>>> rows.split('\n')[0].split(',')
['name', 'genus', 'vore', 'order', 'conservation', 'sleep_total', 'sleep_rem', 'sleep_cycle', 'awake', 'brainwt', 'bodywt']
>>>
>>> rows.split('\n')[0].split(',').index('name')
0
>>> rows.split('\n')[0].split(',').index('sleep_total')
5
>>> rows.split('\n')[0].split(',')[0]
'name'
>>> rows.split('\n')[0].split(',')[5]
'sleep_total'
>>> rows.split('\n')[1].split(',')[0]
'Cheetah'
>>> rows.split('\n')[1].split(',')[5]
'12.1'
>>>
>>>
>>>
>>> print(rows.split('\n')[0].split(',')[0],"\t",
rows.split('\n')[0].split(',')[5], "\n",
rows.split('\n')[1].split(',')[0],"\t",
rows.split('\n')[1].split(',')[5])
name sleep_total
Cheetah 12.1
>>>
>>>
>>> print("a\tb")
a b
>>> print("""
%s \t %s"""%(rows.split('\n')[1].split(',')[0],rows.split('\n')[1].split(',')[5]))
Cheetah 12.1
>>>
>>>
>>>
>>> # looping
>>> # is it line ? is it a word ?
>>> # loop variable
>>> # extra credit -> convert the string(sleep_time) -> float
>>> <file_sep>/Session-7-List-ListMethods/interview_list.py
# Interview program
name=input("Enter your Name ")
dob=input("Enter your Year of birth ")
edu=input("Enter your Degree ")
curent_year=2020
details=[]
details.append(dob)
dob=int(dob)
yr=curent_year-dob
details.append(name)
details.append(dob)
details.append(edu)
print("""
Hi,
Your name is %s,
You're %s years old and you've studied %s"""%(name,curent_year-dob,edu))
print("the list is ",details)
<file_sep>/Session-16-OS-Tasks/placeName.py
# get user input & build url
placeName=input("Enter the place -> ")
url="http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=10&mode=json&units=metric&APPID=YOURAPIKEYHERE"%(placeName)
print("The URL built is \n",url)
<file_sep>/Session-20-Functions/Functions-Routines-Methods.md
Functions - Routines - Methods
dir()
type()
list(), tuple() .. function()
// creating a function
functionName Function Output- returns the op
def - keyword
part-1 > Function Name,Inputs/arguments/args
part-2 > Function Body
part-3 > Function return
// structure of a function
// function defination/creation
def sampleFunction(arg1,arg2,arg3,...argN): # part 1
result=code on args/Inputs # part 2
return result # part 3
def sqr(number):
result=number*number
return result
// fucntion calling
sampleFunction(val1,val2,val3...valN)
camelCaseFunctionNames()
getData()
processData()
generateReport()
def collect():
name=input("Enter a name here ")
age=input("enter your age here ")
return name,age
# create a function that takes 2 numbers and returns the greatest
# of the 2
num1=5
num2=6
if num1>num2:
print(num1 is greater)
else:
print(num2 is greater)
def greater(num1,num2):
if num1>num2:
return num1
else:
return num2
# create a function that takes 3 numbers and returns the greatest
# of the 3
a>b a>c a
b>a b>c b
c>a c>b c
##########################
method - function
methods - Object Specific , str,int,flaot,list,tuple ...
functions - Generic dir(), type()
"string".upper()
['a','b',c'].upper()
##########################<file_sep>/Session-25-Project/weatherapp.py
from flask import Flask, render_template
import requests
import json
app = Flask(__name__)
@app.route('/')
def home_page():
return render_template("weatherdetail.html",name="sreedhar")
@app.route('/details')
def detailed_page():
url="http://api.openweathermap.org/data/2.5/forecast/daily?q=hyderabad,in&cnt=10&mode=json&units=metric&APPID=APIKEY"
#d=requests.get(url).json3()
d=requests.get(url).text
data=json.loads(d)
mn=data.get('list')[0].get('temp').get('min')
mx=data.get('list')[0].get('temp').get('max')
des=data.get('list')[0].get('weather')[0].get('description',"Not Available")
return render_template("weatherdetail.html",maximun=mx,minimum=mn,description=des)
@app.route('/fulldetails/<placename>')
def fulldetailed_page(placename):
url="http://api.openweathermap.org/data/2.5/forecast/daily?q=%s&cnt=10&mode=json&units=metric&APPID=APIKEY"%(placename)
resp=requests.get(url).text
data=json.loads(resp)
table=""
for eachDay in data.get('list'):
table=table+"""<tr><td> %s </td><td> %s </td><td> %s </td></tr>"""%(eachDay.get('temp').get('max'),eachDay.get('temp').get('min'),eachDay.get('weather')[0].get('description',"Not Available"))
return render_template("fullweatherdetails.html",tabledata=table,PlaceName=placename)
# ,eachDay.get('weather')[0].get('description',"Not Available")
if __name__ == '__main__':
app.run(debug=True)
<file_sep>/Session-15-Libraries-req-json/ClassNotes.md
# Libraries / Modules / packages
Libraries - a program / collection of multiple functions ( packed together under one name space)
A sample Library, mathematics would have multiple math related functions
Mathematicspy
- addition()
- sin()
- cosine()
- subtration ()
- sqrt()
# importing functions / classes from a library
##### First install the package
using below, install a library / package / module
pip install moduleName
##### Calling the library into our workspace
syntax :
import <ModuleName>
##### call a functionality from an imported library
syntax :
ModuleName.functionality()
##### This is how we need to import
:
```
1#) import -> keyword
import moduleName
Usage :
moduleName.methodName(inputs)
2# ) selective imports
from ModuleName import MethodName
from ModuleName import MethodName,MethodName,MethodName,MethodName
3#) Nick Names to the imports / aliasing
import math as nope
from ModuleName import MethodName as nopenope
```
### libraries , we'll use in our class
> requests -> how to connect to internet
> os -> how to interact with the OS/System
> json -> to deal with json data
#### requests -> browser
1) enter the web address
2) send request
3) catch the response
4) perform/use response
```
1) enter the web address
-> define a variable
2) send request
-> requests.get(URL/URLVariable)
3) catch the response
-> assign a var to the resp
-> respObj = requests.get(URL/URLVariable)
4) perform/use response
deal with respObj
```
#### JSON -> Data Format
```
- create a json object
- convert a python Obj into a JSON data
- json.dumps(pythonObj)
- create a python object
- convert a json data into Python Object
-json.loads(jsonObj)
```
<file_sep>/Session-20-Functions/functionsWorkOut.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>>
>>> # take a number and return the square of it
>>> num=8
>>> sr_num=num*num
>>> sr_num
64
>>>
>>> def sqr(number):
result=number*number
return result
>>> sqr(2)
4
>>> sqr(8)
64
>>> sqr(89)
7921
>>>
>>> sqr()
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
sqr()
TypeError: sqr() missing 1 required positional argument: 'number'
>>>
>>>
>>> type(sqr)
<class 'function'>
>>>
>>> type()
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
type()
TypeError: type() takes 1 or 3 arguments
>>>
>>>
>>> # create a function that takes a number and returns the
>>> # cube of the number
>>>
>>> # create a function that takes 3 numbers and returns the
>>> # sum of 3 numbers
>>>
>>> # create a function that takes a value and returns
>>> # the type of it
>>>
>>>
>>> def cube(number):
result=number*number*number
return result
>>> cube(2)
8
>>> cube(3)
27
>>> cube(4)
64
>>>
>>> def total(x,y,z):
result=x+y+z
return result
>>> total
<function total at 0x0000004C142768B8>
>>>
>>> total(10,10,10)
30
>>>
>>> def typeof(value):
return type(value)
>>> typeof(3)
<class 'int'>
>>>
>>> typeof(" ")
<class 'str'>
>>>
>>>
>>>
>>> # function that takes 3 args and returns the 3 values as it
>>>
>>> def someNme(a,b,c):
return a,b,c
>>> someNme(1,2,3)
(1, 2, 3)
>>>
>>> someNme("python","is","awesome")
('python', 'is', 'awesome')
>>>
>>> def someNme(a,b,c):
return [a,b,c]
>>> someNme(1,2,3)
[1, 2, 3]
>>>
>>>
>>>
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'cube', 'num', 'someNme', 'sqr', 'sr_num', 'total', 'typeof']
>>> cube(2)
8
>>> two=cube(2)
>>> two
8
>>> three=cube(3)
>>> three
27
>>>
>>> c=someNme(1,2,3)
>>> c
[1, 2, 3]
>>>
>>> c
[1, 2, 3]
>>> c
[1, 2, 3]
>>>
>>> def cube(number):
result=number*number*number
return result
>>> def cube(number):
result=number*number*number
print(result)
>>> def cube(number):
result=number*number*number
return result
>>> cube(5)
125
>>> five=cube(5)
>>> five
125
>>>
>>>
>>> def cube(number):
result=number*number*number
print(result)
>>> cube(5)
125
>>> five=cube(5)
125
>>> five
>>> five
>>> five
>>> type(five)
<class 'NoneType'>
>>>
>>> # function that does nothing
>>> def dummy():
return pass
SyntaxError: invalid syntax
>>>
>>> def dummy():
return None
>>> dummy
<function dummy at 0x0000004C14276678>
>>> dummy()
>>>
>>>
>>> <file_sep>/Session-19-WordCount/idleWorkOut.py
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> "a"=="a"
True
>>> "A"=="a"
False
>>>
>>> "please go out"
'please go out'
>>> "PLEASE GO OUT"
'PLEASE GO OUT'
>>> for line in "william":
print(line)
w
i
l
l
i
a
m
>>> 'romeo and juliet. '.split()
['romeo', 'and', 'juliet.']
>>>
>>>
>>>
>>> d={}
>>> d['word']=1
>>>
>>> d
{'word': 1}
>>>
>>> d['word']
1
>>> d['word']=d['word']+1
>>>
>>> d['word']
2
>>> d['word']=d['word']+1
>>> d['word']
3
>>> d['word']=d['word']+1
>>> d['word']
4
>>>
>>> d
{'word': 4}
>>>
>>> 'sreedhar' in d
False
>>> 'word' in d
True
>>> 'sreedhar' not in d
True
>>> 'word' not in d
False
>>> <file_sep>/Session-28-Files/ReadMe.md
### Files
###### WorkFlow
```
1) Locate the file
2) Open the file
- read mode
- write mode
--- processes ---
2.1) Read the file
apply
.read() method on the fileObj to read all at once
.readline() to read the file line by line
.readlines() to read the file into a list of strings
3) close the file
Fileobj.close()
3.1) verify if the file is closed
Fileobj.closed
2) Opening a file
open() -> To open all the files
2 args
1) FilePath/FileName with extension
2) access mode
open('FIleName.ext',AcessMode)
Access Modes
r - Read mode
w - write mode
a - append mode
open('data.txt','r')
fileObj=open('data.txt','r')
FileName -> data.txt ( just filename if in the same foder)
'c://someFolderName/data.txt' ( if in other folder )
```
### creating a File / writing to a file
```
open('FileYouWanttoCreate.txt','w')
```
### Write to a file
```
- open the file in write mode
- have the content ready which needs to be written
- use .write() method to write to a file
.write("content_to_be_written")
```
| 1d7a45737e3ae2a1faf8e7cb037421feab8cc289 | [
"Markdown",
"Python"
] | 41 | Python | srisreedhar/Mizuho-Python-Programming | 57e89536b51062606bc972c51534b30d7c3a05d5 | 938c9505659e21cc65357d074affb904f7d632b2 |
refs/heads/master | <file_sep>Inprint.documents.downloads.Main = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.access = {};
this.config = {};
this.urls = {};
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.store = new Ext.data.JsonStore({
root: "data",
autoLoad: true,
baseParams: { pictures: true },
url: _source("documents.downloads.list"),
fields: [
"id", "downloaded",
"edition", "edition_shortcut",
"fascicle", "fascicle_shortcut",
"document", "document_shortcut",
"filename", "description", "mime", "extension", "published", "size", "length",
{ name: "created", type: "date", dateFormat: "c" },
{ name: "updated", type: "date", dateFormat: "c" }
]
});
// Column model
this.colModel = new Ext.grid.ColumnModel({
defaults: {
sortable: true,
menuDisabled:true
},
columns: [
this.selectionModel,
{
id:"published",
width: 32,
dataIndex: "published",
sortable: false,
renderer: function(v) {
var image = '';
if (v==1) { image = '<img src="'+ _ico("light-bulb") +'"/>'; }
return image;
}
},
{ id:'filename', header: _("File"), dataIndex:'filename',
renderer: function(value, p, record) {
if (record.get("downloaded") == 0 ) {
return String.format("<span style=\"color:{1}\"><b>{0}</b></span>", value, "black");
} else {
return String.format("<span style=\"color:{1}\">{0}</span>", value, "#6E6E6E");
}
}
},
{ id:'edition', header: _("Edition"), dataIndex:'edition_shortcut', width: 120 },
{ id:'fascicle', header: _("Fascicle"), dataIndex:'fascicle_shortcut', width: 80 },
{ id:'document', header: _("Document"), dataIndex:'document_shortcut', width: 200 },
{ id: 'size', header: _("Size"), dataIndex:'size', width:60, renderer:Ext.util.Format.fileSize},
{ id: 'length', header: _("Characters"), dataIndex:'length', width:60 },
{ id: 'created', header: _("Created"), dataIndex:'created', width:90, xtype: 'datecolumn', format: 'M d H:i' },
{ id: 'updated', header: _("Updated"), dataIndex:'updated', width:90, xtype: 'datecolumn', format: 'M d H:i' }
]
});
this.tbar = [
{
id: "download",
scope:this,
disabled: true,
ref: "../btnDownload",
handler: this.cmpDownload,
cls: "x-btn-text-icon",
text: _("Get archive"),
icon: _ico("arrow-transition-090")
},
{
id: "safedownload",
scope:this,
disabled: true,
ref: "../btnSafeDownload",
handler: this.cmpSafeDownload,
cls: "x-btn-text-icon",
text: _("Safe download"),
icon: _ico("arrow-transition-090")
},
"->",
{
columnWidth: .125,
xtype: "treecombo",
name: "edition",
fieldLabel: _("Edition"),
emptyText: _("Edition") + "...",
minListWidth: 300,
url: _url('/common/tree/editions/'),
baseParams: {
term: 'editions.documents.work:*'
},
rootVisible:true,
root: {
id:'all',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("All editions")
},
listeners: {
scope:this,
select: function (combo, node) {
this.store.baseParams.flt_edition = node.id;
this.store.reload();
}
}
},
{
columnWidth:.125,
xtype: "treecombo",
name: "fascicle",
fieldLabel: _("Fascicle"),
emptyText: _("Fascicle") + "...",
minListWidth: 300,
url: _url('/common/tree/fascicles/'),
baseParams: {
term: 'editions.documents.work:*'
},
rootVisible:true,
root: {
id:'all',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("blue-folder-open-document-text"),
text: _("All fascicles")
},
listeners: {
scope:this,
select: function (combo, node) {
this.store.baseParams.flt_fascicle = node.id;
this.store.reload();
}
}
},
"-",
{
scope:this,
pressed: false,
enableToggle: true,
text: _("Documents"),
ref: "../btnDocuments",
cls: "x-btn-text-icon",
icon: _ico("documents-stack"),
toggleHandler: function(item, pressed) {
this.store.baseParams.documents = pressed;
this.store.reload();
}
},
{
scope:this,
pressed: true,
enableToggle: true,
text: _("Images"),
ref: "../btnPictures",
cls: "x-btn-text-icon",
icon: _ico("pictures-stack"),
toggleHandler: function(item, pressed) {
this.store.baseParams.pictures = pressed;
this.store.reload();
}
}
];
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "filename"
});
// Call parent (required)
Inprint.documents.downloads.Main.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.documents.downloads.Main.superclass.onRender.apply(this, arguments);
this.getSelectionModel().on("selectionchange", function(sm) {
sm.getCount() == 0 ? this.btnDownload.disable() : this.btnDownload.enable();
sm.getCount() == 0 ? this.btnSafeDownload.disable() : this.btnSafeDownload.enable();
}, this);
},
cmpDownload: function (params) {
// generate a new unique id
var frameid = Ext.id();
// create a new iframe element
var frame = document.createElement('iframe');
frame.id = frameid;
frame.name = frameid;
frame.className = 'x-hidden';
// use blank src for Internet Explorer
if (Ext.isIE) {
frame.src = Ext.SSL_SECURE_URL;
}
// append the frame to the document
document.body.appendChild(frame);
// also set the name for Internet Explorer
if (Ext.isIE) {
document.frames[frameid].name = frameid;
}
// create a new form element
var form = Ext.DomHelper.append(document.body, {
tag: "form",
method: "post",
action: _source("documents.downloads.download"),
target: frameid
});
if (params && params.translitEnabled) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "safemode";
hidden.value = "true";
form.appendChild(hidden);
}
Ext.each(this.getSelectionModel().getSelections(), function(record) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "file[]";
hidden.value = record.get("document") +"::"+ record.get("id");
form.appendChild(hidden);
});
document.body.appendChild(form);
form.submit();
},
cmpSafeDownload: function() {
this.cmpDownload({
translitEnabled: true
});
}
});
Inprint.registry.register("document-downloads", {
icon: "drive-download",
text: _("Downloads"),
description: _("List of downloads"),
xobject: Inprint.documents.downloads.Main
});
<file_sep>Inprint.catalog.indexes.Interaction = function(parent, panels) {
var editions = panels.editions;
var headlines = panels.headlines;
var rubrics = panels.rubrics;
// Set defaults
rubrics.disable();
// Set Actions
rubrics.btnCreateItem.on("click", Inprint.getAction("rubric.create") .createDelegate(parent, [rubrics]));
rubrics.btnUpdateItem.on("click", Inprint.getAction("rubric.update") .createDelegate(parent, [rubrics]));
rubrics.btnDeleteItem.on("click", Inprint.getAction("rubric.delete") .createDelegate(parent, [rubrics]));
// Tree Editions Events
editions.getSelectionModel().on("selectionchange", function(sm, node) {
if (node) {
headlines.enable();
headlines.setEdition(node.id);
headlines.getRootNode().id = node.id;
headlines.getRootNode().reload();
}
});
// Tree Headlines Events
headlines.getSelectionModel().on("selectionchange", function(sm, node) {
if (node) {
rubrics.enable();
rubrics.setHeadline(node.id);
rubrics.btnCreateItem.enable();
rubrics.cmpLoad({ headline: node.id });
}
});
headlines.on("contextmenu", function(headline) {
var items = [];
var disabled = true;
if (parent.access["domain.index.manage"]) {
disabled = false;
}
var btnCreate = Inprint.getButton("create.item");
btnCreate.handler = Inprint.getAction("headline.create").createDelegate(parent, [headlines]);
btnCreate.disabled = disabled;
items.push( btnCreate );
if (headline && headline.id != NULLID) {
var btnUpdate = Inprint.getButton("update.item");
btnUpdate.handler = Inprint.getAction("headline.update").createDelegate(parent, [headlines, headline]);
btnUpdate.disabled = disabled;
items.push( btnUpdate );
var btnDelete = Inprint.getButton("delete.item");
btnDelete.handler = Inprint.getAction("headline.delete").createDelegate(parent, [headlines, headline]);
btnDelete.disabled = disabled;
items.push( btnDelete );
}
new Ext.menu.Menu({ items : items }).show(headline.ui.getAnchor());
});
headlines.on("containercontextmenu", function(tree, e) {
var items = [];
var disabled = true;
if (parent.access["domain.index.manage"]) {
disabled = false;
}
var btnCreate = Inprint.getButton("create.item");
btnCreate.handler = Inprint.getAction("headline.create").createDelegate(parent, [headlines]);
btnCreate.disabled = disabled;
items.push( btnCreate );
items.push('-');
items.push({
icon: _ico("arrow-circle-double"),
cls: "x-btn-text-icon",
text: _("Reload"),
handler: function() {
tree.cmpReload();
}
});
new Ext.menu.Menu({ items : items }).showAt(e.getXY());
});
// Grid Rubrics Events
rubrics.getSelectionModel().on("selectionchange", function(sm) {
_disable(rubrics.btnDeleteItem, rubrics.btnUpdateItem);
if (parent.access["domain.index.manage"]) {
if (sm.getCount() == 1) {
_enable(rubrics.btnUpdateItem);
}
if (sm.getCount() > 0) {
_enable(rubrics.btnDeleteItem);
}
}
});
// Set Access
_a(["domain.index.manage"], null, function(terms) {
parent.access = terms;
});
};
<file_sep>#!/bin/sh
find . -type d | xargs chmod -v 755
find . -type f | xargs chmod -v 644
find . -type f -name \*.pl | xargs chmod -v 755
find . -type f -name \*.sh | xargs chmod -v 755<file_sep>Inprint.cmp.composer.Interaction = function(parent, panels) {
var modules = panels.modules;
var templates = panels.templates;
var flash = panels.flash;
modules.getSelectionModel().on("selectionchange", function(sm, node) {
if (node) {
if(node.leaf) {
flash.cmpMoveBlocks({
module: node.attributes.mapping,
page: node.attributes.page
});
}
}
}, modules);
modules.on("contextmenu", function(node, e) {
e.stopEvent();
var items = [];
items.push({
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
ref: "../btnRemove",
scope:this,
handler: this.cmpDelete
});
var coords = e.getXY();
new Ext.menu.Menu({ items : items }).show(node.ui.getAnchor());
}, modules);
modules.on("templateDroped", function(id) {
Ext.Ajax.request({
url: parent.urls.modulesCreate,
scope:this,
params: {
fascicle: parent.fascicle,
pages: parent.selection,
template: id
},
success: function() {
flash.cmpInit();
modules.cmpReload();
}
});
}, modules);
};
<file_sep>Inprint.plugins.rss.control.Access = function(parent, panels) {
};
<file_sep>ALTER TABLE ad_modules RENAME COLUMN check_width TO width;
ALTER TABLE ad_modules RENAME COLUMN check_height TO height;
ALTER TABLE ad_modules RENAME COLUMN check_width_float TO fwidth;
ALTER TABLE ad_modules RENAME COLUMN check_height_float TO fheight;
ALTER TABLE fascicles_modules RENAME COLUMN check_width TO width;
ALTER TABLE fascicles_modules RENAME COLUMN check_height TO height;
ALTER TABLE fascicles_modules RENAME COLUMN check_width_float TO fwidth;
ALTER TABLE fascicles_modules RENAME COLUMN check_height_float TO fheight;
--ALTER TABLE fascicles_requests ADD COLUMN origin_width real DEFAULT 0 NOT NULL;
--ALTER TABLE fascicles_requests ADD COLUMN origin_height real DEFAULT 0 NOT NULL;
--ALTER TABLE fascicles_requests ADD COLUMN origin_fwidth real DEFAULT 0 NOT NULL;
--ALTER TABLE fascicles_requests ADD COLUMN origin_fheight real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_tmpl_modules ADD COLUMN width real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_tmpl_modules ADD COLUMN height real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_tmpl_modules ADD COLUMN fwidth real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_tmpl_modules ADD COLUMN fheight real DEFAULT 0 NOT NULL;
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.documents.GridActions = function() {
return {
// Create new document
Create: function() {
var panel = new Inprint.cmp.CreateDocument();
panel.show();
panel.on("complete", function() { this.cmpReload(); }, this);
},
// Update document's short profile
Update: function() {
var panel = new Inprint.cmp.UpdateDocument({
document: this.getValue("id")
});
panel.show();
panel.on("complete", function() {
this.cmpReload();
}, this);
},
// Capture document from another user
Capture: function() {
Ext.MessageBox.confirm(
_("Document capture"),
_("You really want to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _url("/documents/capture/"),
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
},
// Move document(s) to another user
Transfer: function() {
var params = {};
var editions = this.getValues("edition");
var stages = this.getValues("stage");
for (var c=0; c < editions.length; c++) {
if (params.edition && params.edition != editions[c]) {
params.edition = null;
break;
}
params.edition = editions[c];
}
for (var c=0; c < stages.length; c++) {
if (params.stage && params.stage != stages[c]) {
params.stage = null;
break;
}
params.stage = stages[c];
}
var panel = new Inprint.cmp.ExcahngeBrowser(params).show();
panel.on("complete", function(id){
Ext.Ajax.request({
url: _url("/documents/transfer/"),
scope:this,
success: this.cmpReload,
params: {
id: this.getValues("id"),
transfer: id
}
});
}, this);
},
// Move document(s) to briefcase
Briefcase: function() {
Ext.MessageBox.confirm(
_("Moving to the briefcase"),
_("You really want to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _url("/documents/briefcase/"),
scope:this,
success: this.cmpReload,
params: {
id: this.getValues("id")
}
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
},
// Move document(s) to another fascicle
Move: function() {
var cmp = new Inprint.cmp.MoveDocument();
cmp.setId(this.getValues("id"));
cmp.show();
cmp.on("actioncomplete", function() {
this.cmpReload();
}, this);
},
// Copy document(s) to another fascicle(s)
Copy: function() {
var cmp = new Inprint.cmp.CopyDocument();
cmp.setId(this.getValues("id"));
cmp.show();
cmp.on("actioncomplete", function() {
this.cmpReload();
}, this);
},
// Duplicate document(s) to another fascicle(s)
Duplicate: function() {
var cmp = new Inprint.cmp.DuplicateDocument();
cmp.setId(this.getValues("id"));
cmp.show();
cmp.on("actioncomplete", function() {
this.cmpReload();
}, this);
},
// Move document(s) to Recycle Bin
Recycle: function() {
Ext.MessageBox.confirm(
_("Moving to the recycle bin"),
_("You really want to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _url("/documents/recycle/"),
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
},
// Restore documents from Recycle Bin
Restore: function() {
Ext.MessageBox.confirm(
_("Document restoration"),
_("You really want to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _url("/documents/restore/"),
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
},
// Delete document from DB and Filesystem
Delete: function() {
Ext.MessageBox.confirm(
_("Irreversible removal"),
_("You can't cancel this action!"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _url("/documents/delete/"),
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
};
};
<file_sep>Ext.namespace("Inprint.fascicle.plan");<file_sep>Inprint.setAction("rubric.create", function(grid) {
var headline = grid.getHeadline();
var url = _url("/catalog/rubrics/create/");
var form = new Ext.FormPanel({
url: url,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_HEADLINE,
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_ADD,_BTN_CLOSE ]
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
grid.cmpReload();
}
});
form.getForm().findField("headline").setValue(headline);
var win = Inprint.factory.windows.create(
"Create rubric", 400, 260, form
).show();
});
<file_sep>Ext.ux.DateRangeField = Ext.extend(Ext.form.DateField, {minText:"The dates in this field must be equal to or after {0}",maxText:"The dates in this field must be equal to or before {0}",reverseText:"The end date must be posterior to the start date",notEqualText:"The end date can't be equal to the start date",dateSeparator:" - ",hideValidationButton:false,authorizeEqualValues:true,mergeEqualValues:true,autoReverse:true,setDisabledDates:function(a) {
this.disabledDates = a;
this.initDisabledDays();
if (this.menu) {
this.menu.rangePicker.startDatePicker.setDisabledDates(this.disabledDatesRE);
this.menu.rangePicker.endDatePicker.setDisabledDates(this.disabledDatesRE)
}
},setDisabledDays:function(a) {
this.disabledDays = a;
if (this.menu) {
this.menu.rangePicker.startDatePicker.setDisabledDays(a);
this.menu.rangePicker.endDatePicker.setDisabledDays(a)
}
},setMinValue:function(a) {
this.minValue = (typeof a == "string" ? this.parseDate(a) : a);
if (this.menu) {
this.menu.rangePicker.startDatePicker.setMinDate(this.minValue);
this.menu.rangePicker.endDatePicker.setMinDate(this.minValue)
}
},setMaxValue:function(a) {
this.maxValue = (typeof a == "string" ? this.parseDate(a) : a);
if (this.menu) {
this.menu.rangePicker.startDatePicker.setMaxDate(this.maxValue);
this.menu.rangePicker.endDatePicker.setMaxDate(this.maxValue)
}
},validateValue:function(h) {
h = this.formatDate(h);
if (!Ext.form.DateField.superclass.validateValue.call(this, h)) {
return false
}
if (h.length < 1) {
return true
}
var c = h;
h = this.parseDate(h);
var i = c.split(this.dateSeparator);
if (i.length == 1) {
if (!h) {
this.markInvalid(String.format(this.invalidText, c, this.format));
return false
}
var j = Date.parseDate(i[0], this.format);
var e = Ext.ux.DateRangeField.superclass.validateValue.call(this, j);
if (!e) {
this.markInvalid(String.format(this.invalidText, c, this.format));
return false
} else {
return true
}
} else {
if (i.length == 2) {
if (!h) {
this.markInvalid(String.format(this.invalidText, c, this.format + this.dateSeparator + this.format));
return false
}
var k = Date.parseDate(i[0], this.format);
var g = Date.parseDate(i[1], this.format);
if (!k || !g) {
this.markInvalid(String.format(this.invalidText, c, this.format + this.dateSeparator + this.format));
return false
}
var f = Ext.ux.DateRangeField.superclass.validateValue.call(this, k);
var d = Ext.ux.DateRangeField.superclass.validateValue.call(this, g);
if (!f || !d) {
this.markInvalid(String.format(this.invalidText, c, this.format + this.dateSeparator + this.format));
return false
}
var a = Date.parse(g);
var b = Date.parse(k);
if ((a - b) < 0) {
this.markInvalid(this.reverseText);
return false
}
if (!this.authorizeEqualValues && a == b) {
this.markInvalid(this.notEqualText);
return false
}
} else {
this.markInvalid(String.format(this.invalidText, c, this.format + this.dateSeparator + this.format));
return false
}
}
return true
},parseDate:function(f) {
if (!f || Ext.isDate(f) || this.isRangeDate(f)) {
return f
}
var c = f.split(this.dateSeparator);
if (c.length == 1) {
return Ext.ux.DateRangeField.superclass.parseDate.call(this, f)
} else {
if (c.length == 2) {
var b = Date.parseDate(c[0], this.format);
var e = Date.parseDate(c[1], this.format);
if ((!b || !e) && this.altFormats) {
if (!this.altFormatsArray) {
this.altFormatsArray = this.altFormats.split("|")
}
var d,a;
if (!b) {
for (d = 0,a = this.altFormatsArray.length; d < a && !b; d++) {
b = Date.parseDate(c[0], this.altFormatsArray[d])
}
}
if (!e) {
for (d = 0,a = this.altFormatsArray.length; d < a && !e; d++) {
e = Date.parseDate(c[1], this.altFormatsArray[d])
}
}
}
return{startDate:b,endDate:e}
} else {
return f
}
}
},formatDate:function(a) {
if (Ext.isDate(a)) {
return Ext.ux.DateRangeField.superclass.formatDate.call(this, a)
}
if (this.isRangeDate(a)) {
if (this.mergeEqualValues && Date.parse(a.startDate) == Date.parse(a.endDate)) {
return a.startDate.dateFormat(this.format)
} else {
if (this.autoReverse && Date.parse(a.startDate) > Date.parse(a.endDate)) {
return a.endDate.dateFormat(this.format) + this.dateSeparator + a.startDate.dateFormat(this.format)
} else {
return a.startDate.dateFormat(this.format) + this.dateSeparator + a.endDate.dateFormat(this.format)
}
}
} else {
return a
}
},onTriggerClick:function() {
if (this.disabled) {
return
}
if (!this.menu) {
this.menu = new Ext.ux.DateRangeMenu({hideOnClick:false,hideValidationButton:this.hideValidationButton})
}
this.onFocus();
Ext.apply(this.menu.rangePicker.startDatePicker, {minDate:this.minValue ? this.minValue : new Date(0),maxDate:this.maxValue ? this.maxValue : new Date(2999, 11, 31),disabledDatesRE:this.disabledDatesRE,disabledDatesText:this.disabledDatesText,disabledDays:this.disabledDays,disabledDaysText:this.disabledDaysText,format:this.format,showToday:this.showToday,minText:String.format(this.minText, this.formatDate(this.minValue)),maxText:String.format(this.maxText, this.formatDate(this.maxValue))});
Ext.apply(this.menu.rangePicker.endDatePicker, {minDate:this.minValue ? this.minValue : new Date(0),maxDate:this.maxValue ? this.maxValue : new Date(2999, 11, 31),disabledDatesRE:this.disabledDatesRE,disabledDatesText:this.disabledDatesText,disabledDays:this.disabledDays,disabledDaysText:this.disabledDaysText,format:this.format,showToday:this.showToday,minText:String.format(this.minText, this.formatDate(this.minValue)),maxText:String.format(this.maxText, this.formatDate(this.maxValue))});
var c = new Date();
var a = new Date();
var b = this.getValue();
if (Ext.isDate(b)) {
c = b;
a = b
} else {
if (this.isRangeDate(b)) {
c = b.startDate;
a = b.endDate
}
}
this.menu.rangePicker.startDatePicker.setValue(c);
this.menu.rangePicker.endDatePicker.setValue(a);
this.menu.show(this.el, "tl-bl?");
this.menuEvents("on")
},isRangeDate:function(a) {
return(Ext.isObject(a) && Ext.isDate(a.startDate) && Ext.isDate(a.endDate))
}});
Ext.reg("daterangefield", Ext.ux.DateRangeField);
Ext.ux.DateRangeMenu = Ext.extend(Ext.menu.DateMenu, {layout:"auto",cls:"x-date-range-menu",initComponent:function() {
this.on("beforeshow", this.onBeforeShow, this);
Ext.apply(this, {plain:true,showSeparator:false,items:[this.rangePicker = new Ext.ux.DateRangePicker(this.initialConfig)]});
this.rangePicker.purgeListeners();
Ext.menu.DateMenu.superclass.initComponent.call(this);
this.relayEvents(this.rangePicker, ["select"])
},onBeforeShow:function() {
if (this.rangePicker) {
this.rangePicker.startDatePicker.hideMonthPicker(true);
this.rangePicker.endDatePicker.hideMonthPicker(true)
}
},showAt:function(c, b, a) {
this.parentMenu = b;
if (!this.el) {
this.render()
}
if (a !== false) {
this.fireEvent("beforeshow", this);
c = this.el.adjustForConstraints(c)
}
this.el.setXY(c);
if (this.enableScrolling) {
this.constrainScroll(c[1])
}
this.el.show();
Ext.menu.Menu.superclass.onShow.call(this);
this.hidden = false;
this.focus();
this.fireEvent("show", this)
}});
Ext.reg("daterangemenu", Ext.ux.DateRangeMenu);
Ext.ux.DateRangePicker = Ext.extend(Ext.Panel, {layout:"hbox",layoutConfig:{defaultMargins:{left:5,top:5,right:0,bottom:5}},height:234,width:369,cls:"x-menu-date-range-item",selectedDate:{startDate:null,endDate:null},buttonAlign:"center",hideValidationButton:false,initComponent:function() {
this.items = [this.startDatePicker = new Ext.DatePicker(Ext.apply({internalRender:this.strict || !Ext.isIE,ctCls:"x-menu-date-item"}, this.initialConfig)),this.endDatePicker = new Ext.DatePicker(Ext.apply({internalRender:this.strict || !Ext.isIE,ctCls:"x-menu-date-item"}, this.initialConfig))];
this.startDatePicker.on("select", this.startDateSelect, this);
this.endDatePicker.on("select", this.endDateSelect, this);
this.tbar = new Ext.Toolbar({items:[this.startDateButton = new Ext.Button({text:"Start Date ...",cls:"x-menu-date-range-item-start-date-button",enableToggle:true,allowDepress:false,toggleGroup:"DateButtonsGroup",toggleHandler:this.onStartDatePress.createDelegate(this)}),this.rangeDateButton = new Ext.Button({text:"Range Date",cls:"x-menu-date-range-item-range-date-button",pressed:true,enableToggle:true,allowDepress:false,toggleGroup:"DateButtonsGroup",toggleHandler:this.onRangeDatePress.createDelegate(this)}),"->",this.endDateButton = new Ext.Button({text:"... End Date",cls:"x-menu-date-range-item-end-date-button",enableToggle:true,allowDepress:false,toggleGroup:"DateButtonsGroup",toggleHandler:this.onEndDatePress.createDelegate(this)})]});
if (!this.hideValidationButton) {
this.fbar = new Ext.Toolbar({cls:"x-date-bottom",items:[
{
xtype:"button",
text:"ok",
width:"auto",
handler:this.onOkButtonPress.createDelegate(this)
}
]});
this.height = this.height + 28
}
Ext.ux.DateRangePicker.superclass.initComponent.call(this)
},onRangeDatePress:function(a, b) {
if (b) {
this.startDatePicker.enable();
this.endDatePicker.enable();
this.resetDates()
}
},onStartDatePress:function(a, b) {
if (b) {
this.startDatePicker.enable();
this.endDatePicker.disable();
this.resetDates()
}
},onEndDatePress:function(a, b) {
if (b) {
this.startDatePicker.disable();
this.endDatePicker.enable();
this.resetDates()
}
},startDateSelect:function(b, a) {
this.selectedDate.startDate = a;
if (this.startDateButton.pressed) {
this.selectedDate.endDate = this.endDatePicker.maxDate;
this.returnSelectedDate()
} else {
if (this.selectedDate.endDate !== null) {
this.returnSelectedDate()
}
}
},endDateSelect:function(b, a) {
this.selectedDate.endDate = a;
if (this.endDateButton.pressed) {
this.selectedDate.startDate = this.startDatePicker.minDate;
this.returnSelectedDate()
} else {
if (this.selectedDate.startDate !== null) {
this.returnSelectedDate()
}
}
},resetselectedDate:function() {
this.selectedDate = {startDate:null,endDate:null}
},resetDates:function() {
this.resetselectedDate();
this.startDatePicker.setValue(new Date());
this.endDatePicker.setValue(new Date())
},returnSelectedDate:function() {
this.fireEvent("select", this, this.selectedDate);
this.resetselectedDate()
},onOkButtonPress:function(a, b) {
if (b) {
if (this.startDateButton.pressed) {
this.selectedDate = {startDate:this.startDatePicker.getValue(),endDate:this.endDatePicker.maxDate}
} else {
if (this.endDateButton.pressed) {
this.selectedDate = {startDate:this.startDatePicker.minDate,endDate:this.endDatePicker.getValue()}
} else {
this.selectedDate = {startDate:this.startDatePicker.getValue(),endDate:this.endDatePicker.getValue()}
}
}
this.returnSelectedDate()
}
}});
Ext.reg("daterangepicker", Ext.ux.DateRangePicker);<file_sep>Inprint.plugins.rss.control.Tree = Ext.extend(Ext.tree.TreePanel, {
initComponent: function() {
this.components = {};
this.urls = {
"tree": _url("/plugin/rss/control/tree/"),
"create": _url("/plugin/rss/control/create/"),
"read": _url("/plugin/rss/control/read/"),
"update": _url("/plugin/rss/control/update/"),
"delete": _url("/plugin/rss/control/delete/")
};
Ext.apply(this, {
autoScroll:true,
dataUrl: this.urls.tree,
border:false,
rootVisible: true,
baseParams: { },
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
icon: _ico("feed"),
text: _("Default feed")
}
});
Inprint.plugins.rss.control.Tree.superclass.initComponent.apply(this, arguments);
this.on("beforeappend", function(tree, parent, node) {
if (node.attributes.icon === undefined) {
node.attributes.icon = 'folder-open';
}
node.attributes.icon = _ico(node.attributes.icon);
if (node.attributes.color) {
node.text = "<span style=\"color:#"+ node.attributes.color +"\">" + node.attributes.text + "</span>";
}
});
},
onRender: function() {
Inprint.plugins.rss.control.Tree.superclass.onRender.apply(this, arguments);
this.getRootNode().on("expand", function(node) {
node.firstChild.select();
});
this.getLoader().on("beforeload", function() { this.body.mask(_("Loading data...")); }, this);
this.getLoader().on("load", function() { this.body.unmask(); }, this);
this.getRootNode().expand();
},
cmpCreate: function(node) {
var win = this.components["add-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.create,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_URL,
_FLD_TITLE,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_ADD,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Adding a new edition"),
layout: "fit",
closeAction: "hide",
width:400, height:200,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
node.reload();
}
}, this);
}
var form = win.items.first().getForm();
form.reset();
win.show(this);
this.components["add-window"] = win;
},
cmpUpdate: function(node) {
var win = this.components["edit-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.update,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_ID,
_FLD_URL,
_FLD_TITLE,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Catalog item creation"),
layout: "fit",
closeAction: "hide",
width:400, height:200,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
if (node.parentNode) {
node.parentNode.reload();
} else if(node.reload) {
node.reload();
}
}
}, this);
}
win.show(this);
win.body.mask(_("Loading data..."));
this.components["edit-window"] = win;
var form = win.items.first().getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: node.id
},
success: function(form, action) {
win.body.unmask();
//form.findField("id").setValue(action.result.data.id);
},
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
},
cmpDelete: function(node) {
var title = _("Group removal") +" <"+ node.attributes.shortcut +">";
Ext.MessageBox.confirm(
title,
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: function() {
node.parentNode.reload();
},
params: { id: node.attributes.id }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.cmp.CreateDocument.Access = function(parent, form) {
_a(["catalog.documents.create:*", "catalog.documents.assign:*", "editions.documents.assign:*"], null, function(terms) {
if(terms["catalog.documents.create"]) {
parent.buttons[0].enable();
}
if(terms["catalog.documents.assign"]) {
form.getForm().findField("workgroup").enable();
form.getForm().findField("manager").enable();
}
if(terms["editions.documents.assign"]) {
form.getForm().findField("fascicle").enable();
//form.getForm().findField("headline").enable();
}
});
};
<file_sep>Inprint.documents.editor.FormPanel = Ext.extend( Ext.form.FormPanel,
{
initComponent: function()
{
this.editor = new Inprint.documents.editor.Form();
this.charCounter = new Ext.Toolbar.TextItem('Знаков: 0');
Ext.apply(this, {
border:false,
layout:'fit',
items: this.editor,
bbar: {
xtype: "statusbar",
statusAlign : 'right',
items : [
{
scope : this,
disabled:true,
ref: "../btnSave",
text : _("Save"),
cls : 'x-btn-text-icon',
icon: _ico("disk-black"),
handler : function() {
this.getForm().submit();
}
},
'->',
this.charCounter
]
}
});
Inprint.documents.editor.FormPanel.superclass.initComponent.apply(this, arguments);
},
// Override other inherited methods
onRender: function() {
Inprint.documents.editor.FormPanel.superclass.onRender.apply(this, arguments);
this.getForm().timeout = 15;
this.getForm().url = '/documents/text/set/';
this.getForm().baseParams = {
file: this.file,
document: this.document
};
this.on('beforeaction', function() {
this.body.mask(_("Saving text") + '...');
this.btnSave.disable();
}, this);
this.on('actionfailed', function() {
this.body.unmask();
var rspns = Ext.util.JSON.decode(action.response.responseText);
if (rspns.data.error) {
Ext.MessageBox.alert( _("Error"), rspns.data.error);
} else {
Ext.MessageBox.alert(_("Error"), _("Unable to save text"));
}
if (rspns.data.access ) {
rspns.data.access.fedit? this.btnSave.enable() : this.btnSave.disable();
}
}, this);
this.on('actioncomplete', function(form, action) {
this.body.unmask();
this.parent.cmpReload();
var rspns = Ext.util.JSON.decode(action.response.responseText);
if (rspns.data.error) {
Ext.MessageBox.alert( _("Error"), rspns.data.error);
}
if (rspns.data.access ) {
rspns.data.access.fedit? this.btnSave.enable() : this.btnSave.disable();
}
}, this);
this.editor.on('sync', function( editor, html ) {
var count = this.cmpGetCharCount(html);
Ext.fly( this.charCounter.getEl()).update('Знаков: ' + count );
}, this);
this.editor.on('initialize', function() {
this.body.mask(_("Loading data..."));
Ext.Ajax.request({
url : '/documents/text/get/',
scope : this,
params : {
file : this.file,
document: this.document
},
callback: function(options, success, response) {
this.body.unmask();
var rspns = Ext.util.JSON.decode(response.responseText);
if (rspns.data.error) {
Ext.MessageBox.alert( _("Error"), rspns.data.error);
}
if (rspns.data.access ) {
rspns.data.access.fedit? this.btnSave.enable() : this.btnSave.disable();
}
},
success: function(response, options) {
var rspns = Ext.util.JSON.decode(response.responseText);
this.editor.setValue(rspns.data.text);
},
failure : function(response, options) {
Ext.MessageBox.alert( _("Error"), _("Operation failed"));
}
}, this);
}, this);
},
cmpGetCharCount: function(html) {
html = html.replace(/\s+$/, "");
html = html.replace(/ /g, "-");
html = html.replace(/[\xD]?\xA/g, "");
html = html.replace(/&(lt|gt);/g,
function(strMatch, p1) {
return (p1 == "lt") ? "<" : ">";
});
html = html.replace(/<\/?[^>]+(>|$)/g, "");
var cc = html.length ? html.length : 0;
return cc;
}
});
<file_sep>Ext.namespace("Inprint.fascicle.indexes");
<file_sep>Ext.namespace("Inprint.documents.downloads");
<file_sep>Ext.namespace("Inprint.system.logs");<file_sep>Inprint.calendar.forms.AttachmentRestrictions = Ext.extend( Ext.form.FormPanel,
{
initComponent: function()
{
this.items = [
_FLD_HDN_ID,
{
labelWidth: 20,
xtype: "xdatetime",
name: "doc_date",
format: "F j, Y",
fieldLabel: _("Documents")
},
{
xtype: 'xdatetime',
name: 'adv_date',
format:'F j, Y',
fieldLabel: _("Advertisement")
},
{
xtype: "numberfield",
name: "adv_modules",
fieldLabel: _("Modules")
}
];
Ext.apply(this, {
baseCls: 'x-plain',
defaults:{ anchor:'98%' }
});
Inprint.calendar.forms.AttachmentRestrictions.superclass.initComponent.apply(this, arguments);
this.getForm().url = _source("attachment.restrictions");
},
onRender: function() {
Inprint.calendar.forms.AttachmentRestrictions.superclass.onRender.apply(this, arguments);
},
cmpFill: function (id) {
this.load({
scope:this,
params: { id: id },
url: _source("attachment.read"),
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
}
});
<file_sep>Inprint.fascicle.indexes.Interaction = function(parent, panels) {
var headlines = panels.headlines;
var rubrics = panels.rubrics;
// Tree
headlines.getSelectionModel().on("selectionchange", function(sm, node) {
if (node) {
parent.headline = node.id;
rubrics.enable();
rubrics.cmpLoad({ headline: parent.headline });
rubrics.btnCreate.enable();
}
});
rubrics.getSelectionModel().on("selectionchange", function(sm) {
_disable(rubrics.btnDelete, rubrics.btnUpdate);
if (parent.access.manage) {
if (sm.getCount() == 1) {
_enable(rubrics.btnUpdate);
}
if (sm.getCount() > 0) {
_enable(rubrics.btnDelete);
}
}
});
};
<file_sep>Inprint.calendar.forms.UpdateTemplateForm = Ext.extend( Ext.form.FormPanel, {
initComponent: function() {
this.items = [
_FLD_HDN_ID,
{
xtype: "textfield",
name: "shortcut",
allowBlank:false,
fieldLabel: _("Shortcut")
},
{
xtype: "textfield",
name: "description",
fieldLabel: _("Description")
},
{
xtype: "numberfield",
name: "adv_modules",
fieldLabel: _("Modules")
}
];
Ext.apply(this, {
baseCls: 'x-plain',
defaults:{ anchor:'100%' }
});
Inprint.calendar.forms.UpdateTemplateForm.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.calendar.forms.UpdateTemplateForm.superclass.onRender.apply(this, arguments);
this.getForm().url = _source("template.update");
},
setId: function(id) {
this.cmpSetValue("id", id);
},
cmpFill: function (id) {
this.load({
scope:this,
params: { id: id },
url: _source("template.read"),
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
}
});
<file_sep>Inprint.documents.Profile = Ext.extend(Ext.Panel, {
initComponent: function() {
this.document = this.oid;
this.panels = {};
this.panels.profile = new Inprint.documents.Profile.View({
oid: this.oid,
parent: this
});
this.panels.files = new Inprint.documents.Profile.Files({
oid: this.oid,
parent: this
});
this.panels.comments = new Inprint.documents.Profile.Comments({
oid: this.oid,
parent: this
});
Ext.apply(this, {
border:true,
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "north",
layout:"fit",
split:true,
height:220,
items: this.panels.profile
},
{ region: "center",
layout:"fit",
items: {
activeTab: 0,
border: false,
xtype: "tabpanel",
items:[
this.panels.files
]
}
},
{ region: "east",
layout:"fit",
split:true,
width:400,
items: this.panels.comments
}
]
});
Inprint.documents.Profile.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.documents.Profile.superclass.onRender.apply(this, arguments);
Inprint.documents.Profile.Access(this, this.panels);
Inprint.documents.Profile.Interaction(this, this.panels);
},
getValues: function() {
return [ this.oid ];
},
getValue: function() {
return this.oid;
},
cmpLoad: function() {
Ext.Ajax.request({
url: "/documents/profile/read/",
scope:this,
params: { id: this.oid },
success: function(result) {
var response = Ext.util.JSON.decode(result.responseText);
if (response.data) {
this.document = response.data.id;
this.panels.profile.cmpFill(response.data);
if (response.data.access["discuss"] === true) {
this.panels.comments.btnSay.enable();
}
this.panels.files.cmpAccess(response.data.access);
}
}
});
this.panels.comments.cmpLoad(this.oid);
},
cmpReload: function() {
this.cmpLoad();
this.panels.files.cmpReload(this.oid);
}
});
Inprint.registry.register("document-profile", {
icon: "folder-open-document",
text: _("Document profile"),
description: _("Document profile"),
xobject: Inprint.documents.Profile
});
<file_sep>/* Requests update */
ALTER TABLE fascicles_requests DROP COLUMN IF EXISTS "group_id";
ALTER TABLE fascicles_requests ADD COLUMN "group_id" VARCHAR ;
UPDATE fascicles_requests SET group_id = id;
ALTER TABLE fascicles_requests ALTER COLUMN "group_id" SET NOT NULL;
ALTER TABLE fascicles_requests ALTER COLUMN "group_id" SET DEFAULT uuid_generate_v4();
ALTER TABLE fascicles_requests DROP COLUMN IF EXISTS "fs_folder";
ALTER TABLE fascicles_requests ADD COLUMN "fs_folder" VARCHAR ;
UPDATE fascicles_requests SET fs_folder = '/datastore/requests/' || to_char(created, 'YYYY-MM') || '/' || id;
ALTER TABLE fascicles_requests ALTER COLUMN "fs_folder" SET NOT NULL;
/* Documents update */
ALTER TABLE documents DROP COLUMN IF EXISTS "group_id";
ALTER TABLE documents ADD COLUMN "group_id" VARCHAR ;
UPDATE documents SET group_id = id;
ALTER TABLE documents ALTER COLUMN "group_id" SET NOT NULL;
ALTER TABLE documents ALTER COLUMN "group_id" SET DEFAULT uuid_generate_v4();
ALTER TABLE documents DROP COLUMN IF EXISTS "fs_folder";
ALTER TABLE documents ADD COLUMN "fs_folder" VARCHAR ;
UPDATE documents SET group_id = copygroup;
UPDATE documents SET fs_folder = '/datastore/documents/' || to_char(created, 'YYYY-MM') || '/' || id;
ALTER TABLE documents ALTER COLUMN "fs_folder" SET NOT NULL;
<file_sep>//Inprint.cmp.AccessPanel = Ext.extend(Ext.grid.EditorGridPanel, {
//
// initComponent: function() {
//
// this.components = {};
//
// this.urls = {
// rolemap: "/roles/mapping/"
// };
//
// this.sm = new Ext.grid.CheckboxSelectionModel({
// checkOnly:true
// });
//
// this.store = Inprint.factory.Store.group("/rules/list/", {
// autoLoad:true
// });
//
// this.view = new Ext.grid.GroupingView({
// forceFit:true,
// showGroupName:false,
// startCollapsed:true,
// hideGroupedColumn:true
// });
//
// Ext.apply(this, {
// title: _("Group rules"),
// stripeRows: true,
// columnLines: true,
// clicksToEdit: 1,
// columns: [
// this.sm,
// {
// id:"shortcut",
// header: _("Rule"),
// width: 120,
// sortable: true,
// dataIndex: "shortcut"
// },
// {
// id:"groupby",
// header: _("Group by"),
// width: 120,
// sortable: true,
// dataIndex: "groupby"
// },
// {
// id: "limit",
// header: _("Limit"),
// width: 50,
// dataIndex: 'limit',
// renderer: function(value, metadata, record, row, col, store) {
// if (value === undefined || value == "") {
// return _("Employee");
// }
// return value;
// },
// editor: new Ext.form.ComboBox({
// lazyRender : true,
// store: new Ext.data.ArrayStore({
// fields: ['id', 'name'],
// data : [
// [ 'member', _("Employee")],
// [ 'group', _("Group")]
// ]
// }),
// hiddenName: "id",
// valueField: "id",
// displayField:'name',
// mode: 'local',
// forceSelection: true,
// editable:false,
// emptyText:_("Limitation...")
// })
// }
// ],
//
// tbar: [
// {
// icon: _ico("plus-circle"),
// cls: "x-btn-text-icon",
// text: _("Save"),
// disabled:true,
// ref: "../btnSave",
// scope:this,
// handler: this.cmpSave
// },
// {
// icon: _ico("plus-circle"),
// cls: "x-btn-text-icon",
// text: _("Save recursive"),
// disabled:true,
// ref: "../btnSaveRecursive",
// scope:this,
// handler: this.cmpSave
// },
// '->',
// Inprint.factory.Combo.create("roles", {
// width: 150,
// disableCaching: true,
// listeners: {
// scope:this,
// select: function(combo, record) {
// this.cmpFillByRole(record.get("id"));
// }
// }
// }),
// {
// icon: _ico("arrow-circle-double"),
// cls: "x-btn-icon",
// scope:this,
// handler: this.cmpReload
// }
// ]
// });
//
// Inprint.cmp.AccessPanel.superclass.initComponent.apply(this, arguments);
//
// },
//
// onRender: function() {
// Inprint.cmp.AccessPanel.superclass.onRender.apply(this, arguments);
//
// this.on("afteredit", function(e) {
// var combo = this.getColumnModel().getCellEditor(e.column, e.row).field;
// e.record.set(e.field, combo.getRawValue());
// e.record.set("selection", combo.getValue());
// this.getSelectionModel().selectRow(e.row, true);
// });
//
// },
//
// cmpSave: function() {
// var data = [];
// Ext.each(this.getSelectionModel().getSelections(), function(record) {
// data.push(record.get("id") + "::" + record.get("selection"));
// });
// Ext.Ajax.request({
// url: this.urls.save,
// scope:this,
// success: function() {
// this.cmpReload();
// },
// params: {
// account: this.params.account,
// rule: data
// }
// });
// },
//
// cmpFill: function() {
// alert("Inprint.cmp.AccessPanel:cmpFill must be redefined!");
// //
// //var sm = this.getSelectionModel();
// //sm.clearSelections();
// //
// //var store = this.getStore();
// //
// //this.body.mask(_("Loading"));
// //
// //Ext.Ajax.request({
// // url: this.urls.fill,
// // scope:this,
// // params: {
// // account: this.params.account
// // },
// // success: function(responce) {
// //
// // this.body.unmask();
// //
// // var responce = Ext.util.JSON.decode(responce.responseText);
// // var selection = responce.data;
// //
// // store.each(function(record) {
// // if (selection[ record.get("id") ]) {
// //
// // var rule = record.get("id");
// // var area = selection[ record.get("id") ];
// //
// // record.set("selection", area);
// //
// // Ext.each(record.get("area"), function(item) {
// // if (item[0] == area) {
// // record.set("empty", "<b>"+ item[1] +"</b>");
// // }
// // });
// //
// // sm.selectRecords([ record ], true);
// // }
// // })
// // }
// //});
// },
//
// cmpFillByRole: function(role) {
//
// var sm = this.getSelectionModel();
// sm.clearSelections();
//
// var store = this.getStore();
//
// this.body.mask(_("Loading"));
//
// Ext.Ajax.request({
// url: this.urls.rolemap,
// scope:this,
// params: {
// role: role
// },
// success: function(responce) {
//
// this.body.unmask();
//
// responce = Ext.util.JSON.decode(responce.responseText);
// var selection = responce.data;
//
// // store.each(function(record) {
// // if (selection[ record.get("id") ]) {
// //
// // var rule = record.get("id");
// // var area = selection[ record.get("id") ];
// //
// // record.set("selection", area);
// //
// // Ext.each(record.get("area"), function(item) {
// // if (item[0] == area) {
// // record.set("empty", "<b>"+ item[1] +"</b>");
// // }
// // });
// //
// // sm.selectRecords([ record ], true);
// // }
// // })
// }
// });
// }
//
//
//});
<file_sep>Inprint.documents.Editor = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {};
//this.panels.form = new Inprint.documents.editor.FormPanel({
// parent: this,
// file: this.oid,
// document: this.pid
//});
this.panels.form = new Inprint.documents.editor.FormTinyMce({
parent: this,
file: this.oid,
document: this.pid
});
this.panels.versions = new Inprint.documents.editor.Versions({
title: _("Hot save"),
url: _url("/documents/hotsave"),
parent:this,
oid: this.oid
});
this.panels.hotsaves = new Inprint.documents.editor.Versions({
title: _("Versions"),
url: _url("/documents/versions"),
parent:this,
oid: this.oid
});
this.tabpanel = new Ext.TabPanel({
activeTab: 0,
border:false,
defaults: { autoScroll: true, border:false },
items: [
this.panels.versions,
this.panels.hotsaves
],
listeners: {
"tabchange": function(tabpanel, panel) {
panel.cmpReload();
}
}
});
Ext.apply(this, {
border:false,
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
region: "center",
layout:"fit",
items: this.panels.form
},
{ region: "east",
layout:"fit",
split:true,
width:"50%",
items: this.tabpanel
}
]
});
Inprint.documents.Editor.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.documents.Editor.superclass.onRender.apply(this, arguments);
Inprint.documents.Editor.Interaction(this, this.panels);
},
cmpReload: function() {
if (this.panels.versions.cmpReload) { this.panels.versions.cmpReload(); }
if (this.panels.hotsaves.cmpReload) { this.panels.hotsaves.cmpReload(); }
}
});
Inprint.registry.register("document-editor", {
icon: "document-word-text",
text: _("Text editor"),
description: _("Text editor"),
xobject: Inprint.documents.Editor
});
<file_sep>Inprint.documents.Profile.Comments = Ext.extend(Ext.Panel, {
initComponent: function() {
this.tbar = [
{
icon: _ico("balloon--plus"),
cls: "x-btn-text-icon",
text: _("Add a comment"),
disabled:true,
ref: "../btnSay",
scope:this,
handler: this.cmpSay
}
];
this.tmpl = new Ext.XTemplate(
'<table width="99%" align="center" style="border:0px;">',
'<td style="border:0px;">',
'<tpl for=".">',
'<div style="font-size:12px;padding-left:20px;margin-right:10px;margin-bottom:10px;',
'background:url(/icons/{[ values.icon ? values.icon : "balloon-left" ]}.png) 0px 4px no-repeat;">',
'<div style="padding:3px 0px;',
'<tpl if="values.stage_color">border-bottom:2px solid #{stage_color};</tpl>">',
'<span style="font-weight:bold;">{member_shortcut}</span>',
' — {[ this.fmtDate( values.created ) ]}',
'{[values.stage_shortcut ? values.stage_shortcut : ""]}</div>',
'<div style="font-size:90%;padding:5px 0px;">{fulltext}</div>',
'</div>',
'</tpl>',
'<div style="clear:both;"></div>',
'</td>',
'</table>',
{
fmtDate : function(date) { return _fmtDate(date, 'M j, H:i'); }
}
);
Ext.apply(this, {
border: false,
items: [
{
border:false,
tpl: this.tmpl
}
]
});
Inprint.documents.Profile.Comments.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.documents.Profile.Comments.superclass.onRender.apply(this, arguments);
},
cmpAccess: function(access) {
_disable(this.btnSay);
if (access["discuss"] === true) {
this.btnSay.enable();
}
},
cmpLoad: function (id) {
if (id) {
this.cacheId = id;
var success = function(resp) {
var result = Ext.decode(resp.responseText);
this.cmpFill(result.data);
}
Ext.Ajax.request({
url: _url("/documents/comments/list/"),
scope: this,
success: success,
params: {
id: this.cacheId
}
});
}
},
cmpReload: function() {
this.cmpLoad(this.cacheId);
},
cmpFill: function(records) {
if (records) {
this.items.get(0).update(records);
}
},
cmpSay: function() {
Ext.MessageBox.show({
title: _("Comments"),
msg: _("Please enter your text"),
width:400,
buttons: Ext.MessageBox.OKCANCEL,
multiline: true,
scope:this,
fn: function(btn, text) {
if (btn == "ok") {
Ext.Ajax.request({
url: _url("/documents/comments/save/"),
scope:this,
success: this.cmpReload,
params: {
id: this.oid,
text: text
}
});
}
}
});
}
});
<file_sep>#!/bin/sh
PID_FILE=/var/run/inprint-converter.pid
export INPRINT_CONVERTER_HOME=/root/jod-webapp
case "$1" in
start)
cd ${INPRINT_CONVERTER_HOME} || exit
java -Xmx256m -Xms256m -jar jetty-runner-7.2.0.v20101020.jar --port 9999 --log daemon.log softing-filebackend-service-1.3.war &
echo $! > $PID_FILE
;;
stop)
pid=`cat $PID_FILE`
kill $pid
rm $PID_FILE
;;
esac
exit 0
<file_sep>Inprint.advertising.advertisers.Main = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.store = Inprint.factory.Store.json(
_source("advertisers.list"),
{
autoLoad: true,
totalProperty: 'total'
});
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
var xcolumns = Inprint.advertising.advertisers.Columns;
this.columns = [
this.selectionModel,
xcolumns.serial,
xcolumns.edition,
xcolumns.shortcut,
xcolumns.address,
xcolumns.contact,
xcolumns.inn,
xcolumns.kpp,
xcolumns.bank,
xcolumns.rs,
xcolumns.ks,
xcolumns.bik
];
this.tbar = [
{
icon: _ico("plus-button"),
cls: "x-btn-text-icon",
text: _("Add"),
ref: "../btnCreate",
scope:this,
handler: Inprint.advertising.advertisers.actionCreate
},
{
icon: _ico("pencil"),
cls: "x-btn-text-icon",
text: _("Update"),
disabled:true,
ref: "../btnUpdate",
scope:this,
handler: Inprint.advertising.advertisers.actionUpdate
},
'-',
{
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
disabled:true,
ref: "../btnDelete",
scope:this,
handler: Inprint.advertising.advertisers.actionDelete
}
];
this.bbar = new Ext.PagingToolbar({
pageSize: 100,
store: this.store,
displayInfo: true,
plugins: new Ext.ux.SlidingPager()
});
Ext.apply(this, {
border: false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "shortcut"
});
Inprint.advertising.advertisers.Main.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.advertising.advertisers.Main.superclass.onRender.apply(this, arguments);
this.getSelectionModel().on("selectionchange", function(sm) {
_disable(this.btnUpdate, this.btnDelete);
if (sm.getCount() == 1) {
_enable(this.btnUpdate, this.btnDelete);
} else if (sm.getCount() > 1) {
_enable(this.btnDelete);
}
}, this);
}
});
Inprint.registry.register("advert-advertisers", {
icon: "user-silhouette",
text: _("Advertisers"),
xobject: Inprint.advertising.advertisers.Main
});
<file_sep>#!/bin/sh
hypnotoad --stop script/inprint.pl
sudo -u www-data hypnotoad script/inprint.pl<file_sep>"use strict";
Inprint.calendar.issues.Issues = Ext.extend(Inprint.grid.GridPanel, {
initComponent: function() {
this.access = {};
this.tbar = [
Inprint.fx.btn.Create("../btnCreate", Inprint.calendar.CreateIssueAction.createDelegate(this)),
Inprint.fx.btn.Update("../btnUpdate", Inprint.calendar.UpdateIssueAction.createDelegate(this)),
Inprint.fx.btn.Delete("../btnDelete", Inprint.calendar.DeleteIssueAction.createDelegate(this)),
"-",
Inprint.fx.btn.Button("../btnOpenPlan", "layout-hf-2", "Open Plan", "", Inprint.calendar.ViewPlanAction.createDelegate(this)),
Inprint.fx.btn.Button("../btnOpenComposer", "layout-design", "Open Composer", "", Inprint.calendar.ViewComposerAction.createDelegate(this)),
"-",
Inprint.fx.btn.Button("../btnEnable", "status", "Enable", "", Inprint.calendar.EnableAction.createDelegate(this)),
Inprint.fx.btn.Button("../btnDisable", "status-offline", "Pause", "", Inprint.calendar.DisableAction.createDelegate(this)),
"-",
//Inprint.fx.btn.Copy("../btnCopy", Inprint.calendar.CopyIssueAction.createDelegate(this)),
Inprint.fx.btn.Button("../btnArchive", "blue-folder-zipper", "To Archive", "", Inprint.calendar.ArchiveAction.createDelegate(this)),
//Inprint.fx.btn.Button("../btnProperties", "property", "Properties", "", Inprint.calendar.PropertiesAction.createDelegate(this)),
"-",
Inprint.fx.btn.Button("../btnFormat", "cross-circle", "Format", "", Inprint.calendar.FormatAction.createDelegate(this)),
"->" ,
{
name: "edition",
xtype: "treecombo",
minListWidth: 300,
rootVisible:true,
fieldLabel: _("Edition"),
emptyText: _("Edition") + "...",
url: _url('/common/tree/editions/'),
baseParams: { term: 'editions.documents.work:*' },
root: {
id: "00000000-0000-0000-0000-000000000000",
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("All editions")
},
listeners: {
scope: this,
select: function(combo, record) {
this.cmpLoad({
edition: record.id,
fastype: "issue", archive: false
});
this.enable();
}
}
}
];;
this.store = new Inprint.factory.JsonStore()
.setSource("issue.list")
.setAutoLoad(true)
.setParams({
edition: "00000000-0000-0000-0000-000000000000", fastype: "issue", archive: false })
.addField("id")
.addField("fastype")
.addField("enabled")
.addField("edition")
.addField("edition_shortcut")
.addField("shortcut")
.addField("description")
.addField("adv_date")
.addField("adv_modules")
.addField("print_date")
.addField("doc_date")
.addField("release_date")
.addField("num")
.addField("anum")
.addField("tmpl")
.addField("tmpl_shortcut")
.addField("circulation")
.addField("created")
.addField("updated");
this.columns = [
Inprint.calendar.ux.columns.icon,
Inprint.calendar.ux.columns.status,
Inprint.calendar.ux.columns.shortcut,
Inprint.calendar.ux.columns.edition,
Inprint.calendar.ux.columns.num,
Inprint.calendar.ux.columns.template,
Inprint.calendar.ux.columns.circulation,
Inprint.calendar.ux.columns.docdate,
Inprint.calendar.ux.columns.advdate,
Inprint.calendar.ux.columns.advmodules,
Inprint.calendar.ux.columns.releasedate,
Inprint.calendar.ux.columns.printdate,
Inprint.calendar.ux.columns.created,
Inprint.calendar.ux.columns.updated
];
Ext.apply(this, {
layout:"fit",
region: "center",
split:true
});
Inprint.calendar.issues.Issues.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.calendar.issues.Issues.superclass.onRender.apply(this, arguments);
},
getRecord: function() {
return this.getSelectionModel().getSelected();
}
});
<file_sep>Inprint.fascicle.adverta.Interaction = function(parent, panels) {
var pages = panels.pages;
};
<file_sep>Gutenberg
===============
<file_sep>#!/bin/sh
# Inprint Content 5.0
# Copyright(c) 2001-2010, Softing, LLC.
# <EMAIL>
# http://softing.ru/license
PERL_VERSION=5.16
#sudo port install p$PERL_VERSION-dbd-pg
#sudo port install p$PERL_VERSION-config-tiny
#sudo port install p$PERL_VERSION-data-uuid
#sudo port install p$PERL_VERSION-file-copy-recursive
#sudo port install p$PERL_VERSION-libwww-perl
#sudo port install p$PERL_VERSION-scalar-list-utils
#sudo port install p$PERL_VERSION-moose
#sudo port install p$PERL_VERSION-moosex-types
#sudo port install p$PERL_VERSION-json-any
#sudo port install p$PERL_VERSION-gd
#sudo port install p$PERL_VERSION-gdtextutil
sudo perl -MCPAN -e 'install Mojolicious'
sudo perl -MCPAN -e 'install Mojolicious::Plugin::I18N'
sudo perl -MCPAN -e 'install DBIx::Connector'
sudo perl -MCPAN -e 'install Devel::SimpleTrace'
sudo perl -MCPAN -e 'install File::Util'
sudo perl -MCPAN -e 'install Text::Unidecode'
sudo perl -MCPAN -e 'install GD::Tiler'
sudo perl -MCPAN -e 'install MooseX::Storage'
sudo perl -MCPAN -e 'install MooseX::UndefTolerant'
<file_sep>Inprint.fascicle.indexes.Rubrics = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.components = {};
this.urls = {
"create": _url("/fascicle/rubrics/create/"),
"read": _url("/fascicle/rubrics/read/"),
"update": _url("/fascicle/rubrics/update/"),
"delete": _url("/fascicle/rubrics/delete/")
};
this.store = Inprint.factory.Store.json("/fascicle/rubrics/list/");
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"title",
header: _("Title"),
width: 160,
sortable: true,
dataIndex: "title"
},
{
id:"description",
header: _("Description"),
dataIndex: "description"
}
];
this.tbar = [
{
icon: _ico("marker--plus"),
cls: "x-btn-text-icon",
text: _("Add"),
disabled: true,
ref: "../btnCreate",
scope:this,
handler: function() { this.cmpCreate(); }
},
{
icon: _ico("marker--pencil"),
cls: "x-btn-text-icon",
text: _("Edit"),
disabled: true,
ref: "../btnUpdate",
scope:this,
handler: function() { this.cmpUpdate(); }
},
"-",
{
icon: _ico("marker--minus"),
cls: "x-btn-text-icon",
text: _("Delete"),
disabled: true,
ref: "../btnDelete",
scope:this,
handler: function() { this.cmpDelete(); }
}
];
Ext.apply(this, {
border: false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "description"
});
Inprint.fascicle.indexes.Rubrics.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.indexes.Rubrics.superclass.onRender.apply(this, arguments);
},
cmpCreate: function() {
var win = this.components["add-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.create,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_FASCICLE,
_FLD_HDN_HEADLINE,
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_ADD,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Adding a new category"),
layout: "fit",
closeAction: "hide",
width:400, height:260,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
this.cmpReload();
}
}, this);
}
var form = win.items.first().getForm();
form.reset();
form.findField("fascicle").setValue(this.parent.fascicle);
form.findField("headline").setValue(this.parent.headline);
win.show(this);
this.components["add-window"] = win;
},
cmpUpdate: function() {
var win = this.components["edit-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.update,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_ID,
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Edit category"),
layout: "fit",
closeAction: "hide",
width:400, height:260,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
this.cmpReload();
}
}, this);
}
win.show(this);
win.body.mask(_("Loading..."));
this.components["edit-window"] = win;
var form = win.items.first().getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: this.getValue("id")
},
success: function(form, action) {
win.body.unmask();
form.findField("id").setValue(action.result.data.id);
}
});
},
cmpDelete: function() {
var title = _("Deleting a category");
Ext.MessageBox.confirm(
title,
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.cmp.memberSettingsForm.Form = Ext.extend(Ext.FormPanel, {
initComponent: function() {
this.url = _url("/options/update/");
Ext.apply(this,
{
border:false,
autoScroll:true,
layout: "fit",
items: {
xtype:'tabpanel',
border:false,
deferredRender: false,
activeTab: 0,
defaults:{
bodyStyle:'padding:10px'
},
items:[
{
title: _("Exchange"),
layout:'form',
labelWidth: 120,
defaults: {
width: 230
},
defaultType: 'textfield',
items: [
{
xtype: "treecombo",
hiddenName: "edition",
fieldLabel: _("Edition"),
emptyText: _("Select main edition..."),
minListWidth: 300,
url: _url('/common/tree/editions/'),
baseParams: {
term: 'editions.documents.work:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("All editions")
}
},
{
xtype: "treecombo",
hiddenName: "workgroup",
fieldLabel: _("Group"),
emptyText: _("Select main department..."),
minListWidth: 300,
url: _url('/common/tree/workgroups/'),
baseParams: {
term: 'catalog.documents.view:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("folder-open"),
text: _("All departments")
}
}
]
},
{
title: _("Text editor"),
layout:'form',
labelWidth: 120,
defaults: {
width: 230
},
defaultType: 'textfield',
items: [
new Ext.form.ComboBox({
hiddenName: "font-style",
fieldLabel: _("Font style"),
store: new Ext.data.ArrayStore({
fields: ['id', 'title'],
data : [
["times new roman", _("Times New Roman") ],
]
}),
mode: 'local',
editable: false,
typeAhead: true,
valueField:'id',
displayField:'title',
forceSelection: true,
triggerAction: 'all',
emptyText: _("Select a font style...")
}),
new Ext.form.ComboBox({
hiddenName: "font-size",
fieldLabel: _("Font size"),
store: new Ext.data.ArrayStore({
fields: ['id', 'title'],
data : [
["small", _("Small size") ],
["medium", _("Medium size") ],
["large", _("Large size") ]
]
}),
mode: 'local',
editable: false,
typeAhead: true,
valueField:'id',
displayField:'title',
forceSelection: true,
triggerAction: 'all',
emptyText: _("Select a font size...")
})
]
}
]
}
});
Inprint.cmp.memberSettingsForm.Form.superclass.initComponent.apply(this, arguments);
this.getForm().url = this.url;
},
onRender: function() {
Inprint.cmp.memberSettingsForm.Form.superclass.onRender.apply(this, arguments);
var form = this.getForm();
var options = Inprint.session.options;
var editionId = options["default.edition"];
var editionTitle = options["default.edition.name"];
if (editionId && editionTitle) {
form.findField("edition").on("render", function(field) {
field.setValue( editionId, editionTitle );
});
}
var workgroupId = options["default.workgroup"];
var workgroupTitle = options["default.workgroup.name"];
if (workgroupId && workgroupTitle) {
form.findField("workgroup").on("render", function(field) {
field.setValue( workgroupId, workgroupTitle );
});
}
var fontSizeTitles = {
"small": _("Small size"),
"medium": _("Medium size"),
"large": _("Large size")
};
var fontSize = options["default.font.size"] || "medium";
var fontSizeTitle = fontSizeTitles[ fontSize ] || _("Medium size");
if (fontSize && fontSizeTitle) {
form.findField("font-size").on("render", function(field) {
field.setValue( fontSize, fontSizeTitle );
});
}
var fontStyleTitles = {
"times new roman": "Times New Roman"
};
var fontStyle = options["default.font.style"] || "times new roman";
var fontStyleTitle = fontStyleTitles[ fontStyle ] || "Times New Roman";
if (fontStyle && fontStyleTitle) {
form.findField("font-style").on("render", function(field) {
field.setValue( fontStyle, fontStyleTitle );
field.setRawValue( fontStyle, fontStyleTitle );
});
}
}
});
<file_sep>Inprint.fascicle.places.Places = Ext.extend(Ext.tree.TreePanel, {
initComponent: function() {
this.components = {};
this.urls = {
"tree": _url("/fascicle/templates/places/tree/"),
"create": _url("/fascicle/templates/places/create/"),
"read": _url("/fascicle/templates/places/read/"),
"update": _url("/fascicle/templates/places/update/"),
"delete": _url("/fascicle/templates/places/delete/")
};
Ext.apply(this, {
title:_("Editions"),
autoScroll:true,
dataUrl: this.urls.tree,
border:false,
rootVisible: true,
root: {
id: this.fascicle,
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("blue-folder"),
text: _("Fascicle"),
type: "fascicle"
}
});
Inprint.fascicle.places.Places.superclass.initComponent.apply(this, arguments);
this.on("beforeappend", function(tree, parent, node) {
node.attributes.icon = _ico(node.attributes.icon);
});
},
onRender: function() {
Inprint.fascicle.places.Places.superclass.onRender.apply(this, arguments);
this.getRootNode().on("expand", function(node) {
if (node.firstChild) {
node.firstChild.select();
}
});
this.getLoader().on("beforeload", function() { this.body.mask(_("Loading")); }, this);
this.getLoader().on("load", function() { this.body.unmask(); }, this);
},
cmpCreate: function(node) {
var wndw = this.components["create-window"];
if (!wndw) {
wndw = new Ext.Window({
layout: "fit",
closeAction: "hide",
width:400, height:260,
title: _("Catalog item creation"),
items: {
border:false,
xtype: "form",
labelWidth: 75,
url: this.urls.create,
bodyStyle: "padding:10px",
defaults: {
anchor: "100%",
allowBlank:false
},
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
node.reload();
}
},
items: [
_FLD_HDN_FASCICLE,
_FLD_TITLE,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ]
},
buttons: [
_BTN_WNDW_ADD,
_BTN_WNDW_CANCEL
]
});
this.components["create-window"] = wndw;
}
var form = wndw.findByType("form")[0].getForm();
form.reset();
wndw.show();
form.findField("fascicle").setValue(this.fascicle);
},
cmpUpdate: function(node) {
var win = this.components["edit-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.update,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_ID,
_FLD_TITLE,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Creating a new module"),
layout: "fit",
closeAction: "hide",
width:400, height:300,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
if (node.parentNode) {
node.parentNode.reload();
} else {
node.reload();
}
}
}, this);
}
win.show(this);
win.body.mask(_("Loading..."));
this.components["edit-window"] = win;
var form = win.items.first().getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: node.id
},
success: function(form, action) {
win.body.unmask();
form.findField("id").setValue(action.result.data.id);
},
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
},
cmpDelete: function(node) {
var title = _("Group removal") +" <"+ node.attributes.title +">";
Ext.MessageBox.confirm(
title,
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: function() {
node.parentNode.reload();
},
params: { id: node.attributes.id }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.fascicle.adverta.Modules = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.pageId = null;
this.pageW = null;
this.pageH = null;
this.params = {};
this.components = {};
this.urls = {
"list": "/advertising/modules/list/",
"create": _url("/advertising/modules/create/"),
"read": _url("/advertising/modules/read/"),
"update": _url("/advertising/modules/update/"),
"delete": _url("/advertising/modules/delete/")
};
this.store = Inprint.factory.Store.json(this.urls.list);
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"shortcut",
header: _("Shortcut"),
width: 150,
sortable: true,
dataIndex: "shortcut"
},
{
id:"description",
header: _("Description"),
sortable: true,
dataIndex: "description"
}
];
this.tbar = [
{
disabled:false,
icon: _ico("plus-button"),
cls: "x-btn-text-icon",
text: _("Add"),
ref: "../btnCreate",
scope:this,
handler: this.cmpCreate
},
{
disabled:true,
icon: _ico("pencil"),
cls: "x-btn-text-icon",
text: _("Edit"),
ref: "../btnUpdate",
scope:this,
handler: this.cmpUpdate
},
'-',
{
disabled:true,
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
ref: "../btnDelete",
scope:this,
handler: this.cmpDelete
}
];
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel
//autoExpandColumn: "description"
});
Inprint.fascicle.adverta.Modules.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.adverta.Modules.superclass.onRender.apply(this, arguments);
},
cmpCreate: function() {
var win = this.components["create-window"];
if (!win) {
var form = {
xtype: "form",
modal:true,
frame:false,
border:false,
labelWidth: 75,
url: this.urls.create,
bodyStyle: "padding:5px 5px",
defaults: {
anchor: "100%",
allowBlank:false
},
baseParams: {},
items: [
_FLD_HDN_EDITION,
_FLD_HDN_PAGE,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_SHORTCUT,
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: "numberfield",
allowBlank:false,
allowDecimals:false,
minValue: 1,
name: "amount",
value: 1,
fieldLabel: _("Amount")
}
],
listeners: {
scope:this,
beforeaction: function(form, action) {
var swf = this.components["create-window"].findByType("flash")[0].swf;
var id = Ext.getCmp(this.components["create-window"].getId()).form.getId();
//(function () {
swf.getBlock("Inprint.flash.Proxy.setModule", id, "new_block");
//}).defer(10);
},
actioncomplete: function (form, action) {
if (action.type == "submit") {
this.components["create-window"].hide();
this.cmpReload();
}
}
},
keys: [ _KEY_ENTER_SUBMIT ]
};
var flash = {
xtype: "flash",
swfWidth:380,
swfHeight:360,
hideMode : 'offsets',
url : '/flash/Dispose.swf',
expressInstall: true,
flashVars: {
src: '/flash/Dispose.swf',
scale :'noscale',
autostart: 'yes',
loop: 'yes'
},
listeners: {
scope:this,
initialize: function(panel, flash) {
alert(2);
},
afterrender: function(panel) {
var init = function () {
if (panel.swf.init) {
panel.swf.init(panel.getSwfId(), "letter", 0, 0);
} else {
init.defer(10, this);
}
};
init.defer(10, this);
}
}
};
win = new Ext.Window({
width:700,
height:500,
modal:true,
layout: "border",
closeAction: "hide",
title: _("Adding a new category"),
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "center",
margins: "3 0 3 3",
layout:"fit",
items: form
},
{ region:"east",
margins: "3 3 3 0",
width: 380,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
items: flash
}
],
listeners: {
scope:this,
afterrender: function(panel) {
panel.flash = panel.findByType("flash")[0].swf;
panel.form = panel.findByType("form")[0];
}
},
buttons: [ _BTN_WNDW_ADD, _BTN_WNDW_CLOSE ]
});
}
win.show(this);
this.components["create-window"] = win;
if (this.pageW && this.pageH) {
var configure = function () {
if (win.flash.setGrid) {
win.flash.setGrid( this.pageW, this.pageH );
win.flash.setBlocks( [ { id: "new_block", n:"New modules", x: "0/1", y: "0/1", w: "0/1", h: "0/1" } ] );
win.flash.editBlock( "new_block", true );
} else {
configure.defer(10, this);
}
};
configure.defer(10, this);
}
var form = win.form.getForm();
form.reset();
form.findField("edition").setValue(this.parent.edition);
form.findField("page").setValue(this.pageId);
},
cmpUpdate: function() {
var win = this.components["update-window"];
if (!win) {
var form = {
xtype: "form",
frame:false,
border:false,
labelWidth: 75,
url: this.urls.update,
bodyStyle: "padding:5px 5px",
baseParams: {},
defaults: {
anchor: "100%",
allowBlank:false
},
items: [
_FLD_HDN_ID,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_SHORTCUT,
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: "numberfield",
allowBlank:false,
allowDecimals:false,
minValue: 1,
name: "amount",
value: 1,
fieldLabel: _("Amount")
}
],
listeners: {
scope:this,
beforeaction: function(form, action) {
if (action.type == "submit") {
var swf = this.components["update-window"].findByType("flash")[0].swf;
var id = Ext.getCmp(this.components["update-window"].getId()).form.getId();
//(function () {
swf.getBlock("Inprint.flash.Proxy.setModule", id, "update_block");
//}).defer(10);
}
},
actioncomplete: function (form, action) {
if (action.type == "load") {
var swf = this.components["update-window"].findByType("flash")[0].swf;
var load = function () {
if (swf.setBlocks) {
var record = action.result.data;
swf.deleteAllBlocks();
swf.setBlocks( [ { id: "update_block", n:record.shortcut, x: record.x, y: record.y, w: record.w, h: record.h } ] );
swf.editBlock( "update_block", true );
} else {
load.defer(10, this);
}
};
load.defer(10, this);
}
if (action.type == "submit") {
this.components["update-window"].hide();
this.cmpReload();
}
}
},
keys: [ _KEY_ENTER_SUBMIT ]
};
var flash = {
xtype: "flash",
swfWidth:380,
swfHeight:360,
hideMode : 'offsets',
url : '/flash/Dispose.swf',
expressInstall: true,
flashVars: {
src: '/flash/Dispose.swf',
scale :'noscale',
autostart: 'yes',
loop: 'yes'
},
listeners: {
scope:this,
initialize: function(panel, flash) {
alert(2);
},
afterrender: function(panel) {
var init = function () {
if (panel.swf.init) {
panel.swf.init(panel.getSwfId(), "letter", 0, 0);
} else {
init.defer(10, this);
}
};
init.defer(10, this);
}
}
};
win = new Ext.Window({
width:700,
height:500,
modal:true,
layout: "border",
closeAction: "hide",
title: _("Adding a new category"),
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "center",
margins: "3 0 3 3",
layout:"fit",
items: form
},
{ region:"east",
margins: "3 3 3 0",
width: 380,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
items: flash
}
],
listeners: {
scope:this,
afterrender: function(panel) {
panel.flash = panel.findByType("flash")[0].swf;
panel.form = panel.findByType("form")[0];
}
},
buttons: [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
});
}
win.show(this);
this.components["update-window"] = win;
if (this.pageW && this.pageH) {
var configure = function () {
if (win.flash.setGrid) {
win.flash.setGrid( this.pageW, this.pageH );
win.flash.setBlocks( [ { id: "new_block", n:"New modules", x: "0/1", y: "0/1", w: "0/1", h: "0/1" } ] );
win.flash.editBlock( "new_block", true );
} else {
configure.defer(10, this);
}
};
configure.defer(10, this);
}
var form = win.form.getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: this.getValue("id")
}
});
},
cmpDelete: function() {
Ext.MessageBox.confirm(
_("Warning"),
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.plugins.rss.control.Context = function(parent, panels) {
var tree = panels.tree;
tree.on("contextmenu", function(node) {
this.selection = node;
var disabled = true;
var items = [];
//if (parent.access.editions) {
disabled = false;
//}
items.push({
icon: _ico("feed--plus"),
cls: "x-btn-text-icon",
text: _("Create"),
disabled: disabled,
ref: "../btnCreate",
scope:this,
handler: function() { this.cmpCreate(node); }
});
if (node.id != NULLID) {
items.push({
icon: _ico("feed--pencil"),
cls: "x-btn-text-icon",
text: _("Edit"),
disabled: disabled,
ref: "../btnEdit",
scope:this,
handler: function() { this.cmpUpdate(node); }
});
items.push({
icon: _ico("feed--minus"),
cls: "x-btn-text-icon",
text: _("Remove"),
disabled: disabled,
ref: "../btnRemove",
scope:this,
handler: function() { this.cmpDelete(node); }
});
}
items.push('-', {
icon: _ico("arrow-circle-double"),
cls: "x-btn-text-icon",
text: _("Reload"),
scope: this,
handler: this.cmpReload
});
new Ext.menu.Menu({ items : items }).show(node.ui.getAnchor());
}, tree);
};
<file_sep>Inprint.cmp.memberRules.Interaction = function(parent, panels) {
};
<file_sep>Inprint.plugins.rss.Interaction = function(parent, panels) {
var grid = panels.grid;
var profile = panels.profile;
profile.on("render", function() {
var el = this.getEl();
setTimeout(function() { el.mask( _("Please, select document") ); }, 10);
}, profile);
profile.panels.form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
this.getStore().reload();
AlertBox.show(
_("System event"),
_("Changes have been saved"),
'success', {timeout: 1});
}
}, grid);
grid.getSelectionModel().on("selectionchange", function(sm) {
if (sm.getCount() == 1) {
profile.cmpFill(sm.getSelected().get("id"));
}
if (sm.getCount() > 1) {
profile.getEl().mask( _("Please, select document") );
}
if (sm.getCount() === 0) {
profile.getEl().mask( _("Please, select document") );
}
});
};
<file_sep>// function changeWallpaper () {
// var mycolor = "#007aab";
// var mywallpaper = '1920x1200';
// var myWidth = 0, myHeight = 0;
// if( typeof( window.innerWidth ) == 'number' ) {
// Non-IE
// myWidth = window.innerWidth;
// myHeight = window.innerHeight;
// } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
// IE 6+ in 'standards compliant mode'
// myWidth = document.documentElement.clientWidth;
// myHeight = document.documentElement.clientHeight;
// }
// var resolution = [ [1024,768], [1152,864], [1280,720], [1280,800], [1280,960], [1365,768], [1400,1050], [1440,900], [1600,1200], [1600,900], [1680,1050], [1920,1080], [1920,1200] ];
// resolution.reverse();
// for (var c=0; c<resolution.length;c++) {
// var x = resolution[c][0];
// var y = resolution[c][1];
// if (myWidth <= x) {
// if (myHeight <= y) {
// mywallpaper = x+'x'+y;
// }
// }
// }
// document.body.style.background = mycolor +" url(/wallpapers/"+ mywallpaper +".jpg) no-repeat";
// };
// changeWallpaper();
<file_sep>Inprint.fascicle.template.composer.Context = function(parent, panels) {
var view = panels.pages.getView();
view.on("contextmenu", function( view, index, node, e) {
e.stopEvent();
var selection = panels.pages.cmpGetSelected();
var selLength = selection.length;
var disabled = true;
var disabled1 = true;
var disabled2 = true;
var items = [];
if (parent.access.manage) {
if (selLength == 1) {
disabled1 = false;
}
if (selLength > 0 && selLength < 3) {
disabled2 = false;
}
disabled = false;
}
items.push(
{
ref: "../btnCompose",
disabled:disabled2,
text:'Разметить',
icon: _ico("wand"),
cls: 'x-btn-text-icon',
scope: panels.pages,
handler: panels.pages.cmpPageCompose
}
);
items.push('-', {
icon: _ico("arrow-circle-double"),
cls: "x-btn-text-icon",
text: _("Reload"),
scope: this,
handler: this.cmpReload
});
new Ext.menu.Menu({ items : items }).showAt( e.getXY() );
}, view);
};
<file_sep>Inprint.membersBrowser.PrincipalsView = Ext.extend(Ext.DataView, {
initComponent: function() {
var store = Inprint.factory.Store.json("/principals/list/", {
autoLoad:false
});
var groupicon = _ico("folder");
var membericon = _ico("user");
var tpl = new Ext.XTemplate(
'<tpl for=".">',
'<tpl if="type == \'group\'">',
'<div class="view-item" id="id-{id}" style="background:url('+groupicon+') no-repeat;padding-left:24px;height:20px;cursor:hand;">',
'<b>{shortcut}</b>',
'</div>',
'</tpl>',
'<tpl if="type == \'member\'">',
'<div class="view-item" id="id-{id}" style="background:url('+membericon+') no-repeat;padding-left:24px;height:20px;cursor:hand;">',
'{shortcut}',
'</div>',
'</tpl>',
'</tpl>',
'<div class="x-clear"></div>'
);
Ext.apply(this, {
border:false,
store: store,
tpl: tpl,
//autoHeight:true,
autoScroll:true,
multiSelect: true,
overClass:'x-view-over',
itemSelector:'div.view-item',
emptyText: _("No chains to display")
});
Inprint.membersBrowser.PrincipalsView.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.membersBrowser.PrincipalsView.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.membersBrowser.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {
tree: new Inprint.catalog.Tree(),
view: new Inprint.membersBrowser.PrincipalsView()
};
Ext.apply(this, {
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{ title: _("Employees"),
region: "center",
margins: "3 0 3 0",
layout:"fit",
bodyStyle:"background:transparent",
items: this.panels.view
},
{ title:_("Catalog"),
region:"west",
margins: "3 0 3 3",
width: 200,
minSize: 100,
maxSize: 400,
layout:"fit",
items: this.panels.tree
}
]
});
Inprint.membersBrowser.Panel.superclass.initComponent.apply(this, arguments);
Inprint.membersBrowser.Interaction(this.panels);
},
onRender: function() {
Inprint.membersBrowser.Panel.superclass.onRender.apply(this, arguments);
},
cmpReload:function() {
}
});
Inprint.membersBrowser.Window = function(config) {
var mywindow = new Ext.Window({
title: _("Employees browser"),
layout: "fit",
width:800, height:400,
items: new Inprint.membersBrowser.Panel(config)
});
mywindow.show();
};
<file_sep>Ext.namespace("Inprint.system.settings");<file_sep>Inprint.cmp.UpdateDocument.Form = Ext.extend(Ext.FormPanel, {
initComponent: function() {
this.edition = null;
this.fascicle = null;
var xc = Inprint.factory.Combo;
Ext.apply(this, {
url: _url("/documents/update/"),
border:false,
autoScroll:true,
labelWidth: 80,
bodyStyle: "padding: 10px",
defaults: {
anchor: "100%"
},
items: [
_FLD_HDN_ID,
{
xtype: "titlefield",
value: _("Basic options")
},
{
xtype: 'textarea',
fieldLabel: _("Title"),
name: 'title',
allowBlank:false
},
{
xtype: 'textfield',
fieldLabel: _("Author"),
name: 'author'
},
{
xtype: 'numberfield',
fieldLabel: _("Size"),
name: 'size',
allowDecimals: false,
allowNegative: false
},
{
xtype: 'xdatefield',
name: 'enddate',
format:'F j, Y',
altFormats: 'c',
submitFormat:'Y-m-d',
//minValue: new Date(),
allowBlank:false,
fieldLabel: _("Delivery date")
},
{
xtype: "titlefield",
value: _("Appointment"),
style: "margin-top:10px;"
},
{
disabled: true,
xtype: "treecombo",
name: "maingroup-shortcut",
hiddenName: "maingroup",
fieldLabel: _("Department"),
emptyText: _("Department") + "...",
minListWidth: 300,
url: _url('/common/tree/workgroups/'),
baseParams: {
term: 'catalog.documents.assign:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("folder-open"),
text: _("All departments")
},
listeners: {
scope: this,
select: function(field) {
this.getForm().findField("manager").resetValue();
},
render: function(field) {
//var id = Inprint.session.options["default.workgroup"];
//var title = Inprint.session.options["default.workgroup.name"] || _("Unknown department");
//if (id && title) field.setValue(id, title);
}
}
},
// Assign
xc.getConfig("/documents/combos/managers/", {
disabled: true,
listeners: {
scope: this,
render: function(field) {
//var id = Inprint.session.member.id;
//var title = Inprint.session.member.title || _("Unknown employee");
//if (id && title) field.setValue(id, title);
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.term = "catalog.documents.assign:*";
qe.combo.getStore().baseParams.workgroup = this.getForm().findField("maingroup").getValue();
}
}
}),
{
xtype: "titlefield",
value: _("Indexation"),
style: "margin-top:10px;"
},
// Rubrication
xc.getConfig("/documents/combos/headlines/", {
disabled: false,
listeners: {
scope: this,
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.flt_edition = this.edition;
qe.combo.getStore().baseParams.flt_fascicle = this.fascicle;
}
}
}),
xc.getConfig("/documents/combos/rubrics/", {
disabled: true,
listeners: {
scope: this,
render: function(combo) {
this.getForm().findField("headline").on("select", function() {
combo.enable();
combo.reset();
combo.resetValue();
}, this);
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.flt_edition = this.edition;
qe.combo.getStore().baseParams.flt_fascicle = this.fascicle;
qe.combo.getStore().baseParams.flt_headline = this.getForm().findField("headline").getValue();
}
}
})
]
});
Inprint.cmp.UpdateDocument.Form.superclass.initComponent.apply(this, arguments);
this.getForm().url = this.url;
},
onRender: function() {
Inprint.cmp.UpdateDocument.Form.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.catalog.organization.Access = function(parent, panels) {
var tree = panels.tree;
var grid = panels.grid;
_a(["domain.departments.manage", "domain.employees.manage"], null, function(terms) {
if(terms["domain.departments.manage"]) {
parent.access.departments = true;
}
if(terms["domain.employees.manage"]) {
parent.access.employees = true;
grid.btnAdd.enable();
grid.btnAddToGroup.enable();
grid.getSelectionModel().on("selectionchange", function(sm) {
_disable( grid.btnDelete, grid.btnDeleteFromGroup );
_disable( grid.btnViewProfile, grid.btnUpdateProfile, grid.btnManageRules);
if (sm.getCount()) {
_enable( grid.btnDelete, grid.btnDeleteFromGroup );
}
if (sm.getCount() == 1) {
_enable( grid.btnViewProfile, grid.btnUpdateProfile, grid.btnManageRules);
}
});
}
});
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.namespace("Inprint.factory.actions");
Inprint.factory.actions.manager = new function () {
var items = {};
return {
set: function(name, item) {
items[name] = item;
},
get: function(name, scope, params) {
var item = items[name];
if (!item) {
return function() {
alert("Action "+name+" not found!");
}
}
if (scope) {
Ext.apply(item, { scope: scope });
}
if (params) {
Ext.apply(item, params);
}
return item;
}
}
};
Inprint.setAction = function (name, fnct) {
return Inprint.factory.actions.manager.set(name, fnct);
}
Inprint.getAction = function (name, scope, params) {
return Inprint.factory.actions.manager.get(name, scope, params);
}
<file_sep>Inprint.registry.register("calendar-issues", {
icon: "blue-folders",
text: _("Issues"),
xobject: Inprint.calendar.issues.Main
});
Inprint.registry.register("calendar-archive", {
icon: "calendar-search-result",
text: _("Archive"),
xobject: Inprint.calendar.archive.Main
});
Inprint.registry.register("calendar-templates", {
icon: "puzzle",
text: _("Templates"),
xobject: Inprint.calendar.templates.Main
});
<file_sep>Ext.ns('Ext.ux','Ext.ux.form');
Ext.ux.form.TreeCombo = Ext.extend(Ext.form.TriggerField, {
defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
triggerClass: 'x-form-tree-trigger',
initComponent : function(){
this.editable = false;
this.isExpanded = false;
if (!this.sepperator) {
this.sepperator=','
}
Ext.ux.form.TreeCombo.superclass.initComponent.call(this);
this.on('specialkey', function(f, e){
if(e.getKey() == e.ENTER){
this.onTriggerClick();
}
}, this);
},
onRender : function(ct, position){
Ext.ux.form.TreeCombo.superclass.onRender.call(this, ct, position);
this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
id: (this.hiddenId || Ext.id())}, 'before', true);
},
onTriggerClick: function() {
if (this.disabled == false) {
if (this.isExpanded) {
this.collapse();
} else {
this.expand();
}
}
},
// was called combobox was collapse
collapse: function() {
this.isExpanded=false;
this.getTree().hide();
},
// was called combobox was expand
expand: function () {
this.isExpanded=true;
this.getTree().show();
this.getTree().getEl().alignTo(this.wrap, 'tl-bl?');
},
reload: function (params) {
if (params) {
Ext.apply(this.getTree().getLoader().baseParams, params);
}
this.getTree().getRootNode().reload();
},
getName: function(){
return this.hiddenName || this.name;
},
getValue: function() {
return this.hiddenField.value;
},
setValue: function (id, v) {
if (v) {
this.value = v;
this.setRawValue(v);
this.hiddenField.value = id;
} else {
this.setRawValue(id);
}
if(this.rendered) {
this.validate();
}
return this;
},
validateBlur : function(){
return !this.treePanel || !this.treePanel.isVisible();
},
/*
* following functions are using by treePanel
*/
getTree: function() {
if (!this.treePanel) {
if (!this.minListWidth) {
this.minListWidth = Math.max(200, this.width || 200);
}
if (!this.minListHeight) {
this.minListHeight = 300;
}
this.treePanel = new Ext.tree.TreePanel({
renderTo: Ext.getBody(),
loader: new Ext.tree.TreeLoader({
url: this.url,
preloadChildren: false,
baseParams: this.baseParams
}),
root: this.root,
rootVisible: this.rootVisible,
floating: true,
autoScroll: true,
width: this.minListWidth,
height: this.minListHeight,
listeners: {
scope: this,
hide: this.onTreeHide,
show: this.onTreeShow,
click: this.onTreeNodeClick,
expandnode: this.onExpandOrCollapseNode,
collapsenode: this.onExpandOrCollapseNode,
resize: this.onTreeResize
}
});
//this.treePanel.show();
//this.treePanel.hide();
this.relayEvents(this.treePanel.loader, ['beforeload', 'load', 'loadexception']);
if(this.resizable){
this.resizer = new Ext.Resizable(this.treePanel.getEl(), {
pinned:true, handles:'se'
});
this.mon(this.resizer, 'resize', function(r, w, h){
this.treePanel.setSize(w, h);
}, this);
}
this.treePanel.on("beforeappend", function(tree, parent, node) {
if (node.attributes.icon == undefined) {
node.attributes.icon = 'folder-open';
}
node.attributes.icon = _ico(node.attributes.icon);
if (node.attributes.color) {
node.text = "<span style=\"color:#"+ node.attributes.color +"\">" + node.attributes.text + "</span>";
}
});
}
return this.treePanel;
},
onExpandOrCollapseNode: function() {
if (!this.maxHeight || this.resizable)
return; // -----------------------------> RETURN
var treeEl = this.treePanel.getTreeEl();
var heightPadding = treeEl.getHeight() - treeEl.dom.clientHeight;
var ulEl = treeEl.child('ul'); // Get the underlying tree element
var heightRequired = ulEl.getHeight() + heightPadding;
if (heightRequired > this.maxHeight)
heightRequired = this.maxHeight;
this.treePanel.setHeight(heightRequired);
},
onTreeResize: function() {
if (this.treePanel)
this.treePanel.getEl().alignTo(this.wrap, 'tl-bl?');
},
onTreeShow: function() {
Ext.getDoc().on('mousewheel', this.collapseIf, this);
Ext.getDoc().on('mousedown', this.collapseIf, this);
},
onTreeHide: function() {
Ext.getDoc().un('mousewheel', this.collapseIf, this);
Ext.getDoc().un('mousedown', this.collapseIf, this);
},
collapseIf : function(e){
if(!e.within(this.wrap) && !e.within(this.getTree().getEl())){
this.collapse();
}
},
onTreeNodeClick: function(node, e) {
if(!node.attributes.disabled) {
this.setValue(node.id, node.text);
this.fireEvent('select', this, node);
this.collapse();
}
}
});
Ext.reg('treecombo', Ext.ux.form.TreeCombo);
<file_sep>Inprint.fascicle.indexes.Access = function(parent, panels) {
parent.access.manage = true;
};
<file_sep>Inprint.advertising.downloads.Files = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.store = new Ext.data.JsonStore({
root: "data",
url: _source("requests.files.list"),
fields: [
"id", "object", "name", "description", "mime", "extension",
"cmwidth", "cmheight", "imagesize", "xunits", "yunits",
"colormodel", "colorspace", "xresolution", "yresolution", "software",
"cm_error", "dpi_error", "size_error",
"published", "size", "length",
{ name: "created", type: "date", dateFormat: "c" },
{ name: "updated", type: "date", dateFormat: "c" }
]
});
// Column model
var columns = Inprint.grid.columns.Files();
this.colModel = new Ext.grid.ColumnModel({
defaults: {
sortable: true,
menuDisabled:true
},
columns: [
this.selectionModel,
columns.published,
columns.preview,
{ id:"name", width:200, header: _("Name"), dataIndex: "name", renderer: function(v, p, r) {
return String.format('<div><h1>{0}</h1></div><div>{1}</div>', r.get("name"), r.get("software"));
} },
{ id:"color", width:50, header: _("Color"), dataIndex: "colormodel", renderer: function(v, p, r) {
var string = "{0}";
if (r.get("cm_error")) {
string = "<span style=\"color:red;\">{0}</span>";
}
return String.format(string, r.get("colormodel") );
} },
{ id:"dpi", width: 60, header: _("DPI"), dataIndex: "imagesize", renderer: function(v, p, r) {
var string = "{0}x{1}";
if (r.get("dpi_error")) {
string = "<span style=\"color:red;\">{0}x{1}</span>";
}
return String.format(string, r.get("xresolution"), r.get("yresolution") );
} },
{ id:"imagesize", width: 80, header: _("Size"), dataIndex: "imagesize", renderer: function(v, p, r) {
var string = "{0}x{1}";
if (r.get("size_error")) {
string = "<span style=\"color:red;\">{0}x{1}</span>";
}
return String.format(string, r.get("cmwidth"), r.get("cmheight") );
} },
{ id:"resolution", width:80, header: _("Resolution"), dataIndex: "imagesize" },
columns.created,
columns.updated,
]
});
this.tbar = [
{
scope:this,
disabled:true,
ref: "../btnUpload",
handler: this.cmpUpload,
cls: "x-btn-text-icon",
text: _("Upload files"),
icon: _ico("arrow-transition-270")
},
{
id: "download",
scope:this,
disabled: true,
ref: "../btnDownload",
handler: this.cmpDownload,
cls: "x-btn-text-icon",
text: _("Get archive"),
icon: _ico("arrow-transition-090")
},
{
id: "safedownload",
scope:this,
disabled: true,
ref: "../btnSafeDownload",
handler: this.cmpSafeDownload,
cls: "x-btn-text-icon",
text: _("Safe download"),
icon: _ico("arrow-transition-090")
}
];
Ext.apply(this, {
border: false,
disabled: true,
stripeRows: true,
columnLines: true,
sm: this.selectionModel
});
// Call parent (required)
Inprint.advertising.downloads.Files.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.advertising.downloads.Files.superclass.onRender.apply(this, arguments);
this.on("rowcontextmenu", function(thisGrid, rowIndex, evtObj) {
evtObj.stopEvent();
var record = thisGrid.getStore().getAt(rowIndex);
var selCount = thisGrid.getSelectionModel().getCount();
var rowCtxMenuItems = [];
//if (this.access["fdelete"] === true) {
//rowCtxMenuItems.push("-");
rowCtxMenuItems.push({
icon: _ico("document-shred"),
cls: "x-btn-text-icon",
text: _("Delete file"),
scope:this,
handler : this.cmpDelete
});
//}
thisGrid.rowCtxMenu = new Ext.menu.Menu({
items : rowCtxMenuItems
});
thisGrid.rowCtxMenu.showAt(evtObj.getXY());
}, this);
this.getSelectionModel().on("selectionchange", function(sm) {
sm.getCount() == 0 ? this.btnDownload.disable() : this.btnDownload.enable();
sm.getCount() == 0 ? this.btnSafeDownload.disable() : this.btnSafeDownload.enable();
}, this);
},
setPkey: function(id) {
this.pkey = id;
},
cmpUpload: function() {
var Uploader = new Inprint.cmp.Uploader({
config: {
pkey: this.pkey,
uploadUrl: _source("requests.files.upload")
}
});
Uploader.on("fileUploaded", function() {
Uploader.hide();
this.cmpReload();
}, this);
Uploader.show();
},
cmpDownload: function (params) {
// generate a new unique id
var frameid = Ext.id();
// create a new iframe element
var frame = document.createElement('iframe');
frame.id = frameid;
frame.name = frameid;
frame.className = 'x-hidden';
// use blank src for Internet Explorer
if (Ext.isIE) {
frame.src = Ext.SSL_SECURE_URL;
}
// append the frame to the document
document.body.appendChild(frame);
// also set the name for Internet Explorer
if (Ext.isIE) {
document.frames[frameid].name = frameid;
}
// create a new form element
var form = Ext.DomHelper.append(document.body, {
tag: "form",
method: "post",
action: _source("requests.files.download"),
target: frameid
});
if (params && params.translitEnabled) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "safemode";
hidden.value = "true";
form.appendChild(hidden);
}
Ext.each(this.getSelectionModel().getSelections(), function(record) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "file[]";
hidden.value = record.get("object") +"::"+ record.get("id");
form.appendChild(hidden);
});
document.body.appendChild(form);
form.submit();
},
cmpSafeDownload: function() {
this.cmpDownload({
translitEnabled: true
});
},
cmpDelete: function() {
Ext.MessageBox.confirm(
_("Irrevocable action!"),
_("Remove selected files?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _source("requests.files.delete"),
scope:this,
success: this.cmpReload,
params: {
"pkey": this.pkey,
"file[]": this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.cmp.memberRulesForm.Domain = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {};
this.panels.grid = new Inprint.cmp.memberRulesForm.Domain.Restrictions();
Ext.apply(this, {
border:false,
layout: "fit",
title: _("Company"),
items: this.panels.grid
});
Inprint.cmp.memberRulesForm.Domain.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.memberRulesForm.Domain.superclass.onRender.apply(this, arguments);
},
cmpGetGrid: function() {
return this.panels.grid;
},
cmpReload: function() {
this.grid.cmpReload();
}
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.sources = {
"common.tree.editions": "/common/tree/editions/",
"common.tree.fascicles": "/common/tree/fascicles/",
"common.tree.departments": "/common/tree/departments/",
"advertisers.list": "/advertisers/list/",
"advertisers.create": "/advertisers/create/",
"advertisers.read": "/advertisers/read/",
"advertisers.update": "/advertisers/update/",
"advertisers.delete": "/advertisers/delete/",
"requests.list": "/advertising/requests/list/",
"requests.summary": "/advertising/requests/summary/",
"requests.comments.list": "/advertising/requests/comments/list/",
"requests.comments.save": "/advertising/requests/comments/save/",
"requests.download": "/advertising/requests/download/",
"requests.create": "/advertising/requests/create/",
"requests.read": "/advertising/requests/read/",
"requests.update": "/advertising/requests/update/",
"requests.delete": "/advertising/requests/delete/",
"requests.status": "/advertising/requests/status/",
"requests.files.list": "/advertising/requests/files/list/",
"requests.files.upload": "/advertising/requests/files/upload/",
"requests.files.download": "/advertising/requests/files/download/",
"requests.files.delete": "/advertising/requests/files/delete/",
"calendar.archive": "/calendar/archive/",
"calendar.unarchive": "/calendar/unarchive/",
"calendar.enable": "/calendar/enable/",
"calendar.disable": "/calendar/disable/",
"calendar.copy": "/calendar/copy/",
"calendar.format": "/calendar/format/",
"issue.create": "/calendar/fascicle/create/",
"issue.read": "/calendar/fascicle/read/",
"issue.update": "/calendar/fascicle/update/",
"issue.delete": "/calendar/fascicle/remove/",
"issue.list": "/calendar/fascicle/list/",
"issue.copy": "/calendar/fascicle/copy/",
"attachment.create": "/calendar/attachment/create/",
"attachment.read": "/calendar/attachment/read/",
"attachment.update": "/calendar/attachment/update/",
"attachment.restrictions": "/calendar/attachment/restrictions/",
"attachment.delete": "/calendar/attachment/remove/",
"attachment.list": "/calendar/attachment/list/",
"attachment.copy": "/calendar/attachment/copy/",
"template.list": "/calendar/template/list/",
"template.read": "/calendar/template/read/",
"template.create": "/calendar/template/create/",
"template.update": "/calendar/template/update/",
"template.delete": "/calendar/template/remove/",
"documents.downloads.list": "/documents/downloads/list/",
"documents.downloads.download": "/documents/downloads/download/",
"":""
};
_source = function (key) {
if (!Inprint.sources[key]) {
alert("Can't find source "+ key);
return "404";
}
return _url(Inprint.sources[key]);
};
<file_sep>Inprint.cmp.PrincipalsSelector.Selection = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.store = Inprint.factory.Store.json(this.urlLoad, { autoLoad: false });
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
Ext.apply(this, {
stripeRows: true,
columnLines: true,
enableDragDrop: true,
sm: this.selectionModel,
autoExpandColumn: "description",
columns: [
this.selectionModel,
{
id:"icon",
width: 28,
dataIndex: "type",
renderer: function(v) {
var icon;
switch (v) {
case "group":
icon = _ico("folder");
break;
case "member":
icon = _ico("user");
break;
}
return "<img src=\""+ icon +"\">";
}
},
{
id:"group",
header: _("Group"),
dataIndex: "catalog_shortcut"
},
{
id:"name",
header: _("Title"),
width: 160,
sortable: true,
dataIndex: "title",
renderer: function(v, p, record) {
var text;
switch (record.data.type) {
case "group":
text = "<b>" + v +"</b>";
break;
case "member":
text = v;
break;
}
return text;
}
},
{
id:"description",
header: _("Description"),
dataIndex: "description"
}
]
});
Inprint.cmp.PrincipalsSelector.Selection.superclass.initComponent.apply(this, arguments);
this.addEvents('save');
this.addEvents('delete');
},
onRender: function() {
Inprint.cmp.PrincipalsSelector.Selection.superclass.onRender.apply(this, arguments);
}
});
<file_sep>-- Inprint Content 5.0
-- Copyright(c) 2001-2010, Softing, LLC.
-- <EMAIL>
-- http://softing.ru/license
DELETE FROM ad_advertisers;
DELETE FROM ad_modules;
DELETE FROM ad_places;
DELETE FROM ad_requests;
DELETE FROM branches;
DELETE FROM cache_access;
DELETE FROM cache_visibility;
DELETE FROM catalog;
DELETE FROM documents;
DELETE FROM editions;
DELETE FROM fascicles;
DELETE FROM fascicles_index;
DELETE FROM fascicles_map_documents;
DELETE FROM fascicles_map_holes;
DELETE FROM fascicles_pages;
DELETE FROM history;
DELETE FROM index;
DELETE FROM index_mapping;
DELETE FROM logs;
DELETE FROM map_member_to_catalog;
DELETE FROM map_member_to_rule;
DELETE FROM map_principals_to_stages;
DELETE FROM map_role_to_rule;
DELETE FROM members;
DELETE FROM migration;
DELETE FROM options;
DELETE FROM profiles;
DELETE FROM readiness;
DELETE FROM roles;
DELETE FROM sessions;
DELETE FROM stages;
DELETE FROM state;
<file_sep>Inprint.system.logs.Grid = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.sm = new Ext.grid.CheckboxSelectionModel();
this.store = Inprint.factory.Store.json("/catalog/stages/list/");
this.columns = [
this.sm
];
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true
});
Inprint.system.logs.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.system.logs.Grid.superclass.onRender.apply(this, arguments);
}
});
<file_sep>/*
* Inprint Content 4.5
* Copyright(c) 2001-2010, Softing, LLC.
* <EMAIL>
*
* http://softing.ru/license
*/
Ext.onReady(function() {
Ext.BLANK_IMAGE_URL = '/ext-3.4.0/resources/images/default/s.gif';
Ext.data.Connection.prototype._handleFailure = Ext.data.Connection.prototype.handleFailure;
Ext.data.Connection.prototype.handleFailure = function(response, e) {
var jsonData = Ext.util.JSON.decode(response.responseText);
var errorText = jsonData.error;
errorText = errorText.replace(/%br%/g, "<br/>");
Ext.Msg.show({
title:_("Communication error"),
minWidth:900,
maxWidth:900,
msg: errorText,
buttons: Ext.Msg.OK
});
Ext.data.Connection.prototype._handleFailure.call(this, response, e);
};
Passport();
});
var Passport = function ()
{
var cookie = new Ext.state.CookieProvider({
path: "/",
expires: new Date(new Date().getTime()+(1000*60*60*24*30))
});
var url_params = Ext.urlDecode(window.location.search.substring(1));
var params = {
request: url_params.request,
ajax:true
};
var items = [
// error box
{
id: 'error-box',
xtype: 'box',
autoEl: { tag:'div' },
hidden:true,
cls: 'error-box'
},
// Login and Password's boxes
{
name: 'login',
fieldLabel: _("Login"),
listeners: {
scope:this,
render: function( cmp ) {
if ( cookie.get('passport.login') ) {
cmp.setValue( cookie.get('passport.login') );
}
},
blur: function( cmp ) {
cookie.set('passport.login', cmp.getValue() );
}
}
},
{
name: 'password',
inputType:'<PASSWORD>',
fieldLabel: _("Password")
}
];
// Creating form
this.form = new Ext.FormPanel({
url:'/login/',
labelWidth: 60,
baseParams: params,
bodyStyle:'padding:15px',
defaults: {
anchor:'100%',
allowBlank:false,
xtype:'textfield'
},
items: items
});
// creating window
var win = new Ext.Window({
title : "Inprint Content 5.0",
width: 300,
height:190,
layout: 'fit',
closable:false,
items: this.form,
buttons: [{
text: _("Enter"),
scope:this,
handler: function(){
this.form.getForm().submit();
}
}],
keys: [{
key: 13,
scope:this,
fn: function(){
this.form.getForm().submit();
}
}]
});
this.form.on('beforeaction', function() {
win.body.mask(_("Loading"));
});
this.form.on('actionfailed', function() {
win.body.unmask();
});
this.form.on('actioncomplete', function(form, action) {
win.body.unmask();
var r = Ext.decode( action.response.responseText );
// Error handle
if ( r.success == 'false' ) {
var errorBox = this.form.findById('error-box');
errorBox.show();
Ext.each( r.errors , function (c) {
this.getEl().update(_(c.msg));
}, errorBox);
}
// all fine, go to main page
if ( r.success == 'true' )
{
window.location = url_params.request || '/workspace/';
}
}, this);
win.show();
};
<file_sep>CREATE SCHEMA plugins_rss;
SET search_path = plugins_rss, pg_catalog;
CREATE TABLE rss
(
id uuid NOT NULL DEFAULT public.uuid_generate_v4(),
entity uuid NOT NULL,
title character varying NOT NULL,
description character varying NOT NULL,
fulltext character varying,
sitelink character varying NOT NULL,
priority character varying NOT NULL DEFAULT 0,
published boolean NOT NULL DEFAULT false,
created timestamp(6) with time zone NOT NULL DEFAULT now(),
updated timestamp(6) with time zone NOT NULL DEFAULT now(),
CONSTRAINT rss_pkey PRIMARY KEY (id)
);
CREATE TABLE rss_feeds
(
id uuid NOT NULL DEFAULT public.uuid_generate_v4(),
url character varying NOT NULL,
title character varying NOT NULL,
description character varying NOT NULL,
published boolean NOT NULL DEFAULT false,
created timestamp(6) with time zone NOT NULL DEFAULT now(),
updated timestamp(6) with time zone NOT NULL DEFAULT now(),
CONSTRAINT rss_feeds_pkey PRIMARY KEY (id)
);
CREATE TABLE rss_feeds_mapping
(
id uuid NOT NULL DEFAULT public.uuid_generate_v4(),
feed uuid NOT NULL,
nature character varying NOT NULL,
tag uuid NOT NULL,
CONSTRAINT rss_feeds_mapping_pkey PRIMARY KEY (id),
CONSTRAINT rss_feeds_mapping_feed_fkey FOREIGN KEY (feed)
REFERENCES plugins_rss.rss_feeds (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
);<file_sep>Inprint.cmp.membersList.Window = Ext.extend(Ext.Window, {
initComponent: function() {
this.panels = {};
this.panels.grid = new Inprint.cmp.membersList.Grid();
Ext.apply(this, {
title: _("Employeers list"),
modal: true,
layout: "fit",
closeAction: "hide",
width:800, height:400,
items: this.panels.grid,
buttons:[
{
text: _("Select"),
scope:this,
handler: function() {
this.hide();
this.fireEvent('select', this.panels.grid.getValues("id"));
}
},
{
text: _("Close"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
Inprint.cmp.membersList.Window.superclass.initComponent.apply(this, arguments);
Inprint.cmp.membersList.Interaction(this.panels);
this.addEvents('select');
},
onRender: function() {
Inprint.cmp.membersList.Window.superclass.onRender.apply(this, arguments);
},
cmpLoad: function(node) {
if (!node) {
node = '00000000-0000-0000-0000-000000000000';
}
this.panels.grid.getStore().load({
params: {
node:node
}
});
}
});
<file_sep>Ext.namespace("Inprint.cmp.memberProfileForm");
<file_sep>Ext.namespace("Inprint.documents.profile");
<file_sep>Inprint.documents.Profile.Interaction = function(parent, panels) {
var oid = parent.oid;
var profile = panels.profile;
var files = panels.files;
var comments = panels.comments;
parent.on("render", function() {
parent.cmpLoad();
});
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.namespace("Inprint.factory.windows");
Inprint.factory.windows.create = function (title, width, height, item) {
var wn = new Ext.Window({
title: _(title),
layout: "fit",
width: width,
height: height,
modal:true
});
wn.add(item);
return wn;
};
Inprint.createModalWindow = function(width, height, title, form, btns) {
return new Ext.Window({
plain: true,
modal: true,
layout: "fit",
closeAction: "hide",
bodyStyle:'padding:5px 5px 5px 5px',
title: title,
width: width,
height: height,
items: form,
buttons: btns
});
};
<file_sep>./inprint.pl daemon --reload<file_sep>Inprint.fascicle.places.Access = function(parent, panels) {
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
function icon(icon) {
return "/icons/" + icon + ".png";
}
function _ico(icon) {
return "/icons/" + icon + ".png";
}
function _ico24(icon) {
return "/icons-24/" + icon + ".png";
}
function _ico32(icon) {
return "/icons-32/" + icon + ".png";
}
function _url(url) {
return url;
}
_nullId = function(uuid) {
return "00000000-0000-0000-0000-000000000000";
};
_idIsNull = function(uuid) {
return uuid == "00000000-0000-0000-0000-000000000000";
};
_get_values = function(myfield, myarray) {
var data = [];
Ext.each(myarray, function(record) {
data.push(record.data[myfield]);
});
return data;
};
// Inverse colors
function inprintColorContrast(hexcolor){
var r = parseInt(hexcolor.substr(0,2),16);
var g = parseInt(hexcolor.substr(2,2),16);
var b = parseInt(hexcolor.substr(4,2),16);
var yiq = ((r*299)+(g*587)+(b*114))/1000;
return (yiq >= 128) ? 'black' : 'white';
}
function inprintColorLuminance(hex, lum) {
// validate hex string
hex = String(hex).replace(/[^0-9a-f]/gi, '');
if (hex.length < 6) {
hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
}
lum = lum || 0;
// convert to decimal and change luminosity
var rgb = "#", c, i;
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i*2,2), 16);
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
rgb += ("00"+c).substr(c.length);
}
return rgb;
}
// Ext specifed
function _fmtDate(str, format, inputFormat) {
var dt = Date.parseDate(str, "Y-m-d h:i:s");
if (dt) {
return dt.dateFormat(format || 'M j, Y');
}
return '';
}
// Helpers
function _show() {
Ext.each(arguments, function(c) {
if (c && c.show) {
c.show();
}
});
}
function _hide() {
Ext.each(arguments, function(c) {
if (c && c.hide) {
c.hide();
}
});
}
function _enable() {
Ext.each(arguments, function(c) {
if (c && c.enable) {
c.enable();
}
});
}
function _disable() {
Ext.each(arguments, function(c) {
if (c && c.disable) {
c.disable();
}
});
}
/* Access functions */
function _a(terms, binding, accessfunction, scope) {
Ext.Ajax.request({
url: _url("/access/"),
params: {
term: terms,
binding: binding
},
scope: scope,
success: function(result) {
var data = Ext.util.JSON.decode(result.responseText);
accessfunction(data.result);
}
});
}
function _accessCheck(terms, binding, accessfunction) {
_a(terms, binding, accessfunction);
}
function _arrayAccessCheck(records, fields) {
var result = {};
for (var r=0; r<records.length;r++) {
var access = records[r].get("access");
for (var f=0; f<fields.length;f++) {
var field = fields[f];
if (access[field] && result[field] != 'disabled') {
result[field] = 'enabled';
} else {
result[field] = 'disabled';
}
}
}
return result;
}
<file_sep>Inprint.cmp.ExcahngeBrowser.TreeEditions = Ext.extend(Ext.tree.TreePanel, {
initComponent: function() {
this.loader = new Ext.tree.TreeLoader({
url: _url("/common/tree/editions/"),
baseParams:{ term: 'editions.documents.work:*' }
});
Ext.apply(this, {
title:_("Editions"),
autoScroll:true,
border:false,
rootVisible: false,
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("Editions")
}
});
Inprint.cmp.ExcahngeBrowser.TreeEditions.superclass.initComponent.apply(this, arguments);
this.on("beforeappend", function(tree, parent, node) {
node.attributes.icon = _ico(node.attributes.icon);
});
},
onRender: function() {
Inprint.cmp.ExcahngeBrowser.TreeEditions.superclass.onRender.apply(this, arguments);
this.on("beforeload", function() {
this.body.mask(_("Loading data..."));
});
this.on("load", function() {
this.body.unmask();
});
}
});
<file_sep>Inprint.cmp.adverta.Modules = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {};
this.panels.modules = new Inprint.cmp.adverta.GridModules({
parent: this.parent
});
this.panels.templates = new Inprint.cmp.adverta.GridTemplates({
parent: this.parent
});
Ext.apply(this, {
border:false,
flex:2,
margins: "0 3 0 3",
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
this.panels.modules,
this.panels.templates
]
});
Inprint.cmp.adverta.Modules.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.adverta.Modules.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.advert.modules.Context = function(parent, panels) {
};
<file_sep>"use strict";
Inprint.calendar.archive.Interaction = function(parent, panels) {
var issues = panels.issues;
var attachments = panels.attachments;
issues.store.on("beforeload", function(store, records, options) {
attachments.disable();
attachments.store.removeAll();
});
issues.on("rowclick", function(grid, rowIndex, e) {
var record = grid.store.getAt(rowIndex);
var issue = record.get("id");
var edition = record.get("edition");
_disable(issues.btnOpenPlan, issues.btnCopy, issues.btnUnarchive);
_a(["editions.fascicle.manage:*"], edition, function(access) {
if (access["editions.fascicle.manage"] === true) {
_enable(issues.btnOpenPlan, issues.btnCopy, issues.btnUnarchive);
}
});
attachments.enable();
attachments.cmpLoad({ edition: edition, issue: issue });
});
attachments.on("rowclick", function(grid, rowIndex, e) {
var record = grid.store.getAt(rowIndex);
var issue = record.get("id");
var edition = record.get("edition");
_disable(attachments.btnOpenPlan, attachments.btnCopy, attachments.btnUnArchive);
_a(["editions.attachment.manage:*"], edition, function(access) {
if (access["editions.attachment.manage"] === true) {
_enable(attachments.btnOpenPlan, attachments.btnCopy, attachments.btnUnArchive);
}
});
});
};
<file_sep>Inprint.fascicle.adverta.Requests = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.components = {};
this.urls = {
"create": _url("/fascicle/requests/create/"),
"read": _url("/fascicle/requests/read/"),
"update": _url("/fascicle/requests/update/"),
"delete": _url("/fascicle/requests/delete/")
};
this.store = Inprint.factory.Store.json("/fascicle/requests/list/");
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"searial",
header: _("#"),
width: 30,
sortable: true,
dataIndex: "serialnum"
},
{
id:"advertiser",
header: _("Advertiser"),
width: 120,
sortable: true,
dataIndex: "advertiser_shortcut"
},
{
id:"manager",
header: _("Manager"),
width: 120,
sortable: true,
dataIndex: "manager_shortcut"
},
{
id:"title",
header: _("Title"),
width: 350,
sortable: true,
dataIndex: "shortcut"
},
{
id:"position",
header: _("Place"),
width: 100,
sortable: true,
dataIndex: "place_shortcut"
},
{
id:"template",
header: _("Template"),
width: 100,
sortable: true,
dataIndex: "origin_shortcut"
},
{
id:"module",
header: _("Module"),
width: 100,
sortable: true,
dataIndex: "module_shortcut"
},
{
id:"pages",
header: _("Pages"),
width: 60,
sortable: true,
dataIndex: "pages"
},
{
id:"status",
header: _("Status"),
width: 70,
sortable: true,
dataIndex: "status"
},
{
id:"payment",
header: _("Payment"),
width: 60,
sortable: true,
dataIndex: "payment"
},
{
id:"readiness",
header: _("Readiness"),
width: 80,
sortable: true,
dataIndex: "readiness"
},
{
id:"modified",
header: _("Modified"),
width: 110,
sortable: true,
xtype: 'datecolumn',
format: "Y-m-d H:i",
dataIndex: "updated"
}
];
this.tbar = [
{
icon: _ico("plus-button"),
cls: "x-btn-text-icon",
text: _("Add"),
ref: "../btnCreate",
scope:this,
handler: this.cmpCreate
},
{
icon: _ico("pencil"),
cls: "x-btn-text-icon",
text: _("Update"),
disabled:true,
ref: "../btnUpdate",
scope:this,
handler: this.cmpUpdate
},
'-',
{
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
disabled:true,
ref: "../btnDelete",
scope:this,
handler: this.cmpDelete
}
];
Ext.apply(this, {
border: false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "title"
});
Inprint.fascicle.adverta.Requests.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.adverta.Requests.superclass.onRender.apply(this, arguments);
},
cmpCreate: function() {
var pages = this.parent.panels.pages;
var selection = pages.cmpGetSelected();
if (selection.length > 2) {
return;
}
var wndw = new Inprint.cmp.Adverta({
fascicle: this.parent.fascicle,
selection: selection
});
wndw.on("actioncomplete", function() {
this.parent.cmpReload();
}, this);
wndw.show();
},
cmpUpdate: function() {
alert("update");
},
cmpDelete: function() {
alert("delete");
}
});
<file_sep>Inprint.cmp.CreateDocument.Form = Ext.extend(Ext.FormPanel, {
initComponent: function() {
this.access = {};
var xc = Inprint.factory.Combo;
Ext.apply(this, {
url: _url("/documents/create/"),
border:false,
layout:'column',
autoScroll:true,
bodyStyle: "padding: 20px 10px 20px 10px",
defaults: {
anchor: "100%",
allowBlank:false
},
items: [
{
columnWidth:.55,
layout: 'form',
border:false,
labelWidth: 90,
items: [
{
xtype:'fieldset',
border:false,
title: _("Document description"),
autoHeight:true,
defaults: {
anchor: "95%"
},
defaultType: 'textfield',
items :[
{
fieldLabel: _("Title"),
name: 'title',
allowBlank:false
},
{
fieldLabel: _("Author"),
name: 'author'
},
{
xtype: 'numberfield',
fieldLabel: _("Size"),
name: 'size',
allowDecimals: false,
allowNegative: false
},
{
xtype: "textarea",
fieldLabel: _("Comment"),
name: 'comment'
}
]
}
]
},
{
columnWidth:.45,
layout: 'form',
border:false,
labelWidth: 80,
items: [
{
xtype:'fieldset',
border:false,
title: _("Appointment"),
defaults: {
anchor: "100%"
},
defaultType: 'textfield',
items :[
{
allowBlank:false,
xtype: "treecombo",
name: "edition-shortcut",
hiddenName: "edition",
fieldLabel: _("Edition"),
emptyText: _("Edition") + "...",
minListWidth: 300,
url: _url('/common/tree/editions/'),
baseParams: {
term: 'editions.documents.assign:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("All editions")
},
listeners: {
scope: this,
render: function(field) {
var id = Inprint.session.options["default.edition"];
var title = Inprint.session.options["default.edition.name"] || _("Unknown edition");
if (id && title) {
field.setValue(id, title);
}
},
select: function(field) {
this.getForm().findField("fascicle").reload({
edition: field.getValue()
});
}
}
},
{
disabled: true,
xtype: "treecombo",
name: "workgroup-shortcut",
hiddenName: "workgroup",
fieldLabel: _("Department"),
emptyText: _("Department") + "...",
minListWidth: 300,
url: _url('/common/tree/workgroups/'),
baseParams: {
term: 'catalog.documents.view:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("folder-open"),
text: _("All departments")
},
listeners: {
scope: this,
select: function(field) {
this.getForm().findField("manager").resetValue();
},
render: function(field) {
var id = Inprint.session.options["default.workgroup"];
var title = Inprint.session.options["default.workgroup.name"] || _("Unknown department");
if (id && title) {
field.setValue(id, title);
}
}
}
},
xc.getConfig("/documents/combos/managers/", {
disabled: true,
listeners: {
scope: this,
render: function(field) {
var id = Inprint.session.member.id;
var title = Inprint.session.member.title || _("Unknown employee");
if (id && title) {
field.setValue(id, title);
}
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.term = "catalog.documents.create:*";
qe.combo.getStore().baseParams.edition = this.getForm().findField("edition").getValue();
qe.combo.getStore().baseParams.workgroup = this.getForm().findField("workgroup").getValue();
}
}
})
]
},
{
xtype:'fieldset',
border:false,
title: _("Publication"),
defaults: {
anchor: "100%"
},
items :[
{
xtype: 'xdatefield',
name: 'enddate',
format:'F j, Y',
submitFormat:'Y-m-d',
minValue: new Date(),
allowBlank:false,
fieldLabel: _("Date")
},
{
columnWidth:.125,
xtype: "treecombo",
name: "fascicle-shortcut",
hiddenName: "fascicle",
fieldLabel: _("Fascicle"),
emptyText: _("Fascicle") + "...",
minListWidth: 300,
url: _url('/common/tree/fascicles/'),
baseParams: {
briefcase: true,
term: 'editions.documents.work:*',
edition: Inprint.session.options["default.edition"]
},
root: {
id: '00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("blue-folder-open-document-text"),
text: _("All fascicles")
},
listeners: {
scope: this,
render: function(field) {
var id = '00000000-0000-0000-0000-000000000000';
var title = _("Briefcase");
if (id && title) {
field.setValue(id, title);
}
}
}
},
xc.getConfig("/documents/combos/headlines/", {
disabled: false,
listeners: {
scope: this,
render: function(field) {
this.getForm().findField("edition").on("select", function() {
this.getForm().findField("fascicle").setValue("00000000-0000-0000-0000-000000000000", _("Briefcase"));
field.reset();
}, this);
this.getForm().findField("fascicle").on("select", function() {
field.enable();
field.reset();
}, this);
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.flt_edition = this.getForm().findField("edition").getValue();
qe.combo.getStore().baseParams.flt_fascicle = this.getForm().findField("fascicle").getValue();
}
}
}),
xc.getConfig("/documents/combos/rubrics/", {
disabled: true,
listeners: {
scope: this,
render: function(combo) {
this.getForm().findField("edition").on("select", function() {
combo.disable();
combo.reset();
}, this);
this.getForm().findField("fascicle").on("select", function() {
combo.disable();
combo.reset();
}, this);
this.getForm().findField("headline").on("select", function() {
combo.enable();
combo.reset();
combo.getStore().baseParams.flt_fascicle = this.getForm().findField("fascicle").getValue();
combo.getStore().baseParams.flt_headline = this.getForm().findField("headline").getValue();
}, this);
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
})
]
}
]
}
]
});
Inprint.cmp.CreateDocument.Form.superclass.initComponent.apply(this, arguments);
this.getForm().url = this.url;
},
onRender: function() {
Inprint.cmp.CreateDocument.Form.superclass.onRender.apply(this, arguments);
}
});
<file_sep>-- Inprint Content 5.0
-- Copyright(c) 2001-2011, Softing, LLC.
-- <EMAIL>
-- http://softing.ru/license
-- Package: RSS Plugin, Core
-- Version: 1.0
-- Install Rss Plugin
DELETE FROM plugins.menu WHERE plugin='rss';
DELETE FROM plugins.routes WHERE plugin='rss';
DELETE FROM plugins.rules WHERE plugin='rss';
DELETE FROM plugins.l18n WHERE plugin='rss';
DELETE FROM rss_feeds WHERE id='00000000-0000-0000-0000-000000000000';
-- Insert Menu items
INSERT INTO plugins.menu(plugin, menu_section, menu_id, menu_sortorder, menu_enabled)
VALUES ('rss', 'documents', 'plugin-rss', 100, true);
INSERT INTO plugins.menu(plugin, menu_section, menu_id, menu_sortorder, menu_enabled)
VALUES ('rss', 'settings', 'plugin-rss-control', 100, true);
-- Insert public Routes
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/feeds/', 'plugins-rss', 'feeds', null, true, false);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/feeds/:feed', 'plugins-rss', 'feed', null, true, false);
-- Insert manage Routes
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/list/', 'plugins-rss-manage', 'list', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/read/', 'plugins-rss-manage', 'read', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/update/', 'plugins-rss-manage', 'update', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/save/', 'plugins-rss-manage', 'save', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/filter/', 'plugins-rss-manage', 'filter', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/publish/', 'plugins-rss-manage', 'publish', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/unpublish/', 'plugins-rss-manage', 'unpublish', null, true, true);
-- Insert files manage Routes
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/list/', 'plugins-rss-files', 'list', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/upload/', 'plugins-rss-files', 'upload', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/publish/', 'plugins-rss-files', 'publish', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/unpublish/', 'plugins-rss-files', 'unpublish', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/rename/', 'plugins-rss-files', 'rename', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/description/', 'plugins-rss-files', 'description', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/files/delete/', 'plugins-rss-files', 'delete', null, true, true);
-- Insert settings Routes
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/create/', 'plugins-rss-control', 'create', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/read/', 'plugins-rss-control', 'read', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/update/', 'plugins-rss-control', 'update', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/delete/', 'plugins-rss-control', 'delete', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/list/', 'plugins-rss-control', 'list', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/tree/', 'plugins-rss-control', 'tree', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/save/', 'plugins-rss-control', 'save', null, true, true);
INSERT INTO plugins.routes(plugin, route_url, route_controller, route_action, route_name, route_enabled, route_authentication)
VALUES ('rss', '/rss/control/fill/', 'plugins-rss-control', 'fill', null, true, true);
-- Insert Rules
INSERT INTO plugins.rules(id, plugin, rule_section, rule_subsection, rule_term, rule_sortorder, rule_title, rule_icon, rule_description, rule_enabled)
VALUES ('b98fb3fd-2593-44c8-bcd8-12da48693ef7', 'rss', 'catalog', 'documents', 'rss', 150, 'Can manage rss', 'key', '', true);
<file_sep>Inprint.cmp.UpdateDocument.Interaction = function(panels) {
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.Portal = Ext.extend(Ext.ux.Portal, {
id:'inprint-portal',
initComponent: function() {
//var width = Ext.getBody().getViewSize().width - 20;
//var height = Ext.getBody().getViewSize().height - 85;
var tools = [{
id:'gear',
handler: function(){
Ext.Msg.alert('Message', 'The Settings tool was clicked.');
}
},{
id:'close',
handler: function(e, target, panel){
panel.ownerCt.remove(panel, true);
}
}];
Ext.apply(this, {
border:false,
bodyBorder: false
//items: [{
// columnWidth:.70,
// style:'padding:8px 6px 0 8px',
// items:[{
// title: _("Company news"),
// layout:'fit',
// tools: tools,
// html: "test"
// },{
// title: _("My alerts"),
// tools: tools,
// html: "test"
// }]
//},{
// columnWidth:.30,
// style:'padding:8px 8px 0 6px',
// items:[{
// title: _("Empoyees online"),
// tools: tools,
// html: "test"
// }]
//}]
});
Inprint.Portal.superclass.initComponent.apply(this, arguments);
}
});
//
//,listeners: {
// 'drop': function(e){
// Ext.Msg.alert('Portlet Dropped', e.panel.title + '<br />Column: ' +
// e.columnIndex + '<br />Position: ' + e.position);
// }
//}
<file_sep>-- Inprint Content 5.0
-- Copyright(c) 2001-2010, Softing, LLC.
-- <EMAIL>
-- http://softing.ru/license
-------------------------------------------------------------------------------------------------
-- i18n Russian - Common
-------------------------------------------------------------------------------------------------
UPDATE catalog SET title = 'Издательский дом', shortcut = 'Издательский дом', description = 'Издательский дом'
WHERE id = '00000000-0000-0000-0000-000000000000';
UPDATE editions SET title = 'Все издания', shortcut = 'Все издания', description = 'Все издания'
WHERE id = '00000000-0000-0000-0000-000000000000';
UPDATE fascicles SET shortcut = 'Портфель', description = 'Портфель'
WHERE id = '00000000-0000-0000-0000-000000000000';
UPDATE fascicles SET shortcut = 'Корзина', description = 'Корзина'
WHERE id = '99999999-9999-9999-9999-999999999999';
UPDATE documents SET fascicle_shortcut = 'Портфель'
WHERE fascicle = '00000000-0000-0000-0000-000000000000';
UPDATE documents SET fascicle_shortcut = 'Корзина'
WHERE fascicle = '99999999-9999-9999-9999-999999999999';
UPDATE branches SET title = 'Ветвь по умолчанию', shortcut = 'По умолчанию', description = 'Это ветвь по умолчанию' WHERE id = '00000000-0000-0000-0000-000000000000';
UPDATE readiness SET title = 'Готовность по умолчанию', shortcut = 'По умолчанию', description = 'Это готовность по умолчанию' WHERE id = '00000000-0000-0000-0000-000000000000';
UPDATE stages SET title = 'Ступень по умолчанию', shortcut = 'По умолчанию', description = 'Это ступень по умолчанию' WHERE id = '00000000-0000-0000-0000-000000000000';
UPDATE options SET option_value = 'Издательский дом' WHERE option_name = 'default.workgroup.name';
UPDATE options SET option_value = 'Все издания' WHERE option_name = 'default.edition.name';
-------------------------------------------------------------------------------------------------
-- i18n Russian - Rules
-------------------------------------------------------------------------------------------------
UPDATE rules SET title = 'Может входит в программу' WHERE id = '2fde426b-ed30-4376-9a7b-25278e8f104a';
UPDATE rules SET title = 'Может просматривать конфигурацию' WHERE id = '6406ad57-c889-47c5-acc6-0cd552e9cf5e';
UPDATE rules SET title = 'Может управлять отделами' WHERE id = 'e55d9548-36fe-4e51-bec2-663235b5383e';
UPDATE rules SET title = 'Может управлять сотрудниками' WHERE id = '32e0bb97-2bae-4ce8-865e-cdf0edb3fd93';
UPDATE rules SET title = 'Может управлять изданиями' WHERE id = '2a3cae11-23ea-41c3-bdb8-d3dfdc0d486a';
UPDATE rules SET title = 'Может управлять движением' WHERE id = '086993e0-56aa-441f-8eaf-437c1c5c9691';
UPDATE rules SET title = 'Может управлять готовностью' WHERE id = 'aa4e74ad-116e-4bb2-a910-899c4f288f40';
UPDATE rules SET title = 'Может управлять рубрикатором' WHERE id = '9a756e9c-243a-4f5e-b814-fe3d1162a5e9';
-- Editions Rules
UPDATE rules SET title = 'Может просматривать календарь' WHERE id = 'e6ecbbda-a3c2-49de-ab4a-df127bd467a6';
UPDATE rules SET title = 'Может просматривать шаблоны' WHERE id = '63bd8ded-a884-4b5f-95f2-2797fb3ad6bb';
UPDATE rules SET title = 'Может управлять шаблонами' WHERE id = '2f585b7b-bfa8-4a9f-a33b-74771ce0e89b';
UPDATE rules SET title = 'Может просматривать выпуск' WHERE id = '09584423-a443-4f1c-b5e2-8c1a27a932b4';
UPDATE rules SET title = 'Может управлять выпусками' WHERE id = '901b9596-fb88-412c-b89a-945d162b0992';
UPDATE rules SET title = 'Может просматривать вкладки' WHERE id = '6ae65650-6837-4fca-a948-80ed6a565e25';
UPDATE rules SET title = 'Может управлять вкладками' WHERE id = 'ed8eac8e-370d-463c-a7ee-39ed5ee04a3f';
UPDATE rules SET title = 'Может просматривать рекламу' WHERE id = '30f27d95-c935-4940-b1db-e1e381fd061f';
UPDATE rules SET title = 'Может управлять рекламой' WHERE id = '2b6a5a8a-390f-4dae-909b-fcc93c5740fd';
UPDATE rules SET title = 'Может работать с материалами' WHERE id = '133743df-52ab-4277-b320-3ede5222cb12';
UPDATE rules SET title = 'Может назначать выпуск' WHERE id = '52dc7f72-2057-43c0-831d-55e458d84f39';
-- Catalog Rules
UPDATE rules SET title = 'Может просматривать материалы' WHERE id = 'ac0a0d95-c4d3-4bd7-93c3-cc0fc230936f';
UPDATE rules SET title = 'Может создавать материалы' WHERE id = 'ee992171-d275-4d24-8def-7ff02adec408';
UPDATE rules SET title = 'Может назначать отдел' WHERE id = '6033984a-a762-4392-b086-a8d2cdac4221';
UPDATE rules SET title = 'Может удалять материалы' WHERE id = '3040f8e1-051c-4876-8e8e-0ca4910e7e45';
UPDATE rules SET title = 'Может восстанавливать материалы' WHERE id = 'beba3e8d-86e5-4e98-b3eb-368da28dba5f';
UPDATE rules SET title = 'Может редактировать профиль' WHERE id = '5b27108a-2108-4846-a0a8-3c369f873590';
UPDATE rules SET title = 'Может работать с файлами' WHERE id = 'bff78ebf-2cba-466e-9e3c-89f13a0882fc';
UPDATE rules SET title = 'Может добавлять файлы' WHERE id = 'f4ad42ed-b46b-4b4e-859f-1b69b918a64a';
UPDATE rules SET title = 'Может удалять файлы' WHERE id = 'fe9cd446-2f4b-4844-9b91-5092c0cabece';
UPDATE rules SET title = 'Может захватывать материалы' WHERE id = 'd782679e-3f0a-4499-bda6-8c2600a3e761';
UPDATE rules SET title = 'Может передавать материалы' WHERE id = 'b946bd84-93fc-4a70-b325-d23c2804b2e9';
UPDATE rules SET title = 'Может перемещать материалы' WHERE id = 'b7adafe9-2d5b-44f3-aa87-681fd48466fa';
UPDATE rules SET title = 'Может перемещать в портфель' WHERE id = '6d590a90-58a1-447f-b5ad-e3c62f80a2ef';
UPDATE rules SET title = 'Может участвовать в обсуждении' WHERE id = '6d590a90-58a1-447f-b5ad-b0582b64571a';<file_sep>Ext.namespace("Inprint.plugins.rss.control");
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.form.SpacerField = Ext.extend(Ext.BoxComponent, {
autoCreate: { tag: 'div' },
initComponent: function() {
this.style = "margin-bottom:10px;";
Ext.form.SpacerField.superclass.initComponent.apply(this);
},
onRender: function() {
Ext.form.SpacerField.superclass.onRender.apply(this, arguments);
}
});
Ext.reg('spacerfield', Ext.form.SpacerField);
<file_sep>delete from indx_rubrics;
delete from indx_headlines;
delete from fascicles_indx_rubrics;
delete from fascicles_indx_headlines;
INSERT INTO indx_headlines(id, edition, title, shortcut, description, created, updated)
VALUES ( '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '--', '--', '--', now(), now());
INSERT INTO indx_headlines(id, edition, title, shortcut, description, created, updated)
SELECT id, edition, title, shortcut, description, created, updated FROM index WHERE nature = 'headline';
INSERT INTO indx_rubrics(id, edition, headline, title, shortcut, description, created, updated)
SELECT id, edition, parent, title, shortcut, description, created, updated FROM index t1 WHERE nature = 'rubric'
AND t1.parent IN ( SELECT t2.id FROM index t2 WHERE t2.id=t1.parent );
UPDATE indx_headlines SET bydefault = true WHERE shortcut = '--';
UPDATE indx_rubrics SET bydefault = true WHERE shortcut = '--';
<file_sep>//Ext.namespace("Inprint.portal.events");
<file_sep>Inprint.catalog.readiness.Interaction = function(parent, panels) {
var grid = panels.grid;
var help = panels.help;
// Set Actions
grid.btnCreateItem.on("click", Inprint.getAction("readiness.create") .createDelegate(parent, [grid]));
grid.btnUpdateItem.on("click", Inprint.getAction("readiness.update") .createDelegate(parent, [grid]));
grid.btnDeleteItem.on("click", Inprint.getAction("readiness.delete") .createDelegate(parent, [grid]));
// Grid Readiness Events
grid.getSelectionModel().on("selectionchange", function(sm) {
_disable(grid.btnUpdateItem, grid.btnDeleteItem);
if(parent.access["domain.readiness.manage"]) {
if (sm.getCount() == 1) {
_enable(grid.btnUpdateItem, grid.btnDeleteItem);
} else if (sm.getCount() > 1) {
_enable(grid.btnDeleteItem);
}
}
});
// Set Access
_a(["domain.readiness.manage"], null, function(terms) {
parent.access = terms;
if(parent.access["domain.readiness.manage"]) {
grid.btnCreateItem.enable();
}
});
};
<file_sep>Inprint.advertising.downloads.Requests = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.access = {};
this.config = {};
this.urls = {};
this.sm = new Ext.grid.CheckboxSelectionModel();
this.store = Inprint.factory.Store.json(
_source("requests.list"),
{
remoteSort:true
});
// Column model
var columns = Inprint.grid.columns.Request();
this.colModel = new Ext.grid.ColumnModel({
defaults: {
sortable: true,
menuDisabled:true
},
columns: [
this.sm,
columns.serial,
columns.check,
columns.edition,
columns.advertiser,
columns.title,
columns.another,
columns.position,
columns.module,
columns.pages
]
});
this.tbar = [
new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: ['id', 'name'],
data : [
[ "all", _("All requests") ],
[ "check", _("To check") ],
[ "error", _("With errors") ],
[ "ready", _("Ready") ],
[ "imposed", _("Imposed") ]
]
}),
displayField:'name',
typeAhead: true,
mode: 'local',
editable:false,
forceSelection: true,
triggerAction: 'all',
emptyText: _('Select a filter...'),
listeners: {
scope:this,
select:function(combo, record, index) {
this.cmpLoad({ flt_checked: record.get("id") });
}
}
}),
//{
// scope:this,
// text: _("All requests"),
// cls: "x-btn-text-icon",
// icon: _ico("moneys"),
// handler : function() {
// this.cmpLoad({ flt_checked: "all" });
// }
//},
//{
// scope:this,
// text: _("To check"),
// cls: "x-btn-text-icon",
// icon: _ico("exclamation-octagon"),
// handler : function() {
// this.cmpLoad({ flt_checked: "check" });
// }
//},
//{
// scope:this,
// text: _("With errors"),
// cls: "x-btn-text-icon",
// icon: _ico("exclamation-red"),
// handler : function() {
// this.cmpLoad({ flt_checked: "error" });
// }
//},
//{
// scope:this,
// text: _("Ready"),
// cls: "x-btn-text-icon",
// icon: _ico("tick-circle"),
// handler : function() {
// this.cmpLoad({ flt_checked: "ready" });
// }
//},
//{
// scope:this,
// text: _("Imposed"),
// cls: "x-btn-text-icon",
// icon: _ico("printer"),
// handler : function() {
// this.cmpLoad({ flt_checked: "imposed" });
// }
//}
];
Ext.apply(this, {
border: false,
disabled: true,
stripeRows: true,
columnLines: true
});
// Call parent (required)
Inprint.advertising.downloads.Requests.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.advertising.downloads.Requests.superclass.onRender.apply(this, arguments);
this.on("rowcontextmenu", function(thisGrid, rowIndex, evtObj) {
evtObj.stopEvent();
var rowCtxMenuItems = [];
var record = thisGrid.getStore().getAt(rowIndex);
var selCount = thisGrid.getSelectionModel().getCount();
if (selCount > 0) {
rowCtxMenuItems.push({
icon: _ico("exclamation-octagon"),
cls: "x-btn-text-icon",
text: _("To check"),
scope:this,
handler: function() {
this.cmpSetStatus("check");
}
});
rowCtxMenuItems.push({
icon: _ico("exclamation-red"),
cls: "x-btn-text-icon",
text: _("With errors"),
scope:this,
handler: function() {
this.cmpSetStatus("error");
}
});
rowCtxMenuItems.push({
icon: _ico("tick-circle"),
cls: "x-btn-text-icon",
text: _("Ready"),
scope:this,
handler: function() {
this.cmpSetStatus("ready");
}
});
rowCtxMenuItems.push({
icon: _ico("printer"),
cls: "x-btn-text-icon",
text: _("Imposed"),
scope:this,
handler: function() {
this.cmpSetStatus("imposed");
}
});
if (rowCtxMenuItems.length > 0) {
rowCtxMenuItems.push("-");
}
rowCtxMenuItems.push({
icon: _ico("user-silhouette"),
cls: "x-btn-text-icon",
text: _("Is another's"),
scope:this,
handler: function() {
this.cmpSetStatus("anothers");
}
});
rowCtxMenuItems.push({
icon: _ico("user"),
cls: "x-btn-text-icon",
text: _("Isn't another's"),
scope:this,
handler: function() {
this.cmpSetStatus("notanothers");
}
});
if (rowCtxMenuItems.length > 0) {
rowCtxMenuItems.push("-");
}
rowCtxMenuItems.push({
icon: _ico("arrow-transition-090"),
cls: "x-btn-text-icon",
text: _("Download"),
scope:this,
handler: this.cmpDownload
});
rowCtxMenuItems.push({
icon: _ico("arrow-transition-090"),
cls: "x-btn-text-icon",
text: _("Safe download"),
scope:this,
handler: this.cmpSafeDownload
});
thisGrid.rowCtxMenu = new Ext.menu.Menu({
items : rowCtxMenuItems
});
thisGrid.rowCtxMenu.showAt(evtObj.getXY());
}
}, this);
},
setFascicle: function(fascicle) {
this.fascicle = fascicle;
},
cmpSetStatus: function (status) {
var selection = this.getValues("id");
Ext.Ajax.request({
url: _source("requests.status"),
scope:this,
success: this.cmpReload,
params: { id: selection, status: status }
});
},
cmpDownload: function (params) {
// generate a new unique id
var frameid = Ext.id();
// create a new iframe element
var frame = document.createElement('iframe');
frame.id = frameid;
frame.name = frameid;
frame.className = 'x-hidden';
// use blank src for Internet Explorer
if (Ext.isIE) {
frame.src = Ext.SSL_SECURE_URL;
}
// append the frame to the document
document.body.appendChild(frame);
// also set the name for Internet Explorer
if (Ext.isIE) {
document.frames[frameid].name = frameid;
}
// create a new form element
var form = Ext.DomHelper.append(document.body, {
tag: "form",
method: "post",
action: _source("requests.download"),
target: frameid
});
if (params && params.translitEnabled) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "safemode";
hidden.value = "true";
form.appendChild(hidden);
}
Ext.each(this.getSelectionModel().getSelections(), function(record) {
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "request[]";
hidden.value = record.get("id");
form.appendChild(hidden);
});
document.body.appendChild(form);
form.submit();
},
cmpSafeDownload: function() {
this.cmpDownload({
translitEnabled: true
});
}
});
<file_sep>Ext.namespace("Inprint.plugins.rss");
<file_sep>Inprint.cmp.DuplicateDocument.Grid = Ext.extend(Ext.grid.EditorGridPanel, {
initComponent: function() {
this.currentRecord = null;
var xc = Inprint.factory.Combo;
this.sm = new Ext.grid.CheckboxSelectionModel();
this.store = Inprint.factory.Store.json("/documents/common/fascicles/", {
autoLoad:true
});
this.columns = [
this.sm,
{
id:"edition",
header: _("Edition"),
width: 140,
sortable: true,
dataIndex: "edition_shortcut",
renderer: function (v, p, r) {
var icon, padding;
if (r.get("fastype") == "issue") {
icon = "blue-folder-horizontal";
}
if (r.get("fastype") == "attachment") {
icon = "folder-horizontal";
}
return String.format('<div style="background:url({0}) 0 -2px no-repeat;padding-left:20px;">{1}</div>', _ico(icon), v);
}
},
{
id:"shortcut",
header: _("Shortcut"),
width: 80,
sortable: true,
dataIndex: "shortcut"
},
{
id: "headline",
header: _("Headline"),
width: 150,
dataIndex: 'headline_shortcut',
editor: xc.getConfig("/documents/combos/headlines/", {
listeners: {
scope: this,
select: function(combo, record) {
this.currentRecord.set("headline", record.get("id"));
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.flt_edition = this.currentRecord.get("edition");
qe.combo.getStore().baseParams.flt_fascicle = this.currentRecord.get("id");
}
}
})
},
{
id: "rubric",
header: _("Rubric"),
width: 150,
dataIndex: 'rubric_shortcut',
editor: xc.getConfig("/documents/combos/rubrics/", {
disabled: true,
listeners: {
scope: this,
show: function(combo) {
if (this.currentRecord.get("headline")) {
combo.enable();
} else {
combo.disable();
}
},
select: function(combo, record) {
this.currentRecord.set("rubric", record.get("id"));
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
qe.combo.getStore().baseParams.flt_edition = this.currentRecord.get("edition");
qe.combo.getStore().baseParams.flt_fascicle = this.currentRecord.get("id");
qe.combo.getStore().baseParams.flt_headline = this.currentRecord.get("headline");
}
}
})
}
];
Ext.apply(this, {
border: false,
title: _("Fascicles"),
stripeRows: true,
columnLines: true,
clicksToEdit: 1
});
Inprint.cmp.DuplicateDocument.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.DuplicateDocument.Grid.superclass.onRender.apply(this, arguments);
this.on("beforeedit", function(e) {
this.getSelectionModel().selectRow(e.row, true);
this.currentRecord = e.record;
});
this.on("afteredit", function(e) {
this.getSelectionModel().selectRow(e.row, true);
var combo = this.getColumnModel().getCellEditor(e.column, e.row).field;
e.record.set(e.field, combo.getRawValue());
});
}
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.namespace("Inprint.factory.columns");
Inprint.factory.columns.manager = new function () {
var items = {};
return {
set: function(name, item) {
items[name] = item;
},
get: function(name) {
var item = items[name];
if (!item) {
alert("Column "+name+" not found!");
return false;
}
/* *** */
item.setHeader = function(header) {
this.header = header;
return this;
};
item.setIndex = function(dataIndex) {
this.dataIndex = dataIndex;
return this;
};
item.setWidth = function(width) {
this.width = width;
return this;
};
item.setTemplate = function(template) {
this.template = new Ext.XTemplate(template);
return this;
};
item.setRenderer = function(renderer) {
this.renderer = renderer;
return this;
};
return item;
}
}
};
Inprint.setColumn = function (name, fnct) {
return Inprint.factory.columns.manager.set(name, fnct);
}
Inprint.getColumn = function (name) {
return Inprint.factory.columns.manager.get(name);
}
/* *** */
Inprint.setColumn("shortcut", {
header: _("Shortcut"),
dataIndex: 'shortcut',
width: 180
});
Inprint.setColumn("description", {
header: _("Description"),
dataIndex: 'description',
width: 180
});
Inprint.setColumn("created", {
header: _("Created"),
dataIndex: 'created',
width: 120,
tpl: new Ext.XTemplate('{created:this.formatDate}', {
formatDate: function(date) {
return _fmtDate(date, 'F j, H:i');
}
})
});
Inprint.setColumn("updated", {
header: _("Updated"),
dataIndex: 'updated',
width: 120,
tpl: new Ext.XTemplate('{created:this.formatDate}', {
formatDate: function(date) {
return _fmtDate(date, 'F j, H:i');
}
})
});
/* *** */
Inprint.setColumn("edition", {
header: _("Edition"),
dataIndex: 'edition_shortcut',
width: 180
});
<file_sep>DROP VIEW cache_rules;
DROP VIEW view_members;
DROP VIEW view_rules;
DROP VIEW view_rules_old;
CREATE VIEW "public"."view_rules" AS
SELECT rules.id, 'system' AS plugin, rules.term, rules.section, rules.subsection,
rules.section || '.' || rules.subsection || '.' || rules.term AS termkey,
rules.icon, rules.title, rules.description, rules.sortorder, true AS enabled
FROM rules
UNION
SELECT rules.id, rules.plugin, rules.rule_term AS term, rules.rule_section AS section, rules.rule_subsection AS subsection,
rules.rule_section || '.' || rules.rule_subsection || '.' || rules.rule_term AS termkey,
rules.rule_icon AS icon, rules.rule_title AS title, rules.rule_description AS description, rules.rule_sortorder AS sortorder, rules.rule_enabled AS enabled
FROM plugins.rules;
<file_sep>Inprint.fascicle.modules.Context = function(parent, panels) {
};
<file_sep>Inprint.plugins.rss.control.Interaction = function(parent, panels) {
var tree = panels.tree;
var grid = panels.grid;
var help = panels.help;
var managed = false;
// Tree
tree.getSelectionModel().on("selectionchange", function(sm, node) {
if (node && node.id) {
grid.enable();
grid.cmpFill(node.id);
} else {
grid.disable();
}
});
};
<file_sep>Ext.namespace("Inprint.cmp");
<file_sep>//// Inprint Content 5.0
//// Copyright(c) 2001-2011, Softing, LLC.
//// <EMAIL>
//// http://softing.ru/license
//
//Inprint.factory.RowEditor = function(settings) {
//
// var editor = new Ext.ux.grid.RowEditor({
// clicksToEdit: 2,
// saveText: _("Update"),
// cancelText: _("Cancel")
// });
//
// editor.cmpRecord = Ext.data.Record.create(settings.record);
//
// editor.on("beforeedit", function(roweditor, number) {
// if ( roweditor.grid.getSelectionModel().getSelected().get("id")) {
// this.saveText = _("Update");
// } else {
// this.saveText = _("Create");
// }
// if ( roweditor.btns ) {
// roweditor.btns.items.first().setText(this.saveText);
// }
// });
//
// editor.on("canceledit", function(roweditor, forced) {
// if (!roweditor.record.data.id) {
// roweditor.grid.getStore().remove(roweditor.record);
// }
// });
//
// editor.on("afteredit", function(roweditor, obj, record, number) {
// Ext.Ajax.request({
// method:"post",
// params: record.data,
// url: record.phantom ? settings.create : settings.update,
// scope:editor,
// success: function() {
// this.fireEvent("success");
// }
// });
// });
//
// return editor;
//
//};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.Workspace = function() {
var Portal = new Inprint.Portal();
var Menu = new Inprint.Menu();
var Taskbar = new Inprint.Taskbar();
var Panel = new Ext.Panel({
layout: 'card',
border: false,
bodyBorder:false,
bodyStyle: 'padding:2px;background:transparent;',
items: [],
tbar: Menu,
bbar: Taskbar
})
var Viewport = new Ext.Viewport({
layout: 'fit',
items: Panel
});
return {
getViewport: function(){
return Viewport;
},
getMenu: function(){
return Menu;
},
getPanel: function(){
return Panel;
},
getTaskbar: function(){
return Taskbar;
}
};
};
<file_sep>//// Inprint Content 5.0
//// Copyright(c) 2001-2011, Softing, LLC.
//// <EMAIL>
//// http://softing.ru/license
//
//Inprint.factory.GridChoser = Ext.extend(Ext.grid.GridPanel, {
//
// storeId: null,
// params: {},
// urls: { load: null, fill: null, save: null },
//
// initComponent: function() {
//
// this.components = {};
//
// this.store = Inprint.factory.Store.json(this.storeId);
// this.selectionModel = new Ext.grid.CheckboxSelectionModel();
//
// Ext.apply(this, {
// border:false,
// stripeRows: true,
// columnLines: true,
// sm: this.selectionModel,
// autoExpandColumn: "title",
// columns: [
// this.selectionModel,
// {
// id:"title",
// header: _("Items"),
// sortable: false,
// dataIndex: "title"
// }
// ],
// tbar: [
// {
// icon: _ico("plus-circle.png"),
// cls: "x-btn-text-icon",
// text: _("Save"),
// disabled:true,
// ref: "../btnSave",
// scope:this,
// handler: this.cmpSave
// }
// ]
// });
//
// Inprint.factory.GridChoser.superclass.initComponent.apply(this, arguments);
//
// },
//
// onRender: function() {
// Inprint.factory.GridChoser.superclass.onRender.apply(this, arguments);
// this.store.load();
// },
//
// cmpFill: function() {
//
// this.getSelectionModel().clearSelections();
// Ext.Ajax.request({
// url: this.urls.fill,
// scope: this,
// params: this.params,
// success: function(response) {
//
// var data = Ext.util.JSON.decode(response.responseText);
//
// var ds = this.getStore();
// var sm = this.getSelectionModel();
//
// var cache = {};
// for (var i = 0; i < data.length; i++) {
// cache[ data[i] ] = true;
// }
//
// for (i = 0; i < ds.getCount(); i++) {
// var record = ds.getAt(i);
// if (cache[ record.data.id ]) {
// sm.selectRow(i, true);
// }
// }
//
// }
// });
// },
//
// cmpSave: function() {
//
// var data = this.getValues("id");
// Ext.Ajax.request({
// scope:this,
// url: this.urls.save,
// params: Ext.apply(this.params, {data:data}),
// success: function(response, options) {
// alert("success");
// }
// });
// }
//});
//
////function(parent) {
////
//// var win = false;
//// var grid = false;
////
//// var msg1 = 'Загружаются данные...';
//// var msg2 = 'Операция не удалась';
//// var msg3 = 'Статус';
//// var msgSave = 'Данные успешно сохранены';
////
//// var id1, id2;
////
//// return {
////
//// show: function(config) {
////
//// this.config = config;
//// edition = Inprint.session.edition;
////
//// if (!win) {
////
//// this.toolbar = false;
////
//// win = new Ext.Window({
//// width: 500,
//// height: 400,
//// tbar: this.toolbar,
//// items: this.createGrid(),
//// layout: 'fit',
//// closeAction:'close',
//// buttons: [
//// {
//// text: Inprint.str.save,
//// scope: this,
//// handler: this.submit
//// },
//// {
//// text: Inprint.str.cancel,
//// scope: this,
//// handler: function() {
//// win.hide()
//// }
//// }
//// ],
//// keys: [
//// {
//// key: 27,
//// scope: this,
//// fn: function() {
//// win.hide()
//// }
//// }
//// ]
//// });
//// }
////
//// win.show();
////
//// if (config.name)
//// {
//// win.setTitle('<' + config.name + '>');
//// }
////
//// if (config.fillUrl) {
//// this.fill();
//// }
////
//// if (Ext.getCmp(id1))
//// {
//// Inprint.SetComboValue(Ext.getCmp(id1), edition || Inprint.session.edition);
//// }
////
//// },
////
//// createGrid: function()
//// {
////
//// var sm = new Ext.grid.CheckboxSelectionModel({
//// singleSelect: false
//// });
////
//// var RadioBox = new Ext.grid.RadioColumn({
//// header: 'Основная',
//// stype:'row',
//// inputValue: 1,
//// dataIndex: 'ismain',
//// width: 75,
//// align: 'center',
//// sortable: true
//// });
////
//// grid = new Ext.grid.GridPanel({
//// store: new Ext.data.Store({
//// baseParams: { edition: Inprint.session.edition }
//// ,proxy: new Ext.data.HttpProxy({ url: this.config.loadUrl })
//// ,reader: new Ext.data.JsonReader({ id: 'uuid', fields: [ 'uuid', 'ismain', 'title', 'description' ] })
//// ,autoLoad:true
//// ,listeners: {
//// scope:this,
//// load: function()
//// {
//// if (this.config.fillUrl) {
//// this.fill();
//// }
//// }
//// }
//// })
//// ,sm: sm
//// ,columns: [
//// sm,
//// RadioBox,
//// {
//// header: Inprint.str.department,
//// width: 150,
//// sortable: false,
//// dataIndex: 'title'
//// },
//// {
//// header: Inprint.str.description,
//// width: 200,
//// sortable: false,
//// dataIndex: 'description'
//// }
//// ],
//// plugins: RadioBox,
//// autoExpandColumn:2,
//// frame:false
//// });
////
//// return grid;
//// },
////
//
////
//// ajaxFail: function() {
//// Ext.MessageBox.alert(this.msg3, this.msg2);
//// }
////
//// }
////}
<file_sep>Inprint.cmp.Uploader = Ext.extend(Ext.Window, {
initComponent: function() {
this.panels = {};
this.panels.flash = new Inprint.cmp.uploader.Flash({
config: this.config
});
this.panels.html = new Inprint.cmp.uploader.Html({
config: this.config
});
Ext.apply(this, {
title: _("Upload document"),
modal: true,
layout: "fit",
closeAction: "hide",
width:520, height:280,
items: {
xtype: 'tabpanel',
activeTab: 0,
border: false,
items: [
this.panels.flash,
this.panels.html
]
}
});
Inprint.cmp.Uploader.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.Uploader.superclass.onRender.apply(this, arguments);
Inprint.cmp.uploader.Interaction(this, this.panels);
this.relayEvents(this.panels.flash, ['fileUploaded']);
this.relayEvents(this.panels.html, ['fileUploaded']);
}
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
/*
Фабрика DataStore, привязанна к JsonStore
*/
Ext.namespace("Inprint.factory.store");
Inprint.factory.JsonStore = function () {
return {
xtype: "jsonstore",
fields: [],
root: 'data',
idProperty: 'id',
autoDestroy: true,
addField: function(field) {
this.fields.push(field);
return this;
},
setAutoLoad: function(autoLoad) {
this.autoLoad = autoLoad;
return this;
},
setUrl: function(url) {
this.url = url;
return this;
},
setSource: function(source) {
this.url = _source( source );
return this;
},
setRoot: function(root) {
this.root = root;
return this;
},
setId: function(id) {
this.idProperty = id;
return this;
},
setParams: function(params) {
this.baseParams = params;
return this;
}
}
};
<file_sep>#/bin/sh
dropdb -U inprint inprint-5.0-test
createdb -U inprint -O inprint -E utf8 inprint-5.0-test
psql -U inprint inprint-5.0-test < inprint-dev-schema.sql
psql -U inprint inprint-5.0-test < inprint-dev-data-10-common.sql
psql -U inprint inprint-5.0-test < inprint-dev-data-20-advert.sql
psql -U inprint inprint-5.0-test < inprint-dev-data-30-fascicles.sql
psql -U inprint inprint-5.0-test < inprint-dev-data-50-demo.sql<file_sep>
INSERT
INTO template(id, edition, shortcut, description, deleted, created, updated)
VALUES ('00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', 'Default', 'Default template', false, now(), now());
<file_sep>Ext.namespace("Inprint.fascicle");
Ext.namespace("Inprint.fascicle.plan");
<file_sep>Inprint.setAction("readiness.create", function(grid) {
var url = _url("/catalog/readiness/create/");
var form = new Ext.FormPanel({
url: url,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_SHORTCUT,
_FLD_DESCRIPTION,
_FLD_COLOR,
_FLD_PERCENT
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE,_BTN_CLOSE ]
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
grid.cmpReload();
}
});
var win = Inprint.factory.windows.create(
"Create readiness", 400, 280, form
).show();
});
<file_sep>Inprint.catalog.readiness.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {
grid: new Inprint.catalog.readiness.Grid(),
help: new Inprint.panels.Help({ hid: this.xtype })
};
Ext.apply(this, {
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
layout:"fit",
region: "center",
margins: "3 0 3 3",
items: this.panels.grid
},
{
layout:"fit",
region:"east",
margins: "3 3 3 0",
width: 400,
minSize: 200,
maxSize: 600,
collapseMode: 'mini',
items: this.panels.help
}
]
});
Inprint.catalog.readiness.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.catalog.readiness.Panel.superclass.onRender.apply(this, arguments);
Inprint.catalog.readiness.Interaction(this, this.panels);
},
//getRow: function() {
// return this.panels.grid.getSelectionModel().getSelected().data;
//},
cmpReload:function() {
this.panels.grid.cmpReload();
}
});
Inprint.registry.register("settings-readiness", {
icon: "category",
text: _("Readiness"),
xobject: Inprint.catalog.readiness.Panel
});
<file_sep>Ext.namespace("Inprint.documents.editor.versions");
<file_sep>Inprint.panels.Stub = Ext.extend(Ext.Panel, {
initComponent: function() {
Ext.apply(this, {
});
// Call parent (required)
Inprint.panels.Stub.superclass.initComponent.apply(this, arguments);
},
// Override other inherited methods
onRender: function() {
// Call parent (required)
Inprint.panels.Stub.superclass.onRender.apply(this, arguments);
}
});<file_sep>Inprint.cmp.CreateDocument = Ext.extend(Ext.Window, {
initComponent: function() {
this.addEvents('complete');
this.form = new Inprint.cmp.CreateDocument.Form();
Ext.apply(this, {
modal:true,
layout: "fit",
items: this.form,
width:700, height:380,
title: _("Create a new document"),
buttons:[
{
scope:this,
disabled:true,
text: _("Create"),
handler: function() {
this.form.getForm().submit();
}
},
{
text: _("Cancel"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
this.form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
this.fireEvent("complete", this, this.form);
this.hide();
}
}, this);
Inprint.cmp.CreateDocument.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.CreateDocument.superclass.onRender.apply(this, arguments);
Inprint.cmp.CreateDocument.Access(this, this.form);
}
});
Inprint.registry.register("documents-create", {
modal: false,
icon: "plus-button",
text: _("Create document"),
menutext: _("Create"),
handler: function() {
new Inprint.cmp.CreateDocument().show();
}
});
<file_sep>Inprint.catalog.editions.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.access = {};
this.panels = {};
this.panels.tree = new Inprint.panel.tree.Editions({
baseParams: {
options: "showRoot"
}
});
this.panels.grid = new Inprint.catalog.editions.Grid();
this.panels.help = new Inprint.panels.Help({ hid: this.xtype });
Ext.apply(this, {
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
region: "center",
layout:"fit",
margins: "3 0 3 0",
items: this.panels.grid
},
{
region:"west",
margins: "3 0 3 3",
width: 200,
minSize: 200,
maxSize: 600,
layout:"fit",
items: this.panels.tree
},
{
region:"east",
margins: "3 3 3 0",
width: 400,
minSize: 200,
maxSize: 600,
collapseMode: 'mini',
layout:"fit",
items: this.panels.help
}
]
});
Inprint.catalog.editions.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.catalog.editions.Panel.superclass.onRender.apply(this, arguments);
Inprint.catalog.editions.Interaction(this, this.panels);
},
cmpReload:function() {
this.panels.grid.cmpReload();
}
});
Inprint.registry.register("settings-editions", {
icon: "blue-folders",
text: _("Editions"),
xobject: Inprint.catalog.editions.Panel
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.grid.columns.Files = function() {
return {
published: {
id:"published",
width: 32,
dataIndex: "published",
sortable: false,
renderer: function(v) {
var image = '';
if (v==1) { image = '<img src="'+ _ico("light-bulb") +'"/>'; }
return image;
}
},
preview: {
id:"preview",
header:_("Preview"),
width: 100,
dataIndex: "id",
sortable: false,
scope: this,
renderer: function(v, p, record) {
if(record.get("name").match(/^.+\.(jpg|jpeg|png|gif|tiff|png)$/i)) {
return String.format(
"<a target=\"_blank\" href=\"/files/preview/{0}\"><img src=\"/files/preview/{0}x80\" style=\"border:1px solid silver;\"/></a>",
v);
}
if(record.get("name").match(/^.+\.(rtf|txt|doc|docx|odt)$/i)) {
var file = record.get("id");
var filename = record.get("name");
var document = record.get("document");
return String.format(
"<a href=\"/?aid=document-editor&oid={0}&pid={1}&text={2}\" "+
"onClick=\"Inprint.ObjectResolver.resolve({'aid':'document-editor','oid':'{0}','pid':'{1}','description':'{2}'});return false;\">"+
"<img src=\"/files/preview/{3}x80\" style=\"border:1px solid silver;\"/></a></a>",
file, document, escape(filename), v
);
}
return String.format("<img src=\"/files/preview/{0}x80\" style=\"border:1px solid silver;\"/></a>", v);
}
},
name: {
id:'name',
header: _("File"),
dataIndex:'name',
width:250,
renderer: function(value, meta, record){
var text = String.format("<h2>{0}</h2>", value);
if (record.get("description")) {
text += String.format("<div><i>{0}</i></div>", record.get("description"));
}
text += String.format("<div style=\"padding:5px 0px;\"><a href=\"/files/download/{0}?original=true\">{1}</a></div>", record.get("id"), _("Original file"));
return text;
}
},
size: {
id: "size",
dataIndex:'size',
header: _("Size"),
width: 70,
renderer: Ext.util.Format.fileSize
},
length: {
id: "length",
dataIndex:'length',
header: _("Characters"),
width: 50
},
created: {
id: "created",
dataIndex: "created",
header: _("Created"),
width: 100,
xtype: 'datecolumn',
format: 'M d H:i'
},
updated: {
id: "updated",
dataIndex: "updated",
header: _("Updated"),
width: 100,
xtype: 'datecolumn',
format: 'M d H:i'
}
};
};
<file_sep>Ext.namespace("Inprint.cmp.memberRulesForm");
<file_sep>Inprint.cmp.Composer = Ext.extend(Ext.Window, {
initComponent: function() {
if (!this.urls) {
this.urls = {
"flashInit": _url("/fascicle/composer/initialize/"),
"flashSave": _url("/fascicle/composer/save/"),
"templatesList": "/fascicle/composer/templates/",
"modulesList": "/fascicle/composer/modules/",
"modulesCreate": _url("/fascicle/modules/create/"),
"modulesDelete": _url("/fascicle/modules/delete/")
};
}
this.panels = {};
this.selLength = this.selection.length;
this.panels.modules = new Inprint.cmp.composer.Modules({
parent: this
});
this.panels.templates = new Inprint.cmp.composer.Templates({
parent: this
});
this.panels.flash = new Inprint.cmp.composer.Flash({
parent: this
});
Ext.apply(this, {
border:false,
modal:true,
layout: "border",
closeAction: "hide",
title: _("Разметка полос"),
width: 430 + (this.selLength*260),
height:600,
defaults: {
collapsible: false,
split: true
},
items: [
{
border:false,
region: "center",
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
this.panels.modules,
this.panels.templates
]
},
this.panels.flash
],
buttons: [
{
text: _("Save"),
scope:this,
handler: this.cmpSave
},
{
text: _("Close"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
Inprint.cmp.Composer.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.Composer.superclass.onRender.apply(this, arguments);
Inprint.cmp.composer.Interaction(this, this.panels);
},
setUrls: function (urls) {
this.urls = urls;
},
cmpSave: function() {
this.panels.flash.cmpSave();
}
});
<file_sep>Inprint.calendar.templates.Interaction = function(parent, panels) {
var templates = panels.templates;
templates.on("afterrender", function() {
_a(["editions.template.manage:*"], null, function(access) {
if (access["editions.template.manage"] === true) {
_enable(templates.btnCreate);
}
});
});
templates.on("rowclick", function(grid, rowIndex, e) {
var record = grid.store.getAt(rowIndex);
var issue = record.get("id");
var edition = record.get("edition");
_disable(templates.btnCreate, templates.btnUpdate, templates.btnDelete,
templates.btnOpenPlan, templates.btnOpenComposer);
_a(["editions.template.manage:*"], edition, function(access) {
if (access["editions.template.manage"] === true) {
_enable(templates.btnCreate, templates.btnUpdate, templates.btnDelete,
templates.btnOpenPlan, templates.btnOpenComposer);
}
});
});
};
<file_sep>Inprint.advert.index.Modules = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.params = {};
this.components = {};
this.urls = {
"list": "/advertising/index/modules/",
"save": _url("/advertising/index/save/")
};
this.store = Inprint.factory.Store.json(this.urls.list);
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"page_shortcut",
header: _("Page"),
width: 150,
sortable: true,
dataIndex: "page_title"
},
{
id:"title",
header: _("Title"),
width: 150,
sortable: true,
dataIndex: "title"
},
{
id:"shortcut",
header: _("Shortcut"),
width: 150,
sortable: true,
dataIndex: "shortcut"
},
{
id:"description",
header: _("Description"),
sortable: true,
dataIndex: "description"
},
{
id:"amount",
header: _("Amount"),
sortable: true,
dataIndex: "amount"
},
{
id:"area",
header: _("Area"),
sortable: true,
dataIndex: "area"
},
{
id:"x",
header: _("X"),
sortable: true,
dataIndex: "x"
},
{
id:"y",
header: _("Y"),
sortable: true,
dataIndex: "y"
},
{
id:"w",
header: _("W"),
sortable: true,
dataIndex: "w"
},
{
id:"h",
header: _("H"),
sortable: true,
dataIndex: "h"
}
];
this.tbar = [
{
scope:this,
disabled:true,
text: _("Save"),
ref: "../btnSave",
cls: "x-btn-text-icon",
icon: _ico("disk-black"),
handler: this.cmpSave
}
];
Ext.apply(this, {
border: false,
disabled:true,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "description"
});
Inprint.advert.index.Modules.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.advert.index.Modules.superclass.onRender.apply(this, arguments);
this.getStore().on("load", function() {
var sm = this.getSelectionModel();
var ds = this.store;
sm.clearSelections();
for (i = 0; i < ds.getCount(); i++) {
var record = ds.getAt(i);
if ( record.data.selected ) {
sm.selectRow(i, true);
}
}
}, this);
},
cmpSave: function() {
Ext.MessageBox.confirm(
_("Warning"),
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls.save,
scope:this,
success: this.cmpReload,
params: {
edition: this.parent.edition,
place: this.place,
entity: this.getValues("id"),
type: "module"
}
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.fascicle.modules.Access = function(parent, panels) {
};
<file_sep>Inprint.fascicle.indexes.TreeHeadlines = Ext.extend(Ext.tree.TreePanel, {
initComponent: function() {
this.components = {};
this.urls = {
"tree": _url("/fascicle/headlines/tree/"),
"create": _url("/fascicle/headlines/create/"),
"read": _url("/fascicle/headlines/read/"),
"update": _url("/fascicle/headlines/update/"),
"delete": _url("/fascicle/headlines/delete/")
};
var treeLoader = new Ext.tree.TreeLoader({
dataUrl: this.urls.tree,
baseParams: {
fascicle: this.parent.fascicle
}
});
Ext.apply(this, {
title:_("Headlines"),
autoScroll:true,
loader: treeLoader,
border:false,
root: {
id: this.parent.fascicle,
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("blue-folder"),
text: _("Fascicle"),
type: "fascicle"
}
});
Inprint.fascicle.indexes.TreeHeadlines.superclass.initComponent.apply(this, arguments);
this.on("beforeappend", function(tree, parent, node) {
node.attributes.icon = _ico(node.attributes.icon);
});
},
onRender: function() {
Inprint.fascicle.indexes.TreeHeadlines.superclass.onRender.apply(this, arguments);
this.getLoader().on("beforeload", function() {
this.body.mask(_("Loading"));
}, this);
this.getLoader().on("load", function() { this.body.unmask(); }, this);
},
cmpCreate: function(node) {
var win = this.components["add-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.create,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_FASCICLE,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_ADD,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Adding a new headline"),
layout: "fit",
closeAction: "hide",
width:400, height:260,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
if (node.parentNode) {
node.parentNode.reload();
} else {
node.reload();
}
}
}, this);
}
var form = win.items.first().getForm();
form.reset();
form.findField("fascicle").setValue(this.parent.fascicle);
win.show(this);
this.components["add-window"] = win;
},
cmpUpdate: function(node) {
var win = this.components["edit-window"];
if (!win) {
var form = new Ext.FormPanel({
url: this.urls.update,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_ID,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE,_BTN_CLOSE ]
});
win = new Ext.Window({
title: _("Edit headline"),
layout: "fit",
closeAction: "hide",
width:400, height:260,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
if (node.parentNode) {
node.parentNode.reload();
}
else if (node.reload) {
node.reload();
}
}
}, this);
}
win.show(this);
win.body.mask(_("Loading..."));
this.components["edit-window"] = win;
var form = win.items.first().getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: node.id
},
success: function(form, action) {
win.body.unmask();
form.findField("id").setValue(action.result.data.id);
}
});
},
cmpDelete: function(node) {
var title = _("Group removal") +" <"+ node.attributes.title +">";
Ext.MessageBox.confirm(
title,
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: function() {
node.parentNode.reload();
},
params: { id: node.attributes.id }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.calendar.forms.FormatForm = Ext.extend( Ext.form.FormPanel,
{
initComponent: function()
{
this.url = _source("calendar.format");
this.items = [
_FLD_HDN_ID,
Inprint.factory.Combo.create(
"/calendar/combos/templates/",
{
allowBlank:false,
listeners: {
scope: this,
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
}
),
{
xtype: "checkbox",
fieldLabel: _("Confirmation"),
boxLabel: _("I understand the risk"),
name: "confirmation"
}
];
Ext.apply(this, {
border:false,
baseCls: "x-plain",
bodyStyle: "padding:10px",
defaults: { anchor: "100%" }
});
Inprint.calendar.forms.FormatForm.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.calendar.forms.FormatForm.superclass.onRender.apply(this, arguments);
this.getForm().url = this.url;
},
setId: function(id) {
this.cmpSetValue("id", id);
}
});
<file_sep>DROP TABLE IF EXISTS rss;
DROP TABLE IF EXISTS rss_feeds;
DROP TABLE IF EXISTS rss_feeds_mapping;
DROP TABLE IF EXISTS rss_feeds_options;
DROP TABLE IF EXISTS map_role_to_rule;
DROP TABLE IF EXISTS roles;
DROP TABLE IF EXISTS migration;
DROP TABLE IF EXISTS editions_options;
DROP TABLE IF EXISTS cache_versions;
DROP TABLE IF EXISTS ad_requests;
DROP TABLE IF EXISTS fascicles_requests_files;
ALTER TABLE fascicles ADD COLUMN status character varying NOT NULL DEFAULT 'undefined';
UPDATE fascicles SET status='archive' WHERE archived = true;
UPDATE fascicles SET status='work' WHERE archived = false;
CREATE TABLE "public"."template" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"shortcut" varchar NOT NULL,
"description" varchar,
"deleted" boolean NOT NULL DEFAULT false,
"created" timestamptz(6) DEFAULT now() NOT NULL,
"updated" timestamptz(6) DEFAULT now() NOT NULL,
CONSTRAINT "template_pkey" PRIMARY KEY ("id"),
CONSTRAINT "template_edition_fkey" FOREIGN KEY ("edition") REFERENCES "public"."editions" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE TABLE "public"."template_page" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"template" uuid NOT NULL,
"origin" uuid NOT NULL,
"headline" uuid,
"seqnum" int4,
"width" varchar[],
"height" varchar[],
"created" timestamptz(6) DEFAULT now(),
"updated" timestamptz(6) DEFAULT now(),
CONSTRAINT "template_page_pkey" PRIMARY KEY ("id"),
CONSTRAINT "template_page_template_fkey" FOREIGN KEY ("template") REFERENCES "public"."template" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "template_page_origin_fkey" FOREIGN KEY ("origin") REFERENCES "public"."ad_pages" ("id") ON DELETE RESTRICT ON UPDATE NO ACTION
);
CREATE TABLE "public"."template_module" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"template" uuid NOT NULL,
"place" uuid NOT NULL,
"origin" uuid NOT NULL,
"title" varchar NOT NULL,
"description" varchar,
"amount" int4 DEFAULT 1 NOT NULL,
"w" varchar,
"h" varchar,
"area" float8 DEFAULT 0 NOT NULL,
"created" timestamptz(6) DEFAULT now(),
"updated" timestamptz(6) DEFAULT now(),
"width" float4 DEFAULT 0 NOT NULL,
"height" float4 DEFAULT 0 NOT NULL,
"fwidth" float4 DEFAULT 0 NOT NULL,
"fheight" float4 DEFAULT 0 NOT NULL,
CONSTRAINT "template_module_pkey" PRIMARY KEY ("id"),
CONSTRAINT "template_module_template_fkey" FOREIGN KEY ("template") REFERENCES "public"."template" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "template_module_origin_fkey" FOREIGN KEY ("origin") REFERENCES "public"."ad_modules" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "template_module_place_fkey" FOREIGN KEY ("place") REFERENCES "public"."ad_places" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE TABLE "public"."template_map_module" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"template" uuid NOT NULL,
"module" uuid NOT NULL,
"page" uuid,
"placed" bool DEFAULT false NOT NULL,
"x" varchar,
"y" varchar,
"created" timestamptz(6) DEFAULT now(),
"updated" timestamptz(6) DEFAULT now(),
CONSTRAINT "template_map_module_pkey" PRIMARY KEY ("id"),
CONSTRAINT "template_map_module_template_fkey" FOREIGN KEY ("template") REFERENCES "public"."template" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "template_map_module_module_fkey" FOREIGN KEY ("module") REFERENCES "public"."template_module" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT "template_map_module_page_fkey" FOREIGN KEY ("page") REFERENCES "public"."template_page" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
/*
CREATE TABLE "public"."fascicles_ad" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"fascicle" uuid NOT NULL,
"shortcut" varchar NOT NULL,
"description" varchar,
"ad_serial" serial NOT NULL,
"ad_place" uuid NOT NULL,
"ad_advertiser" uuid NOT NULL,
"ad_manager" uuid NOT NULL,
"ad_status" varchar NOT NULL,
"ad_paid" varchar NOT NULL,
"ad_readiness" varchar NOT NULL,
"ad_squib" varchar NOT NULL,
"ad_check_status" varchar DEFAULT 'new' NOT NULL,
"ad_anothers_layout" bool DEFAULT false NOT NULL,
"ad_imposed" bool DEFAULT false NOT NULL,
"cache_ad_advertiser" varchar NOT NULL,
"cache_ad_place" varchar NOT NULL,
"cache_ad_manager" varchar NOT NULL,
"cache_ad_page" int4,
"cache_ad_pages" varchar,
"module_shortcut" varchar,
"module_description" varchar,
"module_area" float8 DEFAULT 0,
"module_amount" int4 DEFAULT 1,
"module_w" varchar,
"module_h" varchar,
"module_x" varchar,
"module_y" varchar,
"module_pw" float4 DEFAULT 0,
"module_ph" float4 DEFAULT 0,
"module_pfw" float4 DEFAULT 0,
"module_pfh" float4 DEFAULT 0,
"created" timestamptz(6) DEFAULT now() NOT NULL,
"updated" timestamptz(6) DEFAULT now() NOT NULL,
CONSTRAINT "fascicles_ad_pkey" PRIMARY KEY ("id")
);
INSERT INTO fascicles_ad
id,
edition, fascicle,
shortcut, description,
ad_serial, ad_place, ad_advertiser, ad_manager, ad_status, ad_paid, ad_readiness, ad_squib, ad_check_status, ad_anothers_layout, ad_imposed,
cache_ad_advertiser, cache_ad_place, cache_ad_manager, cache_ad_page, cache_ad_pages,
module_shortcut, module_description, module_area, module_amount, module_w, module_h, module_x, module_y, module_pw, module_ph, module_pfw, module_pfh, created, updated,
);
CREATE TABLE "public"."layout" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"fascicle" uuid NOT NULL,
"layout_version" uuid DEFAULT uuid_generate_v4() NOT NULL,
"is_active" bool DEFAULT false NOT NULL,
"created" timestamptz(6) DEFAULT now() NOT NULL,
"updated" timestamptz(6) DEFAULT now() NOT NULL,
CONSTRAINT "layout_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "public"."layout_content" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"edition" uuid NOT NULL,
"fascicle" uuid NOT NULL,
"layout_version" uuid DEFAULT uuid_generate_v4() NOT NULL,
"content_type" varchar NOT NULL,
"content_parent" uuid NOT NULL,
"content_entity" uuid NOT NULL,
"created" timestamptz(6) DEFAULT now() NOT NULL,
"updated" timestamptz(6) DEFAULT now() NOT NULL,
CONSTRAINT "layout_content_pkey" PRIMARY KEY ("id")
);
-- Insert layouts
DELETE FROM layout;
INSERT INTO layout (edition, fascicle, is_active, created, updated)
SELECT edition, id, true, created, updated FROM fascicles;
-- Insert pages
DELETE FROM layout_content WHERE content_type = 'page';
INSERT INTO layout_content (edition, fascicle, layout_version, content_type, content_parent, content_entity, created, updated)
SELECT
t1.edition,
t1.fascicle,
( SELECT layout_version FROM layout l2 WHERE l2.fascicle = t1.fascicle ) as layout_version,
'page',
t1.fascicle,
t1.id,
t1.created,
t1.updated
FROM fascicles_pages as t1;
-- Insert documents
DELETE FROM layout_content WHERE content_type = 'document';
INSERT INTO layout_content (edition, fascicle, layout_version, content_type, content_parent, content_entity, created, updated)
SELECT
t1.edition,
t1.fascicle,
( SELECT layout_version FROM layout l2 WHERE l2.fascicle = t1.fascicle ) as layout_version,
'document',
t1.page,
t1.entity,
t1.created,
t1.updated
FROM fascicles_map_documents as t1;
*/<file_sep>Inprint.fascicle.template.composer.Access = function(parent, panels, access) {
var pages = panels.pages;
if (access.manage) {
parent.btnPageCreate.enable();
}
};
<file_sep>ALTER TABLE map_member_to_rule ADD COLUMN termkey character varying;
UPDATE map_member_to_rule set area='domain' where section='domain';
UPDATE map_member_to_rule set area='edition' where section='editions';
UPDATE map_member_to_rule set termkey = (
SELECT rules.section ||'.'|| rules.subsection ||'.'|| rules.term || ':' || mapper.area
FROM map_member_to_rule as mapper, rules WHERE mapper.term = rules.id AND mapper.id = map_member_to_rule.id);
DELETE FROM map_member_to_rule WHERE termkey is null;
--
ALTER TABLE fascicles DROP COLUMN pnum;
ALTER TABLE fascicles ADD COLUMN num integer;
UPDATE fascicles SET num = 0;
ALTER TABLE fascicles ALTER COLUMN num SET NOT NULL;
ALTER TABLE fascicles ALTER COLUMN num SET DEFAULT 0;
--
ALTER TABLE fascicles DROP COLUMN anum;
ALTER TABLE fascicles ADD COLUMN anum integer;
UPDATE fascicles SET anum = 0;
ALTER TABLE fascicles ALTER COLUMN anum SET NOT NULL;
ALTER TABLE fascicles ALTER COLUMN anum SET DEFAULT 0;
--
ALTER TABLE fascicles ADD COLUMN deleted boolean;
ALTER TABLE fascicles ALTER COLUMN deleted SET DEFAULT false;
UPDATE fascicles SET deleted = false;
ALTER TABLE fascicles ALTER COLUMN deleted SET NOT NULL;
--
ALTER TABLE fascicles DROP COLUMN flagadv;
ALTER TABLE fascicles ADD COLUMN adv_enabled boolean;
UPDATE fascicles SET adv_enabled = true;
ALTER TABLE fascicles ALTER COLUMN adv_enabled SET DEFAULT false;
--
ALTER TABLE fascicles DROP COLUMN flagdoc;
ALTER TABLE fascicles ADD COLUMN doc_enabled boolean;
UPDATE fascicles SET doc_enabled = true;
ALTER TABLE fascicles ALTER COLUMN doc_enabled SET DEFAULT false;
ALTER TABLE fascicles ALTER COLUMN doc_enabled SET NOT NULL;
--
ALTER TABLE fascicles RENAME COLUMN datedoc TO doc_date;
ALTER TABLE fascicles RENAME COLUMN dateadv TO adv_date;
ALTER TABLE fascicles RENAME COLUMN dateprint TO print_date;
ALTER TABLE fascicles RENAME COLUMN dateout TO release_date;
--
ALTER TABLE fascicles ADD COLUMN "tmpl" uuid;
ALTER TABLE fascicles ADD COLUMN tmpl_shortcut character varying;
ALTER TABLE fascicles ALTER COLUMN tmpl_shortcut SET DEFAULT ''::character varying;
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.form.ImageField = Ext.extend(Ext.form.Field, {
autoCreate: {tag: 'img'},
setValue: function(new_value) {
if (new_value) {
this.el.dom.src = new_value;
}
},
initValue : function() {
this.setValue(this.value);
},
initComponent: function() {
Ext.form.ImageField.superclass.initComponent.apply(this);
}
});
Ext.reg('imagefield', Ext.form.ImageField);
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.Ajax.extraParams = {
'ajax': true
};
Ext.Ajax.on('beforerequest', function(conn, options) {
options.extraParams = {
ajax:true
};
});
Ext.Ajax.on('requestexception', function(conn, response, options) {
var errorText = _("Error communicating with server");
var jsonData = Ext.util.JSON.decode(response.responseText);
if (jsonData && jsonData.error) {
errorText = jsonData.error;
errorText = errorText.replace(/%br%/g, "<br/>");
}
Inprint.log(errorText);
});
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
};
Ext.apply(Ext.EventObject, {
within_el:function(el) {
el = Ext.get(el);
if(!el)
return false;
var evt_xy = this.getXY();
var evt_x = evt_xy[0];
var evt_y = evt_xy[1];
return (evt_x > el.getLeft() && evt_x < el.getRight() && evt_y > el.getTop() && evt_y < el.getBottom());
}
});
<file_sep>Inprint.plugins.rss.profile.Form = Ext.extend(Ext.FormPanel, {
initComponent: function() {
this.urls = {
"update": _url("/plugin/rss/update/")
};
Ext.apply(this, {
xtype: "form",
url: this.urls.update,
width: 600,
border:false,
labelWidth: 70,
bodyStyle: "padding:5px 5px",
defaults: {
anchor: "100%",
allowBlank:false
},
items: [
{
xtype: "hidden",
name: "document",
value: this.oid,
allowBlank:false
},
{
xtype:"textfield",
fieldLabel: _("URL"),
emptyText: _("URL"),
allowBlank: true,
name: "link"
},
{
xtype:"textfield",
fieldLabel: _("Title"),
emptyText: _("Title"),
name: "title"
},
{
xtype:"textarea",
fieldLabel: _("Description"),
emptyText: _("Description"),
name: "description",
height:36
},
{
xtype:'htmleditor',
name: "fulltext",
allowBlank:false,
hideLabel:true,
height:200
}
]
});
Inprint.plugins.rss.profile.Form.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.plugins.rss.profile.Form.superclass.onRender.apply(this, arguments);
this.getForm().url = this.urls.update;
}
});
<file_sep>Inprint.cmp.DumbWindow.Interaction = function(panels) {
};
<file_sep>Inprint.cmp.MoveDocument = Ext.extend(Ext.Window, {
initComponent: function() {
this.addEvents('actioncomplete');
this.form = new Inprint.cmp.MoveDocument.Form({
oid: this.oid
});
Ext.apply(this, {
title: _("Move document"),
modal:true,
layout: "fit",
width:380, height:350,
items: this.form,
buttons:[
{
text: _("Move"),
scope:this,
handler: function() {
this.form.getForm().submit();
}
},
{
text: _("Cancel"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
this.form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
this.hide();
this.fireEvent("actioncomplete", this, this.form);
}
}, this);
Inprint.cmp.MoveDocument.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.MoveDocument.superclass.onRender.apply(this, arguments);
Inprint.cmp.MoveDocument.Interaction(this, this.panels);
},
setId: function(data) {
this.form.getForm().baseParams = {
id: data
};
}
});
<file_sep>Ext.ns("Inprint.fascicle.places");<file_sep>Inprint.cmp.composer.Flash = Ext.extend(Ext.Panel, {
initComponent: function() {
this.urls = {
"init": _url("/fascicle/composer/initialize/"),
"save": _url("/fascicle/composer/save/")
};
var selection = this.parent.selection;
var selLength = this.parent.selLength;
selection.sort(function(a, b){
var array1 = a.split("::");
var array2 = b.split("::");
return array1[1] - array2[1];
});
this.pages = [];
for (var c = 1; c < selection.length+1; c++) {
var array = selection[c-1].split("::");
this.pages.push(array[0]);
}
selLength = selection.length;
var flashWidth = 260 * selLength;
this.flashid = Ext.id();
var flash = {
id: this.flashid,
xtype: "flash",
swfWidth:flashWidth,
swfHeight:290,
//hideMode: 'offsets',
url: '/flash/Dispose3.swf',
expressInstall: true,
flashParams: {
scale:"noscale"
},
flashVars: {
src: "/flash/Dispose3.swf",
autostart:"yes",
loop: "yes"
}
};
Ext.apply(this, {
region:"east",
//margins: "3 3 3 0",
width: flashWidth,
minSize: 200,
maxSize: 600,
layout:"hbox",
layoutConfig: {
align : 'stretch',
pack : 'start'
},
items: flash
});
Inprint.cmp.composer.Flash.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.composer.Flash.superclass.onRender.apply(this, arguments);
this.cmpInit();
},
cmpGetFlashById: function(id) {
var panel = this.findById(id);
if (panel) {
return panel.swf;
}
return null;
},
cmpInit: function() {
this.body.mask(_("Loading..."));
Ext.Ajax.request({
url: this.urls.init,
scope:this,
callback : function() {
this.body.unmask();
},
success: function ( result, request ) {
var responce = Ext.util.JSON.decode(result.responseText);
this.cmpInitFlash(responce);
},
params: { page: this.pages }
});
},
cmpInitFlash: function(responce) {
var flash = this.cmpGetFlashById(this.flashid);
if (!flash) {
return;
}
var init = function() {
if (flash.reset) {
flash.reset();
Ext.each(responce.data.pages, function(c) {
flash.setField(c.id, "letter", 0, 0 );
flash.setGrid(c.id, c.w, c.h);
}, this);
Ext.each(responce.data.modules, function(c) {
flash.setBlock(c.page, c.id, c.title, c.x, c.y, c.w, c.h );
}, this);
} else {
init.defer(10, this);
}
};
init.defer(100, this);
},
cmpMoveBlocks: function(composition) {
var flash = this.cmpGetFlashById(this.flashid);
if (!flash) {
return;
}
flash.moveBlock( composition.page, composition.module );
},
cmpSave: function() {
var flash = this.cmpGetFlashById(this.flashid);
if (!flash) {
return;
}
flash.getAllBlocks( "Inprint.flash.Proxy.savePage", this.id );
},
cmpSaveProxy: function(records) {
var data = [];
for (var p=0;p<records.length;p++) {
var modules = records[p].arr;
for (var m=0;m<modules.length;m++) {
var module = modules[m];
var string = module.id +'::'+ module.fid +'::'+ module.x +'::'+ module.y +'::'+ module.w +'::'+ module.h;
data.push(string);
}
}
Ext.Ajax.request({
url: this.urls.save,
scope:this,
success: function ( result, request ) {
var responce = Ext.util.JSON.decode(result.responseText);
this.parent.fireEvent("actioncomplete", this);
},
params: {
modules: data,
fascicle: this.parent.fascicle
}
});
}
});
<file_sep>Inprint.documents.Profile.View = Ext.extend(Ext.Panel, {
initComponent: function() {
var actions = new Inprint.documents.GridActions();
this.tbar = [
{
icon: _ico("card--pencil"),
cls: "x-btn-text-icon",
text: _("Properties"),
disabled:true,
ref: "../btnUpdate",
scope:this.parent,
handler: actions.Update
},
'-',
{
icon: _ico("hand"),
cls: "x-btn-text-icon",
text: _("Capture"),
disabled:true,
ref: "../btnCapture",
scope:this.parent,
handler: actions.Capture
},
{
icon: _ico("arrow"),
cls: "x-btn-text-icon",
text: _("Transfer"),
disabled:true,
ref: "../btnTransfer",
scope:this.parent,
handler: actions.Transfer
},
'-',
{
icon: _ico("blue-folder-import"),
cls: "x-btn-text-icon",
text: _("Move"),
disabled:true,
ref: "../btnMove",
scope:this.parent,
handler: actions.Move
},
{
icon: _ico("briefcase"),
cls: "x-btn-text-icon",
text: _("Briefcase"),
disabled:true,
ref: "../btnBriefcase",
scope:this.parent,
handler: actions.Briefcase
},
"-",
{
icon: _ico("document-copy"),
cls: "x-btn-text-icon",
text: _("Copy"),
disabled:true,
ref: "../btnCopy",
scope:this.parent,
handler: actions.Copy
},
{
icon: _ico("documents"),
cls: "x-btn-text-icon",
text: _("Duplicate"),
disabled:true,
ref: "../btnDuplicate",
scope:this.parent,
handler: actions.Duplicate
},
"-",
{
icon: _ico("bin--plus"),
cls: "x-btn-text-icon",
text: _("Recycle Bin"),
disabled:true,
ref: "../btnRecycle",
scope:this.parent,
handler: actions.Recycle
},
{
icon: _ico("bin--arrow"),
cls: "x-btn-text-icon",
text: _("Restore"),
disabled:true,
ref: "../btnRestore",
scope:this.parent,
handler: actions.Restore
},
{
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Delete"),
disabled:true,
ref: "../btnDelete",
scope:this.parent,
handler: actions.Delete
}
];
Ext.apply(this, {
border: false,
autoScroll:true,
bodyCssClass: "inprint-document-profile",
items: [
{
border:false,
tpl: this.tmpl1
},
{
border:false,
tpl: this.tmpl2
},
{
border:false,
tpl: this.tmpl3
}
]
});
// Call parent (required)
Inprint.documents.Profile.View.superclass.initComponent.apply(this, arguments);
},
// Override other inherited methods
onRender: function() {
// Call parent (required)
Inprint.documents.Profile.View.superclass.onRender.apply(this, arguments);
},
tmpl1: new Ext.XTemplate(
'<table width="99%" align="center">',
'<tr style="background:#f5f5f5;">',
'<th>Название</th>',
'<th width="70">'+ _("Edition") +'</th>',
'<th width="70">'+ _("Issue") +'</td>',
'<th width="90">'+ _("Category") +'</th>',
'<th width="90">'+ _("Rubric") +'</th>',
'<th width="50">'+ _("Characters") +'</th>',
'<th width="80">'+ _("Department") +'</td>',
'<th width="100">'+ _("Editor") +'</th>',
'<th width="130">'+ _("Author") +'</th>',
'<th width="90">'+ _("Date") +'</th>',
'</tr>',
'<tr>',
'<td>{[ this.fmtString( values.title ) ]}</td>',
'<td>{[ this.fmtString( values.edition_shortcut ) ]}</td>',
'<td>{[ this.fmtString( values.fascicle_shortcut ) ]}</td>',
'<td>{[ this.fmtString( values.headline_shortcut ) ]}</td>',
'<td>{[ this.fmtString( values.rubric_shortcut ) ]}</td>',
'<td><nobr>',
'<tpl if="rsize">{rsize}</tpl>',
'<tpl if="!rsize">{psize}</tpl>',
'</nobr></td>',
'<td><nobr>{[ this.fmtString( values.maingroup_shortcut ) ]}</nobr></td>',
'<td><nobr>{[ this.fmtString( values.manager_shortcut ) ]}</nobr></td>',
'<td><nobr>{[ this.fmtString( values.author ) ]}</nobr></td>',
'<td><nobr>',
'<tpl if="fdate">{[ this.fmtDate( values.fdate ) ]}</tpl>',
'<tpl if="!fdate">{[ this.fmtDate( values.pdate ) ]}</tpl>',
'</nobr></td>',
'</tr>',
'</table>',
{
fmtDate : function(date) { return _fmtDate(date, 'M j, H:i'); },
fmtString : function(string) { if (!string) { string = ''; } return string; }
}
),
tmpl2: new Ext.XTemplate(
'<tpl if="history">',
'<table width="99%" align="center" style="border:0px;">',
'<td style="border:0px;">',
'<tpl for="history">',
'<div style="display: inline;padding:3px;padding-left:12px;margin-right:10px;float:left;background:url(/icons/arrow-000-small.png) -3px 2px no-repeat;">',
'<div style="font-weight:bold;border-bottom:2px solid #{color};">{destination_shortcut}</div>',
'<div style="font-size:90%;">{stage_shortcut}</div>',
'<div style="font-size:90%;">{[ this.fmtDate( values.created ) ]}</div>',
'</div>',
'</tpl>',
'<div style="clear:both;"></div>',
'</td>',
'</table>',
'</tpl>',
{
fmtDate : function(date) { return _fmtDate(date, 'M j, H:i'); },
fmtString : function(string) { if (!string) { string = ''; } return string; }
}
),
tmpl3: new Ext.XTemplate(
'<tpl if="fascicles">',
'<table width="99%" align="center">',
'<tr style="background:#f5f5f5;">',
'<th width="270">'+ _("Edition") +'</th>',
'<th width="70">'+ _("Issue") +'</td>',
'<th width="90">'+ _("Category") +'</th>',
'<th>Рубрика</th>',
'</tr>',
'<tpl for="fascicles">',
'<tr>',
'<td><nobr>{[ this.fmtString( values.editions ) ]}</nobr></td>',
'<td>{[ this.fmtString( values.fascicle_shortcut ) ]}</td>',
'<td>{[ this.fmtString( values.headline_shortcut ) ]}</td>',
'<td>{[ this.fmtString( values.rubric_shortcut ) ]}</td>',
'</tr>',
'</tpl>',
'</table>',
'</tpl>',
{
fmtDate : function(date) { return _fmtDate(date, 'M j, H:i'); },
fmtString : function(string) { if (!string) { string = ''; } return string; }
}
),
cmpFill: function(record) {
if (record) {
if (record.access) {
this.cmpAccess(record.fascicle, record.access);
}
this.items.get(0).update(record);
this.items.get(1).update(record);
this.items.get(2).hide();
if (record.fascicles.length > 0) {
this.items.get(2).show();
this.items.get(2).update(record);
}
}
},
cmpAccess: function(fascicle, access) {
_hide(this.btnRecycle, this.btnRestore, this.btnDelete);
if (fascicle == '99999999-9999-9999-9999-999999999999') {
_show(this.btnRestore, this.btnDelete);
} else {
_show(this.btnRecycle);
}
access.update === true ? this.btnUpdate.enable() : this.btnUpdate.disable();
access.capture === true ? this.btnCapture.enable() : this.btnCapture.disable();
access.transfer === true ? this.btnTransfer.enable() : this.btnTransfer.disable();
access.briefcase === true ? this.btnBriefcase.enable() : this.btnBriefcase.disable();
access.move === true ? this.btnMove.enable() : this.btnMove.disable();
access.move === true ? this.btnCopy.enable() : this.btnCopy.disable();
access.move === true ? this.btnDuplicate.enable() : this.btnDuplicate.disable();
access.recover === true ? this.btnRestore.enable() : this.btnRestore.disable();
access["delete"] === true ? this.btnRecycle.enable() : this.btnRecycle.disable();
access["delete"] === true ? this.btnDelete.enable() : this.btnDelete.disable();
}
});
<file_sep>Inprint.cmp.memberRulesForm.Organization = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {};
this.panels.tree = new Inprint.cmp.memberRulesForm.Organization.Tree();
this.panels.grid = new Inprint.cmp.memberRulesForm.Organization.Restrictions();
Ext.apply(this, {
border:false,
title: _("Departments"),
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
region: "center",
layout:"fit",
border:false,
margins: "3 3 3 0",
items: this.panels.grid
},
{
region:"west",
layout:"fit",
border:false,
margins: "3 0 3 3",
width: 200,
items: this.panels.tree
}
]
});
Inprint.cmp.memberRulesForm.Organization.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.memberRulesForm.Organization.superclass.onRender.apply(this, arguments);
},
cmpGetTree: function() {
return this.panels.tree;
},
cmpGetGrid: function() {
return this.panels.grid;
},
cmpReload: function() {
this.panels.grid.cmpReload();
}
});
<file_sep>"use strict";
Inprint.calendar.CreateIssueAction = function() {
var form = new Inprint.calendar.forms.CreateIssueForm();
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
400, 500, _("New issue"),
form, [ _BTN_WNDW_ADD, _BTN_WNDW_CLOSE ]
).build().show();
}
Inprint.calendar.UpdateIssueAction = function() {
var form = new Inprint.calendar.forms.UpdateIssueForm();
form.cmpFill( this.getRecord().get("id") );
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
400, 500, _("Issue parameters"),
form, [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
).build().show();
};
Inprint.calendar.DeleteIssueAction = function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url: _source("issue.delete"),
scope: this,
params: { id: this.getRecord().get("id") },
success: function() {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
}
});
return false;
}
if (btn == 'no') {
return false;
}
Ext.MessageBox.show({
title: _("Important event"),
msg: _("Delete selected item?"),
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
fn: Inprint.calendar.DeleteIssueAction.createDelegate(this)
});
return true;
};
/* Attachments */
Inprint.calendar.CreateAttachmentAction = function() {
var issue = this.getStore().lastOptions.params.issue;
var edition = this.getStore().lastOptions.params.edition;
var form = new Inprint.calendar.forms.AttachmentCreate({
issue: issue,
edition: edition
});
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
form.findParentByType("window").close();
}}, this);
Inprint.fx.Window(
360, 180, _("New attachment"),
form, [ _BTN_WNDW_ADD, _BTN_WNDW_CLOSE ]
).build().show();
};
Inprint.calendar.UpdateAttachmentAction = function(oid) {
var form = new Inprint.calendar.forms.AttachmentUpdate();
form.cmpFill( this.getRecord().get("id") );
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
360, 200, _("Attachment parameters"),
form, [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
).build().show();
};
Inprint.calendar.RestrictionsAttachmentAction = function(oid) {
var form = new Inprint.calendar.forms.AttachmentRestrictions();
form.cmpFill( this.getRecord().get("id") );
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
360, 200, _("Attachment restrictions"),
form, [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
).build().show();
};
Inprint.calendar.DeleteAttachmentAction = function(btn, var1, var2, oid, callback) {
if (btn == 'yes') {
Ext.Ajax.request({
url: _source("attachment.delete"),
scope: this,
params: { id: this.getRecord().get("id") },
success: function() {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
}
});
return false;
}
if (btn == 'no') {
return false;
}
Ext.MessageBox.show({
title: _("Important event"),
msg: _("Delete selected item?"),
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
fn: Inprint.calendar.DeleteAttachmentAction.createDelegate(this)
});
return true;
};
<file_sep>Inprint.documents.editor.Versions = Ext.extend( Ext.Panel, {
initComponent: function() {
this.panels = {};
this.panels.browser = new Inprint.documents.editor.versions.Browser({
parent:this,
url: this.url,
oid: this.oid
});
this.panels.viewer = new Inprint.documents.editor.versions.Viewer({
parent: this,
oid: this.oid
});
// Create Panel
Ext.apply(this, {
layout: "card",
activeItem: 0,
tbar:[
{
icon: _ico("arrow-180"),
cls: "x-btn-text-icon",
text: _("Go back"),
disabled:true,
ref: "../btnBack",
scope:this,
handler: function() {
this.btnBack.disable();
this.btnView.enable();
this.layout.setActiveItem(0);
}
},
{
icon: _ico("eye"),
cls: "x-btn-text-icon",
text: _("View"),
disabled:true,
ref: "../btnView",
scope:this,
handler: this.cmpClick
}
],
items: [
this.panels.browser,
this.panels.viewer
]
});
Inprint.documents.editor.Versions.superclass.initComponent.apply(this, arguments);
},
cmpClick: function() {
this.btnBack.enable();
this.btnView.disable();
this.layout.setActiveItem(1);
this.panels.viewer.load({
text: _("Loading") + "...",
timeout: 30,
mode: "iframe",
url: this.url + "/read/",
params: { version: this.panels.browser.config.selection }
});
},
// Override other inherited methods
onRender: function() {
Inprint.documents.editor.Versions.superclass.onRender.apply(this, arguments);
},
cmpReload: function () {
if (this.panels.browser.cmpReload) { this.panels.browser.cmpReload(); }
}
});
<file_sep>ALTER TABLE ad_modules ADD COLUMN check_width real DEFAULT 0 NOT NULL;
ALTER TABLE ad_modules ADD COLUMN check_height real DEFAULT 0 NOT NULL;
ALTER TABLE ad_modules ADD COLUMN check_width_float real DEFAULT 0 NOT NULL;
ALTER TABLE ad_modules ADD COLUMN check_height_float real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_modules ADD COLUMN check_width real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_modules ADD COLUMN check_height real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_modules ADD COLUMN check_width_float real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_modules ADD COLUMN check_height_float real DEFAULT 0 NOT NULL;
ALTER TABLE cache_files ADD COLUMN file_color varchar;
ALTER TABLE cache_files ADD COLUMN file_resolution int4 DEFAULT 0 NOT NULL;
ALTER TABLE cache_files ADD COLUMN file_width real DEFAULT 0 NOT NULL;
ALTER TABLE cache_files ADD COLUMN file_height real DEFAULT 0 NOT NULL;
ALTER TABLE fascicles_requests ADD COLUMN check_status varchar DEFAULT 'new' NOT NULL;
ALTER TABLE fascicles_requests ADD COLUMN anothers_layout boolean DEFAULT false NOT NULL;
ALTER TABLE fascicles_requests ADD COLUMN imposed boolean DEFAULT false NOT NULL;
CREATE TABLE fascicles_requests_comments
(
id uuid NOT NULL DEFAULT uuid_generate_v4(),
entity uuid NOT NULL,
member uuid NOT NULL,
member_shortcut character varying NOT NULL,
check_status character varying NOT NULL,
fulltext character varying NOT NULL,
created timestamp(6) with time zone NOT NULL DEFAULT now(),
updated timestamp(6) with time zone NOT NULL DEFAULT now(),
CONSTRAINT fascicles_requests_comments_pkey PRIMARY KEY (id)
);
CREATE TABLE fascicles_requests_files
(
id uuid NOT NULL DEFAULT uuid_generate_v4(),
fpath character varying NOT NULL,
fname character varying NOT NULL,
forname character varying NOT NULL,
fextension character varying NOT NULL,
fmime character varying NOT NULL,
fdigest character varying NOT NULL,
fthumbnail character varying,
fdescription character varying,
fsize integer NOT NULL DEFAULT 0,
flength integer NOT NULL DEFAULT 0,
fcolor character varying,
fresolution integer NOT NULL DEFAULT 0,
fwidth real NOT NULL DEFAULT 0,
fheight real NOT NULL DEFAULT 0,
fexists boolean NOT NULL DEFAULT true,
fimpose boolean NOT NULL DEFAULT true,
fstatus character varying,
created timestamp(6) with time zone NOT NULL DEFAULT now(),
updated timestamp(6) with time zone NOT NULL DEFAULT now(),
CONSTRAINT fascicles_requests_files_pkey PRIMARY KEY (id),
CONSTRAINT fascicles_requests_files_fpath_key UNIQUE (fpath, fname)
);<file_sep>Inprint.plugins.rss.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {
grid: new Inprint.plugins.rss.Grid({
parent:this,
oid: this.oid
}),
profile: new Inprint.plugins.rss.Profile({
parent:this,
oid: this.oid
})
};
Ext.apply(this, {
border:true,
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "center",
layout:"fit",
items: this.panels.grid
},
{ region: "south",
layout:"fit",
split:true,
height:354,
items: this.panels.profile
}
]
});
Inprint.plugins.rss.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.plugins.rss.Panel.superclass.onRender.apply(this, arguments);
Inprint.plugins.rss.Access(this, this.panels);
Inprint.plugins.rss.Interaction(this, this.panels);
},
cmpReload: function() {
this.panels.grid.cmpReload();
}
});
Inprint.registry.register("plugin-rss", {
icon: "feed",
text: _("RSS feeds"),
xobject: Inprint.plugins.rss.Panel
});
<file_sep>Ext.namespace("Inprint.cmp.PrincipalsBrowser");
<file_sep>#!/bin/sh
# Inprint Content 5.0
# Copyright(c) 2001-2010, Softing, LLC.
# <EMAIL>
# http://softing.ru/license
apt-get -y install build-essential
apt-get -y install libconfig-tiny-perl
apt-get -y install libdbd-pg-perl
apt-get -y install libdevel-simpletrace-perl
apt-get -y install libfile-copy-recursive-perl
apt-get -y install libgd-gd2-perl
apt-get -y install libgd-text-perl
apt-get -y install libhtml-scrubber-perl
apt-get -y install libossp-uuid-perl
apt-get -y install libtext-unidecode-perl
apt-get -y install libtest-mockmodule-perl
apt-get -y install libwww-perl
apt-get -y install libyaml-perl
apt-get -y install libimage-exiftool-perl
apt-get -y install apache2
apt-get -y install ghostscript
apt-get -y install imagemagick
apt-get -y install perlmagick
apt-get -y install postgresql
apt-get -y install postgresql-contrib
apt-get -y install sun-java6-jre
a2enmod rewrite
a2enmod expires
/etc/init.d/apache2 restart
/etc/init.d/postgresql-8.4 restart
perl -MCPAN -e 'install DBIx::Connector'
perl -MCPAN -e 'install IO::Epoll'
perl -MCPAN -e 'install File::Util'
perl -MCPAN -e 'install Convert::Cyrillic'
perl -MCPAN -e 'install Mojolicious'
<file_sep>Ext.namespace("Inprint.fascicle.planner");<file_sep>Inprint.fascicle.modules.Pages = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.params = {};
this.components = {};
this.urls = {
"list": "/fascicle/templates/pages/list/",
"create": _url("/fascicle/templates/pages/create/"),
"read": _url("/fascicle/templates/pages/read/"),
"update": _url("/fascicle/templates/pages/update/"),
"delete": _url("/fascicle/templates/pages/delete/")
};
this.store = Inprint.factory.Store.json(this.urls.list, {
autoLoad:true,
baseParams: {
fascicle: this.parent.fascicle
}
});
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"title",
header: _("Title"),
width: 150,
sortable: true,
dataIndex: "title"
},
{
id:"description",
header: _("Description"),
sortable: true,
dataIndex: "description"
},
{
id:"w",
header: _("W"),
sortable: true,
dataIndex: "w"
},
{
id:"h",
header: _("H"),
sortable: true,
dataIndex: "h"
}
];
this.tbar = [
{
disabled:true,
icon: _ico("plus-button"),
cls: "x-btn-text-icon",
text: _("Add"),
ref: "../btnCreate",
scope:this,
handler: this.cmpCreate
},
{
disabled:true,
icon: _ico("pencil"),
cls: "x-btn-text-icon",
text: _("Edit"),
ref: "../btnUpdate",
scope:this,
handler: this.cmpUpdate
},
'-',
{
disabled:true,
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
ref: "../btnDelete",
scope:this,
handler: this.cmpDelete
}
];
Ext.apply(this, {
disabled:false,
border:false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "description"
});
Inprint.fascicle.modules.Pages.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.modules.Pages.superclass.onRender.apply(this, arguments);
},
cmpCreate: function() {
var win = this.components["create-window"];
if (!win) {
var form = {
xtype: "form",
frame:false,
border:false,
labelWidth: 75,
url: this.urls.create,
bodyStyle: "padding:5px 5px",
defaults: {
anchor: "100%",
allowBlank:false
},
baseParams: {},
items: [
_FLD_HDN_FASCICLE,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
labelSeparator: '',
boxLabel: _("Yes"),
fieldLabel: _("By default"),
name: 'bydefault',
checked: false
}
],
listeners: {
scope:this,
beforeaction: function(form, action) {
var swf = this.components["create-window"].findByType("flash")[0].swf;
var id = Ext.getCmp(this.components["create-window"].getId()).form.getId();
(function () {
swf.get("Inprint.flash.Proxy.setGrid", id);
}).defer(10);
},
actioncomplete: function (form, action) {
if (action.type == "submit") {
this.components["create-window"].hide();
this.cmpReload();
}
}
},
keys: [ _KEY_ENTER_SUBMIT ]
};
var flash = {
xtype: "flash",
swfWidth:380,
swfHeight:360,
hideMode : 'offsets',
url : '/flash/Grid.swf',
expressInstall: true,
flashVars: {
src: '/flash/Grid.swf',
scale :'noscale',
autostart: 'yes',
loop: 'yes'
},
listeners: {
scope:this,
initialize: function(panel, flash) {
alert(2);
},
afterrender: function(panel) {
var init = function () {
if (panel.swf.init) {
panel.swf.init(panel.getSwfId(), "letter", 0, 0);
} else {
init.defer(100, this);
}
};
init.defer(100, this);
}
}
};
win = new Ext.Window({
width:700,
height:500,
modal:true,
layout: "border",
closeAction: "hide",
title: _("Adding a new category"),
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "center",
margins: "3 0 3 3",
layout:"fit",
items: form
},
{ region:"east",
margins: "3 3 3 0",
width: 380,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
items: flash
}
],
listeners: {
scope:this,
afterrender: function(panel) {
panel.flash = panel.findByType("flash")[0].swf;
panel.form = panel.findByType("form")[0];
}
},
buttons: [ _BTN_WNDW_ADD, _BTN_WNDW_CLOSE ]
});
}
win.show(this);
this.components["create-window"] = win;
var form = win.form.getForm();
form.reset();
form.findField("fascicle").setValue(this.parent.fascicle);
},
cmpUpdate: function() {
var win = this.components["update-window"];
if (!win) {
var form = {
xtype: "form",
frame:false,
border:false,
labelWidth: 75,
url: this.urls.update,
bodyStyle: "padding:5px 5px",
baseParams: {
edition: this.parent.edition
},
defaults: {
anchor: "100%",
allowBlank:false
},
items: [
_FLD_HDN_ID,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
labelSeparator: '',
boxLabel: _("Yes"),
fieldLabel: _("By default"),
name: 'bydefault',
checked: false
}
],
listeners: {
scope:this,
beforeaction: function(form, action) {
if (action.type == "submit") {
var swf = this.components["update-window"].findByType("flash")[0].swf;
var id = Ext.getCmp(this.components["update-window"].getId()).form.getId();
(function () {
swf.get("Inprint.flash.Proxy.setGrid", id);
}).defer(10);
}
},
actioncomplete: function (form, action) {
if (action.type == "load") {
var swf = this.components["update-window"].findByType("flash")[0].swf;
var load = function () {
if (swf.init) {
swf.set(action.result.data.w, action.result.data.h);
} else {
load.defer(100, this);
}
};
load.defer(100, this);
}
if (action.type == "submit") {
this.components["update-window"].hide();
this.cmpReload();
}
}
},
keys: [ _KEY_ENTER_SUBMIT ]
};
var flash = {
xtype: "flash",
swfWidth:380,
swfHeight:360,
hideMode : 'offsets',
url : '/flash/Grid.swf',
expressInstall: true,
flashVars: {
src: '/flash/Grid.swf',
scale :'noscale',
autostart: 'yes',
loop: 'yes'
},
listeners: {
scope:this,
initialize: function(panel, flash) {
alert(2);
},
afterrender: function(panel) {
var init = function () {
if (panel.swf.init) {
panel.swf.init(panel.getSwfId(), "letter", 0, 0);
} else {
init.defer(100, this);
}
};
init.defer(100, this);
}
}
};
win = new Ext.Window({
width:700,
height:500,
modal:true,
layout: "border",
closeAction: "hide",
title: _("Adding a new category"),
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "center",
margins: "3 0 3 3",
layout:"fit",
items: form
},
{ region:"east",
margins: "3 3 3 0",
width: 380,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
items: flash
}
],
listeners: {
scope:this,
afterrender: function(panel) {
panel.flash = panel.findByType("flash")[0].swf;
panel.form = panel.findByType("form")[0];
}
},
buttons: [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
});
}
win.show(this);
this.components["update-window"] = win;
var form = win.form.getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: this.getValue("id")
},
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
},
cmpDelete: function() {
Ext.MessageBox.confirm(
_("Warning"),
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.fascicle.template.composer.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.manager = null;
this.version = null;
this.access = {};
this.fascicle = this.oid;
this.panels = {
pages: new Inprint.fascicle.template.composer.Pages({
parent: this,
oid: this.oid
})
};
this.tbar = [
{
ref: "../btnPageCreate",
disabled:true,
text: "Добавить полосу",
tooltip: 'Добавить новые полосы в этот выпуск',
icon: _ico("plus-button"),
cls: 'x-btn-text-icon',
scope: this.panels.pages,
handler: this.panels.pages.cmpPageCreate
},
{
ref: "../btnPageUpdate",
disabled:true,
text:'Редактировать',
icon: _ico("pencil"),
cls: 'x-btn-text-icon',
scope: this.panels.pages,
handler: this.panels.pages.cmpPageUpdate
},
"-",
{
ref: "../btnPageMoveLeft",
disabled:true,
text:'Сместить влево',
tooltip: 'Перенести отмеченные полосы',
icon: _ico("arrow-stop-180"),
cls: 'x-btn-text-icon',
scope:this.panels.pages,
handler: this.panels.pages.cmpPageMoveLeft
},
{
ref: "../btnPageMoveRight",
disabled:true,
text:'Сместить вправо',
tooltip: 'Перенести отмеченные полосы',
icon: _ico("arrow-stop"),
cls: 'x-btn-text-icon',
scope:this.panels.pages,
handler: this.panels.pages.cmpPageMoveRight
},
{
ref: "../btnPageMove",
disabled:true,
text:'Перенести',
tooltip: 'Перенести отмеченные полосы',
icon: _ico("navigation-000-button"),
cls: 'x-btn-text-icon',
scope:this.panels.pages,
handler: this.panels.pages.cmpPageMove
},
"-",
{
ref: "../btnPageDelete",
disabled:true,
text: 'Удалить',
tooltip: 'Удалить полосы',
icon: _ico("minus-button"),
cls: 'x-btn-text-icon',
scope:this.panels.pages,
handler: this.panels.pages.cmpPageDelete
}
];
Ext.apply(this, {
layout: "fit",
autoScroll:true,
defaults: {
collapsible: false,
split: true
},
items: this.panels.pages
});
Inprint.fascicle.template.composer.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.template.composer.Panel.superclass.onRender.apply(this, arguments);
Inprint.fascicle.template.composer.Context(this, this.panels);
Inprint.fascicle.template.composer.Interaction(this, this.panels);
this.cmpReload();
},
cmpReload: function() {
this.body.mask(_("Loading..."));
Ext.Ajax.request({
scope: this,
url: _url("/template/seance/"),
params: {
fascicle: this.oid
},
callback: function() {
this.body.unmask();
},
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
var shortcut = _("Edit template");
var description = rsp.fascicle.shortcut;
var title = Inprint.ObjectResolver.makeTitle(
this.parent.aid,
this.parent.oid,
null,
this.parent.icon,
shortcut, description);
this.access = rsp.access;
this.parent.setTitle(title);
this.panels.pages.getStore().loadData({ data: rsp.pages });
Inprint.fascicle.template.composer.Access(this, this.panels, rsp.access);
}
});
}
});
Inprint.registry.register("fascicle-template-composer", {
icon: "puzzle--pencil",
text: _("Composing template"),
xobject: Inprint.fascicle.template.composer.Panel
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.ns("Inprint.store");
Ext.ns("Inprint.factory");
Ext.ns("Inprint.fx");
Ext.ns("Inprint.fx.btn");
<file_sep>Inprint.cmp.UpdateDocument = Ext.extend(Ext.Window, {
initComponent: function() {
this.form = new Inprint.cmp.UpdateDocument.Form();
Ext.apply(this, {
title: _("Edit Document Properties"),
modal:true,
layout: "fit",
width:400, height:460,
items: this.form,
buttons:[
{
text: _("Save"),
scope:this,
handler: function() {
this.form.getForm().submit();
}
},
{
text: _("Cancel"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
Inprint.cmp.UpdateDocument.superclass.initComponent.apply(this, arguments);
this.addEvents('complete');
},
onRender: function() {
Inprint.cmp.UpdateDocument.superclass.onRender.apply(this, arguments);
Inprint.cmp.UpdateDocument.Access(this, this.form);
this.form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
this.hide();
this.fireEvent("complete", this, this.form);
}
}, this);
},
onShow: function() {
Ext.Ajax.request({
url: "/documents/read/",
scope:this,
success: this.cmpFill,
params: { id: this.document }
});
},
cmpFill: function(result, request) {
var json = Ext.util.JSON.decode(result.responseText);
var form = this.form.getForm();
this.form.edition = json.data.edition;
this.form.fascicle = json.data.fascicle;
if (json.data.id) {
form.findField("id").setValue(json.data.id);
}
if (json.data.title) {
form.findField("title").setValue(json.data.title);
}
if (json.data.author) {
form.findField("author").setValue(json.data.author);
}
if (json.data.size) {
form.findField("size").setValue(json.data.size);
}
if (json.data.pdate) {
form.findField("enddate").setValue(json.data.pdate);
}
if (json.data.maingroup && json.data.maingroup_shortcut) {
form.findField("maingroup").setValue(json.data.maingroup, json.data.maingroup_shortcut);
}
if (json.data.manager && json.data.manager_shortcut) {
form.findField("manager").setValue(json.data.manager, json.data.manager_shortcut);
}
if (json.data.headline && json.data.headline_shortcut) {
form.findField("headline").setValue(json.data.headline, json.data.headline_shortcut);
form.findField("rubric").enable();
if (json.data.rubric && json.data.rubric_shortcut) {
form.findField("rubric").setValue(json.data.rubric, json.data.rubric_shortcut);
form.findField("rubric").getStore().baseParams.flt_headline = json.data.headline;
}
}
}
});
<file_sep>Inprint.cmp.PrincipalsBrowser = Ext.extend(Ext.Window, {
initComponent: function() {
this.panels = {};
this.panels.grid = new Inprint.cmp.PrincipalsBrowser.Grid();
this.panels.tree = new Inprint.cmp.PrincipalsBrowser.Tree();
Ext.apply(this, {
title: _("Principals list"),
modal: true,
layout: "border",
closeAction: "hide",
width:800, height:400,
items: [
{
region: "center",
layout:"fit",
margins: "3 3 3 0",
border:false,
items: this.panels.grid
},
{
region:"west",
layout:"fit",
margins: "3 0 3 3",
width: 200,
minSize: 100,
maxSize: 600,
collapsible: false,
split: true,
items: this.panels.tree
}
],
buttons:[
{
text: _("Select"),
scope:this,
handler: function() {
this.hide();
this.fireEvent('select', this.panels.grid.getValues("id"));
}
},
{
text: _("Close"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
Inprint.cmp.PrincipalsBrowser.superclass.initComponent.apply(this, arguments);
Inprint.cmp.PrincipalsBrowser.Interaction(this.panels);
this.addEvents('select');
},
onRender: function() {
Inprint.cmp.PrincipalsBrowser.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.advert.modules.Pages = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.params = {};
this.components = {};
this.urls = {
"list": "/advertising/pages/list/",
"create": _url("/advertising/pages/create/"),
"read": _url("/advertising/pages/read/"),
"update": _url("/advertising/pages/update/"),
"delete": _url("/advertising/pages/delete/")
};
this.store = Inprint.factory.Store.json(this.urls.list);
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"title",
header: _("Title"),
width: 150,
sortable: true,
dataIndex: "title"
},
{
id:"description",
header: _("Description"),
sortable: true,
dataIndex: "description"
},
{
id:"w",
header: _("W"),
sortable: true,
dataIndex: "w"
},
{
id:"h",
header: _("H"),
sortable: true,
dataIndex: "h"
}
];
this.tbar = [
{
disabled:true,
icon: _ico("plus-button"),
cls: "x-btn-text-icon",
text: _("Add"),
ref: "../btnCreate",
scope:this,
handler: this.cmpCreate
},
{
disabled:true,
icon: _ico("pencil"),
cls: "x-btn-text-icon",
text: _("Edit"),
ref: "../btnUpdate",
scope:this,
handler: this.cmpUpdate
},
'-',
{
disabled:true,
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
ref: "../btnDelete",
scope:this,
handler: this.cmpDelete
}
];
Ext.apply(this, {
disabled:true,
border:false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "description"
});
Inprint.advert.modules.Pages.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.advert.modules.Pages.superclass.onRender.apply(this, arguments);
},
cmpCreate: function() {
var wndw = this.components["create-window"];
if (!wndw) {
var flash = this.cmpCreateFlash();
var form = this.cmpCreateForm("create", this.urls.create);
wndw = this.cmpCreateWindow(_("Creating a new Page"), [ _BTN_WNDW_ADD, _BTN_WNDW_CLOSE ], form, flash);
this.components["create-window"] = wndw;
}
wndw.show(this);
var form = wndw.form.getForm();
form.reset();
form.findField("edition").setValue(this.parent.edition);
},
cmpUpdate: function() {
var wndw = this.components["update-window"];
if (!wndw) {
var flash = this.cmpCreateFlash();
var form = this.cmpCreateForm("update", this.urls.update);
wndw = this.cmpCreateWindow(_("Creating a new Module"), [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ], form, flash);
this.components["update-window"] = wndw;
}
wndw.show(this);
var form = wndw.form.getForm();
form.reset();
form.load({
url: this.urls.read,
scope:this,
params: {
id: this.getValue("id")
},
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
},
cmpDelete: function() {
Ext.MessageBox.confirm(
_("Warning"),
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
},
cmpCreateFlash: function() {
return {
xtype: "flash",
swfWidth:380,
swfHeight:360,
hideMode : 'offsets',
url : '/flash/Grid.swf',
expressInstall: true,
flashVars: {
src: '/flash/Grid.swf',
scale :'noscale',
autostart: 'yes',
loop: 'yes'
},
listeners: {
scope:this,
afterrender: function(panel) {
var init = function () {
if (panel.swf.init) {
panel.swf.init(panel.getSwfId(), "letter", 0, 0);
} else {
init.defer(100, this);
}
};
init.defer(100, this);
}
}
};
},
cmpCreateForm: function(mode, url) {
var fields = [
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
];
if (mode == "create") {
fields.unshift(_FLD_HDN_EDITION);
}
if (mode == "update") {
fields.unshift(_FLD_HDN_ID);
}
return {
xtype: "form",
frame:false,
border:false,
labelWidth: 75,
url: url,
bodyStyle: "padding:5px 5px",
baseParams: {
edition: this.parent.edition
},
defaults: {
anchor: "100%",
allowBlank:false
},
items: fields,
listeners: {
scope:this,
beforeaction: function(form, action) {
if (action.type == "submit") {
var flash = form.window.flash;
var panelid = form.window.form.getId();
flash.get("Inprint.flash.Proxy.setGrid", panelid);
}
},
actioncomplete: function (form, action) {
if (action.type == "load") {
var flash = form.window.flash;
var load = function () {
if (flash.init) {
flash.set(action.result.data.w, action.result.data.h);
} else {
load.defer(100, this);
}
};
load.defer(100, this);
}
if (action.type == "submit") {
form.window.hide();
this.cmpReload();
}
}
},
keys: [ _KEY_ENTER_SUBMIT ]
};
},
cmpCreateWindow: function(title, btns, form, flash) {
return new Ext.Window({
width:700,
height:500,
modal:true,
layout: "border",
closeAction: "hide",
title: title,
defaults: {
collapsible: false,
split: true
},
items: [
{ region: "center",
margins: "3 0 3 3",
layout:"fit",
items: form
},
{ region:"east",
margins: "3 3 3 0",
width: 380,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
items: flash
}
],
listeners: {
scope:this,
afterrender: function(panel) {
panel.flash = panel.findByType("flash")[0].swf;
panel.form = panel.findByType("form")[0];
panel.form.getForm().window = panel;
}
},
buttons: btns
});
}
});
<file_sep>Ext.namespace("Inprint.fascicle.template.composer");
<file_sep>Inprint.cmp.PrincipalsSelector = Ext.extend(Ext.Window, {
initComponent: function() {
this.panels = {};
this.panels.tree = new Inprint.cmp.PrincipalsSelector.Tree();
this.panels.principals = new Inprint.cmp.PrincipalsSelector.Principals();
this.panels.selection = new Inprint.cmp.PrincipalsSelector.Selection({
urlLoad: this.urlLoad
});
Ext.apply(this, {
title: _("Principals list"),
modal: true,
layout: "border",
width:800, height:500,
items: [
{
region: "center",
border:false,
layout:"border",
margins: "3 3 3 0",
items: [
{
region: "center",
layout:"fit",
margins: "3 3 3 0",
border:false,
items: this.panels.principals
},
{
region:"south",
layout:"fit",
margins: "3 0 3 3",
height: 180,
minSize: 50,
maxSize: 600,
collapsible: false,
split: true,
items: this.panels.selection
}
]
},
{
region:"west",
layout:"fit",
margins: "3 0 3 3",
width: 200,
minSize: 100,
maxSize: 600,
collapsible: false,
split: true,
items: this.panels.tree
}
]
});
Inprint.cmp.PrincipalsSelector.superclass.initComponent.apply(this, arguments);
Inprint.cmp.PrincipalsSelector.Interaction(this.panels);
this.relayEvents(this.panels.selection, ['save', 'delete']);
},
onRender: function() {
Inprint.cmp.PrincipalsSelector.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Ext.namespace("Inprint.cmp.membersList");
<file_sep>Inprint.cmp.Adverta = Ext.extend(Ext.Window, {
initComponent: function() {
this.panels = {};
this.panels.request = new Inprint.cmp.adverta.Request({
parent: this,
fascicle: this.fascicle
});
this.items = [];
this.items.push(this.panels.request);
if ( this.selection.length === 0 ) {
this.panels.templates = new Inprint.cmp.adverta.Templates({
parent: this,
fascicle: this.fascicle
});
this.items.push(this.panels.templates);
}
if ( this.selection.length > 0 ) {
this.panels.modules = new Inprint.cmp.adverta.Modules({
parent: this, fascicle: this.fascicle
});
this.panels.flash = new Inprint.cmp.adverta.Flash({
parent: this
});
this.items.push(this.panels.modules);
this.items.push(this.panels.flash);
}
var winWidth = 600 + (this.selection.length*260);
var title;
var btn;
if (this.mode == "create") {
title = _("Добавление рекламной заявки");
btn = _("Add");
}
if (this.mode == "update") {
title = _("Редактирование заявки");
btn = _("Save");
}
Ext.apply(this, {
border:false,
modal:true,
closeAction: "hide",
title: title,
width: winWidth,
height:600,
layout:'hbox',
layoutConfig: {
align : 'stretch',
pack : 'start'
},
buttons: [
{
text: btn,
scope:this,
handler: this.cmpSave
},
{
text: _("Close"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
Inprint.cmp.Adverta.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.Adverta.superclass.onRender.apply(this, arguments);
Inprint.cmp.Adverta.Interaction(this, this.panels);
this.panels.request.getForm().findField("id").setValue( this.request );
this.panels.request.getForm().findField("fascicle").setValue( this.fascicle );
},
cmpFill: function(record) {
var form = this.panels.request.getForm();
if (this.panels.modules) {
var modules = this.panels.modules.panels.modules;
if (record.data.module) {
if(modules.getNodeById(record.data.module)) {
modules.getNodeById(record.data.module).select();
}
}
}
if (record.data.id) {
form.findField("id").setValue(record.data.id);
}
if (record.data.advertiser && record.data.advertiser_shortcut) {
form.findField("advertiser").setValue(record.data.advertiser, record.data.advertiser_shortcut);
}
if (record.data.shortcut) {
form.findField("shortcut").setValue(record.data.shortcut);
}
if (record.data.description) {
form.findField("description").setValue(record.data.description);
}
if (record.data.status) {
form.findField("status").setValue(record.data.status);
}
if (record.data.squib) {
form.findField("squib").setValue(record.data.squib);
}
if (record.data.payment) {
form.findField("payment").setValue(record.data.payment);
}
if (record.data.readiness) {
form.findField("approved").setValue(record.data.readiness);
}
},
cmpSave: function() {
var form = this.panels.request.getForm();
// No pages selected
if ( this.selection.length == 0 ) {
form.baseParams = {
template: this.panels.templates.cmpGetValue()
};
}
// Some pages selected
if ( this.selection.length > 0 ) {
this.panels.flash.cmpSave();
if (this.panels.modules.panels.modules.cmpGetSelectedNode()) {
form.baseParams = {
module: this.panels.modules.panels.modules.cmpGetSelectedNode().attributes.module
};
}
}
if ( this.mode == "create") {
form.url = _url("/fascicle/requests/create/");
}
if ( this.mode == "update") {
form.url = _url("/fascicle/requests/update/");
}
form.submit();
}
});
<file_sep>Inprint.advert.index.Interaction = function(parent, panels) {
var editions = panels.editions;
var modules = panels.modules;
var headlines = panels.headlines;
// Tree
editions.getSelectionModel().on("selectionchange", function(sm, node) {
modules.disable();
headlines.disable();
if (node && node.attributes.type == "place") {
parent.edition = node.attributes.edition;
modules.enable();
modules.place = node.id;
modules.cmpLoad({ edition: parent.edition, place: modules.place });
headlines.enable();
headlines.place = node.id;
headlines.cmpLoad({ edition: parent.edition, place: headlines.place });
}
});
//Grids
modules.getSelectionModel().on("selectionchange", function(sm) {
_enable(modules.btnSave);
}, parent);
headlines.getSelectionModel().on("selectionchange", function(sm) {
_enable(headlines.btnSave);
}, parent);
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.ns("Inprint");
Ext.ns("Inprint.documents");
Ext.ns("Inprint.panel.tree");
Ext.ns("Inprint.grid.columns");
// Catalog
Ext.namespace("Inprint.catalog.editions");
Ext.namespace("Inprint.catalog.indexes");
Ext.namespace("Inprint.catalog.readiness");
Ext.BLANK_IMAGE_URL = '/extjs/resources/images/default/s.gif';
var EXTJS_VERSION = "3.4.0";
var EXTJS_PATH = "/extjs";
var NULLID = "00000000-0000-0000-0000-000000000000";
Inprint.log = function() {
if(console) {
console.log.apply(console, arguments);
}
}
Ext.onReady(function() {
Ext.QuickTips.init();
// Enable State Manager
var stateProvider = new Ext.ux.state.HttpProvider({
url:'/state/',
autoRead:false,
readBaseParams: {
cmd: 'read'
},
saveBaseParams: {
cmd: 'save'
}
});
Ext.state.Manager.setProvider(
stateProvider
);
Inprint.session = {
options: {}
};
Inprint.checkInProgress = false;
Inprint.checkSettings = function() {
if (Inprint.checkInProgress) {
return;
}
if (
!Inprint.session.member.title ||
!Inprint.session.member.shortcut ||
!Inprint.session.member.position ||
!Inprint.session.options ||
!Inprint.session.options["default.edition"] ||
!Inprint.session.options["default.edition.name"] ||
!Inprint.session.options["default.workgroup"] ||
!Inprint.session.options["default.workgroup.name"]
) {
if (Inprint.session.member.login != "root") {
Inprint.checkInProgress = true;
var setupWindow = new Inprint.cmp.memberSetupWindow();
setupWindow.on("hide", function() {
Inprint.checkInProgress = false;
});
setupWindow.show();
}
}
};
// Start session manager
Inprint.startSession = function(defer) {
Ext.Ajax.request({
url: '/workspace/startsession/',
scope: this,
success: function(response) {
Inprint.session = Ext.util.JSON.decode( response.responseText );
// Restore state data
var stateProvider = Ext.state.Manager.getProvider();
Ext.each(Inprint.session.state, function(item) {
stateProvider.state[item.name] = stateProvider.decodeValue(item.value);
}, this);
// Enable layout
Inprint.layout = new Inprint.Workspace();
// Remove loading mask
Ext.get('loading').remove();
Ext.get('loading-mask').fadeOut({remove:true});
// Resolve url
var params = Ext.urlDecode( window.location.search.substring( 1 ) );
if (Inprint.registry[ params.aid ]){
Inprint.ObjectResolver.resolve({
aid: params.aid,
oid: params.oid,
pid: params.pid,
text: params.text,
description: params.description
});
}
Inprint.checkSettings();
Inprint.updateSession.defer( 90000, this, [ true ]);
}
});
};
Inprint.updateSession = function(defer) {
Ext.Ajax.request({
url: '/workspace/updatesession/',
scope: this,
success: function(response) {
Inprint.session = Ext.util.JSON.decode( response.responseText );
if (Inprint.session && Inprint.session.member.id ){
if (defer) {
Inprint.updateSession.defer( 90000, this, [ true ]);
}
return;
}
Ext.MessageBox.alert(
_("Your session is closed"),
_("Probably someone has entered in Inprint with your login on other computer. <br/> push F5 what to pass to authorization page"),
function() {});
}
});
};
Inprint.startSession(true);
});
<file_sep>Inprint.plugins.rss.control.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.panels = {};
this.panels.tree = new Inprint.plugins.rss.control.Tree();
this.panels.grid = new Inprint.plugins.rss.control.Grid();
this.panels.help = new Inprint.plugins.rss.control.HelpPanel();
Ext.apply(this, {
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
title: _("Feeds"),
region:"west",
margins: "3 0 3 3",
width: 200,
minSize: 200,
maxSize: 600,
layout:"fit",
items: this.panels.tree
},
{
title: _("Indexation"),
region: "center",
layout:"fit",
margins: "3 0 3 0",
items: this.panels.grid
},
{
region:"east",
margins: "3 3 3 0",
width: 400,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
items: this.panels.help
}
]
});
Inprint.plugins.rss.control.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.plugins.rss.control.Panel.superclass.onRender.apply(this, arguments);
Inprint.plugins.rss.control.Access(this, this.panels);
Inprint.plugins.rss.control.Interaction(this, this.panels);
Inprint.plugins.rss.control.Context(this, this.panels);
},
getRow: function() {
return this.panels.grid.getSelectionModel().getSelected().data;
},
cmpReload:function() {
this.panels.tree.cmpReload();
}
});
Inprint.registry.register("plugin-rss-control", {
icon: "feed",
text: _("RSS feeds"),
xobject: Inprint.plugins.rss.control.Panel
});
<file_sep>Inprint.calendar.forms.CopyAttachmentForm = Ext.extend( Ext.form.FormPanel,
{
initComponent: function()
{
this.items = [
{
xtype: "hidden",
name: "source",
allowBlank:false
},
{
xtype: "treecombo",
hiddenName: "issue",
rootVisible:false,
minListWidth: 300,
fieldLabel: _("Fascicle"),
emptyText: _("Fascicle"),
url: _url('/common/tree/fascicles/'),
root: { id:'all', nodeType: 'async' },
baseParams: { attachments: 0, term: 'editions.fascicle.view:*' },
listeners: {
scope: this,
select: function(combo, record) {
var attachment = this.getForm().findField("edition");
attachment.enable();
attachment.root.id = record.attributes.edition;
var root = attachment.getTree().getRootNode();
root.id = record.attributes.edition;
root.reload();
}
}
},
{
xtype: "treecombo",
disabled:true,
hiddenName: "edition",
rootVisible: false,
minListWidth: 300,
autoLoad:false,
fieldLabel: _("Attachment"),
emptyText: _("Attachment..."),
url: _url('/common/tree/editions/'),
root: { id:'none', nodeType: 'async' },
baseParams: { term: 'editions.attachment.manage:*' }
},
{
xtype: "checkbox",
fieldLabel: _("Confirmation"),
boxLabel: _("I understand the risk"),
name: "confirmation"
}
];
Ext.apply(this, {
border:false,
baseCls: 'x-plain',
bodyStyle:'padding:10px',
defaults: { anchor: '100%' }
});
Inprint.calendar.forms.CopyAttachmentForm.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.calendar.forms.CopyAttachmentForm.superclass.onRender.apply(this, arguments);
this.getForm().url = _source("attachment.copy");
},
setSource: function(id) {
this.cmpSetValue("source", id);
}
});
<file_sep>Inprint.cmp.adverta.GridModules = Ext.extend(Ext.ux.tree.TreeGrid, {
initComponent: function() {
this.params = {};
this.components = {};
this.urls = {
"list": "/fascicle/composer/modules/",
"create": _url("/fascicle/modules/create/"),
"delete": _url("/fascicle/modules/delete/")
};
this.columns = [
{
id:"title",
width: 120,
header: _("Title"),
dataIndex: "title"
},
{
id:"place_title",
width: 90,
header: _("Place"),
dataIndex: "place_title",
tpl : new Ext.XTemplate('{format:this.formatString}', {
formatString : function(v, record) {
var amount = record.amount;
var place = record.place_title;
if (amount && place) {
return String.format("{0} / {1}", amount, place);
}
return "";
}
})
}
];
this.loader = new Ext.tree.TreeLoader({
dataUrl: this.urls.list,
baseParams: {
page: this.parent.selection,
filter: "unmapped, unrequested"
}
});
Ext.apply(this, {
layout:"fit",
region: "center",
title: _("Modules"),
enableSort : false,
enableDrop: true,
ddGroup: 'TreeDD',
dropConfig: {
dropAllowed : true,
notifyDrop : function (source, e, data) {
this.tree.fireEvent("templateDroped", source.dragData.node.id);
this.cancelExpand();
return true;
},
onContainerOver: function(source, e, data) {
return "x-tree-drop-ok-append";
}
}
});
Inprint.cmp.adverta.GridModules.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.adverta.GridModules.superclass.onRender.apply(this, arguments);
},
cmpGetSelectedNode: function() {
return this.getSelectionModel().getSelectedNode();
},
cmpReload: function() {
this.getRootNode().reload();
},
cmpDelete: function() {
Ext.MessageBox.confirm(
_("Warning"),
_("You really wish to do this?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: function() {
this.cmpReload();
this.parent.panels.flash.cmpInit();
},
params: {
id: this.cmpGetSelectedNode().attributes.module,
fascicle: this.parent.fascicle
}
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.form.TitleField = Ext.extend(Ext.BoxComponent, {
autoCreate: { tag: 'div' },
initComponent: function() {
this.style = "background:#DDDDDD;padding:4px;margin-bottom:5px;";
if (this.margin) {
this.style += "margin-top:"+ this.margin+"px;";
}
Ext.form.TitleField.superclass.initComponent.apply(this);
},
onRender: function() {
Ext.form.TitleField.superclass.onRender.apply(this, arguments);
this.el.dom.innerHTML = '<b>'+ this.value+'</b>';
}
});
Ext.reg('titlefield', Ext.form.TitleField);
<file_sep>Inprint.calendar.forms.CreateIssueForm = Ext.extend( Ext.form.FormPanel, {
initComponent: function()
{
this.items = [
{
xtype: "titlefield",
value: _("Basic parameters")
},
{
xtype: "textfield",
name: "shortcut",
allowBlank:false,
fieldLabel: _("Shortcut")
},
{
xtype: "textfield",
name: "description",
fieldLabel: _("Description")
},
{
allowBlank:false,
xtype: "treecombo",
name: "edition-shortcut",
hiddenName: "edition",
fieldLabel: _("Edition"),
emptyText: _("Edition") + "...",
minListWidth: 300,
url: _url('/common/tree/editions/'),
baseParams: {
term: 'editions.fascicle.manage:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("All editions")
},
listeners: {
scope: this,
render: function(field) {
var id = Inprint.session.options["default.edition"];
var title = Inprint.session.options["default.edition.name"] || _("Unknown edition");
if (id && title) {
field.setValue(id, title);
}
}
}
},
Inprint.factory.Combo.create(
"/calendar/combos/copyfrom/", {
fieldLabel: _("Copy from"),
name: "source",
listeners: {
render: function(combo) {
combo.setValue("00000000-0000-0000-0000-000000000000", _("Defaults"));
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
}),
{
xtype: "textfield",
name: "num",
fieldLabel: _("Number")
},
{
xtype: "textfield",
name: "anum",
fieldLabel: _("Annual number")
},
{
xtype: "numberfield",
name: "circulation",
fieldLabel: _("Circulation"),
value: 0
},
{
xtype: "titlefield",
value: _("Restrictions")
},
{
labelWidth: 20,
xtype: "xdatetime",
name: "doc_date",
format: "F j, Y",
fieldLabel: _("Documents")
},
{
xtype: 'xdatetime',
name: 'adv_date',
format:'F j, Y',
fieldLabel: _("Advertisement")
},
{
xtype: "numberfield",
name: "adv_modules",
fieldLabel: _("Modules")
},
{
xtype: "titlefield",
value: _("Deadline")
},
{
format:'F j, Y',
name: 'print_date',
xtype: 'xdatefield',
submitFormat:'Y-m-d',
fieldLabel: _("To print")
},
{
xtype: 'xdatefield',
name: 'release_date',
format:'F j, Y',
submitFormat:'Y-m-d',
fieldLabel: _("To publication")
}
];
Ext.apply(this, {
baseCls: 'x-plain',
defaults:{ anchor:'98%' }
});
Inprint.calendar.forms.CreateIssueForm.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.calendar.forms.CreateIssueForm.superclass.onRender.apply(this, arguments);
this.getForm().url = _source("issue.create");
this.getForm().findField("print_date").on("select", function(field, date){
this.getForm().findField("shortcut").setValue(
date.format("d/m/y")
);
}, this)
}
});
<file_sep>Inprint.cmp.memberRules = Ext.extend(Ext.Window, {
initComponent: function() {
this.panels = {};
this.panels.grid = new Inprint.cmp.memberRules.Grid();
Ext.apply(this, {
title: _("Review of access rights"),
modal: true,
layout: "fit",
closeAction: "hide",
width:800, height:400,
items: this.panels.grid
});
Inprint.cmp.memberRules.superclass.initComponent.apply(this, arguments);
Inprint.cmp.memberRules.Interaction(this, this.panels);
},
onRender: function() {
Inprint.cmp.memberRules.superclass.onRender.apply(this, arguments);
}
});
Inprint.registry.register("employee-access", {
icon: "key",
text: _("Access"),
handler: function() {
new Inprint.cmp.memberRules().show();
}
});<file_sep>Inprint.cmp.memberProfileForm.Interaction = function(panels) {
};
<file_sep>Inprint.cmp.memberRules.Grid = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.store = Inprint.factory.Store.json("/catalog/members/rules/", {
autoLoad: true
});
this.columns = [
{
id:"shortcut",
width: 28,
sortable: true,
dataIndex: "area",
renderer: function(value, p, record) {
if (value == "domain") {
return '<img src="'+ _ico("building") +'">';
}
if (value == "edition") {
return '<img src="'+ _ico("book") +'">';
}
if (value == "group") {
return '<img src="'+ _ico("folder") +'">';
}
if (value == "member") {
return '<img src="'+ _ico("user-business") +'">';
}
return '';
}
},
{
id:"binding",
header: _("Binding"),
width: 80,
sortable: true,
dataIndex: "binding_shortcut"
},
{
id:"rules",
header: _("Rules"),
width: 160,
sortable: true,
dataIndex: "rules",
renderer: function(value, p, record) {
return value.join(",");
}
}
];
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
autoExpandColumn: "rules"
});
Inprint.cmp.memberRules.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.memberRules.Grid.superclass.onRender.apply(this, arguments);
}
});
<file_sep>DROP TABLE fascicles_options;
DROP FUNCTION access_delete_after_trigger() CASCADE;
DROP FUNCTION access_insert_after_trigger() CASCADE;
DROP FUNCTION access_update_after_trigger() CASCADE;
DROP FUNCTION rules_delete_after_trigger() CASCADE;
DROP FUNCTION rules_insert_after_trigger() CASCADE;
DROP TABLE cache_access;
DROP TABLE cache_visibility;
-- Insert editions rules
DELETE FROM rules WHERE id = '9d057494-c2c6-41f5-9276-74b33b55c6e3';
UPDATE rules SET sortorder = 70 WHERE id = 'aa4e74ad-116e-4bb2-a910-899c4f288f40';
DELETE FROM rules WHERE section = 'editions';
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('e6ecbbda-a3c2-49de-ab4a-df127bd467a6', 'editions', 'calendar', 'view', 10, 'Can view calendar', 'calendar-day', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('63bd8ded-a884-4b5f-95f2-2797fb3ad6bb', 'editions', 'template', 'view', 20, 'Can view templates', 'puzzle', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('2f585b7b-bfa8-4a9f-a33b-74771ce0e89b', 'editions', 'template', 'manage', 30, 'Can manage templates', 'puzzle--pencil', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('09584423-a443-4f1c-b5e2-8c1a27a932b4', 'editions', 'fascicle', 'view', 40, 'Can view fascicles', 'blue-folder', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('901b9596-fb88-412c-b89a-945d162b0992', 'editions', 'fascicle', 'manage', 50, 'Can manage fascicles', 'blue-folder--pencil', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('6ae65650-6837-4fca-a948-80ed6a565e25', 'editions', 'attachment', 'view', 60, 'Can view attachments', 'folder', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('ed8eac8e-370d-463c-a7ee-39ed5ee04a3f', 'editions', 'attachment', 'manage', 70, 'Can manage attachments', 'folder--pencil', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('30f27d95-c935-4940-b1db-e1e381fd061f', 'editions', 'advert', 'view', 80, 'Can view advertising', 'money', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('2b6a5a8a-390f-4dae-909b-fcc93c5740fd', 'editions', 'advert', 'manage', 90, 'Can manage advertising', 'money--pencil', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('133743df-52ab-4277-b320-3ede5222cb12', 'editions', 'documents', 'work', 100, 'Can manage documents', 'document-word', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('52dc7f72-2057-43c0-831d-55e458d84f39', 'editions', 'documents', 'assign', 110, 'Can assign fascicle', 'document-word', '');
-- Insert documents rules
DELETE FROM rules WHERE section = 'catalog';
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('ac0a0d95-c4d3-4bd7-93c3-cc0fc230936f', 'catalog', 'documents', 'view', 10, 'Can view materials', 'document', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('ee992171-d275-4d24-8def-7ff02adec408', 'catalog', 'documents', 'create', 20, 'Can create materials', 'document--plus', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('3040f8e1-051c-4876-8e8e-0ca4910e7e45', 'catalog', 'documents', 'delete', 30, 'Can delete materials', 'bin', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('beba3e8d-86e5-4e98-b3eb-368da28dba5f', 'catalog', 'documents', 'recover', 40, 'Can recover materials', 'bin--arrow', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('5b27108a-2108-4846-a0a8-3c369f873590', 'catalog', 'documents', 'update', 50, 'Can edit the profile', 'card--pencil', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('6d590a90-58a1-447f-b5ad-b0582b64571a', 'catalog', 'documents', 'discuss', 60, 'Can discuss the materials', 'balloon-left', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('6033984a-a762-4392-b086-a8d2cdac4221', 'catalog', 'documents', 'assign', 70, 'Can assign the editor', 'user-business', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('6d590a90-58a1-447f-b5ad-e3c62f80a2ef', 'catalog', 'documents', 'briefcase', 80, 'Can put in a briefcase', 'briefcase', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('d782679e-3f0a-4499-bda6-8c2600a3e761', 'catalog', 'documents', 'capture', 90, 'Can capture materials', 'hand', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('b946bd84-93fc-4a70-b325-d23c2804b2e9', 'catalog', 'documents', 'transfer', 100, 'Can transfer materials', 'document-import', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('b7adafe9-2d5b-44f3-aa87-681fd48466fa', 'catalog', 'documents', 'move', 110, 'Can move materials', 'blue-folder-import', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('bff78ebf-2cba-466e-9e3c-89f13a0882fc', 'catalog', 'documents', 'fedit', 120, 'Can work with files', 'disk', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('f4ad42ed-b46b-4b4e-859f-1b69b918a64a', 'catalog', 'documents', 'fadd', 130, 'Can add files', 'disk--plus', '');
INSERT INTO rules(id, section, subsection, term, sortorder, title, icon, description)
VALUES ('fe9cd446-2f4b-4844-9b91-5092c0cabece', 'catalog', 'documents', 'fdelete', 140, 'Can delete files', 'disk--minus', '');
-- Update translation
UPDATE rules SET title = 'Может входит в программу' WHERE id = '2fde426b-ed30-4376-9a7b-25278e8f104a';
UPDATE rules SET title = 'Может просматривать конфигурацию' WHERE id = '6406ad57-c889-47c5-acc6-0cd552e9cf5e';
UPDATE rules SET title = 'Может управлять отделами' WHERE id = 'e55d9548-36fe-4e51-bec2-663235b5383e';
UPDATE rules SET title = 'Может управлять сотрудниками' WHERE id = '32e0bb97-2bae-4ce8-865e-cdf0edb3fd93';
UPDATE rules SET title = 'Может управлять изданиями' WHERE id = '2a3cae11-23ea-41c3-bdb8-d3dfdc0d486a';
UPDATE rules SET title = 'Может управлять движением' WHERE id = '086993e0-56aa-441f-8eaf-437c1c5c9691';
UPDATE rules SET title = 'Может управлять ролями' WHERE id = '9d057494-c2c6-41f5-9276-74b33b55c6e3';
UPDATE rules SET title = 'Может управлять готовностью' WHERE id = 'aa4e74ad-116e-4bb2-a910-899c4f288f40';
UPDATE rules SET title = 'Может управлять рубрикатором' WHERE id = '9a756e9c-243a-4f5e-b814-fe3d1162a5e9';
-- Editions Rules
UPDATE rules SET title = 'Может просматривать календарь' WHERE id = 'e6ecbbda-a3c2-49de-ab4a-df127bd467a6';
UPDATE rules SET title = 'Может просматривать шаблоны' WHERE id = '63bd8ded-a884-4b5f-95f2-2797fb3ad6bb';
UPDATE rules SET title = 'Может управлять шаблонами' WHERE id = '2f585b7b-bfa8-4a9f-a33b-74771ce0e89b';
UPDATE rules SET title = 'Может просматривать выпуск' WHERE id = '09584423-a443-4f1c-b5e2-8c1a27a932b4';
UPDATE rules SET title = 'Может управлять выпусками' WHERE id = '901b9596-fb88-412c-b89a-945d162b0992';
UPDATE rules SET title = 'Может просматривать вкладки' WHERE id = '6ae65650-6837-4fca-a948-80ed6a565e25';
UPDATE rules SET title = 'Может управлять вкладками' WHERE id = 'ed8eac8e-370d-463c-a7ee-39ed5ee04a3f';
UPDATE rules SET title = 'Может просматривать рекламу' WHERE id = '30f27d95-c935-4940-b1db-e1e381fd061f';
UPDATE rules SET title = 'Может управлять рекламой' WHERE id = '2b6a5a8a-390f-4dae-909b-fcc93c5740fd';
UPDATE rules SET title = 'Может работать с материалами' WHERE id = '133743df-52ab-4277-b320-3ede5222cb12';
UPDATE rules SET title = 'Может назначать выпуск' WHERE id = '52dc7f72-2057-43c0-831d-55e458d84f39';
-- Catalog Rules
UPDATE rules SET title = 'Может просматривать материалы' WHERE id = 'ac0a0d95-c4d3-4bd7-93c3-cc0fc230936f';
UPDATE rules SET title = 'Может создавать материалы' WHERE id = 'ee992171-d275-4d24-8def-7ff02adec408';
UPDATE rules SET title = 'Может назначать отдел' WHERE id = '6033984a-a762-4392-b086-a8d2cdac4221';
UPDATE rules SET title = 'Может удалять материалы' WHERE id = '3040f8e1-051c-4876-8e8e-0ca4910e7e45';
UPDATE rules SET title = 'Может восстанавливать материалы' WHERE id = 'beba3e8d-86e5-4e98-b3eb-368da28dba5f';
UPDATE rules SET title = 'Может редактировать профиль' WHERE id = '5b27108a-2108-4846-a0a8-3c369f873590';
UPDATE rules SET title = 'Может работать с файлами' WHERE id = 'bff78ebf-2cba-466e-9e3c-89f13a0882fc';
UPDATE rules SET title = 'Может добавлять файлы' WHERE id = 'f4ad42ed-b46b-4b4e-859f-1b69b918a64a';
UPDATE rules SET title = 'Может удалять файлы' WHERE id = 'fe9cd446-2f4b-4844-9b91-5092c0cabece';
UPDATE rules SET title = 'Может захватывать материалы' WHERE id = 'd782679e-3f0a-4499-bda6-8c2600a3e761';
UPDATE rules SET title = 'Может передавать материалы' WHERE id = 'b946bd84-93fc-4a70-b325-d23c2804b2e9';
UPDATE rules SET title = 'Может перемещать материалы' WHERE id = 'b7adafe9-2d5b-44f3-aa87-681fd48466fa';
UPDATE rules SET title = 'Может перемещать в портфель' WHERE id = '6d590a90-58a1-447f-b5ad-e3c62f80a2ef';
UPDATE rules SET title = 'Может учавствовать в обсуждении' WHERE id = '6d590a90-58a1-447f-b5ad-b0582b64571a';
<file_sep>Inprint.catalog.indexes.Rubrics = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.headline = null;
this.store = Inprint.factory.Store.json("/catalog/rubrics/list/");
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"title",
header: _("Title"),
width: 160,
sortable: true,
dataIndex: "title"
},
{
id:"description",
header: _("Description"),
dataIndex: "description"
}
];
this.tbar = [
Inprint.getButton("create.item"),
Inprint.getButton("update.item"),
Inprint.getButton("delete.item")
];
Ext.apply(this, {
title: _("Rubrics"),
border: false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "description"
});
Inprint.catalog.indexes.Rubrics.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.catalog.indexes.Rubrics.superclass.onRender.apply(this, arguments);
},
getHeadline: function() {
return this.edition;
},
setHeadline: function(id) {
this.edition = id;
}
});
<file_sep>Inprint.fascicle.plan.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.fascicle = this.oid;
this.panels = {
pages: new Inprint.fascicle.planner.Pages({
parent: this,
oid: this.oid
})
};
this.tbar = [
"->",
{
width: 100,
value:50,
xtype: "slider",
increment: 50,
minValue: 0,
maxValue: 100,
listeners: {
scope:this,
'afterrender': function (slider) {
var value = Ext.state.Manager.get("planner.page.size");
if (value >= 0 || value <= 100) {
slider.setValue(value);
}
},
'changecomplete': function(slider, value) {
this.panels.pages.cmpResize(value);
}
}
},
"-",
{
text: _("Fascicle") + "/A4",
icon: _ico("printer"),
cls: 'x-btn-text-icon',
scope:this,
handler: function() {
window.location = "/fascicle/print/"+ this.oid +"/landscape/a4";
}
},
{
text: _("Fascicle") + "/A3",
icon: _ico("printer"),
cls: 'x-btn-text-icon',
scope:this,
handler: function() {
window.location = "/fascicle/print/"+ this.oid +"/landscape/a3";
}
},
{
text: _("Advertising"),
icon: _ico("printer"),
cls: 'x-btn-text-icon',
scope:this,
handler: function() {
window.location = "/reports/advertising/fascicle/"+ this.oid;
}
}
];
Ext.apply(this, {
layout: 'fit',
autoScroll:true,
items: this.panels.pages
});
Inprint.fascicle.plan.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.plan.Panel.superclass.onRender.apply(this, arguments);
this.cmpInitSession();
},
cmpInitSession: function () {
this.body.mask("Обновление данных...");
Ext.Ajax.request({
url: _url("/fascicle/seance/"),
scope: this,
params: {
fascicle: this.oid
},
callback: function() {
this.body.unmask();
},
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
var access = rsp.data.access;
var fascicle = rsp.data.fascicle;
var summary = rsp.data.summary;
var advertising = rsp.data.advertising;
var composition = rsp.data.composition;
var documents = rsp.data.documents;
var requests = rsp.data.requests;
var shortcut = rsp.data.fascicle.shortcut;
var description = "";
if (access.manager) {
description += ' [<b>Работает '+ access.manager_shortcut +'</b>]';
}
description += ' [Полос '+ summary.pc +'='+ summary.dc +'+'+ summary.ac;
description += ' | '+ summary.dav +'%/'+ summary.aav +'%]';
var title = Inprint.ObjectResolver.makeTitle(this.parent.aid, this.parent.oid, null, this.parent.icon, shortcut, description);
this.parent.setTitle(title);
if (composition) {
this.panels.pages.getView().cmpLoad({ data: composition });
}
}
});
},
cmpReload: function() {
this.cmpInitSession();
}
});
Inprint.registry.register("fascicle-plan", {
icon: "table",
text: _("Fascicle plan"),
xobject: Inprint.fascicle.plan.Panel
});
<file_sep>Inprint.fascicle.planner.Requests = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.components = {};
this.urls = {
"create": _url("/fascicle/requests/create/"),
"read": _url("/fascicle/requests/read/"),
"update": _url("/fascicle/requests/update/"),
"delete": _url("/fascicle/requests/delete/"),
"move": _url("/fascicle/requests/move/")
};
this.store = Inprint.factory.Store.json("/fascicle/requests/list/", {
remoteSort:true,
baseParams: {
flt_fascicle: this.oid
}
});
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
var columns = Inprint.grid.columns.Request();
this.colModel = new Ext.grid.ColumnModel({
defaults: {
sortable: true,
menuDisabled:true
},
columns: [
this.selectionModel,
columns.serial,
columns.advertiser,
columns.manager,
columns.title,
columns.position,
columns.template,
columns.module,
columns.pages,
columns.status,
columns.payment,
columns.readiness,
columns.modified
]
});
this.tbar = [
{
icon: _ico("plus-button"),
cls: "x-btn-text-icon",
text: _("Add"),
disabled:true,
ref: "../btnCreate",
scope:this,
handler: this.cmpCreate
},
{
icon: _ico("pencil"),
cls: "x-btn-text-icon",
text: _("Update"),
disabled:true,
ref: "../btnUpdate",
scope:this,
handler: this.cmpUpdateProxy
},
{
ref: "../btnMove",
disabled:true,
text:'Перенести',
icon: _ico("navigation-000-button"),
cls: 'x-btn-text-icon',
scope:this,
handler: this.cmpMove
},
'-',
{
ref: "../btnChangeModule",
disabled:true,
text:'Изменить модуль',
icon: _ico("navigation-000-button"),
cls: 'x-btn-text-icon',
scope:this,
handler: this.cmpMove
},
'-',
{
icon: _ico("minus-button"),
cls: "x-btn-text-icon",
text: _("Remove"),
disabled:true,
ref: "../btnDelete",
scope:this,
handler: this.cmpDelete
},
"->",
{
ref: "../btnSwitchToDocuments",
text: 'Документы',
icon: _ico("document-word"),
cls: 'x-btn-text-icon',
scope:this
},
{
ref: "../btnSwitchToRequests",
text: 'Заявки',
icon: _ico("document-excel"),
cls: 'x-btn-text-icon',
pressed: true,
scope:this
}
];
Ext.apply(this, {
border: false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "title"
});
Inprint.fascicle.planner.Requests.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.planner.Requests.superclass.onRender.apply(this, arguments);
},
cmpCreate: function() {
var pages = this.parent.panels.pages;
var fascicle = this.oid;
var selection = pages.cmpGetSelected();
if (selection.length > 2) {
return;
}
var wndw = new Inprint.cmp.Adverta({
mode: "create",
fascicle: this.parent.fascicle,
selection: selection
});
wndw.on("actionfailed", function(form, action) {
if (action.failureType == "server") {
var message = "";
Ext.each(action.result.errors, function(record) {
message += _(record.msg);
});
Ext.MessageBox.show({
title: _('Error!'),
msg: message,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.ERROR
});
}
}, this);
wndw.on("actioncomplete", function() {
wndw.close();
this.parent.cmpReload();
}, this);
wndw.on("hide", function() {
this.parent.cmpReload();
}, this);
wndw.on("close", function() {
this.parent.cmpReload();
}, this);
wndw.show();
},
cmpUpdateProxy: function () {
Ext.Ajax.request({
url: this.urls.read,
params: {
fascicle: this.oid,
request: this.getValue("id")
},
scope: this,
success: function(responce) {
var record = Ext.util.JSON.decode(responce.responseText);
this.cmpUpdate(record);
}
});
},
cmpUpdate: function(record) {
if (!record.data.id) {
return;
}
if (record.data.pages.length > 2) {
return;
}
var wndw = new Inprint.cmp.Adverta({
mode: "update",
record: record.data,
fascicle: this.oid,
selection: record.data.pages
});
wndw.on("actioncomplete", function() {
this.parent.cmpReload();
}, this);
wndw.show();
wndw.cmpFill(record);
},
cmpMove: function(inc) {
var wndw = this.components.move;
if (!wndw) {
wndw = new Ext.Window({
title: 'Перемещение заявки',
width:250,
height:140,
modal:true,
draggable:true,
layout: "fit",
closeAction: "hide",
items: {
xtype: "form",
border: false,
url: this.urls.move,
labelWidth: 60,
defaultType: 'checkbox',
defaults: { anchor: '100%', hideLabel:true },
bodyStyle: 'padding:10px;',
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
this.parent.cmpReload();
}
},
items: [
{
xtype: 'checkbox',
name: 'move-request',
checked:false,
inputValue: 'true',
fieldLabel: '',
labelSeparator: ':',
boxLabel: 'Переместить заявку'
},
{
xtype: 'checkbox',
name: 'move-module',
checked:false,
inputValue: 'true',
fieldLabel: '',
labelSeparator: '',
boxLabel: 'Переместить модуль'
}
]
},
buttons: [
_BTN_WNDW_OK,
_BTN_WNDW_CANCEL
]
});
this.components.move = wndw;
}
var form = wndw.findByType("form")[0].getForm();
form.reset();
form.baseParams = {
fascicle: this.oid,
request: this.getValue("id"),
page: this.parent.panels.pages.cmpGetSelected()
};
wndw.show();
},
cmpDelete: function() {
var wndw = this.components["delete"];
if (!wndw) {
wndw = new Ext.Window({
title: 'Удаление заявки',
width:250,
height:140,
modal:true,
draggable:true,
layout: "fit",
closeAction: "hide",
items: {
xtype: "form",
border: false,
url: this.urls["delete"],
labelWidth: 60,
defaultType: 'checkbox',
defaults: { anchor: '100%', hideLabel:true },
bodyStyle: 'padding:10px;',
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
this.parent.cmpReload();
}
},
items: [
{
xtype: 'checkbox',
name: 'delete-request',
checked:false,
inputValue: 'true',
fieldLabel: '',
labelSeparator: ':',
boxLabel: 'Удалить заявку'
},
{
xtype: 'checkbox',
name: 'delete-module',
checked:false,
inputValue: 'true',
fieldLabel: '',
labelSeparator: '',
boxLabel: 'Удалить модуль'
}
]
},
buttons: [
_BTN_WNDW_OK,
_BTN_WNDW_CANCEL
]
});
this.components["delete"] = wndw;
}
var form = wndw.findByType("form")[0].getForm();
form.reset();
form.baseParams = {
fascicle: this.oid,
request: this.getValues("id")
};
wndw.show();
}
});
<file_sep>Inprint.advertising.downloads.Interaction = function(parent, panels) {
var fascicles = panels.fascicles;
var requests = panels.requests;
var summary = panels.summary;
var files = panels.files;
var comments = panels.comments;
var fascicle = null;
// Tree
fascicles.getSelectionModel().on("selectionchange", function(sm, node) {
_disable( requests, summary, files, comments );
if (node) {
fascicle = node.id;
requests.enable();
requests.setFascicle(fascicle);
requests.cmpLoad({ flt_fascicle: fascicle });
summary.enable();
summary.setFascicle(fascicle);
summary.cmpLoad({ flt_fascicle: fascicle });
}
});
//Grids
requests.getSelectionModel().on("rowselect", function(sm, index, record) {
files.enable();
files.setPkey(record.get("id"));
files.btnUpload.enable();
files.cmpLoad({
request: record.get("id")
});
comments.enable();
comments.btnSay.enable();
comments.cmpLoad(record.get("id"));
});
};
<file_sep>Ext.ns("Inprint.panels");<file_sep>Inprint.documents.editor.versions.Browser = Ext.extend( Ext.list.ListView, {
initComponent: function() {
this.config = {};
var store = new Ext.data.JsonStore({
url: this.url + "/list/",
root: 'data',
baseParams: {
file: this.oid
},
fields: [
'id', 'creator', 'branch', 'stage', 'color', 'created'
]
});
Ext.apply(this, {
border:false,
store: store,
singleSelect: true,
emptyText: _("No versions to display"),
columns: [
{
header: _(""),
width: .03,
dataIndex: "color",
tpl: '<div style="background:#{color};width:20px;"> </div>'
},
{
header: _("Stage"),
width: .15,
dataIndex: "stage"
},
{
header: _("Empoyee"),
width: .15,
dataIndex: "creator"
},
{
header: _("Date"),
dataIndex: "created"
}
]
});
Inprint.documents.editor.versions.Browser.superclass.initComponent.apply(this, arguments);
},
// Override other inherited methods
onRender: function(){
Inprint.documents.editor.versions.Browser.superclass.onRender.apply(this, arguments);
this.on("selectionchange", function(dataview, selection) {
if (selection.length == 1){
this.parent.btnView.enable();
var record = this.getRecord(selection[0]);
this.config.selection = record.get("id");
}
else if (selection.length !== 0){
this.parent.btnView.disable();
}
}, this);
this.on("dblclick", function(dataview, number, node, e) {
this.parent.btnView.enable();
var record = this.getRecord(node);
this.config.selection = record.get("id");
this.parent.cmpClick();
}, this);
},
cmpReload: function() {
this.getStore().reload();
}
});
<file_sep>Inprint.plugins.rss.Access = function(parent, panels) {
var grid = panels.grid;
grid.btnSave.enable();
grid.getSelectionModel().on("selectionchange", function(sm) {
var records = grid.getSelectionModel().getSelections();
var access = _arrayAccessCheck(records, ['manage']);
_disable(grid.btnPublish, grid.btnUnpublish);
if (access.manage == 'enabled') {
_enable(grid.btnPublish, grid.btnUnpublish);
}
});
};
<file_sep>Inprint.advert.modules.Interaction = function(parent, panels) {
var tree = panels.editions;
var pages = panels.pages;
var modules = panels.modules;
// Tree
tree.getSelectionModel().on("selectionchange", function(sm, node) {
pages.disable();
if (node) {
parent.edition = node.attributes.id;
pages.enable();
pages.btnCreate.enable();
pages.cmpLoad({ edition: node.attributes.id });
}
});
//Grids
pages.getSelectionModel().on("selectionchange", function(sm) {
_disable(modules.btnCreate, pages.btnUpdate, pages.btnDelete);
if (sm.getCount() === 0) {
modules.disable();
}
if (sm.getCount() == 1) {
modules.enable();
modules.pageId = pages.getValue("id");
modules.pageW = pages.getValue("w");
modules.pageH = pages.getValue("h");
if (modules.pageId && modules.pageW.length > 0 && modules.pageH.length > 0) {
modules.btnCreate.enable();
}
modules.cmpLoad({ page: modules.pageId });
}
if (sm.getCount() == 1) {
_enable(pages.btnUpdate, pages.btnDelete);
} else if (sm.getCount() > 1) {
_enable(pages.btnDelete);
}
}, parent);
modules.getSelectionModel().on("selectionchange", function(sm) {
_disable(modules.btnUpdate, modules.btnDelete);
if (sm.getCount() == 1) {
_enable(modules.btnUpdate, modules.btnDelete);
} else if (sm.getCount() > 1) {
_enable(modules.btnDelete);
}
}, parent);
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.documents.archive.Panel = Ext.extend(Inprint.documents.Grid, {
initComponent: function() {
Ext.apply(this, {
border: true,
gridmode: "archive",
stateful: true,
stateId: "documents.grid.archive"
});
Inprint.documents.archive.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.documents.archive.Panel.superclass.onRender.apply(this, arguments);
this.btnRestore.hide();
this.btnDelete.hide();
this.getSelectionModel().on("selectionchange", function(sm) {
var records = this.getSelectionModel().getSelections();
var access = _arrayAccessCheck(records, ['delete', 'recover',
'update', 'capture', 'move', 'transfer', 'briefcase']);
_disable(this.btnUpdate, this.btnCapture, this.btnTransfer,
this.btnMove, this.btnBriefcase, this.btnCopy,
this.btnDuplicate, this.btnRecycle, this.btnRestore, this.btnDelete);
if (sm.getCount() == 1) {
if (access.move == 'enabled') this.btnCopy.enable();
if (access.move == 'enabled') this.btnDuplicate.enable();
}
if (sm.getCount() > 0 ) {
if (access.move == 'enabled') this.btnCopy.enable();
if (access.move == 'enabled') this.btnDuplicate.enable();
}
}, this);
}
});
Inprint.registry.register("documents-archive", {
icon: "folders-stack",
menutext: _("Archive"),
text: _("Archival documents"),
xobject: Inprint.documents.archive.Panel
});
<file_sep>CREATE TABLE "public"."cache_access" (
"id" uuid DEFAULT uuid_generate_v4() NOT NULL,
"member" uuid NOT NULL,
"binding" uuid NOT NULL,
"termkey" varchar NOT NULL,
"enabled" bool DEFAULT false NOT NULL,
CONSTRAINT "cache_access_pkey" PRIMARY KEY ("id")
);
DROP INDEX "public"."documents_edition_idx";
CREATE INDEX "documents_edition_idx" ON "public"."documents" ("edition");
DROP INDEX "public"."documents_workgroup_idx";
CREATE INDEX "documents_workgroup_idx" ON "public"."documents" ("workgroup");
DROP INDEX "public"."documents_fascicle_idx";
CREATE INDEX "documents_fascicle_idx" ON "public"."documents" ("fascicle");
DROP INDEX "public"."documents_edition_workgroup_fascicle_idx";
CREATE INDEX "documents_edition_workgroup_fascicle_idx" ON "public"."documents" ("edition", "workgroup", "fascicle");
DROP INDEX "public"."documents_edition_workgroup_idx";
CREATE INDEX "documents_edition_workgroup_idx" ON "public"."documents" ("edition", "workgroup");
<file_sep>Inprint.cmp.uploader.Flash = Ext.extend(AwesomeUploader, {
initComponent: function() {
var cookies = document.cookie.split(";");
var Session;
Ext.each(cookies, function(cookie) {
var nvp = cookie.split("=");
if (nvp[0].trim() == 'sid') {
Session = nvp[1];
}
});
this.initialConfig.extraPostData = {
sid: Session
};
if (this.config.pkey) {
this.initialConfig.extraPostData.id = this.config.pkey;
}
if (this.config.document) {
this.initialConfig.extraPostData.document = this.config.document;
}
this.initialConfig.awesomeUploaderRoot = "/plugins/uploader/";
this.initialConfig.xhrUploadUrl = this.config.uploadUrl;
this.initialConfig.flashUploadUrl = this.config.uploadUrl;
this.initialConfig.standardUploadUrl = this.config.uploadUrl;
this.initialConfig.maxFileSizeBytes = 200 * 1024 * 1024;
this.initialConfig.gridWidth = 490;
this.initialConfig.gridHeight = 175;
this.addEvents( 'fileUploaded' );
Ext.apply(this, {
title: _("Flash mode"),
border:false
});
Inprint.cmp.uploader.Flash.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.uploader.Flash.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.panels.Help = Ext.extend(Ext.Panel, {
initComponent: function() {
Ext.apply(this, {
title: _("Help"),
border:false,
bodyCssClass: "help-panel",
preventBodyReset: true
});
Inprint.panels.Help.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.panels.Help.superclass.onRender.apply(this, arguments);
//if ( this.hid ) {
// this.load({
// method: 'get',
// url: "/help/" + this.hid + "/index.html",
// text: _("Loading...")
// });
//}
}
});
<file_sep>Inprint.cmp.adverta.Request = Ext.extend(Ext.FormPanel, {
initComponent: function() {
var xc = Inprint.factory.Combo;
this.items = [
_FLD_HDN_ID,
_FLD_HDN_FASCICLE,
{
xtype: "titlefield",
value: "Заявка"
},
xc.getConfig("/advertising/combo/advertisers/", {
hideLabel:true,
editable:true,
typeAhead: true,
minChars: 2,
minListWidth: 570,
allowBlank:false,
baseParams: {
fascicle: this.fascicle
},
listeners: {
scope: this,
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
}),
{
xtype: "textfield",
allowBlank:false,
hideLabel:true,
name: "shortcut",
fieldLabel: _("Shortcut"),
emptyText: _("Shortcut")
},
{
xtype: "textarea",
allowBlank:true,
name: "description",
hideLabel:true,
fieldLabel: _("Description"),
emptyText: _("Description")
},
{
xtype: "titlefield",
value: _("Parameters")
},
{
columns: 1,
xtype: 'radiogroup',
fieldLabel: _("Request"),
style: "margin-bottom:10px",
name: "status",
items: [
{ name: "status", inputValue: "possible", boxLabel: _("Possible") },
{ name: "status", inputValue: "active", boxLabel: _("Active") },
{ name: "status", inputValue: "reservation", boxLabel: _("Reservation"), checked: true }
]
},
{
columns: 1,
xtype: 'radiogroup',
fieldLabel: _("Squib"),
style: "margin-bottom:10px",
name: "squib",
items: [
{ name: "squib", inputValue: "yes", boxLabel: _("Yes") },
{ name: "squib", inputValue: "no", boxLabel: _("No"), checked: true }
]
},
{
xtype: 'checkbox',
fieldLabel: _("Paid"),
boxLabel: _("Yes"),
name: 'payment',
checked: false
},
{
xtype: 'checkbox',
fieldLabel: _("Approved"),
boxLabel: _("Yes"),
name: 'approved',
checked: false
}
];
Ext.apply(this, {
flex:1,
width: 250,
labelWidth: 90,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px"
});
Inprint.cmp.adverta.Request.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.adverta.Request.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Ext.namespace("Inprint.flash");
Inprint.flash.Proxy = {
onEvent : function(id, e) {
var fp = Ext.getCmp(id);
if(fp){
fp.onFlashEvent(e);
}else{
arguments.call.defer(10, this, [id, e]);
}
},
setGrid: function(panel, id, w, h) {
var form = Ext.getCmp(panel).getForm();
if (form) {
if (!form.baseParams) {
form.baseParams = {};
}
form.baseParams.w = w;
form.baseParams.h = h;
} else {
alert("Can't find form object!");
}
},
setModule : function(panel, id, hash) {
var form = Ext.getCmp(panel).getForm();
if (form) {
if (!form.baseParams) {
form.baseParams = {};
}
if (hash){
if(hash.x) {
form.baseParams.x = hash.x;
} else {
alert("Can't find x!");
}
if(hash.y) {
form.baseParams.y = hash.y;
} else {
alert("Can't find y!");
}
if(hash.w) {
form.baseParams.w = hash.w;
} else {
alert("Can't find w!");
}
if(hash.h){
form.baseParams.h = hash.h;
} else {
alert("Can't find h!");
}
} else {
alert("Can't find hash!");
}
} else {
alert("Can't find form object!");
}
},
savePage: function(panel, data) {
Ext.getCmp(panel).cmpSaveProxy(data);
}
};
<file_sep>Ext.namespace("Inprint.employee.logs");<file_sep>#!/bin/sh
hypnotoad --stop script/inprint.pl
<file_sep>#!/bin/sh
# Inprint Content 5.0
# Copyright(c) 2001-2010, Softing, LLC.
# <EMAIL>
# http://softing.ru/license
sudo -u postgres psql inprint-5.0 -c " SELECT 'GRANT ALL ON ' || schemaname || '.' || tablename || ' TO inprint;' FROM pg_tables WHERE schemaname IN ('public', 'plugins') ORDER BY schemaname, tablename; "
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.documents.GridColumns = function() {
return {
viewed: {
id : 'viewed',
width : 23,
fixed : true,
header : ' ',
menuDisabled: true,
renderer : function(value, p, record) {
if (!record.data.islooked) {
return '<img title="" src="'+ _ico("flag") +'">';
}
return '';
}
},
title: {
id:"title",
width: 210,
dataIndex: "title",
header: _("Title"),
menuDisabled: false,
renderer : function(value, p, record){
var color = 'black';
if (!record.get("isopen")) {
color = 'gray';
}
var header = String.format(
"<a style=\"color:{3}\" href=\"/workspace/?aid=document-profile&oid={0}&text={1}\""+
" onClick=\"Inprint.ObjectResolver.resolve({aid:'document-profile',oid:'{0}',text:'{1}'});return false;\">{2}"+
"</a>",
record.data.id, escape(value), value, color
);
var access = record.get("access");
var links = record.get("links");
var linksResult = [];
if (links) {
for (var f=0; f<links.length;f++) {
var color = (access.fedit) ? "black" : "gray";
var text = links[f].name;
var file = links[f].id;
var document = record.get("id");
linksResult.push(String.format(
"<a style=\"color:{4}\" href=\"/?aid=document-editor&oid={0}&pid={1}&text={2}\" "+
"onClick=\"Inprint.ObjectResolver.resolve({'aid':'document-editor','oid':'{0}','pid':'{1}','description':'{2}'});return false;\">"+
"<nobr>{3}</nobr></a>",
file, document, escape(text), text, color
));
}
}
var result = "<span style=\"font-size:11px;font-weight:bold;\">"+ header +"</span>";
if (linksResult.length > 0 ) {
result += "<span> — "+ linksResult.join(", ") + "</span>";
}
return result;
}
},
edition: {
id:"edition",
width: 80,
menuDisabled: true,
header: _("Edition"),
dataIndex: "edition_shortcut"
},
maingroup: {
id:"maingroup",
width: 80,
menuDisabled: true,
header: _("Department"),
dataIndex: "maingroup_shortcut"
},
workgroup: {
id:"workgroup",
width: 80,
hidden: true,
menuDisabled: true,
header: _("Where"),
dataIndex: "workgroup_shortcut"
},
fascicle: {
id:"fascicle",
width: 70,
menuDisabled: true,
header: _("Fascicle"),
dataIndex: "fascicle_shortcut",
renderer : function(value, p, record) {
return value;
}
},
headline: {
id:"headline",
menuDisabled: true,
dataIndex: "headline_shortcut",
header: _("Headline"),
width: 90
},
rubric: {
id:"rubric",
menuDisabled: true,
dataIndex: "rubric_shortcut",
header: _("Rubric"),
width: 80
},
pages: {
id:"pages",
menuDisabled: true,
dataIndex: "pages",
header: _("Pages"),
width: 55
},
progress: {
id:"progress",
width: 75,
dataIndex: "progress",
header: _("Progress"),
menuDisabled: true,
renderer : function(v, p, record) {
p.css += ' x-grid3-progresscol ';
var string = '';
if (record.data.pdate) {
string = _fmtDate(record.data.pdate, 'M j');
}
else if (record.data.rdate) {
string = _fmtDate(record.data.rdate, 'M j');
}
var style = '';
var textClass = (v < 55) ? 'x-progress-text-back' : 'x-progress-text-front' + (Ext.isIE6 ? '-ie6' : '');
var fgcolor = "#" + record.data.color;
var bgcolor = inprintColorLuminance(record.data.color, 0.7);
var txtcolor = inprintColorContrast(record.data.color);
var text = String.format(
'<div class="x-progress-text {0}" style="width:100%;color:{3}!important;" id="{1}">{2}</div>',
textClass, Ext.id(), string, txtcolor);
return String.format(
'<div class="x-progress-wrap">'+
'<div class="x-progress-inner" style="border:1px solid {4};background:{3}!important;">'+
'{2}'+
'<div class="x-progress-bar{0}" style="width:{1}%;background:{4}!important;color:{5}!important;"> </div>'+
'</div>',
style, v, text, bgcolor, fgcolor, txtcolor);
}
},
manager: {
id:"manager",
dataIndex: "manager_shortcut",
header: _("Manager"),
width: 100,
menuDisabled: true,
renderer : function(v, p, record) {
if (record.data.workgroup == record.data.manager) {
v = '<b>' +v+ '</b>';
}
return v;
}
},
holder: {
id:"holder",
dataIndex: "holder_shortcut",
header: _("Holder"),
width: 100,
menuDisabled: true,
renderer : function(v, p, record) {
if (record.data.workgroup == record.data.holder) {
v = '<b>' +v+ '</b>';
}
return v;
}
},
images: {
id:"images",
menuDisabled: true,
dataIndex: "images",
header : '<img src="'+ _ico("camera") +'">',
width:23
},
size: {
id:"size",
dataIndex: "rsize",
header : '<img src="'+ _ico("edit") +'">',
width:40,
menuDisabled: true,
renderer : function(value, p, record) {
if (record.data.rsize) {
return record.data.rsize;
}
if (record.data.psize) {
return String.format('<span style="color:silver">{0}</span>', record.data.psize);
}
return '';
}
},
created: {
id:"created",
hidden:true,
menuDisabled: true,
dataIndex: "created",
header: _("Created"),
width: 80,
xtype: 'datecolumn',
format: 'M d H:i'
},
updated: {
id:"updated",
hidden:true,
menuDisabled: true,
dataIndex: "updated",
header: _("Updated"),
width: 80,
xtype: 'datecolumn',
format: 'M d H:i'
},
uploaded: {
id:"uploaded",
hidden:true,
menuDisabled: true,
dataIndex: "uploaded",
header: _("Uploaded"),
width: 80,
xtype: 'datecolumn',
format: 'M d H:i'
},
moved: {
id:"moved",
hidden:true,
menuDisabled: true,
dataIndex: "moved",
header: _("Moved"),
width: 80,
xtype: 'datecolumn',
format: 'M d H:i'
}
};
};
<file_sep>Ext.ns("Inprint.advert.modules");<file_sep>-- Uninsall Rss Plugin
DELETE FROM plugins.menu WHERE plugin='rss';
DELETE FROM plugins.routes WHERE plugin='rss';
DELETE FROM plugins.rules WHERE plugin='rss';
<file_sep>Ext.namespace("Inprint.advert");<file_sep>Inprint.fascicle.adverta.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.manager = null;
this.version = null;
this.access = {};
this.fascicle = this.oid;
this.panels = {
pages: new Inprint.fascicle.adverta.Pages({
parent: this,
oid: this.oid
}),
requests: new Inprint.fascicle.adverta.Requests({
parent: this,
oid: this.oid
}),
summary: new Inprint.fascicle.adverta.Summary({
parent: this,
oid: this.oid
})
};
this.tbar = [
'->',
{
ref: "../btnSave",
disabled:true,
text: 'Сохранить',
tooltip: 'Сохранить изменения в компоновке выпуска',
icon: _ico("disk-black"),
cls: 'x-btn-text-icon',
scope:this,
handler: this.cmpSave
},
'-',
{
ref: "../btnBeginSession",
icon: _ico("control"),
cls: 'x-btn-text-icon',
hidden:false,
text: 'Открыть сеанс',
tooltip: 'Открыть сеанс редактирования',
scope: this,
handler: this.beginEdit
},
{
ref: "../btnCaptureSession",
icon: _ico("hand"),
cls: 'x-btn-text-icon',
hidden:true,
text: 'Захватить сеанс',
tooltip: 'Захватить сеанс редактирования',
scope: this,
handler: this.captureSession
},
{
ref: "../btnEndSession",
icon: _ico("control-stop-square"),
cls: 'x-btn-text-icon',
hidden:true,
text: 'Закрыть сеанс',
tooltip: 'Закрыть сеанс редактирования',
scope: this,
handler: this.endEdit
},
"-",
{
text: 'Печать А4',
icon: _ico("printer"),
cls: 'x-btn-text-icon',
scope:this,
handler: function() {
}
},
{
text: 'Печать А3',
icon: _ico("printer"),
cls: 'x-btn-text-icon',
scope:this,
handler: function() {
}
}
];
Ext.apply(this, {
layout: "border",
autoScroll:true,
defaults: {
collapsible: false,
split: true
},
items: [
{
border:false,
region: "center",
layout: "border",
margins: "3 0 3 3",
defaults: {
collapsible: false,
split: true
},
items: [
{
region: "center",
layout: "fit",
items: this.panels.pages
},
{
region:"south",
height: 200,
minSize: 100,
maxSize: 800,
layout:"fit",
collapseMode: 'mini',
items: this.panels.requests,
stateId: 'fasicles.planner.adverta'
}
]
},
{
region:"east",
margins: "3 3 3 0",
width: 280,
minSize: 50,
maxSize: 800,
layout:"fit",
collapseMode: 'mini',
items: this.panels.summary,
stateId: 'fasicles.planner.summary'
}
]
});
Inprint.fascicle.adverta.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.adverta.Panel.superclass.onRender.apply(this, arguments);
Inprint.fascicle.adverta.Context(this, this.panels);
Inprint.fascicle.adverta.Interaction(this, this.panels);
this.cmpInitSession();
},
cmpInitSession: function () {
this.body.mask("Обновление данных...");
Ext.Ajax.request({
url: _url("/fascicle/seance/"),
scope: this,
params: {
fascicle: this.oid
},
callback: function() {
this.body.unmask();
},
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
this.version = rsp.fascicle.version;
this.manager = rsp.fascicle.manager;
var shortcut = rsp.fascicle.shortcut;
var description = "";
if (rsp.fascicle.manager) {
description += ' [<b>Работает '+ rsp.fascicle.manager_shortcut +'</b>]';
}
description += ' [Полос '+ rsp.fascicle.pc +'='+ rsp.fascicle.dc +'+'+ rsp.fascicle.ac;
description += ' | '+ rsp.fascicle.dav +'%/'+ rsp.fascicle.aav +'%]';
var title = Inprint.ObjectResolver.makeTitle(this.parent.aid, this.parent.oid, null, this.parent.icon, shortcut, description);
this.parent.setTitle(title);
this.panels.pages.getStore().loadData({ data: rsp.pages });
this.panels.requests.getStore().loadData({ data: rsp.requests });
this.panels.summary.getStore().loadData({ data: rsp.summary });
Inprint.fascicle.adverta.Access(this, this.panels, rsp.fascicle.access);
this.cmpCheckSession.defer( 50000, this);
}
});
},
cmpReload: function() {
this.cmpInitSession();
},
cmpCheckSession: function () {
Ext.Ajax.request({
url: _url("/fascicle/check/"),
scope: this,
params: {
fascicle: this.oid
},
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
Inprint.fascicle.adverta.Access(this, this.panels, rsp.fascicle.access);
if (this.manager && this.manager != rsp.fascicle.manager) {
Ext.MessageBox.alert(_("Error"), _("Another employee %1 captured this issue!", [1]));
} else {
this.cmpCheckSession.defer( 50000, this);
}
}
});
},
captureSession: function() {
this.body.mask("Попытка захвата редактирования...");
Ext.Ajax.request({
url: _url("/fascicle/capture/"),
scope: this,
params: {
fascicle: this.oid
},
callback: function() { this.body.unmask(); },
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
if (!rsp.success && rsp.errors[0]) {
Ext.MessageBox.alert(_("Error"), _(rsp.errors[0].msg));
}
this.cmpReload();
}
});
},
beginEdit: function() {
this.body.mask("Открываем выпуск...");
Ext.Ajax.request({
url: _url("/fascicle/open/"),
scope: this,
params: {
fascicle: this.oid
},
callback: function() { this.body.unmask(); },
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
if (!rsp.success && rsp.errors[0]) {
Ext.MessageBox.alert(_("Error"), _(rsp.errors[0].msg));
}
this.cmpReload();
}
});
},
endEdit: function() {
this.body.mask("Закрываем выпуск...");
Ext.Ajax.request({
url: _url("/fascicle/close/"),
scope: this,
params: {
fascicle: this.oid
},
callback: function() { this.body.unmask(); },
success: function(response) {
var rsp = Ext.util.JSON.decode(response.responseText);
if (!rsp.success && rsp.errors[0]) {
Ext.MessageBox.alert(_("Error"), _(rsp.errors[0].msg));
}
this.cmpReload();
}
});
},
cmpSave: function() {
var pages = this.panels.pages;
var requests = this.panels.requests;
var data = [];
// get requests changes
var records = requests.getStore().getModifiedRecords();
if(records.length) {
Ext.each(records, function(r, i) {
var document = r.get('id');
var pages = r.get('pages');
data.push(document +'::'+ pages);
}, this);
}
this.body.mask("Сохранение данных");
var o = {
url: _url("/fascicle/save/"),
params:{
fascicle: this.oid,
document: data
},
scope:this,
success: function () {
requests.getStore().commitChanges();
this.cmpReload();
}
};
Ext.Ajax.request(o);
},
cmpOnClose: function(inc) {
if (inc == 'no') {
return false;
} else if ( inc == 'yes') {
this.endEdit();
Inprint.layout.remove(this);
return true;
}
if (this.sessionIsActive) {
var mbx = Ext.MessageBox.confirm(
'Подтверждение',
'Закрыть сессию перед закрытием вкладки?',
this.cmpOnClose, this
);
return false;
}
return true;
}
});
Inprint.registry.register("fascicle-adverta", {
icon: "money",
text: _("Advertising requests"),
xobject: Inprint.fascicle.adverta.Panel
});
<file_sep>Inprint.fascicle.adverta.Pages = Ext.extend(Ext.Panel, {
initComponent: function() {
this.components = {};
this.urls = {
"read": _url("/fascicle/pages/read/"),
"create": _url("/fascicle/pages/create/"),
"update": _url("/fascicle/pages/update/"),
"delete": _url("/fascicle/pages/delete/"),
"move": _url("/fascicle/pages/move/"),
"left": _url("/fascicle/pages/left/"),
"right": _url("/fascicle/pages/right/"),
"clean": _url("/fascicle/pages/clean/"),
"resize": _url("/fascicle/pages/resize/")
};
this.view = new Inprint.fascicle.plan.View({
parent: this.parent,
fascicle: this.oid
});
Ext.apply(this, {
border:false,
layout: "fit",
autoScroll:true,
items: this.view
});
Inprint.fascicle.adverta.Pages.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.adverta.Pages.superclass.onRender.apply(this, arguments);
},
getView: function() {
return this.view;
},
getIdByNum: function(num) {
var id = null;
var nodes = this.view.getNodes();
Ext.each(nodes, function(c){
if (c.getAttribute("seqnum") == num) {
id = c.id;
}
});
return id;
},
getStore: function() {
return this.view.getStore();
},
cmpGetSelected: function () {
var result = [];
var records = this.view.getSelectedNodes();
Ext.each(records, function(c) {
result.push(c.id +"::"+ c.getAttribute("seqnum"));
}, this);
return result;
},
cmpPageCreate: function() {
var wndw = this.components.create;
if (!wndw) {
wndw = new Ext.Window({
title: 'Добавление полос',
width: 300,
height: 160,
modal:true,
draggable:true,
layout: "fit",
closeAction: "hide",
items: {
xtype: "form",
border: false,
url: this.urls.create,
baseParams: {
fascicle: this.oid
},
labelWidth: 100,
defaultType: 'checkbox',
defaults: { anchor: '100%', hideLabel: true },
bodyStyle: 'padding:10px;',
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
this.parent.cmpReload();
}
},
items: [
{
xtype: 'textfield',
name: 'page',
emptyText: 'Полосы',
allowBlank:false
},
Inprint.factory.Combo.getConfig("/fascicle/combos/headlines/", {
allowBlank:true,
baseParams:{
fascicle: this.oid
},
listeners: {
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
}),
Inprint.factory.Combo.getConfig("/fascicle/combos/templates/", {
allowBlank:false,
baseParams:{
fascicle: this.oid
},
listeners: {
render: function(combo) {
combo.setValue("00000000-0000-0000-0000-000000000000", _("Defaults"));
},
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
})
]
},
buttons: [
_BTN_WNDW_ADD,
_BTN_WNDW_CANCEL
]
});
this.components.create = wndw;
}
var form = wndw.findByType("form")[0].getForm();
form.reset();
wndw.show();
},
// Редактировать
cmpPageUpdate: function() {
var wndw = this.components.update;
if (!wndw) {
wndw = new Ext.Window({
title: 'Редактировать полосы',
width: 300,
height: 160,
modal:true,
draggable:true,
layout: "fit",
closeAction: "hide",
items: {
xtype: "form",
border: false,
url: this.urls.update,
baseParams: {
fascicle: this.oid
},
labelWidth: 100,
defaultType: 'checkbox',
defaults: { anchor: '100%', hideLabel: true },
bodyStyle: 'padding:10px;',
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
this.parent.cmpReload();
}
},
items: [
Inprint.factory.Combo.getConfig("/fascicle/combos/headlines/", {
baseParams:{
fascicle: this.oid
},
listeners: {
beforequery: function(qe) {
delete qe.combo.lastQuery;
}
}
})
]
},
buttons: [
_BTN_WNDW_OK,
_BTN_WNDW_CANCEL
]
});
this.components.update = wndw;
}
wndw.show();
var form = wndw.findByType("form")[0].getForm();
form.reset();
form.baseParams.page = this.cmpGetSelected();
wndw.show();
},
cmpPageCompose: function() {
var selection = this.cmpGetSelected();
if (selection.length > 2) {
return;
}
if (selection.length <= 0) {
return;
}
var wndw = new Inprint.cmp.Composer({
fascicle: this.parent.fascicle,
selection: selection
});
wndw.on("actioncomplete", function() {
this.parent.cmpReload();
}, this);
wndw.show();
},
//Переместить
cmpPageMove: function(inc, text) {
if ( inc == 'cancel') {
return;
}
if ( inc == 'ok') {
Ext.Ajax.request({
url: this.urls.move,
params: {
fascicle: this.oid,
after: text,
page: this.cmpGetSelected()
},
scope: this,
success: function() {
this.parent.cmpReload();
}
});
return;
}
Ext.MessageBox.prompt(
'Перемещение полос',
'Укажите номер полосы, после которой будут размещены выбранные полосы',
this.cmpPageMove, this
);
},
cmpPageMoveLeft: function(inc, text) {
if ( inc == 'cancel') {
return;
}
if ( inc == 'ok') {
Ext.Ajax.request({
url: this.urls.left,
params: {
fascicle: this.oid,
amount: text,
page: this.cmpGetSelected()
},
scope: this,
success: function() {
this.parent.cmpReload();
}
});
return;
}
Ext.MessageBox.prompt(
'Cмещение влево',
'На сколько полос сместить?',
this.cmpPageMoveLeft, this
);
},
cmpPageMoveRight: function(inc, text) {
if ( inc == 'cancel') {
return;
}
if ( inc == 'ok') {
Ext.Ajax.request({
url: this.urls.right,
params: {
fascicle: this.oid,
amount: text,
page: this.cmpGetSelected()
},
scope: this,
success: function() {
this.parent.cmpReload();
}
});
return;
}
Ext.MessageBox.prompt(
'Cмещение вправо',
'На сколько полос сместить?',
this.cmpPageMoveRight, this
);
},
// Стереть
cmpPageClean: function() {
var wndw = this.components.clean;
if (!wndw) {
wndw = new Ext.Window({
title: 'Удаление содержимого полосы',
width:250,
height:140,
modal:true,
draggable:true,
layout: "fit",
closeAction: "hide",
items: {
xtype: "form",
border: false,
url: this.urls.clean,
baseParams: {
fascicle: this.oid
},
labelWidth: 60,
defaultType: 'checkbox',
defaults: { anchor: '100%', hideLabel:true },
bodyStyle: 'padding:10px;',
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
this.parent.cmpReload();
}
},
items: [
{
xtype: 'checkbox',
name: 'documents',
checked:false,
inputValue: 'true',
fieldLabel: '',
labelSeparator: ':',
boxLabel: 'Удалить материалы'
},
{
xtype: 'checkbox',
name: 'adverts',
checked:false,
inputValue: 'true',
fieldLabel: '',
labelSeparator: '',
boxLabel: 'Удалить рекламу'
}
]
},
buttons: [
_BTN_WNDW_OK,
_BTN_WNDW_CANCEL
]
});
this.components.clean = wndw;
}
var form = wndw.findByType("form")[0].getForm();
form.reset();
form.baseParams.page = this.cmpGetSelected();
wndw.show();
},
// разверстать
cmpPageResize: function() {
var wndw = this.components.resize;
if (!wndw) {
wndw = new Ext.Window({
title: 'Разверстка полос',
width:320,
height:240,
modal:true,
draggable:true,
layout: "fit",
closeAction: "hide",
items: {
xtype: "form",
border: false,
url: this.urls.resize,
baseParams: {
fascicle: this.oid
},
labelWidth: 100,
defaultType: 'checkbox',
defaults: { anchor: '100%' },
bodyStyle: 'padding:5px 5px 0;',
listeners: {
scope:this,
actioncomplete: function() {
wndw.hide();
this.parent.cmpReload();
}
},
items: [
{
xtype: 'box',
autoEl: {tag:'div', html: 'Пример: 1, 2, 5-8, 9:10 (9:10 добавит 10 полос после полосы 9).' },
cls: 'inprint-form-helpbox'
},
{
xtype: 'textfield',
name: 'page',
itemCls: 'required',
fieldLabel: 'На полосы'
}
//{
// xtype: 'checkbox',
// name: 'documents',
// checked:true,
// inputValue: 'true',
// fieldLabel: 'Скопировать',
// labelSeparator: ':',
// boxLabel: 'Материалы'
//},
//{
// xtype: 'checkbox',
// name: 'advertisements',
// checked:false,
// inputValue: 'true',
// fieldLabel: '',
// labelSeparator: '',
// boxLabel: 'Рекламу'
//}
]
},
buttons: [
_BTN_WNDW_OK,
_BTN_WNDW_CANCEL
]
});
this.components.resize = wndw;
}
var form = wndw.findByType("form")[0].getForm();
form.reset();
form.baseParams.page = this.cmpGetSelected();
wndw.show();
},
//Удалить
cmpPageDelete: function(inc) {
if ( inc == 'no') {
return;
}
if ( inc == 'yes') {
Ext.Ajax.request({
url: this.urls["delete"],
params: {
fascicle: this.oid,
page: this.cmpGetSelected()
},
scope: this,
success: function() {
this.parent.cmpReload();
}
});
} else {
Ext.MessageBox.confirm(
'Подтверждение',
'Вы действительно хотите безвозвратно удалить полосы?',
this.cmpPageDelete, this
);
}
}
});
<file_sep>Inprint.cmp.memberProfileForm.Window = Ext.extend(Ext.Window, {
initComponent: function() {
this.addEvents('actioncomplete');
this.form = new Inprint.cmp.memberProfileForm.Form();
Ext.apply(this, {
title: _("Edit profile"),
modal: true,
layout: "fit",
closeAction: "hide",
width:600, height:400,
items: this.form,
buttons:[
{
text: _("Save"),
scope:this,
handler: function() {
this.form.getForm().submit();
}
},
{
text: _("Close"),
scope:this,
handler: function() {
this.hide();
}
}
]
});
this.form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
this.hide();
this.fireEvent("actioncomplete");
}
}, this);
Inprint.cmp.memberProfileForm.Window.superclass.initComponent.apply(this, arguments);
Inprint.cmp.memberProfileForm.Interaction(this.panels);
},
onRender: function() {
Inprint.cmp.memberProfileForm.Window.superclass.onRender.apply(this, arguments);
},
cmpFill: function(id) {
this.body.mask(_("Loading"));
var form = this.form.getForm();
form.reset();
form.load({
scope:this,
params: { id: id },
url: "/profile/read/",
success: function(form, action) {
this.body.unmask();
this.form.getForm().findField("imagefield").setValue("/profile/image/"+ id);
},
failure: function(form, action) {
Ext.Msg.alert("Load failed", action.result.errorMessage);
}
});
}
});
Inprint.registry.register("employee-card", {
icon: "card",
text: _("Card"),
handler: function () {
new Inprint.cmp.memberProfileForm.Window().show().cmpFill("self");
}
});
<file_sep>Inprint.fascicle.planner.Interaction = function(parent, panels) {
var access = parent.access;
var pages = panels.pages;
var documents = panels.documents;
var requests = panels.requests;
var summary = panels.summary;
documents.btnSwitchToRequests.handler = function () {
documents.findParentByType("panel").getLayout().setActiveItem(1);
};
requests.btnSwitchToDocuments.handler = function () {
documents.findParentByType("panel").getLayout().setActiveItem(0);
};
// Pages view
pages.view.on("beforeselect", function() {
return (parent.access.save == true) ? true : false;
});
pages.view.on("selectionchange", function(view, data) {
var requests = this.panels.requests;
_disable(this.btnPageUpdate, this.btnPageDelete, this.btnPageMove, this.btnPageMoveLeft, this.btnPageMoveRight, this.btnPageClean, this.btnPageResize);
if (this.access.save) {
_disable(requests.btnMove);
if ( requests.getSelectionModel().getCount() == 1 ) {
var record = requests.getSelectionModel().getSelected();
if (record.get("amount") == data.length) {
_enable(requests.btnMove);
}
}
if (data.length == 1) {
_enable(this.btnPageUpdate, this.btnPageDelete, this.btnPageMove, this.btnPageMoveLeft, this.btnPageMoveRight, this.btnPageClean, this.btnPageResize);
}
if (data.length > 1) {
_enable(this.btnPageUpdate, this.btnPageDelete, this.btnPageMove, this.btnPageClean, this.btnPageResize);
}
}
}, parent);
// Documents table
documents.getSelectionModel().on("selectionchange", function(sm) {
var documents = this.panels.documents;
var records = documents.getSelectionModel().getSelections();
var doc_access = _arrayAccessCheck(records, ['delete', 'recover', 'update', 'capture', 'move', 'transfer', 'briefcase']);
_disable(documents.btnUpdate, documents.btnCapture, documents.btnTransfer, documents.btnMove, documents.btnBriefcase, documents.btnCopy,
documents.btnDuplicate, documents.btnRecycle, documents.btnRestore, documents.btnDelete);
if (this.access.save) {
if (sm.getCount() == 1) {
if (doc_access.update == 'enabled') {
documents.btnUpdate.enable();
}
if (doc_access.capture == 'enabled') {
documents.btnCapture.enable();
}
if (doc_access.transfer == 'enabled') {
documents.btnTransfer.enable();
}
if (doc_access.briefcase == 'enabled') {
documents.btnBriefcase.enable();
}
if (doc_access.move == 'enabled') {
documents.btnMove.enable();
}
if (doc_access["delete"] == 'enabled') {
documents.btnRecycle.enable();
}
}
if (sm.getCount() > 0 ) {
if (doc_access.capture == 'enabled') {
documents.btnCapture.enable();
}
if (doc_access.transfer == 'enabled') {
documents.btnTransfer.enable();
}
if (doc_access.briefcase == 'enabled') {
documents.btnBriefcase.enable();
}
if (doc_access.move == 'enabled') {
documents.btnMove.enable();
}
if (doc_access["delete"] == 'enabled') {
documents.btnRecycle.enable();
}
}
}
}, parent);
// Advert table
requests.getSelectionModel().on("selectionchange", function(sm) {
var pages = this.panels.pages;
var requests = this.panels.requests;
var selectedPages = pages.cmpGetSelected();
var amount = requests.getValue("amount");
if (sm.getCount() == 0) {
_disable(requests.btnUpdate, requests.btnMove, requests.btnDelete);
}
if (this.access.save && this.access.advert_update) {
if (sm.getCount() == 1) {
_enable(requests.btnUpdate, requests.btnDelete);
if (amount == selectedPages.length) {
_enable(requests.btnMove);
}
}
if (sm.getCount() > 0 ) {
_enable(requests.btnDelete);
}
}
}, parent);
};
<file_sep>Inprint.fascicle.places.Interaction = function(parent, panels) {
var places = panels.places;
var modules = panels.modules;
var headlines = panels.headlines;
// Tree
places.getSelectionModel().on("selectionchange", function(sm, node) {
modules.disable();
headlines.disable();
if (node && node.attributes.type == "place") {
//parent.edition = node.attributes.edition;
modules.enable();
modules.place = node.id;
modules.cmpLoad({ fascicle: parent.fascicle, place: node.id });
headlines.enable();
headlines.place = node.id;
headlines.cmpLoad({ fascicle: parent.fascicle, place: node.id });
}
});
//Grids
modules.getSelectionModel().on("selectionchange", function(sm) {
_enable(modules.btnSave);
}, parent);
headlines.getSelectionModel().on("selectionchange", function(sm) {
_enable(headlines.btnSave);
}, parent);
};
<file_sep>Ext.namespace("Inprint.cmp.memberRules");
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.Menu = Ext.extend(Ext.Toolbar,{
initComponent: function(){
Ext.apply(this, {
height:26
});
Inprint.Menu.superclass.initComponent.apply(this, arguments);
},
// Override other inherited methods
onRender: function(){
Inprint.Menu.superclass.onRender.apply(this, arguments);
this.CmpQuery();
// Start a simple clock task that updates a div once per second
var task = {
run: function() {
var clock = Ext.fly("menu-clock");
if (clock) {
clock.update(new Date().format('g:i:s A'));
}
},
interval: 1000 //1 second
};
var runner = new Ext.util.TaskRunner();
runner.start(task);
},
CmpQuery: function() {
if (this.items) {
this.items.each(this.remove, this);
}
Ext.Ajax.request({
url: _url("/menu/"),
scope: this,
success: function (response) {
var result = Ext.util.JSON.decode(response.responseText);
this.CmpLoad(result.data);
}
});
},
CmpLoad: function(result) {
// Обрабатываем все пункты меню
Ext.each(result, function(item) {
if (item == '->') {
this.add(item);
return;
} else {
var btn = this.CmpCreateBtn(item);
this.add(btn);
}
}, this);
this.add("-");
var clock = this.add({ id: "menu-clock", xtype: 'tbtext', text: '00:00:00 --' });
this.doLayout();
},
CmpCreateBtn: function (item) {
if ( Inprint.registry[item.id] ) {
var btn = {};
btn.aid = item.id;
btn.oid = item.oid;
btn.icon = Inprint.registry[btn.aid].icon;
btn.icon = _ico(btn.icon);
if (Inprint.registry[btn.aid]) {
if (Inprint.registry[btn.aid].xtype) {
btn.xtype = Inprint.registry[btn.aid].xtype;
}
}
btn.text = item.menutext || Inprint.registry[btn.aid].menutext || item.text || Inprint.registry[btn.aid].text;
btn.tooltip = item.tooltip || Inprint.registry[btn.aid].tooltip
// Обрабатываем подменю
if (item.menu) {
btn.menu = new Ext.menu.Menu();
Ext.each(item.menu, function(node) {
var btn2 = this.CmpCreateBtn(node);
btn.menu.add(btn2);
}, this);
}
// Обрабатываем кнопку
else {
btn.scope = this;
// Internal handler
if (Inprint.registry[btn.aid].handler) {
btn.handler = Inprint.registry[btn.aid].handler;
}
// Resolve window
else {
btn.handler = function() {
Inprint.ObjectResolver.resolve({
aid: btn.aid,
oid: btn.oid,
text: item.text || Inprint.registry[btn.aid].text,
description: item.description || Inprint.registry[btn.aid].description
});
};
}
}
return btn;
}
return item;
}
});
<file_sep>#!/bin/sh
sudo -u www-data hypnotoad script/inprint.pl<file_sep>Inprint.fascicle.planner.Access = function(parent, panels, access) {
parent.access = access;
var pages = panels.pages;
var documents = panels.documents;
var requests = panels.requests;
//Seance
_hide(parent.btnCaptureSession, parent.btnBeginSession, parent.btnEndSession);
_disable(parent.btnCaptureSession, parent.btnBeginSession, parent.btnEndSession, parent.btnSave);
_disable(documents.btnUpdate, documents.btnCapture, documents.btnTransfer,
documents.btnMove, documents.btnBriefcase, documents.btnCopy,
documents.btnDuplicate, documents.btnRecycle, documents.btnRestore,
documents.btnDelete);
if (access.open) {
parent.btnBeginSession.show();
parent.btnBeginSession.enable();
}
if (access.capture) {
parent.btnCaptureSession.show();
parent.btnCaptureSession.enable();
}
if (access.close) {
parent.btnEndSession.show();
parent.btnEndSession.enable();
}
// Composition
if (access.save) {
parent.btnSave.show();
parent.btnSave.enable();
parent.btnPageCreate.enable();
documents.btnCreate.enable();
documents.btnFromBriefcase.enable();
}
// Advert
if (access.advert_create == 0) {
_disable(requests.btnCreate);
}
if (access.advert_create == 1) {
_enable(requests.btnCreate);
}
if (access.advert_update == 0) {
_disable(requests.btnUpdate, requests.btnMove, requests.btnDelete);
}
};
<file_sep>#!/bin/sh
# 3:2
#if [ -f wallpaper-3x2.jpg ]
#then
# mogrify -resize 1152x768 wallpaper-3x2.jpg 1152x768.jpg
# mogrify -resize 1280x854 wallpaper-3x2.jpg 1280x854.jpg
# mogrify -resize 1440x960 wallpaper-3x2.jpg 1440x960.jpg
#fi
# 5:3 - 1280x768
#if [ -f wallpaper-5x3.jpg ]
#then
# mogrify -resize 1280x768 wallpaper-5x3.jpg 1280x768.jpg
#fi
if [ -f wallpaper-4x3.jpg ] # 4:3
then
mogrify -resize 1024x768 wallpaper-4x3.jpg 1024x768.jpg
mogrify -resize 1152x864 wallpaper-4x3.jpg 1152x864.jpg
mogrify -resize 1280x960 wallpaper-4x3.jpg 1280x960.jpg
mogrify -resize 1400x1050 wallpaper-4x3.jpg 1400x1050.jpg
mogrify -resize 1600x1200 wallpaper-4x3.jpg 1600x1200.jpg
fi
if [ -f wallpaper-5x4.jpg ] # 5:4 - 1280x1024
then
mogrify -resize 1280x1024 wallpaper-5x4.jpg 1280x1024.jpg
fi
if [ -f wallpaper-16x9.jpg ] #16:9
then
mogrify -resize 1280x720 wallpaper-16x9.jpg 1280x720.jpg
mogrify -resize 1365x768 wallpaper-16x9.jpg 1365x768.jpg
mogrify -resize 1600x900 wallpaper-16x9.jpg 1600x900.jpg
mogrify -resize 1920x1080 wallpaper-16x9.jpg 1920x1080.jpg
fi
if [ -f wallpaper-16x10.jpg ] #16:10
then
mogrify -resize 1280x800 wallpaper-16x10.jpg 1280x800.jpg
mogrify -resize 1440x900 wallpaper-16x10.jpg 1440x900.jpg
mogrify -resize 1680x1050 wallpaper-16x10.jpg 1680x1050.jpg
mogrify -resize 1920x1200 wallpaper-16x10.jpg 1920x1200.jpg
fi
<file_sep>Inprint.cmp.memberRulesForm.Domain.Restrictions = Ext.extend(Ext.grid.EditorGridPanel, {
initComponent: function() {
this.uid = null;
this.record = null;
this.components = {};
var url = "/catalog/rules/list/";
this.sm = new Ext.grid.CheckboxSelectionModel({
checkOnly:true
});
this.store = Inprint.factory.Store.json(url, {
autoLoad: false,
baseParams: {
section: 'domain'
}
});
this.columns = [
this.sm,
{
id:"icon",
width: 30,
dataIndex: "icon",
renderer: function (value, meta, record) {
return '<img src="'+ _ico(value) +'"/>';
}
},
{
id:"title",
header: _("Rule"),
width: 120,
sortable: true,
dataIndex: "title",
renderer: function (value, meta, record) {
return _(value);
}
}
];
this.tbar = [
{
icon: _ico("disk-black"),
cls: "x-btn-text-icon",
text: _("Save"),
ref: "../btnSave",
scope:this
}
];
Ext.apply(this, {
disabled: false,
stripeRows: true,
columnLines: true,
clicksToEdit: 1,
autoExpandColumn: "title"
});
Inprint.cmp.memberRulesForm.Domain.Restrictions.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.memberRulesForm.Domain.Restrictions.superclass.onRender.apply(this, arguments);
this.getStore().load();
},
cmpGetBinding: function() {
return "00000000-0000-0000-0000-000000000000";
},
cmpGetSection: function() {
return "domain";
}
});
<file_sep>Inprint.cmp.PrincipalsBrowser.Interaction = function(panels) {
var tree = panels.tree;
var grid = panels.grid;
tree.getSelectionModel().on("selectionchange", function(sm, node) {
grid.enable();
if (node) {
grid.cmpLoad({ node: node.id });
grid.setTitle(_("Members") +' - '+ node.text);
}
});
};
<file_sep>CREATE TABLE "public"."cache_downloads" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"member" uuid NOT NULL,
"document" uuid NOT NULL,
"file" uuid NOT NULL,
"created" timestamp(6) WITH TIME ZONE NOT NULL DEFAULT now(),
"updated" timestamp(6) WITH TIME ZONE NOT NULL DEFAULT now(),
CONSTRAINT "cache_downloads_pkey" PRIMARY KEY ("id"),
CONSTRAINT "cache_downloads_document_fkey" FOREIGN KEY ("document") REFERENCES "public"."documents" ("id") ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE,
CONSTRAINT "cache_downloads_member_fkey" FOREIGN KEY ("member") REFERENCES "public"."members" ("id") ON UPDATE CASCADE ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE
)
WITH (OIDS=FALSE);
ALTER TABLE "public"."cache_downloads" OWNER TO "inprint";<file_sep>Inprint.setAction("headline.update", function(tree, node) {
var urlForm = _url("/catalog/headlines/update/");
var urlRead = _url("/catalog/headlines/read/");
var form = new Ext.FormPanel({
url: urlForm,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_ID,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE,_BTN_CLOSE ]
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
tree.cmpReload();
}
}, this);
form.load({
url: urlRead,
scope:this,
params: {
id: node.id
},
success: function(form, action) {
win.body.unmask();
}
});
var win = Inprint.factory.windows.create(
"Update headline", 400, 260, form
).show();
win.body.mask();
});
<file_sep>Inprint.catalog.organization.Interaction = function(parent, panels) {
var tree = panels.tree;
var grid = panels.grid;
var help = panels.help;
// Tree
tree.on("beforenodedrop", function (e) {
if(Ext.isArray(e.data.selections)) {
var node = this.cmpCurrentNode();
e.cancel = false;
var data = _get_values("id", e.data.selections);
}
return false;
}, tree);
tree.getSelectionModel().on("selectionchange", function(sm, node) {
grid.enable();
if (node) {
grid.cmpLoad({ node: node.id });
grid.setTitle(_("Employees") +' - '+ node.text);
}
});
// Grid buttons
grid.btnAddToGroup.handler = function() {
var win = grid.components["add-to-group-window"];
if (!win) {
win = new Inprint.cmp.membersList.Window();
grid.components["add-to-group-window"] = win;
win.on("select", function(ids) {
Ext.Ajax.request({
url: "/catalog/organization/map/",
scope: grid,
success: grid.cmpReload,
params: {
group: tree.cmpCurrentNode().id,
members: ids
}
});
});
}
win.show();
win.cmpLoad();
};
grid.btnDeleteFromGroup.handler = function() {
Ext.MessageBox.confirm(
_("Termination of membership"),
_("You really want to stop membership in group for the selected accounts?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: "/catalog/organization/unmap/",
scope: grid,
success: grid.cmpReload,
params: {
group: tree.cmpCurrentNode().id,
members: grid.getValues("id")
}
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
};
grid.btnViewProfile.handler = function() {
var win = grid.components["view-profile-window"];
if (!win) {
win = new Inprint.cmp.memberProfile.Window();
grid.components["view-profile-window"] = win;
}
win.show();
win.cmpFill(grid.getValue("id"));
};
grid.btnUpdateProfile.handler = function() {
var win = grid.components["update-profile-window"];
if (!win) {
win = new Inprint.cmp.memberProfileForm.Window();
grid.components["update-profile-window"] = win;
win.on("actioncomplete", function() {
grid.cmpReload();
});
}
win.show();
win.cmpFill(grid.getValue("id"));
};
grid.btnManageRules.handler = function() {
var win = new Inprint.cmp.memberRulesForm.Window({
memberId: grid.getValue("id")
});
win.show();
};
// Grid
grid.getStore().on("load", function(store) {
if (tree.cmpCurrentNode()) {
grid.setTitle(_("Employees") +' - '+ tree.cmpCurrentNode().text +' ('+ store.getCount() +')');
}
});
};
<file_sep>Inprint.setAction("stage.principals", function(grid) {
win = new Inprint.cmp.PrincipalsSelector({
urlLoad: "/catalog/stages/principals-mapping/",
urlDelete: "/catalog/stages/unmap-principals/"
});
win.on("show", function(win) {
win.panels.selection.cmpLoad({
stage: grid.getValue("id")
});
});
win.on("close", function(win) {
grid.cmpReload();
});
win.on("save", function(srcgrid, catalog, ids) {
Ext.Ajax.request({
url: "/catalog/stages/map-principals/",
params: {
stage: grid.getValue("id"),
catalog: catalog,
principals: ids
},
success: function() {
srcgrid.cmpReload();
}
});
});
win.on("delete", function(srcgrid, ids) {
Ext.Ajax.request({
url: "/catalog/stages/unmap-principals/",
params: {
principals: ids
},
success: function() {
srcgrid.cmpReload();
}
});
});
win.show();
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.ObjectResolver = function() {
// Хранилище объектов
var objectHash = {};
var objectStore = [];
return {
resolve: function(item) {
if (!Inprint.registry[item.aid]) {
alert("Can't find Inprint.registry for item.aid");
return;
}
if (Inprint.registry[item.aid].xaction) {
Inprint.registry[item.aid].xaction();
return;
}
item.icon = Inprint.registry[item.aid].icon;
item.modal = Inprint.registry[item.aid].modal;
item.text = item.text || Inprint.registry[item.aid].text;
item.description = item.description || Inprint.registry[item.aid].description;
item.icon = _ico(item.icon);
var panelId = item.aid || Ext.id();
if (Inprint.registry[item.aid].modal === false) {
panelId = Ext.id();
}
if (item.oid) {
panelId += "-" + item.oid;
}
var panel = objectHash[panelId];
if (!panel) {
panel = Inprint.ObjectResolver.create(item, panelId);
}
Inprint.ObjectResolver.show(panel);
},
// Создаем новую панель
create: function(item, panelId){
var config = {
panelId: panelId,
layout: "fit",
border:false,
title: _("Unnamed window"),
icon: "/icon/layout.png"
};
if (item.aid) { config.aid = item.aid; }
if (item.oid) { config.oid = item.oid; }
if (item.pid) { config.pid = item.pid; }
if (item.icon) { config.icon = item.icon; }
var xobject = Inprint.registry[item.aid].xobject;
config.title = Inprint.ObjectResolver.makeTitle(config.aid, config.oid, config.pid, config.icon, unescape(item.text), unescape(item.description));
// Create panel Tools
var tools = [
{
id: "refresh",
qtip: _("Reload this panel"),
scope: Inprint.ObjectResolver,
handler: function(event, toolEl, panel) {
Inprint.ObjectResolver.reload(panel);
}
},
{
id: "close",
qtip: _("Close this panel"),
scope: Inprint.ObjectResolver,
handler: function(event, toolEl, panel) {
Inprint.ObjectResolver.remove(panel);
}
}
];
config.tools = tools;
if (xobject && typeof(xobject) == "function") {
config.items = { xtype: config.aid, oid: config.oid, pid: config.pid };
} else {
config.items = new Ext.Panel({
html:"<h1>" + _("Not implemented") + "</h1>"
});
}
var panel = new Ext.Panel(config);
panel.items.first().parent = panel;
// Register the panel
Inprint.layout.getPanel().add(panel);
panel.taskBtn = Inprint.layout.getTaskbar().addButton({
panel: panel,
icon: panel.icon,
text: Ext.util.Format.ellipsis(_(unescape(item.description || item.text)), 10)
});
panel.taskBtn.toggle();
objectHash[panelId] = panel;
objectStore.push(panel);
return panel;
},
makeTitle: function(aid, oid, pid, icon, text, description) {
var title = "<div style=\"padding-left:21px;background:url(" + icon + ") 0px -1px no-repeat;\">";
title += _(text) ;
title += " <a href=\"?aid="+ aid +"";
if (oid) title += "&oid=" + oid;
if (pid) title += "&pid=" + pid;
if (text) title += "&text=" + text;
if (description && description != 'undefined') title += "&description=" + description;
title += "\" onClick=\"return false;\">[#]</a>";
if (description && description != 'undefined') title += " - " + description;
title += "</div>";
return title;
},
show: function(panel) {
if (panel) {
Inprint.layout.getPanel().layout.setActiveItem(panel);
Inprint.layout.getPanel().doLayout();
Inprint.layout.getViewport().doLayout();
}
},
hide: function(panel) {
if (panel) {
Inprint.layout.getPanel().layout.setActiveItem(0);
}
},
// Обновляем содержимое панели
reload: function(panel) {
if (panel.items.first()) {
if (panel.items.first().cmpReload) {
panel.items.first().cmpReload();
return;
}
}
return;
},
remove: function(panel){
if (panel.taskBtn) {
Inprint.layout.getTaskbar().remove(panel.taskBtn);
}
for (var i = 0, len = objectStore.length; i < len; i++){
if (objectStore[i] == panel) {
objectHash[objectStore[i].panelId] = false;
objectStore.splice(i, 1);
if (objectStore[ i ]) {
Inprint.ObjectResolver.show(objectStore[ i ]);
}
else {
Inprint.ObjectResolver.show(objectStore[ i - 1 ]);
}
}
}
if (objectStore.length === 0) {
Inprint.layout.getPanel().layout.setActiveItem(0);
}
Inprint.layout.getPanel().remove(panel, true);
Inprint.layout.getPanel().doLayout();
}
};
}();
<file_sep>Inprint.setAction("edition.create", function(node) {
var url = _url("/catalog/editions/create/");
var form = new Ext.FormPanel({
url: url,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_PATH,
_FLD_TITLE,
_FLD_SHORTCUT,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_ADD,_BTN_CLOSE ]
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
if (node.reload) {
node.reload();
}
else if (node.parentNode.reload) {
node.parentNode.reload();
}
}
}, this);
form.getForm().findField("path").setValue(node.id);
var win = Inprint.factory.windows.create(
"Create edition", 400, 230, form
).show();
});
<file_sep>Inprint.documents.editor.Form = Ext.extend(Ext.form.HtmlEditor,
{
initComponent: function()
{
var options = Inprint.session.options;
var fontSizeTitles = {
"small": "1em",
"medium": "1.2em",
"large": "1.4em"
};
var fontStyleTitles = {
"times new roman": "Times New Roman"
};
var fontStyle = fontStyleTitles[ options["default.font.style"] ] || "times new roman";
var fontSize = fontSizeTitles [ options["default.font.size"] ] || "1.2em";
Ext.apply(this, {
border: false,
name: 'text',
enableFont: false,
enableLinks: false,
enableColors: false,
enableFontSize: false,
enableAlignments: false,
fontFamilies: ['Times New Roman'],
style: 'font-family:"'+ fontStyle +'";font-size:'+ fontSize +';',
plugins: [
new Ext.ux.form.HtmlEditor.RemoveFormat(),
//new Ext.ux.form.HtmlEditor.Word(),
new Ext.ux.form.HtmlEditor.UndoRedo(),
new Ext.ux.form.HtmlEditor.Divider(),
new Ext.ux.form.HtmlEditor.SpecialCharacters(),
new Ext.ux.form.HtmlEditor.SubSuperScript()
]
});
Inprint.documents.editor.Form.superclass.initComponent.apply(this, arguments);
},
// Override other inherited methods
onRender: function() {
Inprint.documents.editor.Form.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.cmp.memberSetupWindow.Interaction = function(panels) {
};
<file_sep>"use strict";
Inprint.fascicle.planner.Context = function(parent, panels) {
var view = panels.pages.getView();
view.on("contextmenu", function( view, index, node, e) {
if (parent.access.save == false) return false;
e.stopEvent();
var selection = panels.pages.cmpGetSelected();
var selLength = selection.length;
var disabled = true;
var disabled1 = true;
var disabled2 = true;
var items = [];
if (parent.access.save) {
if (selLength == 1) {
disabled1 = false;
}
if (selLength > 0 && selLength < 3) {
disabled2 = false;
}
disabled = false;
}
items.push(
{
ref: "../btnPageCreate",
disabled: disabled,
text: "Добавить полосу",
tooltip: 'Добавить новые полосы в этот выпуск',
icon: _ico("plus-button"),
cls: 'x-btn-text-icon',
scope: panels.pages,
handler: panels.pages.cmpPageCreate
},
{
ref: "../btnPageUpdate",
disabled:disabled,
text:'Редактировать',
icon: _ico("pencil"),
cls: 'x-btn-text-icon',
scope: panels.pages,
handler: panels.pages.cmpPageUpdate
},
"-",
{
ref: "../btnCompose",
disabled:disabled2,
text:'Разметить',
icon: _ico("wand"),
cls: 'x-btn-text-icon',
scope: panels.pages,
handler: panels.pages.cmpPageCompose
},
"-",
{
ref: "../btnPageMoveLeft",
disabled:disabled1,
text:'Сместить влево',
tooltip: 'Перенести отмеченные полосы',
icon: _ico("arrow-stop-180"),
cls: 'x-btn-text-icon',
scope:panels.pages,
handler: panels.pages.cmpPageMoveLeft
},
{
ref: "../btnPageMoveRight",
disabled:disabled1,
text:'Сместить вправо',
tooltip: 'Перенести отмеченные полосы',
icon: _ico("arrow-stop"),
cls: 'x-btn-text-icon',
scope:panels.pages,
handler: panels.pages.cmpPageMoveRight
},
{
ref: "../btnPageMove",
disabled:disabled,
text:'Перенести',
tooltip: 'Перенести отмеченные полосы',
icon: _ico("navigation-000-button"),
cls: 'x-btn-text-icon',
scope:panels.pages,
handler: panels.pages.cmpPageMove
},
"-",
{
ref: "../btnPageClean",
disabled:disabled,
text: 'Очистить',
tooltip: 'Очистить содержимое полос',
icon: _ico("eraser"),
cls: 'x-btn-text-icon',
scope:panels.pages,
handler: panels.pages.cmpPageClean
},
//{
// ref: "../btnPageResize",
// disabled:disabled,
// text: 'Разверстать',
// tooltip: 'Добавить новые полосы скопировав содержимое',
// icon: _ico("arrow-resize-045"),
// cls: 'x-btn-text-icon',
// scope:panels.pages,
// handler: panels.pages.cmpPageResize
//},
"-",
{
ref: "../btnPageDelete",
disabled:disabled,
text: 'Удалить',
tooltip: 'Удалить полосы',
icon: _ico("minus-button"),
cls: 'x-btn-text-icon',
scope:panels.pages,
handler: panels.pages.cmpPageDelete
}
);
items.push('-', {
icon: _ico("arrow-circle-double"),
cls: "x-btn-text-icon",
text: _("Reload"),
scope: this,
handler: this.cmpReload
});
return new Ext.menu.Menu({ items : items }).showAt( e.getXY() );
}, view);
};
<file_sep>Inprint.catalog.indexes.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.access = {};
this.panels = {
editions: new Inprint.panel.tree.Editions({
parent: this
}),
headlines: new Inprint.catalog.indexes.TreeHeadlines({
parent: this
}),
rubrics: new Inprint.catalog.indexes.Rubrics({
parent: this
}),
help: new Inprint.panels.Help({
hid: this.xtype
})
};
Ext.apply(this, {
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
region: "center",
border:false,
layout: "hbox",
margins: "3 0 3 0",
layoutConfig: {
align : 'stretch',
pack : 'start'
},
items: [
{
flex:1,
layout:"fit",
margins: "0 1 0 0",
width: 200,
collapsible: false,
split: true,
items: this.panels.headlines
},
{
flex:2,
layout:"fit",
margins: "0 0 0 1",
items: this.panels.rubrics
}
]
},
{
region:"west",
margins: "3 0 3 3",
width: 200,
minSize: 200,
maxSize: 600,
layout:"fit",
items: this.panels.editions
},
{
region:"east",
margins: "3 3 3 0",
width: 400,
minSize: 200,
maxSize: 600,
collapseMode: 'mini',
layout:"fit",
items: this.panels.help
}
]
});
Inprint.catalog.indexes.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.catalog.indexes.Panel.superclass.onRender.apply(this, arguments);
Inprint.catalog.indexes.Interaction(this, this.panels);
},
cmpReload: function() {
if ( this.panels.rubrics.disabled === false ) {
this.panels.rubrics.cmpReload();
}
}
});
Inprint.registry.register("settings-index", {
icon: "marker",
text: _("Index"),
xobject: Inprint.catalog.indexes.Panel
});
<file_sep>-- Inprint Content 5.0
-- Copyright(c) 2001-2010, Softing, LLC.
-- <EMAIL>
-- http://softing.ru/license
GRANT ALL ON plugins.l18n TO inprint;
GRANT ALL ON plugins.menu TO inprint;
GRANT ALL ON plugins.routes TO inprint;
GRANT ALL ON plugins.rules TO inprint;
GRANT ALL ON public.ad_advertisers TO inprint;
GRANT ALL ON public.ad_index TO inprint;
GRANT ALL ON public.ad_modules TO inprint;
GRANT ALL ON public.ad_pages TO inprint;
GRANT ALL ON public.ad_places TO inprint;
GRANT ALL ON public.ad_requests TO inprint;
GRANT ALL ON public.branches TO inprint;
GRANT ALL ON public.cache_access TO inprint;
GRANT ALL ON public.cache_files TO inprint;
GRANT ALL ON public.cache_hotsave TO inprint;
GRANT ALL ON public.cache_versions TO inprint;
GRANT ALL ON public.cache_visibility TO inprint;
GRANT ALL ON public.catalog TO inprint;
GRANT ALL ON public.comments TO inprint;
GRANT ALL ON public.documents TO inprint;
GRANT ALL ON public.editions TO inprint;
GRANT ALL ON public.editions_options TO inprint;
GRANT ALL ON public.fascicles TO inprint;
GRANT ALL ON public.fascicles_indx_headlines TO inprint;
GRANT ALL ON public.fascicles_indx_rubrics TO inprint;
GRANT ALL ON public.fascicles_map_documents TO inprint;
GRANT ALL ON public.fascicles_map_modules TO inprint;
GRANT ALL ON public.fascicles_map_requests TO inprint;
GRANT ALL ON public.fascicles_modules TO inprint;
GRANT ALL ON public.fascicles_options TO inprint;
GRANT ALL ON public.fascicles_pages TO inprint;
GRANT ALL ON public.fascicles_requests TO inprint;
GRANT ALL ON public.fascicles_tmpl_index TO inprint;
GRANT ALL ON public.fascicles_tmpl_modules TO inprint;
GRANT ALL ON public.fascicles_tmpl_pages TO inprint;
GRANT ALL ON public.fascicles_tmpl_places TO inprint;
GRANT ALL ON public.history TO inprint;
GRANT ALL ON public.indx_headlines TO inprint;
GRANT ALL ON public.indx_rubrics TO inprint;
GRANT ALL ON public.indx_tags TO inprint;
GRANT ALL ON public.logs TO inprint;
GRANT ALL ON public.map_member_to_catalog TO inprint;
GRANT ALL ON public.map_member_to_rule TO inprint;
GRANT ALL ON public.map_principals_to_stages TO inprint;
GRANT ALL ON public.map_role_to_rule TO inprint;
GRANT ALL ON public.members TO inprint;
GRANT ALL ON public.migration TO inprint;
GRANT ALL ON public.options TO inprint;
GRANT ALL ON public.profiles TO inprint;
GRANT ALL ON public.readiness TO inprint;
GRANT ALL ON public.roles TO inprint;
GRANT ALL ON public.rss TO inprint;
GRANT ALL ON public.rss_feeds TO inprint;
GRANT ALL ON public.rss_feeds_mapping TO inprint;
GRANT ALL ON public.rss_feeds_options TO inprint;
GRANT ALL ON public.rules TO inprint;
GRANT ALL ON public.sessions TO inprint;
GRANT ALL ON public.stages TO inprint;
GRANT ALL ON public.state TO inprint;
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.namespace("Inprint.grid");
/* Grid */
Inprint.grid.GridPanel = Ext.extend(Ext.grid.GridPanel, {
/* Custom settings */
cacheParams: { },
border:false,
stripeRows: true,
columnLines: true,
trackMouseOver: false,
loadMask: { msg: _("Loading data...") },
viewConfig: {
emptyText: _("Suitable data is not found"),
deferEmptyText : false
},
/* Custom functions */
cmpGetRecord: function() {
return this.getSelectionModel().getSelected();
},
cmpGetValue: function(value) {
var result;
if (this.getSelectionModel().getSelected()) {
result = this.getSelectionModel().getSelected().get(value);
}
return result;
},
cmpGetValues: function(field) {
var data = [];
Ext.each(this.getSelectionModel().getSelections(), function(record) {
data.push(record.data[field]);
});
return data;
},
cmpClear: function() {
this.getStore().removeAll();
},
cmpLoad: function(params, clear) {
if (clear) {
this.cacheParams = params;
} else {
Ext.apply(this.cacheParams, params);
}
this.getStore().removeAll();
this.getStore().reload({ params: this.cacheParams });
},
cmpReload: function() {
this.getStore().removeAll();
this.getStore().reload();
}
});
// OLD
Ext.grid.GridPanel.prototype.cacheParams = { };
Ext.grid.GridPanel.prototype.loadMask = { msg: _("Loading data...") };
Ext.grid.GridPanel.prototype.viewConfig = {
emptyText: _("Suitable data is not found"),
deferEmptyText : false
};
Ext.grid.GridPanel.prototype.getRecord = function() {
return this.getSelectionModel().getSelected();
};
Ext.grid.GridPanel.prototype.getValue = function(value) {
var result;
if (this.getSelectionModel().getSelected()) {
result = this.getSelectionModel().getSelected().get(value);
}
return result;
};
Ext.grid.GridPanel.prototype.getValues = function(field) {
var data = [];
Ext.each(this.getSelectionModel().getSelections(), function(record) {
data.push(record.data[field]);
});
return data;
};
Ext.grid.GridPanel.prototype.cmpClear = function() {
this.getStore().removeAll();
};
Ext.grid.GridPanel.prototype.cmpLoad = function(params, clear) {
if (clear) {
this.cacheParams = params;
} else {
Ext.apply(this.cacheParams, params);
}
this.getStore().removeAll();
this.getStore().reload({ params: this.cacheParams });
};
Ext.grid.GridPanel.prototype.cmpReload = function() {
this.getStore().removeAll();
this.getStore().reload();
};
<file_sep>"use strict";
Inprint.calendar.ux.columns = {
icon: {
dataIndex: 'fastype',
width: 24,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
if (value == 'issue') var icon = _ico("blue-folder");
if (value == 'attachment') var icon = _ico("folder");
if (value == 'template') var icon = _ico("puzzle");
return String.format('<img src="{0}"/>', icon);
}
},
status: {
dataIndex: 'enabled',
width: 24,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
if (value == 1) var icon = _ico("status");
if (value == 0) var icon = _ico("status-offline");
return String.format('<img src="{0}"/>', icon);
}
},
edition: {
header: _("Edition"),
dataIndex: 'edition_shortcut',
width: 180
},
shortcut: {
header: _("Shortcut"),
dataIndex: 'shortcut',
width: 180
},
template: {
header: _("Template"),
dataIndex: 'tmpl_shortcut',
width: 100
},
num: {
header: _("Number"),
dataIndex: 'num',
width: 80,
tpl: new Ext.XTemplate('{num}/{anum}')
},
circulation: {
header: _("Circulation"),
dataIndex: 'circulation',
width: 80
},
printdate: {
header: _("To print"),
dataIndex: 'print_date',
width: 120,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return _fmtDate(value, 'F j, H:i');
}
},
releasedate: {
header: _("To publication"),
dataIndex: 'release_date',
width: 120,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return _fmtDate(value, 'F j, H:i');
}
},
docdate: {
header: _("Documents"),
dataIndex: 'doc_date',
width: 120,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return _fmtDate(value, 'F j, H:i');
}
},
advdate: {
header: _("Advertisements"),
dataIndex: 'adv_date',
width: 120,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return _fmtDate(value, 'F j, H:i');
}
},
advmodules: {
header: _("Modules"),
dataIndex: 'adv_modules',
width: 80,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return value;
}
},
created: {
header: _("Created"),
dataIndex: 'created',
width: 120,
hidden:true,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return _fmtDate(value, 'F j, H:i');
}
},
updated: {
header: _("Updated"),
dataIndex: 'updated',
width: 120,
hidden:true,
renderer: function(value, metaData, record, rowIndex, colIndex, store) {
return _fmtDate(value, 'F j, H:i');
}
}
};
<file_sep>Ext.namespace("Inprint.cmp.memberProfile");
<file_sep>Inprint.setAction("headline.create", function(headlines) {
var edition = headlines.getEdition();
var url = _url("/catalog/headlines/create/");
var form = new Ext.FormPanel({
url: url,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:5px 5px",
items: [
_FLD_HDN_EDITION,
{
xtype: "titlefield",
value: _("Basic options")
},
_FLD_TITLE,
_FLD_DESCRIPTION,
{
xtype: "titlefield",
value: _("More options")
},
{
xtype: 'checkbox',
fieldLabel: _(""),
labelSeparator: '',
boxLabel: _("Use by default"),
name: 'bydefault',
checked: false
}
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_ADD,_BTN_CLOSE ]
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
headlines.cmpReload();
}
}, this);
form.getForm().findField("edition").setValue(edition);
var win = Inprint.factory.windows.create(
"Create headline", 400, 260, form
).show();
});
<file_sep>/*
* Ext.ux.DatePickerPlus Addon
* Ext.ux.form.DateFieldPlus Addon
*
* @author <NAME> (wm003/lubber)
* @copyright (c) 2008, <NAME> (<EMAIL>) http://www.lubber.de
*
* translation by WhiteRussian
*/
// Be sure to include this AFTER the datepickerwidget in your html-files
if (Ext.ux.DatePickerPlus) {
Ext.apply(Ext.ux.DatePickerPlus.prototype, {
weekName : "Нд",
startDay: 1,
selectWeekText : "Нажмите чтобы выделить все дни в этой неделе",
selectMonthText : "Нажмите чтобы выделить все недели в этом месяце",
maxSelectionDaysTitle: 'Календарь',
maxSelectionDaysText: 'Вы можете выбрать только %0 дней',
undoText: "Отменить",
displayMaskText: 'Пожалуйста подождите...',
nextYearText: "Следующий год (Control+Вверх)",
prevYearText: "Предыдущий год (Control+Вниз)",
nationalHolidays: function(year) {
year = (typeof year === "undefined" ? (this.lastRenderedYear ? this.lastRenderedYear : new Date().getFullYear()) : parseInt(year, 10));
var holidays =
[
{
text: "Новый год",
date: new Date(year, 0, 1)
},
{
text: "Новогодние каникулы",
date: new Date(year, 0, 2)
},
{
text: "Новогодние каникулы",
date: new Date(year, 0, 3)
},
{
text: "Новогодние каникулы",
date: new Date(year, 0, 4)
},
{
text: "Новогодние каникулы",
date: new Date(year, 0, 5)
},
{
text: "<NAME>",
date: new Date(year, 0, 7)
},
{
text: "День защитника Отечества",
date: new Date(year, 1, 23)
},
{
text: "Международный женский день",
date: new Date(year, 2, 8)
},
{
text: "Праздник весны и труда",
date: new Date(year, 3, 1)
},
{
text: "День Победы",
date: new Date(year, 3, 9)
},
{
text: "День России",
date: new Date(year, 5, 12)
},
{
text: "День народного единства",
date: new Date(year, 10, 4)
}
];
return holidays;
}
});
}
<file_sep>//Ext.namespace("Inprint.portal.employees");
<file_sep>Inprint.fascicle.adverta.Access = function(parent, panels, access) {
parent.access = access;
var pages = panels.pages;
var requests = panels.requests;
//Seance
_hide(parent.btnCaptureSession, parent.btnBeginSession, parent.btnEndSession);
_disable(parent.btnCaptureSession, parent.btnBeginSession, parent.btnEndSession, parent.btnSave);
if (access.open && parent.btnBeginSession) {
parent.btnBeginSession.show();
parent.btnBeginSession.enable();
}
if (access.capture && parent.btnCaptureSession) {
parent.btnCaptureSession.show();
parent.btnCaptureSession.enable();
}
if (access.close && parent.btnEndSession) {
parent.btnEndSession.show();
parent.btnEndSession.enable();
}
if (access.save && parent.btnSave) {
parent.btnSave.show();
parent.btnSave.enable();
}
//Pages
//if (access.manage) {
// //parent.btnPageCreate.enable();
//} else {
// //parent.btnPageCreate.disable();
//}
//requests.getSelectionModel().on("selectionchange", function(sm) {
//
//});
};
<file_sep>#!/bin/sh
# Inprint Content 5.0
# Copyright(c) 2001-2010, Softing, LLC.
# <EMAIL>
# http://softing.ru/license
sudo -u postgres psql -d template1 -c "CREATE USER inprint WITH PASSWORD '<PASSWORD>';"
sudo -u postgres psql -d template1 -c "CREATE DATABASE \"inprint-5.0\" OWNER inprint ENCODING 'UTF8'"
sudo -u postgres psql -d template1 -c "GRANT ALL PRIVILEGES ON DATABASE \"inprint-5.0\" TO inprint;"
<file_sep>//Inprint.portal.employees.Panel = Ext.extend(Ext.Panel, {
//
// initComponent: function() {
//
// Inprint.portal.employees.Panel.superclass.initComponent.apply(this, arguments);
//
// },
//
// onRender: function() {
// Inprint.portal.employees.Panel.superclass.onRender.apply(this, arguments);
// }
//});
<file_sep>Ext.namespace("Inprint.catalog.organization");
Ext.namespace("Inprint.member.profile");
<file_sep>Inprint.catalog.organization.Grid = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.components = {};
this.urls = {
"list": "/catalog/members/list/",
"create": _url("/catalog/members/create/"),
"remove": _url("/catalog/members/delete/")
};
this.store = Inprint.factory.Store.json(this.urls.list);
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.selectionModel,
{
id:"login",
header: _("Login"),
width: 80,
sortable: true,
dataIndex: "login"
},
{
id:"position",
header: _("Position"),
width: 160,
sortable: true,
dataIndex: "position"
},
{
id:"shortcut",
header: _("Shortcut"),
width: 120,
sortable: true,
dataIndex: "shortcut"
},
{
id:"name",
header: _("Title"),
width: 120,
sortable: true,
dataIndex: "title"
}
];
this.tbar = [
{
xtype: 'buttongroup',
title: _("Employees"),
defaults: { scale: 'small' },
items: [
{
icon: _ico("user--plus"),
cls: "x-btn-text-icon",
text: _("Add"),
disabled:true,
ref: "../../btnAdd",
scope:this,
handler: this.cmpAddToOrganization
},
{
icon: _ico("user--minus"),
cls: "x-btn-text-icon",
text: _("Remove"),
disabled:true,
ref: "../../btnDelete",
scope:this,
handler: this.cmpDeleteFromOrganization
}
]
},
{
xtype: 'buttongroup',
title: _("Membership"),
defaults: { scale: 'small' },
items: [
{
icon: _ico("plug"),
cls: "x-btn-text-icon",
text: _("Add"),
disabled:true,
ref: "../../btnAddToGroup"
},
{
icon: _ico("plug-disconnect"),
cls: "x-btn-text-icon",
text: _("Remove"),
disabled:true,
ref: "../../btnDeleteFromGroup"
}
]
},
{
xtype: 'buttongroup',
title: _("Profile"),
defaults: { scale: 'small' },
items: [
{
disabled:true,
icon: _ico("card"),
cls: "x-btn-text-icon",
text: _("View"),
ref: "../../btnViewProfile"
},
{
disabled:true,
icon: _ico("card--pencil"),
cls: "x-btn-text-icon",
text: _("Edit"),
ref: "../../btnUpdateProfile"
},
{
disabled:true,
icon: _ico("key-solid"),
cls: "x-btn-text-icon",
text: _("Rights"),
ref: "../../btnManageRules"
}
]
},
{
xtype: 'buttongroup',
title: _("Filter"),
defaults: { scale: 'small' },
items: [
{
xtype:"searchfield",
width:200,
store: this.store
}
]
}
];
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "name",
enableDragDrop: true,
ddGroup:'member2catalog'
});
Inprint.catalog.organization.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.catalog.organization.Grid.superclass.onRender.apply(this, arguments);
},
// Organization
cmpAddToOrganization: function() {
var win = this.components["add-to-organization-window"];
if (!win) {
win = new Ext.Window({
title: _("Edition addition"),
layout: "fit",
closeAction: "hide",
width:400, height:350,
items: new Ext.FormPanel({
url: this.urls.create,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%"
},
bodyStyle: "padding:10px",
items: [
{
xtype:'fieldset',
title: _("System Information"),
defaults: { anchor: "100%" },
defaultType: "textfield",
items :[
{
fieldLabel: _("Login"),
name: "login"
},
{
fieldLabel: _("Password"),
name: "<PASSWORD>"
}
]
},
{
xtype:'fieldset',
title: _("User Information"),
defaults: { anchor: "100%" },
defaultType: "textfield",
items :[
{
fieldLabel: _("Title"),
name: "title"
},
{
fieldLabel: _("Shortcut"),
name: "shortcut"
},
{
fieldLabel: _("Position"),
name: "position"
}
]
}
],
buttons: [
{
text: _("Add"),
handler: function() {
win.items.first().getForm().submit();
}
},
{
text: _("Cancel"),
handler: function() {
win.hide();
}
}
],
listeners: {
scope:this,
"actioncomplete": function() {
win.hide();
this.cmpReload();
}
}
})
});
}
var form = win.items.first().getForm();
form.reset();
win.show(this);
this.components["add-to-organization-window"] = win;
},
cmpDeleteFromOrganization: function() {
Ext.MessageBox.confirm(
_("Account removal"),
_("You really want to remove the selected accounts?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls.remove,
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Ext.ns("Inprint.advert.index");<file_sep>Inprint.cmp.memberRulesForm.Interaction = function(main, panels) {
var domainPanel = main.cmpGetDomainPanel();
var editionsPanel = main.cmpGetEditionsPanel();
var organizationPanel = main.cmpGetOrganizationPanel();
var handlerSave = function(){
main.cmpSave( main.panels.tabs.getActiveTab().cmpGetGrid() );
};
var handlerClear = function(){
main.cmpClear( main.panels.tabs.getActiveTab().cmpGetGrid() );
};
main.panels.domain.cmpGetGrid().btnSave.on("click", handlerSave);
main.panels.editions.cmpGetGrid().btnSave.on("click", handlerSave);
main.panels.organization.cmpGetGrid().btnSave.on("click", handlerSave);
main.panels.editions.cmpGetGrid().btnClear.on("click", handlerClear);
main.panels.organization.cmpGetGrid().btnClear.on("click", handlerClear);
// Domain
domainPanel.on("activate", function() {
main.cmpFill(
domainPanel.cmpGetGrid()
);
});
// Editions
editionsPanel.cmpGetTree().getSelectionModel().on("selectionchange", function(sm, node) {
var grid = editionsPanel.cmpGetGrid();
grid.enable();
grid.cmpSetBinding(node.id);
if (node) main.cmpFill( grid );
});
// Catalog
organizationPanel.cmpGetTree().getSelectionModel().on("selectionchange", function(sm, node) {
var grid = organizationPanel.cmpGetGrid();
grid.enable();
grid.cmpSetBinding(node.id);
if (node) main.cmpFill( grid );
});
};
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.namespace("Inprint.documents.briefcase");
<file_sep>-- Inprint Content 5.0
-- Copyright(c) 2001-2011, Softing, LLC.
-- <EMAIL>
-- http://softing.ru/license
-- Package: RSS Plugin, RU Locale
-- Version: 1.0
UPDATE plugins.rules SET rule_sortorder=1000, rule_title = 'Может редактировать RSS' WHERE id = 'b98fb3fd-2593-44c8-bcd8-12da48693ef7';
DELETE FROM plugins.l18n WHERE plugin='rss' AND l18n_language='ru';
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'RSS feeds', 'RSS ленты');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Access denide', 'Доступ запрещен');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Please, select document', 'Пожалуйста, выберите материал');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Publish', 'Опубликовать');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Unpublish', 'Снять с публикации');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Show', 'Показать');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Show all', 'Показать все');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Show with RSS', 'Показать с RSS');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Show without RSS', 'Показать без RSS');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Feeds', 'Ленты');
INSERT INTO plugins.l18n (plugin, l18n_language, l18n_original, l18n_translation)
VALUES ('rss', 'ru', 'Default feed', 'Лента по умолчанию');
INSERT INTO plugins_rss.rss_feeds(id, url, title, description, published, created, updated)
VALUES ('00000000-0000-0000-0000-000000000000', 'default', 'По умолчанию', 'По умолчанию', true, now(), now());<file_sep>Inprint.calendar.forms.CreateTemplateForm = Ext.extend( Ext.form.FormPanel,
{
initComponent: function()
{
this.items = [
{
allowBlank:false,
xtype: "treecombo",
name: "edition-shortcut",
hiddenName: "edition",
fieldLabel: _("Edition"),
emptyText: _("Edition") + "...",
minListWidth: 300,
url: _url('/common/tree/editions/'),
baseParams: {
term: 'editions.fascicle.manage:*'
},
root: {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
expanded: true,
draggable: false,
icon: _ico("book"),
text: _("All editions")
},
listeners: {
scope: this,
render: function(field) {
var id = Inprint.session.options["default.edition"];
var title = Inprint.session.options["default.edition.name"] || _("Unknown edition");
if (id && title) {
field.setValue(id, title);
}
}
}
},
{
xtype: "textfield",
name: "shortcut",
allowBlank:false,
fieldLabel: _("Shortcut")
},
{
xtype: "textfield",
name: "description",
fieldLabel: _("Description")
},
{
xtype: "numberfield",
name: "adv_modules",
fieldLabel: _("Modules")
}
];
Ext.apply(this, {
baseCls: 'x-plain',
defaults:{ anchor:'100%' }
});
Inprint.calendar.forms.CreateTemplateForm.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.calendar.forms.CreateTemplateForm.superclass.onRender.apply(this, arguments);
this.getForm().url = _source("template.create");
},
setEdition: function(id) {
this.cmpSetValue("edition", id);
}
});
<file_sep>Ext.namespace("Inprint.cmp.composer");<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.namespace("Inprint.factory.buttons");
Inprint.factory.buttons.manager = new function () {
var items = {};
return {
set: function(name, item) {
items[name] = item;
},
get: function(name, icon, tooltip, params) {
var item = items[name];
if (!item) {
return {
text: name,
icon: _ico("question-button"),
cls: "x-btn-text-icon",
tooltip: item.ref
};
}
item.disabled = true;
item.cls = "x-btn-text-icon";
item.tooltip = item.ref;
if (icon) {
item.icon = _ico(icon);
}
if (tooltip) {
item.tooltip = _(tooltip);
}
if (params) {
Ext.apply(item, params);
}
return item;
}
}
};
Inprint.setButton = function (name, item) {
return Inprint.factory.buttons.manager.set(name, item);
}
Inprint.getButton = function (name, params) {
return Inprint.factory.buttons.manager.get(name, params);
}
Inprint.setButton("create.item", {
text: _("Add"),
ref: "../btnCreateItem",
icon: _ico("plus-button")
});
Inprint.setButton("update.item", {
text: _("Edit"),
ref: "../btnUpdateItem",
icon: _ico("pencil")
});
Inprint.setButton("delete.item", {
text: _("Delete"),
icon: _ico("minus-button"),
ref: "../btnDeleteItem"
});
Inprint.setButton("select.principals", {
text: _("Select employees"),
icon: _ico("users"),
ref: "../btnSelectPrincipals"
});
<file_sep>"use strict";
Inprint.calendar.ViewPlanAction = function() {
var record = this.getRecord();
Inprint.ObjectResolver.resolve({ aid:'fascicle-plan', oid: record.get("id"), text: record.get("shortcut") });
};
Inprint.calendar.ViewComposerAction = function() {
var record = this.getRecord();
Inprint.ObjectResolver.resolve({ aid:'fascicle-planner', oid: record.get("id"), text: record.get("shortcut") });
};
Inprint.calendar.TemplateComposerAction = function() {
var record = this.getRecord();
Inprint.ObjectResolver.resolve({ aid:'fascicle-template-composer', oid: record.get("id"), text: record.get("shortcut") });
};
/* Enable trigger */
Inprint.calendar.EnableAction = function() {
var record = this.getRecord();
Ext.Ajax.request({
url: _source("calendar.enable"),
params: { id: record.get("id") },
success: function() {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
}.createDelegate(this)
});
}
Inprint.calendar.DisableAction = function() {
var record = this.getRecord();
Ext.Ajax.request({
url: _source("calendar.disable"),
params: { id: record.get("id") },
success: function() {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
}.createDelegate(this)
});
}
/* Copy */
Inprint.calendar.CopyIssueAction = function() {
var form = new Inprint.calendar.forms.CopyIssueForm({
parent: this
});
form.setId( this.getRecord().get("id") );
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
400, 170, _("Copy issue"),
form, [ _BTN_WNDW_OK, _BTN_WNDW_CLOSE ]
).build().show();
};
Inprint.calendar.CopyAttachmentAction = function() {
var form = new Inprint.calendar.forms.CopyAttachmentForm({
parent: this
});
form.setSource( this.getRecord().get("id") );
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
400, 170, _("Copy attachment"),
form, [ _BTN_WNDW_OK, _BTN_WNDW_CLOSE ]
).build().show();
};
/* Properties*/
Inprint.calendar.PropertiesAction = function() {
var form = new Inprint.calendar.forms.Properties({
parent: this
});
form.setId( this.getRecord().get("id") );
form.on('actioncomplete', function(form, action) {
if (action.type == "submit") {
wndw.close();
this.cmpReload();
}
}, this);
Inprint.fx.Window(
400, 170, _("Copy issue"),
form, [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
).build().show();
};
Inprint.calendar.FormatAction = function() {
var form = new Inprint.calendar.forms.FormatForm({
parent: this
});
form.setId( this.getRecord().get("id") );
form.on('actioncomplete', function(basicForm, action) {
if (action.type == "submit") {
this.cmpReload();
form.findParentByType("window").close();
}
}, this);
Inprint.fx.Window(
400, 170, _("Format issue"),
form, [ _BTN_WNDW_SAVE, _BTN_WNDW_CLOSE ]
).build().show();
};
/* Archive trigger*/
Inprint.calendar.ArchiveAction = function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url: _source("calendar.archive"),
scope: this,
params: { id: this.getRecord().get("id") },
success: function() {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
}
});
return false;
}
if (btn == 'no') {
return false;
}
Ext.MessageBox.show({
title: _("Important event"),
msg: _("Archive the specified release?"),
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
fn: Inprint.calendar.ArchiveAction.createDelegate(this)
});
return true;
};
Inprint.calendar.UnarchiveAction = function(btn) {
if (btn == 'yes') {
Ext.Ajax.request({
url: _source("calendar.unarchive"),
scope: this,
params: { id: this.getRecord().get("id") },
success: function() {
this.cmpReload();
Inprint.layout.getMenu().CmpQuery();
}
});
return false;
}
if (btn == 'no') {
return false;
}
Ext.MessageBox.show({
title: _("Important event"),
msg: _("Unarchive the specified release?"),
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
fn: Inprint.calendar.UnarchiveAction.createDelegate(this)
});
return true;
};
<file_sep>Inprint.catalog.organization.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
this.access = {};
this.panels = {};
this.panels.tree = new Inprint.catalog.organization.Tree();
this.panels.grid = new Inprint.catalog.organization.Grid({
title: _("Members")
});
this.panels.help = new Inprint.panels.Help({ hid: this.xtype });
Ext.apply(this, {
layout: "border",
defaults: {
collapsible: false,
split: true
},
items: [
{
region: "center",
layout:"fit",
margins: "3 0 3 0",
items: this.panels.grid
},
{
region:"west",
margins: "3 0 3 3",
width: 200,
minSize: 200,
maxSize: 600,
layout:"fit",
items: this.panels.tree
},
{
region:"east",
margins: "3 3 3 0",
width: 400,
minSize: 200,
maxSize: 600,
layout:"fit",
collapseMode: 'mini',
collapsed: true,
items: this.panels.help
}
]
});
Inprint.catalog.organization.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.catalog.organization.Panel.superclass.onRender.apply(this, arguments);
Inprint.catalog.organization.Access(this, this.panels);
Inprint.catalog.organization.Context(this, this.panels);
Inprint.catalog.organization.Interaction(this, this.panels);
},
getRow: function() {
return this.panels.grid.getSelectionModel().getSelected().data;
},
cmpReload:function() {
this.panels.grid.cmpReload();
}
});
Inprint.registry.register("settings-organization", {
icon: "building",
text: _("Organization"),
xobject: Inprint.catalog.organization.Panel
});
<file_sep>Inprint.fx.Window = function(width, height, title, form, btns) {
var hash = {
plain: true,
modal: true,
layout: "fit",
closeAction: "hide",
bodyStyle:'padding:5px 5px 5px 5px',
title: title,
width: width,
height: height,
items: form,
buttons: btns
};
return {
build: function() {
return new Ext.Window(hash);
}
}
};
<file_sep>Inprint.catalog.indexes.TreeHeadlines = Ext.extend(Ext.tree.TreePanel, {
initComponent: function() {
this.edition = null;
this.loader = new Ext.tree.TreeLoader({
dataUrl: _url("/catalog/headlines/tree/"),
baseParams: this.baseParams
});
this.root = {
id:'00000000-0000-0000-0000-000000000000',
nodeType: 'async',
draggable: false
};
Ext.apply(this, {
title:_("Headlines"),
border:false,
disabled:true,
autoScroll:true,
rootVisible: false
});
Inprint.catalog.indexes.TreeHeadlines.superclass.initComponent.apply(this, arguments);
this.on("beforeappend", function(tree, parent, node) {
node.attributes.icon = _ico(node.attributes.icon);
});
},
onRender: function() {
Inprint.catalog.indexes.TreeHeadlines.superclass.onRender.apply(this, arguments);
this.getLoader().on("beforeload", function() { this.body.mask(_("Loading")); }, this);
this.getLoader().on("load", function() { this.body.unmask(); }, this);
},
getEdition: function() {
return this.edition;
},
setEdition: function(id) {
this.edition = id;
}
});
<file_sep>Inprint.cmp.memberProfile.Panel = Ext.extend(Ext.Panel, {
initComponent: function() {
Ext.apply(this, {
autoScroll:true,
bodyStyle: "padding: 10px 10px",
tpl: new Ext.XTemplate(
'<div class=" x-panel x-panel-noborder x-form-label-left x-column" style="width: 169px;">'+
'<div class="x-panel-bwrap">'+
'<div class="x-panel-body x-panel-body-noheader x-panel-body-noborder" style="width: 159px;">'+
'<fieldset class=" x-fieldset x-form-label-left" style="width: 137px;">'+
'<legend class="x-fieldset-header x-unselectable" style="-moz-user-select: none;">'+
'<span class="x-fieldset-header-text">'+ _("Photo") +'</span>'+
'</legend>'+
'<div class="x-fieldset-bwrap">'+
'<div class="x-fieldset-body" style="width: 137px;">'+
'<div tabindex="-1" class="x-form-item x-hide-label">'+
'<div style="padding-left: 45px;" class="x-form-element">'+
'<img name="imagefield" class="x-form-field" src="/profile/image/{id}" style="width: 137px;"></div>'+
'<div class="x-form-clear-left"></div>'+
'</div>'+
'</div>'+
'</div>'+
'</fieldset>'+
'</div>'+
'</div>'+
'</div>'+
'<div class=" x-panel x-panel-noborder x-form-label-left x-column" style="width: 394px;">'+
'<div class="x-panel-bwrap">'+
'<div class="x-panel-body x-panel-body-noheader x-panel-body-noborder" style="width: 394px;">'+
'<fieldset class=" x-fieldset x-form-label-left" style="width: 372px;">'+
'<legend class="x-fieldset-header x-unselectable" style="-moz-user-select: none;">'+
'<span class="x-fieldset-header-text">'+ _("System profile") +'</span>'+
'</legend>'+
'<div class="x-fieldset-bwrap">'+
'<div class="x-fieldset-body" style="width: 372px;">'+
'<div tabindex="-1" class="x-form-item " >'+
'<label class="x-form-item-label" style="width: 60px;">'+ _("ID") +':</label>'+
'<div style="padding-left: 65px;" class="x-form-element">'+
'{id}'+
'</div>'+
'<div class="x-form-clear-left"></div>'+
'</div>'+
'<div tabindex="-1" class="x-form-item " >'+
'<label class="x-form-item-label" style="width: 60px;">'+ _("Login") +':</label>'+
'<div style="padding-left: 65px;" class="x-form-element">'+
'{login}'+
'</div>'+
'<div class="x-form-clear-left"></div>'+
'</div>'+
'</div>'+
'</div>'+
'</fieldset>'+
'<fieldset class=" x-fieldset x-form-label-left" style="width: 372px;">'+
'<legend class="x-fieldset-header x-unselectable" style="-moz-user-select: none;">'+
'<span class="x-fieldset-header-text">'+ _("Employee profile") +'</span>'+
'</legend>'+
'<div class="x-fieldset-bwrap">'+
'<div class="x-fieldset-body" style="width: 372px;">'+
'<div tabindex="-1" class="x-form-item " >'+
'<label class="x-form-item-label" style="width: 60px;">'+ _("Title") +':</label>'+
'<div style="padding-left: 65px;" class="x-form-element">'+
'{title}'+
'</div>'+
'<div class="x-form-clear-left"></div>'+
'</div>'+
'<div tabindex="-1" class="x-form-item " >'+
'<label class="x-form-item-label" style="width: 60px;">'+ _("Shortcut") +':</label>'+
'<div style="padding-left: 65px;" class="x-form-element">'+
'{shortcut}'+
'</div>'+
'<div class="x-form-clear-left"></div>'+
'</div>'+
'<div tabindex="-1" class="x-form-item " >'+
'<label class="x-form-item-label" style="width: 60px;">'+ _("Position") +':</label>'+
'<div style="padding-left: 65px;" class="x-form-element">'+
'{position}'+
'</div>'+
'<div class="x-form-clear-left"></div>'+
'</div>'+
'</div>'+
'</div>'+
'</fieldset>'+
'</div>'+
'</div>'+
'</div>'
)
});
Inprint.cmp.memberProfile.Panel.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.memberProfile.Panel.superclass.onRender.apply(this, arguments);
}
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Ext.DataView.prototype.cmpLoad = function(params) {
if (params) {
this.params = params;
this.getStore().reload({ params: params });
} else {
this.getStore().reload({ params: this.params});
}
};
Ext.DataView.prototype.cmpReload = function() {
this.getStore().reload();
};
<file_sep>Inprint.cmp.uploader.Interaction = function(parent, panels) {
var flash = panels.flash;
var html = panels.html;
flash.on("fileupload", function(uploader, success, result){
if(success){
this.fireEvent("fileUploaded", this);
}
}, flash);
html.getForm().on("beforeaction", function ( form, action ) {
parent.body.mask();
}, html.getForm());
html.on("actioncomplete", function ( form, action ) {
parent.body.unmask();
this.fireEvent("fileUploaded", this);
}, html);
};
<file_sep>Inprint.fascicle.planner.Documents = Ext.extend(Ext.grid.EditorGridPanel, {
initComponent: function() {
var actions = new Inprint.documents.GridActions();
var columns = new Inprint.documents.GridColumns();
this.urls = {
"list": "/fascicle/documents/list/",
"briefcase": "/documents/briefcase/",
"capture": "/documents/capture/",
"transfer": "/documents/transfer/",
"recycle": "/documents/recycle/",
"restore": "/documents/restore/",
"delete": "/documents/delete/"
};
this.store = Inprint.factory.Store.group(this.urls.list, {
groupField:'headline_shortcut',
remoteGroup:true,
remoteSort:true,
sortInfo: {
field: 'headline_shortcut',
direction: 'ASC'
},
baseParams: {
gridmode: "all",
flt_fascicle: this.oid
}
});
this.sm = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.sm,
columns.viewed,
columns.title,
Ext.apply(columns.edition, {
hidden:true
}),
columns.maingroup,
columns.manager,
columns.workgroup,
Ext.apply(columns.fascicle, {
hidden:true
}),
columns.headline,
columns.rubric,
Ext.apply(columns.pages, {
editor: new Ext.form.TextField({
allowBlank: true
})
}),
columns.progress,
columns.holder,
columns.images,
columns.size
];
this.tbar = [
{
ref: "../btnCreate",
text: _("Add"),
disabled:true,
icon: _ico("plus-button"),
cls: 'x-btn-text-icon',
scope:this,
handler : actions.Create
},
{
ref: "../btnUpdate",
text: _("Edit"),
disabled:true,
icon: _ico("pencil"),
cls: 'x-btn-text-icon',
scope:this,
handler : actions.Update
},
'-',
{
icon: _ico("hand"),
cls: "x-btn-text-icon",
text: _("Capture"),
disabled:true,
ref: "../btnCapture",
scope:this,
handler: actions.Capture
},
{
icon: _ico("arrow"),
cls: "x-btn-text-icon",
text: _("Transfer"),
disabled:true,
ref: "../btnTransfer",
scope:this,
handler: actions.Transfer
},
"-",
{
ref: "../btnBriefcase",
text: 'В портфель',
disabled:true,
icon: _ico("briefcase--arrow"),
cls: 'x-btn-text-icon',
scope:this,
handler : actions.Briefcase
},
{
ref: "../btnMove",
text: 'В выпуск',
disabled:true,
icon: _ico("newspaper--arrow"),
cls: 'x-btn-text-icon',
scope:this,
handler : actions.Move
},
{
ref: "../btnRecycle",
text: 'В корзину',
disabled:true,
icon: _ico("bin--arrow"),
cls: 'x-btn-text-icon',
scope:this,
handler : actions.Recycle
},
"->",
{
ref: "../btnFromBriefcase",
text: 'Портфель',
disabled:true,
icon: _ico("briefcase"),
cls: 'x-btn-text-icon',
scope:this,
handler : this.cmpShowBriefcase
},
"-",
{
ref: "../btnSwitchToDocuments",
text: 'Документы',
icon: _ico("document-word"),
cls: 'x-btn-text-icon',
pressed: true,
scope:this
},
{
ref: "../btnSwitchToRequests",
text: 'Заявки',
icon: _ico("document-excel"),
cls: 'x-btn-text-icon',
scope:this
}
];
this.view = new Ext.grid.GroupingView({
forceFit:true,
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
});
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
sm: this.sm,
tbar: this.tbar,
columns: this.columns
});
Inprint.fascicle.planner.Documents.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.fascicle.planner.Documents.superclass.onRender.apply(this, arguments);
},
cmpShowBriefcase: function() {
this.dlgShowBriefcase = new Ext.Window({
title: 'Просмотр портфеля материалов',
width: 900, height: 600,
draggable:true,
layout: "fit",
items: new Inprint.fascicle.planner.Briefcase(),
buttons:[
{
text: _("Add"),
scope:this,
handler: function() {
var grid = this.dlgShowBriefcase.items.first();
Ext.Ajax.request({
url: _url("/documents/move/"),
scope: this,
params: {
fascicle: this.oid,
id: grid.getValues("id")
},
success: function(response, options) {
this.parent.cmpReload();
this.dlgShowBriefcase.hide();
}
});
}
},
_BTN_WNDW_CANCEL
]
});
this.dlgShowBriefcase.show();
}
});
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
//Inprint.TaskbarBtn = Ext.extend(Ext.Button, {
Inprint.TaskbarBtn = Ext.extend(Ext.Toolbar.SplitButton, {
panel: false,
icon: '',
text: '',
initComponent : function(){
this.tooltip = this.text;
if ( this.description ) {
this.text = this.text +' <'+ this.description +'>';
}
this.text = Ext.util.Format.ellipsis(this.text || 'Unnamed window', 60);
Ext.apply(this, {
panel: this.panel,
tooltip: this.tooltip,
toggleGroup: "taskbar",
enableToggle: true,
menu : {
items: [{
text: _("Close"),
scope: this,
icon: _ico("cross"),
handler: function() {
Inprint.ObjectResolver.remove(this.panel);
}
}]
}
});
Inprint.TaskbarBtn.superclass.initComponent.call(this);
this.on("click", function(btn) {
if (btn.pressed) {
Inprint.ObjectResolver.show(btn.panel);
} else {
Inprint.ObjectResolver.hide(btn.panel);
}
});
}
});
Inprint.TaskButton = function(cmp, el) {
this.cmp = cmp;
if (! cmp.rawTitle) {
cmp.rawTitle = 'Unnamed window';
}
var text = Ext.util.Format.ellipsis(cmp.rawTitle, 12);
var tooltip = false;
if (cmp.rawTitle.length > text.length) {
tooltip = cmp.rawTitle;
}
Ext.apply(this, {
icon: cmp.icon,
text: text,
tooltip: tooltip
});
Inprint.TaskButton.superclass.constructor.call(this, {
renderTo: el,
handler : function() {
Inprint.layout.show(cmp);
},
clickEvent:'mousedown',
template: new Ext.Template(
'<table border="0" cellpadding="0" cellspacing="0" class="x-btn-wrap x-btn x-btn-text-icon"><tbody><tr>',
'<td class="x-btn-left"><i> </i></td>',
'<td class="x-btn-center"><em unselectable="on"><button class="x-btn-text" type="{1}">{0}</button></em></td>',
'<td class="x-btn-right"><i> </i></td>',
"</tr></tbody></table>")
});
};
Ext.extend(Inprint.TaskButton, Ext.Button, {
onRender : function() {
Inprint.TaskButton.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.cmp.ExcahngeBrowser.Interaction = function(parent, panels) {
var editions = panels.editions;
var stages = panels.stages;
var principals = panels.principals;
editions.autoSelect = true;
stages.autoSelect = true;
// Tree
editions.getLoader().on("load", function(loader, node, rsp) {
var selection = node.findChild("id", parent.edition);
if (selection && editions.autoSelect) {
editions.getSelectionModel().select(selection);
editions.autoSelect = false;
}
});
editions.getSelectionModel().on("selectionchange", function(sm, node) {
if (node) {
stages.getRootNode().id = node.id;
stages.getRootNode().reload();
}
});
stages.getLoader().on("load", function(loader, node, rsp) {
var selection = node.findChild("id", parent.stage);
if (selection && stages.autoSelect) {
stages.getSelectionModel().select(selection);
stages.autoSelect = false;
}
});
stages.getSelectionModel().on("selectionchange", function(sm, node) {
principals.enable();
if (node) {
principals.cmpLoad({ node: node.id });
}
});
//Grids
principals.getSelectionModel().on("selectionchange", function(sm) {
if (sm.getCount() > 0) {
this.buttons[0].enable();
} else {
this.buttons[0].disable();
}
}, parent);
};
<file_sep>Inprint.fascicle.template.composer.Interaction = function(parent, panels) {
var pages = panels.pages;
// Pages view
pages.view.on("selectionchange", function(view, data) {
_disable(
parent.btnPageUpdate,
parent.btnPageDelete,
parent.btnPageMove,
parent.btnPageMoveLeft,
parent.btnPageMoveRight,
parent.btnPageResize);
if (parent.access.manage) {
if (data.length == 1) {
_enable(
parent.btnPageMoveLeft,
parent.btnPageMoveRight
);
}
if (data.length >= 1) {
_enable(
parent.btnPageUpdate,
parent.btnPageDelete,
parent.btnPageMove,
parent.btnPageResize
);
}
}
});
};
<file_sep>Inprint.plugins.rss.profile.Grid = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.store = new Ext.data.JsonStore({
autoLoad:false,
root: "data",
idProperty: "name",
url: _url('/plugin/rss/files/list/'),
fields: [ "id", "name", "description", "mime", "published", "size", "length", "created", "updated" ]
});
this.columns = [
{
id:"approved",
width: 32,
dataIndex: "published",
sortable: false,
renderer: function(v) {
var image = '';
if (v==1) { image = '<img src="'+ _ico("light-bulb") +'"/>'; }
return image;
}
},
{
id:"preview",
header:_("Preview"),
width: 100,
dataIndex: "id",
sortable: false,
renderer: function(v) {
return '<img src="/files/preview/'+ v +'x80" style="border:1px solid silver;"/>';
}
},
{
id:'title',
header: _("File"),
dataIndex:'name',
width:250,
renderer: function(v,p,r) {
var string = '<div><strong>'+v+'</strong></div>';
if (r.get('description')) {
string += '<span>'+ r.get('description') +'</span>';
}
return string;
}
},
{ id: 'size', header: _("Size"), dataIndex:'size', width:100, renderer:Ext.util.Format.fileSize},
{ id: 'created', header: _("Created"), dataIndex:'created', width:120 },
{ id: 'updated', header: _("Updated") ,dataIndex:'updated', width:120 }
];
Ext.apply(this, {
flex:1,
xtype: "grid",
border:false,
enableHdMenu:false,
maskDisabled: true,
loadMask: false,
bodyStyle: "padding:5px 5px",
autoExpandColumn: "title"
});
// Call parent (required)
Inprint.plugins.rss.profile.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.plugins.rss.profile.Grid.superclass.onRender.apply(this, arguments);
this.on("rowcontextmenu", function(thisGrid, rowIndex, evtObj) {
evtObj.stopEvent();
var rowCtxMenuItems = [];
rowCtxMenuItems.push({
icon: _ico("light-bulb"),
cls: "x-btn-text-icon",
text: _("Publish"),
scope:this,
handler: this.cmpPublish
});
rowCtxMenuItems.push({
icon: _ico("light-bulb-off"),
cls: "x-btn-text-icon",
text: _("Unpublish"),
scope:this,
handler: this.cmpUnpublish
});
rowCtxMenuItems.push("-");
rowCtxMenuItems.push({
icon: _ico("edit-column"),
cls: "x-btn-text-icon",
text: _("Change description"),
scope:this,
handler : this.cmpChangeDescription
});
rowCtxMenuItems.push("-");
rowCtxMenuItems.push({
icon: _ico("document-shred"),
cls: "x-btn-text-icon",
text: _("Delete file"),
scope:this,
handler : this.cmpDelete
});
thisGrid.rowCtxMenu = new Ext.menu.Menu({
items : rowCtxMenuItems
});
thisGrid.rowCtxMenu.showAt(evtObj.getXY());
}, this);
},
cmpPublish: function() {
var document = this.getStore().baseParams.document;
var file = this.getValues("id");
Ext.Ajax.request({
url: _url("/plugin/rss/files/publish/"),
scope:this,
success: this.cmpReload,
params: { document: document, file: file }
});
},
cmpUnpublish: function() {
var document = this.getStore().baseParams.document;
var file = this.getValues("id");
Ext.Ajax.request({
url: _url("/plugin/rss/files/unpublish/"),
scope:this,
success: this.cmpReload,
params: { document: document, file: file }
});
},
cmpRenameFile: function() {
var document = this.getStore().baseParams.document;
var file = this.getValues("id");
Ext.MessageBox.prompt(
_("Modification of the file"),
_("Change the file name"),
function(btn, text) {
if (btn == "ok") {
Ext.Ajax.request({
url: _url("/plugin/rss/files/rename/"),
scope:this,
success: this.cmpReload,
params: { document: document, file: file, text: text }
});
}
}, this);
},
cmpChangeDescription: function() {
var document = this.getStore().baseParams.document;
var file = this.getValues("id");
Ext.MessageBox.show({
width:300,
scope:this,
multiline: true,
buttons: Ext.MessageBox.OKCANCEL,
title: _("Modification of the file"),
msg: _("Change the file description"),
fn: function(btn, text) {
if (btn == "ok") {
Ext.Ajax.request({
url: _url("/plugin/rss/files/description/"),
scope:this,
success: this.cmpReload,
params: { document: document, file: file, text: text }
});
}
}
});
},
cmpDelete: function() {
var document = this.getStore().baseParams.document;
var file = this.getValues("id");
Ext.MessageBox.confirm(
_("Delete the file?"),
_("This change can not be undone!"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: _url("/plugin/rss/files/delete/"),
scope:this,
success: this.cmpReload,
params: { document: document, file: file }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Ext.namespace("Inprint.plugins.rss.profile");
<file_sep>// Inprint Content 5.0
// Copyright(c) 2001-2011, Softing, LLC.
// <EMAIL>
// http://softing.ru/license
Inprint.Taskbar = Ext.extend(Ext.Toolbar,{
initComponent: function() {
Ext.apply(this, {
height:28,
enableOverflow: true,
items: [ '-' ]
});
Inprint.Taskbar.superclass.initComponent.call(this);
},
onRender: function() {
Inprint.Taskbar.superclass.onRender.apply(this, arguments);
},
addButton: function(cfg) {
var btn = new Inprint.TaskbarBtn(cfg);
this.add(btn);
this.doLayout();
return btn;
},
pressButton : function(btn) {
this.items.each(function(item, index, length) {
item.removeClass('x-btn-pressed');
if (item == btn) {
item.addClass('x-btn-pressed');
}
});
}
});
<file_sep>Inprint.setAction("stage.create", function (grid) {
var url = _url("/catalog/stages/create/");
var edition = grid.getEdition();
var form = new Ext.FormPanel({
xtype:"form",
url: url,
frame:false,
border:false,
labelWidth: 75,
defaults: {
anchor: "100%",
allowBlank:false
},
bodyStyle: "padding:10px",
items: [
{
name: "branch",
xtype: "hidden",
allowBlank:false,
value: edition
},
Inprint.factory.Combo.getConfig("/catalog/combos/readiness/"),
{ xtype: 'spinnerfield',
fieldLabel: _("Weight"),
name: 'weight',
minValue: 0,
maxValue: 100,
incrementValue: 5,
accelerate: true
},
_FLD_SHORTCUT,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE, _BTN_CLOSE ]
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
grid.cmpReload();
}
});
var win = Inprint.factory.windows.create(
"Create stage", 400, 260, form
).show();
});
<file_sep>Inprint.cmp.UpdateDocument.Access = function(parent, form) {
_a(["catalog.documents.assign:*"], null, function(terms) {
if(terms["catalog.documents.assign"]) {
form.getForm().findField("maingroup").enable();
form.getForm().findField("manager").enable();
}
});
};
<file_sep>ALTER TABLE ad_advertisers ALTER COLUMN title DROP NOT NULL;
<file_sep>Inprint.documents.Profile.Files = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.access = {};
this.record = {};
this.title = _("Files");
this.config = {
document: this.oid
};
this.urls = {
"create": _url("/documents/files/create/"),
"read": _url("/documents/files/read/"),
"update": _url("/documents/files/update/"),
"delete": _url("/documents/files/delete/"),
"rename": _url("/documents/files/rename/"),
"publish": _url("/documents/files/publish/"),
"unpublish": _url("/documents/files/unpublish/"),
"description": _url("/documents/files/description/")
};
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
this.store = new Ext.data.JsonStore({
root: "data",
autoLoad: true,
url: _url("/documents/files/list/"),
baseParams: { document: this.config.document },
fields: [
"id", "document", "name", "description", "mime", "extension",
"published", "size", "length",
{ name: "created", type: "date", dateFormat: "c" },
{ name: "updated", type: "date", dateFormat: "c" }
]
});
// Column model
this.columns = [
this.selectionModel,
{
id:"published",
width: 32,
dataIndex: "published",
sortable: false,
renderer: function(v) {
var image = '';
if (v==1) { image = '<img src="'+ _ico("light-bulb") +'"/>'; }
return image;
}
},
{
id:"preview",
header:_("Preview"),
width: 100,
dataIndex: "id",
sortable: false,
scope: this,
renderer: function(v, p, record) {
if(record.get("name").match(/^.+\.(jpg|jpeg|png|gif|tiff|png)$/i)) {
return String.format(
"<a target=\"_blank\" href=\"/files/preview/{0}\"><img src=\"/files/preview/{0}x80\" style=\"border:1px solid silver;\"/></a>",
v);
}
if(record.get("name").match(/^.+\.(rtf|txt|doc|docx|odt)$/i)) {
var file = record.get("id");
var filename = record.get("name");
var document = record.get("document");
return String.format(
"<a href=\"/?aid=document-editor&oid={0}&pid={1}&text={2}\" "+
"onClick=\"Inprint.ObjectResolver.resolve({'aid':'document-editor','oid':'{0}','pid':'{1}','description':'{2}'});return false;\">"+
"<img src=\"/files/preview/{3}x80\" style=\"border:1px solid silver;\"/></a></a>",
file, document, escape(filename), v
);
}
return String.format("<img src=\"/files/preview/{0}x80\" style=\"border:1px solid silver;\"/></a>", v);
}
},
{ id:'name', header: _("File"), dataIndex:'name', width:250,
renderer: function(value, meta, record){
var text = String.format("<h2>{0}</h2>", value);
if (record.get("description")) {
text += String.format("<div><i>{0}</i></div>", record.get("description"));
}
text += String.format("<div style=\"padding:5px 0px;\"><a href=\"/files/download/{0}?original=true\">{1}</a></div>", record.get("id"), _("Original file"));
return text;
}},
{ id: "size", dataIndex:'size', header: _("Size"), width: 70, renderer: Ext.util.Format.fileSize},
{ id: "length", dataIndex:'length', header: _("Characters"), width: 50},
{ id: "created", dataIndex: "created", header: _("Created"), width: 100, xtype: 'datecolumn', format: 'M d H:i' },
{ id: "updated", dataIndex: "updated", header: _("Updated"), width: 100, xtype: 'datecolumn', format: 'M d H:i' }
];
this.tbar = [
{
icon: _ico("document--plus"),
cls: "x-btn-text-icon",
text: _("Create"),
disabled:true,
ref: "../btnCreate",
scope:this,
handler: this.cmpCreate
},
"-",
{
icon: _ico("arrow-transition-270"),
cls: "x-btn-text-icon",
text: _("Upload files"),
disabled:true,
ref: "../btnUpload",
scope:this,
handler: this.cmpUpload
},
"->",
{
icon: _ico("arrow-transition-090"),
cls: "x-btn-text-icon",
text: _("Get archive"),
scope:this,
handler: function() {
window.location = "/files/download/?rnd="+ Math.random() +"&document="+ this.oid;
}
},
{
icon: _ico("documents-stack"),
cls: "x-btn-text-icon",
text: _("Documents"),
scope:this,
handler: function() {
window.location = "/files/download/?rnd="+ Math.random() +"&filter=documents&document="+ this.oid;
}
},
{
icon: _ico("pictures-stack"),
cls: "x-btn-text-icon",
text: _("Images"),
scope:this,
handler: function() {
window.location = "/files/download/?rnd="+ Math.random() +"&filter=images&document="+ this.oid;
}
}
];
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "name"
});
// Call parent (required)
Inprint.documents.Profile.Files.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.documents.Profile.Files.superclass.onRender.apply(this, arguments);
this.on("rowcontextmenu", function(thisGrid, rowIndex, evtObj) {
evtObj.stopEvent();
var rowCtxMenuItems = [];
var record = thisGrid.getStore().getAt(rowIndex);
var selCount = thisGrid.getSelectionModel().getCount();
if ( selCount > 0 ) {
if ( selCount == 1 ) {
if(record.get("name").match(/^.+\.(doc|docx|odt|rtf|txt)$/i)) {
var btnIcon = (this.access["fedit"] === true) ? _ico("pencil") : _ico("pencil");
var btnText = (this.access["fedit"] === true) ? _("Edit text") : _("View text");
rowCtxMenuItems.push({
scope:this,
icon: btnIcon,
text: btnText,
cls: "x-btn-text-icon",
handler : function() {
Inprint.ObjectResolver.resolve({
aid: "document-editor",
oid: record.get("id"),
pid: record.get("document"),
description: escape(record.get("name"))
});
}
});
}
}
rowCtxMenuItems.push({
icon: _ico("arrow-transition-270"),
cls: "x-btn-text-icon",
text: _("Download file"),
scope:this,
handler : function() {
var items = [];
Ext.each(this.getSelectionModel().getSelections(), function(record) {
items.push("id="+ record.get("id"));
});
window.location = "/files/download/?" + items.join("&");
}
});
if (this.access["fedit"] === true) {
rowCtxMenuItems.push("-");
rowCtxMenuItems.push({
icon: _ico("light-bulb"),
cls: "x-btn-text-icon",
text: _("Publish"),
scope:this,
handler: this.cmpPublish
});
rowCtxMenuItems.push({
icon: _ico("light-bulb-off"),
cls: "x-btn-text-icon",
text: _("Unpublish"),
scope:this,
handler: this.cmpUnpublish
});
if ( selCount == 1 ) {
rowCtxMenuItems.push("-");
//rowCtxMenuItems.push({
// icon: _ico("edit-drop-cap"),
// cls: "x-btn-text-icon",
// text: _("Rename file"),
// scope:this,
// handler : this.cmpRenameFile
//});
rowCtxMenuItems.push({
icon: _ico("edit-column"),
cls: "x-btn-text-icon",
text: _("Change description"),
scope:this,
handler : this.cmpChangeDescription
});
}
}
if (this.access["fdelete"] === true) {
rowCtxMenuItems.push("-");
rowCtxMenuItems.push({
icon: _ico("document-shred"),
cls: "x-btn-text-icon",
text: _("Delete file"),
scope:this,
handler : this.cmpDelete
});
}
rowCtxMenuItems.push("-");
}
rowCtxMenuItems.push({
icon: _ico("arrow-circle-double"),
cls: "x-btn-text-icon",
text: _("Reload"),
scope:this,
handler : this.cmpReload
});
thisGrid.rowCtxMenu = new Ext.menu.Menu({
items : rowCtxMenuItems
});
thisGrid.rowCtxMenu.showAt(evtObj.getXY());
}, this);
},
cmpFill: function(record) {
if (record){
this.record = record;
if (record.access){
this.cmpAccess(record.access);
}
}
},
cmpAccess: function(access) {
this.access = access;
_disable(this.btnCreate, this.btnUpload, this.btnDelete);
if (access["fadd"] === true) {
this.btnCreate.enable();
this.btnUpload.enable();
}
},
cmpCreate: function() {
var form = new Ext.form.FormPanel({
baseCls: 'x-plain',
border:false,
labelWidth: 75,
url: _url("/documents/files/create/"),
bodyStyle: "padding:5px 5px",
defaults: {
anchor: "100%",
allowBlank:false,
hideLabel: true
},
items: [
{
xtype: "hidden",
name: "document",
value: this.config.document
},
_FLD_FILENAME,
_FLD_DESCRIPTION
],
keys: [ _KEY_ENTER_SUBMIT ],
buttons: [ _BTN_SAVE, _BTN_CLOSE ]
});
var win = new Ext.Window({
title: _("Create a new file" + " [RTF]"),
layout: "fit",
closeAction: "hide",
width:400, height:180,
items: form
});
form.on("actioncomplete", function (form, action) {
if (action.type == "submit") {
win.hide();
this.cmpReload();
}
}, this);
win.show();
},
cmpUpdate: function() {
var Uploader = new Inprint.cmp.Uploader({
config: {
document: this.config.document,
uploadUrl: _url("/documents/files/upload/")
}
});
Uploader.on("fileUploaded", function() {
Uploader.hide();
this.cmpReload();
}, this);
Uploader.show();
},
cmpUpload: function() {
var Uploader = new Inprint.cmp.Uploader({
config: {
document: this.config.document,
uploadUrl: _url("/documents/files/upload/")
}
});
Uploader.on("fileUploaded", function() {
Uploader.hide();
this.cmpReload();
}, this);
Uploader.show();
},
// Publish and unpublish file
cmpPublish: function() {
Ext.Ajax.request({
url: this.urls.publish,
scope:this,
success: this.cmpReload,
params: { document: this.config.document, file: this.getValues("id") }
});
},
cmpUnpublish: function() {
var document = this.getStore().baseParams.document;
var file = this.getValues("id");
Ext.Ajax.request({
url: this.urls.unpublish,
scope:this,
success: this.cmpReload,
params: { document: this.config.document, file: this.getValues("id") }
});
},
// Rename file
cmpRenameFile: function() {
Ext.MessageBox.prompt(
_("Renaming a file"),
_("Enter a new filename"),
function(btn, text) {
if (btn == "ok") {
Ext.Ajax.request({
url: this.urls.rename,
success: this.cmpReload,
scope:this,
params: { document: this.config.document, file: this.getValues("id"), filename: text }
});
}
}, this);
},
cmpChangeDescription: function() {
var record = this.getSelectionModel().getSelected();
var box = Ext.MessageBox.show({
width:300,
scope:this,
multiline: true,
buttons: Ext.MessageBox.OKCANCEL,
title: _("Modification of the file description"),
msg: _("Enter a new description for file"),
fn: function(btn, text) {
if (btn == "ok") {
Ext.Ajax.request({
url: this.urls.description,
scope:this,
success: this.cmpReload,
params: { document: this.config.document, file: this.getValues("id"), description: text }
});
}
}
});
},
cmpDelete: function() {
Ext.MessageBox.confirm(
_("Irrevocable action!"),
_("Remove selected files?"),
function(btn) {
if (btn == "yes") {
Ext.Ajax.request({
url: this.urls["delete"],
scope:this,
success: this.cmpReload,
params: { document: this.config.document, file: this.getValues("id") }
});
}
}, this).setIcon(Ext.MessageBox.WARNING);
}
});
<file_sep>Inprint.cmp.membersList.Grid = Ext.extend(Ext.grid.GridPanel, {
initComponent: function() {
this.store = Inprint.factory.Store.json("/catalog/members/list/");
this.selectionModel = new Ext.grid.CheckboxSelectionModel();
Ext.apply(this, {
stripeRows: true,
columnLines: true,
sm: this.selectionModel,
autoExpandColumn: "name",
enableDragDrop: true,
ddGroup:'member2catalog',
columns: [
this.selectionModel,
{
id:"login",
header: _("Login"),
width: 80,
sortable: true,
dataIndex: "login"
},
{
id:"position",
header: _("Position"),
width: 160,
sortable: true,
dataIndex: "position"
},
{
id:"shortcut",
header: _("Shortcut"),
width: 120,
sortable: true,
dataIndex: "shortcut"
},
{
id:"name",
header: _("Title"),
width: 120,
sortable: true,
dataIndex: "title"
}
],
tbar: [
'->',
{
xtype:"searchfield",
width:200,
store: this.store
}
]
});
Inprint.cmp.membersList.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.cmp.membersList.Grid.superclass.onRender.apply(this, arguments);
}
});
<file_sep>Inprint.plugins.rss.Grid = Ext.extend(Ext.grid.EditorGridPanel, {
initComponent: function() {
var actions = new Inprint.documents.GridActions();
var columns = new Inprint.documents.GridColumns();
this.components = {};
this.urls = {
"list": _url("/plugin/rss/list/")
};
var fields = Inprint.store.Columns.documents.list;
fields.push("rss_id", "rss_published", "rss_sortorder");
this.store = Inprint.factory.Store.json( "/documents/list/" , {
autoLoad:true,
remoteSort: true,
totalProperty: 'total',
url: this.urls.list,
baseParams: { flt_rssonly: false },
fields: fields
});
this.sm = new Ext.grid.CheckboxSelectionModel();
this.columns = [
this.sm,
{
width: 32,
id:"publihed",
sortable: false,
dataIndex: "rss_published",
renderer: function(v) {
var image = '';
if (v==1) { image = '<img src="'+ _ico("light-bulb") +'"/>'; }
return image;
}
},
{
width: 40,
id:"sortorder",
sortable: false,
dataIndex: "rss_sortorder",
editor: new Ext.form.TextField({
allowBlank: true
})
},
{
id:"title",
header:_("Title"),
dataIndex: "title",
sortable: false,
renderer: function(v) {
return '<b>'+ v +'</b>';
}
},
columns.edition,
columns.workgroup,
columns.fascicle,
columns.headline,
columns.rubric,
columns.pages,
columns.manager,
columns.progress,
columns.holder,
columns.images,
columns.size
];
this.tbar = [
{
icon: _ico("disk-black"),
cls: "x-btn-text-icon",
text: _("Save"),
ref: "../btnSave",
disabled:true,
scope:this,
handler: this.cmpSave
},
"-",
{
icon: _ico("light-bulb"),
cls: "x-btn-text-icon",
text: _("Publish"),
ref: "../btnPublish",
disabled:true,
scope:this,
handler: this.cmpPublish
},
{
icon: _ico("light-bulb-off"),
cls: "x-btn-text-icon",
text: _("Unpublish"),
ref: "../btnUnpublish",
disabled:true,
scope:this,
handler: this.cmpUnpublish
},
"-",
new Ext.form.ComboBox({
editable:false,
clearable:false,
triggerAction: "all",
forceSelection: true,
valueField: "id",
displayField: "title",
emptyText: _("Show..."),
store: new Ext.data.JsonStore({
autoDestroy: true,
url: _url("/plugin/rss/filter/"),
root: 'data',
fields: [ "id", "title" ]
}),
listeners: {
scope:this,
select: function (combo, record) {
this.store.baseParams.filter = record.get("id");
this.store.reload();
}
}
})
];
this.bbar = new Ext.PagingToolbar({
pageSize: 60,
store: this.store,
displayInfo: true,
displayMsg: _("Displaying documents {0} - {1} of {2}"),
emptyMsg: _("No documents to display")
});
Ext.apply(this, {
border:false,
stripeRows: true,
columnLines: true,
autoExpandColumn: "title",
stateful: true,
stateId: 'documents.plugins.rss.list',
viewConfig: {
getRowClass: function(record, rowIndex, rp, ds) {
var css = '';
if (record.get("rss_id") ) {
css = "inprint-grid-yellow-bg";
}
if (record.get("rss_published") ) {
css = "inprint-grid-green-bg";
}
return css;
}
}
});
Inprint.plugins.rss.Grid.superclass.initComponent.apply(this, arguments);
},
onRender: function() {
Inprint.plugins.rss.Grid.superclass.onRender.apply(this, arguments);
},
cmpSave: function() {
// get modules changes
var data = [];
var records = this.getStore().getModifiedRecords();
if(records.length) {
Ext.each(records, function(r, i) {
var page = r.get("id");
var sortorder = r.get("rss_sortorder");
data.push(page +'::'+ sortorder);
}, this);
}
var o = {
url: _url("/plugin/rss/save/"),
params:{
documents: data
},
scope:this,
success: function () {
this.getStore().commitChanges();
this.cmpReload();
}
};
Ext.Ajax.request(o);
},
cmpPublish: function() {
Ext.Ajax.request({
url: _url("/plugin/rss/publish/"),
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
},
cmpUnpublish: function() {
Ext.Ajax.request({
url: _url("/plugin/rss/unpublish/"),
scope:this,
success: this.cmpReload,
params: { id: this.getValues("id") }
});
}
});
| 8d02a16858f3268149b950f5f5945555b782e907 | [
"JavaScript",
"SQL",
"Markdown",
"Shell"
] | 232 | JavaScript | Softing/gutenberg | 9509c9d39882e691b05ec5a53ebc975abc91644e | 630bad73ce128e4475325faf9bd7fb2668cc3b02 |
refs/heads/master | <file_sep>## 初探GraphQL
记一次上手graphql的过程,方便以后查阅,文章通篇主要使用javascript写代码,其他语言也同理。
#### 1.安装
选择自己需要的语言对应的安装方式。这里选择`javascript`的`Apollo Server`,因为`Apollo Server` 支持所有的 `Node.js HTTP` 服务器框架:`Express`、`Connect`、`HAPI` 和 `Koa`。这里主要使用`express`。
在项目目录中执行:
```
npm install apollo-server-express express
```
注:这里使用的是2.0以上版本,[GraphQL官网安装](https://graphql.cn/code/#javascript)是1.0版本,所以安装的不一样。
#### 2.定义schema
`schema`是用来描述可以查询的数据及其对应的数据类型,可以理解为定义一些接口的格式。
项目中新建`schema.js`,写上以下代码:
```
const { gql } = require('apollo-server-express');
const typeDefs = gql `
type Query {
launches: [LaunchType]
launch(flight_number: Int): LaunchType
}
type LaunchType {
flight_number: Int
mission_name: String
launch_date_local: String
launch_success: Boolean
rocket: RocketType
}
type RocketType {
rocket_id: String
rocket_name: String
rocket_type: String
}
`;
```
解释:
1. 首先引入`gql`,使用了ES6的[带标签的模板字符串](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates)语法,是用于检测是否包含graphql schema语言。
2. `gql`后面跟着的是schema语法的字符串,其中`type Query`里面定义了我们可以查询的两个数据`launches`和`launch`。
3. 先看`launches`是一个数组类型,数组中每一个值都是名为`LaunchType`的对象类型,`type LaunchType`定义了该对象的结构,其中,`Int、String、Boolean`是schema语法的基本类型,`RocketType`又是另一个对象。
4. 我们回头再看`launch`,不同的是一个对象类型`LaunchType`,很好理解,`launch`就是单个的意思,对应单个对象而不是数组。不同的是后面有括号`(flight_number: Int)`,这里是定义了可传入参数及其类型。
#### 3.定义数据解析
第2步我们定义了schema,我们还需定义其对应的数据解释器。
在`schema.js`中加上:
```
const resolvers = {
Query: {
launches() {
return axios.get('https://api.spacexdata.com/v3/launches').then(res => res.data);
// return launches; // 同上相同结构的数据,以防上面链接失效
},
launch(obj, args) {
return axios.get(`https://api.spacexdata.com/v3/launches/${args.flight_number}`)
.then(res => res.data);
// return launch; // 同上相同结构的数据,以防上面链接失效
},
}
};
```
解释:
1. `Query`的意思是查询类型,在该对象下的为查询接口;
2. `launches`和`launch`分别对应的接口数据解析器,即方法,方法可带上参数,第二个参数`args`是常用的,对应格式定义的一些参数。
#### 4.启动服务
启动express服务,并且将appollo服务应用到其中作为中间件。
新建`index.js`:
```
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const schema = require('./schema');
const server = new ApolloServer(schema);
const app = express();
// 将apollo服务应用到express服务中作为一个中间件
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
```
启动:
```
node index.js
```
#### 5.调试
`Apollo Server`自带GraphiQL工具,使调试graphql接口很方便。
打开连接:
```
http://localhost:4000/graphql
```
就能看到以下界面:

通过GraphiQL请求:
##### 查询列表:
左侧输入要请求的数据结构:
```
query {
launches {
flight_number
mission_name
launch_date_local
launch_success
rocket {
rocket_id
rocket_name
rocket_type
}
}
}
```
数据结果:

##### 单个查询:
左侧输入要请求的数据结构和相关参数:
```
query ($flightNumber: Int){
launch(flight_number: $flightNumber){
flight_number
mission_name
launch_date_local
launch_success
rocket{
rocket_id
rocket_name
rocket_type
}
}
}
```
```
{
flightNumber": 3
}
```
数据结果:

#### 6.参考
[GraphQL 官方入门](https://graphql.cn/learn/schema/)
[apollo-server-express](https://www.npmjs.com/package/apollo-server-express)
[gql解释](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#gql)
[半路出家老菜鸟 - GraphQL 入门详解](https://segmentfault.com/a/1190000017766370#articleHeader6)
<file_sep>// const launches = require('./flight-all.json');
// const launch = require('./flight-first.json');
const axios = require('axios');
const { gql } = require('apollo-server-express');
// 使用schema语言构建一个shema(可以理解为一个接口定义)
const typeDefs = gql `
type Query {
launches: [LaunchType]
launch(flight_number: Int): LaunchType
}
type LaunchType {
flight_number: Int
mission_name: String
launch_date_local: String
launch_success: Boolean
rocket: RocketType
}
type RocketType {
rocket_id: String
rocket_name: String
rocket_type: String
}
`;
// 给对应的schema的提供对应的解决方法(可以理解为接口提供数据的方法)
const resolvers = {
Query: {
launches() {
return axios.get('https://api.spacexdata.com/v3/launches').then(res => res.data);
// return launches; // 同上相同结构的数据,以防上面链接失效
},
launch(obj, args) {
return axios.get(`https://api.spacexdata.com/v3/launches/${args.flight_number}`)
.then(res => res.data);
// return launch; // 同上相同结构的数据,以防上面链接失效
},
}
};
module.exports = {
typeDefs,
resolvers,
}; | e06144cf772efe349ea1b8cbfe5b4457756f2bb1 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | simonliang20/hello-graphql | bccd8d1838fdcf2b1dfe6c86bd020d4b06915fb5 | bd35a429cd02b2366753f733032e8ee76a57bbb4 |
refs/heads/master | <repo_name>pinoyshaun1991/AWIN<file_sep>/tests/Service/CurrencyWebserviceServiceTest.php
<?php
use Awin\Common\Service\ApiAbstractService;
use Awin\Service\CurrencyWebserviceService;
use PHPUnit\Framework\TestCase;
class CurrencyWebserviceServiceTest extends TestCase
{
/**
* @dataProvider valueApiProvider
*
* @param $parameter
* @param $expected
* @throws Exception
*/
public function testSetValueApi($parameter, $expected): void
{
$mock = $this->getMockBuilder(CurrencyWebserviceService::class)
->disableOriginalConstructor()
->getMock();
$mock->expects($this->once())
->method('getExchangeRate')
->willReturn('(GBP) £'.filter_var($parameter, FILTER_SANITIZE_NUMBER_INT)*0.25);
$mockedClass = $this->createMock(ApiAbstractService::class);
$mockedClass->method('sendRequest')
->willReturn($expected);
$this->assertEquals($expected, $mock->getExchangeRate($parameter));
}
public function valueApiProvider()
{
return [
['£100', '(GBP) £25'],
['£10', '(GBP) £2.5'],
['£1000', '(GBP) £250'],
['£10000', '(GBP) £2500'],
['£1', '(GBP) £0.25']
];
}
}<file_sep>/tests/Model/TransactionTableModelTest.php
<?php
use PHPUnit\Framework\TestCase;
use Awin\Model\TransactionTableModel;
class TransactionTableModelTest extends TestCase
{
private $returnedTransactionArray = array(
array(
'merchant' => 1,
'date' => '01/01/2020',
'value' => '(GBP) £2500'
)
);
/**
* @dataProvider merchantProvider
*
* @param $parameter
* @param $expectedMessage
* @throws ReflectionException
*/
public function testSetMerchant($parameter, $expectedMessage): void
{
$reflector = new \ReflectionClass(TransactionTableModel::class);
$instance = $reflector->newInstanceWithoutConstructor();
$method = $reflector->getMethod('setMerchant');
$method->setAccessible(true);
$this->expectExceptionMessage($expectedMessage);
$method->invoke($instance, $parameter);
}
public function merchantProvider()
{
return [
['Testing', 'Merchant is required and needs to be a positive number'],
['', 'Merchant is required and needs to be a positive number'],
[array(), 'Merchant is required and needs to be a positive number'],
[-12, 'Merchant is required and needs to be a positive number']
];
}
/**
* @dataProvider merchantWithoutExceptionProvider
*
* @param $parameter
* @param $expected
* @throws Exception
*/
public function testSetMerchantWithoutException($parameter, $expected): void
{
$reflector = new \ReflectionClass(TransactionTableModel::class);
$instance = $reflector->newInstanceWithoutConstructor();
$method = $reflector->getMethod('setMerchant');
$method->setAccessible(true);
$this->assertEquals($expected, $method->invoke($instance, $parameter));
}
public function merchantWithoutExceptionProvider()
{
return [
[2, 2],
[3, 3],
[10, 10],
[100, 100]
];
}
public function testGetMerchant(): void
{
$mockedClass = $this->createMock(TransactionTableModel::class);
$mockedClass->method('getMerchant')
->willReturn(1);
$this->assertEquals(1, $mockedClass->getMerchant());
}
/**
* @dataProvider dateProvider
*
* @param $parameter
* @param $expectedMessage
* @throws ReflectionException
*/
public function testSetDate($parameter, $expectedMessage): void
{
$reflector = new \ReflectionClass(TransactionTableModel::class);
$instance = $reflector->newInstanceWithoutConstructor();
$method = $reflector->getMethod('setDate');
$method->setAccessible(true);
$this->expectExceptionMessage($expectedMessage);
$method->invoke($instance, $parameter);
}
public function dateProvider()
{
return [
['2020/01/01', 'Date has to be valid and can not be null'],
['', 'Date has to be valid and can not be null'],
[-12, 'Date has to be valid and can not be null']
];
}
/**
* @dataProvider dateWithoutExceptionProvider
*
* @param $parameter
* @param $expected
* @throws Exception
*/
public function testSetDateWithoutException($parameter, $expected): void
{
$reflector = new \ReflectionClass(TransactionTableModel::class);
$instance = $reflector->newInstanceWithoutConstructor();
$method = $reflector->getMethod('setDate');
$method->setAccessible(true);
$this->assertEquals($expected, $method->invoke($instance, $parameter));
}
public function dateWithoutExceptionProvider()
{
return [
['01/01/2020', '01/01/2020'],
['15/01/2020', '15/01/2020'],
['01/06/2020', '01/06/2020'],
['03/07/2020', '03/07/2020']
];
}
public function testGetDate(): void
{
$mockedClass = $this->createMock(TransactionTableModel::class);
$mockedClass->method('getDate')
->willReturn('01/01/2020');
$this->assertEquals('01/01/2020', $mockedClass->getDate());
}
/**
* @dataProvider valueProvider
*
* @param $parameter
* @param $expectedMessage
* @throws ReflectionException
*/
public function testSetValue($parameter, $expectedMessage): void
{
$reflector = new \ReflectionClass(TransactionTableModel::class);
$instance = $reflector->newInstanceWithoutConstructor();
$method = $reflector->getMethod('setValue');
$method->setAccessible(true);
$this->expectExceptionMessage($expectedMessage);
$method->invoke($instance, $parameter);
}
public function valueProvider()
{
return [
[null, 'Value can not be null'],
['abcdefg', 'Value needs to be a valid currency type']
];
}
public function testGetValue(): void
{
$mockedClass = $this->createMock(TransactionTableModel::class);
$mockedClass->method('getValue')
->willReturn(1000);
$this->assertEquals(1000, $mockedClass->getValue());
}
public function testFetchTransactions(): void
{
$mockedClass = $this->createMock(TransactionTableModel::class);
$mockedClass->method('fetchTransactions')
->willReturn($this->returnedTransactionArray);
$this->assertEquals($this->returnedTransactionArray, $mockedClass->fetchTransactions());
}
public function testFetchTransactionsById(): void
{
$mockedClass = $this->createMock(TransactionTableModel::class);
$mockedClass->method('fetchTransactionByMerchantId')
->willReturn($this->returnedTransactionArray);
$this->assertEquals($this->returnedTransactionArray, $mockedClass->fetchTransactionByMerchantId(1));
}
}<file_sep>/src/Script/report.php
<?php
use Awin\Controller\MerchantController;
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../vendor/phplucidframe/console-table/src/LucidFrame/Console/ConsoleTable.php';
/**
* Print transactions
*/
if (!function_exists('readline')) {
function readline($question)
{
$fh = fopen('php://stdin', 'r');
echo $question;
$userInput = trim(fgets($fh));
fclose($fh);
return $userInput;
}
}
displayTransactions();
function displayTransactions()
{
$merchant = new MerchantController();
$transactionAnswer = readline('Do you want to list all transactions? Answer Y/N: ');
$table = new LucidFrame\Console\ConsoleTable();
$table
->addHeader('Merchant')
->addHeader('Date')
->addHeader('Value');
if ($transactionAnswer === 'Y' || $transactionAnswer === 'y') {
foreach ($merchant->getTransactions() as $transaction) {
$table
->addRow()
->addColumn($transaction['merchant'])
->addColumn($transaction['date'])
->addColumn($transaction['value']);
}
$table->display();
echo <<<EOL
EOL;
$exitAnswer = readline(' do you want to exit? Answer Y/N: ');
if ($exitAnswer === 'Y' || $exitAnswer === 'y') {
exit();
} else {
displayTransactions();
}
} else if ($transactionAnswer === 'N' || $transactionAnswer === 'n') {
$merchantId = readline('What is the merchant id you would like to view? ');
$merchantResults = $merchant->getTransactionsByMerchant($merchantId);
if (!empty($merchantResults)) {
foreach ($merchantResults as $transaction) {
$table
->addRow()
->addColumn($transaction['merchant'])
->addColumn($transaction['date'])
->addColumn($transaction['value']);
}
$table->display();
echo <<<EOL
EOL;
}
$exitAnswer = readline(' do you want to exit? Answer Y/N: ');
if ($exitAnswer === 'Y' || $exitAnswer === 'y') {
exit();
} else {
displayTransactions();
}
} else {
displayTransactions();
}
}
<file_sep>/src/Controller/CurrencyConverterController.php
<?php
namespace Awin\Controller;
use Awin\Service\CurrencyWebservice;
/**
* Class CurrencyConverter
* @package Controller
*/
class CurrencyConverterController extends CurrencyWebservice
{
/**
* Get the converted currency
*
* @param $amount
* @return string
*/
public function convert($amount)
{
return $this->getExchangeRate($amount);
}
}<file_sep>/src/Common/Service/ApiAbstractService.php
<?php
namespace Awin\Common\Service;
/**
* A generic class to handle all API requests
*
* Class ApiAbstract
* @package Common\Service
*/
abstract class ApiAbstractService
{
/**
* Sends the API request via cURL
*
* @param $url
* @param array $params
* @param string $method
* @return float
*/
public function sendRequest($url, $params = array(), $method = '')
{
return $params['value']*0.25;
}
}<file_sep>/src/Controller/MerchantController.php
<?php
namespace Awin\Controller;
use Awin\Common\Controller\TransactionInterface;
use Exception;
use Awin\Model\TransactionTableModel;
/**
* Implements the transaction interface
*
* Class Merchant
* @package Controller
*/
class MerchantController implements TransactionInterface
{
private $transactionModel;
public function __construct()
{
$this->transactionModel = new TransactionTableModel();
}
/**
* Fetch all transactions
*
* @return array|mixed
* @throws \Exception
*/
public function getTransactions()
{
$transactions = array();
try {
$transactions = $this->transactionModel->fetchTransactions();
} catch (Exception $e) {
print $e->getMessage();
}
return $transactions;
}
/**
* Fetch merchant transactions
*
* @param $id
* @return array|mixed
*/
public function getTransactionsByMerchant($id)
{
$merchantTransactions = array();
try {
$merchantTransactions = $this->transactionModel->fetchTransactionByMerchantId($id);
} catch (Exception $e) {
print $e->getMessage();
}
return $merchantTransactions;
}
}<file_sep>/src/Common/Controller/TransactionInterface.php
<?php
namespace Awin\Common\Controller;
/**
* Declaring the methods needed to display transactions
*
* Interface TransactionInterface
* @package Common\Controller
*/
interface TransactionInterface
{
/**
* Get all transactions
*
* @return mixed
*/
public function getTransactions();
/**
* Get transaction row by id
*
* @param $id
* @return mixed
*/
public function getTransactionsByMerchant($id);
}<file_sep>/src/Model/TransactionTableModel.php
<?php
namespace Awin\Model;
use Exception;
use Awin\Service\CurrencyWebserviceService;
/**
* Class TransactionTable
* @package Model
*/
class TransactionTableModel
{
/**
* @var int
*/
private $merchant;
/**
* @var string
*/
private $date;
/**
* @var int
*/
private $value;
/**
* @var string
*/
private $fileSource;
/**
* @var array
*/
private $rows;
/**
* @var CurrencyWebservice
*/
private $currencyService;
/**
* TransactionTable constructor.
* @throws Exception
*/
public function __construct()
{
$this->merchant = 0;
$this->date = '';
$this->value = 0;
$this->fileSource = __DIR__.'/../../data/data.csv';
$this->rows = array();
$this->currencyService = new CurrencyWebserviceService();
}
/**
* Set the merchant variable type
*
* @param $merchant
* @return int
* @throws Exception
*/
private function setMerchant($merchant): int
{
if (is_null($merchant) || !is_numeric($merchant) || $merchant <= 0) {
throw new Exception('Merchant is required and needs to be a positive number');
}
return $this->merchant = addslashes($merchant);
}
/**
* Retrieve merchant id
*
* @return int
*/
public function getMerchant(): int
{
return stripslashes($this->merchant);
}
/**
* Set the date variable type
*
* @param $date
* @return mixed
* @throws Exception
*/
private function setDate($date): string
{
$dateSplit = explode('/', $date);
if (empty($date) || is_int($date) || checkdate($dateSplit[1], $dateSplit[0], $dateSplit[2]) === false) {
throw new Exception('Date has to be valid and can not be null');
}
return $this->date = $date;
}
/**
* Retrieve date
*
* @return string
*/
public function getDate(): string
{
return $this->date;
}
/**
* Set the value variable type
*
* @param $value
* @return mixed
* @throws Exception
*/
private function setValue($value): string
{
if (is_null($value)) {
throw new Exception('Value can not be null');
}
$rawCurrency = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
if ($this->isCurrency($rawCurrency) == false) {
throw new Exception('Value needs to be a valid currency type');
}
return $this->value = $this->currencyService->getExchangeRate($rawCurrency);
}
/**
* Retrieve value
*
* @return string
*/
public function getValue(): string
{
return $this->value;
}
/**
* Check a valid currency type
*
* @param $number
* @return false|int
*/
private function isCurrency($number): int
{
return preg_match("/^-?[0-9]+(?:\.[0-9]{1,2})?$/", $number);
}
/**
* Fetch all transactions
*
* @return array
* @throws Exception
*/
public function fetchTransactions(): array
{
if (($handle = fopen($this->fileSource, "r")) !== false) {
$row = 0;
while (($data[] = fgetcsv($handle, 1000, ";")) !== false) {
if ($row > 0) {
$this->setMerchant($data[$row][0]);
$this->setDate($data[$row][1]);
$this->setValue($data[$row][2]);
$this->rows[] = array(
'merchant' => $this->getMerchant(),
'date' => $this->getDate(),
'value' => $this->getValue()
);
}
$row++;
}
}
return $this->rows;
}
/**
* Fetch transaction row by merchant id
*
* @param $merchant
* @return array
* @throws Exception
*/
public function fetchTransactionByMerchantId($merchant): array
{
$this->setMerchant($merchant);
$found = false;
if (($handle = fopen($this->fileSource, "r")) !== false) {
$row = 0;
while (($data[] = fgetcsv($handle, 1000, ";")) !== false) {
if (($row > 0 && $found === false) || !empty($this->rows)) {
if ($data[$row][0] == $this->getMerchant()) {
$this->rows[] = array(
'merchant' => $data[$row][0],
'date' => $data[$row][1],
'value' => $this->setValue($data[$row][2])
);
$found = true;
}
}
$row++;
}
if ($found === false) {
throw new Exception('Unable to find transaction');
}
}
return $this->rows;
}
}<file_sep>/src/Service/CurrencyWebserviceService.php
<?php
namespace Awin\Service;
use Awin\Common\Service\ApiAbstractService;
/**
* Dummy web service returning random exchange rates
*
* Class CurrencyWebservice
* @package Service
*/
class CurrencyWebserviceService extends ApiAbstractService
{
public function __construct()
{
setlocale(LC_MONETARY,"en_GB");
}
/**
* Get the GBP exchange rate from given value
*
* @param $currency
* @return string
*/
public function getExchangeRate($currency)
{
$response = $this->sendRequest('http://exchangerate.com/api', array('value' => $currency), 'post');
$returnString = money_format("%i", $response);
return str_replace('GBP', '(GBP) £', $returnString);
}
}<file_sep>/README.md
Affiliate Window Candidate Task
===============================
### Objective
To demonstrate your OOP and unit testing skills.
### Task
Create a simple report that shows transactions for a merchant id specified as command line argument.
The data.csv file contains dummy data in different currencies, the report should be in GBP.
Assume that data changes and comes from a database, csv file is just for simplicity,
feel free to replace with sqlite if that helps.
Please add code, unit tests and documentation (docblocks, comments). You do not need to connect to a real currency webservice, a dummy webservice client that returns random or static values is fine.
Provided code is just an indication, do not feel the need to use them if you don't want to. If something is not clear, improvise.
Use any 3rd party framework or components as you see fit. Please use composer where possible if depending on 3rd party code.
### Assessment
Your task will be assessed on your use of OOP, dependency injection, unit testing and commenting against the level of the position for which you have applied.
Points will be deducted for leaving any redundant files in your code (e.g. left overs from framework skeleton app creation).
### Implementation
This test has been developed using no framework. Autoload generated by composer enabled all the classes that have been created to be loaded and used by means of namespaces.
The codebase adhered to using interfaces and abstract classes from within the Common directory. Within the TransactionTableModel.php file, the getter and setter magic methods have been put in place for not only creating the properties of that class, but to provide validation on what is being set when it comes to executing queries.
Unit tests have been carried out within the codebase using both reflection and mocking approaches.
### How to test
1. Using the terminal, cd into the root directory of the project and execute the following ` php src/Script/report.php`.
2. The following message will display `Do you want to list all transactions? Answer Y/N:`. If Y or y is pressed then a table of all results will be displayed.
3. If N or n is pressed then the following question will be displayed as `What is the merchant id you would like to view?`. Enter the merchant id you would like to view transactions for, then after pressing enter a table displaying all transactions relating to that merchant id will display.
4. Lastly it will then ask whether to exit or not, Y/y will exit the program or N/n will return to the main question of displaying all results.
5. Unit tests have been implemented using PHP Unit, to execute please cd to the root directory and run the following command `./vendor/bin/phpunit tests`. | f673edd16afcdcaa3966477bfd49d60020992523 | [
"Markdown",
"PHP"
] | 10 | PHP | pinoyshaun1991/AWIN | b1cebb00a9c43dcc07527cff86981b90022bbe9c | 31bae69602472ea996c2de152f773cbadf8c2916 |
refs/heads/master | <file_sep>namespace RecruitmentTest
{
public class CreditCard : PaymentProvider
{
public CreditCard(string cardNumber)
{
CardNumber = cardNumber;
}
public string CardNumber { get; }
}
}
<file_sep>using System.Collections.Generic;
namespace RecruitmentTest
{
internal class MenuItemNameComparer : IEqualityComparer<MenuItem>
{
public bool Equals(MenuItem x, MenuItem y)
=> x.Name == y.Name;
public int GetHashCode(MenuItem obj)
=> obj.Name.GetHashCode();
}
}
<file_sep>using AutoFixture;
using NSubstitute;
namespace RecruitmentTest.Tests.AutoFixture
{
internal class PaymentCustomisation : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Register(() =>
{
var paymentGateway = Substitute.For<PaymentGateway>();
paymentGateway.Pay(Arg.Any<PaymentProvider>(), Arg.Any<int>(), Arg.Any<decimal>()).Returns(true);
return paymentGateway;
});
}
}
}
<file_sep>using AutoFixture;
using RecruitmentTest.Tests.Helpers;
namespace RecruitmentTest.Tests.AutoFixture
{
public class DatabaseCustomisation : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Freeze<InMemoryRestaurantDbContextBuilder>();
fixture.Register(() => fixture.Create<InMemoryRestaurantDbContextBuilder>().Build());
}
}
}
<file_sep>namespace RecruitmentTest
{
public interface PaymentProvider
{
}
}<file_sep>using System;
using System.Linq;
using System.Threading.Tasks;
using AutoFixture.Xunit2;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using RecruitmentTest.Controllers;
using RecruitmentTest.Features;
using RecruitmentTest.Tests.AutoFixture;
using RecruitmentTest.Tests.Helpers;
using Xunit;
namespace RecruitmentTest.Tests.Controllers
{
public class HomeControllerTest
{
[Theory, DomainAutoData]
public void Index(TestableHomeController sut)
{
// Act
var result = sut.Index() as ViewResult;
// Assert
Assert.NotNull(result);
}
[Theory, DomainAutoData]
public async Task Index_returns_all_menu_items_grouped_by_course(TestableHomeController sut, RestaurantDbContext setupDb, MenuItemType[] courses)
{
// Given
await setupDb.MenuItemTypes.AddRangeAsync(courses);
await setupDb.SaveChangesAsync();
// When
var result = sut.Index();
var model = result
.Should().BeAssignableTo<ViewResult>()
.Which.Model.Should().BeAssignableTo<Features.OrderCommand>()
.Which.Courses.Should().BeEquivalentTo(courses);
}
[Theory, DomainAutoData]
public void About(HomeController sut)
{
// Act
var result = sut.About() as ViewResult;
// Assert
Assert.Equal("Davey P's Italian Restauranty was established in 2016 to produce Spaghetti Code.", result.ViewData["Message"]);
}
[Theory, DomainAutoData]
public void Contact(HomeController sut)
{
// Act
var result = sut.Contact() as ViewResult;
// Assert
Assert.NotNull(result);
}
[Theory, DomainAutoData]
public async Task Ordering_successfully_shows_item_ordered_in_view(TestableHomeController sut, RestaurantDbContext setupDb)
{
// Given
await setupDb.EnsureSeededAsync();
var orderItem = setupDb.MenuItems.First();
// When
var result = sut.Order(new OrderBuilder(orderItem).Build());
// Then
result
.Should().BeAssignableTo<ViewResult>()
.Which.Model.Should().BeAssignableTo<OrderCommandResult>()
.Which.Ordered.Should().BeEquivalentTo(orderItem);
}
[Theory, DomainAutoData]
public async Task Ordering_with_debit_card_payment_through_PaymentGateway([Frozen] PaymentGateway paymentGateway, TestableHomeController sut, RestaurantDbContext setupDb)
{
// Given
await setupDb.EnsureSeededAsync();
var orderItem = setupDb.MenuItems.First();
// When
var result = sut.Order(new OrderBuilder(orderItem).WithDebitCard().Build());
// Then
paymentGateway.Received().Pay(Arg.Any<DebitCard>(), Arg.Any<int>(), Arg.Any<decimal>());
}
[Theory, DomainAutoData]
public async Task Ordering_with_credit_card_payment_through_PaymentGateway([Frozen] PaymentGateway paymentGateway, TestableHomeController sut, RestaurantDbContext setupDb)
{
// Given
await setupDb.EnsureSeededAsync();
var orderItem = setupDb.MenuItems.First();
// When
var result = sut.Order(new OrderBuilder(orderItem).WithCreditCard().Build());
// Then
paymentGateway.Received().Pay(Arg.Any<CreditCard>(), Arg.Any<int>(), Arg.Any<decimal>());
}
[Theory, DomainAutoData]
public async Task Ordering_one_item_takes_correct_payment_amount([Frozen] PaymentGateway paymentGateway, TestableHomeController sut, RestaurantDbContext context)
{
// Given
await context.EnsureSeededAsync();
var orderItem = context.MenuItems.First();
// When
var result = sut.Order(new OrderBuilder(orderItem).Build());
// Then
paymentGateway.Received().Pay(Arg.Any<PaymentProvider>(), Arg.Any<int>(), orderItem.Price);
}
[Theory, DomainAutoData]
public async Task Ordering_multiple_items_takes_correct_payment_amount([Frozen] PaymentGateway paymentGateway, TestableHomeController sut, RestaurantDbContext context)
{
// Given
await context.EnsureSeededAsync();
var orderItems = context.MenuItems.Take(3).ToList();
var totalPrice = orderItems.Aggregate(0m, (sum, item) => sum + item.Price);
// When
var result = sut.Order(new OrderBuilder(orderItems).Build());
// Then
paymentGateway.Received().Pay(Arg.Any<PaymentProvider>(), Arg.Any<int>(), totalPrice);
}
public class TestableHomeController : HomeController
{
private readonly Func<OrderQueryHandler> menuHandlerFactory;
private readonly Func<OrderCommandHandler> orderHandlerFactory;
public TestableHomeController(
RestaurantDbContext context,
Func<OrderQueryHandler> menuHandlerFactory,
Func<OrderCommandHandler> orderHandlerFactory)
: base(context)
{
this.menuHandlerFactory = menuHandlerFactory;
this.orderHandlerFactory = orderHandlerFactory;
}
public IActionResult Index()
=> base.Index(menuHandlerFactory());
public ActionResult Order(OrderCommand order)
=> base.Order(order, orderHandlerFactory());
}
}
}
<file_sep>using RecruitmentTest.Features;
using System.Collections.Generic;
using System.Linq;
namespace RecruitmentTest.Tests.Helpers
{
public class OrderBuilder
{
private List<MenuItem> MenuItems = new List<MenuItem>();
private int PaymentTypeId;
public OrderBuilder(MenuItem item)
{
WithItem(item);
WithDebitCard();
}
public OrderBuilder(IEnumerable<MenuItem> items)
{
foreach (var item in items)
WithItem(item);
WithDebitCard();
}
public OrderBuilder WithItem(MenuItem item)
{
this.MenuItems.Add(item);
return this;
}
public OrderBuilder WithCreditCard()
{
this.PaymentTypeId = 2;
return this;
}
public OrderBuilder WithDebitCard()
{
this.PaymentTypeId = 1;
return this;
}
internal OrderCommand Build()
=> new OrderCommand
{
OrderedDishes = MenuItems.Select(x => x.Id).ToArray(),
PaymentTypeId = PaymentTypeId,
};
}
}
<file_sep>using AutoFixture;
using AutoFixture.AutoNSubstitute;
namespace RecruitmentTest.Tests.AutoFixture
{
public class DomainAutoDataCustomisations : CompositeCustomization
{
public DomainAutoDataCustomisations()
: base(
new AutoConfiguredNSubstituteCustomization(),
new DatabaseCustomisation(),
new PaymentCustomisation())
{
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
namespace RecruitmentTest.Tests.Helpers
{
public class InMemoryRestaurantDbContextBuilder
{
private readonly string databaseName;
public InMemoryRestaurantDbContextBuilder(string databaseName)
{
this.databaseName = databaseName;
}
public RestaurantDbContext Build()
{
var builder = new DbContextOptionsBuilder<RestaurantDbContext>();
builder.UseInMemoryDatabase(databaseName);
return new RestaurantDbContext(builder.Options);
}
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
namespace RecruitmentTest
{
public class MenuItemType
{
private MenuItemType()
{
}
public MenuItemType(string description, params MenuItem[] items)
{
Description = description;
_Items = items.ToList();
}
public int Id { get; private set; }
public string Description { get; private set; }
private List<MenuItem> _Items { get; set; } = new List<MenuItem>();
public IReadOnlyList<MenuItem> Items => _Items;
internal void AddItems(params MenuItem[] item)
{
_Items.AddRange(item);
}
}
}
<file_sep>using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using RecruitmentTest.Features;
using RecruitmentTest.Models;
namespace RecruitmentTest.Controllers
{
public class HomeController : Controller
{
private readonly RestaurantDbContext context;
public HomeController(RestaurantDbContext context)
{
this.context = context;
}
public IActionResult Index([FromServices] OrderQueryHandler handler)
{
var query = handler.Handle();
return View(query);
}
public IActionResult About()
{
ViewData["Message"] = "<NAME>'s Italian Restauranty was established in 2016 to produce Spaghetti Code.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public ActionResult PaymentFailed()
{
ViewData["Message"] = "Sorry, your payment failed.";
return View();
}
public ActionResult Order(OrderCommand order, [FromServices] OrderCommandHandler handler)
{
var result = handler.Handle(order);
if (result.PaymentOk)
{
ViewData["Message"] = "Thank you. Your order has been placed.";
return View(result);
}
else
{
return RedirectToAction("PaymentFailed");
}
}
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>using System.Collections.Generic;
namespace RecruitmentTest.Features
{
/// <summary>
/// The view model for ordering.
/// </summary>
public class OrderCommand
{
/// <summary>
/// Public parameterless constructor required for ASP.Net MVC model binding.
/// </summary>
public OrderCommand()
{
}
public OrderCommand(IEnumerable<MenuItemType> courses)
{
Courses = courses;
}
public IEnumerable<MenuItemType> Courses { get; }
public int[] OrderedDishes { get; set; }
public int PaymentTypeId { get; set; }
}
}
<file_sep>namespace RecruitmentTest
{
public class CardPaymentGateway : PaymentGateway
{
public bool Pay(PaymentProvider provider, int pin, decimal amount) => true;
}
}
<file_sep>## Log
Development was test first, so the first goal was to make the exising tests pass.
* Project didn't run - EF had permission problems in SQLExpress.
- Switched to using (localdb)
* Migrated project to core version of MVC and EF as I am more familiar with those
- All initial test now pass
* Task 1 - Added CreditCard option
- Added tests that payment gateway is exercised correctly
* Task 2 - Modelled MenuItem as encapsulated part of MenuItemType
- Created Order model for index.cshtml, rendered course headers
* Task 3 - Charge correct price
* Task 4 - Show details of what was ordered
* Task 5 - Allow ordering multiple dishes
Notes about solution
* Basic clean architecture - the infrastructure depends on the domain logic, which has no dependencies
- Often the domain logic would be in a separate assembly to highlight this, but this project is not complex enough
* The domain model contains encapsulated, (nearly) immutable classes
* The domain services provide ancillary functionality (e.g. processing payment)
* Project Features are self-contained groups of classes with their own view model
- query and render the initial model
- client modifies the model
- server processes the modified model (places an order)
* Spiked a branch for view models that used real objects to model ordered dishes, rather than the IDs of the dishes.
In this project I felt that it was over-complicated for the benefit.
* All hard-coded strings of type names have been eradicated, even (especially) in the cshtml
* Tests use randomly generated values and dependency injection
- Keeps tests short and to the point
- Each test has minimum setup required for that test case
- Each test has one reason to fail
- Helps tests to be supple in face of changes to codebase<file_sep>using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace RecruitmentTest
{
public static class PrepareDatabaseExtensions
{
public static async Task<IWebHost> PrepareDatabase(this IWebHost host)
{
using (var scope = host.Services.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
try
{
var context = serviceProvider.GetRequiredService<RestaurantDbContext>();
await context.Database.MigrateAsync();
await context.EnsureSeededAsync();
}
catch (Exception ex)
{
var logger = serviceProvider.GetRequiredService<ILogger<RestaurantDbContext>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
return host;
}
public static async Task<RestaurantDbContext> EnsureSeededAsync(this RestaurantDbContext context)
{
var menu = new[]
{
new MenuItemType(
"Starter",
new[]
{
new MenuItem ( name: "Arancini", price: 2.29m ),
new MenuItem ( name: "Fonduta Formaggi", price: 3.79m ),
new MenuItem ( name: "Bruschetta", price: 3.29m ),
new MenuItem ( name: "Mixed Olives", price: 2.75m ),
new MenuItem ( name: "N'Duja Pizzette", price: 3.10m ),
}),
new MenuItemType(
"Main",
new[]
{
new MenuItem ( name: "Spaghetti Bolognese", price: 6.75m ),
new MenuItem ( name: "Cheeseburger", price: 6.99m ),
new MenuItem ( name: "Lasagne", price: 5.99m ),
new MenuItem ( name: "Lobster and Crab Tortelli", price: 14.99m ),
}),
new MenuItemType(
"Desert",
new[]
{
new MenuItem ( name: "Tiramisu", price: 4.50m ),
new MenuItem ( name: "Plum Tart", price: 3.50m ),
new MenuItem ( name: "Sorbet", price: 1.99m ),
})
};
foreach (var itemType in menu)
{
// needs AddOrUpdate
var existing = context
.MenuItemTypes
.Include(nameof(MenuItemType.Items))
.FirstOrDefault(x => x.Description == itemType.Description);
if (existing == null)
{
await context.MenuItemTypes.AddAsync(itemType);
}
else
{
var missingDishes =
itemType.Items.Except(existing.Items, new MenuItemNameComparer())
.ToArray();
existing.AddItems(missingDishes);
}
}
await context.SaveChangesAsync();
return context;
}
}
}
<file_sep>namespace RecruitmentTest
{
public interface PaymentGateway
{
bool Pay(PaymentProvider provider, int pin, decimal amount);
}
}
<file_sep>namespace RecruitmentTest
{
public class MenuItem
{
private MenuItem()
{
}
public MenuItem(string name, decimal price)
{
Name = name;
price = Price;
}
public int Id { get; private set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace RecruitmentTest
{
public class RestaurantDbContext : DbContext
{
public RestaurantDbContext(DbContextOptions options)
: base(options)
{
}
private DbSet<MenuItem> _MenuItems { get; set; }
public IQueryable<MenuItem> MenuItems => _MenuItems;
public DbSet<MenuItemType> MenuItemTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Keep the original table name
modelBuilder.Entity<MenuItem>().ToTable("MenuItems");
base.OnModelCreating(modelBuilder);
}
}
}
<file_sep>namespace RecruitmentTest.Features
{
public class OrderCommandResult
{
public bool PaymentOk { get; private set; }
public MenuItem[] Ordered { get; private set; }
public static OrderCommandResult Success(MenuItem[] order)
=> new OrderCommandResult
{
PaymentOk = true,
Ordered = order,
};
public static OrderCommandResult Failed()
=> new OrderCommandResult { PaymentOk = false };
}
}
<file_sep>using AutoFixture;
using AutoFixture.Xunit2;
namespace RecruitmentTest.Tests.AutoFixture
{
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false)]
public class DomainAutoDataAttribute : AutoDataAttribute
{
public DomainAutoDataAttribute()
: base(() => new Fixture()
.Customize(new DomainAutoDataCustomisations()))
{
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
namespace RecruitmentTest.Features
{
public class OrderQueryHandler
{
private readonly RestaurantDbContext context;
public OrderQueryHandler(RestaurantDbContext context)
{
this.context = context;
}
public OrderCommand Handle()
=> new OrderCommand(
context
.MenuItemTypes
.Include(x => x.Items));
}
}
<file_sep>using LanguageExt;
using static LanguageExt.Prelude;
namespace RecruitmentTest
{
public class PaymentProviderFactory
{
public Option<PaymentProvider> Create(int paymentProviderId)
{
if (paymentProviderId == 1) return new DebitCard("0123 4567 8910 1112");
if (paymentProviderId == 2) return new CreditCard("9999 9999 9999 9999");
return None;
}
}
}
<file_sep>namespace RecruitmentTest
{
public class DebitCard : PaymentProvider
{
public DebitCard(string cardNumber)
{
CardNumber = cardNumber;
}
public string CardNumber { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
namespace RecruitmentTest.Features
{
public class OrderCommandHandler
{
private readonly RestaurantDbContext context;
private readonly PaymentProviderFactory paymentProviders;
private readonly PaymentGateway paymentGateway;
public OrderCommandHandler(RestaurantDbContext context, PaymentProviderFactory paymentProviders, PaymentGateway paymentGateway)
{
this.context = context;
this.paymentProviders = paymentProviders;
this.paymentGateway = paymentGateway;
}
public OrderCommandResult Handle(OrderCommand order)
{
var items = FindOrderedItems(order);
var price = items.Sum(x => x.Price);
bool paidOk = TakePayment(order, price);
return paidOk
? OrderCommandResult.Success(items.ToArray())
: OrderCommandResult.Failed();
}
private IEnumerable<MenuItem> FindOrderedItems(OrderCommand order)
=> context.MenuItems.Where(x => order.OrderedDishes.Contains(x.Id));
private bool TakePayment(OrderCommand order, decimal price)
{
var paymentProvider = paymentProviders.Create(order.PaymentTypeId);
return paymentProvider
.Map(provider => paymentGateway.Pay(provider, 1234, price))
.IfNone(false);
}
}
}
<file_sep>Scenario
The in-house developer/chef has made a start on the restaurant's website. Unfortunately he was unable to complete the job after being told to 'do some real work' by the owner.
They are now looking for someone to finish the job...
The only payment type available is Debit Card.
** Please extend this to allow the Credit Card option to be selected.
Currently the menu shows everything that is available.
** Please separate the split this into a list for each course type and label appropriately e.g. 'Starters'.
Currently all orders go through at the same price.
** Please correct this so it uses the price of the item chosen.
The 'Payment OK' message appears on standalone page with only the header menu for navigation.
** Please adjust this to improve the user experience.
Further development:
** Allow the user to select multiple items from the menu and be charged accordingly.
** Add some tests for the payment gateway (you will probably need to extend the implementation of the gateway in order to do so).
** You may also notice some of the existing tests are failing. Consider how you might resolve this situation. | 00bf0822012d16e3ad7a17975b80d6283d3f384a | [
"Markdown",
"C#",
"Text"
] | 25 | C# | benagain/Spaghetti | 3dfca55aedc6a2b69f809791234a2bf26090fb1a | a721522685b314e150f185a0c78d5f3b103c4df0 |
refs/heads/master | <file_sep>#include "PID.h";
#include "Robot.c";
#include "PIDController.c";
#include "PID.h"
float totalIntegral = 0;
float prevError = 0;
void pidInit(PID controller, float kP, float kI, float kD) {
controller.kP = kP;
controller.kI = kI;
controller.kD = kD;
}
float pidRun(PID controller, float error) {
float proportional = controller.kP * error;
controller.integral = controller.kI * (controller.integral + error);
float derivative = controller.kD * (prevError - error);
prevError = error;
float output = proportional + controller.integral + derivative;
return output;
}
<file_sep>#include "PID.h"
struct PIDWithFeedForward {
PID pid;
float kF;
};<file_sep>#include "PIDController.c"
#include "Robot.c"
#include "robot_map.h"
PID leftPositionController;
PID rightPositionController;
PID turningPid;
PID gyroTurning;
void setLeftDrive(float left);
void setRightDrive(float right);
void runDriveAt(float power);
void driveForward(float power, int timeout);
void moveForward(int encoders);
void turnToAngle(int desAngle);
void moveForwardPid(float encoder, int marginOfError);
float limit(float v, float limit);
void chezyDrive(float throttle, float wheel, bool isQuickTurn);
task arcadeDrive();
task driveTask();
void setLeftDrive(float left) {
motor[driveLeftA] = left;
motor[driveLeftB] = left;
motor[driveLeftC] = left;
}
void setRightDrive(float right) {
motor[driveRightA] = right;
motor[driveRightB] = right;
motor[driveRightC] = right;
}
void runDriveAt(float power) {
setLeftDrive(power);
setRightDrive(power);
}
void driveForward(float power, int timeout) {
time1[T1] = 0;
while (time1[T1] < timeout) {
runDriveAt(power);
}
runDriveAt(0);
}
void moveForward(int encoders) {
SensorValue[leftDriveTrain] = 0;
SensorValue[rightDriveTrain] = 0;
pidInit(turningPid, 0.06, 0.0, 0.003);
const float aimGyro = SensorValue[gyro];
float encoderAvg = (abs(SensorValue[dgtl3]) + abs(SensorValue[dgtl1]) )/2;
while ( abs(encoderAvg) < abs(encoders)) {
encoderAvg = (abs(SensorValue[dgtl3]) + abs(SensorValue[dgtl1]) )/2;
float gyroError = aimGyro - SensorValue[gyro];
float gyroPower = pidRun(turningPid, gyroError);
setRightDrive(110 - gyroPower);
setLeftDrive(127 + gyroPower);
writeDebugStreamLine("%4.4f", encoderAvg);
}
setRightDrive(0);
setLeftDrive(0);
}
void turnToAngle(int desAngle) {
pidInit(gyroTurning, 0.6, 0.0, 0.01);
SensorValue[gyro] = 0;
bool running = true;
bool timerStarted = false;
while (running) {
float term = pidRun(gyroTurning, desAngle - SensorValue(gyro));
setLeftDrive(-term);
setRightDrive(term);
if (desAngle - SensorValue(gyro) < 90 && !timerStarted) {
time1[T4] = 0;
timerStarted = true;
}
if (timerStarted && time1[T4] > 50) {
setLeftDrive(0);
setRightDrive(0);
running = false;
}
writeDebugStreamLine("-------------error %d", desAngle - SensorValue(gyro));
}
writeDebugStreamLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~gyro don ", "");
wait1Msec(150);
}
void moveForwardPid(float encoder, int marginOfError) {
pidInit(leftPositionController, 0.13, 0.0, 0.01);
pidInit(rightPositionController, 0.21, 0.0, 0.01);
pidInit(turningPid, 0.05, 0.001, 0.01);
bool running = true;
bool timerStarted = false;
time1[T1] = 0;
SensorValue[leftDriveTrain] = 0.0;
SensorValue[rightDriveTrain] = 0.0;
const float aimGyro = SensorValue[gyro];
while (running) {
float leftError = encoder - SensorValue[leftDriveTrain];
float rightError = encoder - -SensorValue[rightDriveTrain];
float gyroError = aimGyro - SensorValue[gyro];
float leftSpeed = pidRun(leftPositionController, leftError);
float rightSpeed = pidRun(rightPositionController, rightError);
float turnSpeed = pidRun(turningPid, gyroError);
writeDebugStreamLine("###################### left power %d", leftSpeed);
writeDebugStreamLine("###################### right power %d", rightSpeed);
writeDebugStreamLine("###################### turn speed %d", turnSpeed);
setLeftDrive((leftSpeed + turnSpeed));
setRightDrive((rightSpeed - turnSpeed));
writeDebugStreamLine("````````````````````````left error %d", leftError);
writeDebugStreamLine("````````````````````````right error %d", rightError);
writeDebugStreamLine("````````````````````````gyro error %d", gyroError);
if (abs(leftError) < marginOfError && abs(rightError) < marginOfError && !timerStarted) {
timerStarted = true;
time1[T1] = 0;
}
if (timerStarted && time1[T1] > 100) {
running = false;
setLeftDrive(0);
setRightDrive(0);
}
}
writeDebugStreamLine("The drive forward is done %d", SensorValue(leftDriveTrain));
writeDebugStreamLine("The drive forward is done %d", SensorValue(rightDriveTrain));
wait1Msec(200);
}
float limit(float v, float limit) {
return (abs(v) < limit) ? v : limit * (v < 0 ? -1 : 1);
}
float pastLeftPower = 0;
float pastRightPower = 0;
float quickStopAccumulator = 0;
float oldWheel = 0;
void chezyDrive(float throttle, float wheel, bool isQuickTurn) {
//writeDebugStreamLine("%4.4f %4.4f", throttle , wheel);
float wheelNonLinearity;
//wheel = threshold(wheel, wheelDeadband);
//throttle = threshold(throttle, throttleDeadband);
float negInertia = wheel - oldWheel;
oldWheel = wheel;
//writeDebugStreamLine("negInertia %4.4f", negInertia);
wheelNonLinearity = 0.6;
// Apply a sin function that's scaled to make it feel better.
wheel = sin(PI / 2.0 * wheelNonLinearity * wheel)
/ sin(PI / 2.0 * wheelNonLinearity);
wheel = sin(PI / 2.0 * wheelNonLinearity * wheel)
/ sin(PI / 2.0 * wheelNonLinearity);
wheel = sin(PI / 2.0 * wheelNonLinearity * wheel)
/ sin(PI / 2.0 * wheelNonLinearity);
// writeDebugStreamLine("newWheel (after sin) %4.4f", wheel);
float leftPwm, rightPwm, overPower;
float sensitivity;
float angularPower;
float linearPower;
// Negative inertia!
float negInertiaAccumulator = 0.0;
float negInertiaScalar;
if (wheel * negInertia > 0.0) {
negInertiaScalar = 1.5;
} else {
if (abs(wheel) > 0.65) {
negInertiaScalar = 5.0;
} else {
negInertiaScalar = 3.0;
}
}
sensitivity = 0.7; // .9
float negInertiaPower = negInertia * negInertiaScalar;
negInertiaAccumulator += negInertiaPower;
// writeDebugStreamLine("negAccumulatotr %4.4f", negInertiaAccumulator);
wheel = wheel + negInertiaAccumulator;
if (negInertiaAccumulator > 1.0) {
negInertiaAccumulator -= 1.0;
} else if (negInertiaAccumulator < -1.0) {
negInertiaAccumulator += 1.0;
} else {
negInertiaAccumulator = 0.0;
}
linearPower = throttle;
// Quickturn!
if (isQuickTurn) {
// if (abs(linearPower) < 0.2) {
float alpha = 0.2;
quickStopAccumulator = (1.0 - alpha) * quickStopAccumulator + alpha
* limit(wheel, 1.0) * 5.0;
// }
overPower = 1.0;
sensitivity = 1.0;
angularPower = wheel;
} else {
overPower = 0.0;
angularPower = abs(throttle) * (wheel * 1.1) * sensitivity - quickStopAccumulator;
if (abs(throttle) < .1) {
angularPower = wheel;
}
if (quickStopAccumulator > 1.0) {
quickStopAccumulator -= 1.0;
} else if (quickStopAccumulator < -1.0) {
quickStopAccumulator += 1.0;
} else {
quickStopAccumulator = 0.0;
}
}
//float CONSTANT = 20;
rightPwm = leftPwm = linearPower;
leftPwm += angularPower;
rightPwm -= angularPower;
pastRightPower = rightPwm;
pastLeftPower = leftPwm;
if (leftPwm > 1.0) {
rightPwm -= overPower * (leftPwm - 1.0);
leftPwm = 1.0;
} else if (rightPwm > 1.0) {
leftPwm -= overPower * (rightPwm - 1.0);
rightPwm = 1.0;
} else if (leftPwm < -1.0) {
rightPwm += overPower * (-1.0 - leftPwm);
leftPwm = -1.0;
} else if (rightPwm < -1.0) {
leftPwm += overPower * (-1.0 - rightPwm);
rightPwm = -1.0;
}
float leftPwmPower = leftPwm * 127.0;
float rightPwmPower = rightPwm * 127.0;
setLeftDrive(leftPwmPower);
setRightDrive(rightPwmPower);
//motor[rightDriveExtra] = (rightPwm * 127.0);
//motor[leftDriveExtra] = (leftPwm * 127.0);
}
task arcadeDrive() {
while (true) {
float throttle = vexRT[Ch3];
float turn = vexRT[Ch1];
setLeftDrive(throttle + turn);
setRightDrive(throttle - turn);
}
}
task driveTask() {
SensorValue(leftDriveTrain)= 0;
SensorValue(rightDriveTrain) = 0;
while (true) {
float toSend = ((float)vexRT[Ch3])/127;
float toSendTurn = ((float)vexRT[Ch1])/127;
if (abs(toSend) < 0.01) {
toSend = 0;
}
chezyDrive((float)toSend, (float)toSendTurn, vexRT[Btn5U]);
// writeDebugStreamLine("Left pos: %f", SensorValue[leftDriveTrain]);
// writeDebugStreamLine("Right pos: %f", SensorValue[rightDriveTrain]);
}
}
<file_sep>#include "PIDController.c"
#include "robot_map.h"
PID armPid;
const int HOME_POS = 500;
const int MID_POS = 2674;
const int HIGH_POS = 3650;
bool running = true;
void setArm(int power);
void manualArm();
void moveArm(int desArmAngle);
task armTask();
task armTask() {
float goal = HOME_POS;
while(true) {
// manualArm();
if (vexRt[Btn7UXmtr2]) {
goal = HOME_POS;
} else if (vexRt[Btn7RXmtr2]) {
goal = MID_POS;
} else if (vexRt[Btn7DXmtr2]) {
goal = HIGH_POS;
}
moveArm(goal);
}
}
void moveArm(int desArmAngle) {
pidInit(armPid, 0.17, 0.0, 13.0); // 0.16, 0.07, 20.0
bool running = true;
bool timerStarted = false;
while(running) {
float armError = desArmAngle - SensorValue(armPot);
float chainPwm = pidRun(armPid, armError);
if (abs(armError) < 100 && !timerStarted) {
timerStarted = true;
time1[T4] = 0;
}
if (timerStarted && time1[T4] > 100) {
running = false;
}
setArm(chainPwm);
}
}
void manualArm() {
double power = vexRt[Ch2Xmtr2];
setArm(power);
}
void setArm(int power) {
motor[armMotor] = -power;
}
<file_sep>#include "robot_map.h"
void setMotor(float power);
task intakeTask() {
while (true) {
if (vexRt[Btn6U] || vexRt[Btn6UXmtr2]) {
setMotor(127);
} else if (vexRt[Btn6D] || vexRt[Btn6DXmtr2]) {
setMotor(-127);
} else {
setMotor(0);
}
}
}
void setMotor(float power) {
motor[intakeMotor] = power;
}<file_sep>#define driveRightA port1
#define driveRightB port2
#define driveRightC port3
#define driveLeftA port10
#define driveLeftB port9
#define driveLeftC port8
#define flywheelA port5
#define flywheelB port6
#define armMotor port7
#define intakeMotor port4
<file_sep># Vex-2018-2019
code for Robie V
<file_sep>#pragma config(UART_Usage, UART1, uartVEXLCD, baudRate19200, IOPins, None, None)
#pragma config(UART_Usage, UART2, uartNotUsed, baudRate4800, IOPins, None, None)
#pragma config(Sensor, in1, gyro, sensorGyro)
#pragma config(Sensor, in2, armPot, sensorPotentiometer)
#pragma config(Sensor, dgtl1, leftDriveTrain, sensorQuadEncoder)
#pragma config(Sensor, dgtl9, rightDriveTrain, sensorQuadEncoder)
#pragma config(Sensor, dgtl11, flywheelEncoder, sensorQuadEncoder)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
#pragma DebuggerWindows("debugStream")
#pragma competitionControl(Competition)
#pragma autonomousDuration(20)
#pragma userControlDuration(120)
#pragma platform(VEX)
#include "Vex_Competition_Includes.c"
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
#include "drive.c"
#include "misc.c"
#include "intake.c"
#include "flywheel.c"
#include "arm.c"
void pre_auton() {
}
task autonomous() {
playSoundFile("1.wav");
}
task usercontrol() {
playSoundFile("1.wav");
startTask(driveTask);
startTask(flywheelTask);
startTask(intakeTask);
startTask(armTask);
while(true) {
runSpeaker();
}
}
<file_sep>
void checkAllPorts() {
motor[port1] = vexRT[Ch3];
motor[port2] = vexRT[Ch3];
motor[port3] = vexRT[Ch3];
motor[port4] = vexRT[Ch3];
motor[port5] = vexRT[Ch3];
motor[port6] = vexRT[Ch3];
motor[port7] = vexRT[Ch3];
motor[port8] = vexRT[Ch3];
motor[port9] = vexRT[Ch3];
motor[port10] = vexRT[Ch3];
}
void runSpeaker() {
if ((vexRT[Btn7U] || vexRT[Btn7U]) && !bSoundActive) {
playSoundFile("30secondsleft.wav");
} else if ((vexRT[Btn7R] || vexRT[Btn7R]) && !bSoundActive) {
playSoundFile("endofmatch.wav");
} else if ((vexRT[Btn7L] || vexRT[Btn7L]) && !bSoundActive) {
playSoundFile("endofauto.wav");
} else if ((vexRT[Btn7D] || vexRT[Btn7D]) && !bSoundActive) {
playSoundFile("mogograb.wav");
} else if ((vexRT[Btn8L] || vexRT[Btn8L]) && !bSoundActive) {
playSoundFile("danger_zone.wav");
} else if ((vexRT[Btn8U] || vexRT[Btn8U]) && !bSoundActive) {
playSoundFile("robotonline.wav");
}
}
<file_sep>#include "PIDWithFeedForward.h"
#include "PIDController.c"
void pidWithFeedForwardInit(PIDWithFeedForward pidF, float kP, float kI, float kD, float kF) {
pidF.pid.kP = kP;
pidF.pid.kI = kI;
pidF.pid.kD = kD;
pidF.kF = kD;
}
float pidWithFeedForwardRun(PIDWithFeedForward pidF, float goal, float curVal) {
float pidOutput = pidRun(pidF.pid, goal - curVal);
float feedForwardTerm = goal * pidF.kF;
return pidOutput + feedForwardTerm;
}
<file_sep>#include "robot_map.h"
#include "PIDControllerWithFeedForward.c"
PIDWithFeedForward controller;
void setMotors(float power);
float runController(float desSpeed);
void twiddle(PIDWithFeedForward pidf, float tolerance);
float tuningRun(float desSpeed, float kP, float kI, float kD, float kF);
float getPosition();
task flywheelTask();
float delayTime = 50;
float prevPosition;
task flywheelTask() {
//SensorValue(flywheelEncoder) = 0;
//pidWithFeedForwardInit(controller, 0.0, 0.0, 0.0, 100);
while (true) {
if (vexRT[Btn8UXmtr2]) {
setMotors(127);
} else if (vexRT[Btn8RXmtr2]) {
setMotors(100);
} else if (vexRT[Btn8DXmtr2]) {
setMotors(90);
} else {
setMotors(0);
}
}
}
void twiddle(PIDWithFeedForward pidf, float tolerance) {
float p[] = {0.0, 0.0, 0.0, 0.0};
float dp[] = {1.0, 1.0, 1.0, 1.0};
float desSpeed = 200;
float bestError = tuningRun(desSpeed, p[0], p[1], p[2], p[3]);
while ((dp[0] + dp[1] + dp[2] + dp[3]) > tolerance) {
for (int i = 0; i < 4; i++) {
p[i] += dp[i];
float error = tuningRun(desSpeed, p[0], p[1], p[2], p[3]);
if (error < bestError) {
bestError = error;
dp[i] *= 1.1;
} else {
p[i] -= 2 * dp[i];
float error = tuningRun(desSpeed, p[0], p[1], p[2], p[3]);
if (error < bestError) {
bestError = error;
dp[i] *= 1.1;
} else {
p[i] += dp[i];
dp[i] *= 0.9;
}
}
writeDebugStreamLine("kP: %f", p[0]);
writeDebugStreamLine("kP: %f", p[1]);
writeDebugStreamLine("kP: %f", p[2]);
writeDebugStreamLine("kP: %f", p[3]);
}
}
pidWithFeedForwardInit(pidf, p[0], p[1], p[2], p[3]);
}
float tuningRun(float desSpeed, float kP, float kI, float kD, float kF) {
float n = 100.0;
float errTotal = 0.0;
pidWithFeedForwardInit(controller, kP, kI, kD, kF);
for (int i = 0; i < 2*n; i++) {
float error = runController(desSpeed);
if (i >= n) {
errTotal += error;
}
}
return errTotal / n;
}
float runController(float desSpeed) {
clearTimer(T1);
float speed = (getPosition() - prevPosition) / ((float)delayTime) * 200.0;
float error = desSpeed - speed;
float output = pidWithFeedForwardRun(controller, desSpeed, speed);
setMotors(output);
writeDebugStreamLine("Output: %f", output);
prevPosition = getPosition();
if (time1[T1] < delayTime) {
wait1Msec(delayTime - time1[T1]);
}
writeDebugStreamLine("Speed: %f", speed);
return error;
}
void setMotors(float power) {
motor[flywheelA] = -power;
motor[flywheelB] = power;
}
float getPosition() {
return (float)SensorValue[flywheelEncoder];
}
<file_sep>
struct PID {
float kP;
float kI;
float kD;
float kILimit;
float integral;
float prevIntegral;
float prevError;
};
| e1f808ef7b2652572241dd188c711707f985e81c | [
"Markdown",
"C"
] | 12 | C | CBlagden/Vex-2018-2019 | abed3fe781adbc011eb81893a5fdb02b896d0e9c | eb28e28ffa21c7c498e0b7072b1009cba74475b1 |
refs/heads/master | <file_sep># MultiLayerPerceptron
Multi Layer Perceptron C++
<file_sep>class node{
public:
float w;
float input;
float output;
node* tail;
void link_node(node *pre, node *post){
pre->tail = post;
}
void cal_output(node *pre){
pre->output = (pre->input * pre->w);
}
};
<file_sep>#include<iostream>
#include <vector>
using namespace std;
float w0 = -0.1;
float w1 = -0.36;
float learning_rate = 0.1;
void perceptron(vector<float> class0, vector<float> class1){
int misclassified_num = 0;
float learning_num = 0;
cout << "(w0 : " << w0 << ", w1 : " << w1 << ")" << endl;
for (int i = 0; i < class0.size(); i++){
if (w0 * class0[i] > 0){
misclassified_num++;
learning_num = class0[i];
}
}
w0 = w0 + (learning_rate*learning_num);
for (int i = 0; i < class1.size(); i++){
if (w1 * class1[i] < 0){
misclassified_num++;
learning_num = class1[i];
}
}
w1 = w1 + (learning_rate*learning_num);
cout << "misclassified_num : "<< misclassified_num << endl << endl;
if (misclassified_num != 0){
perceptron(class0, class1);
}
else{
cout << w0 << "," << w1 << endl;
}
}
int main(){
vector<float> input_class0;
vector<float> input_class1;
int data_num = 0;
float input_data = 0;
cout << "input the number of class0 data : ";
cin >> data_num;
for (int i = 0; i < data_num; i++){
cout << "input the data ("<<i<<"): ";
cin >> input_data;
input_class0.push_back(input_data);
}
cout << "input the number of class1 data : ";
cin >> data_num;
for (int i = 0; i < data_num; i++){
cout << "input the data (" << i << "): ";
cin >> input_data;
input_class1.push_back(input_data);
}
perceptron(input_class0, input_class1);
}
<file_sep>#include <iostream>
#include <math.h>
#include <list>
#include "node.h"
using namespace std;
float learning_rate = 0.1;
int class0_num = 4;
int class1_num = 5;
int class0_x[4] = { -1, -1, 1, 1 };
int class0_y[4] = { 1, -1, 1, -1 };
int class1_x[5] = { -1, 0, 0, 1, 0 };
int class1_y[5] = { 0, -1, 1, 0, 0 };
float error_rate = 0;
float sigmoid(float x){
float y = 0;
y = 1 / (1 + exp(-x));
return y;
}
float sigmoid_function_output(float x){
float y = 0;
y = sigmoid(x)*(1 - sigmoid(x));
return y;
}
float get_error_rate(float output, float desired_value){
return abs(desired_value - output);
}
void update_hidden_weight(node *hidden_node, node *output_node, float error_rate, float learning_rate){
hidden_node->w = learning_rate * error_rate * sigmoid_function_output(output_node->input)*hidden_node->output;
}
void update_input_weight(node *input_node, node *hidden_node, node *output_node, float error_rate, float learning_rate){
input_node->w = learning_rate * (error_rate * sigmoid_function_output(output_node->input) * hidden_node->w) * sigmoid_function_output(hidden_node->input) * input_node->input;
}
void MLP_one(int class0_x[4], int class0_y[4], int class1_x[5], int class1_y[5], node *input_bias, node *input_x, node *input_y, node *hidden_node1, node *output_node){
//learning
for (int i = 0; i < class0_num; i++){
input_x->input = class0_x[i];
input_y->input = class0_y[i];
input_bias->input = 1;
input_x->cal_output(input_x);
input_y->cal_output(input_y);
input_bias->cal_output(input_bias);
hidden_node1->input += (input_x->output + input_y->output + input_bias->output);
}
for (int i = 0; i < class1_num; i++){
input_x->input = class1_x[i];
input_y->input = class1_y[i];
input_bias->input = 1;
input_x->cal_output(input_x);
input_y->cal_output(input_y);
input_bias->cal_output(input_bias);
hidden_node1->input += (input_x->output + input_y->output + input_bias->output);
}
hidden_node1->cal_output(hidden_node1);
output_node->input = hidden_node1->output;
output_node->output = output_node->input;
error_rate = get_error_rate(0.1, output_node->output);
cout << error_rate << endl;
cout << "x_w : " << input_x->w << " / y_w : " << input_y->w << " / bias_w : " << input_bias->w << endl;
if (error_rate > 1.7){
update_hidden_weight(hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_bias, hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_x, hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_y, hidden_node1, output_node, error_rate, learning_rate);
error_rate = get_error_rate(output_node->output, 1.7);
MLP_one(class0_x, class0_y, class1_x, class1_y, input_bias, input_x, input_y, hidden_node1, output_node);
}
}
void MLP_four(int class0_x[4], int class0_y[4], int class1_x[5], int class1_y[5], node *input_bias, node *input_x, node *input_y, node *hidden_node1, node *hidden_node2, node *hidden_node3, node *hidden_node4, node *output_node){
//learning
for (int i = 0; i < class0_num; i++){
input_x->input = class0_x[i];
input_y->input = class0_y[i];
input_bias->input = 1;
input_x->cal_output(input_x);
input_y->cal_output(input_y);
input_bias->cal_output(input_bias);
hidden_node1->input += (input_x->output + input_y->output + input_bias->output);
hidden_node2->input += (input_x->output + input_y->output + input_bias->output);
hidden_node3->input += (input_x->output + input_y->output + input_bias->output);
hidden_node4->input += (input_x->output + input_y->output + input_bias->output);
}
for (int i = 0; i < class1_num; i++){
input_x->input = class1_x[i];
input_y->input = class1_y[i];
input_bias->input = 1;
input_x->cal_output(input_x);
input_y->cal_output(input_y);
input_bias->cal_output(input_bias);
hidden_node1->input += (input_x->output + input_y->output + input_bias->output);
hidden_node2->input += (input_x->output + input_y->output + input_bias->output);
hidden_node3->input += (input_x->output + input_y->output + input_bias->output);
hidden_node4->input += (input_x->output + input_y->output + input_bias->output);
}
hidden_node1->cal_output(hidden_node1);
hidden_node2->cal_output(hidden_node2);
hidden_node3->cal_output(hidden_node3);
hidden_node4->cal_output(hidden_node4);
output_node->input += hidden_node1->output + hidden_node2->output + hidden_node3->output + hidden_node4->output;
output_node->output = output_node->input;
error_rate = get_error_rate(0.1, output_node->output);
cout << error_rate << endl;
cout << "x_w : " << input_x->w << " / y_w : " << input_y->w << " / bias_w : " << input_bias->w << endl;
if (error_rate > 9){
update_hidden_weight(hidden_node1, output_node, error_rate, learning_rate);
update_hidden_weight(hidden_node2, output_node, error_rate, learning_rate);
update_hidden_weight(hidden_node3, output_node, error_rate, learning_rate);
update_hidden_weight(hidden_node4, output_node, error_rate, learning_rate);
update_input_weight(input_bias, hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_x, hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_y, hidden_node1, output_node, error_rate, learning_rate);
error_rate = get_error_rate(output_node->output, 1.7);
MLP_four(class0_x, class0_y, class1_x, class1_y, input_bias, input_x, input_y, hidden_node1, hidden_node2, hidden_node3, hidden_node4, output_node);
}
}
void MLP_five(int class0_x[4], int class0_y[4], int class1_x[5], int class1_y[5], node *input_bias, node *input_x, node *input_y, node *hidden_node1, node *hidden_node2, node *hidden_node3, node *hidden_node4, node *hidden_node5, node *output_node){
for (int i = 0; i < class0_num; i++){
input_x->input = class0_x[i];
input_y->input = class0_y[i];
input_bias->input = 1;
input_x->cal_output(input_x);
input_y->cal_output(input_y);
input_bias->cal_output(input_bias);
hidden_node1->input += (input_x->output + input_y->output + input_bias->output);
hidden_node2->input += (input_x->output + input_y->output + input_bias->output);
hidden_node3->input += (input_x->output + input_y->output + input_bias->output);
hidden_node4->input += (input_x->output + input_y->output + input_bias->output);
hidden_node5->input += (input_x->output + input_y->output + input_bias->output);
}
for (int i = 0; i < class1_num; i++){
input_x->input = class1_x[i];
input_y->input = class1_y[i];
input_bias->input = 1;
input_x->cal_output(input_x);
input_y->cal_output(input_y);
input_bias->cal_output(input_bias);
hidden_node1->input += (input_x->output + input_y->output + input_bias->output);
hidden_node2->input += (input_x->output + input_y->output + input_bias->output);
hidden_node3->input += (input_x->output + input_y->output + input_bias->output);
hidden_node4->input += (input_x->output + input_y->output + input_bias->output);
hidden_node5->input += (input_x->output + input_y->output + input_bias->output);
}
hidden_node1->cal_output(hidden_node1);
hidden_node2->cal_output(hidden_node2);
hidden_node3->cal_output(hidden_node3);
hidden_node4->cal_output(hidden_node4);
hidden_node5->cal_output(hidden_node5);
output_node->input += hidden_node1->output + hidden_node2->output + hidden_node3->output + hidden_node4->output + hidden_node5->output;
output_node->output = output_node->input;
error_rate = get_error_rate(0.1, output_node->output);
cout << error_rate << endl;
cout << "x_w : " << input_x->w << " / y_w : " << input_y->w << " / bias_w : " << input_bias->w << endl;
if (error_rate > 12){
update_hidden_weight(hidden_node1, output_node, error_rate, learning_rate);
update_hidden_weight(hidden_node2, output_node, error_rate, learning_rate);
update_hidden_weight(hidden_node3, output_node, error_rate, learning_rate);
update_hidden_weight(hidden_node4, output_node, error_rate, learning_rate);
update_input_weight(input_bias, hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_x, hidden_node1, output_node, error_rate, learning_rate);
update_input_weight(input_y, hidden_node1, output_node, error_rate, learning_rate);
error_rate = get_error_rate(output_node->output, 1.7);
MLP_five(class0_x, class0_y, class1_x, class1_y, input_bias, input_x, input_y, hidden_node1, hidden_node2, hidden_node3, hidden_node4, hidden_node5, output_node);
}
}
int main(){
node *input_bias = new node();
node *input_x = new node();
node *input_y = new node();
node *hidden_node1 = new node();
node *output_node = new node();
float error_rate = 0;
//initial
input_bias->w = -1;
input_x->w = 0.3;
input_y->w = -1;
hidden_node1->w = 0.5;
// MLP_one(class0_x, class0_y, class1_x, class1_y, input_bias, input_x, input_y, hidden_node1, output_node);
//initial
input_bias->w = -1;
input_x->w = 0.7;
input_y->w = 0.5;
hidden_node1->w = 0.5;
node *hidden_node2 = new node();
node *hidden_node3 = new node();
node *hidden_node4 = new node();
hidden_node2->w = 0.3;
hidden_node3->w = 0.1;
hidden_node4->w = 0.05;
// MLP_four(class0_x, class0_y, class1_x, class1_y, input_bias, input_x, input_y, hidden_node1, hidden_node2, hidden_node3, hidden_node4, output_node);
node *hidden_node5 = new node();
hidden_node5->w = 0.3;
MLP_five(class0_x, class0_y, class1_x, class1_y, input_bias, input_x, input_y, hidden_node1, hidden_node2, hidden_node3, hidden_node4, hidden_node5, output_node);
return 0;
}
| 24b7cb55a8c9b728710aee471ee273ec083992fd | [
"Markdown",
"C++"
] | 4 | Markdown | MrBananaHuman/MultiLayerPerceptron | e44ed2818f1670728f041fc0df8174bfa469eb42 | ebf5ff809c22ffaa2c3c1d3bc12f9f8063a36e00 |
refs/heads/master | <repo_name>AyurM/WebSocket-Game<file_sep>/ws_server.js
"use strict";
var webSocketServer = require('websocket').server;
var http = require('http');
var port = 1337;
//Список подключенных пользователей
var clients = [];
//Настройки игры
var gameSettings = {
playerSpeed: 10,
boardWidth: 922,
boardHeight: 576,
};
//Состояние игры
var gameState = {
players: [],
};
var playerDisconnected = {
index: -1,
};
//Массив с цветами для игроков
var colors = ['red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange', 'white', 'yellow'];
var server = http.createServer(function(request, response) {
//Обработка HTTP-запросов. Так как мы пишем WebSocket-сервер,
//то здесь можно ничего не реализовывать.
});
server.listen(port, (err) => {
if (err) {
return console.log('Error on server start!', err);
}
console.log(`Server is listening on ${port}`);
});
//Создать сервер
var wsServer = new webSocketServer({
httpServer: server
});
//WebSocket сервер
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from ' + request.origin);
var connection = request.accept(null, request.origin);
//Нужно знать индекс клиента, чтобы убрать его в событии 'close'
var index = clients.push(connection) - 1;
console.log((new Date()) + ' Connection accepted');
//Создание нового игрока со случайным цветом и стартовой позицией
var newPlayer = {
index: index,
position: [
Math.floor(Math.random() * gameSettings.boardWidth),
Math.floor(Math.random() * gameSettings.boardHeight)
],
color: colors.shift()
};
//Добавить созданного игрока к состоянию игры
gameState.players.push(newPlayer);
//Разослать обновленное состояние игры всем игрокам
sendGameState();
//Обработчик сообщений от игрока
connection.on('message', function(message) {
//console.log("From: " + index + "; Msg: " + message.utf8Data);
handleCommand(index, message.utf8Data); //обработать команду
sendGameState(); //разослать обновленное состояние игры всем игрокам
});
//Пользователь отсоединился
connection.on('close', function(connection) {
var color = gameState.players[index].color;
console.log((new Date()) + " Player " +
connection.remoteAddress + " disconnected");
//Убрать пользователя из списка подключенных клиентов
clients.splice(index, 1);
//Убрать игрока из состояния игры
gameState.players.splice(index, 1);
//Разослать сообщение о дисконнекте игрока
sendPlayerDisconnected(index);
//Вернуть цвет игрока в общий массив цветов
colors.push(color);
});
});
function sendGameState() {
for (var i = 0; i < clients.length; i++) {
clients[i].sendUTF(JSON.stringify(gameState));
}
}
function sendPlayerDisconnected(index) {
playerDisconnected.index = index;
for (var i = 0; i < clients.length; i++) {
clients[i].sendUTF(JSON.stringify(playerDisconnected));
}
}
function handleCommand(index, command) {
var player = gameState.players[index];
if (player === null) {
return;
}
if (command === "left") {
if (player.position[0] > gameSettings.playerSpeed) {
player.position[0] -= gameSettings.playerSpeed;
}
} else if (command === "right") {
if (player.position[0] < gameSettings.boardWidth) {
player.position[0] += gameSettings.playerSpeed;
}
} else if (command === "up") {
if (player.position[1] > gameSettings.playerSpeed) {
player.position[1] -= gameSettings.playerSpeed;
}
} else if (command === "down") {
if (player.position[1] < gameSettings.boardHeight) {
player.position[1] += gameSettings.playerSpeed;
}
}
} | e8180542a96fda7f715c7edc55edf9053f81617c | [
"JavaScript"
] | 1 | JavaScript | AyurM/WebSocket-Game | 27ac0b82fbf67dc861943162b844ed852c67936e | 9b95638beb2df72686472846c0789bc305f344a0 |
refs/heads/master | <file_sep>package com.example.newcalender
class Product{
var id: Int = 0
var date: String? = null
var event: String? = null
constructor(currentdate: String, currentevent: String)
{
this.date = currentdate
this.event = currentevent
}
}<file_sep>package com.example.newcalender
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import android.widget.CalendarView
class MyDBOpenHelper(
context: Context?,
//name: String?,
factory: SQLiteDatabase.CursorFactory?
//version: Int
) : SQLiteOpenHelper(context, name, factory, version) {
companion object {
private val version = 1
private val name = "DB.db"
val TABLE_NAME = "events"
val COLUMN_ID = "_id"
val COLUMN_NAME1 = "date"
val COLUMN_NAME2 = "event"
var newStringDateDB = ""
var monthyear = ""
}
override fun onCreate(db: SQLiteDatabase?) {
val CREATE_PRODUCT_TABLE = ("CREATE TABLE " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME1 + " TEXT," +
COLUMN_NAME2 + " TEXT" +")")
db?.execSQL(CREATE_PRODUCT_TABLE)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db?.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}
fun addName(name: Product){
val values = ContentValues()
values.put(COLUMN_NAME1, name.date)
values.put(COLUMN_NAME2, name.event)
val db = this.writableDatabase
db.insert(TABLE_NAME, null, values)
db.close()
}
//get all tables from the database
fun getAllEvents(): Cursor?{
val db = this.readableDatabase
return db.rawQuery("SELECT * FROM $TABLE_NAME", null)
}
fun getDateEvents(): Cursor?{
val db = this.readableDatabase
return db.rawQuery("SELECT * FROM $TABLE_NAME WHERE date = '$newStringDateDB'",null)
}
fun getMonthEvents(): Cursor?{
val db = this.readableDatabase
return db.rawQuery("SELECT * FROM $TABLE_NAME WHERE date LIKE '%$monthyear%'", null)
}
}<file_sep>include ':app'
rootProject.name='New Calender'
<file_sep>package com.example.newcalender
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import sun.bob.mcalendarview.MCalendarView
class MainActivity : AppCompatActivity() {
var dateString: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val readdbtv: TextView = findViewById(R.id.readdbtv)
val textView: TextView = findViewById(R.id.newtextView)
val readdbtvevent: TextView = findViewById(R.id.readdbtvevent)
val editText: EditText = findViewById(R.id.editText)
val calendarView: CalendarView = findViewById(R.id.calenderView)
val submit_button: Button = findViewById(R.id.button)
calendarView.setOnDateChangeListener(CalendarView.OnDateChangeListener() { calendarView, year: Int, month: Int, day: Int ->
readdbtv.setText("")
dateString = ("$day/$month/$year")
val newmonthyear = "$month/$year"
readdbtvevent.setText("")
MyDBOpenHelper.newStringDateDB = dateString.toString()
MyDBOpenHelper.monthyear = newmonthyear.toString()
Log.i("Saad", MyDBOpenHelper.newStringDateDB)
val dbHandler = MyDBOpenHelper(this, null)
val cursor_sec = dbHandler.getDateEvents()
try {
cursor_sec!!.moveToFirst()
readdbtvevent.append(
cursor_sec.getString(
cursor_sec.getColumnIndex(MyDBOpenHelper.COLUMN_NAME1)
)
)
cursor_sec!!.moveToFirst()
readdbtvevent.append(
cursor_sec.getString(
cursor_sec.getColumnIndex(MyDBOpenHelper.COLUMN_NAME2)
)
)
while (cursor_sec.moveToNext()) {
readdbtvevent.append(
cursor_sec.getString(
cursor_sec.getColumnIndex(MyDBOpenHelper.COLUMN_NAME1)
)
)
readdbtvevent.append(
cursor_sec.getString(
cursor_sec.getColumnIndex(MyDBOpenHelper.COLUMN_NAME2)
)
)
}
}
catch (e: Exception) { Log.i("MainActivity", "While loop is failing") }
})
submit_button.setOnClickListener(View.OnClickListener {
val dbHandler = MyDBOpenHelper(this, null)
val newdateString: String = dateString.toString()
val newEditTextString: String = " - " + editText.text.toString() + "\n"
val user = Product(newdateString, newEditTextString)
dbHandler.addName(user)
Toast.makeText(this, "Stored", Toast.LENGTH_LONG).show()
readdbtvevent.setText("")
readdbtv.setText("")
editText.setText("")
val cursor = dbHandler.getAllEvents()
cursor!!.moveToFirst()
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME1)
))
)
cursor!!.moveToFirst()
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME2)
))
)
while (cursor.moveToNext()) {
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME1)
))
)
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME2)
))
)
readdbtv.setText("")
}
})
textView.setOnClickListener(View.OnClickListener {
val dbHandler = MyDBOpenHelper(this, null)
readdbtvevent.setText("")
readdbtv.setText("")
editText.setText("")
val cursor = dbHandler.getAllEvents()
cursor!!.moveToFirst()
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME1)
))
)
cursor!!.moveToFirst()
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME2)
))
)
while (cursor.moveToNext()) {
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME1)
))
)
readdbtv.append(
(cursor.getString(
cursor.getColumnIndex(MyDBOpenHelper.COLUMN_NAME2)
))
)
}
})
}
}
| 1f02f3dbe75ccbfc366e2140a23e1e39e02b5d28 | [
"Kotlin",
"Gradle"
] | 4 | Kotlin | saadjamshaid/CalendarView-with-Room-Database | ce1dddc932ad1248fc5df1d71af032a532bea000 | 922b5fd8519c4d491b3f0aeef9ca153666d6b385 |
refs/heads/main | <repo_name>GabrielQ-Tecsup/ProyectoPostea<file_sep>/app/Http/Controllers/Emailcontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Mail\TestMail;
use Illuminate\Support\Facades\Mail;
class Emailcontroller extends Controller
{
public function __construc()
{
$this->middleware('auth');
}
public function enviar(Request $request, $numero)
{
$user = $request->user;
$correo = New Emailbienvenida($user, $numero);
Mail::to($user)->send($correo);
return "Se envio un correo a su cuenta de manera correcta.";
}
}
<file_sep>/resources/lang/es/auth.php
<?php
return [
'E-Mail Address' => 'Correo Electronico',
'Password' => '<PASSWORD>',
'Remember Me' => 'Recuerdame',
'Forgot Your Password?' => 'Te olvidaste la contraseña?',
'Login' => 'Iniciar sesion',
'Register' => 'Registrarse',
'Logout' => 'Cerrar Sesion',
'Confirm Password' => '<PASSWORD>',
'Name' => 'Nombre'
];
| 23eeacb380e059f58017a3abcda720ea3658881d | [
"PHP"
] | 2 | PHP | GabrielQ-Tecsup/ProyectoPostea | 994c028c8c98e6d49785d0acb4ea91cf5930e62a | b015e12f3a86a7eba97ef4178bb965367f9b3e42 |
refs/heads/master | <repo_name>laxmandhakal/graphql-yoga<file_sep>/graphQL/resolver/authen.js
const jwt = require("jsonwebtoken");
const { secret } = require("./config");
module.exports = (ctx) => {
if (ctx.request.headers.token) {
let verified = jwt.verify(ctx.request.headers.token, secret);
return verified;
}
};<file_sep>/graphQL/resolver/subscription.js
const { pubsub } = require("../helper");
module.exports = {
Subscription: {
chat: {
subscribe() {
return pubsub.asyncIterator("chatTopic"); //Topic
},
},
},
};<file_sep>/graphQL/resolver/config.js
const secret = "This is secret key";
module.exports = { secret };<file_sep>/db.connect.js
const database = "mongodb://localhost:27017/test";
const remoteurl = "";
const mongoose = require("mongoose");
mongoose
.connect(remoteurl || database)
.then(() => {
console.log("Connection to DB successful");
})
.catch((err) => {
console.log("Db connection error====", err);
});<file_sep>/graphQL/schema/index.js
/* building GraphQL Schema */
module.exports = `
type userData {
_id: ID!
username: String!
createdAt:String!
updatedAt:String!
email: String!
password: String!
phonenumber: Float
token:String!
}
type chatinfo{
_id:ID!
message:String!
createdAt:String!
updatedAt:String!
}
input userInput{
username: String!
phonenumber: Float
password: String!
email: String!
}
type RootQuery {
userList: [userData!]!
chat:chatinfo
}
type DeleteRes{
response:String!
}
type token{
token:String!
}
type RootMutation {
createUser(newUser: userInput): userData!
deleteUser(username: String! password:String!): DeleteRes!
login(username:String! password:String!):token!
addMessage(message:String!):chatinfo!
}
type Subscription{
chat: chatinfo!
}
schema {
query: RootQuery
mutation: RootMutation
subscription: Subscription
}
`;<file_sep>/graphQL/resolver/mutationResolver.js
const userModels = require("../../model/users");
const chatModel = require("../../model/chat");
const { pubsub } = require("../helper");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { secret } = require("./config");
const tokenChecker = require("./authen");
function getToken(username, email) {
return jwt.sign({ username, email }, secret);
}
module.exports = {
RootMutation: {
createUser: async(_, args, ctx) => {
try {
let bpassword = await bcrypt.hash(args.newUser.password, 12);
args.newUser.password = bpassword;
let query = {
username: args.newUser.username,
password: <PASSWORD>,
email: args.newUser.email,
phonenumber: args.newUser.phonenumber,
};
const createUserDetails = await userModels.findOneAndUpdate(
query,
args.newUser, { upsert: true, new: true }
);
const { username, email } = createUserDetails;
let token = getToken(username, email);
return {...createUserDetails._doc, token };
} catch (error) {
return error;
}
},
deleteUser: async(parent, args, ctx, info) => {
let responseMSG = {};
try {
let query = { username: args.username, password: args.password };
const createUserDetails = await userModels.findOneAndDelete(query);
if (createUserDetails == null) {
responseMSG.response = "No User found for this opertaion";
return responseMSG;
} else {
responseMSG.response = "Success";
return responseMSG;
}
} catch (error) {
responseMSG.response = "Fail";
return responseMSG;
}
},
login: async(_, args, ctx) => {
try {
const { username, password } = args;
let user = await userModels.findOne({
$or: [{ username }, { email: args.username }],
});
if (user) {
let check = bcrypt.compare(password, user.password);
if (check) {
token = getToken(user.username, user.email);
return { token };
}
}
return { token: "error user not found" };
} catch (error) {
return error;
}
},
addMessage: async(_, args, ctx) => {
try {
let verified = tokenChecker(ctx);
const { username, email } = verified;
let userT = await userModels.findOne({ username, email });
if (userT) {
let response = new chatModel({ message: args.message });
let data = await response.save();
pubsub.publish("chatTopic", {
chat: data,
});
return data;
}
} catch (error) {
return error;
}
},
},
}; | f49df4067a95be3972357b70efeb2dc45dcfe7cc | [
"JavaScript"
] | 6 | JavaScript | laxmandhakal/graphql-yoga | a647c0a478c67bec9d0ac709012247cd30e4ca5b | 5ff209255efa2cc12455a6ee3ab5c14ce2ccf10e |
refs/heads/master | <repo_name>hktr92/m2cms-skeleton<file_sep>/web/index-ng.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 6/5/16 5:23 PM
* @since 0.5.2
*/
/**
* Fișierul front-controller.
* Versiunea next-gen
*
* Acest fișier servește drept controller pentru acest website.
* Scopul acestui fișier este să citească ruta (r=controller) și să randeze view-ul (loadTemplate('controller', 'pagina'))
*
* Acest controller este minimalist și crud. Pe acest principiu se bazează structura MVC, însă e mult mai bine dezvoltat.
* Nu-mi permit dezvoltarea unui sistem MVC decent și un Routing avansat, dar fiindcă site-ul este unul lite, nu este
* nevoie de ceva mult prea avansat.
*/
/**
* Această variabilă este pentru cei ce nu pot uploada site-ul în afara folderului public (de obicei `public_htm`l.
*
* Definiți valoarea variabilei pe `true` dacă uploadați tot site-ul în interiorul folderului public
* Definiți valoarea variabilei pe `false` în caz contrar.
*
* Valoarea implicită: false
*/
$backend_in_public = false;
/**
* Includem fișierul bootstrap.
*
* Explicația variabilelor:
* - $directory => în funcție de $backend_in_public, folosește folderul curent sau numele folderului rădăcină.
*/
if ($backend_in_public) {
$directory = __DIR__;
} else {
$directory = dirname(__DIR__);
}
require_once sprintf('%s/async2-ng.php', $directory);
/**
* Prescurtăm câteva variabile din configurație.
* - $beta_server => (bool) dacă serverul este în beta sau nu.
* - $maintenance => (bool) dacă se efectuează lucrări de întreținere pe server.
* se setează automat pe `true` dacă nu se poate realiza conexiunea la baza de date
* a serverului de Metin2
* - $coming_soon => (bool) dacă serverul este în lucru și va fi finalziat curând.
* - $beta_limits => (int) numărul maxim de conturi permise pentru înregistrare
*/
$server_mode = config('server.mode');
$beta_limits = config('beta.limit');
switch ($server_mode)
{
case 'beta':
if ($app['registered_accounts'] <= $beta_limits) {
load_template('splash', 'quick_register');
} else {
load_template('splash', 'register_done');
}
break;
case 'official':
require_once $directory . '/app/routes.php';
break;
case 'coming_soon':
load_template('splash', 'coming_soon');
break;
case 'maintenance':
load_template('splash', 'maintenance');
break;
default:
load_template('splash', 'server_error');
break;
}
<file_sep>/app/safelocker/queries/top_100_guilds.sql
SELECT
`player`.`guild`.`name` AS guild_name,
`player`.`player`.`name` AS guild_leader,
`player`.`guild`.`ladder_point` AS guild_points,
`player`.`guild`.`level` AS guild_level,
`player`.`guild`.`exp` AS guild_exp
FROM
`player`.`guild`
JOIN
`player`.`player`
ON
`player`.`guild`.`master` = `player`.`player`.`id`
ORDER BY
`guild_points` DESC,
`guild_exp` DESC
LIMIT
0,100;<file_sep>/hktr/exception/AppNotBootableException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 29.07.2016 01:21
*/
namespace hktr92\exception;
class AppNotBootableException extends \Exception
{
}<file_sep>/app/safelocker/tables/logs_csrf.sql
CREATE TABLE IF NOT EXISTS `syncms`.`logs_csrf` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`page` VARCHAR(64) NULL,
`locked_token` TEXT NULL,
`given_token` TEXT NULL,
`when` DATETIME NULL,
`hostname` VARCHAR(32) NULL,
`browser` VARCHAR(128) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4<file_sep>/hktr/async2.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 20.07.2016 19:03
*/
namespace hktr92;
use Pimple\Container;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Debug\Debug;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Router;
use Symfony\Component\Finder\Finder;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Doctrine\DBAL\Configuration;
use Doctrine\DBAL\DriverManager;
class async2
{
public $app;
public function __construct($root_dir, $development = false)
{
$this->app = new Container();
$this->app['kernel.root_dir'] = $root_dir;
$this->app['kernel.cache_dir'] = sprintf('%s/app/cache', $root_dir);
$this->app['kernel.config_dir'] = sprintf('%s/app/config', $root_dir);
$this->app['kernel.app_dir'] = sprintf('%s/src', $root_dir);
$this->app['kernel.version'] = rtrim(file_get_contents($root_dir.'/app/safelocker/async2.ver'));
$this->app['dev.enabled'] = $development;
}
public function get_app()
{
return $this->app;
}
public function init_config()
{
$this->app['config'] = function ($c) {
$finder = new Finder();
$config_directory = $c['kernel.config_dir'];
$config_files = [];
$finder->in($config_directory)->files()->name('*.yml');
foreach ($finder as $file) {
$file_info = pathinfo($file->getRealPath());
$config_files[$file_info['filename']] = $file->getRealPath();
}
return new \hktr92\config($config_files);
};
}
public function init_session()
{
$this->app['session'] = function ($c) {
$session = new Session();
$session->setName($c['config']->get_from_config('session', 'name'));
$session->start();
return $session;
};
}
public function init_debug()
{
if ($this->app['dev.enabled']) {
$this->app['dev.debug'] = function () {
$debug = Debug::enable();
return $debug;
};
$this->app['dev.error_handler'] = function () {
return ErrorHandler::register();
};
}
}
public function init_request()
{
$this->app['request'] = function () {
return Request::createFromGlobals();
};
}
public function init_routes()
{
$this->app['routes'] = function ($c) {
$locator = new FileLocator([$c['config_dir']]);
$loader = new YamlFileLoader($locator);
$collection = $loader->load('routes.yml');
$cache_dir = $c['dev.enabled'] ? null : sprintf('%s/routes', $c['cache_dir']);
$context = new RequestContext();
$context->fromRequest($c['request']);
$route = new Router(
$loader,
$collection,
['cache_dir' => $cache_dir],
$context
);
return $route;
};
}
public function init_db()
{
$this->app['db'] = function ($c) {
$connection_parameters = $c['config']->get_from_config('doctrine');
$config = new Configuration();
$db = DriverManager::getConnection($connection_parameters, $config);
return $db;
};
}
public function init_logger()
{
$this->app['logger'] = function ($c) {
$journal = sprintf('%s/logs/async2.log', $c['kernel.root_dir']);
$level = $c['dev.enabled'] ? Logger::DEBUG : Logger::WARNING;
$log = new Logger('async00');
$log->pushHandler(new StreamHandler($journal, $level));
return $log;
};
}
public function init_mailer()
{
$this->app['mailer.message'] = function ($c) {
$message = \Swift_Message::newInstance();
return $message;
};
$this->app['mailer.transport'] = function ($c) {
$transport = \Swift_MailTransport::newInstance();
return $transport;
};
$this->app['mailer.instance'] = function ($c) {
$mailer = \Swift_Mailer::newInstance($c['mailer.transport']);
return $mailer;
};
}
public function init_template()
{
$this->app['template'] = function ($c) {
$template_path = $c['config']->get_from_config('master', 'twig', 'path');
$twig_options = $c['config']->get_from_config('master', 'twig', 'options');
$loader = new \Twig_Loader_Filesystem($template_path);
$twig = new \Twig_Environment($loader, $twig_options);
return $twig;
};
}
public function init_finder()
{
$this->app['finder'] = function () {
return new Finder();
};
}
}
<file_sep>/hktr/exception/InvalidConfigurationException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 01.08.2016 20:38
*/
namespace hktr92\exception;
class InvalidConfigurationException extends \Exception
{
}<file_sep>/src/models/account_panel.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 11.07.2016 19:08
*/
namespace app\model;
class account_panel
{
protected $db;
public function __construct(\PDO $db_handler)
{
$this->db = $db_handler;
}
public function get_user_info($user_id)
{
$query = "SELECT
`account`.`account`.`login` AS account_name,
`account`.`account`.`social_id` AS security_code,
`account`.`account`.`email` AS account_email,
`account`.`account`.`create_time` AS create_time,
`account`.`account`.`is_testor` AS beta_tester,
`account`.`account`.`status` AS account_status,
`account`.`account`.`securitycode` AS account_token,
`account`.`account`.`newsletter` AS subscriber,
`account`.`account`.`nickname` AS display_name
FROM
`account`.`account`
WHERE
`account`.`account`.`id` = :user_id
;";
$stmt = $this->db->prepare($query);
$stmt->execute([
':user_id' => $user_id
]);
return $stmt->fetch();
}
public function check_username_exists($username)
{
$query = "SELECT COUNT(id) FROM account.account WHERE login = '{$username}'";
$exec = $this->db->query($query);
return $exec->fetchColumn();
}
public function get_login_data($username, $password)
{
$command = "SELECT
`id`, `status`, `is_admin`
FROM
`account`.`account`
WHERE
`login` = :username
AND
`password` = :password
;";
$stmt = $this->db->query($command);
$stmt->bindParam(':username', $username, \PDO::PARAM_STR);
$stmt->bindParam(':password', $password, \PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch();
}
}<file_sep>/README.md
Metin2SDF Website Skeleton
==========================
Aceasta este aplicația web de bază al site-ului serverului privat de Metin2, Metin2SDF.
Este o aplicație scrisă de la scratch pentru PHP 7.0, însă a fost adaptată pentru PHP 5.5.
Prin acest proiect s-a încercat actualizarea și îmbunătățirea bazei de lucru a site-urilor de Metin2, în prezent
folosindu-se baza oferită de Darkdev, care acum este nesigură și vulnerabilă, datorită noilor schimbări în limbajul de programare PHP, cum ar fi eliminarea [eliminarea API-ului original MySQL](http://php.net/manual/en/book.mysql.php) și recomandarea trecerii la [API-ul mai sigur și mai modern](http://php.net/manual/en/book.mysqli.php) sau [migrarea la un Database Abstraction Layer](http://php.net/manual/en/book.pdo.php).
Soluția aceasta nu este una perfectă, însă este o dezvoltare în progres. Caracteristicile de bază sunt simple și lipsite de
claritate. Pe viitor se dorește implementarea unei baze cât mai stabile, securizată și modulară, folosindu-se librăriile publice, la care s-au lucrat și testat ore în șir.
What's inside?
--------------
Scheletul pentru site-ul Metin2SDF conține următoarele caracteristici primare:
* **Prezentarea generală** - reprezentat ca fiind o pagină statică pe care apar statisticile generale ale serverului.
* **Panou cont** - este o modificare care se ocupă de înregistrare, conectare și actualizarea informațiilor contului utilizatorului / jucătorului.
* **Panou jucător** - este o modificare care trebuie să afișeze informațiile despre caracterele jucătorului, și informații detaliate ale unui caracter,
* **Panou de control** - este panoul de administrare a site-ului în care se administrează pagina de descărcare a site-ului.
- **Clasament** - este compus din clasamentul jucătorilor și a breslelor
- **Splash** - termenul de „splash” face referire la o pagină statică, separată de restul site-ului. Paginile tip splash sunt folosite pentru paginile de eroare, Beta, Mentenanță și Coming soon.
- **Securitate sporită** - pagina este securizată cât mai mult posibil prin librăriile oferite de Symfony, în special librăria Symfony/Form, care se ocupă de tratarea formularelor, Symfony/HttpFoundation, care se ocupă de Request / Response într-un mod sigur și logic, și utilizarea Doctrine/DBAL pentru interacțiunea cu baza de date.
Tehnologii folosite
--------------
- **PHP** 5.5 sau mai nou
- **Doctrine** pentru interacțiunea cu baza de date
- **Symfony YAML** pentru interpretarea configurației YAML
- **SwiftMailer** pentru trimiterea de mail-uri
- **Bootstrap** 3 pentru design
- **Twig** pentru templating
Specificații Apache:
--------------
- **Versiunea** 2.4.*
- **Module** care trebuie activate: rewrite, mod_php
Specificații PHP:
--------------
- **Extensii** necesare: mcrypt, mbstring, json, ctype, pdo_mysql, session, phar, openssl
- **Configurația** php.ini recomandată:
```ini
[PHP]
date.timezone = Europe/Bucharest ; poate fi schimbată cu alta
short_open_tag = Off ; tag-urile precum <? ?>
magic_quotes_gpc = Off ; magic_quotes este deprecated din php 5.3 si scos din php 7.0
register_globals = Off ; se va ocupa Symfony/HttpFoundation de asta
session.auto_start = Off ; sesiunea va fi inițiată automat de Symfony/HttpFoundation
```
Specificații MySQL:
--------------
- **Configurația** my.cnf / my.ini recomandată:
```ini
[mysqld]
collation-server = utf8mb4_general_ci ; general_ci sau romanian_ci, dar e mai ok așa
character-setserver = utf8mb4 ; utf8mb4 este mai sigur decât utf8 fiindcă are suport multibytes
```
Cerințe de sistem
--------------
Aceste cerințe de sistem sunt recomandate pentru buna funcționare a aplicației web.
- Sistem de operare: Linux
- Server web: Apache 2.4 / Nginx 1.9
- Server DB: MySQL 5.6
- Versiune PHP: 5.5
>**NOTă:** Deoarece Ubuntu 16.04 are în mod implicit PHP 7, se recomandă utilizarea PPA-ului [acesta](https://ppa.launchpad.net/~ondrej/) și instalați php5.5.
Instalare și configurare (Webhost)
----------------------------------
>**NOTĂ!** Această configurație se face __DOAR PENTRU__ Webhost-uri și se presupune că lucrezi de pe Windows. Pentru VPS, citiți mai jos.
## 1) Instalează aplicația
Descărcați ultima versiune de pe [repositoriul oficial](https://github.com/hktr92/m2cms-skeleton/releases). Preferabil ca și arhivă .ZIP
Dezarhivați site-ul pe Desktop sau în alt folder.
## 2) Instalează XAMPP
Acest proiect are nevoie de librării suplimentare pentru buna functionare a site-ului. Aceste librării se instalează cu ajutorul Composer, însă Composer are nevoie de PHP instalat pe sistem și extensia openssl.
Proiectul XAMPP ar trebui să fie suficient pentru această sarcină.
Descărcarea se face de [aici](https://www.apachefriends.org/xampp-files/5.6.23/xampp-win32-5.6.23-0-VC11-installer.exe).
## 2) Instalează dependințele
Proiectul odată descărcat, nu poate rămâne astfel. Aplicația web folosește câteva dependințe necesare funcționării. Pentru acest lucru, aveți nevoie de Composer.
Dacă nu aveți composer, folosiți instrucțiunile de pe pagina [oficială Composer](https://getcomposer.org/download/).
Când executați instalabilul Composer și vă cere calea spre PHP, selectați calea spre php.exe din XAMPP.
Lăsați orice opțiune care face referire la adăugarea Composer în meniu contextual (când dai click dreapta pe un fișier).
După instalarea Composer, deschideți folderul unde ai extras arhiva, click dreapta pe `composer.json` și din meniul contextual Composer, click pe „Install”.
## 3) Configurația serverului web
În folderul `web` creați un fișier nou numit `.htaccess` și puneți următorul conținut:
```
<IfModule mod_rewrite.c>
Options -Indexes -MultiViews FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
```
## 4) Configurația bazei de date.
Creați o bază de date nouă din panoul de control furnizat de firma de webhost (de obicei cPanel). După creare, deschideți phpMyAdmin și importați **toate** fișierele tip SQL din folderul `app/safelocker/tables` **mai puțin** `_database.sql`.
Opțional, dacă vrei să faci baza de date pe serverul MySQL al serverului de Metin2, execută **toate** fișierele tip SQL din folderul amintit anterior, **inclusiv** `_database.sql`.
## 5) Upload-ul.
Redenumiți folderul `web` în `public_html`.
Pentru upload, recomand să se efectueze **în afara folder-ului __public_html__**. Folderele precum `app`, `vendor` și fișierele `composer.json` și `async2.php` **trebuie** să fie în afara folderului public.
Totuși, dacă nu se poate uploada în afara folderului public, efectuați următoarele modificări:
- mutați tot conținutul folderului `web` în rădăcină (unde este `composer.json` și `async2.php`
- deschideți fișierul `index.php` și modificați valoarea variabilei `$backend_in_public` cu valoarea `true`.
>**NOU!** Dacă doriți să testați noul backend, setați valoarea variabilei `$use_oop_backend` pe true în fișierul `index.php`!
## Gata.
Aplicația web este instalată, configurată și funcțională de acum.
Instalare și configurare (VPS)
------------------------------
>**NOTĂ!** Această configurație se face __DOAR PENTRU__ VPS-uri. Pentru webhost, citiți mai jos.
## 1) Instalează aplicația
Recomandabil este să se folosească Git pentru descărcarea proiectului. Actualizările ulterioare pot fi efectuate folosindu-se Git.
user@host~$ git clone https://github.com/hktr92/m2cms-skeleton
Opțional, numele directorului unde se găsește proiectul poate fi modificat, adăugându-se numele ca și parametru:
user@host~$ git clone https://github.com/hktr92/m2cms-skeleton nume_folder
## 2) Instalează dependințele
Proiectul odată descărcat, nu poate rămâne astfel. Aplicația web folosește câteva dependințe necesare funcționării. Pentru acest lucru, aveți nevoie de Composer.
Dacă nu aveți composer, folosiți instrucțiunile de pe pagina https://getcomposer.org/download/ următoarea comandă pentru instalare:
user@host~$ curl -sS https://getcomposer.org/installer | php
Pe urmă, folosiți comanda `install`:
user@host~$ cd m2cms-skeleton
user@host~$ php composer.phar install --no-dev --optimize-autoloader
## 3) Configurația serverului web
Pentru accesarea platformei de pe browser, se recomandă configurarea unui server web (recomandabil Apache sau Nginx).
**Configurația recomandată** pentru rularea aplicației pe serverul web Apache cu mod_php este următoarea:
```
<VirtualHost *:80>
ServerName domain.tld
ServerAlias www.domain.tld
DocumentRoot /var/www/project/web
<Directory /var/www/project/web>
AllowOverride None
Order Allow,Deny
Allow from All
<IfModule mod_rewrite.c>
Options -Indexes -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>
</Directory>
<Directory /var/www/project>
Options FollowSymlinks
</Directory>
ErrorLog /var/log/apache2/project_error.log
CustomLog /var/log/apache2/project_access.log combined
</VirtualHost>
```
**Configurația recomandată** pentru rularea aplicației pe serverul web Nginx este următoarea:
```
server {
server_name domain.tld www.domain.tld;
root /var/www/project/web;
location / {
# try to serve file directly, fallback to index.php
try_files $uri /index.php$is_args$args;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
# When you are using symlinks to link the document root to the
# current version of your application, you should pass the real
# application path instead of the path to the symlink to PHP
# FPM.
# Otherwise, PHP's OPcache may not properly detect changes to
# your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
# for more information).
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
# Prevents URIs that include the front controller. This will 404:
# http://domain.tld/app.php/some-path
# Remove the internal directive to allow URIs like this
internal;
}
error_log /var/log/nginx/project_error.log;
access_log /var/log/nginx/project_access.log;
}
```
## 4) Configurația bazei de date.
Pentru baza de date, conectați-vă cu utilizatorul root / maintainer și executați următorul script:
user@host~$ mysql -u root -p < app/safelocker/tables/*.sql
Acest script SQL va creea baza de date, baza de date și tabelele.
## Gata.
Aplicația web este instalată, configurată și funcțională de acum.
Mediu de dezvoltare utilizat
--------------
- Pentru development:
- Sistem de operare: GNU/Linux Ubuntu 16.04 x86_64
- Server web: Apache 2.4.18
- Versiune PHP: 5.5.37, 5.6.23, 7.0.8, 7.1.0-alpha2 (versiuni multiple prin update-alternatives)
- Bază de date: MySQL 5.7.12
Licență
--------------
Proiectul a fost lansat sub licența MIT.
<file_sep>/app/safelocker/queries/top_100_players.sql
SELECT
`player`.`player`.`name` AS player_name,
`player`.`player`.`level` AS player_level,
`player`.`player`.`exp` AS player_experience,
`player`.`player_index`.`empire` AS player_empire,
`player`.`guild`.`name` AS player_guild
FROM
`player`.`player`
LEFT JOIN
`player`.`player_index`
ON
`player`.`player_index`.`id` = `player`.`player`.`account_id`
LEFT JOIN
`player`.`guild_member`
ON
`player`.`guild_member`.`pid` = `player`.`player`.`id`
LEFT JOIN
`player`.`guild`
ON
`player`.`guild`.`id` = `player`.`guild_member`.`guild_id`
INNER JOIN
`account`.`account`
ON
`account`.`account`.`id` = `player`.`player`.`account_id`
WHERE
`player`.`player`.`name`
NOT LIKE '[%]%'
AND `account`.`account`.`status` != 'BLOCK'
ORDER BY
`player`.`player`.`level` DESC,
`player`.`player`.`exp` DESC
LIMIT 0,100;<file_sep>/TODO.md
Metin2SDF Skeleton TO-DO
========================
General:
- [ ] de implementat trimiterea unui e-mail după înregistrarea contului (SwiftMailer)
- [ ] de implementat un sistem de scriere a noutăților pe prima pagină
- [x] <del>de actualziat funcția url() conform noului sistem de routing</del>
- [x] <del>trebuie să se adauge modul SEO activ în mod implicit</del> SEO nu poate fi dezactivat datorită noului sistem de routing.
Panou cont:
- [ ] de completat panoul cont cu alte caracteristici
- [ ] de finalizat pagina cu informații caracter
Panou jucător:
- [ ] de implementat routing-ul pentru detalii caracter
- [ ] de scris pagina de informații bresle
Panou administrator:
- [ ] de scris CRUD (Create, Read, Update, Delete) pentru pagina de descărcări
- [ ] de scris CRUD pentru pagina de noutăți
- [ ] de scris un sistem de verificare a versiunii
Securitate:
- [ ] implementarea unui sistem de notificare a conectării utilizatorului cu switch din player panel (email / db logging)
- [x] <del>implementarea Monolog pentru logging</del>
- [ ] implementarea Symfony/Form pentru securitate avansată
- [x] <del>implementarea Symfony/HttpFoundation pentru securizare POST, GET, SERVER</del>
Design:
- [ ] de adăugat design (twbt|boilerplate)
- [ ] pagina default de clasament trebuie aranjată mai bine. poate două imagini cu tipurile de clasament?
v0.99:
- [ ] de scris un sistem de verificare / actualizare a versiunii platformei (REST API)
- [ ] de scris un sistem de instalare / pregătire al scheletului<file_sep>/app/functions/security.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 05.06.2016 18:00
*/
/**
* Această funcție securizează un string. Mai exact, aplică filtre pentru „curățare”.
*
* Putem folosi mysqli_real_escape_string(), însă se poate folosi DOAR în context cu cod SQL și nu poate fi apelată
* dacă extensia mysqli este inexistentă.
*
* Din fericire, există alternative, iar filter_var este cel mai eficient în acest context. Are numeroase tipuri de
* filtre definite.
*
* Mai multe informații aveți aici: http://php.net/manual/ro/filter.filters.sanitize.php
*
* @param string $var Variabila care este predispusă la vulnerabilități
* @return string Variabila curățată de orice rele.
*/
function sanitize($var)
{
/**
* Această funcție NU permite array-urile, deci aici sunt oprite.
*/
if (is_array($var)) return null;
return filter_var($var, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
} // END function sanitize
/**
* Această funcție este o alternativă sigură pentru $_POST.
*
* Deoarece $_POST este predispus la vulnerabilități, este necesară filtrarea valorii fiecărui index din array.
* Deoarece în $_POST nu există cod SQL propriu-zis, putem folosi funcția sanitize(), definită mai sus. Astfel,
* curățarea $_POST['username'] se poate face astfel: sanitize($_POST['username']).
*
* Această metodă este cam nesigură, întrucât se folosește un singur tip de filtru în acea funcție. Desigur, se poate
* extinde, dar asta ar însemna rescrierea codului.
*
* Așadar, o soluție mai practică o reprezintă funcția de mai jos. Apelează funcția filter_input pentru INPUT_POST,
* preia $name și aplică filtrul $filter. Mai practic și mai sigur.
*
* @param string $name Numele input-ului preluat din $_POST (ex: username)
* @param string $filter Tipul de filtru. implicit este 'string'.
* @return mixed Valori multiple.
* - (string) valoarea $_POST[$name] filtrat
* - (null) dacă valoarea este inexistentă
* - (false) dacă aplicarea filtrului a eșuat
*/
function fetch_post($name, $filter = 'string')
{
switch ($filter) {
case 'email':
$f = FILTER_SANITIZE_EMAIL;
break;
case 'number':
$f = FILTER_SANITIZE_NUMBER_INT;
break;
case 'float':
$f = FILTER_SANITIZE_NUMBER_FLOAT;
break;
case 'string':
$f = FILTER_SANITIZE_FULL_SPECIAL_CHARS;
break;
default:
$f = FILTER_SANITIZE_FULL_SPECIAL_CHARS;
break;
}
return filter_input(INPUT_POST, $name, $f);
} // END function fetch_post
/**
* Această funcție este o alternativă pentru $_GET
*
* Este apelată aceeași funcție, filter_input, dar de data asta pentru INPUT_GET, preia $name și aplică filtrul special
* pentru link-uri FILTER_SANITIZE_URL.
*
* @param string $name Numele input-ului preluat din $_GET
* @return mixed (string) valoarea $_GET[$name]
* (null) pentru valoare inexistentă
* (false) pentru eșecul aplicării filtrului
*/
function fetch_get($name)
{
return filter_input(INPUT_GET, sanitize($name), FILTER_SANITIZE_URL);
} // END function fetch_get
/**
* Această funcție preia adresa IP reală a clientului.
*
* @return bool|string (bool) dacă IP-ul este invalid
* (string) dacă IP-ul este valid
*/
function get_ip_address() {
$ip_keys = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR'
];
foreach ($ip_keys as $key) {
if (array_key_exists($key, $_SERVER) === true) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
$ip = trim($ip);
if (validate_ip($ip)) {
return $ip;
} else {
return false;
}
}
}
}
return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
} // END function get_ip_address
/**
* Verificăm dacă adresa IP este validă și nu este IP dintr-o rețea privată.
*
* @param string $ip Adresa IP pentru verificare
* @return bool Validitatea adresei IP
*/
function validate_ip($ip)
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return false;
}
return true;
} // END function validate_ip
/**
* MySQL "PASSWORD()" AKA MySQLSHA1 HASH FUNCTION
* Aceasta este funcția pentru password hash folosit în MySQL 4.1.1+
*
* By Rev. <NAME> 10/9/2009 9:36:20 AM
*
* @param string $input Parola pentru calculare
* @param bool $hex Dacă se folosește cod hex sau nu
* @return string Returnează parola cu hash
*/
function mysql_password_hash($input, $hex = true)
{
$sha1_stage1 = sha1($input, true);
$output = sha1($sha1_stage1, !$hex);
return '*'.strtoupper($output);
} //END function mysql_password_hash
/**
* Calculează fiecare pereche hexadecimală în bit-ul corespunzător.
* Similar cu funcția hex2octet din mysql
*
* By <NAME> Fineout 10/9/2009 9:36:20 AM
*
* @param string $hex Codul hex
* @return string Codul binar
*/
function hex_hash_to_bin($hex)
{
$bin = "";
$len = strlen($hex);
for ($i = 0; $i < $len; $i += 2) {
$byte_hex = substr($hex, $i, 2);
$byte_dec = hexdec($byte_hex);
$byte_char = chr($byte_dec);
$bin .= $byte_char;
}
return $bin;
} //END function hex_hash_to_bin
/**
* @param $parameter
* @return bool
* @since v0.5.2
*/
function config($parameter)
{
global $app;
$config = $app['config'];
if (!array_key_exists($parameter, $config)) {
return false;
}
return $config[$parameter];
} // END function config
/**
* Această funcție preia un obiect fix sau un array din $app['config'].
*
* Este scris pentru facilitarea accesării unui item din configurație. Din păcate, această funcție are o adâncime
* maximă de 3 sub-arrays, adică:
*
* $app['config'][$branch][$category][$item]
*
* @param string|null $category Categoria dintr-un anumit branch, ex: 'server' ($app['config']['master']['server'])
* @param string|null $item Un obiect dintr-o categorie din branch-ul respectiv
* @param string $branch Branch-ul din care face parte configurația. Coincide cu numele fișierului
* configurație
* @return array|bool|mixed (array) dacă $item, $category și $branch sunt null, sunt returnate ca array.
* (bool) false la eșec
* (mixed) poate fi orice tip de date suportat de Yaml.
* @deprecated din versiunea 0.5.2
*/
function get_from_config($branch, $category = null, $item = null)
{
trigger_error('Deprecated: function get_from_config() is deprecated, will be removed in v0.7.5.', E_USER_DEPRECATED);
global $app;
$config = $app['config'];
if (!is_array($config)) {
error_log('$config is not array' . PHP_EOL, 3, $app['rootdir'].'/logs/php_error.log');
return false;
}
if (!is_null($branch) && !array_key_exists($branch, $config)) {
error_log('$config['.$branch.'] is not array' . PHP_EOL, 3, $app['rootdir'].'/logs/php_error.log');
return false;
}
if (!is_null($category) && !array_key_exists($category, $config[$branch])) {
error_log('$config['.$branch.']['.$category.'] is not array' . PHP_EOL, 3, $app['rootdir'].'/logs/php_error.log');
return false;
}
if (!is_null($item) && !array_key_exists($item, $config[$branch][$category])) {
error_log('$config['.$branch.']['.$category.']['.$item.'] is not array' . PHP_EOL, 3, $app['rootdir'].'/logs/php_error.log');
return false;
}
if (is_null($category)) {
$return_value = $config[$branch];
} else if (!is_null($category) && is_null($item)) {
$return_value = $config[$branch][$category];
} else if (!is_null($category) && !is_null($item)) {
$return_value = $config[$branch][$category][$item];
} else {
$return_value = $config;
}
return $return_value;
} // END function get_from_config
<file_sep>/hktr/exception/NotObjectException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 01.08.2016 14:26
*/
namespace hktr92\exception;
class NotObjectException extends \Exception
{
}<file_sep>/app/functions/page.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 05.06.2016 5:31 PM
*/
/**
* Această funcție afișează adresa completă spre o anumită pagină. Are valoarea implicită 'null' ca să redirecționeze
* spre pagina principală (ex: metin2sdf.com)
*
* @param string|null $url Pagina care vrei să fie afișată.
* @return string Adresa completă spre acea pagină:
* - metin2sdf.com/pagina-mea pentru SEO activ,
* - metin2sdf.com/index.php?r=pagina-mea pentru SEO inactiv.
*/
function url($url = null)
{
/**
* Preluăm statutul SEO din configurație
*/
$seo = (bool) config('seo.rewrite');
if (!is_bool($seo)) {
trigger_error(sprintf("Error: seo.rewrite must be boolean, %s given.", gettype($seo)), E_USER_ERROR);
}
/**
* Dacă SEO este activ / setat pe true:
* - setăm variabila $return_value cu URL friendly (metin2sdf.com/$url)
* Altfel dacă SEO este inactiv / setat pe false:
* - setăm variabila $return_value cu URL standard (metin2sdf.com/index.php?r=$url)
* În caz contrar ($url are valoare implicit NULL)
* - setăm variabila $return_value fără REQUEST_URI (metin2sdf.com)
*/
if ($seo) {
$return_value = sprintf('%s/%s', get_url(), $url);
} else if (!$seo) {
$return_value = sprintf('%s/index.php?r=%s', get_url(), $url);
} else {
$return_value = get_url();
}
return $return_value;
} // END function url
/**
* Verificăm dacă o anumită pagină se află în REQUEST_URI
*
* Această funcție este utilă pentru afișarea unui mesaj în layout-ul template-ului pe o anumită pagină
* De exemplu, pe prima pagină apar statisticile, iar pe alte pagini nu.
*
* NOTE: __main_page__ a fost pus ca valoare implicită ca să faciliteze utilizarea funcției
* (implicit, funcția e folosită doar pe prima pagină, dar poate fi folosită în altă parte).
* astfel, funcția poate fi apelată fără parametrii.
*
* @param string $page Numele paginii pe care vrei să apară mesajul. Implicit __main_page__, pentru mesaj DOAR PE
* prima pagină a site-ului.
* @return bool
*/
function in_url($page = '__main_page__')
{
if ($page == '__main_page__' && $_SERVER['REQUEST_URI'] == '/' || $_SERVER['REQUEST_URI'] == 'index.php' || $_SERVER['REQUEST_URI'] == 'index.php?r=') {
return true;
} else {
return false;
}
} // END function in_url
/**
* Această funcție construiește URL-ul în funcție de protocol și hostname.
*
* @return string adresa web a hostname-ului (ex: http://metin2sdf.com)
*/
function get_url()
{
if (php_sapi_name() == 'cli') exit;
$protocol = isset($_SERVER['HTTPS']) ? 'https' : 'http';
$hostname = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
return sprintf('%s://%s', $protocol, $hostname);
} // END function get_url
/**
* Această funcție returnează calea spre o resursă folosită pe pagina web (css, imagine, javascript...)
*
* Folderul 'assets' trebuie să fie existent fizic în folderul public ($app['rootdir'] . '/web').
* Fiecare fișier cu o anumită extensie trebuie să aibă folder cu extensia respectivă. Adică:
* - assets/css/site.css => css-ul principal
* - assets/png/logo.png => logo-ul site-ului
*
* @param string $file Numele fișierului pe care vrei să-l returnezi
* @param string $category Categoria (folder fizic în assets) în care să fie căutat
* @return string Returnează calea completă (ex: http://metin2sdf.com/assets/css/site.css)
*/
function asset($file, $category)
{
/**
* Baza de lucru (funcția get_url() și folderul assets)
*/
$base = sprintf('%s/assets', get_url());
return sprintf('%s/%s/%s.%s', $base, $category, $file, $category);
} // END function asset
/**
* Funcția pentru redirecționare pe o anumită pagină
*
* @param string|null $page Pagina unde vrei să redirecționezi.
*/
function redirect($page = null)
{
if (!headers_sent()) {
header(sprintf('Location: %s', url($page)));
}
} // END function redirect
/**
* Această funcție include fișierul-șablon din $app['tpldir'] în funcție de categorie și pagină.
*
* @param string $controller Controller-ul (folder fizic) unde să fie căutat fișierul
* @param string $action Pagina (fișier fizic) unde să fie găsită pagina
* @deprecated
*/
function loadTemplate($controller, $action)
{
trigger_error('Deprecated: function loadTemplate() is deprecated, will be removed in v0.7.5.', E_USER_DEPRECATED);
global $app;
$file = sprintf('%s/%s/%s.phtml', $app['tpldir'], $controller, $action);
if (!file_exists($file)) return;
require_once $file;
} // END function loadTemplate
/**
* Această funcție include fișierul-șablon din $app['tpldir'] în funcție de categorie și pagină.
*
* NOTĂ: începând cu versiunea 0.5.2, această funcție folosește snake_case pentru naming convention.
*
* @param string $controller Controller-ul (folder fizic) unde să fie căutat fișierul
* @param string $action Pagina (fișier fizic) unde să fie găsită pagina
* @since v0.5.2
*/
function load_template($controller, $action)
{
global $app;
$file = sprintf('%s/%s/%s.phtml', $app['tpldir'], $controller, $action);
if (!file_exists($file)) return;
require_once $file;
} // END function load_template
/**
* Această funcție verifică dacă un modul este în whitelist sau nu.
*
* @param string $module_name Numele modulului
* @return bool True dacă există, contrar false.
*/
function module_enabled($module_name)
{
$modules = config('lists.modules');
if (!is_array($modules) && is_bool($modules) && !$modules) {
return false;
}
return in_array($module_name, $modules);
}<file_sep>/tests/test_init_levels.php
<?php
$boot_level = 2;
$level = 4;
$services = [];
$levels = [
0 => ['halt'],
1 => ['logger', 'finder', 'config', 'mailer'],
2 => ['db'],
3 => ['request', 'routes', 'session', 'template'],
4 => ['debug'],
];
if ($level == 0 && $level > 4) {
$services = $levels[$level];
} else if ($level >= 1 && $level <= 4) {
for ($init = 1; $init <= $level; $init++) {
$services[] = $levels[$init];
}
} else {
$services = ['halt'];
}
#xdebug_var_dump($services);
foreach ($services as $boot_level => $services) {
foreach ($services as $service) {
$method = sprintf('init_%s', $service);
#xdebug_var_dump($service, $method);
}
}
$boot_level = 4;
$level = 6;
echo 'boot_level=' . $boot_level . PHP_EOL;
echo 'user_level=' . $level . PHP_EOL;
echo PHP_EOL;
if ($level == 0 || $boot_level == 0) {
$string = sprintf('u=%s;b=%s;c=halt', $level, $boot_level);
} else if (($level >= 1 && $level <= 4) && $level <= $boot_level) {
$string = sprintf('u=%s;b=%s;c=cereale', $level, $boot_level);
} else {
$string = sprintf('u=%s;b=%s;c=nope.', $level, $boot_level);
}
xdebug_var_dump($string);
<file_sep>/hktr/legacy/page.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 05.06.2016 5:31 PM
*/
/**
* Această funcție afișează adresa completă spre o anumită pagină. Are valoarea implicită '/' ca să redirecționeze
* spre pagina principală (ex: metin2sdf.com)
*
* @param string $page Pagina care vrei să fie afișată.
* @return mixed Adresa completă spre acea pagină (http://metin2sdf.com/pagina-mea)
*/
function url($page = '/')
{
global $app;
return $app['routes']->generate($page);
} // END function url
/**
* Verificăm dacă o anumită pagină se află în REQUEST_URI
*
* Această funcție este utilă pentru afișarea unui mesaj în layout-ul template-ului pe o anumită pagină
* De exemplu, pe prima pagină apar statisticile, iar pe alte pagini nu.
*
* @param string $page Numele paginii pe care vrei să apară mesajul. Implicit '/', pentru mesaj DOAR PE
* prima pagină a site-ului.
* @return bool
*/
function in_url($page = '/')
{
global $app;
if ($app['routes']->match($page)) {
$return_value = true;
} else {
$return_value = false;
}
return $return_value;
} // END function in_url
/**
* Această funcție construiește URL-ul în funcție de protocol și hostname.
*
* @return mixed adresa web a hostname-ului (ex: http://metin2sdf.com)
*/
function get_url()
{
if (php_sapi_name() == 'cli') exit;
global $app;
return $app['request']->getUri();
} // END function get_url
/**
* Această funcție returnează calea spre o resursă folosită pe pagina web (css, imagine, javascript...)
*
* Folderul 'assets' trebuie să fie existent fizic în folderul public ($app['rootdir'] . '/web').
* Fiecare fișier cu o anumită extensie trebuie să aibă folder cu extensia respectivă. Adică:
* - assets/css/site.css => css-ul principal
* - assets/png/logo.png => logo-ul site-ului
*
* @param string $file Numele fișierului pe care vrei să-l returnezi
* @param string $category Categoria (folder fizic în assets) în care să fie căutat
* @return string Returnează calea completă (ex: http://metin2sdf.com/assets/css/site.css)
*/
function asset($file, $category)
{
/**
* Baza de lucru (funcția get_url() și folderul assets)
*/
$base = sprintf('%s/assets/', rtrim(get_url()));
return sprintf('%s/%s/%s.%s', rtrim($base), $category, $file, $category);
} // END function asset
/**
* Funcția pentru redirecționare pe o anumită pagină
*
* @param string $route_name numele paginii
* @return \Symfony\Component\HttpFoundation\Response
*/
function redirect($route_name = 'homepage')
{
global $app;
$response = new \Symfony\Component\HttpFoundation\RedirectResponse(302);
$response->setTargetUrl($app['routes']->generate($route_name));
return $response->send();
} // END function redirect
/**
* Această funcție include fișierul-șablon din $app['tpldir'] în funcție de categorie și pagină.
*
* @param string $controller Controller-ul (folder fizic) unde să fie căutat fișierul
* @param string $action Pagina (fișier fizic) unde să fie găsită pagina
* @param int $status Codul statutului HTTP al template-ului. Implicit este 200 HTTP_OK.
* @return \Symfony\Component\HttpFoundation\Response conținutul template-ului.
*/
function loadTemplate($controller, $action, $status = \Symfony\Component\HttpFoundation\Response::HTTP_OK)
{
global $app;
$template = sprintf('%s/%s.html.twig', $controller, $action);
$content = $app['template']->render($template);
return new \Symfony\Component\HttpFoundation\Response($content, $status);
} // END function loadTemplate
/**
* @param string $module_name Numele moduluilui
* @return bool
*/
function module_enabled($module_name)
{
global $app;
return in_array($module_name, $app['config']->get_from_config(null, null, 'modules_list'));
}<file_sep>/src/controller/account_panel.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 11.07.2016 19:13
*/
namespace app\controller;
class account_panel extends hktr92\controller
{
protected $app;
public function __construct($app)
{
$this->app = $app;
$this->model = new app\model\account_panel;
parent::__construct();
}
public function dashboard($user_id)
{
if (!user_is_connected()) {
redirect('panou-cont/conectare');
}
$data = $this->model->get_user_info($user_id);
$account_info = [
'email' => !empty($data['account_email']) ? $data['account_email'] : '-',
'security_code' => !empty($data['security_code']) ? $data['security_code'] : '-',
'create_time' => !empty($data['create_time']) ? $data['create_time'] : '-',
'beta_tester' => !empty($data['beta_tester']) ? ($data['beta_tester'] == 1 ? 'Da' : 'Nu') : '-',
'account_status' => !empty($data['account_status']) ? ($data['account_status'] == 'OK' ? 'Da' : 'Nu') : '-',
'subscriber' => !empty($data['subscriber']) ? ($data['subscriber'] == 1 ? 'Da' : 'Nu') : '-',
'display_name' => !empty($data['display_name']) ? $data['display_name'] : $data['account_name'],
];
$_SESSION['_user_name'] = $account_info['display_name'];
return $this->loadTemplate(__CLASS__, __METHOD__);
}
public function login()
{
/**
* Verificăm dacă utilizatorul este conectat. Dacă da, atunci redirecționăm pe prima pagină a panoului cont.
*/
if (user_is_connected()) {
redirect('panou-cont');
}
/**
* Generăm un token CSRF dacă acesta nu este definit în sesiune.
*/
if (!isset($_SESSION['token'])) $_SESSION['token'] = bin2hex(random_bytes(32));
if(isset($_POST['send'])) {
/**
* Colectăm form-ul în acest array și facem validarea inițială.
* Preluăm valorile din form.
*
* La parolă generăm un hash cu salt-ul din form.
*/
$form_data = [
'utilizator' => fetch_post('user_name') !== false ? fetch_post('user_name') : null,
'parola' => fetch_post('user_pass') !== false ? mysql_password_hash(fetch_post('user_pass')) : null
];
/**
* Continuăm cu validarea form-ului.
*
* În acest loop, verificăm valoarea fiecărui element din $form_data.
*
* Validarea în acest loc poate fi orice: putem verifica dacă valorile sunt nule, dacă parola are o anumită lungime,
* dacă utilizatorul conține caractere din e-mail ș.a.m.d.
*/
foreach ($form_data as $object => $status) {
if (is_null($form_data[$object])) {
$errors[] = sprintf('Câmpul "%s" nu trebuie să fie gol.', ucfirst($object));
}
}
/**
* Aici continuăm cu validarea token-ului CSRF.
*
* Logica este simplă: generăm un hash unic în sesiunea utilizatorului și o punem în $_POST. Dacă hash-ul din sesiune
* este identic cu cel din form, atunci conectarea este validă, iar utilizatorul se poate conecta fără probleme de
* securitate.
*
* Această măsură este importantă întrucât oricine poate să facă o pagină HTML separată care să aibă ca și cod sursă
* la acest script și să salveze datele utilizatorului din form. Acest cod CSRF blochează această tentativă de fraudă.
*
* În acest context, dacă codurile CSRF sunt valide, atunci definim variabilă tip bool care va permite continuarea
* conectării utilizatorului pe site. În caz contrar, va stoca în baza de date informații importante despre
* invaliditatea token-urilor iar variabila tip bool va avea valoare negativă, blocând astfel conectarea pe site.
*/
if (!empty($_POST['token'])) {
if ($_SESSION['token'] === $_POST['token']) {
$csrf_ok = true;
} else {
$query = "INSERT INTO `syncms`.`logs_csrf` (`page`, `locked_token`, `given_token`, `when`, `hostname`, `browser`) VALUES (:page, :token, :page_token, :when, :hostname, :browser)";
$stmt = $app['db']->prepare($query);
$logged = $stmt->execute([
':page' => $_SERVER['REQUEST_URI'],
':token' => $_SESSION['token'],
':page_token' => $_POST['token'],
':when' => date("d-m-Y H:i:s"),
':hostname' => get_client_ip(),
':browser' => $_SERVER['HTTP_USER_AGENT'],
]);
$errors[] = sprintf("Codul unic este necorespunzător.");
$csrf_ok = false;
}
} else {
$blocked = true;
}
/**
* Verificăm dacă utilizatorul este conectat pe site.
*
* Tot în acest context, putem verifica dacă conexiunea la baza de date este activă.
*/
$check = $this->model->check_username_exists($form_data['username']);
$api_error = false;
if ($check <> 1) {
$api_error = true;
}
/**
* Dacă totul este în regulă, atunci putem continua cu conectarea pe site.
*
* Pentru securitate sporită, folosim prepared statements. Acest lucru împiedică folosirea directă a variabilelor
* în query și adaugă un nou plus în prevenirea sql injection.
*/
if ($csrf_ok && empty($errors) && !$api_error && isset($blocked) && $blocked) {
$user_data = $this->model->get_login_data($form_data['utilizator'], $form_data['parola']);
/**
* Aici setăm câteva sesiuni.
*
* Setăm DOAR:
* - user_logged_in (bool) true
* - _user_id (int) ID-ul utilizatorului
* - _user_status (string) statutul utilizatorului
* - user_admin (bool) true
*/
$_SESSION['user_logged_in'] = true;
$_SESSION['_user_id'] = $user_data['id'];
$_SESSION['_user_status'] = $user_data['status'];
if ($user_data['is_admin'] == 1) {
$_SESSION['user_admin'] = true;
}
} else {
$errors[] = "Conectarea pe site nu a putut fi continuată.";
}
}
$current_page = $_SERVER['REQUEST_URI'];
}
}<file_sep>/hktr/legacy/security.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 05.06.2016 18:00
*/
/**
* Această funcție securizează un string. Mai exact, aplică filtre pentru „curățare”.
*
* Putem folosi mysqli_real_escape_string(), însă se poate folosi DOAR în context cu cod SQL și nu poate fi apelată
* dacă extensia mysqli este inexistentă.
*
* Din fericire, există alternative, iar filter_var este cel mai eficient în acest context. Are numeroase tipuri de
* filtre definite.
*
* Mai multe informații aveți aici: http://php.net/manual/ro/filter.filters.sanitize.php
*
* @param string $var Variabila care este predispusă la vulnerabilități
* @return string Variabila curățată de orice rele.
*/
function sanitize($var)
{
/**
* Această funcție NU permite array-urile, deci aici sunt oprite.
*/
if (is_array($var)) return null;
return filter_var($var, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
} // END function sanitize
/**
* Această funcție este o alternativă sigură pentru $_POST.
*
* Deoarece $_POST este predispus la vulnerabilități, este necesară filtrarea valorii fiecărui index din array.
* Deoarece în $_POST nu există cod SQL propriu-zis, putem folosi funcția sanitize(), definită mai sus. Astfel,
* curățarea $_POST['username'] se poate face astfel: sanitize($_POST['username']).
*
* Această metodă este cam nesigură, întrucât se folosește un singur tip de filtru în acea funcție. Desigur, se poate
* extinde, dar asta ar însemna rescrierea codului.
*
* Așadar, o soluție mai practică o reprezintă funcția de mai jos. Apelează funcția filter_input pentru INPUT_POST,
* preia $name și aplică filtrul $filter. Mai practic și mai sigur.
*
* @param string $name Numele input-ului preluat din $_POST (ex: username)
* @param string $filter_type Tipul de filtru. implicit este 'string'.
* @return mixed Valori multiple.
* - (string) valoarea $_POST[$name] filtrat
* - (null) dacă valoarea este inexistentă
* - (false) dacă aplicarea filtrului a eșuat
*/
function fetch_post($name, $filter_type = 'string')
{
global $app;
$parameter_bag = $app['request']->request;
switch ($filter_type) {
case 'email':
$filter = FILTER_SANITIZE_EMAIL;
break;
case 'number':
$filter = FILTER_SANITIZE_NUMBER_INT;
break;
case 'float':
$filter = FILTER_SANITIZE_NUMBER_FLOAT;
break;
case 'string':
$filter = FILTER_SANITIZE_FULL_SPECIAL_CHARS;
break;
default:
$filter = FILTER_SANITIZE_FULL_SPECIAL_CHARS;
break;
}
if ($parameter_bag->has($name)) {
$return_value = $parameter_bag->filter($parameter_bag->get($name), null, $filter);
} else {
$return_value = false;
}
return $return_value;
} // END function fetch_post
/**
* Această funcție este o alternativă pentru $_GET
*
* Este apelată aceeași funcție, filter_input, dar de data asta pentru INPUT_GET, preia $name și aplică filtrul special
* pentru link-uri FILTER_SANITIZE_URL.
*
* @param string $name Numele input-ului preluat din $_GET
* @return mixed (string) valoarea $_GET[$name]
* (null) pentru valoare inexistentă
* (false) pentru eșecul aplicării filtrului
*/
function fetch_get($name)
{
global $app;
$parameter_bag = $app['request']->query;
if ($parameter_bag->has($name)) {
$return_value = $parameter_bag->get($name);
} else {
$return_value = false;
}
return $return_value;
} // END function fetch_get
/**
* Această funcție preia adresa IP reală a clientului.
*
* @return mixed Adresa IP al clientului
*/
function get_ip_address() {
global $app;
return $app['request']->getClientIp();
} // END function get_ip_address
/**
* Verificăm dacă adresa IP este validă și nu este IP dintr-o rețea privată.
*
* @param string $ip Adresa IP pentru verificare
* @return bool Validitatea adresei IP
*/
function validate_ip($ip)
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return false;
}
return true;
} // END function validate_ip
/**
* MySQL "PASSWORD()" AKA MySQLSHA1 HASH FUNCTION
* Aceasta este funcția pentru password hash folosit în MySQL 4.1.1+
*
* By Rev. <NAME> 10/9/2009 9:36:20 AM
*
* @param string $input Parola pentru calculare
* @param bool $hex Dacă se folosește cod hex sau nu
* @return string Returnează parola cu hash
*/
function mysql_password_hash($input, $hex = true)
{
$sha1_stage1 = sha1($input, true);
$output = sha1($sha1_stage1, !$hex);
return '*'.strtoupper($output);
} //END function mysql_password_hash
/**
* Calculează fiecare pereche hexadecimală în bit-ul corespunzător.
* Similar cu funcția hex2octet din mysql
*
* By Rev. <NAME> 10/9/2009 9:36:20 AM
*
* @param string $hex Codul hex
* @return string Codul binar
*/
function hex_hash_to_bin($hex)
{
$bin = "";
$len = strlen($hex);
for ($i = 0; $i < $len; $i += 2) {
$byte_hex = substr($hex, $i, 2);
$byte_dec = hexdec($byte_hex);
$byte_char = chr($byte_dec);
$bin .= $byte_char;
}
return $bin;
} //END function hex_hash_to_bin
/**
* Această funcție preia un obiect fix sau un array din $app['config'].
*
* Este scris pentru facilitarea accesării unui item din configurație. Din păcate, această funcție are o adâncime
* maximă de 3 sub-arrays, adică:
*
* $app['config'][$branch][$category][$item]
*
* @param string|null $category Categoria dintr-un anumit branch, ex: 'server' ($app['config']['master']['server'])
* @param string|null $item Un obiect dintr-o categorie din branch-ul respectiv
* @param string $branch Branch-ul din care face parte configurația. Coincide cu numele fișierului configurație
* @return array|bool|mixed (array) dacă $item, $category și $branch sunt null, sunt returnate ca array.
* (bool) false la eșec
* (mixed) poate fi orice tip de date suportat de Yaml.
*/
function get_from_config($category = null, $item = null, $branch = 'master')
{
global $async2;
$config = $async2->app['config'];
return $config->get_from_config($category, $item, $branch);
} // END function get_from_config
<file_sep>/hktr/exception/SmartConfigGetException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 01.08.2016 14:29
*/
namespace hktr92\exception;
class SmartConfigGetException extends \Exception
{
}<file_sep>/app/routes.php
<?php
/**
* Acest fișier conține toate routes-urile vechi
*
* @package m2cms_skel
* @author hacktor
* @date 22.07.2016 20:24
*/
switch (fetch_get('r')) {
case 'clasament':
load_template('ranking', 'ranking');
break;
case 'clasament/jucători':
load_template('ranking', 'ranking_players');
break;
case 'clasament/bresle':
load_template('ranking', 'ranking_guilds');
break;
case 'descărcare':
load_template('download', 'download');
break;
case 'panou-cont':
load_template('account_panel', 'dashboard');
break;
case 'panou-cont/inregistrare':
load_template('account_panel', 'register');
break;
case 'panou-cont/conectare':
load_template('account_panel', 'login');
break;
case 'panou-cont/schimbă-datele':
load_template('account_panel', 'update_info');
break;
case 'panou-cont/deconectare':
load_template('account_panel', 'logout');
break;
case 'panou-jucator':
load_template('player_panel', 'dashboard');
break;
case 'panou-jucator/caracterele-mele':
load_template('player_panel', 'my_characters');
break;
case 'panou-jucator/breasla':
load_template('player_panel', 'my_guild');
break;
case 'panou-administrare':
load_template('admin_panel', 'dashboard');
break;
case 'panou-administrare/descărcări':
load_template('admin_panel', 'downloads');
break;
default:
load_template('site', 'home');
break;
}<file_sep>/hktr/config.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 20.07.2016 18:33
*/
namespace hktr92;
use hktr92\exception\InvalidConfigBranchException;
use hktr92\exception\InvalidConfigCategoryException;
use hktr92\exception\InvalidConfigItemException;
use hktr92\exception\SmartConfigGetException;
use hktr92\exception\InvalidConfigurationException;
use Symfony\Component\Yaml\Yaml;
class config
{
private $config = [];
private $yaml;
public function __construct(array $configuration)
{
$this->yaml = new Yaml();
foreach ($configuration as $branch => $path)
{
$this->parse_yaml($branch, $path);
}
}
private function parse_yaml($branch, $yaml_file)
{
$this->config[$branch] = $this->yaml->parse(file_get_contents($yaml_file));
}
private function check_config()
{
return is_array($this->config);
}
private function check_branch($branch)
{
return (array_key_exists($branch, $this->config));
}
private function check_category($branch, $category)
{
return (array_key_exists($category, $this->get_branch($branch)));
}
private function check_item($branch, $category, $item)
{
return (array_key_exists($item, $this->get_category($branch, $category)));
}
private function get_branch($branch)
{
return $this->config[$branch];
}
private function get_category($branch, $category)
{
return $this->config[$branch][$category];
}
private function get_item($branch, $category, $item)
{
return $this->config[$branch][$category][$item];
}
public function get_from_config($branch, $category = null, $item = null)
{
if (!$this->check_config()) {
throw new InvalidConfigurationException('The configuration is invalid.');
}
if (!$this->check_branch($branch)) {
throw new InvalidConfigBranchException(sprintf('The "%s" branch is non-existent.', $branch));
}
if (!$this->check_category($branch, $category)) {
throw new InvalidConfigCategoryException(sprintf(
'The "%s" category (found in "%s" branch) is non-existent.',
$category,
$branch
));
}
if (!$this->check_item($branch, $category, $item)) {
throw new InvalidConfigItemException(sprintf(
'The "%s" item (parent of "%s" category, found in "%s" branch) is non-existent.',
$item,
$category,
$branch
));
}
if (is_null($category) && is_null($item)) {
$return_value = $this->get_branch($branch);
} else if (!is_null($category) && is_null($item)) {
$return_value = $this->get_category($branch, $category);
} else if (!is_null($category) && !is_null($item)) {
$return_value = $this->get_item($branch, $category, $item);
} else {
throw new SmartConfigGetException('Nothing to get from config.');
}
return $return_value;
}
}
<file_sep>/hktr/boot.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 28.07.2016 23:10
*/
namespace hktr92;
use hktr92\exception\AppNotBootableException;
/**
* Class boot
* @package hktr92\boot
*
* Această clasă trebuie să se ocupe de nivelurile de init ale aplicației.
* Similar cu linux init: http://www.tldp.org/LDP/sag/html/run-levels-intro.html
*
* Nivelurile de init sunt prezentate în tabelul de mai jos:
* NUME_INIT VALOARE EXPLICATIE
* - INIT_HALT 0 Acest nivel de init, teoretic, trebuie să oprească aplicația web.
* - INIT_BASIC 1 Acest nivel de init trebuie să inițieze funcțiile de sistem (Finder, Mailer, Config, Logger)
* - INIT_DB 2 Acest nivel de init trebuie să inițieze contactul cu baza de date. (Doctrine)
* - INIT_WEB 3 Acest nivel de init inițiază interfața web (Request, Routes, Templating, Session)
* - INIT_DEBUG 4 Acest nivel de init trebuie să activeze toate de mai sus, plus debug.
*/
class boot
{
private $async2;
private $kernel;
private $services;
private $services_whitelist;
private $boot_level;
private $boot_services;
const INIT_HALT = 0;
const INIT_BASIC = 1;
const INIT_DB = 2;
const INIT_WEB = 3;
const INIT_DEBUG = 4;
public function __construct(async2 $async2)
{
$this->kernel = new kernel();
$this->kernel->method_start(__METHOD__);
$this->kernel->log('probing app container as instance of async2 class...');
if (($async2 instanceof async2) == false) {
$this->kernel->log('app container is not instance of async2 class, halting.');
throw new AppNotBootableException('The application is non-bootable.');
}
$this->kernel->log('mounting container into boot class...');
$this->async2 = $async2;
$this->kernel->log('initializing empty services container into boot class...');
$this->services = [];
$this->kernel->log('fetching all available services by level');
$this->fetch_levels();
$this->kernel->method_end();
}
public function init($level)
{
$this->kernel->method_start(__METHOD__);
$this->kernel->log(sprintf('app init level = %d', $level));
$this->boot_level = $level;
if ($level == self::INIT_HALT && $level > self::INIT_DEBUG) {
$this->services[] = $this->services_whitelist[$level];
} else if ($level >= self::INIT_BASIC && $level <= self::INIT_DEBUG) {
for ($init = 1; $init <= $level; $init++) {
$this->services[] = $this->services_whitelist[$init];
}
} else {
$this->services[] = $this->services_whitelist[self::INIT_HALT];
}
$this->kernel->log('calling services...');
$this->call_services();
$this->kernel->method_end();
}
private function call_services()
{
$this->kernel->method_start(__METHOD__);
$this->kernel->log('initializing services:');
foreach ($this->services as $boot_level => $services) {
foreach ($services as $service) {
$method = sprintf('init_%s', $service);
$this->boot_services[] = $service;
$this->kernel->log(sprintf("\t[+] %d:%s", ($boot_level+1), $method));
call_user_func([$this->async2, $method]);
}
}
$this->kernel->log('init completed.');
$this->kernel->method_end();
}
private function fetch_levels()
{
$this->kernel->method_start(__METHOD__);
$this->kernel->log('TODO: whitelist services into kernel.yml file.');
$this->services_whitelist = [
0 => ['halt'],
1 => ['logger', 'finder', 'config', 'mailer'],
2 => ['db'],
3 => ['request', 'routes', 'session', 'template'],
4 => ['debug'],
];
$this->kernel->method_end();
}
public function is_level($level)
{
$this->kernel->method_start(__METHOD__);
$this->kernel->log('checking if init_level=' . $level . ' is in range of boot_level=' . $this->boot_level);
if ($level == self::INIT_HALT || $this->boot_level == self::INIT_HALT) {
$this->kernel->log('the children is grounded and he can not eat cereals.');
$return_value = true;
} else if (
($level >= self::INIT_BASIC && $level <= self::INIT_DEBUG) &&
$level <= $this->boot_level
) {
$this->kernel->log('the children can happily eat cereals.');
$return_value = true;
} else {
$this->kernel->log('the children ate too much cereals and now he is sick.');
$return_value = false;
}
$this->kernel->log('return value: ' . $this->kernel->bool_to_string($return_value));
$this->kernel->method_end();
return $return_value;
}
function is_service($service_name)
{
return in_array($service_name, $this->boot_services);
}
public function emergency_log($message, $level = kernel::ERROR)
{
$this->kernel->method_start(__METHOD__);
$this->kernel->log('===dumping log into kernel logging system:===');
$this->kernel->log($message, $level);
$this->kernel->log('===kernel log dump complete===');
$this->kernel->method_end();
}
}
<file_sep>/app/safelocker/tables/download.sql
CREATE TABLE IF NOT EXISTS `syncms`.`download` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
`description` TEXT NULL,
`version` DOUBLE UNSIGNED NOT NULL,
`channel` ENUM('dev', 'stable', 'testing', 'unknown') NOT NULL DEFAULT 'unknown',
`added_at` DATETIME NULL,
`updated_at` DATETIME NULL,
`link` VARCHAR(45) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COMMENT = 'Tabelul care conține informații despre descărcarea client' /* comment truncated */ /*-ului de Metin2.*/<file_sep>/hktr/exception/AppHaltedException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 29.07.2016 01:32
*/
namespace hktr92\exception;
class AppHaltedException extends \Exception
{
}<file_sep>/hktr/exception/InvalidConfigBranchException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 20.07.2016 20:07
*/
namespace hktr92\exception;
class InvalidConfigBranchException extends \Exception { }<file_sep>/hktr/exception/InvalidArrayException.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 01.08.2016 14:30
*/
namespace hktr92\exception;
class InvalidArrayException extends \Exception
{
}<file_sep>/async2-ng.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 6/5/16 5:23 PM
* @since 0.2
*/
if (PHP_MAJOR_VERSION < 5 || PHP_MAJOR_VERSION > 5) {
echo sprintf("PHP %d instalat, PHP 5 necesar.", PHP_VERSION);
exit;
}
if (PHP_MINOR_VERSION < 5 || PHP_MINOR_VERSION > 6) {
echo sprintf("PHP %d instalat, PHP 5.5 sau 5.6 necesar.", PHP_VERSION);
exit;
}
(preg_match("/async2ng\.[a-zA-Z0-9]/i", $_SERVER['PHP_SELF'])) and exit;
define ('dev', true);
require_once __DIR__.'/vendor/autoload.php';
$async2 = new hktr92\async2(__DIR__, dev);
$boot = new hktr92\boot($async2);
$app = $async2->get_app();
$boot_level = (defined('dev') && is_bool(dev) && dev) ? hktr92\boot::INIT_DEBUG : hktr92\boot::INIT_WEB;
$boot->init($boot_level);
try {
foreach(['security', 'page', 'user'] as $file) require_once sprintf('%s/hktr/legacy/%s.php', __DIR__, $file);
if ($boot->is_service('db')) {
$app['registered_accounts'] = (
$app['db']->query("SELECT count(`id`) FROM `account`.`account`")->fetchColumn() -
$app['config']->get_from_config('server', 'staff_accounts')
);
} else {
$app['registered_accounts'] = '?';
}
} catch(\Exception $e) {
$error_message = sprintf("Exception: %s", $e->getMessage());
if ($boot->is_service('logger')) {
$app['logger']->error($error_message);
} else {
$boot->emergency_log($error_message);
}
}<file_sep>/async2.php
<?php
/**
* MIT License
*
* Copyright (c) 2016 hacktor
*
* 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.
*/
/**
* @package metin2sdf_cms
* @author hacktor
* @date 6/5/16 5:23 PM
* @version 0.1
*/
/**
* Verificăm dacă versiunea majoră PHP este mai mică de 5.
* Dacă da, afișam mesaj de eroare și ieșim din aplicație.
*
* Verificăm dacă versiunea minoră PHP este mai mică de 5.
* Dacă da, afișăm mesaj de eroare și ieșim din aplicație.
*
* Acest schelet necesită utilizarea versiunii PHP 5.5 sau mai nou.
*/
if (PHP_MAJOR_VERSION < 5) {
echo sprintf("PHP %d instalat, PHP 5 necesar.", PHP_VERSION);
exit;
}
if (PHP_MINOR_VERSION < 5) {
echo sprintf("PHP %d instalat, PHP 5.5 necesar.", PHP_VERSION);
exit;
}
/**
* Detectăm dacă se accesează direct acest fișier.
* Dacă da, atunci ieșim din aplicație.
*/
(preg_match("/async2\.[a-zA-Z0-9]/i", $_SERVER['PHP_SELF'])) and exit;
/**
* Definirea modului de lucru
*
* Valoarea implicită este `false` pentru producție, `true` pentru dezvoltare.
* NOTE: nu defini `true` dacă ești pe server de producție!
*/
define ('dev', true);
/**
* Definim numele sesiunii și o inițiem.
* A NU SE MODIFICA NUMELE SESIUNII!!!
*/
session_name("async00");
session_start();
/**
* Includem autoloader-ul pentru librării
* Includem funcțiile importante ale site-ului.
*/
require_once __DIR__.'/vendor/autoload.php';
foreach(["security", "page", "user"] as $file) require_once sprintf("%s/app/functions/%s.php", __DIR__, $file);
/**
* Verificăm dacă modul dezvoltator este activ
* Pe urmă inițiem clasa Debug și ErrorHandler ale Symfony
*/
if (dev) {
Symfony\Component\Debug\Debug::enable();
Symfony\Component\Debug\ErrorHandler::register();
}
try {
/**
* Calea spre directorul rădăcină al proiectului (ex: /var/www/metin2sdf.com)
* De asemenea, am definit calea spre template-uri (/var/www/metin2sdf.com/app/template)
*/
$app['rootdir'] = __DIR__;
$app['tpldir'] = $app['rootdir'] . '/app/template';
/**
* Versiunea site-ului.
* A NU SE MODIFICA! Altfel nu veți putea primi actualizări noi.
*/
$app['version'] = rtrim(file_get_contents(__DIR__.'/app/safelocker/async2.ver'));
/**
* Citim configurațiile site-ului.
* Pentru human-friendly, folosim Yaml.
*
* Stocăm totul în $app['config'][$branch], unde $branch este numele fișierului fără extensie.
*/
$app['config'] = (new Symfony\Component\Yaml\Parser)->parse(file_get_contents($app['rootdir'] . '/app/config/master.yml'));
/**
* Realizăm conexiunea la baza de date MySQL (MariaDB sau alt replacement)
*/
try {
$db_branch = 'db';
$app['db'] = new \PDO(
sprintf('mysql:host=%s;dbname=%s;charset=utf8', config($db_branch . '.hostname'), config($db_branch . '.database')),
config($db_branch . '.username'),
config($db_branch . '.password')
);
unset($db_branch);
} catch (\PDOException $e) {
load_template('splash', 'maintenance');
/**
* Salvăm eroarea în fișierul de erori.
*/
error_log($e->getMessage() . PHP_EOL, 3, __DIR__.'/logs/php_error.log');
exit;
}
/**
* Setăm niște parametrii speciali pentru PDO.
* - ATTR_DEFAULT_FETCH_MODE => setează să se preia totul sub forma unui associative array (['nume-coloana' => 'valoare'])
* - ATTR_EMULATE_PREPARES => măsură de securitate. lăsăm driver-ul nativ să se ocupe de query.
* setarea pe `true` va valida query-urile multiple în prepare.
*/
$app['db']->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$app['db']->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/**
* Aici calculăm numărul de conturi înregistrate minus cele ale staff-ului.
*/
$app['registered_accounts'] = ($app['db']->query("SELECT count(`id`) FROM `account`.`account`")->fetchColumn()) -
config('server.staff');
} catch (\Exception $e) {
/**
* În cazul în care ceva eșuează în blocul try, afișam un template-eroare.
*/
load_template('splash', 'error');
/**
* Salvăm eroarea în fișierul de erori.
*/
error_log($e->getMessage() . PHP_EOL, 3, __DIR__.'/logs/php_error.log');
exit;
}<file_sep>/hktr/kernel.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 29.07.2016 19:23
*/
namespace hktr92;
class kernel
{
public $method_name;
const INFO = 'nfo';
const WARNING = 'wrn';
const ERROR = 'err';
const DEBUG = 'dbg';
public function __construct() { }
public function set_method($method_name)
{
$this->method_name = $method_name;
}
public function log($message, $level = self::INFO)
{
$date = (new \DateTime('now', new \DateTimeZone(date_default_timezone_get())))->format('d.m.Y_H:i:s');
$hostname = gethostname();
$source = $this->method_name;
$kernel_message = sprintf("[%s] @%s <%s>: [%-30s] %s%s", $date, $hostname, $level, $source, $message, PHP_EOL);
$output_file = sprintf('%s/logs/kernel.log', dirname(__DIR__));
$handler = fopen($output_file, 'a+');
fwrite($handler, $kernel_message);
fclose($handler);
}
public function method_start($method = __METHOD__)
{
$this->set_method($method);
$this->log('==============================================');
$this->log('method::start()');
}
public function method_end()
{
$this->log('method::end()');
$this->log('==============================================');
}
public function bool_to_string($bool_value)
{
if (!is_bool($bool_value))
{
throw new \Exception(sprintf('The given value is %s, bool required.', gettype($bool_value)));
}
return $bool_value ? 'true' : 'false';
}
}<file_sep>/app/safelocker/tables/_database.sql
CREATE DATABASE `syncms`;<file_sep>/hktr/configng.php
<?php
/**
* @package m2cms_skel
* @author hacktor
* @date 02.08.2016 20:26
*/
namespace hktr92;
use Symfony\Component\Yaml\Yaml;
class config
{
private $config = [];
private $yaml;
public function __construct(array $configuration)
{
$this->yaml = new Yaml();
foreach ($configuration as $branch => $path)
{
$this->parse_yaml($path);
}
}
private function parse_yaml($yaml_file)
{
$config[] = $this->yaml->parse(file_get_contents($yaml_file));
foreach ($config as $key => $value)
{
array_merge($this->config, $value);
}
}
} | 608d13d0c735aeda13c61224bae9868994c11e12 | [
"Markdown",
"SQL",
"PHP"
] | 30 | PHP | hktr92/m2cms-skeleton | 1b8122efad7e458629f4e837d2b2b211ae73251c | f6993c6658bccb5aa4f2426af7b1a51d34e93674 |
refs/heads/master | <file_sep>//
// MemeGridCell.swift
// MemeApp
//
// Created by <NAME> on 5/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class MemeListCell: UITableViewCell {
@IBOutlet weak var thumbnailImage: UIImageView!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
// I didn't find this as clean as you made it sound 🙁
func setupCellWith(meme:Meme, row: Int) {
thumbnailImage.image = meme.generatedMeme
contentLabel.text = "Meme \(row + 1)"
dateLabel.text = (UIApplication.shared.delegate as! AppDelegate).getReadableDate(dateToConvert: meme.creationTime)
}
}
<file_sep>//
// Model.swift
// MemeApp
//
// Created by <NAME> on 4/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
struct Meme {
var joke: String
var punchLine: String
var originalImage: UIImage
var generatedMeme: UIImage
var creationTime: Date
}
<file_sep>//
// ListController.swift
// MemeApp
//
// Created by <NAME> on 5/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ListController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var emptyPlaceholderView: UIView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBOutlet var memeList: UITableView!
var singleton = (UIApplication.shared.delegate as! AppDelegate)
override func viewDidLoad() {
super.viewDidLoad()
title = "Meme list"
reloadView(hardReload: true)
}
override func viewDidAppear(_ animated: Bool) {
reloadView()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return singleton.memes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MemeListThumbnailCell", for: indexPath) as! MemeListCell
cell.setupCellWith(meme: singleton.memes[indexPath.row], row: indexPath.row)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showMemeFromList", sender: singleton.memes[indexPath.row].generatedMeme)
tableView.cellForRow(at: indexPath)?.isSelected = false
}
func reloadView(hardReload: Bool = false) {
loadingIndicator.startAnimating()
if hardReload {
singleton.refreshPhotoCarret()
}
emptyPlaceholderView.isHidden = !singleton.memes.isEmpty
memeList.isHidden = singleton.memes.isEmpty
memeList.reloadData()
loadingIndicator.stopAnimating()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
(segue.destination as! FullViewController).memeImage = sender as? UIImage
}
@IBAction func addMemeAction(_ sender: Any) {
let addition = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "createMemeView") as! MainController
let navController = UINavigationController(rootViewController: addition)
present(navController, animated:true, completion: nil)
}
}
<file_sep>//
// MainController.swift
// MemeApp
//
// Created by <NAME> on 2/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import Photos
// Moved out to extensions, i don't know why the compiler complained before.
class MainController: UIViewController {
@IBOutlet weak var photoSourceHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var bottomTextField: UITextField!
@IBOutlet weak var topTextField: UITextField!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var deleteButton: UIBarButtonItem!
@IBOutlet weak var photoButton: UIBarButtonItem!
@IBOutlet weak var albumButton: UIBarButtonItem!
@IBOutlet weak var memeImage: UIImageView!
@IBOutlet weak var placeholderTextView: UITextView!
let photoPicker = UIImagePickerController()
var statusBarHidden = false
override func viewDidLoad() {
super.viewDidLoad()
memeImage.autoresizingMask = UIViewAutoresizing.flexibleHeight
photoPicker.delegate = self
photoButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
configureTextField(textField: topTextField, text: "top", placeholder: "Add clever joke")
configureTextField(textField: bottomTextField, text: "bottom", placeholder: "And punch line")
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
print("Low memory in device")
}
//# Public helpers
func showAlert(alertMessage: String, alertTitle: String = "Ups!") {
let lowerCaseAlert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
lowerCaseAlert.addAction(UIAlertAction(title: "Ok", style: .cancel, handler: nil))
present(lowerCaseAlert, animated: true, completion: nil)
}
override var prefersStatusBarHidden: Bool {
return statusBarHidden
}
//# Private helper methods
func configureTextField(textField: UITextField, text: String, placeholder: String) {
let attributes = [NSStrokeWidthAttributeName: -4.0,
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white] as [String : Any];
textField.attributedText = NSAttributedString(string: text.uppercased(), attributes: attributes)
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attributes)
}
private func getImageFromSource(isCameraImage: Bool) {
photoPicker.sourceType = isCameraImage ? .camera : .photoLibrary
present(photoPicker, animated: true, completion: nil)
}
private func setCanvasForCapture(barsHidden: Bool) {
navigationController?.setNavigationBarHidden(barsHidden, animated: false)
photoSourceHeightConstraint.constant = barsHidden ? 0 : 44
// Hiding status bar during capture to ensure full image clarity
statusBarHidden = barsHidden
setNeedsStatusBarAppearanceUpdate()
}
private func generateMemedImage() -> UIImage {
setCanvasForCapture(barsHidden: true)
UIGraphicsBeginImageContext(view.frame.size)
view.drawHierarchy(in: view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
setCanvasForCapture(barsHidden: false)
return memedImage
}
private func getMemeAlbum(albumName: String) -> PHAssetCollection? {
let fetchOptions = PHFetchOptions() // Search parameters
fetchOptions.fetchLimit = 1
fetchOptions.predicate = NSPredicate(format: "title = %@", "Meme Album") // Album name
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: fetchOptions)
return collection.firstObject
}
private func setStorageEnvironment() -> PHAssetCollection! {
let albumName = (UIApplication.shared.delegate as! AppDelegate).memeAlbumName
var generatedCollection = getMemeAlbum(albumName: albumName) // Photos app "pointer"
// If already created, obtain reference
if generatedCollection != nil {
return generatedCollection
}
// Otherwise, let's create the album
do {
try PHPhotoLibrary.shared().performChangesAndWait {
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: albumName)
}
// Once created, obtain that reference
generatedCollection = getMemeAlbum(albumName: albumName)
} catch {
print(error.localizedDescription)
return nil
}
// Return found/generated meme album
return generatedCollection
}
private func saveInAlbum(memeAlbum: PHAssetCollection, producedMeme: UIImage) {
PHPhotoLibrary.shared().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAsset(from: producedMeme)
assetRequest.creationDate = Date()
let assetPlaceholder = assetRequest.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: memeAlbum)
let enumeration: NSArray = [assetPlaceholder!]
albumChangeRequest!.addAssets(enumeration)
}, completionHandler: { success, error in
print(error == nil ? "added image to album" : error!)
})
}
//# Public helpers methods
func enableActions(enable: Bool, removal: Bool = false) {
UIView.animate(withDuration: 0.35, animations: {
self.shareButton.isEnabled = enable
self.deleteButton.isEnabled = enable
self.placeholderTextView.alpha = enable ? 0 : 1
self.memeImage.alpha = enable ? 1 : 0
self.topTextField.alpha = enable ? 1 : 0
self.bottomTextField.alpha = enable ? 1 : 0
}, completion: { _ in
if removal {
self.memeImage.image = nil
}
})
}
//# Keyboard events and handling
func keyboardWillShow(_ notification:Notification) {
if bottomTextField.isFirstResponder {
view.frame.origin.y -= getKeyboardHeight(notification)
navigationController?.toolbar.isHidden = true
}
}
func keyboardWillHide(_ notification:Notification) {
if view.frame.origin.y < 0 {
view.frame.origin.y += getKeyboardHeight(notification)
navigationController?.toolbar.isHidden = false
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
//# Button actions
@IBAction func shareMemeAction(_ sender: Any) {
let producedMeme = generateMemedImage()
let resultingMeme = Meme(joke: topTextField.text!, punchLine: bottomTextField.text!, originalImage: memeImage.image!, generatedMeme: producedMeme, creationTime: Date())
if let environment = setStorageEnvironment() {
let activityViewController = UIActivityViewController(activityItems: [resultingMeme.generatedMeme], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = view
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.addToReadingList, UIActivityType.openInIBooks ]
present(activityViewController, animated: true, completion: nil)
activityViewController.completionWithItemsHandler = { [weak self]
(activityType, completed, returnedItems, error) in
if completed {
(UIApplication.shared.delegate as! AppDelegate).memes.append(resultingMeme)
self?.saveInAlbum(memeAlbum: environment, producedMeme: (self?.generateMemedImage())!)
}
}
} else {
showAlert(alertMessage: "There was an error saving your picture")
}
}
@IBAction func deleteMemeAction(_ sender: Any) {
enableActions(enable: false, removal: true)
}
@IBAction func takePhotoAction(_ sender: Any) {
getImageFromSource(isCameraImage: true)
}
@IBAction func pickPhotoAction(_ sender: Any) {
getImageFromSource(isCameraImage: false)
}
@IBAction func returnAction(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
//# Textfield delegate methods
extension MainController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
if (textField.isEqual(topTextField) && textField.text == "TOP") || (textField.isEqual(bottomTextField) && textField.text == "BOTTOM") {
textField.text = ""
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if (textField.isEqual(topTextField) && textField.text == "") {
textField.text = "TOP"
} else if textField.isEqual(bottomTextField) && textField.text == "" {
textField.text = "BOTTOM"
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return view.endEditing(true)
}
//# Forcing only lowercase characters and no more than 30
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = textField.text else { return true }
if let _ = string.rangeOfCharacter(from: NSCharacterSet.lowercaseLetters) {
showAlert(alertMessage: "Only UPPER CASE letters for greater impact!")
return false
}
let newLength = text.characters.count + string.characters.count - range.length
return newLength <= 30
}
}
extension MainController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//# Picker delegates
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage {
memeImage.image = image
enableActions(enable: true)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
<file_sep># MemeApp
Take pictures and overlays text to make memes out of friends, family, or pets. Also allows sharing with others via social media or email, and viewing past memes in a table or collection view.
## Getting Started
All that's required for this project to run is Xcode 8.3.3+
## Contribute
Feel free to fork the code, add some interesting new feature and make the proper pull request. I'll be more than happy to review it.
## Credits
iOS developer [<NAME>](https://www.linkedin.com/in/mauriciochirino/)<file_sep>//
// AppDelegate.swift
// MemeApp
//
// Created by <NAME> on 2/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import Photos
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let memeAlbumName = "Meme Album"
var window: UIWindow?
var memes = [Meme]()
var assetCollection: PHAssetCollection!
lazy var formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = "MMM/dd/YY hh:mm a"
return formatter
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func refreshPhotoCarret() {
let fetchOptions = PHFetchOptions()
fetchOptions.fetchLimit = 1
fetchOptions.predicate = NSPredicate(format: "title = %@", memeAlbumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .albumRegular, options: fetchOptions)
if let first_Obj:AnyObject = collection.firstObject{
assetCollection = first_Obj as! PHAssetCollection
let assets : PHFetchResult = PHAsset.fetchAssets(in: assetCollection, options: nil)
let imageManager = PHCachingImageManager()
memes.removeAll()
assets.enumerateObjects({ [weak self] (object: AnyObject!, count: Int,
stop: UnsafeMutablePointer<ObjCBool>) in
if object is PHAsset {
let asset = object as! PHAsset
let imageSize = CGSize(width: asset.pixelWidth, height: asset.pixelHeight)
let options = PHImageRequestOptions()
options.deliveryMode = .fastFormat
options.isSynchronous = true
imageManager.requestImage(for: asset, targetSize: imageSize, contentMode: .aspectFit, options: options, resultHandler: {
(image: UIImage?, info: [AnyHashable : Any]?) in
self?.memes.append(Meme(joke: "", punchLine: "", originalImage: image!, generatedMeme: image!, creationTime: asset.creationDate!))
})
}
})
}
}
func getReadableDate(dateToConvert: Date?) -> String {
return dateToConvert != nil ? formatter.string(from: dateToConvert!) : "Unknown"
}
}
<file_sep>//
// GridController.swift
// MemeApp
//
// Created by <NAME> on 6/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class GridController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var emptyPlaceholderView: UIView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var memeGrid: UICollectionView!
var singleton = (UIApplication.shared.delegate as! AppDelegate)
override func viewDidLoad() {
super.viewDidLoad()
title = "Meme grid"
reloadView()
}
override func viewDidAppear(_ animated: Bool) {
reloadView()
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return singleton.memes.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GridCell", for: indexPath) as! MemeGridCell
cell.setupCellWith(meme: singleton.memes[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: "showMemeFromGrid", sender: singleton.memes[indexPath.row].generatedMeme)
collectionView.cellForItem(at: indexPath)?.isSelected = false
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
(segue.destination as! FullViewController).memeImage = sender as? UIImage
}
func reloadView(hardReload: Bool = false) {
loadingIndicator.startAnimating()
if hardReload {
singleton.refreshPhotoCarret()
}
emptyPlaceholderView.isHidden = !singleton.memes.isEmpty
memeGrid.isHidden = singleton.memes.isEmpty
memeGrid.reloadData()
loadingIndicator.stopAnimating()
}
@IBAction func addMemeAction(_ sender: Any) {
let addition = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "createMemeView") as! MainController
let navController = UINavigationController(rootViewController: addition)
present(navController, animated:true, completion: nil)
}
}
<file_sep>//
// FullViewController.swift
// MemeApp
//
// Created by <NAME> on 6/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class FullViewController: UIViewController {
@IBOutlet weak var largeImage: UIImageView!
var memeImage:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
largeImage.image = memeImage
}
}
<file_sep>//
// MemeGridCell.swift
// MemeApp
//
// Created by <NAME> on 6/7/17.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class MemeGridCell: UICollectionViewCell {
@IBOutlet weak var ThumbnailImage: UIImageView!
@IBOutlet weak var dateLabel: UILabel!
// If both classes could inheret from the same class then i'd see the benefit. Please correct me if i'm wrong but UICollectionViewCell is UICollectionReusableView's child and UITableViewCell is child of another kind. I event tried to set them to be one of the kind but storyboard didn't allow it.
func setupCellWith(meme:Meme) {
ThumbnailImage.image = meme.generatedMeme
dateLabel.text = (UIApplication.shared.delegate as! AppDelegate).getReadableDate(dateToConvert: meme.creationTime)
}
}
| 69012a6f64673c5c9d9621c2c4c8f23eeb94def3 | [
"Swift",
"Markdown"
] | 9 | Swift | mchirino89/MemeApp | 59077ec19645f1992fd5794214291c0a557632ec | 85aef0745d104842a4760623cbfc83b3e9438928 |
refs/heads/master | <file_sep>package ua.kiev.prog.demo.Controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import ua.kiev.prog.demo.Service.PriceService;
@Controller
public class PriceController {
@Autowired
private PriceService priceService;
@RequestMapping("/")
public String getPage (Model model){
model.addAttribute("stylusPrice", priceService.get("StylusStore"));
model.addAttribute("royalServiceStorePrice", priceService.get("RoyalStore"));
model.addAttribute("eStorePrice", priceService.get("EStore"));
model.addAttribute("recipientMail", priceService.getMail());
return "page";
}
@PostMapping("/alert")
public String enableAlert (@RequestParam boolean enable, @RequestParam String recipientMail){
priceService.update();
priceService.setStatus(enable);
priceService.setMail(recipientMail);
priceService.enableMonitoringOfPrice();
// priceService.alertUser(); //test
return "redirect:/";
}
@GetMapping("/view")
public String viewPrices (){
priceService.update();
return "redirect:/";
}
}
<file_sep>package ua.kiev.prog.demo.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@Service
public class PriceService {
@Autowired
private PriceRepository priceRepository;
@Autowired
private MailSender mailSender;
private String mail;
private boolean status;
private HashMap<String, Integer> prices = new HashMap<>();
public Integer get (String name){
return prices.get(name);
}
public void update(){
prices.put("StylusStore", priceRepository.getPriceStylusStore());
prices.put("RoyalStore", priceRepository.getPriceRoyalStore());
prices.put("EStore", priceRepository.getPriceEStore());
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public void enableMonitoringOfPrice (){
System.out.println("Work price Monitor");
if (priceRepository.getPriceStylusStore()<prices.get("StylusStore")
|| priceRepository.getPriceEStore()<prices.get("EStore")
|| priceRepository.getPriceRoyalStore()<prices.get("RoyalStore")){
if (mail!=null)
alertUser();
update();
System.out.println("Sending message");
}
}
public void alertUser (){
String message = String.format(
"Hello, Iphone XS became cheaper!!"
);
mailSender.sendMail(mail, "buy Iphone XS))", message);
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}
<file_sep>spring.mvc.view.prefix=/WEB-INF/pages/
spring.mvc.view.suffix=.jsp
spring.mail.host=smtp.ukr.net
spring.mail.username=
spring.mail.password=
spring.mail.port=465
spring.mail.protocol=smtps<file_sep>package ua.kiev.prog.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class PriceMonitorApplication {
public static void main(String[] args) {
SpringApplication.run(PriceMonitorApplication.class, args);
}
@Bean
public SchedulingTasks task() {
return new SchedulingTasks();
}
}
<file_sep>package ua.kiev.prog.demo.Parser;
public interface Parser {
String getPrice ();
}
<file_sep>package ua.kiev.prog.demo.Parser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URL;
@Component
public class StylusParser implements Parser {
private String url = "https://stylus.ua/iphone-xs-256gb-space-gray-p397913c170.html";
@Override
public String getPrice() {
try {
Document page = Jsoup.parse(new URL(url), 8000);
Elements elements = page.select("div[class=regular-price]");
String price = elements.first().text();
return price;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
| 7408317fe0339774abaf36313cd401bb16c7f258 | [
"Java",
"INI"
] | 6 | Java | NVS1/PriceMonitor | b7233599322fd71a74944aab469a6c3b59ca7309 | f34c310ec85ff7f2328052e0ba2d9f9450459d6e |
refs/heads/master | <file_sep>var ffmpeg = require('./ffmpeg')
var through2 = require('through2')
var TokenBucket = require('limiter').TokenBucket
var asciiPixels = require('ascii-pixels')
var ChopStream = require('chop-stream')
var charm = require('charm')
function ThrottleStream (chunksPerSecond) {
var bucket = new TokenBucket(chunksPerSecond, chunksPerSecond, 'second', null)
return through2(function (chunk, _, next) {
bucket.removeTokens(1, function (err) {
next(err, chunk)
})
})
}
function AsciiStream (frameWidth, frameHeight, options) {
return through2(function (frameData, _, next) {
var imageData = {
data: frameData,
width: frameWidth,
height: frameHeight,
format: 'RGB24'
}
// convert to ascii art
var ascii = asciiPixels(imageData, options)
next(null, ascii)
})
}
function TerminalStream () {
var term = charm(process)
term.removeAllListeners('^C')
term.on('^C', function () {
term.cursor(true).end()
process.exit()
})
term.reset()
term.cursor(false)
return through2(function (text, _, next) {
var boldText = '\u001B[1m' + text + '\u001B[22m'
term.erase('screen').position(0, 0).write(boldText)
next()
}).on('end', function () {
term.cursor(true).end()
})
}
// render video as ascii characters
module.exports = function (video, options) {
// set the dimensions for the scaled video
var frameWidth = Math.round(options.width)
var frameHeight = Math.round(video.height / (video.width / frameWidth))
var frameBytes = frameWidth * frameHeight * 3 // rgb24
ffmpeg
.rawImageStream(video.url, options)
.pipe(new ChopStream(frameBytes))
.pipe(new ThrottleStream(options.fps))
.pipe(new AsciiStream(frameWidth, frameHeight, options))
.pipe(new TerminalStream())
.resume() // TODO: makes TerminalStream end (should probably be a writable/output stream instead)
}
<file_sep># YouTube Terminal
[](https://npm.im/youtube-terminal)

[](https://david-dm.org/mathiasvr/youtube-terminal)
[](https://mvr.mit-license.org)
Stream YouTube videos as ascii art in the terminal!
## usage
YouTube Terminal will play the first found search result:
```shell
$ youtube-terminal [options] 'cyanide and happiness'
```
### options
-l, --link [url] Use YouTube link instead of searching
-i, --invert Invert brightness, recommended on white background
--color Use 16 terminal colors [experimental]
-c, --contrast [percent] Adjust video contrast [default: 35]
-w, --width [number] ASCII video character width
-m, --mute Disable audio playback
--fps [number] Adjust playback frame rate
-h, --help Display this usage information
> Note that setting the `--invert` flag had the opposite effect in earlier releases, and was changed based on [this poll](https://github.com/mathiasvr/youtube-terminal/tree/v0.5.2#which-background-color-does-your-terminal-have).
## install
```shell
$ npm install -g youtube-terminal
```
Be sure to have [FFmpeg](https://www.ffmpeg.org) installed as well.
Ubuntu/Debian users should have ALSA installed as well:
```shell
$ sudo apt-get install libasound2-dev
```
## related
[ascii-pixels](https://github.com/mathiasvr/ascii-pixels)
## license
MIT
<file_sep>var ffmpeg = require('fluent-ffmpeg')
var debug = require('debug')('yt-term')
function ffmpegWithEvents (url) {
return ffmpeg(url)
.on('start', function (commandLine) {
debug('Spawned FFmpeg with command: ' + commandLine)
})
.on('end', function () {
debug('FFmpeg instance ended')
})
.on('error', function (err) {
console.error('FFmpeg error: ' + err.message)
})
}
exports.pcmAudio = function (url) {
return ffmpegWithEvents(url)
.noVideo()
.audioCodec('pcm_s16le')
.format('s16le')
}
exports.jpegStream = function (url, options) {
return ffmpegWithEvents(url)
.format('image2')
.videoFilters([
{ filter: 'fps', options: options.fps },
{ filter: 'scale', options: options.width + ':-1' }
])
.outputOptions('-update', '1')
}
exports.rawImageStream = function (url, options) {
return ffmpegWithEvents(url)
.format('rawvideo')
.videoFilters([
{ filter: 'fps', options: options.fps },
{ filter: 'scale', options: options.width + ':-1' }
])
// .outputOptions('-vcodec', 'rawvideo')
.outputOptions('-pix_fmt', 'rgb24')
.outputOptions('-update', '1')
}
<file_sep>module.exports = require('./ffmpeg').pcmAudio
<file_sep>#!/usr/bin/env node
var ytdl = require('ytdl-core')
var Speaker = require('speaker')
var youtubeSearch = require('youtube-crawler')
var debug = require('debug')('yt-term')
var pcmAudio = require('./lib/pcm-audio')
var asciiVideo = require('./lib/ascii-video')
// command line options
var argv = require('minimist')(process.argv.slice(2), {
// TODO: maybe use c to alias color instead of contrast
alias: { l: 'link', i: 'invert', c: 'contrast', w: 'width', m: 'mute', h: 'help' },
boolean: ['invert', 'mute', 'color', 'help']
})
var wrongType = typeof argv.c === 'string' || typeof argv.w === 'string'
if (argv.help || (argv._.length <= 0 && !argv.link) || wrongType) {
printUsage()
} else if (argv.link) {
// play from youtube link
console.log('Playing:', argv.link)
play(argv.link)
} else {
// search youtube and play the first result
var query = argv._.join(' ')
youtubeSearch(query, function (err, results) {
if (err) return console.error(err)
console.log('Playing:', results[0].title)
play(results[0].link)
})
}
function play (url) {
ytdl.getInfo(url, function (err, info) {
if (err) return console.error(err)
if (!argv.mute) playAudio(info)
playVideo(info)
})
}
function playVideo (info) {
// low resolution video only, webm prefered
var videoItems = info.formats
.filter(function (format) { return format.resolution === '144p' && format.audioBitrate === null })
.sort(function (a, b) { return a.container === 'webm' ? -1 : 1 })
// lowest resolution
var video = videoItems[0]
debug('Video format: %s [%s] (%s) %sfps', video.resolution, video.size, video.encoding, video.fps)
// TODO: maybe it is needed to null-check video.size and m, and default to '256x144'
var size = video.size.match(/^(\d+)x(\d+)$/)
var videoInfo = {
url: video.url,
width: size[1],
height: size[2]
}
var videoOptions = {
// TODO: some (old?) videos have fps incorrectly set to 1.
fps: argv.fps /* || video.fps */ || 12,
// TODO: width does not work well if video height is larger than terminal window
width: argv.width || process.stdout.columns || 80,
contrast: (argv.contrast || 35) * 2.55, // percent to byte
invert: !argv.invert,
color: argv.color
}
// play video as ascii
asciiVideo(videoInfo, videoOptions)
}
function playAudio (info) {
// audio only, sorted by quality
var audioItems = info.formats
.filter(function (format) { return format.resolution === null })
.sort(function (a, b) { return b.audioBitrate - a.audioBitrate })
// highest bitrate
var audio = audioItems[0]
debug('Audio quality: %s (%s)', audio.audioBitrate + 'kbps', audio.audioEncoding)
var speaker = new Speaker()
var updateSpeaker = function (codec) {
speaker.channels = codec.audio_details[2] === 'mono' ? 1 : 2
speaker.sampleRate = parseInt(codec.audio_details[1].match(/\d+/)[0], 10)
}
// play audio
pcmAudio(audio.url).on('codecData', updateSpeaker).pipe(speaker)
}
function printUsage () {
console.log('Youtube Terminal v' + require('./package.json').version)
console.log()
console.log('Usage: youtube-terminal [options] "search query"')
console.log()
console.log('Options:')
console.log()
console.log(' -l, --link [url] Use YouTube link instead of searching')
console.log(' -i, --invert Invert brightness, recommended on white background')
console.log(' --color Use 16 terminal colors [experimental]')
console.log(' -c, --contrast [percent] Adjust video contrast [default: 35]')
console.log(' -w, --width [number] ASCII video character width')
console.log(' -m, --mute Disable audio playback')
console.log(' --fps [number] Adjust playback frame rate')
console.log(' -h, --help Display this usage information')
console.log()
process.exit(0)
}
| c5895642833960d76cdd699c51c218d517aa5b8c | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | xxxVxxx/youtube-terminal | b861d320702ba0a13af575ec21d4008bfc1aec8f | b9c5cbdb21bba7bcf93e78e72ebe271509c371bc |
refs/heads/master | <repo_name>rahulsh1/ocp-java8<file_sep>/pages/chapter7.md
---
layout: page
title: Chapter 7. Method Enhancements
description: 1Z0-810 Java SE8
comments: true
---
### 7.1. Adding static methods to interfaces
A static method is a method that is associated with the class in which it is defined rather than with any object.
Every instance of the class shares its static methods. :fire:
- Helper methods can now be part of the Interface, rather than part of classes.
- You can invoke static methods from within default methods
- You cannot invoke default methods from static methods.
- Static methods can only be referenced by the Interface in which they are defined.
- CANNOT use ClassName or instance of the class to refer to it
- Static methods are not inherited...they belong to only that Interface where they are defined.
- An Interface inheriting from one with static method wont have that static method.
- You still have to use the original Interface name to invoke it.
- You may define the static method again, in another sub-interface. Use the appropriate interface name to invoke the static method.
Example:
Comparator interface has been enhanced with static method
* comparing -> specify custom comparator using lambda expresssion
* comparingInt
* naturalOrder
e.g. `myDeck.sort(Comparator.comparing(Card::getRank));`
Example:
{% highlight java linenos %}
interface One {
void doIt();
default void doSomething() {
System.out.println("I - One: Do something");
// Default can invoke static methods.
sayHello();
}
static void sayHello() {
System.out.println("I - One: SayHello");
// Cant call default methods from static context
// doSomething();
}
}
static class OneTest implements One {
@Override
public void doIt() {
System.out.println("C - OneTest: Do it");
}
}
public static void main(String[] args) {
One one = new OneTest();
one.doIt();
one.doSomething();
// Can use only Interface One to call sayHello()
One.sayHello();
}
{% endhighlight %}
:key: Output
C - OneTest: Do it
C - OneTest: Do something
I - One: SayHello
I - One: SayHello
### 7.2. Define and use a default method of a interface; Describe the inheritance rules for a default method
Default methods enable you to add new functionality to the interfaces of your libraries and
ensure binary compatibility with code written for older versions of those interfaces.
- Lets you add new methods without breaking classes that already implement this interface.
- You add a default implementation for this method though.
- You still need a Class instance to call the default methods.
- You can call Interface static method from it
- You can also call other instance methods (abstract ones) from it. (Since you need an instance to call the default method, the abstract methods will be implemented)
When you extend an interface that contains a default method, you can do the following:
- Not mention the default method at all, which lets your extended interface inherit the default method.
- Redeclare the default method, which makes it abstract. i.e. redeclare it but without the implementation. :fire:
- Redefine the default method, which overrides it. i.e Specify some other implementation for the default method.
:boom: You can define an Interface with all default methods? Yes, :fire: One or more or all the methods can be default
e.g: Comparator interface has been enhanced with default method
* thenComparing
* thenComparingDouble to chain Comparators.
Example:
{% highlight java linenos %}
public class DefaultDemo {
@FunctionalInterface
interface One {
void doIt();
public default void doSomething() {
System.out.println("I - One: Do something");
}
default void doSomething2() {
System.out.println("I - One: Do something2");
}
}
// Two is NOT a @FunctionalInterface -> Two SAMs
interface Two extends One {
// Redefined it now
default void doSomething() {
System.out.println("I - Two: Do something");
}
// doSomething2 is now abstract..you cant get the default impl now
void doSomething2();
}
static class OneTest implements One {
@Override
public void doIt() {
System.out.println("C - OneTest: Do it");
}
@Override
public void doSomething() {
System.out.println("C - OneTest: Do something");
}
}
static class TwoTest implements Two {
@Override
public void doIt() {
System.out.println("C - TwoTest: Do it");
}
@Override
public void doSomething2() {
System.out.println("C - TwoTest: Do something");
}
}
public static void main(String[] args) {
One one = new OneTest();
one.doIt();
one.doSomething();
one.doSomething2();
Two two = new TwoTest();
two.doIt();
two.doSomething();
two.doSomething2();
}
}
{% endhighlight %}
:key: Output
C - OneTest: Do it
C - OneTest: Do something
I - One: Do something2
C - TwoTest: Do it
I - Two: Do something
C - TwoTest: Do something
[See Also ](https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html)
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part7)
--------------------------------
[Next Chapter 8. Use Java SE 8 Date/Time API](chapter8.html)
--------------------------------
<file_sep>/pages/chapter6.md
---
layout: page
title: Chapter 6 Lambda Cookbook
description: 1Z0-810 Java SE8
comments: true
---
### 6.1: Develop the code that use Java SE 8 collection improvements: Collection.removeIf, List.replaceAll, Map.computeIfAbsent/Present, Map.forEach
> Java 8 Changes
##### `java.util.Collection<E>` Interface changes
{% highlight java %}
default boolean removeIf(Predicate<? super E> filter)
- Removes all of the elements of this collection that satisfy the given predicate.
default Stream<E> stream()
- Returns a sequential Stream with this collection as its source.
default Stream<E> parallelStream()
- Returns a possibly parallel Stream with this collection as its source.
It is allowable for this method to return a sequential stream.
{% endhighlight %}
##### `java.util.List<E>` Interface changes
{% highlight java %}
default void replaceAll(UnaryOperator<E> operator)
- Replaces each element of this list with the result of applying the operator to that element.
it mutates the elements of the List.
default void sort(Comparator<? super E> c)
- Sorts this list according to the order induced by the specified Comparator.
If the specified comparator is null then all elements in this list will be sorted by
natural order, elems must implement the Comparable interface
{% endhighlight %}
##### `java.util.Iterator<E>` Interface changes
{% highlight java %}
default void forEachRemaining(Consumer<? super E> action)
- Performs the given action for each remaining element until all elements have been processed
{% endhighlight %}
##### java,util.Comparator<T> Interface changes
{% highlight java %}
default Comparator<T> reversed()
- Returns a comparator that imposes the reverse ordering of this comparator.
{% endhighlight %}
##### java.util.Map
{% highlight java %}
default void forEach(BiConsumer<? super K,? super V> action)
- Performs the given action for each entry in this map
default void replaceAll(BiFunction<? super K,? super V,? extends V> function)
- Replaces each entry's value with the result of invoking the given function on that entry
default V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
- If there is no value for the key, then it computes its value using the given mapping function
and inserts it if the value!=null
default V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
- If the value for the specified key is present and non-null, attempts to compute a new mapping
given the key and its current mapped value.
If the function returns null, the mapping is removed.
default V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
- Computes a mapping for the specified key and its current mapped value
{% endhighlight %}
:sweat_drops: Section 6.2 is soon after Section 6.3:
### 6.3: Use merge, flatMap methods on a collection
##### `java.util.Map<K, V>`
{% highlight java %}
default V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)
- If there is no value for this key, use value, if there is, pass to func and assign that
value to the key. If new value is null, removes the key from map
{% endhighlight %}
e.g. To either create or append a String msg to a value mapping:
map.merge(key, msg, String::concat)
##### [java.util.stream.Stream](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html)
{% highlight java %}
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
- Returns a stream consisting of the results of replacing each element of this stream with the
contents of a mapped stream
{% endhighlight %}
Example:
`.flatMap(e -> Stream.of(e.split(" ")))` -> Returns a `stream of R` instead of just R
{% highlight java linenos %}
List<String> list = Arrays.asList("Zello Some", "New Some", "Thing New", "zGood");
List<String> list2 = list.stream()
.flatMap(e -> Stream.of(e.split(" ")))
.peek(s -> System.out.println(s + " "))
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Unique words = " + list2);
{% endhighlight %}
:key: Output
Zello
Some
New
Some
Thing
New
zGood
Unique words = [New, Some, Thing, Zello, zGood]
:point_right: Note the difference with map method :fire:
`<R> Stream<R> map(Function<? super T, ? extends R> mapper)`
- Both map and flatMap take in a Function <T, R>
- flatMap R -> Stream<? extends R> whereas map R -> R
- flatMap is useful when you want to split the incoming stream elements into another stream of same type.
### 6.2 Read files using lambda improvements: Files.find, lines(), walk()
Streams have a `BaseStream.close()` method and implement `AutoCloseable`, but nearly all stream instances do not actually need to be closed after use.
Generally, only streams whose source is an IO channel (such as those returned by `Files.lines(Path, Charset))` will require closing
Most streams are backed by collections, arrays, or generating functions, require no special closing.
The below methods opens up some of other file resource and should be used with the try-with-resources to ensure that the stream's close method is invoked. :fire:
{% highlight java %}
public static Stream<Path> list(Path dir) throws IOException
- Return a lazily populated Stream, the elements of which are the entries in the directory.
The listing is not recursive.
{% endhighlight %}
#### walk:
{% highlight java %}
public static Stream<Path> walk(Path start,
int maxDepth,
FileVisitOption... options) throws IOException
public static Stream<Path> walk(Path start,
FileVisitOption... options) throws IOException
- Return a Stream that is lazily populated with Path by walking the file tree rooted at a given
starting file. The file tree is traversed depth-first, the elements in the stream are Path
objects that are obtained as if by resolving the relative path against start.
{% endhighlight %}
#### find:
{% highlight java %}
public static Stream<Path> find(Path start,
int maxDepth,
BiPredicate<Path,BasicFileAttributes> matcher,
FileVisitOption... options) throws IOException
- Return a Stream that is lazily populated with Path by searching for files in a file tree
rooted at a given starting file.
{% endhighlight %}
#### lines
{% highlight java %}
public static Stream<String> lines(Path path, Charset cs) throws IOException
public static Stream<String> lines(Path path) throws IOException -> Uses UTF-8 charset
- Read all lines from a file as a Stream. Unlike readAllLines, this method does not read
all lines into a List, but instead populates lazily as the stream is consumed.
{% endhighlight %}
The returned stream encapsulates a Reader so this should be called with try-with-resources.
[See Also java.nio.file.Files](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html)
### 6.4: Describe other stream sources: Arrays.stream(), IntStream.range()
##### Arrays:
{% highlight java %}
public static <T> Stream<T> stream(T[] array)
public static <T> Stream<T> stream(T[] array, int startInclusive, int endExclusive)
- Returns a sequential Stream with the specified array as its source.
public static IntStream stream(int[] array)
- Returns a sequential IntStream with the specified array as its source.
public static LongStream stream(long[] array)
- Returns a sequential LongStream with the specified array as its source.
public static DoubleStream stream(double[] array)
- Returns a sequential DoubleStream with the specified array as its source
{% endhighlight %}
Example:
{% highlight java linenos %}
String[] strArray = {"A", "B", "PC", "D", "PM"};
Arrays.stream(strArray)
.filter(s -> s.startsWith("P"))
.forEach(System.out::println);
long[] longArr = {1L, 2L, 3L, 5L, 10L};
LongStream longStream = Arrays.stream(longArr);
System.out.println("Sum = " + longStream.sum());
Output:
PC
PM
Sum = 21
{% endhighlight %}
##### IntStream:
{% highlight java %}
static IntStream range(int startInclusive, int endExclusive)
- Returns range from start to end-1
static IntStream rangeClosed(int startInclusive, int endInclusive)
- Returns range from start to end - Both inclusive
Stream<Integer> boxed()
- Returns a Stream consisting of the elements of this stream, each boxed to an Integer.
{% endhighlight %}
Example:
{% highlight java linenos %}
IntStream intStream = IntStream.range(1, 20);
intStream.forEach(i -> System.out.print(i + " "));
System.out.println("\nAverage: " + IntStream.range(1, 20).average());
// Note it includes numbers upto 20
IntStream intStream2 = IntStream.rangeClosed(1, 20);
intStream2.forEach(i -> System.out.print(i + " "));
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Average: OptionalDouble[10.0]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
{% endhighlight %}
##### IntSummaryStatistics (not mentioned for exam)
A state object for collecting statistics such as count, min, max, sum, and average.
{% highlight java %}
IntSummaryStatistics stats = people.stream()
.collect(Collectors.summarizingInt(Person::getDependents));
{% endhighlight %}
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part6)
--------------------------------
[Next Chapter 7. Method Enhancements](chapter7.html)
--------------------------------<file_sep>/sources/src/main/java/ocp/study/part4/CollectionDemo.java
package ocp.study.part4;
import ocp.study.Employee;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CollectionDemo {
private static void mapDemo() {
Stream<Employee> emps = Stream.of(new Employee("John"), new Employee("Alice"));
Stream<String> names = emps.map(Employee::getName);
List<String> staff = names.collect(Collectors.toList());
System.out.println(staff);
Stream<Employee> emps2 = Stream.of(new Employee("John"), new Employee("Alice"));
Stream<String> names2 = emps2.map(Employee::getName);
Stream<Integer> lengths = names2.map(s -> s.length());
System.out.println("Lens=" + lengths.collect(Collectors.toList()));
}
private static void intStreamDemo() {
Stream<Employee> emps = Stream.of(new Employee("John"), new Employee("Alice"), new Employee("Bob"), new Employee("Janett"));
Stream<String> names = emps.map(Employee::getName);
IntStream istream = names.mapToInt(s -> s.length());
System.out.println("Max: " + istream.max().getAsInt());
// stream has already been operated upon or closed
// System.out.println("Total: " + istream.count());
}
public static void main(String[] args) {
mapDemo();
intStreamDemo();
}
}
<file_sep>/pages/chapter1.md
---
layout: page
title: Chapter 1. Lambda Expressions
description: 1Z0-810 Java SE8
comments: true
---
### 1.1. Describe Java inner classes and develop the code that uses Java inner classes (such as: nested class, static class, local class and anonymous classes)
#### Inner Classes
- nested class
- static class
- local class
- anonymous class
##### 1.1.1 Member Inner Class
- It has access to all methods, fields, and the Outer's this reference:
- Inner class instance must be instantiated with an enclosing instance.
- Outer and inner class can directly access each other's fields and methods (even if private.)
- `Inner i = new Outer().new Inner();`
- You cannot declare static initializers or static member interfaces in a inner class unless that are constants.
##### 1.1.2 Static Nested Classes
- No link to an instance of the outer class.
- Can only access static fields and static methods of the outer class.
- `Outer.Inner n = new Outer.Inner();`
##### 1.1.3 Local classes:
- Classes that are defined in a block, which is a group of zero or more statements between balanced curly braces.
- You typically find local classes defined in the body of a method:
- If method is static, the local inner classes becomes static.
- A local class can access local variables and parameters of the enclosing block that are final or effectively final.
- A local class can access its outer classes members just fine (final/not final)
###### Static method local inner class
- Class inside a static method
- Can only access static members & static methods of outside scope
###### Static members
- Local classes are similar to inner classes so they cannot define or declare any static members. :exclamation: See [OuterInnerDemo](../sources/src/ocp/study/part1/OuterInnerDemo.java)
- You cannot declare an interface inside a block; interfaces are inherently static.
{% highlight java linenos %}
public void saySomething() {
interface HelloThere { // Compile failure
public void greet();
}
}
{% endhighlight %}
<i class="icon-hand-right"></i> You cannot declare static initializers or member interfaces in a local class.
{% highlight java linenos %}
public void saySomething() {
class SayHello {
public static void goodbye() { // Compile failure
System.out.println("Bye bye");
}
}
SayHello.goodbye();
}
{% endhighlight %}
{% highlight java linenos %}
public class OuterInnerDemo {
public static class StaticInner {
private String in;
// OK
static int x = 10;
static final int y = 20;
public static void doIt() {
class StaticInnerInner {
// Compile error: Inner class cannot have static declarations
// static int x = 10;
}
}
}
{% endhighlight %}
##### 1.1.4 Anonmymous class
- has access to the members of its enclosing class.
- cannot access local variables in its enclosing scope that are not declared as final or effectively final.
- Same rules apply as local class
- Anonymous classes also have the same restrictions as local classes with respect to their members:
- You cannot declare static initializers or member interfaces in an anonymous class.
- An anonymous class can have static members provided that they are constant variables.
{% highlight java linenos %}
public class InnerClassDemo {
private int x = 10;
private static int staticX = 20;
public void testAnonymousClass() {
int y = 30;
System.out.println("Anonymous Class");
SomeInterface someInterface = new SomeInterface() {
int z = 40;
// static int z1 = 42; // <-- Inner class cannot have static declarations
static final int z2 = 42; // <-- OK
@Override
public void doSomething() {
// y++; // y needs to be final
x++;
z++;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
System.out.println("staticX is " + staticX);
}
};
someInterface.doSomething();
}
}
{% endhighlight %}
### 1.2. Define and write functional interfaces
##### Functional interfaces
- provide target types for lambda expressions and method references.
- has a single abstract method (SAM), called the functional method for that functional interface,
to which the lambda expression's parameter and return types are matched or adapted.
- All the existing single method interfaces like `Runnable`, `Callable`, `Comparator`, and `ActionListener` in the JDK 8 are now functional interfaces
- `@FunctionalInterface` annotation
- optional, it is a "hint" for Java compiler similar to `@Override`
##### Default methods in interfaces
They are introduced so that you can add new methods in the interface without breaking old code that uses this interface.
- Methods in interfaces can now have implementation :fire:
- A default method is an instance method defined in an interface whose method header begins with the default keyword; it also MUST provide a code body.
- A static method is a class method defined in an interface whose method header begins with the static keyword; it also MUST provide a code body.
- Static methods can be called only with the Interface name i.e cannot refer them by Class name or using an instance
{% highlight java linenos %}
public interface SomeInterface {
default void defdoSome() { /* implementation */ }
static void statdoSome() { /* implementation */ }
void doIt(); // SAM
}
// Calling code:
public static void main(String[] args) {
SomeInterface myInterface = () -> System.out.println("do something");
myInterface.defdoSome();
myInterface.doIt();
MyDefInterface.statdoSome();
}
{% endhighlight %}
### 1.3. Describe a Lambda expression; refactor the code that use anonymous inner class to use Lambda expression; including type inference, target typing
{% highlight java linenos %}
// Pre-Java8 style
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
comp.setText("Button has been clicked");
}
});
// Java8 style
button.addActionListener(e -> comp.setText("Button has been clicked"));
// or
button.addActionListener((ActionEvent e) -> comp.setText("Button has been clicked"));
{% endhighlight %}
##### Lambda Expressions
- A comma-separated list of formal parameters enclosed in parentheses.
- The arrow token **->**
- A body, which consists of a single expression or a statement block
- Remember return statement is NOT an expression so in a lambda expression, you MUST enclose statements in braces ({...}).
- You can omit the data type of the parameters in a lambda expression.
{% highlight java linenos %}
p -> p.getDept() >= 2
(Person p) -> p.getDept() >= 2
(Person p) -> { return p.getDept() >= 2; } // Note the {}
{% endhighlight %}
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part1)
--------------------------------
[Chapter2 - Using Built in Lambda Types](chapter2.html)
--------------------------------
<file_sep>/sources/src/main/java/ocp/study/part6/OtherStreamSources.java
package ocp.study.part6;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class OtherStreamSources {
static void arrays() {
String[] strArray = {"A", "B", "PC", "D", "PM"};
Arrays.stream(strArray)
.filter(s -> s.startsWith("P"))
.forEach(System.out::println);
long[] longArr = {1L, 2L, 3L, 5L, 10L};
LongStream longStream = Arrays.stream(longArr);
System.out.println("Sum = " + longStream.sum());
}
static void intstream() {
IntStream intStream = IntStream.range(1, 20);
intStream.forEach(i -> System.out.print(i + " "));
System.out.println("\nAverage: " + IntStream.range(1, 20).average());
// Note it includes numbers upto 20
IntStream intStream2 = IntStream.rangeClosed(1, 20);
intStream2.forEach(i -> System.out.print(i + " "));
System.out.println();
IntStream intStream1 = IntStream.of(1, 10, 9, 3, 8);
intStream1.sorted().forEach(e -> System.out.print(e + " "));
}
public static void main(String[] args) {
arrays();
intstream();
}
}
<file_sep>/sources/src/main/java/ocp/study/part5/ParallelDemo.java
package ocp.study.part5;
import ocp.study.Person;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
public class ParallelDemo {
static void parallelAvgDemo(List<Person> persons) {
double average = persons.parallelStream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(p -> p.getAge())
.average().getAsDouble();
System.out.println("average=" + average);
}
static void parallelReduce(List<Person> persons) {
// This is called a concurrent reduction.
ConcurrentMap<Person.Sex, List<Person>> byGender =
persons.parallelStream()
.collect(Collectors.groupingByConcurrent(Person::getGender));
System.out.println("Parallel Reduction by Gender " + byGender);
}
static void ordering() {
Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8 };
List<Integer> listOfIntegers =
new ArrayList<>(Arrays.asList(intArray));
System.out.println("listOfIntegers:");
listOfIntegers
.stream()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("listOfIntegers sorted in reverse order:");
Comparator<Integer> normal = Integer::compare;
Comparator<Integer> reversed = normal.reversed();
Collections.sort(listOfIntegers, reversed);
listOfIntegers
.stream()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("Parallel stream");
listOfIntegers
.parallelStream()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("Another parallel stream:");
listOfIntegers
.parallelStream()
.forEach(e -> System.out.print(e + " "));
System.out.println("");
System.out.println("With forEachOrdered:");
listOfIntegers
.parallelStream()
.forEachOrdered(e -> System.out.print(e + " "));
System.out.println("");
// Stateful operation
System.out.println("Stateful operation:");
List<Integer> list = new ArrayList<>();
list.add(11);list.add(12);list.add(13);list.add(14);
List<Integer> serialStorage = list;//Arrays.asList(1, 2, 3, 4, 5);
serialStorage
.stream()
// Don't do this! It uses a stateful lambda expression.
.map(e -> { serialStorage.add(e); return e; }) // Throws java.util.ConcurrentModificationException
.forEachOrdered(e -> System.out.print(e + " "));
}
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("Jane", 25, false));
persons.add(new Person("Alice", 28, false));
persons.add(new Person("Bob", 42, true));
persons.add(new Person("Tina", 19, false));
parallelAvgDemo(persons);
parallelReduce(persons);
ordering();
}
}
<file_sep>/pages/ExamObjectives.md
---
layout: page
title: Exam Objectives
description: 1Z0-810 Java SE8
comments: false
---
### Lambda Expressions
* Describe Java inner classes and develop the code that uses Java inner classes (such as: nested class, static class, local class and anonymous classes)
* Define and write functional interfaces
* Describe a Lambda expression; refactor the code that use anonymous inner class to use Lambda expression; including type inference,target typing
### Using Built in Lambda Types
* Describe the built in interfaces included in Java 8 - java.util.function package
* Develop code that uses Function interface
* Develop code that uses Consumer interface
* Develop code that uses Supplier interface
* Develop code that uses UnaryOperator interface
* Develop code that uses Predicate interface
* Develop the code that use primitive and binary variations of base interfaces of java.util.function package
* Develop the code that use method reference; including refactor the code that use Lambda expression to use method references
### Filtering Collections with Lambdas
* Develop the code that iterates a collection by using forEach; including method chaining
* Describe the Stream interface and pipelines
* Filter a collection using lambda expressions
* Identify lambda operations that are lazy
### Collection Operations with Lambda
* Develop the code to extract data from an object using map
* Search for data using search methods including: findFirst, findAny, anyMatch, allMatch, noneMatch.
* Describe the unique characteristics of the Optional classes
* Perform calculations using methods: count, max, min, average, sum
* Sort a collection using lambda expressions
* Save results to a collection by using the collect method and Collector class; including methods such as averagingDouble,groupingBy,joining,partitioningBy
### Parallel Streams
* Develop the code that use parallel streams
* Implement decomposition, reduction, in streams
### Lambda Cookbook
* Develop the code that use Java SE 8 collection improvements: Colleciton.removeIf, List.replaceAll, Map.computeIfAbsent/Present, Map.forEach
* Read files using lambda improvements: Files.find, lines(), walk()
* Use merge, flatMap methods on a collection
* Describe other stream sources: Arrays.stream(), IntStream.range()
### Method Enhancements
* Adding static methods to interfaces
* Define and use a default method of a interface; Describe the inheritance rules for a default method
### Use Java SE 8 Date/Time API
* Create and manage date-based and time-based events; including combination of date and time into a single object using LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration
* Work with dates and times across time-zones and manage changes resulting from daylight savings
* Define and create timestamps, periods and durations; apply formatting to local and zoned dates and times
### JavaScript on Java with Nashorn
* Develop Javascript code that creates and uses Java members such as Java objects, methods, JavaBeans, Arrays, Collections, Interfaces.
* Develop code that Evaluates JavaScript in java, Passes Java object to Javascript, inovkes Javascript function and call methods on javascript objects.
----------------------------------------------
<file_sep>/pages/chapter5.md
---
layout: page
title: Chapter 5. Parallel Streams
description: 1Z0-810 Java SE8
comments: true
---
### Chp 5.1: Develop the code that use parallel streams
Aggregate operations and parallel streams enable you to implement parallelism with non-thread-safe collections provided
that you do not modify the collection while you are operating on it.
Use `.parallelStream()` instead of `.stream()` or use `.stream().parallel()`
use `.sequential()` method on a stream to convert a parallel stream into a sequential stream
Parallel streams uses the `fork/join` framework that was added in Java 7.
When a stream executes in parallel, the Java runtime partitions the stream into multiple substreams.
Aggregate operations iterate over and process these substreams in parallel and then combine the results.
{% highlight java %}
ConcurrentMap<Person.Sex, List<Person>> byGender =
roster
.parallelStream()
.collect(
Collectors.groupingByConcurrent(Person::getGender));
{% endhighlight %}
> Differences:
- Uses ConcurrentMap instead of Map
- Uses groupingByConcurrent instead of groupingBy
- the operation Collectors.toConcurrentMap performs better with parallel streams than the operation Collectors.toMap.
[See Also](http://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html)
###### Ordering: Pipeline methods
The ordering will be totally random here incase of parallel streams.
{% highlight java %}
listOfIntegers
.parallelStream()
.forEach(e -> System.out.print(e + " "));
{% endhighlight %}
- `forEachOrdered`-> processes the elements of the stream in the order specified by its source. You will loose the benefits of parallelism.
{% highlight java %}
listOfIntegers
.parallelStream()
.forEachOrdered(e -> System.out.print(e + " "));
{% endhighlight %}
:point_right: Interference
- Lambda expressions in stream operations should not interfere.
Interference occurs when the source of a stream is modified while a pipeline processes the stream.
:point_right: Stateful Lambda Expressions
- Avoid using stateful lambda expressions as parameters in stream operations.
- A stateful lambda expression is one whose result depends on any state that might change during the execution of a pipeline
{% highlight java %}
List<Integer> serialStorage = new ArrayList<>();
serialStorage
.stream()
// Don't do this! It uses a stateful lambda expression.
.map(e -> { serialStorage.add(e); return e; }) // Throws ConcurrentModificationException
.forEachOrdered(e -> System.out.print(e + " "));
{% endhighlight %}
:point_right: Make sure you use a concurrent version or synchronized version of the Map/List for parallel stream when you add to it.
otherwise, you'll get incorrect results since multiple threads access and modify the collection.
### Chap 5.2 Implement decomposition, reduction, in streams
#### Reduction Operations:
- Reduce to one value or groups of values
- Many terminal operations (such as average, sum, min, max, and count) return one value by combining the contents of a stream.
- Some terminal operations (such as reduce and collect) return a collection by finding the average of values or grouping elements into categories.
##### Stream.reduce
- `identity`: initial value of the reduction or the default result if no elements
- `accumulator`: a partial result of the reduction and the next element of the stream
:arrow_right: `reduce(BinaryOperator<T> accumulator)`
Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
:arrow_right: `T reduce(T identity, BinaryOperator<T> accumulator)`
Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
:arrow_right: `U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)`
Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.
:fire:
:point_right: The reduce operation always returns a **new** value. The accumulator function also returns a new value every time it processes an element of a stream
Example1:
{% highlight java linenos %}
static void reduce(List<Person> roster) {
Integer totalAge = roster
.stream()
.mapToInt(Person::getAge)
.sum();
System.out.println("TotalAge: " + totalAge);
Integer totalAgeReduce = roster
.stream()
.map(Person::getAge)
.reduce(
0,
(a, b) -> a + b);
System.out.println("TotalAge: " + totalAgeReduce);
}
{% endhighlight %}
Example2:
{% highlight java linenos %}
static class Averager implements IntConsumer {
private int total = 0;
private int count = 0;
public double average() {
return count > 0 ? ((double) total) / count : 0;
}
public void accept(int i) {
total += i;
count++;
}
public void combine(Averager other) {
total += other.total;
count += other.count;
}
}
static void collect(List<Person> roster) {
Averager averageCollect = roster.stream()
.map(Person::getAge)
.collect(Averager::new, Averager::accept, Averager::combine);
System.out.println("Average age of all members: " + averageCollect.average());
}
public static void main(String[] args) {
List<Person> persons = Arrays.asList(new Person("Jane", 25, false), new Person("Alice", 28, false),
new Person("Bob", 42, true), new Person("Tina", 19, false));
collect(persons);
}
{% endhighlight %}
:key: Output
Average age of all members: 28.5
##### Stream.collect
Unlike the reduce method, which always creates a new value when it processes an element, the collect method modifies, or mutates, an existing value.
:arrow_right: `<R,A> R collect(Collector<? super T,A,R> collector)`
Performs a mutable reduction operation on the elements of this stream using a Collector.
:arrow_right: `<R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)`
Performs a mutable reduction operation on the elements of this stream.
The collect operation is best suited for collections.
{% highlight java %}
.collect(Collectors.groupingBy(Person::getGender)); -> returns Map<Gender, List<Person>>
.collect(Collectors.groupingBy(
Person::getGender,
Collectors.averagingInt(Person::getAge)));
{% endhighlight %}
Example:
{% highlight java linenos %}
Map<Person.Sex, Integer> totalAgeByGender =
persons
.stream()
.collect(
Collectors.groupingBy(
Person::getGender,
Collectors.reducing(
0,
Person::getAge,
Integer::sum)));
System.out.println("TotalAgeByGender: " + totalAgeByGender);
>> TotalAgeByGender: {FEMALE=72, MALE=42} // for input above.
{% endhighlight %}
:fire: Know all the above methods very well - the input arguments and the return types.
[See Also](http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html)
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part5)
--------------------------------
[Next Chapter - Lambda Cookbook](chapter6.html)
-------------------------------- <file_sep>/pages/chapter8.md
---
layout: page
title: Chapter 8. Use Java SE 8 Date/Time API
description: 1Z0-810 Java SE8
comments: true
---
### 8.1 Create and manage date-based and time-based events; including combination of date and time into a single object using LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration
The `DayOfWeek` enum consists of seven constants that describe the days of the week: MONDAY through SUNDAY.
The `Month` enum includes constants for the twelve months, JANUARY through DECEMBER.
A `LocalDate` represents a year-month-day in the ISO calendar and is useful for representing a date without a time.
`YearMonth`: This class represents the month of a specific year.
YearMonth date2 = YearMonth.of(2010, Month.FEBRUARY);
`MonthDay` : This class represents the day of a particular month
MonthDay date = MonthDay.of(Month.FEBRUARY, 29);
`Year` : This class represents the Year
Year year = Year.of(2012)
`LocalTime` : Deals with hour-min-sec-nanosecond representing time part of date.
The LocalTime class does not store time zone or daylight saving time information
`LocalDateTime`: The class that handles both date and time, without a time zone
This class is used to represent date (month-day-year) together with time (hour-minute-second-nanosecond).
Combo of LocalDate + LocalTime :fire: Does not store time zone information
[See Table ](https://docs.oracle.com/javase/tutorial/datetime/iso/overview.html)
----------------------------------------------
##### Instant, Period and Duration : Machine Time
`Instant`: Represents the start of a nanosecond on the timeline.
Stores values internally as
private final long seconds;
private final int nanos;
The Instant class does not work with human units of time, such as years, months, or days. You should convert into `LocalDateTime/ZonedOffsetTime` and then do the calculation.
Either a `ZonedDateTime` or an `OffsetTimeZone` object can be converted to an Instant object, as each maps to an exact moment on the timeline.
However to convert an Instant object to a ZonedDateTime or an OffsetDateTime object REQUIRES supplying time zone, or time zone offset, information
`Period`: A Period uses date-based values (years, months, days) to specify an amount of time
Used to define an amount of time with date-based values (years, months, days)
Stores days, month and year as int values
`Duration` : measures an amount of time using time-based values (seconds, nanoseconds).
A Duration is not connected to the timeline, in that it does not track time zones or daylight saving time
Stores values internally as
private final long seconds;
private final int nanos;
{% highlight java linenos %}
Duration d = Duration.ofDays(10);
System.out.println("10days: " + d);
10days: PT240H
{% endhighlight %}
The `ChronoUnit` enum, discussed in the The Temporal Package, defines the units used to measure time.
`ChronoUnit.between` - Method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.
### 8.2 Work with dates and times across time-zones and manage changes resulting from daylight savings
`ZoneId - abstract class`
specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime.
Incorrect zone id to ZoneId.of(...) returns `ZoneRulesException` :fire:
`ZoneOffset - subclass of ZoneId`
specifies a time zone offset from Greenwich/UTC time
`ZonedDateTime` - handles a date and time with a corresponding time zone with a time zone offset from Greenwich/UTC
Stores internally values as:
private final LocalDateTime dateTime;
private final ZoneOffset offset; // UTC offset
private final ZoneId zone;
`OffsetDateTime`
handles a date and time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
The OffsetDateTime class, in effect, combines the LocalDateTime class with the ZoneOffset class.
It is used to represent a full date (year, month, day) and time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC time
`OffsetTime` - handles time with a corresponding time zone offset from Greenwich/UTC, without a time zone ID.
The `OffsetTime` class, in effect, combines the LocalTime class with the ZoneOffset class.
It is used to represent time (hour, minute, second, nanosecond) with an offset from Greenwich/UTC
The OffsetTime class is used in the same situations as the OffsetDateTime class, but when tracking the date is not needed
Although all three classes maintain an offset from Greenwich/UTC time, only ZonedDateTime uses the ZoneRules, part of the java.time.zone package,
to determine how an offset varies for a particular time zone. esp during DST changes. The others dont do that.
### 8.3 Define and create timestamps, periods and durations; apply formatting to local and zoned dates and times
The parse and the format methods throw an exception if a problem occurs during the conversion process.
parse(...) throw DateTimeParseException and
format(...) throws DateTimeException
The `DateTimeFormatter` class is both immutable and thread-safe; it can (and should) be assigned to a static constant where appropriate. :fire:
The java.time.temporal package provides a collection of interfaces, classes, and enums that support date and time code
Classes like LocalDate, LocalTime or ZonedDateTime are all concrete implementations of it (The java.time.temporal.Temporal interface)
`java.time.temporal.ChronoUnit` enum
contains a standard set of date periods units extends from java.time.temporal.TemporalUnit
ChronoUnit.DAYS and ChronoUnit.WEEKS
`ChronoField enum `
Concrete implementation of the TemporalField interface and provides a rich set of defined constants,
DAY_OF_WEEK, MINUTE_OF_HOUR, and MONTH_OF_YEAR.
The TemporalAdjusters class (note the plural) provides a set of predefined adjusters:
first or last day of the month,
first or last day of the year,
last Wednesday of the month, or
first Tuesday after a specific date
The predefined adjusters are defined as static methods and are designed to be used with the static import statement.
Interoperability with Legacy Code. :bang: - Not mentioned in Exam topics though but good to know.
{% highlight java %}
Calendar.toInstant()
- converts the Calendar object to an Instant.
GregorianCalendar.toZonedDateTime()
- converts a GregorianCalendar instance to a ZonedDateTime.
GregorianCalendar.from(ZonedDateTime)
- creates a GregorianCalendar object using the default locale from a ZonedDateTime instance.
Date.from(Instant)
- creates a Date object from an Instant.
Date.toInstant()
- converts a Date object to an Instant.
TimeZone.toZoneId()
- converts a TimeZone object to a ZoneId.
{% endhighlight %}
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part8)
--------------------------------
[Next Chapter 9. JavaScript on Java with Nashorn](chapter9.html)
--------------------------------
<file_sep>/sources/src/main/java/ocp/study/Employee.java
package ocp.study;
public class Employee implements Comparable {
public final String name;
private final Department dept;
public Employee(String n) {
name = n;
dept = new Department("Engg");
}
public Employee(String n, String d) {
name = n;
dept = new Department(d);
}
public String getName() {
return name;
}
public Department getDepartment() {
return dept;
}
@Override
public String toString() {
return name + ":" + dept.getDept();
}
@Override
public int compareTo(Object o) {
return name.compareTo(((Employee) o).getName());
}
}
<file_sep>/pages/chapter4.md
---
layout: page
title: Chapter 4. Collection Operations with Lambda
description: 1Z0-810 Java SE8
comments: true
---
### 4.1. Develop the code to extract data from an object using map
Applying a function to each element of a stream
Streams support the method `map()`, which takes a `Function` as argument.
{% highlight java %}
Stream<Employee> emps = Stream.of(new Employee("Alice"), new Employee("Bob"),
new Employee("Jane"));
List<String> staff = emps.map(Employee::getName);
.collect(Collectors.toList());
System.out.println(staff);
{% endhighlight %}
##### Primitive stream specializations
Java 8 introduces three primitive specialized stream interfaces that support specialized methods (like max(), sum(), average())
to work with streams of numbers: `IntStream` (rather than a `Stream<Integer>`), `DoubleStream`, and `LongStream`.
{% highlight java linenos %}
IntStream istream = names.mapToInt(s -> s.length());
System.out.println("Max: " + istream.max().getAsInt());
// stream has already been operated upon or closed
// following if uncommented will throw an Exception
// System.out.println("Total: " + istream.count());
{% endhighlight %}
### 4.2. Search for data using search methods including: findFirst, findAny, anyMatch, allMatch, noneMatch.
##### Methods on Stream
* `findFirst` - Finding the first element
Optional<T> findFirst();
* `findAny` - Finding an element - findAny
Gives a more flexible alternative to findFirst(). Can be used in a parallel stream.
Optional<T> findAny();
* `anyMatch` - Checking to see if a predicate matches at least one element
Is there an element in the stream matching the given predicate?
boolean anyMatch(Predicate<? super T> predicate);
* `allMatch` - Checking to see if a predicate matches all elements
boolean allMatch(Predicate<? super T> predicate);
* `noneMatch` - Checking to see if a predicate does not matche any element -
boolean noneMatch(Predicate<? super T> predicate);
:fire: Remember the method signatures:
:point_right: All `findXxx()` methods have no arguments and return `Optional`.
:point_right: All `xxxMatch(...)` methods accept a `Predicate` and return a `boolean` primitive.
All the above are `short circuit` operations. If results match or dont match, they will come out without processing the whole stream.
{% highlight java linenos %}
private static void findFirst() {
List<Employee> employees = Arrays.asList(new Employee("Jack"), new Employee("Jill"), new Employee("Jiane"));
Stream<Employee> emps = employees.stream();
Optional<Employee> result = emps.filter(s -> s.getName().contains("i")).findFirst();
System.out.println("findFirst Result = " + result.get());
}
private static void allMatch() {
List<Employee> employees = Arrays.asList(new Employee("Jack"), new Employee("Jill"), new Employee("Jiane"));
Stream<Employee> emps = employees.stream();
boolean result = emps.allMatch(s -> s.getName().startsWith("J"));
System.out.println("allMatch Result = " + result);
}
private static void noneMatch() {
List<Employee> employees = Arrays.asList(new Employee("Jack"), new Employee("Jill"), new Employee("Jiane"));
Stream<Employee> emps = employees.stream();
boolean result = emps.noneMatch(s -> s.getName().startsWith("K"));
System.out.println("noneMatch Result = " + result);
}
{% endhighlight %}
:key: Output
findFirst Result = Jill
allMatch Result = true
noneMatch Result = true
### 4.3. Describe the unique characteristics of the Optional classes
A `java.util.Optional<T>` object is either a wrapper for an Object of type T or a wrapper for no object.
##### Creation
{% highlight java %}
Optional<String> str = Optional.empty();
Optional<String> optStr = Optional.of("Hello");
Optional<String> optStr = Optional.ofNullable(null); -> Optional.empty()
{% endhighlight %}
The Optional class provides several instance methods to read the value contained by an Optional instance.
`Optional.get()`
is the simplest but also the least safe of these methods.
It returns the wrapped value if present but throws a `NoSuchElementException` otherwise. :fire:
For this reason, using this method is almost always a bad idea unless you are really sure the optional contains a value.
`Optional.orElse(T other)`
it allows you to provide a default value for when the optional does not contain a value.
NOTE: the other value may be null.
`Optional.orElseGet(Supplier<? extends T> other)`
is the lazy counterpart of the orElse method,
because the supplier is invoked only if the optional contains no value.
You should use this method either when the default value is time-consuming to create or you want to be sure this is done only
if the optional is empty.
`Optional.orElseThrow(Supplier<? extends X> exceptionSupplier)`
is similar to the get() method in that it throws an exception
when the optional is empty, but in this case it allows you to choose the type of exception that you want to throw.
`Optional.ifPresent(Consumer<? super T> consumer)`
lets you execute the action given as argument if a value is present; otherwise no action is taken.
`Optional.isPresent()` returns true if the Optional contains a value, false otherwise.
{% highlight java linenos %}
public static void main(String[] args) {
Optional<String> opt1 = Optional.of("Hello");
String s = opt1.get();
System.out.println(opt1.isPresent() + " " + s);
Optional<String> opt2 = Optional.empty();
System.out.println("Value or default: " + opt2.orElse("Default"));
// With Supplier
System.out.println("Value or default: " + opt2.orElseGet(() -> "Some default"));
// Print only if opt1 has a value, Takes in a Consumer
opt1.ifPresent(System.out::println);
// Throws NPE
Optional<String> optNull = Optional.of(null);
}
{% endhighlight %}
:key: Output
true Hello
Value or default: Default
Value or default: Some default
Hello
Exception in thread "main" java.lang.NullPointerException
### 4.4. Perform calculations using methods: count, max, min, average, sum
##### Stream Data Methods
`Stream.min(...) and Stream.max(...) `
`Optional<T> min(Comparator<? super T> comp);`
`Optional<T> max(Comparator<? super T> comp);`
`Stream.count()`
`long count()`
:point_right: Note that `min` and `max` return an `Optional`. Also `average` and `sum` apply to primitive streams only :fire:
##### Primitive streams
`IntStream` - also used for short, char, byte, and boolean
`LongStream`, and
`DoubleStream` also for float
:point_right: Stream of objects can be mapped using `mapToInt`, `mapToLong`, or `mapToDouble` methods. :fire:
{% highlight java linenos %}
private static void primitiveStreams() {
List<Integer> list = Arrays.asList(20, 2, 72, 991, 100, -11);
IntStream is = list.stream().mapToInt(t -> t);
System.out.println("Max = " + is.max());
IntStream is2 = list.stream().mapToInt(t -> t);
System.out.println("Min = " + is2.min());
IntStream is3 = list.stream().mapToInt(t -> t);
System.out.println("Sum = " + is3.sum());
IntStream is4 = list.stream().mapToInt(t -> t);
System.out.println("Avg = " + is4.average().getAsDouble());
}
{% endhighlight %}
:key: Output
Max = OptionalInt[991]
Min = OptionalInt[-11]
Sum = 1174
Avg = 195.66666666666666
### 4.5. Sort a collection using lambda expressions
`sorted()` - This is a stateful intermediate operation.
Sorts the input stream that has elements of type Comparable(if not `ClassCastException` is thrown :fire: ) in natural order.
{% highlight java %}
Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)
{% endhighlight %}
Comparators can also be chained using
`.sorted(c1.thenComparing(c2))`
where
`Comparator<Employee> c1 = Comparator.comparing(e -> e.name.length());`
`Comparator<Employee> c2 = (e1, e2) -> e1.name.compareTo(e2.name);`
### 4.6. Save results to a collection by using the collect method and Collector class; including methods such as averagingDouble, groupingBy, joining, partitioningBy
* `joining` - Returns a Collector that concatenates the input elements into a String
{% highlight java %}
static Collector<CharSequence,?,String> joining()
- Returns a Collector that concatenates the input elements into a String, in encounter order.
static Collector<CharSequence,?,String> joining(CharSequence delimiter)
- Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.
static Collector<CharSequence,?,String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
- Returns a Collector that concatenates the input elements, separated by the specified delimiter,
with the specified prefix and suffix, in encounter order.
{% endhighlight %}
* `groupingBy` - Create a group of values
{% highlight java %}
static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)
- Returns a Collector implementing a "group by" operation on input elements of type T,
grouping elements according to a classification function, and returning the results in a Map.
static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier,
Collector<? super T,A,D> downstream)
- Returns a Collector implementing a cascaded "group by" operation on input elements of type T,
grouping elements according to a classification function, and then performing a reduction operation
on the values associated with a given key using the specified downstream Collector.
static <T,K,D,A,M extends Map<K,D>>
Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier,
Supplier<M> mapFactory, Collector<? super T,A,D> downstream)
- Returns a Collector implementing a cascaded "group by" operation on input elements of type T,
grouping elements according to a classification function, and then performing a reduction operation
on the values associated with a given key using the specified downstream Collector.
{% endhighlight %}
Example:
{% highlight java %}
Map<K, List<T> groupingBy(Function<? super T,? extends K> classifier)`
// Group employees by department
Map<Department, List<Employee>> byDept = emps.collect(Collectors.groupingBy(Employee::getDepartment));
{% endhighlight %}
* `partitioningBy`: Returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.
{% highlight java %}
static <T> Collector<T,?,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)
- Returns a Collector which partitions the input elements according to a Predicate,
and organizes them into a Map<Boolean, List<T>>.
static <T,D,A> Collector<T,?,Map<Boolean,D>> partitioningBy(Predicate<? super T> predicate,
Collector<? super T,A,D> downstream)
- Returns a Collector which partitions the input elements according to a Predicate,
reduces the values in each partition according to another Collector, and organizes them
into a Map<Boolean, D> whose values are the result of the downstream reduction.
{% endhighlight %}
Example:
{% highlight java %}
Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)
{% endhighlight %}
* `averagingDouble`:
{% highlight java %}
Double averagingDouble(ToDoubleFunction<? super T> mapper)
{% endhighlight %}
{% highlight java %}
static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)
- Returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements.
static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)
- Returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements.
static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)
- Returns a Collector that produces the arithmetic mean of a long-valued function applied to the input elements.
{% endhighlight %}
:fire: You should know all the overloaded methods given here.
[See Also](http://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html)
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part4)
--------------------------------
[Next Chapter - Parallel Streams](chapter5.html)
--------------------------------
<file_sep>/README.md
Oracle Certified Professional, Java SE 8 Upgrade
-----------------
[Exam Topics](http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-810#tabs-2)
######Contents
+ [My Notes](http://rahulsh1.github.io/ocp-java8)
+ sources : Contains code examples for each of the exam topics
###### References
+ http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
+ http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html
+ http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
+ http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
+ http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
+ http://docs.oracle.com/javase/tutorial/datetime/
+ http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html
+ http://java.boot.by/ocpjp8-upgrade-guide/
<file_sep>/pages/chapter3.md
---
layout: page
title: Chapter 3. Filtering Collections with Lambdas
description: 1Z0-810 Java SE8
comments: true
---
### 3.1. Develop the code that iterates a collection by using forEach; including method chaining
{% highlight java %}
public interface Iterable<T extends Object> {
public Iterator<T> iterator();
public default void forEach(Consumer<? super T> cnsmr) {
...
}
}
{% endhighlight %}
`java.util.Collection` interface extends `java.lang.Iterable`,
Collection Example:
{% highlight java %}
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Smith");
names.forEach(name -> System.out.println(name));
{% endhighlight %}
`java.util.Map` also has a *foreach*
{% highlight java %}
public interface Map<K extends Object, V extends Object> {
/**
* Performs the given action for each entry in this map until all entries have
* been processed or the action throws an exception.
*/
public default void forEach(BiConsumer<? super K, ? super V> bc) {
...
}
...
}
{% endhighlight %}
### 3.2. Describe the Stream interface and pipelines
Stream is a sequence of elements from a source supporting sequential and parallel aggregate operations.
#### Stream Pipelines
To perform a computation, stream operations are composed into a stream pipeline. :fire: A **stream pipeline** consists of:
- **a source** (which might be an array, a Collection, a generator function, an I/O channel, etc.)
- **zero or more intermediate operations** (which transform a Stream into another Stream, such as filter(Predicate p))
- **a terminal operation** (which produces a result or side-effect, such as count() or forEach(Consumer c))
Streams are *lazy*; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed.
Unlike a collection, a **stream is not a data structure**. It instead carries values from a source through a pipeline.
- `Intermediate operations`:
They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering,
but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
**Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed. **
- `Terminal operations`: such as Stream.forEach or Stream.count may traverse the stream to produce a result
##### Intermediate operations:
All intermediate operations are lazy - no results until terminal operation
:point_right: Intermediate operations are further divided into `stateless` and `stateful` operations.
Stateless operations, such as filter and map, retain no state from previously seen element when processing a
new element -- each element can be processed independently of operations on other elements.
Stateful operations, such as distinct and sorted, may incorporate state from previously seen elements when processing new elements.
:point_right: Stateful operations may need to process the entire input before producing a result.
For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
As a result, under parallel computation, some pipelines containing stateful intermediate operations may require multiple passes
on the data or may need to buffer significant data.
Pipelines containing exclusively stateless intermediate operations can be processed in a single pass,
whether sequential or parallel, with minimal data buffering.
- `Stream.filter()`
Stream<T> filter(Predicate<? super T> predicate);
- `Stream.map()`
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
- `Stream.distinct()`
Stream<T> distinct();
- `Stream.peek()`
{% highlight java %}
Stream<T> peek(Consumer<? super T> action)
{% endhighlight %}
Since peek returns the stream itself, nothing will happen if you do this: i.e no output
`list.stream().peek(s -> System.out.println(s.toUpperCase()));`
You can add terminal operations like foreach and then you see both peek and foreach output.
##### Terminal Operations
Stream API operations that returns a result or produce a side effect.
Commonly used terminal methods are forEach, toArray, min, max, findFirst, anyMatch, allMatch, etc.
You can identify terminal methods from the return type, **they will never return a Stream.**
:point_right: You can operate on a stream only once. :fire: Doing another terminal operation will result in :bulb:
`Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed`
- `Stream.collect()`
Stream.collect(...) is a terminal operation to transform the elements of the stream into a different kind of result, e.g. a java.util.List, java.util.Set or java.util.Map:
{% highlight java %}
<R, A> R collect(Collector<? super T, A, R> collector);
public interface Collector<T, A, R> {
Supplier<A> supplier();
BiConsumer<A, T> accumulator();
BinaryOperator<A> combiner();
Function<A, R> finisher();
}
{% endhighlight %}
Java 8 supports various built-in collectors via the Collectors final class.
- `Stream.min()` / `Stream.max()`
Optional<T> min(Comparator<? super T> comparator);`
Optional<T> max(Comparator<? super T> comparator);`
- `Stream.findAny()`
finds any element in the stream, This is a short circuit operation which stops processing of stream early.
Optional<T> findAny();
- `Stream.findFirst()`
Optional<T> findFirst();
- `Stream.count()`
long count();
### 3.3. Filter a collection using lambda expressions
The `Stream.filter(...)` methods is an intermediate operation.
It filters a stream on the basis of a given predicate and returns a stream object.
And again you can apply other stream methods to this instance. The method syntax is as follows
`Stream<T> filter(Predicate<? super T> predicate)`
### 3.4. Identify lambda operations that are lazy
Streams have two types of methods: intermediate and terminal, which work together.
The secret behind their laziness is that we chain multiple intermediate operations followed by a terminal operation.
Methods like `map()` and `filter()` are intermediate; calls to them return immediately and the lambda expressions provided to them are not evaluated right away
The `filter()` method does not look through all the elements in the collection in one shot.
Instead, it runs until it finds the first element that satisfies the condition given.
As soon as it finds an element, it passes that to the next method in the chain.
If the terminal operation got what it needed, the computation of the chain terminates.
:pushpin: What is the output of code below :question:
{% highlight java linenos %}
Stream<String> words = Stream.of("lower", "case", "text");
Stream<String> list2 = words
.peek(s -> System.out.println(s))
.map(s -> s.toUpperCase());
System.out.println(list2);
{% endhighlight %}
:boom:
> If you guessed, just all those words would be upper case :-1:
> If you guessed, both lower (due to peek) and upper case words :-1:
> If you guessed, no output :clap:
Since there is no terminal operation, there would be no output.
If you add a `foreach(System.out::println)` to above stream at the end, you will see all lower case words first and then all upper case words.
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part3)
--------------------------------
[Next Chapter - Collection Operations with Lambda](chapter4.html)
--------------------------------
<file_sep>/pages/chapter2.md
---
layout: page
title: Chapter 2. Using Built in Lambda Types
description: 1Z0-810 Java SE8
comments: true
---
### 2.1. Describe the built in interfaces included in Java 8 - java.util.function package
>New Package: `java.util.function` - Contains a lot of commonly used functional interfaces :fire:
##### java.util.function.Predicate
Represents a predicate (boolean-valued function) of one argument.
{% highlight java %}
public interface Predicate<T extends Object> {
boolean test(T t);
}
{% endhighlight %}
##### java.util.function.Consumer
Represents an operation that accepts a single input argument and returns no result.
{% highlight java %}
public interface Consumer<T extends Object> {
void accept(T t);
}
{% endhighlight %}
##### java.util.function.Function
Represents a function that accepts one argument and produces a result.
{% highlight java %}
public interface Function<T extends Object, R extends Object> {
R apply(T t);
}
{% endhighlight %}
##### java.util.function.Supplier
Represents a supplier of results. There is no requirement that a new or distinct result be returned each time the supplier is invoked.
{% highlight java %}
public interface Supplier<T extends Object> {
T get();
}
{% endhighlight %}
##### java.util.function.UnaryOperator
Represents an operation on a single operand that produces a result of the same type as its operand. This is a specialization of Function for the case where the operand and result are of the same type.
{% highlight java %}
public interface UnaryOperator<T extends Object> extends Function<T, T> {
}
{% endhighlight %}
:point_right: Know the above interfaces very well, the inputs as well as the output. :fire:
### 2.2. Develop code that uses Function interface
{% highlight java %}
public interface Function<T extends Object, R extends Object> {
R apply(T t);
}
{% endhighlight %}
Example:
{% highlight java linenos %}
Function<String, Boolean> f = s -> new Boolean(s);
System.out.println(f.apply("TRUE"));
System.out.println(f.apply("true"));
System.out.println(f.apply("Java8"));
System.out.println(f.apply(null));
{% endhighlight %}
### 2.3. Develop code that uses Consumer interface
{% highlight java %}
public interface Consumer<T extends Object> {
public void accept(T t);
}
{% endhighlight %}
Example:
{% highlight java linenos %}
public class ConsumerDemo {
static class Name {
String name;
Name(String nm) {
name = nm;
}
void setName(String nm) {
name = nm;
}
public String toString() {
return name;
}
}
public static void processList(List<Name> names, Consumer<Name> consumer) {
for (Name n : names) {
consumer.accept(n);
}
}
public static void main(String[] args) {
List<Name> list = Arrays.asList(new Name("a"), new Name("b"), new Name("c"), new Name("d"));
System.out.println(list);
Consumer<Name> capitalize = s -> s.setName(s.name.toUpperCase());
processList(list, capitalize);
System.out.println(list);
}
}
{% endhighlight %}
### 2.4. Develop code that uses Supplier interface
{% highlight java %}
public interface Supplier<T extends Object> {
T get();
}
{% endhighlight %}
Example:
Constructor reference (T::new)
- Much like a method reference, except it is a reference to a constructor instead of a method
- Constructor is not called just referenced.
- On get, the constructor will be called.
{% highlight java linenos %}
Supplier<String> sup = String::new;
System.out.println(sup); // com.jcp8.chapter.two.SupplierDemo$$Lambda$2/990368553@41629346
System.out.println(sup.get()); // ""
{% endhighlight %}
### 2.5. Develop code that uses UnaryOperator interface
{% highlight java %}
public interface UnaryOperator<T extends Object> extends Function<T, T> {
}
{% endhighlight %}
Example:
{% highlight java linenos %}
UnaryOperator<String> uo = s -> "Have a " + s;
System.out.print(uo.apply("good one"));
{% endhighlight %}
### 2.6. Develop code that uses Predicate interface
{% highlight java %}
public interface Predicate<T extends Object> {
boolean test(T t);
}
{% endhighlight %}
Example:
{% highlight java linenos %}
Predicate<String> boolTest = s -> new Boolean(s).booleanValue();
List<String> strList = Arrays.asList("TRUE", "true", null, "", "false", "TrUe");
processList(strList, boolTest);
private static void processList(List<String> list, Predicate<String> predicate) {
for (String s : list) {
System.out.println(s + " Test pass? " + predicate.test(s));
}
}
{% endhighlight %}
### 2.7. Develop the code that use primitive and binary variations of base interfaces of java.util.function package
A specialized version of the functional interfaces in order to avoid autoboxing operations when the inputs or outputs are primitives.
{% highlight java linenos %}
@FunctionalInterface
public interface IntPredicate {
boolean test(int i);
}
{% endhighlight %}
#### Mapping Table
You should know by just the Interface name, what parameter they accept and what they return.
> How to remember :question:
`Intxx` -> Will take int as an argument and return T or nothing depending on type
`ToIntxx` -> Will return int, and take in T as arg if it applies
| `Predicate<T>` | `Consumer<T>` | `Function<T, R>` | `Supplier<T>` | `UnaryOperator<T>` |
| ------------- | ------------- |-----------------|-----------------| -----------------|
| IntPredicate | IntConsumer | IntFunction<R> | IntSupplier | IntUnaryOperator |
| LongPredicate | LongConsumer | LongFunction<R> | LongSupplier | LongUnaryOperator|
| DoublePredicate | DoubleConsumer | DoubleFunction<R>| DoubleSupplier | DoubleUnaryOperator|
| - | - | - | BooleanSupplier | - |
##### Additional Function<T, R>
`IntToDoubleFunction` - Function that accepts an int-valued argument and produces a double-valued result.
`IntToLongFunction` - Function that accepts an int-valued argument and produces a long-valued result.
`LongToDoubleFunction` - Function that accepts a long-valued argument and produces a double-valued result.
`LongToIntFunction` - Function that accepts a long-valued argument and produces an int-valued result.
`ToIntFunction<T>` - Function that produces an int-valued result.
`ToDoubleFunction<T>` - Function that produces a double-valued result.
`ToLongFunction<T>` - Function that produces a long-valued result.
#### Binary Interfaces - Takes two inputs instead of one
| | `Predicate<T>` | `Consumer<T>` | `Function<T, R>` | `Supplier<T>` | `UnaryOperator<T>` |
|-----| ------------- | ------------- |-----------------|-----------------|-------------------|
| Type| BiPredicate<L, R> | BiConsumer<T, U> |BiFunction<T, U, R> | - | BinaryOperator<T> |
|Params| (L, R) -> boolean | (T, U) -> void | (T, U) -> R | - | (T, T) -> T |
##### Additional Ones
> Binary Operators
`IntBinaryOperator` - Function operation upon two int-valued operands and producing an int-valued result.
`LongBinaryOperator` - Function operation upon two long-valued operands and producing a long-valued result.
`DoubleBinaryOperator` - Function operation upon two double-valued operands and producing a double-valued result.
> Object Consumers
`ObjIntConsumer<T>` - Function operation that accepts an Object-valued and an int-valued argument and returns no result.
`ObjLongConsumer<T>` - Function operation that accepts an Object-valued and a long-valued argument and returns no result.
`ObjDoubleConsumer<T>` - Function operation that accepts an Object-valued and a double-valued argument and returns no result.
> To Primitive Bi-Functions
`ToIntBiFunction<T, U>` - Function that accepts two arguments and produces an int-valued result.
`ToLongBiFunction<T, U>` - Function that accepts two arguments and produces a long-valued result.
`ToDoubleBiFunction<T, U>` - Function that accepts two arguments and produces a double-valued result.
:point_right: You have to know each of the above types for the exam, with their arguments and return types. :fire:
### 2.8. Develop the code that use method reference; including refactor the code that use Lambda expression to use method references
##### Method References
- shorthand for lambdas calling only a specific method
- the target reference is placed before the delimiter :: and the name of the method is provided after it.
- String::toUpperCase is a method reference to the method toUpperCase defined in the String class, shorthand for the lambda expression (String s) -> s.toUpperCase();
Four Types:
**ContainingClass::staticMethodName** - Reference to a static method
**ContainingObject::instanceMethodName** - Reference to an instance method of a particular object
**ContainingType::methodName** - Reference to an instance method of an arbitrary object of a particular type
**ClassName::new** - Reference to a constructor
###### Reference to a static method - `Class::staticMethodName`
{% highlight java %}
IntFunction<String> f1 = (i) -> String.valueOf(i);
System.out.println(f1.apply(100));
IntFunction<String> f1 = String::valueOf;
System.out.println(f1.apply(100));
{% endhighlight %}
###### Reference to a constructor - `ClassName::new`
{% highlight java %}
Function<char[], String> f1 = String::new;
System.out.println(f1.apply(new char[] {'H', 'i'}));
{% endhighlight %}
###### Reference to an instance method of an arbitrary object of a particular type - `Class::instanceMethodName`
Reference to an instance method of an arbitrary object of a particular type refers to a non-static method that is not bound to a receiver.
{% highlight java %}
String::trim // (String str) -> { return str.trim(); }.
BiFunction<String, String, Boolean> f1 = String::equalsIgnoreCase;
System.out.println(f1.apply("Hello", "HELLO"))
{% endhighlight %}
###### Reference to an instance method of a particular object - `Object::instanceMethodName`
Reference to an instance method of a particular object refers to a non-static method that is bound to a receiver.
This kind of method references refers to a situation when you are calling a method in a lambda to an external object that already exists
{% highlight java %}
Integer i = new Integer(1);
Supplier<String> f1 = i::toString;
System.out.println(f1.get());
{% endhighlight %}
:bulb: Know when to use which type of method reference.
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part2)
--------------------------------
[Next Chapter - Filtering Collections with Lambdas](chapter3.html)
--------------------------------
<file_sep>/sources/src/main/java/ocp/study/part8/ZonesDemo.java
package ocp.study.part8;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;
public class ZonesDemo {
static void zonedemo() {
Set<String> allZones = ZoneId.getAvailableZoneIds();
// allZones.stream().forEach(System.out::println);
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.of("America/Los_Angeles"));
ZonedDateTime zdt2 = ZonedDateTime.of(ldt, ZoneId.of("Asia/Macau"));
ZonedDateTime zdt3 = ZonedDateTime.of(ldt, ZoneId.of("Europe/Malta"));
System.out.println(ldt + " zdt= " + zdt + " zone offset: " + zdt.getOffset());
System.out.println(ldt + " zdt= " + zdt2 + " zone offset: " + zdt2.getOffset());
System.out.println(ldt + " zdt= " + zdt3 + " zone offset: " + zdt3.getOffset());
}
static void offsetdatetime() {
// Find the last Thursday in July 2013.
LocalDateTime localDate = LocalDateTime.of(2015, Month.APRIL, 25, 11, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
OffsetDateTime lastThursday = offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf(offsetDate + " The last Thursday in April 2015 is the %sth.%n", lastThursday.getDayOfMonth());
}
public static void main(String[] args) {
zonedemo();
offsetdatetime();
}
}
<file_sep>/index.md
---
layout: page
title: Notes for 1Z0-810 Java SE8 Upgrade
description: 1Z0-810 JavaSE8
---
See [Exam Topics](http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=5001&get_params=p_exam_id:1Z0-810#tabs-2)
##### Notes
- [Chapter 1 - Lambda Expressions](pages/chapter1.html)
- [Chapter 2 - Using Built in Lambda Types](pages/chapter2.html)
- [Chapter 3 - Filtering Collections with Lambdas](pages/chapter3.html)
- [Chapter 4 - Collection Operations with Lambda](pages/chapter4.html)
- [Chapter 5 - Parallel Streams](pages/chapter5.html)
- [Chapter 6 - Lambda Cookbook](pages/chapter6.html)
- [Chapter 7 - Method Enhancements](pages/chapter7.html)
- [Chapter 8 - Use Java SE 8 Date/Time API](pages/chapter8.html)
- [Chapter 9 - JavaScript on Java with Nashorn](pages/chapter9.html)
##### Contents
+ sources : Code examples for each of the exam topics
##### References/Credits
+ [Mikalai Zaikin Guide](http://java.boot.by/ocpjp8-upgrade-guide/)
+ [Java tutorial Nested classes](http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html)
+ [Java tutorial Local classes](http://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html)
+ [Java tutorial Lambda Expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)
+ [Java docs java.util.function ](http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html)
+ [Java tutorial Default Methods](http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html)
+ [Java tutorial Datetime](http://docs.oracle.com/javase/tutorial/datetime)
+ [Java tutorial Nashorn api](http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/api.html)
---
Pages created using [simple_site](http://github.com/kbroman/simple_site)
<file_sep>/sources/src/main/java/ocp/study/part6/FilesDemo.java
package ocp.study.part6;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FilesDemo {
private static String ROOT_DIR = "s:/tmp";
static void files() throws IOException {
System.out.println("--> List output:");
// list(...)
Files.list(Paths.get(ROOT_DIR))
.filter(p -> p.toString().contains("sh"))
.forEach(System.out::println);
System.out.println("--> Walk output:");
Files.walk(Paths.get(ROOT_DIR), 3, FileVisitOption.FOLLOW_LINKS)
.filter(p -> p.toString().contains("ai"))
.forEach(System.out::println);
System.out.println("--> find output:");
try (Stream<Path> p3 = Files.find(Paths.get(ROOT_DIR), 3, (path, attr) -> (path.toString().contains("ail")))){
p3.forEach(System.out::println);
}
System.out.println("--> lines output:");
try (Stream<String> lines = Files.lines(Paths.get(ROOT_DIR + "/EchoWorker.java"))) {
lines.filter(s -> s.contains("public")).forEach(System.out::println);
}
}
public static void main(String[] args) throws IOException {
files();
}
}
<file_sep>/pages/chapter9.md
---
layout: page
title: Chapter 9. JavaScript on Java with Nashorn
description: 1Z0-810 Java SE8
comments: true
---
### 9.1 Develop Javascript code that creates and uses Java members such as Java objects, methods, JavaBeans, Arrays, Collections, Interfaces.
Nashorn is the only JavaScript engine included in the JDK. However, you can use any script engine compliant with JSR 223
To get an instance of the Nashorn engine, pass in "nashorn".
Alternatively, you can use any of the following: "Nashorn", "javascript", "JavaScript", "js", "JS", "ecmascript", "ECMAScript".
Command line tools:
{% highlight java %}
jrunscript : Invokes any available script engine
jjs : To evaluate a script file using Nashorn,
pass the name of the script file to the jjs tool.
{% endhighlight %}
{% highlight java %}
jjs> java.lang
[JavaPackage java.lang]
jjs> typeof java.lang
object
jjs> java.lang.System
[JavaClass java.lang.System]
jjs> typeof java.lang.System
function
{% endhighlight %}
Nashorn interprets Java packages as JavaPackage objects, and Java classes as JavaClass function objects, which can be used as constructors for the classes.
The `Java.type()` function takes a string with the fully qualified Java class name, and returns the corresponding JavaClass function object.
{% highlight java %}
jjs> var HashMap = Java.type("java.util.HashMap")
jjs> var mapDef = new HashMap()
jjs> mapDef.put('a', 'val');
jjs> mapDef.get('a');
val
jjs> mapDef.get('b');
null
jjs> mapDef.put('b', 'val2');
null
jjs> mapDef.get('b');
val2
{% endhighlight %}
##### Accessing Class and Instance Members
{% highlight java %}
jjs> Java.type("java.lang.Math").PI
3.141592653589793
jjs> Java.type("java.lang.System").currentTimeMillis()
1429378149988
{% endhighlight %}
##### Extending Java Classes/Interfaces
You can extend a class using the Java.extend() function that takes a Java type as the first argument and
method implementations (in the form of JavaScript functions) as the other arguments.
Below shows a script that extends the java.lang.Runnable interface and uses it to construct a new java.lang.Thread object.
{% highlight java %}
var Run = Java.type("java.lang.Runnable");
var MyRun = Java.extend(Run, {
run: function() {
print("Run in separate thread");
}
});
var Thread = Java.type("java.lang.Thread");
var th = new Thread(new MyRun());
{% endhighlight %}
Nashorn can automatically extend single abstract method (SAM) classes if you provide the function for implementing the method as the argument to the constructor.
{% highlight java %}
var Thread = Java.type("java.lang.Thread")
var th = new Thread(function() print("Run in a separate thread"))
{% endhighlight %}
##### Restricting Script Access to Specified Java Classes
The `jdk.nashorn.api.scripting.ClassFilter` interface enables you to restrict access to specified Java classes from scripts run by a Nashorn script engine
--------------------------------
:memo: [Code examples](https://github.com/rahulsh1/ocp-java8/tree/master/sources/src/ocp/study/part9)
--------------------------------
[Previous Chapter 8. Use Java SE 8 Date/Time API](chapter8.html)
--------------------------------
<file_sep>/sources/src/main/java/ocp/study/part2/ConsumerDemo.java
package ocp.study.part2;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerDemo {
static class Name {
String name;
Name(String nm) {
name = nm;
}
void setName(String nm) {
name = nm;
}
public String toString() {
return name;
}
}
public static void processList(List<Name> names, Consumer<Name> consumer) {
// One way
for (Name n : names) {
consumer.accept(n);
}
// or using method references
// names.forEach(consumer::accept);
}
public static void main(String[] args) {
List<Name> list = Arrays.asList(new Name("a"), new Name("b"), new Name("c"), new Name("d"));
System.out.println(list);
Consumer<Name> capitalize = s -> s.setName(s.name.toUpperCase());
processList(list, capitalize);
System.out.println(list);
}
} | c0baafbbc3317671c75ec15392cb09c00eccea28 | [
"Markdown",
"Java"
] | 19 | Markdown | rahulsh1/ocp-java8 | bfee2adabf131f38dc5af4f57b0fa538e5c0446b | 11b9c4540d0c28ea63e8e0e180c4e4a2f0feee5a |
refs/heads/master | <file_sep>
import React from 'react';
import {shallow, mount} from 'enzyme';
import Header from './header';
import TopNav from './top-nav';
describe(`Header component test`, function() {
it('renders Header properly.', function() {
shallow(<Header />);
});
});<file_sep>
import React from 'react';
import {shallow} from 'enzyme';
import GuessCount from './guess-count';
describe(`GuessCount component testing.`, function() {
it(`renders GuessCount.`, function() {
shallow(<GuessCount />);
});
it(`properly populates guessCount and guessNoun from props when guessCount is plural.`, function() {
const guessCount = 2;
const wrapper = shallow(<GuessCount guessCount={guessCount} />);
expect(wrapper.contains(<h2 id="guessCount">You've made <span id="count">{guessCount}</span> guesses!</h2>)).toEqual(true);
});
it(`properly populates guessCount and guessNoun from props when guessCount is 1.`, function() {
const guessCount = 1;
const wrapper = shallow(<GuessCount guessCount={guessCount} />);
expect(wrapper.contains(<h2 id="guessCount">You've made <span id="count">{guessCount}</span> guess!</h2>)).toEqual(true);
});
});<file_sep>
import React from 'react';
import {shallow} from 'enzyme';
import AuralStatus from './aural-status';
describe(`AuralStatus component test`, function() {
it(`renders AuralStatus`, function() {
shallow(<AuralStatus />);
});
it(`Has props on proper initialization`, function() {
const auralStatus = "thisStatus";
const wrapper = shallow(<AuralStatus auralStatus={auralStatus} />);
expect(wrapper.hasClass(`visuallyhidden`)).toEqual(true);
expect(wrapper.contains(<p
id="status-readout"
className="visuallyhidden"
aria-live="assertive"
aria-atomic="true"
>
{auralStatus}
</p>));
});
})<file_sep>
import React from 'react';
import {shallow, mount} from 'enzyme';
import GuessList from './guess-list';
describe(`GuessList component testing.`, function() {
it(`renders GuessList.`, function() {
const guesses = [6, 4, 2, 19];
shallow(<GuessList guesses={guesses} />);
});
it(`makes <li> elements for each guess in the guess list.`, function() {
const guesses = [6, 4, 2, 19];
/* Tried doing this but failed.
let listedGuesses;
for (let i=1; i < guesses.length; i++){
listedGuesses += <li key={i}>{guesses[i]}</li>;
}
*/
const wrapper = shallow(<GuessList guesses={guesses} />);
expect(wrapper.contains(
<ul id="guessList" className="guessBox clearfix">
<li key="0">
{guesses[0]}
</li>
<li key={1}>
{guesses[1]}
</li>
<li key={2}>
{guesses[2]}
</li>
<li key={3}>
{guesses[3]}
</li>
</ul>
)).toEqual(true);
});
});<file_sep>
import React from 'react';
import {shallow, mount} from 'enzyme';
import GuessSection from './guess-section';
describe(`GuessSection component test`, function() {
it('renders GuessSection properly.', function() {
shallow(<GuessSection />);
});
});<file_sep>
import React from 'react';
import {shallow, mount} from 'enzyme';
import TopNav from './top-nav';
describe(`TopNav component test`, function() {
it('renders TopNav properly.', function() {
shallow(<TopNav />);
});
it(`should fire the onClick callback of onGenerateAuralUpdate.`, function() {
const callback = jest.fn();
const wrapper = shallow(<TopNav onGenerateAuralUpdate={callback}/>);
wrapper.find(`.status-link`).simulate("click");
expect(callback).toHaveBeenCalled();
});
it(`should fire the onClick callback of onRestartGame.`, function() {
const callback = jest.fn();
const wrapper = shallow(<TopNav onRestartGame={callback}/>);
wrapper.find(`.new`).simulate("click");
expect(callback).toHaveBeenCalled();
});
});<file_sep>
import React from 'react';
import {shallow, mount} from 'enzyme';
import Game from './game';
import Header from './header';
import TopNav from './top-nav';
describe(`<Game /> component testing`, function() {
it(`renders Game.`, function() {
shallow(<Game />);
});
it(`proprely sets Game initial state`, function() {
const wrapper = shallow(<Game />);
expect(wrapper.state(`feedback`)).toEqual('Make your guess!');
console.log(`wrapper.instance().state.correctAnswer=`, wrapper.instance().state.correctAnswer);
//expect(wrapper.instance().state.correctAnswer).toEqual(Number);
});
it('Should run the generateAuralUpdate() method.', function() {
const guesses = [6, 4, 2, 19];
const feedback = "You're getting warmer.";
const wrapper = shallow(<Game />);
wrapper.instance().state.guesses = guesses;
wrapper.instance().state.feedback = feedback;
wrapper.instance().generateAuralUpdate();
//wrapper.update();
const expectedAuralStatus = `Here's the status of the game right now: ${feedback} You've made ${guesses.length} guesses. In order of most- to least-recent, they are: ${guesses.join(', ')}`;
expect(wrapper.instance().state.auralStatus).toEqual(expectedAuralStatus);
});
it('Should run the restartGame() method.', function() {
const oldGuesses = [6, 4, 2, 19];
const oldFeedback = "You're getting warmer.";
const oldAuralStatus = "Something";
const wrapper = shallow(<Game />);
wrapper.instance().state.guesses = oldGuesses;
wrapper.instance().state.feedback = oldFeedback;
wrapper.instance().state.auralStatus = oldAuralStatus;
wrapper.update();
wrapper.instance().restartGame();
expect(wrapper.instance().state.guesses).toEqual([]);
expect(wrapper.instance().state.feedback).toEqual('Make your guess!');
expect(wrapper.instance().state.auralStatus).toEqual("");
});
it('Should run the makeGuess() method.', function() {
const oldGuesses = [6, 4, 2, 19];
const guess = 70;
const wrapper = shallow(<Game />);
wrapper.instance().state.guesses = oldGuesses;
wrapper.update();
wrapper.instance().makeGuess(guess);
expect(wrapper.instance().state.guesses).toEqual([6, 4, 2, 19, 70]);
//expect(wrapper.instance().state.feedback).toEqual('Make your guess!'); find To NOT equal
});
});
// !!! Check game to see if we can verify that type Number or int of correctAnswer after it's randomly generated.
// !!! Check game, apparently when testing generateAuralUpdate() I don't need to update()?
// !!! Check guess-list to see if I can get the for loop to work properly.
// !!! Check aural-status-test to see if we can verify the id's value.
/*
it(``, function() {
});
*/ | 737fe1c7df5ea944bf26b96b42bd28ebf8900379 | [
"JavaScript"
] | 7 | JavaScript | spoofBlue/HotAndColdWithTesting | 6e64a6ccaa10a4a3df99178ab477bd96b426465f | e422800efc8748faba9d854ff6216d89567fd4f1 |
refs/heads/master | <repo_name>gabmur92/ed<file_sep>/JSuma/src/jsuma.java
public class jsuma {
public static void main(String[] args) {
int contador =1;
while(contador<=5) {
System.out.println("contador = "+contador);
contador=contador+1;
}
System.out.println("fin de programa");
// for(int contador = 1; contador<=5; contador++)
// System.out.println("contador = "+contador);
//
//
// System.out.println("fin de programa");
}
}
<file_sep>/Ccalculadora/Ccalculadora/Ccalculadora/gtk-gui/MainWindow.cs
// This file has been generated by the GUI designer. Do not modify.
public partial class MainWindow
{
private global::Gtk.VBox vbox1;
private global::Gtk.Label Calculadora;
private global::Gtk.VBox vbox3;
private global::Gtk.Entry Pantalla;
private global::Gtk.HBox hbox5;
private global::Gtk.Button Bvaciar;
private global::Gtk.Button BC;
private global::Gtk.HBox hbox4;
private global::Gtk.Button BP;
private global::Gtk.Button BCero;
private global::Gtk.HBox hbox7;
private global::Gtk.Button BI;
private global::Gtk.Button BR;
private global::Gtk.VBox vbox2;
private global::Gtk.HBox hbox3;
private global::Gtk.Button B7;
private global::Gtk.Button B8;
private global::Gtk.HBox hbox8;
private global::Gtk.Button B9;
private global::Gtk.Button BD;
private global::Gtk.HBox hbox2;
private global::Gtk.Button B4;
private global::Gtk.Button B5;
private global::Gtk.HBox hbox9;
private global::Gtk.Button B6;
private global::Gtk.Button BM;
private global::Gtk.HBox hbox1;
private global::Gtk.Button B1;
private global::Gtk.Button B2;
private global::Gtk.HBox hbox10;
private global::Gtk.Button B3;
private global::Gtk.Button BS;
protected virtual void Build()
{
global::Stetic.Gui.Initialize(this);
// Widget MainWindow
this.Name = "MainWindow";
this.Title = global::Mono.Unix.Catalog.GetString("MainWindow");
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
this.BorderWidth = ((uint)(18));
// Container child MainWindow.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
// Container child vbox1.Gtk.Box+BoxChild
this.Calculadora = new global::Gtk.Label();
this.Calculadora.Name = "Calculadora";
this.Calculadora.LabelProp = global::Mono.Unix.Catalog.GetString("calculadora");
this.vbox1.Add(this.Calculadora);
global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.Calculadora]));
w1.Position = 0;
w1.Expand = false;
w1.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
// Container child vbox3.Gtk.Box+BoxChild
this.Pantalla = new global::Gtk.Entry();
this.Pantalla.CanFocus = true;
this.Pantalla.Name = "Pantalla";
this.Pantalla.IsEditable = false;
this.Pantalla.InvisibleChar = '•';
this.vbox3.Add(this.Pantalla);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.Pantalla]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.hbox5 = new global::Gtk.HBox();
this.hbox5.Name = "hbox5";
this.hbox5.Spacing = 6;
// Container child hbox5.Gtk.Box+BoxChild
this.Bvaciar = new global::Gtk.Button();
this.Bvaciar.WidthRequest = 132;
this.Bvaciar.HeightRequest = 40;
this.Bvaciar.CanFocus = true;
this.Bvaciar.Name = "Bvaciar";
this.Bvaciar.UseUnderline = true;
this.Bvaciar.Label = global::Mono.Unix.Catalog.GetString("VACIAR");
this.hbox5.Add(this.Bvaciar);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.Bvaciar]));
w3.Position = 0;
w3.Expand = false;
w3.Fill = false;
// Container child hbox5.Gtk.Box+BoxChild
this.BC = new global::Gtk.Button();
this.BC.WidthRequest = 40;
this.BC.HeightRequest = 40;
this.BC.CanFocus = true;
this.BC.Name = "BC";
this.BC.UseUnderline = true;
this.BC.Label = global::Mono.Unix.Catalog.GetString("C");
this.hbox5.Add(this.BC);
global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox5[this.BC]));
w4.Position = 1;
w4.Expand = false;
w4.Fill = false;
this.vbox3.Add(this.hbox5);
global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.hbox5]));
w5.Position = 1;
w5.Expand = false;
w5.Fill = false;
// Container child vbox3.Gtk.Box+BoxChild
this.hbox4 = new global::Gtk.HBox();
this.hbox4.Name = "hbox4";
this.hbox4.Spacing = 6;
// Container child hbox4.Gtk.Box+BoxChild
this.BP = new global::Gtk.Button();
this.BP.WidthRequest = 40;
this.BP.HeightRequest = 40;
this.BP.CanFocus = true;
this.BP.Name = "BP";
this.BP.UseUnderline = true;
this.BP.Label = global::Mono.Unix.Catalog.GetString(".");
this.hbox4.Add(this.BP);
global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.BP]));
w6.Position = 0;
w6.Expand = false;
w6.Fill = false;
// Container child hbox4.Gtk.Box+BoxChild
this.BCero = new global::Gtk.Button();
this.BCero.WidthRequest = 40;
this.BCero.HeightRequest = 40;
this.BCero.CanFocus = true;
this.BCero.Name = "BCero";
this.BCero.UseUnderline = true;
this.BCero.Label = global::Mono.Unix.Catalog.GetString("0");
this.hbox4.Add(this.BCero);
global::Gtk.Box.BoxChild w7 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.BCero]));
w7.Position = 1;
w7.Expand = false;
w7.Fill = false;
// Container child hbox4.Gtk.Box+BoxChild
this.hbox7 = new global::Gtk.HBox();
this.hbox7.Name = "hbox7";
this.hbox7.Spacing = 6;
// Container child hbox7.Gtk.Box+BoxChild
this.BI = new global::Gtk.Button();
this.BI.WidthRequest = 40;
this.BI.HeightRequest = 40;
this.BI.CanFocus = true;
this.BI.Name = "BI";
this.BI.UseUnderline = true;
this.BI.Label = global::Mono.Unix.Catalog.GetString("=");
this.hbox7.Add(this.BI);
global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.hbox7[this.BI]));
w8.Position = 0;
w8.Expand = false;
w8.Fill = false;
// Container child hbox7.Gtk.Box+BoxChild
this.BR = new global::Gtk.Button();
this.BR.WidthRequest = 40;
this.BR.HeightRequest = 40;
this.BR.CanFocus = true;
this.BR.Name = "BR";
this.BR.UseUnderline = true;
this.BR.Label = global::Mono.Unix.Catalog.GetString("-");
this.hbox7.Add(this.BR);
global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.hbox7[this.BR]));
w9.Position = 1;
w9.Expand = false;
w9.Fill = false;
this.hbox4.Add(this.hbox7);
global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.hbox4[this.hbox7]));
w10.Position = 2;
w10.Expand = false;
w10.Fill = false;
this.vbox3.Add(this.hbox4);
global::Gtk.Box.BoxChild w11 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.hbox4]));
w11.Position = 2;
w11.Expand = false;
w11.Fill = false;
this.vbox1.Add(this.vbox3);
global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.vbox3]));
w12.Position = 1;
w12.Expand = false;
w12.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.vbox2 = new global::Gtk.VBox();
this.vbox2.Name = "vbox2";
this.vbox2.Spacing = 6;
// Container child vbox2.Gtk.Box+BoxChild
this.hbox3 = new global::Gtk.HBox();
this.hbox3.Name = "hbox3";
this.hbox3.Spacing = 6;
// Container child hbox3.Gtk.Box+BoxChild
this.B7 = new global::Gtk.Button();
this.B7.WidthRequest = 40;
this.B7.HeightRequest = 40;
this.B7.CanFocus = true;
this.B7.Name = "B7";
this.B7.UseUnderline = true;
this.B7.Label = global::Mono.Unix.Catalog.GetString("7");
this.hbox3.Add(this.B7);
global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.B7]));
w13.Position = 0;
w13.Expand = false;
w13.Fill = false;
// Container child hbox3.Gtk.Box+BoxChild
this.B8 = new global::Gtk.Button();
this.B8.WidthRequest = 40;
this.B8.HeightRequest = 40;
this.B8.CanFocus = true;
this.B8.Name = "B8";
this.B8.UseUnderline = true;
this.B8.Label = global::Mono.Unix.Catalog.GetString("8");
this.hbox3.Add(this.B8);
global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.B8]));
w14.Position = 1;
w14.Expand = false;
w14.Fill = false;
// Container child hbox3.Gtk.Box+BoxChild
this.hbox8 = new global::Gtk.HBox();
this.hbox8.Name = "hbox8";
this.hbox8.Spacing = 6;
// Container child hbox8.Gtk.Box+BoxChild
this.B9 = new global::Gtk.Button();
this.B9.WidthRequest = 40;
this.B9.HeightRequest = 40;
this.B9.CanFocus = true;
this.B9.Name = "B9";
this.B9.UseUnderline = true;
this.B9.Label = global::Mono.Unix.Catalog.GetString("9");
this.hbox8.Add(this.B9);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.hbox8[this.B9]));
w15.Position = 0;
w15.Expand = false;
w15.Fill = false;
// Container child hbox8.Gtk.Box+BoxChild
this.BD = new global::Gtk.Button();
this.BD.WidthRequest = 40;
this.BD.HeightRequest = 40;
this.BD.CanFocus = true;
this.BD.Name = "BD";
this.BD.UseUnderline = true;
this.BD.Label = global::Mono.Unix.Catalog.GetString("/");
this.hbox8.Add(this.BD);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.hbox8[this.BD]));
w16.Position = 1;
w16.Expand = false;
w16.Fill = false;
this.hbox3.Add(this.hbox8);
global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.hbox3[this.hbox8]));
w17.Position = 2;
w17.Expand = false;
w17.Fill = false;
this.vbox2.Add(this.hbox3);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.hbox3]));
w18.Position = 0;
w18.Expand = false;
w18.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.hbox2 = new global::Gtk.HBox();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.B4 = new global::Gtk.Button();
this.B4.WidthRequest = 40;
this.B4.HeightRequest = 40;
this.B4.CanFocus = true;
this.B4.Name = "B4";
this.B4.UseUnderline = true;
this.B4.Label = global::Mono.Unix.Catalog.GetString("4");
this.hbox2.Add(this.B4);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.B4]));
w19.Position = 0;
w19.Expand = false;
w19.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.B5 = new global::Gtk.Button();
this.B5.WidthRequest = 40;
this.B5.HeightRequest = 40;
this.B5.CanFocus = true;
this.B5.Name = "B5";
this.B5.UseUnderline = true;
this.B5.Label = global::Mono.Unix.Catalog.GetString("5");
this.hbox2.Add(this.B5);
global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.B5]));
w20.Position = 1;
w20.Expand = false;
w20.Fill = false;
// Container child hbox2.Gtk.Box+BoxChild
this.hbox9 = new global::Gtk.HBox();
this.hbox9.Name = "hbox9";
this.hbox9.Spacing = 6;
// Container child hbox9.Gtk.Box+BoxChild
this.B6 = new global::Gtk.Button();
this.B6.WidthRequest = 40;
this.B6.HeightRequest = 40;
this.B6.CanFocus = true;
this.B6.Name = "B6";
this.B6.UseUnderline = true;
this.B6.Label = global::Mono.Unix.Catalog.GetString("6");
this.hbox9.Add(this.B6);
global::Gtk.Box.BoxChild w21 = ((global::Gtk.Box.BoxChild)(this.hbox9[this.B6]));
w21.Position = 0;
w21.Expand = false;
w21.Fill = false;
// Container child hbox9.Gtk.Box+BoxChild
this.BM = new global::Gtk.Button();
this.BM.WidthRequest = 40;
this.BM.HeightRequest = 40;
this.BM.CanFocus = true;
this.BM.Name = "BM";
this.BM.UseUnderline = true;
this.BM.Label = global::Mono.Unix.Catalog.GetString("*");
this.hbox9.Add(this.BM);
global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.hbox9[this.BM]));
w22.Position = 1;
w22.Expand = false;
w22.Fill = false;
this.hbox2.Add(this.hbox9);
global::Gtk.Box.BoxChild w23 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.hbox9]));
w23.Position = 2;
w23.Expand = false;
w23.Fill = false;
this.vbox2.Add(this.hbox2);
global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.hbox2]));
w24.Position = 1;
w24.Expand = false;
w24.Fill = false;
// Container child vbox2.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.B1 = new global::Gtk.Button();
this.B1.WidthRequest = 40;
this.B1.HeightRequest = 40;
this.B1.CanFocus = true;
this.B1.Name = "B1";
this.B1.UseUnderline = true;
this.B1.Label = global::Mono.Unix.Catalog.GetString("1");
this.hbox1.Add(this.B1);
global::Gtk.Box.BoxChild w25 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.B1]));
w25.Position = 0;
w25.Expand = false;
w25.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.B2 = new global::Gtk.Button();
this.B2.WidthRequest = 40;
this.B2.HeightRequest = 40;
this.B2.CanFocus = true;
this.B2.Name = "B2";
this.B2.UseUnderline = true;
this.B2.Label = global::Mono.Unix.Catalog.GetString("2");
this.hbox1.Add(this.B2);
global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.B2]));
w26.Position = 1;
w26.Expand = false;
w26.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.hbox10 = new global::Gtk.HBox();
this.hbox10.Name = "hbox10";
this.hbox10.Spacing = 6;
// Container child hbox10.Gtk.Box+BoxChild
this.B3 = new global::Gtk.Button();
this.B3.WidthRequest = 40;
this.B3.HeightRequest = 40;
this.B3.CanFocus = true;
this.B3.Name = "B3";
this.B3.UseUnderline = true;
this.B3.Label = global::Mono.Unix.Catalog.GetString("3");
this.hbox10.Add(this.B3);
global::Gtk.Box.BoxChild w27 = ((global::Gtk.Box.BoxChild)(this.hbox10[this.B3]));
w27.Position = 0;
w27.Expand = false;
w27.Fill = false;
// Container child hbox10.Gtk.Box+BoxChild
this.BS = new global::Gtk.Button();
this.BS.WidthRequest = 40;
this.BS.HeightRequest = 40;
this.BS.CanFocus = true;
this.BS.Name = "BS";
this.BS.UseUnderline = true;
this.BS.Label = global::Mono.Unix.Catalog.GetString("+");
this.hbox10.Add(this.BS);
global::Gtk.Box.BoxChild w28 = ((global::Gtk.Box.BoxChild)(this.hbox10[this.BS]));
w28.Position = 1;
w28.Expand = false;
w28.Fill = false;
this.hbox1.Add(this.hbox10);
global::Gtk.Box.BoxChild w29 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.hbox10]));
w29.Position = 2;
w29.Expand = false;
w29.Fill = false;
this.vbox2.Add(this.hbox1);
global::Gtk.Box.BoxChild w30 = ((global::Gtk.Box.BoxChild)(this.vbox2[this.hbox1]));
w30.Position = 2;
w30.Expand = false;
w30.Fill = false;
this.vbox1.Add(this.vbox2);
global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.vbox2]));
w31.Position = 2;
w31.Expand = false;
w31.Fill = false;
this.Add(this.vbox1);
if ((this.Child != null))
{
this.Child.ShowAll();
}
this.DefaultWidth = 214;
this.DefaultHeight = 316;
this.Show();
this.DeleteEvent += new global::Gtk.DeleteEventHandler(this.OnDeleteEvent);
this.Bvaciar.Clicked += new global::System.EventHandler(this.OnBvaciarClicked);
this.BC.Clicked += new global::System.EventHandler(this.OnBCClicked);
this.BP.Clicked += new global::System.EventHandler(this.OnBPClicked);
this.BCero.Clicked += new global::System.EventHandler(this.OnBCeroClicked);
this.BI.Clicked += new global::System.EventHandler(this.OnBIClicked);
this.BR.Clicked += new global::System.EventHandler(this.OnBRClicked);
this.B7.Clicked += new global::System.EventHandler(this.OnB7Clicked);
this.B8.Clicked += new global::System.EventHandler(this.OnB8Clicked);
this.B9.Clicked += new global::System.EventHandler(this.OnB9Clicked);
this.BD.Clicked += new global::System.EventHandler(this.OnBDClicked);
this.B4.Clicked += new global::System.EventHandler(this.OnB4Clicked);
this.B5.Clicked += new global::System.EventHandler(this.OnB5Clicked);
this.B6.Clicked += new global::System.EventHandler(this.OnB6Clicked);
this.BM.Clicked += new global::System.EventHandler(this.OnBMClicked);
this.B1.Clicked += new global::System.EventHandler(this.OnB1Clicked);
this.B2.Clicked += new global::System.EventHandler(this.OnB2Clicked);
this.B3.Clicked += new global::System.EventHandler(this.OnB3Clicked);
this.BS.Clicked += new global::System.EventHandler(this.OnBSClicked);
}
}
<file_sep>/JAdivina/src/iesserpis/ed/Adivina.java
package iesserpis.ed;
import java.util.Scanner;
public class Adivina {
public static void main(String[] args) {
Scanner tcl=new Scanner(System.in);
// un numero aleatorio entre el 1 y el 1000
int x=(int)(Math.random()*1000);
int intentos=1;
int num=0;
System.out.println(x);
System.out.println("Adivina un numero entre 1 y 1000 ");
//para entrar en el programa tienes que introducir un numero diferente de la respuesta, si no saldra
while(num != x&&intentos<25) {
num= tcl.nextInt();
// si aciertas entrara aqui si no saltara
if(num==x) {
//dependiendo de los intentos te dara una respuesta u otra
if (intentos<=5) {
System.out.println("Felicidades eres un maquina, as acertado con solo "+intentos+" intentos");
}
else if(intentos>5 && intentos<=10) {
System.out.println("No esta mal con "+intentos+" intentos");
}
else if(intentos>10 && intentos<=15) {
System.out.println("Bueno "+intentos+" intentos podria ser mejorable...");
}
else {
System.out.println(intentos+"..... Dedicate a otra cosa, te ira mejor");
}
}
//si no has acertado comprobara si es mayor o menor
else if(num>x) {
System.out.println("El numero "+num+" es mayor");
}
else {
System.out.println("El numero "+num+" es menor");
}
intentos++;
}
if(intentos<25) {
System.out.println("Has ganado, Fin de programa");
}
else
System.out.println("Demasiados intentos Has perdido, Fin de programa");
}
}
<file_sep>/README.md
# ed
Repositorio para Entonrnos de Desarrollo del IES serpis
<file_sep>/JVector/src/iesserpis/ed/VectorTest.java
package iesserpis.ed;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import junit.framework.Assert;
class VectorTest {
// void indexOf() {
//
// int[] v= {17, 12, 15, 9, 14};
// int x=15;
// int index=Vector.indexOf(v, x);
//
// assertEquals(2, index);
//
// assertEquals(2, Vector.indexOf(new int[] {17, 12, 15, 9, 14}, 15));
// assertEquals(3, Vector.indexOf(new int[] {17, 12, 15, 9, 14}, 9));
// assertEquals(1, Vector.indexOf(new int[] {17, 12, 15, 9, 14}, 12));
// // es lo mismo
// assertEquals(0, Vector.indexOf(v, 17));
// assertEquals(4, Vector.indexOf(v, 14));
//
// // assertEquals(3, Vector.indexOf(v, 14));
// assertEquals(-1, Vector.indexOf(new int[] {17, 12, 15, 9, 14}, 19));
//
// }
@Test
void max() {
assertEquals (21, Vector.max((new int [] {14,21,12,9,7})));
}
@Test
void selectionSort( ) {
int[] v1 = {14, 21, 12, 7, 9};
Vector.selectionSort(v1);
assertArrayEquals(new int[] {7, 9, 12, 14, 21}, v1);
}
}
<file_sep>/Ccalculadora/Ccalculadora/Ccalculadora/EmptyClass.cs
using System;
namespace Ccalculadora
{
public class EmptyClass
{
public EmptyClass()
{
}
}
}
<file_sep>/Program.cs
using System;
namespace CHolaMundo
{
class MainClass
{
public static void Main(string[] args)
{
string nombre;
int edad;
int a;
int b;
int suma;
int resta;
int mult;
double div;
int ra;
int cont=0;
int numero = 0;
System.Random r = new System.Random();
ra = (r.Next(0, 50 + 1));
Console.WriteLine(ra);
Console.WriteLine("introduce tu nombre");
nombre = Console.ReadLine();
Console.WriteLine("hola " + nombre + " dime tu edad");
edad = int.Parse(Console.ReadLine());
Console.WriteLine(nombre + " tienes " + edad + " años");
Console.WriteLine("dame una cifra");
a = int.Parse(Console.ReadLine());
Console.WriteLine("dame otro numero");
b = int.Parse(Console.ReadLine());
suma = a + b;
resta = a - b;
mult = a * b;
div = a / b;
Console.WriteLine("operaciones: suma" + suma+" resta "+resta+" multiplicacion "+ mult+ " division "+div);
Console.WriteLine("adivina el numero..");
do
{
numero = int.Parse(Console.ReadLine());
if (numero != ra)
{
Console.WriteLine("sigue intentandolo");
cont++;
}
} while (numero == ra);
{
Console.WriteLine("has ganado con: "+cont+" intentos");
}
}
}
}
<file_sep>/Ccalculadora/Ccalculadora/Ccalculadora/MainWindow.cs
using System;
using Gtk;
public partial class MainWindow : Gtk.Window
{
int contador;
String opcion;
float numero1;
float numero2;
float contadorigual;
float result;
operaciones resultado = new operaciones();
public MainWindow() : base(Gtk.WindowType.Toplevel)
{
Build();
Bvaciar.ModifyBg(StateType.Normal, new Gdk.Color(150, 150, 150));
BD.ModifyBg(StateType.Normal, new Gdk.Color(112, 141, 242));
BM.ModifyBg(StateType.Normal, new Gdk.Color(112, 141, 242));
BR.ModifyBg(StateType.Normal, new Gdk.Color(112, 141, 242));
BS.ModifyBg(StateType.Normal, new Gdk.Color(112, 141, 242));
BI.ModifyBg(StateType.Normal, new Gdk.Color(112, 141, 242));
// color de la pantalla
ModifyBg(StateType.Normal, new Gdk.Color(8, 8, 8));
// label1.ModifyBg(StateType.Normal, new Gdk.Color(231, 231, 231));
operaciones resultado = new operaciones();
}
protected void OnDeleteEvent(object sender, DeleteEventArgs a)
{
Application.Quit();
a.RetVal = true;
}
//Boton vaciar
protected void OnBvaciarClicked(object sender, EventArgs e)
{
Pantalla.DeleteText(0, Pantalla.Text.Length);
}
//boton borrar solo un numero
protected void OnBCClicked(object sender, EventArgs e)
{
Pantalla.DeleteText(Pantalla.Text.Length - 1, Pantalla.Text.Length);
String display = Pantalla.Text.ToString();
if (display.Contains("."))
{
contador = 0;
}
}
//boton dividir
protected void OnBDClicked(object sender, EventArgs e)
{
numero1 = Convert.ToSingle(Pantalla.Text);
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
// Pantalla.InsertText(display + " / ");
opcion = "/";
}
//boton multiplicacion
protected void OnBMClicked(object sender, EventArgs e)
{
numero1 = Convert.ToSingle(Pantalla.Text);
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
// Pantalla.InsertText(display + " * ");
opcion = "*";
}
//boton resta
protected void OnBRClicked(object sender, EventArgs e)
{
numero1 = Convert.ToSingle(Pantalla.Text);
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
// Pantalla.InsertText(display + " - ");
opcion = "-";
}
//boton suma
protected void OnBSClicked(object sender, EventArgs e)
{
numero1 = Convert.ToSingle(Pantalla.Text);
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
// Pantalla.InsertText(display + " + ");
opcion = "+";
}
//boton igual
protected void OnBIClicked(object sender, EventArgs e)
{
numero2 = Convert.ToSingle(Pantalla.Text);
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
switch (opcion)
{
case "+":
result = resultado.suma(numero1, numero2);
this.Pantalla.Text = (Convert.ToString(result));
contadorigual++;
break;
case "-":
result = resultado.resta(numero1, numero2);
this.Pantalla.Text = (Convert.ToString(result));
contadorigual++;
break;
case "*":
result = resultado.multiplicacion(numero1, numero2);
this.Pantalla.Text = (Convert.ToString(result));
contadorigual++;
break;
case "/":
result = resultado.division(numero1, numero2);
this.Pantalla.Text = (Convert.ToString(result));
contadorigual++;
break;
}
}
//boton punto(.)
protected void OnBPClicked(object sender, EventArgs e)
{
if (contador == 0)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + " ,");
contador++;
}
}
//cero
protected void OnBCeroClicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + " 0 ");
}
//uno
protected void OnB1Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "1");
}
//dos
protected void OnB2Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "2");
}
//tres
protected void OnB3Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "3");
}
//cuatro
protected void OnB4Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "4");
}
//cinco
protected void OnB5Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "5");
}
protected void OnB6Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "6");
}
protected void OnB7Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "7");
}
protected void OnB8Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "8");
}
protected void OnB9Clicked(object sender, EventArgs e)
{
String display = Pantalla.Text.ToString();
Pantalla.DeleteText(0, Pantalla.Text.Length);
Pantalla.InsertText(display + "9");
}
}
<file_sep>/Ccalculadora/Ccalculadora/Ccalculadora/operaciones.cs
using System;
using Gtk;
public class operaciones
{
public float suma(float numero1, float numero2)
{
return (numero1 + numero2);
}
public float resta(float numero1, float numero2)
{
return (numero1 - numero2);
}
public float multiplicacion(float numero1, float numero2)
{
return (numero1 * numero2);
}
public float division(float numero1, float numero2)
{
return (numero1 / numero2);
}
}
| 06d925498115bbcdb4a447936bf226ce5c592ad2 | [
"C#",
"Java",
"Markdown"
] | 9 | Java | gabmur92/ed | a095ac239d102f1ad98a95aaff1791294562a1d3 | e8b2e4ac06fa9c8225e5a4fd07050ab3136a0490 |
refs/heads/master | <repo_name>yee2542/FluentSearch-FE<file_sep>/src/modules/user/reducers/userReducer/index.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { initUserState } from './init';
import { User, USER } from './types';
const userSlice = createSlice({
name: USER,
initialState: initUserState,
reducers: {
init(state) {
return { ...state, ...initUserState };
},
setUser(state, action: PayloadAction<User>) {
state.user = action.payload;
state.authenticated = true;
},
deleteUser(state) {
return { ...state, ...initUserState };
},
setMessage(state, action: PayloadAction<string>) {
state.msg = action.payload;
},
},
});
export const userActions = userSlice.actions;
export default userSlice.reducer;
<file_sep>/src/modules/history/reducer/historyReducer/init.ts
import { HistoryState } from './types';
export const initHistoryState: HistoryState = {
data: [],
ready: false,
};
<file_sep>/src/modules/photos/components/BoundingBox/constants.ts
import { BoundingBoxType } from './types';
export const mock: BoundingBoxType = {
xMin: 30,
xMax: 90,
yMin: 30,
yMax: 110,
label: 'label',
scaleBorder: 2,
currentImgWidth: 300,
currentImgHeight: 300,
};
<file_sep>/src/modules/task/reducer/taskReducer/index.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { UserTasksDto } from '../../../../common/generated/generated-types';
import { initTaskState } from './init';
import { TASK } from './types';
export const taskSlice = createSlice({
name: TASK,
initialState: initTaskState,
reducers: {
init(state) {
return { ...state, ...initTaskState };
},
setTaskData(state, action: PayloadAction<{ data: UserTasksDto }>) {
const { data } = action.payload;
state.data = data;
state.present.tasks = data.tasks;
},
},
});
export default taskSlice.reducer;
export const taskActions = taskSlice.actions;
<file_sep>/src/common/components/Label/types.ts
import { ReactNode } from 'react';
export type LabelProps = {
color: string;
children: ReactNode;
};
<file_sep>/src/modules/upload/components/UploadButton/types.ts
export type UploadButtonPropsType = {
onFileOnChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
<file_sep>/src/modules/task/components/TaskTable/type.ts
import { TaskStatus } from '../../../../common/generated/generated-types';
export type TaskTablePropsType = {
data: TaskStatus[];
};
<file_sep>/src/common/utils/kFormatter.ts
const kFormatter = (num: number): string => {
return num > 999 ? (num / 1000).toFixed(1) + 'k' : num.toString();
};
export default kFormatter;
<file_sep>/src/modules/user/pages/register/interfaces.ts
import { FormRegister, FormRegisterError } from './types';
export interface Props {
onSubmit?: (form: FormRegister) => void;
onError?: (form: FormRegisterError) => void;
}
<file_sep>/src/modules/photos/components/Lightbox/types.ts
import {
FileInsightMeta,
InsightBBox,
InsightModelEnum,
RecentFile,
} from '../../../../common/generated/generated-types';
export type LightboxPropsType = {
closeLightbox: () => void;
image: RecentFile;
onPrev: (e: React.MouseEvent<HTMLElement>) => void;
onNext: (e: React.MouseEvent<HTMLElement>) => void;
};
export type currentImageSizeType = {
width: number;
height: number;
};
export type FileInsightMetaData = Omit<
FileInsightMeta,
'__typename' | 'owner' | 'original_filename' | 'type' | 'createAt' | 'updateAt'
>;
export type Insights = {
_id: string;
model: InsightModelEnum;
keyword: string;
bbox?: InsightBBox;
};
export type FileInsight = {
fileMeta: FileInsightMetaData;
insights: Insights[];
};
<file_sep>/src/common/hooks/useToggle/types.ts
type useTogglePropsType = [value: boolean, toggle: () => void];
export type { useTogglePropsType };
<file_sep>/src/modules/user/pages/login/interfaces.ts
import { OAuthType } from 'Models/oauth/type';
import { FormLogin, FormLoginError } from './types';
export interface Props {
onSubmit?: (form: FormLogin) => void;
onError?: (form: FormLoginError) => void;
onSubmitOAuth?: (type: OAuthType) => void;
}
<file_sep>/src/modules/upload/reducer/uploadReducer/actions.ts
import { FileListResponseDTO } from 'fluentsearch-types';
import { uploadFile } from 'Modules/upload/services/upload.file';
import { store } from 'Stores/index';
import { uploadActions } from '.';
export const uploadFileData = async (
group: string,
files: File[],
): Promise<FileListResponseDTO[]> => {
const pendingQueue = store
.getState()
.upload.pendingQueue.filter((f) => f.group === group);
const formData = new FormData();
let responseData: FileListResponseDTO[] = [];
for (const task of pendingQueue) {
const id = task._id;
const pendingQueueFilterID = store
.getState()
.upload.pendingQueue.filter((f) => f._id !== id);
if (pendingQueueFilterID)
store.dispatch(uploadActions.setPendingQueue(pendingQueueFilterID));
const file = files.find((file) => file.name === task.originFilename);
if (file) formData.append('files', file);
try {
const fileResponse = await uploadFile(formData);
responseData = fileResponse;
store.dispatch(uploadActions.successUploadFile(task));
} catch (error) {
console.log('error');
store.dispatch(uploadActions.failureUploadFile(task));
}
}
return responseData;
};
export const getUploadProgress = (): void => {
const pendingQueue = store.getState().upload.pendingQueue;
const fulfillQueue = store.getState().upload.fulfillQueue;
const total = pendingQueue.length + fulfillQueue.length;
const totalFullfillProgress = fulfillQueue
.map((el) => el.progress)
.reduce((acc, cur) => (acc += cur), 0);
store.dispatch(uploadActions.setProgress(totalFullfillProgress));
store.dispatch(uploadActions.setProgress(total));
const allTasks = [...pendingQueue, ...fulfillQueue];
const groupDistinct = new Set(allTasks.map((el) => el.group));
const groups = Array.from(groupDistinct).map((groupId) => {
const allTasksFormGroup = allTasks.filter((f) => f.group === groupId);
const fulfillTaskGroupProgress = allTasksFormGroup
.filter((f) => f.state === 'failed' || f.state === 'finish' || f.state === 'cancel')
.map((el) => el.progress)
.reduce((acc, cur) => (acc += cur), 0);
return {
label: groupId,
progress: fulfillTaskGroupProgress,
total: allTasksFormGroup.length,
};
});
store.dispatch(uploadActions.setGroup(groups));
};
<file_sep>/src/modules/history/reducer/historyReducer/types.ts
import { ModelEnum } from 'Modules/history/models/model.enum';
import { StatusEnum } from 'Modules/history/models/status.enum';
import { ErrorState } from 'Stores/common/types/error';
export const HISTORY = 'HISTORY';
export type HistoryState = {
data: [
{
key: string;
taskID: string;
taskName: string;
model: ModelEnum;
startTime: string;
finishTime: string;
status: StatusEnum;
},
][];
ready: boolean;
error?: ErrorState;
};
<file_sep>/src/modules/photos/components/BoundingBox/types.ts
export type BoundingBoxType = {
xMin: number;
xMax: number;
yMin: number;
yMax: number;
label: string;
scaleBorder: number;
currentImgWidth: number;
currentImgHeight: number;
};
<file_sep>/src/modules/user/pages/login/types.ts
import { FormProps } from 'antd/lib/form/Form';
import { InternalNamePath } from 'antd/lib/form/interface';
export type FormLogin = { email: string; password: string };
export type FormLoginError = {
values: FormLogin;
errorFields: {
name: InternalNamePath;
errors: string[];
}[];
};
export type FormErrorValue = FormProps['onFinishFailed'];
export type FormFinishValue = FormProps['onFinish'];
<file_sep>/src/common/constants/menu/types.ts
import { ButtonComponentProps } from 'Components/Button/types';
export type MenuType = {
key: string;
icon?: string;
label: string | ButtonComponentProps;
link: string[];
style?: React.CSSProperties;
active: boolean;
};
<file_sep>/src/common/generated/generated-types.ts
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> &
{ [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
};
export type AppModel = {
__typename?: 'AppModel';
status: Scalars['Int'];
};
export type DataDashboard = {
__typename?: 'DataDashboard';
total: Scalars['Float'];
today: Scalars['Float'];
};
export type Dimension = {
__typename?: 'Dimension';
original_width: Scalars['Float'];
original_height: Scalars['Float'];
extract_width: Scalars['Float'];
extract_height: Scalars['Float'];
};
export type FileDashboardDto = {
__typename?: 'FileDashboardDTO';
photo: DataDashboard;
video: DataDashboard;
};
export type FileDurationMetaDto = {
__typename?: 'FileDurationMetaDTO';
original: Scalars['String'];
hour: Scalars['Float'];
minute: Scalars['Float'];
second: Scalars['Float'];
};
export type FileInsightDto = {
__typename?: 'FileInsightDto';
fileMeta: FileInsightMeta;
insights: Array<InsightDto>;
};
export type FileInsightMeta = {
__typename?: 'FileInsightMeta';
_id: Scalars['String'];
uri: Scalars['String'];
uri_thumbnail: Scalars['String'];
meta: FileInsightMetadata;
owner: Scalars['String'];
original_filename: Scalars['String'];
type: Scalars['String'];
createAt: Scalars['String'];
updateAt: Scalars['String'];
};
export type FileInsightMetadata = {
__typename?: 'FileInsightMetadata';
size: Scalars['Float'];
extension: Scalars['String'];
contentType: Scalars['String'];
width: Scalars['Float'];
height: Scalars['Float'];
fps?: Maybe<Scalars['Float']>;
duration?: Maybe<FileInsightVideoDuration>;
};
export type FileInsightVideoDuration = {
__typename?: 'FileInsightVideoDuration';
original: Scalars['String'];
hour: Scalars['Float'];
minute: Scalars['Float'];
second: Scalars['Float'];
};
export type FileMetaDto = {
__typename?: 'FileMetaDTO';
size: Scalars['Float'];
width: Scalars['Float'];
height: Scalars['Float'];
extension: Scalars['String'];
contentType: Scalars['String'];
sha1?: Maybe<Scalars['String']>;
fps?: Maybe<Scalars['Float']>;
codec?: Maybe<Scalars['String']>;
bitrate?: Maybe<Scalars['Float']>;
duration?: Maybe<FileDurationMetaDto>;
};
export type FileModelDto = {
__typename?: 'FileModelDTO';
_id: Scalars['String'];
uri: Scalars['String'];
meta: FileMetaDto;
owner: Scalars['String'];
zone: ZoneEnum;
original_filename: Scalars['String'];
type: FileTypeEnum;
createAt: Scalars['String'];
updateAt: Scalars['String'];
};
export enum FileTypeEnum {
Image = 'Image',
Video = 'Video',
ImageThumbnail = 'ImageThumbnail',
VideoThumbnail = 'VideoThumbnail',
}
export type FileVideoInsightDto = {
__typename?: 'FileVideoInsightDto';
fileMeta: FileInsightMeta;
insights: Array<InsightVideoDto>;
dimension: Dimension;
model: InsightModelEnum;
};
export type InsightBBox = {
__typename?: 'InsightBBox';
xmax: Scalars['Float'];
ymax: Scalars['Float'];
ymin: Scalars['Float'];
xmin: Scalars['Float'];
};
export type InsightClass = {
__typename?: 'InsightClass';
bbox: InsightBBox;
prob: Scalars['Float'];
fps: Scalars['Float'];
cat: Scalars['String'];
};
export type InsightDto = {
__typename?: 'InsightDTO';
_id: Scalars['String'];
owner: Scalars['String'];
keyword: Scalars['String'];
model: InsightModelEnum;
bbox?: Maybe<InsightBBox>;
prob: Scalars['Float'];
lang: InsightLanguageEnum;
fileId: Scalars['String'];
fileType: InsightFileTypeEnum;
fps?: Maybe<Scalars['Float']>;
createAt: Scalars['String'];
updateAt: Scalars['String'];
};
export enum InsightFileTypeEnum {
Image = 'Image',
Video = 'Video',
ImageThumbnail = 'ImageThumbnail',
VideoThumbnail = 'VideoThumbnail',
}
export enum InsightLanguageEnum {
Th = 'th',
Enus = 'enus',
}
export enum InsightModelEnum {
FacesEmo = 'faces_emo',
Detection_600 = 'detection_600',
IlsvrcGooglenet = 'ilsvrc_googlenet',
BasicFashion = 'basic_fashion',
Classification_21k = 'classification_21k',
Places = 'places',
Vgg16 = 'vgg16',
}
export type InsightVideoDto = {
__typename?: 'InsightVideoDTO';
classes: Array<InsightClass>;
nFps: Scalars['Float'];
};
export enum ModelEnum {
FacesEmo = 'faces_emo',
Detection_600 = 'detection_600',
IlsvrcGooglenet = 'ilsvrc_googlenet',
BasicFashion = 'basic_fashion',
Classification_21k = 'classification_21k',
Places = 'places',
Vgg16 = 'vgg16',
}
export type Mutation = {
__typename?: 'Mutation';
CreateUser: UserWithId;
UpdateUser: UserWithId;
Login: UserSessionDto;
Logout?: Maybe<Scalars['String']>;
RefreshToken?: Maybe<Scalars['String']>;
};
export type MutationCreateUserArgs = {
UserRegisterInput: UserRegisterInput;
};
export type MutationUpdateUserArgs = {
UserUpdateInput: UserUpdateInput;
};
export type MutationLoginArgs = {
UserLoginInputDTO: UserLoginInputDto;
};
export type Query = {
__typename?: 'Query';
ServerStatus: AppModel;
User?: Maybe<UserWithId>;
GetUserBySession?: Maybe<UserWithId>;
Users: Array<UserWithId>;
GetUserTasks: UserTasksDto;
GetRecentFileInsightDashboard: Array<FileInsightDto>;
GetFileImageInsight: FileInsightDto;
GetFileVideoInsight: FileVideoInsightDto;
GetSearch: SearchDto;
GetFileDashboard: FileDashboardDto;
GetFileById: FileModelDto;
GetRecentFiles: RecentFiles;
};
export type QueryUserArgs = {
id: Scalars['String'];
};
export type QueryUsersArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
};
export type QueryGetUserTasksArgs = {
userId: Scalars['String'];
};
export type QueryGetRecentFileInsightDashboardArgs = {
owner: Scalars['String'];
};
export type QueryGetFileImageInsightArgs = {
fileId: Scalars['String'];
};
export type QueryGetFileVideoInsightArgs = {
fileId: Scalars['String'];
};
export type QueryGetSearchArgs = {
word: Scalars['String'];
owner: Scalars['String'];
};
export type QueryGetFileDashboardArgs = {
owner: Scalars['String'];
};
export type QueryGetFileByIdArgs = {
owner: Scalars['String'];
id: Scalars['String'];
};
export type QueryGetRecentFilesArgs = {
skip?: Maybe<Scalars['Int']>;
limit?: Maybe<Scalars['Int']>;
owner: Scalars['String'];
};
export type RecentFile = {
__typename?: 'RecentFile';
_id: Scalars['String'];
original_filename: Scalars['String'];
uri: Scalars['String'];
uri_thumbnail: Scalars['String'];
createAt: Scalars['String'];
updateAt: Scalars['String'];
type: Scalars['String'];
};
export type RecentFiles = {
__typename?: 'RecentFiles';
result: Array<RecentPreviews>;
};
export type RecentPreviews = {
__typename?: 'RecentPreviews';
date: Scalars['String'];
files?: Maybe<Array<RecentFile>>;
};
export type SearchDto = {
__typename?: 'SearchDTO';
results: Array<FileInsightMeta>;
autocomplete: Array<Scalars['String']>;
};
export type TaskStatus = {
__typename?: 'TaskStatus';
name: Scalars['String'];
wait: Scalars['Float'];
excute: Scalars['Float'];
finish: Scalars['Float'];
models: Array<ModelEnum>;
createAt: Scalars['String'];
};
export type UserLoginInputDto = {
password: Scalars['String'];
email: Scalars['String'];
};
export enum UserPackageEnumSession {
FreeUser = 'freeUser',
PaidUser = 'paidUser',
}
export type UserRegisterInput = {
mainEmail: Scalars['String'];
password: Scalars['String'];
name: Scalars['String'];
};
export enum UserRoleEnumSession {
Admin = 'admin',
Staff = 'staff',
User = 'user',
}
export type UserSessionDto = {
__typename?: 'UserSessionDTO';
_id: Scalars['String'];
mainEmail: Scalars['String'];
name: Scalars['String'];
role: UserRoleEnumSession;
package: UserPackageEnumSession;
zone: UserZoneEnumSession;
};
export type UserTasksDto = {
__typename?: 'UserTasksDTO';
tasks: Array<TaskStatus>;
quota: Scalars['Float'];
};
export type UserToken = {
__typename?: 'UserToken';
provider: Scalars['String'];
token: Scalars['String'];
};
export type UserUpdateInput = {
id: Scalars['String'];
mainEmail?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
};
export type UserWithId = {
__typename?: 'UserWithId';
mainEmail: Scalars['String'];
email: Array<Scalars['String']>;
password: Scalars['<PASSWORD>'];
oauth: UserToken;
name?: Maybe<Scalars['String']>;
role: UserRoleEnumSession;
package: UserPackageEnumSession;
zone: UserZoneEnumSession;
deactivate?: Maybe<Scalars['Boolean']>;
createAt: Scalars['String'];
updateAt: Scalars['String'];
_id: Scalars['String'];
};
export enum UserZoneEnumSession {
Th1 = 'TH1',
Th2 = 'TH2',
}
export enum ZoneEnum {
Th = 'TH',
}
export type GetDashboardDataQueryVariables = Exact<{
owner: Scalars['String'];
}>;
export type GetDashboardDataQuery = { __typename?: 'Query' } & {
GetRecentFileInsightDashboard: Array<
{ __typename?: 'FileInsightDto' } & {
fileMeta: { __typename?: 'FileInsightMeta' } & Pick<
FileInsightMeta,
'_id' | 'original_filename' | 'type' | 'uri' | 'uri_thumbnail'
>;
insights: Array<
{ __typename?: 'InsightDTO' } & Pick<InsightDto, 'model' | 'keyword'>
>;
}
>;
GetFileDashboard: { __typename?: 'FileDashboardDTO' } & {
video: { __typename?: 'DataDashboard' } & Pick<DataDashboard, 'today' | 'total'>;
photo: { __typename?: 'DataDashboard' } & Pick<DataDashboard, 'today' | 'total'>;
};
};
export type GetFileImageInsightQueryVariables = Exact<{
fileId: Scalars['String'];
}>;
export type GetFileImageInsightQuery = { __typename?: 'Query' } & {
GetFileImageInsight: { __typename?: 'FileInsightDto' } & {
fileMeta: { __typename?: 'FileInsightMeta' } & Pick<
FileInsightMeta,
'_id' | 'type' | 'uri' | 'uri_thumbnail'
> & {
meta: { __typename?: 'FileInsightMetadata' } & Pick<
FileInsightMetadata,
'size' | 'contentType' | 'width' | 'height' | 'extension'
>;
};
insights: Array<
{ __typename?: 'InsightDTO' } & Pick<InsightDto, '_id' | 'model' | 'keyword'> & {
bbox?: Maybe<
{ __typename?: 'InsightBBox' } & Pick<
InsightBBox,
'xmax' | 'xmin' | 'ymin' | 'ymax'
>
>;
}
>;
};
};
export type GetSearchQueryVariables = Exact<{
owner: Scalars['String'];
word: Scalars['String'];
}>;
export type GetSearchQuery = { __typename?: 'Query' } & {
GetSearch: { __typename?: 'SearchDTO' } & Pick<SearchDto, 'autocomplete'> & {
results: Array<
{ __typename?: 'FileInsightMeta' } & Pick<
FileInsightMeta,
'_id' | 'uri_thumbnail' | 'uri'
>
>;
};
};
export type GetUserTasksQueryVariables = Exact<{
userId: Scalars['String'];
}>;
export type GetUserTasksQuery = { __typename?: 'Query' } & {
GetUserTasks: { __typename?: 'UserTasksDTO' } & Pick<UserTasksDto, 'quota'> & {
tasks: Array<
{ __typename?: 'TaskStatus' } & Pick<
TaskStatus,
'name' | 'wait' | 'excute' | 'finish' | 'models' | 'createAt'
>
>;
};
};
export type GetRecentFilesQueryVariables = Exact<{
owner: Scalars['String'];
limit?: Maybe<Scalars['Int']>;
skip?: Maybe<Scalars['Int']>;
}>;
export type GetRecentFilesQuery = { __typename?: 'Query' } & {
GetRecentFiles: { __typename?: 'RecentFiles' } & {
result: Array<
{ __typename?: 'RecentPreviews' } & Pick<RecentPreviews, 'date'> & {
files?: Maybe<
Array<
{ __typename?: 'RecentFile' } & Pick<
RecentFile,
| '_id'
| 'type'
| 'createAt'
| 'original_filename'
| 'updateAt'
| 'uri'
| 'uri_thumbnail'
>
>
>;
}
>;
};
};
export type GetFileByIdQueryVariables = Exact<{
owner: Scalars['String'];
id: Scalars['String'];
}>;
export type GetFileByIdQuery = { __typename?: 'Query' } & {
GetFileById: { __typename?: 'FileModelDTO' } & Pick<
FileModelDto,
| '_id'
| 'createAt'
| 'original_filename'
| 'owner'
| 'type'
| 'updateAt'
| 'uri'
| 'zone'
> & {
meta: { __typename?: 'FileMetaDTO' } & Pick<
FileMetaDto,
| 'bitrate'
| 'codec'
| 'contentType'
| 'extension'
| 'fps'
| 'height'
| 'sha1'
| 'size'
| 'width'
> & {
duration?: Maybe<
{ __typename?: 'FileDurationMetaDTO' } & Pick<
FileDurationMetaDto,
'hour' | 'minute' | 'original' | 'second'
>
>;
};
};
};
export type GetUserQueryVariables = Exact<{
id: Scalars['String'];
}>;
export type GetUserQuery = { __typename?: 'Query' } & {
User?: Maybe<
{ __typename?: 'UserWithId' } & Pick<
UserWithId,
| '_id'
| 'createAt'
| 'deactivate'
| 'email'
| 'mainEmail'
| 'name'
| 'package'
| 'role'
| 'updateAt'
| 'zone'
> & { oauth: { __typename?: 'UserToken' } & Pick<UserToken, 'provider' | 'token'> }
>;
};
export type GetUsersQueryVariables = Exact<{
limit?: Maybe<Scalars['Int']>;
skip?: Maybe<Scalars['Int']>;
}>;
export type GetUsersQuery = { __typename?: 'Query' } & {
Users: Array<
{ __typename?: 'UserWithId' } & Pick<
UserWithId,
| '_id'
| 'createAt'
| 'deactivate'
| 'email'
| 'mainEmail'
| 'name'
| 'package'
| 'role'
| 'updateAt'
| 'zone'
> & { oauth: { __typename?: 'UserToken' } & Pick<UserToken, 'provider' | 'token'> }
>;
};
export type GetUserBySessionQueryVariables = Exact<{ [key: string]: never }>;
export type GetUserBySessionQuery = { __typename?: 'Query' } & {
GetUserBySession?: Maybe<
{ __typename?: 'UserWithId' } & Pick<
UserWithId,
| '_id'
| 'createAt'
| 'deactivate'
| 'email'
| 'mainEmail'
| 'name'
| 'package'
| 'role'
| 'updateAt'
| 'zone'
> & { oauth: { __typename?: 'UserToken' } & Pick<UserToken, 'provider' | 'token'> }
>;
};
export type GetServerStatusQueryVariables = Exact<{ [key: string]: never }>;
export type GetServerStatusQuery = { __typename?: 'Query' } & {
ServerStatus: { __typename?: 'AppModel' } & Pick<AppModel, 'status'>;
};
export type CreateUserMutationVariables = Exact<{
UserRegisterInput: UserRegisterInput;
}>;
export type CreateUserMutation = { __typename?: 'Mutation' } & {
CreateUser: { __typename?: 'UserWithId' } & Pick<
UserWithId,
'_id' | 'mainEmail' | 'name' | 'package' | 'password' | 'role' | 'zone'
>;
};
export type LoginMutationVariables = Exact<{
UserLoginInputDTO: UserLoginInputDto;
}>;
export type LoginMutation = { __typename?: 'Mutation' } & {
Login: { __typename?: 'UserSessionDTO' } & Pick<
UserSessionDto,
'_id' | 'mainEmail' | 'name' | 'package' | 'role' | 'zone'
>;
};
export type LogoutMutationVariables = Exact<{ [key: string]: never }>;
export type LogoutMutation = { __typename?: 'Mutation' } & Pick<Mutation, 'Logout'>;
export type RefreshTokenMutationVariables = Exact<{ [key: string]: never }>;
export type RefreshTokenMutation = { __typename?: 'Mutation' } & Pick<
Mutation,
'RefreshToken'
>;
export type UpdateUserMutationVariables = Exact<{
UserUpdateInput: UserUpdateInput;
}>;
export type UpdateUserMutation = { __typename?: 'Mutation' } & {
UpdateUser: { __typename?: 'UserWithId' } & Pick<
UserWithId,
| '_id'
| 'createAt'
| 'deactivate'
| 'email'
| 'mainEmail'
| 'name'
| 'package'
| 'role'
| 'updateAt'
| 'zone'
> & { oauth: { __typename?: 'UserToken' } & Pick<UserToken, 'provider' | 'token'> };
};
export const GetDashboardDataDocument = gql`
query GetDashboardData($owner: String!) {
GetRecentFileInsightDashboard(owner: $owner) {
fileMeta {
_id
original_filename
type
uri
uri_thumbnail
}
insights {
model
keyword
}
}
GetFileDashboard(owner: $owner) {
video {
today
total
}
photo {
today
total
}
}
}
`;
/**
* __useGetDashboardDataQuery__
*
* To run a query within a React component, call `useGetDashboardDataQuery` and pass it any options that fit your needs.
* When your component renders, `useGetDashboardDataQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetDashboardDataQuery({
* variables: {
* owner: // value for 'owner'
* },
* });
*/
export function useGetDashboardDataQuery(
baseOptions: Apollo.QueryHookOptions<
GetDashboardDataQuery,
GetDashboardDataQueryVariables
>,
) {
return Apollo.useQuery<GetDashboardDataQuery, GetDashboardDataQueryVariables>(
GetDashboardDataDocument,
baseOptions,
);
}
export function useGetDashboardDataLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<
GetDashboardDataQuery,
GetDashboardDataQueryVariables
>,
) {
return Apollo.useLazyQuery<GetDashboardDataQuery, GetDashboardDataQueryVariables>(
GetDashboardDataDocument,
baseOptions,
);
}
export type GetDashboardDataQueryHookResult = ReturnType<typeof useGetDashboardDataQuery>;
export type GetDashboardDataLazyQueryHookResult = ReturnType<
typeof useGetDashboardDataLazyQuery
>;
export type GetDashboardDataQueryResult = Apollo.QueryResult<
GetDashboardDataQuery,
GetDashboardDataQueryVariables
>;
export const GetFileImageInsightDocument = gql`
query GetFileImageInsight($fileId: String!) {
GetFileImageInsight(fileId: $fileId) {
fileMeta {
_id
type
uri
uri_thumbnail
meta {
size
contentType
width
height
extension
}
}
insights {
_id
model
keyword
bbox {
xmax
xmin
ymin
ymax
}
}
}
}
`;
/**
* __useGetFileImageInsightQuery__
*
* To run a query within a React component, call `useGetFileImageInsightQuery` and pass it any options that fit your needs.
* When your component renders, `useGetFileImageInsightQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetFileImageInsightQuery({
* variables: {
* fileId: // value for 'fileId'
* },
* });
*/
export function useGetFileImageInsightQuery(
baseOptions: Apollo.QueryHookOptions<
GetFileImageInsightQuery,
GetFileImageInsightQueryVariables
>,
) {
return Apollo.useQuery<GetFileImageInsightQuery, GetFileImageInsightQueryVariables>(
GetFileImageInsightDocument,
baseOptions,
);
}
export function useGetFileImageInsightLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<
GetFileImageInsightQuery,
GetFileImageInsightQueryVariables
>,
) {
return Apollo.useLazyQuery<GetFileImageInsightQuery, GetFileImageInsightQueryVariables>(
GetFileImageInsightDocument,
baseOptions,
);
}
export type GetFileImageInsightQueryHookResult = ReturnType<
typeof useGetFileImageInsightQuery
>;
export type GetFileImageInsightLazyQueryHookResult = ReturnType<
typeof useGetFileImageInsightLazyQuery
>;
export type GetFileImageInsightQueryResult = Apollo.QueryResult<
GetFileImageInsightQuery,
GetFileImageInsightQueryVariables
>;
export const GetSearchDocument = gql`
query GetSearch($owner: String!, $word: String!) {
GetSearch(owner: $owner, word: $word) {
results {
_id
uri_thumbnail
uri
}
autocomplete
}
}
`;
/**
* __useGetSearchQuery__
*
* To run a query within a React component, call `useGetSearchQuery` and pass it any options that fit your needs.
* When your component renders, `useGetSearchQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetSearchQuery({
* variables: {
* owner: // value for 'owner'
* word: // value for 'word'
* },
* });
*/
export function useGetSearchQuery(
baseOptions: Apollo.QueryHookOptions<GetSearchQuery, GetSearchQueryVariables>,
) {
return Apollo.useQuery<GetSearchQuery, GetSearchQueryVariables>(
GetSearchDocument,
baseOptions,
);
}
export function useGetSearchLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<GetSearchQuery, GetSearchQueryVariables>,
) {
return Apollo.useLazyQuery<GetSearchQuery, GetSearchQueryVariables>(
GetSearchDocument,
baseOptions,
);
}
export type GetSearchQueryHookResult = ReturnType<typeof useGetSearchQuery>;
export type GetSearchLazyQueryHookResult = ReturnType<typeof useGetSearchLazyQuery>;
export type GetSearchQueryResult = Apollo.QueryResult<
GetSearchQuery,
GetSearchQueryVariables
>;
export const GetUserTasksDocument = gql`
query GetUserTasks($userId: String!) {
GetUserTasks(userId: $userId) {
tasks {
name
wait
excute
finish
models
createAt
}
quota
}
}
`;
/**
* __useGetUserTasksQuery__
*
* To run a query within a React component, call `useGetUserTasksQuery` and pass it any options that fit your needs.
* When your component renders, `useGetUserTasksQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetUserTasksQuery({
* variables: {
* userId: // value for 'userId'
* },
* });
*/
export function useGetUserTasksQuery(
baseOptions: Apollo.QueryHookOptions<GetUserTasksQuery, GetUserTasksQueryVariables>,
) {
return Apollo.useQuery<GetUserTasksQuery, GetUserTasksQueryVariables>(
GetUserTasksDocument,
baseOptions,
);
}
export function useGetUserTasksLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<
GetUserTasksQuery,
GetUserTasksQueryVariables
>,
) {
return Apollo.useLazyQuery<GetUserTasksQuery, GetUserTasksQueryVariables>(
GetUserTasksDocument,
baseOptions,
);
}
export type GetUserTasksQueryHookResult = ReturnType<typeof useGetUserTasksQuery>;
export type GetUserTasksLazyQueryHookResult = ReturnType<typeof useGetUserTasksLazyQuery>;
export type GetUserTasksQueryResult = Apollo.QueryResult<
GetUserTasksQuery,
GetUserTasksQueryVariables
>;
export const GetRecentFilesDocument = gql`
query GetRecentFiles($owner: String!, $limit: Int, $skip: Int) {
GetRecentFiles(owner: $owner, limit: $limit, skip: $skip) {
result {
date
files {
_id
type
createAt
original_filename
updateAt
uri
uri_thumbnail
}
}
}
}
`;
/**
* __useGetRecentFilesQuery__
*
* To run a query within a React component, call `useGetRecentFilesQuery` and pass it any options that fit your needs.
* When your component renders, `useGetRecentFilesQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetRecentFilesQuery({
* variables: {
* owner: // value for 'owner'
* limit: // value for 'limit'
* skip: // value for 'skip'
* },
* });
*/
export function useGetRecentFilesQuery(
baseOptions: Apollo.QueryHookOptions<GetRecentFilesQuery, GetRecentFilesQueryVariables>,
) {
return Apollo.useQuery<GetRecentFilesQuery, GetRecentFilesQueryVariables>(
GetRecentFilesDocument,
baseOptions,
);
}
export function useGetRecentFilesLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<
GetRecentFilesQuery,
GetRecentFilesQueryVariables
>,
) {
return Apollo.useLazyQuery<GetRecentFilesQuery, GetRecentFilesQueryVariables>(
GetRecentFilesDocument,
baseOptions,
);
}
export type GetRecentFilesQueryHookResult = ReturnType<typeof useGetRecentFilesQuery>;
export type GetRecentFilesLazyQueryHookResult = ReturnType<
typeof useGetRecentFilesLazyQuery
>;
export type GetRecentFilesQueryResult = Apollo.QueryResult<
GetRecentFilesQuery,
GetRecentFilesQueryVariables
>;
export const GetFileByIdDocument = gql`
query GetFileById($owner: String!, $id: String!) {
GetFileById(owner: $owner, id: $id) {
_id
createAt
meta {
bitrate
codec
contentType
duration {
hour
minute
original
second
}
extension
fps
height
sha1
size
width
}
original_filename
owner
type
updateAt
uri
zone
}
}
`;
/**
* __useGetFileByIdQuery__
*
* To run a query within a React component, call `useGetFileByIdQuery` and pass it any options that fit your needs.
* When your component renders, `useGetFileByIdQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetFileByIdQuery({
* variables: {
* owner: // value for 'owner'
* id: // value for 'id'
* },
* });
*/
export function useGetFileByIdQuery(
baseOptions: Apollo.QueryHookOptions<GetFileByIdQuery, GetFileByIdQueryVariables>,
) {
return Apollo.useQuery<GetFileByIdQuery, GetFileByIdQueryVariables>(
GetFileByIdDocument,
baseOptions,
);
}
export function useGetFileByIdLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<GetFileByIdQuery, GetFileByIdQueryVariables>,
) {
return Apollo.useLazyQuery<GetFileByIdQuery, GetFileByIdQueryVariables>(
GetFileByIdDocument,
baseOptions,
);
}
export type GetFileByIdQueryHookResult = ReturnType<typeof useGetFileByIdQuery>;
export type GetFileByIdLazyQueryHookResult = ReturnType<typeof useGetFileByIdLazyQuery>;
export type GetFileByIdQueryResult = Apollo.QueryResult<
GetFileByIdQuery,
GetFileByIdQueryVariables
>;
export const GetUserDocument = gql`
query GetUser($id: String!) {
User(id: $id) {
_id
createAt
deactivate
email
mainEmail
name
oauth {
provider
token
}
package
role
updateAt
zone
}
}
`;
/**
* __useGetUserQuery__
*
* To run a query within a React component, call `useGetUserQuery` and pass it any options that fit your needs.
* When your component renders, `useGetUserQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetUserQuery({
* variables: {
* id: // value for 'id'
* },
* });
*/
export function useGetUserQuery(
baseOptions: Apollo.QueryHookOptions<GetUserQuery, GetUserQueryVariables>,
) {
return Apollo.useQuery<GetUserQuery, GetUserQueryVariables>(
GetUserDocument,
baseOptions,
);
}
export function useGetUserLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<GetUserQuery, GetUserQueryVariables>,
) {
return Apollo.useLazyQuery<GetUserQuery, GetUserQueryVariables>(
GetUserDocument,
baseOptions,
);
}
export type GetUserQueryHookResult = ReturnType<typeof useGetUserQuery>;
export type GetUserLazyQueryHookResult = ReturnType<typeof useGetUserLazyQuery>;
export type GetUserQueryResult = Apollo.QueryResult<GetUserQuery, GetUserQueryVariables>;
export const GetUsersDocument = gql`
query GetUsers($limit: Int = 1000, $skip: Int = 0) {
Users(limit: $limit, skip: $skip) {
_id
createAt
deactivate
email
mainEmail
name
oauth {
provider
token
}
package
role
updateAt
zone
}
}
`;
/**
* __useGetUsersQuery__
*
* To run a query within a React component, call `useGetUsersQuery` and pass it any options that fit your needs.
* When your component renders, `useGetUsersQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetUsersQuery({
* variables: {
* limit: // value for 'limit'
* skip: // value for 'skip'
* },
* });
*/
export function useGetUsersQuery(
baseOptions?: Apollo.QueryHookOptions<GetUsersQuery, GetUsersQueryVariables>,
) {
return Apollo.useQuery<GetUsersQuery, GetUsersQueryVariables>(
GetUsersDocument,
baseOptions,
);
}
export function useGetUsersLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<GetUsersQuery, GetUsersQueryVariables>,
) {
return Apollo.useLazyQuery<GetUsersQuery, GetUsersQueryVariables>(
GetUsersDocument,
baseOptions,
);
}
export type GetUsersQueryHookResult = ReturnType<typeof useGetUsersQuery>;
export type GetUsersLazyQueryHookResult = ReturnType<typeof useGetUsersLazyQuery>;
export type GetUsersQueryResult = Apollo.QueryResult<
GetUsersQuery,
GetUsersQueryVariables
>;
export const GetUserBySessionDocument = gql`
query GetUserBySession {
GetUserBySession {
_id
createAt
deactivate
email
mainEmail
name
oauth {
provider
token
}
package
role
updateAt
zone
}
}
`;
/**
* __useGetUserBySessionQuery__
*
* To run a query within a React component, call `useGetUserBySessionQuery` and pass it any options that fit your needs.
* When your component renders, `useGetUserBySessionQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetUserBySessionQuery({
* variables: {
* },
* });
*/
export function useGetUserBySessionQuery(
baseOptions?: Apollo.QueryHookOptions<
GetUserBySessionQuery,
GetUserBySessionQueryVariables
>,
) {
return Apollo.useQuery<GetUserBySessionQuery, GetUserBySessionQueryVariables>(
GetUserBySessionDocument,
baseOptions,
);
}
export function useGetUserBySessionLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<
GetUserBySessionQuery,
GetUserBySessionQueryVariables
>,
) {
return Apollo.useLazyQuery<GetUserBySessionQuery, GetUserBySessionQueryVariables>(
GetUserBySessionDocument,
baseOptions,
);
}
export type GetUserBySessionQueryHookResult = ReturnType<typeof useGetUserBySessionQuery>;
export type GetUserBySessionLazyQueryHookResult = ReturnType<
typeof useGetUserBySessionLazyQuery
>;
export type GetUserBySessionQueryResult = Apollo.QueryResult<
GetUserBySessionQuery,
GetUserBySessionQueryVariables
>;
export const GetServerStatusDocument = gql`
query GetServerStatus {
ServerStatus {
status
}
}
`;
/**
* __useGetServerStatusQuery__
*
* To run a query within a React component, call `useGetServerStatusQuery` and pass it any options that fit your needs.
* When your component renders, `useGetServerStatusQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetServerStatusQuery({
* variables: {
* },
* });
*/
export function useGetServerStatusQuery(
baseOptions?: Apollo.QueryHookOptions<
GetServerStatusQuery,
GetServerStatusQueryVariables
>,
) {
return Apollo.useQuery<GetServerStatusQuery, GetServerStatusQueryVariables>(
GetServerStatusDocument,
baseOptions,
);
}
export function useGetServerStatusLazyQuery(
baseOptions?: Apollo.LazyQueryHookOptions<
GetServerStatusQuery,
GetServerStatusQueryVariables
>,
) {
return Apollo.useLazyQuery<GetServerStatusQuery, GetServerStatusQueryVariables>(
GetServerStatusDocument,
baseOptions,
);
}
export type GetServerStatusQueryHookResult = ReturnType<typeof useGetServerStatusQuery>;
export type GetServerStatusLazyQueryHookResult = ReturnType<
typeof useGetServerStatusLazyQuery
>;
export type GetServerStatusQueryResult = Apollo.QueryResult<
GetServerStatusQuery,
GetServerStatusQueryVariables
>;
export const CreateUserDocument = gql`
mutation CreateUser($UserRegisterInput: UserRegisterInput!) {
CreateUser(UserRegisterInput: $UserRegisterInput) {
_id
mainEmail
name
package
password
role
zone
}
}
`;
export type CreateUserMutationFn = Apollo.MutationFunction<
CreateUserMutation,
CreateUserMutationVariables
>;
/**
* __useCreateUserMutation__
*
* To run a mutation, you first call `useCreateUserMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useCreateUserMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [createUserMutation, { data, loading, error }] = useCreateUserMutation({
* variables: {
* UserRegisterInput: // value for 'UserRegisterInput'
* },
* });
*/
export function useCreateUserMutation(
baseOptions?: Apollo.MutationHookOptions<
CreateUserMutation,
CreateUserMutationVariables
>,
) {
return Apollo.useMutation<CreateUserMutation, CreateUserMutationVariables>(
CreateUserDocument,
baseOptions,
);
}
export type CreateUserMutationHookResult = ReturnType<typeof useCreateUserMutation>;
export type CreateUserMutationResult = Apollo.MutationResult<CreateUserMutation>;
export type CreateUserMutationOptions = Apollo.BaseMutationOptions<
CreateUserMutation,
CreateUserMutationVariables
>;
export const LoginDocument = gql`
mutation Login($UserLoginInputDTO: UserLoginInputDTO!) {
Login(UserLoginInputDTO: $UserLoginInputDTO) {
_id
mainEmail
name
package
role
zone
}
}
`;
export type LoginMutationFn = Apollo.MutationFunction<
LoginMutation,
LoginMutationVariables
>;
/**
* __useLoginMutation__
*
* To run a mutation, you first call `useLoginMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useLoginMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [loginMutation, { data, loading, error }] = useLoginMutation({
* variables: {
* UserLoginInputDTO: // value for 'UserLoginInputDTO'
* },
* });
*/
export function useLoginMutation(
baseOptions?: Apollo.MutationHookOptions<LoginMutation, LoginMutationVariables>,
) {
return Apollo.useMutation<LoginMutation, LoginMutationVariables>(
LoginDocument,
baseOptions,
);
}
export type LoginMutationHookResult = ReturnType<typeof useLoginMutation>;
export type LoginMutationResult = Apollo.MutationResult<LoginMutation>;
export type LoginMutationOptions = Apollo.BaseMutationOptions<
LoginMutation,
LoginMutationVariables
>;
export const LogoutDocument = gql`
mutation Logout {
Logout
}
`;
export type LogoutMutationFn = Apollo.MutationFunction<
LogoutMutation,
LogoutMutationVariables
>;
/**
* __useLogoutMutation__
*
* To run a mutation, you first call `useLogoutMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useLogoutMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [logoutMutation, { data, loading, error }] = useLogoutMutation({
* variables: {
* },
* });
*/
export function useLogoutMutation(
baseOptions?: Apollo.MutationHookOptions<LogoutMutation, LogoutMutationVariables>,
) {
return Apollo.useMutation<LogoutMutation, LogoutMutationVariables>(
LogoutDocument,
baseOptions,
);
}
export type LogoutMutationHookResult = ReturnType<typeof useLogoutMutation>;
export type LogoutMutationResult = Apollo.MutationResult<LogoutMutation>;
export type LogoutMutationOptions = Apollo.BaseMutationOptions<
LogoutMutation,
LogoutMutationVariables
>;
export const RefreshTokenDocument = gql`
mutation RefreshToken {
RefreshToken
}
`;
export type RefreshTokenMutationFn = Apollo.MutationFunction<
RefreshTokenMutation,
RefreshTokenMutationVariables
>;
/**
* __useRefreshTokenMutation__
*
* To run a mutation, you first call `useRefreshTokenMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useRefreshTokenMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [refreshTokenMutation, { data, loading, error }] = useRefreshTokenMutation({
* variables: {
* },
* });
*/
export function useRefreshTokenMutation(
baseOptions?: Apollo.MutationHookOptions<
RefreshTokenMutation,
RefreshTokenMutationVariables
>,
) {
return Apollo.useMutation<RefreshTokenMutation, RefreshTokenMutationVariables>(
RefreshTokenDocument,
baseOptions,
);
}
export type RefreshTokenMutationHookResult = ReturnType<typeof useRefreshTokenMutation>;
export type RefreshTokenMutationResult = Apollo.MutationResult<RefreshTokenMutation>;
export type RefreshTokenMutationOptions = Apollo.BaseMutationOptions<
RefreshTokenMutation,
RefreshTokenMutationVariables
>;
export const UpdateUserDocument = gql`
mutation UpdateUser($UserUpdateInput: UserUpdateInput!) {
UpdateUser(UserUpdateInput: $UserUpdateInput) {
_id
createAt
deactivate
email
mainEmail
name
oauth {
provider
token
}
package
role
updateAt
zone
}
}
`;
export type UpdateUserMutationFn = Apollo.MutationFunction<
UpdateUserMutation,
UpdateUserMutationVariables
>;
/**
* __useUpdateUserMutation__
*
* To run a mutation, you first call `useUpdateUserMutation` within a React component and pass it any options that fit your needs.
* When your component renders, `useUpdateUserMutation` returns a tuple that includes:
* - A mutate function that you can call at any time to execute the mutation
* - An object with fields that represent the current status of the mutation's execution
*
* @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
*
* @example
* const [updateUserMutation, { data, loading, error }] = useUpdateUserMutation({
* variables: {
* UserUpdateInput: // value for 'UserUpdateInput'
* },
* });
*/
export function useUpdateUserMutation(
baseOptions?: Apollo.MutationHookOptions<
UpdateUserMutation,
UpdateUserMutationVariables
>,
) {
return Apollo.useMutation<UpdateUserMutation, UpdateUserMutationVariables>(
UpdateUserDocument,
baseOptions,
);
}
export type UpdateUserMutationHookResult = ReturnType<typeof useUpdateUserMutation>;
export type UpdateUserMutationResult = Apollo.MutationResult<UpdateUserMutation>;
export type UpdateUserMutationOptions = Apollo.BaseMutationOptions<
UpdateUserMutation,
UpdateUserMutationVariables
>;
<file_sep>/src/modules/task/mocks/data.ts
import { Sync, each } from 'factory.ts';
import faker from 'faker';
import { ModelEnum } from '../models/model.enum';
export interface IDataSource {
_id: string;
timestamp: string;
taskID: string;
taskName: string;
model: ModelEnum;
progress: number;
elaspedTime: string;
inprogressPhoto: number;
totalPhoto: number;
}
const DataSourceMock = Sync.makeFactory<IDataSource>({
_id: each(() => faker.random.uuid()),
timestamp: each(() => faker.date.past().toISOString()),
taskID: each(() => faker.random.uuid()),
taskName: each(() => faker.lorem.word()),
model: each(() => faker.random.arrayElement(Object.values(ModelEnum))),
progress: each(() =>
faker.random.number({
min: 0,
max: 100,
}),
),
elaspedTime: each(() => faker.date.past().toISOString()),
inprogressPhoto: each(() =>
faker.random.number({
min: 0,
max: 1000,
}),
),
totalPhoto: each(() =>
faker.random.number({
min: 1000,
max: 2000,
}),
),
});
const ProgressMock = Sync.makeFactory({
progress: each(() =>
faker.random.number({
min: 0,
max: 100,
}),
),
});
const ElaspedTimeMock = Sync.makeFactory({
elaspedTime: each(() => faker.date.past().toISOString()),
});
const InprogressPhotoMock = Sync.makeFactory({
inprogressPhoto: each(() =>
faker.random.number({
min: 0,
max: 1000,
}),
),
});
const TotalPhotoMock = Sync.makeFactory({
totalPhoto: each(() =>
faker.random.number({
min: 1000,
max: 2000,
}),
),
});
const ActiveMock = Sync.makeFactory({
active: each(() => faker.random.boolean()),
});
export const DataSource: IDataSource[] = DataSourceMock.buildList(10);
export const Progress = ProgressMock.build();
export const ElaspedTime = ElaspedTimeMock.build();
export const InprogressPhoto = InprogressPhotoMock.build();
export const TotalPhoto = TotalPhotoMock.build();
export const Active = ActiveMock.build();
<file_sep>/src/common/components/ToggleLabel/types.ts
import { ReactNode } from 'react';
type ToggleLabelProps = {
selected?: boolean;
children: ReactNode;
onClick: () => void;
};
type ToggleLabelWrapperProps = {
selected: boolean;
};
export type { ToggleLabelProps, ToggleLabelWrapperProps };
<file_sep>/src/modules/task/utils/modelColor.ts
export function modelColor(model: string): string {
switch (model) {
case 'faces_emo':
return 'red';
case 'detection_600':
return 'cyan';
case 'ilsvrc_googlenet':
return 'geekblue';
case 'basic_fashion':
return 'orange';
case 'classification_21k':
return 'gold';
case 'places':
return 'green';
case 'vgg16':
return 'blue';
default:
return 'black';
}
}
<file_sep>/src/modules/photos/services/fetch.images.ts
import axios from 'axios';
import { PhotosAPI } from '../constants/photo/interface';
export const fetchImages = async (): Promise<PhotosAPI[]> => {
const apiRoot = 'https://api.unsplash.com';
const accessKey = '<KEY>';
const { data } = await axios.get(
`${apiRoot}/photos/random?client_id=${accessKey}&count=5`,
);
return data;
};
<file_sep>/src/modules/photos/components/GroupThumbnailPhotos/Header/types.ts
export interface Props {
selected: boolean;
date: Date;
onSelect: (s: boolean) => void;
}
<file_sep>/src/modules/dashboard/constants/model.enum.ts
export enum ModelEnum {
RESNET = 'ResNet',
VGG = 'VGG16',
NONE = '-',
}
<file_sep>/src/modules/photos/reducers/instantSearchReducer/types.ts
export const INSTANT_SEARCH = 'INSTANT_SEARCH';
export type InstantSearchReducer = {
autocomplete: string[];
result: { _id: string }[];
word: string;
loading: boolean;
};
<file_sep>/src/modules/dashboard/components/AlbumPreview/types.ts
export type AlbumPreviewProps = {
src: string;
children?: React.ReactNode;
albumName?: string;
albumLength?: number;
label: Array<string>;
//TODO: - required link when have a real props link
link?: string;
};
<file_sep>/src/modules/photos/reducers/photosReducer/index.spec.ts
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import { PhotosAPI } from 'Modules/photos/constants/photo/interface';
import { fetchPhotosData } from './actions';
import photosReducer, { photosActions } from './index';
import { initPhotosState } from './init';
const rootReducer = combineReducers({
photos: photosReducer,
});
const store = configureStore({
reducer: rootReducer,
});
describe('photoReducer test', () => {
it('it should correctly define initial state', () => {
store.dispatch(photosActions.init());
const result = store.getState().photos;
expect(result).toEqual(initPhotosState);
});
it('should have pending/fulfill fetchPhotosData', async () => {
store.dispatch({
type: fetchPhotosData.fulfilled.type,
payload: { data: mockdata },
});
expect(store.getState().photos.data.ready).toBe(true);
});
it('Should able to select photo from data', () => {
const expectedId = 'gd0US-3s-KM';
store.dispatch(photosActions.selectPhotos({ photoId: expectedId, albumId: '' }));
expect(store.getState().photos.presentation.views?.photo?._id).toBe(expectedId);
});
});
const mockdata = ([
{
id: 'gd0US-3s-KM',
created_at: '2021-01-11T09:50:05-05:00',
updated_at: '2021-01-27T03:46:37-05:00',
promoted_at: '2021-01-11T12:48:01-05:00',
width: 5191,
height: 3461,
color: '#262626',
blur_hash: 'L042PDoeIUV@%MWBjtRj00t7t6j]',
description: null,
alt_description: 'white flowers on black background',
urls: {
raw:
'https://images.unsplash.com/photo-1610375550819-e4bd8d698a49?ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1',
full:
'https://images.unsplash.com/photo-1610375550819-e4bd8d698a49?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85',
regular:
'https://images.unsplash.com/photo-1610375550819-e4bd8d698a49?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080',
small:
'https://images.unsplash.com/photo-1610375550819-e4bd8d698a49?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400',
thumb:
'https://images.unsplash.com/photo-1610375550819-e4bd8d698a49?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200',
},
links: {
self: 'https://api.unsplash.com/photos/gd0US-3s-KM',
html: 'https://unsplash.com/photos/gd0US-3s-KM',
download: 'https://unsplash.com/photos/gd0US-3s-KM/download',
download_location: 'https://api.unsplash.com/photos/gd0US-3s-KM/download',
},
categories: [],
likes: 55,
liked_by_user: false,
current_user_collections: [],
sponsorship: null,
user: {
id: 'ZK_E-Z9fbEw',
updated_at: '2021-01-27T10:21:44-05:00',
username: 'emkaay',
name: '<NAME>',
first_name: 'Manuel',
last_name: 'Keller',
twitter_username: null,
portfolio_url: 'http://www.manuel-keller.de',
bio:
'german designer, pro-procrastinator, sleep-addict and hopeless romantic. Loves #000000 / #FFFFFF more than you do. Seriously.',
location: null,
links: [],
profile_image: [],
instagram_username: 'emkaay666',
total_collections: 3,
total_likes: 34,
total_photos: 39,
accepted_tos: true,
},
exif: {
make: 'SONY',
model: 'ILCE-6400',
exposure_time: '1/200',
aperture: '4',
focal_length: '70.0',
iso: 1000,
},
location: {
title: 'Randersacker, Deutschland',
name: 'Randersacker, Deutschland',
city: 'Randersacker',
country: 'Deutschland',
position: [],
},
views: 512071,
downloads: 4170,
},
{
id: 'E8euHYBHRh8',
created_at: '2021-01-12T12:33:32-05:00',
updated_at: '2021-01-27T13:22:28-05:00',
promoted_at: '2021-01-12T12:45:03-05:00',
width: 4000,
height: 6000,
color: '#262626',
blur_hash: 'LHB{}$ELIoxa8wE1fks:_3W;WBt7',
description: null,
alt_description: 'person wearing brown and black hiking shoe',
urls: {
raw:
'https://images.unsplash.com/photo-1610471650881-7a5faa19f466?ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1',
full:
'https://images.unsplash.com/photo-1610471650881-7a5faa19f466?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85',
regular:
'https://images.unsplash.com/photo-1610471650881-7a5faa19f466?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080',
small:
'https://images.unsplash.com/photo-1610471650881-7a5faa19f466?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400',
thumb:
'https://images.unsplash.com/photo-1610471650881-7a5faa19f466?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200',
},
links: {
self: 'https://api.unsplash.com/photos/E8euHYBHRh8',
html: 'https://unsplash.com/photos/E8euHYBHRh8',
download: 'https://unsplash.com/photos/E8euHYBHRh8/download',
download_location: 'https://api.unsplash.com/photos/E8euHYBHRh8/download',
},
categories: [],
likes: 18,
liked_by_user: false,
current_user_collections: [],
sponsorship: null,
user: {
id: 'H39kP5YQVmM',
updated_at: '2021-01-26T07:13:10-05:00',
username: 'maceylarie',
name: '<NAME>',
first_name: 'Macey',
last_name: 'Bundt',
twitter_username: null,
portfolio_url: 'http://www.maceybundt.com',
bio:
'Marketing Specialist I Photographer I Videographer\r\n' +
"Thanks for using my photos! If you want, credit me by using the tag @maceylarie or for our Maine Coon Lux's page, @luxmainecoon ",
location: 'Wisconsin',
links: [],
profile_image: [],
instagram_username: 'maceylarie',
total_collections: 2,
total_likes: 19,
total_photos: 39,
accepted_tos: true,
},
exif: {
make: 'SONY',
model: 'ILCE-7M3',
exposure_time: '1/160',
aperture: '1.8',
focal_length: '50.0',
iso: 50,
},
location: {
title: 'Oregon, USA',
name: 'Oregon, USA',
city: null,
country: 'United States',
position: [],
},
views: 554038,
downloads: 1114,
},
{
id: 'A<PASSWORD>',
created_at: '2021-01-12T23:57:14-05:00',
updated_at: '2021-01-27T09:22:42-05:00',
promoted_at: '2021-01-14T06:12:04-05:00',
width: 6720,
height: 4480,
color: '#d9d9d9',
blur_hash: 'LaN0;y%$s,xu?^s:WBbHMxRPxut7',
description: 'A nice bright bedroom decor',
alt_description: 'white bed linen on bed',
urls: {
raw:
'https://images.unsplash.com/photo-1610513492570-914a65a5d5ae?ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1',
full:
'https://images.unsplash.com/photo-1610513492570-914a65a5d5ae?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85',
regular:
'https://images.unsplash.com/photo-1610513492570-914a65a5d5ae?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080',
small:
'https://images.unsplash.com/photo-1610513492570-914a65a5d5ae?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400',
thumb:
'https://images.unsplash.com/photo-1610513492570-914a65a5d5ae?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200',
},
links: {
self: 'https://api.unsplash.com/photos/A2m-9Yy12-s',
html: 'https://unsplash.com/photos/A2m-9Yy12-s',
download: 'https://unsplash.com/photos/A2m-9Yy12-s/download',
download_location: 'https://api.unsplash.com/photos/A2m-9Yy12-s/download',
},
categories: [],
likes: 43,
liked_by_user: false,
current_user_collections: [],
sponsorship: null,
user: {
id: '4OPTMrypU3g',
updated_at: '2021-01-27T14:28:18-05:00',
username: 'chshashi30',
name: '<NAME>',
first_name: 'Shashi',
last_name: 'Ch',
twitter_username: null,
portfolio_url: 'https://www.instagram.com/thephotographermom/',
bio:
'I am a stock photographer focused on health and wellness. I also do family photography. ',
location: null,
links: [],
profile_image: [],
instagram_username: 'thephotographermom',
total_collections: 0,
total_likes: 7,
total_photos: 48,
accepted_tos: true,
},
exif: {
make: null,
model: null,
exposure_time: null,
aperture: null,
focal_length: null,
iso: null,
},
location: {
title: null,
name: null,
city: null,
country: null,
position: [],
},
views: 311612,
downloads: 3236,
},
{
id: 'NV-2IV74iJU',
created_at: '2021-01-13T04:28:32-05:00',
updated_at: '2021-01-27T07:19:52-05:00',
promoted_at: '2021-01-13T05:27:03-05:00',
width: 4109,
height: 6163,
color: '#f3f3f3',
blur_hash: 'LeIhmh-=t7M{9GaeWBax4TM{M{of',
description: 'Analog point and shoot camera on table\n',
alt_description: 'black and silver camera on white table',
urls: {
raw:
'https://images.unsplash.com/photo-1610530096354-e5da74e8062d?ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1',
full:
'https://images.unsplash.com/photo-1610530096354-e5da74e8062d?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85',
regular:
'https://images.unsplash.com/photo-1610530096354-e5da74e8062d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080',
small:
'https://images.unsplash.com/photo-1610530096354-e5da74e8062d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400',
thumb:
'https://images.unsplash.com/photo-1610530096354-e5da74e8062d?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200',
},
links: {
self: 'https://api.unsplash.com/photos/NV-2IV74iJU',
html: 'https://unsplash.com/photos/NV-2IV74iJU',
download: 'https://unsplash.com/photos/NV-2IV74iJU/download',
download_location: 'https://api.unsplash.com/photos/NV-2IV74iJU/download',
},
categories: [],
likes: 24,
liked_by_user: false,
current_user_collections: [],
sponsorship: null,
user: {
id: 'CU0kB_aF_X4',
updated_at: '2021-01-27T12:43:19-05:00',
username: 'maybejensen',
name: '<NAME>',
first_name: 'Lasse',
last_name: 'Jensen',
twitter_username: 'maybejensen',
portfolio_url: 'http://maybejensen.com',
bio:
'📍Odense / Denmark\r\n' +
'I create marketing images that sell products and ideas. Photography / 3D Illustrations',
location: 'Denmark',
links: [],
profile_image: [],
instagram_username: 'maybejensen',
total_collections: 0,
total_likes: 69,
total_photos: 29,
accepted_tos: true,
},
exif: {
make: 'FUJIFILM',
model: 'X-T4',
exposure_time: '1/50',
aperture: '2.0',
focal_length: '35.0',
iso: 640,
},
location: {
title: null,
name: null,
city: null,
country: null,
position: [],
},
views: 360878,
downloads: 1078,
},
{
id: 'mZ7ZsqrG4is',
created_at: '2021-01-15T21:50:40-05:00',
updated_at: '2021-01-27T14:18:09-05:00',
promoted_at: '2021-01-16T05:54:02-05:00',
width: 2060,
height: 2575,
color: '#a6a6a6',
blur_hash: 'LBAAaat7M{9F~qWBIUofD%WBD%%M',
description: null,
alt_description: 'woman in black suit jacket sitting on seat',
urls: {
raw:
'https://images.unsplash.com/photo-1610765431323-d88c88a2b2c8?ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1',
full:
'https://images.unsplash.com/photo-1610765431323-d88c88a2b2c8?crop=entropy&cs=srgb&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=85',
regular:
'https://images.unsplash.com/photo-1610765431323-d88c88a2b2c8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=1080',
small:
'https://images.unsplash.com/photo-1610765431323-d88c88a2b2c8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=400',
thumb:
'https://images.unsplash.com/photo-1610765431323-d88c88a2b2c8?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MXwxOTc2MTh8MHwxfHJhbmRvbXx8fHx8fHx8&ixlib=rb-1.2.1&q=80&w=200',
},
links: {
self: 'https://api.unsplash.com/photos/mZ7ZsqrG4is',
html: 'https://unsplash.com/photos/mZ7ZsqrG4is',
download: 'https://unsplash.com/photos/mZ7ZsqrG4is/download',
download_location: 'https://api.unsplash.com/photos/mZ7ZsqrG4is/download',
},
categories: [],
likes: 48,
liked_by_user: false,
current_user_collections: [],
sponsorship: null,
user: {
id: 'qvghZd64Lhw',
updated_at: '2021-01-27T14:33:15-05:00',
username: 'happyfaceemoji',
name: '<NAME>',
first_name: '<NAME>',
last_name: null,
twitter_username: null,
portfolio_url: 'https://www.hfeandco.com',
bio: 'Fashion & Beauty Photographer\r\nInstagram: @_happyfaceemoji',
location: 'Vancouver, Canada',
links: [],
profile_image: [],
instagram_username: '_happyfaceemoji',
total_collections: 0,
total_likes: 0,
total_photos: 298,
accepted_tos: true,
},
exif: {
make: null,
model: null,
exposure_time: null,
aperture: null,
focal_length: null,
iso: null,
},
location: {
title: null,
name: null,
city: null,
country: null,
position: [],
},
views: 205791,
downloads: 805,
},
].map((el) => ({ ...el, _id: el.id })) as unknown) as PhotosAPI[];
<file_sep>/src/modules/user/reducers/userReducer/userReducer.spec.ts
import { combineReducers, configureStore } from '@reduxjs/toolkit';
import {
UserPackageEnumSession,
UserRoleEnumSession,
UserZoneEnumSession,
} from '../../../../common/generated/generated-types';
import userReducer, { userActions } from '.';
import { initUserState } from './init';
import { User } from './types';
const rootReducer = combineReducers({
user: userReducer,
});
const store = configureStore({
reducer: rootReducer,
});
describe('user reducer test', () => {
it('should init user state correctly', () => {
store.dispatch(userActions.init());
const result = store.getState().user;
expect(result).toEqual(initUserState);
});
it('should set user correctly', () => {
const UserData: User = {
id: '1',
mainEmail: '<EMAIL>',
name: '<NAME>',
package: UserPackageEnumSession.FreeUser,
role: UserRoleEnumSession.User,
zone: UserZoneEnumSession.Th1,
};
store.dispatch(userActions.setUser(UserData));
const result = store.getState().user.user;
expect(result).toEqual(UserData);
});
it('should delete user correctly', () => {
store.dispatch(userActions.deleteUser());
const result = store.getState().user;
expect(result).toEqual(initUserState);
});
});
<file_sep>/src/modules/dashboard/components/DashboardCard/ProgressCard/types.ts
export type ProgressCardProps = {
cardName: string;
progress: number;
doneNumber: number;
totalNumber: number;
};
<file_sep>/src/modules/photos/reducers/photosReducer/types.ts
import { PayloadAction } from '@reduxjs/toolkit';
import { PhotosAPI } from 'Modules/photos/constants/photo/interface';
import { Album } from 'Modules/photos/models/album';
import { Photo } from 'Modules/photos/models/photo';
import { GroupThumbnailPhotos, ThumbnailPhoto } from 'Modules/photos/models/thumbnail';
import { ErrorState } from 'Stores/common/types/error';
export const PHOTOS = 'PHOTOS';
export type PhotoState = {
data: {
photos: Array<PhotosAPI & { _id: string }>;
albums: Album[];
ready: boolean;
};
presentation: {
thumbnail?: ThumbnailPhoto[];
thumbnailGroup?: GroupThumbnailPhotos[];
views?: {
photo: Photo;
album?: Album;
};
};
error?: ErrorState;
};
export type SelectedPhotoPayload = PayloadAction<{
photoId: Photo['_id'];
albumId: Album['_id'];
}>;
<file_sep>/src/common/utils/path-join.test.ts
import pathJoin from './path-join';
describe('path join', () => {
it('should return what expected', () => {
const resultWithOne = pathJoin(['app']);
expect(resultWithOne).toEqual('app/');
const resultWithSlash = pathJoin(['app', 'test']);
expect(resultWithSlash).toEqual('app/test');
const resultWIthCommna = pathJoin(['app', 'test'], ',');
expect(resultWIthCommna).toEqual('app,test');
});
});
<file_sep>/src/modules/task/utils/checkStatus.ts
export function checkStatus(
wait: number,
excute: number,
finish: number,
): { color: string; status: string } {
let color = '';
let status = '';
if (finish > 0 && excute === 0 && wait === 0) {
color = 'green';
status = 'FINISH';
} else if (excute > 0) {
color = 'orange';
status = 'RUNNING';
} else if (wait > 0 && excute === 0) {
color = 'purple';
status = 'WAITING';
}
return { color, status };
}
<file_sep>/src/modules/photos/reducers/photosReducer/init.ts
import { PhotoState } from './types';
export const initPhotosState: PhotoState = {
data: {
photos: [],
albums: [],
ready: false,
},
presentation: {},
};
<file_sep>/src/modules/photos/constants/photo/interface.ts
import { Tag } from 'Modules/photos/models/tags';
// TODO: deprecate this interface
export interface PhotosAPI {
id: string;
created_at: string;
updated_at: string;
width: number;
height: number;
color: string;
blur_hash: string;
downloads: number;
likes: number;
liked_by_user: boolean;
description: string;
location: LocationAPI;
urls: URLAPI;
links: Link;
user: User;
tags?: Tag[];
}
export interface LocationAPI {
name: string;
city: string;
country: string;
title?: string;
}
export interface URLAPI {
raw: string;
full: string;
regular: string;
small: string;
thumb: string;
}
export interface Link {
self: string;
html: string;
download: string;
download_location: string;
}
export interface User {
name: string;
total_likes: number;
}
<file_sep>/src/modules/photos/components/ThumbnailPhoto/types.ts
import { ThumbnailPhoto } from 'Modules/photos/models/thumbnail';
export interface Props extends ThumbnailPhoto {
onSelect?: (s: boolean) => void;
onClick?: () => void;
}
<file_sep>/src/common/stores/index.ts
import { combineReducers, configureStore, Middleware } from '@reduxjs/toolkit';
import taskReducer from 'Modules/task/reducer/taskReducer';
import historyReducer from 'Modules/history/reducer/historyReducer';
import dashboardReducer from 'Modules/dashboard/reducer/dashboardReducer';
import photosReducer from 'Modules/photos/reducers/photosReducer';
import uploadReducer from 'Modules/upload/reducer/uploadReducer';
import userReducer from 'Modules/user/reducers/userReducer';
import thunk, { ThunkMiddleware } from 'redux-thunk';
import instantSearchReducer from 'Modules/photos/reducers/instantSearchReducer';
const rootReducer = combineReducers({
user: userReducer,
task: taskReducer,
history: historyReducer,
dashboard: dashboardReducer,
photos: photosReducer,
upload: uploadReducer,
instantSearch: instantSearchReducer,
});
export const middleware: ThunkMiddleware[] | Middleware[] = [thunk];
export type StoresState = ReturnType<typeof rootReducer>;
const store = configureStore({
reducer: rootReducer,
middleware,
});
export { store, rootReducer };
<file_sep>/src/common/components/Button/types.ts
interface Style {
type?: 'secondary' | 'success' | 'danger' | 'disable';
}
interface Size {
type?: 'small' | 'large';
}
export type ButtonComponentProps = {
children?: HTMLCollection | string;
onClick?: (e?: React.MouseEvent) => void;
color?: Style['type'];
style?: Style;
size?: Size['type'];
} & React.ButtonHTMLAttributes<HTMLButtonElement>;
<file_sep>/src/modules/history/reducer/historyReducer/index.ts
import { createSlice } from '@reduxjs/toolkit';
import { ErrorStateCodeEnum } from 'Stores/common/types/error';
import { fetchHistoryData } from './actions';
import { initHistoryState } from './init';
import { HISTORY } from './types';
export const historySlice = createSlice({
name: HISTORY,
initialState: initHistoryState,
reducers: {
init(state) {
return { ...state, ...initHistoryState };
},
},
extraReducers: (builder) => {
builder.addCase(fetchHistoryData.rejected, (state) => {
state.ready = false;
state.error = { code: ErrorStateCodeEnum.ServerInternalError, msg: 'api error' };
});
builder.addCase(fetchHistoryData.pending, (state) => {
state.ready = false;
state.error = undefined;
});
builder.addCase(fetchHistoryData.fulfilled, (state, action: any) => {
state.ready = true;
state.error = undefined;
state.data = action.payload.data;
});
},
});
export default historySlice.reducer;
export const historyActions = historySlice.actions;
<file_sep>/Dockerfile
FROM node:14-alpine3.12 as base
COPY yarn.lock yarn.lock
COPY package.json package.json
RUN yarn install
# args
ARG APP_GRAPHQL_ENDPOINT
ENV APP_GRAPHQL_ENDPOINT=${APP_GRAPHQL_ENDPOINT}
ARG APP_BACKEND_STORAGE_ENDPOINT
ENV APP_BACKEND_STORAGE_ENDPOINT=${APP_BACKEND_STORAGE_ENDPOINT}
FROM base as dev
ADD . .
VOLUME [ "/src" ]
CMD ["yarn", "dev"]
EXPOSE 3000
FROM base AS service
ADD . .
# RUN yarn test //temporalilty disable for rush time
RUN yarn build
ENTRYPOINT [ "yarn", "start" ]
EXPOSE 3000
<file_sep>/src/modules/task/utils/stringCutter.ts
export function stringCutter(data: string): string {
const str = data.substring(5, -2);
return str;
}
<file_sep>/src/modules/photos/components/GroupThumbnailPhotos/types.ts
import { GroupThumbnailPhotos } from 'Modules/photos/models/thumbnail';
export interface Props extends GroupThumbnailPhotos {
onSelect?: (s: boolean) => void;
}
<file_sep>/src/modules/dashboard/components/DashboardCard/ModelCard/types.ts
export type ModelCardProps = {
cardName: string;
model: string;
largeNumber: number;
};
<file_sep>/src/modules/photos/models/thumbnail/index.ts
export type ThumbnailPhoto = {
label?: string;
src: string;
selected: boolean;
createAt: Date;
};
export type GroupThumbnailPhotos = {
selected: boolean;
photos: ThumbnailPhoto[];
dateRange: [Date, Date];
};
<file_sep>/src/modules/history/pages/types.ts
import { ModelEnum } from '../models/model.enum';
import { StatusEnum } from '../models/status.enum';
export type HistoryData = {
key: string;
taskID: string;
taskName: string;
model: ModelEnum;
startTime: string;
finishTime: string;
status: StatusEnum;
};
<file_sep>/src/modules/dashboard/constants/init.ts
import { Dashboard } from '../models/types';
export const initState: Dashboard = {
FileDashboardData: {
photo: {
total: 0,
today: 0,
},
video: {
total: 0,
today: 0,
},
},
FileInsightDashboardData: [],
};
<file_sep>/src/common/utils/makeArray.ts
export function makeArray<T>(length: number, generator: () => T): T[] {
return Array.from({ length }, generator);
}
<file_sep>/src/modules/photos/components/GroupThumbnailPhotos/constants.ts
import { GroupThumbnailPhotos } from 'Modules/photos/models/thumbnail';
export const mock: GroupThumbnailPhotos = {
selected: true,
dateRange: [new Date(), new Date()],
photos: [
{
selected: false,
src: 'https://cdn.pixabay.com/photo/2015/07/31/14/59/beach-869195_1280.jpg',
createAt: new Date(),
},
{
selected: true,
src: 'https://cdn.pixabay.com/photo/2021/01/04/12/44/cat-5887426_1280.jpg',
createAt: new Date(),
},
{
selected: true,
src: 'https://cdn.pixabay.com/photo/2021/01/04/12/44/cat-5887426_1280.jpg',
createAt: new Date(),
},
{
selected: true,
src: 'https://cdn.pixabay.com/photo/2021/01/04/12/44/cat-5887426_1280.jpg',
createAt: new Date(),
},
{
selected: true,
src: 'https://cdn.pixabay.com/photo/2021/01/04/12/44/cat-5887426_1280.jpg',
createAt: new Date(),
},
{
selected: true,
src: 'https://cdn.pixabay.com/photo/2021/01/04/12/44/cat-5887426_1280.jpg',
createAt: new Date(),
},
],
};
<file_sep>/src/modules/photos/mocks/data.ts
import { PhotosAPI } from '../constants/photo/interface';
export const mockData: PhotosAPI[] = [
{
id: '12346',
created_at: '',
updated_at: '',
width: 1052,
height: 700,
color: '',
blur_hash: '',
downloads: 0,
likes: 0,
liked_by_user: false,
description: '',
location: {
name: '',
title: '',
city: '',
country: '',
},
urls: {
raw: '',
full: '',
regular: '',
small: '',
thumb:
'https://images.unsplash.com/photo-1558221221-e2d4f80ccaba?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1052&q=80',
},
links: {
self: '',
html: '',
download: '',
download_location: '',
},
user: {
name: '',
total_likes: 0,
},
tags: [
{
result: 'cat',
xMin: 309,
xMax: 696,
yMin: 169,
yMax: 474,
},
],
},
];
<file_sep>/src/modules/task/reducer/taskReducer/types.ts
import { ModelEnum } from 'Modules/task/models/model.enum';
import { ErrorState } from 'Stores/common/types/error';
import { TaskStatus } from '../../../../common/generated/generated-types';
export const TASK = 'TASK';
export type TaskData = {
_id: string;
timestamp: string;
taskID: string;
taskName: string;
model: ModelEnum;
progress: number;
elaspedTime: string;
inprogressPhoto: number;
totalPhoto: number;
};
export enum TaskStatusEnum {
PAUSE = 'PAUSE',
WAITING = 'WAITING',
CANCEL = 'CANCEL',
FINISH = 'FINISH',
RUNNING = 'RUNNING',
}
export type TaskState = {
data: {
tasks: TaskStatus[];
quota: number;
};
present: {
tasks: TaskStatus[];
};
ready: boolean;
error?: ErrorState;
};
<file_sep>/src/modules/photos/models/album/index.ts
export type Album = {
_id: string;
label: string;
createAt: Date;
updateAt: Date;
n: number;
};
<file_sep>/src/modules/upload/components/SelectFileButton/type.ts
type SelectFileButtonPropsType = {
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
export type { SelectFileButtonPropsType };
<file_sep>/src/common/stores/common/types/error.ts
export enum ErrorStateCodeEnum {
ServerInternalError = 500,
BadRequest = 400,
}
export type ErrorState = {
code: ErrorStateCodeEnum;
msg: string;
};
<file_sep>/src/modules/upload/services/upload.file.ts
import adapter from 'Services/adapter.service';
import { FileListResponseDTO } from 'fluentsearch-types';
export const uploadFile = async (file: FormData): Promise<FileListResponseDTO[]> => {
const response = await adapter.instance.post('/', file, {
headers: {
'content-type': 'multipart/form-data',
},
});
return response.data;
};
<file_sep>/src/modules/photos/models/init.ts
import { RecentFile } from '../../../common/generated/generated-types';
export const initialState: RecentFile = {
createAt: '',
original_filename: '',
updateAt: '',
uri: '',
uri_thumbnail: '',
_id: '',
type: '',
};
<file_sep>/src/modules/user/reducers/userReducer/init.ts
import {
UserPackageEnumSession,
UserRoleEnumSession,
UserZoneEnumSession,
} from '../../../../common/generated/generated-types';
import { UserState } from './types';
export const initUserState: UserState = {
user: {
id: '',
mainEmail: '',
name: '',
package: UserPackageEnumSession.FreeUser,
role: UserRoleEnumSession.User,
zone: UserZoneEnumSession.Th1,
},
authenticated: false,
};
<file_sep>/src/common/utils/path-join.ts
const pathJoin = (paths: string[], sep?: string): string => {
const defaultSeperator = '/';
if (paths.length === 1) return `${paths[0]}${sep || defaultSeperator}`;
return paths.join(sep || defaultSeperator);
};
export default pathJoin;
<file_sep>/src/modules/photos/components/Lightbox/constants.ts
import { LightboxPropsType } from './types';
function mockFunction(): void {
console.log('click');
}
export const mock: LightboxPropsType = {
image: {
_id: '1',
original_filename: 'cat.jpg',
uri:
'https://aumento.officemate.co.th/media/catalog/product/h/t/httpss3-ap-southeast-1.amazonaws.compim-prod-product-images68bc68bcce438a2454140271526c7e2497bdce6813ad_mkp0539918dummy.jpg?imwidth=640',
uri_thumbnail:
'https://aumento.officemate.co.th/media/catalog/product/h/t/httpss3-ap-southeast-1.amazonaws.compim-prod-product-images68bc68bcce438a2454140271526c7e2497bdce6813ad_mkp0539918dummy.jpg?imwidth=640',
createAt: 'today',
updateAt: 'today',
type: 'image',
},
onPrev: mockFunction,
onNext: mockFunction,
closeLightbox: mockFunction,
};
<file_sep>/src/common/hooks/useToggle/index.ts
import { useState } from 'react';
import { useTogglePropsType } from './types';
function useToggle(): useTogglePropsType {
const [value, setValue] = useState(false);
const toggle = () => setValue(!value);
return [value, toggle];
}
export default useToggle;
<file_sep>/src/modules/history/mocks/data.ts
import { Sync, each } from 'factory.ts';
import faker from 'faker';
import { StatusEnum } from 'Modules/history/models/status.enum';
import { ModelEnum } from '../models/model.enum';
export interface IDataSource {
key: string;
taskID: string;
taskName: string;
model: ModelEnum;
startTime: string;
finishTime: string;
status: StatusEnum;
}
const DataSourceMock = Sync.makeFactory<IDataSource>({
key: each(() => faker.random.uuid()),
taskID: each(() => faker.random.uuid()),
taskName: each(() => faker.lorem.word()),
model: each(() => faker.random.arrayElement(Object.values(ModelEnum))),
startTime: each(() => faker.date.past().toString()),
finishTime: each(() => faker.date.past().toString()),
status: each(() => faker.random.arrayElement(Object.values(StatusEnum))),
});
export const DataSource: IDataSource[] = DataSourceMock.buildList(10);
<file_sep>/src/modules/user/models/constants.ts
import { FormProps } from 'antd/lib/form';
export const layout: FormProps = {
labelCol: { span: 8 },
wrapperCol: { span: 24 },
};
<file_sep>/src/common/services/adapter.service.ts
import axios, { AxiosInstance } from 'axios';
export const END_POINT =
process.env.APP_BACKEND_STORAGE_ENDPOINT || 'http://storage.fluentsearch.ml';
class Adapter {
instance: AxiosInstance;
constructor() {
this.instance = axios.create({
baseURL: END_POINT,
timeout: 60000,
withCredentials: true,
});
}
}
const adapter = new Adapter();
export default adapter;
<file_sep>/src/modules/dashboard/services/fetch.dashboardData.ts
import { AlbumPreviewProps } from '../components/AlbumPreview/types';
import { AlbumPreviewMockData, DashboardMockData } from '../mocks/data';
import { DashboardData } from '../models/types';
type DashboardDataType = {
DashboardMockData: DashboardData;
AlbumPreviewMockData: AlbumPreviewProps[];
};
const data = {
DashboardMockData,
AlbumPreviewMockData,
};
//TODO: Connect with Adapter and real api
export const fetchDashboard = (): DashboardDataType => {
return data;
};
<file_sep>/src/modules/home/constants/feature/index.ts
import { FeatureType } from './types';
export const APP_FEATURE_CONSTANT: FeatureType[] = [
{
key: '1',
icon: 'CarOutlined',
label: 'Feature 1',
description:
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus earum iusto',
},
{
key: '2',
icon: 'CarOutlined',
label: 'Feature 1',
description:
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus earum iusto',
},
{
key: '3',
icon: 'CarOutlined',
label: 'Feature 1',
description:
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus earum iusto',
},
{
key: '4',
icon: 'CarOutlined',
label: 'Feature 1',
description:
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus earum iusto',
},
{
key: '5',
icon: 'CarOutlined',
label: 'Feature 1',
description:
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus earum iusto',
},
{
key: '6',
icon: 'CarOutlined',
label: 'Feature 1',
description:
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus earum iusto',
},
];
<file_sep>/src/modules/photos/reducers/photosReducer/index.ts
import { createSlice } from '@reduxjs/toolkit';
import { ErrorStateCodeEnum } from 'Stores/common/types/error';
import { fetchPhotosData } from './actions';
import { initPhotosState } from './init';
import { PHOTOS, SelectedPhotoPayload } from './types';
export const photosSlice = createSlice({
name: PHOTOS,
initialState: initPhotosState,
reducers: {
init(state) {
return { ...state, ...initPhotosState };
},
selectPhotos(state, action: SelectedPhotoPayload) {
const { photoId, albumId } = action.payload;
const photo = state.data.photos.find((f) => f._id === photoId);
state.presentation.views = {
//TODO: remove any
photo: { _id: photo?._id || '' } as any,
album: state.data.albums.find((f) => f._id === albumId),
};
},
},
extraReducers: (builder) => {
builder.addCase(fetchPhotosData.rejected, (state) => {
state.data.ready = false;
state.error = {
code: ErrorStateCodeEnum.ServerInternalError,
// TODO: need consistency on msg error maybe add enum ?
msg: 'api error',
};
});
builder.addCase(fetchPhotosData.pending, (state) => {
state.data.ready = false;
state.error = undefined;
});
builder.addCase(fetchPhotosData.fulfilled, (state, action) => {
state.data.ready = true;
state.error = undefined;
state.data.photos = action.payload.data;
});
},
});
export default photosSlice.reducer;
// workaround bad photosActions export
export const photosActions = photosSlice.actions;
<file_sep>/src/modules/photos/reducers/instantSearchReducer/index.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { InstantSearchReducer, INSTANT_SEARCH } from './types';
const initialState: InstantSearchReducer = {
autocomplete: [],
result: [],
word: '',
loading: false,
};
//TODO: unit test
export const instantSearchSlice = createSlice({
name: INSTANT_SEARCH,
initialState,
reducers: {
onSearch(state, action: PayloadAction<{ word: string }>) {
const word = action.payload.word;
if (word === '') {
return initialState;
} else {
state.word = word;
}
},
onData(
state,
action: PayloadAction<{
autocomplete: InstantSearchReducer['autocomplete'];
data: InstantSearchReducer['result'];
loading: boolean;
}>,
) {
const { loading, data, autocomplete } = action.payload;
state.loading = loading;
state.autocomplete = autocomplete;
state.result = data;
},
},
});
export default instantSearchSlice.reducer;
export const instantSearchActions = instantSearchSlice.actions;
<file_sep>/src/modules/photos/components/Lightbox/init.ts
import { FileInsight } from './types';
export const initState: FileInsight = {
fileMeta: {
_id: '',
uri: '',
uri_thumbnail: '',
meta: {
size: 0,
extension: '',
contentType: '',
width: 0,
height: 0,
},
},
insights: [],
};
<file_sep>/src/modules/upload/model/types.ts
export const UPLOAD = 'UPLOAD';
type FileUpload = {
_id: string;
progress: number;
originFilename: string;
createAt: string;
type: 'single' | 'multiple';
group: string;
state: 'waiting' | 'queue' | 'failed' | 'finish' | 'cancel';
};
type GroupTask = {
label: string;
progress: number;
total: number;
};
type UploadTask = {
url: string;
pendingQueue: FileUpload[];
fulfillQueue: FileUpload[];
present: {
current: FileUpload[];
group: GroupTask[];
progress: number;
total: number;
};
};
type Album = {
id: string;
name: string;
albumFiles: string[];
};
export type { FileUpload, GroupTask, UploadTask, Album };
<file_sep>/src/modules/upload/components/UploadProgress/types.ts
import { GroupTask } from '../../model/types';
export type UploadProgressPropsType = {
group: GroupTask[];
total: number;
};
<file_sep>/src/common/utils/kFomatter.test.ts
import kFormatter from './kFormatter';
describe('kFormatter test', () => {
it('should return what expected', () => {
const resultTenThousand = kFormatter(100000);
expect(resultTenThousand).toEqual('100.0k');
const resultLessThousand = kFormatter(300);
expect(resultLessThousand).toEqual('300');
});
});
<file_sep>/src/modules/history/services/fetch.history.ts
import { DataSource, IDataSource } from '../mocks/data';
export const fetchHistory = (): IDataSource[] => {
return DataSource;
};
<file_sep>/src/common/components/Layouts/LayoutWithSearch/types.ts
import { ReactNode } from 'react';
export type ImageProps = {
url: string;
key: string;
};
export type AllPhotoLayoutProps = {
children?: ReactNode;
title?: string;
};
<file_sep>/src/modules/photos/reducers/photosReducer/actions.ts
import { createAsyncThunk } from '@reduxjs/toolkit';
import { PhotosAPI } from 'Modules/photos/constants/photo/interface';
import { fetchImages } from 'Modules/photos/services/fetch.images';
import { PHOTOS } from './types';
// TODO: wtf ? not get any id ?
export const fetchPhotosData = createAsyncThunk(PHOTOS, async () => {
return { data: (await fetchImages()).map((el) => ({ ...el, _id: el.id })) } as {
data: Array<PhotosAPI & { _id: string }>;
};
});
<file_sep>/src/modules/dashboard/mocks/data.ts
import { Sync, each } from 'factory.ts';
import faker from 'faker';
import { makeArray } from 'Utils/makeArray';
import { AlbumPreviewProps } from '../components/AlbumPreview/types';
import { ModelEnum } from '../constants/model.enum';
import { DashboardData } from '../models/types';
const DashboardMock = Sync.makeFactory<DashboardData>({
totalPhotos: each(() => faker.random.number()),
totalVideos: each(() => faker.random.number()),
todayPhotos: each(() => faker.random.number()),
todayVideos: each(() => faker.random.number()),
upcomingModel: each(() => faker.random.word()),
model: each(() => faker.random.arrayElement(Object.values(ModelEnum))),
processWithModelPhoto: each(() => faker.random.number()),
finishRunningPhotos: each(() => faker.random.number()),
totalRunningPhotos: each(() => faker.random.number()),
progressPhoto: each(() =>
faker.random.number({
min: 0,
max: 100,
}),
),
});
const AlbumPreviewMock = Sync.makeFactory<AlbumPreviewProps>({
src: each(() => faker.image.image()),
albumName: each(() => faker.random.word()),
albumLength: each(() => faker.random.number()),
label: each(() => makeArray(3, faker.random.word)),
link: each(() => faker.internet.url()),
});
export const DashboardMockData: DashboardData = DashboardMock.build();
export const AlbumPreviewMockData: AlbumPreviewProps[] = AlbumPreviewMock.buildList(4);
<file_sep>/src/modules/upload/reducer/uploadReducer/init.ts
import { UploadTask } from 'Modules/upload/model/types';
export const initUploadState: UploadTask = {
url: '',
pendingQueue: [],
fulfillQueue: [],
present: {
current: [],
group: [],
progress: -1,
total: -1,
},
};
<file_sep>/src/modules/history/reducer/historyReducer/actions.ts
import { createAsyncThunk } from '@reduxjs/toolkit';
import { fetchHistory } from 'Modules/history/services/fetch.history';
import { HISTORY } from './types';
export const fetchHistoryData = createAsyncThunk(HISTORY, async () => {
return { data: fetchHistory().map((el) => ({ ...el, key: el.key })) };
});
<file_sep>/jest.setup.ts
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import React from 'react';
Enzyme.configure({ adapter: new Adapter() });
React.useLayoutEffect = React.useEffect;
// windows mock implemetation
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
// next/router mock implementation
jest.mock('next/router', () => ({
push: jest.fn(),
useRouter: () => ({
pathname: '',
}),
}));
global.fetch = jest.fn().mockResolvedValue({});
<file_sep>/src/modules/upload/reducer/uploadReducer/index.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { FileUpload, GroupTask, UPLOAD } from 'Modules/upload/model/types';
import { initUploadState } from './init';
export const uploadReducer = createSlice({
name: UPLOAD,
initialState: initUploadState,
reducers: {
init(state) {
return { ...state, ...initUploadState };
},
setPendingQueue(state, action: PayloadAction<FileUpload[]>) {
state.pendingQueue = action.payload;
},
setProgress(state, action: PayloadAction<number>) {
state.present.progress = action.payload;
},
setTotal(state, action: PayloadAction<number>) {
state.present.total = action.payload;
},
setGroup(state, action: PayloadAction<GroupTask[]>) {
state.present.group = action.payload;
},
successUploadFile(state, action: PayloadAction<FileUpload>) {
state.fulfillQueue.push({
...action.payload,
state: 'finish',
progress: 1,
});
},
failureUploadFile(state, action: PayloadAction<FileUpload>) {
state.fulfillQueue.push({
...action.payload,
state: 'failed',
});
},
},
});
export default uploadReducer.reducer;
export const uploadActions = uploadReducer.actions;
<file_sep>/src/modules/home/constants/feature/types.ts
export type FeatureType = {
key: string;
icon: string;
label: string;
description: string;
};
<file_sep>/src/modules/history/models/status.enum.ts
export enum StatusEnum {
FINISH = 'finish',
ERROR = 'error',
RESUME = 'resume',
PAUSED = 'paused',
}
<file_sep>/src/modules/photos/models/tags/index.ts
export type Tag = {
result: string;
xMin: number;
xMax: number;
yMin: number;
yMax: number;
};
<file_sep>/src/common/services/client.ts
import {
ApolloClient,
createHttpLink,
from,
InMemoryCache,
NormalizedCacheObject,
ServerError,
} from '@apollo/client';
import { ErrorResponse, onError } from '@apollo/client/link/error';
import HttpStatusCode from '../constants/httpStatusCode';
export const END_POINT =
process.env.APP_GRAPHQL_ENDPOINT || 'https://federation.fluentsearch.ml/graphql';
const httpLink = createHttpLink({
uri: END_POINT,
credentials: 'include',
});
const logoutLink = onError(({ graphQLErrors, networkError }: ErrorResponse) => {
if (graphQLErrors) {
console.log(graphQLErrors[0]);
if (graphQLErrors[0].extensions) {
switch (graphQLErrors[0].extensions?.code) {
case 'GRAPHQL_VALIDATION_FAILED':
//alert('GRAPHQL_VALIDATION_FAILED');
break;
case 'INTERNAL_SERVER_ERROR':
//alert('Invalid email or password');
break;
case 'UNAUTHENICATED':
//TODO: need to implement refresh token
//alert('UNAUTHENICATED');
//window.location.replace('/login');
break;
default:
console.log(
`[GraphQL error]: Message: ${graphQLErrors[0].message}, Location: ${graphQLErrors[0].locations}, Path: ${graphQLErrors[0].path}`,
);
break;
}
}
}
if (networkError) {
if ((networkError as ServerError)?.statusCode === HttpStatusCode.UNAUTHORIZED)
window.location.replace('/logout');
else if (
(networkError as ServerError)?.statusCode === HttpStatusCode.NOT_IMPLEMENTED
) {
alert(networkError?.message);
window.location.replace('/');
}
}
});
export const client = new ApolloClient({
link: from([logoutLink, httpLink]),
cache: new InMemoryCache(),
});
export const getApolloClient = (ctx?: any, initialState?: NormalizedCacheObject) => {
return client;
};
<file_sep>/src/modules/dashboard/components/DashboardCard/NumberCard/types.ts
export type NumberCardProps = {
cardName: string;
largeNumber: number;
todayNumber: number;
};
<file_sep>/src/modules/photos/models/photo/index.ts
import { Album } from '../album';
import { Tag } from '../tags';
export type Photo = {
_id: string;
label: string;
tags?: Tag[];
albumId?: Album['_id'];
createAt: Date;
updateAt: Date;
meta: MetaPhoto;
description?: string;
src: {
original: string;
thumbnail: string;
};
};
export type MetaPhoto = {
filename: string;
extension: string;
width: number;
height: number;
filesize: number; // bytes
dpi: number | 72; // deph per inchs
placeString?: string;
};
<file_sep>/src/common/models/oauth/type.ts
import { OAuthEnum } from './enum';
export type OAuthType = OAuthEnum.Facebook;
<file_sep>/src/common/services/model/generated-types.ts
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/** A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date-time format. */
DateTime: any;
};
export type AppModel = {
__typename?: 'AppModel';
status: Scalars['Int'];
};
export type BBoxResponseApi = {
__typename?: 'BBoxResponseApi';
xmax: Scalars['Float'];
xmin: Scalars['Float'];
ymax: Scalars['Float'];
ymin: Scalars['Float'];
};
export enum FileExtensionEnum {
Jpg = 'JPG',
Png = 'PNG'
}
export type ImageFileWithInsight = {
__typename?: 'ImageFileWithInsight';
_id: Scalars['String'];
createAt: Scalars['DateTime'];
insight?: Maybe<Array<Insight>>;
label: Scalars['String'];
meta: ImageMeta;
owner: Scalars['String'];
type: Scalars['String'];
updateAt: Scalars['DateTime'];
uri: Scalars['String'];
zone: ZoneEnum;
};
export type ImageMeta = {
__typename?: 'ImageMeta';
contentType: Scalars['String'];
dpi: Scalars['Int'];
extension: FileExtensionEnum;
filename: Scalars['String'];
height: Scalars['Int'];
sha1?: Maybe<Scalars['String']>;
size: Scalars['Int'];
width: Scalars['Int'];
};
export type Insight = {
__typename?: 'Insight';
_id: Scalars['String'];
bbox: BBoxResponseApi;
createAt: Scalars['DateTime'];
fileId: Scalars['String'];
label: Scalars['String'];
lang: LanguageEnum;
model: ModelEnum;
prob: Scalars['Float'];
result: Scalars['String'];
updateAt: Scalars['DateTime'];
};
export enum LanguageEnum {
Enus = 'enus',
Th = 'th'
}
export enum ModelEnum {
Detection_600 = 'detection_600',
FacesEmo = 'faces_emo'
}
export type Query = {
__typename?: 'Query';
getFilesWithInsight: Array<ImageFileWithInsight>;
searchByWord: SearchReponseDto;
serverStatus: AppModel;
};
export type QueryGetFilesWithInsightArgs = {
limit?: Maybe<Scalars['Int']>;
skip?: Maybe<Scalars['Int']>;
userId: Scalars['String'];
};
export type QuerySearchByWordArgs = {
userId: Scalars['String'];
word: Scalars['String'];
};
export type SearchReponseDto = {
__typename?: 'SearchReponseDto';
autocomplete: Array<Scalars['String']>;
result: Array<ImageFileWithInsight>;
};
export enum ZoneEnum {
Th = 'TH'
}
export type GetInsightQueryVariables = Exact<{ [key: string]: never; }>;
export type GetInsightQuery = (
{ __typename?: 'Query' }
& { getFilesWithInsight: Array<(
{ __typename?: 'ImageFileWithInsight' }
& Pick<ImageFileWithInsight, '_id' | 'label' | 'createAt' | 'updateAt' | 'uri' | 'zone'>
& { meta: (
{ __typename?: 'ImageMeta' }
& Pick<ImageMeta, 'width' | 'height'>
), insight?: Maybe<Array<(
{ __typename?: 'Insight' }
& Pick<Insight, 'result'>
& { bbox: (
{ __typename?: 'BBoxResponseApi' }
& Pick<BBoxResponseApi, 'xmax' | 'xmin' | 'ymin' | 'ymax'>
) }
)>> }
)> }
);
export type GetInsightBySearchQueryVariables = Exact<{
word: Scalars['String'];
}>;
export type GetInsightBySearchQuery = (
{ __typename?: 'Query' }
& { searchByWord: (
{ __typename?: 'SearchReponseDto' }
& Pick<SearchReponseDto, 'autocomplete'>
& { result: Array<(
{ __typename?: 'ImageFileWithInsight' }
& Pick<ImageFileWithInsight, '_id'>
)> }
) }
);
export const GetInsightDocument = gql`
query getInsight {
getFilesWithInsight(userId: "1234", skip: 0, limit: 1000) {
_id
label
meta {
width
height
}
createAt
updateAt
uri
zone
insight {
result
bbox {
xmax
xmin
ymin
ymax
}
}
}
}
`;
/**
* __useGetInsightQuery__
*
* To run a query within a React component, call `useGetInsightQuery` and pass it any options that fit your needs.
* When your component renders, `useGetInsightQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetInsightQuery({
* variables: {
* },
* });
*/
export function useGetInsightQuery(baseOptions?: Apollo.QueryHookOptions<GetInsightQuery, GetInsightQueryVariables>) {
return Apollo.useQuery<GetInsightQuery, GetInsightQueryVariables>(GetInsightDocument, baseOptions);
}
export function useGetInsightLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetInsightQuery, GetInsightQueryVariables>) {
return Apollo.useLazyQuery<GetInsightQuery, GetInsightQueryVariables>(GetInsightDocument, baseOptions);
}
export type GetInsightQueryHookResult = ReturnType<typeof useGetInsightQuery>;
export type GetInsightLazyQueryHookResult = ReturnType<typeof useGetInsightLazyQuery>;
export type GetInsightQueryResult = Apollo.QueryResult<GetInsightQuery, GetInsightQueryVariables>;
export const GetInsightBySearchDocument = gql`
query getInsightBySearch($word: String!) {
searchByWord(userId: "1234", word: $word) {
autocomplete
result {
_id
}
}
}
`;
/**
* __useGetInsightBySearchQuery__
*
* To run a query within a React component, call `useGetInsightBySearchQuery` and pass it any options that fit your needs.
* When your component renders, `useGetInsightBySearchQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useGetInsightBySearchQuery({
* variables: {
* word: // value for 'word'
* },
* });
*/
export function useGetInsightBySearchQuery(baseOptions: Apollo.QueryHookOptions<GetInsightBySearchQuery, GetInsightBySearchQueryVariables>) {
return Apollo.useQuery<GetInsightBySearchQuery, GetInsightBySearchQueryVariables>(GetInsightBySearchDocument, baseOptions);
}
export function useGetInsightBySearchLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<GetInsightBySearchQuery, GetInsightBySearchQueryVariables>) {
return Apollo.useLazyQuery<GetInsightBySearchQuery, GetInsightBySearchQueryVariables>(GetInsightBySearchDocument, baseOptions);
}
export type GetInsightBySearchQueryHookResult = ReturnType<typeof useGetInsightBySearchQuery>;
export type GetInsightBySearchLazyQueryHookResult = ReturnType<typeof useGetInsightBySearchLazyQuery>;
export type GetInsightBySearchQueryResult = Apollo.QueryResult<GetInsightBySearchQuery, GetInsightBySearchQueryVariables>;<file_sep>/src/modules/user/services/default.msg.ts
export const MSG_BAD_PASSWORD = '<PASSWORD>';
export const MSG_INTERNAL_ERROR = 'เกิดข้อผิดพลาด';
export const MSG_BAD_USERNAME = 'โปรดกรอกชื่อผู้ใช้งานให้ถูกต้อง';
export const MSG_REQUIRE_USERNAME = 'โปรดกรอกชื่อผู้ใช้งาน';
export const MSG_REQUIRE_PASSWORD = '<PASSWORD>';
<file_sep>/src/modules/user/reducers/userReducer/types.ts
import {
UserPackageEnumSession,
UserRoleEnumSession,
UserZoneEnumSession,
} from '../../../../common/generated/generated-types';
export const USER = 'USER';
export type User = {
id: string;
name: string;
mainEmail: string;
role: UserRoleEnumSession;
zone: UserZoneEnumSession;
package: UserPackageEnumSession;
};
export type UserState = {
user: User;
authenticated: boolean;
msg?: string;
};
<file_sep>/tsconfig.json
{
"compilerOptions": {
"target": "ES2015",
"lib": ["dom", "dom.iterable", "esnext", "ES2016", "ES2018", "ES2019"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": ".",
"strictNullChecks": true,
"paths": {
"Assets/*": ["src/common/assets/*"],
"Components/*": ["src/common/components/*"],
"Hooks/*": ["src/common/hooks/*"],
"Models/*": ["src/common/models/*"],
"Pages/*": ["src/common/pages/*"],
"Services/*": ["src/common/services/*"],
"Stores/*": ["src/common/stores/*"],
"Utils/*": ["src/common/utils/*"],
"Styles/*": ["src/common/styles/*"],
"Tests/*": ["src/common/tests/*"],
"Modules/*": ["src/modules/*"]
}
},
"include": ["next-env.d.ts", "**/**.ts", "**/**.tsx"],
"exclude": ["node_modules", "public", "codegen"]
}
<file_sep>/src/modules/dashboard/models/types.ts
import { ModelEnum } from 'Modules/dashboard/constants/model.enum';
import { ErrorState } from 'Stores/common/types/error';
import { InsightModelEnum } from '../../../common/generated/generated-types';
import { AlbumPreviewProps } from '../components/AlbumPreview/types';
export const DASHBOARD = 'DASHBOARD';
export type DashboardState = {
data: {
dashboardData: DashboardData;
albumPreviewData: AlbumPreviewProps[];
};
presentation: {
totalPhotos: number;
totalVideos: number;
todayPhotos: number;
todayVideos: number;
upcomingModel: string;
model: ModelEnum;
processWithModelPhoto: number;
finishRunningPhotos: number;
totalRunningPhotos: number;
progressPhoto: number;
};
ready: boolean;
error?: ErrorState;
};
export type DashboardData = {
totalPhotos: number;
totalVideos: number;
todayPhotos: number;
todayVideos: number;
upcomingModel: string;
model: ModelEnum;
processWithModelPhoto: number;
finishRunningPhotos: number;
totalRunningPhotos: number;
progressPhoto: number;
};
export type Insight = {
keyword: string;
model: InsightModelEnum;
};
export type DashboardCardType = {
data: Dashboard;
};
export type OverviewAlbumType = {
data: FileInsight[];
};
export type FileInsightMeta = {
_id: string;
type: string;
uri: string;
uri_thumbnail: string;
original_filename: string;
};
export type FileInsight = {
fileMeta: FileInsightMeta;
insights: Insight[];
};
export type DataDashboard = {
total: number;
today: number;
};
export type FileDashboard = {
photo: DataDashboard;
video: DataDashboard;
};
export type Dashboard = {
FileDashboardData: FileDashboard;
FileInsightDashboardData: FileInsight[];
};
<file_sep>/src/modules/dashboard/reducer/dashboardReducer/init.ts
import { ModelEnum } from 'Modules/dashboard/constants/model.enum';
import { DashboardState } from 'Modules/dashboard/models/types';
export const initDashboardState: DashboardState = {
data: {
dashboardData: {
totalPhotos: 0,
totalVideos: 0,
todayPhotos: 0,
todayVideos: 0,
upcomingModel: '-',
model: ModelEnum.NONE,
processWithModelPhoto: 0,
finishRunningPhotos: 0,
totalRunningPhotos: 0,
progressPhoto: 0,
},
albumPreviewData: [],
},
presentation: {
totalPhotos: 0,
totalVideos: 0,
todayPhotos: 0,
todayVideos: 0,
upcomingModel: '-',
model: ModelEnum.NONE,
processWithModelPhoto: 0,
finishRunningPhotos: 0,
totalRunningPhotos: 0,
progressPhoto: 0,
},
ready: false,
};
<file_sep>/src/common/models/oauth/enum.ts
export enum OAuthEnum {
Facebook = 'facebook',
}
<file_sep>/src/modules/upload/components/UploadProgress/UploadItem/types.ts
import { GroupTask } from 'Modules/upload/model/types';
type UploadItemProps = {
file: {
file: GroupTask;
};
};
type ProgressBarPropsType = {
width: number;
};
export type { UploadItemProps, ProgressBarPropsType };
<file_sep>/src/modules/dashboard/reducer/dashboardReducer/actions.ts
import { createAsyncThunk } from '@reduxjs/toolkit';
import { fetchDashboard } from 'Modules/dashboard/services/fetch.dashboardData';
import { DASHBOARD } from '../../models/types';
export const fetchDashboardData = createAsyncThunk(DASHBOARD, async () => {
return { data: fetchDashboard() };
});
<file_sep>/src/modules/task/reducer/taskReducer/init.ts
import { TaskState } from './types';
export const initTaskState: TaskState = {
data: {
tasks: [],
quota: 0,
},
present: {
tasks: [],
},
ready: false,
};
<file_sep>/src/common/stores/index.spec.ts
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { middleware } from '.';
const mockStore = configureStore(middleware);
describe('stores test', () => {
const initialState = {};
const store = mockStore(initialState);
it('it should correctly define initial state', () => {
const expectedInitial = {};
expect(store.getState()).toEqual(expectedInitial);
});
it('it should defined correctly middleware', () => {
const expectedMiddleware = [thunk];
expect(middleware).toEqual(expectedMiddleware);
});
});
<file_sep>/src/modules/dashboard/reducer/dashboardReducer/index.ts
import { createSlice } from '@reduxjs/toolkit';
import { initDashboardState } from './init';
import { DASHBOARD } from '../../models/types';
import { fetchDashboardData } from './actions';
import { ErrorStateCodeEnum } from 'Stores/common/types/error';
export const dashboardSlice = createSlice({
name: DASHBOARD,
initialState: initDashboardState,
reducers: {
init(state) {
return { ...state, ...initDashboardState };
},
},
extraReducers: (builder) => {
builder.addCase(fetchDashboardData.rejected, (state) => {
state.ready = false;
state.error = {
code: ErrorStateCodeEnum.ServerInternalError,
msg: 'api error',
};
});
builder.addCase(fetchDashboardData.pending, (state) => {
state.ready = false;
state.error = undefined;
});
builder.addCase(fetchDashboardData.fulfilled, (state, action) => {
state.ready = true;
state.error = undefined;
state.data.albumPreviewData = action.payload.data.AlbumPreviewMockData;
state.data.dashboardData = action.payload.data.DashboardMockData;
});
},
});
export default dashboardSlice.reducer;
export const dashboardActions = dashboardSlice.actions;
| af14433e802dcad17af962ceb24e1c2fe9063060 | [
"TypeScript",
"JSON with Comments",
"Dockerfile"
] | 96 | TypeScript | yee2542/FluentSearch-FE | fefa9588a2d42f65fb2ac393ecb69d5c67bfcd47 | 4f694c78ee05dc94b503573ea34ae0164a011927 |
refs/heads/master | <repo_name>Bhuvanesh1893/Coding_Test_PromotionEngine<file_sep>/Coding_Test_PromotionEngine.Tests/Controllers/Provided_UnitTestCase.cs
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Coding_Test_PromotionEngine;
using Coding_Test_PromotionEngine.Controllers;
using PromotionEngine_Common.Models;
using Coding_Test_PromotionEngine.Models;
namespace Coding_Test_PromotionEngine.Tests.Controllers
{
[TestFixture]
public class Provided_UnitTestCase
{
private OrderRequest FactoryGetOrderRequest()
{
OrderRequest ordReq = new OrderRequest();
return ordReq;
}
private OrderResponse FactoryGetOrderResponse()
{
OrderResponse ordRes = new OrderResponse();
return ordRes;
}
private OrderController FactoryGetOrderController()
{
OrderController ordCont = new OrderController();
return ordCont;
}
//Testcases provided
[Test]
public void Required_TestCases_1()
{
OrderController controller = FactoryGetOrderController();
OrderRequest ordReq = FactoryGetOrderRequest();
ordReq.LineItems = new List<LineItem>()
{
new LineItem {skuId = "A", quantity = 1},
new LineItem {skuId = "B", quantity = 1},
new LineItem {skuId = "C", quantity = 1}
};
OrderResponse expOrdResp = FactoryGetOrderResponse();
expOrdResp.LineItemPrice = new List<LineItemPrice>()
{
new LineItemPrice { skuId = "A", quantity=1, promoDesc="", skuTotal=50},
new LineItemPrice { skuId = "B", quantity=1, promoDesc="", skuTotal=30},
new LineItemPrice { skuId = "C", quantity=1, promoDesc="", skuTotal=20}
};
expOrdResp.CartTotal = 100;
expOrdResp.RespMessage.StatusCode = 200;
expOrdResp.RespMessage.StatusMessage = "Success";
OrderResponse actOrdResp = controller.Post(ordReq);
//Assert
Assert.That(expOrdResp.LineItemPrice, Is.EqualTo(actOrdResp.LineItemPrice));
Assert.That(expOrdResp.CartTotal, Is.EqualTo(actOrdResp.CartTotal));
Assert.That(expOrdResp.RespMessage, Is.EqualTo(actOrdResp.RespMessage));
}
[Test]
public void Required_TestCases_2()
{
OrderController controller = FactoryGetOrderController();
OrderRequest ordReq = FactoryGetOrderRequest();
ordReq.LineItems = new List<LineItem>()
{
new LineItem {skuId = "A", quantity = 5},
new LineItem {skuId = "B", quantity = 5},
new LineItem {skuId = "C", quantity = 1}
};
OrderResponse expOrdResp = FactoryGetOrderResponse();
expOrdResp.LineItemPrice = new List<LineItemPrice>()
{
new LineItemPrice { skuId = "A", quantity=5, promoDesc="Buy3For130", skuTotal=230},
new LineItemPrice { skuId = "B", quantity=5, promoDesc="Buy2For45", skuTotal=120},
new LineItemPrice { skuId = "C", quantity=1, promoDesc="", skuTotal=20}
};
expOrdResp.CartTotal = 370;
expOrdResp.RespMessage.StatusCode = 200;
expOrdResp.RespMessage.StatusMessage = "Success";
OrderResponse actOrdResp = controller.Post(ordReq);
//Assert
Assert.That(expOrdResp.LineItemPrice, Is.EqualTo(actOrdResp.LineItemPrice));
Assert.That(expOrdResp.CartTotal, Is.EqualTo(actOrdResp.CartTotal));
Assert.That(expOrdResp.RespMessage, Is.EqualTo(actOrdResp.RespMessage));
}
public void Required_TestCases_3()
{
OrderController controller = FactoryGetOrderController();
OrderRequest ordReq = FactoryGetOrderRequest();
ordReq.LineItems = new List<LineItem>()
{
new LineItem {skuId = "A", quantity = 3},
new LineItem {skuId = "B", quantity = 5},
new LineItem {skuId = "C", quantity = 1},
new LineItem {skuId = "D", quantity = 1},
};
OrderResponse expOrdResp = FactoryGetOrderResponse();
expOrdResp.LineItemPrice = new List<LineItemPrice>()
{
new LineItemPrice { skuId = "A", quantity=3, promoDesc="Buy3For130", skuTotal=130},
new LineItemPrice { skuId = "B", quantity=5, promoDesc="Buy2For45", skuTotal=120},
new LineItemPrice { skuId = "C", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=0},
new LineItemPrice { skuId = "D", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=30}
};
expOrdResp.CartTotal = 280;
expOrdResp.RespMessage.StatusCode = 200;
expOrdResp.RespMessage.StatusMessage = "Success";
OrderResponse actOrdResp = controller.Post(ordReq);
//Assert
Assert.That(expOrdResp.LineItemPrice, Is.EqualTo(actOrdResp.LineItemPrice));
Assert.That(expOrdResp.CartTotal, Is.EqualTo(actOrdResp.CartTotal));
Assert.That(expOrdResp.RespMessage, Is.EqualTo(actOrdResp.RespMessage));
}
}
}
<file_sep>/Coding_Test_PromotionEngine/Controllers/OrderController.cs
using Coding_Test_PromotionEngine.Appplication;
using Coding_Test_PromotionEngine.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Coding_Test_PromotionEngine.Controllers
{
public class OrderController : ApiController
{
// POST api/values
public OrderResponse Post([FromBody] OrderRequest ordReq)
{
OrderResponse ordRes = FactoryGetOrderResponse();
try
{
if (ordReq == null || ordReq.LineItems == null || ordReq.LineItems.Count() == 0)
{
ordRes.RespMessage.StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest);
ordRes.RespMessage.StatusMessage = "Invalid Request";
return ordRes;
}
else
{
SkuCheck skuCheck = FactoryGetSkuCheck();
if (skuCheck.Check_Skus(ordReq))
{
ICartCal cartCal = FactoryGetCartCal();
ordRes = cartCal.ProcessLineItems(ordReq);
if(ordRes.RespMessage.StatusCode == 0 && String.IsNullOrEmpty(ordRes.RespMessage.StatusMessage))
{
ordRes.RespMessage.StatusCode = Convert.ToInt32(HttpStatusCode.OK);
ordRes.RespMessage.StatusMessage = "Success";
}
return ordRes;
}
else
{
ordRes.RespMessage.StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest);
ordRes.RespMessage.StatusMessage = "Invalid Items";
return ordRes;
}
}
}
catch(Exception ex)
{
ordRes.RespMessage.StatusCode = Convert.ToInt32(HttpStatusCode.BadRequest);
ordRes.RespMessage.StatusMessage = ex.Message;
return ordRes;
}
}
private OrderResponse FactoryGetOrderResponse()
{
OrderResponse ordRes = new OrderResponse();
return ordRes;
}
private CartCal FactoryGetCartCal()
{
CartCal cartCal = new CartCal();
return cartCal;
}
private SkuCheck FactoryGetSkuCheck()
{
SkuCheck skuCheck = new SkuCheck();
return skuCheck;
}
}
}
<file_sep>/Coding_Test_PromotionEngine/Appplication/ICartCal.cs
using Coding_Test_PromotionEngine.Models;
namespace Coding_Test_PromotionEngine.Appplication
{
public interface ICartCal
{
OrderResponse ProcessLineItems(OrderRequest ordReq);
}
}<file_sep>/Promotions/Adaptor/IPromoPriceCal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PromotionEngine_Common.Models;
namespace Promotions.Adaptor
{
public interface IPromoPriceCal
{
void Run_Promos_Cal_Total(List<LineItemPrice> lineItemPrices, out List<LineItemPrice> upLineItemPrices, out float CartTotal);
}
}
<file_sep>/Promotions/Promotion2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Promotions.Models;
using PromotionEngine_Common.Models;
using SkuPriceInfo;
namespace Promotions
{
public class Promotion2 : IPromotion2
{
private List<BuyTwoSkuForX> _confBuyTwoForX;
private Dictionary<string, float> _skuPriceInfo;
//Configurable parameters for the promotion - Can configure for any two skus for any fixed price
private void ReadXmlBuyTwoSkuforY()
{
try
{
_confBuyTwoForX = new List<BuyTwoSkuForX>();
_confBuyTwoForX.Add(new BuyTwoSkuForX { sku1 = "C", sku2 = "D", price = 30 });
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
//Promotion Logic - Buy 2 different skus for a fixed price
public List<LineItemPrice> BuyTwoSKUForFixed(List<LineItemPrice> listItems)
{
try
{
ReadXmlBuyTwoSkuforY();
int skuQuan1;
int skuQuan2;
ISkuPriceInfo skuPrices = new SkuPriceInfoAdaptor();
_skuPriceInfo = skuPrices.GetSkuPriceInfo();
foreach (var promo in _confBuyTwoForX)
{
var matchingItemsSkuId1 = listItems.Where(y => y.skuId == promo.sku1 && y.promoDesc == string.Empty).ToList();
var matchingItemsSkuId2 = listItems.Where(y => y.skuId == promo.sku2 && y.promoDesc == string.Empty).ToList();
if (matchingItemsSkuId1.Count > 0 && matchingItemsSkuId2.Count > 0)
{
skuQuan1 = matchingItemsSkuId1[0].quantity;
skuQuan2 = matchingItemsSkuId2[0].quantity;
if (skuQuan1 == skuQuan2)
{
foreach(var item in matchingItemsSkuId1)
{
item.promoDesc = "Buy2SKUfor" + promo.price;
item.skuTotal = 0;
}
foreach (var item in matchingItemsSkuId2)
{
item.promoDesc = "Buy2SKUfor" + promo.price;
item.skuTotal = item.quantity * promo.price;
}
}
else if (skuQuan1 > skuQuan2)
{
foreach (var item in matchingItemsSkuId1)
{
item.promoDesc = "Buy2SKUfor" + promo.price;
item.skuTotal = (skuQuan1 - skuQuan2) * _skuPriceInfo[item.skuId];
}
foreach (var item in matchingItemsSkuId2)
{
item.promoDesc = "Buy2SKUfor" + promo.price;
item.skuTotal = item.quantity * promo.price;
}
}
else
{
foreach (var item in matchingItemsSkuId1)
{
item.promoDesc = "Buy2SKUfor" + promo.price;
item.skuTotal = 0;
}
foreach (var item in matchingItemsSkuId2)
{
item.promoDesc = "Buy2SKUfor" + promo.price;
item.skuTotal = (skuQuan1*promo.price) + (skuQuan2-skuQuan1) * _skuPriceInfo[item.skuId];
}
}
}
}
return listItems;
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/Promotions/NonPromoCal.cs
using PromotionEngine_Common.Models;
using SkuPriceInfo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Promotions
{
public class NonPromoCal
{
private Dictionary<string, float> _skuPriceInfo = new Dictionary<string, float>();
public virtual List<LineItemPrice> CalNonPromoSkuTotal(List<LineItemPrice> lineItemPrices)
{
try
{
ISkuPriceInfo skuPr = new SkuPriceInfoAdaptor();
_skuPriceInfo = skuPr.GetSkuPriceInfo();
foreach(var li in lineItemPrices.Where(x=>x.promoDesc==""))
{
li.skuTotal = li.quantity * _skuPriceInfo[li.skuId];
}
return lineItemPrices;
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
public virtual float CalCartTotal(List<LineItemPrice> lineItemPrices)
{
try {
float cartTotal = 0F;
foreach(var item in lineItemPrices)
{
cartTotal += item.skuTotal;
}
return cartTotal;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/README.md
# Coding_Test_PromotionEngine
Coding Test Promotion Engine
Tools used - Visual Studio 2019
Frameworks used - .Net Framework 4.6.2, NUnit 3.12, NUnit3TestAdaptor
Coding Patterns used - Adaptor pattern, Interface Inversion principle
Overview -
1. API created which accepts the Line Items information and returns back with the cart total.
2. Two promotions added in different class files.
3. Configured 3 active promotions.
4. Created a separate class library with adaptors for the fetcing the SKU Price info (hardcoded for now, no use of Db).
URL - {localhost}/api/Order
Sample Test Input :
{
"LineItems": [
{
"skuId": "A",
"quantity": 5
},
{
"skuId": "A",
"quantity": 5
},
{
"skuId": "B",
"quantity": 5
},
{
"skuId": "C",
"quantity": 1
},
{
"skuId": "D",
"quantity": 1
}
]
}
Sample Test Output :
{
"LineItemPrice": [
{
"skuId": "A",
"quantity": 5,
"promoDesc": "Buy3For130",
"skuTotal": 230.0
},
{
"skuId": "A",
"quantity": 5,
"promoDesc": "Buy3For130",
"skuTotal": 230.0
},
{
"skuId": "B",
"quantity": 5,
"promoDesc": "Buy2For45",
"skuTotal": 120.0
},
{
"skuId": "C",
"quantity": 1,
"promoDesc": "Buy2SKUfor30",
"skuTotal": 0.0
},
{
"skuId": "D",
"quantity": 1,
"promoDesc": "Buy2SKUfor30",
"skuTotal": 30.0
}
],
"CartTotal": 610.0,
"RespMessage": {
"StatusCode": 200,
"StatusMessage": "Success"
}
}
<file_sep>/Promotions/Adaptor/PromoPriceCalAdaptor.cs
using PromotionEngine_Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Promotions.Adaptor
{
public class PromoPriceCalAdaptor : NonPromoCal, IPromoPriceCal
{
/* Inherits NonPromoCal(base class) and Interface IPromoPriceCal
* Implements IPromoPriceCal interface to calculate carttotal after promotions are applied
* Acts as a wrapper class for base class methods inside the interface implementation
* Acts as an adaptor for the Promotions
*/
public void Run_Promos_Cal_Total(List<LineItemPrice> lineItemPrices, out List<LineItemPrice> upLineItemPrices, out float CartTotal)
{
try
{
upLineItemPrices = ApplyPromotions(lineItemPrices);
upLineItemPrices = CalNonPromoSkuTotal(upLineItemPrices);
CartTotal = CalCartTotal(upLineItemPrices);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private List<LineItemPrice> ApplyPromotions(List<LineItemPrice> liItemPrices)
{
try
{
List<LineItemPrice> promoItemPrices = new List<LineItemPrice>();
IPromotion1 iP1 = new Promotion1();
promoItemPrices = iP1.BuyNSKUUnitsForFixed(liItemPrices);
IPromotion2 iP2 = new Promotion2();
promoItemPrices = iP2.BuyTwoSKUForFixed(promoItemPrices);
return promoItemPrices;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public override List<LineItemPrice> CalNonPromoSkuTotal(List<LineItemPrice> lineItemPrices)
{
try
{
return base.CalNonPromoSkuTotal(lineItemPrices);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public override float CalCartTotal(List<LineItemPrice> lineItemPrices)
{
try
{
return base.CalCartTotal(lineItemPrices);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/Coding_Test_PromotionEngine.Tests/SkuPriceInfo_Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit;
using NUnit.Framework;
using SkuPriceInfo;
namespace Coding_Test_PromotionEngine.Tests
{
[TestFixture]
public class SkuPriceInfo_Test
{
[Test]
public void GetSkuPrices()
{
//Arrange
Dictionary<string, float> expResult = new Dictionary<string, float>
{
{ "A", 50 }, { "B", 30 }, { "C", 20 }, { "D", 15 }
};
Dictionary<string, float> actResult = new Dictionary<string, float>();
ISkuPriceInfo skuPr = new SkuPriceInfoAdaptor();
//Act
actResult = skuPr.GetSkuPriceInfo();
//Assert
CollectionAssert.AreEquivalent(expResult, actResult);
}
}
}
<file_sep>/SkuPriceInfo/ISkuPriceInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SkuPriceInfo
{
public interface ISkuPriceInfo
{
//Functions exposed to the consumer
Dictionary<string, float> GetSkuPriceInfo();
}
}
<file_sep>/Promotions/IPromotion1.cs
using PromotionEngine_Common.Models;
using System.Collections.Generic;
namespace Promotions
{
public interface IPromotion1
{
List<LineItemPrice> BuyNSKUUnitsForFixed(List<LineItemPrice> LineItems);
}
}<file_sep>/Coding_Test_PromotionEngine.Tests/Promotion2_Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit;
using Promotions;
using PromotionEngine_Common.Models;
using NUnit.Framework;
using System.Web.Http.Routing.Constraints;
namespace Coding_Test_PromotionEngine.Tests
{
[TestFixture]
public class Promotion2_Test
{
[TestCase(2, 2, 0, 60)]
[TestCase(3,2,20,60)]
[TestCase(2, 3, 0, 75)]
public void Promotion2_Test1(int a , int b, float c, float d)
{
List<LineItemPrice> input = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=5, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=4, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=a, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=b, promoDesc="", skuTotal=0},
};
List<LineItemPrice> expResult = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=5, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=4, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=a, promoDesc="Buy2SKUfor30", skuTotal=c},
new LineItemPrice{skuId="D", quantity=b, promoDesc="Buy2SKUfor30", skuTotal=d},
};
List<LineItemPrice> actResult = new List<LineItemPrice>();
IPromotion2 iPr = new Promotion2();
actResult = iPr.BuyTwoSKUForFixed(input);
Assert.That(expResult, Is.EqualTo(actResult));
}
//TestCase with SkuId E not in list-Promotion does not apply
[Test]
public void Promotion2_Test2()
{
List<LineItemPrice> input = new List<LineItemPrice>()
{
new LineItemPrice{skuId="E", quantity=5, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=4, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=1, promoDesc="", skuTotal=0},
};
List<LineItemPrice> expResult = new List<LineItemPrice>()
{
new LineItemPrice{skuId="E", quantity=5, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=4, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=0},
new LineItemPrice{skuId="D", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=30},
};
List<LineItemPrice> actResult = new List<LineItemPrice>();
IPromotion2 iPr = new Promotion2();
actResult = iPr.BuyTwoSKUForFixed(input);
Assert.That(expResult, Is.EqualTo(actResult));
}
}
}
<file_sep>/Promotions/Promotion1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PromotionEngine_Common.Models;
using SkuPriceInfo;
using System.Xml;
using Promotions.Models;
namespace Promotions
{
public class Promotion1 : IPromotion1
{
private List<BuyXforY> _confBuyXforY;
private Dictionary<string, float> _skuPriceInfo;
//Promotion Logic - Buy "N" items of a SKU for a fixed price
public List<LineItemPrice> BuyNSKUUnitsForFixed(List<LineItemPrice> LineItems)
{
try
{
ReadXmlBuyXforY();
ISkuPriceInfo skuPrices = new SkuPriceInfoAdaptor();
_skuPriceInfo = skuPrices.GetSkuPriceInfo();
foreach (var i in _confBuyXforY)
{
foreach (var li in LineItems.Where(x => x.promoDesc == string.Empty && x.skuId == i.sku && x.quantity >= i.quantity))
{
li.promoDesc = "Buy" + i.quantity.ToString() + "For" + i.price.ToString();
li.skuTotal = ((li.quantity / i.quantity) * i.price) + ((li.quantity % i.quantity) * _skuPriceInfo[li.skuId]);
}
}
return LineItems;
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
//Configurable parameters for the promotions - Can configure for any skus and any quantity
private void ReadXmlBuyXforY()
{
try
{
_confBuyXforY = new List<BuyXforY>();
_confBuyXforY.Add(new BuyXforY { sku = "A", quantity = 3, price = 130 });
_confBuyXforY.Add(new BuyXforY { sku = "B", quantity = 2, price = 45 });
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/SkuPriceInfo/SkuPriceInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SkuPriceInfo
{
public class SkuPriceInfo
{
private Dictionary<string, float> skuPriceInfo = new Dictionary<string, float>();
//Base class method to get the SKU Price info - DB related code can be written
public virtual Dictionary<string, float> GetSkuPriceInfoDetails()
{
try
{
skuPriceInfo.Add("A", 50);
skuPriceInfo.Add("B", 30);
skuPriceInfo.Add("C", 20);
skuPriceInfo.Add("D", 15);
return skuPriceInfo;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/Coding_Test_PromotionEngine/Models/OrderResponse.cs
using PromotionEngine_Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Coding_Test_PromotionEngine.Models
{
public class OrderResponse
{
public List<LineItemPrice> LineItemPrice { get; set; }
public float CartTotal { get; set; }
public ResponseMessage RespMessage { get; set; }
public OrderResponse()
{
this.LineItemPrice = new List<LineItemPrice>();
this.CartTotal = 0F;
this.RespMessage = new ResponseMessage();
}
public bool Equals(OrderResponse ordRes)
{
if (CartTotal == ordRes.CartTotal && RespMessage.StatusCode == ordRes.RespMessage.StatusCode
&& RespMessage.StatusMessage == ordRes.RespMessage.StatusMessage)
{
return true;
}
else
{
return false;
}
}
}
}<file_sep>/Coding_Test_PromotionEngine/Models/ResponseMessage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Coding_Test_PromotionEngine.Models
{
public class ResponseMessage : IEquatable<ResponseMessage>
{
public int StatusCode { get; set; }
public string StatusMessage { get; set; }
public bool Equals(ResponseMessage resMsg)
{
if (StatusCode == resMsg.StatusCode && StatusMessage == resMsg.StatusMessage)
{
return true;
}
else
{
return false;
}
}
}
}<file_sep>/Coding_Test_PromotionEngine.Tests/Controllers/OrderControllerTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using NUnit;
using Coding_Test_PromotionEngine;
using Coding_Test_PromotionEngine.Controllers;
using NUnit.Framework;
using PromotionEngine_Common.Models;
using Coding_Test_PromotionEngine.Models;
namespace Coding_Test_PromotionEngine.Tests.Controllers
{
[TestFixture]
public class OrderControllerTest
{
//Test to run return type
[Test]
public void Post_Test1()
{
//Arrange
OrderController controller = new OrderController();
OrderRequest ordReq = new OrderRequest();
OrderResponse expOrdResp = new OrderResponse();
//Assert
Assert.IsInstanceOf(typeof(OrderResponse), controller.Post(ordReq));
}
//Test to run with invalid input or no line items
[Test]
public void Post_Test2()
{
//Arrange
OrderController controller = new OrderController();
OrderRequest ordReq = new OrderRequest();
OrderResponse expOrdResp = new OrderResponse();
expOrdResp.RespMessage.StatusCode = 400;
expOrdResp.RespMessage.StatusMessage = "Invalid Request";
//Assert
Assert.AreEqual(expOrdResp.RespMessage, controller.Post(ordReq).RespMessage);
}
//Test to run with valid input with invalid skus
[Test]
public void Post_Test3()
{
//Arrange
OrderController controller = new OrderController();
OrderRequest ordReq = new OrderRequest();
ordReq.LineItems = new List<LineItem>()
{
new LineItem {skuId = "F", quantity = 2},
new LineItem {skuId = "G", quantity = 2}
};
OrderResponse expOrdResp = new OrderResponse();
expOrdResp.RespMessage.StatusCode = 400;
expOrdResp.RespMessage.StatusMessage = "Invalid Items";
//Assert
Assert.AreEqual(expOrdResp.RespMessage, controller.Post(ordReq).RespMessage);
}
//Test to run with valid input with valid skus
[Test]
public void Post_Test4()
{
//Arrange
OrderController controller = new OrderController();
OrderRequest ordReq = new OrderRequest();
ordReq.LineItems = new List<LineItem>()
{
new LineItem {skuId = "A", quantity = 2},
new LineItem {skuId = "B", quantity = 2}
};
OrderResponse expOrdResp = new OrderResponse();
expOrdResp.RespMessage.StatusCode = 200;
expOrdResp.RespMessage.StatusMessage = "Success";
//Assert
Assert.AreEqual(expOrdResp.RespMessage, controller.Post(ordReq).RespMessage);
}
//Test to run with valid input with valid skus - Compare cartTotal and Skutotals
[Test]
public void Post_Test5()
{
//Arrange
OrderController controller = new OrderController();
OrderRequest ordReq = new OrderRequest();
ordReq.LineItems = new List<LineItem>()
{
new LineItem {skuId = "A", quantity = 1},
new LineItem {skuId = "B", quantity = 1},
new LineItem {skuId = "C", quantity = 1},
new LineItem {skuId = "D", quantity = 1}
};
OrderResponse expOrdResp = new OrderResponse();
expOrdResp.LineItemPrice = new List<LineItemPrice>()
{
new LineItemPrice { skuId = "A", quantity=1, promoDesc="", skuTotal=50},
new LineItemPrice { skuId = "B", quantity=1, promoDesc="", skuTotal=30},
new LineItemPrice { skuId = "C", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=0},
new LineItemPrice { skuId = "D", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=30}
};
expOrdResp.CartTotal = 110;
expOrdResp.RespMessage.StatusCode = 200;
expOrdResp.RespMessage.StatusMessage = "Success";
OrderResponse actOrdResp = controller.Post(ordReq);
//Assert
Assert.That(expOrdResp.LineItemPrice, Is.EqualTo(actOrdResp.LineItemPrice));
Assert.That(expOrdResp.CartTotal, Is.EqualTo(actOrdResp.CartTotal));
Assert.That(expOrdResp.RespMessage, Is.EqualTo(actOrdResp.RespMessage));
}
}
}
<file_sep>/Promotions/Models/BuyXforY.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Promotions.Models
{
public class BuyXforY
{
public string sku { get; set; }
public int quantity {get;set;}
public float price { get; set; }
}
}
<file_sep>/PromotionEngine_Common/Models/LineItem.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PromotionEngine_Common.Models
{
public class LineItem : IEquatable<LineItem>
{
private string _skuId;
private int _quantity;
public string skuId
{
set
{
if(!string.IsNullOrEmpty(value))
{
this._skuId = value;
}
}
get
{
return this._skuId;
}
}
public int quantity
{
set
{
if(value>0)
{
this._quantity = value;
}
else
{
throw new Exception("Quantity cannot be null");
}
}
get
{
return this._quantity;
}
}
public bool Equals(LineItem li)
{
if (li is null)
{
return false;
}
if (skuId == li.skuId && quantity == li.quantity)
{
return true;
}
else
{
return false;
}
}
}
}
<file_sep>/SkuPriceInfo/SkuPriceInfoAdaptor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SkuPriceInfo
{
public class SkuPriceInfoAdaptor : SkuPriceInfo, ISkuPriceInfo
{
/* Inherits SkuPriceInfo(base class) and Interface ISkuPriceInfo
* Implements ISkuPriceInfo interface
* Acts as a wrapper class for base class methods inside the interface implementation
*/
public Dictionary<string, float> GetSkuPriceInfo()
{
try
{
return GetSkuPriceInfoDetails();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public override Dictionary<string, float> GetSkuPriceInfoDetails()
{
try
{
return base.GetSkuPriceInfoDetails();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
<file_sep>/Coding_Test_PromotionEngine.Tests/ApplyPromoCalTotal_Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using NUnit.Framework;
using PromotionEngine_Common.Models;
using Promotions.Adaptor;
namespace Coding_Test_PromotionEngine.Tests
{
[TestFixture]
public class ApplyPromoCalTotal_Test
{
[Test]
public void Cal_CartTotal_With_Promo_Test()
{
IPromoPriceCal promoPriceCal = new PromoPriceCalAdaptor();
List<LineItemPrice> input = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=3, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=2, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=1, promoDesc="", skuTotal=0},
};
List<LineItemPrice> expResult = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=3, promoDesc="Buy3For130", skuTotal=130},
new LineItemPrice{skuId="B", quantity=2, promoDesc="Buy2For45", skuTotal=45},
new LineItemPrice{skuId="C", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=0},
new LineItemPrice{skuId="D", quantity=1, promoDesc="Buy2SKUfor30", skuTotal=30},
};
List<LineItemPrice> actResult = new List<LineItemPrice>();
float actCartTotal;
float expCartTotal = 205;
promoPriceCal.Run_Promos_Cal_Total(input, out actResult, out actCartTotal);
Assert.That(expResult, Is.EqualTo(actResult));
Assert.AreEqual(actCartTotal, expCartTotal);
}
}
}
<file_sep>/Coding_Test_PromotionEngine/Models/OrderRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PromotionEngine_Common.Models;
namespace Coding_Test_PromotionEngine.Models
{
public class OrderRequest
{
public List<LineItem> LineItems { get; set; }
}
}<file_sep>/Coding_Test_PromotionEngine/Appplication/CartCal.cs
using Coding_Test_PromotionEngine.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PromotionEngine_Common.Models;
using Promotions;
using Promotions.Adaptor;
namespace Coding_Test_PromotionEngine.Appplication
{
public class CartCal : ICartCal
{
/* Link between the API and the other projects
* Uses the IPromoPriceCal interface and PromoPriceCalAdaptor to calculate the sku total and the cart total
* Assigns the info to the OrderResponse object
*/
public OrderResponse ProcessLineItems(OrderRequest ordReq)
{
OrderResponse ordRes = new OrderResponse();
ordRes = AddLineItems(ordReq);
ordRes = CalculateCartSkuTotal(ordRes);
return ordRes;
}
private OrderResponse AddLineItems(OrderRequest req)
{
try
{
OrderResponse ordRes = new OrderResponse();
ordRes.LineItemPrice = req.LineItems.ConvertAll(x => new LineItemPrice
{
skuId = x.skuId,
quantity = x.quantity,
promoDesc = "",
skuTotal = 0
});
ordRes.CartTotal = 0;
return ordRes;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private OrderResponse CalculateCartSkuTotal(OrderResponse res)
{
OrderResponse oRes = new OrderResponse();
List<LineItemPrice> outList = new List<LineItemPrice>();
float cartTotal = 0f;
try
{
IPromoPriceCal promoPriceCal = new PromoPriceCalAdaptor();
promoPriceCal.Run_Promos_Cal_Total(res.LineItemPrice, out outList, out cartTotal);
oRes.LineItemPrice = outList;
oRes.CartTotal = cartTotal;
return oRes;
}
catch (Exception ex)
{
oRes.RespMessage.StatusCode = 400;
oRes.RespMessage.StatusMessage = ex.Message;
return oRes;
}
}
}
}<file_sep>/Coding_Test_PromotionEngine/Appplication/SkuCheck.cs
using Coding_Test_PromotionEngine.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Coding_Test_PromotionEngine.Appplication
{
public class SkuCheck
{
public bool Check_Skus(OrderRequest ordReq)
{
List<string> activeSkus = new List<string>(){ "A", "B", "C", "D" };
List<string> reqSkus = new List<string>();
foreach(var item in ordReq.LineItems)
{
reqSkus.Add(item.skuId);
}
return !reqSkus.Except(activeSkus).Any();
}
}
}<file_sep>/Coding_Test_PromotionEngine.Tests/Promotion1_Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit;
using NUnit.Framework;
using PromotionEngine_Common.Models;
using Promotions;
namespace Coding_Test_PromotionEngine.Tests
{
[TestFixture]
public class Promotion1_Test
{
//Basic TestCase with Skus A and B eligible
[TestCase(3,2,130,45)]
[TestCase(4, 3, 180, 75)]
[TestCase(5, 4, 230, 90)]
[TestCase(6, 5, 260, 120)]
public void Promotion1_Test1( int a, int b, float c, float d)
{
List<LineItemPrice> input = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=a, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=b, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=3, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=2, promoDesc="", skuTotal=0},
};
List<LineItemPrice> expResult = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=a, promoDesc="Buy3For130", skuTotal=c},
new LineItemPrice{skuId="B", quantity=b, promoDesc="Buy2For45", skuTotal=d},
new LineItemPrice{skuId="C", quantity=3, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=2, promoDesc="", skuTotal=0},
};
List<LineItemPrice> actResult = new List<LineItemPrice>();
IPromotion1 iPr = new Promotion1();
actResult = iPr.BuyNSKUUnitsForFixed(input);
Assert.That(expResult, Is.EqualTo(actResult));
}
//Basic testcase with none of the skus eligible
[Test]
public void Promotion1_Test2()
{
List<LineItemPrice> input = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=1, promoDesc="", skuTotal=0},
};
List<LineItemPrice> expResult = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="C", quantity=1, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=1, promoDesc="", skuTotal=0},
};
List<LineItemPrice> actResult = new List<LineItemPrice>();
IPromotion1 iPr = new Promotion1();
actResult = iPr.BuyNSKUUnitsForFixed(input);
Assert.That(expResult, Is.EqualTo(actResult));
}
//TestCase with SkuId E not in list-Promotion does not apply
[Test]
public void Promotion1_Test3()
{
List<LineItemPrice> input = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=5, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="B", quantity=4, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="E", quantity=3, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=2, promoDesc="", skuTotal=0},
};
List<LineItemPrice> expResult = new List<LineItemPrice>()
{
new LineItemPrice{skuId="A", quantity=5, promoDesc="Buy3For130", skuTotal=230},
new LineItemPrice{skuId="B", quantity=4, promoDesc="Buy2For45", skuTotal=90},
new LineItemPrice{skuId="E", quantity=3, promoDesc="", skuTotal=0},
new LineItemPrice{skuId="D", quantity=2, promoDesc="", skuTotal=0},
};
List<LineItemPrice> actResult = new List<LineItemPrice>();
IPromotion1 iPr = new Promotion1();
actResult = iPr.BuyNSKUUnitsForFixed(input);
Assert.That(expResult, Is.EqualTo(actResult));
}
}
}
<file_sep>/Promotions/IPromotion2.cs
using PromotionEngine_Common.Models;
using System.Collections.Generic;
namespace Promotions
{
public interface IPromotion2
{
List<LineItemPrice> BuyTwoSKUForFixed(List<LineItemPrice> listItems);
}
}<file_sep>/PromotionEngine_Common/Models/LineItemPrice.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PromotionEngine_Common.Models
{
public class LineItemPrice:IEquatable<LineItemPrice>
{
private string _skuId;
private int _quantity;
private float _skuTotal;
public string skuId
{
set
{
if (!string.IsNullOrEmpty(value))
{
this._skuId = value;
}
else
{
throw new Exception("No skuId");
}
}
get
{
return this._skuId;
}
}
public int quantity
{
set
{
if (value > 0)
{
this._quantity = value;
}
else
{
throw new Exception("Quantity cannot be negative or zero");
}
}
get
{
return this._quantity;
}
}
public string promoDesc { get; set; }
public float skuTotal
{
set
{
if (value >= 0)
{
this._skuTotal = value;
}
else
{
throw new Exception("SkuTotal cannot be negative");
}
}
get
{
return this._skuTotal;
}
}
public bool Equals(LineItemPrice li)
{
if (li is null)
{
return false;
}
if (skuId == li.skuId && quantity == li.quantity && promoDesc == li.promoDesc && skuTotal == li.skuTotal)
{
return true;
}
else
{
return false;
}
}
}
}
| 682e23dc4e015be5df83616a5ba19d9dd28940ed | [
"Markdown",
"C#"
] | 27 | C# | Bhuvanesh1893/Coding_Test_PromotionEngine | 836e09662f44668955c7ec01a1a0d464ae0bfb69 | 588c7bf16c89ff8a769345a85e0363271aa20a4d |
refs/heads/master | <file_sep>'''
Created on Mar 29, 2017
@author: dan
'''
from datetime import datetime
import math
import os
import time
import fire
from digits import DigitData
import image_processing
import numpy as np
import tensorflow as tf
# from tensorflow.examples.tutorials.mnist import input_data
# mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
class Config(object):
init_scale = 0.05
learning_rate = 1.0
max_grad_norm = 5
num_layers = 2
num_steps = 64
hidden_size = 200
in_size = 64
max_epoch = 4
max_max_epoch = 13
keep_prob = 1.0
lr_decay = 0.5
batch_size = 20
forget_bias = 0.0
data_type = tf.float32
num_classes = 11
def small(self):
return self
def medium(self):
self.init_scale = 0.05
self.learning_rate = 1.0
self.max_grad_norm = 5
self.num_layers = 2
self.num_steps = 64
self.hidden_size = 650
self.in_size = 64
self.max_epoch = 6
self.max_max_epoch = 39
self.keep_prob = 0.5
self.lr_decay = 0.8
self.batch_size = 20
self.forget_bias = 0.0
self.data_type = tf.float32
self.num_classes = 11
return self
def large(self):
self.init_scale = 0.04
self.learning_rate = 1.0
self.max_grad_norm = 10
self.num_layers = 2
self.num_steps = 64
self.hidden_size = 1500
self.in_size = 64
self.max_epoch = 14
self.max_max_epoch = 55
self.keep_prob = 0.35
self.lr_decay = 1 / 1.15
self.batch_size = 20
self.forget_bias = 0.0
self.data_type = tf.float32
self.num_classes = 11
return self
def custom(self, logdir,perment=False, init_scale=None, learning_rate=None, max_grad_norm=None,
num_layers=None, num_steps=None, hidden_size=None, in_size=None, max_epoch=None,
max_max_epoch=None, keep_prob=None, lr_decay=None, batch_size=None,
forget_bias=None, data_type=None, num_classes=None):
conf_new = Config()
conf_new.init_scale = init_scale if init_scale else self.init_scale
conf_new.learning_rate = learning_rate if learning_rate else self.learning_rate
conf_new.max_grad_norm = max_grad_norm if max_grad_norm else self.max_grad_norm
conf_new.num_layers = num_layers if num_layers else self.num_layers
conf_new.num_steps = num_steps if num_steps else self.num_steps
conf_new.hidden_size = hidden_size if hidden_size else self.hidden_size
conf_new.in_size = in_size if in_size else self.in_size
conf_new.max_epoch = max_epoch if max_epoch else self.max_epoch
conf_new.max_max_epoch = max_max_epoch if max_max_epoch else self.max_max_epoch
conf_new.keep_prob = keep_prob if keep_prob else self.keep_prob
conf_new.lr_decay = lr_decay if lr_decay else self.lr_decay
conf_new.batch_size = batch_size if batch_size else self.batch_size
conf_new.forget_bias = forget_bias if forget_bias else self.forget_bias
conf_new.data_type = data_type if data_type else self.data_type
conf_new.num_classes = num_classes if num_classes else self.num_classes
if perment:
if not os.path.exists(logdir):
os.makedirs(logdir)
with open(logdir + "/config.cfg", "a") as config_file:
attrs = vars(conf_new)
print('\n'.join("%s: %s" % item for item in attrs.items()))
config_file.write(str(datetime.now()))
config_file.write("\n")
config_file.write(', '.join("%s: %s" % item for item in attrs.items()))
config_file.write("\n\n")
return conf_new
class RNNInput(object):
train_set = DigitData(subset="train")
valid_set = DigitData(subset="validation")
def __init__(self, config, isTrain):
self.config = config
self.isTrain = isTrain
return
def get_data(self):
return self._data_inputs(self.isTrain, False)
def _data_inputs(self, isTrain, isOnehot):
if isTrain:
dataset = self.train_set
else:
dataset = self.valid_set
# batch_x, batch_y = image_processing.distorted_inputs(dataset, self.config.batch_size, self.config.num_steps, 4)
batch_x, batch_y = image_processing.batch_inputs(dataset, self.config.batch_size, isTrain, self.config.num_steps, 4)
batch_x = tf.image.rgb_to_grayscale(batch_x)
batch_x = tf.reshape(batch_x, [self.config.batch_size, self.config.num_steps, self.config.in_size])
batch_y = tf.Print(batch_y, [batch_y], 'Flat = ', summarize=self.config.in_size, first_n=1)
batch_y = tf.cast(batch_y, tf.int32) - 0
if isOnehot:
batch_yy = tf.one_hot(batch_y, 10, 1, 0, -1)
batch_yy = tf.Print(batch_yy, [batch_yy], 'Flat = ', summarize=self.config.in_size, first_n=1)
# batch_x=tf.Print(batch_x, [batch_x],'Pixels = ',summarize=3, first_n=20)
# batch_x = tf.cast(batch_x, tf.float32) + 1
# batch_x = tf.cast(batch_x, tf.int32)
# batch_x = tf.cast(batch_x, tf.float32)
# batch_x=tf.Print(batch_x, [batch_x],'Pixels = ',summarize=3, first_n=20)
print("get data...")
return batch_x, batch_y
class RNNModel(object):
RMSPROP_DECAY = 0.9 # Decay term for RMSProp.
RMSPROP_MOMENTUM = 0.9 # Momentum in RMSProp.
RMSPROP_EPSILON = 1.0 # Epsilon term for RMSProp.
MOVING_AVERAGE_DECAY = 0.9999
def __init__(self, config, inputs_data, isTrain=True):
self.config = config
self.inputs_data = inputs_data
self.images, self.labels = inputs_data.get_data()
self.labels = tf.Print(self.labels, [self.labels], 'Labels : ', summarize=self.config.batch_size, first_n=1)
# self.labels=tf.Print(self.labels, [tf.argmax(self.labels,1)],'Flat1 = '+str(isTrain),summarize=100, first_n=100)
# with tf.device("/gpu:0"):
neural_nets = tf.contrib.rnn.MultiRNNCell(
[self._lstm() for _ in range(self.config.num_layers)], state_is_tuple=True)
self.init_state = neural_nets.zero_state(self.config.batch_size, self.data_type())
output_, self._state = tf.nn.dynamic_rnn(neural_nets, self.images, dtype=self.data_type(), initial_state=self.init_state, parallel_iterations=64)
# output = tf.transpose(output_, [1, 0, 2])
# last = tf.gather(output, int(output.get_shape()[0]) - 1)
# lst=[]
# out = tf.unstack(output_)
# for o in out:
# o=tf.reshape(o, [1,config.in_size*config.hidden_size])
# lst.append(self.inference(o, 128, 32))
# logits_1=tf.reshape(tf.stack(lst, 0),[config.batch_size,config.num_classes])
last = output_[:, -1, :]
softmax_w = tf.get_variable(
"softmax_w", [self.config.hidden_size, self.config.num_classes], dtype=self.data_type()) # 300*10000
softmax_b = tf.get_variable("softmax_b", [self.config.num_classes], dtype=self.data_type()) # 10000
logits = tf.nn.softmax(tf.matmul(last, softmax_w) + softmax_b)
self.labels = tf.to_int64(self.labels)
# self._cost= cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_1, labels=self.labels))
loss = tf.contrib.legacy_seq2seq.sequence_loss_by_example(
[logits],
[tf.reshape(self.labels, [-1])], # 20*5[tensor] =>100 [list]
[tf.ones([config.batch_size], dtype=self.data_type())]) # loss:100[tensor]
self._cost = cost = tf.reduce_sum(loss) / config.batch_size
tf.summary.scalar("loss", self._cost)
logits = tf.Print(logits, [tf.arg_max(logits, 1)], 'logits : ', summarize=self.config.batch_size, first_n=1)
corrects = tf.nn.in_top_k(logits, self.labels, 1)
corrects = tf.Print(corrects, [corrects], 'Prediction : ', summarize=self.config.batch_size, first_n=1)
accuracy = tf.reduce_mean(tf.cast(corrects, tf.float32))
self._accuracy = accuracy
if not isTrain:
tf.summary.scalar("Validation Accuracy", accuracy)
return
else:
tf.summary.scalar("Train Accuracy", accuracy)
self._lr = tf.Variable(0.0, trainable=False)
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), config.max_grad_norm)
# optimizer = tf.train.RMSPropOptimizer(self._lr, self.RMSPROP_DECAY,
# momentum=self.RMSPROP_MOMENTUM,
# epsilon=self.RMSPROP_EPSILON)
optimizer = tf.train.GradientDescentOptimizer(self._lr)
self._train_op = optimizer.apply_gradients(zip(grads, tvars), global_step=tf.contrib.framework.get_or_create_global_step())
tf.summary.scalar('learning_rate', self._lr)
tf.summary.scalar("batch size", self.config.batch_size)
for var in tf.trainable_variables():
tf.summary.histogram(var.op.name, var)
# self._train_op = optimizer.minimize(self._cost,global_step=tf.contrib.framework.get_or_create_global_step())
self._summary_op = tf.summary.merge_all()
self._new_lr = tf.placeholder(
tf.float32, shape=[], name="new_learning_rate")
self._lr_update = tf.assign(self._lr, self._new_lr)
def inference(self,images, hidden1_units, hidden2_units):
"""Build the MNIST model up to where it may be used for inference.
Args:
images: Images placeholder, from inputs().
hidden1_units: Size of the first hidden layer.
hidden2_units: Size of the second hidden layer.
Returns:
softmax_linear: Output tensor with the computed logits.
"""
# Hidden 1
with tf.name_scope('hidden1'):
weights = tf.Variable(
tf.truncated_normal([64*200, hidden1_units],
stddev=1.0 / math.sqrt(float(64*200))),
name='weights')
biases = tf.Variable(tf.zeros([hidden1_units]),
name='biases')
hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)
# Hidden 2
with tf.name_scope('hidden2'):
weights = tf.Variable(
tf.truncated_normal([hidden1_units, hidden2_units],
stddev=1.0 / math.sqrt(float(hidden1_units))),
name='weights')
biases = tf.Variable(tf.zeros([hidden2_units]),
name='biases')
hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)
# Linear
with tf.name_scope('softmax_linear'):
weights = tf.Variable(
tf.truncated_normal([hidden2_units, 11],
stddev=1.0 / math.sqrt(float(hidden2_units))),
name='weights')
biases = tf.Variable(tf.zeros([11]),
name='biases')
logits = tf.matmul(hidden2, weights) + biases
return logits
def data_type(self):
"""tf.float32 or tf.float16"""
return self.config.data_type
def _lstm(self):
"""Cell unit"""
return tf.contrib.rnn.LSTMCell(
self.config.hidden_size, forget_bias=self.config.forget_bias, state_is_tuple=True)
@property
def cost(self):
"""Calculate loss"""
return self._cost
@property
def lr(self):
return self._lr
@property
def last_state(self):
return self._state
@property
def init_op(self):
return tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
@property
def train_op(self):
# self.images, self.labels = self._inputs_data.get_data()
return self._train_op
@property
def accuracy(self):
return self._accuracy
def assign_lr(self, session, lr_value):
session.run(self._lr_update, feed_dict={self._new_lr: lr_value})
@property
def summary_op(self):
return self._summary_op
def _predict(self, inputs):
# TODO: predict
return
def _predict_op(self):
inputs = tf.placeholder(self.data_type(), [self.config.batch_size, self.config.num_steps, self.config.in_size], "TestData")
logits, _ = self._predict(inputs)
return tf.argmax(logits, 1)
class RNN():
def __init__(self, config):
self.config = config
def train(self, session, sv, train_model, valid_model, verbose=False):
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=session, coord=coord)
# summary_writer = tf.summary.FileWriter("log/summary", graph=session.graph)
try:
step = 0
costs = 0.0
iters = 0
start_time = time.time()
# session.run(train_model.init_op)
state = session.run(train_model.init_state)
fetches = {
"cost": train_model.cost,
"final_state": train_model.last_state,
# "embeddings": model.embeddings
"run_op":train_model.train_op
}
epoch = 0
old = 1
while not coord.should_stop():
epoch = step / (9000 / self.config.batch_size)
if epoch != old: # updte learning rate
lr_decay = self.config.lr_decay ** max(epoch + 1 - self.config.max_epoch, 0.0)
train_model.assign_lr(session, self.config.learning_rate * lr_decay)
old = epoch
feed_dict = {}
for i, (c, h) in enumerate(train_model.init_state):
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
if False:
run_options = tf.RunOptions(trace_level=3)
run_metadata = tf.RunMetadata()
rst = session.run(fetches,
feed_dict=feed_dict,
options=run_options,
run_metadata=run_metadata)
sv.summary_writer.add_run_metadata(run_metadata, 'step%03d' % step)
else:
rst = session.run(fetches, feed_dict)
loss_value = rst["cost"]
costs += loss_value
iters += train_model.config.num_steps
state = rst["final_state"]
duration = time.time() - start_time
# Print an overview fairly often.
if (step % 100 == 0 or step % (9000 / self.config.batch_size) == 0) and verbose:
print('Epoch: %d, Step: %d, loss: %.3f, perp: %.2f, lr: %3f (%.3f sec)' % (epoch, step, loss_value, np.exp(costs / iters), session.run(train_model.lr),
duration))
if step % (9000 / self.config.batch_size) == 0:
acc = session.run(train_model.accuracy)
print("Accuracy is:", acc)
valid_acc = session.run(valid_model.accuracy)
print("Validation is:", valid_acc)
summary_str = session.run(train_model.summary_op)
# summary_writer.add_summary(summary_str, step)
sv.summary_computed(session, summary_str, global_step=step)
step += 1
except tf.errors.OutOfRangeError:
print('Done training')
finally:
# When done, ask the threads to stop.
coord.request_stop()
# Wait for threads to finish.
coord.join(threads)
session.close()
class Entrance(object):
def train(self, logdir, model, init_scale=None, learning_rate=None, max_grad_norm=None,
num_layers=None, num_steps=None, hidden_size=None, in_size=None, max_epoch=None,
max_max_epoch=None, keep_prob=None, lr_decay=None, batch_size=None,
forget_bias=None, data_type=None, num_classes=None):
config = Config()
if model == "small":
config = Config().small()
elif model == "medium":
config = Config().medium()
elif model == "large":
config = Config().large()
else:
config = Config()
# config = config.custom(logdir,in_size=64, num_steps=64, batch_size=20,num_classes=11,learning_rate=1.0,hidden_size=200,num_layers=2)
config = config.custom(logdir,perment=True, init_scale=init_scale, learning_rate=learning_rate, max_grad_norm=max_grad_norm,
num_layers=num_layers, num_steps=num_steps, hidden_size=hidden_size, in_size=in_size, max_epoch=max_epoch,
max_max_epoch=max_max_epoch, keep_prob=keep_prob, lr_decay=lr_decay, batch_size=batch_size,
forget_bias=forget_bias, data_type=data_type, num_classes=num_classes)
with tf.Graph().as_default():
initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale)
valid_config = config.custom('',batch_size=20)
with tf.name_scope("Train"):
train_input = RNNInput(config, True)
with tf.variable_scope("Model", reuse=None, initializer=initializer):
m = RNNModel(config, train_input, True)
with tf.name_scope("Valid"):
valid_input = RNNInput(valid_config, False)
with tf.variable_scope("Model", reuse=True, initializer=initializer):
mvalid = RNNModel(valid_config, valid_input, False)
sv = tf.train.Supervisor(logdir=logdir)
with sv.managed_session() as session:
rnn = RNN(config)
rnn.train(session, sv, m, mvalid, True)
tf.app.run()
if __name__ == "__main__":
#train('log_test','small')
fire.Fire(Entrance)
<file_sep>'''
Created on Apr 3, 2017
@author: dan
'''
from __future__ import print_function
from collections import Counter
import random
import sys, os
import threading
import fire
from keras import backend as K
from keras import initializers
import keras
from keras.callbacks import Callback, ReduceLROnPlateau, CSVLogger
from keras.layers import Dense, Activation, TimeDistributed, Embedding
from keras.layers import LSTM, GRU, Dropout
from keras.layers import SimpleRNN
from keras.models import Sequential
from keras.optimizers import RMSprop
from keras.utils.vis_utils import plot_model
from tensorflow.contrib.labeled_tensor import batch
from digits import DigitData
import image_processing
from keras_data import Manualeval
import keras_data
import numpy as np
import tensorflow as tf
import tfboard
from scipy.misc import imsave
batch_size = 100
num_classes = 10
epochs = 30
image_size = 64
# input image dimensions
img_rows, img_cols = 64, 64
(x_train, y_train), (x_valid, y_valid), (x_test, y_test) = keras_data.get_data(distorted=True, imageSize=image_size, isValid=False, isWhole=True)
print("train:", x_train.shape, y_train.shape)
print("valid:", x_valid.shape, y_valid.shape)
print("test:", x_test.shape, y_test.shape)
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# embedding_matrix=np.zeros((len(x_train),4096))
# for i in x_train:
# embedding_matrix[i]=x_train[i]
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
y_valid = keras.utils.to_categorical(y_valid, num_classes)
model = Sequential()
model.add(SimpleRNN(1000,
kernel_initializer=initializers.RandomNormal(stddev=0.001),
# recurrent_initializer=initializers.orthogonal(),
activation='relu',
# batch_size=batch_size,
# input_shape=x_train.shape[1:],
input_shape=(64, 64),
# batch_input_shape=(batch_size,64,64),
return_sequences=False,
# stateful=True
))
# model.add(LSTM(150, return_sequences=True,stateful=False))
# model.add(LSTM(100, return_sequences=False,stateful=False))
model.add(Dense(500, activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Dense(num_classes))
model.add(Activation("softmax"))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.RMSprop(lr=1e-4),
metrics=['accuracy'])
plot_model(model, show_shapes=True, to_file='model_rnn_shapes.png')
# tensorbord=tfboard.TensorBoard(log_dir='logs_rnn', histogram_freq=1, write_graph=True, write_images=False)
csv_logger = CSVLogger('training_rnn.log')
reduce_lr = ReduceLROnPlateau(monitor='val_acc', mode='max', factor=0.1, patience=1, min_lr=0.00001, verbose=1, cooldown=4)
me = Manualeval(model, x_test, y_test)
model.fit(x_train, y_train,
batch_size=batch_size,
shuffle=True,
epochs=epochs,
verbose=2,
validation_data=(x_valid, y_valid), callbacks=[me, csv_logger, reduce_lr])
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
#(_, _), (_, _), (x_test, y_test) = keras_data.get_data(isValid=False)
model2_1=Sequential()
model2_1.add(SimpleRNN(1000,
# recurrent_initializer=initializers.orthogonal(),
activation='relu',
# batch_size=batch_size,
# input_shape=x_train.shape[1:],
input_shape=(64, 64),
# batch_input_shape=(batch_size,64,64),
return_sequences=False,
weights=model.layers[0].get_weights()
# stateful=True
))
# model.add(LSTM(150, return_sequences=True,stateful=False))
# model.add(LSTM(100, return_sequences=False,stateful=False))
model2_1.add(Dense(500, activation='relu',weights=model.layers[1].get_weights()))
rst_=model2_1.predict(x_test, batch_size, verbose=1)
print(rst_.shape)
for i,features in enumerate(rst_):
imsave(str(np.argmax(y_test,axis=-1)[i])+'_rnn_features.jpg',features.reshape(25,20))
rst = model.predict(x_test, batch_size, verbose=1)
pr_result = np.argmax(rst, axis=-1)
tr_result = np.argmax(y_test,axis=-1)#np.argmax(y_test,axis=-1)
bolrst = np.equal(tr_result, pr_result)
from scipy.misc import imsave
for i, bol in enumerate(bolrst):
if not bol:
# print(x_test[i].shape)
imsave(str(i)+'_rnn_T:'+str(tr_result[i]) + '_P:'+str(pr_result[i]) + '.jpg', x_test[i])
<file_sep># encoding=utf-8
'''
Created on Apr 11, 2017
@author: dan
'''
import math
import random
import matplotlib.pyplot as plt
import numpy as np
class Gene():
def __init__(self, chromosome_length, amount, mutation_limit=10, isEarlyStop=False):
self.c_length = chromosome_length
self.population = self.init_population(chromosome_length, amount)
# the trigger of mutation
self.last_winner = 0
self.early_stop = isEarlyStop
self.mutation_num = 0
# the limit of mutation
self.mutation_limit = mutation_limit
def reproduction(self, elitism_rate=0.2, survived_rate=0.5, mutation_rate=0.01, cross_over_rate=0.6):
self.mutation_rate = mutation_rate
# select parent
parents = self.selection(elitism_rate, survived_rate)
# mating and crossover
self.mating(parents, cross_over_rate)
# mutation
self.mutation(mutation_rate)
def create_chromosome(self, length):
"""
Generate binary code as chromosome
"""
chromosome = 0
for i in xrange(length):
chromosome |= (1 << i) * random.randint(0, 1)
return chromosome
def init_population(self, chromosome_length, amount):
self.chromosome_length = chromosome_length
self.amount = amount
return [self.create_chromosome(chromosome_length) for i in xrange(amount)]
def fitness(self, x):
# convert binary to decimal
# x = self.decode(chromosome)
# fitness function +(5*np.sin(x/8))*(np.cos(x/19))
return (-1.0 / 10000) * (x - 1023) * x + (5 * np.sin(x / 8)) * (np.cos(x / 19))
def selection(self, elitism_rate, survived_rate):
"""
keep the strongest one and randomly dorp others
"""
# Find the most valuable ones
ranked = self.get_strongest()
# choose the top n strongest one
retain_length = int(len(ranked) * elitism_rate)
parents = ranked[:retain_length]
# drop someone randomly via survived_rate
for chromosome in ranked[retain_length:]:
if self.lucky(survived_rate):
parents.append(chromosome)
return parents
def get_strongest(self):
# Each chromosome looks like this (16115.027477040323, 16) (165.02303255663, 111)
strongest = [(self.fitness(self.decode(chromosome)), chromosome) for chromosome in self.population]
# rank the population by fitness result
strongest = [x[1] for x in sorted(strongest, reverse=True)]
return strongest
def mating(self, parents, cross_over_rate):
"""
Mating and crossover
"""
# newborn will be added into whole population and reproduce with others.
children = []
# the number of newborn
new_count = len(self.population) - len(parents)
# reproduce children
while len(children) < new_count:
# choose parents randomly to reproduce
parent_a = random.randint(0, len(parents) - 1)
parent_b = random.randint(0, len(parents) - 1)
if parent_a != parent_b:
# choose chromosome break point randomly from parents and generate new chromosome
cross_pos = random.randint(0, self.c_length)
mask = 0
if self.lucky(cross_over_rate):
for i in xrange(cross_pos):
mask |= (1 << i)
parent_a = parents[parent_a]
parent_b = parents[parent_b]
# The child will obtain parents gene
child = ((parent_a & mask) |
(parent_b & ~mask)) & ((1 << self.c_length) - 1)
children.append(child)
else:
if parent_a == 0 and parent_b == 0:
# to prevent the chromosome die out.
print 'The population was terminated!'
self.population = self.init_population(self.chromosome_length, self.amount)
return
# update the whole population
self.population = parents + children
def lucky(self, rate):
"""
randomly return true or false to control the mutation or survivors
the value of rnd will be 1 or 2. the rate control the probability of 1 occurs
"""
rnd = np.random.choice(np.arange(1, 3), p=[rate, 1 - rate])
return rnd == 1
def mutation(self, mutation_rate):
"""
mutation, randomly choose one for mutation
"""
for i in xrange(len(self.population)):
if self.lucky(mutation_rate):
j = random.randint(0, self.c_length - 1)
self.population[i] ^= 1 << j
def decode(self, chromosome):
"""
convert binary to decimal
"""
return chromosome * 1023.0 / (2 ** self.c_length - 1)
def output(self, name):
"""
output current result
"""
ranked = self.get_strongest()
print(ranked[0])
rst = self.decode(ranked[0])
# if the result won't change then trigger mutation manually
if self.last_winner == rst:
if self.mutation_num % 2 == 0:
self.mutation(self.mutation_rate)
self.mutation_num += 1
print name, " mutated ", self.mutation_num, "times."
if self.mutation_num > self.mutation_limit:
print "Too many mutations!"
return -1
if self.fitness(rst) > 31 and self.early_stop:
print "Got it!"
print 'f(x)=', self.fitness(rst), ': x=', rst
return -1
self.last_winner = rst
print 'f(x)=', self.fitness(rst), ': x=', rst
return self.fitness(rst)
if __name__ == '__main__':
"""
The length of chromosome will be 10 as 2^10=1023,the amount of chromosome will be 10.
The smaller of amount you choose the more detail of evolution you will see.
The mutation limit is designed to prevent resource exhaust.
"""
chromosome_length = 10
pop_amount = 50
mutation_limit = 2000
epoch = 50
isEarlyStop = False
crossover_rate = [0.2, 0.4, 0.6, 0.8]
geneA = Gene(chromosome_length, pop_amount, mutation_limit, isEarlyStop)
geneB = Gene(chromosome_length, pop_amount, mutation_limit, isEarlyStop)
geneC = Gene(chromosome_length, pop_amount, mutation_limit, isEarlyStop)
geneD = Gene(chromosome_length, pop_amount, mutation_limit, isEarlyStop)
history = {}
history['A'] = []
history['B'] = []
history['C'] = []
history['D'] = []
# reproduce n iterations
for i, cross_over_rate in enumerate(crossover_rate):
for x in xrange(epoch):
geneA.reproduction(elitism_rate=0.2, survived_rate=0.7, mutation_rate=0.01, cross_over_rate=cross_over_rate)
geneB.reproduction(elitism_rate=0.2, survived_rate=0.7, mutation_rate=0.05, cross_over_rate=cross_over_rate)
geneC.reproduction(elitism_rate=0.2, survived_rate=0.7, mutation_rate=0.1, cross_over_rate=cross_over_rate)
geneD.reproduction(elitism_rate=0.2, survived_rate=0.7, mutation_rate=0.2, cross_over_rate=cross_over_rate)
oa = geneA.output('A')
ob = geneB.output('B')
oc = geneC.output('C')
od = geneD.output('D')
terminate = (oa == -1 or ob == -1 or oc == -1 or od == -1)
if not terminate:
history['A'].append(oa)
history['B'].append(ob)
history['C'].append(oc)
history['D'].append(od)
else:
break
# print x ,history
plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow', 'black', 'pink', 'lightblue'])
plt.plot(history['A'], '.')
plt.plot(history['B'], '.')
plt.plot(history['C'], '.')
plt.plot(history['D'], '.')
average = (np.array(history['A']) + np.array(history['B']) + np.array(history['C']) + np.array(history['D'])) / 4
best = np.amax([np.array(history['A']), np.array(history['B']), np.array(history['C']), np.array(history['D'])], axis=0)
worst = np.amin([np.array(history['A']), np.array(history['B']), np.array(history['C']), np.array(history['D'])], axis=0)
plt.plot(average)
plt.plot(best)
plt.plot(worst)
plt.xlabel('Epoch')
plt.ylabel('Max f(x)')
plt.title('cross_over_rate ' + str(cross_over_rate) + '; population: ' + str(pop_amount))
plt.legend(['mutation_rate:0.01', 'mutation_rate:0.05', 'mutation_rate:0.1', 'mutation_rate:0.2', 'Average', 'Best', 'Worst'], loc='upper left')
plt.show()
<file_sep>'''
Created on Apr 9, 2017
@author: dan
'''
from __future__ import print_function
from collections import Counter
import random
import sys, os
import threading
import fire
from keras import backend as K
from keras import initializers
import keras
from keras.callbacks import Callback, ReduceLROnPlateau, CSVLogger
from keras.engine.topology import Input
from keras.engine.training import Model
from keras.layers import Dense, Activation, TimeDistributed, Embedding
from keras.layers import LSTM, GRU, Dropout
from keras.layers import SimpleRNN
from keras.models import Sequential
from keras.optimizers import RMSprop
from keras.utils.vis_utils import plot_model
from scipy.misc import imsave
from scipy.stats._discrete_distns import logser
from sklearn.cluster import KMeans
from digits import DigitData
import image_processing
from keras_data import Manualeval
import keras_data
import numpy as np
import tensorflow as tf
import tfboard
from sklearn.decomposition import PCA
import matplotlib
import itertools
matplotlib.use('Agg')
import matplotlib.pyplot as plt
# from sklearn.model_selection import StratifiedKFold
batch_size = 50
num_classes = 10
epochs = 20
train_size = 9000
test_size = 1000
image_size = 64
# input image dimensions
img_rows, img_cols = 64, 64
(x_train, y_train), (x_valid, y_valid), (x_test, y_test) = keras_data.get_data(distorted=True, imageSize=image_size, isValid=False, isWhole=True)
print("train:", x_train.shape, y_train.shape)
print("valid:", x_valid.shape, y_valid.shape)
print("test:", x_test.shape, y_test.shape)
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
x_train = np.reshape(x_train, (len(x_train), 64 * 64))
x_valid = np.reshape(x_valid, (len(x_valid), 64 * 64))
x_test = np.reshape(x_test, (len(x_test), 64 * 64))
# 2000, 1500, 1000, 500, 10
# model = Sequential()
# model.add(Dense(35, input_shape=(64 * 64,), activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
# model.add(Dense(64 * 64, activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
# model.compile(loss=keras.losses.binary_crossentropy,
# optimizer=keras.optimizers.Adadelta(),
# metrics=['accuracy'])
# plot_model(model, show_shapes=True, to_file='model_1_ae_shapes.png')
# to decay the learning rate from epoch 5
# model.fit(x_train, x_train,
# batch_size=batch_size,
# epochs=2,
# shuffle=True,
# verbose=2,
# validation_data=(x_valid, x_valid), callbacks=[ csv_logger])
input_img = Input(shape=(64 * 64,))
encoded = Dense(35, activation='relu')(input_img)
decoded = Dense(64 * 64, activation='sigmoid')(encoded)
autoencoder = Model(input_img, decoded)
encoder = Model(input_img, encoded)
# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(35,))
# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]
# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
csv_logger = CSVLogger('training_1_ae.log')
plot_model(autoencoder, show_shapes=True, to_file='model_1_ae_shapes.png')
autoencoder.fit(x_train, x_train,
epochs=20,
batch_size=50,
shuffle=True,
verbose=2,
validation_data=(x_test, x_test),callbacks=[ csv_logger])
#me = Manualeval(model, x_test, x_test)
(x_train, y_train), (_, _), (x_test, y_test) = keras_data.get_data(isValid=False,isWhole=True)
x_test_ = np.reshape(x_test, (len(x_test), 64 * 64))
rst_=autoencoder.predict(x_test_, batch_size, verbose=2)
rst_=np.reshape(rst_,(len(x_test_),64,64))
for i, test in enumerate(x_test):
imsave(str(i)+'_orignal_.jpg', x_test[i])
imsave(str(i)+'_generated_.jpg', rst_[i])
if i==5:
break
x_train_ = np.reshape(x_train, (len(x_train), 64 * 64))
rst = encoder.predict(x_train_, len(x_train), verbose=1)
pca = PCA(n_components=2)
X_r = pca.fit(rst).transform(rst)
plt.figure()
colors = itertools.cycle(['navy', 'turquoise', 'darkorange','coral','darkviolet','blue','red','yellow','green','linen'])
lw = 2
cm = plt.cm.get_cmap('Vega10')
sc=plt.scatter(X_r[:, 0], X_r[:, 1], c=y_train,vmin=0, vmax=9,cmap=cm)
plt.colorbar(sc)
# for color, i, target_name in zip(colors, [0,1,2,3,4,5,6,7,8,9], [0,1,2,3,4,5,6,7,8,9]):
# plt.scatter(X_r[y_test == i, 0], X_r[y_test == i, 1], color=color, alpha=.5, lw=lw,
# label=target_name)
plt.savefig('pca.jpg')
kmeans = KMeans(n_clusters=10, random_state=0).fit(rst)
print(kmeans.labels_)
label_dic={}
for i,l in enumerate(kmeans.labels_):
if not l in label_dic:
label_dic[l]=np.zeros((10,1))
label_dic[l][y_train[i]]+=1
#calculate misclassification
for j in label_dic.keys():
cluster_label=np.argmax(label_dic[j])#true label
wrong=0
for l,k in enumerate(label_dic[j]):
if l==cluster_label:#skip the right one
continue
wrong+=k #calculate the amount of wrong
r=str(label_dic[j].T.tolist()[0])
print(str(1-wrong/np.sum(label_dic[j]))+','+r)
#kmeans.predict(rst[900:1000])
<file_sep>'''
Created on Apr 2, 2017
@author: dan
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os.path
import sys
import time
import NNModel
from digits import DigitData
import image_processing
import tensorflow as tf
train_set = DigitData(subset="train")
valid_set = DigitData(subset="validation")
FLAGS = tf.flags
FLAGS.batch_size = 10
def data_inputs(isTrain, isOnehot):
if isTrain:
dataset = train_set
else:
dataset = valid_set
# batch_x, batch_y = image_processing.batch_inputs(dataset, FLAGS.batch_size, isTrain, 64, 4)
batch_x, batch_y = image_processing.distorted_inputs(dataset, FLAGS.batch_size, 64, 4)
batch_x = tf.image.rgb_to_grayscale(batch_x)
batch_y = tf.Print(batch_y, [batch_y], 'Flat = ', summarize=64, first_n=1)
batch_y = tf.cast(batch_y, tf.int32) - 0
batch_yy = batch_y
if isOnehot:
batch_yy = tf.one_hot(batch_y, 11, 1, 0, -1)
batch_yy = tf.Print(batch_yy, [batch_yy], 'Flat = ', summarize=64, first_n=1)
print("get data...")
return batch_x, batch_yy
def cnn(x_image):
# First convolutional layer - maps one grayscale image to 32 feature maps.
W_conv1 = weight_variable([5, 5, 1, 20])
b_conv1 = bias_variable([20])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# Pooling layer - downsamples by 2X.
h_pool1 = max_pool_2x2(h_conv1)
# Second convolutional layer -- maps 32 feature maps to 64.
W_conv2 = weight_variable([5, 5, 20, 40])
b_conv2 = bias_variable([40])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
# Second pooling layer.
h_pool2 = max_pool_2x2(h_conv2)
# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
# is down to 7x7x64 feature maps -- maps this to 1024 features.
W_fc1 = weight_variable([16 * 16 * 40, 640])
b_fc1 = bias_variable([640])
h_pool2_flat = tf.reshape(h_pool2, [-1, 16 * 16 * 40])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# Dropout - controls the complexity of the model, prevents co-adaptation of
# features.
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, 0.25)
# Map the 1024 features to 10 classes, one for each digit
W_fc2 = weight_variable([640, 100])
b_fc2 = bias_variable([100])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
W_fc21 = weight_variable([100, 11])
b_fc21 = bias_variable([11])
y_conv1 = tf.matmul(y_conv, W_fc21) + b_fc21
return y_conv1, keep_prob
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def do_eval(sess,
op_correct,
data_set):
true_count = 0 # Counts the number of correct predictions.
steps_per_epoch = data_set.num_examples_per_epoch() // FLAGS.batch_size
num_examples = steps_per_epoch * FLAGS.batch_size
for step in xrange(steps_per_epoch):
true_count += sess.run(op_correct, feed_dict={})
precision = float(true_count) / num_examples
sess.run(tf.summary.scalar(data_set.name, precision))
print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(num_examples, true_count, precision))
def run_training():
with tf.Graph().as_default():
images, labels = data_inputs(True, True)
valid_images, valid_labels = data_inputs(False, True)
y_conv, keep_prob = cnn(images)
vy_conv, vkeep_prob = cnn(valid_images)
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=y_conv))
tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(cross_entropy, tvars), 5)
optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)
train_op = optimizer.apply_gradients(zip(grads, tvars), global_step=tf.contrib.framework.get_or_create_global_step())
# train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(labels, 1))
valid_correct_prediction = tf.equal(tf.argmax(vy_conv, 1), tf.argmax(valid_labels, 1))
train_correct = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))
valid_correct = tf.reduce_sum(tf.cast(valid_correct_prediction, tf.float32))
summary = NNModel.summary()
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)
sess.run(init)
for step in xrange(FLAGS.max_steps):
start_time = time.time()
if step % 1000 == 0:
do_eval(sess, valid_correct, valid_set)
do_eval(sess, train_correct, train_set)
loss = sess.run([train_op, cross_entropy])
duration = time.time() - start_time
if step % 100 == 0:
print('Step %d: loss = %.2f (%.3f sec)' % (step, loss[1], duration))
summary_str = sess.run(summary, feed_dict={})
summary_writer.add_summary(summary_str, step)
summary_writer.flush()
coord.request_stop()
coord.join(threads)
def main(_):
if tf.gfile.Exists(FLAGS.log_dir):
tf.gfile.DeleteRecursively(FLAGS.log_dir)
tf.gfile.MakeDirs(FLAGS.log_dir)
run_training()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--learning_rate',
type=float,
default=0.03,
help='Initial learning rate.'
)
parser.add_argument(
'--max_steps',
type=int,
default=54000,
help='Number of steps to run trainer.'
)
parser.add_argument(
'--hidden1',
type=int,
default=128,
help='Number of units in hidden layer 1.'
)
parser.add_argument(
'--hidden2',
type=int,
default=32,
help='Number of units in hidden layer 2.'
)
parser.add_argument(
'--hidden3',
type=int,
default=None,
help='Number of units in hidden layer 3.'
)
parser.add_argument(
'--batch_size',
type=int,
default=10,
help='Batch size. Must divide evenly into the dataset sizes.'
)
# parser.add_argument(
# '--input_data_dir',
# type=str,
# default='/tmp/tensorflow/mnist/input_data',
# help='Directory to put the input data.'
# )
parser.add_argument(
'--log_dir',
type=str,
default='/tmp/tensorflow/mnist/logs/fully_connected_feed',
help='Directory to put the log data.'
)
parser.add_argument(
'--fake_data',
default=False,
help='If true, uses fake data for unit testing.',
action='store_true'
)
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
<file_sep>'''
Created on Apr 3, 2017
@author: dan
'''
from __future__ import print_function
from collections import Counter
import random
import sys, os
import threading
import fire
from keras import backend as K
from keras import initializers
import keras
from keras.callbacks import Callback, ReduceLROnPlateau, CSVLogger
from keras.layers import Dense, Activation, TimeDistributed, Embedding
from keras.layers import LSTM, GRU, Dropout
from keras.layers import SimpleRNN
from keras.models import Sequential
from keras.optimizers import RMSprop
from keras.utils.vis_utils import plot_model
from scipy.stats._discrete_distns import logser
from digits import DigitData
import image_processing
from keras_data import Manualeval
import keras_data
import numpy as np
import tensorflow as tf
import tfboard
from scipy.misc import imsave
# from sklearn.model_selection import StratifiedKFold
batch_size = 50
num_classes = 10
epochs = 20
train_size = 9000
test_size = 1000
image_size = 64
# input image dimensions
img_rows, img_cols = 64, 64
(x_train, y_train), (x_valid, y_valid), (x_test, y_test) = keras_data.get_data(distorted=True, imageSize=image_size, isValid=False, isWhole=True)
print("train:", x_train.shape, y_train.shape)
print("valid:", x_valid.shape, y_valid.shape)
print("test:", x_test.shape, y_test.shape)
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
y_valid = keras.utils.to_categorical(y_valid, num_classes)
x_train = np.reshape(x_train, (len(x_train), 64 * 64))
x_valid = np.reshape(x_valid, (len(x_valid), 64 * 64))
x_test = np.reshape(x_test, (len(x_test), 64 * 64))
# 2000, 1500, 1000, 500, 10
model = Sequential()
model.add(Dense(2500, input_shape=(64 * 64,), activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Dense(2000, activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Dense(1500, activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Dense(1000, activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Dense(500, activation='relu', kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Dense(num_classes, kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Activation("softmax"))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.RMSprop(lr=1e-4),
metrics=['accuracy'])
plot_model(model, show_shapes=True, to_file='model_nn_shapes.png')
reduce_lr = ReduceLROnPlateau(monitor='val_acc', mode='max', factor=0.1, patience=1, min_lr=0.00001, verbose=1, cooldown=4)
csv_logger = CSVLogger('training_nn.log')
me = Manualeval(model, x_test, y_test)
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
# epochs=3,
shuffle=True,
verbose=2,
validation_data=(x_valid, y_valid), callbacks=[me, csv_logger, reduce_lr])
#(_, _), (_, _), (x_test, y_test) = keras_data.get_data(isValid=False)
#generate features
model2_1=Sequential()
model2_1.add(Dense(2500, input_shape=(64 * 64,), activation='relu', weights=model.layers[0].get_weights()))
model2_1.add(Dense(2000, activation='relu', weights=model.layers[1].get_weights()))
model2_1.add(Dense(1500, activation='relu', weights=model.layers[2].get_weights()))
model2_1.add(Dense(1000, activation='relu', weights=model.layers[3].get_weights()))
model2_1.add(Dense(500, activation='relu', weights=model.layers[4].get_weights()))
rst_=model2_1.predict(x_test, batch_size, verbose=1)
print(rst_.shape)
for i,features in enumerate(rst_):
imsave(str(np.argmax(y_test,axis=-1)[i])+'_mlp_features.jpg',features.reshape(25,20))
#generate misclassified
rst = model.predict(x_test, batch_size, verbose=1)
pr_result = np.argmax(rst, axis=-1)
tr_result = np.argmax(y_test,axis=-1)
bolrst = np.equal(tr_result, pr_result)
x_test_ = np.reshape(x_test, (len(x_test), 64 , 64))
for i, bol in enumerate(bolrst):
if not bol:
imsave(str(i)+'_mlp_T:'+str(tr_result[i]) + '_P:'+str(pr_result[i]) + '.jpg', x_test_[i])
# score = model.evaluate(x_test, y_test, verbose=1,batch_size=len(x_test))
# print('Test loss:', score[0])
# print('Test accuracy:', score[1])
<file_sep>'''
Created on Apr 2, 2017
@author: dan
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os.path
import sys
import time
import NNModel
from digits import DigitData
import image_processing
import tensorflow as tf
# pylint: disable=missing-docstring
# Basic model parameters as external flags.
FLAGS = None
train_set = DigitData(subset="train")
valid_set = DigitData(subset="validation")
def data_inputs(isTrain, isOnehot):
if isTrain:
dataset = train_set
else:
dataset = valid_set
batch_x, batch_y = image_processing.batch_inputs(dataset, FLAGS.batch_size, isTrain, 64, 4)
batch_x = tf.image.rgb_to_grayscale(batch_x)
batch_x = tf.reshape(batch_x, [FLAGS.batch_size, 64 * 64])
batch_y = tf.Print(batch_y, [batch_y], 'Flat = ', summarize=64, first_n=1)
batch_y = tf.cast(batch_y, tf.int32) - 0
if isOnehot:
batch_yy = tf.one_hot(batch_y, 10, 1, 0, -1)
batch_yy = tf.Print(batch_yy, [batch_yy], 'Flat = ', summarize=64, first_n=1)
print("get data...")
return batch_x, batch_y
def do_eval(sess,
op_correct,
data_set):
true_count = 0 # Counts the number of correct predictions.
steps_per_epoch = data_set.num_examples_per_epoch() // FLAGS.batch_size
num_examples = steps_per_epoch * FLAGS.batch_size
for step in xrange(steps_per_epoch):
true_count += sess.run(op_correct, feed_dict={})
precision = float(true_count) / num_examples
sess.run(tf.summary.scalar(data_set.name, precision))
print(' Num examples: %d Num correct: %d Precision @ 1: %0.04f' %
(num_examples, true_count, precision))
def run_training():
with tf.Graph().as_default():
images, labels = data_inputs(True, False)
valid_images,valid_labels=data_inputs(False, False)
print("Training")
logits = NNModel.inference(images,
FLAGS.hidden1,
FLAGS.hidden2,
FLAGS.hidden3)
valid_logits = NNModel.inference(valid_images,
FLAGS.hidden1,
FLAGS.hidden2,
FLAGS.hidden3)
loss = NNModel.loss(logits, labels)
train_op = NNModel.training(loss, FLAGS.learning_rate)
eval_correct = NNModel.evaluation(logits, labels)
valid_correct = NNModel.evaluation(valid_logits, valid_labels)
summary = NNModel.summary()
init = tf.global_variables_initializer()
saver = tf.train.Saver()
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)
sess.run(init)
for step in xrange(FLAGS.max_steps):
start_time = time.time()
_, loss_value = sess.run([train_op, loss],
feed_dict={})
duration = time.time() - start_time
if (step + 1) % 1000 == 0 or (step + 1) == FLAGS.max_steps:
checkpoint_file = os.path.join(FLAGS.log_dir, 'model.ckpt')
saver.save(sess, checkpoint_file, global_step=step)
print('Training Data Eval:')
do_eval(sess,
eval_correct,
train_set)
print('Validation Data Eval:')
do_eval(sess,
valid_correct,
valid_set)
# print('Test Data Eval:')
# do_eval(sess,
# eval_correct,
# images_placeholder,
# labels_placeholder,
# data_inputs(False, False))
if step % 100 == 0:
print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value, duration))
summary_str = sess.run(summary, feed_dict={})
summary_writer.add_summary(summary_str, step)
summary_writer.flush()
coord.request_stop()
coord.join(threads)
def main(_):
if tf.gfile.Exists(FLAGS.log_dir):
tf.gfile.DeleteRecursively(FLAGS.log_dir)
tf.gfile.MakeDirs(FLAGS.log_dir)
run_training()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--learning_rate',
type=float,
default=0.01,
help='Initial learning rate.'
)
parser.add_argument(
'--max_steps',
type=int,
default=2000,
help='Number of steps to run trainer.'
)
parser.add_argument(
'--hidden1',
type=int,
default=128,
help='Number of units in hidden layer 1.'
)
parser.add_argument(
'--hidden2',
type=int,
default=32,
help='Number of units in hidden layer 2.'
)
parser.add_argument(
'--hidden3',
type=int,
default=None,
help='Number of units in hidden layer 3.'
)
parser.add_argument(
'--batch_size',
type=int,
default=100,
help='Batch size. Must divide evenly into the dataset sizes.'
)
# parser.add_argument(
# '--input_data_dir',
# type=str,
# default='/tmp/tensorflow/mnist/input_data',
# help='Directory to put the input data.'
# )
parser.add_argument(
'--log_dir',
type=str,
default='/tmp/tensorflow/mnist/logs/fully_connected_feed',
help='Directory to put the log data.'
)
parser.add_argument(
'--fake_data',
default=False,
help='If true, uses fake data for unit testing.',
action='store_true'
)
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
<file_sep>'''
Created on Mar 27, 2017
@author: dan
'''
import time
from tensorflow.contrib import rnn
from digits import DigitData
import image_processing as ip
import numpy as np
import tensorflow as tf
import copy
from tensorflow.contrib.labeled_tensor import placeholder
# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
mnist = ''
# Parameters
training_iters = 10000
batch_size = 20
display_step = 10
# Network Parameters
n_input = 28 # MNIST data input (img shape: 28*28)
n_steps = 28 # timesteps
n_hidden = 300 # hidden layer num of features
num_layers = 2
n_classes = 10 # MNIST total classes (0-9 digits)
FLAGS = tf.app.flags.FLAGS
FLAGS.train_dir = "data"
FLAGS.eval_dir = "data"
final_state = None # RNN memory
train_set = DigitData(subset="train")
valid_set = DigitData(subset="validation")
RMSPROP_DECAY = 0.9 # Decay term for RMSProp.
RMSPROP_MOMENTUM = 0.9 # Momentum in RMSProp.
RMSPROP_EPSILON = 1.0 # Epsilon term for RMSProp.
MOVING_AVERAGE_DECAY=0.9999
initial_learning_rate=0.1
learning_rate_decay_factor=0.16
def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev)
tf.summary.scalar('max', tf.reduce_max(var))
tf.summary.scalar('min', tf.reduce_min(var))
tf.summary.histogram('histogram', var)
def data_inputs(isTrain, isOneHot):
if isTrain:
dataset = train_set
else:
dataset = valid_set
batch_x, batch_y = ip.distorted_inputs(dataset, batch_size, 4)
batch_x = tf.image.rgb_to_grayscale(batch_x)
batch_x = tf.reshape(batch_x, [batch_size, 28, 28])
# batch_y=tf.to_float(batch_y, name='ToFloat')
batch_yy = batch_y
if isOneHot:
batch_yy = tf.one_hot(batch_y, 10, 1, 0, -1)
# sparse_labels = tf.reshape(batch_y, [batch_size, 1])
# indices = tf.reshape(tf.range(batch_size), [batch_size, 1])
# concated = tf.concat(axis=1, values=[indices, sparse_labels])
# num_classes = 10
# dense_labels = tf.sparse_to_dense(concated,
# [batch_x.get_shape()[0], num_classes],
# 1.0, 0.0)
print("get data...")
return batch_x, batch_yy
# tf Graph input
def run_training():
with tf.Graph().as_default():
global_step = tf.get_variable(
'global_step', [],
initializer=tf.constant_initializer(0), trainable=False)
num_batches_per_epoch = (train_set.num_examples_per_epoch() /
batch_size)
decay_steps = int(num_batches_per_epoch * 30.0)
lr = tf.train.exponential_decay(initial_learning_rate,
global_step,
decay_steps,
learning_rate_decay_factor,
staircase=True)
optimizer = tf.train.RMSPropOptimizer(lr, RMSPROP_DECAY,
momentum=RMSPROP_MOMENTUM,
epsilon=RMSPROP_EPSILON)
variable_averages = tf.train.ExponentialMovingAverage(
MOVING_AVERAGE_DECAY, global_step)
# Another possibility is to use tf.slim.get_variables().
variables_to_average = (tf.trainable_variables() +
tf.moving_average_variables())
# images,labels=mnist.train.next_batch(batch_size)
# images=tf.reshape(images, [batch_size, 28, 28])
# labels= tf.one_hot(labels, 10, 1, 0, -1)
images, labels = data_inputs(True, True)
neual_nets = tf.contrib.rnn.MultiRNNCell(
[lstm() for _ in range(num_layers)], state_is_tuple=True)
init_state=neual_nets.zero_state(batch_size, tf.float32)
output_, state = tf.nn.dynamic_rnn(neual_nets, images, dtype=tf.float32,initial_state=init_state)
final_state=state
output = tf.transpose(output_, [1, 0, 2])
last = tf.gather(output, int(output.get_shape()[0]) - 1)
# outputs = tf.reshape(tf.concat(axis=1, values=output), [-1, n_hidden]) # 100*300
softmax_w = tf.get_variable(
"softmax_w", [n_hidden, n_classes], dtype=tf.float32) # 300*10000
softmax_b = tf.get_variable("softmax_b", [n_classes], dtype=tf.float32) # 10000
logits = tf.nn.softmax(tf.matmul(last, softmax_w) + softmax_b)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels))
grads = optimizer.compute_gradients(cost)
for grad, var in grads:
if grad is not None:
tf.summary.histogram(var.op.name + '/gradients', grad)
apply_gradient_op=optimizer.apply_gradients(grads, global_step=global_step)
variables_averages_op = variable_averages.apply(variables_to_average)
train_op = tf.group(apply_gradient_op, variables_averages_op)
tf.summary.scalar('loss', cost)
tf.summary.scalar('global_step', global_step)
#train_op_2 = optimizer.minimize(cost)
train_mistakes = tf.not_equal(tf.argmax(labels, 1), tf.argmax(logits, 1))
train_accuracy_op = tf.reduce_mean(tf.cast(train_mistakes, tf.float32))
tf.summary.scalar('train_accuracy', train_accuracy_op)
######################################################
tf.get_variable_scope().reuse_variables()
valid_images, valid_labels = data_inputs(False, True)
valid_output_, _ = tf.nn.dynamic_rnn(neual_nets, valid_images, dtype=tf.float32)
valid_output = tf.transpose(valid_output_, [1, 0, 2])
valid_last = tf.gather(valid_output, int(valid_output.get_shape()[0]) - 1)
valid_logits = tf.nn.softmax(tf.matmul(valid_last, softmax_w) + softmax_b)
valid_cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=valid_logits, labels=valid_labels))
tf.summary.scalar('valid loss', valid_cost)
valid_mistakes = tf.not_equal(tf.argmax(valid_labels, 1), tf.argmax(valid_logits, 1))
valid_accuracy_op = tf.reduce_mean(tf.cast(valid_mistakes, tf.float32))
tf.summary.scalar('valid_accuracy', valid_accuracy_op)
tf.summary.scalar('learning_rate', lr)
tf.summary.scalar("batch size", batch_size)
for var in tf.trainable_variables():
tf.summary.histogram(var.op.name, var)
summary_op = tf.summary.merge_all()
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess = tf.Session()
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
summary_writer = tf.summary.FileWriter(
FLAGS.train_dir,
graph=sess.graph)
try:
step = 0
start_time = time.time()
state=sess.run(init_state)
while not coord.should_stop():
feed_dict = {}
for i, (c, h) in enumerate(init_state):
print(type(c),c.shape)
feed_dict[c] = state[i].c
feed_dict[h] = state[i].h
_, loss_value,state= sess.run([train_op, cost,final_state],feed_dict)
duration = time.time() - start_time
# Print an overview fairly often.
if step % 100 == 0:
print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,
duration))
acc = sess.run(train_accuracy_op)
print("Accuracy is:", acc)
valid_acc = sess.run(valid_accuracy_op)
print("Validation is:", valid_acc)
summary_str = sess.run(summary_op)
summary_writer.add_summary(summary_str, step)
step += 1
except tf.errors.OutOfRangeError:
print('Done training')
finally:
# When done, ask the threads to stop.
coord.request_stop()
# Wait for threads to finish.
coord.join(threads)
sess.close()
# Define weights
def lstm():
return tf.contrib.rnn.LSTMCell(
n_hidden, forget_bias=0.0, state_is_tuple=True)
def main(_):
run_training()
if __name__ == '__main__':
tf.app.run(main=main)
<file_sep>'''
Created on Apr 3, 2017
@author: dan
'''
import sys
from keras import backend as K
import keras
from keras.callbacks import ReduceLROnPlateau, CSVLogger
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Dense, Dropout, Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.core import Activation
from keras.layers.pooling import MaxPooling1D
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from keras.utils.vis_utils import plot_model
from digits import DigitData
import image_processing
from keras_data import Manualeval
import keras_data
import numpy as np
import tensorflow as tf
import tfboard
from scipy.misc import imsave
batch_size = 50
num_classes = 10
epochs = 20
image_size = 64
(x_train, y_train), (x_valid, y_valid), (x_test, y_test) = keras_data.get_data(distorted=True, imageSize=image_size, isValid=False, isWhole=True)
print("train:", x_train.shape, y_train.shape)
print("valid:", x_valid.shape, y_valid.shape)
print("test:", x_test.shape, y_test.shape)
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
y_valid = keras.utils.to_categorical(y_valid, num_classes)
model = Sequential()
model.add(Conv1D(40, 3,
activation='relu', input_shape=(64, 64)))
model.add(Conv1D(60, 5, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(LSTM(1000))
model.add(Dense(num_classes, kernel_initializer=keras.initializers.RandomUniform(minval=-0.05, maxval=0.05, seed=None)))
model.add(Activation("softmax"))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.RMSprop(lr=1e-4),
metrics=['accuracy'])
plot_model(model, show_shapes=True, to_file='model_cnn-lstm_shapes.png')
print('Train...')
# tensorbord=tfboard.TensorBoard(log_dir='logs_cnn_lstm', histogram_freq=1, write_graph=True, write_images=False)
reduce_lr = ReduceLROnPlateau(monitor='acc', factor=0.2, patience=3, min_lr=0.00001, verbose=1)
csv_logger = CSVLogger('training_cnn_lstm.log')
me = Manualeval(model, x_test, y_test)
model.fit(x_train, y_train,
batch_size=batch_size,
shuffle=True,
verbose=2,
epochs=epochs,
validation_data=(x_valid, y_valid), callbacks=[me, csv_logger, reduce_lr])
score, acc = model.evaluate(x_test, y_test, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)
#(_, _), (_, _), (x_test, y_test) = keras_data.get_data(isValid=False)
model2_1 = Sequential()
model2_1.add(Conv1D(40, 3,
activation='relu', input_shape=(64, 64),weights=model.layers[0].get_weights()))
model2_1.add(Conv1D(60, 5, activation='relu',weights=model.layers[1].get_weights()))
model2_1.add(MaxPooling1D(pool_size=2,weights=model.layers[2].get_weights()))
model2_1.add(LSTM(1000,weights=model.layers[3].get_weights()))
rst_=model2_1.predict(x_test, batch_size, verbose=1)
print(rst_.shape)
for i,features in enumerate(rst_):
imsave(str(np.argmax(y_test,axis=-1)[i])+'_cnn_lstm_features.jpg',features.reshape(25,40))
rst = model.predict(x_test, batch_size, verbose=1)
pr_result = np.argmax(rst, axis=-1)
tr_result = np.argmax(y_test,axis=-1)#np.argmax(y_test,axis=-1)
bolrst = np.equal(tr_result, pr_result)
for i, bol in enumerate(bolrst):
if not bol:
# print(x_test[i].shape)
imsave(str(i)+'_cnnlstm_T:'+str(tr_result[i]) + '_P:'+str(pr_result[i]) + '.jpg', x_test[i])
<file_sep>This is a digits recognition experiment
1. Install tensorflow
2. You also need an linux command: `convert a.tiff a.png` <file_sep>'''
Created on Apr 5, 2017
@author: dan
'''
import sys
from keras.callbacks import Callback
from digits import DigitData
import image_processing
import numpy as np
import tensorflow as tf
# input image dimensions
train_set = DigitData(subset="train")
test_set = DigitData(subset="validation")
whole_set = DigitData("all")
# the data, shuffled and split between train and test sets
def get_data(distorted=False, imageSize=64, isValid=True, isWhole=False):
train_size = 9000
test_size = 1000
images, labels = image_processing.batch_inputs(train_set, train_size, True, imageSize, 1, 1)
imagess, labelss = image_processing.batch_inputs(test_set, test_size, True, imageSize, 1, 1)
if isWhole:
train_size = 10000
image_all, labels_all = image_processing.batch_inputs(whole_set, train_size, True, imageSize, 1, 1)
image_train = image_all
labels_train = labels_all
if distorted:
images_all_d, labels_all_d = image_processing.distorted_inputs(whole_set, train_size, imageSize, 1)
image_train = tf.concat([image_all, images_all_d], 0)
labels_train = tf.concat([labels_all, labels_all_d], 0)
train_size = train_size * 2
image_train = tf.image.rgb_to_grayscale(image_train)
image_train = tf.reshape(image_train, [train_size, imageSize, imageSize])
image_test = labels_test = None
else:
if distorted:
images_d, labels_d = image_processing.distorted_inputs(train_set, train_size, imageSize, 1)
image_train = tf.concat([images, images_d], 0)
labels_train = tf.concat([labels, labels_d], 0)
image_train = tf.image.rgb_to_grayscale(image_train)
train_size = train_size * 2
image_train = tf.reshape(image_train, [train_size, imageSize, imageSize])
images_v, labels_v = image_processing.distorted_inputs(test_set, test_size, imageSize, 1)
image_test = tf.concat([imagess, images_v], 0)
labels_test = tf.concat([labelss, labels_v], 0)
image_test = tf.image.rgb_to_grayscale(image_test)
test_size = test_size * 2
image_test = tf.reshape(image_test, [test_size, imageSize, imageSize])
else:
labels_train = labels
image_train = tf.image.rgb_to_grayscale(images)
image_train = tf.reshape(image_train, [train_size, imageSize, imageSize])
labels_test = labelss
image_test = tf.image.rgb_to_grayscale(imagess)
image_test = tf.reshape(image_test, [test_size, imageSize, imageSize])
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
(x_train, y_train) = sess.run([image_train, labels_train])
if not image_test == None:
(x_test, y_test) = sess.run([image_test, labels_test])
coord.request_stop()
coord.join(threads)
sess.close()
if isWhole:
# return shuffled list
sf = zip(x_train, y_train)
np.random.shuffle(sf)
X, Y = zip(*sf)
x_train = list(X)[0:train_size - 2000]
x_test = list(X)[train_size - 2000:train_size]
y_train = list(Y)[0:train_size - 2000]
y_test = list(Y)[train_size - 2000:train_size]
return (np.array(x_train), np.array(y_train)), (np.array(x_test), np.array(y_test)), (np.array(x_test), np.array(y_test))
if isValid:
return (x_train[0:train_size - 2000], y_train[0:train_size - 2000]), (x_train[train_size - 2000:train_size], y_train[train_size - 2000:train_size]), (x_test, y_test)
else:
return (x_train, y_train), (x_test, y_test), (x_test, y_test)
class Manualeval(Callback):
'''
Add test accuracy at epoch end.
'''
def __init__(self, model, x_test, y_test):
super(Manualeval, self).__init__()
self.x_test = x_test
self.y_test = y_test
self.model = model
def on_epoch_end(self, epoch, logs=None):
print(logs.items())
score = self.manual_eval()
logs["test_acc"] = score[1]
logs["test_loss"] = score[0]
self.manual_eval()
def manual_eval(self):
score = self.model.evaluate(self.x_test, self.y_test, verbose=2, batch_size=len(self.x_test))
print('Test loss:', score[0])
print('Test accuracy:', score[1])
return score
<file_sep>./data_preprocess.sh ../data ../data/SampleDigits.tar.gz
<file_sep>python "$1" \
--train_directory="../data/raw-data/train" \
--validation_directory="../data/raw-data/validation" \
--output_directory="../data/" \
--labels_file="../data/raw-data/labels.txt"
<file_sep>OUTPUT_DIRECTORY=data
TRAIN_DIRECTORY=${OUTPUT_DIRECTORY}/raw-data/train
VALIDATION_DIRECTORY=${OUTPUT_DIRECTORY}/raw-data/validation
LABELS_FILE=${OUTPUT_DIRECTORY}/raw-data/labels.txt
cd inception
WORK_DIR=scripts/
BUILD_SCRIPT="${WORK_DIR}/build_image_data.py"
"${BUILD_SCRIPT}" \
--train_directory="${TRAIN_DIRECTORY}" \
--validation_directory="${VALIDATION_DIRECTORY}" \
--output_directory="${OUTPUT_DIRECTORY}" \
--labels_file="${LABELS_FILE}"
<file_sep>'''
Created on Apr 9, 2017
@author: dan
'''
from __future__ import print_function
from collections import Counter
import random
import sys, os
import threading
import fire
from keras import backend as K
from keras import initializers
import keras
from keras.callbacks import Callback, ReduceLROnPlateau, CSVLogger
from keras.engine.topology import Input
from keras.engine.training import Model
from keras.layers import Dense, Activation, TimeDistributed, Embedding
from keras.layers import LSTM, GRU, Dropout
from keras.layers import SimpleRNN
from keras.models import Sequential
from keras.optimizers import RMSprop
from keras.utils.vis_utils import plot_model
from scipy.misc import imsave
from scipy.stats._discrete_distns import logser
from sklearn.cluster import KMeans
from digits import DigitData
import image_processing
from keras_data import Manualeval
import keras_data
import numpy as np
import tensorflow as tf
import tfboard
# from sklearn.model_selection import StratifiedKFold
batch_size = 50
num_classes = 10
epochs = 20
train_size = 9000
test_size = 1000
image_size = 64
# input image dimensions
img_rows, img_cols = 64, 64
(x_train, y_train), (x_valid, y_valid), (x_test, y_test) = keras_data.get_data(distorted=False, imageSize=image_size, isValid=False, isWhole=True)
print("train:", x_train.shape, y_train.shape)
print("valid:", x_valid.shape, y_valid.shape)
print("test:", x_test.shape, y_test.shape)
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# convert class vectors to binary class matrices
x_train = np.reshape(x_train, (len(x_train), 64 * 64))
x_valid = np.reshape(x_valid, (len(x_valid), 64 * 64))
x_test = np.reshape(x_test, (len(x_test), 64 * 64))
kmeans = KMeans(n_clusters=10, random_state=0).fit(x_train)
print(kmeans.labels_)
label_dic={}
for i,l in enumerate(kmeans.labels_):
if not l in label_dic:
label_dic[l]=np.zeros((10,1))
label_dic[l][y_train[i]]+=1
#calculate misclassification
for j in label_dic.keys():
cluster_label=np.argmax(label_dic[j])#true label
wrong=0
for l,k in enumerate(label_dic[j]):
if l==cluster_label:#skip the right one
continue
wrong+=k #calculate the amount of wrong
r=str(label_dic[j].T.tolist()[0])
print(str(1-wrong/np.sum(label_dic[j]))+','+r)
#kmeans.predict(rst[900:1000])
| d772ac78f2053e7fd81c1a85eab58499a17ea605 | [
"Markdown",
"Python",
"Shell"
] | 15 | Python | Cyber-Neuron/AI_Assignment_Project | 3969584f61a880bdd8dd9339567670229d4b797d | 96d085f524cd2e806d0906460a448bc57fc44b66 |
refs/heads/master | <repo_name>Diego-r-pereira/SOME-2020<file_sep>/Hito2/Splash/app/src/main/java/com/diego/splashscreentome/MainActivity.java
package com.diego.splashscreentome;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private LinearLayout llLogo, llTextWelcome, calculadora;
private Button btSumar;
private EditText text1, text2;
private TextView respuesta;
private Animation animTextWelcome;
private Animation animTextCalculadora;
private Animation animButon;
private String v1, v2;
private Integer res;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeAnimation();
initializeComponents();
createAnimationForLogo();
}
private void initializeComponents(){
llLogo = (LinearLayout) findViewById(R.id.LinearLayoutLogo);
llTextWelcome = (LinearLayout) findViewById(R.id.linerLayoutTextSplash);
calculadora = (LinearLayout) findViewById(R.id.linerLayoutCalculator);
btSumar = (Button) findViewById(R.id.btSum);
btSumar.setOnClickListener(this);
text1 = (EditText) findViewById(R.id.etNumber1);
text2 = (EditText) findViewById(R.id.etNumber2);
respuesta = (TextView) findViewById(R.id.tvResult);
}
public void initializeAnimation() {
animTextWelcome = AnimationUtils.loadAnimation(this, R.anim.animation_for_text_welcome);
animTextCalculadora = AnimationUtils.loadAnimation(this, R.anim.animation_fro_calculator);
animButon = AnimationUtils.loadAnimation(this, R.anim.animation_for_button);
}
private void createAnimationForLogo(){
llLogo.animate().translationY(-900).setDuration(1200).setStartDelay(300);
llTextWelcome.startAnimation(animTextWelcome);
calculadora.setVisibility(View.VISIBLE);
calculadora.startAnimation(animTextCalculadora);
btSumar.startAnimation(animButon);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btSum:
v1 = text1.getText().toString();
v2 = text2.getText().toString();
res = Integer.parseInt(v1) + Integer.parseInt(v2);
respuesta.setText(""+res);
break;
}
}
}<file_sep>/Hito4/EvaluacionHito4/app/src/main/java/com/diego/reciclerview/MainActivity.java
package com.diego.reciclerview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.diego.reciclerview.Adapter.RVAdapter;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RVAdapter rvAdapter, rvPlaylist;
private ArrayList<String> imgNames = new ArrayList<>();
// private ArrayList<Integer> imagesID = new ArrayList<>();
private ArrayList<String> imagesID = new ArrayList<>();
private ArrayList<String> musicsID = new ArrayList<>();
private ArrayList<String> playMusic = new ArrayList<>();
private final String imgURL = "V4OgA4O,yB3d2qH,9jMbaX2,rYndmdq,sypYnSP,HBeK1ot,YCqbt8r,eLk31XX," +
"4ZHp7FO,XzffKgy,DJabk5C";
private final String imgName = "Playlist 1,Playlist 2,Playlist 3,Playlist 4,Playlist 5," +
"Playlist 6,Playlist 7,Playlist 8,Playlist 9,Playlist 10,Playlist 11";
private final String musics = "Music 1,Music 2,Music 3,Music 4,Music 5,Music 6,Music 7,Music 8," +
"Music 9,Music 10,Music 11,Music 12";
// private final String playURL = "asdfasdf,asdfasdf,asdfasd";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initIMagebitMaps();
initRecyclerView();
}
public void initIMagebitMaps(){
imagesID.addAll(Arrays.asList(imgURL.split(",")));
imgNames.addAll(Arrays.asList(imgName.split(",")));
musicsID.addAll(Arrays.asList(musics.split(",")));
// playMusic.addAll(Arrays.asList(playURL.split(",")));
}
public void initRecyclerView(){
recyclerView = findViewById(R.id.rvContainer);
rvAdapter = new RVAdapter(this, imgNames, imagesID);
recyclerView.setAdapter(rvAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
rvPlaylist = new RVAdapter(this, musicsID, imagesID);
}
}
<file_sep>/Hito2/Splash/settings.gradle
rootProject.name='Splash Screen to me'
include ':app'
<file_sep>/Hito3/Onboarding/README.md
# Onboarding-Arduino-Library
Android Library to work on an Onboarding slides, so there is no need to build this from scratch, Thank me later.
<file_sep>/Hito4/EvaluacionHito4/settings.gradle
rootProject.name='ReciclerView'
include ':app'
<file_sep>/Hito3/DefensaHITO3/app/src/main/java/com/diego/defensahito3/App/ScientificCalculatorActivity.java
package com.diego.defensahito3.App;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.diego.defensahito3.R;
public class ScientificCalculatorActivity extends AppCompatActivity {
private TextView tvShowUser, tvShowApp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scientific_calculator);
initializeVariable();
}
public void initializeVariable() {
tvShowUser = findViewById(R.id.tvShowUserSci);
tvShowApp = findViewById(R.id.tvShowAppSci);
String username = getIntent().getStringExtra("USERNAME");
String getApp = getIntent().getStringExtra("SELECTAPP");
String msg = "Bienvenido: " + username;
String msg2 = "Esta es la aplicacion " + getApp;
tvShowUser.setText(msg);
tvShowApp.setText(msg2);
}
}
<file_sep>/README.md
# SOME-2020
File that contents all the content of "Sistemas Operativos Moviles y Embebidos"
<!-- My first working on Readme shit -->
# El orden de las carpetas es la siguiente:
* Carpeta inicial llamada SOME
* El Hito correspondiente
* Las actividades realizadas en el Hito
___

---
## HITO 2
* Calculadora/AndroidTest
* Hito2 <NAME> 2020
* Splash Screem
* Defensa Hito2.pdf
* Defensa Hito2.ppt

---
## HITO 3
* Defesa Hito3
* Onboarding
* Procesual
* Scientific Calculator
* Hito3 Tarea Final.docx
* Hito3 Tarea Final.pdf

---
## HITO 4
* Evaluacion Hito4
* Recicler View

---
### The code
This code has been given for your use so Enjoy IT and have fun!!!
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## License & copyright
Lincense by [MIT](https://choosealicense.com/licenses/mit/) open source
## Contributors
<NAME><file_sep>/OnboardingAppLibrary/README.md
<!-- My first working on Readme shit -->
# Onboarding-Arduino-Library
Android Library to work on an Onboarding slides, so there is no need to build this from scratch, Thank me later.
___
# Onboarding
* *Onboarding es una libreria que te permitira realizar slides entre fragments con el uzo de un adapter.*
* Esto consiste en que veras en la **pantalla un fragment al que puedes cambiar** con dos imagenes en la arte inferior para navegar entre las pantallas atras o adelante
---
## Installation
> Use the the web page [jitpack](https://jitpack.io/) to use the platform.
Lo primero que tienes que hacer es tener listo el proyecto que quieres volver
libreria o crear uno desde cero.
---
### Convert an app module to a library module
This tutorial is part of [Developer](https://developer.android.com/studio/projects/android-library) site of Android
If you have an **existing app module** with all the code you want to reuse, you can **turn it into a library module** as follows:
1. Open the module-level build.gradle file.
1. Delete the line for the applicationId. Only an Android app module can define this.
1. At the top of the file, you should see the following:
> apply plugin: 'com.android.application'
Change it to the following:
> apply plugin: 'com.android.library'
Save the file and click File > Sync Project with Gradle Files.
---
After that we have to set our proyect in **JITPACK**, to acommplish that our link of the proyect in Github is needed, we paste it on the following space:

_After that let's settle a release_

This is for track the version of our repository, which is worth for **JITPACK**

After that we got to push over the button named **Look up** as follow:

And under that section you can find the way to put this on your own module:

---
## Now that everything is settle about the configuration is time to use the library
I'll show you the main code and you can see the main events to put on your own
```android
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializeComponents
_initializeComponents();
//initializeAdapter
_initializeFragmentAdapter();
}
```
```android
public void _initializeComponents(){
viewPagerContainer = findViewById(R.id.viewPagerContainer);
}
```
```android
public void _initializeFragmentAdapter() {
OnboardingAdapter adapter = new OnboardingAdapter(getSupportFragmentManager());
viewPagerContainer.setAdapter(adapter);
}
```
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
## License & copyright
Lincense by [MIT](https://choosealicense.com/licenses/mit/) open source
## Contributors
<NAME><file_sep>/Hito2/Hito2RojasDiego2020/settings.gradle
rootProject.name='<NAME> 2020'
include ':app'
<file_sep>/OnboardingAppLibrary/settings.gradle
rootProject.name='OnboardingApp'
include ':app'
<file_sep>/Hito4/EvaluacionHito4/app/src/main/java/com/diego/reciclerview/Adapter/ViewHolder.java
package com.diego.reciclerview.Adapter;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.diego.reciclerview.R;
import de.hdodenhof.circleimageview.CircleImageView;
public class ViewHolder extends RecyclerView.ViewHolder {
private RelativeLayout rlContainer;
private CircleImageView circleImage, circlePlay, circlePause, circleStop;
private TextView tvImage, tvPlay;
private Button btnListen;
public RelativeLayout getRlContainer() {
return rlContainer;
}
public CircleImageView getCircleImage() {
return circleImage;
}
public CircleImageView getCirclePlay(){
return circlePlay;
}
public CircleImageView getCirclePause(){
return circlePause;
}
public CircleImageView getCircleStop(){
return circleStop;
}
public TextView getTvImage() {
return tvImage;
}
public TextView getTvPlay() {
return tvPlay;
}
public Button getBtnListen(){
return btnListen;
}
public ViewHolder(View itemView) {
super(itemView);
initializeComponents(itemView);
}
private void initializeComponents(View itemView){
rlContainer = itemView.findViewById(R.id.rlListItem);
circleImage = itemView.findViewById(R.id.circleImageViewItem);
circlePlay = itemView.findViewById(R.id.circleIVplay);
circlePause = itemView.findViewById(R.id.circleIVpause);
circleStop = itemView.findViewById(R.id.circleIVStop);
tvPlay = itemView.findViewById(R.id.tvPlay);
tvImage = itemView.findViewById(R.id.tvImage);
btnListen = itemView.findViewById(R.id.buttonListen);
}
}<file_sep>/Hito3/DefensaHITO3/settings.gradle
rootProject.name='Defensa HITO 3'
include ':app'
<file_sep>/Hito3/Onboarding/app/src/main/java/com/diego/onboardingapp/Onboarding/LoginFragment.java
package com.diego.onboardingapp.Onboarding;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.diego.onboardingapp.App.ScientificCalculator;
import com.diego.onboardingapp.R;
/**
* A simple {@link Fragment} subclass.
*/
public class LoginFragment extends Fragment implements View.OnClickListener {
private TextView textBack;
private EditText etLogin, etPassword;
private Button buttonLogin;
private ViewPager viewPager;
private View view;
public LoginFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
// return inflater.inflate(R.layout.fragment_login, container, false);
initializeInflater(inflater, container);
initializeComponents();
return view;
}
public void initializeInflater(LayoutInflater inflater, ViewGroup container){
view = inflater.inflate(R.layout.fragment_login, container, false);
}
public void initializeComponents(){
viewPager = getActivity().findViewById(R.id.viewPagerContainer);
etLogin = view.findViewById(R.id.etEmail);
etPassword = view.findViewById(R.id.etPassword);
textBack = view.findViewById(R.id.textPrevLogin);
textBack.setOnClickListener(this);
buttonLogin = view.findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.textPrevLogin:
viewPager.setCurrentItem(0);
break;
case R.id.buttonLogin:
String username = etLogin.getText().toString();
String password = etPassword.getText().toString();
if (!checkValues(username, password)){
Toast.makeText(getActivity(), "Please add user and password",
Toast.LENGTH_SHORT).show();
}else {
Intent intent = new Intent(getActivity(), ScientificCalculator.class);
intent.putExtra("USERNAME", username);
intent.putExtra("PASSWORD", <PASSWORD>);
startActivity(intent);
getActivity().finish();
}
break;
}
}
public boolean checkValues (String username, String password){
boolean isValid = true;
if (username.equals("") || password.equals("")){
isValid = false;
}
return isValid;
}
}<file_sep>/Hito5/TestLibrary/settings.gradle
rootProject.name='TestLibrary'
include ':app'
| 30f6108ed61d7baaededa6b87814089c8c2078b2 | [
"Markdown",
"Java",
"Gradle"
] | 14 | Java | Diego-r-pereira/SOME-2020 | eaf70cc8d2837aa3fc458491edf2e16fbe542a16 | 201b7124c307094ce28ac1c0efe7ed660eec6183 |
refs/heads/main | <file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class TemperatureSummary(
@SerializedName("Past12HourRange")
val past12HourRange: Past12HourRange,
@SerializedName("Past24HourRange")
val past24HourRange: Past24HourRange,
@SerializedName("Past6HourRange")
val past6HourRange: Past6HourRange
)<file_sep>package com.example.sportsadvisor
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.sportsadvisor.model.HomeFragment
import com.example.sportsadvisor.model.ScoreActivity
import com.example.sportsadvisor.model.SettingsFragment
import com.example.sportsadvisor.model.WeatherFragment
import com.google.gson.Gson
import io.realm.Realm
import io.realm.mongodb.App
import io.realm.mongodb.AppConfiguration
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.MediaType.Companion.toMediaType
class MainActivity : AppCompatActivity() {
var courseCode:String = "208539"
//navbar
//custom nav drawer adapted from:https://johncodeos.com/how-to-create-a-custom-navigation-drawer-in-android-using-kotlin/
lateinit var drawerLayout: DrawerLayout
private lateinit var adapter: NavigationRVAdapter
private var items = arrayListOf(
NavigationItemModel(R.drawable.home, "Home"),
NavigationItemModel(R.drawable.weather, "Weather"),
NavigationItemModel(R.drawable.scores, "Scores"),
NavigationItemModel(R.drawable.profile, "User History"),
NavigationItemModel(R.drawable.settings, "Settings")
)
lateinit var app: App
lateinit var uiThreadRealm: Realm
val gson = Gson()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Initiate a link to the server
Realm.init(this)
val appID = "sportsadvisor-gztkm"
app = App(AppConfiguration.Builder(appID).build())
// gson for parsing data
//set drawer layout
drawerLayout = findViewById(R.id.drawer_layout)
// Set the toolbar
setSupportActionBar(activity_main_toolbar)
// Setup Recyclerview's Layout
navigation_rv.layoutManager = LinearLayoutManager(this)
navigation_rv.setHasFixedSize(true)
val sp = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val displayName = sp.getString("displayName", "")
val course = sp.getString("course", "")
//listens for user navigating pages, updates view and UI for user when interacted with
navigation_rv.addOnItemTouchListener(RecyclerTouchListener(this, object : ClickListener {
override fun onClick(view: View, position: Int) {
val bundle = Bundle()
val course = sp.getString("course", "")
val displayName = sp.getString("displayName", "")
when (position) {
0 -> {
refreshCurrentApp()
if(course == "Oughterard GC") {
courseCode = "208587"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Galway GC") {
courseCode = "208539"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Galway Bay GC") {
courseCode = "3549260"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Bearna GC") {
courseCode = "208553"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Glenlo Abbey GC") {
courseCode = "208539"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Connemara Championship Links") {
courseCode = "1651911"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Athenry GC") {
courseCode = "208546"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Gort GC") {
courseCode = "208564"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Loughrea GC") {
courseCode = "208542"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Tuam GC") {
courseCode = "208543"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Dunmore Demesne GC") {
courseCode = "208562"
WeatherDataProcessor.callCurrentData(courseCode)
}
else if(course == "Mountbellew GC") {
courseCode = "3545589"
WeatherDataProcessor.callCurrentData(courseCode)
}
bundle.putString("fragmentName", "The Average Weather today for $course")
bundle.putString("fullList", WeatherDataProcessor.hourlyListString)
// # Home Fragment
val homeFragment = HomeFragment()
homeFragment.arguments = bundle
supportFragmentManager.beginTransaction().apply {
//fragment lives within activity and becomes the new view
replace(R.id.activity_main_content_id, homeFragment).commit()
}
}
1 -> {
refreshHourlyApp()
if(course == "Oughterard GC") {
courseCode = "208587"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Galway GC") {
courseCode = "208539"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Galway Bay GC") {
courseCode = "3549260"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Bearna GC") {
courseCode = "208553"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Glenlo Abbey GC") {
courseCode = "208539"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Connemara Championship Links") {
courseCode = "1651911"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Athenry GC") {
courseCode = "208546"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Gort GC") {
courseCode = "208564"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Loughrea GC") {
courseCode = "208542"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Tuam GC") {
courseCode = "208543"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Dunmore Demesne GC") {
courseCode = "208562"
WeatherDataProcessor.callHourlyData(courseCode)
}
else if(course == "Mountbellew GC") {
courseCode = "3545589"
WeatherDataProcessor.callHourlyData(courseCode)
}
// # Weather Fragment
bundle.putString("courseName", "Next 12 Hours of Weather for $course")
bundle.putString("fullList", WeatherDataProcessor.hourlyListString)
val weatherFragment = WeatherFragment()
weatherFragment.arguments = bundle
supportFragmentManager.beginTransaction().apply {
//fragment lives within activity and becomes the new view
replace(R.id.activity_main_content_id, weatherFragment).commit()
}
}
2 -> {
// #Score Activity
val intent = Intent(this@MainActivity, ScoreActivity::class.java)
startActivity(intent)
}
3 -> {
// # Profile Activity
val intent = Intent(this@MainActivity, UserHistory::class.java)
startActivity(intent)
}
4 -> {
// # Settings Fragment
val bundle = Bundle()
bundle.putString("fragmentName", "Settings Fragment")
val settingsFragment = SettingsFragment()
supportFragmentManager.beginTransaction().apply {
replace(R.id.activity_main_content_id, settingsFragment).commit()
}
}
}
//updates adapter with curretn position selected
updateAdapter(position)
Handler(Looper.getMainLooper()).postDelayed({
drawerLayout.closeDrawer(GravityCompat.START)
}, 200)
}
}))
// Update Adapter with item data and highlight the default menu item ('Home' Fragment)
updateAdapter(0)
// Set 'Home' as the default fragment when the app starts
// This code is only run oce when application starts
refreshCurrentApp()
val bundle = Bundle()
WeatherDataProcessor.callCurrentData(courseCode)
bundle.putString("fragmentName", "Weather for Galway GC")
bundle.putString("fullList", WeatherDataProcessor.hourlyListString)
val homeFragment = HomeFragment()
homeFragment.arguments = bundle
supportFragmentManager.beginTransaction().apply {
replace(R.id.activity_main_content_id, homeFragment).commit()
}
// Close the soft keyboard when you open or close the Drawer
val toggle: ActionBarDrawerToggle = object : ActionBarDrawerToggle(
this,
drawerLayout,
activity_main_toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
override fun onDrawerClosed(drawerView: View) {
// Triggered once the drawer closes
super.onDrawerClosed(drawerView)
try {
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus?.windowToken, 0)
} catch (e: Exception) {
e.stackTrace
}
}
override fun onDrawerOpened(drawerView: View) {
// Triggered once the drawer opens
super.onDrawerOpened(drawerView)
try {
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
} catch (e: Exception) {
e.stackTrace
}
}
}
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
navigation_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary))
}
// adapted from https://www.youtube.com/watch?v=oOIoRR0AiGo
private fun refreshHourlyApp() {
val sp = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val bundle = Bundle()
val course = sp.getString("course", "")
swipeToRefresh.setOnRefreshListener {
Toast.makeText(this, "Page Refreshed!", Toast.LENGTH_SHORT).show()
swipeToRefresh.isRefreshing = false
WeatherDataProcessor.callHourlyData(courseCode)
bundle.putString("courseName", "Next 12 Hours of Weather for $course")
bundle.putString("fullList", WeatherDataProcessor.hourlyListString)
val weatherFragment = WeatherFragment()
weatherFragment.arguments = bundle
supportFragmentManager.beginTransaction().apply {
replace(R.id.activity_main_content_id, weatherFragment).commit()
}
}
}
// adapted from https://www.youtube.com/watch?v=oOIoRR0AiGo
private fun refreshCurrentApp() {
val sp = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val bundle = Bundle()
val course = sp.getString("course", "")
swipeToRefresh.setOnRefreshListener {
Toast.makeText(this,"Page Refreshed!", Toast.LENGTH_SHORT).show()
swipeToRefresh.isRefreshing = false
WeatherDataProcessor.callCurrentData(courseCode)
bundle.putString("fragmentName", "The Average Weather today for $course")
bundle.putString("fullList", WeatherDataProcessor.hourlyListString)
// # Home Fragment
val homeFragment = HomeFragment()
homeFragment.arguments = bundle
supportFragmentManager.beginTransaction().apply {
replace(R.id.activity_main_content_id, homeFragment).commit()
}
}
}
// will update ui to reflect user changing tab on drawer
private fun updateAdapter(highlightItemPos: Int) {
adapter = NavigationRVAdapter(items, highlightItemPos)
navigation_rv.adapter = adapter
adapter.notifyDataSetChanged()
}
companion object {
val MEDIA_TYPE_MARKDOWN = "text/x-markdown; charset=utf-8".toMediaType()
}
fun login(view: View) {
val login = Intent(this, LoginActivity::class.java)
startActivity(login)
}
fun register(view: View){
val reg = Intent(this, RegisterActivity::class.java)
startActivity(reg)
}
override fun onDestroy() {
super.onDestroy()
// the ui thread realm uses asynchronous transactions, so we can only safely close the realm
// when the activity ends and we can safely assume that those transactions have completed
uiThreadRealm.close()
app.currentUser()?.logOutAsync {
if (it.isSuccess) {
Log.v("QUICKSTART", "Successfully logged out.")
} else {
Log.e("QUICKSTART", "Failed to log out, error: ${it.error}")
}
}
}
}<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Pressure(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Visibility(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past18Hours(
@SerializedName("Imperial")
val imperial: ImperialXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXX
)<file_sep>(function(window, undefined) {
/*********************** START STATIC ACCESS METHODS ************************/
jQuery.extend(jimUtil, {
"loadScrollBars": function() {
jQuery(".s-abdc43e8-b1cb-4436-a4ae-524e2460d3a8 .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
jQuery(".s-24b25c6b-785b-4de3-a635-7aed43730986 .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
jQuery(".s-6c3c8fc1-447b-4383-9310-0b272b10aba5 .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
jQuery(".s-d12245cc-1680-458d-89dd-4f0d7fb22724 .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
jQuery(".s-db8fef49-ca00-4354-a7c9-c378277b6d48 .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
jQuery(".s-1c01cb94-d1dd-4ba9-93ee-0f7bfcbac4ae .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
jQuery(".s-ddd09d44-1c3a-418b-8427-567f505a6240 .ui-page").overscroll({ showThumbs:true, direction:'vertical', roundCorners:false, backgroundColor:'#333333', opacity:'0.7', thickness:'4'});
}
});
/*********************** END STATIC ACCESS METHODS ************************/
}) (window);<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past12HourRange(
@SerializedName("Maximum")
val maximum: Maximum,
@SerializedName("Minimum")
val minimum: Minimum
)<file_sep>package com.example.sportsadvisor.model
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.example.sportsadvisor.LoginActivity
import com.example.sportsadvisor.MainActivity
import com.example.sportsadvisor.R
import io.realm.mongodb.App
import io.realm.mongodb.AppConfiguration
import io.realm.mongodb.User
import kotlinx.android.synthetic.main.fragment_score.*
import kotlinx.android.synthetic.main.login_main.button
import org.bson.Document
import org.bson.types.ObjectId
import java.text.SimpleDateFormat
import java.util.*
class ScoreActivity : AppCompatActivity() {
private lateinit var userCourse: EditText
//playedCourse
override fun onCreate(savedInstanceState: Bundle?) {
var userID = ""
//user prefs allow us to access userID & player handicap saved in locally
val sp = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val displayName = sp.getString("displayName", "")
val handicap = sp.getString("handicap","")
userID = displayName.toString()
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_score)
//calculation will only haooen if all input fields are filled
button.setOnClickListener{
try {
//front 9 holes
front9par.text = "" + (hole1Par.text.toString().toInt() + hole2par.text.toString().toInt() + hole3par.text.toString().toInt() + hole4par.text.toString().toInt() + hole5par.text.toString().toInt() + hole6par.text.toString().toInt() + hole7par.text.toString().toInt() + hole8par.text.toString().toInt() + hole9par.text.toString().toInt()).toString()
front9Score.text = "" + (hole1Score.text.toString().toInt() + hole2Score.text.toString().toInt() + hole3Score.text.toString().toInt() + hole4Score.text.toString().toInt() + hole5Score.text.toString().toInt() + hole6Score.text.toString().toInt() + hole7Score.text.toString().toInt() + hole8Score.text.toString().toInt() + hole9Score.text.toString().toInt()).toString()
//back 9 holes
back9Par.text = "" + (hole10par.text.toString().toInt() + hole11par.text.toString().toInt() + hole12par.text.toString().toInt() + hole13par.text.toString().toInt() + hole14par.text.toString().toInt() + hole15par.text.toString().toInt() + hole16par.text.toString().toInt() + hole17par.text.toString().toInt() + hole18par.text.toString().toInt()).toString()
back9Score.text = "" + (hole10Score.text.toString().toInt() + hole11Score.text.toString().toInt() + hole12Score.text.toString().toInt() + hole13Score.text.toString().toInt() + hole14Score.text.toString().toInt() + hole15Score.text.toString().toInt() + hole16Score.text.toString().toInt() + hole17Score.text.toString().toInt() + hole18Score.text.toString().toInt()).toString()
//18 holes score
totalPar.text ="" + (front9par.text.toString().toInt() + back9Par.text.toString().toInt())
totalScore.text ="" + (front9Score.text.toString().toInt() + back9Score.text.toString().toInt())
//18 holes score with handicap taken into account
netPar.text= handicap.toString()
NettScore.text ="" + (totalScore.text.toString().toInt() - handicap.toString().toInt())
var tpar = Integer.parseInt(totalPar.text as String)
var npar = Integer.parseInt(netPar.text as String)
var nscore = Integer.parseInt(NettScore.text as String)
userCourse = findViewById(R.id.playedCourse)
var courseName = userCourse.text.toString()
/* Calling the function and sending the data generated from user input
* alongside the course name and the unique username the user generates in the settings page*/
sendData(tpar,npar,nscore,courseName,userID)
}catch (e:Exception){
println(e)
Toast.makeText(applicationContext, "error", Toast.LENGTH_LONG).show()
}
}
}
/*Function to send data from the Android Application to the MongoDB Database to be saved as a collection*/
fun sendData(parScore: Int, handicap: Int, nettScore: Int, courseName: String, userID: String)
{
// Saving the data received in the function call into local variables to be sent to the server
var par = parScore
var hand = handicap
var nett = nettScore
var coursename = courseName
var key = userID
//variables used to access the MongoDB Server
lateinit var app: App
var user: User? = null
val appID = "sportsadvisor-gztkm"
app = App(AppConfiguration.Builder(appID).build())
user = app.currentUser()
// service for MongoDB Atlas cluster containing custom user data
val mongoClient = user!!.getMongoClient("mongodb-atlas")
val mongoDatabase = mongoClient.getDatabase("Users")
val mongoCollection = mongoDatabase.getCollection("UserData")
//Getting the current time and date
val currentDate = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Date())
val currentTime = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date())
/*this block of code inserts the data we want to populate the database with into a new collection
on that database. Each append is a different field in the collection and the data is stored in 1 collection
containing everything that has been sent. The userID allows this collection to only be accessed by a user
who inputs that id into the settings page */
mongoCollection.insertOne(Document("UserData",user.id).append("_id", ObjectId()).append("date",currentDate)
.append("time",currentTime).append("course",coursename).append("parScore",par).append("handicap",hand)
.append("totalScore",nett).append("userID", key))
.getAsync { result ->
//An if else method used for debugging purposes
if (result.isSuccess) {
Log.v(
"EXAMPLE",
"Inserted custom user data document. _id of inserted document: ${result.get().insertedId}"
)
} else {
Log.e("EXAMPLE", "Unable to insert custom user data. Error: ${result.error}")
}
}
}
// Function used to return the user to the home page
fun homeClicked(view: View) {
val home = Intent(this, MainActivity::class.java)
startActivity(home)
}
}
<file_sep>package com.example.sportsadvisor.model
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.preference.PreferenceFragmentCompat
import com.example.sportsadvisor.R
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.prefs, rootKey)
Toast.makeText(context, "These are your settings", Toast.LENGTH_SHORT).show()
}
}
<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class ApparentTemperature(
@SerializedName("Imperial")
val imperial: Imperial,
@SerializedName("Metric")
val metric: Metric
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class currentConditionsItem(
@SerializedName("ApparentTemperature")
val apparentTemperature: ApparentTemperature,
@SerializedName("Ceiling")
val ceiling: Ceiling,
@SerializedName("CloudCover")
val cloudCover: Int,
@SerializedName("DewPoint")
val dewPoint: DewPoint,
@SerializedName("EpochTime")
val epochTime: Int,
@SerializedName("HasPrecipitation")
val hasPrecipitation: Boolean,
@SerializedName("IndoorRelativeHumidity")
val indoorRelativeHumidity: Int,
@SerializedName("IsDayTime")
val isDayTime: Boolean,
@SerializedName("Link")
val link: String,
@SerializedName("LocalObservationDateTime")
val localObservationDateTime: String,
@SerializedName("MobileLink")
val mobileLink: String,
@SerializedName("ObstructionsToVisibility")
val obstructionsToVisibility: String,
@SerializedName("Past24HourTemperatureDeparture")
val past24HourTemperatureDeparture: Past24HourTemperatureDeparture,
@SerializedName("Precip1hr")
val precip1hr: Precip1hr,
@SerializedName("PrecipitationSummary")
val precipitationSummary: PrecipitationSummary,
@SerializedName("PrecipitationType")
val precipitationType: Any,
@SerializedName("Pressure")
val pressure: Pressure,
@SerializedName("PressureTendency")
val pressureTendency: PressureTendency,
@SerializedName("RealFeelTemperature")
val realFeelTemperature: RealFeelTemperature,
@SerializedName("RealFeelTemperatureShade")
val realFeelTemperatureShade: RealFeelTemperatureShade,
@SerializedName("RelativeHumidity")
val relativeHumidity: Int,
@SerializedName("Temperature")
val temperature: Temperature,
@SerializedName("TemperatureSummary")
val temperatureSummary: TemperatureSummary,
@SerializedName("UVIndex")
val uVIndex: Int,
@SerializedName("UVIndexText")
val uVIndexText: String,
@SerializedName("Visibility")
val visibility: Visibility,
@SerializedName("WeatherIcon")
val weatherIcon: Int,
@SerializedName("WeatherText")
val weatherText: String,
@SerializedName("WetBulbTemperature")
val wetBulbTemperature: WetBulbTemperature,
@SerializedName("Wind")
val wind: Wind,
@SerializedName("WindChillTemperature")
val windChillTemperature: WindChillTemperature,
@SerializedName("WindGust")
val windGust: WindGust
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class PrecipitationSummary(
@SerializedName("Past12Hours")
val past12Hours: Past12Hours,
@SerializedName("Past18Hours")
val past18Hours: Past18Hours,
@SerializedName("Past24Hours")
val past24Hours: Past24Hours,
@SerializedName("Past3Hours")
val past3Hours: Past3Hours,
@SerializedName("Past6Hours")
val past6Hours: Past6Hours,
@SerializedName("Past9Hours")
val past9Hours: Past9Hours,
@SerializedName("PastHour")
val pastHour: PastHour,
@SerializedName("Precipitation")
val precipitation: Precipitation
)<file_sep>package com.example.sportsadvisor
import CurrentConditionsDataResponse.currentConditionsItem
import HourlyDataResponse.HourlyProcessedDataItem
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
object WeatherDataProcessor : AppCompatActivity() {
private var dataRetreive:String = ""
val gson = Gson()
var list: List<String> = ArrayList()
private var fullHourlyList = mutableListOf<String>()
var currentHourlyList = mutableListOf<String>()
var hourlyData:String = ""
var currentData:String = ""
var hourlyListString:String=""
var currentListString:String=""
// adapted from https://www.youtube.com/watch?v=53BsyxwSBJk&t=874s
// This function fetches the data from the API for the 12 hour data and invokes the savehourlyData if successful
private fun fetchHourlyJson(url: String): String {
// Fetch Request
println("Attempting to Fetch JSON")
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
var body = ""
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
println("Fetched JSON Data")
body = response.body?.string().toString()
saveHourlyData(body)
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute request")
}
})
return body
}
// adapted from https://www.youtube.com/watch?v=53BsyxwSBJk&t=874s
// This function fetches the data from the API for the current hour data and invokes the saveCurrentData if successful
private fun fetchCurrentJson(url: String): String {
// OKHTTP Fetch Request
println("Attempting to Fetch JSON")
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
var body = ""
client.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
println("Fetched JSON Data")
body = response.body?.string().toString()
saveCurrentData(body)
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute request")
}
})
return body
}
// function that when invoked passes data from the fetchHourlyData function and stores the data in Kotlin Data files
// to be outputted to the user
fun saveHourlyData(body: String){
fullHourlyList.clear()
hourlyListString = "";
dataRetreive = body
//println(dataRetreive)
// Adapted from https://www.youtube.com/watch?v=c_91kB4Tvg8
// gson object that stores all the JSON into Kotlin Data Files
// created Kotlin Data Class Files using JSON To Kotlin Class(JSONToKotlinClass) Plugin
val commentResponse = gson.fromJson(body,Array<HourlyProcessedDataItem>::class.java)
for (x in commentResponse.indices)
{
//data is stored to a string to be formatted
list = commentResponse[x].dateTime.split("T",":00+01:00")
hourlyData = list[1] + " " +
pad(commentResponse[x].rain.value) + " " +
pad(commentResponse[x].wind.speed.value) + " " +
pad(commentResponse[x].temperature.value) + " " +
pad(commentResponse[x].realFeelTemperature.value) +" " +
commentResponse[x].relativeHumidity +" " +
UserResults.checkHourlyResults(commentResponse[x].rain.value,
commentResponse[x].wind.speed.value,
commentResponse[x].temperature.value,
commentResponse[x].realFeelTemperature.value,
commentResponse[x].relativeHumidity,
commentResponse[x].isDaylight)
//this is then all stored in a list to be outputted to the user
fullHourlyList.add(hourlyData)
//println(fullList[x])
// the list is then converted back to a list to remove all brackets and punctuation from the list
hourlyListString += fullHourlyList[x] + "\n"
}
println(hourlyListString)
}
// function that when invoked passes data from the fetchCurrentData function and stores the data in Kotlin Data files
// to be outputted to the user
fun saveCurrentData(body: String){
currentHourlyList.clear()
hourlyListString = "";
//adapted from https://www.youtube.com/watch?v=c_91kB4Tvg8
//gson object that stores all the JSON into Kotlin Data Files
// created Kotlin Data Class Files using JSON To Kotlin Class(JSONToKotlinClass) Plugin
val commentResponse: List<currentConditionsItem> = gson.fromJson(body,Array<currentConditionsItem>::class.java).toList()
val currentTime = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date())
for (x in commentResponse.indices)
{
//data is stored to a string to be formatted
currentData = currentTime +" "+
pad(commentResponse[x].precip1hr.metric.value) + " " +
pad(commentResponse[x].wind.speed.metric.value) + " " +
pad(commentResponse[x].temperature.metric.value) + " " +
pad(commentResponse[x].realFeelTemperature.metric.value) +" " +
commentResponse[x].relativeHumidity +" " +
UserResults.checkHourlyResults(commentResponse[x].precip1hr.metric.value,
commentResponse[x].wind.speed.metric.value,
commentResponse[x].temperature.metric.value,
commentResponse[x].realFeelTemperature.metric.value,
commentResponse[x].relativeHumidity,
commentResponse[x].isDayTime)
//this is then all stored in a list to be outputted to the user
currentHourlyList.add(currentData)
//println(fullList[x])
// the list is then converted back to a list to remove all brackets and punctuation from the list
hourlyListString += currentHourlyList[x] + "\n"
}
println(hourlyListString)
}
//function that passes through the api call to the fetchHourlyJson using the course code set from the main activity
open fun callHourlyData(courseCode:String){
//val url = "https://dataservice.accuweather.com/forecasts/v1/hourly/12hour/"+courseCode+"?apikey=Gngag9jfLyY2fDDrLSr27EVYD1TarOiW&language=en-us&details=true&metric=true"
val url = "https://dataservice.accuweather.com/forecasts/v1/hourly/12hour/"+courseCode+"?apikey=BWe2c4RedTW67NTZhUmpK5A036tFtNks&language=en-us&details=true&metric=true"
fetchHourlyJson(url)
}
//function that passes through the api call to the fetchCurrentJson using the course code set from the main activity
open fun callCurrentData(courseCode:String){
//val url = "https://dataservice.accuweather.com/currentconditions/v1/"+courseCode+"?apikey=Gngag9jfLyY2fDDrLSr27EVYD1TarOiW&language=en-us&details=true"
val url = "https://dataservice.accuweather.com/currentconditions/v1/"+courseCode+"?apikey=BWe2c4RedTW67NTZhUmpK5A036tFtNks&language=en-us&details=true"
fetchCurrentJson(url)
}
// function that when called concats a 0 to the number if it is between 0 and 10
fun pad(num:Double):String{
var catnum = "";
if (num < 10.0 && num >= 0.0){
catnum = "0$num"
}else{
catnum = num.toString()
}
return catnum
}
}
<file_sep>package com.example.sportsadvisor
// Imports used on this page
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import io.realm.Realm
import io.realm.mongodb.*
import java.time.*
import java.time.format.*
class LoginActivity : AppCompatActivity() {
//variables for user authentication
lateinit var app: App
private lateinit var email: EditText
private lateinit var password: EditText
private lateinit var realm: Realm
lateinit var emailTxt: String
lateinit var passTxt: String
var name:String = ""
// OnCreate function that launches when the page is opened
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_main)
Realm.init(this)
// The MongoDB Realm App ID
val appID = "sportsadvisor-gztkm"
app = App(AppConfiguration.Builder(appID).build())
email = findViewById(R.id.etUsername)
password = findViewById(R.id.etPassword)
// Find the UserID value stored in the application settings page
val sp = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val displayName = sp.getString("displayName", "")
// Make sure the display dame is not empty and set a local variable to this value
if (displayName != null) {
name = displayName
}
// Set the Current date and time
val date = LocalDate.now()
val time = LocalTime.now()
//Output the date and time for debugging
println(time.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)))
println(date)
}
// Function to output alerts to help user with any problems
private fun showToast(s: String) {
Toast.makeText(applicationContext, s, Toast.LENGTH_LONG).show()
}
/* Function that happens when user presses the login button
Used to collect the user input and check if the input is valid,
if - the data is valid - user is then logged in
else - the user gets an alert informing them what they did wrong
*/
fun loginClicked(view: View) {
//Collect the user input for email and password
emailTxt = email.text.toString()
passTxt = password.text.toString()
println("Username input: $emailTxt Password Input: $passTxt")
/* Check if both email and password received is not empty, if so populates them with invalid data
to allow the mongoDb call to bring back an error */
if (emailTxt.isEmpty() && passTxt.isEmpty()){
emailTxt = "<EMAIL>"
passTxt = "<PASSWORD>"
println("Email and pass empty")
}
// A validation check to see only the password is empty
if (emailTxt == email.text.toString() && passTxt.isEmpty()){
passTxt = "<PASSWORD>"
println("pass empty")
}
// A validation check to see if only the email is empty
if (emailTxt.isEmpty() && passTxt == password.text.toString()){
emailTxt = "<EMAIL>"
println("Email empty")
}
// A variable that takes in the email and password before it is used to try and login
val emailPasswordCredentials: Credentials = Credentials.emailPassword(
emailTxt,
passTxt
)
var user: User? = null
/* Method to allow user to sign in to the database
with the user input stored in the variable emailPasswordCredentials*/
app.loginAsync(emailPasswordCredentials) {
if (it.isSuccess) {
Log.v("AUTH", "Successfully authenticated using an email and password.")
showToast("User has Logged in")
//When user is logged, user is redirected to the home page
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
} else {
Log.e("AUTH", it.error.toString())
showToast("Invalid username/password")
}
}
}
/* Function that when the user pressed the Home button
allows the user to go back to the home page
*/
fun goHome(view: View) {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
//println("result stored $result")
}
}<file_sep>package com.example.sportsadvisor
import java.math.BigDecimal
import java.math.RoundingMode
object UserResults {
var result = 0.0;
// method that takes all the values for the conditions and invokes all their corresponding methods
// in order to calcualte the rating for the hour
open fun checkHourlyResults(rainfall:Double, windSpeed:Double, temperature:Double, feelsLikeTemp:Double, humidity:Int, IsDaylight:Boolean): Double {
val rainResult = checkRainfall(rainfall)
val windResult = checkWindSpeed(windSpeed)
val tempResult = checkTemp(temperature)
val tempFeelResult = checkTempFeel(feelsLikeTemp)
val humidityResult = checkHumidity(humidity)
var TotalResultScore = humidityResult + windResult+ tempResult + tempFeelResult + rainResult
var solution = Math.round(TotalResultScore * 10.0) / 10.0
if (IsDaylight == false){
solution = 0.0
}
return solution
}
// method that takes all the values for the conditions and invokes all their corresponding methods
// in order to calcualte the rating for the hour
open fun checkWeeklyResults(rainfall:Double, windSpeed:Double, temperature:Double, feelsLikeTemp:Double, hoursOfPrec:Double): Double {
val rainResult = checkRainfall(rainfall)
val windResult = checkWindSpeed(windSpeed)
val tempResult = checkTemp(temperature)
val tempFeelResult = checkTempFeel(feelsLikeTemp)
val precipitationResult = checkHoursOfPrec(hoursOfPrec)
val TotalResultScore = precipitationResult + windResult+ tempResult + tempFeelResult + rainResult
return TotalResultScore
}
// function that checks the incoming Precipitation Value and compares it to predetermined values
// it will then out put a value between 0.0 and 5.0
private fun checkHoursOfPrec(hoursOfPrec: Double): Double {
result = 0.0;
if (hoursOfPrec in 0.0..2.0)
{
result = 1.0;
}
else
{
when
{
((hoursOfPrec >10.0)) ->{
result = 0.0
}
((hoursOfPrec > 2.0) and (hoursOfPrec <= 4.0)) ->{
result = 0.8
}
((hoursOfPrec > 4.0) and (hoursOfPrec <= 6.0)) -> {
result = 0.6
}
((hoursOfPrec > 6.0) and (hoursOfPrec <= 8.0)) -> {
result = 0.4
}
((hoursOfPrec > 8.0) and (hoursOfPrec <= 10.0)) -> {
result = 0.2
}
}
}
return result
}
// function that checks the incoming Humidity Value and compares it to predetermined values
// it will then out put a value between 0.0 and 5.0
private fun checkHumidity(humidity: Int): Double {
result = 0.0;
if (humidity in 30..60)
{
result = 1.0
}
else
{
when
{
((humidity <= 10) or (humidity >=90)) ->{
result = 0.3
}
((humidity > 10) or(humidity <= 29)) ->{
result = 0.5
}
((humidity > 60) or (humidity < 90)) -> {
result = 0.7
}
}
}
return result
}
// function that checks the incoming Feels Like Temperature Value and compares it to predetermined values
// it will then out put a value between 0.0 and 5.0
private fun checkTempFeel(feelsLikeTemp: Double): Double {
result = 0.0;
var result = 0.0
if (feelsLikeTemp in 10.0..20.0)
{
result = 1.0
}
else
{
when
{
((feelsLikeTemp > 20.0) and (feelsLikeTemp <=25.0)) ->{
result = 0.8
}
((feelsLikeTemp >25.0) and (feelsLikeTemp <= 30.0)) ->{
result = 0.6
}
((feelsLikeTemp > 5.0) and (feelsLikeTemp < 10.0)) -> {
result = 0.4
}
((feelsLikeTemp > 30.0) and (feelsLikeTemp <= 35.0)) -> {
result = 0.2
}
((feelsLikeTemp > 0.0) and (feelsLikeTemp <= 5.0)) -> {
result = 0.2
}
((feelsLikeTemp > 35.0) or (feelsLikeTemp <= 0)) -> {
result = 0.0
}
}
}
return result
}
// function that checks the incoming Temperature Value and compares it to predetermined values
// it will then out put a value between 0.0 and 5.0
private fun checkTemp(temperature: Double): Double {
result = 0.0;
var result = 0.0
if (temperature in 10.0..20.0)
{
result = 1.0
}
else
{
when
{
((temperature > 20.0) and (temperature <=25.0)) ->{
result = 0.8
}
((temperature >25.0) and (temperature <= 30.0)) ->{
result = 0.6
}
((temperature > 5.0) and (temperature < 10.0)) -> {
result = 0.4
}
((temperature > 30.0) and (temperature <= 35.0)) -> {
result = 0.2
}
((temperature > 0.0) and (temperature <= 5.0)) -> {
result = 0.2
}
((temperature > 35.0) or (temperature <= 0)) -> {
result = 0.0
}
}
}
return result
}
// function that checks the incoming Rainfall Value and compares it to predetermined values
// it will then out put a value between 0.0 and 5.0
private fun checkRainfall(rainfall: Double): Double {
result = 0.0;
var result = 0.0
if (rainfall in 0.0..1.0)
{
result = 1.0
}
else
{
when
{
(rainfall < 2.0) ->{
result = 0.8
}
(rainfall < 3.0) ->{
result = 0.6
}
(rainfall < 4.0) -> {
result = 0.4
}
(rainfall < 5.0) -> {
result = 0.2
}
(rainfall > 5.0) -> {
result = 0.0
}
}
}
return result
}
// function that checks the incoming WindSpeed Value and compares it to predetermined values
// it will then out put a value between 0.0 and 5.0
private fun checkWindSpeed(windSpeed: Double): Double {
result = 0.0;
var result = 0.0
if (windSpeed in 0.0..8.0)
{
result = 1.0
}
else
{
when
{
((windSpeed >= 9.0) and (windSpeed <=16.0)) ->{
result = 0.8
}
((windSpeed >= 17.0) and (windSpeed <= 24.0)) ->{
result = 0.6
}
((windSpeed >= 25.0) and (windSpeed <= 32.0)) -> {
result = 0.4
}
((windSpeed >= 33.0) and (windSpeed <= 40.0)) -> {
result = 0.2
}
(windSpeed >= 40.0) -> {
result = 0.0
}
}
}
return result
}
}
<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Precipitation(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXX
)<file_sep>package com.example.sportsadvisor
// Imports used on this page
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import io.realm.Realm
import io.realm.mongodb.*
class RegisterActivity: AppCompatActivity() {
//variables for user authentication
lateinit var app: App
private lateinit var email: EditText
private lateinit var password: EditText
lateinit var emailTxt: String
lateinit var passTxt: String
// OnCreate function that launches when the page is opened
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.register_main)
Realm.init(this)
// The MongoDB Realm App ID
val appID = "sportsadvisor-gztkm"
app = App(AppConfiguration.Builder(appID).build())
//call the edit text in the login xml page
email = findViewById(R.id.etUsername)
password = findViewById(R.id.etPassword)
}
// Function to output alerts to help user with any problems
private fun showToast(s: String) {
Toast.makeText(applicationContext, s, Toast.LENGTH_LONG).show()
}
/* Function that happens when user presses the register button
Used to collect the user input and check if the input is valid,
if - the data is valid - user is registered
else - the user gets an alert informing them what they did wrong
*/
fun registerClicked(view: View) {
// Collect the input the user has inputted
emailTxt = email.text.toString()
passTxt = password.text.toString()
//a debug line
println("Username added $emailTxt Password Added $passTxt")
// Send the input to the mongoDB database to see if the input is valid
app.emailPassword.registerUserAsync(emailTxt, passTxt) {
// A successful result
if (it.isSuccess) {
Log.i("EXAMPLE", "Successfully registered user.")
showToast("User has now Registered - now click GO TO LOGIN")
// User has not registered - output an alert that informs the user of what is not valid
} else {
if(it.error.equals("email already in use"))
{
// Alert when the email is already registered
Log.e("Email incorrect: ", "Failed to register user: ${it.error}")
showToast("ERROR: Email is already in use")
}
else
{
// Alert when the password length is not correct
Log.e("Password incorrect: ", "Failed to register user: ${it.error}")
showToast("ERROR: Password length is not between 6 - 12 characters")
}
}
}
}
// Function used to return the user to the home page
fun returnClicked(view: View) {
val login = Intent(this, LoginActivity::class.java)
startActivity(login)
}
}<file_sep>package HourlyDataResponse
import com.google.gson.annotations.SerializedName
data class WindGust(
@SerializedName("Speed")
val speed: SpeedX
)<file_sep>package com.example.sportsadvisor.model
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.preference.PreferenceManager
import com.example.sportsadvisor.R
import kotlinx.android.synthetic.main.fragment_weather.view.*
class WeatherFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_weather, container, false)
val courseName = arguments?.getString("courseName")
val dataWeather = arguments?.getString("fullList")
println("DATA WEATHER: "+ dataWeather.toString())
//data passed through bundle obj from MainActivity is displayed in XML page
rootView.fragment_weather.text = courseName
if (dataWeather != null) {
rootView.display_data.text = dataWeather.toString()
}
return rootView
}
}<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class SpeedX(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXXXXXXXXXX
)<file_sep>Download this repository , zip the Dissertation folder and add the zipped folder to Overleaf.
<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Temperature(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXX
)<file_sep>package com.example.sportsadvisor
import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.marginBottom
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.activity_main.view.*
import kotlinx.android.synthetic.main.row_nav_drawer.view.*
//adapted from:https://johncodeos.com/how-to-create-a-custom-navigation-drawer-in-android-using-kotlin/
class NavigationRVAdapter(private var items: ArrayList<NavigationItemModel>, private var currentPos: Int) : RecyclerView.Adapter<NavigationRVAdapter.NavigationItemViewHolder>() {
private lateinit var context: Context
class NavigationItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NavigationItemViewHolder {
context = parent.context
val navItem = LayoutInflater.from(parent.context).inflate(R.layout.row_nav_drawer, parent, false)
return NavigationItemViewHolder(navItem)
}
override fun getItemCount(): Int {
return items.count()
}
override fun onBindViewHolder(holder: NavigationItemViewHolder, position: Int) {
// To highlight the selected item, show different background color
if (position == currentPos) {
holder.itemView.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimaryAccent))
} else {
holder.itemView.setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent))
}
holder.itemView.navigation_icon.setColorFilter(Color.parseColor("#D8F3DC"), PorterDuff.Mode.SRC_ATOP)
holder.itemView.navigation_title.setTextColor(Color.parseColor("#D8F3DC"))
holder.itemView.navigation_title.text = items[position].title
holder.itemView.navigation_icon.setImageResource(items[position].icon)
}
}<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past24HourRange(
@SerializedName("Maximum")
val maximum: MaximumX,
@SerializedName("Minimum")
val minimum: MinimumX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past12Hours(
@SerializedName("Imperial")
val imperial: ImperialXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class DewPoint(
@SerializedName("Imperial")
val imperial: ImperialXX,
@SerializedName("Metric")
val metric: MetricXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class WetBulbTemperature(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class PressureTendency(
@SerializedName("Code")
val code: String,
@SerializedName("LocalizedText")
val localizedText: String
)<file_sep>(function(window, undefined) {
var jimLinks = {
"abdc43e8-b1cb-4436-a4ae-524e2460d3a8" : {
"Two-line-item_24" : [
"ddd09d44-1c3a-418b-8427-567f505a6240"
],
"Two-line-item_34" : [
"24b25c6b-785b-4de3-a635-7aed43730986"
],
"Two-line-item_12" : [
"db8fef49-ca00-4354-a7c9-c378277b6d48"
],
"Two-line-item_23" : [
"1c01cb94-d1dd-4ba9-93ee-0f7bfcbac4ae"
],
"raised_Button" : [
"db8fef49-ca00-4354-a7c9-c378277b6d48"
],
"raised_Button_1" : [
"db8fef49-ca00-4354-a7c9-c378277b6d48"
],
"raised_Button_2" : [
"6c3c8fc1-447b-4383-9310-0b272b10aba5"
],
"Button_1" : [
"24b25c6b-785b-4de3-a635-7aed43730986"
]
},
"24b25c6b-785b-4de3-a635-7aed43730986" : {
},
"6c3c8fc1-447b-4383-9310-0b272b10aba5" : {
"menu" : [
"abdc43e8-b1cb-4436-a4ae-524e2460d3a8"
]
},
"d12245cc-1680-458d-89dd-4f0d7fb22724" : {
"menu" : [
"abdc43e8-b1cb-4436-a4ae-524e2460d3a8"
],
"raised_Button" : [
"db8fef49-ca00-4354-a7c9-c378277b6d48"
],
"raised_Button_1" : [
"db8fef49-ca00-4354-a7c9-c378277b6d48"
],
"raised_Button_2" : [
"6c3c8fc1-447b-4383-9310-0b272b10aba5"
]
},
"db8fef49-ca00-4354-a7c9-c378277b6d48" : {
"menu" : [
"abdc43e8-b1cb-4436-a4ae-524e2460d3a8"
]
},
"ddd09d44-1c3a-418b-8427-567f505a6240" : {
"menu" : [
"abdc43e8-b1cb-4436-a4ae-524e2460d3a8"
],
"raised_Button" : [
"db8fef49-ca00-4354-a7c9-c378277b6d48"
]
}
}
window.jimLinks = jimLinks;
})(window);<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Minimum(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXX
)<file_sep>package com.example.sportsadvisor
// adapted from:https://johncodeos.com/how-to-create-a-custom-navigation-drawer-in-android-using-kotlin/
data class NavigationItemModel(var icon: Int, var title: String)
<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past9Hours(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXX
)<file_sep># Description
This is an Android Application, that is used to assist a golfer in picking the best hour to play a round of golf on their chosen golf course. This is done by giving a reccomendation based on which hour has the best weather conditions over a 12 hour period. It also helps the user record their score while playing so that the user can keep track of their previous games and try to improve their score over time.
# Authors
<NAME> <br>
<NAME><br>
<NAME>
# Features
The app contains seven main features, these include:
+ Current Weather Conditions (Home)
+ Next Twelve Hour Weather Conditions (Weather)
+ Saving Round Total and Nett Score (Scores)
+ Viewing Round Total and Nett Scores (User History)
+ Registering (Register)
+ Logging in (Login)
+ Personalised Settings (Settings)
## Current Weather Conditions
This Feature displays current weather conditions for your chosen golf course and gives a rating based on Five weather conditions,(Rainfall, Wind Speed, Temperature, Real Feel Temperature and Humidity). All these conditions are compared to values within the app and depending on how good the condition is, it will give it a rating between 0.0 and 1.0 all adding up to a value between 0.0 and 5.0. If the hour is before sunrise and after sunset, the rating will be automatically set to 0.0 as the user will have no vision in the dark.
## Next Twelve Hour Weather Conditions
This Feature is exactly the same as the current weather conditions feature when outputted to the user. It displays the same five values and the rating for the hour and also displays for the next twelve hours showing the best hour to start a round of golf.
## Saving Round Total and Nett Score
For this feature of the app, we display a table to the user to input their scores along with the Par for the hole, the user will fil the score for all 18 holes and then their total par and score will be saved to the database.
## Viewing Round Total and Nett Scores
This is where the user is able to see their previous games results that only match their UserID which is set in the settings page. The user presses the get results button and their score data will be shown. These results are retreived from the database and displays the score along with the time, date and the golf course they played on.
## Registering
To allow the user to create an account, this feature was created. It allows the user to create an account to store data from the application. To create an account , the user is required to provide an email and password. The user will receive an alert that the account was verified.
## Logging in
We implented the login feature to allow the user to send the score data to the database and get back an instant response in the user history section of our app. Without this the user would not be able to output any saved data in User History.
## Personalised Settings
Within the settings feature of our app, the user is able to set their preferred golf course, their handicap and their UserID. These can be used throughout the application to cater the application to the needs of the user.
# Compiling, Deploying and Running the Project
## IDE Installation
The first thing to do is check if you have IntelliJ IDEA Ultimate is installed.<br>
It is included free with GitHub Student Developer pack <br>
If you only have the community version installed, uninstall this edition to avoid conflicts.<br>
Please download and install the JetBrains Toolbox - [JetBrains Toolbox download link](https://www.jetbrains.com/toolbox-app/)<br>
When toolbox has installed, please install IntelliJ IDEA Ultimate Edition, version: 2021.1.1 or latest version available.
## SDK Installation
To install an SDK, follow the guidelines set out on this webpage [SDK install guide](https://www.jetbrains.com/help/idea/sdk.html)<br>
The default AVD emulator used for the project is the Pixel 3A phone with Android 9.0(Pie) with API 28
The AVD can be installed be following these steps;
1. Open the Intellij Ultimate IDE Desktop App
2. On the top toolbar click on Tools
3. Then click the last choice called Android
4. This will open up a menu - click on AVD Manager
5. When the AVD manager opens up click on Create virtual device
6. Choose the phone you wish to run the app on and set it to android 9.0(Pie).
## ADK Installation
The default AVD emulator we used for testing the project is the Pixel 3 phone with Android 9.0(Pie) with API 28. \newline
Steps to install the Android Development Kit
1. Open Intellij
2. On the top toolbar click on Tools
3. Then click the last choice called Android
4. This will open up a menu - click on AVD Manager
5. When the AVD manager opens up click on Create virtual device
6. Choose the phone you wish to run the app on and set it to android 9.0(Pie)
## Cloning the Application
To deploy the application, you must first clone the Application from this GitHub Repository using the terminal or GitHub Desktop.
## Deployment
There are three seperate ways to deploy our application but reccomend only two methods
1. Deploy to Emulator from APK File
2. Deploy to Phone
3. Deploy Android Emulator via IntelliJ
### Deploy to Android Emulator from APK File
Any Android Emulator should be capable of running the app-release.APK file but for this demonstration we are using the [Genymotion Android Emulator](https://www.genymotion.com)<br>
+ Download and install the Genymotion Android Emulator and set up the emulator as per [Genymotion Android Emulator Start Up](https://docs.genymotion.com/desktop/latest/01_Get_started.html#using-a-license-server)
+ When Setting up the virtual device make sure the Android version is set to 9.0 - API 28
+ Once the emulator is loaded drag the Apk file found in [APKRelease](https://github.com/stevenJoyce/4thYearGroupProject/tree/main/APKRelease) into the emulator.
+ The App should run
Please note: The App doesn't run as smoothly when deployed to this emulator compared to the being deployed on phones and on the Android Emulator included with the IntelliJ IDEA when the Android ADK is installed.
### Deploy to Mobile/Emulator
For this section we will show how to deploy to the android emulator and mobile device from IntelliJ which can be done following [Build/Run Steps for Android](https://www.jetbrains.com/help/idea/create-your-first-android-application.html#build-run-Android-application).
You can deploy to mobile straight from IntellJ IDEA Ultimate to your android phone by changing the default phone option from the Android Emulator to your mobile device and then press the play button.
<file_sep>package HourlyDataResponse
class HourlyProcessedData : ArrayList<HourlyProcessedDataItem>()<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class WindChillTemperature(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past6Hours(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Direction(
@SerializedName("Degrees")
val degrees: Int,
@SerializedName("English")
val english: String,
@SerializedName("Localized")
val localized: String
)<file_sep>PROJECT=project
TEX=pdflatex --shell-escape --interaction=nonstopmode -halt-on-error
all:
$(TEX) $(PROJECT).tex
clean:
$(RM) -rf *.log *.aux *.out *.bak *.idx *.toc *.nav *.snm *.vrb _minted-slides
% TODO: \usepackage{graphicx} required
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{project}
\caption{}
\label{fig:project}
\end{figure}
<file_sep># Project Software
The first thing to do is check if Intellij Ultimate is installed.It is free with GitHub Student pack \newline
If only community version installed, uninstall it
Download and install JetBrain Toolbox - [toolbox download link](https://www.jetbrains.com/toolbox-app/)
When toolbox runs install DataGrip and Intellij Ultimate both versions: 2020.2.3
<file_sep>package HourlyDataResponse
import com.google.gson.annotations.SerializedName
data class HourlyProcessedDataItem(
@SerializedName("Ceiling")
val ceiling: Ceiling,
@SerializedName("CloudCover")
val cloudCover: Int,
@SerializedName("DateTime")
val dateTime: String,
@SerializedName("DewPoint")
val dewPoint: DewPoint,
@SerializedName("EpochDateTime")
val epochDateTime: Int,
@SerializedName("HasPrecipitation")
val hasPrecipitation: Boolean,
@SerializedName("Ice")
val ice: Ice,
@SerializedName("IceProbability")
val iceProbability: Int,
@SerializedName("IconPhrase")
val iconPhrase: String,
@SerializedName("IndoorRelativeHumidity")
val indoorRelativeHumidity: Int,
@SerializedName("IsDaylight")
val isDaylight: Boolean,
@SerializedName("Link")
val link: String,
@SerializedName("MobileLink")
val mobileLink: String,
@SerializedName("PrecipitationProbability")
val precipitationProbability: Int,
@SerializedName("Rain")
val rain: Rain,
@SerializedName("RainProbability")
val rainProbability: Int,
@SerializedName("RealFeelTemperature")
val realFeelTemperature: RealFeelTemperature,
@SerializedName("RelativeHumidity")
val relativeHumidity: Int,
@SerializedName("Snow")
val snow: Snow,
@SerializedName("SnowProbability")
val snowProbability: Int,
@SerializedName("Temperature")
val temperature: Temperature,
@SerializedName("TotalLiquid")
val totalLiquid: TotalLiquid,
@SerializedName("UVIndex")
val uVIndex: Int,
@SerializedName("UVIndexText")
val uVIndexText: String,
@SerializedName("Visibility")
val visibility: Visibility,
@SerializedName("WeatherIcon")
val weatherIcon: Int,
@SerializedName("WetBulbTemperature")
val wetBulbTemperature: WetBulbTemperature,
@SerializedName("Wind")
val wind: Wind,
@SerializedName("WindGust")
val windGust: WindGust
)<file_sep>package HourlyDataResponse
import com.google.gson.annotations.SerializedName
data class Wind(
@SerializedName("Direction")
val direction: Direction,
@SerializedName("Speed")
val speed: Speed
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past24HourTemperatureDeparture(
@SerializedName("Imperial")
val imperial: ImperialXXX,
@SerializedName("Metric")
val metric: MetricXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class MaximumXX(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class MaximumX(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past6HourRange(
@SerializedName("Maximum")
val maximum: MaximumXX,
@SerializedName("Minimum")
val minimum: MinimumXX
)<file_sep>package CurrentConditionsDataResponse
class currentConditions : ArrayList<currentConditionsItem>()<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class MinimumXX(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXXXXXXX
)<file_sep># Adding the mongoDB server
Open DataGrip
CLick on + symbol in database

Open a browser
Sign in to MongoDB
go to the database - 4thYrFinalGroupProject
Open Cluster0
CLick on connect

When you get the sceen above - clik on option 2 - Connect your application
Now copy the url link provided
Back to Datagrip - make sure that your input mirrors the below image
Add the copied URL
password is <PASSWORD>
changing dbname to data changes the url to match the image

You should see connected in data log to know that you were successful.
<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class PastHour(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Past3Hours(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXX
)<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Precip1hr(
@SerializedName("Imperial")
val imperial: ImperialXXXX,
@SerializedName("Metric")
val metric: MetricXXXX
)<file_sep>var content='<div class="ui-page" deviceName="androidphone" deviceType="mobile" deviceWidth="360" deviceHeight="720">\
<div id="t-f39803f7-df02-4169-93eb-7547fb8c961a" class="template growth-both devMobile canvas firer commentable non-processed" alignment="left" name="Template 1" width="360" height="720">\
<div id="backgroundBox"><div class="colorLayer"></div><div class="imageLayer"></div></div>\
<div id="alignmentBox">\
<link type="text/css" rel="stylesheet" href="./resources/templates/f39803f7-df02-4169-93eb-7547fb8c961a-1613057132191.css" />\
<!--[if IE]><link type="text/css" rel="stylesheet" href="./resources/templates/f39803f7-df02-4169-93eb-7547fb8c961a-1613057132191-ie.css" /><![endif]-->\
<!--[if lte IE 8]><![endif]-->\
<div class="freeLayout">\
</div>\
\
</div>\
<div id="loadMark"></div>\
</div>\
\
<div id="s-d12245cc-1680-458d-89dd-4f0d7fb22724" class="screen growth-vertical devMobile canvas PORTRAIT firer ie-background commentable non-processed" alignment="left" name="Welcome Page" width="360" height="720">\
<div id="backgroundBox"><div class="colorLayer"></div><div class="imageLayer"></div></div>\
<div id="alignmentBox">\
<link type="text/css" rel="stylesheet" href="./resources/screens/d12245cc-1680-458d-89dd-4f0d7fb22724-1613057132191.css" />\
<!--[if IE]><link type="text/css" rel="stylesheet" href="./resources/screens/d12245cc-1680-458d-89dd-4f0d7fb22724-1613057132191-ie.css" /><![endif]-->\
<!--[if lte IE 8]><link type="text/css" rel="stylesheet" href="./resources/screens/d12245cc-1680-458d-89dd-4f0d7fb22724-1613057132191-ie8.css" /><![endif]-->\
<div class="freeLayout">\
<div id="s-Empty_screen" class="group firer ie-background commentable non-processed" customid="Empty_screen" datasizewidth="0.0px" datasizeheight="0.0px" >\
<div id="s-Screen-bg" class="pie percentage richtext manualfit firer commentable pin vpin-beginning hpin-beginning non-processed-percentage non-processed-pin non-processed" customid="Screen-bg" datasizewidth="100.0%" datasizeheight="100.0%" dataX="2.0" dataY="0.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-Screen-bg_0"></span>\
</div>\
</div>\
</div>\
</div>\
</div>\
<div id="s-Softkeys-bg" class="pie percentage rectangle manualfit firer commentable pin vpin-end hpin-center non-processed-percentage non-processed-pin non-processed" customid="Softkeys-bg" datasizewidth="100.0%" datasizeheight="48.0px" datasizewidthpx="360.0" datasizeheightpx="48.0" dataX="2.0" dataY="0.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-Softkeys-bg_0"></span>\
</div>\
</div>\
</div>\
</div>\
</div>\
\
<div id="s-Square" class="pie image lockV firer ie-background commentable pin vpin-end hpin-end non-processed-pin non-processed" customid="Square" datasizewidth="15.0px" datasizeheight="15.0px" dataX="72.0" dataY="17.0" aspectRatio="1.0" alt="image" systemName="./images/b3647acf-a82a-49bf-a3f4-73281ec88af0.svg" overlay="">\
<div class="borderLayer">\
<div class="imageViewport">\
<?xml version="1.0" encoding="UTF-8"?>\
<svg preserveAspectRatio=\'none\' width="16px" height="16px" viewBox="0 0 16 16" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\
<!-- Generator: Sketch 49.2 (51160) - http://www.bohemiancoding.com/sketch -->\
<title>recent</title>\
<desc>Created with Sketch.</desc>\
<defs></defs>\
<g id="s-Square-Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\
<g id="Bars/Navbar-360dp-black" transform="translate(-273.000000, -16.000000)" fill="#FFFFFF">\
<g id="s-Square-Group-3" transform="translate(231.000000, 0.000000)">\
<rect id="s-Square-recent" x="42" y="16" width="16" height="16" rx="1"></rect>\
</g>\
</g>\
</g>\
</svg>\
</div>\
</div>\
</div>\
\
\
<div id="s-Circle" class="pie image lockV firer ie-background commentable pin vpin-end hpin-center non-processed-pin non-processed" customid="Circle" datasizewidth="18.0px" datasizeheight="18.0px" dataX="2.0" dataY="15.0" aspectRatio="1.0" alt="image" systemName="./images/a2a3c16d-6a80-4fe3-9766-bb413fb4943d.svg" overlay="">\
<div class="borderLayer">\
<div class="imageViewport">\
<?xml version="1.0" encoding="UTF-8"?>\
<svg preserveAspectRatio=\'none\' width="20px" height="20px" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\
<!-- Generator: Sketch 49.2 (51160) - http://www.bohemiancoding.com/sketch -->\
<title>home</title>\
<desc>Created with Sketch.</desc>\
<defs></defs>\
<g id="s-Circle-Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\
<g id="Bars/Navbar-360dp-black" transform="translate(-170.000000, -14.000000)">\
<g id="s-Circle-Group-4" transform="translate(130.000000, 0.000000)">\
<g id="s-Circle-home" transform="translate(40.000000, 14.000000)">\
<circle fill="#FFFFFF" fill-rule="evenodd" cx="10" cy="10" r="6"></circle>\
<circle stroke="#FFFFFF" stroke-width="2" cx="10" cy="10" r="9"></circle>\
</g>\
</g>\
</g>\
</g>\
</svg>\
</div>\
</div>\
</div>\
\
\
<div id="s-Triangle" class="pie image lockV firer click ie-background commentable pin vpin-end hpin-beginning non-processed-pin non-processed" customid="Triangle" datasizewidth="15.0px" datasizeheight="15.0px" dataX="78.0" dataY="17.0" aspectRatio="1.0" alt="image" systemName="./images/b39d52fb-13b0-4d98-a31b-99b0b049d494.svg" overlay="">\
<div class="borderLayer">\
<div class="imageViewport">\
<?xml version="1.0" encoding="UTF-8"?>\
<svg preserveAspectRatio=\'none\' width="15px" height="17px" viewBox="0 0 15 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">\
<!-- Generator: Sketch 49.2 (51160) - http://www.bohemiancoding.com/sketch -->\
<title>back</title>\
<desc>Created with Sketch.</desc>\
<defs></defs>\
<g id="s-Triangle-Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\
<g id="Bars/Navbar-360dp-black" transform="translate(-72.000000, -15.000000)" fill="#FFFFFF">\
<g id="s-Triangle-Group-2" transform="translate(29.000000, 0.000000)">\
<path d="M56.2719481,15.2473593 C57.2263246,14.695639 57.9999997,15.1409225 57.9999997,16.2463373 L58,30.7555624 C58,31.859003 57.2280325,32.3072478 56.2719485,31.7545403 L43.7227789,24.4999276 C42.7684024,23.9482072 42.7666949,23.0546789 43.7227789,22.5019715 L56.2719481,15.2473593 Z" id="s-Triangle-back"></path>\
</g>\
</g>\
</g>\
</svg>\
</div>\
</div>\
</div>\
\
<div id="s-Bg" class="pie percentage richtext manualfit firer commentable pin vpin-beginning hpin-beginning non-processed-percentage non-processed-pin non-processed" customid="Bg" datasizewidth="100.0%" datasizeheight="76.0px" dataX="2.0" dataY="0.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-Bg_0"></span>\
</div>\
</div>\
</div>\
</div>\
</div>\
\
<div id="s-more-vertical" class="pie image firer ie-background commentable pin vpin-beginning hpin-end non-processed-pin non-processed" customid="more-vertical" datasizewidth="26.0px" datasizeheight="26.0px" dataX="6.0" dataY="36.0" alt="image" systemName="./images/f3426e4c-7949-4cb3-822b-3bbe09e4c7e0.svg" overlay="#FFFFFF">\
<div class="borderLayer">\
<div class="imageViewport">\
<?xml version="1.0" encoding="UTF-8"?>\
<svg preserveAspectRatio=\'none\' xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" fill="#FFFFFF" jimofill=" " /></svg>\
\
</div>\
</div>\
</div>\
\
\
<div id="s-menu" class="pie image firer click ie-background commentable pin vpin-beginning hpin-beginning non-processed-pin non-processed" customid="menu" datasizewidth="26.0px" datasizeheight="26.0px" dataX="15.0" dataY="36.0" alt="image" systemName="./images/16f9b5a2-103f-4829-b541-31eacddb5ea6.svg" overlay="#FFFFFF">\
<div class="borderLayer">\
<div class="imageViewport">\
<?xml version="1.0" encoding="UTF-8"?>\
<svg preserveAspectRatio=\'none\' xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" fill="#FFFFFF" jimofill=" " /></svg>\
\
</div>\
</div>\
</div>\
\
\
<div id="s-Status-bar" class="group firer ie-background commentable non-processed" customid="Status-bar" datasizewidth="0.0px" datasizeheight="0.0px" >\
<div id="s-Bg_status" class="pie percentage rectangle manualfit firer commentable pin vpin-beginning hpin-beginning non-processed-percentage non-processed-pin non-processed" customid="Bg_status" datasizewidth="100.0%" datasizeheight="20.0px" datasizewidthpx="360.0" datasizeheightpx="20.0" dataX="2.0" dataY="0.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-Bg_status_0"></span>\
</div>\
</div>\
</div>\
</div>\
</div>\
<div id="s-hour" class="pie richtext manualfit firer ie-background commentable pin vpin-beginning hpin-beginning non-processed-pin non-processed" customid="hour" datasizewidth="46.0px" datasizeheight="20.0px" dataX="2.0" dataY="0.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-hour_0">15:45</span>\
</div>\
</div>\
</div>\
</div>\
</div>\
\
<div id="s-signals" class="pie image firer ie-background commentable pin vpin-beginning hpin-end non-processed-pin non-processed" customid="signals" datasizewidth="61.0px" datasizeheight="20.0px" dataX="6.0" dataY="0.0" alt="image">\
<div class="borderLayer">\
<div class="imageViewport">\
<img src="./images/e912ddae-6d49-4f8c-b934-4e980e1d108f.png" />\
</div>\
</div>\
</div>\
\
</div>\
\
</div>\
\
<div id="s-flat_Button_disabled" class="pie button multiline manualfit firer ie-background commentable non-processed" customid="flat_Button_disabled" datasizewidth="107.0px" datasizeheight="36.0px" dataX="180.0" dataY="285.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-flat_Button_disabled_0"></span>\
</div>\
</div>\
</div>\
</div>\
</div>\
<div id="s-Input_1" class="pie text firer commentable non-processed" customid="Input" datasizewidth="310.0px" datasizeheight="29.0px" dataX="27.0" dataY="228.0" ><div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div><div class="borderLayer"><div class="paddingLayer"><div class="content"><div class="valign"><input type="text" value="" maxlength="100" tabindex="-1" placeholder="Email"/></div></div> </div></div></div>\
<div id="s-Input_2" class="pie text firer commentable non-processed" customid="Input" datasizewidth="310.0px" datasizeheight="29.0px" dataX="27.0" dataY="270.5" ><div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div><div class="borderLayer"><div class="paddingLayer"><div class="content"><div class="valign"><input type="text" value="" maxlength="100" tabindex="-1" placeholder="Password"/></div></div> </div></div></div>\
<div id="s-raised_Button" class="pie button multiline manualfit firer click commentable non-processed" customid="raised_Button" datasizewidth="310.0px" datasizeheight="50.0px" dataX="27.0" dataY="303.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-raised_Button_0">Sign Up</span>\
</div>\
</div>\
</div>\
</div>\
</div>\
<div id="s-raised_Button_1" class="pie button multiline manualfit firer click commentable non-processed" customid="raised_Button" datasizewidth="310.0px" datasizeheight="50.0px" dataX="27.0" dataY="360.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-raised_Button_1_0">Login</span>\
</div>\
</div>\
</div>\
</div>\
</div>\
<div id="s-raised_Button_2" class="pie button multiline manualfit firer click commentable non-processed" customid="raised_Button" datasizewidth="250.0px" datasizeheight="36.0px" dataX="55.0" dataY="455.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-raised_Button_2_0">Continue as Guest</span>\
</div>\
</div>\
</div>\
</div>\
</div>\
<div id="s-Paragraph_1" class="pie richtext manualfit firer ie-background commentable non-processed" customid="Paragraph" datasizewidth="178.5px" datasizeheight="31.0px" dataX="55.0" dataY="35.0" >\
<div class="backgroundLayer">\
<div class="colorLayer"></div>\
<div class="imageLayer"></div>\
</div>\
<div class="borderLayer">\
<div class="paddingLayer">\
<div class="content">\
<div class="valign">\
<span id="rtr-s-Paragraph_1_0">Sports Advisor</span>\
</div>\
</div>\
</div>\
</div>\
</div>\
</div>\
\
</div>\
<div id="loadMark"></div>\
</div>\
\
</div>\
';
document.getElementById("chromeTransfer").innerHTML = content;<file_sep>package CurrentConditionsDataResponse
import com.google.gson.annotations.SerializedName
data class Maximum(
@SerializedName("Imperial")
val imperial: ImperialXXXXXXXXXXXXXXXXX,
@SerializedName("Metric")
val metric: MetricXXXXXXXXXXXXXXXXX
)<file_sep>package com.example.sportsadvisor.model
import androidx.fragment.app.Fragment
import com.example.sportsadvisor.R
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_demo.view.*
import kotlinx.android.synthetic.main.fragment_demo.view.display_data
import kotlinx.android.synthetic.main.fragment_demo.view.fragment_weather
import kotlinx.android.synthetic.main.fragment_weather.view.*
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_demo, container, false)
val fragmentName = arguments?.getString("fragmentName")
val dataWeather = arguments?.getString("fullList")
println("DATA WEATHER: "+ dataWeather.toString())
//data passed through bundle obj from MainActivity is displayed in XML page
rootView.fragment_weather.text = fragmentName
if (dataWeather != null) {
rootView.display_data.text = dataWeather.toString()
}
return rootView
}
}
<file_sep>package com.example.sportsadvisor
// Imports used on this page
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import io.realm.mongodb.App
import io.realm.mongodb.AppConfiguration
import io.realm.mongodb.User
import io.realm.mongodb.mongo.iterable.MongoCursor
import org.bson.Document
class UserHistory : AppCompatActivity() {
// Variables used to access the realm app and data
lateinit var app: App
var filteredList = ArrayList<String>()
lateinit var results: MongoCursor<Document>
lateinit var colResults:String
// Used to populate the textView in the user history xml page
private lateinit var text: TextView
// Variables used to store the MongoDB data into a string
var listString:String=""
var fl:String = ""
var fl2:String = ""
var fl3:String = ""
var fl4:String = ""
var userID:String = ""
var user: User? = null
// Allow the data sent back to not include the ObjectID
var query = Document("_id",false)
// OnCreate function that launches when the page is opened
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.userhistory_main)
// The MongoDB Realm App ID
val appID = "sportsadvisor-gztkm"
app = App(AppConfiguration.Builder(appID).build())
// Set the textView to the textView on the xml page
text = findViewById(R.id.userHistory)
// Find the UserID value stored in the application settings page
val sp = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val displayName = sp.getString("displayName", "")
userID = displayName.toString()
user = app.currentUser()
// Variables used to call the MongoDB Atlas cluster containing user data
val mongoClient = user!!.getMongoClient("mongodb-atlas")
// Call the database
val mongoDatabase = mongoClient.getDatabase("Users")
// Call the collection
val mongoCollection = mongoDatabase.getCollection("UserData")
Log.v("EXAMPLE", "Successfully instantiated the MongoDB collection handle")
// Create a variable to filter the collections to only bring back the user data that contains the UserID
val queryFilter = Document("userID", userID)
/* Call the collection and filter the results with the query filter and
output all collections associated with that userID*/
val findTask = mongoCollection.find(queryFilter).projection(query).iterator()
findTask.getAsync { task ->
if (task.isSuccess) {
listString = " "
results = task.get()
Log.v("EXAMPLE", "successfully found all collections:")
var x = 0
var colCount = 1
while (results.hasNext()) {
colResults = results.next().toString()
/* Modify the data received from the call with the split and replace embedded methods in Kotlin*/
filteredList.add(colResults.split("[","{{",",","}}","Document{{","]").toString())
fl += " Collection " + colCount + "\n" +"\t"+ filteredList[x] + "\n\n"
fl2 = fl.replace("[","")
fl3 = fl2.replace(",","\n")
fl4 = fl3.replace("]","")
listString = fl4
// iterator used to store the collection
x++
//Iterator outputted to the user for better readability
colCount++
Log.v("List", listString)
}
} else {
Log.e("EXAMPLE", "failed to find documents with: ${task.error}")
//listString = " No User data found"
}
}
}
// Function used to output the collection data to the page
fun userData(view: View) {
//send stored data to page
text.setText(listString)
}
// Function used to return the user to the home page
fun homeClicked(view: View) {
val home = Intent(this, MainActivity::class.java)
startActivity(home)
}
} | f3055e8b09205b29788ace2226a4f6dc9442a377 | [
"JavaScript",
"Makefile",
"Kotlin",
"Markdown"
] | 55 | Kotlin | EvanGreaney/4thYearGroupProject | 947348889a53a4c04a2ce236bd44dea041076500 | bd8ce56597fc26b708445e2e4082d3d27a51c5f6 |
refs/heads/master | <repo_name>lorrainebaynosa/AmazonStoreFrontInterface<file_sep>/README.md
# AmazonStoreFrontInterface
AmazonStoreFrontInterface creates an Amazon-like storefront that takes in orders from customers and depletes stock from the store's inventory. SQL statements will be used to create the schema (structure for the database), while npm packages inquire and mysql will be used to prompt customers for answers; and query and update the database stored/displayed in MySQLworkbench, respectively.
AmazonStoreFrontInterface is a Command Line Interface(CLI) application that takes in user input and returns data. Screenshots will be displayed showing typical user flow through the application (customer), including prompts and responses after various selections.
CUSTOMER VIEW:
Definitions for column names:
* item_id (unique id for each product)
* product_name (Name of product)
* department_name
* price (cost to customer)
* stock_quantity (how much of the product is available in stores)
In mySQLWorkbench, the code for creating the products table within the bamazon database (bamazon.products):
<img src="images/bamazon_products.jpg" width="800">

In mySQLWorkbench, populating the products table with products:
<img src="images/bamazon_products_original_inventory.jpg" width="800">

In mySQLWorkbench, populating the products table with products, actual display:
<img src="images/bamazon_products_display_customerView.jpg" width="800">

In order to run bamazonCustomer.js on node.js, will need to
1. run npm init to create package.json file with inquirer and mysql dependencies from the terminal and
2. run npm install inquirer and npm install mysql to create node_modules to store the npm packages:
<img src="images/npm_dependencies.jpg" width="800">

Running this application will first display a prompt asking the user if he/she would like to SHOP or EXIT (i.e., end connection to local host) followed by display of all items available for sale. Include ids, names, and prices for sale (customer view of products table).
The app then prompt users with two messages.
* The first message should ask them the ID of the product they would like to buy.
* The second message should ask how many units of the product they would like to buy.
Once the customer has placed the order, your application should check if your store has enough of the product to meet the customer's request.
* If not, the app should log a phrase like `Insufficient quantity!`, and then prevent the order from going through.
However, if your store _does_ have enough of the product, you should fulfill the customer's order.
* This means updating the SQL database to reflect the remaining quantity.
* Once the update goes through, show the customer the total cost of their purchase.
The image below shows that the user has selected 5 units of item_id 10. The order is fulfilled because the number of units selected is equal to the stock_quantity. Cost to the customer: 44875.
<img src="images/purchase_Omega.jpg" width="800">

The original product inventory displayed in mySQLWorkbench appears below:
<img src="images/mySQLWorkbench_original_inventory.jpg" width="800">

After the purchase of five(5) Omega watches, the inventory resolves to 0:
<img src="images/mySQLWorkbench_OmegaPurchase.jpg" width="800">

So if user tries to purchase two(2) more Omega watches, user receives the message `Insufficient quantity!`because the inventory is already at zero. Order is prevented from going through (see screenshot of terminal below):
<img src="images/OmegaDepleted.jpg" width="800">

Validating insufficient quantity when user tries to order 51 of the Apple MacBook Pros advertised at 19.99, item_id = 9, since stock_quantity is 50. Additionally, when user chooses EXIT at the prompt, the connection to the mySQL server via mySQL npm package is terminated.
<img src="images/AppleInsufficientQuantity.jpg" width="800">

In order to test this code, the user will need to:
1. Install mySQLWorkbench and create password for mySQLWorkbench
2. Execute code in Amazon.sql in mySQLWorkbench
3. initiate and install all the npm packages listed in bamazonCustomer.js: inquirer, mysql
4. Enter password for mySQLWorkbench in bamazonCustomer.js
<file_sep>/bamazonCustomer.js
var mysql = require("mysql");
var inquirer = require("inquirer");
// create the connection information for the sql database
var connection = mysql.createConnection({
host: "localhost",
// Your port; if not 3306
port: 3306,
// Your username
user: "root",
// Your password (for mySQL workbench)
password: "<PASSWORD>",
database: "bamazon"
});
// connect to the mysql server and sql database
connection.connect(function (err) {
if (err) throw err;
console.log("connected as id " + connection.threadId);
start();
});
// running application will first display all items available for sale. Display ids, names, and prices of products for sale.
function start() {
inquirer
.prompt({
name: "shopOrExit",
type: "list",
message: "Would you like to [SHOP] or [EXIT]?",
choices: ["SHOP", "EXIT"]
})
.then(function (answer) {
//based on their answer, either call the shop function or end connection
if (answer.shopOrExit === "SHOP") {
connection.query("SELECT item_id, product_name, price FROM products",
function (err, results) {
if (err) throw err;
for (var i = 0; i < results.length; i++) {
console.log(results[i].item_id + " | " + results[i].product_name + " | " + results[i].price);
}
console.log("-----------------------------------");
});
shop();
} else {
connection.end();
}
});
}
// Once the customer sees the products for sale, the app should then prompt users with two messages:
// 1) ask them the ID of the product they would like to buy.
// 2) ask how many units of the product they would like to buy.
function shop() {
// query database for all products for sale
connection.query("SELECT * FROM products", function (err, results) {
if (err) throw err;
// once you have the products for sale, prompt the user for item they would like to shop
inquirer
.prompt([
{
name: "choice",
type: "rawlist",
choices: function () {
var choiceArray = [];
for (var i = 0; i < results.length; i++) {
choiceArray.push(results[i].item_id);
}
return choiceArray;
},
message: "What is the item_id of the product you would like to buy?"
},
{
name: "units",
type: "input",
message: "How many units of the product would like to buy?"
}
])
.then(function (answer) {
// get the information of the chosen item
var chosenItem;
for (var i = 0; i < results.length; i++) {
if (results[i].item_id === answer.choice) {
chosenItem = results[i];
}
}
// based on their answer (customer has placed the order), your application should check if your store has enough of the product to meet the customer's request (READ)
connection.query("SELECT * FROM products", function (err, results) {
if (err) throw err;
if (chosenItem.stock_quantity < parseInt(answer.units)) {
// If store does not have enough product, the app should log a phrase like `Insufficient quantity!`, and then prevent the order from going through.
console.log("Insufficient quantity. See if you would like to purchase another products.");
start();
}
// If store has enough product, you should 1) fulfill the customer's order; 2) update the SQL database to reflect the remaining quantity; and 3) show the customer the total cost of their purchase.
else {
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: chosenItem.stock_quantity - answer.units
},
{
item_id: chosenItem.item_id
}
],
function (error) {
if (error) throw err;
console.log("Total cost of purchase: " + answer.units * chosenItem.price);
console.log("Order placed successfully!");
start();
}
);
}
});
});
});
}
// ALEX, I added a prompt at the beginning to make connection end more fluid. Will I be graded down if the table isn't the 1st thing user sees?<file_sep>/Amazon.sql
DROP DATABASE IF EXISTS bamazon;
-- creates bamazon database
CREATE DATABASE bamazon;
-- specifies that we will be using bamazon database; will store to table products in bamazon database
USE bamazon;
-- creating products table within bamazon database, where item_id, product_name, department_name, price, stock_quantity, and primary key are columns/features/attributes of the table
CREATE TABLE products (
item_id INT NOT NULL AUTO_INCREMENT,
product_name VARCHAR(50) NULL,
department_name VARCHAR(30) NULL,
price DECIMAL(10,2) NULL,
stock_quantity INT NULL,
PRIMARY KEY (item_id)
);
-- adding rows with specified values for each cell, containing 10 different products
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES
('glass teapot', 'kitchen', 19.99, 20),
('yoga mat', 'exercise', 24.99, 50),
('compression stockings', 'clothing', 9.25, 50),
('yellow legal pad, 12 pads per pack', 'office', 17.50, 100),
('Obagi 3 oz SPF 50 sunscreen', 'beauty', 53.00, 200),
('L.O.L surprise underwraps doll', 'toys', 13.88, 150),
('KitchenAid 4.5qt stand mixer, silver', 'kitchen', 199.99, 25),
('Samsung UN65RU7 flat 65in smart TV', 'electronics', 777.99, 30),
('Apple MacBook Pro, 13in 128GB', 'electronics', 19.99, 50),
('Omega Deville Ladies Watch', 'watches', 8975.00, 5);
-- Displaying all columns from products table, with columns ordered by department_name followed by product_name in ascending order (alphabetical order from A-Z)
SELECT *
FROM products
ORDER BY department_name, product_name;
| d83070923f7c7f613de8d6f85b737f22c7d14e13 | [
"Markdown",
"SQL",
"JavaScript"
] | 3 | Markdown | lorrainebaynosa/AmazonStoreFrontInterface | 962d11e66b71e8384d89490f4c892fc4c4fb2203 | 11554222c5e034ff36954907cac1f253cd132150 |
refs/heads/master | <repo_name>drewyeaton/django-orienteer<file_sep>/readme.md
#Orienteer
Orienteer is simple Compass integration for Django projects. It is the easiest
way to give Compass/Sass projects first class status inside your Django
project. Once you define the settings below and add template tags to your
template, fire up the development server. If a CSS file seems to be
out-of-date, Orienteer will run Compass to generate your CSS for you. That's
all there is to it. Be sure to *carefully read the instructions* below for
settings specifics.
##Usage
In your Django settings.py file, define the path to your source files. Your
'src' folder should be inside the directory you define here.
COMPASS_PROJECT_DIR = MEDIA_ROOT + 'css/'
Then, define the output directory. **This is relative to the project directory.**
COMPASS_OUTPUT_DIR = './'
Also, set the URL where your output files will be accessed.
COMPASS_OUTPUT_URL = MEDIA_URL + 'css/'
Finally, define where the compass binary is and how you want your CSS generated.
COMPASS_BIN = '/usr/bin/compass'
COMPASS_STYLE = 'compact'
Next, in your template file you can reference your Sass file along with which media type(s) it is and the appropriate
style tag will be generated.
{% load orienteer %}
{% compass 'my_style' 'screen, print' %}
This will check your Compass project's 'src' directory for the 'my_style.sass'
file, compile it if necessary, and then output the following HTML tag:
<link href='/media/css/my_style.css?1273972058.0' rel='stylesheet' type='text/css' />
That's it!
##Documentation
View [Sass documentation](http://sass-lang.com/docs.html) and
[Compass documentation](http://compass-style.org/docs/) for details on syntax.
Also, be sure to visit the [Compass Google Group](http://groups.google.com/group/compass-users)
for help with Compass related issues.
##Requirements
- [Python](http://python.org/) (2.5 or greater, but not 3.x)
- [Django](http://www.djangoproject.com/) (1.0 or greater)
##Acknowledgements
Special thanks to <NAME> (<EMAIL>) for providing the clever
Django Sass app which was the inspiration for this one.<file_sep>/orienteer/templatetags/orienteer.py
#!/usr/bin/python2.5
#
# Copyright 2010 Sentinel Design. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''Simple Compass integration for Django'''
__author__ = '<NAME> <<EMAIL>>'
__version__ = '0.2'
import os
from commands import getstatusoutput
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def compass(filename, media):
import time
proj_dir = settings.COMPASS_PROJECT_DIR
output_dir = settings.COMPASS_OUTPUT_DIR
output_url = settings.COMPASS_OUTPUT_URL
needs_update = False
# get timestamp of css, if it doesn't exist we need to make it
try:
stat = os.stat(proj_dir + filename + '.css')
output_file_ts = stat.st_mtime
except:
output_file_ts = '1'
css = "<link rel='stylesheet' href='%s?%s' type='text/css' media='%s' />" % (output_url + filename + '.css', output_file_ts, media)
# if we aren't debugging (in production for example), short-cicuit this madness
if not settings.TEMPLATE_DEBUG:
return css
cmd_dict = {
'bin': settings.COMPASS_BIN,
'sass_style': settings.COMPASS_STYLE,
'project_dir': proj_dir,
'output_dir': output_dir,
}
cmd = "%(bin)s compile -s %(sass_style)s --css-dir %(output_dir)s %(project_dir)s" % cmd_dict
(status, output) = getstatusoutput(cmd)
print output
return css
<file_sep>/setup.py
from setuptools import setup, find_packages
LONG_DESCRIPTION = '''Simple Compass integration for Django.'''
CLASSIFIERS = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
KEYWORDS = 'django sass compass css'
setup(name='django-orienteer',
version='0.2',
description='Django Compass App',
long_description=LONG_DESCRIPTION,
author='<NAME>',
author_email='<EMAIL>',
url='http://github.com/sentineldesign/django-orienteer/',
packages=find_packages(),
platforms = ['Platform Independent'],
license = 'Apache License, Version 2.0',
classifiers = CLASSIFIERS,
keywords = KEYWORDS,
) | 288e8db6e489d8c2675ec3b49e68c050e0a59525 | [
"Markdown",
"Python"
] | 3 | Markdown | drewyeaton/django-orienteer | 57518f5da09c05ac36a88e9927f8f6532ed1c78c | 75f8a007952723e1a63d90e4fdbe024ed50fb7ac |
refs/heads/main | <file_sep>#pragma once
class Settings
{
public:
Settings();
~Settings();
int GetScreenWidth();
int GetScreenHeight();
void SetScreenWidth(int screenWidth);
void SetScreenHeight(int screenHeight);
int GetScreenRefreshRate();
float GetMSPerRender();
void SetScreenRefreshRate(int screenRefreshRate);
int GetUpdatesPerSecond();
double GetMSPerUpdate();
private:
int SCREEN_WIDTH, SCREEN_HEIGHT;
int SCREEN_REFRESH_RATE;
double MS_PER_REFRESH;
const int UPDATES_PER_SECOND = 60;
const double MS_PER_UPDATE = 1000 / UPDATES_PER_SECOND;
};
<file_sep>#include "pch.h"
#include "Player.h"
Player::Player()
{
/*this->renderer = renderer;
playerSurface = NULL;*/
}
Player::~Player()
{
}
int Player::GetScore()
{
return 0;
}
float Player::GetXPos()
{
return xPos;
}
float Player::GetYPos()
{
return yPos;
}
void Player::SetXPos(float x)
{
xPos = x;
}
void Player::SetYPos(float y)
{
Player::yPos = y;
}
bool Player::Init(Settings* settings)
{
speed = 5.5;
width = 70;
height = 96;
xPos = settings->GetScreenWidth() / 2 - width / 2;
yPos = settings->GetScreenHeight() / 2 - height / 2;
return true;
}
void Player::Update(bool userInput[8])
{
DoPlayerMovement(userInput);
}
void Player::DoPlayerMovement(bool userInput[8])
{
int xDiff = 0, yDiff = 0;
if (userInput[userInputEnum(movingLeft)])
xDiff -= speed;
if (userInput[userInputEnum(movingRight)])
xDiff += speed;
if (userInput[userInputEnum(movingUp)])
yDiff -= speed;
if (userInput[userInputEnum(movingDown)])
yDiff += speed;
xPos += xDiff;
yPos += yDiff;
}
SDL_Rect Player::Render()
{
rect.w = width;
rect.h = height;
rect.x = xPos;
rect.y = yPos;
return rect;
}
void Player::Clean()
{
//SDL_DestroyTexture(texture);
}
<file_sep>#pragma once
class Time
{
public:
Time();
~Time();
void ResetTimer();
float GetDeltaTime();
};
<file_sep>#pragma once
#include "GameObject.h"
class Entity : public GameObject
{
public:
Entity();
~Entity();
string GetEntityName();
float GetEntityHP();
private:
string name;
float HP;
};
<file_sep>#pragma once
#include "Settings.h"
#include <SDL.h>
#include <SDL_image.h>
#include <string>
class Window
{
public:
Window(Settings* settings);
~Window();
bool InitialiseWindow();
bool InitialiseImages();
void ClearRenderer();
void AddToRenderer(SDL_Rect rect, int renderType);
void DrawToScreen();
void UpdateLife(int num);
void AddScore(int num);
private:
int width, height;
int score, life;
const int numberOffset = 32;
enum renderType { Player, enemy, floor0, floor1, wall, bullet, heart, num , hash};
void DisplayScoreAndLife();
SDL_Window* window = nullptr;
SDL_Renderer* renderer = NULL;
SDL_Texture *playerTexture = nullptr,
*enemyTexture = nullptr,
*wallTexture = nullptr,
*floor0Texture = nullptr,
*floor1Texture = nullptr,
*bulletTexture = nullptr,
*heartTexture = nullptr,
*hashTexture = nullptr;
SDL_Texture *numberTextures[10];
const std::string PLAYER_SPRITE_PATH = "Assets/Textures/Player.png";
const std::string ENEMY_SPRITE_PATH = "Assets/Textures/Zombie.png";
const std::string WALL_SPRITE_PATH = "Assets/Textures/Wall.png";
const std::string FLOOR_0_SPRITE_PATH = "Assets/Textures/Floor0.png";
const std::string FLOOR_1_SPRITE_PATH = "Assets/Textures/Floor1.png";
const std::string BULLET_SPRITE_PATH = "Assets/Textures/Bullet.png";
const std::string HEART_SPRITE_PATH = "Assets/Textures/Heart.png";
const std::string HASH_SPRITE_PATH = "Assets/Textures/Hash.png";
const std::string NUM_SPRITES_PATH[10] = { "Assets/Textures/Number_0.png",
"Assets/Textures/Number_1.png",
"Assets/Textures/Number_2.png",
"Assets/Textures/Number_3.png",
"Assets/Textures/Number_4.png",
"Assets/Textures/Number_5.png",
"Assets/Textures/Number_6.png",
"Assets/Textures/Number_7.png",
"Assets/Textures/Number_8.png",
"Assets/Textures/Number_9.png"};
};
<file_sep>#include "pch.h"
#include "GameObject.h"
GameObject::GameObject()
{
}
GameObject::~GameObject()
{
}
bool GameObject::Init(Settings* settings)
{
return false;
}
bool GameObject::Init(int xPosition, int yPosition)
{
return false;
}
SDL_Rect GameObject::Render()
{
SDL_Rect rect;
rect.h = 0;
rect.w = 0;
rect.x = 0;
rect.y = 0;
return rect;
}
void GameObject::Clean()
{
}
int GameObject::GetWidth()
{
return width;
}
int GameObject::GetHeight()
{
return height;
}
float GameObject::GetXPos()
{
return xPos;
}
float GameObject::GetYPos()
{
return yPos;
}
<file_sep>#pragma once
#include "Entity.h"
class Enemy : public Entity
{
public:
Enemy();
~Enemy();
bool Init(int xPosition, int yPosition) override;
int GetEnemyType();
void DoBehavior(int enemyType);
void Update();
SDL_Rect Render() override;
bool isDefeated;
private:
int enemyType;
float moveSpeed;
};
<file_sep>#include "pch.h"
#include "Bullet.h"
#include <iostream>
Bullet::Bullet(int xPosition, int yPosition, int direction)
{
speed = 10;
DetermineDirection(direction);
xPos = xPosition;
yPos = yPosition;
height = 27;
width = height;
}
Bullet::~Bullet()
{
}
void Bullet::Update()
{
xPos += xChange;
yPos += yChange;
}
SDL_Rect Bullet::Render()
{
SDL_Rect rect;
rect.h = height;
rect.w = width;
rect.x = xPos;
rect.y = yPos;
return rect;
}
void Bullet::DetermineDirection(int direction)
{
enum bulletDirection {Left, Right, Up, Down};
switch (direction)
{
case Left:
xChange = -speed;
yChange = 0;
break;
case Right:
xChange = speed;
yChange = 0;
break;
case Up:
xChange = 0;
yChange = -speed;
break;
case Down:
xChange = 0;
yChange = speed;
break;
}
}
void Bullet::Clean()
{
}
float Bullet::GetXPos()
{
return xPos + width / 2;
}
float Bullet::GetYPos()
{
return yPos + width / 2;
}
<file_sep>#pragma once
#include "MapElement.h"
#include <list>
class Map
{
public:
static list<MapElement> GetWalls();
static list<MapElement> GetFloors();
//[6][10]
private:
const int tileLength = 128;
};
<file_sep>#pragma once
#include "GameObject.h"
class MapElement : public GameObject
{
public:
MapElement(int xPosition, int yPosition, int type);
~MapElement();
void Update();
SDL_Rect Render() override;
void SetMapElementType(int type);
int GetMapElementType();
private:
int mapElementType;
};
<file_sep>#pragma once
#include "Entity.h"
#include <SDL.h>
class Player : public Entity
{
public:
Player();
~Player();
int GetScore();
float GetXPos();
float GetYPos();
void SetXPos(float x);
void SetYPos(float y);
enum userInputEnum { movingLeft, movingRight, movingUp, movingDown, firingLeft, firingRight, firingUp, firingDown };
bool Init(Settings* settings) override;
void Update(bool userInput[8]);
SDL_Rect Render() override;
void Clean() override;
private:
float speed;
void DoPlayerMovement(bool userInput[8]);
SDL_Rect rect;
};
<file_sep>#include "pch.h"
#include "Entity.h"
Entity::Entity()
{
}
Entity::~Entity()
{
}
string Entity::GetEntityName()
{
return name;
}
float Entity::GetEntityHP()
{
return HP;
}
<file_sep>#include "pch.h"
#include "Settings.h"
Settings::Settings()
{
SCREEN_HEIGHT = 768;
SCREEN_WIDTH = 1280;
SCREEN_REFRESH_RATE = 60;
SetScreenRefreshRate(SCREEN_REFRESH_RATE);
}
Settings::~Settings()
{
}
int Settings::GetScreenWidth() { return SCREEN_WIDTH; }
int Settings::GetScreenHeight() { return SCREEN_HEIGHT; }
int Settings::GetScreenRefreshRate() { return SCREEN_REFRESH_RATE; }
float Settings::GetMSPerRender() { return MS_PER_REFRESH; }
int Settings::GetUpdatesPerSecond() { return UPDATES_PER_SECOND; }
double Settings::GetMSPerUpdate() { return MS_PER_UPDATE; }
void Settings::SetScreenWidth(int screenWidth) { SCREEN_WIDTH = screenWidth; }
void Settings::SetScreenHeight(int screenHeight) { SCREEN_HEIGHT = screenHeight; }
void Settings::SetScreenRefreshRate(int screenRefreshRate)
{
SCREEN_REFRESH_RATE = screenRefreshRate;
MS_PER_REFRESH = 1000 / SCREEN_REFRESH_RATE;
}<file_sep>#include "pch.h"
#include "MapElement.h"
MapElement::MapElement(int xPosition, int yPosition, int type)
{
width = 128;
height = width;
SetMapElementType(type);
xPos = xPosition;
yPos = yPosition;
}
MapElement::~MapElement()
{
}
void MapElement::Update()
{
}
SDL_Rect MapElement::Render()
{
SDL_Rect rect;
rect.h = height;
rect.w = width;
rect.x = xPos;
rect.y = yPos;
return rect;
}
void MapElement::SetMapElementType(int type)
{
mapElementType = type;
}
int MapElement::GetMapElementType()
{
return mapElementType;
}
<file_sep>#include "pch.h"
#include "Time.h"
Time::Time()
{
}
Time::~Time()
{
}
void Time::ResetTimer()
{
///this is to reset the timer so that delta time is more accurate throughout the program.
}
float Time::GetDeltaTime()
{
///This should be callable in all gameObject variants. Acts just like Time.deltatime in Unity.
return 0.0f;
}
<file_sep>#pragma once
#include "GameObject.h"
class Bullet : public GameObject
{
public:
Bullet(int xPosition, int yPosition, int direction);
~Bullet();
void Update();
SDL_Rect Render() override;
void DetermineDirection(int direction);
virtual void Clean();
float GetXPos() override;
float GetYPos() override;
private:
float speed;
float xChange, yChange;
};
<file_sep>#pragma once
#include <string>
#include <SDL.h>
#include "Settings.h"
using namespace std;
class GameObject
{
public:
GameObject();
~GameObject();
virtual bool Init(Settings* settings);
virtual bool Init(int xPosition, int yPosition);
virtual SDL_Rect Render();
virtual void Clean();
int GetWidth();
int GetHeight();
virtual float GetXPos();
virtual float GetYPos();
protected:
float xPos, yPos;
float width, height;
};
<file_sep>#include "pch.h"
#include "Map.h"
//[10][6]
enum Type { floor0 = 2, floor1, wall };
list<MapElement> Map::GetWalls()
{
list<MapElement> walls;
//adds top and bottom rows of the grid.
for (int i = 0; i < 10; i++)
{
walls.push_back(MapElement::MapElement(i * 128, 0, wall));
walls.push_back(MapElement::MapElement(i * 128, 5 * 128, wall));
}
//adds the sides of the grid.
for (int i = 1; i < 6; i++)
{
walls.push_back(MapElement::MapElement(0, i * 128, wall));
walls.push_back(MapElement::MapElement(9 * 128, i * 128, wall));
}
return walls;
}
list<MapElement> Map::GetFloors()
{
list<MapElement> floors;
//adds the floors
for (int i = 1; i < 9; i++)
{
for (int j = 1; j < 5; j++)
{
floors.push_back(MapElement::MapElement(i * 128, j * 128, ((i*j) % 2) + 2));
}
}
return floors;
}
<file_sep>// RogueLight.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include "Settings.h"
#include "Player.h"
#include "Enemy.h"
#include "MapElement.h"
#include "Time.h"
#include "Window.h"
#include "Map.h"
#include "Bullet.h"
#include <iostream>
#include <list>
#include <SDL.h>
#include <stdio.h>
using namespace std;
const string ENEMY1_SPRITE_PATH = "Assets\\CharactersSpriteSheet.bmp";
const string MAP_ELEMENTS_SPRITE_PATH = "Assets\\TerrainSpriteSheet.bmp";
Time* timer = new Time();
Settings* settings = new Settings();
enum typesOfEnemies { stationary = 0, standard = 1, fast = 2 };
bool isGameRunning = true;
SDL_Event event;
enum userInputEnum { movingLeft, movingRight, movingUp, movingDown, firingLeft, firingRight, firingUp, firingDown };
bool userInputArray[8] = { false, false, false, false, false, false, false, false };
Window* wind = new Window(settings);
SDL_Surface* frameToRender = NULL;
SDL_Surface* enemyImage = NULL;
Player* player = new Player();
float bulletCooldown = 0, bulletCooldownLength = 1.5;
list<Bullet> bullets;
int life = 4;
float hitCooldown = 0, hitCooldownLength = 1.5;
Enemy enemies[5] = {};
Map map;
list<MapElement> walls;
list<MapElement> floors;
void Shutdown()
{
/*delete &ENEMY1_SPRITE_PATH;
delete &MAP_ELEMENTS_SPRITE_PATH;
delete &isGameRunning;
delete &event;
delete renderer;
delete wind;
delete frameToRender;
delete enemyImage;
delete timer;
delete settings;
delete player;
delete &enemies;
delete &mapElements;*/
}
/*
* This method will check if all condidtions are good to continue running the game.
* If the game needs to shut down all the necessary methods will be called here.
*/
bool UpdateLifecycle()
{
if (isGameRunning)
return true;
else {
Shutdown();
return false;
}
}
/*
GetUserInput() was greatly helped by https://www.libsdl.org/release/SDL-1.2.15/docs/html/guideinputkeyboard.html
The methodology of using a userInputArray is mine but the structure of the switch is theirs.
*/
void GetUserInput()
{
while (SDL_PollEvent(&event))
{
switch (event.type) {
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_a:
userInputArray[userInputEnum(movingLeft)] = true;
break;
case SDLK_d:
userInputArray[userInputEnum(movingRight)] = true;
break;
case SDLK_w:
userInputArray[userInputEnum(movingUp)] = true;
break;
case SDLK_s:
userInputArray[userInputEnum(movingDown)] = true;
break;
case SDLK_LEFT:
userInputArray[userInputEnum(firingLeft)] = true;
break;
case SDLK_RIGHT:
userInputArray[userInputEnum(firingRight)] = true;
break;
case SDLK_UP:
userInputArray[userInputEnum(firingUp)] = true;
break;
case SDLK_DOWN:
userInputArray[userInputEnum(firingDown)] = true;
break;
default:
break;
}
break;
case SDL_KEYUP:
switch (event.key.keysym.sym)
{
case SDLK_a:
userInputArray[userInputEnum(movingLeft)] = false;
break;
case SDLK_d:
userInputArray[userInputEnum(movingRight)] = false;
break;
case SDLK_w:
userInputArray[userInputEnum(movingUp)] = false;
break;
case SDLK_s:
userInputArray[userInputEnum(movingDown)] = false;
break;
case SDLK_LEFT:
userInputArray[userInputEnum(firingLeft)] = false;
break;
case SDLK_RIGHT:
userInputArray[userInputEnum(firingRight)] = false;
break;
case SDLK_UP:
userInputArray[userInputEnum(firingUp)] = false;
break;
case SDLK_DOWN:
userInputArray[userInputEnum(firingDown)] = false;
break;
default:
break;
}
break;
case SDL_QUIT:
isGameRunning = false;
break;
default:
break;
}
}
}
//int i = 0, j = 0;//delete this line.
void UpdateAll()
{
//std::cerr << "U:" << ++i << "\n";//delete this line.
//Updating the map elements
/*for (MapElement me : mapElements)
me.Update();*/
//Updating the enemies
for (Enemy en : enemies)
en.Update();
//Updateing the bullets
list<Bullet>::iterator iter;
for (iter = bullets.begin(); iter != bullets.end(); iter++)
iter->Update();
//Updating the player
player->Update(userInputArray);
}
void RenderAll()
{
enum renderType { Player, enemy, floor0, floor1, wall, bullet };
//std::cerr << "R:" << ++j << "\n";//delete this line.
wind->ClearRenderer();
//Rendering the walls
for (MapElement w : walls)
wind->AddToRenderer(w.Render(), renderType(wall));
//Rendering the floors
for (MapElement f : floors)
wind->AddToRenderer(f.Render(), f.GetMapElementType());
//Rendering the enemies
for (Enemy en : enemies)
if(!en.isDefeated)
wind->AddToRenderer(en.Render(), renderType(enemy));
//Rendering the bullets
for (Bullet b : bullets)
wind->AddToRenderer(b.Render(), renderType(bullet));
//Rendering the player
wind->AddToRenderer(player->Render(), renderType(Player));
//My game loop should have taken care of this.
//SDL_Delay(16);
wind->DrawToScreen();
}
bool WithinRange(float i, float min, float max)
{
if (min < i && i < max)
return true;
return false;
}
void PlayerHitEnemy()
{
if (hitCooldown <= 0)
{
hitCooldown = hitCooldownLength;
printf("player hit enemy\n");
life -= 1;
wind->UpdateLife(life);
if (life <= 0) {
}
cout << life << "\n";
}
}
void BulletHitEnemy(int enemyIndex)
{
enemies[enemyIndex].isDefeated = true;
wind->AddScore(1);
}
void ResolveCollisions()
{
hitCooldown -= 0.05;
float playerLeft = player->GetXPos();
float playerTop = player->GetYPos();
float playerRight = player->GetXPos() + player->GetWidth();
float playerBottom = player->GetYPos() + player->GetHeight();
float entityLeft, entityRight, entityTop, entityBottom;
//list<MapElement>::iterator iter;
//for (iter = walls.begin(); iter != walls.end(); iter++)
//{
// entityLeft = iter->GetXPos();
// entityRight = iter->GetXPos() + iter->GetWidth();
// entityTop = iter->GetYPos();
// entityBottom = iter->GetYPos() + iter->GetHeight();
// /*if (WithinRange(playerLeft, entityLeft, entityRight) && WithinRange(playerTop, entityTop, entityBottom))
// {
// if (WithinRange(playerRight, entityTop, entityBottom) && !WithinRange(playerRight, entityLeft, entityRight))
// {
// player->SetXPos(entityRight);
// }
// if (WithinRange(playerBottom, entityLeft, entityRight) && !WithinRange(playerBottom, entityTop, entityBottom))
// {
// player->SetYPos(entityBottom);
// }
// }*/
// /*if (playerTop < entityBottom && playerBottom > entityBottom && !WithinRange(playerLeft, entityLeft, entityRight) && !WithinRange(playerBottom, entityTop, entityBottom))
// player->SetYPos(entityBottom);*/
// //if(WithinRange(playerTop, entity))
//}
//Handles collisions with walls.
if (playerLeft < 128)
player->SetXPos(128);
if (playerRight > settings->GetScreenWidth() - 128)
player->SetXPos(settings->GetScreenWidth() - 128 - player->GetWidth());
if (playerTop < 128)
player->SetYPos(128);
if (playerBottom > settings->GetScreenHeight() - 128)
player->SetYPos(settings->GetScreenHeight() - 128 - player->GetHeight());
//Looking for collisions between player and enemies.
for (int i = 0; i < 5; i++)
{
if (!enemies[i].isDefeated)
{
entityLeft = enemies[i].GetXPos();
entityRight = enemies[i].GetXPos() + enemies[i].GetWidth();
entityTop = enemies[i].GetYPos();
entityBottom = enemies[i].GetYPos() + enemies[i].GetHeight();
if (WithinRange(playerLeft, entityLeft, entityRight)) {
if (WithinRange(playerTop, entityTop, entityBottom) || WithinRange(playerBottom, entityTop, entityBottom))
PlayerHitEnemy();
}
else if (WithinRange(playerRight, entityLeft, entityRight)) {
if (WithinRange(playerTop, entityTop, entityBottom) || WithinRange(playerBottom, entityTop, entityBottom))
PlayerHitEnemy();
}
}
}
//Looks for bullet collisions.
float bulletRadius = 27 / 2;
list<Bullet>::iterator bull;
for (bull = bullets.begin(); bull != bullets.end(); bull++)
{
//Looks for collisions with enemies first.
for (int i = 0; i < 5; i++)
{
if (!enemies[i].isDefeated)
{
entityLeft = enemies[i].GetXPos();
entityRight = enemies[i].GetXPos() + enemies[i].GetWidth();
entityTop = enemies[i].GetYPos();
entityBottom = enemies[i].GetYPos() + enemies[i].GetHeight();
if (WithinRange(bull->GetXPos() - bulletRadius, entityLeft, entityRight)) {
if (WithinRange(bull->GetYPos() - bulletRadius, entityTop, entityBottom) || WithinRange(bull->GetYPos() + bulletRadius, entityTop, entityBottom))
{
BulletHitEnemy(i);
bullets.erase(bull);
}
}
else if (WithinRange(bull->GetXPos() + bulletRadius, entityLeft, entityRight)) {
if (WithinRange(bull->GetYPos() - bulletRadius, entityTop, entityBottom) || WithinRange(bull->GetYPos() + bulletRadius, entityTop, entityBottom))
{
BulletHitEnemy(i);
bullets.erase(bull);
}
}
}
}
//Looks for collisions with walls.
if (bull->GetXPos() - bulletRadius < 128 || bull->GetXPos() + bulletRadius > settings->GetScreenWidth() - 128 ||
bull->GetYPos() - bulletRadius < 128 || bull->GetYPos() + bulletRadius > settings->GetScreenHeight() - 128)
{
bullets.erase(bull);
}
}
}
enum bulletDirection { Left, Right, Up, Down };
void ShootBullet(int direction)
{
bulletCooldown = bulletCooldownLength;
switch (direction)
{
case bulletDirection(Left):
bullets.push_back(Bullet(player->GetXPos() - 20, player->GetYPos() + player->GetHeight() / 2, bulletDirection(Left)));
break;
case bulletDirection(Right):
bullets.push_back(Bullet(player->GetXPos() + player->GetWidth() + 15, player->GetYPos() + player->GetHeight() / 2, bulletDirection(Right)));
break;
case bulletDirection(Up):
bullets.push_back(Bullet(player->GetXPos() + player->GetWidth() / 2, player->GetYPos() - 5, bulletDirection(Up)));
break;
case bulletDirection(Down):
bullets.push_back(Bullet(player->GetXPos() + player->GetWidth() / 2, player->GetYPos() + player->GetHeight() + 5, bulletDirection(Down)));
break;
}
}
void DoPlayerShooting()
{
bulletCooldown -= 0.05;
if (bulletCooldown <= 0)
{
int direction = -1;
if (userInputArray[userInputEnum(firingLeft)] && !userInputArray[userInputEnum(firingRight)] && !userInputArray[userInputEnum(firingUp)] && !userInputArray[userInputEnum(firingDown)])
direction = bulletDirection(Left);
else if (!userInputArray[userInputEnum(firingLeft)] && userInputArray[userInputEnum(firingRight)] && !userInputArray[userInputEnum(firingUp)] && !userInputArray[userInputEnum(firingDown)])
direction = bulletDirection(Right);
else if (!userInputArray[userInputEnum(firingLeft)] && !userInputArray[userInputEnum(firingRight)] && userInputArray[userInputEnum(firingUp)] && !userInputArray[userInputEnum(firingDown)])
direction = bulletDirection(Up);
else if (!userInputArray[userInputEnum(firingLeft)] && !userInputArray[userInputEnum(firingRight)] && !userInputArray[userInputEnum(firingUp)] && userInputArray[userInputEnum(firingDown)])
direction = bulletDirection(Down);
if (direction != -1)
ShootBullet(direction);
}
}
void CleanAll()
{
player->Clean();
if (player) {
delete player;
player = nullptr;
}
}
//The Game loop was heavily inspired by one found in "Game Programming Patterns" by <NAME> (page 131).
void GameLoop()
{
do
{
GetUserInput();
UpdateAll();
DoPlayerShooting();
ResolveCollisions();
RenderAll();
SDL_Delay(16);
} while (UpdateLifecycle());
}
bool InitialiseObjects()
{
//Load entities here:
if (!player->Init(settings))
{
printf("Player object failed to load.");
return false;
}
int spawnPoints[5][2] = { {150,150},{400,200},{800,500},{950,250},{250,450} };
for (int i = 0; i < 5; i++)
{
enemies[i] = Enemy::Enemy();
if (!enemies[i].Init(spawnPoints[i][0], spawnPoints[i][1]))
{
printf("Enemy failed to initialise.");
return false;
}
}
floors = Map::GetFloors();
walls = Map::GetWalls();
return true;
}
///The main just sets up the window and then starts the game loop. In future, I may choose to load assets here first.
int main(int argc, char* argv[])
{
if (!wind->InitialiseWindow())
{
printf("ERROR: Window failed to initialise! Closing program...");
return 1;
}
if (!InitialiseObjects())
{
printf("ERROR: Objects failed to initialise! Closing program...");
return 1;
}
if (!wind->InitialiseImages())
{
printf("ERROR: Images failed to initialise! Closing program...");
return 1;
}
GameLoop();
return 0;
}<file_sep>#include "pch.h"
#include "Window.h"
#include <iostream>
Window::Window(Settings* settings)
{
width = settings->GetScreenWidth();
height = settings->GetScreenHeight();
score = 0;
life = 4;
}
Window::~Window()
{
delete(&width);
delete(&height);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
/*
* InitialiseWindow() creates the window that the game is ran in.
* Most of this was taken from the class tutorials, specifically the "1. Hello World - SDL.pdf" - accessed on 22/10/2019.
*/
bool Window::InitialiseWindow()
{
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
printf("SDL could not initialise! SDL_Error: %s\n", SDL_GetError());
return false;
}
window = SDL_CreateWindow("Rogue Light", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN);
if (window == nullptr)
{
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
return false;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == nullptr)
{
printf("Renderer could not initialise! SDL_Error: %s\n", SDL_GetError());
return false;
}
}
/*
* I used https://www.youtube.com/watch?v=XS3E7Q_5TMg&list=PLEJbjnzD0g7REtyFUestvXSKTyRFs__lu&index=7 to get started with loading images but modified it shortly after.
*/
bool Window::InitialiseImages()
{
if (IMG_Init(IMG_INIT_PNG) != IMG_INIT_PNG) {
printf("Failed to initialise Image.\n");
return false;
}
//Loading player's image.
SDL_Surface* surface = IMG_Load(PLAYER_SPRITE_PATH.c_str());
if (!surface) {
printf("Player surface failed.\n");
return false;
}
playerTexture = SDL_CreateTextureFromSurface(renderer, surface);
if (!playerTexture) {
printf("Player texture failed.\n");
return false;
}
//Loading enemy's image.
surface = IMG_Load(ENEMY_SPRITE_PATH.c_str());
if (!surface) {
printf("Enemy surface failed.\n");
return false;
}
enemyTexture = SDL_CreateTextureFromSurface(renderer, surface);
if (!enemyTexture) {
printf("Enemy texture failed.\n");
return false;
}
//Loading Wall's image.
surface = IMG_Load(WALL_SPRITE_PATH.c_str());
if (!surface) {
printf("Wall surface failed.\n");
return false;
}
wallTexture = SDL_CreateTextureFromSurface(renderer, surface);
if (!wallTexture) {
printf("Wall texture failed.\n");
return false;
}
//Loading Floor0's image.
surface = IMG_Load(FLOOR_0_SPRITE_PATH.c_str());
if (!surface) {
printf("Floor0 surface failed.\n");
return false;
}
floor0Texture = SDL_CreateTextureFromSurface(renderer, surface);
if (!floor0Texture) {
printf("Floor0 texture failed.\n");
return false;
}
//Loading Floor1's image.
surface = IMG_Load(FLOOR_1_SPRITE_PATH.c_str());
if (!surface) {
printf("Floor1 surface failed.\n");
return false;
}
floor1Texture = SDL_CreateTextureFromSurface(renderer, surface);
if (!floor1Texture) {
printf("Floor1 texture failed.\n");
return false;
}
//Loading Bullet Image.
surface = IMG_Load(BULLET_SPRITE_PATH.c_str());
if (!surface) {
printf("Bullet surface failed.\n");
return false;
}
bulletTexture = SDL_CreateTextureFromSurface(renderer, surface);
if (!bulletTexture) {
printf("Bullet texture failed.\n");
return false;
}
//Loading Number Images
for (int i = 0; i < 10; i++)
{
surface = IMG_Load(NUM_SPRITES_PATH[i].c_str());
if (!surface) {
printf("Number surface failed.\n");
return false;
}
numberTextures[i] = SDL_CreateTextureFromSurface(renderer, surface);
if (!numberTextures[i]) {
printf("Number texture failed.\n");
return false;
}
}
//Loading Heart Image
surface = IMG_Load(HEART_SPRITE_PATH.c_str());
if (!surface) {
printf("Heart surface failed.\n");
return false;
}
heartTexture = SDL_CreateTextureFromSurface(renderer, surface);
if (!heartTexture) {
printf("Heart texture failed.\n");
return false;
}
//Loading Hash Image
surface = IMG_Load(HASH_SPRITE_PATH.c_str());
if (!surface) {
printf("Hash surface failed.\n");
return false;
}
hashTexture = SDL_CreateTextureFromSurface(renderer, surface);
if (!hashTexture) {
printf("Hash texture failed.\n");
return false;
}
SDL_FreeSurface(surface);
return true;
}
void Window::ClearRenderer()
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
}
void Window::DrawToScreen()
{
DisplayScoreAndLife();
SDL_RenderPresent(renderer);
}
void Window::UpdateLife(int num)
{
life = num;
}
void Window::AddScore(int num)
{
score += num;
}
void Window::DisplayScoreAndLife()
{
int xPos = 45, yPos = 45;
SDL_Rect rect;
rect.h = 32;
rect.w = 32;
//hash first
rect.x = xPos;
rect.y = yPos;
AddToRenderer(rect, hash);
//then the score
rect.x += xPos + 5;
AddToRenderer(rect, num);
//then the heart
rect.x += xPos * 2;
AddToRenderer(rect, heart);
//then draw life bar
rect.x += xPos + 5;
if (life < 0)
life = 0;
rect.w = life * 45;
SDL_SetRenderDrawColor(renderer, 147, 13, 49, 255);
SDL_RenderFillRect(renderer, &rect);
}
void Window::AddToRenderer(SDL_Rect rect, int renderType)
{
switch (renderType)
{
case(Player):
SDL_RenderCopy(renderer, playerTexture, nullptr, &rect);
break;
case(enemy):
SDL_RenderCopy(renderer, enemyTexture, nullptr, &rect);
break;
case(floor0):
SDL_RenderCopy(renderer, floor0Texture, nullptr, &rect);
break;
case(floor1):
SDL_RenderCopy(renderer, floor1Texture, nullptr, &rect);
break;
case(wall):
SDL_RenderCopy(renderer, wallTexture, nullptr, &rect);
break;
case(bullet):
SDL_RenderCopy(renderer, bulletTexture, nullptr, &rect);
break;
case(heart):
SDL_RenderCopy(renderer, heartTexture, nullptr, &rect);
break;
case(num):
SDL_RenderCopy(renderer, numberTextures[score], nullptr, &rect);
break;
case(hash):
SDL_RenderCopy(renderer, hashTexture, nullptr, &rect);
break;
default:
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderFillRect(renderer, &rect);
break;
}
}<file_sep># Rogue Light
*A game focusing on game engine building with C++ and SDL by <NAME>.*
## The Game
The player fires bullets horizontally and vertically to defeat the zombie horde.
### The Player
* Moves around with WASD.
* Fires bullets with the arrow keys.
### The Engine
* Uses SDL to render images and to set up the game window.
* Contains a robust game loop.
* I implemented the appropriate update and render methods for each entity.
* Created a tile map for the backdrop.
* Made a hitbox system.
## Current State of Project
The project has been finished and I have moved on to another. I copied the repository here to be public for use in my portfolio.
## Screen Shot

Here we can see the player (bottom, left) shooting a red bullet towards the zombie directly to the right.
<file_sep>#include "pch.h"
#include "Enemy.h"
Enemy::Enemy()
{
}
Enemy::~Enemy()
{
}
bool Enemy::Init(int xPosition, int yPosition)
{
width = 79;
height = 101;
xPos = xPosition;
yPos = yPosition;
isDefeated = false;
return true;
}
int Enemy::GetEnemyType()
{
return enemyType;
}
void Enemy::DoBehavior(int enemyType)
{
}
void Enemy::Update()
{
}
SDL_Rect Enemy::Render()
{
SDL_Rect rect;
rect.h = height;
rect.w = width;
rect.x = xPos;
rect.y = yPos;
return rect;
}
| 149ecee7729803d1e60ae39fc0024705858ac49c | [
"Markdown",
"C++"
] | 22 | C++ | JHuntsGHub/Rogue-Light | 78222f18edbf1fe2ed346cf7feaa7a61d12e99db | a959934b075f6c0ee0557050b1039d788b3f7577 |
refs/heads/master | <file_sep>source 'http://rubygems.org'
gem 'dbi','>=0.4.5'
gem 'mysql'
gem 'dbd-mysql'
gem 'rhoconnect', '5.4.0'
gemfile_path = File.join(File.dirname(__FILE__), ".rcgemfile")
begin
eval(IO.read(gemfile_path))
rescue Exception => e
puts "ERROR: Couldn't read RhoConnect .rcgemfile"
exit 1
end
# Add your application specific gems after this line ...
<file_sep>
require 'DBI'
require 'mysql'
class Employee < SourceAdapter
@@query = 'SELECT id,name FROM employee'
@@create = 'INSERT INTO employee(id,name) VALUES(?,?)'
@@update = 'UPDATE employee SET name= WHERE id = ?'
@@delete = 'DELETE FROM employee WHERE id = ?'
@@url = 'DBI:mysql:final:localhost'
@@user = 'root'
@@pwd = '<PASSWORD>'
def initialize(source)
super(source)
end
def login
# TODO: Login to your data source here if necessary
@dbh = DBI.connect(@@url,@@user,@@pwd)
end
def query(params=nil)
# TODO: Query your backend data source and assign the records
# to a nested hash structure called @result. For example:
# @result = {
# "1"=>{"name"=>"Acme", "industry"=>"Electronics"},
# "2"=>{"name"=>"Best", "industry"=>"Software"}
# }
@result={}
sth = @dbh.prepare(@@query)
sth.execute()
sth.fetch do |row|
item={}
id = row[0]
item[:id] = row[0]
item[:name] = row[1]
@result[id.to_s] = item
end
sth.finish()
end
def create(create_hash)
# TODO: Create a new record in your backend data source
sth = @dbh.prepare(@@create)
sth.execute(create_hash['id'],create_hash['name'])
sth.finish()
create_hash['id']
end
def update(update_hash)
# TODO: Update an existing record in your backend data source
sth = @dbh.prepare(@@update)
sth.execute(update_hash['id'],update_hash['name'])
sth.finish()
end
def delete(delete_hash)
# TODO: write some code here if applicable
# be sure to have a hash key and value for "object"
# for now, we'll say that its OK to not have a delete operation
# raise "Please provide some code to delete a single object in the backend application using the object_id"
sth = @dbh.prepare(@@delete)
sth.execute(delete_hash['id'],delete_hash['name'])
sth.finish()
end
def logoff
# TODO: Logout from the data source if necessary
@dbh.disconnect() if @dbh
end
def store_blob(object,field_name,blob)
# TODO: Handle post requests for blobs here.
# make sure you store the blob object somewhere permanently
raise "Please provide some code to handle blobs if you are using them."
end
end | 07d0c40021b2127eb43daf90a658afc7f8ad6f5a | [
"Ruby"
] | 2 | Ruby | rahulorganize/rahul | 3c5b7a78b392c0ef2a146664d5669cb3b77c729f | f363cbb7feb7490d53a068706425944b4a6fd001 |
refs/heads/master | <file_sep>package net.kencochrane.raven.log4j;
import net.kencochrane.raven.AbstractLoggerTest;
import net.kencochrane.raven.event.Event;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.log4j.NDC;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.UUID;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.hasKey;
import static org.mockito.Mockito.*;
public class SentryAppenderTest extends AbstractLoggerTest {
private Logger logger;
@Before
public void setUp() throws Exception {
logger = Logger.getLogger(SentryAppenderTest.class);
logger.setLevel(Level.ALL);
logger.setAdditivity(false);
logger.addAppender(new SentryAppender(getMockRaven()));
}
@Override
public void logAnyLevel(String message) {
logger.info(message);
}
@Override
public void logAnyLevel(String message, Throwable exception) {
logger.error(message, exception);
}
@Override
public void logAnyLevel(String message, List<String> parameters) {
throw new UnsupportedOperationException();
}
@Override
public String getCurrentLoggerName() {
return logger.getName();
}
@Override
public String getUnformattedMessage() {
throw new UnsupportedOperationException();
}
@Override
@Test
public void testLogLevelConversions() throws Exception {
assertLevelConverted(Event.Level.DEBUG, Level.TRACE);
assertLevelConverted(Event.Level.DEBUG, Level.DEBUG);
assertLevelConverted(Event.Level.INFO, Level.INFO);
assertLevelConverted(Event.Level.WARNING, Level.WARN);
assertLevelConverted(Event.Level.ERROR, Level.ERROR);
assertLevelConverted(Event.Level.FATAL, Level.FATAL);
}
private void assertLevelConverted(Event.Level expectedLevel, Level level) {
logger.log(level, null);
assertLogLevel(expectedLevel);
}
@Override
public void testLogParametrisedMessage() throws Exception {
// Parametrised messages aren't supported
}
@Test
public void testThreadNameAddedToExtra() {
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
logger.info("testMessage");
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getExtra(),
Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, Thread.currentThread().getName()));
}
@Test
public void testMdcAddedToExtra() {
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
String extraKey = UUID.randomUUID().toString();
Object extraValue = mock(Object.class);
MDC.put(extraKey, extraValue);
logger.info("testMessage");
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getExtra(), hasEntry(extraKey, extraValue));
}
@Test
@SuppressWarnings("unchecked")
public void testNdcAddedToExtra() {
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
String extra = UUID.randomUUID().toString();
String extra2 = UUID.randomUUID().toString();
NDC.push(extra);
logger.info("testMessage");
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getExtra(), hasKey(SentryAppender.LOG4J_NDC));
assertThat(eventCaptor.getValue().getExtra().get(SentryAppender.LOG4J_NDC), Matchers.<Object>is(extra));
reset(mockRaven);
NDC.push(extra2);
logger.info("testMessage");
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getExtra(), hasKey(SentryAppender.LOG4J_NDC));
assertThat(eventCaptor.getValue().getExtra().get(SentryAppender.LOG4J_NDC),
Matchers.<Object>is(extra + " " + extra2));
}
}
<file_sep>package net.kencochrane.raven;
import net.kencochrane.raven.dsn.Dsn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
/**
* Factory in charge of creating {@link Raven} instances.
* <p>
* The factories register themselves through the {@link ServiceLoader} system.
* </p>
*/
public abstract class RavenFactory {
private static final ServiceLoader<RavenFactory> AUTO_REGISTERED_FACTORIES = ServiceLoader.load(RavenFactory.class);
private static final Map<String, RavenFactory> MANUALLY_REGISTERED_FACTORIES = new HashMap<String, RavenFactory>();
private static final Logger logger = LoggerFactory.getLogger(RavenFactory.class);
public static void registerFactory(RavenFactory ravenFactory) {
MANUALLY_REGISTERED_FACTORIES.put(ravenFactory.getClass().getName(), ravenFactory);
}
public static Raven ravenInstance() {
return ravenInstance(Dsn.dsnLookup());
}
public static Raven ravenInstance(String dsn) {
return ravenInstance(new Dsn(dsn));
}
public static Raven ravenInstance(Dsn dsn) {
return ravenInstance(dsn, null);
}
public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) {
Raven raven = ravenInstanceFromManualFactories(dsn, ravenFactoryName);
if (raven == null)
raven = ravenInstanceFromAutoFactories(dsn, ravenFactoryName);
if (raven != null)
return raven;
else
throw new IllegalStateException("Couldn't create a raven instance of '" + ravenFactoryName
+ "' for '" + dsn + "'");
}
private static Raven ravenInstanceFromManualFactories(Dsn dsn, String ravenFactoryName) {
Raven raven = null;
if (ravenFactoryName != null && MANUALLY_REGISTERED_FACTORIES.containsKey(ravenFactoryName)) {
RavenFactory ravenFactory = MANUALLY_REGISTERED_FACTORIES.get(ravenFactoryName);
logger.info("Found an appropriate Raven factory for '{}': '{}'", ravenFactoryName, ravenFactory);
raven = ravenFactory.createRavenInstance(dsn);
if (raven == null)
logger.warn("The raven factory '{}' couldn't create an instance of Raven", ravenFactory);
} else if (ravenFactoryName == null) {
for (RavenFactory ravenFactory : MANUALLY_REGISTERED_FACTORIES.values()) {
logger.info("Found an appropriate Raven factory for '{}': '{}'", ravenFactoryName, ravenFactory);
raven = ravenFactory.createRavenInstance(dsn);
if (raven != null) {
break;
} else {
logger.warn("The raven factory '{}' couldn't create an instance of Raven", ravenFactory);
}
}
}
return raven;
}
private static Raven ravenInstanceFromAutoFactories(Dsn dsn, String ravenFactoryName) {
Raven raven = null;
for (RavenFactory ravenFactory : AUTO_REGISTERED_FACTORIES) {
if (ravenFactoryName != null && !ravenFactoryName.equals(ravenFactory.getClass().getName()))
continue;
logger.info("Found an appropriate Raven factory for '{}': '{}'", ravenFactoryName, ravenFactory);
raven = ravenFactory.createRavenInstance(dsn);
if (raven != null) {
break;
} else {
logger.warn("The raven factory '{}' couldn't create an instance of Raven", ravenFactory);
}
}
return raven;
}
public abstract Raven createRavenInstance(Dsn dsn);
}
<file_sep>package net.kencochrane.raven.log4j;
import net.kencochrane.raven.Raven;
import net.kencochrane.raven.connection.Connection;
import org.junit.Test;
import java.io.IOException;
import static org.mockito.Mockito.*;
public class SentryAppenderCloseTest {
@Test
public void testFailedOpenClose() {
// This checks that even if sentry wasn't setup correctly its appender can still be closed.
SentryAppender appender = new SentryAppender();
appender.activateOptions();
appender.close();
}
@Test
public void testMultipleClose() throws IOException {
Raven raven = mock(Raven.class);
Connection connection = mock(Connection.class);
when(raven.getConnection()).thenReturn(connection);
SentryAppender appender = new SentryAppender(raven, true);
appender.close();
appender.close();
verify(connection, times(1)).close();
}
}
<file_sep>package net.kencochrane.raven.log4j2;
import net.kencochrane.raven.Raven;
import net.kencochrane.raven.RavenFactory;
import net.kencochrane.raven.dsn.Dsn;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.event.EventBuilder;
import net.kencochrane.raven.event.interfaces.ExceptionInterface;
import net.kencochrane.raven.event.interfaces.MessageInterface;
import net.kencochrane.raven.event.interfaces.StackTraceInterface;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.DefaultErrorHandler;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.FormattedMessage;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.spi.DefaultThreadContextStack;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.util.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class SentryAppenderTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Raven mockRaven;
@Mock
private RavenFactory mockRavenFactory;
@Mock
private DefaultErrorHandler mockErrorHandler;
private SentryAppender sentryAppender;
@Before
public void setUp() throws Exception {
sentryAppender = new SentryAppender(mockRaven);
setMockErrorHandlerOnAppender(sentryAppender);
when(mockRavenFactory.createRavenInstance(any(Dsn.class))).thenReturn(mockRaven);
RavenFactory.registerFactory(mockRavenFactory);
}
private void setMockErrorHandlerOnAppender(final SentryAppender sentryAppender) {
sentryAppender.setHandler(mockErrorHandler);
Answer<Void> answer = new Answer<Void>() {
private final DefaultErrorHandler actualErrorHandler = new DefaultErrorHandler(sentryAppender);
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
invocation.getMethod().invoke(actualErrorHandler, invocation.getArguments());
return null;
}
};
doAnswer(answer).when(mockErrorHandler).error(anyString());
doAnswer(answer).when(mockErrorHandler).error(anyString(), any(Throwable.class));
doAnswer(answer).when(mockErrorHandler).error(anyString(), any(LogEvent.class), any(Throwable.class));
}
@Test
public void testSimpleMessageLogging() throws Exception {
String message = UUID.randomUUID().toString();
String loggerName = UUID.randomUUID().toString();
String threadName = UUID.randomUUID().toString();
Date date = new Date(1373883196416L);
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
Event event;
sentryAppender.append(new Log4jLogEvent(loggerName, null, null, Level.INFO, new SimpleMessage(message),
null, null, null, threadName, null, date.getTime()));
verify(mockRaven).runBuilderHelpers(any(EventBuilder.class));
verify(mockRaven).sendEvent(eventCaptor.capture());
event = eventCaptor.getValue();
assertThat(event.getMessage(), is(message));
assertThat(event.getLogger(), is(loggerName));
assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName));
assertThat(event.getTimestamp(), is(date));
assertNoErrors();
}
@Test
public void testLogLevelConversions() throws Exception {
assertLevelConverted(Event.Level.DEBUG, Level.TRACE);
assertLevelConverted(Event.Level.DEBUG, Level.DEBUG);
assertLevelConverted(Event.Level.INFO, Level.INFO);
assertLevelConverted(Event.Level.WARNING, Level.WARN);
assertLevelConverted(Event.Level.ERROR, Level.ERROR);
assertLevelConverted(Event.Level.FATAL, Level.FATAL);
}
private void assertLevelConverted(Event.Level expectedLevel, Level level) {
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, null, null, level, new SimpleMessage(""), null));
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getLevel(), is(expectedLevel));
assertNoErrors();
reset(mockRaven);
}
@Test
public void testExceptionLogging() throws Exception {
Exception exception = new Exception();
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.ERROR, new SimpleMessage(""), exception));
verify(mockRaven).sendEvent(eventCaptor.capture());
ExceptionInterface exceptionInterface = (ExceptionInterface) eventCaptor.getValue().getSentryInterfaces()
.get(ExceptionInterface.EXCEPTION_INTERFACE);
Throwable capturedException = exceptionInterface.getThrowable();
assertThat(capturedException.getMessage(), is(exception.getMessage()));
assertThat(capturedException.getStackTrace(), is(exception.getStackTrace()));
assertNoErrors();
}
@Test
public void testLogParametrisedMessage() throws Exception {
String messagePattern = "Formatted message {} {} {}";
Object[] parameters = {"first parameter", new Object[0], null};
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO,
new FormattedMessage(messagePattern, parameters), null));
verify(mockRaven).sendEvent(eventCaptor.capture());
MessageInterface messageInterface = (MessageInterface) eventCaptor.getValue().getSentryInterfaces()
.get(MessageInterface.MESSAGE_INTERFACE);
assertThat(eventCaptor.getValue().getMessage(), is("Formatted message first parameter [] null"));
assertThat(messageInterface.getMessage(), is(messagePattern));
assertThat(messageInterface.getParameters(),
is(Arrays.asList(parameters[0].toString(), parameters[1].toString(), null)));
assertNoErrors();
}
@Test
public void testMarkerAddedToTag() throws Exception {
String markerName = UUID.randomUUID().toString();
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, MarkerManager.getMarker(markerName), null, Level.INFO,
new SimpleMessage(""), null));
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getTags(),
Matchers.<String, Object>hasEntry(SentryAppender.LOG4J_MARKER, markerName));
assertNoErrors();
}
@Test
public void testMdcAddedToExtra() throws Exception {
String extraKey = UUID.randomUUID().toString();
String extraValue = UUID.randomUUID().toString();
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null,
Collections.singletonMap(extraKey, extraValue), null, null, null, 0));
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getExtra(), Matchers.<String, Object>hasEntry(extraKey, extraValue));
assertNoErrors();
}
@Test
@SuppressWarnings("unchecked")
public void testNdcAddedToExtra() throws Exception {
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
ThreadContext.ContextStack contextStack = new DefaultThreadContextStack(true);
contextStack.push(UUID.randomUUID().toString());
contextStack.push(UUID.randomUUID().toString());
contextStack.push(UUID.randomUUID().toString());
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null, null,
contextStack, null, null, 0));
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat((List<String>) eventCaptor.getValue().getExtra().get(SentryAppender.LOG4J_NDC),
equalTo(contextStack.asList()));
assertNoErrors();
}
@Test
public void testSourceUsedAsStacktrace() throws Exception {
StackTraceElement location = new StackTraceElement(UUID.randomUUID().toString(),
UUID.randomUUID().toString(),
UUID.randomUUID().toString(), 42);
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null, null, null,
null, location, 0));
verify(mockRaven).sendEvent(eventCaptor.capture());
StackTraceInterface stackTraceInterface = (StackTraceInterface) eventCaptor.getValue().getSentryInterfaces()
.get(StackTraceInterface.STACKTRACE_INTERFACE);
assertThat(stackTraceInterface.getStackTrace(), arrayWithSize(1));
assertThat(stackTraceInterface.getStackTrace()[0], is(location));
assertNoErrors();
}
@Test
public void testCulpritWithSource() throws Exception {
StackTraceElement location = new StackTraceElement("a", "b", "c", 42);
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null, null, null,
null, location, 0));
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getCulprit(), is("a.b(c:42)"));
assertNoErrors();
}
@Test
public void testCulpritWithoutSource() throws Exception {
String loggerName = UUID.randomUUID().toString();
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
sentryAppender.append(new Log4jLogEvent(loggerName, null, null, Level.INFO, new SimpleMessage(""), null));
verify(mockRaven).sendEvent(eventCaptor.capture());
assertThat(eventCaptor.getValue().getCulprit(), is(loggerName));
assertNoErrors();
}
@Test
public void testClose() throws Exception {
sentryAppender.stop();
verify(mockRaven.getConnection(), never()).close();
sentryAppender = new SentryAppender(mockRaven, true);
setMockErrorHandlerOnAppender(sentryAppender);
sentryAppender.stop();
verify(mockRaven.getConnection()).close();
assertNoErrors();
}
@Test
public void testAppendFailIfCurrentThreadSpawnedByRaven() throws Exception {
try {
Raven.RAVEN_THREAD.set(true);
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null));
verify(mockRaven, never()).sendEvent(any(Event.class));
assertNoErrors();
} finally {
Raven.RAVEN_THREAD.remove();
}
}
@Test
public void testRavenFailureDoesNotPropagate() throws Exception {
doThrow(new UnsupportedOperationException()).when(mockRaven).sendEvent(any(Event.class));
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null));
verify(mockErrorHandler, never()).error(anyString());
verify(mockErrorHandler, never()).error(anyString(), any(Throwable.class));
verify(mockErrorHandler).error(anyString(), any(LogEvent.class), any(Throwable.class));
}
@Test
public void testLazyInitialisation() throws Exception {
String dsnUri = "proto://private:public@host/1";
sentryAppender = new SentryAppender();
setMockErrorHandlerOnAppender(sentryAppender);
sentryAppender.setDsn(dsnUri);
sentryAppender.setRavenFactory(mockRavenFactory.getClass().getName());
sentryAppender.start();
verify(mockRavenFactory, never()).createRavenInstance(any(Dsn.class));
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null));
verify(mockRavenFactory).createRavenInstance(eq(new Dsn(dsnUri)));
assertNoErrors();
}
@Test
public void testDsnAutoDetection() throws Exception {
try {
String dsnUri = "proto://private:public@host/1";
System.setProperty(Dsn.DSN_VARIABLE, dsnUri);
sentryAppender = new SentryAppender();
setMockErrorHandlerOnAppender(sentryAppender);
sentryAppender.setRavenFactory(mockRavenFactory.getClass().getName());
sentryAppender.start();
sentryAppender.append(new Log4jLogEvent(null, null, null, Level.INFO, new SimpleMessage(""), null));
verify(mockRavenFactory).createRavenInstance(eq(new Dsn(dsnUri)));
assertNoErrors();
} finally {
System.clearProperty(Dsn.DSN_VARIABLE);
}
}
private void assertNoErrors() {
verify(mockErrorHandler, never()).error(anyString());
verify(mockErrorHandler, never()).error(anyString(), any(Throwable.class));
verify(mockErrorHandler, never()).error(anyString(), any(LogEvent.class), any(Throwable.class));
}
}
| 44c6f725a24924e2346a83ee5847d248a19d5994 | [
"Java"
] | 4 | Java | werkshy/raven-java | c5eb4f63a9e480d155f01dbd8f5d1eeb016b2658 | 02ad78bda88e91ac8ba17e7296ef6ae9d23f442f |
refs/heads/master | <repo_name>semsevens/movie-go<file_sep>/models/movies.py
#-*- coding: utf-8 -*-
import urllib
import re
from models.nuomi import Nuomi
from models.taobao import Taobao
from models.meituan import Meituan
from functions.file import pickling, unpickling, saveFile
from functions.sort import multipleKeySort
class Movies:
# user interface
def getMovies(self):
return self.movies
def getLabels(self):
return self.labels
def getCinemasName(self):
return self.main.getCinemasName()
def getPinyinCn(self):
return self.pinyinCn
# initialize
def __init__(self, latest = False):
self.main = Nuomi()
self.taobao = Taobao()
self.meituan = Meituan()
self.platformNames = ['nuomi', 'taobao', 'meituan']
self.pinyinCn = {'nuomi': u'糯米', 'taobao': u'淘宝', 'meituan': u'美团'}
self.picklingFile = 'data/pickling.txt'
self.movies = {}
self.morningEnd = "13:00"
self.afternoonEnd = "18:00"
self.nightEnd = "24:00"
self.labels = {'a': u'早场', 'b': u'中场', 'c': u'晚场'}
self.getData(latest)
self.translate(latest)
self.save(latest)
# main methods
def getData(self, latest = False):
if latest:
self.getFlesh()
else:
self.getOld()
return self.movies
def translate(self, latest):
if latest:
translatedData = []
for movieId, theMovie in self.movies.items():
movie = {}
movie['id'] = movieId
movie['info'] = theMovie['info']
rows = []
for cinemaId, theDates in theMovie['cinemas'].items():
for theDate, theRows in theDates.items():
for theRow in theRows.values():
row = {'cinema-id': cinemaId, 'date': theDate}
row.update(theRow)
row['label'] = self.getLabel(row['start'])
platforms = []
for platformName in self.platformNames:
platform = {}
if (platformName + '-price') in row:
platform['name'] = platformName
platform['price'] = row[platformName + '-price']
platform['link'] = row[platformName + '-link']
platforms.append(platform)
multipleKeySort(platforms, ['price'])
row['platforms'] = platforms
rows.append(row)
multipleKeySort(rows, ['date','label', 'cinema-id', 'start'])
rows = self.rowsToGroup(rows, ['date', 'label', 'cinema-id'])
movie['data'] = rows
translatedData.append(movie)
self.movies = translatedData
self.addLowest()
def addLowest(self):
for movieGroup in self.movies:
for dateGroup in movieGroup['data']:
for labelGroup in dateGroup['data']:
for cinemaGroup in labelGroup['data']:
cinemaGroup['data'].sort(key=lambda x:x['platforms'][0]['price'])
cinemaGroup['lowest-price'] = cinemaGroup['data'][0]['platforms'][0]['price']
for movieGroup in self.movies:
for dateGroup in movieGroup['data']:
for labelGroup in dateGroup['data']:
labelGroup['data'].sort(key=lambda x:x['lowest-price'])
def save(self, latest):
if latest:
pickling(self.picklingFile, self.movies)
# internal methods for translate
def getLabel(self, time): # can create a the best judging tree
if time < self.morningEnd:
return 'a'
elif time < self.afternoonEnd:
return 'b'
else:
return 'c'
def rowsToGroup(self, rows, keys):
groups = []
firstKey = keys[0]
nowValue = rows[0][firstKey]
group = {}
group[firstKey] = nowValue
group['data'] = []
for row in rows:
if row[firstKey] == nowValue:
del row[firstKey]
group['data'].append(row)
else:
groups.append(group)
nowValue = row[firstKey]
group = {}
group[firstKey] = nowValue
group['data'] = []
del row[firstKey]
group['data'].append(row)
groups.append(group)
rows = groups
if len(keys) > 1:
for group in groups:
group['data'] = self.rowsToGroup(group['data'], keys[1:])
return rows
# internal methods for getData
def getFlesh(self):
self.movies = self.main.data()
self.mergeData(self.taobao)
self.mergeData(self.meituan)
def getOld(self):
self.movies = self.unpickling(self.picklingFile)
# internal methods for getFlesh
def mergeData(self, obj):
missMovieCount = 0
missCinemaCount = 0
data = obj.data()
for movieId, theMovie in data.items():
movieTitle = obj.mapMovieTitle(movieId)
targetMovieId = self.main.remapMovieTitle(movieTitle)
if targetMovieId == -1:
missMovieCount += 1
print('targetMovieId Error')
continue
for cinemaId, theCinema in theMovie['cinemas'].items():
cinemaName = obj.mapCinemaName(cinemaId)
targetCinemaId = self.main.remapCinemaName(cinemaName)
if targetCinemaId not in self.movies[targetMovieId]['cinemas']:
for d in self.movies[targetMovieId]['cinemas'].keys():
print(d)
print('target cinema id : ' + targetCinemaId)
self.movies[targetMovieId]['cinemas'][targetCinemaId] = {}
for date, theRows in theCinema.items():
if date not in self.movies[targetMovieId]['cinemas'][targetCinemaId]:
for d in self.movies[targetMovieId]['cinemas'][targetCinemaId].keys():
print(d)
print('target date : ' + date)
self.movies[targetMovieId]['cinemas'][targetCinemaId][date] = {}
for startKey, theRow in theRows.items():
if startKey not in self.movies[targetMovieId]['cinemas'][targetCinemaId][date].keys():
for sk in self.movies[targetMovieId]['cinemas'][targetCinemaId][date]:
print(sk)
print('target: ' + startKey)
self.movies[targetMovieId]['cinemas'][targetCinemaId][date][startKey] = {}
self.movies[targetMovieId]['cinemas'][targetCinemaId][date][startKey].update(theRow)
print('missMoive: ' + str(missMovieCount))
print('missCinema: ' + str(missCinemaCount))
<file_sep>/functions/file.py
#-*- coding: utf-8 -*-
import json
def saveFile(filename, data):
f_obj = open(filename, 'w', encoding = 'utf-8')
f_obj.write(data)
f_obj.close()
def pickling(filename, data):
f = open(filename, 'w', encoding = 'utf-8')
json.dump(data, f)
f.close()
def unpickling(filename):
f = open(filename, 'r', encoding = 'utf-8')
data = json.load(f)
f.close()
return data
<file_sep>/models/nuomi.py
#-*- coding: utf-8 -*-
import urllib
import re
from functions.http import getPageCode
from functions.file import pickling, unpickling
from functions.match import fuzzyMatch
class Nuomi:
# user interface
def data(self):
return self.movies
def mapMovieTitle(self, movieId):
return self.moviesIdToTitle[movieId]
def remapMovieTitle(self, movieTitle):
for targetMovieTitle in self.moviesTitleToId.keys():
if fuzzyMatch(targetMovieTitle, movieTitle) > self.movieTitleAccuracy:
return self.moviesTitleToId[targetMovieTitle]
print(movieTitle)
return -1
def mapCinemaName(self, cinemaId):
return self.cinemasIdToName[cinemaId]
def remapCinemaName(self, cinemaName):
for targetCinemaName in self.cinemasNameToId.keys():
if fuzzyMatch(targetCinemaName, cinemaName) > self.cinemaNameAccuracy:
return self.cinemasNameToId[targetCinemaName]
return -1
def getCinemasName(self):
return self.cinemasIdToName
# initialize
def __init__(self, latest = False):
self.moviesFile = 'data/nuomi-movies.txt'
self.moviesIdToTitleFile = 'data/nuomi-m-id-title.txt'
self.movieTitleAccuracy = 50
self.cinemaNameAccuracy = 70
self.movies = {}
self.cinemas = ['<KEY>', '89fd4ea32ca31a5ee4e965a5', '610852113eacfcb8c51b7506']
self.moviesIdToTitle = {}
self.moviesTitleToId = {}
self.cinemasNameToId = {}
self.cinemasIdToName = {'bba<KEY>': u'大地影院(北京昌平菓岭假日广场店)' ,'89fd4ea32ca31a5ee4e965a5': u'昌平保利影剧院' ,'610852113eacfcb8c51b7506': u'首都电影院(昌平店)' }
for cinemaId, cinemaName in self.cinemasIdToName.items():
self.cinemasNameToId[cinemaName] = cinemaId
self.getData(latest)
self.save(latest)
def getData(self, latest = False):
if latest:
self.getFlesh()
else:
self.getOld()
return self.movies
def save(self, latest):
if latest:
pickling(self.moviesFile, self.movies)
pickling(self.moviesIdToTitleFile, self.moviesIdToTitle)
# internal methods for getData
def getOld(self):
self.movies = unpickling(self.moviesFile)
self.moviesIdToTitle = unpickling(self.moviesIdToTitleFile)
for movieId, movieTitle in self.moviesIdToTitle.items():
self.moviesTitleToId[movieTitle] = movieId
def getFlesh(self):
try:
for cinemaId in self.cinemas:
cinemaUrl = self.getCinemaUrl(cinemaId)
pageCode = getPageCode(cinemaUrl)
# pattern = re.compile('<p class="cb-tel">.*?([\d].*?)</p>', re.S)
# items = re.findall(pattern, pageCode)
# cinemaTel = items[0].strip()
pattern = re.compile('movieId="(.*?)".*?<img src="(.*?)"', re.S)
items = re.findall(pattern, pageCode)
for item in items:
movieId = item[0]
movieImg = item[1]
if movieId not in self.movies:
self.movies[movieId] = {}
self.movies[movieId]['info'] = {}
self.movies[movieId]['cinemas'] = {}
self.movies[movieId]['info']['img'] = movieImg
self.movies[movieId]['cinemas'][cinemaId] = {}
movieUrl = self.getMovieUrl(cinemaId, movieId)
pageCode = getPageCode(movieUrl)
if 'title' not in self.movies[movieId]['info']:
self.getMovieInfo(pageCode, self.movies[movieId]['info'])
self.moviesIdToTitle[movieId] = self.movies[movieId]['info']['title']
self.moviesTitleToId[self.movies[movieId]['info']['title']] = movieId
self.getMovieCinema(pageCode, self.movies[movieId]['cinemas'][cinemaId])
except urllib.error.URLError as e:
if hasattr(e, 'code'):
print(e.code)
if hasattr(e, 'reason'):
print(e.reason)
return self.movies
# internal methods for getFlesh
def getCinemaUrl(self, cinemaId):
cinemaUrl = 'http://bj.nuomi.com/cinema/' + cinemaId
return cinemaUrl
def getMovieUrl(self, cinemaId, movieId):
movieUrl = 'http://bj.nuomi.com/pcindex/main/timetable?cinemaid=' + cinemaId + '&mid=' + movieId + '&needMovieInfo=1&tploption=1&_=1450784678479'
return movieUrl
def getMovieInfo(self, pageCode, movieInfo):
pattern = re.compile('h2>.*?>(.*?)</a>.*?/span>(.*?)</p>.*?/span>(.*?)</p>.*?/span>(.*?)</p>.*?/span>(.*?)</li>.*?/span>(.*?)</li>.*?/span>(.*?)</li>.*?/span>(.*?)</p>', re.S)
items = re.findall(pattern, pageCode)
for item in items:
movieInfo['title'] = item[0].strip()
movieInfo['director'] = item[1].strip()
movieInfo['starring'] = item[2].strip()
movieInfo['type'] = item[3].strip()
movieInfo['country'] = item[4].strip()
movieInfo['premiere'] = item[5].strip()
movieInfo['length'] = item[6].strip()
plot = item[7].replace('\r\n', '').strip()
plot = plot.replace(u'>展开<', '')
plot = plot.replace(u'>收起<', '')
pattern = re.compile('<.*?>', re.S)
plot = re.sub(pattern, '', plot)
movieInfo['plot'] = plot
return movieInfo
def getMovieCinema(self, pageCode, movieCinema):
dates = []
pattern = re.compile('movie-date" mon="element=.*?([\d\.]*?)"', re.S)
items = re.findall(pattern, pageCode)
for item in items:
temp = item.strip().split('.')
date = temp[0] + '-' + temp[1]
dates.append(date)
movieCinema[date] = {}
dateIndex = 0;
maxTime = '-00:00'
pattern = re.compile('td>(.*?)<.*?time">(.*?)<.*?<td>(.*?)</td>.*?td>(.*?)</td>.*?price">(.*?)</span>.*?del>(.*?)</del>.*?<a href="(.*?)".*?</td>', re.S)
items = re.findall(pattern, pageCode)
for item in items:
startTime = item[0].strip()
if startTime < maxTime:
dateIndex = dateIndex + 1
maxTime = startTime
record = movieCinema[dates[dateIndex]][startTime[0:2] + startTime[3:5]] = {};
record['start'] = startTime
record['end'] = item[1].strip()
record['version'] = item[2].strip()
record['room'] = item[3].strip()
record['nuomi-price'] = item[4].strip().replace('¥','')[0:2]
record['nuomi-link'] = ('http://bj.nuomi.com' + item[6].strip()).replace('&','&')
return movieCinema
<file_sep>/app.py
#-*- coding: utf-8 -*-
from flask import Flask, request, render_template, send_from_directory
from models.movies import Movies
app = Flask(__name__)
m = Movies(True)
movies = m.getMovies()
labels = m.getLabels()
cinemasName = m.getCinemasName()
pinyinCn = m.getPinyinCn()
@app.route('/', methods = ['GET', 'POST'])
def home():
return render_template('index.html', movies = movies, labels = labels, cinemasName = cinemasName, pinyinCn = pinyinCn)
@app.route('/js/<path:path>')
def send_js(path):
return send_from_directory('js', path)
@app.route('/css/<path:path>')
def send_css(path):
return send_from_directory('css', path)
@app.route('/lib/<path:path>')
def send_lib(path):
return send_from_directory('lib', path)
@app.route('/images/<path:path>')
def send_images(path):
return send_from_directory('images', path)
if __name__ == '__main__':
app.run(debug = True)
<file_sep>/js/map.js
// Shortcuts
var map = new AMap.Map('container',{
zoom: 14,
resizeEnable: true,
center: [116.26,40.215]
});
var pots = new Array('昌平首都电影院', '昌平保利影剧院', '昌平大地影院');
var tools = new Array('公交', '步行', '驾车');
var start = "北京化工大学北校区 5号楼";
var current_status = '';
var tmp = '';
//浏览器定位
map.plugin('AMap.Geolocation', function(){
geolocation = new AMap.Geolocation({
timeout: 10000, //超过10秒后停止定位,默认:无穷大
maximumAge: 0, //定位结果缓存0毫秒,默认:0
showButton: true,
buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy:true
});
map.addControl(geolocation);
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
});
function onComplete(data) {
var str=['定位成功'];
addMarker1(data);
str.push('经度:' + data.position.getLng());
str.push('纬度:' + data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
}
function onError(data) {
document.getElementById('tip').innerHTML = '定位失败';
}
//手动定位
// var autoOptions = {
// input: "tipinput"
// };
// var auto = new AMap.Autocomplete(autoOptions);
// var placeSearch = new AMap.PlaceSearch({
// map: map
// var placeSearch = new AMap.PlaceSearch({
// map: map
// });
// });
// AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
// function select(e) {
// placeSearch.setCity(e.poi.adcode);
// placeSearch.search(e.poi.name); //关键字查询查询
// // marker.on("click", function(e){
// // tmp = marker.getPosition();
// // LoctoAdress(tmp);
// // });
// }
//手动定位
// 关键字输入框调用下拉菜单
$('#keyword').focus(function(){
if ($('#result-box').attr('aria-expanded') == 'false' || $('#result-box').attr('aria-expanded') == undefined)
$('#result-box').attr('aria-expanded', 'true').addClass('uk-open');
});
$('#keyword').blur(function(){
if ($('#result-box').attr('aria-expanded') == 'true')
$('#result-box').attr('aria-expanded', 'false').removeClass('uk-open');
});
// 监听关键字输入框
map.plugin(["AMap.Autocomplete"], function() {
//判断是否IE浏览器
if (navigator.userAgent.indexOf("MSIE") > 0) {
document.getElementById("keyword").onpropertychange = autoSearch;
}
else {
document.getElementById("keyword").oninput = autoSearch;
}
});
// 关键字自动检索
function autoSearch() {
var keywords = document.getElementById("keyword").value;
var auto;
var autoOptions = {
pageIndex:1,
pageSize:10,
city: "" //城市,默认全国
};
autocomplete= new AMap.Autocomplete(autoOptions);
autocomplete.search(keywords, function(status, result){
var item = '';
var items = '';
if (status == 'complete') {
for (var i = 0; i < result['count']; i++) {
item = '<li><a id="' + result['tips'][i]['adcode'] + '" href="#" onMouseDown="select(this)">' + result['tips'][i]['name'] + '</a></li>';
items += item;
}
}
$('#result').html(items); // 将检索到的结果覆盖到下拉菜单
});
}
// 检索函数
var placeSearch = new AMap.PlaceSearch({
map: map
});
// 选择下拉菜单的某项后触发检索
function select(e) {
var adcode = $(e).attr('id');
var name = $(e).text();
placeSearch.setCity(adcode);
placeSearch.search(name);
}
//右键定位
var menu=new ContextMenu(map);
function ContextMenu(map) {
var me = this;
this.mouseTool = new AMap.MouseTool(map);
this.contextMenuPositon = null;
var content = '<div class="startpoint"></div>';
this.contextMenu = new AMap.ContextMenu({isCustom: true, content: content});
map.on('rightclick', function(e) {
me.contextMenu.open(map, e.lnglat);
me.contextMenuPositon = e.lnglat;
// alert(me.contextMenuPositon);
UIkit.notify({
message: '<i class=\'uk-icon-check\'></i> 坐标:' + me.contextMenuPositon + '',
status: 'success',
timeout: 3000,
pos: 'top-center'
});
LoctoAdress(me.contextMenuPositon);
});
}
ContextMenu.prototype.addMarkerMenu=function () {
this.mouseTool.close();
var marker = new AMap.Marker({
map: map,
position: this.contextMenuPositon
});
this.contextMenu.close();
}
//当前位置标记
function addMarker1(d){
var marker = new AMap.Marker({
map:map,
content: '<div class="startpoint"></div>',
position:[d.position.getLng(), d.position.getLat()]
});
marker.on("click", function(e){
tmp = marker.getPosition();
LoctoAdress(tmp);
});
}
//选择影院
function Select_Cinema(i){
for(var j = 0; j < pots.length; j++)
if(i == j){
map.clearMap();
current_status = pots[i];
AdresstoLoc(current_status);
}
}
//电影院标记
function addMarker2(i,d){
var marker = new AMap.Marker({
map:map,
content: '<div class="tag"></div>',
position:[d.location.getLng(), d.location.getLat()]
});
map.plugin('AMap.AdvancedInfoWindow',function(){
var infoWindow = new AMap.AdvancedInfoWindow({
content: d.formattedAddress,
offset: {x:0, y:-30},
asOrigin: true
});
marker.on("click", function(e){
infoWindow.open(map, marker.getPosition());
});
});
}
//周边搜索
function searchNearBy(i,d){
AMap.plugin('AMap.PlaceSearch', function(){
var placeSearch = new AMap.PlaceSearch({
pageSize: 8,
type: '电影院',
pageIndex: 1,
city: "北京",
map: map,
panel: "panel"
});
var cpoint = [d.location.getLng(), d.location.getLat()];
placeSearch.searchNearBy('', cpoint, 5000, function(status, result) {
});
});
}
//选择出行方式
function Select_Tool(i){
map.clearMap( );
switch(i){
case 0:
//bus
AMap.plugin('AMap.Transfer', function(){
var transOptions = new AMap.Transfer({
map: map,
city: '北京市',
panel:'panel',
policy: AMap.TransferPolicy.LEAST_TIME //乘车策略
});
transOptions.search([{keyword: start},{keyword: current_status}], function(status, result){
});
});break;
case 1:
//walk
AMap.plugin('AMap.Walking', function(){
var walking = new AMap.Walking({
map:map,
city:'北京',
panel: "panel"
});
walking.search([{keyword: start},{keyword: current_status}], function(status, result){
});
});break;
case 2:
//car
AMap.plugin('AMap.Driving', function(){
var driving = new AMap.Driving({
map: map,
city: '北京',
panel: 'panel',
policy: AMap.DrivingPolicy.LEAST_DISTANCE
});
driving.search([{keyword: start},{keyword: current_status}], function(status, result){
});
});break;
default: break;
}map.clearMap();
}
//地址-坐标
function AdresstoLoc(data){
map.plugin('AMap.Geocoder', function(){
var geocoder = new AMap.Geocoder({
city: '北京'
});
geocoder.getLocation(data, function(status, result) {
if(status === 'complete' && result.info === 'OK') {
geocoder_CallBack(result);
}
else
UIkit.notify({
message: status + '',
status: 'success',
timeout: 3000,
pos: 'top-center'
});
// kalert(status);
});
});
}
function geocoder_CallBack(data){
var geocode = data.geocodes;
for(var i = 0; i < geocode.length; i++){
addMarker2(i, geocode[i]);
searchNearBy(i, geocode[i]);
}
map.setFitView();
}
//坐标-地址
function LoctoAdress(data){
map.plugin('AMap.Geocoder', function(){
var geocoder = new AMap.Geocoder({
radius: 1000,
extensions: "all"
});
geocoder.getAddress(data, function(status, result) {
if(status === 'complete' && result.info === 'OK') {
start = result.regeocode.formattedAddress; //返回地址描述
// alert(start);
UIkit.notify({
message: start + '',
status: 'info',
timeout: 3000,
pos: 'top-center'
});
}
else
// alert(status);
UIkit.notify({
message: status + '',
status: 'info',
timeout: 3000,
pos: 'top-center'
});
});
});
}
<file_sep>/functions/sort.py
from __future__ import division #
import operator
#confirm the maximum key-value in the first place in list
def MakeMaxHeap(rows, key, E, S):
for i in range((E-S)//2 - 1, -1, -1):
t = i + S
m = 2*i + 1 + S
n = 2*i + 2 + S
if operator.lt(rows[t][key], rows[m][key]):
# swap(rows[t], rows[m])
temp = rows[t]
rows[t] = rows[m]
rows[m] = temp
if operator.lt(n, E) and operator.lt(rows[t][key], rows[n][key]):
# swap(rows[i], rows[n])
temp = rows[t]
rows[t] = rows[n]
rows[n] = temp
#exchange key-value in the first place and the last place in the list
def heapsort(rows, divs, key, E, S): #E-endpoint S-startpoint
mark = E - 1
for i in range(E - 1, S, -1):
temp = rows[i]
rows[i] = rows[S]
rows[S] = temp
#compare with the newest highest key-value
#occur difference
#mark the boundary's position for the next sort
if rows[mark][key] != rows[i][key]:
divs.append(mark)
mark = i
MakeMaxHeap(rows, key, i, S)
#heapsort in each bucket in one key-value
#update new buckets for the other key-value
def multipleKeySort(rows, keys):
divs = []
divs.append(0)
divs.append(len(rows))
for key in keys:
divs.sort()
for i in range(len(divs) - 1, 0, -1):
MakeMaxHeap(rows, key, divs[i], divs[i - 1])
heapsort(rows, divs, key, divs[i], divs[i - 1])
<file_sep>/README.md
# movie-go
Get price from taobao, nuomi and meituan
# NOTICE
python version 3
# INSTALL
pip install -r requirements.txt
# USAGE
python app.py
then, visit http://127.0.0.1:5000
<file_sep>/models/meituan.py
#-*- coding: utf-8 -*-
import re
import urllib
from functions.http import getPageCode
from functions.file import pickling, unpickling
from functions.match import fuzzyMatch
class Meituan:
# user interface
def data(self):
return self.movies
def mapMovieTitle(self, movieId):
return self.moviesIdToTitle[movieId]
def remapMovieTitle(self, movieTitle):
for targetMovieTitle in self.moviesTitleToId.keys():
if fuzzyMatch(targetMovieTitle, movieTitle) > self.movieTitleAccuracy:
return self.moviesTitleToId[targetMovieTitle]
def mapCinemaName(self, cinemaId):
return self.cinemasIdToName[cinemaId]
def remapCinemaName(self, cinemaName):
for targetCinemaName in self.cinemasNameToId.keys():
if fuzzyMatch(targetCinemaName, cinemaName) > self.cinemaNameAccuracy:
return self.cinemasNameToId[targetCinemaName]
# initialize
def __init__(self, latest = False):
self.moviesFile = 'data/meituan-movies.txt'
self.moviesIdToTitleFile = 'data/meituan-m-id-title.txt'
self.movieTitleAccuracy = 50
self.cinemaNameAccuracy = 50
self.movies = {}
self.cinemas = ['8186','66','50']
self.moviesIdToTitle = {}
self.moviesTitleToId = {}
self.cinemasNameToId = {}
self.cinemasIdToName = {'8186': u'首都电影院(悦荟万科广场店)' ,'66': u'大地影院(昌平菓岭店)' ,'50': u'昌平保利影剧院(佳莲时代广场店)' }
for cinemaId, cinemaName in self.cinemasIdToName.items():
self.cinemasNameToId[cinemaName] = cinemaId
self.getData(latest)
self.save(latest)
def getData(self, latest = False):
if latest:
self.getFlesh()
else:
self.getOld()
return self.movies
def save(self, latest):
if latest:
pickling(self.moviesFile, self.movies)
pickling(self.moviesIdToTitleFile, self.moviesIdToTitle)
# internal methods for getData
def getOld(self):
self.movies = unpickling(self.moviesFile)
self.moviesIdToTitle = unpickling(self.moviesIdToTitleFile)
for movieId, movieTitle in self.moviesIdToTitle.items():
self.moviesTitleToId[movieTitle] = movieId
def getFlesh(self):
try:
for cinemaId in self.cinemas:
# t = self.cinemasMap[cinemaId];
# url = 'http://bj.meituan.com/shop/'+ t
# pagecode = getPageCode(url)
# pattern = re.compile("class='field-title'>电话:.*?>(.*?)</div>", re.S)
# items = re.findall(pattern, pagecode)
# for item in items:
# cinemaTel = item.strip()
cinemaUrl = self.getCinemaUrl(cinemaId)
pagecode = getPageCode(cinemaUrl)
pattern = re.compile('"cat":(.*?)"id":(.*?),.*?"nm":"(.*?)"', re.S)
items = re.findall(pattern, pagecode)
for item in items:
movieinfo = item[0].strip();
movieId = item[1].strip();
if movieId not in self.movies:
self.movies[movieId] = {}
self.movies[movieId]['cinemas'] = {}
self.movies[movieId]['info'] = {}
self.movies[movieId]['info']['title'] = item[2].strip()
self.moviesIdToTitle[movieId] = self.movies[movieId]['info']['title']
self.moviesTitleToId[self.movies[movieId]['info']['title']] = movieId
self.movies[movieId]['cinemas'][cinemaId] = {}
self.getMovieStatus(movieinfo, self.movies[movieId]['cinemas'][cinemaId])
except urllib.error.URLError as e:
if hasattr(e, 'code'):
print(e.code)
if hasattr(e, 'reason'):
print(e.reason)
# for movieId, theMovie in self.movies.items():
# for cinemaId, theCinema in theMovie['cinemas'].items():
# for Date, theRows in theCinema.items():
# for theRow in theRows.values():
# print(theRow)
def getCinemaUrl(self, cinemaId):
cinemaUrl = 'http://platform.mobile.meituan.com/open/maoyan/v1/cinema/'+cinemaId+'/movies/shows.json?'
return cinemaUrl
def getMovieStatus(self, pagecode, movieStatus):
dates = {}
pattern = re.compile('"showDate":"(.*?)"', re.S)
dates = re.findall(pattern, pagecode)
for date in dates:
pattern = re.compile('"dt":"'+date+'","tm":"(.*?)",.*?"seatUrl":"(.*?)","sell":(.*?),"sellPr":"(.*?)",', re.S)
date = date[5:]
movieStatus[date] = {}
infos = re.findall(pattern, pagecode)
for info in infos:
status = info[2].strip()
if(status):
start = info[0].strip()
record = movieStatus[date][start[0:2] + start[3:5]] = {}
record['start'] = info[0].strip()
record['meituan-link'] = info[1].strip()
record['meituan-price'] = info[3].strip()[0:2]
print(movieStatus)
return movieStatus
<file_sep>/functions/match.py
#-*- coding: utf-8 -*-
def fuzzyMatch(strA, strB):
count = 0
shortLen = 0
result = 0.0
if len(strA) < len(strB):
shortLen = len(strA)
for b in strB:
for a in strA:
if a == b:
count += 1
else:
shortLen = len(strB)
for a in strA:
for b in strB:
if b == a:
count += 1
if shortLen != 0:
result = count * 100 / shortLen
else:
result = 0
# print('@@@@@@@@@@@@@')
# print(strA)
# print(strB)
# print(result)
# print('@@@@@@@@@@@@@')
return result
<file_sep>/models/taobao.py
#-*- coding: utf-8 -*-
import re
import urllib
from functions.http import getPageCode
from functions.file import pickling, unpickling
from functions.match import fuzzyMatch
class Taobao:
# user interface
def data(self):
return self.movies
def mapMovieTitle(self, movieId):
return self.moviesIdToTitle[movieId]
def remapMovieTitle(self, movieTitle):
for targetMovieTitle in self.moviesTitleToId.keys():
if fuzzyMatch(targetMovieTitle, movieTitle) > self.movieTitleAccuracy:
return self.moviesTitleToId[targetMovieTitle]
def mapCinemaName(self, cinemaId):
return self.cinemasIdToName[cinemaId]
def remapCinemaName(self, cinemaName):
for targetCinemaName in self.cinemasNameToId.keys():
if fuzzyMatch(targetCinemaName, cinemaName) > self.cinemaNameAccuracy:
return self.cinemasNameToId[targetCinemaName]
print(cinemaName)
return -1
# initialize
def __init__(self, latest = False):
self.moviesFile = 'data/taobao-movies.txt'
self.moviesIdToTitleFile = 'data/taobao-m-id-title.txt'
self.movieTitleAccuracy = 50
self.cinemaNameAccuracy = 70
self.movies = {}
self.cinemas = ['15516','4379', '5386']
self.moviesIdToTitle = {}
self.moviesTitleToId = {}
self.cinemasNameToId = {}
self.cinemasIdToName = {'15516': u'首都电影院昌平店','4379': u'北京昌平保利影剧院','5386': u'北京大地影院菓岭假日广场店'}
for cinemaId, cinemaName in self.cinemasIdToName.items():
self.cinemasNameToId[cinemaName] = cinemaId
self.getData(latest)
self.save(latest)
def getData(self, latest = False):
if latest:
self.getFlesh()
else:
self.getOld()
return self.movies
def save(self, latest):
if latest:
pickling(self.moviesFile, self.movies)
pickling(self.moviesIdToTitleFile, self.moviesIdToTitle)
# internal methods for getData
def getOld(self):
self.movies = unpickling(self.moviesFile)
self.moviesIdToTitle = unpickling(self.moviesIdToTitleFile)
for movieId, movieTitle in self.moviesIdToTitle.items():
self.moviesTitleToId[movieTitle] = movieId
def getFlesh(self):
try:
for cinemaId in self.cinemas:
# url = 'https://dianying.taobao.com/cinemaDetail.htm?cinemaId='+cinemaId
# pageCode = getPageCode(url)
# pattern = re.compile('<li>联系电话:(.*?)</li>', re.S)
# items = re.findall(pattern, pageCode)
# for item in items:
# cinemaTel = item.strip()
cinemaUrl = self.getCinemaUrl(cinemaId)
c_pageCode = getPageCode(cinemaUrl)
pattern = re.compile('showId=(.*?)&', re.S)
items = re.findall(pattern, c_pageCode)
items = set(items)
for item in items:
movieId = item
movieUrl = 'http://dianying.taobao.com/cinemaDetailSchedule.htm?cinemaId='+ cinemaId +'&showId='+ movieId
m_pageCode = getPageCode(movieUrl)
if movieId not in self.movies:
self.movies[movieId] = {}
self.movies[movieId]['info'] = {}
self.movies[movieId]['cinemas'] = {}
self.getMovieInfo(m_pageCode, self.movies[movieId]['info'])
self.moviesIdToTitle[movieId] = self.movies[movieId]['info']['title']
self.moviesTitleToId[self.movies[movieId]['info']['title']] = movieId
pattern = re.compile('showId='+movieId+'&showDate=(.*?)&', re.S)
dates = re.findall(pattern, m_pageCode)
dates = set(dates)
self.movies[movieId]['cinemas'][cinemaId] = {}
for date in dates:
url = 'http://dianying.taobao.com/cinemaDetailSchedule.htm?cinemaId='+ cinemaId +'&showId='+ movieId +'&showDate='+date
date = date[5:]
d_pagecode = getPageCode(url)
self.movies[movieId]['cinemas'][cinemaId][date] = {}
self.getMovieStatus(d_pagecode, self.movies[movieId]['cinemas'][cinemaId][date])
except urllib.error.URLError as e:
if hasattr(e, 'code'):
print(e.code)
if hasattr(e, 'reason'):
print(e.reason)
return self.movies
def getCinemaUrl(self, cinemaId):
cinemaUrl = 'https://dianying.taobao.com/cinemaDetailSchedule.htm?cinemaId='+ cinemaId
return cinemaUrl
def getMovieInfo(self, pageCode, movieInfo):
pattern = re.compile('src="(.*?)">.*?href=\'#\'>(.*?)<small.*?\'score\'>(.*?)</small>.*看点:(.*?)</li>.*?导演:(.*?)</li>.*?主演:(.*?)</li>.*?类型:(.*?)</li>.*?制片国家/地区:(.*?)</li>.*?语言:(.*?)</li>.*?/ul>', re.S)
items = re.findall(pattern, pageCode)
for item in items:
movieInfo['img'] = item[0].strip()
movieInfo['title'] = item[1].strip()
movieInfo['score'] = item[2].strip()
movieInfo['light'] = item[3].strip()
movieInfo['director'] = item[4].strip()
movieInfo['staring'] = item[5].strip()
movieInfo['type'] = item[6].strip()
movieInfo['country'] = item[7].strip()
movieInfo['lang'] = item[8].strip()
return movieInfo
def getMovieStatus(self, pageCode, movieStatus):
pattern= re.compile('class="hall-time".*?bold">(.*?)</em>(.*?)</td>.*?"hall-type">(.*?)</td>.*?"hall-name">(.*?)</td>.*?<label>(.*?)</label>.*?"now">(.*?)</em>.*?"old">(.*?)</del>.*?href="(.*?)">', re.S)
items = re.findall(pattern, pageCode)
for item in items:
start = item[0].strip()
record = movieStatus[start[0:2] + start[3:5]] = {}
record['start'] = item[0].strip()
record['end'] = item[1].strip()
record['version'] = item[2].strip()
record['room'] = item[3].strip()
record['seats'] = item[4].strip()
record['taobao-price'] = item[5].strip()[0:2]
# record['now-price'] = item[6].strip()
record['taobao-link'] = item[7].strip()
return movieStatus
<file_sep>/functions/http.py
#-*- coding: utf-8 -*-
import urllib
import urllib.request
def getPageCode(url, headers = { 'Connection': 'Keep-Alive', 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko' }):
request = urllib.request.Request(url, headers = headers)
print('waiting for response: ' + url)
response = urllib.request.urlopen(request)
pageCode = response.read().decode('utf-8')
print('response successfully')
return pageCode
| faeea898c648651b44bb1be27970325542d1f9aa | [
"JavaScript",
"Python",
"Markdown"
] | 11 | Python | semsevens/movie-go | 57a20a00a1a01601514ed844b60744e8f3b25c42 | 4728af78fc5e217b3a4b476ac02fac033d7d897d |
refs/heads/master | <repo_name>neoelec/raccoon_dds<file_sep>/raccoon_dds_sw.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include "raccoon_dds_sw.h"
raccoon_dds_sw::raccoon_dds_sw()
: running(false)
{
}
const char *raccoon_dds_sw::get_name(void)
{
return name;
}
void raccoon_dds_sw::set_frequency(unsigned long frequency)
{
this->frequency = frequency;
}
unsigned long raccoon_dds_sw::get_frequency(void)
{
return frequency;
}
void raccoon_dds_sw::loop(void)
{
prologue();
while (running)
text();
epilogue();
}
void raccoon_dds_sw::start(void)
{
running = true;
}
void raccoon_dds_sw::stop(void)
{
running = false;
}
<file_sep>/raccoon_dds_menu.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_menu.ino
*
* File Description :
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 27/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include <EEPROM.h>
#include <stdio.h>
#include "raccoon_dds.h"
#include "raccoon_dds_menu.h"
#include "raccoon_dds_sw_ecg.h"
#include "raccoon_dds_sw_ramp.h"
#include "raccoon_dds_sw_sawtooth.h"
#include "raccoon_dds_sw_sine.h"
#include "raccoon_dds_sw_square.h"
#include "raccoon_dds_sw_triangle.h"
static const char __raccoon_dds_menu_magic[] PROGMEM = __DATE__ " " __TIME__;
struct raccoon_dds_menu_save_data {
char magic[ARRAY_SIZE(__raccoon_dds_menu_magic)];
raccoon_dds_sw *dds_sw;
unsigned long frequency;
};
static raccoon_dds_menu_save_data *__raccoon_dds_menu_save_data;
static bool __raccoon_dds_menu_verify_magic(void)
{
size_t i;
char tmp_e, tmp_p;
for (i = 0; i < ARRAY_SIZE(__raccoon_dds_menu_magic); i++) {
tmp_e = EEPROM.read((int)(&__raccoon_dds_menu_save_data->magic[i]));
tmp_p = pgm_read_byte(&__raccoon_dds_menu_magic[i]);
if (tmp_p != tmp_e)
return false;
}
return true;
}
static void __raccoon_dds_menu_save_magic(void)
{
size_t i;
char tmp_p;
for (i = 0; i < ARRAY_SIZE(__raccoon_dds_menu_magic); i++) {
tmp_p = pgm_read_byte(&__raccoon_dds_menu_magic[i]);
EEPROM.write((int)(&__raccoon_dds_menu_save_data->magic[i]), tmp_p);
}
}
static void __raccoon_dds_menu_load_dds_sw(void)
{
union {
raccoon_dds_sw *dds_sw;
unsigned long frequency;
uint8_t b[];
} saved;
uint8_t *ptr;
size_t i;
ptr = (uint8_t *)&__raccoon_dds_menu_save_data->dds_sw;
for (i = 0; i < sizeof(raccoon_dds_sw *); i++)
saved.b[i] = EEPROM.read((int)ptr + i);
dds_sw = saved.dds_sw;
ptr = (uint8_t *)&__raccoon_dds_menu_save_data->frequency;;
for (i = 0; i < sizeof(unsigned long ); i++)
saved.b[i] = EEPROM.read((int)ptr + i);
dds_sw->set_frequency(saved.frequency);
}
static void __raccoon_dds_menu_save_dds_sw(void)
{
union {
raccoon_dds_sw *dds_sw;
unsigned long frequency;
uint8_t b[];
} saved;
uint8_t *ptr;
size_t i;
saved.dds_sw = dds_sw;
ptr = (uint8_t *)&__raccoon_dds_menu_save_data->dds_sw;
for (i = 0; i < sizeof(raccoon_dds_sw *); i++)
EEPROM.write((int)ptr + i, saved.b[i]);
saved.frequency = dds_sw->get_frequency();
ptr = (uint8_t *)&__raccoon_dds_menu_save_data->frequency;;
for (i = 0; i < sizeof(unsigned long ); i++)
EEPROM.write((int)ptr + i, saved.b[i]);
}
/* */
class raccoon_dds_submenu_mode : public raccoon_dds_submenu {
public:
raccoon_dds_submenu_mode();
static raccoon_dds_submenu_mode *get_instance(void)
{
return singleton;
}
virtual void init(void);
virtual void key_up(void);
virtual void key_down(void);
private:
void change_item(void);
static raccoon_dds_submenu_mode *singleton;
raccoon_dds_sw *item_current;
raccoon_dds_sw **item_list;
size_t item_nr;
size_t item_idx;
};
#define RACCOON_DDS_SUBMENU_MODE_SW_MAX 6
static raccoon_dds_sw *__raccoon_dds_submenu_mode_item_list[RACCOON_DDS_SUBMENU_MODE_SW_MAX];
raccoon_dds_submenu_mode::raccoon_dds_submenu_mode()
{
item_nr = 0;
item_list = __raccoon_dds_submenu_mode_item_list;
item_list[item_nr++] = raccoon_dds_sw_sine::get_instance();
item_list[item_nr++] = raccoon_dds_sw_square::get_instance();
item_list[item_nr++] = raccoon_dds_sw_triangle::get_instance();
item_list[item_nr++] = raccoon_dds_sw_ramp::get_instance();
item_list[item_nr++] = raccoon_dds_sw_sawtooth::get_instance();
item_list[item_nr++] = raccoon_dds_sw_ecg::get_instance();
item_idx = 0;
item_current = item_list[item_idx];
}
static raccoon_dds_submenu_mode __raccoon_dds_submenu_mode;
raccoon_dds_submenu_mode *raccoon_dds_submenu_mode::singleton =
&__raccoon_dds_submenu_mode;
static const char __menu_change_mode[] PROGMEM = "- Change Func.";
void raccoon_dds_submenu_mode::init(void)
{
dds_hw->lcd_clear();
dds_hw->lcd_print_P(__menu_change_mode);
if (dds_sw != item_current) {
item_idx = 0;
while (dds_sw != item_current)
item_current = item_list[++item_idx];
}
change_item();
}
void raccoon_dds_submenu_mode::key_up(void)
{
if (item_idx)
item_idx--;
else
item_idx = item_nr - 1;
change_item();
}
void raccoon_dds_submenu_mode::key_down(void)
{
item_idx++;
item_idx = item_idx % item_nr;
change_item();
}
void raccoon_dds_submenu_mode::change_item(void)
{
char buf[8];
dds_hw->lcd_clear_row(1);
dds_hw->lcd_set_cursor(0, 1);
sprintf(buf, "%u. ", item_idx + 1);
dds_hw->lcd_print(buf);
item_current = item_list[item_idx];
dds_hw->lcd_print_P(item_current->get_name());
item_current->set_frequency(dds_sw->get_frequency());
dds_sw = item_current;
}
/* */
void raccoon_dds_submenu::init(void)
{
}
void raccoon_dds_submenu::loop(void)
{
}
void raccoon_dds_submenu::key_up(void)
{
}
void raccoon_dds_submenu::key_down(void)
{
}
/* */
class raccoon_dds_submenu_frequency : public raccoon_dds_submenu {
public:
raccoon_dds_submenu_frequency(unsigned long step);
virtual void init(void);
virtual void key_up(void);
virtual void key_down(void);
private:
void display_frequency(void);
void increase_frequency(unsigned long step);
void decrease_frequency(unsigned long step);
unsigned long frequency;
unsigned long step;
uint8_t lcd_col;
};
static const char __menu_mode_change_frequency_0[] PROGMEM = "- Change Freq.";
static const char __menu_mode_change_frequency_1[] PROGMEM = "Freq : ";
raccoon_dds_submenu_frequency::raccoon_dds_submenu_frequency(unsigned long step)
{
this->step = step;
lcd_col = (uint8_t)(11. - log10f((float)step));
}
void raccoon_dds_submenu_frequency::init(void)
{
dds_hw->lcd_clear();
dds_hw->lcd_print_P(__menu_mode_change_frequency_0);
frequency = dds_sw->get_frequency();
display_frequency();
dds_hw->lcd_blink();
}
void raccoon_dds_submenu_frequency::key_up(void)
{
frequency += step;
if (frequency > RACCOON_DDS_HW_MAX_FREQUENCY)
frequency = RACCOON_DDS_HW_MAX_FREQUENCY;
dds_sw->set_frequency(frequency);
display_frequency();
}
void raccoon_dds_submenu_frequency::key_down(void)
{
if (frequency > step)
frequency -= step;
else
frequency = RACCOON_DDS_HW_MIN_FREQUENCY;
if (frequency < RACCOON_DDS_HW_MIN_FREQUENCY)
frequency = RACCOON_DDS_HW_MIN_FREQUENCY;
dds_sw->set_frequency(frequency);
display_frequency();
}
void raccoon_dds_submenu_frequency::display_frequency(void)
{
char buf[16];
dds_hw->lcd_set_cursor(0, 1);
dds_hw->lcd_print_P(__menu_mode_change_frequency_1);
sprintf(buf, "%05lu Hz", frequency);
dds_hw->lcd_print(buf);
dds_hw->lcd_set_cursor(lcd_col, 1);
}
static raccoon_dds_submenu_frequency __raccoon_dds_submenu_frequency_10k(10000);
static raccoon_dds_submenu_frequency __raccoon_dds_submenu_frequency_1k(1000);
static raccoon_dds_submenu_frequency __raccoon_dds_submenu_frequency_100(100);
static raccoon_dds_submenu_frequency __raccoon_dds_submenu_frequency_10(10);
static raccoon_dds_submenu_frequency __raccoon_dds_submenu_frequency_1(1);
/* */
#define RACCOON_DDS_MENU_SUBMENU_MAX 6
static raccoon_dds_submenu *__raccoon_dds_menu_submenu_list[RACCOON_DDS_MENU_SUBMENU_MAX];
raccoon_dds_menu::raccoon_dds_menu()
{
submenu_nr = 0;
submenu_list = __raccoon_dds_menu_submenu_list;
submenu_list[submenu_nr++] = raccoon_dds_submenu_mode::get_instance();
submenu_list[submenu_nr++] = &__raccoon_dds_submenu_frequency_1;
submenu_list[submenu_nr++] = &__raccoon_dds_submenu_frequency_10;
submenu_list[submenu_nr++] = &__raccoon_dds_submenu_frequency_100;
submenu_list[submenu_nr++] = &__raccoon_dds_submenu_frequency_1k;
submenu_list[submenu_nr++] = &__raccoon_dds_submenu_frequency_10k;
submenu_idx = 0;
submenu_current = submenu_list[submenu_idx];
}
static raccoon_dds_menu __raccoon_dds_menu;
raccoon_dds_menu *raccoon_dds_menu::singleton = &__raccoon_dds_menu;
raccoon_dds_menu *raccoon_dds_menu::get_instance(void)
{
return singleton;
}
void raccoon_dds_menu::init(void)
{
state = E_RACCOON_DDS_MENU_ENTERED;
keycode = E_RACCOON_DDS_HW_KEYCODE_INVALID;
if (!__raccoon_dds_menu_verify_magic()) {
dds_sw = raccoon_dds_sw_sine::get_instance();
dds_sw->set_frequency(1000);
__raccoon_dds_menu_save_magic();
__raccoon_dds_menu_save_dds_sw();
} else {
__raccoon_dds_menu_load_dds_sw();
}
}
bool raccoon_dds_menu::run(void)
{
switch (state) {
case E_RACCOON_DDS_MENU_ENTERED:
dds_hw->run_led_off();
change_submenu();
sw_previous = dds_sw;
freq_previous = dds_sw->get_frequency();
state = E_RACCOON_DDS_MENU_SUBMENU;
break;
case E_RACCOON_DDS_MENU_SUBMENU:
switch (keycode) {
case E_RACCOON_DDS_HW_KEYCODE_RUN:
if (dds_sw != sw_previous ||
freq_previous != dds_sw->get_frequency())
__raccoon_dds_menu_save_dds_sw();
display_current_setting();
dds_hw->run_led_on();
dds_sw->start();
state = E_RACCOON_DDS_MENU_DEACTIVE;
return false;
case E_RACCOON_DDS_HW_KEYCODE_LEFT:
if (submenu_idx)
submenu_idx--;
else
submenu_idx = submenu_nr - 1;
change_submenu();
break;
case E_RACCOON_DDS_HW_KEYCODE_RIGHT:
submenu_idx++;
submenu_idx = submenu_idx % submenu_nr;
change_submenu();
break;
case E_RACCOON_DDS_HW_KEYCODE_UP:
submenu_current->key_up();
break;
case E_RACCOON_DDS_HW_KEYCODE_DOWN:
submenu_current->key_down();
break;
default:
break;
}
keycode = E_RACCOON_DDS_HW_KEYCODE_INVALID;
state = E_RACCOON_DDS_MENU_REDY_KEY;
break;
default:
submenu_current->loop();
}
return true;
}
void raccoon_dds_menu::loop(void)
{
if (E_RACCOON_DDS_MENU_DEACTIVE == state)
return;
while (run()) ;
}
void raccoon_dds_menu::handler(void)
{
raccoon_dds_keystate_t keystate;
keystate = dds_hw->button_state();
keycode = dds_hw->button_keycode();
if (E_RACCOON_DDS_KEYSTATE_PRESSED != keystate) {
keycode = E_RACCOON_DDS_HW_KEYCODE_INVALID;
return;
}
if (E_RACCOON_DDS_MENU_DEACTIVE == state &&
E_RACCOON_DDS_HW_KEYCODE_RUN == keycode) {
state = E_RACCOON_DDS_MENU_ENTERED;
dds_sw->stop();
keycode = E_RACCOON_DDS_HW_KEYCODE_INVALID;
} else if (E_RACCOON_DDS_MENU_REDY_KEY == state) {
state = E_RACCOON_DDS_MENU_SUBMENU;
} else {
keycode = E_RACCOON_DDS_HW_KEYCODE_INVALID;
}
}
void raccoon_dds_menu::change_submenu(void)
{
submenu_current = submenu_list[submenu_idx];
submenu_current->init();
}
void raccoon_dds_menu::display_current_setting(void)
{
char buf[16];
dds_hw->lcd_clear();
dds_hw->lcd_set_cursor(0, 0);
dds_hw->lcd_print("Func : ");
dds_hw->lcd_print_P(dds_sw->get_name());
dds_hw->lcd_set_cursor(0, 1);
dds_hw->lcd_print("Freq : ");
sprintf(buf, "%-5lu Hz", dds_sw->get_frequency());
dds_hw->lcd_print(buf);
}
<file_sep>/raccoon_dds_sw_sawtooth.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_sawtooth.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "raccoon_dds_sw_sawtooth.h"
static const char __raccoon_dds_sw_sawtooth_name[] PROGMEM = "SawTooth";
#define RACCOON_DDS_MACH_SAWTOOTH_LOOKUP_TBL \
0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, \
0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, \
0xef, 0xee, 0xed, 0xec, 0xeb, 0xea, 0xe9, 0xe8, \
0xe7, 0xe6, 0xe5, 0xe4, 0xe3, 0xe2, 0xe1, 0xe0, \
0xdf, 0xde, 0xdd, 0xdc, 0xdb, 0xda, 0xd9, 0xd8, \
0xd7, 0xd6, 0xd5, 0xd4, 0xd3, 0xd2, 0xd1, 0xd0, \
0xcf, 0xce, 0xcd, 0xcc, 0xcb, 0xca, 0xc9, 0xc8, \
0xc7, 0xc6, 0xc5, 0xc4, 0xc3, 0xc2, 0xc1, 0xc0, \
0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, \
0xb7, 0xb6, 0xb5, 0xb4, 0xb3, 0xb2, 0xb1, 0xb0, \
0xaf, 0xae, 0xad, 0xac, 0xab, 0xaa, 0xa9, 0xa8, \
0xa7, 0xa6, 0xa5, 0xa4, 0xa3, 0xa2, 0xa1, 0xa0, \
0x9f, 0x9e, 0x9d, 0x9c, 0x9b, 0x9a, 0x99, 0x98, \
0x97, 0x96, 0x95, 0x94, 0x93, 0x92, 0x91, 0x90, \
0x8f, 0x8e, 0x8d, 0x8c, 0x8b, 0x8a, 0x89, 0x88, \
0x87, 0x86, 0x85, 0x84, 0x83, 0x82, 0x81, 0x80, \
0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, \
0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, \
0x6f, 0x6e, 0x6d, 0x6c, 0x6b, 0x6a, 0x69, 0x68, \
0x67, 0x66, 0x65, 0x64, 0x63, 0x62, 0x61, 0x60, \
0x5f, 0x5e, 0x5d, 0x5c, 0x5b, 0x5a, 0x59, 0x58, \
0x57, 0x56, 0x55, 0x54, 0x53, 0x52, 0x51, 0x50, \
0x4f, 0x4e, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, \
0x47, 0x46, 0x45, 0x44, 0x43, 0x42, 0x41, 0x40, \
0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, \
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, \
0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, \
0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, \
0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, \
0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, \
0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, \
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00
static const uint8_t __raccoon_dds_sw_sawtooth_lookup_tbl[] PROGMEM = {
RACCOON_DDS_MACH_SAWTOOTH_LOOKUP_TBL,
RACCOON_DDS_MACH_SAWTOOTH_LOOKUP_TBL
};
raccoon_dds_sw_sawtooth::raccoon_dds_sw_sawtooth(const uint8_t *lookup_tbl)
{
this->lookup_tbl = lookup_tbl;
name = __raccoon_dds_sw_sawtooth_name;
}
static raccoon_dds_sw_sawtooth __raccoon_dds_sw_sawtooth(__raccoon_dds_sw_sawtooth_lookup_tbl);
raccoon_dds_sw_sawtooth *raccoon_dds_sw_sawtooth::singleton =
&__raccoon_dds_sw_sawtooth;
raccoon_dds_sw_sawtooth *raccoon_dds_sw_sawtooth::get_instance(void)
{
return singleton;
}
<file_sep>/raccoon_dds_hw_uno.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_hw_uno.ino
*
* File Description :
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 27/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include <stdint.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "pcint.h"
#include "raccoon_dds_hw.h"
#include "raccoon_dds_hw_uno.h"
/* FIXME: is this a good idea? */
static LiquidCrystal_I2C __raccoon_dds_hw_uno_lcd(
RACCOON_DDS_HW_UNO_LCD_SLAVE,
RACCOON_DDS_HW_UNO_LCD_COL,
RACCOON_DDS_HW_UNO_LCD_ROW);
raccoon_dds_hw_uno::raccoon_dds_hw_uno()
: button_pin(A0),
power_led_pin(12), run_led_pin(13),
lcd(&__raccoon_dds_hw_uno_lcd),
lcd_row_max(RACCOON_DDS_HW_UNO_LCD_ROW - 1),
lcd_col_max(RACCOON_DDS_HW_UNO_LCD_COL - 1)
{
}
static raccoon_dds_hw_uno __raccoon_dds_hw_uno;
raccoon_dds_hw_uno *raccoon_dds_hw_uno::singleton =
&__raccoon_dds_hw_uno;
raccoon_dds_hw_uno *raccoon_dds_hw_uno::get_instance(void)
{
return singleton;
}
void raccoon_dds_hw_uno::init(void)
{
RACCOON_DDS_HW_DDR = 0xFF;
RACCOON_DDS_HW_PORT = 0x00;
Serial.end();
pinMode(button_pin, INPUT);
pcint_enable(button_pin);
pinMode(power_led_pin, OUTPUT);
digitalWrite(power_led_pin, HIGH);
pinMode(run_led_pin, OUTPUT);
digitalWrite(run_led_pin, LOW);
lcd->begin();
lcd->backlight();
lcd_row = lcd_col = 0;
}
raccoon_dds_keystate_t raccoon_dds_hw_uno::button_state(void)
{
return digitalRead(button_pin) ? E_RACCOON_DDS_KEYSTATE_NOT_PRESSED
: E_RACCOON_DDS_KEYSTATE_PRESSED;
}
#define __M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(__resistor_lower, \
__resistor_upper) \
((__resistor_lower) * 1024 / (__resistor_upper + __resistor_lower) + \
RACCOON_DDS_HW_UNO_KEYADC_MARGIN)
#define M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(__nr_pulldn) \
__M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(__nr_pulldn * \
(RACCOON_DDS_HW_UNO_KEYADC_PULLDN), \
RACCOON_DDS_HW_UNO_KEYADC_PULLUP)
#define RACCOON_DDS_HW_UNO_KEYADC_LEFT \
M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(0)
#define RACCOON_DDS_HW_UNO_KEYADC_DOWN \
M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(1)
#define RACCOON_DDS_HW_UNO_KEYADC_UP \
M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(2)
#define RACCOON_DDS_HW_UNO_KEYADC_RIGHT \
M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(3)
#define RACCOON_DDS_HW_UNO_KEYADC_RUN \
M_RACCOON_DDS_HW_UNO_KEYADC_VALUE(4)
#define RACCOON_DDS_HW_UNO_KEYADC_NR_RETRY 20
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
raccoon_morse_keycode_t raccoon_dds_hw_uno::button_keycode(void)
{
int adc_tmp = analogRead(button_pin);
int adc_raw, adc_min, adc_max;
size_t i;
adc_raw = adc_tmp;
adc_max = adc_tmp;
adc_min = adc_tmp;
for (i = 0; i < RACCOON_DDS_HW_UNO_KEYADC_NR_RETRY - 1; i++) {
adc_tmp = analogRead(button_pin);
adc_raw += adc_tmp;
adc_min = min(adc_tmp, adc_min);
adc_max = max(adc_tmp, adc_max);
}
adc_raw -= (adc_min + adc_max);
adc_raw /= (RACCOON_DDS_HW_UNO_KEYADC_NR_RETRY - 2);
if (RACCOON_DDS_HW_UNO_KEYADC_RUN < adc_raw)
return E_RACCOON_DDS_HW_KEYCODE_INVALID;
else if (RACCOON_DDS_HW_UNO_KEYADC_RIGHT < adc_raw)
return E_RACCOON_DDS_HW_KEYCODE_RUN;
else if (RACCOON_DDS_HW_UNO_KEYADC_UP < adc_raw)
return E_RACCOON_DDS_HW_KEYCODE_RIGHT;
else if (RACCOON_DDS_HW_UNO_KEYADC_DOWN < adc_raw)
return E_RACCOON_DDS_HW_KEYCODE_UP;
else if (RACCOON_DDS_HW_UNO_KEYADC_LEFT < adc_raw)
return E_RACCOON_DDS_HW_KEYCODE_DOWN;
return E_RACCOON_DDS_HW_KEYCODE_LEFT;
}
void raccoon_dds_hw_uno::power_led_on(void)
{
digitalWrite(power_led_pin, HIGH);
}
void raccoon_dds_hw_uno::power_led_off(void)
{
digitalWrite(power_led_pin, LOW);
}
void raccoon_dds_hw_uno::run_led_on(void)
{
digitalWrite(run_led_pin, HIGH);
}
void raccoon_dds_hw_uno::run_led_off(void)
{
digitalWrite(run_led_pin, LOW);
}
void raccoon_dds_hw_uno::lcd_clear(void)
{
lcd->clear();
lcd->home();
lcd->noBlink();
lcd_row = 0;
lcd_col = 0;
}
void raccoon_dds_hw_uno::lcd_clear_row(uint8_t row)
{
uint8_t i;
lcd->setCursor(0, row);
for (i = 0; i <= lcd_col_max; i++)
lcd->print(' ');
lcd->setCursor(0, row);
}
void raccoon_dds_hw_uno::lcd_set_cursor(uint8_t col, uint8_t row)
{
if (col > lcd_col_max || row > lcd_col_max)
return;
lcd->setCursor(col, row);
lcd_row = row;
lcd_col = col;
}
void raccoon_dds_hw_uno::lcd_blink(void)
{
lcd->blink();
}
void raccoon_dds_hw_uno::lcd_no_blink(void)
{
lcd->noBlink();
}
void raccoon_dds_hw_uno::lcd_print(char ch)
{
if ('\n' == ch || '\r' == ch)
ch = ' ';
if (lcd_col > lcd_col_max) {
lcd_col = 0;
if (++lcd_row > lcd_row_max)
lcd_row = 0;
lcd_clear_row(lcd_row);
}
lcd->print(ch);
lcd_col++;
}
void raccoon_dds_hw_uno::lcd_print(const char *str)
{
while (*str)
lcd_print(*str++);
}
void raccoon_dds_hw_uno::lcd_print_P(const char *str)
{
char ch;
while (ch = pgm_read_byte(str++))
lcd_print(ch);
}
<file_sep>/raccoon_dds_sw_square.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_square.h
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_SW_SQUARE_H__
#define __RACCOON_DDS_SW_SQUARE_H__
#include "raccoon_dds_sw_lookup.h"
class raccoon_dds_sw_square : public raccoon_dds_sw_lookup {
public:
raccoon_dds_sw_square(const uint8_t *lookup_tbl);
static raccoon_dds_sw_square *get_instance(void);
private:
static raccoon_dds_sw_square *singleton;
};
#endif /* __RACCOON_DDS_SW_SQUARE_H__ */
<file_sep>/raccoon_dds_sw_lookup.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <math.h>
#include <stdint.h>
#include "raccoon_dds_hw.h"
void raccoon_dds_sw_lookup::start(void)
{
raccoon_dds_sw::start();
RACCOON_DDS_MACH_LOOKUP_STATUS_REG &=
~(1 << RACCOON_DDS_MACH_LOOKUP_STATUS_BIT);
}
void raccoon_dds_sw_lookup::stop(void)
{
RACCOON_DDS_MACH_LOOKUP_STATUS_REG |=
1 << RACCOON_DDS_MACH_LOOKUP_STATUS_BIT;
raccoon_dds_sw::stop();
}
/* DDS signal generation function
* Original idea is taken from
* http://www.myplace.nu/avr/minidds/index.htm
*
* The modified one is found ate here.
* http://www.scienceprog.com/avr-dds-signal-generator-v20/
*/
static void inline __raccoon_dds_sw_lookup_loop(const uint8_t *lookup_tbl, uint32_t add)
{
uintptr_t __lookup_tbl = (uintptr_t)lookup_tbl;
uint8_t ad0, ad1, ad2;
ad0 = (uint8_t)(add & 0xFF);
ad1 = (uint8_t)((add >> 8) & 0xFF);
ad2 = (uint8_t)((add >> 16) & 0xFF);
if ((__lookup_tbl & ~0xFF) != __lookup_tbl)
__lookup_tbl = (__lookup_tbl & ~0xFF) + 0x100;
__asm__ volatile (
"eor r18, r18 ;r18<-0" "\n\t"
"eor r19, r19 ;r19<-0" "\n\t"
"1:" "\n\t"
"add r18, %0 ;1 cycle" "\n\t"
"adc r19, %1 ;1 cycle" "\n\t"
"adc %A3, %2 ;1 cycle" "\n\t"
"lpm ;3 cycles" "\n\t"
"out %4, __tmp_reg__ ;1 cycle" "\n\t"
"sbis %5, %6 ;1 cycle if no skip" "\n\t"
"rjmp 1b ;2 cycles. Total 10 cycles" "\n\t"
:
:"r" (ad0),"r" (ad1),"r" (ad2),"e" (__lookup_tbl),
"I" (_SFR_IO_ADDR(RACCOON_DDS_HW_PORT)),
"I" (_SFR_IO_ADDR(RACCOON_DDS_MACH_LOOKUP_STATUS_REG)),
"I" (RACCOON_DDS_MACH_LOOKUP_STATUS_BIT)
:"r18", "r19"
);
}
void raccoon_dds_sw_lookup::prologue(void)
{
// FIXME: to prevent the jitter error cause of internal timer interrupt
// which used in time utilities.
TIMSK0 &= ~(1 << TOIE0);
}
#define RACCOON_DDS_MACH_LOOKUP_SIG_TICKS 10
#define RACCOON_DDS_MACH_LOOKUP_ACC_FRAC_BITS 16
void raccoon_dds_sw_lookup::text(void)
{
uint32_t add;
float resolution;
resolution = (float)RACCOON_DDS_HW_F_CPU;
resolution /= (float)RACCOON_DDS_MACH_LOOKUP_SIG_TICKS;
resolution /= (float)RACCOON_DDS_MACH_LOOKUP_TBL_SZ;
resolution /= (float)((uint32_t)1 << RACCOON_DDS_MACH_LOOKUP_ACC_FRAC_BITS);
add = (uint32_t)roundf((float)frequency / resolution);
__raccoon_dds_sw_lookup_loop(lookup_tbl, add);
}
void raccoon_dds_sw_lookup::epilogue(void)
{
RACCOON_DDS_HW_PORT = 0x00;
TIMSK0 |= 1 << TOIE0;
}
<file_sep>/raccoon_dds_sw_sine.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_sine.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "raccoon_dds_sw_sine.h"
static const char __raccoon_dds_sw_sine_name[] PROGMEM = "Sine";
#define RACCOON_DDS_MACH_SINE_LOOKUP_TBL \
0x80, 0x83, 0x86, 0x89, 0x8c, 0x8f, 0x92, 0x95, \
0x98, 0x9b, 0x9e, 0xa2, 0xa5, 0xa7, 0xaa, 0xad, \
0xb0, 0xb3, 0xb6, 0xb9, 0xbc, 0xbe, 0xc1, 0xc4, \
0xc6, 0xc9, 0xcb, 0xce, 0xd0, 0xd3, 0xd5, 0xd7, \
0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, \
0xea, 0xeb, 0xed, 0xee, 0xf0, 0xf1, 0xf3, 0xf4, \
0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfa, 0xfb, 0xfc, \
0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xfe, 0xfe, 0xfe, 0xfd, \
0xfd, 0xfc, 0xfb, 0xfa, 0xfa, 0xf9, 0xf8, 0xf6, \
0xf5, 0xf4, 0xf3, 0xf1, 0xf0, 0xee, 0xed, 0xeb, \
0xea, 0xe8, 0xe6, 0xe4, 0xe2, 0xe0, 0xde, 0xdc, \
0xda, 0xd7, 0xd5, 0xd3, 0xd0, 0xce, 0xcb, 0xc9, \
0xc6, 0xc4, 0xc1, 0xbe, 0xbc, 0xb9, 0xb6, 0xb3, \
0xb0, 0xad, 0xaa, 0xa7, 0xa5, 0xa2, 0x9e, 0x9b, \
0x98, 0x95, 0x92, 0x8f, 0x8c, 0x89, 0x86, 0x83, \
0x7f, 0x7c, 0x79, 0x76, 0x73, 0x70, 0x6d, 0x6a, \
0x67, 0x64, 0x61, 0x5d, 0x5a, 0x58, 0x55, 0x52, \
0x4f, 0x4c, 0x49, 0x46, 0x43, 0x41, 0x3e, 0x3b, \
0x39, 0x36, 0x34, 0x31, 0x2f, 0x2c, 0x2a, 0x28, \
0x25, 0x23, 0x21, 0x1f, 0x1d, 0x1b, 0x19, 0x17, \
0x15, 0x14, 0x12, 0x11, 0x0f, 0x0e, 0x0c, 0x0b, \
0x0a, 0x09, 0x07, 0x06, 0x05, 0x05, 0x04, 0x03, \
0x02, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, \
0x02, 0x03, 0x04, 0x05, 0x05, 0x06, 0x07, 0x09, \
0x0a, 0x0b, 0x0c, 0x0e, 0x0f, 0x11, 0x12, 0x14, \
0x15, 0x17, 0x19, 0x1b, 0x1d, 0x1f, 0x21, 0x23, \
0x25, 0x28, 0x2a, 0x2c, 0x2f, 0x31, 0x34, 0x36, \
0x39, 0x3b, 0x3e, 0x41, 0x43, 0x46, 0x49, 0x4c, \
0x4f, 0x52, 0x55, 0x58, 0x5a, 0x5d, 0x61, 0x64, \
0x67, 0x6a, 0x6d, 0x70, 0x73, 0x76, 0x79, 0x7c
static const uint8_t __raccoon_dds_sw_sine_lookup_tbl[] PROGMEM = {
RACCOON_DDS_MACH_SINE_LOOKUP_TBL,
RACCOON_DDS_MACH_SINE_LOOKUP_TBL
};
raccoon_dds_sw_sine::raccoon_dds_sw_sine(const uint8_t *lookup_tbl)
{
this->lookup_tbl = lookup_tbl;
name = __raccoon_dds_sw_sine_name;
}
static raccoon_dds_sw_sine __raccoon_dds_sw_sine(__raccoon_dds_sw_sine_lookup_tbl);
raccoon_dds_sw_sine *raccoon_dds_sw_sine::singleton =
&__raccoon_dds_sw_sine;
raccoon_dds_sw_sine *raccoon_dds_sw_sine::get_instance(void)
{
return singleton;
}
<file_sep>/raccoon_dds.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "pcint.h"
#include "raccoon_dds_hw.h"
#include "raccoon_dds_hw_uno.h"
#include "raccoon_dds_sw.h"
#include "raccoon_dds_menu.h"
raccoon_dds_hw *dds_hw;
raccoon_dds_sw *dds_sw;
raccoon_dds_menu *dds_menu;
static void dds_pcint_handler(void)
{
dds_menu->handler();
}
static const char __dds_banner[] PROGMEM = "Raccoon's DDS";
void setup(void)
{
// put your setup code here, to run once:
dds_hw = raccoon_dds_hw_uno::get_instance();
dds_hw->init();
dds_hw->lcd_print_P(__dds_banner);
delay(1000);
dds_menu = raccoon_dds_menu::get_instance();
dds_menu->init();
pcint_attach(E_PCINT1, dds_pcint_handler);
}
void loop(void)
{
// put your main code here, to run repeatedly:
dds_menu->loop();
dds_sw->loop();
}
<file_sep>/raccoon_dds_sw.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw.h
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_SW_H__
#define __RACCOON_DDS_SW_H__
class raccoon_dds_sw {
public:
raccoon_dds_sw();
const char *get_name(void);
void set_frequency(unsigned long frequency);
unsigned long get_frequency(void);
virtual void loop(void);
virtual void start(void);
virtual void stop(void);
protected:
virtual void prologue(void) = 0;
virtual void text(void) = 0;
virtual void epilogue(void) = 0;
const char *name;
bool running;
unsigned long frequency;
};
#endif /* __RACCOON_DDS_SW_H__ */
<file_sep>/pcint.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's Morse Trainer
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : pcint.ino
*
* File Description : the original implementation found in this url
* http://playground.arduino.cc/Main/PinChangeInterrupt
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 13/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include "pcint.h"
static void (*__pcint_handler[E_NR_PCINT])(void);
int pcint_attach(unsigned int idx, void (*handler)(void))
{
if (idx >= E_NR_PCINT)
return -1;
__pcint_handler[idx] = handler;
return 0;
}
int pcint_dettach(unsigned int idx)
{
if (idx >= E_NR_PCINT)
return -1;
__pcint_handler[idx] = NULL;
return 0;
}
void pcint_enable(unsigned int pin)
{
*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));
PCIFR |= bit (digitalPinToPCICRbit(pin));
PCICR |= bit (digitalPinToPCICRbit(pin));
}
void pcint_disable(unsigned int pin)
{
*digitalPinToPCMSK(pin) &= ~(bit(digitalPinToPCMSKbit(pin)));
PCIFR &= ~(bit(digitalPinToPCICRbit(pin)));
PCICR &= ~(bit(digitalPinToPCICRbit(pin)));
}
// handle pin change interrupt for D8 to D13 here
ISR (PCINT0_vect)
{
if (__pcint_handler[E_PCINT0])
__pcint_handler[E_PCINT0]();
}
// handle pin change interrupt for A0 to A5 here
ISR (PCINT1_vect)
{
if (__pcint_handler[E_PCINT1])
__pcint_handler[E_PCINT1]();
}
// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
{
if (__pcint_handler[E_PCINT2])
__pcint_handler[E_PCINT2]();
}
<file_sep>/raccoon_dds_sw_lookup.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup.h
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_SW_LOOKUP_H__
#define __RACCOON_DDS_SW_LOOKUP_H__
#include <stdint.h>
#include "raccoon_dds_sw.h"
#define RACCOON_DDS_MACH_LOOKUP_STATUS_REG GPIOR0
#define RACCOON_DDS_MACH_LOOKUP_STATUS_BIT GPIOR00
#define RACCOON_DDS_MACH_LOOKUP_TBL_SZ 256
class raccoon_dds_sw_lookup : public raccoon_dds_sw {
public:
virtual void start(void);
virtual void stop(void);
protected:
virtual void prologue(void);
virtual void text(void);
virtual void epilogue(void);
const uint8_t *lookup_tbl;
};
#endif /* __RACCOON_DDS_SW_LOOKUP_H__ */
<file_sep>/raccoon_dds_sw_square.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_square.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "raccoon_dds_sw_square.h"
static const char __raccoon_dds_sw_square_name[] PROGMEM = "Square";
#define RACCOON_DDS_MACH_SQUARE_LOOKUP_TBL \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, \
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
static const uint8_t __raccoon_dds_sw_square_lookup_tbl[] PROGMEM = {
RACCOON_DDS_MACH_SQUARE_LOOKUP_TBL,
RACCOON_DDS_MACH_SQUARE_LOOKUP_TBL
};
raccoon_dds_sw_square::raccoon_dds_sw_square(const uint8_t *lookup_tbl)
{
this->lookup_tbl = lookup_tbl;
name = __raccoon_dds_sw_square_name;
}
static raccoon_dds_sw_square __raccoon_dds_sw_square(__raccoon_dds_sw_square_lookup_tbl);
raccoon_dds_sw_square *raccoon_dds_sw_square::singleton =
&__raccoon_dds_sw_square;
raccoon_dds_sw_square *raccoon_dds_sw_square::get_instance(void)
{
return singleton;
}
<file_sep>/pcint.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's Morse Trainer
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : pcint.h
*
* File Description : the original implementation found in this url
* http://playground.arduino.cc/Main/PinChangeInterrupt
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 13/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __PCINT_H__
#define __PCINT_H__
enum {
E_PCINT0 = 0,
E_PCINT1,
E_PCINT2,
E_NR_PCINT,
};
int pcint_attach(unsigned int idx, void (*handler)(void));
int pcint_dettach(unsigned int idx);
void pcint_enable(unsigned int pin);
void pcint_disable(unsigned int pin);
#endif /* __PCINT_H__ */
<file_sep>/raccoon_dds_menu.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_menu.h
*
* File Description :
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 27/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_MENU_H__
#define __RACCOON_DDS_MENU_H__
#include "raccoon_dds_sw.h"
class raccoon_dds_submenu {
public:
virtual void init(void);
virtual void loop(void);
virtual void key_up(void);
virtual void key_down(void);
};
typedef enum {
E_RACCOON_DDS_MENU_DEACTIVE = 0,
E_RACCOON_DDS_MENU_ENTERED,
E_RACCOON_DDS_MENU_REDY_KEY,
E_RACCOON_DDS_MENU_SUBMENU,
} raccoon_menu_state_t;
class raccoon_dds_menu {
public:
raccoon_dds_menu();
static raccoon_dds_menu *get_instance(void);
void init(void);
void loop(void);
void handler(void);
private:
bool run(void);
void change_submenu(void);
void display_current_setting(void);
static raccoon_dds_menu *singleton;
raccoon_dds_submenu **submenu_list;
raccoon_dds_submenu *submenu_current;
size_t submenu_nr;
size_t submenu_idx;
raccoon_menu_state_t state;
raccoon_morse_keycode_t keycode;
raccoon_dds_sw *sw_previous;
unsigned long freq_previous;
};
#endif /* __RACCOON_DDS_MENU_H__ */
<file_sep>/raccoon_dds_sw_triangle.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_triangle.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "raccoon_dds_sw_triangle.h"
static const char __raccoon_dds_sw_triangle_name[] PROGMEM = "Triangle";
#define RACCOON_DDS_MACH_TRIANGLE_LOOKUP_TBL \
0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, \
0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, \
0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, \
0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, \
0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, \
0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, \
0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, \
0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, \
0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e, \
0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, \
0xa0, 0xa2, 0xa4, 0xa6, 0xa8, 0xaa, 0xac, 0xae, \
0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe, \
0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, \
0xd0, 0xd2, 0xd4, 0xd6, 0xd8, 0xda, 0xdc, 0xde, \
0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee, \
0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xff, \
0xff, 0xfc, 0xfa, 0xf8, 0xf6, 0xf4, 0xf2, 0xf0, \
0xee, 0xec, 0xea, 0xe8, 0xe6, 0xe4, 0xe2, 0xe0, \
0xde, 0xdc, 0xda, 0xd8, 0xd6, 0xd4, 0xd2, 0xd0, \
0xce, 0xcc, 0xca, 0xc8, 0xc6, 0xc4, 0xc2, 0xc0, \
0xbe, 0xbc, 0xba, 0xb8, 0xb6, 0xb4, 0xb2, 0xb0, \
0xae, 0xac, 0xaa, 0xa8, 0xa6, 0xa4, 0xa2, 0xa0, \
0x9e, 0x9c, 0x9a, 0x98, 0x96, 0x94, 0x92, 0x90, \
0x8e, 0x8c, 0x8a, 0x88, 0x86, 0x84, 0x82, 0x80, \
0x7e, 0x7c, 0x7a, 0x78, 0x76, 0x74, 0x72, 0x70, \
0x6e, 0x6c, 0x6a, 0x68, 0x66, 0x64, 0x62, 0x60, \
0x5e, 0x5c, 0x5a, 0x58, 0x56, 0x54, 0x52, 0x50, \
0x4e, 0x4c, 0x4a, 0x48, 0x46, 0x44, 0x42, 0x40, \
0x3e, 0x3c, 0x3a, 0x38, 0x36, 0x34, 0x32, 0x30, \
0x2e, 0x2c, 0x2a, 0x28, 0x26, 0x24, 0x22, 0x20, \
0x1e, 0x1c, 0x1a, 0x18, 0x16, 0x14, 0x12, 0x10, \
0x0e, 0x0c, 0x0a, 0x08, 0x06, 0x04, 0x02, 0x00
static const uint8_t __raccoon_dds_sw_triangle_lookup_tbl[] PROGMEM = {
RACCOON_DDS_MACH_TRIANGLE_LOOKUP_TBL,
RACCOON_DDS_MACH_TRIANGLE_LOOKUP_TBL
};
raccoon_dds_sw_triangle::raccoon_dds_sw_triangle(const uint8_t *lookup_tbl)
{
this->lookup_tbl = lookup_tbl;
name = __raccoon_dds_sw_triangle_name;
}
static raccoon_dds_sw_triangle __raccoon_dds_sw_triangle(__raccoon_dds_sw_triangle_lookup_tbl);
raccoon_dds_sw_triangle *raccoon_dds_sw_triangle::singleton =
&__raccoon_dds_sw_triangle;
raccoon_dds_sw_triangle *raccoon_dds_sw_triangle::get_instance(void)
{
return singleton;
}
<file_sep>/raccoon_dds_sw_ramp.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_ramp.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "raccoon_dds_sw_ramp.h"
static const char __raccoon_dds_sw_ramp_name[] PROGMEM = "Ramp";
#define RACCOON_DDS_MACH_RAMP_LOOKUP_TBL \
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, \
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, \
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, \
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, \
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, \
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, \
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, \
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, \
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, \
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, \
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, \
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, \
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, \
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, \
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, \
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, \
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, \
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, \
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, \
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, \
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, \
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, \
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, \
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, \
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, \
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, \
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, \
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, \
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, \
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, \
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, \
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
static const uint8_t __raccoon_dds_sw_ramp_lookup_tbl[] PROGMEM = {
RACCOON_DDS_MACH_RAMP_LOOKUP_TBL,
RACCOON_DDS_MACH_RAMP_LOOKUP_TBL
};
raccoon_dds_sw_ramp::raccoon_dds_sw_ramp(const uint8_t *lookup_tbl)
{
this->lookup_tbl = lookup_tbl;
name = __raccoon_dds_sw_ramp_name;
}
static raccoon_dds_sw_ramp __raccoon_dds_sw_ramp(__raccoon_dds_sw_ramp_lookup_tbl);
raccoon_dds_sw_ramp *raccoon_dds_sw_ramp::singleton =
&__raccoon_dds_sw_ramp;
raccoon_dds_sw_ramp *raccoon_dds_sw_ramp::get_instance(void)
{
return singleton;
}
<file_sep>/raccoon_dds_hw.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_hw.h
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 27/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_HW_H__
#define __RACCOON_DDS_HW_H__
#include <stdint.h>
#define RACCOON_DDS_HW_PORT PORTD
#define RACCOON_DDS_HW_DDR DDRD
#define RACCOON_DDS_HW_F_CPU 16000000UL
#define RACCOON_DDS_HW_MIN_FREQUENCY 1
#define RACCOON_DDS_HW_MAX_FREQUENCY 62500
typedef enum {
E_RACCOON_DDS_HW_KEYCODE_RUN = 0,
E_RACCOON_DDS_HW_KEYCODE_LEFT,
E_RACCOON_DDS_HW_KEYCODE_RIGHT,
E_RACCOON_DDS_HW_KEYCODE_UP,
E_RACCOON_DDS_HW_KEYCODE_DOWN,
E_RACCOON_DDS_HW_KEYCODE_INVALID,
} raccoon_morse_keycode_t;
typedef enum {
E_RACCOON_DDS_KEYSTATE_NOT_PRESSED = 0,
E_RACCOON_DDS_KEYSTATE_PRESSED,
} raccoon_dds_keystate_t;
class raccoon_dds_hw {
public:
virtual void init(void) = 0;
virtual raccoon_dds_keystate_t button_state(void) = 0;
virtual raccoon_morse_keycode_t button_keycode(void) = 0;
virtual void power_led_on(void) = 0;
virtual void power_led_off(void) = 0;
virtual void run_led_on(void) = 0;
virtual void run_led_off(void) = 0;
virtual void lcd_clear(void) = 0;
virtual void lcd_clear_row(uint8_t row) = 0;
virtual void lcd_set_cursor(uint8_t col, uint8_t row) = 0;
virtual void lcd_blink(void) = 0;
virtual void lcd_no_blink(void) = 0;
virtual void lcd_print(char ch) = 0;
virtual void lcd_print(const char *str) = 0;
virtual void lcd_print_P(const char *str) = 0;
};
#endif /* __RACCOON_DDS_HW_H__ */
<file_sep>/raccoon_dds_sw_ecg.ino
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_sw_lookup_ecg.ino
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 21/Aug/2016
* Version : Baby-Raccoon
*/
#include <avr/pgmspace.h>
#include "raccoon_dds_sw_ecg.h"
static const char __raccoon_dds_sw_ecg_name[] PROGMEM = "ECG";
#define RACCOON_DDS_MACH_ECG_LOOKUP_TBL \
0x49, 0x4a, 0x4b, 0x4b, 0x4a, 0x49, 0x49, 0x49, \
0x49, 0x48, 0x47, 0x45, 0x44, 0x43, 0x43, 0x43, \
0x44, 0x44, 0x43, 0x41, 0x3e, 0x3d, 0x3b, 0x39, \
0x38, 0x37, 0x37, 0x36, 0x36, 0x36, 0x37, 0x37, \
0x37, 0x37, 0x37, 0x37, 0x36, 0x35, 0x33, 0x32, \
0x31, 0x31, 0x34, 0x3d, 0x4d, 0x65, 0x84, 0xa9, \
0xcf, 0xee, 0xff, 0xfe, 0xea, 0xc6, 0x9a, 0x6d, \
0x44, 0x25, 0x11, 0x05, 0x00, 0x01, 0x06, 0x0d, \
0x14, 0x1c, 0x24, 0x2d, 0x34, 0x39, 0x3d, 0x40, \
0x41, 0x42, 0x43, 0x44, 0x44, 0x45, 0x46, 0x47, \
0x47, 0x47, 0x47, 0x47, 0x47, 0x47, 0x47, 0x48, \
0x48, 0x48, 0x49, 0x49, 0x4a, 0x4b, 0x4b, 0x4c, \
0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, \
0x56, 0x58, 0x5b, 0x5d, 0x60, 0x62, 0x64, 0x66, \
0x68, 0x6b, 0x6d, 0x70, 0x73, 0x76, 0x79, 0x7b, \
0x7d, 0x7e, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7e, \
0x7d, 0x7c, 0x79, 0x77, 0x74, 0x71, 0x6d, 0x69, \
0x66, 0x62, 0x5f, 0x5c, 0x59, 0x57, 0x54, 0x51, \
0x4f, 0x4d, 0x4c, 0x4b, 0x4a, 0x49, 0x48, 0x46, \
0x45, 0x44, 0x43, 0x43, 0x43, 0x44, 0x44, 0x44, \
0x45, 0x45, 0x45, 0x45, 0x45, 0x45, 0x45, 0x46, \
0x47, 0x48, 0x49, 0x49, 0x4a, 0x4a, 0x4b, 0x4b, \
0x4b, 0x4b, 0x4b, 0x4b, 0x4a, 0x4a, 0x49, 0x49, \
0x49, 0x49, 0x48, 0x48, 0x48, 0x47, 0x47, 0x47, \
0x47, 0x47, 0x47, 0x47, 0x46, 0x46, 0x46, 0x45, \
0x45, 0x45, 0x45, 0x45, 0x46, 0x46, 0x46, 0x45, \
0x44, 0x44, 0x43, 0x43, 0x43, 0x43, 0x42, 0x42, \
0x42, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, \
0x41, 0x40, 0x40, 0x3f, 0x3f, 0x40, 0x40, 0x41, \
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x40, 0x40, \
0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x41, 0x41, \
0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49
static const uint8_t __raccoon_dds_sw_ecg_lookup_tbl[] PROGMEM = {
RACCOON_DDS_MACH_ECG_LOOKUP_TBL,
RACCOON_DDS_MACH_ECG_LOOKUP_TBL
};
raccoon_dds_sw_ecg::raccoon_dds_sw_ecg(const uint8_t *lookup_tbl)
{
this->lookup_tbl = lookup_tbl;
name = __raccoon_dds_sw_ecg_name;
}
static raccoon_dds_sw_ecg __raccoon_dds_sw_ecg(__raccoon_dds_sw_ecg_lookup_tbl);
raccoon_dds_sw_ecg *raccoon_dds_sw_ecg::singleton =
&__raccoon_dds_sw_ecg;
raccoon_dds_sw_ecg *raccoon_dds_sw_ecg::get_instance(void)
{
return singleton;
}
<file_sep>/raccoon_dds.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds.h
*
* File Description :
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 14/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_H__
#define __RACCOON_DDS_H__
#include "raccoon_dds_hw.h"
#include "raccoon_dds_sw.h"
#define ARRAY_SIZE(_a) (sizeof(_a) / sizeof(_a[0]))
extern raccoon_dds_hw *dds_hw;
extern raccoon_dds_sw *dds_sw;
extern raccoon_dds_menu *dds_menu;
#endif /* __RACCOON_DDS_H__ */
<file_sep>/raccoon_dds_hw_uno.h
/**
* Copyright (C) 2016. Joo, <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
/**
* Project Name : Raccoon's DDS
*
* Project Description :
*
* Comments : tabstop = 8, shiftwidth = 8, noexpandtab
*/
/**
* File Name : raccoon_dds_hw_uno.h
*
* File Description :
*
* Author : Joo, <NAME> <<EMAIL>>
* Dept : Raccoon's Cave
* Created Date : 27/Aug/2016
* Version : Baby-Raccoon
*/
#ifndef __RACCOON_DDS_HW_UNO_H__
#define __RACCOON_DDS_HW_UNO_H__
#include <stdint.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "raccoon_dds_hw.h"
// if PCF8574 is used then use the bellow slave address.
#define RACCOON_DDS_HW_UNO_LCD_SLAVE 0x27
// if PCF8574A is used then use the bellow slave address.
//#define RACCOON_DDS_HW_UNO_LCD_SLAVE 0x3F
#define RACCOON_DDS_HW_UNO_LCD_COL 16
#define RACCOON_DDS_HW_UNO_LCD_ROW 2
#define RACCOON_DDS_HW_UNO_KEYADC_MARGIN 20
/* FIXME: select a LARGE pull-up resistance as possible as to prevent error
* while 'analogRead' is called very frequently. */
/* TODO: slect a pull-up resistor whick make about 150 adc value when
* highest pull-down resistance connected. in this hw, one 75K and 4 2K
* resistors are used to handling 5 tack switches. */
#define RACCOON_DDS_HW_UNO_KEYADC_PULLUP 75 /* 75k */
#define RACCOON_DDS_HW_UNO_KEYADC_PULLDN 2 /* 2k */
class raccoon_dds_hw_uno : public raccoon_dds_hw {
public:
raccoon_dds_hw_uno();
static raccoon_dds_hw_uno *get_instance(void);
virtual void init(void);
virtual raccoon_dds_keystate_t button_state(void);
virtual raccoon_morse_keycode_t button_keycode(void);
virtual void power_led_on(void);
virtual void power_led_off(void);
virtual void run_led_on(void);
virtual void run_led_off(void);
virtual void lcd_clear(void);
virtual void lcd_clear_row(uint8_t row);
virtual void lcd_set_cursor(uint8_t col, uint8_t row);
virtual void lcd_blink(void);
virtual void lcd_no_blink(void);
virtual void lcd_print(char ch);
virtual void lcd_print(const char *str);
virtual void lcd_print_P(const char *str);
private:
static raccoon_dds_hw_uno *singleton;
uint8_t button_pin;
uint8_t power_led_pin;
uint8_t run_led_pin;
LiquidCrystal_I2C *lcd;
uint8_t lcd_row_max, lcd_col_max;
uint8_t lcd_row, lcd_col;
};
#endif /* __RACCOON_DDS_HW_UNO_H__ */
| 79e7c881914c3518df0febdc3eb38cf5e9423f48 | [
"C",
"C++"
] | 20 | C++ | neoelec/raccoon_dds | eabd588c4353ed7f47fabea546dbb4f151f6c661 | bf576c01bff020d2719172d7c7a2babb4f6488ad |
refs/heads/master | <repo_name>eeddd/contank<file_sep>/src/main.cpp
#include <iostream>
#include <curses.h>
#include <unistd.h>
bool gameover = false;
int W = 20, H = 16;
int key;
class Tank
{
int m_x, m_y;
int m_size;
char m_body[9];
int m_dir;
public:
Tank() : m_x(0), m_y(0), m_size(9), m_body{ ' ','1',' ', '1','1','1', '1',' ','1' }
{
}
bool Hit(int x, int y)
{
if (x >= m_x && x <= m_x + 2
&& y >= m_y && y <= m_y + 2)
return true;
return false;
}
char GetChar(int a, int b)
{
if (!Hit(a, b)) return ' ';
int x = a - m_x;
int y = b - m_y;
int i = 0;
switch (m_dir % 4)
{
case 0:
i = (y) * 3 + x;
break;
case 1:
i = 6 + y - (x * 3);
break;
case 2:
i = 8 - (y * 3) - x;
break;
case 3:
i = 2 - y + (x * 3);
break;
}
return m_body[i];
}
int& dir() { return m_dir; }
int& x() { return m_x; }
int& y() { return m_y; }
} tank;
void Init()
{
tank.dir() = 0;
tank.x() = 1;
tank.y() = 1;
}
void Draw()
{
for (int y = 0; y < H; y++)
{
for (int x = 0; x < W; x++)
{
move(y, x);
if (x == 0 || x == W-1 || y == 0 || y == H-1)
addch('#');
else if (tank.Hit(x, y))
addch(tank.GetChar(x, y));
else
addch(' ');
}
}
refresh();
}
void Input()
{
switch (key)
{
case KEY_UP:
if (tank.dir() == 0) tank.y() -= 1;
tank.dir() = 0;
break;
case KEY_RIGHT:
if (tank.dir() == 1) tank.x() += 1;
tank.dir() = 1;
break;
case KEY_DOWN:
if (tank.dir() == 2) tank.y() += 1;
tank.dir() = 2;
break;
case KEY_LEFT:
if (tank.dir() == 3) tank.x() -= 1;
tank.dir() = 3;
break;
}
}
void Update()
{
if (tank.x() <= 0)
tank.x() = 1;
else if (tank.x() >= W-3)
tank.x() = W-4;
if (tank.y() <= 0)
tank.y() = 1;
else if (tank.y() >= H-3)
tank.y() = H-4;
}
int main()
{
initscr();
nodelay(stdscr, true);
keypad(stdscr, true);
cbreak();
noecho();
clear();
refresh();
Init();
while (!gameover)
{
Draw();
Input();
Update();
key = getch();
if (key == 'q') break;
}
nodelay(stdscr, false);
move(H/2, W/2-5);
printw("Game Over!");
getch();
endwin();
return 0;
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
set(PROJECT_NAME "contank")
project(${PROJECT_NAME} VERSION 0.1.0)
file(GLOB SOURCES "src/*.cpp")
set(CURSES_NEED_NCURSES TRUE)
find_package(Curses REQUIRED)
include_directories(${CURSES_INCLUDE_DIR})
add_executable(${PROJECT_NAME} ${SOURCES})
if (${CMAKE_CXX_COMPILER_ID} STREQUAL "MSVC")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /SUBSYSTEM:WINDOWS")
add_compile_options("-MDd")
endif()
target_include_directories(${PROJECT_NAME} PRIVATE include)
target_link_libraries(${PROJECT_NAME} ${CURSES_LIBRARIES})
| 7701d1332e951e87b864983770788e18515b2f4b | [
"CMake",
"C++"
] | 2 | C++ | eeddd/contank | 5214935fd7e3d6310e272fd5fe18a0c8db8366a1 | 3cd9e9986aa12d7f5e7761f7e59ff4ff70e41d47 |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
#encoding: utf-8
base = File.dirname(File.absolute_path(__FILE__))
require "#{base}/common.rb"
begin
cache = File.open('.cache', 'r+')
rescue
cache = File.open('.cache', 'w+')
end
contents = cache.read
if contents==''
estados = JSON.parse Iconv.iconv('utf-8', 'iso8859-1', SCT.get('/SerEscogeRuta?estados').body).join
data = {
estados: {},
puntos: {}
}
estados.each {|edo|
nombre = edo['nombre']
$stdout.write "Jugando con #{nombre}..."
data[:estados][edo['id']] = nombre
puntos = JSON.parse Iconv.iconv('utf-8', 'iso8859-1', SCT.get("/SerEscogeRuta?idEstado=#{edo['id']}")).join, :symbolize_names => true
puntos.each {|punto|
data[:puntos][punto[:id]] = {
estado: punto[:idEdo],
coords: [punto[:coordenadaX], punto[:coordenadaY]],
nombre: punto[:nombre]
}
}
$stdout.write " DONE!\n"
}
cache << data.to_json
else
data = JSON.parse contents, :symbolize_names => true
end
puts data.to_json
#lo que sigue son puras mamadas para averiguar la relación entre el mapa de SCT y un mapa de proyección mercator, como la de Google Maps
#todavía no tengo puta idea cómo va a jalar...
=begin
Zócalo
Google Maps dice: y:19.432641,x:-99.133372
SCT dice: y:206.543, x:-43.86,
SCT para mapa dice: y:318.90533, x:275.07587
###
# Para Coords
###
###
# Para Mapa
###
Su plano cartesiano va de LT: 0,0
a BR: 550,400
y: 318.90533 -> 19.432641
x: 275.0758 -> -99.133372
318.90533-25.576385 = 293.328945
275.0758-11.270352=263.805448
19.432641-32.533373 = 13.100731999999997
-99.133372+117.0189 = 17.885528000000008
293.328945/13.100732 = 22.390271398575283
263.805448/17.885528 = 14.749659501245924
1/22.390271398575283 0.04466225452111452
1/14.749659501245924 0.06779817526740388
550/22.390271398575283 = 24.564239986612986+19.432641 43.996880986612986
400/14.749659501245924 = -99.133372-27.11927010696155 -126.25264210696155
43.996880986612986, -126.25264210696155
y0 = 33.5144995851904 (550 * 19.432641 / 318.90533)
x0 = -144.15426147992662 (400 * -99.133372 / 275.0758)
33.5144995851904, -144.15426147992662
318 = ?
550 = 33.5144995851904
1/
#cuernavaca df
df 318.90533#275.07587
cuerna 316.96512#284.0324
318.90533-316.96512 = 1.9402099999999791
275.07587-284.0324 = -8.956529999999987
1.9402099999999791*0.04466225452111452 19.432641-0.08665415284441066 19.34598684715559
-8.956529999999987*0.06779817526740388 -99.13337-0.6072363907277599 -99.74060639072776
19.51929515284441, -99.74060839072776
Cd. <NAME> (Zócalo)#318.90533#275.07587#Monumento a Cuauhtémoc#318.35947#275.15588#PG#PP#1&
Monumento a Cuauhtémoc#318.35947#275.15588#Entronque Av. Insurgentes#318.23096#275.66415#PP#E#6&
T Av. Insurgentes#318.23096#275.66415#Glorieta Manacar#318.11765#276.3586#E#PP#12&
Glorieta Manacar#318.11765#276.3586#Pirámide Cuicuilco (Perisur)#318.27032#277.9469#PP#PP#6&
Pirámide Cuicuilco (Perisur)#318.27032#277.9469#Monumento al Caminero#318.46033#278.44345#PP#PP#6&
Monumento al Caminero#318.46033#278.44345#Tlalpan#318.60132#279.0324#PP#C#6&
Tlalpan#318.60132#279.0324#Entronque Cuernavaca#317.265#283.31448#C#E#4&
Entronque Cuernavaca#317.265#283.31448#Cuernavaca#316.96512#284.0324#E#PG#1
=end<file_sep>#API Traza Tu Ruta
versión 0.1
##Requerimientos
* Ruby >= 1.9.2p180
* Nokogiri >= 1.5.2
* HTTParty >= 0.7.8
##cache
Genera un cache de los puntos de partida posibles, la idea sería que esto nomás hiciera ingesta a una db.
Por ahora, regresa un JSON con los estados y los puntos de partida/destino posibles y los guarda en un cache para luego usar:
##ruta
Regresa la ruta entre dos puntos, usando el servicio de SCT que le saqué a su página a punta de chingadazos.
Idealmente, cada request lo habría de guardar en cache, regresándolo al usuario, y después mandar al server a hacerme un café en lo que le pregunta a SCT si la ruta ha cambiado, ya que cada request se toma su tiempo en completar.
Chance acá luego implemento algo en node+mongo ó neo4j para hacer mi propio servicio sacándo todos los puntos de SCT a través de IFAI, a ver si ahora sí le agarro el pedo a dijkstra.
##devnotes
Las tarifas vigentes de carretera están en: http://aplicaciones4.sct.gob.mx/sibuac_internet/ControllerUI?action=CmdTarifaRep1&countVias=124&radioTipoIva=2&radioSel=1&selectVia=193&selectVia=196&selectVia=1&selectVia=209&selectVia=4&selectVia=5&selectVia=19&selectVia=7&selectVia=9&selectVia=10&selectVia=12&selectVia=13&selectVia=14&selectVia=16&selectVia=115&selectVia=18&selectVia=218&selectVia=20&selectVia=21&selectVia=22&selectVia=23&selectVia=118&selectVia=8&selectVia=195&selectVia=25&selectVia=26&selectVia=27&selectVia=28&selectVia=29&selectVia=30&selectVia=6&selectVia=32&selectVia=33&selectVia=35&selectVia=36&selectVia=37&selectVia=212&selectVia=176&selectVia=199&selectVia=39&selectVia=205&selectVia=48&selectVia=40&selectVia=217&selectVia=42&selectVia=43&selectVia=45&selectVia=49&selectVia=51&selectVia=52&selectVia=54&selectVia=55&selectVia=56&selectVia=57&selectVia=58&selectVia=59&selectVia=219&selectVia=203&selectVia=60&selectVia=61&selectVia=62&selectVia=192&selectVia=65&selectVia=66&selectVia=67&selectVia=68&selectVia=64&selectVia=69&selectVia=70&selectVia=72&selectVia=73&selectVia=74&selectVia=75&selectVia=76&selectVia=77&selectVia=78&selectVia=79&selectVia=198&selectVia=80&selectVia=81&selectVia=162&selectVia=83&selectVia=84&selectVia=85&selectVia=87&selectVia=86&selectVia=88&selectVia=90&selectVia=91&selectVia=89&selectVia=92&selectVia=93&selectVia=94&selectVia=95&selectVia=96&selectVia=97&selectVia=98&selectVia=99&selectVia=100&selectVia=101&selectVia=102&selectVia=103&selectVia=104&selectVia=106&selectVia=107&selectVia=31&selectVia=109&selectVia=110&selectVia=50&selectVia=114&selectVia=180&selectVia=111&selectVia=112&selectVia=200&selectVia=119&selectVia=207&selectVia=204&selectVia=117&selectVia=120&selectVia=121&selectVia=122&selectVia=123&selectVia=124&selectVia=125
Chance <EMAIL> me puede dar más info sobre el tipo de proyección or the lack thereof para poder convertir sus fakeCoords a algo que entienda el resto del mundo
Los servers de aplicaciones5-aplicaciones10 andan con "Options +Indexes", y los demås seguro tienen apps con las que pueda jugar
http://aplicaciones4.sct.gob.mx/sibuac_internet/ControllerUI?action=cmdRutaSolGeo&kml=19315%2C19341%2C24200%2C19344%2C19321%2C24202 da otro mapa, pero el kml no existe, ó a veces existe, o de plano vale verga (http://aplicaciones4.sct.gob.mx/sibuac_internet/SerTraerImagen?ruta=nullCuernavacaAcapulco.kml) Chance tiene algo que ver con ese null?<file_sep>#!/usr/bin/env ruby
#encoding: utf-8
require 'mongo'
require 'json'
require 'pp'
###############
# WIP #
###############
base = File.dirname(File.absolute_path(__FILE__))
content = Iconv.iconv('utf-8', 'iso8859-1', File.open("#{base}/.cache", 'r').read).join ''
data = JSON.parse(content)
data['puntos'].each {|id, punto|
if (punto['nombre'].match(/canc[úu]n/i) || punto['nombre'].match(/zócalo/i) || punto['nombre'].match(/tijuana/i))
pp punto
end
}<file_sep>require 'httparty'
require 'json'
require 'pp'
class SCT
include HTTParty
base_uri 'http://aplicaciones4.sct.gob.mx/sibuac_internet/'
def self.toLat (string)
return (string.to_f*0.04466225452111452)
end
def self.toLon (string)
return -(string.to_f*0.06779817526740388)
end
end<file_sep>#!/usr/bin/env ruby
#encoding: utf-8
begin
base = File.dirname(File.absolute_path(__FILE__))
require "#{base}/common.rb"
require 'nokogiri'
rescue
puts 'Seguro falta algún gem: nogokiri, httparty ó algo por el estilo'
end
if ARGV.count != 2
$stdout.write <<-USAGE
Usage: ruta id_inicio id_fin
Requiero dos argumentos, el id de origen y el id de destino,
por ejemplo \"901\" y \"17050\", que es de Zócalo DF a Cuernavaca
Los ids salen de ./cache por ahora, idealmente estaríangeoreferenciados...
¿supongo?
Regresa: JSON
{
tramos: los tramos que marca SCT en su modalidad
'simplificada', con los tiempos, distancias
y costos asociados;
puntos: Los puntos entre las dos ids, del cual chance
y pueque pueda sacar lat/lon de mercator,
totales: {
distancia: La distancia total a recorrer,
tiempo: El tiempo total del recorrido,
costo: El costo de casetas, de haber
}
Cada tramo consta de:
{
tramo: el nombre del tramo,
estado: la abreviación del estado,
carretera: [opcional] Si es una carretera,
distancia: La distancia del inicio al final del tramo,
tiempo: El tiempo de recorrido del tramo,
caseta: [opcional] el nombre de la caseta,
costo: [opcional] El costo de la caseta
}
Cada punto consta de:
{
inicio: {
nombre: El nombre del punto,
lat: la latitud en el mapa de SCT del punto,
lon: la longitud en el mapa de SCT del punto,
tipo: el tipo de inicio del punto
},
fin: {
nombre: idem,
lat: idem,
lon: idem,
tipo: idem
},
tipo: el tipo del tramo
}
Cabe mencionar que las coordenadas de los puntos aquí, no corresponden a aquellas
de los puntos de "./cache" porque a SCT seguro no se le prendió el foco que usar
coordenadas de una proyección estandar para toda su aplicación sería lo más
conveniente...
USAGE
exit 1
end
#si digo true, uso un archivo de cache para no pedirle nada a SCT y tenga que hacerme viejo en lo que su server pitero contesta
dev = false
from, to = ARGV
cache = File.open("#{base}/.cache", 'r')
begin
data = JSON.parse cache.read, :symbolize_names => true
rescue Exception => e
puts "No pude leer el cache, tal vez hay que correr primero ./cache?"
exit 1
end
from = from.ljust(4, "0")
to = to.ljust(4, "0")
begin
estadoOrigen = data[:puntos][:"#{from}"][:estado]
estadoDestino = data[:puntos][:"#{to}"][:estado]
rescue Exception => e
puts 'Alguno de los puntos que me diste no existen, chécalos!'
exit 1
end
query = {
action: 'cmdSolRutasApple',
tipo: 1,
red: 'simplificada',
edoOrigen: estadoOrigen,
ciudadOrigen: from,
edoDestino: estadoDestino,
ciudadDestino: to,
vehiculos: 2 #de automóvil
}
begin
if !dev
metodoInventadoParaCacharLaExcepcionPorqueSoyUnHuevon
end
html = File.open("#{base}/.htmlCache", 'r')
respuesta = Iconv.iconv('utf-8', 'iso8859-1', html.read).join ''
#respuesta = respuesta.read
rescue
respuesta = SCT.get('/ControllerUI', :query => query).body
html = File.open("#{base}/.htmlCache", 'w+')
html << respuesta
end
html = Nokogiri::HTML(respuesta)
tramos = []
puntos = []
puntosARecorrer = html.css('input[name=destino]')[0].attr('value').split('&')
puntosARecorrer.each {|punto|
inicio, inicio_x, inicio_y, fin, fin_x, fin_y, inicio_tipo, fin_tipo, tipo_punto = punto.split('#')
puntos.push({
inicio: {
nombre: inicio,
lat: inicio_x, #SCT.toLat(inicio_x),
lon: inicio_y, #SCT.toLon(inicio_y),
tipo: inicio_tipo
},
fin: {
nombre: fin,
lat: fin_x, #SCT.toLat(fin_x),
lon: fin_y, #SCT.toLon(fin_y),
tipo: fin_tipo
},
tipo: tipo_punto
})
}
trs = html.css('#tContenido tr')
indexes = [
'tramo',
'estado',
'carretera',
'distancia',
'tiempo',
'caseta',
'costo'
]
distancia = 0.0;
tiempo = 0;
costo = 0.0
trs[2..trs.count-3].each {|node|
tramo = {}
#porque para SCT, es importante tener <tr> vacíos
next unless node.content.strip != ''
node.css('td').each_with_index {|row, index|
#El nuevo padding es ¬¬
value = row.text.gsub(/\302\240/, ' ').strip
next unless value != ''
case index
when 2
# Quitamos "carreteras" que sean Zona Urbana
next unless value != 'Zona Urbana'
when 3
#sumamos distancia
value.to_f
distancia += value
when 4
#Hacemos las horas cantidad de minutos
horas, minutos = value.split(':')
value = ((horas*60) + minutos).to_i
tiempo += value
when 6
#sumamos costo
value = value.to_f
costo += value
end
tramo[indexes[index]] = value
}
tramos.push(tramo)
}
respuesta = {
tramos: tramos,
puntos: puntos,
totales: {
distancia: distancia,
tiempo: tiempo,
costo: costo
}
}
puts respuesta.to_json | e6bd91224293de83dda9b79fd7a1fbd6c0c66fc8 | [
"Markdown",
"Ruby"
] | 5 | Ruby | angelscabrerag/trazaturuta | fda88968d4a2ed0a737c83478c65d9ebde9d2b62 | 15e88cdff761ed88a771de6f5503b4e607ab3c85 |
refs/heads/master | <repo_name>jstnjns/jquery-nearest<file_sep>/js/jquery.nearest.js
(function() {
$.fn.nearest = function(selector) {
var $found = $(),
checkChildren = function(filter) {
var $children = this.children()
$collection = $();
$children.each(function() {
var $matches = $(this).filter(filter),
$fails = $(this).not(filter);
if($matches.length) { $found = $found.add($matches); }
if($fails.length) { checkChildren.call($fails, filter); }
});
};
checkChildren.call(this, selector);
return $found;
}
}());<file_sep>/js/global.js
$(function() {
$(document.body)
.nearest('.end')
.addClass('nearest');
});<file_sep>/readme.markdown
# jQuery Nearest
There have been few, but significant moments where `.find()` and `.children()` have just not been enough. Instances where the opposite of `.closest()` were necessary. Finding the 'nearest' recursive child element is an expensive task (heck, traversing the DOM in general makes me shiver), but on a rare occasion you'll find it a necessary task. That's where `$().nearest()` debuts.
## Documentation
There's not much to document other than there is one argument, the "filter".
```js
$('body').nearest('.end-child');
```
The filter attribute is simply any CSS selector you might pass as a jQuery....query. | 8f0bd270cea7ef46c3ebd73c8fdd2f4d30dff430 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | jstnjns/jquery-nearest | 835a5daa8ddfd2dcd21b212e5f5da9a293198d10 | 4c2ec5b6dfae9740fc2fb49e15386a136da17aed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.