branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/main
|
<repo_name>jovanesDev/NubceoFronEnd<file_sep>/front-end/src/components/MusicStore/MuiscStore.jsx
import React, {useEffect} from "react";
import { useSelector } from "react-redux";
import Grid from '@material-ui/core/Grid'
import {useStyles} from "./styles"
import Bands from "../Bands/Bands";
import UseFilterByGenre from "../../hooks/UseFilterByGenre";
import NotFound from "../404/NotFound";
const MusicStore = ({search}) => {
const classes = useStyles()
const changed = useSelector(state => state.musicStore.changed);
const filterGenre = useSelector(state => state.musicStore.filterGenre);
useEffect(() => {
},[changed])
const [state] = UseFilterByGenre(filterGenre);
const searchItems = state != null && state.filter((char) => (char.name.toLowerCase().includes(search.toLowerCase())))
return (
<Grid
container
spacing={1}
className={classes.conatiner}
>
{(searchItems < 1) && <NotFound/>}
{state != null && searchItems.map((band) => (
<Bands
key={band.id}
name={band.name}
genre={band.genreCode}
year={band.year}
country={band.country}
members={band.members}
id={band.id}
/>
))}
</Grid>
);
};
export default MusicStore;
<file_sep>/front-end/src/components/MusicStore/styles.jsx
import { makeStyles } from "@material-ui/core";
export const useStyles = makeStyles((theme) => ({
conatiner:{
marginBottom:"30px",
minHeight:"93vh",
width:"88%",
marginLeft:"12%"
}
}))<file_sep>/front-end/src/components/UI/Spinner/Spinner.jsx
import React from 'react'
import CircularProgress from '@material-ui/core/CircularProgress';
import {useStyles} from './styles'
const Spinner = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<CircularProgress style={{width:"100px",height:"100px"}}/>
</div>
)
}
export default Spinner
<file_sep>/front-end/src/actions/loadingActions.jsx
import {HIDE_LOADING, SHOW_LOADING} from '../types/types'
export const showLoading = () => {
return ({
type: SHOW_LOADING,
payload : true
})
}
export const hideLoading = () => {
return ({
type:HIDE_LOADING,
payload: false
})
}<file_sep>/front-end/src/hooks/UseFindAlbums.jsx
import { useSelector } from 'react-redux'
const UseFindAlbum = (id) => {
const state = useSelector(state => state.musicStore.albums)
const album = state.filter((album) => (album.bandId === Number(id)))
return [album]
}
export default UseFindAlbum
<file_sep>/front-end/src/components/Bands/Bands.jsx
import {Link} from "react-router-dom"
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import { useStyles } from "./styles";
const Bands = ({name,genre,year,members,country,id}) => {
const classes = useStyles();
return (
<Grid item xs={12} sm={12} md={4} lg={3}>
<Card className={classes.root} variant="outlined">
<CardContent>
<Typography variant="h5" component="h2">
{name}
</Typography>
<Typography className={classes.pos} color="textSecondary">
{genre}
</Typography>
<Typography variant="body2" component="p">
{year}
</Typography>
</CardContent>
<CardActions>
<Link to={`/band/${id}`}>
<Button size="small">Learn More</Button>
</Link>
</CardActions>
</Card>
</Grid>
);
};
export default Bands;
<file_sep>/front-end/src/components/Routes/PrivateComponent.jsx
import React, { useEffect } from "react";
import { Route, Redirect } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { getUserWithToken } from "../../actions/userActions";
import { getMusicStore } from "../../actions/musicStoreActions";
const PrivateComponent = ({ component: Component, ...props }) => {
const token = sessionStorage.getItem("token");
const dispatch = useDispatch();
const auth = useSelector((state) => state.user.auth);
useEffect(() => {
if (token && !auth) {
dispatch(getUserWithToken(token));
}
// eslint-disable-next-line
}, []);
useEffect(() => {
if (token && auth) {
dispatch(getMusicStore(token));
}
// eslint-disable-next-line
}, [token,auth]);
return (
<Route
{...props}
render={(props) =>
!auth || !token ? <Redirect to="/" /> : <Component {...props} />
}
/>
);
};
export default PrivateComponent;
<file_sep>/front-end/src/components/UI/ErrorAlert/ErrorAlert.jsx
import Swal from "sweetalert2"
const errorAlert = (text) => {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: `${text}`,
})
}
export default errorAlert;<file_sep>/README.md
# NubceoFronEnd
Nubceo Front End with React Challenge
# Installation
after clone this repository run "npm install" in folders server and front-end to install all dependencies
# Run Project
1) run "npm run dev" in folder /server/ to enable user authenticaction
2) run "npm start" in folder /front-end/
3) use user credentials to successfully log in
# User Credentials
in folder server you can find archive "users.json" , here you can find email and password to successfully log in
<file_sep>/front-end/src/components/BandsInfo/styles.jsx
import { makeStyles } from "@material-ui/core";
export const useStyles = makeStyles((theme) => ({
root: {
background: "rgb(0,0,0,0.8)",
width: "100%",
minHeight: "100vh",
display: "flex",
justifyContent: "center",
},
container: {
background: "#fff",
borderRadius: "15px",
padding: "20px 0",
},
title: {
textTransform: "uppercase",
},
backButton:{
marginTop:"50px",
padding:"20px 0"
}
}));
<file_sep>/front-end/src/actions/userActions.jsx
import { LOGIN_FAILED, LOGIN_SUCCESS, LOG_OUT, USER_WITH_TOKEN_FAILED, USER_WITH_TOKEN_SUCCESS } from "../types/types"
import { hideLoading, showLoading } from "./loadingActions"
import axios from "../axios/axiosClient"
import errorAlert from "../components/UI/ErrorAlert/ErrorAlert";
export const loginRequest = (data) => {
const {email,password} = data;
return async (dispatch) => {
dispatch(showLoading())
try {
const result = await axios.post("/auth/login",{email,password});
dispatch(loginSuccess(result.data))
dispatch(hideLoading())
} catch (error) {
dispatch(loginFailed())
dispatch(hideLoading())
errorAlert("Email or Password Incorrect")
}
}
}
const loginSuccess = (user) => ({
type:LOGIN_SUCCESS,
payload : user
})
const loginFailed = () => ({
type:LOGIN_FAILED,
payload : null
})
export const getUserWithToken = (token) => {
return async (dispatch) => {
dispatch(showLoading())
try {
const result = await axios.get("/user",{
headers: {
"Authorization":`Bearer ${token}`
}
})
dispatch(getUserWithTokenSuccess(result))
dispatch(hideLoading())
} catch (error) {
dispatch(getUserWithTokenFalied())
dispatch(hideLoading())
errorAlert("Token is experied , please Log In")
}
}
}
const getUserWithTokenSuccess = (user) => ({
type:USER_WITH_TOKEN_SUCCESS,
payload:user
})
const getUserWithTokenFalied = () => ({
type:USER_WITH_TOKEN_FAILED,
payload:null
})
export const logOut = () => ({
type:LOG_OUT,
})<file_sep>/front-end/src/components/Home/Home.jsx
import React, { useState } from 'react'
import Navbar from "../UI/Navbar/Navbar"
import Container from "@material-ui/core/Container";
import MusicStore from "../MusicStore/MuiscStore"
const Home = () => {
const [search,setSearch] = useState("")
return (
<main>
<Container maxWidth="xl">
<Navbar setSearch={setSearch}/>
<MusicStore search={search}/>
</Container>
</main>
)
}
export default Home
<file_sep>/front-end/src/types/types.jsx
export const SHOW_LOADING = "SHOW_LOADING";
export const HIDE_LOADING = "HIDE_LOADING";
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAILED = "LOGIN_FAILED" ;
export const USER_WITH_TOKEN_SUCCESS = "USER_WITH_TOKEN_SUCCESS";
export const USER_WITH_TOKEN_FAILED = "USER_WITH_TOKEN_FAILED";
export const LOG_OUT = "LOG_OUT";
export const GET_MUSIC_STORE_SUCCESS = "GET_MUSIC_STORE_SUCCESS";
export const GET_MUSIC_STORE_FAILED = "GET_MUSIC_STORE_FAILED";
export const SORT_ASC = "SORT_ASC";
export const SORT_DESC = "SORT_DESC";
export const FILTER_BY_GENRE = "FILTER_BY_GENRE";
export const MUSIC_STORE_CHANGED = "MUSIC_STORE_CHANGED"<file_sep>/front-end/src/hooks/UseFilterByGenre.jsx
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
const UseFilterByGenre = (param) => {
const bands = useSelector(state => state.musicStore.bands);
const filterGenre = useSelector(state => state.musicStore.filterGenre);
const [state, setState] = useState(bands)
useEffect(() => {
if(bands){
setState(bands)
}
filter(param)
// eslint-disable-next-line
}, [bands,filterGenre])
const filter = (param) => {
setState(bands);
if(param === ""){
setState(bands);
return;
}else {
setState(state.filter((band) => band.genreCode === param))
}
}
return [state]
}
export default UseFilterByGenre
<file_sep>/front-end/src/components/UI/Navbar/Navbar.jsx
import React from "react";
import { useDispatch } from "react-redux";
import clsx from "clsx";
import CssBaseline from "@material-ui/core/CssBaseline";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import Button from "@material-ui/core/Button";
import MenuIcon from "@material-ui/icons/Menu";
import TextField from "@material-ui/core/TextField";
import Drawer from "../Drawer/SideBar";
import Hidden from "@material-ui/core/Hidden";
import ExitToAppIcon from "@material-ui/icons/ExitToApp";
import { useStyles } from "./styles";
import { logOut } from "../../../actions/userActions";
const Navbar = ({setSearch}) => {
const classes = useStyles();
const dispatch = useDispatch();
const [open, setOpen] = React.useState(false);
const handleDrawerOpen = () => {
setOpen(true);
};
const handleDrawerClose = () => {
setOpen(false);
};
const handleChange = e => {
setSearch(e.target.value)
}
return (
<div className={classes.root}>
<CssBaseline />
<AppBar
className={clsx(classes.appBar, {
[classes.appBarShift]: open,
})}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={handleDrawerOpen}
edge="start"
className={clsx(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography className={classes.title} variant="h6" noWrap>
Nubceo-App
</Typography>
<TextField color="secondary" variant="outlined" onChange={handleChange} label="Search" />
<Hidden smDown>
<div className={classes.navButtonsContainer}>
<Button
variant="contained"
color="secondary"
size="large"
onClick={() => dispatch(logOut())}
startIcon={<ExitToAppIcon />}
>
logout
</Button>
</div>
</Hidden>
</Toolbar>
</AppBar>
<Drawer
open={open}
handleDrawerClose={handleDrawerClose}
logOut={logOut}
/>
</div>
);
};
export default Navbar;
<file_sep>/front-end/src/helpers/validEmptyFields.jsx
const validateOneField = (field) => {
if(field.trim() === ""){
return true;
}
}
const validateFields = (fields) => {
let invalid = false;
for (let i= 0; i < fields.length; i++) {
if(validateOneField(fields[i])){
invalid = true;
}
}
return invalid;
}
export default validateFields;<file_sep>/front-end/src/components/UI/Navbar/styles.jsx
import { makeStyles} from '@material-ui/core/styles';
const drawerWidth = 240;
export const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
marginBottom:"100px",
},
appBar: {
background:theme.palette.primary.main,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
padding:"12px 0 ",
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
marginLeft: drawerWidth,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
menuButton: {
marginRight: theme.spacing(2),
},
hide: {
display: 'none',
},
title:{
flexGrow:1
},
navButtonsContainer:{
margin:"0 40px",
justifyContent:"flex-end"
}
}));<file_sep>/front-end/src/reducers/musicStoreReducer.jsx
import { GET_MUSIC_STORE_FAILED, GET_MUSIC_STORE_SUCCESS, SORT_ASC, SORT_DESC,MUSIC_STORE_CHANGED, FILTER_BY_GENRE } from "../types/types";
const initialState = {
bands:null,
albums:null,
genre:null,
changed:false,
filterGenre:"",
}
const reducer = (state = initialState,action) => {
switch (action.type) {
case GET_MUSIC_STORE_SUCCESS:
return{
...state,
bands:action.payload.bands,
albums:action.payload.albums,
genre:action.payload.genre
}
case GET_MUSIC_STORE_FAILED:
return{
...state,
bands:action.payload,
albums:action.payload,
genre:action.payload
}
case SORT_ASC:
case SORT_DESC:
return {
...state,
bands:action.payload,
changed:false,
}
case FILTER_BY_GENRE:
return{
...state,
filterGenre:action.payload,
changed:false
}
case MUSIC_STORE_CHANGED:
return{
...state,
changed:true,
}
default:
return state;
}
}
export default reducer<file_sep>/front-end/src/hooks/UseFindBandInfo.jsx
import { useSelector } from 'react-redux'
const UseFindBandInfo = (id) => {
const state = useSelector(state => state.musicStore.bands)
const band = state.filter((band) => (band.id === Number(id)))
return [band[0]]
}
export default UseFindBandInfo
<file_sep>/front-end/src/components/BandsInfo/Information/Information.jsx
import React from "react";
import Typography from "@material-ui/core/Typography";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import Box from "@material-ui/core/Box";
import { useStyles } from "./styles";
const Information = ({name,country,genreCode,year}) => {
const classes = useStyles()
return (
<>
<List>
<ListItem>
<Typography className={classes.text}>
<Box fontStyle="normal" textAlign="justify" fontSize={22} m={1}>
Name : {name}
</Box>
</Typography>
</ListItem>
<ListItem>
<Typography className={classes.text}>
<Box fontStyle="normal" textAlign="justify" fontSize={22} m={1}>
Year : {year}
</Box>
</Typography>
</ListItem>
<ListItem>
<Typography className={classes.text}>
<Box fontStyle="normal" textAlign="justify" fontSize={22} m={1}>
Genre : {genreCode}
</Box>
</Typography>
</ListItem>
<ListItem>
<Typography className={classes.text}>
<Box fontStyle="normal" textAlign="justify" fontSize={22} m={1}>
Country : {country}
</Box>
</Typography>
</ListItem>
</List>
</>
);
};
export default Information;
<file_sep>/front-end/src/components/BandsInfo/BandsInfo.jsx
import React from "react";
import { useStyles } from "./styles";
import { useParams,Link } from "react-router-dom";
import Container from "@material-ui/core/Container";
import Typography from "@material-ui/core/Typography";
import Divider from "@material-ui/core/Divider";
import Box from "@material-ui/core/Box";
import UseFindBandInfo from "../../hooks/UseFindBandInfo";
import Information from "./Information/Information";
import Members from "./Members/Members";
import Albums from "./Albums/Albums";
import { Button } from "@material-ui/core";
const BandsInfo = () => {
const classes = useStyles();
const { id } = useParams();
const [band] = UseFindBandInfo(id);
const { name, country, genreCode, year, members } = band;
return (
<div className={classes.root}>
<Container className={classes.container} maxWidth="sm">
<Typography className={classes.title} variant="h4">
<Box fontStyle="bold" textAlign="center" m={4}>
Information
</Box>
</Typography>
<Divider />
<Information
name={name}
country={country}
genreCode={genreCode}
year={year}
/>
<Divider/>
<Members members={members}/>
<Divider/>
<Albums id={id}/>
<Divider/>
<Link to="/home" >
<Button className={classes.backButton} fullWidth variant="contained" size="large" color="secondary">Volver</Button>
</Link>
</Container>
</div>
);
};
export default BandsInfo;
<file_sep>/front-end/src/components/404/NotFound.jsx
import React from 'react'
import Typography from "@material-ui/core/Typography";
const NotFound = () => {
return (
<Typography variant="h3"
style={{display:"flex",flexGrow:"1",justifyContent:"center",alignItems:"center",textTransform:"uppercase"}}
>
No Result ...
</Typography>
)
}
export default NotFound
|
daed2b8375a9a685acbed271eeed4b09346723c9
|
[
"JavaScript",
"Markdown"
] | 22 |
JavaScript
|
jovanesDev/NubceoFronEnd
|
e52eeccf1755a56c32457259de5607bfc47919de
|
0618b4b5e2791c633c82d64b616f1b417e60c612
|
refs/heads/master
|
<repo_name>Akemon/XingChuangBackstage<file_sep>/XingChuangBackstage/src/mode/Worker.java
package mode;
public class Worker {
private String peopleName;
private String companyName;
private String companyPhone;
private String companyAddress;
private String userName;
private String updateTime;
public String getPeopleName() {
return peopleName;
}
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyPhone() {
return companyPhone;
}
public void setCompanyPhone(String companyPhone) {
this.companyPhone = companyPhone;
}
public String getCompanyAddress() {
return companyAddress;
}
public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/XingChuangBackstage/src/database/ConnectDatabase.java
package database;
import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
public class ConnectDatabase {
private String url="jdbc:sqlserver://localhost;DatabaseName=XingChuang";
private String name="sa";
private String pass="<PASSWORD>";
public ConnectDatabase(){
try {
// Mysql 的驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("加载驱动失败!!!");
e.printStackTrace();
}
}
public Connection getConn(){
// 获取数据库的连接
Connection connection = null;
try{
connection= DriverManager.getConnection(url, name, pass);
}catch(Exception e){
System.out.println("获取数据库连接失败!!!");
e.printStackTrace();
}
return connection ;
}
public static void main(String args[]){
Connection conn =new ConnectDatabase().getConn();
}
}
<file_sep>/XingChuangBackstage/src/database/UserData.java
package database;
import java.sql.*;
public class UserData {
public ConnectDatabase connectDatabase =new ConnectDatabase();
public boolean check(String name,String pass){
Connection conn =connectDatabase.getConn();
try {
Statement stmt =conn.createStatement();
ResultSet rs =stmt.executeQuery("select * from userLogin where userName ='"+name+"'");
if(rs.next()){
String userPass =rs.getString("userPass");
if(pass.equals(userPass)) return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
<file_sep>/XingChuangBackstage/src/servlet/getStudentInfo.java
package servlet;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import database.StudentData;
import mode.Student;
/**
* Servlet implementation class getStudentInfo
*/
@WebServlet("/getStudentInfo")
public class getStudentInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public getStudentInfo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String pageNumber =request.getParameter("pageNumber");
String pageSize =request.getParameter("pageSize");
String searchString =request.getParameter("searchString");
PrintWriter pw =response.getWriter();
List<Student> studentList = new StudentData().queryStudentInformation(pageNumber, pageSize,searchString);
JSONArray jsonArray =JSONArray.fromObject(studentList);
JSONObject jsonObject =new JSONObject();
int allDataNumber =new StudentData().getTotalDataNumber();
jsonObject.put("listInformation", jsonArray);
jsonObject.put("allDataNumber", allDataNumber);
pw.write(jsonObject.toString());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<file_sep>/XingChuangBackstage/src/database/CompanyData.java
package database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import mode.Student;
import mode.Worker;
import service.WorkerService;
public class CompanyData {
public ConnectDatabase connectDatabase =new ConnectDatabase();
//游标可移动的查询
public List<Worker> queryWorkerInformation(String pageNumber,String pageSize,String searchString ){
Connection connection =connectDatabase.getConn();
String sql="";
String preSql="";
if(searchString.equals("")){
sql ="select * from enterpriseData";
}else{
preSql ="select * from enterpriseData where peopleName like ? "
+ " or companyName like ? or companyPhone like ? or "
+ "companyAddress like ? or userName like ?";
}
List<Worker> workList =new ArrayList<Worker>();
if(preSql.equals("")){
try {
Statement statement =connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs =statement.executeQuery(sql);
//移动游标
ResultSet rsNew =new WorkerService().moveCursor(pageNumber, pageSize, rs);
//页面展示数据数
int showDataNumber =Integer.parseInt(pageSize);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for(int i=0;i<showDataNumber;i++){
Worker worker =new Worker();
worker.setPeopleName(rsNew.getString("peopleName"));
worker.setCompanyName(rsNew.getString("companyName"));
worker.setCompanyPhone(rsNew.getString("companyPhone"));
worker.setCompanyAddress(rsNew.getString("companyAddress"));
worker.setUserName(rsNew.getString("userName"));
worker.setUpdateTime(df.format(rsNew.getDate("updateTime")));
workList.add(worker);
if(!rsNew.next()) break;
}
}catch(Exception e){
System.out.println("遍历企业数据失败!!!");
e.printStackTrace();
}
}else{
try {
PreparedStatement preStmt =connection.prepareStatement(preSql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
preStmt.setString(1, "%"+searchString+"%");
preStmt.setString(2, "%"+searchString+"%");
preStmt.setString(3, "%"+searchString+"%");
preStmt.setString(4, "%"+searchString+"%");
preStmt.setString(5, "%"+searchString+"%");
ResultSet rs =preStmt.executeQuery();
//移动游标
ResultSet rsNew =new WorkerService().moveCursor(pageNumber, pageSize, rs);
//页面展示数据数
int showDataNumber =Integer.parseInt(pageSize);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
for(int i=0;i<showDataNumber;i++){
Worker worker =new Worker();
worker.setPeopleName(rsNew.getString("peopleName"));
worker.setCompanyName(rsNew.getString("companyName"));
worker.setCompanyPhone(rsNew.getString("companyPhone"));
worker.setCompanyAddress(rsNew.getString("companyAddress"));
worker.setUserName(rsNew.getString("userName"));
worker.setUpdateTime(df.format(rsNew.getDate("updateTime")));
workList.add(worker);
if(!rsNew.next()) break;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return workList;
}
//更新
public void updateWorkerInformation(Worker worker){
Connection connection =connectDatabase.getConn();
try{
String sql ="update enterpriseData set peopleName=?,companyName=?,companyPhone=?,companyAddress=? where userName=?";
PreparedStatement preStatement =connection.prepareStatement(sql);
preStatement.setString(1, worker.getPeopleName());
preStatement.setString(2, worker.getCompanyName());
preStatement.setString(3, worker.getCompanyPhone());
preStatement.setString(4, worker.getCompanyAddress());
preStatement.setString(5, worker.getUserName());
preStatement.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
}
//删除
public void deleteWorkerInformation(String userName){
Connection connection =connectDatabase.getConn();
try {
Statement stmt1 =connection.createStatement();
stmt1.executeUpdate("delete from enterpriseData where userName='"+userName+"'" );
Statement stmt2 =connection.createStatement();
stmt2.executeUpdate( "delete from userLogin where userName='"+userName+"'");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int getTotalDataNumber(){
Connection connection =connectDatabase.getConn();
int total = 0;
try {
Statement statement =connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs =statement.executeQuery("select * from enterpriseData");
rs.last();
total =rs.getRow();
} catch (SQLException e) {
System.out.println("获取所有数据条数失败!!!");
e.printStackTrace();
}
return total;
}
}
<file_sep>/XingChuangBackstage/src/mode/Student.java
package mode;
public class Student {
private String stuNickName;
private String stuSex;
private String stuMail;
private String stuPhone;
private String stuSchool;
private String stuCharacSigna;
private String stuVerifyQuestion;
private String stuVerifyAnswer ;
private String stuPoints;
private String userName;
private String updateTime;
public String getStuNickName() {
return stuNickName;
}
public void setStuNickName(String stuNickName) {
this.stuNickName = stuNickName;
}
public String getStuSex() {
return stuSex;
}
public void setStuSex(String stuSex) {
this.stuSex = stuSex;
}
public String getStuMail() {
return stuMail;
}
public void setStuMail(String stuMail) {
this.stuMail = stuMail;
}
public String getStuPhone() {
return stuPhone;
}
public void setStuPhone(String stuPhone) {
this.stuPhone = stuPhone;
}
public String getStuSchool() {
return stuSchool;
}
public void setStuSchool(String stuSchool) {
this.stuSchool = stuSchool;
}
public String getStuCharacSigna() {
return stuCharacSigna;
}
public void setStuCharacSigna(String stuCharacSigna) {
this.stuCharacSigna = stuCharacSigna;
}
public String getStuVerifyQuestion() {
return stuVerifyQuestion;
}
public void setStuVerifyQuestion(String stuVerifyQuestion) {
this.stuVerifyQuestion = stuVerifyQuestion;
}
public String getStuVerifyAnswer() {
return stuVerifyAnswer;
}
public void setStuVerifyAnswer(String stuVerifyAnswer) {
this.stuVerifyAnswer = stuVerifyAnswer;
}
public String getStuPoints() {
return stuPoints;
}
public void setStuPoints(String stuPoints) {
this.stuPoints = stuPoints;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
}
<file_sep>/XingChuangBackstage/src/servlet/LoginCheck.java
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.UserData;
/**
* Servlet implementation class LoginCheck
*/
@WebServlet("/LoginCheck")
public class LoginCheck extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginCheck() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name =new String (request.getParameter("userName").getBytes("ISO-8859-1"));
String pass =new String (request.getParameter("pass").getBytes("ISO-8859-1"));
boolean flag =new UserData().check(name, pass);
System.out.println(flag);
if(flag){
String number =request.getParameter("numberCheck");
HttpSession session =request.getSession();
String correctNumber =(String) session.getAttribute("rand");
if(correctNumber.equals(number)){
session.setAttribute("user",name);
RequestDispatcher disPatcher =request.getRequestDispatcher("index.jsp");
disPatcher.forward(request, response);
}else{
RequestDispatcher disPatcher =request.getRequestDispatcher("adminLogin.jsp?login=false");
disPatcher.forward(request, response);
}
}else{
RequestDispatcher disPatcher =request.getRequestDispatcher("adminLogin.jsp?login=false");
disPatcher.forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
370c4346c6eef59d7d0dbbf84ce41c3be5c351d1
|
[
"Java"
] | 7 |
Java
|
Akemon/XingChuangBackstage
|
0a901ff42cc364939b0a9337642e1679429cbf9c
|
3cfff295b9442c4842ab2458879b34baed75db9d
|
refs/heads/master
|
<file_sep>from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Post,Tag,Category
from comments.froms import CommentForm
import markdown
from django.views.generic import ListView,DetailView
from markdown.extensions.toc import TocExtension,slugify
from django.db.models import Q
# Create your views here.
class IndexView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
paginate_by = 2
def index(request):
post_list=Post.objects.all().order_by('-created_time')
return render(request,"blog/index.html",context={'post_list':post_list})
def detail(request,pk):
post=get_object_or_404(Post,pk=pk)
post.get_view_num()
post.body = markdown.markdown(post.body,
extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
'markdown.extensions.toc',
])
form=CommentForm()
comment_list=post.comment_set.all()
context={'post':post,
'form':form,
'comment_list':comment_list}
return render(request,'blog/detail.html',context=context)
class PostDetailView(DetailView):
model = Post
template_name = 'blog/detail.html'
context_object_name = 'post'
def get(self, request, *args, **kwargs):
response = super(PostDetailView, self).get(request, *args, **kwargs)
self.object.get_view_num()
return response
def get_object(self, queryset=None):
post = super(PostDetailView, self).get_object(queryset=None)
md = markdown.Markdown(extensions=[
'markdown.extensions.extra',
'markdown.extensions.codehilite',
TocExtension(slugify=slugify),
])
post.body = md.convert(post.body)
post.toc = md.toc
return post
def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
form = CommentForm()
comment_list = self.object.comment_set.all()
context.update({
'form': form,
'comment_list': comment_list
})
return context
class ArchivesView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
def get_queryset(self):
return super(ArchivesView,self).get_queryset().filter(created_time__year=self.kwargs.get('year'),
created_time__month=self.kwargs.get('month')).order_by('-created_time')
def archives(request,year,month):
post_list=Post.objects.filter(created_time__year=year,
created_time__month=month
).order_by('-created_time')
return render(request,'blog/index.html',context={'post_list':post_list})
class CategoryView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
def get_queryset(self):
cate=get_object_or_404(Category,pk=self.kwargs.get('pk'))
return super(CategoryView,self).get_queryset().filter(category=cate)
def category(request,pk):
cate=get_object_or_404(Category,pk=pk)
post_list=Post.objects.filter(category=cate).order_by('-created_time')
return render(request,'blog/index.html',context={'post_list':post_list})
class TagView(ListView):
model = Post
template_name = 'blog/index.html'
context_object_name = 'post_list'
def get_queryset(self):
tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))
return super(TagView, self).get_queryset().filter(tags=tag)
def tag(request,pk):
tag=get_object_or_404(Tag,pk=pk)
post_list=Post.objects.filter(tags=tag).order_by('-created_time')
return render(request,'blog/index.html',context={'post_list':post_list})
def search(request):
q=request.GET.get('q')
error_msg=''
if not q:
error_msg='请输入关键词'
return render(request,'blog/index.html',{'error_msg':error_msg})
post_list=Post.objects.filter(Q(title__icontains=q)|Q(body__icontains=q))
return render(request,'blog/index.html',{'error_msg':error_msg,
'post_list':post_list})
|
2920b55b747582eea025581f4eb3298a1e01b075
|
[
"Python"
] | 1 |
Python
|
sgithubss/myblog
|
ae99c5b154c85cba6c40c72adbd0fbd0e6f60079
|
14b4278f5f4908d4173b5b77d87c551a47327c2e
|
refs/heads/master
|
<repo_name>Vman45/nautilus-scripts-12<file_sep>/whois-script
#!/bin/bash
cd $NAUTILUS_SCRIPT_CURRENT_URI
count=0
percent=0
lines=`wc -l $* | awk '{print $1}'`
rm tmp.txt 2>/dev/null
sort -u $* > $*_unique
echo "Net Range;Net Name;Route;Origin / OrgTechHandle;Country;Organization, notes;IP;Domain" > tmp.csv
while read line; do
domain=""
count=`expr $count + 1`
percent=`expr $count \* 100 / $lines`
echo "$percent"
if [ `echo $line | grep [a-z]` ]; then
domain=$line
lookup=`nslookup $line | grep 'Address' | grep -v '#' | awk '{print $2}'`
line=`echo $lookup | awk '{print $1}'`
fi
whois $line > whoistmp.txt
if [[ `cat whoistmp.txt | grep -v 'No whois server'` ]]; then
cat whoistmp.txt | grep inetnum: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep netname: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep route: | awk -F ' +' '{printf $2" "}' >> tmp.csv
if [[ `cat whoistmp.txt | grep 'route'` ]]; then
printf ";" >> tmp.csv
fi
cat whoistmp.txt | grep origin: | awk -F ' +' '{printf $2" "}' >> tmp.csv
if [[ `cat whoistmp.txt | grep 'route'` ]]; then
printf ";" >> tmp.csv
fi
cat whoistmp.txt | grep country: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep descr: | awk -F ' +' '{printf $2" "}' >> tmp.csv
cat whoistmp.txt | grep NetRange: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep NetName: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep CIDR: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep OrgTechHandle: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep Country: | awk -F ' +' '{printf $2";"}' >> tmp.csv
cat whoistmp.txt | grep OrgName: | awk -F ' +' '{printf $2" "}' >> tmp.csv
echo ";$line;$domain" >> tmp.csv
fi
done < $*_unique | zenity --progress --title="$*" --text="$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" --percentage=0 --no-cancel
rm $*_unique
rm whoistmp.txt
mv tmp.csv $*_`date +%Y%m%d-%H%M%S`.csv
|
a00c131a5a3c58d7c5494cde6da70336a09286fe
|
[
"Shell"
] | 1 |
Shell
|
Vman45/nautilus-scripts-12
|
3ed92bec00e1dd201d4aa6f5d707d86b7a950a0e
|
7287d70f2f625bcf3b53aa32c82b4205a607970a
|
refs/heads/master
|
<repo_name>chrispjacobs/songs_lab<file_sep>/test.rb
class Artist
attr_accessor :name
def initialize(name)
@name = name
@songs_array = []
end
def songs
@songs_array
end
def add_song(song_variable)
@songs_array << song_variable
if song_variable.artist == nil
song_variable.artist = self
end
end
def add_song_by_name(name_string)
new_song_variable = Song.new
new_song_variable.name = name_string
if new_song_variable.artist == nil
new_song_variable.artist = self
end
end
def song_count
@songs_array.count
end
end
class Song
@@all = []
attr_accessor :name, :artist
def initialize(name)
@name = name
@@all << self
end
def artist=(artist)
@artist = artist
artist.add_song(self)
end
def self.all
@@all
end
def artist_name
if self.artist != nil
if self.artist.name != nil
self.artist.name
end
else
nil
end
end
end
the_beatles = Artist.new("The Beatles")
help = Song.new("Help!")
puts "help.artist returns #{help.artist}"
the_beatles.add_song(help)
puts "the_beatles.songs returns #{the_beatles.songs}" # Why does this return multiple instances of the song help? How did multiple instances even come to exist?
puts "help.artist now returns #{help.artist}"
|
7ff69302379ca136f0e0d6ba11b17d6fad7c0baa
|
[
"Ruby"
] | 1 |
Ruby
|
chrispjacobs/songs_lab
|
cfcbed1a3621143c73dd9d517b2e07937f2e7cc7
|
ade157a8aaab19cccf1a56af1c1f7c130ea7cabf
|
refs/heads/master
|
<file_sep>import React from 'react';
const SavedCharacter = props => {
return(
<div>{props.character.name}</div>
)
}
export default SavedCharacter
<file_sep>import React from 'react'
import {
Card, CardImg, CardBody,
CardTitle, CardSubtitle, Button
} from 'reactstrap';
import { connect } from 'react-redux'
import { saveCharacter } from '../actions/saveCharacterAction.js'
const Character = props => {
return(
<Card inverse style={{ backgroundColor: '#333',
borderColor: '#333', borderRadius: '25px',
margin: '20px', padding: '20px', fontFamily: 'Courier New', width: '20rem'}}>
<CardImg inverse style = {{borderRadius: '25px'}}
top width="100%" alt= 'character'
src={props.character.image} />
<CardBody inverse style= {{color: 'white'}}>
<CardTitle>Name: {props.character.name}</CardTitle>
<CardSubtitle>Status: {props.character.status}</CardSubtitle>
<CardSubtitle>Species: {props.character.species}</CardSubtitle>
<button onClick={() => props.saveCharacter(props.character)}>Save Character</button>
</CardBody>
</Card>
)
}
export default connect (null, { saveCharacter })(Character)<file_sep>import {
FETCH_CHARACTERS_FAIL,
FETCH_CHARACTERS_SUCCESS,
FETCH_CHARACTERS_START
} from '../actions'
const initalState = {
characters: [],
error: '',
isFetching: false
};
export const allCharactersReducer = (state = initalState, action) => {
switch(action.type){
case FETCH_CHARACTERS_START:
return {
...state,
isFetching: true,
error: ''
};
case FETCH_CHARACTERS_SUCCESS:
return {
...state,
characters: action.payload,
isFetching: false,
error: ''
};
case FETCH_CHARACTERS_FAIL:
return {
...state,
error: action.payload
}
default:
return state;
}
}<file_sep>import React from 'react';
import { connect } from 'react-redux'
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
import './App.css';
import { Button } from '@material-ui/core'
import { getAllCharacters } from './actions'
import { getRandomCharacter } from './actions'
import Character from './componets/Character';
import saveCharacter from './componets/saveCharacter'
import SavedCharacter from './componets/saveCharacter';
const App = props => {
const fetchAllCharacters = e => {
e.preventDefault();
props.getAllCharacters();
}
const fetchRandomCharacter = e => {
e.preventDefault();
props.getRandomCharacter();
}
return (
<div className='App'>
<h2> <NAME> </h2>
<nav>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/saved'>Saved</Link>
</li>
</nav>
<div className="characters-container">
<Switch>
<Route path='/all'>
{
props.characters.map(item =>
<Character key={item.id} character={item}/>)
}
</Route>
<Route path='/random'>
{
<Character character={props.character}/>
}
</Route>
<Route path='/saved'>
{
props.savedCharacters.map(item =>
<Character character={item}/>)
}
</Route>
</Switch>
</div>
<button onClick={fetchAllCharacters}>
<Link to='/all'>Get All Characters</Link>
</button>
<button onClick={fetchRandomCharacter}>
<Link to='/random'>Get Random Character</Link>
</button>
</div>
)
}
const mapStateToProps = state => {
return {
characters: state.allCharactersReducer.characters,
error: state.allCharactersReducer.error,
isFetching: state.allCharactersReducer.isFetching,
character: state.randomCharacterReducer.character,
savedCharacters: state.saveCharactersReducer.savedCharacters
}
}
export default connect(mapStateToProps, { getAllCharacters, getRandomCharacter })(App);
<file_sep>export const SAVE_CHARACTER = 'SAVE_CHARACTER'
export const saveCharacter = (character) => { //action creator
return { type: SAVE_CHARACTER, payload: character } //action object, //feature is a whole object btw
}
|
89cb870703606c340184f42422828abce6b42fd6
|
[
"JavaScript"
] | 5 |
JavaScript
|
jme-sull/React-Redux-App
|
257c5c9b86b9a0e06a5fa790c649b657a27acaa6
|
3eae95596113f7654b1a35d92cda4fc60977cc7f
|
refs/heads/master
|
<repo_name>leleomaster/asp.net_core_2<file_sep>/README.md
# asp.net_core_2
Learning asp.net core 2
<file_sep>/LearnAspnetCore_2_Page/Models/Customer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace LearnAspnetCore_2_Page.Models
{
public class Customer
{
public int Id { get; set; }
[Required, StringLength(100)]
public string Nome { get; set; }
[Required, StringLength(100)]
public string Cpf { get; set; }
[Required, StringLength(11)]
public string Telefone { get; set; }
[Required, StringLength(2)]
public string Estado { get; set; }
[Required, StringLength(50)]
public string Cidade { get; set; }
[Required, StringLength(25)]
public string Pais { get; set; }
}
}
|
b0c9cae2a60f7f74cd63a2bf95f815e4826c1555
|
[
"Markdown",
"C#"
] | 2 |
Markdown
|
leleomaster/asp.net_core_2
|
3476aade5b0b150d52ace4e63457fdee27572558
|
66c35c7e1633f928b66ac5a8e4b4473fc39fdfef
|
refs/heads/master
|
<file_sep>"""
This example shows how to use stratified sampling to have an equal number
of samples from each class in each batch
"""
import torch
import numpy as np
from torchsample import StratifiedSampler
y = torch.from_numpy(np.array([0, 0, 1, 1, 0, 0, 1, 1]))
sampler = StratifiedSampler(class_vector=y, batch_size=2)
for i, batch_idx in enumerate(sampler):
print(batch_idx, ' - ' , y[batch_idx])
if (i+1) % 2 == 0:
print('\n')
#[out]:
#7 - 1
#1 - 0
#0 - 0
#3 - 1
#4 - 0
#2 - 1
#5 - 0
#6 - 1
#You can see that it evenly samples each batch from
#the 0 and 1 classes. To use it in a sampler:
import torch
import numpy as np
from torchsample import TensorDataset
x = torch.randn(8,2)
y = torch.from_numpy(np.array([0, 0, 1, 1, 0, 0, 1, 1]))
loader = TensorDataset(x, y, batch_size=4, sampler='stratified')
for xbatch, ybatch in loader:
print(ybatch.numpy())
# AND IT WORKS FOR MORE THAN 2 CLASSES
import torch
import numpy as np
from torchsample import TensorDataset
x = torch.randn(8,2)
y = torch.from_numpy(np.array([0, 0, 1, 1, 2, 2, 3, 3]))
loader = TensorDataset(x, y, batch_size=4, sampler='stratified')
for xbatch, ybatch in loader:
print(ybatch.numpy())
# OR:
x = torch.randn(8,2)
y = torch.from_numpy(np.array([0, 0, 1, 1, 0, 0, 1, 1]))
sampler = StratifiedSampler(y, batch_size=2)
loader = TensorDataset(x, y, batch_size=2, sampler=sampler)<file_sep># torch-sample : data augmentation and sampling for pytorch
 
This package provides a set of transforms and data structures for sampling from in-memory or out-of-memory data.
I'm actively taking requests for new transforms or new features to the samplers.
(see [for example](https://github.com/ncullen93/torchsample/issues/1))
## Unique Features
- affine transforms
- transforms directly on arbitrary torch tensors (rather than just PIL images)
- perform transforms on data where both input and target are images
- sample and transform images with no target
- save transformed/augmented images to file
- sample arbitrary data directly from folders with speed
- stratified sampling
- variable batch size (e.g. `loader.next_batch(10)`)
- sample for a fixed number of batches without using an `epoch` loop
## Tutorials and examples
- [torchsample overview](https://github.com/ncullen93/torchsample/blob/master/tutorials/torchsample%20tutorial.ipynb)
- [samplers overview](https://github.com/ncullen93/torchsample/blob/master/tutorials/Samplers.ipynb)
- [cifar in-memory](https://github.com/ncullen93/torchsample/blob/master/examples/cifar_TensorDataset.py)
- [stratified sampling](https://github.com/ncullen93/torchsample/blob/master/examples/stratified_sampling.py)
- [variable batch size](https://github.com/ncullen93/torchsample/blob/master/examples/variable_batchsize.py)
## Example
Perform transforms on datasets where both inputs and targets are images in-memory:
```python
from torchvision.datasets import MNIST
train = MNIST(root='/users/ncullen/desktop/data/', train=True, download=True)
x_train = train.train_data
process = Compose([TypeCast('float'), AddChannel(), RangeNormalize(0,1)])
affine = Affine(rotation_range=30, zoom_range=(1.0,1.4), shear_range=0.1,
translation_range=(0.2,0.2))
tform = Compose([process, affine])
train_loader = TensorDataset(x_train, x_train, co_transform=tform, batch_size=3)
x_batch, y_batch = train_loader.next_batch()
```
Load data out-of-memory using regular expressions:
```python
from torchsample import FolderDataset
train_loader = FolderDataset(root='/users/ncullen/desktop/my_data/',
input_regex='*img*', target_regex='*mask*',
batch_size=32, co_transform=tform, batch_size=3)
x_batch, y_batch = train_loader.next_batch()
```
## Transforms
### Torch Transforms
These transforms work directly on torch tensors
- `Compose()`
- `AddChannel()`
- `SwapDims()`
- `RangeNormalize()`
- `StdNormalize()`
- `Slice2D()`
- `RandomCrop()`
- `SpecialCrop()`
- `Pad()`
- `RandomFlip()`
- `ToTensor()`
### Affine Transforms
The following transforms perform affine (or affine-like) transforms on torch tensors.
- `Rotate()`
- `Translate()`
- `Shear()`
- `Zoom()`
We also provide a class for stringing multiple affine transformations together so that only one interpolation takes place:
- `Affine()`
- `AffineCompose()`
## Sampling
We provide the following datasets which provide general structure and iterators for sampling from and using transforms on in-memory or out-of-memory data:
- `TensorDataset()`
- `FolderDataset()`
<file_sep>
from __future__ import absolute_import
from . import transforms
from .dataset_iter import *
from .datasets import *
from .samplers import *<file_sep>
from __future__ import absolute_import
from .dataset_iter import default_collate, DatasetIter
from .samplers import RandomSampler, SequentialSampler, StratifiedSampler
import torch
import os
import os.path
import warnings
import fnmatch
import math
import numpy as np
try:
import nibabel
except:
warnings.warn('Cant import nibabel.. Cant load brain images')
try:
from PIL import Image
except:
warnings.warn('Cant import PIL.. Cant load PIL images')
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
'.nii.gz', '.npy'
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def find_classes(dir):
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
def pil_loader(path):
return Image.open(path).convert('RGB')
def npy_loader(path):
return torch.from_numpy(np.load(path).astype('float32'))
def nifti_loader(path):
return nibabel.load(path)
def make_dataset(directory, class_mode, class_to_idx=None,
input_regex=None, target_regex=None, ):
"""Map a dataset from a root folder"""
if class_mode == 'image':
if not input_regex and not target_regex:
raise ValueError('must give input_regex and target_regex if'+
' class_mode==image')
inputs = []
targets = []
for subdir in sorted(os.listdir(directory)):
d = os.path.join(directory, subdir)
if not os.path.isdir(d):
continue
for root, _, fnames in sorted(os.walk(d)):
for fname in fnames:
if is_image_file(fname):
if fnmatch.fnmatch(fname, input_regex):
path = os.path.join(root, fname)
inputs.append(path)
if class_mode == 'label':
targets.append(class_to_idx[subdir])
if class_mode == 'image' and \
fnmatch.fnmatch(fname, target_regex):
path = os.path.join(root, fname)
targets.append(path)
if class_mode is None:
return inputs
else:
return inputs, targets
class Dataset(object):
"""An abstract class representing a Dataset.
All other datasets should subclass it. All subclasses should override
``__len__``, that provides the size of the dataset, and ``__getitem__``,
supporting integer indexing in range from 0 to len(self) exclusive.
"""
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def one_epoch(self):
"""Return an iterator that will loop through all the samples one time"""
return DatasetIter(self)
def __iter__(self):
"""Return an iterator that will loop through all the samples one time"""
return DatasetIter(self)
def __next__(self):
"""Return the next batch in the data. If this batch is the last
batch in the data, the iterator will be reset -- allowing you
to loop through the data ad infinitum
"""
new_batch = next(self._iter)
self.batches_seen += 1
if self.batches_seen % self.nb_batches == 0:
#print('Last Batch of Current Epoch')
self._iter = DatasetIter(self)
return new_batch
def next_batch(self, batch_size=None):
_old_batch_size = self._iter.batch_size
if batch_size is not None:
self._iter.batch_size = batch_size
new_batch = next(self._iter)
self.batches_seen += 1
if self.batches_seen % self.nb_batches == 0:
#print('Last Batch of Current Epoch')
self._iter = DatasetIter(self)
# go back to default batch size
self._iter.batch_size = _old_batch_size
return new_batch
next = __next__
class FolderDataset(Dataset):
def __init__(self,
root,
class_mode='label',
input_regex='*',
target_regex=None,
transform=None,
target_transform=None,
co_transform=None,
loader='npy',
batch_size=1,
shuffle=False,
sampler=None,
num_workers=0,
collate_fn=default_collate,
pin_memory=False):
"""Dataset class for loading out-of-memory data.
Arguments
---------
root : string
path to main directory
class_mode : string in `{'label', 'image'}`
type of target sample to look for and return
`label` = return class folder as target
`image` = return another image as target as found by 'target_regex'
NOTE: if class_mode == 'image', you must give an
input and target regex and the input/target images should
be in a folder together with no other images in that folder
input_regex : string (default is any valid image file)
regular expression to find input images
e.g. if all your inputs have the word 'input',
you'd enter something like input_regex='*input*'
target_regex : string (default is Nothing)
regular expression to find target images if class_mode == 'image'
e.g. if all your targets have the word 'segment',
you'd enter somthing like target_regex='*segment*'
transform : torch transform
transform to apply to input sample individually
target_transform : torch transform
transform to apply to target sample individually
loader : string in `{'npy', 'pil', 'nifti'} or function
defines how to load samples from file
if a function is provided, it should take in a file path
as input and return the loaded sample.
Examples
--------
For loading input images and target images (e.g. image and its segmentation):
>>> data = FolderDataset(root=/path/to/main/dir,
class_mode='image', input_regex='*input*',
target_regex='*segment*', loader='pil')
For loading input images with sub-directory as class label:
>>> data = FolderDataset(root=/path/to/main/dir,
class_mode='label', loader='pil')
"""
if loader == 'npy':
loader = npy_loader
elif loader == 'pil':
loader = pil_loader
elif loader == 'nifti':
loader = nifti_loader
root = os.path.expanduser(root)
classes, class_to_idx = find_classes(root)
inputs, targets = make_dataset(root, class_mode,
class_to_idx, input_regex, target_regex)
if len(inputs) == 0:
raise(RuntimeError("Found 0 images in subfolders of: " + root + "\n"
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
self.root = os.path.expanduser(root)
self.inputs = inputs
self.targets = targets
self.classes = classes
self.class_to_idx = class_to_idx
self.transform = transform
self.target_transform = target_transform
self.co_transform = co_transform
self.loader = loader
self.class_mode = class_mode
self.batch_size = batch_size
self.num_workers = num_workers
self.collate_fn = collate_fn
self.pin_memory = pin_memory
if sampler is not None:
self.sampler = sampler
elif shuffle:
self.sampler = RandomSampler(nb_samples=len(self.inputs))
elif not shuffle:
self.sampler = SequentialSampler(nb_samples=len(self.inputs))
if class_mode == 'image':
print('Found %i input images and %i target images' %
(len(self.inputs), len(self.targets)))
elif class_mode == 'label':
print('Found %i input images across %i classes' %
(len(self.inputs), len(self.classes)))
self.batches_seen = 0
self.nb_batches = int(math.ceil(len(self.sampler) / float(self.batch_size)))
self._iter = DatasetIter(self)
def __getitem__(self, index):
# get paths
input_sample = self.inputs[index]
target_sample = self.targets[index]
# load samples into memory
input_sample = self.loader(input_sample)
if self.class_mode == 'image':
target_sample = self.loader(target_sample)
# apply transforms
if self.transform is not None:
input_sample = self.transform(input_sample)
if self.target_transform is not None:
target_sample = self.target_transform(target_sample)
if self.co_transform is not None:
input_sample, target_sample = self.co_transform(input_sample, target_sample)
return input_sample, target_sample
def __len__(self):
return len(self.inputs)
class TensorDataset(Dataset):
def __init__(self,
input_tensor,
target_tensor=None,
transform=None,
target_transform=None,
co_transform=None,
batch_size=1,
shuffle=False,
sampler=None,
num_workers=0,
collate_fn=default_collate,
pin_memory=False):
"""Dataset class for loading in-memory data.
Arguments
---------
input_tensor : torch tensor
target_tensor : torch tensor
transform : torch transform
transform to apply to input sample individually
target_transform : torch transform
transform to apply to target sample individually
loader : string in `{'npy', 'pil', 'nifti'} or function
defines how to load samples from file
if a function is provided, it should take in a file path
as input and return the loaded sample.
Examples
--------
For loading input images and target images (e.g. image and its segmentation):
>>> data = FolderDataset(root=/path/to/main/dir,
class_mode='image', input_regex='*input*',
target_regex='*segment*', loader='pil')
For loading input images with sub-directory as class label:
>>> data = FolderDataset(root=/path/to/main/dir,
class_mode='label', loader='pil')
"""
self.inputs = input_tensor
self.targets = target_tensor
if target_tensor is None:
self.has_target = False
else:
self.has_target = True
self.transform = transform
self.target_transform = target_transform
self.co_transform = co_transform
self.batch_size = batch_size
self.num_workers = num_workers
self.collate_fn = collate_fn
self.pin_memory = pin_memory
if sampler == 'stratified':
self.sampler = StratifiedSampler(class_vector=self.targets,
batch_size=self.batch_size)
elif sampler == 'random':
self.sampler = RandomSampler(nb_samples=len(self.inputs))
elif sampler == 'sequential':
self.sampler = SequentialSampler(nb_samples=len(self.inputs))
elif sampler is not None and not isinstance(sampler, str):
self.sampler = sampler
else:
if shuffle:
self.sampler = RandomSampler(nb_samples=len(self.inputs))
elif not shuffle:
self.sampler = SequentialSampler(nb_samples=len(self.inputs))
self.batches_seen = 0
self.nb_batches = int(math.ceil(len(self.sampler) / float(self.batch_size)))
self._iter = DatasetIter(self)
def __getitem__(self, index):
"""Return a (transformed) input and target sample from an integer index"""
# get paths
input_sample = self.inputs[index]
if self.has_target:
target_sample = self.targets[index]
# apply transforms
if self.transform is not None:
input_sample = self.transform(input_sample)
if self.has_target and self.target_transform is not None:
target_sample = self.target_transform(target_sample)
if self.has_target and self.co_transform is not None:
input_sample, target_sample = self.co_transform(input_sample, target_sample)
if self.has_target:
return input_sample, target_sample
else:
return input_sample
def __len__(self):
"""Number of samples"""
return self.inputs.size(0)
<file_sep>"""
Classify CIFAR10 using a ConvNet and the TensorDataset sampler
"""
import numpy as np
from torchvision.datasets import CIFAR10
data = CIFAR10(root='/users/ncullen/desktop/DATA/cifar/', train=True,
download=True)
x_train = data.train_data # numpy array (50k, 3, 32, 32)
y_train = np.array(data.train_labels) # numpy array (50k,)
data = CIFAR10(root='/users/ncullen/desktop/DATA/cifar/', train=False,
download=True)
x_test = data.test_data # (10k, 3, 32, 32)
y_test = np.array(data.test_labels) # (10k,)
import torch
# convert these to torch tensors
x_train = torch.from_numpy(x_train.astype('float32')).float()
y_train = torch.from_numpy(y_train.astype('uint8')).long()
x_test = torch.from_numpy(x_test.astype('float32')).float()
y_test = torch.from_numpy(y_test.astype('uint8')).long()
## Build the network
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
class Network(nn.Module):
def __init__(self, input_size=(3,32,32)):
super(Network, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3,32,3),
nn.ReLU(),
nn.Conv2d(32,32,3),
nn.ReLU(),
nn.MaxPool2d((3,3))
)
self.flat_fts = self.get_flat_fts(input_size, self.features)
self.classifier = nn.Sequential(
nn.Linear(self.flat_fts, 100),
nn.Dropout(p=0.2),
nn.ReLU(),
nn.Linear(100,10),
nn.LogSoftmax()
)
def get_flat_fts(self, in_size, fts):
f = fts(Variable(torch.ones(1,*in_size)))
return int(np.prod(f.size()[1:]))
def forward(self, x):
fts = self.features(x)
flat_fts = fts.view(-1, self.flat_fts)
out = self.classifier(flat_fts)
return out
def set_optimizer(self, opt):
self.opt = opt
def set_loss(self, loss_fn):
self.loss_fn = loss_fn
def fit(self, x, y, batch_size, nb_epoch):
train_loader = TensorDataset(x, y, batch_size=batch_size)
for epoch in range(nb_epoch):
self.train_loop(train_loader)
def fit_loader(self, loader, nb_epoch):
for epoch in range(nb_epoch):
self.train_loop(loader)
def train_loop(self, loader):
for batch_idx, (x_batch, y_batch) in enumerate(loader):
loss = self.batch_loop(x_batch, y_batch)
if batch_idx % 10 == 0:
print('Batch {} - Loss : {:.02f}'.format(batch_idx,
loss))
def batch_loop(self, x_batch, y_batch):
x_batch = Variable(x_batch)
y_batch = Variable(y_batch)
self.opt.zero_grad()
ypred = self(x_batch)
loss = self.loss_fn(ypred, y_batch)
loss.backward()
self.opt.step()
return loss.data[0]
## Test that the network actually produces the correctly-sized output
net = Network()
net.set_optimizer(optim.Adam(net.parameters()))
net.set_loss(F.nll_loss)
## create sampler
from torchsample import TensorDataset
from torchsample.transforms import RangeNormalize
NB_EPOCH = 10
BATCH_SIZE = 32
train_loader = TensorDataset(x_train, y_train,
transform=RangeNormalize(0.,1.,n_channels=3),
batch_size=BATCH_SIZE, shuffle=False, num_workers=0)
net.fit_loader(train_loader, nb_epoch=10)
<file_sep>
from torchsample.transforms import ToTensor, Compose, RangeNormalize, Slice2D
from torchsample import DataLoader
from torchsample import FolderDataset
def example_RangeNormalize():
tform = Compose([ToTensor(), RangeNormalize(-1,1)])
data = FolderDataset(root='~/desktop/data/segmentation/skullstrip_hcp_2mm_npy/',
class_mode='image', input_regex='*img*', target_regex='*mask*',
loader='npy', transform=tform)
loader = iter(DataLoader(data))
x,y = loader.next()
print(x.min()) # -1
print(x.max()) # +1
def example_Slice():
tform = Compose([ToTensor(), Slice2D(axis=0)])
data = FolderDataset(root='/users/ncullen/desktop/data/segmentation/skullstrip_hcp_2mm_npy/',
class_mode='image', input_regex='*img*', target_regex='*mask*',
loader='npy', co_transform=tform)
loader = iter(DataLoader(data))
x,y = loader.next()
print(x.size()) # (109, 91) -> now 2d instead of 3d
print(y.size()) # (109, 91) -> now 2d instead of 3d<file_sep>"""
Classify CIFAR10 using a ConvNet and the TensorDataset sampler
"""
import numpy as np
from torchvision.datasets import CIFAR10
data = CIFAR10(root='/users/ncullen/desktop/DATA/cifar/', train=True,
download=True)
x_train = data.train_data # numpy array (50k, 3, 32, 32)
y_train = np.array(data.train_labels) # numpy array (50k,)
data = CIFAR10(root='/users/ncullen/desktop/DATA/cifar/', train=False,
download=True)
x_test = data.test_data # (10k, 3, 32, 32)
y_test = np.array(data.test_labels) # (10k,)
import torch
# convert these to torch tensors
x_train = torch.from_numpy(x_train.astype('float32')).float()
y_train = torch.from_numpy(y_train.astype('uint8')).long()
x_test = torch.from_numpy(x_test.astype('float32')).float()
y_test = torch.from_numpy(y_test.astype('uint8')).long()
## Build the network
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
class Network(nn.Module):
def __init__(self, input_size=(3,32,32)):
super(Network, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3,32,3),
nn.ReLU(),
nn.Conv2d(32,32,3),
nn.ReLU(),
nn.MaxPool2d((3,3))
)
self.flat_fts = self.get_flat_fts(input_size, self.features)
self.classifier = nn.Sequential(
nn.Linear(self.flat_fts, 100),
nn.Dropout(p=0.2),
nn.ReLU(),
nn.Linear(100,10),
nn.LogSoftmax()
)
def get_flat_fts(self, in_size, fts):
f = fts(Variable(torch.ones(1,*in_size)))
return int(np.prod(f.size()[1:]))
def forward(self, x):
fts = self.features(x)
flat_fts = fts.view(-1, self.flat_fts)
out = self.classifier(flat_fts)
return out
## Test that the network actually produces the correctly-sized output
net = Network()
## create optimizer
opt = optim.Adam(net.parameters())
## create sampler
from torchsample import TensorDataset
from torchsample.transforms import RangeNormalize
NB_EPOCH = 10
BATCH_SIZE = 32
train_sampler = TensorDataset(x_train, y_train,
transform=RangeNormalize(0.,1.,n_channels=3),
batch_size=BATCH_SIZE, shuffle=False, num_workers=0)
for epoch in range(NB_EPOCH):
for batch_idx, (x_batch, y_batch) in enumerate(train_sampler):
x_batch = Variable(x_batch)
y_batch = Variable(y_batch)
opt.zero_grad()
ypred = net(x_batch)
loss = F.nll_loss(ypred, y_batch)
loss.backward()
opt.step()
if batch_idx % 10 == 0:
print('Batch {} / {} - Loss : {:.02f}'.format(batch_idx,
train_sampler.nb_batches, loss.data[0]))
<file_sep>from torchsample import TensorDataset
import torch
import numpy as np
x = torch.ones(10,1,30,30)
y = torch.from_numpy(np.arange(10))
loader = TensorDataset(x, y, batch_size=2)
xbatch, ybatch = loader.next_batch()
print(ybatch.numpy())
xbatch, ybatch = loader.next_batch(3)
print(ybatch.numpy())
xbatch, ybatch = loader.next_batch()
print(ybatch.numpy())
# SAMPLE A FIXED NUMBER OF BATCHES WITHOUT STOPPING
for i in range(1000):
xbatch, ybatch = loader.next_batch()
# MAKE ONLY ONE PASS THROUGH THE DATA
for xbatch, ybatch in loader:
pass
# DEMONSTRATE THAT THE DATA WILL STILL BE SHUFFLE IF YOU USE NEXT_BATCH()
loader = TensorDataset(x, y, batch_size=2, shuffle=True)
# 10 loops = 2 epochs (n=10 / batch_size = 2 --> 5 loops per "epoch")
for i in range(10):
if i == 5:
print('\n')
xbatch, ybatch = loader.next_batch()
print(ybatch.numpy())
|
4dffe3a0d4453f5f09f57ea70272b0343d9bba72
|
[
"Markdown",
"Python"
] | 8 |
Python
|
sampathweb/torchsample
|
e69997377755af60ade1963be55d3fe3d7f8357d
|
d32d29b7658dd129c1111d31c451a344c8eaf65d
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# 1-example
# A simple demonstration script to find the largest prime number
# below a given limit.
#
# This file is intentionally inefficient in order to demonstrate
# various ways to time execution
#
# Usage:
# time python 1-example.py 10000
#
# Author: <NAME> <<EMAIL>>
# Created: Wed Sep 13 21:50:05 2015 -0400
#
# Copyright (C) 2015 georgetown.edu
# For license information, see LICENSE.txt
#
# ID: 1-example.py [] <EMAIL> $
"""
A simple demonstration script to find the largest prime number
below a given limit.
"""
##########################################################################
## Imports
##########################################################################
import sys
##########################################################################
## Code
##########################################################################
def is_prime(limit):
"""
Using the most time intensive method possible, return True or False
as to whether the supplied number is prime
"""
for number in range(2,limit):
if (limit % number) == 0:
return False
return True
def find_largest_prime(limit):
"""
Find the highest number below the supplied limit/upper bound
that is a prime number
"""
i = 2
largest_prime = None
while i < limit:
if is_prime(i):
largest_prime = i
i += 1
return largest_prime
##########################################################################
## Execution
##########################################################################
if __name__ == '__main__':
upper_bound = int(sys.argv[1])
print find_largest_prime(upper_bound)
<file_sep>Overview
--------
A collection of scripts to demonstrate very easy ways to benchmark code or time execution. These scripts are presented as a starting off point to get you thinking about performance and measurement.
Setup
-----
One of the example files requires a dependency that can be loaded using pip. To install the dependencies from the included requirements file use the `-r` flag as shown in the example below.
$ pip install -r requirements.txt
Example 1
---------
This example demonstrates the use of the `time` utility as found on most Unix like personal computers (may not be available on Windows). For more information on how to use the command, consult the man file with `man time`.
For a quick explanation of real, user, and sys values please review [this](http://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1#556411) Stack Overflow answer.
Usage:
$ time python 1-example.py 10000
Example 2
---------
This example script provides the most straightforward method to provide the elapsed time for a piece of code.
Usage:
$ python 2-example.py 10000
Example 3
---------
This example script uses a slightly more sophisticated method for timing a block of code through the use of Python context managers. For more information on context managers and the "with" statement consult [PEP 343](https://www.python.org/dev/peps/pep-0343/).
Usage:
$ python 3-example.py 10000
Example 4
---------
Finally, our last example uses the line_profiler library to provide line by line statistics into code execution and performance. For more information, visit the Github repository page at [https://github.com/rkern/line_profiler](https://github.com/rkern/line_profiler).
Notice how much time this level of profiling adds to the overall execution.
Usage:
$ kernprof -l -v 4-example.py 10000
<file_sep>line-profiler==1.0
wsgiref==0.1.2
|
f8cdcd5b470062acf75068333da0a3637f366ffd
|
[
"Markdown",
"Python",
"Text"
] | 3 |
Python
|
ArchAiA/xbus-501-timing-demonstrations
|
68ed1739b7acea7d561e6c682c68b916d8998ca1
|
46a3f83b8fa909367ec3343c6f4c60d85739ed54
|
refs/heads/master
|
<repo_name>csbt23/opencharity<file_sep>/README.md
# opencharity
Test project for Compucorp application
<file_sep>/page--node--1.tpl.php
<div id="container">
<header>
<nav>
<div class="row">
<div class="l2 m3 s12">
<?php if ($page['logo']): ?>
<?php print render($page['logo']); ?>
<?php endif; ?>
</div>
<div class="l10 m9 s12">
<?php if ($page['navigation']): ?>
<?php print render($page['navigation']); ?>
<?php endif; ?>
</div>
</div>
</nav>
<div id="banner" class="banner-container">
<div class="row">
<div class="l12 m12 s12 no-padding">
<?php if ($page['banner']): ?>
<?php print render($page['banner']); ?>
<?php endif; ?>
</div>
</div>
</div>
</header>
<div id="banner-bottom">
<div class="row">
<div class="l12 m12 s12">
<div id="banner_bottom">
<?php if ($page['banner_bottom']): ?>
<?php print render($page['banner_bottom']); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
<div id="content-top">
<div class="row">
<h2>GET INVOLVED</h2>
<div class="l4 m4 s12">
<div id="content_top_left" class="front-block">
<?php if ($page['content_top_left']): ?>
<?php print render($page['content_top_left']); ?>
<?php endif; ?>
</div>
</div>
<div class="l4 m4 s12">
<div id="content_top_mid" class="front-block">
<?php if ($page['content_top_mid']): ?>
<?php print render($page['content_top_mid']); ?>
<?php endif; ?>
</div>
</div>
<div class="l4 m4 s12">
<div id="content_top_right" class="front-block">
<?php if ($page['content_top_right']): ?>
<?php print render($page['content_top_right']); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
<main>
<div class="row">
<div class="l12 m12 s12">
<?php if ($messages): ?>
<div id="messages"><div class="section clearfix">
<?php print $messages; ?>
</div></div>
<?php endif; ?>
<div id="content">
<?php if ($tabs): ?>
<div class="tabs">
<?php print render($tabs); ?>
</div>
<?php endif; ?>
<?php print render($page['content']); ?>
</div>
<div class="l12 m12 s12">
<div id="main_content_second">
<?php if ($page['main_content_second']): ?>
<?php print render($page['main_content_second']); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
</main>
<div class="bottomcontent">
<div class="wide row whitebgd">
<div class="l12 m12 s12">
<div id="content_bottom">
<?php if ($page['content_bottom']): ?>
<?php print render($page['content_bottom']); ?>
<?php endif; ?>
</div>
</div>
</div>
</div>
<footer>
<div class="row">
<div class="l12 m12 s12">
<div id="footer_firstrow">
<?php if ($page['footer_firstrow']): ?>
<?php print render($page['footer_firstrow']); ?>
<?php endif; ?>
</div>
</div>
</div>
<div class="row">
<div class="l12 m12 s12">
<div id="footer_bottom">
<?php if ($page['footer_bottom']): ?>
<?php print render($page['footer_bottom']); ?>
<?php endif; ?>
</div>
</div>
</div>
</footer>
</div>
|
7e0b868901bfa8456df5cfe7a110c5c1fe797528
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
csbt23/opencharity
|
69bca371cfdbbf988d1c31cf4c5346a52582d569
|
295e904d4df2d8cc088e4d7e9fc505e86fe5c504
|
refs/heads/master
|
<file_sep>import json
import requests
import boto3
from requests_aws4auth import AWS4Auth
import inflect
def lambda_handler(event, context):
print(event)
print(event["queryStringParameters"]["q"])
p = inflect.engine()
lex_client = boto3.client('lex-runtime')
lex_response = lex_client.post_text(
botName='photoalbum',
botAlias='photoalbum',
userId='user1',
inputText=event["queryStringParameters"]["q"],
)
print(lex_response)
slots = lex_response["slots"]
keywords = slots["keywords"]
keywords_ = slots["keywords_"]
print(slots)
es_host = 'search-photos-ohg3afluv5djy2xmrjlfubafna.us-east-1.es.amazonaws.com'
index = 'photos'
url = 'https://' + es_host + '/' + index + '/_search/'
region = 'us-east-1' # For example, us-west-1
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)
headers = {"Content-Type": "application/json"}
if keywords is not None:
if p.singular_noun(keywords):
label_value = p.singular_noun(keywords)
else:
label_value = keywords
if keywords_ is not None:
if p.singular_noun(keywords_):
label_value += " AND " + p.singular_noun(keywords_)
else:
label_value += " AND " + keywords_
query = {
"query": {
"match": {"labels": label_value}
}
}
print(json.dumps(query))
r = requests.get(url, auth=awsauth, headers=headers, data=json.dumps(query))
r_dict = json.loads(r.text)
print("Peter")
print(r_dict)
result_list = r_dict["hits"]["hits"]
image_url_list = []
response = {}
response["results"] = []
if result_list is not None:
for result in result_list:
response_object = {}
s3_url = "https://" + result["_source"]["bucket"] + ".s3.amazonaws.com/" + result["_source"]["objectKey"]
response_object["url"] = s3_url
response_object["labels"] = result["_source"]["labels"]
response["results"].append(response_object)
print(response)
return {
'statusCode': 200,
'headers': {
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
'body': json.dumps(response)
}
|
6c6a4bdaaf9af373afcd5b6884f9435912bbbe55
|
[
"Python"
] | 1 |
Python
|
Rahul27297/IndexPhotosLambda
|
97fa28880e27271cc9b81bd157b11e33a18a68cd
|
bf621875b6aa8fa9cc139eea7c8021a3fad9bfc4
|
refs/heads/master
|
<file_sep>import numpy as np
import matplotlib.pyplot as plt
np.random.seed()
'''
=================================================================================================================================================================================
Function of true polynomial and creating noisy data
=================================================================================================================================================================================
'''
def poly_fun():
'''
=====================================================================
defined a polynomial function
---------------------------------------------------------------------
size : number of data points in X-axis
X : array of data points in X-axis
y_true : defining a function with known co-efficients
y_noise : for algorithm we need a noisy data here we are creating a noisy data
---------------------------------------------------------------------
return
y_noise
x
y_true
=====================================================================
'''
size = 80
x = np.linspace(1,2,size)
y_true = (0.2*x**3)+(0.5*x**2)+(0.8*x)
noise = np.random.normal(0,0.08,size)
y_noise = y_true + noise
return y_noise,x,y_true
'''
=================================================================================================================================================================================
'''
'''
=================================================================================================================================================================================
Function for jacobian
=================================================================================================================================================================================
'''
def jacobian(y,x):
'''
=====================================================================
jacobian of a function
---------------------------------------------------------------------
partial_1 : partial derivative of first term
partial_2 : partial derivative of second term
partial_3 : partial derivative of third term
---------------------------------------------------------------------
return
jacobian : array of partial deriavtives of the function
=====================================================================
'''
partial_1 = x**3
partial_2 = x**2
partial_3 = x
jacobian = np.array([partial_1,partial_2,partial_3])
return jacobian
'''
=================================================================================================================================================================================
'''
'''
=================================================================================================================================================================================
Function for model_function(m)
=================================================================================================================================================================================
'''
def quadratic_model(delta_y,f_0,gradient_0,hessian_0,ys=None):
'''
======================================================================
quadratic model
----------------------------------------------------------------------
delta_y : step
f_0 : function value f(delta_y=0)
gradient_0 : gradient g(delta_y=0)
hessian_0 : Hessian h(delta_y=0)
----------------------------------------------------------------------
return
m_1 : function f(delta_y)
======================================================================
'''
m_1 = f_0 + np.dot(gradient_0,delta_y)+0.5*np.dot(delta_y,np.dot(hessian_0,delta_y))
return m_1
'''
=================================================================================================================================================================================
'''
'''
=================================================================================================================================================================================
polynomial Function for algorithm
=================================================================================================================================================================================
'''
def poly_fun_unknown(y,x):
'''
=====================================================================
This function defined with unkown co-efficient
---------------------------------------------------------------------
a : unkown co-efficient of the first term
b : unkown co-efficient of the second term
c : unkown co-efficient of the third term
---------------------------------------------------------------------
return
y : algorithm computed co=efficient of a function
=====================================================================
'''
a = y[0]
b = y[1]
c = y[2]
y = (a*x**3)+(b*x**2)+(c*x)
return y
'''
=================================================================================================================================================================================
'''
'''
=================================================================================================================================================================================
Levenberg Marquardt algorithm
=================================================================================================================================================================================
'''
def levenberg_marquardt(y,poly_fun_unknown,jacobian,x,y_noise,lamda,f_tol,eta,max_iteration,lamda_iteration):
'''
======================================================================
Levenberg-Marquardt method for solving
nonlinear least square problems
----------------------------------------------------------------------
y : start parameter np.array([y1,...,yn])
poly_fun_unknown : function for for computing residuals r=poly_fun_unknown(y,x)-y
jacobian : function for jacobian which returns np.array([[dri/dyj,...,drm/dyn)
x : data points np.array([x1,...,xm])
y_noise : data values np.array([y_noise1,...,y_noisem])
lamda : initial value of lamda
ftol : termination criterion
eta : accuracy to accept step
max_iteration : maximum_number of iterations
lambda_itereration : maximum_number of lambda adjustions
----------------------------------------------------------------------
return:
y_1 : algorithm computed co-efficients
======================================================================
'''
no_of_data = len(x)
no_of_para = len(y)
ys = y
standard_deviation = np.std(y_noise)
y_0 = y
residual_0 = (poly_fun_unknown(y_0,x) - y_noise)/standard_deviation
f_0 = 0.5*(np.linalg.norm(residual_0)**2)
jacobian_0 = jacobian(y_0,x)/standard_deviation
gradient_0 = np.inner(jacobian_0,residual_0)
norm_gradient_0 = np.linalg.norm(gradient_0)
i = 1
j = 1
delta_f = 1
loop = 1
while ((abs(delta_f) > f_tol) and (i <= max_iteration) and (j <= lamda_iteration)):
f.write("="*80)
f.write("\n")
f.write(".."*10)
f.write("\n")
f.write("loop = ")
f.write("\t")
f.write(str(loop))
f.write("\n")
f.write(".."*10)
f.write("\n")
square_root_lamda = np.sqrt(lamda)
square_root_lamda_identity = square_root_lamda*np.eye(no_of_para)
jacobian_square_root_lamda_identity = np.hstack([jacobian_0,square_root_lamda_identity])
z = np.zeros(no_of_para)
residual_z = np.hstack([residual_0,z])
(delta_y,residual,rank,sv) = np.linalg.lstsq(jacobian_square_root_lamda_identity.T,-(residual_z), rcond=-1)
norm_delta_y = np.linalg.norm(delta_y)
y_1 = y_0 + delta_y
residual_1 = (poly_fun_unknown(y_1,x) - y_noise)/standard_deviation
f_1 = 0.5*(np.linalg.norm(residual_1)**2)
jacobian_1 = jacobian(y_1,x)/standard_deviation
gradient_1 = np.inner(jacobian_1,residual_1)
norm_gradient_1 = np.linalg.norm(gradient_1)
gradient_0 = np.inner(jacobian_0,residual_0)
#print('gradient_0',gradient_0)
hessian_0 = np.inner(jacobian_0,jacobian_0)
#print('hessian_0',hessian_0)
m_0 = f_0
m_1 = quadratic_model(delta_y,f_0,gradient_0,hessian_0,ys=ys)
a = np.divide((f_0 - f_1),(m_0 - m_1),out=np.zeros_like((m_0 - m_1)),where=(m_0 - m_1)!=0)
delta_f = f_1 - f_0
if a <= 0.25:
lamda = lamda*10
f.write('lamda is increased to = ')
f.write("")
f.write(str(lamda))
f.write("\n")
else:
if a > 0.75:
lamda = lamda/10
f.write('lamda is decreased to = ')
f.write("")
f.write(str(lamda))
f.write("\n")
# else:
# print('keeping same lamda',lamda)
if a > eta:
f.write('step accepted')
f.write("\n")
y_0 = y_1
residual_0 = residual_1
f_0 = f_1
jacobian_0 = jacobian_1
j = 1
i += 1
else:
f.write('step rejected')
f.write("\n")
delta_f = 1
j += 1
if i > max_iteration:
f.write('maximum number of iteration is reached')
if j > lamda_iteration:
f.write('maximum number of lamda iteration is reached')
loop = loop +1
f.write('='*80)
f.write("\n")
f.write('Algorithim computed coeeficient')
f.write("\t")
f.write(str(y_1))
return y_1
'''
=================================================================================================================================================================================
'''
'''
=================================================================================================================================================================================
calling algorithm and writing an output file
=================================================================================================================================================================================
'''
'''y : initial guess for the algorithm'''
y = np.array([10,20,30])
'''Calling a function which generates data for algorithm and true values'''
y_noise,x,y_true = poly_fun()
'''writing an output in a file and calling algorithm'''
with open('Algorithm_testing.txt', 'w') as f:
f.write("="*80)
f.write("\n")
f.write("\t\t\tprogram test for algorithm\n")
f.write("="*80)
f.write("\n")
f.write(".."*20)
f.write("\n")
f.write("True polynomial function = 0.2X^3+0.5X^2+0.8X")
f.write("\n")
f.write(".."*20)
f.write("\n")
f.write("initial guess = ")
f.write(str(y))
f.write("\n")
lm = levenberg_marquardt(y,poly_fun_unknown,jacobian,x,y_noise,lamda = 0.0001,f_tol = 1e-10,eta = 0.001,max_iteration = 100,lamda_iteration = 20)
'''
=================================================================================================================================================================================
Post processing
=================================================================================================================================================================================
'''
'''y_sim : final co-efficients computed by algorithm and for testing data and training data i am suffling the data'''
y_sim = poly_fun_unknown(lm,x)
total_shuffle = np.array([y_noise,x]).T
np.random.shuffle(total_shuffle)
training = total_shuffle[:int(len(x)*0.6)]
testing = total_shuffle[int(len(x)*0.6):]
'''plots for the true function and algorithm computed co-efficient function'''
fig,ax = plt.subplots(2,constrained_layout=True)
ax[0].plot(x,y_true,color='blue',label='True data')
ax[0].scatter(x,y_noise,color='red',marker='.')
ax[1].plot(x,y_true,color='blue',label='True data')
ax[1].plot(x,y_sim,color='black',linestyle ='--',label='simulated data')
ax[1].scatter(x,y_noise,color='red',marker='.')
ax[0].grid()
ax[0].legend()
ax[1].grid()
ax[1].legend()
ax[0].set_title('True function curve ')
ax[0].set_xlabel('X')
ax[0].set_ylabel('Y')
ax[1].set_title('True and Algorithm function curves ')
ax[1].set_xlabel('X')
ax[1].set_ylabel('Y')
plt.savefig("Testing algorithm true and simulated value")
fig,ax = plt.subplots(2,constrained_layout=True)
ax[0].scatter(training[:,1],training[:,0],color='red',marker='.',label='Training data')
ax[0].plot(x,y_sim,color='blue',label='Predicted data')
ax[1].scatter(testing[:,1],testing[:,0],color='red',marker='.',label='Testing data')
ax[1].plot(x,y_sim,color='blue',label='Predicted data')
ax[0].grid()
ax[0].legend()
ax[1].grid()
ax[1].legend()
ax[0].set_title('Training data')
ax[0].set_xlabel('X')
ax[0].set_ylabel('Y')
ax[1].set_title('Testing data')
ax[1].set_xlabel('X')
ax[1].set_ylabel('Y')
plt.savefig("Testing algorithm training-testing datas")
'''
=================================================================================================================================================================================
'''
<file_sep>import numpy as np
import matplotlib.pyplot as plt
'''
================================================================================================================================================================================================
INITIAL PARAMETERS
================================================================================================================================================================================================
'''
'''***MATERIAL PARAMETER***'''
poission_ratio = 0.3
youngs_modulus = 210000 #Mpa
'''***GEOMETRICAL PARAMETER***'''
length = 70 #mm
radius = 5 #mm
'''***TIME PARAMETERS***'''
tau = 0
time_step = 0.1
total_time = 1
'''***EXTERNAL LOADING***'''
f_ext = 100 #Mpa
yield_stress = 350 #Mpa
'''***lame's constant***'''
mu = youngs_modulus/(2*(1+poission_ratio))
lamda = (poission_ratio*youngs_modulus)/((1+poission_ratio)*(1-2*poission_ratio))
k = youngs_modulus/(3*(1-(2*poission_ratio)))
'''***DISCRETIZATION PARAMETERS***'''
nelm = 4
isoparametric_edge = 4
d_o_f = 2
no_nodes = int((np.sqrt(nelm)+1)*(np.sqrt(nelm)+1))
# length_element = 2.5
'''***graphical representation of elements***'''
nelm_length = np.linspace(0,length,np.sqrt(nelm)+1)
nelm_radius = np.linspace(0,radius,np.sqrt(nelm)+1)
yy,xx = np.meshgrid(nelm_length,nelm_radius)
# fig, ax = plt.subplots()
# ax.scatter (xx,yy)
# plt.show()
'''***shape function for isoparametric element***'''
# E1 = 0
# E2 = 0
# N = ([[(1-E1)/4,(1-E2)/4],
# [(1+E1)/4,(1-E2)/4],
# [(1+E1)/4,(1+E2)/4],
# [(1-E1)/4,(1+E2)/4]])
weight = 1
'''
================================================================================================================================================================================================
'''
'''
================================================================================================================================================================================================
deriving all elements coordinates for the calculating jacobian
================================================================================================================================================================================================
'''
def elements_coordinates(nelm,nelm_length,nelm_radius):
all_ele_coord = np.zeros((nelm,4,2))
loop = 0
for j in range(int(np.sqrt(nelm))):
for i in range(int(np.sqrt(nelm))):
ele_coord = np.matrix(([[nelm_radius[i],nelm_length[j]],
[nelm_radius[i+1],nelm_length[j]],
[nelm_radius[i+1],nelm_length[j+1]],
[nelm_radius[i],nelm_length[j+1]]]))
ele_coord = ele_coord.reshape((4,2))
all_ele_coord_zeros = all_ele_coord[loop]+ele_coord
all_ele_coord[loop] = all_ele_coord_zeros
loop += 1
return all_ele_coord
'''
================================================================================================================================================================================================
'''
# area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
'''
================================================================================================================================================================================================
material rotuine
================================================================================================================================================================================================
'''
def material_rotuine(poission_ratio, youngs_modulus,B_matrix,yield_stress,mu,lamda):
c_1 = (youngs_modulus)/(1-poission_ratio**2)
C = c_1*np.array([[1,poission_ratio,0,0],
[poission_ratio,1,0,0],
[0,0,0,0],
[0,0,0,((1-poission_ratio)/2)]])
return C
'''
================================================================================================================================================================================================
'''
'''
================================================================================================================================================================================================
element rotuine
================================================================================================================================================================================================
'''
# element rotuine
def element_rotuine(radius):
k_all_ele = np.zeros((nelm,isoparametric_edge*2,isoparametric_edge*2))
all_ele_coord = elements_coordinates(nelm,nelm_length,nelm_radius)
for i in range(nelm):
k_all = np.zeros((isoparametric_edge*2,isoparametric_edge*2))
for j in range(4):
if j == 0:
E1 = -((np.sqrt(1/3)))
E2 = -((np.sqrt(1/3)))
elif j == 1:
E1 = +((np.sqrt(1/3)))
E2 = -((np.sqrt(1/3)))
elif j == 2:
E1 = +((np.sqrt(1/3)))
E2 = +((np.sqrt(1/3)))
elif j == 3:
E1 = -((np.sqrt(1/3)))
E2 = +((np.sqrt(1/3)))
derivative_N = 1/4*np.matrix([[-(1-E2),(1-E2),(1+E2),-(1+E2)],
[-(1-E1),-(1+E1),(1+E1),(1-E1)]])
x_y_ele = all_ele_coord[i]
jacobi_1 = derivative_N*x_y_ele
jacobi_inverse = np.linalg.inv(jacobi_1)
B_1_matrix = jacobi_inverse*derivative_N
ele_radius = (x_y_ele[0,0]+x_y_ele[1,0]+x_y_ele[2,0]+x_y_ele[3,0])/isoparametric_edge
area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
weight = 1
N_1 = N_2 = N_3 = N_4 = 1/4
B_matrix = np.matrix([[B_1_matrix[0,0],0,B_1_matrix[0,1],0,B_1_matrix[0,2],0,B_1_matrix[0,3],0],
[0,B_1_matrix[1,0],0,B_1_matrix[1,1],0,B_1_matrix[1,2],0,B_1_matrix[1,3]],
[N_1/ele_radius,0,N_2/ele_radius,0,N_3/ele_radius,0,N_4/ele_radius,0],
[B_1_matrix[1,0],B_1_matrix[0,0],B_1_matrix[1,1],B_1_matrix[0,1],B_1_matrix[1,2],B_1_matrix[0,2],B_1_matrix[1,3],B_1_matrix[0,3]]])
c_matrix = material_rotuine(poission_ratio, youngs_modulus,B_matrix,yield_stress,mu,lamda)
k_1 = 2*np.pi*ele_radius*area
k_2 = np.dot(c_matrix,B_matrix)
k_3 = np.dot(np.transpose(B_matrix),k_2)
k_all = k_all + weight*weight*k_1*k_3*np.linalg.det(jacobi_1)
k_all_ele[i] = k_all
return k_all_ele
'''
================================================================================================================================================================================================
'''
'''
================================================================================================================================================================================================
internal force matrix
================================================================================================================================================================================================
'''
# element rotuine
# def internal_force(radius):
# internal_force_matrix_all_ele = np.zeros((nelm,isoparametric_edge*2,1))
# all_ele_coord = elements_coordinates(nelm,nelm_length,nelm_radius)
# for i in range(nelm):
# E1 = 0
# E2 = 0
# derivative_N = 1/4*np.matrix([[-(1-E2),(1-E2),(1+E2),-(1+E2)],
# [-(1-E1),-(1+E1),(1+E1),(1-E1)]])
# x_y_ele = all_ele_coord[i]
# jacobi_1 = derivative_N*x_y_ele
# jacobi_inverse = np.linalg.inv(jacobi_1)
# B_1_matrix = jacobi_inverse*derivative_N
# ele_radius = (x_y_ele[0,0]+x_y_ele[1,0]+x_y_ele[2,0]+x_y_ele[3,0])/isoparametric_edge
# area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
# weight = 2
# N_1 = N_2 = N_3 = N_4 = 1/4
# B_matrix = np.matrix([[B_1_matrix[0,0],0,B_1_matrix[0,1],0,B_1_matrix[0,2],0,B_1_matrix[0,3],0],
# [0,B_1_matrix[1,0],0,B_1_matrix[1,1],0,B_1_matrix[1,2],0,B_1_matrix[1,3]],
# [N_1/ele_radius,0,N_2/ele_radius,0,N_3/ele_radius,0,N_4/ele_radius,0],
# [B_1_matrix[1,0],B_1_matrix[0,0],B_1_matrix[1,1],B_1_matrix[0,1],B_1_matrix[1,2],B_1_matrix[0,2],B_1_matrix[1,3],B_1_matrix[0,3]]])
# c_matrix,stress_matrix = material_rotuine(poission_ratio, youngs_modulus,B_matrix,initial_displacement,i,global_plastic_strain,yield_stress,mu,lamda)
# internal_force_matrix = weight*2*np.pi*radius*area*np.transpose(B_matrix)*stress_matrix*np.linalg.det(jacobi_1)
# internal_force_matrix_all_ele[i] = internal_force_matrix
# return internal_force_matrix_all_ele
'''
================================================================================================================================================================================================
'''
'''
================================================================================================================================================================================================
external force
================================================================================================================================================================================================
'''
# finding the external forces of the elements
def external_force(f_ext,nelm,i,external_force_ele,radius):
# all_ele_coord = elements_coordinates(nelm,nelm_length,nelm_radius)
if i < int(nelm-(np.sqrt(nelm))):
external_force_ele[i] = (np.zeros((isoparametric_edge*2,1)))
return (np.zeros((isoparametric_edge*2,1)))
else:
# x_y_ele = all_ele_coord[i]
ele_radius = radius/int(np.sqrt(nelm))
ele_length = radius/int(np.sqrt(nelm))
external_force = 2*np.pi*ele_radius*((ele_length/2)*f_ext*(1/4))*np.transpose(np.matrix([0,0,0,0,0,4,0,4]))
external_force_ele[i] = external_force
return (external_force)
'''
================================================================================================================================================================================================
'''
'''
================================================================================================================================================================================================
assignment matrix
================================================================================================================================================================================================
'''
def assignment_matrix(nelm,isoparametric_edge,d_o_f):
# nodes of the elements
x_cells = int(np.sqrt(nelm))
y_cells = int(np.sqrt(nelm))
elements = np.arange((x_cells+1)*(y_cells+1)).reshape(y_cells+1,x_cells+1)
# for i in range(0,(x_cells+1),1):
# if i % 2 != 0:
# elements_1 = elements[i]
# elements[i] = elements_1[::-1]
ID = ([])
for i in range(y_cells):
for j in range(x_cells):
id = np.matrix([elements[i,j],elements[i,j+1],elements[i+1,j],elements[i+1,j+1]])
ID = np.append(ID,id)
summation = ([])
for i in ID:
multi = np.array([(i*2),((i*2)+1)])
summation = np.append(summation,multi)
summation = summation.astype(int)
a_column = summation.flatten().reshape(nelm,isoparametric_edge*d_o_f)
# print(sum)
# assignment matrix for all the elements
a_rows = (np.arange(isoparametric_edge*d_o_f)).astype(int)
all_a = np.zeros((nelm,isoparametric_edge*d_o_f , no_nodes*d_o_f))
for k in range(nelm):
a = np.zeros((isoparametric_edge*d_o_f , no_nodes*d_o_f))
for i,j in zip(a_rows,a_column[k]):
a[i,j] = 1
all_a[k] = a
return all_a,summation
'''
================================================================================================================================================================================================
'''
'''
================================================================================================================================================================================================
assembly and newton-raphson
================================================================================================================================================================================================
'''
while True:
k_ele = element_rotuine(radius)
# print(k_ele)
# internal_force_matrix_ele = internal_force(radius)
external_force_ele = np.zeros((nelm,8,1))
for i in range(nelm):
external_force(f_ext,nelm,i,external_force_ele,radius)
all_a,summation = assignment_matrix(nelm,isoparametric_edge,d_o_f)
#assembly
global_stiffness_matrix = np.zeros((no_nodes*2,no_nodes*2))
# global_internal_force_matrix = 0
global_external_force_matrix = 0
for i in range(nelm):
assembly_1 = np.dot((np.transpose(all_a[i])),k_ele[i])
assembly = np.dot(assembly_1,all_a[i])
global_stiffness_matrix = global_stiffness_matrix + assembly
# global_internal_force_matrix = global_internal_force_matrix + np.dot((np.transpose(all_a[i])),internal_force_matrix_ele[i])
global_external_force_matrix = global_external_force_matrix + np.dot((np.transpose(all_a[i])),external_force_ele[i])
G_matrix = global_external_force_matrix
reduced_global_stiffness_matrix_1 = global_stiffness_matrix[2:,2:]
reduced_global_stiffness_matrix_2 = np.delete(reduced_global_stiffness_matrix_1,1,1)
reduced_global_stiffness_matrix_3 = np.delete(reduced_global_stiffness_matrix_2,1,0)
reduced_global_stiffness_matrix_4 = np.delete(reduced_global_stiffness_matrix_3,2,1)
reduced_global_stiffness_matrix_5 = np.delete(reduced_global_stiffness_matrix_4,2,0)
reduced_global_stiffness_matrix_6 = np.delete(reduced_global_stiffness_matrix_5,2,1)
reduced_global_stiffness_matrix_7 = np.delete(reduced_global_stiffness_matrix_6,2,0)
reduced_global_stiffness_matrix_8 = np.delete(reduced_global_stiffness_matrix_7,7,1)
reduced_global_stiffness_matrix = np.delete(reduced_global_stiffness_matrix_8,7,0)
reduced_G_matrix_1 = np.delete(G_matrix,0,0)
reduced_G_matrix_2 = np.delete(reduced_G_matrix_1,0,0)
reduced_G_matrix_3 = np.delete(reduced_G_matrix_2,1,0)
reduced_G_matrix_4 = np.delete(reduced_G_matrix_3,2,0)
reduced_G_matrix_5 = np.delete(reduced_G_matrix_4,2,0)
reduced_G_matrix = np.delete(reduced_G_matrix_5,7,0)
delta_displacement = np.dot(np.linalg.inv(reduced_global_stiffness_matrix),reduced_G_matrix)
# print(delta_displacement)
delta_displacement = np.insert(delta_displacement,0,0)
delta_displacement = np.insert(delta_displacement,1,0)
delta_displacement = np.insert(delta_displacement,3,0)
delta_displacement = np.insert(delta_displacement,5,0)
delta_displacement = np.insert(delta_displacement,6,0)
delta_displacement = np.insert(delta_displacement,12,0)
delta_displacement = delta_displacement.reshape(18,1)
global_displacement = delta_displacement
print(global_displacement)
if (np.linalg.norm(delta_displacement,np.inf) < (0.005 * np.linalg.norm(reduced_G_matrix,np.inf))):
break
<file_sep>import numpy as np
import matplotlib.pyplot as plt
'''
=======================================================
INITIAL PARAMETERS
=======================================================
'''
'''***MATERIAL PARAMETER***'''
poission_ratio = 0.3
youngs_modulus = 200000 #Mpa
'''***GEOMETRICAL PARAMETER***'''
length = 70 #mm
radius = 5 #mm
'''***TIME LIKE PARAMETERS***'''
tau = 0
time_step = 0.1
total_time = 1
'''***EXTERNAL LOADING***'''
f_ext = 400 #Mpa
yield_stress = 350 #Mpa
'''***lame's constant***'''
mu = youngs_modulus/(2*(1+poission_ratio))
lamda = (poission_ratio*youngs_modulus)/((1+poission_ratio)*(1-2*poission_ratio))
k = youngs_modulus/(3*(1-(2*poission_ratio)))
'''***DISCRETIZATION PARAMETERS***'''
nelm = 4
isoparametric_edge = 4
d_o_f = 2
no_nodes = int((np.sqrt(nelm)+1)*(np.sqrt(nelm)+1))
length_element = radius/np.sqrt(nelm)
# graphical representation of elements
nelm_length = np.linspace(0,length,np.sqrt(nelm)+1)
nelm_radius = np.linspace(0,radius,np.sqrt(nelm)+1)
yy,xx = np.meshgrid(nelm_length,nelm_radius)
# fig, ax = plt.subplots()
# ax.scatter (xx,yy)
# plt.show()
'''***shape function for isoparametric element***'''
# E1 = 0
# E2 = 0
# N = ([[(1-E1)/4,(1-E2)/4],
# [(1+E1)/4,(1-E2)/4],
# [(1+E1)/4,(1+E2)/4],
# [(1-E1)/4,(1+E2)/4]])
# weight = 2
'''***deriving all elements coordinates for the calculating jacobian***'''
all_ele_coord = np.zeros((nelm,4,2))
loop = 0
for j in range(int(np.sqrt(nelm))):
for i in range(int(np.sqrt(nelm))):
ele_coord = np.matrix(([[nelm_radius[i],nelm_length[j]],
[nelm_radius[i+1],nelm_length[j]],
[nelm_radius[i+1],nelm_length[j+1]],
[nelm_radius[i],nelm_length[j+1]]]))
ele_coord = ele_coord.reshape((4,2))
all_ele_coord_zeros = all_ele_coord[loop]+ele_coord
all_ele_coord[loop] = all_ele_coord_zeros
loop += 1
area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
# def external_force(f_ext,length_element,nelm,all_ele_coord,i,all_external_force):
# if i < 2:
# all_external_force[i] = (np.zeros((isoparametric_edge*2,1)))
# return (np.zeros((isoparametric_edge*2,1)))
# else:
# x_y_ele = all_ele_coord[i]
# radius = x_y_ele[1,0]
# external_force = (2*3.14*radius*(length_element/2)*f_ext*(1/4))*np.transpose(np.matrix([0,0,0,0,0,4,0,4]))
# all_external_force[i] = external_force
# return (external_force)
# all_external_force = np.zeros((nelm,8,1))
# for i in range(nelm):
# external_force(f_ext,length_element,nelm,all_ele_coord,i,all_external_force)
# print(all_external_force)
# for i in range(nelm):
# if i < 2:
# return (np.zeros((isoparametric_edge*2,1)))
# else:
# x_y_ele = all_ele_coord[i]
# radius = x_y_ele[1,0]
# external_force = (2*3.14*radius*(length_element/2)*f_ext*(1/4))*np.transpose(np.matrix([0,0,0,0,0,4,0,4]))
# return (external_force)
# for i in range(nelm):
# if i < 2:
# print("if",i)
# else:
# print("else",i)
# print(length_element)
# *(np.matrix([0,0,0,0,0,4,0,4]).transpose)
# print(2*np.matrix([1,1]))
# nodes of the elements
# x_cells = int(np.sqrt(nelm))
# y_cells = int(np.sqrt(nelm))
# elements = np.arange((x_cells+1)*(y_cells+1)).reshape(y_cells+1,x_cells+1)
# for i in range(0,(x_cells+1),1):
# if i % 2 != 0:
# elements_1 = elements[i]
# elements[i] = elements_1[::-1]
# ID = ([])
# for i in range(y_cells):
# for j in range(x_cells):
# id = np.matrix([elements[i,j],elements[i,j+1],elements[i+1,j+1],elements[i+1,j]])
# ID = np.append(ID,id)
# # print(ID)
ID = ([0, 1, 4, 5, 1, 2, 3, 4, 4, 3, 8, 7,5, 4, 7, 6,])
sum = ([])
for i in ID:
multi = np.array([(i*2),((i*2)+1)])
sum = np.append(sum,multi)
sum = sum.astype(int)
a_column = sum.flatten().reshape(nelm,isoparametric_edge*d_o_f)
# print(sum)
# assignment matrix for all the elements
a_rows = (np.arange(isoparametric_edge*d_o_f)).astype(int)
all_a = np.zeros((nelm,isoparametric_edge*d_o_f , no_nodes*d_o_f))
for k in range(nelm):
a = np.zeros((isoparametric_edge*d_o_f , no_nodes*d_o_f))
for i,j in zip(a_rows,a_column[k]):
a[i,j] = 1
all_a[k] = a
# print(all_a)
'''
===============================================================================================================
reduced G matrix
================================================================================================================
'''
# k = np.array([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,7,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,13,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18]])
# print(k)
# global_stiffness_matrix = 0
# for i in range(nelm):
# assembly_1 = np.dot((np.transpose(all_a[i])),k)
# assembly = np.dot(assembly_1,all_a[i])
# global_stiffness_matrix = global_stiffness_matrix + assembly
# print(global_stiffness_matrix)
# reduced_1 = k[2:,2:]
# reduced_2 = np.delete(reduced_1,1,1)
# reduced_3 = np.delete(reduced_2,1,0)
# reduced_4 = np.delete(reduced_3,2,1)
# reduced_5 = np.delete(reduced_4,2,0)
# reduced_6 = np.delete(reduced_5,2,1)
# reduced_7 = np.delete(reduced_6,2,0)
# reduced_8 = np.delete(reduced_7,7,1)
# reduced_9 = np.delete(reduced_8,7,0)
# print(reduced_9.shape)
'''
================================================================================================================================================
'''
# a = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18])
# b = a.reshape(18,1)
# # print(b)
# c = np.delete(b,0,0)
# d = np.delete(c,0,0)
# e = np.delete(d,1,0)
# f = np.delete(e,2,0)
# g = np.delete(f,2,0)
# h = np.delete(g,7,0)
# print(h.shape)
'''
===================================================================================================================================================
'''
'''
=========================================================================================================================================================
material rotuine
=========================================================================================================================================================
'''
def material_rotuine(poission_ratio, youngs_modulus,initial_displacement,global_plastic_strain,yield_stress,mu,lamda):
# epsilon = np.dot(B_matrix , initial_displacement)
# strain = epsilon
c_1 = (youngs_modulus)/((1+poission_ratio)*(1-(2*poission_ratio)))
C = c_1*np.matrix([[1-poission_ratio,poission_ratio,poission_ratio,0],
[poission_ratio,1-poission_ratio,poission_ratio,0],
[poission_ratio,poission_ratio,1-poission_ratio,0],
[0,0,0,((1-2*poission_ratio)/2)]])
# trial_stress = np.dot(C , (epsilon - global_plastic_strain))
# trial_stress_deviatoric = trial_stress - (1/3) * np.sum(trial_stress)
# trial_stress_equivalent = np.sqrt((3/2) * (np.sum(trial_stress_deviatoric)**2))
# print(strain)
# if trial_stress_equivalent-yield_stress < 0:
# print("elastic")
# stress = trial_stress
return C
# else:
# # print("plastic")
# delta_lamda = (trial_stress_equivalent-yield_stress)/(3*mu)
# current_stress = ((1/3)*np.sum(trial_stress)*np.ones(4).reshape(4,1)) + (((trial_stress_equivalent-(3*mu*delta_lamda)))/trial_stress_equivalent)*trial_stress_deviatoric
# current_stress_deviatoric = current_stress - (1/3)*np.sum(current_stress)
# current_stress_equivalent = np.sqrt ((3/2)*(np.sum(current_stress_deviatoric)**2))
# plastic_strain = global_plastic_strain + ((delta_lamda * 3/2) / current_stress_equivalent) * current_stress_deviatoric
# stress = current_stress
# c_t_1st = (1/3) * (3*lamda + 2*mu)*np.ones((4,4))
# identity_deviatoric = ((1/2)*(np.eye(4)+np.eye(4)))-((1/3)*np.ones((4,4)))
# c_t_2nd = (2*mu)*((trial_stress_equivalent-(3*mu*delta_lamda))/trial_stress_equivalent)*identity_deviatoric
# c_t_3rd = (3*mu / (trial_stress_equivalent)**2)*(trial_stress_deviatoric*trial_stress_deviatoric.reshape(1,4))
# C_t = c_t_1st + c_t_2nd - c_t_3rd
# return C_t,stress
'''
=========================================================================================================================================================
element rotuine
=========================================================================================================================================================
'''
# element rotuine
def element_rotuine(E1,E2,all_ele_coord,N,area,weight):
k_all_ele = np.zeros((nelm,isoparametric_edge*2,isoparametric_edge*2))
internal_force_matrix_all_ele = np.zeros((nelm,8,1))
for i in range(nelm):
derivative_N = 1/4*np.matrix([[-(1-E2),(1-E2),-(1+E2),(1+E2)],
[-(1-E1),-(1+E1),(1-E1),(1+E1)]])
x_y_ele = all_ele_coord[i]
jacobi_1 = derivative_N*x_y_ele
jacobi_inverse = np.linalg.inv(jacobi_1)
B_1_matrix = jacobi_inverse*derivative_N
radius = x_y_ele[1,0]
N_1 = N_2 = N_3 = N_4 = 1/4
B_matrix = ([[B_1_matrix[0,0],0,B_1_matrix[0,1],0,B_1_matrix[0,2],0,B_1_matrix[0,3],0],
[0,B_1_matrix[1,0],0,B_1_matrix[1,1],0,B_1_matrix[1,2],0,B_1_matrix[1,3]],
[N_1/radius,0,N_2/radius,0,N_3/radius,0,N_4/radius,0],
[B_1_matrix[1,0],B_1_matrix[0,0],B_1_matrix[1,1],B_1_matrix[0,1],B_1_matrix[1,2],B_1_matrix[0,2],B_1_matrix[1,3],B_1_matrix[0,3]]])
c_matrix = material_rotuine(poission_ratio, youngs_modulus,initial_displacement,global_plastic_strain,yield_stress,mu,lamda)
K = weight*2*3.14*radius*area*(np.transpose(B_matrix))@(c_matrix)@(B_matrix)*np.linalg.det(jacobi_1)
# internal_force_matrix = weight*2*3.14*radius*area*np.transpose(B_matrix)*stress_matrix*np.linalg.det(jacobi_1)
# internal_force_matrix_all_ele[i] = internal_force_matrix
k_all_ele[i] = K
return B_matrix
initial_displacement = np.random.rand((isoparametric_edge*2),1)
global_plastic_strain = np.zeros((isoparametric_edge,1))
# k_all = element_rotuine(E1,E2,all_ele_coord,N,area,weight)
# c = material_rotuine(poission_ratio, youngs_modulus,initial_displacement,global_plastic_strain,yield_stress,mu,lamda)
# global_stiffness_matrix = 0
# for i in range(nelm):
# assembly_1 = np.dot((np.transpose(all_a[i])),c)
# assembly = np.dot(assembly_1,all_a[i])
# global_stiffness_matrix = global_stiffness_matrix + assembly
# print(np.transpose(np.transpose(k_all)))
c_1 = (youngs_modulus)/((1+poission_ratio)*(1-(2*poission_ratio)))
C = c_1*np.matrix([[1-poission_ratio,poission_ratio,poission_ratio,0],
[poission_ratio,1-poission_ratio,poission_ratio,0],
[poission_ratio,poission_ratio,1-poission_ratio,0],
[0,0,0,((1-2*poission_ratio)/2)]])
k_all = np.zeros((nelm,isoparametric_edge*2,isoparametric_edge*2))
# k = np.zeros((nelm,isoparametric_edge*2,isoparametric_edge*2))
for i in range(nelm):
k = np.zeros((isoparametric_edge*2,isoparametric_edge*2))
for j in range(nelm):
if j == 0:
E1 = -(int(np.sqrt(1/3)))
E2 = -(int(np.sqrt(1/3)))
elif j == 1:
E1 = +(int(np.sqrt(1/3)))
E2 = -(int(np.sqrt(1/3)))
elif j == 2:
E1 = +(int(np.sqrt(1/3)))
E2 = +(int(np.sqrt(1/3)))
elif j == 3:
E1 = -(int(np.sqrt(1/3)))
E2 = +(int(np.sqrt(1/3)))
weight = 1
derivative_N = 1/4*np.matrix([[-(1-E2),(1-E2),(1+E2),-(1+E2)],
[-(1-E1),-(1+E1),(1+E1),(1-E1)]])
x_y_ele = all_ele_coord[i]
jacobi_1 = derivative_N*x_y_ele
jacobi_inverse = np.linalg.inv(jacobi_1)
B_1_matrix = jacobi_inverse*derivative_N
for a in range(nelm):
if a == 1 & 3:
radius = 1.25
else:
radius = 3.75
N_1 = N_2 = N_3 = N_4 = 1/4
B_matrix = np.matrix([[B_1_matrix[0,0],0,B_1_matrix[0,1],0,B_1_matrix[0,2],0,B_1_matrix[0,3],0],
[0,B_1_matrix[1,0],0,B_1_matrix[1,1],0,B_1_matrix[1,2],0,B_1_matrix[1,3]],
[N_1/radius,0,N_2/radius,0,N_3/radius,0,N_4/radius,0],
[B_1_matrix[1,0],B_1_matrix[0,0],B_1_matrix[1,1],B_1_matrix[0,1],B_1_matrix[1,2],B_1_matrix[0,2],B_1_matrix[1,3],B_1_matrix[0,3]]])
k_1 = 2*3.14*radius
k_2 = np.dot(C,B_matrix)
k_3 = np.dot(np.transpose(B_matrix),k_2)
k = k + k_1*k_3*weight*weight*np.linalg.det(jacobi_1)
# print(E1,E2)
# print(k)
# k_all[i] = k
# print(i,j)
# print(k_all)
# print(k_all)
# k_all[i] = k
# k[i] = weight*2*3.14*radius*np.transpose(B_matrix)*C*B_matrix*np.linalg.det(jacobi_1)
# print((k_all[1].shape))
# # print(k)
# global_stiffness_matrix = 0
# for i in range(nelm):
# assembly_1 = np.dot((np.transpose(all_a[i])),k_all[i])
# assembly = np.dot(assembly_1,all_a[i])
# global_stiffness_matrix = global_stiffness_matrix + assembly
# print((assembly_1))
# print(np.around(global_stiffness_matrix))
# print(all_a)
# x_cells = int(np.sqrt(nelm))
# y_cells = int(np.sqrt(nelm))
# elements = np.arange((x_cells+1)*(y_cells+1)).reshape(y_cells+1,x_cells+1)
# for i in range(0,(x_cells+1),1):
# if i % 2 != 0:
# elements_1 = elements[i]
# elements[i] = elements_1[::-1]
# # print(elements)
# ID = np.array([])
# for i in range(y_cells):
# for j in range(x_cells):
# id = np.matrix([elements[i,j],elements[i,j+1],elements[i+1,j+1],elements[i+1,j]])
# ID = np.append(ID,id)
# print(ID)
# a = np.array([[0,1,2],
# [3,4,5],
# [6,7,8]])
# b = a[1]
# a[1] = b[::-1]
# print(a)
b= np.ones((4,8,8))
global_assembly = 0
for i in range(nelm):
assembly_1 = np.dot((np.transpose(all_a[i])),k_all[i])
assembly = np.dot(assembly_1,all_a[i])
global_assembly = global_assembly+assembly
# print(assembly)
# a_1 = np.matrix([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0]])
# a_2 = np.matrix([[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]])
# a_3 = np.matrix([[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]])
# a_4 = np.matrix([[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]])
# assembly_1 = np.dot((np.transpose(a_1)),k_all[0])
# assembly_one = np.dot(assembly_1,a_1)
# assembly_2 = np.dot((np.transpose(a_2)),k_all[1])
# assembly_two = np.dot(assembly_2,a_2)
# assembly_3 = np.dot((np.transpose(a_3)),k_all[2])
# assembly_three = np.dot(assembly_3,a_3)
# assembly_4 = np.dot((np.transpose(a_4)),k_all[3])
# assembly_four = np.dot(assembly_4,a_4)
# # print(np.linalg.det(assembly_one+assembly_two+assembly_three+assembly_four))
# b_1 = np.matrix([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]])
# b_2 = np.matrix([[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0]])
# b_3 = np.matrix([[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]])
# b_4 = np.matrix([[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0],
# [0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0],
# [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]])
# b_assembly_1 = np.dot((np.transpose(b_1)),k_all[0])
# b_assembly_one = np.dot(b_assembly_1,b_1)
# b_assembly_2 = np.dot((np.transpose(b_2)),k_all[1])
# b_assembly_two = np.dot(b_assembly_2,b_2)
# b_assembly_3 = np.dot((np.transpose(b_3)),k_all[2])
# b_assembly_three = np.dot(b_assembly_3,b_3)
# b_assembly_4 = np.dot((np.transpose(b_4)),k_all[3])
# b_assembly_four = np.dot(b_assembly_4,b_4)
# print(np.linalg.det(b_assembly_one+b_assembly_two+b_assembly_three+b_assembly_four))
# print(np.linalg.det(assembly_one),np.linalg.det(b_assembly_one))
# a_1 = np.matrix([[1,0,0,0,0,0,0,0,0,0,0,0],
# [0,1,0,0,0,0,0,0,0,0,0,0],
# [0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,0,0,1,0],
# [0,0,0,0,0,0,0,0,0,0,0,1],
# [0,0,0,0,0,0,0,0,1,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0]])
# a_2 = np.matrix([[0,0,1,0,0,0,0,0,0,0,0,0],
# [0,0,0,1,0,0,0,0,0,0,0,0],
# [0,0,0,0,1,0,0,0,0,0,0,0],
# [0,0,0,0,0,1,0,0,0,0,0,0],
# [0,0,0,0,0,0,0,0,1,0,0,0],
# [0,0,0,0,0,0,0,0,0,1,0,0],
# [0,0,0,0,0,0,1,0,0,0,0,0],
# [0,0,0,0,0,0,0,1,0,0,0,0]])
# assembly_1 = np.dot((np.transpose(a_1)),k_all[0])
# assembly_one = np.dot(assembly_1,a_1)
# assembly_2 = np.dot((np.transpose(a_2)),k_all[1])
# assembly_two = np.dot(assembly_2,a_2)
# print((assembly_one+assembly_two))
'''# https://www.ccg.msm.cam.ac.uk/images/FEMOR_Lecture_1.pdf #'''
# a = np.dot(np.transpose(a_1),a_1)+np.dot(np.transpose(a_2),a_2)+np.dot(np.transpose(a_3),a_3)+np.dot(np.transpose(a_4),a_4)
# print(np.linalg.det(a))
# print((k_all[0]))
# print(all_a)
'''
===================================================================================================================================
four elements
===================================================================================================================================
'''
##1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9
a_1 = np.matrix([[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], #1
[0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], #1
[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], #2
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], #2
[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], #4
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0], #4
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0]])#5
##1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9
a_2 = np.matrix([[0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], #2
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0], #2
[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0], #3
[0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0], #3
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0], #6
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0]])#6
##1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9
a_3 = np.matrix([[0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0], #4
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0], #4
[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0], #7
[0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0], #7
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], #8
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0]])#8
##1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9
a_4 = np.matrix([[0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0], #5
[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0], #6
[0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0], #6
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], #8
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], #8
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0], #9
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]])#9
# assembly_1 = np.dot((np.transpose(a_1)),k_all[0])
# assembly_one = np.dot(assembly_1,a_1)
# assembly_2 = np.dot((np.transpose(a_2)),k_all[1])
# assembly_two = np.dot(assembly_2,a_2)
# assembly_3 = np.dot((np.transpose(a_3)),k_all[2])
# assembly_three = np.dot(assembly_3,a_3)
# assembly_4 = np.dot((np.transpose(a_4)),k_all[3])
# assembly_four = np.dot(assembly_4,a_4)
# total = assembly_one + assembly_two + assembly_three + assembly_four
# print((total[8,8]))
# print((total[8,9]))
# print((total[9,8]))
# print((total[9,9]))
# print(np.linalg.det(total))
# b = np.ones((8,8))
# assembly_1 = np.dot(b,a_1)
# assembly_one = np.dot(np.transpose(a_1),assembly_1)
# assembly_2 = np.dot(b,a_2)
# assembly_two = np.dot(np.transpose(a_2),assembly_2)
# assembly_3 = np.dot(b,a_3)
# assembly_three = np.dot(np.transpose(a_3),assembly_3)
# assembly_4 = np.dot(b,a_4)
# assembly_four = np.dot(np.transpose(a_4),assembly_4)
# total_assembly = (assembly_one)
# print((total_assembly[8,8]))
# print((total_assembly[8,9]))
# print((total_assembly[9,8]))
# print((total_assembly[9,9]))
# print()
# print(assembly_one)
# print((assembly_one+assembly_two+assembly_three+assembly_four))
# print(np.linalg.inv(assembly_one+assembly_two+assembly_three+assembly_four))
'''
(1,2,4,5),(2,3,5,6),(4,5,7,8),(5,6,8,9)
and
(1,2,5,4),(2,3,6,5),(4,5,8,7),(5,6,9,8)
have same assembly of (18,18) with np.ones
'''
'''
===============================================================================================================================
two elements
===============================================================================================================================
'''
##1,1,2,2,3,3,4,4,5,5,6,6
# a_1 = np.matrix([[1,0,0,0,0,0,0,0,0,0,0,0], #1
# [0,1,0,0,0,0,0,0,0,0,0,0], #1
# [0,0,1,0,0,0,0,0,0,0,0,0], #2
# [0,0,0,1,0,0,0,0,0,0,0,0], #2
# [0,0,0,0,0,0,1,0,0,0,0,0], #4
# [0,0,0,0,0,0,0,1,0,0,0,0], #4
# [0,0,0,0,0,0,0,0,1,0,0,0], #5
# [0,0,0,0,0,0,0,0,0,1,0,0]])#5
# ##1,1,2,2,3,3,4,4,5,5,6,6
# a_2 = np.matrix([[0,0,1,0,0,0,0,0,0,0,0,0], #2
# [0,0,0,1,0,0,0,0,0,0,0,0], #2
# [0,0,0,0,1,0,0,0,0,0,0,0], #3
# [0,0,0,0,0,1,0,0,0,0,0,0], #3
# [0,0,0,0,0,0,0,0,1,0,0,0], #5
# [0,0,0,0,0,0,0,0,0,1,0,0], #5
# [0,0,0,0,0,0,0,0,0,0,1,0], #6
# [0,0,0,0,0,0,0,0,0,0,0,1]])#6
# assembly_1 = np.dot((np.transpose(a_1)),k_all[0])
# assembly_one = np.dot(assembly_1,a_1)
# assembly_2 = np.dot((np.transpose(a_2)),k_all[1])
# assembly_two = np.dot(assembly_2,a_2)
# print(np.linalg.det(assembly_one+assembly_two))
'''
if there any change of id(node numbering) also there is no change in the matrix still det is zero
for two elements its working properly, global stiffness is singular before reducing.
'''
'''
==============================================================================================================================================
'''
# print(np.linalg.det(k_all))
# print(np.allclose(k_all[0],k_all[3]))
# a = all_ele_coord[0]
# print(a[0,0])
# print(a[1,0])
# area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
# print(area)
# print(all_ele_coord)
# nelm = 1
# for i in range(nelm):
# E1 = 0
# E2 = 0
# weight = 2
# derivative_N = 1/4*np.matrix([[-(1-E2),(1-E2),(1+E2),-(1+E2)],
# [-(1-E1),-(1+E1),(1+E1),(1-E1)]])
# x_y_ele = all_ele_coord[i]
# jacobi_1 = derivative_N*x_y_ele
# jacobi_inverse = np.linalg.inv(jacobi_1)
# B_1_matrix = jacobi_inverse*derivative_N
# ele_radius = (x_y_ele[0,0]+x_y_ele[1,0]+x_y_ele[2,0]+x_y_ele[3,0])/isoparametric_edge
# area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
# N_1 = N_2 = N_3 = N_4 = 1/4
# B_matrix = np.matrix([[B_1_matrix[0,0],0,B_1_matrix[0,1],0,B_1_matrix[0,2],0,B_1_matrix[0,3],0],
# [0,B_1_matrix[1,0],0,B_1_matrix[1,1],0,B_1_matrix[1,2],0,B_1_matrix[1,3]],
# [N_1/ele_radius,0,N_2/ele_radius,0,N_3/ele_radius,0,N_4/ele_radius,0],
# [B_1_matrix[1,0],B_1_matrix[0,0],B_1_matrix[1,1],B_1_matrix[0,1],B_1_matrix[1,2],B_1_matrix[0,2],B_1_matrix[1,3],B_1_matrix[0,3]]])
# c_1 = (youngs_modulus)/((1+poission_ratio)*(1-(2*poission_ratio)))
# C = c_1*np.matrix([[1-poission_ratio,poission_ratio,poission_ratio,0],
# [poission_ratio,1-poission_ratio,poission_ratio,0],
# [poission_ratio,poission_ratio,1-poission_ratio,0],
# [0,0,0,((1-2*poission_ratio)/2)]])
# k_1 = 2*np.pi*ele_radius*area
# k_2 = np.dot(C,B_matrix)
# k_3 = np.dot(np.transpose(B_matrix),k_2)
# k = weight*weight*k_1*k_3*np.linalg.det(jacobi_1)
# print((k))
nelm = 4
k_all = np.zeros([nelm,8,8])
for i in range(nelm):
k = 0
for j in range(4):
if j == 0:
E1 = -((np.sqrt(1/3)))
E2 = -((np.sqrt(1/3)))
elif j == 1:
E1 = +((np.sqrt(1/3)))
E2 = -((np.sqrt(1/3)))
elif j == 2:
E1 = +((np.sqrt(1/3)))
E2 = +((np.sqrt(1/3)))
elif j == 3:
E1 = -((np.sqrt(1/3)))
E2 = +((np.sqrt(1/3)))
# print(E1,E2)
weight = 1
derivative_N = 1/4*np.matrix([[-(1-E2),(1-E2),(1+E2),-(1+E2)],
[-(1-E1),-(1+E1),(1+E1),(1-E1)]])
x_y_ele = all_ele_coord[i]
jacobi_1 = derivative_N*x_y_ele
# print(derivative_N)
jacobi_1[0,1] = 0
jacobi_1[1,0] = 0
# print(jacobi_1)
jacobi_inverse = np.linalg.inv(jacobi_1)
# print(jacobi_inverse)
B_1_matrix = jacobi_inverse*derivative_N
# print(B_1_matrix)
ele_radius = (x_y_ele[0,0]+x_y_ele[1,0]+x_y_ele[2,0]+x_y_ele[3,0])/isoparametric_edge
area = all_ele_coord[0,1,0]*all_ele_coord[0,2,1]
N_1 = N_2 = N_3 = N_4 = 1/4
# print(ele_radius)
B_matrix = np.matrix([[B_1_matrix[0,0],0,B_1_matrix[0,1],0,B_1_matrix[0,2],0,B_1_matrix[0,3],0],
[0,B_1_matrix[1,0],0,B_1_matrix[1,1],0,B_1_matrix[1,2],0,B_1_matrix[1,3]],
[N_1/ele_radius,0,N_2/ele_radius,0,N_3/ele_radius,0,N_4/ele_radius,0],
[B_1_matrix[1,0],B_1_matrix[0,0],B_1_matrix[1,1],B_1_matrix[0,1],B_1_matrix[1,2],B_1_matrix[0,2],B_1_matrix[1,3],B_1_matrix[0,3]]])
c_1 = (youngs_modulus)/((1+poission_ratio)*(1-(2*poission_ratio)))
C = c_1*np.matrix([[1-poission_ratio,poission_ratio,poission_ratio,0],
[poission_ratio,1-poission_ratio,poission_ratio,0],
[poission_ratio,poission_ratio,1-poission_ratio,0],
[0,0,0,((1-2*poission_ratio)/2)]])
k_1 = 2*np.pi*ele_radius*area
k_2 = np.dot(C,B_matrix)
k_3 = np.dot(np.transpose(B_matrix),k_2)
k = k + weight*weight*k_1*k_3*np.linalg.det(jacobi_1)
k_all[i] = k
# print(k_all)
'''
=================================================================================================================================================================
'''
# print(np.linalg.eig(k_all))
# for i in range(4):
# print((k_all[i]-k_all[i].T))
assembly_1 = np.dot((np.transpose(a_1)),k_all[0])
assembly_one = np.dot(assembly_1,a_1)
assembly_2 = np.dot((np.transpose(a_2)),k_all[1])
assembly_two = np.dot(assembly_2,a_2)
assembly_3 = np.dot((np.transpose(a_3)),k_all[2])
assembly_three = np.dot(assembly_3,a_3)
assembly_4 = np.dot((np.transpose(a_4)),k_all[3])
assembly_four = np.dot(assembly_4,a_4)
total = assembly_one + assembly_two + assembly_three + assembly_four
print(np.linalg.eig(total))
|
2489cff63e51b5e52cfd1f3c36eb144b89eec06d
|
[
"Python"
] | 3 |
Python
|
ghogul/my_first_project
|
6b557661522d0db11e8c92590817748bacc7ed45
|
20f5f29def0efac873a20ab7864a9c15a692ea83
|
refs/heads/master
|
<repo_name>Putnam3145/auxmaptick<file_sep>/Cargo.toml
[package]
name = "auxmaptick"
version = "0.1.0"
authors = ["Putnam <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["dylib"]
[profile.release]
opt-level = 3
lto = 'thin'
codegen-units = 1
incremental = true
debug = true
[dependencies]
auxtools = { git = "https://github.com/willox/auxtools" }
[dependencies.detour]
version = "0.7"
default-features = false
<file_sep>/src/lib.rs
use auxtools::*;
use detour::RawDetour;
use std::ffi::c_void;
thread_local! {
static SEND_MAPS_ORIGINAL: unsafe extern "C" fn() = {
let byondcore = sigscan::Scanner::for_module(BYONDCORE).unwrap();
let mut send_maps_byond: *const c_void = std::ptr::null();
if cfg!(windows) {
let ptr = byondcore
.find(signature!(
"55 8B EC 6A FF 68 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 50 81 EC ?? ?? ?? ?? A1 ?? ?? ?? ?? 33 C5 89 45 F0 53 56 57 50 8D 45 F4 ?? ?? ?? ?? ?? ?? A0 ?? ?? ?? ?? 04 01 75 05 E8 ?? ?? ?? ?? E8"
))
.unwrap();
send_maps_byond = ptr as *const c_void;
}
if cfg!(unix) {
let ptr = byondcore
.find(signature!(
"55 89 E5 57 56 53 81 EC ?? ?? ?? ?? 80 3D ?? ?? ?? ?? ?? 0F 84 ?? ?? ?? ??"
))
.unwrap();
send_maps_byond = ptr as *const c_void;
}
unsafe {
let tick_hook = RawDetour::new(
send_maps_byond as *const (),
map_tick_hook as *const (),
)
.unwrap();
tick_hook.enable().unwrap();
let ret = std::mem::transmute(tick_hook.trampoline());
std::mem::forget(tick_hook);
ret
}
}
}
#[no_mangle]
unsafe extern "C" fn map_tick_hook() {
let start = std::time::Instant::now();
SEND_MAPS_ORIGINAL.with(|send_maps_original| {
send_maps_original();
});
Value::globals().set("internal_tick_usage", start.elapsed().as_micros() as f32 / 100000.0);
}
#[hook("/proc/initialize_maptick")]
fn _init_map_tick() {
Ok(Value::from(SEND_MAPS_ORIGINAL.with(|_| {
true
})))
}<file_sep>/README.md
Adds functionality to [auxtools](https://github.com/willox/auxtools) that sets a global variable in byond whenever it sends maps showing how long sending maps took, in ticks.
To use, compile this for your target OS, put the compiled library into the same folder as your .dme, then:
1. Define a macro or function to enable the library's instance of auxtools, e.g.
```c
#define AUXMAPTICK ((world.system_type == MS_WINDOWS ? "auxmaptick.dll" : "auxmaptick.so"))
#define AUXMAPTICK_CHECK\
if (!GLOB.auxmaptick_initialized && fexists(AUXMAPTICK) && findtext(call(AUXMAPTICK,"auxtools_init")(),"SUCCESS"))\
GLOB.auxmaptick_initialized = TRUE;\
```
2. Define a `/proc/initialize_maptick` and call it in `/world/New`, after calling the above macro.
3. Do as 1, but for disabling it, e.g., and call it in `/world/Del`.
```c
#define AUXMAPTICK_SHUTDOWN\
if (GLOB.auxmaptick_initialized && fexists(AUXMAPTICK))\
call(AUXMAPTICK,"auxtools_shutdown")();\
GLOB.auxmaptick_initialized = FALSE;\
```
4. You can now get the amount of time in milliseconds used by maptick by accessing the `internal_tick_usage` global variable.
This is going to be made obsolete by Byond 514. When you update to 514, use that instead.
|
92077760c9258ef10c9a6834aa868bb60e5a329c
|
[
"TOML",
"Rust",
"Markdown"
] | 3 |
TOML
|
Putnam3145/auxmaptick
|
940575c4f02aac7db5f2dfe89feca83566e1538f
|
8dcee6254acfbd24ade75fe39c15719e93f89432
|
refs/heads/master
|
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import SeasonDisplay from './SeasonDisplay';
import Spinner from './Spinner';
class App extends React.Component{
state = { lat: null, errorMessage: ''}
// this lifecycle method only gets called once, when our content first shows up on the screen.
componentDidMount(){
window.navigator.geolocation.getCurrentPosition(
(position)=> this.setState({ lat: position.coords.latitude }),
(err)=> this.setState({ errorMessage: err.message })
);
}
// this lifecycle method gets called everytime our component is updated.
componentDidUpdate(){
console.log('My component was just updated');
}
renderContent(){
if(this.state.errorMessage && !this.state.latitude){
return <div>Error: {this.state.errorMessage}</div>
}
if(!this.state.errorMessage && this.state.lat){
return ( <SeasonDisplay lat = {this.state.lat}/>
);
}
return <Spinner message='Please accept location request'/>
}
render(){
return(
// there is actually no className called 'border red', no border
// is meant to appear, we just do this so that we only have ONE return
// line in the render method! Our helper method: 'renderContent'
// Allowing us to better modify our code at the last name
<div className="border red">
{this.renderContent()}
</div>
);
}
};
ReactDOM.render(<App />, document.querySelector('#root'));
|
de2861e6aae7d215fd6568df60fcc3875b99e2c8
|
[
"JavaScript"
] | 1 |
JavaScript
|
ricardosmithco/seasons
|
57f4fb96d9c69a088c612bc03b982ba11ac1ffaf
|
0193ac1666ff67f38044788e8d8c28a69d4c3040
|
refs/heads/master
|
<repo_name>willisdorden/WellStockedStork-react-<file_sep>/app/src/pages/ecomom/Ecomom.js
import React from 'react';
import {BrowserRouter as Router, Route, Link, NavLink} from 'react-router-dom'
import {Grid, Row, Col} from 'react-bootstrap';
import EcoEarthMom from './img/EcoEarthMom.png';
const styles = {
display: 'flex',
justifyContent: "center",
padding: 60
};
const Mom ={
textAlign:"center",
display: "inline",
fontFamily: "book",
};
const Links={
padding: 60,
listStyle: 'none',
display: "inline",
fontFamily: "book",
fontSize: "18",
textAlign: "center",
};
const Content ={
padding: 10,
margin: 10,
backgroundColor: "",
color: "",
display: "inline-block",
fontFamily: "book",
fontSize: "15.5",
textAlign: "center",
};
const Img1 ={
height:250,
width:250,
marginRight:400
};
const col ={
marginLeft: 300
};
const Ecomom =() => {
return(
<div className="Ecomom" style={styles}>
<Grid>
<Row>
<Col md={12} style={Mom}>
<h1 style={Mom}>Eco Earth Mom</h1>
<br/>
<p style={Content}> You’re a mom who wants the best environment for your baby – both at home and in nature.
You don’t need excess and you understand that our actions and consumption have an impact on the world we live in.
You want your baby to grow up with strong values and an appreciation for what’s truly important; not things, but making memories, spending time with loved ones and taking advantage of each day.
While we could certainly recommend that you buy everything new, there are some things that you can find at your local children’s consignment store, often in barely-used condition: bouncers, swings and similar “nice to haves” fit the bill.
For other necessities, check out the list we’ve put together just for you – we think you’ll agree that these items will make life with your baby even more enjoyable!</p>
</Col>
</Row>
<Row>
<Col md={3} style={col}>
<img style={Img1} src={EcoEarthMom}/>
</Col>
<Col md={2}>
<ul style={Links}>
<li><Link to="/ecomom/bathingandgrooming">Bathing & Grooming</Link></li>
<li><Link to="/ecomom/forfun">For Fun</Link></li>
<li><Link to="/ecomom/handyhelper">Handy Helper</Link></li>
<li><Link to="/ecomom/kitchen">Kitchen</Link></li>
<li><Link to="/ecomom/necessities">Necessities</Link></li>
<li><Link to="/ecomom/nursery">Nursery</Link></li>
<li><Link to="/ecomom/onthemove">On the Move</Link></li>
</ul>
</Col>
</Row>
</Grid>
</div>
)
};
export default Ecomom;
<file_sep>/app/src/pages/questions.js
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom';
import axios from 'axios';
import AnswerOption from "./answersContent";
import RaisedButton from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {RadioGroup, Radio} from 'react-radio-group'
const styles = {
display: 'flex',
justifyContent: "center"
};
const style = {
margin: 15,
};
const Content = {
padding: 10,
margin: 10,
backgroundColor: "",
color: "",
display: "inline-block",
fontFamily: "monospace",
fontSize: "18",
};
const answ ={
listStyle: 'none'
};
class Questions extends Component {
constructor(props) {
super(props);
this.state = {
redirect: "",
user: "",
questions: [],
answers: [],
surveyAnswers: {}
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event, value) {
const answers=this.state.surveyAnswers;
answers[event.target.name] = event.target.value;
this.setState({
surveyAnswers:answers
})
}
componentDidMount() {
console.log(this.props.user);
axios.post('/questions')
.then((response) => {
console.log(response);
if (response.status === 200) {
console.log("successfull");
// self.setState({ user: response.data.user.id});
this.setState({user: this.props.user});
this.setState({redirect: false});
this.setState ({ questions : response.data.surveyQuestions})
}
})
.catch(function (error) {
console.log(error);
});
}
handleClick(event){
const payload=
this.state.surveyAnswers
axios.post('/answers', payload)
.then((response) =>{
if(response.status === 200){
console.log('successfull');
}
})
}
render(){
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/login'/>;
}
return (
<div className="dashboard" style={styles}>
<MuiThemeProvider>
<div style={Content}>
<h1>Welcome to The Well-Stocked Stork!</h1>
<br />
{
this.state.questions.map(quest => {
return (
<div>
<p key={quest.id}> {quest.id}. {quest.question} </p>
<ul>
<li style={answ}> <input type="radio" name={`questionId${quest.id}`} key={quest.id}
value={quest.surveyAnswers[0].value}
onChange = {this.handleChange} />
{quest.surveyAnswers[0].body}
</li>
<li style={answ}> <input type="radio" name={`questionId${quest.id}`} key={quest.id}
value={quest.surveyAnswers[1].value}
onChange = {this.handleChange} />
{quest.surveyAnswers[1].body}
</li>
<li style={answ}> <input type="radio" name={`questionId${quest.id}`} key={quest.id}
value={quest.surveyAnswers[2].value}
onChange = {this.handleChange} />
{quest.surveyAnswers[2].body}
</li>
</ul>
</div>
);
})
}
<RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
</div>
</MuiThemeProvider>
</div>
)
}
}
export default Questions;
<file_sep>/app/src/pages/about.js
import React from 'react';
import StorkLogoC from '../img/StorkLogoC.jpg';
import { Grid, Row, Col } from 'react-bootstrap';
import family from '../img/family.JPG';
const styles = {
display: 'flex',
// justifyContent: "center",
backgroundImage:`url(${StorkLogoC})`,
width: "100%",
height: "800",
};
const Img1 ={
padding:"28",
width: "75%",
height: "100%",
};
const Img ={
height:150,
width:200
};
const background ={
backgroundImage:`url(${StorkLogoC})`,
width: "100%",
height: "100%",
};
const Content ={
padding: 10,
margin: 10,
backgroundColor: "",
color: "",
display: "inline-block",
fontFamily: "book",
fontSize: "15.5",
textAlign: "center",
};
const Abt ={
textAlign:"center"
};
const About = () => {
return(
<div className="about" style={styles}>
<Grid>
<Col lg={6} >
<p style={Content}>We’re parents, just like you. We recently had a baby and we quickly came to this realization:
The problem with baby stuff isn’t that you don’t know what to get. You know exactly what you need, but there are so many choices.
For everything. Hundreds of bottles. Just as many nipples. Bibs. Pacifiers. Countless car seats.
Strollers that range in price from $50 to thousands. Diapers galore. Bouncers, swings, and chairs that’ll make your head spin.
Toys of all types. Cribs. Bassinets. Co-sleepers. And that’s just the start! The options seem endless, so we’re here to help.</p>
<p style={Content}>The Well-Stocked Stork is our brainchild. We’re Willis and Darcy, a real-life couple with a newborn son who was born the summer of 2017, more than nine years after his older sister arrived on the scene.
Boy oh boy, have things changed in a decade! We’ve combed through product reviews, ratings and old-fashioned recommendations from actual moms and dads to bring you the best products from a wide-array of retailers.
The best part? We’ll tailor our suggestions to match your personality, budget and style.</p>
<p style={Content}> When you use our recommendations, we’re confident that The Well-Stocked Stork will help you make the best selections to suit your family.
Here’s to your next special delivery,</p>
<p style={Content}> <NAME> Darcy
</p>
</Col>
<Col lg={6} >
<img style={Img1} src={family}/>
</Col>
</Grid>
</div>
)
};
export default About
<file_sep>/server/db/models/submittedAnswers.js
module.exports = function(sequelize, DataTypes) {
const submittedAnswers = sequelize.define("submittedAnswers", {
userAnswer: {
type: DataTypes.JSON,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
submittedAnswers.belongsTo(models.Users, {
foreignKey: 'UsersId',
allowNull: true
});
}
},
underscored: true,
});
return submittedAnswers;
};<file_sep>/app/src/pages/practicalmom/Practicalmom.js
import React from 'react';
import {BrowserRouter as Router, Route, Link, NavLink} from 'react-router-dom'
import {Grid, Row, Col} from 'react-bootstrap';
import PrettyPracticalMom from'./img/PrettyPracticalMom.png';
const styles = {
display: 'flex',
justifyContent: "center",
padding: 60
};
const Mom ={
textAlign:"center",
display: "inline",
fontFamily: "book",
};
const Links={
padding: 60,
listStyle: 'none',
display: "inline",
fontFamily: "book",
fontSize: "18",
textAlign: "center",
};
const Content ={
padding: 10,
margin: 10,
backgroundColor: "",
color: "",
display: "inline-block",
fontFamily: "book",
fontSize: "15.5",
textAlign: "center",
};
const Img1 ={
height:250,
width:250,
marginRight:400
};
const col ={
marginLeft: 300
};
const Practicalmom =() => {
return(
<div className="practicalmom" style={styles}>
<Grid>
<Row>
<Col md={12} style={Mom}>
<h1 style={Mom}>Pretty Practical Mom</h1>
<br/>
<p style={Content}> You know there are “need-to-haves” and “nice-to-haves” and you prioritize accordingly.
You’ll make sure your little one has everything they need to thrive, but don’t feel the need to splurge or overspend on every item for your tiny tot.
Basic necessities are a given, and a few special indulgences are nice every now and then.
You understand that “things” are nice, but love and attention are the most important gifts you can give your child.
Check out the list we’ve put together just for you – we think you’ll agree that these items will make your life with baby practically perfect!</p>
</Col>
</Row>
<Row>
<Col md={3} style={col}>
<img style={Img1} src={PrettyPracticalMom}/>
</Col>
<Col md={2}>
<ul style={Links}>
<li><Link to="/practicalmom/bathingandgrooming">Bathing & Grooming</Link></li>
<li><Link to="/practicalmom/forfun">For Fun</Link></li>
<li><Link to="/practicalmom/handyhelper">Handy Helper</Link></li>
<li><Link to="/practicalmom/kitchen">Kitchen</Link></li>
<li><Link to="/practicalmom/necessities">Necessities</Link></li>
<li><Link to="/practicalmom/nursery">Nursery</Link></li>
<li><Link to="/practicalmom/onthemove">On the Move</Link></li>
</ul>
</Col>
</Row>
</Grid>
</div>
)
};
export default Practicalmom;
<file_sep>/server/controllers/authController.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const db = require("../db/models");
const jwtSecret = process.env.JWT_SECRET;
exports.userRegister = (req, res) => {
const { first_name, last_name, email, username, password } = req.body;
db.Users.create({
first_name,
last_name,
email,
username,
password: generateHash(password),
}).then(function(user) {
// Create the JSON-WebToken
const token = jwt.sign({
data: {
uid: user.id,
username: user.username
}
}, jwtSecret, {
expiresIn: '12h'
});
res.set("Set-Cookie", `token=${token}`);
// Send the json object to the app.js
res.status(200).json({
success: true,
user,
token
});
}).catch(function(error) {
console.log(error);
res.status(500).json({ success: false });
});
};
exports.userLogin = (req, res) => {
db.Users.findOne({
where: {
username: req.body.username
}
}).then(function(user) {
if (!user || !validatePassword(req.body.password, user.password)) {
res.status(401).json({
message: 'Incorrect username or password'
});
} else {
const token = jwt.sign({
data: {
uid: user.id,
username: user.username
}
}, jwtSecret, {
expiresIn: '12h'
});
res.set("Set-Cookie", `token=${token}`);
res.status(200).json({
success: true,
user,
token
});
}
}).catch(function (error) {
console.log(error);
res.status(500).json({ success: false });
})
};
exports.Questions = (req,res) => {
db.surveyQuestions.findAll({
where:{
callId: 1,
},
include: [{
model: db.surveyAnswers
}]
}).then(function(surveyQuestions) {
res.status(200).json({
success: true,
surveyQuestions,
})
})
};
exports.grooming =(req,res) => {
db.Ecomoms.findAll({
where:{
callid: 1,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.forfun =(req,res) => {
db.Ecomoms.findAll({
where:{
callid: 2,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.handyhelper =(req,res) => {
db.Ecomoms.findAll({
where:{
callid: 3,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.kitchen =(req,res) => {
db.Ecomoms.findAll({
where:{
callid: 4,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.necessities =(req,res) => {
db.Ecomoms.findAll({
where:{
callid: 5,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.nursery =(req,res) => {
db.Ecomoms.findAll({
where:{
callid: 6,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.chicgrooming =(req,res) => {
db.Chicmoms.findAll({
where:{
callid: 1,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.chicforfun =(req,res) => {
db.Chicmoms.findAll({
where:{
callid: 2,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.chichandyhelper =(req,res) => {
db.Chicmoms.findAll({
where:{
callid: 3,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.chickitchen =(req,res) => {
db.Chicmoms.findAll({
where:{
callid: 4,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.chicnecessities =(req,res) => {
db.Chicmoms.findAll({
where:{
callid: 5,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.chicnursery =(req,res) => {
db.Chicmoms.findAll({
where:{
callid: 6,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.practicalgrooming =(req,res) => {
db.Practicalmoms.findAll({
where:{
callid: 1,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.practicalforfun =(req,res) => {
db.Practicalmoms.findAll({
where:{
callid: 2,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.practicalhandyhelper =(req,res) => {
db.Practicalmoms.findAll({
where:{
callid: 3,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.practicalkitchen =(req,res) => {
db.Practicalmoms.findAll({
where:{
callid: 4,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.practicalnecessities =(req,res) => {
db.Practicalmoms.findAll({
where:{
callid: 5,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.practicalnursery =(req,res) => {
db.Practicalmoms.findAll({
where:{
callid: 6,
}
}).then(function (Ecomoms) {
res.status(200).json({
success:true,
Ecomoms,
})
})
};
exports.answers = (req, res) => {
console.log(req.body);
db.submittedAnswers.create({
userAnswer: req.body
}).then(function(answers){
res.status(200).json({
success:true,
answers
})
})
};
function generateHash(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
}
function validatePassword(password, storedPassword) {
return storedPassword ? bcrypt.compareSync(password, storedPassword) : false;
}<file_sep>/app/src/pages/radio.js
/**
* Created by admin on 7/30/17.
*/
{
this.state.questions.map(quest => {
return (
<div>
<p key={quest.id}> {quest.id}. {quest.question} </p>
<ul>
<RadioGroup style={answ}
name="answers"
selectedValue={this.state.selectedValue}
onChange={this.handleChange}>
<li>
<Radio key={quest.surveyAnswers[ 0 ].SurveyQuestionId}
value="1"/>{quest.surveyAnswers[ 0 ].body}
</li>
<li>
<Radio key={quest.surveyAnswers[ 1 ].SurveyQuestionId}
value="2"/>{quest.surveyAnswers[ 1 ].body}
</li>
<li>
<Radio key={quest.surveyAnswers[ 2 ].SurveyQuestionId}
value="3"/>{quest.surveyAnswers[ 2 ].body}
</li>
</RadioGroup>
</ul>
</div>
);
})
}<file_sep>/server/db/seeders/20170713003373-ChicmomsSeeders.js
module.exports = {
up: function (queryInterface, Sequelize) {
queryInterface.bulkInsert('Chicmoms', [{
callid:1,
name:"Aquascale 3 in 1 Digital Scale",
category: "Bathing & Grooming" ,
description:"The Aqua Scale is a digital tub to monitor your child's health and well-being. It has a patented technology that adjusts for water and displays your child's weight.",
imgUrl: "http://www.toysrus.com/graphics/product_images/pTRU1-21067633_alternate1_dt.jpg",
buyUrl:"http://www.toysrus.com/product/index.jsp?productId=61949586",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:1,
name:"Fridababy Bitty Bundle of Joy",
category: "Bathing & Grooming" ,
description:"The Bitty Bundle of Joy from Fridababy is the perfect fuss-busting starter kit for new parents. Featuring NoseFrida, the pediatrician recommended booger buster, the Bitty Bundle of Joy also comes equipped with Windi, the all-natural gas passer, and NailFrida for those intimidating baby mani-pedis.",
imgUrl: "http://www.toysrus.com/graphics/tru_prod_images/Fridababy-Bitty-Bundle-of-Joy--pTRU1-23586227dt.jpg",
buyUrl:"https://www.target.com/p/fridababy-bitty-bundle-of-joy/-/A-50729283#lnk=sametab",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:1,
name:"Triple Paste Medicated Ointment for Diaper Rash",
category: "Bathing & Grooming" ,
description:"Triple Paste medicated ointment is the premium choice to help treat and prevent diaper rash. This ointment provides a fragrance free and hypoallergenic option for treating babies with raw and irritated skin. Every baby deserves the best diaper ointment. Triple Paste is everything you need to comfort your baby's diaper rash.",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/81WxLY065bL._SY355_.jpg",
buyUrl:"https://www.amazon.com/Triple-Paste-Medicated-Ointment-16-Ounce/dp/B000GCL2B8/ref=sr_1_cc_9_a_it?s=aps&ie=UTF8&qid=1500505618&sr=1-9-catcorr&keywords=diaper%2Brash%2Bcream&th=1",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:1, name:"3-in-1 Baby Shampoo",
category: "Bathing & Grooming" ,
description:"KEEP YOUR BABY HAPPY, HEALTHY & SAFE: No Harsh Chemicals. No Parabens, No Phosphates, No Sulfates. NO MORE CRYING WITH TEAR FREE Baby Wash - Try the tear test by washing your face with the baby shampoo and body wash",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/71CkEFGU8fL._SY355_.jpg",
buyUrl:"https://www.amazon.com/Baby-Shampoo-Bubble-Bath-Body/dp/B01672BWHO/ref=sr_1_3?s=hpc&ie=UTF8&qid=1500505799&sr=1-3-spons&keywords=baby+shampoo+and+body+wash&psc=1",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:2, name:"Skip Hop Silver Lining Cloud Activity Gym",
category: "For Fun" ,
description:"Enjoy plush playtime on our big, cozy cloud! Every cloud has a silver lining and this dreamy baby activity gym is no exception! Offering hours of plush playtime, it features a soft color palette to complement modern decor along with pops of neon to stimulate baby's sight.",
imgUrl: "http://www.toysrus.com/graphics/product_images/pTRU1-24714263dt.jpg",
buyUrl:"http://www.toysrus.com/product/index.jsp?productId=108706116&cp=2255957.2273443.68241026.3670997&parentPage=family",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:3,
name:"<NAME>",
category: "Handy Helper" ,
description:"The light gray base and frame creates a soft impression, and the monotone fabric seat provides a luxurious feel that will be an attractive detail in your home. Bouncer Bliss is available in a plush cotton quilting and soft, child-friendly mesh - two extra cozy fabrics for a soft start to life. Bouncer Bliss gives your baby a cozy place to rest and play. The ergonomically shaped seat provides proper support to your baby's back, neck and head.",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/71i38aKhjtL._SY450_.jpg",
buyUrl:"https://www.amazon.com/dp/B06XPBB1TH/ref=sxbs_sxwds-stvp_3_s_it?pf_rd_m=ATVPDKIKX0DER&pf_rd_p=2972357942&pd_rd_wg=BLrQo&pf_rd_r=46GTZ9D5HJ7W0BH1SN13&pf_rd_s=desktop-sx-bottom-slot&pf_rd_t=301&pd_rd_i=B06XPBB1TH&pd_rd_w=EGbjO&pf_rd_i=bouncer&pd_rd_r=4VGSXSE1P6B6V6FCDRY0&ie=UTF8&qid=1500506441&sr=3&th=1",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:3,
name:"<NAME> in Winter White",
category: "Handy Helper" ,
description:"This Eco Swaddling Blanket is made with oxygen bleached 100% Organic Cotton Fleece that is so soft and cozy!.Perfectly pure just like a newborn babe! A perfect blanket for the cooler seasons!",
imgUrl: "https://img1.etsystatic.com/000/1/6058634/il_570xN.276688645.jpg",
buyUrl:"https://www.etsy.com/listing/83433159/swaddling-blanket-organic-baby-blanket?&utm_source=google&utm_medium=cpc&utm_campaign=shopping_us_b-home_and_living-bedding-blankets_and_throws-baby_blankets&utm_custom1=a82ab3fb-4352-4ee8-8381-e2fffa5a58cd&gclid=EAIaIQobChMI_qeV-MCW1QIVTDyBCh3J-wKMEAQYAyABEgLmPPD_BwE",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:3,
name:"Dyson Humidifer",
category: "Handy Helper" ,
description:"The Dyson Humidifier in White/Silver exposes every drop of water to an ultraviolet light through patented Ultraviolet Cleanse technology. The cooling humidifier can keep you cool in summer while hydrating the winter air.",
imgUrl: "https://target.scene7.com/is/image/Target/49174308?wid=520&hei=520&fmt=pjpeg",
buyUrl:"http://www.dyson.com/air-treatment/humidifiers.aspx?&mkwid=sPinltkZo_dc&pcrid=159737321954&pkw=%2Bhumidifer&pmt=b&productid=&gclid=EAIaIQobChMIusu59sKW1QIV2AyBCh05yA01EAAYASAAEgK21vD_BwE",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:3,
name:"Wave Baby Premium Soothing Sound Machine",
category: "Handy Helper" ,
description:"Add a sense of calm to your baby’s nursery with this stylish sound machine that helps drown out household noises and promotes more restful sleep. Each of the 6 sound settings were carefully selected with your baby in mind to help you create the ideal mood for naptime or bedtime.",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/41YK84T7kdL.jpg",
buyUrl:"https://www.amazon.com/Wave-Premium-Soothing-Sound-Machine/dp/B0711FK8FZ/ref=sr_1_24_s_it?s=hpc&ie=UTF8&qid=1500508098&sr=1-24&keywords=white+noise+baby",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:3,
name:"Infant Optics DXR-8 Video Baby Monitor",
category: "Handy Helper" ,
description:"The Infant Optics DXR-8 Video Monitor is the first baby monitor with interchangeable lens technology. Three separate lens types normal, wide angle and zoom allow you to choose the most suitable focal length and viewing angle for the specific environment.",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/81PbGDE5jcL._SX355_.jpg",
buyUrl:"https://www.amazon.com/gp/product/B00ECHYTBI/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B00ECHYTBI&linkCode=as2&tag=bestprodtag111046-20",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:4,
name:"Philips Avent Natural Newborn Baby Bottle",
category: "Kitchen" ,
description:"Philips Avent SCD296/02 BPA Free Natural Infant Starter Set is the most natural way to start bottle feeding. The 5 BPA-free Natural bottles included in this kit feature wide breast-shaped nipples with unique comfort petals promoting natural latch on and making it easy to combine breast and bottle feeding. ",
imgUrl: "https://images-na.ssl-images-amazon.com/images/G/01/aplus/detail-page/Philips_AVENT_Natural_Infant_Starter_Set_1.jpg",
buyUrl:"https://www.amazon.com/gp/product/B00E1CI2TO/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B00E1CI2TO&linkCode=as2&tag=bestprodtag111046-20",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:4,
name:"Medela Breastmilk Bottle Set",
category: "Kitchen" ,
description:"Medela polypropylene breast milk bottles are made without BPA, designed to retain breast milk's beneficial properties. Compatible with all Medela breast pumps, so you can pump, store and feed with one container. Great for long term storage. Dishwasher safe. Measure the exact amount of milk you're pumping with the ounce and millimeter markers. Screw on lids for leak proof storage, travel and freezing.",
imgUrl:"https://images-na.ssl-images-amazon.com/images/G/01/aplusautomation/vendorimages/049b374e-a616-459b-bf39-caa784563c8b.jpg._CB334685830_.jpg",
buyUrl:"https://www.amazon.com/gp/product/B001V9EVCM/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B001V9EVCM&linkCode=as2&tag=bestprodtag111046-20",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:4,
name:"Eternal Circle Child's Fork and Spoon Set",
category: "Kitchen" ,
description:"There is no shape more complete, more eternal, than a circle. Fork and spoon in sterling silver. 4.5 long each.",
imgUrl: "http://media.tiffany.com/is/image/Tiffany/EcomItemSocialL/elsa-perettieternal-circle-childs-fork-and-spoon-set-31530016_923489_ED.jpg?defaultImage=NoImageAvailable&op_usm=3,1,6",
buyUrl:"http://www.tiffany.com/gifts/baby-gifts/elsa-peretti-eternal-circle-childs-fork-and-spoon-set-31530016?&fromGrid=1&search_params=p+1-n+10000-c+288202-s+5-r+-t+-ni+1-x+-lr+-hr+-ri+-mi+-pp+1192+5&search=0&origin=browse&searchkeyword=&trackpdp=bg&fromcid=288202&trackgridpos=16",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:4,
name:"<NAME>",
category: "Kitchen" ,
description:"This versatile high chair features durable designer details in addition to innovative construction. Expertly built from the ground up, this revolutionary chair from Nuna is a must-have for your baby’s mealtime. Customizable, supportive and exceedingly tested for safety, the ZAAZ™ will grow with your baby without compromising your pre-baby lifestyle. Plus, the gliding lift mechanism and removable tray and arm bar make clean-up a snap!",
imgUrl: "https://www.potterybarnkids.com/pkimgs/ab/images/dp/wcm/201708/0057/nuna-zaaz-highchair-c.jpg",
buyUrl:"https://www.potterybarnkids.com/products/nuna-zaaz-highchair/?pkey=e%7Cbaby%2Bswing%7C146%7Cbest%7C0%7C1%7C24%7C%7C16&cm_src=PRODUCTSEARCH",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:4,
name:"<NAME>",
category: "Kitchen" ,
description:"Our modern Sugar Chic Baby Bibs are made of high quality designer fabrics on all bib fronts & an absorbent DOUBLE layer of soft organic flannel on the back to keep your drooly baby extra dry & comfortable. ",
imgUrl: "https://s-media-cache-ak0.pinimg.com/736x/0e/e8/c3/0ee8c326e631237c91fb1218a9cd782a--bibs-for-babies-baby-knits.jpg",
buyUrl:"https://www.etsy.com/shop/SugarChicBaby?search_query=bibs",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:4,
name:"Baby Brezza Formula Pro One Step Food Maker",
category: "Kitchen" ,
description:" Introducing Formula Pro, the revolutionary new way of preparing your baby’s formula bottles. The Formula Pro uses worldwide patent-pending technology to measure and mix water and powdered formula to the perfect temperature (about 98 degrees) and consistency. With the push of a button, you can prepare a bottle within seconds that has no air bubbles. ",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/812WVN8zkeL._SL1500_.jpg",
buyUrl:"https://www.amazon.com/Baby-Brezza-Formula-Step-Maker/dp/B00E8KJYNC/ref=sr_1_3_s_it?s=baby-products&ie=UTF8&qid=1500510176&sr=1-3&keywords=formula+mixer",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:5,
name:"<NAME>",
category: "Necessities" ,
description:"Wrap your baby in Pampers Swaddlers diapers, our most trusted comfort and protection and the #1 Choice of US Hospitals.* Our Blankie Soft diaper with a unique Absorb Away Liner pulls wetness and mess away from baby's skin to help keep your baby comfortable. It also has a color-changing wetness indicator that tells you when your baby might need a change.",
imgUrl: "http://www.toysrus.com/graphics/product_images/pTRU1-18515968enh-z6.jpg",
buyUrl:"https://www.amazon.com/Pampers-Swaddlers-Diapers-Size-Count/dp/B00DFFT9SQ/ref=sr_1_1?s=baby-products&ie=UTF8&qid=1500510637&sr=1-1-spons&keywords=diapers&th=1",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:5,
name:"WaterWipes",
category: "Necessities" ,
description:"With such a gentle design, these wipes can be used for several cleaning purposes, including diapering, hand and mouth cleaning, quick body washes and breastfeeding hygiene, and they're safe enough to be used by anyone in the family. The hypoallergenic, soft wipes make a great cleaning solution for individuals with skin sensitivities.",
imgUrl: "http://www.toysrus.com/graphics/product_images/pTRU1-20442751enh-z6.jpg",
buyUrl:"http://www.toysrus.com/product/index.jsp?productId=56479906",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:5,
name:"watson lane betheny baby bag",
category: "Necessities" ,
description:"his season, at kate spade new york, everything's coming up roses, and that includes the watson lane betheny, a chic printed nylon baby bag that boasts loads of mom-friendly details",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/716HToAUiEL._UY500_.jpg",
buyUrl:"https://www.katespade.com/products/watson-lane-betheny-baby-bag/PXRU7645.html?cgid=ks-diaper-bags&dwvar_PXRU7645_color=071&dwvar_PXRU7645_size=UNS#start=2&cgid=ks-diaper-bags",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:6,
name:"Arms Reach Concepts Inc. Co-Sleeper Sleigh Bed",
category: "Nursery" ,
description:"The Arms Reach Sleigh Bedside Co-Sleeper Bassinet is made of beautiful solid beech wood designed to create a classic Sleigh Bed look. It attaches securely to your adult bed and fits all sizes from twin to California King, from 18 to 30 bed heights in two inch increments. The Sleigh Bedside Co-Sleeper Bassinet offers a cozy environment and ease of nighttime nursing while mother rests comfortably in her own bed.",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/41fRsP1x3CL._SX355_.jpg",
buyUrl:"https://www.amazon.com/Arms-Reach-Concepts-Co-Sleeper-Sleigh/dp/B0007CQ6G8/ref=sr_1_4_s_it?s=baby-products&ie=UTF8&qid=1500511330&sr=1-4&keywords=bassinet",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:6,
name:"Cristallo 2 Piece Nursery Set with Leather Panel",
category: "Nursery" ,
description:"Like the playful nature of light that bounces off a crystal and makes rainbows on the wall, the architectural shapes paired with the upholstered cushion of the Cristallo Forever Crib provide a playful combination of refined styling and chic design. The Cristallo Forever Crib is an enchanting blend of classic lines paired with sweet touches of sophisticated luxury.",
imgUrl: "https://images-na.ssl-images-amazon.com/images/I/51ic5ZkbR4L._SY450_.jpg",
buyUrl:"http://www.bambibaby.com/pali-cristallo-2-piece-nursery-set-with-leather-panel-crib-double-dresser?utm_source=google&utm_medium=pla&adpos=1o1&scid=scplp25376&sc_intid=25376&gclid=EAIaIQobChMIkvmh1c-W1QIVWVYNCh2h6QdjEAYYASABEgLkAPD_BwE",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:6,
name:"Fillmore Extra Wide Dresser & Topper Set",
category: "Nursery" ,
description:"Ample storage is a gift you will treasure more with each passing year, as your baby – and your baby's wardrobe – grows. With four small and four large drawers, this substantial dresser will meet your child’s needs through the teen years.",
imgUrl: "https://www.potterybarnkids.com/pkimgs/rk/images/dp/wcm/201728/0003/fillmore-extra-wide-dresser-topper-set-c.jpg",
buyUrl:"https://www.potterybarnkids.com/products/fillmore-extra-wide-dresser-and-changing-table-topper/?pkey=e%7Cbaby%2Bchanging%2Btable%7C81%7Cbest%7C0%7C1%7C24%7C%7C3&sku=5554568&group=1&cm_src=PRODUCTSEARCH",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
callid:6,
name:"Handmade Elephant & Bubble Baby Mobile",
category: "Nursery" ,
description:"This adorable elephant and bubble baby mobile will be the piece that really ties the nursery together! Natural wood and hand-knit organic cotton create the ideal combination for an eco-conscious mum and dad.",
imgUrl: "https://s-media-cache-ak0.pinimg.com/736x/6b/a7/2c/6ba72c1fe58029e2a199315553078b77--mobile-crochet-babymobile.jpg",
buyUrl:"https://www.amazon.com/Handmade-Elephant-Bubble-Baby-Mobile/dp/B01F7O3G0O/ref=sr_1_13_s_it?s=baby-products&ie=UTF8&qid=1500512177&sr=1-13&keywords=eco+friendly+mobile",
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
}]);
},
down: function (queryInterface, Sequelize) {
return queryInterface.dropTable('Chicmoms');
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('Person', null, {});
*/
}
};
<file_sep>/server/db/models/Practicalmoms.js
module.exports = function(sequelize, DataTypes) {
const Practicalmoms = sequelize.define("Practicalmoms", {
callId:{
type: DataTypes.BOOLEAN
},
name: {
type: DataTypes.TEXT
},
category: {
type: DataTypes.TEXT
},
description: {
type: DataTypes.TEXT
},
ImgUrl: {
type: DataTypes.TEXT
},
buyUrl:{
type: DataTypes.TEXT
}
});
return Practicalmoms;
};
<file_sep>/app/src/pages/dashboard.js
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom';
import { Grid, Row, Col } from 'react-bootstrap';
import LogoBlack from '../img/LogoBlack.jpg';
const styles = {
display: 'flex',
// justifyContent: "center",
};
const img ={
backgroundImage:`url(${LogoBlack})`,
width: "100%",
height: 900,
};
const Content ={
padding: 10,
margin: 10,
backgroundColor: "",
color: "",
display: "inline-block",
fontFamily: "monospace",
fontSize: "14",
textAlign: "center",
};
const questionLink = {
listStyle: 'none',
display: 'block',
padding: '16px 0px',
// color: '#757575',
textDecoration: 'none',
};
class Dashboard extends Component {
constructor(props){
super(props);
this.state={
redirect:""
}
}
componentWillMount() {
console.log(this.props.user);
if (this.props.user === null) {
this.setState({redirect: true});
}
}
render(){
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/login'/>;
}
return (
<div className="dashboard" style={styles}>
<Grid style={img}>
<Col md={12} >
<h1>Welcome to The Well-Stocked Stork!</h1>
<p style={Content}>If you’re expecting a baby, Congratulations! And if you’re simply looking around for a friend, you’ve come to the right place, too. (As long as you can answer a few questions that will assist us in determining the “right” mix of products for the upcoming bundle of joy, we can help!)</p>
<p style ={Content}> On the following pages, you’ll be asked to complete 10 fun and easy “quiz-style” questions.
A few considerations and disclaimers:</p>
<p style ={Content}> We use these answers to determine which “mom type” we’re making recommendations for – so keep that in mind when you provide answers.</p>
<p style ={Content}> We use the “mom” term loosely – we know in some families there are two dads, or aunts who act as moms, or moms who prefer to be called something else; we’re totally cool with that.</p>
<p style ={Content}> Our recommendations are based on what we’ve discovered in our own research, in exploring product reviews and from talking to real parents. We think you’ll love our product suggestions, but feel free to modify our lists if something doesn’t feel right to you.</p>
<p style ={Content}> Our site is new so once you’ve completed your survey and received your recommendations, we’d love your feedback. (We mean it!) We want The Well-Stocked Stork to be the best it can be, so please feel free to send your thoughts on how we can make the site even better for future users.</p>
<p style ={Content}> We can’t wait to help you stock up for your new addition!</p>
<p style ={Content}> Now, let’s get started … </p>
<li><Link to="/questions" style={questionLink}>Question</Link></li>
</Col>
</Grid>
{/*<li><Link to="/questions" style={questionLink}>Question</Link></li>*/}
</div>
)
}
}
export default Dashboard;
<file_sep>/server/db/models/surveyQuestions.js
module.exports = function(sequelize, DataTypes) {
const surveyQuestions = sequelize.define("surveyQuestions", {
question: {
type: DataTypes.STRING
},
callId:{
type: DataTypes.BOOLEAN
},
});
surveyQuestions.associate= function(models) {
surveyQuestions.hasMany(models.surveyAnswers, {
foreignKey: {
name: 'SurveyQuestionId',
foreignKeyConstraint: true,
onDelete: "cascade"
},
});
};
return surveyQuestions;
};<file_sep>/server/db/models/surveyAnswers.js
module.exports = function(sequelize, DataTypes) {
const surveyAnswers = sequelize.define("surveyAnswers", {
body: {
type: DataTypes.STRING(1000),
allowNull: false
},
value: {
type: DataTypes.INTEGER,
allowNull: false
},
});
surveyAnswers.associate = function (models) {
surveyAnswers.belongsTo(models.surveyQuestions, {
foreignKey: {
name: 'SurveyQuestionId',
foreignKeyConstraint: true,
allowNull: false
},
});
};
return surveyAnswers;
};
<file_sep>/app/src/sidemenu/sidemenuContent.js
import React from 'react';
import MaterialTitlePanel from './sidemenu material';
import PropTypes from 'prop-types';
import {BrowserRouter as Router, Route, Link, NavLink} from 'react-router-dom'
import { CSSTransitionGroup } from 'react-transition-group';
const styles = {
sidebar: {
width: 256,
height: '100%',
},
sidebarLink: {
display: 'block',
padding: '16px 0px',
color: 'white',
textDecoration: 'none',
fontFamily: "book",
fontSize: " 15.5",
},
divider: {
margin: '8px 0',
height: 1,
backgroundColor: '#d5e1bd',
},
content: {
padding: '16px',
height: '100%',
backgroundColor: '#a4ccd0',
},
sidebarUl: {
listStyle: 'none'
}
};
const SidebarContent = (props) => {
const style = props.style ? {...styles.sidebar, ...props.style} : styles.sidebar;
const links = [];
for (let ind = 0; ind < 10; ind++) {
links.push(
<a key={ind} href="#" style={styles.sidebarLink}>Mock menu item {ind}</a>);
}
return (
<MaterialTitlePanel title="Menu" style={style}>
<div style={styles.content}>
<ul style={styles.sidebarUl}>
<NavLink to="/" style={styles.sidebarLink}>Home</NavLink>
<li><Link to="/about" style={styles.sidebarLink}>About</Link></li>
</ul>
<div style={styles.divider} />
{/*{links}*/}
<ul style={styles.sidebarUl}>
<li><Link to="/register" style={styles.sidebarLink}>Register</Link></li>
<li><Link to="/login" style={styles.sidebarLink}>Login</Link></li>
<li><Link to="/ecomom" style={styles.sidebarLink}>Eco Mom</Link></li>
<li><Link to="/chicmom" style={styles.sidebarLink}>Chic Mom</Link></li>
<li><Link to="/practicalmom" style={styles.sidebarLink}>Practical Mom</Link></li>
</ul>
</div>
</MaterialTitlePanel>
);
};
SidebarContent.propTypes = {
style: PropTypes.object,
};
export default SidebarContent;<file_sep>/server/db/seeders/20170713003370-surveyQuestionsSeeders.js
module.exports = {
up: function (queryInterface, Sequelize) {
queryInterface.bulkInsert('surveyQuestions', [{
id:1,
question: "Which of the following statements applies to you when grocery shopping for your family? " ,
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
}, {
id:2,
question: "It’s date night and your partner lets you pick the restaurant for dinner. Which of the following do you choose: ",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:3,
question: "How often do you purchase clothing for your family?",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:4,
question: "When it comes to technology (cell phones, flat screens, laptops, etc), which of the below best describes you: ",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:5,
question: "How would you describe your relationship with make-up?",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:6,
question: "What does your dream nursery look like? ",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:7,
question: "What do you envision most when you think of your preferred method of transporting your newborn? ",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:8,
question: "You’re in charge of planning this year’s family vacation … where do you go? ",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:9,
question: "When it comes to toys for your kid(s): ",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
},{
id:10,
question: "NOT RELATED TO MOM “TYPE”: What is your plan for feeding your newborn?",
callID:1,
created_at: Sequelize.literal('CURRENT_TIMESTAMP'),
updated_at: Sequelize.literal('CURRENT_TIMESTAMP')
}]);
},
down: function (queryInterface, Sequelize) {
return queryInterface.dropTable('surveyQuestions');
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.bulkDelete('Person', null, {});
*/
}
};<file_sep>/app/src/pages/Login.js
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import React, { Component } from 'react';
import axios from 'axios';
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom'
class Login extends Component {
constructor(props){
super(props);
console.log('login::', props);
this.state={
username:'',
password:'',
redirect:'',
user:""
}
}
handleClick(event){
const self = this;
const payload = {
"username": this.state.username,
"password": <PASSWORD>
};
axios.post('/login', payload)
.then((response) => {
console.log(response);
if (response.status === 200) {
console.log("Login successfull");
this.setState({redirect: true});
// self.setState({ user: response.data.user.id});
this.props.onLogin(response.data.user.id);
}
else if (response.status === 404) {
console.log("Username password do not match");
alert("username or password is incorrect")
}
else {
console.log("Username does not exists");
alert("Username does not exist");
}
})
.catch(function (error) {
console.log(error);
});
}
render() {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/dashboard'/>;
}
return (
<div>
<MuiThemeProvider>
<div>
<h1>Login</h1>
<TextField
hintText="Enter your Username"
floatingLabelText="Username"
onChange = {(event,newValue) => this.setState({username:newValue})}
/>
<br/>
<TextField
type="password"
hintText="Enter your Password"
floatingLabelText="Password"
onChange = {(event,newValue) => this.setState({password:newValue})}
/>
<br/>
<RaisedButton label="Submit" primary={true} style={style} onClick={(event) => this.handleClick(event)}/>
</div>
</MuiThemeProvider>
</div>
);
}
}
const style = {
margin: 15,
};
export default Login;<file_sep>/server/db/config/config.js
module.exports = {
development: {
username: 'root',
password: '<PASSWORD>',
database: 'wellstockedstork',
host: '127.0.0.1',
dialect: 'mysql',
logging: console.log,
seederStorage: 'sequelize',
define: {
timestamps: false
}
},
production: {
use_env_variable: 'JAWSDB_URL',
dialect: 'mysql',
logging: false,
seederStorage: 'sequelize',
},
};<file_sep>/app/src/pages/home.js
import React from 'react';
import lincoln from '../img/lincoln.jpg';
import img01 from '../img/img01.JPG';
import img02 from '../img/img02.JPG';
import img03 from '../img/img03.JPG';
import img04 from '../img/img04.JPG';
import Rotation from 'react-rotation';
import logo from '../img/logo.jpg';
const styles = {
display: 'flex',
justifyContent: "center"
};
const Img={
width: "100%",
height: "100%",
};
const Content ={
padding: 250,
margin: 10,
backgroundImg: "",
color: "",
display: "inline-block",
fontFamily: "monospace",
fontSize: "50",
textAlign: "center",
};
const Home =() => {
return(
<div className="Home" style={styles} >
<img style={Img} src={logo}/>
</div>
)
};
export default Home;
|
6ed856a442c88bcbbd60a10c60fce8e7f27f5e14
|
[
"JavaScript"
] | 17 |
JavaScript
|
willisdorden/WellStockedStork-react-
|
af2db6a3470adc7673e9c87156fa0b4bbf398086
|
14ed0f3eabf5751ae85879672efbd9210a853a60
|
refs/heads/master
|
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: fmakgato <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2018/05/23 09:15:00 by fmakgato #+# #+# #
# Updated: 2018/07/24 14:05:39 by fmakgato ### ########.fr #
# #
# **************************************************************************** #
NAME = libft.a
APPNAME = filler
CSRC = libft/*.c
OSRC = *.o
APPCSRC = *.c
APPHEADER = filler.h
HEADER = libft/libft.h
FLAGS = -Wall -Wextra -Werror -I
all: $(NAME) $(APPNAME)
$(NAME):
@echo "Compiling $(NAME) .....!"
@make -C./libft/
@echo "$(NAME) created!"
$(APPNAME):
@echo "Compiling $(APPNAME) .....!"
gcc -o $(APPNAME) $(FLAGS) $(APPHEADER) $(APPCSRC) libft/$(NAME)
@echo "$(APPNAME) created!"
clean:
@echo "Deleting the $(OSRC) files ...!"
@make clean -C./libft/
@echo "The $(OSRC) deleted!"
fclean:
@echo "Deleting the $(OSRC) files, $(NAME) and $(APPNAME) ...!"
@make fclean -C./libft/
rm -rf $(APPNAME)
@echo "The $(OSRC) files, $(NAME) and $(APPNAME) deleted!"
re: fclean all
@echo "Re-compiled the $(NAME) and $(APPNAME) ...!"
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* plyalgo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmakgato <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/19 11:15:19 by fmakgato #+# #+# */
/* Updated: 2018/07/28 16:04:52 by fmakgato ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
static int algo_down_left(t_filler *ply)
{
int i;
int j;
i = ply->y_map;
while (i > 0)
{
j = 0;
while (j < ply->x_map)
{
if (try_piece(ply, i, j) == 1)
{
ply->ply_x = j;
ply->ply_y = i;
return (1);
}
j++;
}
i--;
}
return (0);
}
static int algo_up_right(t_filler *ply)
{
int i;
int j;
i = 0;
while (i < ply->y_map)
{
j = ply->x_map;
while (j > 0)
{
if (try_piece(ply, i, j) == 1)
{
ply->ply_x = j;
ply->ply_y = i;
return (1);
}
j--;
}
i++;
}
return (0);
}
static int algo_down_right(t_filler *ply)
{
int i;
int j;
i = ply->y_map;
while (i > 0)
{
j = ply->x_map;
while (j > 0)
{
if (try_piece(ply, i, j) == 1)
{
ply->ply_x = j;
ply->ply_y = i;
return (1);
}
j--;
}
i--;
}
return (0);
}
static int algo_up_left(t_filler *ply)
{
int i;
int j;
i = 0;
while (i < ply->y_map)
{
j = 0;
while (j < ply->x_map)
{
if (try_piece(ply, i, j) == 1)
{
ply->ply_x = j;
ply->ply_y = i;
return (1);
}
j++;
}
i++;
}
return (0);
}
int ko_algo(t_filler *ply)
{
if (ply->algo == 0)
return (algo_up_left(ply));
else if (ply->algo == 1)
return (algo_down_right(ply));
else if (ply->algo == 2)
return (algo_up_right(ply));
else if (ply->algo == 3)
return (algo_down_left(ply));
else
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmakgato <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/16 10:56:18 by fmakgato #+# #+# */
/* Updated: 2018/07/28 16:01:39 by fmakgato ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
#include <stdio.h>
#include <stdlib.h>
static int check_piece(t_filler *ply, int i, int j)
{
int my_piece;
int y;
int x;
my_piece = 0;
y = 0;
while (y < ply->y_piece)
{
x = 0;
while (x < ply->x_piece)
{
if ((ply->map[i + y][j + x] == ply->user ||
ply->map[i + y][j + x] == ply->user + 32)
&& ply->piece[y][x] == '*')
my_piece++;
if ((ply->map[i + y][j + x] == ply->oppon ||
ply->map[i + y][j + x] == ply->oppon + 32)
&& ply->piece[y][x] == '*')
return (0);
x++;
}
y++;
}
return ((my_piece == 1) ? 1 : 0);
}
int try_piece(t_filler *ply, int y, int x)
{
if (y + ply->y_piece > ply->y_map)
return (0);
else if (x + ply->x_piece > ply->x_map)
return (0);
else
return (check_piece(ply, y, x));
}
int main(void)
{
char *line;
t_filler *ply;
if (!(ply = ft_memalloc(sizeof(t_filler))))
return (-1);
get_next_line(0, &line);
ply->user = (ft_atoi(line + 10) == 1) ? 'O' : 'X';
while (1)
{
get_next_line(0, &line);
ply->y_map = ft_atoi(&line[8]);
ply->x_map = ft_atoi(&line[11]);
get_map(ply);
if (ko_algo(ply) == 0)
ply->ko = 1;
play_piece(ply);
if (ply->gameover == 1)
break ;
}
free(ply);
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* filler.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmakgato <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/15 15:22:12 by fmakgato #+# #+# */
/* Updated: 2018/07/28 15:56:23 by fmakgato ### ########.fr */
/* */
/* ************************************************************************** */
#include "filler.h"
int get_piece(t_filler *ply, char *line)
{
int n;
int i;
n = 6;
i = 0;
ply->y_piece = ft_atoi(&line[6]);
while (ft_isdigit(line[n]))
n++;
n++;
ply->x_piece = ft_atoi(&line[n]);
if (!ply->piece)
if (!(ply->piece = ft_strnew_two(ply->y_piece, ply->x_piece)))
return (-1);
while (i < ply->y_piece)
{
get_next_line(0, &line);
ply->piece[i] = ft_strdup(line);
i++;
}
return (0);
}
void get_position(t_filler *ply)
{
int i;
int j;
i = 0;
ply->oppon = (ply->user == 'O') ? 'X' : 'O';
while (i < ply->y_map)
{
j = 0;
while (j < ply->x_map)
{
if (ply->map[i][j] == ply->oppon)
{
ply->o_pos_x = j;
ply->o_pos_y = i;
}
else if (ply->map[i][j] == ply->user)
{
ply->u_pos_x = j;
ply->u_pos_y = i;
}
j++;
}
i++;
}
ply->algo = (ply->o_pos_y > ply->u_pos_y) ? 1 : 0;
}
void play_piece(t_filler *ply)
{
if (ply->algo == 0)
ply->algo = 3;
else if (ply->algo == 1)
ply->algo = 2;
else if (ply->algo == 2)
ply->algo = 1;
else if (ply->algo == 3)
ply->algo = 0;
if (ply->ko == 1)
{
ply->gameover = 1;
ft_putnbr(ply->ply_y);
ft_putchar(' ');
ft_putnbr(ply->ply_x);
ft_putchar('\n');
}
else
{
ft_putnbr(ply->ply_y);
ft_putchar(' ');
ft_putnbr(ply->ply_x);
ft_putchar('\n');
}
}
int get_map(t_filler *ply)
{
char *line;
int i;
i = 0;
if (!ply->map)
if (!(ply->map = ft_strnew_two(ply->y_map, ply->x_map)))
return (-1);
get_next_line(0, &line);
while (i <= ply->y_map)
{
get_next_line(0, &line);
if (ft_isdigit(line[0]))
ply->map[i] = ft_strdup(line + 4);
else
get_piece(ply, line);
i++;
}
if (ply->o_pos_x == 0 && ply->o_pos_y == 0 &&
ply->u_pos_x == 0 && ply->u_pos_y == 0)
get_position(ply);
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* filler.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: fmakgato <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/07/16 07:27:09 by fmakgato #+# #+# */
/* Updated: 2018/07/23 15:41:04 by fmakgato ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FILLER_H
# define FILLER_H
# include "libft/libft.h"
typedef struct s_filler
{
char user;
char oppon;
int x_map;
int y_map;
char **map;
int x_piece;
int y_piece;
char **piece;
int u_pos_x;
int u_pos_y;
int o_pos_x;
int o_pos_y;
int ply_x;
int ply_y;
int algo;
int ko;
int gameover;
} t_filler;
int get_map(t_filler *ply);
int get_piece(t_filler *ply, char *line);
int ko_algo(t_filler *ply);
void get_position(t_filler *ply);
int try_piece(t_filler *ply, int y, int x);
void play_piece(t_filler *ply);
#endif
|
1d7e03f2e0e762c4914cfd3b24d66c5fde0a8d5e
|
[
"C",
"Makefile"
] | 5 |
Makefile
|
fmakgato/filler
|
e673af8b34274b573b47b80438ae1bd78f1bd1f7
|
10c9fb950b5121773f9c48da5eeb00071a8dfdc9
|
refs/heads/master
|
<repo_name>bryandavisweb/rollbar-gem<file_sep>/spec/rollbar/request_data_extractor_spec.rb
require 'spec_helper'
require 'rack/mock'
require 'rollbar/request_data_extractor'
class ExtractorDummy
include Rollbar::RequestDataExtractor
end
describe Rollbar::RequestDataExtractor do
subject { ExtractorDummy.new }
let(:env) do
Rack::MockRequest.env_for('/', 'HTTP_HOST' => 'localhost:81', 'HTTP_X_FORWARDED_HOST' => 'example.org:9292')
end
describe '#extract_request_data_from_rack' do
let(:scrubber) { double }
it 'returns a Hash object' do
scrubber_config = {
:scrub_fields => kind_of(Array),
:scrub_user => Rollbar.configuration.scrub_user,
:scrub_password => <PASSWORD>,
:randomize_scrub_length => Rollbar.configuration.randomize_scrub_length
}
expect(Rollbar::Scrubbers::URL).to receive(:new).with(scrubber_config).and_return(scrubber)
expect(scrubber).to receive(:call).with(kind_of(String))
result = subject.extract_request_data_from_rack(env)
expect(result).to be_kind_of(Hash)
end
context 'with invalid utf8 sequence in key', :if => RUBY_VERSION != '1.8.7' do
let(:data) do
File.read(File.expand_path('../../support/encodings/iso_8859_9', __FILE__)).force_encoding(Encoding::ISO_8859_9)
end
let(:env) do
env = Rack::MockRequest.env_for('/',
'HTTP_HOST' => 'localhost:81',
'HTTP_X_FORWARDED_HOST' => 'example.org:9292',
'CONTENT_TYPE' => 'application/json')
env['rack.session'] = { data => 'foo' }
env
end
it 'doesnt crash' do
result = subject.extract_request_data_from_rack(env)
expect(result).to be_kind_of(Hash)
end
end
end
end
<file_sep>/lib/rollbar/core_ext/basic_socket.rb
require 'socket'
class BasicSocket
def as_json
to_s
end
end
<file_sep>/lib/rollbar/js/frameworks/rails.rb
module Rollbar
module Js
module Frameworks
class Rails
attr_accessor :prepared
alias prepared? prepared
def prepare
return if prepared?
if secure_headers?
insert_middleware_after_secure_headers
else
insert_middleware
end
self.prepared = true
end
def insert_middleware_after_secure_headers
instance = self
Rollbar::Railtie.initializer 'rollbar.js.frameworks.rails', :after => 'secure_headers.middleware' do |_app|
instance.insert_middleware
end
end
def insert_middleware
require 'rollbar/js/middleware'
config = {
:options => Rollbar.configuration.js_options,
:enabled => Rollbar.configuration.js_enabled
}
rails_config.middleware.use(::Rollbar::Js::Middleware, config)
end
def secure_headers?
defined?(::SecureHeaders)
end
def rails_config
::Rails.configuration
end
end
end
end
end
<file_sep>/lib/rollbar/scrubbers/url.rb
require 'cgi'
require 'uri'
require 'rollbar/language_support'
module Rollbar
module Scrubbers
class URL
attr_reader :regex
attr_reader :scrub_user
attr_reader :scrub_password
attr_reader :randomize_scrub_length
def initialize(options = {})
@regex = build_regex(options[:scrub_fields])
@scrub_user = options[:scrub_user]
@scrub_password = options[:scrub_password]
@randomize_scrub_length = options.fetch(:randomize_scrub_length, true)
end
def call(url)
return url unless Rollbar::LanguageSupport.can_scrub_url?
uri = URI.parse(url)
uri.user = filter_user(uri.user)
uri.password = filter_password(uri.password)
uri.query = filter_query(uri.query)
uri.to_s
rescue
url
end
private
# Builds a regex to match with any of the received fields.
# The built regex will also match array params like 'user_ids[]'.
def build_regex(fields)
fields_or = fields.map { |field| "#{field}(\\[\\])?" }.join('|')
Regexp.new("^#{fields_or}$")
end
def filter_user(user)
scrub_user && user ? filtered_value(user) : user
end
def filter_password(password)
scrub_password && password ? filtered_value(password) : password
end
def filter_query(query)
return query unless query
params = decode_www_form(query)
encoded_query = encode_www_form(filter_query_params(params))
# We want this to rebuild array params like foo[]=1&foo[]=2
CGI.unescape(encoded_query)
end
def decode_www_form(query)
URI.decode_www_form(query)
end
def encode_www_form(params)
URI.encode_www_form(params)
end
def filter_query_params(params)
params.map do |key, value|
[key, filter_key?(key) ? filtered_value(value) : value]
end
end
def filter_key?(key)
!!(key =~ regex)
end
def filtered_value(value)
if randomize_scrub_length
random_filtered_value
else
'*' * (value.length rescue 8)
end
end
def random_filtered_value
'*' * (rand(5) + 3)
end
end
end
end
<file_sep>/spec/rollbar/util_spec.rb
require 'spec_helper'
require 'rollbar/util'
describe Rollbar::Util do
describe '.deep_merge' do
context 'with nil arguments' do
let(:data) do
{ :foo => :bar }
end
it 'doesnt fail and returns same hash' do
result = Rollbar::Util.deep_merge(nil, data)
expect(result).to be_eql(data)
end
end
end
end
<file_sep>/lib/rollbar/js/frameworks.rb
module Rollbar
module Js
module Frameworks
end
end
end
<file_sep>/lib/rollbar/js.rb
require "rollbar/js/version"
module Rollbar
module Js
extend self
attr_reader :framework
attr_reader :framework_loader
def prepare
@framework ||= detect_framework
@framework_loader ||= load_framework_class.new
@framework_loader.prepare
end
private
def detect_framework
case
when defined?(::Rails::VERSION)
:rails
end
end
def load_framework_class
require "rollbar/js/frameworks/#{framework}"
Rollbar::Js::Frameworks.const_get(framework.to_s.capitalize)
end
end
end
|
cb3f2c09267dfcd38fe0ca2f12b760a87dac3744
|
[
"Ruby"
] | 7 |
Ruby
|
bryandavisweb/rollbar-gem
|
f4383920ac99893ae19d588219fd4330d5aa2d3d
|
cecfa1bae921e2fb5f91397979f72c89dd91e74e
|
refs/heads/master
|
<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.sample
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.maps.Style
import com.utsman.smartmarker.location.LocationWatcher
import com.utsman.smartmarker.mapbox.MarkerOptions
import com.utsman.smartmarker.mapbox.addMarker
import com.utsman.smartmarker.mapbox.toLatLngMapbox
import kotlinx.android.synthetic.main.activity_simple.*
class SimpleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(this, "<KEY>")
setContentView(R.layout.activity_simple)
val locationWatcher = LocationWatcher(this)
locationWatcher.getLocation(this) {
mapbox_view.getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.MAPBOX_STREETS) { style ->
val latlng = it.toLatLngMapbox()
val markerOptions = MarkerOptions.Builder()
.setId("layer-id")
.setIcon(R.drawable.ic_marker_direction_2, true)
.setPosition(latlng)
.build(this)
val marker = mapboxMap.addMarker(markerOptions)
btn_test.setOnClickListener {
style.removeLayer(marker.getId())
}
mapboxMap.addOnMapLongClickListener {
marker.moveMarkerSmoothly(it)
true
}
}
}
}
}
}<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.location;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.LocationRequest;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.util.concurrent.TimeUnit;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pl.charmas.android.reactivelocation2.ReactiveLocationProvider;
public class LocationWatcher {
private Context context;
private CompositeDisposable compositeDisposable;
public static class Priority {
public static long JEDI = 3;
public static long VERY_HIGH = 30;
public static long HIGH = 50;
public static long MEDIUM = 300;
public static long LOW = 3000;
public static long VERY_LOW = 8000;
}
public LocationWatcher(Context context) {
compositeDisposable = new CompositeDisposable();
this.context = context;
}
public void stopLocationWatcher() {
compositeDisposable.dispose();
}
public void getLocation(final Activity activity, final LocationListener locationListener) {
Dexter.withActivity(activity)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
getLocation(locationListener);
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
activity.finish();
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
})
.check();
}
public void getLocation(final LocationListener locationListener) {
LocationRequest request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setNumUpdates(1)
.setInterval(100);
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
Disposable locationDisposable = locationProvider
.getUpdatedLocation(request)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Location>() {
@Override
public void accept(Location location) throws Exception {
locationListener.location(location);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
Log.e("anjay", "cannot update location --> " + throwable.getMessage());
}
});
compositeDisposable.add(locationDisposable);
}
public void getLocationUpdate(final Activity activity, final long priority, final LocationUpdateListener locationUpdateListener) {
Dexter.withActivity(activity)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse response) {
getLocationUpdate(priority, locationUpdateListener);
}
@Override
public void onPermissionDenied(PermissionDeniedResponse response) {
activity.finish();
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
})
.check();
}
public void getLocationUpdate(long priority, final LocationUpdateListener locationUpdateListener) {
LocationRequest request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(100);
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
Disposable locationDisposable = locationProvider
.getUpdatedLocation(request)
.subscribeOn(Schedulers.io())
.doOnNext(new Consumer<Location>() {
@Override
public void accept(Location location) throws Exception {
locationUpdateListener.oldLocation(location);
}
})
.delay(priority, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(new Consumer<Location>() {
@Override
public void accept(Location location) throws Exception {
locationUpdateListener.newLocation(location);
}
})
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
locationUpdateListener.failed(throwable);
}
})
.subscribe();
compositeDisposable.add(locationDisposable);
}
}
<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.mapbox
import com.mapbox.mapboxsdk.geometry.LatLng
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
object MathUtil {
fun computeHeading(from: LatLng, to: LatLng, fromN: Double): Double {
val fromLat = Math.toRadians(from.latitude)
val fromLng = Math.toRadians(from.longitude)
val toLat = Math.toRadians(to.latitude)
val toLng = Math.toRadians(to.longitude)
val dLng = toLng - fromLng
val heading = atan2(
sin(dLng) * cos(toLat),
cos(fromLat) * sin(toLat) - sin(fromLat) * cos(toLat) * cos(dLng)
)
return wrap(Math.toDegrees(heading) - fromN, -180.0, 180.0)
}
private fun wrap(n: Double, min: Double, max: Double): Double {
return if (n >= min && n < max) n else mod(
n - min,
max - min
) + min
}
private fun mod(x: Double, m: Double): Double {
return (x % m + m) % m
}
}<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.mapbox
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.util.Log
import androidx.annotation.DrawableRes
import androidx.core.content.res.ResourcesCompat
import com.mapbox.geojson.Feature
import com.mapbox.geojson.Point
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.PropertyFactory
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
import com.mapbox.mapboxsdk.utils.BitmapUtils
class MarkerBuilder(private val context: Context, private val style: Style?) {
lateinit var jsonSource: GeoJsonSource
lateinit var symbolLayer: SymbolLayer
private fun newSymbol(id: String): SymbolLayer {
return SymbolLayer(id, "source-$id")
}
internal fun newMarker(id: String, latLng: LatLng, @DrawableRes iconVector: Int, vector: Boolean = false): SymbolLayer {
symbolLayer = newSymbol(id)
jsonSource = GeoJsonSource(
"source-$id",
Feature.fromGeometry(Point.fromLngLat(latLng.longitude, latLng.latitude))
)
if (vector) {
style?.addImage("marker-$id", markerVector(context, iconVector))
} else {
val markerBitmap =
BitmapFactory.decodeResource(context.resources, iconVector)
try {
style?.addImage("marker-$id", markerBitmap)
} catch (e: NullPointerException) {
Log.e("SmartMarker-mapbox", "Cannot process bitmap, maybe your marker is vector, please add 'true' in 'addIcon'")
}
}
style?.addSource(jsonSource)
symbolLayer.withProperties(
PropertyFactory.iconImage("marker-$id"),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconAllowOverlap(true)
)
Log.i("symbol layer id is --> ", id)
return symbolLayer
}
}
internal fun Style.addMarker(symbolLayer: SymbolLayer) {
addLayer(symbolLayer)
}
internal fun markerVector(context: Context, @DrawableRes marker: Int): Bitmap {
val drawable = ResourcesCompat.getDrawable(context.resources,
marker, null)
return BitmapUtils.getBitmapFromDrawable(drawable) ?: BitmapFactory.decodeResource(context.resources,
R.drawable.mapbox_marker_icon_default
)
}<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.mapbox
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.graphics.Color
import android.os.Handler
import android.os.SystemClock
import android.util.Log
import android.view.animation.LinearInterpolator
import androidx.annotation.ColorInt
import androidx.annotation.Nullable
import androidx.lifecycle.MutableLiveData
import com.mapbox.android.gestures.RotateGestureDetector
import com.mapbox.geojson.Point
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.PropertyFactory
import com.mapbox.mapboxsdk.style.layers.PropertyValue
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
class Marker(private var currentLatLng: LatLng,
private val mapboxMap: MapboxMap,
private val jsonSource: GeoJsonSource,
private val symbolLayer: SymbolLayer,
private val idMarker: String) {
private val liveRotate = MutableLiveData<Float>()
private var animator: ValueAnimator? = null
private var heading = 0.0
fun getId() = idMarker
fun getRotation() = heading
private val liveVisibility = MutableLiveData<Boolean>()
init {
liveRotate.postValue(0f)
liveRotate.observeForever {
symbolLayer.withProperties(PropertyFactory.iconRotate(it))
}
liveVisibility.observeForever {
symbolLayer.withProperties(PropertyFactory.iconRotate(160f))
}
}
internal fun rotateMarker(rotate: Double) {
rotateMarker(symbolLayer, rotate.toFloat())
}
fun moveMarkerSmoothly(newLatLng: LatLng, @Nullable rotate: Boolean? = true) {
if (animator != null && animator!!.isStarted) {
currentLatLng = animator!!.animatedValue as LatLng
animator!!.cancel()
}
animator = ObjectAnimator.ofObject(latLngEvaluator, currentLatLng, newLatLng).apply {
duration = 2000
addUpdateListener(animatorUpdateListener(jsonSource))
}
animator?.start()
if (rotate != null && rotate) {
mapboxMap.addOnRotateListener(object : MapboxMap.OnRotateListener {
override fun onRotate(detector: RotateGestureDetector) {
}
override fun onRotateEnd(detector: RotateGestureDetector) {
}
override fun onRotateBegin(detector: RotateGestureDetector) {
}
})
rotateMarker(symbolLayer, (getAngle(currentLatLng, newLatLng)).toFloat())
}
}
fun getLatLng() = currentLatLng
fun getSource() = jsonSource
private fun animatorUpdateListener(jsonSource: GeoJsonSource) : ValueAnimator.AnimatorUpdateListener {
return ValueAnimator.AnimatorUpdateListener { value ->
val animatedLatLng = value.animatedValue as LatLng
jsonSource.setGeoJson(Point.fromLngLat(animatedLatLng.longitude, animatedLatLng.latitude))
}
}
private fun rotateMarker(symbolLayer: SymbolLayer?, toRotation: Float) {
val handler = Handler()
val start = SystemClock.uptimeMillis()
var startRotation = symbolLayer?.iconRotate?.value ?: 90f
val duration: Long = 200
handler.post(object : Runnable {
override fun run() {
val elapsed = SystemClock.uptimeMillis() - start
val t = LinearInterpolator().getInterpolation( elapsed.toFloat() / duration)
try {
val rot = t * toRotation + (1 - t) * startRotation
val rotation = if (-rot > 180) rot / 2 else rot
liveRotate.postValue(rotation)
currentLatLng = animator!!.animatedValue as LatLng
startRotation = rotation
if (t < 1.0) {
handler.postDelayed(this, 100)
}
} catch (e: IllegalStateException) {
Log.e("smartmarker-mapbox", "set rotation failed")
}
}
})
}
private fun getAngle(fromLatLng: LatLng, toLatLng: LatLng) : Double {
if (fromLatLng != toLatLng) {
val mapRot = mapboxMap.cameraPosition.bearing
heading = MathUtil.computeHeading(fromLatLng, toLatLng, mapRot)
logi("angle is --> $heading -- $mapRot")
}
return heading
}
private fun logi(msg: String?) = Log.i("anjay", msg)
}
<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.sample
import android.location.Location
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.android.gestures.RotateGestureDetector
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
import com.mapbox.mapboxsdk.location.LocationComponentOptions
import com.mapbox.mapboxsdk.location.modes.CameraMode
import com.mapbox.mapboxsdk.location.modes.RenderMode
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.utsman.smartmarker.location.LocationUpdateListener
import com.utsman.smartmarker.location.LocationWatcher
import com.utsman.smartmarker.mapbox.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_tracker_mapbox.*
import java.util.concurrent.TimeUnit
class TrackerMapboxActivity : AppCompatActivity() {
private val locationWatcher by lazy {
LocationWatcher(this)
}
private val compositeDisposable = CompositeDisposable()
private var marker1: Marker? = null
private lateinit var marker2: Marker
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(this, "<KEY>")
setContentView(R.layout.activity_tracker_mapbox)
mapbox_view_1.getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.OUTDOORS) { style ->
val updatePosition = CameraPosition.Builder()
.zoom(17.0)
.build()
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(updatePosition))
val locationComponentOption = LocationComponentOptions.builder(this)
.bearingTintColor(R.color.colorPrimary)
//.accuracyAlpha(0.8f) // 0.0f - 1.0f
.build()
val locationComponentActivationOptions = LocationComponentActivationOptions
.builder(this, style)
.locationComponentOptions(locationComponentOption)
.useDefaultLocationEngine(true)
.build()
val locationComponent = mapboxMap.locationComponent
locationComponent.activateLocationComponent(locationComponentActivationOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.cameraMode = CameraMode.TRACKING_GPS
locationComponent.renderMode = RenderMode.GPS
timer {
moveCamera(it, mapboxMap)
}
}
}
mapbox_view_2.getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.OUTDOORS) { style ->
locationWatcher.getLocation(this) { location ->
val markerOptions = MarkerOptions.Builder()
.setId("id", true)
.setIcon(R.drawable.ic_marker_direction_2, true)
.setPosition(location.toLatLngMapbox())
.build(this)
marker1 = mapboxMap.addMarker(markerOptions)
moveCamera(location, mapboxMap)
updateLocation()
mapboxMap.addOnRotateListener(object : MapboxMap.OnRotateListener {
override fun onRotate(detector: RotateGestureDetector) {
}
override fun onRotateEnd(detector: RotateGestureDetector) {
toast("rotation --> ${mapboxMap.cameraPosition.bearing}")
logi("rotation --> ${mapboxMap.cameraPosition.bearing}")
}
override fun onRotateBegin(detector: RotateGestureDetector) {
}
})
timer {
moveCamera(it, mapboxMap)
}
}
}
}
mapbox_view_3.getMapAsync { mapboxMap ->
mapboxMap.setStyle(Style.OUTDOORS) { style ->
locationWatcher.getLocation(this) { location ->
val markerOptions = MarkerOptions.Builder()
.setId("layer-id")
.setIcon(R.drawable.ic_marker_direction_2, true)
.setPosition(location.toLatLngMapbox())
.build(this)
marker2 = mapboxMap.addMarker(markerOptions)
logi("marker is --> ${marker2.getId()}")
moveCamera(location, mapboxMap)
updateLocation()
mapboxMap.addOnRotateListener(object : MapboxMap.OnRotateListener {
override fun onRotate(detector: RotateGestureDetector) {
}
override fun onRotateEnd(detector: RotateGestureDetector) {
toast("rotation --> ${mapboxMap.cameraPosition.bearing}")
logi("rotation --> ${mapboxMap.cameraPosition.bearing}")
}
override fun onRotateBegin(detector: RotateGestureDetector) {
}
})
Handler().postDelayed({
toast("start remove marker --> ${marker2.getId()}")
//style.removeImage(marker2?.getId()!!)
//style.removeMarker(marker2!!)
//style.removeLayer
//style.removeLayer(marker2.getId())
//style.layers.clear()
//markerOptions.removeMe()
style.removeLayer("layer-id")
}, 5000)
val updatePosition = CameraPosition.Builder()
.zoom(17.0)
.build()
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(updatePosition))
val locationComponentOption = LocationComponentOptions.builder(this)
.bearingTintColor(R.color.colorPrimary)
//.accuracyAlpha(0.8f) // 0.0f - 1.0f
.build()
val locationComponentActivationOptions = LocationComponentActivationOptions
.builder(this, style)
.locationComponentOptions(locationComponentOption)
.useDefaultLocationEngine(true)
.build()
val locationComponent = mapboxMap.locationComponent
locationComponent.activateLocationComponent(locationComponentActivationOptions)
locationComponent.isLocationComponentEnabled = true
locationComponent.cameraMode = CameraMode.TRACKING_GPS
locationComponent.renderMode = RenderMode.GPS
timer {
moveCamera(it, mapboxMap)
}
}
}
}
}
private fun moveCamera(it: Location, mapboxMap: MapboxMap) {
val updatePosition = CameraPosition.Builder()
.target(it.toLatLngMapbox())
.zoom(17.0)
.build()
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(updatePosition))
}
private fun updateLocation() {
locationWatcher.getLocationUpdate(LocationWatcher.Priority.JEDI, object : LocationUpdateListener {
override fun oldLocation(oldLocation: Location) {
}
override fun newLocation(newLocation: Location) {
marker1?.moveMarkerSmoothly(newLocation.toLatLngMapbox())
marker2?.moveMarkerSmoothly(newLocation.toLatLngMapbox())
}
override fun failed(throwable: Throwable) {
}
})
}
private fun timer(ready: (Location) -> Unit) {
val obs = Observable.interval(5000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
locationWatcher.getLocation(this) {
ready.invoke(it)
}
}
compositeDisposable.add(obs)
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.dispose()
locationWatcher.stopLocationWatcher()
}
}<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.mapbox
import android.content.Context
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
class MarkerOptions private constructor(
internal val context: Context?,
internal val id: String?,
internal val icon: Int?,
internal val vector: Boolean?,
internal val latLng: LatLng?,
internal val rotation: Double?,
internal val symbolLayer: ((SymbolLayer) -> Unit)?) {
data class Builder(
private var context: Context? = null,
private var id: String? = null,
private var requestUniqueId: Boolean? = false,
private var icon: Int = R.drawable.mapbox_marker_icon_default,
private var vector: Boolean? = false,
private var latLng: LatLng? = null,
private var rotation: Double? = null,
private var symbolLayer: ((SymbolLayer) -> Unit)? = null
) {
fun setId(id: String, requestUniqueId: Boolean = false) = apply {
if (requestUniqueId) {
this.id = "${id}_${System.currentTimeMillis()}"
} else {
this.id = id
}
}
fun setIcon(icon: Int, vector: Boolean? = false) = apply {
this.icon = icon
this.vector = vector
}
fun setPosition(latLng: LatLng) = apply { this.latLng = latLng }
fun setRotation(rotation: Double?) = apply { this.rotation = rotation }
fun withSymbolLayer(symbolLayer: ((SymbolLayer) -> Unit)) = apply { this.symbolLayer = symbolLayer }
fun build(context: Context) = MarkerOptions(context, id, icon, vector, latLng, rotation, symbolLayer)
}
internal lateinit var markerSymbol: SymbolLayer
internal var style: Style? = null
/*internal fun addMarkerSymbol(style: Style?, markerSymbol: SymbolLayer) {
this.style = style
this.markerSymbol = markerSymbol
}*/
internal var remo: (() -> Unit?)? = null
internal fun remove(remove : () -> Unit) {
remo = remove
}
fun removeMe() = apply {
remo?.invoke()
}
}
<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
const val kotlin_version = "1.3.50"
object Core {
val kotlin = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
val appCompat = "androidx.appcompat:appcompat:1.0.2"
val ktx = "androidx.core:core-ktx:1.0.2"
val permission = "com.karumi:dexter:5.0.0"
}
object Maps {
val mapbox = "com.mapbox.mapboxsdk:mapbox-android-sdk:8.4.0"
val googleMap = "com.google.android.gms:play-services-maps:17.0.0"
val gmsLocationService = "com.google.android.gms:play-services-location:17.0.0"
val rxLocation = "pl.charmas.android:android-reactive-location2:2.1@aar"
}
object Rx {
val rxJava = "io.reactivex.rxjava2:rxjava:2.2.9"
val rxAndroid = "io.reactivex.rxjava2:rxandroid:2.1.1"
}
object Module {
val smartMarker = ":smartmarker"
val extGoogleMaps = ":extensions:googlemaps"
val extMapbox = ":extensions:mapbox"
}<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.sample
import android.location.Location
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
import com.utsman.smartmarker.SmartMarker
import com.utsman.smartmarker.googlemaps.bitmapFromVector
import com.utsman.smartmarker.googlemaps.toLatLngGoogle
import com.utsman.smartmarker.location.LocationUpdateListener
import com.utsman.smartmarker.location.LocationWatcher
import com.utsman.smartmarker.mapbox.addMarker
import com.utsman.smartmarker.mapbox.toLatLngMapbox
import com.utsman.smartmarker.moveMarkerSmoothly
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
private lateinit var locationWatcher: LocationWatcher
private var googleMarker: Marker? = null
private var mapboxMarker: com.utsman.smartmarker.mapbox.Marker? = null
private var googleMap: GoogleMap? = null
private var mapboxMap: MapboxMap? = null
private val disposable = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(this, "<KEY>")
setContentView(R.layout.activity_main)
locationWatcher = LocationWatcher(this)
val googleMapsView = (google_map_view as SupportMapFragment)
val mapboxMapsView = findViewById<MapView>(R.id.mapbox_view)
// get location once time
locationWatcher.getLocation(this) { loc ->
// google maps async
googleMapsView.getMapAsync { map ->
googleMap = map
val markerOption = MarkerOptions()
.position(loc.toLatLngGoogle())
.icon(bitmapFromVector(this@MainActivity, R.drawable.ic_marker_direction_2))
googleMarker = map.addMarker(markerOption)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc.toLatLngGoogle(), 17f))
}
// mapbox async
mapboxMapsView.getMapAsync { map ->
mapboxMap = map
map.setStyle(Style.OUTDOORS) { style ->
/**
* version 0.0.3
* */
/*val markerUtil = com.utsman.smartmarker.mapbox.MarkerOptions(this, style)
mapboxMarker = markerUtil.addMarker("driver", R.drawable.ic_marker_direction_2, true, loc.toLatLngMapbox())*/
/**
* End version 0.0.3
* */
/**
* version 1.0.3 use MarkerOptions
* */
val markerOptions = com.utsman.smartmarker.mapbox.MarkerOptions.Builder()
.setId("id")
.setIcon(R.drawable.mapbox_marker_icon_default)
.setPosition(loc.toLatLngMapbox())
.build(this)
val bnd = com.mapbox.mapboxsdk.geometry.LatLng(-6.914744, 107.609810)
val jgkt = com.mapbox.mapboxsdk.geometry.LatLng(-7.797068, 110.370529)
val bks = com.mapbox.mapboxsdk.geometry.LatLng(-6.241586, 106.992416)
val btn = com.mapbox.mapboxsdk.geometry.LatLng(-6.120000, 106.150276)
val markerOptions1 = com.utsman.smartmarker.mapbox.MarkerOptions.Builder()
.setId("jgja")
.setIcon(R.drawable.ic_marker_direction_2, true)
.setPosition(jgkt)
.build(this)
val markerOptions2 = com.utsman.smartmarker.mapbox.MarkerOptions.Builder()
.setId("bks")
.setIcon(R.drawable.ic_marker_direction_2, true)
.setPosition(bks)
.build(this)
val markerOptions3 = com.utsman.smartmarker.mapbox.MarkerOptions.Builder()
.setId("btn")
.setPosition(btn)
.build(this)
//val markers = map.addMarkers(markerOptions1, markerOptions2, markerOptions3)
val marker = map.addMarker(markerOptions3)
btn_test.setOnClickListener {
//markers.getId("btn").moveMarkerSmoothly(bks)
marker?.moveMarkerSmoothly(bks)
/*markers.filter {
it.getId() != "bks"
}.apply {
map {
it.moveMarkerSmoothly(bnd)
}
}*/
}
//val bndMarker = map.addMarker(markerOptions1)
val position = CameraPosition.Builder()
.target(loc.toLatLngMapbox())
.zoom(15.0)
.build()
map.animateCamera(com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newCameraPosition(position))
}
}
}
// update camera to marker every 5 second
timer {
//googleMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(it.toLatLngGoogle(), 17f))
val position = CameraPosition.Builder()
.target(it.toLatLngMapbox())
.zoom(15.0)
.build()
//mapboxMap?.animateCamera(com.mapbox.mapboxsdk.camera.CameraUpdateFactory.newCameraPosition(position))
}
// update your location
updateLocation()
}
private fun updateLocation() {
locationWatcher.getLocationUpdate(this, LocationWatcher.Priority.HIGH, object : LocationUpdateListener {
override fun oldLocation(oldLocation: Location) {
}
override fun newLocation(newLocation: Location) {
googleMarker?.moveMarkerSmoothly(newLocation.toLatLngGoogle())
mapboxMarker?.let { marker ->
SmartMarker.moveMarkerSmoothly(marker, newLocation.toLatLngMapbox())
}
}
override fun failed(throwable: Throwable?) {
}
})
}
private fun timer(ready: (Location) -> Unit) {
val obs = Observable.interval(5000, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
locationWatcher.getLocation(this) {
ready.invoke(it)
}
}
disposable.add(obs)
}
override fun onDestroy() {
locationWatcher.stopLocationWatcher()
disposable.dispose()
super.onDestroy()
}
}
<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.mapbox
import android.animation.TypeEvaluator
import android.location.Location
import android.util.Log
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
fun Location.toLatLngMapbox() = LatLng(latitude, longitude)
val latLngEvaluator = object : TypeEvaluator<LatLng> {
val latLng = LatLng()
override fun evaluate(f: Float, startLatLng: LatLng, endLatlng: LatLng): LatLng {
latLng.latitude = startLatLng.latitude + (endLatlng.latitude - startLatLng.latitude) * f
latLng.longitude = startLatLng.longitude + (endLatlng.longitude - startLatLng.longitude) * f
return latLng
}
}
fun MapboxMap.addMarker(options: MarkerOptions): Marker {
val markerBuilder = MarkerBuilder(options.context!!, style)
val marker = markerBuilder.newMarker(options.id!!, options.latLng!!, options.icon!!, options.vector!!)
options.symbolLayer?.invoke(marker)
style?.addMarker(marker)
Log.i("marker is ", "added, markerId -> ${options.id}")
val jsonSource = markerBuilder.jsonSource
val mark = Marker(options.latLng, this, jsonSource, marker, options.id)
options.rotation?.let { rot ->
mark.rotateMarker(rot)
}
val markerLayer = MarkerLayer(markerBuilder.symbolLayer.id, jsonSource.id)
markerLayer.add(mark)
return markerLayer.get(options.id)
}
class MarkerLayer(layerId: String, sourceId: String) : SymbolLayer(layerId, sourceId) {
private val markers: MutableList<Marker> = mutableListOf()
fun add(marker: Marker) = apply { markers.add(marker) }
fun get(id: String): Marker {
return markers.single { id == it.getId() }
}
}<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.sample
import android.content.Context
import android.util.Log
import android.widget.Toast
fun logi(msg: String?) = Log.i("anjay", msg)
fun loge(msg: String?) = Log.e("anjay", msg)
fun Context.toast(msg: String) = Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()<file_sep># Smart Marker For Google Maps and Mapbox
### This library for helper movement marker in your maps
<p align="center">
<img src="https://i.ibb.co/Wspktd7/ezgif-com-gif-maker-1.gif"/>
</p>
## Table of Content
- [Download](https://github.com/utsmannn/SmartMarker#download)
- [Marker](https://github.com/utsmannn/SmartMarker#add-marker)
- [Google Maps](https://github.com/utsmannn/SmartMarker#google-maps)
- [Mapbox](https://github.com/utsmannn/SmartMarker#mapbox)
- [Move Marker](https://github.com/utsmannn/SmartMarker#move-your-marker)
- [Location Watcher](https://github.com/utsmannn/SmartMarker#location-watcher-extension)
- [Installation](https://github.com/utsmannn/SmartMarker#installation)
- [Realtime Level](https://github.com/utsmannn/SmartMarker#realtime-level)
- [Use](https://github.com/utsmannn/SmartMarker#use)
- [Permission Helper](https://github.com/utsmannn/SmartMarker#permission-helper)
- [Other Extensions](https://github.com/utsmannn/SmartMarker#other-extensions)
- [Simple Example](https://github.com/utsmannn/SmartMarker#simple-example)
- [Google Maps Activity](https://github.com/utsmannn/SmartMarker#google-maps-1)
- [Mapbox Activity](https://github.com/utsmannn/SmartMarker#mapbox-1)
## Download
[  ](https://bintray.com/kucingapes/utsman/com.utsman.smartmarker/_latestVersion) <br>
```groovy
// the core library
implementation 'com.utsman.smartmarker:core:1.3.2@aar'
// extension for google maps
implementation 'com.utsman.smartmarker:ext-googlemaps:1.3.2@aar'
// extension for Mapbox
implementation 'com.utsman.smartmarker:ext-mapbox:1.3.2@aar'
```
For extensions, you don't need to add mapbox extensions if you not use the sdk mapbox. As well as the google map sdk.
## Add Marker
### Google Maps
Use the default method as usual for google maps. Reference for add marker in google maps [is here](https://developers.google.com/maps/documentation/android-sdk/map-with-marker) <br>
And code look like this
```kotlin
val markerOption = MarkerOptions()
.position(latLng)
val marker = map.addMarker(markerOption) // this your marker
```
### Mapbox
For Mapbox, adding marker is little hard, so I create helper for it, ***and you must coding after setup ```style```***
```kotlin
// define marker options
val markerOption = MarkerOptions.Builder() // from 'com.utsman.smartmarker.mapbox.MarkerOptions'
.setId("marker-id", true) // if marker id need unique id with timestamp, default is false
.setIcon(R.drawable.ic_marker, true) // if marker is not vector, use 'false'
.setPosition(latLng)
.setRotation(rotation)
.build(context)
// add your marker
val marker = map.addMarker(markerOption)
```
## Move Your Marker
```kotlin
SmartMarker.moveMarkerSmoothly(marker, latLng)
// or for disable rotation
SmartMarker.moveMarkerSmoothly(marker, latLng, false)
// with extensions for kotlin
marker.moveMarkerSmoothly(latLng)
// or for disable rotation
marker.moveMarkerSmoothly(latLng, false)
```
## Location Watcher Extension
I create location extensions for get your location every second with old location and new location, you can setup realtime level. <br>
### Installation
```groovy
implementation 'com.utsman.smartmarker:ext-location:1.2.5@aar'
// for extensions watcher location, you need some library with latest versions
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'pl.charmas.android:android-reactive-location2:2.1@aar'
implementation 'io.reactivex.rxjava2:rxjava:2.2.12'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.karumi:dexter:6.0.0'
```
### Realtime Level
You can setup realtime level for get every second update, `locationWatcher.getLocationUpdate(priority, listener)`
| level | ms |
| -- | -- |
| `LocationWatcher.Priority.JEDI` | 3 ms |
| `LocationWatcher.Priority.VERY_HIGH` | 30 ms |
| `LocationWatcher.Priority.HIGH` | 50 ms |
| `LocationWatcher.Priority.MEDIUM` | 300 ms |
| `LocationWatcher.Priority.LOW` | 3000 ms |
| `LocationWatcher.Priority.VERY_LOW` | 8000 ms |
### Use
```kotlin
// define location watcher
val locationWatcher: LocationWatcher = LocationWatcher(context)
// get location once time
locationWatcher.getLocation { location ->
// your location result
}
// get location update every second
locationWatcher.getLocationUpdate(LocationWatcher.Priority.HIGH, object : LocationUpdateListener {
override fun oldLocation(oldLocation: Location?) {
// your location realtime result
}
override fun newLocation(newLocation: Location?) {
// your location past with delay 30 millisecond (0.03 second)
}
override fun failed(throwable: Throwable?) {
// if location failed
}
})
// stop your watcher in onStop activity
override fun onDestroy() {
locationWatcher.stopLocationWatcher()
super.onDestroy()
}
```
### Permission helper
If you have not applied location permission for your app, you can be set permission with adding context before listener.
```kotlin
// get location once time with permission helper
locationWatcher.getLocation(context) { location ->
// your location result
}
// get location update every second with permission helper
locationWatcher.getLocationUpdate(context, LocationWatcher.Priority.HIGH, object : LocationUpdateListener {
override fun oldLocation(oldLocation: Location?) {
// your location realtime result
}
override fun newLocation(newLocation: Location?) {
// your location past with delay 30 millisecond (0.03 second)
}
override fun failed(throwable: Throwable?) {
// if location failed
}
})
```
Don't forget to add location permission ```android.permission.ACCESS_FINE_LOCATION``` for your apps
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
```
## Other Extensions
```kotlin
// Convert Location to LatLng for Google Maps ('com.google.android.gms.maps.model.LatLng')
location.toLatLngGoogle()
// Convert Location to LatLng for Mapbox ('com.mapbox.mapboxsdk.geometry.LatLng')
location.toLatLngMapbox()
// use marker as vector for Google Maps
bitmapFromVector(context, R.drawable.marker_vector)
```
## Simple Example
### Google Maps
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var locationWatcher: LocationWatcher
private var marker: Marker? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
locationWatcher = LocationWatcher(this)
val googleMapsView = (google_map_view as SupportMapFragment)
locationWatcher.getLocation(this) { loc ->
googleMapsView.getMapAsync { map ->
val markerOption = MarkerOptions()
.position(loc.toLatLngGoogle())
.icon(bitmapFromVector(this@MainActivity, R.drawable.ic_marker))
marker = map.addMarker(markerOption)
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc.toLatLngGoogle(), 17f))
}
}
// device tracker
locationWatcher.getLocationUpdate(this, LocationWatcher.Priority.HIGH, object : LocationUpdateListener {
override fun oldLocation(oldLocation: Location) {
}
override fun newLocation(newLocation: Location) {
// move your marker smoothly with new location
marker?.moveMarkerSmoothly(newLocation.toLatLngGoogle())
// or use class SmartMarker for java
// SmartMarker.moveMarkerSmoothly(marker, newLocation.toLatLngMapbox())
}
override fun failed(throwable: Throwable?) {
}
})
}
}
```
### Mapbox
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var locationWatcher: LocationWatcher
private var marker: Marker? = null // from 'com.utsman.smartmarker.mapbox.Marker'
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setup instance with api key mapbox before 'setContentView'
Mapbox.getInstance(this, "<KEY>")
setContentView(R.layout.activity_main)
locationWatcher = LocationWatcher(this)
locationWatcher.getLocation(this) { loc ->
mapbox_view.getMapAsync { map ->
// set style before setup your marker
map.setStyle(Style.OUTDOORS) { style ->
val markerOption = MarkerOptions.Builder() // from 'com.utsman.smartmarker.mapbox.MarkerOptions'
.setId("marker-id")
.addIcon(R.drawable.ic_marker, true)
.addPosition(loc.toLatLngMapbox())
.build(this)
val markerLayer = map.addMarker(markerOption)
marker = markerLayer.get("marker-id")
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc.toLatLngGoogle(), 17f))
}
}
}
// device tracker
locationWatcher.getLocationUpdate(this, LocationWatcher.Priority.HIGH, object : LocationUpdateListener {
override fun oldLocation(oldLocation: Location) {
}
override fun newLocation(newLocation: Location) {
// move your marker smoothly with new location
marker?.moveMarkerSmoothly(newLocation.toLatLngGoogle())
// or use class SmartMarker for java
// SmartMarker.moveMarkerSmoothly(marker, newLocation.toLatLngMapbox())
}
override fun failed(throwable: Throwable?) {
}
})
}
}
```
## My Other Libraries
- [Recycling](https://github.com/utsmannn/Recycling) <br>
A Library for make an easy and faster RecyclerView without adapter
- [rmqa](https://github.com/utsmannn/rmqa)<br>
Rabbit Message Queue for Android
- [Anko Navigation Drawer](https://github.com/utsmannn/AnkoNavigationDrawer)<br>
Library for implementation Navigation Drawer with styles in Anko
- [Easy Google Login](https://github.com/utsmannn/EasyGoogleLogin)<br>
Library for Simplify Firebase Authenticate Google Auth
---
```
Copyright 2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
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.
```
---
makasih<file_sep>/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.utsman.smartmarker.googlemaps
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.location.Location
import android.os.Handler
import android.os.SystemClock
import android.view.animation.LinearInterpolator
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
fun Location.toLatLngGoogle() = LatLng(latitude, longitude)
fun rotateMarker(marker: Marker, toRotation: Float, rotate: Boolean? = true) {
if (rotate != null && rotate) {
val handler = Handler()
val start = SystemClock.uptimeMillis()
val startRotation = marker.rotation
val duration: Long = 300
handler.post(object : Runnable {
override fun run() {
val elapsed = SystemClock.uptimeMillis() - start
val t = LinearInterpolator().getInterpolation(elapsed.toFloat() / duration)
val rot = t * toRotation + (1 - t) * startRotation
marker.rotation = if (-rot > 180) rot / 2 else rot
if (t < 1.0) {
handler.postDelayed(this, 16)
}
}
})
}
}
fun bitmapFromVector(context: Context, @DrawableRes icon: Int): BitmapDescriptor {
val background = ContextCompat.getDrawable(context, icon)
background!!.setBounds(0, 0, background.intrinsicWidth, background.intrinsicHeight)
val bitmap = Bitmap.createBitmap(background.intrinsicWidth, background.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
background.draw(canvas)
return BitmapDescriptorFactory.fromBitmap(bitmap)
}
fun moveMarkerSmoothly(marker: Marker, newLatLng: LatLng) : ValueAnimator {
val animator = ValueAnimator.ofFloat(0f, 100f)
val deltaLatitude = doubleArrayOf(newLatLng.latitude - marker.position.latitude)
val deltaLongitude = newLatLng.longitude - marker.position.longitude
val prevStep = floatArrayOf(0f)
animator.duration = 1500
animator.addUpdateListener { animation ->
val deltaStep = (animation.animatedValue as Float - prevStep[0]).toDouble()
prevStep[0] = animation.animatedValue as Float
val latLng = LatLng(marker.position.latitude + deltaLatitude[0] * deltaStep * 1.0 / 100, marker.position.longitude + deltaStep * deltaLongitude * 1.0 / 100)
marker.setPosition(latLng)
}
return animator
}
|
8f303e8eb20a515b6abb56907971b21201a266af
|
[
"Markdown",
"Java",
"Kotlin"
] | 13 |
Kotlin
|
MukeshGreenDeveloper/SmartMarker
|
78b433e5df19488ee0fe7ce8e154886ed7ca6a6e
|
b411ef75cffc21b10e513ed2c5a893a7c0885264
|
refs/heads/master
|
<repo_name>MarshallGarey/CS240-ImageEditor<file_sep>/app/src/main/java/edu/byu/cs/imageeditor/studentCode/Image.java
package edu.byu.cs.imageeditor.studentCode;
/**
* Created by <NAME> on 8/31/2016.
* 2-d array of pixels and methods that operate on an image.
*/
public class Image {
private Pixel[][] pixels;
private int rows;
private int cols;
public Image(int numRows, int numCols) {
pixels = new Pixel[numRows][numCols];
this.rows = numRows;
this.cols = numCols;
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public Pixel getPixelAt(int row, int col) {
if (row < 0 || col < 0) {
System.out.printf("error at getPixelAt(), bad indices: row=%d, col=%d\n", row, col);
System.out.println("Returning pixel[0][0]");
return pixels[0][0];
}
else {
return pixels[row][col];
}
}
public void setPixelAt(int row, int col, int r, int g, int b) {
if (row < 0 || col < 0) {
System.out.printf("error at setPixelAt(), bad indices: row=%d, col=%d\n", row, col);
}
else {
this.pixels[row][col].setRed(r);
this.pixels[row][col].setGreen(g);
this.pixels[row][col].setBlue(b);
}
}
public void newPixelAt(int row, int col, int r, int g, int b) {
if (row < 0 || col < 0) {
System.out.printf("error at setPixelAt(), bad indices: row=%d, col=%d\n", row, col);
}
else {
this.pixels[row][col] = new Pixel(r,g,b);
}
}
// writes image to a string in ppm file format
public String toString_ppm_format() {
StringBuilder s = new StringBuilder("");
s.append("P3\n");
s.append(String.format("%d %d\n", this.cols, this.rows));
s.append("255\n");
for (int row_i = 0; row_i < this.rows; row_i++) {
for (int col_i = 0; col_i < this.cols; col_i++) {
s.append(String.format("%d\n%d\n%d\n", this.pixels[row_i][col_i].getRed(),
this.pixels[row_i][col_i].getGreen(), this.pixels[row_i][col_i].getBlue()));
}
}
return s.toString();
}
// invert
public String invertImage() {
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
this.pixels[i][j].invertPixel();
}
}
return this.toString_ppm_format();
}
// grayscale
public String grayscaleImage() {
for (int i = 0; i < this.rows; i++) {
for (int j = 0; j < this.cols; j++) {
this.pixels[i][j].grayscalePixel();
}
}
return this.toString_ppm_format();
}
// emboss
public String embossImage() {
int maxDifference = 0;
int newValue = 0;
int rDiff, gDiff, bDiff;
for (int row_i = this.rows - 1; row_i >= 0; row_i--) {
for (int col_i = this.cols - 1; col_i >= 0; col_i--) {
if ((row_i - 1 < 0) || (col_i - 1 < 0)) {
// set border pixel rgb to 128
this.pixels[row_i][col_i].setRed(128);
this.pixels[row_i][col_i].setGreen(128);
this.pixels[row_i][col_i].setBlue(128);
}
else {
// get max difference of current pixel rgb and ulh pixel rgb,
// giving red highest priority (if abs(diffs) are same), then green, then blue
// add 128, but limit this value to between 0 and 255,
// and then set pixel value to this value
rDiff = this.pixels[row_i][col_i].getRed() -
this.pixels[row_i-1][col_i-1].getRed();
gDiff = this.pixels[row_i][col_i].getGreen() -
this.pixels[row_i-1][col_i-1].getGreen();
bDiff = this.pixels[row_i][col_i].getBlue() -
this.pixels[row_i-1][col_i-1].getBlue();
// get max difference:
if (Math.abs(rDiff) >= Math.abs(gDiff)) {
if ( Math.abs(rDiff) >= Math.abs(bDiff)) {
maxDifference = rDiff;
}
else {
maxDifference = bDiff;
}
}
else {
if (Math.abs(gDiff) >= Math.abs(bDiff)) {
maxDifference = gDiff;
}
else {
maxDifference = bDiff;
}
}
// get new value
newValue = 128 + maxDifference;
if (newValue < 0) {
newValue = 0;
}
else if (newValue > 255) {
newValue = 255;
}
// set new value
this.pixels[row_i][col_i].setRed(newValue);
this.pixels[row_i][col_i].setGreen(newValue);
this.pixels[row_i][col_i].setBlue(newValue);
} // end if-else
} // end for (each column)
} // end for (each row)
return this.toString_ppm_format();
}
// motionblur
public String motionblurImage(int numPixels, Image origImage) {
// Make sure to not accept invalid blur length due to keyboard monkeys
if (numPixels <= 0) {
return this.toString_ppm_format();
}
int r, g, b;
int numPixelsAveraged = 0;
for (int row_i = this.rows - 1; row_i >= 0; row_i--) {
for (int col_i = this.cols - 1; col_i >= 0; col_i--) {
// average the colors
r = g = b = 0;
numPixelsAveraged = 0;
for (int i = 0; i < numPixels; i++) {
if ((col_i + i) < this.cols) {
// pixel in bounds, add this to total value.
numPixelsAveraged++;
r += origImage.pixels[row_i][col_i+i].getRed();
g += origImage.pixels[row_i][col_i+i].getGreen();
b += origImage.pixels[row_i][col_i+i].getBlue();
}
} // end for
// average colors: divide by number of pixels added
r /= numPixelsAveraged;
g /= numPixelsAveraged;
b /= numPixelsAveraged;
// set pixel
this.setPixelAt(row_i, col_i, r, g, b);
} // end for (each col)
} // end for (each row)
return this.toString_ppm_format();
}
}
|
ccac210f629e7bb6d63d5da3ff2f5eeb9b4bd97d
|
[
"Java"
] | 1 |
Java
|
MarshallGarey/CS240-ImageEditor
|
85371084b6358c4d67b9bc55622eacfd0a547917
|
bc47992a1637b91b1a6cd602d0948a661b9b3a3c
|
refs/heads/master
|
<file_sep>package convert
import "strconv"
func Int64ToString(val int64) string {
return strconv.FormatInt(val, 10)
}
func Int2String(val int) string {
return strconv.Itoa(val)
}
func String2Int(str string) int {
if val, err := strconv.Atoi(str); err == nil {
return val
}
return 0
}
func String2Int64(str string) int64 {
if val, err := strconv.ParseInt(str, 10, 64); err == nil {
return val
}
return 0
}
<file_sep>package convert
import (
"testing"
)
func TestString2Int(t *testing.T) {
cases := []struct {
in string
want int
}{
{
"123",
123,
},
{
"12Hello",
0,
},
{
"Hello",
0,
},
}
for _, ca := range cases {
got := String2Int(ca.in)
if got != ca.want {
t.Errorf("String2Int(%q) == %d, want %d", ca.in, got, ca.want)
}
}
}
func TestString2Int64(t *testing.T) {
cases := []struct {
in string
want int64
}{
{
"123",
123,
},
{
"12Hello",
0,
},
{
"Hello",
0,
},
}
for _, ca := range cases {
got := String2Int64(ca.in)
if got != ca.want {
t.Errorf("String2Int64(%q) == %d, want %d", ca.in, got, ca.want)
}
}
}
func TestInt2String(t *testing.T) {
cases := []struct {
in int
want string
}{
{
123,
"123",
},
{
0,
"0",
},
{
-1,
"-1",
},
}
for _, ca := range cases {
got := Int2String(ca.in)
if got != ca.want {
t.Errorf("Int2String(%d) == %q, want %q", ca.in, got, ca.want)
}
}
}
func TestInt64ToString(t *testing.T) {
cases := []struct {
in int64
want string
}{
{
123,
"123",
},
{
0,
"0",
},
{
-1,
"-1",
},
}
for _, ca := range cases {
got := Int64ToString(ca.in)
if got != ca.want {
t.Errorf("Int2String(%d) == %q, want %q", ca.in, got, ca.want)
}
}
}
<file_sep># cockroach
go base package
|
8b29d45d9cca2ad34375dad9c4ef1ec36ceaccc2
|
[
"Markdown",
"Go"
] | 3 |
Go
|
jhq0113/cockroach
|
dfa6b92c263a4dcff279530db13a2d53d3611606
|
951e3ef548398be479b2d2fdf043a6b8f262aa31
|
refs/heads/master
|
<repo_name>sdl1/antichess<file_sep>/antichess/test/test_moves.py
import unittest
from antichess.Board import Board
from antichess import Pieces
from antichess.Rules import Suicide
# TODO large scale move generation
class MovesGenerationTest(unittest.TestCase):
def setUp(self):
self.board = Board()
self.rules = Suicide()
def assertValidMoves(self, board, moves, colour, enforceCaptures=True):
self.board.displayAsText()
v, _ = self.rules.getAllValidMoves(self.board, colour, enforceCaptures)
v_str = map(str, v)
moves_str = map(str, moves)
print "Generated: ", v_str
print "Asserted: ", moves_str
self.assertTrue(set(v_str)==set(moves_str))
def testPawnMoves(self):
self.board.clear()
self.board.setPiece("d2", Pieces.Pawn(0));
validMoves = ["d2d3", "d2d4"];
self.assertValidMoves(self.board, validMoves, 0)
self.board.clear()
self.board.setPiece("a2", Pieces.Pawn(0));
self.board.setPiece("h3", Pieces.Rook(1));
validMoves = ["a2a3", "a2a4"];
self.assertValidMoves(self.board, validMoves, 0)
self.board.setPiece("h1", Pieces.Rook(0));
validMoves = ["h1h3"]
self.assertValidMoves(self.board, validMoves, 0)
def testPrinting(self):
# Test move generation in non-trivial board
# The print statement catches some bugs due
# to out of bounds indices
self.board.clear()
self.board.setPiece("a1", Pieces.Rook(0));
self.board.setPiece("a2", Pieces.Pawn(0));
self.board.setPiece("g1", Pieces.Knight(0));
self.board.setPiece("h1", Pieces.Rook(0));
self.board.setPiece("e2", Pieces.Pawn(0));
self.board.setPiece("f2", Pieces.King(0));
self.board.setPiece("h3", Pieces.Pawn(0));
self.board.setPiece("a3", Pieces.Pawn(1));
self.board.setPiece("g6", Pieces.Pawn(1));
self.board.setPiece("a7", Pieces.Pawn(1));
self.board.setPiece("e7", Pieces.Pawn(1));
self.board.setPiece("f7", Pieces.Pawn(1));
self.board.setPiece("h7", Pieces.Pawn(1));
self.board.setPiece("d7", Pieces.King(1));
self.board.setPiece("h8", Pieces.Rook(1));
self.board.displayAsText()
v, _ = self.rules.getAllValidMoves(self.board, 0, enforceCaptures=True)
for move in v:
print move
self.assertTrue(len(v)>1)
def testPromotionMoves(self):
# Promotion moves
self.board.clear()
self.board.setPiece("c7", Pieces.Pawn(0));
self.board.setPiece("d8", Pieces.Knight(1));
self.board.setPiece("f7", Pieces.Pawn(0));
self.board.setPiece("a2", Pieces.Pawn(1));
self.board.setPiece("b1", Pieces.Knight(0));
self.board.setPiece("f2", Pieces.Pawn(1));
# Without enforcing captures
validMoves = ["c7c8R", "c7c8N", "c7c8B", "c7c8Q", "c7c8K", \
"c7d8R", "c7d8N", "c7d8B", "c7d8Q", "c7d8K", \
"f7f8R", "f7f8N", "f7f8B", "f7f8Q", "f7f8K", \
"b1a3", "b1c3", "b1d2"]
self.assertValidMoves(self.board, validMoves, 0, enforceCaptures=False)
validMoves = ["a2a1R", "a2a1N", "a2a1B", "a2a1Q", "a2a1K", \
"a2b1R", "a2b1N", "a2b1B", "a2b1Q", "a2b1K", \
"f2f1R", "f2f1N", "f2f1B", "f2f1Q", "f2f1K", \
"d8b7", "d8c6", "d8e6", "d8f7"]
self.assertValidMoves(self.board, validMoves, 1, enforceCaptures=False)
# With enforcing captures
validMoves = ["c7d8R", "c7d8N", "c7d8B", "c7d8Q", "c7d8K"]
self.assertValidMoves(self.board, validMoves, 0)
validMoves = ["a2b1R", "a2b1N", "a2b1B", "a2b1Q", "a2b1K", \
"d8f7"]
self.assertValidMoves(self.board, validMoves, 1)
def testRookMoves(self):
self.board.clear()
self.board.setPiece("c2", Pieces.Rook(0))
validMoves = ["c2a2", "c2b2", "c2d2", "c2e2", "c2f2", "c2g2", "c2h2", \
"c2c1", "c2c3", "c2c4", "c2c5", "c2c6", "c2c7", "c2c8"]
self.assertValidMoves(self.board, validMoves, 0)
self.board.clear()
self.board.setPiece("c2", Pieces.Rook(1))
self.assertValidMoves(self.board, validMoves, 1)
def testKnightMoves(self):
self.board.clear()
self.board.setPiece("d4", Pieces.Knight(0))
validMoves = ["d4c2", "d4e2", "d4b3", "d4b5", "d4c6", "d4e6", "d4f5", "d4f3"]
self.assertValidMoves(self.board, validMoves, 0)
self.board.clear()
self.board.setPiece("d4", Pieces.Knight(1))
self.assertValidMoves(self.board, validMoves, 1)
def testBishopMoves(self):
self.board.clear()
self.board.setPiece("f3", Pieces.Bishop(0))
validMoves = ["f3d1", "f3e2", "f3g4", "f3h5", "f3g2", "f3h1", "f3e4", "f3d5", "f3c6", "f3b7", "f3a8"]
self.assertValidMoves(self.board, validMoves, 0)
self.board.clear()
self.board.setPiece("f3", Pieces.Bishop(1))
self.assertValidMoves(self.board, validMoves, 1)
def testKingMoves(self):
self.board.clear()
self.board.setPiece("a1", Pieces.King(0))
self.board.setPiece("e5", Pieces.King(0))
validMoves = ["a1a2", "a1b2", "a1b1", \
"e5e4", "e5e6", "e5d5", "e5f5", "e5d4", "e5f6", "e5f4", "e5d6"]
self.assertValidMoves(self.board, validMoves, 0)
self.board.clear()
self.board.setPiece("a1", Pieces.King(1))
self.board.setPiece("e5", Pieces.King(1))
self.assertValidMoves(self.board, validMoves, 1)
def testQueenMoves(self):
self.board.clear()
self.board.setPiece("f4", Pieces.Queen(0))
validMoves = ["f4a4", "f4b4", "f4c4", "f4d4", "f4e4", "f4g4", "f4h4", \
"f4f1", "f4f2", "f4f3", "f4f5", "f4f6", "f4f7", "f4f8", \
"f4g5", "f4h6", \
"f4e3", "f4d2", "f4c1", \
"f4g3", "f4h2", \
"f4e5", "f4d6", "f4c7", "f4b8"]
self.assertValidMoves(self.board, validMoves, 0)
self.board.clear()
self.board.setPiece("f4", Pieces.Queen(1))
self.assertValidMoves(self.board, validMoves, 1)
if __name__=="__main__":
unittest.main()
<file_sep>/antichess/Player.py
import Board
import Rules
import Move
import Pieces
import random
import sys
import time
class Player:
colour = None
rules = None
name = None
def __init__(self, col, rules=Rules.Suicide()):
self.colour = col
self.rules = rules
class HumanPlayer(Player):
name = "Human"
def getMove(self, board, maxTime):
promptText = "Enter move: "
moves, iscaptures = self.rules.getAllValidMoves(board, self.colour)
# Is there a single forced capture?
if len(moves)==1 and iscaptures[0]:
forcedCapture = True
promptText = "Enter move [ENTER for " + str(moves[0]) + "]: "
else:
forcedCapture = False
metacommand = True
while metacommand:
m = raw_input(promptText)
# Single forced capture
if m=="" and forcedCapture==True:
return moves[0]
# Re-display board
if m=="b":
board.display()
continue
# Retract (undo) last move
if m=="u" or m=="r":
return Rules.Move.RETRACT
# Show list of valid moves
if m=="v":
for i,move in enumerate(moves):
if iscaptures[i]:
print move.__str__() + " [CAPTURE]"
else:
print move
continue
if m=="q":
return Rules.Move.RESIGN
metacommand = False
# If we've got this far, input should be a move
try:
return Move.Move.fromNotation(m, self.colour)
except Exception as e:
print "Couldn't parse input."
return Move.NONE
class PassingPlayer(Player):
name = "Passing"
def getMove(self, board, maxTime):
return Move.PASS
class RandomPlayer(Player):
name = "Random"
def __init__(self, col, rules=Rules.Suicide()):
Player.__init__(self, col, rules)
random.seed()
def getMove(self, board, maxTime):
validMoves, isCapture = self.rules.getAllValidMoves(board, self.colour)
if len(validMoves)==0:
return Move.PASS
#[fr, to] = validMoves[ random.randint(0, len(validMoves)-1) ]
#return [8*fr[0] + fr[1], 8*to[0] + to[1]]
return validMoves[ random.randint(0, len(validMoves)-1) ]
class AIPlayer(Player):
name = "AI"
maxDepth = 0
INFINITY = 999999
def __init__(self, col, maxDepth=1, verbose=False, rules=Rules.Suicide()):
Player.__init__(self, col, rules)
self.maxDepth = maxDepth
self.verbose = verbose
random.seed()
def getMove(self, board, maxTime):
startTime = time.time()
# Be conservative with time
# TODO enforce this exactly
maxTime = maxTime * 0.95
validMoves, isCapture = self.rules.getAllValidMoves(board, self.colour)
random.shuffle(validMoves)
#NOTE: isCapture is now out of order
if len(validMoves)==0:
return Move.PASS
if len(validMoves)==1:
return validMoves[0]
overallBestScore, overallBestMove = -self.INFINITY, validMoves[0]
for depth in range(0,self.maxDepth):
if self.verbose:
print "At depth ", depth
else:
sys.stdout.write(".")
bestScore, bestMove = self.getMoveToDepth(board, maxTime, startTime, validMoves, depth)
# Less than or equals means deeper moves at same score will supersede
if bestScore>=overallBestScore:
overallBestMove = bestMove
overallBestScore = bestScore
if self.verbose: print "Changing best move to ", overallBestMove
if time.time()-startTime > maxTime:
break
# TODO give more weight to deeper evaluations
# TODO overwrite shallow scores with deeper scores - otherwise might make a move which looks good at shallow depth but not at deeper depth
return overallBestMove
def getMoveToDepth(self, board, maxTime, startTime, validMoves, depth):
bestScore, bestMove = -self.INFINITY, validMoves[0]
counter=0
for move in validMoves:
if self.verbose:
print move.__str__()+" ",
done = counter/float(len(validMoves)) * 100
sys.stdout.write( "%d%% " % done )
sys.stdout.flush()
counter += 1
#fr = move[0]
#to = move[1]
#board.makeMove( [8*fr[0]+fr[1], 8*to[0]+to[1]] )
board.makeMove( move )
#score = -self.minimax(board, self.maxDepth, 1-self.colour) #works
score = -self.alphabeta(board, depth, -self.INFINITY, self.INFINITY, 1-self.colour, startTime, maxTime)
board.retractMove()
# Check time - if overtime, ignore this move
elapsedTime = time.time() - startTime
if elapsedTime>maxTime:
if self.verbose: print "Ran out of time."
break
if self.verbose: print "score=%d" % score
sys.stdout.flush()
if score > bestScore:
bestScore, bestMove = score, move
if bestScore==self.INFINITY:
break
if self.verbose: print "Best score is",bestScore,"for move",bestMove
#fr = bestMove[0]
#to = bestMove[1]
#return [ 8*fr[0] + fr[1], 8*to[0]+to[1] ]
return bestScore, bestMove
def heuristic(self, board, colour, validMoves, isCapture):
n_me = board.getNumPieces(colour)
n_him = board.getNumPieces(1-colour)
# Win from material
if n_me==0:
return +self.INFINITY
if n_him==0:
return -self.INFINITY
# Win from no moves
if len(validMoves)==0:
return +self.INFINITY
# Prefer fewer pieces
material_score = n_him - n_me
# Prefer either no captures or lots of capture choices
# TODO just prefer more available moves in general?
num_captures = sum(isCapture)
if num_captures==0:
freedom_score = 3
elif num_captures==1:
freedom_score = -3
else:
freedom_score = 0
return material_score + freedom_score
def minimax(self, board, depth, colour):
validMoves, isCapture = self.rules.getAllValidMoves(board, colour)
if len(validMoves)==0 or depth <= 0:
return self.heuristic(board, colour)
a = -self.INFINITY
for move in validMoves:
#fr = move[0]
#to = move[1]
#board.makeMove( [8*fr[0]+fr[1], 8*to[0]+to[1]] )
board.makeMove( move )
a = max(a, -self.minimax(board, depth-1, 1-colour))
board.retractMove()
def alphabeta(self, board, depth, a, b, colour, startTime, maxTime):
validMoves, isCapture = self.rules.getAllValidMoves(board, colour)
# if there are fewer than N captures, keep looking...
#if 0 < sum(isCapture) < 4:
# #print "---Deepening search [", board.getLastMove(), "]",
# #sys.stdout.flush()
# depth += 1
if len(validMoves)==0 or depth <= 0:
return self.heuristic(board, colour, validMoves, isCapture)
for move in validMoves:
#print " "*(self.maxDepth - depth), move
# fr = move[0]
# to = move[1]
# board.makeMove( [8*fr[0]+fr[1], 8*to[0]+to[1]] )
board.makeMove( move )
a = max(a, -self.alphabeta(board, depth-1, -b, -a, 1-colour, startTime, maxTime))
board.retractMove()
if b <= a:
break
# Check time
elapsedTime = time.time() - startTime
if elapsedTime>maxTime:
return 0 # Will be ignored
return a
<file_sep>/antichess/test/perft.py
from .. import Rules
from .. import Board
# python -m antichess.test.perft
rules = Rules.Suicide()
def perft(board, depth, colour):
nodes = 0
if depth==0:
return 1
moves, _ = rules.getAllValidMoves(board, colour, enforceCaptures=False)
for move in moves:
board.makeMove(move)
nodes = nodes + perft(board, depth-1, 1-colour)
board.retractMove()
return nodes
if __name__=="__main__":
board = Board.Board()
print perft(board, 3, 0)
<file_sep>/antichess.py
#!/usr/bin/python
from antichess.Game import playGame
playGame()
<file_sep>/antichess/Game.py
#!/usr/bin/python
#from rules import suicide
import Board
import Player
import Rules
import Move
from optparse import OptionParser
#import argparse # python 2.7
import time
playerNames = ["White", "Black"]
def playGame():
parser = OptionParser()
parser.add_option("-d", "--depth", type="int", dest="AIdepth", default=99,
help="set maximum AI search depth", metavar="MAXDEPTH")
parser.add_option("-w", "--white", dest="white", default="human",
help="set white player", metavar="PLAYER")
parser.add_option("-b", "--black", dest="black", default="ai",
help="set black player", metavar="PLAYER")
parser.add_option("-t", "--time", type="int", dest="maxTime", default=5,
help="set maximum AI thinking time", metavar="MAXTIME")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False,
help="set verbose AI")
parser.add_option("-s", "--simple", action="store_true", dest="textmode", default=False,
help="use simple board display")
parser.add_option("--singleturn", action="store_true", dest="singleturn", default=False,
help="(debug) play a single turn only")
(options, args) = parser.parse_args()
b = Board.Board(textmode = options.textmode)
AIdepth = options.AIdepth
maxTime = options.maxTime
playertype = [options.white, options.black]
players = []
for i in [0,1]:
p = playertype[i]
if p=="human":
players.append( Player.HumanPlayer(i) )
elif p=="ai":
players.append( Player.AIPlayer(i, AIdepth, options.verbose) )
elif p=="random":
players.append( Player.RandomPlayer(i) )
elif p=="pass":
players.append( Player.PassingPlayer(i) )
else:
#TODO exception
print "Error: unknown player type:", p
exit()
print "%s is %s." % (playerNames[i], players[i].name),
if p=="ai":
print "Depth is %s, max thinking time is %ds." % (AIdepth, maxTime)
print ""
r = Rules.Suicide()
b.display()
print ""
WIN = -1
while True:
for col in [0, 1]:
# First check for win
numpieces = b.getNumPieces(col)
valid, capture = r.getAllValidMoves(b, col)
if numpieces==0 or len(valid)==0:
WIN = col
break
madeValidMove = False;
startTime = time.time()
while not madeValidMove:
print playerNames[col] + "'s turn"
m = players[col].getMove(b, maxTime)
# NoneMove -> try again
if m==Move.NONE:
continue
# If retract, we pop two moves and try again
if m==Move.RETRACT:
lastMoveByThisPlayer = b.getSecondLastMove()
if b.retractTurn():
print playerNames[col], "retracts move", lastMoveByThisPlayer
else:
print "Unable to retract."
print ""
b.display()
print ""
continue
try:
r.validate(m, b, col)
madeValidMove = True
except Rules.RulesViolation as e:
madeValidMove = False
print "Invalid move: " + e.value
print "Got valid move in ", time.time()-startTime, "s"
if m==Rules.Move.RESIGN:
print playerNames[col] + " resigns. "
WIN = 1-col
break
b.makeMove(m)
print ""
b.display()
print playerNames[col] + " moved", m
print ""
if options.singleturn:
exit()
if not WIN==-1:
print playerNames[WIN] + " wins!"
exit()
<file_sep>/antichess/Board.py
import Pieces
import Rules
import Move
import sys
class Board:
pieces = []
WHITE = 0
BLACK = 1
movesMade = []
doublePawnPush = []
madeEnPassant = []
def __init__(self, textmode=False):
self.textmode = textmode
self.pieces.append(Pieces.Rook(self.BLACK))
self.pieces.append(Pieces.Knight(self.BLACK))
self.pieces.append(Pieces.Bishop(self.BLACK))
self.pieces.append(Pieces.Queen(self.BLACK))
self.pieces.append(Pieces.King(self.BLACK))
self.pieces.append(Pieces.Bishop(self.BLACK))
self.pieces.append(Pieces.Knight(self.BLACK))
self.pieces.append(Pieces.Rook(self.BLACK))
for i in range(9,17):
self.pieces.append(Pieces.Pawn(self.BLACK))
for i in range(17, 65-16):
self.pieces.append(None)
for i in range(65-16,65-8):
self.pieces.append(Pieces.Pawn(self.WHITE))
self.pieces.append(Pieces.Rook(self.WHITE))
self.pieces.append(Pieces.Knight(self.WHITE))
self.pieces.append(Pieces.Bishop(self.WHITE))
self.pieces.append(Pieces.Queen(self.WHITE))
self.pieces.append(Pieces.King(self.WHITE))
self.pieces.append(Pieces.Bishop(self.WHITE))
self.pieces.append(Pieces.Knight(self.WHITE))
self.pieces.append(Pieces.Rook(self.WHITE))
def clear(self):
"""Remove all pieces and moves."""
for i in range(0,64):
self.pieces[i] = None
self.movesMade = []
self.doublePawnPush = []
self.madeEnPassant = []
def stringToSquare(self, squareString):
# E.g. squareString = e2
conv = dict(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7)
row = 7 - (int(squareString[1]) - 1)
col = conv[squareString[0]]
return row*8 + col
def setPiece(self, squareString, piece):
square = self.stringToSquare(squareString)
self.pieces[square] = piece
def display(self):
if self.textmode:
self.displayAsText()
else:
self.displayAsUnicode()
def displayAsText(self):
lastMove = self.getLastMove()
print "--a-b-c-d-e-f-g-h--"
for row in range(8):
sys.stdout.write(str(9 - (row+1)))
sys.stdout.write("|")
for col in range(8):
idx = 8*row + col
p = self.pieces[idx]
if (row==lastMove[0][0] and col==lastMove[0][1]) or (row==lastMove[1][0] and col==lastMove[1][1]):
if p==None:
sys.stdout.write(Pieces.bcolours.PIECECOLOURALT[ self.getLastMovedPiece().colour ] + "." + Pieces.bcolours.ENDC)
else:
p.displayAsText(alt=True)
else:
if p==None:
sys.stdout.write(" ")
else:
p.displayAsText()
sys.stdout.write("|")
print 9-(row+1)
print "--a-b-c-d-e-f-g-h--"
def displayAsUnicode(self):
lastMove = self.getLastMove()
print " a b c d e f g h"
for row in range(8):
sys.stdout.write(str(9 - (row+1)))
#sys.stdout.write("|")
sys.stdout.write(" ")
for col in range(8):
idx = 8*row + col
p = self.pieces[idx]
squarecolour = (col + row)%2
if (row==lastMove[0][0] and col==lastMove[0][1]) or (row==lastMove[1][0] and col==lastMove[1][1]):
if p==None:
sys.stdout.write(Pieces.bcolours.PIECECOLOURALT[ self.getLastMovedPiece().colour ] + Pieces.bcolours.BGCOLOURALT[squarecolour] + ". " + Pieces.bcolours.ENDC)
else:
p.displayAsUnicode(squarecolour=squarecolour, alt=True)
else:
if p==None:
sys.stdout.write(Pieces.bcolours.BGCOLOUR[squarecolour] + " " + Pieces.bcolours.ENDC)
else:
p.displayAsUnicode(squarecolour=squarecolour)
sys.stdout.write(" ")
print 9-(row+1)
print " a b c d e f g h"
def makeMove(self, move):
# Allow null moves (passes)
if move==Move.PASS:
return
# Retractions and resignations should not be made here
if move==Move.RETRACT or move==Move.RESIGN:
print "Move error."
exit()
fr, to = move.unpack()
self.movesMade.append( [move, self.pieces[to]] )
# Record double pawn pushes for en passant
if isinstance(self.pieces[fr], Pieces.Pawn) and abs(move.to[0]-move.fr[0])==2:
self.doublePawnPush.append(True)
else:
self.doublePawnPush.append(False)
if move.isEnpassant(self):
self.madeEnPassant.append(True)
# The captured pawn will be in same column, but one row behind
# We don't store it explicitly.
# This is ok because if we want to retract the move, we know it's
# an en passant and therefore which piece to replace and where.
capturedPieceCol = move.to[1]
# Offset is -1 for black, +1 for white
if self.pieces[fr].colour==self.WHITE:
offset = +1
else:
offset = -1
capturedPieceRow = move.to[0] + offset
self.pieces[ capturedPieceRow*8 + capturedPieceCol ] = None
else:
self.madeEnPassant.append(False)
self.pieces[ to ] = self.pieces[ fr ]
self.pieces[ fr ] = None
if isinstance(move, Move.PromotionMove):
self.pieces[ to ] = move.promoteTo
def retractMove(self):
if len(self.movesMade)==0:
return
[move, piece] = self.movesMade.pop()
fr, to = move.unpack()
self.pieces[ fr ] = self.pieces[ to ]
# Put captured piece back in the correct place in case of en passant
if self.madeEnPassant[-1]:
capturedPieceCol = move.to[1]
# Offset is -1 for black, +1 for white
if self.pieces[fr].colour==self.WHITE:
offset = +1
else:
offset = -1
capturedPieceRow = move.to[0] + offset
self.pieces[ capturedPieceRow*8 + capturedPieceCol ] = Pieces.Pawn( 1-self.pieces[fr].colour )
else:
self.pieces[ to ] = piece
if isinstance(move, Move.PromotionMove):
self.pieces[ fr ] = Pieces.Pawn( self.pieces[fr].colour )
self.doublePawnPush.pop()
self.madeEnPassant.pop()
def retractTurn(self):
# Try to pop two moves, to get back to the same player
if len(self.movesMade)<2:
return False
self.retractMove()
self.retractMove()
return True
def getLastMove(self):
if len(self.movesMade)==0:
return Move.NONE
return self.movesMade[-1][0]
def getSecondLastMove(self):
if len(self.movesMade)<2:
return Move.NONE
return self.movesMade[-2][0]
def getLastMovedPiece(self):
if len(self.movesMade)==0:
return None
fr, to = self.getLastMove().unpack()
return self.pieces[to]
def hasCaptures(self, colour):
# Important that we don't enforce captures here, otherwise enter infinite loop
_, isCapture = Rules.Suicide().getAllValidMoves(self, colour, enforceCaptures=False)
return sum(isCapture)>0
def hasPieceOn(self, row, col):
return not (self.pieces[row*8+col] == None)
def getPieceOn(self, m):
row = m[0]
col = m[1]
return self.pieces[row*8+col]
def hasClearPath(self, fr, to):
def sign(x):
if x > 0:
return 1
if x < 0:
return -1
return 0
# check for bishop move first
if abs(fr[0]-to[0]) == abs(fr[1]-to[1]):
if fr[1]>to[1]:
fr, to = to, fr
s = [sign(to[0] - fr[0]), sign(to[1]-fr[1])]
for inc in range(1, to[1]-fr[1]):
if self.hasPieceOn(fr[0]+s[0]*inc, fr[1]+s[1]*inc):
return False
return True
# Now straight-line moves
if fr[0]==to[0]:
if fr[1]>to[1]:
fr, to = to, fr
for col in range(fr[1]+1,to[1]):
if self.hasPieceOn(fr[0], col):
return False
if fr[1]==to[1]:
if fr[0]>to[0]:
fr, to = to, fr
for row in range(fr[0]+1,to[0]):
if self.hasPieceOn(row, fr[1]):
return False
# Anything else, just return True
return True
def getAllPieces(self, colour):
pieces = []
for row in range(0, 8):
for col in range(0, 8):
if self.hasPieceOn(row, col):
p = self.getPieceOn([row,col])
if p.colour==colour:
pieces.append( [row,col] )
return pieces
def getNumPieces(self, colour):
return len( self.getAllPieces(colour) )
<file_sep>/README.md
# antichess
[](https://travis-ci.org/sdl1/antichess)
Terminal implementation of suicide chess / anti-chess, with an AI.
<img src="img/antichess.png" alt="antichess" width="200"/>
## Overview
antichess is a terminal implementation of suicide chess - also called antichess or losing chess - which is a very fun and deep variation of standard chess. The objective of the game is to lose all pieces. Rules are the same as for standard chess, except:
* Captures are obligatory. If one or more captures are available, the capturing player may choose.
* There is no check, checkmate or castling. Kings are treated as a normal piece which may be captured.
* A player that is stalemated wins.
* There is no fifty-move rule or threefold repetition rule.
The first player to lose all their pieces wins. If a player cannot move on their turn, they win.
## Usage
Start a new game as white against the AI, giving it 10 seconds per move thinking time (default is 5):
```shell
./antichess.py -t 10
```
For other command-line options:
```shell
./antichess.py -h
```
Moves are input by specifying the origin and destination squares, e.g.
```shell
e2e4
```
For promotions, specify the desired piece, e.g.
```shell
e7e8Q
```
You can also:
* See valid moves with `v`
* Undo (retract) with `u` or `r`
* Print the board again with `b`
* Resign with `q`
<file_sep>/antichess/test/test_enpassant.py
import unittest
from antichess.Board import Board
from antichess import Pieces
from antichess.Rules import Suicide
from antichess.Move import Move
class EnPassantTest(unittest.TestCase):
def setUp(self):
self.board = Board()
self.rules = Suicide()
def assertValidMoves(self, board, moves, colour, enforceCaptures=True):
self.board.displayAsText()
v, _ = self.rules.getAllValidMoves(self.board, colour, enforceCaptures)
v_str = map(str, v)
moves_str = map(str, moves)
print "Generated: ", v_str
print "Asserted: ", moves_str
self.assertTrue(set(v_str)==set(moves_str))
def testHasCaptures(self):
self.board.clear()
self.board.setPiece("a5", Pieces.Pawn(0))
self.board.setPiece("b7", Pieces.Pawn(1))
self.assertFalse(self.board.hasCaptures(0))
self.board.makeMove(Move.fromNotation("b7b5", 1))
self.assertTrue(self.board.hasCaptures(0))
def testEnPassantCapture(self):
self.board.clear()
# Before en passant
self.board.setPiece("a5", Pieces.Pawn(0))
self.board.setPiece("b7", Pieces.Pawn(1))
self.board.makeMove(Move.fromNotation("b7b5", 1))
self.assertValidMoves(self.board, ["a5b6"], 0)
# Check black pawn on b5
self.assertTrue(isinstance(self.board.pieces[25], Pieces.Pawn))
self.board.makeMove(Move.fromNotation("a5b6", 0))
# Check pawn is gone
self.board.displayAsText()
self.assertTrue(self.board.pieces[25]==None)
self.assertValidMoves(self.board, ["b6b7"], 0)
self.assertValidMoves(self.board, [], 1)
# Check undo
print map(str,self.board.movesMade[-1])
print self.board.getLastMovedPiece().colour
self.board.retractMove()
print map(str,self.board.movesMade[-1])
print self.board.getLastMovedPiece().colour
self.board.displayAsText()
self.assertTrue(isinstance(self.board.pieces[25], Pieces.Pawn))
self.assertEquals(self.board.pieces[25].colour, 1)
def testEnPassantWhite(self):
self.board.clear()
# Before en passant
self.board.setPiece("a5", Pieces.Pawn(0))
self.board.setPiece("b7", Pieces.Pawn(1))
self.board.setPiece("h3", Pieces.Pawn(0))
self.assertValidMoves(self.board, ["a5a6", "h3h4"], 0)
# En passant opportunity
self.board.makeMove(Move.fromNotation("b7b5", 1))
self.assertValidMoves(self.board, ["a5b6"], 0)
self.assertValidMoves(self.board, ["a5a6", "a5b6", "h3h4"], 0, enforceCaptures=False)
# Opportunity passed
self.board.makeMove(Move.fromNotation("h3h4", 0))
self.assertValidMoves(self.board, ["a5a6", "h4h5"], 0)
def testEnPassantBlack(self):
self.board.clear()
# Before en passant
self.board.setPiece("a4", Pieces.Pawn(1))
self.board.setPiece("b2", Pieces.Pawn(0))
self.board.setPiece("h4", Pieces.Pawn(1))
self.assertValidMoves(self.board, ["a4a3", "h4h3"], 1)
# En passant opportunity
self.board.makeMove(Move.fromNotation("b2b4", 0))
self.assertValidMoves(self.board, ["a4b3"], 1)
self.assertValidMoves(self.board, ["a4a3", "a4b3", "h4h3"], 1, enforceCaptures=False)
# Opportunity passed
self.board.makeMove(Move.fromNotation("h4h3", 1))
self.assertValidMoves(self.board, ["a4a3", "h3h2"], 1)
def testEnPassantRegistersAsCapture(self):
self.board.clear()
# Before en passant
self.board.setPiece("a4", Pieces.Pawn(1))
self.board.setPiece("b2", Pieces.Pawn(0))
self.board.setPiece("h4", Pieces.Pawn(1))
self.assertValidMoves(self.board, ["a4a3", "h4h3"], 1)
# En passant opportunity
self.board.makeMove(Move.fromNotation("b2b4", 0))
self.assertValidMoves(self.board, ["a4b3"], 1)
self.assertValidMoves(self.board, ["a4a3", "a4b3", "h4h3"], 1, enforceCaptures=False)
# Check it registers as a capture opportunity
_, iscap = self.rules.getAllValidMoves(self.board, 1, enforceCaptures=True)
self.assertEqual(len(iscap), 1)
self.assertEqual(iscap[0], 1)
# Check we have captures
self.assertTrue(self.board.hasCaptures(1))
# Opportunity passed
self.board.makeMove(Move.fromNotation("h4h3", 1))
_, iscap = self.rules.getAllValidMoves(self.board, 1, enforceCaptures=True)
self.assertEqual(len(iscap), 2)
self.assertEqual(sum(iscap), 0)
def testEnPassantWhiteUndo(self):
self.board.clear()
# Before en passant
self.board.setPiece("a5", Pieces.Pawn(0))
self.board.setPiece("b7", Pieces.Pawn(1))
self.board.setPiece("h3", Pieces.Pawn(0))
self.assertValidMoves(self.board, ["a5a6", "h3h4"], 0)
# En passant opportunity
self.board.makeMove(Move.fromNotation("b7b5", 1))
self.assertValidMoves(self.board, ["a5b6"], 0)
# Opportunity passed
self.board.makeMove(Move.fromNotation("h3h4", 0))
self.assertValidMoves(self.board, ["a5a6", "h4h5"], 0)
# Undo h3h4
self.board.retractMove()
# Opportunity re-appears
self.assertValidMoves(self.board, ["a5b6"], 0, enforceCaptures=True)
self.assertValidMoves(self.board, ["a5a6", "a5b6", "h3h4"], 0, enforceCaptures=False)
# Try lots of undos
self.board.makeMove(Move.fromNotation("h3h4", 0))
self.board.makeMove(Move.fromNotation("h4h5", 0))
self.board.makeMove(Move.fromNotation("b5b4", 1))
self.board.makeMove(Move.fromNotation("h5h6", 0))
self.board.makeMove(Move.fromNotation("b4b3", 1))
self.board.makeMove(Move.fromNotation("h7h8", 0))
self.board.retractMove()
self.board.retractMove()
self.board.retractMove()
self.board.retractMove()
self.board.retractMove()
# Not valid yet...
self.assertValidMoves(self.board, ["a5a6", "h4h5"], 0)
self.board.retractMove()
# Now valid en passant
self.assertValidMoves(self.board, ["a5b6"], 0)
def testDoubleEnpassant(self):
self.board.clear()
self.board.setPiece("c4", Pieces.Pawn(1))
self.board.setPiece("e4", Pieces.Pawn(1))
self.board.setPiece("d2", Pieces.Pawn(0))
self.assertValidMoves(self.board, ["c4c3", "e4e3"], 1)
# Double en passant opportunity
self.board.makeMove(Move.fromNotation("d2d4", 0))
self.assertValidMoves(self.board, ["c4d3", "e4d3"], 1)
self.assertValidMoves(self.board, ["c4c3", "c4d3", "e4e3", "e4d3"], 1, enforceCaptures=False)
# Pass
self.board.makeMove(Move.fromNotation("c4c3", 1))
self.assertValidMoves(self.board, ["c3c2", "e4e3"], 1)
# Undo
self.board.retractMove()
self.assertValidMoves(self.board, ["c4d3", "e4d3"], 1, enforceCaptures=True)
self.assertValidMoves(self.board, ["c4c3", "c4d3", "e4e3", "e4d3"], 1, enforceCaptures=False)
if __name__=="__main__":
unittest.main()
<file_sep>/antichess/Rules.py
import Board
import Pieces
import Move
class RulesViolation(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Suicide():
def validate(self, move, board, col, enforceCaptures=True):
# Allow null moves (passes)
if move==Move.PASS:
return True
# Allow resignation
if move==Move.RESIGN:
return True
# Allow retracting moves
if move==Move.RETRACT:
if len(board.movesMade)==0:
raise RulesViolation("No moves to retract")
print "Retracting move"
return True
# Basic validation - check it's within the board
if move[0][0]<0 or move[0][0]>7 or move[0][1]<0 or move[0][1]>7:
raise RulesViolation("Invalid from square.")
if move[1][0]<0 or move[1][0]>7 or move[1][1]<0 or move[1][1]>7:
raise RulesViolation("Invalid to square.")
fr, to = move.unpack()
# Can't move an empty square or other colour piece
if board.pieces[fr] == None:
raise RulesViolation("Tried to move empty square")
if not board.pieces[fr].colour == col:
raise RulesViolation("Tried to move opponent's piece")
# Can't move onto own piece
if not board.pieces[to] == None:
if board.pieces[to].colour == col:
raise RulesViolation("Tried to move onto own piece")
# If not a knight, must have clear route
frl = [fr/8, fr%8]
tol = [to/8, to%8]
if not isinstance(board.pieces[fr], Pieces.Knight) and not board.hasClearPath(frl, tol):
raise RulesViolation("No clear path between to and from squares")
# Check particular piece movement
if not board.pieces[fr].canMakeMove(board, move):
raise RulesViolation("Piece can't move like that")
# Must make captures if possible
if enforceCaptures:
if board.hasCaptures(col) and (board.pieces[to] == None) and (not move.isEnpassant(board)):
raise RulesViolation("Captures are available")
return True
def getValidMoves(self, board, piece, colour, enforceCaptures=True):
moves = []
fr = piece
# First, we get a (strictly optimistic) list of plausible places this piece could move to,
# ignoring line of sight and promotions.
# This is faster than checking validity of all possible moves.
destList = board.pieces[fr[0]*8+fr[1]].getPlausibleMoves(fr)
for to in destList:
m = Move.Move(fr, to)
try:
self.validate( m, board, colour, enforceCaptures )
moves.append( m )
except RulesViolation as e:
pass
# Now consider promotion moves
promotionPieces = [Pieces.Queen(colour), Pieces.Rook(colour), Pieces.Knight(colour), Pieces.Bishop(colour), Pieces.King(colour)]
if isinstance(board.pieces[fr[0]*8+fr[1]], Pieces.Pawn):
row = fr[0]
if colour==0 and row==1:
for col in [fr[1]-1, fr[1], fr[1]+1]:
to = [0, col]
for pp in promotionPieces:
m = Move.PromotionMove(fr, to, pp)
try:
self.validate( m, board, colour, enforceCaptures )
moves.append( m )
except RulesViolation as e:
pass
elif colour==1 and row==6:
for col in [fr[1]-1, fr[1], fr[1]+1]:
to = [7, col]
for pp in promotionPieces:
m = Move.PromotionMove(fr, to, pp)
try:
self.validate( m, board, colour, enforceCaptures )
moves.append( m )
except RulesViolation as e:
pass
return moves
def getAllValidMoves(self, board, colour, enforceCaptures=True):
validMoves = []
isCapture = []
# All my pieces
pieces = board.getAllPieces(colour)
for p in pieces:
for m in self.getValidMoves(board, p, colour, enforceCaptures):
validMoves.append(m)
fr,to = m.unpack()
capture = (not board.pieces[to] == None) or m.isEnpassant(board)
isCapture.append(capture)
return validMoves, isCapture
<file_sep>/antichess/Pieces.py
import Move
import sys
class bcolours:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[92m'
GREEN_BOLD = '\033[1;92m'
YELLOW = '\033[33m'
BLUE = '\033[94m'
BLUE_BOLD = '\033[1;94m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
CYAN_BOLD = '\033[1;36m'
WHITE = '\033[37m'
WHITE_BOLD = '\033[1;37m'
BG_DARKGRAY = '\033[100m'
BG_DEFAULT = '\033[49m'
ENDC = '\033[0m'
PIECECOLOUR = [GREEN, BLUE]
PIECECOLOURALT = [WHITE, CYAN]
BGCOLOUR = [BG_DEFAULT, BG_DARKGRAY]
BGCOLOURALT = [BG_DEFAULT, BG_DARKGRAY]
class Piece:
colour = None
symbol = None
altsymbol = None
def __init__(self, col, sym, alt=u'\u2656'):
self.colour = col
self.symbol = sym
self.altsymbol = alt
def displayAsText(self, alt=False):
if alt:
print bcolours.PIECECOLOURALT[self.colour] + self.symbol + bcolours.ENDC,
else:
print bcolours.PIECECOLOUR[self.colour] + self.symbol + bcolours.ENDC,
def displayAsUnicode(self, squarecolour=0, alt=False):
if alt:
sys.stdout.write(bcolours.PIECECOLOURALT[self.colour] + bcolours.BGCOLOURALT[squarecolour] + self.altsymbol + " " + bcolours.ENDC)
else:
sys.stdout.write(bcolours.PIECECOLOUR[self.colour] + bcolours.BGCOLOUR[squarecolour] + self.altsymbol + " " + bcolours.ENDC)
#NOTE: canMakeMove ignores whether or not there are pieces in the way
class Pawn(Piece):
def __init__(self, col):
Piece.__init__(self, col, "p", u'\u2659')
def getPlausibleMoves(self, fr):
# Ignoring promotion but including double move
row, col = fr[0], fr[1]
if self.colour==0:
torow = fr[0]-1
moves = [ [torow, col-1], [torow, col], [torow, col+1], [row-2, col] ]
else:
torow = fr[0]+1
moves = [ [torow, col-1], [torow, col], [torow, col+1], [row+2, col] ]
return moves
def canMakeMove(self, board, move):
fr, to = move[0], move[1]
# White
if self.colour==0:
# En passant check:
if abs(to[1]-fr[1])==1 and to[0]==2 and fr[0]==3:
# Last move was pawn push
if len(board.doublePawnPush)>0 and board.doublePawnPush[-1]:
[move, _] = board.movesMade[-1]
_, lastMoveTo = move.unpack()
piece = board.pieces[lastMoveTo]
# Last moved piece was black pawn which started in correct place
# (already know it's double pawn push)
if isinstance(piece, Pawn) and piece.colour==1 and move.fr[0]==1 and move.fr[1]==to[1]:
return True
# First check for captures:
if abs(to[1]-fr[1])==1 and to[0]==fr[0]-1:
if fr[0]==1:
# Promotion with capture
return board.hasPieceOn(to[0], to[1]) and board.getPieceOn(to).colour==1 and isinstance(move, Move.PromotionMove)
else:
return board.hasPieceOn(to[0], to[1]) and board.getPieceOn(to).colour==1
# No capture -> can't move sideways
if not to[1]==fr[1]:
return False
# Can't move onto a piece
if board.hasPieceOn(to[0], to[1]):
return False
# First move can be double
if fr[0]==6:
return (to[0]==5 or to[0]==4)
# Promotion (no capture, that was checked above)
if fr[0]==1:
return to[0]==fr[0]-1 and isinstance(move, Move.PromotionMove)
# Standard
return to[0]==fr[0]-1
# Black
else:
# En passant check:
if abs(to[1]-fr[1])==1 and to[0]==5 and fr[0]==4:
# Last move was pawn push
if len(board.doublePawnPush)>0 and board.doublePawnPush[-1]:
[move, _] = board.movesMade[-1]
_, lastMoveTo = move.unpack()
piece = board.pieces[lastMoveTo]
# Last moved piece was white pawn which started in correct place
# (already know it's double pawn push)
if isinstance(piece, Pawn) and piece.colour==0 and move.fr[0]==6 and move.fr[1]==to[1]:
return True
# First check for captures:
if abs(to[1]-fr[1])==1 and to[0]==fr[0]+1:
if fr[0]==6:
# Promotion with capture
return board.hasPieceOn(to[0], to[1]) and board.getPieceOn(to).colour==0 and isinstance(move, Move.PromotionMove)
else:
return board.hasPieceOn(to[0], to[1]) and board.getPieceOn(to).colour==0
# Can't move onto a piece
if board.hasPieceOn(to[0], to[1]):
return False
# Can't move sideways
if not to[1]==fr[1]:
return False
# First move can be double
if fr[0]==1:
return (to[0]==2 or to[0]==3)
# Promotion (no capture, that was checked above)
if fr[0]==6:
return to[0]==fr[0]+1 and isinstance(move, Move.PromotionMove)
# Standard
return to[0]==fr[0]+1
return False
class King(Piece):
def __init__(self, col):
Piece.__init__(self, col, "K", u'\u2654')
def getPlausibleMoves(self, fr):
moves = []
for row in [fr[0]-1, fr[0], fr[0]+1]:
for col in [fr[1]-1, fr[1], fr[1]+1]:
if not (row==fr[0] and col==fr[1]): moves.append([row,col])
return moves
def canMakeMove(self, board, move):
fr, to = move[0], move[1]
return ( abs(fr[0]-to[0]) <= 1 and abs(fr[1]-to[1]) <= 1 )
class Queen(Piece):
def __init__(self, col):
Piece.__init__(self, col, "Q", u'\u2655')
def getPlausibleMoves(self, fr):
movesRook = Rook(self.colour).getPlausibleMoves(fr)
movesBishop = Bishop(self.colour).getPlausibleMoves(fr)
return movesRook + movesBishop
def canMakeMove(self, board, move):
fr, to = move[0], move[1]
if (fr[1]==to[1] or fr[0]==to[0]):
return True
elif ( abs(fr[0]-to[0]) == abs(fr[1]-to[1]) ):
return True
else:
return False
class Rook(Piece):
def __init__(self, col):
Piece.__init__(self, col, "R", u'\u2656')
def getPlausibleMoves(self, fr):
moves = []
for col in range(0,8):
moves.append([fr[0], col])
for row in range(0,8):
moves.append([row, fr[1]])
return moves
def canMakeMove(self,board, move):
fr, to = move[0], move[1]
return (fr[1]==to[1] or fr[0]==to[0])
class Knight(Piece):
def __init__(self, col):
Piece.__init__(self, col, "N", u'\u2658')
def getPlausibleMoves(self, fr):
moves = []
r,c = fr[0], fr[1]
# Left
if c>1:
if r>0:
moves.append([r-1,c-2])
if r<7:
moves.append([r+1,c-2])
# Right
if c<6:
if r>0:
moves.append([r-1,c+2])
if r<7:
moves.append([r+1,c+2])
# Up
if r>1:
if c>0:
moves.append([r-2,c-1])
if c<7:
moves.append([r-2,c+1])
# Down
if r<6:
if c>0:
moves.append([r+2,c-1])
if c<7:
moves.append([r+2,c+1])
return moves
def canMakeMove(self,board, move):
fr, to = move[0], move[1]
return ( abs(fr[0]-to[0])==2 and abs(fr[1]-to[1])==1 ) or ( abs(fr[1]-to[1])==2 and abs(fr[0]-to[0])==1 )
class Bishop(Piece):
def __init__(self, col):
Piece.__init__(self, col, "B", u'\u2657')
def getPlausibleMoves(self, fr):
moves = []
r,c = fr[0], fr[1]
while r<7 and c<7:
r = r+1
c = c+1
moves.append([r,c])
r,c = fr[0], fr[1]
while r>=1 and c>=1:
r = r-1
c = c-1
moves.append([r,c])
r,c = fr[0], fr[1]
while r>=1 and c<7:
r = r-1
c = c+1
moves.append([r,c])
r,c = fr[0], fr[1]
while r<7 and c>=1:
r = r+1
c = c-1
moves.append([r,c])
return moves
def canMakeMove(self,board, move):
fr, to = move[0], move[1]
return ( abs(fr[0]-to[0]) == abs(fr[1]-to[1]) )
<file_sep>/antichess/Move.py
import Pieces
class MoveViolation(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
rowNotation = "87654321"
colNotation = "abcdefgh"
class Move:
fr = [0, 0]
to = [0, 0]
def __init__(self, fr, to):
self.fr = fr
self.to = to
@staticmethod
def fromNotation(m, colour):
try:
mm = [m[0:2], m[2:4]] # e.g. e2e4
fr = [0, 0]
to = [0, 0]
conv = dict(a=0, b=1, c=2, d=3, e=4, f=5, g=6, h=7)
fr[1] = conv[ mm[0][0] ]
fr[0] = 7 - (int(mm[0][1]) - 1)
to[1] = conv[ mm[1][0] ]
to[0] = 7 - (int(mm[1][1]) - 1)
# Promotion?
promotionDict = dict(Q=Pieces.Queen(colour), R=Pieces.Rook(colour), N=Pieces.Knight(colour), B=Pieces.Bishop(colour), K=Pieces.King(colour))
if len(m)>4:
return PromotionMove( fr, to, promotionDict[m[4]] )
else:
return Move(fr, to)
except Exception as e:
print e
raise
def isEnpassant(self, board):
fr, to = self.unpack()
# En passant if a pawn moves diagonally, and there's no piece in target square
return isinstance(board.pieces[fr], Pieces.Pawn) and abs(self.to[1]-self.fr[1])==1 and board.pieces[to]==None
def __getitem__(self, k):
if k==0:
return self.fr
if k==1:
return self.to
raise MoveViolation("Syntax move[k] only valid for k=0,1")
def unpack(self):
return self.fr[0]*8 + self.fr[1], self.to[0]*8 + self.to[1]
def __str__(self):
rowf = self.fr[0]
colf = self.fr[1]
rowt = self.to[0]
colt = self.to[1]
return colNotation[colf]+rowNotation[rowf]+colNotation[colt]+rowNotation[rowt]
class PromotionMove(Move):
promoteTo = None
def __init__(self, fr, to, promoteTo):
Move.__init__(self, fr, to)
self.promoteTo = promoteTo
def __str__(self):
return Move.__str__(self) + self.promoteTo.symbol
class PassMove(Move):
def __init__(self):
pass
def __str__(self):
return "PASS"
class ResignMove(Move):
def __init__(self):
pass
def __str__(self):
return "RESIGN"
class RetractMove(Move):
def __init__(self):
pass
def __str__(self):
return "RETRACT"
class NoneMove(Move):
def __init__(self):
Move.__init__(self, [-1,-1], [-1,-1])
def __str__(self):
return "NONE"
PASS = PassMove()
RESIGN = ResignMove()
RETRACT = RetractMove()
NONE = NoneMove()
<file_sep>/antichess/__main__.py
from antichess.Game import playGame
playGame()
|
031559bbb447a4b6d53773eb23d3952882643fd0
|
[
"Markdown",
"Python"
] | 12 |
Python
|
sdl1/antichess
|
4beca19f390b790247c6d5735e71fd5cec8396aa
|
113ce684223c2b96f31d98adbd201e8be026d282
|
refs/heads/master
|
<repo_name>tomzion90/Countries_onoapps<file_sep>/Countries/Modules/Countries/Cells/CountriesCell.swift
//
// CountriesCell.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import SVGKit
class CountriesCell: TableViewCell<Country> {
@IBOutlet weak var englishNameLabel: UILabel!
@IBOutlet weak var nativeNameLabel: UILabel!
@IBOutlet weak var areaLabel: UILabel!
@IBOutlet weak var flagImageView: UIImageView!
override var item: Country! {
didSet {
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
super.prepareForReuse()
englishNameLabel.text = nil
nativeNameLabel.text = nil
areaLabel.text = nil
flagImageView.image = nil
}
override func fill(with item: Country) {
super.fill(with: item)
englishNameLabel.text = item.name
nativeNameLabel.text = item.nativeName
flagImageView.image = UIImage(named: "image_place_holder")
DispatchQueue.global(qos: .utility).async {
if let url = URL(string: item.flag!) {
let svgFlagImage = SVGKImage(contentsOf: url)
DispatchQueue.main.async {
self.flagImageView.image = svgFlagImage?.uiImage
}
}
}
guard let area = item.area else {
areaLabel.text = "0"
return
}
areaLabel.text = "\(area) sq km"
}
}
<file_sep>/Countries/Modules/Borders/Cells/MapCell.swift
//
// MapCell.swift
// Countries
//
// Created by <NAME> on 06/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import MapKit
class MapCell: UITableViewCell {
@IBOutlet weak var countryMap: MKMapView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func centerMapOnLocation(location: CLLocation) {
let regionRadius: CLLocationDegrees = 1000000
let coordinateRegion = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
countryMap.setRegion(coordinateRegion, animated: true)
}
func fill(with country: Country){
guard let lanlng = country.latlng else { return }
let latitude = lanlng[0]
let longitude = lanlng[1]
let initialLocation = CLLocation(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
centerMapOnLocation(location: initialLocation)
}
}
<file_sep>/Countries/Model/Country.swift
//
// Countries.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
struct Country: Decodable, Comparable {
var name: String
var nativeName: String?
var area: CGFloat?
var flag: String?
var latlng: [CGFloat]?
var borders: [String]?
static func < (lhs: Country, rhs: Country) -> Bool {
return lhs.area ?? 0 > rhs.area ?? 0
}
}
<file_sep>/Countries/Modules/Countries/DataSource&Delegate/CountriesTableViewDelegate.swift
//
// CountriesTableViewDelegate.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
protocol CountrySelectionDelegate: class {
func presentBorders(of country: Country)
}
class CountriesTableViewDelegate: NSObject, UITableViewDelegate {
weak var selectionDelegate: CountrySelectionDelegate?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let cell = tableView.cellForRow(at: indexPath) as? CountriesCell, let country = cell.item {
selectionDelegate?.presentBorders(of: country)
}
}
}
<file_sep>/Countries/Modules/Borders/DataSource&Delegate/BordersTableViewDelegate.swift
//
// BordersTableViewDelegate.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class BordersTableViewDelegate: NSObject, UITableViewDelegate {
}
<file_sep>/Countries/Extensions/Storyboard.swift
//
// Storyboard.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
enum ViewController: String {
case countriesViewController = "CountriesViewController"
case bordersViewController = "BordersViewController"
}
enum Storyboard: String {
case countries = "Countries"
case borders = "Borders"
}
extension UIStoryboard {
static func instantiate(viewController identifier: ViewController, withStoryboard name: Storyboard) -> UIViewController {
let board = UIStoryboard(name: name.rawValue, bundle: nil)
return board.instantiateViewController(withIdentifier: identifier.rawValue)
}
}
<file_sep>/Countries/Modules/Borders/BordersViewController.swift
//
// BordersViewController.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class BordersViewController: TableView<BorderCell, Border> {
let delegate = BordersTableViewDelegate()
var country: Country?
var searchTerm: String = ""
override func viewDidLoad() {
super.viewDidLoad()
configureSearchTerm()
fetchBorders(searchTerm: searchTerm)
}
override func configure() {
super.configure()
configureTableView(with: delegate, estimatedRowHeight: 300, automaticDimensionRowHeight: true)
tableView.tableHeaderView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: Double(Float.leastNormalMagnitude)))
tableView.register(cellType: MapCell.self)
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.prefersLargeTitles = false
}
func configureSearchTerm() {
guard let borders = country?.borders else { return }
for border in borders {
if borders.last != border {
searchTerm += "\(border);"
} else {
searchTerm += "\(border)"
}
}
}
private func fetchBorders(searchTerm: String) {
let stateView = StateView.loadFromNib()
stateView?.delegate = self
tableView.separatorStyle = .none
stateView?.set(.loading)
tableView.backgroundView = stateView
if searchTerm.isEmpty {
stateView?.set(.empty)
tableView.isScrollEnabled = false
return
}
Service.shared.fetchBorders(searchTerm: searchTerm) { result in
switch result {
case .success(let borders):
self.items = borders
case .failure(let error):
stateView?.set(.networkError)
}
self.tableView.reloadData()
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
}
}
}
extension BordersViewController: stateViewDidTapActionDelegate {
func stateViewDidTapActionButton() {
self.fetchBorders(searchTerm: searchTerm)
}
}
extension BordersViewController {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let country = country else { return "" }
if self.country?.latlng?.count != 0 && section == 0 {
return "\(country.name)׳s Map"
} else {
return "\(country.name)׳s Borders"
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100
}
override func numberOfSections(in tableView: UITableView) -> Int {
if self.country?.latlng?.count != 0 {
return 2
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.country?.latlng?.count != 0 && section == 0 {
return 1
}
return super.tableView(tableView, numberOfRowsInSection: items.count)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if self.country?.latlng?.count != 0 && indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "\(MapCell.self)", for: indexPath) as! MapCell
guard let country = country else { return cell}
cell.fill(with: country)
return cell
}
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
<file_sep>/Countries/Extensions/UIViewController.swift
//
// UIViewController.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func reload(_ tableView: UITableView) {
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
<file_sep>/Countries/Extensions/UIView.swift
//
// UIView.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
extension UIView {
public static func loadFromNib(withFrame frame: CGRect? = nil, identifier: String? = nil, bundle: Bundle = Bundle.main) -> Self? {
guard let view = bundle.loadNibNamed(String(describing: self), owner: nil, options: nil)?.last as? Self else { return nil }
view.frame = frame ?? view.frame
return view
}
}
<file_sep>/Countries/Service/Service.swift
//
// Service.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class Service {
static let shared = Service()
func fetchCountries(completion: @escaping (Result<[Country], Error>) -> Void) {
let urlString = "https://restcountries.eu/rest/v2/all"
fetchData(urlString: urlString, completion: completion)
}
func fetchBorders(searchTerm: String, completion: @escaping (Result<[Border], Error>) -> Void) {
let urlString = "https://restcountries.eu/rest/v2/alpha?codes=\(searchTerm)"
fetchData(urlString: urlString, completion: completion)
}
func fetchData<T: Decodable>(urlString: String, completion: @escaping (Result<T, Error>) -> Void) {
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, responce, error) in
do {
guard let data = data else {
if let error = error {
completion(.failure(error))
}
return
}
let countries = try JSONDecoder().decode(T.self, from: data)
completion(.success(countries))
} catch {
completion(.failure(error))
}
}.resume()
}
}
<file_sep>/Countries/Extensions/UITableView.swift
//
// UITableView.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
extension UITableView {
func register(cellType: UITableViewCell.Type) {
self.register(UINib(nibName: String(describing: cellType), bundle: nil), forCellReuseIdentifier: String(describing: cellType))
}
}
<file_sep>/Countries/Views/StateView.swift
//
// StateView.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
protocol stateViewDidTapActionDelegate: class {
func stateViewDidTapActionButton()
}
class StateView: UIView {
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var stateImage: UIImageView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var actionButton: UIButton!
weak var delegate: stateViewDidTapActionDelegate?
enum State {
case loading
case empty
case networkError
}
func set(_ state: State) {
switch state {
case .loading:
stateLabel.text = "Loading"
stateImage.image = UIImage(named: "loading_state")
actionButton.isHidden = true
activityIndicator.isHidden = false
activityIndicator.startAnimating()
case .empty:
stateLabel.text = "No boarders found"
stateImage.image = UIImage(named: "empty_state")
actionButton.isHidden = true
activityIndicator.isHidden = true
case .networkError:
stateLabel.text = "No signal found"
stateImage.image = UIImage(named: "network_error_state")
actionButton.isHidden = false
activityIndicator.isHidden = true
}
}
@IBAction func didTapActionButton(_ sender: Any) {
delegate?.stateViewDidTapActionButton()
}
}
<file_sep>/Countries/Modules/Countries/CountriesViewController.swift
//
// CountriesViewController.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CountriesViewController: TableView<CountriesCell, Country> {
let delegate = CountriesTableViewDelegate()
override func viewDidLoad() {
super.viewDidLoad()
items = [Country]()
fetchData()
}
override func viewWillAppear(_ animated: Bool) {
navigationController?.navigationBar.prefersLargeTitles = true
}
override func configure() {
super.configure()
title = "Countries"
let navigationSortButton = UIBarButtonItem(image: UIImage(named: "sorting_icon"), style: .plain, target: self, action: #selector(sortingWithOptions))
navigationItem.rightBarButtonItem = navigationSortButton
configureTableView(with: delegate, estimatedRowHeight: 300, automaticDimensionRowHeight: true)
delegate.selectionDelegate = self
}
private func fetchData() {
let stateView = StateView.loadFromNib()
stateView?.delegate = self
tableView.separatorStyle = .none
stateView?.set(.loading)
tableView.backgroundView = stateView
Service.shared.fetchCountries { (result) in
switch result {
case .success(let countries):
self.items = countries
if countries.count == 0 {
stateView?.set(.empty)
return
}
case .failure(let error):
stateView?.set(.networkError)
}
self.tableView.reloadData()
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
}
}
@objc func sortingWithOptions() {
let alertController = UIAlertController(title: "Sort by:", message: nil, preferredStyle: .actionSheet)
let sortAlphabetically = UIAlertAction(title: "Alphabets", style: .default) { _ in
self.sortAlphabetically()
}
let sortByAreaSize = UIAlertAction(title: "Area size", style: .default) { _ in
self.sortByAreaSize()
}
alertController.addAction(sortAlphabetically)
alertController.addAction(sortByAreaSize)
self.present(alertController, animated: true, completion: nil)
}
func sortAlphabetically() {
self.items.sort(by: {$0.name < $1.name})
self.reload(tableView)
}
func sortByAreaSize() {
self.items.sort(by: {$0 < $1})
self.reload(tableView)
}
}
extension CountriesViewController: CountrySelectionDelegate {
func presentBorders(of country: Country) {
let viewController = BordersViewController()
viewController.country = country
UIView.animate(withDuration: 1) {
self.navigationController?.pushViewController(viewController, animated: false)
}
}
}
extension CountriesViewController: stateViewDidTapActionDelegate {
func stateViewDidTapActionButton() {
self.fetchData()
}
}
<file_sep>/Countries/Utilities/TableView.swift
//
// TableView.swift
// Countries
//
// Created by <NAME> on 14/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class TableView<T: TableViewCell<M>, M>: UITableViewController {
var items = [M]()
override func viewDidLoad() {
super.viewDidLoad()
configure()
}
func configure() {
tableView.register(cellType: T.self)
}
func configureTableView(with delegate: UITableViewDelegate,estimatedRowHeight: CGFloat?,automaticDimensionRowHeight: Bool) {
tableView.delegate = delegate
tableView.dataSource = self
if let estimatedRowHeight = estimatedRowHeight {
tableView.estimatedRowHeight = estimatedRowHeight
}
if automaticDimensionRowHeight {
tableView.rowHeight = UITableView.automaticDimension
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "\(T.self)", for: indexPath) as! TableViewCell<M>
cell.fill(with: self.items[indexPath.row])
return cell
}
}
class TableViewCell<M>: UITableViewCell {
var item: M!
func fill(with item: M) {
self.item = item
}
}
<file_sep>/Countries/Modules/Borders/Cells/BorderCell.swift
//
// BorderCell.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class BorderCell: TableViewCell<Border> {
override var item: Border! {
didSet {
}
}
@IBOutlet weak var englishNameLabel: UILabel!
@IBOutlet weak var nativeNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func fill(with item: Border) {
super.fill(with: item)
englishNameLabel.text = item.name
nativeNameLabel.text = item.nativeName
}
}
<file_sep>/Countries/Model/Border.swift
//
// Border.swift
// Countries
//
// Created by <NAME> on 05/11/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
struct Border: Decodable {
var name: String?
var nativeName: String?
}
|
f656c043b72b55a98f3c9411cb9ce7afea33f8ce
|
[
"Swift"
] | 16 |
Swift
|
tomzion90/Countries_onoapps
|
4ae8f914d74ca423d2605b252028457fa289c266
|
b8feff1ac7efeb1a8c02612099dd130e3aa426c0
|
refs/heads/master
|
<repo_name>Andrew-Garofalo/my_2048<file_sep>/public/app.js
function createBoard(size) {
let ins = document.getElementById("board");
for (let i = 0; i < size; i++) {
let sq = document.createElement('div');
sq.className = "boardSquare";
sq.innerHTML = "2";
sq.setAttribute("data-id", i);
ins.appendChild(sq);
}
}
$(document).ready(function () {
console.log("hello");
alert("hello");
createBoard(5);
});
|
24aaf8ce424ed0fb896e5657ecb3a362f0d33e75
|
[
"JavaScript"
] | 1 |
JavaScript
|
Andrew-Garofalo/my_2048
|
8be0ed682252381133ba3cad5f3abcd3d2dd89a3
|
b557c66b41f3e5b4300fc0aefa281139db0a1e20
|
refs/heads/master
|
<repo_name>tharindarodrigo/broker<file_sep>/publisher2.js
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://192.168.8.105');
client.on('connect', function () {
var v = 6;
setInterval(function () {
// v++
// if(v==10) {
// v=6
// }
var a = Math.random()
var x1 = null
if (a < 0.25) {
x1 = {"lap": "1"}
} else if (a < 0.5) {
x1 = {"lap": "2"}
} else if (a < 0.75) {
x1 = {"lap": "3"}
} else {
x1 = {"lap": "4"}
}
x1 = JSON.stringify(x1)
client.publish('google_iobike/common', x1)
console.log(x1)
}, 500);
})
<file_sep>/publisher.js
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://mqtt2.iot.ideamart.io');
client.on('connect', function () {
var v = 6;
setInterval(function () {
// v++
// if(v==10) {
// v=6
// }
var x1 = {"id":"1","rev":4,"duration":"500"}
x1 = JSON.stringify(x1)
client.publish('google_iobike/common', x1)
var x2 = {"id":"2","rev":5,"duration":"500"}
x2 = JSON.stringify(x2)
client.publish('google_iobike/common', x2)
//
// var x3 = {"id":"3","rev":Math.random()*10,"duration":"500"}
// x3 = JSON.stringify(x3)
// client.publish('google_iobike/common', x3)
//
// var x4 = {"id":"4","rev":Math.random()*10,"duration":"500"}
// x4 = JSON.stringify(x4)
// client.publish('google_iobike/common', x4)
// client.publish('myTopic', x.toString())
console.log(x1)
}, 300);
});
|
21d00d5d56d594a97a9c0d78956fc53f25bdf23b
|
[
"JavaScript"
] | 2 |
JavaScript
|
tharindarodrigo/broker
|
8618855397247dc85e8017700ffb6566019aec7b
|
0f131871f54575abcb739588f78f67aa384a69a7
|
refs/heads/master
|
<repo_name>JSH220/BulletSim<file_sep>/python_vers/__init__.py
from .racecar_controller import RacecarController<file_sep>/README.md
# Multi-robot simulation based on pybullet
## Requirements
* [pybullet](https://github.com/bulletphysics/bullet3)
```bash
pip install pybullet
```
* [informer](https://github.com/IamWangYunKai/informer)
```bash
git clone https://github.com/IamWangYunKai/informer
cd informer
python setup.py install
```
## Run
```bash
bash test.bash
```
## Others
* Robot and its coordinate

* Running demo

## TODO
- [x] route plan
- [ ] multi-agent collaboration
<file_sep>/test_rrt.py
from informer import Informer
from time import sleep
import random
import math
import numpy as np
from dynamic_window_approach import DynamicWindowApproach
from informed_rrt_star import InformedRRTStar
def calc_dist(pos1, pos2):
return math.sqrt((pos1[0]-pos2[0])**2 + (pos1[1]-pos2[1])**2)
if __name__ == '__main__':
ifm = Informer(random.randint(100000,999999), block=False)
dwa_controller = DynamicWindowApproach([999., 999.], [0., 0.], 0., np.array([]), 0., 0.)
cnt = 0
need_plan = True
change_goal = True
while True:
if change_goal:
goal_x = 5*random.randint(-1000,1000)/1000.
goal_y = 5*random.randint(-1000,1000)/1000.
ifm.send_sim_goal(goal_x, goal_y)
change_goal = False
need_plan = True
cnt = 0
sleep(0.05)
data = ifm.get_sim_info()
if data != None:
hit_pos = np.array(data['hit_pos'])
goal = data['goal']
pos = data['pos']
ori = data['ori']
vel = data['vel']
yaw_rate = data['yaw_rate']
path = [goal]
if need_plan:
pass
"""
planner = InformedRRTStar(start=pos,
goal=goal,
randArea=[-6, 6],
expandDis=1.0,
goalSampleRate=10,
maxIter=500,
max_cnt=1,
obstacleList=hit_pos)
path = planner.informed_rrt_star_search(animation=True)
need_plan = False
#print(pos, path)
"""
temp_pos = goal
if len(path) > 1 and calc_dist(path[-2], pos) < 0.5:
path.pop()
temp_pos = path[-2]
#need_plan = True
elif len(path) < 2:
temp_pos = goal
else:
temp_pos = path[-2]
if calc_dist(goal, temp_pos) < 0.5:
temp_pos = goal
dwa_controller.update_state(temp_pos, pos, ori, hit_pos, vel, yaw_rate)
u, dwa_traj_predict = dwa_controller.dwa_control()
ifm.send_sim(u[0], u[1])
if calc_dist(goal, pos) < 0.3 or cnt > 10000:
change_goal = True
need_plan = True
cnt += 1<file_sep>/test_dma.py
from informer import Informer
from time import sleep
import random
import numpy as np
from dynamic_window_approach import DynamicWindowApproach
if __name__ == '__main__':
ifm = Informer(random.randint(100000,999999), block=False)
dwa_controller = DynamicWindowApproach([999., 999.], [0., 0.], 0., np.array([]), 0., 0.)
cnt = 0
while True:
if cnt % 10000 == 0:
goal_x = 5*random.randint(-1000,1000)/1000.
goal_y = 5*random.randint(-1000,1000)/1000.
ifm.send_sim_goal(goal_x, goal_y)
data = ifm.get_sim_info()
if data != None:
hit_pos = np.array(data['hit_pos'])
#print(len(hit_pos))
goal = data['goal']
pos = data['pos']
ori = data['ori']
vel = data['vel']
yaw_rate = data['yaw_rate']
dwa_controller.update_state(goal, pos, ori, hit_pos, vel, yaw_rate)
u, dwa_traj_predict = dwa_controller.dwa_control()
ifm.send_sim(u[0], u[1])
sleep(0.01)
cnt += 1<file_sep>/python_vers/sensor_rays.py
import math
from .sensor_interface import SensorI
class BatchRay(SensorI):
def __init__(self, pybullet_client, sensor_pos = [0, 0, 0], ray_len = 25, ray_num = 1024):
self.__pb_client = pybullet_client
assert ray_num < self.__pb_client.MAX_RAY_INTERSECTION_BATCH_SIZE, \
"There are too many rays, which should be less than " + str(self.__pb_client.MAX_RAY_INTERSECTION_BATCH_SIZE)
assert isinstance(sensor_pos, (tuple, list)), \
"sensor_pos should be tuple or list..."
assert len(sensor_pos) == 3, \
"sensor_pos should be 3 dimension..."
self.__sensor_pos = tuple(sensor_pos) # make sure sensor_pos is passed by value
self.__ray_len = ray_len
self.__ray_num = ray_num
self.__ray_hit_color = [1, 0, 0]
self.__ray_miss_color = [0, 1, 0]
self.__ray_from = [self.__sensor_pos for i in range(self.__ray_num)]
self.__ray_to = [
[
self.__sensor_pos[0] + self.__ray_len * math.sin(2. * math.pi * float(i) / self.__ray_num),
self.__sensor_pos[1] + self.__ray_len * math.cos(2. * math.pi * float(i) / self.__ray_num),
self.__sensor_pos[2]
]
for i in range(self.__ray_num)
]
self.__results = []
self.__hit_pos = []
@property
def hit_pos(self):
return self.__hit_pos
def get_sensor_pos(self):
return self.__sensor_pos
def set_sensor_pos(self, pos):
assert isinstance(pos, (list, tuple)), \
"...... Position should be a list or tuple ......"
assert len(pos) == 3, \
"...... Position should be 3 dimension ......"
self.__sensor_pos = tuple(pos)
for i in range(self.__ray_num):
self.__ray_from[i] = self.__sensor_pos
self.__ray_to[i] = [
self.__sensor_pos[0] + self.__ray_len * math.sin(2. * math.pi * float(i) / self.__ray_num),
self.__sensor_pos[1] + self.__ray_len * math.cos(2. * math.pi * float(i) / self.__ray_num),
self.__sensor_pos[2]
]
def scan_env(self):
self.__results = self.__pb_client.rayTestBatch(self.__ray_from, self.__ray_to)
self.__hit_pos = [r[3] for r in self.__results if r[0] >= 0]
return self.__hit_pos
# don't support multi-robot until now
def draw_debug(self, drawStep):
assert isinstance(drawStep, int), \
"drawStep should be int type..."
self.__pb_client.removeAllUserDebugItems()
startPos = [self.__sensor_pos[0], self.__sensor_pos[1], 0]
for i in filter(lambda x : not bool(x % drawStep), range(self.__ray_num)):
hit_object_uid = self.__results[i][0]
if (hit_object_uid < 0):
hit_position = [0, 0, 0]
self.__pb_client.addUserDebugLine(startPos, self.__ray_to[i], self.__ray_miss_color)
else:
hit_position = self.__results[i][3]
self.__pb_client.addUserDebugLine(startPos, hit_position, self.__ray_hit_color)
if __name__ == "__main__":
import pybullet as p
import pybullet_data
import time
p.connect(p.GUI)
additional_path = pybullet_data.getDataPath()
p.setAdditionalSearchPath(additional_path)
p.loadURDF("r2d2.urdf", [3, 3, 1])
pos = [0, 0, 0]
rays = BatchRay(p, sensor_pos = pos, ray_len = 8)
while True:
p.stepSimulation()
rays.scan_env()
rays.draw_debug(5)
pos[0] = pos[0] + 0.01
rays.set_sensor_pos(pos)
# time.sleep(0.01)
<file_sep>/python_vers/sensor_interface.py
from abc import abstractmethod, ABCMeta
# define sensor interface, all sensor's class should inherit from it
class SensorI(object, metaclass = ABCMeta):
# get sensor's position in env
@abstractmethod
def get_sensor_pos(self):
pass
# refresh sensor's position if not binded with robot
@abstractmethod
def set_sensor_pos(self, pos):
pass
# collect data from env
@abstractmethod
def scan_env(self):
pass
# draw some lines or points for debug if necessary
@abstractmethod
def draw_debug(self):
pass
<file_sep>/dynamic_window_approach.py
import math
import matplotlib.pyplot as plt
import numpy as np
class Config:
def __init__(self):
# robot parameter
self.max_speed = 1.0 # [m/s]
self.min_speed = 0.0 # [m/s]
self.max_yawrate = 90.0 * math.pi / 180.0 # [rad/s]
self.max_accel = 0.5 # [m/ss]
self.max_dyawrate = math.pi # [rad/ss]
self.v_reso = 0.1 # [m/s]
self.yawrate_reso = 15.0 * math.pi / 180.0 # [rad/s]
self.predict_time = 1.2 # [s]
self.to_goal_cost_gain = 0.1
self.speed_cost_gain = 1.5
self.obstacle_cost_gain = 1.3
self.robot_width = 0.4 # [m] for collision check
self.robot_length = 0.7 # [m] for collision check
class DynamicWindowApproach(object):
def __init__(self, goal, pos, angle, obst, vel_mod = 0, yaw_rate = 0):
self._config = Config()
self._goal = goal
self._pos = pos
self._angle = angle
self._vel_mod = vel_mod
self._yaw_rate = yaw_rate
self._obst = obst
self._time_step = 0.2
self._state_vec = self._pos + [self._angle, self._vel_mod, self._yaw_rate]
def update_state(self, goal, pos, angle, obst, vel_mod, yaw_rate):
self._goal = goal
self._pos = pos
self._angle = angle
self._vel_mod = vel_mod
self._yaw_rate = yaw_rate
self._obst = obst
self._state_vec = self._pos + [self._angle, self._vel_mod, self._yaw_rate]
def dwa_control(self):
dw = self.calc_dynamic_window()
u, trajectory = self.calc_control_and_trajectory(dw)
return u, trajectory
def calc_dynamic_window(self):
# Dynamic window from robot specification
Vs = [self._config.min_speed, self._config.max_speed,
-self._config.max_yawrate, self._config.max_yawrate]
# Dynamic window from motion model
Vd = [self._vel_mod - self._config.max_accel * self._time_step,
self._vel_mod + self._config.max_accel * self._time_step,
self._yaw_rate - self._config.max_dyawrate * self._time_step,
self._yaw_rate + self._config.max_dyawrate * self._time_step]
# [vmin, vmax, yaw_rate min, yaw_rate max]
dw = [max(Vs[0], Vd[0]), min(Vs[1], Vd[1]),
max(Vs[2], Vd[2]), min(Vs[3], Vd[3])]
return dw
def motion(self, x, u):
x[2] += u[1] * self._time_step
x[0] += u[0] * math.cos(x[2]) * self._time_step
x[1] += u[0] * math.sin(x[2]) * self._time_step
x[3] = u[0]
x[4] = u[1]
return x
def predict_trajectory(self, v, y):
x = np.array(self._state_vec[:])
traj = np.array(x)
time = 0
while time <= self._config.predict_time:
x = self.motion(x, [v, y])
traj = np.vstack((traj, x))
time += self._time_step
return traj
def calc_control_and_trajectory(self, dw):
min_cost = float("inf")
best_u = [0.0, 0.0]
best_trajectory = np.array([self._state_vec])
to_goal_cost = 0
speed_cost = 0
ob_cost = 0
# print("dw:", dw)
for v in np.arange(dw[0], dw[1], self._config.v_reso):
for y in np.arange(dw[2], dw[3], self._config.yawrate_reso):
trajectory = self.predict_trajectory(v, y)
# calc cost
to_goal_cost = self._config.to_goal_cost_gain * self.calc_to_goal_cost(trajectory)
speed_cost = self._config.speed_cost_gain * (self._config.max_speed - trajectory[-1, 3])
ob_cost = self._config.obstacle_cost_gain * self.calc_obstacle_cost(trajectory)
final_cost = to_goal_cost + speed_cost + ob_cost
if min_cost >= final_cost:
min_cost = final_cost
best_u = [v / self._config.max_speed, y / self._config.max_yawrate]
best_trajectory = trajectory
return best_u, best_trajectory
def calc_obstacle_cost(self, trajectory):
if not len(self._obst):
return 0
ox = self._obst[:, 0]
oy = self._obst[:, 1]
dx = trajectory[:, 0] - ox[:, None]
dy = trajectory[:, 1] - oy[:, None]
r = np.hypot(dx, dy)
yaw = trajectory[:, 2]
rot = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]])
rot = np.transpose(rot, [2, 0, 1])
local_ob = self._obst[:, None] - trajectory[:, 0:2]
local_ob = local_ob.reshape(-1, local_ob.shape[-1])
local_ob = np.array([local_ob @ x for x in rot])
local_ob = local_ob.reshape(-1, local_ob.shape[-1])
upper_check = local_ob[:, 0] <= self._config.robot_length / 2
right_check = local_ob[:, 1] <= self._config.robot_width / 2
bottom_check = local_ob[:, 0] >= -self._config.robot_length / 2
left_check = local_ob[:, 1] >= -self._config.robot_width / 2
if (np.logical_and(np.logical_and(upper_check, right_check),
np.logical_and(bottom_check, left_check))).any():
return float("Inf")
min_r = np.min(r)
return 1.0 / min_r # OK
def calc_to_goal_cost(self, trajectory):
dx = self._goal[0] - trajectory[-1, 0]
dy = self._goal[1] - trajectory[-1, 1]
error_angle = math.atan2(dy, dx)
cost_angle = error_angle - trajectory[-1, 2]
cost = abs(math.atan2(math.sin(cost_angle), math.cos(cost_angle)))
return cost
<file_sep>/run-agents.sh
for i in {1..2}
do
python test_dma.py &
done<file_sep>/python_vers/racecar.py
import os
class Racecar(object):
def __init__(self, bullet_client, urdf_root_path, start_pos, start_ori):
self._urdf_root_path = urdf_root_path
self._p = bullet_client
self._carId = 0
self._reset(start_pos, start_ori)
def _reset(self, start_pos, start_ori):
car = self._p.loadURDF(os.path.join(self._urdf_root_path, "racecar/racecar_differential.urdf"),
start_pos,
self._p.getQuaternionFromEuler(start_ori),
useFixedBase=False)
self._carId = car
for wheel in range(self._p.getNumJoints(car)):
self._p.setJointMotorControl2(car,
wheel,
self._p.VELOCITY_CONTROL,
targetVelocity=0,
force=0)
self._p.getJointInfo(car, wheel)
c = self._p.createConstraint(car,
9,
car,
11,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=1, maxForce=10000)
c = self._p.createConstraint(car,
10,
car,
13,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=-1, maxForce=10000)
c = self._p.createConstraint(car,
9,
car,
13,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=-1, maxForce=10000)
c = self._p.createConstraint(car,
16,
car,
18,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=1, maxForce=10000)
c = self._p.createConstraint(car,
16,
car,
19,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=-1, maxForce=10000)
c = self._p.createConstraint(car,
17,
car,
19,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=-1, maxForce=10000)
c = self._p.createConstraint(car,
1,
car,
18,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=-1, gearAuxLink=15, maxForce=10000)
c = self._p.createConstraint(car,
3,
car,
19,
jointType=self._p.JOINT_GEAR,
jointAxis=[0, 1, 0],
parentFramePosition=[0, 0, 0],
childFramePosition=[0, 0, 0])
self._p.changeConstraint(c, gearRatio=-1, gearAuxLink=15, maxForce=10000)
if __name__ == '__main__':
import pybullet as pb
import pybullet_data
from bullet_client import BulletClient
p = BulletClient(pb.GUI)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
planID = p.loadURDF('plane.urdf')
p.setGravity(0,0,-10)
car = Racecar(p, pybullet_data.getDataPath(), [0,0,0], [0,0,0])
while True:
p.stepSimulation()
<file_sep>/python_vers/racecar_controller.py
import math
import numpy as np
from .racecar import Racecar
from .sensor_rays import BatchRay
class RacecarController(Racecar):
def __init__(self, bullet_client, urdfRootPath, time_step, start_pos = [0, 0], start_ori = 0, goal = [0, 0, 0]):
assert isinstance(start_pos, (list, tuple)), \
"Type Error: start pos should be a list or typle..."
assert len(start_pos) == 2, \
"Size Error: start pos should be 2 demension..."
assert isinstance(start_ori, (float, int)), \
"Type Error: start orientation should be a float or int..."
super().__init__(bullet_client, urdfRootPath, start_pos + [0.1,], [0, 0, start_ori])
self._pos = start_pos
self._vel = 0
self._ori = start_ori
self._yaw_rate = 0
self._time_step = time_step
self._goal = goal
#self._maxForceUpperbound = 100
#self._speedMultiplierUpperbound = 100
#self._steeringMultiplierUpperbound = math.pi / 2
self._maxForce = 100
self._speedMultiplier = 20.
self._steeringMultiplier = 1.0
# don't change them
self._steering_links = [0, 2]
self._num_motors = 2
self._motorized_wheels = [8, 15]
self._sensor_pos = self._pos + [0.05,]
self._rays = BatchRay(self._p, self._sensor_pos, 8, 1024)
@property
def orient(self):
return self._ori
@property
def time_step(self):
return self._time_step
@property
def pos(self):
return self._pos
@property
def goal(self):
return self._goal
@property
def yaw_rate(self):
return self._yaw_rate
@property
def vel(self):
return self._vel
@goal.setter
def goal(self, goal):
assert isinstance(goal, list), \
"goal should be a list......"
assert len(goal) == 2, \
"goal should be 2 dimension......"
self._goal = goal
def stepSim(self, drawRays = False, drawStep = 5):
assert isinstance(drawRays, bool), \
"drawRays should be boolen type"
pos, ori = self._p.getBasePositionAndOrientation(self._carId)
self._pos, self._vel = list(pos)[0:2], np.linalg.norm((np.array(pos[0:2]) - np.array(self._pos))) / self._time_step
ori = self._p.getEulerFromQuaternion(ori)[2]
self._ori, self._yaw_rate = ori, (ori - self._ori) / self._time_step
self._rays.set_sensor_pos(self._pos + [0.3,])
hit_pos = self._rays.scan_env()
hit_pos = [p[0:2] for p in hit_pos]
# don't support multi-robot until now
if drawRays:
self._rays.draw_debug(drawStep)
return hit_pos
def apply_action(self, motorCommands):
vel = motorCommands[0] * self._speedMultiplier
steeringAngle = motorCommands[1] * self._steeringMultiplier
for motor in self._motorized_wheels:
self._p.setJointMotorControl2(self._carId,
motor,
self._p.VELOCITY_CONTROL,
targetVelocity=vel,
force=self._maxForce)
for steer in self._steering_links:
self._p.setJointMotorControl2(self._carId,
steer,
self._p.POSITION_CONTROL,
targetPosition=steeringAngle)
<file_sep>/test_terrain.py
# -*- coding: utf-8 -*-
import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0, parentdir)
import json
import socket
import random
import threading
import numpy as np
import matplotlib.pyplot as plt
import pybullet as pb
import pybullet_data as pbd
from pybullet_utils import bullet_client
from python_vers import RacecarController
additional_path = pbd.getDataPath()
timeStep = 1./30.
def setObstacles(number):
for i in range(number):
position = [10.0*random.random() - 5.0, 10.0*random.random() - 5.0, 0]
obstacle_id = pb.createCollisionShape(pb.GEOM_CYLINDER,radius=0.2,height=0.5) \
if random.random() > 0.5 else \
pb.createCollisionShape(pb.GEOM_BOX,halfExtents=[0.4, 0.4, 0.5])
pb.createMultiBody(baseMass=9999,baseCollisionShapeIndex=obstacle_id, basePosition=position)
def draw_collision(hit_pos):
hit_pos = np.array(hit_pos)
x = [val for val in hit_pos[:,0]]
y = [val for val in hit_pos[:,1]]
plt.scatter(x, y, s=1, alpha=0.6)
plt.show()
class RobotManager():
def __init__(self):
self.robots_cmd = {}
self.socket_dict = {}
self.robots_addr = {}
self.robots = {}
self.robots_goal = {}
self.socket_dict['sim'] = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
self.socket_dict['sim'].bind(("", 10007))
self.message_recv_thread = threading.Thread(
target=self.message_recv, args=()
)
self.message_recv_thread.start()
def encode_message(self, data, robot_id=0, mtype='sim', pri=5):
data = {'Mtype':mtype, 'Pri':pri, 'Id':robot_id, 'Data':data}
try:
data = json.dumps(data).encode()
except:
print('Error', type(data['Data']), data, data['Data'])
return "".encode()
return data
def send_simple_package(self, data, socket, address, debug=False):
ret = socket.sendto(data,address)
if debug:
print('Simple send', data)
return ret
def send_message(self, data, address, mtype='sim', pri=5, debug=False):
data = self.encode_message(data=data, robot_id=0, mtype=mtype, pri=pri)
self.send_simple_package(data, self.socket_dict['sim'], address, debug=debug)
def message_recv(self):
while True:
data,addr = self.socket_dict['sim'].recvfrom(65535)
json_data = json.loads(data.decode('utf-8'))
self.parse_message(json_data, addr)
def parse_message(self, message, addr):
message_type = message['Mtype']
#pri = message['Pri']
robot_id = message['Id']
data = message['Data']
if message_type == 'register':
if robot_id in self.robots.keys():
print('re-register robot', robot_id)
else:
print('register robot', robot_id)
self.robots_cmd[robot_id] = [0., 0.]
self.robots_addr[robot_id] = addr
self.robots_goal[robot_id] = [0., 0.]
position = [10.0*random.random() - 5.0, 10.0*random.random() - 5.0]
robot = RacecarController(client, additional_path, timeStep, position, 0)
self.robots[robot_id] = robot
data = str(addr[0])+":"+str(addr[1])
self.send_message(data, addr)
elif message_type == 'cmd':
self.robots_cmd[robot_id] = [data['v'], data['w']]
elif message_type == 'goal':
self.robots_goal[robot_id] = [data['x'], data['y']]
draw_goals(self.robots_goal)
else:
print('Error:',message)
def draw_goals(goals):
global client
client.removeAllUserDebugItems()
for robot_id, goal in goals.items():
client.addUserDebugLine([goal[0], goal[1], 0.],
[goal[0], goal[1], 1.],
lineColorRGB = [1., 0., 0.],
lineWidth = 10.0)
client.addUserDebugText("Goal",
[goal[0], goal[1], 1.],
textColorRGB = [1., 0., 0.],
textSize = 1.5)
if __name__ == "__main__":
client = bullet_client.BulletClient(pb.GUI)
textureId = -1
pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING,0)
terrainShape = pb.createCollisionShape(shapeType = pb.GEOM_HEIGHTFIELD, meshScale=[0.05,0.05,16],fileName = "map.png")
textureId = pb.loadTexture("map.png")
terrain = pb.createMultiBody(0, terrainShape)
pb.changeVisualShape(terrain, -1, textureUniqueId = textureId)
pb.changeVisualShape(terrain, -1, rgbaColor=[1,1,1,1])
pb.configureDebugVisualizer(pb.COV_ENABLE_RENDERING,1)
client.setTimeStep(timeStep)
client.setPhysicsEngineParameter(numSolverIterations=8)
client.setPhysicsEngineParameter(minimumSolverIslandSize=100)
client.configureDebugVisualizer(client.COV_ENABLE_RENDERING,1)
client.setAdditionalSearchPath(pbd.getDataPath())
client.loadURDF('plane.urdf')
#setObstacles(5)
client.setGravity(0,0,-9.8)
x = []
y = []
manager = RobotManager()
while True:
for robot_id in list(manager.robots.keys()):
robot = manager.robots[robot_id]
actions = manager.robots_cmd[robot_id]
robot.apply_action(actions)
hit_pos = robot.stepSim(False, 200)
if len(hit_pos) != 0:
manager.send_message({
'goal': manager.robots_goal[robot_id],
'hit_pos': hit_pos,
'pos': manager.robots[robot_id].pos,
'ori': manager.robots[robot_id].orient,
'vel': manager.robots[robot_id].vel,
'yaw_rate':manager.robots[robot_id].yaw_rate
}, manager.robots_addr[robot_id])
client.stepSimulation()
print('Finish !')<file_sep>/install.sh
pip uninstall informer -y
mkdir _tmp
cd _tmp
git clone https://github.com/IamWangYunKai/informer.git
cd informer
python setup.py install
cd ../..
rm -rf _tmp
|
8ab70110a030e8c642d019c5f8c215ecc3f7d464
|
[
"Markdown",
"Python",
"Shell"
] | 12 |
Python
|
JSH220/BulletSim
|
ac008bc17e15e517d6a36c35351e6d4ed71b8bce
|
a9a070fe055fd28bc62c947076f028147b54bfc8
|
refs/heads/master
|
<repo_name>Divyosmi/URJA<file_sep>/Parser.py
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.AST = []
def add_node(self, parent, node):
for a in self.AST:
if parent in a:
a[parent].append(node)
def build_AST(self):
saved = {}
parent = {}
collect = False
for token in self.tokens:
if token['id'] == 'label':
t = {token['value']: []}
if parent != t:
parent = token['value']
self.AST.append(t)
elif token['id'] == 'keyword':
if token['value'] == 'end':
t = {token['value']: 0}
self.add_node(parent, t)
else:
if collect == False:
saved = token
collect = True
else:
t = {saved['value']: token['value']}
self.add_node(parent, t)
collect = False
elif token['id'] == 'char' or token['id'] == 'atom':
if collect == False:
saved = token
collect = True
else:
t = {saved['value']: token['value']}
self.add_node(parent, t)
collect = False
<file_sep>/lexer.py
class lexer:
def __init__(self, data):
self.numbers = ["0",'1','2','3','4','5','6','7','8','9']
self.data = data
self.tokens = []
self.keywords = [
'add',
'rem',
'sub',
'mul',
'div',
'display',
'#',
'fact',
'fib',
'go'
]
def tokenizer(self):
for loc in self.data:
tmp = []
tid = ''
for l in loc:
if l == '"' and tid == '':
tid = 'char'
tmp = []
elif l == '"' and tid == 'char':
self.tokens.append({'id': tid, 'value': ''.join(tmp)})
tid = ''
tmp = []
elif l == ':':
self.tokens.append({'id': 'label', 'value': ''.join(tmp)})
tmp = []
elif ''.join(tmp) in self.keywords:
self.tokens.append({'id': 'keyword', 'value': ''.join(tmp)})
tmp = []
elif l == '\n':
if len(tmp) > 0:
self.tokens.append({'id':'atom','value':''.join(tmp)})
elif l == ' ' and tid != 'char':
continue
else:
tmp.append(l)
<file_sep>/Evaluator.py
class Evaluator:
def __init__(self, AST):
print("Hi, from urja , wish you all the best")
self.AST = AST
def run(self, node):
if isinstance(node, list):
for n in node:
for k, v in n.items():
self.execute([k, v])
elif isinstance(node, dict):
for k, v in node.items():
self.execute([k, v])
def execute(self, loc):
if isinstance(loc[1], list):
self.run(loc[1])
elif loc[0] == 'display':
self.display(loc[1])
elif loc[0] == 'go':
self.go(loc[1])
elif loc[0] == 'add':
self.add(loc[1])
elif loc[0] == 'sub':
self.sub(loc[1])
elif loc[0] == 'mul':
self.mul(loc[1])
elif loc[0] == 'div':
self.div(loc[1])
elif loc[0] == 'rem':
self.rem(loc[1])
elif loc[0] == '#':
self.comm(loc[1])
elif loc[0] == 'fact':
self.fact(loc[1])
elif loc[0] == 'fib':
self.fib(loc[1])
def go(self, v):
self.run(v)
def comm(self, v):
pass
def fact(self, v):
a = 1
for i in range(1,int(v) + 1):
a *= i
print(a)
def fib(self, v):
v = int(v)
a = 0
b = 1
if v == 0:
pass
elif v == 1:
print(v - 1)
else:
l = []
l.append(a)
l.append(b)
for i in range(2, v + 1):
c = a + b
a = b
b = c
l.append(b)
print(l)
def add(self, v):
w = float(input())
print(float(v) + w)
def rem(self, v):
w = float(input())
print(float(int(v) % int(w)))
def mul(self, v):
w = float(input())
print(float(v) * w)
def div(self, v):
w = float(input())
print(float(v) / w)
def sub(self, v):
w = float(input())
print(float(v) - w)
def display(self, v):
print(v)
<file_sep>/.urja.sh
function urja() {
python main.py
}
<file_sep>/README.md
## Welcome to URJA
You can use the [](https://repl.it/github/Divyosmi/URJA) to maintain and preview the content for your website in Markdown files.
Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files.
### Markdown
urja has everything from basic arithmetic to inbuilt fib fact and more will be updated soon may be 2021
<br>

```
For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/).
### Jekyll Themes
Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/Divyosmi/URJA/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file.
### Support or Contact
Having trouble with Pages? Check out our [documentation](https://help.github.com/categories/github-pages-basics/) or [contact support](https://github.com/contact) and we’ll help you sort it out.
and any one can contact me at my email
|
b98ce53718f6c33e7ee21267650d22aa5339118f
|
[
"Markdown",
"Python",
"Shell"
] | 5 |
Python
|
Divyosmi/URJA
|
d7bf6abdbe42bb390fe1a489bb79a0d066467822
|
fee40c4c1c24da8add586ff7dffa649121bf7383
|
refs/heads/main
|
<repo_name>acnowland/vue-udemy<file_sep>/basics-assignment-2-problem/app.js
const app = Vue.createApp({
data() {
return {
firstInput: "",
secondInput: "",
confirmedInput: "",
};
},
methods: {
showAlert() {
alert("You Clicked Me!");
},
modifyFirstInput(event) {
this.firstInput = event.target.value;
},
modifySecondInput(event) {
this.secondInput = event.target.value;
},
confirmInput() {
this.confirmedInput = this.secondInput;
},
},
});
app.mount("#assignment");
<file_sep>/basics-assignment-1-problem/app.js
const app = Vue.createApp({
data() {
return {
myName: "<NAME>",
myAge: 33,
myAgeInFive: 38,
randomNum: 0,
picture:
"https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.medicalnewstoday.com%2Farticles%2F322868&psig=AOvVaw1Omxw1ss3pMVOye4wei2By&ust=1630608588807000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCNDlncq43vICFQAAAAAdAAAAABAD",
inputValue: "Adam",
};
},
methods: {
favoriteNumber() {
const newRandomNum = Math.random();
return newRandomNum;
},
},
});
app.mount("#assignment");
|
375bfe53c417b20e91985cd261f359ea3e38150a
|
[
"JavaScript"
] | 2 |
JavaScript
|
acnowland/vue-udemy
|
4764731fc86dc1d6bfff81d9338eab2692eb8bf8
|
859c5e615719173dc8fccecceb8f146bb12a98a5
|
refs/heads/master
|
<repo_name>meghna512/meghna512.github.io<file_sep>/index.js
var slide = document.querySelectorAll('.position');
var slideIndex = 0;
var durationSliderInterval = setInterval(nextSlide, 1500);
function resetActive() {
slide.forEach(item => {
item.classList.remove("active");
});
}
function resetInterval() {
clearInterval(durationSliderInterval)
durationSliderInterval = setInterval(nextSlide, 1500);
}
function changeSlide() {
resetActive();
slide[slideIndex].classList.add('active');
}
function nextSlide() {
slideIndex < slide.length - 1 ? slideIndex++ : slideIndex = 0;
changeSlide();
}
function previousSlide() {
slideIndex > 0 ? slideIndex-- : slideIndex = slide.length - 1;
changeSlide();
}
|
f9e3b846022c1863e7e761cdfd489857ab42bc1b
|
[
"JavaScript"
] | 1 |
JavaScript
|
meghna512/meghna512.github.io
|
7a9931a0af79aeefccdc53c9b9db517437a4df7e
|
fc546067cc87a2c024562963dfbf6f178b10ab2f
|
refs/heads/master
|
<repo_name>wm3/scala-2012<file_sep>/programming-in-scala/doc/s8-s9/FileMatcher.java
import java.util.List;
import java.util.ArrayList;
import java.io.File;
/**
* <p>ディレクトリ内でのファイル名検索を行うクラスです。
*
* <p>検索方法は後方一致、部分一致、正規表現の三つです。
*/
public class FileMatcher {
private File[] filesHere = (new File(".")).listFiles();
/** 後方一致検索 */
public List<File> filesEnding(String query) {
List<File> result = new ArrayList<File>();
for (File file : filesHere) {
if (file.getName().endsWith(query)) result.add(file);
}
return result;
}
/** 部分一致検索 */
public List<File> filesContaining(String query) {
List<File> result = new ArrayList<File>();
for (File file : filesHere) {
if (file.getName().contains(query)) result.add(file);
}
return result;
}
/** 正規表現 */
public List<File> filesRegex(String query) {
List<File> result = new ArrayList<File>();
for (File file : filesHere) {
if (file.getName().matches(query)) result.add(file);
}
return result;
}
}
<file_sep>/programming-in-scala/doc/s21/README.md
s21 暗黙の型変換とパラメーター
================
### 概要
- 冗長なコードを簡略化するための暗黙の処理を行わせる機能がある
- 暗黙の型変換
- 暗黙のパラメーター
- 可視境界
- 暗黙な処理が意図せずに行われないために、色々制約がある
- クラスを拡張する方法
暗黙の型変換
--------
- 型キャストみたいな物
- 例: イベントリスナー
- 関数をそのまま渡したい
implicit の規則
--------
- マーキングルール: implicit がついた定義だけが暗黙の型変換(とパラメーター)に使われる
- 関数、変数、オブジェクト定義で使える
- スコープルール: 暗黙の型変換の検索にはスコープが制限される
- 単一の識別子としてスコープ内にある場合
- ×: some.convert(x)、○: convert(x)
- 同一ファイル内にある場合
- import を(直接、もしくはxx._で)している場合
- import Preamble._ と呼ぶためにPreambleクラスを用意することが多い
- コンパニオンオブジェクトのメソッドである場合
- 変換元でも変換先でも
- 一度に一回ルール: 暗黙の型変換が二重に挿入されることは無い
- この制限の回避方法あり
- 明示的変換優先ルール: 書かれた状態で動作する場合は暗黙の型変換を行わない
- (非曖昧性ルール: 他に起こりうる暗黙の型変換が無い場合のみ型変換が行われる)
- オンラインの原文にのみ記載、削除された?
- …と思ったら拡張されて後述されている
### 暗黙の型変換の名前の付け方
- 何でも良い
- (Predef では byte2float などが定義されている)
- 名前が問題となるケース
- 直接呼び出す時
- 名前を指定して import したい時
### implicit が行われる場所
- 要求された方への変換
- レシーバの変換
- 暗黙のパラメーター
要求された型への暗黙の型変換
--------
- 各数値型の(より大きい数値型への)暗黙の型変換はPredefに含まれている
レシーバの変換
--------
- 例: Intから自作有理数クラスへの変換
- 例: -> 演算子
- 該当メソッドを実装した変換が複数ある場合はどうする??
暗黙のパラメーター
--------
- 関数の引数を補完する
- カリー化されたパラメーターリスト全体
- カリー化されてなくてもうまくいった…
- 変数定義にimplicitをつける
- 型パラメーターを使った暗黙のパラメーターも使用できる
- 例: orderer
- 標準ライブラリは基本的な型の orderer を提供している
- (関係している型のコンパニオンオブジェクトの定義もみる)
### 暗黙のパラメーターのためのスタイルの原則
- 意図せずに使用されないように、パラメーターの型は特別な物を使う
- String などをimplicitの型にしない
- (T, T) => Boolean ではなく Ordering を使う
可視境界
--------
- implicit なパラメーターがメソッド内部で暗黙の型変換や暗黙のパラメーターに使われる事が多い
- implicit なパラメーターが直接参照されない事も多い
- 可視境界を使ってメソッド定義を小さくできる
- 「T <% Ordered[T]」は「Ordered[T]として扱える任意のT」と読める
複数の型変換を適用できる時
--------
- 基本的には適用しない
- 片方がより厳密な型を使った変換ならそれを使う(2.8以降)
- サブクラスのメソッドを優先する
- 引数の方がサブクラスになっている
暗黙の型変換のデバッグ
--------
- 見つけられない場合
- 型変換を明示的に書いてみる
- scalac -Xprint:typer
- scala -Xprint:typer
<file_sep>/programming-in-scala/doc/s8-s9/README.md
s8 関数とクロージャー
========
## この章の概要
1. いわゆる「関数型スタイル」のプログラミングが出来る
2. 関数定義の様々な短縮形がある
## メソッド (省略)
## ローカル関数
* ローカル関数のメリット: 名前空間を汚さない、関数のスコープが小さくなる
* 使用例: リスト8.2 (processLine)
* 外のローカル変数も使える
## ファーストクラスの関数
* 関数リテラル
* (varName: Type, ...) => { ... }
* 短縮形1: 本文の中括弧の省略
* 本文が単文の場合: (varName: Type, ...) => { x + y * 3 }
* (varName: Type, ...) => x + y * 3
* Scala の標準ライブラリは関数オブジェクトを渡すために作り込まれている
* 一例として コレクションの foreach、 filter
## 関数リテラルの短縮形
* 短縮形2: 引数の型の省略
* コンパイラが引数の型をうまく推論してくれた場合: arr.filter((x: Int) => x > 0)
* arr.filter((x) => x > 0)
* 短縮形3: 型パラメーターの括弧の省略
* 短縮形2が出来た場合のみ(その上で引数が一つの時かな?)
* arr.filter(x => x > 0)
* 型推論はどういう時に出来る?
* 考えないで良い。まずは普通の形で書いて、その後省略してみる。
* そのうち慣れる!
## プレースホルダー構文
* 短縮形4: プレースホルダーの使用1
* 引数が一つ、かつ型推論してくれる場合: arr = Array(1, -2, 3)
* arr.filter(_ > 0)
* 短縮形5: プレースホルダーの使用2
* 型推論できなかった場合: arr = Array\[Any](1, -2, 3)
* arr.filter((_: Int) > 0)
* 短縮形6: プレースホルダーの使用3
* 引数が複数ある場合: arr.reduce((x, y) => x + y)
* arr.reduce(_ > _)
## 部分適用された関数
* 短縮形7: 引数リスト全体のプレースホルダー
* 一引数以外の関数: def max(x: Int, y: Int) { ... }
* arr.reduce(max _)
* 0引数の関数でもOK
* 短縮形8: プレースホルダーの省略
* うまく推論してくれる場合
* arr.reduce(max)
* println(max) とかはできない。printlnの引数は関数とは限らないため。
* ちなみに: (max _)は呼び出すたびに違うhashCode()を返した。
## クロージャー
* (x: Int) => x + more の more って何が入る? という話
* 正直、使う際にはあまり考えなくても良いと思う
* JavaScript と同じ
* (他の挙動をする言語(Lispとか)を使った事がないです…)
## 関数呼び出しの特殊な形態
* 連続パラメーター
* Java の可変長引数: def echo (args: String*) = args.foreach(println)
* Java と違って配列は渡せない: echo(Array("a", "b")) はエラー
* echo(Array("a", "b"): _*) でJavaの同様のことができる
* 名前付き引数
* 例: def speed(distance: Float, time: Float) = ...
* speed(100, 10) でも speed(distance = 100, time = 10)でもOK
* パラメーターのデフォルト値
* 例: def printTime(out: java.io.PrintStream = Console.out) = ...
* 名前付引数と併用すると良い
## 末尾再帰
* 知ってる人は知っている、知らない人は知らなくても良い
* 末尾再帰を最適化してくれる
* ただしJVMの制約のため、ごく単純なもののみ
* 相互呼び出しや関数オブジェクト呼び出しでは出来ない
* clojure はrecかなんかをつけないと行けなかったけど、なぜだろう
## 感想
* 良くも悪くも短縮形が多い。
* There is more than one way to do it 寄り。これはJavaと大きく異なる。
s9 制御の抽象化
===========
## この章の概要
1. 関数オブジェクトでコードが簡単になる!
2. (擬似的に)新しい制御構文を作る方法
## 重複するコードの削減
* (例: FileMatcher をクラスを作ってみましたので参照)
## クライアントコードの単純化
* コレクションのループ系のメソッド(foreach, map, filter, find, reduce, groupBy, zip ...)
* P.174 下と P.175 上を比較
## (新しい制御構造)
* (例: 自動で stream を close() する書き込みメソッドを書きましたので参照)
## カリー化
* 要するに def doSomething(x: ...)(y: ...)(z: ...) という表記がある、ということ
* 目的の60%くらいは次節の制御構文っぽい呼び出しのためのもの
* 残りの30% くらいは暗黙の引数のためのもの
* 後述する「制御構文の擬似的な拡張」を実現するための物(他に目的はある??)
### ちなみに: カリー化について(憶測が混じっています)
* 元々は計算機科学の理論的な分野の概念
* 偉い学者: 「関数の引数が一つだったり二つだったりすると難しい!」
* 「だから、複数の引数を用意する代わりに関数を返す関数にしよう!」
* ラムダ計算とかがそれ。
* 関数の引数が二つ以上無い言語もある(Haskell)
* 疑問: Scala は本当に「カリー化」?
* 関数を返す関数は作っているし極めて近いが…
* 「変換」なのだろうか? これが分かりにくい原因のようにも見える。
* ちなみに: カリー化(scala) vs ブロック引数定義のための構文(ruby)
* 呼び出す分には両方とも同じ
* 定義方法が違う
## 新しい制御構造を作る
* 引数が一つの場合、f(x) の代わりに f { x } と書ける
## 名前渡しパラメーター
* assert や && を実現するための機能
* リスト9.5 参照
|
23a83c0b0d64b748eebc796b5d9cf62899099a5a
|
[
"Markdown",
"Java"
] | 3 |
Java
|
wm3/scala-2012
|
979806937588e80dbf0a5822e2e53e191c0d83a6
|
63ad813f8cfe47f80fd2debd3ab82171936f6db2
|
refs/heads/main
|
<repo_name>CSBoggs/W19C<file_sep>/gameboard.py
import player
class GameBoard:
def __init__(self):
self.winningRow = 0
self.winningColumn = 2
self.player = player.Player(3,2)
self.board = [
[" * ", " * ", " ", " * ", " * ", " * ", " * ", " * "],
[
" * ",
" ",
" ",
" ",
" ",
" ",
" * ",
" * "
],
[
" * ",
" ",
" * ",
" * ",
" ",
" * ",
" ",
" * "
],
[
" * ",
" ",
" ",
" ",
" * ",
" ",
" ",
" * "
],
[
" * ",
" ",
" * ",
" * ",
" * ",
" * ",
" ",
" * "
],
[
" * ",
" ",
" ",
" ",
" ",
" * ",
" ",
" * "
],
[" * ", " * ", " * ", " * ", " * ", " * ", " * ", " * "],
]
def printBoard(self, playerRow, playerColumn):
for i in range(len(self.board)):
for j in range(len(self.board[i])):
if i == playerRow and j == playerColumn:
print("P", end="")
else:
print(self.board[i][j], end="")
print("")
def checkMove(self, testRow, testColumn):
if self.board[testRow][testColumn].find("*") != -1:
print("Can't move there!")
return False
return True
def player_movement(self, selection):
if(selection == "w"):
if self.checkMove(self.player.rowPosition - 1, self.player.columnPosition):
self.player.moveUp()
elif(selection == "s"):
if self.checkMove(self.player.rowPosition + 1, self.player.columnPosition):
self.player.moveDown()
elif(selection == "a"):
if self.checkMove(self.player.rowPosition, self.player.columnPosition - 1):
self.player.moveLeft()
elif(selection == "d"):
if self.checkMove(self.player.rowPosition, self.player.columnPosition + 1):
self.player.moveRight()
else:
print("Invalid entry! Please try again")
def checkWin(self, playerRow, playerColumn):
return playerRow == self.winningRow and playerColumn == self.winningColumn
<file_sep>/app.py
import gameboard
import player
print("Welcome to the game!")
print("Instructions: ")
print("To move up: w")
print("To move down: s")
print("To move left: a")
print("To move right: d")
print("Try to get to the end! Good Luck!")
print("-----------------------------")
board = gameboard.GameBoard()
while True:
board.printBoard(board.player.rowPosition, board.player.columnPosition)
selection = input("Make a move: ")
board.player_movement(selection)
if board.checkWin(board.player.rowPosition, board.player.columnPosition):
print("You win")
quit()
|
928e03f1497f2586a66278a569444acc610ddf71
|
[
"Python"
] | 2 |
Python
|
CSBoggs/W19C
|
69154a90d5368e2945e868bbdf8a666d1fd11160
|
5b236922541578558fe1b4024c3fd534273c51cc
|
refs/heads/master
|
<file_sep># Train-Scheduler
An app that uses firebase to store data for train arrival times
<file_sep> // Initialize Firebase
var config = {
apiKey: "<KEY>",
authDomain: "taylor-train-scheduler.firebaseapp.com",
databaseURL: "https://taylor-train-scheduler.firebaseio.com",
projectId: "taylor-train-scheduler",
storageBucket: "",
messagingSenderId: "127439110825"
};
firebase.initializeApp(config);
var database = firebase.database();
setInterval(function(startTime) {
$("#timer").html(moment().format('hh:mm a'))
}, 1000);
console.log(moment());
$('#add-button').on("click", function() {
event.preventDefault();
var train = $("#input-train").val().trim();
var destination = $("#input-destination").val().trim();
var stopFreq = $("#input-freq").val().trim();
var stopTime = $("#input-stop").val().trim();
var trainX = {
formtrain: train,
formdestination: destination,
formfrequency: stopFreq,
formstoptime: stopTime,
dateAdded: firebase.database.ServerValue.TIMESTAMP
};
// console.log('Our train info object', trainX)
console.log(trainX.formtrain);
console.log(trainX.formdestination);
console.log(trainX.formfrequency);
console.log(trainX.formstoptime);
console.log(trainX.dateAdded);
$("#input-train").val("");
$("#input-destination").val("");
$("#input-freq").val("");
$("#input-stop").val("");
firebase.database().ref('trains').push(trainX);
// fetchData()
});
// function fetchData() {
database.ref('trains').on("child_added", function(childSnap){
var train = childSnap.val().formtrain;
var destination = childSnap.val().formdestination;
var stopFreq = childSnap.val().formfrequency;
var stopTime = childSnap.val().formstoptime;
console.log("train name " + train);
var convertTime = moment(stopTime, "hh:mm").subtract(1, "years");
console.log(convertTime);
var currentTime = moment();
console.log("current time: " + moment(currentTime).format("hh:mm a"));
$("#timer").text(currentTime.format("hh:mm a"));
var timeDifference = moment().diff(moment(convertTime), "minutes");
console.log("time difference: " + timeDifference);
var remainingTime = timeDifference % stopFreq;
console.log("Remaining time: " + remainingTime);
var nextTrainTime = stopFreq - remainingTime;
console.log("time until next train: " + nextTrainTime);
var nextTrain = moment().add(nextTrainTime, "minutes").format("hh:mm a");
console.log("next train: " + nextTrain);
$("#train-table > tbody").append("<tr><td>" + '<i class="fa fa-trash" id="trashcan" aria-hidden="true"></i>' + "</td><td>" + train + "</td><td>" + destination + "</td><td>" +
stopFreq + "</td><td>" + nextTrain + "</td><td>" + nextTrainTime + "</td></tr>");
});
// }
// fetchData();
// function updateTrain() {
// $("#train-table").empty();
// database.ref('trains').on("child_added", function(childSnap){
// var train = childSnap.val().formtrain;
// var destination = childSnap.val().formdestination;
// var stopFreq = childSnap.val().formfrequency;
// var stopTime = childSnap.val().formstoptime;
// console.log("train name " + train);
// var convertTime = moment(stopTime, "hh:mm").subtract(1, "years");
// console.log(convertTime);
// var currentTime = moment();
// console.log("current time: " + moment(currentTime).format("hh:mm a"));
// $("#timer").text(currentTime.format("hh:mm a"));
// var timeDifference = moment().diff(moment(convertTime), "minutes");
// console.log("time difference: " + timeDifference);
// var remainingTime = timeDifference % stopFreq;
// console.log("Remaining time: " + remainingTime);
// var nextTrainTime = stopFreq - remainingTime;
// console.log("time until next train: " + nextTrainTime);
// var nextTrain = moment().add(nextTrainTime, "minutes").format("hh:mm a");
// console.log("next train: " + nextTrain);
// $("#train-table > tbody").append("<tr><td>" + '<i class="fa fa-trash" id="trashcan" aria-hidden="true"></i>' + "</td><td>" + train + "</td><td>" + destination + "</td><td>" +
// stopFreq + "</td><td>" + nextTrain + "</td><td>" + nextTrainTime + "</td></tr>");
// });
// };
// setInterval(updateTrain, 6000);
|
9377834017689e990618d3af493e5a59b73965d8
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
tdoodchenko/Train-Scheduler
|
88f5971e554636053b79d03ca948281832b1d36a
|
8fe9bd09b8a98bbc307e63371d37483c257531b2
|
refs/heads/master
|
<file_sep>global.__base = __dirname + '/';
const express = require('express');
const bodyParser = require('body-parser');
const Boom = require('boom');
const errorsHelper = require('./utils/errors');
const jobsController = require('./controllers/jobs.controller');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// health check (public endpoint)
app.get('/', (req, res) => {
res.json({ msg: 'Hello world!' });
});
// define routes here
app.use(jobsController);
app.use((e, req, res, next) => {
console.error('[Error]', e);
let error = errorsHelper.createServiceError(e);
if (error.status === 401 && !error.isBoom) {
const message = 'Not authorized to perform the request';
error = Boom.unauthorized(message);
}
if (!error.isBoom) {
error = Boom.badImplementation();
}
res.status(error.output.statusCode).send(error.output);
});
module.exports = app;
<file_sep>
-- data: {
-- name: <string>,
-- description: <string>,
-- numVotes: <number>, // votes per item
-- maxVotes: <number>, // max votes per worker
-- reward: <number>, // how much we pay per vote
-- items_csv: <string>, // path to items file in the server
-- items_gold_csv: <string>, // path to gold items file in the server
-- design: <string>, // html/text content of the task
-- instructions, // html/text content for the instructions of the task
-- platform: <string> // to be defined better
-- }
-- CREATE TABLE job (
-- id bigserial NOT NULL,
-- created_at timestamp,
-- updated_at timestamp,
-- deleted_at timestamp,
-- id_requester bigint, -- to be NOT NULL
-- data JSONB,
-- CONSTRAINT pk_job PRIMARY KEY (id)
-- );<file_sep>const request = require('supertest');
const app = require(__base + 'app');
test('dummy test', () => {
expect(true).toBe(true);
})
// test('POST /jobs should return 400 if mandatory fields are not present', async () => {
// let response = await request(app).post('/jobs');
// expect(response.status).toBe(400);
// });
// test('POST /jobs should return 400 if reward is not present', async () => {
// let wrongJob = {
// data: {
// name: "<NAME>",
// items_csv: "some/path"
// }
// };
// let response = await request(app).post('/jobs').send(wrongJob);
// expect(response.status).toBe(400);
// });
// test('POST /jobs should return 201 ad the id have to be defined if the new job is created', async () => {
// let job = {
// data: {
// name: "<NAME>",
// reward: 0.12,
// items_csv: "some/path"
// }
// };
// let response = await request(app).post('/jobs').send(job);
// expect(response.status).toBe(201);
// expect(response.body.id).toBeDefined();
// });
<file_sep>const Boom = require('boom');
/**
* Returns a business error. The name property
* of the error object is set to "business".
*
* @param {String} msg
* @returns {Error}
*/
const createBusinessError = msg => {
let e = new Error(msg);
e.name = 'business';
return e;
};
/**
* Creates an error that the service layer returns. It uses the boom library.
*
* @param {Error} e An error object. The property name should be set
* to correctly perform the mapping from error to HTTP status code.
*/
const createServiceError = e => {
if (e.name == 'business') {
return Boom.badRequest(e.message);
}
return Boom.badImplementation();
};
module.exports = {
createBusinessError,
createServiceError
};
<file_sep>// this modules is responsible for allowing to publish HITs in
// any of the supported platforms. Also to implement any other
// functionality related to HITs.
const jobsDao = require(__base + 'dao/jobs.dao');
const errHandler = require(__base + 'utils/errors');
const publish = async () => {
// TODO
};
const createJob = async (job) => {
if (!(job instanceof Object)) {
throw errHandler.createBusinessError('Job not defined!');
}
if (!(job.data instanceof Object)) {
throw errHandler.createBusinessError('Job data not defined!');
}
if (job.data.name === undefined) {
throw errHandler.createBusinessError('Job name not defined!');
}
if (job.data.reward === undefined) {
throw errHandler.createBusinessError('Job reward not defined!');
}
if (job.data.items_csv === undefined) {
throw errHandler.createBusinessError('Items CSV path not defined!');
}
let newJob = await jobsDao.createJob(job);
return newJob;
};
module.exports = {
publish,
createJob
};<file_sep># slr-api
| master | develop |
|---------|-------------|
| [](https://travis-ci.com/TrentoCrowdAI/slr-api) | [](https://travis-ci.com/TrentoCrowdAI/slr-api) |
## status
Under development.
<file_sep>const db = require(__base + "db/index");
// create
const createJob = async (job) => {
let res = await db.query(
`insert into ${db.TABLES.Job}(created_at, data) values($1, $2) returning *`,
[new Date(), job.data]
);
return res.rows[0];
};
// get
// delete
// update
module.exports = {
createJob
};<file_sep>// this file exposes the logic implemented in jobs.delegate.js
// as services using express
const express = require('express');
const jobsDelegate = require(__base + 'delegates/jobs.delegate');
const router = express.Router();
// GET /jobs
// GET /jobs/<job id>
// POST /jobs
router.post('/jobs', async (req, res, next) => {
try {
let job = req.body;
let newJob = await jobsDelegate.createJob(job);
res.status(201).json(newJob);
} catch (e) {
// we delegate to the error-handling middleware
next(e);
}
});
// PUT /jobs/<job id>
// DELETE /jobs/<job id>
// POST /jobs/<job id>/publish
module.exports = router;
|
51052e82456b428fb246ddd9335d804e83b560b6
|
[
"JavaScript",
"SQL",
"Markdown"
] | 8 |
JavaScript
|
hexie2108/slr-api
|
63739176e4f07e9bfd8b612a18c1abf8aee0f047
|
0e0af8e48363f91c5d6452a5a4ada5b08c90b7c8
|
refs/heads/master
|
<file_sep>+++
location = "San Francisco"
published_at = 2012-07-09T17:58:52-07:00
slug = "heroku-workflow"
title = "The Heroku CLI's API Workflow"
+++
Ever wondered how the Heroku command line client accomplishes its work? We don't talk about it much, but the Heroku CLI isn't a black box, it's a fairly thin consumer of our own RESTful API, and that means everything you do in your day to day workflow on Heroku is available to work with in a programmatic fashion. The CLI even uses our own implementation of the API library called [heroku.rb](https://github.com/heroku/heroku.rb) (and by the way, heroku.rb is a great choice if you want to consume the API from Ruby).
A handy tool that we use here regularly is inspecting the CLI's workflow by telling Excon to send its output to standard out. Try it for yourself:
``` bash
EXCON_STANDARD_INSTRUMENTOR=true heroku list
```
Any calls that are implemented via heroku.rb make their requests using Excon, but a few of the older endpoints still use Restclient. If you run into one of these, you can do something very similar:
``` bash
RESTCLIENT_LOG=stdout heroku drains -a mutelight
```
<file_sep>package ucommon
import (
"fmt"
"os"
"path/filepath"
"strings"
)
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Constants
//
//
//
//////////////////////////////////////////////////////////////////////////////
const (
// AtomAuthorName is the name of the author to include in Atom feeds.
AtomAuthorName = "<NAME>"
// AtomAbsoluteURL is the absolute URL to use when generating Atom feeds.
AtomAbsoluteURL = "https://mutelight.org"
// AtomTag is a stable constant to use in Atom tags.
AtomTag = "mutelight.org"
// LayoutsDir is the source directory for view layouts.
LayoutsDir = "./layouts"
// MainLayout is the site's main layout.
MainLayout = LayoutsDir + "/main.ace"
// TitleSuffix is the suffix to add to the end of page and Atom titles.
TitleSuffix = " — mutelight.org"
// ViewsDir is the source directory for views.
ViewsDir = "./views"
)
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Functions
//
//
//
//////////////////////////////////////////////////////////////////////////////
// ExitWithError prints the given error to stderr and exits with a status of 1.
func ExitWithError(err error) {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
// ExtractSlug gets a slug for the given filename by using its basename
// stripped of file extension.
func ExtractSlug(source string) string {
return strings.TrimSuffix(filepath.Base(source), filepath.Ext(source))
}
<file_sep>+++
location = "Calgary"
published_at = 2009-11-10T00:00:00-07:00
slug = "new-net-4-feature-enum-hasflag"
tiny_slug = "21"
title = "New .NET 4.0 Feature: Enum.HasFlag()"
+++
A minor inclusion to the new .NET 4.0 framework is the addition of the `Enum.HasFlag()` method. It behaves much like you'd expect, allowing you to check whether an enum instance contains a given flag.
``` cs
[Flags]
public enum PacketOptions
{
None = 0x00,
All = 0xff,
Compressed = 0x01,
Encrypted = 0x02,
}
PacketOptions opts = PacketOptions.All;
Assert.That(opts.HasFlag(PacketOptions.Compressed), Is.True);
```
Previously, flag testing was done using `(opts & PacketOptions.Compressed) != 0`, which was a little awkward because the `!=` operator has higher precedence than `&`, hence the extraneous parenthesis.
If you'd attempted to implement your own `HasFlag` extension method, you'd have realized that it was not possible due to the way C# handles its type constraints (yep, I've been there).
Discovered via [Reed Copsey](http://reedcopsey.com/?p=77).
<file_sep>package main
import (
"fmt"
"html/template"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
texttemplate "text/template"
"time"
"github.com/yosssi/ace"
"golang.org/x/xerrors"
"github.com/brandur/modulir"
"github.com/brandur/modulir/modules/mace"
"github.com/brandur/modulir/modules/matom"
"github.com/brandur/modulir/modules/mfile"
"github.com/brandur/modulir/modules/mmarkdownext"
"github.com/brandur/modulir/modules/mtemplate"
"github.com/brandur/modulir/modules/mtemplatemd"
"github.com/brandur/modulir/modules/mtoml"
"github.com/brandur/mutelight/modules/ucommon"
)
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Variables
//
//
//
//////////////////////////////////////////////////////////////////////////////
// These are all objects that are persisted between build loops so that if
// necessary we can rebuild jobs that depend on them like index pages without
// reparsing all the source material. In each case we try to only reparse the
// sources if those source files actually changed.
var (
articles []*Article
)
// A function map of template helpers which is the combined version of the maps
// from ftemplate, mtemplate, and mtemplatemd.
var htmlTemplateFuncMap template.FuncMap = mtemplate.CombineFuncMaps(
mtemplate.FuncMap,
mtemplatemd.FuncMap,
)
// Same as above, but for text templates.
var textTemplateFuncMap texttemplate.FuncMap = mtemplate.HTMLFuncMapToText(htmlTemplateFuncMap)
// List of common build dependencies, a change in any of which will trigger a
// rebuild on everything: partial views, JavaScripts, and stylesheets. Even
// though some of those changes will false positives, these sources are
// pervasive enough, and changes infrequent enough, that it's worth the
// tradeoff. This variable is a global because so many render functions access
// it.
var universalSources []string
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Init
//
//
//
//////////////////////////////////////////////////////////////////////////////
func init() {
mmarkdownext.FuncMap = textTemplateFuncMap
}
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Build function
//
//
//
//////////////////////////////////////////////////////////////////////////////
func build(c *modulir.Context) []error {
//
// PHASE 0: Setup
//
// (No jobs should be enqueued here.)
//
c.Log.Debugf("Running build loop")
// This is where we stored "versioned" assets like compiled JS and CSS.
// These assets have a release number that we can increment and by
// extension quickly invalidate.
versionedAssetsDir := path.Join(c.TargetDir, "assets", Release)
// A set of source paths that rebuild everything when any one of them
// changes. These are dependencies that are included in more or less
// everything: common partial views, JavaScript sources, and stylesheet
// sources.
universalSources = nil
// Generate a list of partial views to add to universal sources.
{
sources, err := mfile.ReadDirCached(c, c.SourceDir+"/views",
&mfile.ReadDirOptions{ShowMeta: true})
if err != nil {
return []error{err}
}
var partialViews []string
for _, source := range sources {
if strings.HasPrefix(filepath.Base(source), "_") {
partialViews = append(partialViews, source)
}
}
universalSources = append(universalSources, partialViews...)
}
// Generate a set of stylesheet sources to add to universal sources.
{
stylesheetSources, err := mfile.ReadDirCached(c, c.SourceDir+"/content/stylesheets",
&mfile.ReadDirOptions{ShowMeta: true})
if err != nil {
return []error{err}
}
universalSources = append(universalSources, stylesheetSources...)
}
//
// PHASE 1
//
// The build is broken into phases because some jobs depend on jobs that
// ran before them. For example, we need to parse all our article metadata
// before we can create an article index and render the home page (which
// contains a short list of articles).
//
// After each phase, we call `Wait` on our context which will wait for the
// worker pool to finish all its current work and restart it to accept new
// jobs after it has.
//
// The general rule is to make sure that work is done as early as it
// possibly can be. e.g. Jobs with no dependencies should always run in
// phase 1. Try to make sure that as few phases as necessary.
//
{
commonDirs := []string{
c.TargetDir + "/a",
versionedAssetsDir,
}
for _, dir := range commonDirs {
err := mfile.EnsureDir(c, dir)
if err != nil {
return []error{nil}
}
}
}
//
// Symlinks
//
{
commonSymlinks := [][2]string{
{c.SourceDir + "/content/images", c.TargetDir + "/assets/images"},
{c.SourceDir + "/content/javascripts", versionedAssetsDir + "/javascripts"},
{c.SourceDir + "/content/stylesheets", versionedAssetsDir + "/stylesheets"},
}
for _, link := range commonSymlinks {
err := mfile.EnsureSymlink(c, link[0], link[1])
if err != nil {
return []error{nil}
}
}
}
//
// Articles
//
var articlesChanged bool
var articlesMu sync.Mutex
{
sources, err := mfile.ReadDirCached(c, c.SourceDir+"/content/articles", nil)
if err != nil {
return []error{err}
}
for _, s := range sources {
source := s
name := fmt.Sprintf("article: %s", filepath.Base(source))
c.AddJob(name, func() (bool, error) {
return renderArticle(c, source,
&articles, &articlesChanged, &articlesMu)
})
}
}
//
// Robots.txt
//
{
c.AddJob("robots.txt", func() (bool, error) {
return renderRobotsTxt(c)
})
}
//
//
//
// PHASE 2
//
//
//
if errors := c.Wait(); errors != nil {
c.Log.Errorf("Cancelling next phase due to build errors")
return errors
}
// Various sorts for anything that might need it.
{
sortArticles(articles)
}
// Index
{
c.AddJob("index", func() (bool, error) {
return renderIndex(c, articles, articlesChanged)
})
}
//
// Articles
//
// Articles index (archive)
{
c.AddJob("articles index (Archive)", func() (bool, error) {
return renderArticlesIndex(c, articles, articlesChanged)
})
}
// Articles feed
{
c.AddJob("articles feed", func() (bool, error) {
return renderArticlesFeed(c, articles, articlesChanged)
})
}
return nil
}
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Types
//
//
//
//////////////////////////////////////////////////////////////////////////////
// Article represents an article to be rendered.
type Article struct {
// Content is the HTML content of the article. It isn't included as TOML
// frontmatter, and is rather split out of an article's Markdown file,
// rendered, and then added separately.
Content string `toml:"-"`
// Location is the place where the article was published. It may be empty.
Location string `toml:"location"`
// PublishedAt is when the article was published.
PublishedAt *time.Time `toml:"published_at"`
// Slug is a unique identifier for the article that also helps determine
// where it's addressable by URL.
Slug string `toml:"-"`
// TinySlug is a short URL assigned to the article at `/a/<tiny slug>`
// which redirects to the main article.
//
// This was almost certainly something that was never needed, but I added
// it way back near 2010 when I was obsessed with URL shorteners, one of
// the internet's worst ideas.
TinySlug string `toml:"tiny_slug"`
// Title is the article's title.
Title string `toml:"title"`
}
func (a *Article) validate(source string) error {
if a.Title == "" {
return xerrors.Errorf("no title for article: %v", source)
}
if a.PublishedAt == nil {
return xerrors.Errorf("no publish date for article: %v", source)
}
return nil
}
// articleYear holds a collection of articles grouped by year.
type articleYear struct {
Year int
Articles []*Article
}
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Private
//
//
//
//////////////////////////////////////////////////////////////////////////////
// getAceOptions gets a good set of default options for Ace template rendering
// for the project.
func getAceOptions(dynamicReload bool) *ace.Options {
options := &ace.Options{FuncMap: htmlTemplateFuncMap}
if dynamicReload {
options.DynamicReload = true
}
return options
}
// Gets a map of local values for use while rendering a template and includes
// a few "special" values that are globally relevant to all templates.
func getLocals(title string, locals map[string]interface{}) map[string]interface{} {
defaults := map[string]interface{}{
"GoogleAnalyticsID": conf.GoogleAnalyticsID,
"MetaDescription": "",
"Release": Release,
"MutelightEnv": conf.MutelightEnv,
"Title": title,
"TitleSuffix": ucommon.TitleSuffix,
}
for k, v := range locals {
defaults[k] = v
}
return defaults
}
func groupArticlesByYear(articles []*Article) []*articleYear {
var year *articleYear
var years []*articleYear
for _, article := range articles {
if year == nil || year.Year != article.PublishedAt.Year() {
year = &articleYear{article.PublishedAt.Year(), nil}
years = append(years, year)
}
year.Articles = append(year.Articles, article)
}
return years
}
func insertOrReplaceArticle(articles *[]*Article, article *Article) {
for i, a := range *articles {
if article.Slug == a.Slug {
(*articles)[i] = article
return
}
}
*articles = append(*articles, article)
}
func renderArticle(c *modulir.Context, source string,
articles *[]*Article, articlesChanged *bool, mu *sync.Mutex) (bool, error) {
sourceChanged := c.Changed(source)
viewsChanged := c.ChangedAny(append(
[]string{
ucommon.MainLayout,
ucommon.ViewsDir + "/articles/show.ace",
},
universalSources...,
)...)
if !sourceChanged && !viewsChanged {
return false, nil
}
var article Article
data, err := mtoml.ParseFileFrontmatter(c, source, &article)
if err != nil {
return true, err
}
err = article.validate(source)
if err != nil {
return true, err
}
article.Slug = ucommon.ExtractSlug(source)
content, err := mmarkdownext.Render(string(data), &mmarkdownext.RenderOptions{NoRetina: true})
if err != nil {
return true, err
}
article.Content = content
locals := getLocals(article.Title, map[string]interface{}{
"Article": article,
})
// Always use force context because if we made it to here we know that our
// sources have changed.
err = mace.RenderFile(c, ucommon.MainLayout, ucommon.ViewsDir+"/articles/show.ace",
path.Join(c.TargetDir, article.Slug), getAceOptions(viewsChanged), locals)
if err != nil {
return true, err
}
// Ideally, this would be an actual redirect, but the combination of S3 +
// CloudFront makes those somewhat difficult. Also, these should never
// really get used from anywhere anymore so it doesn't actually matter that
// much.
if article.TinySlug != "" {
filename := path.Join(c.TargetDir, "a", article.TinySlug)
err := ioutil.WriteFile(
filename,
[]byte(fmt.Sprintf(
`<!DOCTYPE html><html>please click through to: <strong><a href="/%s">/%s</a></strong></html>`,
article.Slug, article.Slug,
)),
0o600,
)
if err != nil {
return true, xerrors.Errorf("error writing file '%s': %w", filename, err)
}
}
mu.Lock()
insertOrReplaceArticle(articles, &article)
*articlesChanged = true
mu.Unlock()
return true, nil
}
func renderArticlesFeed(c *modulir.Context, articles []*Article, articlesChanged bool) (bool, error) {
if !articlesChanged {
return false, nil
}
return renderFeed(c, "articles", "Articles", articles)
}
func renderArticlesIndex(c *modulir.Context, articles []*Article, articlesChanged bool) (bool, error) {
viewsChanged := c.ChangedAny(append(
[]string{
ucommon.MainLayout,
ucommon.ViewsDir + "/articles/index.ace",
},
universalSources...,
)...)
if !articlesChanged && !viewsChanged {
return false, nil
}
articlesByYear := groupArticlesByYear(articles)
locals := getLocals("Articles", map[string]interface{}{
"ArticlesByYear": articlesByYear,
})
return true, mace.RenderFile(c, ucommon.MainLayout, ucommon.ViewsDir+"/articles/index.ace",
c.TargetDir+"/archive", getAceOptions(viewsChanged), locals)
}
func renderFeed(_ *modulir.Context, slug, title string, articles []*Article) (bool, error) {
filename := slug + ".atom"
title += ucommon.TitleSuffix
feed := &matom.Feed{
Title: title,
ID: "tag:" + ucommon.AtomTag + ",2009:/" + slug,
Links: []*matom.Link{
{Rel: "self", Type: "application/atom+xml", Href: ucommon.AtomAbsoluteURL + "/" + filename},
{Rel: "alternate", Type: "text/html", Href: ucommon.AtomAbsoluteURL},
},
}
if len(articles) > 0 {
feed.Updated = *articles[0].PublishedAt
}
for i, article := range articles {
if i >= conf.NumAtomEntries {
break
}
atomEntry := &matom.Entry{
Title: article.Title,
Content: &matom.EntryContent{Content: article.Content, Type: "html"},
Published: *article.PublishedAt,
Updated: *article.PublishedAt,
Link: &matom.Link{Href: conf.AbsoluteURL + article.Slug},
ID: "tag:" + ucommon.AtomTag + "," + article.PublishedAt.Format("2006-01-02") + ":/" + article.Slug,
AuthorName: ucommon.AtomAuthorName,
AuthorURI: conf.AbsoluteURL,
}
feed.Entries = append(feed.Entries, atomEntry)
}
f, err := os.Create(path.Join(conf.TargetDir, filename))
if err != nil {
return true, xerrors.Errorf("error creating file '%s': %w", filename, err)
}
defer f.Close()
return true, feed.Encode(f, " ")
}
func renderIndex(c *modulir.Context, articles []*Article, articlesChanged bool) (bool, error) {
viewsChanged := c.ChangedAny(append(
[]string{
ucommon.MainLayout,
ucommon.ViewsDir + "/index.ace",
},
universalSources...,
)...)
if !articlesChanged && !viewsChanged {
return false, nil
}
// Cut off the number of items on the main page at some point.
const numTopArticles = 10
var topArticles []*Article
for i := 0; i < numTopArticles; i++ {
if i >= len(articles) {
break
}
topArticles = append(topArticles, articles[i])
}
locals := getLocals("Mutelight", map[string]interface{}{
"TopArticles": topArticles,
})
return true, mace.RenderFile(c, ucommon.MainLayout, ucommon.ViewsDir+"/index.ace",
c.TargetDir+"/index.html", getAceOptions(viewsChanged), locals)
}
func renderRobotsTxt(c *modulir.Context) (bool, error) {
if !c.FirstRun && !c.Forced {
return false, nil
}
var content string
if conf.Drafts {
// Allow Twitterbot so that we can preview card images on dev.
//
// Disallow everything else.
content = `User-agent: Twitterbot
Disallow:
User-agent: *
Disallow: /
`
}
filename := c.TargetDir + "/robots.txt"
outFile, err := os.Create(filename)
if err != nil {
return true, xerrors.Errorf("error creating file '%s': %w", filename, err)
}
if _, err := outFile.WriteString(content); err != nil {
return true, xerrors.Errorf("error writing file '%s': %w", filename, err)
}
outFile.Close()
return true, nil
}
func sortArticles(articles []*Article) {
sort.Slice(articles, func(i, j int) bool {
return articles[j].PublishedAt.Before(*articles[i].PublishedAt)
})
}
<file_sep>+++
location = "Calgary"
published_at = 2011-03-28T00:00:00-06:00
slug = "practical-tmux"
tiny_slug = "42"
title = "Practical Tmux"
+++
Today I switched over completely from GNU Screen to the more modern BSD-licensed alternative, **tmux**. After making sure that tmux had replacements for all Screen's key features, I took the plunge, and haven't looked back. The [project's webpage](http://tmux.sourceforge.net/) has a complete list of features available under tmux, but as an everyday user of Screen, here are the major reasons I switched:
* **Better redraw model:** I use Awesome WM, a tiling window manager, and terminals containing Screen sessions would glitch out regularly; spewing all kinds of artifacts into their windows. Sufficed to say, tmux doesn't do this.
* **Screen contents persisted through full-screen programs:** in Screen, you lose your terminal's previous contents after leaving a full-screen program like an editor. Tmux doesn't have this problem.
* **Rational configuration:** I once tried to configure my screen's status line, and eventually just gave up. In comparison, tmux's lines like `set -g status-right "#[fg=green]#H` are almost a little _too_ easy. This goes for other configuration values as well.
* **Visual bell that works:** one of the only things under Linux that's come close to driving me completely crazy is the line _Wuff -- Wuff!!_. I mean, I'm all good with programmers having a sense of humour, but this is just too much. Even after disabling the visual bell and doing away with this default message, it's tragically not possible to remove the visual bell from Screen completely.
* **Automatic window renaming:** windows are renamed automatically to the command running in them unless their name has been manually changed using `C-a ,`.
* **Vertical splits:** it's always been a mystery that Screen can do horizontal screen splits but not vertical without fancy patches. Tmux does both out of the box.
* **VI key bindings in copy mode:** VI or Emacs keys are available upon entering tmux's copy mode.
* **Runtime configuration:** you can easily open a prompt in tmux to apply configuration to a running session.
Common Problems and Solutions
-----------------------------
All that said, unfortunately tmux isn't completely convention over configuration, and it took a bit of work to get running exactly how I wanted. The purpose of this post is to go over some common tmux problems and their solutions.
### C-b
Now there's a prefix that you have to reach for! Fix this in `~/.tmux.conf` by changing it to `C-a`:
```
set-option -g prefix C-a
```
### C-a C-a for the Last Active Window
This was a feature in Screen that was great enough to keep around. Add the following to `~/.tmux.conf`:
```
bind-key C-a last-window
```
### Command Sequence for Nested Tmux Sessions
Often I'll run a multiplexer inside another multiplexer and need a command sequence to send things to the inner session. In Screen, this could be accomplished using `C-a a <command>`. This doesn't work out of the box in tmux, but can be fixed with a little configuration.
```
bind-key a send-prefix
```
### Start Window Numbering at 1
Zero-based indexing is sure great in programming languages, but not so much in terminal multiplexers where that zero is all the way on the other side of the keyboard.
```
set -g base-index 1
```
### Faster Command Sequences
Upon starting to use tmux, I noticed that I had to add a noticeable delay between two characters in a command sequence for it to recognize the command, for example between the `C-a` and `n` in `C-a n`. This is because tmux is waiting for an escape sequence. Fix that by setting escape time to zero.
```
set -s escape-time 0
```
### Aggressive Resize
By default, all windows in a session are constrained to the size of the smallest client connected to that session, even if both clients are looking at different windows. It seems that in this particular case, Screen has the better default where a window is only constrained in size if a smaller client is actively looking at it. This behaviour can be fixed by setting tmux's `aggressive-resize` option.
```
setw -g aggressive-resize on
```
### Multiple Clients Sharing One Session
Screen and tmux's behaviour for when multiple clients are attached to one session differs slightly. In Screen, each client can be connected to the session but view different windows within it, but in tmux, all clients connected to one session _must_ view the same window.
This problem can be solved in tmux by spawning two separate sessions and synchronizing the second one to the windows of the first. This is accomplished by first issuing a new session:
```
tmux new -s <base session>
```
Then pointing a second new session to the first:
```
tmux new-session -t <base session> -s <new session>
```
However, this usage of tmux results in the problem that detaching from these mirrored sessions will start to litter your system with defunct sessions which can only be cleaned up with some pretty extreme micromanagement. I wrote a script to solve this problem, call it `tmx` and use it simply with `tmx <base session name>`.
``` bash
#!/bin/bash
#
# Modified TMUX start script from:
# http://forums.gentoo.org/viewtopic-t-836006-start-0.html
#
# Store it to `~/bin/tmx` and issue `chmod +x`.
#
# Works because bash automatically trims by assigning to variables and by
# passing arguments
trim() { echo $1; }
if [[ -z "$1" ]]; then
echo "Specify session name as the first argument"
exit
fi
# Only because I often issue `ls` to this script by accident
if [[ "$1" == "ls" ]]; then
tmux ls
exit
fi
base_session="$1"
# This actually works without the trim() on all systems except OSX
tmux_nb=$(trim `tmux ls | grep "^$base_session" | wc -l`)
if [[ "$tmux_nb" == "0" ]]; then
echo "Launching tmux base session $base_session ..."
tmux new-session -s $base_session
else
# Make sure we are not already in a tmux session
if [[ -z "$TMUX" ]]; then
# Kill defunct sessions first
old_sessions=$(tmux ls 2>/dev/null | egrep "^[0-9]{14}.*[0-9]+\)$" | cut -f 1 -d:)
for old_session_id in $old_sessions; do
tmux kill-session -t $old_session_id
done
echo "Launching copy of base session $base_session ..."
# Session is is date and time to prevent conflict
session_id=`date +%Y%m%d%H%M%S`
# Create a new session (without attaching it) and link to base session
# to share windows
tmux new-session -d -t $base_session -s $session_id
# Create a new window in that session
#tmux new-window
# Attach to the new session
tmux attach-session -t $session_id
# When we detach from it, kill the session
tmux kill-session -t $session_id
fi
fi
```
<span class="addendum">Edit (2011/04/01) --</span> added new script logic so that defunct sessions are killed before starting a new one. Defunct sessions are left behind when tmux isn't quit explicitly.
<span class="addendum">Edit (2011/07/21) --</span> added configuration and the `tmx` script to my [tmux-extra repository](https://github.com/brandur/tmux-extra) on GitHub for more convenient access.
### Complete .tmux.conf
Here's my complete `.tmux.conf` for reference.
``` sh
# C-b is not acceptable -- Vim uses it
set-option -g prefix C-a
bind-key C-a last-window
# Start numbering at 1
set -g base-index 1
# Allows for faster key repetition
set -s escape-time 0
# Set status bar
set -g status-bg black
set -g status-fg white
set -g status-left ""
set -g status-right "#[fg=green]#H"
# Rather than constraining window size to the maximum size of any client
# connected to the *session*, constrain window size to the maximum size of any
# client connected to *that window*. Much more reasonable.
setw -g aggressive-resize on
# Allows us to use C-a a <command> to send commands to a TMUX session inside
# another TMUX session
bind-key a send-prefix
# Activity monitoring
#setw -g monitor-activity on
#set -g visual-activity on
# Example of using a shell command in the status line
#set -g status-right "#[fg=yellow]#(uptime | cut -d ',' -f 2-)"
# Highlight active window
set-window-option -g window-status-current-bg red
```
<file_sep>+++
location = "San Francisco"
published_at = 2012-09-02T20:18:29-07:00
slug = "backbone-http-basic-auth"
title = "HTTP Basic Authentication with Backbone"
+++
I recently ran across a situation where I needed to call down to an HTTP basic authenticated API in a Backbone app. Short of doing some hacking of the source, Backbone doesn't provide an easy way to accomplish this, so here's one simple option for your perusal.
Backbone relies on the inclusion of jQuery or Zepto in your project to provide the underlying infrastructure for making AJAX calls. If you're using jQuery, there's a function called `$.ajaxSetup` that will set options before every AJAX call. Use it to set the `Authorization` header (_warning: CoffeeScript_):
``` coffee
$.ajaxSetup
headers:
Authorization: "Basic #{toBase64(":secret-api-password")}"
```
Under HTTP basic, both the user and password need to be base64 encoded before being sent along to the server. JavaScript doesn't provide utilities to handle that out of the box, so the `toBase64` function above needs to be implemented to get this example running.
A nice option is [CryptoJS](http://code.google.com/p/crypto-js/). Download the package and include the following files in your project:
* `core.js`
* `enc-base64.js`
Now you're ready to implement `toBase64` and complete this example:
``` coffee
toBase64 = (str) ->
words = CryptoJS.enc.Latin1.parse(str)
CryptoJS.enc.Base64.stringify(words)
```
<file_sep>+++
location = "Calgary"
published_at = 2009-03-09T00:00:00-06:00
slug = "pretty-uris-with-google-app-engine"
tiny_slug = "4"
title = "Pretty URIs with Google App Engine"
+++
Getting pretty URI/URLs in Google app engine is easy, but the first time I looked I wasn't able to figure out how to do it from Google's documentation, so I've saved some instructions here.
The first step is to add in some regex capture groups when sending your URIs to `WSGIApplication`. The code below specifies that `ScoreHandler` can receive either one argument like `/game/<game_id>/score` or two arguments like `/game/<game_id>/score/<score_id>`.
``` python
from google.appengine.ext import webapp
from handlers.score_handler import ScoreHandler
from wsgiref.handlers import CGIHandler
def main():
application = webapp.WSGIApplication([
(r'/game/(.+)/score/(.+)', ScoreHandler),
(r'/game/(.+)/score', ScoreHandler),
], debug=True)
CGIHandler().run(application)
if __name__ == '__main__':
main()
```
When one of these URI expressions is hit, `WSGIApplication` will expect to find a function in the corresponding handler with a number of arguments equal to the number of regex groups that were matched.
``` python
from google.appengine.ext import webapp
class ScoreHandler(webapp.RequestHandler):
# Receives one or two arguments, depending on which URI
# was accessed
def get(self, game_id, score_id=None):
self.response.out.write(
"game_id = %s, score_id = %s" % (game_id, score_id)
)
```
As shown above, we can also map multiple URIs with different numbers of regex capture groups to the same handler class by providing a function with default arguments. In this example, if `/game/2/score` was hit, `game_id` would have a value of 2 while `score_id` would be `None`. If `/game/2/score/3` was hit, `game_id` would be 2 and `score_id` would be 3.
<file_sep>+++
location = "Calgary"
published_at = 2010-11-25T00:00:00-07:00
slug = "the-most-ambitious-girl-at-work"
tiny_slug = "31"
title = "The Most Ambitious Girl at Work"
+++
Ambition and the work place go hand in hand, but when we're speaking of ambition, we're often talking about a negative form of it. It brings to mind hotshots who play "the game", immersing themselves deeply in office politics to pull ahead into that new management positions or get sent to that next big conference in Florida.
There's good ambition too. The most ambitious girl at work leaves the company today, but under good terms and going on to new and far better things. She went to university and got a degree in computer science and had good long-term prospects in project management, but her ambition was never to climb the corporate ladder, it was to open a dance studio. Saying that she followed her dreams might sound like a cliche, but that's exactly what she did.
The dance studio isn't a blind venture. She's worked on promoting herself within the dance community for years now, and has managed to attract some of the premiere instructors in Calgary. She's been handling logistics in her spare time, and renovations on her new space will be finished by February. I only got a short run down of her marketing strategy, but she's leveraging social media as well as more traditional forms of promotion. I liken her to Andy in _the Shawshank Redemption_ where the guards find his cell empty, only to further discover that he's been building a means to escape for years without anyone realizing it.
Alberta may be one of the best places on Earth to start a small business, between extremely low sales tax, generous tax laws for small business, [SRED](http://en.wikipedia.org/wiki/Scientific_Research_and_Experimental_Development_Tax_Credit_Program), and universal health care (those last two are good for all of Canada), the benefits are very real and the risk is reduced compared to elsewhere. I talk a lot about startups, and I've had two coworkers in my group alone quit in the last years to persue their own ventures. I'm running out of excuses. Everyone in Alberta should be running a small business.
See the emergence of something great at [Pulse Studios](http://www.pulsestudios.ca/).
<file_sep>+++
location = "Calgary"
published_at = 2009-02-22T00:00:00-07:00
slug = "the-power-of-a-name"
tiny_slug = "2"
title = "The Power of a Name"
+++
People looking for quick introduction for good social habits (like me) will often start by reading <NAME>'s famous book _How to Win Friends and Influence People_. It's an old book, first published in 1936, but every bit of its material still applies today, and will continue to apply as long as humans communicate.
Today, I'd like to draw attention to what I think is one of the book's most important points:
p(quote). Remember that a person's name is to that person the sweetest and most important sound in any language.
People love hearing their own name; this applies to everyone all the way from introverts to hardened social veterans. You'll never see much evidence of this, so to make yourself believe it, consider carefully how you react to your own name.
Remember People's Names
-----------------------
One of the major changes I've made to my behaviour in recent months is to always make sure I never need to ask for a person's name a second time. What this means for me, due to my terrible memory for names, is that I write down the names of every person I meet.
The importance of remembering a person's name after first meeting them should never be underestimated. A person with an easy-to-remember name will appreciate your attention to detail, and a person with a hard-to-remember name will be flattered that you remembered theirs. Remembering names is _such_ an easy way to establish good relations with people early on.
Use Names in Conversation
-------------------------
Think back to someone you've known in your life who is really good with people, and I mean _really_ good, a real leader of men. Many years ago I worked at at a popular restaurant under a manager named Richard. Richard had a way with people, and could make almost anyone like him and/or come around to his point of view, definitely useful skills when you're managing a very busy restaurant. He had a variety of techniques he'd use to to win people over, and one of those techniques was to address each of those people by their name everytime he saw them. By doing this, he was making each of those people feel important in a subtle way. If you think back to real leaders you've known, you'll probably realize that many of them were doing exactly the same thing.
Don't be afraid to use someone's name when you're speaking to them one-on-one, even if you know them well. If it's someone you don't know very well, remember to cleary enunciate their name, don't let it come out awkwardly. In general, always make sure you're holding up your end of the conversation by speaking confidently.
<file_sep>+++
location = "San Francisco"
published_at = 2012-07-03T21:46:23-07:00
slug = "406-415"
title = "406, 415, and API Formatting"
+++
While working on getting our API restructured, I had to lookup how we want to respond to a client who has requested a format that we don't support. Is it a `406`? A `415`? Here are some plain English explanations:
* `406 Not acceptable` -- In the context of format, when the server can't (or won't) respond in the format that the client has requested. This requested format could come in via an `Accept` header or an extension in the path.
* `415 Unsupported media type` -- when the client has sent content in a request body that the server doesn't support. This would occur during a `POST` or `PUT` and may be described by the `Content-Type` header.
A user on Stack Overflow puts it as succinctly as possible: ["406 when you can't send what they want, and 415 when they send what you don't want."](http://stackoverflow.com/a/3294567).
<file_sep># mutelight [](https://github.com/brandur/mutelight/actions)
The source for my ancient blog Mutelight, reclaimed from [a previous dynamic project](https://github.com/brandur/mutelight-v2), and remade into a static site powered by [Modulir](https://github.com/brandur/modulir). Online at [mutelight.org](https://mutelight.org).
``` sh
cp .envrc.sample .envrc
direnv allow
make compile && make loop
```
<file_sep>+++
location = "Calgary"
published_at = 2009-06-02T00:00:00-06:00
slug = "the-anatomy-of-a-nant-build-file"
tiny_slug = "10"
title = "The Anatomy of a NAnt Build File"
+++
Over the weekend I was looking at building a simple NAnt file layout that I could use for building one of my projects. Previously, I'd considered NAnt files to be problematical because they have a tendency of evolving into unmanageable behemoths that are thousands of lines long. For example, the build file we use at my day job is a little over 2600 lines and has a layout like this:
``` xml
<project name="Unmanageable" default="build">
...
<target name="build">
<call target="buildProject1" />
<call target="buildProject2" />
<call target="buildProject3" />
</target>
...
<target name="buildProject1">
<csc target="library" output="buildProject1.dll">
<sources>
<include name="**/*.cs" />
</sources>
<references>
<include name="System.dll" />
...
</references>
</csc>
</target>
<target name="buildProject2" depends="buildProject1">
...
</target>
<target name="buildProject3"
depends="buildProject1, buildProject2">
...
</target>
</project>
```
Add in 30 or 40 other projects and about 100 lines worth of property definitions and before you know it you've got a file that will turn developers pale at its very mention. That might not be so bad, but because of the way references have to be entered manually under the `<csc>` tag, everytime you update a reference under one of your projects, it has to be added to the build file as well; so the build file ends up being updated constantly.
Not wanting to run into this problem in my own projects, I started looking for a better way to build projects, and quickly discovered the NAnt [`<solution>` task (NAnt solution task documentation)](http://nant.sourceforge.net/nightly/latest/help/tasks/solution.html). This task can theoretically read a solution or project file, build dependencies, then build the file's target; thus working around the normal NAnt "creep". Sounds great, but it only supports VS 2002 and 2003 solution files, so in practice it's not much use.
MSBuild
-------
With the release of Visual Studio 2005, Microsoft started to include a new build tool called [MSBuild (MSBuild documentation)](http://msdn.microsoft.com/en-us/library/0k6kkbsd.aspx). In its most basic form, the MSBuild command can be used with a few command line switches to build a VS solution or project: `MSBuild "path/Project.csproj" /v:n /t:Build /p:Configuration=release;OutDir="path/bin/"`
MSBuild is more than just a command though; it can also be used to read an MSBuild file written in XML to follow much more complex sets of instructions in a similar fashion to NAnt. I haven't had the chance to explore it fully, but I hope to do a future post comparing its features and ease-of-use to NAnt's.
For now, I found that calling the MSBuild executable from my NAnt scripts acts like a drop-in replacement for NAnt's `<solution>` task with one important difference -- MSBuild works.
A NAnt Solution
---------------
Without further ado, I'd like to present a template that I've been using for my projects that can build multiple application targets using MSBuild, and as you'd expect, has testing targets.
``` xml
<project name="BrandursExcellentTemplate" default="rebuild">
<!-- ============= -->
<!-- Configuration -->
<!-- ============= -->
<!-- Build as: release, debug, etc. -->
<property name="configuration" value="release" />
<!-- Output directory where our executables should be written to -->
<property name="bin-directory" value="${directory::get-current-directory()}/bin/" />
<!-- Location of the MSBuild executable, we use this to build projects -->
<property name="msbuild" value="${framework::get-framework-directory(framework::get-target-framework())}\MSBuild.exe" />
<!-- ============ -->
<!-- Main Targets -->
<!-- ============ -->
<target name="clean" description="Delete all previously compiled binaries.">
<delete>
<fileset>
<include name="**/bin/**" />
<include name="**/obj/**" />
<include name="**/*.suo" />
<include name="**/*.user" />
</fileset>
</delete>
</target>
<target name="build" description="Build all application targets.">
<mkdir dir="${bin-directory}" />
<!-- Neither of these are secondary projects like -->
<!-- libraries, they are executable projects. Their -->
<!-- dependency projects will be built for us by -->
<!-- MSBuild automatically. -->
<call target="build.app1" />
<call target="build.app2" />
</target>
<target name="rebuild" depends="clean, build" />
<target name="test" description="Build test project and run all tests.">
<mkdir dir="${bin-directory}" />
<call target="build.tests" />
<nunit2>
<formatter type="Plain" />
<test assemblyname="${bin-directory}/Test.dll" />
</nunit2>
</target>
<target name="testimmediate" description="Build test project and run all tests.">
<mkdir dir="${bin-directory}" />
<call target="build.tests" />
<nunit2>
<formatter type="Plain" />
<test>
<assemblies>
<include name="${bin-directory}/Test.dll" />
</assemblies>
<categories>
<include name="Immediate" />
</categories>
</test>
</nunit2>
</target>
<!-- ================= -->
<!-- Secondary Targets -->
<!-- ================= -->
<target name="build.app1">
<exec program="${msbuild}" commandline='"src/App1/App1.csproj" /v:n /nologo /t:Build /p:Configuration=${configuration};OutDir="${directory::get-current-directory()}/bin/"' />
</target>
<target name="build.app2">
<exec program="${msbuild}" commandline='"src/App2/App2.csproj" /v:n /nologo /t:Build /p:Configuration=${configuration};OutDir="${directory::get-current-directory()}/bin/"' />
</target>
<target name="build.tests">
<!-- Do not build verbosely (/v:q), user wants to see test results, not build output -->
<exec program="${msbuild}" commandline='"src/Test/Test.csproj" /v:q /nologo /t:Build /p:Configuration=Debug;OutDir="${directory::get-current-directory()}/bin/"' />
</target>
</project>
```
One part of the template I'll comment on is the `testimmediate` target. At work, we used to categorize all our tests using NUnit's category feature, but found over time that we weren't gaining a whole lot of value from the process. Instead of letting categories go to waste, my boss came up with the idea of tagging test fixtures relevant to current features with `[Category("Immediate")]`. That way, developers can run only the immediate category to quickly run the most immediately important tests. I've frequently started using the same concept outside of work as well.
<file_sep>+++
location = "Calgary"
published_at = 2009-05-29T00:00:00-06:00
slug = "finally-tuples-in-c-sharp"
tiny_slug = "9"
title = "FINALLY: Tuples in C#"
+++
It's taken until .NET 4.0, but Microsoft has finally decided to add tuples to the C# language. Here are their prototypes:
``` csharp
/* all tuples are defined under the System namespace */
[SerializableAttribute]
public class Tuple<T1> : IStructuralEquatable,
IStructuralComparable,
IComparable
[SerializableAttribute]
public class Tuple<T1, T2> : IStructuralEquatable,
IStructuralComparable,
IComparable
[SerializableAttribute]
public class Tuple<T1, T2, T3> : IStructuralEquatable,
IStructuralComparable,
IComparable
/* and all the way up to ... */
[SerializableAttribute]
public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable,
IStructuralComparable,
IComparable
```
It's a bit unfortunate for those of us who'd already added our own tuple implementations to our solutions because we'd given up hoping for built-in types years ago. Better late than never though.
Tuples can be created using either the constructors for your type's corresponding arity, or more easily using the static `Tuple.Create` method:
``` csharp
Tuple<int, string> who1 = new Tuple<int, string>(1, "Bob");
Tuple<int, string> who2 = Tuple.Create(2, "Bella");
```
Tuple elements are accessed using the readonly `Item1`, `Item2`, `Item3`, ... properties:
``` csharp
string name1 = who1.Item2; /* "Bob" */
string id2 = who2.Item1; /* 2 */
```
In case you're wondering, you can build a really big tuple using the last type arity: `Tuple<T1, T2, ..., TRest>`. The final `TRest` parameter is used to hold a second tuple inside the first one, and you could even put a third tuple inside the second and so on. As you might expect though, the syntax is clumsy:
``` csharp
Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>> bigTuple =
Tuple.Create(
/* T1 through T7 */
1, 2, 3, 4, 5, 6, 7,
/* TRest */
Tuple.Create(8, 9, 10)
);
```
So, we're not going to see anymore `out` parameters right guys?
<file_sep>+++
location = "San Francisco"
published_at = 2012-08-19T08:43:46-07:00
slug = "caps-lock"
title = "Caps Lock + Tmux"
+++
Nothing. But beyond that, without rebinding, the location and function of caps lock on a modern keyboard is more than inconvenient -- it's actively destructive. Enabling caps lock during a Vim session in normal code causes all hell to break loose, and what's going on isn't obvious unless you've seen the symptoms before.
I was pleasantly surprised to find that in OSX you can now disable caps lock out of the box if you don't intend to rebind it. This is accomplished via `System Preferences --> Keyboard --> Modifier Keys --> Caps Lock Key --> No Action`, and provides a measurable improvement over the system default.
Then I started to wonder whether I could put caps lock to good use by solving another problem caused by Apple's keyboard design, and the answer turned out to be yes.
Caps Lock as Tmux Prefix
------------------------
Tmux has moved beyond a terminal multiplexing tool and has become one of the most important tools in my kit by acting as the de facto window manager for all my important tools and sessions. As such, I hit my Tmux prefix shortcut `C-a` _a lot_, which is tremendously inconvenient because even in 2012 Apple is still jamming a `fn` key onto everything they make so that `ctrl` is harder to hit.
Switching to caps lock as a Tmux prefix solves this problem forever. Here's how to do it:
1. Download [PCKeyboardHack](http://pqrs.org/macosx/keyremap4macbook/pckeyboardhack.html.en), install, and restart.
2. From the new System Preferences pane, change the keycode under the `Change Caps Lock` entry to `109` (that's `F10`), and check its box.
3. In your `.tmux.conf`, change applicable settings to use `F10`:
``` bash
# thanks to PCKeyboardHack, F10 is caps lock and caps lock is F10
set-option -g prefix F10
# go to last window by hitting caps lock two times in rapid succession
bind-key F10 last-window
```
<file_sep>+++
location = "Calgary"
published_at = 2009-06-24T00:00:00-06:00
slug = "a-look-at-less"
tiny_slug = "14"
title = "A Look at Less"
+++
A few weeks ago, I read about a new project called [Less](http://lesscss.org/), a CSS framework that extends CSS by adding a few simple, but extremely useful features. Less' killer concept is it uses existing CSS syntax so that CSS files are automatically valid Less files as well.
I tend to feel that CSS is complex enough as it is, and the last thing I need when building a website is an expansive CSS framework, or a separate build process for CSS files that needs its own detailed configuration. Less being what it is, I was immediately sold on it and as an experiment, converted this website's CSS to Less, a process that took about half an hour. The [finished product](http://github.com/fyrerise/mutelight/blob/5a36d9ff48dd39f74abbf80d4f0bb94d274a6301/css/screen.less) is on GitHub.
Installation
------------
The install process couldn't be easier. Assuming that you've installed Ruby and RubyGems from your package manager, just run the following command:
```
gem install less
```
After installing Less, a `.less` file is converted to `.css` using:
```
lessc source [destination]
```
Usage
-----
### Nested Rules
Less' best feature (IMO) is its support for nested rules. Where in normal CSS you'd have to mark CSS rules with long selectors, you can actually nest selectors inside of other selectors in Less. I tend to write long selectors in CSS because I find that it helps keep display logic out of HTML files, so nesting rules with Less was a natural extension for me.
``` css
/* before */
div.content
{
...
}
div.content ol
{
padding: 0 0 0 20px;
}
div.content ol li
{
text-align: justify;
margin: 0 0 8px 0;
}
```
``` css
/* after */
div.content
{
...
ol
{
padding: 0 0 0 20px;
li
{
text-align: justify;
margin: 0 0 8px 0;
}
}
}
```
Notice how well the nesting complements lists! A nice side effect of Less is that when you nest _ALL_ your document's CSS rules (like [I've done](http://github.com/fyrerise/mutelight/blob/5a36d9ff48dd39f74abbf80d4f0bb94d274a6301/css/screen.less) with mine), the layout of your Less file starts to resemble the layout of your markup file, making rules easy to find.
### Variables
Less introduces variables to CSS, a welcome addition to CSS. Using variables is very simple: define them somewhere in your Less file with `@<var>: <value>;` then refer to them elsewhere with `@<var>`.
``` css
/* primary text color, for main text body */
@primary_color: #a9a9a8;
/* secondary text color, for links, alternate text, etc. */
@secondary_color: #7d7b88;
...
a
{
color: @secondary_color;
}
```
One limitation to variables is that they can't be used with strings, a problem which I describe in more detail below.
### Mixins and Operations
Less also supports mixins and operations, two features I didn't end up putting to use, but which are described very succinctly on [the Less website](http://lesscss.org/).
Limitations
-----------
While switching over to Less, I did encounter a few problems that appear to be unsolvable as far as the framework stands today.
### Nested Selector Groups
When writing CSS, it's common practice to group selectors together when they share properties. For example, if we wanted both our normal links and visited links to be blue, we'd write something like the following.
``` css
a:link, a:visited
{
color: #00f;
}
```
Naturally, you might want to extend this to Less' nested rules as well.
``` css
body
{
/* nested groups */
a:link, a:visited
{
color: #00f;
}
}
```
Unfortunately, if you tried to do so, Less would not output your CSS how you intended. Instead, it would write something like this:
``` css
/* this doesn't work as we would have expected */
body a:link, a:visited
{
color: #00f;
}
```
For these groups to work as we intended, both groups would have to the full CSS selector like `body a:link, body a:visited`.
### String Variables
With the addition of variables, a logical step would be start using them to store string fragments that could be joined with other fragments to build something useful, like a URL:
``` css
@my_images: "http://mutelight.org/images/";
body
{
background: #000 url(@my_images + "back.png");
}
```
Less doesn't seem to like this right now, but hopefully it'll make it into a future version.
Syntax Highlighting in Vim
--------------------------
Of course, Less just wouldn't be as good without some sort of syntax highlighting in Vim! Fortunately, highlighting Less files as CSS works well. Just add the following line to your `~/.vimrc`:
```
au BufRead,BufNewFile *.less setfiletype css
```
<file_sep>+++
location = "Calgary"
published_at = 2010-12-16T00:00:00-07:00
slug = "comments-on-leaving-dot-net"
tiny_slug = "36"
title = "Comments on \"Leaving .NET\""
+++
Yesterday I read [<NAME>'s article on leaving .NET](http://whatupdave.com/post/1170718843/leaving-net) which has recently been making its Internet rounds. I can't help but comment on how accurately he's managed to describe the .NET community and its long list of shortcomings. The article lists a number of problems:
* "Not invented here" syndrome (specifically MVC which Microsoft introduced as some ground-breaking new technology even though it came out years after the technology was already well-established in open source)
* Microsoft doesn't accept patches for code that it claims is open source
* There is generally no collaboration in the community on open source projects
* Codeplex isn't "real" open source, and the community needs to abandon it
Ironically, the very reason that Dave abandoned the Microsoft stack may be the same reason that big industry is so keen on it. To a big company, another big company is a safety net. Companies are more reliable than people: they don't leave the country, or leave projects half finished, and most importantly, they provide a nice stationary legal target. These are all good reasons that help explain why in general, big enterprise prefers leveraging frameworks built by Microsoft over those built by loosely organized groups of liberal hooligans.
One problem that he hit dead on is Microsoft's deep afflication by "not invented here" syndrome. Microsoft has never, and will never work with the community when it comes to open source projects. A few examples that I think about often:
* Releasing the Entity Framework when NHibernate was already widely used. Entity may have caught up, but in its early days, NHibernate was unquestionably superior.
* Microsoft Unit Testing Framework's came out years after a multitude of open source were used all over the place, including big industry.
* Reproducing the popular Subversion in the form of Team Foundation (see below).
* Evangelizing ASP.NET MVC when Rails and .NET frameworks based on Rails were already mature.
* The .NET framework itself! Let's face it, it's hard to refute that C# and .NET were _strongly_ "influenced" by Java and the JVM.
Microsoft has created quite a successful business model around an innovation strategy based on copying what they see out in the wild, and good for them, they're still one of the best possible examples of how to make big money in the software industry. It's that same successful model however, that also ensures that Microsoft is constantly lagging behind new features, sometimes by years, and many of those new features that are actually innovated in house fail to catch on.
Another problem with the copy model is that once in a while, revolutionary innovations in some technology comes at the wrong time (i.e. in the middle of development of a clone), and get missed. An example of this is Team Foundation, which was developed as a successor to SourceSafe and a response to Subversion creeping into .NET territory. By the time Team Foundation was released, the leading edge had switched gears completely and begun using distributed version control (i.e. Git, Mercurial, Darcs), a completely new paradigm, and the rest of industry had started to follow. As far as I know, due to poor timing, Microsoft still has no answer for modern source control.
Despite all this, we should be thankful that there's still a thriving open source community doing work in .NET. Efforts on the Mono project might be the best example of this, but NHibernate has also rebranded themselves recently (NHForge), and .NET projects on Github may even be becoming more relevant than those on Codeplex. Combined with its overwhelming use in the business world, .NET is still a good place to be.
<file_sep>+++
location = "Calgary"
published_at = 2011-05-31T10:34:00-06:00
slug = "what-i-learned-about-javascript-by-breaking-a-top-200-website"
tiny_slug = "ie-js"
title = "What I Learned About JavaScript by Breaking a Top 200 Website"
+++
Let no one contest the fact that I learn my lessons the hard way. Here's the story of how I broke the search engine on one of the Internet's largest websites for IE 6/7 due to a quirk in the JavaScript parser of these older Microsoft browsers.
The bug that I introduced was subtle enough that it made it past two levels of code reviews and through QA as well, which is a partial indicator of how much mind share IE 6/7 users get even within a company that officially supports them. A day after it went live, we'd already received five support calls reporting the problem; pretty good considering that most website users aren't particularly disposed to picking up a phone when they run into a problem.
The bug itself looks decidedly unimpressive considering that it probably impacted thousands of visitors:
``` js
filterTypes = {
FILTER_A: translations.filter_a,
FILTER_B: translations.filter_b,
/* the comma on this last line will break IE 6/7 */
FILTER_C: translations.filter_c,
};
```
Catch that? Any experienced JavaScript developer will probably see it easily, but most of us won't considering that the above code is perfectly valid under any modern day browser or JavaScript interpreter.
In case it wasn't obvious, the compilation problem is the trailing comma after `translations.filter_c` which dumb browsers like IE 6/7 will interpret as an indication that the array/object contains a trailing `undefined` element at the end, effectively like the following:
``` js
filterTypes = {
FILTER_A: translations.filter_a,
FILTER_B: translations.filter_b,
FILTER_C: translations.filter_c,
undefined
};
```
With the addition of the `undefined` element the code above is no longer valid JavaScript, and even a modern interpreter such as the one found in Node.JS will balk at it:
```
SyntaxError: Unexpected token }
```
Recourses
---------
After causing such an embarrassing problem, my obvious next reaction was to implement safeguards to ensure that it never happens again. Here are a few techniques to mitigate the risk of writing unsafe JS.
### CoffeeScript
There is a growing number of forward thinkers out there who believe that writing JS is akin to writing CIL for the CLI or bytecode for the JVM; in short that it's unnecessarily low-level. In the near future, languages like CoffeeScript will be leveraged to write compilable, efficient, and safe JavaScript. The right package for your platform will make transparently deploying CoffeeScript just as easy as if you were writing static JS files directly.
In fact, the future is now. As of [Rails 3.1](http://weblog.rubyonrails.org/2011/5/22/rails-3-1-release-candidate), CoffeeScript now takes the place of JavaScript by default. Personally, CoffeeScript has also been my preferred method of implementing JS for over a year now due to its added language features, and its concise and expressive syntax.
The equivalent CoffeeScript in this case looks very similar to the JS:
``` coffee
filterTypes = {
FILTER_A: translations.filter_a,
FILTER_B: translations.filter_b,
FILTER_C: translations.filter_c,
}
```
The difference is that the Coffee compiler takes care of that trailing comma. The produced JS will look like this:
``` js
(function() {
var filterTypes;
filterTypes = {
FILTER_A: translations.filter_a,
FILTER_B: translations.filter_b,
FILTER_C: translations.filter_c
};
}).call(this);
```
Note also that another common pitfall (global name clashing) is avoided automatically by adding a function wrapper around the compiled code.
### JSLint
Don't have enough pull at your company to change its entire JavaScript backend to CoffeeScript? Well then perhaps JSLint is more to your liking. It's a JS code quality tool that can be integrated with editors like Vim to verify your syntax automatically when you open or save a `.js` file, and will make problems like the trailing array/object comma a thing of the past.
Vim users should try the [jslint.vim plugin](https://github.com/hallettj/jslint.vim). Keep in mind that as well as installing the plugin itself, you'll also need a JavaScript interpreter like Spidermonkey, Rhino, or Node installed on your system.
<file_sep>+++
location = "Calgary"
published_at = 2010-12-15T00:00:00-07:00
slug = "simultaneous-oracle-and-sql-server-support-in-entity-framework-with-designer-generated-objects"
tiny_slug = "35"
title = "Simultaneous Oracle and SQL Server Support in Entity Framework with Designer Generated Objects"
+++
The ADO.NET Entity Framework is a great product. Without going into too much background, it's Microsoft's attempt at an <acronym title="Object-relational Mapper">ORM</acronym> to make working with relational datastores more convenient. In their own words, it solves the _impedance mismatch across various data representations (for example objects and relational stores)_, and _empowers developers to focus on the needs of the application as opposed to the complexities of bridging disparate data source_. I've heard that problems in earlier versions of Entity made it's use quite a burden, but today's version seems to be quite a solid product.
Perhaps Entity's greatest feature it's LINQ-enabled so that it can transform a strongly typed LINQ statement into an SQL expression. These LINQ transformations even support advanced features like joins, aggregates, typecasts, and nullable types. For example, in the following method _all_ the logic gets offloaded to the database. That is, unless you swap out your database provider for an in-memory provider for testing, in that case, all the work would be done by the CLR instead.
``` cs
public IQueryable<LoginStatsViewModel> GetLoginStatsByTimeRange(
DateTime startDate,
DateTime endDate
)
{
return
from l in RepositoryFor<Login>().AsQueryable()
where l.LoginDate >= startDate
&& l.LoginDate < endDate
group l by l.UserKey into g
join u in RepositoryFor<User>().AsQueryable()
on g.Key equals u.UserKey
let t = g.Sum(l => l.TimeSpentOnSite)
select new LoginStatsViewModel()
{
Key = Guid.NewGuid(),
UserKey = g.Key,
UserName = u.UserName,
NumLogins = g.Count(),
LastLoginDate = (int)g.Max(l => l.LoginDate),
UserTypeName = u.UserType.UserTypeName,
TotalNumCaptchaTries = (int)g.Sum(l => l.NumCaptchaTries),
TotalTimeSpentOnSite = t.HasValue ? (double)t.Value : 0.0,
};
}
```
Some other interesting things about this LINQ expression:
* `Guid.NewGuid()` will be translated by Entity into an SQL equivalent
* Explicit join on `User` as well as the implicit join on `UserType` using a navigation property
* Sums on both non-nullable and nullable columns
* The ternary operator (`?:`) works!
* This method is lazy, so the `IQueryable` object returned by it can be queried further before a final SQL statement is generated
Data objects such as `Login` and `User` can be generated automatically by giving the Entity designer a connection string for your SQL Server database, written by hand in a manner similar to what you might do with NHibernate (these are called <acronym title="Plain Old CLR Objects">POCO</acronym> entities), or both.
On the surface, Entity seems like a completely outstanding product that no .NET shop could afford to overlook, and it might be, save for one serious drawback.
Data Providers
--------------
ADO.NET is based on a data provider model which provides a common managed interface that can implemented by data providers to enable interaction with various data stores. A default provider for SQL Server is included in the framework by default, and implementations for any third party databases are left up to, well, third parties. Entity Framework being fairly mature, a [number of data providers](http://msdn.microsoft.com/en-us/data/dd363565.aspx) are already available, and as is common in the Microsoft ecosystem, most of them for a price.
The problem with this arrangement is twofold:
1. SQL Server is nice, and many companies working with .NET try to use it if possible, largely on account of Microsoft's excellent tools support. In practice however, Oracle is extremely pervasive in big business, and many shops require backend support for it.
2. If enabling a data provider was as simple as just dropping in a few DLLs, it would be worth paying another company to save your time. However, the reality of the situation is that getting your existing Entity infrastructure to support a new database will require non-trivial redesign and debugging.
Compare this situation to the open-source alternative for a moment. By changing a single line of configuration in a Ruby on Rails project, I can get support for MySQL, PostgreSQL, SQLite, DB2, SQL Server, Oracle, and other relational databases. By switching out my `ActiveRecord` implementation, I can bring in support for the world of non-relational data stores: CouchDB, MongoDB, Redis, and a host of others. Obviously Ruby's dynamic nature helps a bit here, but the main point is that Entity's multi-platform support has huge room for improvement.
Our goal was to maintain an Entity infrastructure based around Microsoft's default SQL Server provider so that we could leverage its nice Visual Studio support, easy integration of new features released down the road, generation of data objects given a database, and most of all because life is usually made easier in the Microsoft ecosystem by preferring a Microsoft product over a third party alternative. In addition, Oracle support was a requirement due to its popularity among our client base. We strongly preferred an arrangement that would allow us to maintain a single set of data objects for all databases so that duplicated infrastructure wouldn't be necessary.
Devart
------
We tried a number of possible solutions and in the end concluded that the best we could do was to use a backend called [dotConnect created by Devart](http://www.devart.com/dotconnect/). Devart has its own set of tools for building an Entity backend, but we identified that we could also used it for Oracle connectivity with Microsoft tools using a process like the following:
* Ship Devart provider DLLs for Oracle
* Create an alternate `edmx` to tell Devart how to map object properties to database fields, among other things. In general the SQL Server `edmx` would be very similar to the Oracle `edmx`. We'd create the first one by hand, then build a generator to take care of it automatically in the future. Note that an `edmx` is often defined in its components: `csdl`, `msl`, and `ssdl`.
* Create a new Entity Framework configuration string pointing to the Devart Oracle provider and the new `edmx` files
In theory, the whole process is pretty straightforward and should be almost "drop in", involving only some modifications to database mapping types in the `ssdl` component of the `edmx`. In practice though, we found that working with the Devart provider came with a number of gotchas, and we spent the equivalent of one man-week finding suitable solutions for them. Devart is functional, but its support and implementation aren't quite there yet. Oracle is supposed to be releasing a beta for its official ADO.NET provider sometime in 2011, and we'll probably evaluate moving to it when the time comes.
Below is a rough roadmap of what needs to be done to ship Oracle support.
### Installation
The [dotConnect for Oracle](http://www.devart.com/dotconnect/oracle/download.html) package needs to be downloaded and installed in order to get the requisite provider DLLs. Only one person really needs to do this because the DLLs can be checked into the working solution from there and made available to the rest of the team.
A word of warning: after installing Devart, you may be prompted to install the Devart designer tools the next time Visual Studio starts up. I refused this install request, and Devart responded by severely crippling my Visual Studio 2010 installation; symptoms being that all toolbars and panes refused to open, some delivering an error code. It wasn't obvious that Devart was causing the problem, but I uninstalled it and the issues disappeared. I was able to reinstall Devart in a safe manner by carefully disabling any Visual Studio related components during the install process, _and_ refusing the designer tools during Visual Studio's startup.
### DLLs
For full Oracle provider support, three DLLs need to be shipped with an Entity-enabled project: `Devart.Data.dll`, `Devart.Data.Oracle.dll`, and `Devart.Data.Oracle.Entity.dll`. These should be available in the dotConnect installation directory. An appropriate license for these files will also be necessary.
### SSDL and Devart's Special Case Behavior
SSDL is short for _store schema definition language_ and is one of the three major components generated as part of an `edmx`. Its primary reponsibilities are defining associations between entities, the database table corresponding to each entity, and the database types for each entity property.
Here's a small piece of a sample SSDL:
``` xml
<Schema ...>
<EntityType Name="User">
<Key>
<PropertyRef Name="USERKEY" />
</Key>
<Property Name="USERKEY" Type="CHAR" Nullable="false" MaxLength="36" />
<Property Name="USERNAME" Type="VARCHAR2" Nullable="false" MaxLength="50" />
<Property Name="DESCRIPTION" Type="VARCHAR2" MaxLength="200" />
...
</EntityType>
</Schema>
```
The Oracle SSDL will look very similar to the SQL Server SSDL, with a few key differences:
* The top-level `<Schema>` tag's `Provider` attribute must be set to `Devart.Data.Oracle`
* The `<Schema>` tag's `ProviderManifestToken` attribute must be set to `ORA`
* Any `<EntitySet>` tags must have the value of their `Schema` attribute _uppercased_
* Any `<EntitySet>` tags should have a `Table` attribute added to them, where the value is the name of that entity's database table _uppercased_
* All `<Property>` and `<PropertyRef>` tags must have the value of their `Name` attribute _uppercased_
* All `<Property>` tags must have their `Type` attribute changed to an Oracle equivalent, see the table below
There's a good reason that we uppercase many of these values. As of now (December 2010), the Devart provider will wrap any table and column names that are not uppercase in double quotes when building SQL queries. This is unfortunate, because Oracle doesn't support these objects being wrapped in quotes. This problem can be worked around using uppercase for all database object names.
<table>
<caption>SQL Server types and their Oracle equivalents (incomplete table)</caption>
<tr>
<th style="width: 50%;">SQL Server Type</th>
<th style="width: 50%;">Oracle Type (case sensitive)</th>
<tr>
<tr>
<td>bigint</td>
<td>int64</td>
<tr>
<tr>
<td>char</td>
<td>CHAR</td>
<tr>
<tr>
<td>datetime</td>
<td>DATE</td>
<tr>
<tr>
<td>numeric</td>
<td>decimal</td>
<tr>
<tr>
<td>tinyint</td>
<td>byte</td>
<tr>
<tr>
<td>varchar</td>
<td>VARCHAR2</td>
<tr>
</table>
### MSL
MSL is short for _mapping specification language_ and is the next major `edmx` component. Its job is to map the properties of an entity's class representation to the fields of the corresponding database table.
Here's a small piece of a sample MSL:
``` xml
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntitySetMapping Name="User">
<EntityTypeMapping TypeName="Web_Model.User">
<MappingFragment StoreEntitySet="User">
<ScalarProperty Name="UserKey" ColumnName="USERKEY" />
<ScalarProperty Name="UserName" ColumnName="USERNAME" />
<ScalarProperty Name="Description" ColumnName="DESCRIPTION" />
...
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
</Mapping>
```
The Oracle MSL needs fewer changes than the SSDL, and would probably require none at all if Devart's double quoting bug didn't exist:
* All `<*Property>` tags must have the value of their `ColumnName` attribute _uppercased_
### CSDL
CSDL is short for _conceptual schema definition language_ and is the last `edmx` component. It tracks relations, general property information, and navigation properties. Here's a sample section from a CSDL:
``` xml
<Schema Namespace="Web_Model" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityType Name="User">
<Key>
<PropertyRef Name="UserKey" />
</Key>
<Property Type="String" Name="UserKey" Nullable="false" MaxLength="36" FixedLength="true" Unicode="false" />
<Property Type="String" Name="UserName" Nullable="false" MaxLength="50" FixedLength="false" Unicode="false" />
<Property Type="String" Name="Description" MaxLength="200" FixedLength="false" Unicode="false" />
...
</Entitytype>
</Schema>
```
No changes are required to the CSDL for Oracle. We were hoping to simply reuse the CSDL from our SQL Server `edmx` file, but we ended up duplicating it because we ran into a compiler bug that would occur intermittently. We're still not exactly sure what the problem was, but the compilation error looked something like this:
```
Error 19 Value cannot be null.
Parameter name: csdlPath Company.Namespace.Project
```
### Resources and Config Paths
After new SSDL, MSL, and CSDL files have been generated, they should be added to the entity project and their _build action_ changed to _embedded resource_. You'll want to reference these new resources from your Oracle connection string. Keep in mind that the compiler will probably prepend your full namespace path to their resource names, so reference them accordingly. If in doubt, use Reflector to check what path a resource has been embedded in a DLL under.
Here's an example Oracle Entity connection string for use in `App/Web.config`:
``` xml
<add name="Web_Entities"
connectionString="provider=Devart.Data.Oracle;metadata=res://*/Company.Namespace.Project.WebDataModel.Oracle.csdl|res://*/Company.Namespace.Project.WebDataModel.Oracle.ssdl|res://*/Company.Namespace.Project.WebDataModel.Oracle.msl;Provider Connection String='Data Source=myoracleserver/xe;User Id=myoracleuser;Password=<PASSWORD>;'"
providerName="System.Data.EntityClient" />
```
### Conversion
The final step is a conversion project that will allow you to modify your Entity's `edmx` and convert those changes to an equivalent Oracle version. I've included some basic ideas for writing such a program built around XPath (I'm using my own extension methods here so this code won't compile directly).
``` cs
#region Public
public static void Generate(string sourceSchemaPath, string targetPathAndRootName)
{
XmlReader reader = XmlReader.Create(sourceSchemaPath);
XElement root = XElement.Load(reader);
XmlNamespaceManager ns = new XmlNamespaceManager(reader.NameTable);
ns.AddNamespace("cs", "http://schemas.microsoft.com/ado/2008/09/mapping/cs");
ns.AddNamespace("edmx", "http://schemas.microsoft.com/ado/2008/10/edmx");
ns.AddNamespace("ssdl", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl");
ns.AddNamespace("edm", "http://schemas.microsoft.com/ado/2008/09/edm");
XElement msl = GenerateMSL(root, ns);
msl.Save(targetPathRootName + ".msl");
Console.Out.WriteLine("Generated: " + targetPathRootName + ".msl");
XElement ssdl = GenerateSSDL(root, ns);
ssdl.Save(targetPathRootName + ".ssdl");
Console.Out.WriteLine("Generated: " + targetPathRootName + ".ssdl");
XElement csdl = GenerateCSDL(root, ns);
csdl.Save(targetPathRootName + ".csdl");
Console.Out.WriteLine("Generated: " + targetPathRootName + ".csdl");
}
#endregion
#region Private
private static XElement GenerateMSL(XElement root, XmlNamespaceManager ns)
{
foreach (XElement property
in root.XPathSelectElements(
"//edmx:Runtime/edmx:Mappings/cs:Mapping/cs:EntityContainerMapping/" +
"cs:EntitySetMapping/cs:EntityTypeMapping/cs:MappingFragment/*",
ns
))
{
property.ModifyAttribute("ColumnName", v => v.ToUpper());
}
XElement msl =
root.XPathSelectElement("//edmx:Runtime/edmx:Mappings/cs:Mapping", ns);
return msl;
}
private static XElement GenerateCSDL(XElement root, XmlNamespaceManager ns)
{
// No modification -- see explanation above
XElement csdl =
root.XPathSelectElement(
"//edmx:Runtime/edmx:ConceptualModels/edm:Schema",
ns
);
return csdl;
}
private static XElement GenerateSSDL(XElement root, XmlNamespaceManager ns)
{
foreach (XElement entitySet
in root.XPathSelectElements(
"//edmx:Runtime/edmx:StorageModels/ssdl:Schema/" +
"ssdl:EntityContainer/ssdl:EntitySet",
ns
))
{
entitySet.ModifyAttribute("Schema", v => v.ToUpper());
entitySet.SetAttribute("Table", entitySet.Attribute("Name").Value.ToUpper());
}
foreach (XElement property
in root.XPathSelectElements("//*/ssdl:Property", ns))
{
property.ModifyAttribute("Name", v => v.ToUpper());
Action<string> setAttr = v => property.SetAttribute("Type", v);
// Not an exhaustive list
switch (property.Attribute("Type").Value.ToLower())
{
case "bigint":
setAttr("int64"); break;
case "tinyint":
setAttr("byte"); break;
case "char":
setAttr("CHAR"); break;
case "datetime":
setAttr("DATE"); break;
case "numeric":
setAttr("decimal"); break;
case "text":
setAttr("CLOB"); break;
case "varchar":
setAttr("VARCHAR2"); break;
default:
Console.WriteLine(
"Warning: unrecognized property type: " +
property.Attribute("Type").Value
);
break;
}
}
foreach (XElement propertyRef
in root.XPathSelectElements("//*/ssdl:PropertyRef", ns))
{
propertyRef.ModifyAttribute("Name", v => v.ToUpper());
}
XElement ssdl =
root.XPathSelectElement("//edmx:Runtime/edmx:StorageModels/ssdl:Schema", ns);
ssdl.SetAttribute("Provider", "Devart.Data.Oracle");
ssdl.SetAttribute("ProviderManifestToken", "ORA");
return ssdl;
}
#endregion
```
<file_sep>+++
location = "Calgary"
published_at = 2010-12-19T20:37:00-07:00
slug = "swype-for-advanced-users"
tiny_slug = "38"
title = "Swype for Advanced Users"
+++
A tweet from Swype led me to the page for [Swype Tips and Tricks](http://swypeinc.com/tips-tricks.html). I watched most of the videos, but in general found that the tricks were simple enough that they could be easily digested in the form of text, so here they are:
* **Double letter:** swype in a small circle and back onto that letter
* **Capitalize letter midsentence:** after swyping over the letter to be capitalized, swype into the space above the keyboard, then back down to the word's next letter on the keyboard
* **Capitalize entire word:** same as above, but swype a loop in the space above the keyboard
* **Punctuation:** swype from any punctuation key (even if it's an alternate character on the keyboard), and onto the spacebar. That punctuation and a space are inserted.
* **Apostrophes:** as you're entering a word, swype over the apostrophe button in the appropriate location
* **Correction:** double tap a word to bring up a correction menu
* **Add to dictionary:** type a word in manually, and press the spacebar (only works for words, there is another process for complex entities like an e-mail address)
* **Hopping:** for words that have an ambiguous swype pattern (e.g. pit vs. pot vs. put), "hop" between letters by moving out and above them and into the next letter from above
* **Symbols:** press and hold on a letter to add its alternate content
* **Speed:** swype can guess many words even if not every letter in them is "hit". Try typing entire messages without any corrections as a "first pass", then proofread the message and make corrections.
<file_sep>+++
location = "Calgary"
published_at = 2009-10-25T00:00:00-06:00
slug = "swallowing-an-extensible-exception-in-haskell"
tiny_slug = "19"
title = "Swallowing an Extensible Exception in Haskell"
+++
As of version 6.10.1 of the GHC, the `Control.Exception` namespace now uses extensible exceptions, the old style exceptions having been relocated to `Control.OldException`.
This is great news, but in some cases the new extensible exceptions are a little more fussy about how they're used than the old exceptions were, and can spit out some pretty cryptic error messages if handled improperly. For example, I found myself wanting to swallow any exceptions that occurred while trying to create a new CouchDB database. I started out with some straightforward code like this:
``` haskell
runCouchDB' (createDB "logs") `catch` \_ -> return ()
```
Here's the resulting error message:
```
Ambiguous type variable `e' in the constraint:
`GHC.Exception.Exception e'
arising from a use of `Control.Exception.Base.catch'
at <interactive>:1:0-71
Probable fix: add a type signature that fixes these type variable(s)
```
Being pretty new to Haskell, it wasn't immediately obvious to me what the problem was here, but after doing some research I realized that GHC wanted to be provided with the type of exception that I wanted to catch; the idea being that the compiler forces developers to think about what they're doing to some extent. In my case, this happens to be an `ErrorCall` exception instance, so I rewrote my code like this:
``` haskell
runCouchDB' (createDB "logs") `catch` \(_ :: ErrorCall) -> return ()
```
… and it compiles! If I had been doing something in my lambda function above, this type might have been inferred for me by the compiler, but I had to define it explicitly because I didn't use the result in any way. A list of exception instances is available in the [documentation for `Control.Exception`](http://www.haskell.org/ghc/docs/6.10-latest/html/libraries/base/Control-Exception.html#t%3AException).
<file_sep>+++
location = "Calgary"
published_at = 2011-07-17T17:56:00-06:00
slug = "faux-named-queues-with-gearman"
tiny_slug = "named-gearman"
title = "Faux Named Queues with Gearman"
+++
A few months back, our architecture team deemed that a task queue service would be needed for a few upcoming projects, mostly so that we could replace our bad habit of running expensive background work via cron scripts. The software chosen for this role was [Gearman](http://gearman.org), a fast job queueing framework with good PHP support.
Gearman has been mostly pretty functional as far as our requirements were concerned, but came with one rather surprising quirk: any given Gearman server or cluster only supports a single job queue. I say that this is surprising because support for multiple queues is an integral feature of Gearman's alternatives such as RabbitMQ (channels), and Redis (different keyed sets).
Background
----------
To understand the reason that Gearman was built this way, a bit of background is in order. When a Gearman worker connects to a Gearman daemon, it registers the names of all the types of jobs it wants to be able to handle before entering its job loop and being sent work:
``` php
$worker = new GearmanWorker();
$worker->addServer();
// Tell the Gearman daemon that this worker will handle any jobs in its queue
// called 'resizeImage' using the PHP function 'doImageResize'
$worker->addFunction('resizeImage', 'doImageResize');
while ($worker->work())
{
// Finished processing a job
}
function doImageResize($job)
{
// This is where the work happens
}
```
A result of the way this function registration works is that the Gearman daemon knows exactly which connected workers can handle which types of jobs. That is, if only worker #1 registered a function for `resizeImage`, then when a `resizeImage` job is encountered, it must be sent to worker #1.
Another aspect of Gearman's behaviour which isn't intuitively obvious is that if there's a job ready to be pulled off the queue, and has no connected workers that are able to handle it, that job stays in the queue ready to be run, but in the meantime other jobs in the queue continue to be processed. When a worker connects that can handle that previously unprocessable job, it gets passed off immediately.
In this way, jobs that belong to separate logical groups and which may have been stored in different queues in another system, can coexist in a single Gearman queue by simply having distinct Gearman workers.
Faux Named Queues
-----------------
Mostly due to internal IT logistics, we needed a number of people running the same application to be able to be able to share a single Gearman cluster. This proved to be a problem when person #1 would queue a job, and it would promptly be handled by person #2's worker.
Luckily, one of my colleagues realized that we could solve this problem by leveraging the same function registration behaviour detailed above. Clients could prepend a hostname before inserting any jobs:
``` php
$client = new GearmanClient();
$client->addServer();
doBackground($client, 'resizeImage', 'lolcat.jpg');
function doBackground($client, $job, $workload)
{
if (!IS_PRODUCTION) {
$job = $hostname . '-' . $job;
}
$client->doBackground($job, $workload);
}
```
Likewise, workers could prepend a hostname to any jobs they registered:
``` php
$worker = new GearmanWorker();
$worker->addServer();
addFunction($worker, 'resizeImage', 'doImageResize');
while ($worker->work())
{
// Finished processing a job
}
function addFunction($worker, $job, $phpFunction)
{
if (!IS_PRODUCTION) {
$job = $hostname . '-' . $job;
}
$worker->addFunction($job, $phpFunction);
}
```
Using this technique, jobs are only processed by workers running under the same host as the client that queued them, effectively solving our sharing problem; and thanks to Gearman's behaviour when encountering unregistered jobs, users won't block each other, even if their worker isn't running.
A better solution might be to have everyone running local Gearman daemons, but this method serves as an effective alternative in cases where that's not possible.
<file_sep>+++
location = "Flight from Houston"
published_at = 2011-03-15T00:00:00-06:00
slug = "mobility"
tiny_slug = "mobility"
title = "Mobility"
+++
A few days ago, I left the company that I'd been working at for almost exactly three and a half years. Considering that this was my first job out of university, this was a huge deal for me.
The day before my big departure day, my boss conducted my exit interview that he'd disguised as a friendly coffee run. His questions were somewhat indirect, but what we wanted to know was simple: why was I leaving? What could they have done to keep me around?
Of course, like anyone else, I did harbor some grievances with my job, but these were all professional disagreements, and none of them were serious enough to drive me out the door. I cooperated with the exit interview entirely, and was honest about how they could improve their policies to build a more compelling environment for developers. Complaining isn't constructive, so I only mentioned the problems that had viable solutions.
The interview forced me to consider why exactly I'd left, and I realized that it could be explained with one simple idea. Even if my old job had been absolutely perfect: creative environment, senior position, great salary, invisible bureaucracy, blazing hardware, and a hot administrative assistant who laughed at all my jokes, would I be happy five years down the road? I believe the answer is no. Being at SXSW really helped bring into perspective that there are just so many interesting things going on in the world, and what I'm doing at any time is only a tiny piece. Just like I travel to experience other cultures and see the world, I want to be mobile in the workplace. Lifelong workers stay for the same reason that people don't like to travel: because staying home is comfortable.
Starting a new job is one of the most interesting things that a person can do in their life. The sudden influx of new interesting people, ideas, technology, techniques, and environment is a rush of size and scope rarely experienced elsewhere. For this reason, mobility is important.
Too much mobility is possible too, and a successful worker will need to strike a balance. I wouldn't want to leave a job where I hadn't experienced some sense of accomplishment. I'm paid well, and I want employers to feel like they got their money's worth, but I have to consider my own self-development at the same time.
<file_sep>+++
location = "Calgary"
published_at = 2009-11-18T00:00:00-07:00
slug = "the-art-of-screen"
tiny_slug = "22"
title = "The Art of Screen"
+++
During all the years I've used Linux, unquestionably the one greatest productivity improvement I ever experienced was the day I discovered [GNU Screen](http://www.gnu.org/software/screen/). Screen allows you to many things, the most important of which is to continue your terminal sessions from anywhere, and between different consoles.
Activity Monitoring
-------------------
The power of screen continues to amaze me: today I stumbled across a feature by accident that I'd been missing out on all this time (I probably should've given the [man page](http://www.manpagez.com/man/1/screen/) a good read a long time ago). It's called activity monitoring, and it lets you have screen notify you when something happens in a background window. If you're a heavy IM or IRC user like me, these notifications can be tremendously useful.
Turn activity monitoring on for your current window using `C-a M`. Using this same shortcut again will toggle activity monitoring back to off. Now when something happens in this window, Screen will flash a message across its status bar, and display an `@` next to its title.
<img src="/assets/images/articles/the-art-of-screen/screen-status.png" alt="Notice the @ next to a modified window's title" />
The message displayed when something occurs can be changed using `activity <message>` in your configuration file. Change it to an empty string (`""`) to kill the message completely.
### Finch + Irssi
The problem with Screen's activity monitoring is that it will be trigged by any change whatsoever. This leads to problems for common command line apps like Finch and Irssi that update constantly.
In Finch, buddies are constantly coming online and going offline, which triggers the monitor. A partial solution for this is to just close your buddy list window (`M-c`), so that only changes in your chat windows go through to you.
The biggest problem in Irssi (besides the fact that IRC channel are being updated constantly) is that by default, its status bar has a clock that will flip once a minute, and trigger the monitor. The easiest thing to do here is to get rid of the clock: `/statusbar window remove time`. Irssi will save your configuration changes automatically.
<file_sep>+++
location = "Calgary"
published_at = 2010-11-29T00:00:00-07:00
slug = "why-i-track-my-reading-and-you-should-too"
tiny_slug = "33"
title = "Why I Track My Reading and You Should Too"
+++
I recently launched a new side project for tracking [my book history](http://brandur.org/books). Although this project is new, I've been tracking every book that I've read for a few years now in one form or another, and I'd strongly encourage everyone who reads to do the same. I've put together my top reasons for maintaining a reading list record below.
Referrals
---------
Often when speaking to friends we'll remember an outstanding book we've read that relates to the subject of conversation that we'd like to recommend. The problem for those of us with poor memories or who go through a lot of books, that title and author name might be difficult to recall--even if it's on the tip of the tongue. A reading list will save these situations, enabling easy lookup and referral.
Memory
------
Fresh after finishing a book you'll only retain a small portion of all the useful facts and information that it contained. A few months down the road is even worse, you'll only retain a small fraction _of the small fraction_ that you retained originally. After a few years, everything might be gone including the book title. In a way, reading a book is an investment, one where you trade your time for knowledge. If everything you read will be forgotten to a large degree, then you've lost that time invested. Fiction might be an exception to this rule because it's more of a leisure activity.
This concept was my primary motivation for building my [facts project](http://facts.brandur.org) (open sourced on [Github](http://github.com/fyrerise/facts)), useful for breaking a very heavy piece of prose into bits of information that are still meaningful out of context. This is not to say that a fancy web application is required! A plain text file works fine for the purposes of taking down notes on a book.
Analytics
---------
A reading history allows you to easily look up metrics like how many books you've read year to year, or what portion of fiction books you read versus non-fiction. These metrics are useful for determining whether you're maintaining target reading levels, along with other goal setting.
Ease
----
Tracking your reading is far easier than it was a decade ago! Convenient sites like [Goodreads](http://www.goodreads.com/) have appeared, allowing you to track your reading and take advantage of the like-minded community. Before I wrote an application for it, I maintained my reading list in a personal wiki for quick reference and easy updating. If these solutions seem too elaborate, a text file or a written list on paper will do just as well.
<file_sep>+++
location = "Calgary"
published_at = 2009-11-05T00:00:00-07:00
slug = "is-method-documentation-important"
tiny_slug = "20"
title = "Is Method Documentation Important?"
+++
Is class and method documentation important when programming? In my experience, this is a question for which the industry has no general answer, to some it is and to others it isn't.
Before I started developing professionally, I used to document voraciously: I wrote fully-formed Doxygen comments for every variable, class, and method I added to a codebase, explaining both usage and reasoning. In retrospect, maybe it was overkill. One problem is that I'd always comment immediately after an addition or change, and sometimes this resulted in wasted work when I decided some method, variable, or heaven forbid, class, was no longer needed.
I'd worked with at least a few open source projects and with a few well-known APIs that had given me the impression that some coders were even more dedicated to code documentation than I was. A good example of this is [Qt](http://doc.trolltech.com/), a framework that probably has some of the best documentation around.
The C# Ecosystem
----------------
Upon entering the C# world, I realized that business operate a little differently. I want to say that very little thought is attributed to code docs in business, but unfortunately in the case of many C# shops, the reality is that none is at all. This is at least partly due to the advent of *GhostDoc*, a tool that deconstructs class/method/parameter names into valid C# comment mark-up, and leaves you with pretty, but utterly superfluous, comments like the following:
``` cs
/// <summary>
/// Processes the event request.
/// </summary>
/// <param name="eventTriggerCode">The event trigger
/// code.</param>
/// <param name="agencyVehicleData">The agency vehicle
/// data.</param>
/// <param name="locationData">The location data.</param>
/// <returns></returns>
private bool ProcessEventRequest(
```
One of the major problems with this approach is that it's impossible to tell without close inspection which docs were generated from GhostDoc and which weren't. Only comments not generated by GhostDoc are worth reading because GhostDoc comments by definition, provide no more information than is already contained in the documented symbols.
This leads to interesting side-effects when GhostDoc use is widespread. Where I work, GhostDoc is part of the standard developer set-up process, and every developer is encouraged to use it. Thanks to GhostDoc, we've ensured that every variable, method, class, constant, and enumeration in our codebase has docs attached to it; but docs that contain no more information than can be obtained by reading their respective symbol names. The result is predictable: _no one reads docs anymore!_
On many occasions, I've been asked about some implementation detail in some method I wrote. After answering the question, I refer that developer to the method docs that contained the answer so that they can reference those in the future (I never use GhostDoc). The fact that they never thought to read them in the first place isn't surprising in the least, 99% of the time they would have found nothing there.
Not only could you clarify your source code by removing GhostDoc from your development process, but I'm convinced that you could cut costs by saving several megabytes on your source control server by removing the thousands of instances of the following from your code:
``` cs
/// <param name="sender">The source of the event.</param>
/// <param name="e">The EventArgs instance containing the
/// event data.</param>
```
_(Joking)_
But what if there's a good reason that comments in C# have lost their importance? Visual Studio makes code navigation so elementary that it's as easy to find and read a method's source as it is to look up its documentation. Maybe C# developers have simply learnt that reading docs is the hard way of doing things.
Haskell
-------
A similar phenomena has occurred in the Haskell community as well, but maybe for a different reason.
The vast majority of Haskell documentation is minimal to the point of absurdity (I'm not complaining, just pointing out a fact). Take the [standard XHTML combinator library](http://hackage.haskell.org/packages/archive/xhtml/3000.2.0.1/doc/html/Text-XHtml-Strict.html) for example. Giant swathes of data and functions have no documentation at all, and those that do only have a few words. No overall usage information for the library is provided anywhere.
I'm going to say that the poor documentation is mainly due to two things: Haskell's very descriptive type system, and that Haskell developers as a general lot are fairly skilled programmers. My question here is, assuming that my second point has any shred of truth, does that mean that skilled programmers don't consider detailed docs useful?
I Have No Conclusion
--------------------
I haven't experienced enough diversity in development environments to draw any meaningful conclusions on this topic, but I'll write some up anyway.
There are of course some situations where extensive docs is a no-brainer: any kind of API that will be used by anyone without easy access to your source code, for example, or methods where you're doing something _really_ obscure.
All I can say in general is that it's a pleasure working with codebases with documentation that's well-written and which has obviously had some thought put into it, so I'll continue to document my own code the same way.
<file_sep>+++
location = "Calgary"
published_at = 2010-11-07T00:00:00-06:00
slug = "vim-is-writeroom-level-2"
tiny_slug = "30"
title = "Vim is WriteRoom Level 2"
+++
I'm participating in [NaNoWriMo](http://www.nanowrimo.org/) this month and the absolutely critical tool for someone with Internet-fueled ADD like myself is a suite for distraction free writing that will isolate a writer from their busy computer environment.
The traditional choice on Mac OSX has been WriteRoom, an application that will take the user into a very minimalist fullscreen writing mode. Perfect for the aspiring author.
Unfortunately, to a Vim user, WriteRoom is nice, but isn't really a tolerable solution. Luckily, using [MacVim](http://code.google.com/p/macvim/) combined with a small startup script, we can reproduce the WriteRoom interface and get the best of both worlds.
``` vim
set lines=50
set columns=80
colorscheme koehler
set guifont=Monaco:h10
set guioptions-=r
set fuoptions=background:#00000000
set fu
" green normal text
hi Normal guifg=#B3EA46
" hide ~'s
hi NonText guifg=bg
" wrap words
set formatoptions=1
set lbr
" make k and j navigate display lines
map k gk
map j gj
```
Save this as a `*.vim` script (e.g. `focus.vim`) and source it in using MacVim's `mvim` command: `mvim -S focus.vim <file to edit>`. I personally use set an alias for it as well: `alias vif='mvim -S focus.vim'`.
As you can see, we get an interface nearly indistinguishable from the one offered by WriteRoom, and with the full power of Vim. Outstanding!
<div class="figure">
<a href="/assets/images/articles/vim-is-writeroom-level-2/vim-masquerading-as-writeroom.png" title="Link to full-size image"><img src="/assets/images/articles/vim-is-writeroom-level-2/vim-masquerading-as-writeroom-small.png" alt="Vim masquerading as WriteRoom" /></a>
<p><strong>Fig. 1:</strong> <em>Vim masquerading as WriteRoom</em></p>
</div>
<file_sep>+++
location = "Calgary"
published_at = 2011-08-03T07:50:00-06:00
slug = "subtleties-of-the-x-clipboard"
tiny_slug = "x-clipboard"
title = "Subtleties of the X Clipboard"
+++
A few months back, I started running the lean Archlinux build that I've been using through to today. I elected not to use a display manager, instead preferring booting [Awesome](http://awesome.naquadah.org/) (an aptly named tiling window manager) via the `startx` script. After getting used to Awesome's key bindings, and throwing Luakit, Urxvt and Tmux into the mix, I got about as close to an optimized Linux build as I was likely to get.
Everything was perfect ... except for one aspect: the clipboard. Its behavior was utterly perplexing: I could select text and middle-click (or `Shift-Insert`) it most places I wanted, but I could only copy _out_ of Chromium; while pasting it seemed to only respect text that had been copied from itself. Vim was even worse, even with `set clipboard=unnamed` it didn't seem to play nice with anything else.
This was pretty frustrating--the clipboard's importance in the everyday workflow really can't be understated. So what was the problem? To understand, we have to know a little more about the X clipboard.
The X Clipboard
---------------
In X10, **cut-buffers** were introduced. The concept behind this now obsolete mechanism was that when text was selected in a window, the window owner would copy it to a property of the root window called `CUT_BUFFER1`, a universally owned bucket available to every application on the system. General consensus on cut-buffers was that they were the absolute salt of the Earth, so a new system was devised.
Thus **selections** came about. Rather than applications copying data to a global bucket, they request ownership of a selection. When paste is called from another application, it requests data from the client that currently owns the selection. Aside from being much more versatile and less volatile than cut-buffers, selections can also be faster because no data has to be sent on a copy (only on paste). This is especially advantageous when there's a slow connection to the X server, but this strength is also a weakness because data made available by an application disappears when it closes.
Three selections are defined in the <acronym title="Inter-Client Communication Conventions Manual">ICCCM</acronym>: `CLIPBOARD`, `PRIMARY`, and `SECONDARY`, each of which behaves like a clipboard in its own right:
* `CLIPBOARD`: traditionally used when text is copied and pasted from the edit menu, or via the `Ctrl+C` and `Ctrl+V` shortcuts in applications that support them.
* `PRIMARY`: traditionally used when a mouse selection is made, and pasted with middle-click or `Shift-Insert`.
* `SECONDARY`: ill-defined secondary selection. Most applications don't use it.
The heart of the problem for me is that I expected the X clipboard to behave like the clipboard on Windows or Mac OS X, but in fact X's architecture is fundamentally different with two separate, yet equally important, clipboards in use.
### Vim
Naturally, I had to know how Vim interacts with the X clipboard and was pleased to discover that it has some really great documentation on the subject (see for yourself with `:help x11-selection`). When running a GUI or X11-aware version of Vim, it has two registers that interact with X:
* `*` (as in `"*yy`): is the `PRIMARY` selection. `:set clipboard=unnamed` aliases it to the unnamed register.
* `+`: is the `CLIPBOARD` selection. `:set clipboard=unnamedplus` aliases it to the unnamed register.
Vim does not interact with the `SECONDARY` selection.
In Practice
-----------
I'm a Linux person at heart, but for me the two equal and separate selections remain an unfortunate usability problem. Luckily for anyone with the same disposition, [Autocutsel](http://www.nongnu.org/autocutsel/) can help make X's behavior more logical and intuitive. It's a great little program that synchronizes the cut-buffer with `CLIPBOARD`, or both the cut-buffer and `CLIPBOARD` with `PRIMARY` as well.
Install Autocutsel (`pacman -S autocutsel` on Arch) and put the following two lines into your `.xinitrc` (or just run them from a terminal to immediately observe the effects):
```
autocutsel -fork &
autocutsel -selection PRIMARY -fork &
```
Now, no matter where you copy and paste from, be it `Ctrl+C` in Chrome, `p` in Vim, or through text selection in X, your clipboard is consistent across the entire system.
<file_sep>module github.com/brandur/mutelight
go 1.16
require (
github.com/brandur/modulir v0.0.0-20210918175748-8578b95b4e98
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/joeshaw/envdecode v0.0.0-20200121155833-099f1fc765bd
github.com/logrusorgru/aurora v2.0.3+incompatible // indirect
github.com/pelletier/go-toml v1.8.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.7.0
github.com/spf13/cobra v1.1.1
github.com/yosssi/ace v0.0.5
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5
golang.org/x/sys v0.0.0-20210917161153-d61c044b1678 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1
)
<file_sep>+++
location = "Calgary"
published_at = 2010-12-29T00:00:00-07:00
slug = "using-the-little-known-built-in-net-json-parser"
tiny_slug = "40"
title = "Using the Little-known Built-in .NET JSON Parser"
+++
You wouldn't know it, but an alternative to the multitude of JSON parsers built for the .NET platform is to use the one built into the core libraries of .NET itself. It feels like it flies under the radar a bit, which I suspect is due to it not being [listed on the JSON site](http://www.json.org/). The main advantage of preferring the built-in library is that there's one less dependency to track, but a bonus is that we can easily deserialize from multiple formats because the parser works by treating JSON like XML, as I'll discuss in a moment.
Use the JSON deserializer by building an `XmlReader` instance from the static class `JsonReaderWriterFactory`, then using your favorite XML querying technique to extract data (I use XPath below). JSON classes come from the `System.Runtime.Serialization.Json` namespace, accessible by adding a project reference to `System.Runtime.Serialization`.
``` cs
string filename = args[0];
byte[] buffer = File.ReadAllBytes(filename);
XmlReader reader =
JsonReaderWriterFactory
.CreateJsonReader(buffer, new XmlDictionaryReaderQuotas());
XElement root = XElement.Load(reader);
// The fields we'd like to extract
XElement form = root.XPathSelectElement("//form");
XElement status = root.XPathSelectElement("//status");
XElement type = root.XPathSelectElement("//type");
// Field set
IEnumerable<XElement> fields = root.XPathSelectElements("//fields/*");
```
If any of the elements we selected didn't exist, the corresponding `XElement` will hold a `null`. This program will read a simple JSON document like the following:
``` js
{
"form": 13,
"status": "NEW",
"type": "FORM",
"fields": {
"field": { "key": 50, "value": 1 }
}
}
```
Now for the interesting part! Notice in the code snippet above that we load our JSON document with an `XmlReader` and treat it almost exactly like XML. We can leverage this property by rewriting our simple parser to read either a JSON or an XML document.
``` cs
string filename = args[0];
byte[] buffer = File.ReadAllBytes(filename);
XmlReader reader = new FileInfo(filename).Extension.ToLower() == "xml"
? XmlReader.Create(new MemoryStream(buffer))
: JsonReaderWriterFactory
.CreateJsonReader(buffer, new XmlDictionaryReaderQuotas());
XElement root = XElement.Load(reader);
// The fields we'd like to extract
XElement form = root.XPathSelectElement("//form");
XElement status = root.XPathSelectElement("//status");
XElement type = root.XPathSelectElement("//type");
// Field set
IEnumerable<XElement> fields = root.XPathSelectElements("//fields/*");
```
Now our parser will work fine with an XML document that looks like this:
``` xml
<message>
<form>13</form>
<status>ACC</status>
<type>NOOP</type>
<fields>
<field>
<key>50</key>
<value>1</value>
</field>
</fields>
</message>
```
Obviously the similarity of the two types of documents breaks down when we start using more complex features such as JSON's array support, or XML's namespaces; but it sure works great for simple cases.
<file_sep>+++
location = "Berlin"
published_at = 2012-06-09T14:33:13-06:00
slug = "ruby-debug"
title = "A Cross-version Debug Pattern for Ruby"
+++
As circumstances would have it, I work with a few projects that need to be compatible with both Ruby 1.8 and 1.9. I also like to use a debugger, and getting one to work seemlessly under both versions isn't exactly intuitive, so I wanted to share a nice pattern that I've been using recently in my personal projects.
The traditional debugger `ruby-debug` has been known to be 1.9 incompatible for some time now, but more recently, its updated version `ruby-debug19` is no longer 1.9 compatible having been broken by 1.9.3 without a new release. Luckily, the awesome new [`debugger`](https://github.com/cldwalker/debugger) gem stepped in to fill the gap.
Include both debuggers in your `Gemfile` with platform conditionals:
``` ruby
group :development, :test do
gem "debugger", "~> 1.1.3", :platforms => [:ruby_19]
gem "ruby-debug", "~> 0.10.4", :platforms => [:ruby_18]
end
```
I debug pretty often, but don't like to type a lot, so I usually include a shortcut in my `test_helper.rb` to get a debugger invoked quickly regardless of the Ruby version that you're running:
``` ruby
def d
begin
require "debugger"
rescue LoadError
require "ruby-debug"
end
debugger
end
```
Now drop it into a file like so:
``` ruby
def requires_frequent_debugging
risky_call rescue nil
Singleton.manipulate_global_state
d # the debugger will start on the next line
Model.do_business_logic
super
end
```
It might seem like the debugger would start in the `d` method rather than where you want to debug, forcing you to finish the stack frame before you could start debugging. Fortunately, that's not the case. The `d` method has returned by the time the debugger is invoked, leaving you exactly where you want to be.
In a classic case of open-source overkill, I've extracted the pattern described above into a trivial gem called [d2](https://github.com/brandur/d2). Throw it in your Gemfile, make sure that your project is either using `Bundler.setup` or including `require 'd2'` somewhere, then use `d2` somewhere to trigger the debugger.
<span class="addendum">Aside --</span> A slightly interesting Ruby tidbit related to the code above is that we use `rescue LoadError` because a generic `rescue` only catches `StandardError` exceptions. `LoadError` is derived from a different hierarchy headed by `ScriptError`.
<file_sep>+++
location = "the De Young Museum, San Francisco"
published_at = 2012-11-10T14:59:56-08:00
slug = "asset-pipeline"
title = "The Asset Pipeline in Sinatra"
+++
The spectacular asset pipeline that shipped with Rails 3.1 is an easy feature to get used to once you've started using it, and when writing light Sinatra apps it's one feature that I miss enough to pull in. Initially, I'd boot up a Sprockets module directly in my application's rackup file (that's `config.ru`) and map it to a particular URL path. This approach works well, but makes a mess in the rackup file and offers little in terms of fine-grained control. More recently I've found that I can get better flexibility and clarity by running it from a custom Sinatra module.
Add Sprockets and Yahoo's YUI compressor to your `Gemfile`:
``` ruby
gem "sprockets"
gem "yui-compressor"
# I find it well worth to include CoffeeScript and SASS as well
gem "coffee-script"
gem "sass"
```
Your assets file structure should look something like this:
```
+ assets
+ images
- my-jpg.jpg
- my-png.png
+ javascripts
- app.js
- my-scripts.coffee
+ stylesheets
- app.css
- my-styles.sass
```
`app.js` should load all other JavaScript assets in its directory (in the example structure above this will pick up `my-scripts.coffee`):
``` javascript
//= require_tree
```
`app.css` as well (includes `my-styles.sass`):
``` css
//= require_tree
```
The Sinatra module should look something like this:
``` ruby
class Assets < Sinatra::Base
configure do
set :assets, (Sprockets::Environment.new { |env|
env.append_path(settings.root + "/assets/images")
env.append_path(settings.root + "/assets/javascripts")
env.append_path(settings.root + "/assets/stylesheets")
# compress everything in production
if ENV["RACK_ENV"] == "production"
env.js_compressor = YUI::JavaScriptCompressor.new
env.css_compressor = YUI::CssCompressor.new
end
})
end
get "/assets/app.js" do
content_type("application/javascript")
settings.assets["app.js"]
end
get "/assets/app.css" do
content_type("text/css")
settings.assets["app.css"]
end
%w{jpg png}.each do |format|
get "/assets/:image.#{format}" do |image|
content_type("image/#{format}")
settings.assets["#{image}.#{format}"]
end
end
end
```
Now use the assets module as middleware in `config.ru`, and delegate everything else to your main app:
``` ruby
use Assets
run Sinatra::Application
```
<file_sep>+++
location = "Calgary"
published_at = 2009-03-17T00:00:00-06:00
slug = "reading-the-names-of-camera-lenses"
tiny_slug = "7"
title = "Reading the Names of Camera Lenses"
+++
Reading the names of SLR lenses may look like a daunting task to a newcomer, but with a little knowledge of basic photography and the names of a brand's lens designations (and their abbreviations), it's actually pretty easy. The different parts of the name of a popular Nikon lens are broken down in Fig. 1 below.
<div class="figure">
<a href="/assets/images/articles/reading-the-names-of-camera-lenses/parts-of-a-lens-name.png" title="Link to image"><img src="/assets/images/articles/reading-the-names-of-camera-lenses/parts-of-a-lens-name.png" alt="Parts of a lens name" /></a>
<p><strong>Fig. 1:</strong> <em>Parts of a lens name: brand, focal length(s), maximum aperture(s), other</em></p>
</div>
Here are more detailed descriptions of each part:
* **Brand:** the maker of the lens such as _Nikon_ or _Canon_. This part may also contain information on the type of camera that the lens is compatible with, for example _Canon EF-S_ indicates a lens that only works with cameras that have APS-C sized sensors.
* **Focal length(s):** the distance between the centre of the lens and the camera's focal point (the sensor on a digital SLR) when an in-focus image is formed of a distant object. With a _zoom lens_, this number will be a range like 18-200mm, which means that the lens can use focal lengths anywhere from 18mm to 200mm as needed to pull away or zoom in on a subject. A _prime lens_ only has a fixed focal length and will look something like 10.5mm.
* **Maximum aperture(s):** describes the widest diameter to which the camera's _aperture_ (a hole that lets in light) can adjust itself. On a _zoom lens_, like the lens focal lengths, this number will also be a range like f/3.5-5.6. The starting number is the maximum aperture at the camera's shortest focal length, and the ending number is the maximum aperture at the camera's longest focal length.
* **Other:** this is a list of various features and/or integrate technologies of the lens. These abbreviations vary from manufacturer to manufacturer, so you'll have to look up the ones that you don't recognize.
The list below describes each lens feature from the example in Fig. 1:
* **G:** indicates a _gelded_ lens. These are lenses that are not equipped with aperture rings in order to save cost. Instead, the aperture size is changed by the camera it's mounted on. As [Ken Rockwell](http://www.kenrockwell.com/) puts it: G is not a feature, it is a handicap.
* **ED-IF:** actually a combination of two features, _ED_ indicating _extra-low dispersion_ and _IF_ indicating internal focusing. _ED_ is a glass technology that allows for a fast super telephoto without the chromatic aberration that would normally occur and reduce its images' sharpness. _IF_ was an advancement that allowed lenses to do all their focusing internally, where previously the entire lens had to move in and out to focus ([more on internal focusing](http://www.kenrockwell.com/nikon/nikortek.htm#if)).
* **AF-S:** indicates _autofocus_ via _silent wave motor_. Lenses with this feature allow a lens to be focused manually at any time, even if autofocus is still turned on.
* **VR:** indicates vibration reduction, Nikon's technology to compensate for the natural shakiness of your hands while a photo is being taken. Canon's similar technology is called IS (Image Stabilizer) and Sigma's OS (Optical Stabilizer).
* **DX:** indicates compatibility with Nikon's line of small-frame cameras. The sensor in DX series cameras shoots a smaller 16 x 24mm frame while the FX series shoots at full-frame size.
<file_sep>+++
location = "Berlin"
published_at = 2012-06-08T11:16:35-06:00
slug = "authbind"
title = "Authbind with a Simple Test"
+++
Having recently deployed an [ELB](http://aws.amazon.com/elasticloadbalancing/) in front of the production instances running the core Ruby application in our ecosystem, we started experimenting with the idea of removing Nginx from the box's HTTP stack. Why? Having been devised by people smarter than myself, I couldn't understand this idea initially, so let me explain a little further.
We use Unicorn because of its nice [restarting trick](https://github.com/blog/517-unicorn) that enables deploys with minimal complexity, and with no dropped connections. A side effect of the mechanism Unicorn uses to provide this feature is that the Unicorn master process runs on a single port which accepts connections, then delegates to one of the worker processes running on the box. That single port bound to by the master process makes a very nice target for the ELB, removing the need for a reverse proxy local to the box. One less component in the HTTP stack is one less piece that can fail, and reduces the incumbent knowledge required to properly manage our stack.
The fact that Unicorn was designed with the expectation of being run behind Nginx to buffer incoming requests and handle slower connections (it's right there on [the Unicorn philosophy page](http://unicorn.bogomips.org/PHILOSOPHY.html)) is another discussion, but we generally found that Unicorn runs pretty well on its own for our purposes. That is except when it's behind an ELB in HTTPS mode, but those findings deserve an article of their own.
Authbind
--------
Assuming that you want to deploy Unicorn on port 80, the very first challenge you'd run into is that on a typical Linux box, root privileges are required to bind to any ports below 1024. A great way to work around this is by using Authbind, start by installing it via your favorite package manager:
``` bash
aptitude install authbind
```
Authbind's permissions are managed with a special set of files in `/etc/authbind`. Create a file telling Authbind that binding to port 80 should be allowed:
``` bash
touch /etc/authbind/byport/80
```
Authbind determines that a user is allowed to bind an application to port 80 if they have access to execute this file. Change ownership of the file to the user your web server runs under (assumed to be `http` here) and make sure it has executable (`x`) permissions. Alternatively, we could accomplish the same thing using groups.
``` bash
# as root
chown http /etc/authbind/byport/80
chmod 500 /etc/authbind/byport/80
```
Test the setup using Python's built-in HTTP server:
``` bash
# as http user
authbind python -m SimpleHTTPServer 80 # Python 2.x
authbind python -m http.server 80 # Python 3.x
```
That's it! Notice that the web server command here should be prefixed by the `authbind` command for this to be allowed. Another Authbind invocation worth mentioning is `authbind --deep` which enables port binding permissions for the program being executed, as well as any other child programs spawned from it.
<file_sep>+++
location = "Calgary"
published_at = 2010-09-01T00:00:00-06:00
slug = "silverlight-datagrid-make-right-click-select-a-row"
tiny_slug = "28"
title = "Silverlight DataGrid: Make Right-click Select a Row"
+++
A slightly irking characteristic of many data grid libraries is that there seems to be a disconnect between expected usability in a grid, and the default behaviour of those same grids. I've found this to be a problem in all .NET grids that I've used including Infragistics and Microsoft's WPF/Silverlight implementations.
For example, one thing I expect to be able to do is right-click on a grid's row, and have it pull up a context menu with a list of actions to perform on it. Now that context menus have been added to Silverlight 4, half the battle is won, but you still can't get the "correct" right-click behavior out of the box.
Here's how to coax the grid to behave a bit more properly with `VisualTreeHelper`.
``` xml
<!-- XAML -->
<UserControl x:Class="MyControl"
xmlns:grid="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">
<grid:DataGrid MouseRightButtonDown="_grid_MouseRightButtonDown">
<!-- Define a context menu for our grid here -->
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Action!" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</grid:DataGrid>
</UserControl>
```
``` cs
// Code-behind
private void _grid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
IEnumerable<UIElement> elementsUnderMouse =
VisualTreeHelper
.FindElementsInHostCoordinates(e.GetPosition(null), this);
DataGridRow row =
elementsUnderMouse
.Where(uie => uie is DataGridRow)
.Cast<DataGridRow>()
.FirstOrDefault();
if (row != null)
_grid.SelectedItem = row.DataContext;
}
```
The code above uses `VisualTreeHelper` to find any `UIElement`s under the mouse when the user performs a right-click. A set of `UIElement`s is returned including grid rows and cells as well as a good number of other elements. We filter this set for an instance of `DataGridRow`, get is bound data item, then tell the grid to select that object.
<file_sep>+++
location = "Calgary"
published_at = 2009-03-02T00:00:00-07:00
slug = "song-2-is-radios-favourite-track"
tiny_slug = "3"
title = "Song 2 is Radio's Favourite Track"
+++
If you listen to a lot of rock on the radio, you may have noticed by now that Blur's _Song 2_ has consistently been a big winner for years, outlasting the vast majority of other popular songs. _Song 2_ is good, upbeat, and people like it, making it a perfect song for the radio.
What do our friendly radio stations _really_ like about _Song 2_ though? Well, it's short. Clocking in at a mere 1:58, the stations can get some music out of the way before getting back to what they really enjoy: commercials, radio personalities reiterating day old stories that they found on Digg, and more commercials.
<file_sep>package main
import (
"fmt"
"math/rand"
"os"
"strings"
"time"
"github.com/joeshaw/envdecode"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
"github.com/brandur/modulir"
)
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Main
//
//
//
//////////////////////////////////////////////////////////////////////////////
func main() {
rootCmd := &cobra.Command{
Use: "mutelight",
Short: "Mutelight is a static site generator",
Long: strings.TrimSpace(`
Mutelight is a static site generator for the Mutelight' blog.
See the product in action at https://mutelight.org.`),
}
buildCommand := &cobra.Command{
Use: "build",
Short: "Run a single build loop",
Long: strings.TrimSpace(`
Starts the build loop that watches for local changes and runs
when they're detected. A webserver is started on PORT (default
5009).`),
Run: func(cmd *cobra.Command, args []string) {
modulir.Build(getModulirConfig(), build)
},
}
rootCmd.AddCommand(buildCommand)
loopCommand := &cobra.Command{
Use: "loop",
Short: "Start build and serve loop",
Long: strings.TrimSpace(`
Runs the build loop one time and places the result in TARGET_DIR
(default ./public/).`),
Run: func(cmd *cobra.Command, args []string) {
modulir.BuildLoop(getModulirConfig(), build)
},
}
rootCmd.AddCommand(loopCommand)
// Make sure to seed the random number generator or else we'll end up with
// the same random results for every build.
rand.Seed(time.Now().UnixNano())
if err := envdecode.Decode(&conf); err != nil {
fmt.Fprintf(os.Stderr, "Error decoding conf from env: %v", err)
os.Exit(1)
}
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error executing command: %v", err)
os.Exit(1)
}
}
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Variables
//
//
//
//////////////////////////////////////////////////////////////////////////////
// Left as a global for now for the sake of convenience, but it's not used in
// very many places and can probably be refactored as a local if desired.
var conf Conf
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Types
//
//
//
//////////////////////////////////////////////////////////////////////////////
// Conf contains configuration information for the command. It's extracted from
// environment variables.
type Conf struct {
// AbsoluteURL is the absolute URL where the compiled site will be hosted.
// It's used for things like Atom feeds.
AbsoluteURL string `env:"ABSOLUTE_URL,default=https://mutelight.org"`
// Concurrency is the number of build Goroutines that will be used to
// perform build work items.
Concurrency int `env:"CONCURRENCY,default=30"`
// Drafts is whether drafts of articles and fragments should be compiled
// along with their published versions.
//
// Activating drafts also prompts the creation of a robots.txt to make sure
// that drafts aren't inadvertently accessed by web crawlers.
Drafts bool `env:"DRAFTS,default=false"`
// SorgEnv is the environment to run the app with. Use "development" to
// activate development features.
MutelightEnv string `env:"MUTELIGHT_ENV,default=production"`
// GoogleAnalyticsID is the account identifier for Google Analytics to use.
GoogleAnalyticsID string `env:"GOOGLE_ANALYTICS_ID"`
// NumAtomEntries is the number of entries to put in Atom feeds.
NumAtomEntries int `env:"NUM_ATOM_ENTRIES,default=20"`
// Port is the port on which to serve HTTP when looping in development.
Port int `env:"PORT,default=5009"`
// TargetDir is the target location where the site will be built to.
TargetDir string `env:"TARGET_DIR,default=./public"`
// Verbose is whether the program will print debug output as it's running.
Verbose bool `env:"VERBOSE,default=false"`
}
//////////////////////////////////////////////////////////////////////////////
//
//
//
// Private
//
//
//
//////////////////////////////////////////////////////////////////////////////
const (
mutelightEnvDevelopment = "development"
)
func getLog() modulir.LoggerInterface {
log := logrus.New()
if conf.Verbose {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.InfoLevel)
}
return log
}
// getModulirConfig interprets Conf to produce a configuration suitable to pass
// to a Modulir build loop.
func getModulirConfig() *modulir.Config {
return &modulir.Config{
Concurrency: conf.Concurrency,
Log: getLog(),
LogColor: terminal.IsTerminal(int(os.Stdout.Fd())),
Port: conf.Port,
SourceDir: ".",
TargetDir: conf.TargetDir,
Websocket: conf.MutelightEnv == mutelightEnvDevelopment,
}
}
<file_sep>+++
location = "Calgary"
published_at = 2011-04-28T20:19:00-06:00
slug = "redesigned-for-readability"
tiny_slug = "redesign"
title = "Redesigned for Readability"
+++
A few months ago I realized that I disliked the design of my blog enough that I'd usually run my own articles through [Readability](http://readability.com) before trying to read them. Despite being a design insensitive coder, even I realized that I had a case of really horrendous usability on my hands.
Here are a few features of the new design:
* **Google Web Fonts:** I use the [Google Web Fonts API](http://www.google.com/webfonts) to provide a consistent font experience across most platforms. The best part about Google Web Fonts though is that they look great on Linux browsers that would otherwise annoyingly render Linux Font (TM).
* **Text width:** articles should be approximately 100 characters wide for near optimum readability, but will shrink to fit smaller windows where necessary.
* **Text-shadow:** a CSS3 trick that makes text more readable, especially against a distracting background like the one you see here.
* **White space:** I thought that I was doing a pretty good job of using white space before, but was probably mistaken. I like it so much that from now on, I might just use it more often.
Although not quite as visible, I've moved away from **Nanoc** to a new backend:
* <del>**Ruby on Rails:** Mutelight now runs a custom built Rails-powered backend. Overall I find that the flexibility of having the full power of Rails available far outweighs the cost of writing a backend from scratch (working with Rails, writing a backend for a site like this really doesn't take very long). Moving away from a static compiler may come with performance concerns, but in the end Rails' full page caching comes out just as fast. I'll talk about this more in a future article.</del> (it still doesn't run on a static generator, but it's no longer powered by Rails)
* **Client-side syntax highlighter:** due to concerns with the speed of an EC2 micro instance, I've moved away from Pygments to [jQuery Syntax Highlighter](http://balupton.com/projects/jquery-syntaxhighlighter/). It does just as good of a job, and produces pristine markup as a bonus. After investigating available options extensively, I now feel that client-side syntax highlighters are the way forward these days.
* **Tiny URLs:** short links now look like `/a/redesign` instead of `/a/22`, providing more useful context.
* <del>**Formats for free:** all pages will now respond to JSON requests as well as the default HTML. Try accessing [http://mutelight.org/articles/redesigned-for-readability.json](http://mutelight.org/articles/redesigned-for-readability.json) for example.</del> (a subsequent redesign has disabled this feature; I no longer consider it to have much merit)
Another step that I've taken is to remove Disqus commenting (for now at least). I was hoping that these might be effective for correcting mistakes that I've made in articles, but in practice this doesn't seem to happen very often. If you discover a mistake, e-mail me at **<EMAIL>** or send a pull request for a correction [on Github](https://github.com/brandur/mutelight), and I'll get around to correcting myself as soon as possible.
That said, I'm hugely thankful to the people who took the time to leave a comment on the old blog. I do hope you'll continue to provide feedback through other channels.
Lastly, I'll probably be making tweaks over the next few weeks. Enjoy!
<file_sep>+++
location = "Calgary"
published_at = 2010-07-16T00:00:00-06:00
slug = "vimperator+readability"
tiny_slug = "26"
title = "Vimperator + Readability"
+++
* *[Vimperator](http://vimperator.org/)* -- gives Firefox Vim bindings and enables keyboard-based web browsing.
* *[Readability](http://lab.arc90.com/experiments/readability/)* -- reformats hard-to-read web pages (all too common these days) for sane consumption.
Normally, Readability is dragged to your browser's bookmarks toolbar and is used from there. In Vimperator, bookmarks are not too convenient to access, so it's useful to add a quickmark so that you can activate Readability in three quick keystrokes.
1. Go to [Readability](http://lab.arc90.com/experiments/readability/) and select your settings
2. Copy the Javascript used to create your bookmarklet by copying the target of the big _Readability_ button (`;y<link number`> in Vimperator)
3. Open `~/vimperator/info/default/quickmarks`
4. Add `,"r":"<copied bookmarklet code>"` to the end of the hash enclosed by `{...}` (replace `r` with the character of your choice)
5. Restart Firefox
6. Find a badly formatted page and type `gor`
<file_sep>+++
location = "Calgary"
published_at = 2010-07-15T00:00:00-06:00
slug = "building-a-command-line-environment-for-net-development-with-rake"
tiny_slug = "25"
title = "Building a Command Line Environment for .NET Development with Rake"
+++
While developing .NET projects, it's useful to have a set of simple tasks that are are runnable on the command line (rather than through Visual Studio) for a few reasons:
* You can build your solution and run its tests without opening <acronym title="Visual Studio">VS</acronym>
* During development, you can run your test suite without going through VS, which is tempermental and can be slow to respond to input
* In the case of ASP.NET, you can start a development server to view your application
* For free, you get easy commands for use with your <acronym title="Continuous Integration">CI</acronym> server
History
-------
The defacto standard for building .NET from the command line used to be a project called [NAnt](http://en.wikipedia.org/wiki/Nant), a port from Java's Ant that built projects and ran tasks based on descriptions in build XML files. A huge drawback to NAnt was that even though VS already knew how to build your solution, that information was locked up in an `.sln` file, and you'd have to define a separate set of instructions for NAnt, thus forcing you to maintain the build in two places. NAnt build files were also extremely verbose, and would become difficult to maintain for large projects.
Microsoft later introduced their own build tool called [MSBuild](http://en.wikipedia.org/wiki/Msbuild). In its most basic form, MSBuild is an executable that reads a VS solution file, and builds it for you. It also supports more sophisticated tasks that can be defined in MSBuild project files, these files have XML syntax similar to NAnt's.
They key to MSBuild's usefulness was that you'd give it an output target, and it would resolve all the necessary dependencies for you by reading your solution; no more manually building intermediary DLLs with `csc`. It even became fairly common to use a NAnt build file, but to build using an `<exec>` call to MSBuild instead of using built-in NAnt compilation tasks. In fact, I wrote and [building with MSBuild and NAnt](http://mutelight.org/articles/the-anatomy-of-a-nant-build-file.html) last year.
The problem with both NAnt and MSBuild projects is that they're XML, a markup language that is fundamentally hard to read and write for humans. A new movement appeared that started to use Ruby Rakefiles to to build .NET solutions.
Rake
----
[Rake](http://en.wikipedia.org/wiki/Rakefile) is a build tool commonly used for building projects in the Ruby world. One nice thing about it is that it is both written in Ruby, *and* allows the user to write build tasks in Ruby, keeping Rakefiles easy to read, and massively powerful with access to the complete Ruby language and all its Gems.
I'm going to provide a small walkthrough on how to get a Ruby environment installed, and getting a Rakefile up and running for a project:
1. Install [Cygwin](http://www.cygwin.com/), a Linux shell for Windows. When walking through the installer, select the *Devel* tree which includes Ruby.
2. Open a Cygwin shell
3. Download the Rubygems tarball from [Rubyforge](http://rubyforge.org/projects/rubygems/), unpack it, and from Cygwin run `ruby setup.rb install` (your home directory in Cygwin is at `C:\cygwin\home\fyrerise` by default, a good choice of download location for the tarball)
4. Install Rake with `gem install rake` and Bundler with `gem install bundler`
5. In Cygwin, navigate to your .NET project's path (get to a Windows path using `cd /cygdrive/c/Users/...`)
Bundler
-------
Ruby Gems are small software libraries that extend the core language. In most Ruby projects, a large number of Gems are usually needed, and to help manage these dependencies, a package called [Bundler](http://gembundler.com/) was written.
We'll only need a few Gems for our simple build file, but it's best to use Bundler anyway because it's easy and our complexity may increase later on. Project Gem dependencies are tracked in a file called `Gemfile`, create one in your solution's root with the following contents:
``` ruby
source 'http://rubygems.org'
gem 'albacore'
gem 'haml' # Includes Sass
```
Run `bundle install .` (from Cygwin). Two dependencies are now installed:
* **Albacore** -- provides a set of .NET build tasks for Rake
* **Haml** -- allows us to access the [Sass](http://sass-lang.com/) compiler, which I use for my ASP.NET development for a more literate CSS
Our Rakefile
------------
As promised, now it's time for our build file. Create `Rakefile` with these contents (replacing solution, and test project paths appropriately):
``` ruby
# Initialize the Bundler environment, it will handle all other dependencies
require 'rubygems'
require 'bundler'
Bundler.setup
require 'albacore'
require 'mstest_task'
require 'sass/plugin'
# Albacore still defaults to MSBuild 3.5, so specify the exe location manually
MsBuild = 'C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe'
WebDev = 'C:/Program Files/Common Files/microsoft shared/DevServer/10.0/WebDev.WebServer40.EXE'
task :default => :build
desc 'Alias for build:debug'
task :build => 'build:debug'
namespace :build do
[ :debug, :release ].each do |t|
desc "Build the Project solution with #{t} configuration"
msbuild t do |b|
b.path_to_command = MsBuild
b.properties :configuration => t
b.solution = 'Project/Project.sln'
b.targets :Build
end
end
end
desc 'Clean build files from the directory structure'
msbuild :clean do |b|
b.path_to_command = MsBuild
b.solution = 'Project/Project.sln'
b.targets :Clean
end
desc 'Alias for test:all'
task :test => 'test:all'
namespace :test do
desc 'Run all tests'
# Run the category task with no parameters, and therefore no category
task :all => 'test:category'
# Usage -- rake test:category[<category name>]
desc 'Run all tests in a category'
mstest :category, :cat, :needs => 'build:debug' do |t, args|
t.category = args[:cat] if args[:cat]
t.container = 'Project/Project.Tests/bin/Debug/Project.Tests.dll'
end
end
desc 'Start a development server'
exec :server => 'build:debug' do |cmd|
cmd.path_to_command = WebDev
path = 'Project/Project/'
# WebDev.WebServer is *extremely* finicky and is a typical example of
# fragile Microsoft coding. For it to work, its path MUST (a) use
# backslash directory separators, and (b) be absolute. Here we use Cygwin
# to convert a relative Unix path to an absolute Windows path.
path = `cygpath -a -w #{path}`.strip
cmd.parameters << %-"/path:#{path}"-
cmd.parameters << %-"/port:3001"-
puts ''
puts 'Starting development server on http://localhost:3001'
puts 'Ctrl-C to shutdown server'
end
desc 'Updates stylesheets if necessary from their Sass templates'
task :sass do
# @todo: change this once we know our stylesheets location
Sass::Plugin.add_template_location '.'
Sass::Plugin.on_updating_stylesheet do |template, css|
puts "Compiling #{template} to #{css}"
end
Sass::Plugin.update_stylesheets
end
```
Run `rake -T` for a list of available tasks. Here are the important ones:
* `rake build` -- build the project
* `rake build:release` -- build the project with release configuration
* `rake test` -- run our test suite (I'm using the MSTest framework here)
* `rake server` -- start a development server pointing to our project for ASP.NET
<file_sep>+++
location = "Calgary"
published_at = 2011-04-29T11:13:00-06:00
slug = "minimal-guide-to-debugging-php-with-xdebug-and-vim"
tiny_slug = "xdebug"
title = "Minimal Guide to Debugging PHP with XDebug and Vim"
+++
For those of us moving to PHP from modern IDEs like Visual Studio, `var_dump` and `die` are simply not enough! Luckily, I can report a generally positive experience using Vim and XDebug as an effective debugger. Here's a short guide to installation and usage.
Installation
------------
### Server-side
Install XDebug via your system's package manager, PECL/PEAR, or by compiling it from source. See [XDebug's installation instructions](http://www.xdebug.org/docs/install) for up-to-date information on this. Keep in mind though, if you already have something like Cachegrind installed on your server, you may already have and use XDebug.
Configure your PHP installation so that it knows where to find XDebug's `.so` and that debugging should be enabled. This might be done in either `php.ini` or `/etc/php5/conf.d/xdebug.ini`.
```
; point this to wherever your xdebug.so is located
zend_extension=/usr/lib/php5/20090626/xdebug.so
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
```
**Warning:** for XDebug to work properly, you may have to disable your Zend debugger if you have one installed (may be found in `/etc/php5/conf.d/zend.ini`). With Zend enabled, I could connect to an XDebug session, but the next debug command I tried to run (step into, step over, run) would terminate the session.
### Client-side
Install the [DBGp remote debugger interface for Vim](http://www.vim.org/scripts/script.php?script_id=2508). This plugin will allow Vim to interact with Xdebug.
This script requires that your Vim be compiled with Python and signs support. Type `vim --version` and look for `+python` and `+signs` in the features list. If you don't have these features, try installing your distribution's **gVim** package, often it comes along with a command executable that includes them.
Usage
-----
To initialize a debugging session, XDebug will attempt to make a connection to the remote host and port that you specified above (`localhost:9000`), so you need to make sure that your Vim is reachable at that address. Unless you're running Vim on the same server as PHP, this may involve building an SSH tunnel back to your development box.
Start debugging by opening Vim and hitting `F5`, Vim will say:
```
waiting for a new connection on port 9000 for 10 seconds...
```
You have ten seconds to open a web browser and navigate to your running PHP app. It's important to know however, that the debug session will only start if you include the parameter `XDEBUG_SESSION_START=1` with the request (see the _optimization_ section below to remove this requirement). An example URL:
```
http://mysite.com/?XDEBUG_SESSION_START=1
```
Your Vim should now enter debug mode with the debug shortcuts should be listed in a buffer on the right. For example, use `F2` to step into, `F3` to step over, and `F12` to inspect the property under your cursor.
Typing `:Bp` in command mode will toggle a breakpoint on the current line, and `F5` will run the program to hit it. `:Up` and `:Dn` move up and down the stack trace.
`,e` will allow you to evaluate arbitrary code. To fully inspect a property, I recommend running `print_r($var, true)` from eval mode. A word of warning here though: evaluating invalid code may kill your debug session, but your client (Vim) won't realize that it's defunct.
Command line PHP can also be debugged as long as XDebug is enabled in the PHP CLI `php.ini`. This is especially useful for debugging unit tests.
Optimization
------------
The requirement of including `XDEBUG_SESSION_START=1` as a request parameter can be waived by adding the following code to your `php.ini`/`xdebug.ini` and restarting your server. With this setting enabled, XDebug will attempt to start a debugging session with every request.
```
xdebug.remote_autostart=1
```
<file_sep>+++
location = "Calgary"
published_at = 2011-05-03T17:18:00-06:00
series_permalink = "masters-of-vim"
slug = "dbext-the-last-sql-client-youll-ever-need"
tiny_slug = "dbext"
title = "dbext: The Last SQL Client You'll Ever Need"
+++
As the first part of my [Masters of Vim series](/series/masters-of-vim), I'd like to introduce **dbext**, a Vim plugin that's potentially life-changing after fighting through the somewhat daunting initial configuration and usage.
This short article is no substitute for the extensive documentation that comes bundle with the plugin. Additional information and answers to any lingering questions can usually be found there.
Installation
------------
Install the plugin by downloading the [archive from Vim.org](http://www.vim.org/scripts/script.php?script_id=356), or clone the [Git mirror](https://github.com/vim-scripts/dbext.vim).
Additionally, the script itself relies on the command line clients of the various DBMSes that it supports. For dbext to work, refer to the table below and make sure that the binary appropriate for the system you'd like to work with is available. Often these clients are bundled with the DBMS itself, but otherwise should be available through your favorite package manager.
<table>
<caption>Required command line client binaries for each DBMS supported by dbext</caption>
<tr>
<th style="width: 50%;">DBMS</th>
<th style="width: 50%;">Client Bin</th>
<tr>
<tr>
<td>ASA</td>
<td><code>dbisql</code></td>
</tr>
<tr>
<td>ASE (Sybase)</td>
<td><code>isql</code></td>
</tr>
<tr>
<td>DB2</td>
<td><code>db2batch</code> or <code>db2cmd</code></td>
</tr>
<tr>
<td>Ingres</td>
<td><code>sql</code></td>
</tr>
<tr>
<td>MySql</td>
<td><code>isql</code></td>
</tr>
<tr>
<td>Oracle</td>
<td><code>sqlplus</code></td>
</tr>
<tr>
<td>PostgreSQL</td>
<td><code>psql</code></td>
</tr>
<tr>
<td>Microsoft SQL Server</td>
<td><code>osql</code></td>
</tr>
<tr>
<td>SQLite</td>
<td><code>sqlite</code></td>
</tr>
</table>
Configuration
-------------
dbext needs the connection information of the database to operate on. It provides an interactive prompt to enter it, but I'd strongly recommend configuring your `.vimrc` instead.
Any number of profiles (connections) can be configured using this basic format:
``` vim
let g:dbext_default_profile_<profile_name> = '<connection string>'
```
For example:
```
" MySQL
let g:dbext_default_profile_mysql_local = 'type=MYSQL:user=root:passwd=<PASSWORD>:dbname=mysql'
" SQLite
let g:dbext_default_profile_sqlite_for_rails = 'type=SQLITE:dbname=/path/to/my/sqlite.db'
" Microsoft SQL Server
let g:dbext_default_profile_microsoft_production = 'type=SQLSRV:user=sa:passwd=<PASSWORD>:host=localhost'
```
These profile names will be used later to select a database on which to run query, so it's recommended that you make them somewhat logical.
Usage
-----
Open Vim pointing to a `*.sql` file. The SQL extension is not necessary to use dbext, but it's useful to get syntax highlighting. Write in a simple query relevant to your database:
``` sql
select * from user limit 100
```
Move your cursor to anywhere on the line you entered and type `<leader>sel` for `s` SQL, `e` execute, `l` line (from here on out I'm going to assume that `leader` is `\`). dbext will prompt you for a connection:
```
0. None
1. mysql_local
2. sqlite_for_rails
3. microsoft_production
[Optional] Enter profile #: 0
```
Enter the number corresponding to the connection for which your query will run with the results appearing in a split below (`C-w =` to even out the heights of each split).
```
+--------+----------+
| userID | username |
+--------+----------+
| 1 | bob |
| 2 | joe |
| 3 | jen |
+--------+----------+
```
The `\se` (`s` SQL, `e` execute) command is useful for multiline queries. It searches backwards for the beginning of a query by looking for certain SQL command keywords (e.g. `SELECT`) and searches forwards for the end of a query by looking for your connection's command terminator (e.g. `;`). For example, the following SQL should execute with `\se` no matter where your cursor is on it:
``` sql
select *
from user
limit 100;
```
`\st` selects everything from the table whose name is under your cursor (e.g. `user` in the previous example).
`\sT` selects from the table under your cursor, but prompts for the number of rows to select. This is a much safer alternative to `\st` when working with a lot of data.
`\stw` selects from the table under your cursor, but prompts for a where clause (don't include the keyword `WHERE`).
`\sta` prompts for table name, then selects from that table.
### Schema
`\sdt` describes the table whose name is under your cursor:
```
+----------+-----------------------+
| Field | Type |
+----------+-----------------------+
| userID | mediumint(8) unsigned |
| username | varchar(30) |
+----------+-----------------------+
```
`\sdp` is very similar, but instead describes the stored procedure under your cursor.
The three command directives `:DBListTable`, `:DBListProcedure`, and `:DBListView` list the database's tables, stored procedures, and views respectively. I find it useful to map the table list to its own key:
``` vim
map <leader>l :DBListTable<CR>
```
`\slc` copies each of the column names in the table under your cursor to the unnamed register in a format like `userID, username`. This is useful for constructing select queries on tables.
### The Results Buffer
There are a few useful shortcuts specific to when your cursor is in the results buffer.
* `R` will re-run the command which populated the current results.
* `q` will quickly close the results.
Summary
-------
Recall that this article was written to be a very minimal introduction to dbext to highlight what are (in my opinion) some of its most useful features. Refer to dbext's excellent documentation to discover its full potential.
<file_sep>+++
location = "Calgary"
published_at = 2009-06-23T00:00:00-06:00
slug = "four-versions-and-eight-years-in-the-making-iset"
tiny_slug = "13"
title = "Four Versions and Eight Years in the Making: ISet"
+++
Another addition to .NET 4.0 that I'd previously missed is an interface that most of us had long ago given up on ever seeing in as part of a Microsoft product: the `ISet<T>` interface. The [set documentation is on MSDN](http://msdn.microsoft.com/en-us/library/dd412081.aspx), and if you've previously used the `HashSet` class, it should look pretty familiar.
I say that `ISet` is four versions and eight years in the making, because practically speaking, a framework like .NET should've probably included set interfaces and implementations from the get-go. This article's original title was _four versions and eight years *late*_, which in all fairness, might be a more accurate description of the situation. Java, a language that C# borrowed from heavily (to say the least), has had its own `Set` interface since version 1.2, released in December 1998, years before C#'s first release in 2001.
Even giving Microsoft the benefit of the doubt by assuming that they had their reasons for not putting in a proper set until version 3.0, it's still pretty hard to see why they didn't see fit to put in `ISet` at the same time as `HashSet`. Another 4.0 addition, the `SortedSet`, is likely what finally forced Microsoft's hand. Having two separate set classes with no common interface probably felt a little wrong, even to them.
On a positive note, .NET 4.0 is really shaping up to be an outstanding release. With the addition of `ISet`, [tuples](/articles/finally-tuples-in-c-sharp.html), [optional/named parameters and co-variance](/articles/new-features-in-c-sharp-4.html), it seems like Microsoft is really focussing on fixing some of their previous omissions.
<span class="addendum">Addendeum --</span> Did anyone else encapsulate `Dictionary` to roll their own set implementation? I ended up using mine all the way up until `HashSet` walked onto the scene in 3.0.</p>
<file_sep>+++
location = "San Francisco"
published_at = 2012-09-03T00:19:42-07:00
slug = "1-endpoint-n-apps"
title = "1 SSL Endpoint, N Apps"
+++
A few months ago, SSL was rolled out as an included feature for every app on the Heroku platform by enabling secure connection to each app's **heroku/herokuapp.com** domain, so even if developers prefer to use a custom domain, they'll at least have an SSL option for the components of their app where a secure connection is critical.
The platform's answer for developers requiring SSL on a custom domain is the use of the [SSL Endpoint](https://devcenter.heroku.com/articles/ssl-endpoint) addon, priced at $20 a month (the dark days of $100/mo. ssl:ip are finally over!). After adding SSL Endpoint to an app, a developer uploads their cert and an endpoint is created with a name like `mie-6498.herokussl.com`. He or she then CNAMEs their domain to the endpoint and secure requests are routed through with no app changes necessary.
And just a final bit of background: any given request on the Heroku platform enters through the [routing mesh](https://devcenter.heroku.com/articles/http-routing). The tl;dr is that it finds an appropriate runtime where the an app is deployed and forwards its requests through.
One Endpoint
------------
In case the $20/mo. per app for a custom domain seems a steep price to pay, you may be happy to find out that in many cases a single SSL Endpoint can be shared between many apps.
Requests coming through an SSL Endpoint follow the same rules as the rest of the platform--a request may enter through an endpoint but from there is routed through the mesh normally. Therefore, it's not an SSL Endpoint's associated app that decides where a request goes, but rather the incoming domain that's been CNAME'd to the endpoint.
A savvy developer can take advantage of this behavior to allow a single SSL Endpoint to route to any number of Heroku apps. For the connection to stay secure, the cert uploaded to the endpoint needs to be signed for any domains that you intended for use for it, but even a [free cert from StartCom](http://www.startcom.org/) allows two domains to be included without any special verification. A wildcard certificate (i.e. `*.mutelight.org`) will secure an entire stack of apps deployed into the Heroku cloud.
Below is a simple example demonstrating how a single endpoint is shared for both [brandur.org](https://brandur.org) and [facts.brandur.org](https://facts.brandur.org):
``` bash
#
# the app brandur-org below has ssl:endpoint
# the app facts-web does not
#
$ heroku addons -a brandur-org
ssl:endpoint
$ heroku addons -a facts-web
No addons installed
#
# both www.brandur.org (entry point for the app brandur-org) and
# facts.brandur.org (app facts-web) are CNAME'd to mie-6498
#
$ host www.brandur.org
www.brandur.org is an alias for mie-6498.herokussl.com.
$ host facts.brandur.org
facts.brandur.org is an alias for mie-6498.herokussl.com.
#
# both apps get a secure connection because brandur-org's cert includes both
# domains
#
$ heroku certs -a brandur-org
Endpoint Common Name(s) Expires Trusted
---------------------- ----------------------- -------------------- -------
mie-6498.herokussl.com facts.brandur.org, 2013-07-21 03:31 UTC True
www.brandur.org
```
<file_sep>+++
location = "Calgary"
published_at = 2009-03-16T00:00:00-06:00
slug = "how-to-play-1080p-hd-video-encoded-with-x264-in-an-mkv-container"
tiny_slug = "6"
title = "How to Play 1080p HD Video Encoded with x264 in an MKV Container"
+++
Full 1080p HD video in x264/H.264 is notoriously difficult to properly decode, due to both its enormous resolution and high compression. The fact that a huge number of these videos are stored in MKV containers doesn't help the situation, mostly because some common video players don't read MKVs as optimally as possible.
The past few years have seen a plateau in terms of CPU clockspeed, so we haven't been able to rely on ever-increasing processing power to solve the problem. Instead we have to be smart about how we play our HD videos, by moving decoding to our video cards or splitting the work across multiple cores.
This article contains a few tips to play your HD videos the right way (or at least the best ways I've found to date). I've labeled the article with 1080p, but these suggestions work just as well with 720p HD video or lower.
Networked Media Tank
--------------------
If you're willing to try a hardware solution, you can save yourself quite a bit of time installing codecs and messing around with configuration settings on your PC. The idea of a box attached to your TV that can stream media over your network has been around for a while, but it's something that in my opinion, has only really come to fruition recently.
For a while, a hacked Xbox running <acronym title="Xbox Media Center">XBMC</acronym> was far and away the best media player on the market. Unfortunately, the Xbox lacks the horsepower to play any real high-definition material, and newer consoles have never been as useful for media playback as the old Xbox was. Many alternatives are available today: modded Apple TV, Xbox 360, PS3, or your own HTPC, but these options are expensive, lack codec support, or have no chance of hitting 1080p playback. Nowadays, none of these options need even be considered after the relatively recent appearance of a new class of device on the market: the networked media tank (NMT).
Networked media tanks really are just as awesome as their name suggests. These devices are small computers that run [processors made by Sigma Designs](http://www.sigmadesigns.com/public/Products/selection_guide/selection_guide.html) specifically for jobs like decoding HD media (although apparently the official definition of an NMT is a box that runs [Syabas middleware](http://www.syabas.com/solution_nmt.html).) The first thing you'll notice when trying a 1080p x264 MKV on an NMT is just how smooth the playback is, either that, or sheer amazement at how a commercial device is playing an MKV out of the box (that is if you're used to pretty but borderline useless Apple TVs and such).
The most popular NMTs are the [Popcorn Hour](http://www.popcornhour.com/) and the [HDX](http://www.hdx1080.com/) (see a [full list of NMTs](http://www.networkedmediatank.com/wiki/index.php/Products),) both of which are sleek little boxes that can stream over the network, play from a USB drive, or play from a user-installed internal HDD. You can install other interesting add-ons like a BitTorrent client, NZB downloader or a tool to grab cover art for you. These features are all great, but what's the best part? NMTs tend to weigh in just a little over $200 US, in most cases below the comparatively inadequate competition from big names. Personally, I've only had direct experience with the HDX 1000, and found it absolutely outstanding.
Windows
-------
The one HD playback solution under Windows that I'm going to talk about is hardware decoding, where your heavy-lifting is offloaded to your DXVA(DirectX Video Acceleration)-enabled video card. We'll be using Media Player Classic Homecinema so you'll need at least an Nvidia Gefore 8 series, or ATI Radeon HD series card.
Follow these steps to get up and running:
1. Download and install your video card's latest drivers ([Nvidia drivers download page](http://www.Nvidia.com/Download/index.aspx?lang=en-us))
# Download and install [Haali's Media Splitter](http://haali.cs.msu.ru/mkv/), a very fast MKV reader
2. Download and install [Media Player Classic Homecinema](http://mpc-hc.sourceforge.net/) (MPC-HC), a player bundled with DXVA support
3. Under _Options_ → _Playback_ → _Output_, choose _VMR9 (renderless)_ if you're on Windows XP (as seen in Fig. 1 below) or _EVR_ if you're on Windows Vista (see [more information on MPC-HC DXVA support](http://mpc-hc.sourceforge.net/DXVASupport.html))
4. Under _Options_ → _Internal Filters_ → _Source Filters_, uncheck the options for _Matroska_. We do this to allow Haali's Media Splitter to read our MKV files, which is faster than MPC-HC's reader.
<div class="figure">
<a href="/assets/images/articles/how-to-play-1080p-hd-video-encoded-with-x264-in-an-mkv-container/mpc-hc-options-vmr9.png" title="Link to full-size image"><img src="/assets/images/articles/how-to-play-1080p-hd-video-encoded-with-x264-in-an-mkv-container/mpc-hc-options-vmr9-small.png" alt="Settings to correctly enable VMR9 in Media Player Classic Homecinema" /></a>
<p><strong>Fig. 1:</strong> <em>MPC-HC output settings for hardware-accelerated VMR9 playback in Windows</em></p>
</div>
Mac OS X
--------
This one is easy: use [Plex](http://plexapp.com/). Plex (also known as Plexapp) is a fork of XBMC for Intel-based Macintosh computers, and it is _awesome_. Apart from its beautiful and highly-intuitive interface, Plex will use multiple cores to decode HD video, allowing you to play 1080p videos even on your notebook.
Another option, but one I've admittedly never had much luck with, is to use VLC. VLC will be too slow to play HD video out of the box, but you can configure it to skip its x264 loop filter as shown in Fig. 2 below (remember to select the _All_ option from the radio buttons in the bottom left or you won't see these settings). Depending on your processor, this may speed up VLC enough to make it usable.
<div class="figure">
<a href="/assets/images/articles/how-to-play-1080p-hd-video-encoded-with-x264-in-an-mkv-container/vlc-options-skip-loop-filter.png" title="Link to full-size image"><img src="/assets/images/articles/how-to-play-1080p-hd-video-encoded-with-x264-in-an-mkv-container/vlc-options-skip-loop-filter-small.png" alt="Settings to get better VLC performance on Mac OSX by skipping the loop filter" /></a>
<p><strong>Fig. 2:</strong> <em>VLC settings for skip loop filter on Mac OSX</em></p>
</div>
Hardware decoding support has begun to appear in Mac OSX as well. Unfortunately, as things stand today, QuickTime is the only application able to access this functionality, and installing Perian to give QuickTime access to decent codec/container support will break hardware decoding (so you can't win). Many people are hoping that Apple's upcoming release of Mac OS X 10.6 (Snow Leopard), which is supposed to move a lot of computing to the <acronym title="Graphics Processing Unit">GPU</acronym>, will resolve this problem.
Linux
-----
As of November 2008, the proprietary Nvidia drivers for Linux (and other Unix-based systems) support video hardware acceleration in the form of an API called Video Decode and Presentation API for Unix (VDPAU). VDPAU is a Unix equivalent to DXVA on Windows and support for it has already been added or is being added to many popular Linux media players. See the [Wikipedia article on VDPAU](http://en.wikipedia.org/wiki/VDPAU) for more information on supporting players.
I haven't tried VDPAU out for myself so I'll hold off on any specific instructions for Linux until I get the chance.
<file_sep>+++
location = "San Francisco"
published_at = 2012-10-21T20:12:24-07:00
slug = "unicorn-stdout"
title = "Have Unicorn Log to $stdout"
+++
A strange quirk of Unicorn is that by default it will write all its logging output to `$stderr`. Even a relatively harmless operation like a restart will result in noise written to your system error log:
``` sh
executing ["/home/core/.bundle/gems/ruby/1.8/bin/unicorn_rails", "-c", "config/normalized_unicorn.rb"] (in /home/core)
forked child re-executing...
I, [2012-10-17T09:00:35.029145 #12322] INFO -- : inherited addr=/tmp/core.sock fd=4
I, [2012-10-17T09:00:35.029885 #12322] INFO -- : Refreshing Gem list
reaped #<Process::Status: pid=2784,exited(0)> worker=1
reaped #<Process::Status: pid=2785,exited(0)> worker=2
reaped #<Process::Status: pid=2783,exited(0)> worker=0
master complete
master process ready
worker=1 ready
worker=2 ready
worker=0 ready
```
Simply redefining Unicorn's logger to one pointing to `$stdout` will fix the problem:
``` ruby
# by default, Unicorn will log to $stderr; go to $stdout instead
logger Logger.new($stdout)
```
<file_sep>+++
location = "Calgary"
published_at = 2009-02-21T00:00:00-07:00
slug = "dot-net-3-sequence-methods-moved-to-enumerable"
tiny_slug = "1"
title = ".NET 3.5 Sequence Methods Moved to Enumerable"
+++
I still see a lot of C# code samples around online that use `Sequence.Range` to generate a numerical range and `Sequence.Repeat` to repeat a number. This is a little confusing, because these methods may have been around in the early days of .NET 3.0, but have since moved to `System.Linq.Enumerable`.
Shown below is today's correct usage for `Range` and `Repeat`.
``` csharp
using System.Linq;
// Generate a range of integers
// This will enumerate 3, 4, 5, 6, 7, 8, 9
IEnumerable<int> nums = Enumerable.Range(3, 7);
// Repeat any value a given number of times
// This will enumerate 5, 5, 5
IEnumerable<int> fives = Enumerable.Repeat(5, 3);
// This will enumerate "string", "string"
IEnumerable<string> strings = Enumerable.Repeat("string", 2);
```
<file_sep>+++
location = "Calgary"
published_at = 2011-06-17T14:22:00-06:00
slug = "simple-side-by-side-live-and-sandbox-rails-deployment-with-nginx-and-phusion-passenger"
tiny_slug = "simple-phusion"
title = "Simple Side-by-side Live and Sandbox Rails Deployment with Nginx and Phusion Passenger"
+++
Quite some time ago a little language called PHP built itself a little following and, quite suddenly, became one of the largest driving forces of the Internet. One of the key features that enabled this kind of forward momentum was the simplicity with which it could be deployed: simply enable an Apache extension, drop some PHP files into a web directory, and you're live. That was a fine to have back in the early days of the new millenia, but a common misconception that still survives to this day is that PHP is still easier than anything else to deploy.
These days, I'd prefer the simplicity of deploying a Rails app over a PHP app any day, and [Phusion Passenger](http://www.modrails.com/) is the technology that's made this possible. I'd like to present some simple Nginx and Passenger configuration to deploy side-by-side development and production Rails environments.
``` nginx
server {
listen 80;
server_name mutelight.org;
root /home/http/www/mutelight.org/private/askja/public/;
passenger_enabled on;
# Keep a minimum around for fast responsiveness in production
passenger_min_instances 1;
}
server {
listen 80;
server_name pre.mutelight.org;
root /home/http/www/mutelight.org/private/pre/askja/public/;
passenger_enabled on;
rails_env development;
}
```
Here I have two [Askja](http://github.com/brandur/askja) repositories cloned at `mutelight.org/private/askja` and `mutelight.org/private/pre/askja`; Passenger makes these available at `mutelight.org` and `pre.mutelight.org` respectively. The key configuration line in both blocks is `passenger_enabled on;` which tells Passenger that the given roots are Rails apps. Also note that configured paths point to a Rails app's `public` directory, rather than Rails root.
Production at `mutelight.org` mandates that at least one Passenger instance should be kept alive at all times with `passenger_min_instances 1;`, thus keeping the site responsive when a client hits a dynamic page like [Sitemap](http://mutelight.org/sitemap.xml). This is more important for a site that performs a lot of full page caching, because cached pages will be served by Nginx directly and Passenger instances will shut themselves down with nothing to do.
Development at `pre.mutelight.org` specifies `rails_env development;` which is useful for serving better error messages, and avoiding page caching while working in the sandbox. Note that the sandbox has no `passenger_min_instances` directive, allowing all Passenger instances for the sandbox to be shut down while it's not in use.
After Nginx is up and running with the two Rails apps deployed, use the `passenger-status` command (as root) to see how many Passenger instances are running at any given time.
<file_sep>+++
location = "Calgary"
published_at = 2009-06-22T00:00:00-06:00
slug = "nunits-expectedexception-attribute-fails-from-nant"
tiny_slug = "12"
title = "NUnit's ExpectedException Attribute Fails from NAnt"
+++
It seems like there is a bug in NAnt's `<nunit2>` task that occurs when using NUnit's `ExpectedException` attribute. There seems to be [an open bug](http://sourceforge.net/tracker/?func=detail&atid=402868&aid=1942863&group_id=31650) related to this problem, but it's status has been unchanged for some time now (since April 2008). I'm using the NAnt 0.86 beta and NUnit 2.5. Here's a simple test for this problem:
``` csharp
[Test]
[ExpectedException(typeof(Exception))]
public void TestThatExpectedExceptionFails()
{
throw new Exception("wef");
}
```
And a NAnt file to build the test's project it and try to run it:
``` xml
<?xml version="1.0"?>
<project default="default">
<property name="msbuild" value="${framework::get-framework-directory(framework::get-target-framework())}\MSBuild.exe" />
<target name="default">
<exec program="${msbuild}">
<arg value="Proj.csproj" />
<arg value="/target:Rebuild" />
<arg value="/property:Configuration=Debug" />
<arg value="/verbosity:quiet" />
</exec>
<nunit2>
<formatter type="Plain" />
<test assemblyname="bin\Debug\Proj.dll" />
</nunit2>
</target>
</project>
```
Here's what NAnt has to say about that:
```
NAnt 0.86 (Build 0.86.2898.0; beta1; 12/8/2007)
Copyright (C) 2001-2007 <NAME>
http://nant.sourceforge.net
Buildfile: file:///C:/Temp/NAntTest/NAntTest/nant.build
Target framework: Microsoft .NET Framework 3.5
Target(s) specified: default
default:
[exec] Microsoft (R) Build Engine Version 3.5.30729.1
[exec] [Microsoft .NET Framework, Version
2.0.50727.3053]
[exec] Copyright (C) Microsoft Corporation 2007. All
rights reserved.
[exec]
[nunit2] Tests run: 1, Failures: 1, Not run: 0, Time:
0.031 seconds
[nunit2]
[nunit2] Failures:
[nunit2] 1) Proj.Tests.TestThatExpectedExceptionFails :
System.Exception : wef
[nunit2] at Proj.Tests.TestThatExpectedExceptionFails()
in c:\Temp\NAntTest\NAntTest\Tests.cs:line 17
[nunit2]
[nunit2]
[nunit2]
BUILD FAILED
C:\Temp\NAntTest\NAntTest\nant.build(11,6):
Tests Failed.
Total time: 1 seconds.
```
Use Assert.Throws<> Instead
---------------------------
Prior to finding this bug, I used to use `ExpectedException` fairly regularly. It wasn't until I started looking for alternatives that work in NAnt that I realized a fairly persuasive argument could be built that `ExpectedException` isn't the best tool for testing exceptions anyway.
Here are my talking points regarding what `Assert.Throws<>` has over `ExpectedException`:
1. **Readability:** when reading tests that rely on `ExpectedException`, its easy to miss the attribute declarations, which might leave you confused as to what the test was supposed to accomplish upon reading it through. Tests using asserts read cleanly top to bottom.
2. **Test multiple conditions:** a test using asserts can test for multiple thrown exceptions, while a test using `ExpectedException` can only test for one, forcing you to write multiple tests to cover all conditions.
3. **Type parameters look nice:** this one is pretty minor, but using the exception assert allows you to leave out the `typeof()` operator.
An example that demonstrates the advantages of `Assert.Throws<>` follows:
``` csharp
private void MethodWithArgChecks(string arg1, string arg2)
{
if (arg1 == null)
throw new ArgumentException("arg1 = null", "arg1");
if (arg2 == null)
throw new ArgumentException("arg2 = null", "arg2");
}
[Test]
public void TestForThrownExceptionOnBadArgs()
{
Assert.Throws<ArgumentException>(
() => MethodWithArgChecks(null, "ok")
);
Assert.Throws<ArgumentException>(
() => MethodWithArgChecks("ok", null)
);
}
```
<file_sep>+++
location = "Calgary"
published_at = 2011-12-28T22:03:00-07:00
series_permalink = "masters-of-vim"
slug = "learn-to-speak-vim"
tiny_slug = "speak-vim"
title = "Learn to Speak Vim"
+++
I don't often post a blog article containing nothing but a link to content elsewhere, but I'll be doing it today because <NAME>'s [Learn to Speak Vim -- Verbs, Nouns, and Modifiers!](http://yanpritzker.com/2011/12/16/learn-to-speak-vim-verbs-nouns-and-modifiers/) is just that important.
Frustrated beginners will claim that Vim invovles nothing but rote memorization--and they're right, but only on the most basic level. Vim's far more important feature is enabling its users to manipulate code on a large scale by building actions from the editor's primitive building blocks. Thinking of these actions as phrases built from verbs, nouns, and modifiers is a very effective way of illustrating this concept.
<file_sep>+++
location = "Calgary"
published_at = 2010-12-27T00:00:00-07:00
slug = "guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo"
tiny_slug = "39"
title = "Guide to Installing XBMC and Ubuntu on an Acer Revo"
+++
This year as a Christmas gift, my Dad bought my Mom an Acer AspireRevo, a tiny desktop computer particularly well-suited for life as an HTPC. She'd asked for a modern solution to watching movies on the TV and we decided to put together the best possible media playback solution, and at a very competitive price point.
Having recently investigated a variety of the top home theatre packages, I immediately suggested XBMC, a software package originally designed for hacked Xboxes, and which has since grown into a very solid standalone product. I know of two alternatives that didn't win out in this case, but are great home theatre solutions nevertheless:
* **Networked media tanks:** products like the Popcorn Hour and WD TV Live are surprisingly good for HD playback and certainly the best economy option. Their major downside is the interface itself, which is fairly bland (comparatively), and doesn't easily support advanced features like automatic directory indexing and metadata downloading.
* **Plex:** this suite is similar to XBMC and offers the same completeness with even more polish. Its major disadvantages are price (need a Mac), and that the head of the project has plastered pictures of his dog all over the UI.
This guide will walk you through the basic steps to get XBMC up and running at its maximum potential (some steps are specific to the Revo).
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_00.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_00.thumb.jpg" alt="Screenshot of episode listing" /></a>
Ubuntu
------
Install your preferred version of [Ubuntu via USB stick](https://help.ubuntu.com/community/Installation/FromUSBStick). I'd also recommend installing an OpenSSH server so that you can perform maintenance remotely (also, the Revo's keyboard is brutal to type on).
```
sudo apt-get install openssh-server
```
XBMC
----
A streamlined package management system in newer versions of Ubuntu has made installing XBMC dead easy. Run this set of commands:
```
sudo apt-get install python-software-properties pkg-config
sudo add-apt-repository ppa:team-xbmc
sudo apt-get update
sudo apt-get install xbmc xbmc-standalone
sudo apt-get update
```
Vendor-specific video drivers should also be installed. This can easily be done through the Ubuntu UI these days, or via `apt-get`. These video drivers will allow XBMC to leverage hardware accelerated decoding of HD material (through a library called VDPAU), and provide some relief to the Revo's poor Atom processor.
```
sudo apt-get install libvdpau1 nvidia-libvdpau
```
An immediate step should be to **disable Compiz**. Leaving it on will result in a great deal of [tearing artifacts](http://en.wikipedia.org/wiki/Screen_tearing) appearing on screen.
Revo Problems
-------------
### Resolution
Our screen wouldn't default to its full 1920x1080 resolution. We fixed this by making sure that the Nvidia drivers were installed, and changing resolution through the Nvidia configuration pane. Ubuntu's default display settings weren't able to access the correct resolution presets.
### No Sound via HDMI
HDMI cables carry sound as well, but our Revo wouldn't produce any. We solved the problem by installing a terminal program called `alsamixer`:
```
sudo apt-get install alsamixer
```
Open it by typing `alsamixer` at a terminal prompt and its text UI will appear. Move the right arrow over to **S/PDIF 1** and press `m` to unmute it. This should fix the problem, but you'll lose this setting between restarts. Persist your changes by exiting the mixer (using `Esc`) and running `alsactl store`.
Aeon
----
Confluence, the default XBMC is nice, but another skin called Aeon is even more astonishingly beautiful. Aeon development has been discontinued, but a new project called Aeon65 is available to replace it. Install Git so we can retrieve its repository:
```
sudo apt-get install git-core
```
Now set your directory and retrieve Aeon65:
```
cd ~/.xbmc/addons
git clone git://github.com/pix/aeon.git skin.aeon65
```
Restart XBMC if it was running, and change to the new skin by selecting it in `System` → `Appearance` → `Skin`.
These instructions are also [available here](https://github.com/pix/aeon/wiki/linux-download-instructions).
Library Mode
------------
XBMC can run in one of two different modes:
* **File mode:** (for lack of a better name) videos are browsed to using the directory structure that they'd been stored in. Directories from many different sources can be added and browsed including SMB, disk, USB, etc.
* **Library mode:** all movies are extracted from all known movie sources and merged into a centralized library. This library can be browed by movie name but also via metadata such as year, directory, genre, etc. Same goes for TV shows.
Library mode is not default, but it is generally a better browsing experience, especially for novice users. Enabling it is just two easy steps:
1. Add a top-level movie source. From the main menu, go to "Videos" and add a source. Select the location of a movie source and set the content type to movies.
2. From the list of sources, press the left arrow until the "left side menu" comes out. You'll see a Library Mode option. Enable it.
After returning to the main menu, there should be a new "Movies" section. A TV shows source can be added as well to bring up a "TV Shows" section.
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_01.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_01.thumb.jpg" alt="Screenshot of main menu" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_02.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_02.thumb.jpg" alt="Screenshot of movie information" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_03.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_03.thumb.jpg" alt="Screenshot of movie playing" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_04.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_04.thumb.jpg" alt="Screenshot of movie listing" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_05.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_05.thumb.jpg" alt="Screenshot of TV listing" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_06.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_06.thumb.jpg" alt="Screenshot of TV season listing" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_07.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_07.thumb.jpg" alt="Screenshot of episode information" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_08.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_08.thumb.jpg" alt="Screenshot of settings" /></a>
<a href="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_09.png"><img src="/assets/images/articles/guide-to-installing-xbmc-and-ubuntu-on-an-acer-revo/xbmc_aeon_09.thumb.jpg" alt="Screenshot of appearance settings" /></a>
<file_sep>+++
location = "Berlin"
published_at = 2012-06-07T14:44:00+02:00
slug = "heroku-postgres-dev"
title = "Upgrade to Heroku Postgres Dev"
+++
Our [Heroku Postgres Dev](https://postgres.heroku.com/) plans recently went into public beta. They're very exciting work, providing the full power of a true Postgres database for development applications, and for free!
Some key features of the new dev plan is that databases under it are 9.1 (up from 8.3 which is what the shared databases ran under), support hstore, and can be managed remotely using `heroku pg:psql` or any other Postgres client.
However, since the dev plan adds a brand new database, the default is to end up with an empty store with none of your previous application data. If you're like me, and not too familiar with Heroku Postgres, it might not be immediately obvious how to seemlessly get your data migrated over. Lucky for you though, you're on Heroku! Using pgbackups, there's a very simple way to move your data between databases and produce a backup as a convenient byproduct.
Add the `pgbackups` addon and capture a backup of your current shared database:
heroku addons:add pgbackups
heroku pgbackups:capture
The Heroku command will tell you that a backup was produced with a name like `b001`. Now add your new Postgres dev database:
heroku addons:add heroku-postgresql:dev
The name of your new database will come back as a token like `HEROKU_POSTGRESQL_CYAN`. It's attached to your app, but not yet acting as its primary database.
Now all that's left to do is restore the backup you made, and make it your primary:
heroku pgbackups:restore HEROKU_POSTGRESQL_CYAN b001
heroku pg:promote HEROKU_POSTGRESQL_CYAN
Open a psql session to the new Postgres dev instance and check that all your data is properly in place:
heroku pg:psql
Optionally, you can destroy your old shared database:
heroku addons:remove shared-database
<file_sep>+++
location = "Calgary"
published_at = 2009-06-25T00:00:00-06:00
slug = "registering-methods-with-delegates-the-easy-way"
tiny_slug = "15"
title = "Registering Methods with Delegates the Easy Way"
+++
Every C# developer is familiar with the syntax for registering a method to a delegate or event:
``` csharp
_myButton.Click += new EventHandler(myButton_Click);
```
I'm finding that a lot of people don't seem to know about the alternate "shorthand" syntax for doing the same thing that was introduced in .NET 2.0:
``` csharp
_myButton.Click += myButton_Click;
```
I mention this because I feel that the shorthand syntax is preferable in a number of ways, starting with the fact that it's shorter, therefore eliminating some of the normal boilerplate cruft and leaving you with more readable code. It's also easier to understand for developers new to C#. Consider the following:
``` csharp
_myButton.Click += new EventHandler(myButton_Click);
_myButton.Click -= new EventHandler(myButton_Click);
```
Every C# developer eventually learns that even though you created two separate delegate objects in this example, the `myButton_Click` method still gets unregistered. The reason is that when the delegate is looking for a delegate to unregister, it doesn't compare delegates by reference, but instead by the underlying method(s) they will call. I'll be the first to admit that I found this behaviour a little counterintuitive when I started coding C#.
Now, compare the previous example to the same code, but using shorthand notation:
``` csharp
_myButton.Click += myButton_Click;
_myButton.Click -= myButton_Click;
```
Regardless of how much C# you now, it's pretty obvious here that `myButton_Click` is going to be unregistered by the time this snippet finishes executing.
<span class="addendum">Addendum --</span> While looking around for delegate information, I came across a really [great article on weak event listeners in C#](http://www.codeproject.com/KB/cs/WeakEvents.aspx). This is an important concept because despite all the memory safety C# provides to you, it's still easy to get memory leaks from objects dangling by a single delegate reference that wasn't property unregistered.
<file_sep>+++
location = "Silver Star"
published_at = 2010-02-11T00:00:00-07:00
slug = "generating-a-permalink-slug-in-haskell"
tiny_slug = "23"
title = "Generating a Permalink Slug in Haskell"
+++
One of the basic features of any blogging software is a function for generating "slugs" for your articles. A slug is normally a URL-friendly version of your article's title that's had any special characters and spaces stripped out, for example "My Awesome Article!!" might become "my-awesome-article".
Generating a slug is a pretty straightforward exercise with regular expressions, but might not be quite so obvious in Haskell because of the rather arcane way that the regex libraries are provided.
Regex
-----
Regular expressions in Haskell are *weird*. A `Text.Regex.Base` module provides an interface to a [large variety of possible backends](http://www.haskell.org/haskellwiki/Regular_expressions) that do the heavy-lifting. The commonly-used functions in base are `=~` and `=~~`, both polymorphic, meaning they behave differently depending on the type signature we specify for them. Read [this beautifully written Haskell regex tutorial](http://www.serpentine.com/blog/2007/02/27/a-haskell-regular-expression-tutorial/) to understand this in more depth.
I've chosen to use the PCRE backend for Regex; a very fast module that is particularly suited to working with bytestrings. I'd install it on Archlinux like so (the cabal command is suited for any system):
```
sudo pacman -Sy pcre
cabal install regex-base regex-pcre
```
Another caveat in Haskell's regex libraries is that no regex replace function is provided. Here's one borrowed from spookylukey's Haskell blog:
``` haskell
import Text.Regex.PCRE ( (=~~) )
import qualified Data.ByteString.Lazy.Char8 as B
{- | Replace using a regular expression. ByteString version. -}
regexReplace ::
B.ByteString -- ^ regular expression
-> B.ByteString -- ^ replacement text
-> B.ByteString -- ^ text to operate on
-> B.ByteString
regexReplace regex replacement text = go text []
where go str res =
if B.null str
then B.concat . reverse $ res
else case (str =~~ regex) :: Maybe (B.ByteString, B.ByteString, B.ByteString) of
Nothing -> B.concat . reverse $ (str:res)
Just (bef, _ , aft) -> go aft (replacement:bef:res)
```
Bytestrings
-----------
It's generally recommended for fast code to use the `ByteString` type rather than the Haskell's built-in string, because the built-in string is considered slow. A Google search will reveal that massive memory usage and speed improvements in real-world applications are attributed to switching from strings to bytestrings.
Normally to use a bytestring in our code we'd have to write something like:
``` haskell
B.pack "my string"
```
However, if you have a reasonably recent version of GHC, you can specify the `-XOverloadedStrings` language option flag to define bytestrings the same way you define strings.
Generating Slugs
----------------
Now that we've got the basics in place, we can write a simple function to generate slugs for a blog:
``` haskell
import GHC.Unicode ( toLower )
import qualified Data.ByteString.Lazy.Char8 as B
makeSlug :: B.ByteString -> B.ByteString
makeSlug = regexReplace "[ _]" "-"
. regexReplace "[^a-z0-9_ ]+" ""
. B.map toLower
```
Save this to a file called `Slug.hs` and load up a GHCI prompt to test it out (remember to use `-XOverloadedStrings`!):
```
$ ghci -XOverloadedStrings
Prelude> :m Data.ByteString.Lazy.Char8
Prelude Data.ByteString.Lazy.Char8> :load Slug.hs
*Main Data.ByteString.Lazy.Char8> :set prompt "Prelude> "
Prelude> unpack $ makeSlug "My Awesome Article!!"
"my-awesome-article"
Prelude> unpack $ makeSlug "My Awesome w/ Numbers 789_2"
"my-awesome-w-numbers-789-2"
```
That's the gist of it. The slug function itself can now be tweaked as desired.
<file_sep>+++
location = "Calgary"
published_at = 2010-07-19T00:00:00-06:00
slug = "the-bane-of-stack-overflow"
tiny_slug = "27"
title = "The Bane of Stack Overflow"
+++
Stack Overflow is the best development resource online. I want to get that out of the way so that I sound reasonably constructive, rather than critical.
Here's a portrayal of what a fairly well-answered question on <acronym title="Stack Overflow">SO</acronym> looks like:
> *How do I ... in language ...?*
>
> **Responses:**
>
> 1. <img alt="Stack Overflow accepted answer checkmark" src="/assets/images/articles/the-bane-of-stack-overflow/green_checkmark.png" class="inline" /> (Top-rated response, usually well-written and really good)
>
> 2. (Good response)
>
> 3. (Acceptable response)
>
> 4. *You should ....* (poor/irrelevant advice)
>
> 5. *I've always found that ...* (poor/irrelevant advice)
>
> 6. *I think the best way ...* (poor/irrelevant advice)
This works well because the best response is front row centre, and hard to miss. There will be a large set of poor answers, but that's a given, this is the Internet after all! The important part is that the poor responses get muscled out by the good ones and move out of sight.
The problem only really establishes itself on a less-popular and more difficult question:
> *What is the best practice for ...?*
>
> **Responses:**
>
> 1. *You should ....* (poor/irrelevant advice)
>
> 2. *I've always found that ...* (poor/irrelevant advice)
Karma on SO is a valuable resource, far moreso than most other social sites online, and just for that reason people will spend more time and effort acquiring it.
Unfortunately, like anywhere else on the Internet, most people are not informed well enough to comment on a subject as an authority. The difference on SO is that uninformed karma fishers know that to extract the sweet karma that they so crave, they need to make themselves *sound like a real authority*.
The problem is compounded because of SO's high-level userbase. These karma fishers are usually articulate and their answers sound reasonable. They don't go so far as to deceive themselves into thinking their answers are legitimate, but they've discovered that every so often these pot shots will pay off so they're happy to provide answers that they hope will be close enough.
My suggestion for a fix would be to make it more obvious when a question has not been answered to the <acronym title="Origin Poster">OP</acronym>'s satisfaction. The green checkmark is already a good indicator, but its absence might not be noticed on some question to users who aren't regulars.
That said, the system works, and SO is still the best development resource online.
<file_sep>RSS icon from the [Iconic](http://somerandomdude.com/projects/iconic/) set.
<file_sep>.PHONY: all
all: clean install test vet lint check-gofmt build
.PHONY: build
build:
$(shell go env GOPATH)/bin/mutelight build
.PHONY: check-gofmt
check-gofmt:
scripts/check_gofmt.sh
.PHONY: clean
clean:
mkdir -p public/
rm -f -r public/*
.PHONY: compile
compile: install
# Long TTL (in seconds) to set on an object in S3. This is suitable for items
# that we expect to only have to invalidate very rarely like images. Although
# we set it for all assets, those that are expected to change more frequently
# like script or stylesheet files are versioned by a path that can be set at
# build time.
LONG_TTL := 86400
# Short TTL (in seconds) to set on an object in S3. This is suitable for items
# that are expected to change more frequently like any HTML file.
SHORT_TTL := 3600
.PHONY: deploy
deploy: check-target-dir
# Note that AWS_ACCESS_KEY_ID will only be set for builds on the master branch
# because it's stored in GitHub as a secret variable. Secret variables are not
# made available to non-master branches because of the risk of being leaked
# through a script in a rogue pull request.
ifdef AWS_ACCESS_KEY_ID
aws --version
@echo "\n=== Syncing HTML files\n"
# Force text/html for HTML because we're not using an extension.
#
# Note that we don't delete because it could result in a race condition in
# that files that are uploaded with special directives below could be
# removed even while the S3 bucket is actively in-use.
aws s3 sync $(TARGET_DIR) s3://$(S3_BUCKET)/ --acl public-read --cache-control max-age=$(SHORT_TTL) --content-type text/html --exclude 'assets*' $(AWS_CLI_FLAGS)
@echo "\n=== Syncing media assets\n"
# Then move on to assets and allow S3 to detect content type.
#
# Note use of `--size-only` because mtimes may vary as they're not
# preserved by Git. Any updates to a static asset are likely to change its
# size though.
aws s3 sync $(TARGET_DIR)/assets/ s3://$(S3_BUCKET)/assets/ --acl public-read --cache-control max-age=$(LONG_TTL) --follow-symlinks --size-only $(AWS_CLI_FLAGS)
@echo "\n=== Syncing Atom feeds\n"
# Upload Atom feed files with their proper content type.
find $(TARGET_DIR) -name '*.atom' | sed "s|^\$(TARGET_DIR)/||" | xargs -I{} -n1 aws s3 cp $(TARGET_DIR)/{} s3://$(S3_BUCKET)/{} --acl public-read --cache-control max-age=$(SHORT_TTL) --content-type application/xml
@echo "\n=== Syncing index HTML files\n"
# This one is a bit tricker to explain, but what we're doing here is
# uploading directory indexes as files at their directory name. So for
# example, 'articles/index.html` gets uploaded as `articles`.
#
# We do all this work because CloudFront/S3 has trouble with index files.
# An S3 static site can have index.html set to indexes, but CloudFront only
# has the notion of a "root object" which is an index at the top level.
#
# We do this during deploy instead of during build for two reasons:
#
# 1. Some directories need to have an index *and* other files. We must name
# index files with `index.html` locally though because a file and
# directory cannot share a name.
# 2. The `index.html` files are useful for emulating a live server locally:
# Golang's http.FileServer will respect them as indexes.
find $(TARGET_DIR) -name index.html | egrep -v '$(TARGET_DIR)/index.html' | sed "s|^$(TARGET_DIR)/||" | xargs -I{} -n1 dirname {} | xargs -I{} -n1 aws s3 cp $(TARGET_DIR)/{}/index.html s3://$(S3_BUCKET)/{} --acl public-read --cache-control max-age=$(SHORT_TTL) --content-type text/html
@echo "\n=== Fixing robots.txt content type\n"
# Give robots.txt (if it exists) a Content-Type of text/plain. Twitter is
# rabid about this.
[ -f $(TARGET_DIR)/robots.txt ] && aws s3 cp $(TARGET_DIR)/robots.txt s3://$(S3_BUCKET)/ --acl public-read --cache-control max-age=$(SHORT_TTL) --content-type text/plain $(AWS_CLI_FLAGS) || echo "no robots.txt"
else
# No AWS access key. Skipping deploy.
endif
.PHONY: install
install:
go install .
# Usage:
# make PATHS="/ /archive" invalidate
.PHONY: invalidate
invalidate: check-aws-keys check-cloudfront-id
ifndef PATHS
$(error PATHS is required)
endif
aws cloudfront create-invalidation --distribution-id $(CLOUDFRONT_ID) --paths ${PATHS}
# Invalidates CloudFront's entire cache.
.PHONY: invalidate-all
invalidate-all: check-aws-keys check-cloudfront-id
aws cloudfront create-invalidation --distribution-id $(CLOUDFRONT_ID) --paths /
# Invalidates CloudFront's cached assets.
.PHONY: invalidate-assets
invalidate-assets: check-aws-keys check-cloudfront-id
aws cloudfront create-invalidation --distribution-id $(CLOUDFRONT_ID) --paths /assets
.PHONY: killall
killall:
killall mutelight
.PHONY: lint
lint:
$(shell go env GOPATH)/bin/golint -set_exit_status ./...
.PHONY: loop
loop:
$(shell go env GOPATH)/bin/mutelight loop
.PHONY: sigusr2
sigusr2:
killall -SIGUSR2 mutelight
# sigusr2 aliases
.PHONY: reboot
reboot: sigusr2
.PHONY: restart
restart: sigusr2
.PHONY: test
test:
go test ./...
.PHONY: test-nocache
test-nocache:
go test -count=1 ./...
.PHONY: vet
vet:
go vet ./...
#
# Helpers
#
# Requires that variables necessary to make an AWS API call are in the
# environment.
.PHONY: check-aws-keys
check-aws-keys:
ifndef AWS_ACCESS_KEY_ID
$(error AWS_ACCESS_KEY_ID is required)
endif
ifndef AWS_SECRET_ACCESS_KEY
$(error AWS_SECRET_ACCESS_KEY is required)
endif
# Requires that variables necessary to update a CloudFront distribution are in
# the environment.
.PHONY: check-cloudfront-id
check-cloudfront-id:
ifndef CLOUDFRONT_ID
$(error CLOUDFRONT_ID is required)
endif
.PHONY: check-target-dir
check-target-dir:
ifndef TARGET_DIR
$(error TARGET_DIR is required)
endif
<file_sep>+++
location = "Calgary"
published_at = 2010-12-01T00:00:00-07:00
slug = "working-around-powershells-set-alias"
tiny_slug = "34"
title = "Working Around PowerShell's Set-alias"
+++
PowerShell's `set-alias` command is very limited by its apparent inability to easily accept parameters for commands that are being aliased. Those of us who are used to Linux shells where aliases such as `alias ls="ls -lh"` are commonplace have to wrap our heads around the fact that the ideal use case for `set-alias` is a only a simple one to one mapping like `set-alias sql invoke-sqlcmd`.
Fortunately, there's a simple workaround:
``` ruby
function vehicles { invoke-sqlcmd "select * from agencyvehicle" }
```
Use a function instead! The syntax is concise and doesn't come with any harmful side effects.
<span class="addendum">Edit (2010/12/02) --</span> more logical to use a function rather than an alias to a function (_duh!_).
<file_sep>+++
location = "Calgary"
published_at = 2009-08-11T00:00:00-06:00
slug = "application-dot-crawl"
tiny_slug = "16"
title = "Application.Crawl()"
+++
Most .NET developers are familiar with the standard entry point of a WinForms application:
``` csharp
Application.Run(new MainForm());
```
I've been finding recently that the name of this method is rapidly becoming outdated as modern Microsoft technology finds its way into more applications. Developers like myself can get the wrong idea about what this method actually does while skimming source code. Therefore, I respectfully propose that Microsoft obsoletes the `Run` method, and replaces it with something a little more true to form:
``` csharp
Application.Crawl(new MainForm());
```
This insight comes from my recent experience installing Expression Blend 3. I'd previously noticed that Microsoft applications seemed to be getting slower after installing the beta for Visual Studio 2010<sup class="footnote" id="fnr1"><a href="#fn1">1</a></sup>, but Microsoft has really taken the Blend installer to the next level.
Close to 100% of a single core was eaten up for the entire half-hour install process of Blend. The slowdown was so extreme that my mouse cursor skipped around the screen in 20 pixel increments as I made futile attempts to continue my other work. For the record, I'm running a Core 2 E8400 @ 3.00 GHz with 4 GB of memory.
<div class="figure">
<a href="/assets/images/articles/application-dot-crawl/cpu-eater-3.png" title="Link to full-size image"><img src="/assets/images/articles/application-dot-crawl/cpu-eater-3-small.png" alt="Sus microprocessorius, more widely known as the common CPU hog, in its natural habitat" /></a>
<p><strong>Fig. 1:</strong> <em>Sus microprocessorius,</em> more widely known as the common CPU hog, in its natural habitat</p>
</div>
The good news is that Expression Blend itself seems to be very usable. Next week I promise to write about something more constructive.
<p class="footnote" id="fn1"><a href="#fnr1"><sup>1</sup></a> VS 2010 is a beta release. Some performance improvements are bound to make it into the final product.</p>
<file_sep>+++
location = "San Francisco"
published_at = 2012-06-19T19:40:09-07:00
slug = "netrc"
title = "Building an API with Netrc"
+++
If you track the progress of the [Heroku client](https://github.com/heroku/heroku), you may have noticed that in the last few months we've [switched the way that your credentials are stored](https://github.com/heroku/heroku/blob/master/CHANGELOG#L278) over from a custom format in `~/.heroku` to an older and more normalized storage standard, `.netrc`. This isn't an isolated event either, you may have noticed that GitHub has recently changed the recommended [clone method on new repositories to https](https://github.com/brandur/dummy), which has the side-effect of bypassing your standard access with `~/.ssh/id_rsa`. How do you get back to not being prompted for your credentials every time you push to the repository? Netrc.
`.netrc` is an old standard that dates all the way back to the days of FTP, that romantic wild west era of the Internet where the concept of "passive mode" kind of made sense. Its job is to store a user's credentials for accessing remote machines in a simple and consistent format:
machine brandur.org
login <EMAIL>
password <PASSWORD>
machine mutelight.org
login <EMAIL>
password <PASSWORD>
Although originally intended for FTP, its use has since expanded to a other network clients including Git, Curl, and of course Heroku.
A common pattern that I've run into while building API's over the last few months is to protect APIs with HTTP basic authentication. This isn't necessarily the best solution in the long term, passing tokens provisioned with OAuth2 may be better, but it's a mechanism that can be set up quickly and easily.
Take this Sinatra app as an example:
``` ruby
# run with:
# gem install sinatra
# ruby -rubygems api.rb
require "sinatra"
set :port, 5000
helpers do
def auth
@auth ||= Rack::Auth::Basic::Request.new(request.env)
end
def auth_credentials
auth.provided? && auth.basic? ? auth.credentials : nil
end
def authorized?
auth_credentials == [ "", "my-secret-api-key" ]
end
def authorized!
halt 401, "Forbidden" unless authorized?
end
end
put "/private" do
authorized!
200
end
```
After running it, we can test our new API with Curl:
```
curl -i -u ":my-secret-api-key" -X PUT http://localhost:5000/private
HTTP/1.1 200 OK
X-Frame-Options: sameorigin
X-XSS-Protection: 1; mode=block
Content-Type: text/html;charset=utf-8
Content-Length: 0
Connection: keep-alive
Server: thin 1.3.1 codename Triple Espresso
```
Now here's the interesting part. Add the following lines to your `.netrc`:
```
machine localhost
password my-secret-api-key
```
Try the same Curl command again but using the `-n` (for `--netrc`) flag:
```
curl -i -n -X PUT http://localhost:5000/private
```
Voilà! The speed of being able to run ad-hoc queries against an API you're building rather than drudging up your API key every time turns out to be a huge win practically, and it's a pattern that I now use regularly during development.
A limitation that's hinted at above is that you can only have a single entry for `localhost`. Generally, I find that this isn't a huge problem because most of the APIs I want to hit are deployed in a staging or production environment with a named URL.
Heroku
------
Now onto a nice real-world example. Are you a Heroku user? Have you updated your Gem since February 2012? If the answer to both these questions is **yes!**, try this from a console:
```
curl -n https://api.heroku.com/apps
```
Security
--------
A glaring problem with `.netrc` is that it keeps a large number of your extremely confidential credentials out in the open in plain text. Presumably, the file is `chmod`'ed to `600` and you're using full-disk encryption, but that's still probably not enough (say someone happens to find your computer unlocked).
The [netrc](https://rubygems.org/gems/netrc) gem used by the Heroku client will try to find a GnuPG encrypted file at `~/.netrc.gpg` before falling back to the plain text version. Although this convention is far from a standard, it's still recommended security practice.
<file_sep>+++
location = "Calgary"
published_at = 2009-03-24T00:00:00-06:00
slug = "using-the-invoke-design-pattern-with-anonymous-methods"
tiny_slug = "8"
title = "Using the Invoke Design Pattern with Anonymous Methods"
+++
If you've done Windows forms development in .NET you've almost certainly seen the invoke design pattern before.
``` csharp
delegate void UpdateLabelTextCallback(string message);
void UpdateLabelText(string message)
{
if (InvokeRequired)
Invoke(
new UpdateLabelTextCallback(UpdateLabelText),
message
);
else
label1.Text = message;
}
```
This pattern is required on methods that update the UI in some way but which are called from a thread _other_ than the main/UI thread. Failing to use the invoke design pattern will usually result in an `InvalidOperationException` (cross-thread operation not valid) being thrown.
The code sample above shows the conventional implementation of the pattern using a delegate type which mirrors the method you're trying to callback and a call to `Invoke` with a reference back to the same method again. The `InvokeRequired` check decides whether an `Invoke` is necessary, and if it isn't, the method's normal logic is run.
Improving on This
-----------------
The conventional implementation is both long-winded and messy, and it can really start to get ugly when a method gets separated from its callback delegate type when the delegate needs to go in a different `#region`. A moderately complex form may need dozens of methods that follow the invoke pattern, so you'll end up with large sections of code dedicated to callback delegates for specific methods.
Luckily, using anonymous methods we can do a lot better. Let's rewrite our example to use an anonymous method instead of a delegate type.
``` csharp
void UpdateLabelText(string message)
{
if (InvokeRequired)
Invoke(new MethodInvoker(
delegate { UpdateLabelText(message); }
));
else
label1.Text = message;
}
```
Much better! Now if we wanted to, we could take advantage of the fact that a call to `Invoke` on the main thread will have no detrimental effect on our program and make this method even shorter.
``` csharp
void UpdateLabelText(string message)
{
Invoke(new MethodInvoker(
delegate { label1.Text = message; }
));
}
```
It's possible to put any amount of logic into the anonymous method that is being invoked, even if it's more than one or two lines. This is legal of course, but starts to look pretty sloppy pretty fast.
Now with Lambdas
----------------
Anything we can do with an anonymous method we can also do with a lambda expression. For cases like this, it doesn't matter much which type of function you use, but if you're using lambdas everywhere else in your application, you can stick with them for invoke patterns too.
``` csharp
void UpdateLabelText(string message)
{
Invoke(new MethodInvoker(
() => label1.Text = message
));
}
```
<file_sep>+++
location = "Berlin"
published_at = 2012-06-10T15:21:51-06:00
slug = "bin-console"
title = "Your Ruby App Should Have a `bin/console`"
+++
Those of us who have worked or are working on Rails are somewhat spoiled by the ability to boot `script/rails console` and immediately start running commands from inside our projects. What may not be very well known is that this console isn't a piece of Rails black magic, and makes a nice pattern that extends well to any other type of non-Rails Ruby project.
Here's the basic pattern:
``` ruby
#!/usr/bin/env ruby
require "irb"
require "irb/completion" # easy tab completion
# require your libraries + basic initialization
IRB.start
```
With the right initialization, this will immediately drop you into a console with all your project's models, classes, and utilities available, and even with tab completion! It also translates easily over to cloud platforms, being only one `heroku run bin/console` away, so to speak.
I picked up the idea somewhere at Heroku where public opinion generally sways against heavy Rails-esque frameworks and towards more custom solutions built from the right set of lightweight components.
Here's a real world example for the [bin/console of Hekla](https://github.com/brandur/hekla/blob/master/bin/console), which runs this technical journal:
``` ruby
#!/usr/bin/env ruby
require "irb"
require "irb/completion"
require "bundler/setup"
Bundler.require
$: << "./lib"
require "hekla"
DB = Sequel.connect(Hekla::Config.database_url)
require_relative "../models/article"
# Sinatra actually has a hook on `at_exit` that activates whenever it's
# included. This setting will supress it.
set :run, false
IRB.start
```
<file_sep>+++
location = "Calgary"
published_at = 2011-03-19T00:00:00-06:00
slug = "the-south-by-southwest-experience"
tiny_slug = "41"
title = "The South by Southwest Experience"
+++
I was down in Austin this year for South by Southwest Interactive, a rapidly growing conference specializing in entrepreneurship, emerging technology, communication, social media, and design, among other things. I attended with the goals of meeting people, seeing Austin's famous tech culture, and getting inspired. I accomplished all of these and more.
Organization
------------
It's obvious that the people running SXSW have some experience in the area. By and the large, the event is organized extremely well, and this is an impressive feat considering the many thousands of attendees.
When first planning out my time at SXSW, I was a little worried when I saw that talks were spread across the Austin Convention Center, and the local Hilton and Marriott hotels. Would there be time to make my way from building to another between sessions? Well, as it turns out, easily. The hotels are right across the street from the convention center. It even gets better, all the session venues are just a stone's throw from Austin's most popular street for parties and dining (6th Street). Taking a break to grab a quick drink or bite is no problem at all (but there is so much of both for free that paying for either isn't really advisable).
The only piece that disappointed me were the badges themselves, which were both cheaply designed and cheaply printed. My major complains were that my picture was cut off, and that I couldn't opt to have any alternate information on it (Twitter handle for example) without adding it myself with a marker. A decent designer would've had a great opportunity to make these badges into real works of art: big names readable from across the room, a high quality photo, company logos, and so on. I'd probably add a fun/interactive component if I built them: personalized QR-esque codes that could be scanned with the SXSW mobile apps.
<a href="/assets/images/articles/the-south-by-southwest-experience/sxsw-badge-full.jpg"><img src="/assets/images/articles/the-south-by-southwest-experience/sxsw-badge.jpg" alt="SXSW 2011 badge" /></a>
People
------
The most important aspect of any conference are the attendees, and the ones at SXSW were phenomenal. Everyone I spoke to had a story to tell, and one that I was interested to hear. There's no question that the people at SXSW interactive are geeks, but even if that's the case, they're the coolest of the bunch. Almost everyone was social and an able conversationalist.
If you're attending alone like I was, it really pays to be assertive. Everyone's cool, but a lot of people still have a mental barrier that prevents them from introducing themselves to strangers. I regret missing a few conversations that might have been really cool with <NAME> and <NAME>, because I hesitated to introduce myself.
There was a great gender mix, which seemed almost 50/50 by my unscientific estimate. This is a huge improvement over many similar conferences, and SXSW's success here is probably attributable to the wide range of subject matter covered.
Sessions
--------
The sessions at SXSW were by far the most disappointing part, but that didn't affect my experience much. Some presentations were astounding, and I think that I saw the best talk of my life here, but unfortunately most covered only very general subject matter. One girl I spoke to after a session on fixing government put it best: _"interesting, but not really actionable"_.
For example, I went to one presentation titled something like "emerging patterns in iPad user interface design", expecting some sort of discussion on new ideas around iPad UI design. What I got instead was a gallery of screenshots from existing iPad apps, along with a cliche video of a 3-year old intuitively learning to use an iPad.
The advice I'd give to people going to SXSW next year is that if it looks like a session might not be as high quality as you were hoping, just cut your losses and leave (there are dozens of better things that you could be doing at SXSW).
As noted above, there were some really great presentations to be seen. For example, <NAME> delivered an astounding one on his new book, [The Thank-you Economy](http://thankyoueconomybook.com/). The development team at Etsy held their own conference alongside SXSW at Venue 222, and went into some of the very interesting techniques that they've been using internally to produce a high-quality product.
Parties
-------
Provided that you kept an eye on your party schedule, the parties at SXSW were plentiful, fun and free. The only free drinks you could get at most bars were "wells"; mixed drinks using the cheapest possible house brand liquor as a base, but even so, they did the trick. It was a shock coming back to Calgary and having to pay money for booze again.
The best part about the parties wasn't the free liquor, it was the people. I could walk into any SXSW party, start talking to any random person, and it was almost guaranteed that they'd be an interesting conversationalist (because they were fellow attendees of SXSW). I don't know if this could be said about any other party settings in the world.
Many of bars where the parties were taking place were along 6th Street. Even though the SXSW parties were exclusive to attendees, the Austinites who weren't involved in the festival still had no qualms about participating in the rest of Austin's nightlife. 6th Street after midnight is certainly one of the busiest party scenes that I've ever seen.
Internet Connectivity
---------------------
Of course an important aspect of any tech festival is Internet access for foreign attendees. Luckily, finding a wifi hotspot was never a major problem. The convention center and hotels were equipped with wifi of course, and almost any restaurant or club I went to had working wifi as well. Some of the latter would be secured, but I was never once turned down after asking staff for a password.
To wrap it up, SXSW was a great experience, and I'll certainly be there next year.
<file_sep>+++
location = "Calgary"
published_at = 2012-12-29T11:32:30-08:00
slug = "sinatra-rack-test"
title = "Testing Sinatra With Rack-test"
+++
A common problem when starting out with Sinatra and trying to exercise what you've built with `rack-test` is that by default, Sinatra will swallow your errors and spit them out as a big HTML page in the response body. Trying to debug your tests by inspecting an HTML backtrace from `last_response.body` is a harrowing experience (take it from someone who's tried).
The solution is to tell Sinatra to raise errors back to you instead of burying them in HTML. Here's the proper combination of options to accomplish that:
``` ruby
set :raise_errors, true
set :show_exceptions, false
```
Here's a more complete example:
``` ruby
# app.rb
class App < Sinatra::Base
configure do
set :raise_errors, true
set :show_exceptions, false
end
get "/" do
raise "error!"
end
end
```
``` ruby
# app_test.rb
describe App do
include Rack::Test::Methods
it "shows an error" do
get "/"
end
end
```
<file_sep>+++
location = "Calgary"
published_at = 2009-08-13T00:00:00-06:00
slug = "how-to-host-a-wpf-control-in-a-winforms-application"
tiny_slug = "17"
title = "How to Host a WPF Control in a WinForms Application"
+++
As people start making the jump from Windows Forms to WPF, many will hit an intermediate phase where it'll be useful to use WPF components in WinForms and vice-versa. Unfortunately, the two frameworks are not directly compatible because WPF uses `Control` under `System.Windows.Controls` while WinForms uses `Control` under `System.Windows.Forms` -- and in terms of class hierarchies, the two `Control` classes are completely unrelated.
Luckily, Microsoft has had the good sense to give us a workaround. A WinForms application can contain a WPF control by putting the WPF control into an instance of `ElementHost`, a class deriving WinForms' `Control`, and then adding the host to a control collection normally:
``` csharp
/* our WPF control */
MapAnimationLayer animationLayer = new MapAnimationLayer();
/* container that will host our WPF control, we set it using
* the Child property */
ElementHost host = new ElementHost()
{
BackColor = Color.Transparent,
Child = animationLayer,
Dock = DockStyle.Fill,
};
/* now add the ElementHost to our controls collection
* normally */
Controls.Add(host);
```
The `ElementHost` class is part of a special namespace called `System.Windows.Forms.Integration`. Adding this namespace to your solution is slightly tricky because its DLL is not named as you'd expect; it's actually called `WindowsFormsIntegration`. From the Add Reference dialog window, scroll to the bottom of list in the .NET tab and you should see it.
WinForms in WPF
---------------
Similarly, another class called `WindowsFormsHost` allows you to insert WinForms controls into a WPF application. Here it is in XAML:
``` xml
<Window x:Class="WinFormsHostWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
>
<Grid>
<WindowsFormsHost>
<!--
the 'wf' namespace here refers to .NET's
System.Windows.Forms assembly, so this TextBox
is from WinForms
-->
<wf:TextBox x:Name="password" />
</WindowsFormsHost>
</Grid>
</Window>
```
<file_sep>+++
location = "San Francisco"
published_at = 2012-09-02T23:02:34-07:00
slug = "pretty-json"
title = "Prettifying JSON for Curl Development"
+++
In the same vein as my post from a few weeks ago on [developing an API with Curl and Netrc](/netrc), here's a handy trick for sending pre-prettified JSON output back to clients, but only those that are identifying as Curl. The reasoning being that prettified JSON isn't useful most of the time, but it's a nice touch while using developing or testing against an API with Curl.
Bundle MultiJson in your `Gemfile`:
``` ruby
gem "multi_json"
```
Now define a helper for identifying Curl clients, and use it wherever encoding JSON:
``` ruby
# sample Sinatra app
helpers do
def curl?
!!(request.user_agent =~ /curl/)
end
end
get "/articles" do
articles = Article.all
[200, MultiJson.encode(articles, pretty: curl?)]
end
```
<file_sep>+++
location = "Calgary"
published_at = 2012-01-02T23:59:00-07:00
series_permalink = "elements-of-travel"
slug = "the-hitchhikers-guide-to-the-galaxy"
tiny_slug = "guide"
title = "The Hitchhiker's Guide to the Galaxy"
+++
<p class="subheading">Wikipedia can improve the way that you travel by putting a vast store of knowledge at your fingertips. Offline versions allow it to be carried across international lines without incurring massive data charges.</p>
Many of us have fond memories of reading of Arthur Dent and Ford Prefect traveling the galaxy accompanied by their towels and depressed robot. Readers will remember the friendly book inscribed with the words _Don't Panic_, the story's namesake and described as "the standard repository for all knowledge and wisdom". Back in the 90's the idea of a device with compiled information on nearly everything small enough to carry in your pocket was laughable. The closest thing at the time were encyclopedias spanning entire bookshelves (or CD-ROM's).
Today we have our own form of the Guide, and it's better than even Douglas Adams could have imagined: Wikipedia.
Wikipedia is the ultimate travel resource. On a trip across the country it lets you look up everything--from towns and landmarks you're visiting to fact checking your tour guide.
This would be a world with almost perfect flow of information if not for one thing. In every country on Earth, phone carriers actively encourage technological retrogression by keeping data roaming rates prohibitively expensive--and you're going to need data for a Wikipedia lookup.
As luck would have it though, there are a few solutions that will compensate for 3G deficiency on international trips. I personally download a 5 GB dump of Wikipedia with **AllofWiki**, and furthermore use it to browse offline in any country. While traveling Europe last month, I used it to look up the [Berlin Wall](http://en.wikipedia.org/wiki/Berlin_wall), [Kunsthaus Tacheles](http://en.wikipedia.org/wiki/Kunsthaus_Tacheles), the [Lady Moura](http://en.wikipedia.org/wiki/Lady_Moura) (anchored in Monaco), [the Catacombs of Paris](http://en.wikipedia.org/wiki/Catacombs_of_paris), [the TGV](http://en.wikipedia.org/wiki/Tgv), and the [English language](http://en.wikipedia.org/wiki/English_language) (good read!) amongst hundreds of other subjects. A few days into the trip, it became an absolutely indispensable resource.
3G Kindles are also a good options with international wireless Wikipedia access (for free). Also try [Offline Wiki in HTML5](http://offline-wiki.googlecode.com/git/app.html) for a nice notebook solution.
Although we're not yet having Wiki updates pushed to us via the Sub-Etha, this feels like the future.
<file_sep>+++
location = "Calgary"
published_at = 2010-11-26T00:00:00-07:00
slug = "datacontext-in-a-custom-control"
tiny_slug = "32"
title = "DataContext in a Custom Control"
+++
In WPF or Silverlight, new developers will often stumble across the concept of _data context_ when learning about data binding. Data context is a mechanism that allows a framework element to define a data source for itself and its children to use when they participate in data binding. For example, a group box containing a number of associated data fields might specify its data context as some model containing a property for each of those fields. Each child control of that group box only needs to specify a relative binding path containing the name of the property it would like to bind to. Linking to a model object containing that property isn't needed because that model was already set as the data context on a parent element and is inherited.
When building a custom control, a very common technique is set that control's data context back to itself so that child controls can be bound to properties in that same control's code-behind.
``` xml
<UserControl x:Class="MyControl"
DataContext="{Binding RelativeSource={RelativeSource self}}">
<!-- Only a relative path is needed because data -->
<!-- context was set at a higher level -->
<TextBlock Text="{Binding Title}" />
</UserControl>
```
Did you see the bug in the code above? It's not immediately apparent and takes a little experience to realize that a user control should never specify its own data context in its definition. But why?
The answer becomes more apparent when we try to combine the data context concept with our new control elsewhere.
``` xml
<Grid DataContext="{StaticResource ViewModel}">
<!-- Here we'd expect this control to be bound to -->
<!-- MyContent on our ViewModel resource -->
<my:MyControl Content="{Binding MyContent}" />
</Grid>
```
In the above example, we'd expect `MyControl` to behave like any other framework element and bind its `Content` to `MyContent` on our `ViewModel` resource. Unfortunately, for anyone trying to use this control, it's actually binding its `Content` property to `MyContent` on itself (which probably doesn't even exist). The reason is that we already hard-coded a data context into the control's definition, which will take precedent in this case.
Fortunately, there's an easy way to solve this problem. Instead of specifying our data context on the root of the control itself, we should specify the data context on the control's top-level child element. This is often a `Grid` called `LayoutRoot` that Visual Studio generates automatically.
``` xml
<UserControl x:Class="MyControl">
<Grid x:Name="LayoutRoot"
DataContext="{Binding RelativeSource={RelativeSource self}}">
<!-- This child element will still bind the -->
<!-- same way! -->
<TextBlock Text="{Binding Title}" />
</Grid>
</UserControl>
```
Framework elements within the control itself can bind using a relative path in the same way, and data context in classes using the control will not be polluted, which will help prevent unexpected side effects.
<file_sep>+++
location = "Calgary"
published_at = 2010-12-19T00:00:00-07:00
slug = "a-plug-for-swype"
tiny_slug = "37"
title = "A Plug for Swype"
+++
People don't like to talk about it much, but the multitouch technology on Android phones just isn't as good as Apple's. Techcrunch (of all outlets) puts its nice and succinctly:
<p class="quote">If the iPhone is 8/10 on text input, the Nexus One is probably 5/10 and the Nexus S is a solid 6/10.</p>
For most applications it's not really a big problem, but it's particularly noticeable when typing text in portrait orientation. It's subtle. Android devices really aren't that far behind the iDevices in accuracy, but the mistakes get annoying when typing significant amounts of text. It was grating enough that I started typing everything in landscape mode and came close to switching platforms because of it.
A week or so ago I got an invite to the Swype beta, and it changed the way I use Android. The idea behind Swype is that it changes text input by allowing users to slide a finger to each letter of a word in succession and lift their finger only once the word is complete. Swype uses a built in dictionary to guess the word they were typing, and it's astonishingly accurate. Sliding a finger over various letters is never 100% accurate anyway, so the touch accuracy of Android devices really isn't such a big problem anymore. Another implicit feature is that it changes typing back to a one-handed activity, while maintaining approximately the same speed that iPhone and BlackBerry users are getting with two hands.
Edge cases are nicely handled as well. After installation, my own name and those of my contacts are already in Swype's dictionary. Swype is trained with new words by manually typing them out the first time (the Swype keyboard can still be used in the traditional fashion), and they will be henceforth be available for use. Words with double letters are handled by doing a subtle loop around the double letter while Swyping. It still makes mistakes, but these are easily managed by pounding out your message quickly on a first pass, followed by a proofing pass in which words are corrected by double-tapping them.
Android has done everything I wanted for some time: Gmail integration, Google Reader, manages todo lists, Twitter, Facebook, calendar, and alarms, but it fails to excel at any of these things. No one app or feature tied me to the platform. Swype has changed this. Before moving somewhere new, I'm going to be sure to check that there's a viable Swype alternative.
Now for a surprise: this entire post was typed via Swype! Just kidding. I like Swype but I'm not crazy.
<span class="addendum">Edit (2010/12/19) --</span> added [Swype for advanced users](http://mutelight.org/articles/swype-for-advanced-users.html)
<file_sep>+++
location = "Calgary"
published_at = 2010-10-20T00:00:00-06:00
slug = "skipping-null-checks-on-events"
tiny_slug = "29"
title = "Skipping Null Checks on Events"
+++
Yesterday I learned a neat C# trick that can be used to skip the traditional null check associated with defining, then firing events:
``` cs
public class MyClassWithAnEvent
{
public event EventHandler MyEvent;
protected void FireMyEvent()
{
if (MyEvent != null)
MyEvent(this, EventArgs.Empty);
}
}
```
By immediately assigning the event with an empty event handler, we can guarantee that the event is never null, thereby saving us a line of code whenever we call it:
``` cs
public class MyClassWithAnEvent
{
public event EventHandler MyEvent = (o, e) => {};
protected void FireMyEvent()
{
MyEvent(this, EventArgs.Empty);
}
}
```
<file_sep>+++
location = "Calgary"
published_at = 2010-02-15T00:00:00-07:00
slug = "validate-xml-according-to-schema-location-hints"
tiny_slug = "24"
title = "Validate XML According to Schema Location Hints"
+++
For those of us unfortunate enough to still be writing XML documents, it's fairly common practice to "hint" at the location of an XSD schema for a document using attributes in its root node:
``` xml
<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file:Schema.xsd">
...
</root>
```
While working with .NET's `XPathDocument` in C#, I noticed that when using this class with just a URI string argument, it will not validate against your schema. The following code throws no exception even if your XSD indicates an invalid file:
``` cs
using System.Xml.XPath;
XPathDocument d = new XPathDocument("path/to/file.xml");
```
Properly validating your XML involves giving the `XPathDocument` an `XmlReader` instance that's been setup to respect schema location hints:
``` cs
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
XmlReader r = XmlReader.Create(
"path/to/file.xml",
new XmlReaderSettings() {
ValidationType = ValidationType.Schema,
ValidationFlags =
XmlSchemaValidationFlags.ProcessSchemaLocation,
}
);
XPathDocument d = new XPathDocument(r);
```
<file_sep>+++
location = "Calgary"
published_at = 2009-03-11T00:00:00-06:00
slug = "new-features-in-c-sharp-4"
tiny_slug = "5"
title = "New Features in C# 4.0"
+++
Admittedly a few months late, here's my recap of the new C# language features being introduced in 4.0, summarized from the [PDC 2008 talk _the Future of C#_ presented by chief architect <NAME>](http://channel9.msdn.com/pdc2008/TL16/). Note that this post doesn't cover any of the new parallel features of 4.0.
Dynamically Typed Objects
-------------------------
C# 4.0's new dynamic features are built on top of .NET's Dynamic Language Runtime (DLR), an extension of the CLR. IronPython and IronRuby were built on top of the DLR, and now C# and VB will be using its features as well.
Conventionally, if we received an object from somewhere without a class or interface that we could reference from our code, we'd have to store it as an arbitrary `object`. To make matters worse, if we wanted to call a method on that object, we'd have to use reflection, and we'd end up with some pretty nasty-looking code.
``` csharp
// Prior to 4.0, if we received an object with no static
// type that we could reference, we'd call a method on it
// like this
object calc = someObject.GetCalculator();
object result = calc.GetType().InvokeMember(
"Add",
BindingFlags.InvokeMethod,
null,
new object[] { 1, 1 }
);
int sum = Convert.ToInt32(result);
```
In 4.0, we can improve this situation by using the `dynamic` keyword. We can store our object as dynamic, and from then on we can make dynamic calls on that object using the well-known dot operator.
``` csharp
// After 4.0, we can statically type the object we received
// to be dynamic (in the words of <NAME>). We can
// then call methods dynamically on it using just our normal
// dot operator.
dynamic calc = someObject.GetCalculator();
// Note that when we assign the result of our dynamic call
// to a variable, that result is converted dynamically
int sum = calc.Add(1, 1);
```
Unfortunately, the `dynamic` keyword will come with some classic drawbacks of dynamically-typed languages; the most noticeable of which to VS users may be that statement completion on dynamic objects will not be possible. Other problems will be that fewer errors can be caught at compile time, and that runtime performance will not be as good as it is for static objects.
Anders points out that the objective of these new dynamic features is not to make C# a dynamically-typed language, but to make it less painful to talk to dynamic portions of your code when doing so is necessary (for example, talking to JavaScript from Silverlight).
``` python
def GetCalculator():
return Calculator()
# This is the calculator class referenced above written in
# Python
class Calculator():
def Add(self, x, y):
return x + y
```
The Python code shown above is a possible implementation for the arbitrary calculator object referenced in the previous code samples. The code shown below illustrates how this Python code could be used from a C# program.
``` csharp
dynamic pythonCalc =
Python.CreateRuntime().UseFile("Calculator.py");
// Our simple example from above
dynamic calc = pythonCalc.GetCalculator();
int sum = calc.Add(1, 1);
// Since Python is purely dynamic, this will work on any
// type that implements the '+' operator
TimeSpan twoDays = calc.Add(
TimeSpan.FromDays(1),
TimeSpan.FromDays(1)
);
```
Optional and Named Parameters
-----------------------------
Reinforcing their long-standing reputation of being late to the game, Microsoft has finally decided to implement optional and named parameters in C#. Below shows two `TimeSpan` constructors and a possible new revision of them using optional parameters.
``` csharp
// Methods that previously had to have multiple overloads
// like this
public TimeSpan(int hours, int minutes, int seconds)
: self(0, hours, minutes, seconds)
{ ... }
public TimeSpan(int days, int hours, int minutes,
int seconds)
{ ... }
// Could be changed to something more concise like this
public TimeSpan(int seconds = 0, int minutes = 0,
int hours = 0, int days = 0)
// (Note this constructor does not exist, and likely
// never will. I've re-arranged the parameters to show
// how it probably would have been designed in the start
// had this language feature existed then.)
{ ... }
```
Methods written this way can be called in a wide range of different ways as long as all their required parameters are present. Named parameters are written like _parameter name_: _value_.
``` csharp
// 10 seconds
var t1 = new TimeSpan(10);
// 24 hours, 20 minutes, 10 seconds
var t2 = new TimeSpan(10, 20, 24);
// 7 days, 24 hours, 20 minutes, 10 seconds
var t3 = new TimeSpan(10, 20, 24, 7);
// 7 days, 10 seconds
var t4 = new TimeSpan(10, days: 7);
// 7 days, 24 hours, 20 minutes, 10 seconds
var t5 = new TimeSpan(days: 7, hours: 25, minutes: 20,
seconds: 10);
```
Improved COM Interoperability
-----------------------------
Up until 4.0, many COM interop calls were messy ordeals involving many unused parameters, all of which had to be using `ref`.
``` csharp
object fileName = "My Document.docx";
object missing = System.Reflection.Missing.Value;
doc.SaveAs(ref fileName,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
```
C# 4.0 will finally resolve this issue with the introduction of optional parameters and making `ref` optional.
``` csharp
doc.SaveAs("My Document.docx");
```
This improvement has been made possible by:
* **Optional and named parameters**: unused parameters can safely be omitted
* **Optional `ref` modifier**: `ref` need not be used (but only for interop calls, you still need `ref` elsewhere)
* **Interop type embedding**: interop methods that previously took arguments of type `object` now take `dynamic` instead
Co- and Contra-variance
-----------------------
.NET arrays have been co-variant since their introduction, however, they are not _safely_ co-variant. Notice how in the example below we can assign any object back to the string array, and cause a runtime exception.
Remember that objects which are co-variant can be treated as less derived.
``` csharp
string[] strings = GetStringArray();
ProcessUnsafely(strings);
void ProcessUnsafely(object[] objects)
{
objects[0] = "Okay";
objects[1] = new TimeSpan(); // Not okay
}
```
C# generics have always been invariant, but in C# 4.0 they will be safely co-variant.
``` csharp
// This code would previously not have compiled
List<string> strings = GetStringList();
ProcessSafely(strings);
void ProcessSafely(IEnumerable<object> objects)
{
// Safety comes from the fact that IEnumerable cannot
// be changed
}
```
Co-variance is implemented on an interface using the `out` keyword on any co-variant type parameters.
``` csharp
public interface IEnumerable<out T>
{
IEnumerable<T> GetEnumerator();
}
public interface IEnumerator<out T>
{
T Current { get; }
bool MoveNext();
}
```
Contra-variance can also be implemented using the `in` keyword. Remember that objects which are contra-variant can be treated as more derived.
``` csharp
public interface IComparer<in T>
{
int Compare(T x, T y);
}
// Legal
IComparer<object> objComparer = GetComparer();
IComparer<string> strComparer = objComparer;
```
A few notes on co- and contra-variance to remember:
* `in` and `out` are only supported for interfaces and delegate types
* Value types are always invariant (`IEnumerable<int>` cannot be stored to `IEnumerable<object>`)
* `ref` and `out` parameters are always invariant
<file_sep>+++
location = "Calgary"
published_at = 2011-06-13T17:39:00-06:00
slug = "dear-marvel-give-us-a-movie-worth-caring-about"
tiny_slug = "marvel"
title = "Dear Marvel: Give Us a Movie Worth Caring About"
+++
Over the weekend I went to see the [X-Men: First Class](http://en.wikipedia.org/wiki/X-Men:_First_Class), Marvel's new summer blockbuster. If you're willing to look past a few cookie cutter superhero movie moments, and a few scenes that didn't turn out to be nearly as dramatic as the director intended, it's a pretty decent film, especially compared to Marvel's work in the past.
The problem is that the movie isn't anywhere near as good as it should've been.
Like the title suggests, it's about Xavier and Magneto assembling the first class of X-Men. The backdrop of this simple premise is the Cuban Missle Crisis of the 60's, an important period during the Cold War where the world came close to all-out nuclear war. Combine one of the most interesting events in the history of the world with superheroes, and at worst you have a movie that's hard to screw up, and at best a timeless masterpiece.
On a scale of potential, First Class comes out a lot closer to the bottom than to the top. Digging a little below the surface, it's not hard to discover plenty of one-dimensional characters, very few worthwhile emotional moments, non-sensical philosophy<sup class="footnote" id="fnr1"><a href="#fn1">1</a></sup>, kind of a poor mutant selection, and one really questionable evil master plan(TM) (I say "below the surface" here because on the surface, the portrayals of Xavier and Magneto were actually pretty awesome).
I won't criticize it too much because First Class was decent. Just like Thor and Iron Man were decent (although <NAME>r. single-handedly carried the latter to just short of greatness). It seems that the greatest ambition of any Marvel movie is mediocrity, even while superhero films like <NAME> and the Dark Knight have already proven that loftier goals are possible.
Watching the Dark Knight, I saw heroes that I cared for, villains with intense depth, and scenes that truly moved me. The source material exists for the Marvel universe to do the same, but they'd need to embrace the idea of producing something other than a simplistic popcorn thriller. I think it's time.
<p class="footnote" id="fn1"><a href="#fnr1"><sup>1</sup></a> "I believe that true focus lies somewhere between rage and serenity." -- Xavier</p>
<file_sep>+++
location = "San Francisco"
published_at = 2012-07-02T15:43:29-07:00
slug = "todo"
title = "A Simple @todo Pattern"
+++
Modern task tracking apps are both mindblowing in their sophistication, and somewhat ostentatious in their flashiness and sheer volume. We have apps like Remember the Milk that offer multiplatform support with cloud synchronization, and apps like Clear that provide such a beautiful interface and compelling experience that they beg to be used. The earliest apps on both the iPhone and iPad platforms were built for todo lists, and even Apple entered the game years later by introducing their Reminders app in iOS 5.
Despite this attractive selection, I use none of the above. Today, I wanted to share a very simple todo pattern that I've been using for months now with great results. Here it is in its entirety:
```
@todo
=====
* Pick up the milk
* h/Submit TPS report
Finished
--------
* h/Order stationery
Defunct
-------
* Submit talk
# vi: ts=2 sw=2 foldmethod=indent foldlevel=20
```
It's _that_ simple:
1. Current tasks go at the top.
2. Finished go under _finished_.
3. Tasks that were missed or have lapsed go under _defunct_.
The list stays open in Vim wrapped in Tmux pane at all times, and gets synced back to Dropbox. Finished items are transferred between lists using fast Vim bindings. If I think of something away from my computer, I add it to my phone, then transfer the task the next time I'm back.
The Vim hints at the end provide some nice folding behavior, which is useful when your finished list has become very long. Open and close individual lists using `zo` and `zc` respectively (the `foldlevel` hint at the end ensures that all lists are expanded when the file is first opened).
<file_sep>+++
location = "Calgary"
published_at = 2009-09-11T00:00:00-06:00
slug = "haskell-a-good-bet-for-the-future"
tiny_slug = "18"
title = "Haskell: A Good Bet for the Future"
+++
Everyone is pushing concurrency these days. Recently functional programming has re-emerged into the spotlight because the paradigm is particularly conducive to parallel programming. Three languages that have been getting a special amount of attention are Haskell, Erlang, and Clojure (and all three with good reason!).
Microsoft will be releasing a major concurrency framework called [Parallel Extensions](http://en.wikipedia.org/wiki/Parallel_Extensions) along with .NET 4.0, which will include parallel LINQ (PLINQ) and the parallel tasks (AKA futures) library. As usual, they're well behind the curve, but at least when Microsoft gets into something, a lot of corporate programmers will start taking the technology seriously.
My problem recently has been picking one technology to focus on learning. Naturally, a large part of my time will go towards learning the new .NET 4.0 concurrency, but as a language for personal use, Haskell has won my attention. Instead of offering an amateur explanation of its advantages over other languages, I'm just going to link to some of the particularly interesting articles I've read on it recently:
* [No monadic headaches: multi-core concurrency is easy in Haskell](http://cgi.cse.unsw.edu.au/~dons/blog/2007/11/26#no-headaches) -- article on how Haskell's concurrency can act as a direct replacement for Erlang's (but with much nicer syntax), using message passing channels
* [Multicore Programming in Haskell Now!](http://donsbot.wordpress.com/2009/09/05/defun-2009-multicore-programming-in-haskell-now/) -- summary of Haskell's wide range of parallel programming models
* [Supercompilation for Haskell](http://community.haskell.org/~ndm/downloads/slides-supercompilation_for_haskell-03_mar_2009.pdf) (PDF warning) -- how to compile Haskell to rival C's speed
* [Haskell Arrays, Accelerated Using GPUs](http://www.scribd.com/doc/19637022/Haskell-Arrays-Accelerated-with-GPUs) -- executing massively parallel operations on the GPU from Haskell
<file_sep>+++
location = "Calgary"
published_at = 2011-07-14T10:41:00-06:00
slug = "the-objective-c-retain-property-pattern"
tiny_slug = "retain"
title = "The Objective-C Retain Property Pattern"
+++
Being pretty new to the whole Objective-C thing, I was initially a little confused about the proper way to implement properties that use the `retain` keyword. After doing some research on the subject, I've put together a complete sample based on what's considered the "correct" pattern when using them.
``` objc
@interface FactsViewController : NSObject
{
}
@property (nonatomic, retain) NSArray* facts;
@end
@implementation FactsViewController
@synthesize facts = __facts;
- (void) dealloc
{
[__facts release];
[super dealloc];
}
@end
```
In this straightforward example, the class interface defines the `facts` property, which is synthesized in the implementation with a backing field by the name of `__facts`.
The `retain` keyword indicates that the compiler should generate a property setter that retains a reference to a value set to it (i.e. increment the reference count by one). It also ensures that when the property is being set, if it had a previous value, that old value is properly released. The generated setter looks something like this:
``` objc
- (void) setFacts:(NSArray *)value
{
[value retain];
[__facts release];
__facts = value;
}
```
The one other important aspect of the pattern is that `__facts` gets released in `dealloc`. Although a `retain` property handles a release when a new value is being set to it, it does not release automatically when an object is being deallocated--forcing us to release all properties explicitly.
Other resources online may suggest that rather than releasing the backing field with `[__facts release]`, it's cleaner just to clear it with `self.facts = nil` (which will implicitly release the old object). This is generally considered bad practice in case another object observing that property is triggered from inside the destructor, and tries to access the source object while it's in an inconsistent state.
<file_sep>+++
location = "San Francisco"
published_at = 2012-09-02T23:18:31-07:00
slug = "pg-max-connections"
title = "Max Connections for a Postgres Service"
+++
Once in a while, it's useful to know how many connections your Postgres service can support. For example, at Heroku we use this information to help alert us when any of our production-critical databases are approaching their connection limit.
Inspecting a Postgres configuration file will reveal a setting that specifies the maximum number of connections that its associated service will allow:
```
max_connections = 20
```
As with other settings, this can be checked by connecting to any running Postgres and executing the following query:
``` sql
select name, setting from pg_settings where name = 'max_connections';
```
**Protip:** you'll notice that for all our Postgres services at Heroku, from Dev to Ronin, and all the way to Mecha, the response will be `500`.
<file_sep>+++
location = "San Francisco"
published_at = 2013-06-05T07:18:13-07:00
slug = "params"
title = "Discriminating Input"
+++
While designing our [V3 platform API](https://devcenter.heroku.com/articles/platform-api-reference), we made the decision to make the formatting in our requests and responses as symmetric as possible. Although common for an API to return JSON, it's not quite as common to take it as input, but is our recommended usage for all incoming `PATCH`/`POST`/`PUT` requests.
Largely reasons largely for developer convenience, we decided to allow fall back to form-encoded parameters as well (for the time being at least), so we put together a helper method that allows us to handle these in a generic fashion. It looks something like this:
``` ruby
class API < Sinatra::Base
post "/resources" do
params = parse_params
Resource.create(name: params[:name])
201
end
private
def parse_params
if request.content_type == "application/json"
indifferent_params(MultiJson.decode(request.body.read))
request.body.rewind
else
params
end
end
end
```
By specifying `Content-Type: application/json`, JSON-encoded data can be sent to and read by the API:
```
curl -X POST https://api.example.com/resources \
-d '{"name":"my-resource"}' -H "Content-Type: application/json"
```
The more traditional method for encoding POSTs is to use the `application/x-www-form-urlencoded` MIME type which looks like `company=heroku&num_founders=3` and is sent in directly as part of the request body. Rack will decode form-encoded bodies by default and add them to the `params` hash, so our API easily falls back to this:
```
curl -X POST https://api.example.com/resources -d "name=my-resource"
```
(Note that Curl will send `Content-Type: application/x-www-form-urlencoded` by default.)
Good so far, but a side-effect that we hadn't intended is that our API will also read standard query parameters:
```
curl -X POST https://api.example.com/resources?name=my-resource
```
On closer examination of the Rack source code, it's easy to see that Rack is trying to simplify its users lives by blending all incoming parameters into one giant input hash:
``` ruby
def params
@params ||= self.GET.merge(self.POST)
rescue EOFError
self.GET.dup
end
```
While not a problem per se, this does widen the available options for use of API to cases beyond what we considered to be reasonable. We cringed to think about seeing technically correct, but somewhat indiscriminate usage examples:
```
curl -X POST https://api.heroku.com/apps?region=eu -d "name=my-app"
```
By re-implementing the helper above to ignore `params`, the catch-all set of parameters, and instead use `request.POST`, which contains only form-encoded input, we an exclude query input:
``` ruby
def parse_params
if request.content_type == "application/json"
indifferent_params(MultiJson.decode(request.body.read))
request.body.rewind
elsif request.form_data?
indifferent_params(request.POST)
else
{}
end
end
```
## rack-test
As an addendum, it's worth mentioning that `rack-test` also sends `application/x-www-form-urlencoded` by default (and always will unless you explicitly override `Content-Type` to a non-nil value), and that's what's going on when you do this:
``` ruby
it "creates a resource" do
post "/resources", name: "my-resource"
end
```
We found that it was worthwhile writing our tests to check the primary input path foremost, so most look closer to the following:
``` ruby
it "creates a resource" do
header "Content-Type", "application/json"
post "/resources", MultiJson.encode({ name: "my-resource" })
end
```
<file_sep>+++
location = "Calgary"
published_at = 2009-06-04T00:00:00-06:00
slug = "printing-binary-in-c-sharp"
tiny_slug = "11"
title = "Printing Binary in C#"
+++
I've been looking on and off for the last couple days for a way to easily convert binary data to a hex representation in C# for printing. As it turns out, the `BitConverter` class is normally used to do this:
``` csharp
string s = System.BitConverter.ToString(
new byte[] { 1, 15, 17 }
);
// s contains: "01-0F-11"
```
It's also handy for packing and unpacking binary data:
``` csharp
// Given an integer, the converter always returns a 4-byte
// array. The length of this array will depend on the data
// type it's given.
byte[] bytes = System.BitConverter.GetBytes(42);
// bytes contains: { 42, 0, 0, 0 }
// ToInt32 always reads 4 bytes
int num = System.BitConverter.ToInt32(bytes, 0);
// num is: 42
```
|
e9dcfa990822bdff62a9f038f8b9e981fd244832
|
[
"Markdown",
"Go Module",
"Go",
"Makefile"
] | 78 |
Markdown
|
brandur/mutelight
|
f6dcd530abdc421eb828935be694ed03fd4bd503
|
084a41076a5eca539147500900fdb2bc765e10ae
|
refs/heads/master
|
<file_sep>#include "stdafx.h"
#include "trafficLightDetect.h"
using namespace cv;
void TrafficLightDetect::run() {
preProcess();
morphologyEx(red, red2, cv::MORPH_OPEN, square3x3);
morphologyEx(green, green2, cv::MORPH_OPEN, square3x3);
morphologyEx(red2, red2, cv::MORPH_CLOSE, diamond);
morphologyEx(green2, green2, cv::MORPH_CLOSE, diamond);
morphologyEx(black, black2, cv::MORPH_CLOSE, square5x5);
morphologyEx(black2, black2, cv::MORPH_OPEN, square3x3);
Mat tmpred, tmpgreen, tmpblack;
float rectanglerity;
float Area;
float threshlod;
red2.copyTo(tmpred);
green2.copyTo(tmpgreen);
black2.copyTo(tmpblack);
std::list<Rect> RedlightList;
Rect LightRect0;
std::list<Rect> GreenlightList;
std::list<Rect> blackList;
std::list<Rect> rectList;
std::vector<std::vector<cv::Point>> RedLightContours;
std::vector<std::vector<cv::Point>> greenLightContours;
std::vector<std::vector<cv::Point>> blackContours;
findContours(tmpred, RedLightContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
// Eliminate too short or too long contours
int cmin1 = 10; // minimum contour length
int cmax1 = 1000; // maximum contour length
std::vector<std::vector<cv::Point>>::const_iterator Reditc = RedLightContours.begin();
while (Reditc != RedLightContours.end()) {
if (Reditc->size() < cmin1 || Reditc->size() > cmax1) {
Reditc = RedLightContours.erase(Reditc);
} else {
LightRect0 = boundingRect(cv::Mat(*Reditc));
RedlightList.push_back(LightRect0);
++Reditc;
}
}
img_resized.copyTo(redContours);
drawContours(redContours, RedLightContours, -1, Scalar(0, 0, 255), 2);
findContours(tmpgreen, greenLightContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
// Eliminate too short or too long contours
int cmin2 = 10; // minimum contour length
int cmax2 = 1000; // maximum contour length
std::vector<std::vector<cv::Point>>::const_iterator greenItc = greenLightContours.begin();
while (greenItc != greenLightContours.end()) {
if (greenItc->size() < cmin2 || greenItc->size() > cmax2) {
greenItc = greenLightContours.erase(greenItc);
} else {
LightRect0 = boundingRect(cv::Mat(*greenItc));
GreenlightList.push_back(LightRect0);
++greenItc;
}
}
img_resized.copyTo(greenContours);
drawContours(greenContours, greenLightContours, -1, Scalar(0, 255, 0), 2);
// Find traffic light outline
Mat gray_img;
Mat img_thresold;
Mat img_binary;
cvtColor(equaled_img, gray_img, CV_BGR2GRAY);
threshold(gray_img, img_thresold, 0, 255, cv::THRESH_OTSU);
img_thresold.copyTo(otsu);
//morphologyEx(img_thresold, img_binary, cv::MORPH_OPEN, square5x5);
morphologyEx(img_thresold, img_binary, cv::MORPH_CLOSE, squareEle);
morphologyEx(img_thresold, img_thresold, cv::MORPH_OPEN, square5x5);
//morphologyEx(img_binary, img_binary, cv::MORPH_OPEN, square3x3);
Mat tmpPic1;
img_binary.copyTo(tmpPic1);
// Get the contours of the connected components
std::vector<std::vector<cv::Point>> contours;
cv::findContours(tmpPic1,
contours, // a vector of contours
CV_RETR_LIST, // retrieve the external contours
CV_CHAIN_APPROX_NONE); // retrieve all pixels of each contours
// Eliminate too short or too long contours
int cmin = 60; // minimum contour length
int cmax = 2000; // maximum contour length
std::vector<std::vector<cv::Point>>::const_iterator itc = contours.begin();
while (itc != contours.end()) {
if (itc->size() < cmin || itc->size() > cmax) {
itc = contours.erase(itc);
} else {
LightRect0 = boundingRect((*itc));
Area = contourArea((*itc));
rectanglerity = (float)(Area / LightRect0.area());
threshlod = 0.75;
if (rectanglerity > threshlod&&LightRect0.height>LightRect0.width) {
++itc;
} else {
itc = contours.erase(itc);
}
}
}
Rect r0;
float propotion;
itc = contours.begin();
while (itc != contours.end()) {
r0 = cv::boundingRect(cv::Mat(*itc));
Area = contourArea((*itc));
propotion = (float)r0.height / r0.width;
rectanglerity = (float)(Area / r0.area());
//if (abs(propotion - 13.0f / 6.0f) > 0.8)
//{
// itc = contours.erase(itc);
// continue;
//}
if (rectanglerity < 0.8) {
itc = contours.erase(itc);
continue;
} else {
rectList.push_back(r0);
itc++;
}
}
// Combine light color and outline
std::list<Rect>::iterator RectIt;
std::list<Rect>::iterator RedRectIt;
std::list<Rect>::iterator GreenRectIt;
Rect backGroundRect, redLightRect, greenLightRect, minRect, andRect;
float distanceThreshold = 15.0f;
float a, b, c, d;
float tmpNum;
int areaTh;
for (RectIt = rectList.begin(); RectIt != rectList.end(); RectIt++) {
backGroundRect = (*RectIt);
a = backGroundRect.x + backGroundRect.width / 2;
c = backGroundRect.y;
for (RedRectIt = RedlightList.begin(); RedRectIt != RedlightList.end(); RedRectIt++) {
redLightRect = (*RedRectIt);
b = redLightRect.x + redLightRect.width / 2;
d = redLightRect.y;
andRect = redLightRect&backGroundRect;
minRect = redLightRect | backGroundRect;
areaTh = 300;
if (andRect.area() > areaTh || andRect == redLightRect) {
if (abs(a - b) < distanceThreshold&&abs(c - d)<10) {
trafficRedLightRect.push_back(minRect);
break;
}
} else if (flag !=3) {
tmpNum = (float)minRect.height / minRect.width;
if (minRect.area() < 2500 && tmpNum > 2 && tmpNum < 5) {
trafficRedLightRect.push_back(minRect);
break;
}
}
}
for (GreenRectIt = GreenlightList.begin(); GreenRectIt != GreenlightList.end(); GreenRectIt++) {
greenLightRect = *GreenRectIt;
b = greenLightRect.x + greenLightRect.width / 2;
d = greenLightRect.y + greenLightRect.height;
c = backGroundRect.y + backGroundRect.height;
andRect = greenLightRect&backGroundRect;
minRect = greenLightRect | backGroundRect;
if (andRect.area() > areaTh || andRect == greenLightRect) {
if (abs(a - b) < distanceThreshold&&d > c) {
trafficGreenLightRect.push_back(minRect);
break;
}
} else {
tmpNum = (float)minRect.height / minRect.width;
if (minRect.area() < 2500 && tmpNum > 2 && tmpNum < 5) {
trafficGreenLightRect.push_back(minRect);
break;
}
}
}
}
fliter(trafficRedLightRect, img_resized);
fliter(trafficGreenLightRect, img_resized);
int mixAreaTH = 2500;
if (flag == 2) {
mixAreaTH = 400;
}
if (trafficRedLightRect.size()==0&&trafficGreenLightRect.size()==0&&flag!=4) {
//std::cout << "not found" << std::endl;
findContours(tmpblack, blackContours, CV_RETR_LIST, CV_CHAIN_APPROX_NONE);
// Eliminate too short or too long contours
int cmin3 = 30; // minimum contour length
int cmax3 = 500; // maximum contour length
std::vector<std::vector<cv::Point>>::const_iterator blackItc = blackContours.begin();
while (blackItc != blackContours.end()) {
if (blackItc->size() < cmin3 || blackItc->size() > cmax3) {
blackItc = blackContours.erase(blackItc);
} else {
LightRect0 = boundingRect(cv::Mat(*blackItc));
Area = contourArea((*blackItc));
rectanglerity = (float)(Area / LightRect0.area());
if (LightRect0.area() > 1000) {
threshlod = 0.9;
} else {
threshlod = 0.6;
}
if (rectanglerity > threshlod) {
blackList.push_back(LightRect0);
rectList.push_back(LightRect0);
++blackItc;
} else {
blackItc = blackContours.erase(blackItc);
}
}
}
for (RectIt = rectList.begin(); RectIt != rectList.end(); RectIt++) {
backGroundRect = (*RectIt);
a = backGroundRect.x + backGroundRect.width / 2;
c = backGroundRect.y + backGroundRect.height / 2;
for (RedRectIt = RedlightList.begin(); RedRectIt != RedlightList.end(); RedRectIt++) {
redLightRect = (*RedRectIt);
b = redLightRect.x + redLightRect.width / 2;
d = redLightRect.y + redLightRect.height / 2;
andRect = redLightRect&backGroundRect;
if (andRect.area() > 300) {
if (abs(a - b) < distanceThreshold) {
trafficRedLightRect.push_back(backGroundRect);
break;
}
} else {
minRect = redLightRect | backGroundRect;
tmpNum = (float)minRect.height / minRect.width;
if (minRect.area() < mixAreaTH && tmpNum > 2 && tmpNum < 5) {
trafficRedLightRect.push_back(minRect);
break;
}
}
}
for (GreenRectIt = GreenlightList.begin(); GreenRectIt != GreenlightList.end(); GreenRectIt++) {
greenLightRect = *GreenRectIt;
b = greenLightRect.x + greenLightRect.width / 2;
d = greenLightRect.y + greenLightRect.height / 2;
andRect = greenLightRect&backGroundRect;
if (andRect.area() > 300) {
if (abs(a - b) < distanceThreshold) {
trafficGreenLightRect.push_back(backGroundRect);
break;
}
} else {
minRect = greenLightRect | backGroundRect;
tmpNum = (float)minRect.height / minRect.width;
if (minRect.area() < mixAreaTH && tmpNum > 2 && tmpNum < 5) {
trafficGreenLightRect.push_back(minRect);
break;
}
}
}
}
}
RectIt = rectList.begin();
img_resized.copyTo(rectBack);
while (RectIt != rectList.end()) {
rectangle(rectBack, (*RectIt), Scalar(0), 3);
RectIt++;
}
fliter(trafficRedLightRect, img_resized);
fliter(trafficGreenLightRect, img_resized);
// Draw Rect
}
Mat TrafficLightDetect::getResult(Mat img)
{
Mat img_result;
img.copyTo(img_result);
Rect tmpRect;
for (int i = trafficRedLightRect.size(); i > 0; i--) {
tmpRect = trafficRedLightRect.front();
trafficRedLightRect.pop_front();
//rectangle(img_result, tmpRect, Scalar(0, 0, 255), 3);
Point center(tmpRect.x + tmpRect.width/2, tmpRect.y);
circle(img_result, center, tmpRect.width, Scalar(0, 0, 255), 3);
}
for (int i = trafficGreenLightRect.size(); i > 0; i--) {
tmpRect = trafficGreenLightRect.front();
trafficGreenLightRect.pop_front();
//rectangle(img_result, tmpRect, Scalar(0, 255, 0), 3);
Point center(tmpRect.x + tmpRect.width/2, tmpRect.y + tmpRect.height);
circle(img_result, center, tmpRect.width, Scalar(0, 255, 0), 3);
}
return img_result;
}
void TrafficLightDetect::setInputImg(Mat input) {
InputImg = input;
}
void TrafficLightDetect::fliter(std::list<Rect>& rectlist,Mat img)
{
std::list<Rect>::iterator it = rectlist.begin();
while (it!=rectlist.end()) {
if (((*it).y > img.rows / 2) || ((*it).x + (*it).width > (img.cols - 200))) {
it = rectlist.erase(it);
} else {
it++;
}
}
}
void TrafficLightDetect::setflag(string str) {
flag = 1;
}<file_sep>
// TrafficLightDetectionDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TrafficLightDetection.h"
#include "TrafficLightDetectionDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CTrafficLightDetectionDlg dialog
CTrafficLightDetectionDlg::CTrafficLightDetectionDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CTrafficLightDetectionDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CTrafficLightDetectionDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CTrafficLightDetectionDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_LOADPICTURE, &CTrafficLightDetectionDlg::OnBnClickedButtonLoadpicture)
ON_BN_CLICKED(IDC_BUTTON_DETECT, &CTrafficLightDetectionDlg::OnBnClickedButtonDetect)
ON_BN_CLICKED(IDC_BUTTON_GRAY, &CTrafficLightDetectionDlg::OnBnClickedButtonGray)
ON_BN_CLICKED(IDC_BUTTON_SIFT, &CTrafficLightDetectionDlg::OnBnClickedButtonSift)
ON_BN_CLICKED(IDC_BUTTON_EXIT, &CTrafficLightDetectionDlg::OnBnClickedButtonExit)
ON_BN_CLICKED(IDC_BUTTON_HIST, &CTrafficLightDetectionDlg::OnBnClickedButtonHist)
ON_BN_CLICKED(IDC_BUTTON_SHARPEN, &CTrafficLightDetectionDlg::OnBnClickedButtonSharpen)
ON_BN_CLICKED(IDC_BUTTON_SURF, &CTrafficLightDetectionDlg::OnBnClickedButtonSurf)
ON_BN_CLICKED(IDC_BUTTON_ORB, &CTrafficLightDetectionDlg::OnBnClickedButtonOrb)
ON_BN_CLICKED(IDC_BUTTON_MORPHOLOGY, &CTrafficLightDetectionDlg::OnBnClickedButtonMorphology)
ON_BN_CLICKED(IDC_BUTTON_DETECT2, &CTrafficLightDetectionDlg::OnBnClickedButtonDetect2)
END_MESSAGE_MAP()
// CTrafficLightDetectionDlg message handlers
BOOL CTrafficLightDetectionDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
outputList = (CListBox*) GetDlgItem(IDC_OUTPUT);
CRect rc;
GetDlgItem(IDC_STATIC_ORIGINPICTURE)->GetClientRect(&rc);
originalWidth = rc.Width();
originalHeight = rc.Height();
GetDlgItem(IDC_STATIC_PROCESSEDPICTURE)->GetClientRect(&rc);
processedWidth = rc.Width();
processedHeight = rc.Height();
// Set menu
mainMenu.LoadMenu(IDR_MAINMENU);
SetMenu(&mainMenu);
return TRUE; // return TRUE unless you set the focus to a control
}
void CTrafficLightDetectionDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CTrafficLightDetectionDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CTrafficLightDetectionDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
// Mat to CImage
void CTrafficLightDetectionDlg::MatToCImage(cv::Mat& mat, CImage& cImage) {
int w = mat.cols;
int h = mat.rows;
int channels = mat.channels();
const int MaxColors = 256;
RGBQUAD* ColorTable = new RGBQUAD[MaxColors];
if(!cImage.IsNull()) {
cImage.Destroy();
//cImage.Detach();
}
cImage.Create(w, h, 8 * channels);
cImage.GetColorTable(0, MaxColors, ColorTable);
for (int i = 0; i < MaxColors; i++) {
ColorTable[i].rgbBlue = (BYTE)i;
ColorTable[i].rgbGreen = (BYTE)i;
ColorTable[i].rgbRed = (BYTE)i;
ColorTable[i].rgbReserved = 0;
}
cImage.SetColorTable(0, MaxColors, ColorTable);
delete[] ColorTable;
// gray image
if (channels == 1) {
uchar *pS;
uchar *pImg = (uchar *)cImage.GetBits();
int step = cImage.GetPitch();
for (int i = 0; i < h; i++) {
pS = mat.ptr<uchar>(i);
for (int j = 0; j < w; j++) {
*(pImg + i*step + j) = pS[j];
}
}
}
// colorful image
if (channels == 3) {
uchar *pS;
uchar *pImg = (uchar *)cImage.GetBits();
int step = cImage.GetPitch();
for (int i = 0; i < h; i++) {
pS = mat.ptr<uchar>(i);
for (int j = 0; j < w; j++) {
for (int k = 0; k < 3; k++) {
*(pImg + i*step + j * 3 + k) = pS[j * 3 + k];
}
}
}
}
}
void CTrafficLightDetectionDlg::OnBnClickedButtonLoadpicture() {
// TODO: Add your control notification handler code here
CString filePath;
CFileDialog openFileDialog(TRUE, NULL, NULL, 0, _T("JPG Files (*.jpg)|*.jpg|All Files (*.*)|*.*||"));
if (IDOK == openFileDialog.DoModal()) {
trafficLightDetect.reset();
filePath = openFileDialog.GetPathName();
USES_CONVERSION;
char* p = W2A(filePath);
std::string fileName(p);
trafficLightDetect.setflag(fileName);
cv::Mat inputImg = cv::imread(fileName);
if(inputImg.empty()) {
return;
}
inputImg.copyTo(matImage);
resize(inputImg, inputImg, Size(originalWidth, originalHeight));
MatToCImage(inputImg, originalCImage);
if (originalCImage.IsNull())
return;
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
//ReleaseDC(pDC);
pWnd->ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Load Image Success."));
}
}
void CTrafficLightDetectionDlg::OnBnClickedButtonDetect()
{
// TODO: Add your control notification handler code here
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
trafficLightDetect.reset();
if (matImage.empty())
{
outputList->AddString(_T("No Image Loaded."));
return;
}
trafficLightDetect.setInputImg(matImage);
double t = (double) getTickCount();
trafficLightDetect.run();
Mat result;
matImage.copyTo(result);
resize(result, result, Size(640, 480));
result = trafficLightDetect.getResult(result);
resize(result, result, Size(processedWidth, processedHeight));
MatToCImage(result, processedCImgae);
if (processedCImgae.IsNull())
return;
cx = processedCImgae.GetWidth();
cy = processedCImgae.GetHeight();
pWnd = GetDlgItem(IDC_STATIC_PROCESSEDPICTURE);
pDC = pWnd->GetDC();
processedCImgae.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Detect traffic light successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonGray()
{
// TODO: Add your control notification handler code here
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
if (matImage.empty()) {
outputList->AddString(_T("No Image Loaded."));
return;
}
Mat result;
matImage.copyTo(result);
cvtColor(matImage, result, CV_BGR2GRAY);
resize(result, result, Size(processedWidth, processedHeight));
MatToCImage(result, processedCImgae);
if (processedCImgae.IsNull())
return;
cx = processedCImgae.GetWidth();
cy = processedCImgae.GetHeight();
pWnd = GetDlgItem(IDC_STATIC_PROCESSEDPICTURE);
pDC = pWnd->GetDC();
processedCImgae.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Make image gray successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonSift()
{
// TODO: Add your control notification handler code here
Mat input1=imread("01.jpg",1);
Mat input2=imread("02.jpg",1);
SiftFeatureDetector detector;
vector<KeyPoint> keypoint1,keypoint2;
detector.detect(input1,keypoint1);
Mat output1;
drawKeypoints(input1,keypoint1,output1);
imshow("sift_result1.jpg",output1);
imwrite("sift_result1.jpg",output1);
Mat output2;
SiftDescriptorExtractor extractor;
Mat descriptor1,descriptor2;
BruteForceMatcher<L2<float>> matcher;
vector<DMatch> matches;
Mat img_matches;
detector.detect(input2,keypoint2);
drawKeypoints(input2,keypoint2,output2);
imshow("sift_result2.jpg",output2);
imwrite("sift_result2.jpg",output2);
extractor.compute(input1,keypoint1,descriptor1);
extractor.compute(input2,keypoint2,descriptor2);
matcher.match(descriptor1,descriptor2,matches);
drawMatches(input1,keypoint1,input2,keypoint2,matches,img_matches);
imshow("matches",img_matches);
imwrite("matches.jpg",img_matches);
outputList->InsertString(outputList->GetCount(),_T("Sift image successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonExit()
{
// TODO: Add your control notification handler code here
SendMessage(WM_CLOSE);
//DestroyWindow();
}
void CTrafficLightDetectionDlg::OnBnClickedButtonHist()
{
// TODO: Add your control notification handler code here
Mat result;
cvtColor(matImage, result, CV_BGR2HSV);
// Quantize the hue to 30 levels
// and the saturation to 32 levels
int hbins = 30, sbins = 32;
int histSize[] = {hbins, sbins};
// hue varies from 0 to 179, see cvtColor
float hranges[] = { 0, 180 };
// saturation varies from 0 (black-gray-white) to
// 255 (pure spectrum color)
float sranges[] = { 0, 256 };
const float* ranges[] = { hranges, sranges };
MatND hist;
// we compute the histogram from the 0-th and 1-st channels
int channels[] = {0, 1};
calcHist( &result, 1, channels, Mat(), // do not use mask
hist, 2, histSize, ranges,
true, // the histogram is uniform
false );
double maxVal=0;
minMaxLoc(hist, 0, &maxVal, 0, 0);
int scale = 10;
Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3);
for( int h = 0; h < hbins; h++ ) {
for( int s = 0; s < sbins; s++ ) {
float binVal = hist.at<float>(h, s);
int intensity = cvRound(binVal*255/maxVal);
rectangle( histImg, Point(h*scale, s*scale),
Point( (h+1)*scale - 1, (s+1)*scale - 1),
Scalar::all(intensity),
CV_FILLED );
}
}
namedWindow( "H-S Histogram", 1 );
imshow( "H-S Histogram", histImg );
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
if (matImage.empty()) {
outputList->AddString(_T("No Image Loaded."));
return;
}
resize(result, result, Size(processedWidth, processedHeight));
MatToCImage(result, processedCImgae);
if (processedCImgae.IsNull())
return;
cx = processedCImgae.GetWidth();
cy = processedCImgae.GetHeight();
pWnd = GetDlgItem(IDC_STATIC_PROCESSEDPICTURE);
pDC = pWnd->GetDC();
processedCImgae.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Hist image successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonSharpen()
{
// TODO: Add your control notification handler code here
Mat result;
matImage.copyTo(result);
//result.create(matImage.size(), matImage.type());
for (int j= 1; j<matImage.rows-1; j++) { // for all rows
// (except first and last)
const uchar* previous = matImage.ptr<const uchar>(j-1); // previous row
const uchar* current = matImage.ptr<const uchar>(j); // current row
const uchar* next = matImage.ptr<const uchar>(j+1); // next row
uchar* output = result.ptr<uchar>(j); // output row
int ch = matImage.channels();
int starts = ch;
int ends = (matImage.cols - 1) * ch;
for (int col = starts; col < ends; col++) {
//输出图像的遍历指针与当前行的指针同步递增, 以每行的每一个像素点的每一个通道值为一个递增量, 因为要考虑到图像的通道数
*output++ = cv::saturate_cast<uchar>(5 * current[col] - current[col-ch] - current[col+ch] - previous[col] - next[col]);
//*output++ = cv::saturate_cast<uchar>(current[col+ch]+next[col]-2 * current[col]);
}
}
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
if (matImage.empty()) {
outputList->AddString(_T("No Image Loaded."));
return;
}
resize(result, result, Size(processedWidth, processedHeight));
MatToCImage(result, processedCImgae);
if (processedCImgae.IsNull())
return;
cx = processedCImgae.GetWidth();
cy = processedCImgae.GetHeight();
pWnd = GetDlgItem(IDC_STATIC_PROCESSEDPICTURE);
pDC = pWnd->GetDC();
processedCImgae.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Sharpen image successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonSurf()
{
// TODO: Add your control notification handler code here
Mat input1=imread(".\\01.jpg",0);
Mat input2=imread(".\\02.jpg",0);
SurfFeatureDetector detector(2500);
vector<KeyPoint> keypoint1,keypoint2;
detector.detect(input1,keypoint1);
Mat output1;
drawKeypoints(input1,keypoint1,output1,cv::Scalar::all (255),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
//drawKeypoints(input1,keypoint1,output1);
imshow("sift_result1.jpg",output1);
imwrite("sift_result1.jpg",output1);
Mat output2;
SurfDescriptorExtractor extractor;
Mat descriptor1,descriptor2;
BruteForceMatcher<L2<float>> matcher;
vector<DMatch> matches;
Mat img_matches;
detector.detect(input2,keypoint2);
drawKeypoints(input2,keypoint2,output2,cv::Scalar::all (255),cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
imshow("sift_result2.jpg",output2);
imwrite("sift_result2.jpg",output2);
extractor.compute(input1,keypoint1,descriptor1);
extractor.compute(input2,keypoint2,descriptor2);
matcher.match(descriptor1,descriptor2,matches);
drawMatches(input1,keypoint1,input2,keypoint2,matches,img_matches);
imshow("matches",img_matches);
imwrite("matches.jpg",img_matches);
outputList->InsertString(outputList->GetCount(),_T("Surf image successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonOrb()
{
// TODO: Add your control notification handler code here
Mat obj=imread("01.jpg",0); //载入目标图像
Mat scene=imread("02.jpg",0); //载入场景图像
vector<KeyPoint> obj_keypoints,scene_keypoints;
Mat obj_descriptors,scene_descriptors;
ORB detector; //采用ORB算法提取特征点
detector.detect(obj,obj_keypoints);
detector.detect(scene,scene_keypoints);
detector.compute(obj,obj_keypoints,obj_descriptors);
detector.compute(scene,scene_keypoints,scene_descriptors);
BFMatcher matcher(NORM_HAMMING,true); //汉明距离做为相似度度量
vector<DMatch> matches;
matcher.match(obj_descriptors, scene_descriptors, matches);
Mat match_img;
drawMatches(obj,obj_keypoints,scene,scene_keypoints,matches,match_img);
imshow("before mismatching",match_img);
outputList->InsertString(outputList->GetCount(),_T("Orb image successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonMorphology()
{
// TODO: Add your control notification handler code here
int const max_operator = 4;
int const max_elem = 2;
int const max_kernel_size = 21;
srand(time(NULL));
int morph_elem = rand() % max_elem;
int morph_size = rand() % max_kernel_size;
int morph_operator = rand() % max_operator;
Mat result;
Mat element = getStructuringElement( morph_elem, Size( 2*morph_size + 1, 2*morph_size+1 ), Point( morph_size, morph_size ) );
/// Apply the specified morphology operation
int operation = morph_operator + 2;
morphologyEx( matImage, result, operation, element );
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
if (matImage.empty()) {
outputList->AddString(_T("No Image Loaded."));
return;
}
resize(result, result, Size(processedWidth, processedHeight));
MatToCImage(result, processedCImgae);
if (processedCImgae.IsNull())
return;
cx = processedCImgae.GetWidth();
cy = processedCImgae.GetHeight();
pWnd = GetDlgItem(IDC_STATIC_PROCESSEDPICTURE);
pDC = pWnd->GetDC();
processedCImgae.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Morphology image successfully."));
}
void CTrafficLightDetectionDlg::OnBnClickedButtonDetect2()
{
// TODO: Add your control notification handler code here
Mat frame, result;
matImage.copyTo(frame);
matImage.copyTo(result);
cvtColor(frame, frame, CV_RGB2GRAY);
trafficLightDetector.setContexts(trafficLightDetector);
LightState lightState = trafficLightDetector.brightnessDetect(frame);
vector<Rect> boundedRects;
trafficLightDetector.drawTrafficLights(result, lightState);
//trafficLightDetector.drawEnforcement(resultImage, isEnforced, lightState);
//trafficLightDetector.drawBoundedRects(resultImage, boundedRects);
Invalidate();
UpdateWindow();
CWnd* pWnd = GetDlgItem(IDC_STATIC_ORIGINPICTURE);
CDC *pDC = pWnd->GetDC();
int cx = originalCImage.GetWidth();
int cy = originalCImage.GetHeight();
originalCImage.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
resize(result, result, Size(processedWidth, processedHeight));
MatToCImage(result, processedCImgae);
if (processedCImgae.IsNull())
return;
cx = processedCImgae.GetWidth();
cy = processedCImgae.GetHeight();
pWnd = GetDlgItem(IDC_STATIC_PROCESSEDPICTURE);
pDC = pWnd->GetDC();
processedCImgae.Draw(pDC->m_hDC, 0, 0, cx, cy);
ReleaseDC(pDC);
outputList->InsertString(outputList->GetCount(),_T("Detect traffic light successfully."));
}
<file_sep>#include "stdafx.h"
#include "TrafficLightDetector.h"
TrafficLightDetector::TrafficLightDetector() {
}
void TrafficLightDetector::setContexts(TrafficLightDetector &detector) {
for (int i = 0; i < TL_COUNT; i++) {
contexts[i].lightState = UNDEFINED;
detector.contexts.push_back(contexts[i]);
}
}
LightState TrafficLightDetector::brightnessDetect(const Mat &input) {
Mat tmpImage;
input.copyTo(tmpImage);
for (int i = 0; i < contexts.size(); i++) {
Context context = contexts[i];
Mat roi = tmpImage(Rect(context.topLeft, context.botRight));
threshold(roi, roi, 0, 255, THRESH_BINARY | THRESH_OTSU);
bool display_red = (getBrightnessRatioInCircle(tmpImage, context.redCenter, context.lampRadius) > 0.5);
bool display_yellow = (getBrightnessRatioInCircle(tmpImage, context.yellowCenter, context.lampRadius) > 0.5);
bool display_green = (getBrightnessRatioInCircle(tmpImage, context.greenCenter, context.lampRadius) > 0.5);
int currentLightsCode = getCurrentLightsCode(display_red, display_yellow, display_green);
contexts[i].lightState = determineState(contexts[i].lightState, currentLightsCode);
// Make ROI black
roi.setTo(Scalar(0));
}
return contexts[0].lightState;
}
double TrafficLightDetector::getBrightnessRatioInCircle(const Mat &input, const Point center, const int radius) {
int whitePoints = 0;
int blackPoints = 0;
for (int i = center.x - radius; i < center.x + radius; i++) {
for (int j = center.y - radius; j < center.y + radius; j++) {
if ((i - center.x)*(i - center.x) + (j - center.y)*(j - center.y) <= radius*radius) {
(input.at<uchar>(j,i) == 0) ? blackPoints++ : whitePoints++;
}
}
}
//printf("Ratio: %f\n", ((double)whitePoints) / (whitePoints + blackPoints));
return ((double)whitePoints) / (whitePoints + blackPoints);
}
int TrafficLightDetector::getCurrentLightsCode(bool display_red, bool display_yellow, bool display_green) {
return (int)display_red + 2 * ((int) display_yellow) + 4 * ((int) display_green);
}
LightState TrafficLightDetector::determineState(LightState previousState, int currentLightsCode) {
//printf("Previous state: %d, currentCode: %d, Switched state to %d\n", previousState, currentLightsCode, STATE_TRANSITION_MATRIX[previousState][currentLightsCode]);
return STATE_TRANSITION_MATRIX[previousState][currentLightsCode];
}
/*
* Attempt to recognize by color tracking in HSV. Detects good only green, but need to
* play also with S and V parameters range.
*/
void TrafficLightDetector::colorDetect(const Mat &input, Mat &output, const Rect coords, int Hmin, int Hmax) {
if (input.channels() != 3) {
return;
}
Mat hsv, thresholded;
cvtColor(input, hsv, CV_RGB2HSV, 0);
inRange(hsv, Scalar(Hmin,0,0), Scalar(Hmax,255,255), thresholded);
cvtColor(thresholded, thresholded, CV_GRAY2RGB);
thresholded.copyTo(output);
rectangle(output, coords, MY_COLOR_RED);
}
void TrafficLightDetector::drawTrafficLights(Mat &targetImg, LightState lightState) {
switch (lightState) {
case GREEN:
circle(targetImg, GREEN_DRAW_CENTER, LIGHT_DRAW_RADIUS, MY_COLOR_GREEN, -1);
break;
case YELLOW:
circle(targetImg, YELLOW_DRAW_CENTER, LIGHT_DRAW_RADIUS, MY_COLOR_YELLOW, -1);
break;
case RED:
circle(targetImg, RED_DRAW_CENTER, LIGHT_DRAW_RADIUS, MY_COLOR_RED, -1);
break;
case REDYELLOW:
circle(targetImg, YELLOW_DRAW_CENTER, LIGHT_DRAW_RADIUS, MY_COLOR_YELLOW, -1);
circle(targetImg, RED_DRAW_CENTER, LIGHT_DRAW_RADIUS, MY_COLOR_RED, -1);
break;
}
}<file_sep>#include "stdafx.h"
#include "Context.h"
Context::Context(Point aRedCenter, Point aYellowCenter, Point aGreenCenter, int aLampRadius, Point aTopLeft, Point aBotRight) {
redCenter = aRedCenter;
yellowCenter = aYellowCenter;
greenCenter = aGreenCenter;
lampRadius = aLampRadius;
topLeft = aTopLeft;
botRight = aBotRight;
}<file_sep>#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <list>
#include <queue>
#include <cstdlib>
#include <iostream>
using namespace cv;
class TrafficLightDetect {
private :
cv::Mat InputImg;
cv::Mat img_resized;
cv::Mat equaled_img;
cv::Mat halfMaskImg;
cv::Mat red;
cv::Mat green;
cv::Mat black;
cv::Mat red2;
cv::Mat green2;
cv::Mat black2;
cv::Mat redContours;
cv::Mat greenContours;
cv::Mat otsu;
cv::Mat rectBack;
cv::Size presetSize;
cv::Mat square3x3;
cv::Mat square5x5;
cv::Mat square7x7;
cv::Mat squareEle;
cv::Mat cross3x3;
cv::Mat cross5x5;
cv::Mat xElement;
cv::Mat diamond;
float timeCost;
int flag;
std::list<Rect> trafficRedLightRect, trafficGreenLightRect;
void preProcess() {
presetSize = cv::Size(640, 480);
square3x3 = cv::Mat(3, 3, CV_8U, cv::Scalar(1));
square5x5 = cv::Mat(5, 5, CV_8U, cv::Scalar(1));
square7x7 = cv::Mat(7, 7, CV_8U, cv::Scalar(1));
squareEle = cv::Mat(11, 11, CV_8U, cv::Scalar(1));
cross3x3 = cv::Mat(3, 3, CV_8U, cv::Scalar(0));
diamond = cv::Mat(5, 5, CV_8U, cv::Scalar(1));
diamond.at<uchar>(0, 0) = 0;
diamond.at<uchar>(0, 1) = 0;
diamond.at<uchar>(1, 0) = 0;
diamond.at<uchar>(4, 4) = 0;
diamond.at<uchar>(3, 4) = 0;
diamond.at<uchar>(4, 3) = 0;
diamond.at<uchar>(4, 0) = 0;
diamond.at<uchar>(4, 1) = 0;
diamond.at<uchar>(3, 0) = 0;
diamond.at<uchar>(0, 4) = 0;
diamond.at<uchar>(0, 3) = 0;
diamond.at<uchar>(1, 4) = 0;
cross3x3.at<uchar>(0, 1) = 1;
cross3x3.at<uchar>(1, 0) = 1;
cross3x3.at<uchar>(1, 1) = 1;
cross3x3.at<uchar>(1, 2) = 1;
cross3x3.at<uchar>(2, 1) = 1;
cross5x5 = cv::Mat(5, 5, CV_8U, cv::Scalar(0));
for (int i = 0; i < 5; i++) {
cross5x5.at<uchar>(2, i) = 1;
cross5x5.at<uchar>(i, 2) = 1;
}
Mat img_masked;
resize(InputImg, img_resized, presetSize, 0, 0, CV_INTER_LINEAR);
vector<Mat> img_channels;
//Mat result;
split(img_resized, img_channels);
equalizeHist(img_channels[0], img_channels[0]);
equalizeHist(img_channels[1], img_channels[1]);
equalizeHist(img_channels[2], img_channels[2]);
merge(img_channels, equaled_img);
//processImgForRed(equaled_img, result);
red = Mat(img_resized.rows, img_resized.cols, CV_8UC1);
green = Mat(img_resized.rows, img_resized.cols, CV_8UC1);
black = Mat(img_resized.rows, img_resized.cols, CV_8UC1);
normalizeImgRGBForColorDetect(equaled_img, red, green, black);
}
void normalizeImgRGBForColorDetect(cv::Mat img, cv::Mat& red, cv::Mat& green, cv::Mat& black) {
Mat result(img.rows, img.cols, CV_32FC3);
Mat_<Vec3b>::iterator it = img.begin<Vec3b>();
Mat_<Vec3f>::iterator resultIt = result.begin<Vec3f>();
Mat_<Vec3b>::iterator itend = img.end<Vec3b>();
Mat_<Vec3f>::iterator resultItend = result.end<Vec3f>();
Mat_<uchar>::iterator blackIt = black.begin<uchar>();
Mat_<uchar>::iterator blackItend = black.end<uchar>();
int sum = 0;
for (; it != itend&&resultIt != resultItend; it++, resultIt++,blackIt++) {
sum = (*it)[0] + (*it)[1] + (*it)[2];
(*resultIt)[0] = (float)(*it)[0] / sum;
(*resultIt)[1] = (float)(*it)[1] / sum;
(*resultIt)[2] = (float)(*it)[2] / sum;
if ((*it)[0] < 40 && (*it)[1] < 40 && (*it)[2] < 40) {
(*blackIt) = 255;
} else {
(*blackIt) = 0;
}
}
resultIt = result.begin<Vec3f>();
it = img.begin<Vec3b>();
Mat_<uchar>::iterator redIt = red.begin<uchar>();
Mat_<uchar>::iterator redItend = red.end<uchar>();
Mat_<uchar>::iterator greenIt = green.begin<uchar>();
Mat_<uchar>::iterator greenItend = green.end<uchar>();
for (; resultIt != resultItend&&redIt != redItend&&greenIt != greenItend; ++resultIt, ++redIt, ++greenIt) {
if (((*resultIt)[2] - (*resultIt)[1]) > 0.16 && ((*resultIt)[1] - (*resultIt)[0]) < 0.08 && ((*resultIt)[1] < 0.30)) {
(*redIt) = 255;
} else {
(*redIt) = 0;
}
if (((*resultIt)[2] - (*resultIt)[1]) < /*-0.16*/ -0.16 && ((*resultIt)[1] - (*resultIt)[0]) > /*0.18*/ 0.004 && ((*resultIt)[1] > 0.10)) {
(*greenIt) = 255;
} else {
(*greenIt) = 0;
}
//if ((*it)[2] > 100 && (*resultIt)[2] > 0.4 && (*resultIt)[1]<0.3 && (*resultIt)[0] < 0.3)
// (*redIt) = 255;
//else
// (*redIt) = 0;
//if ((*it)[2]>100 && (*resultIt)[2]>0.4 && (*resultIt)[1] > 0.3 && (*resultIt)[0] < 0.3)
// (*yellowIt) = 255;
//else
// (*yellowIt) = 0;
//if (((*it)[0] + (*it)[1])>100 && (*resultIt)[2]<0.3 && (*resultIt)[1]>0.45 && (*resultIt)[0] > 0.45)
// (*greenIt) = 255;
//else
// (*greenIt) = 0;
}
}
public:
TrafficLightDetect(){
}
void run();
void setflag(string str);
Mat getResult(Mat img);
void setInputImg(Mat input);
void fliter(std::list<Rect>& rectlist,Mat img);
void reset() {
trafficRedLightRect.clear();
trafficGreenLightRect.clear();
}
Mat getred(){ return red; }
Mat getred2(){ return red2; }
Mat getredContours(){ return redContours; }
Mat getgreen(){ return green; }
Mat getgreen2(){ return green2; }
Mat getgreenContours(){ return greenContours; }
Mat getblack(){ return black; }
Mat getotsu(){ return otsu; }
Mat getrectback(){ return rectBack; }
};<file_sep>
// TrafficLightDetectionDlg.h : header file
//
#pragma once
#include <atlconv.h>
#include <atlimage.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include <opencv2/legacy/legacy.hpp>
#include <opencv2/legacy/compat.hpp>
#include "trafficLightDetect.h"
#include "TrafficLightDetector.h"
#include <cstdlib>
#include <ctime>
using namespace cv;
// CTrafficLightDetectionDlg dialog
class CTrafficLightDetectionDlg : public CDialogEx
{
// Construction
public:
CTrafficLightDetectionDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_TRAFFICLIGHTDETECTION_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
protected:
private:
TrafficLightDetect trafficLightDetect;
TrafficLightDetector trafficLightDetector;
Mat matImage;
CImage originalCImage, processedCImgae;
CStatic originalImage, processedImage;
double originalWidth, originalHeight;
double processedWidth, processedHeight;
CMenu mainMenu;
CListBox* outputList;
void MatToCImage(cv::Mat& mat, CImage& CI);
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButtonLoadpicture();
afx_msg void OnBnClickedButtonDetect();
afx_msg void OnBnClickedButtonGray();
afx_msg void OnBnClickedButtonSift();
afx_msg void OnBnClickedButtonExit();
afx_msg void OnBnClickedButtonHist();
afx_msg void OnBnClickedButtonSharpen();
afx_msg void OnBnClickedButtonSurf();
afx_msg void OnBnClickedButtonOrb();
afx_msg void OnBnClickedButtonMorphology();
afx_msg void OnBnClickedButtonDetect2();
};
<file_sep>#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\features2d\features2d.hpp>
#include "Context.h"
using namespace cv;
#define MY_COLOR_PURPLE Scalar(255,0,255)
#define MY_COLOR_RED Scalar(0,0,255)
#define MY_COLOR_GREEN Scalar(0,255,0)
#define MY_COLOR_YELLOW Scalar(60,255,255)
#define MY_COLOR_BLUE Scalar(255,0,0)
#define MY_COLOR_WHITE Scalar(255,255,255)
static const LightState STATE_TRANSITION_MATRIX[5][8] = {
{ GREEN, RED, YELLOW, REDYELLOW, GREEN, GREEN, GREEN, UNDEFINED },
{ YELLOW, RED, YELLOW, REDYELLOW, GREEN, GREEN, GREEN, UNDEFINED },
{ RED, RED, REDYELLOW, REDYELLOW, GREEN, GREEN, GREEN, UNDEFINED },
{ REDYELLOW, REDYELLOW, REDYELLOW, REDYELLOW, GREEN, GREEN, GREEN, UNDEFINED },
{ UNDEFINED, RED, YELLOW, REDYELLOW, GREEN, GREEN, GREEN, UNDEFINED }
};
#define RED_DRAW_CENTER Point(465,465)
#define YELLOW_DRAW_CENTER Point(465,500)
#define GREEN_DRAW_CENTER Point(465,535)
#define LIGHT_DRAW_RADIUS 15
#define TL_COUNT 1
#define MIN_WIDTH 50
#define MIN_HEIGHT 50
#define MAX_WIDTH 300
#define MAX_HEIGHT 200
class TrafficLightDetector {
public:
public:
private:
Mat showMask, redMask, blueMask, greenMask;
public:
TrafficLightDetector();
LightState brightnessDetect(const Mat &input);
void colorDetect(const Mat &input, Mat &output, const Rect coords, int Hmin, int Hmax);
vector<Context> contexts;
double getBrightnessRatioInCircle(const Mat &input, const Point center, const int radius);
int getCurrentLightsCode(bool display_red, bool display_yellow, bool display_green);
LightState determineState(LightState previousState, int currentLightsCode);
void setContexts(TrafficLightDetector &detector);
void drawTrafficLights(Mat &targetImg, LightState lightState);
protected:
private:
};
|
f07adbd441cb6466ba8e20b48f48a8d39fddfd12
|
[
"C++"
] | 7 |
C++
|
WoeiSheu/TrafficLightDetection
|
ee9e5b4a7a17869d4a268c2d381f0315073a69e1
|
5505997aa1e26eae986f429cf0a18e0bd6c4f393
|
refs/heads/master
|
<repo_name>truonghoangpham123/SalesApp<file_sep>/SalesApp/SignInVC.swift
//
// SignInVC.swift
// SalesApp
//
// Created by Mac-ninjaKID on 11/28/16.
// Copyright © 2016 KobePham. All rights reserved.
// test
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import SwiftKeychainWrapper
class SignInVC: UIViewController {
@IBOutlet weak var emailField: FancyField!
@IBOutlet weak var pwdField: FancyField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.stringForKey(KEY_UID) {
print("JESS: ID found in keychain")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
// btn facebook Login
@IBAction func facebookBtnTapped(_ sender: Any) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if error != nil {
print("JESS: Unable to authenticate with Facebook - \(error)")
} else if result?.isCancelled == true {
print("JESS: User cancelled Facebook authentication")
} else {
print("JESS: Successfully authenticated with Facebook")
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.firebaseAuth(credential)
}
}
}
func firebaseAuth(_ credential: FIRAuthCredential) {
FIRAuth.auth()?.signIn(
with: credential,
completion: { (user, error) in
if error != nil {
print("JESS: Unable to authenticate with Firebase - \(error)")
} else {
print("JESS: Successfully authenticated with Firebase")
if let user = user{
self.completeSignIn(id: user.uid)
}
}
})
}
// btn Sign In Email & Pwd
@IBAction func signInTapped(_ sender: Any) {
if let email = emailField.text, let pwd = pwdField.text {
FIRAuth.auth()?.signIn(
withEmail: email,
password: pwd,
completion: { (user, error) in
// ...
if error == nil{
print("JESS: Email user authenticated with Firebase - \(error)")
if let user = user{
self.completeSignIn(id: user.uid)
}
}else{
FIRAuth.auth()?.createUser(
withEmail: email,
password: pwd,
completion: { (user, error) in
if error != nil{
print("JESS: Unable to authenticate with Firebase with Email - \(error)")
}
else{
print("JESS: Successfully authenticated with Firebase with Email")
if let user = user{
self.completeSignIn(id: user.uid)
}
}
})
}
})
}
}
func completeSignIn(id: String) {
let keyChainResult = KeychainWrapper.setString(id, forKey: KEY_UID)
print("JESS: Data Save Keychain \(keyChainResult)")
performSegue(withIdentifier: "goToFeed", sender: nil)
}
}
<file_sep>/SalesApp/Constrants.swift
//
// Constrants.swift
// SalesApp
//
// Created by Mac-ninjaKID on 11/28/16.
// Copyright © 2016 KobePham. All rights reserved.
//
import Foundation
import UIKit
let SHADOW_GRAY: CGFloat = 120.0 / 255.0
let KEY_UID = "uid"
<file_sep>/SalesApp/FeedVC.swift
//
// FeedVC.swift
// SalesApp
//
// Created by Mac-ninjaKID on 11/30/16.
// Copyright © 2016 KobePham. All rights reserved.
//
import UIKit
import Firebase
import SwiftKeychainWrapper
import FBSDKCoreKit
class FeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
// tapped SignOut
var singleTapped = UITapGestureRecognizer(target: self, action: Selector("tapDetected"))
singleTapped.numberOfTapsRequired = 1 // you can change this value
signOutTapped.isUserInteractionEnabled = true
signOutTapped.addGestureRecognizer(singleTapped)
tableView.delegate = self
tableView.dataSource = self
}
@IBOutlet weak var signOutTapped: UIImageView!
func tapDetected() {
let keyChainResult = KeychainWrapper.removeObjectForKey(KEY_UID)
print ("JESS: ID removed Keychain \(keyChainResult)")
let firebaseAuth = FIRAuth.auth()
do {
try firebaseAuth?.signOut()
} catch let signOutError as NSError {
print ("JESS: Error signing out Firebase \(signOutError)")
}
performSegue(withIdentifier: "goToSignIn", sender: nil)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "PostCell") as! PostCell
}
}
|
2fa545bf587cfdf6899ec67ffb70b83b160bd10b
|
[
"Swift"
] | 3 |
Swift
|
truonghoangpham123/SalesApp
|
4313ad08712994782ed6a7138dc1c9998c0290eb
|
82529552b669c5acd9f48b2c0523d626e98252e5
|
refs/heads/master
|
<file_sep>package com.vikfil.games_statistic.model;
import lombok.Data;
import java.io.Serializable;
@Data
public class GameDescription implements Serializable {
private String artistName;
private String releaseDate;
private String name;
private String url;
}
<file_sep>free.game = https://rss.itunes.apple.com/api/v1/us/ios-apps/top-free/games/100/explicit.json
paid.game = https://rss.itunes.apple.com/api/v1/us/ios-apps/top-paid/games/100/explicit.json
grossing.game = https://rss.itunes.apple.com/api/v1/us/ios-apps/top-grossing/all/100/explicit.json
<file_sep>package com.vikfil.games_statistic.controller;
import com.vikfil.games_statistic.dto.GameDescriptionDto;
import com.vikfil.games_statistic.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/ios/games/charts")
public class GameController {
private final GameService gameService;
@Autowired
public GameController(GameService gameService) {
this.gameService = gameService;
}
private boolean isLimitCorrect(Integer limit) {
return limit != null && limit > 0 && limit <= 100;
}
@GetMapping("/free")
public List<GameDescriptionDto> freeGames(@RequestParam(name = "limit", required = false) Integer limit) {
return (isLimitCorrect(limit)) ? gameService.getFreeGameByLimit(limit) : gameService.getFreeGame();
}
@GetMapping("/paid")
public List<GameDescriptionDto> paidGames(@RequestParam(name = "limit", required = false) Integer limit) {
return (isLimitCorrect(limit)) ? gameService.getPaidGameByLimit(limit) : gameService.getPaidGame();
}
@GetMapping("/grossing")
public List<GameDescriptionDto> grossingGames(@RequestParam(name = "limit", required = false) Integer limit) {
return (isLimitCorrect(limit)) ? gameService.getGrossingGameByLimit(limit) : gameService.getGrossingGame();
}
}
<file_sep>package com.vikfil.games_statistic.service;
import com.vikfil.games_statistic.dto.GameDescriptionDto;
import com.vikfil.games_statistic.dto.IncomingJsonParserDto;
import com.vikfil.games_statistic.mapper.GameDescriptionMapper;
import com.vikfil.games_statistic.repository.GameRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@Service
public class GameSeacher {
@Value("${free.game}")
private String freeGameLink;
@Value("${paid.game}")
private String paidGameLink;
@Value("${grossing.game}")
private String grossingGameLink;
private final GameRepository freeGameRepositoryImpl;
private final GameRepository paidGameRepositoryImpl;
private final GameRepository grossingGameRepositoryImpl;
private final RestTemplate restTemplate;
private final GameDescriptionMapper gameDescriptionMapper;
@Autowired
public GameSeacher(GameRepository freeGameRepositoryImpl, GameRepository paidGameRepositoryImpl,
GameRepository grossingGameRepositoryImpl, RestTemplate restTemplate, GameDescriptionMapper gameDescriptionMapper) {
this.freeGameRepositoryImpl = freeGameRepositoryImpl;
this.paidGameRepositoryImpl = paidGameRepositoryImpl;
this.grossingGameRepositoryImpl = grossingGameRepositoryImpl;
this.restTemplate = restTemplate;
this.gameDescriptionMapper = gameDescriptionMapper;
}
private IncomingJsonParserDto getGamesFromLink(String urlAddress) {
return restTemplate.getForObject(urlAddress, IncomingJsonParserDto.class);
}
@Scheduled(fixedDelay = 3600000)
public void findFreeGames() {
List<GameDescriptionDto> freeGames = getGamesFromLink(freeGameLink).getFeed().getResults();
freeGameRepositoryImpl.delete();
freeGameRepositoryImpl.save(gameDescriptionMapper.toEntity(freeGames));
}
@Scheduled(fixedDelay = 3600000)
public void findPaidGames() {
List<GameDescriptionDto> paidGames = getGamesFromLink(paidGameLink).getFeed().getResults();
paidGameRepositoryImpl.delete();
paidGameRepositoryImpl.save(gameDescriptionMapper.toEntity(paidGames));
}
@Scheduled(fixedDelay = 3600000)
public void findGrossingGames() {
List<GameDescriptionDto> grossingGames = getGamesFromLink(grossingGameLink).getFeed().getResults();
grossingGameRepositoryImpl.delete();
grossingGameRepositoryImpl.save(gameDescriptionMapper.toEntity(grossingGames));
}
}
<file_sep>package com.vikfil.games_statistic.mapper;
import com.vikfil.games_statistic.dto.GameDescriptionDto;
import com.vikfil.games_statistic.model.GameDescription;
import org.mapstruct.Mapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Mapper(componentModel = "spring")
@Service
public interface GameDescriptionMapper {
List<GameDescription> toEntity(List<GameDescriptionDto> gamesDescriptionDto);
List<GameDescriptionDto> toDto(List<GameDescription> gamesDescription);
}
<file_sep>package com.vikfil.games_statistic.repository;
import com.vikfil.games_statistic.model.GameDescription;
import java.util.List;
public interface GameRepository {
void save(List<GameDescription> gameDescription);
List<GameDescription> findGamesByLimit(int limit);
List<GameDescription> findAllGames();
void delete();
}
<file_sep>package com.vikfil.games_statistic.repository.impl;
import com.vikfil.games_statistic.model.GameDescription;
import com.vikfil.games_statistic.repository.GameRepository;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class GrossingGameRepositoryImpl implements GameRepository {
private static final String GROSSING_GAME = "GROSSING";
private final RedisTemplate<String, GameDescription> redisTemplate;
public GrossingGameRepositoryImpl(RedisTemplate<String, GameDescription> redisTemplate) {
this.redisTemplate = redisTemplate;
}
@Override
public void save(List<GameDescription> gameDescription) {
redisTemplate.opsForList().rightPushAll(GROSSING_GAME, gameDescription);
}
@Override
public List<GameDescription> findAllGames() {
return redisTemplate.opsForList().range(GROSSING_GAME, 0, -1);
}
@Override
public List<GameDescription> findGamesByLimit(int limit) {
return redisTemplate.opsForList().range(GROSSING_GAME, 0, limit-1);
}
@Override
public void delete() {
redisTemplate.delete(GROSSING_GAME);
}
}
|
944c375d55b5e3ce68043d93ee4f0631c613c060
|
[
"Java",
"INI"
] | 7 |
Java
|
vikfil/games_statistic
|
142ecfb1f5dda768a08573417ca07479da419fd1
|
6ef6f923bf8c5c8af7cb1aa2084222e59fb6780e
|
refs/heads/master
|
<repo_name>sarvjeetrajvansh/image-viewer<file_sep>/src/commons/profilePic/ProfilePic.js
import React, { Component } from "react";
import "./ProfilePic.css";
import {
Avatar,
IconButton,
Menu,
MenuItem,
Typography,
} from "@material-ui/core";
import profile_pic from "../../assets/images/profile_pic.png";
export default class ProfilePic extends Component {
constructor(props) {
super(props);
this.state = {
menuState: false,
anchorEl: null,
loggedOut: this.props.loggedOut,
};
}
onProfileIconClick = (e) => {
this.setState({
menuState: !this.state.menuState,
anchorEl: e.currentTarget,
});
};
onMenuClose = () => {
this.setState({ menuState: !this.state.menuState, anchorEl: null });
};
onLogout = () => {
this.props.onIsLoggedInChanged(false);
sessionStorage.clear();
this.props.history.replace("/");
};
onProfileHandler = () => {
this.props.history.replace("/profile");
};
render() {
return (
<>
<IconButton id="profile-icon" onClick={this.onProfileIconClick}>
<Avatar
alt="profile_picture"
src={this.props.isLoggedIn ? profile_pic : null}
/>
</IconButton>
<div>
<Menu
open={this.state.menuState}
onClose={this.onMenuClose}
anchorEl={this.state.anchorEl}
getContentAnchorEl={null}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
keepMounted
>
{this.props.showMyAccount && (
<MenuItem onClick={this.onProfileHandler}>
<Typography>My Account</Typography>
</MenuItem>
)}
<hr className="horizontal-line" />
<MenuItem onClick={this.onLogout}>
<Typography>Logout</Typography>
</MenuItem>
</Menu>
</div>
</>
);
}
}
<file_sep>/README.md
# Image Viewer App
*ImageViewer is a web application, which allows a user to view his/her own profile and the images posted by the user on his/her Instagram account.*
## Listed below are the different pages and the features inside this web application:
1) **Login Page**
*A user can log in to the application using the ‘access-token’ provided by Instagram*
2) **Home Page**
*After logging in, the user is taken to the home page where he/she can view all the images posted by him/her on his/her own Instagram account
Along with each image posted, the user can view the date on which the image was posted, the caption of the image, the hashtags (if any) posted
with the image, and the number of likes on the image.*
* A user can search for an image based on its caption.
* A user can like an image.
* A user can comment on an image.
* On the home page, when a user clicks on his/her profile picture icon on the header, he/she is taken to the profile page.
3) **Profile Page**
*The user can view the total number of image posts on Instagram along with the number of people he/she follows and the number of people who follow him/her
The user can edit his/her full name.
After clicking on an image on the profile page, the user can view all the information of the picture and perform all the functionalities on it,
which the user could see and perform on the home page.*
<file_sep>/src/commons/posts/Posts.js
import React, { Component } from "react";
import { Redirect } from "react-router";
import Post from "../post/Post";
import "./Posts.css";
import Grid from "@material-ui/core/Grid";
export default class Posts extends Component {
onImageTransfer = (imageId) => {
return this.props.cb(imageId);
};
render() {
if (
sessionStorage.getItem("access-token") === undefined ||
this.props.isLoggedIn === false
) {
return <Redirect to={{ pathname: "/" }} />;
}
return (
<>
<Grid container spacing={3}>
{(this.props.totalPosts || []).map((post, index) => (
<Grid item xl={6} lg={6} md={6} xs={4} sm={3} key={"post#" + index}>
<Post
post={post}
cb={this.props.cb}
count={index}
containerId={"post#" + index}
/>
</Grid>
))}
</Grid>
</>
);
}
}
<file_sep>/src/commons/header/Header.js
import React, { Component } from "react";
import "./Header.css";
import SearchBox from "../searchBox/SearchBox";
import ProfilePic from "../profilePic/ProfilePic";
class Header extends Component {
onLoginChange = (newStatus) => {
this.props.onIsLoggedInChanged(newStatus);
};
onFilterPosts = (updatedPosts) => {
this.props.onfilterPostsChange(updatedPosts);
};
logoHandler = () => {
this.props.history.push("/home");
};
render() {
return (
<header className="app-header">
{sessionStorage.getItem("access-token") &&
this.props.isLoggedIn === true ? (
<>
<div
className="logo"
style={
this.props.isProfilePage === true ? { cursor: "pointer" } : null
}
onClick={
this.props.isProfilePage === true ? this.logoHandler : null
}
>
<span className="header-logo-text">Image Viewer</span>
</div>
<div style={{ float: "right", display: "inline" }}>
{this.props.showSearchBox && (
<SearchBox
{...this.props}
allPosts={this.props.allPosts}
onfilterPostsChange={this.onFilterPosts}
/>
)}
<ProfilePic
{...this.props}
showMyAccount={this.props.showSearchBox}
onIsLoggedInChanged={this.onLoginChange}
/>
</div>
</>
) : (
<div className="logo">
<span className="header-logo-text">Image Viewer</span>
</div>
)}
</header>
);
}
}
export default Header;
<file_sep>/src/screens/controller/Controller.js
import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "../home/Home";
import Login from "../../screens/login/Login";
import Profile from "../profile/Profile";
export default class Controller extends Component {
constructor() {
super();
this.state = {
baseUrl: "https://graph.instagram.com/",
isLoggedIn: sessionStorage.getItem("access-token") ? true : false,
};
}
onLoginChange = (newStatus) => {
this.setState({ isLoggedIn: newStatus }, () => {});
};
render() {
return (
<Router>
<Route
exact
path="/"
render={(props) => (
<Login
{...props}
baseUrl={this.state.baseUrl}
isLoggedIn={this.state.isLoggedIn}
onIsLoggedInChanged={this.onLoginChange}
/>
)}
/>
<Route
exact
path="/home"
render={(props) => (
<Home
{...props}
baseUrl={this.state.baseUrl}
isLoggedIn={this.state.isLoggedIn}
onIsLoggedInChanged={this.onLoginChange}
/>
)}
/>
<Route
exact
path="/profile"
render={(props) => (
<Profile
{...props}
baseUrl={this.state.baseUrl}
isLoggedIn={this.state.isLoggedIn}
onIsLoggedInChanged={this.onLoginChange}
/>
)}
/>
</Router>
);
}
}
<file_sep>/src/commons/searchBox/SearchBox.js
import React, { Component } from "react";
import SearchIcon from "@material-ui/icons/Search";
import { Input, InputAdornment } from "@material-ui/core";
import "./SearchBox.css";
export default class SearchBox extends Component {
constructor(props) {
super(props);
this.state = {
searchText: "",
};
}
onSearch = async (e) => {
await this.setState({ searchText: e.target.value });
if (this.state.searchText.trim() === "" || this.state.searchText === null) {
this.setState({ filtered_post: this.props.allPosts });
this.props.onfilterPostsChange(this.props.allPosts);
} else {
let that = this;
let filteredPosts = that.props.allPosts.filter(function (post) {
if (post.caption === undefined) {
return false;
}
return post.caption
.toUpperCase()
.includes(that.state.searchText.toUpperCase());
});
// console.log("--->");
//console.log("--->", filteredPosts);
this.setState({ filtered_post: filteredPosts });
this.props.onfilterPostsChange(filteredPosts);
}
};
componentDidMount() {
this.setState({ filtered_post: this.props.allPosts });
}
render() {
return (
<div className="header-right-flex-container">
{this.props.showSearchBox ? (
<Input
className="search-box"
type="search"
placeholder="Search..."
disableUnderline
startAdornment={
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
}
onChange={this.onSearch}
/>
) : null}
</div>
);
}
}
<file_sep>/src/screens/home/Home.js
import React, { Component } from "react";
import "./Home.css";
import Header from "../../commons/header/Header";
import { Redirect } from "react-router";
import Posts from "../../commons/posts/Posts";
import profile_pic from "../../assets/images/profile_pic.png";
export default class Home extends Component {
constructor() {
super();
this.state = {
allPosts: null,
filterPosts: null,
profilePic: profile_pic,
};
}
componentDidMount() {
if (!this.props.filterPosts) {
this.fetchAllPosts();
}
}
onLoginChange = (newStatus) => {
this.setState({ isLoggedIn: newStatus }, () => {});
};
onFilterPosts = (updatedPosts) => {
// console.log("######");
//console.log("onFilterPosts", this.state.filterPosts, updatedPosts);
setTimeout(() => {
this.setState({ filterPosts: updatedPosts });
}, 500);
// console.log("!!!!");
// console.log(this.state.filterPosts);
};
fetchAllPosts = () => {
let data = null;
let xhr = new XMLHttpRequest();
let that = this;
let url = `${
that.props.baseUrl
}me/media?fields=id,caption&access_token=${sessionStorage.getItem(
"access-token"
)}`;
xhr.open("GET", url);
xhr.send(data);
xhr.addEventListener("readystatechange", async function () {
if (this.readyState === 4) {
that.setState({
allPosts: JSON.parse(this.responseText).data,
filterPosts: JSON.parse(this.responseText).data,
});
}
});
};
getImageData = (imageData) => {
let post = {};
let that = this;
let imageID = imageData.id.replace(/['"]+/g, "");
let url = `${
that.props.baseUrl
}${imageID}?fields=id,media_type,media_url,username,timestamp&access_token=${sessionStorage.getItem(
"access-token"
)}`;
const xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4 && this.status === 200) {
let parsedData = JSON.parse(this.responseText);
post.id = parsedData.id;
post.media_type = parsedData.media_type;
post.media_url = parsedData.media_url;
post.profilePic = that.state.profilePic;
post.username = parsedData.username;
post.likeIcon = "dispBlock";
post.likedIcon = "dispNone";
post.likesCount = Math.floor(Math.random() * 10);
post.clear = "";
if (imageData.caption !== undefined) {
post.caption = imageData.caption || "This is default caption";
post.tags = post.caption.match(/#\S+/g);
}
post.commentContent = [];
post.timestamp = new Date(parsedData.timestamp);
}
});
xhr.open("GET", url, true);
xhr.send();
return post;
};
render() {
if (this.props.isLoggedIn === false) {
return <Redirect to="/" />;
}
if (this.props.isLoggedIn === true) {
return (
<>
<div>
<Header
isLoggedIn={this.props.isLoggedIn}
allPosts={this.state.allPosts}
showSearchBox={true}
onIsLoggedInChanged={this.onLoginChange}
onfilterPostsChange={this.onFilterPosts}
{...this.props}
/>
</div>
<>
<Posts
totalPosts={this.state.filterPosts}
{...this.props}
cb={this.getImageData}
key={123}
/>
</>
</>
);
}
}
}
|
13d2c4739613bb20763a10c044f5baa56833b3c0
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
sarvjeetrajvansh/image-viewer
|
e2c1a4bdd29508273be837b9f51b85611a644e9e
|
5c5ab3eafba840961a0902fd383917ac14582d77
|
refs/heads/master
|
<repo_name>mattldawson/music_box_interactive<file_sep>/dashboard/views.py
from django.shortcuts import render
def run_model(request):
context = {}
return render(request, 'dashboard/run_model.html', context)
def species(request):
context = {}
return render(request, 'dashboard/species.html', context)
def reactions(request):
context = {}
return render(request, 'dashboard/reactions.html', context)
def visualize(request):
context = {}
return render(request, 'dashboard/visualize.html', context)
<file_sep>/dashboard/static/dashboard/js/navigate.js
/**
* Navigation functions
*/
function navSetLinks() {
$('.nav-links').on('click', '.link-run-model', function() {
location.href="run_model"
});
$('.nav-links').on('click', '.link-species', function() {
location.href="species"
});
$('.nav-links').on('click', '.link-reactions', function() {
location.href="reactions"
});
$('.nav-links').on('click', '.link-visualize', function() {
location.href="visualize"
});
$('.nav-links').on('click', '.link-download', function() {
location.href="model_driver/download"
});
}
function updateNavStatus() {
$.ajax({
url: 'model_driver/check_status',
type: 'get',
success: function(response) {
if (response.status == "done") {
if (!$('.link-visualize').length) {
$(".nav-links").append(`
<li class="nav-item px-1.5"><a class="nav-link p-2 link-visualize" href="#"><span
class="oi oi-graph" toggle="tooltip" title="visualize the results"></span></a></li>`);
}
if (!$('.link-download').length) {
$(".nav-links").append(`
<li class="nav-item px-1.5"><a class="nav-link p-2 link-download" href="#"><span
class="oi oi-data-transfer-download" toggle="tooltip" title="download the results"></span></a></li>`);
}
} else {
$('.link-visualize').remove();
$('.link-download').remove();
}
}
});
}
<file_sep>/model_driver/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('run', views.run, name='run'),
path('check_status', views.check_status, name="check_status"),
path('mechanism_data', views.mechanism_data, name="mechanism_data"),
path('download', views.download, name="download"),
]
<file_sep>/dashboard/static/dashboard/js/reaction.js
function deepEqual(a, b) {
return JSON.stringify(a) == JSON.stringify(b);
}
// Id without the count at the end
function rawId(reaction) {
if(reaction.reactants.length == 0){
id = "None";
} else {
id = reaction.reactants.sort().join("_");
}
if (reaction.reactionBranch) {
id += "_" + reaction.reactionBranch;
}
if (reaction.troe) {
id += "_M";
}
return id;
}
function reactionId(reaction, reactions) {
var id = rawId(reaction);
var count = 1;
for (r in reactions) {
if (deepEqual(reactions[r], reaction)) break;
if (rawId(reactions[r]) == id) count++;
}
id += "_" + count;
return id;
}
function reactionName(type, reaction, reactions) {
var name = '';
for (key in reactions) {
if (deepEqual(reaction, reactions[key])) {
for (react_key in reaction.reactants) {
if (react_key == 0) {
name += reaction.reactants[react_key];
} else {
name += ' + ' + reaction.reactants[react_key];
}
}
if (type == 'photolysis') name += ' + hv';
name += ' -> ';
for (prod_key in reaction.products) {
if (prod_key == 0) {
if (reaction.products[prod_key].coefficient == 1) {
name += reaction.products[prod_key].molecule;
} else {
name += reaction.products[prod_key].coefficient + reaction.products[prod_key].molecule;
}
} else {
if (reaction.products[prod_key].coefficient == 1) {
name += ' + ' + reaction.products[prod_key].molecule;
} else {
name += ' + ' + reaction.products[prod_key].coefficient + reaction.products[prod_key].molecule;
}
}
}
break;
}
}
return name;
}
<file_sep>/dashboard/urls.py
from django.urls import path
from . import views
app_name = 'dashboard'
urlpatterns = [
path('', views.run_model, name='run_model'),
path('run_model', views.run_model, name='run_model'),
path('species', views.species, name='species'),
path('reactions', views.reactions, name='reactions'),
path('visualize', views.visualize, name='visualize'),
]
<file_sep>/README.md
# music_box_interactive
Configure and run MusicBox and visualize results in a browser
<file_sep>/model_driver/views.py
from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
import json
import os.path
import subprocess
def run(request):
mb_dir = os.path.join(os.environ['MUSIC_BOX_BUILD_DIR'])
outfile_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "MusicBox_output.nc")
running_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "MODEL_RUNNING")
done_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "MODEL_RUN_COMPLETE")
if os.path.isfile(outfile_path):
os.remove(outfile_path)
if os.path.isfile(running_path):
os.remove(running_path)
if os.path.isfile(done_path):
os.remove(done_path)
process = subprocess.Popen(r'./MusicBox', cwd=mb_dir)
return JsonResponse({ "status" : "started"})
def check_status(request):
running_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "MODEL_RUNNING")
done_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "MODEL_RUN_COMPLETE")
if os.path.isfile(done_path):
return JsonResponse({ "status" : "done" })
if os.path.isfile(running_path):
return JsonResponse({ "status" : "running" })
return JsonResponse({ "status" : "not started" })
def mechanism_data(request):
mechanism_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "molec_info.json")
mech_json = json.load(open(mechanism_path, 'r'))
return JsonResponse(mech_json)
def download(request):
outfile_path = os.path.join(os.environ['MUSIC_BOX_OUTPUT_DIR'], "MusicBox_output.nc")
if os.path.isfile(outfile_path):
with open(outfile_path, 'rb') as outfile:
response = HttpResponse(outfile.read(), content_type="application/x-netcdf")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(outfile_path)
return response
return HttpResponseBadRequest('Missing output file', status=405)
|
20d991e89d9afa982948e1e8362d4018608e1d46
|
[
"JavaScript",
"Python",
"Markdown"
] | 7 |
Python
|
mattldawson/music_box_interactive
|
80630af83bcaddc940167777befb185592d57937
|
67b99ac715f06b2278667cabee656d32685d5c2a
|
refs/heads/master
|
<repo_name>daybrush/knt-ws<file_sep>/src/WServer.h
//
// WServer.hpp
// myKinectStart
//
// Created by next on 2016. 6. 21..
//
//
#pragma once
#include <stdio.h>
#include "ofxLibwebsockets.h"
class WServer : public ofBaseApp{
public:
//server
ofxLibwebsockets::Server server;
ofTrueTypeFont font;
vector<string> messages;
string toLoad;
bool bSendImage;
ofImage currentImage;
void serverInit();
// websocket methods
void onConnect( ofxLibwebsockets::Event& args );
void onOpen( ofxLibwebsockets::Event& args );
void onClose( ofxLibwebsockets::Event& args );
void onIdle( ofxLibwebsockets::Event& args );
void onMessage( ofxLibwebsockets::Event& args );
void onBroadcast( ofxLibwebsockets::Event& args );
void sendMessage(string t);
void update();
};<file_sep>/src/WServer.cpp
//
// WServer.cpp
// myKinectStart
//
// Created by next on 2016. 6. 21..
//
//
#include "WServer.h"
void WServer::serverInit() {
ofxLibwebsockets::ServerOptions options = ofxLibwebsockets::defaultServerOptions();
options.port = 9093;
bool connected = server.setup( options );
// this adds your app as a listener for the server
server.addListener(this);
// setup message queue
font.load("myriad.ttf", 20);
messages.push_back("WebSocket server setup at "+ofToString( server.getPort() ) + ( server.usingSSL() ? " with SSL" : " without SSL") );
ofBackground(0);
ofSetFrameRate(60);
bSendImage = false;
}
void WServer::onConnect( ofxLibwebsockets::Event& args ){
cout<<"on connected"<<endl;
}
void WServer::update(){
cout<< "update" << endl;
}
//--------------------------------------------------------------
void WServer::onOpen( ofxLibwebsockets::Event& args ){
cout<<"new connection open"<<endl;
messages.push_back("New connection from " + args.conn.getClientIP() );
// send the latest image if there is one!
if ( currentImage.bAllocated() ){
args.conn.send( ofToString(currentImage.getWidth()) +":"+ ofToString( currentImage.getHeight() ) +":"+ ofToString( currentImage.getImageType() ) );
args.conn.sendBinary( currentImage );
}
}
//--------------------------------------------------------------
void WServer::onClose( ofxLibwebsockets::Event& args ){
cout<<"on close"<<endl;
messages.push_back("Connection closed");
}
//--------------------------------------------------------------
void WServer::onIdle( ofxLibwebsockets::Event& args ){
cout<<"on idle"<<endl;
}
//--------------------------------------------------------------
void WServer::onMessage( ofxLibwebsockets::Event& args ){
cout<<"got message "<<args.message<<endl;
// trace out string messages or JSON messages!
// args.json is null if badly formed or just not JOSN
if ( !args.json.isNull() ){
messages.push_back("New message: " + args.json.toStyledString() + " from " + args.conn.getClientName() );
} else {
messages.push_back("New message: " + args.message + " from " + args.conn.getClientName() );
}
//if (messages.size() > NUM_MESSAGES) messages.erase( messages.begin() );
// echo server = send message right back!
args.conn.send( args.message );
}
//--------------------------------------------------------------
void WServer::onBroadcast( ofxLibwebsockets::Event& args ){
cout<<"got broadcast "<<args.message<<endl;
}
void WServer::sendMessage(string t) {
server.send(t);
}
<file_sep>/ofApp.h
#pragma once
#include "ofxOpenNI.h"
#include "ofMain.h"
#include "WServer.h"
#define NUM_MESSAGES 20 // how many past messages we want to keep
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
string JointToString(string name, ofxOpenNIJoint &joint);
void userEvent(ofxOpenNIUserEvent & event);
void serverInit();
ofxOpenNI openNIDevice;
ofTrueTypeFont verdana;
private:
WServer server;
};
<file_sep>/ofApp.cpp
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
serverInit();
// ofSetLogLevel(OF_LOG_VERBOSE);
openNIDevice.setup();
openNIDevice.addImageGenerator();
openNIDevice.addDepthGenerator();
openNIDevice.setRegister(true);
openNIDevice.setMirror(true);
openNIDevice.addUserGenerator();
openNIDevice.setMaxNumUsers(2);
openNIDevice.start();
// set properties for all user masks and point clouds
//openNIDevice.setUseMaskPixelsAllUsers(true); // if you just want pixels, use this set to true
openNIDevice.setUseMaskTextureAllUsers(true); // this turns on mask pixels internally AND creates mask textures efficiently
openNIDevice.setUsePointCloudsAllUsers(true);
openNIDevice.setPointCloudDrawSizeAllUsers(2); // size of each 'point' in the point cloud
openNIDevice.setPointCloudResolutionAllUsers(2); // resolution of the mesh created for the point cloud eg., this will use every second depth pixel
verdana.loadFont(ofToDataPath("verdana.ttf"), 24);
}
//--------------------------------------------------------------
void ofApp::update(){
openNIDevice.update();
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSetColor(255, 255, 255);
ofPushMatrix();
// // draw debug (ie., image, depth, skeleton)
openNIDevice.drawDebug();
ofPopMatrix();
//
// ofPushMatrix();
// use a blend mode so we can see 'through' the mask(s)
// ofEnableBlendMode(OF_BLENDMODE_ALPHA);
// get number of current users
int numUsers = openNIDevice.getNumTrackedUsers();
string msg = "";
// iterate through users
ofxOpenNIJoint head, leftHand, rightHand;
for (int i = 0; i < numUsers; i++){
msg += "p" +ofToString(i) + "=";
// get a reference to this user
ofxOpenNIUser & user = openNIDevice.getTrackedUser(i);
user.drawMask();
// you can also access the mesh:
// MESH REFERENCE
//ofMesh & mesh = user.getPointCloud();
// do something with the point cloud mesh
ofPopMatrix();
ofxOpenNIJoint head = user.getJoint(JOINT_HEAD);
ofxOpenNIJoint neck = user.getJoint(JOINT_NECK);
ofxOpenNIJoint leftElbow = user.getJoint(JOINT_LEFT_ELBOW);
ofxOpenNIJoint rightElbow = user.getJoint(JOINT_RIGHT_ELBOW);
ofxOpenNIJoint leftHand = user.getJoint(JOINT_LEFT_HAND);
ofxOpenNIJoint rightHand = user.getJoint(JOINT_RIGHT_HAND);
ofxOpenNIJoint leftKnee = user.getJoint(JOINT_LEFT_KNEE);
ofxOpenNIJoint rightKnee = user.getJoint(JOINT_RIGHT_KNEE);
ofxOpenNIJoint leftFoot = user.getJoint(JOINT_LEFT_FOOT);
ofxOpenNIJoint rightFoot = user.getJoint(JOINT_RIGHT_FOOT);
ofxOpenNIJoint spine = user.getJoint(JOINT_TORSO);
ofxOpenNIJoint leftShoulder = user.getJoint(JOINT_LEFT_SHOULDER);
ofxOpenNIJoint rightShoulder = user.getJoint(JOINT_RIGHT_SHOULDER);
ofPoint leftHandPos = leftHand.getProjectivePosition();
ofPoint rightHandPos = rightHand.getProjectivePosition();
msg += JointToString("he", head);
msg += JointToString("ne", neck);
msg += JointToString("le", leftElbow);
msg += JointToString("re", rightElbow);
msg += JointToString("lh", leftHand);
msg += JointToString("rh", rightHand);
msg += JointToString("lk", leftKnee);
msg += JointToString("rk", rightKnee);
msg += JointToString("sp", spine);
msg += JointToString("lf", leftFoot);
msg += JointToString("rf", rightFoot);
msg += JointToString("ls", rightFoot);
msg += JointToString("rs", rightFoot);
msg+= "\n";
}
server.sendMessage(msg);
ofDisableBlendMode();
ofPopMatrix();
// draw some info regarding frame counts etc
ofSetColor(0, 255, 0);
msg += " MILLIS: " + ofToString(ofGetElapsedTimeMillis()) + " FPS: " + ofToString(ofGetFrameRate()) + " Device FPS: " + ofToString(openNIDevice.getFrameRate());
verdana.drawString(msg, 20, openNIDevice.getNumDevices() * 480 - 20);
}
string ofApp::JointToString(string name, ofxOpenNIJoint &joint) {
ofPoint pos = joint.getProjectivePosition();
return name + ":" + ofToString(pos.x) +"|"+ ofToString(pos.y) + "|"+ ofToString(pos.z) +",";
}
//--------------------------------------------------------------
void ofApp::userEvent(ofxOpenNIUserEvent & event){
// show user event messages in the console
ofLogNotice() << getUserStatusAsString(event.userStatus) << "for user" << event.id << "from device" << event.deviceID;
}
//--------------------------------------------------------------
void ofApp::exit(){
openNIDevice.stop();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
//// server
void ofApp::serverInit() {
server.serverInit();
}
|
c62a092e9b1338be9f23551022a0506b6a7dc425
|
[
"C++"
] | 4 |
C++
|
daybrush/knt-ws
|
4b6030ea519ba410994c699303ba1815619063f7
|
bf5b082582e5345adbac5b707da9b64028d4795a
|
refs/heads/master
|
<repo_name>briquebalant/webcv2.0<file_sep>/README.md
http://briquebalant.github.io/webcv2.0
=======================
### WEB CV 2.3
fais en pur HTML5 / CSS3
+
Une petit de JS pour la forme
**Ne pas tenir** compte du contenu __!__
--> [Web CV - V.3.3](http://www.fuentesloic.com)
*réalisé en boostrap pour tester*
# A récupérer :
1. Header Sub-menu
2. HTML5
3. Template sympa
<file_sep>/main.js
var link = document.querySelector(".menu");
link.onclick = function (evt) {
evt.preventDefault();
var navnone = document.querySelector(".navnone");
var navblock = document.querySelector(".navblock");
if (navnone) {
navnone.className = "navblock";
}
else if (navblock) {
navblock.className = "navnone";
}
}
var butt = document.querySelector("#buttonarchive");
butt.onclick = function (evt) {
evt.preventDefault();
var invisibles = document.querySelectorAll(".invisible"); //j'indique que la variable invisibles pointe TOUTE la class invisible
var visibles = document.querySelectorAll(".visible"); //j'indique que la variable livisibles pointe TOUTE la class visible
[].map.call(invisibles, function(item) {
item.className = "visible"; //si la variable invisible alors classname devient visible
});
[].map.call(visibles, function(item) {
item.className = "invisible"; //si la variable invisible alors classname devient livisible
});
console.log(invisibles) // test
console.log(visibles) // test
}
|
82caeabad6244dc4dad56eebbf8b6dca765134cf
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
briquebalant/webcv2.0
|
26d6dc69044b4c32bc8a04df02e5d42ea6ecf850
|
c701b89d9305d8cce88b168bfdfe38e9e402faf8
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
const slides = [
{
url:'/img/Janna.png',
title:'Ma premiere image'
},
{
url:'/img/Akali.png',
title:'Ma deuxieme image'
},
{
url:'/img/Jinx.png',
title:'Ma troisieme image'
},
{
url:'/img/Kata.png',
title:'Ma quatrieme image'
},{
url:'/img/Mf.png',
title:'Ma premiere image'
},
{
url:'/img/Ahri.png',
title:'Ma deuxieme image'
},{
url:'/img/Janna.png',
title:'Ma premiere image'
},
{
url:'/img/Akali.png',
title:'Ma deuxieme image'
},
{
url:'/img/Jinx.png',
title:'Ma troisieme image'
},
{
url:'/img/Kata.png',
title:'Ma quatrieme image'
},{
url:'/img/Mf.png',
title:'Ma premiere image'
},
{
url:'/img/Ahri.png',
title:'Ma deuxieme image'
},{
url:'/img/Janna.png',
title:'Ma premiere image'
},
{
url:'/img/Akali.png',
title:'Ma deuxieme image'
},
{
url:'/img/Jinx.png',
title:'Ma troisieme image'
},
{
url:'/img/Kata.png',
title:'Ma quatrieme image'
},{
url:'/img/Mf.png',
title:'Ma premiere image'
},
{
url:'/img/Ahri.png',
title:'Ma deuxieme image'
},{
url:'/img/Janna.png',
title:'Ma premiere image'
},
{
url:'/img/Akali.png',
title:'Ma deuxieme image'
},
{
url:'/img/Jinx.png',
title:'Ma troisieme image'
},
{
url:'/img/Kata.png',
title:'Ma quatrieme image'
},{
url:'/img/Mf.png',
title:'Ma premiere image'
},
{
url:'/img/Ahri.png',
title:'Ma deuxieme image'
}
]
class App extends Component {
state = {
position: 0 //position de l'image
}
nextSlide = () => {
if (this.state.position >= 6) {
this.setState({position:0})
}
else {
this.setState({position: ++this.state.position})
}
}
prevSlide = () => {
if (this.state.position <=0) {
this.setState({position:6})
}
else {
this.setState({position: --this.state.position})
}
}
render() {
let newMargin = this.state.position * Math.floor(Math.random() * 4)* -300; //position x largeur image
let newMargin2 = this.state.position * Math.floor(Math.random() * 5)* -300; //position x largeur image
let newMargin3 = this.state.position * Math.floor(Math.random() * 3)* -300; //position x largeur image
return (
<div className="allCont">
<div className="App">
<div className="container">
<ul style={{marginLeft:newMargin}}>
{slides.map(content =>
<li>
<img src={content.url}/>
</li>
)}
</ul>
</div>
<div className="container">
<ul style={{marginLeft:newMargin2}}>
{slides.map(content =>
<li>
<img src={content.url}/>
</li>
)}
</ul>
</div>
<div className="container">
<ul style={{marginLeft:newMargin3}}>
{slides.map(content =>
<li>
<img src={content.url}/>
</li>
)}
</ul>
</div>
<div className="cont">
<div className="cModal" id="modal1">
<div className="Tab">
</div>
</div>
<div className="cModal" id="modal1">
<a href="#modal1" className="navi" ><i className="fa fa-bars" aria-hidden="true"></i></a>
<a className="cross" href="#modal1">push</a>
<div className="Tab2">
</div>
</div>
</div>
{/* double fonction pour eviter que la premiere ne se lance auto */}
</div>
<button onClick={()=>this.nextSlide()}> → </button>
</div>
);
}
}
export default App;
<file_sep># Lol & Hos Cards random Project
### About this:
* Click to open and push button to view your results.

|
e77f3ad8c1c3c20cf5093cd04ae7d00e44e14219
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
Hexya/React-Carrousel
|
7fa9c2a26195cdbdf9a5f04d6f2c5f4bf417bb75
|
91e1e9f803fb49cd282bdda584e849efdda112e2
|
refs/heads/master
|
<repo_name>pau1m/crypto-tools<file_sep>/ctools/src/client/App.js
import React, { Component } from 'react'
import './app.css'
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
posts: [
// {
// id: 0,
// title: 'none'
// }
],
}
}
componentDidMount() {
// fetch('https://jsonplaceholder.typicode.com/posts')
fetch('http://localhost:1338/posts')
.then(res => res.json())
.then(posts => this.setState({
posts: posts
}))
}
render() {
const listItems = this.state.posts.map( (item) => <li>{item.title}</li>)
return (
<>
{this.state.posts[0] ? (
<ol>
{ listItems }
</ol>
) : (
<h1>Loading</h1>
)}
</>
)
}
}
<file_sep>/readme.md
# Crypto Tools
React app with facade api for interrogating crypto stuff.
|
e42b7f285a66bdf457687a10cbba3f04276b9d81
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
pau1m/crypto-tools
|
e744fad527afa5ecbc5305f5ee359860c803eb4a
|
110eaec5ffdc1a1f1b9b1ce7e8c93a8e69187896
|
refs/heads/master
|
<repo_name>Kambizzzz/Trello-Self-Project<file_sep>/js/helper.js
//JS dock
/**
* @returns {HTMLElement}
* @param {String} tagname
* @param {Object} attribute
* @param {HTMLElement / Array / String} content
* @returns
*/
function createElement(tagname, attribute, content){
var el = document.createElement(tagname)
for (var key in attribute){
el.setAttribute(key, attribute[key]);
}
if (typeof content !== 'undefined') {
if (content instanceof HTMLElement) {
el.appendChild(content);
} else{
el.innerText = content;
}
}
return el;
}
<file_sep>/js/color.js
// For toggle button;
function toggleClass() {
const body = document.querySelector('body');
body.classList.toggle('light');
body.style.transition = `0.3s linear`;
}
<file_sep>/js/app.js
var boards = document.querySelector('.boards');
boards.appendChild(createAddListCTA())
var movie = document.getElementById('movie');
console.log(movie)
movie.addEventListener('click' , function(){
var newlist = createListColumn('Movies to watch!');
var insertionPosition = document.getElementById('add-list');
insertionPosition.before(newlist);
});
var book = document.getElementById('book');
console.log(book)
book.addEventListener('click' , function(){
var newlist = createListColumn('Books to read!');
var insertionPosition = document.getElementById('add-list');
insertionPosition.before(newlist);
});
|
f8d42f86ee0cf19907e2d4962b9d54041631eaad
|
[
"JavaScript"
] | 3 |
JavaScript
|
Kambizzzz/Trello-Self-Project
|
aa2fe095380883498ab83e3b0d5d9e665f55da59
|
4287647f84376cbc288eb60645fe19d8be57319c
|
refs/heads/master
|
<repo_name>0x012f5b7d/tun43g214<file_sep>/projects/008_time/USER/main.c
#include "stm32f10x.h"
void Delay(u32 count)
{
u32 i=0;
for(;i<count;i++);
}
void time_init()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_DeInit(TIM3);
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period = 4999; // 1 second 2 interrupt
TIM_TimeBaseInitStruct.TIM_Prescaler = 7199;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
}
void nvic_init()
{
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStruct.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStruct);
}
void TIM3_IRQHandler()
{
if(TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
//led control here!!!s
}
}
int main(void)
{
GPIO_InitTypeDef GPIO_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD, ENABLE);
GPIO_InitType.GPIO_Pin = GPIO_Pin_8; //LED0:PA8
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitType);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_InitType.GPIO_Pin = GPIO_Pin_2; //LED1:PD2
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitType);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
//add clock init here!!!!!!!!!
time_init();
nvic_init();
TIM_Cmd(TIM3, ENABLE);
while(1);
}
<file_sep>/Standard Lib版本/实验4 外部中断实验/USER/main.c
#include "led.h"
#include "delay.h"
#include "sys.h"
#include "key.h"
#include "usart.h"
#include "exti.h"
//ALIENTEK Mini STM32开发板范例代码4
//外部中断实验
//技术支持:www.openedv.com
//广州市星翼电子科技有限公司
int main(void)
{
delay_init(); //延时函数初始化
NVIC_Configuration();// 设置中断优先级分组
uart_init(9600); //串口初始化为9600
LED_Init(); //初始化与LED连接的硬件接口
EXTIX_Init(); //外部中断初始化
LED0=0; //点亮LED
while(1)
{
printf("OK\n");
delay_ms(1000);
}
}
<file_sep>/Standard Lib版本/实验9 输入捕获实验/HARDWARE/TIMER/timer.h
#ifndef __TIMER_H
#define __TIMER_H
#include "sys.h"
void TIM1_PWM_Init(u16 arr,u16 psc);
void TIM2_Cap_Init(u16 arr,u16 psc);
#endif
<file_sep>/Standard Lib版本/实验5 独立看门狗实验/USER/main.c
#include "led.h"
#include "delay.h"
#include "sys.h"
#include "key.h"
#include "usart.h"
#include "iwdg.h"
//ALIENTEK Mini STM32开发板范例代码5
//独立看门狗实验
//技术支持:www.openedv.com
//广州市星翼电子科技有限公司
int main(void)
{
delay_init(); //延时函数初始化
NVIC_Configuration(); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级
uart_init(9600); //串口初始化为9600
LED_Init(); //初始化与LED连接的硬件接口
KEY_Init(); //按键初始化
delay_ms(300); //让人看得到灭
IWDG_Init(4,625); //与分频数为64,重载值为625,溢出时间为1s
LED0=0; //点亮LED0
while(1)
{
if(KEY_Scan(0)==WKUP_PRES)IWDG_Feed();//如果WK_UP按下,则喂狗
delay_ms(10);
};
}
<file_sep>/Standard Lib版本/实验38 综合测试实验/APP/common.h
#ifndef __COMMON_H
#define __COMMON_H
#include "sys.h"
#include "usart.h"
#include "delay.h"
#include "led.h"
#include "key.h"
#include "wdg.h"
#include "timer.h"
#include "lcd.h"
#include "usmart.h"
#include "rtc.h"
#include "wkup.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "24cxx.h"
#include "flash.h"
#include "touch.h"
#include "24l01.h"
#include "remote.h"
#include "ds18b20.h"
#include "ps2.h"
#include "mouse.h"
#include "stmflash.h"
#include "malloc.h"
#include "string.h"
#include "mmc_sd.h"
#include "ff.h"
#include "exfuns.h"
#include "fontupd.h"
#include "text.h"
#include "piclib.h"
#include "t9input.h"
#include "includes.h"
#include "ff.h"
#include "piclib.h"
#include "gui.h"
//////////////////////////////////////////////////////////////////////////////////
//本程序只供学习使用,未经作者许可,不得用于其它任何用途
//ALIENTEK STM32开发板
//APP通用 代码
//正点原子@ALIENTEK
//技术论坛:www.openedv.com
//修改日期:2014/2/16
//版本:V1.1
//版权所有,盗版必究。
//Copyright(C) 广州市星翼电子科技有限公司 2009-2019
//All rights reserved
//*******************************************************************************
//V1.1 20140216
//新增对各种分辨率LCD的支持.
//////////////////////////////////////////////////////////////////////////////////
//硬件平台软硬件版本定义
#define HARDWARE_VERSION 30 //硬件版本,放大10倍,如1.0表示为10
#define SOFTWARE_VERSION 230 //软件版本,放大100倍,如1.00,表示为100
//硬件V3.0
//1,采用STM32F103RCT6作为主控
//2,采用CH340G作为USB转串口芯片
//3,修改JTAG SWD的两个IO口被占用,从而影响仿真的问题.
//4,采用W25Q64作为外部FLASH存储器
//5,更改部分外设的连接方式.
//6,去掉JF24C的预留位置
//系统数据保存基址
#define SYSTEM_PARA_SAVE_BASE 100 //系统信息保存首地址.从100开始.
extern volatile u8 system_task_return;
////////////////////////////////////////////////////////////////////////////////////////////
//各图标/图片路径
extern const u8* APP_OK_PIC; //确认图标
extern const u8* APP_CANCEL_PIC; //取消图标
extern const u8* APP_UNSELECT_PIC; //未选中图标
extern const u8* APP_SELECT_PIC; //选中图标
extern const u8* APP_ASCII_60; //大数字字体路径
extern const u8* APP_ASCII_28; //大数字字体路径
extern const u8* APP_VOL_PIC; //音量图片路径
extern const u8 APP_ALIENTEK_ICO[72]; //启动界面图标,存放在flash
////////////////////////////////////////////////////////////////////////////////////////////
//APP的总功能数目
#define APP_FUNS_NUM 9
//app主要功能界面标题
extern const u8* APP_MFUNS_CAPTION_TBL[APP_FUNS_NUM][GUI_LANGUAGE_NUM];
extern const u8* APP_MODESEL_CAPTION_TBL[GUI_LANGUAGE_NUM];
extern const u8* APP_REMIND_CAPTION_TBL[GUI_LANGUAGE_NUM];
extern const u8* APP_SAVE_CAPTION_TBL[GUI_LANGUAGE_NUM];
extern const u8* APP_CREAT_ERR_MSG_TBL[GUI_LANGUAGE_NUM];
//平滑线的起止颜色定义
#define WIN_SMOOTH_LINE_SEC 0XB1FFC4 //起止颜色
#define WIN_SMOOTH_LINE_MC 0X1600B1 //中间颜色
//弹出窗口选择条目的设置信息
#define APP_ITEM_BTN1_WIDTH 60 //有2个按键时的宽度
#define APP_ITEM_BTN2_WIDTH 100 //只有1个按键时的宽度
#define APP_ITEM_BTN_HEIGHT 30 //按键高度
#define APP_ITEM_ICO_SIZE 32 //ICO图标的尺寸
#define APP_ITEM_SEL_BKCOLOR 0X0EC3 //选择时的背景色
#define APP_WIN_BACK_COLOR 0XC618 //窗体背景色
#define APP_FB_TOPBAR_HEIGHT 20 //文件浏览界面,顶部横条的高度
#define APP_FB_BTMBAR_HEIGHT 20 //文件浏览界面/测试界面,底部横条的高度
#define APP_TEST_TOPBAR_HEIGHT 20 //测试界面,顶部横条高度
/////////////////////////////////////////////////////////////////////////
u32 app_get_rand(u32 max);
void app_srand(u32 seed);
void app_set_lcdsize(u8 mode);
void app_read_bkcolor(u16 x,u16 y,u16 width,u16 height,u16 *ctbl);
void app_recover_bkcolor(u16 x,u16 y,u16 width,u16 height,u16 *ctbl);
void app_gui_tcbar(u16 x,u16 y,u16 width,u16 height,u8 mode);
u8 app_get_numlen(long long num,u8 dir);
void app_show_float(u16 x,u16 y,long long num,u8 flen,u8 clen,u8 font,u16 color,u16 bkcolor);
void app_filebrower(u8 *topname,u8 mode);
void app_showbigchar(u8 *fontbase,u16 x,u16 y,u8 chr,u8 size,u16 color,u16 bkcolor);
void app_showbigstring(u8 *fontbase,u16 x,u16 y,const u8 *p,u8 size,u16 color,u16 bkcolor);
void app_showbignum(u8 *fontbase,u16 x,u16 y,u32 num,u8 len,u8 size,u16 color,u16 bkcolor);
void app_showbig2num(u8 *fontbase,u16 x,u16 y,u8 num,u8 size,u16 color,u16 bkcolor);
void app_show_nummid(u16 x,u16 y,u16 width,u16 height,u32 num,u8 len,u8 size,u16 ptcolor,u16 bkcolor);
void app_draw_smooth_line(u16 x,u16 y,u16 width,u16 height,u32 sergb,u32 mrgb);
u8 app_tp_is_in_area(_m_tp_dev *tp,u16 x,u16 y,u16 width,u16 height);
void app_show_items(u16 x,u16 y,u16 itemwidth,u16 itemheight,u8*name,u8*icopath,u16 color,u16 bkcolor);
u8 * app_get_icopath(u8 mode,u8 *selpath,u8 *unselpath,u8 selx,u8 index);
u8 app_items_sel(u16 x,u16 y,u16 width,u16 height,u8 *items[],u8 itemsize,u8 *selx,u8 mode,u8*caption);
u8 app_listbox_select(u8 *sel,u8 *top,u8 * caption,u8 *items[],u8 itemsize);
void app_show_mono_icos(u16 x,u16 y,u8 width,u8 height,u8 *icosbase,u16 color,u16 bkcolor);
u8 app_system_file_check(void);//系统文件检测
u8 app_boot_cpdmsg(u8*pname,u8 pct,u8 mode);
void app_boot_cpdmsg_set(u16 x,u16 y);
u8 app_system_update(u8(*fcpymsg)(u8*pname,u8 pct,u8 mode));
void app_getstm32_sn(u32 *sn0,u32 *sn1,u32 *sn2);
void app_get_version(u8*buf,u32 ver,u8 len);//得到版本号
void app_usmart_getsn(void);//USMART专用.
u8 app_system_parameter_init(void);//系统信息初始化
#endif
<file_sep>/projects/README.txt
结构说明
--------------------------------------------
001_template:模版代码
002_gpio:gpio驱动led灯
003_systemtick:滴答定时器用到延时函数。
004_exti:按键控制led灯的外部中断实验
005: 外部中断实验
006:独立看门狗实验
007:窗口看门狗实验
008: 定时器实验<file_sep>/projects/010_pwm/USER/main.c
#include "stm32f10x.h"
void Delay(u32 count)
{
u32 i=0;
for(;i<count;i++);
}
void time_init()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
//端口映射
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3, ENABLE);
//这里的端口映射和本开发板不一样,所以跑不起来
TIM_DeInit(TIM3);
//定时器初始化
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period = 899;
TIM_TimeBaseInitStruct.TIM_Prescaler = 0;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
//pwd初始化
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OC2Init(TIM3, &TIM_OCInitStruct);
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
}
int main(void)
{
u8 led_fx = 1;
u16 led_dt = 0;
GPIO_InitTypeDef GPIO_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitType.GPIO_Pin = GPIO_Pin_8; //LED0:PA8
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_AF_PP; //复用功能
GPIO_Init(GPIOA, &GPIO_InitType);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_InitType.GPIO_Pin = GPIO_Pin_2; //LED1:PD2
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_AF_PP; //复用功能
GPIO_Init(GPIOD, &GPIO_InitType);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
time_init();
TIM_Cmd(TIM3, ENABLE);
while(1)
{
Delay(1000);
if(led_fx == 1)
{
led_dt ++;
}
else
{
led_dt --;
}
if(led_dt > 300)
led_fx = 0;
if(led_dt == 0)
led_fx = 1;
TIM_SetCompare2(TIM3, led_dt);
}
}
<file_sep>/projects/004_exti/USER/main.c
#include "stm32f10x.h"
void RCC_HSE_Configuration(void) //HSE作为PLL时钟,PLL作为SYSCLK
{
RCC_DeInit(); /*将外设RCC寄存器重设为缺省值 */
RCC_HSEConfig(RCC_HSE_ON); /*设置外部高速晶振(HSE) HSE晶振打开(ON)*/
if(RCC_WaitForHSEStartUp() == SUCCESS)
{ /*等待HSE起振, SUCCESS:HSE晶振稳定且就绪*/
RCC_HCLKConfig(RCC_SYSCLK_Div1);/*设置AHB时钟(HCLK)RCC_SYSCLK_Div1——AHB时钟 = 系统时*/
RCC_PCLK2Config(RCC_HCLK_Div1); /*设置高速AHB时钟(PCLK2)RCC_HCLK_Div1——APB2时钟 = HCLK*/
RCC_PCLK1Config(RCC_HCLK_Div2); /*设置低速AHB时钟(PCLK1)RCC_HCLK_Div2——APB1时钟 = HCLK / 2*/
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);/*设置PLL时钟源及倍频系数*/
RCC_PLLCmd(ENABLE); /*使能PLL */
while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) ; /*检查指定的RCC标志位(PLL准备好标志)设置与否*/
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); /*设置系统时钟(SYSCLK) */
while(RCC_GetSYSCLKSource() != 0x08); /*0x08:PLL作为系统时钟 */
}
}
void Delay(u32 ms)
{
u32 temp;
SysTick->LOAD = 9000*ms;
SysTick->VAL=0X00;//清空计数器
SysTick->CTRL=0X01;//使能,减到零是无动作,采用外部时钟源
do
{
temp=SysTick->CTRL;//读取当前倒计数值
}while((temp&0x01)&&(!(temp&(1<<16))));//等待时间到达
SysTick->CTRL=0x00; //关闭计数器
SysTick->VAL =0X00; //清空计数器
}
void LED_init()
{
GPIO_InitTypeDef GPIO_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD, ENABLE);
GPIO_InitType.GPIO_Pin = GPIO_Pin_8; //LED0:PA8
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitType);
GPIO_InitType.GPIO_Pin = GPIO_Pin_2; //LED1:PD2
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitType);
}
void key_init()
{
EXTI_InitTypeDef EXTI_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource5);
EXTI_InitType.EXTI_Line = EXTI_Line5;
EXTI_InitType.EXTI_LineCmd = ENABLE;
EXTI_InitType.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitType.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_Init(&EXTI_InitType);
}
void nvic_init()
{
NVIC_InitTypeDef NVIC_InitType;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitType.NVIC_IRQChannel = EXTI9_5_IRQn;
NVIC_InitType.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitType.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitType.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitType);
}
//PA2, PD8
int main(void)
{
RCC_HSE_Configuration();
LED_init();
key_init();
nvic_init();
while(1);
}
void EXTI9_5_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line5)==SET)
{
EXTI_ClearITPendingBit(EXTI_Line5);
if(GPIO_ReadInputDataBit(GPIOC,GPIO_Pin_5)==Bit_RESET)
{
if(GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_8)==Bit_RESET)
{
//LED 熄灭
GPIO_SetBits(GPIOA,GPIO_Pin_8);
}
else
{
//LED 发光
GPIO_ResetBits(GPIOA,GPIO_Pin_8);
}
}
}
EXTI_ClearITPendingBit(EXTI_Line5);
}
<file_sep>/Standard Lib版本/实验38 综合测试实验/USER/main.c
#include "includes.h"
#include "common.h"
#include "mainui.h"
#include "ebook.h"
#include "picviewer.h"
#include "appplay.h"
#include "usbplay.h"
#include "calendar.h"
#include "settings.h"
#include "paint.h"
#include "wirelessplay.h"
#include "notepad.h"
//ALIENTEK MiniSTM32开发板实验38
//综合实验
//技术支持:www.openedv.com
//广州市星翼电子科技有限公司
/////////////////////////UCOSII任务设置///////////////////////////////////
//START 任务
//设置任务优先级
#define START_TASK_PRIO 10 //开始任务的优先级设置为最低
//设置任务堆栈大小
#define START_STK_SIZE 64
//任务堆栈,8字节对齐
__align(8) static OS_STK START_TASK_STK[START_STK_SIZE];
//任务函数
void start_task(void *pdata);
//串口任务
//设置任务优先级
#define USART_TASK_PRIO 7
//设置任务堆栈大小
#define USART_STK_SIZE 64
//任务堆栈,8字节对齐
__align(8) static OS_STK USART_TASK_STK[USART_STK_SIZE];
//任务函数
void usart_task(void *pdata);
//主任务
//设置任务优先级
#define MAIN_TASK_PRIO 6
//设置任务堆栈大小
#define MAIN_STK_SIZE 256
//任务堆栈,8字节对齐
__align(8) static OS_STK MAIN_TASK_STK[MAIN_STK_SIZE];
//任务函数
void main_task(void *pdata);
//串口监视任务
//设置任务优先级
#define WATCH_TASK_PRIO 3
//设置任务堆栈大小
#define WATCH_STK_SIZE 64
//任务堆栈,8字节对齐
__align(8) static OS_STK WATCH_TASK_STK[WATCH_STK_SIZE];
//任务函数
void watch_task(void *pdata);
//////////////////////////////////////////////////////////////////////////////
//显示错误信息
//x,y:坐标.err:错误信息
void system_error_show(u16 x,u16 y,u8*err)
{
POINT_COLOR=RED;
while(1)
{
LCD_ShowString(x,y,240,320,12,err);
delay_ms(400);
LCD_Fill(x,y,240,y+18,BLACK);
delay_ms(100);
LED0=!LED0;
}
}
//系统初始化
void system_init(void)
{
const u8 okoffset=162;
u16 ypos=0;
u16 j=0;
u16 temp=0;
u8 res;
u32 dtsize,dfsize;
u8 *stastr=0;
u8 *version=0;
u8 verbuf[12];
NVIC_Configuration();
delay_init(); //延时初始化
uart_init(115200); //串口1初始化
LCD_Init(); //LCD初始化
LED_Init(); //LED初始化
KEY_Init(); //按键初始化
gui_init();
Adc_Init(); //ADC初始化,内部温度传感器
AT24CXX_Init();
SPI_Flash_Init(); //W25Qxx初始化
mem_init(); //内存池初始化
version=mymalloc(31); //申请31个字节内存
exfuns_init();
REINIT://重新初始化
LCD_Clear(BLACK); //黑屏
POINT_COLOR=WHITE;
BACK_COLOR=BLACK;
j=0;
/////////////////////////////////////////////////////////////////////////
//显示版权信息
ypos=2;
app_show_mono_icos(5,ypos,18,24,(u8*)APP_ALIENTEK_ICO,YELLOW,BLACK);
LCD_ShowString(28,ypos+12*j++,240,320,12, "ALIENTEK MiniSTM32");
LCD_ShowString(28,ypos+12*j++,240,320,12,"Copyright (C) 2010-2020");
app_get_version(verbuf,HARDWARE_VERSION,2);
strcpy((char*)version,"HARDWARE:");
strcat((char*)version,(const char*)verbuf);
strcat((char*)version,", SOFTWARE:");
app_get_version(verbuf,SOFTWARE_VERSION,3);
strcat((char*)version,(const char*)verbuf);
LCD_ShowString(5,ypos+12*j++,240,320,12,version);
sprintf((char*)verbuf,"LCD ID:%04X",lcddev.id); //LCD ID打印到verbuf里面
LCD_ShowString(5,ypos+12*j++,240,320,12, verbuf); //显示LCD ID
//////////////////////////////////////////////////////////////////////////
//开始硬件检测初始化
LCD_ShowString(5,ypos+12*j++,240,320,12, "CPU:STM32F103RCT6 72Mhz");
LCD_ShowString(5,ypos+12*j++,240,320,12, "FLASH:256KB SRAM:48KB");
switch(SPI_FLASH_TYPE)
{
case W25Q80:
temp=1*1024;
break;
case W25Q16:
temp=2*1024;
break;
case W25Q32:
temp=4*1024;
break;
case W25Q64:
temp=8*1024;
break;
default :
system_error_show(5,ypos+12*j++,"Ex Flash Error!!");
break;
}
LCD_ShowString(5,ypos+12*j,240,320,12, "Ex Flash: KB");
LCD_ShowxNum(5+9*6,ypos+12*j,temp,4,12,0);//显示flash大小
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");
LCD_ShowString(5,ypos+12*j,240,320,12, "FATFS Check...");//FATFS检测
f_mount(fs[0],"0:",1); //挂载SD卡
f_mount(fs[1],"1:",1); //挂载FLASH.
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");
//SD卡检测
LCD_ShowString(5,ypos+12*j,240,320,12, "SD Card: MB");//FATFS检测
temp=0;
do
{
temp++;
res=exf_getfree("0:",&dtsize,&dfsize);//得到SD卡剩余容量和总容量
delay_ms(200);
}while(res&&temp<5);//连续检测5次
if(res==0)//得到容量正常
{
temp=dtsize>>10;//单位转换为MB
stastr="OK";
}else
{
temp=0;//出错了,单位为0
stastr="ERROR";
}
LCD_ShowxNum(5+8*6,ypos+12*j,temp,5,12,0); //显示SD卡容量大小
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12,stastr); //SD卡状态
//W25Q64检测,如果不存在文件系统,则先创建.
temp=0;
do
{
temp++;
res=exf_getfree("1:",&dtsize,&dfsize);//得到FLASH剩余容量和总容量
delay_ms(200);
}while(res&&temp<20);//连续检测20次
if(res==0X0D)//文件系统不存在
{
LCD_ShowString(5,ypos+12*j,240,320,12, "Flash Disk Formatting..."); //格式化FLASH
res=f_mkfs("1:",1,4096);//格式化FLASH,1,盘符;1,不需要引导区,8个扇区为1个簇
if(res==0)
{
f_setlabel((const TCHAR *)"1:ALIENTEK"); //设置Flash磁盘的名字为:ALIENTEK
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");//标志格式化成功
res=exf_getfree("1:",&dtsize,&dfsize);//重新获取容量
}
}
if(res==0)//得到FLASH卡剩余容量和总容量
{
LCD_ShowString(5,ypos+12*j,240,320,12, "Flash Disk: KB");//FATFS检测
temp=dtsize;
}else system_error_show(5,ypos+12*(j+1),"Flash Fat Error!"); //flash 文件系统错误
LCD_ShowxNum(5+11*6,ypos+12*j,temp,4,12,0); //显示SD卡容量大小
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12,"OK"); //SD卡状态
//RTC检测
LCD_ShowString(5,ypos+12*j,240,320,12, "RTC Check...");
if(RTC_Init())system_error_show(5,ypos+12*(j+1),"RTC Error!");//RTC检测
else LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");
//24C02检测
LCD_ShowString(5,ypos+12*j,240,320,12, "24C02 Check...");
if(AT24CXX_Check())system_error_show(5,ypos+12*(j+1),"24C02 Error!");//24C02检测
//字库检测
LCD_ShowString(5,ypos+12*j,240,320,12, "Font Check...");
res=KEY_Scan(1);//检测按键
while(font_init()||res==2) //检测字体,如果字体不存在/按下KEY1,则更新字库
{
res=0;//按键无效
if(update_font(5,ypos+12*j,12)!=0)//从SD卡更新
{
system_error_show(5,ypos+12*(j+1),"Font Error!"); //字体错误
}
LCD_Fill(5,ypos+12*j,240,ypos+12*(j+1),BLACK);//填充底色
LCD_ShowString(5,ypos+12*j,240,320,12, "Font Check...");
}
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");//字库检测OK
//系统文件检测
LCD_ShowString(5,ypos+12*j,240,320,12, "SYSTEM Files Check...");
while(app_system_file_check())//系统文件检测
{
LCD_Fill(5,ypos+12*j,240,ypos+12*(j+1),BLACK); //填充底色
LCD_ShowString(5,ypos+12*j,6*8,12,12, "Updating"); //显示updating
app_boot_cpdmsg_set(5,ypos+12*j);//设置到坐标
if(app_system_update(app_boot_cpdmsg)) //更新出错
{
system_error_show(5,ypos+12*(j+1),"SYSTEM File Error!");
}
LCD_Fill(5,ypos+12*j,240,ypos+12*(j+1),BLACK);//填充底色
LCD_ShowString(5,ypos+12*j,240,320,12, "SYSTEM Files Check...");
if(app_system_file_check())//更新了一次,再检测,如果还有不全,说明SD卡文件就不全!
{
system_error_show(5,ypos+12*(j+1),"SYSTEM File Lost!");
}else break;
}
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");
//触摸屏检测
LCD_ShowString(5,ypos+12*j,240,320,12, "Touch Check...");
res=KEY_Scan(1);//检测按键
if(TP_Init()||res==1)//有更新/按下了KEY0,执行校准
{
if(res==1)TP_Adjust();
res=0;//按键无效
goto REINIT; //重新开始初始化
}
LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");//触摸屏检测OK
//系统参数加载
LCD_ShowString(5,ypos+12*j,240,320,12, "SYSTEM Parameter Load...");
if(app_system_parameter_init())system_error_show(5,ypos+12*(j+1),"Parameter Load Error!");//参数加载
else LCD_ShowString(5+okoffset,ypos+12*j++,240,320,12, "OK");
LCD_ShowString(5,ypos+12*j,240,320,12, "SYSTEM Starting...");
delay_ms(1500);
myfree(version);
}
int main(void)
{
system_init();
OSInit();
OSTaskCreate(start_task,(void *)0,(OS_STK *)&START_TASK_STK[START_STK_SIZE-1],START_TASK_PRIO );//创建起始任务
OSStart();
}
//开始任务
void start_task(void *pdata)
{
OS_CPU_SR cpu_sr=0;
pdata = pdata;
OSStatInit(); //初始化统计任务.这里会延时1秒钟左右
app_srand(OSTime);
gui_init(); //gui初始化
piclib_init(); //piclib初始化
OS_ENTER_CRITICAL();//进入临界区(无法被中断打断)
OSTaskCreate(main_task,(void *)0,(OS_STK*)&MAIN_TASK_STK[MAIN_STK_SIZE-1],MAIN_TASK_PRIO);
OSTaskCreate(usart_task,(void *)0,(OS_STK*)&USART_TASK_STK[USART_STK_SIZE-1],USART_TASK_PRIO);
OSTaskCreate(watch_task,(void *)0,(OS_STK*)&WATCH_TASK_STK[WATCH_STK_SIZE-1],WATCH_TASK_PRIO);
OSTaskSuspend(START_TASK_PRIO); //挂起起始任务.
OS_EXIT_CRITICAL(); //退出临界区(可以被中断打断)
}
//主任务
void main_task(void *pdata)
{
u8 selx=0;
mui_init(); //Main UI 初始化
while(1)
{
selx=mui_touch_chk();
system_task_return=0;//清退出标志
switch(selx)
{
case 0: //电子图书
ebook_play();
break;
case 1: //图片浏览
picviewer_play();
break;
case 2: //USB连接
usb_play();
break;
case 3: //APP界面
app_play();
break;
case 4: //日历
calendar_play();
break;
case 5: //系统设置
sysset_play();
break;
case 6: //画板
paint_play();
break;
case 7: //无线通信实验
wireless_play();
break;
case 8: //记事本功能
notepad_play();
break;
}
if(selx<9)mui_load_icos();
delay_ms(1000/OS_TICKS_PER_SEC);//延时一个时钟节拍
}
}
//执行最不需要时效性的代码
void usart_task(void *pdata)
{
OS_CPU_SR cpu_sr=0;
u16 alarmtimse=0;
pdata=pdata;
while(1)
{
delay_ms(1000);
if(alarm.ringsta&1<<7)//执行闹钟扫描函数
{
calendar_alarm_ring(alarm.ringsta&0x3);//闹铃(DS1闪烁)
alarmtimse++;
if(alarmtimse>300)//超过300次了,5分钟以上
{
alarm.ringsta&=~(1<<7);//关闭闹铃
}
}else if(alarmtimse)
{
alarmtimse=0;
LED1=1;//关闭DS1
}
OS_ENTER_CRITICAL();//进入临界区(无法被中断打断)
printf("sram used:%d\r\n",mem_perused()); //打印内存占用率
OS_EXIT_CRITICAL(); //退出临界区(可以被中断打断)
}
}
//强制要求任务返回
volatile u8 system_task_return=0;
//监视任务
void watch_task(void *pdata)
{
u8 t=0;
u8 key;
pdata=pdata;
while(1)
{
if(alarm.ringsta&1<<7)//闹钟在执行
{
calendar_alarm_msg((lcddev.width-44)/2,(lcddev.height-20)/2);//闹钟处理
}
if(gifdecoding)//gif正在解码中
{
key=pic_tp_scan(0);
if(key==1||key==3)gifdecoding=0;//停止GIF解码
}
if(t==200) //2秒钟亮一次
{
LED0=0;
t=0;
}
if(t==8)LED0=1; //亮80ms左右
t++;
key=KEY0_Scan(); //单独扫描KEY0按键
if(key==1) //KEY0按下了
{
system_task_return=1;
if(gifdecoding)gifdecoding=0; //不再播放gif
}
delay_ms(10);
}
}
//硬件错误处理
void HardFault_Handler(void)
{
u32 i;
u8 t=0;
u32 temp;
temp=SCB->CFSR; //fault状态寄存器(@0XE000ED28)包括:MMSR,BFSR,UFSR
printf("CFSR:%8X\r\n",temp); //显示错误值
temp=SCB->HFSR; //硬件fault状态寄存器
printf("HFSR:%8X\r\n",temp); //显示错误值
temp=SCB->DFSR; //调试fault状态寄存器
printf("DFSR:%8X\r\n",temp); //显示错误值
temp=SCB->AFSR; //辅助fault状态寄存器
printf("AFSR:%8X\r\n",temp); //显示错误值
LED1=!LED1;
while(t<5)
{
t++;
LED0=!LED0;
for(i=0;i<0X1FFFFF;i++);
}
}
<file_sep>/projects/005_exti2/STM32F10x_FWLib/readme.txt
C:\Keil\ARM\RV31\LIB\ST\STM32F10x_StdPeriph_Driver
<file_sep>/Standard Lib版本/实验39 ucGUI实验/APP/app.c
#include "includes.h"
#include "app_cfg.h"
#include "led.h"
#include "gui.h"
/*
***************************************************************
全局变量区
****************************************************************
*/
/********************系统堆栈**********************************/
OS_STK UCGUI_DEMO_Task_Stk[UCGUI_DEMO_TASK_STK_SIZE]; //定义栈
OS_STK LED_Task_Stk[LED_TASK_STK_SIZE]; //定义栈
OS_STK TOUCH_TEST_Task_Stk[TOUCH_TEST_TASK_STK_SIZE]; //定义栈
/*
***************************************************************
函数声明区
****************************************************************
*/
static void Create_Task(void);
void Start_Task(void *p_arg);
static void UCGUI_DEMO_Task(void *p_arg);
static void LED_Task(void *p_arg);
static void TOUCH_TEST_Task(void *p_arg);
/*
***************************************************************
*函数名:Create_Task()
*功能: 创建任务
*参数: 无
*返回值:无
****************************************************************
*/
static void Create_Task(void)
{
OSTaskCreateExt(UCGUI_DEMO_Task,
(void *)0,
&UCGUI_DEMO_Task_Stk[UCGUI_DEMO_TASK_STK_SIZE -1],
UCGUI_DEMO_TASK_PRIO,UCGUI_DEMO_TASK_PRIO,
& UCGUI_DEMO_Task_Stk[0],
UCGUI_DEMO_TASK_STK_SIZE,
(void *)0,
OS_TASK_OPT_STK_CHK|OS_TASK_OPT_STK_CLR ); //创建UCGUI DEMO任务
OSTaskCreateExt(LED_Task,
(void *)0,
&LED_Task_Stk[LED_TASK_STK_SIZE -1],
LED_TASK_PRIO,LED_TASK_PRIO,
& LED_Task_Stk[0],
LED_TASK_STK_SIZE,
(void *)0,
OS_TASK_OPT_STK_CHK|OS_TASK_OPT_STK_CLR );
OSTaskCreateExt(TOUCH_TEST_Task,
(void *)0,
&TOUCH_TEST_Task_Stk[TOUCH_TEST_TASK_STK_SIZE -1],
TOUCH_TEST_TASK_PRIO,TOUCH_TEST_TASK_PRIO,
& TOUCH_TEST_Task_Stk[0],
TOUCH_TEST_TASK_STK_SIZE,
(void *)0,
OS_TASK_OPT_STK_CHK|OS_TASK_OPT_STK_CLR );
}
/*
***************************************************************
*函数名:Start_Task
*功能: 开始任务
*参数: p_arg
*返回值:无
****************************************************************
*/
void Start_Task(void *p_arg)
{
(void)p_arg; // 'p_arg' 并没有用到,防止编译器提示警告
Create_Task(); //创建任务
while (1)
{
OSTimeDlyHMSM(0, 0, 0, 500);
}
}
/*
***************************************************************
*函数名:GUI_DEMO_Task
*功能: 运行uCGUI的DEMO
*参数: p_arg
*返回值:无
****************************************************************
*/
static void UCGUI_DEMO_Task(void *p_arg)
{
(void)p_arg;
while(1)
{
GUIDEMO_main();
OSTimeDlyHMSM(0, 0, 0, 10);
}
}
/*
***************************************************************
*函数名:LED_Task
*功能: LED监控代码运行
*参数: p_arg
*返回值:无
****************************************************************
*/
static void LED_Task(void *p_arg)
{
(void)p_arg;
while(1)
{
LED0 = 0;
LED1 = 1;
OSTimeDlyHMSM(0, 0, 0, 200);
LED0 = 1;
LED1 = 0;
OSTimeDlyHMSM(0, 0, 0, 200);
}
}
/*
***************************************************************
*函数名:TOUCH_TEST_Task
*功能: 触摸检测任务
*参数: p_arg
*返回值:无
****************************************************************
*/
static void TOUCH_TEST_Task(void *p_arg)
{
(void)p_arg;
while(1)
{
GUI_TOUCH_Exec(); //监视和刷新触摸板
OSTimeDlyHMSM(0, 0, 0, 10);
}
}
<file_sep>/Standard Lib版本/实验16 内部温度传感器实验/USER/main.c
#include "led.h"
#include "delay.h"
#include "sys.h"
#include "usart.h"
#include "lcd.h"
#include "tsensor.h"
//ALIENTEK Mini STM32开发板范例代码16
//内部温度传感器实验
//技术支持:www.openedv.com
//广州市星翼电子科技有限公司
int main(void)
{
u16 adcx;
float temp;
float temperate;
delay_init(); //延时函数初始化
uart_init(9600); //串口初始化为9600
LED_Init(); //初始化与LED连接的硬件接口
LCD_Init();
T_Adc_Init(); //ADC初始化
POINT_COLOR=RED;//设置字体为红色
LCD_ShowString(60,50,200,16,16,"Mini STM32");
LCD_ShowString(60,70,200,16,16,"Temperature TEST");
LCD_ShowString(60,90,200,16,16,"ATOM@ALIENTEK");
LCD_ShowString(60,110,200,16,16,"2014/3/9");
//显示提示信息
POINT_COLOR=BLUE;//设置字体为蓝色
LCD_ShowString(60,130,200,16,16,"TEMP_VAL:");
LCD_ShowString(60,150,200,16,16,"TEMP_VOL:0.000V");
LCD_ShowString(60,170,200,16,16,"TEMPERATE:00.00C");
while(1)
{
adcx=T_Get_Adc_Average(ADC_CH_TEMP,10);
LCD_ShowxNum(132,130,adcx,4,16,0);//显示ADC的值
temp=(float)adcx*(3.3/4096);
temperate=temp;//保存温度传感器的电压值
adcx=temp;
LCD_ShowxNum(132,150,adcx,1,16,0); //显示电压值整数部分
temp-=(u8)temp; //减掉整数部分
LCD_ShowxNum(148,150,temp*1000,3,16,0X80); //显示电压小数部分
temperate=(1.43-temperate)/0.0043+25; //计算出当前温度值
LCD_ShowxNum(140,170,(u8)temperate,2,16,0); //显示温度整数部分
temperate-=(u8)temperate;
LCD_ShowxNum(164,170,temperate*100,2,16,0X80);//显示温度小数部分
LED0=!LED0;
delay_ms(250);
}
}
<file_sep>/projects/009_uart/USER/main.c
#include "stm32f10x.h"
void Delay(u32 count)
{
u32 i=0;
for(;i<count;i++);
}
int main(void)
{
GPIO_InitTypeDef GPIO_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD, ENABLE);
GPIO_InitType.GPIO_Pin = GPIO_Pin_8; //LED0:PA8
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitType);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_InitType.GPIO_Pin = GPIO_Pin_2; //LED1:PD2
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitType);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
//add clock init here!!!!!!!!!
time_init();
nvic_init();
TIM_Cmd(TIM3, ENABLE);
while(1);
}
<file_sep>/projects/007_wwdg/USER/main.c
#include "stm32f10x.h"
void Delay(u32 count)
{
u32 i=0;
for(;i<count;i++);
}
void wwdg_init()
{
RCC_APB1PeriphResetCmd(RCC_APB1Periph_WWDG, ENABLE);
WWDG_SetPrescaler(WWDG_Prescaler_8); //(PCLK1/4096)/8
WWDG_SetWindowValue(0x4f);
WWDG_ClearFlag();
WWDG_EnableIT();
WWDG_Enable(0x7f);
/*
* WWDG_SetCounter(0x7f) alse set reload counter, but only set and No enble
*/
}
void nvic_init()
{
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStruct.NVIC_IRQChannel = WWDG_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
}
void WWDG_IRQHandler()
{
WWDG_ClearFlag();
WWDG_SetCounter(0x7f);
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8) == 0)
{
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
}
else
{
GPIO_ResetBits(GPIOA, GPIO_Pin_8);
GPIO_ResetBits(GPIOD, GPIO_Pin_2);
}
}
int main(void)
{
GPIO_InitTypeDef GPIO_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD, ENABLE);
GPIO_InitType.GPIO_Pin = GPIO_Pin_8; //LED0:PA8
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitType);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_InitType.GPIO_Pin = GPIO_Pin_2; //LED1:PD2
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitType);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
wwdg_init();
nvic_init();
while(1);
}
<file_sep>/projects/006_iwdg/USER/main.c
#include "stm32f10x.h"
void Delay(u32 count)
{
u32 i=0;
for(;i<count;i++);
}
int main(void)
{
GPIO_InitTypeDef GPIO_InitType;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOD, ENABLE);
GPIO_InitType.GPIO_Pin = GPIO_Pin_8; //LED0:PA8
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOA, &GPIO_InitType);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
GPIO_InitType.GPIO_Pin = GPIO_Pin_2; //LED1:PD2
GPIO_InitType.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitType.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOD, &GPIO_InitType);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable);
IWDG_SetPrescaler(IWDG_Prescaler_4); // 4 * 2^4 = 64
IWDG_SetReload(625);
IWDG_ReloadCounter();
IWDG_Enable();
while(1)
{
GPIO_ResetBits(GPIOA, GPIO_Pin_8);
Delay(6000000);
GPIO_SetBits(GPIOA, GPIO_Pin_8);
Delay(6000000);
GPIO_ResetBits(GPIOD, GPIO_Pin_2);
Delay(6000000);
GPIO_SetBits(GPIOD, GPIO_Pin_2);
Delay(6000000);
}
}
void feed_dog()
{
IWDG_ReloadCounter();
}
|
dd5d77195265e525ec8cc082edcf7d84cda3b210
|
[
"C",
"Text"
] | 15 |
C
|
0x012f5b7d/tun43g214
|
66e2552760a726dccdcd5bf0c4fbac1533b865a5
|
ac77cc81f5016ae8c326ca66a8d065bd2de8ca43
|
refs/heads/master
|
<file_sep>using System;
using SetWindowsService.Application.Business.Contract;
namespace SetWindowsService.Application.Business
{
public class BusinessService : BaseService, IBusinessService
{
public void DoWork()
{
Console.WriteLine("I do something");
}
}
}
<file_sep>using System;
using System.ServiceProcess;
using NLog;
namespace SetWindowsService.Application
{
partial class BussinessWindowsService : ServiceBase
{
public BussinessWindowsService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Bootstrapper.Initialize();
}
protected override void OnStop()
{
var logger = LogManager.GetCurrentClassLogger();
logger.Info(string.Format("Service Shutdown {0:f}", DateTime.Now));
}
}
}
<file_sep>using System;
using System.Threading;
using SetWindowsService.Application.Business.Contract;
namespace SetWindowsService.Application.Business
{
public class TimerBusinessService : BaseService, ITimerBusinessService
{
private const long TIMER_TICK_SECOND = 1000;
private const long TIMER_TICK_MINUTE = 60000;
private const long TIMER_TICK_HOUR = 3600000;
private const long TIMER_TICK_DAY = 86400000;
private const long TIMER_TICK_WEEK = 604800000;
private const long TIMER_TICK_MONTH = 2419200000;
public void DoWorkEverySecond()
{
var timer = new Timer(x => Console.WriteLine("I do something every second"), null, 0, TIMER_TICK_SECOND);
}
public void DoWorkEveryMinute()
{
var timer = new Timer(x => Console.WriteLine("I do something every minute"), null, 0, TIMER_TICK_MINUTE);
}
public void DoWorkEveryHour()
{
var timer = new Timer(x => Console.WriteLine("I do something every hour"), null, 0, TIMER_TICK_HOUR);
}
public void DoWorkEveryDay()
{
var timer = new Timer(x => Console.WriteLine("I do something every day"), null, 0, TIMER_TICK_DAY);
}
public void DoWorkEveryWeek()
{
var timer = new Timer(x => Console.WriteLine("I do something every week"), null, 0, TIMER_TICK_WEEK);
}
public void DoWorkEveryMonth()
{
var timer = new Timer(x => Console.WriteLine("I do something every month"), null, 0, TIMER_TICK_MONTH);
}
}
}<file_sep>using System.ServiceModel;
namespace SetWindowsService.Application.Business.Contract
{
[ServiceContract]
public interface ITimerBusinessService
{
[OperationContract]
void DoWorkEverySecond();
[OperationContract]
void DoWorkEveryMinute();
[OperationContract]
void DoWorkEveryHour();
[OperationContract]
void DoWorkEveryDay();
[OperationContract]
void DoWorkEveryWeek();
[OperationContract]
void DoWorkEveryMonth();
}
}<file_sep>set-windows-service
===================
<file_sep>using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace SetWindowsService.Application
{
[RunInstaller(true)]
public partial class EasyInstaller : Installer
{
public EasyInstaller()
{
InitializeComponent();
var serviceProcess = new ServiceProcessInstaller { Account = ServiceAccount.NetworkService };
var serviceInstaller = new ServiceInstaller
{
ServiceName = "SetWindowsService",
DisplayName = "Set Windows Service",
Description = "Describe your service implemtentation here...",
StartType = ServiceStartMode.Automatic
};
Installers.Add(serviceProcess);
Installers.Add(serviceInstaller);
}
}
}
<file_sep>using System;
using System.ServiceProcess;
namespace SetWindowsService.Application
{
class Program
{
static void Main()
{
if (Environment.UserInteractive)
{
Console.WriteLine("Service is starting!");
Bootstrapper.Initialize();
Console.WriteLine("Service started!");
Console.ReadLine();
}
else
{
ServiceBase.Run(new ServiceBase[] { new BussinessWindowsService() });
}
}
}
}
<file_sep>using System;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using Castle.Facilities.Logging;
using Castle.Facilities.WcfIntegration;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using SetWindowsService.Application.Business;
namespace SetWindowsService.Application
{
public class Bootstrapper
{
public static IWindsorContainer Container { get; private set; }
public static void Initialize()
{
Container = new WindsorContainer();
Container.AddFacility<WcfFacility>();
Container.AddFacility<LoggingFacility>(f => f.UseNLog());
var netNamedPipeBinding = new NetNamedPipeBinding
{
MaxBufferSize = 67108864,
MaxReceivedMessageSize = 67108864,
TransferMode = TransferMode.Streamed,
ReceiveTimeout = new TimeSpan(0, 30, 0),
SendTimeout = new TimeSpan(0, 30, 0)
};
var netTcpBinding = new NetTcpBinding
{
PortSharingEnabled = true,
Security = new NetTcpSecurity { Mode = SecurityMode.None },
MaxBufferSize = 67108864,
MaxReceivedMessageSize = 67108864,
TransferMode = TransferMode.Streamed,
ReceiveTimeout = new TimeSpan(0, 30, 0),
SendTimeout = new TimeSpan(0, 30, 0)
};
Container.Register(
Component.For<ExceptionInterceptor>().LifestyleTransient(),
Types.FromThisAssembly().Pick()
.If(type => type.GetInterfaces().Any(i => i.IsDefined(typeof(ServiceContractAttribute), true) && i.Name != typeof(BaseService).Name))
.Configure(
configurer =>
configurer.Named(configurer.Implementation.Name)
.Interceptors<ExceptionInterceptor>()
.LifestyleSingleton()
.AsWcfService(new DefaultServiceModel().AddEndpoints(
WcfEndpoint.BoundTo(netTcpBinding)
.At(string.Format("net.tcp://localhost:{1}/{0}", configurer.Implementation.Name, ConfigurationManager.AppSettings["Port"])),
WcfEndpoint.BoundTo(netNamedPipeBinding)
.At(string.Format("net.pipe://localhost/{0}", configurer.Implementation.Name)))
.PublishMetadata()))
.WithService.Select((type, baseTypes) => type.GetInterfaces().Where(i => i.IsDefined(typeof(ServiceContractAttribute), true))));
}
}
}
<file_sep>namespace SetWindowsService.Application.Business
{
public class BaseService
{
}
}<file_sep>using System.ServiceModel;
namespace SetWindowsService.Application.Business.Contract
{
[ServiceContract]
public interface IBusinessService
{
[OperationContract]
void DoWork();
}
}
|
ea8b5ddda7414cac0ed2d3315b1f00a3147b9442
|
[
"Markdown",
"C#"
] | 10 |
C#
|
emonarafat/set-windows-service
|
1bd10ab7c7096d867100f32f6170e125913f54ab
|
e1fbaceedeb8a7cd992660ac3ee84f7c3648d2fb
|
refs/heads/master
|
<file_sep># tk_geometric_pattern
## tkinterを用いた幾何学模様のアニメーション
Python3系で動作します。
GUI作成用モジュールであるtkinterは、
Pythonの標準モジュールなので、
Pythonをインストールするだけで実行できます。
### 操作方法
'a', 'z', 's', 'x', 'd', 'c', 'f', 'v'の各キーで、
表示される幾何学模様のパラメータを変更できます。
'q'キーを押すと、プログラムを終了します。
<file_sep># -*- coding: utf-8 -*-
"""
@author: enom
"""
import tkinter as tk
from math import sin, cos, radians
class GeometricPattern():
D_THETA_MAX = 20
DEG = 360
D_PHI = 1
def __init__(self, center_x=0, center_y=0):
self.center_x = center_x
self.center_y = center_y
self.r = int(0.8*min(self.center_x, self.center_y) / 3) #80
self.a = int(0.8*2*min(self.center_x, self.center_y) / 3) #160
self.phi = 0
self.mag = 104
self.d_theta = 1
self.get_points()
def dec_r(self, event):
self.r -= 1
if self.r < 1:
self.r = 1
def inc_r(self, event):
if self.r + self.a < min(self.center_x, self.center_y):
self.r += 1
def dec_a(self, event):
self.a -= 1
if self.a < 1:
self.a = 1
def inc_a(self, event):
if self.r + self.a < min(self.center_x, self.center_y):
self.a += 1
def dec_d_theta(self, event):
self.d_theta -= 1
if self.d_theta < 1:
self.d_theta = 1
def inc_d_theta(self, event):
self.d_theta += 1
if self.d_theta > GeometricPattern.D_THETA_MAX:
self.d_theta = GeometricPattern.D_THETA_MAX
def dec_mag(self, event):
self.mag -= 1
if self.mag < 0:
self.mag %= GeometricPattern.DEG
def inc_mag(self, event):
self.mag += 1
if self.mag >= GeometricPattern.DEG:
self.mag %= GeometricPattern.DEG
def inc_phi(self):
self.phi += 1
self.phi %= GeometricPattern.DEG
def get_points(self):
#self.points = [(x1, y1), (x2, y2), ..., (xn, yn), (x1, y1)]
self.points = [
(self.center_x + self.r*cos(radians(theta))
+ self.a*cos(radians(self.phi + theta*self.mag)),
self.center_y + self.r*sin(radians(theta))
+ self.a*sin(radians(self.phi + theta*self.mag)))
for theta in range(0, GeometricPattern.DEG, self.d_theta)]
self.points.append((self.points[0], self.points[1]))
class Simulator():
MS = 16 #16 ms/frame (approx. 60 fps)
def __init__(self, width, height):
#ウインドウサイズ
self.width = width
self.height = height
#ウインドウとウィジットの作成・設定
self.window = tk.Tk()
self.window.title(string='Sample Trig Function on Tkinter')
self.window.resizable(width=False, height=False)
self.canvas = tk.Canvas(
self.window, width=self.width, height=self.height)
#canvas上での関数の原点座標
self.center_x = width / 2
self.center_y = height / 2
#各文字列を表示する座標
self.quit_x = 20
self.quit_y = 30
self.r_x = width - 20
self.r_y = height - 120
self.a_x = width - 20
self.a_y = height - 90
self.mag_x = width - 20
self.mag_y = height - 60
self.d_theta_x = width - 20
self.d_theta_y = height - 30
self.gp = GeometricPattern(self.center_x, self.center_y)
self.canvas.create_rectangle(
0, 0, self.width, self.height, fill='black')
self.draw()
self.canvas.pack()
#キーバインド
self.window.bind('<KeyPress-q>', self.quit)
self.window.bind('<KeyPress-z>', self.gp.dec_r)
self.window.bind('<KeyPress-a>', self.gp.inc_r)
self.window.bind('<KeyPress-x>', self.gp.dec_a)
self.window.bind('<KeyPress-s>', self.gp.inc_a)
self.window.bind('<KeyPress-c>', self.gp.dec_mag)
self.window.bind('<KeyPress-d>', self.gp.inc_mag)
self.window.bind('<KeyPress-v>', self.gp.dec_d_theta)
self.window.bind('<KeyPress-f>', self.gp.inc_d_theta)
def quit(self, event):
self.window.destroy()
def draw(self):
#幾何学模様の表示
self.canvas.create_line(
self.gp.points, fill='white', tag='sample')
#各文字列の表示
self.canvas.create_text(
self.quit_x, self.quit_y,
text='Quit: q',
tag='sample', font=('Arial', 12), fill='white', anchor=tk.W)
self.canvas.create_text(
self.r_x, self.r_y,
text='Z < '+str(self.gp.r).zfill(3)+'> A',
tag='sample', font=('Arial', 12), fill='white', anchor=tk.E)
self.canvas.create_text(
self.a_x, self.a_y,
text='X < '+str(self.gp.a).zfill(3)+'> S',
tag='sample', font=('Arial', 12), fill='white', anchor=tk.E)
self.canvas.create_text(
self.mag_x, self.mag_y,
text='C < '+str(self.gp.mag).zfill(3)+'> D',
tag='sample', font=('Arial', 12), fill='white', anchor=tk.E)
self.canvas.create_text(
self.d_theta_x, self.d_theta_y,
text='V < '+str(self.gp.d_theta).zfill(3)+'> F',
tag='sample', font=('Arial', 12), fill='white', anchor=tk.E)
def delete(self):
#tagが'sample'のオブジェクトをすべて削除する
self.canvas.delete('sample')
def loop(self):
#描画のメインループ
self.gp.inc_phi()
self.gp.get_points()
self.delete()
self.draw()
self.window.after(Simulator.MS, self.loop)
def main():
WIDTH = 800
HEIGHT = 600
simulator = Simulator(WIDTH, HEIGHT)
simulator.loop()
simulator.window.mainloop()
if __name__ == '__main__':
main()
|
b493ec92a9df2f777bd048a3dd4331f0e18a6693
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
enomgithub/tk_geometric_pattern
|
0ce24a7dae97d88b69aa0943720170d8d1c99308
|
4e98283bf3e8d7ebc1892ce5f957ca75dd4bf108
|
refs/heads/master
|
<repo_name>vietjtnguyen/py-misc<file_sep>/pycalc
#!/usr/bin/python
#import numpy as np
#import pandas as pd
#import scipy as sp
#import scipy.ndimage as nd
#import scipy.signal as sg
from math import *
import ast, datetime, itertools, pickle, random, os, sys
for line in sys.stdin.readlines():
line = line[:line.rfind('#')]
try:
code_object = compile(line, '', 'eval')
output = '# = {:}'.format(str(eval(code_object)))
except SyntaxError as e:
code_object = compile(line, '', 'exec')
exec code_object
output = ''
print('{:}{:}'.format(str(line).strip(), output))
<file_sep>/pymap
#!/usr/bin/python
#import numpy as np
#import pandas as pd
#import scipy as sp
#import scipy.ndimage as nd
#import scipy.signal as sg
from math import *
import ast, datetime, itertools, pickle, random, re, os, sys
function_markers = '!*#-='
items = []
functions = []
for line in sys.stdin.readlines():
line = line[:-1] # remove new line at the end
if len(line) >= 2 and line[0] in function_markers:
function_marker = line[0]
use_arglist = line[1] == '*'
if use_arglist:
function_text = line[2:]
else:
function_text = line[1:]
# append lambda if it isn't there
if not function_text.startswith('lambda '):
function_text = 'lambda {:}'.format(function_text)
# create actual function
code_object = compile(function_text, '', 'eval')
func = eval(code_object)
if function_marker == '!': # map
if use_arglist:
for i in range(len(items)):
items[i] = func(*items[i])
else:
for i in range(len(items)):
items[i] = func(items[i])
functions.append(line)
elif line[0] == '*': # apply
items = func(items)
functions.append(line)
elif line[0] == '#': # enumerate
if use_arglist:
for i, item in enumerate(items):
items[i] = func(i, item)
else:
for i, item in enumerate(items):
items[i] = func((i, item))
functions.append(line)
elif line[0] == '-': # filter
items = filter(func, items)
functions.append(line)
elif line[0] == '=': # reduce
result = func(items)
if line.rfind('#') == -1:
functions.append('{:}# = {:}'.format(line, str(result)))
else:
functions.append('{:}# = {:}'.format(line[:line.rfind('#')], str(result)))
else:
if len(functions) > 0:
for item in items:
print(item)
for function_text in functions:
print(function_text)
del items
del functions
items = []
functions = []
items.append(line)
for item in items:
print(item)
for function_text in functions:
print(function_text)
<file_sep>/README.md
# Miscellaneous Python Tools
## pycalc
Inspired by [Crunch](http://ryanpcarney.com/technologblog/crunch-gets-crunchier-with-v20) I wrote up a Python script to do something similar. It allows for inline, line-by-line (i.e. no function definitions and for loops) code execution with appended results. Really the only difference between passing the code to Python directly is that it will append the results of expressions to the end of the line as a comment.
It is written with the intention of execution in vim like Crunch, but will happily accept anything from standard input. The intended use is via [vim's filter operation](http://vimdoc.sourceforge.net/htmldoc/various.html#:!) (also see [this post](http://usevim.com/2012/06/29/vim101-pipe/)), which is really *really* awesome.
Advantages:
* Code execution in-session
* Results appended, leaving original code intact for quick feedback cycle
* Access to anything Python like [NumPy](http://www.numpy.org/), [SciPy](http://www.scipy.org/), [SymPy](http://sympy.org/en/index.html), etc.
Disadvantages:
* Does not execute multi-line code
* Does not remember variables between executions
### Example
Say we have the following block of code in vim:
```python
paragraph one
x = 23.21
y = 53.32
norm = lambda x, y: sqrt(x*x+y*y)
norm(x, y)
atan2(y, x)
paragraph three
```
If you have your cursor in that second paragraph you can evaluate it with `{V}!pycalc` in vim (assuming pycalc is in your path and your Python is located at `/usr/bin/python`). The result is the following:
```python
paragraph one
x = 23.21
y = 53.32
norm = lambda x, y: sqrt(x*x+y*y)
norm(x, y)# = 58.1526138707
atan2(y, x)# = 1.1602370238
paragraph three
```
## pymap
This script started as some ideas that got into my head while writing pycalc. Basically it lets you write small Python functions (really just [lambdas](http://docs.python.org/2/reference/expressions.html#lambda)) and apply them (i.e. [map](http://docs.python.org/2/library/functions.html#map)) to each input line.
*This documentation is incomplete*
It works by reading each line as it comes in from standard input. If a line does not start with a function marker then it is simply kept as an input line. If a line starts with a function marker then it is treated as code to be evaluated. Functions are evaluated as they're encountered with the results remaining persistent across functions. So you can apply one map and then apply a map on that result.
There are five operations you can perform. Each operation is determined by the first character.
* `!`: applied per item
* `*`: applied to list of items and then assigned to items
* `#`: applied per [enumerated](http://docs.python.org/2/library/functions.html#enumerate) item
* `-`: used to [filter](http://docs.python.org/2/library/functions.html#filter) items
* `=`: applied to list of items and then appends result to end of function
After the function marker you simply define your lambda function. If you don't include the `lambda` then it'll prepend it for you.
At this point the best way to explain it is to look at examples.
### Example
#### Example 1
Input:
```python
[1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11, 12]
!x: sum(eval(x))
```
After evaluating all lines (such as `ggVG!pymap` in vim):
```python
6
22
50
!x: sum(eval(x))
```
If you prefer keeping the input, you can do the following:
```python
[1, 2, 3] # 6
[4, 5, 6, 7] # 22
[8, 9, 10, 11, 12] # 50
!x: '%s # %d' % (x, sum(eval(x)))
```
#### Example 2
Input:
```python
John, [1, 2, 3]
Sarah, [4, 5, 6, 7]
Bob, [8, 9, 10, 11, 12]
!x: x.split(',')
!x: (x[0], eval(','.join(x[1:])))
!*name, items: 'Sum of %s\'s items: %d' % (name, sum(items))
```
After evaluating all lines (such as `ggVG!pymap` in vim):
```text
Sum of John's items: 6
Sum of Sarah's items: 22
Sum of Bob's items: 50
!x: x.split(',')
!x: (x[0], eval(','.join(x[1:])))
!*name, items: 'Sum of %s\'s items: %d' % (name, sum(items))
```
#### Example 3
This example uses NumPy which you can enable by uncommenting the import lines at the top of the script (I should probably change those to try-import blocks).
```python
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
!x: ast.literal_eval(x)
*x: np.array(x)
=x: np.mean(x)
!x: 10*x
=x: np.mean(x)
```
After evaluating all lines (such as `ggVG!pymap` in vim):
```python
[10 20 30]
[40 50 60]
[70 80 90]
!x: ast.literal_eval(x)
*x: np.array(x)
=x: np.mean(x)# = 5.0
!x: 10*x
=x: np.mean(x)# = 50.0
```
|
61f6765e266b4d63e741eb2e70985ad8d7019c0f
|
[
"Markdown",
"Python"
] | 3 |
Python
|
vietjtnguyen/py-misc
|
9998737a9a09a6a35f3b1b75c69a9add7ca0d0d3
|
9a635b99a3aaca865ff7fde8d7d98456f205b8ed
|
refs/heads/master
|
<repo_name>konglingjuanyi/tl-conf<file_sep>/tiaoling-cloud-core/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">
<parent>
<artifactId>tiaoling-cloud</artifactId>
<groupId>com.itiaoling</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>tiaoling-cloud-core</artifactId>
<dependencies>
<!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!--<scope>provided</scope>-->
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- fast jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${common-lang3.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${mail.version}</version>
</dependency>
<!-- gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${code.jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${code.jackson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
</dependencies>
</project><file_sep>/tiaoling-cloud-conf-service/src/main/java/com/tiaoling/cloud/conf/persistence/ConfGroupMapper.java
package com.tiaoling.cloud.conf.persistence;
import com.tiaoling.cloud.conf.domain.ConfGroup;
import java.util.List;
public interface ConfGroupMapper {
int deleteByPrimaryKey(String groupKey);
int insert(ConfGroup record);
int insertSelective(ConfGroup record);
ConfGroup selectByPrimaryKey(String groupKey);
int updateByPrimaryKeySelective(ConfGroup record);
int updateByPrimaryKey(ConfGroup record);
List<ConfGroup> findAll();
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/TriggerLogMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.TriggerLog;
public interface TriggerLogMapper {
int deleteByPrimaryKey(Integer id);
int insert(TriggerLog record);
int insertSelective(TriggerLog record);
TriggerLog selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(TriggerLog record);
int updateByPrimaryKey(TriggerLog record);
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/TriggerInfoMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.TriggerInfo;
import java.util.List;
import java.util.Map;
public interface TriggerInfoMapper {
int deleteByPrimaryKey(Integer id);
int insert(TriggerInfo record);
int insertSelective(TriggerInfo record);
TriggerInfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(TriggerInfo record);
int updateByPrimaryKeyWithBLOBs(TriggerInfo record);
int updateByPrimaryKey(TriggerInfo record);
List<TriggerInfo> selectPageList(Map<String,Object> params);
int selectPageListCount(Map<String,Object> params);
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/TriggerGroupMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.TriggerGroup;
import java.util.List;
public interface TriggerGroupMapper {
int deleteByPrimaryKey(Integer id);
int insert(TriggerGroup record);
int insertSelective(TriggerGroup record);
TriggerGroup selectByPrimaryKey(Integer id);
List<TriggerGroup> findAllTriggerGroup();
int updateByPrimaryKeySelective(TriggerGroup record);
int updateByPrimaryKey(TriggerGroup record);
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/PausedTriggerGrpMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.PausedTriggerGrpKey;
public interface PausedTriggerGrpMapper {
int deleteByPrimaryKey(PausedTriggerGrpKey key);
int insert(PausedTriggerGrpKey record);
int insertSelective(PausedTriggerGrpKey record);
}<file_sep>/tiaoling-cloud-conf-service/src/main/java/com/tiaoling/cloud/conf/domain/ConfNode.java
package com.tiaoling.cloud.conf.domain;
public class ConfNode {
private String nodeGroup;
private String nodeKey;
private String nodeValue;
private String nodeDesc;
private Boolean isdelete;
private String groupKey; // key of prop [in zk]
private String nodeValueReal; // value of prop [in zk]
public String getNodeGroup() {
return nodeGroup;
}
public void setNodeGroup(String nodeGroup) {
this.nodeGroup = nodeGroup;
}
public String getNodeKey() {
return nodeKey;
}
public void setNodeKey(String nodeKey) {
this.nodeKey = nodeKey;
}
public String getNodeValue() {
return nodeValue;
}
public void setNodeValue(String nodeValue) {
this.nodeValue = nodeValue;
}
public String getNodeDesc() {
return nodeDesc;
}
public void setNodeDesc(String nodeDesc) {
this.nodeDesc = nodeDesc;
}
public Boolean getIsdelete() {
return isdelete;
}
public void setIsdelete(Boolean isdelete) {
this.isdelete = isdelete;
}
public String getGroupKey() {
return groupKey;
}
public void setGroupKey(String groupKey) {
this.groupKey = groupKey;
}
public String getNodeValueReal() {
return nodeValueReal;
}
public void setNodeValueReal(String nodeValueReal) {
this.nodeValueReal = nodeValueReal;
}
}<file_sep>/tiaoling-cloud-conf-web/src/main/java/com/tiaoling/cloud/conf/controller/GroupController.java
package com.tiaoling.cloud.conf.controller;
import com.tiaoling.cloud.conf.domain.ConfGroup;
import com.tiaoling.cloud.conf.utils.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/10/10.
*/
@Controller
@RequestMapping(value = "/group")
public class GroupController {
@RequestMapping
public String index(Model model) {
List<ConfGroup> list = new ArrayList<>();
String json ="";
Map<String,Object> params = new HashMap<String,Object>();
String doMethod = CommonPropertiesUtils.get("group_list");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
list=JsonUtils.getListDTO(JsonUtils.getJSONString(map.get("Body")),ConfGroup.class);
}
}
model.addAttribute("list", list);
return "group/group.index";
}
@RequestMapping("/save")
@ResponseBody
public ReturnT<String> save(ConfGroup ConfGroup){
// valid
if (ConfGroup.getGroupKey()==null || StringUtils.isBlank(ConfGroup.getGroupKey())) {
return new ReturnT<String>(500, "请输入GroupKey");
}
if (ConfGroup.getGroupKey().length()<1 || ConfGroup.getGroupKey().length()>100) {
return new ReturnT<String>(500, "GroupKey长度限制为1~100");
}
if (ConfGroup.getGroupName()==null || StringUtils.isBlank(ConfGroup.getGroupName())) {
return new ReturnT<String>(500, "请输入分组名称");
}
if (ConfGroup.getGroupName().length()<1 || ConfGroup.getGroupName().length()>100) {
return new ReturnT<String>(500, "GroupName长度限制为1~100");
}
int ret =0;
String json ="";
String message="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("groupKey",ConfGroup.getGroupKey());
params.put("groupName",ConfGroup.getGroupName());
String doMethod = CommonPropertiesUtils.get("group_add");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
JSONObject object = JSONObject.fromObject(map.get("Body").toString());
ret = object.getInt("row");
}
else
{
message=map.get("Message").toString();
}
}
return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
}
@RequestMapping("/update")
@ResponseBody
public ReturnT<String> update(ConfGroup ConfGroup){
// valid
if (ConfGroup.getGroupKey()==null || StringUtils.isBlank(ConfGroup.getGroupKey())) {
return new ReturnT<String>(500, "请输入GroupKey");
}
if (ConfGroup.getGroupKey().length()<1 || ConfGroup.getGroupKey().length()>100) {
return new ReturnT<String>(500, "GroupKey长度限制为1~100");
}
if (ConfGroup.getGroupName()==null || StringUtils.isBlank(ConfGroup.getGroupName())) {
return new ReturnT<String>(500, "请输入分组名称");
}
if (ConfGroup.getGroupName().length()<1 || ConfGroup.getGroupName().length()>100) {
return new ReturnT<String>(500, "GroupName长度限制为1~100");
}
int ret =0;
String json ="";
String message="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("groupKey",ConfGroup.getGroupKey());
params.put("groupName",ConfGroup.getGroupName());
params.put("isRemove",0);
String doMethod = CommonPropertiesUtils.get("group_update");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
JSONObject object = JSONObject.fromObject(map.get("Body").toString());
ret = object.getInt("row");
}
else
{
message=map.get("Message").toString();
}
}
return (ret>0)?ReturnT.SUCCESS:new ReturnT<String>(500, message);
}
@RequestMapping("/remove")
@ResponseBody
public ReturnT<String> remove(String groupKey){
int ret =0;
String json ="";
String message="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("groupKey",groupKey);
params.put("isRemove",1);
params.put("isdelete",1);
String doMethod = CommonPropertiesUtils.get("group_update");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
JSONObject object = JSONObject.fromObject(map.get("Body").toString());
ret = object.getInt("row");
}
else
{
message=map.get("Message").toString();
}
}
return (ret>0)?ReturnT.SUCCESS:new ReturnT<String>(500, message);
}
}
<file_sep>/tiaoling-cloud-conf-api/src/main/java/com/tiaoling/cloud/conf/controller/GroupController.java
package com.tiaoling.cloud.conf.controller;
import com.tiaoling.cloud.conf.domain.ConfGroup;
import com.tiaoling.cloud.conf.service.intf.ConfGroupService;
import com.tiaoling.cloud.conf.utils.ResultUtil;
import com.tiaoling.cloud.core.utils.HttpUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/10/10.
*/
@Controller
@RequestMapping(value = "group")
public class GroupController {
private Logger logger = LoggerFactory.getLogger(GroupController.class);
@Autowired
private ConfGroupService groupService;
@RequestMapping(value = "add",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String add(HttpServletRequest request, HttpServletResponse response)
{
Map<String,Object> result = new HashMap<>();
int size = request.getContentLength();
InputStream is;
try {
is = request.getInputStream();
byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
String params = new String(reqBodyBytes);
logger.info("tl-conf新增分组(group)(group/add)请求报文:" + params);
JSONObject paramJson = JSONObject.fromObject(params);
if(paramJson==null)
{
return ResultUtil.creComErrorResult("分组信息不能为空");
}
if(paramJson.get("groupKey")==null || paramJson.getString("groupKey").trim().equals(""))
{
return ResultUtil.creComErrorResult("分组键(Key)不能为空");
}
if(paramJson.get("groupName")==null || paramJson.getString("groupName").trim().equals(""))
{
return ResultUtil.creComErrorResult("分组名称不能为空");
}
ConfGroup group= groupService.getGroup(paramJson.getString("groupKey").trim());
if(group!=null)
{
return ResultUtil.creComErrorResult("分组已经存在");
}
else
{
ConfGroup group1 = new ConfGroup();
group1.setGroupKey(paramJson.getString("groupKey").trim());
group1.setGroupName(paramJson.getString("groupName").trim());
group1.setIsdelete(false);
int row= groupService.addGroup(group1);
result.put("row",row);
}
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
return ResultUtil.creObjSucResult(result);
}
@RequestMapping(value = "update",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String update(HttpServletRequest request, HttpServletResponse response)
{
Map<String,Object> result = new HashMap<>();
int size = request.getContentLength();
InputStream is;
try {
is = request.getInputStream();
byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
String params = new String(reqBodyBytes);
logger.info("tl-conf修改分组(group)(group/update)请求报文:" + params);
JSONObject paramJson = JSONObject.fromObject(params);
if(paramJson==null)
{
return ResultUtil.creComErrorResult("分组信息不能为空");
}
int isRemove =paramJson.getInt("isRemove");
if(paramJson.get("groupKey")==null || paramJson.getString("groupKey").trim().equals(""))
{
return ResultUtil.creComErrorResult("分组键(Key)不能为空");
}
if(isRemove==0) {
if (paramJson.get("groupName") == null || paramJson.getString("groupName").trim().equals("")) {
return ResultUtil.creComErrorResult("分组名称不能为空");
}
}
ConfGroup group = groupService.getGroup(paramJson.getString("groupKey").trim());
if(group==null)
{
return ResultUtil.creComErrorResult("分组信息不存在");
}
else
{
if(isRemove==1) group.setIsdelete(true);
else group.setGroupName(paramJson.getString("groupName").trim());
int row= groupService.updateGroup(group);
result.put("row",row);
}
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
return ResultUtil.creObjSucResult(result);
}
}
<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/domain/TriggerLog.java
package com.tiaoling.cloud.job.domain;
import java.util.Date;
public class TriggerLog {
private Integer id;
private Integer jobGroup;
private String jobName;
private String executorAddress;
private String executorHandler;
private String executorParam;
private Date triggerTime;
private String triggerStatus;
private String triggerMsg;
private Date handleTime;
private String handleStatus;
private String handleMsg;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getJobGroup() {
return jobGroup;
}
public void setJobGroup(Integer jobGroup) {
this.jobGroup = jobGroup;
}
public String getJobName() {
return jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
public String getExecutorAddress() {
return executorAddress;
}
public void setExecutorAddress(String executorAddress) {
this.executorAddress = executorAddress;
}
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public Date getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime;
}
public String getTriggerStatus() {
return triggerStatus;
}
public void setTriggerStatus(String triggerStatus) {
this.triggerStatus = triggerStatus;
}
public String getTriggerMsg() {
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
}
public Date getHandleTime() {
return handleTime;
}
public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
}
public String getHandleStatus() {
return handleStatus;
}
public void setHandleStatus(String handleStatus) {
this.handleStatus = handleStatus;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/JobDetailMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.JobDetail;
import com.tiaoling.cloud.job.domain.JobDetailKey;
public interface JobDetailMapper {
int deleteByPrimaryKey(JobDetailKey key);
int insert(JobDetail record);
int insertSelective(JobDetail record);
JobDetail selectByPrimaryKey(JobDetailKey key);
int updateByPrimaryKeySelective(JobDetail record);
int updateByPrimaryKeyWithBLOBs(JobDetail record);
int updateByPrimaryKey(JobDetail record);
}<file_sep>/db/table-tl-conf.sql
CREATE TABLE `tl_conf_group` (
`group_key` varchar(100) NOT NULL,
`group_name` varchar(100) NOT NULL COMMENT '描述',
`isdelete` tinyint(1) DEFAULT '0',
PRIMARY KEY (`group_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `tl_conf_group` VALUES ('default', '默认分组', '0');
-- ----------------------------
-- Table structure for tl_conf_node
-- ----------------------------
CREATE TABLE `tl_conf_node` (
`node_group` varchar(100) NOT NULL COMMENT '分组',
`node_key` varchar(100) NOT NULL COMMENT '配置Key',
`node_value` varchar(512) DEFAULT NULL COMMENT '配置Value',
`node_desc` varchar(100) DEFAULT NULL COMMENT '配置简介',
`isdelete` tinyint(1) DEFAULT NULL,
UNIQUE KEY `u_group_key` (`node_group`,`node_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tl_conf_node
-- ----------------------------
INSERT INTO `tl_conf_node` VALUES ('default', 'key01', '168', '测试配置01', '0');
INSERT INTO `tl_conf_node` VALUES ('default', 'key02', '127.0.0.1:3307', '测试配置02', '0');
<file_sep>/tiaoling-cloud-rpc-core/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">
<parent>
<artifactId>tiaoling-cloud</artifactId>
<groupId>com.itiaoling</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tiaoling-cloud-rpc-core</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<!-- netty -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project><file_sep>/tiaoling-cloud-conf-api/src/main/java/com/tiaoling/cloud/conf/controller/NodeController.java
package com.tiaoling.cloud.conf.controller;
import com.tiaoling.cloud.conf.domain.ConfGroup;
import com.tiaoling.cloud.conf.domain.ConfNode;
import com.tiaoling.cloud.conf.service.intf.ConfNodeService;
import com.tiaoling.cloud.conf.utils.ResultUtil;
import com.tiaoling.cloud.conf.zk.ConfZkClient;
import com.tiaoling.cloud.core.utils.HttpUtils;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
/**
* Created by yhl on 2016/10/11.
*/
@Controller
@RequestMapping(value = "node")
public class NodeController {
private static Logger logger = LoggerFactory.getLogger(NodeController.class);
@Autowired
private ConfNodeService nodeService;
@RequestMapping(value = "add",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String add(HttpServletRequest request, HttpServletResponse response)
{
Map<String,Object> result = new HashMap<>();
int row =0;
int size = request.getContentLength();
InputStream is;
try {
is = request.getInputStream();
byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
String params = new String(reqBodyBytes);
logger.info("tl-conf新增配置结点(node)(node/add)请求报文:" + params);
JSONObject paramJson = JSONObject.fromObject(params);
if(paramJson==null)
{
return ResultUtil.creComErrorResult("配置结点信息不能为空");
}
if(paramJson.get("nodeGroup")==null || paramJson.getString("nodeGroup").trim().equals(""))
{
return ResultUtil.creComErrorResult("分组键(Key)不能为空");
}
if(paramJson.get("nodeKey")==null || paramJson.getString("nodeKey").trim().equals(""))
{
return ResultUtil.creComErrorResult("配置结点Key不能为空");
}
if(paramJson.get("nodeValue")==null || paramJson.getString("nodeValue").trim().equals(""))
{
return ResultUtil.creComErrorResult("配置结点值不能为空");
}
if(paramJson.get("nodeDesc")==null || paramJson.getString("nodeDesc").trim().equals(""))
{
return ResultUtil.creComErrorResult("配置结点描述不能为空");
}
ConfNode node =null;
node = nodeService.getConfNode(paramJson.getString("nodeGroup"),paramJson.getString("nodeKey"));
if(node!=null)
{
return ResultUtil.creComErrorResult("配置结点已经存在");
}
node=new ConfNode();
node.setNodeGroup(paramJson.get("nodeGroup").toString());
node.setNodeKey(paramJson.get("nodeKey").toString());
node.setNodeValue(paramJson.get("nodeValue").toString());
node.setNodeDesc(paramJson.get("nodeDesc").toString());
node.setIsdelete(false);
row = nodeService.insert(node);
result.put("row",row);
String groupKey = ConfZkClient.generateGroupKey(node.getNodeGroup(), node.getNodeKey());
ConfZkClient.setPathDataByKey(groupKey, node.getNodeValue());
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
return ResultUtil.creObjSucResult(result);
}
@RequestMapping(value = "update",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String update(HttpServletRequest request, HttpServletResponse response)
{
Map<String,Object> result = new HashMap<>();
int size = request.getContentLength();
int row =0;
ConfNode node=null;
InputStream is;
try {
is = request.getInputStream();
byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
String params = new String(reqBodyBytes);
logger.info("tl-conf修改配置结点(node)(node/update)请求报文:" + params);
JSONObject paramJson = JSONObject.fromObject(params);
if(paramJson==null)
{
return ResultUtil.creComErrorResult("配置结点信息不能为空");
}
int isRemove =paramJson.getInt("isRemove");
if(paramJson.get("nodeGroup")==null || paramJson.getString("nodeGroup").trim().equals(""))
{
return ResultUtil.creComErrorResult("分组键(Key)不能为空");
}
if(paramJson.get("nodeKey")==null || paramJson.getString("nodeKey").trim().equals(""))
{
return ResultUtil.creComErrorResult("配置结点键(Key)不能为空");
}
node = nodeService.getConfNode(paramJson.getString("nodeGroup").trim(),paramJson.getString("nodeKey").trim());
if(node==null)
{
return ResultUtil.creComErrorResult("配置结点不存在");
}
if(isRemove==0) {
if (paramJson.get("nodeValue") == null || paramJson.getString("nodeValue").trim().equals("")) {
return ResultUtil.creComErrorResult("配置结点值不能为空");
}
if (paramJson.get("nodeDesc") == null || paramJson.getString("nodeDesc").trim().equals("")) {
return ResultUtil.creComErrorResult("配置结点描述不能为空");
}
node.setNodeDesc(paramJson.get("nodeDesc").toString().trim());
node.setNodeValue(paramJson.get("nodeValue").toString().trim());
}
else {
node.setIsdelete(true);
}
row=nodeService.updateConfNode(node);
if(isRemove==0){
String groupKey = ConfZkClient.generateGroupKey(node.getNodeGroup(), node.getNodeKey());
ConfZkClient.setPathDataByKey(groupKey, node.getNodeValue());
}
else
{
String groupKey = ConfZkClient.generateGroupKey(node.getNodeGroup(), node.getNodeKey());
ConfZkClient.deletePathByKey(groupKey);
}
result.put("row",row);
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
return ResultUtil.creObjSucResult(result);
}
}
<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>com.itiaoling</groupId>
<artifactId>tiaoling-cloud</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>tiaoling-cloud-conf-web</module>
<module>tiaoling-cloud-core</module>
<module>tiaoling-cloud-conf-api</module>
<module>tiaoling-cloud-conf-service</module>
<module>tiaoling-cloud-dmps-web</module>
<module>tiaoling-cloud-job-service</module>
<module>tiaoling-cloud-job-api</module>
<module>tiaoling-cloud-rpc-core</module>
</modules>
<packaging>pom</packaging>
<properties>
<junit.version>4.12</junit.version>
<slf4j.version>1.7.21</slf4j.version>
<logback.version>1.1.7</logback.version>
<netty.version>4.0.36.Final</netty.version>
<spring.version>4.3.2.RELEASE</spring.version>
<fastjackson.version>2.8.1</fastjackson.version>
<gson.version>2.7</gson.version>
<json-lib.version>2.4</json-lib.version>
<code.jackson.version>1.9.13</code.jackson.version>
<common-lang3.version>3.4</common-lang3.version>
<mail.version>1.4.7</mail.version>
<protobuf.version>3.0.0</protobuf.version>
<javax.servlet-api.version>2.5</javax.servlet-api.version>
<jsp-api.version>2.1</jsp-api.version>
<druid.version>1.0.26</druid.version>
<mybatis.version>3.3.0</mybatis.version>
<spring-mybatis.version>1.2.5</spring-mybatis.version>
<mysql.version>5.1.38</mysql.version>
<freemarker.version>2.3.23</freemarker.version>
<zk.version>3.4.8</zk.version>
<ehcache.version>2.10.2.2.21</ehcache.version>
</properties>
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/tiaoling-cloud-core/src/main/java/com/tiaoling/cloud/core/framework/controller/BaseController.java
package com.tiaoling.cloud.core.framework.controller;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tiaoling.cloud.core.constant.ComErrorCodeConstants;
import com.tiaoling.cloud.core.exception.BleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/9/30.
*/
public class BaseController {
public static final String VIEW = "view";
public static final String LIST = "list";
public static final String STATUS = "status";
public static final String WARN = "warn";
public static final String SUCCESS = "success";
public static final String ERROR = "error";
public static final String MESSAGE = "message";
public static final String MESSAGES = "messages";
public static final String CONTENT = "content";
private static Logger loger = LoggerFactory.getLogger(BaseController.class);
private static Gson GSON = new GsonBuilder().enableComplexMapKeySerialization()
.setDateFormat("yyyy-MM-dd HH:mm:ss").create();
/**
* AJAX输出,返回null
*
* @param content
* @param type
* @return
*/
public String ajax(HttpServletResponse response, String content, String type) {
try {
response.setContentType(type + ";charset=UTF-8");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
loger.error("IOException:", e);
}
return null;
}
/**
* AJAX输出文本,返回null
*
* @param text
* @return
*/
public String ajaxText(HttpServletResponse response, String text) {
return ajax(response, text, "text/plain");
}
/**
* AJAX输出HTML,返回null
*
* @param html
* @return
*/
public String ajaxHtml(HttpServletResponse response, String html) {
return ajax(response, html, "text/html");
}
/**
* AJAX输出XML,返回null
*
* @param xml
* @return
*/
public String ajaxXml(HttpServletResponse response, String xml) {
return ajax(response, xml, "text/xml");
}
/**
* 根据字符串输出JSON,返回null
*
* @param jsonString
* @return
*/
public String ajaxJson(HttpServletResponse response, String jsonString) {
return ajax(response, jsonString, "text/html");
}
/**
* 根据Map输出JSON,返回null
*
* @param jsonMap
* @return
*/
public String ajaxJson(HttpServletResponse response,
Map<String, String> jsonMap) {
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 输出JSON警告消息,返回null
*
* @param message
* @return
*/
public String ajaxJsonWarnMessage(HttpServletResponse response,
String message) {
Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put(STATUS, WARN);
jsonMap.put(MESSAGE, message);
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 输出JSON警告消息,返回null
*
* @param messages
* @return
*/
public String ajaxJsonWarnMessages(HttpServletResponse response,
List<String> messages) {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put(STATUS, WARN);
jsonMap.put(MESSAGES, messages);
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 输出JSON成功消息,返回null
*
* @param message
* @return
*/
public String ajaxJsonSuccessMessage(HttpServletResponse response,
String message) {
Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put(STATUS, SUCCESS);
jsonMap.put(MESSAGE, message);
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 输出JSON成功消息,返回null
*
* @param messages
* @return
*/
public String ajaxJsonSuccessMessages(HttpServletResponse response,
List<String> messages) {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put(STATUS, SUCCESS);
jsonMap.put(MESSAGES, messages);
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 输出JSON错误消息,返回null
*
* @param message
* @return
*/
public String ajaxJsonErrorMessage(HttpServletResponse response,
String message) {
Map<String, String> jsonMap = new HashMap<String, String>();
jsonMap.put(STATUS, ERROR);
jsonMap.put(MESSAGE, message);
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 输出JSON错误消息,返回null
*
* @param messages
* @return
*/
public String ajaxJsonErrorMessages(HttpServletResponse response,
List<String> messages) {
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put(STATUS, ERROR);
jsonMap.put(MESSAGES, messages);
return ajax(response, GSON.toJson(jsonMap), "text/html");
}
/**
* 设置页面不缓存
*/
public void setResponseNoCache(HttpServletResponse response) {
response.setHeader("progma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setDateHeader("Expires", 0);
}
/**
* 根据Object输出JSON字符串
*/
public String getJson(Object jsonObject) {
return GSON.toJson(jsonObject);
}
/**
* 根据字符串输出JSON,返回null
*
* @param jsonString
* @return
*/
public String ajaxJsonCache(HttpServletResponse response,
String jsonString, String cacheTime) {
return ajaxCache(response, jsonString, "text/html", cacheTime);
}
/**
* AJAX输出,返回null
*
* @param content
* @param type
* @return
*/
public String ajaxCache(HttpServletResponse response, String content,
String type, String cacheTime) {
try {
response.setContentType(type + ";charset=UTF-8");
setCache(response, cacheTime);
response.getWriter().write(content);
response.getWriter().flush();
} catch (IOException e) {
loger.error(e.getMessage());
}
return null;
}
private void setCache(HttpServletResponse response, String cacheTime) {
long now = System.currentTimeMillis();
long cacheTimeLong = Long.parseLong(cacheTime);
response.setDateHeader("Expires", now + cacheTimeLong);
response.setDateHeader("Last-Modified", now - (now % cacheTimeLong));
response.setHeader("Cache-Control", "max-age=" + cacheTime);
response.setHeader("Pragma", "Pragma");
}
/**
* 公共校验参数方法
*
* @Methods Name validateParas
* @param parametersBindingResult
* @param map
* @return boolean
*/
protected boolean validateParas(BindingResult parametersBindingResult,
Map<String, Object> map) {
if (parametersBindingResult.hasErrors()) {
List<FieldError> fes = parametersBindingResult.getFieldErrors();
String checkMsg = fes.get(0).getDefaultMessage();
map.put("success", false);
map.put("errorCode", ComErrorCodeConstants.ErrorCode.VALIDATE_ERROR
.getErrorCode());
map.put("msg", checkMsg);
return false;
}
return true;
}
/**
* spring API请求格式通用处理
*
* @Methods Name handleHttpMessageConversionException
* @param ex
* @return String
*/
@ExceptionHandler({ BleException.class, BindException.class,
MethodArgumentNotValidException.class })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
protected Map<String, Object> handleBusException(Exception ex) {
Map<String, Object> map = new HashMap<String, Object>();
if (ex instanceof BindException) {
BindingResult result = ((BindException) ex).getBindingResult();
List<FieldError> fes = result.getFieldErrors();
String checkMsg = fes.get(0).getDefaultMessage();
map.put("resCode", ComErrorCodeConstants.ErrorCode.VALIDATE_ERROR
.getErrorCode());
map.put("msg", checkMsg);
// MailUtils.SendMailToO2o("极送接口异常信息", "异常类型:BindException" + "异常信息:"
// + checkMsg
// + ExceptionUtils.getStackTrace(ex));
}
// 判断异常类型
else if (ex instanceof MethodArgumentNotValidException) {
// org.springframework.validation.BindException
BindingResult result = ((MethodArgumentNotValidException) ex)
.getBindingResult();
List<FieldError> fes = result.getFieldErrors();
String checkMsg = fes.get(0).getDefaultMessage();
map.put("resCode", ComErrorCodeConstants.ErrorCode.VALIDATE_ERROR
.getErrorCode());
map.put("msg", checkMsg);
// MailUtils.SendMail("<EMAIL>",
// "<EMAIL>", "极送接口异常信息",
// "异常类型:MethodArgumentNotValidException" + "异常信息:" + checkMsg
// + ExceptionUtils.getStackTrace(ex));
} else {
loger.info("throw BleException!cause:{}", ex.getStackTrace());
map.put("resCode", ((BleException) ex).getCode());
map.put("msg", ((BleException) ex).getMessage());
// MailUtils.SendMailToO2o("极送接口异常信息",
// ExceptionUtils.getStackTrace(ex));
}
return map;
}
/**
* spring API请求格式通用处理
*
* @Methods Name handleHttpMessageConversionException
* @param ex
* @return String
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
protected Map<String, Object> handleCommonException(Exception ex) {
Map<String, Object> map = new HashMap<String, Object>();
loger.error("throw Exception!cause:{}", ex.getStackTrace());
if (ex instanceof HttpMessageConversionException) {
map.put("resCode",
ComErrorCodeConstants.ErrorCode.PARA_NORULE_ERROR
.getErrorCode());
// map.put("msg",
// ComErrorCodeConstants.ErrorCode.PARA_NORULE_ERROR.getMemo());
map.put("msg",ex.getMessage());
} else if (ex instanceof HttpMediaTypeException) {
// 请求类型有误
map.put("resCode", "");
// map.put("msg", "请求类型有误!");
map.put("msg",ex.getMessage());
} else if (ex instanceof TypeMismatchException) {
// 请求类型有误
map.put("resCode", "");
// map.put("msg", "参数类型不匹配!");
map.put("msg",ex.getMessage());
} else if (ex instanceof MissingServletRequestParameterException) {
map.put("resCode", "");
// map.put("msg", "请检查必传参数!");
map.put("msg",ex.getMessage());
} else if (ex instanceof BleException) {
map.put("resCode", ((BleException) ex).getCode());
// map.put("msg", ((BleException) ex).getMessage());
map.put("msg",ex.getMessage());
} else {
map.put("resCode",
ComErrorCodeConstants.ErrorCode.SYSTEM_ERROR.getErrorCode());
// map.put("msg", ExceptionUtils.getStackTrace(ex));
map.put("msg",ex.getMessage());
}
// MailUtils.SendMailToO2o("统一异常处理", ExceptionUtils.getStackTrace(ex));
return map;
}
}
<file_sep>/tiaoling-cloud-job-api/src/main/java/com/tiaoling/cloud/job/controller/JobController.java
package com.tiaoling.cloud.job.controller;
import com.tiaoling.cloud.core.utils.HttpUtils;
import com.tiaoling.cloud.job.domain.JobDetail;
import com.tiaoling.cloud.job.domain.TriggerGroup;
import com.tiaoling.cloud.job.domain.TriggerInfo;
import com.tiaoling.cloud.job.service.intf.JobService;
import com.tiaoling.cloud.job.utils.ResultUtil;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/10/11.
*/
@Controller
@RequestMapping("job")
public class JobController {
private static final Logger logger = LoggerFactory.getLogger(JobController.class);
@Autowired
private JobService jobService;
@RequestMapping(value = "group",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String jobInfo(HttpServletRequest request, HttpServletResponse response)
{
List<TriggerGroup> lists = new ArrayList<>();
// int size = request.getContentLength();
// InputStream is;
try {
// is = request.getInputStream();
// byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
// String params = new String(reqBodyBytes);
// logger.info("tl-job获取分组(job)(job/info)请求报文:" + params);
// JSONObject paramJson = JSONObject.fromObject(params);
// ArrayList<String> paramNames = new ArrayList<String>();
lists=jobService.findAllTriggerGroup();
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
if(lists==null || lists.size()==0) return ResultUtil.creObjSucResult(null);
return ResultUtil.creObjSucResultArray(lists);
}
@RequestMapping(value = "list",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String jobList(HttpServletRequest request, HttpServletResponse response)
{
Map<String,Object> result = new HashMap<>();
List<TriggerInfo> lists = new ArrayList<>();
Map<String,Object> params = new HashMap<>();
int count=0;
int size = request.getContentLength();
InputStream is;
try {
is = request.getInputStream();
byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
String paramsStr = new String(reqBodyBytes);
logger.info("tl-job获取分组(job)(job/info)请求报文:" + paramsStr);
JSONObject paramJson = JSONObject.fromObject(paramsStr);
if(paramJson!=null)
{
params.put("start",paramJson.get("start"));
params.put("limit",paramJson.get("limit"));
params.put("jobGroup",paramJson.get("jobGroup"));
params.put("jobName",paramJson.get("jobName"));
lists=jobService.findTriggerInfoPageList(params);
count=jobService.findTriggerInfoPageListCount(params);
}
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
result.put("data",lists);
result.put("count",count);
return ResultUtil.creObjSucResult(result);
}
@RequestMapping(value = "add",method = {RequestMethod.POST},produces = "application/json; charset=utf-8")
@ResponseBody
public String add(HttpServletRequest request, HttpServletResponse response)
{
Map<String,Object> result = new HashMap<>();
int row =0;
int size = request.getContentLength();
InputStream is;
try {
is = request.getInputStream();
byte[] reqBodyBytes = HttpUtils.readBytes(is, size);
String params = new String(reqBodyBytes);
logger.info("tl-job新增TriggerInfo(job)(job/add)请求报文:" + params);
JSONObject paramJson = JSONObject.fromObject(params);
TriggerInfo triggerInfo = new TriggerInfo();
if(paramJson==null)
{
return ResultUtil.creComErrorResult("TriggerInfo信息不能为空");
}
if(paramJson.get("jobGroup")==null || paramJson.getString("jobGroup").trim().equals(""))
{
return ResultUtil.creComErrorResult("分组不能为空");
}
triggerInfo.setJobGroup(paramJson.getInt("jobGroup"));
if(paramJson.get("jobCron")==null || paramJson.getString("jobCron").trim().equals(""))
{
return ResultUtil.creComErrorResult("jobCron不能为空");
}
triggerInfo.setJobCron(paramJson.getString("jobCron"));
if(paramJson.get("author")==null || paramJson.getString("author").trim().equals(""))
{
return ResultUtil.creComErrorResult("author不能为空");
}
triggerInfo.setAuthor(paramJson.getString("author"));
if(paramJson.get("alarmEmail")==null || paramJson.getString("alarmEmail").trim().equals(""))
{
return ResultUtil.creComErrorResult("alarmEmail不能为空");
}
triggerInfo.setAlarmEmail(paramJson.getString("alarmEmail"));
if(paramJson.get("appname")==null || paramJson.getString("appname").trim().equals(""))
{
return ResultUtil.creComErrorResult("appname不能为空");
}
if(paramJson.get("address")==null || paramJson.getString("address").trim().equals(""))
{
return ResultUtil.creComErrorResult("address不能为空");
}
if(paramJson.get("jobName")==null || paramJson.getString("jobName").trim().equals(""))
{
return ResultUtil.creComErrorResult("jobName不能为空");
}
if(paramJson.get("jobParams")==null || paramJson.getString("jobParams").trim().equals(""))
{
return ResultUtil.creComErrorResult("jobParams不能为空");
}
if(paramJson.get("glueSwitch")==null || paramJson.getString("glueSwitch").trim().equals(""))
{
return ResultUtil.creComErrorResult("glueSwitch不能为空");
}
if(paramJson.get("glueSource")==null || paramJson.getString("glueSource").trim().equals(""))
{
return ResultUtil.creComErrorResult("glueSource不能为空");
}
if(paramJson.get("glueRemark")==null || paramJson.getString("glueRemark").trim().equals(""))
{
return ResultUtil.creComErrorResult("glueRemark不能为空");
}
if(paramJson.get("childJobKey")==null || paramJson.getString("childJobKey").trim().equals(""))
{
return ResultUtil.creComErrorResult("childJobKey不能为空");
}
// node = nodeService.getConfNode(paramJson.getString("nodeGroup"),paramJson.getString("nodeKey"));
// if(node!=null)
// {
// return ResultUtil.creComErrorResult("配置结点已经存在");
// }
// node=new ConfNode();
// node.setNodeGroup(paramJson.get("nodeGroup").toString());
// node.setNodeKey(paramJson.get("nodeKey").toString());
// node.setNodeValue(paramJson.get("nodeValue").toString());
// node.setNodeDesc(paramJson.get("nodeDesc").toString());
// node.setIsdelete(false);
// row = nodeService.insert(node);
// result.put("row",row);
// String groupKey = ConfZkClient.generateGroupKey(node.getNodeGroup(), node.getNodeKey());
// ConfZkClient.setPathDataByKey(groupKey, node.getNodeValue());
} catch (IOException e) {
e.printStackTrace();
return ResultUtil.creComErrorResult(e.getMessage());
}
return ResultUtil.creObjSucResult(result);
}
}
<file_sep>/tiaoling-cloud-conf-web/src/main/java/com/tiaoling/cloud/conf/controller/ConfController.java
package com.tiaoling.cloud.conf.controller;
import com.tiaoling.cloud.conf.annotation.PermessionLimit;
import com.tiaoling.cloud.conf.domain.ConfGroup;
import com.tiaoling.cloud.conf.domain.ConfNode;
import com.tiaoling.cloud.conf.utils.CommonPropertiesUtils;
import com.tiaoling.cloud.conf.utils.HttpUtils;
import com.tiaoling.cloud.conf.utils.JsonUtils;
import com.tiaoling.cloud.conf.utils.ReturnT;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/10/9.
*/
@Controller
@RequestMapping("/conf")
public class ConfController {
@RequestMapping("")
@PermessionLimit
public String index(Model model, String znodeKey){
List<ConfGroup> list = new ArrayList<ConfGroup>();
String json ="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("nodeKey",znodeKey);
String doMethod = CommonPropertiesUtils.get("group_list");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
list=JsonUtils.getListDTO(JsonUtils.getJSONString(map.get("Body")),ConfGroup.class);
}
}
model.addAttribute("ConfGroup", list);
return "conf/conf.index";
}
@RequestMapping("/pageList")
@ResponseBody
@PermessionLimit
public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,
@RequestParam(required = false, defaultValue = "10") int length,
String nodeGroup, String nodeKey) {
String json ="";
Map<String,Object> params = new HashMap<String,Object>();
Map<String,Object> result = new HashMap<String,Object>();
params.put("start",start);
params.put("limit",length);
params.put("nodeGroup",nodeGroup);
params.put("nodeKey",nodeKey);
String doMethod = CommonPropertiesUtils.get("node_list");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
HashMap<String,Object> body = (HashMap<String,Object>)map.get("Body");
if(body!=null && body.get("data")!=null)
{
List<ConfNode> nodes = JsonUtils.getListDTO(JsonUtils.getJSONString(body.get("data")),ConfNode.class);
result.put("data",nodes);
result.put("recordsTotal", body.get("count").toString()); // 总记录数
result.put("recordsFiltered", body.get("count").toString()); // 过滤后的总记录数
}
}
}
return result;
}
/**
* get
* @return
*/
@RequestMapping("/delete")
@ResponseBody
@PermessionLimit
public ReturnT<String> delete(String nodeGroup, String nodeKey){
String json ="";
int ret =0;
String message="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("nodeGroup",nodeGroup);
params.put("nodeKey",nodeKey);
params.put("isRemove",1);
params.put("isdelete",1);
String doMethod = CommonPropertiesUtils.get("node_update");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
JSONObject object = JSONObject.fromObject(map.get("Body").toString());
ret = object.getInt("row");
}
else
{
message=map.get("Message").toString();
}
}
return (ret>0)?ReturnT.SUCCESS:new ReturnT<String>(500, message);
}
/**
* create/update
* @return
*/
@RequestMapping("/add")
@ResponseBody
@PermessionLimit
public ReturnT<String> add(ConfNode ConfNode)
{
String json ="";
int ret =0;
String message="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("nodeGroup",ConfNode.getNodeGroup());
params.put("nodeKey",ConfNode.getNodeKey());
params.put("isdelete",0);
params.put("nodeValue",ConfNode.getNodeValue());
params.put("nodeDesc",ConfNode.getNodeDesc());
String doMethod = CommonPropertiesUtils.get("node_add");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
JSONObject object = JSONObject.fromObject(map.get("Body").toString());
ret = object.getInt("row");
}
else
{
message=map.get("Message").toString();
}
}
return (ret>0)?ReturnT.SUCCESS:new ReturnT<String>(500, message);
}
/**
* create/update
* @return
*/
@RequestMapping("/update")
@ResponseBody
@PermessionLimit
public ReturnT<String> update(ConfNode ConfNode)
{
String json ="";
int ret =0;
String message="";
Map<String,Object> params = new HashMap<String,Object>();
params.put("nodeGroup",ConfNode.getNodeGroup());
params.put("nodeKey",ConfNode.getNodeKey());
params.put("isRemove",0);
params.put("isdelete",0);
params.put("nodeValue",ConfNode.getNodeValue());
params.put("nodeDesc",ConfNode.getNodeDesc());
String doMethod = CommonPropertiesUtils.get("node_update");
json = HttpUtils.doPost(CommonPropertiesUtils.get("cloud_conf_api_url") + "/"
+ doMethod, JsonUtils.getJSONString(params));
if(StringUtils.isNotBlank(json))
{
Map<String,Object> map = JsonUtils.toMap(json);
if(map.get("Code").toString().equals("1") && map.get("Body")!=null)
{
JSONObject object = JSONObject.fromObject(map.get("Body").toString());
ret = object.getInt("row");
}
else
{
message=map.get("Message").toString();
}
}
return (ret>0)?ReturnT.SUCCESS:new ReturnT<String>(500, message);
}
}
<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/CronTriggerMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.CronTrigger;
import com.tiaoling.cloud.job.domain.CronTriggerKey;
public interface CronTriggerMapper {
int deleteByPrimaryKey(CronTriggerKey key);
int insert(CronTrigger record);
int insertSelective(CronTrigger record);
CronTrigger selectByPrimaryKey(CronTriggerKey key);
int updateByPrimaryKeySelective(CronTrigger record);
int updateByPrimaryKey(CronTrigger record);
}<file_sep>/tiaoling-cloud-conf-service/src/main/java/com/tiaoling/cloud/conf/persistence/ConfNodeMapper.java
package com.tiaoling.cloud.conf.persistence;
import com.tiaoling.cloud.conf.domain.ConfNode;
import java.util.List;
import java.util.Map;
public interface ConfNodeMapper {
int insert(ConfNode record);
int insertSelective(ConfNode record);
List<ConfNode> pageList(Map<String,Object> params);
int count(Map<String,Object> params);
ConfNode selectByPrimaryKey(Map<String,Object> params);
int update(ConfNode node);
int updateByPrimaryKeySelective(ConfNode node);
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/TriggerLogGlueMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.TriggerLogGlue;
public interface TriggerLogGlueMapper {
int deleteByPrimaryKey(Integer id);
int insert(TriggerLogGlue record);
int insertSelective(TriggerLogGlue record);
TriggerLogGlue selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(TriggerLogGlue record);
int updateByPrimaryKeyWithBLOBs(TriggerLogGlue record);
int updateByPrimaryKey(TriggerLogGlue record);
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/SimpleTriggerMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.SimpleTrigger;
import com.tiaoling.cloud.job.domain.SimpleTriggerKey;
public interface SimpleTriggerMapper {
int deleteByPrimaryKey(SimpleTriggerKey key);
int insert(SimpleTrigger record);
int insertSelective(SimpleTrigger record);
SimpleTrigger selectByPrimaryKey(SimpleTriggerKey key);
int updateByPrimaryKeySelective(SimpleTrigger record);
int updateByPrimaryKey(SimpleTrigger record);
}<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/LockMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.LockKey;
public interface LockMapper {
int deleteByPrimaryKey(LockKey key);
int insert(LockKey record);
int insertSelective(LockKey record);
}<file_sep>/tiaoling-cloud-dmps-web/src/main/java/com/tiaoling/cloud/dmps/utils/JacksonUtil.java
package com.tiaoling.cloud.dmps.utils;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Created by yhl on 2016/10/9.
*/
public class JacksonUtil {
private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
private static final ObjectMapper objectMapper = new ObjectMapper();
public static ObjectMapper getInstance() {
return objectMapper;
}
/**
* bean、array、List、Map --> json
*
* @param obj
* @return
* @throws Exception
*/
public static String writeValueAsString(Object obj) {
try {
return getInstance().writeValueAsString(obj);
} catch (JsonGenerationException e) {
logger.error("", e);
} catch (JsonMappingException e) {
logger.error("", e);
} catch (IOException e) {
logger.error("", e);
}
return null;
}
/**
* string --> bean、Map、List(array)
*
* @param jsonStr
* @param clazz
* @return
* @throws Exception
*/
public static <T> T readValue(String jsonStr, Class<T> clazz) {
try {
return getInstance().readValue(jsonStr, clazz);
} catch (JsonParseException e) {
logger.error("", e);
} catch (JsonMappingException e) {
logger.error("", e);
} catch (IOException e) {
logger.error("", e);
}
return null;
}
public static <T> T readValueRefer(String jsonStr, Class<T> clazz) {
try {
return getInstance().readValue(jsonStr, new TypeReference<T>() { });
} catch (JsonParseException e) {
logger.error("", e);
} catch (JsonMappingException e) {
logger.error("", e);
} catch (IOException e) {
logger.error("", e);
}
return null;
}
}
<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/persistence/FiredTriggerMapper.java
package com.tiaoling.cloud.job.persistence;
import com.tiaoling.cloud.job.domain.FiredTrigger;
import com.tiaoling.cloud.job.domain.FiredTriggerKey;
public interface FiredTriggerMapper {
int deleteByPrimaryKey(FiredTriggerKey key);
int insert(FiredTrigger record);
int insertSelective(FiredTrigger record);
FiredTrigger selectByPrimaryKey(FiredTriggerKey key);
int updateByPrimaryKeySelective(FiredTrigger record);
int updateByPrimaryKey(FiredTrigger record);
}<file_sep>/tiaoling-cloud-core/src/main/java/com/tiaoling/cloud/core/server/Server.java
package com.tiaoling.cloud.core.server;
import com.tiaoling.cloud.core.server.spring.ApplicationContextHolder;
import com.tiaoling.cloud.core.server.spring.DispatcherServletChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by yhl on 2016/9/29.
*/
public class Server {
private static final Logger logger = LoggerFactory.getLogger(Server.class);
private int port;
private ServerBootstrap serverBootstrap;
private DispatcherServletChannelInitializer childHandler;
public Server(int port)
{
this.port=port;
}
public void run() throws Exception
{
if(serverBootstrap!=null) throw new Exception("服务器已启动,请勿重复启动!");
serverBootstrap = new ServerBootstrap();
serverBootstrap.group(new NioEventLoopGroup(),new NioEventLoopGroup()).channel(NioServerSocketChannel.class);
ApplicationContextHolder.init();
childHandler =new DispatcherServletChannelInitializer();
serverBootstrap.childHandler(childHandler);
ChannelFuture future = serverBootstrap.localAddress(port).bind().sync();
future.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
logger.info("服务器启动成功");
}
});
future.channel().closeFuture().sync();
}
public DispatcherServletChannelInitializer getDispatcherServletChannelInitializer()
{
return childHandler;
}
public ServerBootstrap getBootstrap()
{
return serverBootstrap;
}
}
<file_sep>/tiaoling-cloud-conf-service/src/main/java/com/tiaoling/cloud/conf/service/intf/ConfNodeService.java
package com.tiaoling.cloud.conf.service.intf;
import com.tiaoling.cloud.conf.domain.ConfNode;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/10/10.
*/
public interface ConfNodeService {
List<ConfNode> pageList(Map<String,Object> params);
int count(Map<String,Object> params);
ConfNode getConfNode(String groupKey,String nodeKey);
int updateConfNode(ConfNode node);
int insert(ConfNode node);
}
<file_sep>/tiaoling-cloud-dmps-web/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>tiaoling-cloud</artifactId>
<groupId>com.itiaoling</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tiaoling-cloud-dmps-web</artifactId>
<packaging>war</packaging>
<name>tiaoling-cloud-dmps-web Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${spring-mybatis.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>${freemarker.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<!-- gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${fastjackson.version}</version>
</dependency>
</dependencies>
<build>
<finalName>tiaoling-cloud-dmps-web</finalName>
</build>
</project>
<file_sep>/tiaoling-cloud-job-service/src/main/java/com/tiaoling/cloud/job/service/impl/JobServiceImpl.java
package com.tiaoling.cloud.job.service.impl;
import com.tiaoling.cloud.job.domain.TriggerGroup;
import com.tiaoling.cloud.job.domain.TriggerInfo;
import com.tiaoling.cloud.job.persistence.TriggerGroupMapper;
import com.tiaoling.cloud.job.persistence.TriggerInfoMapper;
import com.tiaoling.cloud.job.service.intf.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* Created by yhl on 2016/10/11.
*/
@Service
public class JobServiceImpl implements JobService {
@Autowired
private TriggerGroupMapper triggerGroupMapper;
@Autowired
private TriggerInfoMapper triggerInfoMapper;
@Override
public List<TriggerGroup> findAllTriggerGroup() {
return triggerGroupMapper.findAllTriggerGroup();
}
@Override
public List<TriggerInfo> findTriggerInfoPageList(Map<String, Object> params) {
return triggerInfoMapper.selectPageList(params);
}
@Override
public int findTriggerInfoPageListCount(Map<String, Object> params) {
return triggerInfoMapper.selectPageListCount(params);
}
}
<file_sep>/tiaoling-cloud-conf-service/src/main/java/com/tiaoling/cloud/conf/service/impl/ConfGroupServiceImpl.java
package com.tiaoling.cloud.conf.service.impl;
import com.tiaoling.cloud.conf.domain.ConfGroup;
import com.tiaoling.cloud.conf.persistence.ConfGroupMapper;
import com.tiaoling.cloud.conf.service.intf.ConfGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by yhl on 2016/10/10.
*/
@Service
public class ConfGroupServiceImpl implements ConfGroupService{
@Autowired(required = false)
private ConfGroupMapper groupMapper;
@Override
public List<ConfGroup> findAll() {
return groupMapper.findAll();
}
@Override
public ConfGroup getGroup(String groupKey) {
return groupMapper.selectByPrimaryKey(groupKey);
}
@Override
public int addGroup(ConfGroup group) {
return groupMapper.insert(group);
}
@Override
public int updateGroup(ConfGroup group) {
return groupMapper.updateByPrimaryKeySelective(group);
}
}
<file_sep>/tiaoling-cloud-conf-api/src/main/java/com/tiaoling/cloud/conf/utils/environment/Environment.java
package com.tiaoling.cloud.conf.utils.environment;
import com.tiaoling.cloud.core.utils.PropertyConfigurer;
import java.util.Properties;
/**
* 环境基类
* Created by yhl on 2016/10/10.
*/
public class Environment {
/**
* conf data path in zk
*/
public static final String CONF_DATA_PATH = PropertyConfigurer.getContextProperty("conf_data_path");
/**
* zk address
*/
public static final String ZK_ADDRESS = PropertyConfigurer.getContextProperty("zk_server"); // zk地址:格式 ip1:port,ip2:port,ip3:port
}
<file_sep>/tiaoling-cloud-conf-api/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">
<parent>
<artifactId>tiaoling-cloud</artifactId>
<groupId>com.itiaoling</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>tiaoling-cloud-conf-api</artifactId>
<dependencies>
<!-- netty -->
<dependency>
<groupId>com.itiaoling</groupId>
<artifactId>tiaoling-cloud-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.itiaoling</groupId>
<artifactId>tiaoling-cloud-conf-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--<dependency>-->
<!--<groupId>io.netty</groupId>-->
<!--<artifactId>netty-all</artifactId>-->
<!--<version>${netty.version}</version>-->
<!--</dependency>-->
<!--<!– spring –>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-beans</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-context</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-core</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-context</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-context-support</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-jdbc</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-aspects</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-aop</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-web</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-orm</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-expression</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<!– springmvc –>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-webmvc</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-tx</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.springframework</groupId>-->
<!--<artifactId>spring-test</artifactId>-->
<!--<version>${spring.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>servlet-api</artifactId>-->
<!--<version>${servlet-api.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>javax.servlet-api</artifactId>-->
<!--<version>${javax.servlet-api.version}</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>jsp-api</artifactId>-->
<!--<version>2.0</version>-->
<!--</dependency>-->
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${common-lang3.version}</version>
</dependency>
<!-- mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${mail.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${code.jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${code.jackson.version}</version>
</dependency>
<!-- protobuf -->
<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zk.version}</version>
</dependency>
<!-- encache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.tiaoling.cloud.conf.server.Application</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project><file_sep>/tiaoling-cloud-job-api/src/main/resources/jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/tl-job?Unicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=<PASSWORD>
pool.maxActive=10
pool.maxWait=1000
pool.maxIdle=1
pool.initialSize=2
<file_sep>/tiaoling-cloud-job-api/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">
<parent>
<artifactId>tiaoling-cloud</artifactId>
<groupId>com.itiaoling</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tiaoling-cloud-job-api</artifactId>
<dependencies>
<!-- netty -->
<dependency>
<groupId>com.itiaoling</groupId>
<artifactId>tiaoling-cloud-core</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.itiaoling</groupId>
<artifactId>tiaoling-cloud-job-service</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${common-lang3.version}</version>
</dependency>
<!-- mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>${mail.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${fastjackson.version}</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${code.jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${code.jackson.version}</version>
</dependency>
<!-- protobuf -->
<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zk.version}</version>
</dependency>
<!-- encache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.tiaoling.cloud.job.server.Application</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
|
7d531b3d93a75a3c202ca281d6b20f245185aa9e
|
[
"Java",
"Maven POM",
"SQL",
"INI"
] | 34 |
Maven POM
|
konglingjuanyi/tl-conf
|
e3287951e8f921e4baede055b956025b38d14ccd
|
348fabeaab250acc2b90e73e4946b3f972931ae2
|
refs/heads/main
|
<file_sep># gounchpad
launchpadほしいけど変えないから、キーボードで音をだして遊ぶんだ
# 起動
```go
go run main.go
```
# 停止
q
<file_sep>package jsonutil
import (
"encoding/json"
"gounchpad/pkg/common/chk"
)
// Marshal marshal
func Marshal(v interface{}) string {
b, err := json.Marshal(v)
chk.SE(err)
return string(b)
}
<file_sep>module gounchpad
go 1.15
// require github.com/faiface/beep v1.0.2
replace github.com/faiface/beep => ./lib/beep
require (
github.com/bradhe/stopwatch v0.0.0-20190618212248-a58cccc508ea
github.com/faiface/beep v0.0.0-00010101000000-000000000000
github.com/franela/goblin v0.0.0-20210113153425-413781f5e6c8
github.com/gdamore/tcell v1.4.0
)
<file_sep>package main_test
import (
"fmt"
"log"
"testing"
"github.com/franela/goblin"
"github.com/gdamore/tcell/termbox"
)
// go test -v -count=1 -timeout 30s -run ^Test$ gounchpad
func Test(t *testing.T) {
g := goblin.Goblin(t)
g.Describe("main test", func() {
g.It("aaa", func() {
err := termbox.Init()
if err != nil {
g.Assert(err)
}
defer termbox.Close()
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
switch ev.Key {
case termbox.KeyEsc:
fmt.Println("end")
return
case termbox.KeyArrowUp:
fmt.Println("Up")
case termbox.KeyArrowDown:
fmt.Println("Down")
case termbox.KeyArrowLeft:
fmt.Println("Left")
case termbox.KeyArrowRight:
fmt.Println("Right")
case termbox.KeySpace:
fmt.Println("Space")
default:
fmt.Println("other key:", ev.Key)
}
default:
log.Println("other")
}
}
})
})
}
<file_sep>package main
import (
"fmt"
"gounchpad/pkg/sound"
"github.com/gdamore/tcell/termbox"
)
const coldef = termbox.ColorDefault
func main() {
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
// sound
go sound.Sound(ev.Ch)
// // 画面クリア
termbox.Clear(coldef, coldef)
termbox.SetCell(10, 10, ev.Ch, termbox.ColorWhite, termbox.AttrBold)
termbox.Flush()
// esqで終了
if ev.Key == termbox.KeyEsc {
fmt.Println("bye...")
return
}
}
}
}
<file_sep>package sound
import (
"gounchpad/pkg/common/chk"
"os"
"github.com/faiface/beep"
"github.com/faiface/beep/mp3"
"github.com/faiface/beep/speaker"
)
// 文字に対してなにを鳴らすか?
var soundKeyMap map[rune]string = map[rune]string{
// piano
'a': "./sound/effect/c1.mp3",
's': "./sound/effect/d1.mp3",
'd': "./sound/effect/e1.mp3",
'f': "./sound/effect/f1.mp3",
'g': "./sound/effect/g1.mp3",
'h': "./sound/effect/a1_v3.mp3",
'j': "./sound/effect/b1.mp3",
// 'y': "./sound/effect/a1_v2.mp3",
// 'u': "./sound/effect/a1_v3.mp3",
// drum
'z': "./sound/drum/bass.mp3",
// skrillex
'c': "./sound/skrillex/sound_1_v2.mp3",
'b': "./sound/skrillex/sound_2.mp3",
// 'f': "./sound/skrillex/sound_3.mp3",
// daftpunk
'q': "./sound/daftpunk/daft_punk_1.mp3",
'w': "./sound/daftpunk/daft_punk_2_2.mp3",
'e': "./sound/daftpunk/daft_punk_3.mp3",
}
// オンメモリ再生
var soundBufferMap map[rune]*beep.Buffer
func init() {
// 初期化
err := speaker.Init(44100, 44)
chk.SE(err)
soundBufferMap = make(map[rune]*beep.Buffer, len(soundKeyMap))
for r, filePath := range soundKeyMap {
f, err := os.Open(filePath)
chk.SE(err)
streamer, format, err := mp3.Decode(f)
chk.SE(err)
buffer := beep.NewBuffer(format)
buffer.Append(streamer)
// buffer mapに追加
soundBufferMap[r] = buffer
streamer.Close()
}
}
// Sound 対応する音をならす
func Sound(key rune) {
buffer, exists := soundBufferMap[key]
if !exists {
return
}
done := make(chan bool)
speaker.Play(beep.Seq(buffer.Streamer(0, buffer.Len()), beep.Callback(
func() {
done <- true
},
)))
<-done
}
|
3774fbae5409fca2d39ba740abd103c6e7abe9a3
|
[
"Markdown",
"Go Module",
"Go"
] | 6 |
Markdown
|
sunjin110/gounchpad
|
43f2ed461d03c77b317354c015f2e3d5606a2424
|
4f2c8f827b49eb597647f039867f17857016b15d
|
refs/heads/master
|
<file_sep><?php
namespace Evripay\Payments\Code\Tables;
use Doctrine\ORM\Mapping as ORM;
/**
* Evripay
*
* @ORM\Table(name="evripay_payments", indexes={@ORM\Index(name="payment_id_index", columns={"payment_id"}), @ORM\Index(name="created_by_index", columns={"created_by"}), @ORM\Index(name="modified_by_index", columns={"modified_by"})})
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Payments extends \Kazist\Table\BaseTable {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var integer
*
* @ORM\Column(name="payment_id", type="integer", length=11, nullable=false)
*/
protected $payment_id;
/**
* @var string
*
* @ORM\Column(name="card_status", type="string", length=255, nullable=false)
*/
protected $card_status;
/**
* @var string
*
* @ORM\Column(name="merchant_reference", type="string", length=255, nullable=false)
*/
protected $merchant_reference;
/**
* @var string
*
* @ORM\Column(name="bank_reference", type="string", length=255, nullable=true)
*/
protected $bank_reference;
/**
* @var string
*
* @ORM\Column(name="transaction_data", type="text", nullable=true)
*/
protected $transaction_data;
/**
* @var string
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
protected $description;
/**
* @var integer
*
* @ORM\Column(name="created_by", type="integer", length=11, nullable=false)
*/
protected $created_by;
/**
* @var \DateTime
*
* @ORM\Column(name="date_created", type="datetime", nullable=false)
*/
protected $date_created;
/**
* @var integer
*
* @ORM\Column(name="modified_by", type="integer", length=11, nullable=false)
*/
protected $modified_by;
/**
* @var \DateTime
*
* @ORM\Column(name="date_modified", type="datetime", nullable=false)
*/
protected $date_modified;
/**
* Get id
*
* @return integer
*/
public function getId() {
return $this->id;
}
/**
* Set payment_id
*
* @param integer $paymentId
* @return Evripay
*/
public function setPaymentId($paymentId) {
$this->payment_id = $paymentId;
return $this;
}
/**
* Get payment_id
*
* @return integer
*/
public function getPaymentId() {
return $this->payment_id;
}
/**
* Set card_status
*
* @param string $cardStatus
* @return Evripay
*/
public function setCardStatus($cardStatus) {
$this->card_status = $cardStatus;
return $this;
}
/**
* Get card_status
*
* @return string
*/
public function getCardStatus() {
return $this->card_status;
}
/**
* Set merchant_reference
*
* @param string $merchantReference
* @return Evripay
*/
public function setMerchantReference($merchantReference) {
$this->merchant_reference = $merchantReference;
return $this;
}
/**
* Get merchant_reference
*
* @return string
*/
public function getMerchantReference() {
return $this->merchant_reference;
}
/**
* Set bank_reference
*
* @param string $bankReference
* @return Evripay
*/
public function setBankReference($bankReference) {
$this->bank_reference = $bankReference;
return $this;
}
/**
* Get bank_reference
*
* @return string
*/
public function getBankReference() {
return $this->bank_reference;
}
/**
* Set transaction_data
*
* @param string $transactionData
* @return Evripay
*/
public function setTransactionData($transactionData) {
$this->transaction_data = $transactionData;
return $this;
}
/**
* Get transaction_data
*
* @return string
*/
public function getTransactionData() {
return $this->transaction_data;
}
/**
* Set description
*
* @param string $description
* @return Evripay
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription() {
return $this->description;
}
/**
* Get created_by
*
* @return integer
*/
public function getCreatedBy() {
return $this->created_by;
}
/**
* Get date_created
*
* @return \DateTime
*/
public function getDateCreated() {
return $this->date_created;
}
/**
* Get modified_by
*
* @return integer
*/
public function getModifiedBy() {
return $this->modified_by;
}
/**
* Get date_modified
*
* @return \DateTime
*/
public function getDateModified() {
return $this->date_modified;
}
}
<file_sep><?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Evripay\Payments\Code\Models;
defined('KAZIST') or exit('Not Kazist Framework');
use Kazist\Model\BaseModel;
use Kazist\KazistFactory;
/**
* Description of MarketplaceModel
*
* @author sbc
*/
class PaymentsModel extends BaseModel {
public function notificationTransaction($payment_id) {
$factory = new KazistFactory();
$posted_data['order_id'] = $this->request->request->get('orderid');
$posted_data['card_status'] = $this->request->request->get('Express_Payment_Card_Status');
$posted_data['description'] = $this->request->request->get('Express_Result_Description');
$posted_data['merchant_reference'] = $this->request->request->get('Express_Merchant_Reference');
$posted_data['bank_reference'] = $this->request->request->get('Express_Bank_Reference');
$posted_data['transaction_date'] = $this->request->request->get('Express_Transaction_Date');
$this->saveParams($payment_id, $posted_data);
$status = $posted_data['card_status'];
if ($status == 0) {
parent::successfulTransaction($payment_id);
} elseif ($status == 1 || $status == 2 || $status == 5 || $status == 9) {
$msg = 'Evripay Network Error';
parent::failTransaction($payment_id);
} elseif ($status < 255) {
$msg = 'Evripay Expired or Denied';
parent::failTransaction($payment_id);
} elseif ($status == 255) {
$msg = 'Evripay Required Variables Not Provided.';
parent::failTransaction($payment_id);
} else {
$msg = 'Evripay Denied or Expired';
parent::pendingTransaction($payment_id);
}
}
public function completeTransaction($payment_id) {
$this->notificationTransaction($payment_id);
}
public function cancelTransaction($payment_id) {
parent::cancelTransaction($payment_id);
}
}
|
2ff3d5f2c79376ce2d3e22ff98358925f6cc0947
|
[
"PHP"
] | 2 |
PHP
|
kazist/evripay
|
97ceff5092f2522aec059aa43ad3a82ac0efcc4f
|
2ebf2c18bf256013b08331acb4bbc8f20e400e4a
|
refs/heads/master
|
<repo_name>dimier/velobike<file_sep>/data/convert_weather.py
# coding: utf-8
import re
import csv
import sys
# Пример входных данных:
# Местное время в Санкт-Петербурге,T,Скорость ветра,WW
# 31.10.2014 21:00,3.0,2,Снег непрерывный слабый в срок наблюдения.
# Запуск:
# python convert_weather.py < weather_14.raw.csv > weather_14.csv
dt_re = re.compile('(\d{1,2})\.(\d{1,2})\.(\d{1,4}) (\d{1,2}):(\d{1,2})')
reader = csv.reader(sys.stdin, delimiter=',', quotechar='"')
writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', lineterminator='\n')
header = True
rainy_days = {}
days = []
for row in reader:
if header:
writer.writerow(['dt', 'state', 'description_ru', 'description_en', 'temp'])
header = False
continue
match = dt_re.match(row[0])
if not match:
sys.stderr.write('{}\n'.format(row[0]))
break
(day, month, year, hour, minute) = match.groups()
if len(year) == 2:
year = '20'+year
dt = '{}{:02d}{:02d}'.format(year, int(month), int(day))
conditions = row[3].decode('utf8').lower()
state = ''
if u'дождь' in conditions or u'морось' in conditions or u'снег' in conditions:
state = 'rain'
if hour in ['6', '9', '12', '15', '18'] and state == 'rain':
rainy_days[dt] = row[3]
if hour == '15':
days.append([dt, state, row[3], row[3], row[1]])
for row in sorted(days):
rainy = rainy_days.get(row[0])
if row[1] != 'rain' and rainy:
row[1] = 'rain'
row[2] = rainy
row[3] = rainy
writer.writerow(row)
|
287c5bca2765e1f956564e3538ae6c494f671e66
|
[
"Python"
] | 1 |
Python
|
dimier/velobike
|
f8becf69fc9a750017ccf1832f1eb72631ddf787
|
2d096ca44849b9b2a700274a76746e51c2006b59
|
refs/heads/master
|
<repo_name>zackster/osa-imessage<file_sep>/index.js
const fs = require('fs')
const osa = require('osa2')
const ol = require('one-liner')
const assert = require('assert')
const macosVersion = require('macos-version')
const versions = require('./macos_versions')
const currentVersion = macosVersion()
const messagesDb = require('./lib/messages-db.js')
function warn(str) {
if (!process.env.SUPPRESS_OSA_IMESSAGE_WARNINGS) {
console.error(ol(str))
}
}
if (versions.broken.includes(currentVersion)) {
console.error(
ol(`This version of macOS \(${currentVersion}) is known to be
incompatible with osa-imessage. Please upgrade either
macOS or osa-imessage.`)
)
process.exit(1)
}
if (!versions.working.includes(currentVersion)) {
warn(`This version of macOS \(${currentVersion}) is currently
untested with this version of osa-imessage. Proceed with
caution.`)
}
// Instead of doing something reasonable, Apple stores dates as the number of
// seconds since 01-01-2001 00:00:00 GMT. DATE_OFFSET is the offset in seconds
// between their epoch and unix time
const DATE_OFFSET = 978307200
// Gets the current Apple-style timestamp
function appleTimeNow() {
return Math.floor(Date.now() / 1000) - DATE_OFFSET
}
// Transforms an Apple-style timestamp to a proper unix timestamp
function fromAppleTime(ts) {
if (ts == 0) {
return null
}
// unpackTime returns 0 if the timestamp wasn't packed
// TODO: see `packTimeConditionally`'s comment
if (unpackTime(ts) != 0) {
ts = unpackTime(ts)
}
return new Date((ts + DATE_OFFSET) * 1000)
}
// Since macOS 10.13 High Sierra, some timestamps appear to have extra data
// packed. Dividing by 10^9 seems to get an Apple-style timestamp back.
// According to a StackOverflow user, timestamps now have nanosecond precision
function unpackTime(ts) {
return Math.floor(ts / Math.pow(10, 9))
}
// TODO: Do some kind of database-based detection rather than relying on the
// operating system version
function packTimeConditionally(ts) {
if (macosVersion.is('>=10.13')) {
return ts * Math.pow(10, 9)
} else {
return ts
}
}
// Gets the proper handle string for a contact with the given name
function handleForName(name) {
assert(typeof name == 'string', 'name must be a string')
return osa(name => {
const Messages = Application('Messages')
return Messages.buddies.whose({ name: name })[0].handle()
})(name)
}
// Gets the display name for a given handle
// TODO: support group chats
function nameForHandle(handle) {
assert(typeof handle == 'string', 'handle must be a string')
return osa(handle => {
const Messages = Application('Messages')
return Messages.buddies.whose({ handle: handle }).name()[0]
})(handle)
}
// Sends a message to the given handle
function send(handle, message) {
assert(typeof handle == 'string', 'handle must be a string')
assert(typeof message == 'string', 'message must be a string')
return sendMessageOrFile(handle, message)
}
// Sends the file at the filepath to the given handle
function sendFile(handle, filepath) {
assert(typeof handle == 'string', 'handle must be a string')
assert(typeof filepath == 'string', 'filepath must be a string')
return sendMessageOrFile(handle, filepath, true)
}
// Handles sending a filepath or a message to a given handle
function sendMessageOrFile(handle, messageOrFilepath, isFile) {
return osa((handle, messageOrFilepath, isFile) => {
const Messages = Application('Messages')
let target
try {
target = Messages.buddies.whose({ handle: handle })[0]
} catch (e) {}
try {
target = Messages.textChats.byId('iMessage;+;' + handle)()
} catch (e) {}
let message = messageOrFilepath
// If a string filepath was provided, we need to convert it to an
// osascript file object.
// This must be done in the osa context to have acess to Path
if (isFile) {
message = Path(messageOrFilepath)
}
try {
return Messages.send(message, { to: target })
} catch (e) {
throw new Error(`no thread with handle '${handle}'`)
}
})(handle, messageOrFilepath, isFile)
}
let emitter = null
let emittedMsgs = []
function listen() {
// If listen has already been run, return the existing emitter
if (emitter != null) {
return emitter
}
// Create an EventEmitter
emitter = new (require('events')).EventEmitter()
let last = packTimeConditionally(appleTimeNow() - 5)
let bail = false
function check() {
const db = messagesDb.open()
const query = db.prepare(`
SELECT
guid,
id as handle,
text,
date,
date_read,
is_from_me,
cache_roomnames
FROM message
LEFT OUTER JOIN handle ON message.handle_id = handle.ROWID
WHERE date >= ${last}`);
last = packTimeConditionally(appleTimeNow())
try {
const messages = query.all()
messages.forEach(msg => {
if (emittedMsgs[msg.guid]) return
emittedMsgs[msg.guid] = true
emitter.emit('message', {
guid: msg.guid,
text: msg.text,
handle: msg.handle,
group: msg.cache_roomnames,
fromMe: !!msg.is_from_me,
date: fromAppleTime(msg.date),
dateRead: fromAppleTime(msg.date_read),
})
})
setTimeout(check, 1000)
} catch (err) {
bail = true
emitter.emit('error', err)
warn(`sqlite returned an error while polling for new messages!
bailing out of poll routine for safety. new messages will
not be detected`)
}
}
if (bail) return
check()
return emitter
}
function getRecentChats(limit = 10) {
const db = messagesDb.open()
const query = db.prepare(`
SELECT
guid as id,
chat_identifier as recipientId,
service_name as serviceName,
room_name as roomName,
display_name as displayName
FROM chat
JOIN chat_handle_join ON chat_handle_join.chat_id = chat.ROWID
JOIN handle ON handle.ROWID = chat_handle_join.handle_id
ORDER BY handle.rowid DESC
LIMIT ${limit}`);
const chats = query.all();
return chats
}
module.exports = {
send,
sendFile,
listen,
handleForName,
nameForHandle,
getRecentChats,
SUPPRESS_WARNINGS: false,
}
<file_sep>/example/log.js
const imessage = require('..')
imessage.listen().on('message', (msg) => {
console.log(msg)
})
<file_sep>/readme.md
osa-imessage
====



[](https://github.com/prettier/prettier)
> Send and receive iMessages through nodejs
Installation
===
**Requires OSX 10.10 Yosemite**
```bash
npm install osa-imessage --save
```
Usage
====
Be sure to require `osa-imessage`:
```js
const imessage = require('osa-imessage')
```
**Send a message**
```js
imessage.send('+15555555555', 'Hello World!')
```
**Send a file**
```js
imessage.sendFile('+15555555555', '/Absolute/Path/To/Your/File.jpg')
```
**Receive messages**
```js
imessage.listen().on('message', (msg) => {
if (!msg.fromMe) console.log(`'${msg.text}' from ${msg.handle}`)
})
```
**Send message to name**
```js
imessage.handleForName('<NAME>').then(handle => {
imessage.send(handle, 'Hello')
})
```
**Send message to group**
```js
imessage.send('chat000000000000000000', 'Hello everyone!')
```
**Get recent chats**
```js
imessage.getRecentChats(20) // Defaults to 10
```
API
===
### Send a message
`send(handle, text) -> Promise`
Sends a message to the specified handle.
**handle**
Type: `string`
The user or group to send the message to, in one of the following forms:
- phone number (`+1555555555`)
- email address (`<EMAIL>`)
- group chat id (`chat000000000000000000`)
**text**
Type: `string`
The content of the message to be sent.
**return**
Type: `Promise<>`
A promise that resolves when the message is sent, and rejects if the
message fails to send.
### Receive messages
`listen([interval]) -> EventEmitter`
Begins polling the local iMessage database for new messages.
**interval**
Type: `number`
The rate at which the database is polled for new messages. Defaults to the minimum of `1000 ms`.
**return**
Type: [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter)
An event emitter with that listeners can be attached to. Currently it only has the `message` event.
Example message event
```js
{
text: 'Hello, world!',
handle: '+15555555555',
group: null,
date: new Date('2017-04-11T02:02:13.000Z'),
fromMe: false,
guid: 'F79E08A5-4314-43B2-BB32-563A2BB76177'
}
```
Example *group* message event
```js
{
text: 'Hello, group!',
handle: '+15555555555',
group: 'chat000000000000000000',
date: new Date('2017-04-23T21:18:54.943Z'),
fromMe: false,
guid: 'DCFE0EEC-F9DD-48FC-831B-06C75B76ACB9'
}
```
### Get a handle for a given name
`handleForName(name) -> Promise<handle>`
**name**
Type: `string`
The full name of the desired contact, as displayed in `Messages.app`.
**return**
Type: `Promise<string>`
A promise that resolves with the `handle` of the contact, or rejects if nobody was found.
### Get the name associated with a given handle
`nameForHandle(handle) -> Promise<name>`
**handle**
Type: `string`
The handle of a contact.
**return**
Type: `Promise<string>`
A promise that resolved with the full name of the desired contact, as displayed in `Messages.app`.
### Get recents chats
`getRecentChats(limit) -> Promise`
**limit**
Type: `integer`
Amount of recent chats to return.
**return**
Type: `Promise`
A promise that resolves with an array of chats.
<file_sep>/example/echo.js
const imessage = require('..')
imessage.listen().on('message', (msg) => {
if (!msg.fromMe) {
imessage.send(msg.handle, msg.text)
}
})
<file_sep>/lib/messages-db.js
const sqlite = require('better-sqlite3');
const dbPath = `${process.env.HOME}/Library/Messages/chat.db`
const OPEN_READONLY = true
let db
function open() {
if (db) return db
console.log("Attempting to open DB with dbPath: ", dbPath);
db = new sqlite(dbPath, { readonly: OPEN_READONLY })
return db
}
let isClosing;
function cleanUp() {
if (db && !isClosing) {
isClosing = true
db.close()
}
}
process.on('exit', cleanUp)
process.on('uncaughtException', cleanUp)
module.exports = {
open,
}
|
603649ffc773ef7c1c64aedcfb206d0975963fef
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
zackster/osa-imessage
|
8f90ba009f49a67b5bf882cf82a8287b48442bb8
|
1e3ae3ff74a2f5ea011af04b827f3bf4e186b6fd
|
refs/heads/master
|
<file_sep>from bs4 import BeautifulSoup
import urllib.request as urllib2
from bs4.element import Comment
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
import re
import os
def write_links():
url = 'https://caprivacy.github.io/caprivacy/full/'
file_name = 'privacy_links.txt'
file = open(file_name, 'w')
page = urllib2.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
for link in soup.find_all('a'):
x = link.get('href')
if x != "":
file.write(x + '\n')
def tag_visible(element):
if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
return False
if isinstance(element, Comment):
return False
return True
def get_text_from_link(link):
soup = BeautifulSoup(link, 'html.parser')
texts = soup.findAll(text=True)
visible_texts = filter(tag_visible, texts)
return u" ".join(t.strip() for t in visible_texts)
def write_policies_to_files(fileName, directoryName):
f = open(fileName, "r")
for url in f.readlines():
try:
company = re.findall('https://(.*).co', url)
print(company)
company2 = re.findall('www.(.*)', company[0])
print(company2)
if len(company2) > 0:
company = company2
fileName = directoryName + '/' + company[0] + '.txt'
file = open(fileName,'w')
driver = webdriver.Chrome(executable_path='/Users/abbykrishnan/Downloads/chromedriver')
driver.get(url)
time.sleep(3)
html = driver.page_source
file.write(get_text_from_link(html))
except:
print("problem with", url)
continue
def print_exs(key_word, directoryName):
print(f"Examples for {key_word}")
for fileName in os.listdir('/Users/abbykrishnan/Documents/Spring 2020/Research/privacy-crawler/' + directoryName):
if '.DS_Store' in fileName:
continue
file = open(directoryName + '/' + fileName,'r')
data = file.read().replace('\n', '')
regex = '[^.]*{term}[^.]*\.'.format(term=key_word)
results = re.findall(regex, data.lower())
if len(results) > 0:
print (fileName, results)
print("\n")
if __name__ == '__main__':
# write_policies_to_files("broker_links.txt", "brokers_privacy_texts")
print_exs("financial incentive", "brokers_privacy_texts")
print_exs("discrimination", "brokers_privacy_texts")
print_exs("ssn", "brokers_privacy_texts")
<file_sep># Privacy Policy Scraper
To understand CCPA, it is helpful to have reference to the legal text of many companies
You can put any text into the `print_exs` function and see examples of it in the different policies
Also, change the directories in the functions to ones on your computer.
|
3b4040ef30c070a3a708bebb6961b25c12bdc554
|
[
"Markdown",
"Python"
] | 2 |
Python
|
abbykrish/privacy-policy-scraper
|
314917b3c284a0d7b3c246e39d44783191a20ded
|
1bf47675e005ada83456bf51bfd6a155a974c248
|
refs/heads/master
|
<repo_name>cha63506/wyatt_hosts<file_sep>/template/base_template.ini
127.0.0.1 localhost
# 屏蔽Adobe激活服务器:
0.0.0.0 activate.adobe.com
0.0.0.0 practivate.adobe.com
0.0.0.0 ereg.adobe.com
0.0.0.0 activate.wip3.adobe.com
0.0.0.0 wip3.adobe.com
0.0.0.0 3dns-3.adobe.com
0.0.0.0 3dns-2.adobe.com
0.0.0.0 adobe-dns.adobe.com
0.0.0.0 adobe-dns-2.adobe.com
0.0.0.0 adobe-dns-3.adobe.com
0.0.0.0 ereg.wip3.adobe.com
0.0.0.0 activate-sea.adobe.com
0.0.0.0 wwis-dubc1-vip60.adobe.com
0.0.0.0 activate-sjc0.adobe.com
# Adobe CS6
127.0.0.1 lmlicenses.wip4.adobe.com
127.0.0.1 lm.licenses.adobe.com
# 屏蔽Parallels Desktop 7激活服务器:
127.0.0.1 pd6.blist.parallels.com
127.0.0.1 pd7.blist.parallels.com
127.0.0.1 pdfm7.blist.parallels.com
127.0.0.1 registration.parallels.com
127.0.0.1 parallels.com
127.0.0.1 update.parallels.com
# EasyAcc reverse proxy
172.16.31.10 e.easya.cc
172.16.31.10 r.easya.cc
172.16.58.3 t.easya.cc
192.168.1.150 it.easya.cc
<file_sep>/README.md
# Update at 2014-08-14
因为 GFW 的变化, 修改 hosts 已经不靠谱了~ 换方法吧~
# Update at 2014-06-06
最近 GFW 进行了改变使得 Hosts 翻墙越发的困难, 这个方法应该会被放弃了, 转而使用 PAC + Shadowsocks 了
# Wyatt 自己的 hosts 文件
ps: 脚本需要在 \*nix 下执行, 因为 curb 使用了 curl
## 五块内容:
* Google 服务
* Amazon 静态内容网站
* Apple 服务
* alibaba 中使用的 akamai cdn
* Adobe 屏蔽
* 广告屏蔽
外加在 Chrome 浏览器下使用 [HTTPS
Everywhere](https://chrome.google.com/webstore/detail/https-everywhere/gcbommkclmclpchllfjekcdonpmejbdp?hl=en-US) 速度刚刚滴
## 使用 (\*nix)
1. git clone git://github.com/wppurking/wyatt_hosts.git
2. cd wyatt_hosts
3. bundle install
4. ruby just-ping.rb
5. cp hosts.1[tab] /etc/hosts
That`s all
<file_sep>/just-ping.rb
require 'bundler'
Bundler.require
# Thanks for
# hostsx https://code.google.com/p/hostsx/
# MVPS http://winhelp2002.mvps.org/
# huhamhire-hosts https://code.google.com/p/huhamhire-hosts/
# smarthosts https://code.google.com/p/smarthosts/
# google-hosts https://github.com/txthinking/google-hosts
puts "According to right now pc Location to find domain ip:"
puts "Need Block Ads? (y/n)"
ads = gets.strip == 'y'
puts "Need Ads!" if ads
# 解析要抓取的网站
SITES = open('./sites').read.strip.lines.to_a.map { |l| l.strip }.select { |line| !line.index('#') }
# 最终的 IP 地址
IPS = {}
def just_ping(site)
# 注意, 需要当前的 PC 的网络进入 VPN 后才会最有效, 不然在本地被防火墙给重置了 dns 就无法处理了
cmd = "dig #{site} -4 +short +tcp @8.8.8.8"
result = `#{cmd}`
result.split("\n").select { |ip| ip =~ /^\d{2,3}/}.first
end
SITES.map do |site|
sleep(0.02)
Thread.new do
begin
puts "#{Thread.current} begin..."
IPS[site] = just_ping site.strip
puts "#{Thread.current} end..."
rescue Exception => e
puts "#{e.message} #{site}"
IPS[site] = ''
end
end
end.each(&:join)
base_template = open('template/base_template.ini').read
google_template = open('template/google_template.ini').read
apple_template = open('template/apple_template.ini').read
alibaba_template = open('template/alibaba_template.ini').read
# 组织广告
mvps_tempalte = ads ? HTTParty.get('http://winhelp2002.mvps.org/hosts.txt', headers: {'Accept-Encoding' => 'gzip'}).body.strip : ""
IPS.each do |k, v|
next if v == ''
# google
if k.include?('g.cn')
google_template = google_template.gsub(/\$\{1\}/, v)
google_template = google_template.gsub(/\$\{2\}/, v)
google_template = google_template.gsub(/\$\{4\}/, v)
google_template = google_template.gsub(/\$\{5\}/, v)
elsif k.include?('gstatic')
google_template = google_template.gsub(/\$\{3\}/, v)
# apple
elsif k.include?('icloud')
apple_template = apple_template.gsub(/\$\{1\}/, v)
elsif k.include?('swcdn')
apple_template = apple_template.gsub(/\$\{2\}/, v)
elsif k.include?('mzstatic')
apple_template = apple_template.gsub(/\$\{3\}/, v)
elsif k.include?('phobos')
# 172.16.31.10 fastest
# 192.168.3.11 taiwan
apple_template = apple_template.gsub(/\$\{4\}/, v)
elsif k.include?('edgekey')
apple_template = apple_template.gsub(/\$\{5\}/, v)
elsif k.include?('metrics')
apple_template = apple_template.gsub(/\$\{6\}/, v)
# alibaba
elsif k.include?('aliimg')
alibaba_template = alibaba_template.gsub(/\$\{1\}/, v)
# amazon
else
base_template << "#{v} #{k}\n"
end
puts "#{k} #{v}"
end
all_in_one = base_template << "\n" << google_template << "\n" << apple_template << "\n" << alibaba_template << "\n" << "\n\n" << mvps_tempalte
open("hosts.#{Time.now.to_i}.txt", 'w') { |io| io.write(all_in_one) }
<file_sep>/template/apple_template.ini
#Apple Services Begin
${4} a1.phobos.apple.com
${4} a2.phobos.apple.com
${4} a3.phobos.apple.com
${4} a4.phobos.apple.com
${4} a5.phobos.apple.com
${4} a6.phobos.apple.com
${4} a7.phobos.apple.com
${4} a8.phobos.apple.com
${4} a9.phobos.apple.com
${4} a10.phobos.apple.com
${4} a11.phobos.apple.com
${4} a12.phobos.apple.com
${4} a13.phobos.apple.com
${4} a14.phobos.apple.com
${4} a15.phobos.apple.com
${4} a16.phobos.apple.com
${4} a17.phobos.apple.com
${4} a18.phobos.apple.com
${4} a19.phobos.apple.com
${4} a20.phobos.apple.com
${4} a21.phobos.apple.com
${4} a22.phobos.apple.com
${4} a23.phobos.apple.com
${4} a24.phobos.apple.com
${4} a25.phobos.apple.com
${4} a26.phobos.apple.com
${4} a27.phobos.apple.com
${4} a28.phobos.apple.com
${4} a29.phobos.apple.com
${4} a30.phobos.apple.com
${4} a31.phobos.apple.com
${4} a32.phobos.apple.com
${4} a33.phobos.apple.com
${4} a34.phobos.apple.com
${4} a35.phobos.apple.com
${4} a36.phobos.apple.com
${4} a37.phobos.apple.com
${4} a38.phobos.apple.com
${4} a39.phobos.apple.com
${4} a40.phobos.apple.com
${4} a41.phobos.apple.com
${4} a42.phobos.apple.com
${4} a43.phobos.apple.com
${4} a44.phobos.apple.com
${4} a45.phobos.apple.com
${4} a46.phobos.apple.com
${4} a47.phobos.apple.com
${4} a48.phobos.apple.com
${4} a49.phobos.apple.com
${4} a50.phobos.apple.com
${4} a51.phobos.apple.com
${4} a52.phobos.apple.com
${4} a53.phobos.apple.com
${4} a54.phobos.apple.com
${4} a55.phobos.apple.com
${4} a56.phobos.apple.com
${4} a57.phobos.apple.com
${4} a58.phobos.apple.com
${4} a59.phobos.apple.com
${4} a60.phobos.apple.com
${4} a61.phobos.apple.com
${4} a62.phobos.apple.com
${4} a63.phobos.apple.com
${4} a64.phobos.apple.com
${4} a65.phobos.apple.com
${4} a66.phobos.apple.com
${4} a67.phobos.apple.com
${4} a68.phobos.apple.com
${4} a69.phobos.apple.com
${4} a70.phobos.apple.com
${4} a71.phobos.apple.com
${4} a72.phobos.apple.com
${4} a73.phobos.apple.com
${4} a74.phobos.apple.com
${4} a75.phobos.apple.com
${4} a76.phobos.apple.com
${4} a77.phobos.apple.com
${4} a78.phobos.apple.com
${4} a79.phobos.apple.com
${4} a80.phobos.apple.com
${4} a81.phobos.apple.com
${4} a82.phobos.apple.com
${4} a83.phobos.apple.com
${4} a84.phobos.apple.com
${4} a85.phobos.apple.com
${4} a86.phobos.apple.com
${4} a87.phobos.apple.com
${4} a88.phobos.apple.com
${4} a89.phobos.apple.com
${4} a90.phobos.apple.com
${4} a91.phobos.apple.com
${4} a92.phobos.apple.com
${4} a93.phobos.apple.com
${4} a94.phobos.apple.com
${4} a95.phobos.apple.com
${4} a96.phobos.apple.com
${4} a97.phobos.apple.com
${4} a98.phobos.apple.com
${4} a99.phobos.apple.com
${4} a100.phobos.apple.com
${4} a101.phobos.apple.com
${4} a102.phobos.apple.com
${4} a103.phobos.apple.com
${4} a104.phobos.apple.com
${4} a105.phobos.apple.com
${4} a106.phobos.apple.com
${4} a107.phobos.apple.com
${4} a108.phobos.apple.com
${4} a109.phobos.apple.com
${4} a110.phobos.apple.com
${4} a111.phobos.apple.com
${4} a112.phobos.apple.com
${4} a113.phobos.apple.com
${4} a114.phobos.apple.com
${4} a115.phobos.apple.com
${4} a116.phobos.apple.com
${4} a117.phobos.apple.com
${4} a118.phobos.apple.com
${4} a119.phobos.apple.com
${4} a120.phobos.apple.com
${4} a121.phobos.apple.com
${4} a122.phobos.apple.com
${4} a123.phobos.apple.com
${4} a124.phobos.apple.com
${4} a125.phobos.apple.com
${4} a126.phobos.apple.com
${4} a127.phobos.apple.com
${4} a128.phobos.apple.com
${4} a129.phobos.apple.com
${4} a130.phobos.apple.com
${4} a131.phobos.apple.com
${4} a132.phobos.apple.com
${4} a133.phobos.apple.com
${4} a134.phobos.apple.com
${4} a135.phobos.apple.com
${4} a136.phobos.apple.com
${4} a137.phobos.apple.com
${4} a138.phobos.apple.com
${4} a139.phobos.apple.com
${4} a140.phobos.apple.com
${4} a141.phobos.apple.com
${4} a142.phobos.apple.com
${4} a143.phobos.apple.com
${4} a144.phobos.apple.com
${4} a145.phobos.apple.com
${4} a146.phobos.apple.com
${4} a147.phobos.apple.com
${4} a148.phobos.apple.com
${4} a149.phobos.apple.com
${4} a150.phobos.apple.com
${4} a151.phobos.apple.com
${4} a152.phobos.apple.com
${4} a153.phobos.apple.com
${4} a154.phobos.apple.com
${4} a155.phobos.apple.com
${4} a156.phobos.apple.com
${4} a157.phobos.apple.com
${4} a158.phobos.apple.com
${4} a159.phobos.apple.com
${4} a160.phobos.apple.com
${4} a161.phobos.apple.com
${4} a162.phobos.apple.com
${4} a163.phobos.apple.com
${4} a164.phobos.apple.com
${4} a165.phobos.apple.com
${4} a166.phobos.apple.com
${4} a167.phobos.apple.com
${4} a168.phobos.apple.com
${4} a169.phobos.apple.com
${4} a170.phobos.apple.com
${4} a171.phobos.apple.com
${4} a172.phobos.apple.com
${4} a173.phobos.apple.com
${4} a174.phobos.apple.com
${4} a175.phobos.apple.com
${4} a176.phobos.apple.com
${4} a177.phobos.apple.com
${4} a178.phobos.apple.com
${4} a179.phobos.apple.com
${4} a180.phobos.apple.com
${4} a181.phobos.apple.com
${4} a182.phobos.apple.com
${4} a183.phobos.apple.com
${4} a184.phobos.apple.com
${4} a185.phobos.apple.com
${4} a186.phobos.apple.com
${4} a187.phobos.apple.com
${4} a188.phobos.apple.com
${4} a189.phobos.apple.com
${4} a190.phobos.apple.com
${4} a191.phobos.apple.com
${4} a192.phobos.apple.com
${4} a193.phobos.apple.com
${4} a194.phobos.apple.com
${4} a195.phobos.apple.com
${4} a196.phobos.apple.com
${4} a197.phobos.apple.com
${4} a198.phobos.apple.com
${4} a199.phobos.apple.com
${4} a200.phobos.apple.com
${4} a201.phobos.apple.com
${4} a202.phobos.apple.com
${4} a203.phobos.apple.com
${4} a204.phobos.apple.com
${4} a205.phobos.apple.com
${4} a206.phobos.apple.com
${4} a207.phobos.apple.com
${4} a208.phobos.apple.com
${4} a209.phobos.apple.com
${4} a210.phobos.apple.com
${4} a211.phobos.apple.com
${4} a212.phobos.apple.com
${4} a213.phobos.apple.com
${4} a214.phobos.apple.com
${4} a215.phobos.apple.com
${4} a216.phobos.apple.com
${4} a217.phobos.apple.com
${4} a218.phobos.apple.com
${4} a219.phobos.apple.com
${4} a220.phobos.apple.com
${4} a221.phobos.apple.com
${4} a222.phobos.apple.com
${4} a223.phobos.apple.com
${4} a224.phobos.apple.com
${4} a225.phobos.apple.com
${4} a226.phobos.apple.com
${4} a227.phobos.apple.com
${4} a228.phobos.apple.com
${4} a229.phobos.apple.com
${4} a230.phobos.apple.com
${4} a231.phobos.apple.com
${4} a232.phobos.apple.com
${4} a233.phobos.apple.com
${4} a234.phobos.apple.com
${4} a235.phobos.apple.com
${4} a236.phobos.apple.com
${4} a237.phobos.apple.com
${4} a238.phobos.apple.com
${4} a239.phobos.apple.com
${4} a240.phobos.apple.com
${4} a241.phobos.apple.com
${4} a242.phobos.apple.com
${4} a243.phobos.apple.com
${4} a244.phobos.apple.com
${4} a245.phobos.apple.com
${4} a246.phobos.apple.com
${4} a247.phobos.apple.com
${4} a248.phobos.apple.com
${4} a249.phobos.apple.com
${4} a250.phobos.apple.com
${4} a251.phobos.apple.com
${4} a252.phobos.apple.com
${4} a253.phobos.apple.com
${4} a254.phobos.apple.com
${4} a255.phobos.apple.com
${4} a256.phobos.apple.com
${4} a257.phobos.apple.com
${4} a258.phobos.apple.com
${4} a259.phobos.apple.com
${4} a260.phobos.apple.com
${4} a261.phobos.apple.com
${4} a262.phobos.apple.com
${4} a263.phobos.apple.com
${4} a264.phobos.apple.com
${4} a265.phobos.apple.com
${4} a266.phobos.apple.com
${4} a267.phobos.apple.com
${4} a268.phobos.apple.com
${4} a269.phobos.apple.com
${4} a270.phobos.apple.com
${4} a271.phobos.apple.com
${4} a272.phobos.apple.com
${4} a273.phobos.apple.com
${4} a274.phobos.apple.com
${4} a275.phobos.apple.com
${4} a276.phobos.apple.com
${4} a277.phobos.apple.com
${4} a278.phobos.apple.com
${4} a279.phobos.apple.com
${4} a280.phobos.apple.com
${4} a281.phobos.apple.com
${4} a282.phobos.apple.com
${4} a283.phobos.apple.com
${4} a284.phobos.apple.com
${4} a285.phobos.apple.com
${4} a286.phobos.apple.com
${4} a287.phobos.apple.com
${4} a288.phobos.apple.com
${4} a289.phobos.apple.com
${4} a290.phobos.apple.com
${4} a291.phobos.apple.com
${4} a292.phobos.apple.com
${4} a293.phobos.apple.com
${4} a294.phobos.apple.com
${4} a295.phobos.apple.com
${4} a296.phobos.apple.com
${4} a297.phobos.apple.com
${4} a298.phobos.apple.com
${4} a299.phobos.apple.com
${4} a300.phobos.apple.com
${4} a301.phobos.apple.com
${4} a302.phobos.apple.com
${4} a303.phobos.apple.com
${4} a304.phobos.apple.com
${4} a305.phobos.apple.com
${4} a306.phobos.apple.com
${4} a307.phobos.apple.com
${4} a308.phobos.apple.com
${4} a309.phobos.apple.com
${4} a310.phobos.apple.com
${4} a311.phobos.apple.com
${4} a312.phobos.apple.com
${4} a313.phobos.apple.com
${4} a314.phobos.apple.com
${4} a315.phobos.apple.com
${4} a316.phobos.apple.com
${4} a317.phobos.apple.com
${4} a318.phobos.apple.com
${4} a319.phobos.apple.com
${4} a320.phobos.apple.com
${4} a321.phobos.apple.com
${4} a322.phobos.apple.com
${4} a323.phobos.apple.com
${4} a324.phobos.apple.com
${4} a325.phobos.apple.com
${4} a326.phobos.apple.com
${4} a327.phobos.apple.com
${4} a328.phobos.apple.com
${4} a329.phobos.apple.com
${4} a330.phobos.apple.com
${4} a331.phobos.apple.com
${4} a332.phobos.apple.com
${4} a333.phobos.apple.com
${4} a334.phobos.apple.com
${4} a335.phobos.apple.com
${4} a336.phobos.apple.com
${4} a337.phobos.apple.com
${4} a338.phobos.apple.com
${4} a339.phobos.apple.com
${4} a340.phobos.apple.com
${4} a341.phobos.apple.com
${4} a342.phobos.apple.com
${4} a343.phobos.apple.com
${4} a344.phobos.apple.com
${4} a345.phobos.apple.com
${4} a346.phobos.apple.com
${4} a347.phobos.apple.com
${4} a348.phobos.apple.com
${4} a349.phobos.apple.com
${4} a350.phobos.apple.com
${4} a351.phobos.apple.com
${4} a352.phobos.apple.com
${4} a353.phobos.apple.com
${4} a354.phobos.apple.com
${4} a355.phobos.apple.com
${4} a356.phobos.apple.com
${4} a357.phobos.apple.com
${4} a358.phobos.apple.com
${4} a359.phobos.apple.com
${4} a360.phobos.apple.com
${4} a361.phobos.apple.com
${4} a362.phobos.apple.com
${4} a363.phobos.apple.com
${4} a364.phobos.apple.com
${4} a365.phobos.apple.com
${4} a366.phobos.apple.com
${4} a367.phobos.apple.com
${4} a368.phobos.apple.com
${4} a369.phobos.apple.com
${4} a370.phobos.apple.com
${4} a371.phobos.apple.com
${4} a372.phobos.apple.com
${4} a373.phobos.apple.com
${4} a374.phobos.apple.com
${4} a375.phobos.apple.com
${4} a376.phobos.apple.com
${4} a377.phobos.apple.com
${4} a378.phobos.apple.com
${4} a379.phobos.apple.com
${4} a380.phobos.apple.com
${4} a381.phobos.apple.com
${4} a382.phobos.apple.com
${4} a383.phobos.apple.com
${4} a384.phobos.apple.com
${4} a385.phobos.apple.com
${4} a386.phobos.apple.com
${4} a387.phobos.apple.com
${4} a388.phobos.apple.com
${4} a389.phobos.apple.com
${4} a390.phobos.apple.com
${4} a391.phobos.apple.com
${4} a392.phobos.apple.com
${4} a393.phobos.apple.com
${4} a394.phobos.apple.com
${4} a395.phobos.apple.com
${4} a396.phobos.apple.com
${4} a397.phobos.apple.com
${4} a398.phobos.apple.com
${4} a399.phobos.apple.com
${4} a400.phobos.apple.com
${4} a401.phobos.apple.com
${4} a402.phobos.apple.com
${4} a403.phobos.apple.com
${4} a404.phobos.apple.com
${4} a405.phobos.apple.com
${4} a406.phobos.apple.com
${4} a407.phobos.apple.com
${4} a408.phobos.apple.com
${4} a409.phobos.apple.com
${4} a410.phobos.apple.com
${4} a411.phobos.apple.com
${4} a412.phobos.apple.com
${4} a413.phobos.apple.com
${4} a414.phobos.apple.com
${4} a415.phobos.apple.com
${4} a416.phobos.apple.com
${4} a417.phobos.apple.com
${4} a418.phobos.apple.com
${4} a419.phobos.apple.com
${4} a420.phobos.apple.com
${4} a421.phobos.apple.com
${4} a422.phobos.apple.com
${4} a423.phobos.apple.com
${4} a424.phobos.apple.com
${4} a425.phobos.apple.com
${4} a426.phobos.apple.com
${4} a427.phobos.apple.com
${4} a428.phobos.apple.com
${4} a429.phobos.apple.com
${4} a430.phobos.apple.com
${4} a431.phobos.apple.com
${4} a432.phobos.apple.com
${4} a433.phobos.apple.com
${4} a434.phobos.apple.com
${4} a435.phobos.apple.com
${4} a436.phobos.apple.com
${4} a437.phobos.apple.com
${4} a438.phobos.apple.com
${4} a439.phobos.apple.com
${4} a440.phobos.apple.com
${4} a441.phobos.apple.com
${4} a442.phobos.apple.com
${4} a443.phobos.apple.com
${4} a444.phobos.apple.com
${4} a445.phobos.apple.com
${4} a446.phobos.apple.com
${4} a447.phobos.apple.com
${4} a448.phobos.apple.com
${4} a449.phobos.apple.com
${4} a450.phobos.apple.com
${4} a451.phobos.apple.com
${4} a452.phobos.apple.com
${4} a453.phobos.apple.com
${4} a454.phobos.apple.com
${4} a455.phobos.apple.com
${4} a456.phobos.apple.com
${4} a457.phobos.apple.com
${4} a458.phobos.apple.com
${4} a459.phobos.apple.com
${4} a460.phobos.apple.com
${4} a461.phobos.apple.com
${4} a462.phobos.apple.com
${4} a463.phobos.apple.com
${4} a464.phobos.apple.com
${4} a465.phobos.apple.com
${4} a466.phobos.apple.com
${4} a467.phobos.apple.com
${4} a468.phobos.apple.com
${4} a469.phobos.apple.com
${4} a470.phobos.apple.com
${4} a471.phobos.apple.com
${4} a472.phobos.apple.com
${4} a473.phobos.apple.com
${4} a474.phobos.apple.com
${4} a475.phobos.apple.com
${4} a476.phobos.apple.com
${4} a477.phobos.apple.com
${4} a478.phobos.apple.com
${4} a479.phobos.apple.com
${4} a480.phobos.apple.com
${4} a481.phobos.apple.com
${4} a482.phobos.apple.com
${4} a483.phobos.apple.com
${4} a484.phobos.apple.com
${4} a485.phobos.apple.com
${4} a486.phobos.apple.com
${4} a487.phobos.apple.com
${4} a488.phobos.apple.com
${4} a489.phobos.apple.com
${4} a490.phobos.apple.com
${4} a491.phobos.apple.com
${4} a492.phobos.apple.com
${4} a493.phobos.apple.com
${4} a494.phobos.apple.com
${4} a495.phobos.apple.com
${4} a496.phobos.apple.com
${4} a497.phobos.apple.com
${4} a498.phobos.apple.com
${4} a499.phobos.apple.com
${4} a500.phobos.apple.com
${4} a501.phobos.apple.com
${4} a502.phobos.apple.com
${4} a503.phobos.apple.com
${4} a504.phobos.apple.com
${4} a505.phobos.apple.com
${4} a506.phobos.apple.com
${4} a507.phobos.apple.com
${4} a508.phobos.apple.com
${4} a509.phobos.apple.com
${4} a510.phobos.apple.com
${4} a511.phobos.apple.com
${4} a512.phobos.apple.com
${4} a513.phobos.apple.com
${4} a514.phobos.apple.com
${4} a515.phobos.apple.com
${4} a516.phobos.apple.com
${4} a517.phobos.apple.com
${4} a518.phobos.apple.com
${4} a519.phobos.apple.com
${4} a520.phobos.apple.com
${4} a521.phobos.apple.com
${4} a522.phobos.apple.com
${4} a523.phobos.apple.com
${4} a524.phobos.apple.com
${4} a525.phobos.apple.com
${4} a526.phobos.apple.com
${4} a527.phobos.apple.com
${4} a528.phobos.apple.com
${4} a529.phobos.apple.com
${4} a530.phobos.apple.com
${4} a531.phobos.apple.com
${4} a532.phobos.apple.com
${4} a533.phobos.apple.com
${4} a534.phobos.apple.com
${4} a535.phobos.apple.com
${4} a536.phobos.apple.com
${4} a537.phobos.apple.com
${4} a538.phobos.apple.com
${4} a539.phobos.apple.com
${4} a540.phobos.apple.com
${4} a541.phobos.apple.com
${4} a542.phobos.apple.com
${4} a543.phobos.apple.com
${4} a544.phobos.apple.com
${4} a545.phobos.apple.com
${4} a546.phobos.apple.com
${4} a547.phobos.apple.com
${4} a548.phobos.apple.com
${4} a549.phobos.apple.com
${4} a550.phobos.apple.com
${4} a551.phobos.apple.com
${4} a552.phobos.apple.com
${4} a553.phobos.apple.com
${4} a554.phobos.apple.com
${4} a555.phobos.apple.com
${4} a556.phobos.apple.com
${4} a557.phobos.apple.com
${4} a558.phobos.apple.com
${4} a559.phobos.apple.com
${4} a560.phobos.apple.com
${4} a561.phobos.apple.com
${4} a562.phobos.apple.com
${4} a563.phobos.apple.com
${4} a564.phobos.apple.com
${4} a565.phobos.apple.com
${4} a566.phobos.apple.com
${4} a567.phobos.apple.com
${4} a568.phobos.apple.com
${4} a569.phobos.apple.com
${4} a570.phobos.apple.com
${4} a571.phobos.apple.com
${4} a572.phobos.apple.com
${4} a573.phobos.apple.com
${4} a574.phobos.apple.com
${4} a575.phobos.apple.com
${4} a576.phobos.apple.com
${4} a577.phobos.apple.com
${4} a578.phobos.apple.com
${4} a579.phobos.apple.com
${4} a580.phobos.apple.com
${4} a581.phobos.apple.com
${4} a582.phobos.apple.com
${4} a583.phobos.apple.com
${4} a584.phobos.apple.com
${4} a585.phobos.apple.com
${4} a586.phobos.apple.com
${4} a587.phobos.apple.com
${4} a588.phobos.apple.com
${4} a589.phobos.apple.com
${4} a590.phobos.apple.com
${4} a591.phobos.apple.com
${4} a592.phobos.apple.com
${4} a593.phobos.apple.com
${4} a594.phobos.apple.com
${4} a595.phobos.apple.com
${4} a596.phobos.apple.com
${4} a597.phobos.apple.com
${4} a598.phobos.apple.com
${4} a599.phobos.apple.com
${4} a600.phobos.apple.com
${4} a601.phobos.apple.com
${4} a602.phobos.apple.com
${4} a603.phobos.apple.com
${4} a604.phobos.apple.com
${4} a605.phobos.apple.com
${4} a606.phobos.apple.com
${4} a607.phobos.apple.com
${4} a608.phobos.apple.com
${4} a609.phobos.apple.com
${4} a610.phobos.apple.com
${4} a611.phobos.apple.com
${4} a612.phobos.apple.com
${4} a613.phobos.apple.com
${4} a614.phobos.apple.com
${4} a615.phobos.apple.com
${4} a616.phobos.apple.com
${4} a617.phobos.apple.com
${4} a618.phobos.apple.com
${4} a619.phobos.apple.com
${4} a620.phobos.apple.com
${4} a621.phobos.apple.com
${4} a622.phobos.apple.com
${4} a623.phobos.apple.com
${4} a624.phobos.apple.com
${4} a625.phobos.apple.com
${4} a626.phobos.apple.com
${4} a627.phobos.apple.com
${4} a628.phobos.apple.com
${4} a629.phobos.apple.com
${4} a630.phobos.apple.com
${4} a631.phobos.apple.com
${4} a632.phobos.apple.com
${4} a633.phobos.apple.com
${4} a634.phobos.apple.com
${4} a635.phobos.apple.com
${4} a636.phobos.apple.com
${4} a637.phobos.apple.com
${4} a638.phobos.apple.com
${4} a639.phobos.apple.com
${4} a640.phobos.apple.com
${4} a641.phobos.apple.com
${4} a642.phobos.apple.com
${4} a643.phobos.apple.com
${4} a644.phobos.apple.com
${4} a645.phobos.apple.com
${4} a646.phobos.apple.com
${4} a647.phobos.apple.com
${4} a648.phobos.apple.com
${4} a649.phobos.apple.com
${4} a650.phobos.apple.com
${4} a651.phobos.apple.com
${4} a652.phobos.apple.com
${4} a653.phobos.apple.com
${4} a654.phobos.apple.com
${4} a655.phobos.apple.com
${4} a656.phobos.apple.com
${4} a657.phobos.apple.com
${4} a658.phobos.apple.com
${4} a659.phobos.apple.com
${4} a660.phobos.apple.com
${4} a661.phobos.apple.com
${4} a662.phobos.apple.com
${4} a663.phobos.apple.com
${4} a664.phobos.apple.com
${4} a665.phobos.apple.com
${4} a666.phobos.apple.com
${4} a667.phobos.apple.com
${4} a668.phobos.apple.com
${4} a669.phobos.apple.com
${4} a670.phobos.apple.com
${4} a671.phobos.apple.com
${4} a672.phobos.apple.com
${4} a673.phobos.apple.com
${4} a674.phobos.apple.com
${4} a675.phobos.apple.com
${4} a676.phobos.apple.com
${4} a677.phobos.apple.com
${4} a678.phobos.apple.com
${4} a679.phobos.apple.com
${4} a680.phobos.apple.com
${4} a681.phobos.apple.com
${4} a682.phobos.apple.com
${4} a683.phobos.apple.com
${4} a684.phobos.apple.com
${4} a685.phobos.apple.com
${4} a686.phobos.apple.com
${4} a687.phobos.apple.com
${4} a688.phobos.apple.com
${4} a689.phobos.apple.com
${4} a690.phobos.apple.com
${4} a691.phobos.apple.com
${4} a692.phobos.apple.com
${4} a693.phobos.apple.com
${4} a694.phobos.apple.com
${4} a695.phobos.apple.com
${4} a696.phobos.apple.com
${4} a697.phobos.apple.com
${4} a698.phobos.apple.com
${4} a699.phobos.apple.com
${4} a700.phobos.apple.com
${4} a701.phobos.apple.com
${4} a702.phobos.apple.com
${4} a703.phobos.apple.com
${4} a704.phobos.apple.com
${4} a705.phobos.apple.com
${4} a706.phobos.apple.com
${4} a707.phobos.apple.com
${4} a708.phobos.apple.com
${4} a709.phobos.apple.com
${4} a710.phobos.apple.com
${4} a711.phobos.apple.com
${4} a712.phobos.apple.com
${4} a713.phobos.apple.com
${4} a714.phobos.apple.com
${4} a715.phobos.apple.com
${4} a716.phobos.apple.com
${4} a717.phobos.apple.com
${4} a718.phobos.apple.com
${4} a719.phobos.apple.com
${4} a720.phobos.apple.com
${4} a721.phobos.apple.com
${4} a722.phobos.apple.com
${4} a723.phobos.apple.com
${4} a724.phobos.apple.com
${4} a725.phobos.apple.com
${4} a726.phobos.apple.com
${4} a727.phobos.apple.com
${4} a728.phobos.apple.com
${4} a729.phobos.apple.com
${4} a730.phobos.apple.com
${4} a731.phobos.apple.com
${4} a732.phobos.apple.com
${4} a733.phobos.apple.com
${4} a734.phobos.apple.com
${4} a735.phobos.apple.com
${4} a736.phobos.apple.com
${4} a737.phobos.apple.com
${4} a738.phobos.apple.com
${4} a739.phobos.apple.com
${4} a740.phobos.apple.com
${4} a741.phobos.apple.com
${4} a742.phobos.apple.com
${4} a743.phobos.apple.com
${4} a744.phobos.apple.com
${4} a745.phobos.apple.com
${4} a746.phobos.apple.com
${4} a747.phobos.apple.com
${4} a748.phobos.apple.com
${4} a749.phobos.apple.com
${4} a750.phobos.apple.com
${4} a751.phobos.apple.com
${4} a752.phobos.apple.com
${4} a753.phobos.apple.com
${4} a754.phobos.apple.com
${4} a755.phobos.apple.com
${4} a756.phobos.apple.com
${4} a757.phobos.apple.com
${4} a758.phobos.apple.com
${4} a759.phobos.apple.com
${4} a760.phobos.apple.com
${4} a761.phobos.apple.com
${4} a762.phobos.apple.com
${4} a763.phobos.apple.com
${4} a764.phobos.apple.com
${4} a765.phobos.apple.com
${4} a766.phobos.apple.com
${4} a767.phobos.apple.com
${4} a768.phobos.apple.com
${4} a769.phobos.apple.com
${4} a770.phobos.apple.com
${4} a771.phobos.apple.com
${4} a772.phobos.apple.com
${4} a773.phobos.apple.com
${4} a774.phobos.apple.com
${4} a775.phobos.apple.com
${4} a776.phobos.apple.com
${4} a777.phobos.apple.com
${4} a778.phobos.apple.com
${4} a779.phobos.apple.com
${4} a780.phobos.apple.com
${4} a781.phobos.apple.com
${4} a782.phobos.apple.com
${4} a783.phobos.apple.com
${4} a784.phobos.apple.com
${4} a785.phobos.apple.com
${4} a786.phobos.apple.com
${4} a787.phobos.apple.com
${4} a788.phobos.apple.com
${4} a789.phobos.apple.com
${4} a790.phobos.apple.com
${4} a791.phobos.apple.com
${4} a792.phobos.apple.com
${4} a793.phobos.apple.com
${4} a794.phobos.apple.com
${4} a795.phobos.apple.com
${4} a796.phobos.apple.com
${4} a797.phobos.apple.com
${4} a798.phobos.apple.com
${4} a799.phobos.apple.com
${4} a800.phobos.apple.com
${4} a801.phobos.apple.com
${4} a802.phobos.apple.com
${4} a803.phobos.apple.com
${4} a804.phobos.apple.com
${4} a805.phobos.apple.com
${4} a806.phobos.apple.com
${4} a807.phobos.apple.com
${4} a808.phobos.apple.com
${4} a809.phobos.apple.com
${4} a810.phobos.apple.com
${4} a811.phobos.apple.com
${4} a812.phobos.apple.com
${4} a813.phobos.apple.com
${4} a814.phobos.apple.com
${4} a815.phobos.apple.com
${4} a816.phobos.apple.com
${4} a817.phobos.apple.com
${4} a818.phobos.apple.com
${4} a819.phobos.apple.com
${4} a820.phobos.apple.com
${4} a821.phobos.apple.com
${4} a822.phobos.apple.com
${4} a823.phobos.apple.com
${4} a824.phobos.apple.com
${4} a825.phobos.apple.com
${4} a826.phobos.apple.com
${4} a827.phobos.apple.com
${4} a828.phobos.apple.com
${4} a829.phobos.apple.com
${4} a830.phobos.apple.com
${4} a831.phobos.apple.com
${4} a832.phobos.apple.com
${4} a833.phobos.apple.com
${4} a834.phobos.apple.com
${4} a835.phobos.apple.com
${4} a836.phobos.apple.com
${4} a837.phobos.apple.com
${4} a838.phobos.apple.com
${4} a839.phobos.apple.com
${4} a840.phobos.apple.com
${4} a841.phobos.apple.com
${4} a842.phobos.apple.com
${4} a843.phobos.apple.com
${4} a844.phobos.apple.com
${4} a845.phobos.apple.com
${4} a846.phobos.apple.com
${4} a847.phobos.apple.com
${4} a848.phobos.apple.com
${4} a849.phobos.apple.com
${4} a850.phobos.apple.com
${4} a851.phobos.apple.com
${4} a852.phobos.apple.com
${4} a853.phobos.apple.com
${4} a854.phobos.apple.com
${4} a855.phobos.apple.com
${4} a856.phobos.apple.com
${4} a857.phobos.apple.com
${4} a858.phobos.apple.com
${4} a859.phobos.apple.com
${4} a860.phobos.apple.com
${4} a861.phobos.apple.com
${4} a862.phobos.apple.com
${4} a863.phobos.apple.com
${4} a864.phobos.apple.com
${4} a865.phobos.apple.com
${4} a866.phobos.apple.com
${4} a867.phobos.apple.com
${4} a868.phobos.apple.com
${4} a869.phobos.apple.com
${4} a870.phobos.apple.com
${4} a871.phobos.apple.com
${4} a872.phobos.apple.com
${4} a873.phobos.apple.com
${4} a874.phobos.apple.com
${4} a875.phobos.apple.com
${4} a876.phobos.apple.com
${4} a877.phobos.apple.com
${4} a878.phobos.apple.com
${4} a879.phobos.apple.com
${4} a880.phobos.apple.com
${4} a881.phobos.apple.com
${4} a882.phobos.apple.com
${4} a883.phobos.apple.com
${4} a884.phobos.apple.com
${4} a885.phobos.apple.com
${4} a886.phobos.apple.com
${4} a887.phobos.apple.com
${4} a888.phobos.apple.com
${4} a889.phobos.apple.com
${4} a890.phobos.apple.com
${4} a891.phobos.apple.com
${4} a892.phobos.apple.com
${4} a893.phobos.apple.com
${4} a894.phobos.apple.com
${4} a895.phobos.apple.com
${4} a896.phobos.apple.com
${4} a897.phobos.apple.com
${4} a898.phobos.apple.com
${4} a899.phobos.apple.com
${4} a900.phobos.apple.com
${4} a901.phobos.apple.com
${4} a902.phobos.apple.com
${4} a903.phobos.apple.com
${4} a904.phobos.apple.com
${4} a905.phobos.apple.com
${4} a906.phobos.apple.com
${4} a907.phobos.apple.com
${4} a908.phobos.apple.com
${4} a909.phobos.apple.com
${4} a910.phobos.apple.com
${4} a911.phobos.apple.com
${4} a912.phobos.apple.com
${4} a913.phobos.apple.com
${4} a914.phobos.apple.com
${4} a915.phobos.apple.com
${4} a916.phobos.apple.com
${4} a917.phobos.apple.com
${4} a918.phobos.apple.com
${4} a919.phobos.apple.com
${4} a920.phobos.apple.com
${4} a921.phobos.apple.com
${4} a922.phobos.apple.com
${4} a923.phobos.apple.com
${4} a924.phobos.apple.com
${4} a925.phobos.apple.com
${4} a926.phobos.apple.com
${4} a927.phobos.apple.com
${4} a928.phobos.apple.com
${4} a929.phobos.apple.com
${4} a930.phobos.apple.com
${4} a931.phobos.apple.com
${4} a932.phobos.apple.com
${4} a933.phobos.apple.com
${4} a934.phobos.apple.com
${4} a935.phobos.apple.com
${4} a936.phobos.apple.com
${4} a937.phobos.apple.com
${4} a938.phobos.apple.com
${4} a939.phobos.apple.com
${4} a940.phobos.apple.com
${4} a941.phobos.apple.com
${4} a942.phobos.apple.com
${4} a943.phobos.apple.com
${4} a944.phobos.apple.com
${4} a945.phobos.apple.com
${4} a946.phobos.apple.com
${4} a947.phobos.apple.com
${4} a948.phobos.apple.com
${4} a949.phobos.apple.com
${4} a950.phobos.apple.com
${4} a951.phobos.apple.com
${4} a952.phobos.apple.com
${4} a953.phobos.apple.com
${4} a954.phobos.apple.com
${4} a955.phobos.apple.com
${4} a956.phobos.apple.com
${4} a957.phobos.apple.com
${4} a958.phobos.apple.com
${4} a959.phobos.apple.com
${4} a960.phobos.apple.com
${4} a961.phobos.apple.com
${4} a962.phobos.apple.com
${4} a963.phobos.apple.com
${4} a964.phobos.apple.com
${4} a965.phobos.apple.com
${4} a966.phobos.apple.com
${4} a967.phobos.apple.com
${4} a968.phobos.apple.com
${4} a969.phobos.apple.com
${4} a970.phobos.apple.com
${4} a971.phobos.apple.com
${4} a972.phobos.apple.com
${4} a973.phobos.apple.com
${4} a974.phobos.apple.com
${4} a975.phobos.apple.com
${4} a976.phobos.apple.com
${4} a977.phobos.apple.com
${4} a978.phobos.apple.com
${4} a979.phobos.apple.com
${4} a980.phobos.apple.com
${4} a981.phobos.apple.com
${4} a982.phobos.apple.com
${4} a983.phobos.apple.com
${4} a984.phobos.apple.com
${4} a985.phobos.apple.com
${4} a986.phobos.apple.com
${4} a987.phobos.apple.com
${4} a988.phobos.apple.com
${4} a989.phobos.apple.com
${4} a990.phobos.apple.com
${4} a991.phobos.apple.com
${4} a992.phobos.apple.com
${4} a993.phobos.apple.com
${4} a994.phobos.apple.com
${4} a995.phobos.apple.com
${4} a996.phobos.apple.com
${4} a997.phobos.apple.com
${4} a998.phobos.apple.com
${4} a999.phobos.apple.com
${4} a1000.phobos.apple.com
${4} a1001.phobos.apple.com
${4} a1002.phobos.apple.com
${4} a1003.phobos.apple.com
${4} a1004.phobos.apple.com
${4} a1005.phobos.apple.com
${4} a1006.phobos.apple.com
${4} a1007.phobos.apple.com
${4} a1008.phobos.apple.com
${4} a1009.phobos.apple.com
${4} a1010.phobos.apple.com
${4} a1011.phobos.apple.com
${4} a1012.phobos.apple.com
${4} a1013.phobos.apple.com
${4} a1014.phobos.apple.com
${4} a1015.phobos.apple.com
${4} a1016.phobos.apple.com
${4} a1017.phobos.apple.com
${4} a1018.phobos.apple.com
${4} a1019.phobos.apple.com
${4} a1020.phobos.apple.com
${4} a1021.phobos.apple.com
${4} a1022.phobos.apple.com
${4} a1023.phobos.apple.com
${4} a1024.phobos.apple.com
${4} a1025.phobos.apple.com
${4} a1026.phobos.apple.com
${4} a1027.phobos.apple.com
${4} a1028.phobos.apple.com
${4} a1029.phobos.apple.com
${4} a1030.phobos.apple.com
${4} a1031.phobos.apple.com
${4} a1032.phobos.apple.com
${4} a1033.phobos.apple.com
${4} a1034.phobos.apple.com
${4} a1035.phobos.apple.com
${4} a1036.phobos.apple.com
${4} a1037.phobos.apple.com
${4} a1038.phobos.apple.com
${4} a1039.phobos.apple.com
${4} a1040.phobos.apple.com
${4} a1041.phobos.apple.com
${4} a1042.phobos.apple.com
${4} a1043.phobos.apple.com
${4} a1044.phobos.apple.com
${4} a1045.phobos.apple.com
${4} a1046.phobos.apple.com
${4} a1047.phobos.apple.com
${4} a1048.phobos.apple.com
${4} a1049.phobos.apple.com
${4} a1050.phobos.apple.com
${4} a1051.phobos.apple.com
${4} a1052.phobos.apple.com
${4} a1053.phobos.apple.com
${4} a1054.phobos.apple.com
${4} a1055.phobos.apple.com
${4} a1056.phobos.apple.com
${4} a1057.phobos.apple.com
${4} a1058.phobos.apple.com
${4} a1059.phobos.apple.com
${4} a1060.phobos.apple.com
${4} a1061.phobos.apple.com
${4} a1062.phobos.apple.com
${4} a1063.phobos.apple.com
${4} a1064.phobos.apple.com
${4} a1065.phobos.apple.com
${4} a1066.phobos.apple.com
${4} a1067.phobos.apple.com
${4} a1068.phobos.apple.com
${4} a1069.phobos.apple.com
${4} a1070.phobos.apple.com
${4} a1071.phobos.apple.com
${4} a1072.phobos.apple.com
${4} a1073.phobos.apple.com
${4} a1074.phobos.apple.com
${4} a1075.phobos.apple.com
${4} a1076.phobos.apple.com
${4} a1077.phobos.apple.com
${4} a1078.phobos.apple.com
${4} a1079.phobos.apple.com
${4} a1080.phobos.apple.com
${4} a1081.phobos.apple.com
${4} a1082.phobos.apple.com
${4} a1083.phobos.apple.com
${4} a1084.phobos.apple.com
${4} a1085.phobos.apple.com
${4} a1086.phobos.apple.com
${4} a1087.phobos.apple.com
${4} a1088.phobos.apple.com
${4} a1089.phobos.apple.com
${4} a1090.phobos.apple.com
${4} a1091.phobos.apple.com
${4} a1092.phobos.apple.com
${4} a1093.phobos.apple.com
${4} a1094.phobos.apple.com
${4} a1095.phobos.apple.com
${4} a1096.phobos.apple.com
${4} a1097.phobos.apple.com
${4} a1098.phobos.apple.com
${4} a1099.phobos.apple.com
${4} a1100.phobos.apple.com
${4} a1101.phobos.apple.com
${4} a1102.phobos.apple.com
${4} a1103.phobos.apple.com
${4} a1104.phobos.apple.com
${4} a1105.phobos.apple.com
${4} a1106.phobos.apple.com
${4} a1107.phobos.apple.com
${4} a1108.phobos.apple.com
${4} a1109.phobos.apple.com
${4} a1110.phobos.apple.com
${4} a1111.phobos.apple.com
${4} a1112.phobos.apple.com
${4} a1113.phobos.apple.com
${4} a1114.phobos.apple.com
${4} a1115.phobos.apple.com
${4} a1116.phobos.apple.com
${4} a1117.phobos.apple.com
${4} a1118.phobos.apple.com
${4} a1119.phobos.apple.com
${4} a1120.phobos.apple.com
${4} a1121.phobos.apple.com
${4} a1122.phobos.apple.com
${4} a1123.phobos.apple.com
${4} a1124.phobos.apple.com
${4} a1125.phobos.apple.com
${4} a1126.phobos.apple.com
${4} a1127.phobos.apple.com
${4} a1128.phobos.apple.com
${4} a1129.phobos.apple.com
${4} a1130.phobos.apple.com
${4} a1131.phobos.apple.com
${4} a1132.phobos.apple.com
${4} a1133.phobos.apple.com
${4} a1134.phobos.apple.com
${4} a1135.phobos.apple.com
${4} a1136.phobos.apple.com
${4} a1137.phobos.apple.com
${4} a1138.phobos.apple.com
${4} a1139.phobos.apple.com
${4} a1140.phobos.apple.com
${4} a1141.phobos.apple.com
${4} a1142.phobos.apple.com
${4} a1143.phobos.apple.com
${4} a1144.phobos.apple.com
${4} a1145.phobos.apple.com
${4} a1146.phobos.apple.com
${4} a1147.phobos.apple.com
${4} a1148.phobos.apple.com
${4} a1149.phobos.apple.com
${4} a1150.phobos.apple.com
${4} a1151.phobos.apple.com
${4} a1152.phobos.apple.com
${4} a1153.phobos.apple.com
${4} a1154.phobos.apple.com
${4} a1155.phobos.apple.com
${4} a1156.phobos.apple.com
${4} a1157.phobos.apple.com
${4} a1158.phobos.apple.com
${4} a1159.phobos.apple.com
${4} a1160.phobos.apple.com
${4} a1161.phobos.apple.com
${4} a1162.phobos.apple.com
${4} a1163.phobos.apple.com
${4} a1164.phobos.apple.com
${4} a1165.phobos.apple.com
${4} a1166.phobos.apple.com
${4} a1167.phobos.apple.com
${4} a1168.phobos.apple.com
${4} a1169.phobos.apple.com
${4} a1170.phobos.apple.com
${4} a1171.phobos.apple.com
${4} a1172.phobos.apple.com
${4} a1173.phobos.apple.com
${4} a1174.phobos.apple.com
${4} a1175.phobos.apple.com
${4} a1176.phobos.apple.com
${4} a1177.phobos.apple.com
${4} a1178.phobos.apple.com
${4} a1179.phobos.apple.com
${4} a1180.phobos.apple.com
${4} a1181.phobos.apple.com
${4} a1182.phobos.apple.com
${4} a1183.phobos.apple.com
${4} a1184.phobos.apple.com
${4} a1185.phobos.apple.com
${4} a1186.phobos.apple.com
${4} a1187.phobos.apple.com
${4} a1188.phobos.apple.com
${4} a1189.phobos.apple.com
${4} a1190.phobos.apple.com
${4} a1191.phobos.apple.com
${4} a1192.phobos.apple.com
${4} a1193.phobos.apple.com
${4} a1194.phobos.apple.com
${4} a1195.phobos.apple.com
${4} a1196.phobos.apple.com
${4} a1197.phobos.apple.com
${4} a1198.phobos.apple.com
${4} a1199.phobos.apple.com
${4} a1200.phobos.apple.com
${4} a1201.phobos.apple.com
${4} a1202.phobos.apple.com
${4} a1203.phobos.apple.com
${4} a1204.phobos.apple.com
${4} a1205.phobos.apple.com
${4} a1206.phobos.apple.com
${4} a1207.phobos.apple.com
${4} a1208.phobos.apple.com
${4} a1209.phobos.apple.com
${4} a1210.phobos.apple.com
${4} a1211.phobos.apple.com
${4} a1212.phobos.apple.com
${4} a1213.phobos.apple.com
${4} a1214.phobos.apple.com
${4} a1215.phobos.apple.com
${4} a1216.phobos.apple.com
${4} a1217.phobos.apple.com
${4} a1218.phobos.apple.com
${4} a1219.phobos.apple.com
${4} a1220.phobos.apple.com
${4} a1221.phobos.apple.com
${4} a1222.phobos.apple.com
${4} a1223.phobos.apple.com
${4} a1224.phobos.apple.com
${4} a1225.phobos.apple.com
${4} a1226.phobos.apple.com
${4} a1227.phobos.apple.com
${4} a1228.phobos.apple.com
${4} a1229.phobos.apple.com
${4} a1230.phobos.apple.com
${4} a1231.phobos.apple.com
${4} a1232.phobos.apple.com
${4} a1233.phobos.apple.com
${4} a1234.phobos.apple.com
${4} a1235.phobos.apple.com
${4} a1236.phobos.apple.com
${4} a1237.phobos.apple.com
${4} a1238.phobos.apple.com
${4} a1239.phobos.apple.com
${4} a1240.phobos.apple.com
${4} a1241.phobos.apple.com
${4} a1242.phobos.apple.com
${4} a1243.phobos.apple.com
${4} a1244.phobos.apple.com
${4} a1245.phobos.apple.com
${4} a1246.phobos.apple.com
${4} a1247.phobos.apple.com
${4} a1248.phobos.apple.com
${4} a1249.phobos.apple.com
${4} a1250.phobos.apple.com
${4} a1251.phobos.apple.com
${4} a1252.phobos.apple.com
${4} a1253.phobos.apple.com
${4} a1254.phobos.apple.com
${4} a1255.phobos.apple.com
${4} a1256.phobos.apple.com
${4} a1257.phobos.apple.com
${4} a1258.phobos.apple.com
${4} a1259.phobos.apple.com
${4} a1260.phobos.apple.com
${4} a1261.phobos.apple.com
${4} a1262.phobos.apple.com
${4} a1263.phobos.apple.com
${4} a1264.phobos.apple.com
${4} a1265.phobos.apple.com
${4} a1266.phobos.apple.com
${4} a1267.phobos.apple.com
${4} a1268.phobos.apple.com
${4} a1269.phobos.apple.com
${4} a1270.phobos.apple.com
${4} a1271.phobos.apple.com
${4} a1272.phobos.apple.com
${4} a1273.phobos.apple.com
${4} a1274.phobos.apple.com
${4} a1275.phobos.apple.com
${4} a1276.phobos.apple.com
${4} a1277.phobos.apple.com
${4} a1278.phobos.apple.com
${4} a1279.phobos.apple.com
${4} a1280.phobos.apple.com
${4} a1281.phobos.apple.com
${4} a1282.phobos.apple.com
${4} a1283.phobos.apple.com
${4} a1284.phobos.apple.com
${4} a1285.phobos.apple.com
${4} a1286.phobos.apple.com
${4} a1287.phobos.apple.com
${4} a1288.phobos.apple.com
${4} a1289.phobos.apple.com
${4} a1290.phobos.apple.com
${4} a1291.phobos.apple.com
${4} a1292.phobos.apple.com
${4} a1293.phobos.apple.com
${4} a1294.phobos.apple.com
${4} a1295.phobos.apple.com
${4} a1296.phobos.apple.com
${4} a1297.phobos.apple.com
${4} a1298.phobos.apple.com
${4} a1299.phobos.apple.com
${4} a1300.phobos.apple.com
${4} a1301.phobos.apple.com
${4} a1302.phobos.apple.com
${4} a1303.phobos.apple.com
${4} a1304.phobos.apple.com
${4} a1305.phobos.apple.com
${4} a1306.phobos.apple.com
${4} a1307.phobos.apple.com
${4} a1308.phobos.apple.com
${4} a1309.phobos.apple.com
${4} a1310.phobos.apple.com
${4} a1311.phobos.apple.com
${4} a1312.phobos.apple.com
${4} a1313.phobos.apple.com
${4} a1314.phobos.apple.com
${4} a1315.phobos.apple.com
${4} a1316.phobos.apple.com
${4} a1317.phobos.apple.com
${4} a1318.phobos.apple.com
${4} a1319.phobos.apple.com
${4} a1320.phobos.apple.com
${4} a1321.phobos.apple.com
${4} a1322.phobos.apple.com
${4} a1323.phobos.apple.com
${4} a1324.phobos.apple.com
${4} a1325.phobos.apple.com
${4} a1326.phobos.apple.com
${4} a1327.phobos.apple.com
${4} a1328.phobos.apple.com
${4} a1329.phobos.apple.com
${4} a1330.phobos.apple.com
${4} a1331.phobos.apple.com
${4} a1332.phobos.apple.com
${4} a1333.phobos.apple.com
${4} a1334.phobos.apple.com
${4} a1335.phobos.apple.com
${4} a1336.phobos.apple.com
${4} a1337.phobos.apple.com
${4} a1338.phobos.apple.com
${4} a1339.phobos.apple.com
${4} a1340.phobos.apple.com
${4} a1341.phobos.apple.com
${4} a1342.phobos.apple.com
${4} a1343.phobos.apple.com
${4} a1344.phobos.apple.com
${4} a1345.phobos.apple.com
${4} a1346.phobos.apple.com
${4} a1347.phobos.apple.com
${4} a1348.phobos.apple.com
${4} a1349.phobos.apple.com
${4} a1350.phobos.apple.com
${4} a1351.phobos.apple.com
${4} a1352.phobos.apple.com
${4} a1353.phobos.apple.com
${4} a1354.phobos.apple.com
${4} a1355.phobos.apple.com
${4} a1356.phobos.apple.com
${4} a1357.phobos.apple.com
${4} a1358.phobos.apple.com
${4} a1359.phobos.apple.com
${4} a1360.phobos.apple.com
${4} a1361.phobos.apple.com
${4} a1362.phobos.apple.com
${4} a1363.phobos.apple.com
${4} a1364.phobos.apple.com
${4} a1365.phobos.apple.com
${4} a1366.phobos.apple.com
${4} a1367.phobos.apple.com
${4} a1368.phobos.apple.com
${4} a1369.phobos.apple.com
${4} a1370.phobos.apple.com
${4} a1371.phobos.apple.com
${4} a1372.phobos.apple.com
${4} a1373.phobos.apple.com
${4} a1374.phobos.apple.com
${4} a1375.phobos.apple.com
${4} a1376.phobos.apple.com
${4} a1377.phobos.apple.com
${4} a1378.phobos.apple.com
${4} a1379.phobos.apple.com
${4} a1380.phobos.apple.com
${4} a1381.phobos.apple.com
${4} a1382.phobos.apple.com
${4} a1383.phobos.apple.com
${4} a1384.phobos.apple.com
${4} a1385.phobos.apple.com
${4} a1386.phobos.apple.com
${4} a1387.phobos.apple.com
${4} a1388.phobos.apple.com
${4} a1389.phobos.apple.com
${4} a1390.phobos.apple.com
${4} a1391.phobos.apple.com
${4} a1392.phobos.apple.com
${4} a1393.phobos.apple.com
${4} a1394.phobos.apple.com
${4} a1395.phobos.apple.com
${4} a1396.phobos.apple.com
${4} a1397.phobos.apple.com
${4} a1398.phobos.apple.com
${4} a1399.phobos.apple.com
${4} a1400.phobos.apple.com
${4} a1401.phobos.apple.com
${4} a1402.phobos.apple.com
${4} a1403.phobos.apple.com
${4} a1404.phobos.apple.com
${4} a1405.phobos.apple.com
${4} a1406.phobos.apple.com
${4} a1407.phobos.apple.com
${4} a1408.phobos.apple.com
${4} a1409.phobos.apple.com
${4} a1410.phobos.apple.com
${4} a1411.phobos.apple.com
${4} a1412.phobos.apple.com
${4} a1413.phobos.apple.com
${4} a1414.phobos.apple.com
${4} a1415.phobos.apple.com
${4} a1416.phobos.apple.com
${4} a1417.phobos.apple.com
${4} a1418.phobos.apple.com
${4} a1419.phobos.apple.com
${4} a1420.phobos.apple.com
${4} a1421.phobos.apple.com
${4} a1422.phobos.apple.com
${4} a1423.phobos.apple.com
${4} a1424.phobos.apple.com
${4} a1425.phobos.apple.com
${4} a1426.phobos.apple.com
${4} a1427.phobos.apple.com
${4} a1428.phobos.apple.com
${4} a1429.phobos.apple.com
${4} a1430.phobos.apple.com
${4} a1431.phobos.apple.com
${4} a1432.phobos.apple.com
${4} a1433.phobos.apple.com
${4} a1434.phobos.apple.com
${4} a1435.phobos.apple.com
${4} a1436.phobos.apple.com
${4} a1437.phobos.apple.com
${4} a1438.phobos.apple.com
${4} a1439.phobos.apple.com
${4} a1440.phobos.apple.com
${4} a1441.phobos.apple.com
${4} a1442.phobos.apple.com
${4} a1443.phobos.apple.com
${4} a1444.phobos.apple.com
${4} a1445.phobos.apple.com
${4} a1446.phobos.apple.com
${4} a1447.phobos.apple.com
${4} a1448.phobos.apple.com
${4} a1449.phobos.apple.com
${4} a1450.phobos.apple.com
${4} a1451.phobos.apple.com
${4} a1452.phobos.apple.com
${4} a1453.phobos.apple.com
${4} a1454.phobos.apple.com
${4} a1455.phobos.apple.com
${4} a1456.phobos.apple.com
${4} a1457.phobos.apple.com
${4} a1458.phobos.apple.com
${4} a1459.phobos.apple.com
${4} a1460.phobos.apple.com
${4} a1461.phobos.apple.com
${4} a1462.phobos.apple.com
${4} a1463.phobos.apple.com
${4} a1464.phobos.apple.com
${4} a1465.phobos.apple.com
${4} a1466.phobos.apple.com
${4} a1467.phobos.apple.com
${4} a1468.phobos.apple.com
${4} a1469.phobos.apple.com
${4} a1470.phobos.apple.com
${4} a1471.phobos.apple.com
${4} a1472.phobos.apple.com
${4} a1473.phobos.apple.com
${4} a1474.phobos.apple.com
${4} a1475.phobos.apple.com
${4} a1476.phobos.apple.com
${4} a1477.phobos.apple.com
${4} a1478.phobos.apple.com
${4} a1479.phobos.apple.com
${4} a1480.phobos.apple.com
${4} a1481.phobos.apple.com
${4} a1482.phobos.apple.com
${4} a1483.phobos.apple.com
${4} a1484.phobos.apple.com
${4} a1485.phobos.apple.com
${4} a1486.phobos.apple.com
${4} a1487.phobos.apple.com
${4} a1488.phobos.apple.com
${4} a1489.phobos.apple.com
${4} a1490.phobos.apple.com
${4} a1491.phobos.apple.com
${4} a1492.phobos.apple.com
${4} a1493.phobos.apple.com
${4} a1494.phobos.apple.com
${4} a1495.phobos.apple.com
${4} a1496.phobos.apple.com
${4} a1497.phobos.apple.com
${4} a1498.phobos.apple.com
${4} a1499.phobos.apple.com
${4} a1500.phobos.apple.com
${4} a1501.phobos.apple.com
${4} a1502.phobos.apple.com
${4} a1503.phobos.apple.com
${4} a1504.phobos.apple.com
${4} a1505.phobos.apple.com
${4} a1506.phobos.apple.com
${4} a1507.phobos.apple.com
${4} a1508.phobos.apple.com
${4} a1509.phobos.apple.com
${4} a1510.phobos.apple.com
${4} a1511.phobos.apple.com
${4} a1512.phobos.apple.com
${4} a1513.phobos.apple.com
${4} a1514.phobos.apple.com
${4} a1515.phobos.apple.com
${4} a1516.phobos.apple.com
${4} a1517.phobos.apple.com
${4} a1518.phobos.apple.com
${4} a1519.phobos.apple.com
${4} a1520.phobos.apple.com
${4} a1521.phobos.apple.com
${4} a1522.phobos.apple.com
${4} a1523.phobos.apple.com
${4} a1524.phobos.apple.com
${4} a1525.phobos.apple.com
${4} a1526.phobos.apple.com
${4} a1527.phobos.apple.com
${4} a1528.phobos.apple.com
${4} a1529.phobos.apple.com
${4} a1530.phobos.apple.com
${4} a1531.phobos.apple.com
${4} a1532.phobos.apple.com
${4} a1533.phobos.apple.com
${4} a1534.phobos.apple.com
${4} a1535.phobos.apple.com
${4} a1536.phobos.apple.com
${4} a1537.phobos.apple.com
${4} a1538.phobos.apple.com
${4} a1539.phobos.apple.com
${4} a1540.phobos.apple.com
${4} a1541.phobos.apple.com
${4} a1542.phobos.apple.com
${4} a1543.phobos.apple.com
${4} a1544.phobos.apple.com
${4} a1545.phobos.apple.com
${4} a1546.phobos.apple.com
${4} a1547.phobos.apple.com
${4} a1548.phobos.apple.com
${4} a1549.phobos.apple.com
${4} a1550.phobos.apple.com
${4} a1551.phobos.apple.com
${4} a1552.phobos.apple.com
${4} a1553.phobos.apple.com
${4} a1554.phobos.apple.com
${4} a1555.phobos.apple.com
${4} a1556.phobos.apple.com
${4} a1557.phobos.apple.com
${4} a1558.phobos.apple.com
${4} a1559.phobos.apple.com
${4} a1560.phobos.apple.com
${4} a1561.phobos.apple.com
${4} a1562.phobos.apple.com
${4} a1563.phobos.apple.com
${4} a1564.phobos.apple.com
${4} a1565.phobos.apple.com
${4} a1566.phobos.apple.com
${4} a1567.phobos.apple.com
${4} a1568.phobos.apple.com
${4} a1569.phobos.apple.com
${4} a1570.phobos.apple.com
${4} a1571.phobos.apple.com
${4} a1572.phobos.apple.com
${4} a1573.phobos.apple.com
${4} a1574.phobos.apple.com
${4} a1575.phobos.apple.com
${4} a1576.phobos.apple.com
${4} a1577.phobos.apple.com
${4} a1578.phobos.apple.com
${4} a1579.phobos.apple.com
${4} a1580.phobos.apple.com
${4} a1581.phobos.apple.com
${4} a1582.phobos.apple.com
${4} a1583.phobos.apple.com
${4} a1584.phobos.apple.com
${4} a1585.phobos.apple.com
${4} a1586.phobos.apple.com
${4} a1587.phobos.apple.com
${4} a1588.phobos.apple.com
${4} a1589.phobos.apple.com
${4} a1590.phobos.apple.com
${4} a1591.phobos.apple.com
${4} a1592.phobos.apple.com
${4} a1593.phobos.apple.com
${4} a1594.phobos.apple.com
${4} a1595.phobos.apple.com
${4} a1596.phobos.apple.com
${4} a1597.phobos.apple.com
${4} a1598.phobos.apple.com
${4} a1599.phobos.apple.com
${4} a1600.phobos.apple.com
${4} a1601.phobos.apple.com
${4} a1602.phobos.apple.com
${4} a1603.phobos.apple.com
${4} a1604.phobos.apple.com
${4} a1605.phobos.apple.com
${4} a1606.phobos.apple.com
${4} a1607.phobos.apple.com
${4} a1608.phobos.apple.com
${4} a1609.phobos.apple.com
${4} a1610.phobos.apple.com
${4} a1611.phobos.apple.com
${4} a1612.phobos.apple.com
${4} a1613.phobos.apple.com
${4} a1614.phobos.apple.com
${4} a1615.phobos.apple.com
${4} a1616.phobos.apple.com
${4} a1617.phobos.apple.com
${4} a1618.phobos.apple.com
${4} a1619.phobos.apple.com
${4} a1620.phobos.apple.com
${4} a1621.phobos.apple.com
${4} a1622.phobos.apple.com
${4} a1623.phobos.apple.com
${4} a1624.phobos.apple.com
${4} a1625.phobos.apple.com
${4} a1626.phobos.apple.com
${4} a1627.phobos.apple.com
${4} a1628.phobos.apple.com
${4} a1629.phobos.apple.com
${4} a1630.phobos.apple.com
${4} a1631.phobos.apple.com
${4} a1632.phobos.apple.com
${4} a1633.phobos.apple.com
${4} a1634.phobos.apple.com
${4} a1635.phobos.apple.com
${4} a1636.phobos.apple.com
${4} a1637.phobos.apple.com
${4} a1638.phobos.apple.com
${4} a1639.phobos.apple.com
${4} a1640.phobos.apple.com
${4} a1641.phobos.apple.com
${4} a1642.phobos.apple.com
${4} a1643.phobos.apple.com
${4} a1644.phobos.apple.com
${4} a1645.phobos.apple.com
${4} a1646.phobos.apple.com
${4} a1647.phobos.apple.com
${4} a1648.phobos.apple.com
${4} a1649.phobos.apple.com
${4} a1650.phobos.apple.com
${4} a1651.phobos.apple.com
${4} a1652.phobos.apple.com
${4} a1653.phobos.apple.com
${4} a1654.phobos.apple.com
${4} a1655.phobos.apple.com
${4} a1656.phobos.apple.com
${4} a1657.phobos.apple.com
${4} a1658.phobos.apple.com
${4} a1659.phobos.apple.com
${4} a1660.phobos.apple.com
${4} a1661.phobos.apple.com
${4} a1662.phobos.apple.com
${4} a1663.phobos.apple.com
${4} a1664.phobos.apple.com
${4} a1665.phobos.apple.com
${4} a1666.phobos.apple.com
${4} a1667.phobos.apple.com
${4} a1668.phobos.apple.com
${4} a1669.phobos.apple.com
${4} a1670.phobos.apple.com
${4} a1671.phobos.apple.com
${4} a1672.phobos.apple.com
${4} a1673.phobos.apple.com
${4} a1674.phobos.apple.com
${4} a1675.phobos.apple.com
${4} a1676.phobos.apple.com
${4} a1677.phobos.apple.com
${4} a1678.phobos.apple.com
${4} a1679.phobos.apple.com
${4} a1680.phobos.apple.com
${4} a1681.phobos.apple.com
${4} a1682.phobos.apple.com
${4} a1683.phobos.apple.com
${4} a1684.phobos.apple.com
${4} a1685.phobos.apple.com
${4} a1686.phobos.apple.com
${4} a1687.phobos.apple.com
${4} a1688.phobos.apple.com
${4} a1689.phobos.apple.com
${4} a1690.phobos.apple.com
${4} a1691.phobos.apple.com
${4} a1692.phobos.apple.com
${4} a1693.phobos.apple.com
${4} a1694.phobos.apple.com
${4} a1695.phobos.apple.com
${4} a1696.phobos.apple.com
${4} a1697.phobos.apple.com
${4} a1698.phobos.apple.com
${4} a1699.phobos.apple.com
${4} a1700.phobos.apple.com
${4} a1701.phobos.apple.com
${4} a1702.phobos.apple.com
${4} a1703.phobos.apple.com
${4} a1704.phobos.apple.com
${4} a1705.phobos.apple.com
${4} a1706.phobos.apple.com
${4} a1707.phobos.apple.com
${4} a1708.phobos.apple.com
${4} a1709.phobos.apple.com
${4} a1710.phobos.apple.com
${4} a1711.phobos.apple.com
${4} a1712.phobos.apple.com
${4} a1713.phobos.apple.com
${4} a1714.phobos.apple.com
${4} a1715.phobos.apple.com
${4} a1716.phobos.apple.com
${4} a1717.phobos.apple.com
${4} a1718.phobos.apple.com
${4} a1719.phobos.apple.com
${4} a1720.phobos.apple.com
${4} a1721.phobos.apple.com
${4} a1722.phobos.apple.com
${4} a1723.phobos.apple.com
${4} a1724.phobos.apple.com
${4} a1725.phobos.apple.com
${4} a1726.phobos.apple.com
${4} a1727.phobos.apple.com
${4} a1728.phobos.apple.com
${4} a1729.phobos.apple.com
${4} a1730.phobos.apple.com
${4} a1731.phobos.apple.com
${4} a1732.phobos.apple.com
${4} a1733.phobos.apple.com
${4} a1734.phobos.apple.com
${4} a1735.phobos.apple.com
${4} a1736.phobos.apple.com
${4} a1737.phobos.apple.com
${4} a1738.phobos.apple.com
${4} a1739.phobos.apple.com
${4} a1740.phobos.apple.com
${4} a1741.phobos.apple.com
${4} a1742.phobos.apple.com
${4} a1743.phobos.apple.com
${4} a1744.phobos.apple.com
${4} a1745.phobos.apple.com
${4} a1746.phobos.apple.com
${4} a1747.phobos.apple.com
${4} a1748.phobos.apple.com
${4} a1749.phobos.apple.com
${4} a1750.phobos.apple.com
${4} a1751.phobos.apple.com
${4} a1752.phobos.apple.com
${4} a1753.phobos.apple.com
${4} a1754.phobos.apple.com
${4} a1755.phobos.apple.com
${4} a1756.phobos.apple.com
${4} a1757.phobos.apple.com
${4} a1758.phobos.apple.com
${4} a1759.phobos.apple.com
${4} a1760.phobos.apple.com
${4} a1761.phobos.apple.com
${4} a1762.phobos.apple.com
${4} a1763.phobos.apple.com
${4} a1764.phobos.apple.com
${4} a1765.phobos.apple.com
${4} a1766.phobos.apple.com
${4} a1767.phobos.apple.com
${4} a1768.phobos.apple.com
${4} a1769.phobos.apple.com
${4} a1770.phobos.apple.com
${4} a1771.phobos.apple.com
${4} a1772.phobos.apple.com
${4} a1773.phobos.apple.com
${4} a1774.phobos.apple.com
${4} a1775.phobos.apple.com
${4} a1776.phobos.apple.com
${4} a1777.phobos.apple.com
${4} a1778.phobos.apple.com
${4} a1779.phobos.apple.com
${4} a1780.phobos.apple.com
${4} a1781.phobos.apple.com
${4} a1782.phobos.apple.com
${4} a1783.phobos.apple.com
${4} a1784.phobos.apple.com
${4} a1785.phobos.apple.com
${4} a1786.phobos.apple.com
${4} a1787.phobos.apple.com
${4} a1788.phobos.apple.com
${4} a1789.phobos.apple.com
${4} a1790.phobos.apple.com
${4} a1791.phobos.apple.com
${4} a1792.phobos.apple.com
${4} a1793.phobos.apple.com
${4} a1794.phobos.apple.com
${4} a1795.phobos.apple.com
${4} a1796.phobos.apple.com
${4} a1797.phobos.apple.com
${4} a1798.phobos.apple.com
${4} a1799.phobos.apple.com
${4} a1800.phobos.apple.com
${4} a1801.phobos.apple.com
${4} a1802.phobos.apple.com
${4} a1803.phobos.apple.com
${4} a1804.phobos.apple.com
${4} a1805.phobos.apple.com
${4} a1806.phobos.apple.com
${4} a1807.phobos.apple.com
${4} a1808.phobos.apple.com
${4} a1809.phobos.apple.com
${4} a1810.phobos.apple.com
${4} a1811.phobos.apple.com
${4} a1812.phobos.apple.com
${4} a1813.phobos.apple.com
${4} a1814.phobos.apple.com
${4} a1815.phobos.apple.com
${4} a1816.phobos.apple.com
${4} a1817.phobos.apple.com
${4} a1818.phobos.apple.com
${4} a1819.phobos.apple.com
${4} a1820.phobos.apple.com
${4} a1821.phobos.apple.com
${4} a1822.phobos.apple.com
${4} a1823.phobos.apple.com
${4} a1824.phobos.apple.com
${4} a1825.phobos.apple.com
${4} a1826.phobos.apple.com
${4} a1827.phobos.apple.com
${4} a1828.phobos.apple.com
${4} a1829.phobos.apple.com
${4} a1830.phobos.apple.com
${4} a1831.phobos.apple.com
${4} a1832.phobos.apple.com
${4} a1833.phobos.apple.com
${4} a1834.phobos.apple.com
${4} a1835.phobos.apple.com
${4} a1836.phobos.apple.com
${4} a1837.phobos.apple.com
${4} a1838.phobos.apple.com
${4} a1839.phobos.apple.com
${4} a1840.phobos.apple.com
${4} a1841.phobos.apple.com
${4} a1842.phobos.apple.com
${4} a1843.phobos.apple.com
${4} a1844.phobos.apple.com
${4} a1845.phobos.apple.com
${4} a1846.phobos.apple.com
${4} a1847.phobos.apple.com
${4} a1848.phobos.apple.com
${4} a1849.phobos.apple.com
${4} a1850.phobos.apple.com
${4} a1851.phobos.apple.com
${4} a1852.phobos.apple.com
${4} a1853.phobos.apple.com
${4} a1854.phobos.apple.com
${4} a1855.phobos.apple.com
${4} a1856.phobos.apple.com
${4} a1857.phobos.apple.com
${4} a1858.phobos.apple.com
${4} a1859.phobos.apple.com
${4} a1860.phobos.apple.com
${4} a1861.phobos.apple.com
${4} a1862.phobos.apple.com
${4} a1863.phobos.apple.com
${4} a1864.phobos.apple.com
${4} a1865.phobos.apple.com
${4} a1866.phobos.apple.com
${4} a1867.phobos.apple.com
${4} a1868.phobos.apple.com
${4} a1869.phobos.apple.com
${4} a1870.phobos.apple.com
${4} a1871.phobos.apple.com
${4} a1872.phobos.apple.com
${4} a1873.phobos.apple.com
${4} a1874.phobos.apple.com
${4} a1875.phobos.apple.com
${4} a1876.phobos.apple.com
${4} a1877.phobos.apple.com
${4} a1878.phobos.apple.com
${4} a1879.phobos.apple.com
${4} a1880.phobos.apple.com
${4} a1881.phobos.apple.com
${4} a1882.phobos.apple.com
${4} a1883.phobos.apple.com
${4} a1884.phobos.apple.com
${4} a1885.phobos.apple.com
${4} a1886.phobos.apple.com
${4} a1887.phobos.apple.com
${4} a1888.phobos.apple.com
${4} a1889.phobos.apple.com
${4} a1890.phobos.apple.com
${4} a1891.phobos.apple.com
${4} a1892.phobos.apple.com
${4} a1893.phobos.apple.com
${4} a1894.phobos.apple.com
${4} a1895.phobos.apple.com
${4} a1896.phobos.apple.com
${4} a1897.phobos.apple.com
${4} a1898.phobos.apple.com
${4} a1899.phobos.apple.com
${4} a1900.phobos.apple.com
${4} a1901.phobos.apple.com
${4} a1902.phobos.apple.com
${4} a1903.phobos.apple.com
${4} a1904.phobos.apple.com
${4} a1905.phobos.apple.com
${4} a1906.phobos.apple.com
${4} a1907.phobos.apple.com
${4} a1908.phobos.apple.com
${4} a1909.phobos.apple.com
${4} a1910.phobos.apple.com
${4} a1911.phobos.apple.com
${4} a1912.phobos.apple.com
${4} a1913.phobos.apple.com
${4} a1914.phobos.apple.com
${4} a1915.phobos.apple.com
${4} a1916.phobos.apple.com
${4} a1917.phobos.apple.com
${4} a1918.phobos.apple.com
${4} a1919.phobos.apple.com
${4} a1920.phobos.apple.com
${4} a1921.phobos.apple.com
${4} a1922.phobos.apple.com
${4} a1923.phobos.apple.com
${4} a1924.phobos.apple.com
${4} a1925.phobos.apple.com
${4} a1926.phobos.apple.com
${4} a1927.phobos.apple.com
${4} a1928.phobos.apple.com
${4} a1929.phobos.apple.com
${4} a1930.phobos.apple.com
${4} a1931.phobos.apple.com
${4} a1932.phobos.apple.com
${4} a1933.phobos.apple.com
${4} a1934.phobos.apple.com
${4} a1935.phobos.apple.com
${4} a1936.phobos.apple.com
${4} a1937.phobos.apple.com
${4} a1938.phobos.apple.com
${4} a1939.phobos.apple.com
${4} a1940.phobos.apple.com
${4} a1941.phobos.apple.com
${4} a1942.phobos.apple.com
${4} a1943.phobos.apple.com
${4} a1944.phobos.apple.com
${4} a1945.phobos.apple.com
${4} a1946.phobos.apple.com
${4} a1947.phobos.apple.com
${4} a1948.phobos.apple.com
${4} a1949.phobos.apple.com
${4} a1950.phobos.apple.com
${4} a1951.phobos.apple.com
${4} a1952.phobos.apple.com
${4} a1953.phobos.apple.com
${4} a1954.phobos.apple.com
${4} a1955.phobos.apple.com
${4} a1956.phobos.apple.com
${4} a1957.phobos.apple.com
${4} a1958.phobos.apple.com
${4} a1959.phobos.apple.com
${4} a1960.phobos.apple.com
${4} a1961.phobos.apple.com
${4} a1962.phobos.apple.com
${4} a1963.phobos.apple.com
${4} a1964.phobos.apple.com
${4} a1965.phobos.apple.com
${4} a1966.phobos.apple.com
${4} a1967.phobos.apple.com
${4} a1968.phobos.apple.com
${4} a1969.phobos.apple.com
${4} a1970.phobos.apple.com
${4} a1971.phobos.apple.com
${4} a1972.phobos.apple.com
${4} a1973.phobos.apple.com
${4} a1974.phobos.apple.com
${4} a1975.phobos.apple.com
${4} a1976.phobos.apple.com
${4} a1977.phobos.apple.com
${4} a1978.phobos.apple.com
${4} a1979.phobos.apple.com
${4} a1980.phobos.apple.com
${4} a1981.phobos.apple.com
${4} a1982.phobos.apple.com
${4} a1983.phobos.apple.com
${4} a1984.phobos.apple.com
${4} a1985.phobos.apple.com
${4} a1986.phobos.apple.com
${4} a1987.phobos.apple.com
${4} a1988.phobos.apple.com
${4} a1989.phobos.apple.com
${4} a1990.phobos.apple.com
${4} a1991.phobos.apple.com
${4} a1992.phobos.apple.com
${4} a1993.phobos.apple.com
${4} a1994.phobos.apple.com
${4} a1995.phobos.apple.com
${4} a1996.phobos.apple.com
${4} a1997.phobos.apple.com
${4} a1998.phobos.apple.com
${4} a1999.phobos.apple.com
${4} a2000.phobos.apple.com
${5} devimages.apple.com.edgekey.net
${6} metrics.apple.com
#Apple Services End
<file_sep>/template/alibaba_template.ini
${1} i00.c.aliimg.com
${1} i01.c.aliimg.com
${1} i02.c.aliimg.com
${1} i03.c.aliimg.com
${1} i04.c.aliimg.com
${1} i05.c.aliimg.com
${1} i06.c.aliimg.com
${1} i07.c.aliimg.com
${1} i08.c.aliimg.com
${1} i09.c.aliimg.com
|
a01441203ad5902296514bb3a927daf157d2e9a5
|
[
"Markdown",
"Ruby",
"INI"
] | 5 |
INI
|
cha63506/wyatt_hosts
|
73cd52c261b7fd6ddb5ad18854b78515c70fa724
|
ba078fc4ebcef5b0b3ed7230546ef075fc22f673
|
refs/heads/master
|
<file_sep>import axios from 'axios';
let instance = axios.create({
baseURL: 'https://react-my-burger-tpp.firebaseio.com/'
})
export default instance;
|
435b6161c185edb77e2eddf8a4187946dd6ef8a8
|
[
"TypeScript"
] | 1 |
TypeScript
|
Bleedaxe/react-burger-project
|
825eb7c8ad2c0f7fd6edbfb2fbc70277aeb781d2
|
b5606ebb3c0c909219e0fa33058082a95d400d72
|
refs/heads/master
|
<repo_name>Misa-X/Assorted-Problems-and-Exercises<file_sep>/Assorted Problems and Exercises 1.py
x = input("Enter comma-separated numbers: ")
my_list = [x]
my_tuple = (x)
print("List:",my_list)
print("Tuple:(",my_tuple,")")
|
276af9aa9f2fecdf4d752f898d72d1a87323999e
|
[
"Python"
] | 1 |
Python
|
Misa-X/Assorted-Problems-and-Exercises
|
7ab4fdb6ca62efff7006987deb8e7f3eff718f4a
|
11a53125e56eeff4c0fbfc01b09f959ec4b37b87
|
refs/heads/master
|
<repo_name>leon2017/android-api-analysis<file_sep>/buildSrc/src/main/java/Dependencies.kt
import org.gradle.api.artifacts.dsl.RepositoryHandler
import java.net.URI
/**
* Created by idisfkj on 2019/5/29.
* Email : <EMAIL>.
*/
object Versions {
const val support = "28.0.0"
const val kotlin = "1.3.50"
const val constraint_layout = "1.1.0-beta6"
const val runner = "1.0.1"
const val espresso_core = "3.0.1"
const val junit = "4.12"
const val gradle = "3.4.1"
const val target_sdk = 28
const val min_sdk = 16
const val build_tools = "28.0.3"
const val arch_version = "2.2.0-alpha01"
const val arch_room_version = "2.1.0-rc01"
const val paging_version = "2.1.0"
const val anko_version = "0.10.8"
const val glide = "4.8.0"
const val retrofit = "2.6.0"
const val okhttp_logging_interceptor = "3.9.0"
const val rx_android = "2.0.1"
const val rxjava2 = "2.1.3"
const val work_version = "2.1.0"
const val nav_version = "2.1.0-beta02"
const val core_ktx = "1.0.0"
}
object Dependencies {
const val app_compat = "com.android.support:appcompat-v7:${Versions.support}"
const val recyclerView = "com.android.support:recyclerview-v7:${Versions.support}"
const val kotlin_stdlib = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Versions.kotlin}"
const val kotlin_plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
const val junit = "junit:junit:${Versions.junit}"
const val constraint_layout = "com.android.support.constraint:constraint-layout:${Versions.constraint_layout}"
const val runner = "com.android.support.test:runner:${Versions.runner}"
const val espresso_core = "com.android.support.test.espresso:espresso-core:${Versions.espresso_core}"
const val gradle_plugin = "com.android.tools.build:gradle:${Versions.gradle}"
const val arch_lifecycle = "androidx.lifecycle:lifecycle-extensions:${Versions.arch_version}"
const val arch_viewmodel = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Versions.arch_version}"
const val arch_livedata = "androidx.lifecycle:lifecycle-livedata-ktx:${Versions.arch_version}"
const val arch_runtime = "androidx.lifecycle:lifecycle-runtime-ktx:${Versions.arch_version}"
const val arch_room_runtime = "androidx.room:room-runtime:${Versions.arch_room_version}"
const val arch_room_compiler = "androidx.room:room-compiler:${Versions.arch_room_version}"
const val arch_room = "androidx.room:room-ktx:${Versions.arch_room_version}"
const val paging_runtime = "androidx.paging:paging-runtime:${Versions.paging_version}"
const val anko = "org.jetbrains.anko:anko:${Versions.anko_version}"
const val glide_runtime = "com.github.bumptech.glide:glide:${Versions.glide}"
const val glide_compiler = "com.github.bumptech.glide:compiler:${Versions.glide}"
const val retrofit_runtime = "com.squareup.retrofit2:retrofit:${Versions.retrofit}"
const val retrofit_gson = "com.squareup.retrofit2:converter-gson:${Versions.retrofit}"
const val retrofit_adapter_rxjava2 = "com.squareup.retrofit2:adapter-rxjava2:${Versions.retrofit}"
const val okhttp_logging_interceptor = "com.squareup.okhttp3:logging-interceptor:${Versions.okhttp_logging_interceptor}"
const val rxjava2 = "io.reactivex.rxjava2:rxjava:${Versions.rxjava2}"
const val rx_android = "io.reactivex.rxjava2:rxandroid:${Versions.rx_android}"
const val work_runtime = "androidx.work:work-runtime-ktx:${Versions.work_version}"
const val nav_fragment = "androidx.navigation:navigation-fragment-ktx:${Versions.nav_version}"
const val nav_ui = "androidx.navigation:navigation-ui-ktx:${Versions.nav_version}"
const val nav_safe_args_plugin = "androidx.navigation:navigation-safe-args-gradle-plugin:${Versions.nav_version}"
const val core_ktx = "androidx.core:core-ktx:${Versions.core_ktx}"
val addRepos: (handler: RepositoryHandler) -> Unit = {
it.google()
it.jcenter()
it.maven { url = URI("https://oss.sonatype.org/content/repositories/snapshots") }
}
}
|
42f64b18979fb6391dfd35c618546c9cf21fcc6b
|
[
"Kotlin"
] | 1 |
Kotlin
|
leon2017/android-api-analysis
|
a89dc577c81f377fe820ce2bcb516c1e4ee6c9cd
|
1c8ed03a9f9e33246df0901ecd99cb111c7c7c38
|
refs/heads/main
|
<file_sep>import React, { Component } from "react";
export class Location extends Component {
render() {
return (
<div>
<h1>{this.props.name}</h1>
<h2>
{this.props.lon} / {this.props.lat}
</h2>
<h2>{this.props.type}</h2>
<img
src={this.props.imgURL}
alt="Girl in a jacket"
width="500"
height="600"
/>
</div>
);
}
}
export default Location;
<file_sep>import axios from "axios";
import React, { Component } from "react";
import Form from "./component/Form";
import Location from "./component/Location";
import { Card } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
export class App extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
lon: "",
lat: "",
type: "",
showData: false,
};
}
handlerName = (e) => {
let name = e.target.value;
this.setState({
name: name,
});
};
submitHandler = (e) => {
e.preventDefault();
let confing = {
method: "GET",
baseURL: `https://api.locationiq.com/v1/autocomplete.php?key=<KEY>&q=${this.state.name}`,
};
axios(confing).then((res) => {
let firstLOcation = res.data[0];
this.setState({
name: firstLOcation.display_name,
lon: firstLOcation.lon,
lat: firstLOcation.lat,
type: firstLOcation.type,
showData: true,
});
});
};
render() {
return (
<div>
<Form
handlerName={this.handlerName}
submitHandler={this.submitHandler}
/>
{this.state.showData && (
<Location
name={this.state.name}
lon={this.state.lon}
lat={this.state.lat}
type={this.state.type}
/>
)}
<Card.Img
className="cardImg"
src={`https://maps.locationiq.com/v3/staticmap?key=<KEY>¢er=${this.state.lat},${this.state.lon}`}
alt="Card image"
height="500px"
/>
</div>
);
}
}
export default App;
|
0fc8350a2c4c569f3272f853c5b2cecddd1db211
|
[
"JavaScript"
] | 2 |
JavaScript
|
shaimasawai/city-explorer
|
9f17e7e05b0efd15601df74d4353b9f31c347387
|
f3dd7b77fde84bb77d02e04564d21655b9e3d27e
|
refs/heads/master
|
<repo_name>Tutorgaming/promptdb<file_sep>/src/redux/store/reducers/auth.js
var ENUM = require("../../constants"),
initialState = require("../initialstate");
/*
A reducer is a function that takes the current state and an action, and then returns a
new state. This reducer is responsible for appState.auth data.
See `initialstate.js` for a clear view of what it looks like!
*/
module.exports = function(currentstate,action){
switch(action.type){
case ENUM.ATTEMPTING_LOGIN:
return {
currently: ENUM.AWAITING_AUTH_RESPONSE,
username: "guest",
uid: null
};
case ENUM.LOGOUT:
return {
currently: ENUM.ANONYMOUS,
username: "guest",
uid: null
};
case ENUM.LOGIN_USER:
return {
currently: ENUM.LOGGED_IN,
username: action.username,
uid: action.uid,
fbusername: action.fbusername,
fbid:action.fbid,
logged_in: action.logged_in,
largepic: action.largepic,
picurl: action.picurl
};
case ENUM.HELLO:
console.log("SJFIOAJFIOADJFOAJDFOAIDJFAODIFJAODIFJAOIDJF");
return;
default: return currentstate || initialState.auth;
}
};
<file_sep>/src/components/Header.js
/*
Name : promptDB
Header Bar (Including Gallery) Here
By : <NAME>.
*/
import React, {PropTypes} from 'react';
import {Nav,Navbar, NavItem , NavDropdown , MenuItem} from "react-bootstrap";
import Gallery from "./Gallery";
import {LinkContainer} from 'react-router-bootstrap';
import { connect } from 'react-redux'
export default class Header extends React.Component {
constructor(props) {
super(props);
}
fbLogout() {
FB.logout(function (response) {
// Set Login State in Global Store
// logged_in : false
window.location.reload();
});
}
render() {
return (
<div>
<div style={{marginBottom : 50+"px"}} inline>
<Navbar fixedTop={true} bsStyle="inverse">
<Navbar.Header>
<Navbar.Brand>
<LinkContainer to="/"><a>PROMPT51</a></LinkContainer>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
{(this.props.auth.logged_in)? <Navbar.Collapse>
<Nav>
<LinkContainer to="/displayAll"><NavItem eventKey={1}> ดูข้อมูลรวม </NavItem></LinkContainer>
{(this.props.member.registered)?
<LinkContainer to="/displayEdit"><NavItem eventKey={2}>แก้ไขข้อมูลส่วนตัว</NavItem></LinkContainer>
: <LinkContainer to="/register"><NavItem eventKey={2}>ลงทะเบียน</NavItem></LinkContainer>
}
<NavDropdown eventKey={3} title="ดูข้อมูลศิษย์เก่า" id="basic-nav-dropdown">
<LinkContainer to="/displayRoom/1"><MenuItem eventKey={3.1}> ห้อง 1 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/2"><MenuItem eventKey={3.2}> ห้อง 2 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/3"><MenuItem eventKey={3.3}> ห้อง 3 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/4"><MenuItem eventKey={3.4}> ห้อง 4 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/5"><MenuItem eventKey={3.5}> ห้อง 5 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/6"><MenuItem eventKey={3.6}> ห้อง 6 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/7"><MenuItem eventKey={3.7}> ห้อง 7 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/8"><MenuItem eventKey={3.8}> ห้อง 8 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/9"><MenuItem eventKey={3.9}> ห้อง 9 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/10"><MenuItem eventKey={3.10}> ห้อง 10 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/11"><MenuItem eventKey={3.11}> ห้อง 11 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/12"><MenuItem eventKey={3.12}> ห้อง 12 </MenuItem></LinkContainer>
<LinkContainer to="/displayRoom/EP"><MenuItem eventKey={3.13}> ห้อง EP </MenuItem></LinkContainer>
</NavDropdown>
</Nav>
<Nav pullRight>
<NavItem> <img src={this.props.auth.picurl} style={{width: 20+'px',height: 20+'px'}} /> </NavItem>
<NavItem> <span onClick={this.fbLogout.bind(this)}>logout</span> </NavItem>
</Nav>
</Navbar.Collapse>
:
<Nav pullRight>
<LinkContainer to="/facebookLogin"><NavItem>Login with Facebook</NavItem></LinkContainer>
</Nav>
}
</Navbar>
</div>
<Gallery />
</div>
);
}
}
var mapStateToProps = function(appState){
// This component will have access to `appState.auth` through `this.props.auth`
return {auth:appState.auth , member:appState.member};
};
module.exports = connect(mapStateToProps)(Header);
<file_sep>/README.md
# promptdb
DB For Alum
<file_sep>/src/redux/store/reducers/members.js
/*
Name : promptdb
Member Reducer
Set the Main App States with the Members Data
By : <NAME>.
*/
var ENUM = require("../../constants"),
initialState = require("../initialstate");
module.exports = function(currentstate,action){
switch(action.type){
//WAITING FOR RESPONSE MEMBER POST
case ENUM.POSTING_MEMBER:
return Object.assign({},currentstate,{
isProcessing : action.isProcessing,
hasreceiveddata: false
});
case ENUM.POSTING_MEMBER_ERROR:
return Object.assign({},currentstate,{
error : true,
message : action.message
});
case ENUM.SUCCESS_POST:
return Object.assign({},currentstate,{
error : false,
isProcessing : action.isProcessing,
message : action.message,
registered : true
});
default: return currentstate || initialState.member;
}
}
<file_sep>/src/components/DisplayFacebookLogin.js
/*
Name : promptDB
Facebook Login Page
By : <NAME>.
*/
import React from 'react';
import FacebookLogin from 'react-facebook-login';
import Footer from './Footer'
import {Panel, Button} from 'react-bootstrap'
import Header from './Header'
import * as authen_action from '../redux/actions/auth'
import {connect} from 'react-redux';
class DisplayFacebookLogin extends React.Component {
constructor(props) {
super(props);
// Init the facebook API
this.initialFacebookSDK();
}
initialFacebookSDK(){
//From developer.facebook.com
window.fbAsyncInit = function() {
FB.init({
appId : 1121025771269670,
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.5' // use graph api version 2.5
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
}
doAuthen(){
console.log("Do the Firebase Authentication");
//Emit the Auth Action
this.props.startListeningToAuth();
}
render() {
return (
<div>
{
(this.props.auth.logged_in)?
<Header logged_in={this.props.auth.logged_in} user={this.props.auth}/>
:
<Header logged_in={false}/>
}
<center>
<div className="container">
<Panel bsStyle="primary" header="Login With Facebook / กรุณา Login ด้วย Facebook ">
{(this.props.auth.logged_in)?
<div>
<img src={this.props.auth.largepic}/>
<br/> {this.props.auth.fbusername}
</div>
:
""
}
<br/>
{(!this.props.auth.logged_in)?
<Button onClick={this.doAuthen.bind(this)} bsStyle="primary">
Login with Facebook
</Button>
:
""
}
</Panel>
</div>
</center>
<Footer />
</div>
)
}
}
export default DisplayFacebookLogin;
var mapStateToProps = function(appState){
// This component will have access to `appState.auth` through `this.props.auth`
return {auth:appState.auth};
};
var mapDispatchToProps = function(dispatch){
return {
attemptLogin: function(){ dispatch(authen_action.attemptLogin()); },
startListeningToAuth: function() {dispatch(authen_action.startListeningToAuth());},
sayHello: function(){ dispatch(authen_action.sayHello());},
logoutUser: function(){ dispatch(authen_action.logoutUser()); }
}
};
module.exports = connect(mapStateToProps,mapDispatchToProps)(DisplayFacebookLogin);
<file_sep>/src/redux/actions/members.js
/*
Name : promptdb
Member Actions
CRUD with Databases
By : <NAME>.
*/
import * as ENUM from '../constants';
import firebase from 'firebase';
import {fireRef} from './auth'
// var fireRef = firebase.initializeApp(ENUM.FIREBASE_CONFIG);
const database = firebase.database();
const memberDatabase = database.ref('members');
module.exports = {
//Save a Single Member onto Database
saveMember: function(formData){
return function(dispatch,getState){
var state = getState();
var memberState = formData;
//TODO: Check Access Token Here
var member = {
id : memberState.stdid,
firstname : memberState.firstname,
lastname : memberState.lastname,
room : memberState.roomid,
email : memberState.email,
workplace : memberState.workplace,
phone : memberState.phone,
facebook_id : memberState.facebook_id
};
// REDUX : EMIT THE POSTING (waiting state)
dispatch({
type: ENUM.POSTING_MEMBER,
isProcessing: true
});
// Post Data to database
memberDatabase.push(member,function(error){
if(error){
dispatch({
type:ENUM.POSTING_MEMBER_ERROR,
message: error
});
}else{
dispatch({
type:ENUM.SUCCESS_POST,
isProcessing: false,
message: "Post Member to Database Successfully."
});
// Redirect To
}
});
}
},
helloWorld: function(){
return function(dispatch,getState){
console.log("Hello World from Member Moudules");
}
},
fetchMember: function(memberid){
return function(dispatch,getState){
var member = {
id : null,
firstname : null,
lastname : null,
room : null,
email : null,
workplace : null,
phone : null,
facebook_id : null
};
}
}
}
<file_sep>/src/components/Card.js
import React from "react";
import {Button, Thumbnail,Col} from "react-bootstrap";
class Card extends React.Component {
constructor(props) {
super(props);
}
/*
Schema for Single Member
let member = {
firstname : "",
lastname : "",
nickname : "",
workAt : "",
birthdate : "",
phone_no : "",
facebook_id : "", // To be solve to facebook url
};
*/
render(){
return(
<Col xs={6} md={4}>
<Thumbnail src="http://www.placehold.it/242x200" alt="242x200" style={{marginTop: 50 + 'px'}}>
<center>
<h3>{this.props.nickname}</h3>
<h4>{this.props.firstname}สมหมาย {this.props.lastname}นามสกุลไทย</h4>
</center>
<hr/>
<p>ข้อมูลส่วนตัว</p>
<p>ชื่อ </p>
<p>ชื่อ </p>
<p>ชื่อ </p>
<p>ชื่อ </p>
<p>ชื่อ </p>
<p>ชื่อ </p>
<p>ชื่อ </p>
<p>
<Button bsStyle="primary">Button</Button>
<Button bsStyle="default">Button</Button>
</p>
</Thumbnail>
</Col>
);
}
}
export default Card;
<file_sep>/src/components/Gallery.js
import React, {PropTypes} from 'react';
import {Carousel} from "react-bootstrap";
export default class Gallery extends React.Component {
render() {
return (
<div className="carousel-container">
<h1 className="overlayTitleText">Prompt51 Alumni Database</h1>
<Carousel>
<Carousel.Item>
<img src="/img/mont1.jpg"/>
<Carousel.Caption>
<h3>Slide แรก</h3>
<p>คำบรรยายภาพจะถูกพิมพ์ไว้ตรงนี้</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img src="/img/mont2.jpg"/>
<Carousel.Caption>
<h3>Second slide label</h3>
<p>คำบรรยายภาพจะถูกพิมพ์ไว้ตรงนี้</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img src="/img/mont3.jpg"/>
<Carousel.Caption>
<h3>Third slide label</h3>
<p>คำบรรยายภาพจะถูกพิมพ์ไว้ตรงนี้</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img src="/img/mont4.jpg"/>
<Carousel.Caption>
<h3>Third slide label</h3>
<p>คำบรรยายภาพจะถูกพิมพ์ไว้ตรงนี้</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</div>
);
}
}
<file_sep>/src/components/DisplayAll.js
/*
Name : promptDB
Display List Of All Entries Here
By : <NAME>.
*/
import React from "react";
import CardContainer from "./CardContainer";
import AddMemberForm from "./AddMemberForm";
import {PageHeader,Form,Col,Panel,FormGroup, ControlLabel, FormControl} from "react-bootstrap";
// NavBar
import Header from "./Header";
import Footer from "./Footer";
// Main Entry of this app
class DisplayAll extends React.Component {
constructor(props) {
super(props);
this.prepareTestData.bind(this);
this.state = {
datas :[]
//Login Credential might be included here
};
}
// Generate Mockup Data
prepareTestData(amount){
for( var i = 0 ; i < amount ; i++){
this.state.datas.push(i);
}
}
// Rendering Method
render(){
// Get Data From Server
// Not implemented Yet
// Generate Mockup Data For Usage
this.prepareTestData(22);
// Return The Result via html element
return (
<div>
<Header />
<div className="container">
<PageHeader>Alumni Display - <small> ข้อมูลศิษย์เก่า </small>
{ (this.props.params.roomId)? `ห้อง ${this.props.params.roomId}`:"แสดงทั้งหมด"}
</PageHeader>
<hr/>
<CardContainer datas = {this.state.datas} ></CardContainer>
</div>
<Footer />
</div>
);
}
}
export default DisplayAll;
<file_sep>/src/redux/actions/auth.js
/*
Name : promptdb
Authentication Action
Based on Firebase
By : <NAME>.
*/
import * as ENUM from '../constants';
import firebase from 'firebase';
export var fireRef = firebase.initializeApp(ENUM.FIREBASE_CONFIG);
console.log("init");
module.exports ={
// Check Existing Authentication
startListeningToAuth: function(){
return function(dispatch,getState){
var auth = firebase.auth();
var provider = new firebase.auth.FacebookAuthProvider();
provider.addScope('public_profile');
auth.signInWithPopup(provider).then(function(result) {
var accessToken = result.credential.accessToken;
var fbid = result.user.providerData[0].uid;
var largepic = "http://graph.facebook.com/" + fbid + "/picture?type=large";
var picurl = "http://graph.facebook.com/" + fbid + "/picture?type=square";
dispatch(
{
type: ENUM.LOGIN_USER,
uid: result.user.uid,
fbusername: result.user.displayName,
fbid:fbid,
logged_in: true,
largepic: largepic,
picurl: picurl
}
);
});
}
}
,
attemptLogin: function(){
// Return a function which Attempting Login
return function(dispatch,getState){
dispatch(
{
type:ENUM.ATTEMPTING_LOGIN
}
);
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// TODO : APPLY THE ACTION HERE AFTER SUCCESSFUL LOGIN
console.log("Login Successful via Firebase. ");
}).catch(function(error) {
var errorCode = error.code;
var credential = error.credential;
});
}
}
,
//
logoutUser: function(){
// Return a function which attempting logout
return function(dispatch,getState){
dispatch(
{
type:ENUM.LOGOUT
}
);
// Call Fireauth to unAuth oAuth also
fireRef.unauth();
}
}
};
<file_sep>/src/components/WelcomePage.js
/*
Name : promptDB
Welcome Page
By : <NAME>.
*/
import React from "react";
import CardContainer from "./CardContainer";
import Header from "./Header";
import Footer from "./Footer";
import Gallery from "./Gallery"
import {Panel} from 'react-bootstrap';
// Main Entry of this app
class WelcomePage extends React.Component {
constructor(props) {
super(props);
}
// Routing
render(){
return (
<div>
<Header/>
<br/>
<div className="container">
<Panel bsStyle="success" header="Greetings">
<h2>ยินดีต้อนรับเข้าสู่ระบบลงทะเบียนศิษย์เก่า </h2>
<hr/>
<center>
การใช้งานระบบ ต้องทำการ Login เข้าสู่ระบบด้วย Facebook ก่อน หลังจากนั้นจึงทำการลงทะเบียน
<br/>หากลงทะเบียนแล้ว จะเป็นการแก้ไขข้อมูลส่วนตัวของตนเอง
ผู้ใช้งานสามารถเปิดดูฐานข้อมูลอื่นๆได้เช่นกัน
</center>
</Panel>
</div>
<Footer/>
</div>
);
}
}
export default WelcomePage;
<file_sep>/src/redux/store/reducers/index.js
// Reducers Index
var Redux = require("redux"),
authReducer = require("./auth"),
memberReducer = require("./members");
import { routerReducer } from 'react-router-redux'
//membersReducer = require("./quotes"),
//feedbackReducer = require("./feedback");
var rootReducer = Redux.combineReducers({
auth: authReducer,
member: memberReducer,
routing: routerReducer
});
module.exports = rootReducer;
|
a2a760ca7d8011e25a65d6fbf8cc23341d09ca65
|
[
"JavaScript",
"Markdown"
] | 12 |
JavaScript
|
Tutorgaming/promptdb
|
374356c5b94fa172a63396f1480282f4074695f3
|
2197d05d86c8b824b47cbe7fd1ddb45241c1082d
|
refs/heads/master
|
<repo_name>astupak/muffin-server<file_sep>/middlewares/sorted/05-passport.js
const passport = require('../../libs/passport');
module.exports = passport.initialize();
<file_sep>/middlewares/index.js
const compose = require('koa-compose');
const path = require('path');
const fs = require('fs');
const handlers = fs.readdirSync(path.join(__dirname, 'sorted')).sort();
let middlewares = [];
handlers.forEach((handler) => {
middlewares.push(require('./sorted/' + handler));
});
module.exports = compose(middlewares);<file_sep>/middlewares/sorted/07-csrf-set.js
module.exports = async function(ctx, next) {
// try {
// first, do the middleware, maybe authorize user in the process
await next();
// } finally {
//TODO: !figure this out!
// // then if we have a user, set XSRF token
// if (ctx.req.user) {
// try {
// // if ctx doesn't throw, the user has a valid token in cookie already
// ctx.assertCsrf({_csrf: ctx.cookies.get('XSRF-TOKEN') });
// } catch(e) {
// // error occurs if no token or invalid token (old session)
// // then we set a new (valid) one
// ctx.cookies.set('XSRF-TOKEN', ctx.csrf, { httpOnly: false, signed: false });
// }
// }
// }
};
<file_sep>/index.js
const Koa = require('koa');
const app = new Koa();
const config = require('config');
require('./libs/mongoose');
const routes = require('./routes');
const middlewares = require('./middlewares');
app.use(middlewares);
app.use(routes);
app.listen(3000);
<file_sep>/routes/unprotected/login.js
const passport = require('koa-passport');
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports.login = async (ctx, next) => passport.authenticate('local', { session: false })(ctx, next);
module.exports.generateToken = async (ctx, next) => {
let { user } = ctx.passport;
const token = jwt.sign(user.id, config.jwt.secret);
const formattedToken = `JWT ${token}`;
ctx.status = 200;
ctx.body = {
user: user.toObject(),
formattedToken,
};
}
<file_sep>/routes/index.js
const Router = require('koa-router');
const { checkToken } = require('./protected/checkToken');
const { register } = require('./unprotected/join');
const { login, generateToken } = require('./unprotected/login');
const router = new Router();
//unprotected routes
router.post('/login', login, generateToken);
router.post('/join', register);
//protected routes
router.get('/frontpage', checkToken, require('./protected/frontpage').get);
// router.get('/logout', checkToken, require('./protected/logout').get);
module.exports = router.routes();<file_sep>/routes/protected/logout.js
module.exports.get = async function(ctx, next) {
ctx.status = 200;
ctx.logout();
}<file_sep>/libs/passport/localStrategy.js
const passport = require('koa-passport');
const LocalStrategy = require('passport-local');
const User = require('../../models/user');
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
},
(email, password, done) => {
User.findOne({ email }, (err, user) => {
if (err) {
return done(err);
}
if (!user || !user.checkPassword(password)) {
return done(null, false, { message: 'Нет такого пользователя или пароль неверен.' });
}
return done(null, user);
});
}
));
<file_sep>/routes/protected/frontpage.js
module.exports.get = async function(ctx, next) {
ctx.status = 200;
ctx.body = 'Hi there!';
}<file_sep>/middlewares/sorted/06-csrf-check.js
module.exports = async function(ctx, next) {
//TODO: figure this out!!
// skip these methods
// if (ctx.method === 'GET' || ctx.method === 'HEAD' || ctx.method === 'OPTIONS') {
// return await next();
// }
// let checkCsrf = true;
// if (!ctx.req.user) {
// checkCsrf = false;
// }
// // If test check CSRF only when "X-Test-Csrf" header is set
// if (process.env.NODE_ENV == 'test' && !ctx.get('X-Test-Csrf')) {
// checkCsrf = false;
// }
// if (checkCsrf) {
// ctx.assertCSRF(ctx.request.body);
// } else {
// console.log("csrf check skipped");
// }
await next();
};
|
0ead9c1ec00c8fb1c2b27ba34d66be41e45f702b
|
[
"JavaScript"
] | 10 |
JavaScript
|
astupak/muffin-server
|
7770ddb1292acbca1ee3147c1b6c1c415429c7c2
|
d7f81c8c401302aca0816e5698a027526762ad78
|
refs/heads/main
|
<repo_name>oslokommune/origourls<file_sep>/README.md
# origourls
URL-shortener to create human readable urls
<file_sep>/origourls.go
package main
import "fmt"
// Concept - must be able to store 'key' (urls.os.lol/kjoremiljo) -> https://meet.google.com/iur-phvy-hit or something
// store this data in a key value store ( we will use Amazon S3)
// Origo prod , use AWS lambda, // where to deploy lambda code?
// iac-repo okctl-prod legge inn terraform / cloud formation der.
// push to aws lambad somehow | check how it's done with postgres key rotator. ---
// Use terraform or cloudformation, place directory at ---
func main() {
fmt.Println("Welcome to origourls!")
}
|
1932ddb4d36edcc3a15d36134cf870823b20bbfb
|
[
"Markdown",
"Go"
] | 2 |
Markdown
|
oslokommune/origourls
|
11b16604ab0648fed5d199475ac73167f9486482
|
289d0068f049f3b99b30e0c8498514c7676dd04c
|
refs/heads/master
|
<file_sep>require 'date'
module AddParserToDate
def new(*args)
return super if args.length != 1
value = args.first
return if value.nil?
return value if value.is_a?(Date)
return super unless value.is_a?(String)
value.strip!
begin
if value =~ /^([0]?[1-9]|[12][0-9]|3[01])\.([0]?[1-9]|[1][0-2])\.[0-9]{2}$/
Date.strptime(value, "%d.%m.%y")
elsif value =~ /^([0]?[1-9]|[12][0-9]|3[01])([.-])([0]?[1-9]|[1][0-2])([.-])[0-9]{4}$/
Date.strptime(value, "%d#{ $2 }%m#{ $4 }%Y")
elsif value =~ /^[0-9]{6}$/
Date.strptime("#{value[0..1]}.#{value[2..3]}.#{value[4..5]}", "%d.%m.%y")
elsif value =~ /^[0-9]{8}$/
Date.strptime("#{value[0..1]}.#{value[2..3]}.#{value[4..7]}", "%d.%m.%Y")
elsif value =~ /^[0-9]{2}-([0]?[1-9]|[1][0-2])-([0]?[1-9]|[12][0-9]|3[01])$/
Date.strptime(value, "%y-%m-%d")
elsif value =~ /^[0-9]{4}-([0]?[1-9]|[1][0-2])-([0]?[1-9]|[12][0-9]|3[01])$/
Date.strptime(value, "%Y-%m-%d")
else
nil
end
rescue ArgumentError
nil
end
end
end
Date.singleton_class.prepend AddParserToDate
<file_sep>$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
require "date-parser/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "date-parser"
s.version = DateParser::VERSION
s.authors = ["<NAME>", "<NAME>"]
s.email = ["<EMAIL>", "<EMAIL>"]
s.homepage = "http://www.bfpi.de"
s.summary = "Simple parser for dates and times from strings"
s.description = "Simple parser for dates and times from strings"
s.license = "MIT"
s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"]
s.require_path = 'lib'
s.add_dependency "rails"
end
<file_sep># date-parser
Simple parser for dates and times from strings
<file_sep>require 'date'
module AddParserToDateTime
def new(*args)
return super if args.length != 1
value = args.first
return if value.nil?
return value if value.is_a?(DateTime) || value.is_a?(Time)
return value.to_datetime if value.is_a?(Date)
return super unless value.is_a?(String)
value.strip!
begin
date, time = value.split(/[ T]/, 2)
date = Date.new(date)
return if date.nil?
if time =~ /^(0[0-9]|1[0-9]|2[0-4])[\.\:]?([0-5][0-9])([\.\:]?([0-5][0-9]))?( ?[A-Z]+|(\+|-)(0[0-9]|1[0-2])(:[0-5][0-9])?)?$/
DateTime.new date.year, date.mon, date.day, $1.to_i, $2.to_i, ($4 || 0).to_i, $5 || ''
else
nil
end
rescue ArgumentError
nil
end
end
end
DateTime.singleton_class.prepend AddParserToDateTime
|
5c5fd373e387730e18db818ddfd294e150b1e253
|
[
"Markdown",
"Ruby"
] | 4 |
Ruby
|
bfpi/date-parser
|
45dccc7ff2263e088c959716bfb5146cc9775f8e
|
8bd9e54feafc237b0e7ec9632b6ee1e579c0e907
|
refs/heads/master
|
<file_sep>using UnityEngine;
using System.Collections;
using CnControls;
public class FollowPlayer : MonoBehaviour {
public Transform p_Transform;
public Transform h_Transform;
[SerializeField] float cam_y_offset;
[SerializeField] float cam_z_offset;
[SerializeField] float camEulerAngle_x;
[SerializeField] float cameraFollowSpeed = 2f;
[SerializeField] float distanceBeforeZoom;
[SerializeField] float camZoomFactor = 1.5f;
Vector3 offset;
Quaternion angle;
float cam_y;
float cam_z;
float cam_x;
float distance;
void Start()
{
Vector3 midPoint = (p_Transform.position + h_Transform.position) / 2; // midpoint between hero and player
offset = transform.position - midPoint;
}
void FixedUpdate () {
//cam_y_offset = camEulerAngle_x;
//cam_z_offset = camEulerAngle_x * -1;
if (!LevelState.levelManager.levelStart) return;
Vector3 midPoint = (p_Transform.position + h_Transform.position) / 2; // midpoint between hero and player
distance = (p_Transform.position - h_Transform.position).magnitude; // absolute distance between Hero and Player
cam_x = midPoint.x;
cam_y = (distance > distanceBeforeZoom) ? midPoint.y + (camZoomFactor * cam_y_offset) : midPoint.y + cam_y_offset; // if distance is greater than allowed, zoom out by certain factor
cam_z = (distance > distanceBeforeZoom) ? midPoint.z + (camZoomFactor * cam_z_offset) : midPoint.z + cam_z_offset; // if distance is greater than allowed, zoom out by certain factor
Vector3 newPosition = new Vector3(cam_x, cam_y, cam_z);
transform.position = Vector3.Lerp(transform.position, newPosition, cameraFollowSpeed * Time.deltaTime); // adjust camera to new position by certain speed
//transform.position = offset + midPoint;
angle.eulerAngles = new Vector3(camEulerAngle_x, 0f, 0f);
transform.rotation = angle; // maintain camera angle
}
}
<file_sep>using UnityEngine;
using System.Collections;
using CnControls;
public class P_MoveNotLeading : MonoBehaviour
{
public H_Health h_health;
float moveX, moveZ;
public float moveSpeed = 20f;
Rigidbody p_Rigidbody;
Animator p_anim;
Vector3 movement;
UnityEngine.AI.NavMeshAgent p_nav;
Transform h_transform;
void Start()
{
p_nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
p_Rigidbody = GetComponent<Rigidbody>();
p_anim = GetComponent<Animator>();
h_transform = h_health.gameObject.transform;
}
void FixedUpdate()
{
Moving();
}
void Moving()
{
moveX = CnInputManager.GetAxis("Horizontal");
moveZ = CnInputManager.GetAxis("Vertical");
// Only allow movement if Hero is alive and Level has started
if (h_health.currentHealth > 0 && (moveX != 0 || moveZ != 0) && LevelState.levelManager.levelStart)
{
movement = new Vector3(moveX, 0f, moveZ).normalized;
//movement = transform.TransformDirection(moveX, 0f, moveZ);
// Check Distance of Hero and Player
Vector3 distance = (transform.position - h_transform.position);
// Force distance to stay at 35 by zeroing movement values
if (distance.magnitude > 35f)
{
movement = Vector3.zero;
}
// Move via Navmesh and set animation
p_nav.Move(movement * Time.deltaTime * moveSpeed);
p_anim.SetBool("isRunning", true);
// Turning
Quaternion target_rotation = Quaternion.LookRotation(movement);
p_Rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, target_rotation, 10f));
}
else
{
// Stop animation
p_anim.SetBool("isRunning", false);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MobEffect : MonoBehaviour {
E_Movement e_mov1; // This Enemy instance
void Start()
{
e_mov1 = GetComponentInParent<E_Movement>();
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag("EnemyMobEffect"))
{
E_Movement e_mov2 = other.gameObject.GetComponentInParent<E_Movement>(); // Collided with, Enemy instance
if (e_mov2.startChasing)
{
e_mov1.InitiateChase();
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class FadeManager : MonoBehaviour {
public static FadeManager Instance { set; get; }
public Image levelCompleteImage;
public Image levelFailedImage;
public Text levelCompleteText;
public Text levelFailedText;
bool isInTransition;
bool isShowing;
float transition;
float duration;
Image fadeImage;
Text fadeText;
void Awake()
{
if (Instance == null)
{
Instance = this;
}
}
public void Fade(float duration, bool levelComplete, bool showing)
{
isShowing = showing;
this.duration = duration;
isInTransition = true;
transition = 0;
fadeImage = (levelComplete) ? levelCompleteImage : levelFailedImage;
fadeText = (levelComplete) ? levelCompleteText : levelFailedText;
}
void Update ()
{
if (!isInTransition)
return;
transition += (isShowing) ? Time.deltaTime * (1 / duration) : -Time.deltaTime * (1 / duration);
fadeImage.color = Color.Lerp(Color.clear, Color.black, transition);
fadeText.color = Color.Lerp(Color.clear, Color.white, transition);
if (transition >= 1 || transition <= 0)
isInTransition = false;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MaterialFader : MonoBehaviour {
Transform camTransform;
float distance;
Renderer rend;
float maxSolidDistance;
float newAlpha;
Transform treeTransform;
void Start () {
rend = GetComponent<Renderer>();
newAlpha = 1f;
maxSolidDistance = 50;
treeTransform = GetComponentInParent<Transform>();
}
void FixedUpdate () {
if (!LevelState.levelManager.levelStart) return;
//float newAlpha = 1f;
distance = Vector3.Distance(Camera.main.transform.position, treeTransform.position);
if (distance < maxSolidDistance)
{
newAlpha -= 0.1f;
}
else
{
newAlpha = 1f;
}
newAlpha = Mathf.Clamp(newAlpha, 0.1f, 1f); // limits transparency from 0.1f to 1f
rend.material.color = new Color(rend.material.color.r, rend.material.color.g, rend.material.color.b,
newAlpha);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class H_MoveLeading : MonoBehaviour {
public Transform[] pathPoints;
UnityEngine.AI.NavMeshAgent h_nav;
int currDest = 0;
H_Health h_health;
Animator h_anim;
void Start()
{
h_nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
h_health = GetComponent<H_Health>();
h_anim = GetComponent<Animator>();
}
void FixedUpdate()
{
if (h_health.isDead || !LevelState.levelManager.levelStart)
{
h_anim.SetBool("isRunning", false);
h_nav.SetDestination(transform.position);
return;
}
h_nav.SetDestination(pathPoints[currDest].position);
h_anim.SetBool("isRunning", true);
}
void OnTriggerEnter(Collider other)
{
//Debug.Log("Enter");
if (other.gameObject.CompareTag("PathPoint") && currDest < pathPoints.Length)
{
other.gameObject.SetActive(false);
currDest++;
//Debug.Log("Point reached");
}
else if (other.gameObject.CompareTag("Goal"))
{
// Level end here.. use :manager:
LevelState.levelManager.StopLevel(true);
//Debug.Log("Level Complete!");
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class ResetGameProgress : MonoBehaviour {
void ResetGame()
{
PersistentGameManager.manager.currentLevel = 1;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using CnControls;
public class P_MoveLeading : MonoBehaviour
{
public H_Health h_health;
float moveX, moveZ;
public float moveSpeed = 20f;
Rigidbody p_Rigidbody;
UnityEngine.AI.NavMeshAgent p_nav;
void Start()
{
p_nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
p_Rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (h_health.currentHealth > 0)
{
Moving();
}
}
void Moving()
{
moveX = CnInputManager.GetAxis("Horizontal");
moveZ = CnInputManager.GetAxis("Vertical");
if (moveX != 0 || moveZ != 0)
{
p_nav.Move(new Vector3(moveX, 0f, moveZ) * Time.deltaTime * moveSpeed);
//transform.Rotate(new Vector2(moveX, moveZ));
Quaternion target_rotation = Quaternion.LookRotation(new Vector3(moveX, 0f, moveZ));
p_Rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, target_rotation, 10f));
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Goal"))
{
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class E_Attack : MonoBehaviour {
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
GameObject hero;
bool heroInRange;
float timer;
H_Health h_Health;
void Start () {
hero = GameObject.FindGameObjectWithTag("Hero");
h_Health = hero.GetComponent<H_Health>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject == hero)
{
heroInRange = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject == hero)
{
heroInRange = false;
}
}
void FixedUpdate()
{
if (!LevelState.levelManager.levelStart)
return;
timer += Time.deltaTime;
if (timer >= timeBetweenAttacks && heroInRange)
{
Attack();
}
}
void Attack()
{
timer = 0f;
if (h_Health.currentHealth > 0)
{
h_Health.TakeDamage(attackDamage);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class E_Movement : MonoBehaviour {
public bool startChasing = false;
GameObject chaseImageObj;
Image chaseImage;
GameObject hero;
Transform h_Transform;
H_Health h_health;
UnityEngine.AI.NavMeshAgent e_nav;
Animator e_anim;
GameObject e_image;
float glowAlpha;
float factor = 1f;
void Start()
{
e_nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
chaseImageObj = GameObject.FindGameObjectWithTag("ChaseImage");
hero = GameObject.FindGameObjectWithTag("Hero");
h_Transform = hero.transform;
h_health = hero.GetComponent<H_Health>();
e_anim = GetComponent<Animator>();
e_image = GetComponentInChildren<Image>().gameObject;
e_image.SetActive(false);
chaseImage = chaseImageObj.GetComponent<Image>();
}
void FixedUpdate()
{
if (!LevelState.levelManager.levelStart)
{
e_nav.SetDestination(transform.position);
e_anim.SetBool("isRunning", false);
return;
}
if (startChasing && h_health.currentHealth > 0)
{
ChaseHero();
}
else
{
StopChase();
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject == hero)
{
InitiateChase();
}
}
void OnCollisionEnter(Collision other)
{
if (startChasing && other.gameObject.CompareTag("Player"))
{
StartCoroutine(SlowDown());
}
}
IEnumerator SlowDown()
{
e_nav.speed = 10f;
e_anim.speed = 0.5f;
yield return new WaitForSeconds(3f);
e_nav.speed = 18f;
e_anim.speed = 1f;
}
public void InitiateChase()
{
startChasing = true;
e_image.SetActive(true);
}
public void ChaseHero()
{
e_nav.SetDestination(h_Transform.position);
e_anim.SetBool("isRunning", true);
chaseImage.color = Color.Lerp(Color.white, Color.black, Mathf.PingPong(Time.time, 1));
if (glowAlpha >= 0.3f) factor = -1f;
else if (glowAlpha <= 0.1) factor = 1f;
glowAlpha += factor * 0.01f;
chaseImage.color = new Color(1, 0, 0, glowAlpha);
}
public void StopChase()
{
e_anim.SetBool("isRunning", false);
e_image.SetActive(false);
e_nav.SetDestination(transform.position);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class EnemyCreator : MonoBehaviour {
[SerializeField]
private GameObject[] enemies;
[SerializeField]
private Transform[] spawnPoints;
private int currentEnemyNum = 0;
public int maxEnemiesAllowed;
bool startCreating = false;
void Start()
{
//maxEnemiesAllowed = spawnPoints.Length;
StartCoroutine(OneTimeCreate());
}
IEnumerator OneTimeCreate()
{
yield return new WaitForSeconds(1.5f);
startCreating = true;
}
void LateUpdate()
{
if (startCreating)
{
Spawn();
CheckEnemies();
}
}
void Spawn()
{
if (currentEnemyNum >= maxEnemiesAllowed)
return;
int i_enemy = Random.Range(0, enemies.Length);
int i_spawnPoint;
bool spawnPointActive = false;
while (!spawnPointActive)
{
i_spawnPoint = Random.Range(0, spawnPoints.Length);
if (spawnPoints[i_spawnPoint].gameObject.activeInHierarchy)
{
spawnPointActive = true;
Instantiate(enemies[i_enemy], spawnPoints[i_spawnPoint].position, spawnPoints[i_spawnPoint].rotation, this.gameObject.transform);
spawnPoints[i_spawnPoint].gameObject.SetActive(false);
}
}
++currentEnemyNum;
}
void CheckEnemies()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
currentEnemyNum = enemies.Length;
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class MainMenuShowHide : MonoBehaviour {
public GameObject mainMenuCanvas;
public GameObject levelSelection;
public void ShowLevelSelection()
{
mainMenuCanvas.SetActive(false);
levelSelection.SetActive(true);
}
public void ShowMenu()
{
levelSelection.SetActive(false);
mainMenuCanvas.SetActive(true);
}
public void HideLevelSelection()
{
mainMenuCanvas.SetActive(false);
levelSelection.SetActive(false);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using CnControls;
public class LevelState : MonoBehaviour {
public static LevelState levelManager;
[SerializeField]
private Text levelStateText;
[SerializeField]
private Image levelStateImage;
public H_Health h_health;
private EnemyCreator enemyCreator;
public AudioClip kulintangAudio;
public GameObject p_Controls;
public bool levelStart;
bool STOPPED;
void OnEnable()
{
levelStart = false;
}
void Start()
{
STOPPED = false;
levelManager = this;
levelStart = false;
enemyCreator = GetComponent<EnemyCreator>();
enemyCreator.enabled = false;
p_Controls.SetActive(false);
}
void FixedUpdate()
{
if (!STOPPED && PersistentGameManager.manager.levelLoaded_ && !levelStart && (CnInputManager.TouchCount > 0 || Input.GetKeyUp(KeyCode.Space)))
{
StartLevel();
}
}
void StartLevel()
{
levelStart = true;
p_Controls.SetActive(true);
enemyCreator.enabled = true;
levelStateText.color = Color.clear;
levelStateImage.color = Color.clear;
}
public void StopLevel(bool levelComplete)
{
if (levelComplete) h_health.currentHealth *= 5;
STOPPED = true;
levelStart = false;
p_Controls.SetActive(false);
PersistentGameManager.manager.EndLevel(levelComplete);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class MenuManager : MonoBehaviour {
public GameObject main;
public GameObject levelSelect;
public GameObject inLevelMenu;
// 1 = Main menu
// 2 = Level Select menu
// 3 = Settings menu
public void ShowMenu(int menuNumber)
{
inLevelMenu.SetActive(false);
if (menuNumber == 1)
{
levelSelect.SetActive(false);
main.SetActive(true);
}
else if (menuNumber == 2)
{
main.SetActive(false);
levelSelect.SetActive(true);
}
}
public void InLevelMenu(bool show)
{
inLevelMenu.SetActive(show);
}
public void HideAllMenus()
{
levelSelect.SetActive(false);
main.SetActive(false);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class H_MoveNotLeading : MonoBehaviour
{
UnityEngine.AI.NavMeshAgent h_nav;
public Transform p_transform;
public Button boostButton;
public Image coolDownImage;
public Image boostIndicator;
public Image boostGlowImage;
bool goto_p = true;
H_Health h_health;
Animator h_anim;
float boostCooldown;
bool boosting = false;
Color indicatorColor;
Color boostedColor;
float glowAlpha;
float factor = 1f;
void Start()
{
h_health = GetComponent<H_Health>();
h_nav = GetComponent<UnityEngine.AI.NavMeshAgent>();
h_anim = GetComponent<Animator>();
boostButton.onClick.AddListener(Boost);
boostButton.interactable = true;
boosting = false;
indicatorColor = new Color(1f, 0, 0,0.5f);
boostedColor = new Color(1f, 0, 0, 0.8f);
boostIndicator.color = indicatorColor;
}
void FixedUpdate()
{
coolDownImage.fillAmount = boostCooldown;
if (boostCooldown > 0 && !boosting)
{
boostCooldown -= Time.fixedDeltaTime;
}
else if (!boosting && boostCooldown <= 0)
{
boostButton.interactable = true;
}
if (goto_p && !h_health.isDead && LevelState.levelManager.levelStart)
{
h_nav.SetDestination(p_transform.position);
h_anim.SetBool("isRunning", true);
}
else
{
h_anim.SetBool("isRunning", false);
h_nav.SetDestination(transform.position);
}
if (boosting)
{
BoostingEffects();
}
}
void OnTriggerEnter(Collider other)
{
//Debug.Log("Enter");
if (other.gameObject.CompareTag("Player"))
{
goto_p = false;
if (boosting) StopBoost();
}
if (other.gameObject.CompareTag("Goal")) LevelState.levelManager.StopLevel(true);
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
goto_p = true;
}
//Debug.Log("Exit" + other.gameObject.tag + goto_p);
}
public void Boost()
{
//boostIndicator.color = boostedColor;
h_nav.speed = 25f;
//h_nav.acceleration = 25f;
boostButton.interactable = false;
boosting = true;
glowAlpha = .1f;
}
void StopBoost()
{
boostCooldown = 1f;
boostIndicator.color = indicatorColor;
boosting = false;
h_nav.speed = 14f;
boostGlowImage.color = Color.clear;
//h_nav.acceleration = 16f;
}
void BoostingEffects()
{
if (glowAlpha >= 0.8f) factor = -1f;
else if (glowAlpha <= 0.1) factor = 1f;
glowAlpha += factor * 0.05f;
boostGlowImage.color = new Color(1, 0, 0, glowAlpha);
boostIndicator.color = new Color(1, 0, 0, glowAlpha);
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LoadingScreen : MonoBehaviour {
Text loadingText;
bool fading;
void Start()
{
fading = true;
loadingText = GetComponentInChildren<Text>();
StartCoroutine(Fade());
}
void OnDisable()
{
fading = false;
}
IEnumerator Fade()
{
yield return new WaitForSeconds(.5f);
while (fading)
{
yield return new WaitForSeconds(.5f);
loadingText.color = Color.Lerp(Color.clear, Color.white, .1f);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using UnityEngine.Audio;
public class PersistentGameManager : MonoBehaviour {
public static PersistentGameManager manager;
[HideInInspector] public int loadedLevel = 0;
[HideInInspector] public GameObject hero;
[HideInInspector] public GameObject player;
public bool levelLoaded_ = false;
public Text messageText;
public int currentLevel = 1;
public GameObject bg;
public AudioSource audioSource;
AudioMixerGroup originalMixerGroup;
MenuManager menuManager;
public GameObject loadingScreen;
GameObject terrain;
public AudioClip gong;
void Awake()
{
//Debug.Log("scene count: " + SceneManager.sceneCountInBuildSettings);
//Debug.Log(Application.persistentDataPath);
if (manager == null)
{
DontDestroyOnLoad(this);
manager = this;
}
else if (manager != this)
{
Destroy(gameObject);
}
levelLoaded_ = false;
Load();
}
void Start()
{
//audioSource.Play();
hero = GameObject.FindGameObjectWithTag("Hero");
player = GameObject.FindGameObjectWithTag("Player");
audioSource = GetComponent<AudioSource>();
menuManager = GetComponent<MenuManager>();
messageText.text = messageText.text + " " + currentLevel;
}
public void Reset()
{
currentLevel = 1;
messageText.text = messageText.text + " " + currentLevel;
Save();
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.OpenOrCreate);
PlayerData data = new PlayerData(currentLevel);
bf.Serialize(file, data);
file.Close();
}
public void Load()
{
if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
PlayerData data = (PlayerData) bf.Deserialize(file);
currentLevel = data.level;
}
}
public void EndLevel(bool levelComplete)
{
menuManager.InLevelMenu(false);
int loadLevel;
if (levelComplete)
{
audioSource.Stop();
audioSource.PlayOneShot(gong,1);
loadLevel = SceneManager.GetActiveScene().buildIndex + 1;
Save();
}
else
{
loadLevel = SceneManager.GetActiveScene().buildIndex;
}
if (levelComplete && loadLevel >= SceneManager.sceneCountInBuildSettings)
{
loadLevel = 0;
StartCoroutine(EndGameSequence());
return;
}
StartCoroutine(EndLevelSequence(loadLevel, levelComplete));
}
public void LoadLastLevel()
{
LoadGameLevel(currentLevel);
}
public void LoadGameLevel(int level)
{
loadingScreen.SetActive(true);
ActiveLevel(level);
SceneManager.LoadScene(level, LoadSceneMode.Single);
levelLoaded_ = false;
}
public void LoadMainMenu()
{
SceneManager.LoadScene(0, LoadSceneMode.Single);
menuManager.ShowMenu(1);
InactiveLevel();
}
public void ActiveLevel(int level)
{
menuManager.HideAllMenus();
menuManager.InLevelMenu(true);
//audioSource.clip = kulintang;
audioSource.Play();
bg.SetActive(false);
loadedLevel = level;
}
public void InactiveLevel()
{
audioSource.Stop();
bg.SetActive(true);
}
IEnumerator EndLevelSequence(int loadLevel, bool levelComplete)
{
FadeManager.Instance.Fade(1f, levelComplete, true);
yield return new WaitForSeconds(2f);
LoadGameLevel(loadLevel);
FadeManager.Instance.Fade(1f, levelComplete, false);
}
// Temporary End Game Sequence
IEnumerator EndGameSequence()
{
FadeManager.Instance.Fade(1f, true, true); // level Complete image fade In
yield return new WaitForSeconds(2f);
FadeManager.Instance.Fade(1f, true, false); // level Complete image fade Out
// Back to Main Menu
LoadMainMenu();
}
void FixedUpdate()
{
//Debug.Log("Level loaded: " + levelLoaded_);
if (!levelLoaded_)
{
hero = GameObject.FindGameObjectWithTag("Hero");
player = GameObject.FindGameObjectWithTag("Player");
terrain = GameObject.FindGameObjectWithTag("Terrain");
if (hero != null && player != null && terrain != null)
{
loadingScreen.SetActive(false);
levelLoaded_ = true;
}
}
}
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
[Serializable]
class PlayerData
{
public int level;
public PlayerData(int lvl)
{
level = lvl;
}
}
|
9cdd4f480726934cb2d79b09f010b5bfdca0ee98
|
[
"C#"
] | 17 |
C#
|
lleeeaaaannnnn/kachil
|
32a573d49e6a353bae937549c9024ff41b36ad78
|
3b0661388c6c26730ffea4f7c68b45839dad8a14
|
refs/heads/master
|
<file_sep>// *** Vector ***
// set up vector with dimensions as required
function Vector(x, y, z) {
this.x = this.ox = x || 0;
this.y = this.oy = y || 0;
this.z = this.oz = z || 0;
}
Vector.prototype = {
set: function(x, y, z) {
if (typeof x === 'object') {
z = x.z;
y = x.y;
x = x.x;
}
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
return this;
},
add: function(v) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
},
sub: function(v) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
},
scale: function(s) {
this.x *= s;
this.y *= s;
this.z *= s;
},
rotate: function(m, c, x, y, z) {
rx = m.x || 0;
ry = m.y || 0;
rz = m.z || 0;
// rotate x axis
if (x != 0) {
xx = rx
xy = Math.cos(x)*ry + Math.sin(x)*rz;
xz = Math.cos(x)*rz - Math.sin(x)*ry;
}
else {
xx = rx;
xy = ry;
xz = rz;
}
//rotate y axis
if (y != 0) {
yx = Math.cos(y)*xx - Math.sin(y)*xz;
yy = xy;
yz = Math.cos(y)*xz + Math.sin(y)*xx;
}
else {
yx = xx;
yy = xy;
yz = xz;
}
//rotate z axis
if (z != 0) {
zx = Math.cos(z)*yx - Math.sin(z)*yy;
zy = Math.cos(z)*yy + Math.sin(z)*yx;
zz = yz;
}
else {
zx = yx;
zy = yy;
zz = yz;
}
this.x = zx + c.x; // return screen to centre
this.y = zy + c.y;
this.z = zz + c.z;
},
length: function(n) {
return Math.sqrt(Math.pow(this.ox - n.ox, 2) + Math.pow(this.oy - n.oy, 2) + Math.pow(this.oz - n.oz, 2));
},
height: function(n) {
return this.oz - n.oz;
},
angle: function() {
return Math.atan2(this.y, this.x);
},
angleTo: function(v) {
var dx = v.x - this.x,
dy = v.y - this.y;
return Math.atan2(dy, dx);
},
distanceTo: function(v) {
var dx = v.x - this.x,
dy = v.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
},
distanceToO: function(v) {
var dx = v.ox - this.ox,
dy = v.oy - this.oy;
return Math.sqrt(dx * dx + dy * dy);
},
};
// *** Node ***
function Node(x, y, z, i, p) {
Vector.call(this, x, y, z);
this.id = i;
this._pipe = p || 3;
this.previous = this;
};
// give node vector methods
Node.prototype = (function(o) {
var s = new Vector(0, 0, 0), p;
for (p in o) s[p] = o[p];
return s;
})({
isMouseOver: false,
dragging: false,
_easeRadius: 0,
_dragDistance: null,
selected: false,
COLOR: '#fff',
piped: false,
stope: 0,
highlight: false,
choke: 0,
yield: 0,
hitTest: function(p) {
return this.distanceTo(p) < 5;
},
startDrag: function(dragStartPoint) {
this.dragging = true;
},
drag: function(dragToPoint, n) {
for (var i = 0; i < len; i++) {
if (i === this.id) continue;
n[i].x = dragToPoint.x - this.x + n[i].x;
n[i].y = dragToPoint.y - this.y + n[i].y;
}
this.x = dragToPoint.x;
this.y = dragToPoint.y;
},
endDrag: function() {
this.dragging = false;
},
pressure: function(n) { //used to get the immediate total pressure of a single point
var j, i;
i = nodes[n];
j = this._pipe;
return i.pressure + (this.length(i)+i.choke) * pipes[j]._friction;
},
pressureChange: function(n) { // used to set up pressure array for route
var i = this._pipe;
return (this.length(n)+n.choke) * pipes[i]._friction;
},
render: function(ctx, m, r) {
var c, d;
if (this.highlighted) c = d = '#cc2';
else if (this.dragging || this.selected) c = d = SELECT_COLOR;
else if (this.isMouseOver) c = d = HOVER_COLOR;
else if (m === 2) c = d = r; //color for pressure
else if (m === 1) c = d = '#666'; //color grey
else c = d = this.COLOR; //arrgnt color
if (this.stope) c = STOPE_COLOR;
this._draw(ctx, c, d);
},
_draw: function(ctx, c, d) {
var r, g, rgba, rgbb, grad;
n = this;
p = n.previous;
ctx.fillStyle = c
ctx.strokeStyle = d;
ctx.beginPath();
ctx.moveTo(n.x, n.y);
if (n.choke > 0) {
ctx.arc(n.x, n.y, NODE_RADIUS+2, 0, Math.PI * 2, false);
ctx.stroke();
}
else {
ctx.arc(n.x, n.y, NODE_RADIUS, 0, Math.PI * 2, false);
ctx.fill();
}
if (n.piped) {
ctx.beginPath();
ctx.moveTo(n.x, n.y);
ctx.lineTo(p.x, p.y);
ctx.closePath();
ctx.stroke();
}
if (!graph && this.stope) {
console.log(this.yield);
if (this.yield > 250) {
g = 250;
r = 0;
}
else if (this.yield > 100) {
g = parseInt(((this.yield-100)/150)*250) || 0;
r = parseInt(250-((this.yield-100)/150)*250) || 0;
}
else {
g = 0;
r = 250;
}
rgba = 'rgba(' + String(r) + ',' + String(g) + ',0, 0)';
rgbb = 'rgba(' + String(r) + ',' + String(g) + ',0, 0.8)';
grad = ctx.createRadialGradient(n.x, n.y, 0, n.x, n.y, 20);
grad.addColorStop(0, rgba);
grad.addColorStop(0.4, rgbb);
grad.addColorStop(1, rgba);
ctx.fillStyle = grad;
ctx.moveTo(n.x, n.y);
ctx.arc(n.x, n.y, 40, 0, Math.PI * 2, false);
ctx.fill();
}
}
});
// *** Route ***
function Route(s) {
this.s = s; // stope node (object)
this.a = []; // array of nodes from stope
this.p = []; // array of pressures from stope
this.d = []; // array of pipe distance from pump
this.e = []; // array of elevations from stope
this.r = []; // array of pressure ratings from stope
this.selected = false;
this.xScale = 1;
this.yScale = 1;
this.hover = null;
};
Route.prototype = {
updateArrgt: function() {
var i, n, m, dist, h;
n = this.s;
dist = 0;
h = 0;
this.a = [n];
this.d = [dist];
this.e = [h];
this.r = [h + pipes[n._pipe]._rating*1000/9.81/DENSITY];
while (n != n.previous) { // add nodes in reverse order back to pump
m = n.previous;
h += m.height(n);
this.a.push(m);
this.e.push(h);
this.r.push(h + pipes[n._pipe]._rating*1000/9.81/DENSITY);
n = m;
}
for (i = this.a.length-1; i >= 1; i--) { //add distances
n = this.a[i];
m = this.a[i-1];
dist += (n.length(m) + m.choke)
this.d.push(dist);
}
this.xScale = this.d[this.d.length-1]/(screenWidth/4);
this.yScale = this.r[this.r.length-1]/(screenHeight/4);
},
updatePressure: function() { // 'g' to be used if changes made to recipe or flow only
var a, n, m, p, t;
a = this.a; // route
this.p = [0]
p = t = 0; // stope pressure
for (i = 0; i < a.length-1; i++) {
n = a[i]; // current node (starts at stope)
m = a[i+1]; // previous node
p = m.pressureChange(n)/DENSITY/9.81; // change between previous node and current
t += p
if (t < this.e[i+1]-8) {
t = this.e[i+1] - 8; // if pressure below pipe profile
}
this.p.push(t);
}
},
distanceTo: function(a, b) { //x coordinates only
var d = a - b;
return Math.sqrt(d * d);
},
hitTest: function(p, c) { //mouse, cvs
var i, m, x, d, c;
this.hover = null;
c = c;
x = p.x - (screenWidth*0.75); // mouse x coordinates within context
m = this.distanceTo(this.d[0]/this.xScale, x);
n = 0;
for (i = 1; i < this.d.length; i++) {
d = this.distanceTo(this.d[i]/this.xScale, x)
if (d < m) {
m = d;
n = this.a.length-1-i;
}
}
this.hover = n;
return this.a[n];
},
_draw: function(ctx, w, h) {
var c, x, y, sx, sy, h, w;
c = ctx;
h = h;
w = w;
sx = this.xScale;
sy = this.yScale;
x = 0; // first point at pump
y = h - (this.e[this.e.length-1] / sy);
c.beginPath(); // draw pipe profile
c.moveTo(x, y);
for (i = 1; i < this.a.length; i++) {
j = this.a.length -1 - i;
x = (this.d[i] / sx);
y = h - (this.e[j] / sy);
c.lineTo(x, y);
}
c.strokeStyle = '#4f4';
c.stroke();
x = this.d[0] / sx; // first point at pump
y = h - this.p[this.p.length-1] / sy;
c.beginPath(); // draw HGL
c.moveTo(x, y);
for (i = 1; i < this.a.length; i++) {
j = this.a.length - 1 - i;
x = this.d[i] / sx;
y = h - this.p[j] / sy;
c.lineTo(x, y);
}
c.strokeStyle = '#ddd';
c.stroke();
x = this.d[0] / sx; // first point at pump
y = h - this.r[this.r.length-1] / sy;
c.beginPath(); // draw RATING
c.moveTo(x, y);
for (i = 1; i < this.a.length; i++) {
j = this.a.length - 1 - i;
x = this.d[i] / sx;
y = h - this.r[j] / sy;
c.lineTo(x, y);
}
c.strokeStyle = '#a22';
c.stroke();
if (this.hover != null) {
c.beginPath();
x = this.d[this.d.length - this.hover -1] / sx;
c.moveTo(x, 0);
c.lineTo(x, h);
c.strokeStyle = '#ddd';
c.stroke();
}
}
};
// *** Button ***
function Button(x, y, t, type) {
Vector.call(this, x, y);
this.x = x;
this.y = y;
this.text = t;
this.radius = 10;
this.type = type;
if (this.type === 'a') this.color = BUTTON_COLOR;
else this.color = TAB_COLOR;
};
// give node vector methods
Button.prototype = (function(o) {
var s = new Vector(0, 0, 0), p;
for (p in o) s[p] = o[p];
return s;
})({
isMouseOver: false,
dragging: false,
selected: false,
hitTest: function(p) {
return this.distanceTo(p) < 15;
},
startDrag: function(dragStartPoint) {
this.dragging = true;
},
endDrag: function(g) {
this.dragging = false;
if (this.isMouseOver) this.select(g);
},
select: function(g) {
var t = this.selected;
for (var i = 0; i < g.length; i++) {
g[i].selected = false;
}
if (t) this.selected = false;
else this.selected = true;
},
render: function(ctx) {
if (this.dragging || this.selected) {
this._draw(ctx, SELECT_COLOR);
}
else if (this.isMouseOver) {
this._draw(ctx, HOVER_COLOR);
}
else {
this._draw(ctx, this.color)
}
},
_draw: function(ctx, c) {
if (this.type === 'a') {
ctx.fillStyle = c;
ctx.beginPath();
//ctx.arc(screenWidth - 65, this.y, this.radius, 0, Math.PI * 2, false);
ctx.textAlign = 'center';
ctx.fillText(this.text, this.x, this.y);
ctx.fill();
ctx.restore();
}
if (this.type === 'b') {
ctx.fillStyle = c;
ctx.fillRect(this.x, 0, TAB_WIDTH, TAB_HEIGHT);
ctx.fillStyle = '#eee';
ctx.fillText(this.text, this.x+10, this.y-5)
ctx.fill();
ctx.restore();
}
if (this.type === 'c') {
ctx.fillStyle = c;
ctx.fillText(this.text, this.x-25, this.y+6);
ctx.fill();
ctx.restore();
}
}
});
function Graph(data) {
this.y = data || [];
this.my = 0;
this.yScale = screenHeight/4/1500;
this.hover = null;
};
Graph.prototype = {
update: function(which) {
var r, y, z, my = 0;
if (which) {
graph = 1;
y = [];
for (i = 0; i < routes.length; i++) {
r = routes[i]
r.updateArrgt();
y.push(r.p[r.p.length-1] - r.e[r.e.length-1]);
}
this.yScale = screenHeight/4/1500;
}
else {
graph = 0;
y = [];
for (i = 0; i < routes.length; i++) {
r = routes[i]
y.push(r.a[0].yield);
}
this.yScale = screenHeight/4/750;
}
this.y = y;
},
hitTest: function(p) { //mouse
var x;
this.hover = null;
x = p.x - (screenWidth*0.75); // mouse x coordinates within context
this.hover = parseInt(x/(screenWidth*0.25/this.y.length));
return this.hover;
},
_draw: function(ctx) {
var i, len, y, dx, bx, by, bh, bw, text;
c = ctx;
len = this.y.length;
dx = screenWidth/4/len;
for (i = 0; i < len; i++) {
y = this.y[i];
if (i === this.hover) c.fillStyle = '#777';
else c.fillStyle = '#444';
bx = parseInt(dx*i);
by = screenHeight/4;
bw = parseInt(dx*0.7);
bh = -1*parseInt(y*this.yScale);
if (graph) text = String(parseInt(y/10)/100);
else text = String(parseInt(y));
c.fillRect(bx, by, bw, bh);
c.fillStyle = '#ccc';
c.fillText(text, bx, by-10);
c.fill();
}
}
};
function Crosshairs(i, x, y) {
Vector.call(this, x, y);
this.id = i;
this.x = x;
this.y = y;
};
Crosshairs.prototype = (function(o) {
var s = new Vector(0, 0, 0), p;
for (p in o) s[p] = o[p];
return s;
})({
isMouseOver: false,
dragging: false,
isActive: false,
hitTest: function(p) {
var x, y;
x = p.x - screenWidth*0.75 - this.x;
y = p.y - this.y;
if (this.id === 'a') y -= screenHeight*0.25;
return (x > -20 && y > -20 && x < 20 && y < 20);
},
startDrag: function(dragStartPoint) {
this.dragging = true;
this.isActive = true;
},
drag: function(dragToPoint) {
var x;
x = dragToPoint.x - screenWidth * 0.75;
if (x > 0) this.x = x;
if (this.id === 'a') this.y = dragToPoint.y - screenHeight * 0.25;
},
endDrag: function(g) {
this.dragging = false;
},
_draw: function(ctx) {
var a, x, y, w, h, c;
c = ctx
w = screenWidth/4;
h = screenHeight/4;
x = this.x;
y = this.y;
if (this.isActive) a = '#e72';
else a = '#888';
if (this.id === 'a') {
c.beginPath();
c.moveTo(0, y);
c.lineTo(w, y);
c.moveTo(x, 0);
c.lineTo(x, h);
c.strokeStyle= '#666';
c.lineWidth = 1;
c.stroke();
c.beginPath();
c.moveTo(x-15, y);
c.lineTo(x+15, y);
c.moveTo(x, y-15);
c.lineTo(x, y+15);
c.strokeStyle = a;
c.lineWidth = 3;
c.stroke();
c.fillStyle = '#ccc'
c.fillText(parseInt(FLOW_RATE) + ' m3/h', x+2, h-2);
c.fillText(parseInt(TONNAGE) + ' t/h', 0, y-2);
c.fill();
}
else if (this.id === 'b') {
c.save();
c.beginPath();
c.moveTo(0, y);
c.lineTo(w, y);
c.strokeStyle= '#333';
c.lineWidth = 2;
c.stroke();
c.beginPath();
c.moveTo(x-7, h-2);
c.lineTo(x+7, h-2);
c.moveTo(x+7, y-15);
c.lineTo(x-7, y-15);
c.moveTo(x, h-2);
c.lineTo(x, y-15);
c.closePath();
c.strokeStyle= a;
c.lineWidth = 3;
c.stroke();
c.restore();
c.fillStyle = '#ccc'
c.fillText(parseInt(MAX_PUMP/100)/10 + ' MPa', x+5, y);
}
}
});
function SteelPipe(id, diameter, rating, OD, wall, wear) {
this.id = id;
this.d = diameter;
this.r = rating;
this.OD = OD;
this.t = wall;
this.ID = this.OD-(this.t*2);
this.CSA = (Math.PI*(this.ID*this.ID)) / 4000000;
this.mass = (Math.PI*(this.OD*this.OD)) / 4000000 - this.CSA;
this.wear = wear || 1.5;
if (this.d < 8) {
this.groove = 2.11;
this.weld = 0.85;
}
else {
this.groove = 2.34;
this.weld = 1;
}
if (this.r <= 4) {
this.coupling = '77';
if (this.d < 8) this.c_rating = 6.89;
else this.c_rating = 5.82;
}
else if (this.r === 8) {
this.coupling = 'HP70ES';
if (this.d === 4) this.c_rating = 17.24;
else if (this.d === 6) this.c_rating = 13.79;
else this.c_rating = 10.34;
}
else if (this.r >= 12) {
this.coupling = '808';
if (this.d < 8) this.c_rating = 20.68;
else this.c_rating = 17.24;
}
this.rating();
this.update();
}
SteelPipe.prototype = {
p_rating: 0,
_rating: 0,
_text: '',
_velocity: 0,
_friction: 0,
_length: 0,
rating: function() {
this.min_t = this.t * (1 - MILL_TOLERANCE) - (this.wear + this.groove);
this.p_rating = (2 * MIN_YIELD * this.weld * WELD_STRENGTH * this.min_t / (this.OD-(2 * Y_VALUE * this.min_t)))
if (this.c_rating > this.p_rating) this._rating = this.p_rating;
else this._rating = this.c_rating;
},
update: function() {
this._velocity = this.velocity(FLOW_RATE);
this._friction = this.friction(YIELD_STRESS, VISCOSITY);
this.text();
},
velocity: function(f) {
return f / this.CSA / 3600;
},
friction: function(y,vis) {
/*
// Durand using Colebrook-White
var w, d, v, Re, Rek, r, f, Func, diff, colebrook, g, vs, vw, Cv;
w = 1000,
r = 0.0000508,
d = this.ID/1000,
v = this._velocity,
Func = 1,
Re = w * v * d / 0.001002,
g = 9.81;
vw = TONNAGE/CONCENTRATION - TONNAGE;
vs = TONNAGE/SG;
Cv = vs/(vw + vs);
if (Re > 0) {
f = Math.pow(1 / (4 * Math.log(3.7 * d / r) / Math.log(10)), 2);
Rek = r / d * Re * Math.sqrt(f / 2); // Roughness Reynold's number
if (Rek < 70) {
f = 0.079 / Math.pow(Re, 0.25); // Blasius equation
while (Math.abs(Func) > 0.00001) {
Func = Math.pow(f, -0.5) + 4 * Math.log(r / (3.7 * d) + 1.26 * (Math.pow(f, -0.5)) / Re) * 1 / Math.log(10);
diff = -0.5 * Math.pow(f, (-3 / 2)) + 4 / Math.log(10) * 1 / (r / 3.7 / d + 1.26 / (Re * Math.pow(f, 0.5))) * (-1.26 / 2 / Re * Math.pow(f, (-3 / 2)));
f = f - Func / diff;
}
}
else f = Math.pow(1 / (4 * Math.log(3.7 * d / r) / Math.log(10)), 2);
}
else f = 0;
colebrook = 2 * w * f * Math.pow(v, 2) / d / 1000;
return colebrook * (DENSITY + 85 * Cv * Math.pow(((g * d * (SG - 1)/1)/Math.pow(v, 2))*(1/ Math.sqrt(4)), 3/2))
*/
// Homogeneous
var v, i, t, n = 1, c = 0,
low = y,
high = 100000,
d = this.ID/1000,
v = this._velocity,
l = 8 * v / d,
r = 1;
while (Math.abs(l-r) > 0.0001) {
c++;
t = (low + high) / 2;
var a = 4 * n / Math.pow(t,3) * Math.pow(1/vis,1/n) * Math.pow(t-y,(n+1)/n)
var b = Math.pow(t - y,2) / (3*n+1)+2 * y*(t-y) / (2*n+1) + Math.pow(y,2) / (n+1)
r = a * b
if (r > l) {
high = t;
}
if (r < l) {
low = t;
}
if (v < 0 || c > 1000) {
console.log('gradient error');
break
}
}
return t * 4 / d / 1000
},
totalLength: function() {
var i, n;
this._length = 0;
for (i = 0; i < nodes.length; i ++) {
n = nodes[i];
if (n._pipe === this.id) {
this._length += n.length(n.previous) + n.choke;
}
}
},
text: function() {
this._text = [
String(this.d) + ' in',
'Sch ' + String(this.r) + '0',
String(this.OD),
String(parseInt(this.ID*100)/100),
String(this.t),
String(PIPE_ROUGHNESS),
String(parseInt(this._velocity*100)/100),
String(parseInt(this._friction*1000)/1000),
String(parseInt(this._length)),
String(parseInt(this._rating*100)/100)
]
}
}
|
8f541189f96050f479472b4d2d8b913448541026
|
[
"JavaScript"
] | 1 |
JavaScript
|
philomather/nodejs-ex
|
a8380270bbe4f3ea1f4befef85c57f6644a2cf2d
|
1698373854a6a1428aa7b9aea7386072ad472a93
|
refs/heads/master
|
<repo_name>NrjMeyer/Event<file_sep>/app/controllers/events_controller.rb
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
@event = Event.new(event_params)
@event.creator_id = current_user.id
@event.save
redirect_to user_path(current_user)
end
def show
@event = Event.find(params[:id])
end
def index
@events = Event.all
end
private
def event_params
params.require(:event).permit(:description, :date, :place)
end
end
<file_sep>/README.md
# The Gossip Project
**Projet réaliser par Meyer || sur slack: @meyer**
# Avant propos
Ce projet est inspiré par cel d'un collègue
## Lisez ici,
Tout d'abord, lire le Readme.md jusqu'à la fin avant de corriger.***C'est très important!***
## Projet du jour
**Bonjour les correcteurs !**
Voici la liste des projets aujourd'hui:
- 01 - ***Eventbrite like*** -
> **Note:**
>- Chaque project contient un repertoire github et un lien vers heroku
>- Cloner le repertoire
>- Vérifier d'abord si la version de votre Rails est vieux (version inférieur à 5.x.x, **si c'est le cas, installer la version recommandée** (version 5.x.x)
>- Pas la peine de lancer votre serveur car il suffit de tester le site déployé sur heroku: https://eventbrite-by-thp.herokuapp.com
>- Tout ces codes sont déjà testés et fonctionnent normalement avant d'être uploader sur ce repository. Si vous constatez un problème, n'hésitez pas à me **contacter sur Slack**
|
aa509018514a297a06e175e2762e3c13e8505816
|
[
"Markdown",
"Ruby"
] | 2 |
Ruby
|
NrjMeyer/Event
|
e3720ea13e162ceb59f313797e5e285cd13e7925
|
49e20a45850ddd6cd24479d87cd66e03b8dc462e
|
refs/heads/master
|
<file_sep>from yt_model import YTModel
from yt_view import YTView
class YTController():
''' The controller for the youtube transcription program.
Attributes:
model: an instance of a YTModel object that represents the model of the
youtube transcription program.
view: an instance of the YTView object which represents the view of the
youtube transcription program.
'''
def __init__(self):
self.model = YTModel()
self.view = YTView()
def start_program(self):
''' Starts the youtube transcription program. '''
self.view.introduction()
video_id = self.view.get_youtube_id()
transcript = self.model.get_manually_created_transcript(video_id)
self.view.print_transcript(transcript)
if __name__ == "__main__":
controller = YTController()
controller.start_program()<file_sep>from youtube_transcript_api import YouTubeTranscriptApi
class YTModel():
''' The model of the youtube transcription program. '''
def get_transcript(self, video_id):
''' Gets the transcript of a youtube video.
Args:
video_id: a string representing the id of a youtube video
Returns:
An array of dictionaries each containing duration, start, and text
key pairs that cover the transcription for the youtube video
identified through video_id. Uses manually created transcript
if available, otherwise it will use the auto generated one.
'''
transcript = YouTubeTranscriptApi.get_transcript(video_id)
return transcript
def get_manually_created_transcript(self, video_id):
''' Gets the transcript of a youtube video.
Args:
video_id: a string representing the id of a youtube video
Returns:
An array of dictionaries each containing duration, start, and text
key pairs that cover the manually generated transcription for
the youtube video identified through video_id. If none exists,
it will throw an error.
'''
transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
generated = transcript_list.find_manually_created_transcript(['en'])
return generated.fetch()<file_sep># YoutubeTranscriptionMVC
A coding assignment to transcribe youtube videos using the MVC design pattern. This is a LOT in terms of the depth of thinking you need to do. Remember what I told you this week, try to understand the general philosophy and motivation behind this and don't concern yourself too much with the less important aspects such as coding. It's perfectly okay for the code to not work, that's not the point of this assignment. Give it your best shot and write down every thought in your head concerning each question.
## Introduction
Remember that one of the topics we discussed this week was the MVC (model view controller) design pattern. This is a relatively simple but extremely powerful design pattern used broadly through industry.
You can read more about the MVC pattern [here](https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html) to refresh your memory. This is a very simple approach to MVC, it can actually get quite a bit more complex and there are many different ways to approach implementation of MVC (if you're interested in learning more about what this means ask me in our next lesson!). I was surprised to see a number of other reputable websites discussing MVC pretty badly, Apple does a good job of explaining it here correctly. In any case, I would be wary of what you read on the internet regarding MVC design pattern, it seems some people on the internet do not really understand what MVC is on a foundational level.
MVC is born out of a philosophy of purity, of building a system that is inherently flexible, maintanable, defensive, modular, coordinated, among other things. This is a rapidly growing idea in the field of Computer Science and software, we touched very briefly on functional programming once and it's a great example of this philosophy. Functional programming is a programming paradigm centered on that idea of purity, it's a programming style that in simple terms leads to less bugs and is theoretically very clean.
In any case let's get to the project at hand. You'll be working on a program that transcribes youtube videos and hopefully better understand what MVC means in the real world.
## Set Up
Clone this repository into your projects folder. Click the green "clone" button, copy the web url of this repository. Open terminal, navigate to the projects directory (`cd ~/Desktop/projects/`). Now run the command:
```
git clone https://github.com/foerever/YoutubeTranscriptionMVC.git
```
I'm using a python package manager called pipenv. Remember, we talked about thoughtfulness in everything we build? Package managers are a great example of this. When you're working with others, people might have different software and different versions of libraries installed. That difference can lead to bugs and can lead to programs working for you but not for others. So we document the packages and use a package manager to deal with versioning/installation. These days people take it a step further and fully replicate the entire development environment using something called docker. It's an extremely useful tool but out of the scope of this lesson.
We already used a package manager in our previous projects that you should be somewhat familiar with, npm.
To install this package manager run the following command in terminal:
```
pip3 install pipenv
```
This will use the python 3 default package manager called pip3 to install this somewhat more sophisticated package manager called pipenv.
This repository already has a pipfile which documents what package dependencies you need. To install the required packages I specify, run this command in the terminal (your terminal should be currently in the root of this project folder). To do this open terminal, navigate to the projects directory (`cd ~/Desktop/projects/YoutubeTranscriptionMVC`).
```
pipenv install
```
When you want to work on the project you should run this command so that you are working within the context of the virtual environment set by pipenv:
```
pipenv shell
```
This should turn your regular command line prompt of:
```
anthonyc@Anthonys-MacBook-Pro-4:~/Desktop/projects/YoutubeTranscriptionMVC$
```
Into:
```
(YoutubeTranscriptionMVC) anthonyc@Anthonys-MacBook-Pro-4:~/Desktop/projects/YoutubeTranscriptionMVC$
```
This indicates that you are working in the correct python environment for this project defined by the pipfile. Now we're ready to get started.
## Project
To do this project, we have 3 team members called model, view, and controller. You're the team leader, you need these 3 to work together to transcribe youtube videos. Each team member has something only they're capable of doing. Model can handle all the application logic. View can handle the interface. Controller can control what model and view do at any given time. Now, model and view both really hate you. They refuse to work directly with you. So you can only communicate with them through the controller. One more caveat, because of a special curse the model and view can never know each other exist. This means they can never interact directly with one another.
This is the scenario and how you should think about these 3 seperate components in the context of the MVC design pattern.
The way this program works is extremely simple since our aim is very simple. Our view is the interface for our user, it allows a user to input a youtube url that they want a transcription of. The model is able to retrieve the transcript of a youtube video given its id. The controller actually starts, runs, and coordinates the program. It's what allows us to seperate the model and the view. It is the only place where model and view are imported. It's worth noting here that the more complex of a project you have the more you get to appreciate the power of solid design patterns. This is obviously a relatively simple but interesting program. You should still be able to get the general gist of MVC from this program. To run the project (make sure you're in the pipenv environment noted above) run this command in the terminal:
```
python3 yt_controller.py
```
The program will prompt you for the url of a youtube video to transcribe. Try this example from Khan Academy going over the American healthcare system:
```
https://www.youtube.com/watch?v=VpLKdKkpg68
```
### Problems
(1) What's the problem with using (`get_manually_created_transcript()`) in yt_controller? What if our youtube video doesn't have manually created transcript?
For example, try inputting this WSJ interview with Microsoft CEO Satya Nadella:
```
https://www.youtube.com/watch?v=kexuG-YcQFA
```
Conveniently for us, youtube actually has ~okay auto generated youtube captions which we'll fetch and turn into our transcript. Even more conveniently for us, some other developer (me) already wrote a generalized version in the model that will get the auto generated transcript if the manually created one doesn't exist. This function is `get_transcript()` in the model component. Luckily for us, it's very easy to replace the erroneous part in the controller because we're following the MVC design pattern.
Change the error prone transcribe method used in the controller with the more generalized version.
(2) In `yt_view.py` the function `get_youtube_id()` is somewhat problematic. For one thing, it's succeptible to bugs because we rely too heavily on external dependencies to process inputs that can vary wildly. But one important thing to note is that in using the elegant ternary operator in the last line we don't tell the user why they have to re-input the youtube url. If we fail to capture the video id whether that is the fault of the user or our program, there is simply no handling of this error at all.
Write some error handling code that at a minimum notifies the user of why they have to re-input the youtube url in the case of faulty input or processing.
(3) Let's say our team has had a discussion and determined that url parsing is application logic and therefore should not be contained in the view component. Modify the program such that the url parsing is done in the model instead.
(4) The transcript isn't very pretty. It's in dictionary form. Concatenate the transcript into one long string and print that instead.
(BONUS) Create additional functionality in our program such that a user can search the video for the timestamp(s) (if any) in which the video mentions some key phrase (which the user can input).
For example, you can imagine that there is a student who is looking through long (1-2 hour) lecture videos about the biology and chemistry of a sunflower. You're specifically looking for information regarding photosynthesis of sunflower plants. Now the student doesn't want to sit through 6 hours of sunflower biology when this student only wants to know about how a sunflower does photosynthesis. Unfortunately you can't control-f in a youtube video. But with our program maybe they can. The student should be able to enter a search term "photosynthesis" as well as a youtube video url and get a list of the exact timestamps where photosynthesis is mentioned!
## Styling
Thoughtfulness. Yes, that again. Now if we're being thoughtful when we're writing code, it might occur to us that we want other people to be able to understand our code easily. Likewise, we want to be able to easily understand the code of other developers. That's why developers have code style, the big companies often have great style guides that people throughout the world adhere to. For example, Airbnb has a well known style guide for javascript. For python, I think Google has written the best style guide which is called Pep 8. Let's try to adhere to that style guide for our code! But if it's a bit too much to do I completely understand!
Read about it [here](https://www.python.org/dev/peps/pep-0008/).<file_sep>from pprint import pprint
from urllib.parse import urlparse
from urllib.parse import parse_qs
class YTView():
''' The view of the youtube transcription program. '''
def introduction(self):
''' Prints the introduction to the youtube transcription service. '''
print("Welcome to Youtube Translation Service!")
def get_youtube_id(self):
''' Gets the youtube id from the user. '''
video_url = input("Please enter the Youtube URL you wish to transcribe:\n")
video_id = self.parse_id(video_url)
# This is what a ternary operator looks like in Python!
# Ternator operators reduce simple if else statements that normally
# would take up 4 lines down to 1 line. You can think of it like this:
# return <THIS> if <THIS> exists else <REPEAT THIS FUNCTION>
# Ternary operators are very useful for functional programming but in
# general can be a stylistically cleaner way of writing code.
return video_id if video_id else self.get_youtube_id()
def parse_id(self, url):
''' Parses the id of a video given a valid youtube url.
Args:
url: a string representing a valid youtube url.
Returns:
A string representing the video id of a valid youtube
video from the input url.
'''
url_data = urlparse(url)
query = parse_qs(url_data.query)
return query['v'][0]
def print_transcript(self, transcript):
''' Pretty prints the transcript
Args:
transcript: an array of dictionaries representing the transcript
of a youtube video.
'''
pprint(transcript)
|
f386479b67facfffb17e9198d38506b724af9660
|
[
"Markdown",
"Python"
] | 4 |
Python
|
foerever/YoutubeTranscriptionMVC
|
91e2c524da7f086df5aea5a166223e1bb23adf30
|
62c586a19d0e672202097a374deeba31955d15ac
|
refs/heads/master
|
<repo_name>jawharEu/NodeJsTutorial<file_sep>/src/app.js
const express = require('express')
const path = require('path')
const hbs = require('hbs')
const forecast = require('./utils/forecast')
const geocode = require('./utils/geocode')
//for heroku
const port = process.env.PORT || 3000
// console.log(__dirname);//directory absolute path
// console.log(__filename);//file absolute path
// console.log(path.join(__dirname, '../public'));
const app = express()
//Define paths for express config
const publicDirPath = path.join(__dirname, '../public')
const viewsPath = path.join(__dirname, '../templates/views')
const partialspath = path.join(__dirname, '../templates/partials')
// Setup handlebars engine and views location
app.set('view engine', 'hbs')
app.set('views', viewsPath) //customise views directory path
hbs.registerPartials(partialspath)
//setup static directory to serve
//customise server to match the html file in public directory
app.use(express.static(publicDirPath))
app.get('', (req, res) => {
res.render('index', {
title: 'Weather application',
name: '<NAME>'
})
})
app.get('/about', (req, res) => {
res.render('about', {
title: 'This a dynamic body of about web page',
})
})
app.get('/help', (req, res) => {
res.render('help', {
title: 'This a dynamic body of help web page',
})
})
app.get('/weather', (req, res) => {
if (!req.query.address) {
return res.send({
error: 'you must provide an address !'
})
}
geocode(req.query.address, (error, { latitude, longitude, location } = {}) => {
if (error) {
return res.send({ error });
}
forecast(latitude, longitude, (error, data) => {
if (error) {
return res.send({ error })
}
res.send(
{
forecast: data,
location,
address: req.query.address
}
);
})
})
})
app.get('/product', (req, res) => {
if (!req.query.search) {
return res.send({
error: 'you must provide search term ! '
})
}
res.send({
products: []
})
})
app.get('/help/*', (req, res) => {
res.render('404', {
body: 'Help article not found !'
})
})
app.get('*', (req, res) => {
res.render('404', {
body: 'Soryy ! Not found !',
})
})
// app.com === get contain first arg wich is the request url
// app.get('', (req, res)=>{
// res.send('<h1>hello express !</h1>')
// })
// app.get('/help' , (req,res)=>{
// res.send([{
// name : 'Jawhar',
// age : 24
// }])
// })
// app.get('/about' , (req, res)=>{
// res.send('<h2>This is the first nodejs express application !</h2>')
// })
app.listen(port, () => {
console.log('Server is up on port '+ port);
})<file_sep>/public/assets/js/app.js
// console.log('client side javascript file is loaded !');
// fetch('http://puzzle.mead.io/puzzle').then((response) => {
// response.json().then((data) => {
// console.log(data);
// })
// })
const weatherForm = document.querySelector('.form')
const search = document.querySelector('input')
const messageOne = document.querySelector('#message1')
const messageTwo = document.querySelector('#message2')
const errormsg = document.querySelector('errormsg')
weatherForm.addEventListener('submit', (event) => {
event.preventDefault(); //prevent loading
const location = search.value
fetch('/weather?address=' + location)
.then((response) => {
response.json().then((data) => {
if (data.error) {
errormsg.textContent = data.error;
} else {
messageOne.textContent=data.forecast
messageTwo.textContent=data.location;
// console.log(data.address);
// console.log(data.forecast);
}
})
})
})
|
8c2f0a563b110000fa821f6ceb7412992ae4aacd
|
[
"JavaScript"
] | 2 |
JavaScript
|
jawharEu/NodeJsTutorial
|
8e012108e35e29ea0d9e20b2f271867c3c8cd0ee
|
eedaadd8a4f9a431727e47009c8de0cc522536dc
|
refs/heads/master
|
<file_sep>TflCameras::Application.routes.draw do
resources :cameras
root to: "cameras#index"
end
<file_sep>// $(function(){
// var mapOptions,
// canvas,
// map;
// mapOptions = {
// zoom:13,
// center:new google.maps.LatLng(51.508742, -0.120850),
// mapTypeId:google.maps.MapTypeId.ROADMAP
// };
// canvas = document.getElementById("googleMap");
// map = new google.maps.Map(canvas, mapOptions);
// var cameras = $.getJSON('/cameras.json', function(data){
// cameras = data
// var markers = []
// for(var i=0; i < cameras.length; i++){
// var marker = new google.maps.Marker({
// position: new google.maps.LatLng(parseFloat(cameras[i].lat), parseFloat(cameras[i].lng)),
// map: map,
// title: 'text',
// camera_id: i
// });
// markers[i] = marker;
// google.maps.event.addListener(markers[i], 'click', function() {
// camera = cameras[this.camera_id]
// var contentString = '<div id="content"><img src="http://www.tfl.gov.uk/tfl/livetravelnews/trafficcams/cctv/' +
// cameras[this.camera_id].file + '"><p>' + cameras[this.camera_id].location + ", " + cameras[this.camera_id].postcode + '</p></div>';
// var infowindow = new google.maps.InfoWindow({
// content: contentString
// });
// infowindow.open(map,markers[this.camera_id])
// });
// }
// });
// });
|
4bccca67519ab41d3be174eee5229ccd844ccfc4
|
[
"JavaScript",
"Ruby"
] | 2 |
Ruby
|
jdeslangles/tflCameras
|
a69316e690ce248acf73557ac9e1ac53d0ceaf1d
|
0e2c46baf6832004df172685ab38289fc0efdb73
|
refs/heads/main
|
<repo_name>egory4fash/Kassa<file_sep>/main.py
import os
import pickle
class Kassa:
TICKETS_FILE = "tickets.pickle"
MONEY_FILE = "money.pickle"
def __init__(self):
self.tickets = None
self.money = 0
self._read_data()
def _read_data(self):
if os.path.exists(self.TICKETS_FILE): # Trying to open a base if exists, appending() if not
with open(self.TICKETS_FILE, "rb") as file:
base = pickle.load(file)
with open(self.MONEY_FILE, "rb") as file:
money = pickle.load(file)
else:
print("База отсустсвует")
base = self._create_base()
money = float(input("Скока денег?"))
self.tickets = base
self.money = money
@staticmethod
def _create_base():
# adding new elements in base
# base format:
# {price1: [[start1, end1], [start2, end2]...],
# price2: [[start1, end1], [start2, end2]...], }
base = {}
while True:
price = input("price ['' for finish]: ")
if not price:
break
price = float(price)
base[price] = []
while True:
input_line = input("start/end ['' for finish]: ")
if not input_line:
break
start, end = (int(i) for i in input_line.split())
base[price].append([start, end])
return base
def sell(self):
price, quantity = input("Через пробел цена и количество").split()
price = float(price)
quantity = int(quantity)
bunches = self.tickets.get(price, [])
while quantity:
if not bunches:
raise BaseException(f'fake tickets: ')
bunch = bunches[0]
bunch_size = bunch[1] - bunch[0] + 1
if quantity < bunch_size:
bunch[0] += quantity
break
else:
del bunches[0]
quantity -= bunch_size
self.money += price * quantity
def save(self):
# save self.tickets into file
with open(self.TICKETS_FILE, "wb") as file: # saving in pickle file
pickle.dump(self.tickets, file)
with open(self.MONEY_FILE, "wb") as file: # saving in pickle file
pickle.dump(self.money, file)
def debug(self):
print(f"money: {self.money}\ntickets:\n{self.tickets}")
if __name__ == "__main__":
k = Kassa()
k.sell()
k.debug()
k.save()
|
30ca0dc94eb8701c10d1bb1ec8f737ad8e4e65bd
|
[
"Python"
] | 1 |
Python
|
egory4fash/Kassa
|
af645cd969f2f2c6ad59adb2da4b1dd1cd1bdf55
|
488d191ca914aa24acf9068097e5d5f3cc1368f7
|
refs/heads/master
|
<repo_name>revuwem/react-hooks-learning<file_sep>/src/use-context.js
import React, {useContext} from 'react';
import ReactDOM from 'react-dom';
const SomeContext = React.createContext();
const App=()=>{
return(
<SomeContext.Provider value={'Tinky Winky'}>
<Para />
</SomeContext.Provider>
);
}
const Para = () =>{
const value = useContext(SomeContext);
return <p>{value}</p>;
}
ReactDOM.render(
<App/>,
document.getElementById('root')
);<file_sep>/src/use-state.js
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return (
<div>
<HookSwitcher />
</div>
);
}
const HookSwitcher = () => {
const [color, setColor] = useState('green');
const [fontSize, setFontSize] = useState(1.5);
return (
<div
style={{
padding: '10px',
backgroundColor: color,
color: 'white',
fontWeight: 'bold',
textAlign: 'center',
fontSize: `${fontSize}em`
}}>
<button
onClick={() => { setColor('green') }}>
Green
</button>
<button
onClick={() => { setColor('orange') }}>
Orange
</button>
<button
onClick={() => setFontSize((s)=>s+1)}>
Increase font size
</button>
<button
onClick={() => setFontSize((s)=>s-1)}>
Derease font size
</button>
<p>Make React great again!</p>
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<file_sep>/src/use-effect.js
import React, { Component, useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
const App = () => {
const [value, setValue] = useState(1);
const [visible, setVisible] = useState(true);
if (visible) {
return (
<div>
<button
onClick={() => setValue((v => v + 1))}>+</button>
<button
onClick={() => setVisible(false)}>hide</button>
{/* <ClassCounter value={value} /> */}
{/* <HookCounter value={value} /> */}
{/* <Notification /> */}
<PlanetInfo id={value} />
</div>
);
} else {
return <button onClick={() => { setVisible(true) }}>show</button>;
}
};
class ClassCounter extends Component {
componentDidMount() {
console.log('class: mount');
}
componentDidUpdate(props) {
console.log('class: update');
}
componentWillUnmount() {
console.log('class: unmount');
}
render() {
return <p>{this.props.value}</p>;
}
}
const HookCounter = ({ value }) => {
// componentDidMount + componentWillUnmount
useEffect(() => {
console.log('mounted');
return () => console.log('unmounted');
}, [])
// //componentDidMount
// useEffect(() => console.log('mounted'), []);
// componentDidUpdate
useEffect(() => console.log('updated'), [value]);
// componentWillUnmount
// useEffect(() => () => console.log('cleared'), []);
return <p>{value}</p>;
}
const Notification = (props) => {
const [visible, setVisible] = useState(true);
useEffect(() => {
const timeout = setTimeout(() => setVisible(false), 3500);
return () => clearTimeout(timeout);
}, []);
return (
<div>
{visible && <p>Hello</p>}
</div>);
}
const PlanetInfo = ({ id }) => {
const [name, setName] = useState('Loading ...');
useEffect(() => {
let cancelled = false;
fetch(`https://swapi.dev/api/planets/${id}`)
.then(res => res.json())
.then(data => !cancelled && setName(data.name));
return () => cancelled = true;
}, [id]);
return (
<div>
{id} - {name}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
4d9b9859634418e7e23cf352ff76bf9a44d8f5e8
|
[
"JavaScript"
] | 3 |
JavaScript
|
revuwem/react-hooks-learning
|
3b24a0bb6b775f72e3b47413cc19ad2a8ef29d2a
|
3cd6b729bb787ca1a07c453ae9893a4704ee714a
|
refs/heads/master
|
<repo_name>Rainase/transportManager<file_sep>/application/controllers/home.php
<?php
if (! defined('BASEPATH'))
exit('Access not allowed!');
class Home extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->database();
}
function index(){
if ($this->session->userdata('kuller_login') != 1)
redirect(base_url() . 'index.php/login', 'refresh');
if ($this->session->userdata('kuller_login') == 1)
redirect(base_url() . 'index.php/kuller/dashboard', 'refresh');
}
}<file_sep>/application/views/index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<?php include 'includes_style.php';?>
<title><?php echo $page_title;?> | <?php echo $system_title;?></title>
</head>
<body>
<?php include 'header.php';?>
<div class="container-fluid" id="main-container">
<?php include $this->session->userdata('login_type').'/navigation.php';?>
<div id="main-content" >
<?php include 'page_info.php';?>
<?php include $this->session->userdata('login_type').'/'.$page_name.'.php';?>
</div>
</div>
<?php include 'includes_js.php';?>
<?php include 'modal_hidden.php';?>
</body>
</html><file_sep>/application/views/includes_style.php
<!--base css styles-->
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/css/cloud-admin.css" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/css/themes/default.css" id="skin-switcher" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/css/responsive.css" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/js/bootstrap-daterangepicker/daterangepicker-bs3.css" />
<!-- STYLESHEETS --><!--[if lt IE 9]><script src="js/flot/excanvas.min.js"></script><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script><![endif]-->
<link href="<?php echo base_url();?>template/assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<!-- FONTS -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>
<?php
$system_name = $this->db->get_where('settings' , array('type'=>'system_name'))->row()->description;
$system_title = $this->db->get_where('settings' , array('type'=>'system_title'))->row()->description;
?>
<file_sep>/application/controllers/clients.php
<?php
if (! defined('BASEPATH'))
exit('Access not allowed!');
class Clients extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->database();
}
function index(){
if ($this->session->userdata('client_login') != 1)
redirect(base_url() . 'index.php/login', 'refresh');
if ($this->session->userdata('client_login') == 1)
redirect(base_url() . 'index.php/clients/dashboard', 'refresh');
}
function dashboard(){
if($this->session->userdata('client_login') != 1)
redirect(base_url() . 'index.php/login', 'refresh');
$page_data['page_name'] = 'dashboard';
$page_data['page_title'] = get_phrase('client_dashboard');
$this->load->view('index', $page_data);
}
function kullerid(){
if($this->session->userdata('client_login') != 1)
redirect(base_url() . 'index.php/login', 'refresh');
$page_data['page_name'] = 'kullerid';
$page_data['page_title'] = get_phrase('couriers');
$this->load->view('index', $page_data);
}
function my_shipments($param1 = '', $param2 = '', $param3 = ''){
if($this->session->userdata('client_login') != 1)
redirect(base_url() . 'index.php/login', 'refresh');
if ($param1 == 'create') {
$data['name'] = $this->input->post('name');
$data['description'] = $this->input->post('description');
$data['weight'] = $this->input->post('weight');
$data['size'] = $this->input->post('size');
$data['date_pickup_first'] = $this->input->post('date_pickup_first');
$data['date_pickup_last'] = $this->input->post('date_pickup_last');
$data['quantity'] = $this->input->post('quantity');
$data['date_arrive_first'] = $this->input->post('date_arrive_first');
$data['date_arrive_last'] = $this->input->post('date_arrive_last');
$data['client_id'] = $this->session->userdata('client_id');
$this->db->insert('shipments', $data);
$shipment_id = mysql_insert_id();
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/shimpent_image/' . $student_id . '.jpg');
//$this->email_model->account_opening_email('student', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
redirect(base_url() . 'index.php/clients/my_shipments/', 'refresh');
}
if ($param2 == 'do_update') {
$data['name'] = $this->input->post('name');
$data['description'] = $this->input->post('description');
$data['weight'] = $this->input->post('weight');
$data['size'] = $this->input->post('size');
$data['date_pickup_first'] = $this->input->post('date_pickup_first');
$data['date_pickup_last'] = $this->input->post('date_pickup_last');
$data['quantity'] = $this->input->post('quantity');
$data['date_arrive_first'] = $this->input->post('date_arrive_first');
$data['date_arrive_last'] = $this->input->post('date_arrive_last');
$this->db->where('shimpent_id', $param3);
$this->db->update('shipments', $data);
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/student_image/' . $param3 . '.jpg');
$this->crud_model->clear_cache();
redirect(base_url() . 'index.php/clients/my_shipments/' . $param1, 'refresh');
}
if ($param2 == 'edit') {
$page_data['edit_data'] = $this->db->get_where('shimpents', array(
'shimpent_id' => $param3
))->result_array();
}
$page_data['my_shipments'] = $this->db->get_where('shipments', array(
'client_id' => $this->session->userdata('client_id')))->result_array();
$page_data['page_name'] = 'my_shipments';
$page_data['page_title'] = get_phrase('my_shipments');
$this->load->view('index', $page_data);
}
function manage_profile($param1 = '', $param2 = '', $param3 = ''){
if($this->session->userdata('client_login') != 1)
redirect(base_url(), 'refresh');
$page_data['manage_profile'] = $this->db->get('clients')->result_array();
$page_data['page_name'] = 'manage_profile';
$page_data['page_title'] = get_phrase('manage_profile');
$this->load->view('index', $page_data);
}
}<file_sep>/application/views/clients/manage_profile.php
<?php
foreach($manage_profile as $row):
?>
<?php endforeach;?>
<!-- USER PROFILE -->
<div class="row">
<div class="col-md-12">
<!-- BOX -->
<div class="box border">
<div class="box-title">
<h4><i class="fa fa-user"></i><span class="hidden-inline-mobile">Hello, <?php echo $row['name'];?>!</span></h4>
</div>
<div class="box-body">
<div class="tabbable header-tabs user-profile">
<ul class="nav nav-tabs">
<li class="active"><a href="#pro_overview" data-toggle="tab"><i class="fa fa-dot-circle-o"></i> <span class="hidden-inline-mobile">Overview</span></a></li>
</ul>
<div class="tab-content">
<!-- OVERVIEW -->
<div class="tab-pane fade in active" id="pro_overview">
<div class="row">
<!-- PROFILE PIC -->
<div class="col-md-3">
<div class="list-group">
<li class="list-group-item zero-padding">
<img alt="" class="img-responsive" src="<?php echo base_url();?>template/user.jpg">
</li>
<div class="list-group-item profile-details">
<h2><?php echo $row['name'];?></h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt laoreet dolore magna aliquam tincidunt erat volutpat laoreet dolore magna aliquam tincidunt erat volutpat.</p>
<label><?php echo get_phrase('email');?></label>
<p><?php echo $row['email'];?></p>
<label><?php echo get_phrase('location');?></label>
<p><?php //echo $row['address'];?></p>
<p><a href="#">www.jenniferblogs.com</a></p>
</div>
</div>
</div>
<!-- /PROFILE PIC -->
<!-- PROFILE DETAILS -->
<div class="col-md-9">
<!-- ROW 1 -->
<div class="row">
<div class="col-md-7 profile-details">
<h3><?php echo get_phrase('company_details');?></h3>
<div class="divide-20"></div>
<!-- BUTTONS -->
<div class="row">
<div class="col-md-4">
<a class="btn btn-danger btn-icon input-block-level" href="javascript:void(0);">
<i class="fa fa-truck fa-2x"></i>
<div><?php echo get_phrase('number_of_shipments');?></div>
<span class="label label-right label-warning"><?php //echo $row['number_of_trucks'];?></span>
</a>
</div>
<div class="col-md-4">
<a class="btn btn-primary btn-icon input-block-level" href="javascript:void(0);">
<i class="fa fa-users fa-2x"></i>
<div><?php echo get_phrase('number_of_drivers');?></div>
<span class="label label-right label-danger"><?php //echo $row['number_of_drivers'];?></span>
</a>
</div>
<div class="col-md-4">
<a class="btn btn-pink btn-icon input-block-level" href="javascript:void(0);">
<i class="fa fa-dribbble fa-2x"></i>
<div><?php echo get_phrase('trailer_types');?></div>
<span class="label label-right label-info"><?php //echo $row['trailer_types'];?></span>
</a>
</div>
<div class="col-md-4">
<a class="btn btn-success btn-icon input-block-level" href="javascript:void(0);">
<i class="fa fa-globe fa-2x"></i>
<div><?php echo get_phrase('service_area');?></div>
</a>
</div>
</div>
<!-- /BUTTONS -->
</div>
<div class="col-md-5">
<!-- BOX -->
<div class="box border inverse">
<div class="box-title">
<h4><i class="fa fa-bars"></i>Statistics</h4>
</div>
<div class="box-body big sparkline-stats">
</div>
</div>
<!-- /BOX -->
<!-- /SAMPLE -->
</div>
</div>
<!-- /ROW 1 -->
<div class="divide-40"></div>
</div>
<!-- /PROFILE DETAILS -->
</div>
</div>
<!-- /OVERVIEW -->
</div>
</div>
<!-- /USER PROFILE -->
</div>
</div>
</div>
</div>
<file_sep>/application/views/includes_js.php
<!-- JAVASCRIPTS -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="<?php echo base_url();?>template/assets/js/jquery-1.9.1.min.js"></script>
<script src="<?php echo base_url();?>template/assets/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>template/assets/js/waypoint/waypoints.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>template/assets/js/bootstrap-daterangepicker/daterangepicker.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>template/assets/js/navmaster/jquery.scrollTo.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>template/assets/js/navmaster/jquery.nav.js"></script>
<script src="<?php echo base_url();?>template/assets/js/isotope/jquery.isotope.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo base_url();?>template/assets/js/isotope/imagesloaded.pkgd.min.js"></script>
<!-- COLORBOX -->
<script type="text/javascript" src="<?php echo base_url();?>template/assets/js/colorbox/jquery.colorbox.min.js"></script>
<script src="<?php echo base_url();?>template/assets/js/script.js"></script><file_sep>/application/controllers/login.php
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Login extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('crud_model');
$this->load->database();
}
public function index()
{
if ($this->session->userdata('kuller_login') == 1)
redirect(base_url() . 'index.php/kuller/dashboard', 'refresh');
if ($this->session->userdata('client_login') == 1)
redirect(base_url() . 'index.php/clients/dashboard', 'refresh');
$config = array(
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|xss_clean|valid_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required|xss_clean|callback__validate_login'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('_validate_login', ucfirst($this->input->post('login_type')) . 'Sisselogimine ebaõnnestus!');
$this->form_validation->set_error_delimiters('<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>', '</div>');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login');
} else {
if ($this->session->userdata('kuller_login') == 1)
redirect(base_url() . 'index.php/kuller/dashboard');
if ($this->session->userdata('client_login') == 1)
redirect(base_url() . 'index.php/clients/dashboard');
}
}
/***validate login****/
function _validate_login($str)
{
if ($this->input->post('login_type') == '') {
$this->session->set_flashdata('flash_message', 'select_account_type');
redirect(base_url() . 'index.php/login', 'refresh');
return FALSE;
}
$query = $this->db->get_where($this->input->post('login_type'), array(
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
));
if ($query->num_rows() > 0) {
$row = $query->row();
if ($this->input->post('login_type') == 'kuller') {
$this->session->set_userdata('kuller_login', '1');
$this->session->set_userdata('kuller_id', $row->admin_id);
$this->session->set_userdata('name', $row->name);
//$this->session->set_userdata('level', $row->level);
$this->session->set_userdata('login_type', 'kuller');
}
if ($this->input->post('login_type') == 'clients') {
$this->session->set_userdata('client_login', '1');
$this->session->set_userdata('client_id', $row->client_id);
$this->session->set_userdata('name', $row->name);
$this->session->set_userdata('login_type', 'clients');
}
return TRUE;
} else {
$this->session->set_flashdata('flash_message', 'login_failed');
redirect(base_url() . 'index.php/login', 'refresh');
return FALSE;
}
}
/*******LOGOUT FUNCTION *******/
function logout()
{
$this->session->unset_userdata();
$this->session->sess_destroy();
$this->session->set_flashdata('logout_notification', 'logged_out');
redirect(base_url() . 'index.php/login', 'refresh');
}
}<file_sep>/application/views/kuller/clients.php
<?php if($client_id != ""):?>
<div class="row">
<div class="col-md-4 col-md-offset-3">
<div class="box border inverse">
<div class="box-title">
<h4><i class="fa fa-info"></i></i> <?php echo get_phrase('select_category_to_see_the_list');?></h4>
</div>
<div class="box-body">
<select name="client_id" onchange="window.location='<?php echo base_url();?>index.php/kuller/clients/'+this.value">
<option value=""><?php echo get_phrase('product_type');?></option>
<?php $types = $this->db->get('product_type')->result_array();
foreach($types as $row): ?>
<option value="<?php echo $row['product_type_id'];?>"
<?php if($client_id == $row['product_type_id'])echo 'selected';?>>
<?php echo $row['product_type_name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
<!-- Amount of Clients seleced by Type -->
<?php if($client_id != ''):?>
<div class=" action-nav-button" style="width:150px;">
<a class="btn btn-pink btn-icon input-block-level">
<h4><i class="fa fa-users"></i></h4>
<div><p>Total <?php echo count($clients);?> clients</p></div>
</a>
</div>
<!-- END Amount of Clients seleced by Type -->
<!-- Begin of DATA TABLES -->
<div class="row">
<div class="col-md-11">
<!-- Begin BOX -->
<div class="box border green">
<div class="box-title">
<h4><i class="fa fa-table"></i><?php echo get_phrase('client_list');?> / </h4><small><?php echo $row['product_type_name'];?></small>
<div class="tools hidden-xs">
<a href="javascript:;" class="reload">
<i class="fa fa-refresh"></i>
</a>
</div>
</div>
<div class="box-body">
<table id="datatable1" cellpadding="0" cellspacing="0" border="0" class="datatable table table-striped table-bordered table-hover">
<thead>
<tr>
<th><?php echo get_phrase('product_name');?></th>
<th><?php echo get_phrase('product_weight');?></th>
<th><?php echo get_phrase('quantity');?></th>
<th><?php echo get_phrase('date_dispatch_first');?></th>
<th><?php echo get_phrase('date_dispatch_last');?></th>
<th><?php echo get_phrase('product_owner');?></th>
<th><?php echo get_phrase('options');?></th>
</tr>
</thead>
<tbody>
<?php $count = 1;foreach($clients as $row):?>
<tr>
<td><?php echo $row['product'];?></td>
<td><?php echo $row['weight'];?><small> kg</small></td>
<td><?php echo $row['quantity'];?><?php echo get_phrase('pieces');?></td>
<td><?php echo $row['date_dispatch_first'];?></td>
<td><?php echo $row['date_dispatch_last'];?></td>
<td><?php echo $row['owner'];?></td>
<td>
<a data-toggle="modal" href="#modal-form" onclick="modal('product_full_info',<?php echo $row['client_id'];?>)" class="btn btn-default btn-small">
<i class="icon-user"></i> <?php echo get_phrase('profile'); ?>
</a>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
<?php endif;?>
<!-- End of BOX -->
</div>
</div>
<!-- ENd of DATA TABLES -->
<!-- /CATEGoRY BOX BEGIN -->
<?php endif;?>
<?php if($client_id == ""):?>
<div class="row">
<div class="col-md-4 col-md-offset-3">
<div class="box border inverse">
<div class="box-title">
<h4><i class="fa fa-info"></i></i> <?php echo get_phrase('select_category_to_see_the_list');?></h4>
</div>
<div class="box-body">
<select name="client_id" onchange="window.location='<?php echo base_url();?>index.php/kuller/clients/'+this.value">
<option value=""><?php echo get_phrase('product_type');?></option>
<?php $types = $this->db->get('product_type')->result_array();
foreach($types as $row): ?>
<option value="<?php echo $row['product_type_id'];?>"
<?php if($client_id == $row['product_type_id'])echo 'selected';?>>
<?php echo $row['product_type_name'];?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
<!-- /CATEGoRY BOX END -->
<?php endif;?><file_sep>/application/controllers/kuller.php
<?php
if (! defined('BASEPATH'))
exit('Access not allowed!');
class Kuller extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->database();
}
function index(){
if ($this->session->userdata('kuller_login') != 1)
redirect(base_url() . 'index.php?login', 'refresh');
if ($this->session->userdata('kuller_login') == 1)
redirect(base_url() . 'index.php/kuller/dashboard', 'refresh');
}
function dashboard()
{
if ($this->session->userdata('kuller_login') != 1)
redirect(base_url(), 'refresh');
$page_data['page_name'] = 'dashboard';
$page_data['page_title'] = get_phrase('courier_dashboard');
$this->load->view('index', $page_data);
}
function clients($param1 = '', $param2 = '', $param3 = '')
{
if ($this->session->userdata('kuller_login') != 1)
redirect(base_url(), 'refresh');
$page_data['client_id'] = $param1;
$page_data['clients'] = $this->db->get_where('product', array(
'product_type_id' => $param1
))->result_array();
$page_data['page_name'] = 'clients';
$page_data['page_title'] = get_phrase('courier_clients');
$this->load->view('index', $page_data);
}
function manage_profile($param1 = '', $param2 = '', $param3 = ''){
if($this->session->userdata('kuller_login') != 1)
redirect(base_url(), 'refresh');
$page_data['manage_profile'] = $this->db->get('kuller')->result_array();
$page_data['page_name'] = 'manage_profile';
$page_data['page_title'] = get_phrase('manage_profile');
$this->load->view('index', $page_data);
}
}<file_sep>/application/views/page_info.php
<div class="page-title">
<div>
<div class="clearfix">
<h3 class="content-title pull-left"><?php echo $page_title;?></h3>
</div>
</div>
</div>
<?php if($this->session->flashdata('flash_message') != ""):?>
<script>
$(document).ready(function() {
Growl.info({title:"<?php echo $this->session->flashdata('flash_message');?>",text:" "})
});
</script>
<?php endif;?><file_sep>/application/views/modal.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<?php //include 'includes_top.php';?>
<title><?php echo $page_title;?> | <?php echo $system_title;?></title>
<link rel="shortcut icon" href="<?php echo base_url();?>template/images/favicon.png">
</head>
<body>
<?php include $this->session->userdata('login_type').'/modal_'.$page_name.'.php';?>
<?php include 'includes_js.php';?>
</body>
</html><file_sep>/application/views/clients/navigation.php
<!-- SIDEBAR -->
<div id="sidebar" class="sidebar">
<div class="sidebar-menu nav-collapse">
<!-- SIDEBAR MENU -->
<ul>
<!--dashboard -->
<li class="<?php if($page_name == 'dashboard')echo 'active';?>">
<a href="<?php echo base_url();?>index.php/clients/dashboard">
<i class="fa fa-tachometer fa-fw"></i> <span class="menu-text"><?php echo get_phrase('dashboard');?></span>
</a>
</li>
<li class="<?php if($page_name == 'kullerid')echo 'active';?>">
<a href="<?php echo base_url();?>index.php/clients/kullerid">
<i class="fa fa-bookmark-o fa-fw"></i> <span class="menu-text"><?php echo get_phrase('couriers');?></span>
</a>
</li>
<li class="<?php if($page_name == 'my_shipments')echo 'active';?>">
<a href="<?php echo base_url();?>index.php/clients/my_shipments">
<i class="fa fa-bookmark-o fa-fw"></i> <span class="menu-text"><?php echo get_phrase('my_shipments');?></span>
</a>
</li>
</ul>
<!-- /SIDEBAR MENU -->
</div>
</div>
<!-- /SIDEBAR -->
<file_sep>/application/views/header.php
<!-- HEADER -->
<header class="navbar clearfix" id="header">
<div class="container">
<div class="navbar-header">
<!-- COMPANY LOGO -->
<a class="navbar-brand" href="#"><i class="fa fa-truck"> Transport Manager</i></a>
<!-- /COMPANY LOGO -->
</div>
<!-- BEGIN TOP NAVIGATION MENU -->
<ul class="nav navbar-nav pull-right">
<!-- BEGIN LANGUAGE DROPDOWN -->
<li class="dropdown" id="header-notification">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-flag"></i>
<span><?php echo get_phrase('select_language');?></span>
</a>
<ul class="dropdown-menu notification">
<?php
$fields = $this->db->list_fields('language');
foreach ($fields as $field)
{
if($field == 'phrase_id' || $field == 'phrase')continue;
?>
<li>
<a href="<?php echo base_url();?>index.php/multilanguage/select_language/<?php echo $field;?>">
<span class="label label-success">EN</span>
<span class="body">
<span class="message"><?php echo $field;?></span>
<?php //selecting current language
if($this->session->userdata('current_language') == $field):?>
<i class="fa fa-check"></i>
<?php endif;?>
</span>
</a>
</li>
<?php
}
?>
</ul>
</li>
<!-- END LANGUAGE DROPDOWN -->
<!-- BEGIN TODO DROPDOWN -->
<li class="dropdown" id="header-tasks">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-tasks"></i>
<span class="badge">3</span>
</a>
<ul class="dropdown-menu tasks">
<li class="dropdown-title">
<span><i class="fa fa-check"></i> 6 tasks in progress</span>
</li>
<li>
<a href="#">
<span class="header clearfix">
<span class="pull-left">Software Update</span>
<span class="pull-right">60%</span>
</span>
<div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
<span class="sr-only">60% Complete</span>
</div>
</div>
</a>
</li>
<li class="footer">
<a href="#">See all tasks <i class="fa fa-arrow-circle-right"></i></a>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<li class="dropdown user" id="header-user">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img alt="" src="img/avatars/avatar3.jpg" />
<span class="username"><?php echo $this->session->userdata('name');?></span>
<i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu">
<li><a href="<?php echo base_url();?>index.php/<?php echo $this->session->userdata('login_type');?>/manage_profile"><i class="fa fa-user"></i> My Profile</a></li>
<li><a href=""><i class="fa fa-cog"></i> Account Settings</a></li>
<li><a href="#"><i class="fa fa-eye"></i> Privacy Settings</a></li>
<li><a href="<?php echo base_url();?>index.php/login/logout"><i class="fa fa-power-off"></i> Log Out</a></li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
</ul>
<!-- END TOP NAVIGATION MENU -->
</div>
</header>
<!--/HEADER --><file_sep>/application/views/kuller/navigation.php
<!-- SIDEBAR -->
<div id="sidebar" class="sidebar">
<div class="sidebar-menu nav-collapse">
<!-- SIDEBAR QUICK-LAUNCH -->
<!-- <div id="quicklaunch">
<!-- /SIDEBAR QUICK-LAUNCH -->
<!-- SIDEBAR MENU -->
<ul>
<!--dashboard -->
<li class="<?php if($page_name == 'dashboard')echo 'active';?>">
<a href="<?php echo base_url();?>index.php/kuller/dashboard">
<i class="fa fa-tachometer fa-fw"></i> <span class="menu-text"><?php echo get_phrase('dashboard');?></span>
</a>
</li>
<li class="<?php if($page_name == 'clients')echo 'active';?>">
<a href="<?php echo base_url();?>index.php/kuller/clients">
<i class="fa fa-bookmark-o fa-fw"></i> <span class="menu-text"><?php echo get_phrase('clients');?></span>
</a>
</li>
</ul>
<!-- /SIDEBAR MENU -->
</div>
</div>
<!-- /SIDEBAR -->
<file_sep>/application/controllers/modal.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Modal extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
}
/***default functin, redirects to login page if no admin logged in yet***/
public function index()
{
}
function popup($param1 = '' , $param2 = '' , $param3 = '')
{
if($param1 == 'product_full_info' )
{
$page_data['current_product_id'] = $param2;
}
$page_data['page_name'] = $param1;
$this->load->view('modal' ,$page_data);
}
}
<file_sep>/application/views/kuller/modal_product_full_info.php
<!--base css styles-->
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/css/cloud-admin.css" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/css/themes/default.css" id="skin-switcher" >
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/assets/css/responsive.css" >
<!-- STYLESHEETS --><!--[if lt IE 9]><script src="js/flot/excanvas.min.js"></script><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script><![endif]-->
<link href="<?php echo base_url();?>template/assets/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<!-- FONTS -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700' rel='stylesheet' type='text/css'>
<?php
$product_info = $this->crud_model->get_product_info($current_product_id);
foreach($product_info as $row):?>
<div class="box border inverse">
<div class="box-title">
<h4><i class="fa fa-table"></i>Info</h4>
</div>
<div class="box-body">
<table class="table table-bordered">
<tr>
<td><?php echo get_phrase('product_name');?></td>
<td><?php echo $row['product'];?></td>
</tr>
<tr>
<td><?php echo get_phrase('product_type');?></td>
<td><?php //echo $this->crud_model->get_product_type_name($row['product_type_id']);?><bold>VajaUurida</bold></td>
</tr>
<tr>
<td><?php echo get_phrase('weight');?></td>
<td><?php echo $row['weight'];?><small> kg</small></td>
</tr>
<tr>
<td><?php echo get_phrase('pieces');?></td>
<td><?php echo $row['quantity'];?><?php echo get_phrase('pieces');?></td>
</tr>
<tr>
<td><?php echo get_phrase('date_dispatch_first');?></td>
<td><?php echo $row['date_dispatch_first'];?></td>
</tr>
<tr>
<td><?php echo get_phrase('date_dispatch_last');?></td>
<td><?php echo $row['date_dispatch_last'];?></td>
</tr>
<tr>
<td><?php echo get_phrase('owner');?></td>
<td><?php echo $row['owner'];?></td>
</tr>
</table>
</div>
<!--<iframe class="google_map" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?q=<?php echo $row['address'];?>&output=embed&iwloc=near"></iframe>-->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&extension=.js"></script>
<script>
jQuery(document).ready(function () {
var map;
var centerPosition = new google.maps.LatLng(40.747688, -74.004142);
var style = [{
"stylers": [{
"visibility": "on"
}]
}, {
"featureType": "road",
"stylers": [{
"visibility": "on"
}, {
"color": "#ffffff"
}]
}, {
"featureType": "road.arterial",
"stylers": [{
"visibility": "on"
}, {
"color": "#fee379"
}]
}, {
"featureType": "road.highway",
"stylers": [{
"visibility": "on"
}, {
"color": "#fee379"
}]
}, {
"featureType": "landscape",
"stylers": [{
"visibility": "on"
}, {
"color": "#f3f4f4"
}]
}, {
"featureType": "water",
"stylers": [{
"visibility": "on"
}, {
"color": "#7fc8ed"
}]
}, {}, {
"featureType": "road",
"elementType": "labels",
"stylers": [{
"visibility": "off"
}]
}, {
"featureType": "poi.park",
"elementType": "geometry.fill",
"stylers": [{
"visibility": "on"
}, {
"color": "#83cead"
}]
}, {
"elementType": "labels",
"stylers": [{
"visibility": "on"
}]
}, {
"featureType": "landscape.man_made",
"elementType": "geometry",
"stylers": [{
"weight": 1
}, {
"visibility": "off"
}]
}]
var image = {
url: 'https://dl.dropboxusercontent.com/u/814783/fiddle/marker.png',
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 0)
};
var shadow = {
url: 'https://dl.dropboxusercontent.com/u/814783/fiddle/shadow.png',
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 0)
};
var marker = new google.maps.Marker({
position: centerPosition,
map: map,
icon: image,
shadow: shadow
});
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), mapOptions);
map.setOptions({
styles: style
});
var address = "<?php echo $row['address'];?>";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
//alert("Geocode was not successful for the following reason: " + status);
}
});
});
</script>
<?php endforeach;?>
<file_sep>/application/views/clients/my_shipments.php
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#my_shipments" data-toggle="tab"><i class="fa fa-home"></i><?php echo get_phrase('my_shipmnets');?></a></li>
<li><a href="#add_new" data-toggle="tab"><i class="fa fa-envelope"></i><?php echo get_phrase('add_new_shipment');?></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade in active" id="my_shipments">
<div class="divide-10"></div>
<p>
<!-- Begin of DATA TABLES -->
<div class="row">
<div class="col-md-12">
<!-- Begin BOX -->
<div class="box border green">
<div class="box-title">
<h4><i class="fa fa-table"></i><?php echo get_phrase('my_shipment_list');?> / </h4><small></small>
</div>
<div class="box-body">
<table id="datatable1" cellpadding="0" cellspacing="0" border="0" class="datatable table table-striped table-bordered table-hover">
<thead>
<tr>
<th><?php echo get_phrase('product_name');?></th>
<th><?php echo get_phrase('product_weight');?></th>
<th><?php echo get_phrase('quantity');?></th>
<th><?php echo get_phrase('date_dispatch_first');?></th>
<th><?php echo get_phrase('date_dispatch_last');?></th>
<th><?php echo get_phrase('description');?></th>
<th><?php echo get_phrase('size');?></th>
<th><?php echo get_phrase('date_arrive_first');?></th>
<th><?php echo get_phrase('date_dispatch_last');?></th>
<th><?php echo get_phrase('options');?></th>
</tr>
</thead>
<tbody>
<?php $count = 1;foreach($my_shipments as $row):?>
<tr>
<td><?php echo $row['name'];?></td>
<td><?php echo $row['weight'];?><small> kg</small></td>
<td><?php echo $row['quantity'];?>/<?php echo get_phrase('pieces');?></td>
<td><?php echo $row['date_pickup_first'];?></td>
<td><?php echo $row['date_pickup_last'];?></td>
<td><?php echo $row['description'];?></td>
<td><?php echo $row['size'];?></td>
<td><?php echo $row['date_arrive_first'];?></td>
<td><?php echo $row['date_arrive_last'];?></td>
<td>
<a data-toggle="modal" href="#modal-form" onclick="modal('edit_shipment',<?php echo $row['shipment_id'];?>)" class="btn btn-default btn-small">
<i class="icon-user"></i> <?php echo get_phrase('edit'); ?>
</a>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
</div>
<!-- End of BOX -->
</div>
</div>
<!-- ENd of DATA TABLES -->
</p>
</div>
<div class="tab-pane fade" id="add_new">
<div class="divide-10"></div>
<!----CREATION FORM STARTS---->
<div class="tab-pane box" id="add" style="padding: 5px">
<div class="box-content">
<?php echo form_open('clients/my_shipments/create' , array('class' => 'form-horizontal validatable','target'=>'_top', 'enctype' => 'multipart/form-data'));?>
<form method="post" action="<?php echo base_url();?>index.php?clients/my_shipments/create/" class="form-horizontal validatable" enctype="multipart/form-data">
<div class="padded">
<div class="control-group">
<label class="control-label"><?php echo get_phrase('name');?></label>
<div class="controls">
<input type="text" class="validate[required]" name="name"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('description');?></label>
<div class="controls">
<input type="text" class="form-control datepicker" name="description"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('weight');?></label>
<div class="controls">
<input type="text" class="" name="weight"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('size');?></label>
<div class="controls">
<input type="text" class="" name="size"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('date_pickup_first');?></label>
<div class="controls">
<input type="text" class="" name="date_pickup_first"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('date_pickup_last');?></label>
<div class="controls">
<input type="text" class="" name="email"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('quantity');?></label>
<div class="controls">
<input type="text" class="" name="quantity"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('date_arrive_first');?></label>
<div class="controls">
<input type="text" class="" name="date_arrive_first"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('date_arrive_last');?></label>
<div class="controls">
<input type="text" class="" name="date_arrive_last"/>
</div>
</div>
<div class="control-group">
<label class="control-label"><?php echo get_phrase('photo');?></label>
<div class="controls" style="width:210px;">
<input type="file" class="" name="userfile" id="imgInp" />
</div>
</div>
<div class="control-group">
<label class="control-label"></label>
<div class="controls" style="width:210px;">
<img id="blah" src="<?php echo base_url();?>uploads/user.jpg" alt="your image" height="100" />
</div>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-gray"><?php echo get_phrase('add_shipment');?></button>
</div>
</form>
</div>
</div>
<!----CREATION FORM ENDS--->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
|
7ff6c23ee82a37da0c8e9614d1cd45ff1644f24a
|
[
"PHP"
] | 17 |
PHP
|
Rainase/transportManager
|
f746e2a735935acb97bef9236ef6bb598655bfff
|
8bfedf801796b3a234b0cc4000134a5717be14e4
|
refs/heads/master
|
<file_sep>#include <math.h>
#include <stdio.h>
#include <stdint.h>
#include "lab2_funcs.h"
#include "lab2.h"
void printhelp(void)
{
printf("Available commands: \n");
printf("help: Show this message \n");
printf("set: <var> <value>: Set variable <var> to value <value>, e.g. \"set a 3.14\" \n");
printf("sin: <res> <var>: Calculates the sin values of <var> and sotres in <res> \n");
printf("clear: <var>: Sets all value in an array <var> to 0 or sets a single <var> to 0 \n");
printf("show: <var>: Shows the value of the value or shows the value of the array\n");
printf("calc: <var>: two <var> that can be manipulated using +,-,* and /. array <var> can only be manipulated using + and -\n");
printf("vars: Shows all variables \n");
printf("showCSV: print the contents of a .csv file on the screen. \n");
printf("importCSV: <var> <filename>: Imports <filename> into variable <var>\n");
printf("exportMAT: <var> <filename>: export one array into a matlab file that can be loaded by matlab.\n");
printf("exportCSV: <var> <filename>: Saves <var> variable into the CSV file <filename>\n");
printf("quit: exit this application \n");
printf("exit: exit this application \n");
printf("exit x: exit this application with return code x \n");
return;
}
int set(char name, double v)
{
matlab_var_t *var_ptrv =find_var(name);
matlab_arr_t *var_ptra =find_arr(name);
if(!var_ptrv && !var_ptra)
{
printf("Not a variable \n");
return 1;
}
else if (!var_ptra)
var_ptrv->v=v;
else if (!var_ptrv)
{
for(int i=0; i<ARRAY_LEN; i++)
{
var_ptra->v[i]=v;
}
}
return 1;
}
int clear(char name)
{
matlab_var_t *var_ptrv =find_var(name);
matlab_arr_t *var_ptra =find_arr(name);
if(!var_ptrv && !var_ptra)
{
printf("Not a variable \n");
return 1;
}
else if (!var_ptra)
var_ptrv->v=0;
else if (!var_ptrv)
{
for(int i=0; i<ARRAY_LEN; i++)
{
var_ptra->v[i]=0;
}
}
return 1;
}
int show(char name)
{
matlab_var_t *var_ptrv =find_var(name);
matlab_arr_t *var_ptra =find_arr(name);
if(!var_ptrv && !var_ptra)
{
printf("Not a variable \n");
return 1;
}
else if (!var_ptra)
printf("%1f \n",var_ptrv->v);
else if (!var_ptrv)
{
for(int i=0; i<ARRAY_LEN; i++)
{
printf("%f \n",var_ptra->v[i]);
}
}
return 1;
}
int array(char name, double start, double stop)
{
matlab_arr_t *var_ptra = find_arr(name);
if (!var_ptra)
{
printf("Not a variable \n");
return 1;
}
double step=(stop-start)/49;
for(int i=0; i<ARRAY_LEN; i++)
{
var_ptra->v[i]=start+step*i;
}
return 1;
}
int calc(char r, char x, char y, char op)
{
matlab_var_t *var_r =find_var(r);
matlab_arr_t *var_ar =find_arr(r);
matlab_var_t *var_x =find_var(x);
matlab_arr_t *var_ax =find_arr(x);
matlab_var_t *var_y =find_var(y);
matlab_arr_t *var_ay =find_arr(y); //(!var_r && !var_x && !var_y && !var_ar && !var_ax && !var_ay)
if(!var_r || !var_x || !var_y)
{
if(!var_ar || !var_ax || !var_ay)
{
printf("One or more are not a variable \n");
return 1;
}
}
if (!var_ar) //Inskick är inte array
{
if(op=='+')
var_r->v=var_x->v+var_y->v;
else if(op=='-')
var_r->v=var_x->v-var_y->v;
else if(op=='*')
var_r->v=var_x->v*var_y->v;
else if(op=='/')
{
if(var_y->v==0)
{
printf("Can't divide by 0 \n");
return 1;
}
var_r->v=var_x->v/var_y->v;
}
else
{
printf("Unknown operator \n");
return 1;
}
}
else if(!var_r)
{
if(op=='+')
{
for(int i=0; i<ARRAY_LEN; i++)
{
var_ar->v[i]=var_ax->v[i]+var_ay->v[i];
}
}
else if(op=='-')
{
for(int i=0; i<ARRAY_LEN; i++)
{
var_ar->v[i]=var_ax->v[i]-var_ay->v[i];
}
}
else
{
printf("Unknown operator \n");
return 1;
}
}
return 1;
}
void show_vars(void)
{
matlab_var_t *var_a =find_var('a');
matlab_var_t *var_b =find_var('b');
matlab_var_t *var_c =find_var('c');
matlab_var_t *var_r =find_var('r');
matlab_var_t *var_y =find_var('y');
matlab_var_t *var_x =find_var('x');
printf("%c:%f \n",var_a->n,var_a->v);
printf("%c:%f \n",var_b->n,var_b->v);
printf("%c:%f \n",var_c->n,var_c->v);
printf("%c:%f \n",var_r->n,var_r->v);
printf("%c:%f \n",var_x->n,var_x->v);
printf("%c:%f \n",var_y->n,var_y->v);
}
int showCSV(const char *filename)
{
char value[100];
FILE* input;
if(!(input=fopen(filename,"r")))
{
printf("File does not exist \n");
return 1;
}
if(!strcmp(filename,"eventsig.csv")||!strcmp(filename,"bouncesig2.csv")||!strcmp(filename,"bouncesig.csv"))
{
fgets(value,100,input);
}
for(int i=0; i<ARRAY_LEN; i++)
{
fgets(value,100,input);
if(isdigit(value[0])==0)
{
fgets(value,100,input);
}
printf("%s", value);
}
fclose(input);
return 1;
}
int importcsv(char var, const char *filename)
{
matlab_arr_t *var_ar =find_arr(var);
if(!var_ar)
{
printf("Not a variable \n");
return 1;
}
char value[100];
FILE* input;
if(!(input=fopen(filename,"r")))
{
printf("File does not exist \n");
return 1;
}
for(int i=0; i<ARRAY_LEN; i++)
{
fgets(value,100,input);
if(isdigit(value[0])==0)
{
fgets(value,100,input);
}
var_ar->v[i]=atof(value);
}
fclose(input);
return 1;
}
int exportcsv(char var,const char* filename)
{
matlab_arr_t *var_ar =find_arr(var);
if(!var_ar)
{
printf("Not a variable \n");
return 1;
}
FILE* input;
input=fopen(filename,"w");
for(int i=0; i<50; i++)
{
fprintf(input,"%f \n",var_ar->v[i]);
}
fclose(input);
return 1;
}
int exportMAT(char var,const char *filename)
{
typedef struct
{
uint32_t type;
uint32_t mrows;
uint32_t ncols;
uint32_t imagf;
uint32_t namelen;
} Fmatrix;
char car[2];
car[0]=var;
car[1]='\0';
Fmatrix header;
header.type=0000;
header.mrows=ARRAY_LEN;
header.ncols=1;
header.imagf=0;
header.namelen=1+1;
int mn;
matlab_arr_t *var_ar=find_arr(var);
if(!var_ar)
{
printf("Not a variable \n");
return 1;
}
FILE* input;
input=fopen(filename,"wb");
double a[ARRAY_LEN];
for(int i=0; i<ARRAY_LEN; i++)
{
a[i]=var_ar->v[i];
}
fwrite(&header,sizeof(Fmatrix),1,input);
fwrite(&car,sizeof(char)*header.namelen,1,input);
mn = header.mrows*header.ncols;
fwrite(a,sizeof(double),mn,input);
fclose(input);
return 1;
}
int debounce(char R,char I)
{
matlab_arr_t *var_aR =find_arr(R);
matlab_arr_t *var_aI =find_arr(I);
if(!var_aR||!var_aI)
{
printf("Not a variable \n");
return 1;
}
for(int i=0; i<ARRAY_LEN; i++)
{
if(var_aI->v[i]<0.3)
{
var_aR->v[i]=0.00;
}
else if (var_aI->v[i]>3.0)
{
var_aR->v[i]=3.30;
}
else
{
var_aR->v[i]=var_aI->v[i];
}
}
return 1;
}
int event(char R,char I)
{
matlab_arr_t *var_aR =find_arr(R);
matlab_arr_t *var_aI =find_arr(I);
int samplesize=0;
int startfinish=0;
int start=0;
if(!var_aR||!var_aI)
{
printf("Not a variable \n");
return 1;
}
for(int i=0; i<ARRAY_LEN; i++)
{
if(var_aI->v[i]>0.5 && startfinish==0)
{
start=i;
startfinish++;
samplesize++;
}
else if(var_aI->v[i]>0.5 && startfinish==1)
{
samplesize++;
}
else if(var_aI->v[i]<0.5 && samplesize>10)
{
for(int a=start; a==i; a++)
{
var_aR->v[a]=var_aI->v[a];
}
printf("Event start detected @%i\n",start);
printf("Event stop detected @%i\n",i);
startfinish=0;
samplesize=0;
}
else if(var_aI->v[i]<0.5)
{
var_aR->v[i]=0;
start=0;
startfinish=0;
samplesize=0;
}
}
return 1;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include "lab2_funcs.h"
#include "lab2.h"
#define MAX_WORDS 4
matlab_var_t vars[6] = { {'a', 0},{'b', 0},{'c', 0},{'r', 0},{'x', 0},{'y', 0}};
matlab_arr_t arrs[6] = { {'A', {0}},{'B', {0}},{'C', {0}},{'R', {0}},{'X', {0}},{'Y', {0}}};
int main(int argc, char *argv[])
{
char line[255];
while(1)
{
printf("> ");
fgets(line,sizeof(line),stdin);
processLine(line);
}
}
char *my_strndup(const char *src,int n) //Allokerar och kopierar
{
char *word;
word=malloc(sizeof(char)*(n+1));
strncpy(word,src,n);
word[n]='\0';
return (word);
}
int split_line(const char* line,char *words[MAX_WORDS]) //Delar in i ord och lägger i words
{
int word_count;
int wordsize=1;
for(word_count =0; word_count < MAX_WORDS; ++word_count)
{
wordsize=0;
while(isspace(*line))
{
line++;
}
if(*line=='\0')
break;
const char *wordstart=line;
while(!isspace(*line) && *line!='\0')
{
wordsize++;
line++;
}
words[word_count]= my_strndup(wordstart, wordsize); //Sparar ord i array
}
return word_count;
}
int processLine(const char *line)
{
char *words[MAX_WORDS];
int word_count= split_line(line, words);//Delar ord och kollar antal ord
if (words[0]==NULL)
return 1;
if (!strcmp(words[0], "quit"))
{
exit(0);
return 1;
}
else if (!strcmp(words[0], "exit"))
{
if (words[1]==NULL)
exit(0);
else
exit(words[1]);
return 1;
}
else if (!strcmp(words[0], "help"))
{
printhelp();
return 1;
}
else if (!strcmp(words[0], "set"))//KOLLAR efter R
{
double d=atof(words[2]);
set(words[1][0],d);
}
else if (!strcmp(words[0],"array"))
{
double d1=atof(words[2]);
double d2=atof(words[3]);
array(words[1][0],d1,d2);
}
else if (!strcmp(words[0],"show"))
{
show(words[1][0]);
}
else if (!strcmp(words[0],"clear"))
{
clear(words[1][0]);
}
else if (words[0][1]=='=')
{
calc(words[0][0],words[0][2],words[0][4],words[0][3]);
}
else if (!strcmp(words[0],"vars"))
{
show_vars();
}
else if (!strcmp(words[0],"showCSV"))
{
showCSV(words[1]);
}
else if (!strcmp(words[0],"importCSV"))
{
importcsv(words[1][0],words[2]);
}
else if (!strcmp(words[0],"exportCSV"))
{
exportcsv(words[1][0],words[2]);
}
else if (!strcmp(words[0],"exportMAT"))
{
exportMAT(words[1][0],words[2]);
}
else if (!strcmp(words[0],"sin"))
{
matlab_arr_t *var_ax =find_arr(words[2][0]);
matlab_arr_t *var_ay =find_arr(words[1][0]);
if(!var_ax||!var_ay)
{
printf("Not a variable \n");
return 1;
}
for(int i=0; i<ARRAY_LEN; i++)
{
var_ay->v[i]=sin(var_ax->v[i]);
}
}
else if (!strcmp(words[0],"debounce"))
{
debounce(words[1][0],words[2][0]);
}
else if (!strcmp(words[0],"event"))
{
event(words[1][0],words[2][0]);
}
else
printf("Unknown command \"%s\" \n",words[0]);
}
matlab_var_t *find_var(char var)
{
for(int i=0; i<6; i++)
{
if (vars[i].n==var)
return &vars[i];
}
return NULL;
}
matlab_arr_t *find_arr(char var)
{
for(int i=0; i<6; i++)
{
if (arrs[i].n==var)
return &arrs[i];
}
return NULL;
}
|
79b163d361091881f41ffae814f405fb59a4c5d0
|
[
"C"
] | 2 |
C
|
Chrille0100/Labb2
|
2c6cb7ce7c267125fd4f99c203f26c669de4b340
|
ec10b4849739fabbaf8af191488eab6ef462d929
|
refs/heads/master
|
<repo_name>danyAmaral/move-it<file_sep>/moveit/src/app/pages/pomodoro-timer/components/challenge-box/challenge-box.component.ts
import {
Component,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges,
} from '@angular/core';
import { IChallenge } from 'src/app/interfaces/IChallenge';
import { CountdownService } from 'src/services/Countdown.service';
@Component({
selector: 'app-challenge-box',
templateUrl: './challenge-box.component.html',
styleUrls: ['./challenge-box.component.scss'],
})
export class ChallengeBoxComponent implements OnInit, OnDestroy {
challenge: IChallenge;
constructor(private countdownService: CountdownService) {}
ngOnDestroy(): void {
this.countdownService.challengeActive.unsubscribe();
}
ngOnInit(): void {
this.countdownService.challengeActive.subscribe((challenge) => {
this.challenge = challenge;
});
}
getImgage(image) {
return `/assets/icons/${image}.svg`;
}
completeChallenge() {
this.countdownService.completeChallenge();
this.clearChallenge();
}
failChallenge() {
this.countdownService.failChallenge();
this.clearChallenge();
}
clearChallenge() {
this.challenge = null;
}
}
<file_sep>/moveit/src/services/Countdown.service.ts
import { Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { BehaviorSubject } from 'rxjs';
import { IChallenge } from 'src/app/interfaces/IChallenge';
import { ICountdown } from 'src/app/interfaces/ICountdown';
import * as data from '../services/challenges.json';
@Injectable({
providedIn: 'root',
})
export class CountdownService {
countdown: BehaviorSubject<ICountdown>;
countdownMain: ICountdown;
challengeActive: BehaviorSubject<IChallenge>;
time = 0.1 * 60;
challenges: IChallenge[];
interval: any;
constructor(private cookieService: CookieService) {
this.countdown = new BehaviorSubject<ICountdown>(null);
this.challengeActive = new BehaviorSubject<IChallenge>(null);
const countdownDefault = this.countdownDefault();
this.countdown.next(countdownDefault);
this.countdownMain = countdownDefault;
this.challenges = (data as any).default as IChallenge[];
}
public startCountdown() {
this.countdownMain.hasActive = true;
this.interval = setInterval(() => {
if (this.time > 0) {
this.time = this.time - 1;
this.countdownMain.minutes = Math.floor(this.time / 60);
this.countdownMain.seconds = this.time % 60;
this.countdown.next(this.countdownMain);
} else {
clearInterval(this.interval);
this.countdownMain.hasActive = false;
this.countdownMain.hasFinish = true;
this.countdown.next(this.countdownMain);
this.startNewChallenge();
}
}, 1000);
}
resetCountdown() {
clearInterval(this.interval);
this.countdownMain.hasActive = false;
this.countdownMain.hasFinish = false;
this.countdown.next(this.countdownDefault());
}
countdownDefault(): ICountdown {
const timeDefault = 0.1 * 60;
const minutes = Math.floor(timeDefault / 60);
const seconds = timeDefault % 60;
this.time = timeDefault;
return {
minutes,
seconds,
hasActive: false,
hasFinish: false,
} as ICountdown;
}
clearCountdown() {
this.countdownMain = this.countdownDefault();
this.countdown.next(this.countdownMain);
}
startNewChallenge() {
const randomChallengeIndex = Math.floor(
Math.random() * this.challenges.length
);
const challenge = this.challenges[randomChallengeIndex];
this.setAtiveChallenge(challenge);
// new Audio('/notification.mp3').play();
// if (Notification.permission === 'granted') {
// const notify = new Notification('Novo desafio', {
// body: `valendo ${challenge.amount} xp!`,
// });
// }
}
setAtiveChallenge(challenge?: IChallenge) {
if (this.challengeActive) {
this.challengeActive.next(challenge);
}
}
failChallenge() {
this.reset();
}
reset() {
this.clearCountdown();
this.resetCountdown();
this.setAtiveChallenge(null);
}
completeChallenge() {
if (!this.challengeActive?.value) {
return;
}
const challenge = this.challengeActive.value;
const currentExperience = Number(this.getCookie('currentExperience'));
const amount = challenge.amount;
const finalExperiece = currentExperience + amount;
// if (finalExperiece >= experienceToNextLevel) {
// finalExperiece = finalExperiece - experienceToNextLevel;
// // levelUp();
// }
this.setCurrentExperience(finalExperiece);
// setChallengesCompleted(challengesCompleted + 1);
this.reset();
}
setCurrentExperience(newCurrentExperience: number) {
this.setCookie('currentExperience', newCurrentExperience.toString());
}
setCookie(key: string, value: string) {
this.cookieService.set(key, value);
}
getCookie(key: string) {
return this.cookieService.get(key);
}
}
<file_sep>/moveit/src/app/interfaces/IChallenge.ts
export interface IChallenge {
type: string;
description: string;
amount: number;
}
<file_sep>/moveit/src/app/pages/pomodoro-timer/components/countdown/countdown.component.ts
import { Component, OnChanges, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { ICountdown } from 'src/app/interfaces/ICountdown';
import { CountdownService } from '../../../../../services/Countdown.service';
@Component({
selector: 'app-countdown',
templateUrl: './countdown.component.html',
styleUrls: ['./countdown.component.scss'],
})
export class CountdownComponent implements OnInit, OnChanges {
constructor(private _countdownService: CountdownService) {}
countdown: ICountdown;
secondLeft: string;
secondRigth: string;
minuteLeft: string;
minuteRigth: string;
hasActive = false;
hasFinish = false;
ngOnInit(): void {
this._countdownService.countdown.subscribe((countdown) => {
this.countdown = countdown;
this.setTimeInfo();
});
}
ngOnChanges() {
this.countdown = this._countdownService.countdown.value;
this.setTimeInfo();
}
startCountdown() {
this._countdownService.startCountdown();
}
resetCountdown() {
this._countdownService.resetCountdown();
}
setTimeInfo() {
const [minuteLeft, minuteRigth] = String(this.countdown.minutes)
.padStart(2, '0')
.split('');
const [secondLeft, secondRigth] = String(this.countdown.seconds)
.padStart(2, '0')
.split('');
this.secondLeft = secondLeft;
this.secondRigth = secondRigth;
this.minuteLeft = minuteLeft;
this.minuteRigth = minuteRigth;
this.hasActive = this.countdown.hasActive;
this.hasFinish = this.countdown.hasFinish;
}
}
<file_sep>/moveit/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './pages/home/home.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { PomodoroTimerComponent } from './pages/pomodoro-timer/pomodoro-timer.component';
import { ExperienceBarComponent } from './pages/pomodoro-timer/components/experience-bar/experience-bar.component';
import { CountdownComponent } from './pages/pomodoro-timer/components/countdown/countdown.component';
import { ChallengeBoxComponent } from './pages/pomodoro-timer/components/challenge-box/challenge-box.component';
import { CompletedChallengesComponent } from './pages/pomodoro-timer/components/completed-challenges/completed-challenges.component';
import { ProfileComponent } from './pages/pomodoro-timer/components/profile/profile.component';
import { CookieService } from 'ngx-cookie-service';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
PomodoroTimerComponent,
ExperienceBarComponent,
CountdownComponent,
ChallengeBoxComponent,
CompletedChallengesComponent,
ProfileComponent,
],
imports: [BrowserModule, AppRoutingModule, FontAwesomeModule],
providers: [CookieService],
bootstrap: [AppComponent],
})
export class AppModule {}
<file_sep>/moveit/src/app/interfaces/ICountdown.ts
export interface ICountdown {
minutes: number;
seconds: number;
hasActive: boolean;
hasFinish: boolean;
}
|
797edd195fa1ddca677037fb01b05eb5cef7b680
|
[
"TypeScript"
] | 6 |
TypeScript
|
danyAmaral/move-it
|
e6376294f8b41286e7af09306fdab5573aff23a5
|
160666affbe0a3a71af5559ebb0bf111a6dfcdb6
|
refs/heads/main
|
<file_sep># CoverByCycles
A demonstration code for directed cycle decomposition.
<file_sep>#!/usr/bin/env python3
"""
Here is a sample program to decompose a hydrogen bond network into cycles.
It is as close as possible to the one used in the paper, but it is slightly different from the code used in the actual analysis.
"""
# pip import numpy networkx pairlist cycless
import numpy as np
import networkx as nx
import pairlist as pl
from cycless.dicycles import dicycles_iter
def read_water(file):
"""
A sample of the loader
(Assume an MDVIEW-type file)
"""
# Assume that the first line is the cell dimension
cell = [float(x) for x in file.readline().split()[1:]]
# cell shape matrix (unit is AA)
cell = np.diag(cell)
while True:
line = file.readline()
if line[0] != "-":
break
N = int(line)
waters = []
H = []
O = []
for i in range(N):
cols = file.readline().split() # name X Y Z
if cols[0][0] == "O":
O += [float(x) for x in cols[1:]]
elif cols[0][0] == "H":
H += [float(x) for x in cols[1:]]
if len(O) == 3 and len(H) == 6:
waters.append(O+H) # nine numbers
H = []
O = []
# inverse of the cell matrix
celli = np.linalg.inv(cell)
# fractional coordinate
waters = np.array(waters).reshape([-1, 3]) # OHH order
rpos = np.array(waters) @ celli
return rpos, cell
def AtoX(A):
# 環の個数のほうが十分多い場合の近似
# 特異値分解
Q1, S, Q2T = np.linalg.svd(A)
# print(Q1.shape, S.shape, Q2T.shape)
# ほぼ0の要素を0にする
S[np.abs(S)<1e-12] = 0
rank = np.sum(np.abs(S) > 0)
# print(S,r)
# SS = Q1.T @ A @ Q2T.T
# 対角行列S†の準備
Sd = np.zeros_like(A).T
Sd[:rank, :rank] = np.diag(1/S[:rank])
# print(SS)
# print(Sd.shape)
# A†
Ad = Q2T.T @ Sd @ Q1.T
#print(Ad.shape)
b = np.ones(A.shape[0])
x = Ad@b
# print(A@x)
# print(x)
return x, rank
def weight(g):
# label the edges
HBcode = {(d,a): x for x, (d,a) in enumerate(dg.edges())}
A = []
cycles = []
for s in range(4, 16):
lastA = len(A)
for cycle in dicycles_iter(g,s):
cycles.append(cycle)
row = np.zeros(len(HBcode))
for j in range(len(cycle)):
edge = HBcode[cycle[j-1], cycle[j]]
row[edge] = 1.0
A.append(row)
if lastA==len(A):
continue
lastA = len(A)
AT = np.array(A).T
# Quasi-inverse matrix
x, rank = AtoX(AT)
print(f"Largest cycle size {s}")
print(f"Number of cycles {len(cycles)}")
b = AT @ x
print(f"Sum weight: {b}")
if np.allclose(b, np.ones_like(b)):
return cycles, x
# read the atomic positions
# e.g. genice 1c -r 4 4 4 -f mdview > 1c.mdv
with open("1c.mdv") as file:
rpos, cell = read_water(file)
# define the directed graph
Opos = rpos[::3].copy()
H1pos = rpos[1::3].copy()
H2pos = rpos[2::3].copy()
dg = nx.DiGraph()
# add the edge if intermolecular O-H distance is less than 2.45 AA
for i,j,d in pl.pairs_iter(H1pos, 2.45, cell=cell, pos2=Opos, distance=True):
if d > 1.5:
vec = Opos[j] - Opos[i]
vec -= np.floor(vec + 0.5) # PBC
dg.add_edge(i,j, vec=vec)
for i,j,d in pl.pairs_iter(H2pos, 2.45, cell=cell, pos2=Opos, distance=True):
if d > 1.5:
vec = Opos[j] - Opos[i]
vec -= np.floor(vec + 0.5) # PBC
dg.add_edge(i,j, vec=vec)
# find all the cycles and determine the weights
cycles, weights = weight(dg)
for cycle, weight in zip(cycles, weights):
print(cycle, weight)
<file_sep>test: 1c.mdv
python3 cover_by_cycles.py
1c.mdv:
genice 1c -r 4 4 4 -f mdview > $@
prepare:
pip install genice
|
a3108a29dd55e36b2ec5074359b57650faaceed3
|
[
"Markdown",
"Python",
"Makefile"
] | 3 |
Markdown
|
vitroid/CoverByCycles
|
d97bb2cf396b4a4506bfe2f47c9e5ec0a2769361
|
83021d31a590011299baf5aa1b73503460d0ecdf
|
refs/heads/master
|
<file_sep>package com.example.tppokemon;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.example.tppokemon.adapter.GenerationAdapter;
import com.example.tppokemon.adapter.PokemonAdapter;
import com.example.tppokemon.database.PokemonDatabase;
import com.example.tppokemon.di.RetrofitModule;
import com.example.tppokemon.http.IPokemonService;
import com.example.tppokemon.model.Generation;
import com.example.tppokemon.model.ListGeneration;
import com.example.tppokemon.model.ListPokemon;
import com.example.tppokemon.model.Pokemon;
import com.example.tppokemon.viewmodel.PokemonViewModel;
import java.util.ArrayList;
import java.util.List;
import dagger.hilt.EntryPoint;
import dagger.hilt.android.AndroidEntryPoint;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.internal.EverythingIsNonNull;
@AndroidEntryPoint
public class MainActivity extends AppCompatActivity implements DataTransfer {
private PokemonViewModel viewModel;
private RecyclerView recyclerView;
private RecyclerView recyclerViewballs;
private PokemonAdapter pokemonAdapter;
private GenerationAdapter generationAdapter;
private PokemonAdapter.RecyclerViewClickListner listner;
private PokemonDatabase database;
private LinearLayoutManager layoutManager;
private ArrayList<Generation> listGeneration = new ArrayList<Generation>();
private IPokemonService generation;
private Call<ListGeneration> baseGenerationCall;
private LottieAnimationView lottieAnimationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.pokemon_recyclerView);
recyclerViewballs = findViewById(R.id.generationballs);
generationAdapter = new GenerationAdapter(this, MainActivity.this);
layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerViewballs.setLayoutManager(layoutManager);
recyclerViewballs.setAdapter(generationAdapter);
database = PokemonDatabase.getInstance(this);
generation = RetrofitModule.providePokemonService();
baseGenerationCall = generation.getListGeneration();
lottieAnimationView = findViewById(R.id.pokemon_load);
listner = new PokemonAdapter.RecyclerViewClickListner() {
@Override
public void onClick(View v, int position) {
Intent intent = new Intent(getApplicationContext(),PokemonDetailsActivity.class);
intent.putExtra("pokemon_name",pokemonAdapter.getPokemonAt(position).getName());
intent.putExtra("pokemon_image",pokemonAdapter.getPokemonAt(position).getUrl());
startActivity(intent);
}
};
baseGenerationCall.enqueue(new Callback<ListGeneration>() {
@Override
@EverythingIsNonNull
public void onResponse(Call<ListGeneration> call, Response<ListGeneration> response) {
ListGeneration listGenerationn = response.body();
listGeneration = listGenerationn.getResults();
generationAdapter.setGenerationballs(listGeneration);
}
@Override
public void onFailure(Call<ListGeneration> call, Throwable t) {
}
});
pokemonAdapter = new PokemonAdapter(this,listner);
recyclerView.setLayoutManager(new GridLayoutManager(this,3));
recyclerView.setAdapter(pokemonAdapter);
viewModel = new ViewModelProvider(this).get(PokemonViewModel.class);
lottieAnimationView.setVisibility(View.GONE);
lottieAnimationView.setVisibility(View.VISIBLE);
if(!database.pokemonDao().getAll("Gen 1").isEmpty()){
pokemonAdapter.setList((ArrayList)database.pokemonDao().getAll("Gen 1"));
lottieAnimationView.setVisibility(View.GONE);
}
else {
lottieAnimationView.setVisibility(View.VISIBLE);
viewModel.getPokemons();
viewModel.getPokemonList().observe(this, new Observer<ArrayList<Pokemon>>() {
@Override
public void onChanged(ArrayList<Pokemon> pokemons) {
pokemonAdapter.setList(pokemons);
pokemonAdapter.getmList().stream().forEach(pokemon -> {
pokemon.setGeneration("Gen 1");
database.pokemonDao().insert(pokemon);
});
lottieAnimationView.setVisibility(View.GONE);
}
});
}
}
@Override
public void onSetValues(int offset,int limit,String generation) {
lottieAnimationView.setVisibility(View.VISIBLE);
if(!database.pokemonDao().getAll(generation).isEmpty()){
pokemonAdapter.setList((ArrayList)database.pokemonDao().getAll(generation));
lottieAnimationView.setVisibility(View.GONE);
}
else {
viewModel.getPokemonsByGeneration(offset, limit)
.subscribe(res -> {
lottieAnimationView.setVisibility(View.VISIBLE);
pokemonAdapter.setList(res);
res.stream().forEach(pokemon -> {
pokemon.setGeneration(generation);
database.pokemonDao().insert(pokemon);
});
lottieAnimationView.setVisibility(View.GONE);
});
}
}
}<file_sep>package com.example.tppokemon.database;
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import com.example.tppokemon.model.Family;
import com.example.tppokemon.model.Pokemon;
import com.example.tppokemon.model.PokemonDetails;
import com.example.tppokemon.model.PokemonEvolution;
import com.example.tppokemon.model.PokemonType;
import com.example.tppokemon.model.Type;
@Database(entities = {Pokemon.class}, version = 6, exportSchema = false)
public abstract class PokemonDatabase extends RoomDatabase {
private static PokemonDatabase database;
private static String DATABASE_NAME = "PokemonDB";
public synchronized static PokemonDatabase getInstance(Context context) {
if (database == null) {
// when database is null
// Initialize database
database = Room.databaseBuilder(context.getApplicationContext(),
PokemonDatabase.class, DATABASE_NAME)
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
}
// Return database
return database;
}
public abstract PokemonDao pokemonDao();
}
<file_sep>package com.example.tppokemon.database;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import com.example.tppokemon.model.Pokemon;
import java.util.ArrayList;
import java.util.List;
@Dao
public interface PokemonDao {
@Query("SELECT * FROM Pokemon where generation = :generation")
List<Pokemon> getAll(String generation);
@Insert
void insert( Pokemon pokemon);
@Delete
void delete(Pokemon pokemon);
}
<file_sep>package com.example.tppokemon;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.airbnb.lottie.LottieAnimationView;
import com.example.tppokemon.model.PokemonDetails;
import com.example.tppokemon.viewmodel.PokemonViewModel;
/**
* A simple {@link Fragment} subclass.
* Use the {@link PokemonInfos#newInstance} factory method to
* create an instance of this fragment.
*/
public class PokemonInfos extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public PokemonInfos() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment PokemonInfos.
*/
// TODO: Rename and change types and number of parameters
public static PokemonInfos newInstance(String param1, String param2) {
PokemonInfos fragment = new PokemonInfos();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pokemon_infos, container, false);
LottieAnimationView lottieAnimationView = view.findViewById(R.id.infos_load);
TextView pokemonHeight = (TextView) view.findViewById(R.id.pokemon_height);
TextView pokemonWeight = (TextView) view.findViewById(R.id.pokemon_weight);
TextView pokemonTypeOne = (TextView) view.findViewById(R.id.pokemon_type_1);
TextView pokemonTypeTwo = (TextView) view.findViewById(R.id.pokemon_type_2);
Bundle bundle = this.getArguments();
pokemonHeight.setText(bundle.getInt("height") + " m");
pokemonWeight.setText(bundle.getInt("weight") + " kg");
pokemonTypeOne.setText(bundle.getString("type_one"));
pokemonTypeTwo.setText(bundle.getString("type_two"));
lottieAnimationView.setVisibility(View.GONE);
return view;
}
}<file_sep>package com.example.tppokemon.http;
import com.example.tppokemon.model.PokemonEvolution;
import java.util.List;
import io.reactivex.rxjava3.core.Observable;
import retrofit2.http.GET;
import retrofit2.http.Path;
public interface IPokemonEvolutionsService {
@GET("{pokemonId}")
Observable<List<PokemonEvolution>> getPokemonEvolutions(@Path("pokemonId") String pokemonId);
}
<file_sep># android-pokemon BY <NAME>, <NAME>
Les fonctionnalités qui ont été implementer sont:
- Lister les pokemons par generation.
- Clicker sur chaque pokemon et naviguer vers une nouvelle activity.
- NavigationBar entre les informations et l'evolution du pokemon.
- Lottie pour l'animation pendant le chargement(que ce soit la liste des pokemons ou bien les images d'evolution).
- Room pour sauvegarder la liste des pokemons par generation.
- Le bouton Back(retour) a la page d'acceuil depuis la page des informations pokemon.
# Les captures d'ecran de l'application






<file_sep>package com.example.tppokemon.http;
import com.example.tppokemon.model.ListGeneration;
import com.example.tppokemon.model.ListPokemon;
import com.example.tppokemon.model.PokemonDetails;
import io.reactivex.rxjava3.core.Observable;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface IPokemonService {
@GET("pokemon?limit=151")
Observable<ListPokemon> getPokemons();
@GET("pokemon")
Observable<ListPokemon> getPokemonsByGeneration(@Query("offset") int offset, @Query("limit") int limit);
@GET("pokemon/{pokemonId}")
Observable<PokemonDetails> getPokemonDetails(@Path("pokemonId") String pokemonId);
@GET("generation")
Call<ListGeneration> getListGeneration();
}
<file_sep>package com.example.tppokemon.model;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Index;
import androidx.room.PrimaryKey;
import androidx.room.TypeConverters;
import com.example.tppokemon.TypeConverterString;
import java.util.List;
public class Family {
private int id;
private int evolutionStage;
private List<String> evolutionLine;
private int listevolutionfk ;
public Family(int id, int evolutionStage, List<String> evolutionLine) {
this.id = id;
this.evolutionStage = evolutionStage;
this.evolutionLine = evolutionLine;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEvolutionStage() {
return evolutionStage;
}
public void setEvolutionStage(int evolutionStage) {
this.evolutionStage = evolutionStage;
}
public List<String> getEvolutionLine() {
return evolutionLine;
}
public void setEvolutionLine(List<String> evolutionLine) {
this.evolutionLine = evolutionLine;
}
public int getListevolutionfk() { return listevolutionfk; }
public void setListevolutionfk(int listevolutionfk) { this.listevolutionfk = listevolutionfk; }
}
<file_sep>package com.example.tppokemon.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.tppokemon.R;
import java.util.ArrayList;
public class PokemonEvolutionsAdapter extends RecyclerView.Adapter<PokemonEvolutionsAdapter.ViewHolder> {
private ArrayList<String> evolutionUrls = new ArrayList<>();
private Context mContext;
private ItemClickListener listner;
public PokemonEvolutionsAdapter(Context mContext) {
this.mContext = mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.pokemon_evolution_item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Glide.with(mContext).load(evolutionUrls.get(position).toString())
.into(holder.evolutionImage);
}
@Override
public int getItemCount() {
return evolutionUrls.size();
}
public void setEvolutionUrls(ArrayList<String> imageUrls){
this.evolutionUrls = imageUrls;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView evolutionImage;
public ViewHolder(@NonNull View itemView) {
super(itemView);
evolutionImage = itemView.findViewById(R.id.evolution_image);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(listner != null) listner.onItemClick(v,getAdapterPosition());
}
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
<file_sep>package com.example.tppokemon.repository;
import com.example.tppokemon.http.IPokemonEvolutionsService;
import com.example.tppokemon.http.IPokemonService;
import com.example.tppokemon.model.ListPokemon;
import com.example.tppokemon.model.PokemonDetails;
import com.example.tppokemon.model.PokemonEvolution;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import io.reactivex.rxjava3.core.Observable;
public class Repository {
private IPokemonService pokemonService;
private IPokemonEvolutionsService pokemonEvolutionsService;
@Inject
public Repository(@Named("pokemon") IPokemonService pokemonService, @Named("evolution") IPokemonEvolutionsService pokemonEvolutionsService) {
this.pokemonService = pokemonService;
this.pokemonEvolutionsService = pokemonEvolutionsService;
}
public Observable<ListPokemon> getPokemons(){
return pokemonService.getPokemons();
}
public Observable<ListPokemon> getPokemonsByGeneration(int offset, int limit){
return pokemonService.getPokemonsByGeneration(offset,limit);
}
public Observable<PokemonDetails> getPokemonDetails(String pokemonId) {
return pokemonService.getPokemonDetails(pokemonId);
}
public Observable<List<PokemonEvolution>> getPokemonEvolutions(String pokemonId){
return pokemonEvolutionsService.getPokemonEvolutions(pokemonId);
}
}
<file_sep>package com.example.tppokemon.viewmodel;
import android.annotation.SuppressLint;
import android.util.Log;
import androidx.hilt.lifecycle.ViewModelInject;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.tppokemon.model.ListPokemon;
import com.example.tppokemon.model.Pokemon;
import com.example.tppokemon.model.PokemonDetails;
import com.example.tppokemon.model.PokemonEvolution;
import com.example.tppokemon.repository.Repository;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class PokemonViewModel extends ViewModel {
private Repository repository;
MutableLiveData<ArrayList<Pokemon>> pokemonList = new MutableLiveData<>();
MutableLiveData<PokemonDetails> pokemonDetails = new MutableLiveData<>();
MutableLiveData<List<PokemonEvolution>> pokemonEvolutions = new MutableLiveData<>();
@ViewModelInject
public PokemonViewModel(Repository repository) {
this.repository = repository;
}
public MutableLiveData<ArrayList<Pokemon>> getPokemonList() {
return pokemonList;
}
@SuppressLint("CheckResult")
public void getPokemons(){
repository.getPokemons().subscribeOn(Schedulers.io())
.map(new Function<ListPokemon, ArrayList<Pokemon>>() {
@Override
public ArrayList<Pokemon> apply(ListPokemon listPokemon) throws Throwable {
ArrayList<Pokemon> list = listPokemon.getResults();
for(Pokemon pokemon : list){
String url = pokemon.getUrl();
String[] pokemonIndex = url.split("/");
pokemon.setUrl("https://pokeres.bastionbot.org/images/pokemon/"+
pokemonIndex[pokemonIndex.length -1] + ".png");
}
return list;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(res -> pokemonList.setValue(res),
err -> Log.e("ViewModel",err.getMessage()));
}
public @NonNull Observable<ArrayList<Pokemon>> getPokemonsByGeneration(int offset, int limit){
return repository.getPokemonsByGeneration(offset, limit).subscribeOn(Schedulers.io())
.map(new Function<ListPokemon, ArrayList<Pokemon>>() {
@Override
public ArrayList<Pokemon> apply(ListPokemon listPokemon) throws Throwable {
ArrayList<Pokemon> list = listPokemon.getResults();
for(Pokemon pokemon : list){
String url = pokemon.getUrl();
String[] pokemonIndex = url.split("/");
pokemon.setUrl("https://pokeres.bastionbot.org/images/pokemon/"+
pokemonIndex[pokemonIndex.length -1] + ".png");
}
return list;
}
})
.observeOn(AndroidSchedulers.mainThread());
}
public void getPokemonDetails(String pokemonId){
repository.getPokemonDetails(pokemonId).subscribeOn(Schedulers.io())
.map(new Function<PokemonDetails, PokemonDetails>() {
@Override
public PokemonDetails apply(PokemonDetails pokemonDetails) throws Throwable {
return pokemonDetails;
}
}
)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(res -> pokemonDetails.setValue(res),
err -> Log.e("ViewModel",err.getMessage()));
}
public MutableLiveData<PokemonDetails> getPokemonDetails() {
return pokemonDetails;
}
public void getPokemonEvolutions(String pokemonId){
repository.getPokemonEvolutions(pokemonId).subscribeOn(Schedulers.io())
.map(new Function<List<PokemonEvolution>, List<PokemonEvolution>>() {
@Override
public List<PokemonEvolution> apply(List<PokemonEvolution> pokemonEvolutions) throws Throwable {
return pokemonEvolutions;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(res -> pokemonEvolutions.setValue(res),
err -> Log.e("ViewModel",err.getMessage()));
}
public MutableLiveData<List<PokemonEvolution>> getPokemonEvolutions() {
return pokemonEvolutions;
}
public @NonNull Observable<PokemonDetails> getPokemonDetailsId(String pokemonId){
return repository.getPokemonDetails(pokemonId).subscribeOn(Schedulers.io())
.map(new Function<PokemonDetails, PokemonDetails>() {
@Override
public PokemonDetails apply(PokemonDetails pokemonDetails) throws Throwable {
return pokemonDetails;
}
}
)
.observeOn(AndroidSchedulers.mainThread());
}
}
<file_sep>package com.example.tppokemon;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
@GlideModule
public class PokemonGlad extends AppGlideModule {
}
<file_sep>package com.example.tppokemon.di;
import com.example.tppokemon.http.IPokemonEvolutionsService;
import com.example.tppokemon.http.IPokemonService;
import javax.inject.Named;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import hu.akarnokd.rxjava3.retrofit.RxJava3CallAdapterFactory;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
@InstallIn(ApplicationComponent.class)
public class RetrofitModule {
@Provides
@Singleton
@Named("pokemon")
public static IPokemonService providePokemonService(){
return new Retrofit.Builder()
.baseUrl("https://pokeapi.co/api/v2/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
.create(IPokemonService.class);
}
@Provides
@Singleton
@Named("evolution")
public static IPokemonEvolutionsService providePokemonEvolutionsService(){
return new Retrofit.Builder()
.baseUrl("https://pokeapi.glitch.me/v1/pokemon/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build()
.create(IPokemonEvolutionsService .class);
}
}
<file_sep>package com.example.tppokemon.adapter;
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.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.tppokemon.DataTransfer;
import com.example.tppokemon.R;
import com.example.tppokemon.model.Generation;
import java.util.ArrayList;
public class GenerationAdapter extends RecyclerView.Adapter<GenerationAdapter.ViewHolder> {
public ArrayList<Generation> generationballs = new ArrayList<Generation>();
public Context context;
public DataTransfer datatransfer;
public GenerationAdapter (DataTransfer datatransfer, Context context){
this.context = context;
this.datatransfer = datatransfer;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.generationballs, parent,false);
return new ViewHolder(contactView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Generation generationBall = this.generationballs.get(position);
Glide.with(context).load("https://pngimg.com/uploads/pokeball/pokeball_PNG21.png").centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.ball);
holder.nom.setText(generationBall.getName());
holder.ball.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int positionButton = holder.getAdapterPosition();
int offset = getOffsetAndLimit(generationballs.get(positionButton).getName())[0];
int limit = getOffsetAndLimit(generationballs.get(positionButton).getName())[1];
String generation = generationballs.get(positionButton).getName();
datatransfer.onSetValues(offset,limit,generation);
}
});
}
@Override
public int getItemCount() {
return generationballs.size();
}
public void setGenerationballs(ArrayList<Generation> list){
this.generationballs = list;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView ball ;
TextView nom;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ball = (ImageView) itemView.findViewById(R.id.picture);
nom = (TextView) itemView.findViewById(R.id.nom);
}
}
private int[] getOffsetAndLimit(String name){
switch(name) {
case "Gen 1": return new int[]{0, 151};
case "Gen 2" : return new int[]{151, 100};
case "Gen 3" : return new int[]{251, 135};
case "Gen 4" : return new int[]{386, 107};
case "Gen 5" : return new int[]{493, 156};
case "Gen 6" : return new int[]{649, 72};
case "Gen 7" : return new int[]{721, 86};
case "Gen 8" : return new int[]{807, 90};
default: return null;
}
}
}
|
6b98f5d13de89c784ae72c3fbbd35dacf9862b64
|
[
"Markdown",
"Java"
] | 14 |
Java
|
Trister00/android-pokemon
|
184df1fe3ab6b4f01d0e63411308b92d1edae2af
|
04e341bd175d9511ce02296329c39d2a95c4788a
|
refs/heads/master
|
<file_sep>$(document).ready(function() {
/* Questions & Answers */
//1. Show me how to calculate the average price of all items.
var num1 = items.filter((items) => items.price).reduce((total, current) => total + current.price / items.filter((items) => items.price).length, 0);
$(".num1").append(num1);
//***************************
//***************************
//2. Show me how to get an array of items that cost between $14.00 and $18.00 USD
var num2;
num2 = items.filter((items) => items.price >=14 && items.price <=18).map(items => items.title);
$(".num2").append(num2);
//***************************
//***************************
//3. Which item has a "GBP" currency code? Display it's name and price.
var num3;
num3 = items.filter((items)=> items.currency_code === "GBP").map((items) => items.title);
$(".num3").append(num3);
//***************************
//***************************
//4. Display a list of all items who are made of wood.
var num4;
num4 = items.filter((items)=>items.materials.includes("wood")).map((items) => items.title);
$(".num4").append(num4);
//***************************
//***************************
//5. Which items are made of eight or more materials? Display the name, number of items and the items it is made of.
var num5;
num5 = items.filter((items) => items.materials.length >= 8 ).map((items) => items.title + items.materials + items.quantity);
$(".num5").append(num5);
//***************************
//***************************
//6. How many items were made by their sellers?
var num6;
num6 = items.filter((items)=> items.who_made === "i_did").map((items) => items.title).length;
$(".num6").append(num6);
});
|
1622375bad139a7739a4fbbb960a4253fff6968f
|
[
"JavaScript"
] | 1 |
JavaScript
|
brandonkhilton/EtsyItems
|
8937be2a14c0e5e7a095e7092a10ef7107def69b
|
4865a5d32da7b8c41ee455bb0757d1ca82e2c096
|
refs/heads/main
|
<repo_name>ChainDot/dapp-myprecious<file_sep>/src/App.js
import React, { createContext } from "react";
import Dapp from "./Dapp";
import { MypreciousAddress, MypreciousAbi } from "./contracts/Myprecious";
import { useContract } from "web3-hooks";
export const MypreciousContext = createContext(null);
const App = () => {
const myprecious = useContract(MypreciousAddress, MypreciousAbi);
return (
<MypreciousContext.Provider value={myprecious}>
<Dapp />
</MypreciousContext.Provider>
);
};
export default App;
<file_sep>/src/Dapp.js
import { Button } from "@chakra-ui/button";
import { useDisclosure } from "@chakra-ui/hooks";
import { Box, Flex, Heading, Text } from "@chakra-ui/layout";
import {
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from "@chakra-ui/modal";
import { useToast } from "@chakra-ui/toast";
import React, { useContext } from "react";
import { Web3Context } from "web3-hooks";
import Main from "./components/Main";
const Dapp = () => {
const [web3State, login] = useContext(Web3Context);
const toast = useToast();
const {
isOpen: isOpenLogoutModal,
onOpen: onOpenLogoutModal,
onClose: onCloseLogoutModal,
} = useDisclosure();
const handleLoginClick = () => {
return !web3State.isLogged ? login() : "";
};
return (
<>
<Box direction="column" minH="100vh">
<Modal isOpen={isOpenLogoutModal} onClose={onCloseLogoutModal}>
<ModalOverlay />
<ModalContent>
<ModalHeader>Logout using Metamask</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Text>Use MetaMask to logout.</Text>
</ModalBody>
<ModalFooter>
<Button colorScheme="blue" onClick={onCloseLogoutModal}>
Close
</Button>
</ModalFooter>
</ModalContent>
</Modal>
<Box p="2rem" bg="blue.400">
<Flex justify="space-around">
<Heading
size="lg"
align="center"
color="blue.900"
borderWidth="3px"
borderColor="blue.900"
p="5"
borderRadius="7"
>
My Precious NFTs
</Heading>
{!web3State.isLogged ? (
<Text mb="5px" color="blue.900" fontWeight="bold">
You need to login first.
</Text>
) : (
<Flex direction="column" mx="24px">
<Text mb="5px" color="blue.900" fontWeight="bold">
Account: {web3State.account}
</Text>
<Text mb="5px" color="blue.900" fontWeight="bold">
Ether Balance: {web3State.balance} ETH
</Text>
</Flex>
)}
<Button
colorScheme="blue"
onClick={() =>
!web3State.isLogged ? handleLoginClick() : onOpenLogoutModal()
}
>
{!web3State.isLogged ? "Log in" : "Log out"}
</Button>
</Flex>
</Box>
<Main />
</Box>
</>
);
};
export default Dapp;
<file_sep>/src/components/Main.js
import { Button } from "@chakra-ui/button";
import { Box, Flex, Text } from "@chakra-ui/layout";
import { Textarea } from "@chakra-ui/textarea";
import { useToast } from "@chakra-ui/toast";
import React, { useContext, useState } from "react";
import { Web3Context } from "web3-hooks";
import { MypreciousContext } from "../App";
import { ethers } from "ethers";
const Main = () => {
const [web3State] = useContext(Web3Context);
const [precious, setPrecious] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [textArea, setTextArea] = useState("");
const [url, setUrl] = useState("");
const nft = useContext(MypreciousContext);
const toast = useToast();
const handleTextOnChange = (event) => {
setTextArea(event.target.value);
};
const handleURLOnChange = (event) => {
setUrl(event.target.value);
};
const handlePreciousClick = async () => {
try {
setIsLoading(true);
let tx = await nft.newPrecious(ethers.utils.id(textArea), url);
await tx.wait();
toast({
title: "Confirmed transaction",
description: `Address ${web3State.account} \nTransaction hash: ${tx.hash}`,
status: "success",
duration: 9000,
isClosable: true,
});
setPrecious(tx);
} catch (e) {
toast({
title: "Transaction signature denied",
description: e.message,
status: "error",
duration: 9000,
isClosable: true,
});
console.error(e);
} finally {
setIsLoading(false);
}
};
return (
<>
<Box margin="10">
<Flex
direction="column"
align="center"
justify="center"
mt="1.5rem"
borderWidth="2px"
p="3"
borderColor="blue.400"
borderRadius="10"
margin="10"
>
<Text fontSize="1.25rem" m="1rem" color="blue.600" fontWeight="bold">
Create your NFT
</Text>
<Textarea
placeholder="Enter your text here"
m="1rem"
size="lg"
onChange={handleTextOnChange}
/>
<Textarea
placeholder="Enter your URL here"
m="1rem"
size="lg"
onChange={handleURLOnChange}
/>
<Button mb="8px" colorScheme="blue" onClick={handlePreciousClick}>
Send
</Button>
</Flex>
</Box>
</>
);
};
export default Main;
|
64f4ea4aad53a338592cd77ed89fa870227fd106
|
[
"JavaScript"
] | 3 |
JavaScript
|
ChainDot/dapp-myprecious
|
6d84edfd4bc862a856a423a545dd48d5f6bba6bf
|
a68add209426927ec7b11dbf98fa1478df134191
|
refs/heads/master
|
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from "./App";
import vdom from 'react-vdom';
import Tabs from "./Tabs";
import Tab from "./Tab";
function makeWebComponentExample(root) {
const title = document.createElement('h2');
title.textContent = 'Web Component Example';
const el = document.createElement('div');
el.innerHTML = `
<x-tabs>
<x-tab title="Tab 01" closable>
<div>
<h3>Tab 01 Content</h3>
</div>
</x-tab>
<x-tab title="Tab 02">
<div>
<h3>Tab 02 Content</h3>
</div>
</x-tab>
</x-tabs>
`;
root.appendChild(title);
root.appendChild(el);
}
function makeReactExample(root) {
const app = <App/>;
const inspectButton = document.createElement('button');
inspectButton.textContent = 'Inspect';
const title = document.createElement('h2');
title.textContent = 'React Example';
const el = document.createElement('div');
inspectButton.addEventListener('click', () => {
console.log(vdom(app).children[2]);
});
root.appendChild(title);
root.appendChild(inspectButton);
root.appendChild(el);
ReactDOM.render(app, el);
}
function makeSimpleReactExample(root) {
ReactDOM.render(
<Tabs>
<Tab closable={true} title="Tab 01"><h3>Tab 01 Content</h3></Tab>
<Tab title="Tab 02"><h3>Tab 02 Content</h3></Tab>
</Tabs>, root);
}
const webComponentsRoot = document.getElementById('web-components-root');
const reactRoot = document.getElementById('react-root');
const simpleReactRoot = document.getElementById('simple-react-root');
makeWebComponentExample(webComponentsRoot);
makeReactExample(reactRoot);
makeSimpleReactExample(simpleReactRoot);
|
427821bf8127163c711e3a3e7466357306528087
|
[
"JavaScript"
] | 1 |
JavaScript
|
luciVuc/react-web-components
|
ce639240f99627c00f8f050e01cf53d956f88ceb
|
a86491cea0ea1f9524ccc5cdad02bbadf7cdbdcc
|
refs/heads/master
|
<repo_name>dstarner15/bashcuts<file_sep>/ga
#!/bin/bash
# Bash script to easily add all files and commit to git.
directory=${PWD}
message="Automated Commit from <NAME>"
branch="master"
if (("${#}" > 0))
then
if [[ ${1} == "-h" ]]
then
echo "No help for this yet :o"
exit 0
fi
if ! [[ -z ${1} ]]
then
message=${1}
fi
if [[ "${2}" ]]
then
branch=${2}
else
echo "Invalid argument! Run ga -h for help."
exit 1
fi
fi
echo "Trying to commit code to project in ${directory}"
if [[ -z "$(ls -a ${directory} | grep .git)" ]]
then
echo "FATAL: The directory ${directory} does not have a git project in it!"
exit 1
fi
echo $(git add .)
echo $(git commit -m "${message}")
echo $(git push -u origin ${branch})
<file_sep>/print
#!/bin/bash
# Simple bash script to print out all the contents of a directory cleanly
directory=${PWD}
echo ${1}
if (( "${#}" > 0 ))
then
if [[ ${1} == "-h" ]]
then
echo "This is a bash script to print out all files and list directories."
echo "Options:"
echo "print --> A simple call will print the current directory."
echo "print DIRECTORY --> A path argument will print out that directory"
exit 0
fi
if [[ -d "${1}" ]]
then
directory=${1}
else
echo "Invalid argument; run print -h for help"
exit 1
fi
fi
echo "Printing out all files in ${directory}"
for file in $directory/*
do
echo
if [[ -f ${file} ]]
then
echo "********Start********"
echo "$(basename "${file}")"
echo "---------------------"
cat ${file}
echo
echo "*********End*********"
elif [[ -d ${file} ]]
then
echo "********Start********"
echo "Directory Listing of $(basename "${file}")"
echo "---------------------"
ls ${file}
echo
echo "*********End*********"
fi
echo
done
|
1e3d603e5eea80e7140e2bb9125a9db802d46c02
|
[
"Shell"
] | 2 |
Shell
|
dstarner15/bashcuts
|
9a505df612b15a3006146d5b6651ae2d1cbcdd84
|
b472d54d650a2f960a61a0f608a570c5f1461b25
|
refs/heads/master
|
<file_sep>const {series,src,dest,watch} = require('gulp');
const sass = require('gulp-sass');
const browserSync = require('browser-sync').create();
const gulp = require('gulp');
function sass_func(){
return src(['node_modules/bootstrap/scss/bootstrap.scss','src/scss/*.scss']).
pipe(sass()).
pipe(dest('src/css')).
pipe(browserSync.stream())
}
function js(){
return src(['node_modules/bootstrap/dist/js/bootstrap.min.js','node_modules/jquery/dist/jquery.min.js','node_modules/popper.js/dist/umd/popper.min.js']).
pipe(dest('src/js')).
pipe(browserSync.stream())
}
function server(){
browserSync.init({
server:{
baseDir : './src'
}
});
watch(['node_modules/bootstrap/scss/bootstrap.scss','src/scss/*.scss'],sass_func);
watch('src\*.html').on('change',browserSync.reload);
watch('src\*.js').on('change',browserSync.reload);
}
function fonts(){
return src('node_modules/font-awesome/fonts/*').
pipe(dest('src/fonts'));
}
function fa(){
return src('node_modules/font-awesome/css/font-awesome.min.css').pipe(dest('src/css'));
}
exports.default = series(fonts,sass_func,js,server,fa);
|
03ae2512e5a7509bfd22b072c9b6a6cb52905e9f
|
[
"JavaScript"
] | 1 |
JavaScript
|
erichuang2015/bootstrap_template
|
2c704175a3baa1ed969807f4ca0753628740f375
|
4be992e65e182797418109b5088a01d80f86eec4
|
refs/heads/master
|
<file_sep># jvm-dynamic-optimizations-performance-test
Performance tests to demonstrate some of the profile-based (optimistic, speculative) optimizations performed by the JVM.
Check [this](https://advancedweb.hu/2017/03/01/jvm_optimistic_optimizations/) post for details.
<file_sep>package hu.advancedweb;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* This test measures the performance differences between cases
* whether or not there is a dominant branch.
*
* Run this test with:
* mvn clean install; java -jar target/benchmarks.jar "hu.advancedweb.Branching.*"
*
* To enable diagnostic log about inlining:
* mvn clean install; java -jar -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining target/benchmarks.jar "hu.advancedweb.Branching.*"
*
* @author <NAME>
*/
public class Branching {
@State(Scope.Thread)
public static class MyState {
public int valueSink; // just store the result somewhere, to avoid dead code removal
public double chanceOfNegativeNumber = 0.0;
Random random = new Random();
@Setup
public void setup() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(
() -> {
System.out.println("50%");
chanceOfNegativeNumber = 0.5d;
},
20, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("40%");
chanceOfNegativeNumber = 0.4d;
},
25, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("30%");
chanceOfNegativeNumber = 0.3d;
},
28, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("20%");
chanceOfNegativeNumber = 0.2d;
},
31, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("10%");
chanceOfNegativeNumber = 0.1d;
},
34, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("5%");
chanceOfNegativeNumber = 0.05d;
},
37, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("1%");
chanceOfNegativeNumber = 0.01d;
},
40, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("0");
chanceOfNegativeNumber = 0.00d;
},
43, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("neg");
chanceOfNegativeNumber = 1.0d;
},
46, TimeUnit.SECONDS);
}
}
@Measurement(iterations=100)
@Benchmark
public void testMethod(MyState s) throws Exception {
int i = getRandomNumber(s.random, s.chanceOfNegativeNumber);
doSomeBranching(s, i);
}
private int getRandomNumber(Random random, double chanceOfNegativeNumber) {
return random.nextInt(Integer.MAX_VALUE) - ((int)(Integer.MAX_VALUE * chanceOfNegativeNumber));
}
private void doSomeBranching(MyState s, int i) {
if (i >= 0) {
s.valueSink += 2;
} else {
s.valueSink += 1;
}
}
}
<file_sep>package hu.advancedweb;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* This test measures the performance differences between monomorphic,
* bimorphic, and megamorphic call sites caused by JVM inlining policy.
*
* Run this test with:
* mvn clean install; java -jar target/benchmarks.jar "hu.advancedweb.NMorphicInlinig.*"
*
* To enable diagnostic log about inlining:
* mvn clean install; java -jar -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining target/benchmarks.jar "hu.advancedweb.NMorphicInlinig.*"
*
* @author <NAME>
*/
public class NMorphicInlinig {
@State(Scope.Thread)
public static class TestState {
public int state;
public int valueSink; // just store the result somewhere, to avoid dead code removal
public Calculator simple = new SimpleCalculator();
public Calculator marvelous = new MarvelousCalculator();
public Calculator magnificent = new MagnificentCalculator();
public Calculator shiny = new ShinyCalculator();
public Calculator x = new XCalculator();
/**
* This method modifies the test state.
* @see NMorphicInlinig#getCalculator(TestState)
*/
@Setup
public void setup() {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(
() -> {
System.out.println("Iteration Deoptimize: 1");
state = 1;
},
25, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("Iteration Deoptimize: 2");
state = 2;
},
35, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("Iteration Deoptimize: 3");
state = 3;
},
160, TimeUnit.SECONDS);
executor.schedule(
() -> {
System.out.println("Iteration Deoptimize: 4");
state = 4;
},
180, TimeUnit.SECONDS);
}
}
@Measurement(iterations = 20000, time = 1, timeUnit = TimeUnit.SECONDS)
@Benchmark
public void testMethod(TestState s) throws Exception {
Calculator c = getCalculator(s);
s.valueSink = s.valueSink + handleRequest(c, 1312, 2435);
}
private int handleRequest(Calculator c, int a, int b) {
return c.doSomeCalculation(a, b);
}
/**
* A static method as a baseline.
* Change the method above to use this method instead of the polymorphic call.
*/
private static int doSomeCalculation(int startValue, int step) {
return startValue + step;
}
static final Random r = new Random();
/**
* Returns a calculator implementation, depending on the state of the test.
* The state is modified by scheduled tasks.
* @see TestState
*/
private Calculator getCalculator(TestState s) {
if (s.state == 0) {
return getCalculatorMono(s);
} else if (s.state == 1) {
return getCalculatorMonoRare(s);
} else if (s.state == 2) {
return getCalculatorEvenTwo(s);
} else if (s.state == 3) {
return getCalculatorEven(s);
} else {
return getCalculatorMono(s);
}
}
private Calculator getCalculatorEven(TestState s) {
int c = r.nextInt(5);
s.valueSink += c;
if (c == 0) {
return s.shiny;
} else if (c == 1) {
return s.magnificent;
} else if (c == 2){
return s.simple;
} else if (c == 3) {
return s.marvelous;
} else {
return s.x ;
}
}
private Calculator getCalculatorEvenTwo(TestState s) {
int c = r.nextInt(2);
s.valueSink += c;
if (c == 0) {
return s.marvelous;
} else {
return s.simple;
}
}
private Calculator getCalculatorEvenThree(TestState s) {
int c = r.nextInt(4);
s.valueSink += c;
if (c == 0) {
return s.marvelous;
} else if(c == 1) {
return s.simple;
} else {
return s.shiny;
}
}
private Calculator getCalculatorEvenFour(TestState s) {
int c = r.nextInt(4);
s.valueSink += c;
if (c == 0) {
return s.marvelous;
} else if(c == 1) {
return s.simple;
} else if (c==2){
return s.magnificent;
} else {
return s.shiny;
}
}
private Calculator getCalculatorMono(TestState s) {
int c = r.nextInt(5);
s.valueSink += c;
if (c == 0) {
return s.marvelous;
} else if (c == 1) {
return s.marvelous;
} else if (c == 2){
return s.marvelous;
} else if (c == 3) {
return s.marvelous;
} else {
return s.marvelous;
}
}
private Calculator getCalculatorMonoRare(TestState s) {
int c = r.nextInt(Integer.MAX_VALUE);
s.valueSink += c;
if (c == 0) {
System.out.println("Oh, a rare SimpleCalculator!");
return s.simple;
}
else if (c == 1) {
System.out.println("Oh, a rare ShinyCalculator!");
return s.shiny;
} else if (c == 2) {
System.out.println("Oh, a rare XCalculator!");
return s.x;
} else if (c == 3) {
System.out.println("Oh, a rare MagnificentCalculator!");
return s.magnificent;
} else {
return s.marvelous;
}
}
/*
* Different Calculator implementations.
*/
interface Calculator {
int doSomeCalculation(int a, int b);
}
static class SimpleCalculator implements Calculator {
public int doSomeCalculation(int startValue, int step) {
return startValue + step;
}
}
static class ShinyCalculator implements Calculator {
public int doSomeCalculation(int startValue, int step) {
return startValue + step;
}
}
static class MagnificentCalculator implements Calculator {
public int doSomeCalculation(int startValue, int step) {
return startValue + step;
}
}
static class MarvelousCalculator implements Calculator {
public int doSomeCalculation(int startValue, int step) {
return startValue + step;
}
}
static class XCalculator implements Calculator {
public int doSomeCalculation(int startValue, int step) {
return startValue + step;
}
}
}
|
8003f3571170a54e2449bd836e2d0e87c51516a5
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
leonzhouwei/jvm-dynamic-optimizations-performance-test
|
73d41f693e43247632e1dd54ea88de51368ebe0a
|
35965a4512ac2dc141e76f4c242e031f5fd387e1
|
refs/heads/master
|
<repo_name>Holmes1204/Rov_ros<file_sep>/scripts/rov_vision_class.py
#!/usr/bin/python
# -*- coding:utf-8 -*-
import cv2
import numpy as np
import os
import threading
import time
import rospy
from topic_example.msg import Img_fb
class RosImg():
def __init__(self):
self.img_pub = rospy.Publisher('img_feedback', Img_fb, queue_size=1)
self.img_fb = Img_fb()
def send_msg(self, angle, dist):
self.img_fb.angle_fb = round(angle, 7)
self.img_fb.dist_fb = round(dist, 7)
self.img_pub.publish(self.img_fb)
class RovVision:
def __init__(self):
self.thresh_val = 100
self.if_move = True # when using, should put False instead
self.pre_angle = 0
self.now_error = 0
self.ros_node = RosImg()
self.run_main = True
# self.forward, self.bottom = self.selectCamera() # for real camera
cap_forward = cv2.VideoCapture("/home/holmes/ros_ws/EngCom/src/ros_serial/scripts/ROV_test2.mp4") # test only
#cap_forward = cv2.VideoCapture(6)
cap_bottom = [] # test only
thread_follow_line = threading.Thread(target=self.followLine)
thread_detect_block = threading.Thread(target=self.detectBlock)
thread_start_move = threading.Thread(target=self.startMove)
thread_follow_line.setDaemon(True)
thread_detect_block.setDaemon(True)
thread_start_move.setDaemon(True)
ret, img_forward = cap_forward.read()
img_forward = cv2.flip(img_forward, 0)
self.img_forward_src = cv2.flip(img_forward, 1)
thread_start_move.start()
while (not self.if_move) and self.run_main:
try:
ret, img_forward = cap_forward.read()
img_forward = cv2.flip(img_forward, 0)
self.img_forward_src = cv2.flip(img_forward, 1)
time.sleep(0.05)
except:
pass
thread_follow_line.start()
thread_detect_block.start()
while self.run_main:
try:
ret, img_forward = cap_forward.read()
img_forward = cv2.flip(img_forward, 0)
self.img_forward_src = cv2.flip(img_forward, 1)
time.sleep(0.05)
except:
pass
def selectCamera(self):
"""
In linux only
cap_forward for autoAdapt and followLine, cap_bottom for detectBlock
:return: cap_forward, cap_bottom
"""
vid = os.listdir('/dev/')
vid_num = []
# find all the camera index
for i in range(len(vid)):
if 'video' in vid[i]:
vid_num.append(int(vid[i][-1]))
del vid
# remove unavailable element
for vid in vid_num:
try:
cap = cv2.VideoCapture(vid)
except:
vid_num.remove(vid)
del cap
# get two video streams
cap_forward = cv2.VideoCapture(vid_num[0])
cap_bottom = cv2.VideoCapture(vid_num[1])
# if high resolution is bottom >
# if high resolution is forward <
if cap_forward.get(3) > cap_bottom.get(3):
cap_tmp = cap_forward
cap_forward = cap_bottom
cap_bottom = cap_tmp
del cap_tmp
# set to low resolution
cap_forward.set(3, 640)
cap_forward.set(4, 480)
cap_bottom.set(3, 640)
cap_bottom.set(4, 480)
return cap_forward, cap_bottom
def detectBlock(self):
pass
def followLine(self):
"""
follow line
input: global img img_forward_src
output: global thresh_val and pre_angle
:param: none
:return: none
"""
rate=rospy.Rate(10)
while True: # and not rospy.is_shutdown()):
img_src = self.img_forward_src
img_src = cv2.resize(img_src, (640, 360))
img_2 = img_src[:, :, 2]
img_2 = cv2.GaussianBlur(img_2, (15, 15), 15)
img_2 = cv2.blur(img_2, (15, 15))
img_2 = cv2.medianBlur(img_2, 15)
ret, img_2 = cv2.threshold(img_2, self.thresh_val, 255, cv2.THRESH_BINARY)
track_img = np.where(img_2 == 0)
track_x = (track_img[1]).T
track_y = (track_img[0]).T
output_img = cv2.cvtColor(img_2, cv2.COLOR_GRAY2BGR)
if (not len(track_x) == 0) and (not len(track_y) == 0):
# fit linear function according to the white region
pre_fit = np.polyfit(img_src.shape[0] - track_y + 1, track_x + 1, 1) # #col = f(#row)
pre_val = np.polyval(pre_fit, [0, img_src.shape[0] - 1]).astype(np.int) # #col = f(#row)
output_img = cv2.line(output_img, (int((pre_val[0] + pre_val[1]) / 2), output_img.shape[0]),
(int((pre_val[1] + pre_val[0]) / 2), 0), (0, 255, 0), 5)
output_img = cv2.line(output_img, (pre_val[0], img_src.shape[0]),
(pre_val[1], 0), (0, 0, 255), 5) # point(#col(topmin butmax), # row)
# calculate degree error
pre_angle = (pre_val[0] - pre_val[1]) / np.sqrt((pre_val[0] - pre_val[1]) ** 2 + img_src.shape[0] ** 2)
pre_angle = np.arcsin(pre_angle)
# calculate position error
bot_part = np.where(track_y > img_src.shape[0] - (img_src.shape[0] / 4))
now_error = np.mean(track_x[bot_part])
now_error = now_error - img_src.shape[1] / 2
if not np.isnan(pre_angle) and not np.isnan(now_error):
self.pre_angle = pre_angle
self.now_error = now_error
self.ros_node.send_msg(round(self.pre_angle, 7), round(self.now_error, 7))
output_img = cv2.putText(output_img, 'angle error:' + str(round(self.pre_angle, 7)),
(int(img_src.shape[1] * 0.03), int(img_src.shape[0] * 0.1)),
cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255), 3)
output_img = cv2.putText(output_img, 'horizontal error:' + str(round(self.now_error, 7)),
(int(img_src.shape[1] * 0.03), int(img_src.shape[0] * 0.2)),
cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255), 3)
else:
output_img = cv2.putText(output_img, 'angle error:' + str(round(self.pre_angle, 7)),
(int(img_src.shape[1] * 0.03), int(img_src.shape[0] * 0.1)),
cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255), 3)
output_img = cv2.putText(output_img, 'horizontal error:' + str(round(self.now_error, 7)),
(int(img_src.shape[1] * 0.03), int(img_src.shape[0] * 0.2)),
cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 255), 3)
output_img = cv2.hconcat([img_src, output_img])
cv2.imshow('', output_img)
rate.sleep()
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
self.run_main = False
break
def startMove(self):
while not self.if_move:
try:
img_src = self.img_forward_src
img_src = cv2.resize(img_src, (640, 360))
# use blue to detect the start zone, use red to detect line
img_2 = img_src[:, :, 2]
img_2 = cv2.GaussianBlur(img_2, (15, 15), 15)
img_2 = cv2.blur(img_2, (15, 15))
img_2 = cv2.medianBlur(img_2, 15)
img_0 = img_src[:, :, 0]
img_0 = cv2.GaussianBlur(img_0, (15, 15), 15)
img_0 = cv2.blur(img_0, (15, 15))
img_0 = cv2.medianBlur(img_0, 15)
ret, img_2 = cv2.threshold(img_2, self.thresh_val, 255, cv2.THRESH_BINARY)
ret, img_0 = cv2.threshold(img_0, 100, 255, cv2.THRESH_BINARY)
track_img = np.where(img_2 == 255)
track_x = (track_img[1]).T
track_y = (track_img[0]).T
start_img = np.where(img_0 == 0)
start_x = (start_img[1]).T
start_y = (start_img[0]).T
cv2.imshow('2', img_2)
cv2.imshow('1', img_0)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
self.run_main = False
break
if len(start_x) == 0 or len(start_y) == 0:
continue
img = cv2.cvtColor(img_2, cv2.COLOR_GRAY2BGR)
# fit linear function according to the white region
pre_fit = np.polyfit(img_src.shape[0] - track_y + 1, track_x + 1, 1) # #col = f(#row)
dis_mean = np.sum(((track_x + 1) - pre_fit[0] * (img.shape[0] - track_y + 1) - pre_fit[1]) \
/ np.sqrt(pre_fit[0] ** 2 + 1)) * (1 / track_x.size)
dis_var = ((track_x + 1) - pre_fit[0] * (img.shape[0] - track_y + 1) - pre_fit[1]) \
/ np.sqrt(pre_fit[0] ** 2 + 1) - dis_mean
dis_var = np.dot(dis_var, dis_var.T) * (1 / track_x.size)
dis_s = np.sqrt(dis_var) # standard error
start_width = max(start_x) - min(start_x)
start_height = max(start_y) - min(start_y)
start_mid_x = np.mean(start_x) + 1
start_mid_y = np.mean(img_src.shape[0] - start_y + 1)
start_range = np.polyval(pre_fit, start_mid_y)
# if the height of the black is bigger than 0.1 * the width of the black
# and the black area is bigger than 0.5 of the boundary
# and the center of the black is within the line
if start_height >= 0.1 * start_width \
and len(start_y) >= 0.5 * start_width * start_height \
and start_range - dis_s <= start_mid_x <= start_range + dis_s:
self.if_move = 1
except:
pass
if __name__ == "__main__":
rospy.init_node('img_feedback')
rov_vision = RovVision()<file_sep>/include/topic_example/mbot_linux_serial.h
#ifndef MBOT_LINUX_SERIAL_H
#define MBOT_LINUX_SERIAL_H
#include <ros/ros.h>
#include <ros/time.h>
#include <boost/asio.hpp>
#include <geometry_msgs/Twist.h>
typedef union
{
uint16_t u16;
uint8_t u8[2];
}uint16to8;
struct mtr_msg
{
/* data */
uint8_t mtr_state[10];
};
void serialInit();
bool TX_serial_msg(const mtr_msg& mtr);
//extern bool readSpeed(double &Left_v,double &Right_v,double &Angle,unsigned char &ctrlFlag);
unsigned char getCrc8(unsigned char *ptr, unsigned short len);
#endif//MBOT_LINUX_SERIAL_H
<file_sep>/src/mbot_linux_serial.cpp
//针对my_rov的串口通信协议
#include <topic_example/mbot_linux_serial.h>
using namespace std;
using namespace boost::asio;
//串口相关对象
boost::asio::io_service iosev;
boost::asio::serial_port sp(iosev, "/dev/ttyUSB0");
//boost::asio::serial_port sp(iosev, "/dev/ttyTHS1");
boost::system::error_code err;
/********************************************************
串口发送接收相关常量、变量、共用体对象
********************************************************/
const unsigned char ender[2] = {0xBF, 0xBB};//定义消息头
const unsigned char header[2] = {0xAF, 0xAA};
/********************************************************
函数功能:串口参数初始化
入口参数:无
出口参数:
********************************************************/
void serialInit()//串口初始化
{
/*波特率*/
sp.set_option(serial_port::baud_rate(115200));
/*数据位*/
sp.set_option(serial_port::character_size(8));
/*奇偶校验位*/
sp.set_option(serial_port::parity(serial_port::parity::none));
/*停止位*/
sp.set_option(serial_port::stop_bits(serial_port::stop_bits::one));
/*串口流控制*/
sp.set_option(serial_port::flow_control(serial_port::flow_control::none));
}
bool TX_serial_msg(const mtr_msg& mtr)
{
const int length = 10;
uint8_t buf[3+length+3] = {0};//定义发送数据变量
// 设置消息头
buf[0] = header[0];
buf[1] = header[1]; //buf[0] buf[1]
buf[2] = length; //buf[2] size为6
for (int i = 0; i < length; i++)
{
buf[3+i]=mtr.mtr_state[i];
}
// 设置校验值、消息尾
buf[3 + length] = getCrc8(buf, 3 + length);
buf[3 + length + 1] = ender[0];
buf[3 + length + 2] = ender[1];
if(boost::asio::write(sp, boost::asio::buffer(buf))!=0)
{
return true;
}
else
{
return false;
}
}
/********************************************************
函数功能:获得8位循环冗余校验值
入口参数:数组地址、长度
出口参数:校验值
********************************************************/
unsigned char getCrc8(unsigned char *ptr, unsigned short len)
{
unsigned char crc;
unsigned char i;
crc = 0;
while(len--)
{
crc ^= *ptr++;
for(i = 0; i < 8; i++)
{
if(crc&0x01)
crc=(crc>>1)^0x8C;
else
crc >>= 1;
}
}
return crc;
}
<file_sep>/README.md
# Rov_ros
工程训练比赛代码
为了方便大家一起更改,也为了方便移植到jetson nano 上, 故放到github上
队员:zjh,lym,zzm,xlh
<file_sep>/src/publish_node.cpp
/**************************
用遥控器通过上位机串口通讯控制stm32来控制6个推进器运动
//安装推进器注意:1 头 2
// 5 6
// 3 4
*************************/
//遥控器操作方式:左摇杆负责平面运动,右摇杆竖直方向为沉浮,水平方向为原地转动
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <topic_example/mbot_linux_serial.h>
#include <sensor_msgs/Joy.h>
#include <string.h>
#include <topic_example/Img_fb.h>
void img_fb_callback(const topic_example::Img_fb::ConstPtr& img_fb_msg){
float angle_error = img_fb_msg->angle_fb;
float dist_error = img_fb_msg->dist_fb;
static mtr_msg mtrs;
static int x=1,count;
mtrs.mtr_state[0] = 1;
mtrs.mtr_state[1] = angle_error*2400/3.1415926;
mtrs.mtr_state[2] = (int) dist_error;
mtrs.mtr_state[3] = x;
mtrs.mtr_state[4] = 0;
mtrs.mtr_state[5] = 0;
mtrs.mtr_state[6] = 0;
mtrs.mtr_state[7] = 0;
mtrs.mtr_state[8] = 0;
mtrs.mtr_state[9] = 0;
mtrs.mtr_state[10] = 0;
if(count==100){
x=(x==1?2:1);
count=0;}
count++;
if(TX_serial_msg(mtrs))
ROS_INFO("%d %d %d %d",mtrs.mtr_state[0],mtrs.mtr_state[1],mtrs.mtr_state[2],mtrs.mtr_state[3]);
else
ROS_INFO("failed!");
return;
return;
}
int main(int agrc,char **argv)
{
ros::init(agrc,argv,"serial_stm32");
ros::NodeHandle nh;
//ros::Subscriber joy_sub = nh.subscribe("/joy", 1000, &joy_callback);//订阅手柄
ros::Subscriber img_fb_sub = nh.subscribe("/img_feedback", 100, &img_fb_callback);
ros::Rate loop_rate(100);
//串口初始化
serialInit();
while(ros::ok())
{
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
|
4aebb52508ca1944bd2b43603e9386e7c08cfb03
|
[
"Markdown",
"C",
"Python",
"C++"
] | 5 |
Python
|
Holmes1204/Rov_ros
|
fa57f848138c27bc54f383834af6773ce6975084
|
406175f6b4dbe5260ca9dfcf42532c638d86a709
|
refs/heads/master
|
<file_sep>package tests.data;
public enum ItPlatformaUser {
USER("Test22"),
USER2("Test23"),
USER3("Test24"),
EMAIL("<EMAIL>"),
EMAIL2("<EMAIL>"),
EMAIL3("<EMAIL>%&# <EMAIL>"),
PASSWORD("<PASSWORD>"),
PASSWORD2("<PASSWORD>");
private final String value;
ItPlatformaUser(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
<file_sep>site = https://https://it-platforma.website/
login = sitelogin
password = <PASSWORD><file_sep>package tests.runners;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.WebDriverRunner;
import com.codeborne.selenide.logevents.SelenideLogger;
import io.qameta.allure.selenide.AllureSelenide;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import tests.pages.BasePage;
public class Debug extends BasePage {
@Parameters({"browserName"})
@BeforeMethod(alwaysRun = true)
static public void customConfig(@Optional String browserName) {
Configuration.timeout = 30000;
Configuration.reportsFolder = "target/screenshots";
if (browserName != null) {
Configuration.browser = browserName;
}
Configuration.startMaximized = true;
SelenideLogger.addListener("AllureSelenide", new AllureSelenide().screenshots(true).savePageSource(true));
}
@AfterMethod(alwaysRun = true)
public static void tearDown() {
WebDriverRunner.closeWebDriver();
}
}
<file_sep>package tests.pages.itplatforma;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import io.qameta.allure.Step;
import static com.codeborne.selenide.Selectors.byXpath;
import static com.codeborne.selenide.Selenide.$;
import static tests.logger.CustomLogger.logger;
public class ItPlatformaAuthorization {
SelenideElement buttonSingIn = $(byXpath("//span[@class='text-wrap' and text()='Sign in']"));
SelenideElement fieldUser = $(byXpath("//input[@id='user_login']"));
SelenideElement fieldPassword = $(byXpath("//input[@id='user_pass']"));
SelenideElement buttonLogin = $(byXpath("//button[@class='tml-button']"));
String checkErrorMessege = "//li";
String checkErrorMessege1 = "//li[@class='tml-error']/a";
SelenideElement checkBoxRememberMe = $(byXpath("//input[@id='rememberme']"));
@Step
public void pressButtonSingIn() {
buttonSingIn.click();
logger.info("ok");
}
@Step
public void fillTheFieldUser(String user) {
fieldUser.clear();
fieldUser.sendKeys(user);
logger.info(user + " - ok");
}
@Step
public void fillTheFieldPassword(String password) {
fieldPassword.clear();
fieldPassword.sendKeys(password);
logger.info("ok");
}
@Step
public void pressButtonLogin() {
buttonLogin.click();
logger.info("ok");
}
@Step
public void checkErrorMessage(String errorText) {
$(byXpath(checkErrorMessege + "[text()='" + errorText + "']")).shouldBe(Condition.visible);
logger.info(errorText + "ok");
}
@Step
public void checkErrorMessage1(String errorText) {
$(byXpath(checkErrorMessege1 + "[text()='" + errorText + "']")).shouldBe(Condition.visible);
logger.info(errorText + "ok");
}
@Step
public void setCheckBoxRememberMe() {
checkBoxRememberMe.click();
logger.info("ok");
}
}
<file_sep>package tests.utils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class SimpleExcelWriterExample {
public static void writeToExcelFile(String var1, String var2) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Java Books");
Object[][] bookData = {
{var1, var2, 35},
};
int rowCount = 0;
for (Object[] aBook : bookData) {
Row row = sheet.createRow(rowCount++);
int columnCount = 0;
for (Object field : aBook) {
Cell cell = row.createCell(columnCount++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try (FileOutputStream outputStream = new FileOutputStream("target//JavaBooks.xlsx")) {
workbook.write(outputStream);
System.out.println("Done");
}
}
}
<file_sep>package tests.pages;
import tests.pages.itplatforma.ItPlatformaAuthorization;
import tests.pages.itplatforma.ItPlatformaMainPage;
import tests.pages.itplatforma.ItPlatformaRegistration;
public class BasePage {
public ItPlatformaMainPage ItPlatformaMainPage = new ItPlatformaMainPage();
public ItPlatformaAuthorization ItPlatformaAuthorization = new ItPlatformaAuthorization();
public ItPlatformaRegistration ItPlatformaRegistration = new ItPlatformaRegistration();
}
<file_sep># project_w45_nikolay
Examen Automation QALight W45(groupe)
|
13ef8d6e4ccb958f280447214aeb548d64b3fcc4
|
[
"Markdown",
"Java",
"INI"
] | 7 |
Java
|
NikolayAntonyuk/project_w45_nikolay
|
0220ab001874bd6b9470f62da8e5e91672729c80
|
4f6d8b010e54dab3d1548fc184f9a30d9914fb78
|
refs/heads/master
|
<repo_name>RafeeAlbadri/Prescriptipn<file_sep>/Haeder.js
import React, { Component } from 'react';
import Context from './Context';
import styled from 'styled-Components';
let Add = styled.button`
background-color:#009FB4;
border:none;
border-radius:60px;
`
let Container = styled.header `
background-color: #132E41;
height: 120px;
width: 100%;
box-shadow: 2px 4px 15px #707070;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0px;
margin: 0px;
`
class Header extends Component {
render() {
return (
<Context.Consumer>
{
()=>{
return (
<Container>
<img width="140px" src={require('./assets/logo.jpg')}></img>
<Add>Add Prescription</Add>
</Container>
)
}
}
</Context.Consumer>
)
}
}
export default Header
|
9d115c4a1fdca9d0c4565f96e3d302c1994e96bc
|
[
"JavaScript"
] | 1 |
JavaScript
|
RafeeAlbadri/Prescriptipn
|
ab734191334e28993675f4f002a4e9fb02de7a2a
|
a6e648d09699a1e42286917e2792d774e5a51942
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
import tempfile
import sys
import os
import time
import eventlet
import re
import argparse
import logging
import configparser
from eventlet.green import socket
from eventlet.green import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('local-file',
help='Local file to upload')
parser.add_argument('remote-file',
help="Remote file destination")
parser.add_argument('hosts',
help="File containing list of hosts",
default='',
nargs='?')
parser.add_argument('--retry',
default=0,
type=int,
help="Number of times to retry in case of failure. " +
"Use -1 to make it retry forever (not recommended)")
parser.add_argument('--port',
default=8998,
help="Port number to run the tracker on")
parser.add_argument('--remote-path',
default='/tmp/herd',
help="Temporary path to store uploads")
parser.add_argument('--data-file',
default='./data',
help="Temporary file to store for bittornado.")
parser.add_argument('--log-dir',
default='/tmp/herd',
help="Path to the directory for murder logs")
parser.add_argument('--hostlist',
default=False,
help="Comma separated list of hots")
opts = vars(parser.parse_args())
murder_client = eventlet.import_patched('murder_client')
bttrack = eventlet.import_patched('BitTornado.BT1.track')
makemetafile = eventlet.import_patched('BitTornado.BT1.makemetafile')
username=''
password=''
log = logging.getLogger('herd')
log.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
# add the handlers to the log
log.addHandler(ch)
herd_root = os.path.dirname(os.path.realpath(__file__))
bittornado_tgz = os.path.join(herd_root, 'bittornado.tar.gz')
murderclient_py = os.path.join(herd_root, 'murder_client.py')
def run(local_file, remote_file, hosts):
start = time.time()
log.info("Spawning tracker...")
eventlet.spawn(track)
eventlet.sleep(1)
local_host = (local_ip(), opts['port'])
log.info("Creating torrent (host %s:%s)..." % local_host)
torrent_file = mktorrent(local_file, '%s:%s' % local_host)
log.info("Seeding %s" % torrent_file)
eventlet.spawn(seed, torrent_file, local_file)
log.info("Transferring")
if not os.path.isfile(bittornado_tgz):
cwd = os.getcwd()
os.chdir(herd_root)
args = ['tar', 'czf', 'bittornado.tar.gz', 'BitTornado']
log.info("Executing: " + " ".join(args))
subprocess.call(args)
os.chdir(cwd)
pool = eventlet.GreenPool(100)
threads = []
remainingHosts = hosts
for host in hosts:
global username
host= '%s@%s'%(username,host)
threads.append(pool.spawn(transfer, host, torrent_file, remote_file, opts['retry']))
for thread in threads:
host = thread.wait()
remainingHosts.remove(host)
log.info("Done: %-6s Remaining: %s" % (host, remainingHosts))
os.unlink(torrent_file)
try:
os.unlink(opts['data_file'])
except OSError:
pass
log.info("Finished, took %.2f seconds." % (time.time() - start))
def transfer(host, local_file, remote_target, retry=0):
rp = opts['remote_path']
file_name = os.path.basename(local_file)
remote_file = '%s/%s' % (rp, file_name)
if ssh(host, 'test -d %s/BitTornado' % rp) != 0:
ssh(host, "mkdir %s" % rp)
scp(host, bittornado_tgz, '%s/bittornado.tar.gz' % rp)
ssh(host, "cd %s; tar zxvf bittornado.tar.gz > /dev/null" % rp)
scp(host, murderclient_py, '%s/murder_client.py' % rp)
log.info("Copying %s to %s:%s" % (local_file, host, remote_file))
scp(host, local_file, remote_file)
command = 'python %s/murder_client.py peer %s %s' % (rp, remote_file, remote_target)
log.info("running \"%s\" on %s" % (command, host))
result = ssh(host, command)
ssh(host, 'rm %s' % remote_file)
if result != 0:
log.info("%s FAILED with code %s" % (host, result))
while retry != 0:
retry = retry - 1
log.info("retrying on %s" % host)
transfer(host, local_file, remote_target, 0)
return host
#def ssh(host, command):
# if not os.path.exists(opts['log_dir']):
# os.makedirs(opts['log_dir'])
#
# with open("%s%s%s-ssh.log" % (opts['log_dir'], os.path.sep, host), 'a') as log:
# result = subprocess.call(['ssh', '-o UserKnownHostsFile=/dev/null',
# '-o LogLevel=quiet',
# '-o StrictHostKeyChecking=no',
# host, command], stdout=log,
# stderr=log)
# return result
def ssh(host,command):
global password
if not os.path.exists(opts['log_dir']):
os.makedirs(opts['log_dir'])
incommand = ['sshpass','-p',password,'ssh',host,command]
result = subprocess.call(incommand)
print ('SSH complete')
return result
def scp(host, local_file, remote_file):
incommand=['sshpass','-p',password,'scp',local_file,'%s:%s' %(host,remote_file)]
print(incommand)
return subprocess.call(incommand,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
def mktorrent(file_name, tracker):
torrent_file = tempfile.mkstemp('.torrent')
makemetafile.make_meta_file(file_name, "http://%s/announce" % tracker,
{'target': torrent_file[1], 'piece_size_pow2': 0})
return torrent_file[1]
def track():
bttrack.track(["--dfile", opts['data_file'], "--port", opts['port']])
def seed(torrent, local_file):
murder_client.run(["--responsefile", torrent,
"--saveas", local_file])
def local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("10.1.0.0", 0))
return s.getsockname()[0]
def parseconfig():
config= configparser.ConfigParser()
config.read('info.ini')
global username;
username=config.get('USER','user').strip('"')
global password
password=config.get('USER','password').strip('"')
def herdmain():
if not os.path.exists(opts['hosts']) and opts['hostlist'] is False:
sys.exit('ERROR: hosts file "%s" does not exist' % opts['hosts'])
if opts['hosts']:
hosts = [line.strip() for line in open(opts['hosts'], 'r')]
# filter out comments and empty lines
hosts = [host for host in hosts if not re.match("^#", host) and not host == '']
else:
hosts = opts['hostlist'].split(',')
# handles duplicates
hosts = list(set(hosts))
parseconfig()
log.info("Running with options: %s" % opts)
log.info("Running for hosts: %s" % hosts)
run(opts['local-file'], opts['remote-file'], hosts)
herdmain()
|
9a3958cc05ee7cb7d74aeef71b1adabe58b8086a
|
[
"Python"
] | 1 |
Python
|
sachuin23/Herd
|
3cd3b4f68990e97d3ef264be54383942d4d094c0
|
90f945cd1c28f87f16647c938d676c90cd1258f7
|
refs/heads/master
|
<repo_name>alextheprogrammer21/Interview-Scheduler<file_sep>/src/helpers/selectors.js
export function getAppointmentsForDay(state, day) {
let appointments = [];
const filteredDays = state.days.filter(currentDay => currentDay.name === day);
if (filteredDays.length > 0 && filteredDays[0].appointments.length > 0) {
appointments = filteredDays[0].appointments.map((appointmentId) => state.appointments[appointmentId]);
}
return appointments;
}
export function getInterview(state, interview) {
if (interview) {
let student = interview.student;
let interviewer = state.interviewers[interview.interviewer];
let interviewInfo = { student, interviewer };
return interviewInfo;
}
return null;
}
export function getInterviewersForDay(state, day) {
let interviewers = [];
const filteredDays = state.days.filter(currentDay => currentDay.name === day);
if (filteredDays.length > 0 && filteredDays[0].interviewers.length > 0) {
interviewers = filteredDays[0].interviewers.map((interviewerId) => state.interviewers[interviewerId]);
}
return interviewers;
}<file_sep>/README.md
# Interview Scheduler
A scheduler that allows users to set up, edit, or delete appointments. Made with React.
### Main Page

### New Appointment

### Delete Appointment Confirmation

## Dependencies
- axios
- classnames
- normalize.css
- react
- react-dom
- react-scripts
- storybook
## Setup
Install dependencies with `npm install`.
## Running Webpack Development Server
```sh
npm start
```
## Running Storybook Visual Testbed
```sh
npm run storybook
```
<file_sep>/src/hooks/useVisualMode.js
import React from "react";
export default function useVisualMode(initial) {
const [mode, setMode] = React.useState(initial);
const [history, setHistory] = React.useState([initial]);
function transition(newMode) {
setHistory([...history, newMode]);
setMode(newMode);
}
function back() {
if (history[history.length - 1] === initial) {
} else {
setHistory(history.slice(0, history.length - 1));
setMode(history[history.length - 2]);
}
}
return { mode, transition, back };
}
<file_sep>/src/hooks/useApplicationData.js
import React from "react";
const axios = require("axios").default;
export default function useApplicationData() {
const [state, setState] = React.useState({
day: "Monday",
days: [],
appointments: {},
interviewers: {},
spots: 5
});
const setDay = day => setState({ ...state, day });
let calenderDay = "Monday";
for (const element in state.days) {
if (state.day === state.days[element].name) {
calenderDay = element;
}
}
React.useEffect(() => {
Promise.all([
Promise.resolve(axios.get("/api/days")),
Promise.resolve(axios.get("/api/appointments")),
Promise.resolve(axios.get("/api/interviewers"))
]).then(all => {
setState(prev => ({
days: all[0].data,
appointments: all[1].data,
interviewers: all[2].data
}));
});
}, []);
function bookInterview(id, interview) {
const appointment = {
...state.appointments[id],
interview: { ...interview }
};
const appointments = {
...state.appointments,
[id]: appointment
};
return axios.put(`/api/appointments/${id}`, appointment).then(() => {
setState(state => ({ ...state, appointments }));
Promise.all([axios.get("/api/days")]).then(([days]) => {
setState(state => ({ ...state, days: days.data }));
});
});
}
const getSpotsForDay = state => {
const dayFound = { ...state.days.find(obj => obj.name === state.day) };
let spots = 0;
for (const appointmentId of dayFound.appointments) {
if (state.appointments[appointmentId].interview === null) {
spots++;
}
}
const dayIndex = dayFound.id - 1;
return { spots, dayIndex };
};
const cancelInterview = id => {
const appointment = {
...state.appointments[id],
interview: null
};
const appointments = {
...state.appointments,
[id]: appointment
};
const newStateTemp = { ...state, appointments };
const { spots, dayIndex } = getSpotsForDay(newStateTemp);
const daySpotsUpdate = { ...state.days[dayIndex], spots };
const updatedDays = [...state.days];
updatedDays[dayIndex] = daySpotsUpdate;
return new Promise((resolve, reject) => {
axios
.delete(`/api/appointments/${id}`)
.then(function(res) {
setState({ ...state, appointments, days: updatedDays });
resolve();
})
.catch(function(error) {
console.log(error);
reject();
});
});
};
return { state, setDay, bookInterview, cancelInterview };
}
|
efa49560b4bc9ab0ed3fabf3e55feaec5d144eec
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
alextheprogrammer21/Interview-Scheduler
|
244293793e558ede924966c07ae3e4b9902cc020
|
ae918e4c7d047d20b47505237f9ddb9decd5da52
|
refs/heads/master
|
<file_sep>(function( $ ) {
$.fn.fileViewer = function (action) {
var self = this;
if(action === null){
$(self).click(function() {
$(self).addClass("hidden");
$(self).find("iframe").addClass("hidden");
//$(self).find("iframe").attr("src", null);
});
$(self).find("iframe").click(function() {
event.stopPropagation();
});
$(self).find("iframe").load(function() {
if ($(this).attr("src") != null) {
$(this).removeClass("hidden");
$(self).removeClass("hidden");
}
});
}else if(action === "open"{
$(this).removeClass("hidden");
$(self).removeClass("hidden");
}else if(action === "safeOpen"{
if ($(this).attr("src") != null) {
$(this).removeClass("hidden");
$(self).removeClass("hidden");
}
}else if(typeof action === "object"){
if(action.src != null){
$(self).find("iframe").attr("src", action.src);
}
}
}
}( jQuery ));
<file_sep>(function ( $ ) {
/**
* @version: 1.0.0
* @author <NAME> <<EMAIL>>
* @requires: jQuery 1.10.2+
*
* Método jQuery encargado de comprobar la validez de los datos introducidos en
* función de los atributos añadidos a dichos campos. Pueden ser los siguientes:
* -data-check-required: el campo es obligatorio
* -data.check-format: el valor ha de cumplir con la expresión regular pasada
* en este atributo.
*
* @param params {Object}
* Objeto que almacena los de configuración de la función:
* -params.callback: función que se ejecutará al realizar la comprobación de
* cada campo. Dicha función recibirá dos parámetros:
* -flag: booleano que en estado true si el campo ha
* pasado la comprobación y en estado false en caso contrario.
* -element: objeto jQuery sobre el que se ha realizado la comprobación.
* @returns {Boolean}
* True en caso de que todos los campos superen la validación, false en caso
* de de alguno no la supere.
*/
jQuery.prototype.checkInputs = function(params){
var ok = true;
$(this.selector).each(function(){
var flag = true;
if($(this).attr("data-check-required") != undefined && ($(this).val() == null || $(this).val() == "")){
flag = false;
ok = false;
}
if($(this).attr("data-check-format") != undefined && $(this).val() != "" && $(this).val() != null && !$(this).val().match($(this).attr("data-check-format"))){
flag = false;
ok = false;
}
if(typeof params.callback == 'function'){
params.callback(flag, $(this));
}
});
return ok;
};
}( jQuery ));
<file_sep>(function ( $ ) {
$.fn.presentation = function(params){
var settings = $.extend({time: 3000}, params);
$(this).each(function(index){
var self = this;
var presentationElements = $(self).find(".presentation-element");
var maxOuterHeight = 0;
presentationElements.each(function(index2){
if($(this).outerHeight() > maxOuterHeight){
maxOuterHeight = $(this).outerHeight();
}
});
$(self).height(maxOuterHeight);
$(window).resize(function(){
var maxOuterHeight = 0;
presentationElements.each(function(index2){
if($(this).outerHeight() > maxOuterHeight){
maxOuterHeight = $(this).outerHeight();
}
});
$(self).height(maxOuterHeight);
});
setInterval(function(){
var visibleElementPos = null;
presentationElements.each(function(index2){
if(visibleElementPos != null){
$(this).removeClass("show-out");
$(this).addClass("show-in");
return false;
}
if($(this).hasClass("show-in")){
$(this).removeClass("show-in");
$(this).addClass("show-out");
visibleElementPos = index2;
}
});
if(visibleElementPos == (presentationElements.length - 1)){
presentationElements.first().removeClass("show-out");
presentationElements.first().addClass("show-in");
}
}, settings.time);
});
return this;
};
}( jQuery ));
|
a75021c04aee04875733f34c4c43ac0070c96c0c
|
[
"JavaScript"
] | 3 |
JavaScript
|
jorgeac89/JQueryPlugins
|
2dddba34e3808f1b57d59c97ea6dba05161b48e8
|
acdd97d3ff1b18969813f080bb60631afc8e90b2
|
refs/heads/master
|
<file_sep>\name{eclat}
\alias{eclat}
\title{Mining Associations with Eclat}
\description{
Mine frequent itemsets with the Eclat algorithm.
This algorithm uses simple intersection operations for equivalence
class clustering along with bottom-up lattice traversal.
}
\usage{
eclat(data, parameter = NULL, control = NULL)
}
\arguments{
\item{data}{object of class
\code{\linkS4class{transactions}} or any data structure
which can be coerced into
\code{\linkS4class{transactions}} (e.g., binary
\code{matrix}, \code{data.frame}).}
\item{parameter}{object of class
\code{\linkS4class{ECparameter}} or named list (default
values are: support 0.1 and maxlen 5)}
\item{control}{object of class
\code{\linkS4class{ECcontrol}} or named list for
algorithmic controls.}
}
\details{
Calls the C implementation of the Eclat algorithm by Christian
Borgelt for mining frequent itemsets.
Note for control parameter \code{tidLists=TRUE}:
Since storing transaction ID lists is very memory intensive,
creating transaction ID lists only works for minimum
support values which create a relatively small number of itemsets.
See also \code{\link{supportingTransactions}}.
\code{\link{ruleInduction}} can be used to generate rules from the found itemsets.
A weighted version of ECLAT is available as function \code{\link{weclat}}.
This version can be used to perform weighted association rule mining (WARM).
}
\value{
Returns an object of class \code{\linkS4class{itemsets}}.
}
\references{
<NAME>, <NAME>, <NAME>, and <NAME>. (1997)
\emph{New algorithms for fast discovery of association rules}.
Technical Report 651, Computer Science Department, University of
Rochester, Rochester, NY 14627.
<NAME> (2003) Efficient Implementations of Apriori and
Eclat. \emph{Workshop of Frequent Item Set Mining Implementations}
(FIMI 2003, Melbourne, FL, USA).
ECLAT Implementation: \url{http://www.borgelt.net/eclat.html}
}
\seealso{
\code{\link{ECparameter-class}},
\code{\link{ECcontrol-class}},
\code{\link{transactions-class}},
\code{\link{itemsets-class}},
\code{\link{weclat}},
\code{\link{apriori}},
\code{\link{ruleInduction}},
\code{\link{supportingTransactions}}
}
\author{<NAME> and <NAME>}
\examples{
data("Adult")
## Mine itemsets with minimum support of 0.1 and 5 or less items
itemsets <- eclat(Adult,
parameter = list(supp = 0.1, maxlen = 5))
itemsets
## Create rules from the itemsets
rules <- ruleInduction(itemsets, Adult, confidence = .9)
rules
}
\keyword{models}
<file_sep>#######################################################################
# arules - Mining Association Rules and Frequent Itemsets
# Copyright (C) 2011-2015 <NAME>, <NAME>,
# <NAME> and <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
### discretize continuous variables
discretize <- function(x, method="interval", categories=3, labels=NULL,
ordered =FALSE, onlycuts = FALSE, ...) {
methods = c("interval", "frequency", "cluster", "fixed")
method <- methods[pmatch(tolower(method), methods)]
if(is.na(method)) stop("Unknown method!")
res <- switch(method,
interval = {
categories <- seq(from=min(x, na.rm=TRUE), to=max(x, na.rm=TRUE),
length.out=categories+1)
if(onlycuts) categories else .cut2(x, cuts=categories,
oneval=FALSE, ...)
},
frequency = .cut2(x, g=categories, onlycuts=onlycuts, ...),
cluster = {
cl <- stats::kmeans(stats::na.omit(x), categories, ...)
centers <- sort(cl$centers[,1])
categories <- as.numeric(c(min(x, na.rm=TRUE), head(centers,
length(centers)-1) + diff(centers)/2, max(x, na.rm=TRUE)))
if(onlycuts) categories else .cut2(x, cuts=categories, ...)
},
fixed = {
x[x<min(categories) | x>max(categories)] <- NA
if(onlycuts) categories else .cut2(x, cuts=categories, ...)
}
)
if(onlycuts) return(res)
if(ordered) res <- as.ordered(res)
if(!is.null(labels)) levels(res) <- labels
res
}
<file_sep>#######################################################################
# arules - Mining Association Rules and Frequent Itemsets
# Copyright (C) 2011-2015 <NAME>, <NAME>,
# <NAME> and <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
##*******************************************************
## Function inspect
##
## print informations for associations and transactions
setMethod("inspect", signature(x = "itemsets"),
function(x, itemSep = ",", setStart = "{", setEnd = "}", linebreak = NULL,
...) {
n_of_itemsets <- length(x)
if(n_of_itemsets == 0) return(invisible(NULL))
## Nothing to inspect here ...
l <- labels(x, itemSep, setStart, setEnd)
if(is.null(linebreak))
linebreak <- any(nchar(l) > options("width")$width*2/3)
if(!linebreak) {
out <- data.frame(items = l)
if(nrow(quality(x)) > 0) out <- cbind(out, quality(x))
rownames(out) <- paste0('[', 1:n_of_itemsets, ']')
print(out, right = FALSE)
} else {
## number of rows + fix empty itemsets
items <- unlist(lapply(as(items(x), "list"),
FUN = function(x) if(length(x) == 0) "" else x))
n_of_items <- size(items(x))
n_of_items[n_of_items == 0] <- 1
## calculate begin and end positions
entry_beg_pos <- cumsum(c(1, n_of_items[-n_of_itemsets]))
entry_end_pos <- entry_beg_pos+n_of_items-1
## prepare output
n_of_rows <- sum(n_of_items)
quality <- quality(x)
## Output.
out <- matrix("", nrow = n_of_rows+1, ncol = 2 + NCOL(quality))
## Column 1: itemset nr.
tmp <- rep.int("", n_of_rows + 1)
tmp[entry_beg_pos+1] <- paste0('[', 1:n_of_itemsets, ']')
out[,1] <- format(tmp)
## Column 2: items in the item sets, one per line.
pre <- rep.int(" ", n_of_rows)
pre[entry_beg_pos] <- rep.int(setStart, length(entry_beg_pos))
post <- rep.int(itemSep, n_of_rows)
post[entry_end_pos] <- rep.int(setEnd, length(entry_end_pos))
out[, 2] <- format(c("items",
paste(pre, unlist(items), post, sep = "")))
## Remaining columns: quality measures.
for(i in seq(length = NCOL(quality))) {
tmp <- rep.int("", n_of_rows + 1)
tmp[1] <- names(quality)[i]
tmp[entry_end_pos + 1] <- format(quality[[i]])
out[, i + 2] <- format(tmp, justify = "right")
}
## Output.
cat(t(out), sep = c(rep.int(" ", NCOL(out) - 1), "\n"))
}
})
setMethod("inspect", signature(x = "rules"),
function(x, itemSep = ",", setStart = "{", setEnd = "}", ruleSep = "=>",
linebreak = NULL, ...) {
n_of_rules <- length(x)
if(n_of_rules == 0) return(invisible(NULL))
## Nothing to inspect here ...
lhs <- labels(lhs(x), itemSep, setStart, setEnd)
rhs <- labels(rhs(x), itemSep, setStart, setEnd)
if(is.null(linebreak))
linebreak <- any(nchar(lhs)+nchar(rhs)+nchar(ruleSep) >
options("width")$width*2/3)
if(!linebreak) {
out <- data.frame(lhs = lhs, "." = ruleSep, rhs = rhs)
if(nrow(quality(x)) > 0) out <- cbind(out, quality(x))
colnames(out)[2] <- ""
rownames(out) <- paste0('[', 1:n_of_rules, ']')
print(out, right = FALSE)
} else {
items_lhs <- as(lhs(x), "list")
items_rhs <- as(rhs(x), "list")
### Empty RHS!
items_rhs <- lapply(items_rhs, FUN = function(r)
if(length(r)==0) "" else r
)
quality <- quality(x)
## Rewrite empty LHSs.
ind <- sapply(items_lhs, length) == 0
if(any(ind)) items_lhs[ind] <- ""
## Various lengths ...
n_of_items_lhs <- sapply(items_lhs, length)
n_of_items_rhs <- sapply(items_rhs, length)
entry_end_pos <- cumsum(n_of_items_lhs + n_of_items_rhs - 1) + 1
entry_beg_pos <- c(1, entry_end_pos[-n_of_rules]) + 1
entry_mid_pos <- entry_beg_pos + n_of_items_lhs - 1
lhs_pos <- unlist(mapply(seq, entry_beg_pos, entry_mid_pos,
SIMPLIFY = FALSE))
rhs_pos <- unlist(mapply(seq, entry_mid_pos, entry_end_pos,
SIMPLIFY = FALSE))
n_of_rows <- entry_end_pos[n_of_rules]
out <- matrix("", nrow = n_of_rows, ncol = 4 + NCOL(quality))
## Column 1: Rule number
tmp <- rep.int("", n_of_rows)
tmp[entry_beg_pos] <- paste0('[', 1:n_of_rules, ']')
out[, 1] <- format(tmp)
## Column 2: lhs.
pre <- rep.int(" ", n_of_rows)
pre[entry_beg_pos] <- setStart
post <- rep.int("", n_of_rows)
post[lhs_pos] <- itemSep
post[entry_mid_pos] <- setEnd
tmp <- rep.int("", n_of_rows)
tmp[lhs_pos] <- unlist(items_lhs)
out[, 2] <-
format(c("lhs", paste(pre, tmp, post, sep = "")[-1]))
## Column 3: '=>'
tmp <- rep.int("", n_of_rows)
tmp[entry_mid_pos] <- ruleSep
out[, 3] <- format(tmp)
## Column 4: rhs.
pre <- rep.int(" ", n_of_rows)
pre[entry_mid_pos] <- setStart
post <- rep.int("", n_of_rows)
post[rhs_pos] <- itemSep
post[entry_end_pos] <- setEnd
tmp <- rep.int("", n_of_rows)
tmp[rhs_pos] <- unlist(items_rhs)
out[, 4] <-
format(c("rhs", paste(pre, tmp, post, sep = "")[-1]))
## Remaining columns: quality measures.
for(i in seq(length = NCOL(quality))) {
tmp <- rep.int("", n_of_rows)
tmp[1] <- names(quality)[i]
tmp[entry_end_pos] <- format(quality[[i]])
out[, i + 4] <- format(tmp, justify = "right")
}
## Output.
cat(t(out), sep = c(rep.int(" ", NCOL(out) - 1), "\n"))
}
})
setMethod("inspect", signature(x = "transactions"),
function(x, itemSep = ",", setStart = "{", setEnd = "}", linebreak = NULL,
...) {
n_of_itemsets <- length(x)
if(n_of_itemsets == 0) return(invisible(NULL))
## Nothing to inspect here ...
l <- labels(x, itemSep, setStart, setEnd)
if(is.null(linebreak))
linebreak <- any(nchar(l) > options("width")$width*2/3)
if(!linebreak) {
out <- data.frame(items = l)
if(nrow(transactionInfo(x)) > 0)
out <- cbind(out, transactionInfo(x))
rownames(out) <- paste0('[', 1:n_of_itemsets, ']')
print(out, right = FALSE)
} else {
## number of rows + fix empty itemsets
items <- unlist(lapply(as(x, "list"),
FUN = function(x) if(length(x) == 0) "" else x))
n_of_items <- size(x)
n_of_items[n_of_items == 0] <- 1
## calculate begin and end positions
entry_beg_pos <- cumsum(c(1, n_of_items[-n_of_itemsets]))
entry_end_pos <- entry_beg_pos+n_of_items-1
## prepare output
n_of_rows <- sum(n_of_items)
transactionInfo <- transactionInfo(x)
## Output.
out <- matrix("", nrow = n_of_rows+1, ncol = 2 + NCOL(transactionInfo))
## Column 1: itemset nr.
tmp <- rep.int("", n_of_rows + 1)
tmp[entry_beg_pos+1] <- paste0('[', 1:n_of_itemsets, ']')
out[,1] <- format(tmp)
## Column 2: items in the item sets, one per line.
pre <- rep.int(" ", n_of_rows)
pre[entry_beg_pos] <- rep.int(setStart, length(entry_beg_pos))
post <- rep.int(itemSep, n_of_rows)
post[entry_end_pos] <- rep.int(setEnd, length(entry_end_pos))
out[, 2] <- format(c("items",
paste(pre, unlist(items), post, sep = "")))
## Remaining columns: transactionInfo.
for(i in seq(length = NCOL(transactionInfo))) {
tmp <- rep.int("", n_of_rows + 1)
tmp[1] <- names(transactionInfo)[i]
tmp[entry_end_pos + 1] <- format(transactionInfo[[i]])
out[, i + 2] <- format(tmp, justify = "right")
}
## Output.
cat(t(out), sep = c(rep.int(" ", NCOL(out) - 1), "\n"))
}
})
setMethod("inspect", signature(x = "itemMatrix"),
function(x, itemSep = ",", setStart = "{", setEnd = "}", linebreak = NULL,
...) {
n_of_itemsets <- length(x)
if(n_of_itemsets == 0) return(invisible(NULL))
## Nothing to inspect here ...
l <- labels(x, itemSep, setStart, setEnd)
if(is.null(linebreak))
linebreak <- any(nchar(l) > options("width")$width*2/3)
if(!linebreak) {
out <- data.frame(items = l)
rownames(out) <- paste0('[', 1:n_of_itemsets, ']')
print(out, right = FALSE)
} else {
items <- unlist(lapply(as(x, "list"),
FUN = function(x) if(length(x) == 0) "" else x))
n_of_items <- size(x)
n_of_items[n_of_items == 0] <- 1
## calculate begin and end positions
entry_beg_pos <- cumsum(c(1, n_of_items[-n_of_itemsets]))
entry_end_pos <- entry_beg_pos+n_of_items-1
## prepare output
n_of_rows <- sum(n_of_items)
## Output.
out <- matrix("", nrow = n_of_rows+1, ncol = 2)
## Column 1: itemset nr.
tmp <- rep.int("", n_of_rows + 1)
tmp[entry_beg_pos+1] <- paste0('[', 1:n_of_itemsets, ']')
out[,1] <- format(tmp)
## Column 2: items in the item sets, one per line.
pre <- rep.int(" ", n_of_rows)
pre[entry_beg_pos] <- rep.int(setStart, length(entry_beg_pos))
post <- rep.int(itemSep, n_of_rows)
post[entry_end_pos] <- rep.int(setEnd, length(entry_end_pos))
out[, 2] <- format(c("items",
paste(pre, unlist(items), post, sep = "")))
## Output.
cat(t(out), sep = c(rep.int(" ", NCOL(out) - 1), "\n"))
}
})
## tidLists are easy so we use sprintf
setMethod("inspect", signature(x = "tidLists"),
function(x, ...) {
print(data.frame(items = itemLabels(x), transationIDs = labels(x),
row.names = NULL), right = FALSE)
}
)
<file_sep>\name{discretize}
\alias{discretize}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{Convert a Continuous Variable into a Categorical Variable}
\description{
This function implements several basic unsupervized methods to convert continuous variables into a categorical variables (factor) suitable for association rule mining.
}
\usage{
discretize(x, method="interval", categories = 3, labels = NULL,
ordered=FALSE, onlycuts=FALSE, ...)
}
\arguments{
\item{x}{a numeric vector (continuous variable).}
\item{method}{ discretization method. Available are: "interval" (equal interval width), "frequency" (equal frequency), "cluster" (k-means clustering) and
"fixed" (categories specifies interval boundaries).}
\item{categories}{ number of categories or a vector with boundaries
(all values outside the boundaries will be set to NA). }
\item{labels}{ character vector; names for categories.}
\item{ordered}{ logical; return a factor with ordered levels? }
\item{onlycuts}{ logical; return only computed interval boundaries? }
\item{\dots}{for method "cluster" further arguments are passed on to
\code{kmeans}. }.
}
\details{
\code{discretize} only implements unsupervised discretization. See packages \pkg{discretization} or \pkg{RWeka} for supervised discretization.
}
\value{
%% ~Describe the value returned
%% If it is a LIST, use
%% \item{comp1 }{Description of 'comp1'}
%% \item{comp2 }{Description of 'comp2'}
%% ...
A factor representing the categorized continuous variable or, if
\code{onlycuts=TRUE}, a vector with the interval boundaries.
}
%\references{
%}
%\seealso{
%}
\examples{
data(iris)
x <- iris[,4]
hist(x, breaks=20, main="Data")
def.par <- par(no.readonly = TRUE) # save default
layout(mat=rbind(1:2,3:4))
### convert continuous variables into categories (there are 3 types of flowers)
### default is equal interval width
table(discretize(x, categories=3))
hist(x, breaks=20, main="Equal Interval length")
abline(v=discretize(x, categories=3, onlycuts=TRUE),
col="red")
### equal frequency
table(discretize(x, "frequency", categories=3))
hist(x, breaks=20, main="Equal Frequency")
abline(v=discretize(x, method="frequency", categories=3, onlycuts=TRUE),
col="red")
### k-means clustering
table(discretize(x, "cluster", categories=3))
hist(x, breaks=20, main="K-Means")
abline(v=discretize(x, method="cluster", categories=3, onlycuts=TRUE),
col="red")
### user-specified
table(discretize(x, "fixed", categories = c(-Inf,.8,Inf)))
table(discretize(x, "fixed", categories = c(-Inf,.8, Inf),
labels=c("small", "large")))
hist(x, breaks=20, main="Fixed")
abline(v=discretize(x, method="fixed", categories = c(-Inf,.8,Inf),
onlycuts=TRUE), col="red")
par(def.par) # reset to default
### prepare the iris data set for association rule mining
for(i in 1:4) iris[,i] <- discretize(iris[,i], "frequency", categories=3)
trans <- as(iris, "transactions")
inspect(head(trans, 1))
as(head(trans, 3),"matrix")
}
\author{<NAME>}
\keyword{manip}
<file_sep>\name{is.redundant}
\alias{is.redundant}
\alias{is.redundant,rules-method}
%
%
\title{Find Redundant Rules}
\description{
Provides the generic functions and the S4 method \code{is.redundant}
to find redundant rules.
}
\usage{
is.redundant(x, ...)
\S4method{is.redundant}{rules}(x, measure = "confidence")
}
\arguments{
\item{x}{ a set of rules.}
\item{measure}{ measure used to check for redundancy. }
\item{...}{ additional arguments. }
}
\details{
A rule is redundant if a more general rules with the same or a higher
confidence exists.
That is, a more specific rule is redundant if it is only equally or even less
predictive than a more general rule. A rule is more general if it has
the same RHS but one or more items removed from the LHS. Formally,
a rule \eqn{X \Rightarrow Y}{X -> Y} is redundant if
\deqn{\exists X' \subset X \quad conf(X' \Rightarrow Y) \ge conf(X \Rightarrow Y).}{
for some X' subset X, conf(X' -> Y) >= conf(X -> Y).}
This is equivalent to a
negative or zero \emph{improvement} as defined by Bayardo et al. (2000).
In this implementation other measures than confidence, e.g.
improvement of lift, can be used as well.
}
\value{
returns a logical vector indicating which rules are redundant.
}
\seealso{
\code{\link{interestMeasure}}
}
\references{
<NAME>. , <NAME>, and <NAME> (2000). Constraint-based rule mining in large, dense databases. \emph{Data Mining and Knowledge Discovery,} 4(2/3):217--240.
}
\examples{
data("Income")
## mine some rules with the consequent "language in home=english"
rules <- apriori(Income, parameter = list(support = 0.5),
appearance = list(rhs = "language in home=english", default = "lhs"))
## for better comparison we sort the rules by confidence and add Bayado's improvement
rules <- sort(rules, by = "confidence")
quality(rules)$improvement <- interestMeasure(rules, measure = "improvement")
inspect(rules)
is.redundant(rules)
## redundant rules
inspect(rules[is.redundant(rules)])
## non-redundant rules
inspect(rules[!is.redundant(rules)])
}
\author{<NAME> and <NAME>}
\keyword{manip}
<file_sep>## FIXME: missing tests
## * itemCoding
## * aggregate
## * discretize
## * dissimilarity
## * pmml
## * predict
## * supportingTransactions
|
187337b1f53c771c1537f2dc3b5c6dde99519b02
|
[
"R"
] | 6 |
R
|
lgallindo/arules
|
887184cd80068e04531b0c13bc231ecbd1afddfb
|
8da9dabe54a7351afa3e7bec12c0c11bbc9de741
|
refs/heads/master
|
<repo_name>reciosonny/news-feed-eradicator<file_sep>/src/lib/is-enabled.ts
const paths = ['', '/'];
export default function isEnabled() {
return paths.indexOf(window.location.pathname) > -1;
}
<file_sep>/src/eradicate.ts
// Include the stylesheets
import './eradicate.css';
import * as FbClassic from './sites/fb-classic';
import * as Fb2020 from './sites/fb-2020';
// Determine which variant we're working with
if (FbClassic.checkSite()) {
FbClassic.eradicate();
} else {
Fb2020.eradicate();
}
|
e03ad7e19cf9a929c04c1979fa6917b5d90364b1
|
[
"TypeScript"
] | 2 |
TypeScript
|
reciosonny/news-feed-eradicator
|
fb285d15078cd019f9dc0455ffae4db5b5aa66c4
|
d11322b390834dbe7136175f1f28452baae6291d
|
refs/heads/master
|
<repo_name>VartikaToTheNew/Forager<file_sep>/src/main/java/com/ttnd/forager/dao/impl/SampleDaoImpl.java
package com.ttnd.forager.dao.impl;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.ttnd.forager.dao.SampleDao;
import com.ttnd.forager.entites.Greeting;
@Repository
public class SampleDaoImpl implements SampleDao{
EntityManager entityManager;
// @PersistenceContext
// public void setEntityManager(EntityManager entityManager) {
// this.entityManager = entityManager;
// }
public void saveUser(Greeting user) {
// System.out.println("Saving the user....");
// entityManager.persist(user);
// System.out.println("User saved");
}
}
|
fb01542614fe68b7611cbf80ff358d4cd19daf7d
|
[
"Java"
] | 1 |
Java
|
VartikaToTheNew/Forager
|
557c3c465b74cb2f821ecdb36bc444c8d81123b3
|
a968654040f851059396eb5bcf1c5ecbcc05710e
|
refs/heads/master
|
<file_sep>const path = require("path");
const { readFileAsync } = require("./readFileAsync");
const { isDescriptionLine, isParamLine, isReturnLine } = require("./identify");
const {
normalizeDescription,
normalizeMethod,
normalizeReturn,
normalizeParam,
} = require("./normalizers");
const getLines = async (filename) => {
const fileContent = await readFileAsync(filename);
return fileContent.split("\n");
};
const getTokens = (lines) => {
let hash = {};
return lines.reduce((tokens, line, i) => {
if (isDescriptionLine(lines[i - 1])) {
hash = {};
hash.description = normalizeDescription(lines[i - 1]);
}
if (isParamLine(line)) {
const param = normalizeParam(line);
hash.params = hash.params || [];
hash.params.push(param);
} else if (isReturnLine(line)) {
hash["return"] = normalizeReturn(line);
hash["method"] = normalizeMethod(lines[i + 1]);
tokens.push(hash);
}
return tokens;
}, []);
};
const sort = (items) => {
const toLowerCase = (obj) => obj.method.toLowerCase();
return [...items].sort((_a, _b) => {
const a = toLowerCase(_a);
const b = toLowerCase(_b);
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
});
};
const parseFile = async (filename, shouldSort) => {
const lines = await getLines(filename);
const items = getTokens(lines);
return {
object: path.basename(filename, path.extname(filename)),
items: shouldSort ? sort(items) : items,
};
};
module.exports = {
parseFile,
};
<file_sep>const fs = require("fs");
const readFileAsync = async (filename) => {
const fileData = await fs.promises.readFile(filename, "utf8");
return fileData;
};
const writeFileAsync = (data) => {
return fs.promises.writeFile("./doc.html", data);
};
module.exports = {
readFileAsync,
writeFileAsync,
};
<file_sep>const normalizeDescription = value => value.replace(/^\s+-{2}\s+/, '');
const normalizeMethod = value => value.match(/\s+(\w+)/)[1];
const normalizeReturn = value => value.match(/{(.*?)}/)[1];
const normalizeParam = value =>
value
.match(/\w+\s+{.*}/)
.pop()
.replace(/\s+{/, ':')
.slice(0, -1);
module.exports = {
normalizeDescription,
normalizeMethod,
normalizeReturn,
normalizeParam,
};
<file_sep>const validation = (param, value) => new RegExp(`^\\s+-{2}\\s+${param}`).test(value);
const isDescriptionLine = line => validation("[^@]", line);
const isParamLine = line => validation("@param", line);
const isReturnLine = line => validation("@return", line);
module.exports = {
isDescriptionLine,
isParamLine,
isReturnLine
};
<file_sep>const Handlebars = require("handlebars");
const { readFileAsync, writeFileAsync } = require("./readFileAsync");
const buildHtml = (tpl, data) => {
const template = Handlebars.compile(tpl);
return template(data);
};
const generatePage = async (data) => {
const tpl = await readFileAsync("./lib/template.html");
const html = buildHtml(tpl, data);
await writeFileAsync(html);
};
module.exports = {
generatePage,
};
<file_sep>#!/usr/bin/env node
const { parseFile } = require("./lib/parseFile");
const { generatePage } = require("./lib/generatePage");
(async () => {
const filename = process.argv[2];
const data = await parseFile(filename, true);
console.log(await generatePage(data));
})();
|
ff033b761fe2dad6ea05f7c405e905eb6770fb33
|
[
"JavaScript"
] | 6 |
JavaScript
|
EvandroLG/luaDoc
|
33089ae1b2904becc02a524a74870b49d6881492
|
1e66f8b3fe91f2de204e20762cde2583c927e34d
|
refs/heads/master
|
<repo_name>hammmay/JS-Flashcards<file_sep>/js/scripts.js
$(document).ready(function() {
$(".card").click(function() {
$(this).find(".front").toggleClass("hidden");
$(this).find(".back").toggleClass("hidden");
});
});
|
09a2a6f7777eea9c67cff7342e5f7069f0c48675
|
[
"JavaScript"
] | 1 |
JavaScript
|
hammmay/JS-Flashcards
|
8cb288f0a4379404f063e978ca415b80ad56a931
|
ecd79d748b8aa344519c22fc04a3713d36fcb733
|
refs/heads/master
|
<file_sep>#-------------------------------------------------------------------------------
# Name: grafica
#
# Author: <NAME>
#
# Proyecto: CRUD con interfaz Tkinter
# Created: 14/10/2019
# Copyright: (c) Juan 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from funciones import *
from tkinter import messagebox
from tkinter.tix import *
from matplotlib import pyplot
cont=1 ## Variable para incrementar código automaticamente
objListas = ListaLigada()
## -------------------------------FUNCIONES-------------------------------------
def guardar():
global cont
codigo = cont
nombre = txtNombre.get()
edad = txtEdad.get()
if(nombre != "" and edad!=""):
if (edad.isnumeric()):
objListas.agregarAlFinal(codigo, nombre, edad) ## Asignando datos a la lista
txtNombre.delete(0, 'end') ## Vaciando campos
txtEdad.delete(0, 'end')
txtNombre.focus() ## Enfocando cursor en input especifico
cont +=1
txtCodigo.config(state='normal') ## Hablitando campo de texto
edadPromedio = objListas.edadPromedio()
lblTituloEdad = Label(window, text="EDAD PROMEDIO: ", ## Creando label Titulo Edad promedio
font=("Bahnschrift Light Condensed", 18),bg="#151f29", fg="#fff71d")
lblTituloEdad.place(x=140, y=525)
lblEdadPromedio.config(text=edadPromedio)
lblDatos.config(state='normal') ## Hablitando labels
lblCodigoDatos.config(state='normal')
lblNombreDatos.config(state='normal')
lblEdadDatos.config(state='normal')
btnConsultar.config(state='normal', cursor="hand2") ## Hablitando botones
btnModificar.config(state='normal', cursor="hand2")
btnEliminar.config(state='normal', cursor="hand2")
arr = objListas.listar()
item = Text(window, width=40,height=10,bg="#0b2239", ## Creando Table de datos
font=("Bahnschrift Light Condensed", 13), fg="white")
item.place(x=40, y=310)
for i in range(len(arr)):
item.insert(INSERT, " " + str(arr[i][0]) + " " + str(arr[i][1]) + " " + str(arr[i][2]) + "\n")
item.insert(INSERT, "_______________________________________________________")
messagebox.showinfo('EXITO', 'Registro Guardado') ## Mensaje de exito
x1 = []
y1 = []
for i in range(len(arr)):
x1.append("("+ str(arr[i][0]) + ")")
y1.append(int(arr[i][2]))
pyplot.bar(x1, y1, label='Edades', width=0.5, color='orange')
pyplot.title("")
pyplot.ylabel("Edad")
pyplot.xlabel("Código")
pyplot.show()
else:
messagebox.showerror('ERROR', 'Edad no es correcta')
txtEdad.delete(0, 'end')
txtEdad.focus()
else:
messagebox.showerror('ERROR', 'Llene los campos')
if txtCodigo.get() == "":
txtCodigo.focus()
elif txtNombre.get() == "":
txtNombre.focus()
elif txtEdad.get() == "":
txtEdad.focus()
def consultar():
codigo = txtCodigo.get()
if (codigo != ""):
txtCodigo.delete(0,'end')
txtNombre.delete(0,'end')
txtEdad.delete(0,'end')
codigo = int(codigo)
sw = objListas.consultar(codigo)
if (sw!=False):
txtCodigo.insert(0, codigo)
txtNombre.insert(0, sw[0])
txtEdad.insert(0, sw[1])
else:
txtCodigo.insert(0, codigo)
messagebox.showerror("Error", "El usuario no existe.",icon="warning")
else:
messagebox.showerror("Error", "Introduzca el código a consultar.",icon="error")
txtCodigo.focus()
def modificar():
codigo = txtCodigo.get()
nombre = txtNombre.get()
edad = txtEdad.get()
if (codigo != "" and nombre != "" and edad!=""):
if (edad.isnumeric()):
codigo = int(codigo)
sw = objListas.modificar(codigo,nombre,edad)
if (sw!=False):
edadPromedio = objListas.edadPromedio()
lblTituloEdad = Label(window, text="EDAD PROMEDIO: ", ## Creando label Titulo Edad promedio
font=("Bahnschrift Light Condensed", 18),bg="#151f29",
fg="#fff71d")
lblTituloEdad.place(x=140, y=525)
lblEdadPromedio.config(text=edadPromedio)
arr = objListas.listar()
item = Text(window, width=40,height=10,bg="#0b2239", ## Creando Table de datos
font=("Bahnschrift Light Condensed", 13), fg="white")
item.place(x=40, y=310)
for i in range(len(arr)):
item.insert(INSERT, " " + str(arr[i][0]) + " " + str(arr[i][1]) + " " + str(arr[i][2]) + "\n")
item.insert(INSERT, "_______________________________________________________")
messagebox.showinfo("Información","Usuario modificado.",icon="info")
x1 = []
y1 = []
for i in range(len(arr)):
x1.append("(" + str(arr[i][0]) + ")")
y1.append(int(arr[i][2]))
pyplot.bar(x1, y1, label='Edades', width=0.5, color='orange')
pyplot.title("")
pyplot.ylabel("Edad")
pyplot.xlabel("Código")
pyplot.show()
else:
txtCodigo.insert(0, codigo)
messagebox.showerror("Error", "El usuario no existe.",icon="warning")
else:
messagebox.showerror('ERROR', 'Edad no es correcta')
txtEdad.delete(0, 'end')
txtEdad.focus()
else:
messagebox.showerror("Error", "Complete todos los campos.",icon="error");
if txtCodigo.get() == "":
txtCodigo.focus()
elif txtNombre.get() == "":
txtNombre.focus()
elif txtEdad.get() == "":
txtEdad.focus()
def eliminar():
codigo = txtCodigo.get()
if len(codigo) != 0:
codigo = int(codigo)
sw = objListas.eliminar(codigo) ## Retorna un boleano si lo eliminó o no
if (sw):
edadPromedio = objListas.edadPromedio()
lblTituloEdad = Label(window, text="EDAD PROMEDIO: ", ## Creando label Titulo Edad promedio
font=("Bahnschrift Light Condensed", 18),bg="#151f29",
fg="#fff71d")
lblTituloEdad.place(x=140, y=525)
lblEdadPromedio.config(text=edadPromedio)
arr = objListas.listar()
item = Text(window, width=40,height=10,bg="#0b2239", ## Creando Table de datos
font=("Bahnschrift Light Condensed", 13), fg="white")
item.place(x=40, y=310)
for i in range(len(arr)):
item.insert(INSERT, " " + str(arr[i][0]) + " " + str(arr[i][1]) + " " + str(arr[i][2]) + "\n")
item.insert(INSERT, "_______________________________________________________")
messagebox.showinfo("Información","Usuario borrado.",icon="info")
x1 = []
y1 = []
for i in range(len(arr)):
x1.append("("+ str(arr[i][0]) + ")")
y1.append(int(arr[i][2]))
pyplot.bar(x1, y1, label='Edades', width=0.5, color='orange')
pyplot.title("")
pyplot.ylabel("Edad")
pyplot.xlabel("Código")
pyplot.show()
txtCodigo.delete(0, 'end')
txtNombre.delete(0, 'end')
txtEdad.delete(0, 'end')
txtCodigo.focus()
else:
messagebox.showerror("Error", "El usuario no existe.",icon="warning")
else:
messagebox.showerror("Error", "Introduzca el código del usuario a eliminar.",icon="error")
txtCodigo.focus()
##-----------------------------GRAFICA------------------------------------------
window = Tk()
window.tk.call('wm', 'resizable', window._w, False, False)
window.iconbitmap("search.ico")
window.title("Formulario")
window.configure(background="#151f29")
window.geometry('370x570+350+80') ##(ancho x altura + EjeX + EjeY)
lblTitulo = Label(window, text="FORMULARIO", font=("Bahnschrift SemiBold Condensed", 40), fg="#50e6ff",bg="#151f29")
lblTitulo.grid(row=0, column=1)
## CODIGO(lbl, txt)
lblCodigo = Label(window, text="Codigo:" ,font=("Bahnschrift Light Condensed", 18), fg="#ff9349",bg="#151f29")
lblCodigo.grid(row=1, column=0)
txtCodigo = Entry(window,width=25, bg="#0b2239",borderwidth = 1, fg="white",font=("Bahnschrift Light Condensed", 13),state='disable')
txtCodigo.grid(row=1, column=1)
## NOMBRE(lbl, txt)
lblNombre = Label(window, text="Nombre:", font=("Bahnschrift Light Condensed", 18), fg="#ff9349",bg="#151f29",anchor="center")
lblNombre.grid(row=2, column=0,sticky="NW")
txtNombre = Entry(window,width=25,bg="#0b2239",borderwidth = 1,fg="white", font=("Bahnschrift Light Condensed", 13))
txtNombre.grid(row=2, column=1)
txtNombre.focus()
## EDAD(lbl, txt)
lblEdad = Label(window, text="Edad:", font=("Bahnschrift Light Condensed", 18), fg="#ff9349",bg="#151f29")
lblEdad.grid(row=3, column=0)
txtEdad = Entry(window,width=25,bg="#0b2239",borderwidth = 1,fg="white",font=("Bahnschrift Light Condensed", 13))
txtEdad.grid(row=3, column=1)
## ESPACIO
lblEspacio = Label(window, text="", font=("Bahnschrift Light Condensed", 18),bg="#151f29")
lblEspacio.grid(row=4, column=0)
## ESPACIO
lblEspacio = Label(window, text="", font=("Bahnschrift Light Condensed", 18),bg="#151f29")
lblEspacio.grid(row=5, column=0)
## BOTON GUARDAR
btnGuardar = Button(window, text="Guardar", bg="#42c146", fg="white", cursor="hand2", relief=RIDGE ,command=guardar)
btnGuardar.place(x=30, y=195)
## BOTON CONSULTAR,
btnConsultar= Button(window, text="Consultar", bg="#151f29", fg="white",relief=RIDGE, state='disable', command=consultar)
btnConsultar.place(x=100, y=195)
## BOTON MODIFICAR
btnModificar = Button(window, text="Modificar", bg="#151f29", fg="white",relief=RIDGE, state='disable', command=modificar)
btnModificar.place(x=180, y=195)
## BOTON ELIMINAR
btnEliminar= Button(window, text="Eliminar", bg="#e3220f", fg="white", relief=RIDGE,command=eliminar, state='disable')
btnEliminar.place(x=260, y=195)
## TITULO DATOS
lblDatos = Label(window, text="DATOS", font=("Bahnschrift Light Condensed", 18),fg="#50e6ff",bg="#151f29", state='disable')
lblDatos.grid(row=6, column=1)
## TITULO CODIGO DATOS
lblCodigoDatos = Label(window, text="CÓDIGO", font=("Bahnschrift Light Condensed", 15),fg="#ff9349",bg="#151f29", state='disable')
lblCodigoDatos.place(x=60, y=278)
## TITULO NOMBRE DATOS
lblNombreDatos = Label(window, text="NOMBRE", font=("Bahnschrift Light Condensed", 15),fg="#ff9349",bg="#151f29", state='disable')
lblNombreDatos.place(x=156, y=278)
## TITULO EDAD DATOS
lblEdadDatos = Label(window, text="EDAD", font=("Bahnschrift Light Condensed", 15),fg="#ff9349",bg="#151f29", state='disable')
lblEdadDatos.place(x=250, y=278)
## EDAD PROMEDIO
lblEdadPromedio = Label(window, text="",font=("Bahnschrift Light Condensed", 18),bg="#151f29",fg="white")
lblEdadPromedio.place(x=285, y=525)
## MOSTRAR LA VENTANA
window.mainloop()<file_sep>#-------------------------------------------------------------------------------
# Name: funciones
#
# Author: <NAME>
#
# Proyecto: CRUD con interfaz Tkinter
# Created: 14/10/2019
# Copyright: (c) Juan 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
class Nodo:
def __init__(self, codigo, nombre, edad, siguiente):
self.codigo = codigo
self.nombre = nombre
self.edad = edad
self.siguiente = siguiente
class ListaLigada:
def __init__(self):
self.cabeza = None
## AGREGANDO NODO AL FINAL
def agregarAlFinal(self, codigo, nombre, edad):
if self.cabeza==None:
self.cabeza = Nodo(codigo, nombre, edad,None)
else:
actual = self.cabeza
while actual.siguiente != None:
actual = actual.siguiente
actual.siguiente = Nodo(codigo, nombre, edad,None)
## CONTADOR CANTIDAD DE NODOS
def contarNodos(self):
contador = 0
if self.cabeza==None:
return contador
else:
actual = self.cabeza
while actual != None:
actual = actual.siguiente
contador+=1
return contador
## IMPRIMIR LISTA
def mostrarLista(self):
actual = self.cabeza
while actual != None:
print(actual.codigo, actual.nombre, actual.edad, end =" => ")
actual = actual.siguiente
## MATRIZ CON NODOS DE LA LISTA
def listar(self):
mat=[]
n = self.contarNodos()
actual = self.cabeza
for i in range(n):
mat.append([])
mat[i].append(actual.codigo)
mat[i].append(actual.nombre)
mat[i].append(actual.edad)
actual = actual.siguiente
return mat
## ELMINAR NODO
def eliminar(self,cod):
if self.cabeza != None:
actual = self.cabeza
anterior = actual
## ELIMINANDO PRIMER DATO
if cod == actual.codigo:
self.cabeza = actual.siguiente
sw = True
return sw
else:
sw = True
while actual != None:
if cod == actual.codigo:
anterior.siguiente = actual.siguiente
sw = True
break
else:
sw = False
anterior = actual
actual = actual.siguiente
return sw
else:
sw = False
return sw
## BUSQUEDA
def consultar(self,cod):
if self.cabeza != None:
n = self.contarNodos()
n = int(n)
actual = self.cabeza
for i in range(n):
if cod == actual.codigo:
sw = []
sw.append(actual.nombre)
sw.append(actual.edad)
break
else:
sw = False
actual = actual.siguiente
return sw
else:
sw = False
return sw
## MODIFICAR
def modificar(self,cod, nombre, edad):
if self.consultar(cod)!= False:
actual = self.cabeza
while cod != actual.codigo:
actual = actual.siguiente
actual.nombre = nombre
actual.edad = edad
else:
sw = False
return sw
## PROMEDIO EDAD
def edadPromedio(self):
if self.cabeza != None:
edades = 0
promedio = 0
cantidad = self.contarNodos()
cantidad = int(cantidad)
actual = self.cabeza
for i in range(cantidad):
edades = edades + int(actual.edad)
actual = actual.siguiente
promedio = edades/cantidad
promedio = int(promedio)
return promedio
else:
promedio = 0
return promedio
def rangoEdades(self):
if self.cabeza != None:
cantEdades010 = 0
cantEdades1020 = 0
cantEdades2030 = 0
cantEdades4050 = 0
cantEdades6070 = 0
cantEdades8090 = 0
cantEdades90100 = 0
cantidad = self.contarNodos()
cantidad = int(cantidad)
actual = self.cabeza
while actual != None:
edades = edades + int(actual.edad)
actual = actual.siguiente
promedio = edades/cantidad
promedio = int(promedio)
return promedio
else:
promedio = 0
return promedio
|
b2b276cfc6697270e387e0d15813870a4ff7541d
|
[
"Python"
] | 2 |
Python
|
jdhl27/CRUD-Python
|
f074cfa4537571134f5da7f53c58f341256a7b0d
|
694aa26a3dc53c046470a26d24cfcf3c222cb95d
|
refs/heads/master
|
<file_sep>Salón de la fama de OMIBC
=========================
TODO:
1. Definir razones de por que hacer todo vainilla
1. Simplicidad de capacitación
2. Curiosidad técnica a quien decida llevar a cabo cosas elegantes
3. Simplicidad de mantenimiento
## Configuración de API Google Spread sheets
1. Instalar python
1. Simplifica altamente el proceso de probar localmente cualquier cambio
2. Seguir pasos en configuración https://developers.google.com/sheets/api/quickstart/js para habilitar el uso del API de Google Spreadsheets
1. Habrá que tomar en cuenta que este acceso probablamente lo deba dar un administrador de UABC
2. Agregar información sobre como asegurar la llave de API para evitar su mal uso
3. Seguir pasos para configuración de github pages en: https://pages.github.com/ utilizando Organization site (o quizá proyecto, habrá que validar eso)
1. Deberá ser sin tema, para evitar todo el overheader instalación de Jekyll, y aprender como configurarlo
<file_sep>var HallOfFameApi = function (apiKey, spreadSheetId) {
var getData = function (range) {
return fetch(
'https://sheets.googleapis.com/v4/spreadsheets/' +
spreadSheetId +
'/values/' +
range +
'?key='+encodeURIComponent(apiKey)
).then(function (response) {
if (response.status === 200) {
return response.json();
}
});
};
this.getOlimpiadas = function () {
return getData('Olimpiadas!A:A')
.then(function (response) {
return response.values;
})
.then(function (rows) {
return rows.map(function (row) {return row[0]});
});
};
};
var getEnv = function (defaultEnv) {
return fetch('dev.env.json')
.then(function (resp) {
if (resp.status === 200) {
return resp.json();
}
return defaultEnv;
});
};
var API_KEY = '<KEY>';
var table = document.getElementById('resultados');
var tableHeader = table.querySelector('thead');
var tableBody = table.querySelector('tbody');
var olimpiadaSelect = document.getElementById('olimpiadas')
var spreadSheetId = '1aTG1lp__BLsUfchFs1CJkWRVUDyswXonNXq_TRKgjmk';
google.charts.load('current');
google.charts.setOnLoadCallback(function () {
getEnv({
GOOGLE_API_KEY: API_KEY,
}).then(function (env) {
var apiKey = env.GOOGLE_API_KEY;
var api = new HallOfFameApi(apiKey, spreadSheetId);
var cache = {};
function uiRefreshOlimpiadaResults(rawData) {
tableHeader.innerHTML = '';
tableBody.innerHTML = '';
var headerRow = document.createElement('tr');
rawData.cols.forEach(function (colModel) {
var th = document.createElement('th');
th.innerText = colModel.label;
headerRow.appendChild(th);
});
tableHeader.appendChild(headerRow);
rawData.rows.forEach(function (rowData) {
var row = document.createElement('tr');
rowData.c.forEach(function (cellData) {
var td = document.createElement('td');
td.innerText = cellData.v;
row.appendChild(td);
});
tableBody.appendChild(row);
});
}
function refreshOlimpiadaResults() {
var currentOlimpiada = olimpiadaSelect.options[olimpiadaSelect.selectedIndex].value;
var query = 'select A, B, C, D, H WHERE A = "' + currentOlimpiada + '"';
if (cache.hasOwnProperty(query)) {
return uiRefreshOlimpiadaResults(cache[query]);
}
var queryObj = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/'+spreadSheetId+'/gviz/tq?sheet=Resultados&headers=1&tq=' + encodeURIComponent(query));
queryObj.send(function(response) {
var rawData = JSON.parse(response.getDataTable().toJSON());
cache[query] = rawData;
return uiRefreshOlimpiadaResults(rawData);
});
}
olimpiadaSelect.addEventListener('change', function () {
refreshOlimpiadaResults();
});
api.getOlimpiadas()
.then(function(olimpiadas) {
olimpiadas.forEach(function (olimpiadaName) {
var option = document.createElement('option');
option.innerText = olimpiadaName;
option.value = olimpiadaName;
olimpiadaSelect.appendChild(option);
});
})
.then(refreshOlimpiadaResults);
});
});
<file_sep># Salón de la fama OMIBC
Página de Github para la administración del salón de la fama de OMIBC, aquí se podrán visualizar todos los
|
1d952156c19aa57cb07715013bb2c52eb27d99d2
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
macarenomarco/hall_of_fame
|
e18e5f12b0a1c50126f55da0c141554f8c7f4c81
|
d5a0ff2bcd87bbb6c167e4b17d527d01374c844e
|
refs/heads/master
|
<repo_name>AkashBiswas080/OpenBrowser<file_sep>/src/test/java/AmazonBrowser.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AmazonBrowser {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = " https://www.google.com/aclk?sa=L&ai=DChcSEwjo8eLxgcvxAhU-dG8EHXCgD-wYABABGgJqZg&ae=2&sig=AOD64_2kz-W_4PeL-i3x8UdEg_ky0S0NdQ&q&adurl&ved=2ahUKEwiKz9vxgcvxAhWnB50JHYrXD8kQ0Qx6BAgDEAE";
driver.get(url);
}
}
|
cd250169ed3b44509f3f6418c9a201712df4edf5
|
[
"Java"
] | 1 |
Java
|
AkashBiswas080/OpenBrowser
|
0a2d08dc9db61e4951c00d49ba40ee0ad803a2d4
|
92fa606f3ac08d2285be7d8c01566cfc75fb0e4f
|
refs/heads/master
|
<file_sep>pyregx python专用的正则工具
============
作为程序猿 , 每天都会遇到正则的提取,但大部分为通用的,
是否可以把这些常用正则收集起来, 方便你的调用哪
使用方法
----------------------------------
:::python
from pyregx.pyregx import PPattern
regx = PPattern()
print p.IP != '192.168.3.11' #返回true
p.mail.find_iter('<EMAIL>') #['<EMAIL>']
p.html_tag.find_iter("<html xx=11>") #['<html xx=11>']
热烈欢迎
--------------------------------------
本人小码农,希望正则高手添加更多使用的正则
对于python,希望高手指教
总结
-----------------------
真爱生命,小心用python ,不是我不喜欢,但是它的类型太弱化了,对于大型工程 , 维护的时间或许多余编程的时间
<file_sep># coding=utf-8
#!/usr/bin/env python
import re
import sys
import time
reload(sys)
sys.setdefaultencoding('utf-8')
REGX_ARRY = [(
'time', '(20)(0[1-9]|1[1-4])[年/-]{1}(0?[1-9]|1[0-2]{0,1})[月/-]{1}(0?[1-9]{1}|[1-2]{1}[0-9]{1}|3[01]?)日?[ ]{0,}(0?[0-9]{1}|[1-5]{1}[0-9])[点:]{0,}'),
('year', '(今|明|后|大后|大前|前)年'),
('today', ur'(今|明|后|昨|前|大前|大后)(天|日)'),
('pa_m', '((上|下|中)午|(早|晚)上)(?!([0-9]{1}|([1]{1}[0-2]{1}))点)'), ]
'''
2014年04月23日 14:14:41
2014年04月23日 20:30:29
2014年04月23日06:50
2013年7月17日
12月27日
今晚19时44分
2014-04-23
4月22日
4月23日
23日
04月23日 08:55
2014年4月23日上午
'''
now_day = time.time()
WORD_EXTRACT_REGX = ur'|'.join(ur'(?P<%s>%s)' % (pair[0], pair[1]) for pair in REGX_ARRY)
WORD_EXTRACT = re.compile(WORD_EXTRACT_REGX, re.U | re.IGNORECASE).finditer
clear_word_set = set([u'的', u',', u','])
def clear_word(word):
if word and isinstance(word, (str, unicode)):
if isinstance(word, (str)):
word = word.decode('utf-8')
return ''.join([__tag for __tag in word if __tag not in clear_word_set])
raise Exception, 'word isn\'t str or unicode'
print clear_word("2014年04月23日14:14:41,前年的今天,上午10点我去公司了".decode('utf-8'))
for i in WORD_EXTRACT("前年的今天,上午10点我去公司了".decode('utf-8')):
print i.groupdict()
<file_sep>
from pyregx.pyregx import PPattern
if __name__ == "__main__":
p = PPattern()
print p.IP != '172.16.58.3'
del p.IP
print p.mail.find_iter('<EMAIL>')
print p.html_tag.find_iter("<html xx=11>")
print p.date == '2013/12/05'
print 'xx'.replace('x', 'y')<file_sep>#!/usr/bin/env python
# coding=utf-8
import regdict
import re
class PyRe(object):
def __init__(self, pattern):
self.__pattern = pattern
self.__start_pattern = self.__pattern
self.__end_pattern = self.__pattern
self.__equal_pattern = self.__pattern
if not pattern.startswith('^'):
self.__start_pattern = '^%s' % self.__pattern
self.__equal_pattern = '^%s' % self.__pattern
if not pattern.endswith('$'):
self.__end_pattern = '%s$' % self.__pattern
self.__equal_pattern = '%s$' % self.__pattern
self.__start_compile = re.compile(self.__start_pattern)
self.__compile = re.compile(pattern)
self.__end_compile = re.compile(self.__end_pattern)
self.__equal_compile = re.compile(self.__equal_pattern)
def equal(self, data):
if self.__equal_compile.match(data):
return True
return False
def start_with(self, data):
if self.__start_compile.match(data):
return True
else:
return False
def end_with(self, data):
if self.__end_compile.match(data):
return True
else:
return False
def __eq__(self, data):
if data and isinstance(data, (str, unicode)):
if self.equal(data):
return True
return False
else:
raise TypeError, 'data must be str or unicode!'
def __ne__(self, data):
return not self.__eq__(data)
# 数据中包含正则表达式数据
# 如果有数据符合正则
# 返回 True
#
def contain(self, data):
if self.__compile.search(data):
return True
else:
return False
def find_all(self, data, callable=None):
return self.__compile.findall(data)
def find_iter(self, data, callable=None):
find_data = []
find_data.extend([match.group()
for match in self.__compile.finditer(data)])
return find_data
class PPattern(object):
__pattern_dict = {}
def __setattr__(self, key, value):
if key and value and isinstance(key, (str)) and isinstance(value, (PyRe)):
if not self.__pattern_dict.has_key(key):
self.__pattern_dict[key] = value
else:
raise TypeError, 'key must string and value is PyRe'
def __getattr__(self, key):
if isinstance(key, (str)):
if not self.__pattern_dict.has_key(key):
if regdict.regx_dict.has_key(key.upper()):
self.__pattern_dict[key] = PyRe(
regdict.regx_dict[key.upper()])
else:
raise NotImplementedError, 'regx_dict 没有正则'
return self.__pattern_dict[key]
raise TypeError, 'key must be sting '
def __delattr__(self, key):
if key and isinstance(key, str):
if self.__pattern_dict.has_key(key):
del self.__pattern_dict[key]
else:
raise TypeError, 'key must be string'
if __name__ == "__main__":
p = PPattern()
print p.IP != '192.168.3.11'
del p.IP
print p.mail.find_iter('<EMAIL>')
print p.html_tag.find_iter("<html xx=11>")
print p.date == '2013/12/05'
print 'xx'.replace('x', 'y')
|
c05a7a4c98cae23033d45e8b2951d9ef87f81590
|
[
"Markdown",
"Python"
] | 4 |
Markdown
|
intohole/pyregx
|
989e283f4cd854728f0d1e9f28b0dd5a77697ac6
|
2219faf8cee6318da3c571a1582ce27215bc4af7
|
refs/heads/master
|
<file_sep>function loadArticles(){
$.get('/api/posts',(posts)=>{
console.log(posts);
for(post of posts){
let article = post.body.substr(0,300);
$('#postList').append(`
<div class="card-deck col-md-4 my-3">
<div class="card shadow">
<div class="card-body">
<h5 class="card-title">${post.title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${post.user.username}</h6>
<p class="card-text">${article}
<a href="#">read more ..</a></p>
<a href="#" class="card-link">Like</a>
<a href="#" class="card-link">Comment</a>
</div>
</div>
</div>
`)
}
})
}
loadArticles();<file_sep>const ADJECTIVES = ['boundless','plausible','sleepy','electronic','dangerous','slim','purple'];
const OBJECTS = ['puddle','piano','window','bowl','socks','brocolli','chalk']
function genRandomUsername(){
const adj = ADJECTIVES[parseInt(Math.random()*7)];
const obj = OBJECTS[parseInt(Math.random()*7)];
return `${adj}-${obj}`;
}
module.exports = {
genRandomUsername
}<file_sep>function isLoginNeeded(){
let curr_user = window.localStorage.user ? JSON.parse(window.localStorage.user) : null;
if(curr_user==null){
const user = $.post('/api/users',(user)=>{
window.localStorage.user = JSON.stringify(user);
$('#userName').text(user.username);
})
}
else{
$('#userName').text(curr_user.username);
}
}
$(()=>{
$('#navbar').load('/components/navbar.html',isLoginNeeded)
$('#footer').load('/components/footer.html')
})<file_sep>const {genNeWComment,findAllComments} = require('../../controllers/comments');
const Router = require('express').Router();
const route = Router;
route.get('/',async(req,res)=>{
const comments = await findAllComments();
res.status(200).send(comments);
})
route.post('/',async(req,res)=>{
const {body,title,userId,postId} = req.body;
console.log(body,title,userId,postId);
if(!body || !title || !userId || !postId){
res.status(400).send("Invalid body,title,userId,postId of the comment");
}
const comment = await genNeWComment(userId,postId,title,body);
res.status(200).send(comment);
})
module.exports = {
CommentRoute : route
}<file_sep>const {db} = require('./db/models');
const express = require('express');
const app = express();
const {UserRoute} = require('./routes/users');
const {PostRoute} = require('./routes/posts')
app.use('/api/users',UserRoute);
app.use('/api/posts',PostRoute);
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.use('/',express.static(__dirname+'/public'));
db.sync({alter:true})
.then(()=>{
app.listen(4444,()=>{
console.log("Server started");
})
})
.catch((err)=>{
console.error(new Error("Could sync database"));
console.error(err);
})<file_sep># Social media sample project
## Database setup
``` shell
$ mysql -u root
```
```mysql
CREATE DATABASE socialmediadb;
CREATE USER socialuser IDENTIFIED BY '<PASSWORD>pass';
GRANT ALL PRIVILIGES ON socialmediadb.* to socialuser;
FLUSH PRIVILEGES;
```
## Project Structure
``` shell
src
├── controllers # functions to connect routes to db operations
├── db # db connections and models
├── public # html/css/js for static part of the site
└── routes # express middlewares route wise
```
## Api Documentation
### `users`
## Folder structure
### `Frontend`
```shell
├── app
│ └── social.js
├── components
│ └── navbar.html
├── css
│ └── bootstrap.css
├── fonts
│ ├── muli.css
│ ├── Muli-Italic.woff2
│ └── Muli.woff2
├── index.html
└── js
├── bootstrap.js
├── jquery-3.4.1.js
└── popper.js
```
## Project Structure
```shell
.
├── controllers
│ ├── comments.js
│ ├── posts.js
│ └── users.js
├── db
│ └── models.js
├── public
│ ├── app
│ │ ├── allPost.js
│ │ ├── navbar.js
│ │ ├── social.js
│ │ ├── socialstyle.css
│ │ └── writePost.js
│ ├── components
│ │ ├── allPost.html
│ │ ├── footer.html
│ │ ├── navbar.html
│ │ └── writePost.html
│ ├── css
│ │ └── bootstrap.css
│ ├── fonts
│ │ ├── muli.css
│ │ ├── Muli-Italic.woff2
│ │ └── Muli.woff2
│ ├── index.html
│ └── js
│ ├── bootstrap.js
│ ├── jquery-3.4.1.js
│ └── popper.js
├── routes
│ ├── posts
│ │ ├── comments.js
│ │ └── index.js
│ └── users
│ └── index.js
├── server.js
└── utils
└── username.js
```<file_sep>const {db} = require('../src/db/models');
before(async()=>{
console.log("Database synced");
await db.sync();
})<file_sep>const {Users,Posts,db,Comments} = require('../db/models');
async function genNeWComment(userId,postId,title,body){
const comment = await Comments.create({
userId,
postId,
body,
title
})
return comment;
}
async function findAllComments(query){
const comment = await Comments.findAll({
include : [Users,Posts]
});
return comment;
}
module.exports = {
genNeWComment,findAllComments
}
//Test code
// async function task(){
// const userno = parseInt(Math.random()*8 + 1);
// const postno = parseInt(Math.random()*6 + 1);
// const comment = await genNeWComment(userno,postno,`Comment on post ${postno}`,
// `This is a comment by user${userno} at post${postno}`);
// console.log(comment);
// const comments = await findAllComments();
// for(comment of comments){
// console.log(`${comment.title}\n${comment.body}\n
// User = ${comment.user.username}\n
// Post = ${comment.post.id}===========\n`)
// }
// }
// task();<file_sep>const {genUsername,getUserByID,getUserByUsername} = require('../../src/controllers/users')
const {expect} = require('chai')
describe('controllers/users',async()=>{
let createdUser = null;
it('should create annonymus users',async()=>{
createdUser = await genUsername();
expect(createdUser).to.have.property('username')
expect(createdUser.id).to.be.a('number')
})
it('should get user by userID',async()=>{
let foundUser = await getUserByID(createdUser.id)
expect(foundUser.username).to.equal(createdUser.username);
})
it('should get user by userID',async()=>{
let foundUser = await getUserByUsername(createdUser.username)
expect(foundUser.id).to.equal(createdUser.id);
})
})<file_sep>const Router = require('express').Router();
const express = require('express');
const {createNewPost,findAllPost} = require('../../controllers/posts')
const route = Router;
const {CommentRoute} = require('./comments');
route.use(express.json());
route.use(express.urlencoded({extended:true}));
route.use('/comment',CommentRoute);
route.post('/',async(req,res)=>{
const {title,body,userId} = req.body;
if((!title) || (!body) || (!userId)){
res.status(400).send("Enter valid title body userId");
}
else{
const post = await createNewPost(userId,title,body);
res.status(201).send(post);
}
})
route.get('/',async(req,res)=>{
let query = {}
if(req.query){
query = req.query
}
console.log(req.query);
const posts = await findAllPost(query);
res.status(200).send(posts);
})
// route.post('/',async(req,res)=>{
// const post = await createNewPost(parseInt(Math.random()*5 +1 ),`This is title by ${parseInt(Math.random()*5 + 1)}`,`This is body by ${parseInt(Math.random()*5 + 1)}`);
// res.status(201).send(post);
// })
module.exports = {
PostRoute : route
}<file_sep>const {Posts,Users} = require('../db/models');
async function createNewPost(userId,title,body){
const post = await Posts.create({
userId,
title,
body
})
return post;
}
async function findAllPost(query){
let whereClause = {}
if(query.userId){
whereClause.userId = query.userId
}
const post = await Posts.findAll({
where : whereClause,
include : [Users]
});
return post;
}
// async function task(){
// console.log(await findAllPost({}))
// }
// async function task(){
// // console.log(await createNewPost(3,'Sample title1','This is sample post by 3'));
// // console.log(await createNewPost(4,'Sample title2','This is sample post by 4'));
// // console.log(await createNewPost(2,'Sample title3','This is sample post by 2'));
// // console.log(await createNewPost(5,'Sample title4','This is sample post by 5'));
// // console.log(await createNewPost(1,'Sample title5','This is sample post by 1'));
// const post = await showAllPost();
// for(p of post){
// //console.log(p);
// console.log(`${p.title}\n${p.body}\nauthor : ${p.user.username}\n ==========\n`)
// }
// }
//task();
module.exports = {
createNewPost,
findAllPost
}<file_sep>$(()=>{
let btnPost = $('#btnPost')
let inpTitle = $('#inpTitle')
let inpBody = $('#inpBody')
btnPost.click(()=>{
let title = inpTitle.val();
let body = inpBody.val();
let userId = (JSON.parse(window.localStorage.user)).id
console.log("sdfdgfh");
$.post('/api/posts',{
userId : userId,
body : body,
title : title
},
(post)=>{
console.log(post);
})
})
})
|
5b6eae7a94f0c9bd197cb84933e7249ae7556715
|
[
"JavaScript",
"Markdown"
] | 12 |
JavaScript
|
ayushdip/social_media
|
7970be4338cca98e5e615c7b56c458c2b382c6ee
|
7543617f4e339a91cdb8dfbef15c995e96a02516
|
refs/heads/master
|
<file_sep>import { combineReducers } from 'redux';
const initialState = {
categoriesList: [
],
categoriesFormFields: {
name: '',
isNew: true
}
};
const categoriesList = (state = initialState.categoriesList, action) => {
switch (action.type) {
case 'FETCH_CATEGORIES_SUCCESS':
const newCategories = Object.keys(action.data).reduce((prev, curr) => ({
...prev,
[action.data[curr].id]: {
...action.data[curr]
}
}), {});
return newCategories;
case 'POST_CATEGORY_SUCCESS':
return action.returnData;
case 'PUT_CATEGORY_SUCCESS':
return action.returnData;
case 'DELETE_CATEGORY_SUCCESS':
return action.returnData;
default:
return state;
}
};
const categoriesFormFields = (state = initialState.categoriesFormFields, action) => {
switch (action.type) {
case 'EDIT_FIELD_CATEGORY':
return {
...state,
[action.field]: action.value
};
case 'TAKE_TO_EDIT_CATEGORY':
return {
...state,
id: action.json.id,
name: action.json.name,
isNew: false
};
case 'PUT_CATEGORY_SUCCESS':
return {
name: '',
isNew: true
};
case 'CANCEL_EDIT_CATEGORY':
return {
name: '',
isNew: true
};
case 'POST_CATEGORY_SUCCESS':
return {
name: '',
isNew: true
};
default:
return state;
}
};
export default combineReducers({
categoriesList,
categoriesFormFields
})
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
import Header from '../../components/Header';
import * as actions from '../Spending/actions';
import selectors from '../Spending/selectors';
class Spending extends Component {
constructor(props) {
super(props);
const {
fetchSpending,
fetchCategories
} = this.props;
fetchSpending();
fetchCategories();
}
selectCategory = () => e => {
const {
selectCategory
} = this.props;
selectCategory(e.value);
};
addSpending = (e) => {
e.preventDefault();
const {
spendingFormFields,
spendingList,
addSpending
} = this.props;
let id;
const size = 1000;
if (spendingFormFields.amount.length !== 0 && spendingFormFields.description.length !== 0) {
if (spendingList.length !== 0) {
while (!id) {
const randomNumber = Math.floor(Math.random() * size);
if (Object.keys(spendingList).every(v=>+v!==randomNumber)) {
id = randomNumber;
}
}
}
else {
id = 1;
}
const newItem = {
id,
amount: spendingFormFields.amount,
description: spendingFormFields.description,
date: moment().format('lll')
};
if (spendingFormFields.category_name) {
newItem.category = spendingFormFields.category_name;
}
const dataToPost = {
...spendingList,
[id]: newItem
};
addSpending(dataToPost);
}
};
editSpending = e => {
e.preventDefault();
const {
spendingFormFields,
spendingList,
editSpending
} = this.props;
if (spendingFormFields.amount.length !== 0 && spendingFormFields.description.length !== 0) {
const newItem = {
id: spendingFormFields.id,
amount: spendingFormFields.amount,
description: spendingFormFields.description,
category: spendingFormFields.category_name,
date: moment().format('lll')
};
const dataToPut = {
...spendingList,
[spendingFormFields.id]: newItem
};
editSpending(dataToPut);
}
};
cancelEditSpending = e => {
e.preventDefault();
const {
cancelEditSpending
} = this.props;
cancelEditSpending();
};
takeToEditSpending = id => e => {
e.preventDefault();
const {
spendingList,
takeToEditSpending
} = this.props;
takeToEditSpending(spendingList[id]);
};
deleteSpending = id => e => {
e.preventDefault();
const {
spendingList,
deleteSpending
} = this.props;
let dataToPost = {
...spendingList
};
delete dataToPost[id];
deleteSpending(dataToPost);
};
edit = field => e => {
const {
editField
} = this.props;
editField(field, e.target.value);
};
render() {
const {
spendingList,
categoriesList,
spendingFormFields
} = this.props;
const spendingToShow = spendingList && Object.keys(spendingList).map((keys, index) => (
<tr key={`spending__${index}`}>
<td>{index+1}</td>
<td>{spendingList[keys].amount}</td>
<td>{spendingList[keys].description}</td>
<td>{spendingList[keys].category}</td>
<td>{spendingList[keys].date}</td>
<td><button className="btn btn-warning" onClick={this.takeToEditSpending(spendingList[keys].id)}>Edit</button></td>
<td><button className="btn btn-danger" onClick={this.deleteSpending(spendingList[keys].id)}>Delete</button></td>
</tr>
));
return (
<div>
<Header />
<div className="main__wrap">
<div className="spending__add__form">
<form>
<div className="form-group">
<label htmlFor="amount">Amount:</label>
<input type="number" className="form-control" placeholder="Amount" id="amount" onChange={this.edit('amount')} value={spendingFormFields.amount}/>
</div>
<div className="form-group">
<label htmlFor="price">Description:</label>
<input type="text" className="form-control" id="description" placeholder="Description" onChange={this.edit('description')} value={spendingFormFields.description}/>
</div>
<div className="form-group">
<label htmlFor="sel1">Category:</label>
<Select
name="form-field-name"
options={categoriesList}
onChange={this.selectCategory()}
value={spendingFormFields.category_name}
clearable={false}
/>
</div>
{
spendingFormFields.isNew
?
<button className="btn btn-success" onClick={this.addSpending}>Add</button>
:
<div>
<button className="btn btn-warning" onClick={this.editSpending}>Edit</button>
<button className="btn btn-default" onClick={this.cancelEditSpending}>Cancel</button>
</div>
}
</form>
</div>
{
spendingToShow.length === 0
?
<div style={{'textAlign': 'center'}}>No items here. Create one!</div>
:
<table className="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Amount</th>
<th>Description</th>
<th>Category</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{ spendingToShow }
</tbody>
</table>
}
</div>
</div>
)
}
}
export default connect(selectors, actions)(Spending);
<file_sep>import React from 'react'
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import configureStore from './store/configureStore';
import Main from './containers/Main/Main';
import Incomes from './containers/Incomes/Incomes';
import Spending from './containers/Spending/Spending';
import Categories from './containers/Categories/Categories';
import Home from './containers/Home/Home';
export const store = configureStore();
render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={Home}>
<IndexRoute component={Main} />
<Route path="/incomes" component={Incomes}/>
<Route path="/spending" component={Spending}/>
<Route path="/categories" component={Categories}/>
</Route>
</Router>
</Provider>,
document.getElementById('root'),
);<file_sep>/** **********************************************
* Add all reducers to this file for combine it. *
*************************************************/
import { combineReducers } from 'redux';
import Main from './containers/Main/reducers';
import Incomes from './containers/Incomes/reducers';
import Spending from './containers/Spending/reducers';
import Categories from './containers/Categories/reducers';
const rootReducer = combineReducers({
Main,
Incomes,
Spending,
Categories
});
export default rootReducer;
<file_sep>import { createStructuredSelector } from 'reselect';
const REDUCER = 'Spending';
const spendingList = state => state[REDUCER].spendingList;
const categoriesList = state => state[REDUCER].categoriesList;
const spendingFormFields = state => state[REDUCER].spendingFormFields;
export default createStructuredSelector({
spendingList,
categoriesList,
spendingFormFields
});<file_sep>import { createStructuredSelector } from 'reselect';
const REDUCER = 'Main';
const selectedCategory = state => state[REDUCER].selectedCategory;
const incomesList = state => state[REDUCER].incomesList;
const spendingList = state => state[REDUCER].spendingList;
const categoriesList = state => state[REDUCER].categoriesList;
export default createStructuredSelector({
selectedCategory,
incomesList,
spendingList,
categoriesList
});<file_sep>import { combineReducers } from 'redux';
const initialState = {
incomesList: [
],
spendingList: [
],
categoriesList: [
],
selectedCategory: ''
};
const selectedCategory = (state = initialState.selectedCategory, action) => {
switch (action.type) {
case 'SELECT_CATEGORY':
return action.category_name;
default:
return state;
}
};
const incomesList = (state = initialState.incomesList, action) => {
switch (action.type) {
case 'FETCH_INCOMES_SUCCESS':
let newIncomesArr = [];
Object.keys(action.data).forEach(key=>(
newIncomesArr.push({
label: action.data[key].date,
value: action.data[key].amount,
category: action.data[key].category
})
));
return newIncomesArr;
default:
return state;
}
};
const spendingList = (state = initialState.spendingList, action) => {
switch (action.type) {
case 'FETCH_SPENDING_SUCCESS':
let newSpendingArr = [];
Object.keys(action.data).forEach(key=>(
newSpendingArr.push({
label: action.data[key].date,
value: action.data[key].amount,
category: action.data[key].category
})
));
return newSpendingArr;
default:
return state;
}
};
const categoriesList = (state = initialState.categoriesList, action) => {
switch (action.type) {
case 'FETCH_CATEGORIES_SUCCESS':
let newCategoriesArr = [];
Object.keys(action.data).forEach(key=>(
newCategoriesArr.push({
label: action.data[key].name,
value: action.data[key].name
})
));
return newCategoriesArr;
default:
return state;
}
};
export default combineReducers({
selectedCategory,
incomesList,
spendingList,
categoriesList
})
<file_sep>export const fetchIncomes = () => {
return dispatch => {
if (!localStorage.getItem('IncomesList')) {
dispatch({
type: 'FETCH_INCOMES_FAIL'
})
}
else {
dispatch({
type: 'FETCH_INCOMES_SUCCESS',
data: JSON.parse(localStorage.getItem('IncomesList'))
})
}
}
};
export const fetchCategories = () => {
return dispatch => {
if (!localStorage.getItem('CategoriesList')) {
dispatch({
type: 'FETCH_CATEGORIES_FAIL'
})
}
else {
dispatch({
type: 'FETCH_CATEGORIES_SUCCESS',
data: JSON.parse(localStorage.getItem('CategoriesList'))
})
}
}
};
export const addIncome = (jsonToPost) => {
return dispatch => {
localStorage.setItem('IncomesList', JSON.stringify(jsonToPost));
dispatch({
type: 'POST_INCOME_SUCCESS',
returnData: jsonToPost
})
}
};
export const deleteIncome = (jsonToPost) => {
return dispatch => {
localStorage.setItem('IncomesList', JSON.stringify(jsonToPost));
dispatch({
type: 'DELETE_INCOME_SUCCESS',
returnData: jsonToPost
})
}
};
export const selectCategory = category_name => {
return {
type: 'SELECT_CATEGORY',
category_name
}
};
export const editField = (field, value) => {
return {
type: 'EDIT_FIELD_INCOME',
field,
value
}
};
export const editIncome = jsonToPut => {
return dispatch => {
localStorage.setItem('IncomesList', JSON.stringify(jsonToPut));
dispatch({
type: 'PUT_INCOME_SUCCESS',
returnData: jsonToPut
})
}
};
export const takeToEditIncome = json => {
return {
type: 'TAKE_TO_EDIT_INCOME',
json
}
};
export const cancelEditIncome = () => {
return {
type: 'CANCEL_EDIT_INCOME'
}
};
<file_sep>export const fetchCategories = () => {
return dispatch => {
if (!localStorage.getItem('CategoriesList')) {
dispatch({
type: 'FETCH_CATEGORIES_FAIL'
})
}
else {
dispatch({
type: 'FETCH_CATEGORIES_SUCCESS',
data: JSON.parse(localStorage.getItem('CategoriesList'))
})
}
}
};
export const addCategory = jsonToPost => {
return dispatch => {
localStorage.setItem('CategoriesList', JSON.stringify(jsonToPost));
dispatch({
type: 'POST_CATEGORY_SUCCESS',
returnData: jsonToPost
})
}
};
export const deleteCategory = jsonToPost => {
return dispatch => {
localStorage.setItem('CategoriesList', JSON.stringify(jsonToPost));
dispatch({
type: 'DELETE_CATEGORY_SUCCESS',
returnData: jsonToPost
})
}
};
export const editCategory = jsonToPut => {
return dispatch => {
localStorage.setItem('CategoriesList', JSON.stringify(jsonToPut));
dispatch({
type: 'PUT_CATEGORY_SUCCESS',
returnData: jsonToPut
})
}
};
export const takeToEditCategory = json => {
return {
type: 'TAKE_TO_EDIT_CATEGORY',
json
}
};
export const cancelEditCategory = () => {
return {
type: 'CANCEL_EDIT_CATEGORY'
}
};
export const editField = (field, value) => {
return {
type: 'EDIT_FIELD_CATEGORY',
field,
value
}
};
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import Select from 'react-select';
import 'react-select/dist/react-select.css';
import Header from '../../components/Header';
import * as actions from '../Incomes/actions';
import selectors from '../Incomes/selectors';
class Incomes extends Component {
constructor(props) {
super(props);
const {
fetchIncomes,
fetchCategories
} = this.props;
fetchIncomes();
fetchCategories();
}
selectCategory = () => e => {
const {
selectCategory
} = this.props;
selectCategory(e.value);
};
addIncome = (e) => {
e.preventDefault();
const {
incomesFormFields,
incomesList,
addIncome
} = this.props;
let id;
const size = 1000;
if (incomesFormFields.amount.length !== 0 && incomesFormFields.description.length !== 0) {
if (incomesList.length !== 0) {
while (!id) {
const randomNumber = Math.floor(Math.random() * size);
if (Object.keys(incomesList).every(v=>+v!==randomNumber)) {
id = randomNumber;
}
}
}
else {
id = 1;
}
const newItem = {
id,
amount: incomesFormFields.amount,
description: incomesFormFields.description,
date: moment().format('lll')
};
if (incomesFormFields.category_name) {
newItem.category = incomesFormFields.category_name;
}
const dataToPost = {
...incomesList,
[id]: newItem
};
addIncome(dataToPost);
}
};
editIncome = e => {
e.preventDefault();
const {
incomesFormFields,
incomesList,
editIncome
} = this.props;
if (incomesFormFields.amount.length !== 0 && incomesFormFields.description.length !== 0) {
const newItem = {
id: incomesFormFields.id,
amount: incomesFormFields.amount,
description: incomesFormFields.description,
category: incomesFormFields.category_name,
date: moment().format('lll')
};
const dataToPut = {
...incomesList,
[incomesFormFields.id]: newItem
};
editIncome(dataToPut);
}
};
cancelEditIncome = e => {
e.preventDefault();
const {
cancelEditIncome
} = this.props;
cancelEditIncome();
};
takeToEditIncome = id => e => {
e.preventDefault();
const {
incomesList,
takeToEditIncome
} = this.props;
takeToEditIncome(incomesList[id]);
};
deleteIncome = (id) => e => {
e.preventDefault();
const {
incomesList,
deleteIncome
} = this.props;
let dataToPost = {
...incomesList
};
delete dataToPost[id];
deleteIncome(dataToPost);
};
edit = field => e => {
const {
editField
} = this.props;
editField(field, e.target.value);
};
render() {
const {
incomesList,
categoriesList,
incomesFormFields
} = this.props;
const incomesToShow = incomesList && Object.keys(incomesList).map((keys, index) => (
<tr key={`income__${index}`}>
<td>{index+1}</td>
<td>{incomesList[keys].amount}</td>
<td>{incomesList[keys].description}</td>
<td>{incomesList[keys].category}</td>
<td>{incomesList[keys].date}</td>
<td><button className="btn btn-warning" onClick={this.takeToEditIncome(incomesList[keys].id)}>Edit</button></td>
<td><button className="btn btn-danger" onClick={this.deleteIncome(incomesList[keys].id)}>Delete</button></td>
</tr>
));
return (
<div>
<Header />
<div className="main__wrap">
<div className="income__add__form">
<form>
<div className="form-group">
<label htmlFor="amount">Amount:</label>
<input type="number" className="form-control" placeholder="Amount" id="amount" onChange={this.edit('amount')} value={incomesFormFields.amount}/>
</div>
<div className="form-group">
<label htmlFor="price">Description:</label>
<input type="text" className="form-control" id="description" placeholder="Description" onChange={this.edit('description')} value={incomesFormFields.description}/>
</div>
<div className="form-group">
<label htmlFor="sel1">Category:</label>
<Select
name="form-field-name"
options={categoriesList}
onChange={this.selectCategory()}
value={incomesFormFields.category_name}
clearable={false}
/>
</div>
{
incomesFormFields.isNew
?
<button className="btn btn-success" onClick={this.addIncome}>Add</button>
:
<div>
<button className="btn btn-warning" onClick={this.editIncome}>Edit</button>
<button className="btn btn-default" onClick={this.cancelEditIncome}>Cancel</button>
</div>
}
</form>
</div>
{
incomesToShow.length === 0
?
<div style={{'textAlign': 'center'}}>No items here. Create one!</div>
:
<table className="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Amount</th>
<th>Description</th>
<th>Category</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{ incomesToShow }
</tbody>
</table>
}
</div>
</div>
)
}
}
export default connect(selectors, actions)(Incomes);
<file_sep>import { combineReducers } from 'redux';
const initialState = {
incomesList: [
],
categoriesList: [
],
incomesFormFields: {
category_name: '',
amount: '',
description: '',
isNew: true
}
};
const incomesList = (state = initialState.incomesList, action) => {
switch (action.type) {
case 'FETCH_INCOMES_SUCCESS':
const newIncomes = Object.keys(action.data).reduce((prev, curr) => ({
...prev,
[action.data[curr].id]: {
...action.data[curr]
}
}), {});
return newIncomes;
case 'POST_INCOME_SUCCESS':
return action.returnData;
case 'PUT_INCOME_SUCCESS':
return action.returnData;
case 'DELETE_INCOME_SUCCESS':
return action.returnData;
default:
return state;
}
};
const categoriesList = (state = initialState.categoriesList, action) => {
switch (action.type) {
case 'FETCH_CATEGORIES_SUCCESS':
let newCategoriesArr = [];
Object.keys(action.data).forEach(key=>(
newCategoriesArr.push({
label: action.data[key].name,
value: action.data[key].name
})
));
return newCategoriesArr;
default:
return state;
}
};
const incomesFormFields = (state = initialState.incomesFormFields, action) => {
switch (action.type) {
case 'SELECT_CATEGORY':
return {
...state,
category_name: action.category_name
};
case 'EDIT_FIELD_INCOME':
return {
...state,
[action.field]: action.value
};
case 'TAKE_TO_EDIT_INCOME':
return {
...state,
id: action.json.id,
amount: action.json.amount,
description: action.json.description,
category_name: action.json.category,
isNew: false
};
case 'PUT_INCOME_SUCCESS':
return {
name: '',
isNew: true
};
case 'CANCEL_EDIT_INCOME':
return {
name: '',
isNew: true
};
case 'POST_INCOME_SUCCESS':
return {
amount: '',
description: '',
isNew: true
};
default:
return state;
}
};
export default combineReducers({
incomesList,
categoriesList,
incomesFormFields
})
<file_sep>Setup guide
- Install git
- Install node js
commands below:
- git clone https://github.com/heiets/spendee-test.git
go to app directory (-cd spendee-test)
- npm install
- npm start
<file_sep>import { createStructuredSelector } from 'reselect';
const REDUCER = 'Incomes';
const incomesList = state => state[REDUCER].incomesList;
const categoriesList = state => state[REDUCER].categoriesList;
const incomesFormFields = state => state[REDUCER].incomesFormFields;
export default createStructuredSelector({
incomesList,
categoriesList,
incomesFormFields
});<file_sep>export const fetchSpending = () => {
return dispatch => {
if (!localStorage.getItem('SpendingList')) {
dispatch({
type: 'FETCH_SPENDING_FAIL'
})
}
else {
dispatch({
type: 'FETCH_SPENDING_SUCCESS',
data: JSON.parse(localStorage.getItem('SpendingList'))
})
}
}
};
export const fetchCategories = () => {
return dispatch => {
if (!localStorage.getItem('CategoriesList')) {
dispatch({
type: 'FETCH_CATEGORIES_FAIL'
})
}
else {
dispatch({
type: 'FETCH_CATEGORIES_SUCCESS',
data: JSON.parse(localStorage.getItem('CategoriesList'))
})
}
}
};
export const addSpending = jsonToPost => {
return dispatch => {
localStorage.setItem('SpendingList', JSON.stringify(jsonToPost));
dispatch({
type: 'POST_SPENDING_SUCCESS',
returnData: jsonToPost
})
}
};
export const deleteSpending = jsonToPost => {
return dispatch => {
localStorage.setItem('SpendingList', JSON.stringify(jsonToPost));
dispatch({
type: 'DELETE_SPENDING_SUCCESS',
returnData: jsonToPost
})
}
};
export const selectCategory = category_name => {
return {
type: 'SELECT_CATEGORY',
category_name
}
};
export const editField = (field, value) => {
return {
type: 'EDIT_FIELD_SPENDING',
field,
value
}
};
export const editSpending = jsonToPut => {
return dispatch => {
localStorage.setItem('SpendingList', JSON.stringify(jsonToPut));
dispatch({
type: 'PUT_SPENDING_SUCCESS',
returnData: jsonToPut
})
}
};
export const takeToEditSpending = json => {
return {
type: 'TAKE_TO_EDIT_SPENDING',
json
}
};
export const cancelEditSpending = () => {
return {
type: 'CANCEL_EDIT_SPENDING'
}
};<file_sep>export const fetchSpending = () => {
return dispatch => {
if (!localStorage.getItem('SpendingList')) {
dispatch({
type: 'FETCH_SPENDING_FAIL'
})
}
else {
dispatch({
type: 'FETCH_SPENDING_SUCCESS',
data: JSON.parse(localStorage.getItem('SpendingList'))
})
}
}
};
export const fetchIncomes = () => {
return dispatch => {
if (!localStorage.getItem('IncomesList')) {
dispatch({
type: 'FETCH_INCOMES_FAIL'
})
}
else {
dispatch({
type: 'FETCH_INCOMES_SUCCESS',
data: JSON.parse(localStorage.getItem('IncomesList'))
})
}
}
};
export const fetchCategories = () => {
return dispatch => {
if (!localStorage.getItem('CategoriesList')) {
dispatch({
type: 'FETCH_CATEGORIES_FAIL'
})
}
else {
dispatch({
type: 'FETCH_CATEGORIES_SUCCESS',
data: JSON.parse(localStorage.getItem('CategoriesList'))
})
}
}
};
export const selectCategory = category_name => {
return {
type: 'SELECT_CATEGORY',
category_name
}
};
|
8c9351952ced9ef5628154e65c11901f729b1ba4
|
[
"JavaScript",
"Markdown"
] | 15 |
JavaScript
|
heiets/spendee-test
|
48bd6d35f3feb7ee2e095215f00186a5a92239e0
|
42db2768f671426a4802a9e9f6d8d5c9a9712567
|
refs/heads/master
|
<repo_name>pawan231/2048<file_sep>/README.md
# play_2048
It is implementation of the popular game-2048 in C++.
For enjoying the game,you just need to run 2048.cpp on terminal.
Check instructions options for How to play the game.<file_sep>/2048.cpp
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<iomanip>
using namespace std;
//total score
int score=0;
//to set max limit on no. of times undo can be performed
int undo_flag=0;
//variable which stores score made in previous move, used to reduce the total score
//in case undo choice is selected
int undo_score=0;
class play{
int g[4][4];
int g_copy[4][4];
void initialize();
void display();
void move_up();
void move_down();
void move_left();
void move_right();
int check_full();
int random_index(int x);
void sum_up();
void sum_down();
void sum_left();
void sum_right();
void generate_new_index();
int calculate_max();
void instructions();
int game_ends();
void end_display();
void win_display();
void lose_display();
void restart();
public:
void play_game();
};
void play :: instructions(){
cout<<"\nInstructions for playing 2048 are:: \n"<<endl;
cout<<"For moving tiles enter \nw-move up/na-move left\nd-move right\ns-move down\n"<<endl;
cout<<"When two tiles with same number touch, they merge into one. \nWhen 2048 is created, the player wins!\n"<<endl;
cout<<"please don't try to undo consecutively\n\n";
display();
}
int play :: random_index(int x){
int index;
index=rand()%x + 0;
return index;
}
void play :: lose_display(){
system("clear");
cout<<"\t\t\tGAME OVER\n\n";
cout<<"Your final score is "<<score<<"\n\n";
cout<<"Thanks for trying!!!\n\n";
exit(0);
}
void play :: restart(){
char ch;
cout<<"\nAre you sure to restart the game??\n\n";
cout<<"enter y to restart and n to continue.\n\n";
cin>>ch;
if(ch=='y'){
score=0;
undo_score=0;
initialize();
}
}
int play :: check_full(){
int full_flag=1;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(g[i][j]==0){
full_flag=0;
break;
}
}
}
return full_flag;
}
void play :: win_display(){
char ch;
cout<<"\t\t\tYOU WON!!!\n\n";
cout<<"Your total score is "<<score<<"\n\n";
cout<<"Do you wish to continue???\n";
cout<<"Enter y to continue and n to quit\n\n";
cin>>ch;
if(ch=='n'){
end_display();
}
}
int play :: calculate_max(){
int i,j;
int max=0;
for(i=0;i<4;i++){
for(j=0;j<4;j++){
if(g[i][j]>max){
max=g[i][j];
}
}
}
return max;
}
void play :: end_display(){
system("clear");
cout<<"\nYour final score is :: "<<score<<endl<<endl;
cout<<"Thanks for trying!!!\n\n";
cout<<"Good Bye!!!\n"<<endl;
exit(0);
}
int play :: game_ends(){
int i,j,flag=1;
for(i=0;i<4;i++){
for(j=0;j<3;j++){
if(g[i][j]==g[i][j+1]){
flag=0;
break;
}
}
if(flag==0){
break;
}
}
if(flag==1){
for(i=0;i<3;i++){
for(j=0;j<4;j++){
if(g[i][j]==g[i+1][j]){
flag=0;
break;
}
}
if(flag==0){
break;
}
}
}
return flag;
}
void play :: generate_new_index(){
int flag=1;
if(!check_full()){
while(flag){
int i=random_index(4);
int j=random_index(4);
if(g[i][j]==0){
int y=rand()%10+0;
if(y<6){
g[i][j]=2;
}else{
g[i][j]=4;
}
flag=0;
}
}
}
}
/*
* initialize the matrices g and g_copy
* two of the indices to value = 2 and other values to 0
*/
void play :: initialize(){
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
g[i][j]=0;
g_copy[i][j]=0;
}
}
int i=random_index(4);
int j=random_index(4);
g[i][j]=2;
i=random_index(4);
j=random_index(4);
g[i][j]=2;
display();
}
void play :: move_up(){
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(!g[j][i]){
for(int k=j+1;k<4;k++){
if(g[k][i]){
g[j][i]=g[k][i];
g[k][i]=0;
break;
}
}
}
}
}
}
void play :: move_down(){
for(int i=0;i<4;i++){
for(int j=3;j>=0;j--){
if(!g[j][i]){
for(int k=j-1;k>=0;k--){
if(g[k][i]){
g[j][i]=g[k][i];
g[k][i]=0;
break;
}
}
}
}
}
}
void play :: move_left(){
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(!g[i][j]){
for(int k=j+1;k<4;k++){
if(g[i][k]){
g[i][j]=g[i][k];
g[i][k]=0;
break;
}
}
}
}
}
}
void play :: move_right(){
for(int i=0;i<4;i++){
for(int j=3;j>=0;j--){
if(!g[i][j]){
for(int k=j-1;k>=0;k--){
if(g[i][k]){
g[i][j]=g[i][k];
g[i][k]=0;
break;
}
}
}
}
}
}
void play :: sum_up(){
for(int i=0;i<4;i++){
for(int j=0;j<3;j++){
if(g[j][i] && g[j][i]==g[j+1][i]){
g[j][i]=g[j][i] + g[j+1][i];
g[j+1][i]=0;
score+=g[j][i];
undo_score+=g[j][i];
}
}
}
}
void play :: sum_down(){
for(int i=0;i<4;i++){
for(int j=3;j>0;j--){
if(g[j][i] && g[j][i]==g[j-1][i]){
g[j][i]=g[j][i] + g[j-1][i];
g[j-1][i]=0;
score+=g[j][i];
undo_score+=g[j][i];
}
}
}
}
void play :: sum_left(){
for(int i=0;i<4;i++){
for(int j=0;j<3;j++){
if(g[i][j] && g[i][j]==g[i][j+1]){
g[i][j]=g[i][j] + g[i][j+1];
g[i][j+1]=0;
score+=g[i][j];
undo_score+=g[i][j];
}
}
}
}
void play :: sum_right(){
for(int i=0;i<4;i++){
for(int j=3;j>0;j--){
if(g[i][j] && g[i][j]==g[i][j-1]){
g[i][j]=g[i][j] + g[i][j-1];
g[i][j-1]=0;
score=score + g[i][j];
undo_score+=g[i][j];
}
}
}
}
/*
* function to take choice from user
* and call functions accordingly
*/
void play :: play_game(){
int flag=0;
char choice,ch;
initialize();
cin>>choice;
while((choice=='w' || choice=='a' || choice=='s' || choice=='d' || choice=='q' || choice=='i' || choice=='u' || choice=='r')){
//make copy of previous move before updating the current matrix to g_copy
if(choice!='u'){
for(int m=0;m<4;m++){
for(int n=0;n<4;n++){
g_copy[m][n]=g[m][n];
}
}
}
switch(choice){
//move up
case 'w':
undo_score=0;
move_up();
sum_up();
move_up();
generate_new_index();
system("clear");
display();
break;
//move down
case 's':
undo_score=0;
move_down();
sum_down();
move_down();
generate_new_index();
system("clear");
display();
break;
//move left
case 'a':
undo_score=0;
move_left();
sum_left();
move_left();
generate_new_index();
system("clear");
display();
break;
//move right
case 'd':
undo_score=0;
move_right();
sum_right();
move_right();
generate_new_index();
system("clear");
display();
break;
//quit
case 'q':
cout<<"Are you sure you want to quit??\nEnter y to quit and n to continue!\n"<<endl;
cin>>ch;
if(ch=='y' || ch == 'Y'){
end_display();
}
display();
break;
//display instructions
case 'i':
instructions();
break;
//restart 2048
case 'r':
restart();
break;
//undo move
case 'u':
if(undo_flag<5){
for(int m=0;m<4;m++){
for(int n=0;n<4;n++){
g[m][n]=g_copy[m][n];
}
}
score-=undo_score;
undo_flag++;
system("clear");
display();
}else{
system("clear");
display();
cout<<"\n\nYou cannot undo the matrix more than 5 times.\n\nSorry!!!\n"<<endl;
}
}
//check if any block of matrix reached to value = 2048
int find_max=calculate_max();
if(find_max==2048){
win_display();
}
/*
* check_full() checks if grid is full
* game_ends() perform a check if continuous block in up-down or
right-left direction has same values
* if no continuous block has same value, then no further move can be made
and game ends
*/
if(check_full()){
if(game_ends()){
lose_display();
}
}
cout<<"enter choice: "<<endl;
cin>>choice;
while(choice!='w' && choice!='s' && choice!='d' && choice!='a' && choice!='q' && choice!='i' && choice!='u' && choice!='r'){
cout<<"\nYou had entered the wrong choice!\nPlease enter correct choice to continue!"<<endl;
cin>>choice;
}
}
}
/*
* display function
* called after every move
*/
void play :: display(){
cout<<"\n\t\t\t\t\t\t\t 2048\n\n";
cout<<" score :: "<<score<<endl<<endl;
for(int i=0;i<4;i++){
cout<<" ";
for(int j=0;j<4;j++){
cout<<setw(8)<<g[i][j]<<setw(8)<<"|"<<setw(8);
}
cout<<endl<<endl<<endl;
}
cout<<"\n\n\n";
cout<<"\t\t\t\t\t\t\t\t\tr-restart\n\tw\t\t\t\t^\t\t\t\ti-instructions\na\ts\td\t\t<\t"<<"v"<<"\t>\t\t\tq-quit u-undo\n\n";
}
int main(){
play p;
srand(time(NULL));
p.play_game();
return 0;
}
|
463c1f4c7205bf0f76de3062f29c8dc146ebca13
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
pawan231/2048
|
d5e3a64d1918ad8bd28f130c714dc4bcf79fae3d
|
ba29723eca4a311e3c4a21022e63ab0f39667e0c
|
refs/heads/master
|
<file_sep>define(function(require,exports,module) {
var CryptoJS = require('./lib/crypto-js');
console.log(CryptoJS);
exports.test = function(value) {
function strToJson(str){
var json = eval('(' + str + ')');
return json;
}
var data = "message";
var key = CryptoJS.enc.Latin1.parse('2015$!@aiyoutech');
var iv = CryptoJS.enc.Latin1.parse('0123456789abcdef');
var encrypted = CryptoJS.AES.encrypt(data,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.ZeroPadding});
var encrypted= value;
var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,padding:CryptoJS.pad.ZeroPadding});
var result = decrypted.toString(CryptoJS.enc.Utf8);
console.log(result)
return strToJson(result);
}
});<file_sep>// Seajs配置
seajs.config({
base: baseUrl,
paths: {
'common': '/lovedate/common'
},
alias: {
'jquery': 'common/js/lib/jquery.min.js',
'ajax': 'common/js/ajax/ajax',
// 'jssha': '/node_modules/jssha/src/sha.js',
'doT': 'common/js/lib/doT',
'tools': 'common/js/tools',
'globalState': 'common/js/globalState',
'albumBig': 'common/components/album_big',
'select': 'common/components/select',
'select_address': 'common/components/select_address',
'wx': 'common/js/lib/jweixin-1.0.0.js',
'wx_config': 'common/js/wechat/wx_config',
'alert': 'common/components/alert',
'hint': 'common/components/hint',
// 'enum': 'common/json/enum.json'
},
preload: ['jquery']
});
<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-25
*/
define(function(require,exports,module) {
exports.selectPI = function(config) {
var selectContain = {};
selectContain.create = function(callback) {
var bg = document.createElement('div');
bg.className = 'select_bg';
var box = document.createElement('div');
box.className = 'select_box';
box.innerHTML = [
'<div class="select_title_box">',
'<div class="select_cancel"><span>取消</span></div>',
'<div class="select_title"></div>',
'<div class="select_confirm"><span>完成</span></div>',
'</div>',
'<ul class="select_items">',
'</ul>',
'<div class="selected_flag"></div>'
].join('');
document.body.appendChild(bg);
document.body.appendChild(box);
selectContain.setConstant();
selectContain.setVariables();
}
//移除控件
selectContain.remove = function() {
if(selectContain.selectBg.parentNode) {
selectContain.selectBg.parentNode.removeChild(selectContain.selectBg);
selectContain.selectBox.parentNode.removeChild(selectContain.selectBox);
}
}
//设置常量
selectContain.setConstant = function() {
//选择插件dom
selectContain.selectBg = document.getElementsByClassName('select_bg')[0];
selectContain.selectBox = document.getElementsByClassName('select_box')[0];
selectContain.confirmBtn = (document.getElementsByClassName('select_confirm')[0]).children[0];//确认按钮
selectContain.cancelBtn = (document.getElementsByClassName('select_cancel')[0]).children[0];//取消按钮
selectContain.selectItemArr = document.getElementsByClassName('select_item');
selectContain.selectItems = document.getElementsByClassName('select_items')[0];//select_items
selectContain.selectTitle = document.getElementsByClassName('select_title')[0];//标题
selectContain.recievePara = {
title: config.title || '默认标题',
optionArr: config.selectOptions || [],
confirmCallback: config.confirmCallback || function() {
selectContain.remove();
},
cancelCallback: config.cancelCallback || function() {
selectContain.remove();
}
};
}
//设置控制变量
selectContain.setVariables = function() {
selectContain.returnIndex = 0;
selectContain.paraType = 0; //判断参数数组类型 0 string 1 obj
selectContain.isScrollend = true; //判断滚动是否结束
}
//处理选择数据
selectContain.dealSelectOption = function() {
var selectItemDom = '';
var optionArrLoc = selectContain.recievePara.optionArr;
if(typeof optionArrLoc[0] == 'object'){
selectContain.paraType = 1;
} else {
selectContain.paraType = 0;
}
optionArrLoc.push('');
optionArrLoc.push('');
optionArrLoc.push('');
optionArrLoc.unshift('');
optionArrLoc.unshift('');
optionArrLoc.unshift('');
optionArrLoc.forEach(function(value,index) {
var temIndex = index - 3;
if(selectContain.paraType == 1) {
selectItemDom += '<li class="select_item" data-code="'+ value.code + '" data-index=' + temIndex + '>' + (value.value?value.value:"") + '</li>'
} else {
selectItemDom += '<li class="select_item" data-index=' + temIndex + '>' + value + '</li>'
}
})
selectContain.selectItems.innerHTML = selectItemDom;
selectContain.itemHeight = document.getElementsByClassName('select_item')[4].offsetHeight;//一个选项高度
}
selectContain.init = function() {
selectContain.create();
selectContain.selectBg.style.display = 'block';
selectContain.selectBox.style.display = 'block';
selectContain.selectTitle.innerHTML = selectContain.recievePara.title;//显示title
selectContain.dealSelectOption();
selectContain.confirmAndCancelEvent();
selectContain.scrollDeal();
}
//确认和取消事件
selectContain.confirmAndCancelEvent = function() {
var selectItemArr = selectContain.selectItemArr;
selectContain.cancelBtn.addEventListener('click',function(e) {
selectContain.recievePara.cancelCallback();
selectContain.remove();
});
selectContain.confirmBtn.addEventListener('click',function(e) {
if(selectContain.isScrollend) {
console.log(selectContain.returnIndex);
if(selectContain.paraType == 1) {
var selectValue = {
value: selectItemArr[selectContain.returnIndex + 3].innerHTML,
code: selectItemArr[selectContain.returnIndex +3].getAttribute('data-code')
};
} else {
var selectValue = selectItemArr[selectContain.returnIndex + 3].innerHTML;
}
selectContain.recievePara.confirmCallback(selectValue);
selectContain.remove();
}
});
}
selectContain.scrollDeal = function() {
var isTouchEnd = false;
var selectItems = selectContain.selectItems;
var itemHeight = selectContain.itemHeight;
selectItems.addEventListener('touchstart',function(e) {
isTouchEnd = false;
selectContain.isScrollend = false;
// e.preventDefault()
});
selectItems.addEventListener('touchcancel',function(e) {
// selectContain.selectTitle.innerHTML = 'cancel';
isTouchEnd = true;
if(selectContain.isScrollend) {
var scrollMultiple = selectItems.scrollTop/itemHeight;
selectItems.scrollTop = Math.round(scrollMultiple)*itemHeight;
// isTouchEnd = false;
}
});
selectItems.addEventListener('touchend',function(e) {
// alert('touchend' + selectContain.isScrollend)
// selectContain.selectTitle.innerHTML = 'end';
isTouchEnd = true;
if(selectContain.isScrollend) {
var scrollMultiple = selectItems.scrollTop/itemHeight;
selectItems.scrollTop = Math.round(scrollMultiple)*itemHeight;
// isTouchEnd = false;
}
});
function justifyIsScrollStop() {
// 判断此刻到顶部的距离是否和1秒前的距离相等
if(selectItems.scrollTop == topValue) {
clearInterval(interval);
interval = null;
var scrollMultiple = selectItems.scrollTop/itemHeight;
console.log(Math.round(scrollMultiple));
selectContain.returnIndex = Math.round(scrollMultiple);
selectItems.scrollTop = Math.round(scrollMultiple)*itemHeight;
selectContain.isScrollend = true;
}
}
var topValue = 0,// 上次滚动条到顶部的距离
interval = null;// 定时器
selectItems.onscroll = function() {
// console.log(interval + ' ' + isTouchEnd);
if(interval == null && isTouchEnd) {// 未发起时,启动定时器,1秒1执行
interval = setInterval(function(){
selectContain.isScrollend = false;
justifyIsScrollStop()
}, 1000);
isInScroll = true;
} else {
selectContain.isScrollend = true;
}
topValue = selectItems.scrollTop;
}
}
selectContain.init();
}
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-28
*/
define(function(require,exports,module) {
var doT = require('doT');
var ajax = require('ajax');
(function init() {
var profileInfo = JSON.parse(LS.getItem('profileInfo'));
console.log(profileInfo);
if(profileInfo.b159 && profileInfo.b159 == 1) {
$('.wechatinput').val(profileInfo.b157);
$('.switch img').attr({'src':'../../assets/img/switch_on.png','data-status':'1'});
} else {
$('.wechatinput').val(profileInfo.b157);
$('.switch img').attr({'src':'../../assets/img/switch_off.png','data-status':'2'});
}
$('.switch img').click(function(e) {
if($(this).attr('data-status') == 1) {
$(this).attr({'src':'../../assets/img/switch_off.png','data-status':'2'});
} else {
$(this).attr({'src':'../../assets/img/switch_on.png','data-status':'1'});
}
});
$('.qq_confirm').click(function(e) {
profileInfo.b157 = $('.wechatinput').val();
profileInfo.b159 = $('.switch img').attr('data-status');
var postProfileInfo = {};
for(var key in profileInfo) {
var newKey = 'a' + key.substr(1);
postProfileInfo[newKey] = profileInfo[key];
}
updateWechat(postProfileInfo,profileInfo);
});
})();
function updateWechat(postProfileInfo,profileInfo) {
ajax.ajax({
url: '/lp-bus-msc/f_108_11_2.service',
type: 'POST',
data: postProfileInfo,
callback: function(res){
console.log(res);
LS.setItem('profileInfo', JSON.stringify(profileInfo));
history.go(-1);
},
err: function(err) {
console.log(err);
}
})
};
});<file_sep>//计算font-size
!function () {
document.addEventListener('DOMContentLoaded', function () {
var html = document.documentElement;
var windowWidth = html.clientWidth;
html.style.fontSize = windowWidth / 7.5 + 'px';
// 等价于html.style.fontSize = windowWidth / 640 * 100 + 'px';
}, false);
}();
var LS = localStorage;
var debug = true;
var baseUrl = location.origin;
var ageSection = [],
heigthSection = [],
weightSection = [];
for(var i=0; i<=99; i++) {
ageSection.push(i);
}
for(var j=130; j<=220; j++) {
heigthSection.push(j);
}
for(var k=40; k<=120; k++) {
weightSection.push(k);
}
document.onclick = function(e) {
if(e.target.parentNode.className == 'header_back') {
history.back();
}
}
function isTrue(str) {
if(str=='null' || str=='undefined' || str=='false' || str=='' || str==null || str==undefined || str==false) {
return false;
} else {
return true;
}
}<file_sep>define(function(require,exports,module) {
var hint = {
};
hint.create = function(showMsg) {
var hintDom = $('<div class="hint_box"><div>' + showMsg + '</div></div>');
var hintStyle = [
'display:none;',
'position: fixed;',
'top: 0;',
'left: 0;',
'bottom: 0;',
'right: 0;',
'margin: auto;',
'height: .7rem;',
'line-height: .7rem;',
'text-align: center;'
].join('');
var hintDivStyle = [
'color: #ffffff;',
'font-size: .3rem;',
'text-align: center;background: black;',
'width: auto;',
'display: inline-block;',
'padding: 0 .2rem;',
'border-radius: .1rem;'
].join('');
$('body').append(hintDom);
$('.hint_box').attr('style', hintStyle);
$('.hint_box div').attr('style', hintDivStyle);
$('.hint_box').fadeIn('slow',function() {
$('.hint_box').fadeOut(1500,function() {
$(this).remove();
});
});
}
hint.show = function(showMsg) {
hint.create(showMsg);
};
exports.show = hint.show;
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-25
*/
define(function(require,exports,module) {
var ajax = require('ajax');
$('.convert_btn').click(function() {
if(judgePone($('.phone_input').val())) {
$('.convert').hide();
$('.convert_late').show();
}
});
function judgePone(phoneNum) {
if(/^1[3,5,7,8]\d{9}$/g.test(phoneNum)){
return true;
}
else{
return false;
}
}
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-28
*/
define(function(require,exports,module) {
// var wx =require('wx');
// var wx_config =require('wx_config');
var albumBig = require('albumBig');
var doT = require('doT');
var ajax = require('ajax');
var hint = require('hint');
var tools = require('tools');
var albumsArr = [];
function getAlbums() {
ajax.ajax({
url: '/lp-file-msc/f_111_11_1.service',
type: 'post',
loading: true,
// debug: true,
data: {
// a78: '',
// a95: '',
// a110: ''
},
callback: function(res){
console.log(res);
var template = doT.template($('#album_item').html());
$('.album').append(template(res.body));
$.each(res.body,function(i,v) {
albumsArr.push(v.b58);
});
events();
},
err: function(err) {
console.log(err);
}
})
}
getAlbums();
// events();
function events() {
$('.album .img_box .album_img').click(function(e) {
var index = $(this).attr('data-index');
albumBig.showBigPic(albumsArr,index,true, function(indexPara) {
console.log(indexPara);
deleteAlbum(indexPara);
});
});
//添加相册
$('.album .img_box .add_btn').click(function(e) {
// wx.chooseImage({
// count: 9, // 默认9
// sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
// sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
// success: function (res) {
// var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
// }
// });
$('input').trigger('click');
});
//保存相册
$('input').on('change',function() {
takephoto(this, function() {
location.reload();
});
});
}
function deleteAlbum(index) {
console.log(index);
var delId = $('.album .img_box .album_img[data-index=' + index + ']').attr('data-id');
ajax.ajax({
url: '/lp-file-msc/f_111_12_3.service',
type: "POST",
loading: true,
data: {
a34: delId
},
callback:function(data){
console.log(data);
hint.show('照片删除成功');
location.reload();
},
err: function(err) {
console.log(err);
}
})
// $('.album .img_box .album_img[data-index=' + index + ']').closest('.img_box').remove();
}
function takephoto(file, uploadSucCallback){
var reader = new FileReader();
reader.onload = function(evt){
var fd = new FormData(document.getElementById("headuploadForm"));
ajax.ajax({
uploadFormat: true,
url: '/lp-file-msc/f_111_10_2.service',
type: "POST",
data: fd,
loading: true,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
callback:function(data){
hint.show('照片上传成功');
console.log(data);
uploadSucCallback();
},
err: function(err) {
alert('err');
console.log(err);
}
});
};
reader.readAsDataURL(file.files[0]);
};
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-28
*/
define(function(require,exports,module) {
var globalState = LS.globalState ? JSON.parse(LS.globalState) : {
footerIndex : 0
}
exports.footerIndex = globalState.footerIndex;
exports.setFooterIndex = function(value) {
globalState.footerIndex = value;
LS.globalState = JSON.stringify(globalState);
}
exports.personId = globalState.personId;
exports.setPersonId = function(id) {
globalState.personId = id;
LS.globalState = JSON.stringify(globalState);
}
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-04-28
*/
define(function(require,exports,module) {
exports.init = function() {
$('.mesage_person_list').on('click','.person_item', function(e) {
location.href = './message.html'
});
$('.message_none .fill_btn').click(function() {
location.href = './profile/profileinfo.html';
})
}
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-04-28
*/
define(function(require,exports,module) {
//全屏查看图片插件
exports.show = function(title,text,confirmCallback) {
var alert = {};
alert.create = function() {
$('body').append(alert.alertDom);
$('.alert_bg').attr('data-id','2')
$('.alert_bg').attr('style','position: fixed;width: 100%;height: 100%;background: #000;opacity: .5;top: 0;left: 0;')
$('.alert').attr('style','position: absolute;left: 0;top:0;right:0;bottom: 0;width: 5.44rem;height: 3.45rem;margin: auto;text-align: center;background: #ffffff;border-radius: .1rem;font-size: 0;box-sizing:border-box;-moz-box-sizing:border-box; /* Firefox */-webkit-box-sizing:border-box; /* Safari */padding: 0 .36rem;')
$('.alert_img').attr('style','width: 1.2rem;height: 1.2rem;margin-top: -0.6rem;')
$('.alert_title').attr('style','font-size: .32rem;color: #333333;margin-top: .32rem;')
$('.alert_text').attr('style','font-size: .28rem;color: #666666;margin-top: .28rem;')
$('.alert_btn').attr('style','font-size: .32rem;color: #e43f3f;height: .88rem;line-height: .88rem;border-top: 1px solid #efefef;margin-top: .36rem;')
alert.confirmEvent();
}
alert.paras = {
title: title || '温馨提示',
text: text || '绑定成功,你以后可以用手机登录啦!',
confirmCallback: confirmCallback || function(){
alert.remove();
}
}
alert.remove = function() {
$('.alert_bg').remove();
$('.alert').remove();
}
alert.alertDom = [
'<div class="alert_bg"></div>',
'<div class="alert">',
'<img class="alert_img" src="../../assets/img/alert_logo.png">',
'<div class="alert_title">温馨提示</div>',
'<div class="alert_text">绑定成功,你以后可以用手机登录啦!</div>',
'<div class="alert_btn">好哒</div>',
'</div>'
].join('');
alert.confirmEvent = function() {
$('.alert_btn').click(function() {
alert.paras.confirmCallback();
if($('.alert')) {
alert.remove();
}
});
}
alert.init = function() {
alert.create();
}
alert.init();
};
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-04-28
*/
define(function(require,exports,module) {
var doT = require('doT');
var ajax = require('ajax');
var globalState = require('../common/js/globalState');
(function getRecommender() {
ajax.ajax({
url: '/lp-bus-msc/f_108_22_1.service',
type: 'post',
loading: true,
data: {
a69: JSON.parse(LS.getItem('profileInfo')).b69,
// a40: '',
// a38: '',
// a67: '',
// a9: ''
},
callback: function(res) {
console.log(res);
if(res.body) {
var template = doT.template($('#recommender').html());
var recommenderDom = '';
$.each(res.body,function(i,v) {
recommenderDom += template(v);
});
$('.person_lists').html(recommenderDom);
} else {
console.log('跳转');
// location.href = './index.html';
}
},
err: function(err){
console.log(err);
}
})
}) ();
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-25
*/
define(function(require,exports,module) {
// alert(location.href);
var globalState = require('../common/js/globalState');
var ajax = require('ajax');
// LS.clear();
//普通登录
function login() {
ajax.ajax({
url: '/lp-author-msc/f_120_10_1.service',
type: 'post',
login: true,
data: {
// a81: '10122289', //测试账号
// a56: 'iu523151'
a81: '10135488', //aries的账号
a56: 'iu919573'
},
callback: function(res) {
console.log(res);
if(res.code = 200) {
console.log('login success');
LS.setItem('userId', res.body.b80);
LS.setItem('sessionId', res.body.b101);
LS.setItem('sex', res.body.b69);
location.href = './index.html';
}
},
err: function(err) {
console.log(err)
}
});
}
//第三方登录
var loginByWechat = {
};
// LS.setItem('sessionId', '3f94f54b99ae22d5b29504924a16c8b9');
// LS.setItem('userId', '103205601');
// LS.setItem('sex', 0);
// LS.setItem('username', '10132388');
// LS.setItem('password', '<PASSWORD>');
$('.button').click(function() {
globalState.setFooterIndex(0);
location.href = './index.html';
})
//获取code
loginByWechat.getCode = function() {
var code = location.search.split('&')[0].split('=')[1];
loginByWechat.getAccess_tokenAndOpenid(code);
}
//根据code 获取 openid 和 access_token -- 微信接口
loginByWechat.getAccess_tokenAndOpenid = function(code) {
var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxd5f871e36f664d36&secret=5f8d6276fffdf69304f901ded9569a39&code=' + code + '&grant_type=authorization_code';
// alert(url);
ajax.ajax2({
url: url,
type: 'get',
loading: true,
suc: function(res) {
// alert(res.openid);
// alert(res.access_token);
loginByWechat.getProfileInfoByOpenidAndToken(res.openid,res.access_token);
},
err: function(err) {
alert(err);
}
})
}
//根据openid、access_token获取个人 sessionId, userId,性别,头像
loginByWechat.getProfileInfoByOpenidAndToken = function(openid, access_token) {
ajax.ajax({
url: '/lp-author-msc/f_132_15_1.service',
type: 'post',
login: true,
loading: true,
data: {
a162: 1,
a167: openid,
a169: access_token
},
callback: function(res) {
// alert(res.body.b101);
// alert(res.body.b80);
// alert(res.body.b69);
// alert(res.body.b81);
// alert(res.body.b56);
// alert(res.body.b168);
// alert(res.body.b166); //头像
// alert(JSON.stringify(res.body));
LS.setItem('sessionId', res.body.b101);
LS.setItem('userId', res.body.b80);
LS.setItem('sex', res.body.b69);
LS.setItem('username', res.body.b81);
// alert(res.body.b81);
// alert(res.body.b56);
LS.setItem('password', <PASSWORD>);
LS.setItem('headImg', res.body.b166);
loginByWechat.saveProfileInfo();
},
err: function(err) {
alert(err);
console.log(err)
}
});
};
//保存信息
loginByWechat.saveProfileInfo = function() {
ajax.ajax({
url: '/lp-bus-msc/f_108_11_2.service',
type: 'post',
loading: true,
data: {
a69: LS.getItem('sex'),
a57: LS.getItem('headImg')
},
callback: function(res) {
// alert('saveinfo suc');;
location.href = './index.html';
},
err: function(err) {
// alert('save err');
location.href = './index.html';
console.log(err)
}
})
}
loginByWechat.init = function() {
loginByWechat.getCode();
// loginByWechat.getProfileInfoByOpenidAndToken('<PASSWORD>','<PASSWORD>');
}
// login();
loginByWechat.init();
function loginSocket() {
var socket = new WebSocket('ws://192.168.0.121:9066');
socket.onopen = function(event) {
console.log('open: ' + socket.readyState);
var msg = {
"object": {
password: '<PASSWORD>',
userId: 'iu855887',
clientType: 3,
appId: 1999
},
"type": 2001
}
// socket.send(JSON.stringify(msg));
}
socket.onclose = function(event) {
console.log('socket close, statue' + socket.readyState);
}
socket.onmessage= function(data) {
console.log('socket message');
console.log(data);
}
socket.onerror = function(event) {
console.log('We got an error: ' + event.data);
}
}
// loginSocket();
// 获取 jsapi_ticket
// var access_token = "<KEY>"
// ajax.ajax2({
// url: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+ access_token + '&type=jsapi',
// type: 'get',
// success: function(res) {
// console.log(res);
// },
// error: function(err) {
// console.log(err);
// }
// });
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-25
*/
define(function(require,exports,module) {
var doT = require('doT');
var ajax = require('ajax');
var globalState = require('globalState');
var hint = require('hint');
function initBanner(imgList) {
var template = doT.template($('#fate_header_item').html());
var imgListDom = '';
$.each(imgList,function(i,v) {
imgListDom += template({
photo_url:v.b57,
userId: v.b80
});
});
$('.fate_header').html(imgListDom);
}
function initPerson(personList) {
var template = doT.template($('#fate_person_item').html());
var personListDom = [];
$.each(personList, function(i,v) {
personListDom += template({
photoUrl: v.b57,
name: v.b52 || '未知',
age: v.b1 || '未知',
height: v.b33 || '未知',
position: v.b67 || '未知',
isLove: v.b116,
userId: v.b80
})
});
$('.fate_person_list').html(personListDom);
}
(function events() {
$('.fate_header').on('click','li img',function(e) {
var userId = $(this).attr('data-id');
// console.log(userId);
globalState.setPersonId(userId);
location.href = './personhome.html';
});
$('.fate_person_list').on('click','li.person_item .person_box', function() {
var userId = $(this).attr('data-id');
// console.log(userId);
globalState.setPersonId(userId);
location.href = './personhome.html';
}).on('click','li.person_item .love_btn',function(e) { //关注好友
var self = $(this);
var userId = self.closest('.person_item').find('.person_box').attr('data-id');
if(self.find('span').text() == '喜欢') {
var url = '/lp-bus-msc/f_105_10_2.service';
var btnType = 'add';
} else {
var url = '/lp-bus-msc/f_105_12_3.service';
var btnType = 'delete';
}
ajax.ajax({
url: url,
type: 'post',
data: {
a77: userId
},
callback: function(res) {
console.log(res);
if(btnType == 'add') {
hint.show('已喜欢');
self.find('span').text('已喜欢');
} else {
self.find('span').text('喜欢');
hint.show('已取消喜欢');
}
},
err: function(err){
console.log(err);
}
});
});
$('.fate_ad').click(function() {
location.href = './profile/profilevipprovilege.html';
})
})();
exports.init = function() {
ajax.ajax({
url: '/lp-bus-msc/f_111_17_1.service',
type: 'post',
loading: true,
data: {
a69: isTrue(LS.getItem('profileInfo'))?(JSON.parse(LS.getItem('profileInfo'))).b69:'',
a95: 1,
a9: isTrue(LS.getItem('profileInfo'))?(JSON.parse(LS.getItem('profileInfo'))).b9:'',
a67: isTrue(LS.getItem('profileInfo'))?(JSON.parse(LS.getItem('profileInfo'))).b67:'',
a40: isTrue(LS.getItem('lon'))?LS.getItem('lon'):'',
a38: isTrue(LS.getItem('lat'))?LS.getItem('lat'):'',
a117: ''
},
callback: function(res) {
// console.log(res);
initBanner(res.body.b179);
initPerson(res.body.b180);
},
err: function(err){
console.log(err);
}
})
}
});<file_sep>define(function(require,exports,module) {
var wx = require('wx');
var locationUrl = location.href;
if(locationUrl.indexOf('index.html') != -1) {
var checkData = { jsapi_ticket: '<KEY>',
nonceStr: '0sy66jqxhzjmj9k',
timestamp: '1474186439',
url: 'http://aries.vip.natapp.cn/lovedate/view/index.html',
signature: '4409537db08bb54abd206dbab4ff147e859d775c' }
} else if(locationUrl.indexOf('profilealbum.html') != -1) {
var checkData = { jsapi_ticket: '<KEY>',
nonceStr: 'ur63o2hukxogvi',
timestamp: '1470817311',
url: 'http://aries.vip.natapp.cn/lovedate/view/profile/profilealbum.html',
signature: '6d886ccdebcc8af431458a54a1fe8904b864a13e'
};
} else if(locationUrl.indexOf('pay.html') != -1) {
var checkData ={ jsapi_ticket: '<KEY>',
nonceStr: 'pae4dcldlijjdcx',
timestamp: '1471338849',
url: 'http://aries.vip.natapp.cn/lovedate/view/pay.html',
signature: '1a5f782e867ec325f901fbbb97955b5f5b9a7b84' }
}
!(function configWechat() {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: 'wxd5f871e36f664d36', // 必填,公众号的唯一标识
timestamp: checkData.timestamp, // 必填,生成签名的时间戳
nonceStr: checkData.nonceStr, // 必填,生成签名的随机串
signature: checkData.signature,// 必填,签名,见附录1
jsApiList: [
'checkJsApi',
'onMenuShareTimeline',
'onMenuShareAppMessage',
'onMenuShareQQ',
'onMenuShareWeibo',
'hideMenuItems',
'showMenuItems',
'hideAllNonBaseMenuItem',
'showAllNonBaseMenuItem',
'translateVoice',
'startRecord',
'stopRecord',
'onRecordEnd',
'playVoice',
'pauseVoice',
'stopVoice',
'uploadVoice',
'downloadVoice',
'chooseImage',
'previewImage',
'uploadImage',
'downloadImage',
'getNetworkType',
'openLocation',
'getLocation',
'hideOptionMenu',
'showOptionMenu',
'closeWindow',
'scanQRCode',
'chooseWXPay',
'openProductSpecificView',
'addCard',
'chooseCard',
'openCard'
] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
}) ();
exports.ready = function(callBackFuc) {
wx.ready(function(){
callBackFuc();
});
}
exports.chooseImage = function(callBackFuc) {
}
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-04-28
*/
define(function(require,exports,module) {
//全屏查看图片插件
exports.showBigPic = function(data, picIndex, isBigBooeal, deleteCallback) {
// history.pushState(null,null,'detail.html');
var delIndex;
var isNeedBack = false;
var thisUrl = window.location.href;
// console.log(thisUrl);
window.location=thisUrl + '#foo';
isNeedBack = true;
var screenWidth =window.innerWidth;//屏宽
var screenHeight =window.innerHeight;//屏高
var bigPicBgDom = $('<div class="bigPicBg"></div>');
var bgOpacity = isBigBooeal?'1':'0.5';
var bigPicBgDomStyle = [
'width: 100%;',
'height: 100%;',
'background: #000000;',
'position: fixed;',
'z-index: 1;',
'left: 0;',
'top: 0;',
'overflow: hidden;',
'font-size:0;',
'opacity:' + bgOpacity + ';'
];
bigPicBgDom.attr('style', bigPicBgDomStyle.join(''));
var bigPicBoxDom = $('<div class="bigPicBox"></div>'); //最外层盒子
var bigPicBoxDomStyle = [
'width: 100%;',
'height: 100%;',
'position: fixed;',
'z-index: 3333;',
'left: 0;',
'top: 0;',
'overflow: hidden;',
'font-size:0;'
];
bigPicBoxDom.attr('style',bigPicBoxDomStyle.join(''));
var len = data.length;
var bigPicCounter = $('<div class="bigPicCounter">' + (+picIndex+1) + '/' + len + '</div>'); //相册计数
var bigPicCounterStyle = [
'position: absolute;',
'bottom: .4rem;',
'left: .4rem;',
'height: .5rem;',
'line-height: .5rem;',
'width: 1rem;',
'background: #000000;',
'text-align: center;',
'color: #ffffff;',
'opacity: 0.5;',
'z-index:999;',
'font-size: .36rem'
];
bigPicCounter.attr('style', bigPicCounterStyle.join(''));
var bigPicDel = $('<img class="delBtn" src="' + '/lovedate/assets/img/delBtn.png">')
var bigPicDelStyle = [
'z-index:9999;',
'position:absolute;',
'left: .2rem;',
'top: .2rem;',
'width: .48rem;',
'height: .48rem;'
];
bigPicDel.attr('style', bigPicDelStyle.join(''));
var bigPicClose = $('<img class="closeBtn" src="' + '/lovedate/assets/img/closeBtn.png">')
var bigPicCloseStyle = [
'z-index:9999;',
'position:absolute;',
'right: .2rem;',
'top: .2rem;',
'width: .48rem;',
'height: .48rem;'
];
bigPicClose.attr('style', bigPicCloseStyle.join(''));
var bigPicUl = $('<div class="bigPicLists"></div>');//相册加载盒子
var bigPicUlStyle = [
'width:' + len*screenWidth + 'px;',
'margin: 0;',
'padding: 0;',
'position: absolute;',
'left: -' + picIndex*screenWidth + 'px;',
'top: 0;',
'height: 100%;'
];
console.log(screenWidth + '--' + screenHeight);
// alert((screenHeight - screenWidth)/2);
bigPicUl.attr('style', bigPicUlStyle.join(''));
for (var i = 0; i < len; i++) {
var picItemDom = $('<img class="bigPicItem" data-index="' + i + '" src="' + data[i] + '">'); //相册中的每张图片
if(isBigBooeal) {
var picItemDomStyle = [
'float: left;',
'width: ' + screenWidth + 'px;',
'height: 100%;',
];
} else {
var picItemDomStyle = [
'float: left;',
'width: ' + screenWidth + 'px;',
'height: ' + screenWidth + 'px;',
'margin-top: ' + (screenHeight - screenWidth)/2 + 'px'
]
}
// console.log(screenHeight);
picItemDom.attr('style',picItemDomStyle.join(''));
bigPicUl.append(picItemDom);
}
bigPicBoxDom.append(bigPicCounter);
if(isBigBooeal){
bigPicBoxDom.append(bigPicDel);
}
bigPicBoxDom.append(bigPicClose);
bigPicBoxDom.append(bigPicUl)
$('body').append(bigPicBgDom);
$('body').append(bigPicBoxDom);
var events = function() {
var bigPicItemLen = $('.bigPicItem').length;
var startX,endX;
var nowLeft;
$('.bigPicBox').on('touchstart','.bigPicItem', function(e) {
// e.preventDefault();
startX = e.originalEvent.targetTouches[0].pageX;
nowLeft = $(this).closest('.bigPicLists').css('left');
}).on('touchmove','.bigPicItem',function(e){
e.preventDefault();
var durX = e.originalEvent.targetTouches[0].pageX;
var moveX = durX - startX;
$(this).closest('.bigPicLists').css('left', (moveX + parseInt(nowLeft)) + 'px');
}).on('touchend','.bigPicItem',function(e) {
// e.preventDefault();
var index = $(this).attr('data-index');
endX = e.originalEvent.changedTouches[0].pageX;
if( (endX-startX) > 50 && index > 0) {
// $(this).closest('.bigPicLists').css('left', (-index + 1) * screenWidth + 'px');
$(this).closest('.bigPicLists').stop(false).animate({left: (-index + 1) * screenWidth + 'px'}, 300);
$('.bigPicCounter').text(((+index + 1)-1) + '/' + len);
} else if ( (endX - startX) < -50 && index < bigPicItemLen-1) {
// console.log((-index - 1) * screenWidth);
// $(this).closest('.bigPicLists').css('left', (-index - 1) * screenWidth + 'px');
$(this).closest('.bigPicLists').stop(false).animate({left: (-index - 1) * screenWidth + 'px'}, 300);
$('.bigPicCounter').text(((+index + 1)+1) + '/' + len);
} else {
// $(this).closest('.bigPicLists').css('left',(index * screenWidth) + 'px');
$(this).closest('.bigPicLists').stop(false).animate({left: -(index * screenWidth) + 'px'}, 300);
}
}).on('click','.bigPicItem',function(e) {
isNeedBack = false;
e.preventDefault();
$('.bigPicBg').remove();
$(this).closest('.bigPicBox').remove();
history.back();
}).on('click','.closeBtn',function(e) {
isNeedBack = false;
e.preventDefault();
$('.bigPicBg').remove();
$(this).closest('.bigPicBox').remove();
history.back();
}).on('click','.delBtn',function(e) {
var returnIndex = $('.bigPicCounter').text().split('/')[0] - 1;
isNeedBack = false;
e.preventDefault();
$('.bigPicBg').remove();
$(this).closest('.bigPicBox').remove();
if(deleteCallback) {
deleteCallback(returnIndex);
}
history.back();
});
window.onpopstate = function() {
if(isNeedBack) {
// history.back();
$('.bigPicBg').remove();
$('.bigPicBox').remove();
}
};
};
events();
};
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-28
* b69: 1 男 2 女
*/
define(function(require,exports,module) {
var doT = require('doT');
var ajax = require('ajax');
(function init() {
var profileInfo = JSON.parse(LS.getItem('profileInfo'));
console.log(profileInfo);
if(profileInfo.b69 == 1){
$('.boy .check_img').attr('src','../../assets/img/check_yes.png').removeClass('can_click');
$('.girl .check_img').attr('src','../../assets/img/check_no.png').addClass('can_click');
} else {
$('.boy .check_img').attr('src','../../assets/img/check_no.png').addClass('can_click');
$('.girl .check_img').attr('src','../../assets/img/check_yes.png').removeClass('can_click');
}
$('.checkbox').on('click','.can_click',function(e) {
var sex = $(this).attr('data-sex');
console.log(sex);
if(sex == 1) {
$('.boy .check_img').attr('src','../../assets/img/check_yes.png').removeClass('can_click');
$('.girl .check_img').attr('src','../../assets/img/check_no.png').addClass('can_click');
} else {
$('.boy .check_img').attr('src','../../assets/img/check_no.png').addClass('can_click');
$('.girl .check_img').attr('src','../../assets/img/check_yes.png').removeClass('can_click');
}
profileInfo.b69 = sex;
});
$('.sex_confirm').click(function(e) {
var postProfileInfo = {};
for(var key in profileInfo) {
var newKey = 'a' + key.substr(1);
postProfileInfo[newKey] = profileInfo[key];
}
updateSex(postProfileInfo,profileInfo);
});
})();
function updateSex(postProfileInfo,profileInfo) {
ajax.ajax({
url: '/lp-bus-msc/f_108_11_2.service',
type: 'POST',
loading: true,
data: postProfileInfo,
callback: function(res){
console.log(res);
LS.setItem('profileInfo', JSON.stringify(profileInfo));
history.go(-1);
},
err: function(err) {
console.log(err);
}
})
};
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-04-28
*/
define(function(require,exports,module) {
var doT = require('../../common/js/lib/doT');
var ajax = require('../../common/js/ajax/ajax');
var select = require('../../common/components/select');
var select_address = require('../../common/components/select_address');
var tools = require('../../common/js/tools');
var hint = require('hint');
(function init() {
getProfileInfo();
})();
function getProfileInfo() {
ajax.ajax({
url: '/lp-bus-msc/f_108_10_1.service',
type: 'POST',
loading: true,
data: {
// a78: '',
// a95: '',
// a110: ''
},
callback: function(res){
console.log(res);
LS.setItem('profileInfo', JSON.stringify(res.body));
var template = doT.template($('#profile_info').html());
var templateData;
if(res.body) {
templateData = res.body;
templateData.b19 = tools.getEnumNameByCode('educationLevel', templateData.b19);//学历
templateData.b62 = tools.getEnumNameByCode('profession_personal', templateData.b62);//职业
// templateData.b62 = tools.getEnumNameByCode('wage', templateData.b62);//月收入
templateData.b194 = tools.getEnumNameByCode('dating_purpose', templateData.b194);//交友目的
templateData.b195 = tools.getEnumNameByCode('indulged', templateData.b195);//恋爱观
templateData.b196 = tools.getEnumNameByCode('meet_place', templateData.b196);//首次见面希望
templateData.b197 = tools.getEnumNameByCode('love_place', templateData.b197);//爱爱的地点
templateData.b9 = tools.getCityIds(templateData.b67,templateData.b9);//市
templateData.b67 = tools.getProvinceNameById(templateData.b67);//省
}
$('body').append(template(templateData));
events();
},
err: function(err) {
console.log(err);
}
});
};
function events() {
$('.info_item .qq').click(function(e) {
location.href = './profileinfo_qq.html';
});
$('.info_item .wechat').click(function(e) {
location.href = './profileinfo_wechat.html';
});
$('.info_item .nickname').click(function() {
location.href = './profileinfo_nickname.html';
})
$('.info_item .sex').click(function() {
location.href = './profileinfo_sex.html';
});
$('.info_item .motto_value').click(function() {
location.href = './profileinfo_motto.html';
});
$('body').on('click','.info_item .age',function(e) {
var self = this;
select.selectPI({
title: '年龄',
selectOptions: ageSection,
confirmCallback: function(data) {
updateInfo('b1',data);
console.log(data);
$(self).text(data);
}
});
}).on('click','.info_item .height',function(e) {
var self = this;
select.selectPI({
title: '身高',
selectOptions: heigthSection,
confirmCallback: function(data) {
updateInfo('b33',data);
console.log(data);
$(self).text(data);
}
});
}).on('click','.info_item .weight',function(e) {
var self = this;
select.selectPI({
title: '体重',
selectOptions: weightSection,
confirmCallback: function(data) {
updateInfo('b88',data);
// console.log(data);
$(self).text(data);
}
});
}).on('click','.info_item .educationLevel',function(e) {
selectByKey($(this), 'b19', 'educationLevel', '学历');
}).on('click','.info_item .profession_personal',function(e) {
selectByKey($(this), 'b62', 'profession_personal', '职业');
}).on('click','.info_item .dating_purpose',function(e) {
selectByKey($(this), 'b194', 'dating_purpose', '交友目的');
}).on('click','.info_item .love_place',function(e) {
selectByKey($(this), 'b197', 'love_place', '爱爱的地点');
}).on('click','.info_item .meet_place',function(e) {
selectByKey($(this), 'b196', 'meet_place', '首次见面希望');
}).on('click','.info_item .indulged',function(e) {
selectByKey($(this), 'b195', 'indulged', '恋爱观');
}).on('click','.info_item .address',function(e) {
var self = $(this);
var addressEnumArr = require('../../common/json/provence.json');
console.log(addressEnumArr)
select_address.selectPI({
title: '选择地区',
selectOptions: addressEnumArr.body,
confirmCallback: function(data){
updateInfo(['b67','b9'],[data.provinceId,data.cityId]);
self.text(data.provinceName + data.cityName);
}
})
}).on('click','.info_item .wage',function(e) {
var self = $(this);
var wageEnumArr = tools.getEnum('wage');
select.selectPI({
title: '月收入',
selectOptions: wageEnumArr,
confirmCallback: function(data) {
updateInfo(['a87','a86'],[data.value.split('-')[0],data.value.split('-')[1]]);
self.text(data.value);
}
})
});
};
function selectByKey(dom, key, enumName, title) {
var enumArr = tools.getEnum(enumName);
select.selectPI({
title: title,
selectOptions: enumArr,
confirmCallback: function(data) {
// console.log(data);
updateInfo(key ,data.code);
dom.text(data.value);
}
});
}
function updateInfo(key,value) {
var profileInfo = JSON.parse(LS.getItem('profileInfo'));
if(typeof key == 'object') {
for(var i in key) {
profileInfo[key[i]] = value[i]
}
} else {
profileInfo[key] = value;
}
var postProfileInfo = {};
for(var key in profileInfo) {
var newKey = 'a' + key.substr(1);
postProfileInfo[newKey] = profileInfo[key];
}
ajax.ajax({
url: '/lp-bus-msc/f_108_11_2.service',
type: 'POST',
data: postProfileInfo,
callback: function(res){
console.log(res);
hint.show('修改成功');
LS.setItem('profileInfo', JSON.stringify(profileInfo));
},
err: function(err) {
hint.show('修改失败');
console.log(err);
}
})
}
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-07-28
*/
define(function(require,exports,module) {
var doT = require('doT');
var ajax = require('ajax');
(function init() {
var profileInfo = JSON.parse(LS.getItem('profileInfo'));
// console.log(profileInfo);
$('.nicknameinput').val(profileInfo.b52);
$('.nick_confirm').click(function(e) {
profileInfo.b52 = $('.nicknameinput').val();
var postProfileInfo = {};
for(var key in profileInfo) {
var newKey = 'a' + key.substr(1);
postProfileInfo[newKey] = profileInfo[key];
}
updateNickname(postProfileInfo,profileInfo);
});
})();
function updateNickname(postProfileInfo,profileInfo) {
ajax.ajax({
url: '/lp-bus-msc/f_108_11_2.service',
type: 'POST',
loading: true,
data: postProfileInfo,
callback: function(res){
console.log(res);
LS.setItem('profileInfo', JSON.stringify(profileInfo));
history.go(-1);
},
err: function(err) {
console.log(err);
}
})
};
});<file_sep>/*
* @Author: wangxiaochen
* @Date: 2016-04-28
*/
define(function(require,exports,module) {
var doT = require('doT');
var ajax = require('ajax');
var globalState = require('globalState');
function initNearByPerson(personList) {
// console.log(personList);
var template = doT.template($('#nearby_person_item').html());
var personListDom = [];
$.each(personList, function(i,v) {
personListDom += template({
photoUrl: v.b57,
userId: v.b80,
name: v.b52 || '未知',
age: v.b1 || '未知',
height: v.b33 || '未知',
distance: v.b94 || '未知'
})
});
$('.nearby_person_list').html(personListDom);
}
(function event() {
$('.nearby_person_list').on('click','.person_item .head_img', function(e) {
var userId = $(this).closest('.person_item').attr('data-id');
globalState.setPersonId(userId);
location.href = './personhome.html';
});
$('.nearby_greet_btn').click(function(e) {//一键打招呼
console.log('一键打招呼')
});
})();
exports.init = function() {
$('.position').text(LS.getItem('address'));
ajax.ajax({
url: '/lp-bus-msc/f_108_16_1.service',
type: 'post',
loading: true,
data: {
a69: isTrue(LS.getItem('profileInfo'))?(JSON.parse(LS.getItem('profileInfo'))).b69:1,
a95: 1,
a9: isTrue(LS.getItem('profileInfo'))?(JSON.parse(LS.getItem('profileInfo'))).b9:'',
a67: isTrue(LS.getItem('profileInfo'))?(JSON.parse(LS.getItem('profileInfo'))).b67:'',
a40: isTrue(LS.getItem('lon'))?LS.getItem('lon'):'',
a38: isTrue(LS.getItem('lat'))?LS.getItem('lat'):'',
a117: ''
},
callback: function(res) {
console.log(res);
initNearByPerson(res.body);
},
err: function(err){
console.log(err);
}
})
}
});
|
75aa39f9e4397edcc0934a392979fe9fe09b603e
|
[
"JavaScript"
] | 20 |
JavaScript
|
arieswxc/lovedate
|
8cad8dfc8f337a47a04e5e71b32feb9040666f7f
|
487ba198b79f89ef1105979a691265ebe4277d2e
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.